diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 7545f75644..085af67ae0 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -5,15 +5,15 @@ # docker build --target standalone -t acode-dev .devcontainer/ # docker run -it -v $(pwd):/workspaces/acode acode-dev -FROM mcr.microsoft.com/devcontainers/java:1-21-bookworm AS base +FROM mcr.microsoft.com/devcontainers/base:ubuntu-24.04 AS base -ARG ANDROID_PLATFORM=36 +ARG ANDROID_PLATFORM=37 ARG ANDROID_BUILD_TOOLS=36.0.0 ARG CMDLINE_TOOLS_VERSION=11076708 -ARG NODE_VERSION=22 -ARG GRADLE_VERSION=8.11 +ARG NODE_VERSION=24 +ARG JAVA_VERSION=26 -ENV GRADLE_HOME=/opt/gradle +ENV JAVA_HOME=/opt/java/openjdk # removes broken yarn repo present in base image RUN rm -f /etc/apt/sources.list.d/yarn.list @@ -24,13 +24,19 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ curl \ && rm -rf /var/lib/apt/lists/* -# Install Gradle -RUN wget -q "https://services.gradle.org/distributions/gradle-${GRADLE_VERSION}-bin.zip" -O /tmp/gradle.zip \ - && unzip -q /tmp/gradle.zip -d /opt \ - && rm /tmp/gradle.zip \ - && ln -s /opt/gradle-${GRADLE_VERSION} ${GRADLE_HOME} - -ENV PATH="${PATH}:${GRADLE_HOME}/bin" +# The project wrapper supplies Gradle; install only its Java runtime here. +RUN set -eu; \ + case "$(dpkg --print-architecture)" in \ + amd64) architecture=x64 ;; \ + arm64) architecture=aarch64 ;; \ + *) exit 1 ;; \ + esac; \ + curl -fL "https://api.adoptium.net/v3/binary/latest/${JAVA_VERSION}/ga/linux/${architecture}/jdk/hotspot/normal/eclipse" -o /tmp/jdk.tar.gz; \ + mkdir -p "${JAVA_HOME}"; \ + tar -xzf /tmp/jdk.tar.gz --strip-components=1 -C "${JAVA_HOME}"; \ + rm /tmp/jdk.tar.gz + +ENV PATH="${JAVA_HOME}/bin:${PATH}" WORKDIR /workspaces/acode diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 9b60c448ae..be13697a3c 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -6,17 +6,17 @@ }, "containerEnv": { - "JAVA_HOME": "/usr/local/openjdk-21" + "JAVA_HOME": "/opt/java/openjdk" }, "remoteEnv": { - "JAVA_HOME": "/usr/local/openjdk-21", + "JAVA_HOME": "/opt/java/openjdk", "ANDROID_SDK_ROOT": "${containerEnv:ANDROID_HOME}", "PATH": "${containerEnv:PATH}:${containerEnv:ANDROID_HOME}/build-tools/36.0.0" }, "features": { "ghcr.io/nordcominc/devcontainer-features/android-sdk:2": { - "platform": "36", + "platform": "37", "build_tools": "36.0.0" }, "ghcr.io/devcontainers/features/node:2.1": { @@ -28,7 +28,7 @@ } }, "overrideCommand": true, - "postCreateCommand": "pnpm run setup", + "postCreateCommand": "git submodule update --init --recursive && npm ci", "remoteUser": "root", "customizations": { "vscode": { diff --git a/.dockerignore b/.dockerignore index 56e1f21c53..62b3512550 100644 --- a/.dockerignore +++ b/.dockerignore @@ -5,8 +5,6 @@ node_modules/ # Build outputs platforms/ plugins/ -www/css/build/ -www/js/build/ # IDE .vscode/ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index db104d8948..e8a9f06c9a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -61,9 +61,18 @@ jobs: - name: Install dependencies run: npm ci --no-audit --no-fund + - name: Setup Java + uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: '26' + - name: Run unit tests run: npm run test + - name: Check TypeScript + run: npm run typecheck + translation-check: name: Translation Check (On PR Only) timeout-minutes: 5 @@ -97,3 +106,4 @@ jobs: run: | npm ci --no-audit --no-fund npm run lang check + diff --git a/.github/workflows/native-tests.yml b/.github/workflows/native-tests.yml new file mode 100644 index 0000000000..fb339f8b66 --- /dev/null +++ b/.github/workflows/native-tests.yml @@ -0,0 +1,181 @@ +name: Native Tests + +# Native suites are slow (macOS runners, Gradle), so PRs only run the platform +# whose code they touch; the daily run catches breakage coming from src/. +on: + push: + branches: + - main + paths: + - 'platforms/**' + - 'dev/**' + - 'tests/fixtures/ssh/**' + - 'package.json' + - 'package-lock.json' + - '.github/workflows/native-tests.yml' + pull_request: + paths: + - 'platforms/**' + - 'dev/**' + - 'tests/fixtures/ssh/**' + - 'package.json' + - 'package-lock.json' + - '.github/workflows/native-tests.yml' + schedule: + - cron: "0 5 * * *" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + changes: + name: Detect changed platforms + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + pull-requests: read + outputs: + android: ${{ steps.filter.outputs.android }} + ios: ${{ steps.filter.outputs.ios }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + if: github.event_name == 'push' || github.event_name == 'pull_request' + - name: Detect changed files + id: filter + if: github.event_name == 'push' || github.event_name == 'pull_request' + uses: dorny/paths-filter@v4 + with: + filters: | + shared: &shared + - 'dev/config.js' + - 'dev/sync.js' + - 'dev/scripts/native.js' + - 'dev/scripts/build.sh' + - 'package.json' + - 'package-lock.json' + - '.github/workflows/native-tests.yml' + android: + - *shared + - 'platforms/android/**' + - 'dev/storage_manager.mjs' + - 'dev/scripts/android.js' + ios: + - *shared + - 'platforms/ios/**' + - 'dev/ios/**' + - 'dev/scripts/ios.js' + - 'dev/scripts/iosAds.js' + - 'tests/fixtures/ssh/**' + + android: + name: Android (${{ matrix.variant }}, ${{ matrix.distribution }}) + needs: changes + if: needs.changes.outputs.android == 'true' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - variant: paid + package: com.foxdebug.acode + distribution: store + - variant: free + package: com.foxdebug.acodefree + distribution: store + - variant: paid + package: com.foxdebug.acode + distribution: fdroid + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + submodules: recursive + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: '26' + cache: gradle + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: '24' + cache: npm + - name: Install dependencies + run: npm ci --no-audit --no-fund + - name: Install Android SDK packages + run: $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager 'platforms;android-37.0' 'build-tools;36.0.0' + - name: Select package + run: npm pkg set androidPackageId=${{ matrix.package }} + - name: Native unit tests + run: npm run test:android -- ${{ matrix.distribution }} + + ios: + name: iOS + needs: changes + if: needs.changes.outputs.ios == 'true' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + runs-on: macos-15 + timeout-minutes: 30 + env: + DEVELOPER_DIR: /Applications/Xcode_26.3.app/Contents/Developer + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + submodules: recursive + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: '24' + cache: npm + - name: Install dependencies + run: npm ci --no-audit --no-fund + - name: Install Alpine runtime build tools + run: brew install meson ninja llvm lld + - name: Prepare local iOS configuration + run: cp platforms/ios/Config.xcconfig.example platforms/ios/Config.xcconfig + - name: Select iPhone and iPad simulators with working StoreKit and icon testing + id: simulator + run: | + node <<'JS' + const { execFileSync } = require('node:child_process'); + const { appendFileSync } = require('node:fs'); + const { devices } = JSON.parse(execFileSync('xcrun', ['simctl', 'list', 'devices', 'available', '--json'])); + // 26.2 simulators fail alternate icon changes; 26.3–26.5 fails SKTestSession: + // https://developer.apple.com/forums/thread/826971 + const runtime = 'com.apple.CoreSimulator.SimRuntime.iOS-18-6'; + const supported = devices[runtime] || []; + for (const [type, output] of [['iPhone-16-Pro', 'id'], ['iPad-Air-11-inch-M3', 'ipad']]) { + const identifier = `com.apple.CoreSimulator.SimDeviceType.${type}`; + const device = supported.find(device => device.isAvailable && device.deviceTypeIdentifier === identifier); + if (!device) throw new Error(`Missing iOS 18.6 ${type} simulator for integration tests`); + console.log(`Using ${type} on iOS 18.6: ${device.udid}`); + appendFileSync(process.env.GITHUB_OUTPUT, `${output}=${device.udid}\n`); + } + JS + - name: Build and run simulator tests with SSH and FTP fixtures + run: | + python3 -m venv .ios-build/ssh-fixture-venv + .ios-build/ssh-fixture-venv/bin/pip install -r tests/fixtures/ssh/requirements.txt + # Temporarily exclude Alpine process exits on hosted runners (run 41789669396). + # Local runs retain these tests; InAppRunnerTests also starts Alpine. + skips=() + for test in AlpineInteractionTests AlpineLspTests AlpinePackageTests AlpineSignalTests AlpineSimdTests AlpineTerminalServerTests AlpineTerminalTests InAppRunnerTests; do + skips+=("-skip-testing:runnerTests/$test") + done + .ios-build/ssh-fixture-venv/bin/python tests/fixtures/ssh/server.py -- npm run test:ios -- --target=${{ steps.simulator.outputs.id }} "${skips[@]}" + - name: Run iPad startup and native UI checks + run: | + checks=() + for test in AppBridgeTests SystemUITests KeyboardLayoutTests PlatformUITests HapticControlsTests DocumentsPickerTests ShareTests PreviewBrowserTests FilesBrowserTests BrowserBridgeTests; do + checks+=("-only-testing:runnerTests/$test") + done + checks+=("-only-testing:runnerUITests/AppIconUITests") + xcodebuild -project platforms/ios/runner.xcodeproj -scheme runner \ + -configuration Debug -sdk iphonesimulator \ + -destination 'platform=iOS Simulator,id=${{ steps.simulator.outputs.ipad }}' \ + -derivedDataPath .ios-build -clonedSourcePackagesDirPath .ios-build/SourcePackages \ + -parallel-testing-enabled NO -collect-test-diagnostics never \ + "${checks[@]}" CODE_SIGNING_ALLOWED=YES CODE_SIGN_IDENTITY=- test-without-building diff --git a/.github/workflows/nightly-build.yml b/.github/workflows/nightly-build.yml index beb371e43a..2fd7c4dea0 100644 --- a/.github/workflows/nightly-build.yml +++ b/.github/workflows/nightly-build.yml @@ -110,7 +110,7 @@ jobs: uses: actions/setup-java@v6 with: distribution: temurin - java-version: "21" + java-version: "26" cache: ${{ (!(inputs.is_PR && inputs.PR_NUMBER) && github.ref == 'refs/heads/main' && 'gradle') || '' }} - name: Setup Node @@ -136,10 +136,10 @@ jobs: - name: Extract base version id: base run: | - VERSION=$(grep -oP 'version="\K[0-9.]+' config.xml) + VERSION=$(node -p "require('./package.json').version") echo "version=$VERSION" >> "$GITHUB_OUTPUT" - - name: Compose and set build version in config.xml + - name: Compose and set build version in package.json id: version run: | SHORT="$(echo "${{ steps.meta.outputs.git_commit }}" | cut -c1-7)" @@ -149,21 +149,25 @@ jobs: SUFFIX="$SHORT" fi UPDATED="${{ steps.base.outputs.version }}-${{ env.VERSION_LABEL }}.$SUFFIX" - sed -i "s/version=\"${{ steps.base.outputs.version }}\"/version=\"$UPDATED\"/g" config.xml + BUILD_VERSION="$UPDATED" node -e 'const fs = require("node:fs"); const p = require("./package.json"); p.version = process.env.BUILD_VERSION; fs.writeFileSync("package.json", JSON.stringify(p, null, 2) + "\n");' echo "updated_version=$UPDATED" >> "$GITHUB_OUTPUT" echo "NORMAL_APK_PATH=/tmp/acode-debug-normal-$UPDATED.apk" >> "$GITHUB_ENV" echo "FDROID_APK_PATH=/tmp/acode-debug-fdroid-$UPDATED.apk" >> "$GITHUB_ENV" - name: Install deps run: | - npm install - npm install -g cordova - npm run setup + npm ci --no-audit --no-fund + + - name: Install Android SDK packages + run: $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager 'platforms;android-37.0' 'build-tools;36.0.0' + + - name: Select paid package + run: npm pkg set androidPackageId=com.foxdebug.acode - name: Build normal APK run: | - node utils/storage_manager.mjs y - npm run build paid dev apk + node dev/storage_manager.mjs y + npm run build -- dev apk mv platforms/android/app/build/outputs/apk/debug/app-debug.apk ${{ env.NORMAL_APK_PATH }} - name: Upload normal artifact @@ -175,8 +179,8 @@ jobs: - name: Build fdroid APK if: ${{ !inputs.is_PR }} run: | - node utils/storage_manager.mjs y - npm run build paid dev apk fdroid + node dev/storage_manager.mjs y + npm run build -- dev apk fdroid mv platforms/android/app/build/outputs/apk/debug/app-debug.apk ${{ env.FDROID_APK_PATH }} - name: Upload fdroid artifact diff --git a/.github/workflows/nightly-release.yml b/.github/workflows/nightly-release.yml index 33191fbad1..4421aba63c 100644 --- a/.github/workflows/nightly-release.yml +++ b/.github/workflows/nightly-release.yml @@ -16,7 +16,7 @@ concurrency: jobs: build: if: ${{ github.repository_owner == 'Acode-Foundation' }} - uses: Acode-Foundation/acode/.github/workflows/nightly-build.yml@main + uses: ./.github/workflows/nightly-build.yml permissions: contents: read pull-requests: read @@ -152,7 +152,7 @@ jobs: id: notes continue-on-error: true run: | - RELEASE_NOTES="$(node utils/scripts/generate-release-notes.js \ + RELEASE_NOTES="$(node dev/scripts/generate-release-notes.js \ ${{ github.repository_owner }} Acode ${{ github.sha }} \ --format md --from-tag ${{ steps.prev.outputs.tag_commit }} --important-only --quiet --changelog-only || true)" { diff --git a/.github/workflows/on-demand-preview-releases-PR.yml b/.github/workflows/on-demand-preview-releases-PR.yml index 8254116d6a..3dd9c16ae9 100644 --- a/.github/workflows/on-demand-preview-releases-PR.yml +++ b/.github/workflows/on-demand-preview-releases-PR.yml @@ -82,7 +82,7 @@ jobs: secrets: KEYSTORE_CONTENT: ${{ secrets.KEYSTORE_CONTENT }} BUILD_JSON_CONTENT: ${{ secrets.BUILD_JSON_CONTENT }} - uses: Acode-Foundation/acode/.github/workflows/nightly-build.yml@main + uses: ./.github/workflows/nightly-build.yml with: is_PR: true PR_NUMBER: ${{ github.event.pull_request.number }} diff --git a/.gitignore b/.gitignore index 724555f56c..257944173d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,5 @@ node_modules /build.json -/www/build -/plugins -/platforms /keystore.jks /platforms/android/debug-signing.properties /platforms/android/release-signing.properties @@ -21,8 +18,15 @@ local.properties tsconfig.tsbuildinfo .dev-cert.pem .dev-key.pem -/www/cordova.js -/www/cordova_plugins.js .pnpm-store/ pnpm-workspace.yaml pnpm-workspace.yml +platforms/android/**/build/ +platforms/android/.gradle/ +platforms/**/bundle/ + +.ios-build/ +**/Config.xcconfig +platforms/ios/**/*.xcuserstate +platforms/ios/**/xcuserdata/ +/docs/reviews/ diff --git a/.vscode/launch.json b/.vscode/launch.json index 2a6b9c2656..60c7ac797a 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,17 +1,20 @@ { - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", - "name": "Run Android", + "name": "Run Acode Android", "skipFiles": [ "/**" ], - "program": "${workspaceFolder}\\utils\\run-android.js", + "program": "${workspaceFolder}/dev/scripts/android.js", + "args": [ + "run", + "dev", + "apk" + ], + "cwd": "${workspaceFolder}" } ] -} \ No newline at end of file +} diff --git a/.vscode/plugins.json b/.vscode/plugins.json deleted file mode 100644 index 1f29ca1ec7..0000000000 --- a/.vscode/plugins.json +++ /dev/null @@ -1 +0,0 @@ -{"plugins":["cordova-clipboard","cordova-plugin-buildinfo","cordova-plugin-device","cordova-plugin-file","cordova-plugin-sftp","cordova-plugin-server","cordova-plugin-ftp","cordova-plugin-sdcard","cordova-plugin-browser","cordova-plugin-iap","cordova-plugin-system","cordova-plugin-advanced-http"]} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 4a16b5167c..b024bb9153 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -91,7 +91,6 @@ "copyline", "copylinesdown", "copylinesup", - "cordova", "corejs", "cppheader", "crossorigin", @@ -123,6 +122,7 @@ "endregion", "ensime", "ERUDA", + "FDROID", "filebrowser", "filesize", "Fira", diff --git a/.vscode/typings/cordova/cordova.d.ts b/.vscode/typings/cordova/cordova.d.ts deleted file mode 100644 index 594e9b801e..0000000000 --- a/.vscode/typings/cordova/cordova.d.ts +++ /dev/null @@ -1,77 +0,0 @@ -// Type definitions for Apache Cordova -// Project: http://cordova.apache.org -// Definitions by: Microsoft Open Technologies Inc. -// Definitions: https://github.com/borisyankov/DefinitelyTyped -// -// Copyright (c) Microsoft Open Technologies, Inc. -// Licensed under the MIT license. - -interface Cordova { - /** Invokes native functionality by specifying corresponding service name, action and optional parameters. - * @param success A success callback function. - * @param fail An error callback function. - * @param service The service name to call on the native side (corresponds to a native class). - * @param action The action name to call on the native side (generally corresponds to the native class method). - * @param args An array of arguments to pass into the native environment. - */ - exec(success: () => any, fail: () => any, service: string, action: string, args?: string[]): void; - /** Gets the operating system name. */ - platformId: string; - /** Gets Cordova framework version */ - version: string; - /** Defines custom logic as a Cordova module. Other modules can later access it using module name provided. */ - define(moduleName: string, factory: (require: any, exports: any, module: any) => any): void; - /** Access a Cordova module by name. */ - require(moduleName: string): any; - /** Namespace for Cordova plugin functionality */ - plugins:CordovaPlugins; -} - -interface CordovaPlugins {} - -interface Document { - addEventListener(type: "deviceready", listener: (ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "resume", listener: (ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "backbutton", listener: (ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "menubutton", listener: (ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "searchbutton", listener: (ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "startcallbutton", listener: (ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "endcallbutton", listener: (ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "volumedownbutton", listener: (ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "volumeupbutton", listener: (ev: Event) => any, useCapture?: boolean): void; - - removeEventListener(type: "deviceready", listener: (ev: Event) => any, useCapture?: boolean): void; - removeEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; - removeEventListener(type: "resume", listener: (ev: Event) => any, useCapture?: boolean): void; - removeEventListener(type: "backbutton", listener: (ev: Event) => any, useCapture?: boolean): void; - removeEventListener(type: "menubutton", listener: (ev: Event) => any, useCapture?: boolean): void; - removeEventListener(type: "searchbutton", listener: (ev: Event) => any, useCapture?: boolean): void; - removeEventListener(type: "startcallbutton", listener: (ev: Event) => any, useCapture?: boolean): void; - removeEventListener(type: "endcallbutton", listener: (ev: Event) => any, useCapture?: boolean): void; - removeEventListener(type: "volumedownbutton", listener: (ev: Event) => any, useCapture?: boolean): void; - removeEventListener(type: "volumeupbutton", listener: (ev: Event) => any, useCapture?: boolean): void; - - addEventListener(type: string, listener: (ev: Event) => any, useCapture?: boolean): void; - removeEventListener(type: string, listener: (ev: Event) => any, useCapture?: boolean): void; -} - -interface Window { - cordova:Cordova; -} - -// cordova/argscheck module -interface ArgsCheck { - checkArgs(argsSpec: string, functionName: string, args: any[], callee?: any): void; - getValue(value?: any, defaultValue?: any): any; - enableChecks: boolean; -} - -// cordova/urlutil module -interface UrlUtil { - makeAbsolute(url: string): string -} - -/** Apache Cordova instance */ -declare var cordova: Cordova; - diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000000..3e5848854e --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,59 @@ +# Acode — Coding Rules + +## Non-Negotiable + +1. **No redundant code.** If functionality already exists as a component or common function, + reuse it. Never duplicate logic. + +2. **No `_` prefixed variable names.** No `_temp`, `_private`, `_internal`, etc. + Use proper descriptive names. + +3. **Functions at the bottom.** All function definitions go after the main + component/class logic, at file or closure scope. Never interleave function + declarations with execution code. + +4. **Maintainable and readable.** Prefer clarity over cleverness. Split files if they + exceed ~200 lines. Use descriptive, self-documenting names. + +5. **No unnecessary comments.** Comments only when the code itself can't explain *why*. + Never comment *what* the code does — it should be obvious from the names and structure. + +## Import Order + +1. Non-JS imports first (SCSS, CSS, images, fonts) +2. Then library/package imports (React, third-party) +3. Then local imports from `"src"` root +4. Then same-directory relative imports (`./`) + +Concrete example: +```typescript +import "./App.scss"; // 1. non-JS at top +import "res/icons/style.css"; +import { useState } from "react"; // 2. packages +import Page from "components/Page"; +import store from "lib/store"; // 3. src/ root imports +import localHelper from "./utils"; // 4. same-directory +``` + +## Biome Formatter Rules (from `biome.json`) + +Run `pnpm format` before committing. Biome auto-fixes: + +- **Tabs** for indentation (`indentStyle: "tab"`) +- **Double quotes** for strings (`quoteStyle: "double"`) +- **Organize imports** automatically (sorts + removes unused) +- All **recommended** linter rules enabled (except disabled ones below) +- Disabled a11y rules: `noLabelWithoutControl`, `useAnchorContent`, `noStaticElementInteractions`, `useKeyWithClickEvents`, `useMediaCaption` +- Disabled: `noDangerouslySetInnerHtml` (security), `noControlCharactersInRegex` (suspicious) + +## Conventions (match existing codebase) + +- `export default function/class/const` — default exports everywhere +- Imports from `"src"` root — webpack resolves `src/` as a module root +- React components: `export default function ComponentName()` +- Classes: `export default class ClassName` with `#private` fields +- Types: `interface` over `type`, named exports from `src/types/` +- SCSS: one `.scss` per component, co-located +- `const` everywhere, `let` only when reassignment is required +- `async/await` over raw Promises +- `try/catch` with `console.error` for errors diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b037b296e..6a24337a29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Change Log +## Unreleased + +* Ad-free pass redemption is discontinued; previously earned time remains valid until expiry. The `system.redeemReward` wrapper and native action have been removed. Plugins using that action must stop offering redemption. Internal pass-offer helpers and the `isWatchingRewardedAd` export were also removed. + ## v1.13.5 * fix(terminal): stop proot "can't sanitize binding" fd warnings by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2878 @@ -14,7 +18,7 @@ ## v1.13.4 -* fix: prevent Cordova exec startup race by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2851 +* fix: prevent native execution startup race by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2851 * fix(editor): improve selection contrast on active lines by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2852 * fix(editor): treat missing write capability as editable by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2853 * fix: race condition when moving to exact line/col by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2856 @@ -271,7 +275,7 @@ * fix(sidebar): keep sidebar app activation exclusive after plugin install by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1932 * fix(file-browser): resolve nested path creation from parent listings by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1935 * fix(terminal): prevent restoring stale terminal sessions by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1943 -* fix(android): adapt Cordova hooks and resources for cordova-android 15 by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1944 +* fix(android): adapt Android build hooks and resources for runtime version 15 by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1944 * fix(plugin): fix plugin install by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1946 * fix(webview): fix WebView resize handling by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1947 * fix(lsp): honor per-server formatting toggle by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1958 @@ -394,8 +398,8 @@ * chore: update nightly build workflow to use a fine-grained GITHUB_TOKEN for generating nightly release notes by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/1751 * chore: message type detection in release notes script by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/1786 * update(sftp): dependencies for SFTP plugin by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/1792 -* chore(deps): bump tmp and cordova by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/1720 -* chore(deps): bump tough-cookie and cordova by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/1721 +* chore(deps): bump tmp and the Android runtime by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/1720 +* chore(deps): bump tough-cookie and the Android runtime by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/1721 * chore(deps): bump systeminformation from 5.27.11 to 5.27.14 by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/1750 * chore(deps): bump tar from 7.5.2 to 7.5.3 by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/1829 @@ -556,7 +560,7 @@ * feat: Improve handling of intents before files are restored on startup by @bajrangCoder * fix: don't save state of SAFMode="single" files by @bajrangCoder * fix: plugin passing undefined to plugin item on plugin page by @bajrangCoder -* Integrated cordova-plugin-buildinfo as a local plugin by @RohitKushvaha01 +* Integrated native build information as a local plugin by @RohitKushvaha01 * fix: crash when running unsaved file by @RohitKushvaha01 * feat: show open source plugin url on plugin page by @bajrangCoder * fix: Make "None" option clickable in select dialog on formatter settings by @bajrangCoder @@ -676,7 +680,7 @@ * Exposed API for plugin developers to add content in editor tabs via `EditorFile` * Redesigned the About page by @bajrangCoder in #1153 * Added a plugin rebuild option for local plugins by @bajrangCoder in #1150 - * Plugins can use `cordova.plugin.http` instead of `fetch` to avoid CORS issues when making network requests + * Plugins can use the native HTTP API instead of `fetch` to avoid CORS issues when making network requests * Redesigned the Plugin page by @bajrangCoder in #1152 * Added new metadata fields in `plugin.json`: `license`, `changelog`, `keywords`, and `contributors` * Added a new option to open files in an external app from the file browser in #1163 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 485215ac27..81e338b3c0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,7 +21,7 @@ Thank you for your interest in contributing to Acode! This guide will help you g 5. Once ready, build the APK: ```bash - pnpm run build paid dev apk + npm run build -- dev apk ``` > Use any package manager (pnpm, bun, npm, yarn, etc.) @@ -48,10 +48,9 @@ docker run -it --rm \ acode-dev \ bash -# Inside the container, run setup and build -# bun run setup && bun run build paid dev apk -pnpm run setup -pnpm run build paid dev apk # or pnpm run build p d +# Inside the container, install dependencies and build +npm ci +npm run build -- dev apk ``` **Keep container running for repeated use:** @@ -64,8 +63,8 @@ docker run -d --name acode-dev \ sleep infinity # Execute commands in the running container -docker exec -it acode-dev bash -c "pnpm run setup" -docker exec -it acode-dev pnpm run build paid dev apk +docker exec -it acode-dev bash -c "npm ci" +docker exec -it acode-dev npm run build -- dev apk # Stop and remove when done docker stop acode-dev && docker rm acode-dev @@ -81,11 +80,11 @@ If you prefer not to use Docker at all: | Requirement | Version | |------------|---------| -| **Node.js** | 18+ (22 recommended) | -| **pnpm** or **bun** | Latest | -| **Java JDK** | 17+ (21 recommended) | -| **Android SDK** | API 35 | -| **Gradle** | 8.x | +| **Node.js** | 24 LTS | +| **npm** | Included with Node.js | +| **Java JDK** | 26 (any vendor) | +| **Android SDK** | API 37 | +| **Gradle** | 9.8.0-rc-3 (included wrapper) | ### Environment Setup @@ -103,61 +102,321 @@ export ANDROID_HOME="$HOME/Android/Sdk" export PATH="$PATH:$ANDROID_HOME/platform-tools:$ANDROID_HOME/cmdline-tools/latest/bin" ``` -Some more environment variables, check [cordova docs](https://cordova.apache.org/docs/en/latest/guide/platforms/android/index.html). +Set `JAVA_HOME` to any JDK 26 installation and add `$JAVA_HOME/bin` to `PATH`. The checked-in daemon criteria require Java 26 (any vendor), and the Gradle wrapper downloads the required Gradle version automatically. Android Gradle Plugin 9.4.1 supplies built-in Kotlin support. + +The wrapper pins and verifies the Gradle 9.8.0-rc-3 distribution. Java and Kotlin still emit Java 21 bytecode for Android compatibility; the build itself runs on Java 26. ### Build Steps +Web sources follow the Proteus layout: `src/index.html` is the entry HTML and +`src/res/` contains static artwork. Rspack writes the complete web bundle to +`platforms/android/app/src/main/assets/bundle/` or `platforms/ios/runner/bundle/`. +These directories are generated and ignored by Git. The dev server serves the +selected platform's bundle; edit source files in `src/`, not generated files. + ```bash # Clone the repository git clone --recurse-submodules https://github.com/Acode-Foundation/Acode.git cd Acode -# Install dependencies and set up Cordova -pnpm run setup +# Install dependencies +npm ci # Build the APK -pnpm run build paid dev apk # or pnpm run build p d +npm run build -- dev apk ``` -The APK will be at: `platforms/android/app/build/outputs/apk/debug/app-debug.apk` +The APK will be at: `platforms/android/app/build/outputs/apk//debug/app--debug.apk` > [!NOTE] -> `@codemirror/lsp-client` comes from the `codemirror-lsp-client` git submodule and is installed as a local `file:` dependency, so the submodule must be cloned before `setup` runs. If it isn't, `setup` stops with a missing-submodules error — see [Troubleshooting](#-troubleshooting). - -## 🔧 Troubleshooting +> `@codemirror/lsp-client` comes from the `codemirror-lsp-client` git submodule and is installed as a local `file:` dependency, so initialize the submodule before running `npm ci` — see [Troubleshooting](#-troubleshooting). + +## iOS development + +Use macOS with Xcode 26 and an installed iOS simulator runtime, plus Node.js 24. +Copy `platforms/ios/Config.xcconfig.example` to `platforms/ios/Config.xcconfig` +once on a new checkout. This ignored file is only for local signing settings such +as `DEVELOPMENT_TEAM`; leave the team empty for simulator builds. Version, build +number, display name and bundle ID are synced from `package.json` into the Xcode +project by `dev/sync.js`; keep the icon and other public build settings in the +Xcode project. +Keep `runner/PrivacyInfo.xcprivacy` aligned with native API use: it declares file +metadata, app-local preferences and elapsed-time measurements. Both targets +also declare the local capacity checks used by filesystem requests (`E174.1`). +They include this resource automatically through the template's synchronized folder. +Check the built app's root manifest when changing target resource membership. +Use iOS 18.6 or 26.2 for StoreKit integration tests. iOS 26.3–26.5 has a +[StoreKitTest configuration regression](https://developer.apple.com/forums/thread/826971) +in command-line runs; CI selects an unaffected installed runtime. +Android SDK and Java are not needed for an iOS-only build. Install Java to run the +complete shared test suite, which also checks Android build configuration. -### `setup` fails: submodules are not checked out +```bash +npm ci +npm run dev:ios +``` -`@codemirror/lsp-client` is not fetched from a registry. It comes from the -[`codemirror-lsp-client`](https://github.com/Acode-Foundation/codemirror-lsp-client) -git submodule and is installed as a local `file:` dependency. +Like the Proteus template, this prepares the web bundle and opens Xcode. Select +the `runner` scheme, select your connected iPhone, +and press **Cmd+R** to build, sign and install. Signing uses your local +`Config.xcconfig`. `npm start -- ios` also opens Xcode after preparing the bundle. +`--device` is accepted for this flow; `--target` is reserved for scripted simulator +runs. Keep the Mac and iPhone on the same local network and allow Acode's local +network access for live reload. Swift changes require another **Cmd+R** in Xcode. -Before installing dependencies, `pnpm run setup` reads `.gitmodules` and verifies that -every submodule it declares has actually been cloned — a directory only counts as cloned -when it contains at least one non-hidden file. An empty, missing, or partial checkout (for -example one holding only `.git` or `node_modules`) therefore stops setup with: +For a scripted simulator build, install and launch, pass its UUID explicitly: -``` -The following submodule(s) are not checked out (empty or absent): +```bash +xcrun simctl list devices available +npm run build -- ios dev +npm start -- ios --target= +npm run dev:ios -- --target= +npm run test:ios -- --target= ``` -To fix it, initialize the submodules from the repository root and re-run setup: +For the SSH/SFTP and FTP/FTPS integration tests, run the same simulator command inside the +local fixture. It uses disposable keys, TLS certificates and files, binds only to loopback, and +does not execute shell commands on your Mac. The wrapper stops it after testing. +Explicit and implicit FTPS use allocated listener ports; native tests route the +port-990 profile to its listener while retaining TLS hostname verification. +These integration cases are skipped when the fixture is absent; CI includes it. ```bash -git submodule update --init --recursive -pnpm run setup +python3 -m venv .ios-build/ssh-fixture-venv +.ios-build/ssh-fixture-venv/bin/pip install -r tests/fixtures/ssh/requirements.txt +.ios-build/ssh-fixture-venv/bin/python tests/fixtures/ssh/server.py -- npm run test:ios -- --target= ``` -This usually means the repository was cloned without `--recurse-submodules`. Cloning with -submodules avoids the problem entirely: +The iOS SSH transport uses pinned libssh2 and OpenSSL Swift packages. Xcode +resolves them automatically; keep `Package.resolved` in version control. FTP/FTPS +uses vendored curl source and shares that OpenSSL package. Source provenance, +configuration and update instructions are in +[`platforms/ios/Packages/CCurl/README.md`](platforms/ios/Packages/CCurl/README.md). +FTPS validates the server certificate and hostname; port 990 uses implicit TLS +and other ports use explicit TLS, with encrypted data connections. + +`dev:ios` serves the web bundle over HTTP on the Mac's local-network address. +With a simulator `--target`, it binds to loopback and automatically rebuilds +changed Swift sources. Both modes reload JavaScript changes. The app retains its +`acode://localhost` origin. Normal API connections continue to validate TLS. + +The native iOS workspace index uses the system SQLite library and the existing +`fileIndex` API. Simulator tests exercise persistent scans, incremental updates, +search/replace events, cancellation and the Search in Files UI. The index lives +in the app's `Library/NoCloud/workspace-index.sqlite`; it is regenerated from +workspaces and is excluded from backups. Remote providers keep their JavaScript +file discovery and search path. + +Keep iOS keyboard-mode adaptation in `src/platforms/ios/input.ts`; it restores +field defaults for prompts and preserves input/autofill semantics. Native menu +suppression uses `AppWebView` and UIKit's menu builder. Do not remove or replace +private WebKit input views. Fullscreen tests exercise orientation and restoring +the editor/preview size after WebKit moves the WebView between containers. +Filename prompts keep corrections and suggestions disabled on iOS even in normal +keyboard mode; retain ordinary text defaults and explicit capitalization options. +On iPad, multitasking can prevent programmatic rotation. A rejected orientation +request must leave fullscreen usable and clear the temporary orientation policy. +CI reuses each edition's built tests for focused iPad startup, file-picker, sharing, +Safari, preview and native UI checks. An iPad UUID also works with `test:ios` above. + +`PreviewTransferTests` verifies pending-download cancellation, restoring the editor +after closing a preview with an alert, and cache invalidation. Keep asynchronous +navigation and dialog presentation disabled after a preview is closed. For manual +preview smoke tests, serve an attachment link and an HTML file input: cancel once, +download twice, then select the first file from Acode/Downloads and compare its +bytes in the page. `PreviewUploadTests` completes a multi-file multipart upload +through the native picker's public delegate and compares the selected names, file +contents and serialized request bytes. Keep touch selection, interrupted transfers +and external Files providers in manual checks. +`PreviewDownloadTests` verifies that accepted downloads finish after the preview +is closed and released, while broken responses remove partial files. Keep accepted +transfers owned by `PreviewDownloadManager`, separate from preview UI lifetime. +`SSHTransferTests` cancels a throttled download through the public SFTP bridge and +checks reconnection. It also drops server connections during 8 MiB uploads and +downloads, verifies request rejection and disconnected state, and checks that +retries replace partial content. These tests need the loopback fixture above. +`FTPTransferTests` checks disconnecting a throttled download and recovering after +interrupted FTP/FTPS uploads and downloads in active and passive modes. Its +fixture closes disposable connections mid-transfer; keep these checks local. + +iOS has one free app: the `runner` target and scheme use the bundle ID from +`package.json.appleAppId`, while `package.json.androidPackageId` selects the +Android edition. iOS always builds the free web bundle and native advertising +implementation. Version, build number and display name are synced from +`package.json` by `dev/sync.js`. Simulator builds use ad-hoc signing so Keychain +services work without a distribution certificate. + +The target includes `platforms/ios/ads`, Google Mobile Ads/UMP and advertising +metadata. `ads.json` supplies ad-unit IDs through the web build configuration; +`dev/scripts/iosAds.js` separately writes the app ID and advertising metadata into +`.ios-build/App-Info.plist`. Run the normal script before building `runner` in Xcode +to prepare both the plist and web bundle. The adapted AdMob Plus code retains its +MIT notice in `platforms/ios/ads/AdMobPlus-LICENSE.txt`. + +The app gathers UMP consent, then native startup waits for ATT to settle before +starting Mobile Ads; consent is checked again before startup and ad requests. +ATT waits are bounded to 30 seconds. A timeout fails startup without granting +authorization; retry/foreground checks read the OS status, and cancellation never +starts a second prompt while the original OS request is outstanding. +On physical Release builds, a verified StoreKit sandbox/Xcode environment selects +Google demo units. A failed, unverified or timed-out lookup keeps the configured +units; the lookup deadline is three seconds. Verified environments are cached for +the process; failed/unverified lookups retry after a 30-second cooldown, and +concurrent lookups share one request. Debug/simulator selection comes from +the build configuration and SDK test-device behavior. Simulator tests do not +establish TestFlight/App Review environment selection or production ad fill. + +The icon picker uses UIKit alternate icons and the existing reward/Pro gates. +`runner.icon` and the fifteen alternate app-icon sets use Acode's existing +`src/res/icons` artwork, rasterized at 1024 pixels. Keep these checked-in resources +aligned when changing the artwork; no generation hook runs during builds. +The scheme includes a Settings interaction test that changes and restores +the icon, including Apple's confirmation and portrait/landscape rotation on +iPhone and iPad. It uses the local StoreKit Pro fixture to unlock the picker. +Native tests cover packaged icons +and the bridge; shared tests cover reward and purchase gates. + +Calling `Bridge.setup()` again intentionally invalidates callbacks from the old +navigation and resets its services before rebuilding them for the supplied WebView. +Normal page navigation calls `reset()` and reuses the same WebView and services. + +The `System` file utilities retain Android's result shapes, newline semantics and +nonrecursive deletion while restricting paths to the sandbox or granted Files +folders. Reward-pass state uses Keychain. Android file-edit intents and launcher +shortcuts are hidden on iOS; sharing and opening exported copies remain available. +`PluginInstallTests` installs the disposable ZIP in `runnerTests/Fixtures` through +the Plugins source prompt, exercising extraction, script loading, legacy APIs, +plugin context and cleanup. The fixture is test-bundle-only. +`DocumentsPickerTests` checks picker return values, cancellation and reload +cleanup; `ShareTests` checks exported copies and share-sheet cleanup. They drive +the real UIKit controllers through public delegates/completions. Keep native +Files-provider selection and destination sharing in the manual smoke checks. +Include Save to Files, opening the exported copy in Acode, and saving an edit back +to that copy. Existing-file writes must use the file's own grant without resolving +its parent folder; `internalFsWrite.test.js` covers this alongside creation flags +and write failures. Incoming share tabs intentionally do not persist in sessions. +`FilesBrowserTests` opens Documents and reads a selected file through the shared +file-browser UI and filesystem API, including iOS storage capability checks. +Keep iOS root-history restoration before device readiness so saved sessions and +folder-tree paths use the current container. Only recorded roots that remain +authorized may remap an older URL; do not infer ownership from a container UUID. +`FileURLTests` checks encoded native URLs, metadata and binary WebView fetches for +reserved filenames. Use the native `resolveLocalFileSystemURI` alias for encoded +URLs; the app's `resolveLocalFileSystemURL` wrapper encodes raw paths itself. +`FileSymlinkTests` checks that entry paths, deletion and moves preserve symlink +identity and leave targets intact. Keep target authorization on reads even when +entry metadata retains the link's name. +Reuse `FileTransfer` for coordinated copies and moves. Native FileEntry replacement +semantics are covered by `FileTransferTests`; the shared filesystem wrapper keeps +its existing conflict checks. Successful moves notify file presenters using +[`item(at:didMoveTo:)`](https://developer.apple.com/documentation/foundation/nsfilecoordinator/item(at:didmoveto:)). +`FileContentsTests` covers ranged reads, binary-reader chunks, write offsets and +negative truncation. Preserve Android's EOF and error behavior; invalid truncate +lengths must never be converted into a successful zero-length write. +`FileEntryTests` checks filesystem-root boundaries, child paths, creation flags, +invalid names and capacity requests without allocating the requested space. +For upgrade smoke tests, save a file and add it to Recents, reinstall the app +without uninstalling it, then verify editing and Recents after the container moves. + +The native `Iap` service uses StoreKit 2 with the existing callback API. +`IapBridgeTests` loads `runnerTests/Iap.storekit` into StoreKitTest; the fixture +ships only in the test bundle and does not configure normal app launches. +Tests make local simulated purchases without an App Store account or real charges. +The service accepts existing SKU strings unchanged. Configure matching products +for the chosen production bundle before App Store testing. Transactions expose +`store: "appstore"` and a signed JWS in `purchaseToken`/`signedTransactionInfo`; +the backend must verify Apple transactions instead of sending them to Google Play. +The Settings page includes an iOS-only Restore purchases action. Neither billing +restrictions nor a missing App Store product enable the Android external checkout. +Until the backend supports Apple orders and refunds, iOS disables new paid-plugin +and sponsorship purchases. Free and account-owned plugins can still be installed +directly, as dependencies and from backups; unowned paid plugins are skipped during +restore. Keep those gates in `src/lib/platform.js` until the corresponding backend +flows are verified. Local Pro purchase and restoration remain enabled. +The Google Play rating action is hidden on iOS until its App Store listing is +configured. `PlatformUITests` covers Settings/About interaction and copied device +information; keep store links and restoration instructions specific to the platform. + +`npm run build -- ios prod --device` builds an unsigned device app. Use +`platforms/ios/runner.xcodeproj` in Xcode to configure your team, signing and device +installation. Direct Xcode builds use the version defaults in `project.pbxproj`; +the npm scripts supply the version from `package.json`. Tests and build output are under +`.ios-build/`. `--skip-web` reuses an already-built web bundle. + +See [docs/ios-port.md](docs/ios-port.md) before testing feature parity. App Store +products, iOS advertising identifiers, physical-device validation and several +native services are still pending. + +## Native Android development + +`platforms/android` is checked-in source: edit it directly in Android Studio. There is no platform generation or native plugin installation step. + +`FileResourceTest` checks the real WebView request interceptor against local files +whose names contain URI delimiters and percent escapes. Its file IO runs through +the native background pool. Keep decoded filesystem paths as paths when creating +their file URIs; parsing them as URL text loses literal filename characters. + +- `platforms/android/app/src/main/java`: Acode runtime and shared native services. +- `platforms/android/app/src/free`: advertising implementation and metadata. +- `platforms/android/app/src/store`: billing and proot assets, excluded by `fdroid`. +- `src/native`: typed native APIs imported by `src/native/index.ts`; `bridge(service)` binds promise-based actions to the shared transport. +- `src/platforms/android` and `src/platforms/ios`: platform transports using the shared callback and binary protocol. +- `platforms/ios`: iOS app, with the template's runtime in `runner` and native services in `runner/lib`. Simulator tests and native dependencies remain alongside the app. See the [port checklist](docs/ios-port.md) for remaining work. +- `platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServiceRegistry.kt`: native service registration, extended by the `free`/`paid` and `store`/`fdroid` source sets. +- `package.json`: Android package ID (`androidPackageId`), Apple app ID (`appleAppId`), version and version code. + +The native APIs are available through `Bridge.exec`, `Bridge.file`, `Bridge.http`, `Bridge.clipboard` and `Bridge.websocket`. App source uses these APIs or ordinary imports. For existing third-party plugins, `src/native/pluginCompatibility.js` exposes the legacy `cordova` namespace and module names for the public native APIs, forwarding to the same implementations. Existing direct globals and `deviceready`, pause/resume and hardware-button events remain available. Keep compatibility aliases in that file; do not use them inside Acode or add Cordova dependencies. Advertising and billing APIs retain their build-edition restrictions. + +Set `package.json.androidPackageId` before building or starting development: + +| `androidPackageId` | Edition | +| --- | --- | +| `com.foxdebug.acode` | Paid, without AdMob | +| `com.foxdebug.acodefree` | Free, with AdMob | + +The scripts and Android Studio read this value; there is no free/paid command argument. +After changing it, restart `npm run dev`. Only the selected Gradle flavor is enabled. +Use `npm run build` to refresh web assets before building directly in Android Studio, which uses the last compiled web bundle. +`npm run dev` hot-reloads JavaScript through Rspack and rebuilds the app when tracked Android source changes. +Startup probes the dev server with Proteus's three-second timeout and loads its +scripts when reachable, or uses the APK's bundled assets when unavailable. The +page stays at `https://localhost` so API CORS permissions, cookies and local +storage keep the same origin. Lazy-loaded assets use the loaded bundle's URL. +Stop and reopen the app after disconnecting the server to use the bundled build. +Gradle only compiles native source and packages the compiled web assets; no Java/Kotlin source is copied or generated by project scripts. +Paid builds exclude the AdMob native sources, Google ads/consent SDKs, manifest entries, +and JavaScript bridge. The editor uses small inactive ads APIs in paid builds, so +AdMob initialization, consent and rewarded-ad implementation are not bundled either. +Shared billing and proot remain available unless `fdroid` is requested. ```bash -git clone --recurse-submodules https://github.com/Acode-Foundation/Acode.git +npm run build -- dev apk +npm run build -- prod bundle +npm run build -- dev apk fdroid +npm run start -- android d +npm run dev -- android --target=DEVICE_SERIAL +npm test +npm run test:android +npm run typecheck ``` -> [!NOTE] -> The check is skipped when `.gitmodules` is absent (for example an unpacked source -> archive) or declares no submodules, so those setups are unaffected. +Release signing still reads the ignored `build.json` and keystore. Rspack compiles the native JavaScript APIs alongside the editor; there is no separate plugin build, installation, copying or source-generation command. + +The familiar APK/AAB paths remain available under `platforms/android/app/build/outputs/apk/{debug,release}` and `outputs/bundle/release`. + +`node dev/storage_manager.mjs y` or `n` toggles all-files access in the tracked Android manifest for the next build. Build scripts read package identity without rewriting it or reinstalling plugins. + +## 🔧 Troubleshooting + +### Missing local dependency + +`@codemirror/lsp-client` comes from the `codemirror-lsp-client` git submodule. +If dependency installation fails because it is missing, initialize it first: + +```bash +git submodule update --init --recursive +npm ci +``` ## 📝 Contribution Guidelines @@ -167,7 +426,7 @@ git clone --recurse-submodules https://github.com/Acode-Foundation/Acode.git 2. **Make changes** - keep commits focused and atomic 3. **Check code quality:** ```bash - pnpm run check + npm run check ``` 4. **Test** on a device or emulator if possible @@ -181,7 +440,7 @@ git clone --recurse-submodules https://github.com/Acode-Foundation/Acode.git ### Code Style We use [Biome](https://biomejs.dev/) for linting and formatting: -- Run `pnpm run check` before committing +- Run `npm run check` before committing - Install the Biome VS Code extension for auto-formatting ### Performance Changes @@ -210,10 +469,10 @@ refactor: simplify file loading logic 2. Add it to `src/lib/lang.js` 3. Use the translation utilities: ```bash - pnpm run lang add # Add new string - pnpm run lang remove # Remove string - pnpm run lang search # Search strings - pnpm run lang update # Update translations + npm run lang add # Add new string + npm run lang remove # Remove string + npm run lang search # Search strings + npm run lang update # Update translations ``` ## ℹ️ Adding New Icons (to the existing font family) @@ -231,7 +490,7 @@ Many font editing software and web-based tools exist for this purpose. Some of t ### Steps in Icomoon to add new Icons -1. Download the `code-editor-icon.icomoon.json` file from https://github.com/Acode-Foundation/Acode/tree/main/utils +1. Download the `code-editor-icon.icomoon.json` file from https://github.com/Acode-Foundation/Acode/tree/main/dev 2. Go to https://icomoon.io/ > Import 3. Import the `code-editor-icon.icomoon.json` downloaded (in step 1) 4. All icons will be displayed after importing. @@ -247,7 +506,7 @@ Many font editing software and web-based tools exist for this purpose. Some of t 1. Extract the downloaded zip file; navigate to the `fonts` folder inside it. 2. Rename `code-editor-icon.ttf` to `icons.ttf`. 3. Copy & paste the renamed `icons.ttf` into https://github.com/Acode-Foundation/Acode/tree/main/src/res/icons -4. Copy and paste the `code-editor-icon.icomoon.json` file (downloaded in the adding icons steps) onto https://github.com/Acode-Foundation/Acode/tree/main/utils (yes, replace it with the newer one; we downloaded!) +4. Copy and paste the `code-editor-icon.icomoon.json` file (downloaded in the adding icons steps) onto https://github.com/Acode-Foundation/Acode/tree/main/dev (yes, replace it with the newer one; we downloaded!) 4. Commit the changes **ON A NEW branch** (by following: [Commit Messages guide](#commit-messages)) ## 🔌 Plugin Development @@ -255,3 +514,9 @@ Many font editing software and web-based tools exist for this purpose. Some of t To create plugins for Acode: - [Plugin Starter Repository](https://github.com/Acode-Foundation/acode-plugin) - [Plugin Documentation](https://docs.acode.app/) + +### iOS Alpine terminal + +Install `brew install meson ninja llvm lld` on an Apple Silicon Mac before building iOS. The normal scripts and direct Xcode builds compile the vendored runtime automatically. `Config.xcconfig` remains limited to ignored local signing information. See [Alpine runtime documentation](platforms/ios/Alpine/README.md) for source revisions, local adaptations, licensing, filesystem layout, and compatibility limits. + +The `AlpineTerminalTests`, `AlpineInteractionTests`, `AlpinePackageTests`, and `AlpineLspTests` suites exercise the real WebView bridge, installation, filesystem editing, backup/restore, interactive tabs, Node/npm, and the existing JSON language server. Installation and package tests require access to Alpine and npm repositories. Run them on a dedicated simulator because they install packages and restore its terminal filesystem. Keep physical-device performance and background validation separate from simulator results. diff --git a/_typos.toml b/_typos.toml index ca02d14706..9d1b75fabc 100644 --- a/_typos.toml +++ b/_typos.toml @@ -5,11 +5,9 @@ check-filename = true extend-exclude = [ "node_modules", "codemirror-lsp-client", - "www", "*.yaml", ".vscode", "fastlane", - "hooks", "*.gradle", "plugins", "platforms", @@ -60,3 +58,5 @@ sav = "sav" ist = "ist" Hel = "Hel" edn = "edn" +# Apple simulator device identifier +udid = "udid" diff --git a/ads.json b/ads.json new file mode 100644 index 0000000000..63aeb1be66 --- /dev/null +++ b/ads.json @@ -0,0 +1,34 @@ +{ + "android": { + "production": { + "appId": "ca-app-pub-5911839694379275~4255791238", + "banner": "ca-app-pub-5911839694379275/9157899592", + "interstitial": "ca-app-pub-5911839694379275/9570937608", + "rewarded": "ca-app-pub-5911839694379275/1633667633", + "appOpen": "ca-app-pub-5911839694379275/4600740197" + }, + "test": { + "appId": "ca-app-pub-3940256099942544~3347511713", + "banner": "ca-app-pub-3940256099942544/6300978111", + "interstitial": "ca-app-pub-3940256099942544/1033173712", + "rewarded": "ca-app-pub-3940256099942544/5224354917", + "appOpen": "ca-app-pub-3940256099942544/9257395921" + } + }, + "ios": { + "production": { + "appId": "ca-app-pub-5911839694379275~2802776745", + "banner": "ca-app-pub-5911839694379275/7672969208", + "interstitial": "ca-app-pub-5911839694379275/8054492011", + "rewarded": "ca-app-pub-5911839694379275/4550361278", + "appOpen": "ca-app-pub-5911839694379275/4115247005" + }, + "test": { + "appId": "ca-app-pub-3940256099942544~1458002511", + "banner": "ca-app-pub-3940256099942544/2435281174", + "interstitial": "ca-app-pub-3940256099942544/4411468910", + "rewarded": "ca-app-pub-3940256099942544/1712485313", + "appOpen": "ca-app-pub-3940256099942544/5575463023" + } + } +} diff --git a/biome.json b/biome.json index 7f2cae5e99..324b2caa86 100644 --- a/biome.json +++ b/biome.json @@ -41,14 +41,9 @@ "includes": [ "src/**/*.js", "src/**/*.ts", - "utils/**/*.js", + "dev/**/*.js", "src/lang/**/*.json", "tests/**", - "!src/plugins/**/*.js", - "!src/plugins/**/*.ts", - "!www/**/*", - "!plugins/**/*", - "!hooks/**/*", "!fastlane/**/*", "!platforms/**/*" ] diff --git a/build-extras.gradle b/build-extras.gradle deleted file mode 100644 index 4b1e8cf979..0000000000 --- a/build-extras.gradle +++ /dev/null @@ -1,24 +0,0 @@ -android { - packagingOptions { - pickFirst 'META-INF/versions/9/OSGI-INF/MANIFEST.MF' - } - buildTypes { - release { - //might cause ClassNotFoundException errors - //to fix those errors you need to either put @Keep on the class/feild or add a entry in progrud rules file - minifyEnabled true - shrinkResources true - proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' - } - } -} - -configurations { - all { - exclude module: 'commons-logging' - exclude group: 'org.bouncycastle', module: 'bcprov-jdk15on' - exclude group: 'org.bouncycastle', module: 'bcpkix-jdk15on' - exclude group: 'org.bouncycastle', module: 'bcpkix-jdk18on' - exclude group: 'org.bouncycastle', module: 'bcprov-jdk18on' - } -} \ No newline at end of file diff --git a/bun.lock b/bun.lock index 1c8f73deb4..6e85014361 100644 --- a/bun.lock +++ b/bun.lock @@ -3,7 +3,7 @@ "configVersion": 0, "workspaces": { "": { - "name": "com.foxdebug.acode", + "name": "acode-app", "dependencies": { "@acode.app/canvas-view": "^0.0.11", "@codemirror/autocomplete": "^6.20.3", @@ -55,7 +55,6 @@ "acorn": "^8.18.0", "autosize": "^6.0.1", "codemirror": "^6.0.2", - "cordova": "13.0.0", "core-js": "^3.50.0", "dayjs": "^1.11.23", "dompurify": "^3.4.14", @@ -64,7 +63,7 @@ "filesize": "^11.0.22", "html-tag-js": "^2.4.16", "jszip": "^3.10.1", - "katex": "^0.16.47", + "katex": "^0.19.0", "markdown-it": "^14.3.0", "markdown-it-anchor": "^9.2.1", "markdown-it-emoji": "^3.1.0", @@ -77,6 +76,7 @@ "mustache": "^4.2.0", "pele": "^1.10.0", "picomatch": "^4.0.7", + "tough-cookie": "^6.0.2", "url-parse": "^1.5.10", "vanilla-picker": "^2.12.3", "vscode-css-languageservice": "6.3.10", @@ -100,34 +100,11 @@ "@rspack/cli": "^2.2.0", "@rspack/core": "^2.2.0", "@types/ace": "^0.0.52", - "@types/cordova": "^11.0.3", "@types/url-parse": "^1.4.11", "autoprefixer": "^10.5.4", "babel-loader": "^10.1.1", "chokidar": "^4.0.3", - "com.foxdebug.acode.rk.auth": "file:src/plugins/auth", - "com.foxdebug.acode.rk.customtabs": "file:src/plugins/custom-tabs", - "com.foxdebug.acode.rk.exec.proot": "file:src/plugins/proot", - "com.foxdebug.acode.rk.exec.terminal": "file:src/plugins/terminal", - "com.foxdebug.acode.rk.plugin.plugincontext": "file:src/plugins/pluginContext", - "cordova-android": "^15.1.0", - "cordova-clipboard": "^1.3.0", - "cordova-plugin-acode-webview": "file:src/plugins/webview", - "cordova-plugin-advanced-http": "file:src/plugins/cordova-plugin-advanced-http", - "cordova-plugin-browser": "file:src/plugins/browser", - "cordova-plugin-buildinfo": "file:src/plugins/cordova-plugin-buildinfo", - "cordova-plugin-crashhandler": "file:src/plugins/cordova-plugin-crashhandler", - "cordova-plugin-device": "^2.1.0", - "cordova-plugin-file": "^8.1.3", - "cordova-plugin-ftp": "file:src/plugins/ftp", - "cordova-plugin-iap": "file:src/plugins/iap", - "cordova-plugin-sdcard": "file:src/plugins/sdcard", - "cordova-plugin-server": "file:src/plugins/server", - "cordova-plugin-sftp": "file:src/plugins/sftp", - "cordova-plugin-system": "file:src/plugins/system", - "cordova-plugin-websocket": "file:src/plugins/websocket", "css-loader": "^7.1.4", - "elementtree": "^0.1.7", "happy-dom": "^20.11.6", "mini-css-extract-plugin": "^2.10.2", "path-browserify": "^1.0.1", @@ -160,33 +137,33 @@ "tar": "^7.5.22", }, "packages": { - "@acode.app/canvas-view": ["@acode.app/canvas-view@0.0.11", "", { "dependencies": { "@codemirror/language": "^6.13.1", "@codemirror/state": "^6.7.6", "@codemirror/view": "^6.43.14", "@lezer/common": "^1.5.5", "@lezer/highlight": "^1.2.5", "style-mod": "^4.1.2" }, "peerDependencies": { "@codemirror/autocomplete": "^6.0.0" }, "optionalPeers": ["@codemirror/autocomplete"] }, "sha512-ohsVQatQfgn555ksFsLe7+nzLoACLJ93hF8yCDpWUeCMoN26k4idiH1MnZzHm8frl/ZOIyGxXCjL15no0pfKqQ=="], + "@acode.app/canvas-view": ["@acode.app/canvas-view@0.0.11", "", { "dependencies": { "@codemirror/language": "^6.13.1", "@codemirror/state": "^6.7.6", "@codemirror/view": "^6.43.14", "@lezer/common": "^1.5.5", "@lezer/highlight": "^1.2.5", "style-mod": "^4.1.2" }, "peerDependencies": { "@codemirror/autocomplete": "^6.0.0" } }, "sha512-ohsVQatQfgn555ksFsLe7+nzLoACLJ93hF8yCDpWUeCMoN26k4idiH1MnZzHm8frl/ZOIyGxXCjL15no0pfKqQ=="], - "@babel/code-frame": ["@babel/code-frame@8.0.0", "", { "dependencies": { "@babel/helper-validator-identifier": "^8.0.0", "js-tokens": "^10.0.0" } }, "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw=="], + "@babel/code-frame": ["@babel/code-frame@8.0.6", "", { "dependencies": { "@babel/helper-validator-identifier": "^8.0.6", "js-tokens": "^10.0.0" } }, "sha512-uMHhvmDmwFiLuiozaoRYTZHqMFuu3fem/X9JY78lohAuLoh8LSGGC8JqUzo2cVuBsBxkjMZNk56CE7ock8Xxkw=="], - "@babel/compat-data": ["@babel/compat-data@8.0.0", "", {}, "sha512-DOjnob/cXOUgDOozCDeq/aK2p5y8dUIVdf6tNhEV1HQRd6I8aQ4f4fbtHRVEvb6lP3BGomrKHiS8ICAASSVQSw=="], + "@babel/compat-data": ["@babel/compat-data@8.0.5", "", {}, "sha512-YLsYoQMvL8l8WrGpN3Zj7O1wK5LEBN+cQtux7BcuHyxIXve724XG+zuJ1n3U1cUweRtTzQOA4IHbuQw3N34SZw=="], - "@babel/core": ["@babel/core@8.0.1", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-compilation-targets": "^8.0.0", "@babel/helpers": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/template": "^8.0.0", "@babel/traverse": "^8.0.0", "@babel/types": "^8.0.0", "@types/gensync": "^1.0.5", "convert-source-map": "^2.0.0", "empathic": "^2.0.1", "gensync": "^1.0.0-beta.2", "import-meta-resolve": "^4.2.0", "json5": "^2.2.3", "obug": "^2.1.1", "semver": "^7.7.3" } }, "sha512-5FgxM4dLQpMJHSiVATk8foW263dVHQHBVpXYiimNECVWG01f4nFyEbQixeT6Mwvg7TayREJ2gpKl3o2RoMdnqw=="], + "@babel/core": ["@babel/core@8.0.6", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/generator": "^8.0.6", "@babel/helper-compilation-targets": "^8.0.6", "@babel/helpers": "^8.0.5", "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", "@babel/traverse": "^8.0.6", "@babel/types": "^8.0.6", "@types/gensync": "^1.0.5", "convert-source-map": "^2.0.0", "empathic": "^2.0.1", "gensync": "^1.0.0-beta.2", "import-meta-resolve": "^4.2.0", "json5": "^2.2.3", "obug": "^2.1.1", "verkit": "^0.3.2" } }, "sha512-5zwYt1V4ji3mXKKRIAkohSJ29WepxNwxQi+7y7P5AcVPh1dcxnZBU2cfxHnPwS+u9+lZnXPsv30TQaF2xg+Tfg=="], "@babel/generator": ["@babel/generator@7.29.8", "", { "dependencies": { "@babel/parser": "^7.29.8", "@babel/types": "^7.29.8", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg=="], "@babel/helper-annotate-as-pure": ["@babel/helper-annotate-as-pure@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" } }, "sha512-NSpMkMsvvZqzThJ0p1B02cbtA2ObEyfBvq950bmNkyxsxvcxwhvvCB036rKhlEnuBBo30bOrk13u3FzlKSoRrw=="], - "@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@8.0.0", "", { "dependencies": { "@babel/compat-data": "^8.0.0", "@babel/helper-validator-option": "^8.0.0", "browserslist": "^4.24.0", "lru-cache": "^11.0.0", "semver": "^7.7.3" } }, "sha512-JwculLABZvyPvyLBpwU/E/IbH2uM3mnxNtIJpxnIfb24y1PrdVxK5Dqjle4DpgqpGRnwgC7G8IkzPdSXZrO1Ew=="], + "@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@8.0.6", "", { "dependencies": { "@babel/compat-data": "^8.0.5", "@babel/helper-validator-option": "^8.0.0", "browserslist": "^4.24.0", "flru": "1.0.2", "verkit": "^0.3.2" } }, "sha512-HTrtZ4+iA0+kzdbCgvdSk1U4pEl3BvpGnlUbualCGNbrVhhQvhgBzurTUmqpWyvyHbWYWaIfdx2mOlL9LJjsew=="], - "@babel/helper-create-class-features-plugin": ["@babel/helper-create-class-features-plugin@8.0.1", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^8.0.0", "@babel/helper-member-expression-to-functions": "^8.0.0", "@babel/helper-optimise-call-expression": "^8.0.0", "@babel/helper-replace-supers": "^8.0.1", "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0", "@babel/traverse": "^8.0.0", "semver": "^7.7.3" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-++t3ZktzlLmASAxIlxeXQK9Z2YwUafYGYcvGBFevqOqt16HozVHStUoQvWD09fzAZOb/uJGpUTBuGK41AJAuOA=="], + "@babel/helper-create-class-features-plugin": ["@babel/helper-create-class-features-plugin@8.0.6", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^8.0.0", "@babel/helper-member-expression-to-functions": "^8.0.5", "@babel/helper-optimise-call-expression": "^8.0.0", "@babel/helper-replace-supers": "^8.0.1", "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0", "@babel/traverse": "^8.0.6", "verkit": "^0.3.2" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-Hy7wG2Pk1LnAkFMq0CbBk789XMTYVzYGxR7tKgk+TOpZckQRME3Tdou4mMT/8DFjJFxFZ8R6UsS4DR/duBKlVA=="], - "@babel/helper-create-regexp-features-plugin": ["@babel/helper-create-regexp-features-plugin@8.0.1", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^8.0.0", "regexpu-core": "^6.3.1", "semver": "^7.7.3" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-PydTbcVTiIfVweHMeY1u3MslaD/ZzvnaTNhJp+7ghofelLWshF66Ckc/ZsjStfvRQIKQ4uVG0yEJucyDtyrWgw=="], + "@babel/helper-create-regexp-features-plugin": ["@babel/helper-create-regexp-features-plugin@8.0.5", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^8.0.0", "regexpu-core": "^6.3.1", "verkit": "^0.3.2" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-TWnIgw21pAv/FbBKB8ks26DMxQ+A3aBdi1HUBp+QhqSE8QdOqJgSK/FEvdMYPTZcHBBJPZ5pN6DDKmC5ZYPJbg=="], "@babel/helper-define-polyfill-provider": ["@babel/helper-define-polyfill-provider@1.0.0", "", { "dependencies": { "@babel/helper-compilation-targets": "^8.0.0", "@babel/helper-plugin-utils": "^8.0.0", "lodash.debounce": "^4.0.8" }, "peerDependencies": { "@babel/core": "^7.4.0 || ^8.0.0" } }, "sha512-9jzVaTeZyXRDKTgUnNzcPQMO8y0ga3o+Z4fKjNet9Fcx7slgKa83qRbz0EwROSd6qO6CoEe/HQszqSPKb5lhkw=="], "@babel/helper-globals": ["@babel/helper-globals@7.29.7", "", {}, "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA=="], - "@babel/helper-member-expression-to-functions": ["@babel/helper-member-expression-to-functions@8.0.0", "", { "dependencies": { "@babel/traverse": "^8.0.0", "@babel/types": "^8.0.0" } }, "sha512-xkXrMbtk87Gk7+oKBVmBc6EORg/Qwx++AHESldmHkpvG8wgccdhJJFwrzqlF382Fk8wfXhJHWE/g/43QvEGNPQ=="], + "@babel/helper-member-expression-to-functions": ["@babel/helper-member-expression-to-functions@8.0.5", "", { "dependencies": { "@babel/traverse": "^8.0.5", "@babel/types": "^8.0.5" } }, "sha512-GLe05QD98BkNFTkjaqeqF9QSRoHLKrrB4tpoplyQuuPrQJ72rtmkM4wvqJLX/sjZPqkbK5MUYSsuUTqdJoOVjA=="], "@babel/helper-module-imports": ["@babel/helper-module-imports@8.0.0", "", { "dependencies": { "@babel/traverse": "^8.0.0", "@babel/types": "^8.0.0" } }, "sha512-NZ7mSS93o4ndX4KrbD7W8Sf3QT8Qe24PrnFyUcuOPDzK6faqDFKjY9RG7he7+I7FdiQ4llpnosFqzrXa+Vy3Ew=="], - "@babel/helper-module-transforms": ["@babel/helper-module-transforms@8.0.1", "", { "dependencies": { "@babel/helper-module-imports": "^8.0.0", "@babel/helper-validator-identifier": "^8.0.0", "@babel/traverse": "^8.0.0" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-UgAhl1kqiW5ciE0yCXqqvnb4H2n3IELJ7lIIQRezwDPilPEZX5i+Rvbja9MFTkwUn2biEiSMeV31aUzR4Lwakw=="], + "@babel/helper-module-transforms": ["@babel/helper-module-transforms@8.0.6", "", { "dependencies": { "@babel/helper-module-imports": "^8.0.0", "@babel/helper-validator-identifier": "^8.0.6", "@babel/traverse": "^8.0.6" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-YUi+3X0cb0v97xKhuqkLdrwQtP6XXv1eVbhLRCFyMwG481UskbMQk4mjH7K/Jg3oJ1KLskvFwwq4kF/QnABkWQ=="], "@babel/helper-optimise-call-expression": ["@babel/helper-optimise-call-expression@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" } }, "sha512-3W6satvtPuCUkUx63S2jMoW9EQNYkADgs1HTfufmL7gCmAulHMKupA/12WNz4A0GMMFn/YnWWwqOT9IZrJHQjg=="], @@ -198,17 +175,17 @@ "@babel/helper-skip-transparent-expression-wrappers": ["@babel/helper-skip-transparent-expression-wrappers@8.0.0", "", { "dependencies": { "@babel/traverse": "^8.0.0", "@babel/types": "^8.0.0" } }, "sha512-xmCA9kP3IhySsqhzwIdWGlDN/1A4cCKNBO/uwZx/3YzmDoMePwno2Q5/Bq0q+tYaKbeF940YiKV/kaW8Mzvpjw=="], - "@babel/helper-string-parser": ["@babel/helper-string-parser@8.0.0", "", {}, "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg=="], + "@babel/helper-string-parser": ["@babel/helper-string-parser@8.0.6", "", {}, "sha512-+6HYEBnsDRZHJtUTAEfMQd0zMDqdFHS7C+5vAsEZqBUr3vEMWOWlHJ0Jz1gS8jJIlCvLsuA6ivmeoqzH936YcA=="], - "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.0", "", {}, "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g=="], + "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.6", "", {}, "sha512-HYx0YmuchRxRSpnjvcNffnPS8DCauKNmnumIuHG3jnQAVewRA7kfJGwF13ayEpSZs7s4R/oBH4eppuXcAQd5JQ=="], "@babel/helper-validator-option": ["@babel/helper-validator-option@8.0.0", "", {}, "sha512-U4Dybxh4WESWHt5XhBeExi4DrY0/DNK1aHpQbsrQXCUbFHuMweT0TpLEWKvaraV2Y6fS+ZXunsZ8zIuZIgvF2Q=="], "@babel/helper-wrap-function": ["@babel/helper-wrap-function@8.0.0", "", { "dependencies": { "@babel/template": "^8.0.0", "@babel/traverse": "^8.0.0", "@babel/types": "^8.0.0" } }, "sha512-Qpm8+wi5xfDkBfollanwriCcKniFfBmMmaKB01GVM6VGzKXo1fdxosZp04qEr5HM+LKhwr3hG1yRy8+ORsficA=="], - "@babel/helpers": ["@babel/helpers@8.0.0", "", { "dependencies": { "@babel/template": "^8.0.0", "@babel/types": "^8.0.0" } }, "sha512-wfbi91pM3py96oIiJEz7qIpyXDytgr9zQC1HEWwlGNVRAEmItuU/0a41ZUKu1sJGyhhOIpc4t5vk4PYzt8wpsg=="], + "@babel/helpers": ["@babel/helpers@8.0.5", "", { "dependencies": { "@babel/template": "^8.0.0", "@babel/types": "^8.0.5" } }, "sha512-fQtPOXjYOYv85PIdwotp2TJGVYOycX0PQq+l844fFAxOULtBy8BVF35GyeueX0r4KvDthqPH5xAI1clQPk/2uA=="], - "@babel/parser": ["@babel/parser@7.29.8", "", { "dependencies": { "@babel/types": "^7.29.8" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA=="], + "@babel/parser": ["@babel/parser@7.29.9", "", { "dependencies": { "@babel/types": "^7.29.8" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA=="], "@babel/plugin-bugfix-firefox-class-in-computed-class-key": ["@babel/plugin-bugfix-firefox-class-in-computed-class-key@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-Ytgjjne4RnG3Oig7ik+NfY4ebRY30BPptVkkyu1f72eINJXRM3/bkU++tIc5aPvyLmo4KH20avq0xJ2o+9aEnw=="], @@ -216,33 +193,33 @@ "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": ["@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-DJviKTxYfH0hFwnMiW4dnPyMGzS3Hrr4zUfXl1zwQ0QiGlGlNYklLoPSYEQr8S7nau0/K7NdQjTh0qbYuyFjCA=="], - "@babel/plugin-bugfix-safari-rest-destructuring-rhs-array": ["@babel/plugin-bugfix-safari-rest-destructuring-rhs-array@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-DmR/N+B9+4PbURFj4+zdnWj49/PFAnK2bn8+E4ZAmwn3J5QCxnbG7Ep6aRfz9M8Aw+rBro0kIJQycvzFpl4buQ=="], + "@babel/plugin-bugfix-safari-rest-destructuring-rhs-array": ["@babel/plugin-bugfix-safari-rest-destructuring-rhs-array@8.0.6", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-vk9CzgaQGcTTBL8F0YNr7LBEka6pXP/I5KcMj0oicGXUquWSNqxiijHGQkHF+s8m910NbGMpn5mU2sFV7AQjBA=="], "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": ["@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0", "@babel/plugin-transform-optional-chaining": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-x8bi0LFVD2xkULjfNn+hCMg16yAFHAM9fS/ThSFeYBi+0MP9K6qcY2BZb4urUwC7PYtEy5wPe6TKjOEjXrCGFA=="], "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": ["@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-P8+RN2n7ts2s1vnE+lXdHYf+dhnmcGSen/kWzBsVluT9Sey5AqmcRXYWlHqgQxaNlKTD5YMa1tf5z4d1v8W88w=="], - "@babel/plugin-syntax-typescript": ["@babel/plugin-syntax-typescript@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-YBpIeuOZSUZx7RGH/U+dIAsHDHyojBVDRHNBUgOiUDS5IIcgBm1uyu9xs/2kM27B/bmDfOxzJ9k8cU2QuOwGIA=="], + "@babel/plugin-syntax-typescript": ["@babel/plugin-syntax-typescript@8.0.3", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-jmTPwps7oSQSZaV1SxkQ3C12UWyufGysGc5OzDpZzvPAIX4mO7dJT3hoqkWVrSImvkcMiknir1iLN1SNV/CZzg=="], "@babel/plugin-transform-arrow-functions": ["@babel/plugin-transform-arrow-functions@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-o/gr7kRlq3PKLLuYth4udOsrC7geBerti+QtwPeyxMOsEQO1d8kDHqk9r2PtMx2y9i8FG7tzyTerfv1yMLSMsQ=="], - "@babel/plugin-transform-async-generator-functions": ["@babel/plugin-transform-async-generator-functions@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-remap-async-to-generator": "^8.0.1", "@babel/traverse": "^8.0.0" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-kqnSMF1YHBzuiQrl68675i5Ma1oljvo+SJsNEZFZVBu5BUrVIZm9KId3ui2PdtLK2sv2zM8sJnjPDfgLxQlEqQ=="], + "@babel/plugin-transform-async-generator-functions": ["@babel/plugin-transform-async-generator-functions@8.0.6", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-remap-async-to-generator": "^8.0.1", "@babel/traverse": "^8.0.6" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-4K13qZ2TVi9W/NHMg3y0Fguu63cPjGNZT5TpPctIUDdiuIpxo4jwvySGrPWlD6KD00exvpx6Y6l5foFEpnzDcg=="], "@babel/plugin-transform-async-to-generator": ["@babel/plugin-transform-async-to-generator@8.0.1", "", { "dependencies": { "@babel/helper-module-imports": "^8.0.0", "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-remap-async-to-generator": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-e1jmmEU4p2Lx64sA1+EF8e8/RxPuegzbXcEbmFp5alDyLE+f2ViUpZ77bRWMXzihTwgVVmn/TOpqDbAuS5g1Ew=="], "@babel/plugin-transform-block-scoped-functions": ["@babel/plugin-transform-block-scoped-functions@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-0V97/gcf7LIgPieEiK1YT0eXa18XJFSLOTZjzEZhA9SJIqZhD/IwGUrCitBzXSmnGCP7hchwC6svHtJ/Eidcpg=="], - "@babel/plugin-transform-block-scoping": ["@babel/plugin-transform-block-scoping@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-HxiQvKsSCs2jOmMhjDrooHaZYOy6W8bqwXp/zjdgPjsNrda6tK9/CH3a/cVIeg6ge3hSS02ALqvqgIo4rTsuSg=="], + "@babel/plugin-transform-block-scoping": ["@babel/plugin-transform-block-scoping@8.0.5", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-czkN3g76Ns2wMe1C0IuceKUCqCe/yJ1by0qz4h4znq74K/Ks7K2Fx6Dplq9ecS65Z3rJHxT9a/kDSF2LbEov8w=="], "@babel/plugin-transform-class-properties": ["@babel/plugin-transform-class-properties@8.0.1", "", { "dependencies": { "@babel/helper-create-class-features-plugin": "^8.0.1", "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-tORnYiVhIHnKj90TgbSZXrO24f9oEpA6MgFxpIDSKKlHv7AzBIRhkMlYevanueLNYaQXqZWarfCgXM4bWTfNiw=="], - "@babel/plugin-transform-class-static-block": ["@babel/plugin-transform-class-static-block@8.0.1", "", { "dependencies": { "@babel/helper-create-class-features-plugin": "^8.0.1", "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-NEVK+L0Le8h8tJ+IK0CGS5y9Yi1ZHxLj6M5PeanhMFuq9aSo0XI+Wtmbuyop6fTNukOm7ORNntf/kwid891vqQ=="], + "@babel/plugin-transform-class-static-block": ["@babel/plugin-transform-class-static-block@8.0.5", "", { "dependencies": { "@babel/helper-create-class-features-plugin": "^8.0.5", "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-hyqluKOSy6PVOoHDEb4xsjFbtOSy+FFNzHNCrAHS5T+LxS8BtZHBCIVYFAcWzhBf/wRYsYu2uEpUvRmHYeOf8A=="], - "@babel/plugin-transform-classes": ["@babel/plugin-transform-classes@8.0.1", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^8.0.0", "@babel/helper-compilation-targets": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-replace-supers": "^8.0.1", "@babel/traverse": "^8.0.0" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-phwyCES8kIMAdVOFw25ztmgAvkl2G+TvUv7azUYyrlR1Qoo3eLJC/MU3MGUKFZ4BWtsJ1NTJM1lKRLzKbswg7w=="], + "@babel/plugin-transform-classes": ["@babel/plugin-transform-classes@8.0.5", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^8.0.0", "@babel/helper-compilation-targets": "^8.0.5", "@babel/helper-globals": "^8.0.0", "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-replace-supers": "^8.0.1", "@babel/traverse": "^8.0.5" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-GKFgovQQzZfEDFxclYFDOiw/Pszxa1epcs7RasL7yyeqi6rxL61Vbqt0uSDPc2M7XXCmNZnQZaK19333v6rabA=="], "@babel/plugin-transform-computed-properties": ["@babel/plugin-transform-computed-properties@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-i4l3OGLO8DUDcwdnyraOvILbhqdUf4QgfzhVxSOSzRy49XKXrY7pwaSg9gDSKmhZfNPrEMciBSJSciQh/CjB1A=="], - "@babel/plugin-transform-destructuring": ["@babel/plugin-transform-destructuring@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-RtR8uLDl0QcCmqMNIkM8gmDeYZ3rS0ZH+sa+I6sfc09yFoqfp9AEPgBstq9KyfVb0lFCVSRFfJXCI70FIl5ccw=="], + "@babel/plugin-transform-destructuring": ["@babel/plugin-transform-destructuring@8.0.5", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-evjxc5fGvpXG2WMGSalpX8IJZVumLIDgk5r5eRhvXRDqFX/GPWq1BeRfJalPCcwJfrR5A/wvegUhx9W5Nr7/mg=="], "@babel/plugin-transform-dotall-regex": ["@babel/plugin-transform-dotall-regex@8.0.1", "", { "dependencies": { "@babel/helper-create-regexp-features-plugin": "^8.0.1", "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-czOUoSaZljJ92yu+bYlXqb/UBN8K9daNCob/B6/7nthSvfGP6YhCnfqD64XWfyb2dN4ypxALNplApoJrsMd4fw=="], @@ -252,7 +229,7 @@ "@babel/plugin-transform-dynamic-import": ["@babel/plugin-transform-dynamic-import@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-AS9GlgKc43tJNRu7yOvLaTko4qmdOb+8M69uNS8i421WLO20eVez7LdG5khKdi8E0LIQpYzzzdGIrdXWnO753g=="], - "@babel/plugin-transform-explicit-resource-management": ["@babel/plugin-transform-explicit-resource-management@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1", "@babel/plugin-transform-destructuring": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-VzDIYwBlLCpV6mJfloRdJm8HmYnMqs7O+bGha8yfg2kP7jAdxeCw6yZBVBeaKKQUThtSU52iy+3lB7DhYsbOBA=="], + "@babel/plugin-transform-explicit-resource-management": ["@babel/plugin-transform-explicit-resource-management@8.0.5", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1", "@babel/plugin-transform-destructuring": "^8.0.5" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-Vr20jk/ZxRGu30o0jYvcKl2Pf0tiyr8H9q2ZGxYD6yjOpv9DdP6//I85q0cSOdADZhsu/ZZoApjGVCfl4xnVJw=="], "@babel/plugin-transform-exponentiation-operator": ["@babel/plugin-transform-exponentiation-operator@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-DsZvUUklUmDQ7d2vp+VjqgUWD51mGxhZZ1FPdPP9Hcj0vsgGUKX+zEBGp/vzB1O5PZUxWT/Euq5fu39M9dm9wg=="], @@ -292,27 +269,27 @@ "@babel/plugin-transform-optional-catch-binding": ["@babel/plugin-transform-optional-catch-binding@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-b2OQ74uGliyATcasTjxGy2O/86UI/n+EN4juB4EMfEwTi9j9uq70PuP0L8fW77vfRY66gO/YoTo/WbIdQ/Si1g=="], - "@babel/plugin-transform-optional-chaining": ["@babel/plugin-transform-optional-chaining@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-WtRS1c94lZGpGHxYLXMEWeoMVcuv8nkiyr8BTs6OYZv7N3Y9xVE8nbdFIl4lDJH6aH8/pLhqAQOL69d/WI9WdA=="], + "@babel/plugin-transform-optional-chaining": ["@babel/plugin-transform-optional-chaining@8.0.5", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-w8ouIDKdmUc2oyvBx4S/WtiQM7bMww5LGjB2A4L1+sDWZGw37XxzqOqfgHnPm+2ldINmAqrf2ekzpeJ/sS9poQ=="], - "@babel/plugin-transform-parameters": ["@babel/plugin-transform-parameters@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-IIwRqroW0CYQwR6+3pnmu27z+H98poScWdnov8z6osumMeEsFxAFBBsDS2CFk2jFpPlGqVr89jK/HXO6i5DzxQ=="], + "@babel/plugin-transform-parameters": ["@babel/plugin-transform-parameters@8.0.5", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-oXsstDkzuE+gOqBz2+e1VFqDew0KlGgd9GT4MGptmcIq3uDbxcowHRSaqMCvp3nbiZws4wTm8Phuk9ZJO3NtTg=="], "@babel/plugin-transform-private-methods": ["@babel/plugin-transform-private-methods@8.0.1", "", { "dependencies": { "@babel/helper-create-class-features-plugin": "^8.0.1", "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-TrFCGcXaVDh6S5IRhmLSRTY9H80VTCMQWnZtzBRg4RWg3KCLmdmsmj4M15kZAPZfoPkWL/SJb4em3Py/vOiX8g=="], - "@babel/plugin-transform-private-property-in-object": ["@babel/plugin-transform-private-property-in-object@8.0.1", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^8.0.0", "@babel/helper-create-class-features-plugin": "^8.0.1", "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-e+yfOqSYBZaf3PARpiQkjZrpWYgmcFLhK+1tevh2CpHR1O9/36IdyPnAZusESX5nzVV/XZTDAtQBRLa8HPT5Dw=="], + "@babel/plugin-transform-private-property-in-object": ["@babel/plugin-transform-private-property-in-object@8.0.5", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^8.0.0", "@babel/helper-create-class-features-plugin": "^8.0.5", "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-OilYoElZMdD/My3fJTh0jLOPy8Y9Jfpcb9nPXG0Bpy4oRbZeeVX39P1cXKsPwnXTBZg7qEKk8TQ0lzpJvdK3yw=="], "@babel/plugin-transform-property-literals": ["@babel/plugin-transform-property-literals@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-Z/qx4cxUtYR1nt7XWRutObPxDks98fEYsjWbVeKEqZH6y3AGknmgzCqmHf2FHWZCl1DfoPeuJY+3hZ+35D+2tg=="], - "@babel/plugin-transform-regenerator": ["@babel/plugin-transform-regenerator@8.0.2", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-aFfsjCRYducRV4dPnpsBbdRkLjboca9FVDg6HZCgy0Ahvk2ZQ/2exmCRC5qS9P6rsWwrmIheNaIM6A1j2F8KMA=="], + "@babel/plugin-transform-regenerator": ["@babel/plugin-transform-regenerator@8.0.6", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-ky/yW+PcQfHyOhbQFNkcHOCIHXaEANYaXCucZ1MY1PdSJRjaf3AX/TMKS6nCij73YtU1bVNy7Zx5NWAJy42TQA=="], "@babel/plugin-transform-regexp-modifiers": ["@babel/plugin-transform-regexp-modifiers@8.0.1", "", { "dependencies": { "@babel/helper-create-regexp-features-plugin": "^8.0.1", "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-02ITRDBesPdTYU0oShAzERwEPzozOUQSXlz3qrt8JGuhalBJQv9z5NjgHJPC9sS3Fsam8gDtfAEpBnqZwUIdjQ=="], "@babel/plugin-transform-reserved-words": ["@babel/plugin-transform-reserved-words@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-+aykZi7ZP3U84veqfJXm3HhPZGddWFi64g7jr0ni6tb1zel+1ey+SL+IRKPoZXFyFqvYEsoqrmx4PyEJRlHl/Q=="], - "@babel/plugin-transform-runtime": ["@babel/plugin-transform-runtime@8.0.1", "", { "dependencies": { "@babel/helper-module-imports": "^8.0.0", "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-MPDpKBrxn+thQay3eJmUiSeHswiT7MkINb48hHkX6OzodB149PKq1kred+lpMebrDzHA+G1ekCQnlYSkyEqAOw=="], + "@babel/plugin-transform-runtime": ["@babel/plugin-transform-runtime@8.0.6", "", { "dependencies": { "@babel/helper-module-imports": "^8.0.0", "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-2djup+i7z4taCN9VCJsmPNC0GT5A0FhI+S0tZwK+FRDZdaEOQUYVmfKOg/hIKhMBXjOFxEsBHvGE0Thqj71edA=="], "@babel/plugin-transform-shorthand-properties": ["@babel/plugin-transform-shorthand-properties@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-JddANd9yPVH8dYgVoNkqAH5BftnsDxFpG51Zas7sc6F3poz5QWcejHNGO8a/57IX5ByjGSzEmYk9Z7ZMa5MWaw=="], - "@babel/plugin-transform-spread": ["@babel/plugin-transform-spread@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-O9Bw9FyxlSw1SlMg3S82/GKNZ0x77RPbHezotEy1JTlIM/vk6WO8jW1iF+iTiKLOXNvi+b+LZ9t77Gi+Q0FhGg=="], + "@babel/plugin-transform-spread": ["@babel/plugin-transform-spread@8.0.5", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-thqaGFTViCmJxUPJ3IivfaGHz8eodOL7UbsZ2gMOybSi8uQFXFEoabnnILMl4ZCok0vVrKD4HKq9MJWSj5qqxw=="], "@babel/plugin-transform-sticky-regex": ["@babel/plugin-transform-sticky-regex@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-IsVP6WrZZQdaG2zLmeKwWiI+ua2NB5L1+f77C2/8z2NCDz7uxlIA/lnwocYOJk9PXcOC2sZgRls3LN4XpNduzQ=="], @@ -320,7 +297,7 @@ "@babel/plugin-transform-typeof-symbol": ["@babel/plugin-transform-typeof-symbol@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-+wJoxgxP2gtey0UMUOMhzMMji2XHO/Uu6MXUh/r5Yhc2jngKzK/wFxY2WNe4UCaRcMvCb4gcnB8wIgFXJsocXg=="], - "@babel/plugin-transform-typescript": ["@babel/plugin-transform-typescript@8.0.1", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^8.0.0", "@babel/helper-create-class-features-plugin": "^8.0.1", "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0", "@babel/plugin-syntax-typescript": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-0Svqp3413Eg0GElldykF/T7SNsxQO5YVGD70fZyAdZTnX8WRgcopmbiU7GTa5xY5ZnJcEpNbfns8/GjX+/1yeA=="], + "@babel/plugin-transform-typescript": ["@babel/plugin-transform-typescript@8.0.6", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^8.0.0", "@babel/helper-create-class-features-plugin": "^8.0.6", "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0", "@babel/plugin-syntax-typescript": "^8.0.3" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-WF3yRlQtClzScvQbWct00ix63+w3DPiyU0WmCBU4YqK539n3VvJFElElpevoD8wfu6953CbiNoUZBi2B7/5jXw=="], "@babel/plugin-transform-unicode-escapes": ["@babel/plugin-transform-unicode-escapes@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-TAXJepIJ6vZphytTwcf+LuXi2M2ZWI43VCqNw+1ZZLPP/38Z1A8j4Mahvg8kqDgMOSM/cakk+hedTJCiw3jQuQ=="], @@ -330,7 +307,7 @@ "@babel/plugin-transform-unicode-sets-regex": ["@babel/plugin-transform-unicode-sets-regex@8.0.1", "", { "dependencies": { "@babel/helper-create-regexp-features-plugin": "^8.0.1", "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-MlQeyS0K7gh0XNeLBMS/3Z07HjDOKhA7xm2L18GyxOXyiFHI9E+ZuQ4mFYmcLjluXsE/Wf6dABIqZvKpKw0Z3w=="], - "@babel/preset-env": ["@babel/preset-env@8.0.2", "", { "dependencies": { "@babel/compat-data": "^8.0.0", "@babel/helper-compilation-targets": "^8.0.0", "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-validator-option": "^8.0.0", "@babel/plugin-bugfix-firefox-class-in-computed-class-key": "^8.0.1", "@babel/plugin-bugfix-safari-class-field-initializer-scope": "^8.0.1", "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^8.0.1", "@babel/plugin-bugfix-safari-rest-destructuring-rhs-array": "^8.0.1", "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^8.0.1", "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": "^8.0.1", "@babel/plugin-transform-arrow-functions": "^8.0.1", "@babel/plugin-transform-async-generator-functions": "^8.0.1", "@babel/plugin-transform-async-to-generator": "^8.0.1", "@babel/plugin-transform-block-scoped-functions": "^8.0.1", "@babel/plugin-transform-block-scoping": "^8.0.1", "@babel/plugin-transform-class-properties": "^8.0.1", "@babel/plugin-transform-class-static-block": "^8.0.1", "@babel/plugin-transform-classes": "^8.0.1", "@babel/plugin-transform-computed-properties": "^8.0.1", "@babel/plugin-transform-destructuring": "^8.0.1", "@babel/plugin-transform-dotall-regex": "^8.0.1", "@babel/plugin-transform-duplicate-keys": "^8.0.1", "@babel/plugin-transform-duplicate-named-capturing-groups-regex": "^8.0.1", "@babel/plugin-transform-dynamic-import": "^8.0.1", "@babel/plugin-transform-explicit-resource-management": "^8.0.1", "@babel/plugin-transform-exponentiation-operator": "^8.0.1", "@babel/plugin-transform-export-namespace-from": "^8.0.1", "@babel/plugin-transform-for-of": "^8.0.1", "@babel/plugin-transform-function-name": "^8.0.1", "@babel/plugin-transform-json-strings": "^8.0.1", "@babel/plugin-transform-literals": "^8.0.1", "@babel/plugin-transform-logical-assignment-operators": "^8.0.1", "@babel/plugin-transform-member-expression-literals": "^8.0.1", "@babel/plugin-transform-modules-amd": "^8.0.1", "@babel/plugin-transform-modules-commonjs": "^8.0.1", "@babel/plugin-transform-modules-systemjs": "^8.0.1", "@babel/plugin-transform-modules-umd": "^8.0.1", "@babel/plugin-transform-named-capturing-groups-regex": "^8.0.1", "@babel/plugin-transform-new-target": "^8.0.1", "@babel/plugin-transform-nullish-coalescing-operator": "^8.0.1", "@babel/plugin-transform-numeric-separator": "^8.0.1", "@babel/plugin-transform-object-rest-spread": "^8.0.1", "@babel/plugin-transform-object-super": "^8.0.1", "@babel/plugin-transform-optional-catch-binding": "^8.0.1", "@babel/plugin-transform-optional-chaining": "^8.0.1", "@babel/plugin-transform-parameters": "^8.0.1", "@babel/plugin-transform-private-methods": "^8.0.1", "@babel/plugin-transform-private-property-in-object": "^8.0.1", "@babel/plugin-transform-property-literals": "^8.0.1", "@babel/plugin-transform-regenerator": "^8.0.2", "@babel/plugin-transform-regexp-modifiers": "^8.0.1", "@babel/plugin-transform-reserved-words": "^8.0.1", "@babel/plugin-transform-shorthand-properties": "^8.0.1", "@babel/plugin-transform-spread": "^8.0.1", "@babel/plugin-transform-sticky-regex": "^8.0.1", "@babel/plugin-transform-template-literals": "^8.0.1", "@babel/plugin-transform-typeof-symbol": "^8.0.1", "@babel/plugin-transform-unicode-escapes": "^8.0.1", "@babel/plugin-transform-unicode-property-regex": "^8.0.1", "@babel/plugin-transform-unicode-regex": "^8.0.1", "@babel/plugin-transform-unicode-sets-regex": "^8.0.1", "@babel/preset-modules": "^0.2.0", "babel-plugin-polyfill-corejs3": "^1.0.0", "core-js-compat": "^3.48.0", "semver": "^7.7.3" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-CUGLn9hNBCF/eXnwdFAWERbniCcXCRvnKwLV9fegeUEIqv7YlU2MepsWMMM54GcILx5XYMnRh+JAL+K5G+mK6g=="], + "@babel/preset-env": ["@babel/preset-env@8.0.6", "", { "dependencies": { "@babel/compat-data": "^8.0.5", "@babel/helper-compilation-targets": "^8.0.6", "@babel/helper-plugin-utils": "^8.0.1", "@babel/helper-validator-option": "^8.0.0", "@babel/plugin-bugfix-firefox-class-in-computed-class-key": "^8.0.1", "@babel/plugin-bugfix-safari-class-field-initializer-scope": "^8.0.1", "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^8.0.1", "@babel/plugin-bugfix-safari-rest-destructuring-rhs-array": "^8.0.6", "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^8.0.1", "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": "^8.0.1", "@babel/plugin-transform-arrow-functions": "^8.0.1", "@babel/plugin-transform-async-generator-functions": "^8.0.6", "@babel/plugin-transform-async-to-generator": "^8.0.1", "@babel/plugin-transform-block-scoped-functions": "^8.0.1", "@babel/plugin-transform-block-scoping": "^8.0.5", "@babel/plugin-transform-class-properties": "^8.0.1", "@babel/plugin-transform-class-static-block": "^8.0.5", "@babel/plugin-transform-classes": "^8.0.5", "@babel/plugin-transform-computed-properties": "^8.0.1", "@babel/plugin-transform-destructuring": "^8.0.5", "@babel/plugin-transform-dotall-regex": "^8.0.1", "@babel/plugin-transform-duplicate-keys": "^8.0.1", "@babel/plugin-transform-duplicate-named-capturing-groups-regex": "^8.0.1", "@babel/plugin-transform-dynamic-import": "^8.0.1", "@babel/plugin-transform-explicit-resource-management": "^8.0.5", "@babel/plugin-transform-exponentiation-operator": "^8.0.1", "@babel/plugin-transform-export-namespace-from": "^8.0.1", "@babel/plugin-transform-for-of": "^8.0.1", "@babel/plugin-transform-function-name": "^8.0.1", "@babel/plugin-transform-json-strings": "^8.0.1", "@babel/plugin-transform-literals": "^8.0.1", "@babel/plugin-transform-logical-assignment-operators": "^8.0.1", "@babel/plugin-transform-member-expression-literals": "^8.0.1", "@babel/plugin-transform-modules-amd": "^8.0.1", "@babel/plugin-transform-modules-commonjs": "^8.0.1", "@babel/plugin-transform-modules-systemjs": "^8.0.1", "@babel/plugin-transform-modules-umd": "^8.0.1", "@babel/plugin-transform-named-capturing-groups-regex": "^8.0.1", "@babel/plugin-transform-new-target": "^8.0.1", "@babel/plugin-transform-nullish-coalescing-operator": "^8.0.1", "@babel/plugin-transform-numeric-separator": "^8.0.1", "@babel/plugin-transform-object-rest-spread": "^8.0.1", "@babel/plugin-transform-object-super": "^8.0.1", "@babel/plugin-transform-optional-catch-binding": "^8.0.1", "@babel/plugin-transform-optional-chaining": "^8.0.5", "@babel/plugin-transform-parameters": "^8.0.5", "@babel/plugin-transform-private-methods": "^8.0.1", "@babel/plugin-transform-private-property-in-object": "^8.0.5", "@babel/plugin-transform-property-literals": "^8.0.1", "@babel/plugin-transform-regenerator": "^8.0.6", "@babel/plugin-transform-regexp-modifiers": "^8.0.1", "@babel/plugin-transform-reserved-words": "^8.0.1", "@babel/plugin-transform-shorthand-properties": "^8.0.1", "@babel/plugin-transform-spread": "^8.0.5", "@babel/plugin-transform-sticky-regex": "^8.0.1", "@babel/plugin-transform-template-literals": "^8.0.1", "@babel/plugin-transform-typeof-symbol": "^8.0.1", "@babel/plugin-transform-unicode-escapes": "^8.0.1", "@babel/plugin-transform-unicode-property-regex": "^8.0.1", "@babel/plugin-transform-unicode-regex": "^8.0.1", "@babel/plugin-transform-unicode-sets-regex": "^8.0.1", "@babel/preset-modules": "^0.2.0", "babel-plugin-polyfill-corejs3": "^1.0.0", "core-js-compat": "^3.48.0", "verkit": "^0.3.2" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-Ekl110OgRBQtibBTXrXyuxhy2p7QxpzWT45cFOZCBFKBan3o8vN54sQ26GtqyTyORSNWKx0GOmIdLTTu/Y+prA=="], "@babel/preset-modules": ["@babel/preset-modules@0.2.0", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1", "@babel/plugin-transform-dotall-regex": "^8.0.1", "@babel/plugin-transform-unicode-property-regex": "^8.0.1", "@babel/types": "^8.0.0", "esutils": "^2.0.2" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-yz0RBN2fx4fjCeFcTWsWgL7PxSRltvTa0Qg14HkWCU3qS8MO7ZSJlBVbGceynd5C9NsJwwUHNQD3dc6tYO+jqQ=="], @@ -344,7 +321,7 @@ "@babel/traverse": ["@babel/traverse@7.29.8", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.8", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.8", "@babel/template": "^7.29.7", "@babel/types": "^7.29.8", "debug": "^4.3.1" } }, "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg=="], - "@babel/types": ["@babel/types@8.0.0", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0", "@babel/helper-validator-identifier": "^8.0.0" } }, "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw=="], + "@babel/types": ["@babel/types@8.0.6", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.6", "@babel/helper-validator-identifier": "^8.0.6" } }, "sha512-c+xgSWboV2pdwXP67BUWDVRHi2BO5Q3KwxyFVs7taVTY+fsK47/L51ZXQoV9rozHJDNHvJ4v4WEsI/IlxV2l2A=="], "@bazel/runfiles": ["@bazel/runfiles@6.5.0", "", {}, "sha512-RzahvqTkfpY2jsDxo8YItPX+/iZ6hbiikw1YhE0bA9EKBR5Og8Pa6FHn9PO9M0zaXRVsr0GFQLKbB/0rzy9SzA=="], @@ -370,7 +347,7 @@ "@codemirror/buildhelper": ["@codemirror/buildhelper@1.0.2", "", { "dependencies": { "@lezer/generator": "^1.0.0", "@marijn/buildtool": "^1.0.0", "@marijn/testtool": "^0.1.3" }, "bin": { "cm-buildhelper": "bin/cm-buildhelper.js", "cm-runtests": "bin/cm-runtests.js" } }, "sha512-aVewtDPZptq9dTvYqIjpu9HTEmMaKAE4VL22z5E1ycgY5e1LdAiRd5YYjqzQeqLjxpWsHy+emO3n5UUcxpUmSg=="], - "@codemirror/commands": ["@codemirror/commands@6.11.0", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.7.0", "@codemirror/view": "^6.27.0", "@lezer/common": "^1.1.0" } }, "sha512-/K4Rl5BN0OtTiPWmJCdqODu38XnDMsDxKY5rgrPnCkutPTJf2wVbkoixLfealF5Kwse/s8P8M5jAiURiwSwnFA=="], + "@codemirror/commands": ["@codemirror/commands@6.11.1", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.7.0", "@codemirror/view": "^6.27.0", "@lezer/common": "^1.1.0" } }, "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg=="], "@codemirror/lang-angular": ["@codemirror/lang-angular@0.1.4", "", { "dependencies": { "@codemirror/lang-html": "^6.0.0", "@codemirror/lang-javascript": "^6.1.2", "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.3" } }, "sha512-oap+gsltb/fzdlTQWD6BFF4bSLKcDnlxDsLdePiJpCVNKWXSTAbiiQeYI3UmES+BLAdkmIC1WjyztC1pi/bX4g=="], @@ -392,7 +369,7 @@ "@codemirror/lang-less": ["@codemirror/lang-less@6.0.2", "", { "dependencies": { "@codemirror/lang-css": "^6.2.0", "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-EYdQTG22V+KUUk8Qq582g7FMnCZeEHsyuOJisHRft/mQ+ZSZ2w51NupvDUHiqtsOy7It5cHLPGfHQLpMh9bqpQ=="], - "@codemirror/lang-liquid": ["@codemirror/lang-liquid@6.3.2", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.1" } }, "sha512-6PDVU3ZnfeYyz1at1E/ttorErZvZFXXt1OPhtfe1EZJ2V2iDFa0CwPqPgG5F7NXN0yONGoBogKmFAafKTqlwIw=="], + "@codemirror/lang-liquid": ["@codemirror/lang-liquid@6.3.3", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.1" } }, "sha512-U9EnyzWuAx1TX3MZSKDXydKH734n1Aogk/ijKdW+jdIwmbf9zSPQYOIKggC/b2PTRjQb7ddvMktmxnfTLuv/SQ=="], "@codemirror/lang-markdown": ["@codemirror/lang-markdown@6.5.2", "", { "dependencies": { "@codemirror/autocomplete": "^6.7.1", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.3.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.2.1", "@lezer/markdown": "^1.0.0" } }, "sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw=="], @@ -418,13 +395,13 @@ "@codemirror/language-data": ["@codemirror/language-data@6.5.2", "", { "dependencies": { "@codemirror/lang-angular": "^0.1.0", "@codemirror/lang-cpp": "^6.0.0", "@codemirror/lang-css": "^6.0.0", "@codemirror/lang-go": "^6.0.0", "@codemirror/lang-html": "^6.0.0", "@codemirror/lang-java": "^6.0.0", "@codemirror/lang-javascript": "^6.0.0", "@codemirror/lang-jinja": "^6.0.0", "@codemirror/lang-json": "^6.0.0", "@codemirror/lang-less": "^6.0.0", "@codemirror/lang-liquid": "^6.0.0", "@codemirror/lang-markdown": "^6.0.0", "@codemirror/lang-php": "^6.0.0", "@codemirror/lang-python": "^6.0.0", "@codemirror/lang-rust": "^6.0.0", "@codemirror/lang-sass": "^6.0.0", "@codemirror/lang-sql": "^6.0.0", "@codemirror/lang-vue": "^0.1.1", "@codemirror/lang-wast": "^6.0.0", "@codemirror/lang-xml": "^6.0.0", "@codemirror/lang-yaml": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/legacy-modes": "^6.4.0" } }, "sha512-CPkWBKrNS8stYbEU5kwBwTf3JB1kghlbh4FSAwzGW2TEscdeHHH4FGysREW86Mqnj3Qn09s0/6Ea/TutmoTobg=="], - "@codemirror/legacy-modes": ["@codemirror/legacy-modes@6.5.3", "", { "dependencies": { "@codemirror/language": "^6.0.0" } }, "sha512-xCsmIzH78MyWkib9jlPaaun57XNkfbMIhagfaZVd0iLTqlpw3jXaIcbZm72MTmmn64eTZpBVNjbyYh+QXnxRsg=="], + "@codemirror/legacy-modes": ["@codemirror/legacy-modes@6.5.4", "", { "dependencies": { "@codemirror/language": "^6.0.0" } }, "sha512-/cZr6qZyl08iYNLGsJ862CXXNI51LryRFRE40ejgoIjXZz0C1rGkD3/Ek5jM/8w1ceRjqtt4qx/KLMh4zBTgew=="], "@codemirror/lint": ["@codemirror/lint@6.9.7", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.42.0", "crelt": "^1.0.5" } }, "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg=="], "@codemirror/lsp-client": ["@codemirror/lsp-client@file:codemirror-lsp-client", { "dependencies": { "@codemirror/autocomplete": "^6.20.0", "@codemirror/language": "^6.11.0", "@codemirror/lint": "^6.8.5", "@codemirror/state": "^6.5.2", "@codemirror/view": "^6.37.0", "@lezer/highlight": "^1.2.1", "marked": "^15.0.12", "vscode-languageserver-protocol": "^3.17.5" }, "devDependencies": { "@codemirror/buildhelper": "^1.0.0", "@codemirror/lang-javascript": "^6.0.0", "typescript": "^5.8.3", "typescript-language-server": "^4.3.4" } }], - "@codemirror/search": ["@codemirror/search@6.7.1", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.37.0", "crelt": "^1.0.5" } }, "sha512-uMe5UO6PamJtSHrXhhHOzSX3ReWtiJrva6GnPMwSOrZtiExb5X5eExhr2OUZQVvdxPsKpY3Ro2mFbQadpPWmHA=="], + "@codemirror/search": ["@codemirror/search@6.7.2", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.37.0", "crelt": "^1.0.5" } }, "sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA=="], "@codemirror/state": ["@codemirror/state@6.7.6", "", { "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } }, "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w=="], @@ -452,12 +429,6 @@ "@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g=="], - "@gar/promise-retry": ["@gar/promise-retry@1.0.3", "", {}, "sha512-GmzA9ckNokPypTg10pgpeHNQe7ph+iIKKmhKu3Ob9ANkswreCx7R3cKmY781K8QK3AqVL3xVh9A42JvIAbkkSA=="], - - "@isaacs/fs-minipass": ["@isaacs/fs-minipass@4.0.1", "", { "dependencies": { "minipass": "^7.0.4" } }, "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w=="], - - "@isaacs/string-locale-compare": ["@isaacs/string-locale-compare@1.1.0", "", {}, "sha512-SQ7Kzhh9+D+ZW9MA0zkYv3VXhIDNx+LzM6EJ+/65I3QY+enU6Itte7E5XX7EWrqLW2FN4n06GWzBnPoC3th2aQ=="], - "@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="], "@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="], @@ -466,17 +437,17 @@ "@jridgewell/source-map": ["@jridgewell/source-map@0.3.11", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25" } }, "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA=="], - "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="], + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], "@lezer/common": ["@lezer/common@1.5.6", "", {}, "sha512-NZxu3q49ck+YYbEJPuIPIyFP37XneBvzPIarBHEXBLBVfkZqQieZ/Y2boYnGNYtmjpOZLnAKs/lwqtmDpi365w=="], - "@lezer/cpp": ["@lezer/cpp@1.1.5", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-DIhSXmYtJKLehrjzDFN+2cPt547ySQ41nA8yqcDf/GxMc+YM736xqltFkvADL2M0VebU5I+3+4ks2Vv+Kyq3Aw=="], + "@lezer/cpp": ["@lezer/cpp@1.1.6", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-vh9gWWJOXFVY8HBHK3Twzq8MgwG2iN4GSyzBP9sCGTe37P15x2R14VaBQk0VA0ezTRN1KHYBBsHhvpGZ2Xy/pA=="], - "@lezer/css": ["@lezer/css@1.3.3", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.0" } }, "sha512-RzBo8r+/6QJeow7aPHIpGVIH59xTcJXp399820gZoMo9noQDRVpJLheIBUicYwKcsbOYoBRoLZlf2720dG/4Tg=="], + "@lezer/css": ["@lezer/css@1.3.8", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.0" } }, "sha512-EJn1zcL9qoDptief6ipWKZKLiOpXkxSe0+t8CH9oiMVcZlq7NBWrjCqnc/41EIjeo/ITj1gFFiATdTkaJDL+Og=="], - "@lezer/generator": ["@lezer/generator@1.8.0", "", { "dependencies": { "@lezer/common": "^1.1.0", "@lezer/lr": "^1.3.0" }, "bin": { "lezer-generator": "src/lezer-generator.cjs" } }, "sha512-/SF4EDWowPqV1jOgoGSGTIFsE7Ezdr7ZYxyihl5eMKVO5tlnpIhFcDavgm1hHY5GEonoOAEnJ0CU0x+tvuAuUg=="], + "@lezer/generator": ["@lezer/generator@1.8.1", "", { "dependencies": { "@lezer/common": "^1.1.0", "@lezer/lr": "^1.3.0" }, "bin": { "lezer-generator": "src/lezer-generator.cjs" } }, "sha512-7q7szXqT7EPTs6SODBl58Qoz/4OrhNvm5pW4lbu1ZDnG5e0nn7drLzeN9Nxkm8j/1iMs5QZ9j3i4SV+W4Z6SQA=="], "@lezer/go": ["@lezer/go@1.0.1", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.0" } }, "sha512-xToRsYxwsgJNHTgNdStpcvmbVuKxTapV0dM0wey1geMMRc9aggoVyKgzYp41D2/vVOx+Ii4hmE206kvxIXBVXQ=="], @@ -484,21 +455,21 @@ "@lezer/html": ["@lezer/html@1.3.13", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg=="], - "@lezer/java": ["@lezer/java@1.1.3", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-yHquUfujwg6Yu4Fd1GNHCvidIvJwi/1Xu2DaKl/pfWIA2c1oXkVvawH3NyXhCaFx4OdlYBVX5wvz2f7Aoa/4Xw=="], + "@lezer/java": ["@lezer/java@1.1.4", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-gQylJ2xHV2xXsVqtnAcJrcROvLZJaQiC0tR//+q0k961BxqvyYttusPkJ8d9T1fPDJKHJW2etUH8XbIn9jhVUg=="], - "@lezer/javascript": ["@lezer/javascript@1.5.4", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.1.3", "@lezer/lr": "^1.3.0" } }, "sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA=="], + "@lezer/javascript": ["@lezer/javascript@1.5.6", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.1.3", "@lezer/lr": "^1.3.0" } }, "sha512-sEvOqpl4vJQca0NugSQK02vQPbc5KrvoojnYGoqqFgFO0MtcYhwGiHKVEB+LuXYJnfyXo4QPA8ztbrEa4Fw5NA=="], "@lezer/json": ["@lezer/json@1.0.3", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ=="], "@lezer/lr": ["@lezer/lr@1.4.10", "", { "dependencies": { "@lezer/common": "^1.0.0" } }, "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A=="], - "@lezer/markdown": ["@lezer/markdown@1.6.3", "", { "dependencies": { "@lezer/common": "^1.5.0", "@lezer/highlight": "^1.0.0" } }, "sha512-jpGm5Ps+XErS+xA4urw7ogEGkeZOahVQF21Z6oECF0sj+2liwZopd2+I8uH5I/vZsRuuze3OxBREIANLf6KKUw=="], + "@lezer/markdown": ["@lezer/markdown@1.7.2", "", { "dependencies": { "@lezer/common": "^1.5.0", "@lezer/highlight": "^1.0.0" } }, "sha512-iTkYvoVcKt3WkeL7qUDyXHONZEwLio4wj8KTNi2dnjQEXBZKMV63BpQrPqfsM+OkvuRbiSTAcycYAsQzLhRNoQ=="], - "@lezer/php": ["@lezer/php@1.0.5", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.1.0" } }, "sha512-W7asp9DhM6q0W6DYNwIkLSKOvxlXRrif+UXBMxzsJUuqmhE7oVU+gS3THO4S/Puh7Xzgm858UNaFi6dxTP8dJA=="], + "@lezer/php": ["@lezer/php@1.0.6", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.1.0" } }, "sha512-QJ2xNXPmsm/Z3IpThq8fnJrEIVpxhsIoj6GZBW0JYEd/l9zxpJZW216X4fzqQY4vgpdGIumypvI4uQjd4tnYtw=="], - "@lezer/python": ["@lezer/python@1.1.18", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-31FiUrU7z9+d/ElGQLJFXl+dKOdx0jALlP3KEOsGTex8mvj+SoE1FgItcHWK/axkxCHGUSpqIHt6JAWfWu9Rhg=="], + "@lezer/python": ["@lezer/python@1.1.19", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-MhQIURHRytsNzP/YXnqpYKW6la6voAH3kyplTOOiCdjyFY6cWWGFVmYVdHIPrElqSDf4iCDktQCockB9FxuhzQ=="], - "@lezer/rust": ["@lezer/rust@1.0.2", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-Lz5sIPBdF2FUXcWeCu1//ojFAZqzTQNRga0aYv6dYXqJqPfMdCAI0NzajWUd4Xijj1IKJLtjoXRPMvTKWBcqKg=="], + "@lezer/rust": ["@lezer/rust@1.0.3", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-XxErOjZzQ7yJt1agUT4fu9qQvESZ3acgoxpPaPTPOiUx+duCjaVAtZGFIgphkHxlN05djdVAIOy/wItShMEjqQ=="], "@lezer/sass": ["@lezer/sass@1.1.0", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-3mMGdCTUZ/84ArHOuXWQr37pnf7f+Nw9ycPUeKX+wu19b7pSMcZGLbaXwvD2APMBDOGxPmpK/O6S1v1EvLoqgQ=="], @@ -506,7 +477,7 @@ "@lezer/yaml": ["@lezer/yaml@1.0.4", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.4.0" } }, "sha512-2lrrHqxalACEbxIbsjhqGpSW8kWpUKuY6RHgnSAFZa6qK62wvnPxA8hGOwOoDbwHcOFs5M4o27mjGu+P7TvBmw=="], - "@marijn/buildtool": ["@marijn/buildtool@1.2.0", "", { "dependencies": { "@types/mocha": "^9.1.1", "acorn": "^8.10.0", "acorn-walk": "^8.2.0", "rollup": "^4.8.0", "rollup-plugin-dts": "^6.1.0", "typescript": "^5.3.3" } }, "sha512-ytEK7n4NVrq6Rhq2J+N/CcvJLl6NX0bZ1qSi3w8lxZVcI4L6Y6vj1pugcTnv+YdyFNwFuACSdDesetZmQqSy1w=="], + "@marijn/buildtool": ["@marijn/buildtool@1.2.1", "", { "dependencies": { "@types/mocha": "^9.1.1", "acorn": "^8.10.0", "acorn-walk": "^8.2.0", "rollup": "^4.8.0", "rollup-plugin-dts": "^6.1.0", "typescript": "^5.3.3" } }, "sha512-CcbDNOPXiY5pW+YECfc5PuqXR9YvGRENlo8vVCNDo7AuJgKfo+DkEQk6emaqZy58TrVrKy+BCj+IErV0ZiPJnQ=="], "@marijn/find-cluster-break": ["@marijn/find-cluster-break@1.0.4", "", {}, "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ=="], @@ -516,216 +487,160 @@ "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.6", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg=="], - "@netflix/nerror": ["@netflix/nerror@1.1.3", "", { "dependencies": { "assert-plus": "^1.0.0", "extsprintf": "^1.4.0", "lodash": "^4.17.15" } }, "sha512-b+MGNyP9/LXkapreJzNUzcvuzZslj/RGgdVVJ16P2wSlYatfLycPObImqVJSmNAdyeShvNeM/pl3sVZsObFueg=="], - - "@nodelib/fs.scandir": ["@nodelib/fs.scandir@2.1.5", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="], - - "@nodelib/fs.stat": ["@nodelib/fs.stat@2.0.5", "", {}, "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A=="], - - "@nodelib/fs.walk": ["@nodelib/fs.walk@1.2.8", "", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg=="], - - "@npmcli/agent": ["@npmcli/agent@4.0.0", "", { "dependencies": { "agent-base": "^7.1.0", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.1", "lru-cache": "^11.2.1", "socks-proxy-agent": "^8.0.3" } }, "sha512-kAQTcEN9E8ERLVg5AsGwLNoFb+oEG6engbqAU2P43gD4JEIkNGMHdVQ096FsOAAYpZPB0RSt0zgInKIAS1l5QA=="], - - "@npmcli/arborist": ["@npmcli/arborist@9.5.0", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@isaacs/string-locale-compare": "^1.1.0", "@npmcli/fs": "^5.0.0", "@npmcli/installed-package-contents": "^4.0.0", "@npmcli/map-workspaces": "^5.0.0", "@npmcli/metavuln-calculator": "^9.0.2", "@npmcli/name-from-folder": "^4.0.0", "@npmcli/node-gyp": "^5.0.0", "@npmcli/package-json": "^7.0.0", "@npmcli/query": "^5.0.0", "@npmcli/redact": "^4.0.0", "@npmcli/run-script": "^10.0.0", "bin-links": "^6.0.0", "cacache": "^20.0.1", "common-ancestor-path": "^2.0.0", "hosted-git-info": "^9.0.0", "json-stringify-nice": "^1.1.4", "lru-cache": "^11.2.1", "minimatch": "^10.0.3", "nopt": "^9.0.0", "npm-install-checks": "^8.0.0", "npm-package-arg": "^13.0.0", "npm-pick-manifest": "^11.0.1", "npm-registry-fetch": "^19.0.0", "pacote": "^21.0.2", "parse-conflict-json": "^5.0.1", "proc-log": "^6.0.0", "proggy": "^4.0.0", "promise-all-reject-late": "^1.0.0", "promise-call-limit": "^3.0.1", "semver": "^7.3.7", "ssri": "^13.0.0", "treeverse": "^3.0.0", "walk-up-path": "^4.0.0" }, "bin": { "arborist": "bin/index.js" } }, "sha512-qS+TtKWC58sjBjD+szLrhEj2TCLnwzUA9vlMyCnU9ztw01ZjQSu25iQPxeBa0sk9sS9/Hzs/xJMWl7J/vRCjGQ=="], - - "@npmcli/fs": ["@npmcli/fs@5.0.0", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-7OsC1gNORBEawOa5+j2pXN9vsicaIOH5cPXxoR6fJOmH6/EXpJB2CajXOu1fPRFun2m1lktEFX11+P89hqO/og=="], - - "@npmcli/git": ["@npmcli/git@7.0.2", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@npmcli/promise-spawn": "^9.0.0", "ini": "^6.0.0", "lru-cache": "^11.2.1", "npm-pick-manifest": "^11.0.1", "proc-log": "^6.0.0", "semver": "^7.3.5", "which": "^6.0.0" } }, "sha512-oeolHDjExNAJAnlYP2qzNjMX/Xi9bmu78C9dIGr4xjobrSKbuMYCph8lTzn4vnW3NjIqVmw/f8BCfouqyJXlRg=="], - - "@npmcli/installed-package-contents": ["@npmcli/installed-package-contents@4.0.0", "", { "dependencies": { "npm-bundled": "^5.0.0", "npm-normalize-package-bin": "^5.0.0" }, "bin": { "installed-package-contents": "bin/index.js" } }, "sha512-yNyAdkBxB72gtZ4GrwXCM0ZUedo9nIbOMKfGjt6Cu6DXf0p8y1PViZAKDC8q8kv/fufx0WTjRBdSlyrvnP7hmA=="], - - "@npmcli/map-workspaces": ["@npmcli/map-workspaces@5.0.3", "", { "dependencies": { "@npmcli/name-from-folder": "^4.0.0", "@npmcli/package-json": "^7.0.0", "glob": "^13.0.0", "minimatch": "^10.0.3" } }, "sha512-o2grssXo1e774E5OtEwwrgoszYRh0lqkJH+Pb9r78UcqdGJRDRfhpM8DvZPjzNLLNYeD/rNbjOKM3Ss5UABROw=="], - - "@npmcli/metavuln-calculator": ["@npmcli/metavuln-calculator@9.0.3", "", { "dependencies": { "cacache": "^20.0.0", "json-parse-even-better-errors": "^5.0.0", "pacote": "^21.0.0", "proc-log": "^6.0.0", "semver": "^7.3.5" } }, "sha512-94GLSYhLXF2t2LAC7pDwLaM4uCARzxShyAQKsirmlNcpidH89VA4/+K1LbJmRMgz5gy65E/QBBWQdUvGLe2Frg=="], - - "@npmcli/name-from-folder": ["@npmcli/name-from-folder@4.0.0", "", {}, "sha512-qfrhVlOSqmKM8i6rkNdZzABj8MKEITGFAY+4teqBziksCQAOLutiAxM1wY2BKEd8KjUSpWmWCYxvXr0y4VTlPg=="], - - "@npmcli/node-gyp": ["@npmcli/node-gyp@5.0.0", "", {}, "sha512-uuG5HZFXLfyFKqg8QypsmgLQW7smiRjVc45bqD/ofZZcR/uxEjgQU8qDPv0s9TEeMUiAAU/GC5bR6++UdTirIQ=="], - - "@npmcli/package-json": ["@npmcli/package-json@7.0.5", "", { "dependencies": { "@npmcli/git": "^7.0.0", "glob": "^13.0.0", "hosted-git-info": "^9.0.0", "json-parse-even-better-errors": "^5.0.0", "proc-log": "^6.0.0", "semver": "^7.5.3", "spdx-expression-parse": "^4.0.0" } }, "sha512-iVuTlG3ORq2iaVa1IWUxAO/jIp77tUKBhoMjuzYW2kL4MLN1bi/ofqkZ7D7OOwh8coAx1/S2ge0rMdGv8sLSOQ=="], - - "@npmcli/promise-spawn": ["@npmcli/promise-spawn@9.0.1", "", { "dependencies": { "which": "^6.0.0" } }, "sha512-OLUaoqBuyxeTqUvjA3FZFiXUfYC1alp3Sa99gW3EUDz3tZ3CbXDdcZ7qWKBzicrJleIgucoWamWH1saAmH/l2Q=="], - - "@npmcli/query": ["@npmcli/query@5.0.0", "", { "dependencies": { "postcss-selector-parser": "^7.0.0" } }, "sha512-8TZWfTQOsODpLqo9SVhVjHovmKXNpevHU0gO9e+y4V4fRIOneiXy0u0sMP9LmS71XivrEWfZWg50ReH4WRT4aQ=="], - - "@npmcli/redact": ["@npmcli/redact@4.0.0", "", {}, "sha512-gOBg5YHMfZy+TfHArfVogwgfBeQnKbbGo3pSUyK/gSI0AVu+pEiDVcKlQb0D8Mg1LNRZILZ6XG8I5dJ4KuAd9Q=="], - - "@npmcli/run-script": ["@npmcli/run-script@10.0.4", "", { "dependencies": { "@npmcli/node-gyp": "^5.0.0", "@npmcli/package-json": "^7.0.0", "@npmcli/promise-spawn": "^9.0.0", "node-gyp": "^12.1.0", "proc-log": "^6.0.0" } }, "sha512-mGUWr1uMnf0le2TwfOZY4SFxZGXGfm4Jtay/nwAa2FLNAKXUoUwaGwBMNH36UHPtinWfTSJ3nqFQr0091CxVGg=="], + "@oxc-project/types": ["@oxc-project/types@0.152.0", "", {}, "sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw=="], - "@oxc-project/types": ["@oxc-project/types@0.147.0", "", {}, "sha512-IJ3s6ltHLp45S0bh7phkX+gJO7A1Wuz2EaqpAhb8WjqDwbzMiWKHhyyT42tskaWjEYXtHtVCPpnBJVT9+dcRLg=="], + "@parcel/watcher": ["@parcel/watcher@2.6.0", "", { "dependencies": { "detect-libc": "^2.0.3", "is-glob": "^4.0.3", "node-addon-api": "^7.0.0", "picomatch": "^4.0.4" }, "optionalDependencies": { "@parcel/watcher-android-arm64": "2.6.0", "@parcel/watcher-darwin-arm64": "2.6.0", "@parcel/watcher-darwin-x64": "2.6.0", "@parcel/watcher-freebsd-x64": "2.6.0", "@parcel/watcher-linux-arm-glibc": "2.6.0", "@parcel/watcher-linux-arm-musl": "2.6.0", "@parcel/watcher-linux-arm64-glibc": "2.6.0", "@parcel/watcher-linux-arm64-musl": "2.6.0", "@parcel/watcher-linux-x64-glibc": "2.6.0", "@parcel/watcher-linux-x64-musl": "2.6.0", "@parcel/watcher-win32-arm64": "2.6.0", "@parcel/watcher-win32-x64": "2.6.0" } }, "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w=="], - "@parcel/watcher": ["@parcel/watcher@2.5.6", "", { "dependencies": { "detect-libc": "^2.0.3", "is-glob": "^4.0.3", "node-addon-api": "^7.0.0", "picomatch": "^4.0.3" }, "optionalDependencies": { "@parcel/watcher-android-arm64": "2.5.6", "@parcel/watcher-darwin-arm64": "2.5.6", "@parcel/watcher-darwin-x64": "2.5.6", "@parcel/watcher-freebsd-x64": "2.5.6", "@parcel/watcher-linux-arm-glibc": "2.5.6", "@parcel/watcher-linux-arm-musl": "2.5.6", "@parcel/watcher-linux-arm64-glibc": "2.5.6", "@parcel/watcher-linux-arm64-musl": "2.5.6", "@parcel/watcher-linux-x64-glibc": "2.5.6", "@parcel/watcher-linux-x64-musl": "2.5.6", "@parcel/watcher-win32-arm64": "2.5.6", "@parcel/watcher-win32-ia32": "2.5.6", "@parcel/watcher-win32-x64": "2.5.6" } }, "sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ=="], + "@parcel/watcher-android-arm64": ["@parcel/watcher-android-arm64@2.6.0", "", { "os": "android", "cpu": "arm64" }, "sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA=="], - "@parcel/watcher-android-arm64": ["@parcel/watcher-android-arm64@2.5.6", "", { "os": "android", "cpu": "arm64" }, "sha512-YQxSS34tPF/6ZG7r/Ih9xy+kP/WwediEUsqmtf0cuCV5TPPKw/PQHRhueUo6JdeFJaqV3pyjm0GdYjZotbRt/A=="], + "@parcel/watcher-darwin-arm64": ["@parcel/watcher-darwin-arm64@2.6.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw=="], - "@parcel/watcher-darwin-arm64": ["@parcel/watcher-darwin-arm64@2.5.6", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Z2ZdrnwyXvvvdtRHLmM4knydIdU9adO3D4n/0cVipF3rRiwP+3/sfzpAwA/qKFL6i1ModaabkU7IbpeMBgiVEA=="], + "@parcel/watcher-darwin-x64": ["@parcel/watcher-darwin-x64@2.6.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw=="], - "@parcel/watcher-darwin-x64": ["@parcel/watcher-darwin-x64@2.5.6", "", { "os": "darwin", "cpu": "x64" }, "sha512-HgvOf3W9dhithcwOWX9uDZyn1lW9R+7tPZ4sug+NGrGIo4Rk1hAXLEbcH1TQSqxts0NYXXlOWqVpvS1SFS4fRg=="], + "@parcel/watcher-freebsd-x64": ["@parcel/watcher-freebsd-x64@2.6.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ=="], - "@parcel/watcher-freebsd-x64": ["@parcel/watcher-freebsd-x64@2.5.6", "", { "os": "freebsd", "cpu": "x64" }, "sha512-vJVi8yd/qzJxEKHkeemh7w3YAn6RJCtYlE4HPMoVnCpIXEzSrxErBW5SJBgKLbXU3WdIpkjBTeUNtyBVn8TRng=="], + "@parcel/watcher-linux-arm-glibc": ["@parcel/watcher-linux-arm-glibc@2.6.0", "", { "os": "linux", "cpu": "arm" }, "sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg=="], - "@parcel/watcher-linux-arm-glibc": ["@parcel/watcher-linux-arm-glibc@2.5.6", "", { "os": "linux", "cpu": "arm" }, "sha512-9JiYfB6h6BgV50CCfasfLf/uvOcJskMSwcdH1PHH9rvS1IrNy8zad6IUVPVUfmXr+u+Km9IxcfMLzgdOudz9EQ=="], + "@parcel/watcher-linux-arm-musl": ["@parcel/watcher-linux-arm-musl@2.6.0", "", { "os": "linux", "cpu": "arm" }, "sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw=="], - "@parcel/watcher-linux-arm-musl": ["@parcel/watcher-linux-arm-musl@2.5.6", "", { "os": "linux", "cpu": "arm" }, "sha512-Ve3gUCG57nuUUSyjBq/MAM0CzArtuIOxsBdQ+ftz6ho8n7s1i9E1Nmk/xmP323r2YL0SONs1EuwqBp2u1k5fxg=="], + "@parcel/watcher-linux-arm64-glibc": ["@parcel/watcher-linux-arm64-glibc@2.6.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g=="], - "@parcel/watcher-linux-arm64-glibc": ["@parcel/watcher-linux-arm64-glibc@2.5.6", "", { "os": "linux", "cpu": "arm64" }, "sha512-f2g/DT3NhGPdBmMWYoxixqYr3v/UXcmLOYy16Bx0TM20Tchduwr4EaCbmxh1321TABqPGDpS8D/ggOTaljijOA=="], + "@parcel/watcher-linux-arm64-musl": ["@parcel/watcher-linux-arm64-musl@2.6.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA=="], - "@parcel/watcher-linux-arm64-musl": ["@parcel/watcher-linux-arm64-musl@2.5.6", "", { "os": "linux", "cpu": "arm64" }, "sha512-qb6naMDGlbCwdhLj6hgoVKJl2odL34z2sqkC7Z6kzir8b5W65WYDpLB6R06KabvZdgoHI/zxke4b3zR0wAbDTA=="], + "@parcel/watcher-linux-x64-glibc": ["@parcel/watcher-linux-x64-glibc@2.6.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A=="], - "@parcel/watcher-linux-x64-glibc": ["@parcel/watcher-linux-x64-glibc@2.5.6", "", { "os": "linux", "cpu": "x64" }, "sha512-kbT5wvNQlx7NaGjzPFu8nVIW1rWqV780O7ZtkjuWaPUgpv2NMFpjYERVi0UYj1msZNyCzGlaCWEtzc+exjMGbQ=="], + "@parcel/watcher-linux-x64-musl": ["@parcel/watcher-linux-x64-musl@2.6.0", "", { "os": "linux", "cpu": "x64" }, "sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw=="], - "@parcel/watcher-linux-x64-musl": ["@parcel/watcher-linux-x64-musl@2.5.6", "", { "os": "linux", "cpu": "x64" }, "sha512-1JRFeC+h7RdXwldHzTsmdtYR/Ku8SylLgTU/reMuqdVD7CtLwf0VR1FqeprZ0eHQkO0vqsbvFLXUmYm/uNKJBg=="], + "@parcel/watcher-win32-arm64": ["@parcel/watcher-win32-arm64@2.6.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ=="], - "@parcel/watcher-win32-arm64": ["@parcel/watcher-win32-arm64@2.5.6", "", { "os": "win32", "cpu": "arm64" }, "sha512-3ukyebjc6eGlw9yRt678DxVF7rjXatWiHvTXqphZLvo7aC5NdEgFufVwjFfY51ijYEWpXbqF5jtrK275z52D4Q=="], + "@parcel/watcher-win32-x64": ["@parcel/watcher-win32-x64@2.6.0", "", { "os": "win32", "cpu": "x64" }, "sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A=="], - "@parcel/watcher-win32-ia32": ["@parcel/watcher-win32-ia32@2.5.6", "", { "os": "win32", "cpu": "ia32" }, "sha512-k35yLp1ZMwwee3Ez/pxBi5cf4AoBKYXj00CZ80jUz5h8prpiaQsiRPKQMxoLstNuqe2vR4RNPEAEcjEFzhEz/g=="], + "@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.12", "", { "os": "android", "cpu": "arm" }, "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A=="], - "@parcel/watcher-win32-x64": ["@parcel/watcher-win32-x64@2.5.6", "", { "os": "win32", "cpu": "x64" }, "sha512-hbQlYcCq5dlAX9Qx+kFb0FHue6vbjlf0FrNzSKdYK2APUf7tGfGxQCk2ihEREmbR6ZMc0MVAD5RIX/41gpUzTw=="], + "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.12", "", { "os": "android", "cpu": "arm64" }, "sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg=="], - "@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.6", "", { "os": "android", "cpu": "arm" }, "sha512-b+jTcARdTiFLI6jB4a5XjTm0RWd6KcRfQj/I2356fxUZemiho9zQLxo0RtCuMDAyKcLo6cEltkgbQp6d1+sjjQ=="], + "@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.12", "", { "os": "darwin", "cpu": "arm64" }, "sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w=="], - "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.6", "", { "os": "android", "cpu": "arm64" }, "sha512-lkWU8ZJaRk9q3CIEY1Tc7vIFALp3Xw5NfGJo2hQg5oIqNgxWi1zI+IiDEK3r70BF5Dzol1tcXsnzsRc8NLhG+Q=="], + "@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.12", "", { "os": "darwin", "cpu": "x64" }, "sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA=="], - "@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.6", "", { "os": "darwin", "cpu": "arm64" }, "sha512-dgR56NYnvAszm7Ob1B2/Vn0e8bUQYZH2UjVaMMtMVOCKFSfjhfLmuA/9+O+F+ajUdG6B/bSssrKW6JJYASa8jA=="], + "@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.12", "", { "os": "freebsd", "cpu": "x64" }, "sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ=="], - "@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.6", "", { "os": "darwin", "cpu": "x64" }, "sha512-vpVxFvUCFioJqug7OTvqptkc4yb8UX0AwfDmJpaR/0sWz+BUmqSVAf7c8JkUgnN8YLspb4a/N6NhTyMAmdyQ7Q=="], + "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.12", "", { "os": "linux", "cpu": "arm" }, "sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g=="], - "@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.6", "", { "os": "freebsd", "cpu": "x64" }, "sha512-h1wG6Y6K3JlRswxsI64qQJqBAy4vrLuHgRbc8CZMGSWTOFRY6ghMApM1NKzB2I0n5xV1fjkE18SuVl2QpLeNpA=="], + "@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw=="], - "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.6", "", { "os": "linux", "cpu": "arm" }, "sha512-tbCiqub0q2MVWJKgF5PoAlNWCtQydiOYSLIkd8sByqK/6MMYLJRcSXSYodqYtd0O+Fw7QaVmKKlS4oL94YRZ0w=="], + "@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw=="], - "@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.6", "", { "os": "linux", "cpu": "arm64" }, "sha512-oxK9+baEBPhZG5HB4URY+uU04zJWeZlH6Tb9rB5DK4DF9XR1uXNLXt5Q5ZsugTKayNCNLhkcwz/ye74hRI98dg=="], + "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.12", "", { "os": "linux", "cpu": "ppc64" }, "sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ=="], - "@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.6", "", { "os": "linux", "cpu": "arm64" }, "sha512-muWCk27FVBEZtv0MsK8gnfSmgczA8KQ0uRVJbTABKhkRfQc38aUrcb7fhi3BNiyseFmgcRsoMfQsSNJ+DbZdSw=="], + "@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.12", "", { "os": "linux", "cpu": "s390x" }, "sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw=="], - "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.6", "", { "os": "linux", "cpu": "ppc64" }, "sha512-eWDoSfU7Co2qj3vgB3Dt4lj1mG6CoWbcJQkRMP3XJplyCMtuaq3LHvPFjS9QIPvMGWVadJC04Xiy0IdcVPtnwQ=="], + "@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.12", "", { "os": "linux", "cpu": "x64" }, "sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw=="], - "@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.6", "", { "os": "linux", "cpu": "s390x" }, "sha512-2bWNjRSIayvupRKxXUY2tWG9fYdoUlTqWywHRvE8Eq3GvuQ+f2HeIkve697fIt+IQs/PV8yFsdWuhp1aJ1PdnA=="], + "@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.12", "", { "os": "linux", "cpu": "x64" }, "sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g=="], - "@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.6", "", { "os": "linux", "cpu": "x64" }, "sha512-KekI0gS0wLxe1UBSQSjenBVwou/JkcQPDzBPICGZjxUv9k3RteHDPBQaiOicZUFKRIH2wKEimGwVpnJsbPzu7w=="], + "@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.12", "", { "os": "none", "cpu": "arm64" }, "sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA=="], - "@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.6", "", { "os": "linux", "cpu": "x64" }, "sha512-TvtPnfVr+HtyGiDmPK4VWmlNm7QhNNAcK5Q9A7aOXsI8545yCyaoMaicXrFZ72JzeYjaUVk7yT243zT0jzjFKQ=="], + "@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.12", "", { "os": "win32", "cpu": "arm64" }, "sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew=="], - "@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.6", "", { "os": "none", "cpu": "arm64" }, "sha512-iOo0VEay2XFhaCcH0sps5XIimkSuOnNaZrf6+ZkoSOQBJPKNU48RkmJv0/lSpipexu5P+ouFgafe5IGr/DiQfg=="], - - "@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.6", "", { "os": "win32", "cpu": "arm64" }, "sha512-y5NTmmasMS455JlOCO4ZM9krIchv3Mvm1crL1iUPGOPgEzSkves9n0SdC5Sjz6+qWDFhd8/JpfWMH8NSWNHe+A=="], - - "@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.6", "", { "os": "win32", "cpu": "x64" }, "sha512-np8iZSLfXlAD4kWhiyq/u0Yt8oZDtRQ8lGhQaCXo2rl37KNjeU0GjJuwr4P3oeZ++ROfofsKNBqR5LTO8aXyWQ=="], + "@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.12", "", { "os": "win32", "cpu": "x64" }, "sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ=="], "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="], - "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.63.3", "", { "os": "android", "cpu": "arm" }, "sha512-w3Jnvi1ocaVm/c7yVPpfB98XeSRBMyzp6njL5MVVbGyXjpmUkN+s6Hp4t0PqhGCCaI1ZHMKXt/w0lA1RCaLVcw=="], - - "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.63.3", "", { "os": "android", "cpu": "arm64" }, "sha512-uI/ESiaIbbRYAEhzy8PCUWDp1hB0bjAqM06mW9flOoNO4Q8DQpeoREhBR5Hegfl+wpXiguyJv6XSPzEN7OxyHQ=="], - - "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.63.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-oxhrd1jmXLwWZ83eQYDXxuqRdkqkzrjR3JobKeuUyfdNZo11FuQIvqEOZhyIT7OBHxXoGslDDjN0cQcM6T0TqQ=="], - - "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.63.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-7/YiIMghVE8DrxKvNdorAaJVdriOFgOIpdStnPx8ppx5zfTwC3jBCSEAIzB7JD5404m65THl6H93UTTVUvypmg=="], + "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.64.0", "", { "os": "android", "cpu": "arm" }, "sha512-FLLpX941CD/7aBvX3GqLGBM9OvY5PGXTryPJkG5r5/OuBpZpV5k45Uo3RxAvqd35tsyc3hH1bhtz921IKzoIzg=="], - "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.63.3", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-GXFZRRoMAytaI5z6N3Zhfw0WL18Q0M8r95D5hlC4GqE/lGk8pbSJNUBoOWDfbm6dTciqHj2nU87tI5f6XhQiOg=="], + "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.64.0", "", { "os": "android", "cpu": "arm64" }, "sha512-iI32XM/jnDYJsvx5ai/za/7gWO9XoSeFFtU06/ZCaRgyilfJOjaopD3nOpk2WrTCGOyeDt4hleUiGOAnd5tHNg=="], - "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.63.3", "", { "os": "freebsd", "cpu": "x64" }, "sha512-77W+8X3ddYgPxUpB8nZFQs2Mq+wc4HVlcSRtApXLjYBcnPMkttrSnU8VwKQjeWYhMsITHFs5cWBQ8vz1Q+5RHQ=="], + "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.64.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-dRBZlbt2sEtF8Mn4MODThze9fIPdDoOhVSlXMAKy5dQbOYK9pOOoPY4Fat3OTtr0+8zbJo5TTZwlsfxY/kDNJg=="], - "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.63.3", "", { "os": "linux", "cpu": "arm" }, "sha512-FVkwK+iUC+mq+GipVK46rRVticfAPtvPUNlqlGXUDxdVk/UGjQiiiUVPUrEXdSpU2ufU0XxLGyTqDtBidDOVmg=="], + "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.64.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Y3whrJOMucfkhgNkvcM93M6j8C53iEAMmPMYD99C6G1kUy4ELigLWk9ar2/4aCBSRgsql0zdlOemLgW2m5GZgQ=="], - "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.63.3", "", { "os": "linux", "cpu": "arm" }, "sha512-+aGU1t3398yQOVj1Bz8o3e+KtswxAPvO+mtxtNdfXYMkXIHu7XhhkCD7/DEH9q8tF8uhDnMWvfpUKI8y1sZJsg=="], + "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.64.0", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-S6S1GEzPjFF6IONYJX3AKt/799+8RgBgCcwRnUo+Ep1IvBxUbw5M51iU0TDdK2NWWVnSvCQ8yi6Em0fGASMOng=="], - "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.63.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-cR0kjpRXR2KJ2oQK8E2KTPtphs+b9hZ8IhTZubNryt/RsqgdOZBQ2Zq0q5UedtiIi0rs3jVhJh55RE1ZHUVGUA=="], + "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.64.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-Ed1DPoFENkXj4IGzSB12SesV40iP6LxCCrbTIkSGIQBpOOxpBM+0kj62lmaeIHfMWTDoddqTOtqc7s8LYfn+Pw=="], - "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.63.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-y1RYi4Q3/9ByVWSSt9kX2ustE0B7kFYbJ6zZdVZVyqopZs3yhCTwRfrjIX4vezUJInma/Gs6BOFDJg7yZmJ0IQ=="], + "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.64.0", "", { "os": "linux", "cpu": "arm" }, "sha512-J/6xhutJPtFyIkmHdf4olOdHHKH5kOJNumojdWn+Elv5ICEYTVOa362Vw27TxsK0BLzb1le3EDlO3UbvFK1lnQ=="], - "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.63.3", "", { "os": "linux", "cpu": "none" }, "sha512-DNhEA5viIj3Z5bZLE4z4oV8N5ozWqDwyt7T6KG7VdLDJ0nW+rNOYlphBl4/3HQkK75qipPLsVOfStHHOwN9WSg=="], + "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.64.0", "", { "os": "linux", "cpu": "arm" }, "sha512-G4L/Nnx59d2LvDoV/P4S5lZ7oVLT6hodOHMacqjiq2LL2gts86KbkEBTYL53+fBt0odhf7XPIbIATGoYiJctxg=="], - "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.63.3", "", { "os": "linux", "cpu": "none" }, "sha512-17gQCqrIpXBX2Cmi9/TygnVOqGbzsba/iaqcYSL8FY7lNugg+7AiYNs5c5nKWD+NRQha36Sa0CqkJqH4XVHwnQ=="], + "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.64.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-zF16pvJDEUksGYRbfnXne7pdklAyj2XDmJeYKgP93oq0cUyX9Y8O7lUo1R+IY1GagP/YBvCEDCe7eEcAKpw//g=="], - "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.63.3", "", { "os": "linux", "cpu": "ppc64" }, "sha512-6LwVnZRIyINpdku/yOcI8Tm9YqLmhHK5emmlOOnW9tO0SYEm1FmKPcsSAGp0NBlqR2P04xaND4jvN6sTHqhq8A=="], + "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.64.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-nIggWn8n+w12+R5lsV+PYYoUY8vuObxPAQqJI7WES+9v0qspYuAHoZMfYM0yLxlipasT5BY9ht5W8t5c/rSCkg=="], - "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.63.3", "", { "os": "linux", "cpu": "ppc64" }, "sha512-xMUqkTXlEUtI/p5AAukMwBRr1enU3efsTeF+bskeFfk8t1C9rcC8sLREcZXmTfAXEbvRdJVSonVJez3TMlbR3w=="], + "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.64.0", "", { "os": "linux", "cpu": "none" }, "sha512-WLOTiHPzszP0dxIMsHpFeDSOSB5I49Mj8K4+yKE3H1X/D0JRG5XZ5jrctJLMjnUc/LUzaKiwq6EHWNJ8pup8PA=="], - "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.63.3", "", { "os": "linux", "cpu": "none" }, "sha512-S3E94co9F9WRRqEaUoQZ38K1gCz6KiM+nL7/3ijq7fDGF3OznjS5TasgYITlvl27GQKtu4lOAOsr5MFwkijvOA=="], + "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.64.0", "", { "os": "linux", "cpu": "none" }, "sha512-35RK9aRhh7g7Pmeu5gQ01aCvrhXzj9LoBE6xtUcEH1ns+nyTaSzxSpADmBQINu4QiTDGvmQYwo1j5hlg1rRXFw=="], - "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.63.3", "", { "os": "linux", "cpu": "none" }, "sha512-1QtRDwG42x5BJI3s9mxu5rEjDnfbSnk20HQ9/ylTAYnSwYwxMVb+Vgu34wzzTQ7ogqBybebgQNUDAvZVQ38DbA=="], + "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.64.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-RqTfnpoTjuWfPAmqK5p2edt2AMCDJWm6oTn7sKfmyx+6tRga0ip05SJ977o6udTcIiDeF/CJMUfkaN4gtWt6Aw=="], - "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.63.3", "", { "os": "linux", "cpu": "s390x" }, "sha512-BQhejF6ZXOpxbngiNTP12GCGQeaDVL2QXGeBVViKIYzFHM5RKxTxwUMB1fr1BeNFphFMpnRqC5QSXFSa4z6UQw=="], + "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.64.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-RQjZPigjxFvFZDijG6rjlSXxhRaTf9zLYVpGK+lVcga64oMqP1GbgVqCb46eHTTceSIgp89Ja0y5aPe3GFBYHg=="], - "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.63.3", "", { "os": "linux", "cpu": "x64" }, "sha512-SXagRwnI2Wlwlitllu59UK/nGVbD1CKPcNqDplHwIC4BqJcpXFjD32d1R/RbuISa95HdQrZM3/7v4bKiowFaLA=="], + "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.64.0", "", { "os": "linux", "cpu": "none" }, "sha512-tjL58mgQcTRnDRpeky+Sth1MKQeYi2Ct6r3Luq9E5aTSjnM/i/JbozqZkKqp9thM5+oDSZxo+05f9kdQedfTGA=="], - "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.63.3", "", { "os": "linux", "cpu": "x64" }, "sha512-2IPozoEALRCziGqE8O9KMK60PMu5TS1huv4fwoeCexj+WjmcwFtX9CTOVbfXCUqcELAubEwRFPYlzb/WvwY2HQ=="], + "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.64.0", "", { "os": "linux", "cpu": "none" }, "sha512-ictoRyVaoZ8C67myHef+8hhCa6IplXJJ/xUCkVCxziV4zxMZh+jvhkhGsPBLqj1S72fnqD0QH5zL4lcaa4X7DQ=="], - "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.63.3", "", { "os": "openbsd", "cpu": "x64" }, "sha512-AoxqosUHT9IX54hFn2TiN6A7d6ZKTtE6pd2bqWtqkkNJ6HJGaU6FRouGX8L1O7R/ZwsnCnpQrHzb4pDEx+UHRQ=="], + "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.64.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-8aVvZ2hfr9RLFzBQkQNmYeHLDja8fLeQAmLt757zdKN/B+8L809KlLJKctQjS22wZotptV8G6o7fVPuAs8S1tQ=="], - "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.63.3", "", { "os": "none", "cpu": "arm64" }, "sha512-d+CaftKgmkFBzCwezMqqy1d0QNNYugqLCMcYVQWBy5SS2YfeMP8Q8ripkgx9O8IyBXXLHrJ+aaCV4U96usv6Yg=="], + "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.64.0", "", { "os": "linux", "cpu": "x64" }, "sha512-2dEF8GAcDKwshUfydD+GhosppNyBzhVUHkdFF3CXd3FpOkzj/RZzF5aoEtzklujklT5qFVRU2GK/cFeLaTNKVg=="], - "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.63.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-xXlDF6nR1eOuXbdDy5Hl5fmtY7teUDevF/k0O7IPoZe4Tpmdv+lgdE5JRsnhQtt37ql9P0VF2kAN9a0OCZdo+Q=="], + "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.64.0", "", { "os": "linux", "cpu": "x64" }, "sha512-3XHTvoo2hKkh0MiOfS7SkhHjMaaWF7P4F3drocZZaho/Z8w7h/jpnuBHm91BOQLfvrKHs1yR+zir4E8RI3XzTQ=="], - "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.63.3", "", { "os": "win32", "cpu": "ia32" }, "sha512-YtXAgLN+JP7Ay6qG3eWhc7IHMQPzLc8r3uvhAvlJIoCz/4Q32+Bl9Fmnywidh8v1GOIMmymjovfqY9ETAtysvA=="], + "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.64.0", "", { "os": "openbsd", "cpu": "x64" }, "sha512-HKtkzodL4a3KFWDXDoO61cRynAWTR3LnAE0oGtfG9lcNFpNuVYUFOByxDgNqEvic9rvaQbAj+SFwTEWDptRaIw=="], - "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.63.3", "", { "os": "win32", "cpu": "x64" }, "sha512-WuWtSJRNo549vzcfZyEgfqb6zeSgn1F+UE5kQ+BCjzz0W4MGCjntUHkZVc1VRuAM7+ULaSyhiPxD1spyewFvkQ=="], + "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.64.0", "", { "os": "none", "cpu": "arm64" }, "sha512-JBsxqiY16uyyCujtoC3s7zL+SrYyNElptD7K4V+KUoJ2V8/XG3hPWpheK+SuPwNh1cikJvIZmIdsrYXvD6PLJw=="], - "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.63.3", "", { "os": "win32", "cpu": "x64" }, "sha512-+lIKX7O0+IGe7WuhATaAMMeT7B76vfhXH/l9wLQL+nvyhbw2ohYCKIdWL56JfDu75CWt5oKRP4QFH/jkMtBquA=="], + "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.64.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-S5Qrijh37qhnUYQ0ay8WN3LuWeKjow7wTUyCOPMZtnXiBXYXdsZETI6ZLfYnQAKovltckPLBFdNeD61P2rJc7g=="], - "@rspack/binding": ["@rspack/binding@2.2.0", "", { "optionalDependencies": { "@rspack/binding-darwin-arm64": "2.2.0", "@rspack/binding-darwin-x64": "2.2.0", "@rspack/binding-linux-arm64-gnu": "2.2.0", "@rspack/binding-linux-arm64-musl": "2.2.0", "@rspack/binding-linux-ppc64-gnu": "2.2.0", "@rspack/binding-linux-riscv64-gnu": "2.2.0", "@rspack/binding-linux-riscv64-musl": "2.2.0", "@rspack/binding-linux-s390x-gnu": "2.2.0", "@rspack/binding-linux-x64-gnu": "2.2.0", "@rspack/binding-linux-x64-musl": "2.2.0", "@rspack/binding-wasm32-wasi": "2.2.0", "@rspack/binding-win32-arm64-msvc": "2.2.0", "@rspack/binding-win32-ia32-msvc": "2.2.0", "@rspack/binding-win32-x64-msvc": "2.2.0" } }, "sha512-nxZzJqqB0EmEKp6qjzFNkBb/SgGt0k0DSENrLvAJgvVvrm3waVsubD0cfxtPlZY/rd5SzadzxWGEHRyFcds5nA=="], + "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.64.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-zbZ6iMmLFEsCtTdc2/y1F/cDFVNNCPF7Ae8PCT/wdPE//hGwYp6r+MyCLMFX+kOeIe09Pz6ASfnnfpSTN1FJQQ=="], - "@rspack/binding-darwin-arm64": ["@rspack/binding-darwin-arm64@2.2.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-KAVVT7hp3NBjtc/RY2UtOjzzc8i+s4pIhW1p52UV+Aev6ywQCu3dXwkHTonpPvJO3hqLXc4zIMH5l4HbMqBm4g=="], + "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.64.0", "", { "os": "win32", "cpu": "x64" }, "sha512-L6Hw69oNpuYaOr1zCG30v0/DqKYCSRwodPGwIcVZ/6f8SOzq9rxtL/xNVI5MO4wjli+Ko0ErK9uHJL3mNPt8wQ=="], - "@rspack/binding-darwin-x64": ["@rspack/binding-darwin-x64@2.2.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-rzyJCX99aFwl540trsVMNZOgK4+IFm2d5+YeP+RdNo9Uprxloz8vHz0J4dYtaq6MRiCAyM60dAwEa3wJMwqWAQ=="], + "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.64.0", "", { "os": "win32", "cpu": "x64" }, "sha512-nl+CTWIgOGszQmUz/kanfgrfFZ4qiwxKIfT/ryl3N3Ewk5tqizmYtNXiqb7Bu/fDtNgu1kyxdFiAUJNur3iysg=="], - "@rspack/binding-linux-arm64-gnu": ["@rspack/binding-linux-arm64-gnu@2.2.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-0t8QOiOMcBV7RvPSsTJ5DQ4QCK6FIyUZy77qbxnS6asGTOXPZZn7V5cL26IxEv/wuHdQ6tQOXheau1fi+gGyBQ=="], + "@rspack/binding": ["@rspack/binding@2.2.8", "", { "optionalDependencies": { "@rspack/binding-darwin-arm64": "2.2.8", "@rspack/binding-darwin-x64": "2.2.8", "@rspack/binding-linux-arm64-gnu": "2.2.8", "@rspack/binding-linux-arm64-musl": "2.2.8", "@rspack/binding-linux-ppc64-gnu": "2.2.8", "@rspack/binding-linux-riscv64-gnu": "2.2.8", "@rspack/binding-linux-riscv64-musl": "2.2.8", "@rspack/binding-linux-s390x-gnu": "2.2.8", "@rspack/binding-linux-x64-gnu": "2.2.8", "@rspack/binding-linux-x64-musl": "2.2.8", "@rspack/binding-wasm32-wasi": "2.2.8", "@rspack/binding-win32-arm64-msvc": "2.2.8", "@rspack/binding-win32-ia32-msvc": "2.2.8", "@rspack/binding-win32-x64-msvc": "2.2.8" } }, "sha512-c9flkSua3khHnOKBCRk8BkHGOwU9YB7niv+5JfQXiLZIvJmgKsZ7PD8QrFklMhsJT3oVAc6c9GN7/wy1YkACjA=="], - "@rspack/binding-linux-arm64-musl": ["@rspack/binding-linux-arm64-musl@2.2.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-BAvCukqcuHxUdE294ITCohvhVkEklW8RbkKkR36Uo0WyIiMPGrnvPjARPn0/4Q4xMAz7lUmC60sZrvJHlAOKMw=="], + "@rspack/binding-darwin-arm64": ["@rspack/binding-darwin-arm64@2.2.8", "", { "os": "darwin", "cpu": "arm64" }, "sha512-d6GuY/k7kJk7SOXmruIz0m+2fIXaLv2SnBHEYsbvBzE7ZO6QXq7fSABWFWNnSnNu+brYHA5Dr/skV81bXgTTCw=="], - "@rspack/binding-linux-ppc64-gnu": ["@rspack/binding-linux-ppc64-gnu@2.2.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-nCHqZLv/E8nm2ccGkb00F5DQtXxzGy3W3X73ArA+N0+zXJUnzRcSRSwr7AE8pVgP/FYfX4yMFgUXy0g0YxYGRA=="], + "@rspack/binding-darwin-x64": ["@rspack/binding-darwin-x64@2.2.8", "", { "os": "darwin", "cpu": "x64" }, "sha512-xCVou/jJASjEAjwy1T3hPJcJqA5QZASJfUwHqEk+nA0v44MagwH8tM8lsOvRfhzR7N2+YFac1rfZOUT8uM3awg=="], - "@rspack/binding-linux-riscv64-gnu": ["@rspack/binding-linux-riscv64-gnu@2.2.0", "", { "os": "linux", "cpu": "none" }, "sha512-CA3WEqKFDI6FAZTnCho2n9pmdPWZYAW/S8mqgxd0cx2Jix43at3VyLxhCC7ED5A9WBSFn/AdHaIbVtgoQHVhWA=="], + "@rspack/binding-linux-arm64-gnu": ["@rspack/binding-linux-arm64-gnu@2.2.8", "", { "os": "linux", "cpu": "arm64" }, "sha512-Zy/ss6YAQTjOWKDkcWrbKtu+pySltqT22wn68nlrWKygPWLNmMdU5anlsnwRTIuQ3MF0YJRS42ARauVtlqvRQw=="], - "@rspack/binding-linux-riscv64-musl": ["@rspack/binding-linux-riscv64-musl@2.2.0", "", { "os": "linux", "cpu": "none" }, "sha512-kHB960oClkoPRPZ6sdkhRvqbdRIlbpIMYd/Tbxfmn3DWQahiCk1pkUFJbOtFq3EgESxZISV4THl442W2Y57HvQ=="], + "@rspack/binding-linux-arm64-musl": ["@rspack/binding-linux-arm64-musl@2.2.8", "", { "os": "linux", "cpu": "arm64" }, "sha512-lxgp5O8PhL3St9p82llHoNoeWzp9jltW5S9F00p00XPJZHUIuxbwfLSzn/6Wg86USEmafLoBkyD9CM8rBd3SNQ=="], - "@rspack/binding-linux-s390x-gnu": ["@rspack/binding-linux-s390x-gnu@2.2.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-lVBdiffVo1jq0P0jT36jNou2suLB4ueQI4aWUs+HM+h67YPBtVKWu/mo5Wh59+8nowgcZmYaFM5hdH69963I9w=="], + "@rspack/binding-linux-ppc64-gnu": ["@rspack/binding-linux-ppc64-gnu@2.2.8", "", { "os": "linux", "cpu": "ppc64" }, "sha512-MY+YqpT02tcDCMgHy+IewQsaz7ql4mbJaAqqMlTIqvQwAUl9dXEP7BL352OgCxm9VRebTldE5lK99A3wVd3zqA=="], - "@rspack/binding-linux-x64-gnu": ["@rspack/binding-linux-x64-gnu@2.2.0", "", { "os": "linux", "cpu": "x64" }, "sha512-M49UaWspE0YJ3268DsquD8idEQTfjBDMvO/I8qccV/Z5T+Q98FJ+kIs5liUaTWb48OIbDEK+8ZKx5QzLbfVN6g=="], + "@rspack/binding-linux-riscv64-gnu": ["@rspack/binding-linux-riscv64-gnu@2.2.8", "", { "os": "linux", "cpu": "none" }, "sha512-wmN9OigSGNGCKY+AOYaWI8LJcIi8qvs5KjueBueCKOnTV6MPIEujA75QZH1pehTTYKvdGv7r2EtUXUmWpn7/SQ=="], - "@rspack/binding-linux-x64-musl": ["@rspack/binding-linux-x64-musl@2.2.0", "", { "os": "linux", "cpu": "x64" }, "sha512-YYbs0wmey+5blhEQDE4Dax3TwJtqfGwe2QBm3OLphlBHo/fcZVvimzKkMV0/pVrZTLy2z5ZAwNhGMY64bNr77w=="], + "@rspack/binding-linux-riscv64-musl": ["@rspack/binding-linux-riscv64-musl@2.2.8", "", { "os": "linux", "cpu": "none" }, "sha512-ZcQMYR10hLh581zs9MFnFFn0F7wyt5fkDffyukeMHJEoPJrbkfl6cQtsUdpQnZ+mYGYS5KydD1DT9/eMH65jjw=="], - "@rspack/binding-wasm32-wasi": ["@rspack/binding-wasm32-wasi@2.2.0", "", { "dependencies": { "@emnapi/core": "1.11.3", "@emnapi/runtime": "1.11.3", "@napi-rs/wasm-runtime": "1.1.6" }, "cpu": "none" }, "sha512-rerLPTN/HD4EvLNWs3O2N+Eb37eGvLRIP3dXXc3n+UzTebOepAsahNn44vXeRBsE4m/pHkpDJjwgWTytgQ2gBw=="], + "@rspack/binding-linux-s390x-gnu": ["@rspack/binding-linux-s390x-gnu@2.2.8", "", { "os": "linux", "cpu": "s390x" }, "sha512-ahBiE+Ir1FMYvStYicihhSJlS2YRagxtry0jWH8zW287o7C0eiHJ+pteJHHC15T5RJqm0j6w5TuwYe+F9AYxxg=="], - "@rspack/binding-win32-arm64-msvc": ["@rspack/binding-win32-arm64-msvc@2.2.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-JUAmnbOQYGTRyX28vls/MOMonZWcmcCi5YtEq6YMc8Xqh3Qx0HUwaLM/I1xr/N9BX3b8CV0dQDOpNuBc2ei+CA=="], + "@rspack/binding-linux-x64-gnu": ["@rspack/binding-linux-x64-gnu@2.2.8", "", { "os": "linux", "cpu": "x64" }, "sha512-dncEI515NoPXh3zzWk06Rb3mhSV76myiFKqXiJ8K4fVAe5x/RlweMhvPhHhm7RnIMeBld7BeStzOqj38XFsWGA=="], - "@rspack/binding-win32-ia32-msvc": ["@rspack/binding-win32-ia32-msvc@2.2.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-wOmQRUaOG0eWH/fnfslA9yK9xKfaq9X+3Xa1TdTJnTqlo0ARJYs6A+Lzjbs7cxdY/o1f12Xe00BG3nQozReUOg=="], + "@rspack/binding-linux-x64-musl": ["@rspack/binding-linux-x64-musl@2.2.8", "", { "os": "linux", "cpu": "x64" }, "sha512-pfFyU03PjD0GaQG8zOQOHwq51rrJZetXjTGpMmz7iA1hq/f9lChJsDWrC8/7VXeQLwBofLZlOODqe8OM8OBzgA=="], - "@rspack/binding-win32-x64-msvc": ["@rspack/binding-win32-x64-msvc@2.2.0", "", { "os": "win32", "cpu": "x64" }, "sha512-v6/3bFr9+i7hRpgulL9b5qCvZL0VgR4vQGQNqOWezUzZmPUj9LYpvB0L9xZIVwDQ2ug/xBiA58bfg5IbESgoyw=="], + "@rspack/binding-wasm32-wasi": ["@rspack/binding-wasm32-wasi@2.2.8", "", { "dependencies": { "@emnapi/core": "1.11.3", "@emnapi/runtime": "1.11.3", "@napi-rs/wasm-runtime": "1.1.6" }, "cpu": "none" }, "sha512-3mOJuZTrF56jOh/GD9chLMJKbzPZ6Ty2OIML7+lLz0Yk2XS/xWRfLn85Dmnkb/O6UF65x7+p8VPAIZlBtLTclw=="], - "@rspack/cli": ["@rspack/cli@2.2.0", "", { "peerDependencies": { "@rspack/core": "^2.0.0-0", "@rspack/dev-server": "^2.0.0-0" }, "optionalPeers": ["@rspack/dev-server"], "bin": { "rspack": "bin/rspack.js" } }, "sha512-GSiQPG5v5tN8vYJdUMYX44sPiwVVG8H25fq3LWRydVB4WswDAD/N3qNgWZtFVliQdLH3ZWzFdFUoCyZmea0TMA=="], + "@rspack/binding-win32-arm64-msvc": ["@rspack/binding-win32-arm64-msvc@2.2.8", "", { "os": "win32", "cpu": "arm64" }, "sha512-Cu/RMZT/16s+67xhl6X1pswetL3GLSQl+LnugKRh08Ul21A/tR7vxC4g4aih4u9k5SXCAngxFUt8zAjKnHIBqA=="], - "@rspack/core": ["@rspack/core@2.2.0", "", { "dependencies": { "@rspack/binding": "2.2.0" }, "peerDependencies": { "@module-federation/runtime-tools": "^0.24.1 || ^2.0.0", "@swc/helpers": "^0.5.23" }, "optionalPeers": ["@module-federation/runtime-tools", "@swc/helpers"] }, "sha512-3W7oX0BAHbK4VlknH3lfyfRvupzxdZtyEa+DfKmdjzmIAcqYtHnFd0nLqp5dzitDPyDI1TIKkDhpB0AZJn0pVg=="], + "@rspack/binding-win32-ia32-msvc": ["@rspack/binding-win32-ia32-msvc@2.2.8", "", { "os": "win32", "cpu": "ia32" }, "sha512-H/erd6di8OapZhhM0raA/7XduPn9jusfLMeO1XF+AmF9WF3HzHgMjha1j+KwtPgQnaH69w6AhY+G2472VIwQmw=="], - "@sigstore/bundle": ["@sigstore/bundle@4.0.0", "", { "dependencies": { "@sigstore/protobuf-specs": "^0.5.0" } }, "sha512-NwCl5Y0V6Di0NexvkTqdoVfmjTaQwoLM236r89KEojGmq/jMls8S+zb7yOwAPdXvbwfKDlP+lmXgAL4vKSQT+A=="], + "@rspack/binding-win32-x64-msvc": ["@rspack/binding-win32-x64-msvc@2.2.8", "", { "os": "win32", "cpu": "x64" }, "sha512-BziHSUlIQM0MliCqdcHuBXSkQGtPoHQTXJce7fsgnTAzQFgPeog92qTNezYI4IrQ7pQouyiVJ2HPieUbVPRKQQ=="], - "@sigstore/core": ["@sigstore/core@3.2.1", "", {}, "sha512-qRsxPnCrbC/puegGxKuynfnxgLiHqWStrSjxkoB4YKqq3Z3s4cyZyj42ZdWFAEblNP65C+rBH8EuREHIXoi83g=="], + "@rspack/cli": ["@rspack/cli@2.2.8", "", { "peerDependencies": { "@rspack/core": "^2.0.0-0", "@rspack/dev-server": "^2.0.0-0" }, "optionalPeers": ["@rspack/dev-server"], "bin": { "rspack": "bin/rspack.js" } }, "sha512-6f5ITncKnqXUKZVHmD3qHMVZzQz+C07oCdci+eqBwLswA3n9AhNiM0LR4Es1ai528rv5SpiUDUFulziqSEl2Cw=="], - "@sigstore/protobuf-specs": ["@sigstore/protobuf-specs@0.5.1", "", {}, "sha512-/ScWUhhoFasJsSRGTVBwId1loQjjnjAfE4djL6ZhrXRpNCmPTnUKF5Jokd58ILseOMjzET3UrMOtJPS9sYeI0g=="], - - "@sigstore/sign": ["@sigstore/sign@4.1.1", "", { "dependencies": { "@gar/promise-retry": "^1.0.2", "@sigstore/bundle": "^4.0.0", "@sigstore/core": "^3.2.0", "@sigstore/protobuf-specs": "^0.5.0", "make-fetch-happen": "^15.0.4", "proc-log": "^6.1.0" } }, "sha512-Hf4xglukg0XXQ2RiD5vSoLjdPe8OBUPA8XeVjUObheuDcWdYWrnH/BNmxZCzkAy68MzmNCxXLeurJvs6hcP2OQ=="], - - "@sigstore/tuf": ["@sigstore/tuf@4.0.2", "", { "dependencies": { "@sigstore/protobuf-specs": "^0.5.0", "tuf-js": "^4.1.0" } }, "sha512-TCAzTy0xzdP79EnxSjq9KQ3eaR7+FmudLC6eRKknVKZbV7ZNlGLClAAQb/HMNJ5n2OBNk2GT1tEmU0xuPr+SLQ=="], - - "@sigstore/verify": ["@sigstore/verify@3.1.1", "", { "dependencies": { "@sigstore/bundle": "^4.0.0", "@sigstore/core": "^3.2.1", "@sigstore/protobuf-specs": "^0.5.0" } }, "sha512-qv7+G3J2cc6wwFj3yKvXOamzqhMwSk1ogPGmhpS8iXllcPrJaIIBA+4HbttlHVu1pqWTdmaCH/WE7UOC51kdoA=="], + "@rspack/core": ["@rspack/core@2.2.8", "", { "dependencies": { "@rspack/binding": "2.2.8" }, "peerDependencies": { "@module-federation/runtime-tools": "^0.24.1 || ^2.0.0", "@swc/helpers": "^0.5.23" }, "optionalPeers": ["@module-federation/runtime-tools", "@swc/helpers"] }, "sha512-JugsVrnbMGNYzMH++7gR9enygpP/lAo9PbVRq3XmJg0ryIvCpST0XJjBcccaSjYaaPamsjrddihmgVLMFp+yXw=="], "@sphinxxxx/color-conversion": ["@sphinxxxx/color-conversion@2.2.2", "", {}, "sha512-XExJS3cLqgrmNBIP3bBw6+1oQ1ksGjFh0+oClDKFYpCCqx/hlqwWO5KO/S63fzUo67SxI9dMrF0y5T/Ey7h8Zw=="], "@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - "@tufjs/canonical-json": ["@tufjs/canonical-json@2.0.0", "", {}, "sha512-yVtV8zsdo8qFHe+/3kw81dSLyF7D576A5cCFCi4X7B39tWT7SekaEFUnvnWJHz+9qO7qJTah1JbrDjWKqFtdWA=="], - - "@tufjs/models": ["@tufjs/models@4.1.0", "", { "dependencies": { "@tufjs/canonical-json": "2.0.0", "minimatch": "^10.1.1" } }, "sha512-Y8cK9aggNRsqJVaKUlEYs4s7CvQ1b1ta2DVPyAimb0I2qhzjNk+A+mxvll/klL0RlfuIUei8BF7YWiua4kQqww=="], - - "@tybys/wasm-util": ["@tybys/wasm-util@0.10.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg=="], + "@tybys/wasm-util": ["@tybys/wasm-util@0.10.4", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A=="], "@types/ace": ["@types/ace@0.0.52", "", {}, "sha512-YPF9S7fzpuyrxru+sG/rrTpZkC6gpHBPF14W3x70kqVOD+ks6jkYLapk4yceh36xej7K4HYxcyz9ZDQ2lTvwgQ=="], "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], - "@types/cordova": ["@types/cordova@11.0.3", "", {}, "sha512-kyuRQ40/NWQVhqGIHq78Ehu2Bf9Mlg0LhmSmis6ZFJK7z933FRfYi8tHe/k/0fB+PGfCf95rJC6TO7dopaFvAg=="], - "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], "@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], @@ -744,7 +659,7 @@ "@types/mocha": ["@types/mocha@9.1.1", "", {}, "sha512-Z61JK7DKDtdKTWwLeElSEBcWGRLY8g95ic5FoQqI9CMx0ns/Ghep3B4DfcEimiKMvtamNVULVNKEsiwV3aQmXw=="], - "@types/node": ["@types/node@26.1.2", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg=="], + "@types/node": ["@types/node@26.6.4", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-ldVPDCzj7fsaGZrLB0NuHuTvJcsNasysBAqMolr/cgxrLd1xbqxIr3XJiPnHHJUCxj5sNF1vnRj9aWnrVh5Jcg=="], "@types/trusted-types": ["@types/trusted-types@2.0.7", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="], @@ -752,12 +667,10 @@ "@types/whatwg-mimetype": ["@types/whatwg-mimetype@3.0.2", "", {}, "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="], - "@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="], + "@types/ws": ["@types/ws@8.18.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w=="], "@ungap/custom-elements": ["@ungap/custom-elements@1.3.0", "", {}, "sha512-f4q/s76+8nOy+fhrNHyetuoPDR01lmlZB5czfCG+OOnBw/Wf+x48DcCDPmMQY7oL8xYFL8qfenMoiS8DUkKBUw=="], - "@ungap/promise-all-settled": ["@ungap/promise-all-settled@1.1.2", "", {}, "sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q=="], - "@vitest/expect": ["@vitest/expect@4.1.11", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw=="], "@vitest/mocker": ["@vitest/mocker@4.1.11", "", { "dependencies": { "@vitest/spy": "4.1.11", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw"] }, "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ=="], @@ -804,8 +717,6 @@ "@webassemblyjs/wast-printer": ["@webassemblyjs/wast-printer@1.14.1", "", { "dependencies": { "@webassemblyjs/ast": "1.14.1", "@xtuc/long": "4.2.2" } }, "sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw=="], - "@xmldom/xmldom": ["@xmldom/xmldom@0.9.10", "", {}, "sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw=="], - "@xterm/addon-attach": ["@xterm/addon-attach@0.12.0", "", {}, "sha512-1lxvXM4JYSm60lbFmE8WMOy2oF2ip3Ye8jWorSAmwy7x8FiC53netEJ5RguL8+FSRj79MUQsNCb2hprY2QA2ig=="], "@xterm/addon-fit": ["@xterm/addon-fit@0.11.0", "", {}, "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g=="], @@ -826,27 +737,19 @@ "@xtuc/long": ["@xtuc/long@4.2.2", "", {}, "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ=="], - "abbrev": ["abbrev@4.0.0", "", {}, "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA=="], - "acorn": ["acorn@8.18.0", "", { "bin": "bin/acorn" }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="], "acorn-walk": ["acorn-walk@8.3.5", "", { "dependencies": { "acorn": "^8.11.0" } }, "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw=="], - "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], - "ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], - "ajv-formats": ["ajv-formats@2.1.1", "", { "dependencies": { "ajv": "^8.0.0" }, "peerDependencies": { "ajv": "^8.0.0" } }, "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA=="], + "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" }, "peerDependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], "ajv-keywords": ["ajv-keywords@5.1.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3" }, "peerDependencies": { "ajv": "^8.8.2" } }, "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw=="], - "android-versions": ["android-versions@2.2.1", "", { "dependencies": { "semver": "^7.5.2" } }, "sha512-FSSdICv/djaE7TuMpv6IWjbv2JwZxJJVQUGz0/9omi1cmdjrKC8tBFo8BZrUFMzZpGien0zQ6KGc4LtC+AC8jA=="], + "ansi-colors": ["ansi-colors@4.1.3", "", {}, "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw=="], - "ansi": ["ansi@0.3.1", "", {}, "sha512-iFY7JCgHbepc0b82yLaw4IMortylNb6wG4kL+4R0C3iv6i+RHGHux/yUX5BTiRvSX/shMnngjR1YyNMnXEFh5A=="], - - "ansi-colors": ["ansi-colors@4.1.1", "", {}, "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA=="], - - "ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + "ansi-regex": ["ansi-regex@6.4.0", "", {}, "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw=="], "ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], @@ -854,13 +757,9 @@ "argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], - "array-union": ["array-union@2.1.0", "", {}, "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw=="], - - "assert-plus": ["assert-plus@1.0.0", "", {}, "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw=="], - - "assertion-error": ["assertion-error@1.1.0", "", {}, "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw=="], + "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], - "autoprefixer": ["autoprefixer@10.5.4", "", { "dependencies": { "browserslist": "^4.28.6", "caniuse-lite": "^1.0.30001806", "fraction.js": "^5.3.4", "picocolors": "^1.1.1", "postcss-value-parser": "^4.2.0" }, "peerDependencies": { "postcss": "^8.1.0" }, "bin": "bin/autoprefixer" }, "sha512-MaU0U/za7N3r6brxD4YB/l4NSrFzLPlANv6wEuQVaIPlD3L4W9rFcQPbL/EilY9BHhHvhfcz3gInDLrEtWT4EA=="], + "autoprefixer": ["autoprefixer@10.6.1", "", { "dependencies": { "browserslist": "^4.28.9", "caniuse-lite": "^1.0.30001810", "fraction.js": "^5.3.4", "picocolors": "^1.1.1", "postcss-value-parser": "^4.2.0" }, "peerDependencies": { "postcss": "^8.1.0" }, "bin": "bin/autoprefixer" }, "sha512-cL1Qz6ADZhcEbny/8HPfe99J6HhNoYtpX2LFLIbhgGE7Q1hlQVkYFdetDN7Id3KiQxhDrHwzlHr/YQCnZ8+xSA=="], "autosize": ["autosize@6.0.1", "", {}, "sha512-f86EjiUKE6Xvczc4ioP1JBlWG7FKrE13qe/DxBCpe8GCipCq2nFw73aO8QEBKHfSbYGDN5eB9jXWKen7tspDqQ=="], @@ -870,197 +769,85 @@ "balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], - "base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="], - - "baseline-browser-mapping": ["baseline-browser-mapping@2.11.19", "", { "bin": "dist/cli.cjs" }, "sha512-Grytf1xOxOEMTGRwx6rLGKkTabd4vMg3VrKdj/7joCmV0qgh4QwMMO6xh34YEXQqirAuUdgQGa5orJQQ+69RBw=="], - - "big-integer": ["big-integer@1.6.52", "", {}, "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg=="], + "baseline-browser-mapping": ["baseline-browser-mapping@2.11.27", "", { "bin": "dist/cli.cjs" }, "sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ=="], "big.js": ["big.js@5.2.2", "", {}, "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ=="], - "bin-links": ["bin-links@6.0.0", "", { "dependencies": { "cmd-shim": "^8.0.0", "npm-normalize-package-bin": "^5.0.0", "proc-log": "^6.0.0", "read-cmd-shim": "^6.0.0", "write-file-atomic": "^7.0.0" } }, "sha512-X4CiKlcV2GjnCMwnKAfbVWpHa++65th9TuzAEYtZoATiOE2DQKhSp4CJlyLoTqdhBKlXjpXjCTYPNNFS33Fi6w=="], - "binary-extensions": ["binary-extensions@2.3.0", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="], - "bplist-parser": ["bplist-parser@0.3.2", "", { "dependencies": { "big-integer": "1.6.x" } }, "sha512-apC2+fspHGI3mMKj+dGevkGo/tCqVB8jMb6i+OX+E29p0Iposz07fABkRIfVUPNd5A5VbuOz1bZbnmkKLYF+wQ=="], - - "brace-expansion": ["brace-expansion@1.1.15", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg=="], + "brace-expansion": ["brace-expansion@2.1.7", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g=="], "braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="], "browser-stdout": ["browser-stdout@1.3.1", "", {}, "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw=="], - "browserslist": ["browserslist@4.28.8", "", { "dependencies": { "baseline-browser-mapping": "^2.11.12", "caniuse-lite": "^1.0.30001809", "electron-to-chromium": "^1.5.402", "node-releases": "^2.0.53", "update-browserslist-db": "^1.3.0" }, "bin": "cli.js" }, "sha512-V2NpofLblG64mfOtSgDhOJESZEGogzDMBv/q+W6oc4LXWP/q75eOXoOaaOu1EOadB9U4Bwx/e0yzbvwKH8zalA=="], + "browserslist": ["browserslist@4.29.3", "", { "dependencies": { "baseline-browser-mapping": "^2.11.26", "caniuse-lite": "^1.0.30001813", "electron-to-chromium": "^1.5.439", "node-releases": "^2.0.57", "update-browserslist-db": "^1.3.3" }, "bin": "cli.js" }, "sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA=="], "buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="], "buffer-image-size": ["buffer-image-size@0.6.4", "", { "dependencies": { "@types/node": "*" } }, "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ=="], - "cacache": ["cacache@20.0.4", "", { "dependencies": { "@npmcli/fs": "^5.0.0", "fs-minipass": "^3.0.0", "glob": "^13.0.0", "lru-cache": "^11.1.0", "minipass": "^7.0.3", "minipass-collect": "^2.0.1", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "p-map": "^7.0.2", "ssri": "^13.0.0" } }, "sha512-M3Lab8NPYlZU2exsL3bMVvMrMqgwCnMWfdZbK28bn3pK6APT/Te/I8hjRPNu1uwORY9a1eEQoifXbKPQMfMTOA=="], - "callsites": ["callsites@3.1.0", "", {}, "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ=="], "camelcase": ["camelcase@6.3.0", "", {}, "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA=="], - "caniuse-lite": ["caniuse-lite@1.0.30001810", "", {}, "sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg=="], + "caniuse-lite": ["caniuse-lite@1.0.30001814", "", {}, "sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA=="], - "chai": ["chai@4.3.6", "", { "dependencies": { "assertion-error": "^1.1.0", "check-error": "^1.0.2", "deep-eql": "^3.0.1", "get-func-name": "^2.0.0", "loupe": "^2.3.1", "pathval": "^1.1.1", "type-detect": "^4.0.5" } }, "sha512-bbcp3YfHCUzMOvKqsztczerVgBKSsEijCySNlHHbX3VG1nskvqjz5Rfso1gGwD6w6oOV3eI60pKuMOV5MV7p3Q=="], + "chai": ["chai@6.3.0", "", {}, "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg=="], "chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], - "check-error": ["check-error@1.0.3", "", { "dependencies": { "get-func-name": "^2.0.2" } }, "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg=="], - "chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], - "chownr": ["chownr@3.0.0", "", {}, "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g=="], - "chrome-trace-event": ["chrome-trace-event@1.0.4", "", {}, "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ=="], - "cli": ["cli@1.0.1", "", { "dependencies": { "exit": "0.1.2", "glob": "^7.1.1" } }, "sha512-41U72MB56TfUMGndAKK8vJ78eooOD4Z5NOL4xEfjc0c23s+6EYKXlXsmACBVclLP1yOfWCgEganVzddVrSNoTg=="], - "cliui": ["cliui@9.0.1", "", { "dependencies": { "string-width": "^7.2.0", "strip-ansi": "^7.1.0", "wrap-ansi": "^9.0.0" } }, "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w=="], - "cmd-shim": ["cmd-shim@8.0.0", "", {}, "sha512-Jk/BK6NCapZ58BKUxlSI+ouKRbjH1NLZCgJkYoab+vEHUY3f6OzpNBN9u7HFSv9J6TRDGs4PLOHezoKGaFRSCA=="], - "codemirror": ["codemirror@6.0.2", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/commands": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/lint": "^6.0.0", "@codemirror/search": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0" } }, "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw=="], "color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], "color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], - "colors": ["colors@1.4.0", "", {}, "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA=="], - - "com.foxdebug.acode.rk.auth": ["com.foxdebug.acode.rk.auth@file:src/plugins/auth", {}], - - "com.foxdebug.acode.rk.customtabs": ["com.foxdebug.acode.rk.customtabs@file:src/plugins/custom-tabs", {}], - - "com.foxdebug.acode.rk.exec.proot": ["com.foxdebug.acode.rk.exec.proot@file:src/plugins/proot", {}], - - "com.foxdebug.acode.rk.exec.terminal": ["com.foxdebug.acode.rk.exec.terminal@file:src/plugins/terminal", {}], - - "com.foxdebug.acode.rk.plugin.plugincontext": ["com.foxdebug.acode.rk.plugin.plugincontext@file:src/plugins/pluginContext", {}], - - "commander": ["commander@8.3.0", "", {}, "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww=="], - - "common-ancestor-path": ["common-ancestor-path@2.0.0", "", {}, "sha512-dnN3ibLeoRf2HNC+OlCiNc5d2zxbLJXOtiZUudNFSXZrNSydxcCsSpRzXwfu7BBWCIfHPw+xTayeBvJCP/D8Ng=="], - - "concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="], - - "configstore": ["configstore@5.0.1", "", { "dependencies": { "dot-prop": "^5.2.0", "graceful-fs": "^4.1.2", "make-dir": "^3.0.0", "unique-string": "^2.0.0", "write-file-atomic": "^3.0.0", "xdg-basedir": "^4.0.0" } }, "sha512-aMKprgk5YhBNyH25hj8wGt2+D52Sw1DRRIzqBwLp2Ya9mFmY8KPvvtvmna8SxVR9JMZ4kzMD68N22vlaRpkeFA=="], - - "console-browserify": ["console-browserify@1.1.0", "", { "dependencies": { "date-now": "^0.1.4" } }, "sha512-duS7VP5pvfsNLDvL1O4VOEbw37AI3A4ZUQYemvDlnpGrNu9tprR7BYWpDYwC0Xia0Zxz5ZupdiIrUp0GH1aXfg=="], + "commander": ["commander@15.0.0", "", {}, "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg=="], "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], - "cordova": ["cordova@13.0.0", "", { "dependencies": { "configstore": "^5.0.1", "cordova-common": "^6.0.0", "cordova-create": "^6.0.0", "cordova-lib": "^13.0.0", "editor": "^1.0.0", "execa": "^5.1.1", "nopt": "^9.0.0", "semver": "^7.7.3", "systeminformation": "^5.27.11" }, "bin": "bin/cordova" }, "sha512-QAIMwmYLL0jHo4vauWSnRd2fr9l+wajG+F5aUkrC6e4ZQGSTv0wAiRmpqQUkIc1ZdELisKDQws/BjHz5nP/sLw=="], - - "cordova-android": ["cordova-android@15.1.0", "", { "dependencies": { "android-versions": "^2.1.1", "cordova-common": "^6.0.0", "dedent": "^1.7.1", "execa": "^5.1.1", "fast-glob": "^3.3.3", "is-path-inside": "^3.0.3", "nopt": "^9.0.0", "properties-parser": "^0.6.0", "semver": "^7.7.4", "string-argv": "^0.3.2", "untildify": "^4.0.0", "which": "^6.0.1" } }, "sha512-mnOnOisYUVhyrLCPVlHJBKh4ro+X6nZA7nPqBrpVnyTpiiDiakNCfbBJjSs1MTBUJZ6dcmhhvNKZWPT9w6aGPA=="], - - "cordova-app-hello-world": ["cordova-app-hello-world@7.0.0", "", {}, "sha512-uDTncFkI73ko+wEf6IEO9bw8lQRMQGnfdi5pPMei4P8+plChNcRW5fxjKlhM/8ZrT8OAWiHsQRrP4pIAn3HQ4g=="], - - "cordova-clipboard": ["cordova-clipboard@1.3.0", "", {}, "sha512-IGk4LZm/DJ0Xk/jgakHm4wa+A/lrRP3QfzMAHDG7oWLJS4ISOpfI32Wez4ndnENItRslGyBVyJyKD83CxELCAw=="], - - "cordova-common": ["cordova-common@6.0.0", "", { "dependencies": { "@netflix/nerror": "^1.1.3", "ansi": "^0.3.1", "bplist-parser": "^0.3.2", "elementtree": "^0.1.7", "endent": "^2.1.0", "fast-glob": "^3.3.3", "plist": "^3.1.0" } }, "sha512-16WPC1DuxVdshV3RoQUXqhcJVdhxWGwiFysA4TkYuboqoev6mgt0JuIJFxmQbzR/DuyuONaVe0L0O0Hf1C08Mg=="], - - "cordova-create": ["cordova-create@6.0.0", "", { "dependencies": { "cordova-app-hello-world": "^7.0.0", "cordova-common": "^6.0.0", "cordova-fetch": "^5.0.0", "globby": "^11.1.0", "import-fresh": "^3.3.1", "isobject": "^4.0.0", "npm-package-arg": "^13.0.0", "path-is-inside": "^1.0.2", "tmp": "^0.2.5", "valid-identifier": "0.0.2" } }, "sha512-LD41sLn2GsmAlj3576R3xlUM3BP0rt0CYd5LdbzU82WBI3ApMrrhM6xcHDYJfe1nfSL89O/nb/u/h7+7DhPQeA=="], - - "cordova-fetch": ["cordova-fetch@5.0.0", "", { "dependencies": { "@npmcli/arborist": "^9.1.3", "cordova-common": "^6.0.0", "execa": "^5.1.1", "npm-package-arg": "^13.0.0", "pacote": "^21.0.0", "resolve": "^1.22.10", "semver": "^7.7.2", "which": "^5.0.0" } }, "sha512-fsYnVfx32AOrFO6tw4EkzSig7WjNhze35dKIzdw20zTQetDKEfWA79PpCaoiSeahGi6O2MdnOFabLhEa8se6jg=="], - - "cordova-lib": ["cordova-lib@13.0.0", "", { "dependencies": { "cordova-common": "^6.0.0", "cordova-fetch": "^5.0.0", "detect-indent": "^6.1.0", "detect-newline": "^3.1.0", "execa": "^5.1.1", "globby": "^11.1.0", "semver": "^7.7.2", "stringify-package": "^1.0.1", "write-file-atomic": "^7.0.0" } }, "sha512-y8WQ+J6JtiU9C72ujvI3p+ScFJkg0VJwNfaUCqk9nPAssw2C6HltHk+ik/WrLUn6uDmwAM6gmfGUIMU2iVrNxA=="], - - "cordova-plugin-acode-webview": ["cordova-plugin-acode-webview@file:src/plugins/webview", {}], - - "cordova-plugin-advanced-http": ["/cordova-plugin-advanced-http@file:src/plugins/cordova-plugin-advanced-http", { "devDependencies": { "chai": "4.3.6", "colors": "1.4.0", "cordova": "13.0.0", "mocha": "9.2.2", "umd-tough-cookie": "3.0.0", "xml2js": "0.4.23" } }], - - "cordova-plugin-browser": ["cordova-plugin-browser@file:src/plugins/browser", {}], - - "cordova-plugin-buildinfo": ["/cordova-plugin-buildinfo@file:src/plugins/cordova-plugin-buildinfo", { "devDependencies": { "jshint": "^2.6.0" } }], - - "cordova-plugin-crashhandler": ["/cordova-plugin-crashhandler@file:src/plugins/cordova-plugin-crashhandler", {}], - - "cordova-plugin-device": ["cordova-plugin-device@2.1.0", "", {}, "sha512-FU0Lw1jZpuKOgG4v80LrfMAOIMCGfAVPumn7AwaX9S1iU/X3OPZUyoKUgP09q4bxL35IeNPkqNWVKYduAXZ1sg=="], - - "cordova-plugin-file": ["cordova-plugin-file@8.1.3", "", {}, "sha512-KlnP3CapNIsKncoWV5lYcIFYDPl0aZ1J3AH3QESlQX1Cb6Ct0p6GrAUvINyrFsjPbWHj8i0b6la6udVsghbATg=="], - - "cordova-plugin-ftp": ["cordova-plugin-ftp@file:src/plugins/ftp", {}], - - "cordova-plugin-iap": ["cordova-plugin-iap@file:src/plugins/iap", {}], - - "cordova-plugin-sdcard": ["cordova-plugin-sdcard@file:src/plugins/sdcard", {}], - - "cordova-plugin-server": ["cordova-plugin-server@file:src/plugins/server", {}], - - "cordova-plugin-sftp": ["cordova-plugin-sftp@file:src/plugins/sftp", {}], - - "cordova-plugin-system": ["cordova-plugin-system@file:src/plugins/system", {}], - - "cordova-plugin-websocket": ["cordova-plugin-websocket@file:src/plugins/websocket", {}], - "core-js": ["core-js@3.50.0", "", {}, "sha512-BRWgOLKkFeCgRudR6zrs8p9XJZcE14grzKMMssoYrk6krtuEZ7MTKPIY5RzOnqsEKIR9kst7wNzphttraT+Yqw=="], - "core-js-compat": ["core-js-compat@3.49.0", "", { "dependencies": { "browserslist": "^4.28.1" } }, "sha512-VQXt1jr9cBz03b331DFDCCP90b3fanciLkgiOoy8SBHy06gNf+vQ1A3WFLqG7I8TipYIKeYK9wxd0tUrvHcOZA=="], + "core-js-compat": ["core-js-compat@3.50.0", "", { "dependencies": { "browserslist": "^4.28.7" } }, "sha512-XGpFGbMLHwSt74YLTKho7Ib242qi6O8MSX+sRokV4oz7iKXvQWGYZthjIhjRGMxjzVkAubBO512dKGYcefmX3Q=="], - "core-js-pure": ["core-js-pure@3.49.0", "", {}, "sha512-XM4RFka59xATyJv/cS3O3Kml72hQXUeGRuuTmMYFxwzc9/7C8OYTaIR/Ji+Yt8DXzsFLNhat15cE/JP15HrCgw=="], + "core-js-pure": ["core-js-pure@3.50.0", "", {}, "sha512-6GP3Pxz4IKyWjAfa747vIu/jilB5z29JWROLqH/b+pXVcpgh6tM06ZIBwSuglgVqzDYURhOK6oEzTrG0bCHitA=="], "core-util-is": ["core-util-is@1.0.3", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="], - "cosmiconfig": ["cosmiconfig@9.0.1", "", { "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", "js-yaml": "^4.1.0", "parse-json": "^5.2.0" }, "peerDependencies": { "typescript": ">=4.9.5" } }, "sha512-hr4ihw+DBqcvrsEDioRO31Z17x71pUYoNe/4h6Z0wB72p7MU7/9gH8Q3s12NFhHPfYBBOV3qyfUxmr/Yn3shnQ=="], - - "crelt": ["crelt@1.0.6", "", {}, "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g=="], + "cosmiconfig": ["cosmiconfig@9.0.2", "", { "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", "js-yaml": "^4.1.0", "parse-json": "^5.2.0" }, "peerDependencies": { "typescript": ">=4.9.5" } }, "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg=="], - "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], + "crelt": ["crelt@1.0.7", "", {}, "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA=="], - "crypto-random-string": ["crypto-random-string@2.0.0", "", {}, "sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA=="], - - "css-loader": ["css-loader@7.1.4", "", { "dependencies": { "icss-utils": "^5.1.0", "postcss": "^8.4.40", "postcss-modules-extract-imports": "^3.1.0", "postcss-modules-local-by-default": "^4.0.5", "postcss-modules-scope": "^3.2.0", "postcss-modules-values": "^4.0.0", "postcss-value-parser": "^4.2.0", "semver": "^7.6.3" }, "peerDependencies": { "@rspack/core": "0.x || ^1.0.0 || ^2.0.0-0", "webpack": "^5.27.0" } }, "sha512-vv3J9tlOl04WjiMvHQI/9tmIrCxVrj6PFbHemBB1iihpeRbi/I4h033eoFIhwxBBqLhI0KYFS7yvynBFhIZfTw=="], + "css-loader": ["css-loader@7.1.5", "", { "dependencies": { "icss-utils": "^5.1.0", "postcss": "^8.4.40", "postcss-modules-extract-imports": "^3.1.0", "postcss-modules-local-by-default": "^4.0.5", "postcss-modules-scope": "^3.2.0", "postcss-modules-values": "^4.0.0", "postcss-value-parser": "^4.2.0", "semver": "^7.6.3" }, "peerDependencies": { "@rspack/core": "0.x || ^1.0.0 || ^2.0.0-0", "webpack": "^5.27.0" } }, "sha512-Q7iAfQkU2twNBryKX/vGAlE+GAmkF7quhSzAGNK8fBimxk3+tqg245rH52UPb9dioBolBc8rP0ihmHBaDTJQBA=="], "cssesc": ["cssesc@3.0.0", "", { "bin": "bin/cssesc" }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="], - "date-now": ["date-now@0.1.4", "", {}, "sha512-AsElvov3LoNB7tf5k37H2jYSB+ZZPMT5sG2QjJCcdlV5chIv6htBUBUui2IKRjgtKAKtCBN7Zbwa+MtwLjSeNw=="], - "dayjs": ["dayjs@1.11.23", "", {}, "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ=="], "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], "decamelize": ["decamelize@4.0.0", "", {}, "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ=="], - "dedent": ["dedent@1.7.2", "", { "peerDependencies": { "babel-plugin-macros": "^3.1.0" }, "optionalPeers": ["babel-plugin-macros"] }, "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA=="], - - "deep-eql": ["deep-eql@3.0.1", "", { "dependencies": { "type-detect": "^4.0.0" } }, "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw=="], - "depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="], "destroy": ["destroy@1.2.0", "", {}, "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg=="], - "detect-indent": ["detect-indent@6.1.0", "", {}, "sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA=="], - "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], - "detect-newline": ["detect-newline@3.1.0", "", {}, "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA=="], - - "diff": ["diff@5.0.0", "", {}, "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w=="], - - "dir-glob": ["dir-glob@3.0.1", "", { "dependencies": { "path-type": "^4.0.0" } }, "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA=="], + "diff": ["diff@5.2.2", "", {}, "sha512-vtcDfH3TOjP8UekytvnHH1o1P4FcUdt4eQ1Y+Abap1tk/OB2MWQvcwS2ClCd1zuIhc3JKOx6p3kod8Vfys3E+A=="], - "dom-serializer": ["dom-serializer@0.2.2", "", { "dependencies": { "domelementtype": "^2.0.1", "entities": "^2.0.0" } }, "sha512-2/xPb3ORsQ42nHYiSunXkDjPLBaEj/xTwUO4B7XCZQTRk7EBtTOPaygh10YAAh2OI1Qrp6NWfpAhzswj0ydt9g=="], - - "domelementtype": ["domelementtype@1.3.1", "", {}, "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w=="], - - "domhandler": ["domhandler@2.3.0", "", { "dependencies": { "domelementtype": "1" } }, "sha512-q9bUwjfp7Eif8jWxxxPSykdRZAb6GkguBGSgvvCrhI9wB71W2K/Kvv4E61CF/mcCfnVJDeDWx/Vb/uAqbDj6UQ=="], - - "dompurify": ["dompurify@3.4.14", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-dVoH9z+MY+C9IilgGCk3YfFqjLi3fChm2OiKJMzh6axrJ5qwxqWaZamgmHrpv22CN/KdbZJuGEGgfQoL00LTdg=="], - - "domutils": ["domutils@1.5.1", "", { "dependencies": { "dom-serializer": "0", "domelementtype": "1" } }, "sha512-gSu5Oi/I+3wDENBsOWBiRK1eoGxcywYSqg3rR960/+EfY0CF4EX1VPkgHOZ3WiS/Jg2DtliF6BhWcHlfpYUcGw=="], - - "dot-prop": ["dot-prop@5.3.0", "", { "dependencies": { "is-obj": "^2.0.0" } }, "sha512-QM8q3zDe58hqUqjraQOmzZ1LIH9SWQJTlEKCH4kJ2oQvLZk7RbQXvtDM2XEq3fwkV9CCvvH4LA0AV+ogFsBM2Q=="], - - "editor": ["editor@1.0.0", "", {}, "sha512-SoRmbGStwNYHgKfjOrX2L0mUvp9bUVv0uPppZSOMAntEbcFtoC3MKF5b3T6HQPXKIV+QGY3xPO3JK5it5lVkuw=="], + "dompurify": ["dompurify@3.4.16", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ=="], "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], - "electron-to-chromium": ["electron-to-chromium@1.5.415", "", {}, "sha512-958V+Kbhtgz+SxXeEVKBjrlKRBIDAYvUJfwhjxMZ5S6ut9jAl7l9ZKBkBrvjyjZE36PabLUo2L8kEeV5O4vgJg=="], - - "elementtree": ["elementtree@0.1.7", "", { "dependencies": { "sax": "1.1.4" } }, "sha512-wkgGT6kugeQk/P6VZ/f4T+4HB41BVgNBq5CDIZVbQ02nvTVqAiVTbskxxu3eA/X96lMlfYOwnLQpN2v5E1zDEg=="], + "electron-to-chromium": ["electron-to-chromium@1.5.444", "", {}, "sha512-5ss/uJfoDYDHT0lfJzT6FbcskIzROIOPf0BbbFkGcvDzoJU7i//9GDrwwIHQVmIsrAGiF3ihpADBRIsrEFt1rQ=="], "emmet": ["emmet@2.4.11", "", { "dependencies": { "@emmetio/abbreviation": "^2.3.3", "@emmetio/css-abbreviation": "^2.1.8" } }, "sha512-23QPJB3moh/U9sT4rQzGgeyyGIrcM+GH5uVYg2C6wZIxAIJq7Ng3QLT79tl8FUwDXhyq9SusfknOrofAKqvgyQ=="], @@ -1068,13 +855,11 @@ "emojis-list": ["emojis-list@3.0.0", "", {}, "sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q=="], - "empathic": ["empathic@2.0.1", "", {}, "sha512-YGRs8knHhKHVShLkFET/rWAU8kmHbOV5LwN938RHI0pljAJ1Gf6SzXsSmRaEzcXTtOOmVqJ5+WtQPL5uigY50Q=="], + "empathic": ["empathic@2.1.0", "", {}, "sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw=="], "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="], - "endent": ["endent@2.1.0", "", { "dependencies": { "dedent": "^0.7.0", "fast-json-parse": "^1.0.3", "objectorarray": "^1.0.5" } }, "sha512-r8VyPX7XL8U01Xgnb1CjZ3XV+z90cXIJ9JPE/R9SEC9vpw2P6CfsRPJmp20DppC5N7ZAMCmjYkJIa744Iyg96w=="], - - "enhanced-resolve": ["enhanced-resolve@5.24.5", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A=="], + "enhanced-resolve": ["enhanced-resolve@5.26.0", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw=="], "entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="], @@ -1084,7 +869,7 @@ "es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="], - "es-module-lexer": ["es-module-lexer@2.1.0", "", {}, "sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ=="], + "es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], "escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="], @@ -1104,31 +889,17 @@ "events": ["events@3.3.0", "", {}, "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q=="], - "execa": ["execa@5.1.1", "", { "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^6.0.0", "human-signals": "^2.1.0", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.1", "onetime": "^5.1.2", "signal-exit": "^3.0.3", "strip-final-newline": "^2.0.0" } }, "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg=="], - - "exit": ["exit@0.1.2", "", {}, "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ=="], - "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="], - "exponential-backoff": ["exponential-backoff@3.1.3", "", {}, "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA=="], - - "extsprintf": ["extsprintf@1.4.1", "", {}, "sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA=="], - "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], - "fast-glob": ["fast-glob@3.3.3", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="], - - "fast-json-parse": ["fast-json-parse@1.0.3", "", {}, "sha512-FRWsaZRWEJ1ESVNbDWmsAlqDk96gPQezzLghafp5J4GUKjbCz3OkAHuZs5TuPEtkbVQERysLp9xv6c24fBm8Aw=="], - "fast-json-stable-stringify": ["fast-json-stable-stringify@2.1.0", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="], - "fast-uri": ["fast-uri@3.1.2", "", {}, "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ=="], - - "fastq": ["fastq@1.20.1", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw=="], + "fast-uri": ["fast-uri@3.1.8", "", {}, "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg=="], "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" } }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], - "filesize": ["filesize@11.0.22", "", {}, "sha512-RlCVs9CY+oSsRnNZn95J9vDXjNjOwddKyTFjOYtA4yxYVIxBnwiVVGJX+TFhsmu3uUf81JDGyijtYL9xgawlTw=="], + "filesize": ["filesize@11.0.25", "", {}, "sha512-oPVK4S+B5nRK8eL5FORi4RSzbz/1PmUx17NQLMIWv8tlNVDUFgLY0GNApL7tEebL4WgkBqSJGB3AJsCXUs01hw=="], "fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="], @@ -1136,14 +907,14 @@ "flat": ["flat@5.0.2", "", { "bin": "cli.js" }, "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ=="], + "flru": ["flru@1.0.2", "", {}, "sha512-kWyh8ADvHBFz6ua5xYOPnUroZTT/bwWfrCeL0Wj1dzG4/YOmOcfJ99W8dOVyyynJN35rZ9aCOtHChqQovV7yog=="], + "fraction.js": ["fraction.js@5.3.4", "", {}, "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ=="], "framer-motion": ["framer-motion@12.43.0", "", { "dependencies": { "motion-dom": "^12.43.0", "motion-utils": "^12.39.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-1eaL3RvR/kAlbG7UYcpMptEyzPoENO0c6w7ZnB3/hh2vSAz/6uGAFn6fdoqTBguNstf3MsFhJHsD/0DHiclG+g=="], "fresh": ["fresh@0.5.2", "", {}, "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q=="], - "fs-minipass": ["fs-minipass@3.0.3", "", { "dependencies": { "minipass": "^7.0.3" } }, "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw=="], - "fs.realpath": ["fs.realpath@1.0.0", "", {}, "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw=="], "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], @@ -1154,77 +925,45 @@ "get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="], - "get-east-asian-width": ["get-east-asian-width@1.6.0", "", {}, "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA=="], - - "get-func-name": ["get-func-name@2.0.2", "", {}, "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ=="], + "get-east-asian-width": ["get-east-asian-width@1.7.0", "", {}, "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q=="], - "get-stream": ["get-stream@6.0.1", "", {}, "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg=="], - - "glob": ["glob@7.2.0", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.0.4", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q=="], + "glob": ["glob@8.1.0", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^5.0.1", "once": "^1.3.0" } }, "sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ=="], "glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], - "globby": ["globby@11.1.0", "", { "dependencies": { "array-union": "^2.1.0", "dir-glob": "^3.0.1", "fast-glob": "^3.2.9", "ignore": "^5.2.0", "merge2": "^1.4.1", "slash": "^3.0.0" } }, "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g=="], - "graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="], - "growl": ["growl@1.10.5", "", {}, "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA=="], - - "happy-dom": ["happy-dom@20.11.6", "", { "dependencies": { "@types/node": ">=20.0.0", "@types/whatwg-mimetype": "^3.0.2", "@types/ws": "^8.18.1", "buffer-image-size": "^0.6.4", "entities": "^7.0.1", "whatwg-mimetype": "^3.0.0", "ws": "^8.21.0" } }, "sha512-Hldbg8AdAa5a5oDcZpjqnGitp7JB0hqWmfv/8qr+kft4vzSD8BHsbdRfzYvL/0QcbKcURC/yyoygbeDQarPvYg=="], + "happy-dom": ["happy-dom@20.14.5", "", { "dependencies": { "@types/node": ">=20.0.0", "@types/whatwg-mimetype": "^3.0.2", "@types/ws": "^8.18.1", "buffer-image-size": "^0.6.4", "entities": "^7.0.1", "whatwg-mimetype": "^3.0.0", "ws": "^8.21.0" } }, "sha512-x/RzkpWO40bTjIoT30iQtt64FLLmH/iRcUCN2X//bLx7H3ifkdfPXyqsro/OYtqzIAhiLMMA7mmiOR9C3NOKjQ=="], "has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="], - "hasown": ["hasown@2.0.3", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg=="], + "hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], "he": ["he@1.2.0", "", { "bin": "bin/he" }, "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw=="], - "hosted-git-info": ["hosted-git-info@9.0.3", "", { "dependencies": { "lru-cache": "^11.1.0" } }, "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg=="], - "html-tag-js": ["html-tag-js@2.4.16", "", {}, "sha512-emVNouMF3t2yXpnnjgxCgkMY2W1ZrVC47qsHIJpPKgaH94Nqv355T7E1ZRkV6mWa3vLImHklH7vEcSURDhfq/A=="], - "htmlparser2": ["htmlparser2@3.8.3", "", { "dependencies": { "domelementtype": "1", "domhandler": "2.3", "domutils": "1.5", "entities": "1.0", "readable-stream": "1.1" } }, "sha512-hBxEg3CYXe+rPIua8ETe7tmG3XDn9B0edOE/e9wH2nLczxzgdu0m0aNHY+5wFZiviLWLdANPJTssa92dMcXQ5Q=="], - - "http-cache-semantics": ["http-cache-semantics@4.2.0", "", {}, "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ=="], - "http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], - "http-proxy-agent": ["http-proxy-agent@7.0.2", "", { "dependencies": { "agent-base": "^7.1.0", "debug": "^4.3.4" } }, "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig=="], - - "https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], - - "human-signals": ["human-signals@2.1.0", "", {}, "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw=="], - - "iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="], - "icss-utils": ["icss-utils@5.1.0", "", { "peerDependencies": { "postcss": "^8.1.0" } }, "sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA=="], - "ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="], - - "ignore-walk": ["ignore-walk@8.0.0", "", { "dependencies": { "minimatch": "^10.0.3" } }, "sha512-FCeMZT4NiRQGh+YkeKMtWrOmBgWjHjMJ26WQWrRQyoyzqevdaGSakUaJW5xQYmjLlUVk2qUnCjYVBax9EKKg8A=="], - "immediate": ["immediate@3.0.6", "", {}, "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ=="], - "immutable": ["immutable@5.1.5", "", {}, "sha512-t7xcm2siw+hlUM68I+UEOK+z84RzmN59as9DZ7P1l0994DKUWV7UXBMQZVxaoMSRQ+PBZbHCOoBt7a2wxOMt+A=="], + "immutable": ["immutable@5.1.9", "", {}, "sha512-m8nVez3rwrgmWxtLMt1ZYXB2Lv7OKYn/disyxAlSDYAlKSlFoPPfIAmAM/M5xqL4m4C/wAPw7S2/CNaUii1Hxg=="], "import-fresh": ["import-fresh@3.3.1", "", { "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" } }, "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ=="], "import-meta-resolve": ["import-meta-resolve@4.2.0", "", {}, "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg=="], - "imurmurhash": ["imurmurhash@0.1.4", "", {}, "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA=="], - "inflight": ["inflight@1.0.6", "", { "dependencies": { "once": "^1.3.0", "wrappy": "1" } }, "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA=="], "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], - "ini": ["ini@6.0.0", "", {}, "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ=="], - - "ip-address": ["ip-address@10.2.0", "", {}, "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA=="], - "is-arrayish": ["is-arrayish@0.2.1", "", {}, "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg=="], "is-binary-path": ["is-binary-path@2.1.0", "", { "dependencies": { "binary-extensions": "^2.0.0" } }, "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw=="], - "is-core-module": ["is-core-module@2.16.2", "", { "dependencies": { "hasown": "^2.0.3" } }, "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA=="], + "is-core-module": ["is-core-module@2.17.0", "", { "dependencies": { "hasown": "^2.0.4" } }, "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA=="], "is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="], @@ -1234,24 +973,12 @@ "is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="], - "is-obj": ["is-obj@2.0.0", "", {}, "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w=="], - - "is-path-inside": ["is-path-inside@3.0.3", "", {}, "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ=="], - "is-plain-obj": ["is-plain-obj@2.1.0", "", {}, "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA=="], - "is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="], - - "is-typedarray": ["is-typedarray@1.0.0", "", {}, "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA=="], - "is-unicode-supported": ["is-unicode-supported@0.1.0", "", {}, "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw=="], "isarray": ["isarray@1.0.0", "", {}, "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="], - "isexe": ["isexe@4.0.0", "", {}, "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw=="], - - "isobject": ["isobject@4.0.0", "", {}, "sha512-S/2fF5wH8SJA/kmwr6HYhK/RI/OkhD84k8ntalo0iJjZikgq1XFvR5M8NPT1x5F7fBwCG3qHfnzeP/Vh/ZxCUA=="], - "ist": ["ist@1.1.7", "", {}, "sha512-ex9JyqY+tCjBlxN1pXlqxEgtGGUGp1TG83ll1xpu8SfPgOhfAhEGCuepNHlB+d7Le+hLoBcfCu/G0ZQaFbi9hA=="], "jest-worker": ["jest-worker@27.5.1", "", { "dependencies": { "@types/node": "*", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg=="], @@ -1260,31 +987,21 @@ "js-tokens": ["js-tokens@10.0.0", "", {}, "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q=="], - "js-yaml": ["js-yaml@4.1.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": "bin/js-yaml.js" }, "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA=="], + "js-yaml": ["js-yaml@4.3.2", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": "bin/js-yaml.js" }, "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA=="], "jsesc": ["jsesc@3.1.0", "", { "bin": "bin/jsesc" }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="], - "jshint": ["jshint@2.13.6", "", { "dependencies": { "cli": "~1.0.0", "console-browserify": "1.1.x", "exit": "0.1.x", "htmlparser2": "3.8.x", "lodash": "~4.17.21", "minimatch": "~3.0.2", "strip-json-comments": "1.0.x" }, "bin": "bin/jshint" }, "sha512-IVdB4G0NTTeQZrBoM8C5JFVLjV2KtZ9APgybDA1MK73xb09qFs0jCXyQLnCOp1cSZZZbvhq/6mfXHUTaDkffuQ=="], - "json-parse-even-better-errors": ["json-parse-even-better-errors@2.3.1", "", {}, "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w=="], "json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], - "json-stringify-nice": ["json-stringify-nice@1.1.4", "", {}, "sha512-5Z5RFW63yxReJ7vANgW6eZFGWaQvnPE3WNmZoOJrSkGju2etKA2L5rrOa1sm877TVTFt57A80BH1bArcmlLfPw=="], - "json5": ["json5@2.2.3", "", { "bin": "lib/cli.js" }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="], "jsonc-parser": ["jsonc-parser@3.3.1", "", {}, "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ=="], - "jsonparse": ["jsonparse@1.3.1", "", {}, "sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg=="], - - "jszip": ["jszip@3.10.1", "", { "dependencies": { "lie": "~3.3.0", "pako": "~1.0.2", "readable-stream": "~2.3.6", "setimmediate": "^1.0.5" } }, "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g=="], - - "just-diff": ["just-diff@6.0.2", "", {}, "sha512-S59eriX5u3/QhMNq3v/gm8Kd0w8OS6Tz2FS1NG4blv+z0MuQcBRJyFWjdovM0Rad4/P4aUPFtnkNjMjyMlMSYA=="], - - "just-diff-apply": ["just-diff-apply@5.5.0", "", {}, "sha512-OYTthRfSh55WOItVqwpefPtNt2VdKsq5AnAK6apdtR6yCH8pr0CmSr710J0Mf+WdQy7K/OzMy7K2MgAfdQURDw=="], + "jszip": ["jszip@3.10.2", "", { "dependencies": { "lie": "~3.3.0", "pako": "~1.0.2", "readable-stream": "~2.3.6", "setimmediate": "^1.0.5" } }, "sha512-3l+rb15IOWtUhU0H5MFqES/T6Kh7abYwjosBey/vD6hDt8zoEffkSC5Ws5SGtgVw3gBx2NEbhTeSW1+kWkpyTQ=="], - "katex": ["katex@0.16.47", "", { "dependencies": { "commander": "^8.3.0" }, "bin": "cli.js" }, "sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg=="], + "katex": ["katex@0.19.0", "", { "dependencies": { "commander": "^15.0.0" }, "bin": "cli.js" }, "sha512-v6Tznz3zJ7u3niRCoDTsumM2+HA2XXcCu+WAacCeHD2z3p9A9Ks987o5FzfTGBN0e8A0vjEgIDvLbICrXpdw/Q=="], "lie": ["lie@3.3.0", "", { "dependencies": { "immediate": "~3.0.5" } }, "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ=="], @@ -1320,23 +1037,13 @@ "locate-path": ["locate-path@6.0.0", "", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="], - "lodash": ["lodash@4.17.23", "", {}, "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w=="], - "lodash.debounce": ["lodash.debounce@4.0.8", "", {}, "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow=="], "log-symbols": ["log-symbols@4.1.0", "", { "dependencies": { "chalk": "^4.1.0", "is-unicode-supported": "^0.1.0" } }, "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg=="], - "loupe": ["loupe@2.3.7", "", { "dependencies": { "get-func-name": "^2.0.1" } }, "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA=="], - - "lru-cache": ["lru-cache@11.5.1", "", {}, "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A=="], - "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], - "make-dir": ["make-dir@3.1.0", "", { "dependencies": { "semver": "^6.0.0" } }, "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw=="], - - "make-fetch-happen": ["make-fetch-happen@15.0.5", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@npmcli/agent": "^4.0.0", "@npmcli/redact": "^4.0.0", "cacache": "^20.0.1", "http-cache-semantics": "^4.1.1", "minipass": "^7.0.2", "minipass-fetch": "^5.0.0", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "negotiator": "^1.0.0", "proc-log": "^6.0.0", "ssri": "^13.0.0" } }, "sha512-uCbIa8jWWmQZt4dSnEStkVC6gdakiinAm4PiGsywIkguF0eWMdcjDz0ECYhUolFU3pFLOev9VNPCEygydXnddg=="], - - "markdown-it": ["markdown-it@14.3.0", "", { "dependencies": { "argparse": "^2.0.1", "entities": "^4.5.0", "linkify-it": "^5.0.2", "mdurl": "^2.0.0", "punycode.js": "^2.3.1", "uc.micro": "^2.1.0" }, "bin": "bin/markdown-it.mjs" }, "sha512-RCEsPjR+sr0x+AuYp601tKTkgFG4YEPLCzHST3cQ/fhlJkqAkz1L2/Qbp1j9qw5SBwQHFBoW8+hoN5xssOF0Tw=="], + "markdown-it": ["markdown-it@14.3.2", "", { "dependencies": { "argparse": "^2.0.1", "entities": "^4.5.0", "linkify-it": "^5.0.2", "mdurl": "^2.0.0", "punycode.js": "^2.3.1", "uc.micro": "^2.1.0" }, "bin": "bin/markdown-it.mjs" }, "sha512-sHHjZ5fJKlgrG4qns2YwVcdNep35h5fERrfkD2YNsb9UFk0UIHarbiTaHKVMlPuWAoiilyK8Fv/jAm11slsY7Q=="], "markdown-it-anchor": ["markdown-it-anchor@9.2.1", "", { "peerDependencies": { "@types/markdown-it": "*", "markdown-it": "*" } }, "sha512-p6APiLJDFAW2GEvaavDvhIBn7jrX2jLv77NkBGgNacFTurbORYc4pyYySg/mI6mpR6cHQuAtzKtmqgQr4K8dsQ=="], @@ -1352,43 +1059,23 @@ "marked": ["marked@15.0.12", "", { "bin": "bin/marked.js" }, "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA=="], - "mdurl": ["mdurl@2.0.0", "", {}, "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w=="], + "mdurl": ["mdurl@2.1.0", "", {}, "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg=="], "merge-stream": ["merge-stream@2.0.0", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="], - "merge2": ["merge2@1.4.1", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="], - - "micromatch": ["micromatch@4.0.8", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="], - "mime": ["mime@1.6.0", "", { "bin": "cli.js" }, "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg=="], "mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="], "mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="], - "mimic-fn": ["mimic-fn@2.1.0", "", {}, "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg=="], - "mini-css-extract-plugin": ["mini-css-extract-plugin@2.10.2", "", { "dependencies": { "schema-utils": "^4.0.0", "tapable": "^2.2.1" }, "peerDependencies": { "webpack": "^5.0.0" } }, "sha512-AOSS0IdEB95ayVkxn5oGzNQwqAi2J0Jb/kKm43t7H73s8+f5873g0yuj0PNvK4dO75mu5DHg4nlgp4k6Kga8eg=="], - "minimatch": ["minimatch@4.2.1", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-9Uq1ChtSZO+Mxa/CL1eGizn2vRn3MlLgzhT0Iz8zaY8NdvxvB0d5QdPFmCKf7JKA9Lerx5vRrnwO03jsSfGG9g=="], - - "minimizer-webpack-plugin": ["minimizer-webpack-plugin@5.10.0", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.31", "jest-worker": "^27.4.5", "schema-utils": "^4.3.3", "terser": "^5.51.0" }, "peerDependencies": { "webpack": "^5.1.0" } }, "sha512-2//60T4S0X1Ug/dqLDOgDaGlZsN1Lv8hf8oB0NOV/KIHSaXlPwXBBIbim79dE2Z7NEs52ES8YHoSv6Lmsk+XNg=="], - - "minipass": ["minipass@7.1.3", "", {}, "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="], - - "minipass-collect": ["minipass-collect@2.0.1", "", { "dependencies": { "minipass": "^7.0.3" } }, "sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw=="], - - "minipass-fetch": ["minipass-fetch@5.0.2", "", { "dependencies": { "minipass": "^7.0.3", "minipass-sized": "^2.0.0", "minizlib": "^3.0.1" }, "optionalDependencies": { "iconv-lite": "^0.7.2" } }, "sha512-2d0q2a8eCi2IRg/IGubCNRJoYbA1+YPXAzQVRFmB45gdGZafyivnZ5YSEfo3JikbjGxOdntGFvBQGqaSMXlAFQ=="], - - "minipass-flush": ["minipass-flush@1.0.7", "", { "dependencies": { "minipass": "^3.0.0" } }, "sha512-TbqTz9cUwWyHS2Dy89P3ocAGUGxKjjLuR9z8w4WUTGAVgEj17/4nhgo2Du56i0Fm3Pm30g4iA8Lcqctc76jCzA=="], - - "minipass-pipeline": ["minipass-pipeline@1.2.4", "", { "dependencies": { "minipass": "^3.0.0" } }, "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A=="], - - "minipass-sized": ["minipass-sized@2.0.0", "", { "dependencies": { "minipass": "^7.1.2" } }, "sha512-zSsHhto5BcUVM2m1LurnXY6M//cGhVaegT71OfOXoprxT6o780GZd792ea6FfrQkuU4usHZIUczAQMRUE2plzA=="], + "minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="], - "minizlib": ["minizlib@3.1.0", "", { "dependencies": { "minipass": "^7.1.2" } }, "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw=="], + "minimizer-webpack-plugin": ["minimizer-webpack-plugin@5.13.0", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.31", "jest-worker": "^27.4.5", "schema-utils": "^4.3.3", "terser": "^5.51.0" }, "peerDependencies": { "webpack": "^5.1.0" } }, "sha512-OO1NF2zHj6sf4CNv2AsUWYcS8WEwkVKQDXxxKzlOxx1Xl+WlqYtVC+oNlGNwGkLAOnpj277BSHypWwRtd9w4JQ=="], - "mocha": ["mocha@9.2.2", "", { "dependencies": { "@ungap/promise-all-settled": "1.1.2", "ansi-colors": "4.1.1", "browser-stdout": "1.3.1", "chokidar": "3.5.3", "debug": "4.3.3", "diff": "5.0.0", "escape-string-regexp": "4.0.0", "find-up": "5.0.0", "glob": "7.2.0", "growl": "1.10.5", "he": "1.2.0", "js-yaml": "4.1.0", "log-symbols": "4.1.0", "minimatch": "4.2.1", "ms": "2.1.3", "nanoid": "3.3.1", "serialize-javascript": "6.0.0", "strip-json-comments": "3.1.1", "supports-color": "8.1.1", "which": "2.0.2", "workerpool": "6.2.0", "yargs": "16.2.0", "yargs-parser": "20.2.4", "yargs-unparser": "2.0.0" }, "bin": { "_mocha": "bin/_mocha", "mocha": "bin/mocha" } }, "sha512-L6XC3EdwT6YrIk0yXpavvLkn8h+EU+Y5UcCHKECyMbdUIxyMuZj4bX4U9e1nvnvUUvQVsV2VHQr5zLdcUkhW/g=="], + "mocha": ["mocha@10.8.2", "", { "dependencies": { "ansi-colors": "^4.1.3", "browser-stdout": "^1.3.1", "chokidar": "^3.5.3", "debug": "^4.3.5", "diff": "^5.2.0", "escape-string-regexp": "^4.0.0", "find-up": "^5.0.0", "glob": "^8.1.0", "he": "^1.2.0", "js-yaml": "^4.1.0", "log-symbols": "^4.1.0", "minimatch": "^5.1.6", "ms": "^2.1.3", "serialize-javascript": "^6.0.2", "strip-json-comments": "^3.1.1", "supports-color": "^8.1.1", "workerpool": "^6.5.1", "yargs": "^16.2.0", "yargs-parser": "^20.2.9", "yargs-unparser": "^2.0.0" }, "bin": { "_mocha": "bin/_mocha", "mocha": "bin/mocha.js" } }, "sha512-VZlYo/WE8t1tstuRmqgeyBgCbJc/lEdopaa+axcKzTBJ+UIdlAB9XnmvTCAH4pwR4ElNInaedhEBmZD8iCSVEg=="], "motion": ["motion@12.43.0", "", { "dependencies": { "framer-motion": "^12.43.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-BQgQbSa9Hn3/mtbib0MK53y6JSANa+YKUKlaYnWzAVDH424RYQ5LVpV3pNiWH00BA2z4ojsSdMzqT7g2FQwjuQ=="], @@ -1400,62 +1087,30 @@ "mustache": ["mustache@4.2.0", "", { "bin": "bin/mustache" }, "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ=="], - "nanoid": ["nanoid@3.3.18", "", { "bin": "bin/nanoid.cjs" }, "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w=="], - - "negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="], + "nanoid": ["nanoid@3.3.19", "", { "bin": "bin/nanoid.cjs" }, "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug=="], "neo-async": ["neo-async@2.6.2", "", {}, "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw=="], "node-addon-api": ["node-addon-api@7.1.1", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="], - "node-gyp": ["node-gyp@12.3.0", "", { "dependencies": { "env-paths": "^2.2.0", "exponential-backoff": "^3.1.1", "graceful-fs": "^4.2.6", "nopt": "^9.0.0", "proc-log": "^6.0.0", "semver": "^7.3.5", "tar": "^7.5.4", "tinyglobby": "^0.2.12", "undici": "^6.25.0", "which": "^6.0.0" }, "bin": "bin/node-gyp.js" }, "sha512-QNcUWM+HgJplcPzBvFBZ9VXacyGZ4+VTOb80PwWR+TlVzoHbRKULNEzpRsnaoxG3Wzr7Qh7BYxGDU3CbKib2Yg=="], - - "node-releases": ["node-releases@2.0.53", "", {}, "sha512-D9UOmYG3UH1V+ENW56t5QXBwJw1YEY18ruVeus89Rw+SyIgjPkCO84bRzO3uNIYosJbNwiabWVn48o3uJLjxFQ=="], - - "nopt": ["nopt@9.0.0", "", { "dependencies": { "abbrev": "^4.0.0" }, "bin": "bin/nopt.js" }, "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw=="], + "node-releases": ["node-releases@2.0.57", "", {}, "sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw=="], "normalize-path": ["normalize-path@3.0.0", "", {}, "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="], - "npm-bundled": ["npm-bundled@5.0.0", "", { "dependencies": { "npm-normalize-package-bin": "^5.0.0" } }, "sha512-JLSpbzh6UUXIEoqPsYBvVNVmyrjVZ1fzEFbqxKkTJQkWBO3xFzFT+KDnSKQWwOQNbuWRwt5LSD6HOTLGIWzfrw=="], - - "npm-install-checks": ["npm-install-checks@8.0.0", "", { "dependencies": { "semver": "^7.1.1" } }, "sha512-ScAUdMpyzkbpxoNekQ3tNRdFI8SJ86wgKZSQZdUxT+bj0wVFpsEMWnkXP0twVe1gJyNF5apBWDJhhIbgrIViRA=="], - - "npm-normalize-package-bin": ["npm-normalize-package-bin@5.0.0", "", {}, "sha512-CJi3OS4JLsNMmr2u07OJlhcrPxCeOeP/4xq67aWNai6TNWWbTrlNDgl8NcFKVlcBKp18GPj+EzbNIgrBfZhsag=="], - - "npm-package-arg": ["npm-package-arg@13.0.2", "", { "dependencies": { "hosted-git-info": "^9.0.0", "proc-log": "^6.0.0", "semver": "^7.3.5", "validate-npm-package-name": "^7.0.0" } }, "sha512-IciCE3SY3uE84Ld8WZU23gAPPV9rIYod4F+rc+vJ7h7cwAJt9Vk6TVsK60ry7Uj3SRS3bqRRIGuTp9YVlk6WNA=="], - - "npm-packlist": ["npm-packlist@10.0.4", "", { "dependencies": { "ignore-walk": "^8.0.0", "proc-log": "^6.0.0" } }, "sha512-uMW73iajD8hiH4ZBxEV3HC+eTnppIqwakjOYuvgddnalIw2lJguKviK1pcUJDlIWm1wSJkchpDZDSVVsZEYRng=="], - - "npm-pick-manifest": ["npm-pick-manifest@11.0.3", "", { "dependencies": { "npm-install-checks": "^8.0.0", "npm-normalize-package-bin": "^5.0.0", "npm-package-arg": "^13.0.0", "semver": "^7.3.5" } }, "sha512-buzyCfeoGY/PxKqmBqn1IUJrZnUi1VVJTdSSRPGI60tJdUhUoSQFhs0zycJokDdOznQentgrpf8LayEHyyYlqQ=="], - - "npm-registry-fetch": ["npm-registry-fetch@19.1.1", "", { "dependencies": { "@npmcli/redact": "^4.0.0", "jsonparse": "^1.3.1", "make-fetch-happen": "^15.0.0", "minipass": "^7.0.2", "minipass-fetch": "^5.0.0", "minizlib": "^3.0.1", "npm-package-arg": "^13.0.0", "proc-log": "^6.0.0" } }, "sha512-TakBap6OM1w0H73VZVDf44iFXsOS3h+L4wVMXmbWOQroZgFhMch0juN6XSzBNlD965yIKvWg2dfu7NSiaYLxtw=="], - - "npm-run-path": ["npm-run-path@4.0.1", "", { "dependencies": { "path-key": "^3.0.0" } }, "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw=="], - - "objectorarray": ["objectorarray@1.0.5", "", {}, "sha512-eJJDYkhJFFbBBAxeh8xW+weHlkI28n2ZdQV/J/DNfWfSKlGEf2xcfAbZTv3riEXHAhL9SVOTs2pRmXiSTf78xg=="], - - "obug": ["obug@2.1.3", "", {}, "sha512-9miFgM2OFba7hB+pRgvtV84pYTBaoTHohvmIgiRt6dRIzbwEOIaNaP+dIlGs2fNFoB0SeISs0Jz5WFVRid6Xyg=="], + "obug": ["obug@2.2.1", "", {}, "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q=="], "on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="], "once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="], - "onetime": ["onetime@5.1.2", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="], - "p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="], "p-locate": ["p-locate@5.0.0", "", { "dependencies": { "p-limit": "^3.0.2" } }, "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw=="], - "p-map": ["p-map@7.0.4", "", {}, "sha512-tkAQEw8ysMzmkhgw8k+1U/iPhWNhykKnSk4Rd5zLoPJCuJaGRPo6YposrZgaxHKzDHdDWWZvE/Sk7hsL2X/CpQ=="], - - "pacote": ["pacote@21.5.0", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@npmcli/git": "^7.0.0", "@npmcli/installed-package-contents": "^4.0.0", "@npmcli/package-json": "^7.0.0", "@npmcli/promise-spawn": "^9.0.0", "@npmcli/run-script": "^10.0.0", "cacache": "^20.0.0", "fs-minipass": "^3.0.0", "minipass": "^7.0.2", "npm-package-arg": "^13.0.0", "npm-packlist": "^10.0.1", "npm-pick-manifest": "^11.0.1", "npm-registry-fetch": "^19.0.0", "proc-log": "^6.0.0", "sigstore": "^4.0.0", "ssri": "^13.0.0", "tar": "^7.4.3" }, "bin": "bin/index.js" }, "sha512-VtZ0SB8mb5Tzw3dXDfVAIjhyVKUHZkS/ZH9/5mpKenwC9sFOXNI0JI7kEF7IMkwOnsWMFrvAZHzx1T5fmrp9FQ=="], - "pako": ["pako@1.0.11", "", {}, "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw=="], "parent-module": ["parent-module@1.0.1", "", { "dependencies": { "callsites": "^3.0.0" } }, "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g=="], - "parse-conflict-json": ["parse-conflict-json@5.0.1", "", { "dependencies": { "json-parse-even-better-errors": "^5.0.0", "just-diff": "^6.0.0", "just-diff-apply": "^5.2.0" } }, "sha512-ZHEmNKMq1wyJXNwLxyHnluPfRAFSIliBvbK/UiOceROt4Xh9Pz0fq49NytIaeaCUf5VR86hwQ/34FCcNU5/LKQ=="], - "parse-json": ["parse-json@5.2.0", "", { "dependencies": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", "json-parse-even-better-errors": "^2.3.0", "lines-and-columns": "^1.1.6" } }, "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg=="], "parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="], @@ -1464,31 +1119,17 @@ "path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="], - "path-is-absolute": ["path-is-absolute@1.0.1", "", {}, "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg=="], - - "path-is-inside": ["path-is-inside@1.0.2", "", {}, "sha512-DUWJr3+ULp4zXmol/SZkFf3JGsS9/SIv+Y3Rt93/UjPpDpklB5f1er4O3POIbUuUJ3FXgqte2Q7SrU6zAqwk8w=="], - - "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], - "path-parse": ["path-parse@1.0.7", "", {}, "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw=="], - "path-scurry": ["path-scurry@2.0.2", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg=="], - - "path-type": ["path-type@4.0.0", "", {}, "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw=="], - "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - "pathval": ["pathval@1.1.1", "", {}, "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ=="], - - "pele": ["pele@1.10.0", "", {}, "sha512-hDMEM+GQ01pZin8tst3PRXGeB/xFATvXBreHHtjx2glSNAQ7nHFq7EbMuNJGTbqkYgueWPboLjyUBsAudsb1qQ=="], + "pele": ["pele@1.12.0", "", {}, "sha512-3OdOK6rvkaTB569R4/I8U0H82MqPRxj7vfkbowa2rRhgSBPFhvWlfFy5eae0jP+2A6hE8abE17nsdyxJz2VBiQ=="], "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], "picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], - "plist": ["plist@3.1.1", "", { "dependencies": { "@xmldom/xmldom": "^0.9.10", "base64-js": "^1.5.1", "xmlbuilder": "^15.1.1" } }, "sha512-ZIfcLJC+7E7FBFnDxm9MPmt7D+DidyQ26lewieO75AdhA2ayMtsJSES0iWzqJQbcVRSrTufQoy0DR94xHue0oA=="], - - "postcss": ["postcss@8.5.26", "", { "dependencies": { "nanoid": "^3.3.17", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ=="], + "postcss": ["postcss@8.5.28", "", { "dependencies": { "nanoid": "^3.3.18", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A=="], "postcss-loader": ["postcss-loader@8.2.1", "", { "dependencies": { "cosmiconfig": "^9.0.0", "jiti": "^2.5.1", "semver": "^7.6.2" }, "peerDependencies": { "@rspack/core": "0.x || ^1.0.0 || ^2.0.0-0", "postcss": "^7.0.0 || ^8.0.1", "webpack": "^5.0.0" } }, "sha512-k98jtRzthjj3f76MYTs9JTpRqV1RaaMhEU0Lpw9OTmQZQdppg4B30VZ74BojuBHt3F4KyubHJoXCMUeM8Bqeow=="], @@ -1500,55 +1141,41 @@ "postcss-modules-values": ["postcss-modules-values@4.0.0", "", { "dependencies": { "icss-utils": "^5.0.0" }, "peerDependencies": { "postcss": "^8.1.0" } }, "sha512-RDxHkAiEGI78gS2ofyvCsu7iycRv7oqw5xMWn9iMoR0N/7mf9D50ecQqUo5BZ9Zh2vH4bCUR/ktCqbB9m8vJjQ=="], - "postcss-selector-parser": ["postcss-selector-parser@7.1.1", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg=="], + "postcss-selector-parser": ["postcss-selector-parser@7.1.6", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw=="], "postcss-value-parser": ["postcss-value-parser@4.2.0", "", {}, "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ=="], - "prettier": ["prettier@3.8.3", "", { "bin": "bin/prettier.cjs" }, "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw=="], - - "prettier-plugin-java": ["prettier-plugin-java@2.9.1", "", { "dependencies": { "web-tree-sitter": "0.26.8" }, "peerDependencies": { "prettier": "^3.0.0" } }, "sha512-qdvMRgSlx5li5fkbIQlMAUSJQn8rIwP2Ux0U1Xg8ganHMAK4UOUoOG00GeZfoLRllSgNt5V3dZOlwUXPLoamSQ=="], + "prettier": ["prettier@3.9.9", "", { "bin": "bin/prettier.cjs" }, "sha512-Z/CJHIkdujO/OtN7nXUii0Rf3VT5SRuhjBA82Xvu2XhBUgX3nhP67T0LHceBdQLex7OOFGTox+Q5Yg8Jk2Qivg=="], - "proc-log": ["proc-log@6.1.0", "", {}, "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ=="], + "prettier-plugin-java": ["prettier-plugin-java@2.11.0", "", { "dependencies": { "web-tree-sitter": "0.27.0" }, "peerDependencies": { "prettier": "^3.0.0" } }, "sha512-pLwm2wHvVvW5eVVLf1cq2orY2ATaIj5ngN8hJ5ZdXYzUHzxrfaZkk2xmu8Mz/duBXAc2xT/cUH5+dK414HQSTw=="], "process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="], - "proggy": ["proggy@4.0.0", "", {}, "sha512-MbA4R+WQT76ZBm/5JUpV9yqcJt92175+Y0Bodg3HgiXzrmKu7Ggq+bpn6y6wHH+gN9NcyKn3yg1+d47VaKwNAQ=="], - - "promise-all-reject-late": ["promise-all-reject-late@1.0.1", "", {}, "sha512-vuf0Lf0lOxyQREH7GDIOUMLS7kz+gs8i6B+Yi8dC68a2sychGrHTJYghMBD6k7eUcH0H5P73EckCA48xijWqXw=="], - - "promise-call-limit": ["promise-call-limit@3.0.2", "", {}, "sha512-mRPQO2T1QQVw11E7+UdCJu7S61eJVWknzml9sC1heAdj1jxl0fWMBypIt9ZOcLFf8FkG995ZD7RnVk7HH72fZw=="], - - "properties-parser": ["properties-parser@0.6.0", "", {}, "sha512-qvr2cSmoA0dln0MARAKwBzPkkXn7FqwX+RVVNpMdMJc7rt9mqO2cXwluxtux9fHrLhjnPFaQkS8BM0kFrTCnSw=="], - "punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="], "punycode.js": ["punycode.js@2.3.1", "", {}, "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA=="], "querystringify": ["querystringify@2.2.0", "", {}, "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ=="], - "queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="], - "randombytes": ["randombytes@2.1.0", "", { "dependencies": { "safe-buffer": "^5.1.0" } }, "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ=="], "range-parser": ["range-parser@1.2.1", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="], "raw-loader": ["raw-loader@4.0.2", "", { "dependencies": { "loader-utils": "^2.0.0", "schema-utils": "^3.0.0" }, "peerDependencies": { "webpack": "^4.0.0 || ^5.0.0" } }, "sha512-ZnScIV3ag9A4wPX/ZayxL/jZH+euYb6FcUinPcgiQW0+UBtEv0O6Q3lGd3cqJ+GHH+rksEv3Pj99oxJ3u3VIKA=="], - "read-cmd-shim": ["read-cmd-shim@6.0.0", "", {}, "sha512-1zM5HuOfagXCBWMN83fuFI/x+T/UhZ7k+KIzhrHXcQoeX5+7gmaDYjELQHmmzIodumBHeByBJT4QYS7ufAgs7A=="], - "readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="], "readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], "regenerate": ["regenerate@1.4.2", "", {}, "sha512-zrceR/XhGYU/d/opr2EKO7aRHUeiBI8qjtfHqADTwZd6Szfy16la6kqD0MIUs5z5hx6AaKa+PixpPrR289+I0A=="], - "regenerate-unicode-properties": ["regenerate-unicode-properties@10.2.2", "", { "dependencies": { "regenerate": "^1.4.2" } }, "sha512-m03P+zhBeQd1RGnYxrGyDAPpWX/epKirLrp8e3qevZdVkKtnCrjjWczIbYc8+xd6vcTStVlqfycTx1KR4LOr0g=="], + "regenerate-unicode-properties": ["regenerate-unicode-properties@10.3.0", "", { "dependencies": { "regenerate": "^1.4.2" } }, "sha512-9ns8odR8e9q3otKeHj3DE80jZYKg6zVeZKE+zQmRKXFoVUcuiTGeO6iusDhPRoIQQPVPRvH+SfBhrTud4eczuw=="], - "regexpu-core": ["regexpu-core@6.4.0", "", { "dependencies": { "regenerate": "^1.4.2", "regenerate-unicode-properties": "^10.2.2", "regjsgen": "^0.8.0", "regjsparser": "^0.13.0", "unicode-match-property-ecmascript": "^2.0.0", "unicode-match-property-value-ecmascript": "^2.2.1" } }, "sha512-0ghuzq67LI9bLXpOX/ISfve/Mq33a4aFRzoQYhnnok1JOFpmE/A2TBGkNVenOGEeSBCjIiWcc6MVOG5HEQv0sA=="], + "regexpu-core": ["regexpu-core@6.5.2", "", { "dependencies": { "regenerate": "^1.4.2", "regenerate-unicode-properties": "^10.3.0", "regjsgen": "^0.8.0", "regjsparser": "^0.13.0", "unicode-match-property-ecmascript": "^2.0.0", "unicode-match-property-value-ecmascript": "^2.2.1" } }, "sha512-zkmVH92DlzjSFc4xKGZp/2BXIFrDIdBQBC8gUXKCsMgKYb1bkCkxfSuoW1werDjaTEMTbULkHtKFHe1L+Abnaw=="], "regjsgen": ["regjsgen@0.8.0", "", {}, "sha512-RvwtGe3d7LvWiDQXeQw8p5asZUmfU1G/l6WbUXeHta7Y2PEIvBTwH6E2EfmYUK8pxcxEdEmaomqyp0vZZ7C+3Q=="], - "regjsparser": ["regjsparser@0.13.2", "", { "dependencies": { "jsesc": "~3.1.0" }, "bin": "bin/parser" }, "sha512-NgRBy2Nx/bE+9F27nVHnqcN5HjyLmecqsqx2PJHu3/IEtADD4WuxuXIVExD5PoSDFVrl78dOonfcOe5O+5nbzQ=="], + "regjsparser": ["regjsparser@0.13.3", "", { "dependencies": { "jsesc": "~3.1.0" }, "bin": "bin/parser" }, "sha512-ycwFAS14Jw4mppvmK4GR/J6u3WpWpjkEApehuHtLc/8VpPNpDMbQ4WjqwplXifGeyKOzHSFLmSPqzksDQE2Sfg=="], "require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="], @@ -1560,35 +1187,27 @@ "resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="], - "reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="], - - "rolldown": ["rolldown@1.2.6", "", { "dependencies": { "@oxc-project/types": "=0.147.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.6", "@rolldown/binding-android-arm64": "1.2.6", "@rolldown/binding-darwin-arm64": "1.2.6", "@rolldown/binding-darwin-x64": "1.2.6", "@rolldown/binding-freebsd-x64": "1.2.6", "@rolldown/binding-linux-arm-gnueabihf": "1.2.6", "@rolldown/binding-linux-arm64-gnu": "1.2.6", "@rolldown/binding-linux-arm64-musl": "1.2.6", "@rolldown/binding-linux-ppc64-gnu": "1.2.6", "@rolldown/binding-linux-s390x-gnu": "1.2.6", "@rolldown/binding-linux-x64-gnu": "1.2.6", "@rolldown/binding-linux-x64-musl": "1.2.6", "@rolldown/binding-openharmony-arm64": "1.2.6", "@rolldown/binding-win32-arm64-msvc": "1.2.6", "@rolldown/binding-win32-x64-msvc": "1.2.6" }, "bin": "bin/cli.mjs" }, "sha512-vMM4q3aixf46GiF1Kok8jDPFsEpXgFWGjUHXNkNHNm+Y2adXAG2dbX91jkti3i0ZRsOlcmbuzAz1poObSHCmUA=="], + "rolldown": ["rolldown@1.2.12", "", { "dependencies": { "@oxc-project/types": "=0.152.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.12", "@rolldown/binding-android-arm64": "1.2.12", "@rolldown/binding-darwin-arm64": "1.2.12", "@rolldown/binding-darwin-x64": "1.2.12", "@rolldown/binding-freebsd-x64": "1.2.12", "@rolldown/binding-linux-arm-gnueabihf": "1.2.12", "@rolldown/binding-linux-arm64-gnu": "1.2.12", "@rolldown/binding-linux-arm64-musl": "1.2.12", "@rolldown/binding-linux-ppc64-gnu": "1.2.12", "@rolldown/binding-linux-s390x-gnu": "1.2.12", "@rolldown/binding-linux-x64-gnu": "1.2.12", "@rolldown/binding-linux-x64-musl": "1.2.12", "@rolldown/binding-openharmony-arm64": "1.2.12", "@rolldown/binding-win32-arm64-msvc": "1.2.12", "@rolldown/binding-win32-x64-msvc": "1.2.12" }, "bin": "bin/cli.mjs" }, "sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ=="], - "rollup": ["rollup@4.63.3", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@napi-rs/lzma-linux-x64-gnu": "1.5.1", "@rollup/rollup-android-arm-eabi": "4.63.3", "@rollup/rollup-android-arm64": "4.63.3", "@rollup/rollup-darwin-arm64": "4.63.3", "@rollup/rollup-darwin-x64": "4.63.3", "@rollup/rollup-freebsd-arm64": "4.63.3", "@rollup/rollup-freebsd-x64": "4.63.3", "@rollup/rollup-linux-arm-gnueabihf": "4.63.3", "@rollup/rollup-linux-arm-musleabihf": "4.63.3", "@rollup/rollup-linux-arm64-gnu": "4.63.3", "@rollup/rollup-linux-arm64-musl": "4.63.3", "@rollup/rollup-linux-loong64-gnu": "4.63.3", "@rollup/rollup-linux-loong64-musl": "4.63.3", "@rollup/rollup-linux-ppc64-gnu": "4.63.3", "@rollup/rollup-linux-ppc64-musl": "4.63.3", "@rollup/rollup-linux-riscv64-gnu": "4.63.3", "@rollup/rollup-linux-riscv64-musl": "4.63.3", "@rollup/rollup-linux-s390x-gnu": "4.63.3", "@rollup/rollup-linux-x64-gnu": "4.63.3", "@rollup/rollup-linux-x64-musl": "4.63.3", "@rollup/rollup-openbsd-x64": "4.63.3", "@rollup/rollup-openharmony-arm64": "4.63.3", "@rollup/rollup-win32-arm64-msvc": "4.63.3", "@rollup/rollup-win32-ia32-msvc": "4.63.3", "@rollup/rollup-win32-x64-gnu": "4.63.3", "@rollup/rollup-win32-x64-msvc": "4.63.3", "fsevents": "~2.3.2" }, "bin": "dist/bin/rollup" }, "sha512-1i2XreiAoMMXuPGD6Msj2xWrMMkHojNRKivInxGQcg7/1KuPuYlfUutLyh4drnOxUTHX9cHI4wFoat8D/NKaBw=="], + "rollup": ["rollup@4.64.0", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@napi-rs/lzma-linux-x64-gnu": "1.5.1", "@rollup/rollup-android-arm-eabi": "4.64.0", "@rollup/rollup-android-arm64": "4.64.0", "@rollup/rollup-darwin-arm64": "4.64.0", "@rollup/rollup-darwin-x64": "4.64.0", "@rollup/rollup-freebsd-arm64": "4.64.0", "@rollup/rollup-freebsd-x64": "4.64.0", "@rollup/rollup-linux-arm-gnueabihf": "4.64.0", "@rollup/rollup-linux-arm-musleabihf": "4.64.0", "@rollup/rollup-linux-arm64-gnu": "4.64.0", "@rollup/rollup-linux-arm64-musl": "4.64.0", "@rollup/rollup-linux-loong64-gnu": "4.64.0", "@rollup/rollup-linux-loong64-musl": "4.64.0", "@rollup/rollup-linux-ppc64-gnu": "4.64.0", "@rollup/rollup-linux-ppc64-musl": "4.64.0", "@rollup/rollup-linux-riscv64-gnu": "4.64.0", "@rollup/rollup-linux-riscv64-musl": "4.64.0", "@rollup/rollup-linux-s390x-gnu": "4.64.0", "@rollup/rollup-linux-x64-gnu": "4.64.0", "@rollup/rollup-linux-x64-musl": "4.64.0", "@rollup/rollup-openbsd-x64": "4.64.0", "@rollup/rollup-openharmony-arm64": "4.64.0", "@rollup/rollup-win32-arm64-msvc": "4.64.0", "@rollup/rollup-win32-ia32-msvc": "4.64.0", "@rollup/rollup-win32-x64-gnu": "4.64.0", "@rollup/rollup-win32-x64-msvc": "4.64.0", "fsevents": "~2.3.2" }, "bin": "dist/bin/rollup" }, "sha512-gjA/kFeDfffII8COoPsvLPvE16hWDTEc1+0QKQNKUkuV8iJjqsC4xXs8/FzuL0v9EV39kuxTbAgcFoTRyy2TGQ=="], "rollup-plugin-dts": ["rollup-plugin-dts@6.5.1", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "@jridgewell/sourcemap-codec": "^1.5.5", "convert-source-map": "^2.0.0", "magic-string": "^0.30.21" }, "optionalDependencies": { "@babel/code-frame": "^8.0.0" }, "peerDependencies": { "@typescript/typescript6": "^6", "rollup": "^3 || ^4", "typescript": "^4.5 || ^5 || ^6 || ^7" }, "optionalPeers": ["@typescript/typescript6"] }, "sha512-jODTXp3H7MK/Ur/ErtsrQ0G1GvaCmc3du+y5pNrdBMf6d7HlL2Nd/N6TkEr+f75CkUj01zEoEd7y2elH0eHi1Q=="], - "run-parallel": ["run-parallel@1.2.0", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="], - "safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="], - "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="], - - "sass": ["sass@1.103.1", "", { "dependencies": { "chokidar": "^5.0.0", "immutable": "^5.1.5", "source-map-js": ">=0.6.2 <2.0.0" }, "optionalDependencies": { "@parcel/watcher": "^2.4.1" }, "bin": "sass.js" }, "sha512-9icZURbP51S6S0QGoyaeqk9uB06GNWxsFYWfH5RgpFgqK5FA8tJcM3AdVxrZEVJ7dz+L87nG95gBKf4VuaMHGw=="], + "sass": ["sass@1.105.1", "", { "dependencies": { "chokidar": "^5.0.0", "immutable": "^5.1.5", "source-map-js": ">=0.6.2 <2.0.0" }, "optionalDependencies": { "@parcel/watcher": "^2.4.1" }, "bin": "sass.js" }, "sha512-1CnAWPyrrnVQzXGB/DUep1vYCKCm1CIBr+YxjjiW6wk9qtzemnGP4qicH56T2F9S4Hjtv/Ne3jDz8JqfdDU4oA=="], "sass-loader": ["sass-loader@16.0.8", "", { "dependencies": { "neo-async": "^2.6.2" }, "peerDependencies": { "@rspack/core": "0.x || ^1.0.0 || ^2.0.0-0", "node-sass": "^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 || ^9.0.0", "sass": "^1.3.0", "sass-embedded": "*", "webpack": "^5.0.0" }, "optionalPeers": ["node-sass", "sass-embedded"] }, "sha512-hcov4ZwZJIGbEuyNr9EmiTmZueyrxSToE6GOzoZnq5JM7ecRO7ttyvilPn+VmRsqiP16+VYZzVnGZj/hzZgKBA=="], - "sax": ["sax@1.1.4", "", {}, "sha512-5f3k2PbGGp+YtKJjOItpg3P99IMD84E4HOvcfleTb5joCHNXYLsR9yWFPOYGgaeMPDubQILTCMdsFb2OMeOjtg=="], - - "schema-utils": ["schema-utils@4.3.3", "", { "dependencies": { "@types/json-schema": "^7.0.9", "ajv": "^8.9.0", "ajv-formats": "^2.1.1", "ajv-keywords": "^5.1.0" } }, "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA=="], + "schema-utils": ["schema-utils@4.5.0", "", { "dependencies": { "@types/json-schema": "^7.0.15", "ajv": "^8.20.0", "ajv-formats": "^3.0.1", "ajv-keywords": "^5.1.0" } }, "sha512-zJlMCZ0cAR5p/Y4oVpRoqioDMJcGxaXRrQ/4rP4WyR84vc5z/DolXdbvXeDpTwbtocDFr2rhPqHPErDCUtz2kA=="], - "selenium-webdriver": ["selenium-webdriver@4.49.0", "", { "dependencies": { "@bazel/runfiles": "^6.5.0", "jszip": "^3.10.1", "tmp": "^0.2.7", "ws": "^8.21.3" } }, "sha512-16XqeOEMj+4+p+pzLLyvNWmF5jCY05EKIl3e1anZBgv4+zq7PUTtiNjKtQhMpwosZ0wIMKDFAQ2xdyogOHD4DA=="], + "selenium-webdriver": ["selenium-webdriver@4.50.0", "", { "dependencies": { "@bazel/runfiles": "^6.5.0", "jszip": "^3.10.2", "tmp": "^0.2.7", "ws": "^8.22.0" } }, "sha512-E8DhBVMpnsNwShcxSWG8oCVJLQoPZiEciqz/inH7YkKvnR/kBiSNjaJux+7iuA4x6/77N8T68vWMTJgW169kOg=="], - "semver": ["semver@7.8.4", "", { "bin": "bin/semver.js" }, "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA=="], + "semver": ["semver@7.8.5", "", { "bin": "bin/semver.js" }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], "send": ["send@0.19.2", "", { "dependencies": { "debug": "2.6.9", "depd": "2.0.0", "destroy": "1.2.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", "fresh": "~0.5.2", "http-errors": "~2.0.1", "mime": "1.6.0", "ms": "2.1.3", "on-finished": "~2.4.1", "range-parser": "~1.2.1", "statuses": "~2.0.2" } }, "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg=="], - "serialize-javascript": ["serialize-javascript@6.0.0", "", { "dependencies": { "randombytes": "^2.1.0" } }, "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag=="], + "serialize-javascript": ["serialize-javascript@6.0.2", "", { "dependencies": { "randombytes": "^2.1.0" } }, "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g=="], "serve-static": ["serve-static@1.16.3", "", { "dependencies": { "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "parseurl": "~1.3.3", "send": "~0.19.1" } }, "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA=="], @@ -1596,85 +1215,55 @@ "setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="], - "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], - - "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], - "siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="], - "signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="], - - "sigstore": ["sigstore@4.1.0", "", { "dependencies": { "@sigstore/bundle": "^4.0.0", "@sigstore/core": "^3.1.0", "@sigstore/protobuf-specs": "^0.5.0", "@sigstore/sign": "^4.1.0", "@sigstore/tuf": "^4.0.1", "@sigstore/verify": "^3.1.0" } }, "sha512-/fUgUhYghuLzVT/gaJoeVehLCgZiUxPCPMcyVNY0lIf/cTCz58K/WTI7PefDarXxp9nUKpEwg1yyz3eSBMTtgA=="], - - "slash": ["slash@3.0.0", "", {}, "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q=="], - - "smart-buffer": ["smart-buffer@4.2.0", "", {}, "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="], - - "socks": ["socks@2.8.9", "", { "dependencies": { "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" } }, "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw=="], - - "socks-proxy-agent": ["socks-proxy-agent@8.0.5", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "^4.3.4", "socks": "^2.8.3" } }, "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw=="], - "source-map": ["source-map@0.7.6", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="], - "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], + "source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="], "source-map-support": ["source-map-support@0.5.21", "", { "dependencies": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" } }, "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w=="], - "spdx-exceptions": ["spdx-exceptions@2.5.0", "", {}, "sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w=="], - - "spdx-expression-parse": ["spdx-expression-parse@4.0.0", "", { "dependencies": { "spdx-exceptions": "^2.1.0", "spdx-license-ids": "^3.0.0" } }, "sha512-Clya5JIij/7C6bRR22+tnGXbc4VKlibKSVj2iHvVeX5iMW7s1SIQlqu699JkODJJIhh/pUu8L0/VLh8xflD+LQ=="], - - "spdx-license-ids": ["spdx-license-ids@3.0.23", "", {}, "sha512-CWLcCCH7VLu13TgOH+r8p1O/Znwhqv/dbb6lqWy67G+pT1kHmeD/+V36AVb/vq8QMIQwVShJ6Ssl5FPh0fuSdw=="], - "sprintf": ["sprintf@0.1.5", "", {}, "sha512-4X5KsuXFQ7f+d7Y+bi4qSb6eI+YoifDTGr0MQJXRoYO7BO7evfRCjds6kk3z7l5CiJYxgDN1x5Er4WiyCt+zTQ=="], - "ssri": ["ssri@13.0.1", "", { "dependencies": { "minipass": "^7.0.3" } }, "sha512-QUiRf1+u9wPTL/76GTYlKttDEBWV1ga9ZXW8BG6kfdeyyM8LGPix9gROyg9V2+P0xNyF3X2Go526xKFdMZrHSQ=="], - "stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="], "statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="], - "std-env": ["std-env@4.2.0", "", {}, "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw=="], + "std-env": ["std-env@4.3.0", "", {}, "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag=="], - "string-argv": ["string-argv@0.3.2", "", {}, "sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q=="], - - "string-width": ["string-width@8.2.2", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg=="], + "string-width": ["string-width@8.3.0", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ=="], "string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="], - "stringify-package": ["stringify-package@1.0.1", "", {}, "sha512-sa4DUQsYciMP1xhKWGuFM04fB0LG/9DlluZoSVywUMRNvzid6XucHK0/90xGxRoHrAaROrcHK1aPKaijCtSrhg=="], - "strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], - "strip-final-newline": ["strip-final-newline@2.0.0", "", {}, "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA=="], - "strip-json-comments": ["strip-json-comments@3.1.1", "", {}, "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="], "style-loader": ["style-loader@4.0.0", "", { "peerDependencies": { "webpack": "^5.27.0" } }, "sha512-1V4WqhhZZgjVAVJyt7TdDPZoPBPNHbekX4fWnCJL1yQukhCeZhJySUL+gL9y6sNdN95uEOS83Y55SqHcP7MzLA=="], - "style-mod": ["style-mod@4.1.3", "", {}, "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ=="], + "style-mod": ["style-mod@4.1.4", "", {}, "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw=="], - "supports-color": ["supports-color@8.1.1", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="], + "supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], "supports-preserve-symlinks-flag": ["supports-preserve-symlinks-flag@1.0.0", "", {}, "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="], - "systeminformation": ["systeminformation@5.31.6", "", { "os": "!aix", "bin": "lib/cli.js" }, "sha512-Uv2b2uGGM6ns+26czgW2cYRabYdnswM0ddSOOlryHOaelzsmDSet1iM/NT7VOYxW8x/BW+HkY+b1Ve2pLTSGSA=="], - "tapable": ["tapable@2.3.3", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="], - "tar": ["tar@7.5.22", "", { "dependencies": { "@isaacs/fs-minipass": "^4.0.0", "chownr": "^3.0.0", "minipass": "^7.1.2", "minizlib": "^3.1.0", "yallist": "^5.0.0" } }, "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA=="], - "terminal": ["terminal@0.1.4", "", { "dependencies": { "sprintf": ">= 0.1.1" } }, "sha512-w6OAFpUO+TimZUdQ46dK3fYYOCCBIsS2QUfIEkzX21oJ8tvJOJvJkcmrbleLH5KG02SNohYFDj81bL3VPaULsQ=="], "terser": ["terser@5.51.2", "", { "dependencies": { "@jridgewell/source-map": "^0.3.3", "acorn": "^8.15.0", "commander": "^2.20.0", "source-map-support": "~0.5.20" }, "bin": "bin/terser" }, "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q=="], "tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="], - "tinyexec": ["tinyexec@1.1.2", "", {}, "sha512-dAqSqE/RabpBKI8+h26GfLq6Vb3JVXs30XYQjdMjaj/c2tS8IYYMbIzP599KtRj7c57/wYApb3QjgRgXmrCukA=="], + "tinyexec": ["tinyexec@1.3.1", "", {}, "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA=="], "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], - "tinyrainbow": ["tinyrainbow@3.1.1", "", {}, "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw=="], + "tinyrainbow": ["tinyrainbow@3.2.0", "", {}, "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A=="], + + "tldts": ["tldts@7.4.16", "", { "dependencies": { "tldts-core": "^7.4.16" }, "bin": "bin/cli.js" }, "sha512-QwBER5KMR86IIjpIiO7H/Z3IMJPsZ1A6RKPAqzTTgOyUQUSt9FdnKcqhTaJmkY6HVrgouZHZR0ncK5QxvmnQeg=="], + + "tldts-core": ["tldts-core@7.4.16", "", {}, "sha512-MDolfaSJtlSK5Y0A1xl3277ekubZwobpBjugknDizI9O5Rm60a1m8k4ICK+MRsCDzPygT81mp3BBf5RKDlFRfA=="], "tmp": ["tmp@0.2.7", "", {}, "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw=="], @@ -1682,29 +1271,19 @@ "toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="], - "treeverse": ["treeverse@3.0.0", "", {}, "sha512-gcANaAnd2QDZFmHFEOF4k7uc1J/6a6z3DJMd/QwEyxLoKGiptJRwid582r7QIsFlFMIZ3SnxfS52S4hm2DHkuQ=="], + "tough-cookie": ["tough-cookie@6.0.2", "", { "dependencies": { "tldts": "^7.0.5" } }, "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA=="], "ts-loader": ["ts-loader@9.6.2", "", { "dependencies": { "chalk": "^4.1.0", "picomatch": "^4.0.0", "source-map": "^0.7.4" }, "peerDependencies": { "loader-utils": "*", "typescript": "*", "webpack": "^4.0.0 || ^5.0.0" } }, "sha512-R4iuczmtgxvtuI556s+hTZ6/7Ee03VCAk/l/M8LY1OAsUgB7YydsCxkgq9D9pKRaD7GJqUi2u8fp9zZP/ufjKA=="], "tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], - "tuf-js": ["tuf-js@4.1.0", "", { "dependencies": { "@tufjs/models": "4.1.0", "debug": "^4.4.3", "make-fetch-happen": "^15.0.1" } }, "sha512-50QV99kCKH5P/Vs4E2Gzp7BopNV+KzTXqWeaxrfu5IQJBOULRsTIS9seSsOVT8ZnGXzCyx55nYWAi4qJzpZKEQ=="], - - "type-detect": ["type-detect@4.1.0", "", {}, "sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw=="], - - "typedarray-to-buffer": ["typedarray-to-buffer@3.1.5", "", { "dependencies": { "is-typedarray": "^1.0.0" } }, "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q=="], - "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], "typescript-language-server": ["typescript-language-server@4.4.1", "", { "bin": "lib/cli.mjs" }, "sha512-vEvDw+cjY75afMN2rhx0z8sQtFDAUHoBniksBmB6NUZlDt0rEIwQq01VMiqyXFm9uZwcED2475cmDeXxoDHleg=="], "uc.micro": ["uc.micro@2.1.0", "", {}, "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A=="], - "umd-tough-cookie": ["umd-tough-cookie@3.0.0", "", {}, "sha512-LgVV1jgzEPgC/zOj6T9OIDBTj7YCGEJkgoxV2gHYv1Crlst1X95lRIF48hFleGgv4v01Z86LxyyLyvl++M2Srg=="], - - "undici": ["undici@6.27.0", "", {}, "sha512-YmfV3YnEDzXRC5lZ2jWtWWHKGUm1zIt8AhesR1tens+HTNv+YZlN/dp6G727LOvMJ8xjP9Be7Y2Sdr96LDm+pg=="], - - "undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="], + "undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], "unicode-canonical-property-names-ecmascript": ["unicode-canonical-property-names-ecmascript@2.0.1", "", {}, "sha512-dA8WbNeb2a6oQzAQ55YlT5vQAWGV9WXOsi3SskE3bcCdM0P4SDd+24zS/OCacdRq5BkdsRj9q3Pg6YyQoxIGqg=="], @@ -1714,11 +1293,7 @@ "unicode-property-aliases-ecmascript": ["unicode-property-aliases-ecmascript@2.2.0", "", {}, "sha512-hpbDzxUY9BFwX+UeBnxv3Sh1q7HFxj48DTmXchNgRa46lO8uj3/1iEn3MiNUYTg1g9ctIqXCCERn8gYZhHC5lQ=="], - "unique-string": ["unique-string@2.0.0", "", { "dependencies": { "crypto-random-string": "^2.0.0" } }, "sha512-uNaeirEPvpZWSgzwsPGtU2zVSTrn/8L5q/IexZmH0eH6SA73CmAA5U4GwORTxQAZs95TAXLNqeLoPPNO5gZfWg=="], - - "untildify": ["untildify@4.0.0", "", {}, "sha512-KK8xQ1mkzZeg9inewmFVDNkg3l5LUhoq9kN6iWYB/CC9YMG8HA+c1Q8HwDe6dEX7kErrEVNVBO3fWsVq5iDgtw=="], - - "update-browserslist-db": ["update-browserslist-db@1.3.1", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": "cli.js" }, "sha512-ZZ61DsRsOnakl74HAmp3oSN4aXUmEWXf+i/yv0h7tIBfICc3VdrFErQKUUKPgu3AMsTUMbcongALEN4l6GSUrQ=="], + "update-browserslist-db": ["update-browserslist-db@1.3.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": "cli.js" }, "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ=="], "uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="], @@ -1726,13 +1301,11 @@ "util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], - "valid-identifier": ["valid-identifier@0.0.2", "", {}, "sha512-zaSmOW6ykXwrkX0YTuFUSoALNEKGaQHpxBJQLb3TXspRNDpBwbfrIQCZqAQ0LKBlKuyn2YOq7NNd6415hvZ33g=="], - - "validate-npm-package-name": ["validate-npm-package-name@7.0.2", "", {}, "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A=="], - "vanilla-picker": ["vanilla-picker@2.12.3", "", { "dependencies": { "@sphinxxxx/color-conversion": "^2.2.2" } }, "sha512-qVkT1E7yMbUsB2mmJNFmaXMWE2hF8ffqzMMwe9zdAikd8u2VfnsVY2HQcOUi2F38bgbxzlJBEdS1UUhOXdF9GQ=="], - "vite": ["vite@8.2.2", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.5", "postcss": "^8.5.26", "rolldown": "~1.2.4", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.4.0 || ^0.5.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@vitejs/devtools", "esbuild", "less", "sass-embedded", "stylus", "sugarss", "tsx", "yaml"], "bin": "bin/vite.js" }, "sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q=="], + "verkit": ["verkit@0.3.2", "", {}, "sha512-zj/ob3UsvJGN0whEAKFp53REA5X66hvffVqoCtVQAakJKnKlH+/PcOfMoFwIG/o4rElqLv/ycAFlx8ZlXUorCg=="], + + "vite": ["vite@8.3.2", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.28", "rolldown": "~1.2.11", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@vitejs/devtools", "esbuild", "less", "sass-embedded", "stylus", "sugarss", "tsx", "yaml"], "bin": "bin/vite.js" }, "sha512-SQr1x6W5vVSbROg7vsyXIaxK9b0G7zsT68acdWWRmnBUsgDieLCRG+Rep9WdZgcposvv/GSnr4GUUBqB3vXq6w=="], "vitest": ["vitest@4.1.11", "", { "dependencies": { "@vitest/expect": "4.1.11", "@vitest/mocker": "4.1.11", "@vitest/pretty-format": "4.1.11", "@vitest/runner": "4.1.11", "@vitest/snapshot": "4.1.11", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^4.0.0-rc.1", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.1.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.1.11", "@vitest/browser-preview": "4.1.11", "@vitest/browser-webdriverio": "4.1.11", "@vitest/coverage-istanbul": "4.1.11", "@vitest/coverage-v8": "4.1.11", "@vitest/ui": "4.1.11", "happy-dom": "*", "jsdom": "*", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "jsdom"], "bin": "vitest.mjs" }, "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw=="], @@ -1742,55 +1315,41 @@ "vscode-json-languageservice": ["vscode-json-languageservice@5.7.2", "", { "dependencies": { "@vscode/l10n": "^0.0.18", "jsonc-parser": "^3.3.1", "vscode-languageserver-textdocument": "^1.0.12", "vscode-languageserver-types": "^3.17.5", "vscode-uri": "^3.1.0" } }, "sha512-WtKRDtJfFEmLrgtu+ODexOHm/6/krRF0k6t+uvkKIKW1Jh9ZIyxZQwJJwB3qhrEgvAxa37zbUg+vn+UyUK/U2w=="], - "vscode-jsonrpc": ["vscode-jsonrpc@8.2.0", "", {}, "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA=="], + "vscode-jsonrpc": ["vscode-jsonrpc@9.0.3", "", {}, "sha512-qETYf9PCl1lVfwR+oBmMfc4vP2nqLNA35ABxorw3j06+xlKRgDVxbLgKm4Y/xPL0YWdeDjLoI4ImICIT3nB0zQ=="], - "vscode-languageserver-protocol": ["vscode-languageserver-protocol@3.17.5", "", { "dependencies": { "vscode-jsonrpc": "8.2.0", "vscode-languageserver-types": "3.17.5" } }, "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg=="], + "vscode-languageserver-protocol": ["vscode-languageserver-protocol@3.18.4", "", { "dependencies": { "vscode-jsonrpc": "9.0.3", "vscode-languageserver-types": "3.18.4" } }, "sha512-CCXbyr99dafRJzJH/0Ryk7ly5T8XPmSR0//OuF2w4m+9JiOin7zcAT5iET8GRE7Z9taFBejb3GbM0a0mbjdbrg=="], "vscode-languageserver-textdocument": ["vscode-languageserver-textdocument@1.0.12", "", {}, "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA=="], - "vscode-languageserver-types": ["vscode-languageserver-types@3.17.5", "", {}, "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg=="], + "vscode-languageserver-types": ["vscode-languageserver-types@3.18.4", "", {}, "sha512-nQsacoiijvl0fRf2q28uFDrAVwRhdCa3QveiF7/CX0r18mLR5FU/1WskSsCKOjmEbtteKUnY8x8Yzxop+k0zwg=="], - "vscode-uri": ["vscode-uri@3.1.0", "", {}, "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ=="], + "vscode-uri": ["vscode-uri@3.2.0", "", {}, "sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg=="], "w3c-keyname": ["w3c-keyname@2.2.8", "", {}, "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ=="], - "walk-up-path": ["walk-up-path@4.0.0", "", {}, "sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A=="], - "watchpack": ["watchpack@2.5.2", "", { "dependencies": { "graceful-fs": "^4.1.2" } }, "sha512-6i/00NBjP4yGPs+caKSyRfpTF/8Torsu0MOW3mMzIbhgISFder8i7xbqgHlLMwJrdiN8ndBV3UA1/AfzPSr+jg=="], - "web-tree-sitter": ["web-tree-sitter@0.26.8", "", {}, "sha512-4sUwi7ZyOrIk5KLgYLkc2A/F0LFMQnBhfb+2Cdl7ik4ePJ6JD+fk4ofI2sA5eGawBKBaK4Vntt7Ww5KcEsay4A=="], + "web-tree-sitter": ["web-tree-sitter@0.27.0", "", {}, "sha512-XK08gj6RwTMQatAG7uVRP8MunqotL/XC19vHgkSPKmELgbGPBj4ECvB8haHOUnyj6ls2B8t42UTro14zxGgAHg=="], - "webpack": ["webpack@5.110.3", "", { "dependencies": { "@types/estree": "^1.0.8", "@types/json-schema": "^7.0.15", "@webassemblyjs/ast": "^1.14.1", "@webassemblyjs/wasm-edit": "^1.14.1", "@webassemblyjs/wasm-parser": "^1.14.1", "acorn": "^8.16.0", "browserslist": "^4.28.1", "chrome-trace-event": "^1.0.2", "enhanced-resolve": "^5.24.4", "es-module-lexer": "^2.1.0", "events": "^3.2.0", "graceful-fs": "^4.2.11", "mime-db": "^1.54.0", "minimizer-webpack-plugin": "^5.7.0", "neo-async": "^2.6.2", "schema-utils": "^4.3.3", "tapable": "^2.3.0", "watchpack": "^2.5.2", "webpack-sources": "^3.5.1" }, "bin": "bin/webpack.js" }, "sha512-GuizBzRvo9YPpyoNMf3ag7AzxbaW85qrRSqTha345KyJbAFPt3/cMzBM0h+RWg7SK/7DdzRLINP3LvQ0hvr4hg=="], + "webpack": ["webpack@5.111.1", "", { "dependencies": { "@types/estree": "^1.0.8", "@types/json-schema": "^7.0.15", "@webassemblyjs/ast": "^1.14.1", "@webassemblyjs/wasm-edit": "^1.14.1", "@webassemblyjs/wasm-parser": "^1.14.1", "browserslist": "^4.28.1", "chrome-trace-event": "^1.0.2", "enhanced-resolve": "^5.25.0", "es-module-lexer": "^2.1.0", "events": "^3.2.0", "graceful-fs": "^4.2.11", "mime-db": "^1.54.0", "minimizer-webpack-plugin": "^5.7.0", "schema-utils": "^4.5.0", "tapable": "^2.3.0", "watchpack": "^2.5.2", "webpack-sources": "^3.5.1" }, "bin": "bin/webpack.js" }, "sha512-cNypaz0RP+S4cvQVi1M/3bRUkvNP0xZpL0TjFx+c6jg64VbxD+2weWDgY9UnjRI6dhZgtaj8DU76GGFcJ79xPQ=="], - "webpack-sources": ["webpack-sources@3.5.1", "", {}, "sha512-jyuiGJdtvY434z5bUZrjz67v76/ePNvFZTp9Mdz29IlH4+GPsgyGjiv0fKI+M7BdkU6ADjulUcKAd3tUK3WlEw=="], + "webpack-sources": ["webpack-sources@3.6.0", "", {}, "sha512-EIMmPVvNI0CYXyRPp34F2Qk7W37/BZVZIofS6LAUnrNjCVahS+hO4mxwFJDjQjODTGZDtVzLYoN2+1dYkhk9qA=="], "whatwg-mimetype": ["whatwg-mimetype@3.0.0", "", {}, "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q=="], - "which": ["which@6.0.1", "", { "dependencies": { "isexe": "^4.0.0" }, "bin": { "node-which": "bin/which.js" } }, "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg=="], - "why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": "cli.js" }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="], - "workerpool": ["workerpool@6.2.0", "", {}, "sha512-Rsk5qQHJ9eowMH28Jwhe8HEbmdYDX4lwoMWshiCXugjtHqMD9ZbiqSDLxcsfdqsETPzVUtX5s1Z5kStiIM6l4A=="], + "workerpool": ["workerpool@6.5.1", "", {}, "sha512-Fs4dNYcsdpYSAfVxhnl1L5zTksjvOJxtC5hzMNl+1t9B8hTJTdKDyZ5ju7ztgPy+ft9tBFXoOlDNiOT9WUXZlA=="], "wrap-ansi": ["wrap-ansi@9.0.2", "", { "dependencies": { "ansi-styles": "^6.2.1", "string-width": "^7.0.0", "strip-ansi": "^7.1.0" } }, "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww=="], "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], - "write-file-atomic": ["write-file-atomic@3.0.3", "", { "dependencies": { "imurmurhash": "^0.1.4", "is-typedarray": "^1.0.0", "signal-exit": "^3.0.2", "typedarray-to-buffer": "^3.1.5" } }, "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q=="], - - "ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="], - - "xdg-basedir": ["xdg-basedir@4.0.0", "", {}, "sha512-PSNhEJDejZYV7h50BohL09Er9VaIefr2LMAf3OEmpCkjOi34eYyQYAXUTjEQtZJTKcF0E2UKTh+osDLsgNim9Q=="], - - "xml2js": ["xml2js@0.4.23", "", { "dependencies": { "sax": ">=0.6.0", "xmlbuilder": "~11.0.0" } }, "sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug=="], - - "xmlbuilder": ["xmlbuilder@11.0.1", "", {}, "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA=="], + "ws": ["ws@8.22.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg=="], "y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="], - "yallist": ["yallist@5.0.0", "", {}, "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw=="], - - "yargs": ["yargs@18.1.0", "", { "dependencies": { "cliui": "^9.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "string-width": "^8.2.1", "y18n": "^5.0.5", "yargs-parser": "^22.0.0" } }, "sha512-2rAgRKu54VsHkqI0/tYkmluGXHD4KW7yZoycuqDQ15QOTnc2VVfy0nN/1eMhnQLO00A+dwtK20xuCnc1YGeUyg=="], + "yargs": ["yargs@18.2.0", "", { "dependencies": { "cliui": "^9.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "string-width": "^8.2.1", "y18n": "^5.0.5", "yargs-parser": "^22.0.0" } }, "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w=="], "yargs-parser": ["yargs-parser@22.0.0", "", {}, "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw=="], @@ -1798,41 +1357,39 @@ "yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], - "@babel/core/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + "@babel/core/@babel/generator": ["@babel/generator@8.0.6", "", { "dependencies": { "@babel/parser": "^8.0.6", "@babel/types": "^8.0.6", "@jridgewell/gen-mapping": "0.4.0-beta.0", "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng=="], - "@babel/core/@babel/parser": ["@babel/parser@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ=="], + "@babel/core/@babel/parser": ["@babel/parser@8.0.6", "", { "dependencies": { "@babel/types": "^8.0.6" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg=="], - "@babel/core/@babel/traverse": ["@babel/traverse@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/template": "^8.0.0", "@babel/types": "^8.0.0", "obug": "^2.1.1" } }, "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw=="], + "@babel/core/@babel/traverse": ["@babel/traverse@8.0.6", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/generator": "^8.0.6", "@babel/helper-globals": "^8.0.6", "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", "@babel/types": "^8.0.6", "obug": "^2.1.1" } }, "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ=="], "@babel/generator/@babel/types": ["@babel/types@7.29.8", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg=="], - "@babel/helper-create-class-features-plugin/@babel/traverse": ["@babel/traverse@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/template": "^8.0.0", "@babel/types": "^8.0.0", "obug": "^2.1.1" } }, "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw=="], + "@babel/helper-create-class-features-plugin/@babel/traverse": ["@babel/traverse@8.0.6", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/generator": "^8.0.6", "@babel/helper-globals": "^8.0.6", "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", "@babel/types": "^8.0.6", "obug": "^2.1.1" } }, "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ=="], - "@babel/helper-member-expression-to-functions/@babel/traverse": ["@babel/traverse@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/template": "^8.0.0", "@babel/types": "^8.0.0", "obug": "^2.1.1" } }, "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw=="], + "@babel/helper-member-expression-to-functions/@babel/traverse": ["@babel/traverse@8.0.6", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/generator": "^8.0.6", "@babel/helper-globals": "^8.0.6", "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", "@babel/types": "^8.0.6", "obug": "^2.1.1" } }, "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ=="], - "@babel/helper-module-imports/@babel/traverse": ["@babel/traverse@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/template": "^8.0.0", "@babel/types": "^8.0.0", "obug": "^2.1.1" } }, "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw=="], + "@babel/helper-module-imports/@babel/traverse": ["@babel/traverse@8.0.6", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/generator": "^8.0.6", "@babel/helper-globals": "^8.0.6", "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", "@babel/types": "^8.0.6", "obug": "^2.1.1" } }, "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ=="], - "@babel/helper-module-transforms/@babel/traverse": ["@babel/traverse@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/template": "^8.0.0", "@babel/types": "^8.0.0", "obug": "^2.1.1" } }, "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw=="], + "@babel/helper-module-transforms/@babel/traverse": ["@babel/traverse@8.0.6", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/generator": "^8.0.6", "@babel/helper-globals": "^8.0.6", "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", "@babel/types": "^8.0.6", "obug": "^2.1.1" } }, "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ=="], - "@babel/helper-remap-async-to-generator/@babel/traverse": ["@babel/traverse@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/template": "^8.0.0", "@babel/types": "^8.0.0", "obug": "^2.1.1" } }, "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw=="], + "@babel/helper-remap-async-to-generator/@babel/traverse": ["@babel/traverse@8.0.6", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/generator": "^8.0.6", "@babel/helper-globals": "^8.0.6", "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", "@babel/types": "^8.0.6", "obug": "^2.1.1" } }, "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ=="], - "@babel/helper-replace-supers/@babel/traverse": ["@babel/traverse@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/template": "^8.0.0", "@babel/types": "^8.0.0", "obug": "^2.1.1" } }, "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw=="], + "@babel/helper-replace-supers/@babel/traverse": ["@babel/traverse@8.0.6", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/generator": "^8.0.6", "@babel/helper-globals": "^8.0.6", "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", "@babel/types": "^8.0.6", "obug": "^2.1.1" } }, "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ=="], - "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse": ["@babel/traverse@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/template": "^8.0.0", "@babel/types": "^8.0.0", "obug": "^2.1.1" } }, "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw=="], + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse": ["@babel/traverse@8.0.6", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/generator": "^8.0.6", "@babel/helper-globals": "^8.0.6", "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", "@babel/types": "^8.0.6", "obug": "^2.1.1" } }, "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ=="], - "@babel/helper-wrap-function/@babel/traverse": ["@babel/traverse@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/template": "^8.0.0", "@babel/types": "^8.0.0", "obug": "^2.1.1" } }, "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw=="], + "@babel/helper-wrap-function/@babel/traverse": ["@babel/traverse@8.0.6", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/generator": "^8.0.6", "@babel/helper-globals": "^8.0.6", "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", "@babel/types": "^8.0.6", "obug": "^2.1.1" } }, "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ=="], "@babel/parser/@babel/types": ["@babel/types@7.29.8", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg=="], - "@babel/plugin-transform-async-generator-functions/@babel/traverse": ["@babel/traverse@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/template": "^8.0.0", "@babel/types": "^8.0.0", "obug": "^2.1.1" } }, "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw=="], - - "@babel/plugin-transform-classes/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + "@babel/plugin-transform-async-generator-functions/@babel/traverse": ["@babel/traverse@8.0.6", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/generator": "^8.0.6", "@babel/helper-globals": "^8.0.6", "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", "@babel/types": "^8.0.6", "obug": "^2.1.1" } }, "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ=="], - "@babel/plugin-transform-classes/@babel/traverse": ["@babel/traverse@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/template": "^8.0.0", "@babel/types": "^8.0.0", "obug": "^2.1.1" } }, "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw=="], + "@babel/plugin-transform-classes/@babel/helper-globals": ["@babel/helper-globals@8.0.6", "", {}, "sha512-OdnA/N52LhzFpeUuVz5YGuSWjc7TPHiFmVYZbPlSgExocO2GwbxVpSni9MVs5wwW+wZ4kPuwBEBN9pIPDYz1mA=="], - "@babel/preset-modules/@babel/types": ["@babel/types@8.0.4", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0", "@babel/helper-validator-identifier": "^8.0.4" } }, "sha512-eY+Yn3dCqTGmyiq2QRU66lA5FL8lqqqvecHt0fF3uHONIa7ToYsaCiWV8lOKqAs0Rb2SjixiKFROngnulPtt2g=="], + "@babel/plugin-transform-classes/@babel/traverse": ["@babel/traverse@8.0.6", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/generator": "^8.0.6", "@babel/helper-globals": "^8.0.6", "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", "@babel/types": "^8.0.6", "obug": "^2.1.1" } }, "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ=="], - "@babel/template/@babel/parser": ["@babel/parser@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ=="], + "@babel/template/@babel/parser": ["@babel/parser@8.0.6", "", { "dependencies": { "@babel/types": "^8.0.6" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg=="], "@babel/traverse/@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], @@ -1840,128 +1397,26 @@ "@babel/traverse/@babel/types": ["@babel/types@7.29.8", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg=="], - "@marijn/testtool/mocha": ["mocha@10.8.2", "", { "dependencies": { "ansi-colors": "^4.1.3", "browser-stdout": "^1.3.1", "chokidar": "^3.5.3", "debug": "^4.3.5", "diff": "^5.2.0", "escape-string-regexp": "^4.0.0", "find-up": "^5.0.0", "glob": "^8.1.0", "he": "^1.2.0", "js-yaml": "^4.1.0", "log-symbols": "^4.1.0", "minimatch": "^5.1.6", "ms": "^2.1.3", "serialize-javascript": "^6.0.2", "strip-json-comments": "^3.1.1", "supports-color": "^8.1.1", "workerpool": "^6.5.1", "yargs": "^16.2.0", "yargs-parser": "^20.2.9", "yargs-unparser": "^2.0.0" }, "bin": { "_mocha": "bin/_mocha", "mocha": "bin/mocha.js" } }, "sha512-VZlYo/WE8t1tstuRmqgeyBgCbJc/lEdopaa+axcKzTBJ+UIdlAB9XnmvTCAH4pwR4ElNInaedhEBmZD8iCSVEg=="], - - "@netflix/nerror/lodash": ["lodash@4.18.1", "", {}, "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q=="], - - "@npmcli/arborist/minimatch": ["minimatch@10.2.5", "", { "dependencies": { "brace-expansion": "^5.0.5" } }, "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg=="], - - "@npmcli/arborist/semver": ["semver@7.8.0", "", { "bin": "bin/semver.js" }, "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="], - - "@npmcli/fs/semver": ["semver@7.8.0", "", { "bin": "bin/semver.js" }, "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="], - - "@npmcli/git/semver": ["semver@7.8.0", "", { "bin": "bin/semver.js" }, "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="], - - "@npmcli/map-workspaces/glob": ["glob@13.0.6", "", { "dependencies": { "minimatch": "^10.2.2", "minipass": "^7.1.3", "path-scurry": "^2.0.2" } }, "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw=="], - - "@npmcli/map-workspaces/minimatch": ["minimatch@10.2.5", "", { "dependencies": { "brace-expansion": "^5.0.5" } }, "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg=="], - - "@npmcli/metavuln-calculator/json-parse-even-better-errors": ["json-parse-even-better-errors@5.0.0", "", {}, "sha512-ZF1nxZ28VhQouRWhUcVlUIN3qwSgPuswK05s/HIaoetAoE/9tngVmCHjSxmSQPav1nd+lPtTL0YZ/2AFdR/iYQ=="], - - "@npmcli/metavuln-calculator/semver": ["semver@7.8.0", "", { "bin": "bin/semver.js" }, "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="], - - "@npmcli/package-json/glob": ["glob@13.0.6", "", { "dependencies": { "minimatch": "^10.2.2", "minipass": "^7.1.3", "path-scurry": "^2.0.2" } }, "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw=="], - - "@npmcli/package-json/json-parse-even-better-errors": ["json-parse-even-better-errors@5.0.0", "", {}, "sha512-ZF1nxZ28VhQouRWhUcVlUIN3qwSgPuswK05s/HIaoetAoE/9tngVmCHjSxmSQPav1nd+lPtTL0YZ/2AFdR/iYQ=="], - - "@npmcli/package-json/semver": ["semver@7.8.0", "", { "bin": "bin/semver.js" }, "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="], - - "@tufjs/models/minimatch": ["minimatch@10.2.5", "", { "dependencies": { "brace-expansion": "^5.0.5" } }, "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg=="], - - "@types/chai/assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], - - "@vitest/expect/chai": ["chai@6.2.2", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="], - - "android-versions/semver": ["semver@7.8.5", "", { "bin": "bin/semver.js" }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], - "anymatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], - "bin-links/write-file-atomic": ["write-file-atomic@7.0.1", "", { "dependencies": { "signal-exit": "^4.0.1" } }, "sha512-OTIk8iR8/aCRWBqvxrzxR0hgxWpnYBblY1S5hDWBQfk/VFmJwzmJgQFN3WsoUKHISv2eAwe+PpbUzyL1CKTLXg=="], - - "cacache/glob": ["glob@13.0.6", "", { "dependencies": { "minimatch": "^10.2.2", "minipass": "^7.1.3", "path-scurry": "^2.0.2" } }, "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw=="], - - "chalk/supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], - - "cli/glob": ["glob@7.2.3", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="], - "cliui/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], - "cordova/semver": ["semver@7.8.0", "", { "bin": "bin/semver.js" }, "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="], - - "cordova-android/semver": ["semver@7.8.5", "", { "bin": "bin/semver.js" }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], - - "cordova-fetch/semver": ["semver@7.8.0", "", { "bin": "bin/semver.js" }, "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="], - - "cordova-fetch/which": ["which@5.0.0", "", { "dependencies": { "isexe": "^3.1.1" }, "bin": { "node-which": "bin/which.js" } }, "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ=="], - - "cordova-lib/semver": ["semver@7.8.0", "", { "bin": "bin/semver.js" }, "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="], - - "cordova-lib/write-file-atomic": ["write-file-atomic@7.0.1", "", { "dependencies": { "signal-exit": "^4.0.1" } }, "sha512-OTIk8iR8/aCRWBqvxrzxR0hgxWpnYBblY1S5hDWBQfk/VFmJwzmJgQFN3WsoUKHISv2eAwe+PpbUzyL1CKTLXg=="], - - "cosmiconfig/js-yaml": ["js-yaml@4.2.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": "bin/js-yaml.js" }, "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw=="], - - "cross-spawn/which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], - - "css-loader/semver": ["semver@7.8.0", "", { "bin": "bin/semver.js" }, "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="], - - "dom-serializer/domelementtype": ["domelementtype@2.3.0", "", {}, "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw=="], - - "dom-serializer/entities": ["entities@2.2.0", "", {}, "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A=="], - - "endent/dedent": ["dedent@0.7.0", "", {}, "sha512-Q6fKUPqnAHAyhiUgFU7BUzLiv0kd8saH9al7tnu5Q/okj6dnupxyTgFIBjVzJATdfIAm9NAsvXNzjaKa+bxVyA=="], - - "glob/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="], - - "htmlparser2/entities": ["entities@1.0.0", "", {}, "sha512-LbLqfXgJMmy81t+7c14mnulFHJ170cM6E+0vMXR9k/ZiZwgX8i5pNgjTCX3SO4VeUsFLV+8InixoretwU+MjBQ=="], - - "htmlparser2/readable-stream": ["readable-stream@1.1.14", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.1", "isarray": "0.0.1", "string_decoder": "~0.10.x" } }, "sha512-+MeVjFf4L44XUkhM1eYbD8fyEsxcV81pqMSR5gblfcLCHfZvbrqy4/qYHE+/R5HoBUT11WV5O08Cr1n3YXkWVQ=="], - - "ignore-walk/minimatch": ["minimatch@10.2.5", "", { "dependencies": { "brace-expansion": "^5.0.5" } }, "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg=="], - - "jshint/minimatch": ["minimatch@3.0.8", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-6FsRAQsxQ61mw+qP1ZzbL9Bc78x2p5OqNgNpnoAFLTrX8n5Kxph0CsnhmKKNXTWjXqU5L0pGPR7hYk+XWZr60Q=="], - - "jshint/strip-json-comments": ["strip-json-comments@1.0.4", "", { "bin": "cli.js" }, "sha512-AOPG8EBc5wAikaG1/7uFCNFJwnKOuQwFTpYBdTW6OvWHeZBQBrAA/amefHGrEiOnCPcLFZK6FUPtWVKpQVIRgg=="], - - "make-dir/semver": ["semver@6.3.1", "", { "bin": "bin/semver.js" }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + "jest-worker/supports-color": ["supports-color@8.1.1", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="], "markdown-it/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="], - "micromatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], - - "minipass-flush/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], - - "minipass-pipeline/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], - - "mocha/chokidar": ["chokidar@3.5.3", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw=="], - - "mocha/debug": ["debug@4.3.3", "", { "dependencies": { "ms": "2.1.2" } }, "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q=="], + "mocha/chokidar": ["chokidar@3.6.0", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="], "mocha/escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="], - "mocha/nanoid": ["nanoid@3.3.1", "", { "bin": "bin/nanoid.cjs" }, "sha512-n6Vs/3KGyxPQd6uO0eH4Bv0ojGSUvuLlIHtC3Y0kEO23YRge8H9x1GCzLn28YX0H66pMkxuaeESFq4tKISKwdw=="], - - "mocha/which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], - - "mocha/yargs": ["yargs@16.2.0", "", { "dependencies": { "cliui": "^7.0.2", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.0", "y18n": "^5.0.5", "yargs-parser": "^20.2.2" } }, "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw=="], - - "mocha/yargs-parser": ["yargs-parser@20.2.4", "", {}, "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA=="], + "mocha/supports-color": ["supports-color@8.1.1", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="], - "node-gyp/semver": ["semver@7.8.0", "", { "bin": "bin/semver.js" }, "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="], + "mocha/yargs": ["yargs@16.2.2", "", { "dependencies": { "cliui": "^7.0.2", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.0", "y18n": "^5.0.5", "yargs-parser": "^20.2.2" } }, "sha512-Nt9ZJjXTv5R8MHbqby/wXQ6Gi0Bb3TcYZkR1bzuL4yB2OxWPkXknz513gEF0GoA6tn00UpbPvERW8rzCuWCA6w=="], - "npm-install-checks/semver": ["semver@7.8.0", "", { "bin": "bin/semver.js" }, "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="], - - "npm-package-arg/semver": ["semver@7.8.0", "", { "bin": "bin/semver.js" }, "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="], - - "npm-pick-manifest/semver": ["semver@7.8.0", "", { "bin": "bin/semver.js" }, "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="], - - "parse-conflict-json/json-parse-even-better-errors": ["json-parse-even-better-errors@5.0.0", "", {}, "sha512-ZF1nxZ28VhQouRWhUcVlUIN3qwSgPuswK05s/HIaoetAoE/9tngVmCHjSxmSQPav1nd+lPtTL0YZ/2AFdR/iYQ=="], + "mocha/yargs-parser": ["yargs-parser@20.2.9", "", {}, "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w=="], "parse-json/@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], - "plist/xmlbuilder": ["xmlbuilder@15.1.1", "", {}, "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg=="], - - "postcss-loader/semver": ["semver@7.8.0", "", { "bin": "bin/semver.js" }, "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="], - "raw-loader/schema-utils": ["schema-utils@3.3.0", "", { "dependencies": { "@types/json-schema": "^7.0.8", "ajv": "^6.12.5", "ajv-keywords": "^3.5.2" } }, "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg=="], "sass/chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], @@ -1972,79 +1427,81 @@ "terser/commander": ["commander@2.20.3", "", {}, "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="], + "vscode-css-languageservice/vscode-languageserver-types": ["vscode-languageserver-types@3.17.5", "", {}, "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg=="], + "wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], "wrap-ansi/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], - "@babel/core/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + "@babel/core/@babel/generator/@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.4.0-beta.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w=="], + + "@babel/core/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.6", "", {}, "sha512-OdnA/N52LhzFpeUuVz5YGuSWjc7TPHiFmVYZbPlSgExocO2GwbxVpSni9MVs5wwW+wZ4kPuwBEBN9pIPDYz1mA=="], "@babel/generator/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="], "@babel/generator/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], - "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/generator": ["@babel/generator@8.0.6", "", { "dependencies": { "@babel/parser": "^8.0.6", "@babel/types": "^8.0.6", "@jridgewell/gen-mapping": "0.4.0-beta.0", "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng=="], - "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.6", "", {}, "sha512-OdnA/N52LhzFpeUuVz5YGuSWjc7TPHiFmVYZbPlSgExocO2GwbxVpSni9MVs5wwW+wZ4kPuwBEBN9pIPDYz1mA=="], - "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/parser": ["@babel/parser@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ=="], + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/parser": ["@babel/parser@8.0.6", "", { "dependencies": { "@babel/types": "^8.0.6" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg=="], - "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/generator": ["@babel/generator@8.0.6", "", { "dependencies": { "@babel/parser": "^8.0.6", "@babel/types": "^8.0.6", "@jridgewell/gen-mapping": "0.4.0-beta.0", "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng=="], - "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.6", "", {}, "sha512-OdnA/N52LhzFpeUuVz5YGuSWjc7TPHiFmVYZbPlSgExocO2GwbxVpSni9MVs5wwW+wZ4kPuwBEBN9pIPDYz1mA=="], - "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/parser": ["@babel/parser@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ=="], + "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/parser": ["@babel/parser@8.0.6", "", { "dependencies": { "@babel/types": "^8.0.6" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg=="], - "@babel/helper-module-imports/@babel/traverse/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + "@babel/helper-module-imports/@babel/traverse/@babel/generator": ["@babel/generator@8.0.6", "", { "dependencies": { "@babel/parser": "^8.0.6", "@babel/types": "^8.0.6", "@jridgewell/gen-mapping": "0.4.0-beta.0", "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng=="], - "@babel/helper-module-imports/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + "@babel/helper-module-imports/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.6", "", {}, "sha512-OdnA/N52LhzFpeUuVz5YGuSWjc7TPHiFmVYZbPlSgExocO2GwbxVpSni9MVs5wwW+wZ4kPuwBEBN9pIPDYz1mA=="], - "@babel/helper-module-imports/@babel/traverse/@babel/parser": ["@babel/parser@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ=="], + "@babel/helper-module-imports/@babel/traverse/@babel/parser": ["@babel/parser@8.0.6", "", { "dependencies": { "@babel/types": "^8.0.6" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg=="], - "@babel/helper-module-transforms/@babel/traverse/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + "@babel/helper-module-transforms/@babel/traverse/@babel/generator": ["@babel/generator@8.0.6", "", { "dependencies": { "@babel/parser": "^8.0.6", "@babel/types": "^8.0.6", "@jridgewell/gen-mapping": "0.4.0-beta.0", "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng=="], - "@babel/helper-module-transforms/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + "@babel/helper-module-transforms/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.6", "", {}, "sha512-OdnA/N52LhzFpeUuVz5YGuSWjc7TPHiFmVYZbPlSgExocO2GwbxVpSni9MVs5wwW+wZ4kPuwBEBN9pIPDYz1mA=="], - "@babel/helper-module-transforms/@babel/traverse/@babel/parser": ["@babel/parser@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ=="], + "@babel/helper-module-transforms/@babel/traverse/@babel/parser": ["@babel/parser@8.0.6", "", { "dependencies": { "@babel/types": "^8.0.6" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg=="], - "@babel/helper-remap-async-to-generator/@babel/traverse/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + "@babel/helper-remap-async-to-generator/@babel/traverse/@babel/generator": ["@babel/generator@8.0.6", "", { "dependencies": { "@babel/parser": "^8.0.6", "@babel/types": "^8.0.6", "@jridgewell/gen-mapping": "0.4.0-beta.0", "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng=="], - "@babel/helper-remap-async-to-generator/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + "@babel/helper-remap-async-to-generator/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.6", "", {}, "sha512-OdnA/N52LhzFpeUuVz5YGuSWjc7TPHiFmVYZbPlSgExocO2GwbxVpSni9MVs5wwW+wZ4kPuwBEBN9pIPDYz1mA=="], - "@babel/helper-remap-async-to-generator/@babel/traverse/@babel/parser": ["@babel/parser@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ=="], + "@babel/helper-remap-async-to-generator/@babel/traverse/@babel/parser": ["@babel/parser@8.0.6", "", { "dependencies": { "@babel/types": "^8.0.6" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg=="], - "@babel/helper-replace-supers/@babel/traverse/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + "@babel/helper-replace-supers/@babel/traverse/@babel/generator": ["@babel/generator@8.0.6", "", { "dependencies": { "@babel/parser": "^8.0.6", "@babel/types": "^8.0.6", "@jridgewell/gen-mapping": "0.4.0-beta.0", "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng=="], - "@babel/helper-replace-supers/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + "@babel/helper-replace-supers/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.6", "", {}, "sha512-OdnA/N52LhzFpeUuVz5YGuSWjc7TPHiFmVYZbPlSgExocO2GwbxVpSni9MVs5wwW+wZ4kPuwBEBN9pIPDYz1mA=="], - "@babel/helper-replace-supers/@babel/traverse/@babel/parser": ["@babel/parser@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ=="], + "@babel/helper-replace-supers/@babel/traverse/@babel/parser": ["@babel/parser@8.0.6", "", { "dependencies": { "@babel/types": "^8.0.6" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg=="], - "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/generator": ["@babel/generator@8.0.6", "", { "dependencies": { "@babel/parser": "^8.0.6", "@babel/types": "^8.0.6", "@jridgewell/gen-mapping": "0.4.0-beta.0", "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng=="], - "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.6", "", {}, "sha512-OdnA/N52LhzFpeUuVz5YGuSWjc7TPHiFmVYZbPlSgExocO2GwbxVpSni9MVs5wwW+wZ4kPuwBEBN9pIPDYz1mA=="], - "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/parser": ["@babel/parser@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ=="], + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/parser": ["@babel/parser@8.0.6", "", { "dependencies": { "@babel/types": "^8.0.6" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg=="], - "@babel/helper-wrap-function/@babel/traverse/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + "@babel/helper-wrap-function/@babel/traverse/@babel/generator": ["@babel/generator@8.0.6", "", { "dependencies": { "@babel/parser": "^8.0.6", "@babel/types": "^8.0.6", "@jridgewell/gen-mapping": "0.4.0-beta.0", "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng=="], - "@babel/helper-wrap-function/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + "@babel/helper-wrap-function/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.6", "", {}, "sha512-OdnA/N52LhzFpeUuVz5YGuSWjc7TPHiFmVYZbPlSgExocO2GwbxVpSni9MVs5wwW+wZ4kPuwBEBN9pIPDYz1mA=="], - "@babel/helper-wrap-function/@babel/traverse/@babel/parser": ["@babel/parser@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ=="], + "@babel/helper-wrap-function/@babel/traverse/@babel/parser": ["@babel/parser@8.0.6", "", { "dependencies": { "@babel/types": "^8.0.6" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg=="], "@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="], "@babel/parser/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], - "@babel/plugin-transform-async-generator-functions/@babel/traverse/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + "@babel/plugin-transform-async-generator-functions/@babel/traverse/@babel/generator": ["@babel/generator@8.0.6", "", { "dependencies": { "@babel/parser": "^8.0.6", "@babel/types": "^8.0.6", "@jridgewell/gen-mapping": "0.4.0-beta.0", "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng=="], - "@babel/plugin-transform-async-generator-functions/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + "@babel/plugin-transform-async-generator-functions/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.6", "", {}, "sha512-OdnA/N52LhzFpeUuVz5YGuSWjc7TPHiFmVYZbPlSgExocO2GwbxVpSni9MVs5wwW+wZ4kPuwBEBN9pIPDYz1mA=="], - "@babel/plugin-transform-async-generator-functions/@babel/traverse/@babel/parser": ["@babel/parser@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ=="], + "@babel/plugin-transform-async-generator-functions/@babel/traverse/@babel/parser": ["@babel/parser@8.0.6", "", { "dependencies": { "@babel/types": "^8.0.6" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg=="], - "@babel/plugin-transform-classes/@babel/traverse/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + "@babel/plugin-transform-classes/@babel/traverse/@babel/generator": ["@babel/generator@8.0.6", "", { "dependencies": { "@babel/parser": "^8.0.6", "@babel/types": "^8.0.6", "@jridgewell/gen-mapping": "0.4.0-beta.0", "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng=="], - "@babel/plugin-transform-classes/@babel/traverse/@babel/parser": ["@babel/parser@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ=="], - - "@babel/preset-modules/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.4", "", {}, "sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg=="], + "@babel/plugin-transform-classes/@babel/traverse/@babel/parser": ["@babel/parser@8.0.6", "", { "dependencies": { "@babel/types": "^8.0.6" }, "bin": { "parser": "bin/babel-parser.js" } }, "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg=="], "@babel/traverse/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], @@ -2054,68 +1511,8 @@ "@babel/traverse/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], - "@marijn/testtool/mocha/ansi-colors": ["ansi-colors@4.1.3", "", {}, "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw=="], - - "@marijn/testtool/mocha/chokidar": ["chokidar@3.6.0", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="], - - "@marijn/testtool/mocha/diff": ["diff@5.2.2", "", {}, "sha512-vtcDfH3TOjP8UekytvnHH1o1P4FcUdt4eQ1Y+Abap1tk/OB2MWQvcwS2ClCd1zuIhc3JKOx6p3kod8Vfys3E+A=="], - - "@marijn/testtool/mocha/escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="], - - "@marijn/testtool/mocha/glob": ["glob@8.1.0", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^5.0.1", "once": "^1.3.0" } }, "sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ=="], - - "@marijn/testtool/mocha/js-yaml": ["js-yaml@4.2.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": "bin/js-yaml.js" }, "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw=="], - - "@marijn/testtool/mocha/minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="], - - "@marijn/testtool/mocha/serialize-javascript": ["serialize-javascript@6.0.2", "", { "dependencies": { "randombytes": "^2.1.0" } }, "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g=="], - - "@marijn/testtool/mocha/workerpool": ["workerpool@6.5.1", "", {}, "sha512-Fs4dNYcsdpYSAfVxhnl1L5zTksjvOJxtC5hzMNl+1t9B8hTJTdKDyZ5ju7ztgPy+ft9tBFXoOlDNiOT9WUXZlA=="], - - "@marijn/testtool/mocha/yargs": ["yargs@16.2.2", "", { "dependencies": { "cliui": "^7.0.2", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.0", "y18n": "^5.0.5", "yargs-parser": "^20.2.2" } }, "sha512-Nt9ZJjXTv5R8MHbqby/wXQ6Gi0Bb3TcYZkR1bzuL4yB2OxWPkXknz513gEF0GoA6tn00UpbPvERW8rzCuWCA6w=="], - - "@marijn/testtool/mocha/yargs-parser": ["yargs-parser@20.2.9", "", {}, "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w=="], - - "@npmcli/arborist/minimatch/brace-expansion": ["brace-expansion@5.0.6", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g=="], - - "@npmcli/map-workspaces/minimatch/brace-expansion": ["brace-expansion@5.0.6", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g=="], - - "@npmcli/package-json/glob/minimatch": ["minimatch@10.2.5", "", { "dependencies": { "brace-expansion": "^5.0.5" } }, "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg=="], - - "@tufjs/models/minimatch/brace-expansion": ["brace-expansion@5.0.6", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g=="], - - "bin-links/write-file-atomic/signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="], - - "cacache/glob/minimatch": ["minimatch@10.2.5", "", { "dependencies": { "brace-expansion": "^5.0.5" } }, "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg=="], - - "cli/glob/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="], - - "cordova-fetch/which/isexe": ["isexe@3.1.5", "", {}, "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w=="], - - "cordova-lib/write-file-atomic/signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="], - - "cross-spawn/which/isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], - - "glob/minimatch/brace-expansion": ["brace-expansion@1.1.14", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g=="], - - "htmlparser2/readable-stream/isarray": ["isarray@0.0.1", "", {}, "sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ=="], - - "htmlparser2/readable-stream/string_decoder": ["string_decoder@0.10.31", "", {}, "sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ=="], - - "ignore-walk/minimatch/brace-expansion": ["brace-expansion@5.0.6", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g=="], - - "jshint/minimatch/brace-expansion": ["brace-expansion@1.1.14", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g=="], - - "minipass-flush/minipass/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], - - "minipass-pipeline/minipass/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], - "mocha/chokidar/readdirp": ["readdirp@3.6.0", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="], - "mocha/debug/ms": ["ms@2.1.2", "", {}, "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="], - - "mocha/which/isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], - "mocha/yargs/cliui": ["cliui@7.0.4", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^7.0.0" } }, "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ=="], "mocha/yargs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], @@ -2132,27 +1529,25 @@ "send/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], - "@marijn/testtool/mocha/chokidar/readdirp": ["readdirp@3.6.0", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="], - - "@marijn/testtool/mocha/minimatch/brace-expansion": ["brace-expansion@2.1.7", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g=="], + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/generator/@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.4.0-beta.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w=="], - "@marijn/testtool/mocha/yargs/cliui": ["cliui@7.0.4", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^7.0.0" } }, "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ=="], + "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/generator/@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.4.0-beta.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w=="], - "@marijn/testtool/mocha/yargs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + "@babel/helper-module-imports/@babel/traverse/@babel/generator/@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.4.0-beta.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w=="], - "@npmcli/arborist/minimatch/brace-expansion/balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], + "@babel/helper-module-transforms/@babel/traverse/@babel/generator/@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.4.0-beta.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w=="], - "@npmcli/map-workspaces/minimatch/brace-expansion/balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], + "@babel/helper-remap-async-to-generator/@babel/traverse/@babel/generator/@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.4.0-beta.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w=="], - "@npmcli/package-json/glob/minimatch/brace-expansion": ["brace-expansion@5.0.6", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g=="], + "@babel/helper-replace-supers/@babel/traverse/@babel/generator/@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.4.0-beta.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w=="], - "@tufjs/models/minimatch/brace-expansion/balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/generator/@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.4.0-beta.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w=="], - "cacache/glob/minimatch/brace-expansion": ["brace-expansion@5.0.6", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g=="], + "@babel/helper-wrap-function/@babel/traverse/@babel/generator/@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.4.0-beta.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w=="], - "cli/glob/minimatch/brace-expansion": ["brace-expansion@1.1.14", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g=="], + "@babel/plugin-transform-async-generator-functions/@babel/traverse/@babel/generator/@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.4.0-beta.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w=="], - "ignore-walk/minimatch/brace-expansion/balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], + "@babel/plugin-transform-classes/@babel/traverse/@babel/generator/@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.4.0-beta.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w=="], "mocha/chokidar/readdirp/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], @@ -2166,26 +1561,8 @@ "raw-loader/schema-utils/ajv/json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], - "@marijn/testtool/mocha/chokidar/readdirp/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], - - "@marijn/testtool/mocha/yargs/cliui/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], - - "@marijn/testtool/mocha/yargs/cliui/wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="], - - "@marijn/testtool/mocha/yargs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], - - "@marijn/testtool/mocha/yargs/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], - - "@npmcli/package-json/glob/minimatch/brace-expansion/balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], - - "cacache/glob/minimatch/brace-expansion/balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], - "mocha/yargs/cliui/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], "mocha/yargs/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], - - "@marijn/testtool/mocha/yargs/cliui/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], - - "@marijn/testtool/mocha/yargs/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], } } diff --git a/codemirror-lsp-client b/codemirror-lsp-client deleted file mode 160000 index db6930c2b6..0000000000 --- a/codemirror-lsp-client +++ /dev/null @@ -1 +0,0 @@ -Subproject commit db6930c2b6db67e14978f08ae8f5aeb149d29468 diff --git a/codemirror-lsp-client/.gitignore b/codemirror-lsp-client/.gitignore new file mode 100644 index 0000000000..eebad72f86 --- /dev/null +++ b/codemirror-lsp-client/.gitignore @@ -0,0 +1,7 @@ +/node_modules +package-lock.json +/dist +/test/*.js +/test/*.d.ts +/test/*.d.ts.map +.tern-* diff --git a/codemirror-lsp-client/CHANGELOG.md b/codemirror-lsp-client/CHANGELOG.md new file mode 100644 index 0000000000..95fdefb298 --- /dev/null +++ b/codemirror-lsp-client/CHANGELOG.md @@ -0,0 +1,91 @@ +## 6.2.5-acode.1 (2026-08-04) + +### New features + +Allow multiple LSP clients to bind to one editor, with per-client feature +selection, priority routing, independent document synchronization, and merged +completion and hover providers. + +## 6.2.5 (2026-06-09) + +### Bug fixes + +Strip backslash escapes in snippets in places where CodeMirror doesn't support them. + +Support the `extraTextEdits` field in completions. + +## 6.2.4 (2026-05-15) + +### Bug fixes + +Tell the server we prefer Markdown docs over plain text. + +Support completion-set-wide `insertTextFormat` options. + +Support separate filter and display names for completions. + +## 6.2.3 (2026-04-15) + +### Bug fixes + +Don't crash when trying to jump to a symbol that the server does not provide a location for. + +Fix the argument passed to cancel requests. + +## 6.2.2 (2026-03-02) + +### Bug fixes + +In completion snippets from the server, treat `$1` the same as `${1}`. + +## 6.2.1 (2025-11-20) + +### Bug fixes + +Support `sortText` properties on LSP completions. + +## 6.2.0 (2025-10-27) + +### New features + +`serverCompletion` now takes an option `validFor` that can be used to configure the regexp used in the result. + +## 6.1.2 (2025-09-10) + +### Bug fixes + +Fix an issue where snippet completions would display the snippet source as their label. + +## 6.1.1 (2025-09-02) + +### Bug fixes + +Properly declare the @codemirror/lint dependency. + +Make sure document changes are eagerly pushed to the server when `serverDiagnostics` is active. + +## 6.1.0 (2025-08-23) + +### New features + +`LSPClient` now accepts an array of extensions directly in its configuration. These can also add behavior (client capabilities and notification handlers) to the client itself. + +The new `serverDiagnostics` extension makes the client receive diagnostics from the server, and show them via the CodeMirror linter. + +The new `languageServerExtensions` function provides an extension bundle interface, that works for client extensions as well as editor extensions. + +`LSPClient` now has a `plugin` method for conveniently creating an editor extension. `LSPPlugin.create` is deprecated in favor of this method. + +## 6.0.1 (2025-08-05) + +### Bug fixes + +Fix a bug that prevented reuse of completions when adding to the completed identifier. + +Properly render plain strings included in arrays for a hover tooltip's `content` data as Markdown content. + +## 6.0.0 (2025-07-02) + +### Breaking changes + +First numbered release. diff --git a/codemirror-lsp-client/LICENSE b/codemirror-lsp-client/LICENSE new file mode 100644 index 0000000000..75a4b63481 --- /dev/null +++ b/codemirror-lsp-client/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2025 by Marijn Haverbeke and others + +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/codemirror-lsp-client/README.md b/codemirror-lsp-client/README.md new file mode 100644 index 0000000000..452e433d43 --- /dev/null +++ b/codemirror-lsp-client/README.md @@ -0,0 +1,95 @@ +# @codemirror/lsp-client [![NPM version](https://img.shields.io/npm/v/@codemirror/lsp-client.svg)](https://www.npmjs.org/package/@codemirror/lsp-client) + +[ [**WEBSITE**](https://codemirror.net/) | [**DOCS**](https://codemirror.net/docs/ref/#lsp-client) | [**ISSUES**](https://code.haverbeke.berlin/codemirror/dev/issues) | [**FORUM**](https://discuss.codemirror.net/c/v6/) | [**CHANGELOG**](https://code.haverbeke.berlin/codemirror/lsp-client/src/branch/main/CHANGELOG.md) ] + +This package implements a language server protocol (LSP) client for +the [CodeMirror](https://codemirror.net/) code editor. + +The [project page](https://codemirror.net/) has more information, a +number of [examples](https://codemirror.net/examples/) and the +[documentation](https://codemirror.net/docs/ref/#lsp-client). + +This code is released under an +[MIT license](https://code.haverbeke.berlin/codemirror/lsp-client/tree/main/LICENSE). + +We aim to be an inclusive, welcoming community. To make that explicit, +we have a [code of +conduct](http://contributor-covenant.org/version/1/1/0/) that applies +to communication around the project. + +## Usage + +There are various ways to run a language server and connect it to a +web page. You can run it on the server and proxy it through a web +socket, or, if it is written in JavaScript or can be compiled to WASM, +run it directly in the client. The @codemirror/lsp-client package +talks to the server through a ([`Transport`](#lsp-client.Transport)) +object, which exposes a small interface for sending and receiving JSON +messages. + +Responsibility for how to actually talk to the server, how to connect +and to handle disconnects are left to the code that implements the +transport. + +## Multiple servers per editor (Acode fork) + +This Acode Foundation fork allows several independent clients to attach to the +same `EditorView`. For example, TypeScript can be the primary provider while +Tailwind CSS contributes completions, hover information, and diagnostics. + +```javascript +new EditorView({ + extensions: [ + typescriptClient.plugin(uri, "typescriptreact", {priority: 100}), + tailwindClient.plugin(uri, "typescriptreact", { + priority: 50, + features: {formatting: false, rename: false} + }) + ] +}) +``` + +Bindings are ordered by descending `priority`. Completion and hover results +are combined across eligible providers. Features that need one owner, such as +formatting, rename, navigation, and signature help, use the first capable +eligible binding. A feature is enabled unless its binding sets that feature to +`false`. + +Document edits are recorded once per editor. Each client keeps an independent +sync revision, and its pending `ChangeSet` is composed lazily only when that +client synchronizes. Thus, attaching idle supplemental clients does not add a +per-client loop to the typing path. + +This example uses a crude transport that doesn't handle errors at all. + + +```javascript +import {Transport, LSPClient, languageServerExtensions} from "@codemirror/lsp-client" +import {basicSetup, EditorView} from "codemirror" +import {typescriptLanguage} from "@codemirror/lang-javascript" + +function simpleWebSocketTransport(uri: string): Promise { + let handlers: ((value: string) => void)[] = [] + let sock = new WebSocket(uri) + sock.onmessage = e => { for (let h of handlers) h(e.data.toString()) } + return new Promise(resolve => { + sock.onopen = () => resolve({ + send(message: string) { sock.send(message) }, + subscribe(handler: (value: string) => void) { handlers.push(handler) }, + unsubscribe(handler: (value: string) => void) { handlers = handlers.filter(h => h != handler) } + }) + }) +} + +let transport = await simpleWebSocketTransport("ws://host:port") +let client = new LSPClient({extensions: languageServerExtensions()}).connect(transport) + +new EditorView({ + extensions: [ + basicSetup, + typescriptLanguage, + client.plugin("file:///some/file.ts"), + ], + parent: document.body +}) +``` diff --git a/codemirror-lsp-client/UPSTREAM.md b/codemirror-lsp-client/UPSTREAM.md new file mode 100644 index 0000000000..1a183fe670 --- /dev/null +++ b/codemirror-lsp-client/UPSTREAM.md @@ -0,0 +1,33 @@ +# Upstream + +- Repository: https://code.haverbeke.berlin/codemirror/lsp-client +- Imported package: `@codemirror/lsp-client@6.2.5` +- License: MIT; the original notice is preserved in `LICENSE` +- Imported on: 2026-08-04 + +This repository is Acode Foundation's standalone fork. Its primary change is +support for attaching multiple independent LSP clients to one CodeMirror +`EditorView`. + +Keep upstream imports and Acode changes in separate commits when practical. + +To sync a release: + +1. Download or clone the new upstream version into a temporary directory. +2. Diff its `src`, `test`, `README.md`, `CHANGELOG.md`, `LICENSE`, and + `package.json` against this directory. +3. Apply upstream-only changes first, keeping this package's local metadata and + the multi-client changes described in the Acode changelog. +4. Run Acode's typecheck, `tests/unit/lspMultiClient.test.js`, full unit suite, + and production build. + +Keep the canonical repository configured as the `upstream` remote: + +```shell +git remote add upstream https://code.haverbeke.berlin/codemirror/lsp-client.git +git fetch upstream --tags +``` + +Acode consumes an exact commit of this repository through its package +manifest. After publishing a new fork commit, update that commit hash in +Acode's `package.json` and lockfiles. diff --git a/codemirror-lsp-client/bin/tsserver-ws.js b/codemirror-lsp-client/bin/tsserver-ws.js new file mode 100644 index 0000000000..6c649bc72a --- /dev/null +++ b/codemirror-lsp-client/bin/tsserver-ws.js @@ -0,0 +1,64 @@ +import {WebSocketServer} from "ws" +import {spawn} from "node:child_process" +import {join} from "node:path" + +let project = join(import.meta.dirname, "..", "test") + +let server = new WebSocketServer({port: 8777}) + +class MessageReader { + message = "" + pending = -1 + + constructor(onMessage) { this.onMessage = onMessage } + + data(data) { + this.message += data + console.log("GET ", data) + for (;;) { + if (this.pending == -1) { + let brk = this.message.indexOf("\r\n\r\n") + if (brk < 0) break + let len = /content-length: (\d+)/i.exec(this.message.slice(0, brk)) + if (!len) throw new Error("Missing content-length header") + this.message = this.message.slice(brk + 4) + this.pending = +len[1] + console.log("parsed header", this.pending, "msg=", this.message) + } else if (this.pending <= this.message.length) { + console.log('finished', this.pending) + this.onMessage(this.message.slice(0, this.pending)) + this.message = this.message.slice(this.pending) + this.pending = -1 + } else { + console.log("out") + break + } + } + } +} + +server.on("connection", sock => { + console.log("New connection") + let ts = spawn(join(import.meta.dirname, "..", "..", "node_modules", ".bin", "typescript-language-server"), ["--stdio"], { + cwd: project, + encoding: "utf8", + stdio: ["pipe", "pipe", process.stderr] + }) + let reader = new MessageReader(message => { + console.log("==> " + message) + sock.send(message) + }) + ts.stdout.on("data", blob => reader.data(blob.toString("utf8"))) + ts.on("close", () => { + sock.close() + }) + sock.on("error", console.error) + sock.on("message", data => { + console.log("<== " + data) + ts.stdin.write(`Content-Length: ${data.length}\r\n\r\n${data}`) + }) + sock.on("close", () => { + console.log("Closed") + ts.kill() + }) +}) diff --git a/codemirror-lsp-client/package.json b/codemirror-lsp-client/package.json new file mode 100644 index 0000000000..aae85018e5 --- /dev/null +++ b/codemirror-lsp-client/package.json @@ -0,0 +1,40 @@ +{ + "name": "@codemirror/lsp-client", + "version": "6.2.5-acode.1", + "description": "Acode Foundation's multi-server language protocol client for CodeMirror", + "keywords": [ + "codemirror", + "lsp" + ], + "license": "MIT", + "author": "Marijn Haverbeke ", + "repository": { + "type": "git", + "url": "git+https://github.com/Acode-Foundation/codemirror-lsp-client.git" + }, + "bugs": { + "url": "https://github.com/Acode-Foundation/codemirror-lsp-client/issues" + }, + "type": "module", + "main": "dist/index.js", + "scripts": { + "test": "cm-runtests", + "prepare": "cm-buildhelper src/index.ts" + }, + "dependencies": { + "marked": "^15.0.12", + "@codemirror/autocomplete": "^6.20.0", + "@codemirror/language": "^6.11.0", + "@codemirror/lint": "^6.8.5", + "@codemirror/state": "^6.5.2", + "@codemirror/view": "^6.37.0", + "@lezer/highlight": "^1.2.1", + "vscode-languageserver-protocol": "^3.17.5" + }, + "devDependencies": { + "@codemirror/buildhelper": "^1.0.0", + "@codemirror/lang-javascript": "^6.0.0", + "typescript": "^5.8.3", + "typescript-language-server": "^4.3.4" + } +} diff --git a/codemirror-lsp-client/src/README.md b/codemirror-lsp-client/src/README.md new file mode 100644 index 0000000000..e896d606a5 --- /dev/null +++ b/codemirror-lsp-client/src/README.md @@ -0,0 +1,67 @@ +### Client + +@LSPClient + +@LSPClientConfig + +@LSPClientExtension + +@Transport + +@LSPPlugin + +@WorkspaceMapping + +### Workspaces + +@Workspace + +@WorkspaceFile + +### Extensions + +@languageServerExtensions + +@languageServerSupport + +@serverCompletion + +@serverCompletionSource + +@serverDiagnostics + +@hoverTooltips + +@formatDocument + +@formatKeymap + +@renameSymbol + +@renameKeymap + +@signatureHelp + +@showSignatureHelp + +@nextSignature + +@prevSignature + +@signatureKeymap + +@jumpToDefinition + +@jumpToDeclaration + +@jumpToTypeDefinition + +@jumpToImplementation + +@jumpToDefinitionKeymap + +@findReferences + +@closeReferencePanel + +@findReferencesKeymap diff --git a/codemirror-lsp-client/src/client.ts b/codemirror-lsp-client/src/client.ts new file mode 100644 index 0000000000..bee1c2eff6 --- /dev/null +++ b/codemirror-lsp-client/src/client.ts @@ -0,0 +1,512 @@ +import type * as lsp from "vscode-languageserver-protocol" +import {showDialog} from "@codemirror/view" +import {ChangeSet, ChangeDesc, MapMode, Text, Extension} from "@codemirror/state" +import {Language} from "@codemirror/language" +import {LSPPlugin, LSPPluginOptions, lspPluginBinding} from "./plugin" +import {toPosition, fromPosition} from "./pos" +import {Workspace, WorkspaceFile, DefaultWorkspace} from "./workspace" +import {lspTheme} from "./theme" + +class Request { + declare resolve: (result: Result) => void + declare reject: (error: any) => void + promise: Promise + + constructor( + readonly id: number, + readonly params: any, + readonly timeout: ReturnType + ) { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve + this.reject = reject + }) + } +} + +const clientCapabilities: lsp.ClientCapabilities = { + general: { + markdown: { + parser: "marked", + }, + }, + textDocument: { + completion: { + completionItem: { + snippetSupport: true, + documentationFormat: ["markdown", "plaintext"], + insertReplaceSupport: false, + }, + completionList: { + itemDefaults: ["commitCharacters", "editRange", "insertTextFormat"] + }, + completionItemKind: {valueSet: []}, + contextSupport: true, + }, + hover: { + contentFormat: ["markdown", "plaintext"] + }, + formatting: {}, + rename: {}, + signatureHelp: { + contextSupport: true, + signatureInformation: { + documentationFormat: ["markdown", "plaintext"], + parameterInformation: {labelOffsetSupport: true}, + activeParameterSupport: true, + }, + }, + definition: {}, + declaration: {}, + implementation: {}, + typeDefinition: {}, + references: {}, + diagnostic: {}, + }, + window: { + showMessage: {} + } +} + +/// A workspace mapping is used to track changes made to open +/// documents, so that positions returned by a request can be +/// interpreted in terms of the current, potentially changed document. +export class WorkspaceMapping { + /// @internal + mappings: Map = new Map + private startDocs: Map = new Map + + /// @internal + constructor(private client: LSPClient) { + for (let file of client.workspace.files) { + this.mappings.set(file.uri, ChangeSet.empty(file.doc.length)) + this.startDocs.set(file.uri, file.doc) + } + } + + /// @internal + addChanges(uri: string, changes: ChangeDesc) { + let known = this.mappings.get(uri) + if (known) this.mappings.set(uri, known.composeDesc(changes)) + } + + /// Get the changes made to the document with the given URI since + /// the mapping was created. Returns null for documents that aren't + /// open. + getMapping(uri: string) { + let known = this.mappings.get(uri) + if (!known) return null + let file = this.client.workspace.getFile(uri), view = file?.getView(), plugin = view && LSPPlugin.get(view, this.client) + return plugin ? known.composeDesc(plugin.unsyncedChanges) : known + } + + /// Map a position in the given file forward to the current document state. + mapPos(uri: string, pos: number, assoc?: number): number + mapPos(uri: string, pos: number, assoc: number, mode: MapMode): number | null + mapPos(uri: string, pos: number, assoc = -1, mode: MapMode = MapMode.Simple): number | null { + let changes = this.getMapping(uri) + return changes ? changes.mapPos(pos, assoc, mode) : pos + } + + /// Convert an LSP-style position referring to a document at the + /// time the mapping was created to an offset in the current document. + mapPosition(uri: string, pos: lsp.Position, assoc?: number): number + mapPosition(uri: string, pos: lsp.Position, assoc: number, mode: MapMode): number | null + mapPosition(uri: string, pos: lsp.Position, assoc = -1, mode: MapMode = MapMode.Simple): number | null { + let start = this.startDocs.get(uri) + if (!start) throw new Error("Cannot map from a file that's not in the workspace") + let off = fromPosition(start, pos) + let changes = this.getMapping(uri) + return changes ? changes.mapPos(off, assoc, mode) : off + } + + /// Disconnect this mapping from the client so that it will no + /// longer be notified of new changes. You must make sure to call + /// this on every mapping you create, except when you use + /// [`withMapping`](#lsp-client.LSPClient.withMapping), which will + /// automatically schedule a disconnect when the given promise + /// resolves or aborts. + destroy() { + this.client.activeMappings = this.client.activeMappings.filter(m => m != this) + } +} + +/// An object of this type should be used to wrap whatever transport +/// layer you use to talk to your language server. Messages should +/// contain only the JSON messages, no LSP headers. +export type Transport = { + /// Send a message to the server. Should throw if the connection is + /// broken somehow. + send(message: string): void + /// Register a handler for messages coming from the server. + subscribe(handler: (value: string) => void): void + /// Unregister a handler registered with `subscribe`. + unsubscribe(handler: (value: string) => void): void +} + +const defaultNotificationHandlers: {[method: string]: (client: LSPClient, params: any) => void} = { + "window/logMessage": (client, params: lsp.LogMessageParams) => { + if (params.type == 1) console.error("[lsp] " + params.message) + else if (params.type == 2) console.warn("[lsp] " + params.message) + }, + "window/showMessage": (client, params: lsp.ShowMessageParams) => { + if (params.type > 3 /* Info */) return + let view + for (let f of client.workspace.files) if (view = f.getView()) break + if (view) showDialog(view, { + label: params.message, + class: "cm-lsp-message cm-lsp-message-" + (params.type == 1 ? "error" : params.type == 2 ? "warning" : "info"), + top: true + }) + } +} + +/// Configuration options that can be passed to the LSP client. +export type LSPClientConfig = { + /// The project root URI passed to the server, when necessary. + rootUri?: string + /// An optional function to create a + /// [workspace](#lsp-client.Workspace) object for the client to use. + /// When not given, this will default to a simple workspace that + /// only opens files that have an active editor, and only allows one + /// editor per file. + workspace?: (client: LSPClient) => Workspace + /// The amount of milliseconds after which requests are + /// automatically timed out. Defaults to 3000. + timeout?: number + /// LSP servers can send Markdown code, which the client must render + /// and display as HTML. Markdown can contain arbitrary HTML and is + /// thus a potential channel for cross-site scripting attacks, if + /// someone is able to compromise your LSP server or your connection + /// to it. You can pass an HTML sanitizer here to strip out + /// suspicious HTML structure. + sanitizeHTML?: (html: string) => string + /// By default, the Markdown renderer will only be able to highlght + /// code embedded in the Markdown text when its language tag matches + /// the name of the language used by the editor. You can provide a + /// function here that returns a CodeMirror language object for a + /// given language tag to support more languages. + highlightLanguage?: (name: string) => Language | null + /// By default, the client will only handle the server notifications + /// `window/logMessage` (logging warnings and errors to the console) + /// and `window/showMessage`. You can pass additional handlers here. + /// They will be tried before the built-in handlers, and override + /// those when they return true. + notificationHandlers?: {[method: string]: (client: LSPClient, params: any) => boolean} + /// When no handler is found for a notification, it will be passed + /// to this function, if given. + unhandledNotification?: (client: LSPClient, method: string, params: any) => void + /// Provide a set of extensions, which may be plain CodeMirror + /// extensions, or objects containing additional client capabilities + /// or notification handlers. Any CodeMirror extensions provided + /// here will be included in the extension returned by + /// [`LSPPlugin.create`](#lsp-client.LSPPlugin^create). + extensions?: readonly (Extension | LSPClientExtension)[] +} + +/// Objects of this type can be included in the +/// [`extensions`](#lsp-client.LSPClientConfig.extensions) option to +/// `LSPClient` to modularly configure client capabilities or +/// notification handlers. +export type LSPClientExtension = { + /// Extra [client + /// capabilities](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#clientCapabilities) + /// to send to the server when initializing. The object provided + /// here will be merged with the capabilities the client provides by + /// default. + clientCapabilities?: Record, + /// Additional [notification + /// handlers](#lsp-client.LSPClientConfig.notificationHandlers). + /// These will be tried after notification handlers defined directly + /// in the config object, and then in order of appearance in the + /// [`extensions`](#lsp-client.LSPClientConfig.extensions) array. + notificationHandlers?: {[method: string]: (client: LSPClient, params: any) => boolean}, + /// An optional CodeMirror extension to include. + editorExtension?: Extension +} + +/// An LSP client manages a connection to a language server. It should +/// be explicitly [connected](#lsp-client.LSPClient.connect) before +/// use. +export class LSPClient { + /// @internal + transport: Transport | null = null + /// The client's [workspace](#lsp-client.Workspace). + workspace: Workspace + private nextReqID = 0 + private requests: Request[] = [] + /// @internal + activeMappings: WorkspaceMapping[] = [] + /// The capabilities advertised by the server. Will be null when not + /// connected or initialized. + serverCapabilities: lsp.ServerCapabilities | null = null + private supportSync = -1 + /// A promise that resolves once the client connection is initialized. Will be + /// replaced by a new promise object when you call `disconnect`. + initializing: Promise + declare private init: {resolve: (value: null) => void, reject: (err: any) => void} + private timeout: number + /// @internal + extensions: Extension[] = [] + + /// Create a client object. + constructor( + /// @internal + readonly config: LSPClientConfig = {} + ) { + this.receiveMessage = this.receiveMessage.bind(this) + this.initializing = new Promise((resolve, reject) => this.init = {resolve, reject}) + this.timeout = config.timeout ?? 3000 + this.workspace = config.workspace ? config.workspace(this) : new DefaultWorkspace(this) + + if (config.extensions) for (let ext of config.extensions) { + if (Array.isArray(ext) || (ext as any).extension) this.extensions.push(ext as Extension) + else if ((ext as LSPClientExtension).editorExtension) this.extensions.push((ext as LSPClientExtension).editorExtension!) + } + } + + /// Whether this client is connected (has a transport). + get connected() { return !!this.transport } + + /// Connect this client to a server over the given transport. Will + /// immediately start the initialization exchange with the server, + /// and resolve `this.initializing` (which it also returns) when + /// successful. + connect(transport: Transport) { + if (this.transport) this.transport.unsubscribe(this.receiveMessage) + this.transport = transport + transport.subscribe(this.receiveMessage) + let capabilities = clientCapabilities + if (this.config.extensions) for (let ext of this.config.extensions) { + let {clientCapabilities} = ext as LSPClientExtension + if (clientCapabilities) capabilities = mergeCapabilities(capabilities, clientCapabilities) + } + this.requestInner("initialize", { + processId: null, + clientInfo: {name: "@codemirror/lsp-client"}, + rootUri: this.config.rootUri || null, + capabilities + }).promise.then(resp => { + this.serverCapabilities = resp.capabilities + let sync = resp.capabilities.textDocumentSync + this.supportSync = sync == null ? 0 : typeof sync == "number" ? sync : sync.change ?? 0 + transport.send(JSON.stringify({jsonrpc: "2.0", method: "initialized", params: {}})) + this.init.resolve(null) + }, this.init.reject) + this.workspace.connected() + return this + } + + /// Disconnect the client from the server. + disconnect() { + if (this.transport) this.transport.unsubscribe(this.receiveMessage) + this.serverCapabilities = null + this.initializing = new Promise((resolve, reject) => this.init = {resolve, reject}) + this.workspace.disconnected() + } + + /// Create a plugin for this client, to add to an editor + /// configuration. This extension is necessary to use LSP-related + /// functionality exported by this package. The returned extension + /// will include the editor + /// extensions included in this client's + /// [configuration](#lsp-client.LSPClientConfig.extensions). + /// + /// Creating an editor with this plugin will cause + /// [`openFile`](#lsp-client.Workspace.openFile) to be called on the + /// workspace. + /// + /// By default, the language ID given to the server for this file is + /// derived from the editor's language configuration via + /// [`Language.name`](#language.Language.name). You can pass in + /// a specific ID as a third parameter. + plugin(fileURI: string, languageID?: string, options?: LSPPluginOptions): Extension { + return [ + lspPluginBinding({client: this, uri: fileURI, languageID, options}), + lspTheme, + this.extensions + ] + } + + /// Send a `textDocument/didOpen` notification to the server. + didOpen(file: WorkspaceFile) { + this.notification("textDocument/didOpen", { + textDocument: { + uri: file.uri, + languageId: file.languageId, + text: file.doc.toString(), + version: file.version + } + }) + } + + /// Send a `textDocument/didClose` notification to the server. + didClose(uri: string) { + this.notification("textDocument/didClose", {textDocument: {uri}}) + } + + private receiveMessage(msg: string) { + const value = JSON.parse(msg) as lsp.ResponseMessage | lsp.NotificationMessage | lsp.RequestMessage + if ("id" in value && !("method" in value)) { + let index = this.requests.findIndex(r => r.id == value.id) + if (index < 0) { + console.warn(`[lsp] Received a response for non-existent request ${value.id}`) + } else { + let req = this.requests[index] + clearTimeout(req.timeout) + this.requests.splice(index, 1) + if (value.error) req.reject(value.error) + else req.resolve(value.result) + } + } else if (!("id" in value)) { + let handler = this.config.notificationHandlers?.[value.method] + if (handler && handler(this, value.params)) return + if (this.config.extensions) for (let ext of this.config.extensions) { + let {notificationHandlers} = ext as LSPClientExtension + let handler = notificationHandlers?.[value.method] + if (handler && handler(this, value.params)) return + } + let deflt = defaultNotificationHandlers[value.method] + if (deflt) deflt(this, value.params) + else if (this.config.unhandledNotification) this.config.unhandledNotification(this, value.method, value.params) + } else { + let resp: lsp.ResponseMessage = { + jsonrpc: "2.0", + id: value.id, + error: {code: -32601 /* MethodNotFound */, message: "Method not implemented"} + } + this.transport!.send(JSON.stringify(resp)) + } + } + + /// Make a request to the server. Returns a promise that resolves to + /// the response or rejects with a failure message. You'll probably + /// want to use types from the `vscode-languageserver-protocol` + /// package for the type parameters. + /// + /// The caller is responsible for + /// [synchronizing](#lsp-client.LSPClient.sync) state before the + /// request and correctly handling state drift caused by local + /// changes that happened during the request. + request(method: string, params: Params): Promise { + if (!this.transport) return Promise.reject(new Error("Client not connected")) + return this.initializing.then(() => this.requestInner(method, params).promise) + } + + private requestInner( + method: string, + params: Params, + mapped = false + ): Request { + let id = ++this.nextReqID, data: lsp.RequestMessage = { + jsonrpc: "2.0", + id, + method, + params: params as any + } + let req = new Request(id, params, setTimeout(() => this.timeoutRequest(req), this.timeout)) + this.requests.push(req) + try { this.transport!.send(JSON.stringify(data)) } + catch(e) { req.reject(e) } + return req + } + + /// Send a notification to the server. + notification(method: string, params: Params) { + if (!this.transport) return + this.initializing.then(() => { + let data: lsp.NotificationMessage = { + jsonrpc: "2.0", + method, + params: params as any + } + this.transport!.send(JSON.stringify(data)) + }) + } + + /// Cancel the in-progress request with the given parameter value + /// (which is compared by identity). + cancelRequest(params: any) { + let found = this.requests.find(r => r.params === params) + if (found) this.notification("$/cancelRequest", {id: found.id}) + } + + /// @internal + hasCapability(name: keyof lsp.ServerCapabilities) { + return this.serverCapabilities ? !!this.serverCapabilities[name] : null + } + + /// Create a [workspace mapping](#lsp-client.WorkspaceMapping) that + /// tracks changes to files in this client's workspace, relative to + /// the moment where it was created. Make sure you call + /// [`destroy`](#lsp-client.WorkspaceMapping.destroy) on the mapping + /// when you're done with it. + workspaceMapping() { + let mapping = new WorkspaceMapping(this) + this.activeMappings.push(mapping) + return mapping + } + + /// Run the given promise with a [workspace + /// mapping](#lsp-client.WorkspaceMapping) active. Automatically + /// release the mapping when the promise resolves or rejects. + withMapping(f: (mapping: WorkspaceMapping) => Promise): Promise { + let mapping = this.workspaceMapping() + return f(mapping).finally(() => mapping.destroy()) + } + + /// Push any [pending changes](#lsp-client.Workspace.syncFiles) in + /// the open files to the server. You'll want to call this before + /// most types of requests, to make sure the server isn't working + /// with outdated information. + sync() { + for (let {file, changes, prevDoc} of this.workspace.syncFiles()) { + for (let mapping of this.activeMappings) + mapping.addChanges(file.uri, changes) + if (this.supportSync) this.notification("textDocument/didChange", { + textDocument: {uri: file.uri, version: file.version}, + contentChanges: contentChangesFor(file, prevDoc, changes, this.supportSync == 2 /* Incremental */) + }) + } + } + + private timeoutRequest(req: Request) { + let index = this.requests.indexOf(req) + if (index > -1) { + req.reject(new Error("Request timed out")) + this.requests.splice(index, 1) + } + } +} + +const enum Sync { AlwaysIfSmaller = 1024 } + +function contentChangesFor( + file: WorkspaceFile, + startDoc: Text, + changes: ChangeSet, + supportInc: boolean +): lsp.TextDocumentContentChangeEvent[] { + if (!supportInc || file.doc.length < Sync.AlwaysIfSmaller) + return [{text: file.doc.toString()}] + let events: lsp.TextDocumentContentChangeEvent[] = [] + changes.iterChanges((fromA, toA, fromB, toB, inserted) => { + events.push({ + range: {start: toPosition(startDoc, fromA), end: toPosition(startDoc, toA)}, + text: inserted.toString() + }) + }) + return events.reverse() +} + +function mergeCapabilities(base: any, add?: any) { + if (add == null) return base + if (typeof base != "object" || typeof add != "object") return add + let result: Record = {} + let baseProps = Object.keys(base), addProps = Object.keys(add) + for (let prop of baseProps) + result[prop] = addProps.indexOf(prop) > -1 ? mergeCapabilities(base[prop], add[prop]) : base[prop] + for (let prop of addProps) + if (baseProps.indexOf(prop) < 0) result[prop] = add[prop] + return result +} diff --git a/codemirror-lsp-client/src/completion.ts b/codemirror-lsp-client/src/completion.ts new file mode 100644 index 0000000000..1a40af5821 --- /dev/null +++ b/codemirror-lsp-client/src/completion.ts @@ -0,0 +1,287 @@ +import type * as lsp from "vscode-languageserver-protocol" +import {EditorState, Extension, Facet, ChangeDesc, ChangeSpec} from "@codemirror/state" +import {EditorView} from "@codemirror/view" +import {CompletionSource, Completion, CompletionResult, CompletionContext, + snippet, autocompletion, insertCompletionText} from "@codemirror/autocomplete" +import {LSPPlugin} from "./plugin" +import {fromPositionChecked} from "./pos" + +// Convert from LSP's snippet syntax to @codemirror/autocompletion's +// one. Remove backslashes before `$}]`, which don't support backslash +// escapes in CodeMirror, and expand `$1` to `${1}`. +function lspToSnippet(text: string): string { + return text.replace(/\\([$}\\])|\$(\d+)/g, (_m, esc, field) => esc || `\${${field}}`) +} + +/// Register the [language server completion +/// source](#lsp-client.serverCompletionSource) as an autocompletion +/// source. +let defaultServerCompletion: Extension | null = null + +export function serverCompletion(config: { + /// By default, the completion source that asks the language server + /// for completions is added as a regular source, in addition to any + /// other sources. Set this to true to make it replace all + /// completion sources. + override?: boolean + /// Set a custom + /// [`validFor`](#autocomplete.CompletionResult.validFor) expression + /// to use in the completion results. By default, the library uses an + /// expression that accepts word characters, optionally prefixed by + /// any non-word prefixes found in the results. + validFor?: RegExp +} = {}): Extension { + if (!config.override && !config.validFor && defaultServerCompletion) + return defaultServerCompletion + let result: Extension[] + if (config.override) { + result = [autocompletion({override: [serverCompletionSource]})] + } else { + let data = [{autocomplete: serverCompletionSource}] + result = [autocompletion(), EditorState.languageData.of(() => data)] + } + if (config.validFor) result.push(completionConfig.of({validFor: config.validFor})) + if (!config.override && !config.validFor) defaultServerCompletion = result + return result +} + +const completionConfig = Facet.define<{validFor: RegExp}, {validFor: RegExp | null}>({ + combine: results => results.length ? results[0] : {validFor: null} +}) + +function getCompletions(plugin: LSPPlugin, pos: number, context: lsp.CompletionContext, abort?: CompletionContext) { + if (plugin.client.hasCapability("completionProvider") === false) return Promise.resolve(null) + plugin.client.sync() + let params: lsp.CompletionParams = { + position: plugin.toPosition(pos), + textDocument: {uri: plugin.uri}, + context + } + if (abort) abort.addEventListener("abort", () => plugin.client.cancelRequest(params)) + return plugin.client.request( + "textDocument/completion", params) +} + +// Look for non-alphanumeric prefixes in the completions, and return a +// regexp that matches them, to use in validFor +function prefixRegexp(items: readonly lsp.CompletionItem[]) { + let step = Math.ceil(items.length / 50), prefixes: string[] = [] + for (let i = 0; i < items.length; i += step) { + let item = items[i], text = item.textEdit?.newText || item.textEditText || item.insertText || item.label + if (!/^\w/.test(text)) { + let prefix = /^[^\w]*/.exec(text)![0] + if (prefixes.indexOf(prefix) < 0) prefixes.push(prefix) + } + } + if (!prefixes.length) return /^\w*$/ + return new RegExp("^(?:" + prefixes.map((RegExp as any).escape || (s => s.replace(/[^\w\s]/g, "\\$&"))).join("|") + ")?\\w*$") +} + +function shouldTriggerCompletion(plugin: LSPPlugin, character: string) : "identifier" | "triggerCharacter" | null { + let triggers = plugin.client.serverCapabilities?.completionProvider?.triggerCharacters + if (triggers && triggers.indexOf(character) > -1) return "triggerCharacter" + if (/[a-zA-Z_]/.test(character)) return "identifier" + return null +} + +type TextEdit = {from: number, to: number, text: string} + +type ExtraEdits = {index: number, edits: readonly TextEdit[], text: string} + +function resultMapper(changes: ChangeDesc | null, extraEdits: ExtraEdits[]) { + return (result: CompletionResult, newChanges: ChangeDesc): CompletionResult => { + changes = changes ? changes.composeDesc(newChanges) : newChanges + let options = result.options.slice() + for (let {index, edits, text} of extraEdits) + options[index] = {...options[index], apply: applyEdits(edits, text, changes)} + return { + ...result, + options, + map: resultMapper(changes, extraEdits) + } + } +} + +function applyEdits(edits: readonly TextEdit[], text: string, mapped: ChangeDesc | null) { + return (view: EditorView, completion: Completion, from: number, to: number) => { + let base = insertCompletionText(view.state, text, from, to) + let changes: ChangeSpec[] = [] + for (let {from, to, text} of edits) { + if (mapped) { + if (mapped.touchesRange(from, to)) continue + let len = to - from + from = mapped.mapPos(from, 1) + to = from + len + } + changes.push({from, to, insert: text}) + } + view.dispatch(base, {changes}) + } +} + +function completionForPlugin(plugin: LSPPlugin, context: CompletionContext): Promise | null { + let triggerChar = context.state.sliceDoc(context.pos - 1, context.pos) + let triggerReason = context.explicit ? "invoked" : shouldTriggerCompletion(plugin, triggerChar) + if (!triggerReason) return null + let completionContext: lsp.CompletionContext = triggerReason == "triggerCharacter" + ? {triggerKind: 2 /* TriggerCharacter */, triggerCharacter: triggerChar} + : {triggerKind: 1 /* Invoked */} + return getCompletions(plugin, context.pos, completionContext, context).then(result => { + if (!result) return null + if (Array.isArray(result)) result = {items: result} as lsp.CompletionList + let {from, to} = completionResultRange(context, result) + let defaultCommitChars = result.itemDefaults?.commitCharacters + let config = context.state.facet(completionConfig) + let extraEdits: ExtraEdits[] = [] + + return { + from, to, + options: result.items.map((item, i) => { + let text = item.textEdit?.newText || item.textEditText || item.insertText || item.label + let option: Completion = { + label: item.filterText || item.label, + displayLabel: item.label, + type: item.kind && kindToType[item.kind], + } + let insertTextFormat = item.insertTextFormat ?? result.itemDefaults?.insertTextFormat + if (item.commitCharacters && item.commitCharacters != defaultCommitChars) + option.commitCharacters = item.commitCharacters + if (item.detail) option.detail = item.detail + if (item.sortText) option.sortText = item.sortText + if (insertTextFormat == 2 /* Snippet */) { + option.apply = (view, c, from, to) => snippet(lspToSnippet(text))(view, c, from, to) + } else if (item.additionalTextEdits) { + let edits: TextEdit[] = [] + for (let edit of item.additionalTextEdits) { + let from = fromPositionChecked(context.state.doc, edit.range.start) + let to = fromPositionChecked(context.state.doc, edit.range.end) + if (from != null && to != null) edits.push({from, to, text: edit.newText}) + } + extraEdits.push({index: i, text, edits}) + option.apply = applyEdits(edits, text, null) + } else if (option.label != text) { + option.apply = text + } + if (item.documentation) option.info = () => renderDocInfo(plugin, item.documentation!) + return option + }), + commitCharacters: defaultCommitChars, + validFor: result.isIncomplete ? undefined : (config.validFor ?? prefixRegexp(result.items)), + map: extraEdits.length ? resultMapper(null, extraEdits) : undefined + } + }, err => { + if ("code" in err && (err as lsp.ResponseError).code == -32800 /* RequestCancelled */) + return null + throw err + }) +} + +function mappedOptionRange(option: Completion, source: CompletionResult, from: number, to: number): Completion { + const sourceFrom = source.from, sourceTo = source.to ?? sourceFrom + if (sourceFrom == from && sourceTo == to) return option + const apply = option.apply ?? option.label + return { + ...option, + apply(view, completion) { + if (typeof apply == "function") apply(view, completion, sourceFrom, sourceTo) + else view.dispatch(insertCompletionText(view.state, apply, sourceFrom, sourceTo)) + } + } +} + +function mergeCompletionResults(results: readonly CompletionResult[]): CompletionResult | null { + if (!results.length) return null + if (results.length == 1) return results[0] + + let from = results[0].from, to = results[0].to ?? results[0].from + for (let i = 1; i < results.length; i++) { + from = Math.min(from, results[i].from) + to = Math.max(to, results[i].to ?? results[i].from) + } + + const options: Completion[] = [], seen = new Set() + for (const result of results) { + for (const raw of result.options) { + const option = result.commitCharacters && !raw.commitCharacters + ? {...raw, commitCharacters: result.commitCharacters} + : raw + // Providers often return identical keyword entries. Keep the first one, + // which follows binding priority, while preserving distinct details. + const key = `${option.label}\u0000${option.detail || ""}\u0000${option.type || ""}` + if (seen.has(key)) continue + seen.add(key) + options.push(mappedOptionRange(option, result, from, to)) + } + } + + const firstValidFor = results[0].validFor + const validFor = results.every(result => String(result.validFor) == String(firstValidFor)) + ? firstValidFor + : undefined + return {from, to, options, validFor} +} + +/// A completion source that requests completions from every eligible language +/// server attached to the editor and combines their results. Requests are +/// independent so one failing supplemental server cannot suppress the others. +export const serverCompletionSource: CompletionSource = context => { + if (!context.view) return null + const plugins = LSPPlugin.getAll(context.view, "completion") + .filter(plugin => plugin.client.hasCapability("completionProvider") !== false) + if (!plugins.length) return null + const requests = plugins.map(plugin => completionForPlugin(plugin, context)) + .filter((request): request is Promise => !!request) + if (!requests.length) return null + if (requests.length == 1) return requests[0] + return Promise.allSettled(requests).then(settled => { + const results: CompletionResult[] = [] + for (const item of settled) { + if (item.status == "fulfilled") { + if (item.value) results.push(item.value) + } else if (!context.aborted) { + console.warn("[lsp] Completion provider failed", item.reason) + } + } + return mergeCompletionResults(results) + }) +} + +function completionResultRange(cx: CompletionContext, result: lsp.CompletionList): {from: number, to: number} { + if (!result.items.length) return {from: cx.pos, to: cx.pos} + let defaultRange = result.itemDefaults?.editRange, item0 = result.items[0] + let range = defaultRange ? ("insert" in defaultRange ? defaultRange.insert : defaultRange) + : item0.textEdit ? ("range" in item0.textEdit ? item0.textEdit.range : item0.textEdit.insert) + : null + if (!range) return cx.state.wordAt(cx.pos) || {from: cx.pos, to: cx.pos} + let line = cx.state.doc.lineAt(cx.pos) + return {from: line.from + range.start.character, to: line.from + range.end.character} +} + +function renderDocInfo(plugin: LSPPlugin, doc: string | lsp.MarkupContent) { + let elt = document.createElement("div") + elt.className = "cm-lsp-documentation cm-lsp-completion-documentation" + elt.innerHTML = plugin.docToHTML(doc) + return elt +} + +const kindToType: {[kind: number]: string} = { + 1: "text", // Text + 2: "method", // Method + 3: "function", // Function + 4: "class", // Constructor + 5: "property", // Field + 6: "variable", // Variable + 7: "class", // Class + 8: "interface", // Interface + 9: "namespace", // Module + 10: "property", // Property + 11: "keyword", // Unit + 12: "constant", // Value + 13: "constant", // Enum + 14: "keyword", // Keyword + 16: "constant", // Color + 20: "constant", // EnumMember + 21: "constant", // Constant + 22: "class", // Struct + 25: "type" // TypeParameter +} diff --git a/codemirror-lsp-client/src/definition.ts b/codemirror-lsp-client/src/definition.ts new file mode 100644 index 0000000000..0fda59e0c4 --- /dev/null +++ b/codemirror-lsp-client/src/definition.ts @@ -0,0 +1,85 @@ +import type * as lsp from "vscode-languageserver-protocol" +import {EditorView, Command, KeyBinding} from "@codemirror/view" +import {LSPPlugin} from "./plugin" + +function getDefinition(plugin: LSPPlugin, pos: number) { + return plugin.client.request("textDocument/definition", { + textDocument: {uri: plugin.uri}, + position: plugin.toPosition(pos) + }) +} + +function getDeclaration(plugin: LSPPlugin, pos: number) { + return plugin.client.request("textDocument/declaration", { + textDocument: {uri: plugin.uri}, + position: plugin.toPosition(pos) + }) +} + +function getTypeDefinition(plugin: LSPPlugin, pos: number) { + return plugin.client.request("textDocument/typeDefinition", { + textDocument: {uri: plugin.uri}, + position: plugin.toPosition(pos) + }) +} + +function getImplementation(plugin: LSPPlugin, pos: number) { + return plugin.client.request("textDocument/implementation", { + textDocument: {uri: plugin.uri}, + position: plugin.toPosition(pos) + }) +} + +function jumpToOrigin(view: EditorView, type: {get: typeof getDefinition, capability: keyof lsp.ServerCapabilities}): boolean { + const feature = type.capability == "declarationProvider" ? "declaration" + : type.capability == "typeDefinitionProvider" ? "typeDefinition" + : type.capability == "implementationProvider" ? "implementation" + : "definition" + const plugin = LSPPlugin.getAll(view, feature) + .find(plugin => plugin.client.hasCapability(type.capability) !== false) + if (!plugin || plugin.client.hasCapability(type.capability) === false) return false + plugin.client.sync() + plugin.client.withMapping(mapping => type.get(plugin, view.state.selection.main.head).then(response => { + let loc = Array.isArray(response) ? response[0] : response + if (!loc) return + + return (loc.uri == plugin.uri ? Promise.resolve(view) : plugin.client.workspace.displayFile(loc.uri)).then(target => { + if (!target) return + let pos = mapping.getMapping(loc.uri) ? mapping.mapPosition(loc.uri, loc.range.start) + : plugin.fromPosition(loc.range.start, target.state.doc) + target.dispatch({selection: {anchor: pos}, scrollIntoView: true, userEvent: "select.definition"}) + }) + }, error => plugin.reportError("Find definition failed", error))) + return true +} + +/// Jump to the definition of the symbol at the cursor. To support +/// cross-file jumps, you'll need to implement +/// [`Workspace.displayFile`](#lsp-client.Workspace.displayFile). +export const jumpToDefinition: Command = view => jumpToOrigin(view, { + get: getDefinition, + capability: "definitionProvider" +}) + +/// Jump to the declaration of the symbol at the cursor. +export const jumpToDeclaration: Command = view => jumpToOrigin(view, { + get: getDeclaration, + capability: "declarationProvider" +}) + +/// Jump to the type definition of the symbol at the cursor. +export const jumpToTypeDefinition: Command = view => jumpToOrigin(view, { + get: getTypeDefinition, + capability: "typeDefinitionProvider" +}) + +/// Jump to the implementation of the symbol at the cursor. +export const jumpToImplementation: Command = view => jumpToOrigin(view, { + get: getImplementation, + capability: "implementationProvider" +}) + +/// Binds F12 to [`jumpToDefinition`](#lsp-client.jumpToDefinition). +export const jumpToDefinitionKeymap: readonly KeyBinding[] = [ + {key: "F12", run: jumpToDefinition, preventDefault: true}, +] diff --git a/codemirror-lsp-client/src/diagnostics.ts b/codemirror-lsp-client/src/diagnostics.ts new file mode 100644 index 0000000000..4f5e8021a0 --- /dev/null +++ b/codemirror-lsp-client/src/diagnostics.ts @@ -0,0 +1,60 @@ +import type * as lsp from "vscode-languageserver-protocol" +import {forEachDiagnostic, setDiagnostics} from "@codemirror/lint" +import type {Diagnostic} from "@codemirror/lint" +import {ViewPlugin, ViewUpdate} from "@codemirror/view" +import {LSPPlugin} from "./plugin" +import type {LSPClient, LSPClientExtension} from "./client" + +function toSeverity(sev: lsp.DiagnosticSeverity): Diagnostic["severity"] { + return sev == 1 ? "error" : sev == 2 ? "warning" : sev == 3 ? "info" : "hint" +} + +const diagnosticClient = Symbol("lspDiagnosticClient") +type ClientDiagnostic = Diagnostic & {[diagnosticClient]?: LSPClient} + +const autoSync = ViewPlugin.fromClass(class { + pending: ReturnType | null = null + update(update: ViewUpdate) { + if (update.docChanged) { + if (this.pending != null) clearTimeout(this.pending) + this.pending = setTimeout(() => { + this.pending = null + LSPPlugin.syncAll(update.view) + }, 500) + } + } + destroy() { + if (this.pending != null) clearTimeout(this.pending) + } +}) + +export function serverDiagnostics(): LSPClientExtension { + return { + clientCapabilities: {textDocument: {publishDiagnostics: {versionSupport: true}}}, + notificationHandlers: { + "textDocument/publishDiagnostics": (client, params: lsp.PublishDiagnosticsParams) => { + let file = client.workspace.getFile(params.uri) + if (!file || params.version != null && params.version != file.version) return false + const view = file.getView(), plugin = view && LSPPlugin.get(view, client) + if (!view || !plugin) return false + // The lint package already maps stored diagnostics through editor + // changes. Preserve those current positions for every other provider + // and replace only this client's contribution. + const diagnostics: ClientDiagnostic[] = [] + forEachDiagnostic(view.state, (item: ClientDiagnostic, from, to) => { + if (item[diagnosticClient] !== client) diagnostics.push({...item, from, to}) + }) + diagnostics.push(...params.diagnostics.map(item => ({ + from: plugin.unsyncedChanges.mapPos(plugin.fromPosition(item.range.start, plugin.syncedDoc)), + to: plugin.unsyncedChanges.mapPos(plugin.fromPosition(item.range.end, plugin.syncedDoc)), + severity: toSeverity(item.severity ?? 1), + message: item.message, + [diagnosticClient]: client + }))) + view.dispatch(setDiagnostics(view.state, diagnostics)) + return true + } + }, + editorExtension: autoSync + } +} diff --git a/codemirror-lsp-client/src/formatting.ts b/codemirror-lsp-client/src/formatting.ts new file mode 100644 index 0000000000..82fea16404 --- /dev/null +++ b/codemirror-lsp-client/src/formatting.ts @@ -0,0 +1,53 @@ +import type * as lsp from "vscode-languageserver-protocol" +import {Command, KeyBinding} from "@codemirror/view" +import {ChangeSpec} from "@codemirror/state" +import {indentUnit, getIndentUnit} from "@codemirror/language" +import {LSPPlugin} from "./plugin" + +function getFormatting(plugin: LSPPlugin, options: lsp.FormattingOptions) { + return plugin.client.request("textDocument/formatting", { + options, + textDocument: {uri: plugin.uri}, + }) +} + +/// This command asks the language server to reformat the document, +/// and then applies the changes it returns. +export const formatDocument: Command = view => { + const plugin = LSPPlugin.getAll(view, "formatting") + .find(plugin => plugin.client.hasCapability("documentFormattingProvider") !== false) + if (!plugin) return false + plugin.client.sync() + plugin.client.withMapping(mapping => getFormatting(plugin, { + tabSize: getIndentUnit(view.state), + insertSpaces: view.state.facet(indentUnit).indexOf("\t") < 0, + }).then(response => { + if (!response) return + let changed = mapping.getMapping(plugin.uri) + let changes: ChangeSpec[] = [] + for (let change of response) { + let from = mapping.mapPosition(plugin.uri, change.range.start) + let to = mapping.mapPosition(plugin.uri, change.range.end) + if (changed) { + // Don't try to apply the changes if code inside of any of them was touched + if (changed.touchesRange(from, to)) return + from = changed.mapPos(from, 1) + to = changed.mapPos(to, -1) + } + changes.push({from, to, insert: change.newText}) + } + view.dispatch({ + changes, + userEvent: "format" + }) + }, err => { + plugin.reportError("Formatting request failed", err) + })) + return true +} + +/// A keymap that binds Shift-Alt-f to +/// [`formatDocument`](#lsp-client.formatDocument). +export const formatKeymap: readonly KeyBinding[] = [ + {key: "Shift-Alt-f", run: formatDocument, preventDefault: true} +] diff --git a/codemirror-lsp-client/src/hover.ts b/codemirror-lsp-client/src/hover.ts new file mode 100644 index 0000000000..516a2059dc --- /dev/null +++ b/codemirror-lsp-client/src/hover.ts @@ -0,0 +1,94 @@ +import type * as lsp from "vscode-languageserver-protocol" +import {EditorView, Tooltip, hoverTooltip} from "@codemirror/view" +import {Extension} from "@codemirror/state" +import {language as languageFacet, highlightingFor} from "@codemirror/language" +import {highlightCode} from "@lezer/highlight" +import {fromPosition} from "./pos" +import {escHTML} from "./text" +import {LSPPlugin} from "./plugin" + +/// Create an extension that queries the language server for hover +/// tooltips when the user hovers over the code with their pointer, +/// and displays a tooltip when the server provides one. +let defaultHoverTooltips: Extension | null = null + +export function hoverTooltips(config: {hoverTime?: number} = {}): Extension { + if (config.hoverTime == null && defaultHoverTooltips) return defaultHoverTooltips + const extension = hoverTooltip(lspTooltipSource, { + hideOn: tr => tr.docChanged, + hoverTime: config.hoverTime + }) + if (config.hoverTime == null) defaultHoverTooltips = extension + return extension +} + +function hoverRequest(plugin: LSPPlugin, pos: number) { + if (plugin.client.hasCapability("hoverProvider") === false) return Promise.resolve(null) + plugin.client.sync() + return plugin.client.request("textDocument/hover", { + position: plugin.toPosition(pos), + textDocument: {uri: plugin.uri}, + }) +} + +function lspTooltipSource(view: EditorView, pos: number): Promise { + const plugins = LSPPlugin.getAll(view, "hover") + .filter(plugin => plugin.client.hasCapability("hoverProvider") !== false) + if (!plugins.length) return Promise.resolve(null) + return Promise.allSettled(plugins.map(plugin => hoverRequest(plugin, pos))).then(settled => { + const results: {plugin: LSPPlugin, result: lsp.Hover}[] = [] + for (let i = 0; i < settled.length; i++) { + const item = settled[i] + if (item.status == "fulfilled" && item.value) results.push({plugin: plugins[i], result: item.value}) + else if (item.status == "rejected") console.warn("[lsp] Hover provider failed", item.reason) + } + if (!results.length) return null + let from = pos, to = pos + for (const {result} of results) if (result.range) { + from = Math.min(from, fromPosition(view.state.doc, result.range.start)) + to = Math.max(to, fromPosition(view.state.doc, result.range.end)) + } + return { + pos: from, + end: to, + create() { + let elt = document.createElement("div") + elt.className = "cm-lsp-hover-tooltip cm-lsp-documentation" + for (let i = 0; i < results.length; i++) { + if (i) elt.appendChild(document.createElement("hr")) + const section = elt.appendChild(document.createElement("div")) + section.innerHTML = renderTooltipContent(results[i].plugin, results[i].result.contents) + } + return {dom: elt} + }, + above: true + } + }) +} + +function renderTooltipContent( + plugin: LSPPlugin, + value: string | lsp.MarkupContent | lsp.MarkedString | lsp.MarkedString[] +) { + if (Array.isArray(value)) return value.map(m => renderCode(plugin, m)).join("
") + if (typeof value == "string" || typeof value == "object" && "language" in value) return renderCode(plugin, value) + return plugin.docToHTML(value) +} + +function renderCode(plugin: LSPPlugin, code: lsp.MarkedString) { + if (typeof code == "string") return plugin.docToHTML(code, "markdown") + let {language, value} = code + let lang = plugin.client.config.highlightLanguage && plugin.client.config.highlightLanguage(language || "") + if (!lang) { + let viewLang = plugin.view.state.facet(languageFacet) + if (viewLang && (!language || viewLang.name == language)) lang = viewLang + } + if (!lang) return escHTML(value) + let result = "" + highlightCode(value, lang.parser.parse(value), {style: tags => highlightingFor(plugin.view.state, tags)}, (text, cls) => { + result += cls ? `${escHTML(text)}` : escHTML(text) + }, () => { + result += "
" + }) + return result +} diff --git a/codemirror-lsp-client/src/index.ts b/codemirror-lsp-client/src/index.ts new file mode 100644 index 0000000000..edaadd48ff --- /dev/null +++ b/codemirror-lsp-client/src/index.ts @@ -0,0 +1,69 @@ +export {LSPClient, WorkspaceMapping} from "./client" +export type {Transport, LSPClientConfig, LSPClientExtension} from "./client" +export {LSPPlugin} from "./plugin" +export type {LSPFeature, LSPPluginOptions} from "./plugin" +export {Workspace} from "./workspace" +export type {WorkspaceFile} from "./workspace" +export {serverCompletion, serverCompletionSource} from "./completion" +export {hoverTooltips} from "./hover" +export {formatDocument, formatKeymap} from "./formatting" +export {renameSymbol, renameKeymap} from "./rename" +export {signatureHelp, nextSignature, prevSignature, showSignatureHelp, signatureKeymap} from "./signature" +export {jumpToDefinition, jumpToDeclaration, jumpToTypeDefinition, jumpToImplementation, jumpToDefinitionKeymap} from "./definition" +export {findReferences, closeReferencePanel, findReferencesKeymap} from "./references" +export {serverDiagnostics} from "./diagnostics" + +import type {Extension} from "@codemirror/state" +import {keymap} from "@codemirror/view" +import {LSPClient} from "./client" +import type {LSPClientExtension} from "./client" +import {LSPPlugin} from "./plugin" +import {serverCompletion} from "./completion" +import {hoverTooltips} from "./hover" +import {formatKeymap} from "./formatting" +import {renameKeymap} from "./rename" +import {signatureHelp} from "./signature" +import {jumpToDefinitionKeymap} from "./definition" +import {findReferencesKeymap} from "./references" +import {serverDiagnostics} from "./diagnostics" + +const languageServerKeymap = keymap.of([ + ...formatKeymap, + ...renameKeymap, + ...jumpToDefinitionKeymap, + ...findReferencesKeymap +]) + +/// Returns an extension that enables the [LSP +/// plugin](#lsp-client.LSPPlugin) as well as LSP based +/// autocompletion, hover tooltips, and signature help, along with the +/// keymaps for reformatting, renaming symbols, jumping to definition, +/// and finding references. +/// +/// This function is deprecated. Prefer to directly use +/// [`LSPPlugin.create`](#lsp-client.LSPPlugin^create) and either add +/// the extensions you need directly, or configure them in the client +/// via [`languageServerExtensions`](#lsp-client.languageServerExtensions). +export function languageServerSupport(client: LSPClient, uri: string, languageID?: string): Extension { + return [ + LSPPlugin.create(client, uri, languageID), + serverCompletion(), + hoverTooltips(), + languageServerKeymap, + signatureHelp(), + ] +} + +/// This function bundles all the extensions defined in this package, +/// in a way that can be passed to the +/// [`extensions`](#lsp-client.LSPClientConfig.extensions) option to +/// `LSPClient`. +export function languageServerExtensions(): readonly (Extension | LSPClientExtension)[] { + return [ + serverCompletion(), + hoverTooltips(), + languageServerKeymap, + signatureHelp(), + serverDiagnostics() + ] +} diff --git a/codemirror-lsp-client/src/plugin.ts b/codemirror-lsp-client/src/plugin.ts new file mode 100644 index 0000000000..152a02bbf4 --- /dev/null +++ b/codemirror-lsp-client/src/plugin.ts @@ -0,0 +1,270 @@ +import type * as lsp from "vscode-languageserver-protocol" +import {EditorView, ViewPlugin, ViewUpdate, showDialog} from "@codemirror/view" +import {ChangeSet, Text, Extension, Facet} from "@codemirror/state" +import {language} from "@codemirror/language" +import {type LSPClient} from "./client" +import {docToHTML, withContext} from "./text" +import {toPosition, fromPosition} from "./pos" + +/// Features that can be independently enabled or disabled for an editor +/// binding. This lets a supplemental server contribute completions and +/// diagnostics without becoming the formatter or rename provider. +export type LSPFeature = + | "completion" + | "hover" + | "signatureHelp" + | "diagnostics" + | "formatting" + | "rename" + | "definition" + | "declaration" + | "typeDefinition" + | "implementation" + | "references" + | "codeAction" + | "documentSymbol" + | "inlayHint" + | "documentColor" + +/// Options controlling a client's role when several clients are attached to +/// the same editor. +export type LSPPluginOptions = { + /// Higher-priority clients are considered first for single-owner features. + priority?: number + /// Features default to enabled. Set a feature to false to exclude this + /// client from that feature's provider set. + features?: Partial> +} + +type LSPPluginSpec = { + client: LSPClient + uri: string + languageID?: string + options?: LSPPluginOptions +} + +type ChangeEntry = { + revision: number + changes: ChangeSet +} + +const lspBindings = Facet.define({ + combine: values => values +}) + +class LSPViewPlugin { + private revision = 0 + private changes: ChangeEntry[] = [] + private plugins: LSPPlugin[] = [] + + constructor(readonly view: EditorView) { + this.configure(view.state.facet(lspBindings)) + } + + update(update: ViewUpdate) { + // Record each editor transaction once, regardless of how many language + // servers are attached. Per-client ChangeSets are composed lazily at sync. + if (update.docChanged) { + this.revision++ + this.changes.push({revision: this.revision, changes: update.changes}) + } + const before = update.startState.facet(lspBindings) + const after = update.state.facet(lspBindings) + if (before !== after) this.configure(after) + } + + destroy() { + for (const plugin of this.plugins) plugin.destroy() + this.plugins = [] + this.changes = [] + } + + get(client?: LSPClient): LSPPlugin | null { + if (!client) return this.plugins[0] || null + return this.plugins.find(plugin => plugin.client === client) || null + } + + getAll(feature?: LSPFeature): readonly LSPPlugin[] { + return feature + ? this.plugins.filter(plugin => plugin.featureEnabled(feature)) + : this.plugins + } + + pendingChanges(plugin: LSPPlugin): ChangeSet { + let result = ChangeSet.empty(plugin.syncedDoc.length) + for (const entry of this.changes) { + if (entry.revision > plugin.syncedRevision) + result = result.compose(entry.changes) + } + return result + } + + clear(plugin: LSPPlugin) { + plugin.syncedDoc = this.view.state.doc + plugin.syncedRevision = this.revision + this.pruneChanges() + } + + private configure(specs: readonly LSPPluginSpec[]) { + const unique: LSPPluginSpec[] = [] + for (const spec of specs) { + if (!unique.some(other => other.client === spec.client)) unique.push(spec) + } + + const remaining = new Set(this.plugins) + const next: {plugin: LSPPlugin, order: number}[] = [] + for (let order = 0; order < unique.length; order++) { + const spec = unique[order] + let plugin = this.plugins.find(candidate => + candidate.client === spec.client && + candidate.uri === spec.uri && + candidate.languageID === spec.languageID) + if (plugin) { + remaining.delete(plugin) + plugin.setOptions(spec.options) + } else { + plugin = new LSPPlugin(this.view, spec, this, this.revision) + } + next.push({plugin, order}) + } + for (const plugin of remaining) plugin.destroy() + next.sort((a, b) => b.plugin.priority - a.plugin.priority || a.order - b.order) + this.plugins = next.map(item => item.plugin) + this.pruneChanges() + } + + private pruneChanges() { + if (!this.plugins.length) { + this.changes = [] + return + } + let earliest = this.plugins[0].syncedRevision + for (let i = 1; i < this.plugins.length; i++) + earliest = Math.min(earliest, this.plugins[i].syncedRevision) + let drop = 0 + while (drop < this.changes.length && this.changes[drop].revision <= earliest) drop++ + if (drop) this.changes.splice(0, drop) + } +} + +/// A binding between one editor and one language server client. +export class LSPPlugin { + /// The client connection. + client: LSPClient + /// The URI of this file. + uri: string + /// The language identifier sent to this client. + languageID: string + /// The version of the document that was synchronized to the server. + syncedDoc: Text + /// @internal + syncedRevision: number + private options: LSPPluginOptions + + /// @internal + constructor( + readonly view: EditorView, + {client, uri, languageID, options}: LSPPluginSpec, + private owner: LSPViewPlugin, + revision: number + ) { + this.client = client + this.uri = uri + if (!languageID) { + const lang = view.state.facet(language) + languageID = lang ? lang.name : "" + } + this.languageID = languageID + this.options = options || {} + this.syncedDoc = view.state.doc + this.syncedRevision = revision + client.workspace.openFile(uri, languageID, view) + } + + /// Priority used when a feature needs a single owning client. + get priority() { return this.options.priority ?? 0 } + + /// Whether this binding is eligible to provide a feature. + featureEnabled(feature: LSPFeature) { + return this.options.features?.[feature] !== false + } + + /// @internal + setOptions(options?: LSPPluginOptions) { + this.options = options || {} + } + + /// Render a doc string from the server to HTML. + docToHTML(value: string | lsp.MarkupContent, defaultKind: lsp.MarkupKind = "plaintext") { + const html = withContext(this.view, this.client.config.highlightLanguage, () => docToHTML(value, defaultKind)) + return this.client.config.sanitizeHTML ? this.client.config.sanitizeHTML(html) : html + } + + /// Convert a document offset into an LSP position. + toPosition(pos: number, doc: Text = this.view.state.doc) { + return toPosition(doc, pos) + } + + /// Convert an LSP position into a document offset. + fromPosition(pos: lsp.Position, doc: Text = this.view.state.doc) { + return fromPosition(doc, pos) + } + + /// Display an error in this plugin's editor. + reportError(message: string, err: any) { + showDialog(this.view, { + label: this.view.state.phrase(message) + ": " + (err.message || err), + class: "cm-lsp-message cm-lsp-message-error", + top: true + }) + } + + /// Changes since this client last synchronized. They are composed lazily so + /// typing cost does not scale with the number of attached clients. + get unsyncedChanges(): ChangeSet { + return this.owner.pendingChanges(this) + } + + /// Mark this client's current pending changes as synchronized. + clear() { + this.owner.clear(this) + } + + /// @internal + destroy() { + this.client.workspace.closeFile(this.uri, this.view) + } + + /// Get the primary plugin, or the plugin for a specific client. + static get(view: EditorView, client?: LSPClient) { + return view.plugin(lspPlugin)?.get(client) || null + } + + /// Get all plugins, ordered by descending priority. + static getAll(view: EditorView, feature?: LSPFeature) { + return view.plugin(lspPlugin)?.getAll(feature) || [] + } + + /// Get the first plugin eligible for a feature. + static getForFeature(view: EditorView, feature: LSPFeature) { + return this.getAll(view, feature)[0] || null + } + + /// Synchronize all attached clients. Each client independently decides + /// whether it has pending document changes. + static syncAll(view: EditorView) { + for (const plugin of this.getAll(view)) plugin.client.sync() + } + + /// Deprecated. Use `LSPClient.plugin` instead. + static create(client: LSPClient, fileURI: string, languageID?: string, options?: LSPPluginOptions): Extension { + return client.plugin(fileURI, languageID, options) + } +} + +export const lspPlugin = ViewPlugin.fromClass(LSPViewPlugin) + +/// @internal +export function lspPluginBinding(spec: LSPPluginSpec): Extension { + return [lspBindings.of(spec), lspPlugin] +} diff --git a/codemirror-lsp-client/src/pos.ts b/codemirror-lsp-client/src/pos.ts new file mode 100644 index 0000000000..f7f877d470 --- /dev/null +++ b/codemirror-lsp-client/src/pos.ts @@ -0,0 +1,20 @@ +import type * as lsp from "vscode-languageserver-protocol" +import {Text} from "@codemirror/state" + +export function toPosition(doc: Text, pos: number): lsp.Position { + let line = doc.lineAt(pos) + return {line: line.number - 1, character: pos - line.from} +} + +export function fromPosition(doc: Text, pos: lsp.Position): number { + let line = doc.line(pos.line + 1) + return line.from + pos.character +} + +export function fromPositionChecked(doc: Text, pos: lsp.Position): number | null { + if (pos.line < 0 || pos.line >= doc.lines) return null + let line = doc.line(pos.line + 1) + if (pos.character < 0 || pos.character > line.length) return null + return line.from + pos.character +} + diff --git a/codemirror-lsp-client/src/references.ts b/codemirror-lsp-client/src/references.ts new file mode 100644 index 0000000000..83b7b168dd --- /dev/null +++ b/codemirror-lsp-client/src/references.ts @@ -0,0 +1,200 @@ +import type * as lsp from "vscode-languageserver-protocol" +import {Command, KeyBinding, showPanel, PanelConstructor, EditorView} from "@codemirror/view" +import {StateField, StateEffect} from "@codemirror/state" +import {LSPPlugin} from "./plugin" +import {WorkspaceFile} from "./workspace" +import {WorkspaceMapping} from "./client" +import type {LSPClient} from "./client" + +function getReferences(plugin: LSPPlugin, pos: number) { + return plugin.client.request("textDocument/references", { + textDocument: {uri: plugin.uri}, + position: plugin.toPosition(pos), + context: {includeDeclaration: true} + }) +} + +type ReferenceLocation = {file: WorkspaceFile, range: lsp.Range} + +/// Ask the server to locate all references to the symbol at the +/// cursor. When the server can provide such references, show them as +/// a list in a panel. +export const findReferences: Command = view => { + const plugin = LSPPlugin.getAll(view, "references") + .find(plugin => plugin.client.hasCapability("referencesProvider") !== false) + if (!plugin || plugin.client.hasCapability("referencesProvider") === false) return false + plugin.client.sync() + let mapping = plugin.client.workspaceMapping(), passedMapping = false + getReferences(plugin, view.state.selection.main.head).then(response => { + if (!response) return + return Promise.all(response.map(loc => plugin.client.workspace.requestFile(loc.uri).then(file => { + return file ? {file, range: loc.range} : null + }))).then(resolved => { + let locs = resolved.filter(l => l) as ReferenceLocation[] + if (locs.length) { + displayReferences(plugin.view, locs, mapping, plugin.client) + passedMapping = true + } + }) + }, err => plugin.reportError("Finding references failed", err)).finally(() => { + if (!passedMapping) mapping.destroy() + }) + return true +} + +/// Close the reference panel, if it is open. +export const closeReferencePanel: Command = view => { + if (!view.state.field(referencePanel, false)) return false + view.dispatch({effects: setReferencePanel.of(null)}) + return true +} + +const referencePanel = StateField.define({ + create() { return null }, + + update(panel, tr) { + for (let e of tr.effects) if (e.is(setReferencePanel)) return e.value + return panel + }, + + provide: f => showPanel.from(f) +}) + +const setReferencePanel = StateEffect.define() + +function displayReferences(view: EditorView, locs: readonly ReferenceLocation[], mapping: WorkspaceMapping, client: LSPClient) { + let panel = createReferencePanel(locs, mapping, client) + let effect = view.state.field(referencePanel, false) === undefined + ? StateEffect.appendConfig.of(referencePanel.init(() => panel)) + : setReferencePanel.of(panel) + view.dispatch({effects: effect}) +} + +function createReferencePanel(locs: readonly ReferenceLocation[], mapping: WorkspaceMapping, client: LSPClient): PanelConstructor { + let created = false + // Make sure that if this panel isn't used, the mapping still gets destroyed + setTimeout(() => {if (!created) mapping.destroy()}, 500) + + return view => { + created = true + let prefixLen = findCommonPrefix(locs.map(l => l.file.uri)) + let panel = document.createElement("div"), curFile = null + panel.className = "cm-lsp-reference-panel" + panel.tabIndex = 0 + panel.role = "listbox" + panel.setAttribute("aria-label", view.state.phrase("Reference list")) + let options: HTMLElement[] = [] + for (let {file, range} of locs) { + let fileName = file.uri.slice(prefixLen) + if (fileName != curFile) { + curFile = fileName + let header = panel.appendChild(document.createElement("div")) + header.className = "cm-lsp-reference-file" + header.textContent = fileName + } + let entry = panel.appendChild(document.createElement("div")) + entry.className = "cm-lsp-reference" + entry.role = "option" + let from = mapping.mapPosition(file.uri, range.start, 1), to = mapping.mapPosition(file.uri, range.end, -1) + let view = file.getView(), line = (view ? view.state.doc : file.doc).lineAt(from) + let lineNumber = entry.appendChild(document.createElement("span")) + lineNumber.className = "cm-lsp-reference-line" + lineNumber.textContent = (line.number + ": ").padStart(5, " ") + let textBefore = line.text.slice(Math.max(0, from - line.from - 50), from - line.from) + if (textBefore) entry.appendChild(document.createTextNode(textBefore)) + entry.appendChild(document.createElement("strong")).textContent = line.text.slice(from - line.from, to - line.from) + let textAfter = line.text.slice(to - line.from, Math.min(line.length, 100 - textBefore.length)) + if (textAfter) entry.appendChild(document.createTextNode(textAfter)) + if (!options.length) entry.setAttribute("aria-selected", "true") + options.push(entry) + } + + function curSelection() { + for (let i = 0; i < options.length; i++) { + if (options[i].hasAttribute("aria-selected")) return i + } + return 0 + } + function setSelection(index: number) { + for (let i = 0; i < options.length; i++) { + if (i == index) options[i].setAttribute("aria-selected", "true") + else options[i].removeAttribute("aria-selected") + } + } + function showReference(index: number) { + let {file, range} = locs[index] + let plugin = LSPPlugin.get(view, client) + if (!plugin) return + Promise.resolve(file.uri == plugin.uri ? view : plugin.client.workspace.displayFile(file.uri)).then(view => { + if (!view) return + let pos = mapping.mapPosition(file.uri, range.start, 1) + view.focus() + view.dispatch({ + selection: {anchor: pos}, + scrollIntoView: true + }) + }) + } + + panel.addEventListener("keydown", event => { + if (event.keyCode == 27) { // Escape + closeReferencePanel(view) + view.focus() + } else if (event.keyCode == 38 || event.keyCode == 33) { // ArrowUp, PageUp + setSelection((curSelection() - 1 + locs.length) % locs.length) + } else if (event.keyCode == 40 || event.keyCode == 34) { // ArrowDown, PageDown + setSelection((curSelection() + 1) % locs.length) + } else if (event.keyCode == 36) { // Home + setSelection(0) + } else if (event.keyCode == 35) { // End + setSelection(options.length - 1) + } else if (event.keyCode == 13 || event.keyCode == 10) { // Enter, Space + showReference(curSelection()) + } else { + return + } + event.preventDefault() + }) + panel.addEventListener("click", event => { + for (let i = 0; i < options.length; i++) { + if (options[i].contains(event.target as HTMLElement)) { + setSelection(i) + showReference(i) + event.preventDefault() + } + } + }) + let dom = document.createElement("div") + dom.appendChild(panel) + let close = dom.appendChild(document.createElement("button")) + close.className = "cm-dialog-close" + close.textContent = "×" + close.addEventListener("click", () => closeReferencePanel(view)) + close.setAttribute("aria-label", view.state.phrase("close")) + + return { + dom, + destroy: () => mapping.destroy(), + mount: () => panel.focus(), + } + } +} + +function findCommonPrefix(uris: string[]) { + let first = uris[0], prefix = first.length + for (let i = 1; i < uris.length; i++) { + let uri = uris[i], j = 0 + for (let e = Math.min(prefix, uri.length); j < e && first[j] == uri[j]; j++) {} + prefix = j + } + while (prefix && first[prefix - 1] != "/") prefix-- + return prefix +} + +/// Binds Shift-F12 to [`findReferences`](#lsp-client.findReferences) +/// and Escape to +/// [`closeReferencePanel`](#lsp-client.closeReferencePanel). +export const findReferencesKeymap: readonly KeyBinding[] = [ + {key: "Shift-F12", run: findReferences, preventDefault: true}, + {key: "Escape", run: closeReferencePanel}, +] diff --git a/codemirror-lsp-client/src/rename.ts b/codemirror-lsp-client/src/rename.ts new file mode 100644 index 0000000000..28381fca2b --- /dev/null +++ b/codemirror-lsp-client/src/rename.ts @@ -0,0 +1,77 @@ +import type * as lsp from "vscode-languageserver-protocol" +import {EditorView, Command, KeyBinding, showDialog, getDialog} from "@codemirror/view" +import {LSPPlugin} from "./plugin" + +function getRename(plugin: LSPPlugin, pos: number, newName: string) { + return plugin.client.request("textDocument/rename", { + newName, + position: plugin.toPosition(pos), + textDocument: {uri: plugin.uri}, + }) +} + +/// This command will, if the cursor is over a word, prompt the user +/// for a new name for that symbol, and ask the language server to +/// perform a rename of that symbol. +/// +/// Note that this may affect files other than the one loaded into +/// this view. See the +/// [`Workspace.updateFile`](#lsp-client.Workspace.updateFile) +/// method. +export const renameSymbol: Command = view => { + let wordRange = view.state.wordAt(view.state.selection.main.head) + let plugin = LSPPlugin.getAll(view, "rename") + .find(plugin => plugin.client.hasCapability("renameProvider") !== false) + if (!wordRange || !plugin || plugin.client.hasCapability("renameProvider") === false) return false + const word = view.state.sliceDoc(wordRange.from, wordRange.to) + let panel = getDialog(view, "cm-lsp-rename-panel") + if (panel) { + let input = panel.dom.querySelector("[name=name]") as HTMLInputElement + input.value = word + input.select() + } else { + let {close, result} = showDialog(view, { + label: view.state.phrase("New name"), + input: {name: "name", value: word}, + focus: true, + submitLabel: view.state.phrase("rename"), + class: "cm-lsp-rename-panel", + }) + result.then(form => { + view.dispatch({effects: close}) + if (form) doRename(view, (form.elements.namedItem("name") as HTMLInputElement).value) + }) + } + return true +} + +function doRename(view: EditorView, newName: string) { + const plugin = LSPPlugin.getAll(view, "rename") + .find(plugin => plugin.client.hasCapability("renameProvider") !== false) + const word = view.state.wordAt(view.state.selection.main.head) + if (!plugin || !word) return false + + plugin.client.sync() + plugin.client.withMapping(mapping => getRename(plugin, word.from, newName).then(response => { + if (!response) return + uris: for (let uri in response.changes) { + let lspChanges = response.changes[uri], file = plugin.client.workspace.getFile(uri) + if (!lspChanges.length || !file) continue + plugin.client.workspace.updateFile(uri, { + changes: lspChanges.map(change => ({ + from: mapping.mapPosition(uri, change.range.start), + to: mapping.mapPosition(uri, change.range.end), + insert: change.newText + })), + userEvent: "rename" + }) + } + }, err => { + plugin.reportError("Rename request failed", err) + })) +} + +/// A keymap that binds F2 to [`renameSymbol`](#lsp-client.renameSymbol). +export const renameKeymap: readonly KeyBinding[] = [ + {key: "F2", run: renameSymbol, preventDefault: true} +] diff --git a/codemirror-lsp-client/src/signature.ts b/codemirror-lsp-client/src/signature.ts new file mode 100644 index 0000000000..a0b07438c5 --- /dev/null +++ b/codemirror-lsp-client/src/signature.ts @@ -0,0 +1,274 @@ +import type * as lsp from "vscode-languageserver-protocol" +import {StateField, StateEffect, Prec, Extension} from "@codemirror/state" +import {EditorView, ViewPlugin, ViewUpdate, keymap, KeyBinding, + Tooltip, showTooltip, Command} from "@codemirror/view" +import {LSPPlugin} from "./plugin" +import type {LSPClient} from "./client" + +function getSignatureHelp(plugin: LSPPlugin, pos: number, context: lsp.SignatureHelpContext) { + if (plugin.client.hasCapability("signatureHelpProvider") === false) return Promise.resolve(null) + plugin.client.sync() + return plugin.client.request("textDocument/signatureHelp", { + context, + position: plugin.toPosition(pos), + textDocument: {uri: plugin.uri}, + }) +} + +const signaturePlugin = ViewPlugin.fromClass(class { + activeRequest: {pos: number, drop: boolean} | null = null + delayedRequest: ReturnType | null = null + + update(update: ViewUpdate) { + if (this.activeRequest) { + if (update.selectionSet) { + this.activeRequest.drop = true + this.activeRequest = null + } else if (update.docChanged) { + this.activeRequest.pos = update.changes.mapPos(this.activeRequest.pos) + } + } + + const plugin = LSPPlugin.getAll(update.view, "signatureHelp") + .find(plugin => plugin.client.hasCapability("signatureHelpProvider") !== false) + if (!plugin) return + const sigState = update.view.state.field(signatureState) + let triggerCharacter = "" + if (update.docChanged && update.transactions.some(tr => tr.isUserEvent("input.type"))) { + const serverConf = plugin.client.serverCapabilities?.signatureHelpProvider + const triggers = (serverConf?.triggerCharacters || []).concat(sigState && serverConf?.retriggerCharacters || []) + if (triggers) { + update.changes.iterChanges((fromA, toA, fromB, toB, inserted) => { + let ins = inserted.toString() + if (ins) for (let ch of triggers) { + if (ins.indexOf(ch) > -1) triggerCharacter = ch + } + }) + } + } + + if (triggerCharacter) { + this.startRequest(plugin, { + triggerKind: 2 /* TriggerCharacter */, + isRetrigger: !!sigState, + triggerCharacter, + activeSignatureHelp: sigState ? sigState.data : undefined + }) + } else if (sigState && update.selectionSet) { + if (this.delayedRequest != null) clearTimeout(this.delayedRequest) + this.delayedRequest = setTimeout(() => { + this.startRequest(plugin, { + triggerKind: 3 /* ContentChange */, + isRetrigger: true, + activeSignatureHelp: sigState.data, + }) + }, 250) + } + } + + startRequest(plugin: LSPPlugin, context: lsp.SignatureHelpContext) { + if (this.delayedRequest != null) clearTimeout(this.delayedRequest) + let {view} = plugin, pos = view.state.selection.main.head + if (this.activeRequest) this.activeRequest.drop = true + let req = this.activeRequest = {pos, drop: false} + getSignatureHelp(plugin, pos, context).then(result => { + if (req.drop) return + if (result && result.signatures.length) { + let cur = view.state.field(signatureState) + let same = cur && sameSignatures(cur.data, result) + let active = same && context.triggerKind == 3 ? cur!.active : result.activeSignature ?? 0 + // Don't update at all if nothing changed + if (same && sameActiveParam(cur!.data, result, active)) return + view.dispatch({effects: signatureEffect.of({ + data: result, + active, + pos: same ? cur!.tooltip.pos : req.pos, + client: plugin.client + })}) + } else if (view.state.field(signatureState)) { + view.dispatch({effects: signatureEffect.of(null)}) + } + }, context.triggerKind == 1 /* Invoked */ ? err => plugin.reportError("Signature request failed", err) : undefined) + } + + destroy() { + if (this.delayedRequest != null) clearTimeout(this.delayedRequest) + if (this.activeRequest) this.activeRequest.drop = true + } +}) + +function sameSignatures(a: lsp.SignatureHelp, b: lsp.SignatureHelp) { + if (a.signatures.length != b.signatures.length) return false + return a.signatures.every((s, i) => s.label == b.signatures[i].label) +} + +function sameActiveParam(a: lsp.SignatureHelp, b: lsp.SignatureHelp, active: number) { + return (a.signatures[active].activeParameter ?? a.activeParameter) == + (b.signatures[active].activeParameter ?? b.activeParameter) +} + +class SignatureState { + constructor( + readonly data: lsp.SignatureHelp, + readonly active: number, + readonly tooltip: Tooltip, + readonly client: LSPClient + ) {} +} + +const signatureState = StateField.define({ + create() { return null }, + update(sig, tr) { + for (let e of tr.effects) if (e.is(signatureEffect)) { + if (e.value) { + return new SignatureState(e.value.data, e.value.active, + signatureTooltip(e.value.data, e.value.active, e.value.pos, e.value.client), e.value.client) + } else { + return null + } + } + if (sig && tr.docChanged) + return new SignatureState(sig.data, sig.active, + {...sig.tooltip, pos: tr.changes.mapPos(sig.tooltip.pos)}, sig.client) + return sig + }, + provide: f => showTooltip.from(f, sig => sig && sig.tooltip) +}) + +const signatureEffect = StateEffect.define<{ + data: lsp.SignatureHelp, + active: number, + pos: number, + client: LSPClient +} | null>() + +function signatureTooltip(data: lsp.SignatureHelp, active: number, pos: number, client: LSPClient): Tooltip { + return { + pos, + above: true, + create: view => drawSignatureTooltip(view, data, active, client) + } +} + +function drawSignatureTooltip(view: EditorView, data: lsp.SignatureHelp, active: number, client: LSPClient) { + let dom = document.createElement("div") + dom.className = "cm-lsp-signature-tooltip" + if (data.signatures.length > 1) { + dom.classList.add("cm-lsp-signature-multiple") + let num = dom.appendChild(document.createElement("div")) + num.className = "cm-lsp-signature-num" + num.textContent = `${active + 1}/${data.signatures.length}` + } + + let signature = data.signatures[active] + let sig = dom.appendChild(document.createElement("div")) + sig.className = "cm-lsp-signature" + let activeFrom = 0, activeTo = 0 + let activeN = signature.activeParameter ?? data.activeParameter + let activeParam = activeN != null && signature.parameters ? signature.parameters[activeN] : null + if (activeParam && Array.isArray(activeParam.label)) { + ;[activeFrom, activeTo] = activeParam.label + } else if (activeParam) { + let found = signature.label.indexOf(activeParam.label as string) + if (found > -1) { + activeFrom = found + activeTo = found + activeParam.label.length + } + } + if (activeTo) { + sig.appendChild(document.createTextNode(signature.label.slice(0, activeFrom))) + let activeElt = sig.appendChild(document.createElement("span")) + activeElt.className = "cm-lsp-active-parameter" + activeElt.textContent = signature.label.slice(activeFrom, activeTo) + sig.appendChild(document.createTextNode(signature.label.slice(activeTo))) + } else { + sig.textContent = signature.label + } + if (signature.documentation) { + let plugin = LSPPlugin.get(view, client) + if (plugin) { + let docs = dom.appendChild(document.createElement("div")) + docs.className = "cm-lsp-signature-documentation cm-lsp-documentation" + docs.innerHTML = plugin.docToHTML(signature.documentation) + } + } + return {dom} +} + +/// Explicitly prompt the server to provide signature help at the +/// cursor. +export const showSignatureHelp: Command = view => { + let plugin = view.plugin(signaturePlugin) + if (!plugin) { + view.dispatch({effects: StateEffect.appendConfig.of([signatureState, signaturePlugin])}) + plugin = view.plugin(signaturePlugin) + } + let field = view.state.field(signatureState) + if (!plugin || field === undefined) return false + let lspPlugin = LSPPlugin.getAll(view, "signatureHelp") + .find(plugin => plugin.client.hasCapability("signatureHelpProvider") !== false) + if (!lspPlugin) return false + plugin.startRequest(lspPlugin, { + triggerKind: 1 /* Invoked */, + activeSignatureHelp: field ? field.data : undefined, + isRetrigger: !!field + }) + return true +} + +/// If there is an active signature tooltip with multiple signatures, +/// move to the next one. +export const nextSignature: Command = view => { + let field = view.state.field(signatureState) + if (!field) return false + if (field.active < field.data.signatures.length - 1) + view.dispatch({effects: signatureEffect.of({ + data: field.data, active: field.active + 1, pos: field.tooltip.pos, client: field.client + })}) + return true +} + +/// If there is an active signature tooltip with multiple signatures, +/// move to the previous signature. +export const prevSignature: Command = view => { + let field = view.state.field(signatureState) + if (!field) return false + if (field.active > 0) + view.dispatch({effects: signatureEffect.of({ + data: field.data, active: field.active - 1, pos: field.tooltip.pos, client: field.client + })}) + return true +} + +/// A keymap that binds +/// +/// - Ctrl-Shift-Space (Cmd-Shift-Space on macOS) to +/// [`showSignatureHelp`](#lsp-client.showSignatureHelp) +/// +/// - Ctrl-Shift-ArrowUp (Cmd-Shift-ArrowUp on macOS) to +/// [`prevSignature`](#lsp-client.prevSignature) +/// +/// - Ctrl-Shift-ArrowDown (Cmd-Shift-ArrowDown on macOS) to +/// [`nextSignature`](#lsp-client.nextSignature) +/// +/// Note that these keys are automatically bound by +/// [`signatureHelp`](#lsp-client.signatureHelp) unless you pass it +/// `keymap: false`. +export const signatureKeymap: readonly KeyBinding[] = [ + {key: "Mod-Shift-Space", run: showSignatureHelp}, + {key: "Mod-Shift-ArrowUp", run: prevSignature}, + {key: "Mod-Shift-ArrowDown", run: nextSignature}, +] + +/// Returns an extension that enables signature help. Will bind the +/// keys in [`signatureKeymap`](#lsp-client.signatureKeymap) unless +/// `keymap` is set to `false`. +const signatureHelpWithoutKeymap: Extension = [signatureState, signaturePlugin] +const signatureHelpWithKeymap: Extension = [ + signatureHelpWithoutKeymap, + Prec.high(keymap.of(signatureKeymap)) +] + +export function signatureHelp(config: {keymap?: boolean} = {}): Extension { + return config.keymap === false ? signatureHelpWithoutKeymap : signatureHelpWithKeymap +} diff --git a/codemirror-lsp-client/src/text.ts b/codemirror-lsp-client/src/text.ts new file mode 100644 index 0000000000..59773d08ef --- /dev/null +++ b/codemirror-lsp-client/src/text.ts @@ -0,0 +1,56 @@ +import type * as lsp from "vscode-languageserver-protocol" +import {Marked} from "marked" +import {EditorView} from "@codemirror/view" +import {Language, language as languageFacet, highlightingFor} from "@codemirror/language" +import {highlightCode, Highlighter} from "@lezer/highlight" + +let context: {view: EditorView, language: ((name: string) => Language | null) | undefined} | null = null + +export function withContext(view: EditorView, language: ((name: string) => Language | null) | undefined, f: () => T): T { + let prev = context + try { + context = {view, language} + return f() + } finally { + context = prev + } +} + +const marked = new Marked({ + walkTokens(token) { + if (!context || token.type != "code") return + + let lang = context.language && context.language(token.lang) + if (!lang) { + let viewLang = context.view.state.facet(languageFacet) + if (viewLang && viewLang.name == token.lang) lang = viewLang + } + if (!lang) return + let highlighter: Highlighter = {style: tags => highlightingFor(context!.view.state, tags)} + let result = "" + highlightCode(token.text, lang.parser.parse(token.text), highlighter, (text, cls) => { + result += cls ? `${escHTML(text)}` : escHTML(text) + }, () => { + result += "
" + }) + token.escaped = true + token.text = result + } +}) + +export function escHTML(text: string) { + return text.replace(/[\n<&]/g, ch => ch == "\n" ? "
" : ch == "<" ? "<" : "&") +} + +export function docToHTML(value: string | lsp.MarkupContent, defaultKind: lsp.MarkupKind) { + let kind = defaultKind, text = value + if (typeof text != "string") { + kind = text.kind + text = text.value + } + if (kind == "plaintext") { + return escHTML(text) + } else { + return marked.parse(text, {async: false, }) + } +} diff --git a/codemirror-lsp-client/src/theme.ts b/codemirror-lsp-client/src/theme.ts new file mode 100644 index 0000000000..1c0c45560b --- /dev/null +++ b/codemirror-lsp-client/src/theme.ts @@ -0,0 +1,79 @@ +import {EditorView} from "@codemirror/view" + +export const lspTheme = EditorView.baseTheme({ + ".cm-lsp-documentation": { + padding: "0 7px", + "& p, & pre": { + margin: "2px 0" + } + }, + + ".cm-lsp-signature-tooltip": { + padding: "2px 6px", + borderRadius: "2.5px", + position: "relative", + maxWidth: "30em", + maxHeight: "10em", + overflowY: "scroll", + "& .cm-lsp-documentation": { + padding: "0", + fontSize: "80%", + }, + "& .cm-lsp-signature-num": { + fontFamily: "monospace", + position: "absolute", + left: "2px", top: "4px", + fontSize: "70%", + lineHeight: "1.3" + }, + "& .cm-lsp-signature": { + fontFamily: "monospace", + textIndent: "1em hanging", + }, + "& .cm-lsp-active-parameter": { + fontWeight: "bold" + }, + }, + ".cm-lsp-signature-multiple": { + paddingLeft: "1.5em" + }, + + ".cm-panel.cm-lsp-rename-panel": { + padding: "2px 6px 4px", + position: "relative", + "& label": { fontSize: "80%" }, + "& [name=close]": { + position: "absolute", + top: "0", bottom: "0", + right: "4px", + backgroundColor: "inherit", + border: "none", + font: "inherit", + padding: "0" + } + }, + + ".cm-lsp-message button[type=submit]": { + display: "block" + }, + + ".cm-lsp-reference-panel": { + fontFamily: "monospace", + whiteSpace: "pre", + padding: "3px 6px", + maxHeight: "120px", + overflow: "auto", + "& .cm-lsp-reference-file": { + fontWeight: "bold", + }, + "& .cm-lsp-reference": { + cursor: "pointer", + "&[aria-selected]": { + backgroundColor: "#0077ee44" + }, + }, + "& .cm-lsp-reference-line": { + opacity: "0.7", + }, + }, +}) diff --git a/codemirror-lsp-client/src/workspace.ts b/codemirror-lsp-client/src/workspace.ts new file mode 100644 index 0000000000..dd0c3b2031 --- /dev/null +++ b/codemirror-lsp-client/src/workspace.ts @@ -0,0 +1,161 @@ +import {Text, ChangeSet, TransactionSpec} from "@codemirror/state" +import {EditorView} from "@codemirror/view" +import {LSPClient} from "./client" +import {LSPPlugin} from "./plugin" + +/// A file that is open in a workspace. +export interface WorkspaceFile { + /// The file's unique URI. + uri: string + /// The LSP language ID for the file's content. + languageId: string + /// The current version of the file. + version: number + /// The document corresponding to `this.version`. Will not reflect + /// changes made after that version was synchronized. Will be + /// updated, along with `version`, by + /// [`syncFiles`](#lsp-client.Workspace.syncFiles). + doc: Text + /// Get an active editor view for this file, if there is one. For + /// workspaces that support multiple views on a file, `main` + /// indicates a preferred view. + getView(main?: EditorView): EditorView | null +} + +interface WorkspaceFileUpdate { + file: WorkspaceFile + prevDoc: Text + changes: ChangeSet +} + +/// Implementing your own workspace class can provide more control +/// over the way files are loaded and managed when interacting with +/// the language server. See +/// [`LSPClientConfig.workspace`](#lsp-client.LSPClientConfig.workspace). +export abstract class Workspace { + /// The files currently open in the workspace. + abstract files: WorkspaceFile[] + + /// The constructor, as called by the client when creating a + /// workspace. + constructor( + /// The LSP client associated with this workspace. + readonly client: LSPClient + ) {} + + /// Find the open file with the given URI, if it exists. The default + /// implementation just looks it up in `this.files`. + getFile(uri: string) : WorkspaceFile | null { + return this.files.find(f => f.uri == uri) || null + } + + /// Check all open files for changes (usually from editors, but they + /// may also come from other sources). When a file is changed, + /// return a record that describes the changes, and update the file's + /// [`version`](#lsp-client.WorkspaceFile.version) and + /// [`doc`](#lsp-client.WorkspaceFile.doc) properties to reflect the + /// new version. + abstract syncFiles(): readonly WorkspaceFileUpdate[] + + /// Called to request that the workspace open a file. The default + /// implementation simply returns the file if it is open, null + /// otherwise. + requestFile(uri: string): Promise { + return Promise.resolve(this.getFile(uri)) + } + + /// Called when an editor is created for a file. The implementation + /// should track the file in + /// [`this.files`](#lsp-client.Workspace.files) and, if it wasn't + /// open already, call + /// [`LSPClient.didOpen`](#lsp-client.LSPClient.didOpen). + abstract openFile(uri: string, languageId: string, view: EditorView): void + + /// Called when an editor holding this file is destroyed or + /// reconfigured to no longer hold it. The implementation should + /// track this and, when it closes the file, make sure to call + /// [`LSPClient.didClose`](#lsp-client.LSPClient.didClose). + abstract closeFile(uri: string, view: EditorView): void + + /// Called when the client for this workspace is connected. The + /// default implementation calls + /// [`LSPClient.didOpen`](#lsp-client.LSPClient.didOpen) on all open + /// files. + connected(): void { + for (let file of this.files) this.client.didOpen(file) + } + + /// Called when the client for this workspace is disconnected. The + /// default implementation does nothing. + disconnected(): void {} + + /// Called when a server-initiated change to a file is applied. The + /// default implementation simply dispatches the update to the + /// file's view, if the file is open and has a view. + updateFile(uri: string, update: TransactionSpec): void { + let file = this.getFile(uri) + if (file) file.getView()?.dispatch(update) + } + + /// When the client needs to put a file other than the one loaded in + /// the current editor in front of the user, for example in + /// [`jumpToDefinition`](#lsp-client.jumpToDefinition), it will call + /// this function. It should make sure to create or find an editor + /// with the file and make it visible to the user, or return null if + /// this isn't possible. + displayFile(uri: string): Promise { + let file = this.getFile(uri) + return Promise.resolve(file ? file.getView() : null) + } +} + +class DefaultWorkspaceFile implements WorkspaceFile { + constructor(readonly uri: string, + readonly languageId: string, + public version: number, + public doc: Text, + readonly view: EditorView) {} + + getView() { return this.view } +} + +export class DefaultWorkspace extends Workspace { + files: DefaultWorkspaceFile[] = [] + private fileVersions: {[uri: string]: number} = Object.create(null) + + nextFileVersion(uri: string) { + return this.fileVersions[uri] = (this.fileVersions[uri] ?? -1) + 1 + } + + syncFiles() { + let result: WorkspaceFileUpdate[] = [] + for (let file of this.files) { + let plugin = LSPPlugin.get(file.view, this.client) + if (!plugin) continue + let changes = plugin.unsyncedChanges + if (!changes.empty) { + result.push({changes, file, prevDoc: file.doc}) + file.doc = file.view.state.doc + file.version = this.nextFileVersion(file.uri) + plugin.clear() + } + } + return result + } + + openFile(uri: string, languageId: string, view: EditorView) { + if (this.getFile(uri)) + throw new Error("Default workspace implementation doesn't support multiple views on the same file") + let file = new DefaultWorkspaceFile(uri, languageId, this.nextFileVersion(uri), view.state.doc, view) + this.files.push(file) + this.client.didOpen(file) + } + + closeFile(uri: string) { + let file = this.getFile(uri) + if (file) { + this.files = this.files.filter(f => f != file) + this.client.didClose(uri) + } + } +} diff --git a/codemirror-lsp-client/test/server.ts b/codemirror-lsp-client/test/server.ts new file mode 100644 index 0000000000..4845fe9da1 --- /dev/null +++ b/codemirror-lsp-client/test/server.ts @@ -0,0 +1,207 @@ +import type * as lsp from "vscode-languageserver-protocol" +import {Transport} from "@codemirror/lsp-client" + +const serverCapabilities: lsp.ServerCapabilities = { + textDocumentSync: {openClose: true, change: 2}, + renameProvider: true, + documentFormattingProvider: true, + completionProvider: {triggerCharacters: [","]}, + hoverProvider: true, + signatureHelpProvider: {}, +} + +const requestHandlers: {[method: string]: (params: any, server: DummyServer) => any} = { + "initialize": (params: lsp.InitializeParams, server): lsp.InitializeResult => { + return {capabilities: serverCapabilities, serverInfo: {name: "Dummy server"}} + }, + + "textDocument/rename": (params: lsp.RenameParams, server): lsp.WorkspaceEdit | null => { + let file = server.getFile(params.textDocument.uri) + if (!file) throw new ServerError(-32602, "File not open") + let pos = resolvePosition(file.text, params.position) + let from = pos, to = pos + while (from && /\w/.test(file.text[from - 1])) from-- + while (to < file.text.length && /\w/.test(file.text[to])) to++ + if (from == to) return null + let word = file.text.slice(from, to), changes: {[uri: string]: lsp.TextEdit[]} = {} + for (let file of server.files) { + let found: lsp.TextEdit[] = [], pos = 0, next + while ((next = file.text.indexOf(word, pos)) > -1) { + pos = next + word.length + found.push({ + newText: params.newName, + range: {start: toPosition(file.text, next), end: toPosition(file.text, pos)} + }) + } + if (found.length) changes[file.uri] = found + } + return {changes} + }, + + "textDocument/formatting": (params: lsp.DocumentFormattingParams, server): lsp.TextEdit[] | null => { + let file = server.getFile(params.textDocument.uri) + if (!file) throw new ServerError(-32602, "File not open") + let end = toPosition(file.text, file.text.length) + return [{newText: "\n// formatted!", range: {start: end, end}}] + }, + + "textDocument/completion": (params: lsp.CompletionParams, server): lsp.CompletionList | null => { + let before = {line: params.position.line, character: params.position.character - 1} + return { + isIncomplete: true, + itemDefaults: { + editRange: {start: before, end: params.position} + }, + items: [ + {label: "one", kind: 14, commitCharacters: ["."], textEdit: {newText: "one!", range: {start: before, end: params.position}}}, + {label: "ookay", kind: 7, documentation: "`code` stuff", insertText: "okay"}, + {label: "fn", kind: 3, insertText: "fn(${1:\\$arg})$0", insertTextFormat: 2}, + {label: "Bar", kind: 7, insertText: "Bar", additionalTextEdits: [ + {range: {start: {line: 0, character: 0}, end: {line: 0, character: 0}}, newText: "use Bar;\n"}, + ]}, + {label: "Zap", kind: 7, insertText: "Zap", additionalTextEdits: [ + {range: {start: {line: 2, character: 0}, end: {line: 2, character: 0}}, newText: "MID\n"}, + ]}, + ] + } + }, + + "textDocument/hover": (params: lsp.HoverParams, server): lsp.Hover | null => { + return { + range: {start: params.position, end: params.position}, + contents: {language: "javascript", value: "'hover'"} + } + }, + + "textDocument/signatureHelp": (params: lsp.SignatureHelpParams, server): lsp.SignatureHelp | null => { + return { + signatures: [{ + label: "(a, b) => c", + activeParameter: 1, + parameters: [{label: [1, 2]}, {label: [4, 5]}] + }, { + label: "(x, y) => c", + activeParameter: 1, + parameters: [{label: [1, 2]}, {label: [4, 5]}] + }], + activeSignature: 0, + } + }, + + "custom/sendNotification": (params: {method: string, params: any}, server) => { + server.broadcast({jsonrpc: "2.0", method: params.method, params: params.params}) + }, +} + +const notificationHandlers: {[method: string]: (params: any, server: DummyServer) => void} = { + "initialized": (params: lsp.InitializedParams, server) => { + server.initialized = true + }, + "textDocument/didOpen": (params: lsp.DidOpenTextDocumentParams, server) => { + let {uri, text, languageId} = params.textDocument + if (!server.getFile(params.textDocument.uri)) + server.files.push(new OpenFile(uri, languageId, text)) + }, + "textDocument/didClose": (params: lsp.DidCloseTextDocumentParams, server) => { + server.files = server.files.filter(f => f.uri != params.textDocument.uri) + }, + "textDocument/didChange": (params: lsp.DidChangeTextDocumentParams, server) => { + let file = server.getFile(params.textDocument.uri) + if (file) for (let ch of params.contentChanges) { + if ("range" in ch) + file.text = file.text.slice(0, resolvePosition(file.text, ch.range.start)) + ch.text + + file.text.slice(resolvePosition(file.text, ch.range.end)) + else + file.text = ch.text + } + } +} + +function resolvePosition(text: string, pos: lsp.Position) { + let line = 0, off = 0 + while (line < pos.line) { + let next = text.indexOf("\n", off) + if (!next) throw new RangeError("Position out of bounds") + off = next + 1 + line++ + } + off += pos.character + if (off > text.length) throw new RangeError("Position out of bounds") + return off +} + +function toPosition(text: string, pos: number): lsp.Position { + for (let off = 0, line = 0;;) { + let next = text.indexOf("\n", off) + if (next < 0 || next >= pos) return {line, character: pos - off} + off = next + 1 + line++ + } +} + +class ServerError extends Error { + constructor(readonly code: number, message: string) { super(message) } +} + +class OpenFile { + constructor(readonly uri: string, readonly languageId: string, public text: string) {} +} + +export class DummyServer implements Transport { + initialized = false + subscribers: ((msg: string) => void)[] = [] + files: OpenFile[] = [] + + constructor(readonly config: { + delay?: {[method: string]: number}, + brokenPipe?: () => boolean + } = {}) { + } + + subscribe(listener: (msg: string) => void) { + this.subscribers.push(listener) + } + + unsubscribe(listener: (msg: string) => void) { + this.subscribers = this.subscribers.filter(l => l != listener) + } + + send(message: string) { + if (this.config.brokenPipe?.()) throw new Error("Broken Pipe") + const msg = JSON.parse(message) as lsp.RequestMessage | lsp.NotificationMessage + if ("id" in msg) { + this.handleRequest(msg.method, msg.params).then(result => { + this.broadcast({jsonrpc: "2.0", id: msg.id, result}) + }, e => { + let error = e instanceof ServerError ? {code: e.code, message: e.message} + : {code: -32603 /* InternalError */, message: String(e)} + this.broadcast({jsonrpc: "2.0", id: msg.id, error}) + }) + } else { + this.handleNotification(msg.method, msg.params) + } + } + + broadcast(message: any) { + for (let sub of this.subscribers) sub(JSON.stringify(message)) + } + + handleRequest(method: string, params: Params): Promise { + return new Promise(resolve => { + if (!this.initialized && method != "initialize") + throw new ServerError(-32002 /* ServerNotInitialized */, "Not initialized") + let handler = requestHandlers[method] + if (!handler) throw new ServerError(-32601 /* MethodNotFound */, "Method not found") + let result = handler(params, this), delay = this.config.delay?.[method] + if (delay) setTimeout(() => resolve(result), delay) + else queueMicrotask(() => resolve(result)) + }) + } + + handleNotification(method: string, params: Params) { + let handler = notificationHandlers[method] + if (handler) handler(params, this) + } + + getFile(uri: string) { return this.files.find(f => f.uri == uri) } +} diff --git a/codemirror-lsp-client/test/webtest-client.ts b/codemirror-lsp-client/test/webtest-client.ts new file mode 100644 index 0000000000..79147ebd4f --- /dev/null +++ b/codemirror-lsp-client/test/webtest-client.ts @@ -0,0 +1,403 @@ +import type * as lsp from "vscode-languageserver-protocol" +import ist from "ist" +import {LSPClientConfig, LSPClient, LSPPlugin, renameSymbol, + formatDocument, serverCompletion, hoverTooltips, + showSignatureHelp, nextSignature} from "@codemirror/lsp-client" +import {EditorView, EditorViewConfig} from "@codemirror/view" +import {javascript} from "@codemirror/lang-javascript" +import {syntaxHighlighting} from "@codemirror/language" +import {startCompletion, currentCompletions, acceptCompletion, autocompletion, moveCompletionSelection} from "@codemirror/autocomplete" +import {classHighlighter} from "@lezer/highlight" +import {DummyServer} from "./server.js" + +function setup(conf: {client?: LSPClientConfig, server?: ConstructorParameters[0]} = {}) { + let server = new DummyServer(conf.server) + let client = new LSPClient(conf.client) + client.connect(server) + return {server, client} +} + +const URI = "file:///home/holly/src/test.js" + +function ed(client: LSPClient, conf: EditorViewConfig, uri = URI) { + return new EditorView({...conf, extensions: [conf.extensions || [], LSPPlugin.create(client, uri, "javascript")]}) +} + +function sync(cm: EditorView) { + LSPPlugin.get(cm)!.client.sync() +} + +function wait(ms: number = 2) { + return new Promise(resolve => setTimeout(resolve, ms)) +} + +function place(cm: EditorView) { + let ws = document.querySelector("#workspace")! + while (ws.firstChild) ws.firstChild.remove() + ws.appendChild(cm.dom) + setTimeout(() => cm.destroy(), 1000) + return cm +} + +describe("LSPClient", () => { + it("can connect to a server", () => { + let {client} = setup() + return client.initializing + }) + + it("can open a file", async () => { + let {client, server} = setup() + ed(client, {doc: "stitchwort"}) + await wait() + ist(server.getFile(URI)!.text, "stitchwort") + }) + + it("can update a file", async () => { + let {client, server} = setup() + let cm = ed(client, {doc: "goldenrod"}) + cm.dispatch({changes: {from: 1, insert: "-"}}) + sync(cm) + await wait() + ist(server.getFile(URI)!.text, cm.state.sliceDoc()) + }) + + it("can update a file with multiple changes", async () => { + let {client, server} = setup() + let cm = ed(client, {doc: "hawkweed\n".repeat(1000)}) + await wait() + cm.dispatch({changes: [{from: 0, insert: "<"}, {from: cm.state.doc.length, insert: ">"}]}) + sync(cm) + await wait() + ist(server.getFile(URI)!.text, cm.state.sliceDoc()) + }) + + it("can close a file", async () => { + let {client, server} = setup() + let cm = ed(client, {doc: "cowleek"}) + await wait() + cm.destroy() + await wait() + ist(!server.getFile(URI)) + }) + + it("can open multiple files", async () => { + let {client, server} = setup() + let cm1 = ed(client, {doc: "elder"}), cm2 = ed(client, {doc: "alfalfa"}, "file:///x") + cm1.dispatch({changes: {from: 5, insert: "?"}}) + cm2.dispatch({changes: {from: 7, insert: "!"}}) + sync(cm1) + await wait() + ist(server.getFile(URI)!.text, "elder?") + ist(server.getFile("file:///x")!.text, "alfalfa!") + }) + + it("can provide mapping", async () => { + let {client} = setup() + let cm = ed(client, {doc: "1\n2\n3"}) + await client.withMapping(async mapping => { + let req = client.request("textDocument/formatting", { + textDocument: {uri: URI}, + options: {tabSize: 2, insertSpaces: true} + }) + cm.dispatch({changes: {from: 1, to: 3}}) + let response = await req + ist(response![0].range.start.line, 2) + ist(mapping.mapPos(URI, 5), 3) + }) + }) + + it("can provide mapping across syncs", async () => { + let {client} = setup({server: {delay: {"textDocument/formatting": 10}}}) + let cm = ed(client, {doc: "1\n2\n3"}) + await client.withMapping(async mapping => { + let req = client.request("textDocument/formatting", { + textDocument: {uri: URI}, + options: {tabSize: 2, insertSpaces: true} + }) + cm.dispatch({changes: {from: 1, to: 3}}) + sync(cm) + cm.dispatch({changes: {from: 0, insert: "#"}}) + let response = await req + ist(response![0].range.start.line, 2) + ist(mapping.mapPos(URI, 5), 4) + }) + }) + + it("reports invalid methods", async () => { + let {client} = setup() + try { + await client.request("none/such", {}) + ist(false) + } catch (e: any) { + ist(e.code, -32601) + } + }) + + it("can receive custom notifications", async () => { + let received: any = null + let {client} = setup({client: {notificationHandlers: { + "custom/notification": (client, params) => received = params + }}}) + client.request("custom/sendNotification", {method: "custom/notification", params: {verify: true}}) + await wait() + ist(received.verify) + }) + + it("can report unknown notifications", async () => { + let received: any = null + let {client} = setup({client: {unhandledNotification: (client, method, params) => received = params}}) + client.request("custom/sendNotification", {method: "custom/notification", params: {verify: true}}) + await wait() + ist(received.verify) + }) + + it("can display messages in the editor", async () => { + let {client} = setup() + let cm = ed(client, {}) + client.request("custom/sendNotification", {method: "window/showMessage", params: {type: 2 /* Warning */, message: "WARNING"}}) + await wait() + let dialog = cm.dom.querySelector(".cm-lsp-message-warning")! + ist(dialog) + ist(dialog.innerHTML.indexOf("WARNING"), "-1", ">") + }) + + it("routes exceptions from Transport.send to the request promise", async () => { + let broken = false + let {client} = setup({server: {brokenPipe: () => broken}}) + await client.initializing + broken = true + let req = client.request("test", {}) + try { + await req + ist(false) + } catch (e: any) { + ist(e.message, "Broken Pipe") + } + }) + + describe("LSPPlugin", () => { + it("can attach multiple clients with independent synchronization", async () => { + let first = setup(), second = setup() + let cm = new EditorView({ + doc: "one", + extensions: [ + second.client.plugin(URI, "javascript", { + priority: 10, + features: {formatting: false} + }), + first.client.plugin(URI, "javascript", {priority: 100}) + ] + }) + await Promise.all([first.client.initializing, second.client.initializing]) + await wait() + ist(LSPPlugin.getAll(cm).length, 2) + ist(LSPPlugin.get(cm)!.client, first.client) + ist(LSPPlugin.getAll(cm, "formatting").length, 1) + + cm.dispatch({changes: {from: 3, insert: "!"}}) + first.client.sync() + await wait() + ist(first.server.getFile(URI)!.text, "one!") + ist(second.server.getFile(URI)!.text, "one") + + second.client.sync() + await wait() + ist(second.server.getFile(URI)!.text, "one!") + cm.destroy() + }) + + it("can render doc strings", () => { + let {client} = setup({client: {sanitizeHTML: s => s.replace(/x/g, "y")}}) + let cm = ed(client, {}) + ist(LSPPlugin.get(cm)!.docToHTML({kind: "markdown", value: "# xx"}), "

yy

\n") + }) + + it("can render doc strings with highlighting", () => { + let {client} = setup() + let cm = ed(client, {extensions: [ + javascript(), + syntaxHighlighting(classHighlighter) + ]}) + ist(LSPPlugin.get(cm)!.docToHTML({kind: "markdown", value: "```javascript\nreturn\n```"}), + '
return\n
\n') + }) + + it("can convert to LSP positions", () => { + let {client} = setup() + let cm = ed(client, {doc: "one\ntwo\nthree"}) + let pos = LSPPlugin.get(cm)!.toPosition(6) + ist(pos.line, 1) + ist(pos.character, 2) + }) + + it("can convert from positions", () => { + let {client} = setup() + let cm = ed(client, {doc: "one\ntwo\nthree"}) + ist(LSPPlugin.get(cm)!.fromPosition({line: 0, character: 3}), 3) + ist(LSPPlugin.get(cm)!.fromPosition({line: 2, character: 1}), 9) + }) + + it("can display errors", () => { + let {client} = setup() + let cm = ed(client, {}) + LSPPlugin.get(cm)!.reportError("E", "Oh no") + ist(cm.dom.querySelector(".cm-lsp-message-error")!.innerHTML.indexOf("Oh no"), -1, ">") + }) + }) + + describe("renameSymbol", () => { + it("can run a rename", async () => { + let {client} = setup() + let cm = place(ed(client, {doc: "let foo = 1; console.log(foo)", selection: {anchor: 4}})) + let cm2 = ed(client, {doc: "foo?"}, "file:///2") + await wait() + ist(renameSymbol(cm), true) + let form = cm.dom.querySelector(".cm-panel form") as HTMLFormElement + form.querySelector("input")!.value = "bar" + form.requestSubmit() + await wait() + ist(cm.state.sliceDoc(), "let bar = 1; console.log(bar)") + ist(cm2.state.sliceDoc(), "bar?") + cm.destroy() + }) + + it("can handle changes during the request", async () => { + let {client} = setup({server: {delay: {"textDocument/rename": 5}}}) + let cm = place(ed(client, {doc: "let foo = 1; console.log(foo)", selection: {anchor: 4}})) + await wait() + ist(renameSymbol(cm), true) + let form = cm.dom.querySelector(".cm-panel form") as HTMLFormElement + form.querySelector("input")!.value = "bar" + form.requestSubmit() + await wait() + cm.dispatch({changes: {from: 0, insert: " "}}) + await wait(10) + ist(cm.state.sliceDoc(), " let bar = 1; console.log(bar)") + cm.destroy() + }) + }) + + describe("formatDocument", () => { + it("can make format requests", async () => { + let {client} = setup() + let cm = ed(client, {doc: "hawthorn"}) + formatDocument(cm) + await wait() + ist(cm.state.sliceDoc(), "hawthorn\n// formatted!") + }) + }) + + describe("completion", () => { + it("can get completions from the server", async () => { + let {client} = setup() + let cm = ed(client, {doc: "..o", selection: {anchor: 3}, extensions: [ + serverCompletion(), + autocompletion({interactionDelay: 0, activateOnTypingDelay: 10}) + ]}) + startCompletion(cm) + await wait(60) + let cs = currentCompletions(cm.state) + ist(cs.length, 2) + ist(cs[0].label, "one") + ist(cs[1].label, "ookay") + acceptCompletion(cm) + ist(cm.state.sliceDoc(), "..one!") + cm.dispatch({changes: {from: 6, insert: "\no"}, userEvent: "input.type", selection: {anchor: 8}}) + await wait(20) + ist(currentCompletions(cm.state).length, 2) + moveCompletionSelection(true)(cm) + await wait() + ist(cm.dom.querySelector(".cm-completionInfo")) + acceptCompletion(cm) + ist(cm.state.sliceDoc(), "..one!\nokay") + }) + + it("expands snippet completions and unescapes LSP escapes", async () => { + let {client} = setup() + let cm = ed(client, {doc: "..f", selection: {anchor: 3}, extensions: [ + serverCompletion(), + autocompletion({interactionDelay: 0, activateOnTypingDelay: 10}) + ]}) + startCompletion(cm) + await wait(60) + let cs = currentCompletions(cm.state) + ist(cs.length, 1) + ist(cs[0].label, "fn") + acceptCompletion(cm) + // `\$arg` must come through as a literal `$arg`, not the raw `\$arg`. + ist(cm.state.sliceDoc(), "..fn($arg)") + }) + + it("applies additionalTextEdits (e.g. an auto-import)", async () => { + let {client} = setup() + let cm = ed(client, {doc: "..b", selection: {anchor: 3}, extensions: [ + serverCompletion(), + autocompletion({interactionDelay: 0, activateOnTypingDelay: 10}) + ]}) + startCompletion(cm) + await wait(60) + let cs = currentCompletions(cm.state) + ist(cs.length, 1) + ist(cs[0].label, "Bar") + acceptCompletion(cm) + // The completion inserts "Bar" *and* the item's additionalTextEdits add + // the `use Bar;` line at the top. + ist(cm.state.sliceDoc(), "use Bar;\n..Bar") + }) + + it("maps additionalTextEdit positions through changes that arrive while the completion is active", async () => { + let {client} = setup() + // Server's "Zap" completion ships an additionalTextEdit at line 2, + // char 0 — i.e. the start of "L2" in this document. + let cm = ed(client, {doc: "L0\nL1\nL2\n..z", selection: {anchor: 12}, extensions: [ + serverCompletion(), + autocompletion({interactionDelay: 0, activateOnTypingDelay: 10}) + ]}) + startCompletion(cm) + await wait(60) + let cs = currentCompletions(cm.state) + ist(cs.length, 1) + ist(cs[0].label, "Zap") + // Insert a line at the very top. This is far from the cursor, so CM + // keeps the completion alive — but the LSP edit's `line: 2` now refers + // to a different line in the new document. + cm.dispatch({changes: {from: 0, insert: "HEADER\n"}}) + acceptCompletion(cm) + // The "MID\n" insertion should land before the *original* L2 line, + // which after the HEADER insertion is the third line. + ist(cm.state.sliceDoc(), "HEADER\nL0\nL1\nMID\nL2\n..Zap") + }) + }) + + describe("hoverTooltips", () => { + it("can retrieve hover info", async () => { + let {client} = setup() + let cm = place(ed(client, {doc: "speedwell", extensions: [ + hoverTooltips({hoverTime: 10}), + javascript(), + syntaxHighlighting(classHighlighter) + ]})) + let pos = cm.coordsAtPos(1)!, x = pos.left, y = pos.top + 5 + cm.contentDOM.firstChild!.dispatchEvent(new MouseEvent("mousemove", { + screenX: x, screenY: y, + clientX: x, clientY: y, + bubbles: true + })) + await wait(15) + ist(cm.dom.querySelector(".cm-tooltip .tok-string")) + cm.destroy() + }) + }) + + describe("signatureHelp", () => { + it("can display a signature", async () => { + let {client} = setup() + let cm = ed(client, {doc: "bugloss"}) + showSignatureHelp(cm) + await wait() + ist(cm.dom.querySelector(".cm-lsp-active-parameter")!.innerHTML, "b") + nextSignature(cm) + ist(cm.dom.querySelector(".cm-lsp-active-parameter")!.innerHTML, "y") + }) + }) +}) diff --git a/config.xml b/config.xml deleted file mode 100644 index 0241142964..0000000000 --- a/config.xml +++ /dev/null @@ -1,341 +0,0 @@ - - - Acode - - Light weight code editor and web IDE for android. - - - Foxdebug - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/utils/code-editor-icon.icomoon.json b/dev/code-editor-icon.icomoon.json similarity index 100% rename from utils/code-editor-icon.icomoon.json rename to dev/code-editor-icon.icomoon.json diff --git a/dev/config.js b/dev/config.js new file mode 100755 index 0000000000..d9593f8b3b --- /dev/null +++ b/dev/config.js @@ -0,0 +1,59 @@ +const fs = require("node:fs"); +const path = require("node:path"); +const ads = require("../ads.json"); +const ID_PAID = "com.foxdebug.acode"; +const ID_FREE = "com.foxdebug.acodefree"; + +module.exports = { getAppConfig, getWebBundlePath, getAdConfig }; + +function getAdConfig(platform, mode) { + const release = mode === "Release"; + const config = ads[platform]?.[release ? "production" : "test"]; + if (!config) throw new Error(`Unsupported advertising platform: ${platform}`); + for (const name of [ + "appId", + "banner", + "interstitial", + "rewarded", + "appOpen", + ]) { + const id = config[name]; + const separator = name === "appId" ? "~" : "/"; + const pattern = new RegExp(`^ca-app-pub-\\d{16}${separator}\\d{10}$`); + if ( + !pattern.test(id) || + (release && id.startsWith("ca-app-pub-3940256099942544")) + ) { + throw new Error( + `Invalid ${platform} ${name} ID in ads.json for ${mode}.`, + ); + } + } + return config; +} + +function getAppConfig(platform = process.env.ACODE_PLATFORM || "android") { + const { androidPackageId, appleAppId } = JSON.parse( + fs.readFileSync(path.resolve(__dirname, "../package.json"), "utf8"), + ); + if (platform === "ios") return { variant: "free", targetId: appleAppId }; + if (![ID_PAID, ID_FREE].includes(androidPackageId)) { + throw new Error( + `Set package.json androidPackageId to ${ID_PAID} (paid) or ${ID_FREE} (free).`, + ); + } + return { + variant: androidPackageId === ID_FREE ? "free" : "paid", + targetId: androidPackageId, + }; +} + +function getWebBundlePath(platform = process.env.ACODE_PLATFORM || "android") { + return path.resolve( + __dirname, + "..", + platform === "ios" + ? "platforms/ios/runner/bundle" + : "platforms/android/app/src/main/assets/bundle", + ); +} diff --git a/utils/custom-loaders/html-tag-jsx-loader.js b/dev/custom-loaders/html-tag-jsx-loader.js similarity index 100% rename from utils/custom-loaders/html-tag-jsx-loader.js rename to dev/custom-loaders/html-tag-jsx-loader.js diff --git a/dev/ios/skadnetwork.json b/dev/ios/skadnetwork.json new file mode 100644 index 0000000000..6aa4e24b3b --- /dev/null +++ b/dev/ios/skadnetwork.json @@ -0,0 +1,52 @@ +[ + "cstr6suwn9.skadnetwork", + "4fzdc2evr5.skadnetwork", + "2fnua5tdw4.skadnetwork", + "ydx93a7ass.skadnetwork", + "p78axxw29g.skadnetwork", + "v72qych5uu.skadnetwork", + "ludvb6z3bs.skadnetwork", + "cp8zw746q7.skadnetwork", + "3sh42y64q3.skadnetwork", + "c6k4g5qg8m.skadnetwork", + "s39g8k73mm.skadnetwork", + "wg4vff78zm.skadnetwork", + "3qy4746246.skadnetwork", + "f38h382jlk.skadnetwork", + "hs6bdukanm.skadnetwork", + "mlmmfzh3r3.skadnetwork", + "v4nxqhlyqp.skadnetwork", + "wzmmz9fp6w.skadnetwork", + "su67r6k2v3.skadnetwork", + "yclnxrl5pm.skadnetwork", + "t38b2kh725.skadnetwork", + "7ug5zh24hu.skadnetwork", + "gta9lk7p23.skadnetwork", + "vutu7akeur.skadnetwork", + "y5ghdn5j9k.skadnetwork", + "v9wttpbfk9.skadnetwork", + "n38lu8286q.skadnetwork", + "47vhws6wlr.skadnetwork", + "kbd757ywx3.skadnetwork", + "9t245vhmpl.skadnetwork", + "a2p9lx4jpn.skadnetwork", + "22mmun2rn5.skadnetwork", + "44jx6755aq.skadnetwork", + "k674qkevps.skadnetwork", + "4468km3ulz.skadnetwork", + "2u9pt9hc89.skadnetwork", + "8s468mfl3y.skadnetwork", + "klf5c3l5u5.skadnetwork", + "ppxm28t8ap.skadnetwork", + "kbmxgpxpgc.skadnetwork", + "uw77j35x4d.skadnetwork", + "578prtvx9j.skadnetwork", + "4dzt52r2t5.skadnetwork", + "tl55sbb4fm.skadnetwork", + "c3frkrj4fj.skadnetwork", + "e5fvkxwrpn.skadnetwork", + "8c4e2ghe7u.skadnetwork", + "3rd42ekr43.skadnetwork", + "97r2b46745.skadnetwork", + "3qcr597p9d.skadnetwork" +] diff --git a/utils/lang.js b/dev/lang.js similarity index 100% rename from utils/lang.js rename to dev/lang.js diff --git a/dev/scripts/android.js b/dev/scripts/android.js new file mode 100644 index 0000000000..dc41880147 --- /dev/null +++ b/dev/scripts/android.js @@ -0,0 +1,139 @@ +const fs = require("node:fs"); +const path = require("node:path"); +const { spawnSync } = require("node:child_process"); +const { getAppConfig } = require("../config"); +const { sync } = require("../sync"); +const root = path.resolve(__dirname, "../.."); + +module.exports = { parseOptions, build, launch }; +if (require.main === module) { + try { + const args = process.argv.slice(2); + const options = parseOptions(args); + if (args.includes("test")) { + runGradle(`test${capitalize(variantFlavor(options))}DebugUnitTest`); + } else { + const artifact = build(options); + if (args.includes("run")) launch(options, artifact); + } + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } +} + +function parseOptions(args) { + if (args.some((arg) => /^(free|paid)$/i.test(arg))) { + throw new Error( + "Choose free or paid with package.json androidPackageId; remove the free/paid argument.", + ); + } + return { + ...getAppConfig("android"), + mode: args.some((arg) => ["p", "prod"].includes(arg)) ? "p" : "d", + channel: args.includes("fdroid") ? "fdroid" : "store", + bundle: args.includes("bundle"), + skipWeb: args.includes("--skip-web"), + target: args.find((arg) => arg.startsWith("--target="))?.slice(9), + emulator: args.includes("--emulator") || args.includes("-e"), + }; +} + +function build(options) { + sync(); + if (!options.skipWeb) { + run( + process.execPath, + [ + path.join( + path.dirname(require.resolve("@rspack/cli/package.json")), + "bin/rspack.js", + ), + "--mode", + options.mode === "p" ? "production" : "development", + ], + { + ACODE_PLATFORM: "android", + ACODE_FDROID: String(options.channel === "fdroid"), + }, + ); + } + const type = options.mode === "p" ? "release" : "debug"; + const flavor = variantFlavor(options); + const task = `${options.bundle ? "bundle" : "assemble"}${capitalize(flavor)}${capitalize(type)}`; + runGradle(task); + const outputs = path.join(root, "platforms/android/app/build/outputs"); + const extension = options.bundle ? "aab" : "apk"; + const file = `app-${options.variant}-${options.channel}-${type}.${extension}`; + let source = options.bundle + ? path.join(outputs, "bundle", flavor + capitalize(type), file) + : path.join(outputs, "apk", flavor, type, file); + const unsigned = !options.bundle && !fs.existsSync(source); + if (unsigned) source = source.replace(/\.apk$/, "-unsigned.apk"); + const destination = path.join( + outputs, + options.bundle ? "bundle" : "apk", + type, + `app-${type}${unsigned ? "-unsigned" : ""}.${extension}`, + ); + fs.mkdirSync(path.dirname(destination), { recursive: true }); + fs.copyFileSync(source, destination); + console.log(`Built ${destination}`); + return destination; +} + +function launch(options, artifact) { + const args = options.target + ? ["-s", options.target] + : options.emulator + ? ["-e"] + : []; + const sdk = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT; + const adb = sdk + ? path.join( + sdk, + "platform-tools", + process.platform === "win32" ? "adb.exe" : "adb", + ) + : "adb"; + const id = options.targetId; + run(adb, [...args, "install", "-r", artifact]); + run(adb, [ + ...args, + "shell", + "am", + "start", + "-n", + `${id}/com.foxdebug.acode.MainActivity`, + ]); +} + +function gradle() { + return path.join( + root, + "platforms/android", + process.platform === "win32" ? "gradlew.bat" : "gradlew", + ); +} +function runGradle(task) { + run(gradle(), ["-p", "platforms/android", `:app:${task}`, "--console=plain"]); +} +function variantFlavor(options) { + return options.variant + capitalize(options.channel); +} +function capitalize(value) { + return value[0].toUpperCase() + value.slice(1); +} +function run(command, args, env = {}) { + const result = spawnSync(command, args, { + cwd: root, + env: { ...process.env, ...env }, + stdio: "inherit", + shell: process.platform === "win32" && command.endsWith(".bat"), + }); + if (result.error) throw result.error; + if (result.status !== 0) + throw new Error( + `${path.basename(command)} failed with exit code ${result.status}`, + ); +} diff --git a/dev/scripts/build.sh b/dev/scripts/build.sh new file mode 100644 index 0000000000..48017320b8 --- /dev/null +++ b/dev/scripts/build.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +exec node dev/scripts/native.js "$@" diff --git a/dev/scripts/dev.js b/dev/scripts/dev.js new file mode 100644 index 0000000000..3ef4e5a545 --- /dev/null +++ b/dev/scripts/dev.js @@ -0,0 +1,461 @@ +#!/usr/bin/env node + +/** + * Acode Dev Orchestrator + * + * Starts: + * 1. HTTP static file server (serves the platform bundle) + WebSocket reload relay (same port) + * 2. rspack --watch with DEV_MODE enabled + * 3. Acode native build/install (after first successful compilation) + * 4. File watcher on native sources and JavaScript APIs for rebuilds + * + * The app retains its local origin and loads dev scripts when reachable, + * otherwise using the assets bundled in the app. + * A WebSocket connection from the app receives "reload" messages on recompile. + */ + +const { spawn, execSync } = require("node:child_process"); +const fs = require("node:fs"); +const path = require("node:path"); +const https = require("node:https"); +const net = require("node:net"); +const { WebSocketServer } = require("ws"); +const os = require("node:os"); +const { getWebBundlePath } = require("../config"); + +// ─── helpers ──────────────────────────────────────────────────────────────── + +const ROOT = path.resolve(__dirname, "../.."); +let currentOptions; +const MIME = { + ".html": "text/html", + ".js": "application/javascript", + ".mjs": "application/javascript", + ".css": "text/css", + ".json": "application/json", + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".gif": "image/gif", + ".svg": "image/svg+xml", + ".ico": "image/x-icon", + ".woff": "font/woff", + ".woff2": "font/woff2", + ".ttf": "font/ttf", + ".map": "application/json", +}; + +function getLocalIP() { + const interfaces = os.networkInterfaces(); + for (const iface of Object.values(interfaces)) { + if (!iface) continue; + for (const addr of iface) { + if (addr.family === "IPv4" && !addr.internal) { + // Prefer 192.168.x.x or 10.x.x.x over other private ranges + if ( + addr.address.startsWith("192.168.") || + addr.address.startsWith("10.") + ) { + return addr.address; + } + } + } + } + // Fallback: any non-internal IPv4 + for (const iface of Object.values(interfaces)) { + if (!iface) continue; + for (const addr of iface) { + if (addr.family === "IPv4" && !addr.internal) { + return addr.address; + } + } + } + return "127.0.0.1"; +} + +function getFreePort() { + return new Promise((resolve, reject) => { + const server = net.createServer(); + server.listen(0, () => { + const port = server.address().port; + server.close(() => resolve(port)); + }); + server.on("error", reject); + }); +} + +function log(label, msg) { + const reset = "\x1b[0m"; + const green = "\x1b[92m"; + const yellow = "\x1b[93m"; + const blue = "\x1b[94m"; + const colors = { info: blue, ok: green, warn: yellow }; + const c = colors[label] || reset; + console.log(` ${c}[${label}]${reset} ${msg}`); +} + +function resolveSpawnCommand(command) { + if (process.platform !== "win32") return command; + const lower = command.toLowerCase(); + if (lower.endsWith(".cmd") || lower.endsWith(".exe")) return command; + if (lower === "npx" || lower === "npm") { + return `${command}.cmd`; + } + return command; +} + +function buildSpawnEnv(extra = {}) { + const merged = { ...process.env, ...extra }; + const sanitized = {}; + + for (const [key, value] of Object.entries(merged)) { + if (!key || key.startsWith("=") || value === undefined) continue; + sanitized[key] = String(value); + } + + return sanitized; +} + +function spawnAsync(command, args, options) { + return new Promise((resolve, reject) => { + const mergedOptions = { + stdio: "inherit", + ...options, + env: options?.env ? buildSpawnEnv(options.env) : options?.env, + }; + const proc = spawn(resolveSpawnCommand(command), args, mergedOptions); + proc.on("close", (code) => { + if (code === 0) resolve(); + else reject(new Error(`${command} exited with code ${code}`)); + }); + proc.on("error", reject); + }); +} + +// ─── self-signed certificate ───────────────────────────────────────────────── + +let _cachedCert = null; + +function getDevCert() { + if (_cachedCert) return _cachedCert; + + const certPath = path.join(ROOT, ".dev-cert.pem"); + const keyPath = path.join(ROOT, ".dev-key.pem"); + + // Reuse existing cert if available + if (fs.existsSync(certPath) && fs.existsSync(keyPath)) { + _cachedCert = { + cert: fs.readFileSync(certPath), + key: fs.readFileSync(keyPath), + }; + return _cachedCert; + } + + // Generate via openssl (available on macOS, Linux, and Git Bash on Windows) + try { + execSync( + `openssl req -x509 -newkey rsa:2048 -keyout "${keyPath}" -out "${certPath}" -days 365 -nodes -subj "/CN=acode-dev"`, + { stdio: "pipe" }, + ); + _cachedCert = { + cert: fs.readFileSync(certPath), + key: fs.readFileSync(keyPath), + }; + log("ok", "Generated self-signed dev certificate"); + return _cachedCert; + } catch (_e) { + // openssl not available + } + + log("warn", "openssl not found — falling back to HTTP"); + return null; +} + +// ─── HTTPS + WebSocket server ───────────────────────────────────────────────── + +async function createServer(port, useTLS = true) { + const tls = useTLS ? getDevCert() : null; + let server; + + if (tls) { + server = https.createServer(tls, handleRequest); + } else { + if (useTLS) { + log("warn", "No TLS certificate — falling back to HTTP"); + log("warn", "Install openssl to enable HTTPS for your dev server"); + } + const http = require("node:http"); + server = http.createServer(handleRequest); + } + + const wss = new WebSocketServer({ server }); + + wss.on("connection", (ws) => { + log("info", "App connected via WebSocket"); + ws.on("error", () => {}); + }); + + return { + server, + wss, + broadcast: (msg) => broadcast(wss, msg), + isHttps: !!tls, + protocol: tls ? "https" : "http", + }; +} + +function handleRequest(req, res) { + let urlPath = req.url.split("?")[0]; + if (urlPath === "/") urlPath = "/index.html"; + const relative = path.normalize(urlPath).replace(/^\/+/, ""); + const bundle = getWebBundlePath(currentOptions.platform); + const filePath = path.join(bundle, relative); + if (!filePath.startsWith(bundle + path.sep) && filePath !== bundle) { + res.writeHead(403); + res.end("Forbidden"); + return; + } + + const ext = path.extname(filePath).toLowerCase(); + const contentType = MIME[ext] || "application/octet-stream"; + + fs.readFile(filePath, (err, data) => { + if (err) { + res.writeHead(404); + res.end("Not found"); + return; + } + res.writeHead(200, { + "Content-Type": contentType, + "Access-Control-Allow-Origin": "*", + "Cache-Control": "no-cache, no-store, must-revalidate", + }); + res.end(data); + }); +} + +function broadcast(wss, message) { + if (typeof message !== "string") { + message = JSON.stringify(message); + } + for (const client of wss.clients) { + if (client.readyState === 1) { + client.send(message); + } + } +} + +// Native build helpers +async function launchApp(target, platform, emulator) { + const args = [ + path.join(ROOT, `dev/scripts/${platform}.js`), + "run", + "--skip-web", + ]; + if (currentOptions.channel === "fdroid") args.push("fdroid"); + if (currentOptions.device) args.push("--device"); + if (target) args.push(`--target=${target}`); + if (emulator && platform === "android") args.push("--emulator"); + await spawnAsync(process.execPath, args, { cwd: ROOT }); +} + +// ─── rspack watcher ────────────────────────────────────────────────────────── + +function startRspackWatch(host, port, proto, onCompiled) { + log("info", "Starting rspack --watch..."); + + const env = buildSpawnEnv({ + DEV_MODE: "true", + ACODE_PLATFORM: currentOptions.platform, + ACODE_FDROID: String(currentOptions.channel === "fdroid"), + DEV_HOST: host, + DEV_PORT: String(port), + DEV_PROTO: proto, + }); + const rspackBin = path.join( + ROOT, + "node_modules", + "@rspack", + "cli", + "bin", + "rspack.js", + ); + + const useLocalRspack = fs.existsSync(rspackBin); + if (!useLocalRspack) { + log("warn", "Local rspack CLI not found, falling back to npx rspack"); + } + + const proc = useLocalRspack + ? spawn(process.execPath, [rspackBin, "--watch", "--mode", "development"], { + cwd: ROOT, + env, + stdio: "pipe", + }) + : spawn( + resolveSpawnCommand("npx"), + ["rspack", "--watch", "--mode", "development"], + { + cwd: ROOT, + env, + stdio: "pipe", + }, + ); + + let firstCompile = true; + + proc.stdout.on("data", (chunk) => { + const text = chunk.toString(); + process.stdout.write(text); + if (text.includes("compiled successfully") || text.includes("compiled")) { + if (firstCompile) { + firstCompile = false; + } + onCompiled(); + } + }); + + proc.stderr.on("data", (chunk) => { + process.stderr.write(chunk); + }); + + proc.on("error", (err) => { + log("warn", `rspack error: ${err.message}`); + log("warn", "rspack watcher failed to start; exiting dev mode"); + process.exit(1); + }); + + proc.on("close", (code) => { + if (code !== 0 && code !== null) { + log("warn", `rspack exited with code ${code}`); + } + }); + + return proc; +} + +function watchNative(platform, target, emulator) { + if (platform === "ios" && !target) return; + const chokidar = require("chokidar"); + let timer; + let building = false; + let pending = false; + const sources = + platform === "ios" + ? [ + "platforms/ios/runner", + "platforms/ios/ads", + "dev/ios", + "dev/scripts/iosAds.js", + "platforms/ios/runner.xcodeproj/project.pbxproj", + "platforms/ios/Config.xcconfig", + ] + : ["platforms/android/app/src"]; + const watcher = chokidar.watch( + sources.map((source) => path.join(ROOT, source)), + { + ignoreInitial: true, + ignored: (file) => file.split(path.sep).includes("bundle"), + awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 100 }, + }, + ); + watcher.on("all", () => { + pending = true; + clearTimeout(timer); + timer = setTimeout(rebuild, 1000); + }); + async function rebuild() { + if (building || !pending) return; + building = true; + pending = false; + try { + await launchApp(target, platform, emulator); + } catch (error) { + log("warn", `${platform} rebuild failed: ${error.message}`); + } finally { + building = false; + if (pending) void rebuild(); + } + } +} + +// ─── main ──────────────────────────────────────────────────────────────────── + +async function main() { + const args = process.argv.slice(2); + const platform = ( + args.find((a) => /^(android|ios|browser)$/i.test(a)) || "android" + ).toLowerCase(); + if (platform === "browser") + throw new Error("Choose android or ios for native development."); + if (platform === "ios" && process.platform !== "darwin") + throw new Error("iOS development requires macOS and Xcode."); + currentOptions = { ...require(`./${platform}`).parseOptions(args), platform }; + const target = + args.find((a) => a.startsWith("--target="))?.split("=")[1] || null; + const emulator = args.includes("--emulator") || args.includes("-e"); + + console.log("\n ⚡ Acode Dev Mode\n"); + + log( + "info", + `Configuring ${currentOptions.targetId} (${currentOptions.variant})...`, + ); + + const simulator = platform === "ios" && !!target; + const host = simulator ? "127.0.0.1" : getLocalIP(); + const port = await getFreePort(); + + log("info", `Local IP: ${host}`); + log("info", `Port: ${port}`); + + // 2. Start HTTPS (or HTTP fallback) + WebSocket server + const { server, broadcast, protocol } = await createServer( + port, + platform !== "ios", + ); + const origin = `${protocol}://${host}:${port}`; + log("info", `Dev Origin: ${origin}`); + server.listen(port, platform === "ios" ? host : undefined, () => { + log("ok", "Dev server started"); + }); + + // 3. Start rspack --watch + let appLaunched = false; + + startRspackWatch(host, port, protocol, () => { + broadcast("reload"); + + if (!appLaunched) { + appLaunched = true; + setTimeout(async () => { + try { + await launchApp(target, platform, emulator); + } catch (err) { + log("warn", `Launch failed: ${err.message}`); + } + }, 3000); + } + }); + + watchNative(platform, target, emulator); + + // Graceful shutdown + process.on("SIGINT", () => { + log("info", "Shutting down..."); + server.close(); + process.exit(0); + }); + + process.on("SIGTERM", () => { + server.close(); + process.exit(0); + }); +} + +if (require.main === module) { + main().catch((err) => { + console.error(err); + process.exit(1); + }); +} diff --git a/utils/scripts/generate-release-notes.js b/dev/scripts/generate-release-notes.js similarity index 100% rename from utils/scripts/generate-release-notes.js rename to dev/scripts/generate-release-notes.js diff --git a/dev/scripts/ios.js b/dev/scripts/ios.js new file mode 100644 index 0000000000..9baa6b3dca --- /dev/null +++ b/dev/scripts/ios.js @@ -0,0 +1,167 @@ +const path = require("node:path"); +const { spawnSync } = require("node:child_process"); +const { getAppConfig } = require("../config"); +const { sync } = require("../sync"); +const { prepareAds } = require("./iosAds"); +const root = path.resolve(__dirname, "../.."); + +module.exports = { parseOptions, build, launch }; +if (require.main === module) { + try { + const args = process.argv.slice(2); + const options = parseOptions(args); + const artifact = + args.includes("run") && (!options.target || options.device) + ? prepare(options) + : build(options); + if (args.includes("run")) launch(options, artifact); + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } +} + +function parseOptions(args) { + if (args.some((arg) => /^(free|paid|fdroid|apk|bundle)$/i.test(arg))) { + throw new Error("iOS has one free edition; use ios dev or ios prod."); + } + if ( + args.includes("--device") && + args.some((arg) => arg.startsWith("--target=")) + ) + throw new Error( + "For an iPhone, omit --target and select the device in Xcode.", + ); + return { + ...getAppConfig("ios"), + mode: args.some((arg) => ["p", "prod"].includes(arg)) ? "Release" : "Debug", + action: args.includes("test") ? "test" : "build", + skipWeb: args.includes("--skip-web"), + skipTests: args.filter((arg) => arg.startsWith("-skip-testing:")), + device: args.includes("--device"), + target: args.find((arg) => arg.startsWith("--target="))?.slice(9), + }; +} + +function prepare(options) { + if (process.platform !== "darwin") + throw new Error("iOS builds require macOS and Xcode."); + sync(); + if (!options.skipWeb) { + run( + process.execPath, + [ + path.join( + path.dirname(require.resolve("@rspack/cli/package.json")), + "bin/rspack.js", + ), + "--mode", + options.mode === "Release" ? "production" : "development", + ], + { ACODE_PLATFORM: "ios", ACODE_FDROID: "false" }, + ); + } + prepareAds(options.mode); +} + +function build(options) { + if (options.action === "test" && (!options.target || options.device)) + throw new Error("iOS tests require --target=."); + prepare(options); + const sdk = options.device ? "iphoneos" : "iphonesimulator"; + run("xcodebuild", [ + "-project", + "platforms/ios/runner.xcodeproj", + "-scheme", + "runner", + "-configuration", + options.mode, + "-sdk", + sdk, + "-destination", + options.action === "test" + ? `platform=iOS Simulator,id=${options.target}` + : options.device + ? "generic/platform=iOS" + : "generic/platform=iOS Simulator", + "-derivedDataPath", + ".ios-build", + "-clonedSourcePackagesDirPath", + ".ios-build/SourcePackages", + ...(options.device + ? ["CODE_SIGNING_ALLOWED=NO"] + : ["CODE_SIGNING_ALLOWED=YES", "CODE_SIGN_IDENTITY=-"]), + ...(options.action === "test" + ? [ + "-parallel-testing-enabled", + "NO", + "-collect-test-diagnostics", + "never", + ...(options.skipTests || []), + ] + : []), + options.action, + ]); + const artifact = path.join( + root, + ".ios-build/Build/Products", + `${options.mode}-${sdk}`, + "runner.app", + ); + console.log(`${options.action === "test" ? "Tested" : "Built"} ${artifact}`); + return artifact; +} + +function launch(options, artifact) { + if (options.device || !options.target) { + run("open", [ + "-b", + "com.apple.dt.Xcode", + path.join(root, "platforms/ios/runner.xcodeproj"), + ]); + console.log( + "In Xcode, select the runner scheme and your iPhone, then press Cmd+R to build and install.", + ); + if (options.mode === "Release") + console.log("Set the scheme's Run build configuration to Release."); + return; + } + const target = options.target; + const devices = JSON.parse( + run( + "xcrun", + ["simctl", "list", "devices", "available", "--json"], + {}, + true, + ), + ); + const device = Object.values(devices.devices) + .flat() + .find((device) => device.udid === target); + if (!device) + throw new Error( + `Simulator ${target} not found. For an iPhone, omit --target and select the device in Xcode.`, + ); + if (device.state !== "Booted") run("xcrun", ["simctl", "boot", target]); + run("xcrun", ["simctl", "bootstatus", target, "-b"]); + spawnSync("xcrun", ["simctl", "terminate", target, options.targetId], { + stdio: "ignore", + }); + run("xcrun", ["simctl", "install", target, artifact]); + run("xcrun", ["simctl", "launch", target, options.targetId]); +} + +function run(command, args, env = {}, capture = false) { + const result = spawnSync(command, args, { + cwd: root, + env: { ...process.env, ...env }, + stdio: capture ? "pipe" : "inherit", + encoding: "utf8", + }); + if (result.error) throw result.error; + if (result.status !== 0) + throw new Error( + result.stderr || `${command} failed with exit code ${result.status}`, + ); + return result.stdout; +} diff --git a/dev/scripts/iosAds.js b/dev/scripts/iosAds.js new file mode 100644 index 0000000000..bc15137191 --- /dev/null +++ b/dev/scripts/iosAds.js @@ -0,0 +1,36 @@ +const fs = require("node:fs"); +const path = require("node:path"); +const { execFileSync } = require("node:child_process"); +const networks = require("../ios/skadnetwork.json"); +const { getAdConfig } = require("../config"); +const root = path.resolve(__dirname, "../.."); + +module.exports = { prepareAds }; + +function prepareAds(mode) { + const { appId } = getAdConfig("ios", mode); + const file = path.join(root, ".ios-build/App-Info.plist"); + fs.mkdirSync(path.dirname(file), { recursive: true }); + execFileSync("plutil", [ + "-convert", + "xml1", + "-o", + file, + path.join(root, "platforms/ios/runner/Info.plist"), + ]); + for (const [key, value] of Object.entries({ + GADApplicationIdentifier: appId, + GADDelayAppMeasurementInit: true, + NSUserTrackingUsageDescription: + "Your permission helps show relevant ads that support the free version of Acode.", + SKAdNetworkItems: networks.map((id) => ({ SKAdNetworkIdentifier: id })), + })) { + execFileSync("plutil", [ + "-insert", + key, + "-json", + JSON.stringify(value), + file, + ]); + } +} diff --git a/dev/scripts/native.js b/dev/scripts/native.js new file mode 100644 index 0000000000..a7db8d84d4 --- /dev/null +++ b/dev/scripts/native.js @@ -0,0 +1,16 @@ +const { spawnSync } = require("node:child_process"); +const path = require("node:path"); +const args = process.argv.slice(2); +const platform = args.includes("ios") ? "ios" : "android"; +if ( + !args.some((arg) => ["run", "test", "d", "dev", "p", "prod"].includes(arg)) +) { + args.push("prod"); +} +const result = spawnSync( + process.execPath, + [path.join(__dirname, `${platform}.js`), ...args], + { stdio: "inherit" }, +); +if (result.error) throw result.error; +process.exitCode = result.status ?? 1; diff --git a/dev/scripts/start.sh b/dev/scripts/start.sh new file mode 100644 index 0000000000..7bc5b6b42c --- /dev/null +++ b/dev/scripts/start.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +exec node dev/scripts/native.js run "$@" diff --git a/dev/storage_manager.mjs b/dev/storage_manager.mjs new file mode 100644 index 0000000000..10fe2e4b01 --- /dev/null +++ b/dev/storage_manager.mjs @@ -0,0 +1,19 @@ +#!/usr/bin/env node +import readline from "node:readline/promises"; +import { readFile, writeFile } from "node:fs/promises"; + +const manifest = new URL("../platforms/android/app/src/main/AndroidManifest.xml", import.meta.url); +const args = process.argv.slice(2); +let answer = args[0]; +if (!answer) { + const prompt = readline.createInterface({ input: process.stdin, output: process.stdout }); + answer = await prompt.question("Enable 'MANAGE_EXTERNAL_STORAGE' permission? Y/n: "); + prompt.close(); +} +if (!["y", "yes", "--yes", "-y", "n", "no", "--no", "-n"].includes(answer.toLowerCase())) throw new Error("Choose yes or no."); +const enabled = ["y", "yes", "--yes", "-y"].includes(answer.toLowerCase()); +const source = await readFile(manifest, "utf8"); +const permission = ' '; +const clean = source.replace(/\s*/g, ""); +await writeFile(manifest, enabled ? clean.replace("", `${permission}\n`) : clean); +console.log(`All-files access ${enabled ? "enabled" : "disabled"} for the next Android build.`); diff --git a/dev/stripSourceMapComments.js b/dev/stripSourceMapComments.js new file mode 100644 index 0000000000..3f9bf5c4a1 --- /dev/null +++ b/dev/stripSourceMapComments.js @@ -0,0 +1,46 @@ +const { rspack } = require("@rspack/core"); + +const LINE_COMMENT = /\/\/[#@][ \t]*sourceMappingURL=[^\n\r]*/g; +const BLOCK_COMMENT = /\/\*[#@][ \t]*sourceMappingURL=[\s\S]*?\*\//g; + +/** + * Removes stale sourceMappingURL comments left in bundled dependencies. + * + * Rspack emits no `.map` files, but some vendored libraries (e.g. TypeScript's + * worker) keep a `//# sourceMappingURL=` comment in the middle of their source. + * WebKit honors it, requests the missing map through the app scheme handler, and + * logs a failed resource load. + */ +class StripSourceMapCommentsPlugin { + apply(compiler) { + compiler.hooks.thisCompilation.tap( + StripSourceMapCommentsPlugin.name, + (compilation) => { + compilation.hooks.processAssets.tap( + { + name: StripSourceMapCommentsPlugin.name, + stage: rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE, + }, + (assets) => { + for (const name of Object.keys(assets)) { + if (!/\.(?:m?js|css)$/.test(name)) continue; + const asset = compilation.getAsset(name); + const text = asset.source.source().toString(); + const stripped = text + .replace(LINE_COMMENT, "") + .replace(BLOCK_COMMENT, ""); + if (stripped !== text) { + compilation.updateAsset( + name, + new rspack.sources.RawSource(stripped), + ); + } + } + }, + ); + }, + ); + } +} + +module.exports = StripSourceMapCommentsPlugin; diff --git a/dev/sync.js b/dev/sync.js new file mode 100644 index 0000000000..c7fc7e7a8f --- /dev/null +++ b/dev/sync.js @@ -0,0 +1,85 @@ +const fs = require("node:fs"); +const path = require("node:path"); + +const root = path.resolve(__dirname, ".."); +const packageFile = path.join(root, "package.json"); +const projectFile = path.join( + root, + "platforms/ios/runner.xcodeproj/project.pbxproj", +); +const infoPlistFile = path.join(root, "platforms/ios/runner/Info.plist"); +const stringsFile = path.join( + root, + "platforms/android/app/src/main/res/values/strings.xml", +); +const settingsGradleFile = path.join( + root, + "platforms/android/settings.gradle.kts", +); +const indexHtmlFile = path.join(root, "src/index.html"); + +module.exports = { sync, patchProjectFile, patchDisplayName }; + +function sync() { + const pkg = JSON.parse(fs.readFileSync(packageFile, "utf8")); + patchProjectFile(pkg); + patchDisplayName(pkg); +} + +function patchProjectFile(pkg) { + patchFile(projectFile, (content) => + content + .replace( + /MARKETING_VERSION = [^;]+;/g, + `MARKETING_VERSION = ${pkg.version};`, + ) + .replace( + /CURRENT_PROJECT_VERSION = [^;]+;/g, + `CURRENT_PROJECT_VERSION = ${pkg.versionCode};`, + ) + .replace( + /PRODUCT_BUNDLE_IDENTIFIER = ("?)([^";]+)\1;/g, + (match, quote, bundleId) => { + if (bundleId.endsWith(".ui-tests")) + return `PRODUCT_BUNDLE_IDENTIFIER = "${pkg.appleAppId}.ui-tests";`; + if (bundleId.endsWith(".tests")) + return `PRODUCT_BUNDLE_IDENTIFIER = ${pkg.appleAppId}.tests;`; + return `PRODUCT_BUNDLE_IDENTIFIER = ${pkg.appleAppId};`; + }, + ) + .replace( + /INFOPLIST_KEY_CFBundleDisplayName = [^;]+;/g, + `INFOPLIST_KEY_CFBundleDisplayName = ${pkg.displayName};`, + ), + ); +} + +function patchDisplayName(pkg) { + patchFile(infoPlistFile, (content) => + content.replace( + /(CFBundle(?:Display)?Name<\/key>\s*\n\s*)[^<]*(<\/string>)/g, + `$1${pkg.displayName}$2`, + ), + ); + patchFile(stringsFile, (content) => + content.replace( + /()[^<]*(<\/string>)/, + `$1${pkg.displayName}$2`, + ), + ); + patchFile(settingsGradleFile, (content) => + content.replace( + /(rootProject\.name\s*=\s*")[^"]*(")/, + `$1${pkg.displayName}$2`, + ), + ); + patchFile(indexHtmlFile, (content) => + content.replace(/()[^<]*(<\/title>)/, `$1${pkg.displayName}$2`), + ); +} + +function patchFile(file, transform) { + const content = fs.readFileSync(file, "utf8"); + const updated = transform(content); + if (updated !== content) fs.writeFileSync(file, updated, "utf8"); +} diff --git a/docs/ios-port.md b/docs/ios-port.md new file mode 100644 index 0000000000..5f4982939f --- /dev/null +++ b/docs/ios-port.md @@ -0,0 +1,626 @@ +# iOS port tracking + +## Current iOS app identity + +iOS now has one free app: bundle ID from `package.json.appleAppId`, Xcode +target/scheme `runner`, and test target `runnerTests`. Both native code and the +web bundle include the free advertising implementation regardless of Android's +`androidPackageId` selection. +Build commands and configuration are in [CONTRIBUTING.md](../CONTRIBUTING.md). +The validation history below includes runs made before this consolidation; +references to separate paid/free builds describe those earlier runs. + + +The iOS port aims to preserve Acode's editor and public native/plugin APIs. +Android remains supported. This checklist records unfinished work; a successful build alone does +not establish feature parity. + +`CustomTabs.open` options `authTabId` and `reportLifecycle`, and the native +`CustomTabs` action `close`, are iOS-only. Android ignores those options and +rejects `close`. Call `Bridge.exec(success, error, "CustomTabs", "close", [authTabId])` +to dismiss a matching tab; a stale ID leaves the active tab open. With +`reportLifecycle: true`, the callback receives `opened` and `closed` events; +the `lib/customTab` promise resolves on the first event only. + +The template runtime stays in `platforms/ios/runner`, with native services under +`runner/lib`. `Config.xcconfig` is ignored and reserved for local signing settings; +public icon settings live in `runner.xcodeproj/project.pbxproj`, while version, +build number, display name and bundle ID are synced into it from `package.json` +by `dev/sync.js`. +The shared `runner/PrivacyInfo.xcprivacy` declares file metadata access in the +sandbox and user-selected folders (`C617.1`, `3B52.1`), app-local preferences +(`CA92.1`), elapsed-time measurements for search deadlines (`35F9.1`) and requested +filesystem capacity checks (`E174.1`), following +[Apple's required-reason API categories](https://developer.apple.com/documentation/bundleresources/app-privacy-configuration/nsprivacyaccessedapitypes/nsprivacyaccessedapitype). +Both app targets package it at the bundle root. Bundled SDKs retain their own +privacy manifests; production privacy disclosures still need review alongside +the configured account and advertising services. + +- [ ] Build, run and development scripts; Xcode resources and app metadata +- [ ] Startup, lifecycle, keyboard, safe areas, orientation and native UI +- [ ] Sandbox file operations, encodings, file watching and workspace search +- [ ] Files picker, persistent folder access, incoming files and sharing +- [ ] Native HTTP, streaming, downloads, cookies, TLS and WebSockets +- [ ] Local preview server, browser, custom tabs and embedded WebViews +- [ ] FTP/FTPS, SFTP, saved credentials, host-key verification and remote shells +- [ ] Authentication and plugin contexts with Keychain-backed secrets +- [ ] StoreKit purchases/restoration and supported advertising APIs +- [ ] iOS capability checks in menus, settings, commands and runtime providers +- [ ] Regression tests, simulator smoke tests, CI and contributor documentation + +Android intents/package launching, APK updates, all-files access permissions +and Android battery controls remain platform exclusions. The main menu offers +Exit on iOS through `exit(0)`; Apple discourages programmatic termination, so +App Review may flag it. +Local terminals and native language-server processes use the ARM64 Alpine +runtime described in [platforms/ios/Alpine/README.md](../platforms/ios/Alpine/README.md). +It preserves Acode's terminal UI, AXS protocol and shell initialization script; +Linux package compatibility is bounded by the emulator, Node JIT restrictions, +and iOS process lifetime. Browser-based and remote language servers remain available. + +The native registration audit matches 22 of Android's 23 services to iOS services. +`Executor` and `BackgroundExecutor` now execute inside Alpine. `CrashHandler` +only installs Android's uncaught-exception handler and starts its crash activity, +with no public bridge actions. Launcher-shortcut, package-launch and +storage-manager controls remain gated in commands, menus and settings. Of the +54 Android `System` dispatch actions, the eight absent from the iOS service and +JavaScript proxy are the four launcher-shortcut actions, `launch-app`, +`getNativeLibraryPath`, `setExec` and `requestStorageManager`. These are deliberate +platform exclusions. `set-input-type` is handled by the iOS JavaScript proxy. +This checks registration and dispatch coverage; behavior validation is recorded +below and still has the device and production gaps listed at the end. + +The navigation stack also respects the app-exit capability: an empty stack on iOS +does not offer an exit confirmation or invoke exit callbacks. Stacked pages and +dialogs still dismiss normally, and Android retains its existing confirmation and +close-callback behavior. Three regression cases reproduced the missing guard; +60 shared navigation, app-icon and quick-tools tests pass after the fix. Four +focused native checks pass per edition, covering real dialog dismissal, iOS +settings, file-context-menu events with tap feedback, and quick-tools saving. + +External documents use Apple's document picker and security-scoped bookmarks; +there is no unrestricted filesystem permission on iOS. Services unavailable on a +platform must reject calls promptly instead of leaving promises pending. +`App.overrideButton` and `App.clearHistory` reject on iOS through both +`Bridge.exec` and the legacy `CoreAndroid` compatibility entry point. App bridge +regressions cover those error callbacks alongside shared editor startup. + +## Verified locally + +The default iOS start/dev flow follows Proteus by preparing the web bundle and +opening Xcode for device selection, signing and installation. An explicit +simulator `--target` retains scripted build/install/launch. This fixes the default +flow attempting `simctl install booted` and failing with exit 148 when no simulator +was running. Device live reload uses the Mac's LAN address; explicit simulator +development continues to use loopback. + +The last full contributor runs passed 100 paid native tests plus one paid UI +test, and 105 free native tests on iOS 18.6, including local SSH, FTP/FTPS and +StoreKit fixtures. Neither run skipped tests. Both targets also rebuild with the +app privacy manifest verified in their packaged resources. The latest full shared +JavaScript run passed 793 tests across 99 files; its one conditional Java +native-search test passed separately with Android Studio's JDK on `PATH` (794 +tests in total). The earlier 784-test baseline also passed TypeScript and +translation checks. Later focused native checks are recorded below. +StoreKit coverage uses local simulated transactions; it does not verify production +products or the purchase backend. Advertising checks verify the free bridge, +consent gating, load cancellation, banner layout and paid-impression payloads; +the paid app excludes the SDK classes, resources and metadata. + +The simulator suite currently exercises editor startup, safe-area layout, reading, +editing and saving files, watching coordinated writes, worker loading, incoming +files with Unicode and reserved characters, sandbox traversal protection, +encodings, HTTP and WebSocket payloads, streaming backpressure, API cookies and +uploads, sign-in challenge/state validation, callback isolation, and Keychain +namespace isolation. These are simulator checks, not physical-device coverage. + +Native file URLs escape literal `?` characters in paths, preserving real query +parameters and Android content-provider URLs. Focused checks pass 27 shared tests +and seven iOS tests per edition, including binary WebView fetches from nested +reserved-character paths and worker scripts with `#`, `?`, percent and Unicode +names. Encoded native URLs use `resolveLocalFileSystemURI`; the app's +`resolveLocalFileSystemURL` wrapper expects raw paths and applies `Url.safe`. + +File entries preserve symlink names and paths. A native regression reproduced +deletion and renaming affecting the target instead of the link. Removal and moves +now act on the link, while reads still validate the target against authorized +roots. Tests cover direct bridge calls, public entry resolution, child lookup, +directory listing, metadata, WebView reads, destination collisions, dangling +relative links and denied access to ungranted targets. The 24 affected native +checks pass per edition, including file-picker, sharing, archive and plugin +installation flows. The full runs above include these filesystem regressions. + +The native `FileEntry.copyTo` and `moveTo` APIs replace existing files and empty +directories, matching Android's native contract. Nonempty directories, mismatched +types, copying an item onto itself and copying a directory into itself reject +without changing contents. `FileTransfer` coordinates both paths and stages +replacement copies before replacing the destination; the existing System copy +utilities reuse it. Regression checks compare 2 MB binary transfers, verify an +unreadable source leaves the existing destination intact, and receive file-watch +notifications after moves. The shared `fsOperation` wrapper retains its separate +policy of rejecting existing destinations before calling these native APIs. +All 20 focused transfer, symlink, file-service, System utility and editor checks +pass in both editions. + +Native reads treat a negative end offset as EOF and bound ranges to the file's +size. Writes beyond EOF append without introducing zero-filled gaps, and negative +truncation rejects with Android's error code instead of emptying the file. +`FileContentsTests` reproduces those mismatches and checks recovery after a failed +truncate. It also verifies all byte values through array-buffer, binary-string +and data-URL reads, including sliced files spanning the default native chunks. +All 14 focused content, file-service, URL and editor checks pass in both editions. + +Directory entries interpret absolute child paths from their filesystem root and +normalize relative parent traversal within that root. A root's parent is itself. +Creation, copy and move reject colon-containing names with Android's encoding +error. Filesystem requests check positive size requirements against available +space and report quota errors without allocating storage. `FileEntryTests` +exercises these contracts through the public API, including exclusive creation, +type mismatches and preserving existing contents after rejected operations. + +Android regression checks passed native unit tests, production web bundling and +debug APK builds for paid, free and paid F-Droid. An isolated API 37 emulator ran +all three APKs and verified startup, editor save/read, internal file URLs, and +retained terminal, running-process, exit, edit-with, shortcut and sharing actions. +This exposed a decoded-path bug in Android's file resource handler: `#` and other +reserved filename characters were reparsed as URI syntax, causing a 404. Local +paths now use `Uri.fromFile`; a native regression test checks exact binary bytes +for plain names, reserved characters and a literal `%23` name. Content-provider +URI handling is unchanged. These checks do not replace Android physical-device +or minimum-API validation. + +Native text comparisons use exact UTF-16 code units, matching Android and +JavaScript. Unicode-normalization changes must count as edits even when the text +looks identical. A bridge regression reproduced missed changes with Swift's +canonical-equivalence comparison, then passed after the fix for composed and +decomposed accents, Hangul, reordered combining marks and UTF-8/UTF-16 files. +The comparison, existing System utilities and editor-save checks pass in both +editions; the free run also covers the archive round trip described below. + +Files pickers preserve the existing API result types: image and folder selection +return a URI, while document selection returns metadata. Cancellation, concurrent +requests and WebView reloads resolve or release the pending request, and stale +picker callbacks cannot complete a newer request. Security-scoped access is owned +by the shared file service; repeated selection refreshes the same bookmark, and +sandbox selections do not create redundant bookmarks. Native integration tests +cover these contracts using the picker's delegate; a separate simulator UI check +selected a folder, created an HTML file and opened it in the editor. Third-party +providers and iCloud still need verification. + +Saved file references survive app-container relocation. iOS records previously +authorized root paths, resolves older native file URLs against the current grant, +and updates Acode's sessions, Recents, saved storages and expanded-tree paths before +device readiness. Missing grants are not restored by path history. Native tests +cover several relocations, nested roots, boundary checks and unavailable grants; +shared tests cover startup ordering, encoded paths and storage-write failures. +A two-install simulator check reproduced the original permission error and then +verified both the retained native URL and the updated Recents entry with the fix. +External-provider moves/revocation and signed-device upgrades remain unverified. +The relocation lookup uses a separate internal bridge action; the original +`File.requestAllPaths` response and public filesystem API shapes are retained. + +Sharing exports an isolated temporary copy with the requested filename. The +native test checks binary content, concurrent presentation rejection and cleanup +after cancellation or WebView reload. Reload dismisses the old sheet as well. +An iOS 18.6 interaction check exported a document through Save to Files, previewed +it in Files, then opened and edited that copy in both Acode editions. The original +28-byte document stayed unchanged; the external copy contained the exact 63 bytes +expected after both edits. This reproduced a save failure caused by requesting the +ungranted parent folder of an individually granted document. Existing-file writes +now resolve the file directly; new-file creation still requires its parent folder. +The 49 focused shared tests cover grant boundaries, writer errors and creation +flags; 19 affected native checks pass per edition, with the final six startup/editor +checks also verifying directory type errors. Incoming share tabs retain Android's +temporary-session behavior. Other share destinations, third-party providers, +iCloud and physical-device grants remain unverified. The file browser omits +unavailable Android storage roots on iOS. Terminal Public is shared with Alpine. Acode's Documents +folder opens directly; a simulator test browses it and reads a selected file +through the shared filesystem API. + +A separate normal-app check created an On My iPhone folder through Files, granted +that folder to Acode, then created, edited and renamed a project file. The renamed +tab and project restored after force quit; another edit saved through the restored +folder grant. The final external file matched all 43 expected bytes. This covers +the local Files provider on the iOS 18.6 simulator, not iCloud or other providers. + +SSH/SFTP uses libssh2 through a pinned Swift package, with credentials and host +keys stored in Keychain. The existing JavaScript file browser and remote-terminal +APIs are retained. Tests cover password authentication, encrypted RSA PEM and +Ed25519 OpenSSH private keys, redacted profile metadata, preserving saved secrets +during edits, unknown-host prompt cancellation, persisted host trust, changed-key +rejection, cancellation of a stalled handshake, and timeout invalidation. SFTP tests cover Unicode and +reserved filenames, directory creation/listing/stat/rename/removal, relative and +broken symlinks, permission errors, and streamed binary uploads/downloads. Shell +tests verify PTY resize, Unicode input/output, combined command output, and exit +status and quiet commands that outlive the connection deadline. Connection +timeouts retain Android's 10-second default and 1–30-second range; running commands +have no fixed deadline and can be stopped by closing the connection. These checks +use a disposable loopback server; real remote servers and reconnects after iOS +background suspension need further coverage. + +A throttled 8 MiB SFTP fixture also checks closing a connection after data has +started arriving. The original bridge request must report cancellation within +five seconds, `isConnected` must clear, and reconnecting must download the next +file without returning stale partial content. Both editions pass this check. + +A separate server-disconnect check interrupts both an 8 MiB SFTP download and +upload after transferring a real file prefix. Each public bridge request must +reject within five seconds and `isConnected` must clear. Reconnecting downloads +the next file over the partial local file and retries an upload over the partial +remote file, verifying the recovered contents exactly. Nine focused SSH/SFTP +checks pass in each edition without app-code changes. The loopback fixture +confines these failures to dedicated filenames and disposable connections; it +does not simulate iOS process suspension or a physical-device network change. + +Both editions also passed a manual Home-screen round trip on the iPad iOS 18.6 +simulator with an SSH shell open and an 8 MiB SFTP download in progress. The app +entered the background before the full file arrived, emitted pause/resume events, +and returned with the SFTP connection intact. Shell input/output worked before +and after the transition, and every downloaded byte matched the fixture. The +free edition returned to its existing Split View session with Files. A temporary +native harness verified these outcomes while the simulator UI drove app switching; +it is not part of the unattended suite. This checks app switching, not physical +device suspension, process termination or network changes. + +FTP/FTPS uses vendored curl 8.22.0 source with the existing OpenSSL dependency. +The public `Ftp` bridge and JavaScript file-browser API are retained. Tests cover +active and passive connections, Unicode/reserved filenames, hidden files, empty +directories, file metadata and symlinks, working-directory changes and connection +reuse, raw command replies, recursive deletion, binary uploads/downloads, +reconnects, cancelled handshakes, invalid credentials, and command-injection +rejection. FTPS tests require encryption on both control and data channels and +verify trusted certificates, untrusted certificates and hostname mismatches. +Normal connections use Apple's certificate trust store; tests supply a +disposable CA only to the internal native client. Port 990 selects implicit TLS. +The fixture exercises both TLS modes with active and passive binary transfers, +untrusted certificates and hostname mismatches. Its implicit listener uses an +allocated loopback port; an internal client override routes the port-990 profile +there without changing its TLS mode or certificate hostname. All seven focused +FTP bridge, transport and transfer-lifecycle tests pass in both editions. +An 8 MiB throttled download is interrupted through the public `disconnect` action; +the original request rejects within five seconds and reconnecting replaces the +partial local file with the next download. Separate fixture failures drop a +download's data connection and an upload's control/data connections before +completion. FTP, explicit FTPS and implicit FTPS all reject those transfers and +recover for subsequent uploads/downloads in active and passive modes. Actual +remote servers, background suspension and physical-device LAN access remain to +be checked. + +Dependency revisions are recorded in Xcode's `Package.resolved`; third-party +license notices ship in `runner/SSH-Licenses.txt` and `runner/FTP-Licenses.txt`. +Curl source provenance and build configuration are documented in +`Packages/CCurl/README.md`. The contributor guide describes the optional local +remote-server fixtures, which CI starts for the iOS test suite. + +The preview tests exercise an unsaved editor file through the existing JavaScript +request handler, console events, responsive viewport sizing, parallel binary +responses, UTF-8 text, HEAD, ETags, byte ranges and server restart. Preview pages +use a separate WebKit store and cannot call the app's native bridge. Plugin +WebViews retain hidden/fullscreen modes, document-start messaging, restricted +navigation, HTML reloads and state across hide/show; closing destroys the instance. +The HTTP parser is shared with Proteus's embedded proxy. Request bodies currently +have a 64 MiB limit, with 64 concurrent connections and a 60-second idle timeout. + +Preview restarts preserve the new request handler while the old iOS listener is +still shutting down. The shared Run action sends stop, start and handler +registration without waiting for each callback; rejecting registration during +shutdown left the next preview unable to load. An automated regression reproduces +that sequence across four server generations and verifies each response comes +from the replacement handler. Five focused server, parser and editor-preview +checks pass in each edition. + +Both editions also passed a manual preview-to-Safari round trip on the iPad iOS +18.6 simulator, including the free app's Split View session. Safari visibly loaded +the unsaved HTML page through Acode's actual preview server. Returning to Acode +preserved the unsaved editor text, closed the original preview and successfully +opened a fresh preview. This interaction exposed the restart bug above and +passed after its fix. The temporary native harness and Safari fixture tabs were +removed afterward. Long-running external previews and physical-device suspension +remain unverified. + +Additional preview regressions cover closing an unanswered download prompt, +restoring the editor after dismissing the preview and its alert together, and +cancelling navigation queued behind asynchronous cache removal. Closed hidden +WebViews cannot reuse the app's presenter for late dialogs. A resource-cache test +verifies cache reuse before refresh and fresh content after disabling the cache. +The six focused preview and plugin-WebView tests pass in both paid and free builds. +Accepted downloads use an app-owned `PreviewDownloadManager` with Apple's +[`WKDownload`](https://developer.apple.com/documentation/webkit/wkdownload), so they +retain their original request and continue after the preview closes, matching +Android's download ownership. Closing still cancels an unanswered confirmation. +An integration test holds a 16 MiB response open, closes and releases the preview, +then verifies the completed file byte for byte and its completion alert in the +editor. A truncated response reports failure and removes its partial file. These +checks run alongside the existing prompt, cache and upload tests in both editions. +A simulator UI check cancelled a download, saved the same binary attachment twice +without overwriting it, then selected the first download through the native Files +picker. Both saved files and the page's `File.arrayBuffer()` matched the original +bytes. The temporary interactive test and its files were removed afterward. +A further paid simulator UI check selected two files and sent a multipart POST to +a loopback server; its response matched the full serialized request byte for byte. +`PreviewUploadTests` now automates the complete round trip in both editions through +the native document picker's public delegate. It verifies multiple selection, +binary and UTF-8 file contents, exact on-disk filenames and the complete multipart +request body. Filename assertions use the on-disk spelling because iOS can normalize +Unicode during file creation. The test removes its disposable files afterward. +Both editions passed a further manual Home-screen round trip on the iPad iOS 18.6 +simulator during a 16 MiB WebKit download. A temporary native harness held the +HTTP response open until the app entered the background, then completed it before +the app returned. After resuming, it verified the completion alert, every saved +byte, retained preview page state and a fresh HTTP request. The simulator UI drove +the Home/app-switcher transitions; the harness used the existing in-app HTTP +fixture under XCTest. The temporary harness was removed from the test target +afterward. This does not establish physical-device suspension or background +execution behavior. +Provider-backed files, app suspension/termination and physical-device background +downloads remain unverified. + +On iOS, file workspaces now use the public native `fileIndex` API and the existing +Search in Files UI. The SQLite-backed index preserves streamed scan events, +paginated queries, incremental subtree updates, cached text, dirty invalidation, +unsaved editor overlays, search options and replacement events (regex +replacements expand `$1`, `$&` and `$<name>` like JavaScript's `String.replace`). Remote +providers retain their JavaScript discovery/search fallback; Android SAF URLs +remain Android-only. Replacement produces editor text and does not write files. + +Tests cover a 1,200-file workspace, persistence across index instances, cancelled +scan rollback, exclusions/hidden files, symlink cycles, Unicode and reserved +filenames, SQL wildcard escaping, UTF-16/BOM detection and match positions, +searching open `.env` files, binary detection, large files without truncation, +and cancellation through the public bridge. Search retains the 200-match batch, +5,000-match-per-file cap, two-second regex deadline, 512-Ki-character text cache, +and 16 MiB direct/128 MiB explicitly included file read limits. Larger real +projects, external Files providers, iCloud materialization and physical-device +performance still need validation. + +Testing on iOS 18.6 exposed an unbounded ancestor walk in workspace scans. +Traversal now stops at the filesystem root or a non-shortening parent path and +checks cancellation while walking ancestors. The existing scan, symlink-cycle, +rollback and search tests pass on the minimum supported runtime. + +ZIP browsing, extraction, creation and plugin installation use the existing +JSZip implementation. A simulator integration test in both editions selects files and a folder +in Acode's file browser, compresses them and imports the ZIP through the native +picker delegate. It verifies a 32 MiB binary payload, Unicode/reserved filenames, +empty files/directories and a second extraction that preserves the first. It also +uses the normal Cancel button after a real native write and verifies that only the +partial import is removed. The fixture delays that write's completion callback +until Cancel appears; compression, native I/O and cleanup use the actual app path. +The expanded workflow passes in both editions on the iOS 18.6 iPhone simulator. +Plugin installation tests install a local archive through the Plugins source +prompt, verify nested binary assets and an empty directory, load its script and +legacy Cordova API calls, check its isolated plugin context and Installed-list +entry, then unmount and remove it. A separate paid simulator UI check installed +the same disposable fixture through Plugins → Local → Select document and the +native Files picker, with the same content and API assertions. Its temporary test +and installed fixture were removed afterward. External-provider archives, +process interruption and physical-device memory limits remain unverified. + +The remaining supported `System` file utilities preserve Android's public return +types, newline-appending text writes, nonrecursive deletion and relative symlinks. +Binary copy and asset extraction use coordinated writes and preserve an existing +destination when reading the source fails. Checks cover dangling links, sandbox +escapes, Unicode paths and the JavaScript wrappers. Legacy SHA-256 text checksums +and cache clearing are supported; clearing the WebView cache keeps app storage. + +All sixteen existing app icons are packaged for iPhone and iPad, including Acode's +default artwork. UIKit changes the launcher icon in place. The shared picker +retains reward/Pro requirements and persistence, and omits Android's app-exit +warning on iOS. New ad-free passes are discontinued. Existing earned time remains +active until its stored expiry, with native Keychain state preserved. +Native tests verify packaged icon metadata and actual DOM hit targets after +startup. A paid-edition UI test changes and restores the icon through Settings, +acknowledging Apple's confirmation. An iOS-only centering rule keeps WebKit's +accessibility bounds aligned with the picker; Android retains its original CSS. + +Android edit-in-place intents and pinned launcher file shortcuts are absent from +iOS menus and commands. Direct unsupported intent calls reject explicitly; Share +and Open with still export copies through the system share sheet. Android's +uncaught-Java-exception crash activity has no iOS equivalent; native fatal crashes +use Apple's crash reports rather than attempting to open UI during a crash. + +About shows WebKit information without an Android store link, and copied device +reports identify iOS. Plugin minimum-version warnings retain the installation +restriction without linking to Google Play. The Google Play rating action is hidden +until an iOS App Store listing is configured. Pro purchase instructions describe +restoring with the same Apple Account. The two new translation keys have English +defaults across locales. `PlatformUITests` verifies Settings, About and diagnostics +in both editions, including delegated clicks and hidden-setting search results. + +Custom tabs use Safari and external links use the system URL handler. Safari owns +its title and toolbar appearance; iOS 26 deprecates the toolbar tint preference. +See [Apple's API documentation](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller/preferredbartintcolor). + +The paid build also passed a manual iPhone simulator check for startup, the live +plugin catalogue, keyboard touch input, editor resizing, and portrait/landscape +safe areas. `dev:ios` was verified to install the app, reload JavaScript edits, +and rebuild/relaunch for Swift edits. + +Focused iPad Pro 13-inch (M4), iPadOS 18.6 runs passed 18 native tests per edition: +startup, safe areas, editor/file operations, Files browsing, document-picker +contracts, share-sheet cleanup, Safari, preview/console/viewport controls, input +attributes, fullscreen policy, iOS navigation and quick-tools touch/click saving. +The file-menu fixture waits for loading and dismissal overlays to finish before +the next interaction. CI includes the expanded native set for the unified iOS app. +The earlier paid Settings touch test also changes and +restores the app icon while rotating between portrait and landscape. CI runs +these focused checks after the iPhone suite, reusing its existing build. +The paid edition passed the earlier 15 native checks and rotation/icon interaction +test on a separate iPadOS 26.5 simulator as well. + +Manual free-edition checks on iPadOS 18.6 cover tracking denial, software-keyboard +typing, simulated hardware-keyboard input, and editor rotation in Split View with +Files. Switching back to the software keyboard initially left the caret below the +visible editor until another keystroke. The shared handler now uses iOS's native +keyboard height, including when a hardware keyboard is reported, and recognizes +dismissal after rotation without relying on the largest previous window height. +The same Split View interaction now reveals the caret without typing. Five shared +regression cases cover these transitions, the compact keyboard toolbar, and +unchanged Android behavior; 40 focused shared tests pass. A native WebKit resize +fixture verifies the keyboard event and visible caret, alongside the three system +UI tests in both iPad editions. The keyboard fixture also passes on iPhone in both +editions. CI includes the new keyboard fixture for iPad. +Divider dragging did not respond to the automation, so arbitrary window resizing +and physical-keyboard behavior remain unverified. + +The iOS input adapter implements the existing keyboard-mode APIs with WebKit's +`autocorrect`, `spellcheck` and `writingsuggestions` attributes. Both no-suggestion +modes use the same iOS policy; normal mode restores each field's own attributes. +Dynamic fields are included without changing their input type, autofill, value or +selection. This replaces the template's success-only keyboard handler and private +WebKit subview removal. See [WebKit's writing-suggestions documentation](https://webkit.org/blog/15865/webkit-features-in-safari-18-0/). + +Filename prompts disable automatic capitalization, correction and suggestions on +iOS. An interactive check reproduced `ios-` becoming `iOS-`; after the fix, a new +lowercase filename and two-line editor content saved exactly, verified from the +simulator's Documents directory. The focused native prompt test passes in both +editions, including ordinary text defaults and explicit capitalization overrides; +all three shared input-adapter tests also pass. + +Tap feedback reuses Proteus's existing `Native.haptic` service on iOS. The shared +helper retains Android vibration durations and safely skips unavailable browser +feedback. Quick tools, tab dragging, file context menus and terminal selection +use it. A native regression reproduced quick-tools Save throwing on the absent +`navigator.vibrate` API, then verified exact file saves through both touch and +click handlers with feedback enabled. Eight focused editor, file-browser and +haptic checks pass per edition; the normal-app project check above also used the +quick-tools Save button. Physical haptic sensation remains unverified. + +The main WebView implements element fullscreen using a manual +popover and edge-to-edge native layout, preserving iframe state and touch +coordinates without WebKit's browser fullscreen presentation. Fullscreen styles +apply to the owner and its shadow hosts; inline layout overrides are restored on +exit. Iframe documents and preview WebViews retain WebKit fullscreen. The existing `orientation` plugin API applies +portrait/landscape requests only during foreground fullscreen, releases its policy +on exit, reload or unlock, and temporarily restores normal rotation while inactive. +A completed downward swipe (at least 40 points) starting anywhere across the top +(within 44 points below the top safe-area inset) +reveals the native Back button in main-app fullscreen. It hides after three seconds, +on backgrounding or on exit; tapping restarts its hide timer. A completed left-edge +swipe (at least 60 points) delivers Back directly. `fullscreen.setBackHandler(callback | null)` +receives these actions through `fullscreenbackbutton`; without a handler they exit +fullscreen. A visible modal within the fullscreen owner gets the first opportunity +to handle Escape, regardless of focus; native dialogs receive a cancellable close +request that consumes Back. Back closes Astray's open pause menu and +resumes the game even after interacting with the menu or revealing the native button. +Registration clears on exit or reload, survives orientation unlock, and delivery +is disabled while inactive. Games such as Astray can open their pause menu while +remaining in landscape, then restore the editor through Exit. Simulator tests cover +ownership, callback failure, Back controls, touch coordinates, rotation and restoration. +Motion sensor readings require a physical device; simulated inputs are test fixtures. +On iPadOS 18.6 and 26.5 with multitasking enabled, UIKit rejects programmatic +orientation changes. The API rejects its promise and clears the requested policy; +fullscreen entry/exit and normal device rotation remain available. Keep iPad +multitasking enabled rather than adding the deprecated +[`UIRequiresFullScreen`](https://developer.apple.com/documentation/bundleresources/information-property-list/uirequiresfullscreen) +compatibility mode. The integration test verifies the denial and cleanup on iPad +while retaining the successful rotation checks on iPhone. + +Native selection-menu suppression clears the contextual menu through UIKit's +public menu builder; keyboard shortcuts and text interaction remain enabled. +Tests verify the bridge flag, DOM selection and status-bar visibility. Actual +long-press/right-click menu presentation and third-party keyboard suggestions +still need manual checks; calling UIKit's edit interaction programmatically did +not reproduce normal menu presentation in the simulator. + +The account API uses an iOS-only fetch/XHR URL adapter because the app's custom +scheme has an opaque browser origin. The native handler restricts requests to +the Acode API origin, retains TLS verification, honors credential omission and +keeps HttpOnly cookies out of JavaScript. Blob/FormData bodies are normalized to +bytes before WebKit forwarding. Synchronous XHR uploads of Blob/FormData cannot +be normalized asynchronously and currently reject explicitly. + +Authentication uses the existing one-time app-code protocol in a system web +authentication session, with the verifier and token in Keychain. Automated tests +do not log in to a real account. A complete interactive login/logout and account +purchase flow still needs validation. + +The `Iap` bridge now uses StoreKit 2, preserving product lookup, launch callbacks, +persistent purchase updates, purchase states and numeric errors. Only verified, +active transactions are returned as owned. Purchases remain unfinished until the +existing acknowledgement/consume calls; unfinished purchases survive WebView +reloads. Tokens carry Apple's signed JWS, with `store: "appstore"`, transaction +IDs, environment and `signedTransactionInfo` also included. Acknowledgement looks +up the token's reference in verified local ownership because StoreKit can re-sign +the same transaction. Decoded token claims alone never establish ownership. + +The iOS Settings page adds Restore purchases using `AppStore.sync()`. Shared +purchase listeners now match the requested product, preventing another product's +update from unlocking Pro or completing a plugin purchase. Unavailable billing +on iOS does not enable the existing Android external-checkout fallback. + +StoreKit integration tests cover product metadata, purchase acknowledgement, +restoration, refunds, consumables, reload recovery, cancellation, deferred +approval, listener persistence, and rejection of invalid signatures. The fixture +catalogue lives only in the test bundle. The installed iOS 26.5 simulator failed +to configure StoreKitTest, matching Apple's reported +[command-line testing issue](https://developer.apple.com/forums/thread/826971); +CI selects iOS 18.6 or 26.2 and does not silently skip billing tests. + +Production billing is still incomplete. Existing SKU strings are passed through +unchanged, so matching App Store products and production bundle IDs must be +configured. The sibling backend's paid-plugin and sponsorship routes currently +validate Google Play tokens only. They cannot accept these Apple transactions +until Apple verification and store-aware order/refund handling are implemented. +Until then, iOS hides new paid-plugin and sponsorship purchases and Google Play +refund links. Free and account-owned plugins remain installable, including as +dependencies and during backup restore; installed plugins retain update/removal +actions. An unowned paid dependency stops installation and backup restore reports +unowned paid plugins as skipped. The sponsor list remains available. Shared tests +exercise these paths and retain Android's store-token behavior. Local Pro purchase +and restoration still use StoreKit. No backend or production account changes have +been made. + +The normal free app also displayed Google's live banner and rewarded test +creatives on the iPad iOS 18.6 simulator. The banner handled Split View, portrait +rotation and software-keyboard hiding/restoration. Completing and dismissing one +rewarded test ad granted exactly one Quick pass, showed one hour remaining and +1/3 redemptions, and suppressed the Settings banner. A temporary manual bridge +check also passed interstitial loading, presentation, impression and dismissal +callbacks on the iPad, preserving editor content, layout and the existing reward +pass. Ad requests now include the presenting window's scene; the regression +reproduced the missing scene for all six native formats, and all six AdMob bridge +tests pass with the correction. Live portrait and landscape Split View checks +displayed the full interstitial test image and passed dismissal, though other +landscape runs had an unexplained black creative. The iPhone rendered the full +test image, but its dismissal check timed out after desktop UI targeting failures. +These test-ad checks do not establish production delivery, consent variants or +physical-device behavior. + +## Remaining native work + +Both Debug device builds compile and pass deep signature verification with the +existing local development profiles. The profiles include the currently paired +iPhone 15, which has Developer Mode enabled. The free build uses Google's sample +advertising app ID; the paid build omits it. Both editions also compile with +`build-for-testing`; their signed native test bundles and device `.xctestrun` +manifests have been verified locally. The paid UI-test runner is signed as well. +Separate installation apps without test bundles are preserved under +`.ios-build/DeviceApps`. A subsequent read-only device check confirmed the paid +`app.acode` app is installed on the iPhone as version 1.13.5, build 1011. Xcode +reports a completed `runner` run on that phone, with the WebView finishing +`acode://localhost/`. This establishes device installation and native WebView +startup, not editor or native-service parity. The free `app.acode.free` app is +not installed. Automated physical-device tests have not been run; their installation +and execution approval remains pending. + +- Production StoreKit configuration, Apple verification for paid plugins and + sponsorships, account purchase flows, and production AdMob/consent/ATT validation. + Production bundle, product, App Store listing and advertising identifiers are + pending. +- Remaining remote-connection lifecycle/device checks, external + provider indexing and large-workspace performance on physical devices. +- Physical-device background preview transfers and external browser lifecycle, LAN access, + process-interrupted archives and external-provider archive operations. +- Native context-menu and third-party keyboard touch checks, other share + destinations and Files-provider persistence, revocation and app-upgrade paths. + Acode's notification UI remains in shared JavaScript; the template + scanner/notification services are not part of its Android native API surface. +- Additional iPad window resizing and floating-keyboard checks, physical keyboard, + accessibility, broader manual checks on the oldest supported iOS, signed physical-device + testing and Android physical-device/minimum-API regression validation. + +Build, start and simulator-test commands are documented in CONTRIBUTING.md. +The iOS CI jobs build and test both package editions without release credentials; +the workflow has not been run on GitHub yet. Build success does not establish +parity for the native services still listed above. diff --git a/hooks/README.md b/hooks/README.md deleted file mode 100644 index fb280b96c0..0000000000 --- a/hooks/README.md +++ /dev/null @@ -1,23 +0,0 @@ -<!-- -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---> -# Cordova Hooks - -Cordova Hooks represent special scripts which could be added by application and plugin developers or even by your own build system to customize cordova commands. See Hooks Guide for more details: http://cordova.apache.org/docs/en/edge/guide_appdev_hooks_index.md.html#Hooks%20Guide. diff --git a/hooks/android/ImmersiveFullscreen.java b/hooks/android/ImmersiveFullscreen.java deleted file mode 100644 index 28d9f8a9ab..0000000000 --- a/hooks/android/ImmersiveFullscreen.java +++ /dev/null @@ -1,221 +0,0 @@ -package org.apache.cordova; - -import android.app.Activity; -import android.content.pm.ActivityInfo; -import android.os.Build; -import android.view.View; -import android.view.ViewTreeObserver; -import android.view.Window; -import android.view.WindowManager; -import androidx.core.view.ViewCompat; -import androidx.core.view.WindowCompat; -import androidx.core.view.WindowInsetsCompat; -import androidx.core.view.WindowInsetsControllerCompat; - -/** Owns window state only while Cordova is displaying a browser fullscreen view. */ -final class ImmersiveFullscreen - implements - ViewTreeObserver.OnWindowFocusChangeListener, - View.OnAttachStateChangeListener -{ - - @SuppressWarnings("deprecation") - private static final int LEGACY_FULLSCREEN_FLAGS = - View.SYSTEM_UI_FLAG_FULLSCREEN | - View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | - View.SYSTEM_UI_FLAG_IMMERSIVE | - View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; - - private final Activity activity; - private final Window window; - private final View decor; - private final WindowInsetsControllerCompat controller; - private final Runnable onExit; - private View fullscreenView; - private ViewTreeObserver focusObserver; - private boolean statusBarVisible; - private boolean navigationBarVisible; - private int previousBehavior; - private int previousCutoutMode; - private int previousLegacyFlags; - private boolean resumed; - private Integer requestedOrientation; - private int previousOrientation; - private boolean orientationApplied; - - ImmersiveFullscreen(Activity activity, boolean resumed, Runnable onExit) { - this.activity = activity; - this.resumed = resumed; - this.onExit = onExit; - window = activity.getWindow(); - decor = window.getDecorView(); - controller = WindowCompat.getInsetsController(window, decor); - } - - @SuppressWarnings("deprecation") - void enter(View view) { - if (fullscreenView != null) return; - - WindowInsetsCompat insets = ViewCompat.getRootWindowInsets(decor); - int flags = decor.getSystemUiVisibility(); - statusBarVisible = - insets != null - ? insets.isVisible(WindowInsetsCompat.Type.statusBars()) - : (flags & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0 && - (window.getAttributes().flags & - WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0; - navigationBarVisible = - insets != null - ? insets.isVisible(WindowInsetsCompat.Type.navigationBars()) - : (flags & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0; - previousBehavior = controller.getSystemBarsBehavior(); - previousLegacyFlags = flags & LEGACY_FULLSCREEN_FLAGS; - if (Build.VERSION.SDK_INT >= 28) { - WindowManager.LayoutParams attributes = window.getAttributes(); - previousCutoutMode = attributes.layoutInDisplayCutoutMode; - attributes.layoutInDisplayCutoutMode = - Build.VERSION.SDK_INT >= 30 - ? WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS - : WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; - window.setAttributes(attributes); - } - - fullscreenView = view; - // The wrapper fills Cordova's root, with no status/navigation bar margins. - // Only the keyboard should shrink the usable area. Leave the root's inset - // listener alone so normal editor layout is unchanged on exit. - ViewCompat.setOnApplyWindowInsetsListener(view, (target, appliedInsets) -> { - int bottom = appliedInsets - .getInsets(WindowInsetsCompat.Type.ime()) - .bottom; - target.setPadding(0, 0, 0, bottom); - return appliedInsets; - }); - view.addOnAttachStateChangeListener(this); - focusObserver = decor.getViewTreeObserver(); - focusObserver.addOnWindowFocusChangeListener(this); - reapply(); - ViewCompat.requestApplyInsets(view); - } - - void reapply() { - if ( - !resumed || - fullscreenView == null || - !fullscreenView.isAttachedToWindow() || - !decor.hasWindowFocus() - ) return; - controller.setSystemBarsBehavior( - WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE - ); - controller.hide(WindowInsetsCompat.Type.systemBars()); - } - - void lockOrientation(String orientation) { - final int requested; - if ("landscape".equals(orientation)) { - requested = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE; - } else if ("portrait".equals(orientation)) { - requested = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT; - } else { - throw new IllegalArgumentException( - "Orientation must be landscape or portrait." - ); - } - if ( - !resumed || fullscreenView == null || !fullscreenView.isAttachedToWindow() - ) { - throw new IllegalStateException( - "Orientation requires foreground fullscreen." - ); - } - - int previous = activity.getRequestedOrientation(); - activity.setRequestedOrientation(requested); - // Only a successful first request owns the restoration state. Changing - // modes or resuming this session must not replace it with our own override. - if (requestedOrientation == null) previousOrientation = previous; - requestedOrientation = requested; - orientationApplied = true; - } - - void unlockOrientation() { - restoreOrientation(); - requestedOrientation = null; - } - - void pause() { - resumed = false; - restoreOrientation(); - } - - void resume() { - resumed = true; - if ( - fullscreenView != null && - fullscreenView.isAttachedToWindow() && - requestedOrientation != null - ) { - activity.setRequestedOrientation(requestedOrientation); - orientationApplied = true; - } - reapply(); - } - - private void restoreOrientation() { - if (!orientationApplied) return; - activity.setRequestedOrientation(previousOrientation); - orientationApplied = false; - } - - @SuppressWarnings("deprecation") - void exit() { - if (fullscreenView == null) return; - View view = fullscreenView; - fullscreenView = null; - onExit.run(); - unlockOrientation(); - view.removeOnAttachStateChangeListener(this); - ViewCompat.setOnApplyWindowInsetsListener(view, null); - view.setPadding(0, 0, 0, 0); - if ( - focusObserver.isAlive() - ) focusObserver.removeOnWindowFocusChangeListener(this); - focusObserver = null; - - controller.setSystemBarsBehavior(previousBehavior); - restoreBar(WindowInsetsCompat.Type.statusBars(), statusBarVisible); - restoreBar(WindowInsetsCompat.Type.navigationBars(), navigationBarVisible); - if (Build.VERSION.SDK_INT < 30) { - // Restore only the bits we own; keep any theme changes made meanwhile. - decor.setSystemUiVisibility( - (decor.getSystemUiVisibility() & ~LEGACY_FULLSCREEN_FLAGS) | - previousLegacyFlags - ); - } - if (Build.VERSION.SDK_INT >= 28) { - WindowManager.LayoutParams attributes = window.getAttributes(); - attributes.layoutInDisplayCutoutMode = previousCutoutMode; - window.setAttributes(attributes); - } - ViewCompat.requestApplyInsets(decor); - } - - private void restoreBar(int type, boolean visible) { - if (visible) controller.show(type); - else controller.hide(type); - } - - @Override - public void onWindowFocusChanged(boolean hasFocus) { - if (hasFocus) reapply(); - } - - @Override - public void onViewAttachedToWindow(View view) {} - - @Override - public void onViewDetachedFromWindow(View view) { - exit(); - } -} diff --git a/hooks/immersive-fullscreen.js b/hooks/immersive-fullscreen.js deleted file mode 100644 index 0d776d7d83..0000000000 --- a/hooks/immersive-fullscreen.js +++ /dev/null @@ -1,162 +0,0 @@ -const fs = require("node:fs"); -const path = require("node:path"); - -// Patch Cordova's existing custom-view lifecycle rather than replacing its -// WebChromeClient (which also owns dialogs, permissions and file selection). -module.exports = function prepareImmersiveFullscreen(context) { - if (!context.opts.platforms.includes("android")) return; - - const root = context.opts.projectRoot; - const destination = path.join( - root, - "platforms/android/CordovaLib/src/org/apache/cordova", - ); - const webViewPath = path.join(destination, "CordovaWebViewImpl.java"); - const controller = fs.readFileSync( - path.join(root, "hooks/android/ImmersiveFullscreen.java"), - "utf8", - ); - const original = fs.readFileSync(webViewPath, "utf8"); - const newline = original.includes("\r\n") ? "\r\n" : "\n"; - - // Markers delimit our generated blocks so each prepare can replace them safely, - // including when only the controller changes. - let source = original - .replace(/\r\n/g, "\n") - .replace( - /^[ \t]*\/\/ ACODE_FULLSCREEN_BEGIN ([a-z]+)\n[\s\S]*?^[ \t]*\/\/ ACODE_FULLSCREEN_END \1\n/gm, - "", - ); - if (/ACODE_FULLSCREEN_(BEGIN|END)/.test(source)) { - throw new Error( - "Acode fullscreen: incomplete generated patch; regenerate the Android platform.", - ); - } - - function insert(name, anchor, code, before = false) { - const matches = [...source.matchAll(new RegExp(anchor.source, "gm"))]; - if (matches.length !== 1) { - throw new Error( - `Acode fullscreen: expected one Cordova ${name} anchor, found ${matches.length}. Update hooks/immersive-fullscreen.js for this Cordova version.`, - ); - } - const indent = matches[0][1]; - const block = [ - `// ACODE_FULLSCREEN_BEGIN ${name}`, - ...code.trim().split("\n"), - `// ACODE_FULLSCREEN_END ${name}`, - ] - .map((line) => indent + line) - .join("\n"); - source = source.replace(anchor, (match) => - before ? `${block}\n${match}` : `${match}\n${block}`, - ); - } - - // System calls these setters on the UI thread; null releases the orientation override. - insert( - "field", - /^([ \t]*)private View mCustomView;[ \t]*$/m, - ` -private ImmersiveFullscreen immersiveFullscreen; -private boolean fullscreenPaused; -private boolean fullscreenBackHandlerEnabled; - -public void setFullscreenBackHandler(boolean enabled) { - if (enabled && (mCustomView == null || !mCustomView.isAttachedToWindow() || fullscreenPaused)) { - throw new IllegalStateException("Back handler requires foreground fullscreen."); - } - fullscreenBackHandlerEnabled = enabled; -} - -public void setFullscreenOrientation(String orientation) { - if (orientation == null) { - if (immersiveFullscreen != null) immersiveFullscreen.unlockOrientation(); - return; - } - if (immersiveFullscreen == null) { - throw new IllegalStateException("Orientation requires foreground fullscreen."); - } - immersiveFullscreen.lockOrientation(orientation); -} -`, - ); - // CoreAndroid's message channel accepts only Cordova's built-in events. - insert( - "back", - /(?<=if \(isBackButton && mCustomView != null\) \{\n)^([ \t]*)hideCustomView\(\);\n[ \t]*return true;[ \t]*$/m, - ` -if (fullscreenBackHandlerEnabled) { - engine.evaluateJavascript("cordova.fireDocumentEvent('fullscreenbackbutton');", null); - return true; -} -`, - true, - ); - insert( - "enter", - /^([ \t]*)parent\.bringToFront\(\);[ \t]*$/m, - ` -fullscreenBackHandlerEnabled = false; -immersiveFullscreen = new ImmersiveFullscreen(cordova.getActivity(), !fullscreenPaused, () -> fullscreenBackHandlerEnabled = false); -immersiveFullscreen.enter(wrapperView); -`, - ); - insert( - "exit", - /^([ \t]*)mCustomView\.setVisibility\(View\.GONE\);[ \t]*$/m, - ` -fullscreenBackHandlerEnabled = false; -if (immersiveFullscreen != null) { - immersiveFullscreen.exit(); - immersiveFullscreen = null; -} -`, - true, - ); - insert( - "pause", - /^([ \t]*)pluginManager\.onPause\(keepRunning\);[ \t]*$/m, - ` -fullscreenPaused = true; -if (immersiveFullscreen != null) immersiveFullscreen.pause(); -`, - true, - ); - insert( - "resume", - /^([ \t]*)this\.pluginManager\.onResume\(keepRunning\);[ \t]*$/m, - ` -fullscreenPaused = false; -if (immersiveFullscreen != null) immersiveFullscreen.resume(); -`, - true, - ); - insert( - "reset", - /^([ \t]*)pluginManager\.onReset\(\);[ \t]*$/m, - ` -fullscreenBackHandlerEnabled = false; -if (immersiveFullscreen != null) immersiveFullscreen.unlockOrientation(); -`, - true, - ); - // Release fullscreen while the WebView and its callback are still alive. - insert( - "destroy", - /^([ \t]*)engine\.destroy\(\);[ \t]*$/m, - ` -fullscreenBackHandlerEnabled = false; -hideCustomView(); -`, - true, - ); - - // Validate all anchors before writing either generated file. - fs.writeFileSync( - path.join(destination, "ImmersiveFullscreen.java"), - controller, - ); - const patched = source.replace(/\n/g, newline); - if (patched !== original) fs.writeFileSync(webViewPath, patched); -}; diff --git a/hooks/modify-java-files.js b/hooks/modify-java-files.js deleted file mode 100644 index 9e90e3c197..0000000000 --- a/hooks/modify-java-files.js +++ /dev/null @@ -1,497 +0,0 @@ -const path = require('path'); -const fs = require('fs'); -const prettier = require('prettier'); - -main(); - -async function main() { - const patchVersion = '2'; - const flagFile = path.resolve(__dirname, '../platforms/android/.flag_done'); - if (fs.existsSync(flagFile)) { - const appliedVersion = fs.readFileSync(flagFile, 'utf8').trim(); - if (appliedVersion === patchVersion) { - return; - } - } - - const base = path.resolve(__dirname, `../platforms/android/CordovaLib/src/org/apache/cordova`); - const files = { - 'SystemWebView.java': `${base}/engine/SystemWebView.java`, - 'SystemWebViewEngine.java': `${base}/engine/SystemWebViewEngine.java`, - 'CordovaWebViewEngine.java': `${base}/CordovaWebViewEngine.java`, - 'CordovaWebView.java': `${base}/CordovaWebView.java`, - 'CordovaWebViewImpl.java': `${base}/CordovaWebViewImpl.java`, - }; - - const interfaceMethod = { - name: 'setInputType', - modifier: 'public', - returnType: 'void', - params: [ - { - type: 'int', - name: 'type', - } - ], - }; - - const nativeContextMenuInterfaceMethod = { - name: 'setNativeContextMenuDisabled', - modifier: 'public', - returnType: 'void', - params: [ - { - type: 'boolean', - name: 'disabled', - } - ], - }; - - const setInputTypeMethod = { - name: 'setInputType', - modifier: 'public', - returnType: 'void', - params: [ - { - type: 'int', - name: 'type', - } - ], - body: ['webView.setInputType(type);'], - }; - - const setNativeContextMenuDisabledMethod = { - name: 'setNativeContextMenuDisabled', - modifier: 'public', - returnType: 'void', - params: [ - { - type: 'boolean', - name: 'disabled', - } - ], - body: ['webView.setNativeContextMenuDisabled(disabled);'], - }; - - const contentToAdd = { - 'SystemWebView.java': { - 'import': [ - 'android.graphics.Rect', - 'android.os.Build', - 'android.text.InputType', - 'android.view.ActionMode', - 'android.view.inputmethod.InputConnection', - 'android.view.inputmethod.EditorInfo', - 'android.view.Menu', - 'android.view.MenuItem', - 'android.view.View', - ], - 'fields': [ - { - type: 'int', - name: 'type', - modifier: 'private', - value: '-1', - }, - { - type: 'int', - name: 'NO_SUGGESTIONS', - modifier: 'private', - value: '0', - }, - { - type: 'int', - name: 'NO_SUGGESTIONS_AGGRESSIVE', - modifier: 'private', - value: '1', - }, - { - type: 'boolean', - name: 'nativeContextMenuDisabled', - modifier: 'private', - value: 'false', - }, - ], - methods: [ - { - ...setInputTypeMethod, - body: [`this.type = type;`] - }, - { - name: 'setNativeContextMenuDisabled', - modifier: 'public', - returnType: 'void', - params: [ - { - type: 'boolean', - name: 'disabled', - } - ], - body: [`this.nativeContextMenuDisabled = disabled;`], - }, - { - name: 'onCreateInputConnection', - modifier: 'public', - returnType: 'InputConnection', - params: [ - { - type: 'EditorInfo', - name: 'outAttrs', - } - ], - body: [ - `InputConnection ic = super.onCreateInputConnection(outAttrs); - if (type == NO_SUGGESTIONS) { - outAttrs.inputType |= InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS; - } else if (type == NO_SUGGESTIONS_AGGRESSIVE) { - outAttrs.inputType = - InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | - InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD; - } else { - outAttrs.inputType |= InputType.TYPE_NULL; - } - - return ic;`, - ], - notation: '@Override', - }, - { - name: 'startActionMode', - modifier: 'public', - returnType: 'ActionMode', - params: [ - { - type: 'ActionMode.Callback', - name: 'callback', - } - ], - body: [ - `return suppressActionMode(super.startActionMode(wrapActionModeCallback(callback)));`, - ], - notation: '@Override', - }, - { - name: 'startActionMode', - modifier: 'public', - returnType: 'ActionMode', - params: [ - { - type: 'ActionMode.Callback', - name: 'callback', - }, - { - type: 'int', - name: 'type', - } - ], - body: [ - `return suppressActionMode(super.startActionMode(wrapActionModeCallback(callback), type));`, - ], - notation: '@Override', - }, - { - name: 'startActionModeForChild', - modifier: 'public', - returnType: 'ActionMode', - params: [ - { - type: 'View', - name: 'originalView', - }, - { - type: 'ActionMode.Callback', - name: 'callback', - } - ], - body: [ - `return suppressActionMode(super.startActionModeForChild(originalView, wrapActionModeCallback(callback)));`, - ], - notation: '@Override', - }, - { - name: 'startActionModeForChild', - modifier: 'public', - returnType: 'ActionMode', - params: [ - { - type: 'View', - name: 'originalView', - }, - { - type: 'ActionMode.Callback', - name: 'callback', - }, - { - type: 'int', - name: 'type', - } - ], - body: [ - `return suppressActionMode(super.startActionModeForChild(originalView, wrapActionModeCallback(callback), type));`, - ], - notation: '@Override', - }, - { - name: 'wrapActionModeCallback', - modifier: 'private', - returnType: 'ActionMode.Callback', - params: [ - { - type: 'ActionMode.Callback', - name: 'callback', - } - ], - body: [ - `if (!nativeContextMenuDisabled || callback == null) { - return callback; - } - return new ActionMode.Callback2() { - @Override - public boolean onCreateActionMode(ActionMode mode, Menu menu) { - boolean created = callback.onCreateActionMode(mode, menu); - if (created) { - suppressActionModeUi(mode, menu); - } - return created; - } - - @Override - public boolean onPrepareActionMode(ActionMode mode, Menu menu) { - boolean prepared = callback.onPrepareActionMode(mode, menu); - suppressActionModeUi(mode, menu); - return prepared; - } - - @Override - public boolean onActionItemClicked(ActionMode mode, MenuItem item) { - return callback.onActionItemClicked(mode, item); - } - - @Override - public void onDestroyActionMode(ActionMode mode) { - callback.onDestroyActionMode(mode); - } - - @Override - public void onGetContentRect(ActionMode mode, View view, Rect outRect) { - if (callback instanceof ActionMode.Callback2) { - ((ActionMode.Callback2) callback).onGetContentRect(mode, view, outRect); - return; - } - super.onGetContentRect(mode, view, outRect); - } - };`, - ], - }, - { - name: 'suppressActionMode', - modifier: 'private', - returnType: 'ActionMode', - params: [ - { - type: 'ActionMode', - name: 'mode', - } - ], - body: [ - `if (mode == null || !nativeContextMenuDisabled) { - return mode; - } - suppressActionModeUi(mode, mode.getMenu()); - return mode;`, - ], - }, - { - name: 'suppressActionModeUi', - modifier: 'private', - returnType: 'void', - params: [ - { - type: 'ActionMode', - name: 'mode', - }, - { - type: 'Menu', - name: 'menu', - } - ], - body: [ - `if (mode == null || !nativeContextMenuDisabled || menu == null) { - return; - } - menu.clear(); - mode.setTitle(null); - mode.setSubtitle(null); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - post(() -> { - if (!nativeContextMenuDisabled) { - return; - } - try { - mode.hide(0); - } catch (Throwable ignored) { - } - }); - }`, - ], - }, - ] - }, - 'SystemWebViewEngine.java': { - methods: [ - setInputTypeMethod, - setNativeContextMenuDisabledMethod, - ] - }, - 'CordovaWebViewEngine.java': { - methods: [ - interfaceMethod, - nativeContextMenuInterfaceMethod, - ] - }, - 'CordovaWebView.java': { - methods: [ - interfaceMethod, - nativeContextMenuInterfaceMethod, - ] - }, - 'CordovaWebViewImpl.java': { - methods: [ - { - ...setInputTypeMethod, - body: [`engine.setInputType(type);`] - }, - { - ...setNativeContextMenuDisabledMethod, - body: [`engine.setNativeContextMenuDisabled(disabled);`] - } - ] - } - }; - - const fileContent = {}; - - for (let file in files) { - fileContent[file] = fs.readFileSync(files[file], 'utf8'); - } - - for (let file in contentToAdd) { - const content = fileContent[file]; - const contentToAddTo = contentToAdd[file]; - const text = removeComments(content); - let newContent = await format(text); - if (contentToAddTo.import) { - const imports = contentToAddTo.import.map(importStr => { - return `import ${importStr};`; - }).join('\n'); - - newContent = newContent.replace( - /^(\s*)(import.*;)/m, - `$1${imports}\n$2` - ); - } - if (contentToAddTo.fields) { - const fields = contentToAddTo.fields.map(field => { - return getFieldString(field); - }).join('\n'); - newContent = newContent.replace( - /^(\s*)(\w+\s+\w+\s*;)/m, - `$1${fields}\n$2` - ); - } - if (contentToAddTo.methods) { - const methods = contentToAddTo.methods.map(method => { - return getMethodString(method); - }).join('\n'); - - if (isInterface(file, content)) { - const regex = getInterfaceDeclarationRegex(file); - newContent = newContent.replace( - regex, - `$1${methods}\n$2` - ); - } else { - let regex = getConstructorRegex(file); - if (regex.test(newContent)) { - newContent = newContent.replace( - regex, - `$1${methods}\n$2` - ); - } else { - regex = getClassDeclarationRegex(file); - newContent = newContent.replace( - regex, - `$1${methods}\n$2` - ); - } - } - } - - newContent = await format(newContent); - fs.writeFile(files[file], newContent, err => { - if (err) { - console.log(err); - process.exit(1); - } - - console.log(`${files[file]} updated`); - }); - } - - fs.writeFile(flagFile, patchVersion, err => { - if (err) { - console.log(err); - process.exit(1); - } - - console.log(`${flagFile} updated`); - }); - - async function format(content) { - return prettier.format(content, { - plugins: ['prettier-plugin-java'], - parser: 'java', - tabWidth: 2, - printWidth: Infinity - }); - } - - function getMethodString(method) { - const params = method.params.map(param => { - return `${param.type} ${param.name}`; - }).join(', '); - - let str = `${method.modifier} ${method.returnType} ${method.name}(${params})`; - if (method.notation) { - str = `\n${method.notation}\n${str}`; - } - if (method.body) { - return str + `{${method.body.join('')}}`; - } - return str + ';'; - } - - function getFieldString(field) { - return `${field.modifier} ${field.type} ${field.name}${field.value ? ` = ${field.value}` : ''};`; - } - - function isInterface(filename, content) { - return content.indexOf(`interface ${filename.split('.')[0]}`) > -1; - } - - function getConstructorRegex(filename) { - return new RegExp(`([^]*?${filename.split('.')[0]}\\s*\\(.*?\\)\\s*{[^}]*})([^]*)`, 'm'); - } - - function getInterfaceDeclarationRegex(filename) { - return new RegExp(`([^]*?interface\\s+${filename.split('.')[0]}[\\s\\w]*{)([^]*})`, 'm'); - } - - function getClassDeclarationRegex(filename) { - return new RegExp(`([^]*?class\\s+${filename.split('.')[0]}[\\s\\w]*{)([^]*})`, 'm'); - } - - function removeComments(content) { - return content.replace(/\/\*[^]*?\*\/|([^\\:]|^)\/\/.*$/gm, ''); - } -} diff --git a/hooks/move-files.js b/hooks/move-files.js deleted file mode 100644 index df4295c223..0000000000 --- a/hooks/move-files.js +++ /dev/null @@ -1,36 +0,0 @@ -const path = require('path'); -const fs = require('fs'); - -const gradleFilePath = path.resolve(__dirname, '../build-extras.gradle'); -const newGradleFilePath = path.resolve( - __dirname, - '../platforms/android/app/build-extras.gradle' -); -const buildFilePath = path.resolve(__dirname, '../build.json'); -const newBuildFilePath = path.resolve( - __dirname, - '../platforms/android/build.json' -); - -const repeatChar = (char, times) => { - let res = ''; - while (--times >= 0) res += char; - return res; -}; - -let msg; -if (!fs.existsSync(newBuildFilePath) && fs.existsSync(buildFilePath)) { - msg = '== Moved build.json =='; - console.log(repeatChar('=', msg.length)); - console.log(msg); - console.log(repeatChar('=', msg.length)); - fs.copyFileSync(buildFilePath, newBuildFilePath); -} - -if (!fs.existsSync(newGradleFilePath) && fs.existsSync(gradleFilePath)) { - msg = '== Moved build-extras.gradle =='; - console.log(repeatChar('=', msg.length)); - console.log(msg); - console.log(repeatChar('=', msg.length)); - fs.copyFileSync(gradleFilePath, newGradleFilePath); -} diff --git a/hooks/post-process.js b/hooks/post-process.js deleted file mode 100644 index 449669cf4c..0000000000 --- a/hooks/post-process.js +++ /dev/null @@ -1,441 +0,0 @@ -/* eslint-disable no-console */ -const path = require('path'); -const fs = require('fs'); -const { execSync } = require('child_process'); - -const buildFilePath = path.resolve(__dirname, '../build.json'); -const copyToPath = path.resolve(__dirname, '../platforms/android/build.json'); -const gradleFilePath = path.resolve(__dirname, '../build-extras.gradle'); -const androidGradleFilePath = path.resolve( - __dirname, - '../platforms/android/app/build-extras.gradle' -); -const resPath = path.resolve(__dirname, '../platforms/android/app/src/main/res/'); -const localResPath = path.resolve(__dirname, '../res/android/'); - -if ( - !fs.existsSync(copyToPath) - && fs.existsSync(buildFilePath) -) fs.copyFileSync(buildFilePath, copyToPath); - -if (fs.existsSync(androidGradleFilePath)) fs.unlinkSync(androidGradleFilePath); -fs.copyFileSync(gradleFilePath, androidGradleFilePath); - -// Cordova Android 15 generates `cdv_*` resources and version-qualified value -// directories that are required later in the build. Keep the generated tree and -// only overlay this project's custom resources on top of it. -copyDirRecursively(localResPath, resPath); -// Cordova can retain plugin Java from an earlier install during prepare. -// Keep the System plugin's icon map in sync with the launcher resources. -copyDirRecursively( - path.resolve(__dirname, '../src/plugins/system/android'), - path.resolve(__dirname, '../platforms/android/app/src/main/java') -); -enableLegacyJni(); -enableStaticContext(); -disableSplashFadeOnRealmeAndroid13(); -removeLegacyKeyboardWorkaround(); -patchTargetSdkVersion(); -stripLauncherFilterFromMainActivity(); - -function getPackageName() { - const configPath = path.resolve(__dirname, '../config.xml'); - if (!fs.existsSync(configPath)) { - console.warn('[Cordova Hook] ⚠️ config.xml not found at', configPath); - throw new Error(`config.xml is missing at ${configPath}`); - } - const content = fs.readFileSync(configPath, 'utf-8'); - const match = content.match(/id="([^"]+)"/); - const packageName = match ? match[1] : 'com.foxdebug.acode'; - return packageName; -} - - -function getTmpDir() { - const tmpdirEnv = process.env.TMPDIR; - - if (tmpdirEnv) { - try { - fs.accessSync(tmpdirEnv, fs.constants.R_OK | fs.constants.W_OK); - return tmpdirEnv; - } catch { - // TMPDIR exists but not accessible - } - } - - try { - fs.accessSync("/tmp", fs.constants.R_OK | fs.constants.W_OK); - return "/tmp"; - } catch { - console.log("Error: No usable temporary directory found (TMPDIR or /tmp not accessible)."); - return null; - // process.exit(1); - } -} - -/** - * Removes the MAIN/LAUNCHER intent-filter from MainActivity in the generated - * AndroidManifest. The launcher role is handled by activity-aliases instead - * (see config.xml), so that switching app icons at runtime only toggles aliases - * and never disables the running MainActivity component (which would otherwise - * force-stop/restart the app). - */ -function stripLauncherFilterFromMainActivity() { - const prefix = execSync('npm prefix').toString().trim(); - const manifestPath = path.join( - prefix, - 'platforms/android/app/src/main/AndroidManifest.xml' - ); - - if (!fs.existsSync(manifestPath)) { - console.warn('[Cordova Hook] ⚠️ AndroidManifest.xml not found'); - return; - } - - let content = fs.readFileSync(manifestPath, 'utf-8'); - const updated = content.replace( - /(<activity[^>]*\bname="MainActivity"[^>]*>)\s*<intent-filter[^>]*>\s*<action android:name="android\.intent\.action\.MAIN"[^>]*\/>\s*<category android:name="android\.intent\.category\.LAUNCHER"[^>]*\/>\s*<\/intent-filter>/, - '$1' - ); - - if (updated !== content) { - fs.writeFileSync(manifestPath, updated, 'utf-8'); - console.log( - '[Cordova Hook] ✅ Removed launcher intent-filter from MainActivity' - ); - } else { - console.log( - '[Cordova Hook] ✅ Launcher intent-filter already removed, skipping' - ); - } -} - -function patchTargetSdkVersion() { - const prefix = execSync('npm prefix').toString().trim(); - const gradleFile = path.join(prefix, 'platforms/android/app/build.gradle'); - - if (!fs.existsSync(gradleFile)) { - console.warn('[Cordova Hook] ⚠️ build.gradle not found'); - return; - } - - let content = fs.readFileSync(gradleFile, 'utf-8'); - - const sdkRegex = /targetSdkVersion\s+(cordovaConfig\.SDK_VERSION|\d+)/; - - if (sdkRegex.test(content)) { - let api = "36"; - const tmp = getTmpDir(); - if (tmp == null) { - console.warn("---------------------------------------------------------------------------------\n\n\n\n"); - console.warn(`⚠️ fdroid.bool not found`); - console.warn("⚠️ Fdroid flavour will be built"); - api = "28"; - console.warn("\n\n\n\n---------------------------------------------------------------------------------"); - } else { - const froidFlag = path.join(getTmpDir(), 'fdroid.bool'); - - if (fs.existsSync(froidFlag)) { - const fdroid = fs.readFileSync(froidFlag, 'utf-8').trim(); - if (fdroid == "true") { - api = "28"; - } - } else { - console.warn("---------------------------------------------------------------------------------\n\n\n\n"); - console.warn(`⚠️ fdroid.bool not found`); - console.warn("⚠️ Fdroid flavour will be built"); - api = "28"; - console.warn("\n\n\n\n---------------------------------------------------------------------------------"); - //process.exit(1); - } - } - - - content = content.replace(sdkRegex, 'targetSdkVersion ' + api); - fs.writeFileSync(gradleFile, content, 'utf-8'); - console.log('[Cordova Hook] ✅ Patched targetSdkVersion to ' + api); - } else { - console.warn('[Cordova Hook] ⚠️ targetSdkVersion not found'); - } -} - - -function enableLegacyJni() { - const prefix = execSync('npm prefix').toString().trim(); - const gradleFile = path.join(prefix, 'platforms/android/app/build.gradle'); - - if (!fs.existsSync(gradleFile)){ - console.warn('[Cordova Hook] ⚠️ build.gradle not found'); - return - }; - - let content = fs.readFileSync(gradleFile, 'utf-8'); - // Check for correct block to avoid duplicate insertion - if (content.includes('useLegacyPackaging = true')){ - console.log('[Cordova Hook] ✅ Legacy JNI packaging already enabled, skipping'); - return - }; - - // Inject under android block with correct Groovy syntax - content = content.replace(/android\s*{/, match => { - return ( - match + - ` - packagingOptions { - jniLibs { - useLegacyPackaging = true - } - }` - ); - }); - - fs.writeFileSync(gradleFile, content, 'utf-8'); - console.log('[Cordova Hook] ✅ Enabled legacy JNI packaging'); -} - -function enableStaticContext() { - try { - const prefix = execSync('npm prefix').toString().trim(); - const packageName = getPackageName(); - const mainActivityPath = path.join( - prefix, - 'platforms/android/app/src/main/java', - packageName.replace(/\./g, '/'), - 'MainActivity.java' - ); - - if (!fs.existsSync(mainActivityPath)) { - console.warn('[Cordova Hook] ⚠️ MainActivity.java not found at', mainActivityPath); - return; - } - - let content = fs.readFileSync(mainActivityPath, 'utf-8'); - - // Skip if fully patched - if ( - content.includes('WeakReference<Context>') && - content.includes('public static Context getContext()') && - content.includes('weakContext = new WeakReference<>(this);') - ) { - console.log('[Cordova Hook] ✅ Static context already enabled, skipping'); - return; - } - - // Add missing imports - if (!content.includes('import java.lang.ref.WeakReference;')) { - content = content.replace( - /import org\.apache\.cordova\.\*;/, - match => - match + - '\nimport android.content.Context;\nimport java.lang.ref.WeakReference;' - ); - } - - // Inject static field and method into class body - content = content.replace( - /public class MainActivity extends CordovaActivity\s*\{/, - match => - match + - `\n\n private static WeakReference<Context> weakContext;\n\n` + - ` public static Context getContext() {\n` + - ` return weakContext != null ? weakContext.get() : null;\n` + - ` }\n` - ); - - // Insert weakContext assignment inside onCreate - content = content.replace( - /super\.onCreate\(savedInstanceState\);/, - `super.onCreate(savedInstanceState);\n weakContext = new WeakReference<>(this);` - ); - - fs.writeFileSync(mainActivityPath, content, 'utf-8'); - console.log('[Cordova Hook] ✅ Enabled static context'); - } catch (err) { - console.error('[Cordova Hook] ❌ Failed to patch MainActivity:', err.message); - } -} - -function disableSplashFadeOnRealmeAndroid13() { - try { - const prefix = execSync('npm prefix').toString().trim(); - const packageName = getPackageName(); - const mainActivityPath = path.join( - prefix, - 'platforms/android/app/src/main/java', - packageName.replace(/\./g, '/'), - 'MainActivity.java' - ); - - if (!fs.existsSync(mainActivityPath)) { - console.warn('[Cordova Hook] ⚠️ MainActivity.java not found at', mainActivityPath); - return; - } - - let content = fs.readFileSync(mainActivityPath, 'utf-8'); - - if ( - content.includes('hasBrokenRealmeSplashTransfer()') && - content.includes('preferences.set("FadeSplashScreen", false);') - ) { - console.log('[Cordova Hook] ✅ realme splash workaround already enabled, skipping'); - return; - } - - if (!content.includes('import android.os.Build;')) { - content = content.replace( - /import android\.os\.Bundle;/, - 'import android.os.Build;\nimport android.os.Bundle;' - ); - } - - content = content.replace( - /\n\s*@Override\n\s*public void onCreate\(Bundle savedInstanceState\)/, - ` - - private static boolean hasBrokenRealmeSplashTransfer() { - return Build.VERSION.SDK_INT == Build.VERSION_CODES.TIRAMISU - && ("realme".equalsIgnoreCase(Build.MANUFACTURER) - || "realme".equalsIgnoreCase(Build.BRAND)); - } - - @Override - protected void loadConfig() { - super.loadConfig(); - - // Some realme Android 13 builds pass a null SurfaceControl while handing the - // splash view to an app-provided exit animation. Avoid only that handoff. - if (hasBrokenRealmeSplashTransfer()) { - preferences.set("FadeSplashScreen", false); - } - } - - @Override - public void onCreate(Bundle savedInstanceState)` - ); - - if (!content.includes('preferences.set("FadeSplashScreen", false);')) { - console.warn('[Cordova Hook] ⚠️ Unable to inject realme splash workaround'); - return; - } - - fs.writeFileSync(mainActivityPath, content, 'utf-8'); - console.log('[Cordova Hook] ✅ Disabled splash fade on realme Android 13'); - } catch (err) { - console.error( - '[Cordova Hook] ❌ Failed to patch realme splash workaround:', - err.message - ); - } -} - -function removeLegacyKeyboardWorkaround() { - try { - const prefix = execSync('npm prefix').toString().trim(); - const packageName = getPackageName(); - const mainActivityPath = path.join( - prefix, - 'platforms/android/app/src/main/java', - packageName.replace(/\./g, '/'), - 'MainActivity.java' - ); - - if (!fs.existsSync(mainActivityPath)) { - return; - } - - const content = fs.readFileSync(mainActivityPath, 'utf-8'); - const updatedContent = content - .replace(/\r?\nimport com\.foxdebug\.system\.SoftInputAssist;/, '') - .replace(/\r?\n\s*private SoftInputAssist softInputAssist;\r?\n/, '\n') - .replace( - /\r?\n\s*softInputAssist = new SoftInputAssist\(this\);/, - '' - ); - - if (updatedContent !== content) { - fs.writeFileSync(mainActivityPath, updatedContent, 'utf-8'); - console.log('[Cordova Hook] ✅ Removed legacy keyboard workaround'); - } - } catch (err) { - console.error( - '[Cordova Hook] ❌ Failed to remove legacy keyboard workaround:', - err.message - ); - } -} - -/** - * Copy directory recursively - * @param {string} src Source directory - * @param {string} dest Destination directory - * @param {string[]} skip Files to not copy - */ -function copyDirRecursively(src, dest, skip = [], currPath = '') { - const exists = fs.existsSync(src); - const stats = exists && fs.statSync(src); - const isDirectory = exists && stats.isDirectory(); - - if (!exists) { - console.log(`File ${src} does not exist`); - return; - } - - if (!fs.existsSync(dest) && isDirectory) { - fs.mkdirSync(dest); - } - - if (exists && isDirectory) { - fs.mkdirSync(dest, { recursive: true }); - fs.readdirSync(src).forEach((childItemName) => { - const relativePath = path.join(currPath, childItemName); - if (childItemName.startsWith('.')) return; - if (skip.includes(childItemName) || skip.includes(relativePath)) return; - copyDirRecursively( - path.join(src, childItemName), - path.join(dest, childItemName), - skip, - relativePath, - ); - }); - } else { - removeConflictingResourceFiles(src, dest); - fs.copyFileSync(src, dest); - - // log - const message = `copied: ${path.basename(src)}`; - console.log('\x1b[32m%s\x1b[0m', message); // green - } -} - -function removeConflictingResourceFiles(src, dest) { - const parentDir = path.dirname(dest); - - if (!fs.existsSync(parentDir)) { - return; - } - - const resourceDirName = path.basename(parentDir); - if (!resourceDirName.startsWith('mipmap') && !resourceDirName.startsWith('drawable')) { - return; - } - - const srcExt = path.extname(src); - const resourceName = path.basename(src, srcExt); - - for (const existingName of fs.readdirSync(parentDir)) { - const existingPath = path.join(parentDir, existingName); - if (existingPath === dest || !fs.statSync(existingPath).isFile()) { - continue; - } - - const existingExt = path.extname(existingName); - const existingResourceName = path.basename(existingName, existingExt); - - if (existingResourceName !== resourceName || existingExt === srcExt) { - continue; - } - - fs.rmSync(existingPath); - console.log('\x1b[31m%s\x1b[0m', `deleted conflicting resource: ${existingName}`); - } -} diff --git a/hooks/restore-cordova-resources.js b/hooks/restore-cordova-resources.js deleted file mode 100644 index f515a64277..0000000000 --- a/hooks/restore-cordova-resources.js +++ /dev/null @@ -1,49 +0,0 @@ -const fs = require("fs"); -const path = require("path"); - -const templateResPath = path.resolve( - __dirname, - "../node_modules/cordova-android/templates/project/res", -); -const androidResPath = path.resolve( - __dirname, - "../platforms/android/app/src/main/res", -); - -if (!fs.existsSync(templateResPath) || !fs.existsSync(androidResPath)) { - process.exit(0); -} - -restoreCordovaResourceFiles(templateResPath); - -function restoreCordovaResourceFiles(currentPath) { - for (const entry of fs.readdirSync(currentPath, { withFileTypes: true })) { - const absolutePath = path.join(currentPath, entry.name); - - if (entry.isDirectory()) { - restoreCordovaResourceFiles(absolutePath); - continue; - } - - if (!shouldRestore(absolutePath)) { - continue; - } - - const relativePath = path.relative(templateResPath, absolutePath); - const destinationPath = path.join(androidResPath, relativePath); - - if (fs.existsSync(destinationPath)) { - continue; - } - - fs.mkdirSync(path.dirname(destinationPath), { recursive: true }); - fs.copyFileSync(absolutePath, destinationPath); - console.log(`[Cordova Hook] Restored ${relativePath}`); - } -} - -function shouldRestore(filePath) { - const fileName = path.basename(filePath); - - return fileName.startsWith("cdv_") || fileName === "ic_cdv_splashscreen.xml"; -} diff --git a/icomoon.json b/icomoon.json new file mode 100644 index 0000000000..db9b65cedc --- /dev/null +++ b/icomoon.json @@ -0,0 +1 @@ +{"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]},"formats":[{"order":0,"mOpen":false,"item":{"tag":"ItemFont","args":[{"addPalettes":false,"classPerGlyph":true,"fontFamily":{"value":"code-editor-icon"},"prefix":{"value":"icon-"},"scss":true}]}}],"glyphs":[{"extras":{"name":"text-search","codePoint":61482},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]},"xmlns:xlink":{"tag":"StringValue","args":["http://www.w3.org/1999/xlink"]}},"children":[{"tag":"Text","args":["\n "]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[21,6],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[3,6]}]}]}]]}]}},"children":[]}]},{"tag":"Text","args":["\n "]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[10,12],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[3,12]}]}]}]]}]}},"children":[]}]},{"tag":"Text","args":["\n "]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[10,18],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[3,18]}]}]}]]}]}},"children":[]}]},{"tag":"Text","args":["\n "]},{"tag":"Element","args":[{"tagName":"circle","attributes":{"cx":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[17]}]}]},"cy":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[15]}]}]},"r":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[3]}]}]}},"children":[]}]},{"tag":"Text","args":["\n "]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[21,19],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[19.1,17.1]}]}]}]]}]}},"children":[]}]},{"tag":"Text","args":["\n"]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"wand","codePoint":61460},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-wand-icon lucide-wand"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[15,4],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[15,2]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[15,16],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[15,14]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[8,9],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[10,9]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[20,9],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[22,9]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[17.8,11.8],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[19,13]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[15,9],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[15.01,9]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[17.8,6.2],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[19,5]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[3,21],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[12,12]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[12.2,6.2],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[11,5]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"wand-sparkles","codePoint":61459},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-wand-sparkles-icon lucide-wand-sparkles"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[21.64,3.64],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[20.36,2.3600000000000003]}]},{"tag":"EllipticArcTo","args":[{"rx":1.21,"ry":1.21,"phi":0,"fA":false,"fS":false,"end":[18.64,2.3600000000000003]}]},{"tag":"LineTo","args":[{"point":[2.36,18.64]}]},{"tag":"EllipticArcTo","args":[{"rx":1.21,"ry":1.21,"phi":0,"fA":false,"fS":false,"end":[2.36,20.36]}]},{"tag":"LineTo","args":[{"point":[3.6399999999999997,21.64]}]},{"tag":"EllipticArcTo","args":[{"rx":1.2,"ry":1.2,"phi":0,"fA":false,"fS":false,"end":[5.359999999999999,21.64]}]},{"tag":"LineTo","args":[{"point":[21.64,5.36]}]},{"tag":"EllipticArcTo","args":[{"rx":1.2,"ry":1.2,"phi":0,"fA":false,"fS":false,"end":[21.64,3.6400000000000006]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[14,7],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[17,10]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[5,6],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[5,10]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[19,14],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[19,18]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[10,2],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[10,4]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[7,8],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[3,8]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[21,16],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[17,16]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[11,3],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[9,3]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"link","codePoint":61458},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-link-icon lucide-link"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[10,13],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":5,"ry":5,"phi":0,"fA":false,"fS":false,"end":[17.54,13.54]}]},{"tag":"LineTo","args":[{"point":[20.54,10.54]}]},{"tag":"EllipticArcTo","args":[{"rx":5,"ry":5,"phi":0,"fA":false,"fS":false,"end":[13.469999999999999,3.469999999999999]}]},{"tag":"LineTo","args":[{"point":[11.749999999999998,5.179999999999999]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[14,11],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":5,"ry":5,"phi":0,"fA":false,"fS":false,"end":[6.46,10.46]}]},{"tag":"LineTo","args":[{"point":[3.46,13.46]}]},{"tag":"EllipticArcTo","args":[{"rx":5,"ry":5,"phi":0,"fA":false,"fS":false,"end":[10.530000000000001,20.53]}]},{"tag":"LineTo","args":[{"point":[12.240000000000002,18.82]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"brain","codePoint":61457},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-brain-icon lucide-brain"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[12,18],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[12,5]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[15,13],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":4.17,"ry":4.17,"phi":0,"fA":false,"fS":true,"end":[12,9]}]},{"tag":"EllipticArcTo","args":[{"rx":4.17,"ry":4.17,"phi":0,"fA":false,"fS":true,"end":[9,13]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[17.598,6.5],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":3,"ry":3,"phi":0,"fA":true,"fS":false,"end":[12,5]}]},{"tag":"EllipticArcTo","args":[{"rx":3,"ry":3,"phi":0,"fA":true,"fS":false,"end":[6.402,6.5]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[17.997,5.125],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":4,"ry":4,"phi":0,"fA":false,"fS":true,"end":[20.523,10.895]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[18,18],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":4,"ry":4,"phi":0,"fA":false,"fS":false,"end":[20,10.536]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[19.967,17.483],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":4,"ry":4,"phi":0,"fA":true,"fS":true,"end":[12,18]}]},{"tag":"EllipticArcTo","args":[{"rx":4,"ry":4,"phi":0,"fA":true,"fS":true,"end":[4.033,17.483]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[6,18],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":4,"ry":4,"phi":0,"fA":false,"fS":true,"end":[4,10.536]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[6.003,5.125],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":4,"ry":4,"phi":0,"fA":false,"fS":false,"end":[3.4770000000000003,10.895]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"paperclip","codePoint":61456},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-paperclip-icon lucide-paperclip"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[16,6],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[7.586,14.586]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":false,"end":[10.415000000000001,17.415]}]},{"tag":"LineTo","args":[{"point":[18.829,8.828999999999999]}]},{"tag":"EllipticArcTo","args":[{"rx":4,"ry":4,"phi":0,"fA":true,"fS":false,"end":[13.172,3.171999999999999]}]},{"tag":"LineTo","args":[{"point":[4.793000000000001,11.722999999999999]}]},{"tag":"EllipticArcTo","args":[{"rx":6,"ry":6,"phi":0,"fA":true,"fS":false,"end":[13.278,20.208]}]},{"tag":"LineTo","args":[{"point":[21.657,11.656999999999998]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"palette","codePoint":61455},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-palette-icon lucide-palette"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[12,22],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":true,"end":[12,2]}]},{"tag":"EllipticArcTo","args":[{"rx":10,"ry":9,"phi":0,"fA":false,"fS":true,"end":[22,11]}]},{"tag":"EllipticArcTo","args":[{"rx":5,"ry":5,"phi":0,"fA":false,"fS":true,"end":[17,16]}]},{"tag":"LineTo","args":[{"point":[14.75,16]}]},{"tag":"EllipticArcTo","args":[{"rx":1.75,"ry":1.75,"phi":0,"fA":false,"fS":false,"end":[13.35,18.8]}]},{"tag":"LineTo","args":[{"point":[13.65,19.2]}]},{"tag":"EllipticArcTo","args":[{"rx":1.75,"ry":1.75,"phi":0,"fA":false,"fS":true,"end":[12.25,22]}]},{"tag":"LineTo","args":[{"point":[12,22]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"circle","attributes":{"cx":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[13.5]}]}]},"cy":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[6.5]}]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"r":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[0.5]}]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"circle","attributes":{"cx":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[17.5]}]}]},"cy":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[10.5]}]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"r":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[0.5]}]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"circle","attributes":{"cx":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[6.5]}]}]},"cy":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[12.5]}]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"r":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[0.5]}]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"circle","attributes":{"cx":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[8.5]}]}]},"cy":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[7.5]}]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"r":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[0.5]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"loader","codePoint":61454},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-loader-icon lucide-loader"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[12,2],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[12,6]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[16.2,7.8],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[19.099999999999998,4.9]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[18,12],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[22,12]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[16.2,16.2],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[19.099999999999998,19.099999999999998]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[12,18],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[12,22]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[4.9,19.1],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[7.800000000000001,16.200000000000003]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[2,12],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[6,12]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[4.9,4.9],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[7.800000000000001,7.800000000000001]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"square-terminal","codePoint":61453},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-square-terminal-icon lucide-square-terminal"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[7,11],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[9,9]}]},{"tag":"LineTo","args":[{"point":[7,7]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[11,13],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[15,13]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"rect","attributes":{"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[18]}]}]},"rx":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"ry":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[18]}]}]},"x":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[3]}]}]},"y":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[3]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"house","codePoint":61452},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-house-icon lucide-house"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[15,21],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[15,13]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":false,"end":[14,12]}]},{"tag":"LineTo","args":[{"point":[10,12]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":false,"end":[9,13]}]},{"tag":"LineTo","args":[{"point":[9,21]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[3,10],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":true,"end":[3.709,8.472]}]},{"tag":"LineTo","args":[{"point":[10.709,2.4719999999999995]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":true,"end":[13.291,2.4719999999999995]}]},{"tag":"LineTo","args":[{"point":[20.291,8.472]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":true,"end":[21,10]}]},{"tag":"LineTo","args":[{"point":[21,19]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":true,"end":[19,21]}]},{"tag":"LineTo","args":[{"point":[5,21]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":true,"end":[3,19]}]},{"tag":"LineTo","args":[{"point":[3,10]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"message-circle","codePoint":61451},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-message-circle-icon lucide-message-circle"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[2.992,16.342],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":true,"end":[3.086,17.509]}]},{"tag":"LineTo","args":[{"point":[2.021,20.799]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":false,"end":[3.2569999999999997,21.967]}]},{"tag":"LineTo","args":[{"point":[6.67,20.968999999999998]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":true,"end":[7.769,21.060999999999996]}]},{"tag":"EllipticArcTo","args":[{"rx":10,"ry":10,"phi":0,"fA":true,"fS":false,"end":[2.992,16.341999999999995]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"user-round","codePoint":61450},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-user-round-icon lucide-user-round"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"circle","attributes":{"cx":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[12]}]}]},"cy":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[8]}]}]},"r":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[5]}]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[20,21],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":8,"ry":8,"phi":0,"fA":false,"fS":false,"end":[4,21]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"funnel","codePoint":61449},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-funnel-icon lucide-funnel"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[10,20],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":false,"end":[10.553,20.895]}]},{"tag":"LineTo","args":[{"point":[12.553,21.895]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":false,"end":[14,21]}]},{"tag":"LineTo","args":[{"point":[14,14]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":true,"end":[14.517,12.659]}]},{"tag":"LineTo","args":[{"point":[21.74,4.67]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":false,"end":[21,3]}]},{"tag":"LineTo","args":[{"point":[3,3]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":false,"end":[2.258,4.67]}]},{"tag":"LineTo","args":[{"point":[9.483,12.658999999999999]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":true,"end":[10,14]}]},{"tag":"LineTo","args":[{"point":[10,20]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"zap","codePoint":61440},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-zap-icon lucide-zap"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[4,14],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":true,"end":[3.2199999999999998,12.370000000000001]}]},{"tag":"LineTo","args":[{"point":[13.120000000000001,2.1700000000000017]}]},{"tag":"EllipticArcTo","args":[{"rx":0.5,"ry":0.5,"phi":0,"fA":false,"fS":true,"end":[13.98,2.6300000000000017]}]},{"tag":"LineTo","args":[{"point":[12.06,8.650000000000002]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":false,"end":[13,10]}]},{"tag":"LineTo","args":[{"point":[20,10]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":true,"end":[20.78,11.629999999999999]}]},{"tag":"LineTo","args":[{"point":[10.88,21.83]}]},{"tag":"EllipticArcTo","args":[{"rx":0.5,"ry":0.5,"phi":0,"fA":false,"fS":true,"end":[10.020000000000001,21.369999999999997]}]},{"tag":"LineTo","args":[{"point":[11.940000000000001,15.349999999999998]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":false,"end":[11,14]}]},{"tag":"LineTo","args":[{"point":[4,14]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"verified","codePoint":61441},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["size-6"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Text","args":["\n "]},{"tag":"Element","args":[{"tagName":"path","attributes":{"clip-rule":{"tag":"Value","args":[{"tag":"FillRule","args":[{"tag":"EvenOdd","args":[]}]}]},"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[8.603,3.799],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":4.49,"ry":4.49,"phi":0,"fA":false,"fS":true,"end":[12,2.25]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[13.357,2.25],"c2":[14.573,2.85],"end":[15.397,3.799]}]}]},{"tag":"EllipticArcTo","args":[{"rx":4.49,"ry":4.49,"phi":0,"fA":false,"fS":true,"end":[18.895,5.106]}]},{"tag":"EllipticArcTo","args":[{"rx":4.491,"ry":4.491,"phi":0,"fA":false,"fS":true,"end":[20.201999999999998,8.603]}]},{"tag":"EllipticArcTo","args":[{"rx":4.49,"ry":4.49,"phi":0,"fA":false,"fS":true,"end":[21.75,12]}]},{"tag":"EllipticArcTo","args":[{"rx":4.49,"ry":4.49,"phi":0,"fA":false,"fS":true,"end":[20.201,15.397]}]},{"tag":"EllipticArcTo","args":[{"rx":4.491,"ry":4.491,"phi":0,"fA":false,"fS":true,"end":[18.894000000000002,18.894]}]},{"tag":"EllipticArcTo","args":[{"rx":4.491,"ry":4.491,"phi":0,"fA":false,"fS":true,"end":[15.397000000000002,20.200999999999997]}]},{"tag":"EllipticArcTo","args":[{"rx":4.49,"ry":4.49,"phi":0,"fA":false,"fS":true,"end":[12,21.75]}]},{"tag":"EllipticArcTo","args":[{"rx":4.49,"ry":4.49,"phi":0,"fA":false,"fS":true,"end":[8.603,20.201]}]},{"tag":"EllipticArcTo","args":[{"rx":4.49,"ry":4.49,"phi":0,"fA":false,"fS":true,"end":[5.1049999999999995,18.895]}]},{"tag":"EllipticArcTo","args":[{"rx":4.491,"ry":4.491,"phi":0,"fA":false,"fS":true,"end":[3.7979999999999996,15.396999999999998]}]},{"tag":"EllipticArcTo","args":[{"rx":4.49,"ry":4.49,"phi":0,"fA":false,"fS":true,"end":[2.25,12]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[2.25,10.643],"c2":[2.85,9.427],"end":[3.799,8.603]}]}]},{"tag":"EllipticArcTo","args":[{"rx":4.49,"ry":4.49,"phi":0,"fA":false,"fS":true,"end":[5.106,5.106]}]},{"tag":"EllipticArcTo","args":[{"rx":4.49,"ry":4.49,"phi":0,"fA":false,"fS":true,"end":[8.603,3.799]}]}]},{"start":[15.61,10.186],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":0.75,"ry":0.75,"phi":0,"fA":true,"fS":false,"end":[14.389999999999999,9.314]}]},{"tag":"LineTo","args":[{"point":[11.153999999999998,13.844000000000001]}]},{"tag":"LineTo","args":[{"point":[9.53,12.22]}]},{"tag":"EllipticArcTo","args":[{"rx":0.75,"ry":0.75,"phi":0,"fA":false,"fS":false,"end":[8.469999999999999,13.280000000000001]}]},{"tag":"LineTo","args":[{"point":[10.719999999999999,15.530000000000001]}]},{"tag":"EllipticArcTo","args":[{"rx":0.75,"ry":0.75,"phi":0,"fA":false,"fS":false,"end":[11.86,15.436000000000002]}]},{"tag":"LineTo","args":[{"point":[15.61,10.186]}]}]}]]}]},"fill-rule":{"tag":"Value","args":[{"tag":"FillRule","args":[{"tag":"EvenOdd","args":[]}]}]}},"children":[]}]},{"tag":"Text","args":["\n"]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"terminal","codePoint":61442},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[1024]}]}]},"version":{"tag":"StringValue","args":["1.1"]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[1024]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Text","args":["\n"]},{"tag":"Text","args":["\n"]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[155.435,173.611],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[140.416,178.902],"c2":[128,196.86399999999998],"end":[128,213.334]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[128,216.747],"c2":[129.237,223.318],"end":[130.773,227.969]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[133.29,235.606],"c2":[144.085,246.956],"end":[249.76999999999998,352.854]}]}]},{"tag":"LineTo","args":[{"point":[366.037,469.334]}]},{"tag":"LineTo","args":[{"point":[249.76999999999998,585.814]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[144.08499999999998,691.713],"c2":[133.28999999999996,703.062],"end":[130.77299999999997,710.699]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[125.26899999999996,727.3389999999999],"c2":[128.89599999999996,743.382],"end":[140.79999999999995,755.286]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[148.42199999999997,762.954],"c2":[158.97599999999994,767.6999999999999],"end":[170.63899999999995,767.6999999999999]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[177.55899999999994,767.6999999999999],"c2":[184.08899999999994,766.0289999999999],"end":[189.84699999999995,763.069]}]}]},{"tag":"LineTo","args":[{"point":[189.61099999999996,763.179]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[195.02999999999997,760.576],"c2":[234.32599999999996,722.304],"end":[330.45399999999995,625.963]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[456.96099999999996,499.24299999999994],"c2":[463.95799999999997,491.904],"end":[466.77399999999994,483.24299999999994]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[468.18299999999994,479.1599999999999],"c2":[468.99699999999996,474.4549999999999],"end":[468.99699999999996,469.55999999999995]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[468.99699999999996,462.57599999999996],"c2":[467.34099999999995,455.97999999999996],"end":[464.4,450.14099999999996]}]}]},{"tag":"LineTo","args":[{"point":[464.513,450.38899999999995]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[461.90999999999997,444.96999999999997],"c2":[423.638,405.717],"end":[327.29699999999997,309.54599999999994]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[205.48399999999998,187.94599999999994],"c2":[192.98199999999997,175.95699999999994],"end":[185.30199999999996,173.43899999999994]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[180.92499999999995,171.84899999999993],"c2":[175.87299999999996,170.92999999999995],"end":[170.60699999999997,170.92999999999995]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[165.16199999999998,170.92999999999995],"c2":[159.94699999999997,171.91199999999995],"end":[155.12899999999996,173.70999999999995]}]}]},{"tag":"LineTo","args":[{"point":[155.435,173.611]}]}]},{"start":[497.664,770.688],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[487.908,774.264],"c2":[480.01599999999996,780.983],"end":[475.033,789.596]}]}]},{"tag":"LineTo","args":[{"point":[474.923,789.802]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[470.87,796.671],"c2":[470.187,799.743],"end":[470.187,810.666]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[470.187,821.589],"c2":[470.87,824.6610000000001],"end":[474.923,831.5300000000001]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[477.526,835.9250000000001],"c2":[482.176,841.5140000000001],"end":[485.291,843.8610000000001]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[498.219,853.7170000000001],"c2":[489.984,853.3330000000001],"end":[682.582,853.3330000000001]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[881.622,853.3330000000001],"c2":[869.718,854.1010000000001],"end":[883.2429999999999,840.5760000000001]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[890.9739999999999,832.9570000000001],"c2":[895.7639999999999,822.3710000000001],"end":[895.7639999999999,810.6670000000001]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[895.7639999999999,798.9630000000002],"c2":[890.9739999999999,788.3770000000002],"end":[883.2479999999999,780.7630000000001]}]}]},{"tag":"LineTo","args":[{"point":[883.2429999999999,780.7580000000002]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[869.718,767.2330000000002],"c2":[881.7499999999999,768.0010000000002],"end":[681.942,768.1290000000001]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[532.225,768.2140000000002],"c2":[503.254,768.6410000000001],"end":[497.664,770.688]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]},{"tag":"Text","args":["\n"]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"tag","codePoint":61443},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[16]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":16,"height":16}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[16]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[1,7.775],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[1,2.75]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[1,1.784],"c2":[1.784,1],"end":[2.75,1]}]}]},{"tag":"LineTo","args":[{"point":[7.775,1]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[8.239,1],"c2":[8.685,1.184],"end":[9.013,1.513]}]}]},{"tag":"LineTo","args":[{"point":[15.263,7.763]}]},{"tag":"EllipticArcTo","args":[{"rx":1.75,"ry":1.75,"phi":0,"fA":false,"fS":true,"end":[15.263,10.237]}]},{"tag":"LineTo","args":[{"point":[10.237,15.263]}]},{"tag":"EllipticArcTo","args":[{"rx":1.75,"ry":1.75,"phi":0,"fA":false,"fS":true,"end":[7.763,15.263]}]},{"tag":"LineTo","args":[{"point":[1.513,9.013]}]},{"tag":"EllipticArcTo","args":[{"rx":1.752,"ry":1.752,"phi":0,"fA":false,"fS":true,"end":[1,7.775]}]}]},{"start":[2.5,7.775],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[2.5,7.841],"c2":[2.526,7.905],"end":[2.573,7.952]}]}]},{"tag":"LineTo","args":[{"point":[8.823,14.202]}]},{"tag":"EllipticArcTo","args":[{"rx":0.25,"ry":0.25,"phi":0,"fA":false,"fS":false,"end":[9.177,14.202]}]},{"tag":"LineTo","args":[{"point":[14.202,9.177]}]},{"tag":"EllipticArcTo","args":[{"rx":0.25,"ry":0.25,"phi":0,"fA":false,"fS":false,"end":[14.202,8.823]}]},{"tag":"LineTo","args":[{"point":[7.952,2.5730000000000004]}]},{"tag":"EllipticArcTo","args":[{"rx":0.25,"ry":0.25,"phi":0,"fA":false,"fS":false,"end":[7.775,2.5000000000000004]}]},{"tag":"LineTo","args":[{"point":[2.75,2.5000000000000004]}]},{"tag":"EllipticArcTo","args":[{"rx":0.25,"ry":0.25,"phi":0,"fA":false,"fS":false,"end":[2.5,2.7500000000000004]}]},{"tag":"LineTo","args":[{"point":[2.5,7.775]}]}]},{"start":[6,5],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":true,"fS":true,"end":[6,7]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":true,"end":[6,5]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"scale","codePoint":61444},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-scale-icon lucide-scale"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[12,3],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[12,21]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[19,8],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[22,16]}]},{"tag":"EllipticArcTo","args":[{"rx":5,"ry":5,"phi":0,"fA":false,"fS":true,"end":[16,16]}]},{"tag":"LineTo","args":[{"point":[19,8]}]}]},{"start":[19,8],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[19,7]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[3,7],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[4,7]}]},{"tag":"EllipticArcTo","args":[{"rx":17,"ry":17,"phi":0,"fA":false,"fS":false,"end":[12,5]}]},{"tag":"EllipticArcTo","args":[{"rx":17,"ry":17,"phi":0,"fA":false,"fS":false,"end":[20,7]}]},{"tag":"LineTo","args":[{"point":[21,7]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[5,8],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[8,16]}]},{"tag":"EllipticArcTo","args":[{"rx":5,"ry":5,"phi":0,"fA":false,"fS":true,"end":[2,16]}]},{"tag":"LineTo","args":[{"point":[5,8]}]}]},{"start":[5,8],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[5,7]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[7,21],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[17,21]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"cart","codePoint":61445},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-shopping-cart-icon lucide-shopping-cart"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"circle","attributes":{"cx":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[8]}]}]},"cy":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[21]}]}]},"r":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[1]}]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"circle","attributes":{"cx":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[19]}]}]},"cy":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[21]}]}]},"r":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[1]}]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[2.05,2.05],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[4.05,2.05]}]},{"tag":"LineTo","args":[{"point":[6.71,14.469999999999999]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":false,"end":[8.71,16.049999999999997]}]},{"tag":"LineTo","args":[{"point":[18.490000000000002,16.049999999999997]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":false,"end":[20.44,14.479999999999997]}]},{"tag":"LineTo","args":[{"point":[22.09,7.049999999999997]}]},{"tag":"LineTo","args":[{"point":[5.12,7.049999999999997]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"lightbulb","codePoint":61446},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-lightbulb-icon lucide-lightbulb"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[15,14],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[15.2,13],"c2":[15.7,12.3],"end":[16.5,11.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[17.5,10.6],"c2":[18,9.3],"end":[18,8]}]}]},{"tag":"EllipticArcTo","args":[{"rx":6,"ry":6,"phi":0,"fA":false,"fS":false,"end":[6,8]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[6,9],"c2":[6.2,10.2],"end":[7.5,11.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"CParams","args":[{"c1":[8.2,12.2],"c2":[8.8,13],"end":[9,14]}]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[9,18],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[15,18]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[10,22],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[14,22]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"pin","codePoint":61447},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-pin-icon lucide-pin"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[12,17],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[12,22]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[9,10.76],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":true,"end":[7.89,12.55]}]},{"tag":"LineTo","args":[{"point":[6.109999999999999,13.450000000000001]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":false,"end":[5,15.24]}]},{"tag":"LineTo","args":[{"point":[5,16]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":false,"end":[6,17]}]},{"tag":"LineTo","args":[{"point":[18,17]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":false,"end":[19,16]}]},{"tag":"LineTo","args":[{"point":[19,15.24]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":false,"end":[17.89,13.45]}]},{"tag":"LineTo","args":[{"point":[16.11,12.549999999999999]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":true,"end":[15,10.76]}]},{"tag":"LineTo","args":[{"point":[15,7]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":true,"end":[16,6]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":false,"end":[16,2]}]},{"tag":"LineTo","args":[{"point":[8,2]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":false,"end":[8,6]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":true,"end":[9,7]}]},{"tag":"LineTo","args":[{"point":[9,10.76]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"pin-off","codePoint":61448},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"class":{"tag":"StringValue","args":["lucide lucide-pin-off-icon lucide-pin-off"]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"NoPaint","args":[]}]}]},"height":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"stroke":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]},"stroke-linecap":{"tag":"Value","args":[{"tag":"StrokeLineCap","args":[{"tag":"RoundCap","args":[]}]}]},"stroke-linejoin":{"tag":"Value","args":[{"tag":"StrokeLineJoin","args":[{"tag":"RoundJoin","args":[]}]}]},"stroke-width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[2]}]}]},"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":24,"height":24}]}]},"width":{"tag":"Value","args":[{"tag":"Length","args":[{"tag":"Px","args":[24]}]}]},"xmlns":{"tag":"StringValue","args":["http://www.w3.org/2000/svg"]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[12,17],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[12,22]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[15,9.34],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[15,7]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":true,"end":[16,6]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":false,"end":[16,2]}]},{"tag":"LineTo","args":[{"point":[7.89,2]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[2,2],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[22,22]}]}]}]]}]}},"children":[]}]},{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[9,9],"endings":{"tag":"Disconnected","args":[{}]},"cmds":[{"tag":"LineTo","args":[{"point":[9,10.76]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":true,"end":[7.89,12.55]}]},{"tag":"LineTo","args":[{"point":[6.109999999999999,13.450000000000001]}]},{"tag":"EllipticArcTo","args":[{"rx":2,"ry":2,"phi":0,"fA":false,"fS":false,"end":[5,15.24]}]},{"tag":"LineTo","args":[{"point":[5,16]}]},{"tag":"EllipticArcTo","args":[{"rx":1,"ry":1,"phi":0,"fA":false,"fS":false,"end":[6,17]}]},{"tag":"LineTo","args":[{"point":[17,17]}]}]}]]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-information","codePoint":59648},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[513,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[513,928]}]},{"tag":"LineTo","args":[{"point":[513,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[497,904],"end":[488.5,875.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,847],"end":[480,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,773],"end":[496,735]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[513,697],"end":[541,669]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[569,641],"end":[607,624]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,608],"end":[688,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[709,608],"end":[729.5,612]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[750,616],"end":[768,624]}]}]},{"tag":"LineTo","args":[{"point":[768,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,320],"end":[563,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,64]}]},{"tag":"LineTo","args":[{"point":[224,64]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[160,128]}]}]},{"tag":"LineTo","args":[{"point":[160,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[224,928]}]}]},{"tag":"LineTo","args":[{"point":[513,928]}]}]},{"start":[768,288],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[576,256]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]}]},{"start":[812.5,940.5],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,889],"end":[864,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,743],"end":[812.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,640],"end":[688,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,640],"end":[563.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,743],"end":[512,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,889],"end":[563.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,992],"end":[688,992]}]}]},{"tag":"LineTo","args":[{"point":[688,992]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,992],"end":[812.5,940.5]}]}]}]},{"start":[704,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[704,864]}]},{"tag":"LineTo","args":[{"point":[736,864]}]},{"tag":"LineTo","args":[{"point":[736,896]}]},{"tag":"LineTo","args":[{"point":[640,896]}]},{"tag":"LineTo","args":[{"point":[640,864]}]},{"tag":"LineTo","args":[{"point":[672,864]}]},{"tag":"LineTo","args":[{"point":[672,832]}]},{"tag":"LineTo","args":[{"point":[640,832]}]},{"tag":"LineTo","args":[{"point":[640,800]}]},{"tag":"LineTo","args":[{"point":[704,800]}]}]},{"start":[704,736],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[704,768]}]},{"tag":"LineTo","args":[{"point":[672,768]}]},{"tag":"LineTo","args":[{"point":[672,736]}]},{"tag":"LineTo","args":[{"point":[704,736]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-information-outline","codePoint":59649},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[552,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[224,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[160,864]}]}]},{"tag":"LineTo","args":[{"point":[160,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[224,64]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]},{"tag":"LineTo","args":[{"point":[768,659]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[811,681],"end":[837.5,723]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,765],"end":[864,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,889],"end":[812.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,992],"end":[688,992]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[647,992],"end":[611.5,974.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,957],"end":[552,928]}]}]},{"tag":"LineTo","args":[{"point":[552,928]}]},{"tag":"LineTo","args":[{"point":[552,928]}]}]},{"start":[531,896],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[531,896]}]},{"tag":"LineTo","args":[{"point":[531,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[522,878],"end":[517,858]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,838],"end":[512,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,743],"end":[563.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,640],"end":[688,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[700,640],"end":[712.5,641.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[725,643],"end":[736,647]}]}]},{"tag":"LineTo","args":[{"point":[736,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[581,320],"end":[562.5,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,96]}]},{"tag":"LineTo","args":[{"point":[224,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,96],"end":[201.5,105.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,115],"end":[192,128]}]}]},{"tag":"LineTo","args":[{"point":[192,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,877],"end":[201.5,886.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,896],"end":[224,896]}]}]},{"tag":"LineTo","args":[{"point":[531,896]}]}]},{"start":[576,112],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[576,256]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[608,288]}]}]},{"tag":"LineTo","args":[{"point":[726,288]}]},{"tag":"LineTo","args":[{"point":[576,112]}]}]},{"start":[790,918],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,876],"end":[832,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,756],"end":[790,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[748,672],"end":[688,672]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[628,672],"end":[586,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,756],"end":[544,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,876],"end":[586,918]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[628,960],"end":[688,960]}]}]},{"tag":"LineTo","args":[{"point":[688,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[748,960],"end":[790,918]}]}]}]},{"start":[704,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[704,864]}]},{"tag":"LineTo","args":[{"point":[736,864]}]},{"tag":"LineTo","args":[{"point":[736,896]}]},{"tag":"LineTo","args":[{"point":[640,896]}]},{"tag":"LineTo","args":[{"point":[640,864]}]},{"tag":"LineTo","args":[{"point":[672,864]}]},{"tag":"LineTo","args":[{"point":[672,832]}]},{"tag":"LineTo","args":[{"point":[640,832]}]},{"tag":"LineTo","args":[{"point":[640,800]}]},{"tag":"LineTo","args":[{"point":[704,800]}]}]},{"start":[704,736],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[704,768]}]},{"tag":"LineTo","args":[{"point":[672,768]}]},{"tag":"LineTo","args":[{"point":[672,736]}]},{"tag":"LineTo","args":[{"point":[704,736]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-forbidden","codePoint":59650},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[825,705],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[577,953]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[600,971],"end":[628,981.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[656,992],"end":[688,992]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,992],"end":[812.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,889],"end":[864,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,784],"end":[853.5,756]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[843,728],"end":[825,705]}]}]}]},{"start":[802,682],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,930]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[534,907],"end":[523,878]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,849],"end":[512,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,743],"end":[563.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,640],"end":[688,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[721,640],"end":[750,651]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[779,662],"end":[802,682]}]}]}]},{"start":[513,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[513,928]}]},{"tag":"LineTo","args":[{"point":[513,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[497,904],"end":[488.5,875.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,847],"end":[480,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,773],"end":[496,735]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[513,697],"end":[541,669]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[569,641],"end":[607,624]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,608],"end":[688,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[709,608],"end":[729.5,612]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[750,616],"end":[768,624]}]}]},{"tag":"LineTo","args":[{"point":[768,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,320],"end":[563,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,64]}]},{"tag":"LineTo","args":[{"point":[224,64]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[160,128]}]}]},{"tag":"LineTo","args":[{"point":[160,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[224,928]}]}]},{"tag":"LineTo","args":[{"point":[513,928]}]}]},{"start":[768,288],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[576,256]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-forbidden-outline","codePoint":59651},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[598,929],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[617,943],"end":[640,951.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[663,960],"end":[688,960]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[748,960],"end":[790,918]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,876],"end":[832,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,790],"end":[823.5,767.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[815,745],"end":[801,726]}]}]},{"tag":"LineTo","args":[{"point":[598,929]}]}]},{"start":[736,680.5],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[713,672],"end":[688,672]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[628,672],"end":[586,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,756],"end":[544,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,842],"end":[552.5,864.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[561,887],"end":[575,906]}]}]},{"tag":"LineTo","args":[{"point":[778,703]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[759,689],"end":[736,680.5]}]}]}]},{"start":[552,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[224,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[160,864]}]}]},{"tag":"LineTo","args":[{"point":[160,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[224,64]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]},{"tag":"LineTo","args":[{"point":[768,659]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[811,681],"end":[837.5,723]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,765],"end":[864,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,889],"end":[812.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,992],"end":[688,992]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[647,992],"end":[611.5,974.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,957],"end":[552,928]}]}]},{"tag":"LineTo","args":[{"point":[552,928]}]},{"tag":"LineTo","args":[{"point":[552,928]}]}]},{"start":[531,896],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[531,896]}]},{"tag":"LineTo","args":[{"point":[531,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[522,878],"end":[517,858]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,838],"end":[512,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,743],"end":[563.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,640],"end":[688,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[700,640],"end":[712.5,641.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[725,643],"end":[736,647]}]}]},{"tag":"LineTo","args":[{"point":[736,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[581,320],"end":[562.5,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,96]}]},{"tag":"LineTo","args":[{"point":[224,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,96],"end":[201.5,105.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,115],"end":[192,128]}]}]},{"tag":"LineTo","args":[{"point":[192,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,877],"end":[201.5,886.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,896],"end":[224,896]}]}]},{"tag":"LineTo","args":[{"point":[531,896]}]}]},{"start":[576,112],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[576,256]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[608,288]}]}]},{"tag":"LineTo","args":[{"point":[726,288]}]},{"tag":"LineTo","args":[{"point":[576,112]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-remove","codePoint":59652},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[513,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[513,928]}]},{"tag":"LineTo","args":[{"point":[513,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[497,904],"end":[488.5,875.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,847],"end":[480,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,773],"end":[496,735]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[513,697],"end":[541,669]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[569,641],"end":[607,624]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,608],"end":[688,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[709,608],"end":[729.5,612]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[750,616],"end":[768,624]}]}]},{"tag":"LineTo","args":[{"point":[768,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,320],"end":[563,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,64]}]},{"tag":"LineTo","args":[{"point":[224,64]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[160,128]}]}]},{"tag":"LineTo","args":[{"point":[160,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[224,928]}]}]},{"tag":"LineTo","args":[{"point":[513,928]}]}]},{"start":[768,288],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[576,256]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]}]},{"start":[812.5,940.5],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,889],"end":[864,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,743],"end":[812.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,640],"end":[688,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,640],"end":[563.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,743],"end":[512,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,889],"end":[563.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,992],"end":[688,992]}]}]},{"tag":"LineTo","args":[{"point":[688,992]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,992],"end":[812.5,940.5]}]}]}]},{"start":[800,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[800,832]}]},{"tag":"LineTo","args":[{"point":[576,832]}]},{"tag":"LineTo","args":[{"point":[576,800]}]},{"tag":"LineTo","args":[{"point":[800,800]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-remove-outline","codePoint":59653},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[552,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[224,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[160,864]}]}]},{"tag":"LineTo","args":[{"point":[160,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[224,64]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]},{"tag":"LineTo","args":[{"point":[768,659]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[811,681],"end":[837.5,723]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,765],"end":[864,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,889],"end":[812.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,992],"end":[688,992]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[647,992],"end":[611.5,974.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,957],"end":[552,928]}]}]},{"tag":"LineTo","args":[{"point":[552,928]}]},{"tag":"LineTo","args":[{"point":[552,928]}]}]},{"start":[531,896],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[531,896]}]},{"tag":"LineTo","args":[{"point":[531,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[522,878],"end":[517,858]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,838],"end":[512,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,743],"end":[563.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,640],"end":[688,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[700,640],"end":[712.5,641.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[725,643],"end":[736,647]}]}]},{"tag":"LineTo","args":[{"point":[736,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[581,320],"end":[562.5,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,96]}]},{"tag":"LineTo","args":[{"point":[224,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,96],"end":[201.5,105.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,115],"end":[192,128]}]}]},{"tag":"LineTo","args":[{"point":[192,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,877],"end":[201.5,886.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,896],"end":[224,896]}]}]},{"tag":"LineTo","args":[{"point":[531,896]}]}]},{"start":[576,112],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[576,256]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[608,288]}]}]},{"tag":"LineTo","args":[{"point":[726,288]}]},{"tag":"LineTo","args":[{"point":[576,112]}]}]},{"start":[790,918],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,876],"end":[832,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,756],"end":[790,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[748,672],"end":[688,672]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[628,672],"end":[586,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,756],"end":[544,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,876],"end":[586,918]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[628,960],"end":[688,960]}]}]},{"tag":"LineTo","args":[{"point":[688,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[748,960],"end":[790,918]}]}]}]},{"start":[800,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[800,832]}]},{"tag":"LineTo","args":[{"point":[576,832]}]},{"tag":"LineTo","args":[{"point":[576,800]}]},{"tag":"LineTo","args":[{"point":[800,800]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-checked","codePoint":59654},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[513,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[513,928]}]},{"tag":"LineTo","args":[{"point":[513,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[497,904],"end":[488.5,875.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,847],"end":[480,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,773],"end":[496,735]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[513,697],"end":[541,669]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[569,641],"end":[607,624]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,608],"end":[688,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[709,608],"end":[729.5,612]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[750,616],"end":[768,624]}]}]},{"tag":"LineTo","args":[{"point":[768,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,320],"end":[563,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,64]}]},{"tag":"LineTo","args":[{"point":[224,64]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[160,128]}]}]},{"tag":"LineTo","args":[{"point":[160,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[224,928]}]}]},{"tag":"LineTo","args":[{"point":[513,928]}]}]},{"start":[768,288],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[576,256]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]}]},{"start":[688,992],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,992],"end":[563.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,889],"end":[512,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,743],"end":[563.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,640],"end":[688,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,640],"end":[812.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,743],"end":[864,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,889],"end":[812.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,992],"end":[688,992]}]}]}]},{"start":[672,904],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[795,780]}]},{"tag":"LineTo","args":[{"point":[772,757]}]},{"tag":"LineTo","args":[{"point":[672,857]}]},{"tag":"LineTo","args":[{"point":[620,805]}]},{"tag":"LineTo","args":[{"point":[597,828]}]},{"tag":"LineTo","args":[{"point":[672,904]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-checked-outline","codePoint":59655},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[552,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[224,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[160,864]}]}]},{"tag":"LineTo","args":[{"point":[160,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[224,64]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]},{"tag":"LineTo","args":[{"point":[768,659]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[811,681],"end":[837.5,723]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,765],"end":[864,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,889],"end":[812.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,992],"end":[688,992]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[647,992],"end":[611.5,974.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,957],"end":[552,928]}]}]},{"tag":"LineTo","args":[{"point":[552,928]}]},{"tag":"LineTo","args":[{"point":[552,928]}]}]},{"start":[531,896],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[531,896]}]},{"tag":"LineTo","args":[{"point":[531,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[522,878],"end":[517,858]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,838],"end":[512,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,743],"end":[563.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,640],"end":[688,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[700,640],"end":[712.5,641.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[725,643],"end":[736,647]}]}]},{"tag":"LineTo","args":[{"point":[736,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[581,320],"end":[562.5,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,96]}]},{"tag":"LineTo","args":[{"point":[224,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,96],"end":[201.5,105.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,115],"end":[192,128]}]}]},{"tag":"LineTo","args":[{"point":[192,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,877],"end":[201.5,886.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,896],"end":[224,896]}]}]},{"tag":"LineTo","args":[{"point":[531,896]}]}]},{"start":[576,112],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[576,256]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[608,288]}]}]},{"tag":"LineTo","args":[{"point":[726,288]}]},{"tag":"LineTo","args":[{"point":[576,112]}]}]},{"start":[790,918],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,876],"end":[832,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,756],"end":[790,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[748,672],"end":[688,672]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[628,672],"end":[586,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,756],"end":[544,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,876],"end":[586,918]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[628,960],"end":[688,960]}]}]},{"tag":"LineTo","args":[{"point":[688,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[748,960],"end":[790,918]}]}]}]},{"start":[672,904],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[795,780]}]},{"tag":"LineTo","args":[{"point":[772,757]}]},{"tag":"LineTo","args":[{"point":[672,857]}]},{"tag":"LineTo","args":[{"point":[620,805]}]},{"tag":"LineTo","args":[{"point":[597,828]}]},{"tag":"LineTo","args":[{"point":[672,904]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-cancel","codePoint":59656},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[756,907],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[779,884]}]},{"tag":"LineTo","args":[{"point":[711,816]}]},{"tag":"LineTo","args":[{"point":[779,748]}]},{"tag":"LineTo","args":[{"point":[756,725]}]},{"tag":"LineTo","args":[{"point":[688,793]}]},{"tag":"LineTo","args":[{"point":[620,725]}]},{"tag":"LineTo","args":[{"point":[597,748]}]},{"tag":"LineTo","args":[{"point":[665,816]}]},{"tag":"LineTo","args":[{"point":[597,884]}]},{"tag":"LineTo","args":[{"point":[620,907]}]},{"tag":"LineTo","args":[{"point":[688,839]}]},{"tag":"LineTo","args":[{"point":[756,907]}]}]},{"start":[513,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[513,928]}]},{"tag":"LineTo","args":[{"point":[513,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[497,904],"end":[488.5,875.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,847],"end":[480,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,773],"end":[496,735]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[513,697],"end":[541,669]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[569,641],"end":[607,624]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,608],"end":[688,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[709,608],"end":[729.5,612]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[750,616],"end":[768,624]}]}]},{"tag":"LineTo","args":[{"point":[768,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,320],"end":[563,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,64]}]},{"tag":"LineTo","args":[{"point":[224,64]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[160,128]}]}]},{"tag":"LineTo","args":[{"point":[160,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[224,928]}]}]},{"tag":"LineTo","args":[{"point":[513,928]}]}]},{"start":[768,288],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[576,256]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]}]},{"start":[688,992],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,992],"end":[563.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,889],"end":[512,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,743],"end":[563.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,640],"end":[688,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,640],"end":[812.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,743],"end":[864,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,889],"end":[812.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,992],"end":[688,992]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-cancel-outline","codePoint":59657},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[756,907],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[779,884]}]},{"tag":"LineTo","args":[{"point":[711,816]}]},{"tag":"LineTo","args":[{"point":[779,748]}]},{"tag":"LineTo","args":[{"point":[756,725]}]},{"tag":"LineTo","args":[{"point":[688,793]}]},{"tag":"LineTo","args":[{"point":[620,725]}]},{"tag":"LineTo","args":[{"point":[597,748]}]},{"tag":"LineTo","args":[{"point":[665,816]}]},{"tag":"LineTo","args":[{"point":[597,884]}]},{"tag":"LineTo","args":[{"point":[620,907]}]},{"tag":"LineTo","args":[{"point":[688,839]}]},{"tag":"LineTo","args":[{"point":[756,907]}]}]},{"start":[552,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[224,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[160,864]}]}]},{"tag":"LineTo","args":[{"point":[160,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[224,64]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]},{"tag":"LineTo","args":[{"point":[768,659]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[811,681],"end":[837.5,723]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,765],"end":[864,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,889],"end":[812.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,992],"end":[688,992]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[647,992],"end":[611.5,974.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,957],"end":[552,928]}]}]},{"tag":"LineTo","args":[{"point":[552,928]}]},{"tag":"LineTo","args":[{"point":[552,928]}]}]},{"start":[531,896],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[531,896]}]},{"tag":"LineTo","args":[{"point":[531,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[522,878],"end":[517,858]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,838],"end":[512,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,743],"end":[563.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,640],"end":[688,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[700,640],"end":[712.5,641.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[725,643],"end":[736,647]}]}]},{"tag":"LineTo","args":[{"point":[736,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[581,320],"end":[562.5,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,96]}]},{"tag":"LineTo","args":[{"point":[224,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,96],"end":[201.5,105.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,115],"end":[192,128]}]}]},{"tag":"LineTo","args":[{"point":[192,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,877],"end":[201.5,886.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,896],"end":[224,896]}]}]},{"tag":"LineTo","args":[{"point":[531,896]}]}]},{"start":[576,112],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[576,256]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[608,288]}]}]},{"tag":"LineTo","args":[{"point":[726,288]}]},{"tag":"LineTo","args":[{"point":[576,112]}]}]},{"start":[790,918],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,876],"end":[832,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,756],"end":[790,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[748,672],"end":[688,672]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[628,672],"end":[586,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,756],"end":[544,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,876],"end":[586,918]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[628,960],"end":[688,960]}]}]},{"tag":"LineTo","args":[{"point":[688,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[748,960],"end":[790,918]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-error","codePoint":59658},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[448,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[656,576]}]},{"tag":"LineTo","args":[{"point":[768,766]}]},{"tag":"LineTo","args":[{"point":[768,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,320],"end":[563,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,64]}]},{"tag":"LineTo","args":[{"point":[224,64]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[160,128]}]}]},{"tag":"LineTo","args":[{"point":[160,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[224,928]}]}]},{"tag":"LineTo","args":[{"point":[448,928]}]}]},{"start":[768,288],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[576,256]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]}]},{"start":[448,992],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[864,992]}]},{"tag":"LineTo","args":[{"point":[656,640]}]},{"tag":"LineTo","args":[{"point":[448,992]}]}]},{"start":[672,768],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[672,864]}]},{"tag":"LineTo","args":[{"point":[640,864]}]},{"tag":"LineTo","args":[{"point":[640,768]}]},{"tag":"LineTo","args":[{"point":[672,768]}]}]},{"start":[672,896],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[672,928]}]},{"tag":"LineTo","args":[{"point":[640,928]}]},{"tag":"LineTo","args":[{"point":[640,896]}]},{"tag":"LineTo","args":[{"point":[672,896]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-error-outline","codePoint":59659},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[768,830],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[864,992]}]},{"tag":"LineTo","args":[{"point":[448,992]}]},{"tag":"LineTo","args":[{"point":[486,928]}]},{"tag":"LineTo","args":[{"point":[224,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[160,864]}]}]},{"tag":"LineTo","args":[{"point":[160,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[224,64]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]},{"tag":"LineTo","args":[{"point":[768,830]}]}]},{"start":[505,896],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[656,640]}]},{"tag":"LineTo","args":[{"point":[736,775]}]},{"tag":"LineTo","args":[{"point":[736,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[581,320],"end":[562.5,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,96]}]},{"tag":"LineTo","args":[{"point":[224,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,96],"end":[201.5,105.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,115],"end":[192,128]}]}]},{"tag":"LineTo","args":[{"point":[192,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,877],"end":[201.5,886.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,896],"end":[224,896]}]}]},{"tag":"LineTo","args":[{"point":[505,896]}]}]},{"start":[576,112],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[576,256]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[608,288]}]}]},{"tag":"LineTo","args":[{"point":[726,288]}]},{"tag":"LineTo","args":[{"point":[576,112]}]}]},{"start":[504,960],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[808,960]}]},{"tag":"LineTo","args":[{"point":[656,704]}]},{"tag":"LineTo","args":[{"point":[504,960]}]}]},{"start":[672,768],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[672,864]}]},{"tag":"LineTo","args":[{"point":[640,864]}]},{"tag":"LineTo","args":[{"point":[640,768]}]},{"tag":"LineTo","args":[{"point":[672,768]}]}]},{"start":[672,896],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[672,928]}]},{"tag":"LineTo","args":[{"point":[640,928]}]},{"tag":"LineTo","args":[{"point":[640,896]}]},{"tag":"LineTo","args":[{"point":[672,896]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-locked","codePoint":59660},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[768,320],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,584]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[757,580],"end":[745,578]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[733,576],"end":[720,576]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[660,576],"end":[618,618.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,661],"end":[576,720]}]}]},{"tag":"LineTo","args":[{"point":[576,739]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[562,744],"end":[553,756]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,768],"end":[544,784]}]}]},{"tag":"LineTo","args":[{"point":[544,928]}]},{"tag":"LineTo","args":[{"point":[224,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[160,864]}]}]},{"tag":"LineTo","args":[{"point":[160,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[224,64]}]}]},{"tag":"LineTo","args":[{"point":[544,64]}]},{"tag":"LineTo","args":[{"point":[544,256]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[563,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,320],"end":[608,320]}]}]},{"tag":"LineTo","args":[{"point":[768,320]}]}]},{"start":[576,64],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,288]}]},{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[576,256]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]}]},{"start":[608,720],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,674],"end":[641,641]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[674,608],"end":[720,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[766,608],"end":[799,641]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,674],"end":[832,720]}]}]},{"tag":"LineTo","args":[{"point":[832,768]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[845,768],"end":[854.5,777.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,787],"end":[864,800]}]}]},{"tag":"LineTo","args":[{"point":[864,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,973],"end":[854.5,982.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[845,992],"end":[832,992]}]}]},{"tag":"LineTo","args":[{"point":[608,992]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,992],"end":[585.5,982.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,973],"end":[576,960]}]}]},{"tag":"LineTo","args":[{"point":[576,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,787],"end":[585.5,777.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,768],"end":[608,768]}]}]},{"tag":"LineTo","args":[{"point":[608,720]}]}]},{"start":[640,768],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[800,768]}]},{"tag":"LineTo","args":[{"point":[800,720]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[800,687],"end":[776.5,663.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[753,640],"end":[720,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[687,640],"end":[663.5,663.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,687],"end":[640,720]}]}]},{"tag":"LineTo","args":[{"point":[640,768]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-locked-outline","codePoint":59661},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[576,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[224,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[160,864]}]}]},{"tag":"LineTo","args":[{"point":[160,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[224,64]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]},{"tag":"LineTo","args":[{"point":[768,619]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[796,632],"end":[814,659.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,687],"end":[832,720]}]}]},{"tag":"LineTo","args":[{"point":[832,768]}]},{"tag":"LineTo","args":[{"point":[832,768]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[845,768],"end":[854.5,777.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,787],"end":[864,800]}]}]},{"tag":"LineTo","args":[{"point":[864,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,973],"end":[854.5,982.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[845,992],"end":[832,992]}]}]},{"tag":"LineTo","args":[{"point":[608,992]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,992],"end":[585.5,982.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,973],"end":[576,960]}]}]},{"tag":"LineTo","args":[{"point":[576,928]}]}]},{"start":[576,896],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[576,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,787],"end":[585.5,777.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,768],"end":[608,768]}]}]},{"tag":"LineTo","args":[{"point":[608,768]}]},{"tag":"LineTo","args":[{"point":[608,720]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,674],"end":[641,641]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[674,608],"end":[720,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[724,608],"end":[728,608.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[732,609],"end":[736,609]}]}]},{"tag":"LineTo","args":[{"point":[736,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[581,320],"end":[562.5,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,96]}]},{"tag":"LineTo","args":[{"point":[224,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,96],"end":[201.5,105.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,115],"end":[192,128]}]}]},{"tag":"LineTo","args":[{"point":[192,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,877],"end":[201.5,886.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,896],"end":[224,896]}]}]},{"tag":"LineTo","args":[{"point":[576,896]}]}]},{"start":[800,768],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[800,720]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[800,687],"end":[776.5,663.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[753,640],"end":[720,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[687,640],"end":[663.5,663.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,687],"end":[640,720]}]}]},{"tag":"LineTo","args":[{"point":[640,768]}]},{"tag":"LineTo","args":[{"point":[800,768]}]}]},{"start":[576,112],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[576,256]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[608,288]}]}]},{"tag":"LineTo","args":[{"point":[726,288]}]},{"tag":"LineTo","args":[{"point":[576,112]}]}]},{"start":[624,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[617,800],"end":[612.5,804.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,809],"end":[608,816]}]}]},{"tag":"LineTo","args":[{"point":[608,944]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,951],"end":[613,955.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,960],"end":[624,960]}]}]},{"tag":"LineTo","args":[{"point":[816,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[823,960],"end":[827.5,955.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,951],"end":[832,944]}]}]},{"tag":"LineTo","args":[{"point":[832,816]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,809],"end":[827,804.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[822,800],"end":[816,800]}]}]},{"tag":"LineTo","args":[{"point":[624,800]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-unlocked","codePoint":59662},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[768,320],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,552]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[757,548],"end":[745,546]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[733,544],"end":[720,544]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[660,544],"end":[618,586]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,628],"end":[576,688]}]}]},{"tag":"LineTo","args":[{"point":[576,744]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[562,753],"end":[553,767.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,782],"end":[544,800]}]}]},{"tag":"LineTo","args":[{"point":[544,928]}]},{"tag":"LineTo","args":[{"point":[224,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[160,864]}]}]},{"tag":"LineTo","args":[{"point":[160,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[224,64]}]}]},{"tag":"LineTo","args":[{"point":[544,64]}]},{"tag":"LineTo","args":[{"point":[544,256]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[563,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,320],"end":[608,320]}]}]},{"tag":"LineTo","args":[{"point":[768,320]}]}]},{"start":[576,64],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,288]}]},{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[576,256]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]}]},{"start":[816,768],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[640,768]}]},{"tag":"LineTo","args":[{"point":[640,688]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,655],"end":[663.5,631.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[687,608],"end":[720,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[753,608],"end":[776.5,631.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[800,655],"end":[800,688]}]}]},{"tag":"LineTo","args":[{"point":[800,704]}]},{"tag":"LineTo","args":[{"point":[832,704]}]},{"tag":"LineTo","args":[{"point":[832,688]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,642],"end":[799,609]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[766,576],"end":[720,576]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[674,576],"end":[641,608.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,641],"end":[608,688]}]}]},{"tag":"LineTo","args":[{"point":[608,768]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,768],"end":[585.5,777.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,787],"end":[576,800]}]}]},{"tag":"LineTo","args":[{"point":[576,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,973],"end":[585.5,982.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,992],"end":[608,992]}]}]},{"tag":"LineTo","args":[{"point":[832,992]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[845,992],"end":[854.5,982.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,973],"end":[864,960]}]}]},{"tag":"LineTo","args":[{"point":[864,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,787],"end":[854.5,777.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[845,768],"end":[832,768]}]}]},{"tag":"LineTo","args":[{"point":[816,768]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-unlocked-outline","codePoint":59663},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[768,587],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,587]}]},{"tag":"LineTo","args":[{"point":[768,587]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[796,600],"end":[814,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,655],"end":[832,688]}]}]},{"tag":"LineTo","args":[{"point":[832,704]}]},{"tag":"LineTo","args":[{"point":[800,704]}]},{"tag":"LineTo","args":[{"point":[800,688]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[800,655],"end":[776.5,631.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[753,608],"end":[720,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[687,608],"end":[663.5,631.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,655],"end":[640,688]}]}]},{"tag":"LineTo","args":[{"point":[640,768]}]},{"tag":"LineTo","args":[{"point":[832,768]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[845,768],"end":[854.5,777.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,787],"end":[864,800]}]}]},{"tag":"LineTo","args":[{"point":[864,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,973],"end":[854.5,982.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[845,992],"end":[832,992]}]}]},{"tag":"LineTo","args":[{"point":[608,992]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,992],"end":[585.5,982.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,973],"end":[576,960]}]}]},{"tag":"LineTo","args":[{"point":[576,928]}]},{"tag":"LineTo","args":[{"point":[224,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[160,864]}]}]},{"tag":"LineTo","args":[{"point":[160,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[224,64]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]},{"tag":"LineTo","args":[{"point":[768,587]}]}]},{"start":[576,896],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[576,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,787],"end":[585.5,777.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,768],"end":[608,768]}]}]},{"tag":"LineTo","args":[{"point":[608,688]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,642],"end":[641,609]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[674,576],"end":[720,576]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[724,576],"end":[728,576.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[732,577],"end":[736,577]}]}]},{"tag":"LineTo","args":[{"point":[736,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[581,320],"end":[562.5,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,96]}]},{"tag":"LineTo","args":[{"point":[224,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,96],"end":[201.5,105.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,115],"end":[192,128]}]}]},{"tag":"LineTo","args":[{"point":[192,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,877],"end":[201.5,886.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,896],"end":[224,896]}]}]},{"tag":"LineTo","args":[{"point":[576,896]}]}]},{"start":[576,112],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[576,256]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[608,288]}]}]},{"tag":"LineTo","args":[{"point":[726,288]}]},{"tag":"LineTo","args":[{"point":[576,112]}]}]},{"start":[624,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[617,800],"end":[612.5,804.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,809],"end":[608,816]}]}]},{"tag":"LineTo","args":[{"point":[608,944]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,951],"end":[613,955.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,960],"end":[624,960]}]}]},{"tag":"LineTo","args":[{"point":[816,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[823,960],"end":[827.5,955.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,951],"end":[832,944]}]}]},{"tag":"LineTo","args":[{"point":[832,816]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,809],"end":[827,804.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[822,800],"end":[816,800]}]}]},{"tag":"LineTo","args":[{"point":[624,800]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-search","codePoint":59664},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[725,876],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[748,853]}]},{"tag":"LineTo","args":[{"point":[577,682]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[591,663],"end":[599.5,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,617],"end":[608,592]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,532],"end":[566,490]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[524,448],"end":[464,448]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[404,448],"end":[362,490]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,532],"end":[320,592]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,652],"end":[362,694]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[404,736],"end":[464,736]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[490,736],"end":[512.5,727.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[535,719],"end":[554,705]}]}]},{"tag":"LineTo","args":[{"point":[725,876]}]}]},{"start":[608,96],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,315],"end":[627,333.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[646,352],"end":[672,352]}]}]},{"tag":"LineTo","args":[{"point":[832,352]}]},{"tag":"LineTo","args":[{"point":[832,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,923],"end":[813.5,941.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[795,960],"end":[768,960]}]}]},{"tag":"LineTo","args":[{"point":[288,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[261,960],"end":[242.5,941]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,922],"end":[224,896]}]}]},{"tag":"LineTo","args":[{"point":[224,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,134],"end":[243,115]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[262,96],"end":[288,96]}]}]},{"tag":"LineTo","args":[{"point":[608,96]}]}]},{"start":[832,320],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[672,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[659,320],"end":[649.5,310.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,301],"end":[640,288]}]}]},{"tag":"LineTo","args":[{"point":[640,96]}]},{"tag":"LineTo","args":[{"point":[832,320]}]}]},{"start":[464,704],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[418,704],"end":[385,671]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[352,638],"end":[352,592]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[352,546],"end":[385,513]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[418,480],"end":[464,480]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[510,480],"end":[543,513]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,546],"end":[576,592]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,638],"end":[543,671]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[510,704],"end":[464,704]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-search-outline","codePoint":59665},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[725,876],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[748,853]}]},{"tag":"LineTo","args":[{"point":[577,682]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[591,663],"end":[599.5,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,617],"end":[608,592]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,532],"end":[566,490]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[524,448],"end":[464,448]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[404,448],"end":[362,490]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,532],"end":[320,592]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,652],"end":[362,694]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[404,736],"end":[464,736]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[490,736],"end":[512.5,727.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[535,719],"end":[554,705]}]}]},{"tag":"LineTo","args":[{"point":[725,876]}]}]},{"start":[624,96],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[288,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[262,96],"end":[243,115]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,134],"end":[224,160]}]}]},{"tag":"LineTo","args":[{"point":[224,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,922],"end":[242.5,941]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[261,960],"end":[288,960]}]}]},{"tag":"LineTo","args":[{"point":[768,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[795,960],"end":[813.5,941.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,923],"end":[832,896]}]}]},{"tag":"LineTo","args":[{"point":[832,320]}]},{"tag":"LineTo","args":[{"point":[640,96]}]},{"tag":"LineTo","args":[{"point":[624,96]}]}]},{"start":[608,128],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,315],"end":[626.5,333.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,352],"end":[672,352]}]}]},{"tag":"LineTo","args":[{"point":[800,352]}]},{"tag":"LineTo","args":[{"point":[800,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[800,909],"end":[790.5,918.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[781,928],"end":[768,928]}]}]},{"tag":"LineTo","args":[{"point":[288,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,928],"end":[265.5,918.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,909],"end":[256,896]}]}]},{"tag":"LineTo","args":[{"point":[256,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,147],"end":[265.5,137.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,128],"end":[288,128]}]}]},{"tag":"LineTo","args":[{"point":[608,128]}]}]},{"start":[640,144],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[790,320]}]},{"tag":"LineTo","args":[{"point":[672,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[659,320],"end":[649.5,310.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,301],"end":[640,288]}]}]},{"tag":"LineTo","args":[{"point":[640,144]}]}]},{"start":[464,704],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[418,704],"end":[385,671]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[352,638],"end":[352,592]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[352,546],"end":[385,513]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[418,480],"end":[464,480]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[510,480],"end":[543,513]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,546],"end":[576,592]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,638],"end":[543,671]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[510,704],"end":[464,704]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-code","codePoint":59666},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[608,96],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[288,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[262,96],"end":[243,115]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,134],"end":[224,160]}]}]},{"tag":"LineTo","args":[{"point":[224,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,922],"end":[242.5,941]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[261,960],"end":[288,960]}]}]},{"tag":"LineTo","args":[{"point":[768,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[795,960],"end":[813.5,941.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,923],"end":[832,896]}]}]},{"tag":"LineTo","args":[{"point":[832,352]}]},{"tag":"LineTo","args":[{"point":[672,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[646,352],"end":[627,333.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,315],"end":[608,288]}]}]},{"tag":"LineTo","args":[{"point":[608,96]}]}]},{"start":[832,320],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[672,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[659,320],"end":[649.5,310.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,301],"end":[640,288]}]}]},{"tag":"LineTo","args":[{"point":[640,96]}]},{"tag":"LineTo","args":[{"point":[832,320]}]}]},{"start":[288,704],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[416,576]}]},{"tag":"LineTo","args":[{"point":[438,598]}]},{"tag":"LineTo","args":[{"point":[333,704]}]},{"tag":"LineTo","args":[{"point":[438,810]}]},{"tag":"LineTo","args":[{"point":[416,832]}]},{"tag":"LineTo","args":[{"point":[288,704]}]}]},{"start":[618,810],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[723,704]}]},{"tag":"LineTo","args":[{"point":[618,598]}]},{"tag":"LineTo","args":[{"point":[640,576]}]},{"tag":"LineTo","args":[{"point":[768,704]}]},{"tag":"LineTo","args":[{"point":[640,832]}]},{"tag":"LineTo","args":[{"point":[618,810]}]}]},{"start":[576,576],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,832]}]},{"tag":"LineTo","args":[{"point":[480,832]}]},{"tag":"LineTo","args":[{"point":[544,576]}]},{"tag":"LineTo","args":[{"point":[576,576]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-code-outline","codePoint":59667},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[624,96],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[288,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[262,96],"end":[243,115]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,134],"end":[224,160]}]}]},{"tag":"LineTo","args":[{"point":[224,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,922],"end":[242.5,941]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[261,960],"end":[288,960]}]}]},{"tag":"LineTo","args":[{"point":[768,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[795,960],"end":[813.5,941.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,923],"end":[832,896]}]}]},{"tag":"LineTo","args":[{"point":[832,320]}]},{"tag":"LineTo","args":[{"point":[640,96]}]},{"tag":"LineTo","args":[{"point":[624,96]}]}]},{"start":[608,128],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,315],"end":[626.5,333.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,352],"end":[672,352]}]}]},{"tag":"LineTo","args":[{"point":[800,352]}]},{"tag":"LineTo","args":[{"point":[800,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[800,909],"end":[790.5,918.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[781,928],"end":[768,928]}]}]},{"tag":"LineTo","args":[{"point":[288,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,928],"end":[265.5,918.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,909],"end":[256,896]}]}]},{"tag":"LineTo","args":[{"point":[256,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,147],"end":[265.5,137.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,128],"end":[288,128]}]}]},{"tag":"LineTo","args":[{"point":[608,128]}]}]},{"start":[640,144],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[790,320]}]},{"tag":"LineTo","args":[{"point":[672,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[659,320],"end":[649.5,310.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,301],"end":[640,288]}]}]},{"tag":"LineTo","args":[{"point":[640,144]}]}]},{"start":[576,576],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,832]}]},{"tag":"LineTo","args":[{"point":[480,832]}]},{"tag":"LineTo","args":[{"point":[544,576]}]},{"tag":"LineTo","args":[{"point":[576,576]}]}]},{"start":[438,778],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[365,704]}]},{"tag":"LineTo","args":[{"point":[438,630]}]},{"tag":"LineTo","args":[{"point":[416,608]}]},{"tag":"LineTo","args":[{"point":[320,704]}]},{"tag":"LineTo","args":[{"point":[416,800]}]},{"tag":"LineTo","args":[{"point":[438,778]}]}]},{"start":[618,778],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[691,704]}]},{"tag":"LineTo","args":[{"point":[618,630]}]},{"tag":"LineTo","args":[{"point":[640,608]}]},{"tag":"LineTo","args":[{"point":[736,704]}]},{"tag":"LineTo","args":[{"point":[640,800]}]},{"tag":"LineTo","args":[{"point":[618,778]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-text","codePoint":59668},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[608,96],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[288,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[262,96],"end":[243,115]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,134],"end":[224,160]}]}]},{"tag":"LineTo","args":[{"point":[224,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,922],"end":[242.5,941]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[261,960],"end":[288,960]}]}]},{"tag":"LineTo","args":[{"point":[768,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[795,960],"end":[813.5,941.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,923],"end":[832,896]}]}]},{"tag":"LineTo","args":[{"point":[832,352]}]},{"tag":"LineTo","args":[{"point":[672,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[646,352],"end":[627,333.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,315],"end":[608,288]}]}]},{"tag":"LineTo","args":[{"point":[608,96]}]}]},{"start":[480,192],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[480,256]}]},{"tag":"LineTo","args":[{"point":[448,256]}]},{"tag":"LineTo","args":[{"point":[448,224]}]},{"tag":"LineTo","args":[{"point":[416,224]}]},{"tag":"LineTo","args":[{"point":[416,352]}]},{"tag":"LineTo","args":[{"point":[384,352]}]},{"tag":"LineTo","args":[{"point":[384,224]}]},{"tag":"LineTo","args":[{"point":[352,224]}]},{"tag":"LineTo","args":[{"point":[352,256]}]},{"tag":"LineTo","args":[{"point":[320,256]}]},{"tag":"LineTo","args":[{"point":[320,192]}]},{"tag":"LineTo","args":[{"point":[480,192]}]}]},{"start":[832,320],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[672,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[659,320],"end":[649.5,310.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,301],"end":[640,288]}]}]},{"tag":"LineTo","args":[{"point":[640,96]}]},{"tag":"LineTo","args":[{"point":[832,320]}]}]},{"start":[736,512],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,544]}]},{"tag":"LineTo","args":[{"point":[320,544]}]},{"tag":"LineTo","args":[{"point":[320,512]}]},{"tag":"LineTo","args":[{"point":[736,512]}]}]},{"start":[736,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,448]}]},{"tag":"LineTo","args":[{"point":[320,448]}]},{"tag":"LineTo","args":[{"point":[320,416]}]},{"tag":"LineTo","args":[{"point":[736,416]}]}]},{"start":[736,608],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,640]}]},{"tag":"LineTo","args":[{"point":[320,640]}]},{"tag":"LineTo","args":[{"point":[320,608]}]},{"tag":"LineTo","args":[{"point":[736,608]}]}]},{"start":[736,704],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,736]}]},{"tag":"LineTo","args":[{"point":[320,736]}]},{"tag":"LineTo","args":[{"point":[320,704]}]},{"tag":"LineTo","args":[{"point":[736,704]}]}]},{"start":[736,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,832]}]},{"tag":"LineTo","args":[{"point":[320,832]}]},{"tag":"LineTo","args":[{"point":[320,800]}]},{"tag":"LineTo","args":[{"point":[736,800]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-text-outline","codePoint":59669},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[624,96],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[288,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[262,96],"end":[243,115]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,134],"end":[224,160]}]}]},{"tag":"LineTo","args":[{"point":[224,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,922],"end":[242.5,941]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[261,960],"end":[288,960]}]}]},{"tag":"LineTo","args":[{"point":[768,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[795,960],"end":[813.5,941.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,923],"end":[832,896]}]}]},{"tag":"LineTo","args":[{"point":[832,320]}]},{"tag":"LineTo","args":[{"point":[640,96]}]},{"tag":"LineTo","args":[{"point":[624,96]}]}]},{"start":[608,128],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,315],"end":[626.5,333.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,352],"end":[672,352]}]}]},{"tag":"LineTo","args":[{"point":[800,352]}]},{"tag":"LineTo","args":[{"point":[800,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[800,909],"end":[790.5,918.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[781,928],"end":[768,928]}]}]},{"tag":"LineTo","args":[{"point":[288,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,928],"end":[265.5,918.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,909],"end":[256,896]}]}]},{"tag":"LineTo","args":[{"point":[256,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,147],"end":[265.5,137.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,128],"end":[288,128]}]}]},{"tag":"LineTo","args":[{"point":[608,128]}]}]},{"start":[640,144],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[790,320]}]},{"tag":"LineTo","args":[{"point":[672,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[659,320],"end":[649.5,310.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,301],"end":[640,288]}]}]},{"tag":"LineTo","args":[{"point":[640,144]}]}]},{"start":[480,192],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[480,256]}]},{"tag":"LineTo","args":[{"point":[448,256]}]},{"tag":"LineTo","args":[{"point":[448,224]}]},{"tag":"LineTo","args":[{"point":[416,224]}]},{"tag":"LineTo","args":[{"point":[416,352]}]},{"tag":"LineTo","args":[{"point":[384,352]}]},{"tag":"LineTo","args":[{"point":[384,224]}]},{"tag":"LineTo","args":[{"point":[352,224]}]},{"tag":"LineTo","args":[{"point":[352,256]}]},{"tag":"LineTo","args":[{"point":[320,256]}]},{"tag":"LineTo","args":[{"point":[320,192]}]},{"tag":"LineTo","args":[{"point":[480,192]}]}]},{"start":[736,512],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,544]}]},{"tag":"LineTo","args":[{"point":[320,544]}]},{"tag":"LineTo","args":[{"point":[320,512]}]},{"tag":"LineTo","args":[{"point":[736,512]}]}]},{"start":[736,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,448]}]},{"tag":"LineTo","args":[{"point":[320,448]}]},{"tag":"LineTo","args":[{"point":[320,416]}]},{"tag":"LineTo","args":[{"point":[736,416]}]}]},{"start":[736,608],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,640]}]},{"tag":"LineTo","args":[{"point":[320,640]}]},{"tag":"LineTo","args":[{"point":[320,608]}]},{"tag":"LineTo","args":[{"point":[736,608]}]}]},{"start":[736,704],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,736]}]},{"tag":"LineTo","args":[{"point":[320,736]}]},{"tag":"LineTo","args":[{"point":[320,704]}]},{"tag":"LineTo","args":[{"point":[736,704]}]}]},{"start":[736,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,832]}]},{"tag":"LineTo","args":[{"point":[320,832]}]},{"tag":"LineTo","args":[{"point":[320,800]}]},{"tag":"LineTo","args":[{"point":[736,800]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"text_format","codePoint":59670},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[592,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[432,491]}]},{"tag":"LineTo","args":[{"point":[512,277]}]},{"tag":"LineTo","args":[{"point":[592,491]}]}]},{"start":[618,567],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[658,661]}]},{"tag":"LineTo","args":[{"point":[746,661]}]},{"tag":"LineTo","args":[{"point":[544,191]}]},{"tag":"LineTo","args":[{"point":[480,191]}]},{"tag":"LineTo","args":[{"point":[278,661]}]},{"tag":"LineTo","args":[{"point":[366,661]}]},{"tag":"LineTo","args":[{"point":[406,567]}]},{"tag":"LineTo","args":[{"point":[618,567]}]}]},{"start":[214,831],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[810,831]}]},{"tag":"LineTo","args":[{"point":[810,747]}]},{"tag":"LineTo","args":[{"point":[214,747]}]},{"tag":"LineTo","args":[{"point":[214,831]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"chat_bubble","codePoint":59671},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[170,107],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,107],"end":[111,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,157],"end":[86,191]}]}]},{"tag":"LineTo","args":[{"point":[86,959]}]},{"tag":"LineTo","args":[{"point":[256,789]}]},{"tag":"LineTo","args":[{"point":[854,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,789],"end":[913,763]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,737],"end":[938,703]}]}]},{"tag":"LineTo","args":[{"point":[938,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,157],"end":[913,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,107],"end":[854,107]}]}]},{"tag":"LineTo","args":[{"point":[170,107]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"movie","codePoint":59672},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[854,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[726,363]}]},{"tag":"LineTo","args":[{"point":[640,191]}]},{"tag":"LineTo","args":[{"point":[554,191]}]},{"tag":"LineTo","args":[{"point":[640,363]}]},{"tag":"LineTo","args":[{"point":[512,363]}]},{"tag":"LineTo","args":[{"point":[426,191]}]},{"tag":"LineTo","args":[{"point":[342,191]}]},{"tag":"LineTo","args":[{"point":[426,363]}]},{"tag":"LineTo","args":[{"point":[298,363]}]},{"tag":"LineTo","args":[{"point":[214,191]}]},{"tag":"LineTo","args":[{"point":[170,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,191],"end":[111,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,243],"end":[86,277]}]}]},{"tag":"LineTo","args":[{"point":[86,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,823],"end":[111,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,875],"end":[170,875]}]}]},{"tag":"LineTo","args":[{"point":[854,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,875],"end":[913,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,823],"end":[938,789]}]}]},{"tag":"LineTo","args":[{"point":[938,191]}]},{"tag":"LineTo","args":[{"point":[768,191]}]},{"tag":"LineTo","args":[{"point":[854,363]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"videocam","codePoint":59673},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[726,319],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,301],"end":[713,289]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[700,277],"end":[682,277]}]}]},{"tag":"LineTo","args":[{"point":[170,277]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[152,277],"end":[140,289]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,301],"end":[128,319]}]}]},{"tag":"LineTo","args":[{"point":[128,747]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,765],"end":[140,777]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[152,789],"end":[170,789]}]}]},{"tag":"LineTo","args":[{"point":[682,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[700,789],"end":[713,777]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,765],"end":[726,747]}]}]},{"tag":"LineTo","args":[{"point":[726,597]}]},{"tag":"LineTo","args":[{"point":[896,767]}]},{"tag":"LineTo","args":[{"point":[896,299]}]},{"tag":"LineTo","args":[{"point":[726,469]}]},{"tag":"LineTo","args":[{"point":[726,319]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-add","codePoint":59674},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[576,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[576,832]}]},{"tag":"LineTo","args":[{"point":[672,832]}]},{"tag":"LineTo","args":[{"point":[672,928]}]},{"tag":"LineTo","args":[{"point":[704,928]}]},{"tag":"LineTo","args":[{"point":[704,832]}]},{"tag":"LineTo","args":[{"point":[800,832]}]},{"tag":"LineTo","args":[{"point":[800,800]}]},{"tag":"LineTo","args":[{"point":[704,800]}]},{"tag":"LineTo","args":[{"point":[704,704]}]},{"tag":"LineTo","args":[{"point":[672,704]}]},{"tag":"LineTo","args":[{"point":[672,800]}]},{"tag":"LineTo","args":[{"point":[576,800]}]}]},{"start":[513,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[513,928]}]},{"tag":"LineTo","args":[{"point":[513,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[497,904],"end":[488.5,875.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,847],"end":[480,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,773],"end":[496,735]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[513,697],"end":[541,669]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[569,641],"end":[607,624]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,608],"end":[688,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[709,608],"end":[729.5,612]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[750,616],"end":[768,624]}]}]},{"tag":"LineTo","args":[{"point":[768,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,320],"end":[563,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,64]}]},{"tag":"LineTo","args":[{"point":[224,64]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[160,128]}]}]},{"tag":"LineTo","args":[{"point":[160,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[224,928]}]}]},{"tag":"LineTo","args":[{"point":[513,928]}]}]},{"start":[768,288],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[576,256]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]}]},{"start":[688,992],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,992],"end":[563.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,889],"end":[512,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,743],"end":[563.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,640],"end":[688,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,640],"end":[812.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,743],"end":[864,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,889],"end":[812.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,992],"end":[688,992]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-add-outline","codePoint":59675},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[576,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[576,832]}]},{"tag":"LineTo","args":[{"point":[672,832]}]},{"tag":"LineTo","args":[{"point":[672,928]}]},{"tag":"LineTo","args":[{"point":[704,928]}]},{"tag":"LineTo","args":[{"point":[704,832]}]},{"tag":"LineTo","args":[{"point":[800,832]}]},{"tag":"LineTo","args":[{"point":[800,800]}]},{"tag":"LineTo","args":[{"point":[704,800]}]},{"tag":"LineTo","args":[{"point":[704,704]}]},{"tag":"LineTo","args":[{"point":[672,704]}]},{"tag":"LineTo","args":[{"point":[672,800]}]},{"tag":"LineTo","args":[{"point":[576,800]}]}]},{"start":[552,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[224,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,928],"end":[178.5,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,890],"end":[160,864]}]}]},{"tag":"LineTo","args":[{"point":[160,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,102],"end":[179,83]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,64],"end":[224,64]}]}]},{"tag":"LineTo","args":[{"point":[576,64]}]},{"tag":"LineTo","args":[{"point":[768,288]}]},{"tag":"LineTo","args":[{"point":[768,659]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[811,681],"end":[837.5,723]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,765],"end":[864,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,889],"end":[812.5,940.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[761,992],"end":[688,992]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[647,992],"end":[611.5,974.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,957],"end":[552,928]}]}]},{"tag":"LineTo","args":[{"point":[552,928]}]},{"tag":"LineTo","args":[{"point":[552,928]}]}]},{"start":[531,896],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[531,896]}]},{"tag":"LineTo","args":[{"point":[531,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[522,878],"end":[517,858]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,838],"end":[512,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,743],"end":[563.5,691.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,640],"end":[688,640]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[700,640],"end":[712.5,641.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[725,643],"end":[736,647]}]}]},{"tag":"LineTo","args":[{"point":[736,320]}]},{"tag":"LineTo","args":[{"point":[608,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[581,320],"end":[562.5,301.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,283],"end":[544,256]}]}]},{"tag":"LineTo","args":[{"point":[544,96]}]},{"tag":"LineTo","args":[{"point":[224,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,96],"end":[201.5,105.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,115],"end":[192,128]}]}]},{"tag":"LineTo","args":[{"point":[192,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,877],"end":[201.5,886.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[211,896],"end":[224,896]}]}]},{"tag":"LineTo","args":[{"point":[531,896]}]}]},{"start":[576,112],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[576,256]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,269],"end":[585.5,278.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,288],"end":[608,288]}]}]},{"tag":"LineTo","args":[{"point":[726,288]}]},{"tag":"LineTo","args":[{"point":[576,112]}]}]},{"start":[790,918],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,876],"end":[832,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,756],"end":[790,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[748,672],"end":[688,672]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[628,672],"end":[586,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,756],"end":[544,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,876],"end":[586,918]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[628,960],"end":[688,960]}]}]},{"tag":"LineTo","args":[{"point":[688,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[748,960],"end":[790,918]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"documents","codePoint":59676},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[736,864],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,987],"end":[717.5,1005.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[699,1024],"end":[672,1024]}]}]},{"tag":"LineTo","args":[{"point":[192,1024]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[165,1024],"end":[146.5,1005]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,986],"end":[128,960]}]}]},{"tag":"LineTo","args":[{"point":[128,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,198],"end":[147,179]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[166,160],"end":[192,160]}]}]},{"tag":"LineTo","args":[{"point":[512,160]}]},{"tag":"LineTo","args":[{"point":[512,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,379],"end":[531,397.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[550,416],"end":[576,416]}]}]},{"tag":"LineTo","args":[{"point":[736,416]}]},{"tag":"LineTo","args":[{"point":[736,864]}]},{"tag":"LineTo","args":[{"point":[768,864]}]},{"tag":"LineTo","args":[{"point":[768,371]}]},{"tag":"LineTo","args":[{"point":[560,128]}]},{"tag":"LineTo","args":[{"point":[320,128]}]},{"tag":"LineTo","args":[{"point":[320,64]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,38],"end":[339,19]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[358,0],"end":[384,0]}]}]},{"tag":"LineTo","args":[{"point":[704,0]}]},{"tag":"LineTo","args":[{"point":[704,192]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,219],"end":[723,237.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[742,256],"end":[768,256]}]}]},{"tag":"LineTo","args":[{"point":[928,256]}]},{"tag":"LineTo","args":[{"point":[928,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,827],"end":[909.5,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[891,864],"end":[864,864]}]}]},{"tag":"LineTo","args":[{"point":[736,864]}]}]},{"start":[928,224],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[755,224],"end":[745.5,214.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,205],"end":[736,192]}]}]},{"tag":"LineTo","args":[{"point":[736,0]}]},{"tag":"LineTo","args":[{"point":[928,224]}]}]},{"start":[736,384],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[576,384]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[563,384],"end":[553.5,374.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,365],"end":[544,352]}]}]},{"tag":"LineTo","args":[{"point":[544,160]}]},{"tag":"LineTo","args":[{"point":[736,384]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"documents-outline","codePoint":59677},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[736,384],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[544,160]}]},{"tag":"LineTo","args":[{"point":[352,160]}]},{"tag":"LineTo","args":[{"point":[352,64]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[352,51],"end":[361.5,41.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[371,32],"end":[384,32]}]}]},{"tag":"LineTo","args":[{"point":[704,32]}]},{"tag":"LineTo","args":[{"point":[704,192]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,219],"end":[722.5,237.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[741,256],"end":[768,256]}]}]},{"tag":"LineTo","args":[{"point":[896,256]}]},{"tag":"LineTo","args":[{"point":[896,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,813],"end":[886.5,822.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[877,832],"end":[864,832]}]}]},{"tag":"LineTo","args":[{"point":[736,832]}]},{"tag":"LineTo","args":[{"point":[736,400]}]},{"tag":"LineTo","args":[{"point":[736,384]}]}]},{"start":[320,160],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[192,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[166,160],"end":[147,179]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,198],"end":[128,224]}]}]},{"tag":"LineTo","args":[{"point":[128,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,986],"end":[146.5,1005]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[165,1024],"end":[192,1024]}]}]},{"tag":"LineTo","args":[{"point":[672,1024]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[699,1024],"end":[717.5,1005.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,987],"end":[736,960]}]}]},{"tag":"LineTo","args":[{"point":[736,864]}]},{"tag":"LineTo","args":[{"point":[864,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[891,864],"end":[909.5,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,827],"end":[928,800]}]}]},{"tag":"LineTo","args":[{"point":[928,224]}]},{"tag":"LineTo","args":[{"point":[736,0]}]},{"tag":"LineTo","args":[{"point":[384,0]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[358,0],"end":[339,19]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,38],"end":[320,64]}]}]},{"tag":"LineTo","args":[{"point":[320,160]}]}]},{"start":[736,48],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[886,224]}]},{"tag":"LineTo","args":[{"point":[768,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[755,224],"end":[745.5,214.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,205],"end":[736,192]}]}]},{"tag":"LineTo","args":[{"point":[736,48]}]}]},{"start":[512,192],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,379],"end":[530.5,397.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[549,416],"end":[576,416]}]}]},{"tag":"LineTo","args":[{"point":[704,416]}]},{"tag":"LineTo","args":[{"point":[704,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,973],"end":[694.5,982.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[685,992],"end":[672,992]}]}]},{"tag":"LineTo","args":[{"point":[192,992]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[179,992],"end":[169.5,982.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,973],"end":[160,960]}]}]},{"tag":"LineTo","args":[{"point":[160,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,211],"end":[169.5,201.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[179,192],"end":[192,192]}]}]},{"tag":"LineTo","args":[{"point":[512,192]}]}]},{"start":[544,208],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[694,384]}]},{"tag":"LineTo","args":[{"point":[576,384]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[563,384],"end":[553.5,374.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,365],"end":[544,352]}]}]},{"tag":"LineTo","args":[{"point":[544,208]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder-information","codePoint":59678},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[673,832],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[673,832]}]},{"tag":"LineTo","args":[{"point":[673,832]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[657,808],"end":[648.5,779.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,751],"end":[640,720]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,677],"end":[656,639]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[673,601],"end":[701,573]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[729,545],"end":[767,528]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[805,512],"end":[848,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[869,512],"end":[889.5,516]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[910,520],"end":[928,528]}]}]},{"tag":"LineTo","args":[{"point":[928,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,293],"end":[909,274.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[890,256],"end":[864,256]}]}]},{"tag":"LineTo","args":[{"point":[480,256]}]},{"tag":"LineTo","args":[{"point":[416,128]}]},{"tag":"LineTo","args":[{"point":[64,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[38,128],"end":[19,146.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,165],"end":[0,192]}]}]},{"tag":"LineTo","args":[{"point":[0,768]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,795],"end":[19,813.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[38,832],"end":[64,832]}]}]},{"tag":"LineTo","args":[{"point":[673,832]}]}]},{"start":[928,384],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[928,416]}]},{"tag":"LineTo","args":[{"point":[0,416]}]},{"tag":"LineTo","args":[{"point":[0,384]}]},{"tag":"LineTo","args":[{"point":[928,384]}]}]},{"start":[972.5,844.5],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,793],"end":[1024,720]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,647],"end":[972.5,595.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[921,544],"end":[848,544]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[775,544],"end":[723.5,595.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,647],"end":[672,720]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,793],"end":[723.5,844.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[775,896],"end":[848,896]}]}]},{"tag":"LineTo","args":[{"point":[848,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[921,896],"end":[972.5,844.5]}]}]}]},{"start":[864,704],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[864,768]}]},{"tag":"LineTo","args":[{"point":[896,768]}]},{"tag":"LineTo","args":[{"point":[896,800]}]},{"tag":"LineTo","args":[{"point":[800,800]}]},{"tag":"LineTo","args":[{"point":[800,768]}]},{"tag":"LineTo","args":[{"point":[832,768]}]},{"tag":"LineTo","args":[{"point":[832,736]}]},{"tag":"LineTo","args":[{"point":[800,736]}]},{"tag":"LineTo","args":[{"point":[800,704]}]},{"tag":"LineTo","args":[{"point":[864,704]}]}]},{"start":[864,640],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[864,672]}]},{"tag":"LineTo","args":[{"point":[832,672]}]},{"tag":"LineTo","args":[{"point":[832,640]}]},{"tag":"LineTo","args":[{"point":[864,640]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder-information-outline","codePoint":59679},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[64,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[51,800],"end":[41.5,790.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,781],"end":[32,768]}]}]},{"tag":"LineTo","args":[{"point":[32,416]}]},{"tag":"LineTo","args":[{"point":[896,416]}]},{"tag":"LineTo","args":[{"point":[896,551]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[885,547],"end":[872.5,545.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[860,544],"end":[848,544]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[775,544],"end":[723.5,595.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,647],"end":[672,720]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,742],"end":[677,762]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,782],"end":[691,800]}]}]},{"tag":"LineTo","args":[{"point":[691,800]}]},{"tag":"LineTo","args":[{"point":[64,800]}]}]},{"start":[712,832],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[712,832]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,861],"end":[771.5,878.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[807,896],"end":[848,896]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[921,896],"end":[972.5,844.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,793],"end":[1024,720]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,669],"end":[997.5,627]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[971,585],"end":[928,563]}]}]},{"tag":"LineTo","args":[{"point":[928,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,293],"end":[909,274.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[890,256],"end":[864,256]}]}]},{"tag":"LineTo","args":[{"point":[480,256]}]},{"tag":"LineTo","args":[{"point":[416,128]}]},{"tag":"LineTo","args":[{"point":[64,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[38,128],"end":[19,146.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,165],"end":[0,192]}]}]},{"tag":"LineTo","args":[{"point":[0,768]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,795],"end":[19,813.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[38,832],"end":[64,832]}]}]},{"tag":"LineTo","args":[{"point":[712,832]}]}]},{"start":[32,384],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[32,192]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,179],"end":[41.5,169.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[51,160],"end":[64,160]}]}]},{"tag":"LineTo","args":[{"point":[397,160]}]},{"tag":"LineTo","args":[{"point":[460,288]}]},{"tag":"LineTo","args":[{"point":[864,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[877,288],"end":[886.5,297.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,307],"end":[896,320]}]}]},{"tag":"LineTo","args":[{"point":[896,384]}]},{"tag":"LineTo","args":[{"point":[32,384]}]}]},{"start":[848,864],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[788,864],"end":[746,822]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,780],"end":[704,720]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,660],"end":[746,618]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[788,576],"end":[848,576]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[908,576],"end":[950,618]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[992,660],"end":[992,720]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[992,780],"end":[950,822]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[908,864],"end":[848,864]}]}]}]},{"start":[864,640],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[864,672]}]},{"tag":"LineTo","args":[{"point":[832,672]}]},{"tag":"LineTo","args":[{"point":[832,640]}]},{"tag":"LineTo","args":[{"point":[864,640]}]}]},{"start":[864,704],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[864,768]}]},{"tag":"LineTo","args":[{"point":[896,768]}]},{"tag":"LineTo","args":[{"point":[896,800]}]},{"tag":"LineTo","args":[{"point":[800,800]}]},{"tag":"LineTo","args":[{"point":[800,768]}]},{"tag":"LineTo","args":[{"point":[832,768]}]},{"tag":"LineTo","args":[{"point":[832,736]}]},{"tag":"LineTo","args":[{"point":[800,736]}]},{"tag":"LineTo","args":[{"point":[800,704]}]},{"tag":"LineTo","args":[{"point":[864,704]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder-remove","codePoint":59680},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[673,864],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[673,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[657,840],"end":[648.5,811.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,783],"end":[640,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,709],"end":[656,671]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[673,633],"end":[701,605]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[729,577],"end":[767,560]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[805,544],"end":[848,544]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[869,544],"end":[889.5,548]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[910,552],"end":[928,560]}]}]},{"tag":"LineTo","args":[{"point":[928,448]}]},{"tag":"LineTo","args":[{"point":[0,448]}]},{"tag":"LineTo","args":[{"point":[0,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,827],"end":[19,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[38,864],"end":[64,864]}]}]},{"tag":"LineTo","args":[{"point":[673,864]}]}]},{"start":[928,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[928,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,325],"end":[909,306.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[890,288],"end":[864,288]}]}]},{"tag":"LineTo","args":[{"point":[480,288]}]},{"tag":"LineTo","args":[{"point":[416,160]}]},{"tag":"LineTo","args":[{"point":[64,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[38,160],"end":[19,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,197],"end":[0,224]}]}]},{"tag":"LineTo","args":[{"point":[0,416]}]},{"tag":"LineTo","args":[{"point":[928,416]}]}]},{"start":[972.5,876.5],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,825],"end":[1024,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,679],"end":[972.5,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[921,576],"end":[848,576]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[775,576],"end":[723.5,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,679],"end":[672,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,825],"end":[723.5,876.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[775,928],"end":[848,928]}]}]},{"tag":"LineTo","args":[{"point":[848,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[921,928],"end":[972.5,876.5]}]}]}]},{"start":[960,736],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[960,768]}]},{"tag":"LineTo","args":[{"point":[736,768]}]},{"tag":"LineTo","args":[{"point":[736,736]}]},{"tag":"LineTo","args":[{"point":[960,736]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder-remove-outline","codePoint":59681},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[64,832],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[51,832],"end":[41.5,822.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,813],"end":[32,800]}]}]},{"tag":"LineTo","args":[{"point":[32,448]}]},{"tag":"LineTo","args":[{"point":[896,448]}]},{"tag":"LineTo","args":[{"point":[896,583]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[885,579],"end":[872.5,577.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[860,576],"end":[848,576]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[775,576],"end":[723.5,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,679],"end":[672,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,774],"end":[677,794]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,814],"end":[691,832]}]}]},{"tag":"LineTo","args":[{"point":[691,832]}]},{"tag":"LineTo","args":[{"point":[64,832]}]}]},{"start":[712,864],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[712,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,893],"end":[771.5,910.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[807,928],"end":[848,928]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[921,928],"end":[972.5,876.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,825],"end":[1024,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,701],"end":[997.5,659]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[971,617],"end":[928,595]}]}]},{"tag":"LineTo","args":[{"point":[928,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,325],"end":[909,306.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[890,288],"end":[864,288]}]}]},{"tag":"LineTo","args":[{"point":[480,288]}]},{"tag":"LineTo","args":[{"point":[416,160]}]},{"tag":"LineTo","args":[{"point":[64,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[38,160],"end":[19,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,197],"end":[0,224]}]}]},{"tag":"LineTo","args":[{"point":[0,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,827],"end":[19,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[38,864],"end":[64,864]}]}]},{"tag":"LineTo","args":[{"point":[712,864]}]}]},{"start":[32,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[32,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,211],"end":[41.5,201.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[51,192],"end":[64,192]}]}]},{"tag":"LineTo","args":[{"point":[397,192]}]},{"tag":"LineTo","args":[{"point":[460,320]}]},{"tag":"LineTo","args":[{"point":[864,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[877,320],"end":[886.5,329.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,339],"end":[896,352]}]}]},{"tag":"LineTo","args":[{"point":[896,416]}]},{"tag":"LineTo","args":[{"point":[32,416]}]}]},{"start":[848,896],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[788,896],"end":[746,854]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,812],"end":[704,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,692],"end":[746,650]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[788,608],"end":[848,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[908,608],"end":[950,650]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[992,692],"end":[992,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[992,812],"end":[950,854]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[908,896],"end":[848,896]}]}]}]},{"start":[960,736],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[960,768]}]},{"tag":"LineTo","args":[{"point":[736,768]}]},{"tag":"LineTo","args":[{"point":[736,736]}]},{"tag":"LineTo","args":[{"point":[960,736]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder-add","codePoint":59682},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[832,864],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[864,864]}]},{"tag":"LineTo","args":[{"point":[864,768]}]},{"tag":"LineTo","args":[{"point":[960,768]}]},{"tag":"LineTo","args":[{"point":[960,736]}]},{"tag":"LineTo","args":[{"point":[864,736]}]},{"tag":"LineTo","args":[{"point":[864,640]}]},{"tag":"LineTo","args":[{"point":[832,640]}]},{"tag":"LineTo","args":[{"point":[832,736]}]},{"tag":"LineTo","args":[{"point":[736,736]}]},{"tag":"LineTo","args":[{"point":[736,768]}]},{"tag":"LineTo","args":[{"point":[832,768]}]},{"tag":"LineTo","args":[{"point":[832,864]}]}]},{"start":[673,864],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[673,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[657,840],"end":[648.5,811.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,783],"end":[640,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,709],"end":[656,671]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[673,633],"end":[701,605]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[729,577],"end":[767,560]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[805,544],"end":[848,544]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[869,544],"end":[889.5,548]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[910,552],"end":[928,560]}]}]},{"tag":"LineTo","args":[{"point":[928,448]}]},{"tag":"LineTo","args":[{"point":[0,448]}]},{"tag":"LineTo","args":[{"point":[0,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,827],"end":[19,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[38,864],"end":[64,864]}]}]},{"tag":"LineTo","args":[{"point":[673,864]}]}]},{"start":[928,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[928,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,325],"end":[909,306.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[890,288],"end":[864,288]}]}]},{"tag":"LineTo","args":[{"point":[480,288]}]},{"tag":"LineTo","args":[{"point":[416,160]}]},{"tag":"LineTo","args":[{"point":[64,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[38,160],"end":[19,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,197],"end":[0,224]}]}]},{"tag":"LineTo","args":[{"point":[0,416]}]},{"tag":"LineTo","args":[{"point":[928,416]}]}]},{"start":[848,928],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[775,928],"end":[723.5,876.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,825],"end":[672,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,679],"end":[723.5,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[775,576],"end":[848,576]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[921,576],"end":[972.5,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,679],"end":[1024,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,825],"end":[972.5,876.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[921,928],"end":[848,928]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder-add-outline","codePoint":59683},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[736,736],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,768]}]},{"tag":"LineTo","args":[{"point":[832,768]}]},{"tag":"LineTo","args":[{"point":[832,864]}]},{"tag":"LineTo","args":[{"point":[864,864]}]},{"tag":"LineTo","args":[{"point":[864,768]}]},{"tag":"LineTo","args":[{"point":[960,768]}]},{"tag":"LineTo","args":[{"point":[960,736]}]},{"tag":"LineTo","args":[{"point":[864,736]}]},{"tag":"LineTo","args":[{"point":[864,640]}]},{"tag":"LineTo","args":[{"point":[832,640]}]},{"tag":"LineTo","args":[{"point":[832,736]}]},{"tag":"LineTo","args":[{"point":[736,736]}]}]},{"start":[64,832],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[51,832],"end":[41.5,822.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,813],"end":[32,800]}]}]},{"tag":"LineTo","args":[{"point":[32,448]}]},{"tag":"LineTo","args":[{"point":[896,448]}]},{"tag":"LineTo","args":[{"point":[896,583]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[885,579],"end":[872.5,577.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[860,576],"end":[848,576]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[775,576],"end":[723.5,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,679],"end":[672,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,774],"end":[677,794]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,814],"end":[691,832]}]}]},{"tag":"LineTo","args":[{"point":[691,832]}]},{"tag":"LineTo","args":[{"point":[64,832]}]}]},{"start":[712,864],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[712,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,893],"end":[771.5,910.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[807,928],"end":[848,928]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[921,928],"end":[972.5,876.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,825],"end":[1024,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,701],"end":[997.5,659]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[971,617],"end":[928,595]}]}]},{"tag":"LineTo","args":[{"point":[928,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,325],"end":[909,306.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[890,288],"end":[864,288]}]}]},{"tag":"LineTo","args":[{"point":[480,288]}]},{"tag":"LineTo","args":[{"point":[416,160]}]},{"tag":"LineTo","args":[{"point":[64,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[38,160],"end":[19,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,197],"end":[0,224]}]}]},{"tag":"LineTo","args":[{"point":[0,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,827],"end":[19,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[38,864],"end":[64,864]}]}]},{"tag":"LineTo","args":[{"point":[712,864]}]}]},{"start":[32,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[32,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,211],"end":[41.5,201.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[51,192],"end":[64,192]}]}]},{"tag":"LineTo","args":[{"point":[397,192]}]},{"tag":"LineTo","args":[{"point":[460,320]}]},{"tag":"LineTo","args":[{"point":[864,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[877,320],"end":[886.5,329.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,339],"end":[896,352]}]}]},{"tag":"LineTo","args":[{"point":[896,416]}]},{"tag":"LineTo","args":[{"point":[32,416]}]}]},{"start":[848,896],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[788,896],"end":[746,854]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,812],"end":[704,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,692],"end":[746,650]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[788,608],"end":[848,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[908,608],"end":[950,650]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[992,692],"end":[992,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[992,812],"end":[950,854]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[908,896],"end":[848,896]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder-upload","codePoint":59684},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[480,864],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[480,576]}]},{"tag":"LineTo","args":[{"point":[376,680]}]},{"tag":"LineTo","args":[{"point":[352,656]}]},{"tag":"LineTo","args":[{"point":[496,512]}]},{"tag":"LineTo","args":[{"point":[640,656]}]},{"tag":"LineTo","args":[{"point":[616,680]}]},{"tag":"LineTo","args":[{"point":[512,576]}]},{"tag":"LineTo","args":[{"point":[512,864]}]},{"tag":"LineTo","args":[{"point":[896,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[923,864],"end":[941.5,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,827],"end":[960,800]}]}]},{"tag":"LineTo","args":[{"point":[960,448]}]},{"tag":"LineTo","args":[{"point":[32,448]}]},{"tag":"LineTo","args":[{"point":[32,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,827],"end":[51,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,864],"end":[96,864]}]}]},{"tag":"LineTo","args":[{"point":[480,864]}]}]},{"start":[960,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[960,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,325],"end":[941,306.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[922,288],"end":[896,288]}]}]},{"tag":"LineTo","args":[{"point":[512,288]}]},{"tag":"LineTo","args":[{"point":[448,160]}]},{"tag":"LineTo","args":[{"point":[96,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,160],"end":[51,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,197],"end":[32,224]}]}]},{"tag":"LineTo","args":[{"point":[32,416]}]},{"tag":"LineTo","args":[{"point":[960,416]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder-upload-outline","codePoint":59685},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[480,544],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[376,648]}]},{"tag":"LineTo","args":[{"point":[352,624]}]},{"tag":"LineTo","args":[{"point":[496,480]}]},{"tag":"LineTo","args":[{"point":[640,624]}]},{"tag":"LineTo","args":[{"point":[616,648]}]},{"tag":"LineTo","args":[{"point":[512,544]}]},{"tag":"LineTo","args":[{"point":[512,832]}]},{"tag":"LineTo","args":[{"point":[896,832]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[909,832],"end":[918.5,822.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,813],"end":[928,800]}]}]},{"tag":"LineTo","args":[{"point":[928,448]}]},{"tag":"LineTo","args":[{"point":[64,448]}]},{"tag":"LineTo","args":[{"point":[64,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[64,813],"end":[73.5,822.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[83,832],"end":[96,832]}]}]},{"tag":"LineTo","args":[{"point":[480,832]}]},{"tag":"LineTo","args":[{"point":[480,544]}]}]},{"start":[928,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[928,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,339],"end":[918.5,329.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[909,320],"end":[896,320]}]}]},{"tag":"LineTo","args":[{"point":[492,320]}]},{"tag":"LineTo","args":[{"point":[429,192]}]},{"tag":"LineTo","args":[{"point":[96,192]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[83,192],"end":[73.5,201.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[64,211],"end":[64,224]}]}]},{"tag":"LineTo","args":[{"point":[64,416]}]},{"tag":"LineTo","args":[{"point":[928,416]}]}]},{"start":[512,288],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[896,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[922,288],"end":[941,306.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,325],"end":[960,352]}]}]},{"tag":"LineTo","args":[{"point":[960,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,827],"end":[941.5,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[923,864],"end":[896,864]}]}]},{"tag":"LineTo","args":[{"point":[96,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,864],"end":[51,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,827],"end":[32,800]}]}]},{"tag":"LineTo","args":[{"point":[32,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,197],"end":[51,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,160],"end":[96,160]}]}]},{"tag":"LineTo","args":[{"point":[448,160]}]},{"tag":"LineTo","args":[{"point":[512,288]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder-download","codePoint":59686},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,448],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,738]}]},{"tag":"LineTo","args":[{"point":[616,634]}]},{"tag":"LineTo","args":[{"point":[640,658]}]},{"tag":"LineTo","args":[{"point":[496,802]}]},{"tag":"LineTo","args":[{"point":[352,658]}]},{"tag":"LineTo","args":[{"point":[376,634]}]},{"tag":"LineTo","args":[{"point":[480,738]}]},{"tag":"LineTo","args":[{"point":[480,448]}]},{"tag":"LineTo","args":[{"point":[32,448]}]},{"tag":"LineTo","args":[{"point":[32,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,827],"end":[51,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,864],"end":[96,864]}]}]},{"tag":"LineTo","args":[{"point":[896,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[923,864],"end":[941.5,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,827],"end":[960,800]}]}]},{"tag":"LineTo","args":[{"point":[960,448]}]},{"tag":"LineTo","args":[{"point":[512,448]}]}]},{"start":[960,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[960,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,325],"end":[941,306.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[922,288],"end":[896,288]}]}]},{"tag":"LineTo","args":[{"point":[512,288]}]},{"tag":"LineTo","args":[{"point":[448,160]}]},{"tag":"LineTo","args":[{"point":[96,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,160],"end":[51,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,197],"end":[32,224]}]}]},{"tag":"LineTo","args":[{"point":[32,416]}]},{"tag":"LineTo","args":[{"point":[960,416]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder-download-outline","codePoint":59687},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,448],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,738]}]},{"tag":"LineTo","args":[{"point":[616,634]}]},{"tag":"LineTo","args":[{"point":[640,658]}]},{"tag":"LineTo","args":[{"point":[496,802]}]},{"tag":"LineTo","args":[{"point":[352,658]}]},{"tag":"LineTo","args":[{"point":[376,634]}]},{"tag":"LineTo","args":[{"point":[480,738]}]},{"tag":"LineTo","args":[{"point":[480,448]}]},{"tag":"LineTo","args":[{"point":[64,448]}]},{"tag":"LineTo","args":[{"point":[64,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[64,813],"end":[73.5,822.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[83,832],"end":[96,832]}]}]},{"tag":"LineTo","args":[{"point":[896,832]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[909,832],"end":[918.5,822.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,813],"end":[928,800]}]}]},{"tag":"LineTo","args":[{"point":[928,448]}]},{"tag":"LineTo","args":[{"point":[512,448]}]}]},{"start":[928,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[928,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,339],"end":[918.5,329.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[909,320],"end":[896,320]}]}]},{"tag":"LineTo","args":[{"point":[492,320]}]},{"tag":"LineTo","args":[{"point":[429,192]}]},{"tag":"LineTo","args":[{"point":[96,192]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[83,192],"end":[73.5,201.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[64,211],"end":[64,224]}]}]},{"tag":"LineTo","args":[{"point":[64,416]}]},{"tag":"LineTo","args":[{"point":[928,416]}]}]},{"start":[512,288],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[896,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[922,288],"end":[941,306.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,325],"end":[960,352]}]}]},{"tag":"LineTo","args":[{"point":[960,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,827],"end":[941.5,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[923,864],"end":[896,864]}]}]},{"tag":"LineTo","args":[{"point":[96,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,864],"end":[51,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,827],"end":[32,800]}]}]},{"tag":"LineTo","args":[{"point":[32,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,197],"end":[51,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,160],"end":[96,160]}]}]},{"tag":"LineTo","args":[{"point":[448,160]}]},{"tag":"LineTo","args":[{"point":[512,288]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder-search","codePoint":59688},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[693,812],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[716,789]}]},{"tag":"LineTo","args":[{"point":[545,618]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[559,599],"end":[567.5,576]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,553],"end":[576,528]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,468],"end":[534,426]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[492,384],"end":[432,384]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,384],"end":[330,426]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[288,468],"end":[288,528]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[288,588],"end":[330,630]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,672],"end":[432,672]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[458,672],"end":[480.5,663.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[503,655],"end":[522,641]}]}]},{"tag":"LineTo","args":[{"point":[693,812]}]}]},{"start":[512,288],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[896,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[922,288],"end":[941,306.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,325],"end":[960,352]}]}]},{"tag":"LineTo","args":[{"point":[960,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,827],"end":[941.5,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[923,864],"end":[896,864]}]}]},{"tag":"LineTo","args":[{"point":[96,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,864],"end":[51,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,827],"end":[32,800]}]}]},{"tag":"LineTo","args":[{"point":[32,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,197],"end":[51,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,160],"end":[96,160]}]}]},{"tag":"LineTo","args":[{"point":[448,160]}]},{"tag":"LineTo","args":[{"point":[512,288]}]}]},{"start":[432,640],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[386,640],"end":[353,607]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,574],"end":[320,528]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,482],"end":[353,449]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[386,416],"end":[432,416]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,416],"end":[511,449]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,482],"end":[544,528]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,574],"end":[511,607]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,640],"end":[432,640]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder-search-outline","codePoint":59689},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[693,812],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[716,789]}]},{"tag":"LineTo","args":[{"point":[545,618]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[559,599],"end":[567.5,576]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,553],"end":[576,528]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,468],"end":[534,426]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[492,384],"end":[432,384]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,384],"end":[330,426]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[288,468],"end":[288,528]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[288,588],"end":[330,630]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,672],"end":[432,672]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[458,672],"end":[480.5,663.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[503,655],"end":[522,641]}]}]},{"tag":"LineTo","args":[{"point":[693,812]}]}]},{"start":[448,160],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[96,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,160],"end":[51,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,197],"end":[32,224]}]}]},{"tag":"LineTo","args":[{"point":[32,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,827],"end":[51,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,864],"end":[96,864]}]}]},{"tag":"LineTo","args":[{"point":[896,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[923,864],"end":[941.5,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,827],"end":[960,800]}]}]},{"tag":"LineTo","args":[{"point":[960,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,325],"end":[941,306.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[922,288],"end":[896,288]}]}]},{"tag":"LineTo","args":[{"point":[512,288]}]},{"tag":"LineTo","args":[{"point":[448,160]}]}]},{"start":[492,320],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[896,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[909,320],"end":[918.5,329.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,339],"end":[928,352]}]}]},{"tag":"LineTo","args":[{"point":[928,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,813],"end":[918.5,822.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[909,832],"end":[896,832]}]}]},{"tag":"LineTo","args":[{"point":[96,832]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[83,832],"end":[73.5,822.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[64,813],"end":[64,800]}]}]},{"tag":"LineTo","args":[{"point":[64,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[64,211],"end":[73.5,201.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[83,192],"end":[96,192]}]}]},{"tag":"LineTo","args":[{"point":[429,192]}]},{"tag":"LineTo","args":[{"point":[492,320]}]}]},{"start":[432,640],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[386,640],"end":[353,607]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,574],"end":[320,528]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,482],"end":[353,449]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[386,416],"end":[432,416]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,416],"end":[511,449]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,482],"end":[544,528]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,574],"end":[511,607]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,640],"end":[432,640]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder","codePoint":59690},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[960,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[960,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,325],"end":[941,306.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[922,288],"end":[896,288]}]}]},{"tag":"LineTo","args":[{"point":[512,288]}]},{"tag":"LineTo","args":[{"point":[448,160]}]},{"tag":"LineTo","args":[{"point":[96,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,160],"end":[51,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,197],"end":[32,224]}]}]},{"tag":"LineTo","args":[{"point":[32,416]}]},{"tag":"LineTo","args":[{"point":[960,416]}]}]},{"start":[32,448],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[960,448]}]},{"tag":"LineTo","args":[{"point":[960,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,827],"end":[941.5,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[923,864],"end":[896,864]}]}]},{"tag":"LineTo","args":[{"point":[96,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,864],"end":[51,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,827],"end":[32,800]}]}]},{"tag":"LineTo","args":[{"point":[32,448]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder-outline","codePoint":59691},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[928,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[928,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,339],"end":[918.5,329.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[909,320],"end":[896,320]}]}]},{"tag":"LineTo","args":[{"point":[492,320]}]},{"tag":"LineTo","args":[{"point":[429,192]}]},{"tag":"LineTo","args":[{"point":[96,192]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[83,192],"end":[73.5,201.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[64,211],"end":[64,224]}]}]},{"tag":"LineTo","args":[{"point":[64,416]}]},{"tag":"LineTo","args":[{"point":[928,416]}]}]},{"start":[64,448],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[64,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[64,813],"end":[73.5,822.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[83,832],"end":[96,832]}]}]},{"tag":"LineTo","args":[{"point":[896,832]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[909,832],"end":[918.5,822.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,813],"end":[928,800]}]}]},{"tag":"LineTo","args":[{"point":[928,448]}]},{"tag":"LineTo","args":[{"point":[64,448]}]}]},{"start":[512,288],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[896,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[922,288],"end":[941,306.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,325],"end":[960,352]}]}]},{"tag":"LineTo","args":[{"point":[960,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,827],"end":[941.5,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[923,864],"end":[896,864]}]}]},{"tag":"LineTo","args":[{"point":[96,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,864],"end":[51,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,827],"end":[32,800]}]}]},{"tag":"LineTo","args":[{"point":[32,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,197],"end":[51,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,160],"end":[96,160]}]}]},{"tag":"LineTo","args":[{"point":[448,160]}]},{"tag":"LineTo","args":[{"point":[512,288]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder2","codePoint":59692},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,288],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[896,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[922,288],"end":[941,306.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,325],"end":[960,352]}]}]},{"tag":"LineTo","args":[{"point":[960,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,827],"end":[941.5,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[923,864],"end":[896,864]}]}]},{"tag":"LineTo","args":[{"point":[96,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,864],"end":[51,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,827],"end":[32,800]}]}]},{"tag":"LineTo","args":[{"point":[32,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,197],"end":[51,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,160],"end":[96,160]}]}]},{"tag":"LineTo","args":[{"point":[448,160]}]},{"tag":"LineTo","args":[{"point":[512,288]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder2-outline","codePoint":59693},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[448,160],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[96,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,160],"end":[51,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,197],"end":[32,224]}]}]},{"tag":"LineTo","args":[{"point":[32,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,827],"end":[51,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[70,864],"end":[96,864]}]}]},{"tag":"LineTo","args":[{"point":[896,864]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[923,864],"end":[941.5,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,827],"end":[960,800]}]}]},{"tag":"LineTo","args":[{"point":[960,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[960,325],"end":[941,306.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[922,288],"end":[896,288]}]}]},{"tag":"LineTo","args":[{"point":[512,288]}]},{"tag":"LineTo","args":[{"point":[448,160]}]}]},{"start":[492,320],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[896,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[909,320],"end":[918.5,329.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,339],"end":[928,352]}]}]},{"tag":"LineTo","args":[{"point":[928,800]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[928,813],"end":[918.5,822.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[909,832],"end":[896,832]}]}]},{"tag":"LineTo","args":[{"point":[96,832]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[83,832],"end":[73.5,822.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[64,813],"end":[64,800]}]}]},{"tag":"LineTo","args":[{"point":[64,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[64,211],"end":[73.5,201.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[83,192],"end":[96,192]}]}]},{"tag":"LineTo","args":[{"point":[429,192]}]},{"tag":"LineTo","args":[{"point":[492,320]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"android","codePoint":59694},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[945,393],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[945,393]}]},{"tag":"LineTo","args":[{"point":[945,658]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[945,684],"end":[926.5,702.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[908,721],"end":[882,721]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[856,721],"end":[837.5,702.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[819,684],"end":[819,658]}]}]},{"tag":"LineTo","args":[{"point":[819,394]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[819,368],"end":[837.5,349.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[856,331],"end":[882,331]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[908,331],"end":[926.5,349.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[945,368],"end":[945,394]}]}]},{"tag":"LineTo","args":[{"point":[945,393]}]}]},{"start":[230,343],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[793,342]}]},{"tag":"LineTo","args":[{"point":[793,753]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[793,781],"end":[773,800.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[753,820],"end":[726,820]}]}]},{"tag":"LineTo","args":[{"point":[680,820]}]},{"tag":"LineTo","args":[{"point":[680,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,987],"end":[661.5,1005.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[643,1024],"end":[616,1024]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[590,1024],"end":[572,1005.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,987],"end":[554,961]}]}]},{"tag":"LineTo","args":[{"point":[554,821]}]},{"tag":"LineTo","args":[{"point":[469,821]}]},{"tag":"LineTo","args":[{"point":[469,961]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[468,987],"end":[449.5,1005]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[431,1023],"end":[405,1023]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,1023],"end":[361.5,1004.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[343,986],"end":[343,960]}]}]},{"tag":"LineTo","args":[{"point":[343,820]}]},{"tag":"LineTo","args":[{"point":[297,820]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[270,820],"end":[250,800.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[230,781],"end":[230,752]}]}]},{"tag":"LineTo","args":[{"point":[230,343]}]}]},{"start":[659,211],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[666,204],"end":[666,194]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[666,184],"end":[659,177]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,170],"end":[642,170]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[632,170],"end":[625,177]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,184],"end":[618,194]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,204],"end":[625,211]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[632,218],"end":[642,218]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,218],"end":[659,211]}]}]}]},{"start":[383,218],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[393,218],"end":[400,211]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[407,204],"end":[407,194]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[407,184],"end":[400,177]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[393,170],"end":[383,170]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[373,170],"end":[366,177]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[359,184],"end":[359,194]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[359,204],"end":[366,211]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[373,218],"end":[383,218]}]}]}]},{"start":[651,93],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[716,126],"end":[756,186.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[796,247],"end":[796,320]}]}]},{"tag":"LineTo","args":[{"point":[228,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[228,247],"end":[268,186.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[308,126],"end":[373,93]}]}]},{"tag":"LineTo","args":[{"point":[329,13]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[327,10],"end":[328,6.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[329,3],"end":[332,1]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[335,-1],"end":[338.5,0]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,1],"end":[344,4]}]}]},{"tag":"LineTo","args":[{"point":[388,86]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[416,73],"end":[447,66.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,60],"end":[512,60]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[545,60],"end":[576,67]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[607,74],"end":[635,87]}]}]},{"tag":"LineTo","args":[{"point":[680,6]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,2],"end":[685,1]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,0],"end":[692,2]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[695,4],"end":[696,7.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[697,11],"end":[695,14]}]}]},{"tag":"LineTo","args":[{"point":[651,95]}]},{"tag":"LineTo","args":[{"point":[651,93]}]}]},{"start":[143,331],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[168,331],"end":[186.5,349.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[205,368],"end":[205,394]}]}]},{"tag":"LineTo","args":[{"point":[205,658]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[205,684],"end":[186.5,702.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[168,721],"end":[142,721]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[116,721],"end":[97.5,702.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[79,684],"end":[79,658]}]}]},{"tag":"LineTo","args":[{"point":[79,394]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[79,367],"end":[97.5,348.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[116,330],"end":[142,330]}]}]},{"tag":"LineTo","args":[{"point":[143,331]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"angular","codePoint":59695},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,330],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[600,540]}]},{"tag":"LineTo","args":[{"point":[424,540]}]},{"tag":"LineTo","args":[{"point":[512,330]}]}]},{"start":[512,0],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[994,170]}]},{"tag":"LineTo","args":[{"point":[921,800]}]},{"tag":"LineTo","args":[{"point":[512,1024]}]},{"tag":"LineTo","args":[{"point":[103,800]}]},{"tag":"LineTo","args":[{"point":[29,170]}]},{"tag":"LineTo","args":[{"point":[512,0]}]}]},{"start":[512,113],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,781]}]},{"tag":"LineTo","args":[{"point":[323,781]}]},{"tag":"LineTo","args":[{"point":[384,632]}]},{"tag":"LineTo","args":[{"point":[640,632]}]},{"tag":"LineTo","args":[{"point":[701,781]}]},{"tag":"LineTo","args":[{"point":[813,781]}]},{"tag":"LineTo","args":[{"point":[512,113]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"css3","codePoint":59696},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[64,0],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[146,920]}]},{"tag":"LineTo","args":[{"point":[511,1024]}]},{"tag":"LineTo","args":[{"point":[879,920]}]},{"tag":"LineTo","args":[{"point":[960,0]}]},{"tag":"LineTo","args":[{"point":[64,0]}]}]},{"start":[793,188],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[741,758]}]},{"tag":"LineTo","args":[{"point":[512,823]}]},{"tag":"LineTo","args":[{"point":[279,750]}]},{"tag":"LineTo","args":[{"point":[266,586]}]},{"tag":"LineTo","args":[{"point":[378,586]}]},{"tag":"LineTo","args":[{"point":[386,676]}]},{"tag":"LineTo","args":[{"point":[512,710]}]},{"tag":"LineTo","args":[{"point":[636,676]}]},{"tag":"LineTo","args":[{"point":[652,526]}]},{"tag":"LineTo","args":[{"point":[388,526]}]},{"tag":"LineTo","args":[{"point":[378,416]}]},{"tag":"LineTo","args":[{"point":[661,416]}]},{"tag":"LineTo","args":[{"point":[672,300]}]},{"tag":"LineTo","args":[{"point":[240,300]}]},{"tag":"LineTo","args":[{"point":[231,188]}]},{"tag":"LineTo","args":[{"point":[793,188]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"dev-dot-to","codePoint":59697},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[317,429],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[325,436],"end":[327,448.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[329,461],"end":[329,522]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[329,581],"end":[327.5,594.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[326,608],"end":[318,616]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[311,622],"end":[303.5,624.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[296,627],"end":[282,627]}]}]},{"tag":"LineTo","args":[{"point":[259,628]}]},{"tag":"LineTo","args":[{"point":[257,523]}]},{"tag":"LineTo","args":[{"point":[256,419]}]},{"tag":"LineTo","args":[{"point":[281,419]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[293,419],"end":[302,421.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[311,424],"end":[317,429]}]}]}]},{"start":[1024,211],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[1024,813]}]},{"tag":"LineTo","args":[{"point":[0,813]}]},{"tag":"LineTo","args":[{"point":[0,211]}]},{"tag":"LineTo","args":[{"point":[1024,211]}]}]},{"start":[365,653],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,635],"end":[383.5,609]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[387,583],"end":[385,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,449],"end":[382,432.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,416],"end":[372,402]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[358,379],"end":[336,371.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[314,364],"end":[261,364]}]}]},{"tag":"LineTo","args":[{"point":[201,364]}]},{"tag":"LineTo","args":[{"point":[201,686]}]},{"tag":"LineTo","args":[{"point":[257,686]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[304,686],"end":[327.5,678.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[351,671],"end":[365,653]}]}]}]},{"start":[582,420],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[582,364]}]},{"tag":"LineTo","args":[{"point":[512,364]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[460,364],"end":[450,366]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[440,368],"end":[432,378]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[425,387],"end":[423.5,408]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[422,429],"end":[422,526]}]}]},{"tag":"LineTo","args":[{"point":[422,661]}]},{"tag":"LineTo","args":[{"point":[434,673]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[443,682],"end":[454,684]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[465,686],"end":[514,686]}]}]},{"tag":"LineTo","args":[{"point":[582,686]}]},{"tag":"LineTo","args":[{"point":[582,631]}]},{"tag":"LineTo","args":[{"point":[531,629]}]},{"tag":"LineTo","args":[{"point":[479,628]}]},{"tag":"LineTo","args":[{"point":[479,553]}]},{"tag":"LineTo","args":[{"point":[511,551]}]},{"tag":"LineTo","args":[{"point":[542,550]}]},{"tag":"LineTo","args":[{"point":[542,495]}]},{"tag":"LineTo","args":[{"point":[477,495]}]},{"tag":"LineTo","args":[{"point":[477,419]}]},{"tag":"LineTo","args":[{"point":[582,419]}]},{"tag":"LineTo","args":[{"point":[582,420]}]}]},{"start":[782,652],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[784,647],"end":[796,603]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[808,559],"end":[822,507]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[836,455],"end":[847,412]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[858,369],"end":[858,367]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[858,366],"end":[849,365.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[840,365],"end":[827,365]}]}]},{"tag":"LineTo","args":[{"point":[796,367]}]},{"tag":"LineTo","args":[{"point":[768,474]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[754,526],"end":[746,551.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[738,577],"end":[736,573]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[735,568],"end":[726,536]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[718,503],"end":[708,466]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[698,429],"end":[690,398]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[683,367],"end":[683,367]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[683,366],"end":[673,365]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[663,364],"end":[651,364]}]}]},{"tag":"LineTo","args":[{"point":[618,364]}]},{"tag":"LineTo","args":[{"point":[637,436]}]},{"tag":"LineTo","args":[{"point":[676,580]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,627],"end":[694.5,643]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[701,659],"end":[711,669]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[718,677],"end":[726,681.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[734,686],"end":[739,686]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[751,686],"end":[764,676]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[777,666],"end":[782,652]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"facebook","codePoint":59698},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[1024,512],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,608],"end":[991,693]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[958,779],"end":[900,846.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[842,914],"end":[763,958]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[684,1003],"end":[592,1018]}]}]},{"tag":"LineTo","args":[{"point":[592,660]}]},{"tag":"LineTo","args":[{"point":[711,660]}]},{"tag":"LineTo","args":[{"point":[734,512]}]},{"tag":"LineTo","args":[{"point":[592,512]}]},{"tag":"LineTo","args":[{"point":[592,416]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[592,386],"end":[610,361]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[628,336],"end":[675,336]}]}]},{"tag":"LineTo","args":[{"point":[740,336]}]},{"tag":"LineTo","args":[{"point":[740,210]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[740,210],"end":[703.5,205]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[667,200],"end":[625,200]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[538,200],"end":[485,251.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[432,303],"end":[432,399]}]}]},{"tag":"LineTo","args":[{"point":[432,512]}]},{"tag":"LineTo","args":[{"point":[302,512]}]},{"tag":"LineTo","args":[{"point":[302,660]}]},{"tag":"LineTo","args":[{"point":[432,660]}]},{"tag":"LineTo","args":[{"point":[432,1018]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[340,1003],"end":[261,958]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[182,914],"end":[124,846.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[66,779],"end":[33,693]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,608],"end":[0,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,406],"end":[40,313]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[80,219],"end":[149.5,149.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[219,80],"end":[313,40]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[406,0],"end":[512,0]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,0],"end":[711,40]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[804,80],"end":[873.5,149.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[943,219],"end":[984,313]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,406],"end":[1024,512]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"git","codePoint":59699},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[1005,466],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,486],"end":[1024,513]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,540],"end":[1005,560]}]}]},{"tag":"LineTo","args":[{"point":[560,1005]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[540,1024],"end":[513,1024]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[486,1024],"end":[466,1005]}]}]},{"tag":"LineTo","args":[{"point":[19,558]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,538],"end":[0,511]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,484],"end":[19,464]}]}]},{"tag":"LineTo","args":[{"point":[326,158]}]},{"tag":"LineTo","args":[{"point":[442,274]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[433,295],"end":[437,318.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[441,342],"end":[458,360]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[464,366],"end":[470.5,370]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[477,374],"end":[484,377]}]}]},{"tag":"LineTo","args":[{"point":[484,658]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[477,661],"end":[470.5,665.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[464,670],"end":[458,675]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[435,698],"end":[435,730.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[435,763],"end":[458,786]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[481,809],"end":[514,809]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[547,809],"end":[570,786]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[592,763],"end":[592,730.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[592,698],"end":[570,675]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[565,671],"end":[559.5,667]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,663],"end":[549,660]}]}]},{"tag":"LineTo","args":[{"point":[549,382]}]},{"tag":"LineTo","args":[{"point":[655,488]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[646,509],"end":[650.5,532.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[655,556],"end":[672,573]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[695,596],"end":[727.5,596]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[760,596],"end":[783,573]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[806,550],"end":[806,517.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[806,485],"end":[783,462]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[767,445],"end":[745,440.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[723,436],"end":[702,443]}]}]},{"tag":"LineTo","args":[{"point":[589,330]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[596,309],"end":[591,287]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[586,265],"end":[570,249]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,232],"end":[532,227.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[510,223],"end":[489,230]}]}]},{"tag":"LineTo","args":[{"point":[372,112]}]},{"tag":"LineTo","args":[{"point":[464,19]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[484,0],"end":[511,0]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[538,0],"end":[558,19]}]}]},{"tag":"LineTo","args":[{"point":[1005,466]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"github","codePoint":59700},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,13],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,13],"end":[711,53]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[805,93],"end":[874.5,162.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[944,232],"end":[984,325]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,419],"end":[1024,525]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,609],"end":[998,686]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[972,763],"end":[925,826.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[878,890],"end":[814,937]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[749,985],"end":[673,1010]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[653,1014],"end":[645,1005]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[637,996],"end":[637,985]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[637,973],"end":[637.5,935]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[638,897],"end":[638,845]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[638,809],"end":[627.5,785.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[617,762],"end":[603,751]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[646,746],"end":[688,733]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[730,721],"end":[763,693.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[796,666],"end":[817,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[837,572],"end":[837,498]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[837,456],"end":[823,421.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[809,387],"end":[785,361]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[788,351],"end":[794,314.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[800,278],"end":[779,225]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[779,225],"end":[745.5,226.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[712,228],"end":[639,278]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[609,269],"end":[576.5,264.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,260],"end":[511,260]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[479,260],"end":[446.5,264.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[414,269],"end":[383,278]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[310,228],"end":[276.5,226.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[243,225],"end":[243,225]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,278],"end":[228,314.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[234,351],"end":[238,361]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[213,387],"end":[199,421.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[185,456],"end":[185,498]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[185,571],"end":[206,618]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[226,665],"end":[259,693]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[292,721],"end":[334,734]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[376,746],"end":[419,751]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[408,761],"end":[399,778]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[390,795],"end":[386,819]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[364,829],"end":[317.5,832.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[271,836],"end":[237,777]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[237,777],"end":[217,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,727],"end":[159,724]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[159,724],"end":[139.5,727.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[120,731],"end":[155,755]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[155,755],"end":[174.5,770.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[194,786],"end":[212,830]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[212,830],"end":[245,876]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[278,922],"end":[384,899]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[385,931],"end":[385,954]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[385,977],"end":[385,986]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[385,996],"end":[377,1005]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[369,1014],"end":[350,1010]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[274,985],"end":[210,938]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[145,891],"end":[98.5,827.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[52,764],"end":[26,687]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,610],"end":[0,525]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,419],"end":[40,325]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[80,232],"end":[149.5,162.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[219,93],"end":[313,53]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[406,13],"end":[512,13]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"gmail","codePoint":59701},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[1024,192],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,178],"end":[1019,166.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1014,155],"end":[1006,146]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[997,138],"end":[985.5,133]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[974,128],"end":[960,128]}]}]},{"tag":"LineTo","args":[{"point":[939,128]}]},{"tag":"LineTo","args":[{"point":[512,437]}]},{"tag":"LineTo","args":[{"point":[85,128]}]},{"tag":"LineTo","args":[{"point":[64,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[50,128],"end":[38.5,133]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[27,138],"end":[18,146]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[10,155],"end":[5,166.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,178],"end":[0,192]}]}]},{"tag":"LineTo","args":[{"point":[0,832]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,859],"end":[18.5,877.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[37,896],"end":[64,896]}]}]},{"tag":"LineTo","args":[{"point":[128,896]}]},{"tag":"LineTo","args":[{"point":[128,315]}]},{"tag":"LineTo","args":[{"point":[512,591]}]},{"tag":"LineTo","args":[{"point":[896,315]}]},{"tag":"LineTo","args":[{"point":[896,896]}]},{"tag":"LineTo","args":[{"point":[960,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[987,896],"end":[1005.5,877.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,859],"end":[1024,832]}]}]},{"tag":"LineTo","args":[{"point":[1024,192]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"googlechrome","codePoint":59702},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[692,371],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[691,370]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[699,379],"end":[705,389]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[711,399],"end":[717,410]}]}]},{"tag":"LineTo","args":[{"point":[716,408]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[728,432],"end":[734.5,458.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[741,485],"end":[741,513]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[741,540],"end":[735,565]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[729,590],"end":[719,612]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[712,627],"end":[702.5,640.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[693,654],"end":[681,666]}]}]},{"tag":"LineTo","args":[{"point":[472,1023]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[482,1023],"end":[491.5,1023.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[501,1024],"end":[511,1024]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[616,1024],"end":[710,983]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[803,943],"end":[873,873]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[943,803],"end":[983,710]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,616],"end":[1024,511]}]}]},{"tag":"LineTo","args":[{"point":[1024,511]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,453],"end":[1012,399.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1000,346],"end":[978,299]}]}]},{"tag":"LineTo","args":[{"point":[692,371]}]}]},{"start":[554,737],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[522,743],"end":[489,740]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[456,737],"end":[424,725]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[362,701],"end":[330.5,650.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[299,600],"end":[293,583]}]}]},{"tag":"LineTo","args":[{"point":[87,225]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[44,289],"end":[22,362]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,435],"end":[0,511]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,610],"end":[36,698]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[71,787],"end":[133.5,855.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[196,924],"end":[281,968]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[365,1012],"end":[463,1022]}]}]},{"tag":"LineTo","args":[{"point":[554,737]}]}]},{"start":[511,325],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[511,325]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[511,325],"end":[511.5,325]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,325],"end":[512,325]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[534,325],"end":[554,329.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[574,334],"end":[591,343]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[646,368],"end":[676,424.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[706,481],"end":[698,540]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[691,588],"end":[659.5,628]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[628,668],"end":[583,687]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[532,707],"end":[476,696]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[420,685],"end":[381,647]}]}]},{"tag":"LineTo","args":[{"point":[381,647]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[355,621],"end":[340,586]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[325,551],"end":[325,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[325,502],"end":[326,492.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[327,483],"end":[328,475]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[341,412],"end":[394,369]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[447,326],"end":[511,325]}]}]}]},{"start":[301,425],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[301,424]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[310,402],"end":[323.5,382.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[337,363],"end":[354,347]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[385,317],"end":[431.5,299]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,281],"end":[536,285]}]}]},{"tag":"LineTo","args":[{"point":[972,285]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[939,219],"end":[891,167]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[842,114],"end":[782,77]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[722,40],"end":[654,20]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[585,0],"end":[512,0]}]}]},{"tag":"LineTo","args":[{"point":[512,0]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[448,0],"end":[388,15]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[329,30],"end":[276,57.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[223,85],"end":[177,124]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[132,163],"end":[96,212]}]}]},{"tag":"LineTo","args":[{"point":[301,425]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"googledrive","codePoint":59703},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[189,956],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[853,956]}]},{"tag":"LineTo","args":[{"point":[1024,660]}]},{"tag":"LineTo","args":[{"point":[360,660]}]},{"tag":"LineTo","args":[{"point":[189,956]}]}]},{"start":[341,660],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[503,380]}]},{"tag":"LineTo","args":[{"point":[332,84]}]},{"tag":"LineTo","args":[{"point":[0,660]}]},{"tag":"LineTo","args":[{"point":[171,956]}]},{"tag":"LineTo","args":[{"point":[341,660]}]}]},{"start":[1015,644],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[683,68]}]},{"tag":"LineTo","args":[{"point":[341,68]}]},{"tag":"LineTo","args":[{"point":[673,644]}]},{"tag":"LineTo","args":[{"point":[1015,644]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"googleplay","codePoint":59704},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[544,508],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[57,1024]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[53,1020],"end":[51,1015.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[49,1011],"end":[49,1004]}]}]},{"tag":"LineTo","args":[{"point":[49,13]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[49,9],"end":[50,6]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[51,3],"end":[52,0]}]}]},{"tag":"LineTo","args":[{"point":[544,508]}]}]},{"start":[577,542],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[169,977]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[216,950],"end":[277,915]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[339,880],"end":[393.5,848.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[448,817],"end":[486,796]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[523,775],"end":[523,775]}]}]},{"tag":"LineTo","args":[{"point":[703,672]}]},{"tag":"LineTo","args":[{"point":[577,542]}]}]},{"start":[611,507],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[748,362]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[757,368],"end":[788,386]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[820,404],"end":[855,424.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[890,445],"end":[920,462]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[950,479],"end":[958,483]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[974,491],"end":[974.5,504]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[975,517],"end":[957,528]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[948,533],"end":[917,550]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[886,568],"end":[850.5,588]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[815,608],"end":[785,625]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[754,643],"end":[746,647]}]}]},{"tag":"LineTo","args":[{"point":[611,507]}]}]},{"start":[577,473],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[128,8]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[165,29],"end":[231,67]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,105],"end":[362.5,142]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[427,179],"end":[475,206]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[523,234],"end":[523,234]}]}]},{"tag":"LineTo","args":[{"point":[704,337]}]},{"tag":"LineTo","args":[{"point":[577,473]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"html5","codePoint":59705},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[64,0],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[146,920]}]},{"tag":"LineTo","args":[{"point":[511,1024]}]},{"tag":"LineTo","args":[{"point":[879,920]}]},{"tag":"LineTo","args":[{"point":[960,0]}]},{"tag":"LineTo","args":[{"point":[64,0]}]}]},{"start":[364,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[773,416]}]},{"tag":"LineTo","args":[{"point":[742,764]}]},{"tag":"LineTo","args":[{"point":[512,826]}]},{"tag":"LineTo","args":[{"point":[281,764]}]},{"tag":"LineTo","args":[{"point":[267,586]}]},{"tag":"LineTo","args":[{"point":[378,586]}]},{"tag":"LineTo","args":[{"point":[386,676]}]},{"tag":"LineTo","args":[{"point":[512,710]}]},{"tag":"LineTo","args":[{"point":[636,676]}]},{"tag":"LineTo","args":[{"point":[650,530]}]},{"tag":"LineTo","args":[{"point":[261,530]}]},{"tag":"LineTo","args":[{"point":[231,188]}]},{"tag":"LineTo","args":[{"point":[793,188]}]},{"tag":"LineTo","args":[{"point":[783,300]}]},{"tag":"LineTo","args":[{"point":[354,300]}]},{"tag":"LineTo","args":[{"point":[364,416]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"instagram","codePoint":59706},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,0],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[616,0],"end":[649,0.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,1],"end":[723,3]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[764,5],"end":[793.5,11]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[823,17],"end":[847,27]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[873,37],"end":[895,51]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[917,65],"end":[938,86]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[959,107],"end":[973,129]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[987,151],"end":[997,177]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1007,201],"end":[1013,230.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1019,260],"end":[1021,301]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1023,342],"end":[1023.5,375]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,408],"end":[1024,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,616],"end":[1023.5,649]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1023,682],"end":[1021,723]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1019,764],"end":[1013,793.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1007,823],"end":[997,847]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[987,873],"end":[973,895]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[959,917],"end":[938,938]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[917,959],"end":[895,973]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[873,987],"end":[847,997]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[823,1007],"end":[793.5,1013]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[764,1019],"end":[723,1021]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,1023],"end":[649,1023.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[616,1024],"end":[512,1024]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[408,1024],"end":[375,1023.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,1023],"end":[301,1021]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[260,1019],"end":[230.5,1013]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[201,1007],"end":[177,997]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[151,987],"end":[129,973]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[107,959],"end":[86,938]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[65,917],"end":[51,895]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[37,873],"end":[27,847]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[17,823],"end":[11,793.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[5,764],"end":[3,723]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1,682],"end":[0.5,649]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,616],"end":[0,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,408],"end":[0.5,375]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1,342],"end":[3,301]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[5,260],"end":[11,230.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[17,201],"end":[27,177]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[37,151],"end":[51,129]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[65,107],"end":[86,86]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[107,65],"end":[129,51]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[151,37],"end":[177,27]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[201,17],"end":[230.5,11]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[260,5],"end":[301,3]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,1],"end":[375,0.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[408,0],"end":[512,0]}]}]}]},{"start":[512,92],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[510,91]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[407,91],"end":[375.5,91.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[344,92],"end":[303,93]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[265,95],"end":[243,100.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[221,106],"end":[208,111]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[190,118],"end":[176.5,127]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[163,136],"end":[149,150]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,163],"end":[126.5,176.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[117,190],"end":[111,209]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[105,222],"end":[100,244.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[95,267],"end":[93,304]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[91,345],"end":[90.5,377]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[90,409],"end":[90,511]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[90,614],"end":[90.5,646]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[91,678],"end":[93,718]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[95,755],"end":[100,777.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[105,800],"end":[111,813]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[117,831],"end":[126.5,845]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,859],"end":[149,872]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[163,886],"end":[176.5,894.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[190,903],"end":[208,911]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[221,916],"end":[243.5,921.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[266,927],"end":[303,929]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[344,930],"end":[376,931]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[408,932],"end":[511,932]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[613,932],"end":[645,931.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[677,931],"end":[718,929]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[755,927],"end":[777.5,921.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[800,916],"end":[813,911]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[831,904],"end":[845,895]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[859,886],"end":[872,873]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[886,859],"end":[894.5,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[903,832],"end":[911,814]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[916,800],"end":[921.5,778]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[927,756],"end":[929,719]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[930,678],"end":[931,646.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[932,615],"end":[932,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[932,409],"end":[931.5,377.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[931,346],"end":[929,305]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[927,268],"end":[921.5,246]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[916,224],"end":[911,210]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[904,192],"end":[895,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[886,165],"end":[873,151]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[859,138],"end":[845.5,129]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,120],"end":[814,113]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[800,108],"end":[778,102.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[756,97],"end":[719,95]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[678,93],"end":[646,92.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[614,92],"end":[512,92]}]}]}]},{"start":[614,270],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[614,270]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[662,290],"end":[698,326]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[734,362],"end":[754,410]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[775,458],"end":[775,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[775,566],"end":[754,614]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[734,662],"end":[698,698]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[662,734],"end":[614,754]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[566,775],"end":[512,775]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[458,775],"end":[410,754]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[362,734],"end":[326,698]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,662],"end":[270,614]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[249,566],"end":[249,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[249,458],"end":[270,410]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,362],"end":[326,326]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[362,290],"end":[410,270]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[458,249],"end":[512,249]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[566,249],"end":[614,270]}]}]}]},{"start":[633,633],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[683,583],"end":[683,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[683,441],"end":[633,391]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[583,341],"end":[512,341]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[441,341],"end":[391,391]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[341,441],"end":[341,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[341,583],"end":[391,633]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[441,683],"end":[512,683]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[583,683],"end":[633,633]}]}]}]},{"start":[847,239],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[847,213],"end":[829,195]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[811,177],"end":[785,177]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[760,177],"end":[742,195]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[724,213],"end":[724,239]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[724,264],"end":[742,282]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[760,300],"end":[785,300]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[811,300],"end":[829,282]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[847,264],"end":[847,239]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"ionic","codePoint":59707},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[978,300],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1001,350],"end":[1012.5,403.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,457],"end":[1024,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,618],"end":[984,711]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[943,804],"end":[873.5,873.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[804,943],"end":[711,984]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,1024],"end":[512,1024]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[406,1024],"end":[313,984]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[220,943],"end":[150.5,873.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[81,804],"end":[40,711]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,618],"end":[0,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,406],"end":[40,313]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[81,220],"end":[150.5,150.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[220,81],"end":[313,40]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[406,0],"end":[512,0]}]}]},{"tag":"LineTo","args":[{"point":[512,0]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,0],"end":[512.5,0]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[513,0],"end":[513,0]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[577,0],"end":[636.5,15]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[696,30],"end":[747,57]}]}]},{"tag":"LineTo","args":[{"point":[756,62]}]},{"tag":"LineTo","args":[{"point":[748,69]}]},{"tag":"LineTo","args":[{"point":[748,69]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[733,81],"end":[721,96.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[709,112],"end":[701,131]}]}]},{"tag":"LineTo","args":[{"point":[698,137]}]},{"tag":"LineTo","args":[{"point":[691,134]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[649,114],"end":[604,104]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[559,94],"end":[512,94]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,94],"end":[349,127]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[273,159],"end":[216.5,216]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[160,273],"end":[127,349]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[94,426],"end":[94,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[94,598],"end":[127,675]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[159,751],"end":[216,807.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[273,864],"end":[349,897]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[425,930],"end":[512,930]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,930],"end":[675,897]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[751,864],"end":[807.5,807.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,751],"end":[897,674]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[930,598],"end":[930,512]}]}]},{"tag":"LineTo","args":[{"point":[930,512]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[930,512],"end":[930,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[930,512],"end":[930,511]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[930,468],"end":[921.5,427.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[913,387],"end":[898,351]}]}]},{"tag":"LineTo","args":[{"point":[895,345]}]},{"tag":"LineTo","args":[{"point":[902,342]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[921,335],"end":[937,324]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[953,313],"end":[966,298]}]}]},{"tag":"LineTo","args":[{"point":[974,290]}]},{"tag":"LineTo","args":[{"point":[978,300]}]}]},{"start":[512,279],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,279]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[560,279],"end":[603,297]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,315],"end":[677,347]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[709,379],"end":[727,421]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[745,464],"end":[745,512]}]}]},{"tag":"LineTo","args":[{"point":[745,512]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[745,560],"end":[727,603]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[709,645],"end":[677,677]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,709],"end":[603,727]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[560,745],"end":[512,745]}]}]},{"tag":"LineTo","args":[{"point":[512,745]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[464,745],"end":[421,727]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[379,709],"end":[347,677]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[315,645],"end":[297,603]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[279,560],"end":[279,512]}]}]},{"tag":"LineTo","args":[{"point":[279,512]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[279,464],"end":[297,421]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[315,379],"end":[347,347]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[379,315],"end":[421,297]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[464,279],"end":[512,279]}]}]}]},{"start":[953,193],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[953,149],"end":[922,118]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[891,87],"end":[847,87]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[803,87],"end":[772,118]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[741,149],"end":[741,193]}]}]},{"tag":"LineTo","args":[{"point":[741,193]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[741,237],"end":[772,268]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[803,299],"end":[847,299]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[891,299],"end":[922,268]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[953,237],"end":[953,193]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"javascript","codePoint":59708},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[0,1024],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[1024,1024]}]},{"tag":"LineTo","args":[{"point":[1024,0]}]},{"tag":"LineTo","args":[{"point":[0,0]}]},{"tag":"LineTo","args":[{"point":[0,1024]}]}]},{"start":[940,780],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[938,777]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[943,807],"end":[939.5,825.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[936,844],"end":[935,847]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[923,890],"end":[886,913]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[849,935],"end":[804,939.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[759,944],"end":[714,931]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[670,918],"end":[642,890]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[630,877],"end":[622,867.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[614,858],"end":[607,843]}]}]},{"tag":"LineTo","args":[{"point":[685,798]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[701,822],"end":[717.5,835.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[734,849],"end":[760,855]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[795,859],"end":[823.5,845.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[852,832],"end":[844,795]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[836,764],"end":[785,748.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[734,733],"end":[690,701]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[646,671],"end":[637.5,611]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[629,551],"end":[666,510]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[678,495],"end":[697.5,483.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[717,472],"end":[739,467]}]}]},{"tag":"LineTo","args":[{"point":[769,463]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[812,462],"end":[840.5,473.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[869,485],"end":[890,507]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[895,513],"end":[900.5,520]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[906,527],"end":[915,541]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[891,555],"end":[882,561]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[873,567],"end":[840,589]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,573],"end":[821,563.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[810,554],"end":[798,550]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[779,545],"end":[758.5,551.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[738,558],"end":[733,578]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[731,585],"end":[731.5,591.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[732,598],"end":[735,609]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[743,626],"end":[765.5,636]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[788,646],"end":[812,657]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[880,685],"end":[907.5,715]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[935,745],"end":[940,780]}]}]}]},{"start":[557,471],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[557,473]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[557,539],"end":[557,605]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[557,671],"end":[557,737]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[557,778],"end":[556.5,814]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[556,850],"end":[540,879]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[528,902],"end":[508,917]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[488,932],"end":[462,940]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[424,948],"end":[388.5,943.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[353,939],"end":[326,922]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[307,911],"end":[293,894.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[279,878],"end":[269,858]}]}]},{"tag":"LineTo","args":[{"point":[347,810]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[348,810],"end":[349,812.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[350,815],"end":[352,818]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[360,830],"end":[367.5,839]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[375,848],"end":[388,854]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[400,858],"end":[422,857]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[444,856],"end":[455,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[461,823],"end":[461,790.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[461,758],"end":[461,718]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[461,656],"end":[461,594.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[461,533],"end":[461,471]}]}]},{"tag":"LineTo","args":[{"point":[557,471]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"jekyll","codePoint":59709},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[344,1024],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[344,1024]}]},{"tag":"LineTo","args":[{"point":[345,1024]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[379,1024],"end":[408,1005.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[437,987],"end":[453,957]}]}]},{"tag":"LineTo","args":[{"point":[454,957]}]},{"tag":"LineTo","args":[{"point":[755,171]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[758,165],"end":[769.5,152.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[781,140],"end":[791,131]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[793,130],"end":[794.5,128]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[796,126],"end":[797,124]}]}]},{"tag":"LineTo","args":[{"point":[798,123]}]},{"tag":"LineTo","args":[{"point":[799,122]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[804,110],"end":[796,97.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[788,85],"end":[769,70]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[753,58],"end":[730.5,46]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[708,34],"end":[682,24]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,13],"end":[623.5,6.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,0],"end":[574,0]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[556,0],"end":[545,4.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[534,9],"end":[531,19]}]}]},{"tag":"LineTo","args":[{"point":[530,20]}]},{"tag":"LineTo","args":[{"point":[530,20]}]},{"tag":"LineTo","args":[{"point":[530,20]}]},{"tag":"LineTo","args":[{"point":[530,21]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[529,24],"end":[529,26.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[529,29],"end":[529,32]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[531,43],"end":[531.5,60]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[532,77],"end":[529,86]}]}]},{"tag":"LineTo","args":[{"point":[230,861]}]},{"tag":"LineTo","args":[{"point":[227,871]}]},{"tag":"LineTo","args":[{"point":[227,871]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[215,915],"end":[236,957]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[257,999],"end":[301,1016]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[312,1020],"end":[322.5,1022]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[333,1024],"end":[344,1024]}]}]}]},{"start":[251,865],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[548,92]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,77],"end":[552,54]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[550,31],"end":[550,27]}]}]},{"tag":"LineTo","args":[{"point":[550,26]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[550,24],"end":[555,22]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[560,20],"end":[573,20]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[592,20],"end":[619,26.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[646,33],"end":[674,43]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[698,53],"end":[719,64]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[740,75],"end":[755,86]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[771,98],"end":[775,105]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[779,112],"end":[779,114]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[779,114],"end":[778.5,114.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[778,115],"end":[778,115]}]}]},{"tag":"LineTo","args":[{"point":[777,116]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[773,120],"end":[756.5,136]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[740,152],"end":[736,164]}]}]},{"tag":"LineTo","args":[{"point":[439,936]}]},{"tag":"LineTo","args":[{"point":[438,939]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,968],"end":[400.5,985.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[375,1003],"end":[344,1003]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[335,1003],"end":[326,1001.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[317,1000],"end":[308,996]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[270,982],"end":[253,944]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[236,906],"end":[250,867]}]}]},{"tag":"LineTo","args":[{"point":[251,865]}]}]},{"start":[633,374],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[418,933]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[407,963],"end":[376.5,976.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[346,990],"end":[316,978]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[285,966],"end":[270.5,935.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,905],"end":[268,875]}]}]},{"tag":"LineTo","args":[{"point":[405,518]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[405,518],"end":[417.5,502]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[430,486],"end":[455,471]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[481,456],"end":[503.5,454]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[526,452],"end":[554,439]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,426],"end":[607.5,400]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[633,374],"end":[633,374]}]}]}]},{"start":[418,805.5],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[417,809],"end":[418,812]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[419,815],"end":[422.5,816.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,818],"end":[429,816]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[433,815],"end":[434,811.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[435,808],"end":[434,805]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[433,802],"end":[429.5,800.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,799],"end":[423,800]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[419,802],"end":[418,805.5]}]}]}]},{"start":[379,723],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[385,721],"end":[386.5,716]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,711],"end":[386,707]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,702],"end":[379,700]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[374,698],"end":[369,700]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[364,702],"end":[362,707]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[360,712],"end":[362,717]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[364,722],"end":[369,724]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[374,726],"end":[379,724]}]}]},{"tag":"LineTo","args":[{"point":[379,723]}]}]},{"start":[392,677],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[391,677]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[395,686],"end":[404.5,689.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[414,693],"end":[424,689]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[433,685],"end":[436.5,675.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[440,666],"end":[436,657]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[431,647],"end":[422,643.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[413,640],"end":[404,644]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[395,649],"end":[391.5,658.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,668],"end":[392,677]}]}]}]},{"start":[495,580],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[495,580]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[490,582],"end":[488,587]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[486,592],"end":[488,597]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[490,602],"end":[495.5,604]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[501,606],"end":[506,604]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[510,602],"end":[512,597]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[514,592],"end":[512,587]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[510,582],"end":[505,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[500,578],"end":[495,580]}]}]}]},{"start":[440,522],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[437,523],"end":[435.5,526.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[434,530],"end":[435,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[437,536],"end":[440,537.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[443,539],"end":[447,537]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[450,536],"end":[451.5,532.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[453,529],"end":[451,526]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[450,523],"end":[446.5,521.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[443,520],"end":[440,522]}]}]}]},{"start":[584,49],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[584,49]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[580,57],"end":[600.5,71.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[621,86],"end":[653,99]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[685,111],"end":[710,114]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[735,117],"end":[738,108]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[742,100],"end":[721.5,85.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[701,71],"end":[669,58]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[637,46],"end":[612,43]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[587,40],"end":[584,49]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"linkedin","codePoint":59710},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[872,873],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[872,604]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[872,506],"end":[839,439]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[806,372],"end":[690,372]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[635,372],"end":[598.5,397]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[562,422],"end":[547,451]}]}]},{"tag":"LineTo","args":[{"point":[545,451]}]},{"tag":"LineTo","args":[{"point":[545,384]}]},{"tag":"LineTo","args":[{"point":[399,384]}]},{"tag":"LineTo","args":[{"point":[399,873]}]},{"tag":"LineTo","args":[{"point":[551,873]}]},{"tag":"LineTo","args":[{"point":[551,631]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[551,583],"end":[566.5,544]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,505],"end":[642,505]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[700,505],"end":[710.5,549]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[721,593],"end":[721,635]}]}]},{"tag":"LineTo","args":[{"point":[721,873]}]},{"tag":"LineTo","args":[{"point":[872,873]}]}]},{"start":[228,317],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[264,317],"end":[290,291]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[316,265],"end":[316,229]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[316,193],"end":[290,167]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[264,141],"end":[228,141]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[191,141],"end":[165.5,167]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[140,193],"end":[140,229]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[140,265],"end":[165.5,291]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[191,317],"end":[228,317]}]}]}]},{"start":[304,384],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[152,384]}]},{"tag":"LineTo","args":[{"point":[152,873]}]},{"tag":"LineTo","args":[{"point":[304,873]}]},{"tag":"LineTo","args":[{"point":[304,384]}]}]},{"start":[948,0],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[948,0]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[979,0],"end":[1001.5,21.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,43],"end":[1024,74]}]}]},{"tag":"LineTo","args":[{"point":[1024,950]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,981],"end":[1001.5,1002.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[979,1024],"end":[948,1024]}]}]},{"tag":"LineTo","args":[{"point":[76,1024]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[44,1024],"end":[22,1002.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,981],"end":[0,950]}]}]},{"tag":"LineTo","args":[{"point":[0,74]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,43],"end":[22,21.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[44,0],"end":[76,0]}]}]},{"tag":"LineTo","args":[{"point":[948,0]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"markdown","codePoint":59711},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[950,827],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[950,827]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[981,827],"end":[1002.5,805.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,784],"end":[1024,753]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,753],"end":[1024,753]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,753],"end":[1024,753]}]}]},{"tag":"LineTo","args":[{"point":[1024,271]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,240],"end":[1002.5,218.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[981,197],"end":[950,197]}]}]},{"tag":"LineTo","args":[{"point":[74,197]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[43,197],"end":[21.5,218.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,240],"end":[0,271]}]}]},{"tag":"LineTo","args":[{"point":[0,753]}]},{"tag":"LineTo","args":[{"point":[0,753]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,784],"end":[21.5,805.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[43,827],"end":[74,827]}]}]},{"tag":"LineTo","args":[{"point":[950,827]}]}]},{"start":[148,679],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[148,345]}]},{"tag":"LineTo","args":[{"point":[246,345]}]},{"tag":"LineTo","args":[{"point":[345,468]}]},{"tag":"LineTo","args":[{"point":[443,345]}]},{"tag":"LineTo","args":[{"point":[542,345]}]},{"tag":"LineTo","args":[{"point":[542,679]}]},{"tag":"LineTo","args":[{"point":[443,679]}]},{"tag":"LineTo","args":[{"point":[443,487]}]},{"tag":"LineTo","args":[{"point":[345,610]}]},{"tag":"LineTo","args":[{"point":[246,487]}]},{"tag":"LineTo","args":[{"point":[246,679]}]},{"tag":"LineTo","args":[{"point":[148,679]}]}]},{"start":[758,684],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[610,512]}]},{"tag":"LineTo","args":[{"point":[709,512]}]},{"tag":"LineTo","args":[{"point":[709,345]}]},{"tag":"LineTo","args":[{"point":[807,345]}]},{"tag":"LineTo","args":[{"point":[807,512]}]},{"tag":"LineTo","args":[{"point":[906,512]}]},{"tag":"LineTo","args":[{"point":[758,684]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"npm","codePoint":59712},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[1024,313],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[1024,654]}]},{"tag":"LineTo","args":[{"point":[512,654]}]},{"tag":"LineTo","args":[{"point":[512,711]}]},{"tag":"LineTo","args":[{"point":[284,711]}]},{"tag":"LineTo","args":[{"point":[284,654]}]},{"tag":"LineTo","args":[{"point":[0,654]}]},{"tag":"LineTo","args":[{"point":[0,313]}]},{"tag":"LineTo","args":[{"point":[1024,313]}]}]},{"start":[284,370],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[57,370]}]},{"tag":"LineTo","args":[{"point":[57,597]}]},{"tag":"LineTo","args":[{"point":[171,597]}]},{"tag":"LineTo","args":[{"point":[171,427]}]},{"tag":"LineTo","args":[{"point":[228,427]}]},{"tag":"LineTo","args":[{"point":[228,597]}]},{"tag":"LineTo","args":[{"point":[284,597]}]},{"tag":"LineTo","args":[{"point":[284,370]}]}]},{"start":[569,597],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[569,370]}]},{"tag":"LineTo","args":[{"point":[341,370]}]},{"tag":"LineTo","args":[{"point":[341,654]}]},{"tag":"LineTo","args":[{"point":[455,654]}]},{"tag":"LineTo","args":[{"point":[455,597]}]},{"tag":"LineTo","args":[{"point":[569,597]}]}]},{"start":[967,597],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[967,370]}]},{"tag":"LineTo","args":[{"point":[626,370]}]},{"tag":"LineTo","args":[{"point":[626,597]}]},{"tag":"LineTo","args":[{"point":[740,597]}]},{"tag":"LineTo","args":[{"point":[740,427]}]},{"tag":"LineTo","args":[{"point":[796,427]}]},{"tag":"LineTo","args":[{"point":[796,597]}]},{"tag":"LineTo","args":[{"point":[853,597]}]},{"tag":"LineTo","args":[{"point":[853,427]}]},{"tag":"LineTo","args":[{"point":[910,427]}]},{"tag":"LineTo","args":[{"point":[910,597]}]},{"tag":"LineTo","args":[{"point":[967,597]}]}]},{"start":[455,540],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,540]}]},{"tag":"LineTo","args":[{"point":[512,427]}]},{"tag":"LineTo","args":[{"point":[455,427]}]},{"tag":"LineTo","args":[{"point":[455,540]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"python","codePoint":59713},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[611,8],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[565,2]}]},{"tag":"LineTo","args":[{"point":[511,0]}]},{"tag":"LineTo","args":[{"point":[475,1]}]},{"tag":"LineTo","args":[{"point":[442,3]}]},{"tag":"LineTo","args":[{"point":[412,5]}]},{"tag":"LineTo","args":[{"point":[384,9]}]},{"tag":"LineTo","args":[{"point":[360,15]}]},{"tag":"LineTo","args":[{"point":[338,21]}]},{"tag":"LineTo","args":[{"point":[319,29]}]},{"tag":"LineTo","args":[{"point":[303,37]}]},{"tag":"LineTo","args":[{"point":[290,47]}]},{"tag":"LineTo","args":[{"point":[279,58]}]},{"tag":"LineTo","args":[{"point":[272,70]}]},{"tag":"LineTo","args":[{"point":[267,83]}]},{"tag":"LineTo","args":[{"point":[265,98]}]},{"tag":"LineTo","args":[{"point":[266,113]}]},{"tag":"LineTo","args":[{"point":[266,231]}]},{"tag":"LineTo","args":[{"point":[515,231]}]},{"tag":"LineTo","args":[{"point":[515,266]}]},{"tag":"LineTo","args":[{"point":[167,266]}]},{"tag":"LineTo","args":[{"point":[165,266]}]},{"tag":"LineTo","args":[{"point":[158,266]}]},{"tag":"LineTo","args":[{"point":[148,266]}]},{"tag":"LineTo","args":[{"point":[134,268]}]},{"tag":"LineTo","args":[{"point":[119,273]}]},{"tag":"LineTo","args":[{"point":[102,279]}]},{"tag":"LineTo","args":[{"point":[84,290]}]},{"tag":"LineTo","args":[{"point":[66,304]}]},{"tag":"LineTo","args":[{"point":[49,323]}]},{"tag":"LineTo","args":[{"point":[33,347]}]},{"tag":"LineTo","args":[{"point":[20,377]}]},{"tag":"LineTo","args":[{"point":[9,414]}]},{"tag":"LineTo","args":[{"point":[3,459]}]},{"tag":"LineTo","args":[{"point":[0,511]}]},{"tag":"LineTo","args":[{"point":[2,563]}]},{"tag":"LineTo","args":[{"point":[8,608]}]},{"tag":"LineTo","args":[{"point":[17,646]}]},{"tag":"LineTo","args":[{"point":[29,677]}]},{"tag":"LineTo","args":[{"point":[43,702]}]},{"tag":"LineTo","args":[{"point":[58,721]}]},{"tag":"LineTo","args":[{"point":[73,737]}]},{"tag":"LineTo","args":[{"point":[88,748]}]},{"tag":"LineTo","args":[{"point":[103,756]}]},{"tag":"LineTo","args":[{"point":[117,761]}]},{"tag":"LineTo","args":[{"point":[129,764]}]},{"tag":"LineTo","args":[{"point":[138,765]}]},{"tag":"LineTo","args":[{"point":[233,765]}]},{"tag":"LineTo","args":[{"point":[233,634]}]},{"tag":"LineTo","args":[{"point":[234,625]}]},{"tag":"LineTo","args":[{"point":[236,614]}]},{"tag":"LineTo","args":[{"point":[239,600]}]},{"tag":"LineTo","args":[{"point":[243,585]}]},{"tag":"LineTo","args":[{"point":[249,570]}]},{"tag":"LineTo","args":[{"point":[258,554]}]},{"tag":"LineTo","args":[{"point":[269,539]}]},{"tag":"LineTo","args":[{"point":[283,526]}]},{"tag":"LineTo","args":[{"point":[301,514]}]},{"tag":"LineTo","args":[{"point":[322,505]}]},{"tag":"LineTo","args":[{"point":[347,499]}]},{"tag":"LineTo","args":[{"point":[377,497]}]},{"tag":"LineTo","args":[{"point":[631,497]}]},{"tag":"LineTo","args":[{"point":[640,496]}]},{"tag":"LineTo","args":[{"point":[652,494]}]},{"tag":"LineTo","args":[{"point":[664,491]}]},{"tag":"LineTo","args":[{"point":[678,487]}]},{"tag":"LineTo","args":[{"point":[693,481]}]},{"tag":"LineTo","args":[{"point":[708,473]}]},{"tag":"LineTo","args":[{"point":[722,462]}]},{"tag":"LineTo","args":[{"point":[735,449]}]},{"tag":"LineTo","args":[{"point":[746,433]}]},{"tag":"LineTo","args":[{"point":[755,413]}]},{"tag":"LineTo","args":[{"point":[761,390]}]},{"tag":"LineTo","args":[{"point":[763,363]}]},{"tag":"LineTo","args":[{"point":[763,135]}]},{"tag":"LineTo","args":[{"point":[763,129]}]},{"tag":"LineTo","args":[{"point":[762,121]}]},{"tag":"LineTo","args":[{"point":[761,110]}]},{"tag":"LineTo","args":[{"point":[756,97]}]},{"tag":"LineTo","args":[{"point":[750,83]}]},{"tag":"LineTo","args":[{"point":[739,68]}]},{"tag":"LineTo","args":[{"point":[724,54]}]},{"tag":"LineTo","args":[{"point":[705,40]}]},{"tag":"LineTo","args":[{"point":[680,27]}]},{"tag":"LineTo","args":[{"point":[649,16]}]},{"tag":"LineTo","args":[{"point":[611,8]}]}]},{"start":[356,83],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[373,79]}]},{"tag":"LineTo","args":[{"point":[391,83]}]},{"tag":"LineTo","args":[{"point":[405,92]}]},{"tag":"LineTo","args":[{"point":[415,106]}]},{"tag":"LineTo","args":[{"point":[418,124]}]},{"tag":"LineTo","args":[{"point":[415,141]}]},{"tag":"LineTo","args":[{"point":[405,156]}]},{"tag":"LineTo","args":[{"point":[391,165]}]},{"tag":"LineTo","args":[{"point":[373,169]}]},{"tag":"LineTo","args":[{"point":[356,165]}]},{"tag":"LineTo","args":[{"point":[342,156]}]},{"tag":"LineTo","args":[{"point":[332,141]}]},{"tag":"LineTo","args":[{"point":[329,124]}]},{"tag":"LineTo","args":[{"point":[332,106]}]},{"tag":"LineTo","args":[{"point":[342,92]}]},{"tag":"LineTo","args":[{"point":[356,83]}]}]},{"start":[900,261],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[891,259]}]},{"tag":"LineTo","args":[{"point":[885,259]}]},{"tag":"LineTo","args":[{"point":[796,259]}]},{"tag":"LineTo","args":[{"point":[796,390]}]},{"tag":"LineTo","args":[{"point":[795,399]}]},{"tag":"LineTo","args":[{"point":[794,410]}]},{"tag":"LineTo","args":[{"point":[791,424]}]},{"tag":"LineTo","args":[{"point":[786,439]}]},{"tag":"LineTo","args":[{"point":[780,454]}]},{"tag":"LineTo","args":[{"point":[771,470]}]},{"tag":"LineTo","args":[{"point":[760,485]}]},{"tag":"LineTo","args":[{"point":[746,498]}]},{"tag":"LineTo","args":[{"point":[728,510]}]},{"tag":"LineTo","args":[{"point":[707,519]}]},{"tag":"LineTo","args":[{"point":[682,525]}]},{"tag":"LineTo","args":[{"point":[652,527]}]},{"tag":"LineTo","args":[{"point":[403,527]}]},{"tag":"LineTo","args":[{"point":[398,528]}]},{"tag":"LineTo","args":[{"point":[389,529]}]},{"tag":"LineTo","args":[{"point":[378,530]}]},{"tag":"LineTo","args":[{"point":[365,533]}]},{"tag":"LineTo","args":[{"point":[351,537]}]},{"tag":"LineTo","args":[{"point":[336,543]}]},{"tag":"LineTo","args":[{"point":[321,552]}]},{"tag":"LineTo","args":[{"point":[307,562]}]},{"tag":"LineTo","args":[{"point":[294,576]}]},{"tag":"LineTo","args":[{"point":[283,592]}]},{"tag":"LineTo","args":[{"point":[274,611]}]},{"tag":"LineTo","args":[{"point":[268,634]}]},{"tag":"LineTo","args":[{"point":[266,662]}]},{"tag":"LineTo","args":[{"point":[266,890]}]},{"tag":"LineTo","args":[{"point":[266,895]}]},{"tag":"LineTo","args":[{"point":[267,904]}]},{"tag":"LineTo","args":[{"point":[268,914]}]},{"tag":"LineTo","args":[{"point":[273,927]}]},{"tag":"LineTo","args":[{"point":[279,941]}]},{"tag":"LineTo","args":[{"point":[290,956]}]},{"tag":"LineTo","args":[{"point":[305,970]}]},{"tag":"LineTo","args":[{"point":[324,984]}]},{"tag":"LineTo","args":[{"point":[349,997]}]},{"tag":"LineTo","args":[{"point":[380,1008]}]},{"tag":"LineTo","args":[{"point":[419,1016]}]},{"tag":"LineTo","args":[{"point":[464,1022]}]},{"tag":"LineTo","args":[{"point":[518,1024]}]},{"tag":"LineTo","args":[{"point":[554,1024]}]},{"tag":"LineTo","args":[{"point":[587,1022]}]},{"tag":"LineTo","args":[{"point":[617,1019]}]},{"tag":"LineTo","args":[{"point":[645,1015]}]},{"tag":"LineTo","args":[{"point":[669,1009]}]},{"tag":"LineTo","args":[{"point":[691,1003]}]},{"tag":"LineTo","args":[{"point":[710,996]}]},{"tag":"LineTo","args":[{"point":[726,987]}]},{"tag":"LineTo","args":[{"point":[739,977]}]},{"tag":"LineTo","args":[{"point":[750,966]}]},{"tag":"LineTo","args":[{"point":[757,954]}]},{"tag":"LineTo","args":[{"point":[762,941]}]},{"tag":"LineTo","args":[{"point":[764,926]}]},{"tag":"LineTo","args":[{"point":[763,911]}]},{"tag":"LineTo","args":[{"point":[763,793]}]},{"tag":"LineTo","args":[{"point":[514,793]}]},{"tag":"LineTo","args":[{"point":[514,758]}]},{"tag":"LineTo","args":[{"point":[864,758]}]},{"tag":"LineTo","args":[{"point":[871,759]}]},{"tag":"LineTo","args":[{"point":[881,758]}]},{"tag":"LineTo","args":[{"point":[895,756]}]},{"tag":"LineTo","args":[{"point":[911,752]}]},{"tag":"LineTo","args":[{"point":[928,745]}]},{"tag":"LineTo","args":[{"point":[945,735]}]},{"tag":"LineTo","args":[{"point":[963,721]}]},{"tag":"LineTo","args":[{"point":[980,701]}]},{"tag":"LineTo","args":[{"point":[996,677]}]},{"tag":"LineTo","args":[{"point":[1009,647]}]},{"tag":"LineTo","args":[{"point":[1020,610]}]},{"tag":"LineTo","args":[{"point":[1027,566]}]},{"tag":"LineTo","args":[{"point":[1029,513]}]},{"tag":"LineTo","args":[{"point":[1027,461]}]},{"tag":"LineTo","args":[{"point":[1021,416]}]},{"tag":"LineTo","args":[{"point":[1012,379]}]},{"tag":"LineTo","args":[{"point":[1000,348]}]},{"tag":"LineTo","args":[{"point":[986,323]}]},{"tag":"LineTo","args":[{"point":[972,303]}]},{"tag":"LineTo","args":[{"point":[956,288]}]},{"tag":"LineTo","args":[{"point":[941,276]}]},{"tag":"LineTo","args":[{"point":[926,268]}]},{"tag":"LineTo","args":[{"point":[912,263]}]},{"tag":"LineTo","args":[{"point":[900,261]}]}]},{"start":[638,859],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[656,855]}]},{"tag":"LineTo","args":[{"point":[673,859]}]},{"tag":"LineTo","args":[{"point":[687,869]}]},{"tag":"LineTo","args":[{"point":[697,883]}]},{"tag":"LineTo","args":[{"point":[701,900]}]},{"tag":"LineTo","args":[{"point":[697,918]}]},{"tag":"LineTo","args":[{"point":[687,932]}]},{"tag":"LineTo","args":[{"point":[673,942]}]},{"tag":"LineTo","args":[{"point":[656,945]}]},{"tag":"LineTo","args":[{"point":[638,942]}]},{"tag":"LineTo","args":[{"point":[624,932]}]},{"tag":"LineTo","args":[{"point":[614,918]}]},{"tag":"LineTo","args":[{"point":[611,900]}]},{"tag":"LineTo","args":[{"point":[614,883]}]},{"tag":"LineTo","args":[{"point":[624,869]}]},{"tag":"LineTo","args":[{"point":[638,859]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"react","codePoint":59714},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,421],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[550,421],"end":[576.5,447.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[603,474],"end":[603,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[603,550],"end":[576.5,576.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[550,603],"end":[512,603]}]}]},{"tag":"LineTo","args":[{"point":[512,603]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[474,603],"end":[447.5,576.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[421,550],"end":[421,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[421,474],"end":[447.5,447.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[474,421],"end":[512,421]}]}]}]},{"start":[256,694],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[262,674]}]},{"tag":"LineTo","args":[{"point":[264,667]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,627],"end":[289.5,590]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[304,553],"end":[320,521]}]}]},{"tag":"LineTo","args":[{"point":[324,512]}]},{"tag":"LineTo","args":[{"point":[320,503]}]},{"tag":"LineTo","args":[{"point":[323,509]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[305,472],"end":[290,433.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,395],"end":[262,350]}]}]},{"tag":"LineTo","args":[{"point":[256,330]}]},{"tag":"LineTo","args":[{"point":[236,335]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[124,364],"end":[62,410]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,456],"end":[0,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,568],"end":[62,614]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[124,660],"end":[236,688]}]}]},{"tag":"LineTo","args":[{"point":[256,694]}]}]},{"start":[227,382],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[229,389]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[240,423],"end":[252.5,454]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[265,485],"end":[277,512]}]}]},{"tag":"LineTo","args":[{"point":[280,505]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[265,537],"end":[252,570]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[239,603],"end":[227,642]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[141,618],"end":[92,583]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[43,548],"end":[43,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[43,475],"end":[92,440.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[141,406],"end":[227,382]}]}]}]},{"start":[768,694],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[788,688]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[900,660],"end":[962,614]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,568],"end":[1024,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,456],"end":[962,410]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[900,364],"end":[788,335]}]}]},{"tag":"LineTo","args":[{"point":[768,330]}]},{"tag":"LineTo","args":[{"point":[762,350]}]},{"tag":"LineTo","args":[{"point":[760,357]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[748,396],"end":[734,433.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[720,471],"end":[704,503]}]}]},{"tag":"LineTo","args":[{"point":[699,512]}]},{"tag":"LineTo","args":[{"point":[704,521]}]},{"tag":"LineTo","args":[{"point":[701,515]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[719,551],"end":[734,590]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[749,629],"end":[762,674]}]}]},{"tag":"LineTo","args":[{"point":[768,694]}]}]},{"start":[747,512],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[744,518]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[759,487],"end":[772,454]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[785,421],"end":[797,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[883,406],"end":[932,440.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[981,475],"end":[981,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[981,548],"end":[932,583]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[883,618],"end":[797,642]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[787,610],"end":[774.5,577.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[762,545],"end":[747,512]}]}]}]},{"start":[227,382],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[247,377]}]},{"tag":"LineTo","args":[{"point":[240,378]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[280,368],"end":[321.5,361]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[363,354],"end":[408,351]}]}]},{"tag":"LineTo","args":[{"point":[418,350]}]},{"tag":"LineTo","args":[{"point":[424,341]}]},{"tag":"LineTo","args":[{"point":[426,338]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[449,305],"end":[474.5,274]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[500,243],"end":[527,215]}]}]},{"tag":"LineTo","args":[{"point":[542,200]}]},{"tag":"LineTo","args":[{"point":[527,185]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[447,103],"end":[375,72.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[303,42],"end":[256,69]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[208,97],"end":[198.5,173.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[189,250],"end":[221,362]}]}]},{"tag":"LineTo","args":[{"point":[227,382]}]}]},{"start":[307,99],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[341,99],"end":[386.5,125.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[432,152],"end":[482,200]}]}]},{"tag":"LineTo","args":[{"point":[483,200]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[460,225],"end":[438,252]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[416,279],"end":[395,309]}]}]},{"tag":"LineTo","args":[{"point":[390,309]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[354,313],"end":[320,318]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[286,323],"end":[257,330]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[235,244],"end":[240.5,184]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[246,124],"end":[277,106]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[284,102],"end":[291.5,100.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[299,99],"end":[307,99]}]}]}]},{"start":[717,968],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[717,968]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[717,968],"end":[717.5,968]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[718,968],"end":[718,968]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[732,968],"end":[744.5,964.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[757,961],"end":[768,954]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[816,927],"end":[825.5,850]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[835,773],"end":[803,662]}]}]},{"tag":"LineTo","args":[{"point":[797,642]}]},{"tag":"LineTo","args":[{"point":[777,647]}]},{"tag":"LineTo","args":[{"point":[784,646]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[744,656],"end":[702.5,662.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[661,669],"end":[616,673]}]}]},{"tag":"LineTo","args":[{"point":[606,674]}]},{"tag":"LineTo","args":[{"point":[600,682]}]},{"tag":"LineTo","args":[{"point":[598,685]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[575,718],"end":[549.5,749]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[524,780],"end":[497,809]}]}]},{"tag":"LineTo","args":[{"point":[482,824]}]},{"tag":"LineTo","args":[{"point":[497,839]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[557,901],"end":[614,934.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[671,968],"end":[717,968]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[717,968],"end":[717,968]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[717,968],"end":[717,968]}]}]}]},{"start":[542,823],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[541,824]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,799],"end":[586,772]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,745],"end":[629,715]}]}]},{"tag":"LineTo","args":[{"point":[633,714]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[669,711],"end":[703.5,705.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[738,700],"end":[767,693]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[789,779],"end":[783.5,839]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[778,899],"end":[747,918]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[740,921],"end":[732.5,923]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[725,925],"end":[717,925]}]}]},{"tag":"LineTo","args":[{"point":[717,925]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[683,925],"end":[637.5,898.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[592,872],"end":[542,823]}]}]}]},{"start":[803,362],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[835,250],"end":[825.5,173.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[816,97],"end":[768,69]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[720,42],"end":[648,72.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,103],"end":[497,185]}]}]},{"tag":"LineTo","args":[{"point":[482,200]}]},{"tag":"LineTo","args":[{"point":[497,215]}]},{"tag":"LineTo","args":[{"point":[496,215]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[524,243],"end":[549.5,274.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[575,306],"end":[600,341]}]}]},{"tag":"LineTo","args":[{"point":[606,350]}]},{"tag":"LineTo","args":[{"point":[616,351]}]},{"tag":"LineTo","args":[{"point":[619,351]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[662,354],"end":[702,361]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[742,368],"end":[777,377]}]}]},{"tag":"LineTo","args":[{"point":[797,382]}]},{"tag":"LineTo","args":[{"point":[803,362]}]}]},{"start":[629,309],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[627,306]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[607,278],"end":[585.5,251.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,225],"end":[542,200]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[604,139],"end":[659.5,113.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[715,88],"end":[747,106]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[778,124],"end":[783.5,184]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[789,244],"end":[767,330]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[735,323],"end":[700.5,317.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[666,312],"end":[629,309]}]}]}]},{"start":[307,968],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[353,968],"end":[409.5,934.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[466,901],"end":[527,839]}]}]},{"tag":"LineTo","args":[{"point":[542,824]}]},{"tag":"LineTo","args":[{"point":[527,809]}]},{"tag":"LineTo","args":[{"point":[528,809]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[500,780],"end":[474,749]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[448,718],"end":[424,682]}]}]},{"tag":"LineTo","args":[{"point":[418,674]}]},{"tag":"LineTo","args":[{"point":[408,673]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[365,669],"end":[324.5,662.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[284,656],"end":[247,647]}]}]},{"tag":"LineTo","args":[{"point":[227,642]}]},{"tag":"LineTo","args":[{"point":[221,662]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[189,773],"end":[198.5,850]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[208,927],"end":[256,954]}]}]},{"tag":"LineTo","args":[{"point":[256,954]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[267,961],"end":[279.5,964.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[292,968],"end":[306,968]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[306,968],"end":[306.5,968]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[307,968],"end":[307,968]}]}]}]},{"start":[257,693],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[250,692]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[284,700],"end":[320,705.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[356,711],"end":[395,715]}]}]},{"tag":"LineTo","args":[{"point":[397,718]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[417,746],"end":[438.5,772.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[460,799],"end":[482,823]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[420,884],"end":[364.5,910]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[309,936],"end":[277,918]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[246,899],"end":[240.5,839]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[235,779],"end":[257,693]}]}]}]},{"start":[512,720],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[538,720],"end":[565,719]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[592,718],"end":[619,716]}]}]},{"tag":"LineTo","args":[{"point":[629,715]}]},{"tag":"LineTo","args":[{"point":[635,707]}]},{"tag":"LineTo","args":[{"point":[632,711]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[663,668],"end":[690,621]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[717,574],"end":[742,521]}]}]},{"tag":"LineTo","args":[{"point":[747,512]}]},{"tag":"LineTo","args":[{"point":[742,503]}]},{"tag":"LineTo","args":[{"point":[739,495]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[716,447],"end":[689.5,402]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[663,357],"end":[635,317]}]}]},{"tag":"LineTo","args":[{"point":[629,309]}]},{"tag":"LineTo","args":[{"point":[619,308]}]},{"tag":"LineTo","args":[{"point":[624,308]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[596,306],"end":[568,305]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[540,304],"end":[512,304]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[484,304],"end":[456.5,305]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[429,306],"end":[405,308]}]}]},{"tag":"LineTo","args":[{"point":[395,309]}]},{"tag":"LineTo","args":[{"point":[389,317]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[373,339],"end":[359,362]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[345,385],"end":[331,408]}]}]},{"tag":"LineTo","args":[{"point":[335,402]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[321,424],"end":[308.5,448.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[296,473],"end":[282,503]}]}]},{"tag":"LineTo","args":[{"point":[277,512]}]},{"tag":"LineTo","args":[{"point":[282,521]}]},{"tag":"LineTo","args":[{"point":[285,529]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[296,553],"end":[308,575.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,598],"end":[331,616]}]}]},{"tag":"LineTo","args":[{"point":[335,622]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[348,645],"end":[362,666.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[376,688],"end":[389,707]}]}]},{"tag":"LineTo","args":[{"point":[395,715]}]},{"tag":"LineTo","args":[{"point":[405,716]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[432,718],"end":[459,719]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[486,720],"end":[512,720]}]}]}]},{"start":[418,674],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[421,678]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[395,640],"end":[371,599.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[347,559],"end":[325,512]}]}]},{"tag":"LineTo","args":[{"point":[328,505]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[348,463],"end":[371,424]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[394,385],"end":[418,350]}]}]},{"tag":"LineTo","args":[{"point":[414,350]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[438,348],"end":[462.5,347]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[487,346],"end":[512,346]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[537,346],"end":[561,347]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[585,348],"end":[606,350]}]}]},{"tag":"LineTo","args":[{"point":[603,346]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[629,383],"end":[653,424]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[677,465],"end":[699,512]}]}]},{"tag":"LineTo","args":[{"point":[696,519]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[676,561],"end":[653,600]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[630,639],"end":[606,674]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[558,677],"end":[512,677]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[466,677],"end":[418,674]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"stackexchange","codePoint":59715},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[927,665],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[97,665]}]},{"tag":"LineTo","args":[{"point":[97,709]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[97,765],"end":[136,804.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[175,844],"end":[229,844]}]}]},{"tag":"LineTo","args":[{"point":[582,844]}]},{"tag":"LineTo","args":[{"point":[582,1024]}]},{"tag":"LineTo","args":[{"point":[756,844]}]},{"tag":"LineTo","args":[{"point":[795,844]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[849,844],"end":[888,804.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[927,765],"end":[927,709]}]}]},{"tag":"LineTo","args":[{"point":[927,665]}]}]},{"start":[97,446],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[97,616]}]},{"tag":"LineTo","args":[{"point":[922,616]}]},{"tag":"LineTo","args":[{"point":[922,446]}]},{"tag":"LineTo","args":[{"point":[97,446]}]}]},{"start":[97,227],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[97,397]}]},{"tag":"LineTo","args":[{"point":[922,397]}]},{"tag":"LineTo","args":[{"point":[922,227]}]},{"tag":"LineTo","args":[{"point":[97,227]}]}]},{"start":[793,0],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[229,0]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[175,0],"end":[136,39.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[97,79],"end":[97,136]}]}]},{"tag":"LineTo","args":[{"point":[97,180]}]},{"tag":"LineTo","args":[{"point":[922,180]}]},{"tag":"LineTo","args":[{"point":[922,136]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[922,79],"end":[884,39.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[846,0],"end":[793,0]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"stackoverflow","codePoint":59716},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[810,933],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[170,933]}]},{"tag":"LineTo","args":[{"point":[170,660]}]},{"tag":"LineTo","args":[{"point":[79,660]}]},{"tag":"LineTo","args":[{"point":[79,1024]}]},{"tag":"LineTo","args":[{"point":[901,1024]}]},{"tag":"LineTo","args":[{"point":[901,660]}]},{"tag":"LineTo","args":[{"point":[810,660]}]},{"tag":"LineTo","args":[{"point":[810,933]}]}]},{"start":[261,751],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[719,751]}]},{"tag":"LineTo","args":[{"point":[719,842]}]},{"tag":"LineTo","args":[{"point":[261,842]}]},{"tag":"LineTo","args":[{"point":[261,751]}]}]},{"start":[272,635],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[291,547]}]},{"tag":"LineTo","args":[{"point":[738,640]}]},{"tag":"LineTo","args":[{"point":[719,728]}]},{"tag":"LineTo","args":[{"point":[272,635]}]}]},{"start":[330,419],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[368,336]}]},{"tag":"LineTo","args":[{"point":[782,529]}]},{"tag":"LineTo","args":[{"point":[744,612]}]},{"tag":"LineTo","args":[{"point":[330,419]}]}]},{"start":[446,215],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[446,215]}]},{"tag":"LineTo","args":[{"point":[504,146]}]},{"tag":"LineTo","args":[{"point":[854,438]}]},{"tag":"LineTo","args":[{"point":[796,507]}]},{"tag":"LineTo","args":[{"point":[446,215]}]}]},{"start":[945,367],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[871,422]}]},{"tag":"LineTo","args":[{"point":[598,55]}]},{"tag":"LineTo","args":[{"point":[672,0]}]},{"tag":"LineTo","args":[{"point":[945,367]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"telegram","codePoint":59717},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[1020,161],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1032,114],"end":[1008.5,94]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[985,74],"end":[954,87]}]}]},{"tag":"LineTo","args":[{"point":[47,437]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1,456],"end":[0,478.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[-1,501],"end":[36,512]}]}]},{"tag":"LineTo","args":[{"point":[269,585]}]},{"tag":"LineTo","args":[{"point":[350,849]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[358,870],"end":[360.5,879.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[363,889],"end":[386,889]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[403,889],"end":[413,882]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[423,875],"end":[433,865]}]}]},{"tag":"LineTo","args":[{"point":[546,756]}]},{"tag":"LineTo","args":[{"point":[781,929]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[813,947],"end":[835.5,937.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[858,928],"end":[866,889]}]}]},{"tag":"LineTo","args":[{"point":[1020,162]}]},{"tag":"LineTo","args":[{"point":[1020,161]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"twitter","codePoint":59718},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[1022,195],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[1024,196]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1003,227],"end":[976.5,254.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[950,282],"end":[919,305]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[920,311],"end":[920,318]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[920,325],"end":[920,331]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[920,435],"end":[881,541]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[842,648],"end":[766,734]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[690,820],"end":[579,874]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[467,928],"end":[322,928]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[278,928],"end":[235,922]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,915],"end":[151.5,903]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[111,891],"end":[73,874]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[35,856],"end":[0,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[13,835],"end":[25,836]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[37,837],"end":[50,837]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[123,837],"end":[190,813]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[257,789],"end":[310,747]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[241,746],"end":[187.5,705]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[134,664],"end":[114,601]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[123,603],"end":[133,604]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[143,605],"end":[153,605]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[167,605],"end":[181,603]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[195,601],"end":[208,598]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,583],"end":[88,525.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[40,468],"end":[40,392]}]}]},{"tag":"LineTo","args":[{"point":[40,389]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[61,401],"end":[85,407.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[109,414],"end":[135,415]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[93,387],"end":[67.5,341]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[42,295],"end":[42,240]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[42,211],"end":[49,184.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[56,158],"end":[70,135]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[109,182],"end":[157,221]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[205,260],"end":[260,288.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[315,317],"end":[376,334]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[437,350],"end":[503,354]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[500,342],"end":[498.5,330]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[497,318],"end":[497,306]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[497,262],"end":[514,224]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[530,186],"end":[558.5,157.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[587,129],"end":[625,112]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[664,96],"end":[707,96]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[753,96],"end":[792.5,114]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,132],"end":[860,162]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,155],"end":[929.5,142.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[963,130],"end":[994,112]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[982,149],"end":[958,178.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[934,208],"end":[902,228]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[933,224],"end":[963.5,215.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[994,207],"end":[1022,195]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"visualstudiocode","codePoint":59719},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[768,0],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,831]}]},{"tag":"LineTo","args":[{"point":[0,765]}]},{"tag":"LineTo","args":[{"point":[0,789]}]},{"tag":"LineTo","args":[{"point":[768,1024]}]},{"tag":"LineTo","args":[{"point":[1024,917]}]},{"tag":"LineTo","args":[{"point":[1024,107]}]},{"tag":"LineTo","args":[{"point":[768,0]}]}]},{"start":[103,595],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[250,484]}]},{"tag":"LineTo","args":[{"point":[512,725]}]},{"tag":"LineTo","args":[{"point":[640,663]}]},{"tag":"LineTo","args":[{"point":[640,190]}]},{"tag":"LineTo","args":[{"point":[512,128]}]},{"tag":"LineTo","args":[{"point":[250,369]}]},{"tag":"LineTo","args":[{"point":[103,259]}]},{"tag":"LineTo","args":[{"point":[43,294]}]},{"tag":"LineTo","args":[{"point":[187,427]}]},{"tag":"LineTo","args":[{"point":[43,559]}]},{"tag":"LineTo","args":[{"point":[103,595]}]}]},{"start":[512,287],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,567]}]},{"tag":"LineTo","args":[{"point":[326,427]}]},{"tag":"LineTo","args":[{"point":[512,287]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"webpack","codePoint":59720},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[897,773],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[757,693]}]},{"tag":"LineTo","args":[{"point":[527,819]}]},{"tag":"LineTo","args":[{"point":[527,981]}]},{"tag":"LineTo","args":[{"point":[897,773]}]}]},{"start":[922,750],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[787,673]}]},{"tag":"LineTo","args":[{"point":[787,393]}]},{"tag":"LineTo","args":[{"point":[922,315]}]},{"tag":"LineTo","args":[{"point":[922,750]}]}]},{"start":[125,773],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[264,693]}]},{"tag":"LineTo","args":[{"point":[495,819]}]},{"tag":"LineTo","args":[{"point":[495,981]}]},{"tag":"LineTo","args":[{"point":[125,773]}]}]},{"start":[100,750],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[235,673]}]},{"tag":"LineTo","args":[{"point":[235,393]}]},{"tag":"LineTo","args":[{"point":[100,315]}]},{"tag":"LineTo","args":[{"point":[100,750]}]}]},{"start":[115,287],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[250,364]}]},{"tag":"LineTo","args":[{"point":[495,230]}]},{"tag":"LineTo","args":[{"point":[495,73]}]},{"tag":"LineTo","args":[{"point":[115,287]}]}]},{"start":[906,287],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[772,364]}]},{"tag":"LineTo","args":[{"point":[527,230]}]},{"tag":"LineTo","args":[{"point":[527,73]}]},{"tag":"LineTo","args":[{"point":[906,287]}]}]},{"start":[495,782],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[495,542]}]},{"tag":"LineTo","args":[{"point":[267,411]}]},{"tag":"LineTo","args":[{"point":[267,658]}]},{"tag":"LineTo","args":[{"point":[495,782]}]}]},{"start":[527,782],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[527,542]}]},{"tag":"LineTo","args":[{"point":[754,411]}]},{"tag":"LineTo","args":[{"point":[754,658]}]},{"tag":"LineTo","args":[{"point":[527,782]}]}]},{"start":[283,383],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[511,514]}]},{"tag":"LineTo","args":[{"point":[739,383]}]},{"tag":"LineTo","args":[{"point":[511,258]}]},{"tag":"LineTo","args":[{"point":[283,383]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"yarn","codePoint":59721},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[711,40],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[711,40]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[805,80],"end":[874.5,149.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[944,219],"end":[984,313]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,406],"end":[1024,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,618],"end":[984,711]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[944,805],"end":[874.5,874.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[805,944],"end":[711,984]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,1024],"end":[512,1024]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[406,1024],"end":[313,984]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[219,944],"end":[149.5,874.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[80,805],"end":[40,711]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,618],"end":[0,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,406],"end":[40,313]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[80,219],"end":[149.5,149.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[219,80],"end":[313,40]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[406,0],"end":[512,0]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,0],"end":[711,40]}]}]}]},{"start":[545,175],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[545,175]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[541,175],"end":[537.5,175.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[534,176],"end":[531,178]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[518,182],"end":[507.5,194]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[497,206],"end":[487,227]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[485,231],"end":[484,234]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[483,237],"end":[482,240]}]}]},{"tag":"LineTo","args":[{"point":[481,240]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[452,242],"end":[427,254]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[402,266],"end":[384,287]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,290],"end":[374.5,292.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[369,295],"end":[363,298]}]}]},{"tag":"LineTo","args":[{"point":[363,298]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[350,302],"end":[342.5,313.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[335,325],"end":[328,344]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[318,371],"end":[325,396]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[332,421],"end":[342,438]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[328,451],"end":[312,470]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[296,489],"end":[286,512]}]}]},{"tag":"LineTo","args":[{"point":[286,511]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[278,532],"end":[273,554.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[268,577],"end":[268,601]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[268,603],"end":[268,605]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[268,607],"end":[268,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[258,619],"end":[245.5,638.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[233,658],"end":[231,681]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[228,714],"end":[236.5,735]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[245,756],"end":[250,764]}]}]},{"tag":"LineTo","args":[{"point":[250,765]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[252,767],"end":[253.5,769]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[255,771],"end":[257,773]}]}]},{"tag":"LineTo","args":[{"point":[257,772]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,774],"end":[256,776.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,779],"end":[256,781]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,794],"end":[263,805]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[270,816],"end":[281,822]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[301,832],"end":[326,835]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[351,838],"end":[372,828]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,836],"end":[394.5,842.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[409,849],"end":[434,849]}]}]},{"tag":"LineTo","args":[{"point":[436,849]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[442,849],"end":[501,845]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[560,841],"end":[584,835]}]}]},{"tag":"LineTo","args":[{"point":[584,835]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[593,833],"end":[600,829.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[607,826],"end":[614,821]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[629,816],"end":[666,801.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[703,787],"end":[742,761]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[770,743],"end":[784.5,736.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[799,730],"end":[820,725]}]}]},{"tag":"LineTo","args":[{"point":[820,725]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[838,721],"end":[849.5,707]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[861,693],"end":[861,674]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[861,672],"end":[861,670.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[861,669],"end":[860,667]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[858,646],"end":[841.5,633]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[825,620],"end":[803,620]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,621],"end":[740.5,634.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[713,648],"end":[694,660]}]}]},{"tag":"LineTo","args":[{"point":[695,659]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[689,663],"end":[682.5,666.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[676,670],"end":[668,674]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[669,657],"end":[667,635]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[665,613],"end":[656,588]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,558],"end":[632,539.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[619,521],"end":[609,510]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[621,492],"end":[635,466]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[649,440],"end":[657,400]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[664,366],"end":[661,321]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[658,276],"end":[643,246]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,240],"end":[634.5,236]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[629,232],"end":[623,230]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[620,230],"end":[614.5,229]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[609,228],"end":[599,231]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[584,200],"end":[577.5,192.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[571,185],"end":[567,182]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[562,179],"end":[556.5,177]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[551,175],"end":[545,175]}]}]}]},{"start":[545,205],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[545,205]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[545,205],"end":[545,205]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[545,205],"end":[545,205]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[547,205],"end":[548.5,205.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[550,206],"end":[552,207]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[557,211],"end":[571,240.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[585,270],"end":[585,270]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[585,270],"end":[599.5,262.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[614,255],"end":[617,260]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[629,285],"end":[631.5,325.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[634,366],"end":[628,394]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[619,442],"end":[600,469.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[581,497],"end":[571,513]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[569,517],"end":[590,533.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[611,550],"end":[629,598]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,643],"end":[638.5,675.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[632,708],"end":[634,712]}]}]},{"tag":"LineTo","args":[{"point":[635,714]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[635,714],"end":[653.5,711]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,708],"end":[709,685]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[729,673],"end":[752.5,661.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[776,650],"end":[803,650]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[829,650],"end":[831,670.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[833,691],"end":[813,696]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[790,702],"end":[773,709.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[756,717],"end":[727,736]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[681,766],"end":[640,780]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[599,794],"end":[599,794]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[599,794],"end":[594,798.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[589,803],"end":[577,806]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[556,811],"end":[499.5,815]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[443,819],"end":[436,819]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[417,819],"end":[405,814.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[393,810],"end":[390,802]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,778],"end":[394.5,767]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[409,756],"end":[409,756]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[409,756],"end":[405,753.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[401,751],"end":[398,748]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[395,745],"end":[392.5,741]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[390,737],"end":[389,739]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[385,749],"end":[381.5,766.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[378,784],"end":[368,794]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[355,808],"end":[333,806]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[311,804],"end":[295,796]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[279,787],"end":[288,771.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[297,756],"end":[297,756]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[297,756],"end":[289.5,758]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[282,760],"end":[275,749]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[269,739],"end":[264,722]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[259,705],"end":[261,684]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[262,660],"end":[280.5,640.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[299,621],"end":[299,621]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[299,621],"end":[298.5,591]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,561],"end":[313,524]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[327,491],"end":[355,467.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[383,444],"end":[383,444]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[383,444],"end":[363.5,415]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[344,386],"end":[356,354]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[364,334],"end":[367.5,330.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[371,327],"end":[374,326]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[383,322],"end":[391,318]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[399,314],"end":[406,307]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[438,273],"end":[470,271.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[502,270],"end":[502,270]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[502,270],"end":[515.5,238]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[529,206],"end":[545,205]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"youtube","codePoint":59722},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[1002,265],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[1001,257]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1012,316],"end":[1018,377.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,439],"end":[1024,502]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,505],"end":[1024,507.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,510],"end":[1024,512]}]}]},{"tag":"LineTo","args":[{"point":[1024,512]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,514],"end":[1024,516.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,519],"end":[1024,521]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,584],"end":[1018.5,645]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1013,706],"end":[1002,759]}]}]},{"tag":"LineTo","args":[{"point":[1002,760]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[993,792],"end":[969.5,815.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[946,839],"end":[913,848]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[883,856],"end":[817,861]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[750,865],"end":[682.5,867]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,869],"end":[564,869]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,870],"end":[512,870]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,870],"end":[461,869]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[410,869],"end":[342,867]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[274,865],"end":[208,861]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[141,856],"end":[112,848]}]}]},{"tag":"LineTo","args":[{"point":[111,848]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[79,839],"end":[55.5,815.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,792],"end":[22,759]}]}]},{"tag":"LineTo","args":[{"point":[24,767]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[12,707],"end":[6,644]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,581],"end":[0,516]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,515],"end":[0,514]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,513],"end":[0,512]}]}]},{"tag":"LineTo","args":[{"point":[0,513]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,511],"end":[0,510]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,509],"end":[0,507]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,443],"end":[6,381]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[12,319],"end":[22,265]}]}]},{"tag":"LineTo","args":[{"point":[23,264]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[32,232],"end":[55.5,208.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[79,185],"end":[112,176]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[142,167],"end":[208,163]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,159],"end":[342.5,157]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[410,155],"end":[461,155]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,154],"end":[512,154]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[512,154],"end":[564,155]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[615,155],"end":[683,157]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[751,159],"end":[817,163]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[883,168],"end":[913,176]}]}]},{"tag":"LineTo","args":[{"point":[914,176]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[946,185],"end":[969.5,208.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[993,232],"end":[1002,265]}]}]}]},{"start":[677,512],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[410,359]}]},{"tag":"LineTo","args":[{"point":[410,666]}]},{"tag":"LineTo","args":[{"point":[677,512]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"error","codePoint":59723},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[470,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,319]}]},{"tag":"LineTo","args":[{"point":[554,319]}]},{"tag":"LineTo","args":[{"point":[554,575]}]},{"tag":"LineTo","args":[{"point":[470,575]}]}]},{"start":[470,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,661]}]},{"tag":"LineTo","args":[{"point":[554,661]}]},{"tag":"LineTo","args":[{"point":[554,747]}]},{"tag":"LineTo","args":[{"point":[470,747]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"error_outline","codePoint":59724},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]},{"start":[470,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,575]}]},{"tag":"LineTo","args":[{"point":[554,319]}]},{"tag":"LineTo","args":[{"point":[470,319]}]},{"tag":"LineTo","args":[{"point":[470,575]}]}]},{"start":[470,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,747]}]},{"tag":"LineTo","args":[{"point":[554,661]}]},{"tag":"LineTo","args":[{"point":[470,661]}]},{"tag":"LineTo","args":[{"point":[470,747]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"warningreport_problem","codePoint":59725},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[470,619],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,447]}]},{"tag":"LineTo","args":[{"point":[554,447]}]},{"tag":"LineTo","args":[{"point":[554,619]}]},{"tag":"LineTo","args":[{"point":[470,619]}]}]},{"start":[470,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,703]}]},{"tag":"LineTo","args":[{"point":[554,703]}]},{"tag":"LineTo","args":[{"point":[554,789]}]},{"tag":"LineTo","args":[{"point":[470,789]}]}]},{"start":[982,917],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,107]}]},{"tag":"LineTo","args":[{"point":[42,917]}]},{"tag":"LineTo","args":[{"point":[982,917]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"library_addqueueadd_to_photos","codePoint":59726},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[640,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[640,661]}]},{"tag":"LineTo","args":[{"point":[554,661]}]},{"tag":"LineTo","args":[{"point":[554,491]}]},{"tag":"LineTo","args":[{"point":[384,491]}]},{"tag":"LineTo","args":[{"point":[384,405]}]},{"tag":"LineTo","args":[{"point":[554,405]}]},{"tag":"LineTo","args":[{"point":[554,235]}]},{"tag":"LineTo","args":[{"point":[640,235]}]},{"tag":"LineTo","args":[{"point":[640,405]}]},{"tag":"LineTo","args":[{"point":[810,405]}]},{"tag":"LineTo","args":[{"point":[810,491]}]},{"tag":"LineTo","args":[{"point":[640,491]}]}]},{"start":[342,107],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[308,107],"end":[282,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,157],"end":[256,191]}]}]},{"tag":"LineTo","args":[{"point":[256,703]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,737],"end":[282,763]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[308,789],"end":[342,789]}]}]},{"tag":"LineTo","args":[{"point":[854,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,789],"end":[913,763]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,737],"end":[938,703]}]}]},{"tag":"LineTo","args":[{"point":[938,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,157],"end":[913,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,107],"end":[854,107]}]}]},{"tag":"LineTo","args":[{"point":[342,107]}]}]},{"start":[86,277],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[86,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,909],"end":[111,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,959],"end":[170,959]}]}]},{"tag":"LineTo","args":[{"point":[768,959]}]},{"tag":"LineTo","args":[{"point":[768,875]}]},{"tag":"LineTo","args":[{"point":[170,875]}]},{"tag":"LineTo","args":[{"point":[170,277]}]},{"tag":"LineTo","args":[{"point":[86,277]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"library_music","codePoint":59727},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[86,277],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[86,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,909],"end":[111,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,959],"end":[170,959]}]}]},{"tag":"LineTo","args":[{"point":[768,959]}]},{"tag":"LineTo","args":[{"point":[768,875]}]},{"tag":"LineTo","args":[{"point":[170,875]}]},{"tag":"LineTo","args":[{"point":[170,277]}]},{"tag":"LineTo","args":[{"point":[86,277]}]}]},{"start":[640,319],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[640,555]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,599],"end":[609,630]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[578,661],"end":[534,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[490,661],"end":[458,630]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,599],"end":[426,555]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,511],"end":[458,479]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[490,447],"end":[534,447]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[570,447],"end":[598,469]}]}]},{"tag":"LineTo","args":[{"point":[598,235]}]},{"tag":"LineTo","args":[{"point":[768,235]}]},{"tag":"LineTo","args":[{"point":[768,319]}]},{"tag":"LineTo","args":[{"point":[640,319]}]}]},{"start":[342,107],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[308,107],"end":[282,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,157],"end":[256,191]}]}]},{"tag":"LineTo","args":[{"point":[256,703]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,737],"end":[282,763]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[308,789],"end":[342,789]}]}]},{"tag":"LineTo","args":[{"point":[854,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,789],"end":[913,763]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,737],"end":[938,703]}]}]},{"tag":"LineTo","args":[{"point":[938,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,157],"end":[913,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,107],"end":[854,107]}]}]},{"tag":"LineTo","args":[{"point":[342,107]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"new_releases","codePoint":59728},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[470,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,319]}]},{"tag":"LineTo","args":[{"point":[554,319]}]},{"tag":"LineTo","args":[{"point":[554,575]}]},{"tag":"LineTo","args":[{"point":[470,575]}]}]},{"start":[470,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,661]}]},{"tag":"LineTo","args":[{"point":[554,661]}]},{"tag":"LineTo","args":[{"point":[554,747]}]},{"tag":"LineTo","args":[{"point":[470,747]}]}]},{"start":[878,415],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[892,257]}]},{"tag":"LineTo","args":[{"point":[738,223]}]},{"tag":"LineTo","args":[{"point":[658,87]}]},{"tag":"LineTo","args":[{"point":[512,149]}]},{"tag":"LineTo","args":[{"point":[366,87]}]},{"tag":"LineTo","args":[{"point":[286,223]}]},{"tag":"LineTo","args":[{"point":[132,257]}]},{"tag":"LineTo","args":[{"point":[146,413]}]},{"tag":"LineTo","args":[{"point":[42,533]}]},{"tag":"LineTo","args":[{"point":[146,651]}]},{"tag":"LineTo","args":[{"point":[132,809]}]},{"tag":"LineTo","args":[{"point":[286,845]}]},{"tag":"LineTo","args":[{"point":[366,979]}]},{"tag":"LineTo","args":[{"point":[512,917]}]},{"tag":"LineTo","args":[{"point":[658,979]}]},{"tag":"LineTo","args":[{"point":[738,843]}]},{"tag":"LineTo","args":[{"point":[892,809]}]},{"tag":"LineTo","args":[{"point":[878,651]}]},{"tag":"LineTo","args":[{"point":[982,533]}]},{"tag":"LineTo","args":[{"point":[878,415]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"not_interesteddo_not_disturb","codePoint":59729},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[302,263],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[340,233],"end":[402,212]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[464,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,653],"end":[782,743]}]}]},{"tag":"LineTo","args":[{"point":[302,263]}]}]},{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,413],"end":[242,323]}]}]},{"tag":"LineTo","args":[{"point":[722,803]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[684,833],"end":[622,854]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[560,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"pause","codePoint":59730},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[598,831],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,831]}]},{"tag":"LineTo","args":[{"point":[768,235]}]},{"tag":"LineTo","args":[{"point":[598,235]}]},{"tag":"LineTo","args":[{"point":[598,831]}]}]},{"start":[426,831],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,235]}]},{"tag":"LineTo","args":[{"point":[256,235]}]},{"tag":"LineTo","args":[{"point":[256,831]}]},{"tag":"LineTo","args":[{"point":[426,831]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"pause_circle_filled","codePoint":59731},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[554,703],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,363]}]},{"tag":"LineTo","args":[{"point":[640,363]}]},{"tag":"LineTo","args":[{"point":[640,703]}]},{"tag":"LineTo","args":[{"point":[554,703]}]}]},{"start":[384,703],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[384,363]}]},{"tag":"LineTo","args":[{"point":[470,363]}]},{"tag":"LineTo","args":[{"point":[470,703]}]},{"tag":"LineTo","args":[{"point":[384,703]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"pause_circle_outline","codePoint":59732},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[640,703],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[640,363]}]},{"tag":"LineTo","args":[{"point":[554,363]}]},{"tag":"LineTo","args":[{"point":[554,703]}]},{"tag":"LineTo","args":[{"point":[640,703]}]}]},{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]},{"start":[470,703],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,363]}]},{"tag":"LineTo","args":[{"point":[384,363]}]},{"tag":"LineTo","args":[{"point":[384,703]}]},{"tag":"LineTo","args":[{"point":[470,703]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"play_arrow","codePoint":59733},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[342,831],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[810,533]}]},{"tag":"LineTo","args":[{"point":[342,235]}]},{"tag":"LineTo","args":[{"point":[342,831]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"play_circle_filled","codePoint":59734},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[426,341],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,533]}]},{"tag":"LineTo","args":[{"point":[426,725]}]},{"tag":"LineTo","args":[{"point":[426,341]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"play_circle_outline","codePoint":59735},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]},{"start":[682,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,341]}]},{"tag":"LineTo","args":[{"point":[426,725]}]},{"tag":"LineTo","args":[{"point":[682,533]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"repeat","codePoint":59736},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[298,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[298,619]}]},{"tag":"LineTo","args":[{"point":[128,789]}]},{"tag":"LineTo","args":[{"point":[298,959]}]},{"tag":"LineTo","args":[{"point":[298,831]}]},{"tag":"LineTo","args":[{"point":[810,831]}]},{"tag":"LineTo","args":[{"point":[810,575]}]},{"tag":"LineTo","args":[{"point":[726,575]}]},{"tag":"LineTo","args":[{"point":[726,747]}]},{"tag":"LineTo","args":[{"point":[298,747]}]}]},{"start":[726,319],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[726,447]}]},{"tag":"LineTo","args":[{"point":[896,277]}]},{"tag":"LineTo","args":[{"point":[726,107]}]},{"tag":"LineTo","args":[{"point":[726,235]}]},{"tag":"LineTo","args":[{"point":[214,235]}]},{"tag":"LineTo","args":[{"point":[214,491]}]},{"tag":"LineTo","args":[{"point":[298,491]}]},{"tag":"LineTo","args":[{"point":[298,319]}]},{"tag":"LineTo","args":[{"point":[726,319]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"repeat_one","codePoint":59737},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[554,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,405]}]},{"tag":"LineTo","args":[{"point":[426,447]}]},{"tag":"LineTo","args":[{"point":[426,491]}]},{"tag":"LineTo","args":[{"point":[490,491]}]},{"tag":"LineTo","args":[{"point":[490,661]}]},{"tag":"LineTo","args":[{"point":[554,661]}]},{"tag":"LineTo","args":[{"point":[554,405]}]}]},{"start":[298,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[298,619]}]},{"tag":"LineTo","args":[{"point":[128,789]}]},{"tag":"LineTo","args":[{"point":[298,959]}]},{"tag":"LineTo","args":[{"point":[298,831]}]},{"tag":"LineTo","args":[{"point":[810,831]}]},{"tag":"LineTo","args":[{"point":[810,575]}]},{"tag":"LineTo","args":[{"point":[726,575]}]},{"tag":"LineTo","args":[{"point":[726,747]}]},{"tag":"LineTo","args":[{"point":[298,747]}]}]},{"start":[726,319],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[726,447]}]},{"tag":"LineTo","args":[{"point":[896,277]}]},{"tag":"LineTo","args":[{"point":[726,107]}]},{"tag":"LineTo","args":[{"point":[726,235]}]},{"tag":"LineTo","args":[{"point":[214,235]}]},{"tag":"LineTo","args":[{"point":[214,491]}]},{"tag":"LineTo","args":[{"point":[298,491]}]},{"tag":"LineTo","args":[{"point":[298,319]}]},{"tag":"LineTo","args":[{"point":[726,319]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"replay","codePoint":59738},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,63],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[298,277]}]},{"tag":"LineTo","args":[{"point":[512,491]}]},{"tag":"LineTo","args":[{"point":[512,319]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,319],"end":[693,394]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,469],"end":[768,575]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,681],"end":[693,756]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,831],"end":[512,831]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[406,831],"end":[331,756]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,681],"end":[256,575]}]}]},{"tag":"LineTo","args":[{"point":[170,575]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,717],"end":[271,817]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,917],"end":[512,917]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,917],"end":[753,817]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,717],"end":[854,575]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,435],"end":[754,335]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[654,235],"end":[512,235]}]}]},{"tag":"LineTo","args":[{"point":[512,63]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"shuffle","codePoint":59739},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[572,653],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[706,787]}]},{"tag":"LineTo","args":[{"point":[618,875]}]},{"tag":"LineTo","args":[{"point":[854,875]}]},{"tag":"LineTo","args":[{"point":[854,639]}]},{"tag":"LineTo","args":[{"point":[766,727]}]},{"tag":"LineTo","args":[{"point":[632,593]}]},{"tag":"LineTo","args":[{"point":[572,653]}]}]},{"start":[706,279],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[170,815]}]},{"tag":"LineTo","args":[{"point":[230,875]}]},{"tag":"LineTo","args":[{"point":[766,339]}]},{"tag":"LineTo","args":[{"point":[854,427]}]},{"tag":"LineTo","args":[{"point":[854,191]}]},{"tag":"LineTo","args":[{"point":[618,191]}]},{"tag":"LineTo","args":[{"point":[706,279]}]}]},{"start":[230,191],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[170,251]}]},{"tag":"LineTo","args":[{"point":[392,473]}]},{"tag":"LineTo","args":[{"point":[452,413]}]},{"tag":"LineTo","args":[{"point":[230,191]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"skip_next","codePoint":59740},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[682,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,789]}]},{"tag":"LineTo","args":[{"point":[768,277]}]},{"tag":"LineTo","args":[{"point":[682,277]}]},{"tag":"LineTo","args":[{"point":[682,789]}]}]},{"start":[618,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[256,277]}]},{"tag":"LineTo","args":[{"point":[256,789]}]},{"tag":"LineTo","args":[{"point":[618,533]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"skip_previous","codePoint":59741},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[768,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,277]}]},{"tag":"LineTo","args":[{"point":[406,533]}]},{"tag":"LineTo","args":[{"point":[768,789]}]}]},{"start":[256,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[342,789]}]},{"tag":"LineTo","args":[{"point":[342,277]}]},{"tag":"LineTo","args":[{"point":[256,277]}]},{"tag":"LineTo","args":[{"point":[256,789]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"emailmailmarkunreadlocal_post_office","codePoint":59742},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[170,363]}]},{"tag":"LineTo","args":[{"point":[170,277]}]},{"tag":"LineTo","args":[{"point":[512,491]}]},{"tag":"LineTo","args":[{"point":[854,277]}]},{"tag":"LineTo","args":[{"point":[854,363]}]},{"tag":"LineTo","args":[{"point":[512,575]}]}]},{"start":[170,191],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,191],"end":[111,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,243],"end":[86,277]}]}]},{"tag":"LineTo","args":[{"point":[86,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,823],"end":[111,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,875],"end":[170,875]}]}]},{"tag":"LineTo","args":[{"point":[854,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,875],"end":[913,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,823],"end":[938,789]}]}]},{"tag":"LineTo","args":[{"point":[938,277]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,243],"end":[913,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,191],"end":[854,191]}]}]},{"tag":"LineTo","args":[{"point":[170,191]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"vpn_key","codePoint":59743},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[239,593],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[239,593]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,567],"end":[214,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,499],"end":[239,473]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[264,447],"end":[298,447]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[332,447],"end":[358,473]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,499],"end":[384,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,567],"end":[358,593]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[332,619],"end":[298,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[264,619],"end":[239,593]}]}]}]},{"start":[443,327],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[443,327]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,277],"end":[298,277]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,277],"end":[117,352]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[42,427],"end":[42,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[42,639],"end":[117,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,789],"end":[298,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,789],"end":[443,739]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[514,689],"end":[540,619]}]}]},{"tag":"LineTo","args":[{"point":[726,619]}]},{"tag":"LineTo","args":[{"point":[726,789]}]},{"tag":"LineTo","args":[{"point":[896,789]}]},{"tag":"LineTo","args":[{"point":[896,619]}]},{"tag":"LineTo","args":[{"point":[982,619]}]},{"tag":"LineTo","args":[{"point":[982,447]}]},{"tag":"LineTo","args":[{"point":[540,447]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[514,377],"end":[443,327]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"add","codePoint":59744},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[810,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,491]}]},{"tag":"LineTo","args":[{"point":[554,235]}]},{"tag":"LineTo","args":[{"point":[470,235]}]},{"tag":"LineTo","args":[{"point":[470,491]}]},{"tag":"LineTo","args":[{"point":[214,491]}]},{"tag":"LineTo","args":[{"point":[214,575]}]},{"tag":"LineTo","args":[{"point":[470,575]}]},{"tag":"LineTo","args":[{"point":[470,831]}]},{"tag":"LineTo","args":[{"point":[554,831]}]},{"tag":"LineTo","args":[{"point":[554,575]}]},{"tag":"LineTo","args":[{"point":[810,575]}]},{"tag":"LineTo","args":[{"point":[810,491]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"add_box","codePoint":59745},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[554,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,747]}]},{"tag":"LineTo","args":[{"point":[470,747]}]},{"tag":"LineTo","args":[{"point":[470,575]}]},{"tag":"LineTo","args":[{"point":[298,575]}]},{"tag":"LineTo","args":[{"point":[298,491]}]},{"tag":"LineTo","args":[{"point":[470,491]}]},{"tag":"LineTo","args":[{"point":[470,319]}]},{"tag":"LineTo","args":[{"point":[554,319]}]},{"tag":"LineTo","args":[{"point":[554,491]}]},{"tag":"LineTo","args":[{"point":[726,491]}]},{"tag":"LineTo","args":[{"point":[726,575]}]},{"tag":"LineTo","args":[{"point":[554,575]}]}]},{"start":[214,149],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,149],"end":[153,174]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,199],"end":[128,235]}]}]},{"tag":"LineTo","args":[{"point":[128,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,867],"end":[153,892]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,917],"end":[214,917]}]}]},{"tag":"LineTo","args":[{"point":[810,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,917],"end":[870,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,865],"end":[896,831]}]}]},{"tag":"LineTo","args":[{"point":[896,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,201],"end":[870,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,149],"end":[810,149]}]}]},{"tag":"LineTo","args":[{"point":[214,149]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"add_circle","codePoint":59746},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[554,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,747]}]},{"tag":"LineTo","args":[{"point":[470,747]}]},{"tag":"LineTo","args":[{"point":[470,575]}]},{"tag":"LineTo","args":[{"point":[298,575]}]},{"tag":"LineTo","args":[{"point":[298,491]}]},{"tag":"LineTo","args":[{"point":[470,491]}]},{"tag":"LineTo","args":[{"point":[470,319]}]},{"tag":"LineTo","args":[{"point":[554,319]}]},{"tag":"LineTo","args":[{"point":[554,491]}]},{"tag":"LineTo","args":[{"point":[726,491]}]},{"tag":"LineTo","args":[{"point":[726,575]}]},{"tag":"LineTo","args":[{"point":[554,575]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"add_circle_outlinecontrol_point","codePoint":59747},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]},{"start":[470,319],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,491]}]},{"tag":"LineTo","args":[{"point":[298,491]}]},{"tag":"LineTo","args":[{"point":[298,575]}]},{"tag":"LineTo","args":[{"point":[470,575]}]},{"tag":"LineTo","args":[{"point":[470,747]}]},{"tag":"LineTo","args":[{"point":[554,747]}]},{"tag":"LineTo","args":[{"point":[554,575]}]},{"tag":"LineTo","args":[{"point":[726,575]}]},{"tag":"LineTo","args":[{"point":[726,491]}]},{"tag":"LineTo","args":[{"point":[554,491]}]},{"tag":"LineTo","args":[{"point":[554,319]}]},{"tag":"LineTo","args":[{"point":[470,319]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"block","codePoint":59748},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[302,803],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[302,803]}]},{"tag":"LineTo","args":[{"point":[782,323]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[812,361],"end":[833,423]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,485],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[392,875],"end":[302,803]}]}]}]},{"start":[271,292],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,292]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[632,191],"end":[722,263]}]}]},{"tag":"LineTo","args":[{"point":[242,743]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[212,705],"end":[191,643]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,581],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"clearclose","codePoint":59749},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[750,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,473]}]},{"tag":"LineTo","args":[{"point":[274,235]}]},{"tag":"LineTo","args":[{"point":[214,295]}]},{"tag":"LineTo","args":[{"point":[452,533]}]},{"tag":"LineTo","args":[{"point":[214,771]}]},{"tag":"LineTo","args":[{"point":[274,831]}]},{"tag":"LineTo","args":[{"point":[512,593]}]},{"tag":"LineTo","args":[{"point":[750,831]}]},{"tag":"LineTo","args":[{"point":[810,771]}]},{"tag":"LineTo","args":[{"point":[572,533]}]},{"tag":"LineTo","args":[{"point":[810,295]}]},{"tag":"LineTo","args":[{"point":[750,235]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"copy","codePoint":59750},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[342,917],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[342,319]}]},{"tag":"LineTo","args":[{"point":[810,319]}]},{"tag":"LineTo","args":[{"point":[810,917]}]},{"tag":"LineTo","args":[{"point":[342,917]}]}]},{"start":[342,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[308,235],"end":[282,260]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,285],"end":[256,319]}]}]},{"tag":"LineTo","args":[{"point":[256,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,951],"end":[282,977]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[308,1003],"end":[342,1003]}]}]},{"tag":"LineTo","args":[{"point":[810,1003]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,1003],"end":[870,977]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,951],"end":[896,917]}]}]},{"tag":"LineTo","args":[{"point":[896,319]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,285],"end":[870,260]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,235],"end":[810,235]}]}]},{"tag":"LineTo","args":[{"point":[342,235]}]}]},{"start":[170,63],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,63],"end":[111,89]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,115],"end":[86,149]}]}]},{"tag":"LineTo","args":[{"point":[86,747]}]},{"tag":"LineTo","args":[{"point":[170,747]}]},{"tag":"LineTo","args":[{"point":[170,149]}]},{"tag":"LineTo","args":[{"point":[682,149]}]},{"tag":"LineTo","args":[{"point":[682,63]}]},{"tag":"LineTo","args":[{"point":[170,63]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"cut","codePoint":59751},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[554,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[640,491]}]},{"tag":"LineTo","args":[{"point":[938,191]}]},{"tag":"LineTo","args":[{"point":[938,149]}]},{"tag":"LineTo","args":[{"point":[810,149]}]},{"tag":"LineTo","args":[{"point":[554,405]}]}]},{"start":[490,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[490,533]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[490,511],"end":[512,511]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[534,511],"end":[534,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[534,555],"end":[512,555]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[490,555],"end":[490,533]}]}]}]},{"start":[196,850],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[196,850]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,825],"end":[170,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,753],"end":[196,728]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,703],"end":[256,703]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,703],"end":[316,728]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,753],"end":[342,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,825],"end":[316,850]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,875],"end":[256,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,875],"end":[196,850]}]}]}]},{"start":[196,338],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[196,338]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,313],"end":[170,277]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,241],"end":[196,216]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,191],"end":[256,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,191],"end":[316,216]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,241],"end":[342,277]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,313],"end":[316,338]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,363],"end":[256,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,363],"end":[196,338]}]}]}]},{"start":[426,277],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,277]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,207],"end":[376,157]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[326,107],"end":[256,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[186,107],"end":[136,157]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,207],"end":[86,277]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,347],"end":[136,397]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[186,447],"end":[256,447]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[296,447],"end":[326,433]}]}]},{"tag":"LineTo","args":[{"point":[426,533]}]},{"tag":"LineTo","args":[{"point":[326,633]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[296,619],"end":[256,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[186,619],"end":[136,669]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,719],"end":[86,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,859],"end":[136,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[186,959],"end":[256,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[326,959],"end":[376,909]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,859],"end":[426,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,749],"end":[412,719]}]}]},{"tag":"LineTo","args":[{"point":[512,619]}]},{"tag":"LineTo","args":[{"point":[810,917]}]},{"tag":"LineTo","args":[{"point":[938,917]}]},{"tag":"LineTo","args":[{"point":[938,875]}]},{"tag":"LineTo","args":[{"point":[412,347]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,317],"end":[426,277]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"paste","codePoint":59752},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[214,875],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[214,191]}]},{"tag":"LineTo","args":[{"point":[298,191]}]},{"tag":"LineTo","args":[{"point":[298,319]}]},{"tag":"LineTo","args":[{"point":[726,319]}]},{"tag":"LineTo","args":[{"point":[726,191]}]},{"tag":"LineTo","args":[{"point":[810,191]}]},{"tag":"LineTo","args":[{"point":[810,875]}]},{"tag":"LineTo","args":[{"point":[214,875]}]}]},{"start":[542,119],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[542,119]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,131],"end":[554,149]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,167],"end":[542,179]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[530,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[494,191],"end":[482,179]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[470,167],"end":[470,149]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[470,131],"end":[482,119]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[494,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[530,107],"end":[542,119]}]}]}]},{"start":[632,107],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,69],"end":[586,45]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,21],"end":[512,21]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[470,21],"end":[438,45]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[406,69],"end":[392,107]}]}]},{"tag":"LineTo","args":[{"point":[214,107]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,107],"end":[154,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,157],"end":[128,191]}]}]},{"tag":"LineTo","args":[{"point":[128,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,909],"end":[154,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,959],"end":[214,959]}]}]},{"tag":"LineTo","args":[{"point":[810,959]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,959],"end":[870,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,909],"end":[896,875]}]}]},{"tag":"LineTo","args":[{"point":[896,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,157],"end":[870,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,107],"end":[810,107]}]}]},{"tag":"LineTo","args":[{"point":[632,107]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"edit","codePoint":59753},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[896,291],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[896,291]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,273],"end":[884,261]}]}]},{"tag":"LineTo","args":[{"point":[784,161]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[772,149],"end":[754,149]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,149],"end":[724,161]}]}]},{"tag":"LineTo","args":[{"point":[646,239]}]},{"tag":"LineTo","args":[{"point":[806,399]}]},{"tag":"LineTo","args":[{"point":[884,321]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,309],"end":[896,291]}]}]}]},{"start":[128,917],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[288,917]}]},{"tag":"LineTo","args":[{"point":[760,445]}]},{"tag":"LineTo","args":[{"point":[600,285]}]},{"tag":"LineTo","args":[{"point":[128,757]}]},{"tag":"LineTo","args":[{"point":[128,917]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"drafts","codePoint":59754},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[160,355],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,149]}]},{"tag":"LineTo","args":[{"point":[864,355]}]},{"tag":"LineTo","args":[{"point":[512,575]}]},{"tag":"LineTo","args":[{"point":[160,355]}]}]},{"start":[898,289],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[898,289]}]},{"tag":"LineTo","args":[{"point":[512,63]}]},{"tag":"LineTo","args":[{"point":[126,289]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,313],"end":[86,363]}]}]},{"tag":"LineTo","args":[{"point":[86,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,823],"end":[111,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,875],"end":[170,875]}]}]},{"tag":"LineTo","args":[{"point":[854,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,875],"end":[913,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,823],"end":[938,789]}]}]},{"tag":"LineTo","args":[{"point":[938,363]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,313],"end":[898,289]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"forward","codePoint":59755},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[170,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[170,703]}]},{"tag":"LineTo","args":[{"point":[512,703]}]},{"tag":"LineTo","args":[{"point":[512,875]}]},{"tag":"LineTo","args":[{"point":[854,533]}]},{"tag":"LineTo","args":[{"point":[512,191]}]},{"tag":"LineTo","args":[{"point":[512,363]}]},{"tag":"LineTo","args":[{"point":[170,363]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"remove","codePoint":59756},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[810,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[214,491]}]},{"tag":"LineTo","args":[{"point":[214,575]}]},{"tag":"LineTo","args":[{"point":[810,575]}]},{"tag":"LineTo","args":[{"point":[810,491]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"remove_circledo_not_disturb_on","codePoint":59757},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[298,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[298,491]}]},{"tag":"LineTo","args":[{"point":[726,491]}]},{"tag":"LineTo","args":[{"point":[726,575]}]},{"tag":"LineTo","args":[{"point":[298,575]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"remove_circle_outline","codePoint":59758},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]},{"start":[298,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[726,575]}]},{"tag":"LineTo","args":[{"point":[726,491]}]},{"tag":"LineTo","args":[{"point":[298,491]}]},{"tag":"LineTo","args":[{"point":[298,575]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"send","codePoint":59759},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[982,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[86,149]}]},{"tag":"LineTo","args":[{"point":[86,447]}]},{"tag":"LineTo","args":[{"point":[726,533]}]},{"tag":"LineTo","args":[{"point":[86,619]}]},{"tag":"LineTo","args":[{"point":[86,917]}]},{"tag":"LineTo","args":[{"point":[982,533]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"undo","codePoint":59760},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[238,473],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[238,473]}]},{"tag":"LineTo","args":[{"point":[86,319]}]},{"tag":"LineTo","args":[{"point":[86,703]}]},{"tag":"LineTo","args":[{"point":[470,703]}]},{"tag":"LineTo","args":[{"point":[314,549]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[410,469],"end":[534,469]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[646,469],"end":[735,534]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[824,599],"end":[858,703]}]}]},{"tag":"LineTo","args":[{"point":[958,671]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[912,535],"end":[796,449]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,363],"end":[534,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[364,363],"end":[238,473]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"save_alt","codePoint":59761},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[554,149],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,149]}]},{"tag":"LineTo","args":[{"point":[470,561]}]},{"tag":"LineTo","args":[{"point":[358,451]}]},{"tag":"LineTo","args":[{"point":[298,511]}]},{"tag":"LineTo","args":[{"point":[512,725]}]},{"tag":"LineTo","args":[{"point":[726,511]}]},{"tag":"LineTo","args":[{"point":[666,451]}]},{"tag":"LineTo","args":[{"point":[554,561]}]},{"tag":"LineTo","args":[{"point":[554,149]}]}]},{"start":[810,831],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[214,831]}]},{"tag":"LineTo","args":[{"point":[214,533]}]},{"tag":"LineTo","args":[{"point":[128,533]}]},{"tag":"LineTo","args":[{"point":[128,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,865],"end":[154,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,917],"end":[214,917]}]}]},{"tag":"LineTo","args":[{"point":[810,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,917],"end":[870,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,865],"end":[896,831]}]}]},{"tag":"LineTo","args":[{"point":[896,533]}]},{"tag":"LineTo","args":[{"point":[810,533]}]},{"tag":"LineTo","args":[{"point":[810,831]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"file_copy","codePoint":59762},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[598,299],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[832,533]}]},{"tag":"LineTo","args":[{"point":[598,533]}]},{"tag":"LineTo","args":[{"point":[598,299]}]}]},{"start":[342,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[308,235],"end":[282,260]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,285],"end":[256,319]}]}]},{"tag":"LineTo","args":[{"point":[256,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,951],"end":[281,977]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[306,1003],"end":[340,1003]}]}]},{"tag":"LineTo","args":[{"point":[810,1003]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,1003],"end":[870,977]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,951],"end":[896,917]}]}]},{"tag":"LineTo","args":[{"point":[896,491]}]},{"tag":"LineTo","args":[{"point":[640,235]}]},{"tag":"LineTo","args":[{"point":[342,235]}]}]},{"start":[170,63],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,63],"end":[111,89]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,115],"end":[86,149]}]}]},{"tag":"LineTo","args":[{"point":[86,747]}]},{"tag":"LineTo","args":[{"point":[170,747]}]},{"tag":"LineTo","args":[{"point":[170,149]}]},{"tag":"LineTo","args":[{"point":[682,149]}]},{"tag":"LineTo","args":[{"point":[682,63]}]},{"tag":"LineTo","args":[{"point":[170,63]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"sd_storagesd_card","codePoint":59763},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[682,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,191]}]},{"tag":"LineTo","args":[{"point":[768,191]}]},{"tag":"LineTo","args":[{"point":[768,363]}]},{"tag":"LineTo","args":[{"point":[682,363]}]}]},{"start":[554,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,191]}]},{"tag":"LineTo","args":[{"point":[640,191]}]},{"tag":"LineTo","args":[{"point":[640,363]}]},{"tag":"LineTo","args":[{"point":[554,363]}]}]},{"start":[426,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,191]}]},{"tag":"LineTo","args":[{"point":[512,191]}]},{"tag":"LineTo","args":[{"point":[512,363]}]},{"tag":"LineTo","args":[{"point":[426,363]}]}]},{"start":[426,107],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[172,363]}]},{"tag":"LineTo","args":[{"point":[170,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,909],"end":[196,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,959],"end":[256,959]}]}]},{"tag":"LineTo","args":[{"point":[768,959]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[802,959],"end":[828,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,909],"end":[854,875]}]}]},{"tag":"LineTo","args":[{"point":[854,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,157],"end":[828,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[802,107],"end":[768,107]}]}]},{"tag":"LineTo","args":[{"point":[426,107]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"attach_file","codePoint":59764},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[704,767],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,837],"end":[654,888]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[604,939],"end":[534,939]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[464,939],"end":[413,888]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[362,837],"end":[362,767]}]}]},{"tag":"LineTo","args":[{"point":[362,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[362,191],"end":[394,159]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,127],"end":[470,127]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[514,127],"end":[545,159]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,191],"end":[576,235]}]}]},{"tag":"LineTo","args":[{"point":[576,683]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,701],"end":[564,713]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[552,725],"end":[534,725]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[516,725],"end":[503,713]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[490,701],"end":[490,683]}]}]},{"tag":"LineTo","args":[{"point":[490,277]}]},{"tag":"LineTo","args":[{"point":[426,277]}]},{"tag":"LineTo","args":[{"point":[426,683]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,727],"end":[458,758]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[490,789],"end":[534,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[578,789],"end":[609,758]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,727],"end":[640,683]}]}]},{"tag":"LineTo","args":[{"point":[640,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,165],"end":[590,114]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[540,63],"end":[470,63]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[400,63],"end":[349,114]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,165],"end":[298,235]}]}]},{"tag":"LineTo","args":[{"point":[298,767]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,865],"end":[367,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,1003],"end":[534,1003]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[632,1003],"end":[700,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,865],"end":[768,767]}]}]},{"tag":"LineTo","args":[{"point":[768,277]}]},{"tag":"LineTo","args":[{"point":[704,277]}]},{"tag":"LineTo","args":[{"point":[704,767]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"attach_money","codePoint":59765},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[376,395],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[376,395]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[376,359],"end":[407,337]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[438,315],"end":[490,315]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[594,315],"end":[598,405]}]}]},{"tag":"LineTo","args":[{"point":[692,405]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[690,347],"end":[655,303]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[620,259],"end":[554,243]}]}]},{"tag":"LineTo","args":[{"point":[554,149]}]},{"tag":"LineTo","args":[{"point":[426,149]}]},{"tag":"LineTo","args":[{"point":[426,241]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[362,255],"end":[320,296]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[278,337],"end":[278,395]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[278,525],"end":[478,571]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[606,603],"end":[606,675]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[606,705],"end":[579,728]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[552,751],"end":[490,751]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,751],"end":[364,661]}]}]},{"tag":"LineTo","args":[{"point":[270,661]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[274,727],"end":[317,769]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[360,811],"end":[426,825]}]}]},{"tag":"LineTo","args":[{"point":[426,917]}]},{"tag":"LineTo","args":[{"point":[554,917]}]},{"tag":"LineTo","args":[{"point":[554,825]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[622,813],"end":[663,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,735],"end":[704,673]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,629],"end":[687,597]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[670,565],"end":[638,544]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[606,523],"end":[577,511]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[548,499],"end":[504,487]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[376,453],"end":[376,395]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"format_bold","codePoint":59766},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[426,683],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,555]}]},{"tag":"LineTo","args":[{"point":[576,555]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[604,555],"end":[622,574]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,593],"end":[640,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,645],"end":[622,664]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[604,683],"end":[576,683]}]}]},{"tag":"LineTo","args":[{"point":[426,683]}]}]},{"start":[554,299],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[580,299],"end":[599,318]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,337],"end":[618,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,389],"end":[599,408]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[580,427],"end":[554,427]}]}]},{"tag":"LineTo","args":[{"point":[426,427]}]},{"tag":"LineTo","args":[{"point":[426,299]}]},{"tag":"LineTo","args":[{"point":[554,299]}]}]},{"start":[736,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,363]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,291],"end":[687,241]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[638,191],"end":[566,191]}]}]},{"tag":"LineTo","args":[{"point":[298,191]}]},{"tag":"LineTo","args":[{"point":[298,789]}]},{"tag":"LineTo","args":[{"point":[600,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[668,789],"end":[713,742]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[758,695],"end":[758,627]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[758,523],"end":[666,481]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,435],"end":[736,363]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"format_color_fill","codePoint":59767},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[0,1045],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[1024,1045]}]},{"tag":"LineTo","args":[{"point":[1024,875]}]},{"tag":"LineTo","args":[{"point":[0,875]}]},{"tag":"LineTo","args":[{"point":[0,1045]}]}]},{"start":[788,537],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,561],"end":[747,599]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,637],"end":[726,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,695],"end":[751,721]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[776,747],"end":[810,747]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,747],"end":[870,721]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,695],"end":[896,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,605],"end":[810,511]}]}]},{"tag":"LineTo","args":[{"point":[788,537]}]}]},{"start":[426,243],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[632,447]}]},{"tag":"LineTo","args":[{"point":[222,447]}]},{"tag":"LineTo","args":[{"point":[426,243]}]}]},{"start":[326,21],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[264,81]}]},{"tag":"LineTo","args":[{"point":[366,183]}]},{"tag":"LineTo","args":[{"point":[146,403]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,421],"end":[128,447]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,475],"end":[146,493]}]}]},{"tag":"LineTo","args":[{"point":[382,727]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[402,747],"end":[426,747]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[452,747],"end":[472,727]}]}]},{"tag":"LineTo","args":[{"point":[706,493]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,475],"end":[726,449]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,423],"end":[706,403]}]}]},{"tag":"LineTo","args":[{"point":[326,21]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"music_video","codePoint":59768},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[380,751],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[380,751]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[418,789],"end":[470,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[522,789],"end":[560,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,715],"end":[598,663]}]}]},{"tag":"LineTo","args":[{"point":[598,363]}]},{"tag":"LineTo","args":[{"point":[726,363]}]},{"tag":"LineTo","args":[{"point":[726,277]}]},{"tag":"LineTo","args":[{"point":[512,277]}]},{"tag":"LineTo","args":[{"point":[512,541]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[484,533],"end":[470,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[418,533],"end":[380,571]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,609],"end":[342,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,713],"end":[380,751]}]}]}]},{"start":[128,831],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[128,235]}]},{"tag":"LineTo","args":[{"point":[896,235]}]},{"tag":"LineTo","args":[{"point":[896,831]}]},{"tag":"LineTo","args":[{"point":[128,831]}]}]},{"start":[128,149],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[94,149],"end":[68,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[42,201],"end":[42,235]}]}]},{"tag":"LineTo","args":[{"point":[42,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[42,865],"end":[68,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[94,917],"end":[128,917]}]}]},{"tag":"LineTo","args":[{"point":[896,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[930,917],"end":[956,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[982,865],"end":[982,831]}]}]},{"tag":"LineTo","args":[{"point":[982,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[982,201],"end":[956,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[930,149],"end":[896,149]}]}]},{"tag":"LineTo","args":[{"point":[128,149]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"format_size","codePoint":59769},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[256,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[256,831]}]},{"tag":"LineTo","args":[{"point":[384,831]}]},{"tag":"LineTo","args":[{"point":[384,533]}]},{"tag":"LineTo","args":[{"point":[512,533]}]},{"tag":"LineTo","args":[{"point":[512,405]}]},{"tag":"LineTo","args":[{"point":[128,405]}]},{"tag":"LineTo","args":[{"point":[128,533]}]},{"tag":"LineTo","args":[{"point":[256,533]}]}]},{"start":[384,319],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[598,319]}]},{"tag":"LineTo","args":[{"point":[598,831]}]},{"tag":"LineTo","args":[{"point":[726,831]}]},{"tag":"LineTo","args":[{"point":[726,319]}]},{"tag":"LineTo","args":[{"point":[938,319]}]},{"tag":"LineTo","args":[{"point":[938,191]}]},{"tag":"LineTo","args":[{"point":[384,191]}]},{"tag":"LineTo","args":[{"point":[384,319]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"format_underlined","codePoint":59770},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[214,917],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[810,917]}]},{"tag":"LineTo","args":[{"point":[810,831]}]},{"tag":"LineTo","args":[{"point":[214,831]}]},{"tag":"LineTo","args":[{"point":[214,917]}]}]},{"start":[693,672],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[693,672]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,597],"end":[768,491]}]}]},{"tag":"LineTo","args":[{"point":[768,149]}]},{"tag":"LineTo","args":[{"point":[662,149]}]},{"tag":"LineTo","args":[{"point":[662,491]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[662,553],"end":[618,596]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[574,639],"end":[512,639]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[450,639],"end":[406,596]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[362,553],"end":[362,491]}]}]},{"tag":"LineTo","args":[{"point":[362,149]}]},{"tag":"LineTo","args":[{"point":[256,149]}]},{"tag":"LineTo","args":[{"point":[256,491]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,597],"end":[331,672]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[406,747],"end":[512,747]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,747],"end":[693,672]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"insert_chartpollassessment","codePoint":59771},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[640,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[640,575]}]},{"tag":"LineTo","args":[{"point":[726,575]}]},{"tag":"LineTo","args":[{"point":[726,747]}]},{"tag":"LineTo","args":[{"point":[640,747]}]}]},{"start":[470,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,319]}]},{"tag":"LineTo","args":[{"point":[554,319]}]},{"tag":"LineTo","args":[{"point":[554,747]}]},{"tag":"LineTo","args":[{"point":[470,747]}]}]},{"start":[298,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[298,447]}]},{"tag":"LineTo","args":[{"point":[384,447]}]},{"tag":"LineTo","args":[{"point":[384,747]}]},{"tag":"LineTo","args":[{"point":[298,747]}]}]},{"start":[214,149],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,149],"end":[154,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,201],"end":[128,235]}]}]},{"tag":"LineTo","args":[{"point":[128,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,865],"end":[154,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,917],"end":[214,917]}]}]},{"tag":"LineTo","args":[{"point":[810,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,917],"end":[870,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,865],"end":[896,831]}]}]},{"tag":"LineTo","args":[{"point":[896,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,201],"end":[870,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,149],"end":[810,149]}]}]},{"tag":"LineTo","args":[{"point":[214,149]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"insert_emoticontag_facesmood","codePoint":59772},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[645,726],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[645,726]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,685],"end":[730,619]}]}]},{"tag":"LineTo","args":[{"point":[294,619]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,685],"end":[379,726]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[438,767],"end":[512,767]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[586,767],"end":[645,726]}]}]}]},{"start":[407,472],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[407,472]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,453],"end":[426,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,401],"end":[407,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,363],"end":[362,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,363],"end":[317,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,401],"end":[298,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,453],"end":[317,472]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,491],"end":[362,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,491],"end":[407,472]}]}]}]},{"start":[707,472],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[707,472]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,453],"end":[726,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,401],"end":[707,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,363],"end":[662,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,363],"end":[617,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,401],"end":[598,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,453],"end":[617,472]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,491],"end":[662,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,491],"end":[707,472]}]}]}]},{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"insert_invitationevent","codePoint":59773},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[214,831],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[214,363]}]},{"tag":"LineTo","args":[{"point":[810,363]}]},{"tag":"LineTo","args":[{"point":[810,831]}]},{"tag":"LineTo","args":[{"point":[214,831]}]}]},{"start":[682,149],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[342,149]}]},{"tag":"LineTo","args":[{"point":[342,63]}]},{"tag":"LineTo","args":[{"point":[256,63]}]},{"tag":"LineTo","args":[{"point":[256,149]}]},{"tag":"LineTo","args":[{"point":[214,149]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,149],"end":[153,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,201],"end":[128,235]}]}]},{"tag":"LineTo","args":[{"point":[128,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,867],"end":[153,892]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,917],"end":[214,917]}]}]},{"tag":"LineTo","args":[{"point":[810,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,917],"end":[870,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,865],"end":[896,831]}]}]},{"tag":"LineTo","args":[{"point":[896,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,201],"end":[870,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,149],"end":[810,149]}]}]},{"tag":"LineTo","args":[{"point":[768,149]}]},{"tag":"LineTo","args":[{"point":[768,63]}]},{"tag":"LineTo","args":[{"point":[682,63]}]},{"tag":"LineTo","args":[{"point":[682,149]}]}]},{"start":[512,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,747]}]},{"tag":"LineTo","args":[{"point":[726,747]}]},{"tag":"LineTo","args":[{"point":[726,533]}]},{"tag":"LineTo","args":[{"point":[512,533]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"image","codePoint":59774},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[470,725],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[618,533]}]},{"tag":"LineTo","args":[{"point":[810,789]}]},{"tag":"LineTo","args":[{"point":[214,789]}]},{"tag":"LineTo","args":[{"point":[362,597]}]},{"tag":"LineTo","args":[{"point":[470,725]}]}]},{"start":[896,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,201],"end":[870,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,149],"end":[810,149]}]}]},{"tag":"LineTo","args":[{"point":[214,149]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,149],"end":[154,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,201],"end":[128,235]}]}]},{"tag":"LineTo","args":[{"point":[128,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,865],"end":[154,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,917],"end":[214,917]}]}]},{"tag":"LineTo","args":[{"point":[810,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,917],"end":[870,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,865],"end":[896,831]}]}]},{"tag":"LineTo","args":[{"point":[896,235]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"publish","codePoint":59775},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[384,619],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[384,875]}]},{"tag":"LineTo","args":[{"point":[640,875]}]},{"tag":"LineTo","args":[{"point":[640,619]}]},{"tag":"LineTo","args":[{"point":[810,619]}]},{"tag":"LineTo","args":[{"point":[512,319]}]},{"tag":"LineTo","args":[{"point":[214,619]}]},{"tag":"LineTo","args":[{"point":[384,619]}]}]},{"start":[214,277],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[810,277]}]},{"tag":"LineTo","args":[{"point":[810,191]}]},{"tag":"LineTo","args":[{"point":[214,191]}]},{"tag":"LineTo","args":[{"point":[214,277]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"vertical_align_bottom","codePoint":59776},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[170,917],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[854,917]}]},{"tag":"LineTo","args":[{"point":[854,831]}]},{"tag":"LineTo","args":[{"point":[170,831]}]},{"tag":"LineTo","args":[{"point":[170,917]}]}]},{"start":[554,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,149]}]},{"tag":"LineTo","args":[{"point":[470,149]}]},{"tag":"LineTo","args":[{"point":[470,575]}]},{"tag":"LineTo","args":[{"point":[342,575]}]},{"tag":"LineTo","args":[{"point":[512,747]}]},{"tag":"LineTo","args":[{"point":[682,575]}]},{"tag":"LineTo","args":[{"point":[554,575]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"vertical_align_top","codePoint":59777},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[170,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[854,235]}]},{"tag":"LineTo","args":[{"point":[854,149]}]},{"tag":"LineTo","args":[{"point":[170,149]}]},{"tag":"LineTo","args":[{"point":[170,235]}]}]},{"start":[470,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,917]}]},{"tag":"LineTo","args":[{"point":[554,917]}]},{"tag":"LineTo","args":[{"point":[554,491]}]},{"tag":"LineTo","args":[{"point":[682,491]}]},{"tag":"LineTo","args":[{"point":[512,319]}]},{"tag":"LineTo","args":[{"point":[342,491]}]},{"tag":"LineTo","args":[{"point":[470,491]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"monetization_on","codePoint":59778},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[572,875],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[458,875]}]},{"tag":"LineTo","args":[{"point":[458,791]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[324,761],"end":[318,647]}]}]},{"tag":"LineTo","args":[{"point":[402,647]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[410,727],"end":[516,727]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[572,727],"end":[595,706]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,685],"end":[618,659]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,593],"end":[504,567]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[326,523],"end":[326,411]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[326,357],"end":[363,322]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[400,287],"end":[458,275]}]}]},{"tag":"LineTo","args":[{"point":[458,191]}]},{"tag":"LineTo","args":[{"point":[572,191]}]},{"tag":"LineTo","args":[{"point":[572,275]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[690,305],"end":[694,419]}]}]},{"tag":"LineTo","args":[{"point":[610,419]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[606,339],"end":[516,339]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[468,339],"end":[441,359]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[414,379],"end":[414,409]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[414,463],"end":[526,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[706,537],"end":[706,659]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[706,767],"end":[572,793]}]}]},{"tag":"LineTo","args":[{"point":[572,875]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"cloud","codePoint":59779},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[713,267],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[713,267]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[620,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[422,191],"end":[346,239]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[270,287],"end":[228,365]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[134,375],"end":[67,450]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,525],"end":[0,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,725],"end":[75,800]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[150,875],"end":[256,875]}]}]},{"tag":"LineTo","args":[{"point":[810,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[898,875],"end":[961,812]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,749],"end":[1024,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,577],"end":[966,516]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[908,455],"end":[826,449]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[806,343],"end":[713,267]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"cloud_done","codePoint":59780},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[278,597],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[338,537]}]},{"tag":"LineTo","args":[{"point":[426,625]}]},{"tag":"LineTo","args":[{"point":[648,405]}]},{"tag":"LineTo","args":[{"point":[708,465]}]},{"tag":"LineTo","args":[{"point":[426,747]}]},{"tag":"LineTo","args":[{"point":[278,597]}]}]},{"start":[713,267],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[713,267]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[620,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[422,191],"end":[346,239]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[270,287],"end":[228,365]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[134,375],"end":[67,450]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,525],"end":[0,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,725],"end":[75,800]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[150,875],"end":[256,875]}]}]},{"tag":"LineTo","args":[{"point":[810,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[898,875],"end":[961,812]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,749],"end":[1024,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,577],"end":[966,516]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[908,455],"end":[826,449]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[806,343],"end":[713,267]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"cloud_download","codePoint":59781},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[298,575]}]},{"tag":"LineTo","args":[{"point":[426,575]}]},{"tag":"LineTo","args":[{"point":[426,405]}]},{"tag":"LineTo","args":[{"point":[598,405]}]},{"tag":"LineTo","args":[{"point":[598,575]}]},{"tag":"LineTo","args":[{"point":[726,575]}]},{"tag":"LineTo","args":[{"point":[512,789]}]}]},{"start":[713,267],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[713,267]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[620,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[422,191],"end":[346,239]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[270,287],"end":[228,365]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[134,375],"end":[67,450]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,525],"end":[0,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,725],"end":[75,800]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[150,875],"end":[256,875]}]}]},{"tag":"LineTo","args":[{"point":[810,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[898,875],"end":[961,812]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,749],"end":[1024,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,577],"end":[966,516]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[908,455],"end":[826,449]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[806,343],"end":[713,267]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"cloud_uploadbackup","codePoint":59782},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[598,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,747]}]},{"tag":"LineTo","args":[{"point":[426,575]}]},{"tag":"LineTo","args":[{"point":[298,575]}]},{"tag":"LineTo","args":[{"point":[512,363]}]},{"tag":"LineTo","args":[{"point":[726,575]}]},{"tag":"LineTo","args":[{"point":[598,575]}]},{"tag":"LineTo","args":[{"point":[598,747]}]}]},{"start":[713,267],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[713,267]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[620,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[422,191],"end":[346,239]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[270,287],"end":[228,365]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[134,375],"end":[67,450]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,525],"end":[0,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,725],"end":[75,800]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[150,875],"end":[256,875]}]}]},{"tag":"LineTo","args":[{"point":[810,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[898,875],"end":[961,812]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,749],"end":[1024,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,577],"end":[966,516]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[908,455],"end":[826,449]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[806,343],"end":[713,267]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"file_downloadget_app","codePoint":59783},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[214,875],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[810,875]}]},{"tag":"LineTo","args":[{"point":[810,789]}]},{"tag":"LineTo","args":[{"point":[214,789]}]},{"tag":"LineTo","args":[{"point":[214,875]}]}]},{"start":[640,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[640,149]}]},{"tag":"LineTo","args":[{"point":[384,149]}]},{"tag":"LineTo","args":[{"point":[384,405]}]},{"tag":"LineTo","args":[{"point":[214,405]}]},{"tag":"LineTo","args":[{"point":[512,703]}]},{"tag":"LineTo","args":[{"point":[810,405]}]},{"tag":"LineTo","args":[{"point":[640,405]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"file_upload","codePoint":59784},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[214,875],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[810,875]}]},{"tag":"LineTo","args":[{"point":[810,789]}]},{"tag":"LineTo","args":[{"point":[214,789]}]},{"tag":"LineTo","args":[{"point":[214,875]}]}]},{"start":[640,703],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[640,447]}]},{"tag":"LineTo","args":[{"point":[810,447]}]},{"tag":"LineTo","args":[{"point":[512,149]}]},{"tag":"LineTo","args":[{"point":[214,447]}]},{"tag":"LineTo","args":[{"point":[384,447]}]},{"tag":"LineTo","args":[{"point":[384,703]}]},{"tag":"LineTo","args":[{"point":[640,703]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"audiotrack","codePoint":59785},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,545],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[476,533],"end":[448,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[368,533],"end":[312,589]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,645],"end":[256,725]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,805],"end":[312,861]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[368,917],"end":[448,917]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[522,917],"end":[576,868]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[630,819],"end":[638,747]}]}]},{"tag":"LineTo","args":[{"point":[640,747]}]},{"tag":"LineTo","args":[{"point":[640,277]}]},{"tag":"LineTo","args":[{"point":[810,277]}]},{"tag":"LineTo","args":[{"point":[810,149]}]},{"tag":"LineTo","args":[{"point":[512,149]}]},{"tag":"LineTo","args":[{"point":[512,545]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"music_note","codePoint":59786},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,599],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[468,575],"end":[426,575]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[356,575],"end":[306,626]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,677],"end":[256,747]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,817],"end":[306,867]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[356,917],"end":[426,917]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[496,917],"end":[547,867]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,817],"end":[598,747]}]}]},{"tag":"LineTo","args":[{"point":[598,319]}]},{"tag":"LineTo","args":[{"point":[768,319]}]},{"tag":"LineTo","args":[{"point":[768,149]}]},{"tag":"LineTo","args":[{"point":[512,149]}]},{"tag":"LineTo","args":[{"point":[512,599]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"movie_filter","codePoint":59787},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[682,619],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[642,531]}]},{"tag":"LineTo","args":[{"point":[554,491]}]},{"tag":"LineTo","args":[{"point":[642,451]}]},{"tag":"LineTo","args":[{"point":[682,363]}]},{"tag":"LineTo","args":[{"point":[722,451]}]},{"tag":"LineTo","args":[{"point":[810,491]}]},{"tag":"LineTo","args":[{"point":[722,531]}]},{"tag":"LineTo","args":[{"point":[682,619]}]}]},{"start":[426,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[374,671]}]},{"tag":"LineTo","args":[{"point":[256,619]}]},{"tag":"LineTo","args":[{"point":[374,565]}]},{"tag":"LineTo","args":[{"point":[426,447]}]},{"tag":"LineTo","args":[{"point":[480,565]}]},{"tag":"LineTo","args":[{"point":[598,619]}]},{"tag":"LineTo","args":[{"point":[480,671]}]},{"tag":"LineTo","args":[{"point":[426,789]}]}]},{"start":[854,319],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[726,319]}]},{"tag":"LineTo","args":[{"point":[640,191]}]},{"tag":"LineTo","args":[{"point":[554,191]}]},{"tag":"LineTo","args":[{"point":[640,319]}]},{"tag":"LineTo","args":[{"point":[512,319]}]},{"tag":"LineTo","args":[{"point":[426,191]}]},{"tag":"LineTo","args":[{"point":[342,191]}]},{"tag":"LineTo","args":[{"point":[426,319]}]},{"tag":"LineTo","args":[{"point":[298,319]}]},{"tag":"LineTo","args":[{"point":[214,191]}]},{"tag":"LineTo","args":[{"point":[170,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,191],"end":[111,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,243],"end":[86,277]}]}]},{"tag":"LineTo","args":[{"point":[86,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,823],"end":[111,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,875],"end":[170,875]}]}]},{"tag":"LineTo","args":[{"point":[854,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,875],"end":[913,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,823],"end":[938,789]}]}]},{"tag":"LineTo","args":[{"point":[938,191]}]},{"tag":"LineTo","args":[{"point":[768,191]}]},{"tag":"LineTo","args":[{"point":[854,319]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"local_moviestheaters","codePoint":59788},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[682,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,319]}]},{"tag":"LineTo","args":[{"point":[768,319]}]},{"tag":"LineTo","args":[{"point":[768,405]}]},{"tag":"LineTo","args":[{"point":[682,405]}]}]},{"start":[682,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,491]}]},{"tag":"LineTo","args":[{"point":[768,491]}]},{"tag":"LineTo","args":[{"point":[768,575]}]},{"tag":"LineTo","args":[{"point":[682,575]}]}]},{"start":[682,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,661]}]},{"tag":"LineTo","args":[{"point":[768,661]}]},{"tag":"LineTo","args":[{"point":[768,747]}]},{"tag":"LineTo","args":[{"point":[682,747]}]}]},{"start":[256,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[256,319]}]},{"tag":"LineTo","args":[{"point":[342,319]}]},{"tag":"LineTo","args":[{"point":[342,405]}]},{"tag":"LineTo","args":[{"point":[256,405]}]}]},{"start":[256,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[256,491]}]},{"tag":"LineTo","args":[{"point":[342,491]}]},{"tag":"LineTo","args":[{"point":[342,575]}]},{"tag":"LineTo","args":[{"point":[256,575]}]}]},{"start":[256,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[256,661]}]},{"tag":"LineTo","args":[{"point":[342,661]}]},{"tag":"LineTo","args":[{"point":[342,747]}]},{"tag":"LineTo","args":[{"point":[256,747]}]}]},{"start":[768,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,235]}]},{"tag":"LineTo","args":[{"point":[682,149]}]},{"tag":"LineTo","args":[{"point":[342,149]}]},{"tag":"LineTo","args":[{"point":[342,235]}]},{"tag":"LineTo","args":[{"point":[256,235]}]},{"tag":"LineTo","args":[{"point":[256,149]}]},{"tag":"LineTo","args":[{"point":[170,149]}]},{"tag":"LineTo","args":[{"point":[170,917]}]},{"tag":"LineTo","args":[{"point":[256,917]}]},{"tag":"LineTo","args":[{"point":[256,831]}]},{"tag":"LineTo","args":[{"point":[342,831]}]},{"tag":"LineTo","args":[{"point":[342,917]}]},{"tag":"LineTo","args":[{"point":[682,917]}]},{"tag":"LineTo","args":[{"point":[682,831]}]},{"tag":"LineTo","args":[{"point":[768,831]}]},{"tag":"LineTo","args":[{"point":[768,917]}]},{"tag":"LineTo","args":[{"point":[854,917]}]},{"tag":"LineTo","args":[{"point":[854,149]}]},{"tag":"LineTo","args":[{"point":[768,149]}]},{"tag":"LineTo","args":[{"point":[768,235]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"keyboard_arrow_down","codePoint":59789},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[256,447],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,703]}]},{"tag":"LineTo","args":[{"point":[768,447]}]},{"tag":"LineTo","args":[{"point":[708,387]}]},{"tag":"LineTo","args":[{"point":[512,583]}]},{"tag":"LineTo","args":[{"point":[316,387]}]},{"tag":"LineTo","args":[{"point":[256,447]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"keyboard_arrow_left","codePoint":59790},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[462,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[658,337]}]},{"tag":"LineTo","args":[{"point":[598,277]}]},{"tag":"LineTo","args":[{"point":[342,533]}]},{"tag":"LineTo","args":[{"point":[598,789]}]},{"tag":"LineTo","args":[{"point":[658,729]}]},{"tag":"LineTo","args":[{"point":[462,533]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"keyboard_arrow_right","codePoint":59791},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[426,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,533]}]},{"tag":"LineTo","args":[{"point":[426,277]}]},{"tag":"LineTo","args":[{"point":[366,337]}]},{"tag":"LineTo","args":[{"point":[562,533]}]},{"tag":"LineTo","args":[{"point":[366,729]}]},{"tag":"LineTo","args":[{"point":[426,789]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"keyboard_arrow_up","codePoint":59792},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,483],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[708,679]}]},{"tag":"LineTo","args":[{"point":[768,619]}]},{"tag":"LineTo","args":[{"point":[512,363]}]},{"tag":"LineTo","args":[{"point":[256,619]}]},{"tag":"LineTo","args":[{"point":[316,679]}]},{"tag":"LineTo","args":[{"point":[512,483]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"keyboard_backspace","codePoint":59793},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[292,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[444,337]}]},{"tag":"LineTo","args":[{"point":[384,277]}]},{"tag":"LineTo","args":[{"point":[128,533]}]},{"tag":"LineTo","args":[{"point":[384,789]}]},{"tag":"LineTo","args":[{"point":[444,729]}]},{"tag":"LineTo","args":[{"point":[292,575]}]},{"tag":"LineTo","args":[{"point":[896,575]}]},{"tag":"LineTo","args":[{"point":[896,491]}]},{"tag":"LineTo","args":[{"point":[292,491]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"keyboard_capslock","codePoint":59794},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[768,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,703]}]},{"tag":"LineTo","args":[{"point":[256,703]}]},{"tag":"LineTo","args":[{"point":[256,789]}]},{"tag":"LineTo","args":[{"point":[768,789]}]}]},{"start":[708,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,515]}]},{"tag":"LineTo","args":[{"point":[512,259]}]},{"tag":"LineTo","args":[{"point":[256,515]}]},{"tag":"LineTo","args":[{"point":[316,575]}]},{"tag":"LineTo","args":[{"point":[512,379]}]},{"tag":"LineTo","args":[{"point":[708,575]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"keyboard_hide","codePoint":59795},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[682,831],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[342,831]}]},{"tag":"LineTo","args":[{"point":[512,1003]}]},{"tag":"LineTo","args":[{"point":[682,831]}]}]},{"start":[726,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[726,277]}]},{"tag":"LineTo","args":[{"point":[810,277]}]},{"tag":"LineTo","args":[{"point":[810,363]}]},{"tag":"LineTo","args":[{"point":[726,363]}]}]},{"start":[726,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[726,405]}]},{"tag":"LineTo","args":[{"point":[810,405]}]},{"tag":"LineTo","args":[{"point":[810,491]}]},{"tag":"LineTo","args":[{"point":[726,491]}]}]},{"start":[598,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[598,277]}]},{"tag":"LineTo","args":[{"point":[682,277]}]},{"tag":"LineTo","args":[{"point":[682,363]}]},{"tag":"LineTo","args":[{"point":[598,363]}]}]},{"start":[598,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[598,405]}]},{"tag":"LineTo","args":[{"point":[682,405]}]},{"tag":"LineTo","args":[{"point":[682,491]}]},{"tag":"LineTo","args":[{"point":[598,491]}]}]},{"start":[342,661],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[342,575]}]},{"tag":"LineTo","args":[{"point":[682,575]}]},{"tag":"LineTo","args":[{"point":[682,661]}]},{"tag":"LineTo","args":[{"point":[342,661]}]}]},{"start":[214,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[214,277]}]},{"tag":"LineTo","args":[{"point":[298,277]}]},{"tag":"LineTo","args":[{"point":[298,363]}]},{"tag":"LineTo","args":[{"point":[214,363]}]}]},{"start":[214,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[214,405]}]},{"tag":"LineTo","args":[{"point":[298,405]}]},{"tag":"LineTo","args":[{"point":[298,491]}]},{"tag":"LineTo","args":[{"point":[214,491]}]}]},{"start":[426,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,491]}]},{"tag":"LineTo","args":[{"point":[342,491]}]},{"tag":"LineTo","args":[{"point":[342,405]}]},{"tag":"LineTo","args":[{"point":[426,405]}]}]},{"start":[426,277],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,363]}]},{"tag":"LineTo","args":[{"point":[342,363]}]},{"tag":"LineTo","args":[{"point":[342,277]}]},{"tag":"LineTo","args":[{"point":[426,277]}]}]},{"start":[554,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,491]}]},{"tag":"LineTo","args":[{"point":[470,491]}]},{"tag":"LineTo","args":[{"point":[470,405]}]},{"tag":"LineTo","args":[{"point":[554,405]}]}]},{"start":[554,277],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,363]}]},{"tag":"LineTo","args":[{"point":[470,363]}]},{"tag":"LineTo","args":[{"point":[470,277]}]},{"tag":"LineTo","args":[{"point":[554,277]}]}]},{"start":[170,149],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,149],"end":[111,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,201],"end":[86,235]}]}]},{"tag":"LineTo","args":[{"point":[86,661]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,695],"end":[111,721]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,747],"end":[170,747]}]}]},{"tag":"LineTo","args":[{"point":[854,747]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,747],"end":[913,721]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,695],"end":[938,661]}]}]},{"tag":"LineTo","args":[{"point":[938,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,201],"end":[913,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,149],"end":[854,149]}]}]},{"tag":"LineTo","args":[{"point":[170,149]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"keyboard_tab","codePoint":59796},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[854,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[938,789]}]},{"tag":"LineTo","args":[{"point":[938,277]}]},{"tag":"LineTo","args":[{"point":[854,277]}]},{"tag":"LineTo","args":[{"point":[854,789]}]}]},{"start":[648,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[42,491]}]},{"tag":"LineTo","args":[{"point":[42,575]}]},{"tag":"LineTo","args":[{"point":[648,575]}]},{"tag":"LineTo","args":[{"point":[494,729]}]},{"tag":"LineTo","args":[{"point":[554,789]}]},{"tag":"LineTo","args":[{"point":[810,533]}]},{"tag":"LineTo","args":[{"point":[554,277]}]},{"tag":"LineTo","args":[{"point":[494,337]}]},{"tag":"LineTo","args":[{"point":[648,491]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"keyboard_voice","codePoint":59797},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[671,689],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[671,689]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[604,751],"end":[512,751]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[420,751],"end":[353,689]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[286,627],"end":[286,533]}]}]},{"tag":"LineTo","args":[{"point":[214,533]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,641],"end":[289,722]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[364,803],"end":[470,819]}]}]},{"tag":"LineTo","args":[{"point":[470,959]}]},{"tag":"LineTo","args":[{"point":[554,959]}]},{"tag":"LineTo","args":[{"point":[554,819]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[660,803],"end":[735,722]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[810,641],"end":[810,533]}]}]},{"tag":"LineTo","args":[{"point":[738,533]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[738,627],"end":[671,689]}]}]}]},{"start":[602,623],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[602,623]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,585],"end":[640,533]}]}]},{"tag":"LineTo","args":[{"point":[640,277]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,225],"end":[602,187]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,149],"end":[512,149]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[460,149],"end":[422,187]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,225],"end":[384,277]}]}]},{"tag":"LineTo","args":[{"point":[384,533]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,585],"end":[422,623]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[460,661],"end":[512,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,661],"end":[602,623]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"laptop_chromebook","codePoint":59798},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[170,661],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[170,235]}]},{"tag":"LineTo","args":[{"point":[854,235]}]},{"tag":"LineTo","args":[{"point":[854,661]}]},{"tag":"LineTo","args":[{"point":[170,661]}]}]},{"start":[426,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,747]}]},{"tag":"LineTo","args":[{"point":[598,747]}]},{"tag":"LineTo","args":[{"point":[598,789]}]},{"tag":"LineTo","args":[{"point":[426,789]}]}]},{"start":[938,149],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[86,149]}]},{"tag":"LineTo","args":[{"point":[86,789]}]},{"tag":"LineTo","args":[{"point":[0,789]}]},{"tag":"LineTo","args":[{"point":[0,875]}]},{"tag":"LineTo","args":[{"point":[1024,875]}]},{"tag":"LineTo","args":[{"point":[1024,789]}]},{"tag":"LineTo","args":[{"point":[938,789]}]},{"tag":"LineTo","args":[{"point":[938,149]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"laptop_mac","codePoint":59799},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[482,819],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[482,819]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[470,807],"end":[470,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[470,771],"end":[482,759]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[494,747],"end":[512,747]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[530,747],"end":[542,759]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,771],"end":[554,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,807],"end":[542,819]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[530,831],"end":[512,831]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[494,831],"end":[482,819]}]}]}]},{"start":[854,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[854,703]}]},{"tag":"LineTo","args":[{"point":[170,703]}]},{"tag":"LineTo","args":[{"point":[170,235]}]},{"tag":"LineTo","args":[{"point":[854,235]}]}]},{"start":[913,763],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[913,763]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,737],"end":[938,703]}]}]},{"tag":"LineTo","args":[{"point":[938,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,201],"end":[913,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,149],"end":[854,149]}]}]},{"tag":"LineTo","args":[{"point":[170,149]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,149],"end":[111,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,201],"end":[86,235]}]}]},{"tag":"LineTo","args":[{"point":[86,703]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,737],"end":[111,763]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,789],"end":[170,789]}]}]},{"tag":"LineTo","args":[{"point":[0,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,823],"end":[26,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[52,875],"end":[86,875]}]}]},{"tag":"LineTo","args":[{"point":[938,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[972,875],"end":[998,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,823],"end":[1024,789]}]}]},{"tag":"LineTo","args":[{"point":[854,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,789],"end":[913,763]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"laptop_windows","codePoint":59800},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[854,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[854,661]}]},{"tag":"LineTo","args":[{"point":[170,661]}]},{"tag":"LineTo","args":[{"point":[170,235]}]},{"tag":"LineTo","args":[{"point":[854,235]}]}]},{"start":[854,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,747],"end":[913,721]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,695],"end":[938,661]}]}]},{"tag":"LineTo","args":[{"point":[938,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,201],"end":[913,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,149],"end":[854,149]}]}]},{"tag":"LineTo","args":[{"point":[170,149]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,149],"end":[111,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,201],"end":[86,235]}]}]},{"tag":"LineTo","args":[{"point":[86,661]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,695],"end":[111,721]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,747],"end":[170,747]}]}]},{"tag":"LineTo","args":[{"point":[170,789]}]},{"tag":"LineTo","args":[{"point":[0,789]}]},{"tag":"LineTo","args":[{"point":[0,875]}]},{"tag":"LineTo","args":[{"point":[1024,875]}]},{"tag":"LineTo","args":[{"point":[1024,789]}]},{"tag":"LineTo","args":[{"point":[854,789]}]},{"tag":"LineTo","args":[{"point":[854,747]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"phone_android","codePoint":59801},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[288,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[288,191]}]},{"tag":"LineTo","args":[{"point":[736,191]}]},{"tag":"LineTo","args":[{"point":[736,789]}]},{"tag":"LineTo","args":[{"point":[288,789]}]}]},{"start":[426,917],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,875]}]},{"tag":"LineTo","args":[{"point":[598,875]}]},{"tag":"LineTo","args":[{"point":[598,917]}]},{"tag":"LineTo","args":[{"point":[426,917]}]}]},{"start":[342,63],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,63],"end":[252,101]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,139],"end":[214,191]}]}]},{"tag":"LineTo","args":[{"point":[214,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,927],"end":[252,965]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,1003],"end":[342,1003]}]}]},{"tag":"LineTo","args":[{"point":[682,1003]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[734,1003],"end":[772,965]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[810,927],"end":[810,875]}]}]},{"tag":"LineTo","args":[{"point":[810,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[810,139],"end":[772,101]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[734,63],"end":[682,63]}]}]},{"tag":"LineTo","args":[{"point":[342,63]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"phone_iphone","codePoint":59802},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[298,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[298,191]}]},{"tag":"LineTo","args":[{"point":[682,191]}]},{"tag":"LineTo","args":[{"point":[682,789]}]},{"tag":"LineTo","args":[{"point":[298,789]}]}]},{"start":[445,940],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[445,940]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,921],"end":[426,895]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,869],"end":[445,850]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[464,831],"end":[490,831]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[516,831],"end":[535,850]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,869],"end":[554,895]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,921],"end":[535,940]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[516,959],"end":[490,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[464,959],"end":[445,940]}]}]}]},{"start":[320,63],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[276,63],"end":[245,95]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,127],"end":[214,171]}]}]},{"tag":"LineTo","args":[{"point":[214,895]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,939],"end":[245,971]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[276,1003],"end":[320,1003]}]}]},{"tag":"LineTo","args":[{"point":[662,1003]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[706,1003],"end":[737,971]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,939],"end":[768,895]}]}]},{"tag":"LineTo","args":[{"point":[768,171]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,127],"end":[737,95]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[706,63],"end":[662,63]}]}]},{"tag":"LineTo","args":[{"point":[320,63]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"color_lenspalette","codePoint":59803},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[701,515],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[701,515]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,497],"end":[682,469]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,441],"end":[701,423]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[720,405],"end":[746,405]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[772,405],"end":[791,423]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[810,441],"end":[810,469]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[810,497],"end":[791,515]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[772,533],"end":[746,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[720,533],"end":[701,515]}]}]}]},{"start":[573,344],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[573,344]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,325],"end":[554,299]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,273],"end":[573,254]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[592,235],"end":[618,235]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[644,235],"end":[663,254]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,273],"end":[682,299]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,325],"end":[663,344]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[644,363],"end":[618,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[592,363],"end":[573,344]}]}]}]},{"start":[361,344],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[361,344]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,325],"end":[342,299]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,273],"end":[361,254]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,235],"end":[406,235]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[432,235],"end":[451,254]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[470,273],"end":[470,299]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[470,325],"end":[451,344]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[432,363],"end":[406,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,363],"end":[361,344]}]}]}]},{"start":[233,515],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[233,515]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,497],"end":[214,469]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,441],"end":[233,423]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[252,405],"end":[278,405]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[304,405],"end":[323,423]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,441],"end":[342,469]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,497],"end":[323,515]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[304,533],"end":[278,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[252,533],"end":[233,515]}]}]}]},{"start":[240,261],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[240,261]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,373],"end":[128,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,693],"end":[240,805]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[352,917],"end":[512,917]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[540,917],"end":[558,899]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,881],"end":[576,853]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,829],"end":[560,809]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,789],"end":[544,767]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,741],"end":[562,722]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[580,703],"end":[608,703]}]}]},{"tag":"LineTo","args":[{"point":[682,703]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[770,703],"end":[833,641]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,579],"end":[896,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,349],"end":[783,249]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[670,149],"end":[512,149]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[352,149],"end":[240,261]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"colorize","codePoint":59804},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[214,749],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[558,405]}]},{"tag":"LineTo","args":[{"point":[640,487]}]},{"tag":"LineTo","args":[{"point":[296,831]}]},{"tag":"LineTo","args":[{"point":[214,749]}]}]},{"start":[784,161],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[772,149],"end":[754,149]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,149],"end":[724,161]}]}]},{"tag":"LineTo","args":[{"point":[590,295]}]},{"tag":"LineTo","args":[{"point":[508,213]}]},{"tag":"LineTo","args":[{"point":[448,273]}]},{"tag":"LineTo","args":[{"point":[508,333]}]},{"tag":"LineTo","args":[{"point":[128,715]}]},{"tag":"LineTo","args":[{"point":[128,917]}]},{"tag":"LineTo","args":[{"point":[330,917]}]},{"tag":"LineTo","args":[{"point":[712,537]}]},{"tag":"LineTo","args":[{"point":[772,597]}]},{"tag":"LineTo","args":[{"point":[832,537]}]},{"tag":"LineTo","args":[{"point":[750,455]}]},{"tag":"LineTo","args":[{"point":[884,321]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[914,291],"end":[884,261]}]}]},{"tag":"LineTo","args":[{"point":[784,161]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"navigate_beforechevron_left","codePoint":59805},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[598,277],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[342,533]}]},{"tag":"LineTo","args":[{"point":[598,789]}]},{"tag":"LineTo","args":[{"point":[658,729]}]},{"tag":"LineTo","args":[{"point":[462,533]}]},{"tag":"LineTo","args":[{"point":[658,337]}]},{"tag":"LineTo","args":[{"point":[598,277]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"navigate_nextchevron_right","codePoint":59806},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[366,337],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[562,533]}]},{"tag":"LineTo","args":[{"point":[366,729]}]},{"tag":"LineTo","args":[{"point":[426,789]}]},{"tag":"LineTo","args":[{"point":[682,533]}]},{"tag":"LineTo","args":[{"point":[426,277]}]},{"tag":"LineTo","args":[{"point":[366,337]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"remove_red_eyevisibility","codePoint":59807},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[422,443],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[422,443]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,481],"end":[384,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,585],"end":[422,623]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[460,661],"end":[512,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,661],"end":[602,623]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,585],"end":[640,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,481],"end":[602,443]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,405],"end":[512,405]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[460,405],"end":[422,443]}]}]}]},{"start":[361,684],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[361,684]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,621],"end":[298,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,445],"end":[361,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[424,319],"end":[512,319]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[600,319],"end":[663,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,445],"end":[726,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,621],"end":[663,684]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[600,747],"end":[512,747]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[424,747],"end":[361,684]}]}]}]},{"start":[226,301],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[226,301]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[98,389],"end":[42,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[98,677],"end":[226,765]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[354,853],"end":[512,853]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[670,853],"end":[798,765]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[926,677],"end":[982,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[926,389],"end":[798,301]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[670,213],"end":[512,213]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[354,213],"end":[226,301]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"tune","codePoint":59808},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[726,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[726,319]}]},{"tag":"LineTo","args":[{"point":[896,319]}]},{"tag":"LineTo","args":[{"point":[896,235]}]},{"tag":"LineTo","args":[{"point":[726,235]}]},{"tag":"LineTo","args":[{"point":[726,149]}]},{"tag":"LineTo","args":[{"point":[640,149]}]},{"tag":"LineTo","args":[{"point":[640,405]}]},{"tag":"LineTo","args":[{"point":[726,405]}]}]},{"start":[896,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,491]}]},{"tag":"LineTo","args":[{"point":[470,575]}]},{"tag":"LineTo","args":[{"point":[896,575]}]},{"tag":"LineTo","args":[{"point":[896,491]}]}]},{"start":[298,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[128,491]}]},{"tag":"LineTo","args":[{"point":[128,575]}]},{"tag":"LineTo","args":[{"point":[298,575]}]},{"tag":"LineTo","args":[{"point":[298,661]}]},{"tag":"LineTo","args":[{"point":[384,661]}]},{"tag":"LineTo","args":[{"point":[384,405]}]},{"tag":"LineTo","args":[{"point":[298,405]}]},{"tag":"LineTo","args":[{"point":[298,491]}]}]},{"start":[554,831],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[896,831]}]},{"tag":"LineTo","args":[{"point":[896,747]}]},{"tag":"LineTo","args":[{"point":[554,747]}]},{"tag":"LineTo","args":[{"point":[554,661]}]},{"tag":"LineTo","args":[{"point":[470,661]}]},{"tag":"LineTo","args":[{"point":[470,917]}]},{"tag":"LineTo","args":[{"point":[554,917]}]},{"tag":"LineTo","args":[{"point":[554,831]}]}]},{"start":[128,319],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,319]}]},{"tag":"LineTo","args":[{"point":[554,235]}]},{"tag":"LineTo","args":[{"point":[128,235]}]},{"tag":"LineTo","args":[{"point":[128,319]}]}]},{"start":[128,831],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[384,831]}]},{"tag":"LineTo","args":[{"point":[384,747]}]},{"tag":"LineTo","args":[{"point":[128,747]}]},{"tag":"LineTo","args":[{"point":[128,831]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"add_photo_alternate","codePoint":59809},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[342,661],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,789]}]},{"tag":"LineTo","args":[{"point":[554,619]}]},{"tag":"LineTo","args":[{"point":[726,831]}]},{"tag":"LineTo","args":[{"point":[214,831]}]},{"tag":"LineTo","args":[{"point":[342,661]}]}]},{"start":[682,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,363]}]},{"tag":"LineTo","args":[{"point":[554,235]}]},{"tag":"LineTo","args":[{"point":[214,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,235],"end":[154,260]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,285],"end":[128,319]}]}]},{"tag":"LineTo","args":[{"point":[128,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,865],"end":[154,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,917],"end":[214,917]}]}]},{"tag":"LineTo","args":[{"point":[726,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[760,917],"end":[785,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[810,865],"end":[810,831]}]}]},{"tag":"LineTo","args":[{"point":[810,491]}]},{"tag":"LineTo","args":[{"point":[682,491]}]},{"tag":"LineTo","args":[{"point":[682,363]}]}]},{"start":[938,319],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[938,235]}]},{"tag":"LineTo","args":[{"point":[810,235]}]},{"tag":"LineTo","args":[{"point":[810,107]}]},{"tag":"LineTo","args":[{"point":[726,107]}]},{"tag":"LineTo","args":[{"point":[726,235]}]},{"tag":"LineTo","args":[{"point":[598,235]}]},{"tag":"LineTo","args":[{"point":[598,319]}]},{"tag":"LineTo","args":[{"point":[726,319]}]},{"tag":"LineTo","args":[{"point":[726,447]}]},{"tag":"LineTo","args":[{"point":[810,447]}]},{"tag":"LineTo","args":[{"point":[810,319]}]},{"tag":"LineTo","args":[{"point":[938,319]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"image_search","codePoint":59810},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[586,374],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[586,374]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,343],"end":[554,299]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,255],"end":[586,223]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,191],"end":[662,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[706,191],"end":[737,223]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,255],"end":[768,299]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,343],"end":[737,374]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[706,405],"end":[662,405]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,405],"end":[586,374]}]}]}]},{"start":[854,299],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[854,299]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,219],"end":[798,163]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[742,107],"end":[662,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,107],"end":[526,163]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[470,219],"end":[470,299]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[470,379],"end":[525,435]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[580,491],"end":[660,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[712,491],"end":[762,461]}]}]},{"tag":"LineTo","args":[{"point":[896,593]}]},{"tag":"LineTo","args":[{"point":[956,533]}]},{"tag":"LineTo","args":[{"point":[824,401]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,351],"end":[854,299]}]}]}]},{"start":[552,589],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[436,739]}]},{"tag":"LineTo","args":[{"point":[352,639]}]},{"tag":"LineTo","args":[{"point":[234,789]}]},{"tag":"LineTo","args":[{"point":[704,789]}]},{"tag":"LineTo","args":[{"point":[552,589]}]}]},{"start":[768,875],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[170,875]}]},{"tag":"LineTo","args":[{"point":[170,277]}]},{"tag":"LineTo","args":[{"point":[384,277]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[386,233],"end":[406,191]}]}]},{"tag":"LineTo","args":[{"point":[170,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,191],"end":[111,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,243],"end":[86,277]}]}]},{"tag":"LineTo","args":[{"point":[86,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,909],"end":[111,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,959],"end":[170,959]}]}]},{"tag":"LineTo","args":[{"point":[768,959]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[802,959],"end":[828,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,909],"end":[854,875]}]}]},{"tag":"LineTo","args":[{"point":[854,661]}]},{"tag":"LineTo","args":[{"point":[768,575]}]},{"tag":"LineTo","args":[{"point":[768,875]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"beenhere","codePoint":59811},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[214,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[274,431]}]},{"tag":"LineTo","args":[{"point":[426,583]}]},{"tag":"LineTo","args":[{"point":[750,259]}]},{"tag":"LineTo","args":[{"point":[810,319]}]},{"tag":"LineTo","args":[{"point":[426,703]}]},{"tag":"LineTo","args":[{"point":[214,491]}]}]},{"start":[214,63],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,63],"end":[154,89]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,115],"end":[128,149]}]}]},{"tag":"LineTo","args":[{"point":[128,701]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,743],"end":[166,771]}]}]},{"tag":"LineTo","args":[{"point":[512,1003]}]},{"tag":"LineTo","args":[{"point":[858,771]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,743],"end":[896,701]}]}]},{"tag":"LineTo","args":[{"point":[896,149]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,115],"end":[870,89]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,63],"end":[810,63]}]}]},{"tag":"LineTo","args":[{"point":[214,63]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"apps","codePoint":59812},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[854,875],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[854,703]}]},{"tag":"LineTo","args":[{"point":[682,703]}]},{"tag":"LineTo","args":[{"point":[682,875]}]},{"tag":"LineTo","args":[{"point":[854,875]}]}]},{"start":[854,619],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[854,447]}]},{"tag":"LineTo","args":[{"point":[682,447]}]},{"tag":"LineTo","args":[{"point":[682,619]}]},{"tag":"LineTo","args":[{"point":[854,619]}]}]},{"start":[598,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[598,191]}]},{"tag":"LineTo","args":[{"point":[426,191]}]},{"tag":"LineTo","args":[{"point":[426,363]}]},{"tag":"LineTo","args":[{"point":[598,363]}]}]},{"start":[682,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[854,363]}]},{"tag":"LineTo","args":[{"point":[854,191]}]},{"tag":"LineTo","args":[{"point":[682,191]}]},{"tag":"LineTo","args":[{"point":[682,363]}]}]},{"start":[598,619],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[598,447]}]},{"tag":"LineTo","args":[{"point":[426,447]}]},{"tag":"LineTo","args":[{"point":[426,619]}]},{"tag":"LineTo","args":[{"point":[598,619]}]}]},{"start":[342,619],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[342,447]}]},{"tag":"LineTo","args":[{"point":[170,447]}]},{"tag":"LineTo","args":[{"point":[170,619]}]},{"tag":"LineTo","args":[{"point":[342,619]}]}]},{"start":[342,875],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[342,703]}]},{"tag":"LineTo","args":[{"point":[170,703]}]},{"tag":"LineTo","args":[{"point":[170,875]}]},{"tag":"LineTo","args":[{"point":[342,875]}]}]},{"start":[598,875],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[598,703]}]},{"tag":"LineTo","args":[{"point":[426,703]}]},{"tag":"LineTo","args":[{"point":[426,875]}]},{"tag":"LineTo","args":[{"point":[598,875]}]}]},{"start":[342,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[342,191]}]},{"tag":"LineTo","args":[{"point":[170,191]}]},{"tag":"LineTo","args":[{"point":[170,363]}]},{"tag":"LineTo","args":[{"point":[342,363]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"arrow_back","codePoint":59813},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[334,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[572,251]}]},{"tag":"LineTo","args":[{"point":[512,191]}]},{"tag":"LineTo","args":[{"point":[170,533]}]},{"tag":"LineTo","args":[{"point":[512,875]}]},{"tag":"LineTo","args":[{"point":[572,815]}]},{"tag":"LineTo","args":[{"point":[334,575]}]},{"tag":"LineTo","args":[{"point":[854,575]}]},{"tag":"LineTo","args":[{"point":[854,491]}]},{"tag":"LineTo","args":[{"point":[334,491]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"arrow_drop_down","codePoint":59814},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,661],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[726,447]}]},{"tag":"LineTo","args":[{"point":[298,447]}]},{"tag":"LineTo","args":[{"point":[512,661]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"arrow_drop_down_circle","codePoint":59815},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[342,447],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,447]}]},{"tag":"LineTo","args":[{"point":[512,619]}]},{"tag":"LineTo","args":[{"point":[342,447]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"arrow_drop_up","codePoint":59816},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[726,619],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,405]}]},{"tag":"LineTo","args":[{"point":[298,619]}]},{"tag":"LineTo","args":[{"point":[726,619]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"arrow_forward","codePoint":59817},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[452,251],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[690,491]}]},{"tag":"LineTo","args":[{"point":[170,491]}]},{"tag":"LineTo","args":[{"point":[170,575]}]},{"tag":"LineTo","args":[{"point":[690,575]}]},{"tag":"LineTo","args":[{"point":[452,815]}]},{"tag":"LineTo","args":[{"point":[512,875]}]},{"tag":"LineTo","args":[{"point":[854,533]}]},{"tag":"LineTo","args":[{"point":[512,191]}]},{"tag":"LineTo","args":[{"point":[452,251]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"cancel","codePoint":59818},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[666,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,593]}]},{"tag":"LineTo","args":[{"point":[358,747]}]},{"tag":"LineTo","args":[{"point":[298,687]}]},{"tag":"LineTo","args":[{"point":[452,533]}]},{"tag":"LineTo","args":[{"point":[298,379]}]},{"tag":"LineTo","args":[{"point":[358,319]}]},{"tag":"LineTo","args":[{"point":[512,473]}]},{"tag":"LineTo","args":[{"point":[666,319]}]},{"tag":"LineTo","args":[{"point":[726,379]}]},{"tag":"LineTo","args":[{"point":[572,533]}]},{"tag":"LineTo","args":[{"point":[726,687]}]},{"tag":"LineTo","args":[{"point":[666,747]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"check","codePoint":59819},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[206,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[146,593]}]},{"tag":"LineTo","args":[{"point":[384,831]}]},{"tag":"LineTo","args":[{"point":[896,319]}]},{"tag":"LineTo","args":[{"point":[836,259]}]},{"tag":"LineTo","args":[{"point":[384,711]}]},{"tag":"LineTo","args":[{"point":[206,533]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"expand_less","codePoint":59820},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[256,619],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[316,679]}]},{"tag":"LineTo","args":[{"point":[512,483]}]},{"tag":"LineTo","args":[{"point":[708,679]}]},{"tag":"LineTo","args":[{"point":[768,619]}]},{"tag":"LineTo","args":[{"point":[512,363]}]},{"tag":"LineTo","args":[{"point":[256,619]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"expand_more","codePoint":59821},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,583],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[316,387]}]},{"tag":"LineTo","args":[{"point":[256,447]}]},{"tag":"LineTo","args":[{"point":[512,703]}]},{"tag":"LineTo","args":[{"point":[768,447]}]},{"tag":"LineTo","args":[{"point":[708,387]}]},{"tag":"LineTo","args":[{"point":[512,583]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"fullscreen","codePoint":59822},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[598,319],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[726,319]}]},{"tag":"LineTo","args":[{"point":[726,447]}]},{"tag":"LineTo","args":[{"point":[810,447]}]},{"tag":"LineTo","args":[{"point":[810,235]}]},{"tag":"LineTo","args":[{"point":[598,235]}]},{"tag":"LineTo","args":[{"point":[598,319]}]}]},{"start":[598,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[598,831]}]},{"tag":"LineTo","args":[{"point":[810,831]}]},{"tag":"LineTo","args":[{"point":[810,619]}]},{"tag":"LineTo","args":[{"point":[726,619]}]},{"tag":"LineTo","args":[{"point":[726,747]}]},{"tag":"LineTo","args":[{"point":[598,747]}]}]},{"start":[298,447],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[298,319]}]},{"tag":"LineTo","args":[{"point":[426,319]}]},{"tag":"LineTo","args":[{"point":[426,235]}]},{"tag":"LineTo","args":[{"point":[214,235]}]},{"tag":"LineTo","args":[{"point":[214,447]}]},{"tag":"LineTo","args":[{"point":[298,447]}]}]},{"start":[214,619],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[214,831]}]},{"tag":"LineTo","args":[{"point":[426,831]}]},{"tag":"LineTo","args":[{"point":[426,747]}]},{"tag":"LineTo","args":[{"point":[298,747]}]},{"tag":"LineTo","args":[{"point":[298,619]}]},{"tag":"LineTo","args":[{"point":[214,619]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"fullscreen_exit","codePoint":59823},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[682,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[598,235]}]},{"tag":"LineTo","args":[{"point":[598,447]}]},{"tag":"LineTo","args":[{"point":[810,447]}]},{"tag":"LineTo","args":[{"point":[810,363]}]},{"tag":"LineTo","args":[{"point":[682,363]}]},{"tag":"LineTo","args":[{"point":[682,235]}]}]},{"start":[682,831],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,703]}]},{"tag":"LineTo","args":[{"point":[810,703]}]},{"tag":"LineTo","args":[{"point":[810,619]}]},{"tag":"LineTo","args":[{"point":[598,619]}]},{"tag":"LineTo","args":[{"point":[598,831]}]},{"tag":"LineTo","args":[{"point":[682,831]}]}]},{"start":[214,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[214,447]}]},{"tag":"LineTo","args":[{"point":[426,447]}]},{"tag":"LineTo","args":[{"point":[426,235]}]},{"tag":"LineTo","args":[{"point":[342,235]}]},{"tag":"LineTo","args":[{"point":[342,363]}]},{"tag":"LineTo","args":[{"point":[214,363]}]}]},{"start":[342,703],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[342,831]}]},{"tag":"LineTo","args":[{"point":[426,831]}]},{"tag":"LineTo","args":[{"point":[426,619]}]},{"tag":"LineTo","args":[{"point":[214,619]}]},{"tag":"LineTo","args":[{"point":[214,703]}]},{"tag":"LineTo","args":[{"point":[342,703]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"menu","codePoint":59824},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[128,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[896,363]}]},{"tag":"LineTo","args":[{"point":[896,277]}]},{"tag":"LineTo","args":[{"point":[128,277]}]},{"tag":"LineTo","args":[{"point":[128,363]}]}]},{"start":[896,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[896,491]}]},{"tag":"LineTo","args":[{"point":[128,491]}]},{"tag":"LineTo","args":[{"point":[128,575]}]},{"tag":"LineTo","args":[{"point":[896,575]}]}]},{"start":[896,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[896,703]}]},{"tag":"LineTo","args":[{"point":[128,703]}]},{"tag":"LineTo","args":[{"point":[128,789]}]},{"tag":"LineTo","args":[{"point":[896,789]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"keyboard_control","codePoint":59825},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[452,473],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[452,473]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,499],"end":[426,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,567],"end":[452,593]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,619],"end":[512,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,619],"end":[572,593]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,567],"end":[598,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,499],"end":[572,473]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,447],"end":[512,447]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,447],"end":[452,473]}]}]}]},{"start":[708,473],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[708,473]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,499],"end":[682,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,567],"end":[708,593]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[734,619],"end":[768,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[802,619],"end":[828,593]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,567],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,499],"end":[828,473]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[802,447],"end":[768,447]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[734,447],"end":[708,473]}]}]}]},{"start":[196,473],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[196,473]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,499],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,567],"end":[196,593]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,619],"end":[256,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,619],"end":[316,593]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,567],"end":[342,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,499],"end":[316,473]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,447],"end":[256,447]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,447],"end":[196,473]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"more_vert","codePoint":59826},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[452,729],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[452,729]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,755],"end":[426,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,823],"end":[452,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,875],"end":[572,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,823],"end":[598,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,755],"end":[572,729]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,703],"end":[512,703]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,703],"end":[452,729]}]}]}]},{"start":[452,473],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[452,473]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,499],"end":[426,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,567],"end":[452,593]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,619],"end":[512,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,619],"end":[572,593]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,567],"end":[598,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,499],"end":[572,473]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,447],"end":[512,447]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,447],"end":[452,473]}]}]}]},{"start":[572,337],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[572,337]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,311],"end":[598,277]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,243],"end":[572,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,191],"end":[452,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,243],"end":[426,277]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,311],"end":[452,337]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,363],"end":[512,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,363],"end":[572,337]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"refresh","codePoint":59827},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[643,220],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[643,220]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[572,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[272,291]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[172,391],"end":[172,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[172,675],"end":[272,775]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[630,875],"end":[722,803]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[814,731],"end":[842,619]}]}]},{"tag":"LineTo","args":[{"point":[754,619]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[728,689],"end":[657,739]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[586,789],"end":[512,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[406,789],"end":[331,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,639],"end":[256,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,427],"end":[331,352]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[406,277],"end":[512,277]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[616,277],"end":[692,353]}]}]},{"tag":"LineTo","args":[{"point":[554,491]}]},{"tag":"LineTo","args":[{"point":[854,491]}]},{"tag":"LineTo","args":[{"point":[854,191]}]},{"tag":"LineTo","args":[{"point":[754,291]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[714,249],"end":[643,220]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"unfold_less","codePoint":59828},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[648,191],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,327]}]},{"tag":"LineTo","args":[{"point":[376,191]}]},{"tag":"LineTo","args":[{"point":[316,251]}]},{"tag":"LineTo","args":[{"point":[512,447]}]},{"tag":"LineTo","args":[{"point":[708,251]}]},{"tag":"LineTo","args":[{"point":[648,191]}]}]},{"start":[376,875],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,739]}]},{"tag":"LineTo","args":[{"point":[648,875]}]},{"tag":"LineTo","args":[{"point":[708,815]}]},{"tag":"LineTo","args":[{"point":[512,619]}]},{"tag":"LineTo","args":[{"point":[316,815]}]},{"tag":"LineTo","args":[{"point":[376,875]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"unfold_more","codePoint":59829},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[376,661],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[316,721]}]},{"tag":"LineTo","args":[{"point":[512,917]}]},{"tag":"LineTo","args":[{"point":[708,721]}]},{"tag":"LineTo","args":[{"point":[648,661]}]},{"tag":"LineTo","args":[{"point":[512,797]}]},{"tag":"LineTo","args":[{"point":[376,661]}]}]},{"start":[648,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[708,345]}]},{"tag":"LineTo","args":[{"point":[512,149]}]},{"tag":"LineTo","args":[{"point":[316,345]}]},{"tag":"LineTo","args":[{"point":[376,405]}]},{"tag":"LineTo","args":[{"point":[512,269]}]},{"tag":"LineTo","args":[{"point":[648,405]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"arrow_upward","codePoint":59830},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[230,593],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,355]}]},{"tag":"LineTo","args":[{"point":[470,875]}]},{"tag":"LineTo","args":[{"point":[554,875]}]},{"tag":"LineTo","args":[{"point":[554,355]}]},{"tag":"LineTo","args":[{"point":[792,593]}]},{"tag":"LineTo","args":[{"point":[854,533]}]},{"tag":"LineTo","args":[{"point":[512,191]}]},{"tag":"LineTo","args":[{"point":[170,533]}]},{"tag":"LineTo","args":[{"point":[230,593]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"subdirectory_arrow_left","codePoint":59831},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[214,661],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,917]}]},{"tag":"LineTo","args":[{"point":[530,857]}]},{"tag":"LineTo","args":[{"point":[376,703]}]},{"tag":"LineTo","args":[{"point":[854,703]}]},{"tag":"LineTo","args":[{"point":[854,191]}]},{"tag":"LineTo","args":[{"point":[768,191]}]},{"tag":"LineTo","args":[{"point":[768,619]}]},{"tag":"LineTo","args":[{"point":[376,619]}]},{"tag":"LineTo","args":[{"point":[530,465]}]},{"tag":"LineTo","args":[{"point":[470,405]}]},{"tag":"LineTo","args":[{"point":[214,661]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"subdirectory_arrow_right","codePoint":59832},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[554,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[494,465]}]},{"tag":"LineTo","args":[{"point":[648,619]}]},{"tag":"LineTo","args":[{"point":[256,619]}]},{"tag":"LineTo","args":[{"point":[256,191]}]},{"tag":"LineTo","args":[{"point":[170,191]}]},{"tag":"LineTo","args":[{"point":[170,703]}]},{"tag":"LineTo","args":[{"point":[648,703]}]},{"tag":"LineTo","args":[{"point":[494,857]}]},{"tag":"LineTo","args":[{"point":[554,917]}]},{"tag":"LineTo","args":[{"point":[810,661]}]},{"tag":"LineTo","args":[{"point":[554,405]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"arrow_downward","codePoint":59833},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[794,473],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,711]}]},{"tag":"LineTo","args":[{"point":[554,191]}]},{"tag":"LineTo","args":[{"point":[470,191]}]},{"tag":"LineTo","args":[{"point":[470,711]}]},{"tag":"LineTo","args":[{"point":[232,473]}]},{"tag":"LineTo","args":[{"point":[170,533]}]},{"tag":"LineTo","args":[{"point":[512,875]}]},{"tag":"LineTo","args":[{"point":[854,533]}]},{"tag":"LineTo","args":[{"point":[794,473]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"first_page","codePoint":59834},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[256,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[342,789]}]},{"tag":"LineTo","args":[{"point":[342,277]}]},{"tag":"LineTo","args":[{"point":[256,277]}]},{"tag":"LineTo","args":[{"point":[256,789]}]}]},{"start":[590,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[786,337]}]},{"tag":"LineTo","args":[{"point":[726,277]}]},{"tag":"LineTo","args":[{"point":[470,533]}]},{"tag":"LineTo","args":[{"point":[726,789]}]},{"tag":"LineTo","args":[{"point":[786,729]}]},{"tag":"LineTo","args":[{"point":[590,533]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"last_page","codePoint":59835},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[682,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,789]}]},{"tag":"LineTo","args":[{"point":[768,277]}]},{"tag":"LineTo","args":[{"point":[682,277]}]},{"tag":"LineTo","args":[{"point":[682,789]}]}]},{"start":[434,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[238,729]}]},{"tag":"LineTo","args":[{"point":[298,789]}]},{"tag":"LineTo","args":[{"point":[554,533]}]},{"tag":"LineTo","args":[{"point":[298,277]}]},{"tag":"LineTo","args":[{"point":[238,337]}]},{"tag":"LineTo","args":[{"point":[434,533]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"arrow_left","codePoint":59836},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[384,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[598,747]}]},{"tag":"LineTo","args":[{"point":[598,319]}]},{"tag":"LineTo","args":[{"point":[384,533]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"arrow_right","codePoint":59837},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[640,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,319]}]},{"tag":"LineTo","args":[{"point":[426,747]}]},{"tag":"LineTo","args":[{"point":[640,533]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"arrow_back_ios","codePoint":59838},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[422,111],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[0,533]}]},{"tag":"LineTo","args":[{"point":[422,955]}]},{"tag":"LineTo","args":[{"point":[498,879]}]},{"tag":"LineTo","args":[{"point":[152,533]}]},{"tag":"LineTo","args":[{"point":[498,187]}]},{"tag":"LineTo","args":[{"point":[422,111]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"arrow_forward_ios","codePoint":59839},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[588,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[250,869]}]},{"tag":"LineTo","args":[{"point":[342,959]}]},{"tag":"LineTo","args":[{"point":[768,533]}]},{"tag":"LineTo","args":[{"point":[342,107]}]},{"tag":"LineTo","args":[{"point":[250,197]}]},{"tag":"LineTo","args":[{"point":[588,533]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder_special","codePoint":59840},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[640,673],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[514,747]}]},{"tag":"LineTo","args":[{"point":[548,605]}]},{"tag":"LineTo","args":[{"point":[438,509]}]},{"tag":"LineTo","args":[{"point":[582,497]}]},{"tag":"LineTo","args":[{"point":[640,363]}]},{"tag":"LineTo","args":[{"point":[698,497]}]},{"tag":"LineTo","args":[{"point":[842,509]}]},{"tag":"LineTo","args":[{"point":[732,605]}]},{"tag":"LineTo","args":[{"point":[766,747]}]},{"tag":"LineTo","args":[{"point":[640,673]}]}]},{"start":[512,277],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,191]}]},{"tag":"LineTo","args":[{"point":[170,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,191],"end":[111,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,243],"end":[86,277]}]}]},{"tag":"LineTo","args":[{"point":[86,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,823],"end":[111,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,875],"end":[170,875]}]}]},{"tag":"LineTo","args":[{"point":[854,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,875],"end":[913,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,823],"end":[938,789]}]}]},{"tag":"LineTo","args":[{"point":[938,363]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,329],"end":[913,303]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,277],"end":[854,277]}]}]},{"tag":"LineTo","args":[{"point":[512,277]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"priority_high","codePoint":59841},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[426,661],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[598,661]}]},{"tag":"LineTo","args":[{"point":[598,149]}]},{"tag":"LineTo","args":[{"point":[426,149]}]},{"tag":"LineTo","args":[{"point":[426,661]}]}]},{"start":[451,892],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[451,892]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[476,917],"end":[512,917]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[548,917],"end":[573,892]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,867],"end":[598,831]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,795],"end":[573,771]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[548,747],"end":[512,747]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[476,747],"end":[451,771]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,795],"end":[426,831]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,867],"end":[451,892]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"notifications","codePoint":59842},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[768,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,391],"end":[717,317]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[666,243],"end":[576,221]}]}]},{"tag":"LineTo","args":[{"point":[576,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,165],"end":[558,146]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[540,127],"end":[512,127]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[484,127],"end":[466,146]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[448,165],"end":[448,191]}]}]},{"tag":"LineTo","args":[{"point":[448,221]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[358,243],"end":[307,317]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,391],"end":[256,491]}]}]},{"tag":"LineTo","args":[{"point":[256,703]}]},{"tag":"LineTo","args":[{"point":[170,789]}]},{"tag":"LineTo","args":[{"point":[170,831]}]},{"tag":"LineTo","args":[{"point":[854,831]}]},{"tag":"LineTo","args":[{"point":[854,789]}]},{"tag":"LineTo","args":[{"point":[768,703]}]},{"tag":"LineTo","args":[{"point":[768,491]}]}]},{"start":[572,934],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[572,934]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,909],"end":[598,875]}]}]},{"tag":"LineTo","args":[{"point":[426,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,911],"end":[451,935]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[476,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,959],"end":[572,934]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"notifications_none","codePoint":59843},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[342,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[342,491]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,409],"end":[388,354]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[434,299],"end":[512,299]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[590,299],"end":[636,354]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,409],"end":[682,491]}]}]},{"tag":"LineTo","args":[{"point":[682,747]}]},{"tag":"LineTo","args":[{"point":[342,747]}]}]},{"start":[768,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,391],"end":[717,317]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[666,243],"end":[576,221]}]}]},{"tag":"LineTo","args":[{"point":[576,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,165],"end":[558,146]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[540,127],"end":[512,127]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[484,127],"end":[466,146]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[448,165],"end":[448,191]}]}]},{"tag":"LineTo","args":[{"point":[448,221]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[358,243],"end":[307,317]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,391],"end":[256,491]}]}]},{"tag":"LineTo","args":[{"point":[256,703]}]},{"tag":"LineTo","args":[{"point":[170,789]}]},{"tag":"LineTo","args":[{"point":[170,831]}]},{"tag":"LineTo","args":[{"point":[854,831]}]},{"tag":"LineTo","args":[{"point":[854,789]}]},{"tag":"LineTo","args":[{"point":[768,703]}]},{"tag":"LineTo","args":[{"point":[768,491]}]}]},{"start":[572,934],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[572,934]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,909],"end":[598,875]}]}]},{"tag":"LineTo","args":[{"point":[426,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,909],"end":[452,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,959],"end":[572,934]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"person","codePoint":59844},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[287,666],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[287,666]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,713],"end":[170,789]}]}]},{"tag":"LineTo","args":[{"point":[170,875]}]},{"tag":"LineTo","args":[{"point":[854,875]}]},{"tag":"LineTo","args":[{"point":[854,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,713],"end":[737,666]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[620,619],"end":[512,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[404,619],"end":[287,666]}]}]}]},{"start":[632,483],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[632,483]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,433],"end":[682,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,293],"end":[632,242]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[442,191],"end":[392,242]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,293],"end":[342,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,433],"end":[392,483]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[442,533],"end":[512,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,533],"end":[632,483]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"public","codePoint":59845},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[682,703],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,703]}]},{"tag":"LineTo","args":[{"point":[640,703]}]},{"tag":"LineTo","args":[{"point":[640,575]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,557],"end":[628,545]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[616,533],"end":[598,533]}]}]},{"tag":"LineTo","args":[{"point":[342,533]}]},{"tag":"LineTo","args":[{"point":[342,447]}]},{"tag":"LineTo","args":[{"point":[426,447]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[444,447],"end":[457,435]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[470,423],"end":[470,405]}]}]},{"tag":"LineTo","args":[{"point":[470,319]}]},{"tag":"LineTo","args":[{"point":[554,319]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[588,319],"end":[614,294]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,269],"end":[640,235]}]}]},{"tag":"LineTo","args":[{"point":[640,217]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,255],"end":[795,341]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,427],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,667],"end":[764,763]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[742,703],"end":[682,703]}]}]}]},{"start":[257,759],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[257,759]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,663],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,497],"end":[180,457]}]}]},{"tag":"LineTo","args":[{"point":[384,661]}]},{"tag":"LineTo","args":[{"point":[384,703]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,737],"end":[410,763]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,789],"end":[470,789]}]}]},{"tag":"LineTo","args":[{"point":[470,871]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[344,855],"end":[257,759]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"share","codePoint":59846},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[684,739],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[684,739]}]},{"tag":"LineTo","args":[{"point":[380,563]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,543],"end":[384,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,523],"end":[380,503]}]}]},{"tag":"LineTo","args":[{"point":[680,327]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[720,363],"end":[768,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[820,363],"end":[858,325]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,287],"end":[896,235]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,183],"end":[858,145]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[820,107],"end":[768,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[716,107],"end":[678,145]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,183],"end":[640,235]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,245],"end":[644,265]}]}]},{"tag":"LineTo","args":[{"point":[344,439]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[306,405],"end":[256,405]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[204,405],"end":[166,443]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,481],"end":[128,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,585],"end":[166,623]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[204,661],"end":[256,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[306,661],"end":[344,627]}]}]},{"tag":"LineTo","args":[{"point":[646,803]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[644,811],"end":[644,831]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[644,883],"end":[681,920]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[718,957],"end":[768,957]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[818,957],"end":[855,920]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[892,883],"end":[892,831]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[892,781],"end":[856,744]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[820,707],"end":[768,707]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[720,707],"end":[684,739]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"sentiment_dissatisfied","codePoint":59847},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[596,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[596,747]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,743],"end":[617,722]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,701],"end":[640,699]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[580,661],"end":[512,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[440,661],"end":[384,699]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[404,721],"end":[406,723]}]}]},{"tag":"LineTo","args":[{"point":[428,747]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[468,725],"end":[512,725]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[558,725],"end":[596,747]}]}]}]},{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]},{"start":[317,472],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[317,472]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,491],"end":[362,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,491],"end":[407,472]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,453],"end":[426,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,401],"end":[407,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,363],"end":[362,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,363],"end":[317,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,401],"end":[298,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,453],"end":[317,472]}]}]}]},{"start":[617,472],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[617,472]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,491],"end":[662,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,491],"end":[707,472]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,453],"end":[726,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,401],"end":[707,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,363],"end":[662,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,363],"end":[617,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,401],"end":[598,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,453],"end":[617,472]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"sentiment_neutral","codePoint":59848},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]},{"start":[317,472],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[317,472]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,491],"end":[362,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,491],"end":[407,472]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,453],"end":[426,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,401],"end":[407,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,363],"end":[362,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,363],"end":[317,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,401],"end":[298,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,453],"end":[317,472]}]}]}]},{"start":[617,472],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[617,472]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,491],"end":[662,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,491],"end":[707,472]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,453],"end":[726,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,401],"end":[707,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,363],"end":[662,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,363],"end":[617,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,401],"end":[598,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,453],"end":[617,472]}]}]}]},{"start":[384,725],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[640,725]}]},{"tag":"LineTo","args":[{"point":[640,683]}]},{"tag":"LineTo","args":[{"point":[384,683]}]},{"tag":"LineTo","args":[{"point":[384,725]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"sentiment_satisfied","codePoint":59849},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[428,681],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[428,681]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[410,699],"end":[386,731]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[444,767],"end":[512,767]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,767],"end":[640,731]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[634,725],"end":[596,681]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[556,703],"end":[512,703]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[466,703],"end":[428,681]}]}]}]},{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]},{"start":[317,472],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[317,472]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,491],"end":[362,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,491],"end":[407,472]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,453],"end":[426,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,401],"end":[407,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,363],"end":[362,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,363],"end":[317,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,401],"end":[298,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,453],"end":[317,472]}]}]}]},{"start":[617,472],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[617,472]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,491],"end":[662,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,491],"end":[707,472]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,453],"end":[726,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,401],"end":[707,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,363],"end":[662,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,363],"end":[617,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,401],"end":[598,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,453],"end":[617,472]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"sentiment_very_dissatisfied","codePoint":59850},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[379,660],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[379,660]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,701],"end":[294,767]}]}]},{"tag":"LineTo","args":[{"point":[364,767]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[414,683],"end":[512,683]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[610,683],"end":[660,767]}]}]},{"tag":"LineTo","args":[{"point":[730,767]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,701],"end":[645,660]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[586,619],"end":[512,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[438,619],"end":[379,660]}]}]}]},{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]},{"start":[317,472],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[317,472]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,491],"end":[362,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,491],"end":[407,472]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,453],"end":[426,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,401],"end":[407,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,363],"end":[362,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,363],"end":[317,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,401],"end":[298,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,453],"end":[317,472]}]}]}]},{"start":[617,472],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[617,472]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,491],"end":[662,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,491],"end":[707,472]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,453],"end":[726,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,401],"end":[707,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,363],"end":[662,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,363],"end":[617,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,401],"end":[598,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,453],"end":[617,472]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"sentiment_very_satisfied","codePoint":59851},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[382,742],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[382,742]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[440,789],"end":[512,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[584,789],"end":[642,742]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[700,695],"end":[726,619]}]}]},{"tag":"LineTo","args":[{"point":[298,619]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[324,695],"end":[382,742]}]}]}]},{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]},{"start":[317,472],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[317,472]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,491],"end":[362,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,491],"end":[407,472]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,453],"end":[426,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,401],"end":[407,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,363],"end":[362,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,363],"end":[317,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,401],"end":[298,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,453],"end":[317,472]}]}]}]},{"start":[617,472],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[617,472]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,491],"end":[662,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,491],"end":[707,472]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,453],"end":[726,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,401],"end":[707,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,363],"end":[662,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,363],"end":[617,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,401],"end":[598,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,453],"end":[617,472]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"stargrade","codePoint":59852},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[776,917],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[706,617]}]},{"tag":"LineTo","args":[{"point":[938,415]}]},{"tag":"LineTo","args":[{"point":[632,389]}]},{"tag":"LineTo","args":[{"point":[512,107]}]},{"tag":"LineTo","args":[{"point":[392,389]}]},{"tag":"LineTo","args":[{"point":[86,415]}]},{"tag":"LineTo","args":[{"point":[318,617]}]},{"tag":"LineTo","args":[{"point":[248,917]}]},{"tag":"LineTo","args":[{"point":[512,757]}]},{"tag":"LineTo","args":[{"point":[776,917]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"star_half","codePoint":59853},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,281],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[584,453]}]},{"tag":"LineTo","args":[{"point":[772,469]}]},{"tag":"LineTo","args":[{"point":[630,593]}]},{"tag":"LineTo","args":[{"point":[672,775]}]},{"tag":"LineTo","args":[{"point":[512,679]}]},{"tag":"LineTo","args":[{"point":[512,281]}]}]},{"start":[632,389],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,107]}]},{"tag":"LineTo","args":[{"point":[392,389]}]},{"tag":"LineTo","args":[{"point":[86,415]}]},{"tag":"LineTo","args":[{"point":[318,617]}]},{"tag":"LineTo","args":[{"point":[248,917]}]},{"tag":"LineTo","args":[{"point":[512,757]}]},{"tag":"LineTo","args":[{"point":[776,917]}]},{"tag":"LineTo","args":[{"point":[706,617]}]},{"tag":"LineTo","args":[{"point":[938,415]}]},{"tag":"LineTo","args":[{"point":[632,389]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"star_outline","codePoint":59854},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[352,775],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[394,593]}]},{"tag":"LineTo","args":[{"point":[252,469]}]},{"tag":"LineTo","args":[{"point":[440,453]}]},{"tag":"LineTo","args":[{"point":[512,281]}]},{"tag":"LineTo","args":[{"point":[584,453]}]},{"tag":"LineTo","args":[{"point":[772,469]}]},{"tag":"LineTo","args":[{"point":[630,593]}]},{"tag":"LineTo","args":[{"point":[672,775]}]},{"tag":"LineTo","args":[{"point":[512,679]}]},{"tag":"LineTo","args":[{"point":[352,775]}]}]},{"start":[632,389],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,107]}]},{"tag":"LineTo","args":[{"point":[392,389]}]},{"tag":"LineTo","args":[{"point":[86,415]}]},{"tag":"LineTo","args":[{"point":[318,617]}]},{"tag":"LineTo","args":[{"point":[248,917]}]},{"tag":"LineTo","args":[{"point":[512,757]}]},{"tag":"LineTo","args":[{"point":[776,917]}]},{"tag":"LineTo","args":[{"point":[706,617]}]},{"tag":"LineTo","args":[{"point":[938,415]}]},{"tag":"LineTo","args":[{"point":[632,389]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"account_box","codePoint":59855},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[344,652],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[344,652]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[432,615],"end":[512,615]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[592,615],"end":[680,652]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,689],"end":[768,747]}]}]},{"tag":"LineTo","args":[{"point":[768,789]}]},{"tag":"LineTo","args":[{"point":[256,789]}]},{"tag":"LineTo","args":[{"point":[256,747]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,689],"end":[344,652]}]}]}]},{"start":[602,495],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[602,495]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,533],"end":[512,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[460,533],"end":[422,495]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,457],"end":[384,405]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,353],"end":[422,315]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[460,277],"end":[512,277]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,277],"end":[602,315]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,353],"end":[640,405]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,457],"end":[602,495]}]}]}]},{"start":[128,831],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,867],"end":[153,892]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,917],"end":[214,917]}]}]},{"tag":"LineTo","args":[{"point":[810,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,917],"end":[870,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,865],"end":[896,831]}]}]},{"tag":"LineTo","args":[{"point":[896,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,201],"end":[870,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,149],"end":[810,149]}]}]},{"tag":"LineTo","args":[{"point":[214,149]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,149],"end":[153,174]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,199],"end":[128,235]}]}]},{"tag":"LineTo","args":[{"point":[128,831]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"account_circle","codePoint":59856},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[369,801],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[369,801]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[294,761],"end":[256,703]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[258,645],"end":[346,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[434,571],"end":[512,571]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[590,571],"end":[678,609]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[766,647],"end":[768,703]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[730,761],"end":[655,801]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[580,841],"end":[512,841]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[444,841],"end":[369,801]}]}]}]},{"start":[602,273],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[602,273]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,311],"end":[640,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,415],"end":[602,453]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,491],"end":[512,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[460,491],"end":[422,453]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,415],"end":[384,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,311],"end":[422,273]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[460,235],"end":[512,235]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,235],"end":[602,273]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"android-full","codePoint":59857},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[598,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[598,191]}]},{"tag":"LineTo","args":[{"point":[640,191]}]},{"tag":"LineTo","args":[{"point":[640,235]}]},{"tag":"LineTo","args":[{"point":[598,235]}]}]},{"start":[384,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[384,191]}]},{"tag":"LineTo","args":[{"point":[426,191]}]},{"tag":"LineTo","args":[{"point":[426,235]}]},{"tag":"LineTo","args":[{"point":[384,235]}]}]},{"start":[718,57],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[732,41],"end":[718,27]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,13],"end":[688,27]}]}]},{"tag":"LineTo","args":[{"point":[624,91]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,63],"end":[512,63]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[450,63],"end":[398,91]}]}]},{"tag":"LineTo","args":[{"point":[334,27]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,13],"end":[304,27]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[288,41],"end":[304,57]}]}]},{"tag":"LineTo","args":[{"point":[360,113]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[316,145],"end":[286,205]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,265],"end":[256,319]}]}]},{"tag":"LineTo","args":[{"point":[768,319]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,189],"end":[662,113]}]}]},{"tag":"LineTo","args":[{"point":[718,57]}]}]},{"start":[829,382],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[829,382]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[810,401],"end":[810,427]}]}]},{"tag":"LineTo","args":[{"point":[810,725]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[810,753],"end":[829,771]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[848,789],"end":[874,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[900,789],"end":[919,771]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,753],"end":[938,725]}]}]},{"tag":"LineTo","args":[{"point":[938,427]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,401],"end":[919,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[900,363],"end":[874,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[848,363],"end":[829,382]}]}]}]},{"start":[105,382],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[105,382]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,401],"end":[86,427]}]}]},{"tag":"LineTo","args":[{"point":[86,725]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,753],"end":[105,771]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[124,789],"end":[150,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[176,789],"end":[195,771]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,753],"end":[214,725]}]}]},{"tag":"LineTo","args":[{"point":[214,427]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,401],"end":[195,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[176,363],"end":[150,363]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[124,363],"end":[105,382]}]}]}]},{"start":[268,819],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[268,819]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[280,831],"end":[298,831]}]}]},{"tag":"LineTo","args":[{"point":[342,831]}]},{"tag":"LineTo","args":[{"point":[342,981]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,1009],"end":[361,1027]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,1045],"end":[406,1045]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[432,1045],"end":[451,1027]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[470,1009],"end":[470,981]}]}]},{"tag":"LineTo","args":[{"point":[470,831]}]},{"tag":"LineTo","args":[{"point":[554,831]}]},{"tag":"LineTo","args":[{"point":[554,981]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,1009],"end":[573,1027]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[592,1045],"end":[618,1045]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[644,1045],"end":[663,1027]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,1009],"end":[682,981]}]}]},{"tag":"LineTo","args":[{"point":[682,831]}]},{"tag":"LineTo","args":[{"point":[726,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[744,831],"end":[756,819]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,807],"end":[768,789]}]}]},{"tag":"LineTo","args":[{"point":[768,363]}]},{"tag":"LineTo","args":[{"point":[256,363]}]},{"tag":"LineTo","args":[{"point":[256,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,807],"end":[268,819]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"autorenew","codePoint":59858},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[738,413],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,473],"end":[768,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,639],"end":[693,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,789],"end":[512,789]}]}]},{"tag":"LineTo","args":[{"point":[512,661]}]},{"tag":"LineTo","args":[{"point":[342,831]}]},{"tag":"LineTo","args":[{"point":[512,1003]}]},{"tag":"LineTo","args":[{"point":[512,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,433],"end":[800,351]}]}]},{"tag":"LineTo","args":[{"point":[738,413]}]}]},{"start":[512,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,235]}]},{"tag":"LineTo","args":[{"point":[512,63]}]},{"tag":"LineTo","args":[{"point":[512,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,633],"end":[224,715]}]}]},{"tag":"LineTo","args":[{"point":[286,653]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,597],"end":[256,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,427],"end":[331,352]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[406,277],"end":[512,277]}]}]},{"tag":"LineTo","args":[{"point":[512,405]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"cached","codePoint":59859},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[331,352],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[331,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[406,277],"end":[512,277]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[578,277],"end":[632,307]}]}]},{"tag":"LineTo","args":[{"point":[694,245]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[612,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[170,533]}]}]},{"tag":"LineTo","args":[{"point":[42,533]}]},{"tag":"LineTo","args":[{"point":[214,703]}]},{"tag":"LineTo","args":[{"point":[384,533]}]},{"tag":"LineTo","args":[{"point":[256,533]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,427],"end":[331,352]}]}]}]},{"start":[640,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,533]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,639],"end":[693,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,789],"end":[512,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[448,789],"end":[392,759]}]}]},{"tag":"LineTo","args":[{"point":[330,821]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[412,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[854,533]}]}]},{"tag":"LineTo","args":[{"point":[982,533]}]},{"tag":"LineTo","args":[{"point":[810,363]}]},{"tag":"LineTo","args":[{"point":[640,533]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"check_circle","codePoint":59860},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[214,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[274,473]}]},{"tag":"LineTo","args":[{"point":[426,625]}]},{"tag":"LineTo","args":[{"point":[750,301]}]},{"tag":"LineTo","args":[{"point":[810,363]}]},{"tag":"LineTo","args":[{"point":[426,747]}]},{"tag":"LineTo","args":[{"point":[214,533]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"code","codePoint":59861},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[682,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[938,533]}]},{"tag":"LineTo","args":[{"point":[682,277]}]},{"tag":"LineTo","args":[{"point":[622,337]}]},{"tag":"LineTo","args":[{"point":[820,533]}]},{"tag":"LineTo","args":[{"point":[622,729]}]},{"tag":"LineTo","args":[{"point":[682,789]}]}]},{"start":[204,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[402,337]}]},{"tag":"LineTo","args":[{"point":[342,277]}]},{"tag":"LineTo","args":[{"point":[86,533]}]},{"tag":"LineTo","args":[{"point":[342,789]}]},{"tag":"LineTo","args":[{"point":[402,729]}]},{"tag":"LineTo","args":[{"point":[204,533]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"delete","codePoint":59862},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[662,191],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[618,149]}]},{"tag":"LineTo","args":[{"point":[406,149]}]},{"tag":"LineTo","args":[{"point":[362,191]}]},{"tag":"LineTo","args":[{"point":[214,191]}]},{"tag":"LineTo","args":[{"point":[214,277]}]},{"tag":"LineTo","args":[{"point":[810,277]}]},{"tag":"LineTo","args":[{"point":[810,191]}]},{"tag":"LineTo","args":[{"point":[662,191]}]}]},{"start":[282,891],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[282,891]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[308,917],"end":[342,917]}]}]},{"tag":"LineTo","args":[{"point":[682,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[716,917],"end":[742,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,865],"end":[768,831]}]}]},{"tag":"LineTo","args":[{"point":[768,319]}]},{"tag":"LineTo","args":[{"point":[256,319]}]},{"tag":"LineTo","args":[{"point":[256,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,865],"end":[282,891]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"exit_to_app","codePoint":59863},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[214,149],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,149],"end":[153,174]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,199],"end":[128,235]}]}]},{"tag":"LineTo","args":[{"point":[128,405]}]},{"tag":"LineTo","args":[{"point":[214,405]}]},{"tag":"LineTo","args":[{"point":[214,235]}]},{"tag":"LineTo","args":[{"point":[810,235]}]},{"tag":"LineTo","args":[{"point":[810,831]}]},{"tag":"LineTo","args":[{"point":[214,831]}]},{"tag":"LineTo","args":[{"point":[214,661]}]},{"tag":"LineTo","args":[{"point":[128,661]}]},{"tag":"LineTo","args":[{"point":[128,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,867],"end":[153,892]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,917],"end":[214,917]}]}]},{"tag":"LineTo","args":[{"point":[810,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,917],"end":[870,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,865],"end":[896,831]}]}]},{"tag":"LineTo","args":[{"point":[896,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,201],"end":[870,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,149],"end":[810,149]}]}]},{"tag":"LineTo","args":[{"point":[214,149]}]}]},{"start":[490,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[704,533]}]},{"tag":"LineTo","args":[{"point":[490,319]}]},{"tag":"LineTo","args":[{"point":[430,379]}]},{"tag":"LineTo","args":[{"point":[540,491]}]},{"tag":"LineTo","args":[{"point":[128,491]}]},{"tag":"LineTo","args":[{"point":[128,575]}]},{"tag":"LineTo","args":[{"point":[540,575]}]},{"tag":"LineTo","args":[{"point":[430,687]}]},{"tag":"LineTo","args":[{"point":[490,747]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"extension","codePoint":59864},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[810,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[810,319]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[810,285],"end":[785,260]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[760,235],"end":[726,235]}]}]},{"tag":"LineTo","args":[{"point":[554,235]}]},{"tag":"LineTo","args":[{"point":[554,171]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,127],"end":[523,95]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[492,63],"end":[448,63]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[404,63],"end":[373,95]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,127],"end":[342,171]}]}]},{"tag":"LineTo","args":[{"point":[342,235]}]},{"tag":"LineTo","args":[{"point":[170,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,235],"end":[111,260]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,285],"end":[86,319]}]}]},{"tag":"LineTo","args":[{"point":[86,481]}]},{"tag":"LineTo","args":[{"point":[150,481]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,481],"end":[231,515]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[264,549],"end":[264,597]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[264,645],"end":[231,679]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,713],"end":[150,713]}]}]},{"tag":"LineTo","args":[{"point":[86,713]}]},{"tag":"LineTo","args":[{"point":[86,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,909],"end":[111,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,959],"end":[170,959]}]}]},{"tag":"LineTo","args":[{"point":[332,959]}]},{"tag":"LineTo","args":[{"point":[332,895]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[332,847],"end":[366,814]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[400,781],"end":[448,781]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[496,781],"end":[530,814]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,847],"end":[564,895]}]}]},{"tag":"LineTo","args":[{"point":[564,959]}]},{"tag":"LineTo","args":[{"point":[726,959]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[760,959],"end":[785,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[810,909],"end":[810,875]}]}]},{"tag":"LineTo","args":[{"point":[810,703]}]},{"tag":"LineTo","args":[{"point":[874,703]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[918,703],"end":[950,672]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[982,641],"end":[982,597]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[982,553],"end":[950,522]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[918,491],"end":[874,491]}]}]},{"tag":"LineTo","args":[{"point":[810,491]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"favorite","codePoint":59865},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[574,877],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[712,753],"end":[773,691]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[834,629],"end":[886,545]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,461],"end":[938,383]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,285],"end":[871,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[804,149],"end":[704,149]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[588,149],"end":[512,239]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,149],"end":[320,149]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[220,149],"end":[153,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,285],"end":[86,383]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,441],"end":[108,496]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[130,551],"end":[189,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[248,687],"end":[296,733]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[344,779],"end":[450,875]}]}]},{"tag":"LineTo","args":[{"point":[512,931]}]},{"tag":"LineTo","args":[{"point":[574,877]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"favorite_outline","codePoint":59866},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,817],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[508,813]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[412,727],"end":[366,683]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[320,639],"end":[266,579]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[212,519],"end":[191,473]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,427],"end":[170,383]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,319],"end":[213,277]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,235],"end":[320,235]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[370,235],"end":[413,263]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[456,291],"end":[472,335]}]}]},{"tag":"LineTo","args":[{"point":[552,335]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[568,291],"end":[611,263]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[654,235],"end":[704,235]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,235],"end":[811,277]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,319],"end":[854,383]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,427],"end":[833,473]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[812,519],"end":[758,579]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,639],"end":[658,683]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[612,727],"end":[516,813]}]}]},{"tag":"LineTo","args":[{"point":[512,817]}]}]},{"start":[512,239],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,239]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,149],"end":[320,149]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[220,149],"end":[153,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,285],"end":[86,383]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,461],"end":[138,545]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[190,629],"end":[251,691]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[312,753],"end":[450,877]}]}]},{"tag":"LineTo","args":[{"point":[512,931]}]},{"tag":"LineTo","args":[{"point":[574,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,779],"end":[728,733]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[776,687],"end":[835,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[894,551],"end":[916,496]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,441],"end":[938,383]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,285],"end":[871,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[804,149],"end":[704,149]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[588,149],"end":[512,239]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"help","codePoint":59867},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[604,541],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,595],"end":[554,661]}]}]},{"tag":"LineTo","args":[{"point":[470,661]}]},{"tag":"LineTo","args":[{"point":[470,639]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[470,573],"end":[520,519]}]}]},{"tag":"LineTo","args":[{"point":[572,465]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,439],"end":[598,405]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,371],"end":[572,345]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,319],"end":[512,319]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,319],"end":[452,345]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,371],"end":[426,405]}]}]},{"tag":"LineTo","args":[{"point":[342,405]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,335],"end":[392,285]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[442,235],"end":[512,235]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,235],"end":[632,285]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,335],"end":[682,405]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,461],"end":[642,501]}]}]},{"tag":"LineTo","args":[{"point":[604,541]}]}]},{"start":[470,831],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,747]}]},{"tag":"LineTo","args":[{"point":[554,747]}]},{"tag":"LineTo","args":[{"point":[554,831]}]},{"tag":"LineTo","args":[{"point":[470,831]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"highlight_remove","codePoint":59868},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]},{"start":[512,473],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[402,363]}]},{"tag":"LineTo","args":[{"point":[342,423]}]},{"tag":"LineTo","args":[{"point":[452,533]}]},{"tag":"LineTo","args":[{"point":[342,643]}]},{"tag":"LineTo","args":[{"point":[402,703]}]},{"tag":"LineTo","args":[{"point":[512,593]}]},{"tag":"LineTo","args":[{"point":[622,703]}]},{"tag":"LineTo","args":[{"point":[682,643]}]},{"tag":"LineTo","args":[{"point":[572,533]}]},{"tag":"LineTo","args":[{"point":[682,423]}]},{"tag":"LineTo","args":[{"point":[622,363]}]},{"tag":"LineTo","args":[{"point":[512,473]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"historyrestore","codePoint":59869},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[694,685]}]},{"tag":"LineTo","args":[{"point":[726,633]}]},{"tag":"LineTo","args":[{"point":[576,543]}]},{"tag":"LineTo","args":[{"point":[576,363]}]},{"tag":"LineTo","args":[{"point":[512,363]}]},{"tag":"LineTo","args":[{"point":[512,575]}]}]},{"start":[283,261],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[283,261]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,373],"end":[170,533]}]}]},{"tag":"LineTo","args":[{"point":[42,533]}]},{"tag":"LineTo","args":[{"point":[208,699]}]},{"tag":"LineTo","args":[{"point":[212,705]}]},{"tag":"LineTo","args":[{"point":[384,533]}]},{"tag":"LineTo","args":[{"point":[256,533]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,409],"end":[343,322]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[430,235],"end":[554,235]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[678,235],"end":[766,322]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,409],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,657],"end":[766,744]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[678,831],"end":[554,831]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[432,831],"end":[344,743]}]}]},{"tag":"LineTo","args":[{"point":[284,805]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[330,851],"end":[409,884]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[488,917],"end":[554,917]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[712,917],"end":[825,805]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,693],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,373],"end":[825,261]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[712,149],"end":[554,149]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[396,149],"end":[283,261]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"home","codePoint":59870},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[426,619],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[598,619]}]},{"tag":"LineTo","args":[{"point":[598,875]}]},{"tag":"LineTo","args":[{"point":[810,875]}]},{"tag":"LineTo","args":[{"point":[810,533]}]},{"tag":"LineTo","args":[{"point":[938,533]}]},{"tag":"LineTo","args":[{"point":[512,149]}]},{"tag":"LineTo","args":[{"point":[86,533]}]},{"tag":"LineTo","args":[{"point":[214,533]}]},{"tag":"LineTo","args":[{"point":[214,875]}]},{"tag":"LineTo","args":[{"point":[426,875]}]},{"tag":"LineTo","args":[{"point":[426,619]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"httpslock","codePoint":59871},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[380,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[380,277]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,223],"end":[419,184]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[458,145],"end":[512,145]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[566,145],"end":[605,184]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[644,223],"end":[644,277]}]}]},{"tag":"LineTo","args":[{"point":[644,363]}]},{"tag":"LineTo","args":[{"point":[380,363]}]}]},{"start":[452,721],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[452,721]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,695],"end":[426,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,627],"end":[452,601]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,575],"end":[512,575]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,575],"end":[572,601]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,627],"end":[598,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,695],"end":[572,721]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,747],"end":[512,747]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,747],"end":[452,721]}]}]}]},{"start":[726,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[726,277]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,189],"end":[663,126]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[600,63],"end":[512,63]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[424,63],"end":[361,126]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,189],"end":[298,277]}]}]},{"tag":"LineTo","args":[{"point":[298,363]}]},{"tag":"LineTo","args":[{"point":[256,363]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,363],"end":[196,388]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,413],"end":[170,447]}]}]},{"tag":"LineTo","args":[{"point":[170,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,909],"end":[196,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,959],"end":[256,959]}]}]},{"tag":"LineTo","args":[{"point":[768,959]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[802,959],"end":[828,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,909],"end":[854,875]}]}]},{"tag":"LineTo","args":[{"point":[854,447]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,413],"end":[828,388]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[802,363],"end":[768,363]}]}]},{"tag":"LineTo","args":[{"point":[726,363]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"info","codePoint":59872},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[470,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,319]}]},{"tag":"LineTo","args":[{"point":[554,319]}]},{"tag":"LineTo","args":[{"point":[554,405]}]},{"tag":"LineTo","args":[{"point":[470,405]}]}]},{"start":[470,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,491]}]},{"tag":"LineTo","args":[{"point":[554,491]}]},{"tag":"LineTo","args":[{"point":[554,747]}]},{"tag":"LineTo","args":[{"point":[470,747]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"info_outline","codePoint":59873},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[554,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,319]}]},{"tag":"LineTo","args":[{"point":[470,319]}]},{"tag":"LineTo","args":[{"point":[470,405]}]},{"tag":"LineTo","args":[{"point":[554,405]}]}]},{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]},{"start":[554,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,491]}]},{"tag":"LineTo","args":[{"point":[470,491]}]},{"tag":"LineTo","args":[{"point":[470,747]}]},{"tag":"LineTo","args":[{"point":[554,747]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"input","codePoint":59874},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[640,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,363]}]},{"tag":"LineTo","args":[{"point":[470,491]}]},{"tag":"LineTo","args":[{"point":[42,491]}]},{"tag":"LineTo","args":[{"point":[42,575]}]},{"tag":"LineTo","args":[{"point":[470,575]}]},{"tag":"LineTo","args":[{"point":[470,703]}]},{"tag":"LineTo","args":[{"point":[640,533]}]}]},{"start":[128,149],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[94,149],"end":[68,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[42,201],"end":[42,235]}]}]},{"tag":"LineTo","args":[{"point":[42,405]}]},{"tag":"LineTo","args":[{"point":[128,405]}]},{"tag":"LineTo","args":[{"point":[128,233]}]},{"tag":"LineTo","args":[{"point":[896,233]}]},{"tag":"LineTo","args":[{"point":[896,833]}]},{"tag":"LineTo","args":[{"point":[128,833]}]},{"tag":"LineTo","args":[{"point":[128,661]}]},{"tag":"LineTo","args":[{"point":[42,661]}]},{"tag":"LineTo","args":[{"point":[42,833]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[42,867],"end":[68,892]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[94,917],"end":[128,917]}]}]},{"tag":"LineTo","args":[{"point":[896,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[930,917],"end":[956,892]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[982,867],"end":[982,833]}]}]},{"tag":"LineTo","args":[{"point":[982,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[982,199],"end":[957,174]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[932,149],"end":[896,149]}]}]},{"tag":"LineTo","args":[{"point":[128,149]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"label","codePoint":59875},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[682,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,235]}]},{"tag":"LineTo","args":[{"point":[214,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,235],"end":[154,260]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,285],"end":[128,319]}]}]},{"tag":"LineTo","args":[{"point":[128,747]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,781],"end":[154,806]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,831],"end":[214,831]}]}]},{"tag":"LineTo","args":[{"point":[682,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,831],"end":[752,795]}]}]},{"tag":"LineTo","args":[{"point":[938,533]}]},{"tag":"LineTo","args":[{"point":[752,271]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,235],"end":[682,235]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"label_outline","codePoint":59876},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[214,747],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[214,319]}]},{"tag":"LineTo","args":[{"point":[682,319]}]},{"tag":"LineTo","args":[{"point":[834,533]}]},{"tag":"LineTo","args":[{"point":[682,747]}]},{"tag":"LineTo","args":[{"point":[214,747]}]}]},{"start":[682,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,235]}]},{"tag":"LineTo","args":[{"point":[214,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,235],"end":[154,260]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,285],"end":[128,319]}]}]},{"tag":"LineTo","args":[{"point":[128,747]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,781],"end":[154,806]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,831],"end":[214,831]}]}]},{"tag":"LineTo","args":[{"point":[682,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,831],"end":[752,795]}]}]},{"tag":"LineTo","args":[{"point":[938,533]}]},{"tag":"LineTo","args":[{"point":[752,271]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,235],"end":[682,235]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"perm_media","codePoint":59877},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[490,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[640,597]}]},{"tag":"LineTo","args":[{"point":[746,469]}]},{"tag":"LineTo","args":[{"point":[896,661]}]},{"tag":"LineTo","args":[{"point":[298,661]}]},{"tag":"LineTo","args":[{"point":[490,405]}]}]},{"start":[598,191],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,107]}]},{"tag":"LineTo","args":[{"point":[256,107]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,107],"end":[197,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[172,157],"end":[172,191]}]}]},{"tag":"LineTo","args":[{"point":[170,703]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,737],"end":[196,763]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,789],"end":[256,789]}]}]},{"tag":"LineTo","args":[{"point":[938,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[972,789],"end":[998,763]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,737],"end":[1024,703]}]}]},{"tag":"LineTo","args":[{"point":[1024,277]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,243],"end":[998,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[972,191],"end":[938,191]}]}]},{"tag":"LineTo","args":[{"point":[598,191]}]}]},{"start":[0,277],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[0,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,909],"end":[26,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[52,959],"end":[86,959]}]}]},{"tag":"LineTo","args":[{"point":[854,959]}]},{"tag":"LineTo","args":[{"point":[854,875]}]},{"tag":"LineTo","args":[{"point":[86,875]}]},{"tag":"LineTo","args":[{"point":[86,277]}]},{"tag":"LineTo","args":[{"point":[0,277]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"power_settings_new","codePoint":59878},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[700,303],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[746,339],"end":[778,407]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[810,475],"end":[810,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[810,657],"end":[723,744]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,831],"end":[512,831]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,831],"end":[301,744]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,657],"end":[214,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,475],"end":[246,407]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[278,339],"end":[324,301]}]}]},{"tag":"LineTo","args":[{"point":[264,241]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[208,289],"end":[168,375]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,461],"end":[128,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,693],"end":[240,805]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[352,917],"end":[512,917]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,917],"end":[784,805]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,693],"end":[896,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,357],"end":[760,241]}]}]},{"tag":"LineTo","args":[{"point":[700,303]}]}]},{"start":[470,149],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,575]}]},{"tag":"LineTo","args":[{"point":[554,575]}]},{"tag":"LineTo","args":[{"point":[554,149]}]},{"tag":"LineTo","args":[{"point":[470,149]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"search","codePoint":59879},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[270,563],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[270,563]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,507],"end":[214,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,347],"end":[270,291]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[326,235],"end":[406,235]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[486,235],"end":[542,291]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,347],"end":[598,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,507],"end":[542,563]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[486,619],"end":[406,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[326,619],"end":[270,563]}]}]}]},{"start":[628,619],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[616,607]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[642,575],"end":[662,522]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,469],"end":[682,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,311],"end":[602,230]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[522,149],"end":[406,149]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,149],"end":[209,230]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,311],"end":[128,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,543],"end":[209,623]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,703],"end":[406,703]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[510,703],"end":[586,637]}]}]},{"tag":"LineTo","args":[{"point":[598,649]}]},{"tag":"LineTo","args":[{"point":[598,683]}]},{"tag":"LineTo","args":[{"point":[810,895]}]},{"tag":"LineTo","args":[{"point":[874,831]}]},{"tag":"LineTo","args":[{"point":[662,619]}]},{"tag":"LineTo","args":[{"point":[628,619]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"settings","codePoint":59880},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[406,639],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[406,639]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[362,595],"end":[362,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[362,471],"end":[406,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[450,383],"end":[512,383]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[574,383],"end":[618,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[662,471],"end":[662,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[662,595],"end":[618,639]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[574,683],"end":[512,683]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[450,683],"end":[406,639]}]}]}]},{"start":[832,533],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[832,533]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,505],"end":[830,491]}]}]},{"tag":"LineTo","args":[{"point":[920,421]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[934,411],"end":[924,393]}]}]},{"tag":"LineTo","args":[{"point":[838,245]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[830,231],"end":[812,237]}]}]},{"tag":"LineTo","args":[{"point":[706,279]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,253],"end":[634,237]}]}]},{"tag":"LineTo","args":[{"point":[618,125]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[614,107],"end":[598,107]}]}]},{"tag":"LineTo","args":[{"point":[426,107]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[410,107],"end":[406,125]}]}]},{"tag":"LineTo","args":[{"point":[390,237]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[360,249],"end":[318,279]}]}]},{"tag":"LineTo","args":[{"point":[212,237]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[194,231],"end":[186,245]}]}]},{"tag":"LineTo","args":[{"point":[100,393]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[90,411],"end":[104,421]}]}]},{"tag":"LineTo","args":[{"point":[194,491]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,505],"end":[192,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[192,561],"end":[194,575]}]}]},{"tag":"LineTo","args":[{"point":[104,645]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[90,655],"end":[100,673]}]}]},{"tag":"LineTo","args":[{"point":[186,821]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[194,835],"end":[212,829]}]}]},{"tag":"LineTo","args":[{"point":[318,787]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[352,813],"end":[390,829]}]}]},{"tag":"LineTo","args":[{"point":[406,941]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[410,959],"end":[426,959]}]}]},{"tag":"LineTo","args":[{"point":[598,959]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[614,959],"end":[618,941]}]}]},{"tag":"LineTo","args":[{"point":[634,829]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[664,817],"end":[706,787]}]}]},{"tag":"LineTo","args":[{"point":[812,829]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[830,835],"end":[838,821]}]}]},{"tag":"LineTo","args":[{"point":[924,673]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[934,655],"end":[920,645]}]}]},{"tag":"LineTo","args":[{"point":[830,575]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,561],"end":[832,533]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"settings_applications","codePoint":59881},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[734,563],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[734,563]}]},{"tag":"LineTo","args":[{"point":[798,611]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[808,619],"end":[800,631]}]}]},{"tag":"LineTo","args":[{"point":[740,733]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[732,745],"end":[722,741]}]}]},{"tag":"LineTo","args":[{"point":[648,711]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[630,725],"end":[598,739]}]}]},{"tag":"LineTo","args":[{"point":[586,819]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[584,831],"end":[572,831]}]}]},{"tag":"LineTo","args":[{"point":[452,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[442,831],"end":[438,819]}]}]},{"tag":"LineTo","args":[{"point":[426,741]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[402,731],"end":[376,711]}]}]},{"tag":"LineTo","args":[{"point":[302,741]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,745],"end":[284,735]}]}]},{"tag":"LineTo","args":[{"point":[224,631]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,629],"end":[222,623]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,613],"end":[226,611]}]}]},{"tag":"LineTo","args":[{"point":[290,563]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[288,553],"end":[288,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[288,513],"end":[290,503]}]}]},{"tag":"LineTo","args":[{"point":[226,455]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,453],"end":[222,443]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[222,437],"end":[224,435]}]}]},{"tag":"LineTo","args":[{"point":[284,333]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[292,321],"end":[302,325]}]}]},{"tag":"LineTo","args":[{"point":[376,355]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[394,341],"end":[426,327]}]}]},{"tag":"LineTo","args":[{"point":[438,247]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[440,235],"end":[452,235]}]}]},{"tag":"LineTo","args":[{"point":[572,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,235],"end":[586,247]}]}]},{"tag":"LineTo","args":[{"point":[598,325]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[622,335],"end":[648,355]}]}]},{"tag":"LineTo","args":[{"point":[722,325]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[734,321],"end":[740,331]}]}]},{"tag":"LineTo","args":[{"point":[800,435]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[808,447],"end":[798,455]}]}]},{"tag":"LineTo","args":[{"point":[734,503]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,513],"end":[736,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,553],"end":[734,563]}]}]}]},{"start":[214,149],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,149],"end":[153,174]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,199],"end":[128,235]}]}]},{"tag":"LineTo","args":[{"point":[128,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,867],"end":[153,892]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,917],"end":[214,917]}]}]},{"tag":"LineTo","args":[{"point":[810,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[846,917],"end":[871,892]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,867],"end":[896,831]}]}]},{"tag":"LineTo","args":[{"point":[896,235]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,199],"end":[871,174]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[846,149],"end":[810,149]}]}]},{"tag":"LineTo","args":[{"point":[214,149]}]}]},{"start":[452,473],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[452,473]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,499],"end":[426,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,567],"end":[452,593]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,619],"end":[512,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,619],"end":[572,593]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,567],"end":[598,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[598,499],"end":[572,473]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,447],"end":[512,447]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,447],"end":[452,473]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"shop","codePoint":59882},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[384,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[704,575]}]},{"tag":"LineTo","args":[{"point":[384,789]}]},{"tag":"LineTo","args":[{"point":[384,405]}]}]},{"start":[598,191],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[598,277]}]},{"tag":"LineTo","args":[{"point":[426,277]}]},{"tag":"LineTo","args":[{"point":[426,191]}]},{"tag":"LineTo","args":[{"point":[598,191]}]}]},{"start":[682,191],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,155],"end":[658,131]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[634,107],"end":[598,107]}]}]},{"tag":"LineTo","args":[{"point":[426,107]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[390,107],"end":[366,131]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,155],"end":[342,191]}]}]},{"tag":"LineTo","args":[{"point":[342,277]}]},{"tag":"LineTo","args":[{"point":[86,277]}]},{"tag":"LineTo","args":[{"point":[86,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,867],"end":[110,892]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[134,917],"end":[170,917]}]}]},{"tag":"LineTo","args":[{"point":[854,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[890,917],"end":[914,892]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,867],"end":[938,831]}]}]},{"tag":"LineTo","args":[{"point":[938,277]}]},{"tag":"LineTo","args":[{"point":[682,277]}]},{"tag":"LineTo","args":[{"point":[682,191]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"spellcheck","codePoint":59883},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[576,861],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[420,703]}]},{"tag":"LineTo","args":[{"point":[360,763]}]},{"tag":"LineTo","args":[{"point":[576,981]}]},{"tag":"LineTo","args":[{"point":[982,575]}]},{"tag":"LineTo","args":[{"point":[922,515]}]},{"tag":"LineTo","args":[{"point":[576,861]}]}]},{"start":[362,255],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[450,491]}]},{"tag":"LineTo","args":[{"point":[274,491]}]},{"tag":"LineTo","args":[{"point":[362,255]}]}]},{"start":[620,703],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[402,149]}]},{"tag":"LineTo","args":[{"point":[322,149]}]},{"tag":"LineTo","args":[{"point":[104,703]}]},{"tag":"LineTo","args":[{"point":[194,703]}]},{"tag":"LineTo","args":[{"point":[242,575]}]},{"tag":"LineTo","args":[{"point":[482,575]}]},{"tag":"LineTo","args":[{"point":[532,703]}]},{"tag":"LineTo","args":[{"point":[620,703]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"stars","codePoint":59884},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,681],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[332,789]}]},{"tag":"LineTo","args":[{"point":[380,583]}]},{"tag":"LineTo","args":[{"point":[220,445]}]},{"tag":"LineTo","args":[{"point":[430,429]}]},{"tag":"LineTo","args":[{"point":[512,235]}]},{"tag":"LineTo","args":[{"point":[594,427]}]},{"tag":"LineTo","args":[{"point":[804,445]}]},{"tag":"LineTo","args":[{"point":[644,583]}]},{"tag":"LineTo","args":[{"point":[692,789]}]},{"tag":"LineTo","args":[{"point":[512,681]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"translate","codePoint":59885},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[746,561],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[816,747]}]},{"tag":"LineTo","args":[{"point":[678,747]}]},{"tag":"LineTo","args":[{"point":[746,561]}]}]},{"start":[704,447],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,959]}]},{"tag":"LineTo","args":[{"point":[598,959]}]},{"tag":"LineTo","args":[{"point":[646,831]}]},{"tag":"LineTo","args":[{"point":[848,831]}]},{"tag":"LineTo","args":[{"point":[896,959]}]},{"tag":"LineTo","args":[{"point":[982,959]}]},{"tag":"LineTo","args":[{"point":[790,447]}]},{"tag":"LineTo","args":[{"point":[704,447]}]}]},{"start":[440,557],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[442,555]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[488,503],"end":[534,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[580,341],"end":[600,277]}]}]},{"tag":"LineTo","args":[{"point":[726,277]}]},{"tag":"LineTo","args":[{"point":[726,191]}]},{"tag":"LineTo","args":[{"point":[426,191]}]},{"tag":"LineTo","args":[{"point":[426,107]}]},{"tag":"LineTo","args":[{"point":[342,107]}]},{"tag":"LineTo","args":[{"point":[342,191]}]},{"tag":"LineTo","args":[{"point":[42,191]}]},{"tag":"LineTo","args":[{"point":[42,277]}]},{"tag":"LineTo","args":[{"point":[520,277]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[476,403],"end":[384,505]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[328,443],"end":[286,363]}]}]},{"tag":"LineTo","args":[{"point":[200,363]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[248,469],"end":[328,557]}]}]},{"tag":"LineTo","args":[{"point":[110,771]}]},{"tag":"LineTo","args":[{"point":[170,831]}]},{"tag":"LineTo","args":[{"point":[384,619]}]},{"tag":"LineTo","args":[{"point":[516,751]}]},{"tag":"LineTo","args":[{"point":[550,663]}]},{"tag":"LineTo","args":[{"point":[440,557]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"visibility_off","codePoint":59886},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[640,541],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[640,533]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,481],"end":[602,443]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,405],"end":[512,405]}]}]},{"tag":"LineTo","args":[{"point":[506,405]}]},{"tag":"LineTo","args":[{"point":[640,541]}]}]},{"start":[388,505],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,521],"end":[384,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,585],"end":[422,623]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[460,661],"end":[512,661]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[524,661],"end":[540,657]}]}]},{"tag":"LineTo","args":[{"point":[606,723]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[558,747],"end":[512,747]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[424,747],"end":[361,684]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,621],"end":[298,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[298,487],"end":[322,439]}]}]},{"tag":"LineTo","args":[{"point":[388,505]}]}]},{"start":[135,253],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[135,253]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,297],"end":[202,321]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[158,355],"end":[111,418]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[64,481],"end":[42,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[98,677],"end":[226,765]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[354,853],"end":[512,853]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[612,853],"end":[698,817]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,845],"end":[779,897]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,949],"end":[842,959]}]}]},{"tag":"LineTo","args":[{"point":[896,905]}]},{"tag":"LineTo","args":[{"point":[140,149]}]},{"tag":"LineTo","args":[{"point":[86,203]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[92,209],"end":[135,253]}]}]}]},{"start":[663,382],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[663,382]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,445],"end":[726,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,573],"end":[710,611]}]}]},{"tag":"LineTo","args":[{"point":[834,735]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[932,651],"end":[980,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[924,389],"end":[797,301]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[670,213],"end":[512,213]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[420,213],"end":[342,243]}]}]},{"tag":"LineTo","args":[{"point":[434,335]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[472,319],"end":[512,319]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[600,319],"end":[663,382]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"update","codePoint":59887},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[470,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,575]}]},{"tag":"LineTo","args":[{"point":[652,685]}]},{"tag":"LineTo","args":[{"point":[682,633]}]},{"tag":"LineTo","args":[{"point":[534,543]}]},{"tag":"LineTo","args":[{"point":[534,363]}]},{"tag":"LineTo","args":[{"point":[470,363]}]}]},{"start":[896,149],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[780,269]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[734,223],"end":[655,190]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,157],"end":[510,157]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[444,157],"end":[365,190]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[286,223],"end":[240,269]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,381],"end":[128,538]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,695],"end":[240,805]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[352,917],"end":[512,917]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,917],"end":[784,805]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,695],"end":[896,537]}]}]},{"tag":"LineTo","args":[{"point":[810,537]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[810,659],"end":[724,745]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,781],"end":[625,807]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[562,833],"end":[512,833]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[462,833],"end":[400,807]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[338,781],"end":[302,745]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[266,709],"end":[240,648]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,587],"end":[214,537]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,487],"end":[240,426]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[266,365],"end":[302,329]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[390,243],"end":[513,244]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[636,245],"end":[724,333]}]}]},{"tag":"LineTo","args":[{"point":[606,453]}]},{"tag":"LineTo","args":[{"point":[896,453]}]},{"tag":"LineTo","args":[{"point":[896,149]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"g_translate","codePoint":59888},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[905,926],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[905,926]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[892,939],"end":[874,939]}]}]},{"tag":"LineTo","args":[{"point":[598,939]}]},{"tag":"LineTo","args":[{"point":[682,831]}]},{"tag":"LineTo","args":[{"point":[638,699]}]},{"tag":"LineTo","args":[{"point":[770,831]}]},{"tag":"LineTo","args":[{"point":[810,793]}]},{"tag":"LineTo","args":[{"point":[670,653]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[742,573],"end":[772,473]}]}]},{"tag":"LineTo","args":[{"point":[854,473]}]},{"tag":"LineTo","args":[{"point":[854,417]}]},{"tag":"LineTo","args":[{"point":[660,417]}]},{"tag":"LineTo","args":[{"point":[660,363]}]},{"tag":"LineTo","args":[{"point":[606,363]}]},{"tag":"LineTo","args":[{"point":[606,417]}]},{"tag":"LineTo","args":[{"point":[544,417]}]},{"tag":"LineTo","args":[{"point":[488,255]}]},{"tag":"LineTo","args":[{"point":[874,255]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[892,255],"end":[905,268]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[918,281],"end":[918,299]}]}]},{"tag":"LineTo","args":[{"point":[918,895]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[918,913],"end":[905,926]}]}]}]},{"start":[720,473],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[694,553],"end":[632,621]}]}]},{"tag":"LineTo","args":[{"point":[596,573]}]},{"tag":"LineTo","args":[{"point":[562,473]}]},{"tag":"LineTo","args":[{"point":[720,473]}]}]},{"start":[148,641],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[148,641]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,579],"end":[86,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,403],"end":[148,340]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[210,277],"end":[298,277]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,277],"end":[442,333]}]}]},{"tag":"LineTo","args":[{"point":[386,387]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[352,353],"end":[298,353]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[242,353],"end":[203,393]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[164,433],"end":[164,491]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[164,547],"end":[203,587]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[242,627],"end":[298,627]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[356,627],"end":[388,595]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[420,563],"end":[424,525]}]}]},{"tag":"LineTo","args":[{"point":[298,525]}]},{"tag":"LineTo","args":[{"point":[298,451]}]},{"tag":"LineTo","args":[{"point":[498,451]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[504,493],"end":[504,495]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[504,587],"end":[447,645]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[390,703],"end":[298,703]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[210,703],"end":[148,641]}]}]}]},{"start":[470,191],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,63]}]},{"tag":"LineTo","args":[{"point":[128,63]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[94,63],"end":[68,89]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[42,115],"end":[42,149]}]}]},{"tag":"LineTo","args":[{"point":[42,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[42,823],"end":[68,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[94,875],"end":[128,875]}]}]},{"tag":"LineTo","args":[{"point":[470,875]}]},{"tag":"LineTo","args":[{"point":[512,1003]}]},{"tag":"LineTo","args":[{"point":[896,1003]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[930,1003],"end":[956,977]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[982,951],"end":[982,917]}]}]},{"tag":"LineTo","args":[{"point":[982,277]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[982,243],"end":[956,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[930,191],"end":[896,191]}]}]},{"tag":"LineTo","args":[{"point":[470,191]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"check_circle_outline","codePoint":59889},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[271,774],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[271,774]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,673],"end":[170,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,393],"end":[271,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,191],"end":[512,191]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,191],"end":[753,292]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,393],"end":[854,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,673],"end":[753,774]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,875],"end":[512,875]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[372,875],"end":[271,774]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]},{"start":[426,625],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[274,473]}]},{"tag":"LineTo","args":[{"point":[214,533]}]},{"tag":"LineTo","args":[{"point":[426,747]}]},{"tag":"LineTo","args":[{"point":[768,405]}]},{"tag":"LineTo","args":[{"point":[708,345]}]},{"tag":"LineTo","args":[{"point":[426,625]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"delete_outline","codePoint":59890},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[618,149],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[406,149]}]},{"tag":"LineTo","args":[{"point":[362,191]}]},{"tag":"LineTo","args":[{"point":[214,191]}]},{"tag":"LineTo","args":[{"point":[214,277]}]},{"tag":"LineTo","args":[{"point":[810,277]}]},{"tag":"LineTo","args":[{"point":[810,191]}]},{"tag":"LineTo","args":[{"point":[662,191]}]},{"tag":"LineTo","args":[{"point":[618,149]}]}]},{"start":[682,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,831]}]},{"tag":"LineTo","args":[{"point":[342,831]}]},{"tag":"LineTo","args":[{"point":[342,405]}]},{"tag":"LineTo","args":[{"point":[682,405]}]}]},{"start":[282,891],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[282,891]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[308,917],"end":[342,917]}]}]},{"tag":"LineTo","args":[{"point":[682,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[716,917],"end":[742,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,865],"end":[768,831]}]}]},{"tag":"LineTo","args":[{"point":[768,319]}]},{"tag":"LineTo","args":[{"point":[256,319]}]},{"tag":"LineTo","args":[{"point":[256,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,865],"end":[282,891]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"drive_folder_upload","codePoint":59891},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[402,637],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,569]}]},{"tag":"LineTo","args":[{"point":[470,747]}]},{"tag":"LineTo","args":[{"point":[554,747]}]},{"tag":"LineTo","args":[{"point":[554,569]}]},{"tag":"LineTo","args":[{"point":[622,637]}]},{"tag":"LineTo","args":[{"point":[682,577]}]},{"tag":"LineTo","args":[{"point":[512,405]}]},{"tag":"LineTo","args":[{"point":[342,577]}]},{"tag":"LineTo","args":[{"point":[402,637]}]}]},{"start":[170,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[170,363]}]},{"tag":"LineTo","args":[{"point":[854,363]}]},{"tag":"LineTo","args":[{"point":[854,789]}]},{"tag":"LineTo","args":[{"point":[170,789]}]}]},{"start":[512,277],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,191]}]},{"tag":"LineTo","args":[{"point":[170,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,191],"end":[111,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,243],"end":[86,277]}]}]},{"tag":"LineTo","args":[{"point":[86,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,823],"end":[111,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,875],"end":[170,875]}]}]},{"tag":"LineTo","args":[{"point":[854,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,875],"end":[913,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,823],"end":[938,789]}]}]},{"tag":"LineTo","args":[{"point":[938,363]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,329],"end":[913,303]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,277],"end":[854,277]}]}]},{"tag":"LineTo","args":[{"point":[512,277]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"library_add_check","codePoint":59892},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[86,277],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[86,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,909],"end":[111,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,959],"end":[170,959]}]}]},{"tag":"LineTo","args":[{"point":[768,959]}]},{"tag":"LineTo","args":[{"point":[768,875]}]},{"tag":"LineTo","args":[{"point":[170,875]}]},{"tag":"LineTo","args":[{"point":[170,277]}]},{"tag":"LineTo","args":[{"point":[86,277]}]}]},{"start":[384,469],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[444,409]}]},{"tag":"LineTo","args":[{"point":[532,497]}]},{"tag":"LineTo","args":[{"point":[750,277]}]},{"tag":"LineTo","args":[{"point":[810,337]}]},{"tag":"LineTo","args":[{"point":[532,619]}]},{"tag":"LineTo","args":[{"point":[384,469]}]}]},{"start":[342,107],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[308,107],"end":[282,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,157],"end":[256,191]}]}]},{"tag":"LineTo","args":[{"point":[256,703]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,737],"end":[282,763]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[308,789],"end":[342,789]}]}]},{"tag":"LineTo","args":[{"point":[854,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,789],"end":[913,763]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,737],"end":[938,703]}]}]},{"tag":"LineTo","args":[{"point":[938,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,157],"end":[913,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,107],"end":[854,107]}]}]},{"tag":"LineTo","args":[{"point":[342,107]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"replay_circle_filled","codePoint":59893},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[693,714],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[693,714]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,789],"end":[512,789]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[406,789],"end":[331,714]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,639],"end":[256,533]}]}]},{"tag":"LineTo","args":[{"point":[342,533]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[342,603],"end":[392,653]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[442,703],"end":[512,703]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,703],"end":[632,653]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,603],"end":[682,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[682,463],"end":[632,413]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[582,363],"end":[512,363]}]}]},{"tag":"LineTo","args":[{"point":[512,491]}]},{"tag":"LineTo","args":[{"point":[342,319]}]},{"tag":"LineTo","args":[{"point":[512,149]}]},{"tag":"LineTo","args":[{"point":[512,277]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,277],"end":[693,352]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,427],"end":[768,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,639],"end":[693,714]}]}]}]},{"start":[211,232],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[211,232]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,357],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,709],"end":[211,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,959],"end":[512,959]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,959],"end":[813,834]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,709],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,357],"end":[813,232]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,107],"end":[512,107]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[336,107],"end":[211,232]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"redo","codePoint":59894},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[490,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[490,363]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[344,363],"end":[227,449]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[110,535],"end":[66,671]}]}]},{"tag":"LineTo","args":[{"point":[166,703]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[198,605],"end":[293,537]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,469],"end":[490,469]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[614,469],"end":[710,549]}]}]},{"tag":"LineTo","args":[{"point":[554,703]}]},{"tag":"LineTo","args":[{"point":[938,703]}]},{"tag":"LineTo","args":[{"point":[938,319]}]},{"tag":"LineTo","args":[{"point":[786,473]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[660,363],"end":[490,363]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"save","codePoint":59895},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[214,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[214,235]}]},{"tag":"LineTo","args":[{"point":[640,235]}]},{"tag":"LineTo","args":[{"point":[640,405]}]},{"tag":"LineTo","args":[{"point":[214,405]}]}]},{"start":[422,793],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[422,793]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,755],"end":[384,703]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[384,651],"end":[422,613]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[460,575],"end":[512,575]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,575],"end":[602,613]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,651],"end":[640,703]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,755],"end":[602,793]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,831],"end":[512,831]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[460,831],"end":[422,793]}]}]}]},{"start":[214,149],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,149],"end":[153,174]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,199],"end":[128,235]}]}]},{"tag":"LineTo","args":[{"point":[128,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,867],"end":[153,892]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,917],"end":[214,917]}]}]},{"tag":"LineTo","args":[{"point":[810,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,917],"end":[870,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,865],"end":[896,831]}]}]},{"tag":"LineTo","args":[{"point":[896,319]}]},{"tag":"LineTo","args":[{"point":[726,149]}]},{"tag":"LineTo","args":[{"point":[214,149]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"zip","codePoint":59896},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,578],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,578]}]},{"tag":"LineTo","args":[{"point":[512,578]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[485,583],"end":[466.5,605]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[448,627],"end":[448,656]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[448,689],"end":[471.5,712.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[495,736],"end":[528,736]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[561,736],"end":[584.5,712.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,689],"end":[608,656]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,627],"end":[590,605]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[572,583],"end":[544,578]}]}]},{"tag":"LineTo","args":[{"point":[544,512]}]},{"tag":"LineTo","args":[{"point":[576,512]}]},{"tag":"LineTo","args":[{"point":[576,480]}]},{"tag":"LineTo","args":[{"point":[544,480]}]},{"tag":"LineTo","args":[{"point":[544,448]}]},{"tag":"LineTo","args":[{"point":[576,448]}]},{"tag":"LineTo","args":[{"point":[576,416]}]},{"tag":"LineTo","args":[{"point":[544,416]}]},{"tag":"LineTo","args":[{"point":[544,384]}]},{"tag":"LineTo","args":[{"point":[576,384]}]},{"tag":"LineTo","args":[{"point":[576,352]}]},{"tag":"LineTo","args":[{"point":[544,352]}]},{"tag":"LineTo","args":[{"point":[544,320]}]},{"tag":"LineTo","args":[{"point":[576,320]}]},{"tag":"LineTo","args":[{"point":[576,288]}]},{"tag":"LineTo","args":[{"point":[544,288]}]},{"tag":"LineTo","args":[{"point":[544,256]}]},{"tag":"LineTo","args":[{"point":[576,256]}]},{"tag":"LineTo","args":[{"point":[576,224]}]},{"tag":"LineTo","args":[{"point":[544,224]}]},{"tag":"LineTo","args":[{"point":[544,192]}]},{"tag":"LineTo","args":[{"point":[576,192]}]},{"tag":"LineTo","args":[{"point":[576,160]}]},{"tag":"LineTo","args":[{"point":[544,160]}]},{"tag":"LineTo","args":[{"point":[544,128]}]},{"tag":"LineTo","args":[{"point":[576,128]}]},{"tag":"LineTo","args":[{"point":[576,96]}]},{"tag":"LineTo","args":[{"point":[704,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[757,96],"end":[794.5,133.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,171],"end":[832,224]}]}]},{"tag":"LineTo","args":[{"point":[832,832]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,885],"end":[794.5,922.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[757,960],"end":[704,960]}]}]},{"tag":"LineTo","args":[{"point":[352,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[299,960],"end":[261.5,922.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,885],"end":[224,832]}]}]},{"tag":"LineTo","args":[{"point":[224,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,171],"end":[261.5,133.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[299,96],"end":[352,96]}]}]},{"tag":"LineTo","args":[{"point":[512,96]}]},{"tag":"LineTo","args":[{"point":[512,128]}]},{"tag":"LineTo","args":[{"point":[480,128]}]},{"tag":"LineTo","args":[{"point":[480,160]}]},{"tag":"LineTo","args":[{"point":[512,160]}]},{"tag":"LineTo","args":[{"point":[512,192]}]},{"tag":"LineTo","args":[{"point":[480,192]}]},{"tag":"LineTo","args":[{"point":[480,224]}]},{"tag":"LineTo","args":[{"point":[512,224]}]},{"tag":"LineTo","args":[{"point":[512,256]}]},{"tag":"LineTo","args":[{"point":[480,256]}]},{"tag":"LineTo","args":[{"point":[480,288]}]},{"tag":"LineTo","args":[{"point":[512,288]}]},{"tag":"LineTo","args":[{"point":[512,320]}]},{"tag":"LineTo","args":[{"point":[480,320]}]},{"tag":"LineTo","args":[{"point":[480,352]}]},{"tag":"LineTo","args":[{"point":[512,352]}]},{"tag":"LineTo","args":[{"point":[512,384]}]},{"tag":"LineTo","args":[{"point":[480,384]}]},{"tag":"LineTo","args":[{"point":[480,416]}]},{"tag":"LineTo","args":[{"point":[512,416]}]},{"tag":"LineTo","args":[{"point":[512,448]}]},{"tag":"LineTo","args":[{"point":[480,448]}]},{"tag":"LineTo","args":[{"point":[480,480]}]},{"tag":"LineTo","args":[{"point":[512,480]}]},{"tag":"LineTo","args":[{"point":[512,512]}]},{"tag":"LineTo","args":[{"point":[480,512]}]},{"tag":"LineTo","args":[{"point":[480,544]}]},{"tag":"LineTo","args":[{"point":[512,544]}]},{"tag":"LineTo","args":[{"point":[512,578]}]}]},{"start":[528,608],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[548,608],"end":[562,622]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,636],"end":[576,656]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,676],"end":[562,690]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[548,704],"end":[528,704]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[508,704],"end":[494,690]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,676],"end":[480,656]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,636],"end":[494,622]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[508,608],"end":[528,608]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"zip-outline","codePoint":59897},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,561],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,544]}]},{"tag":"LineTo","args":[{"point":[480,544]}]},{"tag":"LineTo","args":[{"point":[480,512]}]},{"tag":"LineTo","args":[{"point":[512,512]}]},{"tag":"LineTo","args":[{"point":[512,480]}]},{"tag":"LineTo","args":[{"point":[480,480]}]},{"tag":"LineTo","args":[{"point":[480,448]}]},{"tag":"LineTo","args":[{"point":[512,448]}]},{"tag":"LineTo","args":[{"point":[512,416]}]},{"tag":"LineTo","args":[{"point":[480,416]}]},{"tag":"LineTo","args":[{"point":[480,384]}]},{"tag":"LineTo","args":[{"point":[512,384]}]},{"tag":"LineTo","args":[{"point":[512,352]}]},{"tag":"LineTo","args":[{"point":[480,352]}]},{"tag":"LineTo","args":[{"point":[480,320]}]},{"tag":"LineTo","args":[{"point":[512,320]}]},{"tag":"LineTo","args":[{"point":[512,288]}]},{"tag":"LineTo","args":[{"point":[480,288]}]},{"tag":"LineTo","args":[{"point":[480,256]}]},{"tag":"LineTo","args":[{"point":[512,256]}]},{"tag":"LineTo","args":[{"point":[512,224]}]},{"tag":"LineTo","args":[{"point":[480,224]}]},{"tag":"LineTo","args":[{"point":[480,192]}]},{"tag":"LineTo","args":[{"point":[512,192]}]},{"tag":"LineTo","args":[{"point":[512,160]}]},{"tag":"LineTo","args":[{"point":[480,160]}]},{"tag":"LineTo","args":[{"point":[480,128]}]},{"tag":"LineTo","args":[{"point":[352,128]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[312,128],"end":[284,156]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,184],"end":[256,224]}]}]},{"tag":"LineTo","args":[{"point":[256,832]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,872],"end":[284,900]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[312,928],"end":[352,928]}]}]},{"tag":"LineTo","args":[{"point":[704,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[744,928],"end":[772,900]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[800,872],"end":[800,832]}]}]},{"tag":"LineTo","args":[{"point":[800,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[800,184],"end":[772,156]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[744,128],"end":[704,128]}]}]},{"tag":"LineTo","args":[{"point":[544,128]}]},{"tag":"LineTo","args":[{"point":[544,160]}]},{"tag":"LineTo","args":[{"point":[576,160]}]},{"tag":"LineTo","args":[{"point":[576,192]}]},{"tag":"LineTo","args":[{"point":[544,192]}]},{"tag":"LineTo","args":[{"point":[544,224]}]},{"tag":"LineTo","args":[{"point":[576,224]}]},{"tag":"LineTo","args":[{"point":[576,256]}]},{"tag":"LineTo","args":[{"point":[544,256]}]},{"tag":"LineTo","args":[{"point":[544,288]}]},{"tag":"LineTo","args":[{"point":[576,288]}]},{"tag":"LineTo","args":[{"point":[576,320]}]},{"tag":"LineTo","args":[{"point":[544,320]}]},{"tag":"LineTo","args":[{"point":[544,352]}]},{"tag":"LineTo","args":[{"point":[576,352]}]},{"tag":"LineTo","args":[{"point":[576,384]}]},{"tag":"LineTo","args":[{"point":[544,384]}]},{"tag":"LineTo","args":[{"point":[544,416]}]},{"tag":"LineTo","args":[{"point":[576,416]}]},{"tag":"LineTo","args":[{"point":[576,448]}]},{"tag":"LineTo","args":[{"point":[544,448]}]},{"tag":"LineTo","args":[{"point":[544,480]}]},{"tag":"LineTo","args":[{"point":[576,480]}]},{"tag":"LineTo","args":[{"point":[576,512]}]},{"tag":"LineTo","args":[{"point":[544,512]}]},{"tag":"LineTo","args":[{"point":[544,578]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[572,583],"end":[590,605]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,627],"end":[608,656]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,689],"end":[584.5,712.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[561,736],"end":[528,736]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[495,736],"end":[471.5,712.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[448,689],"end":[448,656]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[448,627],"end":[466.5,605]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[485,583],"end":[512,578]}]}]},{"tag":"LineTo","args":[{"point":[512,561]}]}]},{"start":[352,96],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[704,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[757,96],"end":[794.5,133.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,171],"end":[832,224]}]}]},{"tag":"LineTo","args":[{"point":[832,832]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,885],"end":[794.5,922.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[757,960],"end":[704,960]}]}]},{"tag":"LineTo","args":[{"point":[352,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[299,960],"end":[261.5,922.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,885],"end":[224,832]}]}]},{"tag":"LineTo","args":[{"point":[224,224]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,171],"end":[261.5,133.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[299,96],"end":[352,96]}]}]}]},{"start":[494,622],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,636],"end":[480,656]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[480,676],"end":[494,690]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[508,704],"end":[528,704]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[548,704],"end":[562,690]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,676],"end":[576,656]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,636],"end":[562,622]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[548,608],"end":[528,608]}]}]},{"tag":"LineTo","args":[{"point":[528,608]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[508,608],"end":[494,622]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"logout","codePoint":59898},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[512,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,149]}]},{"tag":"LineTo","args":[{"point":[170,149]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,149],"end":[111,175]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,201],"end":[86,235]}]}]},{"tag":"LineTo","args":[{"point":[86,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,865],"end":[111,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,917],"end":[170,917]}]}]},{"tag":"LineTo","args":[{"point":[512,917]}]},{"tag":"LineTo","args":[{"point":[512,831]}]},{"tag":"LineTo","args":[{"point":[170,831]}]},{"tag":"LineTo","args":[{"point":[170,235]}]},{"tag":"LineTo","args":[{"point":[512,235]}]}]},{"start":[666,379],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[776,491]}]},{"tag":"LineTo","args":[{"point":[342,491]}]},{"tag":"LineTo","args":[{"point":[342,575]}]},{"tag":"LineTo","args":[{"point":[776,575]}]},{"tag":"LineTo","args":[{"point":[666,685]}]},{"tag":"LineTo","args":[{"point":[726,747]}]},{"tag":"LineTo","args":[{"point":[938,533]}]},{"tag":"LineTo","args":[{"point":[726,319]}]},{"tag":"LineTo","args":[{"point":[666,379]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder_open","codePoint":59899},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[170,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[170,363]}]},{"tag":"LineTo","args":[{"point":[854,363]}]},{"tag":"LineTo","args":[{"point":[854,789]}]},{"tag":"LineTo","args":[{"point":[170,789]}]}]},{"start":[512,277],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[426,191]}]},{"tag":"LineTo","args":[{"point":[170,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,191],"end":[111,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,243],"end":[86,277]}]}]},{"tag":"LineTo","args":[{"point":[86,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,823],"end":[111,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,875],"end":[170,875]}]}]},{"tag":"LineTo","args":[{"point":[854,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,875],"end":[913,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,823],"end":[938,789]}]}]},{"tag":"LineTo","args":[{"point":[938,363]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,329],"end":[913,303]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,277],"end":[854,277]}]}]},{"tag":"LineTo","args":[{"point":[512,277]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"launchopen_in_new","codePoint":59900},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[598,235],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[750,235]}]},{"tag":"LineTo","args":[{"point":[332,653]}]},{"tag":"LineTo","args":[{"point":[392,713]}]},{"tag":"LineTo","args":[{"point":[810,295]}]},{"tag":"LineTo","args":[{"point":[810,447]}]},{"tag":"LineTo","args":[{"point":[896,447]}]},{"tag":"LineTo","args":[{"point":[896,149]}]},{"tag":"LineTo","args":[{"point":[598,149]}]},{"tag":"LineTo","args":[{"point":[598,235]}]}]},{"start":[214,831],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[214,235]}]},{"tag":"LineTo","args":[{"point":[512,235]}]},{"tag":"LineTo","args":[{"point":[512,149]}]},{"tag":"LineTo","args":[{"point":[214,149]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,149],"end":[153,174]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,199],"end":[128,235]}]}]},{"tag":"LineTo","args":[{"point":[128,831]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,867],"end":[153,892]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,917],"end":[214,917]}]}]},{"tag":"LineTo","args":[{"point":[810,917]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,917],"end":[870,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,865],"end":[896,831]}]}]},{"tag":"LineTo","args":[{"point":[896,533]}]},{"tag":"LineTo","args":[{"point":[810,533]}]},{"tag":"LineTo","args":[{"point":[810,831]}]},{"tag":"LineTo","args":[{"point":[214,831]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"open_in_browser","codePoint":59901},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[342,619],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[470,619]}]},{"tag":"LineTo","args":[{"point":[470,875]}]},{"tag":"LineTo","args":[{"point":[554,875]}]},{"tag":"LineTo","args":[{"point":[554,619]}]},{"tag":"LineTo","args":[{"point":[682,619]}]},{"tag":"LineTo","args":[{"point":[512,447]}]},{"tag":"LineTo","args":[{"point":[342,619]}]}]},{"start":[214,191],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,191],"end":[153,216]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,241],"end":[128,277]}]}]},{"tag":"LineTo","args":[{"point":[128,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[128,825],"end":[153,850]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[178,875],"end":[214,875]}]}]},{"tag":"LineTo","args":[{"point":[384,875]}]},{"tag":"LineTo","args":[{"point":[384,789]}]},{"tag":"LineTo","args":[{"point":[214,789]}]},{"tag":"LineTo","args":[{"point":[214,363]}]},{"tag":"LineTo","args":[{"point":[810,363]}]},{"tag":"LineTo","args":[{"point":[810,789]}]},{"tag":"LineTo","args":[{"point":[640,789]}]},{"tag":"LineTo","args":[{"point":[640,875]}]},{"tag":"LineTo","args":[{"point":[810,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[844,875],"end":[870,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,823],"end":[896,789]}]}]},{"tag":"LineTo","args":[{"point":[896,277]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[896,241],"end":[871,216]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[846,191],"end":[810,191]}]}]},{"tag":"LineTo","args":[{"point":[214,191]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"vue","codePoint":59902},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[1024,69],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,955]}]},{"tag":"LineTo","args":[{"point":[0,69]}]},{"tag":"LineTo","args":[{"point":[205,69]}]},{"tag":"LineTo","args":[{"point":[205,68]}]},{"tag":"LineTo","args":[{"point":[394,68]}]},{"tag":"LineTo","args":[{"point":[512,273]}]},{"tag":"LineTo","args":[{"point":[630,68]}]},{"tag":"LineTo","args":[{"point":[819,68]}]},{"tag":"LineTo","args":[{"point":[819,69]}]},{"tag":"LineTo","args":[{"point":[1024,69]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"angularuniversal","codePoint":59903},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[666,481],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[666,481]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[666,473],"end":[660,467]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[654,461],"end":[645,461]}]}]},{"tag":"LineTo","args":[{"point":[379,461]}]},{"tag":"LineTo","args":[{"point":[379,461]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[370,461],"end":[364,467]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[358,473],"end":[358,481]}]}]},{"tag":"LineTo","args":[{"point":[358,543]}]},{"tag":"LineTo","args":[{"point":[358,543]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[358,551],"end":[364,557]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[370,563],"end":[379,563]}]}]},{"tag":"LineTo","args":[{"point":[645,563]}]},{"tag":"LineTo","args":[{"point":[645,563]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[654,563],"end":[660,557]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[666,551],"end":[666,543]}]}]},{"tag":"LineTo","args":[{"point":[666,481]}]}]},{"start":[512,666],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[533,666],"end":[548,681]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[563,696],"end":[563,717]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[563,738],"end":[548,753]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[533,768],"end":[512,768]}]}]},{"tag":"LineTo","args":[{"point":[512,768]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[491,768],"end":[476,753]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[461,738],"end":[461,717]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[461,696],"end":[476,681]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[491,666],"end":[512,666]}]}]}]},{"start":[645,307],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[654,307],"end":[660,313]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[666,319],"end":[666,328]}]}]},{"tag":"LineTo","args":[{"point":[666,389]}]},{"tag":"LineTo","args":[{"point":[666,389]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[666,398],"end":[660,404]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[654,410],"end":[645,410]}]}]},{"tag":"LineTo","args":[{"point":[379,410]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[370,410],"end":[364,404]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[358,398],"end":[358,389]}]}]},{"tag":"LineTo","args":[{"point":[358,328]}]},{"tag":"LineTo","args":[{"point":[358,328]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[358,319],"end":[364,313]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[370,307],"end":[379,307]}]}]},{"tag":"LineTo","args":[{"point":[645,307]}]}]},{"start":[511,0],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[36,170]}]},{"tag":"LineTo","args":[{"point":[108,799]}]},{"tag":"LineTo","args":[{"point":[511,1024]}]},{"tag":"LineTo","args":[{"point":[915,799]}]},{"tag":"LineTo","args":[{"point":[988,170]}]},{"tag":"LineTo","args":[{"point":[511,0]}]}]},{"start":[717,758],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[717,758]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[717,783],"end":[699,801]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[681,819],"end":[655,819]}]}]},{"tag":"LineTo","args":[{"point":[369,819]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[343,819],"end":[325,801]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[307,783],"end":[307,758]}]}]},{"tag":"LineTo","args":[{"point":[307,266]}]},{"tag":"LineTo","args":[{"point":[307,266]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[307,241],"end":[325,223]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[343,205],"end":[369,205]}]}]},{"tag":"LineTo","args":[{"point":[655,205]}]},{"tag":"LineTo","args":[{"point":[655,205]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[681,205],"end":[699,223]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[717,241],"end":[717,266]}]}]},{"tag":"LineTo","args":[{"point":[717,758]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"linkinsert_link","codePoint":59904},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[554,319],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[554,401]}]},{"tag":"LineTo","args":[{"point":[726,401]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[780,401],"end":[819,440]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[858,479],"end":[858,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[858,587],"end":[819,626]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[780,665],"end":[726,665]}]}]},{"tag":"LineTo","args":[{"point":[554,665]}]},{"tag":"LineTo","args":[{"point":[554,747]}]},{"tag":"LineTo","args":[{"point":[726,747]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[814,747],"end":[876,684]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,621],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,445],"end":[876,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[814,319],"end":[726,319]}]}]},{"tag":"LineTo","args":[{"point":[554,319]}]}]},{"start":[682,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[682,491]}]},{"tag":"LineTo","args":[{"point":[342,491]}]},{"tag":"LineTo","args":[{"point":[342,575]}]},{"tag":"LineTo","args":[{"point":[682,575]}]}]},{"start":[205,440],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[205,440]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[244,401],"end":[298,401]}]}]},{"tag":"LineTo","args":[{"point":[470,401]}]},{"tag":"LineTo","args":[{"point":[470,319]}]},{"tag":"LineTo","args":[{"point":[298,319]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[210,319],"end":[148,382]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,445],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,621],"end":[148,684]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[210,747],"end":[298,747]}]}]},{"tag":"LineTo","args":[{"point":[470,747]}]},{"tag":"LineTo","args":[{"point":[470,665]}]},{"tag":"LineTo","args":[{"point":[298,665]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[244,665],"end":[205,626]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[166,587],"end":[166,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[166,479],"end":[205,440]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-text2","codePoint":59905},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[608,96],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[288,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[262,96],"end":[243,115]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,134],"end":[224,160]}]}]},{"tag":"LineTo","args":[{"point":[224,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,922],"end":[242.5,941]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[261,960],"end":[288,960]}]}]},{"tag":"LineTo","args":[{"point":[768,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[795,960],"end":[813.5,941.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,923],"end":[832,896]}]}]},{"tag":"LineTo","args":[{"point":[832,352]}]},{"tag":"LineTo","args":[{"point":[672,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[646,352],"end":[627,333.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,315],"end":[608,288]}]}]},{"tag":"LineTo","args":[{"point":[608,96]}]}]},{"start":[480,320],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[480,352]}]},{"tag":"LineTo","args":[{"point":[320,352]}]},{"tag":"LineTo","args":[{"point":[320,320]}]},{"tag":"LineTo","args":[{"point":[480,320]}]}]},{"start":[544,224],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[544,256]}]},{"tag":"LineTo","args":[{"point":[320,256]}]},{"tag":"LineTo","args":[{"point":[320,224]}]},{"tag":"LineTo","args":[{"point":[544,224]}]}]},{"start":[736,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,448]}]},{"tag":"LineTo","args":[{"point":[320,448]}]},{"tag":"LineTo","args":[{"point":[320,416]}]},{"tag":"LineTo","args":[{"point":[736,416]}]}]},{"start":[640,512],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[640,544]}]},{"tag":"LineTo","args":[{"point":[320,544]}]},{"tag":"LineTo","args":[{"point":[320,512]}]},{"tag":"LineTo","args":[{"point":[640,512]}]}]},{"start":[736,608],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,640]}]},{"tag":"LineTo","args":[{"point":[320,640]}]},{"tag":"LineTo","args":[{"point":[320,608]}]},{"tag":"LineTo","args":[{"point":[736,608]}]}]},{"start":[608,704],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,736]}]},{"tag":"LineTo","args":[{"point":[320,736]}]},{"tag":"LineTo","args":[{"point":[320,704]}]},{"tag":"LineTo","args":[{"point":[608,704]}]}]},{"start":[736,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,832]}]},{"tag":"LineTo","args":[{"point":[320,832]}]},{"tag":"LineTo","args":[{"point":[320,800]}]},{"tag":"LineTo","args":[{"point":[736,800]}]}]},{"start":[832,320],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[672,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[659,320],"end":[649.5,310.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,301],"end":[640,288]}]}]},{"tag":"LineTo","args":[{"point":[640,96]}]},{"tag":"LineTo","args":[{"point":[832,320]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-text2-outline","codePoint":59906},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[624,96],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[288,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[262,96],"end":[243,115]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,134],"end":[224,160]}]}]},{"tag":"LineTo","args":[{"point":[224,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,922],"end":[242.5,941]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[261,960],"end":[288,960]}]}]},{"tag":"LineTo","args":[{"point":[768,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[795,960],"end":[813.5,941.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,923],"end":[832,896]}]}]},{"tag":"LineTo","args":[{"point":[832,320]}]},{"tag":"LineTo","args":[{"point":[640,96]}]},{"tag":"LineTo","args":[{"point":[624,96]}]}]},{"start":[608,128],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,315],"end":[626.5,333.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,352],"end":[672,352]}]}]},{"tag":"LineTo","args":[{"point":[800,352]}]},{"tag":"LineTo","args":[{"point":[800,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[800,909],"end":[790.5,918.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[781,928],"end":[768,928]}]}]},{"tag":"LineTo","args":[{"point":[288,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,928],"end":[265.5,918.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,909],"end":[256,896]}]}]},{"tag":"LineTo","args":[{"point":[256,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,147],"end":[265.5,137.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,128],"end":[288,128]}]}]},{"tag":"LineTo","args":[{"point":[608,128]}]}]},{"start":[640,144],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[790,320]}]},{"tag":"LineTo","args":[{"point":[672,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[659,320],"end":[649.5,310.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,301],"end":[640,288]}]}]},{"tag":"LineTo","args":[{"point":[640,144]}]}]},{"start":[480,320],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[480,352]}]},{"tag":"LineTo","args":[{"point":[320,352]}]},{"tag":"LineTo","args":[{"point":[320,320]}]},{"tag":"LineTo","args":[{"point":[480,320]}]}]},{"start":[544,224],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[544,256]}]},{"tag":"LineTo","args":[{"point":[320,256]}]},{"tag":"LineTo","args":[{"point":[320,224]}]},{"tag":"LineTo","args":[{"point":[544,224]}]}]},{"start":[736,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,448]}]},{"tag":"LineTo","args":[{"point":[320,448]}]},{"tag":"LineTo","args":[{"point":[320,416]}]},{"tag":"LineTo","args":[{"point":[736,416]}]}]},{"start":[640,512],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[640,544]}]},{"tag":"LineTo","args":[{"point":[320,544]}]},{"tag":"LineTo","args":[{"point":[320,512]}]},{"tag":"LineTo","args":[{"point":[640,512]}]}]},{"start":[736,608],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,640]}]},{"tag":"LineTo","args":[{"point":[320,640]}]},{"tag":"LineTo","args":[{"point":[320,608]}]},{"tag":"LineTo","args":[{"point":[736,608]}]}]},{"start":[608,704],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,736]}]},{"tag":"LineTo","args":[{"point":[320,736]}]},{"tag":"LineTo","args":[{"point":[320,704]}]},{"tag":"LineTo","args":[{"point":[608,704]}]}]},{"start":[736,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,832]}]},{"tag":"LineTo","args":[{"point":[320,832]}]},{"tag":"LineTo","args":[{"point":[320,800]}]},{"tag":"LineTo","args":[{"point":[736,800]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-text4","codePoint":59907},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[608,96],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[288,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[262,96],"end":[243,115]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,134],"end":[224,160]}]}]},{"tag":"LineTo","args":[{"point":[224,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,922],"end":[242.5,941]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[261,960],"end":[288,960]}]}]},{"tag":"LineTo","args":[{"point":[768,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[795,960],"end":[813.5,941.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,923],"end":[832,896]}]}]},{"tag":"LineTo","args":[{"point":[832,352]}]},{"tag":"LineTo","args":[{"point":[672,352]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[646,352],"end":[627,333.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,315],"end":[608,288]}]}]},{"tag":"LineTo","args":[{"point":[608,96]}]}]},{"start":[832,320],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[672,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[659,320],"end":[649.5,310.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,301],"end":[640,288]}]}]},{"tag":"LineTo","args":[{"point":[640,96]}]},{"tag":"LineTo","args":[{"point":[832,320]}]}]},{"start":[544,320],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[544,352]}]},{"tag":"LineTo","args":[{"point":[320,352]}]},{"tag":"LineTo","args":[{"point":[320,320]}]},{"tag":"LineTo","args":[{"point":[544,320]}]}]},{"start":[544,224],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[544,256]}]},{"tag":"LineTo","args":[{"point":[320,256]}]},{"tag":"LineTo","args":[{"point":[320,224]}]},{"tag":"LineTo","args":[{"point":[544,224]}]}]},{"start":[736,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,448]}]},{"tag":"LineTo","args":[{"point":[320,448]}]},{"tag":"LineTo","args":[{"point":[320,416]}]},{"tag":"LineTo","args":[{"point":[736,416]}]}]},{"start":[736,512],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,544]}]},{"tag":"LineTo","args":[{"point":[320,544]}]},{"tag":"LineTo","args":[{"point":[320,512]}]},{"tag":"LineTo","args":[{"point":[736,512]}]}]},{"start":[736,608],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,640]}]},{"tag":"LineTo","args":[{"point":[320,640]}]},{"tag":"LineTo","args":[{"point":[320,608]}]},{"tag":"LineTo","args":[{"point":[736,608]}]}]},{"start":[736,704],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,736]}]},{"tag":"LineTo","args":[{"point":[320,736]}]},{"tag":"LineTo","args":[{"point":[320,704]}]},{"tag":"LineTo","args":[{"point":[736,704]}]}]},{"start":[736,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,832]}]},{"tag":"LineTo","args":[{"point":[320,832]}]},{"tag":"LineTo","args":[{"point":[320,800]}]},{"tag":"LineTo","args":[{"point":[736,800]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"document-text5","codePoint":59908},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[624,96],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[288,96]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[262,96],"end":[243,115]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,134],"end":[224,160]}]}]},{"tag":"LineTo","args":[{"point":[224,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[224,922],"end":[242.5,941]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[261,960],"end":[288,960]}]}]},{"tag":"LineTo","args":[{"point":[768,960]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[795,960],"end":[813.5,941.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[832,923],"end":[832,896]}]}]},{"tag":"LineTo","args":[{"point":[832,320]}]},{"tag":"LineTo","args":[{"point":[640,96]}]},{"tag":"LineTo","args":[{"point":[624,96]}]}]},{"start":[608,128],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[608,288]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[608,315],"end":[626.5,333.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[645,352],"end":[672,352]}]}]},{"tag":"LineTo","args":[{"point":[800,352]}]},{"tag":"LineTo","args":[{"point":[800,896]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[800,909],"end":[790.5,918.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[781,928],"end":[768,928]}]}]},{"tag":"LineTo","args":[{"point":[288,928]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,928],"end":[265.5,918.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,909],"end":[256,896]}]}]},{"tag":"LineTo","args":[{"point":[256,160]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[256,147],"end":[265.5,137.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,128],"end":[288,128]}]}]},{"tag":"LineTo","args":[{"point":[608,128]}]}]},{"start":[640,144],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[790,320]}]},{"tag":"LineTo","args":[{"point":[672,320]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[659,320],"end":[649.5,310.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,301],"end":[640,288]}]}]},{"tag":"LineTo","args":[{"point":[640,144]}]}]},{"start":[544,320],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[544,352]}]},{"tag":"LineTo","args":[{"point":[320,352]}]},{"tag":"LineTo","args":[{"point":[320,320]}]},{"tag":"LineTo","args":[{"point":[544,320]}]}]},{"start":[544,224],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[544,256]}]},{"tag":"LineTo","args":[{"point":[320,256]}]},{"tag":"LineTo","args":[{"point":[320,224]}]},{"tag":"LineTo","args":[{"point":[544,224]}]}]},{"start":[736,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,448]}]},{"tag":"LineTo","args":[{"point":[320,448]}]},{"tag":"LineTo","args":[{"point":[320,416]}]},{"tag":"LineTo","args":[{"point":[736,416]}]}]},{"start":[736,512],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,544]}]},{"tag":"LineTo","args":[{"point":[320,544]}]},{"tag":"LineTo","args":[{"point":[320,512]}]},{"tag":"LineTo","args":[{"point":[736,512]}]}]},{"start":[736,608],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,640]}]},{"tag":"LineTo","args":[{"point":[320,640]}]},{"tag":"LineTo","args":[{"point":[320,608]}]},{"tag":"LineTo","args":[{"point":[736,608]}]}]},{"start":[736,704],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,736]}]},{"tag":"LineTo","args":[{"point":[320,736]}]},{"tag":"LineTo","args":[{"point":[320,704]}]},{"tag":"LineTo","args":[{"point":[736,704]}]}]},{"start":[736,800],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[736,832]}]},{"tag":"LineTo","args":[{"point":[320,832]}]},{"tag":"LineTo","args":[{"point":[320,800]}]},{"tag":"LineTo","args":[{"point":[736,800]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"folder4","codePoint":59909},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[170,191],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,191],"end":[111,217]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,243],"end":[86,277]}]}]},{"tag":"LineTo","args":[{"point":[86,789]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,823],"end":[111,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,875],"end":[170,875]}]}]},{"tag":"LineTo","args":[{"point":[854,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,875],"end":[913,849]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,823],"end":[938,789]}]}]},{"tag":"LineTo","args":[{"point":[938,363]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,329],"end":[913,303]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,277],"end":[854,277]}]}]},{"tag":"LineTo","args":[{"point":[512,277]}]},{"tag":"LineTo","args":[{"point":[426,191]}]},{"tag":"LineTo","args":[{"point":[170,191]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"shift","codePoint":59910},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":968,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[192,419],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[201,419],"end":[209.5,419.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[218,420],"end":[227,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[236,423],"end":[245,425.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[254,428],"end":[263,431]}]}]},{"tag":"LineTo","args":[{"point":[263,431]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[269,433],"end":[272.5,438]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[276,443],"end":[276,449]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[276,449],"end":[276,449]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[276,449],"end":[276,449]}]}]},{"tag":"LineTo","args":[{"point":[276,478]}]},{"tag":"LineTo","args":[{"point":[276,478]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[276,486],"end":[270.5,492]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[265,498],"end":[256,498]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[254,498],"end":[252,497.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[250,497],"end":[248,496]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[240,492],"end":[233,489.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[226,487],"end":[220,485]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[213,483],"end":[207,482.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[201,482],"end":[196,482]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[186,482],"end":[179.5,483.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[173,485],"end":[170,488]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[167,490],"end":[166,491.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[165,493],"end":[165,498]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[165,502],"end":[165.5,503.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[166,505],"end":[167,505]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[167,506],"end":[173.5,508.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[180,511],"end":[191,513]}]}]},{"tag":"LineTo","args":[{"point":[191,513]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[191,513],"end":[191,513]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[191,513],"end":[191,513]}]}]},{"tag":"LineTo","args":[{"point":[209,516]}]},{"tag":"LineTo","args":[{"point":[209,516]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[227,520],"end":[242,526.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[257,533],"end":[268,544]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[278,555],"end":[283.5,569.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[289,584],"end":[289,600]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[289,620],"end":[282,636.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,653],"end":[260,664]}]}]},{"tag":"LineTo","args":[{"point":[260,664]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[246,675],"end":[227,680]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[208,685],"end":[186,685]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[177,685],"end":[167.5,684]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[158,683],"end":[149,681]}]}]},{"tag":"LineTo","args":[{"point":[149,681]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[149,681],"end":[149,681]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[149,681],"end":[149,681]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[149,681],"end":[149,681]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[149,681],"end":[149,681]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[139,679],"end":[129.5,676]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[120,673],"end":[110,670]}]}]},{"tag":"LineTo","args":[{"point":[110,670]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[104,667],"end":[100.5,662]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[97,657],"end":[97,651]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[97,651],"end":[97,651]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[97,651],"end":[97,651]}]}]},{"tag":"LineTo","args":[{"point":[97,621]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[97,613],"end":[102.5,607]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[108,601],"end":[117,601]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[119,601],"end":[121.5,601.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[124,602],"end":[126,604]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[134,608],"end":[142,611.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[150,615],"end":[157,617]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[165,619],"end":[172,620]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[179,621],"end":[186,621]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[197,621],"end":[203.5,619.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[210,618],"end":[213,615]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[217,613],"end":[218,610.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[219,608],"end":[219,603]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[219,598],"end":[218,596]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[217,594],"end":[215,592]}]}]},{"tag":"LineTo","args":[{"point":[215,592]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[215,592],"end":[215,592]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[215,592],"end":[215,592]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[214,590],"end":[208,587.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[202,585],"end":[192,583]}]}]},{"tag":"LineTo","args":[{"point":[175,580]}]},{"tag":"LineTo","args":[{"point":[175,580]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[175,580],"end":[175,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[175,580],"end":[175,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[175,580],"end":[175,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[175,580],"end":[175,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[156,576],"end":[141.5,570]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[127,564],"end":[117,554]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[106,544],"end":[101,530]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[96,516],"end":[96,501]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[96,483],"end":[103,467]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[110,451],"end":[124,440]}]}]},{"tag":"LineTo","args":[{"point":[123,440]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[123,440],"end":[123.5,440]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[124,440],"end":[124,440]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[137,429],"end":[154.5,424]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[172,419],"end":[192,419]}]}]}]},{"start":[345,422],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[353,422],"end":[359,428]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[365,434],"end":[365,442]}]}]},{"tag":"LineTo","args":[{"point":[365,512]}]},{"tag":"LineTo","args":[{"point":[433,512]}]},{"tag":"LineTo","args":[{"point":[433,442]}]},{"tag":"LineTo","args":[{"point":[433,442]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[433,434],"end":[439,428]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[445,422],"end":[453,422]}]}]},{"tag":"LineTo","args":[{"point":[482,422]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[491,422],"end":[496.5,428]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[502,434],"end":[502,442]}]}]},{"tag":"LineTo","args":[{"point":[502,661]}]},{"tag":"LineTo","args":[{"point":[502,661]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[502,669],"end":[496.5,674.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[491,680],"end":[482,680]}]}]},{"tag":"LineTo","args":[{"point":[453,680]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[445,680],"end":[439,674.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[433,669],"end":[433,661]}]}]},{"tag":"LineTo","args":[{"point":[433,576]}]},{"tag":"LineTo","args":[{"point":[365,576]}]},{"tag":"LineTo","args":[{"point":[365,661]}]},{"tag":"LineTo","args":[{"point":[365,661]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[365,669],"end":[359,674.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[353,680],"end":[345,680]}]}]},{"tag":"LineTo","args":[{"point":[316,680]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[308,680],"end":[302,674.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[296,669],"end":[296,661]}]}]},{"tag":"LineTo","args":[{"point":[296,442]}]},{"tag":"LineTo","args":[{"point":[296,442]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[296,434],"end":[302,428]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[308,422],"end":[316,422]}]}]},{"tag":"LineTo","args":[{"point":[345,422]}]}]},{"start":[541,422],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[667,422]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[669,422],"end":[670,422.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[671,423],"end":[673,423]}]}]},{"tag":"LineTo","args":[{"point":[673,423]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[674,423],"end":[675.5,422.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[677,422],"end":[679,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[679,422],"end":[679,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[679,422],"end":[679,422]}]}]},{"tag":"LineTo","args":[{"point":[864,422]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[872,422],"end":[877.5,428]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[883,434],"end":[883,442]}]}]},{"tag":"LineTo","args":[{"point":[883,467]}]},{"tag":"LineTo","args":[{"point":[883,467]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[883,475],"end":[877.5,481]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[872,487],"end":[864,487]}]}]},{"tag":"LineTo","args":[{"point":[806,487]}]},{"tag":"LineTo","args":[{"point":[806,661]}]},{"tag":"LineTo","args":[{"point":[806,661]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[806,669],"end":[800,674.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[794,680],"end":[786,680]}]}]},{"tag":"LineTo","args":[{"point":[756,680]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[748,680],"end":[742.5,674.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[737,669],"end":[737,661]}]}]},{"tag":"LineTo","args":[{"point":[737,487]}]},{"tag":"LineTo","args":[{"point":[679,487]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[677,487],"end":[675.5,486.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[674,486],"end":[673,486]}]}]},{"tag":"LineTo","args":[{"point":[673,486]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,486],"end":[670.5,486.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[669,487],"end":[667,487]}]}]},{"tag":"LineTo","args":[{"point":[591,487]}]},{"tag":"LineTo","args":[{"point":[591,512]}]},{"tag":"LineTo","args":[{"point":[658,512]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[666,512],"end":[671.5,517.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[677,523],"end":[677,531]}]}]},{"tag":"LineTo","args":[{"point":[677,556]}]},{"tag":"LineTo","args":[{"point":[677,556]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[677,564],"end":[671.5,570]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[666,576],"end":[658,576]}]}]},{"tag":"LineTo","args":[{"point":[591,576]}]},{"tag":"LineTo","args":[{"point":[591,661]}]},{"tag":"LineTo","args":[{"point":[591,661]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[591,669],"end":[585,674.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[579,680],"end":[571,680]}]}]},{"tag":"LineTo","args":[{"point":[541,680]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[533,680],"end":[527.5,674.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[522,669],"end":[522,661]}]}]},{"tag":"LineTo","args":[{"point":[522,442]}]},{"tag":"LineTo","args":[{"point":[522,442]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[522,434],"end":[527.5,428]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[533,422],"end":[541,422]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"replace","codePoint":59911},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":968,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[942,570],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[942,570]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[953,570],"end":[960.5,577.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[968,585],"end":[968,595]}]}]},{"tag":"LineTo","args":[{"point":[968,998]}]},{"tag":"LineTo","args":[{"point":[968,998]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[968,1009],"end":[960.5,1016.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[953,1024],"end":[942,1024]}]}]},{"tag":"LineTo","args":[{"point":[539,1024]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[529,1024],"end":[521.5,1016.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[514,1009],"end":[514,998]}]}]},{"tag":"LineTo","args":[{"point":[514,595]}]},{"tag":"LineTo","args":[{"point":[514,595]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[514,585],"end":[521.5,577.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[529,570],"end":[539,570]}]}]},{"tag":"LineTo","args":[{"point":[942,570]}]}]},{"start":[565,973],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[917,973]}]},{"tag":"LineTo","args":[{"point":[917,621]}]},{"tag":"LineTo","args":[{"point":[565,621]}]},{"tag":"LineTo","args":[{"point":[565,973]}]}]},{"start":[777,220],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[777,542]}]},{"tag":"LineTo","args":[{"point":[777,542]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[777,542],"end":[777,542]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[777,542],"end":[777,542]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[777,553],"end":[769.5,560.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[762,568],"end":[751,568]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[740,568],"end":[732.5,560.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[725,553],"end":[725,542]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[725,542],"end":[725,542]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[725,542],"end":[725,542]}]}]},{"tag":"LineTo","args":[{"point":[725,271]}]},{"tag":"LineTo","args":[{"point":[441,271]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[441,271],"end":[440.5,271.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[440,272],"end":[440,272]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[430,272],"end":[422.5,264]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[415,256],"end":[415,246]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[415,235],"end":[422.5,227.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[430,220],"end":[440,220]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[440,220],"end":[440.5,220]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[441,220],"end":[441,220]}]}]},{"tag":"LineTo","args":[{"point":[777,220]}]}]},{"start":[26,0],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[77,0]}]},{"tag":"LineTo","args":[{"point":[93,6]}]},{"tag":"LineTo","args":[{"point":[102,24]}]},{"tag":"LineTo","args":[{"point":[96,43]}]},{"tag":"LineTo","args":[{"point":[77,51]}]},{"tag":"LineTo","args":[{"point":[26,51]}]},{"tag":"LineTo","args":[{"point":[9,46]}]},{"tag":"LineTo","args":[{"point":[0,27]}]},{"tag":"LineTo","args":[{"point":[7,8]}]},{"tag":"LineTo","args":[{"point":[26,0]}]}]},{"start":[231,0],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[282,0]}]},{"tag":"LineTo","args":[{"point":[298,6]}]},{"tag":"LineTo","args":[{"point":[307,24]}]},{"tag":"LineTo","args":[{"point":[301,43]}]},{"tag":"LineTo","args":[{"point":[282,51]}]},{"tag":"LineTo","args":[{"point":[231,51]}]},{"tag":"LineTo","args":[{"point":[215,46]}]},{"tag":"LineTo","args":[{"point":[205,27]}]},{"tag":"LineTo","args":[{"point":[212,8]}]},{"tag":"LineTo","args":[{"point":[231,0]}]}]},{"start":[427,7],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[446,14]}]},{"tag":"LineTo","args":[{"point":[454,33]}]},{"tag":"LineTo","args":[{"point":[454,84]}]},{"tag":"LineTo","args":[{"point":[449,100]}]},{"tag":"LineTo","args":[{"point":[430,110]}]},{"tag":"LineTo","args":[{"point":[411,103]}]},{"tag":"LineTo","args":[{"point":[403,84]}]},{"tag":"LineTo","args":[{"point":[403,33]}]},{"tag":"LineTo","args":[{"point":[409,17]}]},{"tag":"LineTo","args":[{"point":[427,7]}]}]},{"start":[24,126],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[43,132]}]},{"tag":"LineTo","args":[{"point":[51,151]}]},{"tag":"LineTo","args":[{"point":[51,202]}]},{"tag":"LineTo","args":[{"point":[46,218]}]},{"tag":"LineTo","args":[{"point":[27,228]}]},{"tag":"LineTo","args":[{"point":[8,221]}]},{"tag":"LineTo","args":[{"point":[0,202]}]},{"tag":"LineTo","args":[{"point":[0,151]}]},{"tag":"LineTo","args":[{"point":[6,135]}]},{"tag":"LineTo","args":[{"point":[24,126]}]}]},{"start":[427,212],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[446,219]}]},{"tag":"LineTo","args":[{"point":[454,238]}]},{"tag":"LineTo","args":[{"point":[454,289]}]},{"tag":"LineTo","args":[{"point":[449,305]}]},{"tag":"LineTo","args":[{"point":[430,315]}]},{"tag":"LineTo","args":[{"point":[411,308]}]},{"tag":"LineTo","args":[{"point":[403,289]}]},{"tag":"LineTo","args":[{"point":[403,238]}]},{"tag":"LineTo","args":[{"point":[409,222]}]},{"tag":"LineTo","args":[{"point":[427,212]}]}]},{"start":[24,331],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[43,337]}]},{"tag":"LineTo","args":[{"point":[51,356]}]},{"tag":"LineTo","args":[{"point":[51,407]}]},{"tag":"LineTo","args":[{"point":[46,424]}]},{"tag":"LineTo","args":[{"point":[27,433]}]},{"tag":"LineTo","args":[{"point":[8,426]}]},{"tag":"LineTo","args":[{"point":[0,407]}]},{"tag":"LineTo","args":[{"point":[0,356]}]},{"tag":"LineTo","args":[{"point":[6,340]}]},{"tag":"LineTo","args":[{"point":[24,331]}]}]},{"start":[158,403],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[209,403]}]},{"tag":"LineTo","args":[{"point":[226,409]}]},{"tag":"LineTo","args":[{"point":[235,427]}]},{"tag":"LineTo","args":[{"point":[228,446]}]},{"tag":"LineTo","args":[{"point":[209,454]}]},{"tag":"LineTo","args":[{"point":[158,454]}]},{"tag":"LineTo","args":[{"point":[142,449]}]},{"tag":"LineTo","args":[{"point":[133,430]}]},{"tag":"LineTo","args":[{"point":[139,411]}]},{"tag":"LineTo","args":[{"point":[158,403]}]}]},{"start":[363,403],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[414,403]}]},{"tag":"LineTo","args":[{"point":[431,409]}]},{"tag":"LineTo","args":[{"point":[440,427]}]},{"tag":"LineTo","args":[{"point":[433,446]}]},{"tag":"LineTo","args":[{"point":[414,454]}]},{"tag":"LineTo","args":[{"point":[363,454]}]},{"tag":"LineTo","args":[{"point":[347,449]}]},{"tag":"LineTo","args":[{"point":[338,430]}]},{"tag":"LineTo","args":[{"point":[344,411]}]},{"tag":"LineTo","args":[{"point":[363,403]}]}]},{"start":[629,394],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[629,394]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[629,394],"end":[629,394]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[629,394],"end":[629,394]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[634,394],"end":[639,396]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[644,398],"end":[647,402]}]}]},{"tag":"LineTo","args":[{"point":[751,505]}]},{"tag":"LineTo","args":[{"point":[855,402]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[858,398],"end":[863,396]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[868,394],"end":[873,394]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[884,394],"end":[891.5,401.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[899,409],"end":[899,419]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[899,425],"end":[897,429.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[895,434],"end":[891,438]}]}]},{"tag":"LineTo","args":[{"point":[769,560]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[766,563],"end":[761,565]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[756,567],"end":[751,567]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[746,567],"end":[741,565]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,563],"end":[733,560]}]}]},{"tag":"LineTo","args":[{"point":[611,438]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[607,434],"end":[605,429.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[603,425],"end":[603,419]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[603,409],"end":[610.5,401.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,394],"end":[629,394]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"replace_all","codePoint":59912},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":968,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[778,253],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[778,672]}]},{"tag":"LineTo","args":[{"point":[778,672]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[778,672],"end":[778,672]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[778,672],"end":[778,672]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[778,682],"end":[771,689]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[764,696],"end":[753,696]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[743,696],"end":[735.5,689]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[728,682],"end":[728,672]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[728,672],"end":[728,672]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[728,672],"end":[728,672]}]}]},{"tag":"LineTo","args":[{"point":[728,300]}]},{"tag":"LineTo","args":[{"point":[438,300]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[438,300],"end":[438,300]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[438,300],"end":[438,300]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[428,300],"end":[420.5,293]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[413,286],"end":[413,277]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[413,267],"end":[420.5,260]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[428,253],"end":[438,253]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[438,253],"end":[438,253]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[438,253],"end":[438,253]}]}]},{"tag":"LineTo","args":[{"point":[778,253]}]}]},{"start":[26,0],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[77,0]}]},{"tag":"LineTo","args":[{"point":[93,6]}]},{"tag":"LineTo","args":[{"point":[102,24]}]},{"tag":"LineTo","args":[{"point":[96,43]}]},{"tag":"LineTo","args":[{"point":[77,51]}]},{"tag":"LineTo","args":[{"point":[26,51]}]},{"tag":"LineTo","args":[{"point":[9,46]}]},{"tag":"LineTo","args":[{"point":[0,27]}]},{"tag":"LineTo","args":[{"point":[7,8]}]},{"tag":"LineTo","args":[{"point":[26,0]}]}]},{"start":[231,0],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[282,0]}]},{"tag":"LineTo","args":[{"point":[298,6]}]},{"tag":"LineTo","args":[{"point":[307,24]}]},{"tag":"LineTo","args":[{"point":[301,43]}]},{"tag":"LineTo","args":[{"point":[282,51]}]},{"tag":"LineTo","args":[{"point":[231,51]}]},{"tag":"LineTo","args":[{"point":[215,46]}]},{"tag":"LineTo","args":[{"point":[205,27]}]},{"tag":"LineTo","args":[{"point":[212,8]}]},{"tag":"LineTo","args":[{"point":[231,0]}]}]},{"start":[427,7],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[446,14]}]},{"tag":"LineTo","args":[{"point":[454,33]}]},{"tag":"LineTo","args":[{"point":[454,84]}]},{"tag":"LineTo","args":[{"point":[449,100]}]},{"tag":"LineTo","args":[{"point":[430,110]}]},{"tag":"LineTo","args":[{"point":[411,103]}]},{"tag":"LineTo","args":[{"point":[403,84]}]},{"tag":"LineTo","args":[{"point":[403,33]}]},{"tag":"LineTo","args":[{"point":[409,17]}]},{"tag":"LineTo","args":[{"point":[427,7]}]}]},{"start":[24,126],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[43,132]}]},{"tag":"LineTo","args":[{"point":[51,151]}]},{"tag":"LineTo","args":[{"point":[51,202]}]},{"tag":"LineTo","args":[{"point":[46,218]}]},{"tag":"LineTo","args":[{"point":[27,228]}]},{"tag":"LineTo","args":[{"point":[8,221]}]},{"tag":"LineTo","args":[{"point":[0,202]}]},{"tag":"LineTo","args":[{"point":[0,151]}]},{"tag":"LineTo","args":[{"point":[6,135]}]},{"tag":"LineTo","args":[{"point":[24,126]}]}]},{"start":[427,212],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[446,219]}]},{"tag":"LineTo","args":[{"point":[454,238]}]},{"tag":"LineTo","args":[{"point":[454,289]}]},{"tag":"LineTo","args":[{"point":[449,305]}]},{"tag":"LineTo","args":[{"point":[430,315]}]},{"tag":"LineTo","args":[{"point":[411,308]}]},{"tag":"LineTo","args":[{"point":[403,289]}]},{"tag":"LineTo","args":[{"point":[403,238]}]},{"tag":"LineTo","args":[{"point":[409,222]}]},{"tag":"LineTo","args":[{"point":[427,212]}]}]},{"start":[24,331],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[43,337]}]},{"tag":"LineTo","args":[{"point":[51,356]}]},{"tag":"LineTo","args":[{"point":[51,407]}]},{"tag":"LineTo","args":[{"point":[46,424]}]},{"tag":"LineTo","args":[{"point":[27,433]}]},{"tag":"LineTo","args":[{"point":[8,426]}]},{"tag":"LineTo","args":[{"point":[0,407]}]},{"tag":"LineTo","args":[{"point":[0,356]}]},{"tag":"LineTo","args":[{"point":[6,340]}]},{"tag":"LineTo","args":[{"point":[24,331]}]}]},{"start":[158,403],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[209,403]}]},{"tag":"LineTo","args":[{"point":[226,409]}]},{"tag":"LineTo","args":[{"point":[235,427]}]},{"tag":"LineTo","args":[{"point":[228,446]}]},{"tag":"LineTo","args":[{"point":[209,454]}]},{"tag":"LineTo","args":[{"point":[158,454]}]},{"tag":"LineTo","args":[{"point":[142,449]}]},{"tag":"LineTo","args":[{"point":[133,430]}]},{"tag":"LineTo","args":[{"point":[139,411]}]},{"tag":"LineTo","args":[{"point":[158,403]}]}]},{"start":[363,403],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[414,403]}]},{"tag":"LineTo","args":[{"point":[431,409]}]},{"tag":"LineTo","args":[{"point":[440,427]}]},{"tag":"LineTo","args":[{"point":[433,446]}]},{"tag":"LineTo","args":[{"point":[414,454]}]},{"tag":"LineTo","args":[{"point":[363,454]}]},{"tag":"LineTo","args":[{"point":[347,449]}]},{"tag":"LineTo","args":[{"point":[338,430]}]},{"tag":"LineTo","args":[{"point":[344,411]}]},{"tag":"LineTo","args":[{"point":[363,403]}]}]},{"start":[629,580],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[629,580]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[629,580],"end":[629,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[629,580],"end":[629,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[634,580],"end":[639,582.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[644,585],"end":[647,588]}]}]},{"tag":"LineTo","args":[{"point":[751,692]}]},{"tag":"LineTo","args":[{"point":[855,588]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[858,585],"end":[863,582.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[868,580],"end":[873,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[884,580],"end":[891.5,587.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[899,595],"end":[899,606]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[899,611],"end":[897,616]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[895,621],"end":[891,624]}]}]},{"tag":"LineTo","args":[{"point":[769,746]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[766,750],"end":[761,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[756,754],"end":[751,754]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[746,754],"end":[741,752]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[736,750],"end":[733,746]}]}]},{"tag":"LineTo","args":[{"point":[611,624]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[607,621],"end":[605,616]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[603,611],"end":[603,606]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[603,595],"end":[610.5,587.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[618,580],"end":[629,580]}]}]}]},{"start":[372,764],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[372,764]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[382,764],"end":[389.5,771.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[397,779],"end":[397,790]}]}]},{"tag":"LineTo","args":[{"point":[397,998]}]},{"tag":"LineTo","args":[{"point":[397,998]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[397,1009],"end":[389.5,1016.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[382,1024],"end":[372,1024]}]}]},{"tag":"LineTo","args":[{"point":[163,1024]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[153,1024],"end":[145.5,1016.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[138,1009],"end":[138,998]}]}]},{"tag":"LineTo","args":[{"point":[138,790]}]},{"tag":"LineTo","args":[{"point":[138,790]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[138,779],"end":[145.5,771.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[153,764],"end":[163,764]}]}]},{"tag":"LineTo","args":[{"point":[372,764]}]}]},{"start":[189,973],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[346,973]}]},{"tag":"LineTo","args":[{"point":[346,815]}]},{"tag":"LineTo","args":[{"point":[189,815]}]},{"tag":"LineTo","args":[{"point":[189,973]}]}]},{"start":[657,764],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[657,764]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[668,764],"end":[675.5,771.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[683,779],"end":[683,790]}]}]},{"tag":"LineTo","args":[{"point":[683,998]}]},{"tag":"LineTo","args":[{"point":[683,998]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[683,1009],"end":[675.5,1016.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[668,1024],"end":[657,1024]}]}]},{"tag":"LineTo","args":[{"point":[449,1024]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[438,1024],"end":[430.5,1016.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[423,1009],"end":[423,998]}]}]},{"tag":"LineTo","args":[{"point":[423,790]}]},{"tag":"LineTo","args":[{"point":[423,790]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[423,779],"end":[430.5,771.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[438,764],"end":[449,764]}]}]},{"tag":"LineTo","args":[{"point":[657,764]}]}]},{"start":[474,973],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[631,973]}]},{"tag":"LineTo","args":[{"point":[631,815]}]},{"tag":"LineTo","args":[{"point":[474,815]}]},{"tag":"LineTo","args":[{"point":[474,973]}]}]},{"start":[942,764],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[942,764]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[953,764],"end":[960.5,771.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[968,779],"end":[968,790]}]}]},{"tag":"LineTo","args":[{"point":[968,998]}]},{"tag":"LineTo","args":[{"point":[968,998]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[968,1009],"end":[960.5,1016.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[953,1024],"end":[942,1024]}]}]},{"tag":"LineTo","args":[{"point":[734,1024]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[723,1024],"end":[715.5,1016.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[708,1009],"end":[708,998]}]}]},{"tag":"LineTo","args":[{"point":[708,790]}]},{"tag":"LineTo","args":[{"point":[708,790]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[708,779],"end":[715.5,771.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[723,764],"end":[734,764]}]}]},{"tag":"LineTo","args":[{"point":[942,764]}]}]},{"start":[759,973],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[917,973]}]},{"tag":"LineTo","args":[{"point":[917,815]}]},{"tag":"LineTo","args":[{"point":[759,815]}]},{"tag":"LineTo","args":[{"point":[759,973]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"moveline-up","codePoint":59913},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":968,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[530,304],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[530,304],"end":[530,304]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[530,304],"end":[530,304]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[525,304],"end":[520,302]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[515,300],"end":[512,296]}]}]},{"tag":"LineTo","args":[{"point":[408,192]}]},{"tag":"LineTo","args":[{"point":[304,296]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[300,300],"end":[295.5,302]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[291,304],"end":[285,304]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,304],"end":[267.5,296.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[260,289],"end":[260,279]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[260,273],"end":[262,268.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[264,264],"end":[268,260]}]}]},{"tag":"LineTo","args":[{"point":[390,138]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[393,135],"end":[398,133]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[403,131],"end":[408,131]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[413,131],"end":[417.5,133]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[422,135],"end":[426,138]}]}]},{"tag":"LineTo","args":[{"point":[548,260]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[552,264],"end":[554,268.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[556,273],"end":[556,278]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[556,289],"end":[548.5,296.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[541,304],"end":[530,304]}]}]}]},{"start":[408,899],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[408,899]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[408,899],"end":[408,899]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[408,899],"end":[408,899]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[396,899],"end":[388,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,883],"end":[380,871]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,871],"end":[380,871]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,871],"end":[380,871]}]}]},{"tag":"LineTo","args":[{"point":[380,192]}]},{"tag":"LineTo","args":[{"point":[380,192]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,192],"end":[380,192]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,192],"end":[380,192]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,180],"end":[388,172]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[396,164],"end":[408,164]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[420,164],"end":[428,172]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,180],"end":[436,192]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,192],"end":[436,192]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,192],"end":[436,192]}]}]},{"tag":"LineTo","args":[{"point":[436,871]}]},{"tag":"LineTo","args":[{"point":[436,871]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,871],"end":[436,871]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,871],"end":[436,871]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,883],"end":[428,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[420,899],"end":[408,899]}]}]}]},{"start":[521,394],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[566,394]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[568,394],"end":[570,395.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[572,397],"end":[573,399]}]}]},{"tag":"LineTo","args":[{"point":[622,530]}]},{"tag":"LineTo","args":[{"point":[671,399]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,397],"end":[674,395.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[676,394],"end":[679,394]}]}]},{"tag":"LineTo","args":[{"point":[723,394]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,394],"end":[728.5,396.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[731,399],"end":[731,402]}]}]},{"tag":"LineTo","args":[{"point":[731,622]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[731,625],"end":[728.5,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,630],"end":[723,630]}]}]},{"tag":"LineTo","args":[{"point":[694,630]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[691,630],"end":[688.5,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[686,625],"end":[686,622]}]}]},{"tag":"LineTo","args":[{"point":[686,471]}]},{"tag":"LineTo","args":[{"point":[644,583]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[644,585],"end":[642,586.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,588],"end":[637,588]}]}]},{"tag":"LineTo","args":[{"point":[607,588]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[605,588],"end":[603,586.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[601,585],"end":[600,583]}]}]},{"tag":"LineTo","args":[{"point":[558,471]}]},{"tag":"LineTo","args":[{"point":[558,622]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[558,625],"end":[555.5,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[553,630],"end":[550,630]}]}]},{"tag":"LineTo","args":[{"point":[521,630]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[518,630],"end":[516,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[514,625],"end":[514,622]}]}]},{"tag":"LineTo","args":[{"point":[514,402]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[514,399],"end":[516,396.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[518,394],"end":[521,394]}]}]}]},{"start":[697.5,422],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[698,422],"end":[698,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[698,422],"end":[698,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[698,422],"end":[698,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[698,422],"end":[697.5,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[697,422],"end":[697,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[697,422],"end":[697.5,422]}]}]}]},{"start":[715,613],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[715,615]}]},{"tag":"LineTo","args":[{"point":[702,615]}]},{"tag":"LineTo","args":[{"point":[702,613]}]},{"tag":"LineTo","args":[{"point":[702,615]}]},{"tag":"LineTo","args":[{"point":[715,615]}]},{"tag":"LineTo","args":[{"point":[715,613]}]}]},{"start":[529,615],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[543,615]}]},{"tag":"LineTo","args":[{"point":[536,615]}]},{"tag":"LineTo","args":[{"point":[529,615]}]},{"tag":"LineTo","args":[{"point":[529,613]}]},{"tag":"LineTo","args":[{"point":[529,615]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"moveline-down","codePoint":59914},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":968,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[285,726],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[285,726]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[285,726],"end":[285.5,726]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[286,726],"end":[286,726]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[291,726],"end":[295.5,728]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[300,730],"end":[304,733]}]}]},{"tag":"LineTo","args":[{"point":[408,837]}]},{"tag":"LineTo","args":[{"point":[512,733]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[515,730],"end":[520,728]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[525,726],"end":[530,726]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[541,726],"end":[548.5,733.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[556,741],"end":[556,751]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[556,757],"end":[553.5,761.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[551,766],"end":[548,770]}]}]},{"tag":"LineTo","args":[{"point":[426,892]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[422,895],"end":[417.5,897]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[413,899],"end":[408,899]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[402,899],"end":[397.5,897]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[393,895],"end":[390,892]}]}]},{"tag":"LineTo","args":[{"point":[268,770]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[264,766],"end":[262,761.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[260,757],"end":[260,751]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[260,741],"end":[267.5,733.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,726],"end":[285,726]}]}]}]},{"start":[407,131],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[407,131],"end":[407.5,131]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[408,131],"end":[408,131]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[419,131],"end":[427.5,139]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,147],"end":[436,159]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,159],"end":[436,159]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,159],"end":[436,159]}]}]},{"tag":"LineTo","args":[{"point":[436,837]}]},{"tag":"LineTo","args":[{"point":[436,837]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,837],"end":[436,837.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,838],"end":[436,838]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,849],"end":[427.5,857.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[419,866],"end":[408,866]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[396,866],"end":[388,857.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,849],"end":[380,838]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,838],"end":[380,837.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,837],"end":[380,837]}]}]},{"tag":"LineTo","args":[{"point":[380,159]}]},{"tag":"LineTo","args":[{"point":[380,159]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,159],"end":[380,159]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,159],"end":[380,159]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,147],"end":[388,139]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[396,131],"end":[407,131]}]}]}]},{"start":[521,394],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[566,394]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[568,394],"end":[570,395.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[572,397],"end":[573,399]}]}]},{"tag":"LineTo","args":[{"point":[622,530]}]},{"tag":"LineTo","args":[{"point":[671,399]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,397],"end":[674,395.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[676,394],"end":[679,394]}]}]},{"tag":"LineTo","args":[{"point":[723,394]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,394],"end":[728.5,396.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[731,399],"end":[731,402]}]}]},{"tag":"LineTo","args":[{"point":[731,622]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[731,625],"end":[728.5,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[726,630],"end":[723,630]}]}]},{"tag":"LineTo","args":[{"point":[694,630]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[691,630],"end":[688.5,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[686,625],"end":[686,622]}]}]},{"tag":"LineTo","args":[{"point":[686,471]}]},{"tag":"LineTo","args":[{"point":[644,583]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[644,585],"end":[642,586.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[640,588],"end":[637,588]}]}]},{"tag":"LineTo","args":[{"point":[607,588]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[605,588],"end":[603,586.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[601,585],"end":[600,583]}]}]},{"tag":"LineTo","args":[{"point":[558,471]}]},{"tag":"LineTo","args":[{"point":[558,622]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[558,625],"end":[555.5,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[553,630],"end":[550,630]}]}]},{"tag":"LineTo","args":[{"point":[521,630]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[518,630],"end":[516,627.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[514,625],"end":[514,622]}]}]},{"tag":"LineTo","args":[{"point":[514,402]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[514,399],"end":[516,396.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[518,394],"end":[521,394]}]}]}]},{"start":[697.5,422],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[698,422],"end":[698,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[698,422],"end":[698,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[698,422],"end":[698,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[698,422],"end":[697.5,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[697,422],"end":[697,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[697,422],"end":[697.5,422]}]}]}]},{"start":[715,613],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[715,615]}]},{"tag":"LineTo","args":[{"point":[702,615]}]},{"tag":"LineTo","args":[{"point":[702,613]}]},{"tag":"LineTo","args":[{"point":[702,615]}]},{"tag":"LineTo","args":[{"point":[715,615]}]},{"tag":"LineTo","args":[{"point":[715,613]}]}]},{"start":[529,615],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[543,615]}]},{"tag":"LineTo","args":[{"point":[536,615]}]},{"tag":"LineTo","args":[{"point":[529,615]}]},{"tag":"LineTo","args":[{"point":[529,613]}]},{"tag":"LineTo","args":[{"point":[529,615]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"copyline-up","codePoint":59915},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":968,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[530,304],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[530,304],"end":[530,304]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[530,304],"end":[530,304]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[525,304],"end":[520,302]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[515,300],"end":[512,296]}]}]},{"tag":"LineTo","args":[{"point":[408,192]}]},{"tag":"LineTo","args":[{"point":[304,296]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[300,300],"end":[295.5,302]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[291,304],"end":[285,304]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,304],"end":[267.5,296.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[260,289],"end":[260,279]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[260,273],"end":[262,268.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[264,264],"end":[268,260]}]}]},{"tag":"LineTo","args":[{"point":[390,138]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[393,135],"end":[398,133]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[403,131],"end":[408,131]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[413,131],"end":[417.5,133]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[422,135],"end":[426,138]}]}]},{"tag":"LineTo","args":[{"point":[548,260]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[552,264],"end":[554,268.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[556,273],"end":[556,278]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[556,289],"end":[548.5,296.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[541,304],"end":[530,304]}]}]}]},{"start":[408,899],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[408,899]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[408,899],"end":[408,899]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[408,899],"end":[408,899]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[396,899],"end":[388,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,883],"end":[380,871]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,871],"end":[380,871]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,871],"end":[380,871]}]}]},{"tag":"LineTo","args":[{"point":[380,192]}]},{"tag":"LineTo","args":[{"point":[380,192]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,192],"end":[380,192]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,192],"end":[380,192]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,180],"end":[388,172]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[396,164],"end":[408,164]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[420,164],"end":[428,172]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,180],"end":[436,192]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,192],"end":[436,192]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,192],"end":[436,192]}]}]},{"tag":"LineTo","args":[{"point":[436,871]}]},{"tag":"LineTo","args":[{"point":[436,871]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,871],"end":[436,871]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,871],"end":[436,871]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,883],"end":[428,891]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[420,899],"end":[408,899]}]}]}]},{"start":[643,393],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[654,393],"end":[665,394.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[676,396],"end":[686,399]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[686,399],"end":[686,399]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[686,399],"end":[686,399]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[696,401],"end":[705.5,405]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[715,409],"end":[724,415]}]}]},{"tag":"LineTo","args":[{"point":[724,415]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[727,416],"end":[728.5,418.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[730,421],"end":[730,424]}]}]},{"tag":"LineTo","args":[{"point":[730,454]}]},{"tag":"LineTo","args":[{"point":[730,454]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[730,458],"end":[726.5,461.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[723,465],"end":[719,465]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[717,465],"end":[715,464.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[713,464],"end":[712,462]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,456],"end":[696,451.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,447],"end":[680,444]}]}]},{"tag":"LineTo","args":[{"point":[680,444]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,444],"end":[680,444]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,444],"end":[680,444]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,442],"end":[663,440.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[654,439],"end":[645,439]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[625,439],"end":[612,443.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[599,448],"end":[590,457]}]}]},{"tag":"LineTo","args":[{"point":[590,457]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[590,457],"end":[590,457]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[590,457],"end":[590,457]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[581,466],"end":[576,479.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[571,493],"end":[571,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[571,531],"end":[575.5,544.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[580,558],"end":[590,567]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[599,576],"end":[612,580.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[625,585],"end":[645,585]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[654,585],"end":[663,583.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,582],"end":[680,580]}]}]},{"tag":"LineTo","args":[{"point":[680,580]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,580],"end":[680,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,580],"end":[680,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,580],"end":[680,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,580],"end":[680,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,577],"end":[696,572.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,568],"end":[712,562]}]}]},{"tag":"LineTo","args":[{"point":[712,562]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[713,560],"end":[715,559.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[717,559],"end":[719,559]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[723,559],"end":[726.5,562.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[730,566],"end":[730,570]}]}]},{"tag":"LineTo","args":[{"point":[730,600]}]},{"tag":"LineTo","args":[{"point":[730,600]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[730,603],"end":[728.5,605.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[727,608],"end":[724,609]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[715,615],"end":[705.5,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[696,623],"end":[686,625]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[675,628],"end":[664.5,629.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[654,631],"end":[643,631]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[614,631],"end":[590.5,623]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[567,615],"end":[549,599]}]}]},{"tag":"LineTo","args":[{"point":[549,599]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[549,599],"end":[549,599]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[549,599],"end":[549,599]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[532,583],"end":[523.5,561]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[515,539],"end":[515,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[515,485],"end":[523.5,463]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[532,441],"end":[549,425]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[567,409],"end":[590.5,401]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[614,393],"end":[643,393]}]}]}]},{"start":[643,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[617,416],"end":[597.5,422.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[578,429],"end":[565,441]}]}]},{"tag":"LineTo","args":[{"point":[565,441]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[565,441],"end":[565,441]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[565,441],"end":[565,441]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[551,454],"end":[544,471.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[537,489],"end":[537,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[537,535],"end":[544,552.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[551,570],"end":[565,583]}]}]},{"tag":"LineTo","args":[{"point":[565,583]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[578,595],"end":[597.5,601.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[617,608],"end":[643,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[653,608],"end":[662,607]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[671,606],"end":[680,604]}]}]},{"tag":"LineTo","args":[{"point":[680,604]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,604],"end":[680,604]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,604],"end":[680,604]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,604],"end":[680,604]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,604],"end":[680,604]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[687,602],"end":[694,599]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[701,596],"end":[708,592]}]}]},{"tag":"LineTo","args":[{"point":[708,589]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[703,592],"end":[698,595.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[693,599],"end":[688,601]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[677,604],"end":[666.5,606]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[656,608],"end":[645,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[623,608],"end":[605,601.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[587,595],"end":[574,583]}]}]},{"tag":"LineTo","args":[{"point":[574,583]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[574,583],"end":[574,583]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[574,583],"end":[574,583]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[561,570],"end":[555,552]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[549,534],"end":[549,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[549,490],"end":[555,472]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[561,454],"end":[574,441]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[587,429],"end":[605,422.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[623,416],"end":[645,416]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[656,416],"end":[666.5,418]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[677,420],"end":[688,423]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[693,425],"end":[698,428.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[703,432],"end":[708,435]}]}]},{"tag":"LineTo","args":[{"point":[708,431]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[701,428],"end":[694.5,425]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,422],"end":[680,420]}]}]},{"tag":"LineTo","args":[{"point":[680,420]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,420],"end":[680,420]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,420],"end":[680,420]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[671,418],"end":[662,417]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[653,416],"end":[643,416]}]}]}]},{"start":[635,608],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[649,609],"end":[661.5,607.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[674,606],"end":[685,602]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[689,601],"end":[692.5,599.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[696,598],"end":[701,595]}]}]},{"tag":"LineTo","args":[{"point":[707,592]}]},{"tag":"LineTo","args":[{"point":[707,591]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[707,590],"end":[706.5,590]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[706,590],"end":[702,593]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[695,597],"end":[692,598.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[689,600],"end":[684,602]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[677,604],"end":[669.5,605.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[662,607],"end":[655,607]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[651,608],"end":[644,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[637,608],"end":[634,607]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[622,607],"end":[612,604]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[602,601],"end":[594,597]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[578,589],"end":[567.5,575.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[557,562],"end":[552,543]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[549,529],"end":[549,511.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[549,494],"end":[552,480]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[555,470],"end":[559.5,461.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[564,453],"end":[570,446]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[572,443],"end":[575.5,440]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[579,437],"end":[581,435]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[593,426],"end":[607,421.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[621,417],"end":[639,416]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[650,416],"end":[661,417.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,419],"end":[683,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,423],"end":[691.5,425]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[695,427],"end":[701,431]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[703,432],"end":[704.5,433]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[706,434],"end":[707,434]}]}]},{"tag":"LineTo","args":[{"point":[707,435]}]},{"tag":"LineTo","args":[{"point":[707,431]}]},{"tag":"LineTo","args":[{"point":[702,429]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[700,428],"end":[697.5,427]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[695,426],"end":[694,425]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[686,422],"end":[676.5,419.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[667,417],"end":[656,416]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,416],"end":[643,416]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[634,416],"end":[630,416]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[612,418],"end":[599.5,422]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[587,426],"end":[576,433]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[572,435],"end":[569,437.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[566,440],"end":[563,443]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[557,449],"end":[553.5,454]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[550,459],"end":[547,465]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[542,475],"end":[539.5,486.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[537,498],"end":[537,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[537,522],"end":[538,530.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[539,539],"end":[542,547]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[545,557],"end":[550,565]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[555,573],"end":[562,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[575,593],"end":[593.5,600]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[612,607],"end":[635,608]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"copyline-down","codePoint":59916},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":968,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[285,726],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[285,726]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[285,726],"end":[285.5,726]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[286,726],"end":[286,726]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[291,726],"end":[295.5,728]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[300,730],"end":[304,733]}]}]},{"tag":"LineTo","args":[{"point":[408,837]}]},{"tag":"LineTo","args":[{"point":[512,733]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[515,730],"end":[520,728]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[525,726],"end":[530,726]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[541,726],"end":[548.5,733.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[556,741],"end":[556,751]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[556,757],"end":[553.5,761.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[551,766],"end":[548,770]}]}]},{"tag":"LineTo","args":[{"point":[426,892]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[422,895],"end":[417.5,897]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[413,899],"end":[408,899]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[402,899],"end":[397.5,897]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[393,895],"end":[390,892]}]}]},{"tag":"LineTo","args":[{"point":[268,770]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[264,766],"end":[262,761.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[260,757],"end":[260,751]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[260,741],"end":[267.5,733.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[275,726],"end":[285,726]}]}]}]},{"start":[407,131],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[407,131],"end":[407.5,131]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[408,131],"end":[408,131]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[419,131],"end":[427.5,139]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,147],"end":[436,159]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,159],"end":[436,159]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,159],"end":[436,159]}]}]},{"tag":"LineTo","args":[{"point":[436,837]}]},{"tag":"LineTo","args":[{"point":[436,837]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,837],"end":[436,837.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,838],"end":[436,838]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,849],"end":[427.5,857.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[419,866],"end":[408,866]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[396,866],"end":[388,857.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,849],"end":[380,838]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,838],"end":[380,837.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,837],"end":[380,837]}]}]},{"tag":"LineTo","args":[{"point":[380,159]}]},{"tag":"LineTo","args":[{"point":[380,159]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,159],"end":[380,159]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,159],"end":[380,159]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[380,147],"end":[388,139]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[396,131],"end":[407,131]}]}]}]},{"start":[643,393],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[654,393],"end":[665,394.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[676,396],"end":[686,399]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[686,399],"end":[686,399]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[686,399],"end":[686,399]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[696,401],"end":[705.5,405]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[715,409],"end":[724,415]}]}]},{"tag":"LineTo","args":[{"point":[724,415]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[727,416],"end":[728.5,418.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[730,421],"end":[730,424]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[730,424],"end":[730,424]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[730,424],"end":[730,424]}]}]},{"tag":"LineTo","args":[{"point":[730,454]}]},{"tag":"LineTo","args":[{"point":[730,454]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[730,458],"end":[726.5,461.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[723,465],"end":[719,465]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[717,465],"end":[715,464.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[713,464],"end":[712,462]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,456],"end":[696,451.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,447],"end":[680,444]}]}]},{"tag":"LineTo","args":[{"point":[680,444]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,444],"end":[680,444]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,444],"end":[680,444]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,442],"end":[663,440.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[654,439],"end":[645,439]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[625,439],"end":[612,443.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[599,448],"end":[590,457]}]}]},{"tag":"LineTo","args":[{"point":[590,457]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[590,457],"end":[590,457]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[590,457],"end":[590,457]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[581,466],"end":[576,479.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[571,493],"end":[571,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[571,531],"end":[575.5,544.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[580,558],"end":[590,567]}]}]},{"tag":"LineTo","args":[{"point":[590,567]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[599,576],"end":[612,580.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[625,585],"end":[645,585]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[654,585],"end":[663,583.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[672,582],"end":[680,580]}]}]},{"tag":"LineTo","args":[{"point":[680,580]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,580],"end":[680,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,580],"end":[680,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,577],"end":[696,572.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,568],"end":[712,562]}]}]},{"tag":"LineTo","args":[{"point":[712,562]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[713,560],"end":[715,559.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[717,559],"end":[719,559]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[723,559],"end":[726.5,562.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[730,566],"end":[730,570]}]}]},{"tag":"LineTo","args":[{"point":[730,600]}]},{"tag":"LineTo","args":[{"point":[730,600]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[730,603],"end":[728.5,605.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[727,608],"end":[724,609]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[715,615],"end":[705.5,619]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[696,623],"end":[686,625]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[675,628],"end":[664.5,629.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[654,631],"end":[643,631]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[614,631],"end":[590.5,623]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[567,615],"end":[549,599]}]}]},{"tag":"LineTo","args":[{"point":[549,599]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[549,599],"end":[549,599]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[549,599],"end":[549,599]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[532,583],"end":[523.5,561]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[515,539],"end":[515,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[515,485],"end":[523.5,463]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[532,441],"end":[549,425]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[567,409],"end":[590.5,401]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[614,393],"end":[643,393]}]}]}]},{"start":[643,416],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[617,416],"end":[597.5,422.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[578,429],"end":[565,441]}]}]},{"tag":"LineTo","args":[{"point":[565,441]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[565,441],"end":[565,441]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[565,441],"end":[565,441]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[551,454],"end":[544,471.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[537,489],"end":[537,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[537,535],"end":[544,552.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[551,570],"end":[565,583]}]}]},{"tag":"LineTo","args":[{"point":[565,583]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[578,595],"end":[597.5,601.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[617,608],"end":[643,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[653,608],"end":[662,607]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[671,606],"end":[680,604]}]}]},{"tag":"LineTo","args":[{"point":[680,604]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,604],"end":[680,604]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,604],"end":[680,604]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,604],"end":[680,604]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,604],"end":[680,604]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[687,602],"end":[694,599]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[701,596],"end":[708,592]}]}]},{"tag":"LineTo","args":[{"point":[708,589]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[703,592],"end":[698,595.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[693,599],"end":[688,601]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[677,604],"end":[666.5,606]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[656,608],"end":[645,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[623,608],"end":[605,601.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[587,595],"end":[574,583]}]}]},{"tag":"LineTo","args":[{"point":[574,583]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[574,583],"end":[574,583]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[574,583],"end":[574,583]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[561,570],"end":[555,552]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[549,534],"end":[549,512]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[549,490],"end":[555,472]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[561,454],"end":[574,441]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[587,429],"end":[605,422.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[623,416],"end":[645,416]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[656,416],"end":[666.5,418]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[677,420],"end":[688,423]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[693,425],"end":[698,428.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[703,432],"end":[708,435]}]}]},{"tag":"LineTo","args":[{"point":[708,431]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[701,428],"end":[694.5,425]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[688,422],"end":[680,420]}]}]},{"tag":"LineTo","args":[{"point":[680,420]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,420],"end":[680,420]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,420],"end":[680,420]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[671,418],"end":[662,417]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[653,416],"end":[643,416]}]}]}]},{"start":[637,608],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[653,609],"end":[666.5,607]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[680,605],"end":[691,600]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[694,599],"end":[698,597]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[702,595],"end":[705,594]}]}]},{"tag":"LineTo","args":[{"point":[707,592]}]},{"tag":"LineTo","args":[{"point":[707,591]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[707,590],"end":[707,590]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[707,590],"end":[707,590]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[707,590],"end":[705.5,591]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[704,592],"end":[702,593]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[695,597],"end":[692,598.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[689,600],"end":[684,602]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[679,603],"end":[673,604.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[667,606],"end":[662,607]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[657,607],"end":[654,607.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[651,608],"end":[644,608]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[637,608],"end":[633,607.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[629,607],"end":[623,606]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,602],"end":[577,585.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[559,569],"end":[552,543]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[549,531],"end":[548.5,516]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[548,501],"end":[551,488]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[553,474],"end":[559,462]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[565,450],"end":[574,441]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[585,431],"end":[599.5,424.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[614,418],"end":[633,417]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[637,416],"end":[645,416]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[653,416],"end":[657,417]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[665,418],"end":[673,419.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[681,421],"end":[688,423]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[690,424],"end":[693.5,426]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[697,428],"end":[700,430]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[701,431],"end":[703,432]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[705,433],"end":[705,433]}]}]},{"tag":"LineTo","args":[{"point":[707,435]}]},{"tag":"LineTo","args":[{"point":[707,431]}]},{"tag":"LineTo","args":[{"point":[702,429]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[695,425],"end":[690,423]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[685,421],"end":[678,420]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[673,418],"end":[668,417.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[663,417],"end":[656,416]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,416],"end":[641.5,416]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[631,416],"end":[627,416]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[614,418],"end":[604,420.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[594,423],"end":[584,428]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[573,434],"end":[563.5,443]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[554,452],"end":[548,463]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[544,471],"end":[541.5,479.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[539,488],"end":[538,500]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[537,503],"end":[537,511.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[537,520],"end":[537,523]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[539,542],"end":[545,555.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[551,569],"end":[562,580]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[576,594],"end":[594.5,601]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[613,608],"end":[637,608]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"acode","codePoint":59917},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[976,526],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[976,531],"end":[974.5,537.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[973,544],"end":[967,550]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[965,552],"end":[963,554]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[961,556],"end":[959,558]}]}]},{"tag":"LineTo","args":[{"point":[959,558]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[930,589],"end":[885.5,635]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[841,681],"end":[813,709]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[808,714],"end":[803,717]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[798,720],"end":[792,720]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[777,720],"end":[750,720]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[723,720],"end":[708,720]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[706,720],"end":[704,719.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[702,719],"end":[701,719]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[705,746],"end":[709.5,772]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[714,798],"end":[718,822]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[720,833],"end":[710,843.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[700,854],"end":[690,854]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[675,854],"end":[655,854]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[635,854],"end":[624,854]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[616,854],"end":[606.5,846.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[597,839],"end":[595,824]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[587,785],"end":[578,734]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[568,683],"end":[557,625.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[546,568],"end":[534,508]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[523,447],"end":[512,390]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[501,447],"end":[489,508]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,568],"end":[467,626]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[456,684],"end":[446,735]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[436,786],"end":[429,824]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[426,840],"end":[417,847.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[408,855],"end":[400,855]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[388,855],"end":[368.5,855]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[349,855],"end":[334,855]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[324,855],"end":[313.5,844.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[303,834],"end":[305,823]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[309,799],"end":[313.5,773]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[318,747],"end":[323,719]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[321,720],"end":[319,720.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[317,721],"end":[315,721]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[300,721],"end":[273.5,721]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[247,721],"end":[231,721]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[226,721],"end":[220.5,718]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[215,715],"end":[210,710]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[183,682],"end":[138,636]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[93,590],"end":[64,559]}]}]},{"tag":"LineTo","args":[{"point":[64,559]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[62,557],"end":[60,555]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[58,553],"end":[56,551]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[51,545],"end":[49,538.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[47,532],"end":[47,527]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[47,526],"end":[47.5,525]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[48,524],"end":[48,523]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[48,518],"end":[50,512.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[52,507],"end":[56,502]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[58,500],"end":[60,498]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[62,496],"end":[64,494]}]}]},{"tag":"LineTo","args":[{"point":[64,494]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[93,463],"end":[138,417]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[183,371],"end":[210,343]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[215,338],"end":[220.5,335]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[226,332],"end":[231,332]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[247,332],"end":[273.5,332]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[300,332],"end":[315,332]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[324,332],"end":[332,338.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[340,345],"end":[343,352]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[347,362],"end":[346,374]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[345,386],"end":[337,395]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[314,418],"end":[264.5,469]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[215,520],"end":[209,526]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[215,533],"end":[262.5,582]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[310,631],"end":[334,656]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[345,595],"end":[355,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[366,471],"end":[376,412]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[386,353],"end":[395,299]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[404,246],"end":[411,203]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[413,191],"end":[422.5,181]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[432,171],"end":[441,171]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[452,171],"end":[468.5,171]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[485,171],"end":[500,171]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[501,170],"end":[502.5,170]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[504,170],"end":[506,170]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[520,170],"end":[544,170]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[568,170],"end":[583,170]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[592,170],"end":[601,180]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[610,190],"end":[612,202]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[620,245],"end":[629,298]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[638,352],"end":[648,410.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[658,469],"end":[669,532]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[679,594],"end":[690,654]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[714,630],"end":[761,581]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[808,532],"end":[814,525]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[808,519],"end":[759,468]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[710,417],"end":[687,394]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[678,385],"end":[677.5,373]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[677,361],"end":[681,351]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[683,344],"end":[691,337.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[699,331],"end":[708,331]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[723,331],"end":[750,331]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[777,331],"end":[792,331]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[798,331],"end":[803,334]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[808,337],"end":[813,342]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[841,370],"end":[885.5,416]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[930,462],"end":[959,493]}]}]},{"tag":"LineTo","args":[{"point":[959,493]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[961,495],"end":[963,497]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[965,499],"end":[967,501]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[972,506],"end":[973.5,511.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[975,517],"end":[976,522]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[976,523],"end":[976,524]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[976,525],"end":[976,526]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"patreon","codePoint":59919},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[799,51],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[799,51]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[866,80],"end":[916,130.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[966,181],"end":[995,248]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,315],"end":[1024,391]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,467],"end":[995,534]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[966,601],"end":[916,651]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[866,701],"end":[799,730]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[732,758],"end":[656,758]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[580,758],"end":[513,730]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[446,701],"end":[396,651]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[346,601],"end":[317,534]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[288,467],"end":[288,391]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[288,315],"end":[317,248]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[346,181],"end":[396,130.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[446,80],"end":[513,51]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[580,22],"end":[656,22]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[732,22],"end":[799,51]}]}]}]},{"start":[0,22],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[180,22]}]},{"tag":"LineTo","args":[{"point":[180,1004]}]},{"tag":"LineTo","args":[{"point":[0,1004]}]},{"tag":"LineTo","args":[{"point":[0,22]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"paypal","codePoint":59920},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[295,1024],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[295,1023]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[316,1023],"end":[334.5,1008.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[353,994],"end":[358,973]}]}]},{"tag":"LineTo","args":[{"point":[403,777]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[408,756],"end":[427,741]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[446,726],"end":[467,726]}]}]},{"tag":"LineTo","args":[{"point":[505,726]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[566,726],"end":[619,720]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[673,714],"end":[720.5,701.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[768,689],"end":[808,670]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[848,652],"end":[882,627]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[950,577],"end":[983.5,511.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1017,446],"end":[1017,365]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1017,330],"end":[1010.5,300]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1004,270],"end":[992,246]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[979,222],"end":[961,203]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[943,184],"end":[919,169]}]}]},{"tag":"LineTo","args":[{"point":[913,166]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[913,166],"end":[913,166.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[913,167],"end":[913,168]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[926,191],"end":[932.5,221]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[939,251],"end":[939,287]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[939,368],"end":[905,433]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[871,498],"end":[804,548]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[770,573],"end":[730,592]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[689,611],"end":[642,623.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[595,636],"end":[541,642]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[487,648],"end":[427,648]}]}]},{"tag":"LineTo","args":[{"point":[389,648]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[368,648],"end":[349.5,663]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[331,678],"end":[326,699]}]}]},{"tag":"LineTo","args":[{"point":[280,894]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[276,915],"end":[257,930]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[238,945],"end":[217,945]}]}]},{"tag":"LineTo","args":[{"point":[129,945]}]},{"tag":"LineTo","args":[{"point":[122,974]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[118,994],"end":[129.5,1009]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[141,1024],"end":[162,1024]}]}]},{"tag":"LineTo","args":[{"point":[295,1024]}]}]},{"start":[181,909],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[180,907]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[201,907],"end":[219.5,892.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[238,878],"end":[243,857]}]}]},{"tag":"LineTo","args":[{"point":[288,662]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[293,641],"end":[311.5,626.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[330,612],"end":[352,612]}]}]},{"tag":"LineTo","args":[{"point":[389,612]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[450,612],"end":[504,606]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[557,600],"end":[604.5,587.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[652,575],"end":[692,556]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[733,538],"end":[766,513]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[834,463],"end":[867.5,398]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[901,333],"end":[901,251]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[901,216],"end":[895,186]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[889,156],"end":[876,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[864,108],"end":[845.5,88.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[827,69],"end":[804,55]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[779,39],"end":[750.5,28.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[722,18],"end":[689,12]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[656,6],"end":[617,3]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[578,0],"end":[534,0]}]}]},{"tag":"LineTo","args":[{"point":[258,0]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[237,0],"end":[218.5,15]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[200,30],"end":[195,50]}]}]},{"tag":"LineTo","args":[{"point":[8,859]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[3,879],"end":[15,894]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[27,909],"end":[48,909]}]}]},{"tag":"LineTo","args":[{"point":[181,909]}]}]},{"start":[498,168],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[497,168]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[535,168],"end":[564,174.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[593,181],"end":[612,194]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[631,206],"end":[640.5,226]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[650,246],"end":[650,272]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[650,312],"end":[635.5,343.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[621,375],"end":[591,396]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[561,418],"end":[519.5,429]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[478,440],"end":[424,440]}]}]},{"tag":"LineTo","args":[{"point":[392,440]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[371,440],"end":[359,425]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[347,410],"end":[352,390]}]}]},{"tag":"LineTo","args":[{"point":[392,218]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[397,197],"end":[415.5,182.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[434,168],"end":[455,168]}]}]},{"tag":"LineTo","args":[{"point":[498,168]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"ruby","codePoint":59921},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[860,4],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[860,3]}]},{"tag":"LineTo","args":[{"point":[704,90]}]},{"tag":"LineTo","args":[{"point":[974,310]}]},{"tag":"LineTo","args":[{"point":[1000,332]}]},{"tag":"LineTo","args":[{"point":[624,356]}]},{"tag":"LineTo","args":[{"point":[666,523]}]},{"tag":"LineTo","args":[{"point":[726,755]}]},{"tag":"LineTo","args":[{"point":[331,628]}]},{"tag":"LineTo","args":[{"point":[330,630]}]},{"tag":"LineTo","args":[{"point":[332,629]}]},{"tag":"LineTo","args":[{"point":[212,1020]}]},{"tag":"LineTo","args":[{"point":[70,689]}]},{"tag":"LineTo","args":[{"point":[0,817]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[2,890],"end":[27,931]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[51,971],"end":[83.5,991]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[116,1011],"end":[151,1015]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[186,1020],"end":[209,1021]}]}]},{"tag":"LineTo","args":[{"point":[966,969]}]},{"tag":"LineTo","args":[{"point":[1024,206]}]},{"tag":"LineTo","args":[{"point":[1023,207]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1025,138],"end":[991,79]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[957,20],"end":[860,4]}]}]}]},{"start":[219,216],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[219,217]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[162,273],"end":[120,335]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[78,396],"end":[56.5,452.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[35,509],"end":[36,557]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[36,604],"end":[65,633]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[93,661],"end":[141,659]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[189,658],"end":[246.5,633]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[304,608],"end":[366,564]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[428,520],"end":[486,464]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[543,407],"end":[585,347]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[627,286],"end":[649,230]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[671,174],"end":[671,128]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[670,81],"end":[642,53]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[614,24],"end":[566,25]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[517,26],"end":[459,49.5]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[401,73],"end":[339,117]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[276,160],"end":[219,216]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"font_download","codePoint":59922},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[632,683],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[392,683]}]},{"tag":"LineTo","args":[{"point":[344,811]}]},{"tag":"LineTo","args":[{"point":[254,811]}]},{"tag":"LineTo","args":[{"point":[472,255]}]},{"tag":"LineTo","args":[{"point":[552,255]}]},{"tag":"LineTo","args":[{"point":[770,811]}]},{"tag":"LineTo","args":[{"point":[680,811]}]},{"tag":"LineTo","args":[{"point":[632,683]}]}]},{"start":[170,107],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,107],"end":[111,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,157],"end":[86,191]}]}]},{"tag":"LineTo","args":[{"point":[86,875]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,909],"end":[111,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[136,959],"end":[170,959]}]}]},{"tag":"LineTo","args":[{"point":[854,959]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,959],"end":[913,934]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,909],"end":[938,875]}]}]},{"tag":"LineTo","args":[{"point":[938,191]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,157],"end":[913,132]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[888,107],"end":[854,107]}]}]},{"tag":"LineTo","args":[{"point":[170,107]}]}]},{"start":[600,597],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,361]}]},{"tag":"LineTo","args":[{"point":[424,597]}]},{"tag":"LineTo","args":[{"point":[600,597]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"notes","codePoint":59923},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[896,575],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[896,491]}]},{"tag":"LineTo","args":[{"point":[128,491]}]},{"tag":"LineTo","args":[{"point":[128,575]}]},{"tag":"LineTo","args":[{"point":[896,575]}]}]},{"start":[128,363],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[896,363]}]},{"tag":"LineTo","args":[{"point":[896,277]}]},{"tag":"LineTo","args":[{"point":[128,277]}]},{"tag":"LineTo","args":[{"point":[128,363]}]}]},{"start":[640,789],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[640,703]}]},{"tag":"LineTo","args":[{"point":[128,703]}]},{"tag":"LineTo","args":[{"point":[128,789]}]},{"tag":"LineTo","args":[{"point":[640,789]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"http","codePoint":59924},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[832,511],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[832,469]}]},{"tag":"LineTo","args":[{"point":[918,469]}]},{"tag":"LineTo","args":[{"point":[918,511]}]},{"tag":"LineTo","args":[{"point":[832,511]}]}]},{"start":[768,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[768,661]}]},{"tag":"LineTo","args":[{"point":[832,661]}]},{"tag":"LineTo","args":[{"point":[832,575]}]},{"tag":"LineTo","args":[{"point":[918,575]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[944,575],"end":[963,556]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[982,537],"end":[982,511]}]}]},{"tag":"LineTo","args":[{"point":[982,469]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[982,443],"end":[963,424]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[944,405],"end":[918,405]}]}]},{"tag":"LineTo","args":[{"point":[768,405]}]}]},{"start":[598,469],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[598,661]}]},{"tag":"LineTo","args":[{"point":[662,661]}]},{"tag":"LineTo","args":[{"point":[662,469]}]},{"tag":"LineTo","args":[{"point":[726,469]}]},{"tag":"LineTo","args":[{"point":[726,405]}]},{"tag":"LineTo","args":[{"point":[534,405]}]},{"tag":"LineTo","args":[{"point":[534,469]}]},{"tag":"LineTo","args":[{"point":[598,469]}]}]},{"start":[362,469],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[362,661]}]},{"tag":"LineTo","args":[{"point":[426,661]}]},{"tag":"LineTo","args":[{"point":[426,469]}]},{"tag":"LineTo","args":[{"point":[490,469]}]},{"tag":"LineTo","args":[{"point":[490,405]}]},{"tag":"LineTo","args":[{"point":[298,405]}]},{"tag":"LineTo","args":[{"point":[298,469]}]},{"tag":"LineTo","args":[{"point":[362,469]}]}]},{"start":[106,491],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[106,405]}]},{"tag":"LineTo","args":[{"point":[42,405]}]},{"tag":"LineTo","args":[{"point":[42,661]}]},{"tag":"LineTo","args":[{"point":[106,661]}]},{"tag":"LineTo","args":[{"point":[106,555]}]},{"tag":"LineTo","args":[{"point":[192,555]}]},{"tag":"LineTo","args":[{"point":[192,661]}]},{"tag":"LineTo","args":[{"point":[256,661]}]},{"tag":"LineTo","args":[{"point":[256,405]}]},{"tag":"LineTo","args":[{"point":[192,405]}]},{"tag":"LineTo","args":[{"point":[192,491]}]},{"tag":"LineTo","args":[{"point":[106,491]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"compare_arrows","codePoint":59925},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[640,447],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[938,447]}]},{"tag":"LineTo","args":[{"point":[938,363]}]},{"tag":"LineTo","args":[{"point":[640,363]}]},{"tag":"LineTo","args":[{"point":[640,235]}]},{"tag":"LineTo","args":[{"point":[470,405]}]},{"tag":"LineTo","args":[{"point":[640,575]}]},{"tag":"LineTo","args":[{"point":[640,447]}]}]},{"start":[86,619],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[86,703]}]},{"tag":"LineTo","args":[{"point":[384,703]}]},{"tag":"LineTo","args":[{"point":[384,831]}]},{"tag":"LineTo","args":[{"point":[554,661]}]},{"tag":"LineTo","args":[{"point":[384,491]}]},{"tag":"LineTo","args":[{"point":[384,619]}]},{"tag":"LineTo","args":[{"point":[86,619]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"home_filled","codePoint":59926},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[170,405],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[170,917]}]},{"tag":"LineTo","args":[{"point":[384,917]}]},{"tag":"LineTo","args":[{"point":[384,619]}]},{"tag":"LineTo","args":[{"point":[640,619]}]},{"tag":"LineTo","args":[{"point":[640,917]}]},{"tag":"LineTo","args":[{"point":[854,917]}]},{"tag":"LineTo","args":[{"point":[854,405]}]},{"tag":"LineTo","args":[{"point":[512,149]}]},{"tag":"LineTo","args":[{"point":[170,405]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"height","codePoint":59927},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[682,319],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[512,149]}]},{"tag":"LineTo","args":[{"point":[342,319]}]},{"tag":"LineTo","args":[{"point":[470,319]}]},{"tag":"LineTo","args":[{"point":[470,747]}]},{"tag":"LineTo","args":[{"point":[342,747]}]},{"tag":"LineTo","args":[{"point":[512,917]}]},{"tag":"LineTo","args":[{"point":[682,747]}]},{"tag":"LineTo","args":[{"point":[554,747]}]},{"tag":"LineTo","args":[{"point":[554,319]}]},{"tag":"LineTo","args":[{"point":[682,319]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}},{"extras":{"name":"all_inclusive","codePoint":59928},"node":{"tag":"Element","args":[{"tagName":"svg","attributes":{"viewBox":{"tag":"Value","args":[{"tag":"ViewBox","args":[{"minX":0,"minY":0,"width":1024,"height":1024}]}]}},"children":[{"tag":"Element","args":[{"tagName":"path","attributes":{"d":{"tag":"Value","args":[{"tag":"Paths","args":[[{"start":[632,369],"endings":{"tag":"Connected","args":[]},"cmds":[{"tag":"LineTo","args":[{"point":[632,369]}]},{"tag":"LineTo","args":[{"point":[512,475]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[474,511],"end":[332,635]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,677],"end":[230,677]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,677],"end":[128,635]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,593],"end":[86,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[86,473],"end":[128,431]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[170,389],"end":[230,389]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[290,389],"end":[334,433]}]}]},{"tag":"LineTo","args":[{"point":[382,475]}]},{"tag":"LineTo","args":[{"point":[448,419]}]},{"tag":"LineTo","args":[{"point":[394,371]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[366,343],"end":[319,323]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[272,303],"end":[232,303]}]}]},{"tag":"LineTo","args":[{"point":[230,303]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[134,303],"end":[67,371]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,439],"end":[0,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[0,627],"end":[67,695]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[134,763],"end":[230,763]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[326,763],"end":[392,697]}]}]},{"tag":"LineTo","args":[{"point":[512,591]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[550,555],"end":[692,431]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[734,389],"end":[794,389]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,389],"end":[896,431]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,473],"end":[938,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[938,593],"end":[896,635]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[854,677],"end":[794,677]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[734,677],"end":[690,633]}]}]},{"tag":"LineTo","args":[{"point":[640,591]}]},{"tag":"LineTo","args":[{"point":[576,647]}]},{"tag":"LineTo","args":[{"point":[630,695]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[660,723],"end":[707,743]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[754,763],"end":[792,763]}]}]},{"tag":"LineTo","args":[{"point":[794,763]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[890,763],"end":[957,695]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,627],"end":[1024,533]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[1024,439],"end":[957,371]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[890,303],"end":[794,303]}]}]},{"tag":"BezierCurveTo","args":[{"tag":"QParams","args":[{"c":[698,303],"end":[632,369]}]}]}]}]]}]},"fill":{"tag":"Value","args":[{"tag":"Paint","args":[{"tag":"CurrentColor","args":[]}]}]}},"children":[]}]}]}]},"palettes":{"index":0,"table":[[{"background":{"tag":"AutomaticColor","args":[]},"foreground":{"tag":"AutomaticColor","args":[]}},[]]]}}]} \ No newline at end of file diff --git a/jsconfig.json b/jsconfig.json index b1983ca52c..6ad5ba2ee1 100644 --- a/jsconfig.json +++ b/jsconfig.json @@ -1,5 +1,5 @@ { - "exclude": ["**/node_modules", "**/platforms", "**/www", "www/js/ace/**/*"], + "exclude": ["**/node_modules", "**/platforms"], "compilerOptions": { "paths": { "*": ["./src/*"] diff --git a/licenses/NOTICE b/licenses/NOTICE new file mode 100644 index 0000000000..36c7bfe4c0 --- /dev/null +++ b/licenses/NOTICE @@ -0,0 +1,2 @@ +Native JavaScript helpers in src/native/{argscheck,base64,builder,channel,originalSymbols,statusbar,utils}.js are adapted from Apache Cordova JS under Apache-2.0. See native-runtime-LICENSE and native-runtime-NOTICE. +Native Android HTTP code is adapted from cordova-plugin-advanced-http; see advanced-http-LICENSE and native-provenance.json. diff --git a/licenses/README.md b/licenses/README.md new file mode 100644 index 0000000000..9f1228595f --- /dev/null +++ b/licenses/README.md @@ -0,0 +1,16 @@ +# Native source attribution + +The Android host was adapted from [Proteus](https://github.com/foxbiz/proteus), +revision `e350d77e0b60c361d93853b23858828200770898`. +The [native source inventory](native-provenance.json) records upstream plugin +identities and versions. These names document source ownership and licensing; +they are not build dependencies or runtime registration. + +Apache notices and original license texts are retained in this directory. +Adaptations replace runtime imports, callback handling and native service +registration with the app-owned bridge. Java packages and classes have been +renamed to match their current source locations. + +The HTTP MIT license is preserved from the [upstream license](https://github.com/silkimen/cordova-plugin-advanced-http/blob/master/LICENSE). + +The iOS Alpine runtime has separate GPL licensing and retained upstream sources. See [the runtime provenance](../platforms/ios/Alpine/README.md) and its GPL and libarchive license texts. diff --git a/src/plugins/admob/LICENSE b/licenses/admob-LICENSE similarity index 100% rename from src/plugins/admob/LICENSE rename to licenses/admob-LICENSE diff --git a/licenses/advanced-http-LICENSE b/licenses/advanced-http-LICENSE new file mode 100644 index 0000000000..862ae69e59 --- /dev/null +++ b/licenses/advanced-http-LICENSE @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) 2019 Sefa Ilkimen +Copyright (c) 2017 Mobisys GmbH +Copyright (c) 2014 Wymsee, Inc + +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/src/plugins/cordova-plugin-buildinfo/LICENSE b/licenses/buildinfo-LICENSE similarity index 100% rename from src/plugins/cordova-plugin-buildinfo/LICENSE rename to licenses/buildinfo-LICENSE diff --git a/licenses/clipboard-LICENSE b/licenses/clipboard-LICENSE new file mode 100644 index 0000000000..9593150df3 --- /dev/null +++ b/licenses/clipboard-LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Verso Solutions LLC + +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/licenses/clipboard/LICENSE b/licenses/clipboard/LICENSE new file mode 100644 index 0000000000..9593150df3 --- /dev/null +++ b/licenses/clipboard/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Verso Solutions LLC + +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/licenses/device-LICENSE b/licenses/device-LICENSE new file mode 100644 index 0000000000..7a4a3ea242 --- /dev/null +++ b/licenses/device-LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/licenses/device-NOTICE b/licenses/device-NOTICE new file mode 100644 index 0000000000..8ec56a5241 --- /dev/null +++ b/licenses/device-NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/licenses/device/LICENSE b/licenses/device/LICENSE new file mode 100644 index 0000000000..7a4a3ea242 --- /dev/null +++ b/licenses/device/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/licenses/device/NOTICE b/licenses/device/NOTICE new file mode 100644 index 0000000000..8ec56a5241 --- /dev/null +++ b/licenses/device/NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/licenses/file-LICENSE b/licenses/file-LICENSE new file mode 100644 index 0000000000..7a4a3ea242 --- /dev/null +++ b/licenses/file-LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/licenses/file-NOTICE b/licenses/file-NOTICE new file mode 100644 index 0000000000..8ec56a5241 --- /dev/null +++ b/licenses/file-NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/licenses/file/LICENSE b/licenses/file/LICENSE new file mode 100644 index 0000000000..7a4a3ea242 --- /dev/null +++ b/licenses/file/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/licenses/file/NOTICE b/licenses/file/NOTICE new file mode 100644 index 0000000000..8ec56a5241 --- /dev/null +++ b/licenses/file/NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/licenses/ftp-LICENSE.md b/licenses/ftp-LICENSE.md new file mode 100644 index 0000000000..b14abd6c6c --- /dev/null +++ b/licenses/ftp-LICENSE.md @@ -0,0 +1,3 @@ +- GoldRaccoon is under [original author's license](https://github.com/albertodebortoli/GoldRaccoon/blob/master/LICENSE.markdown) +- ftp4j is under [LGPL](http://opensource.org/licenses/LGPL-2.1) +- All other codes (written by me) are under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) diff --git a/licenses/native-provenance.json b/licenses/native-provenance.json new file mode 100644 index 0000000000..117018d6fd --- /dev/null +++ b/licenses/native-provenance.json @@ -0,0 +1,107 @@ +[ + { + "module": "admob", + "id": "admob-plus-cordova", + "version": "2.0.0-alpha.19" + }, + { + "module": "auth", + "id": "com.foxdebug.acode.rk.auth", + "version": "1.0.0" + }, + { + "module": "browser", + "id": "cordova-plugin-browser", + "version": "1.0.0" + }, + { + "module": "clipboard", + "id": "cordova-clipboard", + "version": "1.3.0" + }, + { + "module": "cordova-plugin-advanced-http", + "id": "cordova-plugin-advanced-http", + "version": "3.3.1" + }, + { + "module": "cordova-plugin-buildinfo", + "id": "cordova-plugin-buildinfo", + "version": "4.0.0" + }, + { + "module": "cordova-plugin-crashhandler", + "id": "cordova-plugin-crashhandler", + "version": "1.0.0" + }, + { + "module": "custom-tabs", + "id": "com.foxdebug.acode.rk.customtabs", + "version": "1.0.0" + }, + { + "module": "device", + "id": "cordova-plugin-device", + "version": "2.1.0" + }, + { + "module": "file", + "id": "cordova-plugin-file", + "version": "8.1.3" + }, + { + "module": "ftp", + "id": "cordova-plugin-ftp", + "version": "1.1.1" + }, + { + "module": "iap", + "id": "cordova-plugin-iap", + "version": "0.0.1" + }, + { + "module": "pluginContext", + "id": "com.foxdebug.acode.rk.plugin.plugincontext", + "version": "1.0.0" + }, + { + "module": "proot", + "id": "com.foxdebug.acode.rk.exec.proot", + "version": "1.0.0" + }, + { + "module": "sdcard", + "id": "cordova-plugin-sdcard", + "version": "0.0.1" + }, + { + "module": "server", + "id": "cordova-plugin-server", + "version": "1.1.1" + }, + { + "module": "sftp", + "id": "cordova-plugin-sftp", + "version": "1.1.1" + }, + { + "module": "system", + "id": "cordova-plugin-system", + "version": "0.0.1" + }, + { + "module": "terminal", + "id": "com.foxdebug.acode.rk.exec.terminal", + "version": "1.0.0" + }, + { + "module": "websocket", + "id": "cordova-plugin-websocket", + "version": "0.0.1" + }, + { + "module": "webview", + "id": "cordova-plugin-acode-webview", + "version": "1.0.0" + } +] diff --git a/licenses/native-runtime-LICENSE b/licenses/native-runtime-LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/licenses/native-runtime-LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/native-runtime-NOTICE b/licenses/native-runtime-NOTICE new file mode 100644 index 0000000000..2ce6eeece1 --- /dev/null +++ b/licenses/native-runtime-NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2015-2020 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/licenses/sftp-LICENSE.md b/licenses/sftp-LICENSE.md new file mode 100644 index 0000000000..b14abd6c6c --- /dev/null +++ b/licenses/sftp-LICENSE.md @@ -0,0 +1,3 @@ +- GoldRaccoon is under [original author's license](https://github.com/albertodebortoli/GoldRaccoon/blob/master/LICENSE.markdown) +- ftp4j is under [LGPL](http://opensource.org/licenses/LGPL-2.1) +- All other codes (written by me) are under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) diff --git a/package-lock.json b/package-lock.json index b30ed54174..290845e7d7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { - "name": "com.foxdebug.acode", - "version": "1.13.5", + "name": "acode-app", + "version": "1.13.6", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "com.foxdebug.acode", - "version": "1.13.5", + "name": "acode-app", + "version": "1.13.6", "license": "MIT", "dependencies": { "@acode.app/canvas-view": "^0.0.11", @@ -59,7 +59,6 @@ "acorn": "^8.18.0", "autosize": "^6.0.1", "codemirror": "^6.0.2", - "cordova": "13.0.0", "core-js": "^3.50.0", "dayjs": "^1.11.23", "dompurify": "^3.4.14", @@ -68,7 +67,7 @@ "filesize": "^11.0.22", "html-tag-js": "^2.4.16", "jszip": "^3.10.1", - "katex": "^0.16.47", + "katex": "^0.19.0", "markdown-it": "^14.3.0", "markdown-it-anchor": "^9.2.1", "markdown-it-emoji": "^3.1.0", @@ -81,6 +80,7 @@ "mustache": "^4.2.0", "pele": "^1.10.0", "picomatch": "^4.0.7", + "tough-cookie": "^6.0.2", "url-parse": "^1.5.10", "vanilla-picker": "^2.12.3", "vscode-css-languageservice": "6.3.10", @@ -104,34 +104,11 @@ "@rspack/cli": "^2.2.0", "@rspack/core": "^2.2.0", "@types/ace": "^0.0.52", - "@types/cordova": "^11.0.3", "@types/url-parse": "^1.4.11", "autoprefixer": "^10.5.4", "babel-loader": "^10.1.1", "chokidar": "^4.0.3", - "com.foxdebug.acode.rk.auth": "file:src/plugins/auth", - "com.foxdebug.acode.rk.customtabs": "file:src/plugins/custom-tabs", - "com.foxdebug.acode.rk.exec.proot": "file:src/plugins/proot", - "com.foxdebug.acode.rk.exec.terminal": "file:src/plugins/terminal", - "com.foxdebug.acode.rk.plugin.plugincontext": "file:src/plugins/pluginContext", - "cordova-android": "^15.1.0", - "cordova-clipboard": "^1.3.0", - "cordova-plugin-acode-webview": "file:src/plugins/webview", - "cordova-plugin-advanced-http": "file:src/plugins/cordova-plugin-advanced-http", - "cordova-plugin-browser": "file:src/plugins/browser", - "cordova-plugin-buildinfo": "file:src/plugins/cordova-plugin-buildinfo", - "cordova-plugin-crashhandler": "file:src/plugins/cordova-plugin-crashhandler", - "cordova-plugin-device": "^2.1.0", - "cordova-plugin-file": "^8.1.3", - "cordova-plugin-ftp": "file:src/plugins/ftp", - "cordova-plugin-iap": "file:src/plugins/iap", - "cordova-plugin-sdcard": "file:src/plugins/sdcard", - "cordova-plugin-server": "file:src/plugins/server", - "cordova-plugin-sftp": "file:src/plugins/sftp", - "cordova-plugin-system": "file:src/plugins/system", - "cordova-plugin-websocket": "file:src/plugins/websocket", "css-loader": "^7.1.4", - "elementtree": "^0.1.7", "happy-dom": "^20.11.6", "mini-css-extract-plugin": "^2.10.2", "path-browserify": "^1.0.1", @@ -171,6 +148,18 @@ "typescript-language-server": "^4.3.4" } }, + "codemirror-lsp-client/node_modules/marked": { + "version": "15.0.12", + "resolved": "https://registry.npmjs.org/marked/-/marked-15.0.12.tgz", + "integrity": "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/@acode.app/canvas-view": { "version": "0.0.11", "resolved": "https://registry.npmjs.org/@acode.app/canvas-view/-/canvas-view-0.0.11.tgz", @@ -194,24 +183,23 @@ } }, "node_modules/@babel/code-frame": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", - "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.6.tgz", + "integrity": "sha512-uMHhvmDmwFiLuiozaoRYTZHqMFuu3fem/X9JY78lohAuLoh8LSGGC8JqUzo2cVuBsBxkjMZNk56CE7ock8Xxkw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^7.29.7", - "js-tokens": "^4.0.0", - "picocolors": "^1.1.1" + "@babel/helper-validator-identifier": "^8.0.6", + "js-tokens": "^10.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/compat-data": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-8.0.0.tgz", - "integrity": "sha512-DOjnob/cXOUgDOozCDeq/aK2p5y8dUIVdf6tNhEV1HQRd6I8aQ4f4fbtHRVEvb6lP3BGomrKHiS8ICAASSVQSw==", + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-8.0.5.tgz", + "integrity": "sha512-YLsYoQMvL8l8WrGpN3Zj7O1wK5LEBN+cQtux7BcuHyxIXve724XG+zuJ1n3U1cUweRtTzQOA4IHbuQw3N34SZw==", "dev": true, "license": "MIT", "engines": { @@ -219,20 +207,20 @@ } }, "node_modules/@babel/core": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-8.0.1.tgz", - "integrity": "sha512-5FgxM4dLQpMJHSiVATk8foW263dVHQHBVpXYiimNECVWG01f4nFyEbQixeT6Mwvg7TayREJ2gpKl3o2RoMdnqw==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-8.0.6.tgz", + "integrity": "sha512-5zwYt1V4ji3mXKKRIAkohSJ29WepxNwxQi+7y7P5AcVPh1dcxnZBU2cfxHnPwS+u9+lZnXPsv30TQaF2xg+Tfg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/generator": "^8.0.0", - "@babel/helper-compilation-targets": "^8.0.0", - "@babel/helpers": "^8.0.0", - "@babel/parser": "^8.0.0", + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.0.6", + "@babel/helper-compilation-targets": "^8.0.6", + "@babel/helpers": "^8.0.5", + "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", - "@babel/traverse": "^8.0.0", - "@babel/types": "^8.0.0", + "@babel/traverse": "^8.0.6", + "@babel/types": "^8.0.6", "@types/gensync": "^1.0.5", "convert-source-map": "^2.0.0", "empathic": "^2.0.1", @@ -240,7 +228,7 @@ "import-meta-resolve": "^4.2.0", "json5": "^2.2.3", "obug": "^2.1.1", - "semver": "^7.7.3" + "verkit": "^0.3.2" }, "engines": { "node": "^22.18.0 || >=24.11.0" @@ -250,31 +238,17 @@ "url": "https://opencollective.com/babel" } }, - "node_modules/@babel/core/node_modules/@babel/code-frame": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.0.tgz", - "integrity": "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-validator-identifier": "^8.0.0", - "js-tokens": "^10.0.0" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, "node_modules/@babel/core/node_modules/@babel/generator": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.0.tgz", - "integrity": "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.6.tgz", + "integrity": "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", + "@babel/parser": "^8.0.6", + "@babel/types": "^8.0.6", + "@jridgewell/gen-mapping": "0.4.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" }, @@ -282,44 +256,14 @@ "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/core/node_modules/@babel/helper-globals": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-8.0.0.tgz", - "integrity": "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, - "node_modules/@babel/core/node_modules/@babel/helper-string-parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, - "node_modules/@babel/core/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, "node_modules/@babel/core/node_modules/@babel/parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.0.tgz", - "integrity": "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.6.tgz", + "integrity": "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^8.0.0" + "@babel/types": "^8.0.6" }, "bin": { "parser": "bin/babel-parser.js" @@ -328,72 +272,34 @@ "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/core/node_modules/@babel/template": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-8.0.0.tgz", - "integrity": "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, "node_modules/@babel/core/node_modules/@babel/traverse": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.0.tgz", - "integrity": "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.6.tgz", + "integrity": "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/generator": "^8.0.0", - "@babel/helper-globals": "^8.0.0", - "@babel/parser": "^8.0.0", + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.0.6", + "@babel/helper-globals": "^8.0.6", + "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", - "@babel/types": "^8.0.0", + "@babel/types": "^8.0.6", "obug": "^2.1.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/core/node_modules/@babel/types": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.0.tgz", - "integrity": "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==", + "node_modules/@babel/core/node_modules/@jridgewell/gen-mapping": { + "version": "0.4.0-beta.0", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.4.0-beta.0.tgz", + "integrity": "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, - "node_modules/@babel/core/node_modules/js-tokens": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", - "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@babel/core/node_modules/semver": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.4.tgz", - "integrity": "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" + "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.24" } }, "node_modules/@babel/generator": { @@ -413,97 +319,84 @@ "node": ">=6.9.0" } }, - "node_modules/@babel/helper-annotate-as-pure": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-8.0.0.tgz", - "integrity": "sha512-NSpMkMsvvZqzThJ0p1B02cbtA2ObEyfBvq950bmNkyxsxvcxwhvvCB036rKhlEnuBBo30bOrk13u3FzlKSoRrw==", + "node_modules/@babel/generator/node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", "dev": true, "license": "MIT", - "dependencies": { - "@babel/types": "^8.0.0" - }, "engines": { - "node": "^22.18.0 || >=24.11.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/helper-annotate-as-pure/node_modules/@babel/helper-string-parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", + "node_modules/@babel/generator/node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", "dev": true, "license": "MIT", "engines": { - "node": "^22.18.0 || >=24.11.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/helper-annotate-as-pure/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", + "node_modules/@babel/generator/node_modules/@babel/types": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", + "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, "engines": { - "node": "^22.18.0 || >=24.11.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/helper-annotate-as-pure/node_modules/@babel/types": { + "node_modules/@babel/helper-annotate-as-pure": { "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.0.tgz", - "integrity": "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==", + "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-8.0.0.tgz", + "integrity": "sha512-NSpMkMsvvZqzThJ0p1B02cbtA2ObEyfBvq950bmNkyxsxvcxwhvvCB036rKhlEnuBBo30bOrk13u3FzlKSoRrw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0" + "@babel/types": "^8.0.0" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/helper-compilation-targets": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-8.0.0.tgz", - "integrity": "sha512-JwculLABZvyPvyLBpwU/E/IbH2uM3mnxNtIJpxnIfb24y1PrdVxK5Dqjle4DpgqpGRnwgC7G8IkzPdSXZrO1Ew==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-8.0.6.tgz", + "integrity": "sha512-HTrtZ4+iA0+kzdbCgvdSk1U4pEl3BvpGnlUbualCGNbrVhhQvhgBzurTUmqpWyvyHbWYWaIfdx2mOlL9LJjsew==", "dev": true, "license": "MIT", "dependencies": { - "@babel/compat-data": "^8.0.0", + "@babel/compat-data": "^8.0.5", "@babel/helper-validator-option": "^8.0.0", "browserslist": "^4.24.0", - "lru-cache": "^11.0.0", - "semver": "^7.7.3" + "flru": "1.0.2", + "verkit": "^0.3.2" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-compilation-targets/node_modules/semver": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.4.tgz", - "integrity": "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/@babel/helper-create-class-features-plugin": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-8.0.1.tgz", - "integrity": "sha512-++t3ZktzlLmASAxIlxeXQK9Z2YwUafYGYcvGBFevqOqt16HozVHStUoQvWD09fzAZOb/uJGpUTBuGK41AJAuOA==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-8.0.6.tgz", + "integrity": "sha512-Hy7wG2Pk1LnAkFMq0CbBk789XMTYVzYGxR7tKgk+TOpZckQRME3Tdou4mMT/8DFjJFxFZ8R6UsS4DR/duBKlVA==", "dev": true, "license": "MIT", "dependencies": { "@babel/helper-annotate-as-pure": "^8.0.0", - "@babel/helper-member-expression-to-functions": "^8.0.0", + "@babel/helper-member-expression-to-functions": "^8.0.5", "@babel/helper-optimise-call-expression": "^8.0.0", "@babel/helper-replace-supers": "^8.0.1", "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0", - "@babel/traverse": "^8.0.0", - "semver": "^7.7.3" + "@babel/traverse": "^8.0.6", + "verkit": "^0.3.2" }, "engines": { "node": "^22.18.0 || >=24.11.0" @@ -512,31 +405,17 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-create-class-features-plugin/node_modules/@babel/code-frame": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.0.tgz", - "integrity": "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-validator-identifier": "^8.0.0", - "js-tokens": "^10.0.0" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, "node_modules/@babel/helper-create-class-features-plugin/node_modules/@babel/generator": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.0.tgz", - "integrity": "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.6.tgz", + "integrity": "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", + "@babel/parser": "^8.0.6", + "@babel/types": "^8.0.6", + "@jridgewell/gen-mapping": "0.4.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" }, @@ -544,44 +423,14 @@ "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-create-class-features-plugin/node_modules/@babel/helper-globals": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-8.0.0.tgz", - "integrity": "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, - "node_modules/@babel/helper-create-class-features-plugin/node_modules/@babel/helper-string-parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, - "node_modules/@babel/helper-create-class-features-plugin/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, "node_modules/@babel/helper-create-class-features-plugin/node_modules/@babel/parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.0.tgz", - "integrity": "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.6.tgz", + "integrity": "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^8.0.0" + "@babel/types": "^8.0.6" }, "bin": { "parser": "bin/babel-parser.js" @@ -590,84 +439,46 @@ "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-create-class-features-plugin/node_modules/@babel/template": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-8.0.0.tgz", - "integrity": "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, "node_modules/@babel/helper-create-class-features-plugin/node_modules/@babel/traverse": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.0.tgz", - "integrity": "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.6.tgz", + "integrity": "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/generator": "^8.0.0", - "@babel/helper-globals": "^8.0.0", - "@babel/parser": "^8.0.0", + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.0.6", + "@babel/helper-globals": "^8.0.6", + "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", - "@babel/types": "^8.0.0", + "@babel/types": "^8.0.6", "obug": "^2.1.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-create-class-features-plugin/node_modules/@babel/types": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.0.tgz", - "integrity": "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==", + "node_modules/@babel/helper-create-class-features-plugin/node_modules/@jridgewell/gen-mapping": { + "version": "0.4.0-beta.0", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.4.0-beta.0.tgz", + "integrity": "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, - "node_modules/@babel/helper-create-class-features-plugin/node_modules/js-tokens": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", - "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@babel/helper-create-class-features-plugin/node_modules/semver": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.4.tgz", - "integrity": "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" + "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.24" } }, "node_modules/@babel/helper-create-regexp-features-plugin": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-8.0.1.tgz", - "integrity": "sha512-PydTbcVTiIfVweHMeY1u3MslaD/ZzvnaTNhJp+7ghofelLWshF66Ckc/ZsjStfvRQIKQ4uVG0yEJucyDtyrWgw==", + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-8.0.5.tgz", + "integrity": "sha512-TWnIgw21pAv/FbBKB8ks26DMxQ+A3aBdi1HUBp+QhqSE8QdOqJgSK/FEvdMYPTZcHBBJPZ5pN6DDKmC5ZYPJbg==", "dev": true, "license": "MIT", "dependencies": { "@babel/helper-annotate-as-pure": "^8.0.0", "regexpu-core": "^6.3.1", - "semver": "^7.7.3" + "verkit": "^0.3.2" }, "engines": { "node": "^22.18.0 || >=24.11.0" @@ -676,19 +487,6 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-create-regexp-features-plugin/node_modules/semver": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.4.tgz", - "integrity": "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/@babel/helper-define-polyfill-provider": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-1.0.0.tgz", @@ -708,318 +506,370 @@ } }, "node_modules/@babel/helper-globals": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", - "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-8.0.6.tgz", + "integrity": "sha512-OdnA/N52LhzFpeUuVz5YGuSWjc7TPHiFmVYZbPlSgExocO2GwbxVpSni9MVs5wwW+wZ4kPuwBEBN9pIPDYz1mA==", "dev": true, "license": "MIT", "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/helper-member-expression-to-functions": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-8.0.0.tgz", - "integrity": "sha512-xkXrMbtk87Gk7+oKBVmBc6EORg/Qwx++AHESldmHkpvG8wgccdhJJFwrzqlF382Fk8wfXhJHWE/g/43QvEGNPQ==", + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-8.0.5.tgz", + "integrity": "sha512-GLe05QD98BkNFTkjaqeqF9QSRoHLKrrB4tpoplyQuuPrQJ72rtmkM4wvqJLX/sjZPqkbK5MUYSsuUTqdJoOVjA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/traverse": "^8.0.0", - "@babel/types": "^8.0.0" + "@babel/traverse": "^8.0.5", + "@babel/types": "^8.0.5" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-member-expression-to-functions/node_modules/@babel/code-frame": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.0.tgz", - "integrity": "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==", + "node_modules/@babel/helper-member-expression-to-functions/node_modules/@babel/generator": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.6.tgz", + "integrity": "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^8.0.0", - "js-tokens": "^10.0.0" - }, + "@babel/parser": "^8.0.6", + "@babel/types": "^8.0.6", + "@jridgewell/gen-mapping": "0.4.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.31", + "@types/jsesc": "^2.5.0", + "jsesc": "^3.0.2" + }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-member-expression-to-functions/node_modules/@babel/generator": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.0.tgz", - "integrity": "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g==", + "node_modules/@babel/helper-member-expression-to-functions/node_modules/@babel/parser": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.6.tgz", + "integrity": "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "@types/jsesc": "^2.5.0", - "jsesc": "^3.0.2" + "@babel/types": "^8.0.6" + }, + "bin": { + "parser": "bin/babel-parser.js" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-member-expression-to-functions/node_modules/@babel/helper-globals": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-8.0.0.tgz", - "integrity": "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw==", + "node_modules/@babel/helper-member-expression-to-functions/node_modules/@babel/traverse": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.6.tgz", + "integrity": "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.0.6", + "@babel/helper-globals": "^8.0.6", + "@babel/parser": "^8.0.6", + "@babel/template": "^8.0.0", + "@babel/types": "^8.0.6", + "obug": "^2.1.1" + }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-member-expression-to-functions/node_modules/@babel/helper-string-parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", + "node_modules/@babel/helper-member-expression-to-functions/node_modules/@jridgewell/gen-mapping": { + "version": "0.4.0-beta.0", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.4.0-beta.0.tgz", + "integrity": "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w==", "dev": true, "license": "MIT", - "engines": { - "node": "^22.18.0 || >=24.11.0" + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.24" } }, - "node_modules/@babel/helper-member-expression-to-functions/node_modules/@babel/helper-validator-identifier": { + "node_modules/@babel/helper-module-imports": { "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-8.0.0.tgz", + "integrity": "sha512-NZ7mSS93o4ndX4KrbD7W8Sf3QT8Qe24PrnFyUcuOPDzK6faqDFKjY9RG7he7+I7FdiQ4llpnosFqzrXa+Vy3Ew==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/traverse": "^8.0.0", + "@babel/types": "^8.0.0" + }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-member-expression-to-functions/node_modules/@babel/parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.0.tgz", - "integrity": "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ==", + "node_modules/@babel/helper-module-imports/node_modules/@babel/generator": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.6.tgz", + "integrity": "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^8.0.0" - }, - "bin": { - "parser": "bin/babel-parser.js" + "@babel/parser": "^8.0.6", + "@babel/types": "^8.0.6", + "@jridgewell/gen-mapping": "0.4.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.31", + "@types/jsesc": "^2.5.0", + "jsesc": "^3.0.2" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-member-expression-to-functions/node_modules/@babel/template": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-8.0.0.tgz", - "integrity": "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==", + "node_modules/@babel/helper-module-imports/node_modules/@babel/parser": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.6.tgz", + "integrity": "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0" + "@babel/types": "^8.0.6" + }, + "bin": { + "parser": "bin/babel-parser.js" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-member-expression-to-functions/node_modules/@babel/traverse": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.0.tgz", - "integrity": "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw==", + "node_modules/@babel/helper-module-imports/node_modules/@babel/traverse": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.6.tgz", + "integrity": "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/generator": "^8.0.0", - "@babel/helper-globals": "^8.0.0", - "@babel/parser": "^8.0.0", + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.0.6", + "@babel/helper-globals": "^8.0.6", + "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", - "@babel/types": "^8.0.0", + "@babel/types": "^8.0.6", "obug": "^2.1.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-member-expression-to-functions/node_modules/@babel/types": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.0.tgz", - "integrity": "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==", + "node_modules/@babel/helper-module-imports/node_modules/@jridgewell/gen-mapping": { + "version": "0.4.0-beta.0", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.4.0-beta.0.tgz", + "integrity": "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0" + "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-8.0.6.tgz", + "integrity": "sha512-YUi+3X0cb0v97xKhuqkLdrwQtP6XXv1eVbhLRCFyMwG481UskbMQk4mjH7K/Jg3oJ1KLskvFwwq4kF/QnABkWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^8.0.0", + "@babel/helper-validator-identifier": "^8.0.6", + "@babel/traverse": "^8.0.6" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-member-expression-to-functions/node_modules/js-tokens": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", - "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@babel/helper-module-imports": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-8.0.0.tgz", - "integrity": "sha512-NZ7mSS93o4ndX4KrbD7W8Sf3QT8Qe24PrnFyUcuOPDzK6faqDFKjY9RG7he7+I7FdiQ4llpnosFqzrXa+Vy3Ew==", + "node_modules/@babel/helper-module-transforms/node_modules/@babel/generator": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.6.tgz", + "integrity": "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng==", "dev": true, "license": "MIT", "dependencies": { - "@babel/traverse": "^8.0.0", - "@babel/types": "^8.0.0" + "@babel/parser": "^8.0.6", + "@babel/types": "^8.0.6", + "@jridgewell/gen-mapping": "0.4.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.31", + "@types/jsesc": "^2.5.0", + "jsesc": "^3.0.2" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-imports/node_modules/@babel/code-frame": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.0.tgz", - "integrity": "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==", + "node_modules/@babel/helper-module-transforms/node_modules/@babel/parser": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.6.tgz", + "integrity": "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^8.0.0", - "js-tokens": "^10.0.0" + "@babel/types": "^8.0.6" + }, + "bin": { + "parser": "bin/babel-parser.js" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-imports/node_modules/@babel/generator": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.0.tgz", - "integrity": "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g==", + "node_modules/@babel/helper-module-transforms/node_modules/@babel/traverse": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.6.tgz", + "integrity": "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "@types/jsesc": "^2.5.0", - "jsesc": "^3.0.2" + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.0.6", + "@babel/helper-globals": "^8.0.6", + "@babel/parser": "^8.0.6", + "@babel/template": "^8.0.0", + "@babel/types": "^8.0.6", + "obug": "^2.1.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-imports/node_modules/@babel/helper-globals": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-8.0.0.tgz", - "integrity": "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw==", + "node_modules/@babel/helper-module-transforms/node_modules/@jridgewell/gen-mapping": { + "version": "0.4.0-beta.0", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.4.0-beta.0.tgz", + "integrity": "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w==", "dev": true, "license": "MIT", - "engines": { - "node": "^22.18.0 || >=24.11.0" + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.24" } }, - "node_modules/@babel/helper-module-imports/node_modules/@babel/helper-string-parser": { + "node_modules/@babel/helper-optimise-call-expression": { "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-8.0.0.tgz", + "integrity": "sha512-3W6satvtPuCUkUx63S2jMoW9EQNYkADgs1HTfufmL7gCmAulHMKupA/12WNz4A0GMMFn/YnWWwqOT9IZrJHQjg==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/types": "^8.0.0" + }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-imports/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", + "node_modules/@babel/helper-plugin-utils": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-8.0.1.tgz", + "integrity": "sha512-3PKFgjTyPlhFhorfP+SjKQxLViIL++zWjFOO4hGriYU+Bsm983DxEM1JmDRJVWXV0O9npu+xXRqz7Pbd3mh70g==", "dev": true, "license": "MIT", "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-module-imports/node_modules/@babel/parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.0.tgz", - "integrity": "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ==", + "node_modules/@babel/helper-remap-async-to-generator": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-8.0.1.tgz", + "integrity": "sha512-baAKuLEMmu6BCSY3tuiU7qglM1qOZt6F1SrFScA241oNqksxkxfEZEKztlGRmoVns9AQ5UgArH7RsUEjxWnzgQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^8.0.0" - }, - "bin": { - "parser": "bin/babel-parser.js" + "@babel/helper-annotate-as-pure": "^8.0.0", + "@babel/helper-wrap-function": "^8.0.0", + "@babel/traverse": "^8.0.0" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-module-imports/node_modules/@babel/template": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-8.0.0.tgz", - "integrity": "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==", + "node_modules/@babel/helper-remap-async-to-generator/node_modules/@babel/generator": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.6.tgz", + "integrity": "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0" + "@babel/parser": "^8.0.6", + "@babel/types": "^8.0.6", + "@jridgewell/gen-mapping": "0.4.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.31", + "@types/jsesc": "^2.5.0", + "jsesc": "^3.0.2" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-imports/node_modules/@babel/traverse": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.0.tgz", - "integrity": "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw==", + "node_modules/@babel/helper-remap-async-to-generator/node_modules/@babel/parser": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.6.tgz", + "integrity": "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/generator": "^8.0.0", - "@babel/helper-globals": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/template": "^8.0.0", - "@babel/types": "^8.0.0", - "obug": "^2.1.1" + "@babel/types": "^8.0.6" + }, + "bin": { + "parser": "bin/babel-parser.js" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-imports/node_modules/@babel/types": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.0.tgz", - "integrity": "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==", + "node_modules/@babel/helper-remap-async-to-generator/node_modules/@babel/traverse": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.6.tgz", + "integrity": "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0" + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.0.6", + "@babel/helper-globals": "^8.0.6", + "@babel/parser": "^8.0.6", + "@babel/template": "^8.0.0", + "@babel/types": "^8.0.6", + "obug": "^2.1.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-imports/node_modules/js-tokens": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", - "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", + "node_modules/@babel/helper-remap-async-to-generator/node_modules/@jridgewell/gen-mapping": { + "version": "0.4.0-beta.0", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.4.0-beta.0.tgz", + "integrity": "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w==", "dev": true, - "license": "MIT" + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.24" + } }, - "node_modules/@babel/helper-module-transforms": { + "node_modules/@babel/helper-replace-supers": { "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-8.0.1.tgz", - "integrity": "sha512-UgAhl1kqiW5ciE0yCXqqvnb4H2n3IELJ7lIIQRezwDPilPEZX5i+Rvbja9MFTkwUn2biEiSMeV31aUzR4Lwakw==", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-8.0.1.tgz", + "integrity": "sha512-B1SZADIcy3tmH8CmWvj4SHi/oAPom4UL3uknTc2QRNsPVLFk/sPnZvQL/8kj7Y5omvjMqie0vklvs6XM4OLW5Q==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-module-imports": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0", + "@babel/helper-member-expression-to-functions": "^8.0.0", + "@babel/helper-optimise-call-expression": "^8.0.0", "@babel/traverse": "^8.0.0" }, "engines": { @@ -1029,360 +879,378 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-module-transforms/node_modules/@babel/code-frame": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.0.tgz", - "integrity": "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==", + "node_modules/@babel/helper-replace-supers/node_modules/@babel/generator": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.6.tgz", + "integrity": "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^8.0.0", - "js-tokens": "^10.0.0" + "@babel/parser": "^8.0.6", + "@babel/types": "^8.0.6", + "@jridgewell/gen-mapping": "0.4.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.31", + "@types/jsesc": "^2.5.0", + "jsesc": "^3.0.2" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-transforms/node_modules/@babel/generator": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.0.tgz", - "integrity": "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g==", + "node_modules/@babel/helper-replace-supers/node_modules/@babel/parser": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.6.tgz", + "integrity": "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "@types/jsesc": "^2.5.0", - "jsesc": "^3.0.2" + "@babel/types": "^8.0.6" + }, + "bin": { + "parser": "bin/babel-parser.js" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-transforms/node_modules/@babel/helper-globals": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-8.0.0.tgz", - "integrity": "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw==", + "node_modules/@babel/helper-replace-supers/node_modules/@babel/traverse": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.6.tgz", + "integrity": "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.0.6", + "@babel/helper-globals": "^8.0.6", + "@babel/parser": "^8.0.6", + "@babel/template": "^8.0.0", + "@babel/types": "^8.0.6", + "obug": "^2.1.1" + }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-transforms/node_modules/@babel/helper-string-parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", + "node_modules/@babel/helper-replace-supers/node_modules/@jridgewell/gen-mapping": { + "version": "0.4.0-beta.0", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.4.0-beta.0.tgz", + "integrity": "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w==", "dev": true, "license": "MIT", - "engines": { - "node": "^22.18.0 || >=24.11.0" + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.24" } }, - "node_modules/@babel/helper-module-transforms/node_modules/@babel/helper-validator-identifier": { + "node_modules/@babel/helper-skip-transparent-expression-wrappers": { "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", + "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-8.0.0.tgz", + "integrity": "sha512-xmCA9kP3IhySsqhzwIdWGlDN/1A4cCKNBO/uwZx/3YzmDoMePwno2Q5/Bq0q+tYaKbeF940YiKV/kaW8Mzvpjw==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/traverse": "^8.0.0", + "@babel/types": "^8.0.0" + }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-transforms/node_modules/@babel/parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.0.tgz", - "integrity": "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ==", + "node_modules/@babel/helper-skip-transparent-expression-wrappers/node_modules/@babel/generator": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.6.tgz", + "integrity": "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^8.0.0" - }, - "bin": { - "parser": "bin/babel-parser.js" + "@babel/parser": "^8.0.6", + "@babel/types": "^8.0.6", + "@jridgewell/gen-mapping": "0.4.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.31", + "@types/jsesc": "^2.5.0", + "jsesc": "^3.0.2" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-transforms/node_modules/@babel/template": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-8.0.0.tgz", - "integrity": "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==", + "node_modules/@babel/helper-skip-transparent-expression-wrappers/node_modules/@babel/parser": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.6.tgz", + "integrity": "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0" + "@babel/types": "^8.0.6" + }, + "bin": { + "parser": "bin/babel-parser.js" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-transforms/node_modules/@babel/traverse": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.0.tgz", - "integrity": "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw==", + "node_modules/@babel/helper-skip-transparent-expression-wrappers/node_modules/@babel/traverse": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.6.tgz", + "integrity": "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/generator": "^8.0.0", - "@babel/helper-globals": "^8.0.0", - "@babel/parser": "^8.0.0", + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.0.6", + "@babel/helper-globals": "^8.0.6", + "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", - "@babel/types": "^8.0.0", + "@babel/types": "^8.0.6", "obug": "^2.1.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-transforms/node_modules/@babel/types": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.0.tgz", - "integrity": "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==", + "node_modules/@babel/helper-skip-transparent-expression-wrappers/node_modules/@jridgewell/gen-mapping": { + "version": "0.4.0-beta.0", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.4.0-beta.0.tgz", + "integrity": "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0" - }, + "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.6.tgz", + "integrity": "sha512-+6HYEBnsDRZHJtUTAEfMQd0zMDqdFHS7C+5vAsEZqBUr3vEMWOWlHJ0Jz1gS8jJIlCvLsuA6ivmeoqzH936YcA==", + "dev": true, + "license": "MIT", "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-module-transforms/node_modules/js-tokens": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", - "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@babel/helper-optimise-call-expression": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-8.0.0.tgz", - "integrity": "sha512-3W6satvtPuCUkUx63S2jMoW9EQNYkADgs1HTfufmL7gCmAulHMKupA/12WNz4A0GMMFn/YnWWwqOT9IZrJHQjg==", + "node_modules/@babel/helper-validator-identifier": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.6.tgz", + "integrity": "sha512-HYx0YmuchRxRSpnjvcNffnPS8DCauKNmnumIuHG3jnQAVewRA7kfJGwF13ayEpSZs7s4R/oBH4eppuXcAQd5JQ==", "dev": true, "license": "MIT", - "dependencies": { - "@babel/types": "^8.0.0" - }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-optimise-call-expression/node_modules/@babel/helper-string-parser": { + "node_modules/@babel/helper-validator-option": { "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-8.0.0.tgz", + "integrity": "sha512-U4Dybxh4WESWHt5XhBeExi4DrY0/DNK1aHpQbsrQXCUbFHuMweT0TpLEWKvaraV2Y6fS+ZXunsZ8zIuZIgvF2Q==", "dev": true, "license": "MIT", "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-optimise-call-expression/node_modules/@babel/helper-validator-identifier": { + "node_modules/@babel/helper-wrap-function": { "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", + "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-8.0.0.tgz", + "integrity": "sha512-Qpm8+wi5xfDkBfollanwriCcKniFfBmMmaKB01GVM6VGzKXo1fdxosZp04qEr5HM+LKhwr3hG1yRy8+ORsficA==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/template": "^8.0.0", + "@babel/traverse": "^8.0.0", + "@babel/types": "^8.0.0" + }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-optimise-call-expression/node_modules/@babel/types": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.0.tgz", - "integrity": "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==", + "node_modules/@babel/helper-wrap-function/node_modules/@babel/generator": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.6.tgz", + "integrity": "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0" + "@babel/parser": "^8.0.6", + "@babel/types": "^8.0.6", + "@jridgewell/gen-mapping": "0.4.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.31", + "@types/jsesc": "^2.5.0", + "jsesc": "^3.0.2" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-plugin-utils": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-8.0.1.tgz", - "integrity": "sha512-3PKFgjTyPlhFhorfP+SjKQxLViIL++zWjFOO4hGriYU+Bsm983DxEM1JmDRJVWXV0O9npu+xXRqz7Pbd3mh70g==", + "node_modules/@babel/helper-wrap-function/node_modules/@babel/parser": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.6.tgz", + "integrity": "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/types": "^8.0.6" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, "engines": { "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-remap-async-to-generator": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-8.0.1.tgz", - "integrity": "sha512-baAKuLEMmu6BCSY3tuiU7qglM1qOZt6F1SrFScA241oNqksxkxfEZEKztlGRmoVns9AQ5UgArH7RsUEjxWnzgQ==", + "node_modules/@babel/helper-wrap-function/node_modules/@babel/traverse": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.6.tgz", + "integrity": "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-annotate-as-pure": "^8.0.0", - "@babel/helper-wrap-function": "^8.0.0", - "@babel/traverse": "^8.0.0" + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.0.6", + "@babel/helper-globals": "^8.0.6", + "@babel/parser": "^8.0.6", + "@babel/template": "^8.0.0", + "@babel/types": "^8.0.6", + "obug": "^2.1.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-remap-async-to-generator/node_modules/@babel/code-frame": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.0.tgz", - "integrity": "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==", + "node_modules/@babel/helper-wrap-function/node_modules/@jridgewell/gen-mapping": { + "version": "0.4.0-beta.0", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.4.0-beta.0.tgz", + "integrity": "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^8.0.0", - "js-tokens": "^10.0.0" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" + "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.24" } }, - "node_modules/@babel/helper-remap-async-to-generator/node_modules/@babel/generator": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.0.tgz", - "integrity": "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g==", + "node_modules/@babel/helpers": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-8.0.5.tgz", + "integrity": "sha512-fQtPOXjYOYv85PIdwotp2TJGVYOycX0PQq+l844fFAxOULtBy8BVF35GyeueX0r4KvDthqPH5xAI1clQPk/2uA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "@types/jsesc": "^2.5.0", - "jsesc": "^3.0.2" + "@babel/template": "^8.0.0", + "@babel/types": "^8.0.5" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-remap-async-to-generator/node_modules/@babel/helper-globals": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-8.0.0.tgz", - "integrity": "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw==", + "node_modules/@babel/parser": { + "version": "7.29.9", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz", + "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.8" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, "engines": { - "node": "^22.18.0 || >=24.11.0" + "node": ">=6.0.0" } }, - "node_modules/@babel/helper-remap-async-to-generator/node_modules/@babel/helper-string-parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", + "node_modules/@babel/parser/node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", "dev": true, "license": "MIT", "engines": { - "node": "^22.18.0 || >=24.11.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/helper-remap-async-to-generator/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", + "node_modules/@babel/parser/node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", "dev": true, "license": "MIT", "engines": { - "node": "^22.18.0 || >=24.11.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/helper-remap-async-to-generator/node_modules/@babel/parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.0.tgz", - "integrity": "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ==", + "node_modules/@babel/parser/node_modules/@babel/types": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", + "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^8.0.0" - }, - "bin": { - "parser": "bin/babel-parser.js" + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" }, "engines": { - "node": "^22.18.0 || >=24.11.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/helper-remap-async-to-generator/node_modules/@babel/template": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-8.0.0.tgz", - "integrity": "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==", + "node_modules/@babel/plugin-bugfix-firefox-class-in-computed-class-key": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-firefox-class-in-computed-class-key/-/plugin-bugfix-firefox-class-in-computed-class-key-8.0.1.tgz", + "integrity": "sha512-Ytgjjne4RnG3Oig7ik+NfY4ebRY30BPptVkkyu1f72eINJXRM3/bkU++tIc5aPvyLmo4KH20avq0xJ2o+9aEnw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-remap-async-to-generator/node_modules/@babel/traverse": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.0.tgz", - "integrity": "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw==", + "node_modules/@babel/plugin-bugfix-safari-class-field-initializer-scope": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-class-field-initializer-scope/-/plugin-bugfix-safari-class-field-initializer-scope-8.0.1.tgz", + "integrity": "sha512-X7pAMBhuKluA7UfwZNvKN0XVVu/AGeo84Z75eJl85rcb8J2aBzLK92btahM1X5h0oi0QIrbe0qIMA/0+4Buk7w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/generator": "^8.0.0", - "@babel/helper-globals": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/template": "^8.0.0", - "@babel/types": "^8.0.0", - "obug": "^2.1.1" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-remap-async-to-generator/node_modules/@babel/types": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.0.tgz", - "integrity": "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==", + "node_modules/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/-/plugin-bugfix-safari-id-destructuring-collision-in-function-expression-8.0.1.tgz", + "integrity": "sha512-DJviKTxYfH0hFwnMiW4dnPyMGzS3Hrr4zUfXl1zwQ0QiGlGlNYklLoPSYEQr8S7nau0/K7NdQjTh0qbYuyFjCA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-remap-async-to-generator/node_modules/js-tokens": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", - "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@babel/helper-replace-supers": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-8.0.1.tgz", - "integrity": "sha512-B1SZADIcy3tmH8CmWvj4SHi/oAPom4UL3uknTc2QRNsPVLFk/sPnZvQL/8kj7Y5omvjMqie0vklvs6XM4OLW5Q==", + "node_modules/@babel/plugin-bugfix-safari-rest-destructuring-rhs-array": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-rest-destructuring-rhs-array/-/plugin-bugfix-safari-rest-destructuring-rhs-array-8.0.6.tgz", + "integrity": "sha512-vk9CzgaQGcTTBL8F0YNr7LBEka6pXP/I5KcMj0oicGXUquWSNqxiijHGQkHF+s8m910NbGMpn5mU2sFV7AQjBA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-member-expression-to-functions": "^8.0.0", - "@babel/helper-optimise-call-expression": "^8.0.0", - "@babel/traverse": "^8.0.0" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" }, "engines": { "node": "^22.18.0 || >=24.11.0" @@ -1391,584 +1259,658 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-replace-supers/node_modules/@babel/code-frame": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.0.tgz", - "integrity": "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==", + "node_modules/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining/-/plugin-bugfix-v8-spread-parameters-in-optional-chaining-8.0.1.tgz", + "integrity": "sha512-x8bi0LFVD2xkULjfNn+hCMg16yAFHAM9fS/ThSFeYBi+0MP9K6qcY2BZb4urUwC7PYtEy5wPe6TKjOEjXrCGFA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^8.0.0", - "js-tokens": "^10.0.0" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0", + "@babel/plugin-transform-optional-chaining": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-replace-supers/node_modules/@babel/generator": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.0.tgz", - "integrity": "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g==", + "node_modules/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly/-/plugin-bugfix-v8-static-class-fields-redefine-readonly-8.0.1.tgz", + "integrity": "sha512-P8+RN2n7ts2s1vnE+lXdHYf+dhnmcGSen/kWzBsVluT9Sey5AqmcRXYWlHqgQxaNlKTD5YMa1tf5z4d1v8W88w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "@types/jsesc": "^2.5.0", - "jsesc": "^3.0.2" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-replace-supers/node_modules/@babel/helper-globals": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-8.0.0.tgz", - "integrity": "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw==", + "node_modules/@babel/plugin-syntax-typescript": { + "version": "8.0.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-8.0.3.tgz", + "integrity": "sha512-jmTPwps7oSQSZaV1SxkQ3C12UWyufGysGc5OzDpZzvPAIX4mO7dJT3hoqkWVrSImvkcMiknir1iLN1SNV/CZzg==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^8.0.1" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-replace-supers/node_modules/@babel/helper-string-parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", + "node_modules/@babel/plugin-transform-arrow-functions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-8.0.1.tgz", + "integrity": "sha512-o/gr7kRlq3PKLLuYth4udOsrC7geBerti+QtwPeyxMOsEQO1d8kDHqk9r2PtMx2y9i8FG7tzyTerfv1yMLSMsQ==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^8.0.1" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-replace-supers/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", + "node_modules/@babel/plugin-transform-async-generator-functions": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-8.0.6.tgz", + "integrity": "sha512-4K13qZ2TVi9W/NHMg3y0Fguu63cPjGNZT5TpPctIUDdiuIpxo4jwvySGrPWlD6KD00exvpx6Y6l5foFEpnzDcg==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-remap-async-to-generator": "^8.0.1", + "@babel/traverse": "^8.0.6" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-replace-supers/node_modules/@babel/parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.0.tgz", - "integrity": "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ==", + "node_modules/@babel/plugin-transform-async-generator-functions/node_modules/@babel/generator": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.6.tgz", + "integrity": "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^8.0.0" - }, - "bin": { - "parser": "bin/babel-parser.js" + "@babel/parser": "^8.0.6", + "@babel/types": "^8.0.6", + "@jridgewell/gen-mapping": "0.4.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.31", + "@types/jsesc": "^2.5.0", + "jsesc": "^3.0.2" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-replace-supers/node_modules/@babel/template": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-8.0.0.tgz", - "integrity": "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==", + "node_modules/@babel/plugin-transform-async-generator-functions/node_modules/@babel/parser": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.6.tgz", + "integrity": "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0" + "@babel/types": "^8.0.6" + }, + "bin": { + "parser": "bin/babel-parser.js" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-replace-supers/node_modules/@babel/traverse": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.0.tgz", - "integrity": "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw==", + "node_modules/@babel/plugin-transform-async-generator-functions/node_modules/@babel/traverse": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.6.tgz", + "integrity": "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/generator": "^8.0.0", - "@babel/helper-globals": "^8.0.0", - "@babel/parser": "^8.0.0", + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.0.6", + "@babel/helper-globals": "^8.0.6", + "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", - "@babel/types": "^8.0.0", + "@babel/types": "^8.0.6", "obug": "^2.1.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-replace-supers/node_modules/@babel/types": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.0.tgz", - "integrity": "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==", + "node_modules/@babel/plugin-transform-async-generator-functions/node_modules/@jridgewell/gen-mapping": { + "version": "0.4.0-beta.0", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.4.0-beta.0.tgz", + "integrity": "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" + "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.24" } }, - "node_modules/@babel/helper-replace-supers/node_modules/js-tokens": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", - "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@babel/helper-skip-transparent-expression-wrappers": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-8.0.0.tgz", - "integrity": "sha512-xmCA9kP3IhySsqhzwIdWGlDN/1A4cCKNBO/uwZx/3YzmDoMePwno2Q5/Bq0q+tYaKbeF940YiKV/kaW8Mzvpjw==", + "node_modules/@babel/plugin-transform-async-to-generator": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-8.0.1.tgz", + "integrity": "sha512-e1jmmEU4p2Lx64sA1+EF8e8/RxPuegzbXcEbmFp5alDyLE+f2ViUpZ77bRWMXzihTwgVVmn/TOpqDbAuS5g1Ew==", "dev": true, "license": "MIT", "dependencies": { - "@babel/traverse": "^8.0.0", - "@babel/types": "^8.0.0" + "@babel/helper-module-imports": "^8.0.0", + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-remap-async-to-generator": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-skip-transparent-expression-wrappers/node_modules/@babel/code-frame": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.0.tgz", - "integrity": "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==", + "node_modules/@babel/plugin-transform-block-scoped-functions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-8.0.1.tgz", + "integrity": "sha512-0V97/gcf7LIgPieEiK1YT0eXa18XJFSLOTZjzEZhA9SJIqZhD/IwGUrCitBzXSmnGCP7hchwC6svHtJ/Eidcpg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^8.0.0", - "js-tokens": "^10.0.0" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-skip-transparent-expression-wrappers/node_modules/@babel/generator": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.0.tgz", - "integrity": "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g==", + "node_modules/@babel/plugin-transform-block-scoping": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-8.0.5.tgz", + "integrity": "sha512-czkN3g76Ns2wMe1C0IuceKUCqCe/yJ1by0qz4h4znq74K/Ks7K2Fx6Dplq9ecS65Z3rJHxT9a/kDSF2LbEov8w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "@types/jsesc": "^2.5.0", - "jsesc": "^3.0.2" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-skip-transparent-expression-wrappers/node_modules/@babel/helper-globals": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-8.0.0.tgz", - "integrity": "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw==", + "node_modules/@babel/plugin-transform-class-properties": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-8.0.1.tgz", + "integrity": "sha512-tORnYiVhIHnKj90TgbSZXrO24f9oEpA6MgFxpIDSKKlHv7AzBIRhkMlYevanueLNYaQXqZWarfCgXM4bWTfNiw==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-create-class-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-skip-transparent-expression-wrappers/node_modules/@babel/helper-string-parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", + "node_modules/@babel/plugin-transform-class-static-block": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-static-block/-/plugin-transform-class-static-block-8.0.5.tgz", + "integrity": "sha512-hyqluKOSy6PVOoHDEb4xsjFbtOSy+FFNzHNCrAHS5T+LxS8BtZHBCIVYFAcWzhBf/wRYsYu2uEpUvRmHYeOf8A==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-create-class-features-plugin": "^8.0.5", + "@babel/helper-plugin-utils": "^8.0.1" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-skip-transparent-expression-wrappers/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", + "node_modules/@babel/plugin-transform-classes": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-8.0.5.tgz", + "integrity": "sha512-GKFgovQQzZfEDFxclYFDOiw/Pszxa1epcs7RasL7yyeqi6rxL61Vbqt0uSDPc2M7XXCmNZnQZaK19333v6rabA==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^8.0.0", + "@babel/helper-compilation-targets": "^8.0.5", + "@babel/helper-globals": "^8.0.0", + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-replace-supers": "^8.0.1", + "@babel/traverse": "^8.0.5" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-skip-transparent-expression-wrappers/node_modules/@babel/parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.0.tgz", - "integrity": "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ==", + "node_modules/@babel/plugin-transform-classes/node_modules/@babel/generator": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.6.tgz", + "integrity": "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^8.0.0" - }, - "bin": { - "parser": "bin/babel-parser.js" + "@babel/parser": "^8.0.6", + "@babel/types": "^8.0.6", + "@jridgewell/gen-mapping": "0.4.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.31", + "@types/jsesc": "^2.5.0", + "jsesc": "^3.0.2" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-skip-transparent-expression-wrappers/node_modules/@babel/template": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-8.0.0.tgz", - "integrity": "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==", + "node_modules/@babel/plugin-transform-classes/node_modules/@babel/parser": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.6.tgz", + "integrity": "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0" + "@babel/types": "^8.0.6" + }, + "bin": { + "parser": "bin/babel-parser.js" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-skip-transparent-expression-wrappers/node_modules/@babel/traverse": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.0.tgz", - "integrity": "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw==", + "node_modules/@babel/plugin-transform-classes/node_modules/@babel/traverse": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.6.tgz", + "integrity": "sha512-ilYV+qLStGzSKLipJlETdvdtpK3rAuwfCmCoGKv15MU4EoeIuLkespSNoNLFGOPSciEHx9TLWtN5mv0fz5w5mQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/generator": "^8.0.0", - "@babel/helper-globals": "^8.0.0", - "@babel/parser": "^8.0.0", + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.0.6", + "@babel/helper-globals": "^8.0.6", + "@babel/parser": "^8.0.6", "@babel/template": "^8.0.0", - "@babel/types": "^8.0.0", + "@babel/types": "^8.0.6", "obug": "^2.1.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/helper-skip-transparent-expression-wrappers/node_modules/@babel/types": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.0.tgz", - "integrity": "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==", + "node_modules/@babel/plugin-transform-classes/node_modules/@jridgewell/gen-mapping": { + "version": "0.4.0-beta.0", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.4.0-beta.0.tgz", + "integrity": "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" + "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.24" } }, - "node_modules/@babel/helper-skip-transparent-expression-wrappers/node_modules/js-tokens": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", - "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@babel/helper-string-parser": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", - "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "node_modules/@babel/plugin-transform-computed-properties": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-8.0.1.tgz", + "integrity": "sha512-i4l3OGLO8DUDcwdnyraOvILbhqdUf4QgfzhVxSOSzRy49XKXrY7pwaSg9gDSKmhZfNPrEMciBSJSciQh/CjB1A==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^8.0.1" + }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", - "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "node_modules/@babel/plugin-transform-destructuring": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-8.0.5.tgz", + "integrity": "sha512-evjxc5fGvpXG2WMGSalpX8IJZVumLIDgk5r5eRhvXRDqFX/GPWq1BeRfJalPCcwJfrR5A/wvegUhx9W5Nr7/mg==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^8.0.1" + }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-validator-option": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-8.0.0.tgz", - "integrity": "sha512-U4Dybxh4WESWHt5XhBeExi4DrY0/DNK1aHpQbsrQXCUbFHuMweT0TpLEWKvaraV2Y6fS+ZXunsZ8zIuZIgvF2Q==", + "node_modules/@babel/plugin-transform-dotall-regex": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-8.0.1.tgz", + "integrity": "sha512-czOUoSaZljJ92yu+bYlXqb/UBN8K9daNCob/B6/7nthSvfGP6YhCnfqD64XWfyb2dN4ypxALNplApoJrsMd4fw==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-wrap-function": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-8.0.0.tgz", - "integrity": "sha512-Qpm8+wi5xfDkBfollanwriCcKniFfBmMmaKB01GVM6VGzKXo1fdxosZp04qEr5HM+LKhwr3hG1yRy8+ORsficA==", + "node_modules/@babel/plugin-transform-duplicate-keys": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-8.0.1.tgz", + "integrity": "sha512-kNnVLkxFUEcTtCyB5PFVQ5Xoy88Bk1lU/ZgDu97CW8eNhRH2Wsiy8Sq5l5dFnwtIUYjzsXHU77jUy1W5AtGSIw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/template": "^8.0.0", - "@babel/traverse": "^8.0.0", - "@babel/types": "^8.0.0" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-wrap-function/node_modules/@babel/code-frame": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.0.tgz", - "integrity": "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==", + "node_modules/@babel/plugin-transform-duplicate-named-capturing-groups-regex": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-named-capturing-groups-regex/-/plugin-transform-duplicate-named-capturing-groups-regex-8.0.1.tgz", + "integrity": "sha512-Tv43P47o6fuHgBL7HLHQg3WKXohW9CEUGjLtnCDW27yJLK0zKUdTTqREbZbycNHA83hewMjde5tF6ekrHu9bAA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^8.0.0", - "js-tokens": "^10.0.0" + "@babel/helper-create-regexp-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-wrap-function/node_modules/@babel/generator": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.0.tgz", - "integrity": "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g==", + "node_modules/@babel/plugin-transform-dynamic-import": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dynamic-import/-/plugin-transform-dynamic-import-8.0.1.tgz", + "integrity": "sha512-AS9GlgKc43tJNRu7yOvLaTko4qmdOb+8M69uNS8i421WLO20eVez7LdG5khKdi8E0LIQpYzzzdGIrdXWnO753g==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "@types/jsesc": "^2.5.0", - "jsesc": "^3.0.2" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-wrap-function/node_modules/@babel/helper-globals": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-8.0.0.tgz", - "integrity": "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw==", + "node_modules/@babel/plugin-transform-explicit-resource-management": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-explicit-resource-management/-/plugin-transform-explicit-resource-management-8.0.5.tgz", + "integrity": "sha512-Vr20jk/ZxRGu30o0jYvcKl2Pf0tiyr8H9q2ZGxYD6yjOpv9DdP6//I85q0cSOdADZhsu/ZZoApjGVCfl4xnVJw==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/plugin-transform-destructuring": "^8.0.5" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-wrap-function/node_modules/@babel/helper-string-parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", + "node_modules/@babel/plugin-transform-exponentiation-operator": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-8.0.1.tgz", + "integrity": "sha512-DsZvUUklUmDQ7d2vp+VjqgUWD51mGxhZZ1FPdPP9Hcj0vsgGUKX+zEBGp/vzB1O5PZUxWT/Euq5fu39M9dm9wg==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^8.0.1" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-wrap-function/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", + "node_modules/@babel/plugin-transform-export-namespace-from": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-export-namespace-from/-/plugin-transform-export-namespace-from-8.0.1.tgz", + "integrity": "sha512-bFzznm46bvWGaTYKle3iolbBJ+oPBfUjwCPesxlFE3SQ7DaY9EHf/8Y5ZzrodKJi8JDdcAyaVWaDUSVyhULh0g==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^8.0.1" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-wrap-function/node_modules/@babel/parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.0.tgz", - "integrity": "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ==", + "node_modules/@babel/plugin-transform-for-of": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-8.0.1.tgz", + "integrity": "sha512-rpeXtgELjpIBQH/+YmyFlD9timPEVCyqY+TNednzoeoTYvXSBEeUvYnYE+BK8rB8m6hHiNK7aL9QWKhGifEJCw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^8.0.0" - }, - "bin": { - "parser": "bin/babel-parser.js" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-wrap-function/node_modules/@babel/template": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-8.0.0.tgz", - "integrity": "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==", + "node_modules/@babel/plugin-transform-function-name": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-function-name/-/plugin-transform-function-name-8.0.1.tgz", + "integrity": "sha512-H1L/JfPf3CqmubuaiZaquXKQ8MRs4YWSsgRllkTviM8TafcCNnlvc4/fJZ3rXP8HmFM+/Bg+TlsPehUI9BtDFA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0" + "@babel/helper-compilation-targets": "^8.0.0", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-wrap-function/node_modules/@babel/traverse": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.0.tgz", - "integrity": "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw==", + "node_modules/@babel/plugin-transform-json-strings": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-json-strings/-/plugin-transform-json-strings-8.0.1.tgz", + "integrity": "sha512-Mowp8X0J6p7ZehLU82B5e65te2uuSeDHyxrEROwEAS2VKXNXssfw5ZMqhY7k9iXTsOv1Xs/49G3lDCj9Vvw8qQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/generator": "^8.0.0", - "@babel/helper-globals": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/template": "^8.0.0", - "@babel/types": "^8.0.0", - "obug": "^2.1.1" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-wrap-function/node_modules/@babel/types": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.0.tgz", - "integrity": "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==", + "node_modules/@babel/plugin-transform-literals": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-8.0.1.tgz", + "integrity": "sha512-ai7kfPRcfyUV1EszXoF1PvL3IuJoCuH08WSEPoRcJTWfZZ55VL/rcfvbVY16QLA3jjbzzSneQSoCtD3L6OyUjw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helper-wrap-function/node_modules/js-tokens": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", - "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@babel/helpers": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-8.0.0.tgz", - "integrity": "sha512-wfbi91pM3py96oIiJEz7qIpyXDytgr9zQC1HEWwlGNVRAEmItuU/0a41ZUKu1sJGyhhOIpc4t5vk4PYzt8wpsg==", + "node_modules/@babel/plugin-transform-logical-assignment-operators": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-logical-assignment-operators/-/plugin-transform-logical-assignment-operators-8.0.1.tgz", + "integrity": "sha512-Emvtr5zkEGyCNAmt+qKD5EUh8G0RbxV9EZWrDdX0LuVy5tBq1B3fOIslvVF9aCJmpnwS/AvAT53b9LxAZyXlng==", "dev": true, "license": "MIT", "dependencies": { - "@babel/template": "^8.0.0", - "@babel/types": "^8.0.0" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helpers/node_modules/@babel/code-frame": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.0.tgz", - "integrity": "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==", + "node_modules/@babel/plugin-transform-member-expression-literals": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-8.0.1.tgz", + "integrity": "sha512-3Axi9abnyGsm/hh6DsKPZ1Cr9fTtKqS7w0Ig5g12mU269YclpH8pV3xMln2vPLexXgUp6S6L+I06d9/YOLfRKA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^8.0.0", - "js-tokens": "^10.0.0" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helpers/node_modules/@babel/helper-string-parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, - "node_modules/@babel/helpers/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", + "node_modules/@babel/plugin-transform-modules-amd": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-8.0.1.tgz", + "integrity": "sha512-FDdhET8y1YFDNRuoynqSf23WTzbBBpbIB2oRrlFX7YYm9uWtFvJDSD1r/epBSjfPkOjeaaLgRW9xNnt3JGx46A==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-module-transforms": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helpers/node_modules/@babel/parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.0.tgz", - "integrity": "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ==", + "node_modules/@babel/plugin-transform-modules-commonjs": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-8.0.1.tgz", + "integrity": "sha512-PMuzulWrrzFNmY3lXSk/tV9NRb7y0eZZLJY4UEo2TKszroxvUZHAPPi+T9FDyrQhod+TQA+t+8/QYaaMpiEuhA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^8.0.0" - }, - "bin": { - "parser": "bin/babel-parser.js" + "@babel/helper-module-transforms": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helpers/node_modules/@babel/template": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-8.0.0.tgz", - "integrity": "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==", + "node_modules/@babel/plugin-transform-modules-systemjs": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-8.0.1.tgz", + "integrity": "sha512-0NEHanXmnFEnfT2dLKTXnu7m8GXFsnxRgteBC2aH21hYMBwAgxu5dcTdi/Eg+ToI1HbZe0CHwz4XRLgRNQhYoQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0" + "@babel/helper-module-transforms": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-validator-identifier": "^8.0.0" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helpers/node_modules/@babel/types": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.0.tgz", - "integrity": "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==", + "node_modules/@babel/plugin-transform-modules-umd": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-8.0.1.tgz", + "integrity": "sha512-XKTa2J2MdkmbVEeChq9f7Or0VYcsF0NyVBgytRyeN9F+J+ETAB2SHhfkG4toz/ssuU0i+h/QgJ6ddo5YakSQcA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0" + "@babel/helper-module-transforms": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/helpers/node_modules/js-tokens": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", - "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@babel/parser": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz", - "integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==", + "node_modules/@babel/plugin-transform-named-capturing-groups-regex": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-8.0.1.tgz", + "integrity": "sha512-zCHu+Jr2gTdJE48lN9SV/kXueCW2M79mKtKJc/ttfzzr/jvgdQdCd17RADMqFRQc/25MLxdtjTmlD0HSAMOlIQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^7.29.8" - }, - "bin": { - "parser": "bin/babel-parser.js" + "@babel/helper-create-regexp-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.0.0" + "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-bugfix-firefox-class-in-computed-class-key": { + "node_modules/@babel/plugin-transform-new-target": { "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-firefox-class-in-computed-class-key/-/plugin-bugfix-firefox-class-in-computed-class-key-8.0.1.tgz", - "integrity": "sha512-Ytgjjne4RnG3Oig7ik+NfY4ebRY30BPptVkkyu1f72eINJXRM3/bkU++tIc5aPvyLmo4KH20avq0xJ2o+9aEnw==", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-new-target/-/plugin-transform-new-target-8.0.1.tgz", + "integrity": "sha512-QSQxVg1x4PuOuhWUs4Y9u+x9Y+ER8z6G3tC+bDLBzvoOrNLJrEBQLRnwrTP8e5klihAw6Z+e9X5RjdAKcAGapA==", "dev": true, "license": "MIT", "dependencies": { @@ -1981,10 +1923,10 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-bugfix-safari-class-field-initializer-scope": { + "node_modules/@babel/plugin-transform-nullish-coalescing-operator": { "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-class-field-initializer-scope/-/plugin-bugfix-safari-class-field-initializer-scope-8.0.1.tgz", - "integrity": "sha512-X7pAMBhuKluA7UfwZNvKN0XVVu/AGeo84Z75eJl85rcb8J2aBzLK92btahM1X5h0oi0QIrbe0qIMA/0+4Buk7w==", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-8.0.1.tgz", + "integrity": "sha512-AgCJAmQLF7+PtsK79wJqr4xJ2StHCXlz7JL5CVFP4HejJx25Tk6yl1ZrXvi0cKh3VGDVnfVxefxnrpsBirgpyQ==", "dev": true, "license": "MIT", "dependencies": { @@ -1997,10 +1939,10 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": { + "node_modules/@babel/plugin-transform-numeric-separator": { "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/-/plugin-bugfix-safari-id-destructuring-collision-in-function-expression-8.0.1.tgz", - "integrity": "sha512-DJviKTxYfH0hFwnMiW4dnPyMGzS3Hrr4zUfXl1zwQ0QiGlGlNYklLoPSYEQr8S7nau0/K7NdQjTh0qbYuyFjCA==", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-numeric-separator/-/plugin-transform-numeric-separator-8.0.1.tgz", + "integrity": "sha512-it2DmUyLIA1GQUXlFDEnI+/G89mTgxndnAiZYpW8xYR6LboblfirMqiWJeTna5uypQJg7viTT4D1iEURRtFcfw==", "dev": true, "license": "MIT", "dependencies": { @@ -2013,15 +1955,17 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-bugfix-safari-rest-destructuring-rhs-array": { + "node_modules/@babel/plugin-transform-object-rest-spread": { "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-rest-destructuring-rhs-array/-/plugin-bugfix-safari-rest-destructuring-rhs-array-8.0.1.tgz", - "integrity": "sha512-DmR/N+B9+4PbURFj4+zdnWj49/PFAnK2bn8+E4ZAmwn3J5QCxnbG7Ep6aRfz9M8Aw+rBro0kIJQycvzFpl4buQ==", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-rest-spread/-/plugin-transform-object-rest-spread-8.0.1.tgz", + "integrity": "sha512-VmxkDu6bBdbxRzqn6E93hYucug4OVa6svSO19W//vVzNUGAmQzk3QRyHyyEtfcjSLR3NWfRsWwVM9zExLmd+2w==", "dev": true, "license": "MIT", "dependencies": { + "@babel/helper-compilation-targets": "^8.0.0", "@babel/helper-plugin-utils": "^8.0.1", - "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" + "@babel/plugin-transform-destructuring": "^8.0.1", + "@babel/plugin-transform-parameters": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" @@ -2030,16 +1974,15 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": { + "node_modules/@babel/plugin-transform-object-super": { "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining/-/plugin-bugfix-v8-spread-parameters-in-optional-chaining-8.0.1.tgz", - "integrity": "sha512-x8bi0LFVD2xkULjfNn+hCMg16yAFHAM9fS/ThSFeYBi+0MP9K6qcY2BZb4urUwC7PYtEy5wPe6TKjOEjXrCGFA==", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-8.0.1.tgz", + "integrity": "sha512-fDkPXRTRKGm25bAq01q82UM4ypPqdVXCwphUUm4t1dL01fGIG0v8KRvT+4BjhMAtRxtPuI34t5Vs7yjRgs3ZgQ==", "dev": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^8.0.1", - "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0", - "@babel/plugin-transform-optional-chaining": "^8.0.1" + "@babel/helper-replace-supers": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" @@ -2048,10 +1991,10 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": { + "node_modules/@babel/plugin-transform-optional-catch-binding": { "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly/-/plugin-bugfix-v8-static-class-fields-redefine-readonly-8.0.1.tgz", - "integrity": "sha512-P8+RN2n7ts2s1vnE+lXdHYf+dhnmcGSen/kWzBsVluT9Sey5AqmcRXYWlHqgQxaNlKTD5YMa1tf5z4d1v8W88w==", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-catch-binding/-/plugin-transform-optional-catch-binding-8.0.1.tgz", + "integrity": "sha512-b2OQ74uGliyATcasTjxGy2O/86UI/n+EN4juB4EMfEwTi9j9uq70PuP0L8fW77vfRY66gO/YoTo/WbIdQ/Si1g==", "dev": true, "license": "MIT", "dependencies": { @@ -2064,14 +2007,15 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-syntax-typescript": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-8.0.1.tgz", - "integrity": "sha512-YBpIeuOZSUZx7RGH/U+dIAsHDHyojBVDRHNBUgOiUDS5IIcgBm1uyu9xs/2kM27B/bmDfOxzJ9k8cU2QuOwGIA==", + "node_modules/@babel/plugin-transform-optional-chaining": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-8.0.5.tgz", + "integrity": "sha512-w8ouIDKdmUc2oyvBx4S/WtiQM7bMww5LGjB2A4L1+sDWZGw37XxzqOqfgHnPm+2ldINmAqrf2ekzpeJ/sS9poQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" }, "engines": { "node": "^22.18.0 || >=24.11.0" @@ -2080,10 +2024,10 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-arrow-functions": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-8.0.1.tgz", - "integrity": "sha512-o/gr7kRlq3PKLLuYth4udOsrC7geBerti+QtwPeyxMOsEQO1d8kDHqk9r2PtMx2y9i8FG7tzyTerfv1yMLSMsQ==", + "node_modules/@babel/plugin-transform-parameters": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-8.0.5.tgz", + "integrity": "sha512-oXsstDkzuE+gOqBz2+e1VFqDew0KlGgd9GT4MGptmcIq3uDbxcowHRSaqMCvp3nbiZws4wTm8Phuk9ZJO3NtTg==", "dev": true, "license": "MIT", "dependencies": { @@ -2096,16 +2040,15 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-async-generator-functions": { + "node_modules/@babel/plugin-transform-private-methods": { "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-8.0.1.tgz", - "integrity": "sha512-kqnSMF1YHBzuiQrl68675i5Ma1oljvo+SJsNEZFZVBu5BUrVIZm9KId3ui2PdtLK2sv2zM8sJnjPDfgLxQlEqQ==", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-8.0.1.tgz", + "integrity": "sha512-TrFCGcXaVDh6S5IRhmLSRTY9H80VTCMQWnZtzBRg4RWg3KCLmdmsmj4M15kZAPZfoPkWL/SJb4em3Py/vOiX8g==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1", - "@babel/helper-remap-async-to-generator": "^8.0.1", - "@babel/traverse": "^8.0.0" + "@babel/helper-create-class-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" @@ -2114,149 +2057,163 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-async-generator-functions/node_modules/@babel/code-frame": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.0.tgz", - "integrity": "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==", + "node_modules/@babel/plugin-transform-private-property-in-object": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-8.0.5.tgz", + "integrity": "sha512-OilYoElZMdD/My3fJTh0jLOPy8Y9Jfpcb9nPXG0Bpy4oRbZeeVX39P1cXKsPwnXTBZg7qEKk8TQ0lzpJvdK3yw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^8.0.0", - "js-tokens": "^10.0.0" + "@babel/helper-annotate-as-pure": "^8.0.0", + "@babel/helper-create-class-features-plugin": "^8.0.5", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-async-generator-functions/node_modules/@babel/generator": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.0.tgz", - "integrity": "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g==", + "node_modules/@babel/plugin-transform-property-literals": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-8.0.1.tgz", + "integrity": "sha512-Z/qx4cxUtYR1nt7XWRutObPxDks98fEYsjWbVeKEqZH6y3AGknmgzCqmHf2FHWZCl1DfoPeuJY+3hZ+35D+2tg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "@types/jsesc": "^2.5.0", - "jsesc": "^3.0.2" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-async-generator-functions/node_modules/@babel/helper-globals": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-8.0.0.tgz", - "integrity": "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw==", + "node_modules/@babel/plugin-transform-regenerator": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-8.0.6.tgz", + "integrity": "sha512-ky/yW+PcQfHyOhbQFNkcHOCIHXaEANYaXCucZ1MY1PdSJRjaf3AX/TMKS6nCij73YtU1bVNy7Zx5NWAJy42TQA==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^8.0.1" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-async-generator-functions/node_modules/@babel/helper-string-parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", + "node_modules/@babel/plugin-transform-regexp-modifiers": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regexp-modifiers/-/plugin-transform-regexp-modifiers-8.0.1.tgz", + "integrity": "sha512-02ITRDBesPdTYU0oShAzERwEPzozOUQSXlz3qrt8JGuhalBJQv9z5NjgHJPC9sS3Fsam8gDtfAEpBnqZwUIdjQ==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-async-generator-functions/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", - "dev": true, - "license": "MIT", + "node_modules/@babel/plugin-transform-reserved-words": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-8.0.1.tgz", + "integrity": "sha512-+aykZi7ZP3U84veqfJXm3HhPZGddWFi64g7jr0ni6tb1zel+1ey+SL+IRKPoZXFyFqvYEsoqrmx4PyEJRlHl/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^8.0.1" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-async-generator-functions/node_modules/@babel/parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.0.tgz", - "integrity": "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ==", + "node_modules/@babel/plugin-transform-runtime": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-8.0.6.tgz", + "integrity": "sha512-2djup+i7z4taCN9VCJsmPNC0GT5A0FhI+S0tZwK+FRDZdaEOQUYVmfKOg/hIKhMBXjOFxEsBHvGE0Thqj71edA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^8.0.0" - }, - "bin": { - "parser": "bin/babel-parser.js" + "@babel/helper-module-imports": "^8.0.0", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-async-generator-functions/node_modules/@babel/template": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-8.0.0.tgz", - "integrity": "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==", + "node_modules/@babel/plugin-transform-shorthand-properties": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-8.0.1.tgz", + "integrity": "sha512-JddANd9yPVH8dYgVoNkqAH5BftnsDxFpG51Zas7sc6F3poz5QWcejHNGO8a/57IX5ByjGSzEmYk9Z7ZMa5MWaw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-async-generator-functions/node_modules/@babel/traverse": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.0.tgz", - "integrity": "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw==", + "node_modules/@babel/plugin-transform-spread": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-8.0.5.tgz", + "integrity": "sha512-thqaGFTViCmJxUPJ3IivfaGHz8eodOL7UbsZ2gMOybSi8uQFXFEoabnnILMl4ZCok0vVrKD4HKq9MJWSj5qqxw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/generator": "^8.0.0", - "@babel/helper-globals": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/template": "^8.0.0", - "@babel/types": "^8.0.0", - "obug": "^2.1.1" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-async-generator-functions/node_modules/@babel/types": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.0.tgz", - "integrity": "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==", + "node_modules/@babel/plugin-transform-sticky-regex": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-8.0.1.tgz", + "integrity": "sha512-IsVP6WrZZQdaG2zLmeKwWiI+ua2NB5L1+f77C2/8z2NCDz7uxlIA/lnwocYOJk9PXcOC2sZgRls3LN4XpNduzQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-async-generator-functions/node_modules/js-tokens": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", - "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@babel/plugin-transform-async-to-generator": { + "node_modules/@babel/plugin-transform-template-literals": { "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-8.0.1.tgz", - "integrity": "sha512-e1jmmEU4p2Lx64sA1+EF8e8/RxPuegzbXcEbmFp5alDyLE+f2ViUpZ77bRWMXzihTwgVVmn/TOpqDbAuS5g1Ew==", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-8.0.1.tgz", + "integrity": "sha512-JXvtj5+BJA9Qv3prDzW2z2DkGTJNmG0BObTdUD03STiu1Jr4fNQkQy3hYZgPL46a2RjcuhwBMYf49BOuJ98gnA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-module-imports": "^8.0.0", - "@babel/helper-plugin-utils": "^8.0.1", - "@babel/helper-remap-async-to-generator": "^8.0.1" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" @@ -2265,10 +2222,10 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-block-scoped-functions": { + "node_modules/@babel/plugin-transform-typeof-symbol": { "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-8.0.1.tgz", - "integrity": "sha512-0V97/gcf7LIgPieEiK1YT0eXa18XJFSLOTZjzEZhA9SJIqZhD/IwGUrCitBzXSmnGCP7hchwC6svHtJ/Eidcpg==", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-8.0.1.tgz", + "integrity": "sha512-+wJoxgxP2gtey0UMUOMhzMMji2XHO/Uu6MXUh/r5Yhc2jngKzK/wFxY2WNe4UCaRcMvCb4gcnB8wIgFXJsocXg==", "dev": true, "license": "MIT", "dependencies": { @@ -2281,14 +2238,18 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-block-scoping": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-8.0.1.tgz", - "integrity": "sha512-HxiQvKsSCs2jOmMhjDrooHaZYOy6W8bqwXp/zjdgPjsNrda6tK9/CH3a/cVIeg6ge3hSS02ALqvqgIo4rTsuSg==", + "node_modules/@babel/plugin-transform-typescript": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-8.0.6.tgz", + "integrity": "sha512-WF3yRlQtClzScvQbWct00ix63+w3DPiyU0WmCBU4YqK539n3VvJFElElpevoD8wfu6953CbiNoUZBi2B7/5jXw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" + "@babel/helper-annotate-as-pure": "^8.0.0", + "@babel/helper-create-class-features-plugin": "^8.0.6", + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0", + "@babel/plugin-syntax-typescript": "^8.0.3" }, "engines": { "node": "^22.18.0 || >=24.11.0" @@ -2297,14 +2258,13 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-class-properties": { + "node_modules/@babel/plugin-transform-unicode-escapes": { "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-8.0.1.tgz", - "integrity": "sha512-tORnYiVhIHnKj90TgbSZXrO24f9oEpA6MgFxpIDSKKlHv7AzBIRhkMlYevanueLNYaQXqZWarfCgXM4bWTfNiw==", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-escapes/-/plugin-transform-unicode-escapes-8.0.1.tgz", + "integrity": "sha512-TAXJepIJ6vZphytTwcf+LuXi2M2ZWI43VCqNw+1ZZLPP/38Z1A8j4Mahvg8kqDgMOSM/cakk+hedTJCiw3jQuQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-create-class-features-plugin": "^8.0.1", "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { @@ -2314,14 +2274,14 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-class-static-block": { + "node_modules/@babel/plugin-transform-unicode-property-regex": { "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-static-block/-/plugin-transform-class-static-block-8.0.1.tgz", - "integrity": "sha512-NEVK+L0Le8h8tJ+IK0CGS5y9Yi1ZHxLj6M5PeanhMFuq9aSo0XI+Wtmbuyop6fTNukOm7ORNntf/kwid891vqQ==", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-property-regex/-/plugin-transform-unicode-property-regex-8.0.1.tgz", + "integrity": "sha512-zjBN9tSMSuomNDfurL69Gf7+v4D2t5uI1mSZaYJDo88SKpbduhCXqtxH7Tx66iCF6caWYwnBzSM0tnCozmQq5Q==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-create-class-features-plugin": "^8.0.1", + "@babel/helper-create-regexp-features-plugin": "^8.0.1", "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { @@ -2331,19 +2291,15 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-classes": { + "node_modules/@babel/plugin-transform-unicode-regex": { "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-8.0.1.tgz", - "integrity": "sha512-phwyCES8kIMAdVOFw25ztmgAvkl2G+TvUv7azUYyrlR1Qoo3eLJC/MU3MGUKFZ4BWtsJ1NTJM1lKRLzKbswg7w==", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-8.0.1.tgz", + "integrity": "sha512-v0oO83cvT5lwbcIVRShpx4vaHD8AvM9IBowsQuTeP+kGmhh3recJQs33Bl6dlo3/2g9amlznLbFGn4VJbPCJqA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-annotate-as-pure": "^8.0.0", - "@babel/helper-compilation-targets": "^8.0.0", - "@babel/helper-globals": "^8.0.0", - "@babel/helper-plugin-utils": "^8.0.1", - "@babel/helper-replace-supers": "^8.0.1", - "@babel/traverse": "^8.0.0" + "@babel/helper-create-regexp-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" @@ -2352,85 +2308,163 @@ "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-classes/node_modules/@babel/code-frame": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.0.tgz", - "integrity": "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==", + "node_modules/@babel/plugin-transform-unicode-sets-regex": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-8.0.1.tgz", + "integrity": "sha512-MlQeyS0K7gh0XNeLBMS/3Z07HjDOKhA7xm2L18GyxOXyiFHI9E+ZuQ4mFYmcLjluXsE/Wf6dABIqZvKpKw0Z3w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^8.0.0", - "js-tokens": "^10.0.0" + "@babel/helper-create-regexp-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-classes/node_modules/@babel/generator": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.0.tgz", - "integrity": "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g==", + "node_modules/@babel/preset-env": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-8.0.6.tgz", + "integrity": "sha512-Ekl110OgRBQtibBTXrXyuxhy2p7QxpzWT45cFOZCBFKBan3o8vN54sQ26GtqyTyORSNWKx0GOmIdLTTu/Y+prA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^8.0.0", - "@babel/types": "^8.0.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "@types/jsesc": "^2.5.0", - "jsesc": "^3.0.2" + "@babel/compat-data": "^8.0.5", + "@babel/helper-compilation-targets": "^8.0.6", + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-validator-option": "^8.0.0", + "@babel/plugin-bugfix-firefox-class-in-computed-class-key": "^8.0.1", + "@babel/plugin-bugfix-safari-class-field-initializer-scope": "^8.0.1", + "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^8.0.1", + "@babel/plugin-bugfix-safari-rest-destructuring-rhs-array": "^8.0.6", + "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^8.0.1", + "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": "^8.0.1", + "@babel/plugin-transform-arrow-functions": "^8.0.1", + "@babel/plugin-transform-async-generator-functions": "^8.0.6", + "@babel/plugin-transform-async-to-generator": "^8.0.1", + "@babel/plugin-transform-block-scoped-functions": "^8.0.1", + "@babel/plugin-transform-block-scoping": "^8.0.5", + "@babel/plugin-transform-class-properties": "^8.0.1", + "@babel/plugin-transform-class-static-block": "^8.0.5", + "@babel/plugin-transform-classes": "^8.0.5", + "@babel/plugin-transform-computed-properties": "^8.0.1", + "@babel/plugin-transform-destructuring": "^8.0.5", + "@babel/plugin-transform-dotall-regex": "^8.0.1", + "@babel/plugin-transform-duplicate-keys": "^8.0.1", + "@babel/plugin-transform-duplicate-named-capturing-groups-regex": "^8.0.1", + "@babel/plugin-transform-dynamic-import": "^8.0.1", + "@babel/plugin-transform-explicit-resource-management": "^8.0.5", + "@babel/plugin-transform-exponentiation-operator": "^8.0.1", + "@babel/plugin-transform-export-namespace-from": "^8.0.1", + "@babel/plugin-transform-for-of": "^8.0.1", + "@babel/plugin-transform-function-name": "^8.0.1", + "@babel/plugin-transform-json-strings": "^8.0.1", + "@babel/plugin-transform-literals": "^8.0.1", + "@babel/plugin-transform-logical-assignment-operators": "^8.0.1", + "@babel/plugin-transform-member-expression-literals": "^8.0.1", + "@babel/plugin-transform-modules-amd": "^8.0.1", + "@babel/plugin-transform-modules-commonjs": "^8.0.1", + "@babel/plugin-transform-modules-systemjs": "^8.0.1", + "@babel/plugin-transform-modules-umd": "^8.0.1", + "@babel/plugin-transform-named-capturing-groups-regex": "^8.0.1", + "@babel/plugin-transform-new-target": "^8.0.1", + "@babel/plugin-transform-nullish-coalescing-operator": "^8.0.1", + "@babel/plugin-transform-numeric-separator": "^8.0.1", + "@babel/plugin-transform-object-rest-spread": "^8.0.1", + "@babel/plugin-transform-object-super": "^8.0.1", + "@babel/plugin-transform-optional-catch-binding": "^8.0.1", + "@babel/plugin-transform-optional-chaining": "^8.0.5", + "@babel/plugin-transform-parameters": "^8.0.5", + "@babel/plugin-transform-private-methods": "^8.0.1", + "@babel/plugin-transform-private-property-in-object": "^8.0.5", + "@babel/plugin-transform-property-literals": "^8.0.1", + "@babel/plugin-transform-regenerator": "^8.0.6", + "@babel/plugin-transform-regexp-modifiers": "^8.0.1", + "@babel/plugin-transform-reserved-words": "^8.0.1", + "@babel/plugin-transform-shorthand-properties": "^8.0.1", + "@babel/plugin-transform-spread": "^8.0.5", + "@babel/plugin-transform-sticky-regex": "^8.0.1", + "@babel/plugin-transform-template-literals": "^8.0.1", + "@babel/plugin-transform-typeof-symbol": "^8.0.1", + "@babel/plugin-transform-unicode-escapes": "^8.0.1", + "@babel/plugin-transform-unicode-property-regex": "^8.0.1", + "@babel/plugin-transform-unicode-regex": "^8.0.1", + "@babel/plugin-transform-unicode-sets-regex": "^8.0.1", + "@babel/preset-modules": "^0.2.0", + "babel-plugin-polyfill-corejs3": "^1.0.0", + "core-js-compat": "^3.48.0", + "verkit": "^0.3.2" }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-classes/node_modules/@babel/helper-globals": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-8.0.0.tgz", - "integrity": "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw==", + "node_modules/@babel/preset-modules": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@babel/preset-modules/-/preset-modules-0.2.0.tgz", + "integrity": "sha512-yz0RBN2fx4fjCeFcTWsWgL7PxSRltvTa0Qg14HkWCU3qS8MO7ZSJlBVbGceynd5C9NsJwwUHNQD3dc6tYO+jqQ==", "dev": true, "license": "MIT", - "engines": { - "node": "^22.18.0 || >=24.11.0" + "dependencies": { + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/plugin-transform-dotall-regex": "^8.0.1", + "@babel/plugin-transform-unicode-property-regex": "^8.0.1", + "@babel/types": "^8.0.0", + "esutils": "^2.0.2" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-classes/node_modules/@babel/helper-string-parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", + "node_modules/@babel/preset-typescript": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-8.0.1.tgz", + "integrity": "sha512-qrPhQIN1NLrPmzgazF9XKQqXrOcp/WJly+K+6ReFonn24FZqRJO7clxOJo6Ni75L+2vAqI3cHVU2OJLBxoPp5A==", "dev": true, "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-validator-option": "^8.0.0", + "@babel/plugin-transform-modules-commonjs": "^8.0.1", + "@babel/plugin-transform-typescript": "^8.0.1" + }, "engines": { "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-classes/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", + "node_modules/@babel/runtime": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz", + "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", "dev": true, "license": "MIT", "engines": { - "node": "^22.18.0 || >=24.11.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/plugin-transform-classes/node_modules/@babel/parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.0.tgz", - "integrity": "sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ==", + "node_modules/@babel/runtime-corejs3": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.29.7.tgz", + "integrity": "sha512-ppj9ouYku+RX0ljtgZd+KMO5mkM2bCqg8H2PYAFWnLsHEIKIdRojqbJ2i3eVHrisuxy7nOFCmngTDdWtUCdXUQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^8.0.0" - }, - "bin": { - "parser": "bin/babel-parser.js" + "core-js-pure": "^3.48.0" }, "engines": { - "node": "^22.18.0 || >=24.11.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/plugin-transform-classes/node_modules/@babel/template": { + "node_modules/@babel/template": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/@babel/template/-/template-8.0.0.tgz", "integrity": "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==", @@ -2445,2763 +2479,1179 @@ "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/plugin-transform-classes/node_modules/@babel/traverse": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.0.tgz", - "integrity": "sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw==", + "node_modules/@babel/template/node_modules/@babel/parser": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.6.tgz", + "integrity": "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^8.0.0", - "@babel/generator": "^8.0.0", - "@babel/helper-globals": "^8.0.0", - "@babel/parser": "^8.0.0", - "@babel/template": "^8.0.0", - "@babel/types": "^8.0.0", - "obug": "^2.1.1" + "@babel/types": "^8.0.6" + }, + "bin": { + "parser": "bin/babel-parser.js" }, "engines": { "node": "^22.18.0 || >=24.11.0" } }, - "node_modules/@babel/plugin-transform-classes/node_modules/@babel/types": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.0.tgz", - "integrity": "sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.0" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, - "node_modules/@babel/plugin-transform-classes/node_modules/js-tokens": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", - "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@babel/plugin-transform-computed-properties": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-8.0.1.tgz", - "integrity": "sha512-i4l3OGLO8DUDcwdnyraOvILbhqdUf4QgfzhVxSOSzRy49XKXrY7pwaSg9gDSKmhZfNPrEMciBSJSciQh/CjB1A==", + "node_modules/@babel/traverse": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz", + "integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.8", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.8", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8", + "debug": "^4.3.1" }, "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/plugin-transform-destructuring": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-8.0.1.tgz", - "integrity": "sha512-RtR8uLDl0QcCmqMNIkM8gmDeYZ3rS0ZH+sa+I6sfc09yFoqfp9AEPgBstq9KyfVb0lFCVSRFfJXCI70FIl5ccw==", + "node_modules/@babel/traverse/node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" }, "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/plugin-transform-dotall-regex": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-8.0.1.tgz", - "integrity": "sha512-czOUoSaZljJ92yu+bYlXqb/UBN8K9daNCob/B6/7nthSvfGP6YhCnfqD64XWfyb2dN4ypxALNplApoJrsMd4fw==", + "node_modules/@babel/traverse/node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", "dev": true, "license": "MIT", - "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^8.0.1", - "@babel/helper-plugin-utils": "^8.0.1" - }, "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/plugin-transform-duplicate-keys": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-8.0.1.tgz", - "integrity": "sha512-kNnVLkxFUEcTtCyB5PFVQ5Xoy88Bk1lU/ZgDu97CW8eNhRH2Wsiy8Sq5l5dFnwtIUYjzsXHU77jUy1W5AtGSIw==", + "node_modules/@babel/traverse/node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", "dev": true, "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/plugin-transform-duplicate-named-capturing-groups-regex": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-named-capturing-groups-regex/-/plugin-transform-duplicate-named-capturing-groups-regex-8.0.1.tgz", - "integrity": "sha512-Tv43P47o6fuHgBL7HLHQg3WKXohW9CEUGjLtnCDW27yJLK0zKUdTTqREbZbycNHA83hewMjde5tF6ekrHu9bAA==", + "node_modules/@babel/traverse/node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", "dev": true, "license": "MIT", - "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^8.0.1", - "@babel/helper-plugin-utils": "^8.0.1" - }, "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/plugin-transform-dynamic-import": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dynamic-import/-/plugin-transform-dynamic-import-8.0.1.tgz", - "integrity": "sha512-AS9GlgKc43tJNRu7yOvLaTko4qmdOb+8M69uNS8i421WLO20eVez7LdG5khKdi8E0LIQpYzzzdGIrdXWnO753g==", + "node_modules/@babel/traverse/node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" }, "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/plugin-transform-explicit-resource-management": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-explicit-resource-management/-/plugin-transform-explicit-resource-management-8.0.1.tgz", - "integrity": "sha512-VzDIYwBlLCpV6mJfloRdJm8HmYnMqs7O+bGha8yfg2kP7jAdxeCw6yZBVBeaKKQUThtSU52iy+3lB7DhYsbOBA==", + "node_modules/@babel/traverse/node_modules/@babel/types": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", + "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1", - "@babel/plugin-transform-destructuring": "^8.0.1" + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" }, "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "node": ">=6.9.0" } }, - "node_modules/@babel/plugin-transform-exponentiation-operator": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-8.0.1.tgz", - "integrity": "sha512-DsZvUUklUmDQ7d2vp+VjqgUWD51mGxhZZ1FPdPP9Hcj0vsgGUKX+zEBGp/vzB1O5PZUxWT/Euq5fu39M9dm9wg==", + "node_modules/@babel/traverse/node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } + "license": "MIT" }, - "node_modules/@babel/plugin-transform-export-namespace-from": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-export-namespace-from/-/plugin-transform-export-namespace-from-8.0.1.tgz", - "integrity": "sha512-bFzznm46bvWGaTYKle3iolbBJ+oPBfUjwCPesxlFE3SQ7DaY9EHf/8Y5ZzrodKJi8JDdcAyaVWaDUSVyhULh0g==", + "node_modules/@babel/types": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.6.tgz", + "integrity": "sha512-c+xgSWboV2pdwXP67BUWDVRHi2BO5Q3KwxyFVs7taVTY+fsK47/L51ZXQoV9rozHJDNHvJ4v4WEsI/IlxV2l2A==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" + "@babel/helper-string-parser": "^8.0.6", + "@babel/helper-validator-identifier": "^8.0.6" }, "engines": { "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" } }, - "node_modules/@babel/plugin-transform-for-of": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-8.0.1.tgz", - "integrity": "sha512-rpeXtgELjpIBQH/+YmyFlD9timPEVCyqY+TNednzoeoTYvXSBEeUvYnYE+BK8rB8m6hHiNK7aL9QWKhGifEJCw==", + "node_modules/@bazel/runfiles": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/@bazel/runfiles/-/runfiles-6.5.0.tgz", + "integrity": "sha512-RzahvqTkfpY2jsDxo8YItPX+/iZ6hbiikw1YhE0bA9EKBR5Og8Pa6FHn9PO9M0zaXRVsr0GFQLKbB/0rzy9SzA==", "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1", - "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } + "license": "Apache-2.0" }, - "node_modules/@babel/plugin-transform-function-name": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-function-name/-/plugin-transform-function-name-8.0.1.tgz", - "integrity": "sha512-H1L/JfPf3CqmubuaiZaquXKQ8MRs4YWSsgRllkTviM8TafcCNnlvc4/fJZ3rXP8HmFM+/Bg+TlsPehUI9BtDFA==", + "node_modules/@biomejs/biome": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.4.11.tgz", + "integrity": "sha512-nWxHX8tf3Opb/qRgZpBbsTOqOodkbrkJ7S+JxJAruxOReaDPPmPuLBAGQ8vigyUgo0QBB+oQltNEAvalLcjggA==", "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-compilation-targets": "^8.0.0", - "@babel/helper-plugin-utils": "^8.0.1" + "license": "MIT OR Apache-2.0", + "bin": { + "biome": "bin/biome" }, "engines": { - "node": "^22.18.0 || >=24.11.0" + "node": ">=14.21.3" }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/biome" + }, + "optionalDependencies": { + "@biomejs/cli-darwin-arm64": "2.4.11", + "@biomejs/cli-darwin-x64": "2.4.11", + "@biomejs/cli-linux-arm64": "2.4.11", + "@biomejs/cli-linux-arm64-musl": "2.4.11", + "@biomejs/cli-linux-x64": "2.4.11", + "@biomejs/cli-linux-x64-musl": "2.4.11", + "@biomejs/cli-win32-arm64": "2.4.11", + "@biomejs/cli-win32-x64": "2.4.11" } }, - "node_modules/@babel/plugin-transform-json-strings": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-json-strings/-/plugin-transform-json-strings-8.0.1.tgz", - "integrity": "sha512-Mowp8X0J6p7ZehLU82B5e65te2uuSeDHyxrEROwEAS2VKXNXssfw5ZMqhY7k9iXTsOv1Xs/49G3lDCj9Vvw8qQ==", + "node_modules/@biomejs/cli-darwin-arm64": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.4.11.tgz", + "integrity": "sha512-wOt+ed+L2dgZanWyL6i29qlXMc088N11optzpo10peayObBaAshbTcxKUchzEMp9QSY8rh5h6VfAFE3WTS1rqg==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "node": ">=14.21.3" } }, - "node_modules/@babel/plugin-transform-literals": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-8.0.1.tgz", - "integrity": "sha512-ai7kfPRcfyUV1EszXoF1PvL3IuJoCuH08WSEPoRcJTWfZZ55VL/rcfvbVY16QLA3jjbzzSneQSoCtD3L6OyUjw==", + "node_modules/@biomejs/cli-darwin-x64": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.4.11.tgz", + "integrity": "sha512-gZ6zR8XmZlExfi/Pz/PffmdpWOQ8Qhy7oBztgkR8/ylSRyLwfRPSadmiVCV8WQ8PoJ2MWUy2fgID9zmtgUUJmw==", + "cpu": [ + "x64" + ], "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "node": ">=14.21.3" } }, - "node_modules/@babel/plugin-transform-logical-assignment-operators": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-logical-assignment-operators/-/plugin-transform-logical-assignment-operators-8.0.1.tgz", - "integrity": "sha512-Emvtr5zkEGyCNAmt+qKD5EUh8G0RbxV9EZWrDdX0LuVy5tBq1B3fOIslvVF9aCJmpnwS/AvAT53b9LxAZyXlng==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-member-expression-literals": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-8.0.1.tgz", - "integrity": "sha512-3Axi9abnyGsm/hh6DsKPZ1Cr9fTtKqS7w0Ig5g12mU269YclpH8pV3xMln2vPLexXgUp6S6L+I06d9/YOLfRKA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-modules-amd": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-8.0.1.tgz", - "integrity": "sha512-FDdhET8y1YFDNRuoynqSf23WTzbBBpbIB2oRrlFX7YYm9uWtFvJDSD1r/epBSjfPkOjeaaLgRW9xNnt3JGx46A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-transforms": "^8.0.1", - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-modules-commonjs": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-8.0.1.tgz", - "integrity": "sha512-PMuzulWrrzFNmY3lXSk/tV9NRb7y0eZZLJY4UEo2TKszroxvUZHAPPi+T9FDyrQhod+TQA+t+8/QYaaMpiEuhA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-transforms": "^8.0.1", - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-modules-systemjs": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-8.0.1.tgz", - "integrity": "sha512-0NEHanXmnFEnfT2dLKTXnu7m8GXFsnxRgteBC2aH21hYMBwAgxu5dcTdi/Eg+ToI1HbZe0CHwz4XRLgRNQhYoQ==", + "node_modules/@biomejs/cli-linux-arm64": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.4.11.tgz", + "integrity": "sha512-avdJaEElXrKceK0va9FkJ4P5ci3N01TGkc6ni3P8l3BElqbOz42Wg2IyX3gbh0ZLEd4HVKEIrmuVu/AMuSeFFA==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-transforms": "^8.0.1", - "@babel/helper-plugin-utils": "^8.0.1", - "@babel/helper-validator-identifier": "^8.0.0" - }, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "node": ">=14.21.3" } }, - "node_modules/@babel/plugin-transform-modules-systemjs/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.0.tgz", - "integrity": "sha512-kXxQVZHNOctSJJsqzmcbPSCEkM6oHNnDIkua7g9RCO9xRHj2eCiKvRx2KPdfWR9QxcGWnK/oArrtunmie3rL9g==", + "node_modules/@biomejs/cli-linux-arm64-musl": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.4.11.tgz", + "integrity": "sha512-+Sbo1OAmlegtdwqFE8iOxFIWLh1B3OEgsuZfBpyyN/kWuqZ8dx9ZEes6zVnDMo+zRHF2wLynRVhoQmV7ohxl2Q==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "MIT", + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": "^22.18.0 || >=24.11.0" + "node": ">=14.21.3" } }, - "node_modules/@babel/plugin-transform-modules-umd": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-8.0.1.tgz", - "integrity": "sha512-XKTa2J2MdkmbVEeChq9f7Or0VYcsF0NyVBgytRyeN9F+J+ETAB2SHhfkG4toz/ssuU0i+h/QgJ6ddo5YakSQcA==", + "node_modules/@biomejs/cli-linux-x64": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.4.11.tgz", + "integrity": "sha512-TagWV0iomp5LnEnxWFg4nQO+e52Fow349vaX0Q/PIcX6Zhk4GGBgp3qqZ8PVkpC+cuehRctMf3+6+FgQ8jCEFQ==", + "cpu": [ + "x64" + ], "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-transforms": "^8.0.1", - "@babel/helper-plugin-utils": "^8.0.1" - }, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "node": ">=14.21.3" } }, - "node_modules/@babel/plugin-transform-named-capturing-groups-regex": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-8.0.1.tgz", - "integrity": "sha512-zCHu+Jr2gTdJE48lN9SV/kXueCW2M79mKtKJc/ttfzzr/jvgdQdCd17RADMqFRQc/25MLxdtjTmlD0HSAMOlIQ==", + "node_modules/@biomejs/cli-linux-x64-musl": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.4.11.tgz", + "integrity": "sha512-bexd2IklK7ZgPhrz6jXzpIL6dEAH9MlJU1xGTrypx+FICxrXUp4CqtwfiuoDKse+UlgAlWtzML3jrMqeEAHEhA==", + "cpu": [ + "x64" + ], "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^8.0.1", - "@babel/helper-plugin-utils": "^8.0.1" - }, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "node": ">=14.21.3" } }, - "node_modules/@babel/plugin-transform-new-target": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-new-target/-/plugin-transform-new-target-8.0.1.tgz", - "integrity": "sha512-QSQxVg1x4PuOuhWUs4Y9u+x9Y+ER8z6G3tC+bDLBzvoOrNLJrEBQLRnwrTP8e5klihAw6Z+e9X5RjdAKcAGapA==", + "node_modules/@biomejs/cli-win32-arm64": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.4.11.tgz", + "integrity": "sha512-RJhaTnY8byzxDt4bDVb7AFPHkPcjOPK3xBip4ZRTrN3TEfyhjLRm3r3mqknqydgVTB74XG8l4jMLwEACEeihVg==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "node": ">=14.21.3" } }, - "node_modules/@babel/plugin-transform-nullish-coalescing-operator": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-8.0.1.tgz", - "integrity": "sha512-AgCJAmQLF7+PtsK79wJqr4xJ2StHCXlz7JL5CVFP4HejJx25Tk6yl1ZrXvi0cKh3VGDVnfVxefxnrpsBirgpyQ==", + "node_modules/@biomejs/cli-win32-x64": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.4.11.tgz", + "integrity": "sha512-A8D3JM/00C2KQgUV3oj8Ba15EHEYwebAGCy5Sf9GAjr5Y3+kJIYOiESoqRDeuRZueuMdCsbLZIUqmPhpYXJE9A==", + "cpu": [ + "x64" + ], "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "node": ">=14.21.3" } }, - "node_modules/@babel/plugin-transform-numeric-separator": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-numeric-separator/-/plugin-transform-numeric-separator-8.0.1.tgz", - "integrity": "sha512-it2DmUyLIA1GQUXlFDEnI+/G89mTgxndnAiZYpW8xYR6LboblfirMqiWJeTna5uypQJg7viTT4D1iEURRtFcfw==", - "dev": true, + "node_modules/@codemirror/autocomplete": { + "version": "6.20.3", + "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz", + "integrity": "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.17.0", + "@lezer/common": "^1.0.0" } }, - "node_modules/@babel/plugin-transform-object-rest-spread": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-rest-spread/-/plugin-transform-object-rest-spread-8.0.1.tgz", - "integrity": "sha512-VmxkDu6bBdbxRzqn6E93hYucug4OVa6svSO19W//vVzNUGAmQzk3QRyHyyEtfcjSLR3NWfRsWwVM9zExLmd+2w==", + "node_modules/@codemirror/buildhelper": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@codemirror/buildhelper/-/buildhelper-1.0.2.tgz", + "integrity": "sha512-aVewtDPZptq9dTvYqIjpu9HTEmMaKAE4VL22z5E1ycgY5e1LdAiRd5YYjqzQeqLjxpWsHy+emO3n5UUcxpUmSg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-compilation-targets": "^8.0.0", - "@babel/helper-plugin-utils": "^8.0.1", - "@babel/plugin-transform-destructuring": "^8.0.1", - "@babel/plugin-transform-parameters": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" + "@lezer/generator": "^1.0.0", + "@marijn/buildtool": "^1.0.0", + "@marijn/testtool": "^0.1.3" }, - "peerDependencies": { - "@babel/core": "^8.0.0" + "bin": { + "cm-buildhelper": "bin/cm-buildhelper.js", + "cm-runtests": "bin/cm-runtests.js" } }, - "node_modules/@babel/plugin-transform-object-super": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-8.0.1.tgz", - "integrity": "sha512-fDkPXRTRKGm25bAq01q82UM4ypPqdVXCwphUUm4t1dL01fGIG0v8KRvT+4BjhMAtRxtPuI34t5Vs7yjRgs3ZgQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1", - "@babel/helper-replace-supers": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-optional-catch-binding": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-catch-binding/-/plugin-transform-optional-catch-binding-8.0.1.tgz", - "integrity": "sha512-b2OQ74uGliyATcasTjxGy2O/86UI/n+EN4juB4EMfEwTi9j9uq70PuP0L8fW77vfRY66gO/YoTo/WbIdQ/Si1g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-optional-chaining": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-8.0.1.tgz", - "integrity": "sha512-WtRS1c94lZGpGHxYLXMEWeoMVcuv8nkiyr8BTs6OYZv7N3Y9xVE8nbdFIl4lDJH6aH8/pLhqAQOL69d/WI9WdA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1", - "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-parameters": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-8.0.1.tgz", - "integrity": "sha512-IIwRqroW0CYQwR6+3pnmu27z+H98poScWdnov8z6osumMeEsFxAFBBsDS2CFk2jFpPlGqVr89jK/HXO6i5DzxQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-private-methods": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-8.0.1.tgz", - "integrity": "sha512-TrFCGcXaVDh6S5IRhmLSRTY9H80VTCMQWnZtzBRg4RWg3KCLmdmsmj4M15kZAPZfoPkWL/SJb4em3Py/vOiX8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-create-class-features-plugin": "^8.0.1", - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-private-property-in-object": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-8.0.1.tgz", - "integrity": "sha512-e+yfOqSYBZaf3PARpiQkjZrpWYgmcFLhK+1tevh2CpHR1O9/36IdyPnAZusESX5nzVV/XZTDAtQBRLa8HPT5Dw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-annotate-as-pure": "^8.0.0", - "@babel/helper-create-class-features-plugin": "^8.0.1", - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-property-literals": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-8.0.1.tgz", - "integrity": "sha512-Z/qx4cxUtYR1nt7XWRutObPxDks98fEYsjWbVeKEqZH6y3AGknmgzCqmHf2FHWZCl1DfoPeuJY+3hZ+35D+2tg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-regenerator": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-8.0.2.tgz", - "integrity": "sha512-aFfsjCRYducRV4dPnpsBbdRkLjboca9FVDg6HZCgy0Ahvk2ZQ/2exmCRC5qS9P6rsWwrmIheNaIM6A1j2F8KMA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-regexp-modifiers": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regexp-modifiers/-/plugin-transform-regexp-modifiers-8.0.1.tgz", - "integrity": "sha512-02ITRDBesPdTYU0oShAzERwEPzozOUQSXlz3qrt8JGuhalBJQv9z5NjgHJPC9sS3Fsam8gDtfAEpBnqZwUIdjQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^8.0.1", - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-reserved-words": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-8.0.1.tgz", - "integrity": "sha512-+aykZi7ZP3U84veqfJXm3HhPZGddWFi64g7jr0ni6tb1zel+1ey+SL+IRKPoZXFyFqvYEsoqrmx4PyEJRlHl/Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-runtime": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-8.0.1.tgz", - "integrity": "sha512-MPDpKBrxn+thQay3eJmUiSeHswiT7MkINb48hHkX6OzodB149PKq1kred+lpMebrDzHA+G1ekCQnlYSkyEqAOw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-imports": "^8.0.0", - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-shorthand-properties": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-8.0.1.tgz", - "integrity": "sha512-JddANd9yPVH8dYgVoNkqAH5BftnsDxFpG51Zas7sc6F3poz5QWcejHNGO8a/57IX5ByjGSzEmYk9Z7ZMa5MWaw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-spread": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-8.0.1.tgz", - "integrity": "sha512-O9Bw9FyxlSw1SlMg3S82/GKNZ0x77RPbHezotEy1JTlIM/vk6WO8jW1iF+iTiKLOXNvi+b+LZ9t77Gi+Q0FhGg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1", - "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-sticky-regex": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-8.0.1.tgz", - "integrity": "sha512-IsVP6WrZZQdaG2zLmeKwWiI+ua2NB5L1+f77C2/8z2NCDz7uxlIA/lnwocYOJk9PXcOC2sZgRls3LN4XpNduzQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-template-literals": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-8.0.1.tgz", - "integrity": "sha512-JXvtj5+BJA9Qv3prDzW2z2DkGTJNmG0BObTdUD03STiu1Jr4fNQkQy3hYZgPL46a2RjcuhwBMYf49BOuJ98gnA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-typeof-symbol": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-8.0.1.tgz", - "integrity": "sha512-+wJoxgxP2gtey0UMUOMhzMMji2XHO/Uu6MXUh/r5Yhc2jngKzK/wFxY2WNe4UCaRcMvCb4gcnB8wIgFXJsocXg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-typescript": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-8.0.1.tgz", - "integrity": "sha512-0Svqp3413Eg0GElldykF/T7SNsxQO5YVGD70fZyAdZTnX8WRgcopmbiU7GTa5xY5ZnJcEpNbfns8/GjX+/1yeA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-annotate-as-pure": "^8.0.0", - "@babel/helper-create-class-features-plugin": "^8.0.1", - "@babel/helper-plugin-utils": "^8.0.1", - "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0", - "@babel/plugin-syntax-typescript": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-unicode-escapes": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-escapes/-/plugin-transform-unicode-escapes-8.0.1.tgz", - "integrity": "sha512-TAXJepIJ6vZphytTwcf+LuXi2M2ZWI43VCqNw+1ZZLPP/38Z1A8j4Mahvg8kqDgMOSM/cakk+hedTJCiw3jQuQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-unicode-property-regex": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-property-regex/-/plugin-transform-unicode-property-regex-8.0.1.tgz", - "integrity": "sha512-zjBN9tSMSuomNDfurL69Gf7+v4D2t5uI1mSZaYJDo88SKpbduhCXqtxH7Tx66iCF6caWYwnBzSM0tnCozmQq5Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^8.0.1", - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-unicode-regex": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-8.0.1.tgz", - "integrity": "sha512-v0oO83cvT5lwbcIVRShpx4vaHD8AvM9IBowsQuTeP+kGmhh3recJQs33Bl6dlo3/2g9amlznLbFGn4VJbPCJqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^8.0.1", - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/plugin-transform-unicode-sets-regex": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-8.0.1.tgz", - "integrity": "sha512-MlQeyS0K7gh0XNeLBMS/3Z07HjDOKhA7xm2L18GyxOXyiFHI9E+ZuQ4mFYmcLjluXsE/Wf6dABIqZvKpKw0Z3w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^8.0.1", - "@babel/helper-plugin-utils": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/preset-env": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-8.0.2.tgz", - "integrity": "sha512-CUGLn9hNBCF/eXnwdFAWERbniCcXCRvnKwLV9fegeUEIqv7YlU2MepsWMMM54GcILx5XYMnRh+JAL+K5G+mK6g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/compat-data": "^8.0.0", - "@babel/helper-compilation-targets": "^8.0.0", - "@babel/helper-plugin-utils": "^8.0.1", - "@babel/helper-validator-option": "^8.0.0", - "@babel/plugin-bugfix-firefox-class-in-computed-class-key": "^8.0.1", - "@babel/plugin-bugfix-safari-class-field-initializer-scope": "^8.0.1", - "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^8.0.1", - "@babel/plugin-bugfix-safari-rest-destructuring-rhs-array": "^8.0.1", - "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^8.0.1", - "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": "^8.0.1", - "@babel/plugin-transform-arrow-functions": "^8.0.1", - "@babel/plugin-transform-async-generator-functions": "^8.0.1", - "@babel/plugin-transform-async-to-generator": "^8.0.1", - "@babel/plugin-transform-block-scoped-functions": "^8.0.1", - "@babel/plugin-transform-block-scoping": "^8.0.1", - "@babel/plugin-transform-class-properties": "^8.0.1", - "@babel/plugin-transform-class-static-block": "^8.0.1", - "@babel/plugin-transform-classes": "^8.0.1", - "@babel/plugin-transform-computed-properties": "^8.0.1", - "@babel/plugin-transform-destructuring": "^8.0.1", - "@babel/plugin-transform-dotall-regex": "^8.0.1", - "@babel/plugin-transform-duplicate-keys": "^8.0.1", - "@babel/plugin-transform-duplicate-named-capturing-groups-regex": "^8.0.1", - "@babel/plugin-transform-dynamic-import": "^8.0.1", - "@babel/plugin-transform-explicit-resource-management": "^8.0.1", - "@babel/plugin-transform-exponentiation-operator": "^8.0.1", - "@babel/plugin-transform-export-namespace-from": "^8.0.1", - "@babel/plugin-transform-for-of": "^8.0.1", - "@babel/plugin-transform-function-name": "^8.0.1", - "@babel/plugin-transform-json-strings": "^8.0.1", - "@babel/plugin-transform-literals": "^8.0.1", - "@babel/plugin-transform-logical-assignment-operators": "^8.0.1", - "@babel/plugin-transform-member-expression-literals": "^8.0.1", - "@babel/plugin-transform-modules-amd": "^8.0.1", - "@babel/plugin-transform-modules-commonjs": "^8.0.1", - "@babel/plugin-transform-modules-systemjs": "^8.0.1", - "@babel/plugin-transform-modules-umd": "^8.0.1", - "@babel/plugin-transform-named-capturing-groups-regex": "^8.0.1", - "@babel/plugin-transform-new-target": "^8.0.1", - "@babel/plugin-transform-nullish-coalescing-operator": "^8.0.1", - "@babel/plugin-transform-numeric-separator": "^8.0.1", - "@babel/plugin-transform-object-rest-spread": "^8.0.1", - "@babel/plugin-transform-object-super": "^8.0.1", - "@babel/plugin-transform-optional-catch-binding": "^8.0.1", - "@babel/plugin-transform-optional-chaining": "^8.0.1", - "@babel/plugin-transform-parameters": "^8.0.1", - "@babel/plugin-transform-private-methods": "^8.0.1", - "@babel/plugin-transform-private-property-in-object": "^8.0.1", - "@babel/plugin-transform-property-literals": "^8.0.1", - "@babel/plugin-transform-regenerator": "^8.0.2", - "@babel/plugin-transform-regexp-modifiers": "^8.0.1", - "@babel/plugin-transform-reserved-words": "^8.0.1", - "@babel/plugin-transform-shorthand-properties": "^8.0.1", - "@babel/plugin-transform-spread": "^8.0.1", - "@babel/plugin-transform-sticky-regex": "^8.0.1", - "@babel/plugin-transform-template-literals": "^8.0.1", - "@babel/plugin-transform-typeof-symbol": "^8.0.1", - "@babel/plugin-transform-unicode-escapes": "^8.0.1", - "@babel/plugin-transform-unicode-property-regex": "^8.0.1", - "@babel/plugin-transform-unicode-regex": "^8.0.1", - "@babel/plugin-transform-unicode-sets-regex": "^8.0.1", - "@babel/preset-modules": "^0.2.0", - "babel-plugin-polyfill-corejs3": "^1.0.0", - "core-js-compat": "^3.48.0", - "semver": "^7.7.3" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/preset-env/node_modules/semver": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.4.tgz", - "integrity": "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@babel/preset-modules": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/@babel/preset-modules/-/preset-modules-0.2.0.tgz", - "integrity": "sha512-yz0RBN2fx4fjCeFcTWsWgL7PxSRltvTa0Qg14HkWCU3qS8MO7ZSJlBVbGceynd5C9NsJwwUHNQD3dc6tYO+jqQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1", - "@babel/plugin-transform-dotall-regex": "^8.0.1", - "@babel/plugin-transform-unicode-property-regex": "^8.0.1", - "@babel/types": "^8.0.0", - "esutils": "^2.0.2" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/preset-modules/node_modules/@babel/helper-string-parser": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz", - "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, - "node_modules/@babel/preset-modules/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.4", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.4.tgz", - "integrity": "sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, - "node_modules/@babel/preset-modules/node_modules/@babel/types": { - "version": "8.0.4", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.4.tgz", - "integrity": "sha512-eY+Yn3dCqTGmyiq2QRU66lA5FL8lqqqvecHt0fF3uHONIa7ToYsaCiWV8lOKqAs0Rb2SjixiKFROngnulPtt2g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^8.0.0", - "@babel/helper-validator-identifier": "^8.0.4" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, - "node_modules/@babel/preset-typescript": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-8.0.1.tgz", - "integrity": "sha512-qrPhQIN1NLrPmzgazF9XKQqXrOcp/WJly+K+6ReFonn24FZqRJO7clxOJo6Ni75L+2vAqI3cHVU2OJLBxoPp5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^8.0.1", - "@babel/helper-validator-option": "^8.0.0", - "@babel/plugin-transform-modules-commonjs": "^8.0.1", - "@babel/plugin-transform-typescript": "^8.0.1" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - }, - "peerDependencies": { - "@babel/core": "^8.0.0" - } - }, - "node_modules/@babel/runtime": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz", - "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/runtime-corejs3": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.29.7.tgz", - "integrity": "sha512-ppj9ouYku+RX0ljtgZd+KMO5mkM2bCqg8H2PYAFWnLsHEIKIdRojqbJ2i3eVHrisuxy7nOFCmngTDdWtUCdXUQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "core-js-pure": "^3.48.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/template": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", - "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/parser": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/traverse": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz", - "integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.8", - "@babel/helper-globals": "^7.29.7", - "@babel/parser": "^7.29.8", - "@babel/template": "^7.29.7", - "@babel/types": "^7.29.8", - "debug": "^4.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/types": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", - "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^7.29.7", - "@babel/helper-validator-identifier": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@bazel/runfiles": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/@bazel/runfiles/-/runfiles-6.5.0.tgz", - "integrity": "sha512-RzahvqTkfpY2jsDxo8YItPX+/iZ6hbiikw1YhE0bA9EKBR5Og8Pa6FHn9PO9M0zaXRVsr0GFQLKbB/0rzy9SzA==", - "dev": true, - "license": "Apache-2.0" - }, - "node_modules/@biomejs/biome": { - "version": "2.4.11", - "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.4.11.tgz", - "integrity": "sha512-nWxHX8tf3Opb/qRgZpBbsTOqOodkbrkJ7S+JxJAruxOReaDPPmPuLBAGQ8vigyUgo0QBB+oQltNEAvalLcjggA==", - "dev": true, - "license": "MIT OR Apache-2.0", - "bin": { - "biome": "bin/biome" - }, - "engines": { - "node": ">=14.21.3" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/biome" - }, - "optionalDependencies": { - "@biomejs/cli-darwin-arm64": "2.4.11", - "@biomejs/cli-darwin-x64": "2.4.11", - "@biomejs/cli-linux-arm64": "2.4.11", - "@biomejs/cli-linux-arm64-musl": "2.4.11", - "@biomejs/cli-linux-x64": "2.4.11", - "@biomejs/cli-linux-x64-musl": "2.4.11", - "@biomejs/cli-win32-arm64": "2.4.11", - "@biomejs/cli-win32-x64": "2.4.11" - } - }, - "node_modules/@biomejs/cli-darwin-arm64": { - "version": "2.4.11", - "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.4.11.tgz", - "integrity": "sha512-wOt+ed+L2dgZanWyL6i29qlXMc088N11optzpo10peayObBaAshbTcxKUchzEMp9QSY8rh5h6VfAFE3WTS1rqg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-darwin-x64": { - "version": "2.4.11", - "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.4.11.tgz", - "integrity": "sha512-gZ6zR8XmZlExfi/Pz/PffmdpWOQ8Qhy7oBztgkR8/ylSRyLwfRPSadmiVCV8WQ8PoJ2MWUy2fgID9zmtgUUJmw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-arm64": { - "version": "2.4.11", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.4.11.tgz", - "integrity": "sha512-avdJaEElXrKceK0va9FkJ4P5ci3N01TGkc6ni3P8l3BElqbOz42Wg2IyX3gbh0ZLEd4HVKEIrmuVu/AMuSeFFA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-arm64-musl": { - "version": "2.4.11", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.4.11.tgz", - "integrity": "sha512-+Sbo1OAmlegtdwqFE8iOxFIWLh1B3OEgsuZfBpyyN/kWuqZ8dx9ZEes6zVnDMo+zRHF2wLynRVhoQmV7ohxl2Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-x64": { - "version": "2.4.11", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.4.11.tgz", - "integrity": "sha512-TagWV0iomp5LnEnxWFg4nQO+e52Fow349vaX0Q/PIcX6Zhk4GGBgp3qqZ8PVkpC+cuehRctMf3+6+FgQ8jCEFQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-x64-musl": { - "version": "2.4.11", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.4.11.tgz", - "integrity": "sha512-bexd2IklK7ZgPhrz6jXzpIL6dEAH9MlJU1xGTrypx+FICxrXUp4CqtwfiuoDKse+UlgAlWtzML3jrMqeEAHEhA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-win32-arm64": { - "version": "2.4.11", - "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.4.11.tgz", - "integrity": "sha512-RJhaTnY8byzxDt4bDVb7AFPHkPcjOPK3xBip4ZRTrN3TEfyhjLRm3r3mqknqydgVTB74XG8l4jMLwEACEeihVg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-win32-x64": { - "version": "2.4.11", - "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.4.11.tgz", - "integrity": "sha512-A8D3JM/00C2KQgUV3oj8Ba15EHEYwebAGCy5Sf9GAjr5Y3+kJIYOiESoqRDeuRZueuMdCsbLZIUqmPhpYXJE9A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@codemirror/autocomplete": { - "version": "6.20.3", - "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz", - "integrity": "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==", - "license": "MIT", - "dependencies": { - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.17.0", - "@lezer/common": "^1.0.0" - } - }, - "node_modules/@codemirror/buildhelper": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@codemirror/buildhelper/-/buildhelper-1.0.2.tgz", - "integrity": "sha512-aVewtDPZptq9dTvYqIjpu9HTEmMaKAE4VL22z5E1ycgY5e1LdAiRd5YYjqzQeqLjxpWsHy+emO3n5UUcxpUmSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@lezer/generator": "^1.0.0", - "@marijn/buildtool": "^1.0.0", - "@marijn/testtool": "^0.1.3" - }, - "bin": { - "cm-buildhelper": "bin/cm-buildhelper.js", - "cm-runtests": "bin/cm-runtests.js" - } - }, - "node_modules/@codemirror/commands": { - "version": "6.11.0", - "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.0.tgz", - "integrity": "sha512-/K4Rl5BN0OtTiPWmJCdqODu38XnDMsDxKY5rgrPnCkutPTJf2wVbkoixLfealF5Kwse/s8P8M5jAiURiwSwnFA==", - "license": "MIT", - "dependencies": { - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.7.0", - "@codemirror/view": "^6.27.0", - "@lezer/common": "^1.1.0" - } - }, - "node_modules/@codemirror/lang-angular": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/@codemirror/lang-angular/-/lang-angular-0.1.4.tgz", - "integrity": "sha512-oap+gsltb/fzdlTQWD6BFF4bSLKcDnlxDsLdePiJpCVNKWXSTAbiiQeYI3UmES+BLAdkmIC1WjyztC1pi/bX4g==", - "license": "MIT", - "dependencies": { - "@codemirror/lang-html": "^6.0.0", - "@codemirror/lang-javascript": "^6.1.2", - "@codemirror/language": "^6.0.0", - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.3.3" - } - }, - "node_modules/@codemirror/lang-cpp": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/@codemirror/lang-cpp/-/lang-cpp-6.0.3.tgz", - "integrity": "sha512-URM26M3vunFFn9/sm6rzqrBzDgfWuDixp85uTY49wKudToc2jTHUrKIGGKs+QWND+YLofNNZpxcNGRynFJfvgA==", - "license": "MIT", - "dependencies": { - "@codemirror/language": "^6.0.0", - "@lezer/cpp": "^1.0.0" - } - }, - "node_modules/@codemirror/lang-css": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz", - "integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==", - "license": "MIT", - "dependencies": { - "@codemirror/autocomplete": "^6.0.0", - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@lezer/common": "^1.0.2", - "@lezer/css": "^1.1.7" - } - }, - "node_modules/@codemirror/lang-go": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/@codemirror/lang-go/-/lang-go-6.0.1.tgz", - "integrity": "sha512-7fNvbyNylvqCphW9HD6WFnRpcDjr+KXX/FgqXy5H5ZS0eC5edDljukm/yNgYkwTsgp2busdod50AOTIy6Jikfg==", - "license": "MIT", - "dependencies": { - "@codemirror/autocomplete": "^6.0.0", - "@codemirror/language": "^6.6.0", - "@codemirror/state": "^6.0.0", - "@lezer/common": "^1.0.0", - "@lezer/go": "^1.0.0" - } - }, - "node_modules/@codemirror/lang-html": { - "version": "6.4.12", - "resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.12.tgz", - "integrity": "sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==", - "license": "MIT", - "dependencies": { - "@codemirror/autocomplete": "^6.0.0", - "@codemirror/lang-css": "^6.0.0", - "@codemirror/lang-javascript": "^6.0.0", - "@codemirror/language": "^6.4.0", - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.17.0", - "@lezer/common": "^1.0.0", - "@lezer/css": "^1.1.0", - "@lezer/html": "^1.3.12" - } - }, - "node_modules/@codemirror/lang-java": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/@codemirror/lang-java/-/lang-java-6.0.2.tgz", - "integrity": "sha512-m5Nt1mQ/cznJY7tMfQTJchmrjdjQ71IDs+55d1GAa8DGaB8JXWsVCkVT284C3RTASaY43YknrK2X3hPO/J3MOQ==", - "license": "MIT", - "dependencies": { - "@codemirror/language": "^6.0.0", - "@lezer/java": "^1.0.0" - } - }, - "node_modules/@codemirror/lang-javascript": { - "version": "6.2.5", - "resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz", - "integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==", - "license": "MIT", - "dependencies": { - "@codemirror/autocomplete": "^6.0.0", - "@codemirror/language": "^6.6.0", - "@codemirror/lint": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.17.0", - "@lezer/common": "^1.0.0", - "@lezer/javascript": "^1.0.0" - } - }, - "node_modules/@codemirror/lang-jinja": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/@codemirror/lang-jinja/-/lang-jinja-6.0.1.tgz", - "integrity": "sha512-P5kyHLObzjtbGj16h+hyvZTxJhSjBEeSx4wMjbnAf3b0uwTy2+F0zGjMZL4PQOm/mh2eGZ5xUDVZXgwP783Nsw==", - "license": "MIT", - "dependencies": { - "@codemirror/autocomplete": "^6.0.0", - "@codemirror/lang-html": "^6.0.0", - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0", - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.2.0", - "@lezer/lr": "^1.4.0" - } - }, - "node_modules/@codemirror/lang-json": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/@codemirror/lang-json/-/lang-json-6.0.2.tgz", - "integrity": "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==", - "license": "MIT", - "dependencies": { - "@codemirror/language": "^6.0.0", - "@lezer/json": "^1.0.0" - } - }, - "node_modules/@codemirror/lang-less": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/@codemirror/lang-less/-/lang-less-6.0.2.tgz", - "integrity": "sha512-EYdQTG22V+KUUk8Qq582g7FMnCZeEHsyuOJisHRft/mQ+ZSZ2w51NupvDUHiqtsOy7It5cHLPGfHQLpMh9bqpQ==", - "license": "MIT", - "dependencies": { - "@codemirror/lang-css": "^6.2.0", - "@codemirror/language": "^6.0.0", - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0" - } - }, - "node_modules/@codemirror/lang-liquid": { - "version": "6.3.2", - "resolved": "https://registry.npmjs.org/@codemirror/lang-liquid/-/lang-liquid-6.3.2.tgz", - "integrity": "sha512-6PDVU3ZnfeYyz1at1E/ttorErZvZFXXt1OPhtfe1EZJ2V2iDFa0CwPqPgG5F7NXN0yONGoBogKmFAafKTqlwIw==", - "license": "MIT", - "dependencies": { - "@codemirror/autocomplete": "^6.0.0", - "@codemirror/lang-html": "^6.0.0", - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0", - "@lezer/common": "^1.0.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.3.1" - } - }, - "node_modules/@codemirror/lang-markdown": { - "version": "6.5.2", - "resolved": "https://registry.npmjs.org/@codemirror/lang-markdown/-/lang-markdown-6.5.2.tgz", - "integrity": "sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw==", - "license": "MIT", - "dependencies": { - "@codemirror/autocomplete": "^6.7.1", - "@codemirror/lang-html": "^6.0.0", - "@codemirror/language": "^6.3.0", - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0", - "@lezer/common": "^1.2.1", - "@lezer/markdown": "^1.0.0" - } - }, - "node_modules/@codemirror/lang-php": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/@codemirror/lang-php/-/lang-php-6.0.2.tgz", - "integrity": "sha512-ZKy2v1n8Fc8oEXj0Th0PUMXzQJ0AIR6TaZU+PbDHExFwdu+guzOA4jmCHS1Nz4vbFezwD7LyBdDnddSJeScMCA==", - "license": "MIT", - "dependencies": { - "@codemirror/lang-html": "^6.0.0", - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@lezer/common": "^1.0.0", - "@lezer/php": "^1.0.0" - } - }, - "node_modules/@codemirror/lang-python": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.2.1.tgz", - "integrity": "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw==", - "license": "MIT", - "dependencies": { - "@codemirror/autocomplete": "^6.3.2", - "@codemirror/language": "^6.8.0", - "@codemirror/state": "^6.0.0", - "@lezer/common": "^1.2.1", - "@lezer/python": "^1.1.4" - } - }, - "node_modules/@codemirror/lang-rust": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/@codemirror/lang-rust/-/lang-rust-6.0.2.tgz", - "integrity": "sha512-EZaGjCUegtiU7kSMvOfEZpaCReowEf3yNidYu7+vfuGTm9ow4mthAparY5hisJqOHmJowVH3Upu+eJlUji6qqA==", - "license": "MIT", - "dependencies": { - "@codemirror/language": "^6.0.0", - "@lezer/rust": "^1.0.0" - } - }, - "node_modules/@codemirror/lang-sass": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/@codemirror/lang-sass/-/lang-sass-6.0.2.tgz", - "integrity": "sha512-l/bdzIABvnTo1nzdY6U+kPAC51czYQcOErfzQ9zSm9D8GmNPD0WTW8st/CJwBTPLO8jlrbyvlSEcN20dc4iL0Q==", - "license": "MIT", - "dependencies": { - "@codemirror/lang-css": "^6.2.0", - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@lezer/common": "^1.0.2", - "@lezer/sass": "^1.0.0" - } - }, - "node_modules/@codemirror/lang-sql": { - "version": "6.10.0", - "resolved": "https://registry.npmjs.org/@codemirror/lang-sql/-/lang-sql-6.10.0.tgz", - "integrity": "sha512-6ayPkEd/yRw0XKBx5uAiToSgGECo/GY2NoJIHXIIQh1EVwLuKoU8BP/qK0qH5NLXAbtJRLuT73hx7P9X34iO4w==", - "license": "MIT", - "dependencies": { - "@codemirror/autocomplete": "^6.0.0", - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0" - } - }, - "node_modules/@codemirror/lang-vue": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@codemirror/lang-vue/-/lang-vue-0.1.3.tgz", - "integrity": "sha512-QSKdtYTDRhEHCfo5zOShzxCmqKJvgGrZwDQSdbvCRJ5pRLWBS7pD/8e/tH44aVQT6FKm0t6RVNoSUWHOI5vNug==", - "license": "MIT", - "dependencies": { - "@codemirror/lang-html": "^6.0.0", - "@codemirror/lang-javascript": "^6.1.2", - "@codemirror/language": "^6.0.0", - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.3.1" - } - }, - "node_modules/@codemirror/lang-wast": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/@codemirror/lang-wast/-/lang-wast-6.0.2.tgz", - "integrity": "sha512-Imi2KTpVGm7TKuUkqyJ5NRmeFWF7aMpNiwHnLQe0x9kmrxElndyH0K6H/gXtWwY6UshMRAhpENsgfpSwsgmC6Q==", - "license": "MIT", - "dependencies": { - "@codemirror/language": "^6.0.0", - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0" - } - }, - "node_modules/@codemirror/lang-xml": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/@codemirror/lang-xml/-/lang-xml-6.1.0.tgz", - "integrity": "sha512-3z0blhicHLfwi2UgkZYRPioSgVTo9PV5GP5ducFH6FaHy0IAJRg+ixj5gTR1gnT/glAIC8xv4w2VL1LoZfs+Jg==", - "license": "MIT", - "dependencies": { - "@codemirror/autocomplete": "^6.0.0", - "@codemirror/language": "^6.4.0", - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0", - "@lezer/common": "^1.0.0", - "@lezer/xml": "^1.0.0" - } - }, - "node_modules/@codemirror/lang-yaml": { - "version": "6.1.3", - "resolved": "https://registry.npmjs.org/@codemirror/lang-yaml/-/lang-yaml-6.1.3.tgz", - "integrity": "sha512-AZ8DJBuXGVHybpBQhmZtgew5//4hv3tdkXnr3vDmOUMJRuB6vn/uuwtmTOTlqEaQFg3hQSVeA90NmvIQyUV6FQ==", - "license": "MIT", - "dependencies": { - "@codemirror/autocomplete": "^6.0.0", - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.2.0", - "@lezer/lr": "^1.0.0", - "@lezer/yaml": "^1.0.0" - } - }, - "node_modules/@codemirror/language": { - "version": "6.13.1", - "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.13.1.tgz", - "integrity": "sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==", - "license": "MIT", - "dependencies": { - "@codemirror/state": "^6.0.0", - "@codemirror/streamparser": "^6.0.0", - "@codemirror/view": "^6.23.0", - "@lezer/common": "^1.5.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0", - "style-mod": "^4.0.0" - } - }, - "node_modules/@codemirror/language-data": { - "version": "6.5.2", - "resolved": "https://registry.npmjs.org/@codemirror/language-data/-/language-data-6.5.2.tgz", - "integrity": "sha512-CPkWBKrNS8stYbEU5kwBwTf3JB1kghlbh4FSAwzGW2TEscdeHHH4FGysREW86Mqnj3Qn09s0/6Ea/TutmoTobg==", - "license": "MIT", - "dependencies": { - "@codemirror/lang-angular": "^0.1.0", - "@codemirror/lang-cpp": "^6.0.0", - "@codemirror/lang-css": "^6.0.0", - "@codemirror/lang-go": "^6.0.0", - "@codemirror/lang-html": "^6.0.0", - "@codemirror/lang-java": "^6.0.0", - "@codemirror/lang-javascript": "^6.0.0", - "@codemirror/lang-jinja": "^6.0.0", - "@codemirror/lang-json": "^6.0.0", - "@codemirror/lang-less": "^6.0.0", - "@codemirror/lang-liquid": "^6.0.0", - "@codemirror/lang-markdown": "^6.0.0", - "@codemirror/lang-php": "^6.0.0", - "@codemirror/lang-python": "^6.0.0", - "@codemirror/lang-rust": "^6.0.0", - "@codemirror/lang-sass": "^6.0.0", - "@codemirror/lang-sql": "^6.0.0", - "@codemirror/lang-vue": "^0.1.1", - "@codemirror/lang-wast": "^6.0.0", - "@codemirror/lang-xml": "^6.0.0", - "@codemirror/lang-yaml": "^6.0.0", - "@codemirror/language": "^6.0.0", - "@codemirror/legacy-modes": "^6.4.0" - } - }, - "node_modules/@codemirror/legacy-modes": { - "version": "6.5.3", - "resolved": "https://registry.npmjs.org/@codemirror/legacy-modes/-/legacy-modes-6.5.3.tgz", - "integrity": "sha512-xCsmIzH78MyWkib9jlPaaun57XNkfbMIhagfaZVd0iLTqlpw3jXaIcbZm72MTmmn64eTZpBVNjbyYh+QXnxRsg==", - "license": "MIT", - "dependencies": { - "@codemirror/language": "^6.0.0" - } - }, - "node_modules/@codemirror/lint": { - "version": "6.9.7", - "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz", - "integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==", - "license": "MIT", - "dependencies": { - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.42.0", - "crelt": "^1.0.5" - } - }, - "node_modules/@codemirror/lsp-client": { - "resolved": "codemirror-lsp-client", - "link": true - }, - "node_modules/@codemirror/search": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.7.1.tgz", - "integrity": "sha512-uMe5UO6PamJtSHrXhhHOzSX3ReWtiJrva6GnPMwSOrZtiExb5X5eExhr2OUZQVvdxPsKpY3Ro2mFbQadpPWmHA==", - "license": "MIT", - "dependencies": { - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.37.0", - "crelt": "^1.0.5" - } - }, - "node_modules/@codemirror/state": { - "version": "6.7.6", - "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz", - "integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==", - "license": "MIT", - "dependencies": { - "@marijn/find-cluster-break": "^1.0.0" - } - }, - "node_modules/@codemirror/streamparser": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/@codemirror/streamparser/-/streamparser-6.0.0.tgz", - "integrity": "sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==", - "license": "MIT" - }, - "node_modules/@codemirror/theme-one-dark": { - "version": "6.1.3", - "resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz", - "integrity": "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==", - "license": "MIT", - "dependencies": { - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0", - "@lezer/highlight": "^1.0.0" - } - }, - "node_modules/@codemirror/view": { - "version": "6.43.15", - "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.15.tgz", - "integrity": "sha512-HHsfpqFeHyXLs983pSRe38Xajs0vFWZQ2BuX0m7Ki8w3jZ5iD8cuR3lBz2/5/X53Dhf32SBHKh6rtSTB6tKeGw==", - "license": "MIT", - "dependencies": { - "@codemirror/state": "^6.7.0", - "crelt": "^1.0.6", - "style-mod": "^4.1.0", - "w3c-keyname": "^2.2.4" - } - }, - "node_modules/@deadlyjack/ajax": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@deadlyjack/ajax/-/ajax-1.2.6.tgz", - "integrity": "sha512-VwZU8YUflO2/V/dl3dluu+3jg8Ghz/W5fwxD5Z21OZXKeV73d+vStKVBe4wi+Av2KbTR35K7Z+5Q3iIpjB41MA==", - "license": "MIT" - }, - "node_modules/@emmetio/abbreviation": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/@emmetio/abbreviation/-/abbreviation-2.3.3.tgz", - "integrity": "sha512-mgv58UrU3rh4YgbE/TzgLQwJ3pFsHHhCLqY20aJq+9comytTXUDNGG/SMtSeMJdkpxgXSXunBGLD8Boka3JyVA==", - "license": "MIT", - "dependencies": { - "@emmetio/scanner": "^1.0.4" - } - }, - "node_modules/@emmetio/codemirror6-plugin": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/@emmetio/codemirror6-plugin/-/codemirror6-plugin-0.4.1.tgz", - "integrity": "sha512-OwMtvCjYM6XfFREqxNr1rg+MB5FsZh+nLCxsYjFi0ZZTlDJZ2sWAwWHlfJvNJ4H2Q+HQ71tUO0+OUPgUEFG0HQ==", - "dependencies": { - "@emmetio/math-expression": "^1.0.5", - "emmet": "^2.4.11" - }, - "peerDependencies": { - "@codemirror/autocomplete": "^6.17.0", - "@codemirror/commands": "^6.6.0", - "@codemirror/lang-css": "^6.2.1", - "@codemirror/lang-html": "^6.4.9", - "@codemirror/lang-javascript": "^6.2.2", - "@codemirror/language": "^6.10.2", - "@codemirror/state": "^6.4.1", - "@codemirror/view": "^6.29.1" - } - }, - "node_modules/@emmetio/css-abbreviation": { - "version": "2.1.8", - "resolved": "https://registry.npmjs.org/@emmetio/css-abbreviation/-/css-abbreviation-2.1.8.tgz", - "integrity": "sha512-s9yjhJ6saOO/uk1V74eifykk2CBYi01STTK3WlXWGOepyKa23ymJ053+DNQjpFcy1ingpaO7AxCcwLvHFY9tuw==", - "license": "MIT", - "dependencies": { - "@emmetio/scanner": "^1.0.4" - } - }, - "node_modules/@emmetio/math-expression": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@emmetio/math-expression/-/math-expression-1.0.5.tgz", - "integrity": "sha512-qf5SXD/ViS04rXSeDg9CRGM10xLC9dVaKIbMHrrwxYr5LNB/C0rOfokhGSBwnVQKcidLmdRJeNWH1V1tppZ84Q==", - "license": "MIT", - "dependencies": { - "@emmetio/scanner": "^1.0.4" - } - }, - "node_modules/@emmetio/scanner": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@emmetio/scanner/-/scanner-1.0.4.tgz", - "integrity": "sha512-IqRuJtQff7YHHBk4G8YZ45uB9BaAGcwQeVzgj/zj8/UdOhtQpEIupUhSk8dys6spFIWVZVeK20CzGEnqR5SbqA==", - "license": "MIT" - }, - "node_modules/@emnapi/core": { - "version": "1.11.3", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz", - "integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.3", - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/runtime": { - "version": "1.11.3", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", - "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/wasi-threads": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz", - "integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@gar/promise-retry": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@gar/promise-retry/-/promise-retry-1.0.3.tgz", - "integrity": "sha512-GmzA9ckNokPypTg10pgpeHNQe7ph+iIKKmhKu3Ob9ANkswreCx7R3cKmY781K8QK3AqVL3xVh9A42JvIAbkkSA==", - "license": "MIT", - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/@isaacs/fs-minipass": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", - "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", - "license": "ISC", - "dependencies": { - "minipass": "^7.0.4" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@isaacs/string-locale-compare": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@isaacs/string-locale-compare/-/string-locale-compare-1.1.0.tgz", - "integrity": "sha512-SQ7Kzhh9+D+ZW9MA0zkYv3VXhIDNx+LzM6EJ+/65I3QY+enU6Itte7E5XX7EWrqLW2FN4n06GWzBnPoC3th2aQ==", - "license": "ISC" - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.13", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", - "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", - "dev": true, + "node_modules/@codemirror/commands": { + "version": "6.11.1", + "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.1.tgz", + "integrity": "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==", "license": "MIT", "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.0", - "@jridgewell/trace-mapping": "^0.3.24" + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.7.0", + "@codemirror/view": "^6.27.0", + "@lezer/common": "^1.1.0" } }, - "node_modules/@jridgewell/remapping": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", - "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", - "dev": true, + "node_modules/@codemirror/lang-angular": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/@codemirror/lang-angular/-/lang-angular-0.1.4.tgz", + "integrity": "sha512-oap+gsltb/fzdlTQWD6BFF4bSLKcDnlxDsLdePiJpCVNKWXSTAbiiQeYI3UmES+BLAdkmIC1WjyztC1pi/bX4g==", "license": "MIT", "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" + "@codemirror/lang-html": "^6.0.0", + "@codemirror/lang-javascript": "^6.1.2", + "@codemirror/language": "^6.0.0", + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.3.3" } }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, + "node_modules/@codemirror/lang-cpp": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/@codemirror/lang-cpp/-/lang-cpp-6.0.3.tgz", + "integrity": "sha512-URM26M3vunFFn9/sm6rzqrBzDgfWuDixp85uTY49wKudToc2jTHUrKIGGKs+QWND+YLofNNZpxcNGRynFJfvgA==", "license": "MIT", - "engines": { - "node": ">=6.0.0" + "dependencies": { + "@codemirror/language": "^6.0.0", + "@lezer/cpp": "^1.0.0" } }, - "node_modules/@jridgewell/source-map": { - "version": "0.3.11", - "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz", - "integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==", - "dev": true, + "node_modules/@codemirror/lang-css": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz", + "integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==", "license": "MIT", - "peer": true, "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.25" + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@lezer/common": "^1.0.2", + "@lezer/css": "^1.1.7" } }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.31", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", - "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", - "dev": true, + "node_modules/@codemirror/lang-go": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@codemirror/lang-go/-/lang-go-6.0.1.tgz", + "integrity": "sha512-7fNvbyNylvqCphW9HD6WFnRpcDjr+KXX/FgqXy5H5ZS0eC5edDljukm/yNgYkwTsgp2busdod50AOTIy6Jikfg==", "license": "MIT", "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/language": "^6.6.0", + "@codemirror/state": "^6.0.0", + "@lezer/common": "^1.0.0", + "@lezer/go": "^1.0.0" } }, - "node_modules/@lezer/common": { - "version": "1.5.6", - "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.6.tgz", - "integrity": "sha512-NZxu3q49ck+YYbEJPuIPIyFP37XneBvzPIarBHEXBLBVfkZqQieZ/Y2boYnGNYtmjpOZLnAKs/lwqtmDpi365w==", - "license": "MIT" - }, - "node_modules/@lezer/cpp": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@lezer/cpp/-/cpp-1.1.5.tgz", - "integrity": "sha512-DIhSXmYtJKLehrjzDFN+2cPt547ySQ41nA8yqcDf/GxMc+YM736xqltFkvADL2M0VebU5I+3+4ks2Vv+Kyq3Aw==", + "node_modules/@codemirror/lang-html": { + "version": "6.4.12", + "resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.12.tgz", + "integrity": "sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==", "license": "MIT", "dependencies": { - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0" + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/lang-css": "^6.0.0", + "@codemirror/lang-javascript": "^6.0.0", + "@codemirror/language": "^6.4.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.17.0", + "@lezer/common": "^1.0.0", + "@lezer/css": "^1.1.0", + "@lezer/html": "^1.3.12" } }, - "node_modules/@lezer/css": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.3.tgz", - "integrity": "sha512-RzBo8r+/6QJeow7aPHIpGVIH59xTcJXp399820gZoMo9noQDRVpJLheIBUicYwKcsbOYoBRoLZlf2720dG/4Tg==", + "node_modules/@codemirror/lang-java": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@codemirror/lang-java/-/lang-java-6.0.2.tgz", + "integrity": "sha512-m5Nt1mQ/cznJY7tMfQTJchmrjdjQ71IDs+55d1GAa8DGaB8JXWsVCkVT284C3RTASaY43YknrK2X3hPO/J3MOQ==", "license": "MIT", "dependencies": { - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.3.0" + "@codemirror/language": "^6.0.0", + "@lezer/java": "^1.0.0" } }, - "node_modules/@lezer/generator": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@lezer/generator/-/generator-1.8.0.tgz", - "integrity": "sha512-/SF4EDWowPqV1jOgoGSGTIFsE7Ezdr7ZYxyihl5eMKVO5tlnpIhFcDavgm1hHY5GEonoOAEnJ0CU0x+tvuAuUg==", - "dev": true, + "node_modules/@codemirror/lang-javascript": { + "version": "6.2.5", + "resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz", + "integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==", "license": "MIT", "dependencies": { - "@lezer/common": "^1.1.0", - "@lezer/lr": "^1.3.0" - }, - "bin": { - "lezer-generator": "src/lezer-generator.cjs" + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/language": "^6.6.0", + "@codemirror/lint": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.17.0", + "@lezer/common": "^1.0.0", + "@lezer/javascript": "^1.0.0" } }, - "node_modules/@lezer/go": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@lezer/go/-/go-1.0.1.tgz", - "integrity": "sha512-xToRsYxwsgJNHTgNdStpcvmbVuKxTapV0dM0wey1geMMRc9aggoVyKgzYp41D2/vVOx+Ii4hmE206kvxIXBVXQ==", + "node_modules/@codemirror/lang-jinja": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@codemirror/lang-jinja/-/lang-jinja-6.0.1.tgz", + "integrity": "sha512-P5kyHLObzjtbGj16h+hyvZTxJhSjBEeSx4wMjbnAf3b0uwTy2+F0zGjMZL4PQOm/mh2eGZ5xUDVZXgwP783Nsw==", "license": "MIT", "dependencies": { + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/lang-html": "^6.0.0", + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0", "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.3.0" + "@lezer/highlight": "^1.2.0", + "@lezer/lr": "^1.4.0" } }, - "node_modules/@lezer/highlight": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.5.tgz", - "integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==", + "node_modules/@codemirror/lang-json": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@codemirror/lang-json/-/lang-json-6.0.2.tgz", + "integrity": "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==", "license": "MIT", "dependencies": { - "@lezer/common": "^1.3.0" + "@codemirror/language": "^6.0.0", + "@lezer/json": "^1.0.0" } }, - "node_modules/@lezer/html": { - "version": "1.3.13", - "resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz", - "integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==", + "node_modules/@codemirror/lang-less": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@codemirror/lang-less/-/lang-less-6.0.2.tgz", + "integrity": "sha512-EYdQTG22V+KUUk8Qq582g7FMnCZeEHsyuOJisHRft/mQ+ZSZ2w51NupvDUHiqtsOy7It5cHLPGfHQLpMh9bqpQ==", "license": "MIT", "dependencies": { + "@codemirror/lang-css": "^6.2.0", + "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, - "node_modules/@lezer/java": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@lezer/java/-/java-1.1.3.tgz", - "integrity": "sha512-yHquUfujwg6Yu4Fd1GNHCvidIvJwi/1Xu2DaKl/pfWIA2c1oXkVvawH3NyXhCaFx4OdlYBVX5wvz2f7Aoa/4Xw==", + "node_modules/@codemirror/lang-liquid": { + "version": "6.3.3", + "resolved": "https://registry.npmjs.org/@codemirror/lang-liquid/-/lang-liquid-6.3.3.tgz", + "integrity": "sha512-U9EnyzWuAx1TX3MZSKDXydKH734n1Aogk/ijKdW+jdIwmbf9zSPQYOIKggC/b2PTRjQb7ddvMktmxnfTLuv/SQ==", "license": "MIT", "dependencies": { - "@lezer/common": "^1.2.0", + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/lang-html": "^6.0.0", + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0", + "@lezer/common": "^1.0.0", "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0" + "@lezer/lr": "^1.3.1" } }, - "node_modules/@lezer/javascript": { - "version": "1.5.4", - "resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.4.tgz", - "integrity": "sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==", + "node_modules/@codemirror/lang-markdown": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/@codemirror/lang-markdown/-/lang-markdown-6.5.2.tgz", + "integrity": "sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw==", "license": "MIT", "dependencies": { - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.1.3", - "@lezer/lr": "^1.3.0" + "@codemirror/autocomplete": "^6.7.1", + "@codemirror/lang-html": "^6.0.0", + "@codemirror/language": "^6.3.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0", + "@lezer/common": "^1.2.1", + "@lezer/markdown": "^1.0.0" } }, - "node_modules/@lezer/json": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@lezer/json/-/json-1.0.3.tgz", - "integrity": "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==", + "node_modules/@codemirror/lang-php": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@codemirror/lang-php/-/lang-php-6.0.2.tgz", + "integrity": "sha512-ZKy2v1n8Fc8oEXj0Th0PUMXzQJ0AIR6TaZU+PbDHExFwdu+guzOA4jmCHS1Nz4vbFezwD7LyBdDnddSJeScMCA==", "license": "MIT", "dependencies": { - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0" + "@codemirror/lang-html": "^6.0.0", + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@lezer/common": "^1.0.0", + "@lezer/php": "^1.0.0" } }, - "node_modules/@lezer/lr": { - "version": "1.4.10", - "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz", - "integrity": "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==", + "node_modules/@codemirror/lang-python": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.2.1.tgz", + "integrity": "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw==", "license": "MIT", "dependencies": { - "@lezer/common": "^1.0.0" + "@codemirror/autocomplete": "^6.3.2", + "@codemirror/language": "^6.8.0", + "@codemirror/state": "^6.0.0", + "@lezer/common": "^1.2.1", + "@lezer/python": "^1.1.4" } }, - "node_modules/@lezer/markdown": { - "version": "1.6.3", - "resolved": "https://registry.npmjs.org/@lezer/markdown/-/markdown-1.6.3.tgz", - "integrity": "sha512-jpGm5Ps+XErS+xA4urw7ogEGkeZOahVQF21Z6oECF0sj+2liwZopd2+I8uH5I/vZsRuuze3OxBREIANLf6KKUw==", + "node_modules/@codemirror/lang-rust": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@codemirror/lang-rust/-/lang-rust-6.0.2.tgz", + "integrity": "sha512-EZaGjCUegtiU7kSMvOfEZpaCReowEf3yNidYu7+vfuGTm9ow4mthAparY5hisJqOHmJowVH3Upu+eJlUji6qqA==", "license": "MIT", "dependencies": { - "@lezer/common": "^1.5.0", - "@lezer/highlight": "^1.0.0" + "@codemirror/language": "^6.0.0", + "@lezer/rust": "^1.0.0" } }, - "node_modules/@lezer/php": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@lezer/php/-/php-1.0.5.tgz", - "integrity": "sha512-W7asp9DhM6q0W6DYNwIkLSKOvxlXRrif+UXBMxzsJUuqmhE7oVU+gS3THO4S/Puh7Xzgm858UNaFi6dxTP8dJA==", + "node_modules/@codemirror/lang-sass": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@codemirror/lang-sass/-/lang-sass-6.0.2.tgz", + "integrity": "sha512-l/bdzIABvnTo1nzdY6U+kPAC51czYQcOErfzQ9zSm9D8GmNPD0WTW8st/CJwBTPLO8jlrbyvlSEcN20dc4iL0Q==", "license": "MIT", "dependencies": { - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.1.0" + "@codemirror/lang-css": "^6.2.0", + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@lezer/common": "^1.0.2", + "@lezer/sass": "^1.0.0" } }, - "node_modules/@lezer/python": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/@lezer/python/-/python-1.1.18.tgz", - "integrity": "sha512-31FiUrU7z9+d/ElGQLJFXl+dKOdx0jALlP3KEOsGTex8mvj+SoE1FgItcHWK/axkxCHGUSpqIHt6JAWfWu9Rhg==", + "node_modules/@codemirror/lang-sql": { + "version": "6.10.0", + "resolved": "https://registry.npmjs.org/@codemirror/lang-sql/-/lang-sql-6.10.0.tgz", + "integrity": "sha512-6ayPkEd/yRw0XKBx5uAiToSgGECo/GY2NoJIHXIIQh1EVwLuKoU8BP/qK0qH5NLXAbtJRLuT73hx7P9X34iO4w==", "license": "MIT", "dependencies": { + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, - "node_modules/@lezer/rust": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@lezer/rust/-/rust-1.0.2.tgz", - "integrity": "sha512-Lz5sIPBdF2FUXcWeCu1//ojFAZqzTQNRga0aYv6dYXqJqPfMdCAI0NzajWUd4Xijj1IKJLtjoXRPMvTKWBcqKg==", + "node_modules/@codemirror/lang-vue": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@codemirror/lang-vue/-/lang-vue-0.1.3.tgz", + "integrity": "sha512-QSKdtYTDRhEHCfo5zOShzxCmqKJvgGrZwDQSdbvCRJ5pRLWBS7pD/8e/tH44aVQT6FKm0t6RVNoSUWHOI5vNug==", "license": "MIT", "dependencies": { + "@codemirror/lang-html": "^6.0.0", + "@codemirror/lang-javascript": "^6.1.2", + "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0" + "@lezer/lr": "^1.3.1" } }, - "node_modules/@lezer/sass": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@lezer/sass/-/sass-1.1.0.tgz", - "integrity": "sha512-3mMGdCTUZ/84ArHOuXWQr37pnf7f+Nw9ycPUeKX+wu19b7pSMcZGLbaXwvD2APMBDOGxPmpK/O6S1v1EvLoqgQ==", + "node_modules/@codemirror/lang-wast": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@codemirror/lang-wast/-/lang-wast-6.0.2.tgz", + "integrity": "sha512-Imi2KTpVGm7TKuUkqyJ5NRmeFWF7aMpNiwHnLQe0x9kmrxElndyH0K6H/gXtWwY6UshMRAhpENsgfpSwsgmC6Q==", "license": "MIT", "dependencies": { + "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, - "node_modules/@lezer/xml": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/@lezer/xml/-/xml-1.0.6.tgz", - "integrity": "sha512-CdDwirL0OEaStFue/66ZmFSeppuL6Dwjlk8qk153mSQwiSH/Dlri4GNymrNWnUmPl2Um7QfV1FO9KFUyX3Twww==", + "node_modules/@codemirror/lang-xml": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@codemirror/lang-xml/-/lang-xml-6.1.0.tgz", + "integrity": "sha512-3z0blhicHLfwi2UgkZYRPioSgVTo9PV5GP5ducFH6FaHy0IAJRg+ixj5gTR1gnT/glAIC8xv4w2VL1LoZfs+Jg==", "license": "MIT", "dependencies": { - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0" + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/language": "^6.4.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0", + "@lezer/common": "^1.0.0", + "@lezer/xml": "^1.0.0" } }, - "node_modules/@lezer/yaml": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@lezer/yaml/-/yaml-1.0.4.tgz", - "integrity": "sha512-2lrrHqxalACEbxIbsjhqGpSW8kWpUKuY6RHgnSAFZa6qK62wvnPxA8hGOwOoDbwHcOFs5M4o27mjGu+P7TvBmw==", + "node_modules/@codemirror/lang-yaml": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/@codemirror/lang-yaml/-/lang-yaml-6.1.3.tgz", + "integrity": "sha512-AZ8DJBuXGVHybpBQhmZtgew5//4hv3tdkXnr3vDmOUMJRuB6vn/uuwtmTOTlqEaQFg3hQSVeA90NmvIQyUV6FQ==", "license": "MIT", "dependencies": { + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.4.0" + "@lezer/highlight": "^1.2.0", + "@lezer/lr": "^1.0.0", + "@lezer/yaml": "^1.0.0" } }, - "node_modules/@marijn/buildtool": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@marijn/buildtool/-/buildtool-1.2.0.tgz", - "integrity": "sha512-ytEK7n4NVrq6Rhq2J+N/CcvJLl6NX0bZ1qSi3w8lxZVcI4L6Y6vj1pugcTnv+YdyFNwFuACSdDesetZmQqSy1w==", - "dev": true, + "node_modules/@codemirror/language": { + "version": "6.13.1", + "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.13.1.tgz", + "integrity": "sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==", "license": "MIT", "dependencies": { - "@types/mocha": "^9.1.1", - "acorn": "^8.10.0", - "acorn-walk": "^8.2.0", - "rollup": "^4.8.0", - "rollup-plugin-dts": "^6.1.0", - "typescript": "^5.3.3" + "@codemirror/state": "^6.0.0", + "@codemirror/streamparser": "^6.0.0", + "@codemirror/view": "^6.23.0", + "@lezer/common": "^1.5.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0", + "style-mod": "^4.0.0" } }, - "node_modules/@marijn/find-cluster-break": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz", - "integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==", - "license": "MIT" - }, - "node_modules/@marijn/testtool": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@marijn/testtool/-/testtool-0.1.3.tgz", - "integrity": "sha512-Rdi3amfFyTZoUXxMc95k9x9Ult+DtQSuOHsZwN5wtIKQ5JdXQaErgtWgGjW0Fpg4Rj0YrUCpWOj0VqsumAt5JA==", - "dev": true, + "node_modules/@codemirror/language-data": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/@codemirror/language-data/-/language-data-6.5.2.tgz", + "integrity": "sha512-CPkWBKrNS8stYbEU5kwBwTf3JB1kghlbh4FSAwzGW2TEscdeHHH4FGysREW86Mqnj3Qn09s0/6Ea/TutmoTobg==", "license": "MIT", "dependencies": { - "esmoduleserve": "^0.2.0", - "ist": "^1.1.7", - "mocha": "^10.0.0", - "selenium-webdriver": "^4.10.0", - "serve-static": "^1.14.1" - }, - "bin": { - "testtool": "bin/testtool.js" + "@codemirror/lang-angular": "^0.1.0", + "@codemirror/lang-cpp": "^6.0.0", + "@codemirror/lang-css": "^6.0.0", + "@codemirror/lang-go": "^6.0.0", + "@codemirror/lang-html": "^6.0.0", + "@codemirror/lang-java": "^6.0.0", + "@codemirror/lang-javascript": "^6.0.0", + "@codemirror/lang-jinja": "^6.0.0", + "@codemirror/lang-json": "^6.0.0", + "@codemirror/lang-less": "^6.0.0", + "@codemirror/lang-liquid": "^6.0.0", + "@codemirror/lang-markdown": "^6.0.0", + "@codemirror/lang-php": "^6.0.0", + "@codemirror/lang-python": "^6.0.0", + "@codemirror/lang-rust": "^6.0.0", + "@codemirror/lang-sass": "^6.0.0", + "@codemirror/lang-sql": "^6.0.0", + "@codemirror/lang-vue": "^0.1.1", + "@codemirror/lang-wast": "^6.0.0", + "@codemirror/lang-xml": "^6.0.0", + "@codemirror/lang-yaml": "^6.0.0", + "@codemirror/language": "^6.0.0", + "@codemirror/legacy-modes": "^6.4.0" } }, - "node_modules/@marijn/testtool/node_modules/ansi-colors": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz", - "integrity": "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==", - "dev": true, + "node_modules/@codemirror/legacy-modes": { + "version": "6.5.4", + "resolved": "https://registry.npmjs.org/@codemirror/legacy-modes/-/legacy-modes-6.5.4.tgz", + "integrity": "sha512-/cZr6qZyl08iYNLGsJ862CXXNI51LryRFRE40ejgoIjXZz0C1rGkD3/Ek5jM/8w1ceRjqtt4qx/KLMh4zBTgew==", "license": "MIT", - "engines": { - "node": ">=6" + "dependencies": { + "@codemirror/language": "^6.0.0" } }, - "node_modules/@marijn/testtool/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, + "node_modules/@codemirror/lint": { + "version": "6.9.7", + "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz", + "integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==", "license": "MIT", - "engines": { - "node": ">=8" + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.42.0", + "crelt": "^1.0.5" } }, - "node_modules/@marijn/testtool/node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true, - "license": "MIT" + "node_modules/@codemirror/lsp-client": { + "resolved": "codemirror-lsp-client", + "link": true }, - "node_modules/@marijn/testtool/node_modules/brace-expansion": { - "version": "2.1.7", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", - "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", - "dev": true, + "node_modules/@codemirror/search": { + "version": "6.7.2", + "resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.7.2.tgz", + "integrity": "sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==", "license": "MIT", "dependencies": { - "balanced-match": "^1.0.0" + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.37.0", + "crelt": "^1.0.5" } }, - "node_modules/@marijn/testtool/node_modules/chokidar": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", - "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", - "dev": true, + "node_modules/@codemirror/state": { + "version": "6.7.6", + "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz", + "integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==", "license": "MIT", "dependencies": { - "anymatch": "~3.1.2", - "braces": "~3.0.2", - "glob-parent": "~5.1.2", - "is-binary-path": "~2.1.0", - "is-glob": "~4.0.1", - "normalize-path": "~3.0.0", - "readdirp": "~3.6.0" - }, - "engines": { - "node": ">= 8.10.0" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - }, - "optionalDependencies": { - "fsevents": "~2.3.2" + "@marijn/find-cluster-break": "^1.0.0" } }, - "node_modules/@marijn/testtool/node_modules/cliui": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", - "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", - "dev": true, - "license": "ISC", + "node_modules/@codemirror/streamparser": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@codemirror/streamparser/-/streamparser-6.0.0.tgz", + "integrity": "sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==", + "license": "MIT" + }, + "node_modules/@codemirror/theme-one-dark": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz", + "integrity": "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==", + "license": "MIT", "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", - "wrap-ansi": "^7.0.0" + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0", + "@lezer/highlight": "^1.0.0" } }, - "node_modules/@marijn/testtool/node_modules/diff": { - "version": "5.2.2", - "resolved": "https://registry.npmjs.org/diff/-/diff-5.2.2.tgz", - "integrity": "sha512-vtcDfH3TOjP8UekytvnHH1o1P4FcUdt4eQ1Y+Abap1tk/OB2MWQvcwS2ClCd1zuIhc3JKOx6p3kod8Vfys3E+A==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.3.1" + "node_modules/@codemirror/view": { + "version": "6.43.15", + "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.15.tgz", + "integrity": "sha512-HHsfpqFeHyXLs983pSRe38Xajs0vFWZQ2BuX0m7Ki8w3jZ5iD8cuR3lBz2/5/X53Dhf32SBHKh6rtSTB6tKeGw==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.7.0", + "crelt": "^1.0.6", + "style-mod": "^4.1.0", + "w3c-keyname": "^2.2.4" } }, - "node_modules/@marijn/testtool/node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, + "node_modules/@deadlyjack/ajax": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@deadlyjack/ajax/-/ajax-1.2.6.tgz", + "integrity": "sha512-VwZU8YUflO2/V/dl3dluu+3jg8Ghz/W5fwxD5Z21OZXKeV73d+vStKVBe4wi+Av2KbTR35K7Z+5Q3iIpjB41MA==", "license": "MIT" }, - "node_modules/@marijn/testtool/node_modules/escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true, + "node_modules/@emmetio/abbreviation": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@emmetio/abbreviation/-/abbreviation-2.3.3.tgz", + "integrity": "sha512-mgv58UrU3rh4YgbE/TzgLQwJ3pFsHHhCLqY20aJq+9comytTXUDNGG/SMtSeMJdkpxgXSXunBGLD8Boka3JyVA==", "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "dependencies": { + "@emmetio/scanner": "^1.0.4" } }, - "node_modules/@marijn/testtool/node_modules/glob": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz", - "integrity": "sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==", - "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", - "dev": true, - "license": "ISC", + "node_modules/@emmetio/codemirror6-plugin": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@emmetio/codemirror6-plugin/-/codemirror6-plugin-0.4.1.tgz", + "integrity": "sha512-OwMtvCjYM6XfFREqxNr1rg+MB5FsZh+nLCxsYjFi0ZZTlDJZ2sWAwWHlfJvNJ4H2Q+HQ71tUO0+OUPgUEFG0HQ==", "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^5.0.1", - "once": "^1.3.0" - }, - "engines": { - "node": ">=12" + "@emmetio/math-expression": "^1.0.5", + "emmet": "^2.4.11" }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "peerDependencies": { + "@codemirror/autocomplete": "^6.17.0", + "@codemirror/commands": "^6.6.0", + "@codemirror/lang-css": "^6.2.1", + "@codemirror/lang-html": "^6.4.9", + "@codemirror/lang-javascript": "^6.2.2", + "@codemirror/language": "^6.10.2", + "@codemirror/state": "^6.4.1", + "@codemirror/view": "^6.29.1" } }, - "node_modules/@marijn/testtool/node_modules/minimatch": { - "version": "5.1.9", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", - "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", - "dev": true, - "license": "ISC", + "node_modules/@emmetio/css-abbreviation": { + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/@emmetio/css-abbreviation/-/css-abbreviation-2.1.8.tgz", + "integrity": "sha512-s9yjhJ6saOO/uk1V74eifykk2CBYi01STTK3WlXWGOepyKa23ymJ053+DNQjpFcy1ingpaO7AxCcwLvHFY9tuw==", + "license": "MIT", "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=10" + "@emmetio/scanner": "^1.0.4" } }, - "node_modules/@marijn/testtool/node_modules/mocha": { - "version": "10.8.2", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-10.8.2.tgz", - "integrity": "sha512-VZlYo/WE8t1tstuRmqgeyBgCbJc/lEdopaa+axcKzTBJ+UIdlAB9XnmvTCAH4pwR4ElNInaedhEBmZD8iCSVEg==", - "dev": true, + "node_modules/@emmetio/math-expression": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@emmetio/math-expression/-/math-expression-1.0.5.tgz", + "integrity": "sha512-qf5SXD/ViS04rXSeDg9CRGM10xLC9dVaKIbMHrrwxYr5LNB/C0rOfokhGSBwnVQKcidLmdRJeNWH1V1tppZ84Q==", "license": "MIT", "dependencies": { - "ansi-colors": "^4.1.3", - "browser-stdout": "^1.3.1", - "chokidar": "^3.5.3", - "debug": "^4.3.5", - "diff": "^5.2.0", - "escape-string-regexp": "^4.0.0", - "find-up": "^5.0.0", - "glob": "^8.1.0", - "he": "^1.2.0", - "js-yaml": "^4.1.0", - "log-symbols": "^4.1.0", - "minimatch": "^5.1.6", - "ms": "^2.1.3", - "serialize-javascript": "^6.0.2", - "strip-json-comments": "^3.1.1", - "supports-color": "^8.1.1", - "workerpool": "^6.5.1", - "yargs": "^16.2.0", - "yargs-parser": "^20.2.9", - "yargs-unparser": "^2.0.0" - }, - "bin": { - "_mocha": "bin/_mocha", - "mocha": "bin/mocha.js" - }, - "engines": { - "node": ">= 14.0.0" + "@emmetio/scanner": "^1.0.4" } }, - "node_modules/@marijn/testtool/node_modules/picomatch": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", - "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "node_modules/@emmetio/scanner": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@emmetio/scanner/-/scanner-1.0.4.tgz", + "integrity": "sha512-IqRuJtQff7YHHBk4G8YZ45uB9BaAGcwQeVzgj/zj8/UdOhtQpEIupUhSk8dys6spFIWVZVeK20CzGEnqR5SbqA==", + "license": "MIT" + }, + "node_modules/@emnapi/core": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz", + "integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==", "dev": true, "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" } }, - "node_modules/@marijn/testtool/node_modules/readdirp": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", - "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", "dev": true, "license": "MIT", + "optional": true, "dependencies": { - "picomatch": "^2.2.1" - }, - "engines": { - "node": ">=8.10.0" + "tslib": "^2.4.0" } }, - "node_modules/@marijn/testtool/node_modules/serialize-javascript": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", - "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz", + "integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==", "dev": true, - "license": "BSD-3-Clause", + "license": "MIT", + "optional": true, "dependencies": { - "randombytes": "^2.1.0" + "tslib": "^2.4.0" } }, - "node_modules/@marijn/testtool/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", "dev": true, "license": "MIT", "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" } }, - "node_modules/@marijn/testtool/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", "dev": true, "license": "MIT", "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" } }, - "node_modules/@marijn/testtool/node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", "dev": true, "license": "MIT", "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=6.0.0" } }, - "node_modules/@marijn/testtool/node_modules/supports-color": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "node_modules/@jridgewell/source-map": { + "version": "0.3.11", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz", + "integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/supports-color?sponsor=1" + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25" } }, - "node_modules/@marijn/testtool/node_modules/workerpool": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.5.1.tgz", - "integrity": "sha512-Fs4dNYcsdpYSAfVxhnl1L5zTksjvOJxtC5hzMNl+1t9B8hTJTdKDyZ5ju7ztgPy+ft9tBFXoOlDNiOT9WUXZlA==", + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", "dev": true, - "license": "Apache-2.0" + "license": "MIT" }, - "node_modules/@marijn/testtool/node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", "dev": true, "license": "MIT", "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" } }, - "node_modules/@marijn/testtool/node_modules/yargs": { - "version": "16.2.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.2.tgz", - "integrity": "sha512-Nt9ZJjXTv5R8MHbqby/wXQ6Gi0Bb3TcYZkR1bzuL4yB2OxWPkXknz513gEF0GoA6tn00UpbPvERW8rzCuWCA6w==", - "dev": true, + "node_modules/@lezer/common": { + "version": "1.5.6", + "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.6.tgz", + "integrity": "sha512-NZxu3q49ck+YYbEJPuIPIyFP37XneBvzPIarBHEXBLBVfkZqQieZ/Y2boYnGNYtmjpOZLnAKs/lwqtmDpi365w==", + "license": "MIT" + }, + "node_modules/@lezer/cpp": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@lezer/cpp/-/cpp-1.1.6.tgz", + "integrity": "sha512-vh9gWWJOXFVY8HBHK3Twzq8MgwG2iN4GSyzBP9sCGTe37P15x2R14VaBQk0VA0ezTRN1KHYBBsHhvpGZ2Xy/pA==", "license": "MIT", "dependencies": { - "cliui": "^7.0.2", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.0", - "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@marijn/testtool/node_modules/yargs-parser": { - "version": "20.2.9", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", - "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=10" + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" } }, - "node_modules/@napi-rs/lzma-linux-x64-gnu": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", - "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", - "cpu": [ - "x64" - ], - "dev": true, + "node_modules/@lezer/css": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.8.tgz", + "integrity": "sha512-EJn1zcL9qoDptief6ipWKZKLiOpXkxSe0+t8CH9oiMVcZlq7NBWrjCqnc/41EIjeo/ITj1gFFiATdTkaJDL+Og==", "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^22.20 || ^24.12 || >=25" + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.3.0" } }, - "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz", - "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==", + "node_modules/@lezer/generator": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@lezer/generator/-/generator-1.8.1.tgz", + "integrity": "sha512-7q7szXqT7EPTs6SODBl58Qoz/4OrhNvm5pW4lbu1ZDnG5e0nn7drLzeN9Nxkm8j/1iMs5QZ9j3i4SV+W4Z6SQA==", "dev": true, "license": "MIT", - "optional": true, "dependencies": { - "@tybys/wasm-util": "^0.10.3" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" + "@lezer/common": "^1.1.0", + "@lezer/lr": "^1.3.0" }, - "peerDependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1" + "bin": { + "lezer-generator": "src/lezer-generator.cjs" } }, - "node_modules/@netflix/nerror": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@netflix/nerror/-/nerror-1.1.3.tgz", - "integrity": "sha512-b+MGNyP9/LXkapreJzNUzcvuzZslj/RGgdVVJ16P2wSlYatfLycPObImqVJSmNAdyeShvNeM/pl3sVZsObFueg==", + "node_modules/@lezer/go": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@lezer/go/-/go-1.0.1.tgz", + "integrity": "sha512-xToRsYxwsgJNHTgNdStpcvmbVuKxTapV0dM0wey1geMMRc9aggoVyKgzYp41D2/vVOx+Ii4hmE206kvxIXBVXQ==", "license": "MIT", "dependencies": { - "assert-plus": "^1.0.0", - "extsprintf": "^1.4.0", - "lodash": "^4.17.15" + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.3.0" } }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "node_modules/@lezer/highlight": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.5.tgz", + "integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==", "license": "MIT", "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, - "engines": { - "node": ">= 8" + "@lezer/common": "^1.3.0" } }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "node_modules/@lezer/html": { + "version": "1.3.13", + "resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz", + "integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==", "license": "MIT", - "engines": { - "node": ">= 8" + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" } }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "node_modules/@lezer/java": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@lezer/java/-/java-1.1.4.tgz", + "integrity": "sha512-gQylJ2xHV2xXsVqtnAcJrcROvLZJaQiC0tR//+q0k961BxqvyYttusPkJ8d9T1fPDJKHJW2etUH8XbIn9jhVUg==", "license": "MIT", "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, - "engines": { - "node": ">= 8" + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" } }, - "node_modules/@npmcli/agent": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-4.0.0.tgz", - "integrity": "sha512-kAQTcEN9E8ERLVg5AsGwLNoFb+oEG6engbqAU2P43gD4JEIkNGMHdVQ096FsOAAYpZPB0RSt0zgInKIAS1l5QA==", - "license": "ISC", + "node_modules/@lezer/javascript": { + "version": "1.5.6", + "resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.6.tgz", + "integrity": "sha512-sEvOqpl4vJQca0NugSQK02vQPbc5KrvoojnYGoqqFgFO0MtcYhwGiHKVEB+LuXYJnfyXo4QPA8ztbrEa4Fw5NA==", + "license": "MIT", "dependencies": { - "agent-base": "^7.1.0", - "http-proxy-agent": "^7.0.0", - "https-proxy-agent": "^7.0.1", - "lru-cache": "^11.2.1", - "socks-proxy-agent": "^8.0.3" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.1.3", + "@lezer/lr": "^1.3.0" } }, - "node_modules/@npmcli/arborist": { - "version": "9.5.0", - "resolved": "https://registry.npmjs.org/@npmcli/arborist/-/arborist-9.5.0.tgz", - "integrity": "sha512-qS+TtKWC58sjBjD+szLrhEj2TCLnwzUA9vlMyCnU9ztw01ZjQSu25iQPxeBa0sk9sS9/Hzs/xJMWl7J/vRCjGQ==", - "license": "ISC", + "node_modules/@lezer/json": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@lezer/json/-/json-1.0.3.tgz", + "integrity": "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==", + "license": "MIT", "dependencies": { - "@gar/promise-retry": "^1.0.0", - "@isaacs/string-locale-compare": "^1.1.0", - "@npmcli/fs": "^5.0.0", - "@npmcli/installed-package-contents": "^4.0.0", - "@npmcli/map-workspaces": "^5.0.0", - "@npmcli/metavuln-calculator": "^9.0.2", - "@npmcli/name-from-folder": "^4.0.0", - "@npmcli/node-gyp": "^5.0.0", - "@npmcli/package-json": "^7.0.0", - "@npmcli/query": "^5.0.0", - "@npmcli/redact": "^4.0.0", - "@npmcli/run-script": "^10.0.0", - "bin-links": "^6.0.0", - "cacache": "^20.0.1", - "common-ancestor-path": "^2.0.0", - "hosted-git-info": "^9.0.0", - "json-stringify-nice": "^1.1.4", - "lru-cache": "^11.2.1", - "minimatch": "^10.0.3", - "nopt": "^9.0.0", - "npm-install-checks": "^8.0.0", - "npm-package-arg": "^13.0.0", - "npm-pick-manifest": "^11.0.1", - "npm-registry-fetch": "^19.0.0", - "pacote": "^21.0.2", - "parse-conflict-json": "^5.0.1", - "proc-log": "^6.0.0", - "proggy": "^4.0.0", - "promise-all-reject-late": "^1.0.0", - "promise-call-limit": "^3.0.1", - "semver": "^7.3.7", - "ssri": "^13.0.0", - "treeverse": "^3.0.0", - "walk-up-path": "^4.0.0" - }, - "bin": { - "arborist": "bin/index.js" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/@npmcli/arborist/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" } }, - "node_modules/@npmcli/fs": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-5.0.0.tgz", - "integrity": "sha512-7OsC1gNORBEawOa5+j2pXN9vsicaIOH5cPXxoR6fJOmH6/EXpJB2CajXOu1fPRFun2m1lktEFX11+P89hqO/og==", - "license": "ISC", + "node_modules/@lezer/lr": { + "version": "1.4.10", + "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz", + "integrity": "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==", + "license": "MIT", "dependencies": { - "semver": "^7.3.5" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/@npmcli/fs/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" + "@lezer/common": "^1.0.0" } }, - "node_modules/@npmcli/git": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@npmcli/git/-/git-7.0.2.tgz", - "integrity": "sha512-oeolHDjExNAJAnlYP2qzNjMX/Xi9bmu78C9dIGr4xjobrSKbuMYCph8lTzn4vnW3NjIqVmw/f8BCfouqyJXlRg==", - "license": "ISC", + "node_modules/@lezer/markdown": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/@lezer/markdown/-/markdown-1.7.2.tgz", + "integrity": "sha512-iTkYvoVcKt3WkeL7qUDyXHONZEwLio4wj8KTNi2dnjQEXBZKMV63BpQrPqfsM+OkvuRbiSTAcycYAsQzLhRNoQ==", + "license": "MIT", "dependencies": { - "@gar/promise-retry": "^1.0.0", - "@npmcli/promise-spawn": "^9.0.0", - "ini": "^6.0.0", - "lru-cache": "^11.2.1", - "npm-pick-manifest": "^11.0.1", - "proc-log": "^6.0.0", - "semver": "^7.3.5", - "which": "^6.0.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/@npmcli/git/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" + "@lezer/common": "^1.5.0", + "@lezer/highlight": "^1.0.0" } }, - "node_modules/@npmcli/installed-package-contents": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@npmcli/installed-package-contents/-/installed-package-contents-4.0.0.tgz", - "integrity": "sha512-yNyAdkBxB72gtZ4GrwXCM0ZUedo9nIbOMKfGjt6Cu6DXf0p8y1PViZAKDC8q8kv/fufx0WTjRBdSlyrvnP7hmA==", - "license": "ISC", + "node_modules/@lezer/php": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@lezer/php/-/php-1.0.6.tgz", + "integrity": "sha512-QJ2xNXPmsm/Z3IpThq8fnJrEIVpxhsIoj6GZBW0JYEd/l9zxpJZW216X4fzqQY4vgpdGIumypvI4uQjd4tnYtw==", + "license": "MIT", "dependencies": { - "npm-bundled": "^5.0.0", - "npm-normalize-package-bin": "^5.0.0" - }, - "bin": { - "installed-package-contents": "bin/index.js" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.1.0" } }, - "node_modules/@npmcli/map-workspaces": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/@npmcli/map-workspaces/-/map-workspaces-5.0.3.tgz", - "integrity": "sha512-o2grssXo1e774E5OtEwwrgoszYRh0lqkJH+Pb9r78UcqdGJRDRfhpM8DvZPjzNLLNYeD/rNbjOKM3Ss5UABROw==", - "license": "ISC", + "node_modules/@lezer/python": { + "version": "1.1.19", + "resolved": "https://registry.npmjs.org/@lezer/python/-/python-1.1.19.tgz", + "integrity": "sha512-MhQIURHRytsNzP/YXnqpYKW6la6voAH3kyplTOOiCdjyFY6cWWGFVmYVdHIPrElqSDf4iCDktQCockB9FxuhzQ==", + "license": "MIT", "dependencies": { - "@npmcli/name-from-folder": "^4.0.0", - "@npmcli/package-json": "^7.0.0", - "glob": "^13.0.0", - "minimatch": "^10.0.3" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" } }, - "node_modules/@npmcli/metavuln-calculator": { - "version": "9.0.3", - "resolved": "https://registry.npmjs.org/@npmcli/metavuln-calculator/-/metavuln-calculator-9.0.3.tgz", - "integrity": "sha512-94GLSYhLXF2t2LAC7pDwLaM4uCARzxShyAQKsirmlNcpidH89VA4/+K1LbJmRMgz5gy65E/QBBWQdUvGLe2Frg==", - "license": "ISC", + "node_modules/@lezer/rust": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@lezer/rust/-/rust-1.0.3.tgz", + "integrity": "sha512-XxErOjZzQ7yJt1agUT4fu9qQvESZ3acgoxpPaPTPOiUx+duCjaVAtZGFIgphkHxlN05djdVAIOy/wItShMEjqQ==", + "license": "MIT", "dependencies": { - "cacache": "^20.0.0", - "json-parse-even-better-errors": "^5.0.0", - "pacote": "^21.0.0", - "proc-log": "^6.0.0", - "semver": "^7.3.5" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@npmcli/name-from-folder": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@npmcli/name-from-folder/-/name-from-folder-4.0.0.tgz", - "integrity": "sha512-qfrhVlOSqmKM8i6rkNdZzABj8MKEITGFAY+4teqBziksCQAOLutiAxM1wY2BKEd8KjUSpWmWCYxvXr0y4VTlPg==", - "license": "ISC", - "engines": { - "node": "^20.17.0 || >=22.9.0" + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" } }, - "node_modules/@npmcli/node-gyp": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@npmcli/node-gyp/-/node-gyp-5.0.0.tgz", - "integrity": "sha512-uuG5HZFXLfyFKqg8QypsmgLQW7smiRjVc45bqD/ofZZcR/uxEjgQU8qDPv0s9TEeMUiAAU/GC5bR6++UdTirIQ==", - "license": "ISC", - "engines": { - "node": "^20.17.0 || >=22.9.0" + "node_modules/@lezer/sass": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@lezer/sass/-/sass-1.1.0.tgz", + "integrity": "sha512-3mMGdCTUZ/84ArHOuXWQr37pnf7f+Nw9ycPUeKX+wu19b7pSMcZGLbaXwvD2APMBDOGxPmpK/O6S1v1EvLoqgQ==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" } }, - "node_modules/@npmcli/package-json": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/@npmcli/package-json/-/package-json-7.0.5.tgz", - "integrity": "sha512-iVuTlG3ORq2iaVa1IWUxAO/jIp77tUKBhoMjuzYW2kL4MLN1bi/ofqkZ7D7OOwh8coAx1/S2ge0rMdGv8sLSOQ==", - "license": "ISC", + "node_modules/@lezer/xml": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@lezer/xml/-/xml-1.0.6.tgz", + "integrity": "sha512-CdDwirL0OEaStFue/66ZmFSeppuL6Dwjlk8qk153mSQwiSH/Dlri4GNymrNWnUmPl2Um7QfV1FO9KFUyX3Twww==", + "license": "MIT", "dependencies": { - "@npmcli/git": "^7.0.0", - "glob": "^13.0.0", - "hosted-git-info": "^9.0.0", - "json-parse-even-better-errors": "^5.0.0", - "proc-log": "^6.0.0", - "semver": "^7.5.3", - "spdx-expression-parse": "^4.0.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" } }, - "node_modules/@npmcli/package-json/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" + "node_modules/@lezer/yaml": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@lezer/yaml/-/yaml-1.0.4.tgz", + "integrity": "sha512-2lrrHqxalACEbxIbsjhqGpSW8kWpUKuY6RHgnSAFZa6qK62wvnPxA8hGOwOoDbwHcOFs5M4o27mjGu+P7TvBmw==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.4.0" } }, - "node_modules/@npmcli/promise-spawn": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/@npmcli/promise-spawn/-/promise-spawn-9.0.1.tgz", - "integrity": "sha512-OLUaoqBuyxeTqUvjA3FZFiXUfYC1alp3Sa99gW3EUDz3tZ3CbXDdcZ7qWKBzicrJleIgucoWamWH1saAmH/l2Q==", - "license": "ISC", + "node_modules/@marijn/buildtool": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@marijn/buildtool/-/buildtool-1.2.1.tgz", + "integrity": "sha512-CcbDNOPXiY5pW+YECfc5PuqXR9YvGRENlo8vVCNDo7AuJgKfo+DkEQk6emaqZy58TrVrKy+BCj+IErV0ZiPJnQ==", + "dev": true, + "license": "MIT", "dependencies": { - "which": "^6.0.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" + "@types/mocha": "^9.1.1", + "acorn": "^8.10.0", + "acorn-walk": "^8.2.0", + "rollup": "^4.8.0", + "rollup-plugin-dts": "^6.1.0", + "typescript": "^5.3.3" } }, - "node_modules/@npmcli/query": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@npmcli/query/-/query-5.0.0.tgz", - "integrity": "sha512-8TZWfTQOsODpLqo9SVhVjHovmKXNpevHU0gO9e+y4V4fRIOneiXy0u0sMP9LmS71XivrEWfZWg50ReH4WRT4aQ==", - "license": "ISC", + "node_modules/@marijn/find-cluster-break": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz", + "integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==", + "license": "MIT" + }, + "node_modules/@marijn/testtool": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@marijn/testtool/-/testtool-0.1.3.tgz", + "integrity": "sha512-Rdi3amfFyTZoUXxMc95k9x9Ult+DtQSuOHsZwN5wtIKQ5JdXQaErgtWgGjW0Fpg4Rj0YrUCpWOj0VqsumAt5JA==", + "dev": true, + "license": "MIT", "dependencies": { - "postcss-selector-parser": "^7.0.0" + "esmoduleserve": "^0.2.0", + "ist": "^1.1.7", + "mocha": "^10.0.0", + "selenium-webdriver": "^4.10.0", + "serve-static": "^1.14.1" }, - "engines": { - "node": "^20.17.0 || >=22.9.0" + "bin": { + "testtool": "bin/testtool.js" } }, - "node_modules/@npmcli/redact": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@npmcli/redact/-/redact-4.0.0.tgz", - "integrity": "sha512-gOBg5YHMfZy+TfHArfVogwgfBeQnKbbGo3pSUyK/gSI0AVu+pEiDVcKlQb0D8Mg1LNRZILZ6XG8I5dJ4KuAd9Q==", - "license": "ISC", + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": "^20.17.0 || >=22.9.0" + "node": "^22.20 || ^24.12 || >=25" } }, - "node_modules/@npmcli/run-script": { - "version": "10.0.4", - "resolved": "https://registry.npmjs.org/@npmcli/run-script/-/run-script-10.0.4.tgz", - "integrity": "sha512-mGUWr1uMnf0le2TwfOZY4SFxZGXGfm4Jtay/nwAa2FLNAKXUoUwaGwBMNH36UHPtinWfTSJ3nqFQr0091CxVGg==", - "license": "ISC", + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz", + "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==", + "dev": true, + "license": "MIT", + "optional": true, "dependencies": { - "@npmcli/node-gyp": "^5.0.0", - "@npmcli/package-json": "^7.0.0", - "@npmcli/promise-spawn": "^9.0.0", - "node-gyp": "^12.1.0", - "proc-log": "^6.0.0" + "@tybys/wasm-util": "^0.10.3" }, - "engines": { - "node": "^20.17.0 || >=22.9.0" + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1" } }, "node_modules/@oxc-project/types": { - "version": "0.147.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.147.0.tgz", - "integrity": "sha512-IJ3s6ltHLp45S0bh7phkX+gJO7A1Wuz2EaqpAhb8WjqDwbzMiWKHhyyT42tskaWjEYXtHtVCPpnBJVT9+dcRLg==", + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.152.0.tgz", + "integrity": "sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==", "dev": true, "license": "MIT", "funding": { - "url": "https://github.com/sponsors/Boshen" + "url": "https://github.com/sponsors/oxc-project" } }, "node_modules/@parcel/watcher": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.5.6.tgz", - "integrity": "sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", + "integrity": "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -5210,7 +3660,7 @@ "detect-libc": "^2.0.3", "is-glob": "^4.0.3", "node-addon-api": "^7.0.0", - "picomatch": "^4.0.3" + "picomatch": "^4.0.4" }, "engines": { "node": ">= 10.0.0" @@ -5220,25 +3670,24 @@ "url": "https://opencollective.com/parcel" }, "optionalDependencies": { - "@parcel/watcher-android-arm64": "2.5.6", - "@parcel/watcher-darwin-arm64": "2.5.6", - "@parcel/watcher-darwin-x64": "2.5.6", - "@parcel/watcher-freebsd-x64": "2.5.6", - "@parcel/watcher-linux-arm-glibc": "2.5.6", - "@parcel/watcher-linux-arm-musl": "2.5.6", - "@parcel/watcher-linux-arm64-glibc": "2.5.6", - "@parcel/watcher-linux-arm64-musl": "2.5.6", - "@parcel/watcher-linux-x64-glibc": "2.5.6", - "@parcel/watcher-linux-x64-musl": "2.5.6", - "@parcel/watcher-win32-arm64": "2.5.6", - "@parcel/watcher-win32-ia32": "2.5.6", - "@parcel/watcher-win32-x64": "2.5.6" + "@parcel/watcher-android-arm64": "2.6.0", + "@parcel/watcher-darwin-arm64": "2.6.0", + "@parcel/watcher-darwin-x64": "2.6.0", + "@parcel/watcher-freebsd-x64": "2.6.0", + "@parcel/watcher-linux-arm-glibc": "2.6.0", + "@parcel/watcher-linux-arm-musl": "2.6.0", + "@parcel/watcher-linux-arm64-glibc": "2.6.0", + "@parcel/watcher-linux-arm64-musl": "2.6.0", + "@parcel/watcher-linux-x64-glibc": "2.6.0", + "@parcel/watcher-linux-x64-musl": "2.6.0", + "@parcel/watcher-win32-arm64": "2.6.0", + "@parcel/watcher-win32-x64": "2.6.0" } }, "node_modules/@parcel/watcher-android-arm64": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.5.6.tgz", - "integrity": "sha512-YQxSS34tPF/6ZG7r/Ih9xy+kP/WwediEUsqmtf0cuCV5TPPKw/PQHRhueUo6JdeFJaqV3pyjm0GdYjZotbRt/A==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.6.0.tgz", + "integrity": "sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA==", "cpu": [ "arm64" ], @@ -5257,9 +3706,9 @@ } }, "node_modules/@parcel/watcher-darwin-arm64": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.5.6.tgz", - "integrity": "sha512-Z2ZdrnwyXvvvdtRHLmM4knydIdU9adO3D4n/0cVipF3rRiwP+3/sfzpAwA/qKFL6i1ModaabkU7IbpeMBgiVEA==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.6.0.tgz", + "integrity": "sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw==", "cpu": [ "arm64" ], @@ -5278,9 +3727,9 @@ } }, "node_modules/@parcel/watcher-darwin-x64": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.5.6.tgz", - "integrity": "sha512-HgvOf3W9dhithcwOWX9uDZyn1lW9R+7tPZ4sug+NGrGIo4Rk1hAXLEbcH1TQSqxts0NYXXlOWqVpvS1SFS4fRg==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.6.0.tgz", + "integrity": "sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw==", "cpu": [ "x64" ], @@ -5299,9 +3748,9 @@ } }, "node_modules/@parcel/watcher-freebsd-x64": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.5.6.tgz", - "integrity": "sha512-vJVi8yd/qzJxEKHkeemh7w3YAn6RJCtYlE4HPMoVnCpIXEzSrxErBW5SJBgKLbXU3WdIpkjBTeUNtyBVn8TRng==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.6.0.tgz", + "integrity": "sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ==", "cpu": [ "x64" ], @@ -5320,9 +3769,9 @@ } }, "node_modules/@parcel/watcher-linux-arm-glibc": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.5.6.tgz", - "integrity": "sha512-9JiYfB6h6BgV50CCfasfLf/uvOcJskMSwcdH1PHH9rvS1IrNy8zad6IUVPVUfmXr+u+Km9IxcfMLzgdOudz9EQ==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.6.0.tgz", + "integrity": "sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg==", "cpu": [ "arm" ], @@ -5341,9 +3790,9 @@ } }, "node_modules/@parcel/watcher-linux-arm-musl": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.5.6.tgz", - "integrity": "sha512-Ve3gUCG57nuUUSyjBq/MAM0CzArtuIOxsBdQ+ftz6ho8n7s1i9E1Nmk/xmP323r2YL0SONs1EuwqBp2u1k5fxg==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.6.0.tgz", + "integrity": "sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw==", "cpu": [ "arm" ], @@ -5362,9 +3811,9 @@ } }, "node_modules/@parcel/watcher-linux-arm64-glibc": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.5.6.tgz", - "integrity": "sha512-f2g/DT3NhGPdBmMWYoxixqYr3v/UXcmLOYy16Bx0TM20Tchduwr4EaCbmxh1321TABqPGDpS8D/ggOTaljijOA==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.6.0.tgz", + "integrity": "sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g==", "cpu": [ "arm64" ], @@ -5383,9 +3832,9 @@ } }, "node_modules/@parcel/watcher-linux-arm64-musl": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.5.6.tgz", - "integrity": "sha512-qb6naMDGlbCwdhLj6hgoVKJl2odL34z2sqkC7Z6kzir8b5W65WYDpLB6R06KabvZdgoHI/zxke4b3zR0wAbDTA==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.6.0.tgz", + "integrity": "sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA==", "cpu": [ "arm64" ], @@ -5404,9 +3853,9 @@ } }, "node_modules/@parcel/watcher-linux-x64-glibc": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.5.6.tgz", - "integrity": "sha512-kbT5wvNQlx7NaGjzPFu8nVIW1rWqV780O7ZtkjuWaPUgpv2NMFpjYERVi0UYj1msZNyCzGlaCWEtzc+exjMGbQ==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.6.0.tgz", + "integrity": "sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A==", "cpu": [ "x64" ], @@ -5425,9 +3874,9 @@ } }, "node_modules/@parcel/watcher-linux-x64-musl": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.5.6.tgz", - "integrity": "sha512-1JRFeC+h7RdXwldHzTsmdtYR/Ku8SylLgTU/reMuqdVD7CtLwf0VR1FqeprZ0eHQkO0vqsbvFLXUmYm/uNKJBg==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.6.0.tgz", + "integrity": "sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw==", "cpu": [ "x64" ], @@ -5446,9 +3895,9 @@ } }, "node_modules/@parcel/watcher-win32-arm64": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.5.6.tgz", - "integrity": "sha512-3ukyebjc6eGlw9yRt678DxVF7rjXatWiHvTXqphZLvo7aC5NdEgFufVwjFfY51ijYEWpXbqF5jtrK275z52D4Q==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.6.0.tgz", + "integrity": "sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ==", "cpu": [ "arm64" ], @@ -5466,31 +3915,10 @@ "url": "https://opencollective.com/parcel" } }, - "node_modules/@parcel/watcher-win32-ia32": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-ia32/-/watcher-win32-ia32-2.5.6.tgz", - "integrity": "sha512-k35yLp1ZMwwee3Ez/pxBi5cf4AoBKYXj00CZ80jUz5h8prpiaQsiRPKQMxoLstNuqe2vR4RNPEAEcjEFzhEz/g==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, "node_modules/@parcel/watcher-win32-x64": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.5.6.tgz", - "integrity": "sha512-hbQlYcCq5dlAX9Qx+kFb0FHue6vbjlf0FrNzSKdYK2APUf7tGfGxQCk2ihEREmbR6ZMc0MVAD5RIX/41gpUzTw==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.6.0.tgz", + "integrity": "sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A==", "cpu": [ "x64" ], @@ -5509,9 +3937,9 @@ } }, "node_modules/@rolldown/binding-android-arm-eabi": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.6.tgz", - "integrity": "sha512-b+jTcARdTiFLI6jB4a5XjTm0RWd6KcRfQj/I2356fxUZemiho9zQLxo0RtCuMDAyKcLo6cEltkgbQp6d1+sjjQ==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.12.tgz", + "integrity": "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==", "cpu": [ "arm" ], @@ -5526,9 +3954,9 @@ } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.6.tgz", - "integrity": "sha512-lkWU8ZJaRk9q3CIEY1Tc7vIFALp3Xw5NfGJo2hQg5oIqNgxWi1zI+IiDEK3r70BF5Dzol1tcXsnzsRc8NLhG+Q==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.12.tgz", + "integrity": "sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg==", "cpu": [ "arm64" ], @@ -5543,9 +3971,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.6.tgz", - "integrity": "sha512-dgR56NYnvAszm7Ob1B2/Vn0e8bUQYZH2UjVaMMtMVOCKFSfjhfLmuA/9+O+F+ajUdG6B/bSssrKW6JJYASa8jA==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.12.tgz", + "integrity": "sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w==", "cpu": [ "arm64" ], @@ -5560,9 +3988,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.6.tgz", - "integrity": "sha512-vpVxFvUCFioJqug7OTvqptkc4yb8UX0AwfDmJpaR/0sWz+BUmqSVAf7c8JkUgnN8YLspb4a/N6NhTyMAmdyQ7Q==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.12.tgz", + "integrity": "sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA==", "cpu": [ "x64" ], @@ -5577,9 +4005,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.6.tgz", - "integrity": "sha512-h1wG6Y6K3JlRswxsI64qQJqBAy4vrLuHgRbc8CZMGSWTOFRY6ghMApM1NKzB2I0n5xV1fjkE18SuVl2QpLeNpA==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.12.tgz", + "integrity": "sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ==", "cpu": [ "x64" ], @@ -5594,9 +4022,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.6.tgz", - "integrity": "sha512-tbCiqub0q2MVWJKgF5PoAlNWCtQydiOYSLIkd8sByqK/6MMYLJRcSXSYodqYtd0O+Fw7QaVmKKlS4oL94YRZ0w==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.12.tgz", + "integrity": "sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g==", "cpu": [ "arm" ], @@ -5611,9 +4039,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.6.tgz", - "integrity": "sha512-oxK9+baEBPhZG5HB4URY+uU04zJWeZlH6Tb9rB5DK4DF9XR1uXNLXt5Q5ZsugTKayNCNLhkcwz/ye74hRI98dg==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.12.tgz", + "integrity": "sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw==", "cpu": [ "arm64" ], @@ -5628,9 +4056,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.6.tgz", - "integrity": "sha512-muWCk27FVBEZtv0MsK8gnfSmgczA8KQ0uRVJbTABKhkRfQc38aUrcb7fhi3BNiyseFmgcRsoMfQsSNJ+DbZdSw==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.12.tgz", + "integrity": "sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw==", "cpu": [ "arm64" ], @@ -5645,9 +4073,9 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.6.tgz", - "integrity": "sha512-eWDoSfU7Co2qj3vgB3Dt4lj1mG6CoWbcJQkRMP3XJplyCMtuaq3LHvPFjS9QIPvMGWVadJC04Xiy0IdcVPtnwQ==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.12.tgz", + "integrity": "sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ==", "cpu": [ "ppc64" ], @@ -5662,9 +4090,9 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.6.tgz", - "integrity": "sha512-2bWNjRSIayvupRKxXUY2tWG9fYdoUlTqWywHRvE8Eq3GvuQ+f2HeIkve697fIt+IQs/PV8yFsdWuhp1aJ1PdnA==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.12.tgz", + "integrity": "sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw==", "cpu": [ "s390x" ], @@ -5679,9 +4107,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.6.tgz", - "integrity": "sha512-KekI0gS0wLxe1UBSQSjenBVwou/JkcQPDzBPICGZjxUv9k3RteHDPBQaiOicZUFKRIH2wKEimGwVpnJsbPzu7w==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.12.tgz", + "integrity": "sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw==", "cpu": [ "x64" ], @@ -5696,9 +4124,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.6.tgz", - "integrity": "sha512-TvtPnfVr+HtyGiDmPK4VWmlNm7QhNNAcK5Q9A7aOXsI8545yCyaoMaicXrFZ72JzeYjaUVk7yT243zT0jzjFKQ==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.12.tgz", + "integrity": "sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g==", "cpu": [ "x64" ], @@ -5713,9 +4141,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.6.tgz", - "integrity": "sha512-iOo0VEay2XFhaCcH0sps5XIimkSuOnNaZrf6+ZkoSOQBJPKNU48RkmJv0/lSpipexu5P+ouFgafe5IGr/DiQfg==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.12.tgz", + "integrity": "sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA==", "cpu": [ "arm64" ], @@ -5730,9 +4158,9 @@ } }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.6.tgz", - "integrity": "sha512-y5NTmmasMS455JlOCO4ZM9krIchv3Mvm1crL1iUPGOPgEzSkves9n0SdC5Sjz6+qWDFhd8/JpfWMH8NSWNHe+A==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.12.tgz", + "integrity": "sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew==", "cpu": [ "arm64" ], @@ -5747,9 +4175,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.6.tgz", - "integrity": "sha512-np8iZSLfXlAD4kWhiyq/u0Yt8oZDtRQ8lGhQaCXo2rl37KNjeU0GjJuwr4P3oeZ++ROfofsKNBqR5LTO8aXyWQ==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.12.tgz", + "integrity": "sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ==", "cpu": [ "x64" ], @@ -5771,9 +4199,9 @@ "license": "MIT" }, "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.3.tgz", - "integrity": "sha512-w3Jnvi1ocaVm/c7yVPpfB98XeSRBMyzp6njL5MVVbGyXjpmUkN+s6Hp4t0PqhGCCaI1ZHMKXt/w0lA1RCaLVcw==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.0.tgz", + "integrity": "sha512-FLLpX941CD/7aBvX3GqLGBM9OvY5PGXTryPJkG5r5/OuBpZpV5k45Uo3RxAvqd35tsyc3hH1bhtz921IKzoIzg==", "cpu": [ "arm" ], @@ -5785,9 +4213,9 @@ ] }, "node_modules/@rollup/rollup-android-arm64": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.63.3.tgz", - "integrity": "sha512-uI/ESiaIbbRYAEhzy8PCUWDp1hB0bjAqM06mW9flOoNO4Q8DQpeoREhBR5Hegfl+wpXiguyJv6XSPzEN7OxyHQ==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.0.tgz", + "integrity": "sha512-iI32XM/jnDYJsvx5ai/za/7gWO9XoSeFFtU06/ZCaRgyilfJOjaopD3nOpk2WrTCGOyeDt4hleUiGOAnd5tHNg==", "cpu": [ "arm64" ], @@ -5799,9 +4227,9 @@ ] }, "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.63.3.tgz", - "integrity": "sha512-oxhrd1jmXLwWZ83eQYDXxuqRdkqkzrjR3JobKeuUyfdNZo11FuQIvqEOZhyIT7OBHxXoGslDDjN0cQcM6T0TqQ==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.0.tgz", + "integrity": "sha512-dRBZlbt2sEtF8Mn4MODThze9fIPdDoOhVSlXMAKy5dQbOYK9pOOoPY4Fat3OTtr0+8zbJo5TTZwlsfxY/kDNJg==", "cpu": [ "arm64" ], @@ -5813,9 +4241,9 @@ ] }, "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.63.3.tgz", - "integrity": "sha512-7/YiIMghVE8DrxKvNdorAaJVdriOFgOIpdStnPx8ppx5zfTwC3jBCSEAIzB7JD5404m65THl6H93UTTVUvypmg==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.0.tgz", + "integrity": "sha512-Y3whrJOMucfkhgNkvcM93M6j8C53iEAMmPMYD99C6G1kUy4ELigLWk9ar2/4aCBSRgsql0zdlOemLgW2m5GZgQ==", "cpu": [ "x64" ], @@ -5827,9 +4255,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.63.3.tgz", - "integrity": "sha512-GXFZRRoMAytaI5z6N3Zhfw0WL18Q0M8r95D5hlC4GqE/lGk8pbSJNUBoOWDfbm6dTciqHj2nU87tI5f6XhQiOg==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.0.tgz", + "integrity": "sha512-S6S1GEzPjFF6IONYJX3AKt/799+8RgBgCcwRnUo+Ep1IvBxUbw5M51iU0TDdK2NWWVnSvCQ8yi6Em0fGASMOng==", "cpu": [ "arm64" ], @@ -5841,9 +4269,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.63.3.tgz", - "integrity": "sha512-77W+8X3ddYgPxUpB8nZFQs2Mq+wc4HVlcSRtApXLjYBcnPMkttrSnU8VwKQjeWYhMsITHFs5cWBQ8vz1Q+5RHQ==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.0.tgz", + "integrity": "sha512-Ed1DPoFENkXj4IGzSB12SesV40iP6LxCCrbTIkSGIQBpOOxpBM+0kj62lmaeIHfMWTDoddqTOtqc7s8LYfn+Pw==", "cpu": [ "x64" ], @@ -5855,9 +4283,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.63.3.tgz", - "integrity": "sha512-FVkwK+iUC+mq+GipVK46rRVticfAPtvPUNlqlGXUDxdVk/UGjQiiiUVPUrEXdSpU2ufU0XxLGyTqDtBidDOVmg==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.0.tgz", + "integrity": "sha512-J/6xhutJPtFyIkmHdf4olOdHHKH5kOJNumojdWn+Elv5ICEYTVOa362Vw27TxsK0BLzb1le3EDlO3UbvFK1lnQ==", "cpu": [ "arm" ], @@ -5869,9 +4297,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.63.3.tgz", - "integrity": "sha512-+aGU1t3398yQOVj1Bz8o3e+KtswxAPvO+mtxtNdfXYMkXIHu7XhhkCD7/DEH9q8tF8uhDnMWvfpUKI8y1sZJsg==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.0.tgz", + "integrity": "sha512-G4L/Nnx59d2LvDoV/P4S5lZ7oVLT6hodOHMacqjiq2LL2gts86KbkEBTYL53+fBt0odhf7XPIbIATGoYiJctxg==", "cpu": [ "arm" ], @@ -5883,9 +4311,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.63.3.tgz", - "integrity": "sha512-cR0kjpRXR2KJ2oQK8E2KTPtphs+b9hZ8IhTZubNryt/RsqgdOZBQ2Zq0q5UedtiIi0rs3jVhJh55RE1ZHUVGUA==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.0.tgz", + "integrity": "sha512-zF16pvJDEUksGYRbfnXne7pdklAyj2XDmJeYKgP93oq0cUyX9Y8O7lUo1R+IY1GagP/YBvCEDCe7eEcAKpw//g==", "cpu": [ "arm64" ], @@ -5897,9 +4325,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.63.3.tgz", - "integrity": "sha512-y1RYi4Q3/9ByVWSSt9kX2ustE0B7kFYbJ6zZdVZVyqopZs3yhCTwRfrjIX4vezUJInma/Gs6BOFDJg7yZmJ0IQ==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.0.tgz", + "integrity": "sha512-nIggWn8n+w12+R5lsV+PYYoUY8vuObxPAQqJI7WES+9v0qspYuAHoZMfYM0yLxlipasT5BY9ht5W8t5c/rSCkg==", "cpu": [ "arm64" ], @@ -5911,9 +4339,9 @@ ] }, "node_modules/@rollup/rollup-linux-loong64-gnu": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.63.3.tgz", - "integrity": "sha512-DNhEA5viIj3Z5bZLE4z4oV8N5ozWqDwyt7T6KG7VdLDJ0nW+rNOYlphBl4/3HQkK75qipPLsVOfStHHOwN9WSg==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.0.tgz", + "integrity": "sha512-WLOTiHPzszP0dxIMsHpFeDSOSB5I49Mj8K4+yKE3H1X/D0JRG5XZ5jrctJLMjnUc/LUzaKiwq6EHWNJ8pup8PA==", "cpu": [ "loong64" ], @@ -5925,9 +4353,9 @@ ] }, "node_modules/@rollup/rollup-linux-loong64-musl": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.63.3.tgz", - "integrity": "sha512-17gQCqrIpXBX2Cmi9/TygnVOqGbzsba/iaqcYSL8FY7lNugg+7AiYNs5c5nKWD+NRQha36Sa0CqkJqH4XVHwnQ==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.0.tgz", + "integrity": "sha512-35RK9aRhh7g7Pmeu5gQ01aCvrhXzj9LoBE6xtUcEH1ns+nyTaSzxSpADmBQINu4QiTDGvmQYwo1j5hlg1rRXFw==", "cpu": [ "loong64" ], @@ -5939,9 +4367,9 @@ ] }, "node_modules/@rollup/rollup-linux-ppc64-gnu": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.63.3.tgz", - "integrity": "sha512-6LwVnZRIyINpdku/yOcI8Tm9YqLmhHK5emmlOOnW9tO0SYEm1FmKPcsSAGp0NBlqR2P04xaND4jvN6sTHqhq8A==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.0.tgz", + "integrity": "sha512-RqTfnpoTjuWfPAmqK5p2edt2AMCDJWm6oTn7sKfmyx+6tRga0ip05SJ977o6udTcIiDeF/CJMUfkaN4gtWt6Aw==", "cpu": [ "ppc64" ], @@ -5953,9 +4381,9 @@ ] }, "node_modules/@rollup/rollup-linux-ppc64-musl": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.63.3.tgz", - "integrity": "sha512-xMUqkTXlEUtI/p5AAukMwBRr1enU3efsTeF+bskeFfk8t1C9rcC8sLREcZXmTfAXEbvRdJVSonVJez3TMlbR3w==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.0.tgz", + "integrity": "sha512-RQjZPigjxFvFZDijG6rjlSXxhRaTf9zLYVpGK+lVcga64oMqP1GbgVqCb46eHTTceSIgp89Ja0y5aPe3GFBYHg==", "cpu": [ "ppc64" ], @@ -5967,9 +4395,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.63.3.tgz", - "integrity": "sha512-S3E94co9F9WRRqEaUoQZ38K1gCz6KiM+nL7/3ijq7fDGF3OznjS5TasgYITlvl27GQKtu4lOAOsr5MFwkijvOA==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.0.tgz", + "integrity": "sha512-tjL58mgQcTRnDRpeky+Sth1MKQeYi2Ct6r3Luq9E5aTSjnM/i/JbozqZkKqp9thM5+oDSZxo+05f9kdQedfTGA==", "cpu": [ "riscv64" ], @@ -5981,9 +4409,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.63.3.tgz", - "integrity": "sha512-1QtRDwG42x5BJI3s9mxu5rEjDnfbSnk20HQ9/ylTAYnSwYwxMVb+Vgu34wzzTQ7ogqBybebgQNUDAvZVQ38DbA==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.0.tgz", + "integrity": "sha512-ictoRyVaoZ8C67myHef+8hhCa6IplXJJ/xUCkVCxziV4zxMZh+jvhkhGsPBLqj1S72fnqD0QH5zL4lcaa4X7DQ==", "cpu": [ "riscv64" ], @@ -5995,9 +4423,9 @@ ] }, "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.63.3.tgz", - "integrity": "sha512-BQhejF6ZXOpxbngiNTP12GCGQeaDVL2QXGeBVViKIYzFHM5RKxTxwUMB1fr1BeNFphFMpnRqC5QSXFSa4z6UQw==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.0.tgz", + "integrity": "sha512-8aVvZ2hfr9RLFzBQkQNmYeHLDja8fLeQAmLt757zdKN/B+8L809KlLJKctQjS22wZotptV8G6o7fVPuAs8S1tQ==", "cpu": [ "s390x" ], @@ -6009,9 +4437,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.63.3.tgz", - "integrity": "sha512-SXagRwnI2Wlwlitllu59UK/nGVbD1CKPcNqDplHwIC4BqJcpXFjD32d1R/RbuISa95HdQrZM3/7v4bKiowFaLA==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.0.tgz", + "integrity": "sha512-2dEF8GAcDKwshUfydD+GhosppNyBzhVUHkdFF3CXd3FpOkzj/RZzF5aoEtzklujklT5qFVRU2GK/cFeLaTNKVg==", "cpu": [ "x64" ], @@ -6023,9 +4451,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.63.3.tgz", - "integrity": "sha512-2IPozoEALRCziGqE8O9KMK60PMu5TS1huv4fwoeCexj+WjmcwFtX9CTOVbfXCUqcELAubEwRFPYlzb/WvwY2HQ==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.0.tgz", + "integrity": "sha512-3XHTvoo2hKkh0MiOfS7SkhHjMaaWF7P4F3drocZZaho/Z8w7h/jpnuBHm91BOQLfvrKHs1yR+zir4E8RI3XzTQ==", "cpu": [ "x64" ], @@ -6037,9 +4465,9 @@ ] }, "node_modules/@rollup/rollup-openbsd-x64": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.63.3.tgz", - "integrity": "sha512-AoxqosUHT9IX54hFn2TiN6A7d6ZKTtE6pd2bqWtqkkNJ6HJGaU6FRouGX8L1O7R/ZwsnCnpQrHzb4pDEx+UHRQ==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.0.tgz", + "integrity": "sha512-HKtkzodL4a3KFWDXDoO61cRynAWTR3LnAE0oGtfG9lcNFpNuVYUFOByxDgNqEvic9rvaQbAj+SFwTEWDptRaIw==", "cpu": [ "x64" ], @@ -6051,9 +4479,9 @@ ] }, "node_modules/@rollup/rollup-openharmony-arm64": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.63.3.tgz", - "integrity": "sha512-d+CaftKgmkFBzCwezMqqy1d0QNNYugqLCMcYVQWBy5SS2YfeMP8Q8ripkgx9O8IyBXXLHrJ+aaCV4U96usv6Yg==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.0.tgz", + "integrity": "sha512-JBsxqiY16uyyCujtoC3s7zL+SrYyNElptD7K4V+KUoJ2V8/XG3hPWpheK+SuPwNh1cikJvIZmIdsrYXvD6PLJw==", "cpu": [ "arm64" ], @@ -6065,9 +4493,9 @@ ] }, "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.63.3.tgz", - "integrity": "sha512-xXlDF6nR1eOuXbdDy5Hl5fmtY7teUDevF/k0O7IPoZe4Tpmdv+lgdE5JRsnhQtt37ql9P0VF2kAN9a0OCZdo+Q==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.0.tgz", + "integrity": "sha512-S5Qrijh37qhnUYQ0ay8WN3LuWeKjow7wTUyCOPMZtnXiBXYXdsZETI6ZLfYnQAKovltckPLBFdNeD61P2rJc7g==", "cpu": [ "arm64" ], @@ -6079,9 +4507,9 @@ ] }, "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.63.3.tgz", - "integrity": "sha512-YtXAgLN+JP7Ay6qG3eWhc7IHMQPzLc8r3uvhAvlJIoCz/4Q32+Bl9Fmnywidh8v1GOIMmymjovfqY9ETAtysvA==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.0.tgz", + "integrity": "sha512-zbZ6iMmLFEsCtTdc2/y1F/cDFVNNCPF7Ae8PCT/wdPE//hGwYp6r+MyCLMFX+kOeIe09Pz6ASfnnfpSTN1FJQQ==", "cpu": [ "ia32" ], @@ -6093,9 +4521,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-gnu": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.63.3.tgz", - "integrity": "sha512-WuWtSJRNo549vzcfZyEgfqb6zeSgn1F+UE5kQ+BCjzz0W4MGCjntUHkZVc1VRuAM7+ULaSyhiPxD1spyewFvkQ==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.0.tgz", + "integrity": "sha512-L6Hw69oNpuYaOr1zCG30v0/DqKYCSRwodPGwIcVZ/6f8SOzq9rxtL/xNVI5MO4wjli+Ko0ErK9uHJL3mNPt8wQ==", "cpu": [ "x64" ], @@ -6107,9 +4535,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.63.3.tgz", - "integrity": "sha512-+lIKX7O0+IGe7WuhATaAMMeT7B76vfhXH/l9wLQL+nvyhbw2ohYCKIdWL56JfDu75CWt5oKRP4QFH/jkMtBquA==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.0.tgz", + "integrity": "sha512-nl+CTWIgOGszQmUz/kanfgrfFZ4qiwxKIfT/ryl3N3Ewk5tqizmYtNXiqb7Bu/fDtNgu1kyxdFiAUJNur3iysg==", "cpu": [ "x64" ], @@ -6121,32 +4549,32 @@ ] }, "node_modules/@rspack/binding": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.2.0.tgz", - "integrity": "sha512-nxZzJqqB0EmEKp6qjzFNkBb/SgGt0k0DSENrLvAJgvVvrm3waVsubD0cfxtPlZY/rd5SzadzxWGEHRyFcds5nA==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.2.8.tgz", + "integrity": "sha512-c9flkSua3khHnOKBCRk8BkHGOwU9YB7niv+5JfQXiLZIvJmgKsZ7PD8QrFklMhsJT3oVAc6c9GN7/wy1YkACjA==", "dev": true, "license": "MIT", "optionalDependencies": { - "@rspack/binding-darwin-arm64": "2.2.0", - "@rspack/binding-darwin-x64": "2.2.0", - "@rspack/binding-linux-arm64-gnu": "2.2.0", - "@rspack/binding-linux-arm64-musl": "2.2.0", - "@rspack/binding-linux-ppc64-gnu": "2.2.0", - "@rspack/binding-linux-riscv64-gnu": "2.2.0", - "@rspack/binding-linux-riscv64-musl": "2.2.0", - "@rspack/binding-linux-s390x-gnu": "2.2.0", - "@rspack/binding-linux-x64-gnu": "2.2.0", - "@rspack/binding-linux-x64-musl": "2.2.0", - "@rspack/binding-wasm32-wasi": "2.2.0", - "@rspack/binding-win32-arm64-msvc": "2.2.0", - "@rspack/binding-win32-ia32-msvc": "2.2.0", - "@rspack/binding-win32-x64-msvc": "2.2.0" + "@rspack/binding-darwin-arm64": "2.2.8", + "@rspack/binding-darwin-x64": "2.2.8", + "@rspack/binding-linux-arm64-gnu": "2.2.8", + "@rspack/binding-linux-arm64-musl": "2.2.8", + "@rspack/binding-linux-ppc64-gnu": "2.2.8", + "@rspack/binding-linux-riscv64-gnu": "2.2.8", + "@rspack/binding-linux-riscv64-musl": "2.2.8", + "@rspack/binding-linux-s390x-gnu": "2.2.8", + "@rspack/binding-linux-x64-gnu": "2.2.8", + "@rspack/binding-linux-x64-musl": "2.2.8", + "@rspack/binding-wasm32-wasi": "2.2.8", + "@rspack/binding-win32-arm64-msvc": "2.2.8", + "@rspack/binding-win32-ia32-msvc": "2.2.8", + "@rspack/binding-win32-x64-msvc": "2.2.8" } }, "node_modules/@rspack/binding-darwin-arm64": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.2.0.tgz", - "integrity": "sha512-KAVVT7hp3NBjtc/RY2UtOjzzc8i+s4pIhW1p52UV+Aev6ywQCu3dXwkHTonpPvJO3hqLXc4zIMH5l4HbMqBm4g==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.2.8.tgz", + "integrity": "sha512-d6GuY/k7kJk7SOXmruIz0m+2fIXaLv2SnBHEYsbvBzE7ZO6QXq7fSABWFWNnSnNu+brYHA5Dr/skV81bXgTTCw==", "cpu": [ "arm64" ], @@ -6158,9 +4586,9 @@ ] }, "node_modules/@rspack/binding-darwin-x64": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.2.0.tgz", - "integrity": "sha512-rzyJCX99aFwl540trsVMNZOgK4+IFm2d5+YeP+RdNo9Uprxloz8vHz0J4dYtaq6MRiCAyM60dAwEa3wJMwqWAQ==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.2.8.tgz", + "integrity": "sha512-xCVou/jJASjEAjwy1T3hPJcJqA5QZASJfUwHqEk+nA0v44MagwH8tM8lsOvRfhzR7N2+YFac1rfZOUT8uM3awg==", "cpu": [ "x64" ], @@ -6172,9 +4600,9 @@ ] }, "node_modules/@rspack/binding-linux-arm64-gnu": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.2.0.tgz", - "integrity": "sha512-0t8QOiOMcBV7RvPSsTJ5DQ4QCK6FIyUZy77qbxnS6asGTOXPZZn7V5cL26IxEv/wuHdQ6tQOXheau1fi+gGyBQ==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.2.8.tgz", + "integrity": "sha512-Zy/ss6YAQTjOWKDkcWrbKtu+pySltqT22wn68nlrWKygPWLNmMdU5anlsnwRTIuQ3MF0YJRS42ARauVtlqvRQw==", "cpu": [ "arm64" ], @@ -6186,9 +4614,9 @@ ] }, "node_modules/@rspack/binding-linux-arm64-musl": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.2.0.tgz", - "integrity": "sha512-BAvCukqcuHxUdE294ITCohvhVkEklW8RbkKkR36Uo0WyIiMPGrnvPjARPn0/4Q4xMAz7lUmC60sZrvJHlAOKMw==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.2.8.tgz", + "integrity": "sha512-lxgp5O8PhL3St9p82llHoNoeWzp9jltW5S9F00p00XPJZHUIuxbwfLSzn/6Wg86USEmafLoBkyD9CM8rBd3SNQ==", "cpu": [ "arm64" ], @@ -6200,9 +4628,9 @@ ] }, "node_modules/@rspack/binding-linux-ppc64-gnu": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.2.0.tgz", - "integrity": "sha512-nCHqZLv/E8nm2ccGkb00F5DQtXxzGy3W3X73ArA+N0+zXJUnzRcSRSwr7AE8pVgP/FYfX4yMFgUXy0g0YxYGRA==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.2.8.tgz", + "integrity": "sha512-MY+YqpT02tcDCMgHy+IewQsaz7ql4mbJaAqqMlTIqvQwAUl9dXEP7BL352OgCxm9VRebTldE5lK99A3wVd3zqA==", "cpu": [ "ppc64" ], @@ -6214,9 +4642,9 @@ ] }, "node_modules/@rspack/binding-linux-riscv64-gnu": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.2.0.tgz", - "integrity": "sha512-CA3WEqKFDI6FAZTnCho2n9pmdPWZYAW/S8mqgxd0cx2Jix43at3VyLxhCC7ED5A9WBSFn/AdHaIbVtgoQHVhWA==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.2.8.tgz", + "integrity": "sha512-wmN9OigSGNGCKY+AOYaWI8LJcIi8qvs5KjueBueCKOnTV6MPIEujA75QZH1pehTTYKvdGv7r2EtUXUmWpn7/SQ==", "cpu": [ "riscv64" ], @@ -6228,9 +4656,9 @@ ] }, "node_modules/@rspack/binding-linux-riscv64-musl": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.2.0.tgz", - "integrity": "sha512-kHB960oClkoPRPZ6sdkhRvqbdRIlbpIMYd/Tbxfmn3DWQahiCk1pkUFJbOtFq3EgESxZISV4THl442W2Y57HvQ==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.2.8.tgz", + "integrity": "sha512-ZcQMYR10hLh581zs9MFnFFn0F7wyt5fkDffyukeMHJEoPJrbkfl6cQtsUdpQnZ+mYGYS5KydD1DT9/eMH65jjw==", "cpu": [ "riscv64" ], @@ -6242,9 +4670,9 @@ ] }, "node_modules/@rspack/binding-linux-s390x-gnu": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.2.0.tgz", - "integrity": "sha512-lVBdiffVo1jq0P0jT36jNou2suLB4ueQI4aWUs+HM+h67YPBtVKWu/mo5Wh59+8nowgcZmYaFM5hdH69963I9w==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.2.8.tgz", + "integrity": "sha512-ahBiE+Ir1FMYvStYicihhSJlS2YRagxtry0jWH8zW287o7C0eiHJ+pteJHHC15T5RJqm0j6w5TuwYe+F9AYxxg==", "cpu": [ "s390x" ], @@ -6256,9 +4684,9 @@ ] }, "node_modules/@rspack/binding-linux-x64-gnu": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.2.0.tgz", - "integrity": "sha512-M49UaWspE0YJ3268DsquD8idEQTfjBDMvO/I8qccV/Z5T+Q98FJ+kIs5liUaTWb48OIbDEK+8ZKx5QzLbfVN6g==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.2.8.tgz", + "integrity": "sha512-dncEI515NoPXh3zzWk06Rb3mhSV76myiFKqXiJ8K4fVAe5x/RlweMhvPhHhm7RnIMeBld7BeStzOqj38XFsWGA==", "cpu": [ "x64" ], @@ -6270,9 +4698,9 @@ ] }, "node_modules/@rspack/binding-linux-x64-musl": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.2.0.tgz", - "integrity": "sha512-YYbs0wmey+5blhEQDE4Dax3TwJtqfGwe2QBm3OLphlBHo/fcZVvimzKkMV0/pVrZTLy2z5ZAwNhGMY64bNr77w==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.2.8.tgz", + "integrity": "sha512-pfFyU03PjD0GaQG8zOQOHwq51rrJZetXjTGpMmz7iA1hq/f9lChJsDWrC8/7VXeQLwBofLZlOODqe8OM8OBzgA==", "cpu": [ "x64" ], @@ -6284,9 +4712,9 @@ ] }, "node_modules/@rspack/binding-wasm32-wasi": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.2.0.tgz", - "integrity": "sha512-rerLPTN/HD4EvLNWs3O2N+Eb37eGvLRIP3dXXc3n+UzTebOepAsahNn44vXeRBsE4m/pHkpDJjwgWTytgQ2gBw==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.2.8.tgz", + "integrity": "sha512-3mOJuZTrF56jOh/GD9chLMJKbzPZ6Ty2OIML7+lLz0Yk2XS/xWRfLn85Dmnkb/O6UF65x7+p8VPAIZlBtLTclw==", "cpu": [ "wasm32" ], @@ -6300,9 +4728,9 @@ } }, "node_modules/@rspack/binding-win32-arm64-msvc": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.2.0.tgz", - "integrity": "sha512-JUAmnbOQYGTRyX28vls/MOMonZWcmcCi5YtEq6YMc8Xqh3Qx0HUwaLM/I1xr/N9BX3b8CV0dQDOpNuBc2ei+CA==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.2.8.tgz", + "integrity": "sha512-Cu/RMZT/16s+67xhl6X1pswetL3GLSQl+LnugKRh08Ul21A/tR7vxC4g4aih4u9k5SXCAngxFUt8zAjKnHIBqA==", "cpu": [ "arm64" ], @@ -6314,9 +4742,9 @@ ] }, "node_modules/@rspack/binding-win32-ia32-msvc": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.2.0.tgz", - "integrity": "sha512-wOmQRUaOG0eWH/fnfslA9yK9xKfaq9X+3Xa1TdTJnTqlo0ARJYs6A+Lzjbs7cxdY/o1f12Xe00BG3nQozReUOg==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.2.8.tgz", + "integrity": "sha512-H/erd6di8OapZhhM0raA/7XduPn9jusfLMeO1XF+AmF9WF3HzHgMjha1j+KwtPgQnaH69w6AhY+G2472VIwQmw==", "cpu": [ "ia32" ], @@ -6328,9 +4756,9 @@ ] }, "node_modules/@rspack/binding-win32-x64-msvc": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.2.0.tgz", - "integrity": "sha512-v6/3bFr9+i7hRpgulL9b5qCvZL0VgR4vQGQNqOWezUzZmPUj9LYpvB0L9xZIVwDQ2ug/xBiA58bfg5IbESgoyw==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.2.8.tgz", + "integrity": "sha512-BziHSUlIQM0MliCqdcHuBXSkQGtPoHQTXJce7fsgnTAzQFgPeog92qTNezYI4IrQ7pQouyiVJ2HPieUbVPRKQQ==", "cpu": [ "x64" ], @@ -6342,9 +4770,9 @@ ] }, "node_modules/@rspack/cli": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/cli/-/cli-2.2.0.tgz", - "integrity": "sha512-GSiQPG5v5tN8vYJdUMYX44sPiwVVG8H25fq3LWRydVB4WswDAD/N3qNgWZtFVliQdLH3ZWzFdFUoCyZmea0TMA==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/cli/-/cli-2.2.8.tgz", + "integrity": "sha512-6f5ITncKnqXUKZVHmD3qHMVZzQz+C07oCdci+eqBwLswA3n9AhNiM0LR4Es1ai528rv5SpiUDUFulziqSEl2Cw==", "dev": true, "license": "MIT", "bin": { @@ -6361,13 +4789,13 @@ } }, "node_modules/@rspack/core": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.2.0.tgz", - "integrity": "sha512-3W7oX0BAHbK4VlknH3lfyfRvupzxdZtyEa+DfKmdjzmIAcqYtHnFd0nLqp5dzitDPyDI1TIKkDhpB0AZJn0pVg==", + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.2.8.tgz", + "integrity": "sha512-JugsVrnbMGNYzMH++7gR9enygpP/lAo9PbVRq3XmJg0ryIvCpST0XJjBcccaSjYaaPamsjrddihmgVLMFp+yXw==", "dev": true, "license": "MIT", "dependencies": { - "@rspack/binding": "2.2.0" + "@rspack/binding": "2.2.8" }, "engines": { "node": "^20.19.0 || >=22.12.0" @@ -6385,80 +4813,6 @@ } } }, - "node_modules/@sigstore/bundle": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@sigstore/bundle/-/bundle-4.0.0.tgz", - "integrity": "sha512-NwCl5Y0V6Di0NexvkTqdoVfmjTaQwoLM236r89KEojGmq/jMls8S+zb7yOwAPdXvbwfKDlP+lmXgAL4vKSQT+A==", - "license": "Apache-2.0", - "dependencies": { - "@sigstore/protobuf-specs": "^0.5.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/@sigstore/core": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/@sigstore/core/-/core-3.2.1.tgz", - "integrity": "sha512-qRsxPnCrbC/puegGxKuynfnxgLiHqWStrSjxkoB4YKqq3Z3s4cyZyj42ZdWFAEblNP65C+rBH8EuREHIXoi83g==", - "license": "Apache-2.0", - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/@sigstore/protobuf-specs": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/@sigstore/protobuf-specs/-/protobuf-specs-0.5.1.tgz", - "integrity": "sha512-/ScWUhhoFasJsSRGTVBwId1loQjjnjAfE4djL6ZhrXRpNCmPTnUKF5Jokd58ILseOMjzET3UrMOtJPS9sYeI0g==", - "license": "Apache-2.0", - "engines": { - "node": "^18.17.0 || >=20.5.0" - } - }, - "node_modules/@sigstore/sign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@sigstore/sign/-/sign-4.1.1.tgz", - "integrity": "sha512-Hf4xglukg0XXQ2RiD5vSoLjdPe8OBUPA8XeVjUObheuDcWdYWrnH/BNmxZCzkAy68MzmNCxXLeurJvs6hcP2OQ==", - "license": "Apache-2.0", - "dependencies": { - "@gar/promise-retry": "^1.0.2", - "@sigstore/bundle": "^4.0.0", - "@sigstore/core": "^3.2.0", - "@sigstore/protobuf-specs": "^0.5.0", - "make-fetch-happen": "^15.0.4", - "proc-log": "^6.1.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/@sigstore/tuf": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@sigstore/tuf/-/tuf-4.0.2.tgz", - "integrity": "sha512-TCAzTy0xzdP79EnxSjq9KQ3eaR7+FmudLC6eRKknVKZbV7ZNlGLClAAQb/HMNJ5n2OBNk2GT1tEmU0xuPr+SLQ==", - "license": "Apache-2.0", - "dependencies": { - "@sigstore/protobuf-specs": "^0.5.0", - "tuf-js": "^4.1.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/@sigstore/verify": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@sigstore/verify/-/verify-3.1.1.tgz", - "integrity": "sha512-qv7+G3J2cc6wwFj3yKvXOamzqhMwSk1ogPGmhpS8iXllcPrJaIIBA+4HbttlHVu1pqWTdmaCH/WE7UOC51kdoA==", - "license": "Apache-2.0", - "dependencies": { - "@sigstore/bundle": "^4.0.0", - "@sigstore/core": "^3.2.1", - "@sigstore/protobuf-specs": "^0.5.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/@sphinxxxx/color-conversion": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/@sphinxxxx/color-conversion/-/color-conversion-2.2.2.tgz", @@ -6472,32 +4826,10 @@ "dev": true, "license": "MIT" }, - "node_modules/@tufjs/canonical-json": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@tufjs/canonical-json/-/canonical-json-2.0.0.tgz", - "integrity": "sha512-yVtV8zsdo8qFHe+/3kw81dSLyF7D576A5cCFCi4X7B39tWT7SekaEFUnvnWJHz+9qO7qJTah1JbrDjWKqFtdWA==", - "license": "MIT", - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@tufjs/models": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@tufjs/models/-/models-4.1.0.tgz", - "integrity": "sha512-Y8cK9aggNRsqJVaKUlEYs4s7CvQ1b1ta2DVPyAimb0I2qhzjNk+A+mxvll/klL0RlfuIUei8BF7YWiua4kQqww==", - "license": "MIT", - "dependencies": { - "@tufjs/canonical-json": "2.0.0", - "minimatch": "^10.1.1" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/@tybys/wasm-util": { - "version": "0.10.3", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz", - "integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==", + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", + "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", "dev": true, "license": "MIT", "optional": true, @@ -6523,23 +4855,6 @@ "assertion-error": "^2.0.1" } }, - "node_modules/@types/chai/node_modules/assertion-error": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", - "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - } - }, - "node_modules/@types/cordova": { - "version": "11.0.3", - "resolved": "https://registry.npmjs.org/@types/cordova/-/cordova-11.0.3.tgz", - "integrity": "sha512-kyuRQ40/NWQVhqGIHq78Ehu2Bf9Mlg0LhmSmis6ZFJK7z933FRfYi8tHe/k/0fB+PGfCf95rJC6TO7dopaFvAg==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/deep-eql": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", @@ -6608,13 +4923,13 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "26.1.2", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.2.tgz", - "integrity": "sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg==", + "version": "26.6.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.4.tgz", + "integrity": "sha512-ldVPDCzj7fsaGZrLB0NuHuTvJcsNasysBAqMolr/cgxrLd1xbqxIr3XJiPnHHJUCxj5sNF1vnRj9aWnrVh5Jcg==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~8.3.0" + "undici-types": "~8.9.0" } }, "node_modules/@types/trusted-types": { @@ -6639,9 +4954,9 @@ "license": "MIT" }, "node_modules/@types/ws": { - "version": "8.18.1", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", - "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", "dev": true, "license": "MIT", "dependencies": { @@ -6654,13 +4969,6 @@ "integrity": "sha512-f4q/s76+8nOy+fhrNHyetuoPDR01lmlZB5czfCG+OOnBw/Wf+x48DcCDPmMQY7oL8xYFL8qfenMoiS8DUkKBUw==", "license": "ISC" }, - "node_modules/@ungap/promise-all-settled": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@ungap/promise-all-settled/-/promise-all-settled-1.1.2.tgz", - "integrity": "sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q==", - "dev": true, - "license": "ISC" - }, "node_modules/@vitest/expect": { "version": "4.1.11", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", @@ -6679,16 +4987,6 @@ "url": "https://opencollective.com/vitest" } }, - "node_modules/@vitest/expect/node_modules/chai": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", - "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, "node_modules/@vitest/mocker": { "version": "4.1.11", "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", @@ -6966,15 +5264,6 @@ "@xtuc/long": "4.2.2" } }, - "node_modules/@xmldom/xmldom": { - "version": "0.9.10", - "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.10.tgz", - "integrity": "sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==", - "license": "MIT", - "engines": { - "node": ">=14.6" - } - }, "node_modules/@xterm/addon-attach": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/@xterm/addon-attach/-/addon-attach-0.12.0.tgz", @@ -7042,15 +5331,6 @@ "license": "Apache-2.0", "peer": true }, - "node_modules/abbrev": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz", - "integrity": "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==", - "license": "ISC", - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/acorn": { "version": "8.18.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", @@ -7076,15 +5356,6 @@ "node": ">=0.4.0" } }, - "node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, "node_modules/ajv": { "version": "8.20.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", @@ -7103,9 +5374,9 @@ } }, "node_modules/ajv-formats": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", - "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", "dev": true, "license": "MIT", "dependencies": { @@ -7133,39 +5404,10 @@ "ajv": "^8.8.2" } }, - "node_modules/android-versions": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/android-versions/-/android-versions-2.2.1.tgz", - "integrity": "sha512-FSSdICv/djaE7TuMpv6IWjbv2JwZxJJVQUGz0/9omi1cmdjrKC8tBFo8BZrUFMzZpGien0zQ6KGc4LtC+AC8jA==", - "dev": true, - "license": "MIT", - "dependencies": { - "semver": "^7.5.2" - } - }, - "node_modules/android-versions/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/ansi": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/ansi/-/ansi-0.3.1.tgz", - "integrity": "sha512-iFY7JCgHbepc0b82yLaw4IMortylNb6wG4kL+4R0C3iv6i+RHGHux/yUX5BTiRvSX/shMnngjR1YyNMnXEFh5A==", - "license": "MIT" - }, "node_modules/ansi-colors": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", - "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz", + "integrity": "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==", "dev": true, "license": "MIT", "engines": { @@ -7173,9 +5415,9 @@ } }, "node_modules/ansi-regex": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", - "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz", + "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==", "license": "MIT", "engines": { "node": ">=12" @@ -7233,38 +5475,20 @@ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", "license": "Python-2.0" }, - "node_modules/array-union": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", - "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/assert-plus": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", - "integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==", - "license": "MIT", - "engines": { - "node": ">=0.8" - } - }, "node_modules/assertion-error": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", - "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", "dev": true, "license": "MIT", "engines": { - "node": "*" + "node": ">=12" } }, "node_modules/autoprefixer": { - "version": "10.5.4", - "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.5.4.tgz", - "integrity": "sha512-MaU0U/za7N3r6brxD4YB/l4NSrFzLPlANv6wEuQVaIPlD3L4W9rFcQPbL/EilY9BHhHvhfcz3gInDLrEtWT4EA==", + "version": "10.6.1", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.6.1.tgz", + "integrity": "sha512-cL1Qz6ADZhcEbny/8HPfe99J6HhNoYtpX2LFLIbhgGE7Q1hlQVkYFdetDN7Id3KiQxhDrHwzlHr/YQCnZ8+xSA==", "dev": true, "funding": [ { @@ -7282,8 +5506,8 @@ ], "license": "MIT", "dependencies": { - "browserslist": "^4.28.6", - "caniuse-lite": "^1.0.30001806", + "browserslist": "^4.28.9", + "caniuse-lite": "^1.0.30001810", "fraction.js": "^5.3.4", "picocolors": "^1.1.1", "postcss-value-parser": "^4.2.0" @@ -7348,38 +5572,16 @@ } }, "node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, "license": "MIT" }, "node_modules/baseline-browser-mapping": { - "version": "2.11.19", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.19.tgz", - "integrity": "sha512-Grytf1xOxOEMTGRwx6rLGKkTabd4vMg3VrKdj/7joCmV0qgh4QwMMO6xh34YEXQqirAuUdgQGa5orJQQ+69RBw==", + "version": "2.11.27", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.27.tgz", + "integrity": "sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==", "dev": true, "license": "Apache-2.0", "bin": { @@ -7389,63 +5591,14 @@ "node": ">=6.0.0" } }, - "node_modules/big-integer": { - "version": "1.6.52", - "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", - "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", - "license": "Unlicense", - "engines": { - "node": ">=0.6" - } - }, "node_modules/big.js": { "version": "5.2.2", "resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz", - "integrity": "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": "*" - } - }, - "node_modules/bin-links": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/bin-links/-/bin-links-6.0.0.tgz", - "integrity": "sha512-X4CiKlcV2GjnCMwnKAfbVWpHa++65th9TuzAEYtZoATiOE2DQKhSp4CJlyLoTqdhBKlXjpXjCTYPNNFS33Fi6w==", - "license": "ISC", - "dependencies": { - "cmd-shim": "^8.0.0", - "npm-normalize-package-bin": "^5.0.0", - "proc-log": "^6.0.0", - "read-cmd-shim": "^6.0.0", - "write-file-atomic": "^7.0.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/bin-links/node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/bin-links/node_modules/write-file-atomic": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-7.0.1.tgz", - "integrity": "sha512-OTIk8iR8/aCRWBqvxrzxR0hgxWpnYBblY1S5hDWBQfk/VFmJwzmJgQFN3WsoUKHISv2eAwe+PpbUzyL1CKTLXg==", - "license": "ISC", - "dependencies": { - "signal-exit": "^4.0.1" - }, + "integrity": "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==", + "dev": true, + "license": "MIT", "engines": { - "node": "^20.17.0 || >=22.9.0" + "node": "*" } }, "node_modules/binary-extensions": { @@ -7461,34 +5614,21 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/bplist-parser": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/bplist-parser/-/bplist-parser-0.3.2.tgz", - "integrity": "sha512-apC2+fspHGI3mMKj+dGevkGo/tCqVB8jMb6i+OX+E29p0Iposz07fABkRIfVUPNd5A5VbuOz1bZbnmkKLYF+wQ==", - "license": "MIT", - "dependencies": { - "big-integer": "1.6.x" - }, - "engines": { - "node": ">= 5.10.0" - } - }, "node_modules/brace-expansion": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz", - "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", + "dev": true, "license": "MIT", "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" + "balanced-match": "^1.0.0" } }, "node_modules/braces": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, "license": "MIT", "dependencies": { "fill-range": "^7.1.1" @@ -7505,9 +5645,9 @@ "license": "ISC" }, "node_modules/browserslist": { - "version": "4.28.8", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.8.tgz", - "integrity": "sha512-V2NpofLblG64mfOtSgDhOJESZEGogzDMBv/q+W6oc4LXWP/q75eOXoOaaOu1EOadB9U4Bwx/e0yzbvwKH8zalA==", + "version": "4.29.3", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.3.tgz", + "integrity": "sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==", "dev": true, "funding": [ { @@ -7525,11 +5665,11 @@ ], "license": "MIT", "dependencies": { - "baseline-browser-mapping": "^2.11.12", - "caniuse-lite": "^1.0.30001809", - "electron-to-chromium": "^1.5.402", - "node-releases": "^2.0.53", - "update-browserslist-db": "^1.3.0" + "baseline-browser-mapping": "^2.11.26", + "caniuse-lite": "^1.0.30001813", + "electron-to-chromium": "^1.5.439", + "node-releases": "^2.0.57", + "update-browserslist-db": "^1.3.3" }, "bin": { "browserslist": "cli.js" @@ -7559,31 +5699,11 @@ "node": ">=4.0" } }, - "node_modules/cacache": { - "version": "20.0.4", - "resolved": "https://registry.npmjs.org/cacache/-/cacache-20.0.4.tgz", - "integrity": "sha512-M3Lab8NPYlZU2exsL3bMVvMrMqgwCnMWfdZbK28bn3pK6APT/Te/I8hjRPNu1uwORY9a1eEQoifXbKPQMfMTOA==", - "license": "ISC", - "dependencies": { - "@npmcli/fs": "^5.0.0", - "fs-minipass": "^3.0.0", - "glob": "^13.0.0", - "lru-cache": "^11.1.0", - "minipass": "^7.0.3", - "minipass-collect": "^2.0.1", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "p-map": "^7.0.2", - "ssri": "^13.0.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -7603,9 +5723,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001810", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001810.tgz", - "integrity": "sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==", + "version": "1.0.30001814", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001814.tgz", + "integrity": "sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==", "dev": true, "funding": [ { @@ -7623,626 +5743,155 @@ ], "license": "CC-BY-4.0" }, - "node_modules/chai": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.6.tgz", - "integrity": "sha512-bbcp3YfHCUzMOvKqsztczerVgBKSsEijCySNlHHbX3VG1nskvqjz5Rfso1gGwD6w6oOV3eI60pKuMOV5MV7p3Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "assertion-error": "^1.1.0", - "check-error": "^1.0.2", - "deep-eql": "^3.0.1", - "get-func-name": "^2.0.0", - "loupe": "^2.3.1", - "pathval": "^1.1.1", - "type-detect": "^4.0.5" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/check-error": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz", - "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==", - "dev": true, - "license": "MIT", - "dependencies": { - "get-func-name": "^2.0.2" - }, - "engines": { - "node": "*" - } - }, - "node_modules/chokidar": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", - "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", - "dev": true, - "license": "MIT", - "dependencies": { - "readdirp": "^4.0.1" - }, - "engines": { - "node": ">= 14.16.0" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/chownr": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", - "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/chrome-trace-event": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz", - "integrity": "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=6.0" - } - }, - "node_modules/cli": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/cli/-/cli-1.0.1.tgz", - "integrity": "sha512-41U72MB56TfUMGndAKK8vJ78eooOD4Z5NOL4xEfjc0c23s+6EYKXlXsmACBVclLP1yOfWCgEganVzddVrSNoTg==", - "dev": true, - "license": "MIT", - "dependencies": { - "exit": "0.1.2", - "glob": "^7.1.1" - }, - "engines": { - "node": ">=0.2.5" - } - }, - "node_modules/cli/node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true, - "license": "MIT" - }, - "node_modules/cli/node_modules/brace-expansion": { - "version": "1.1.14", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.14.tgz", - "integrity": "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/cli/node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/cli/node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/cliui": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", - "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==", - "license": "ISC", - "dependencies": { - "string-width": "^7.2.0", - "strip-ansi": "^7.1.0", - "wrap-ansi": "^9.0.0" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cmd-shim": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/cmd-shim/-/cmd-shim-8.0.0.tgz", - "integrity": "sha512-Jk/BK6NCapZ58BKUxlSI+ouKRbjH1NLZCgJkYoab+vEHUY3f6OzpNBN9u7HFSv9J6TRDGs4PLOHezoKGaFRSCA==", - "license": "ISC", - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/codemirror": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.2.tgz", - "integrity": "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==", - "license": "MIT", - "dependencies": { - "@codemirror/autocomplete": "^6.0.0", - "@codemirror/commands": "^6.0.0", - "@codemirror/language": "^6.0.0", - "@codemirror/lint": "^6.0.0", - "@codemirror/search": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, - "license": "MIT" - }, - "node_modules/colors": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", - "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.1.90" - } - }, - "node_modules/com.foxdebug.acode.rk.auth": { - "resolved": "src/plugins/auth", - "link": true - }, - "node_modules/com.foxdebug.acode.rk.customtabs": { - "resolved": "src/plugins/custom-tabs", - "link": true - }, - "node_modules/com.foxdebug.acode.rk.exec.proot": { - "resolved": "src/plugins/proot", - "link": true - }, - "node_modules/com.foxdebug.acode.rk.exec.terminal": { - "resolved": "src/plugins/terminal", - "link": true - }, - "node_modules/com.foxdebug.acode.rk.plugin.plugincontext": { - "resolved": "src/plugins/pluginContext", - "link": true - }, - "node_modules/commander": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz", - "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==", - "license": "MIT", - "engines": { - "node": ">= 12" - } - }, - "node_modules/common-ancestor-path": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/common-ancestor-path/-/common-ancestor-path-2.0.0.tgz", - "integrity": "sha512-dnN3ibLeoRf2HNC+OlCiNc5d2zxbLJXOtiZUudNFSXZrNSydxcCsSpRzXwfu7BBWCIfHPw+xTayeBvJCP/D8Ng==", - "license": "BlueOak-1.0.0", - "engines": { - "node": ">= 18" - } - }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true, - "license": "MIT" - }, - "node_modules/configstore": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/configstore/-/configstore-5.0.1.tgz", - "integrity": "sha512-aMKprgk5YhBNyH25hj8wGt2+D52Sw1DRRIzqBwLp2Ya9mFmY8KPvvtvmna8SxVR9JMZ4kzMD68N22vlaRpkeFA==", - "license": "BSD-2-Clause", - "dependencies": { - "dot-prop": "^5.2.0", - "graceful-fs": "^4.1.2", - "make-dir": "^3.0.0", - "unique-string": "^2.0.0", - "write-file-atomic": "^3.0.0", - "xdg-basedir": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/console-browserify": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz", - "integrity": "sha512-duS7VP5pvfsNLDvL1O4VOEbw37AI3A4ZUQYemvDlnpGrNu9tprR7BYWpDYwC0Xia0Zxz5ZupdiIrUp0GH1aXfg==", - "dev": true, - "dependencies": { - "date-now": "^0.1.4" - } - }, - "node_modules/convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", - "dev": true, - "license": "MIT" - }, - "node_modules/cordova": { - "version": "13.0.0", - "resolved": "https://registry.npmjs.org/cordova/-/cordova-13.0.0.tgz", - "integrity": "sha512-QAIMwmYLL0jHo4vauWSnRd2fr9l+wajG+F5aUkrC6e4ZQGSTv0wAiRmpqQUkIc1ZdELisKDQws/BjHz5nP/sLw==", - "license": "Apache-2.0", - "dependencies": { - "configstore": "^5.0.1", - "cordova-common": "^6.0.0", - "cordova-create": "^6.0.0", - "cordova-lib": "^13.0.0", - "editor": "^1.0.0", - "execa": "^5.1.1", - "nopt": "^9.0.0", - "semver": "^7.7.3", - "systeminformation": "^5.27.11" - }, - "bin": { - "cordova": "bin/cordova" - }, - "engines": { - "node": ">=20.17.0 || >=22.9.0" - } - }, - "node_modules/cordova-android": { - "version": "15.1.0", - "resolved": "https://registry.npmjs.org/cordova-android/-/cordova-android-15.1.0.tgz", - "integrity": "sha512-mnOnOisYUVhyrLCPVlHJBKh4ro+X6nZA7nPqBrpVnyTpiiDiakNCfbBJjSs1MTBUJZ6dcmhhvNKZWPT9w6aGPA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "android-versions": "^2.1.1", - "cordova-common": "^6.0.0", - "dedent": "^1.7.1", - "execa": "^5.1.1", - "fast-glob": "^3.3.3", - "is-path-inside": "^3.0.3", - "nopt": "^9.0.0", - "properties-parser": "^0.6.0", - "semver": "^7.7.4", - "string-argv": "^0.3.2", - "untildify": "^4.0.0", - "which": "^6.0.1" - }, - "engines": { - "node": ">=20.17.0 || >=22.9.0" - } - }, - "node_modules/cordova-android/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, + "license": "MIT", "engines": { - "node": ">=10" + "node": ">=18" } }, - "node_modules/cordova-app-hello-world": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/cordova-app-hello-world/-/cordova-app-hello-world-7.0.0.tgz", - "integrity": "sha512-uDTncFkI73ko+wEf6IEO9bw8lQRMQGnfdi5pPMei4P8+plChNcRW5fxjKlhM/8ZrT8OAWiHsQRrP4pIAn3HQ4g==", - "license": "Apache-2.0" - }, - "node_modules/cordova-clipboard": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/cordova-clipboard/-/cordova-clipboard-1.3.0.tgz", - "integrity": "sha512-IGk4LZm/DJ0Xk/jgakHm4wa+A/lrRP3QfzMAHDG7oWLJS4ISOpfI32Wez4ndnENItRslGyBVyJyKD83CxELCAw==", + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, - "license": "MIT" - }, - "node_modules/cordova-common": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/cordova-common/-/cordova-common-6.0.0.tgz", - "integrity": "sha512-16WPC1DuxVdshV3RoQUXqhcJVdhxWGwiFysA4TkYuboqoev6mgt0JuIJFxmQbzR/DuyuONaVe0L0O0Hf1C08Mg==", - "license": "Apache-2.0", + "license": "MIT", "dependencies": { - "@netflix/nerror": "^1.1.3", - "ansi": "^0.3.1", - "bplist-parser": "^0.3.2", - "elementtree": "^0.1.7", - "endent": "^2.1.0", - "fast-glob": "^3.3.3", - "plist": "^3.1.0" + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" }, "engines": { - "node": ">=20.9.0" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "node_modules/cordova-create": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/cordova-create/-/cordova-create-6.0.0.tgz", - "integrity": "sha512-LD41sLn2GsmAlj3576R3xlUM3BP0rt0CYd5LdbzU82WBI3ApMrrhM6xcHDYJfe1nfSL89O/nb/u/h7+7DhPQeA==", - "license": "Apache-2.0", + "node_modules/chalk/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", "dependencies": { - "cordova-app-hello-world": "^7.0.0", - "cordova-common": "^6.0.0", - "cordova-fetch": "^5.0.0", - "globby": "^11.1.0", - "import-fresh": "^3.3.1", - "isobject": "^4.0.0", - "npm-package-arg": "^13.0.0", - "path-is-inside": "^1.0.2", - "tmp": "^0.2.5", - "valid-identifier": "0.0.2" + "has-flag": "^4.0.0" }, "engines": { - "node": ">=20.17.0 || >=22.9.0" + "node": ">=8" } }, - "node_modules/cordova-fetch": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/cordova-fetch/-/cordova-fetch-5.0.0.tgz", - "integrity": "sha512-fsYnVfx32AOrFO6tw4EkzSig7WjNhze35dKIzdw20zTQetDKEfWA79PpCaoiSeahGi6O2MdnOFabLhEa8se6jg==", - "license": "Apache-2.0", + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", "dependencies": { - "@npmcli/arborist": "^9.1.3", - "cordova-common": "^6.0.0", - "execa": "^5.1.1", - "npm-package-arg": "^13.0.0", - "pacote": "^21.0.0", - "resolve": "^1.22.10", - "semver": "^7.7.2", - "which": "^5.0.0" + "readdirp": "^4.0.1" }, "engines": { - "node": ">=20.9.0", - "npm": ">=8.1.0" - } - }, - "node_modules/cordova-fetch/node_modules/isexe": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", - "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" } }, - "node_modules/cordova-fetch/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, + "node_modules/chrome-trace-event": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz", + "integrity": "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==", + "dev": true, + "license": "MIT", + "peer": true, "engines": { - "node": ">=10" + "node": ">=6.0" } }, - "node_modules/cordova-fetch/node_modules/which": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", - "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==", + "node_modules/cliui": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", + "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==", "license": "ISC", "dependencies": { - "isexe": "^3.1.1" - }, - "bin": { - "node-which": "bin/which.js" + "string-width": "^7.2.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" }, "engines": { - "node": "^18.17.0 || >=20.5.0" + "node": ">=20" } }, - "node_modules/cordova-lib": { - "version": "13.0.0", - "resolved": "https://registry.npmjs.org/cordova-lib/-/cordova-lib-13.0.0.tgz", - "integrity": "sha512-y8WQ+J6JtiU9C72ujvI3p+ScFJkg0VJwNfaUCqk9nPAssw2C6HltHk+ik/WrLUn6uDmwAM6gmfGUIMU2iVrNxA==", - "license": "Apache-2.0", + "node_modules/cliui/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", "dependencies": { - "cordova-common": "^6.0.0", - "cordova-fetch": "^5.0.0", - "detect-indent": "^6.1.0", - "detect-newline": "^3.1.0", - "execa": "^5.1.1", - "globby": "^11.1.0", - "semver": "^7.7.2", - "stringify-package": "^1.0.1", - "write-file-atomic": "^7.0.0" - }, - "engines": { - "node": ">=20.17.0 || >=22.9.0" - } - }, - "node_modules/cordova-lib/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" }, "engines": { - "node": ">=10" - } - }, - "node_modules/cordova-lib/node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "license": "ISC", - "engines": { - "node": ">=14" + "node": ">=18" }, "funding": { - "url": "https://github.com/sponsors/isaacs" + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/cordova-lib/node_modules/write-file-atomic": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-7.0.1.tgz", - "integrity": "sha512-OTIk8iR8/aCRWBqvxrzxR0hgxWpnYBblY1S5hDWBQfk/VFmJwzmJgQFN3WsoUKHISv2eAwe+PpbUzyL1CKTLXg==", - "license": "ISC", + "node_modules/codemirror": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.2.tgz", + "integrity": "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==", + "license": "MIT", "dependencies": { - "signal-exit": "^4.0.1" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/commands": "^6.0.0", + "@codemirror/language": "^6.0.0", + "@codemirror/lint": "^6.0.0", + "@codemirror/search": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0" } }, - "node_modules/cordova-plugin-acode-webview": { - "resolved": "src/plugins/webview", - "link": true - }, - "node_modules/cordova-plugin-advanced-http": { - "resolved": "src/plugins/cordova-plugin-advanced-http", - "link": true - }, - "node_modules/cordova-plugin-browser": { - "resolved": "src/plugins/browser", - "link": true - }, - "node_modules/cordova-plugin-buildinfo": { - "resolved": "src/plugins/cordova-plugin-buildinfo", - "link": true - }, - "node_modules/cordova-plugin-crashhandler": { - "resolved": "src/plugins/cordova-plugin-crashhandler", - "link": true - }, - "node_modules/cordova-plugin-device": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cordova-plugin-device/-/cordova-plugin-device-2.1.0.tgz", - "integrity": "sha512-FU0Lw1jZpuKOgG4v80LrfMAOIMCGfAVPumn7AwaX9S1iU/X3OPZUyoKUgP09q4bxL35IeNPkqNWVKYduAXZ1sg==", + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, - "license": "Apache-2.0", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, "engines": { - "cordovaDependencies": { - "3.0.0": { - "cordova": ">100", - "cordova-electron": ">=3.0.0" - } - } + "node": ">=7.0.0" } }, - "node_modules/cordova-plugin-file": { - "version": "8.1.3", - "resolved": "https://registry.npmjs.org/cordova-plugin-file/-/cordova-plugin-file-8.1.3.tgz", - "integrity": "sha512-KlnP3CapNIsKncoWV5lYcIFYDPl0aZ1J3AH3QESlQX1Cb6Ct0p6GrAUvINyrFsjPbWHj8i0b6la6udVsghbATg==", + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true, - "license": "Apache-2.0", - "engines": { - "cordovaDependencies": { - "5.0.0": { - "cordova-android": ">=6.3.0" - }, - "7.0.0": { - "cordova-android": ">=10.0.0" - }, - "8.0.0": { - "cordova-android": ">=12.0.0" - }, - "9.0.0": { - "cordova": ">100" - } - } - } - }, - "node_modules/cordova-plugin-ftp": { - "resolved": "src/plugins/ftp", - "link": true - }, - "node_modules/cordova-plugin-iap": { - "resolved": "src/plugins/iap", - "link": true - }, - "node_modules/cordova-plugin-sdcard": { - "resolved": "src/plugins/sdcard", - "link": true - }, - "node_modules/cordova-plugin-server": { - "resolved": "src/plugins/server", - "link": true - }, - "node_modules/cordova-plugin-sftp": { - "resolved": "src/plugins/sftp", - "link": true - }, - "node_modules/cordova-plugin-system": { - "resolved": "src/plugins/system", - "link": true - }, - "node_modules/cordova-plugin-websocket": { - "resolved": "src/plugins/websocket", - "link": true + "license": "MIT" }, - "node_modules/cordova/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, + "node_modules/commander": { + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-15.0.0.tgz", + "integrity": "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==", + "license": "MIT", "engines": { - "node": ">=10" + "node": ">=22.12.0" } }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, "node_modules/core-js": { "version": "3.50.0", "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.50.0.tgz", @@ -8258,13 +5907,16 @@ } }, "node_modules/core-js-compat": { - "version": "3.49.0", - "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.49.0.tgz", - "integrity": "sha512-VQXt1jr9cBz03b331DFDCCP90b3fanciLkgiOoy8SBHy06gNf+vQ1A3WFLqG7I8TipYIKeYK9wxd0tUrvHcOZA==", + "version": "3.50.0", + "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.50.0.tgz", + "integrity": "sha512-XGpFGbMLHwSt74YLTKho7Ib242qi6O8MSX+sRokV4oz7iKXvQWGYZthjIhjRGMxjzVkAubBO512dKGYcefmX3Q==", "dev": true, "license": "MIT", "dependencies": { - "browserslist": "^4.28.1" + "browserslist": "^4.28.7" + }, + "engines": { + "node": ">=6.4.0" }, "funding": { "type": "opencollective", @@ -8272,12 +5924,15 @@ } }, "node_modules/core-js-pure": { - "version": "3.49.0", - "resolved": "https://registry.npmjs.org/core-js-pure/-/core-js-pure-3.49.0.tgz", - "integrity": "sha512-XM4RFka59xATyJv/cS3O3Kml72hQXUeGRuuTmMYFxwzc9/7C8OYTaIR/Ji+Yt8DXzsFLNhat15cE/JP15HrCgw==", + "version": "3.50.0", + "resolved": "https://registry.npmjs.org/core-js-pure/-/core-js-pure-3.50.0.tgz", + "integrity": "sha512-6GP3Pxz4IKyWjAfa747vIu/jilB5z29JWROLqH/b+pXVcpgh6tM06ZIBwSuglgVqzDYURhOK6oEzTrG0bCHitA==", "dev": true, "hasInstallScript": true, "license": "MIT", + "engines": { + "node": "*" + }, "funding": { "type": "opencollective", "url": "https://opencollective.com/core-js" @@ -8290,9 +5945,9 @@ "license": "MIT" }, "node_modules/cosmiconfig": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.1.tgz", - "integrity": "sha512-hr4ihw+DBqcvrsEDioRO31Z17x71pUYoNe/4h6Z0wB72p7MU7/9gH8Q3s12NFhHPfYBBOV3qyfUxmr/Yn3shnQ==", + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.2.tgz", + "integrity": "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg==", "dev": true, "license": "MIT", "dependencies": { @@ -8317,59 +5972,15 @@ } }, "node_modules/crelt": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz", - "integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==", + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz", + "integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==", "license": "MIT" }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/cross-spawn/node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "license": "ISC" - }, - "node_modules/cross-spawn/node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/crypto-random-string": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-2.0.0.tgz", - "integrity": "sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/css-loader": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-7.1.4.tgz", - "integrity": "sha512-vv3J9tlOl04WjiMvHQI/9tmIrCxVrj6PFbHemBB1iihpeRbi/I4h033eoFIhwxBBqLhI0KYFS7yvynBFhIZfTw==", + "version": "7.1.5", + "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-7.1.5.tgz", + "integrity": "sha512-Q7iAfQkU2twNBryKX/vGAlE+GAmkF7quhSzAGNK8fBimxk3+tqg245rH52UPb9dioBolBc8rP0ihmHBaDTJQBA==", "dev": true, "license": "MIT", "dependencies": { @@ -8402,23 +6013,11 @@ } } }, - "node_modules/css-loader/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/cssesc": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true, "license": "MIT", "bin": { "cssesc": "bin/cssesc" @@ -8427,12 +6026,6 @@ "node": ">=4" } }, - "node_modules/date-now": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz", - "integrity": "sha512-AsElvov3LoNB7tf5k37H2jYSB+ZZPMT5sG2QjJCcdlV5chIv6htBUBUui2IKRjgtKAKtCBN7Zbwa+MtwLjSeNw==", - "dev": true - }, "node_modules/dayjs": { "version": "1.11.23", "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz", @@ -8443,58 +6036,31 @@ "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, "license": "MIT", "dependencies": { "ms": "^2.1.3" }, "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/decamelize": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-4.0.0.tgz", - "integrity": "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/dedent": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz", - "integrity": "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "babel-plugin-macros": "^3.1.0" + "node": ">=6.0" }, "peerDependenciesMeta": { - "babel-plugin-macros": { + "supports-color": { "optional": true } } }, - "node_modules/deep-eql": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-3.0.1.tgz", - "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==", + "node_modules/decamelize": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-4.0.0.tgz", + "integrity": "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==", "dev": true, "license": "MIT", - "dependencies": { - "type-detect": "^4.0.0" - }, "engines": { - "node": ">=0.12" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/depd": { @@ -8518,15 +6084,6 @@ "npm": "1.2.8000 || >= 1.4.16" } }, - "node_modules/detect-indent": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-6.1.0.tgz", - "integrity": "sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -8537,124 +6094,25 @@ "node": ">=8" } }, - "node_modules/detect-newline": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", - "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/diff": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz", - "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==", + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-5.2.2.tgz", + "integrity": "sha512-vtcDfH3TOjP8UekytvnHH1o1P4FcUdt4eQ1Y+Abap1tk/OB2MWQvcwS2ClCd1zuIhc3JKOx6p3kod8Vfys3E+A==", "dev": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.3.1" } }, - "node_modules/dir-glob": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", - "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", - "license": "MIT", - "dependencies": { - "path-type": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/dom-serializer": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.2.2.tgz", - "integrity": "sha512-2/xPb3ORsQ42nHYiSunXkDjPLBaEj/xTwUO4B7XCZQTRk7EBtTOPaygh10YAAh2OI1Qrp6NWfpAhzswj0ydt9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "domelementtype": "^2.0.1", - "entities": "^2.0.0" - } - }, - "node_modules/dom-serializer/node_modules/domelementtype": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", - "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "license": "BSD-2-Clause" - }, - "node_modules/dom-serializer/node_modules/entities": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", - "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", - "dev": true, - "license": "BSD-2-Clause", - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/domelementtype": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.1.tgz", - "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==", - "dev": true, - "license": "BSD-2-Clause" - }, - "node_modules/domhandler": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.3.0.tgz", - "integrity": "sha512-q9bUwjfp7Eif8jWxxxPSykdRZAb6GkguBGSgvvCrhI9wB71W2K/Kvv4E61CF/mcCfnVJDeDWx/Vb/uAqbDj6UQ==", - "dev": true, - "dependencies": { - "domelementtype": "1" - } - }, "node_modules/dompurify": { - "version": "3.4.14", - "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.14.tgz", - "integrity": "sha512-dVoH9z+MY+C9IilgGCk3YfFqjLi3fChm2OiKJMzh6axrJ5qwxqWaZamgmHrpv22CN/KdbZJuGEGgfQoL00LTdg==", + "version": "3.4.16", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.16.tgz", + "integrity": "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==", "license": "(MPL-2.0 OR Apache-2.0)", "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, - "node_modules/domutils": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz", - "integrity": "sha512-gSu5Oi/I+3wDENBsOWBiRK1eoGxcywYSqg3rR960/+EfY0CF4EX1VPkgHOZ3WiS/Jg2DtliF6BhWcHlfpYUcGw==", - "dev": true, - "dependencies": { - "dom-serializer": "0", - "domelementtype": "1" - } - }, - "node_modules/dot-prop": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-5.3.0.tgz", - "integrity": "sha512-QM8q3zDe58hqUqjraQOmzZ1LIH9SWQJTlEKCH4kJ2oQvLZk7RbQXvtDM2XEq3fwkV9CCvvH4LA0AV+ogFsBM2Q==", - "license": "MIT", - "dependencies": { - "is-obj": "^2.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/editor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/editor/-/editor-1.0.0.tgz", - "integrity": "sha512-SoRmbGStwNYHgKfjOrX2L0mUvp9bUVv0uPppZSOMAntEbcFtoC3MKF5b3T6HQPXKIV+QGY3xPO3JK5it5lVkuw==", - "license": "MIT" - }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -8663,24 +6121,12 @@ "license": "MIT" }, "node_modules/electron-to-chromium": { - "version": "1.5.415", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.415.tgz", - "integrity": "sha512-958V+Kbhtgz+SxXeEVKBjrlKRBIDAYvUJfwhjxMZ5S6ut9jAl7l9ZKBkBrvjyjZE36PabLUo2L8kEeV5O4vgJg==", + "version": "1.5.444", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.444.tgz", + "integrity": "sha512-5ss/uJfoDYDHT0lfJzT6FbcskIzROIOPf0BbbFkGcvDzoJU7i//9GDrwwIHQVmIsrAGiF3ihpADBRIsrEFt1rQ==", "dev": true, "license": "ISC" }, - "node_modules/elementtree": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/elementtree/-/elementtree-0.1.7.tgz", - "integrity": "sha512-wkgGT6kugeQk/P6VZ/f4T+4HB41BVgNBq5CDIZVbQ02nvTVqAiVTbskxxu3eA/X96lMlfYOwnLQpN2v5E1zDEg==", - "license": "Apache-2.0", - "dependencies": { - "sax": "1.1.4" - }, - "engines": { - "node": ">= 0.4.0" - } - }, "node_modules/emmet": { "version": "2.4.11", "resolved": "https://registry.npmjs.org/emmet/-/emmet-2.4.11.tgz", @@ -8714,9 +6160,9 @@ } }, "node_modules/empathic": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/empathic/-/empathic-2.0.1.tgz", - "integrity": "sha512-YGRs8knHhKHVShLkFET/rWAU8kmHbOV5LwN938RHI0pljAJ1Gf6SzXsSmRaEzcXTtOOmVqJ5+WtQPL5uigY50Q==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/empathic/-/empathic-2.1.0.tgz", + "integrity": "sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw==", "dev": true, "license": "MIT", "engines": { @@ -8733,27 +6179,10 @@ "node": ">= 0.8" } }, - "node_modules/endent": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/endent/-/endent-2.1.0.tgz", - "integrity": "sha512-r8VyPX7XL8U01Xgnb1CjZ3XV+z90cXIJ9JPE/R9SEC9vpw2P6CfsRPJmp20DppC5N7ZAMCmjYkJIa744Iyg96w==", - "license": "MIT", - "dependencies": { - "dedent": "^0.7.0", - "fast-json-parse": "^1.0.3", - "objectorarray": "^1.0.5" - } - }, - "node_modules/endent/node_modules/dedent": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", - "integrity": "sha512-Q6fKUPqnAHAyhiUgFU7BUzLiv0kd8saH9al7tnu5Q/okj6dnupxyTgFIBjVzJATdfIAm9NAsvXNzjaKa+bxVyA==", - "license": "MIT" - }, "node_modules/enhanced-resolve": { - "version": "5.24.5", - "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.24.5.tgz", - "integrity": "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A==", + "version": "5.26.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.0.tgz", + "integrity": "sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw==", "dev": true, "license": "MIT", "peer": true, @@ -8766,9 +6195,10 @@ } }, "node_modules/entities": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", - "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "dev": true, "license": "BSD-2-Clause", "engines": { "node": ">=0.12" @@ -8781,6 +6211,7 @@ "version": "2.2.1", "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -8800,15 +6231,16 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" } }, "node_modules/es-module-lexer": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.1.0.tgz", - "integrity": "sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==", + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", "dev": true, "license": "MIT" }, @@ -8910,38 +6342,6 @@ "node": ">=0.8.x" } }, - "node_modules/execa": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", - "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", - "license": "MIT", - "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" - } - }, - "node_modules/exit": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", - "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", - "dev": true, - "engines": { - "node": ">= 0.8.0" - } - }, "node_modules/expect-type": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", @@ -8952,21 +6352,6 @@ "node": ">=12.0.0" } }, - "node_modules/exponential-backoff": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz", - "integrity": "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==", - "license": "Apache-2.0" - }, - "node_modules/extsprintf": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.4.1.tgz", - "integrity": "sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA==", - "engines": [ - "node >=0.6.0" - ], - "license": "MIT" - }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -8974,28 +6359,6 @@ "dev": true, "license": "MIT" }, - "node_modules/fast-glob": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", - "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.8" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/fast-json-parse": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/fast-json-parse/-/fast-json-parse-1.0.3.tgz", - "integrity": "sha512-FRWsaZRWEJ1ESVNbDWmsAlqDk96gPQezzLghafp5J4GUKjbCz3OkAHuZs5TuPEtkbVQERysLp9xv6c24fBm8Aw==", - "license": "MIT" - }, "node_modules/fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", @@ -9004,9 +6367,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz", - "integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==", + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", + "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", "dev": true, "funding": [ { @@ -9020,19 +6383,11 @@ ], "license": "BSD-3-Clause" }, - "node_modules/fastq": { - "version": "1.20.1", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", - "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", - "license": "ISC", - "dependencies": { - "reusify": "^1.0.4" - } - }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, "license": "MIT", "engines": { "node": ">=12.0.0" @@ -9047,9 +6402,9 @@ } }, "node_modules/filesize": { - "version": "11.0.22", - "resolved": "https://registry.npmjs.org/filesize/-/filesize-11.0.22.tgz", - "integrity": "sha512-RlCVs9CY+oSsRnNZn95J9vDXjNjOwddKyTFjOYtA4yxYVIxBnwiVVGJX+TFhsmu3uUf81JDGyijtYL9xgawlTw==", + "version": "11.0.25", + "resolved": "https://registry.npmjs.org/filesize/-/filesize-11.0.25.tgz", + "integrity": "sha512-oPVK4S+B5nRK8eL5FORi4RSzbz/1PmUx17NQLMIWv8tlNVDUFgLY0GNApL7tEebL4WgkBqSJGB3AJsCXUs01hw==", "license": "BSD-3-Clause", "engines": { "node": ">= 10.8.0" @@ -9059,6 +6414,7 @@ "version": "7.1.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, "license": "MIT", "dependencies": { "to-regex-range": "^5.0.1" @@ -9094,6 +6450,16 @@ "flat": "cli.js" } }, + "node_modules/flru": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz", + "integrity": "sha512-kWyh8ADvHBFz6ua5xYOPnUroZTT/bwWfrCeL0Wj1dzG4/YOmOcfJ99W8dOVyyynJN35rZ9aCOtHChqQovV7yog==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/fraction.js": { "version": "5.3.4", "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz", @@ -9145,18 +6511,6 @@ "node": ">= 0.6" } }, - "node_modules/fs-minipass": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-3.0.3.tgz", - "integrity": "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw==", - "license": "ISC", - "dependencies": { - "minipass": "^7.0.3" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -9183,6 +6537,7 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" @@ -9208,9 +6563,9 @@ } }, "node_modules/get-east-asian-width": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz", - "integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", "license": "MIT", "engines": { "node": ">=18" @@ -9219,40 +6574,22 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/get-func-name": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", - "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": "*" - } - }, - "node_modules/get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/glob": { - "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", - "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", - "license": "BlueOak-1.0.0", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz", + "integrity": "sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "ISC", "dependencies": { - "minimatch": "^10.2.2", - "minipass": "^7.1.3", - "path-scurry": "^2.0.2" + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^5.0.1", + "once": "^1.3.0" }, "engines": { - "node": "18 || 20 || >=22" + "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -9262,6 +6599,7 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, "license": "ISC", "dependencies": { "is-glob": "^4.0.1" @@ -9270,46 +6608,18 @@ "node": ">= 6" } }, - "node_modules/globby": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", - "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", - "license": "MIT", - "dependencies": { - "array-union": "^2.1.0", - "dir-glob": "^3.0.1", - "fast-glob": "^3.2.9", - "ignore": "^5.2.0", - "merge2": "^1.4.1", - "slash": "^3.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/graceful-fs": { "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "license": "ISC" - }, - "node_modules/growl": { - "version": "1.10.5", - "resolved": "https://registry.npmjs.org/growl/-/growl-1.10.5.tgz", - "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==", "dev": true, - "license": "MIT", - "engines": { - "node": ">=4.x" - } + "license": "ISC", + "peer": true }, "node_modules/happy-dom": { - "version": "20.11.6", - "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.11.6.tgz", - "integrity": "sha512-Hldbg8AdAa5a5oDcZpjqnGitp7JB0hqWmfv/8qr+kft4vzSD8BHsbdRfzYvL/0QcbKcURC/yyoygbeDQarPvYg==", + "version": "20.14.5", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.14.5.tgz", + "integrity": "sha512-x/RzkpWO40bTjIoT30iQtt64FLLmH/iRcUCN2X//bLx7H3ifkdfPXyqsro/OYtqzIAhiLMMA7mmiOR9C3NOKjQ==", "dev": true, "license": "MIT", "dependencies": { @@ -9325,19 +6635,6 @@ "node": ">=20.0.0" } }, - "node_modules/happy-dom/node_modules/entities": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", - "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -9349,9 +6646,10 @@ } }, "node_modules/hasown": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz", - "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -9361,87 +6659,21 @@ } }, "node_modules/he": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", - "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", - "dev": true, - "license": "MIT", - "bin": { - "he": "bin/he" - } - }, - "node_modules/hosted-git-info": { - "version": "9.0.3", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz", - "integrity": "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==", - "license": "ISC", - "dependencies": { - "lru-cache": "^11.1.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/html-tag-js": { - "version": "2.4.16", - "resolved": "https://registry.npmjs.org/html-tag-js/-/html-tag-js-2.4.16.tgz", - "integrity": "sha512-emVNouMF3t2yXpnnjgxCgkMY2W1ZrVC47qsHIJpPKgaH94Nqv355T7E1ZRkV6mWa3vLImHklH7vEcSURDhfq/A==", - "license": "MIT" - }, - "node_modules/htmlparser2": { - "version": "3.8.3", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.8.3.tgz", - "integrity": "sha512-hBxEg3CYXe+rPIua8ETe7tmG3XDn9B0edOE/e9wH2nLczxzgdu0m0aNHY+5wFZiviLWLdANPJTssa92dMcXQ5Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "domelementtype": "1", - "domhandler": "2.3", - "domutils": "1.5", - "entities": "1.0", - "readable-stream": "1.1" - } - }, - "node_modules/htmlparser2/node_modules/entities": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-1.0.0.tgz", - "integrity": "sha512-LbLqfXgJMmy81t+7c14mnulFHJ170cM6E+0vMXR9k/ZiZwgX8i5pNgjTCX3SO4VeUsFLV+8InixoretwU+MjBQ==", - "dev": true, - "license": "BSD-like" - }, - "node_modules/htmlparser2/node_modules/isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/htmlparser2/node_modules/readable-stream": { - "version": "1.1.14", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", - "integrity": "sha512-+MeVjFf4L44XUkhM1eYbD8fyEsxcV81pqMSR5gblfcLCHfZvbrqy4/qYHE+/R5HoBUT11WV5O08Cr1n3YXkWVQ==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", "dev": true, "license": "MIT", - "dependencies": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.1", - "isarray": "0.0.1", - "string_decoder": "~0.10.x" + "bin": { + "he": "bin/he" } }, - "node_modules/htmlparser2/node_modules/string_decoder": { - "version": "0.10.31", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", - "integrity": "sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ==", - "dev": true, + "node_modules/html-tag-js": { + "version": "2.4.16", + "resolved": "https://registry.npmjs.org/html-tag-js/-/html-tag-js-2.4.16.tgz", + "integrity": "sha512-emVNouMF3t2yXpnnjgxCgkMY2W1ZrVC47qsHIJpPKgaH94Nqv355T7E1ZRkV6mWa3vLImHklH7vEcSURDhfq/A==", "license": "MIT" }, - "node_modules/http-cache-semantics": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz", - "integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==", - "license": "BSD-2-Clause" - }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -9463,41 +6695,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/http-proxy-agent": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", - "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.0", - "debug": "^4.3.4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/https-proxy-agent": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", - "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.2", - "debug": "4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/human-signals": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", - "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", - "license": "Apache-2.0", - "engines": { - "node": ">=10.17.0" - } - }, "node_modules/icss-utils": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/icss-utils/-/icss-utils-5.1.0.tgz", @@ -9511,27 +6708,6 @@ "postcss": "^8.1.0" } }, - "node_modules/ignore": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", - "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "node_modules/ignore-walk": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/ignore-walk/-/ignore-walk-8.0.0.tgz", - "integrity": "sha512-FCeMZT4NiRQGh+YkeKMtWrOmBgWjHjMJ26WQWrRQyoyzqevdaGSakUaJW5xQYmjLlUVk2qUnCjYVBax9EKKg8A==", - "license": "ISC", - "dependencies": { - "minimatch": "^10.0.3" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/immediate": { "version": "3.0.6", "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", @@ -9539,9 +6715,9 @@ "license": "MIT" }, "node_modules/immutable": { - "version": "5.1.5", - "resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.5.tgz", - "integrity": "sha512-t7xcm2siw+hlUM68I+UEOK+z84RzmN59as9DZ7P1l0994DKUWV7UXBMQZVxaoMSRQ+PBZbHCOoBt7a2wxOMt+A==", + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.9.tgz", + "integrity": "sha512-m8nVez3rwrgmWxtLMt1ZYXB2Lv7OKYn/disyxAlSDYAlKSlFoPPfIAmAM/M5xqL4m4C/wAPw7S2/CNaUii1Hxg==", "dev": true, "license": "MIT" }, @@ -9549,6 +6725,7 @@ "version": "3.3.1", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, "license": "MIT", "dependencies": { "parent-module": "^1.0.0", @@ -9572,15 +6749,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "license": "MIT", - "engines": { - "node": ">=0.8.19" - } - }, "node_modules/inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", @@ -9599,24 +6767,6 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, - "node_modules/ini": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/ini/-/ini-6.0.0.tgz", - "integrity": "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ==", - "license": "ISC", - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/ip-address": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz", - "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==", - "license": "MIT", - "engines": { - "node": ">= 12" - } - }, "node_modules/is-arrayish": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", @@ -9638,12 +6788,13 @@ } }, "node_modules/is-core-module": { - "version": "2.16.2", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.2.tgz", - "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==", + "version": "2.17.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.17.0.tgz", + "integrity": "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==", + "dev": true, "license": "MIT", "dependencies": { - "hasown": "^2.0.3" + "hasown": "^2.0.4" }, "engines": { "node": ">= 0.4" @@ -9656,6 +6807,7 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -9675,6 +6827,7 @@ "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, "license": "MIT", "dependencies": { "is-extglob": "^2.1.1" @@ -9687,28 +6840,10 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "license": "MIT", - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/is-obj": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz", - "integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/is-path-inside": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", - "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", "dev": true, "license": "MIT", "engines": { - "node": ">=8" + "node": ">=0.12.0" } }, "node_modules/is-plain-obj": { @@ -9721,24 +6856,6 @@ "node": ">=8" } }, - "node_modules/is-stream": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", - "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/is-typedarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", - "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==", - "license": "MIT" - }, "node_modules/is-unicode-supported": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", @@ -9758,24 +6875,6 @@ "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", "license": "MIT" }, - "node_modules/isexe": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz", - "integrity": "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==", - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=20" - } - }, - "node_modules/isobject": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-4.0.0.tgz", - "integrity": "sha512-S/2fF5wH8SJA/kmwr6HYhK/RI/OkhD84k8ntalo0iJjZikgq1XFvR5M8NPT1x5F7fBwCG3qHfnzeP/Vh/ZxCUA==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/ist": { "version": "1.1.7", "resolved": "https://registry.npmjs.org/ist/-/ist-1.1.7.tgz", @@ -9799,23 +6898,6 @@ "node": ">= 10.13.0" } }, - "node_modules/jest-worker/node_modules/supports-color": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/supports-color?sponsor=1" - } - }, "node_modules/jiti": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", @@ -9827,16 +6909,16 @@ } }, "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", + "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", "dev": true, "license": "MIT" }, "node_modules/js-yaml": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz", - "integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", "dev": true, "funding": [ { @@ -9869,72 +6951,13 @@ "node": ">=6" } }, - "node_modules/jshint": { - "version": "2.13.6", - "resolved": "https://registry.npmjs.org/jshint/-/jshint-2.13.6.tgz", - "integrity": "sha512-IVdB4G0NTTeQZrBoM8C5JFVLjV2KtZ9APgybDA1MK73xb09qFs0jCXyQLnCOp1cSZZZbvhq/6mfXHUTaDkffuQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "cli": "~1.0.0", - "console-browserify": "1.1.x", - "exit": "0.1.x", - "htmlparser2": "3.8.x", - "lodash": "~4.17.21", - "minimatch": "~3.0.2", - "strip-json-comments": "1.0.x" - }, - "bin": { - "jshint": "bin/jshint" - } - }, - "node_modules/jshint/node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true, - "license": "MIT" - }, - "node_modules/jshint/node_modules/brace-expansion": { - "version": "1.1.14", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.14.tgz", - "integrity": "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/jshint/node_modules/lodash": { - "version": "4.17.23", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz", - "integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==", + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", "dev": true, "license": "MIT" }, - "node_modules/jshint/node_modules/minimatch": { - "version": "3.0.8", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.8.tgz", - "integrity": "sha512-6FsRAQsxQ61mw+qP1ZzbL9Bc78x2p5OqNgNpnoAFLTrX8n5Kxph0CsnhmKKNXTWjXqU5L0pGPR7hYk+XWZr60Q==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/json-parse-even-better-errors": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-5.0.0.tgz", - "integrity": "sha512-ZF1nxZ28VhQouRWhUcVlUIN3qwSgPuswK05s/HIaoetAoE/9tngVmCHjSxmSQPav1nd+lPtTL0YZ/2AFdR/iYQ==", - "license": "MIT", - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", @@ -9942,15 +6965,6 @@ "dev": true, "license": "MIT" }, - "node_modules/json-stringify-nice": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/json-stringify-nice/-/json-stringify-nice-1.1.4.tgz", - "integrity": "sha512-5Z5RFW63yxReJ7vANgW6eZFGWaQvnPE3WNmZoOJrSkGju2etKA2L5rrOa1sm877TVTFt57A80BH1bArcmlLfPw==", - "license": "ISC", - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/json5": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", @@ -9970,19 +6984,10 @@ "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==", "license": "MIT" }, - "node_modules/jsonparse": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", - "integrity": "sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==", - "engines": [ - "node >= 0.2.0" - ], - "license": "MIT" - }, "node_modules/jszip": { - "version": "3.10.1", - "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", - "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==", + "version": "3.10.2", + "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.2.tgz", + "integrity": "sha512-3l+rb15IOWtUhU0H5MFqES/T6Kh7abYwjosBey/vD6hDt8zoEffkSC5Ws5SGtgVw3gBx2NEbhTeSW1+kWkpyTQ==", "license": "(MIT OR GPL-3.0-or-later)", "dependencies": { "lie": "~3.3.0", @@ -9991,29 +6996,17 @@ "setimmediate": "^1.0.5" } }, - "node_modules/just-diff": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/just-diff/-/just-diff-6.0.2.tgz", - "integrity": "sha512-S59eriX5u3/QhMNq3v/gm8Kd0w8OS6Tz2FS1NG4blv+z0MuQcBRJyFWjdovM0Rad4/P4aUPFtnkNjMjyMlMSYA==", - "license": "MIT" - }, - "node_modules/just-diff-apply": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/just-diff-apply/-/just-diff-apply-5.5.0.tgz", - "integrity": "sha512-OYTthRfSh55WOItVqwpefPtNt2VdKsq5AnAK6apdtR6yCH8pr0CmSr710J0Mf+WdQy7K/OzMy7K2MgAfdQURDw==", - "license": "MIT" - }, "node_modules/katex": { - "version": "0.16.47", - "resolved": "https://registry.npmjs.org/katex/-/katex-0.16.47.tgz", - "integrity": "sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg==", + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/katex/-/katex-0.19.0.tgz", + "integrity": "sha512-v6Tznz3zJ7u3niRCoDTsumM2+HA2XXcCu+WAacCeHD2z3p9A9Ks987o5FzfTGBN0e8A0vjEgIDvLbICrXpdw/Q==", "funding": [ "https://opencollective.com/katex", "https://github.com/sponsors/katex" ], "license": "MIT", "dependencies": { - "commander": "^8.3.0" + "commander": "^15.0.0" }, "bin": { "katex": "cli.js" @@ -10346,12 +7339,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/lodash": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", - "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", - "license": "MIT" - }, "node_modules/lodash.debounce": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", @@ -10376,25 +7363,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/loupe": { - "version": "2.3.7", - "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", - "integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==", - "dev": true, - "license": "MIT", - "dependencies": { - "get-func-name": "^2.0.1" - } - }, - "node_modules/lru-cache": { - "version": "11.5.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz", - "integrity": "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==", - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -10405,48 +7373,10 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, - "node_modules/make-dir": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", - "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", - "license": "MIT", - "dependencies": { - "semver": "^6.0.0" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/make-fetch-happen": { - "version": "15.0.5", - "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-15.0.5.tgz", - "integrity": "sha512-uCbIa8jWWmQZt4dSnEStkVC6gdakiinAm4PiGsywIkguF0eWMdcjDz0ECYhUolFU3pFLOev9VNPCEygydXnddg==", - "license": "ISC", - "dependencies": { - "@gar/promise-retry": "^1.0.0", - "@npmcli/agent": "^4.0.0", - "@npmcli/redact": "^4.0.0", - "cacache": "^20.0.1", - "http-cache-semantics": "^4.1.1", - "minipass": "^7.0.2", - "minipass-fetch": "^5.0.0", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "negotiator": "^1.0.0", - "proc-log": "^6.0.0", - "ssri": "^13.0.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/markdown-it": { - "version": "14.3.0", - "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.3.0.tgz", - "integrity": "sha512-RCEsPjR+sr0x+AuYp601tKTkgFG4YEPLCzHST3cQ/fhlJkqAkz1L2/Qbp1j9qw5SBwQHFBoW8+hoN5xssOF0Tw==", + "version": "14.3.2", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.3.2.tgz", + "integrity": "sha512-sHHjZ5fJKlgrG4qns2YwVcdNep35h5fERrfkD2YNsb9UFk0UIHarbiTaHKVMlPuWAoiilyK8Fv/jAm11slsY7Q==", "funding": [ { "type": "github", @@ -10516,63 +7446,31 @@ "integrity": "sha512-4hhkiX8/gus+6e53PLCUmUrsa6ZWGgJW2XCW6O0ASvZUiezIK900ZicinTDtG3kAO2kon7oUA/ReWmpW2FByxg==", "license": "MIT" }, - "node_modules/marked": { - "version": "15.0.12", - "resolved": "https://registry.npmjs.org/marked/-/marked-15.0.12.tgz", - "integrity": "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA==", - "license": "MIT", - "bin": { - "marked": "bin/marked.js" - }, + "node_modules/markdown-it/node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "license": "BSD-2-Clause", "engines": { - "node": ">= 18" + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" } }, "node_modules/mdurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz", - "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.1.0.tgz", + "integrity": "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==", "license": "MIT" }, "node_modules/merge-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", - "license": "MIT" - }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", - "license": "MIT", - "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/micromatch/node_modules/picomatch": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", - "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } + "peer": true }, "node_modules/mime": { "version": "1.6.0", @@ -10606,19 +7504,10 @@ }, "engines": { "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/mimic-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "license": "MIT", - "engines": { - "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/mini-css-extract-plugin": { @@ -10643,24 +7532,22 @@ } }, "node_modules/minimatch": { - "version": "10.2.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", - "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", - "license": "BlueOak-1.0.0", + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", + "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", + "dev": true, + "license": "ISC", "dependencies": { - "brace-expansion": "^5.0.5" + "brace-expansion": "^2.0.1" }, "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "node": ">=10" } }, "node_modules/minimizer-webpack-plugin": { - "version": "5.10.0", - "resolved": "https://registry.npmjs.org/minimizer-webpack-plugin/-/minimizer-webpack-plugin-5.10.0.tgz", - "integrity": "sha512-2//60T4S0X1Ug/dqLDOgDaGlZsN1Lv8hf8oB0NOV/KIHSaXlPwXBBIbim79dE2Z7NEs52ES8YHoSv6Lmsk+XNg==", + "version": "5.13.0", + "resolved": "https://registry.npmjs.org/minimizer-webpack-plugin/-/minimizer-webpack-plugin-5.13.0.tgz", + "integrity": "sha512-OO1NF2zHj6sf4CNv2AsUWYcS8WEwkVKQDXxxKzlOxx1Xl+WlqYtVC+oNlGNwGkLAOnpj277BSHypWwRtd9w4JQ==", "dev": true, "license": "MIT", "peer": true, @@ -10731,175 +7618,40 @@ } } }, - "node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/minipass-collect": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-2.0.1.tgz", - "integrity": "sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw==", - "license": "ISC", - "dependencies": { - "minipass": "^7.0.3" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/minipass-fetch": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-5.0.2.tgz", - "integrity": "sha512-2d0q2a8eCi2IRg/IGubCNRJoYbA1+YPXAzQVRFmB45gdGZafyivnZ5YSEfo3JikbjGxOdntGFvBQGqaSMXlAFQ==", - "license": "MIT", - "dependencies": { - "minipass": "^7.0.3", - "minipass-sized": "^2.0.0", - "minizlib": "^3.0.1" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - }, - "optionalDependencies": { - "iconv-lite": "^0.7.2" - } - }, - "node_modules/minipass-fetch/node_modules/iconv-lite": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", - "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", - "license": "MIT", - "optional": true, - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/minipass-flush": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.7.tgz", - "integrity": "sha512-TbqTz9cUwWyHS2Dy89P3ocAGUGxKjjLuR9z8w4WUTGAVgEj17/4nhgo2Du56i0Fm3Pm30g4iA8Lcqctc76jCzA==", - "license": "BlueOak-1.0.0", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/minipass-flush/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-pipeline": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz", - "integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==", - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-pipeline/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-sized": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-2.0.0.tgz", - "integrity": "sha512-zSsHhto5BcUVM2m1LurnXY6M//cGhVaegT71OfOXoprxT6o780GZd792ea6FfrQkuU4usHZIUczAQMRUE2plzA==", - "license": "ISC", - "dependencies": { - "minipass": "^7.1.2" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minizlib": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", - "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", + "node_modules/mocha": { + "version": "10.8.2", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-10.8.2.tgz", + "integrity": "sha512-VZlYo/WE8t1tstuRmqgeyBgCbJc/lEdopaa+axcKzTBJ+UIdlAB9XnmvTCAH4pwR4ElNInaedhEBmZD8iCSVEg==", + "dev": true, "license": "MIT", "dependencies": { - "minipass": "^7.1.2" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/mocha": { - "version": "9.2.2", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-9.2.2.tgz", - "integrity": "sha512-L6XC3EdwT6YrIk0yXpavvLkn8h+EU+Y5UcCHKECyMbdUIxyMuZj4bX4U9e1nvnvUUvQVsV2VHQr5zLdcUkhW/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@ungap/promise-all-settled": "1.1.2", - "ansi-colors": "4.1.1", - "browser-stdout": "1.3.1", - "chokidar": "3.5.3", - "debug": "4.3.3", - "diff": "5.0.0", - "escape-string-regexp": "4.0.0", - "find-up": "5.0.0", - "glob": "7.2.0", - "growl": "1.10.5", - "he": "1.2.0", - "js-yaml": "4.1.0", - "log-symbols": "4.1.0", - "minimatch": "4.2.1", - "ms": "2.1.3", - "nanoid": "3.3.1", - "serialize-javascript": "6.0.0", - "strip-json-comments": "3.1.1", - "supports-color": "8.1.1", - "which": "2.0.2", - "workerpool": "6.2.0", - "yargs": "16.2.0", - "yargs-parser": "20.2.4", - "yargs-unparser": "2.0.0" + "ansi-colors": "^4.1.3", + "browser-stdout": "^1.3.1", + "chokidar": "^3.5.3", + "debug": "^4.3.5", + "diff": "^5.2.0", + "escape-string-regexp": "^4.0.0", + "find-up": "^5.0.0", + "glob": "^8.1.0", + "he": "^1.2.0", + "js-yaml": "^4.1.0", + "log-symbols": "^4.1.0", + "minimatch": "^5.1.6", + "ms": "^2.1.3", + "serialize-javascript": "^6.0.2", + "strip-json-comments": "^3.1.1", + "supports-color": "^8.1.1", + "workerpool": "^6.5.1", + "yargs": "^16.2.0", + "yargs-parser": "^20.2.9", + "yargs-unparser": "^2.0.0" }, "bin": { "_mocha": "bin/_mocha", - "mocha": "bin/mocha" + "mocha": "bin/mocha.js" }, "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/mochajs" + "node": ">= 14.0.0" } }, "node_modules/mocha/node_modules/ansi-regex": { @@ -10912,35 +7664,11 @@ "node": ">=8" } }, - "node_modules/mocha/node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true, - "license": "MIT" - }, - "node_modules/mocha/node_modules/brace-expansion": { - "version": "1.1.15", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz", - "integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, "node_modules/mocha/node_modules/chokidar": { - "version": "3.5.3", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", - "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://paulmillr.com/funding/" - } - ], "license": "MIT", "dependencies": { "anymatch": "~3.1.2", @@ -10954,6 +7682,9 @@ "engines": { "node": ">= 8.10.0" }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, "optionalDependencies": { "fsevents": "~2.3.2" } @@ -10970,31 +7701,6 @@ "wrap-ansi": "^7.0.0" } }, - "node_modules/mocha/node_modules/debug": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz", - "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/mocha/node_modules/debug/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true, - "license": "MIT" - }, "node_modules/mocha/node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -11015,87 +7721,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/mocha/node_modules/glob": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", - "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", - "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/mocha/node_modules/glob/node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/mocha/node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, - "license": "ISC" - }, - "node_modules/mocha/node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "dev": true, - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, - "node_modules/mocha/node_modules/minimatch": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-4.2.1.tgz", - "integrity": "sha512-9Uq1ChtSZO+Mxa/CL1eGizn2vRn3MlLgzhT0Iz8zaY8NdvxvB0d5QdPFmCKf7JKA9Lerx5vRrnwO03jsSfGG9g==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/mocha/node_modules/nanoid": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.1.tgz", - "integrity": "sha512-n6Vs/3KGyxPQd6uO0eH4Bv0ojGSUvuLlIHtC3Y0kEO23YRge8H9x1GCzLn28YX0H66pMkxuaeESFq4tKISKwdw==", - "dev": true, - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, "node_modules/mocha/node_modules/picomatch": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", @@ -11133,66 +7758,21 @@ "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" }, - "engines": { - "node": ">=8" - } - }, - "node_modules/mocha/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/mocha/node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/mocha/node_modules/supports-color": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/supports-color?sponsor=1" + "engines": { + "node": ">=8" } }, - "node_modules/mocha/node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "node_modules/mocha/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, - "license": "ISC", + "license": "MIT", "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" + "ansi-regex": "^5.0.1" }, "engines": { - "node": ">= 8" + "node": ">=8" } }, "node_modules/mocha/node_modules/wrap-ansi": { @@ -11214,9 +7794,9 @@ } }, "node_modules/mocha/node_modules/yargs": { - "version": "16.2.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", - "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "version": "16.2.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.2.tgz", + "integrity": "sha512-Nt9ZJjXTv5R8MHbqby/wXQ6Gi0Bb3TcYZkR1bzuL4yB2OxWPkXknz513gEF0GoA6tn00UpbPvERW8rzCuWCA6w==", "dev": true, "license": "MIT", "dependencies": { @@ -11232,16 +7812,6 @@ "node": ">=10" } }, - "node_modules/mocha/node_modules/yargs-parser": { - "version": "20.2.4", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.4.tgz", - "integrity": "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=10" - } - }, "node_modules/motion": { "version": "12.43.0", "resolved": "https://registry.npmjs.org/motion/-/motion-12.43.0.tgz", @@ -11287,6 +7857,7 @@ "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, "license": "MIT" }, "node_modules/mustache": { @@ -11299,9 +7870,9 @@ } }, "node_modules/nanoid": { - "version": "3.3.18", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz", - "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==", + "version": "3.3.19", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", + "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==", "dev": true, "funding": [ { @@ -11317,15 +7888,6 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, - "node_modules/negotiator": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", - "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, "node_modules/neo-async": { "version": "2.6.2", "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", @@ -11341,67 +7903,16 @@ "license": "MIT", "optional": true }, - "node_modules/node-gyp": { - "version": "12.3.0", - "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-12.3.0.tgz", - "integrity": "sha512-QNcUWM+HgJplcPzBvFBZ9VXacyGZ4+VTOb80PwWR+TlVzoHbRKULNEzpRsnaoxG3Wzr7Qh7BYxGDU3CbKib2Yg==", - "license": "MIT", - "dependencies": { - "env-paths": "^2.2.0", - "exponential-backoff": "^3.1.1", - "graceful-fs": "^4.2.6", - "nopt": "^9.0.0", - "proc-log": "^6.0.0", - "semver": "^7.3.5", - "tar": "^7.5.4", - "tinyglobby": "^0.2.12", - "undici": "^6.25.0", - "which": "^6.0.0" - }, - "bin": { - "node-gyp": "bin/node-gyp.js" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/node-gyp/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/node-releases": { - "version": "2.0.53", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.53.tgz", - "integrity": "sha512-D9UOmYG3UH1V+ENW56t5QXBwJw1YEY18ruVeus89Rw+SyIgjPkCO84bRzO3uNIYosJbNwiabWVn48o3uJLjxFQ==", + "version": "2.0.57", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.57.tgz", + "integrity": "sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==", "dev": true, "license": "MIT", "engines": { "node": ">=18" } }, - "node_modules/nopt": { - "version": "9.0.0", - "resolved": "https://registry.npmjs.org/nopt/-/nopt-9.0.0.tgz", - "integrity": "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw==", - "license": "ISC", - "dependencies": { - "abbrev": "^4.0.0" - }, - "bin": { - "nopt": "bin/nopt.js" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -11412,159 +7923,10 @@ "node": ">=0.10.0" } }, - "node_modules/npm-bundled": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/npm-bundled/-/npm-bundled-5.0.0.tgz", - "integrity": "sha512-JLSpbzh6UUXIEoqPsYBvVNVmyrjVZ1fzEFbqxKkTJQkWBO3xFzFT+KDnSKQWwOQNbuWRwt5LSD6HOTLGIWzfrw==", - "license": "ISC", - "dependencies": { - "npm-normalize-package-bin": "^5.0.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/npm-install-checks": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/npm-install-checks/-/npm-install-checks-8.0.0.tgz", - "integrity": "sha512-ScAUdMpyzkbpxoNekQ3tNRdFI8SJ86wgKZSQZdUxT+bj0wVFpsEMWnkXP0twVe1gJyNF5apBWDJhhIbgrIViRA==", - "license": "BSD-2-Clause", - "dependencies": { - "semver": "^7.1.1" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/npm-install-checks/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/npm-normalize-package-bin": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-5.0.0.tgz", - "integrity": "sha512-CJi3OS4JLsNMmr2u07OJlhcrPxCeOeP/4xq67aWNai6TNWWbTrlNDgl8NcFKVlcBKp18GPj+EzbNIgrBfZhsag==", - "license": "ISC", - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/npm-package-arg": { - "version": "13.0.2", - "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-13.0.2.tgz", - "integrity": "sha512-IciCE3SY3uE84Ld8WZU23gAPPV9rIYod4F+rc+vJ7h7cwAJt9Vk6TVsK60ry7Uj3SRS3bqRRIGuTp9YVlk6WNA==", - "license": "ISC", - "dependencies": { - "hosted-git-info": "^9.0.0", - "proc-log": "^6.0.0", - "semver": "^7.3.5", - "validate-npm-package-name": "^7.0.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/npm-package-arg/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/npm-packlist": { - "version": "10.0.4", - "resolved": "https://registry.npmjs.org/npm-packlist/-/npm-packlist-10.0.4.tgz", - "integrity": "sha512-uMW73iajD8hiH4ZBxEV3HC+eTnppIqwakjOYuvgddnalIw2lJguKviK1pcUJDlIWm1wSJkchpDZDSVVsZEYRng==", - "license": "ISC", - "dependencies": { - "ignore-walk": "^8.0.0", - "proc-log": "^6.0.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/npm-pick-manifest": { - "version": "11.0.3", - "resolved": "https://registry.npmjs.org/npm-pick-manifest/-/npm-pick-manifest-11.0.3.tgz", - "integrity": "sha512-buzyCfeoGY/PxKqmBqn1IUJrZnUi1VVJTdSSRPGI60tJdUhUoSQFhs0zycJokDdOznQentgrpf8LayEHyyYlqQ==", - "license": "ISC", - "dependencies": { - "npm-install-checks": "^8.0.0", - "npm-normalize-package-bin": "^5.0.0", - "npm-package-arg": "^13.0.0", - "semver": "^7.3.5" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/npm-pick-manifest/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/npm-registry-fetch": { - "version": "19.1.1", - "resolved": "https://registry.npmjs.org/npm-registry-fetch/-/npm-registry-fetch-19.1.1.tgz", - "integrity": "sha512-TakBap6OM1w0H73VZVDf44iFXsOS3h+L4wVMXmbWOQroZgFhMch0juN6XSzBNlD965yIKvWg2dfu7NSiaYLxtw==", - "license": "ISC", - "dependencies": { - "@npmcli/redact": "^4.0.0", - "jsonparse": "^1.3.1", - "make-fetch-happen": "^15.0.0", - "minipass": "^7.0.2", - "minipass-fetch": "^5.0.0", - "minizlib": "^3.0.1", - "npm-package-arg": "^13.0.0", - "proc-log": "^6.0.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/npm-run-path": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", - "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", - "license": "MIT", - "dependencies": { - "path-key": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/objectorarray": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/objectorarray/-/objectorarray-1.0.5.tgz", - "integrity": "sha512-eJJDYkhJFFbBBAxeh8xW+weHlkI28n2ZdQV/J/DNfWfSKlGEf2xcfAbZTv3riEXHAhL9SVOTs2pRmXiSTf78xg==", - "license": "ISC" - }, "node_modules/obug": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.3.tgz", - "integrity": "sha512-9miFgM2OFba7hB+pRgvtV84pYTBaoTHohvmIgiRt6dRIzbwEOIaNaP+dIlGs2fNFoB0SeISs0Jz5WFVRid6Xyg==", + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz", + "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==", "dev": true, "funding": [ "https://github.com/sponsors/sxzz", @@ -11598,21 +7960,6 @@ "wrappy": "1" } }, - "node_modules/onetime": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", - "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", - "license": "MIT", - "dependencies": { - "mimic-fn": "^2.1.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/p-limit": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", @@ -11645,49 +7992,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/p-map": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-7.0.4.tgz", - "integrity": "sha512-tkAQEw8ysMzmkhgw8k+1U/iPhWNhykKnSk4Rd5zLoPJCuJaGRPo6YposrZgaxHKzDHdDWWZvE/Sk7hsL2X/CpQ==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/pacote": { - "version": "21.5.0", - "resolved": "https://registry.npmjs.org/pacote/-/pacote-21.5.0.tgz", - "integrity": "sha512-VtZ0SB8mb5Tzw3dXDfVAIjhyVKUHZkS/ZH9/5mpKenwC9sFOXNI0JI7kEF7IMkwOnsWMFrvAZHzx1T5fmrp9FQ==", - "license": "ISC", - "dependencies": { - "@gar/promise-retry": "^1.0.0", - "@npmcli/git": "^7.0.0", - "@npmcli/installed-package-contents": "^4.0.0", - "@npmcli/package-json": "^7.0.0", - "@npmcli/promise-spawn": "^9.0.0", - "@npmcli/run-script": "^10.0.0", - "cacache": "^20.0.0", - "fs-minipass": "^3.0.0", - "minipass": "^7.0.2", - "npm-package-arg": "^13.0.0", - "npm-packlist": "^10.0.1", - "npm-pick-manifest": "^11.0.1", - "npm-registry-fetch": "^19.0.0", - "proc-log": "^6.0.0", - "sigstore": "^4.0.0", - "ssri": "^13.0.0", - "tar": "^7.4.3" - }, - "bin": { - "pacote": "bin/index.js" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/pako": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", @@ -11698,6 +8002,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, "license": "MIT", "dependencies": { "callsites": "^3.0.0" @@ -11706,20 +8011,6 @@ "node": ">=6" } }, - "node_modules/parse-conflict-json": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/parse-conflict-json/-/parse-conflict-json-5.0.1.tgz", - "integrity": "sha512-ZHEmNKMq1wyJXNwLxyHnluPfRAFSIliBvbK/UiOceROt4Xh9Pz0fq49NytIaeaCUf5VR86hwQ/34FCcNU5/LKQ==", - "license": "ISC", - "dependencies": { - "json-parse-even-better-errors": "^5.0.0", - "just-diff": "^6.0.0", - "just-diff-apply": "^5.2.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/parse-json": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", @@ -11739,10 +8030,35 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/parse-json/node_modules/json-parse-even-better-errors": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "node_modules/parse-json/node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/parse-json/node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/parse-json/node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", "dev": true, "license": "MIT" }, @@ -11773,62 +8089,13 @@ "node": ">=8" } }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/path-is-inside": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", - "integrity": "sha512-DUWJr3+ULp4zXmol/SZkFf3JGsS9/SIv+Y3Rt93/UjPpDpklB5f1er4O3POIbUuUJ3FXgqte2Q7SrU6zAqwk8w==", - "license": "(WTFPL OR MIT)" - }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/path-parse": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, "license": "MIT" }, - "node_modules/path-scurry": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", - "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/path-type": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", - "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/pathe": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", @@ -11836,20 +8103,10 @@ "dev": true, "license": "MIT" }, - "node_modules/pathval": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", - "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": "*" - } - }, "node_modules/pele": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/pele/-/pele-1.10.0.tgz", - "integrity": "sha512-hDMEM+GQ01pZin8tst3PRXGeB/xFATvXBreHHtjx2glSNAQ7nHFq7EbMuNJGTbqkYgueWPboLjyUBsAudsb1qQ==", + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/pele/-/pele-1.12.0.tgz", + "integrity": "sha512-3OdOK6rvkaTB569R4/I8U0H82MqPRxj7vfkbowa2rRhgSBPFhvWlfFy5eae0jP+2A6hE8abE17nsdyxJz2VBiQ==", "license": "MIT", "engines": { "node": ">=20" @@ -11874,24 +8131,10 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, - "node_modules/plist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz", - "integrity": "sha512-ZIfcLJC+7E7FBFnDxm9MPmt7D+DidyQ26lewieO75AdhA2ayMtsJSES0iWzqJQbcVRSrTufQoy0DR94xHue0oA==", - "license": "MIT", - "dependencies": { - "@xmldom/xmldom": "^0.9.10", - "base64-js": "^1.5.1", - "xmlbuilder": "^15.1.1" - }, - "engines": { - "node": ">=10.4.0" - } - }, "node_modules/postcss": { - "version": "8.5.26", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", - "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==", + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", "dev": true, "funding": [ { @@ -11909,7 +8152,7 @@ ], "license": "MIT", "dependencies": { - "nanoid": "^3.3.17", + "nanoid": "^3.3.18", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" }, @@ -11946,20 +8189,7 @@ }, "webpack": { "optional": true - } - } - }, - "node_modules/postcss-loader/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" + } } }, "node_modules/postcss-modules-extract-imports": { @@ -12026,9 +8256,10 @@ } }, "node_modules/postcss-selector-parser": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", - "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz", + "integrity": "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw==", + "dev": true, "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -12046,9 +8277,9 @@ "license": "MIT" }, "node_modules/prettier": { - "version": "3.8.3", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.3.tgz", - "integrity": "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==", + "version": "3.9.9", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.9.tgz", + "integrity": "sha512-Z/CJHIkdujO/OtN7nXUii0Rf3VT5SRuhjBA82Xvu2XhBUgX3nhP67T0LHceBdQLex7OOFGTox+Q5Yg8Jk2Qivg==", "dev": true, "license": "MIT", "bin": { @@ -12062,70 +8293,24 @@ } }, "node_modules/prettier-plugin-java": { - "version": "2.9.1", - "resolved": "https://registry.npmjs.org/prettier-plugin-java/-/prettier-plugin-java-2.9.1.tgz", - "integrity": "sha512-qdvMRgSlx5li5fkbIQlMAUSJQn8rIwP2Ux0U1Xg8ganHMAK4UOUoOG00GeZfoLRllSgNt5V3dZOlwUXPLoamSQ==", + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/prettier-plugin-java/-/prettier-plugin-java-2.11.0.tgz", + "integrity": "sha512-pLwm2wHvVvW5eVVLf1cq2orY2ATaIj5ngN8hJ5ZdXYzUHzxrfaZkk2xmu8Mz/duBXAc2xT/cUH5+dK414HQSTw==", "dev": true, "license": "Apache-2.0", "dependencies": { - "web-tree-sitter": "0.26.8" + "web-tree-sitter": "0.27.0" }, "peerDependencies": { "prettier": "^3.0.0" } }, - "node_modules/proc-log": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", - "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", - "license": "ISC", - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/process-nextick-args": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", "license": "MIT" }, - "node_modules/proggy": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/proggy/-/proggy-4.0.0.tgz", - "integrity": "sha512-MbA4R+WQT76ZBm/5JUpV9yqcJt92175+Y0Bodg3HgiXzrmKu7Ggq+bpn6y6wHH+gN9NcyKn3yg1+d47VaKwNAQ==", - "license": "ISC", - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/promise-all-reject-late": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/promise-all-reject-late/-/promise-all-reject-late-1.0.1.tgz", - "integrity": "sha512-vuf0Lf0lOxyQREH7GDIOUMLS7kz+gs8i6B+Yi8dC68a2sychGrHTJYghMBD6k7eUcH0H5P73EckCA48xijWqXw==", - "license": "ISC", - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/promise-call-limit": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/promise-call-limit/-/promise-call-limit-3.0.2.tgz", - "integrity": "sha512-mRPQO2T1QQVw11E7+UdCJu7S61eJVWknzml9sC1heAdj1jxl0fWMBypIt9ZOcLFf8FkG995ZD7RnVk7HH72fZw==", - "license": "ISC", - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/properties-parser": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/properties-parser/-/properties-parser-0.6.0.tgz", - "integrity": "sha512-qvr2cSmoA0dln0MARAKwBzPkkXn7FqwX+RVVNpMdMJc7rt9mqO2cXwluxtux9fHrLhjnPFaQkS8BM0kFrTCnSw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.3.1" - } - }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", @@ -12151,26 +8336,6 @@ "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", "license": "MIT" }, - "node_modules/queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, "node_modules/randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -12265,15 +8430,6 @@ "url": "https://opencollective.com/webpack" } }, - "node_modules/read-cmd-shim": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/read-cmd-shim/-/read-cmd-shim-6.0.0.tgz", - "integrity": "sha512-1zM5HuOfagXCBWMN83fuFI/x+T/UhZ7k+KIzhrHXcQoeX5+7gmaDYjELQHmmzIodumBHeByBJT4QYS7ufAgs7A==", - "license": "ISC", - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/readable-stream": { "version": "2.3.8", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", @@ -12311,9 +8467,9 @@ "license": "MIT" }, "node_modules/regenerate-unicode-properties": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-10.2.2.tgz", - "integrity": "sha512-m03P+zhBeQd1RGnYxrGyDAPpWX/epKirLrp8e3qevZdVkKtnCrjjWczIbYc8+xd6vcTStVlqfycTx1KR4LOr0g==", + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-10.3.0.tgz", + "integrity": "sha512-9ns8odR8e9q3otKeHj3DE80jZYKg6zVeZKE+zQmRKXFoVUcuiTGeO6iusDhPRoIQQPVPRvH+SfBhrTud4eczuw==", "dev": true, "license": "MIT", "dependencies": { @@ -12324,14 +8480,14 @@ } }, "node_modules/regexpu-core": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-6.4.0.tgz", - "integrity": "sha512-0ghuzq67LI9bLXpOX/ISfve/Mq33a4aFRzoQYhnnok1JOFpmE/A2TBGkNVenOGEeSBCjIiWcc6MVOG5HEQv0sA==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-6.5.2.tgz", + "integrity": "sha512-zkmVH92DlzjSFc4xKGZp/2BXIFrDIdBQBC8gUXKCsMgKYb1bkCkxfSuoW1werDjaTEMTbULkHtKFHe1L+Abnaw==", "dev": true, "license": "MIT", "dependencies": { "regenerate": "^1.4.2", - "regenerate-unicode-properties": "^10.2.2", + "regenerate-unicode-properties": "^10.3.0", "regjsgen": "^0.8.0", "regjsparser": "^0.13.0", "unicode-match-property-ecmascript": "^2.0.0", @@ -12349,9 +8505,9 @@ "license": "MIT" }, "node_modules/regjsparser": { - "version": "0.13.2", - "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.13.2.tgz", - "integrity": "sha512-NgRBy2Nx/bE+9F27nVHnqcN5HjyLmecqsqx2PJHu3/IEtADD4WuxuXIVExD5PoSDFVrl78dOonfcOe5O+5nbzQ==", + "version": "0.13.3", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.13.3.tgz", + "integrity": "sha512-ycwFAS14Jw4mppvmK4GR/J6u3WpWpjkEApehuHtLc/8VpPNpDMbQ4WjqwplXifGeyKOzHSFLmSPqzksDQE2Sfg==", "dev": true, "license": "BSD-2-Clause", "dependencies": { @@ -12391,6 +8547,7 @@ "version": "1.22.12", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", + "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -12412,29 +8569,20 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, "license": "MIT", "engines": { "node": ">=4" } }, - "node_modules/reusify": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", - "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", - "license": "MIT", - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" - } - }, "node_modules/rolldown": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.6.tgz", - "integrity": "sha512-vMM4q3aixf46GiF1Kok8jDPFsEpXgFWGjUHXNkNHNm+Y2adXAG2dbX91jkti3i0ZRsOlcmbuzAz1poObSHCmUA==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.12.tgz", + "integrity": "sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.147.0", + "@oxc-project/types": "=0.152.0", "@rolldown/pluginutils": "^1.0.0" }, "bin": { @@ -12444,27 +8592,27 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm-eabi": "1.2.6", - "@rolldown/binding-android-arm64": "1.2.6", - "@rolldown/binding-darwin-arm64": "1.2.6", - "@rolldown/binding-darwin-x64": "1.2.6", - "@rolldown/binding-freebsd-x64": "1.2.6", - "@rolldown/binding-linux-arm-gnueabihf": "1.2.6", - "@rolldown/binding-linux-arm64-gnu": "1.2.6", - "@rolldown/binding-linux-arm64-musl": "1.2.6", - "@rolldown/binding-linux-ppc64-gnu": "1.2.6", - "@rolldown/binding-linux-s390x-gnu": "1.2.6", - "@rolldown/binding-linux-x64-gnu": "1.2.6", - "@rolldown/binding-linux-x64-musl": "1.2.6", - "@rolldown/binding-openharmony-arm64": "1.2.6", - "@rolldown/binding-win32-arm64-msvc": "1.2.6", - "@rolldown/binding-win32-x64-msvc": "1.2.6" + "@rolldown/binding-android-arm-eabi": "1.2.12", + "@rolldown/binding-android-arm64": "1.2.12", + "@rolldown/binding-darwin-arm64": "1.2.12", + "@rolldown/binding-darwin-x64": "1.2.12", + "@rolldown/binding-freebsd-x64": "1.2.12", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.12", + "@rolldown/binding-linux-arm64-gnu": "1.2.12", + "@rolldown/binding-linux-arm64-musl": "1.2.12", + "@rolldown/binding-linux-ppc64-gnu": "1.2.12", + "@rolldown/binding-linux-s390x-gnu": "1.2.12", + "@rolldown/binding-linux-x64-gnu": "1.2.12", + "@rolldown/binding-linux-x64-musl": "1.2.12", + "@rolldown/binding-openharmony-arm64": "1.2.12", + "@rolldown/binding-win32-arm64-msvc": "1.2.12", + "@rolldown/binding-win32-x64-msvc": "1.2.12" } }, "node_modules/rollup": { - "version": "4.63.3", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.3.tgz", - "integrity": "sha512-1i2XreiAoMMXuPGD6Msj2xWrMMkHojNRKivInxGQcg7/1KuPuYlfUutLyh4drnOxUTHX9cHI4wFoat8D/NKaBw==", + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.0.tgz", + "integrity": "sha512-gjA/kFeDfffII8COoPsvLPvE16hWDTEc1+0QKQNKUkuV8iJjqsC4xXs8/FzuL0v9EV39kuxTbAgcFoTRyy2TGQ==", "dev": true, "license": "MIT", "dependencies": { @@ -12479,31 +8627,31 @@ }, "optionalDependencies": { "@napi-rs/lzma-linux-x64-gnu": "1.5.1", - "@rollup/rollup-android-arm-eabi": "4.63.3", - "@rollup/rollup-android-arm64": "4.63.3", - "@rollup/rollup-darwin-arm64": "4.63.3", - "@rollup/rollup-darwin-x64": "4.63.3", - "@rollup/rollup-freebsd-arm64": "4.63.3", - "@rollup/rollup-freebsd-x64": "4.63.3", - "@rollup/rollup-linux-arm-gnueabihf": "4.63.3", - "@rollup/rollup-linux-arm-musleabihf": "4.63.3", - "@rollup/rollup-linux-arm64-gnu": "4.63.3", - "@rollup/rollup-linux-arm64-musl": "4.63.3", - "@rollup/rollup-linux-loong64-gnu": "4.63.3", - "@rollup/rollup-linux-loong64-musl": "4.63.3", - "@rollup/rollup-linux-ppc64-gnu": "4.63.3", - "@rollup/rollup-linux-ppc64-musl": "4.63.3", - "@rollup/rollup-linux-riscv64-gnu": "4.63.3", - "@rollup/rollup-linux-riscv64-musl": "4.63.3", - "@rollup/rollup-linux-s390x-gnu": "4.63.3", - "@rollup/rollup-linux-x64-gnu": "4.63.3", - "@rollup/rollup-linux-x64-musl": "4.63.3", - "@rollup/rollup-openbsd-x64": "4.63.3", - "@rollup/rollup-openharmony-arm64": "4.63.3", - "@rollup/rollup-win32-arm64-msvc": "4.63.3", - "@rollup/rollup-win32-ia32-msvc": "4.63.3", - "@rollup/rollup-win32-x64-gnu": "4.63.3", - "@rollup/rollup-win32-x64-msvc": "4.63.3", + "@rollup/rollup-android-arm-eabi": "4.64.0", + "@rollup/rollup-android-arm64": "4.64.0", + "@rollup/rollup-darwin-arm64": "4.64.0", + "@rollup/rollup-darwin-x64": "4.64.0", + "@rollup/rollup-freebsd-arm64": "4.64.0", + "@rollup/rollup-freebsd-x64": "4.64.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.64.0", + "@rollup/rollup-linux-arm-musleabihf": "4.64.0", + "@rollup/rollup-linux-arm64-gnu": "4.64.0", + "@rollup/rollup-linux-arm64-musl": "4.64.0", + "@rollup/rollup-linux-loong64-gnu": "4.64.0", + "@rollup/rollup-linux-loong64-musl": "4.64.0", + "@rollup/rollup-linux-ppc64-gnu": "4.64.0", + "@rollup/rollup-linux-ppc64-musl": "4.64.0", + "@rollup/rollup-linux-riscv64-gnu": "4.64.0", + "@rollup/rollup-linux-riscv64-musl": "4.64.0", + "@rollup/rollup-linux-s390x-gnu": "4.64.0", + "@rollup/rollup-linux-x64-gnu": "4.64.0", + "@rollup/rollup-linux-x64-musl": "4.64.0", + "@rollup/rollup-openbsd-x64": "4.64.0", + "@rollup/rollup-openharmony-arm64": "4.64.0", + "@rollup/rollup-win32-arm64-msvc": "4.64.0", + "@rollup/rollup-win32-ia32-msvc": "4.64.0", + "@rollup/rollup-win32-x64-gnu": "4.64.0", + "@rollup/rollup-win32-x64-msvc": "4.64.0", "fsevents": "~2.3.2" } }, @@ -12539,80 +8687,16 @@ } } }, - "node_modules/rollup-plugin-dts/node_modules/@babel/code-frame": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.0.tgz", - "integrity": "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@babel/helper-validator-identifier": "^8.0.0", - "js-tokens": "^10.0.0" - }, - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, - "node_modules/rollup-plugin-dts/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.4", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.4.tgz", - "integrity": "sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg==", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": "^22.18.0 || >=24.11.0" - } - }, - "node_modules/rollup-plugin-dts/node_modules/js-tokens": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", - "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/run-parallel": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "queue-microtask": "^1.2.2" - } - }, "node_modules/safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "license": "MIT" }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "license": "MIT", - "optional": true - }, "node_modules/sass": { - "version": "1.103.1", - "resolved": "https://registry.npmjs.org/sass/-/sass-1.103.1.tgz", - "integrity": "sha512-9icZURbP51S6S0QGoyaeqk9uB06GNWxsFYWfH5RgpFgqK5FA8tJcM3AdVxrZEVJ7dz+L87nG95gBKf4VuaMHGw==", + "version": "1.105.1", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.105.1.tgz", + "integrity": "sha512-1CnAWPyrrnVQzXGB/DUep1vYCKCm1CIBr+YxjjiW6wk9qtzemnGP4qicH56T2F9S4Hjtv/Ne3jDz8JqfdDU4oA==", "dev": true, "license": "MIT", "dependencies": { @@ -12701,22 +8785,16 @@ "url": "https://paulmillr.com/funding/" } }, - "node_modules/sax": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/sax/-/sax-1.1.4.tgz", - "integrity": "sha512-5f3k2PbGGp+YtKJjOItpg3P99IMD84E4HOvcfleTb5joCHNXYLsR9yWFPOYGgaeMPDubQILTCMdsFb2OMeOjtg==", - "license": "ISC" - }, "node_modules/schema-utils": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.3.3.tgz", - "integrity": "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==", + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.5.0.tgz", + "integrity": "sha512-zJlMCZ0cAR5p/Y4oVpRoqioDMJcGxaXRrQ/4rP4WyR84vc5z/DolXdbvXeDpTwbtocDFr2rhPqHPErDCUtz2kA==", "dev": true, "license": "MIT", "dependencies": { - "@types/json-schema": "^7.0.9", - "ajv": "^8.9.0", - "ajv-formats": "^2.1.1", + "@types/json-schema": "^7.0.15", + "ajv": "^8.20.0", + "ajv-formats": "^3.0.1", "ajv-keywords": "^5.1.0" }, "engines": { @@ -12728,9 +8806,9 @@ } }, "node_modules/selenium-webdriver": { - "version": "4.49.0", - "resolved": "https://registry.npmjs.org/selenium-webdriver/-/selenium-webdriver-4.49.0.tgz", - "integrity": "sha512-16XqeOEMj+4+p+pzLLyvNWmF5jCY05EKIl3e1anZBgv4+zq7PUTtiNjKtQhMpwosZ0wIMKDFAQ2xdyogOHD4DA==", + "version": "4.50.0", + "resolved": "https://registry.npmjs.org/selenium-webdriver/-/selenium-webdriver-4.50.0.tgz", + "integrity": "sha512-E8DhBVMpnsNwShcxSWG8oCVJLQoPZiEciqz/inH7YkKvnR/kBiSNjaJux+7iuA4x6/77N8T68vWMTJgW169kOg==", "dev": true, "funding": [ { @@ -12745,21 +8823,25 @@ "license": "Apache-2.0", "dependencies": { "@bazel/runfiles": "^6.5.0", - "jszip": "^3.10.1", + "jszip": "^3.10.2", "tmp": "^0.2.7", - "ws": "^8.21.3" + "ws": "^8.22.0" }, "engines": { "node": ">= 22.0.0" } }, "node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" } }, "node_modules/send": { @@ -12805,9 +8887,9 @@ "license": "MIT" }, "node_modules/serialize-javascript": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz", - "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", + "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -12843,27 +8925,6 @@ "dev": true, "license": "ISC" }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/siginfo": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", @@ -12871,76 +8932,6 @@ "dev": true, "license": "ISC" }, - "node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "license": "ISC" - }, - "node_modules/sigstore": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/sigstore/-/sigstore-4.1.0.tgz", - "integrity": "sha512-/fUgUhYghuLzVT/gaJoeVehLCgZiUxPCPMcyVNY0lIf/cTCz58K/WTI7PefDarXxp9nUKpEwg1yyz3eSBMTtgA==", - "license": "Apache-2.0", - "dependencies": { - "@sigstore/bundle": "^4.0.0", - "@sigstore/core": "^3.1.0", - "@sigstore/protobuf-specs": "^0.5.0", - "@sigstore/sign": "^4.1.0", - "@sigstore/tuf": "^4.0.1", - "@sigstore/verify": "^3.1.0" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/smart-buffer": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", - "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", - "license": "MIT", - "engines": { - "node": ">= 6.0.0", - "npm": ">= 3.0.0" - } - }, - "node_modules/socks": { - "version": "2.8.9", - "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.9.tgz", - "integrity": "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw==", - "license": "MIT", - "dependencies": { - "ip-address": "^10.1.1", - "smart-buffer": "^4.2.0" - }, - "engines": { - "node": ">= 10.0.0", - "npm": ">= 3.0.0" - } - }, - "node_modules/socks-proxy-agent": { - "version": "8.0.5", - "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", - "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.2", - "debug": "^4.3.4", - "socks": "^2.8.3" - }, - "engines": { - "node": ">= 14" - } - }, "node_modules/source-map": { "version": "0.7.6", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", @@ -12952,9 +8943,9 @@ } }, "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "dev": true, "license": "BSD-3-Clause", "engines": { @@ -12984,28 +8975,6 @@ "node": ">=0.10.0" } }, - "node_modules/spdx-exceptions": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.5.0.tgz", - "integrity": "sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w==", - "license": "CC-BY-3.0" - }, - "node_modules/spdx-expression-parse": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-4.0.0.tgz", - "integrity": "sha512-Clya5JIij/7C6bRR22+tnGXbc4VKlibKSVj2iHvVeX5iMW7s1SIQlqu699JkODJJIhh/pUu8L0/VLh8xflD+LQ==", - "license": "MIT", - "dependencies": { - "spdx-exceptions": "^2.1.0", - "spdx-license-ids": "^3.0.0" - } - }, - "node_modules/spdx-license-ids": { - "version": "3.0.23", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.23.tgz", - "integrity": "sha512-CWLcCCH7VLu13TgOH+r8p1O/Znwhqv/dbb6lqWy67G+pT1kHmeD/+V36AVb/vq8QMIQwVShJ6Ssl5FPh0fuSdw==", - "license": "CC0-1.0" - }, "node_modules/sprintf": { "version": "0.1.5", "resolved": "https://registry.npmjs.org/sprintf/-/sprintf-0.1.5.tgz", @@ -13017,18 +8986,6 @@ "node": ">=0.2.4" } }, - "node_modules/ssri": { - "version": "13.0.1", - "resolved": "https://registry.npmjs.org/ssri/-/ssri-13.0.1.tgz", - "integrity": "sha512-QUiRf1+u9wPTL/76GTYlKttDEBWV1ga9ZXW8BG6kfdeyyM8LGPix9gROyg9V2+P0xNyF3X2Go526xKFdMZrHSQ==", - "license": "ISC", - "dependencies": { - "minipass": "^7.0.3" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/stackback": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", @@ -13047,9 +9004,9 @@ } }, "node_modules/std-env": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz", - "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", "dev": true, "license": "MIT" }, @@ -13062,40 +9019,22 @@ "safe-buffer": "~5.1.0" } }, - "node_modules/string-argv": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.2.tgz", - "integrity": "sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.6.19" - } - }, "node_modules/string-width": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", - "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz", + "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==", "license": "MIT", "dependencies": { - "emoji-regex": "^10.3.0", - "get-east-asian-width": "^1.0.0", - "strip-ansi": "^7.1.0" + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" }, "engines": { - "node": ">=18" + "node": ">=20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/stringify-package": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/stringify-package/-/stringify-package-1.0.1.tgz", - "integrity": "sha512-sa4DUQsYciMP1xhKWGuFM04fB0LG/9DlluZoSVywUMRNvzid6XucHK0/90xGxRoHrAaROrcHK1aPKaijCtSrhg==", - "deprecated": "This module is not used anymore, and has been replaced by @npmcli/package-json", - "license": "ISC" - }, "node_modules/strip-ansi": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", @@ -13111,26 +9050,17 @@ "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, - "node_modules/strip-final-newline": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/strip-json-comments": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.4.tgz", - "integrity": "sha512-AOPG8EBc5wAikaG1/7uFCNFJwnKOuQwFTpYBdTW6OvWHeZBQBrAA/amefHGrEiOnCPcLFZK6FUPtWVKpQVIRgg==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", "dev": true, "license": "MIT", - "bin": { - "strip-json-comments": "cli.js" - }, "engines": { - "node": ">=0.8.0" + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/style-loader": { @@ -13151,28 +9081,32 @@ } }, "node_modules/style-mod": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz", - "integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==", + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.4.tgz", + "integrity": "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==", "license": "MIT" }, "node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", "dev": true, "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, "engines": { - "node": ">=8" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" } }, "node_modules/supports-preserve-symlinks-flag": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -13181,32 +9115,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/systeminformation": { - "version": "5.31.6", - "resolved": "https://registry.npmjs.org/systeminformation/-/systeminformation-5.31.6.tgz", - "integrity": "sha512-Uv2b2uGGM6ns+26czgW2cYRabYdnswM0ddSOOlryHOaelzsmDSet1iM/NT7VOYxW8x/BW+HkY+b1Ve2pLTSGSA==", - "license": "MIT", - "os": [ - "darwin", - "linux", - "win32", - "freebsd", - "openbsd", - "netbsd", - "sunos", - "android" - ], - "bin": { - "systeminformation": "lib/cli.js" - }, - "engines": { - "node": ">=8.0.0" - }, - "funding": { - "type": "Buy me a coffee", - "url": "https://www.buymeacoffee.com/systeminfo" - } - }, "node_modules/tapable": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz", @@ -13221,31 +9129,6 @@ "url": "https://opencollective.com/webpack" } }, - "node_modules/tar": { - "version": "7.5.22", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz", - "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==", - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/fs-minipass": "^4.0.0", - "chownr": "^3.0.0", - "minipass": "^7.1.2", - "minizlib": "^3.1.0", - "yallist": "^5.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/tar/node_modules/yallist": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", - "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, "node_modules/terminal": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/terminal/-/terminal-0.1.4.tgz", @@ -13294,9 +9177,9 @@ "license": "MIT" }, "node_modules/tinyexec": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.1.2.tgz", - "integrity": "sha512-dAqSqE/RabpBKI8+h26GfLq6Vb3JVXs30XYQjdMjaj/c2tS8IYYMbIzP599KtRj7c57/wYApb3QjgRgXmrCukA==", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", "dev": true, "license": "MIT", "engines": { @@ -13307,6 +9190,7 @@ "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, "license": "MIT", "dependencies": { "fdir": "^6.5.0", @@ -13320,19 +9204,38 @@ } }, "node_modules/tinyrainbow": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz", - "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.2.0.tgz", + "integrity": "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==", "dev": true, "license": "MIT", "engines": { "node": ">=14.0.0" } }, + "node_modules/tldts": { + "version": "7.4.16", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.16.tgz", + "integrity": "sha512-QwBER5KMR86IIjpIiO7H/Z3IMJPsZ1A6RKPAqzTTgOyUQUSt9FdnKcqhTaJmkY6HVrgouZHZR0ncK5QxvmnQeg==", + "license": "MIT", + "dependencies": { + "tldts-core": "^7.4.16" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.4.16", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.16.tgz", + "integrity": "sha512-MDolfaSJtlSK5Y0A1xl3277ekubZwobpBjugknDizI9O5Rm60a1m8k4ICK+MRsCDzPygT81mp3BBf5RKDlFRfA==", + "license": "MIT" + }, "node_modules/tmp": { "version": "0.2.7", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==", + "dev": true, "license": "MIT", "engines": { "node": ">=14.14" @@ -13342,6 +9245,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, "license": "MIT", "dependencies": { "is-number": "^7.0.0" @@ -13360,13 +9264,16 @@ "node": ">=0.6" } }, - "node_modules/treeverse": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/treeverse/-/treeverse-3.0.0.tgz", - "integrity": "sha512-gcANaAnd2QDZFmHFEOF4k7uc1J/6a6z3DJMd/QwEyxLoKGiptJRwid582r7QIsFlFMIZ3SnxfS52S4hm2DHkuQ==", - "license": "ISC", + "node_modules/tough-cookie": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz", + "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==", + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": ">=16" } }, "node_modules/ts-loader": { @@ -13400,39 +9307,6 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, - "node_modules/tuf-js": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/tuf-js/-/tuf-js-4.1.0.tgz", - "integrity": "sha512-50QV99kCKH5P/Vs4E2Gzp7BopNV+KzTXqWeaxrfu5IQJBOULRsTIS9seSsOVT8ZnGXzCyx55nYWAi4qJzpZKEQ==", - "license": "MIT", - "dependencies": { - "@tufjs/models": "4.1.0", - "debug": "^4.4.3", - "make-fetch-happen": "^15.0.1" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/type-detect": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.1.0.tgz", - "integrity": "sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/typedarray-to-buffer": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", - "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", - "license": "MIT", - "dependencies": { - "is-typedarray": "^1.0.0" - } - }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -13466,26 +9340,10 @@ "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==", "license": "MIT" }, - "node_modules/umd-tough-cookie": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/umd-tough-cookie/-/umd-tough-cookie-3.0.0.tgz", - "integrity": "sha512-LgVV1jgzEPgC/zOj6T9OIDBTj7YCGEJkgoxV2gHYv1Crlst1X95lRIF48hFleGgv4v01Z86LxyyLyvl++M2Srg==", - "dev": true, - "license": "MIT" - }, - "node_modules/undici": { - "version": "6.27.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.27.0.tgz", - "integrity": "sha512-YmfV3YnEDzXRC5lZ2jWtWWHKGUm1zIt8AhesR1tens+HTNv+YZlN/dp6G727LOvMJ8xjP9Be7Y2Sdr96LDm+pg==", - "license": "MIT", - "engines": { - "node": ">=18.17" - } - }, "node_modules/undici-types": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", - "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", "dev": true, "license": "MIT" }, @@ -13533,32 +9391,10 @@ "node": ">=4" } }, - "node_modules/unique-string": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz", - "integrity": "sha512-uNaeirEPvpZWSgzwsPGtU2zVSTrn/8L5q/IexZmH0eH6SA73CmAA5U4GwORTxQAZs95TAXLNqeLoPPNO5gZfWg==", - "license": "MIT", - "dependencies": { - "crypto-random-string": "^2.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/untildify": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/untildify/-/untildify-4.0.0.tgz", - "integrity": "sha512-KK8xQ1mkzZeg9inewmFVDNkg3l5LUhoq9kN6iWYB/CC9YMG8HA+c1Q8HwDe6dEX7kErrEVNVBO3fWsVq5iDgtw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/update-browserslist-db": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.1.tgz", - "integrity": "sha512-ZZ61DsRsOnakl74HAmp3oSN4aXUmEWXf+i/yv0h7tIBfICc3VdrFErQKUUKPgu3AMsTUMbcongALEN4l6GSUrQ==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz", + "integrity": "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==", "dev": true, "funding": [ { @@ -13612,21 +9448,6 @@ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", "license": "MIT" }, - "node_modules/valid-identifier": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/valid-identifier/-/valid-identifier-0.0.2.tgz", - "integrity": "sha512-zaSmOW6ykXwrkX0YTuFUSoALNEKGaQHpxBJQLb3TXspRNDpBwbfrIQCZqAQ0LKBlKuyn2YOq7NNd6415hvZ33g==", - "license": "Apache-2.0" - }, - "node_modules/validate-npm-package-name": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-7.0.2.tgz", - "integrity": "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A==", - "license": "ISC", - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/vanilla-picker": { "version": "2.12.3", "resolved": "https://registry.npmjs.org/vanilla-picker/-/vanilla-picker-2.12.3.tgz", @@ -13636,17 +9457,30 @@ "@sphinxxxx/color-conversion": "^2.2.2" } }, + "node_modules/verkit": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/verkit/-/verkit-0.3.2.tgz", + "integrity": "sha512-zj/ob3UsvJGN0whEAKFp53REA5X66hvffVqoCtVQAakJKnKlH+/PcOfMoFwIG/o4rElqLv/ycAFlx8ZlXUorCg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/sxzz" + } + }, "node_modules/vite": { - "version": "8.2.2", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.2.2.tgz", - "integrity": "sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q==", + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.2.tgz", + "integrity": "sha512-SQr1x6W5vVSbROg7vsyXIaxK9b0G7zsT68acdWWRmnBUsgDieLCRG+Rep9WdZgcposvv/GSnr4GUUBqB3vXq6w==", "dev": true, "license": "MIT", "dependencies": { "lightningcss": "^1.33.0", - "picomatch": "^4.0.5", - "postcss": "^8.5.26", - "rolldown": "~1.2.4", + "picomatch": "^4.0.7", + "postcss": "^8.5.28", + "rolldown": "~1.2.11", "tinyglobby": "^0.2.17" }, "bin": { @@ -13663,7 +9497,7 @@ }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", - "@vitejs/devtools": "^0.4.0 || ^0.5.0", + "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", @@ -13816,6 +9650,12 @@ "vscode-uri": "^3.1.0" } }, + "node_modules/vscode-css-languageservice/node_modules/vscode-languageserver-types": { + "version": "3.17.5", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz", + "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==", + "license": "MIT" + }, "node_modules/vscode-html-languageservice": { "version": "5.6.2", "resolved": "https://registry.npmjs.org/vscode-html-languageservice/-/vscode-html-languageservice-5.6.2.tgz", @@ -13842,22 +9682,22 @@ } }, "node_modules/vscode-jsonrpc": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz", - "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==", + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-9.0.3.tgz", + "integrity": "sha512-qETYf9PCl1lVfwR+oBmMfc4vP2nqLNA35ABxorw3j06+xlKRgDVxbLgKm4Y/xPL0YWdeDjLoI4ImICIT3nB0zQ==", "license": "MIT", "engines": { "node": ">=14.0.0" } }, "node_modules/vscode-languageserver-protocol": { - "version": "3.17.5", - "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz", - "integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==", + "version": "3.18.4", + "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.18.4.tgz", + "integrity": "sha512-CCXbyr99dafRJzJH/0Ryk7ly5T8XPmSR0//OuF2w4m+9JiOin7zcAT5iET8GRE7Z9taFBejb3GbM0a0mbjdbrg==", "license": "MIT", "dependencies": { - "vscode-jsonrpc": "8.2.0", - "vscode-languageserver-types": "3.17.5" + "vscode-jsonrpc": "9.0.3", + "vscode-languageserver-types": "3.18.4" } }, "node_modules/vscode-languageserver-textdocument": { @@ -13867,15 +9707,15 @@ "license": "MIT" }, "node_modules/vscode-languageserver-types": { - "version": "3.17.5", - "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz", - "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==", + "version": "3.18.4", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.18.4.tgz", + "integrity": "sha512-nQsacoiijvl0fRf2q28uFDrAVwRhdCa3QveiF7/CX0r18mLR5FU/1WskSsCKOjmEbtteKUnY8x8Yzxop+k0zwg==", "license": "MIT" }, "node_modules/vscode-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", - "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.2.0.tgz", + "integrity": "sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg==", "license": "MIT" }, "node_modules/w3c-keyname": { @@ -13884,15 +9724,6 @@ "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==", "license": "MIT" }, - "node_modules/walk-up-path": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/walk-up-path/-/walk-up-path-4.0.0.tgz", - "integrity": "sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A==", - "license": "ISC", - "engines": { - "node": "20 || >=22" - } - }, "node_modules/watchpack": { "version": "2.5.2", "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.5.2.tgz", @@ -13908,16 +9739,16 @@ } }, "node_modules/web-tree-sitter": { - "version": "0.26.8", - "resolved": "https://registry.npmjs.org/web-tree-sitter/-/web-tree-sitter-0.26.8.tgz", - "integrity": "sha512-4sUwi7ZyOrIk5KLgYLkc2A/F0LFMQnBhfb+2Cdl7ik4ePJ6JD+fk4ofI2sA5eGawBKBaK4Vntt7Ww5KcEsay4A==", + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/web-tree-sitter/-/web-tree-sitter-0.27.0.tgz", + "integrity": "sha512-XK08gj6RwTMQatAG7uVRP8MunqotL/XC19vHgkSPKmELgbGPBj4ECvB8haHOUnyj6ls2B8t42UTro14zxGgAHg==", "dev": true, "license": "MIT" }, "node_modules/webpack": { - "version": "5.110.3", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.110.3.tgz", - "integrity": "sha512-GuizBzRvo9YPpyoNMf3ag7AzxbaW85qrRSqTha345KyJbAFPt3/cMzBM0h+RWg7SK/7DdzRLINP3LvQ0hvr4hg==", + "version": "5.111.1", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.111.1.tgz", + "integrity": "sha512-cNypaz0RP+S4cvQVi1M/3bRUkvNP0xZpL0TjFx+c6jg64VbxD+2weWDgY9UnjRI6dhZgtaj8DU76GGFcJ79xPQ==", "dev": true, "license": "MIT", "peer": true, @@ -13927,17 +9758,15 @@ "@webassemblyjs/ast": "^1.14.1", "@webassemblyjs/wasm-edit": "^1.14.1", "@webassemblyjs/wasm-parser": "^1.14.1", - "acorn": "^8.16.0", "browserslist": "^4.28.1", "chrome-trace-event": "^1.0.2", - "enhanced-resolve": "^5.24.4", + "enhanced-resolve": "^5.25.0", "es-module-lexer": "^2.1.0", "events": "^3.2.0", "graceful-fs": "^4.2.11", "mime-db": "^1.54.0", "minimizer-webpack-plugin": "^5.7.0", - "neo-async": "^2.6.2", - "schema-utils": "^4.3.3", + "schema-utils": "^4.5.0", "tapable": "^2.3.0", "watchpack": "^2.5.2", "webpack-sources": "^3.5.1" @@ -13959,9 +9788,9 @@ } }, "node_modules/webpack-sources": { - "version": "3.5.1", - "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.5.1.tgz", - "integrity": "sha512-jyuiGJdtvY434z5bUZrjz67v76/ePNvFZTp9Mdz29IlH4+GPsgyGjiv0fKI+M7BdkU6ADjulUcKAd3tUK3WlEw==", + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.6.0.tgz", + "integrity": "sha512-EIMmPVvNI0CYXyRPp34F2Qk7W37/BZVZIofS6LAUnrNjCVahS+hO4mxwFJDjQjODTGZDtVzLYoN2+1dYkhk9qA==", "dev": true, "license": "MIT", "peer": true, @@ -13979,21 +9808,6 @@ "node": ">=12" } }, - "node_modules/which": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz", - "integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==", - "license": "ISC", - "dependencies": { - "isexe": "^4.0.0" - }, - "bin": { - "node-which": "bin/which.js" - }, - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/why-is-node-running": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", @@ -14012,9 +9826,9 @@ } }, "node_modules/workerpool": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.2.0.tgz", - "integrity": "sha512-Rsk5qQHJ9eowMH28Jwhe8HEbmdYDX4lwoMWshiCXugjtHqMD9ZbiqSDLxcsfdqsETPzVUtX5s1Z5kStiIM6l4A==", + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.5.1.tgz", + "integrity": "sha512-Fs4dNYcsdpYSAfVxhnl1L5zTksjvOJxtC5hzMNl+1t9B8hTJTdKDyZ5ju7ztgPy+ft9tBFXoOlDNiOT9WUXZlA==", "dev": true, "license": "Apache-2.0" }, @@ -14047,6 +9861,23 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", @@ -14054,22 +9885,10 @@ "dev": true, "license": "ISC" }, - "node_modules/write-file-atomic": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", - "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", - "license": "ISC", - "dependencies": { - "imurmurhash": "^0.1.4", - "is-typedarray": "^1.0.0", - "signal-exit": "^3.0.2", - "typedarray-to-buffer": "^3.1.5" - } - }, "node_modules/ws": { - "version": "8.21.3", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", - "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", "dev": true, "license": "MIT", "engines": { @@ -14088,48 +9907,6 @@ } } }, - "node_modules/xdg-basedir": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-4.0.0.tgz", - "integrity": "sha512-PSNhEJDejZYV7h50BohL09Er9VaIefr2LMAf3OEmpCkjOi34eYyQYAXUTjEQtZJTKcF0E2UKTh+osDLsgNim9Q==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/xml2js": { - "version": "0.4.23", - "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.23.tgz", - "integrity": "sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug==", - "dev": true, - "license": "MIT", - "dependencies": { - "sax": ">=0.6.0", - "xmlbuilder": "~11.0.0" - }, - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/xml2js/node_modules/xmlbuilder": { - "version": "11.0.1", - "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", - "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/xmlbuilder": { - "version": "15.1.1", - "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", - "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==", - "license": "MIT", - "engines": { - "node": ">=8.0" - } - }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", @@ -14139,16 +9916,10 @@ "node": ">=10" } }, - "node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "license": "ISC" - }, "node_modules/yargs": { - "version": "18.1.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.1.0.tgz", - "integrity": "sha512-2rAgRKu54VsHkqI0/tYkmluGXHD4KW7yZoycuqDQ15QOTnc2VVfy0nN/1eMhnQLO00A+dwtK20xuCnc1YGeUyg==", + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.2.0.tgz", + "integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==", "license": "MIT", "dependencies": { "cliui": "^9.0.1", @@ -14163,12 +9934,13 @@ } }, "node_modules/yargs-parser": { - "version": "22.0.0", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", - "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==", + "version": "20.2.9", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", + "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", + "dev": true, "license": "ISC", "engines": { - "node": "^20.19.0 || ^22.12.0 || >=23" + "node": ">=10" } }, "node_modules/yargs-unparser": { @@ -14187,20 +9959,13 @@ "node": ">=10" } }, - "node_modules/yargs/node_modules/string-width": { - "version": "8.2.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.2.2.tgz", - "integrity": "sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg==", - "license": "MIT", - "dependencies": { - "get-east-asian-width": "^1.5.0", - "strip-ansi": "^7.1.2" - }, + "node_modules/yargs/node_modules/yargs-parser": { + "version": "22.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", + "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==", + "license": "ISC", "engines": { - "node": ">=20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": "^20.19.0 || ^22.12.0 || >=23" } }, "node_modules/yocto-queue": { @@ -14215,144 +9980,6 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } - }, - "src/plugins/auth": { - "name": "com.foxdebug.acode.rk.auth", - "version": "1.0.0", - "dev": true, - "license": "MIT" - }, - "src/plugins/browser": { - "name": "cordova-plugin-browser", - "version": "1.0.0", - "dev": true, - "license": "ISC" - }, - "src/plugins/cordova-plugin-advanced-http": { - "version": "3.3.1", - "dev": true, - "engines": [ - { - "name": "cordova", - "version": ">=4.0.0" - } - ], - "license": "MIT", - "devDependencies": { - "chai": "4.3.6", - "colors": "1.4.0", - "cordova": "13.0.0", - "mocha": "9.2.2", - "umd-tough-cookie": "3.0.0", - "xml2js": "0.4.23" - } - }, - "src/plugins/cordova-plugin-buildinfo": { - "version": "4.0.0", - "dev": true, - "license": "MIT", - "devDependencies": { - "jshint": "^2.6.0" - }, - "engines": { - "cordovaDependencies": { - "0.0.0": { - "cordova": ">=4.0.0" - }, - "2.0.0": { - "cordova": ">=5.4.0", - "cordova-android": ">=5.0.0" - }, - "3.0.0": { - "cordova": ">=5.4.0", - "cordova-android": ">=5.0.0" - }, - "4.0.0": { - "cordova": ">=5.4.0", - "cordova-android": ">=5.0.0" - }, - "5.0.0": { - "cordova": ">100" - } - } - } - }, - "src/plugins/cordova-plugin-crashhandler": { - "version": "1.0.0", - "dev": true, - "license": "MIT" - }, - "src/plugins/custom-tabs": { - "name": "com.foxdebug.acode.rk.customtabs", - "version": "1.0.0", - "dev": true, - "license": "MIT" - }, - "src/plugins/ftp": { - "name": "cordova-plugin-ftp", - "version": "1.1.1", - "dev": true, - "license": "Apache-2.0" - }, - "src/plugins/iap": { - "name": "cordova-plugin-iap", - "version": "1.0.0", - "dev": true, - "license": "ISC" - }, - "src/plugins/pluginContext": { - "name": "com.foxdebug.acode.rk.plugin.plugincontext", - "version": "1.0.0", - "dev": true, - "license": "MIT" - }, - "src/plugins/proot": { - "name": "com.foxdebug.acode.rk.exec.proot", - "version": "1.0.0", - "dev": true, - "license": "MIT" - }, - "src/plugins/sdcard": { - "name": "cordova-plugin-sdcard", - "version": "1.1.0", - "dev": true, - "license": "ISC" - }, - "src/plugins/server": { - "name": "cordova-plugin-server", - "version": "1.0.0", - "dev": true, - "license": "MIT" - }, - "src/plugins/sftp": { - "name": "cordova-plugin-sftp", - "version": "1.1.1", - "dev": true, - "license": "Apache-2.0" - }, - "src/plugins/system": { - "name": "cordova-plugin-system", - "version": "1.0.3", - "dev": true, - "license": "ISC" - }, - "src/plugins/terminal": { - "name": "com.foxdebug.acode.rk.exec.terminal", - "version": "1.0.0", - "dev": true, - "license": "MIT" - }, - "src/plugins/websocket": { - "name": "cordova-plugin-websocket", - "version": "0.0.1", - "dev": true, - "license": "Apache-2.0" - }, - "src/plugins/webview": { - "name": "cordova-plugin-acode-webview", - "version": "2.0.0", - "dev": true, - "license": "Apache-2.0" } } } diff --git a/package.json b/package.json index e35b644bc0..68b446d1d6 100644 --- a/package.json +++ b/package.json @@ -1,69 +1,42 @@ { - "name": "com.foxdebug.acode", + "name": "acode-app", "displayName": "Acode", - "version": "1.13.5", - "description": "Acode is a code editor for android", + "version": "1.13.6", + "versionCode": 1023, + "androidPackageId": "com.foxdebug.acode", + "appleAppId": "app.acode", + "description": "Powerful code editor and terminal for IOS and Android", "scripts": { - "lang": "node ./utils/lang.js", - "build": "sh utils/scripts/build.sh", - "build:admob": "npm ci --prefix src/plugins/admob --no-audit --no-fund && npm run build --prefix src/plugins/admob", - "start": "sh utils/scripts/start.sh", - "dev": "node utils/scripts/dev.js", - "dev:android": "node utils/scripts/dev.js android", - "clean": "sh utils/scripts/clean.sh android android", - "plugin": "sh utils/scripts/plugin.sh", - "setup": "node ./utils/setup.js", + "lang": "node ./dev/lang.js", + "build": "sh dev/scripts/build.sh", + "start": "sh dev/scripts/start.sh", + "dev": "node dev/scripts/dev.js", + "dev:android": "node dev/scripts/dev.js android", + "dev:ios": "node dev/scripts/dev.js ios", "lint": "biome lint --write", "format": "biome format --write", "check": "biome check --write", - "check:admob-bundle": "node utils/scripts/checkAdmobBundle.js", "test": "vitest run", + "test:android": "node dev/scripts/android.js test", + "test:ios": "node dev/scripts/ios.js test", "typecheck": "tsc --noEmit", - "updateAce": "node ./utils/updateAce.js", "test:watch": "vitest" }, "keywords": [ - "ecosystem:cordova" + "acode", + "android", + "editor" ], "author": "Foxdebug (Ajit Kumar)", "license": "MIT", - "cordova": { - "plugins": { - "cordova-clipboard": {}, - "cordova-plugin-device": {}, - "cordova-plugin-file": {}, - "cordova-plugin-server": {}, - "cordova-plugin-ftp": {}, - "cordova-plugin-sdcard": {}, - "cordova-plugin-websocket": {}, - "cordova-plugin-buildinfo": {}, - "cordova-plugin-browser": {}, - "cordova-plugin-sftp": {}, - "com.foxdebug.acode.rk.exec.terminal": {}, - "com.foxdebug.acode.rk.plugin.plugincontext": {}, - "com.foxdebug.acode.rk.auth": {}, - "com.foxdebug.acode.rk.exec.proot": {}, - "cordova-plugin-iap": {}, - "com.foxdebug.acode.rk.customtabs": {}, - "cordova-plugin-crashhandler": {}, - "cordova-plugin-advanced-http": { - "ANDROIDBLACKLISTSECURESOCKETPROTOCOLS": "SSLv3,TLSv1" - }, - "cordova-plugin-acode-webview": {}, - "cordova-plugin-system": {} - }, - "platforms": [ - "android" - ] - }, "repository": { "type": "git", - "url": "git+https://github.com/deadlyjack/acode.git" + "url": "git+https://github.com/Acode-Foundation/Acode.git" }, "bugs": { - "url": "https://github.com/deadlyjack/acode/issues" + "url": "https://github.com/Acode-Foundation/Acode/issues" }, - "homepage": "https://github.com/deadlyjack/acode#readme", + "homepage": "https://acode.app", "devDependencies": { "@babel/core": "^8.0.1", "@babel/generator": "^7.29.8", @@ -79,34 +52,11 @@ "@rspack/cli": "^2.2.0", "@rspack/core": "^2.2.0", "@types/ace": "^0.0.52", - "@types/cordova": "^11.0.3", "@types/url-parse": "^1.4.11", "autoprefixer": "^10.5.4", "babel-loader": "^10.1.1", "chokidar": "^4.0.3", - "com.foxdebug.acode.rk.auth": "file:src/plugins/auth", - "com.foxdebug.acode.rk.customtabs": "file:src/plugins/custom-tabs", - "com.foxdebug.acode.rk.exec.proot": "file:src/plugins/proot", - "com.foxdebug.acode.rk.exec.terminal": "file:src/plugins/terminal", - "com.foxdebug.acode.rk.plugin.plugincontext": "file:src/plugins/pluginContext", - "cordova-android": "^15.1.0", - "cordova-clipboard": "^1.3.0", - "cordova-plugin-acode-webview": "file:src/plugins/webview", - "cordova-plugin-advanced-http": "file:src/plugins/cordova-plugin-advanced-http", - "cordova-plugin-browser": "file:src/plugins/browser", - "cordova-plugin-buildinfo": "file:src/plugins/cordova-plugin-buildinfo", - "cordova-plugin-crashhandler": "file:src/plugins/cordova-plugin-crashhandler", - "cordova-plugin-device": "^2.1.0", - "cordova-plugin-file": "^8.1.3", - "cordova-plugin-ftp": "file:src/plugins/ftp", - "cordova-plugin-iap": "file:src/plugins/iap", - "cordova-plugin-sdcard": "file:src/plugins/sdcard", - "cordova-plugin-server": "file:src/plugins/server", - "cordova-plugin-sftp": "file:src/plugins/sftp", - "cordova-plugin-system": "file:src/plugins/system", - "cordova-plugin-websocket": "file:src/plugins/websocket", "css-loader": "^7.1.4", - "elementtree": "^0.1.7", "happy-dom": "^20.11.6", "mini-css-extract-plugin": "^2.10.2", "path-browserify": "^1.0.1", @@ -175,7 +125,6 @@ "acorn": "^8.18.0", "autosize": "^6.0.1", "codemirror": "^6.0.2", - "cordova": "13.0.0", "core-js": "^3.50.0", "dayjs": "^1.11.23", "dompurify": "^3.4.14", @@ -184,7 +133,7 @@ "filesize": "^11.0.22", "html-tag-js": "^2.4.16", "jszip": "^3.10.1", - "katex": "^0.16.47", + "katex": "^0.19.0", "markdown-it": "^14.3.0", "markdown-it-anchor": "^9.2.1", "markdown-it-emoji": "^3.1.0", @@ -197,6 +146,7 @@ "mustache": "^4.2.0", "pele": "^1.10.0", "picomatch": "^4.0.7", + "tough-cookie": "^6.0.2", "url-parse": "^1.5.10", "vanilla-picker": "^2.12.3", "vscode-css-languageservice": "6.3.10", @@ -223,4 +173,4 @@ "core-js@3.49.0": true, "core-js-pure@3.49.0": true } -} +} \ No newline at end of file diff --git a/platforms/android/AGENTS.md b/platforms/android/AGENTS.md new file mode 100644 index 0000000000..37b5d3dd35 --- /dev/null +++ b/platforms/android/AGENTS.md @@ -0,0 +1,4 @@ +- Always use kotlin for writing new code +- Avoid java +- Always add keep rules in proguard file for add @Keep annotation if a file must be preserved +- always write idiomatic android/kotlin code never take shortcuts \ No newline at end of file diff --git a/platforms/android/app/.gitignore b/platforms/android/app/.gitignore new file mode 100644 index 0000000000..42afabfd2a --- /dev/null +++ b/platforms/android/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/platforms/android/app/build.gradle.kts b/platforms/android/app/build.gradle.kts new file mode 100644 index 0000000000..df4b915ffc --- /dev/null +++ b/platforms/android/app/build.gradle.kts @@ -0,0 +1,146 @@ +import groovy.json.JsonSlurper +import java.io.File + +plugins { + alias(libs.plugins.android.application) +} + +val acode = file("../../../package.json").parseJsonObject() +val ads = file("../../../ads.json").parseJsonObject().jsonObject("android")!! +val selectedEdition = mapOf( + "com.foxdebug.acode" to "paid", + "com.foxdebug.acodefree" to "free" +)[acode["androidPackageId"] as String] + ?: throw GradleException("Set package.json androidPackageId to com.foxdebug.acode (paid) or com.foxdebug.acodefree (free).") + +android { + //this is not package name do not change + namespace = "com.foxdebug.acode" + compileSdk = 37 + buildToolsVersion = "36.0.0" + defaultConfig { + minSdk = 26 + targetSdk = 37 + versionCode = (acode["versionCode"] as Number).toInt() + versionName = acode["version"] as String + } + flavorDimensions += listOf("edition", "channel") + productFlavors { + create("paid") { + dimension = "edition" + applicationId = "com.foxdebug.acode" + } + create("free") { + dimension = "edition" + applicationId = "com.foxdebug.acodefree" + } + create("store") { + dimension = "channel" + buildConfigField("boolean", "FDROID", "false") + } + create("fdroid") { + dimension = "channel" + targetSdk = 28 + buildConfigField("boolean", "FDROID", "true") + } + } + buildFeatures { + buildConfig = true + resValues = true + } + signingConfigs { + create("release") + val configFile = file("../../../build.json") + if (configFile.exists()) { + val signingConfigurations = configFile.parseJsonObject().jsonObject("android") + listOf("debug", "release").forEach { type -> + val config = signingConfigurations?.jsonObject(type) ?: return@forEach + val keystore = config["keystore"] as? String ?: return@forEach + getByName(type) { + storeFile = if (File(keystore).isAbsolute) file(keystore) else file("../../../$keystore") + storePassword = config["storePassword"] as? String + keyAlias = config["alias"] as? String + keyPassword = config["password"] as? String + (config["keystoreType"] as? String)?.let { storeType = it } + } + } + } + } + buildTypes { + getByName("debug") { + isDebuggable = true + manifestPlaceholders["admobAppId"] = ads.jsonObject("test")!!["appId"] as String + } + getByName("release") { + manifestPlaceholders["admobAppId"] = ads.jsonObject("production")!!["appId"] as String + isMinifyEnabled = true + isShrinkResources = true + if (signingConfigs.getByName("release").storeFile != null) { + signingConfig = signingConfigs.getByName("release") + } + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 + } + packaging { + jniLibs { + useLegacyPackaging = true + } + resources { + pickFirsts += "META-INF/versions/9/OSGI-INF/MANIFEST.MF" + } + } + testOptions { + unitTests.isIncludeAndroidResources = true + } +} + +configurations.configureEach { + exclude(module = "commons-logging") + exclude(group = "org.bouncycastle", module = "bcprov-jdk15on") + exclude(group = "org.bouncycastle", module = "bcpkix-jdk15on") + exclude(group = "org.bouncycastle", module = "bcpkix-jdk18on") + exclude(group = "org.bouncycastle", module = "bcprov-jdk18on") +} + +dependencies { + implementation(libs.androidx.appcompat) + implementation(libs.androidx.browser) + implementation(libs.androidx.core) + implementation(libs.androidx.core.google.shortcuts) + implementation(libs.androidx.core.splashscreen) + implementation(libs.androidx.documentfile) + implementation(libs.androidx.security.crypto) + implementation(libs.androidx.webkit) + implementation(libs.bouncycastle.bcpkix) + implementation(libs.bouncycastle.bcprov) + implementation(libs.commons.codec) + implementation(libs.commons.io) + implementation(libs.commons.net) + implementation(libs.java.websocket) + implementation(libs.maverick.synergy.client) + implementation(libs.nanohttpd) + implementation(libs.okhttp) + + //check product flavours + "freeImplementation"(libs.play.services.ads) + "freeImplementation"(libs.user.messaging.platform) + "storeImplementation"(libs.billing.client) + testImplementation(libs.junit) + testImplementation(libs.robolectric) +} + +androidComponents { + beforeVariants(selector().all()) { variant -> + variant.enable = variant.productFlavors.first { it.first == "edition" }.second == selectedEdition + } +} + +@Suppress("UNCHECKED_CAST") +fun File.parseJsonObject(): Map<String, Any> = JsonSlurper().parse(this) as Map<String, Any> + +@Suppress("UNCHECKED_CAST") +fun Map<String, Any>.jsonObject(key: String): Map<String, Any>? = this[key] as? Map<String, Any> diff --git a/platforms/android/app/proguard-rules.pro b/platforms/android/app/proguard-rules.pro new file mode 100644 index 0000000000..1f0218b721 --- /dev/null +++ b/platforms/android/app/proguard-rules.pro @@ -0,0 +1,25 @@ +# Keep Acode classes +-keep class com.foxdebug.acode.runtime.** { *; } + +# Services are registered by type in ServiceRegistry, but a few of them dispatch +# actions by method name through reflection (e.g. Ftp.execute() uses +# getClass().getDeclaredMethod(action, JSONArray, Callback)). +# Without keeping the members, R8 strips methods such as connect()/listDirectory() +# and those calls fail at runtime with NoSuchMethodException. +-keep public class * extends com.foxdebug.acode.runtime.Service { *; } + +# WebView JS bridge methods are invoked by name from JavaScript. +-keepclassmembers class * { + @android.webkit.JavascriptInterface <methods>; +} + +# BuildInfo resolves the app BuildConfig and its fields reflectively. +-keep class **.BuildConfig { *; } + +# maverick-synergy (SSH/SFTP) references java.lang.management from +# Utils.generateThreadDump(), which does not exist on Android. That method is +# never reached on Android, so ignore the missing Java SE classes. +-dontwarn java.lang.management.** + +# Keep Javascript Interface attributes +-keepattributes *Annotation*,EnclosingMethod,InnerClasses,Signature diff --git a/platforms/android/app/src/fdroid/java/com/foxdebug/acode/runtime/ChannelServices.kt b/platforms/android/app/src/fdroid/java/com/foxdebug/acode/runtime/ChannelServices.kt new file mode 100644 index 0000000000..4791604e86 --- /dev/null +++ b/platforms/android/app/src/fdroid/java/com/foxdebug/acode/runtime/ChannelServices.kt @@ -0,0 +1,5 @@ +package com.foxdebug.acode.runtime + +internal object ChannelServices : ServiceModule { + override val services: List<ServiceDefinition> = emptyList() +} diff --git a/platforms/android/app/src/free/AndroidManifest.xml b/platforms/android/app/src/free/AndroidManifest.xml new file mode 100644 index 0000000000..166e99a9bb --- /dev/null +++ b/platforms/android/app/src/free/AndroidManifest.xml @@ -0,0 +1,10 @@ +<manifest xmlns:android="http://schemas.android.com/apk/res/android"> + <application> + <activity android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:excludeFromRecents="true" android:name="com.google.android.gms.ads.AdActivity" android:noHistory="true" /> + <meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="${admobAppId}" /> + <meta-data android:name="com.google.android.gms.ads.DELAY_APP_MEASUREMENT_INIT" android:value="true" /> + <meta-data android:name="com.google.android.gms.ads.flag.OPTIMIZE_INITIALIZATION" android:value="true" /> + <meta-data android:name="com.google.android.gms.ads.flag.OPTIMIZE_AD_LOADING" android:value="true" /> + <meta-data android:name="com.google.android.gms.ads.flag.INTEGRATION_MANAGER" android:value="webview" /> + </application> +</manifest> diff --git a/src/plugins/admob/src/android/core/util.kt b/platforms/android/app/src/free/java/admob/plus/core/util.kt similarity index 99% rename from src/plugins/admob/src/android/core/util.kt rename to platforms/android/app/src/free/java/admob/plus/core/util.kt index 6cd03cbf79..a8b525533f 100644 --- a/src/plugins/admob/src/android/core/util.kt +++ b/platforms/android/app/src/free/java/admob/plus/core/util.kt @@ -1,6 +1,6 @@ package admob.plus.core -import admob.plus.cordova.ads.AdSizeType +import app.acode.ads.ads.AdSizeType import android.annotation.SuppressLint import android.app.Activity import android.content.res.Resources diff --git a/src/plugins/admob/src/android/cordova/AdMob.kt b/platforms/android/app/src/free/java/app/acode/ads/AdMob.kt similarity index 80% rename from src/plugins/admob/src/android/cordova/AdMob.kt rename to platforms/android/app/src/free/java/app/acode/ads/AdMob.kt index 45b32656ff..03553e2b02 100644 --- a/src/plugins/admob/src/android/cordova/AdMob.kt +++ b/platforms/android/app/src/free/java/app/acode/ads/AdMob.kt @@ -1,13 +1,13 @@ -package admob.plus.cordova - -import admob.plus.cordova.ads.AppOpen -import admob.plus.cordova.ads.Banner -import admob.plus.cordova.ads.Interstitial -import admob.plus.cordova.ads.Native -import admob.plus.cordova.ads.Rewarded -import admob.plus.cordova.ads.RewardedInterstitial -import admob.plus.cordova.ads.WebViewAd -import admob.plus.cordova.ads.getParentView +package app.acode.ads + +import app.acode.ads.ads.AppOpen +import app.acode.ads.ads.Banner +import app.acode.ads.ads.Interstitial +import app.acode.ads.ads.Native +import app.acode.ads.ads.Rewarded +import app.acode.ads.ads.RewardedInterstitial +import app.acode.ads.ads.WebViewAd +import app.acode.ads.ads.getParentView import admob.plus.core.buildRequestConfiguration import admob.plus.core.configForTestLabIfNeeded import admob.plus.core.isRunningInTestLab @@ -18,9 +18,9 @@ import android.util.Log import android.view.ViewGroup import android.webkit.WebView import com.google.android.gms.ads.MobileAds -import org.apache.cordova.CallbackContext -import org.apache.cordova.CordovaPlugin -import org.apache.cordova.PluginResult +import com.foxdebug.acode.runtime.Callback +import com.foxdebug.acode.runtime.Service +import com.foxdebug.acode.runtime.Payload import org.json.JSONArray import org.json.JSONException import org.json.JSONObject @@ -33,11 +33,11 @@ internal fun shouldDispatchAdShow( canShowWhileLoading: Boolean, ): Boolean = isLoaded || canShowWhileLoading -class AdMob : CordovaPlugin() { - lateinit var context: CallbackContext - private var readyCallbackContext: CallbackContext? = null +class AdMob : Service() { + lateinit var context: Callback + private var readyCallbackContext: Callback? = null private var sdkReady = false - private val eventQueue: ArrayList<PluginResult> = arrayListOf() + private val eventQueue: ArrayList<Payload> = arrayListOf() private val privacy: Privacy by lazy { Privacy(this) } private val actions = mapOf( @@ -49,6 +49,7 @@ class AdMob : CordovaPlugin() { Actions.AD_IS_LOADED to ::executeAdIsLoaded, Actions.AD_LOAD to ::executeAdLoad, Actions.AD_SHOW to ::executeAdShow, + Actions.AD_RECOVER_PRESENTATION to ::executeAdRecoverPresentation, Actions.AD_HIDE to ::executeAdHide, Actions.PRIVACY_GATHER_CONSENT to privacy::gatherConsent, Actions.PRIVACY_GET_STATE to privacy::getState, @@ -57,8 +58,8 @@ class AdMob : CordovaPlugin() { Actions.WEBVIEW_GOTO to ::executeWebviewGoto, ) - override fun pluginInitialize() { - super.pluginInitialize() + override fun serviceInitialize() { + super.serviceInitialize() Log.i(TAG, "Initialize plugin") } @@ -66,7 +67,7 @@ class AdMob : CordovaPlugin() { override fun execute( action: String, data: JSONArray, - callbackContext: CallbackContext + callbackContext: Callback ): Boolean { context = callbackContext val ctx = ExecuteContext(action, data, callbackContext, this) @@ -85,7 +86,7 @@ class AdMob : CordovaPlugin() { readyCallbackContext = ctx.callbackContext emit( Events.READY, - mapOf("isRunningInTestLab" to isRunningInTestLab(cordova.activity)) + mapOf("isRunningInTestLab" to isRunningInTestLab(host!!.activity)) ) return true } @@ -143,14 +144,14 @@ class AdMob : CordovaPlugin() { private fun executeAdDestroy(ctx: ExecuteContext) { val id = ctx.optId() ?: return ctx.reject("id is required") - cordova.activity.runOnUiThread { + host!!.activity.runOnUiThread { ads[id]?.onDestroy() ctx.resolve() } } private fun executeAdIsLoaded(ctx: ExecuteContext) { - cordova.activity.runOnUiThread { + host!!.activity.runOnUiThread { ctx.optAdOrReject()?.let { ad -> ctx.resolve(ad.isLoaded) } @@ -158,7 +159,7 @@ class AdMob : CordovaPlugin() { } private fun executeAdLoad(ctx: ExecuteContext) { - cordova.activity.runOnUiThread { + host!!.activity.runOnUiThread { ctx.optAdOrReject()?.let { ad -> ad.load(ctx) } @@ -166,7 +167,7 @@ class AdMob : CordovaPlugin() { } private fun executeAdShow(ctx: ExecuteContext) { - cordova.activity.runOnUiThread { + host!!.activity.runOnUiThread { ctx.optAdOrReject()?.let { ad -> if (shouldDispatchAdShow(ad.isLoaded, ad.canShowWhileLoading)) { ad.show(ctx) @@ -177,35 +178,40 @@ class AdMob : CordovaPlugin() { } } + private fun executeAdRecoverPresentation(ctx: ExecuteContext) { + val id = ctx.optId() ?: return ctx.reject("id is required") + activity.runOnUiThread { ctx.resolve(recoverAdPresentation(activity, id)) } + } + private fun executeAdHide(ctx: ExecuteContext) { - cordova.activity.runOnUiThread { + host!!.activity.runOnUiThread { ctx.optAdOrReject()?.hide(ctx) } } private fun executeWebviewGoto(ctx: ExecuteContext) { - cordova.activity.runOnUiThread { - val webView = webView.view as WebView + host!!.activity.runOnUiThread { + val webView = webView!!.view as WebView webView.loadUrl(ctx.args.getString(0)) ctx.resolve() } } - val activity: Activity get() = cordova.activity + val activity: Activity get() = host!!.activity val contentView: ViewGroup? get() = activity.findViewById(android.R.id.content) - ?: getParentView(webView.view) + ?: getParentView(webView!!.view) fun emit(eventName: String, data: Map<String, Any?>) { val event = JSONObject(mapOf("type" to eventName, "data" to data)) - val result = PluginResult(PluginResult.Status.OK, event) + val result = Payload(Payload.Status.OK, event) result.keepCallback = true - readyCallbackContext?.sendPluginResult(result) ?: eventQueue.add(result) + readyCallbackContext?.sendPayload(result) ?: eventQueue.add(result) } - override fun onConfigurationChanged(newConfig: Configuration) { + override fun onConfigurationChanged(newConfig: Configuration?) { super.onConfigurationChanged(newConfig) ads.forEach { (_, ad) -> ad.onConfigurationChanged(newConfig) @@ -242,7 +248,7 @@ class AdMob : CordovaPlugin() { val previousAds = synchronized(ads) { ads.values.toList().also { ads.clear() } } - cordova.activity.runOnUiThread { + host!!.activity.runOnUiThread { for (ad in previousAds) { ad.onDestroy() } diff --git a/platforms/android/app/src/free/java/app/acode/ads/AdRecovery.kt b/platforms/android/app/src/free/java/app/acode/ads/AdRecovery.kt new file mode 100644 index 0000000000..16f2d75342 --- /dev/null +++ b/platforms/android/app/src/free/java/app/acode/ads/AdRecovery.kt @@ -0,0 +1,18 @@ +package app.acode.ads + +import android.app.Activity +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import app.acode.ads.ads.Rewarded + +internal fun recoverAdPresentation(activity: Activity, id: String): Boolean { + val lifecycle = (activity as? LifecycleOwner)?.lifecycle ?: return false + if (!lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED) || + !activity.hasWindowFocus() || activity.isFinishing || activity.isDestroyed + ) return false + // AdActivity (or an external ad destination) must no longer own the foreground. + val ad = ads[id] ?: return true + if (ad !is Rewarded) return false + ad.onDestroy() + return true +} diff --git a/platforms/android/app/src/free/java/app/acode/ads/ExecuteContext.kt b/platforms/android/app/src/free/java/app/acode/ads/ExecuteContext.kt new file mode 100644 index 0000000000..6f917834de --- /dev/null +++ b/platforms/android/app/src/free/java/app/acode/ads/ExecuteContext.kt @@ -0,0 +1,68 @@ +package app.acode.ads + +import app.acode.ads.ads.AdBase +import android.app.Activity +import com.foxdebug.acode.runtime.Callback +import com.foxdebug.acode.runtime.Payload +import org.json.JSONArray +import org.json.JSONObject +import java.util.Collections.synchronizedMap + +val ads = synchronizedMap(mutableMapOf<String, AdBase>()) + +data class ExecuteContext( + val action: String, + val args: JSONArray, + val callbackContext: Callback, + val plugin: AdMob, +) { + val opts: JSONObject by lazy { args.optJSONObject(0) } + + val activity: Activity get() = plugin.host!!.activity + + fun optBoolean(name: String): Boolean? { + return if (opts.has(name)) opts.optBoolean(name) else null + } + + fun optString(name: String): String? { + return if (opts.has(name)) opts.optString(name) else null + } + + fun resolve() { + callbackContext.success() + } + + fun resolve(data: Boolean) { + val result = Payload(Payload.Status.OK, data) + sendResult(result) + } + + fun resolve(data: Map<String, Any>) { + callbackContext.success(JSONObject(data)) + } + + fun reject(msg: String?) { + callbackContext.error(msg) + } + + fun sendResult(result: Payload) { + callbackContext.sendPayload(result) + } + + fun optId(): String? { + return optString("id") + } + + private fun optAd(): AdBase? { + return optId()?.let { + ads[it] + } + } + + fun optAdOrReject(): AdBase? { + return optAd() ?: let { + reject("Ad not found") + null + } + } +} diff --git a/src/plugins/admob/src/android/cordova/Generated.kt b/platforms/android/app/src/free/java/app/acode/ads/Generated.kt similarity index 87% rename from src/plugins/admob/src/android/cordova/Generated.kt rename to platforms/android/app/src/free/java/app/acode/ads/Generated.kt index 20db58553e..e8b6143528 100644 --- a/src/plugins/admob/src/android/cordova/Generated.kt +++ b/platforms/android/app/src/free/java/app/acode/ads/Generated.kt @@ -1,5 +1,5 @@ -// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -package admob.plus.cordova +// AdMob Plus protocol constants, maintained locally for Acode bridge extensions. +package app.acode.ads object Actions { const val AD_CREATE = "adCreate" @@ -8,6 +8,7 @@ object Actions { const val AD_IS_LOADED = "adIsLoaded" const val AD_LOAD = "adLoad" const val AD_SHOW = "adShow" + const val AD_RECOVER_PRESENTATION = "adRecoverPresentation" const val BANNER_CONFIG = "bannerConfig" const val CONFIGURE = "configure" const val PRIVACY_GATHER_CONSENT = "privacyGatherConsent" diff --git a/src/plugins/admob/src/android/cordova/Privacy.kt b/platforms/android/app/src/free/java/app/acode/ads/Privacy.kt similarity index 99% rename from src/plugins/admob/src/android/cordova/Privacy.kt rename to platforms/android/app/src/free/java/app/acode/ads/Privacy.kt index b2c2264a53..3103db0c2c 100644 --- a/src/plugins/admob/src/android/cordova/Privacy.kt +++ b/platforms/android/app/src/free/java/app/acode/ads/Privacy.kt @@ -1,4 +1,4 @@ -package admob.plus.cordova +package app.acode.ads import admob.plus.core.jsonArray2stringList import android.content.pm.ApplicationInfo diff --git a/src/plugins/admob/src/android/cordova/ads/AdBase.kt b/platforms/android/app/src/free/java/app/acode/ads/ads/AdBase.kt similarity index 91% rename from src/plugins/admob/src/android/cordova/ads/AdBase.kt rename to platforms/android/app/src/free/java/app/acode/ads/ads/AdBase.kt index 4a9238524f..9692432d2a 100644 --- a/src/plugins/admob/src/android/cordova/ads/AdBase.kt +++ b/platforms/android/app/src/free/java/app/acode/ads/ads/AdBase.kt @@ -1,9 +1,9 @@ -package admob.plus.cordova.ads +package app.acode.ads.ads -import admob.plus.cordova.AdMob -import admob.plus.cordova.Events -import admob.plus.cordova.ExecuteContext -import admob.plus.cordova.ads +import app.acode.ads.AdMob +import app.acode.ads.Events +import app.acode.ads.ExecuteContext +import app.acode.ads.ads import admob.plus.core.buildAdRequest import android.content.res.Configuration import android.view.View @@ -13,7 +13,7 @@ import com.google.android.gms.ads.AdValue import com.google.android.gms.ads.OnPaidEventListener import com.google.android.gms.ads.ResponseInfo import com.google.android.gms.ads.rewarded.RewardItem -import org.apache.cordova.CordovaWebView +import com.foxdebug.acode.runtime.webview.AppWebView import org.json.JSONObject fun getParentView(view: View?): ViewGroup? { @@ -35,8 +35,8 @@ abstract class AdBase(ctx: ExecuteContext) { protected val plugin = ctx.plugin - private val cordovaWebView: CordovaWebView get() = plugin.webView - val webView: View get() = cordovaWebView.view + private val BridgeWebView: AppWebView get() = plugin.webView!! + val webView: View get() = BridgeWebView.view val webViewParent: ViewGroup get() = (webView.parent as? ViewGroup) ?: throw IllegalStateException("webView has no parent") init { @@ -49,7 +49,7 @@ abstract class AdBase(ctx: ExecuteContext) { } } - open fun onConfigurationChanged(newConfig: Configuration) {} + open fun onConfigurationChanged(newConfig: Configuration?) {} open fun onPause(multitasking: Boolean) {} open fun onResume(multitasking: Boolean) {} open fun onDestroy() { diff --git a/src/plugins/admob/src/android/cordova/ads/AppOpen.kt b/platforms/android/app/src/free/java/app/acode/ads/ads/AppOpen.kt similarity index 95% rename from src/plugins/admob/src/android/cordova/ads/AppOpen.kt rename to platforms/android/app/src/free/java/app/acode/ads/ads/AppOpen.kt index 1d875aad57..1d03636b74 100644 --- a/src/plugins/admob/src/android/cordova/ads/AppOpen.kt +++ b/platforms/android/app/src/free/java/app/acode/ads/ads/AppOpen.kt @@ -1,7 +1,7 @@ -package admob.plus.cordova.ads +package app.acode.ads.ads -import admob.plus.cordova.Events -import admob.plus.cordova.ExecuteContext +import app.acode.ads.Events +import app.acode.ads.ExecuteContext import admob.plus.core.buildAdRequest import com.google.android.gms.ads.AdError import com.google.android.gms.ads.AdRequest diff --git a/src/plugins/admob/src/android/cordova/ads/Banner.kt b/platforms/android/app/src/free/java/app/acode/ads/ads/Banner.kt similarity index 99% rename from src/plugins/admob/src/android/cordova/ads/Banner.kt rename to platforms/android/app/src/free/java/app/acode/ads/ads/Banner.kt index 79fde7f593..88469a15e4 100644 --- a/src/plugins/admob/src/android/cordova/ads/Banner.kt +++ b/platforms/android/app/src/free/java/app/acode/ads/ads/Banner.kt @@ -1,7 +1,7 @@ -package admob.plus.cordova.ads +package app.acode.ads.ads -import admob.plus.cordova.Events -import admob.plus.cordova.ExecuteContext +import app.acode.ads.Events +import app.acode.ads.ExecuteContext import admob.plus.core.buildAdSize import admob.plus.core.pxToDp import android.content.res.Configuration @@ -264,7 +264,7 @@ class Banner(ctx: ExecuteContext) : AdBase(ctx) { ctx.resolve() } - override fun onConfigurationChanged(newConfig: Configuration) { + override fun onConfigurationChanged(newConfig: Configuration?) { super.onConfigurationChanged(newConfig) plugin.activity.runOnUiThread { webView.post { diff --git a/src/plugins/admob/src/android/cordova/ads/Interstitial.kt b/platforms/android/app/src/free/java/app/acode/ads/ads/Interstitial.kt similarity index 95% rename from src/plugins/admob/src/android/cordova/ads/Interstitial.kt rename to platforms/android/app/src/free/java/app/acode/ads/ads/Interstitial.kt index c19d9591d3..6ca91341e8 100644 --- a/src/plugins/admob/src/android/cordova/ads/Interstitial.kt +++ b/platforms/android/app/src/free/java/app/acode/ads/ads/Interstitial.kt @@ -1,7 +1,7 @@ -package admob.plus.cordova.ads +package app.acode.ads.ads -import admob.plus.cordova.Events -import admob.plus.cordova.ExecuteContext +import app.acode.ads.Events +import app.acode.ads.ExecuteContext import com.google.android.gms.ads.AdError import com.google.android.gms.ads.LoadAdError import com.google.android.gms.ads.interstitial.InterstitialAd diff --git a/src/plugins/admob/src/android/cordova/ads/Native.kt b/platforms/android/app/src/free/java/app/acode/ads/ads/Native.kt similarity index 97% rename from src/plugins/admob/src/android/cordova/ads/Native.kt rename to platforms/android/app/src/free/java/app/acode/ads/ads/Native.kt index 6b25a5a566..6223d1a7d8 100644 --- a/src/plugins/admob/src/android/cordova/ads/Native.kt +++ b/platforms/android/app/src/free/java/app/acode/ads/ads/Native.kt @@ -1,7 +1,7 @@ -package admob.plus.cordova.ads +package app.acode.ads.ads -import admob.plus.cordova.Events -import admob.plus.cordova.ExecuteContext +import app.acode.ads.Events +import app.acode.ads.ExecuteContext import admob.plus.core.buildAdRequest import admob.plus.core.dpToPx import android.util.Log diff --git a/src/plugins/admob/src/android/cordova/ads/Rewarded.kt b/platforms/android/app/src/free/java/app/acode/ads/ads/Rewarded.kt similarity index 97% rename from src/plugins/admob/src/android/cordova/ads/Rewarded.kt rename to platforms/android/app/src/free/java/app/acode/ads/ads/Rewarded.kt index 545c5240d6..3d019571b4 100644 --- a/src/plugins/admob/src/android/cordova/ads/Rewarded.kt +++ b/platforms/android/app/src/free/java/app/acode/ads/ads/Rewarded.kt @@ -1,7 +1,7 @@ -package admob.plus.cordova.ads +package app.acode.ads.ads -import admob.plus.cordova.Events -import admob.plus.cordova.ExecuteContext +import app.acode.ads.Events +import app.acode.ads.ExecuteContext import com.google.android.gms.ads.AdError import com.google.android.gms.ads.FullScreenContentCallback import com.google.android.gms.ads.LoadAdError diff --git a/src/plugins/admob/src/android/cordova/ads/RewardedInterstitial.kt b/platforms/android/app/src/free/java/app/acode/ads/ads/RewardedInterstitial.kt similarity index 96% rename from src/plugins/admob/src/android/cordova/ads/RewardedInterstitial.kt rename to platforms/android/app/src/free/java/app/acode/ads/ads/RewardedInterstitial.kt index bda6559a64..5d396a0233 100644 --- a/src/plugins/admob/src/android/cordova/ads/RewardedInterstitial.kt +++ b/platforms/android/app/src/free/java/app/acode/ads/ads/RewardedInterstitial.kt @@ -1,7 +1,7 @@ -package admob.plus.cordova.ads +package app.acode.ads.ads -import admob.plus.cordova.Events -import admob.plus.cordova.ExecuteContext +import app.acode.ads.Events +import app.acode.ads.ExecuteContext import com.google.android.gms.ads.AdError import com.google.android.gms.ads.FullScreenContentCallback import com.google.android.gms.ads.LoadAdError diff --git a/src/plugins/admob/src/android/cordova/ads/WebViewAd.kt b/platforms/android/app/src/free/java/app/acode/ads/ads/WebViewAd.kt similarity index 87% rename from src/plugins/admob/src/android/cordova/ads/WebViewAd.kt rename to platforms/android/app/src/free/java/app/acode/ads/ads/WebViewAd.kt index 286c159554..a3ffb24457 100644 --- a/src/plugins/admob/src/android/cordova/ads/WebViewAd.kt +++ b/platforms/android/app/src/free/java/app/acode/ads/ads/WebViewAd.kt @@ -1,7 +1,7 @@ -package admob.plus.cordova.ads +package app.acode.ads.ads import android.util.Log -import admob.plus.cordova.ExecuteContext +import app.acode.ads.ExecuteContext class WebViewAd(ctx: ExecuteContext) : AdBase(ctx) { init { diff --git a/platforms/android/app/src/free/java/com/foxdebug/acode/runtime/EditionServices.kt b/platforms/android/app/src/free/java/com/foxdebug/acode/runtime/EditionServices.kt new file mode 100644 index 0000000000..13762ae85f --- /dev/null +++ b/platforms/android/app/src/free/java/com/foxdebug/acode/runtime/EditionServices.kt @@ -0,0 +1,9 @@ +package com.foxdebug.acode.runtime + +import app.acode.ads.AdMob + +internal object EditionServices : ServiceModule { + override val services: List<ServiceDefinition> = listOf( + ServiceDefinition(ServiceName.AD_MOB) { AdMob() }, + ) +} diff --git a/platforms/android/app/src/free/res/values/ic_launcher_background.xml b/platforms/android/app/src/free/res/values/ic_launcher_background.xml new file mode 100644 index 0000000000..fb2314652d --- /dev/null +++ b/platforms/android/app/src/free/res/values/ic_launcher_background.xml @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <color name="ic_launcher_background">#ffffff</color> + <color name="ic_splash_background">#313131</color> +</resources> diff --git a/platforms/android/app/src/main/AndroidManifest.xml b/platforms/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..97e42e14b3 --- /dev/null +++ b/platforms/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,358 @@ +<manifest xmlns:tools="http://schemas.android.com/tools" + xmlns:android="http://schemas.android.com/apk/res/android"> + + + <uses-permission android:name="android.permission.WAKE_LOCK" /> + <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> + <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" /> + <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> + <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> + <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> + <uses-permission android:name="android.permission.VIBRATE" /> + <uses-permission android:name="android.permission.INTERNET" /> + <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> + + + <queries> + <intent> + <action android:name="android.support.customtabs.action.CustomTabsService" /> + </intent> + </queries> + + + <application + android:name=".Acode" + android:enableOnBackInvokedCallback="false" + android:hardwareAccelerated="true" + android:icon="@mipmap/ic_launcher" + android:label="@string/app_name" + android:largeHeap="true" + android:networkSecurityConfig="@xml/network_security_config" + android:requestLegacyExternalStorage="true" + android:roundIcon="@mipmap/ic_launcher_round" + android:supportsRtl="true" + android:theme="@style/Theme.App.SplashScreen" + android:usesCleartextTraffic="true" + tools:targetApi="33"> + + <activity + android:name=".MainActivity" + android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation" + android:exported="true" + android:launchMode="singleTask" + android:resizeableActivity="true" + android:windowSoftInputMode="adjustResize"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.VIEW" /> + <action android:name="android.intent.action.EDIT" /> + + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.LAUNCHER" /> + + <data + android:mimeType="*/*" + android:scheme="file" /> + <data + android:mimeType="*/*" + android:scheme="content" /> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.SEND" /> + <action android:name="android.intent.action.SEND_MULTIPLE" /> + + <category android:name="android.intent.category.DEFAULT" /> + + <data android:mimeType="application/pdf" /> + <data android:mimeType="application/vnd.openxmlformats-officedocument.wordprocessingml.document" /> + <data android:mimeType="application/vnd.openxmlformats-officedocument.wordprocessingml.template" /> + <data android:mimeType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" /> + <data android:mimeType="application/vnd.ms-excel" /> + <data android:mimeType="application/vnd.oasis.opendocument.spreadsheet" /> + <data android:mimeType="text/csv" /> + <data android:mimeType="text/tab-separated-values" /> + <data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.presentation" /> + <data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.slideshow" /> + <data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.template" /> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.VIEW" /> + + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.BROWSABLE" /> + + <data android:scheme="acode" /> + </intent-filter> + <intent-filter android:autoVerify="true"> + <action android:name="android.intent.action.VIEW" /> + + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.BROWSABLE" /> + + <data android:scheme="http" /> + <data android:scheme="https" /> + <data android:host="acode.app" /> + </intent-filter> + </activity> + <activity + android:name=".browser.BrowserActivity" + android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode" + android:resizeableActivity="true" + android:theme="@style/Theme.App.Activity" + android:windowSoftInputMode="adjustResize" /> + <activity + android:name=".crashhandler.CrashActivity" + android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode" + android:exported="false" + android:launchMode="singleInstance" + android:process=":crash" + android:theme="@style/Theme.AppCompat.DayNight.NoActionBar" /> + + <provider + android:name="androidx.core.content.FileProvider" + android:authorities="${applicationId}.provider" + android:exported="false" + android:grantUriPermissions="true"> + <meta-data + android:name="android.support.FILE_PROVIDER_PATHS" + android:resource="@xml/file_provider" /> + </provider> + <provider + android:name="com.foxdebug.acode.terminal.AlpineDocumentProvider" + android:authorities="${applicationId}.documents" + android:exported="true" + android:grantUriPermissions="true" + android:icon="@mipmap/ic_launcher" + android:permission="android.permission.MANAGE_DOCUMENTS"> + <intent-filter> + <action android:name="android.content.action.DOCUMENTS_PROVIDER" /> + </intent-filter> + </provider> + + <service + android:name="com.foxdebug.acode.terminal.TerminalService" + android:enabled="true" + android:exported="false" + android:foregroundServiceType="specialUse" /> + <activity + android:name=".webview.WebViewActivity" + android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode" + android:resizeableActivity="true" + android:theme="@style/Theme.App.Activity" + android:windowSoftInputMode="adjustResize" /> + + <activity-alias + android:name=".MainActivityIconDefault" + android:enabled="true" + android:exported="true" + android:icon="@mipmap/ic_launcher" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_launcher_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconPro" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_pro" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_pro_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconMidnightCircuit" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_midnight_circuit" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_midnight_circuit_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconAuroraPulse" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_aurora_pulse" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_aurora_pulse_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconTerminalGlow" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_terminal_glow" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_terminal_glow_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconSolarFlare" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_solar_flare" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_solar_flare_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconBlueprint" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_blueprint" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_blueprint_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconPixelParty" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_pixel_party" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_pixel_party_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconPrism" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_prism" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_prism_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconPorcelain" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_porcelain" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_porcelain_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconTangerine" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_tangerine" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_tangerine_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconTidal" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_tidal" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_tidal_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconLilac" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_lilac" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_lilac_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconVolt" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_volt" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_volt_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconCobalt" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_cobalt" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_cobalt_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + <activity-alias + android:name=".MainActivityIconGlacier" + android:enabled="false" + android:exported="true" + android:icon="@mipmap/ic_acode_glacier" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_acode_glacier_round" + android:targetActivity=".MainActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity-alias> + </application> + + + +</manifest> \ No newline at end of file diff --git a/src/plugins/system/res/android/icon.ttf b/platforms/android/app/src/main/assets/font/icon.ttf similarity index 100% rename from src/plugins/system/res/android/icon.ttf rename to platforms/android/app/src/main/assets/font/icon.ttf diff --git a/src/plugins/terminal/scripts/init-alpine.sh b/platforms/android/app/src/main/assets/init-alpine.sh similarity index 76% rename from src/plugins/terminal/scripts/init-alpine.sh rename to platforms/android/app/src/main/assets/init-alpine.sh index 130ae9588c..f370c27ffb 100644 --- a/src/plugins/terminal/scripts/init-alpine.sh +++ b/platforms/android/app/src/main/assets/init-alpine.sh @@ -1,3 +1,4 @@ +ALPINE_ROOT=${ALPINE_ROOT:-$PREFIX/alpine} export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/share/bin:/usr/share/sbin:/usr/local/bin:/usr/local/sbin:/system/bin:/system/xbin:$PREFIX/local/bin export PS1="\[\e[38;5;46m\]\u\[\033[39m\]@localhost \[\033[39m\]\w \[\033[0m\]\\$ " export HOME=/public @@ -5,6 +6,7 @@ export TERM=xterm-256color INSTALLING=false FAILSAFE=false +PREPARE=false # Parse internal flags while [ $# -gt 0 ]; do @@ -17,6 +19,10 @@ while [ $# -gt 0 ]; do FAILSAFE=true shift ;; + --prepare) + PREPARE=true + shift + ;; --) shift break @@ -33,20 +39,30 @@ if [ "$INSTALLING" != true ] && [ $# -gt 0 ] && [ "${1#--}" = "$1" ]; then exec "$@" fi -required_packages="bash command-not-found tzdata wget" +required_packages="bash command-not-found tzdata wget curl libstdc++" +if [ "$ALPINE_ROOT" = "/" ]; then + required_packages="$required_packages procps-ng tar gzip" +fi missing_packages="" +installed_packages=" $(apk info -e $required_packages 2>/dev/null | tr '\n' ' ') " + for pkg in $required_packages; do - if ! apk info -e "$pkg" >/dev/null 2>&1; then - missing_packages="$missing_packages $pkg" - fi + case "$installed_packages" in + *" $pkg "*) ;; + *) missing_packages="$missing_packages $pkg" ;; + esac done if [ -n "$missing_packages" ]; then echo -e "\e[34;1m[*] \e[0mInstalling important packages\e[0m" apk update && apk upgrade - apk add $missing_packages - if [ $? -eq 0 ]; then + if ! apk add $missing_packages || ! apk info -e $required_packages >/dev/null 2>&1; then + echo "Failed to install required Alpine packages." >&2 + if [ "$INSTALLING" = true ] || [ "$PREPARE" = true ]; then + exit 1 + fi + else echo -e "\e[32;1m[+] \e[0mSuccessfully installed\e[0m" fi echo -e "\e[34m[*] \e[0mUse \e[32mapk\e[0m to install new packages\e[0m" @@ -85,8 +101,8 @@ fi echo "$$" > "$PREFIX/pid" chmod +x "$PREFIX/axs" - if [ ! -e "$PREFIX/alpine/etc/acode_motd" ]; then - cat <<EOF > "$PREFIX/alpine/etc/acode_motd" + if [ ! -e "$ALPINE_ROOT/etc/acode_motd" ]; then + cat <<EOF > "$ALPINE_ROOT/etc/acode_motd" Welcome to Alpine Linux in Acode! Working with packages: @@ -100,9 +116,9 @@ EOF fi # Create acode CLI tool - if [ ! -e "$PREFIX/alpine/usr/local/bin/acode" ]; then - mkdir -p "$PREFIX/alpine/usr/local/bin" - cat <<'ACODE_CLI' > "$PREFIX/alpine/usr/local/bin/acode" + if [ ! -e "$ALPINE_ROOT/usr/local/bin/acode" ]; then + mkdir -p "$ALPINE_ROOT/usr/local/bin" + cat <<'ACODE_CLI' > "$ALPINE_ROOT/usr/local/bin/acode" #!/bin/bash # acode - Open files/folders in Acode editor # Uses OSC escape sequences to communicate with the Acode terminal @@ -177,13 +193,13 @@ for arg in "$@"; do esac done ACODE_CLI - chmod +x "$PREFIX/alpine/usr/local/bin/acode" + chmod +x "$ALPINE_ROOT/usr/local/bin/acode" fi # Create initrc if it doesn't exist #initrc runs in bash so we can use bash features -if [ ! -e "$PREFIX/alpine/initrc" ]; then - cat <<'EOF' > "$PREFIX/alpine/initrc" +if [ ! -e "$ALPINE_ROOT/initrc" ]; then + cat <<'EOF' > "$ALPINE_ROOT/initrc" # Source rc files if they exist if [ -f "/etc/profile" ]; then @@ -288,24 +304,27 @@ _acode_preexec() { check_binary_execution "$cmd" } -# Preserve any existing DEBUG trap and append our handler instead of overwriting it. -# This avoids clobbering user-installed preexec hooks (starship, fzf, bash-preexec, etc.). -__acode_existing_debug_trap="$(trap -p DEBUG 2>/dev/null)" -if [[ -n "${__acode_existing_debug_trap}" ]]; then - __acode_existing_cmd="$(printf "%s" "${__acode_existing_debug_trap}" | sed -E "s/.*'((.*)?)'.*/\1/")" -else - __acode_existing_cmd="" -fi - -# Only add our handler if it's not already present -if [[ "${__acode_existing_cmd}" != *"_acode_preexec"* ]]; then - if [[ -n "${__acode_existing_cmd}" ]]; then - trap "${__acode_existing_cmd}; _acode_preexec" DEBUG +# Only Android storage needs the check; it costs two subshells per command. +if [ -d /sdcard ] || [ -d /storage ]; then + # Preserve any existing DEBUG trap and append our handler instead of overwriting it. + # This avoids clobbering user-installed preexec hooks (starship, fzf, bash-preexec, etc.). + __acode_existing_debug_trap="$(trap -p DEBUG 2>/dev/null)" + if [[ -n "${__acode_existing_debug_trap}" ]]; then + __acode_existing_cmd="$(printf "%s" "${__acode_existing_debug_trap}" | sed -E "s/.*'((.*)?)'.*/\1/")" else - trap '_acode_preexec' DEBUG + __acode_existing_cmd="" + fi + + # Only add our handler if it's not already present + if [[ "${__acode_existing_cmd}" != *"_acode_preexec"* ]]; then + if [[ -n "${__acode_existing_cmd}" ]]; then + trap "${__acode_existing_cmd}; _acode_preexec" DEBUG + else + trap '_acode_preexec' DEBUG + fi fi + unset __acode_existing_debug_trap __acode_existing_cmd fi -unset __acode_existing_debug_trap __acode_existing_cmd # Command-not-found handler command_not_found_handle() { @@ -341,17 +360,18 @@ EOF fi # Add PS1 only if not already present -if ! grep -q 'PS1=' "$PREFIX/alpine/initrc"; then +if ! grep -q 'PS1=' "$ALPINE_ROOT/initrc"; then # Smart path shortening (fish-style: ~/p/s/components) - echo 'PS1="\[\033[1;32m\]\u\[\033[0m\]@localhost \[\033[1;34m\]\$_PS1_PATH\[\033[0m\] \[\$([ \$_PS1_EXIT -ne 0 ] && echo \"\033[31m\")\]\$\[\033[0m\] "' >> "$PREFIX/alpine/initrc" + echo 'PS1="\[\033[1;32m\]\u\[\033[0m\]@localhost \[\033[1;34m\]\$_PS1_PATH\[\033[0m\] \[\$([ \$_PS1_EXIT -ne 0 ] && echo \"\033[31m\")\]\$\[\033[0m\] "' >> "$ALPINE_ROOT/initrc" # Simple prompt (uncomment below and comment above if you prefer full paths) - # echo 'PS1="\[\033[1;32m\]\u\[\033[0m\]@localhost \[\033[1;34m\]\w\[\033[0m\] \$ "' >> "$PREFIX/alpine/initrc" + # echo 'PS1="\[\033[1;32m\]\u\[\033[0m\]@localhost \[\033[1;34m\]\w\[\033[0m\] \$ "' >> "$ALPINE_ROOT/initrc" fi -chmod +x "$PREFIX/alpine/initrc" +chmod +x "$ALPINE_ROOT/initrc" -if [ "$FAILSAFE" != true ]; then +# --prepare only sets up the environment; the caller serves the terminals +if [ "$FAILSAFE" != true ] && [ "$PREPARE" != true ]; then #everytime a terminal is started initrc will run "$PREFIX/axs" -c "bash --rcfile /initrc -i" fi diff --git a/src/plugins/terminal/scripts/init-sandbox.sh b/platforms/android/app/src/main/assets/init-sandbox.sh similarity index 100% rename from src/plugins/terminal/scripts/init-sandbox.sh rename to platforms/android/app/src/main/assets/init-sandbox.sh diff --git a/src/plugins/terminal/scripts/rm-wrapper.sh b/platforms/android/app/src/main/assets/rm-wrapper.sh similarity index 100% rename from src/plugins/terminal/scripts/rm-wrapper.sh rename to platforms/android/app/src/main/assets/rm-wrapper.sh diff --git a/platforms/android/app/src/main/ic_launcher-playstore.png b/platforms/android/app/src/main/ic_launcher-playstore.png new file mode 100644 index 0000000000..2717dcbbcf Binary files /dev/null and b/platforms/android/app/src/main/ic_launcher-playstore.png differ diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/Acode.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/Acode.kt new file mode 100644 index 0000000000..26d0eb2c3f --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/Acode.kt @@ -0,0 +1,6 @@ +package com.foxdebug.acode + +import com.foxdebug.acode.runtime.RuntimeBaseApplication + +class Acode : RuntimeBaseApplication() { +} \ No newline at end of file diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/MainActivity.java b/platforms/android/app/src/main/java/com/foxdebug/acode/MainActivity.java new file mode 100644 index 0000000000..8e7db49309 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/MainActivity.java @@ -0,0 +1,5 @@ +package com.foxdebug.acode; + +import com.foxdebug.acode.runtime.BaseWebActivity; + +public final class MainActivity extends BaseWebActivity {} diff --git a/src/plugins/auth/src/android/Authenticator.java b/platforms/android/app/src/main/java/com/foxdebug/acode/auth/Authenticator.java similarity index 86% rename from src/plugins/auth/src/android/Authenticator.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/auth/Authenticator.java index 54f754415f..ba5d00a3e2 100644 --- a/src/plugins/auth/src/android/Authenticator.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/auth/Authenticator.java @@ -1,4 +1,4 @@ -package com.foxdebug.acode.rk.auth; +package com.foxdebug.acode.auth; import android.content.Intent; import android.net.Uri; @@ -6,7 +6,7 @@ import android.webkit.CookieManager; import android.webkit.WebView; import androidx.browser.customtabs.CustomTabsIntent; -import com.foxdebug.acode.rk.auth.EncryptedPreferenceManager; + import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; @@ -16,12 +16,13 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.SecureRandom; -import org.apache.cordova.*; +import com.foxdebug.acode.runtime.*; + import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -public class Authenticator extends CordovaPlugin { +public class Authenticator extends Service { private static final String TAG = "AcodeAuth"; private static final String PREFS_FILENAME = "acode_auth_secure"; private static final String KEY_TOKEN = "auth_token"; @@ -41,12 +42,12 @@ public class Authenticator extends CordovaPlugin { }; private EncryptedPreferenceManager prefManager; private final Object loginCallbackLock = new Object(); - private volatile CallbackContext loginCallback; + private volatile Callback loginCallback; @Override - protected void pluginInitialize() { + public void serviceInitialize() { Log.d(TAG, "Initializing Authenticator Plugin..."); - this.prefManager = new EncryptedPreferenceManager(this.cordova.getContext(), PREFS_FILENAME); + this.prefManager = new EncryptedPreferenceManager(this.host.getContext(), PREFS_FILENAME); WebView androidWebView = (WebView) webView.getView(); CookieManager.getInstance().setAcceptThirdPartyCookies(androidWebView, true); @@ -62,24 +63,24 @@ protected void pluginInitialize() { setTokenCookie(token); } - handleAuthCallback(cordova.getActivity().getIntent()); + handleAuthCallback(host.getActivity().getIntent()); } @Override - public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { + public boolean execute(String action, JSONArray args, Callback callbackContext) throws JSONException { Log.i(TAG, "Native Action Called: " + action); switch (action) { case "logout": prefManager.remove(KEY_TOKEN); - cordova.getActivity().runOnUiThread(() -> clearTokenCookie()); + host.getActivity().runOnUiThread(() -> clearTokenCookie()); if (callbackContext != null) callbackContext.success(); return true; case "saveToken": String token = args.getString(0); Log.d(TAG, "Saving new token..."); prefManager.setString(KEY_TOKEN, token); - cordova.getActivity().runOnUiThread(() -> setTokenCookie(token)); + host.getActivity().runOnUiThread(() -> setTokenCookie(token)); callbackContext.success(); return true; case "login": @@ -99,7 +100,7 @@ public void onNewIntent(Intent intent) { } } - private void startLogin(JSONObject options, CallbackContext callbackContext) { + private void startLogin(JSONObject options, Callback callbackContext) { String baseUrl = options.optString("baseUrl", "https://acode.app"); int appVersionCode = options.optInt("appVersionCode", 0); String state = randomHex(24); @@ -115,28 +116,30 @@ private void startLogin(JSONObject options, CallbackContext callbackContext) { .buildUpon() .appendEncodedPath("login") .appendQueryParameter("redirect", "app") + .appendQueryParameter("src", "android") + .appendQueryParameter("androidPackage", host.getContext().getPackageName()) .appendQueryParameter("authFlow", "app-code") .appendQueryParameter("state", state) .appendQueryParameter("challenge", challenge) .appendQueryParameter("appVersionCode", String.valueOf(appVersionCode)) .build(); - cordova.getActivity().runOnUiThread(() -> { + host.getActivity().runOnUiThread(() -> { try { CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder().build(); customTabsIntent.intent.putExtra(CustomTabsIntent.EXTRA_TITLE_VISIBILITY_STATE, CustomTabsIntent.SHOW_PAGE_TITLE); - customTabsIntent.launchUrl(cordova.getActivity(), loginUri); + customTabsIntent.launchUrl(host.getActivity(), loginUri); - PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); + Payload result = new Payload(Payload.Status.NO_RESULT); result.setKeepCallback(true); - callbackContext.sendPluginResult(result); + callbackContext.sendPayload(result); } catch (Exception error) { Intent fallback = new Intent(Intent.ACTION_VIEW, loginUri); try { - cordova.getActivity().startActivity(fallback); - PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); + host.getActivity().startActivity(fallback); + Payload result = new Payload(Payload.Status.NO_RESULT); result.setKeepCallback(true); - callbackContext.sendPluginResult(result); + callbackContext.sendPayload(result); } catch (Exception fallbackError) { failLogin(fallbackError.getMessage()); } @@ -161,15 +164,15 @@ private boolean handleAuthCallback(Intent intent) { return true; } - cordova.getThreadPool().execute(() -> { + host.getThreadPool().execute(() -> { try { String token = exchangeCode(baseUrl, code, state, verifier); prefManager.setString(KEY_TOKEN, token); prefManager.remove(KEY_PENDING_STATE); prefManager.remove(KEY_PENDING_VERIFIER); prefManager.remove(KEY_PENDING_BASE_URL); - cordova.getActivity().runOnUiThread(() -> setTokenCookie(token)); - CallbackContext callback = takeLoginCallback(); + host.getActivity().runOnUiThread(() -> setTokenCookie(token)); + Callback callback = takeLoginCallback(); if (callback != null) { callback.success(); } @@ -237,14 +240,14 @@ private void failLogin(String message) { prefManager.remove(KEY_PENDING_STATE); prefManager.remove(KEY_PENDING_VERIFIER); prefManager.remove(KEY_PENDING_BASE_URL); - CallbackContext callback = takeLoginCallback(); + Callback callback = takeLoginCallback(); if (callback != null) { callback.error(message); } } - private void setLoginCallback(CallbackContext callbackContext) { - CallbackContext previousCallback = null; + private void setLoginCallback(Callback callbackContext) { + Callback previousCallback = null; synchronized (loginCallbackLock) { previousCallback = loginCallback; loginCallback = callbackContext; @@ -254,9 +257,9 @@ private void setLoginCallback(CallbackContext callbackContext) { } } - private CallbackContext takeLoginCallback() { + private Callback takeLoginCallback() { synchronized (loginCallbackLock) { - CallbackContext callback = loginCallback; + Callback callback = loginCallback; loginCallback = null; return callback; } diff --git a/src/plugins/auth/src/android/EncryptedPreferenceManager.java b/platforms/android/app/src/main/java/com/foxdebug/acode/auth/EncryptedPreferenceManager.java similarity index 98% rename from src/plugins/auth/src/android/EncryptedPreferenceManager.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/auth/EncryptedPreferenceManager.java index 51a32a19ff..6a8ee27a0b 100644 --- a/src/plugins/auth/src/android/EncryptedPreferenceManager.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/auth/EncryptedPreferenceManager.java @@ -1,4 +1,4 @@ -package com.foxdebug.acode.rk.auth; +package com.foxdebug.acode.auth; import android.content.Context; import android.content.SharedPreferences; diff --git a/src/plugins/browser/android/com/foxdebug/browser/Browser.java b/platforms/android/app/src/main/java/com/foxdebug/acode/browser/Browser.java similarity index 98% rename from src/plugins/browser/android/com/foxdebug/browser/Browser.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/browser/Browser.java index bd0d4ab93d..c42ca49702 100644 --- a/src/plugins/browser/android/com/foxdebug/browser/Browser.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/browser/Browser.java @@ -1,16 +1,13 @@ -package com.foxdebug.browser; +package com.foxdebug.acode.browser; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; -import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.net.Uri; -import android.os.Build; import android.text.InputType; import android.text.TextUtils; -import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; @@ -18,7 +15,6 @@ import android.view.ViewTreeObserver; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; -import android.webkit.ConsoleMessage; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebSettings; @@ -31,21 +27,17 @@ import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; -import com.foxdebug.browser.Emulator; -import com.foxdebug.browser.Menu; -import com.foxdebug.system.Ui; + +import com.foxdebug.acode.system.Ui; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import android.app.AlertDialog; import android.app.DownloadManager; -import android.content.Context; -import android.net.Uri; import android.os.Environment; import android.webkit.DownloadListener; import android.webkit.URLUtil; -import android.webkit.WebView; import android.widget.Toast; import android.os.Handler; import android.os.Looper; diff --git a/src/plugins/browser/android/com/foxdebug/browser/BrowserActivity.java b/platforms/android/app/src/main/java/com/foxdebug/acode/browser/BrowserActivity.java similarity index 98% rename from src/plugins/browser/android/com/foxdebug/browser/BrowserActivity.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/browser/BrowserActivity.java index ddca862409..e624f86103 100644 --- a/src/plugins/browser/android/com/foxdebug/browser/BrowserActivity.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/browser/BrowserActivity.java @@ -1,8 +1,7 @@ -package com.foxdebug.browser; +package com.foxdebug.acode.browser; import android.app.Activity; import android.content.Intent; -import android.graphics.Color; import android.graphics.Insets; import android.os.Build; import android.os.Bundle; @@ -13,7 +12,7 @@ import android.view.WindowInsetsController; import android.view.WindowManager; import android.webkit.WebChromeClient; -import com.foxdebug.system.Ui; +import com.foxdebug.acode.system.Ui; import org.json.JSONObject; public class BrowserActivity extends Activity { diff --git a/src/plugins/browser/android/com/foxdebug/browser/Emulator.java b/platforms/android/app/src/main/java/com/foxdebug/acode/browser/Emulator.java similarity index 99% rename from src/plugins/browser/android/com/foxdebug/browser/Emulator.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/browser/Emulator.java index 25f0d70eae..ead772e5fc 100644 --- a/src/plugins/browser/android/com/foxdebug/browser/Emulator.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/browser/Emulator.java @@ -1,4 +1,4 @@ -package com.foxdebug.browser; +package com.foxdebug.acode.browser; import android.content.Context; import android.graphics.Typeface; @@ -10,10 +10,9 @@ import android.widget.ScrollView; import android.widget.SeekBar; import android.widget.TextView; -import com.foxdebug.system.Ui; +import com.foxdebug.acode.system.Ui; + import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; import java.util.HashMap; public class Emulator extends LinearLayout { diff --git a/src/plugins/browser/android/com/foxdebug/browser/Menu.java b/platforms/android/app/src/main/java/com/foxdebug/acode/browser/Menu.java similarity index 98% rename from src/plugins/browser/android/com/foxdebug/browser/Menu.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/browser/Menu.java index 8b5bbb544e..41ea1963d4 100644 --- a/src/plugins/browser/android/com/foxdebug/browser/Menu.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/browser/Menu.java @@ -1,10 +1,9 @@ -package com.foxdebug.browser; +package com.foxdebug.acode.browser; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Bitmap; import android.graphics.drawable.GradientDrawable; -import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; @@ -16,7 +15,7 @@ import android.widget.ScrollView; import android.widget.TextView; import com.foxdebug.acode.R; -import com.foxdebug.system.Ui; +import com.foxdebug.acode.system.Ui; public class Menu extends PopupWindow { diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/browser/Plugin.java b/platforms/android/app/src/main/java/com/foxdebug/acode/browser/Plugin.java new file mode 100644 index 0000000000..7c941490a1 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/browser/Plugin.java @@ -0,0 +1,44 @@ +package com.foxdebug.acode.browser; + +import android.content.Intent; + +import com.foxdebug.acode.runtime.BridgeContext; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Service; + +import org.jetbrains.annotations.NotNull; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class Plugin extends Service { + BridgeContext bridgeContext; + + @Override + public void initialize(@NotNull BridgeContext bridgeContext) { + this.bridgeContext = bridgeContext; + } + + @Override + public boolean execute( + String action, + JSONArray args, + Callback callbackContext + ) throws JSONException { + if (action.equals("open")) { + String url = args.getString(0); + JSONObject theme = args.getJSONObject(1); + boolean onlyConsole = args.optBoolean(2, false); + String themeString = theme.toString(); + Intent intent = new Intent(bridgeContext.getWebActivity(), BrowserActivity.class); + + intent.putExtra("url", url); + intent.putExtra("theme", themeString); + intent.putExtra("onlyConsole", onlyConsole); + bridgeContext.getWebActivity().startActivity(intent); + callbackContext.success("Opened browser"); + return true; + } + return false; + } +} diff --git a/src/plugins/cordova-plugin-buildinfo/src/android/BuildInfo.java b/platforms/android/app/src/main/java/com/foxdebug/acode/buildinfo/BuildInfo.java similarity index 93% rename from src/plugins/cordova-plugin-buildinfo/src/android/BuildInfo.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/buildinfo/BuildInfo.java index 98a1d67844..5dc2ac3409 100644 --- a/src/plugins/cordova-plugin-buildinfo/src/android/BuildInfo.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/buildinfo/BuildInfo.java @@ -22,15 +22,15 @@ of this software and associated documentation files (the "Software"), to deal SOFTWARE. */ -package org.apache.cordova.buildinfo; +package com.foxdebug.acode.buildinfo; import android.app.Activity; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.util.Log; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaPlugin; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Service; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -39,12 +39,12 @@ of this software and associated documentation files (the "Software"), to deal import java.text.SimpleDateFormat; /** - * BuildInfo Cordova Plugin + * BuildInfo Native Plugin * * @author Mikihiro Hayashi * @since 1.0.0 */ -public class BuildInfo extends CordovaPlugin { +public class BuildInfo extends Service { private static final String TAG = "BuildInfo"; /** @@ -66,7 +66,7 @@ public BuildInfo() { * @return * @throws JSONException */ - public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { + public boolean execute(String action, JSONArray args, Callback callbackContext) throws JSONException { if ("init".equals(action)) { String buildConfigClassName = null; @@ -86,7 +86,7 @@ public boolean execute(String action, JSONArray args, CallbackContext callbackCo * @param buildConfigClassName null or specified BuildConfig class name * @param callbackContext */ - private void init(String buildConfigClassName, CallbackContext callbackContext) { + private void init(String buildConfigClassName, Callback callbackContext) { // Cached check if (null != mBuildInfoCache) { callbackContext.success(mBuildInfoCache); @@ -94,7 +94,7 @@ private void init(String buildConfigClassName, CallbackContext callbackContext) } // Load PackageInfo - Activity activity = cordova.getActivity(); + Activity activity = host.getActivity(); String packageName = activity.getPackageName(); String basePackageName = packageName; CharSequence displayName = ""; @@ -117,7 +117,7 @@ private void init(String buildConfigClassName, CallbackContext callbackContext) Class c = null; if (null == buildConfigClassName) { - buildConfigClassName = packageName + ".BuildConfig"; + buildConfigClassName = "com.foxdebug.acode.BuildConfig"; } try { @@ -152,7 +152,7 @@ private void init(String buildConfigClassName, CallbackContext callbackContext) //mBuildInfoCache.put("buildDate" , convertLongToDateTimeString(getClassFieldLong(c, "_BUILDINFO_TIMESTAMP", 0L))); mBuildInfoCache.put("installDate" , convertLongToDateTimeString(firstInstallTime)); mBuildInfoCache.put("buildType" , getClassFieldString(c, "BUILD_TYPE", "")); - mBuildInfoCache.put("flavor" , getClassFieldString(c, "FLAVOR", "")); + mBuildInfoCache.put("flavor" , getClassFieldString(c, "FLAVOR_edition", getClassFieldString(c, "FLAVOR", ""))); if (debug) { Log.d(TAG, "packageName : \"" + mBuildInfoCache.getString("packageName") + "\""); diff --git a/src/plugins/cordova-plugin-crashhandler/src/android/CrashActivity.java b/platforms/android/app/src/main/java/com/foxdebug/acode/crashhandler/CrashActivity.java similarity index 99% rename from src/plugins/cordova-plugin-crashhandler/src/android/CrashActivity.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/crashhandler/CrashActivity.java index e9cd989e92..be00bf904b 100644 --- a/src/plugins/cordova-plugin-crashhandler/src/android/CrashActivity.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/crashhandler/CrashActivity.java @@ -1,4 +1,4 @@ -package com.foxdebug.crashhandler; +package com.foxdebug.acode.crashhandler; import android.app.Activity; import android.content.ClipData; diff --git a/src/plugins/cordova-plugin-crashhandler/src/android/CrashHandler.java b/platforms/android/app/src/main/java/com/foxdebug/acode/crashhandler/CrashHandler.java similarity index 83% rename from src/plugins/cordova-plugin-crashhandler/src/android/CrashHandler.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/crashhandler/CrashHandler.java index cc02d1cc55..8bee6e01a7 100644 --- a/src/plugins/cordova-plugin-crashhandler/src/android/CrashHandler.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/crashhandler/CrashHandler.java @@ -1,21 +1,21 @@ -package com.foxdebug.crashhandler; +package com.foxdebug.acode.crashhandler; import android.content.Context; import android.content.Intent; import android.util.Log; import java.io.PrintWriter; import java.io.StringWriter; -import org.apache.cordova.CordovaInterface; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.CordovaWebView; -public class CrashHandler extends CordovaPlugin { +import com.foxdebug.acode.runtime.BridgeContext; +import com.foxdebug.acode.runtime.Service; + +public class CrashHandler extends Service { private static final String TAG = "CrashHandler"; @Override - public void initialize(CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); + public void initialize(BridgeContext bridgeContext) { + super.initialize(bridgeContext); Log.d(TAG, "Initializing CrashHandler..."); Thread.setDefaultUncaughtExceptionHandler( @@ -30,8 +30,7 @@ public void uncaughtException(Thread thread, Throwable ex) { ex.printStackTrace(pw); String stackTrace = sw.toString(); - Context context = cordova - .getActivity() + Context context = bridgeContext.getWebActivity() .getApplicationContext(); Intent intent = new Intent( context, diff --git a/src/plugins/custom-tabs/src/CustomTabsPlugin.java b/platforms/android/app/src/main/java/com/foxdebug/acode/customtabs/CustomTabsPlugin.java similarity index 84% rename from src/plugins/custom-tabs/src/CustomTabsPlugin.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/customtabs/CustomTabsPlugin.java index a7ee4cc2ac..33d47ad6a3 100644 --- a/src/plugins/custom-tabs/src/CustomTabsPlugin.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/customtabs/CustomTabsPlugin.java @@ -1,4 +1,4 @@ -package com.foxdebug.acode.rk.customtabs; +package com.foxdebug.acode.customtabs; import android.content.ActivityNotFoundException; import android.content.Intent; @@ -7,18 +7,18 @@ import androidx.browser.customtabs.CustomTabsIntent; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaPlugin; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Service; import org.json.JSONArray; import org.json.JSONObject; -public class CustomTabsPlugin extends CordovaPlugin { +public class CustomTabsPlugin extends Service { @Override public boolean execute( String action, JSONArray args, - CallbackContext callbackContext + Callback callbackContext ) { if ("open".equals(action)) { @@ -28,7 +28,7 @@ public boolean execute( ? args.optJSONObject(1) : new JSONObject(); - cordova.getActivity().runOnUiThread(() -> { + host.getActivity().runOnUiThread(() -> { try { openCustomTab(url, options); callbackContext.success(); @@ -64,7 +64,7 @@ private void openCustomTab(String url, JSONObject options) { try { customTabsIntent.launchUrl( - cordova.getActivity(), + host.getActivity(), Uri.parse(url) ); } catch (ActivityNotFoundException e) { @@ -73,7 +73,7 @@ private void openCustomTab(String url, JSONObject options) { Intent.ACTION_VIEW, Uri.parse(url) ); - cordova.getActivity().startActivity(fallback); + host.getActivity().startActivity(fallback); } } } diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/device/Device.java b/platforms/android/app/src/main/java/com/foxdebug/acode/device/Device.java new file mode 100644 index 0000000000..1d08d5a1ae --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/device/Device.java @@ -0,0 +1,172 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package com.foxdebug.acode.device; + +import java.util.TimeZone; + +import com.foxdebug.acode.runtime.BridgeContext; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Service; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import android.provider.Settings; + +public class Device extends Service { + public static final String TAG = "Device"; + + public static String platform; // Device OS + public static String uuid; // Device UUID + + private static final String ANDROID_PLATFORM = "Android"; + private static final String AMAZON_PLATFORM = "amazon-fireos"; + private static final String AMAZON_DEVICE = "Amazon"; + + /** + * Constructor. + */ + public Device() { + } + + /** + * Sets the context of the Command. This can then be used to do things like + * get file paths associated with the Activity. + * + * @param Bridge The context of the main Activity. + * @param webView The AppView Native is running in. + */ + public void initialize(BridgeContext bridgeContext) { + super.initialize(bridgeContext); + Device.uuid = getUuid(); + } + + /** + * Executes the request and returns Payload. + * + * @param action The action to execute. + * @param args JSONArry of arguments for the plugin. + * @param callbackContext The callback id used when calling back into JavaScript. + * @return True if the action was valid, false if not. + */ + public boolean execute(String action, JSONArray args, Callback callbackContext) throws JSONException { + if ("getDeviceInfo".equals(action)) { + JSONObject r = new JSONObject(); + r.put("uuid", Device.uuid); + r.put("version", this.getOSVersion()); + r.put("platform", this.getPlatform()); + r.put("model", this.getModel()); + r.put("manufacturer", this.getManufacturer()); + r.put("isVirtual", this.isVirtual()); + r.put("serial", this.getSerialNumber()); + r.put("sdkVersion", this.getSDKVersion()); + callbackContext.success(r); + } + else { + return false; + } + return true; + } + + //-------------------------------------------------------------------------- + // LOCAL METHODS + //-------------------------------------------------------------------------- + + /** + * Get the OS name. + * + * @return + */ + public String getPlatform() { + String platform; + if (isAmazonDevice()) { + platform = AMAZON_PLATFORM; + } else { + platform = ANDROID_PLATFORM; + } + return platform; + } + + /** + * Get the device's Universally Unique Identifier (UUID). + * + * @return + */ + public String getUuid() { + String uuid = Settings.Secure.getString(this.host.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); + return uuid; + } + + public String getModel() { + String model = android.os.Build.MODEL; + return model; + } + + public String getProductName() { + String productname = android.os.Build.PRODUCT; + return productname; + } + + public String getManufacturer() { + String manufacturer = android.os.Build.MANUFACTURER; + return manufacturer; + } + + public String getSerialNumber() { + String serial = android.os.Build.SERIAL; + return serial; + } + + /** + * Get the OS version. + * + * @return + */ + public String getOSVersion() { + String osversion = android.os.Build.VERSION.RELEASE; + return osversion; + } + + public String getSDKVersion() { + return String.valueOf(android.os.Build.VERSION.SDK_INT); + } + + public String getTimeZoneID() { + TimeZone tz = TimeZone.getDefault(); + return (tz.getID()); + } + + /** + * Function to check if the device is manufactured by Amazon + * + * @return + */ + public boolean isAmazonDevice() { + if (android.os.Build.MANUFACTURER.equals(AMAZON_DEVICE)) { + return true; + } + return false; + } + + public boolean isVirtual() { + return android.os.Build.FINGERPRINT.contains("generic") || + android.os.Build.PRODUCT.contains("sdk"); + } + +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/file/AssetFilesystem.java b/platforms/android/app/src/main/java/com/foxdebug/acode/file/AssetFilesystem.java new file mode 100644 index 0000000000..55f70e7475 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/file/AssetFilesystem.java @@ -0,0 +1,293 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package com.foxdebug.acode.file; + +import android.content.res.AssetManager; +import android.net.Uri; +import android.util.Log; + +import com.foxdebug.acode.runtime.Preferences; +import com.foxdebug.acode.runtime.ResourceApi; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.util.HashMap; +import java.util.Map; + +public class AssetFilesystem extends Filesystem { + + private final AssetManager assetManager; + + // A custom gradle hook creates the cdvasset.manifest file, which speeds up asset listing a tonne. + // See: http://stackoverflow.com/questions/16911558/android-assetmanager-list-incredibly-slow + private static Object listCacheLock = new Object(); + private static boolean listCacheFromFile; + private static Map<String, String[]> listCache; + private static Map<String, Long> lengthCache; + + private static final String LOG_TAG = "AssetFilesystem"; + + private void lazyInitCaches() { + synchronized (listCacheLock) { + if (listCache == null) { + ObjectInputStream ois = null; + try { + ois = new ObjectInputStream(assetManager.open("cdvasset.manifest")); + listCache = (Map<String, String[]>) ois.readObject(); + lengthCache = (Map<String, Long>) ois.readObject(); + listCacheFromFile = true; + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + // Asset manifest won't exist if the gradle hook isn't set up correctly. + } finally { + if (ois != null) { + try { + ois.close(); + } catch (IOException e) { + Log.d(LOG_TAG, e.getLocalizedMessage()); + } + } + } + if (listCache == null) { + Log.w("AssetFilesystem", "Asset manifest not found. Recursive copies and directory listing will be slow."); + listCache = new HashMap<String, String[]>(); + } + } + } + } + + private String[] listAssets(String assetPath) throws IOException { + if (assetPath.startsWith("/")) { + assetPath = assetPath.substring(1); + } + if (assetPath.endsWith("/")) { + assetPath = assetPath.substring(0, assetPath.length() - 1); + } + lazyInitCaches(); + String[] ret = listCache.get(assetPath); + if (ret == null) { + if (listCacheFromFile) { + ret = new String[0]; + } else { + ret = assetManager.list(assetPath); + listCache.put(assetPath, ret); + } + } + return ret; + } + + private long getAssetSize(String assetPath) throws FileNotFoundException { + if (assetPath.startsWith("/")) { + assetPath = assetPath.substring(1); + } + lazyInitCaches(); + if (lengthCache != null) { + Long ret = lengthCache.get(assetPath); + if (ret == null) { + throw new FileNotFoundException("Asset not found: " + assetPath); + } + return ret; + } + ResourceApi.OpenForReadResult offr = null; + try { + offr = resourceApi.openForRead(nativeUriForFullPath(assetPath)); + long length = offr.length; + if (length < 0) { + // available() doesn't always yield the file size, but for assets it does. + length = offr.inputStream.available(); + } + return length; + } catch (IOException e) { + FileNotFoundException fnfe = new FileNotFoundException("File not found: " + assetPath); + fnfe.initCause(e); + throw fnfe; + } finally { + if (offr != null) { + try { + offr.inputStream.close(); + } catch (IOException e) { + Log.d(LOG_TAG, e.getLocalizedMessage()); + } + } + } + } + + public AssetFilesystem(AssetManager assetManager, ResourceApi resourceApi, Preferences preferences) { + super(Uri.parse("file:///android_asset/"), "assets", resourceApi, preferences); + this.assetManager = assetManager; + } + + @Override + public Uri toNativeUri(LocalFilesystemURL inputURL) { + return nativeUriForFullPath(inputURL.path); + } + + @Override + public LocalFilesystemURL toLocalUri(Uri inputURL) { + if (!"file".equals(inputURL.getScheme())) { + return null; + } + File f = new File(inputURL.getPath()); + // Removes and duplicate /s (e.g. file:///a//b/c) + Uri resolvedUri = Uri.fromFile(f); + String rootUriNoTrailingSlash = rootUri.getEncodedPath(); + rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1); + if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) { + return null; + } + String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length()); + // Strip leading slash + if (!subPath.isEmpty()) { + subPath = subPath.substring(1); + } + + Uri.Builder b = createLocalUriBuilder(); + + if (!subPath.isEmpty()) { + b.appendEncodedPath(subPath); + } + if (isDirectory(subPath) || inputURL.getPath().endsWith("/")) { + // Add trailing / for directories. + b.appendEncodedPath(""); + } + return LocalFilesystemURL.parse(b.build()); + } + + private boolean isDirectory(String assetPath) { + try { + return listAssets(assetPath).length != 0; + } catch (IOException e) { + return false; + } + } + + @Override + public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException { + String pathNoSlashes = inputURL.path.substring(1); + if (pathNoSlashes.endsWith("/")) { + pathNoSlashes = pathNoSlashes.substring(0, pathNoSlashes.length() - 1); + } + + String[] files; + try { + files = listAssets(pathNoSlashes); + } catch (IOException e) { + FileNotFoundException fnfe = new FileNotFoundException(); + fnfe.initCause(e); + throw fnfe; + } + + LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length]; + for (int i = 0; i < files.length; ++i) { + entries[i] = localUrlforFullPath(new File(inputURL.path, files[i]).getPath()); + } + return entries; + } + + @Override + public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, + String path, JSONObject options, boolean directory) + throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException { + if (options != null && options.optBoolean("create")) { + throw new UnsupportedOperationException("Assets are read-only"); + } + + // Check whether the supplied path is absolute or relative + if (directory && !path.endsWith("/")) { + path += "/"; + } + + LocalFilesystemURL requestedURL; + if (path.startsWith("/")) { + requestedURL = localUrlforFullPath(normalizePath(path)); + } else { + requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path)); + } + + // Throws a FileNotFoundException if it doesn't exist. + getFileMetadataForLocalURL(requestedURL); + + boolean isDir = isDirectory(requestedURL.path); + if (directory && !isDir) { + throw new TypeMismatchException("path doesn't exist or is file"); + } else if (!directory && isDir) { + throw new TypeMismatchException("path doesn't exist or is directory"); + } + + // Return the directory + return makeEntryForURL(requestedURL); + } + + @Override + public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException { + JSONObject metadata = new JSONObject(); + long size = inputURL.isDirectory ? 0 : getAssetSize(inputURL.path); + try { + metadata.put("size", size); + metadata.put("type", inputURL.isDirectory ? "text/directory" : resourceApi.getMimeType(toNativeUri(inputURL))); + metadata.put("name", new File(inputURL.path).getName()); + metadata.put("fullPath", inputURL.path); + metadata.put("lastModifiedDate", 0); + } catch (JSONException e) { + return null; + } + return metadata; + } + + @Override + public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) { + return false; + } + + @Override + long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset, boolean isBinary) throws NoModificationAllowedException, IOException { + throw new NoModificationAllowedException("Assets are read-only"); + } + + @Override + long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException, NoModificationAllowedException { + throw new NoModificationAllowedException("Assets are read-only"); + } + + @Override + String filesystemPathForURL(LocalFilesystemURL url) { + return new File(rootUri.getPath(), url.path).toString(); + } + + @Override + LocalFilesystemURL URLforFilesystemPath(String path) { + return null; + } + + @Override + boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException { + throw new NoModificationAllowedException("Assets are read-only"); + } + + @Override + boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws NoModificationAllowedException { + throw new NoModificationAllowedException("Assets are read-only"); + } + +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/file/ContentFilesystem.java b/platforms/android/app/src/main/java/com/foxdebug/acode/file/ContentFilesystem.java new file mode 100644 index 0000000000..35d4cd1f83 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/file/ContentFilesystem.java @@ -0,0 +1,224 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package com.foxdebug.acode.file; + +import android.content.ContentResolver; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.provider.DocumentsContract; +import android.provider.MediaStore; +import android.provider.OpenableColumns; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; + +import com.foxdebug.acode.runtime.Preferences; +import com.foxdebug.acode.runtime.ResourceApi; +import org.json.JSONException; +import org.json.JSONObject; + +public class ContentFilesystem extends Filesystem { + + private final Context context; + + public ContentFilesystem(Context context, ResourceApi resourceApi, Preferences preferences) { + super(Uri.parse("content://"), "content", resourceApi, preferences); + this.context = context; + } + + @Override + public Uri toNativeUri(LocalFilesystemURL inputURL) { + String encodedPath = inputURL.uri.getEncodedPath(); + String authorityAndPath = encodedPath.substring(encodedPath.indexOf(this.name) + 1 + this.name.length() + 2); + if (authorityAndPath.length() < 2) { + return null; + } + String ret = "content://" + authorityAndPath; + String query = inputURL.uri.getEncodedQuery(); + if (query != null) { + ret += '?' + query; + } + String frag = inputURL.uri.getEncodedFragment(); + if (frag != null) { + ret += '#' + frag; + } + return Uri.parse(ret); + } + + @Override + public LocalFilesystemURL toLocalUri(Uri inputURL) { + if (!"content".equals(inputURL.getScheme())) { + return null; + } + String subPath = inputURL.getEncodedPath(); + if (subPath.length() > 0) { + subPath = subPath.substring(1); + } + + Uri.Builder b = createLocalUriBuilder().appendPath(inputURL.getAuthority()); + + if (subPath.length() > 0) { + b.appendEncodedPath(subPath); + } + Uri localUri = b.encodedQuery(inputURL.getEncodedQuery()) + .encodedFragment(inputURL.getEncodedFragment()) + .build(); + return LocalFilesystemURL.parse(localUri); + } + + @Override + public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, + String fileName, JSONObject options, boolean directory) throws IOException, TypeMismatchException, JSONException { + throw new UnsupportedOperationException("getFile() not supported for content:. Use resolveLocalFileSystemURL instead."); + } + + @Override + public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) + throws NoModificationAllowedException { + Uri contentUri = toNativeUri(inputURL); + try { + context.getContentResolver().delete(contentUri, null, null); + } catch (UnsupportedOperationException t) { + // Was seeing this on the File mobile-spec tests on 4.0.3 x86 emulator. + // The ContentResolver applies only when the file was registered in the + // first case, which is generally only the case with images. + NoModificationAllowedException nmae = new NoModificationAllowedException("Deleting not supported for content uri: " + contentUri); + nmae.initCause(t); + throw nmae; + } + return true; + } + + @Override + public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) + throws NoModificationAllowedException { + throw new NoModificationAllowedException("Cannot remove content url"); + } + + @Override + public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException { + throw new UnsupportedOperationException("readEntriesAtLocalURL() not supported for content:. Use resolveLocalFileSystemURL instead."); + } + + @Override + public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException { + long size = -1; + long lastModified = 0; + Uri nativeUri = toNativeUri(inputURL); + String mimeType = resourceApi.getMimeType(nativeUri); + Cursor cursor = openCursorForURL(nativeUri); + try { + if (cursor != null && cursor.moveToFirst()) { + Long sizeForCursor = resourceSizeForCursor(cursor); + if (sizeForCursor != null) { + size = sizeForCursor.longValue(); + } + Long modified = lastModifiedDateForCursor(cursor); + if (modified != null) + lastModified = modified.longValue(); + } else { + // Some content providers don't support cursors at all! + ResourceApi.OpenForReadResult offr = resourceApi.openForRead(nativeUri); + size = offr.length; + } + } catch (IOException e) { + FileNotFoundException fnfe = new FileNotFoundException(); + fnfe.initCause(e); + throw fnfe; + } finally { + if (cursor != null) + cursor.close(); + } + + JSONObject metadata = new JSONObject(); + try { + metadata.put("size", size); + metadata.put("type", mimeType); + metadata.put("name", name); + metadata.put("fullPath", inputURL.path); + metadata.put("lastModifiedDate", lastModified); + } catch (JSONException e) { + return null; + } + return metadata; + } + + @Override + public long writeToFileAtURL(LocalFilesystemURL inputURL, String data, + int offset, boolean isBinary) throws NoModificationAllowedException { + throw new NoModificationAllowedException("Couldn't write to file given its content URI"); + } + @Override + public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) + throws NoModificationAllowedException { + throw new NoModificationAllowedException("Couldn't truncate file given its content URI"); + } + + protected Cursor openCursorForURL(Uri nativeUri) { + ContentResolver contentResolver = context.getContentResolver(); + try { + return contentResolver.query(nativeUri, null, null, null, null); + } catch (UnsupportedOperationException e) { + return null; + } + } + + private Long resourceSizeForCursor(Cursor cursor) { + int columnIndex = cursor.getColumnIndex(OpenableColumns.SIZE); + if (columnIndex != -1) { + String sizeStr = cursor.getString(columnIndex); + if (sizeStr != null) { + return Long.parseLong(sizeStr); + } + } + return null; + } + + protected Long lastModifiedDateForCursor(Cursor cursor) { + int columnIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED); + if (columnIndex == -1) { + columnIndex = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_LAST_MODIFIED); + } + if (columnIndex != -1) { + String dateStr = cursor.getString(columnIndex); + if (dateStr != null) { + return Long.parseLong(dateStr); + } + } + return null; + } + + @Override + public String filesystemPathForURL(LocalFilesystemURL url) { + File f = resourceApi.mapUriToFile(toNativeUri(url)); + return f == null ? null : f.getAbsolutePath(); + } + + @Override + public LocalFilesystemURL URLforFilesystemPath(String path) { + // Returns null as we don't support reverse mapping back to content:// URLs + return null; + } + + @Override + public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) { + return true; + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/file/DirectoryManager.java b/platforms/android/app/src/main/java/com/foxdebug/acode/file/DirectoryManager.java new file mode 100644 index 0000000000..fa6c211142 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/file/DirectoryManager.java @@ -0,0 +1,134 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package com.foxdebug.acode.file; + +import android.os.Environment; +import android.os.StatFs; + +import java.io.File; + +/** + * This class provides file directory utilities. + * All file operations are performed on the SD card. + * + * It is used by the FileUtils class. + */ +public class DirectoryManager { + + @SuppressWarnings("unused") + private static final String LOG_TAG = "DirectoryManager"; + + /** + * Determine if a file or directory exists. + * @param name The name of the file to check. + * @return T=exists, F=not found + */ + public static boolean testFileExists(String name) { + boolean status; + + // If SD card exists + if ((testSaveLocationExists()) && (!name.equals(""))) { + File path = Environment.getExternalStorageDirectory(); + File newPath = constructFilePaths(path.toString(), name); + status = newPath.exists(); + } + // If no SD card + else { + status = false; + } + return status; + } + + /** + * Get the free space in external storage + * + * @return Size in KB or -1 if not available + */ + public static long getFreeExternalStorageSpace() { + String status = Environment.getExternalStorageState(); + long freeSpaceInBytes = 0; + + // Check if external storage exists + if (status.equals(Environment.MEDIA_MOUNTED)) { + freeSpaceInBytes = getFreeSpaceInBytes(Environment.getExternalStorageDirectory().getPath()); + } else { + // If no external storage then return -1 + return -1; + } + + return freeSpaceInBytes / 1024; + } + + /** + * Given a path return the number of free bytes in the filesystem containing the path. + * + * @param path to the file system + * @return free space in bytes + */ + public static long getFreeSpaceInBytes(String path) { + try { + StatFs stat = new StatFs(path); + long blockSize = stat.getBlockSize(); + long availableBlocks = stat.getAvailableBlocks(); + return availableBlocks * blockSize; + } catch (IllegalArgumentException e) { + // The path was invalid. Just return 0 free bytes. + return 0; + } + } + + /** + * Determine if SD card exists. + * + * @return T=exists, F=not found + */ + public static boolean testSaveLocationExists() { + String sDCardStatus = Environment.getExternalStorageState(); + boolean status; + + // If SD card is mounted + if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) { + status = true; + } + + // If no SD card + else { + status = false; + } + return status; + } + + /** + * Create a new file object from two file paths. + * + * @param file1 Base file path + * @param file2 Remaining file path + * @return File object + */ + private static File constructFilePaths (String file1, String file2) { + File newPath; + if (file2.startsWith(file1)) { + newPath = new File(file2); + } + else { + newPath = new File(file1 + "/" + file2); + } + return newPath; + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/file/EncodingException.java b/platforms/android/app/src/main/java/com/foxdebug/acode/file/EncodingException.java new file mode 100644 index 0000000000..1e2c20cacd --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/file/EncodingException.java @@ -0,0 +1,29 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ + +package com.foxdebug.acode.file; + +@SuppressWarnings("serial") +public class EncodingException extends Exception { + + public EncodingException(String message) { + super(message); + } + +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/file/FileExistsException.java b/platforms/android/app/src/main/java/com/foxdebug/acode/file/FileExistsException.java new file mode 100644 index 0000000000..20a871119e --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/file/FileExistsException.java @@ -0,0 +1,29 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ + +package com.foxdebug.acode.file; + +@SuppressWarnings("serial") +public class FileExistsException extends Exception { + + public FileExistsException(String msg) { + super(msg); + } + +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/file/FileUtils.java b/platforms/android/app/src/main/java/com/foxdebug/acode/file/FileUtils.java new file mode 100644 index 0000000000..f083c76842 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/file/FileUtils.java @@ -0,0 +1,1344 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package com.foxdebug.acode.file; + +import android.Manifest; +import android.app.Activity; +import android.content.Context; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.os.Build; +import android.os.Environment; +import android.util.Base64; +import android.util.Log; +import android.webkit.MimeTypeMap; +import android.webkit.WebResourceResponse; + +import androidx.webkit.WebViewAssetLoader; + +import com.foxdebug.acode.runtime.BridgeContext; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Service; +import com.foxdebug.acode.runtime.ServicePathHandler; +import com.foxdebug.acode.runtime.ResourceApi; +import com.foxdebug.acode.runtime.Payload; + +import org.jetbrains.annotations.NotNull; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; + +/** + * This class provides file and directory services to JavaScript. + */ +public class FileUtils extends Service { + private static final String LOG_TAG = "FileUtils"; + + public static int NOT_FOUND_ERR = 1; + public static int SECURITY_ERR = 2; + public static int ABORT_ERR = 3; + + public static int NOT_READABLE_ERR = 4; + public static int ENCODING_ERR = 5; + public static int NO_MODIFICATION_ALLOWED_ERR = 6; + public static int INVALID_STATE_ERR = 7; + public static int SYNTAX_ERR = 8; + public static int INVALID_MODIFICATION_ERR = 9; + public static int QUOTA_EXCEEDED_ERR = 10; + public static int TYPE_MISMATCH_ERR = 11; + public static int PATH_EXISTS_ERR = 12; + + /* + * Permission callback codes + */ + + public static final int ACTION_GET_FILE = 0; + public static final int ACTION_WRITE = 1; + public static final int ACTION_GET_DIRECTORY = 2; + public static final int ACTION_READ_ENTRIES = 3; + + public static final int WRITE = 3; + public static final int READ = 4; + + public static int UNKNOWN_ERR = 1000; + + private boolean configured = false; + + private PendingRequests pendingRequests; + + // This field exists only to support getEntry, below, which has been deprecated + private static FileUtils filePlugin; + + private interface FileOp { + void run(JSONArray args) throws Exception; + } + + private ArrayList<Filesystem> filesystems; + + public void registerFilesystem(Filesystem fs) { + if (fs != null && filesystemForName(fs.name) == null) { + this.filesystems.add(fs); + } + } + + private Filesystem filesystemForName(String name) { + for (Filesystem fs : filesystems) { + if (fs != null && fs.name != null && fs.name.equals(name)) { + return fs; + } + } + return null; + } + + protected String[] getExtraFileSystemsPreference(Activity activity) { + String fileSystemsStr = preferences.getString("androidextrafilesystems", "files,files-external,documents,sdcard,cache,cache-external,assets,root"); + return fileSystemsStr.split(","); + } + + protected void registerExtraFileSystems(String[] filesystems, HashMap<String, String> availableFileSystems) { + HashSet<String> installedFileSystems = new HashSet<String>(); + + /* Register filesystems in order */ + for (String fsName : filesystems) { + if (!installedFileSystems.contains(fsName)) { + String fsRoot = availableFileSystems.get(fsName); + if (fsRoot != null) { + File newRoot = new File(fsRoot); + if (newRoot.mkdirs() || newRoot.isDirectory()) { + registerFilesystem(new LocalFilesystem(fsName, webView.getContext(), webView.getResourceApi(), newRoot, preferences)); + installedFileSystems.add(fsName); + } else { + Log.d(LOG_TAG, "Unable to create root dir for filesystem \"" + fsName + "\", skipping"); + } + } else { + Log.d(LOG_TAG, "Unrecognized extra filesystem identifier: " + fsName); + } + } + } + } + + protected HashMap<String, String> getAvailableFileSystems(Activity activity) { + Context context = activity.getApplicationContext(); + HashMap<String, String> availableFileSystems = new HashMap<String, String>(); + + availableFileSystems.put("files", context.getFilesDir().getAbsolutePath()); + availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath()); + availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath()); + availableFileSystems.put("root", "/"); + if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { + try { + availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath()); + availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath()); + availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath()); + } catch (NullPointerException e) { + Log.d(LOG_TAG, "External storage unavailable, check to see if USB Mass Storage Mode is on"); + } + } + + return availableFileSystems; + } + + @Override + public void initialize(BridgeContext bridgeContext) { + super.initialize(bridgeContext); + this.filesystems = new ArrayList<Filesystem>(); + this.pendingRequests = new PendingRequests(); + + String tempRoot = null; + String persistentRoot = null; + + Activity activity = host.getActivity(); + String packageName = activity.getPackageName(); + + String location = preferences.getString("androidpersistentfilelocation", "internal"); + + tempRoot = activity.getCacheDir().getAbsolutePath(); + if ("internal".equalsIgnoreCase(location)) { + persistentRoot = activity.getFilesDir().getAbsolutePath() + "/files/"; + this.configured = true; + } else if ("compatibility".equalsIgnoreCase(location)) { + /* + * Fall-back to compatibility mode -- this is the logic implemented in + * earlier versions of this plugin, and should be maintained here so + * that apps which were originally deployed with older versions of the + * plugin can continue to provide access to files stored under those + * versions. + */ + if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { + persistentRoot = Environment.getExternalStorageDirectory().getAbsolutePath(); + tempRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + + "/Android/data/" + packageName + "/cache/"; + } else { + persistentRoot = "/data/data/" + packageName; + } + this.configured = true; + } + + if (this.configured) { + // Create the directories if they don't exist. + File tmpRootFile = new File(tempRoot); + File persistentRootFile = new File(persistentRoot); + tmpRootFile.mkdirs(); + persistentRootFile.mkdirs(); + + // Register initial filesystems + // Note: The temporary and persistent filesystems need to be the first two + // registered, so that they will match window.TEMPORARY and window.PERSISTENT, + // per spec. + this.registerFilesystem(new LocalFilesystem("temporary", webView.getContext(), webView.getResourceApi(), tmpRootFile, preferences)); + this.registerFilesystem(new LocalFilesystem("persistent", webView.getContext(), webView.getResourceApi(), persistentRootFile, preferences)); + this.registerFilesystem(new ContentFilesystem(webView.getContext(), webView.getResourceApi(), preferences)); + this.registerFilesystem(new AssetFilesystem(webView.getContext().getAssets(), webView.getResourceApi(), preferences)); + + registerExtraFileSystems(getExtraFileSystemsPreference(activity), getAvailableFileSystems(activity)); + + // Initialize static plugin reference for deprecated getEntry method + if (filePlugin == null) { + FileUtils.filePlugin = this; + } + } else { + Log.e(LOG_TAG, "File plugin configuration error: Please set AndroidPersistentFileLocation in config.xml to one of \"internal\" (for new applications) or \"compatibility\" (for compatibility with previous versions)"); + activity.finish(); + } + } + + public static FileUtils getFilePlugin() { + return filePlugin; + } + + private Filesystem filesystemForURL(LocalFilesystemURL localURL) { + if (localURL == null) return null; + return filesystemForName(localURL.fsName); + } + + @Override + public Uri remapUri(Uri uri) { + // Remap only cdvfile: URLs (not content:). + if (!LocalFilesystemURL.FILESYSTEM_PROTOCOL.equals(uri.getScheme())) { + return null; + } + + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(uri); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + return null; + } + String path = fs.filesystemPathForURL(inputURL); + + if (path != null) { + return Uri.parse("file://" + fs.filesystemPathForURL(inputURL)); + } + return null; + } catch (IllegalArgumentException e) { + return null; + } + } + + public boolean execute(String action, final String rawArgs, final Callback callbackContext) { + if (!configured) { + callbackContext.sendPayload(new Payload(Payload.Status.ERROR, "File plugin is not configured. Please see the README.md file for details on how to update config.xml")); + return true; + } + + if (action.equals("testSaveLocationExists")) { + threadhelper(new FileOp() { + public void run(JSONArray args) { + + boolean b = DirectoryManager.testSaveLocationExists(); + callbackContext.sendPayload(new Payload(Payload.Status.OK, b)); + } + }, rawArgs, callbackContext); + } else if (action.equals("getFreeDiskSpace")) { + threadhelper(new FileOp() { + public void run(JSONArray args) { + // The getFreeDiskSpace plugin API is not documented, but some apps call it anyway via exec(). + // For compatibility it always returns free space in the primary external storage, and + // does NOT fallback to internal store if external storage is unavailable. + long l = DirectoryManager.getFreeExternalStorageSpace(); + callbackContext.sendPayload(new Payload(Payload.Status.OK, l)); + } + }, rawArgs, callbackContext); + } else if (action.equals("testFileExists")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException { + String fname = args.getString(0); + boolean b = DirectoryManager.testFileExists(fname); + callbackContext.sendPayload(new Payload(Payload.Status.OK, b)); + } + }, rawArgs, callbackContext); + } else if (action.equals("testDirectoryExists")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException { + String fname = args.getString(0); + boolean b = DirectoryManager.testFileExists(fname); + callbackContext.sendPayload(new Payload(Payload.Status.OK, b)); + } + }, rawArgs, callbackContext); + } else if (action.equals("readAsText")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException, MalformedURLException { + String encoding = args.getString(1); + int start = args.getInt(2); + int end = args.getInt(3); + String fname = args.getString(0); + readFileAs(fname, start, end, callbackContext, encoding, Payload.MESSAGE_TYPE_STRING); + } + }, rawArgs, callbackContext); + } else if (action.equals("readAsDataURL")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException, MalformedURLException { + int start = args.getInt(1); + int end = args.getInt(2); + String fname = args.getString(0); + readFileAs(fname, start, end, callbackContext, null, -1); + } + }, rawArgs, callbackContext); + } else if (action.equals("readAsArrayBuffer")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException, MalformedURLException { + int start = args.getInt(1); + int end = args.getInt(2); + String fname = args.getString(0); + readFileAs(fname, start, end, callbackContext, null, Payload.MESSAGE_TYPE_ARRAYBUFFER); + } + }, rawArgs, callbackContext); + } else if (action.equals("readAsBinaryString")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException, MalformedURLException { + int start = args.getInt(1); + int end = args.getInt(2); + String fname = args.getString(0); + readFileAs(fname, start, end, callbackContext, null, Payload.MESSAGE_TYPE_BINARYSTRING); + } + }, rawArgs, callbackContext); + } else if (action.equals("write")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException { + String fname = args.getString(0); + String nativeURL = resolveLocalFileSystemURI(fname).getString("nativeURL"); + String data = args.getString(1); + int offset = args.getInt(2); + Boolean isBinary = args.getBoolean(3); + + if (needPermission(nativeURL, WRITE)) { + getWritePermission(rawArgs, ACTION_WRITE, callbackContext); + } else { + long fileSize = write(fname, data, offset, isBinary); + callbackContext.sendPayload(new Payload(Payload.Status.OK, fileSize)); + } + + } + }, rawArgs, callbackContext); + } else if (action.equals("truncate")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException { + String fname = args.getString(0); + int offset = args.getInt(1); + long fileSize = truncateFile(fname, offset); + callbackContext.sendPayload(new Payload(Payload.Status.OK, fileSize)); + } + }, rawArgs, callbackContext); + } else if (action.equals("requestAllFileSystems")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws IOException, JSONException { + callbackContext.success(requestAllFileSystems()); + } + }, rawArgs, callbackContext); + } else if (action.equals("requestAllPaths")) { + host.getThreadPool().execute( + new Runnable() { + public void run() { + try { + callbackContext.success(requestAllPaths()); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + ); + } else if (action.equals("requestFileSystem")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException { + int fstype = args.getInt(0); + long requiredSize = args.optLong(1); + requestFileSystem(fstype, requiredSize, callbackContext); + } + }, rawArgs, callbackContext); + } else if (action.equals("resolveLocalFileSystemURI")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws IOException, JSONException { + String fname = args.getString(0); + JSONObject obj = resolveLocalFileSystemURI(fname); + callbackContext.success(obj); + } + }, rawArgs, callbackContext); + } else if (action.equals("getFileMetadata")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException { + String fname = args.getString(0); + JSONObject obj = getFileMetadata(fname); + callbackContext.success(obj); + } + }, rawArgs, callbackContext); + } else if (action.equals("getParent")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException, IOException { + String fname = args.getString(0); + JSONObject obj = getParent(fname); + callbackContext.success(obj); + } + }, rawArgs, callbackContext); + } else if (action.equals("getDirectory")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException { + String dirname = args.getString(0); + String path = args.getString(1); + String nativeURL = resolveLocalFileSystemURI(dirname).getString("nativeURL"); + boolean containsCreate = (args.isNull(2)) ? false : args.getJSONObject(2).optBoolean("create", false); + + if (containsCreate && needPermission(nativeURL, WRITE)) { + getWritePermission(rawArgs, ACTION_GET_DIRECTORY, callbackContext); + } else if (!containsCreate && needPermission(nativeURL, READ)) { + getReadPermission(rawArgs, ACTION_GET_DIRECTORY, callbackContext); + } else { + JSONObject obj = getFile(dirname, path, args.optJSONObject(2), true); + callbackContext.success(obj); + } + } + }, rawArgs, callbackContext); + } else if (action.equals("getFile")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException { + String dirname = args.getString(0); + String path = args.getString(1); + + if (dirname.contains(LocalFilesystemURL.CDVFILE_KEYWORD) == true) { + JSONObject obj = getFile(dirname, path, args.optJSONObject(2), false); + callbackContext.success(obj); + } else { + String nativeURL = resolveLocalFileSystemURI(dirname).getString("nativeURL"); + boolean containsCreate = (args.isNull(2)) ? false : args.getJSONObject(2).optBoolean("create", false); + + if (containsCreate && needPermission(nativeURL, WRITE)) { + getWritePermission(rawArgs, ACTION_GET_FILE, callbackContext); + } else if (!containsCreate && needPermission(nativeURL, READ)) { + getReadPermission(rawArgs, ACTION_GET_FILE, callbackContext); + } else { + JSONObject obj = getFile(dirname, path, args.optJSONObject(2), false); + callbackContext.success(obj); + } + } + } + }, rawArgs, callbackContext); + } else if (action.equals("remove")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException, NoModificationAllowedException, InvalidModificationException, MalformedURLException { + String fname = args.getString(0); + boolean success = remove(fname); + if (success) { + callbackContext.success(); + } else { + callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR); + } + } + }, rawArgs, callbackContext); + } else if (action.equals("removeRecursively")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException, FileExistsException, MalformedURLException, NoModificationAllowedException { + String fname = args.getString(0); + boolean success = removeRecursively(fname); + if (success) { + callbackContext.success(); + } else { + callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR); + } + } + }, rawArgs, callbackContext); + } else if (action.equals("moveTo")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException { + String fname = args.getString(0); + String newParent = args.getString(1); + String newName = args.getString(2); + JSONObject entry = transferTo(fname, newParent, newName, true); + callbackContext.success(entry); + } + }, rawArgs, callbackContext); + } else if (action.equals("copyTo")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException { + String fname = args.getString(0); + String newParent = args.getString(1); + String newName = args.getString(2); + JSONObject entry = transferTo(fname, newParent, newName, false); + callbackContext.success(entry); + } + }, rawArgs, callbackContext); + } else if (action.equals("readEntries")) { + threadhelper(new FileOp() { + public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException, IOException { + String directory = args.getString(0); + String nativeURL = resolveLocalFileSystemURI(directory).getString("nativeURL"); + if (needPermission(nativeURL, READ)) { + getReadPermission(rawArgs, ACTION_READ_ENTRIES, callbackContext); + } else { + JSONArray entries = readEntries(directory); + callbackContext.success(entries); + } + } + }, rawArgs, callbackContext); + } else if (action.equals("_getLocalFilesystemPath")) { + // Internal method for testing: Get the on-disk location of a local filesystem url. + // [Currently used for testing file-transfer] + threadhelper(new FileOp() { + public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException { + String localURLstr = args.getString(0); + String fname = filesystemPathForURL(localURLstr); + callbackContext.success(fname); + } + }, rawArgs, callbackContext); + } else { + return false; + } + return true; + } + + private void getReadPermission(String rawArgs, int action, Callback callbackContext) { + int requestCode = pendingRequests.createRequest(rawArgs, action, callbackContext); + if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + host.requestPermissions(this, requestCode, + new String[]{Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO, Manifest.permission.READ_MEDIA_AUDIO}); + } else { + host.requestPermission(this, requestCode, Manifest.permission.READ_EXTERNAL_STORAGE); + } + } + + private void getWritePermission(String rawArgs, int action, Callback callbackContext) { + if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + int requestCode = pendingRequests.createRequest(rawArgs, action, callbackContext); + host.requestPermission(this, requestCode, Manifest.permission.WRITE_EXTERNAL_STORAGE); + } + } + + /** + * If your app targets Android 13 (SDK 33) or higher and needs to access media files that other apps have created, + * you must request one or more of the following granular media permissions READ_MEDIA_* + * instead of the READ_EXTERNAL_STORAGE permission: + * + * Refer to: https://developer.android.com/about/versions/13/behavior-changes-13 + * + * @return + */ + private boolean hasReadPermission() { + if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + return host.hasPermission(Manifest.permission.READ_MEDIA_IMAGES) + && host.hasPermission(Manifest.permission.READ_MEDIA_VIDEO) + && host.hasPermission(Manifest.permission.READ_MEDIA_AUDIO); + } else { + return host.hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE); + } + } + + private boolean hasWritePermission() { + // Starting with API 33, requesting WRITE_EXTERNAL_STORAGE is an auto permission rejection + return android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU + ? true + : host.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE); + } + + private boolean needPermission(String nativeURL, int permissionType) throws JSONException { + JSONObject j = requestAllPaths(); + ArrayList<String> allowedStorageDirectories = new ArrayList<String>(); + allowedStorageDirectories.add(j.getString("applicationDirectory")); + allowedStorageDirectories.add(j.getString("applicationStorageDirectory")); + if (j.has("externalApplicationStorageDirectory")) { + allowedStorageDirectories.add(j.getString("externalApplicationStorageDirectory")); + } + + if (permissionType == READ && hasReadPermission()) { + return false; + } else if (permissionType == WRITE && hasWritePermission()) { + return false; + } + + // Permission required if the native url lies outside the allowed storage directories + for (String directory : allowedStorageDirectories) { + if (nativeURL.startsWith(directory)) { + return false; + } + } + return true; + } + + + public LocalFilesystemURL resolveNativeUri(Uri nativeUri) { + LocalFilesystemURL localURL = null; + + // Try all installed filesystems. Return the best matching URL + // (determined by the shortest resulting URL) + for (Filesystem fs : filesystems) { + LocalFilesystemURL url = fs.toLocalUri(nativeUri); + if (url != null) { + // A shorter fullPath implies that the filesystem is a better + // match for the local path than the previous best. + if (localURL == null || (url.uri.toString().length() < localURL.toString().length())) { + localURL = url; + } + } + } + return localURL; + } + + /* + * These two native-only methods can be used by other plugins to translate between + * device file system paths and URLs. By design, there is no direct JavaScript + * interface to these methods. + */ + + public String filesystemPathForURL(String localURLstr) throws MalformedURLException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(localURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + return fs.filesystemPathForURL(inputURL); + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + } + + public LocalFilesystemURL filesystemURLforLocalPath(String localPath) { + LocalFilesystemURL localURL = null; + int shortestFullPath = 0; + + // Try all installed filesystems. Return the best matching URL + // (determined by the shortest resulting URL) + for (Filesystem fs : filesystems) { + LocalFilesystemURL url = fs.URLforFilesystemPath(localPath); + if (url != null) { + // A shorter fullPath implies that the filesystem is a better + // match for the local path than the previous best. + if (localURL == null || (url.path.length() < shortestFullPath)) { + localURL = url; + shortestFullPath = url.path.length(); + } + } + } + return localURL; + } + + + /* helper to execute functions async and handle the result codes + * + */ + private void threadhelper(final FileOp f, final String rawArgs, final Callback callbackContext) { + host.getThreadPool().execute(new Runnable() { + public void run() { + try { + JSONArray args = new JSONArray(rawArgs); + f.run(args); + } catch (Exception e) { + if (e instanceof EncodingException) { + callbackContext.error(FileUtils.ENCODING_ERR); + } else if (e instanceof FileNotFoundException) { + callbackContext.error(FileUtils.NOT_FOUND_ERR); + } else if (e instanceof FileExistsException) { + callbackContext.error(FileUtils.PATH_EXISTS_ERR); + } else if (e instanceof NoModificationAllowedException) { + callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR); + } else if (e instanceof InvalidModificationException) { + callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR); + } else if (e instanceof MalformedURLException) { + callbackContext.error(FileUtils.ENCODING_ERR); + } else if (e instanceof IOException) { + callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR); + } else if (e instanceof TypeMismatchException) { + callbackContext.error(FileUtils.TYPE_MISMATCH_ERR); + } else if (e instanceof JSONException) { + callbackContext.sendPayload(new Payload(Payload.Status.JSON_EXCEPTION)); + } else if (e instanceof SecurityException) { + callbackContext.error(FileUtils.SECURITY_ERR); + } else { + e.printStackTrace(); + callbackContext.error(FileUtils.UNKNOWN_ERR); + } + } + } + }); + } + + /** + * Allows the user to look up the Entry for a file or directory referred to by a local URI. + * + * @param uriString of the file/directory to look up + * @return a JSONObject representing a Entry from the filesystem + * @throws MalformedURLException if the url is not valid + * @throws FileNotFoundException if the file does not exist + * @throws IOException if the user can't read the file + * @throws JSONException + */ + private JSONObject resolveLocalFileSystemURI(String uriString) throws IOException, JSONException { + if (uriString == null) { + throw new MalformedURLException("Unrecognized filesystem URL"); + } + Uri uri = Uri.parse(uriString); + boolean isNativeUri = false; + + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(uri); + if (inputURL == null) { + /* Check for file://, content:// urls */ + inputURL = resolveNativeUri(uri); + isNativeUri = true; + } + + try { + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + if (fs.exists(inputURL)) { + if (!isNativeUri) { + // If not already resolved as native URI, resolve to a native URI and back to + // fix the terminating slash based on whether the entry is a directory or file. + inputURL = fs.toLocalUri(fs.toNativeUri(inputURL)); + } + + return fs.getEntryForLocalURL(inputURL); + } + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + throw new FileNotFoundException(); + } + + /** + * Read the list of files from this directory. + * + * @return a JSONArray containing JSONObjects that represent Entry objects. + * @throws FileNotFoundException if the directory is not found. + * @throws JSONException + * @throws MalformedURLException + */ + private JSONArray readEntries(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + return fs.readEntriesAtLocalURL(inputURL); + + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + } + + /** + * A setup method that handles the move/copy of files/directories + * + * @param newName for the file directory to be called, if null use existing file name + * @param move if false do a copy, if true do a move + * @return a Entry object + * @throws NoModificationAllowedException + * @throws IOException + * @throws InvalidModificationException + * @throws EncodingException + * @throws JSONException + * @throws FileExistsException + */ + private JSONObject transferTo(String srcURLstr, String destURLstr, String newName, boolean move) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException { + if (srcURLstr == null || destURLstr == null) { + // either no source or no destination provided + throw new FileNotFoundException(); + } + + LocalFilesystemURL srcURL = LocalFilesystemURL.parse(srcURLstr); + LocalFilesystemURL destURL = LocalFilesystemURL.parse(destURLstr); + + Filesystem srcFs = this.filesystemForURL(srcURL); + Filesystem destFs = this.filesystemForURL(destURL); + + // Check for invalid file name + if (newName != null && newName.contains(":")) { + throw new EncodingException("Bad file name"); + } + + return destFs.copyFileToURL(destURL, newName, srcFs, srcURL, move); + } + + /** + * Deletes a directory and all of its contents, if any. In the event of an error + * [e.g. trying to delete a directory that contains a file that cannot be removed], + * some of the contents of the directory may be deleted. + * It is an error to attempt to delete the root directory of a filesystem. + * + * @return a boolean representing success of failure + * @throws FileExistsException + * @throws NoModificationAllowedException + * @throws MalformedURLException + */ + private boolean removeRecursively(String baseURLstr) throws FileExistsException, NoModificationAllowedException, MalformedURLException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr); + // You can't delete the root directory. + if ("".equals(inputURL.path) || "/".equals(inputURL.path)) { + throw new NoModificationAllowedException("You can't delete the root directory"); + } + + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + return fs.recursiveRemoveFileAtLocalURL(inputURL); + + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + } + + + /** + * Deletes a file or directory. It is an error to attempt to delete a directory that is not empty. + * It is an error to attempt to delete the root directory of a filesystem. + * + * @return a boolean representing success of failure + * @throws NoModificationAllowedException + * @throws InvalidModificationException + * @throws MalformedURLException + */ + private boolean remove(String baseURLstr) throws NoModificationAllowedException, InvalidModificationException, MalformedURLException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr); + // You can't delete the root directory. + if ("".equals(inputURL.path) || "/".equals(inputURL.path)) { + + throw new NoModificationAllowedException("You can't delete the root directory"); + } + + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + return fs.removeFileAtLocalURL(inputURL); + + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + } + + /** + * Creates or looks up a file. + * + * @param baseURLstr base directory + * @param path file/directory to lookup or create + * @param options specify whether to create or not + * @param directory if true look up directory, if false look up file + * @return a Entry object + * @throws FileExistsException + * @throws IOException + * @throws TypeMismatchException + * @throws EncodingException + * @throws JSONException + */ + private JSONObject getFile(String baseURLstr, String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr); + + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + return fs.getFileForLocalURL(inputURL, path, options, directory); + + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + + } + + /** + * Look up the parent DirectoryEntry containing this Entry. + * If this Entry is the root of its filesystem, its parent is itself. + */ + private JSONObject getParent(String baseURLstr) throws JSONException, IOException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + return fs.getParentForLocalURL(inputURL); + + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + } + + /** + * Returns a File that represents the current state of the file that this FileEntry represents. + * + * @return returns a JSONObject represent a W3C File object + */ + private JSONObject getFileMetadata(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + return fs.getFileMetadataForLocalURL(inputURL); + + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + } + + /** + * Requests a filesystem in which to store application data. + * + * @param type of file system requested + * @param requiredSize required free space in the file system in bytes + * @param callbackContext context for returning the result or error + * @throws JSONException + */ + private void requestFileSystem(int type, long requiredSize, final Callback callbackContext) throws JSONException { + Filesystem rootFs = null; + try { + rootFs = this.filesystems.get(type); + } catch (ArrayIndexOutOfBoundsException e) { + // Pass null through + } + if (rootFs == null) { + callbackContext.sendPayload(new Payload(Payload.Status.ERROR, FileUtils.NOT_FOUND_ERR)); + } else { + // If a nonzero required size was specified, check that the retrieved filesystem has enough free space. + long availableSize = 0; + if (requiredSize > 0) { + availableSize = rootFs.getFreeSpaceInBytes(); + } + + if (availableSize < requiredSize) { + callbackContext.sendPayload(new Payload(Payload.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR)); + } else { + JSONObject fs = new JSONObject(); + fs.put("name", rootFs.name); + fs.put("root", rootFs.getRootEntry()); + callbackContext.success(fs); + } + } + } + + /** + * Requests a filesystem in which to store application data. + * + * @return a JSONObject representing the file system + */ + private JSONArray requestAllFileSystems() throws IOException, JSONException { + JSONArray ret = new JSONArray(); + for (Filesystem fs : filesystems) { + ret.put(fs.getRootEntry()); + } + return ret; + } + + private static String toDirUrl(File f) { + return Uri.fromFile(f).toString() + '/'; + } + + private JSONObject requestAllPaths() throws JSONException { + Context context = host.getActivity(); + JSONObject ret = new JSONObject(); + ret.put("applicationDirectory", "file:///android_asset/"); + ret.put("applicationStorageDirectory", toDirUrl(context.getFilesDir().getParentFile())); + ret.put("dataDirectory", toDirUrl(context.getFilesDir())); + ret.put("cacheDirectory", toDirUrl(context.getCacheDir())); + if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { + try { + ret.put("externalApplicationStorageDirectory", toDirUrl(context.getExternalFilesDir(null).getParentFile())); + ret.put("externalDataDirectory", toDirUrl(context.getExternalFilesDir(null))); + ret.put("externalCacheDirectory", toDirUrl(context.getExternalCacheDir())); + ret.put("externalRootDirectory", toDirUrl(Environment.getExternalStorageDirectory())); + } catch (NullPointerException e) { + /* If external storage is unavailable, context.getExternal* returns null */ + Log.d(LOG_TAG, "Unable to access these paths, most liklely due to USB storage"); + } + } + return ret; + } + + /** + * Returns a JSON object representing the given File. Internal APIs should be modified + * to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin. + * + * @param file the File to convert + * @return a JSON representation of the given File + * @throws JSONException + */ + public JSONObject getEntryForFile(File file) throws JSONException { + JSONObject entry; + + for (Filesystem fs : filesystems) { + entry = fs.makeEntryForFile(file); + if (entry != null) { + return entry; + } + } + return null; + } + + /** + * Returns a JSON object representing the given File. Deprecated, as this is only used by + * FileTransfer, and because it is a static method that should really be an instance method, + * since it depends on the actual filesystem roots in use. Internal APIs should be modified + * to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin. + * + * @param file the File to convert + * @return a JSON representation of the given File + * @throws JSONException + */ + @Deprecated + public static JSONObject getEntry(File file) throws JSONException { + if (getFilePlugin() != null) { + return getFilePlugin().getEntryForFile(file); + } + return null; + } + + /** + * Read the contents of a file. + * This is done in a background thread; the result is sent to the callback. + * + * @param start Start position in the file. + * @param end End position to stop at (exclusive). + * @param callbackContext The context through which to send the result. + * @param encoding The encoding to return contents as. Typical value is UTF-8. (see http://www.iana.org/assignments/character-sets) + * @param resultType The desired type of data to send to the callback. + * @return Contents of file. + */ + public void readFileAs(final String srcURLstr, final int start, final int end, final Callback callbackContext, final String encoding, final int resultType) throws MalformedURLException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + + fs.readFileAtURL(inputURL, start, end, new Filesystem.ReadFileCallback() { + public void handleData(InputStream inputStream, String contentType) { + try { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final int BUFFER_SIZE = 8192; + byte[] buffer = new byte[BUFFER_SIZE]; + + for (; ; ) { + int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE); + + if (bytesRead <= 0) { + break; + } + os.write(buffer, 0, bytesRead); + } + + Payload result; + switch (resultType) { + case Payload.MESSAGE_TYPE_STRING: + result = new Payload(Payload.Status.OK, os.toString(encoding)); + break; + case Payload.MESSAGE_TYPE_ARRAYBUFFER: + result = new Payload(Payload.Status.OK, os.toByteArray()); + break; + case Payload.MESSAGE_TYPE_BINARYSTRING: + result = new Payload(Payload.Status.OK, os.toByteArray(), true); + break; + default: // Base64. + byte[] base64 = Base64.encode(os.toByteArray(), Base64.NO_WRAP); + String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII"); + result = new Payload(Payload.Status.OK, s); + } + + callbackContext.sendPayload(result); + } catch (IOException e) { + Log.d(LOG_TAG, e.getLocalizedMessage()); + callbackContext.sendPayload(new Payload(Payload.Status.IO_EXCEPTION, NOT_READABLE_ERR)); + } + } + }); + + + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } catch (FileNotFoundException e) { + callbackContext.sendPayload(new Payload(Payload.Status.IO_EXCEPTION, NOT_FOUND_ERR)); + } catch (IOException e) { + Log.d(LOG_TAG, e.getLocalizedMessage()); + callbackContext.sendPayload(new Payload(Payload.Status.IO_EXCEPTION, NOT_READABLE_ERR)); + } + } + + + /** + * Write contents of file. + * + * @param data The contents of the file. + * @param offset The position to begin writing the file. + * @param isBinary True if the file contents are base64-encoded binary data + */ + /**/ + public long write(String srcURLstr, String data, int offset, boolean isBinary) throws FileNotFoundException, IOException, NoModificationAllowedException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + + return fs.writeToFileAtURL(inputURL, data, offset, isBinary); + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + + } + + /** + * Truncate the file to size + */ + private long truncateFile(String srcURLstr, long size) throws FileNotFoundException, IOException, NoModificationAllowedException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + + return fs.truncateFileAtURL(inputURL, size); + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + } + + + /* + * Handle the response + */ + + public void onRequestPermissionResult(int requestCode, String[] permissions, + int[] grantResults) throws JSONException { + + final PendingRequests.Request req = pendingRequests.getAndRemove(requestCode); + if (req != null) { + for (int r : grantResults) { + if (r == PackageManager.PERMISSION_DENIED) { + req.getCallbackContext().sendPayload(new Payload(Payload.Status.ERROR, SECURITY_ERR)); + return; + } + } + switch (req.getAction()) { + case ACTION_GET_FILE: + threadhelper(new FileOp() { + public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException { + String dirname = args.getString(0); + + String path = args.getString(1); + JSONObject obj = getFile(dirname, path, args.optJSONObject(2), false); + req.getCallbackContext().success(obj); + } + }, req.getRawArgs(), req.getCallbackContext()); + break; + case ACTION_GET_DIRECTORY: + threadhelper(new FileOp() { + public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException { + String dirname = args.getString(0); + + String path = args.getString(1); + JSONObject obj = getFile(dirname, path, args.optJSONObject(2), true); + req.getCallbackContext().success(obj); + } + }, req.getRawArgs(), req.getCallbackContext()); + break; + case ACTION_WRITE: + threadhelper(new FileOp() { + public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException { + String fname = args.getString(0); + String data = args.getString(1); + int offset = args.getInt(2); + Boolean isBinary = args.getBoolean(3); + long fileSize = write(fname, data, offset, isBinary); + req.getCallbackContext().sendPayload(new Payload(Payload.Status.OK, fileSize)); + } + }, req.getRawArgs(), req.getCallbackContext()); + break; + case ACTION_READ_ENTRIES: + threadhelper(new FileOp() { + public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException { + String fname = args.getString(0); + JSONArray entries = readEntries(fname); + req.getCallbackContext().success(entries); + } + }, req.getRawArgs(), req.getCallbackContext()); + break; + } + } else { + Log.d(LOG_TAG, "Received permission callback for unknown request code"); + } + } + + private String getMimeType(Uri uri) { + String fileExtensionFromUrl = MimeTypeMap.getFileExtensionFromUrl(uri.toString()).toLowerCase(); + return MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtensionFromUrl); + } + + public ServicePathHandler getPathHandler() { + final ResourceApi resourceApi = webView.getResourceApi(); + + WebViewAssetLoader.PathHandler pathHandler = path -> { + String targetFileSystem = null; + + if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("persistent"))) { + targetFileSystem = "persistent"; + } else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("temporary"))) { + targetFileSystem = "temporary"; + } else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("files"))) { + targetFileSystem = "files"; + } else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("documents"))) { + targetFileSystem = "documents"; + } else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("cache"))) { + targetFileSystem = "cache"; + } else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("root"))) { + targetFileSystem = "root"; + } else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("files-external"))) { + targetFileSystem = "files-external"; + } else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("sdcard"))) { + targetFileSystem = "sdcard"; + } else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("cache-external"))) { + targetFileSystem = "cache-external"; + } else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("assets"))) { + targetFileSystem = "assets"; + } else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("content"))) { + targetFileSystem = "content"; + } + + boolean isAssetsFS = "assets".equals(targetFileSystem); + + if (targetFileSystem != null) { + // Loop the registered file systems to find the target. + for (Filesystem fileSystem : filesystems) { + /* + * When target is discovered: + * 1. Transform the url path to the native path + * 2. Load the file contents + * 3. Get the file mime type + * 4. Return the file & mime information back we Web Resources + */ + if (fileSystem.name.equals(targetFileSystem)) { + // E.g. replace __cdvfile_persistent__ with native path "/data/user/0/com.example.file/files/files/" + + if ("content".equals(targetFileSystem)) { + // The WebviewAssetLoader uses getPath API, which gives us a decoded path + // For content paths however, we need it to remain encoded. + // The Uri.encode API will encode forward slashes, therefore we must + // split the path, encode each segment, and rebuild the path + String[] pathParts = path.split("/"); + path = ""; + for (String part : pathParts) { + if ("".equals(path)) { + path = Uri.encode(part); + } + else { + path += "/" + Uri.encode(part); + } + } + } + + String fileSystemNativeUri = fileSystem.rootUri.toString().replace("file://", ""); + String fileTarget = path.replace(LocalFilesystemURL.fsNameToCdvKeyword(targetFileSystem) + "/", fileSystemNativeUri); + + if (isAssetsFS) { + fileTarget = fileTarget.replace("/android_asset/", ""); + } + + Uri fileUri = "file".equals(fileSystem.rootUri.getScheme()) + ? Uri.fromFile(new File(fileTarget)) + : Uri.parse(fileTarget); + String mimeType = null; + + try { + InputStream io = null; + if (isAssetsFS) { + io = webView.getContext().getAssets().open(fileTarget); + mimeType = getMimeType(fileUri); + } else { + if (fileUri.getScheme() == null) { + fileUri = Uri.parse(fileSystem.rootUri.getScheme() + "://" + fileUri.getPath()); + } + ResourceApi.OpenForReadResult resource = resourceApi.openForRead(fileUri); + io = resource.inputStream; + mimeType = resource.mimeType; + } + + return new WebResourceResponse(mimeType, null, io); + } catch (FileNotFoundException e) { + Log.e(LOG_TAG, e.getMessage()); + } catch (IOException e) { + Log.e(LOG_TAG, e.getMessage()); + } + } + } + } + + return null; + }; + + return new ServicePathHandler(pathHandler); + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/file/Filesystem.java b/platforms/android/app/src/main/java/com/foxdebug/acode/file/Filesystem.java new file mode 100644 index 0000000000..f7d15d5323 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/file/Filesystem.java @@ -0,0 +1,348 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package com.foxdebug.acode.file; + +import android.net.Uri; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Arrays; + +import com.foxdebug.acode.runtime.Preferences; +import com.foxdebug.acode.runtime.ResourceApi; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public abstract class Filesystem { + + protected final Uri rootUri; + protected final ResourceApi resourceApi; + protected final Preferences preferences; + public final String name; + private JSONObject rootEntry; + + static String SCHEME_HTTPS = "https"; + static String DEFAULT_HOSTNAME = "localhost"; + + public Filesystem(Uri rootUri, String name, ResourceApi resourceApi, Preferences preferences) { + this.rootUri = rootUri; + this.name = name; + this.resourceApi = resourceApi; + this.preferences = preferences; + } + + public interface ReadFileCallback { + public void handleData(InputStream inputStream, String contentType) throws IOException; + } + + public static JSONObject makeEntryForURL(LocalFilesystemURL inputURL, Uri nativeURL) { + try { + String path = inputURL.path; + int end = path.endsWith("/") ? 1 : 0; + String[] parts = path.substring(0, path.length() - end).split("/+"); + String fileName = parts[parts.length - 1]; + + JSONObject entry = new JSONObject(); + entry.put("isFile", !inputURL.isDirectory); + entry.put("isDirectory", inputURL.isDirectory); + entry.put("name", fileName); + entry.put("fullPath", path); + // The file system can't be specified, as it would lead to an infinite loop, + // but the filesystem name can be. + entry.put("filesystemName", inputURL.fsName); + // Backwards compatibility + entry.put("filesystem", "temporary".equals(inputURL.fsName) ? 0 : 1); + + String nativeUrlStr = nativeURL.toString(); + if (inputURL.isDirectory && !nativeUrlStr.endsWith("/")) { + nativeUrlStr += "/"; + } + entry.put("nativeURL", nativeUrlStr); + return entry; + } catch (JSONException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + public JSONObject makeEntryForURL(LocalFilesystemURL inputURL) { + Uri nativeUri = toNativeUri(inputURL); + return nativeUri == null ? null : makeEntryForURL(inputURL, nativeUri); + } + + public JSONObject makeEntryForNativeUri(Uri nativeUri) { + LocalFilesystemURL inputUrl = toLocalUri(nativeUri); + return inputUrl == null ? null : makeEntryForURL(inputUrl, nativeUri); + } + + public JSONObject getEntryForLocalURL(LocalFilesystemURL inputURL) throws IOException { + return makeEntryForURL(inputURL); + } + + public JSONObject makeEntryForFile(File file) { + return makeEntryForNativeUri(Uri.fromFile(file)); + } + + abstract JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, String path, + JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException; + + abstract boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException; + + abstract boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException, NoModificationAllowedException; + + abstract LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException; + + public final JSONArray readEntriesAtLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException { + LocalFilesystemURL[] children = listChildren(inputURL); + JSONArray entries = new JSONArray(); + if (children != null) { + for (LocalFilesystemURL url : children) { + entries.put(makeEntryForURL(url)); + } + } + return entries; + } + + abstract JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException; + + public Uri getRootUri() { + return rootUri; + } + + public boolean exists(LocalFilesystemURL inputURL) { + try { + getFileMetadataForLocalURL(inputURL); + } catch (FileNotFoundException e) { + return false; + } + return true; + } + + public Uri nativeUriForFullPath(String fullPath) { + Uri ret = null; + if (fullPath != null) { + String encodedPath = Uri.fromFile(new File(fullPath)).getEncodedPath(); + if (encodedPath.startsWith("/")) { + encodedPath = encodedPath.substring(1); + } + ret = rootUri.buildUpon().appendEncodedPath(encodedPath).build(); + } + return ret; + } + + public LocalFilesystemURL localUrlforFullPath(String fullPath) { + Uri nativeUri = nativeUriForFullPath(fullPath); + if (nativeUri != null) { + return toLocalUri(nativeUri); + } + return null; + } + + /** + * Removes multiple repeated //s, and collapses processes ../s. + */ + protected static String normalizePath(String rawPath) { + // If this is an absolute path, trim the leading "/" and replace it later + boolean isAbsolutePath = rawPath.startsWith("/"); + if (isAbsolutePath) { + rawPath = rawPath.replaceFirst("/+", ""); + } + ArrayList<String> components = new ArrayList<String>(Arrays.asList(rawPath.split("/+"))); + for (int index = 0; index < components.size(); ++index) { + if (components.get(index).equals("..")) { + components.remove(index); + if (index > 0) { + components.remove(index-1); + --index; + } + } + } + StringBuilder normalizedPath = new StringBuilder(); + for(String component: components) { + normalizedPath.append("/"); + normalizedPath.append(component); + } + if (isAbsolutePath) { + return normalizedPath.toString(); + } else { + return normalizedPath.toString().substring(1); + } + } + + /** + * Gets the free space in bytes available on this filesystem. + * Subclasses may override this method to return nonzero free space. + */ + public long getFreeSpaceInBytes() { + return 0; + } + + public abstract Uri toNativeUri(LocalFilesystemURL inputURL); + public abstract LocalFilesystemURL toLocalUri(Uri inputURL); + + public JSONObject getRootEntry() { + if (rootEntry == null) { + rootEntry = makeEntryForNativeUri(rootUri); + } + return rootEntry; + } + + public JSONObject getParentForLocalURL(LocalFilesystemURL inputURL) throws IOException { + Uri parentUri = inputURL.uri; + String parentPath = new File(inputURL.uri.getPath()).getParent(); + if (!"/".equals(parentPath)) { + parentUri = inputURL.uri.buildUpon().path(parentPath + '/').build(); + } + return getEntryForLocalURL(LocalFilesystemURL.parse(parentUri)); + } + + protected LocalFilesystemURL makeDestinationURL(String newName, LocalFilesystemURL srcURL, LocalFilesystemURL destURL, boolean isDirectory) { + // I know this looks weird but it is to work around a JSON bug. + if ("null".equals(newName) || "".equals(newName)) { + newName = srcURL.uri.getLastPathSegment();; + } + + String newDest = destURL.uri.toString(); + if (newDest.endsWith("/")) { + newDest = newDest + newName; + } else { + newDest = newDest + "/" + newName; + } + if (isDirectory) { + newDest += '/'; + } + return LocalFilesystemURL.parse(newDest); + } + + /* Read a source URL (possibly from a different filesystem, srcFs,) and copy it to + * the destination URL on this filesystem, optionally with a new filename. + * If move is true, then this method should either perform an atomic move operation + * or remove the source file when finished. + */ + public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName, + Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException { + // First, check to see that we can do it + if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) { + throw new NoModificationAllowedException("Cannot move file at source URL"); + } + final LocalFilesystemURL destination = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory); + + Uri srcNativeUri = srcFs.toNativeUri(srcURL); + + ResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(srcNativeUri); + OutputStream os = null; + try { + os = getOutputStreamForURL(destination); + } catch (IOException e) { + ofrr.inputStream.close(); + throw e; + } + // Closes streams. + resourceApi.copyResource(ofrr, os); + + if (move) { + srcFs.removeFileAtLocalURL(srcURL); + } + return getEntryForLocalURL(destination); + } + + public OutputStream getOutputStreamForURL(LocalFilesystemURL inputURL) throws IOException { + return resourceApi.openOutputStream(toNativeUri(inputURL)); + } + + public void readFileAtURL(LocalFilesystemURL inputURL, long start, long end, + ReadFileCallback readFileCallback) throws IOException { + ResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(toNativeUri(inputURL)); + if (end < 0) { + end = ofrr.length; + } + long numBytesToRead = end - start; + try { + if (start > 0) { + ofrr.inputStream.skip(start); + } + InputStream inputStream = ofrr.inputStream; + if (end < ofrr.length) { + inputStream = new LimitedInputStream(inputStream, numBytesToRead); + } + readFileCallback.handleData(inputStream, ofrr.mimeType); + } finally { + ofrr.inputStream.close(); + } + } + + abstract long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset, + boolean isBinary) throws NoModificationAllowedException, IOException; + + abstract long truncateFileAtURL(LocalFilesystemURL inputURL, long size) + throws IOException, NoModificationAllowedException; + + // This method should return null if filesystem urls cannot be mapped to paths + abstract String filesystemPathForURL(LocalFilesystemURL url); + + abstract LocalFilesystemURL URLforFilesystemPath(String path); + + abstract boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL); + + protected class LimitedInputStream extends FilterInputStream { + long numBytesToRead; + public LimitedInputStream(InputStream in, long numBytesToRead) { + super(in); + this.numBytesToRead = numBytesToRead; + } + @Override + public int read() throws IOException { + if (numBytesToRead <= 0) { + return -1; + } + numBytesToRead--; + return in.read(); + } + @Override + public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException { + if (numBytesToRead <= 0) { + return -1; + } + int bytesToRead = byteCount; + if (byteCount > numBytesToRead) { + bytesToRead = (int)numBytesToRead; // Cast okay; long is less than int here. + } + int numBytesRead = in.read(buffer, byteOffset, bytesToRead); + numBytesToRead -= numBytesRead; + return numBytesRead; + } + } + + protected Uri.Builder createLocalUriBuilder() { + String scheme = preferences.getString("scheme", SCHEME_HTTPS).toLowerCase(); + String hostname = preferences.getString("hostname", DEFAULT_HOSTNAME).toLowerCase(); + String path = LocalFilesystemURL.fsNameToCdvKeyword(name); + + return new Uri.Builder() + .scheme(scheme) + .authority(hostname) + .path(path); + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/file/InvalidModificationException.java b/platforms/android/app/src/main/java/com/foxdebug/acode/file/InvalidModificationException.java new file mode 100644 index 0000000000..da9d9dc6b2 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/file/InvalidModificationException.java @@ -0,0 +1,30 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ + + +package com.foxdebug.acode.file; + +@SuppressWarnings("serial") +public class InvalidModificationException extends Exception { + + public InvalidModificationException(String message) { + super(message); + } + +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/file/LocalFilesystem.java b/platforms/android/app/src/main/java/com/foxdebug/acode/file/LocalFilesystem.java new file mode 100644 index 0000000000..f7d6902e25 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/file/LocalFilesystem.java @@ -0,0 +1,470 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package com.foxdebug.acode.file; + +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.os.Build; +import android.os.Environment; +import android.util.Base64; + +import com.foxdebug.acode.runtime.Preferences; +import com.foxdebug.acode.runtime.ResourceApi; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.channels.FileChannel; +import java.nio.charset.Charset; + +public class LocalFilesystem extends Filesystem { + private final Context context; + + public LocalFilesystem(String name, Context context, ResourceApi resourceApi, File fsRoot, Preferences preferences) { + super(Uri.fromFile(fsRoot).buildUpon().appendEncodedPath("").build(), name, resourceApi, preferences); + this.context = context; + } + + public String filesystemPathForFullPath(String fullPath) { + return new File(rootUri.getPath(), fullPath).toString(); + } + + @Override + public String filesystemPathForURL(LocalFilesystemURL url) { + return filesystemPathForFullPath(url.path); + } + + private String fullPathForFilesystemPath(String absolutePath) { + if (absolutePath != null && absolutePath.startsWith(rootUri.getPath())) { + return absolutePath.substring(rootUri.getPath().length() - 1); + } + return null; + } + + @Override + public Uri toNativeUri(LocalFilesystemURL inputURL) { + return nativeUriForFullPath(inputURL.path); + } + + @Override + public LocalFilesystemURL toLocalUri(Uri inputURL) { + if (!"file".equals(inputURL.getScheme())) { + return null; + } + File f = new File(inputURL.getPath()); + // Removes and duplicate /s (e.g. file:///a//b/c) + Uri resolvedUri = Uri.fromFile(f); + String rootUriNoTrailingSlash = rootUri.getEncodedPath(); + rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1); + if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) { + return null; + } + String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length()); + // Strip leading slash + if (!subPath.isEmpty()) { + subPath = subPath.substring(1); + } + + Uri.Builder b = createLocalUriBuilder(); + + if (!subPath.isEmpty()) { + b.appendEncodedPath(subPath); + } + if (f.isDirectory()) { + // Add trailing / for directories. + b.appendEncodedPath(""); + } + return LocalFilesystemURL.parse(b.build()); + } + + @Override + public LocalFilesystemURL URLforFilesystemPath(String path) { + return localUrlforFullPath(fullPathForFilesystemPath(path)); + } + + @Override + public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, + String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException { + boolean create = false; + boolean exclusive = false; + + if (options != null) { + create = options.optBoolean("create"); + if (create) { + exclusive = options.optBoolean("exclusive"); + } + } + + // Check for a ":" character in the file to line up with BB and iOS + if (path.contains(":")) { + throw new EncodingException("This path has an invalid \":\" in it."); + } + + LocalFilesystemURL requestedURL; + + // Check whether the supplied path is absolute or relative + if (directory && !path.endsWith("/")) { + path += "/"; + } + if (path.startsWith("/")) { + requestedURL = localUrlforFullPath(normalizePath(path)); + } else { + requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path)); + } + + File fp = new File(this.filesystemPathForURL(requestedURL)); + + if (create) { + if (exclusive && fp.exists()) { + throw new FileExistsException("create/exclusive fails"); + } + if (directory) { + fp.mkdir(); + } else { + fp.createNewFile(); + } + if (!fp.exists()) { + throw new FileExistsException("create fails"); + } + } + else { + if (!fp.exists()) { + throw new FileNotFoundException("path does not exist"); + } + if (directory) { + if (fp.isFile()) { + throw new TypeMismatchException("path doesn't exist or is file"); + } + } else { + if (fp.isDirectory()) { + throw new TypeMismatchException("path doesn't exist or is directory"); + } + } + } + + // Return the directory + return makeEntryForURL(requestedURL); + } + + @Override + public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException { + + File fp = new File(filesystemPathForURL(inputURL)); + + // You can't delete a directory that is not empty + if (fp.isDirectory() && fp.list().length > 0) { + throw new InvalidModificationException("You can't delete a directory that is not empty."); + } + + return fp.delete(); + } + + @Override + public boolean exists(LocalFilesystemURL inputURL) { + File fp = new File(filesystemPathForURL(inputURL)); + return fp.exists(); + } + + @Override + public long getFreeSpaceInBytes() { + return DirectoryManager.getFreeSpaceInBytes(rootUri.getPath()); + } + + @Override + public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException { + File directory = new File(filesystemPathForURL(inputURL)); + return removeDirRecursively(directory); + } + + protected boolean removeDirRecursively(File directory) throws FileExistsException { + if (directory.isDirectory()) { + for (File file : directory.listFiles()) { + removeDirRecursively(file); + } + } + + if (!directory.delete()) { + throw new FileExistsException("could not delete: " + directory.getName()); + } else { + return true; + } + } + + @Override + public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException { + File fp = new File(filesystemPathForURL(inputURL)); + + if (!fp.exists()) { + // The directory we are listing doesn't exist so we should fail. + throw new FileNotFoundException(); + } + + File[] files = fp.listFiles(); + if (files == null) { + // inputURL is a directory + return null; + } + LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length]; + for (int i = 0; i < files.length; i++) { + entries[i] = URLforFilesystemPath(files[i].getPath()); + } + + return entries; + } + + @Override + public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException { + File file = new File(filesystemPathForURL(inputURL)); + + if (!file.exists()) { + throw new FileNotFoundException("File at " + inputURL.uri + " does not exist."); + } + + JSONObject metadata = new JSONObject(); + try { + // Ensure that directories report a size of 0 + metadata.put("size", file.isDirectory() ? 0 : file.length()); + metadata.put("type", resourceApi.getMimeType(Uri.fromFile(file))); + metadata.put("name", file.getName()); + metadata.put("fullPath", inputURL.path); + metadata.put("lastModifiedDate", file.lastModified()); + } catch (JSONException e) { + return null; + } + return metadata; + } + + private void copyFile(Filesystem srcFs, LocalFilesystemURL srcURL, File destFile, boolean move) throws IOException, InvalidModificationException, NoModificationAllowedException { + if (move) { + String realSrcPath = srcFs.filesystemPathForURL(srcURL); + if (realSrcPath != null) { + File srcFile = new File(realSrcPath); + if (srcFile.renameTo(destFile)) { + return; + } + // Trying to rename the file failed. Possibly because we moved across file system on the device. + } + } + + ResourceApi.OpenForReadResult offr = resourceApi.openForRead(srcFs.toNativeUri(srcURL)); + resourceApi.copyResource(offr, new FileOutputStream(destFile)); + + if (move) { + srcFs.removeFileAtLocalURL(srcURL); + } + } + + private void copyDirectory(Filesystem srcFs, LocalFilesystemURL srcURL, File dstDir, boolean move) throws IOException, NoModificationAllowedException, InvalidModificationException, FileExistsException { + if (move) { + String realSrcPath = srcFs.filesystemPathForURL(srcURL); + if (realSrcPath != null) { + File srcDir = new File(realSrcPath); + // If the destination directory already exists and is empty then delete it. This is according to spec. + if (dstDir.exists()) { + if (dstDir.list().length > 0) { + throw new InvalidModificationException("directory is not empty"); + } + dstDir.delete(); + } + // Try to rename the directory + if (srcDir.renameTo(dstDir)) { + return; + } + // Trying to rename the file failed. Possibly because we moved across file system on the device. + } + } + + if (dstDir.exists()) { + if (dstDir.list().length > 0) { + throw new InvalidModificationException("directory is not empty"); + } + } else { + if (!dstDir.mkdir()) { + // If we can't create the directory then fail + throw new NoModificationAllowedException("Couldn't create the destination directory"); + } + } + + LocalFilesystemURL[] children = srcFs.listChildren(srcURL); + for (LocalFilesystemURL childLocalUrl : children) { + File target = new File(dstDir, new File(childLocalUrl.path).getName()); + if (childLocalUrl.isDirectory) { + copyDirectory(srcFs, childLocalUrl, target, false); + } else { + copyFile(srcFs, childLocalUrl, target, false); + } + } + + if (move) { + srcFs.recursiveRemoveFileAtLocalURL(srcURL); + } + } + + @Override + public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName, + Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException { + + // Check to see if the destination directory exists + String newParent = this.filesystemPathForURL(destURL); + File destinationDir = new File(newParent); + if (!destinationDir.exists()) { + // The destination does not exist so we should fail. + throw new FileNotFoundException("The source does not exist"); + } + + // Figure out where we should be copying to + final LocalFilesystemURL destinationURL = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory); + + Uri dstNativeUri = toNativeUri(destinationURL); + Uri srcNativeUri = srcFs.toNativeUri(srcURL); + // Check to see if source and destination are the same file + if (dstNativeUri.equals(srcNativeUri)) { + throw new InvalidModificationException("Can't copy onto itself"); + } + + if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) { + throw new InvalidModificationException("Source URL is read-only (cannot move)"); + } + + File destFile = new File(dstNativeUri.getPath()); + if (destFile.exists()) { + if (!srcURL.isDirectory && destFile.isDirectory()) { + throw new InvalidModificationException("Can't copy/move a file to an existing directory"); + } else if (srcURL.isDirectory && destFile.isFile()) { + throw new InvalidModificationException("Can't copy/move a directory to an existing file"); + } + } + + if (srcURL.isDirectory) { + // E.g. Copy /sdcard/myDir to /sdcard/myDir/backup + if (dstNativeUri.toString().startsWith(srcNativeUri.toString() + '/')) { + throw new InvalidModificationException("Can't copy directory into itself"); + } + copyDirectory(srcFs, srcURL, destFile, move); + } else { + copyFile(srcFs, srcURL, destFile, move); + } + return makeEntryForURL(destinationURL); + } + + @Override + public long writeToFileAtURL(LocalFilesystemURL inputURL, String data, + int offset, boolean isBinary) throws IOException, NoModificationAllowedException { + + boolean append = false; + if (offset > 0) { + this.truncateFileAtURL(inputURL, offset); + append = true; + } + + byte[] rawData; + if (isBinary) { + rawData = Base64.decode(data, Base64.DEFAULT); + } else { + rawData = data.getBytes(Charset.defaultCharset()); + } + ByteArrayInputStream in = new ByteArrayInputStream(rawData); + try + { + byte buff[] = new byte[rawData.length]; + String absolutePath = filesystemPathForURL(inputURL); + FileOutputStream out = new FileOutputStream(absolutePath, append); + try { + in.read(buff, 0, buff.length); + out.write(buff, 0, rawData.length); + out.flush(); + } finally { + // Always close the output + out.close(); + } + if (isPublicDirectory(absolutePath)) { + broadcastNewFile(Uri.fromFile(new File(absolutePath))); + } + } + catch (NullPointerException e) + { + // This is a bug in the Android implementation of the Java Stack + NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString()); + realException.initCause(e); + throw realException; + } + + return rawData.length; + } + + private boolean isPublicDirectory(String absolutePath) { + // TODO: should expose a way to scan app's private files (maybe via a flag). + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + // Lollipop has a bug where SD cards are null. + for (File f : context.getExternalMediaDirs()) { + if(f != null && absolutePath.startsWith(f.getAbsolutePath())) { + return true; + } + } + } + + String extPath = Environment.getExternalStorageDirectory().getAbsolutePath(); + return absolutePath.startsWith(extPath); + } + + /** + * Send broadcast of new file so files appear over MTP + */ + private void broadcastNewFile(Uri nativeUri) { + Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, nativeUri); + context.sendBroadcast(intent); + } + + @Override + public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException { + File file = new File(filesystemPathForURL(inputURL)); + + if (!file.exists()) { + throw new FileNotFoundException("File at " + inputURL.uri + " does not exist."); + } + + RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw"); + try { + if (raf.length() >= size) { + FileChannel channel = raf.getChannel(); + channel.truncate(size); + return size; + } + + return raf.length(); + } finally { + raf.close(); + } + + + } + + @Override + public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) { + String path = filesystemPathForURL(inputURL); + File file = new File(path); + return file.exists(); + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/file/LocalFilesystemURL.java b/platforms/android/app/src/main/java/com/foxdebug/acode/file/LocalFilesystemURL.java new file mode 100644 index 0000000000..37df05eaaa --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/file/LocalFilesystemURL.java @@ -0,0 +1,74 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package com.foxdebug.acode.file; + +import android.net.Uri; + +public class LocalFilesystemURL { + + public static final String FILESYSTEM_PROTOCOL = "cdvfile"; + public static final String CDVFILE_KEYWORD = "__cdvfile_"; + + public final Uri uri; + public final String fsName; + public final String path; + public final boolean isDirectory; + + private LocalFilesystemURL(Uri uri, String fsName, String fsPath, boolean isDirectory) { + this.uri = uri; + this.fsName = fsName; + this.path = fsPath; + this.isDirectory = isDirectory; + } + + public static LocalFilesystemURL parse(Uri uri) { + if(!uri.toString().contains(CDVFILE_KEYWORD)) { + return null; + } + + String path = uri.getPath(); + if (path.length() < 1) { + return null; + } + + int firstSlashIdx = path.indexOf('/', 1); + if (firstSlashIdx < 0) { + return null; + } + + String fsName = path.substring(1, firstSlashIdx); + fsName = fsName.substring(CDVFILE_KEYWORD.length()); + fsName = fsName.substring(0, fsName.length() - 2); + + path = path.substring(firstSlashIdx); + + boolean isDirectory = path.charAt(path.length() - 1) == '/'; + return new LocalFilesystemURL(uri, fsName, path, isDirectory); + } + + public static LocalFilesystemURL parse(String uri) { + return parse(Uri.parse(uri)); + } + + public static String fsNameToCdvKeyword(String fsName) { return CDVFILE_KEYWORD + fsName + "__"; } + + public String toString() { + return uri.toString(); + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/file/NoModificationAllowedException.java b/platforms/android/app/src/main/java/com/foxdebug/acode/file/NoModificationAllowedException.java new file mode 100644 index 0000000000..bbe2cd2095 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/file/NoModificationAllowedException.java @@ -0,0 +1,29 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ + +package com.foxdebug.acode.file; + +@SuppressWarnings("serial") +public class NoModificationAllowedException extends Exception { + + public NoModificationAllowedException(String message) { + super(message); + } + +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/file/PendingRequests.java b/platforms/android/app/src/main/java/com/foxdebug/acode/file/PendingRequests.java new file mode 100644 index 0000000000..c00cc4471c --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/file/PendingRequests.java @@ -0,0 +1,94 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package com.foxdebug.acode.file; + +import android.util.SparseArray; + +import com.foxdebug.acode.runtime.Callback; + +/** + * Holds pending runtime permission requests + */ +class PendingRequests { + private int currentReqId = 0; + private SparseArray<Request> requests = new SparseArray<Request>(); + + /** + * Creates a request and adds it to the array of pending requests. Each created request gets a + * unique result code for use with requestPermission() + * @param rawArgs The raw arguments passed to the plugin + * @param action The action this request corresponds to (get file, etc.) + * @param callbackContext The Callback for this plugin call + * @return The request code that can be used to retrieve the Request object + */ + public synchronized int createRequest(String rawArgs, int action, Callback callbackContext) { + Request req = new Request(rawArgs, action, callbackContext); + requests.put(req.requestCode, req); + return req.requestCode; + } + + /** + * Gets the request corresponding to this request code and removes it from the pending requests + * @param requestCode The request code for the desired request + * @return The request corresponding to the given request code or null if such a + * request is not found + */ + public synchronized Request getAndRemove(int requestCode) { + Request result = requests.get(requestCode); + requests.remove(requestCode); + return result; + } + + /** + * Holds the options and Callback for a call made to the plugin. + */ + public class Request { + + // Unique int used to identify this request in any Android permission callback + private int requestCode; + + // Action to be performed after permission request result + private int action; + + // Raw arguments passed to plugin + private String rawArgs; + + // The callback context for this plugin request + private Callback callbackContext; + + private Request(String rawArgs, int action, Callback callbackContext) { + this.rawArgs = rawArgs; + this.action = action; + this.callbackContext = callbackContext; + this.requestCode = currentReqId ++; + } + + public int getAction() { + return this.action; + } + + public String getRawArgs() { + return rawArgs; + } + + public Callback getCallbackContext() { + return callbackContext; + } + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/file/TypeMismatchException.java b/platforms/android/app/src/main/java/com/foxdebug/acode/file/TypeMismatchException.java new file mode 100644 index 0000000000..e1ab6cb37e --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/file/TypeMismatchException.java @@ -0,0 +1,30 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ + + +package com.foxdebug.acode.file; + +@SuppressWarnings("serial") +public class TypeMismatchException extends Exception { + + public TypeMismatchException(String message) { + super(message); + } + +} diff --git a/src/plugins/ftp/src/android/com/foxdebug/ftp/Ftp.java b/platforms/android/app/src/main/java/com/foxdebug/acode/ftp/Ftp.java similarity index 92% rename from src/plugins/ftp/src/android/com/foxdebug/ftp/Ftp.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/ftp/Ftp.java index b2de25446a..6ae42ce6b2 100644 --- a/src/plugins/ftp/src/android/com/foxdebug/ftp/Ftp.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/ftp/Ftp.java @@ -1,62 +1,54 @@ -package com.foxdebug.ftp; +package com.foxdebug.acode.ftp; import android.app.Activity; import android.content.Context; import android.util.Log; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; import java.lang.SecurityException; import java.lang.reflect.Method; -import java.net.SocketException; import java.net.URI; import java.net.URISyntaxException; -import java.net.URISyntaxException; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; -import java.util.List; + import org.apache.commons.net.ftp.*; import org.apache.commons.net.ftp.parser.ParserInitializationException; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaInterface; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.CordovaWebView; + +import com.foxdebug.acode.Acode; +import com.foxdebug.acode.runtime.BridgeContext; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Service; import org.json.JSONArray; -import org.json.JSONException; import org.json.JSONObject; -public class Ftp extends CordovaPlugin { +import kotlinx.coroutines.GlobalScope; + +public class Ftp extends Service { HashMap<String, FTPClient> ftpProfiles = new HashMap<String, FTPClient>(); Context context; Activity activity; String connectionID; - public void initialize(CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); - context = cordova.getContext(); - activity = cordova.getActivity(); + public void initialize(BridgeContext bridgeContext) { + super.initialize(bridgeContext); + context = bridgeContext.getWebActivity(); + activity = bridgeContext.getWebActivity(); } public boolean execute( String action, JSONArray args, - CallbackContext callback + Callback callback ) { try { Method method = this.getClass() - .getDeclaredMethod(action, JSONArray.class, CallbackContext.class); + .getDeclaredMethod(action, JSONArray.class, Callback.class); if (method != null) { method.invoke(this, args, callback); return true; @@ -74,16 +66,16 @@ public boolean execute( } } - public void connect(JSONArray args, CallbackContext callback) { + public void connect(JSONArray args, Callback callback) { connect(args, callback, false); } public void connect( JSONArray args, - CallbackContext callback, + Callback callback, boolean isRetry ) { - cordova + Acode.getInstance() .getThreadPool() .execute( new Runnable() { @@ -202,8 +194,8 @@ private static String getParentPath(String path) { return path.substring(0, lastSepIndex); } - public void listDirectory(JSONArray args, CallbackContext callback) { - cordova + public void listDirectory(JSONArray args, Callback callback) { + Acode.getInstance() .getThreadPool() .execute( new Runnable() { @@ -315,9 +307,9 @@ public void run() { ); } - public void exists(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void exists(JSONArray args, Callback callback) { + + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -365,9 +357,8 @@ public void run() { ); } - public void sendNoOp(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void sendNoOp(JSONArray args, Callback callback) { + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -388,9 +379,8 @@ public void run() { ); } - public void deleteFile(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void deleteFile(JSONArray args, Callback callback) { + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -428,9 +418,8 @@ public void run() { ); } - public void deleteDirectory(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void deleteDirectory(JSONArray args, Callback callback) { + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -471,9 +460,8 @@ public void run() { ); } - public void rename(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void rename(JSONArray args, Callback callback) { + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -558,9 +546,8 @@ public void run() { ); } - public void downloadFile(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void downloadFile(JSONArray args, Callback callback) { + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -645,9 +632,8 @@ public void run() { ); } - public void uploadFile(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void uploadFile(JSONArray args, Callback callback) { + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -723,9 +709,8 @@ public void run() { ); } - public void getKeepAlive(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void getKeepAlive(JSONArray args, Callback callback) { + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -752,9 +737,8 @@ public void run() { ); } - public void execCommand(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void execCommand(JSONArray args, Callback callback) { + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -791,9 +775,8 @@ public void run() { ); } - public void isConnected(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void isConnected(JSONArray args, Callback callback) { + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -822,9 +805,8 @@ public void run() { ); } - public void disconnect(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void disconnect(JSONArray args, Callback callback) { + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -846,9 +828,8 @@ public void run() { ); } - public void createDirectory(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void createDirectory(JSONArray args, Callback callback) { + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -884,9 +865,8 @@ public void run() { ); } - public void changeDirectory(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void changeDirectory(JSONArray args, Callback callback) { + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -924,10 +904,9 @@ public void run() { public void changeToParentDirectory( JSONArray args, - CallbackContext callback + Callback callback ) { - cordova - .getThreadPool() + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -957,9 +936,8 @@ public void run() { ); } - public void getWorkingDirectory(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void getWorkingDirectory(JSONArray args, Callback callback) { + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { @@ -989,9 +967,8 @@ public void run() { ); } - public void getStat(JSONArray args, CallbackContext callback) { - cordova - .getThreadPool() + public void getStat(JSONArray args, Callback callback) { + Acode.getInstance().getThreadPool() .execute( new Runnable() { public void run() { diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeClientAuth.java b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeClientAuth.java new file mode 100644 index 0000000000..c72f001d93 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeClientAuth.java @@ -0,0 +1,113 @@ +package com.foxdebug.acode.http; + +import android.app.Activity; +import android.content.Context; +import android.security.KeyChain; +import android.security.KeyChainAliasCallback; +import android.util.Log; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.net.URI; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; + +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; + +import com.foxdebug.acode.runtime.Callback; + +import com.silkimen.http.KeyChainKeyManager; +import com.silkimen.http.TLSConfiguration; + +class NativeClientAuth implements Runnable, KeyChainAliasCallback { + private static final String TAG = "Native-Plugin-HTTP"; + + private String mode; + private String aliasString; + private byte[] rawPkcs; + private String pkcsPassword; + private Activity activity; + private Context context; + private TLSConfiguration tlsConfiguration; + private Callback callbackContext; + + public NativeClientAuth(final String mode, final String aliasString, final byte[] rawPkcs, + final String pkcsPassword, final Activity activity, final Context context, final TLSConfiguration configContainer, + final Callback callbackContext) { + + this.mode = mode; + this.aliasString = aliasString; + this.rawPkcs = rawPkcs; + this.pkcsPassword = pkcsPassword; + this.activity = activity; + this.tlsConfiguration = configContainer; + this.context = context; + this.callbackContext = callbackContext; + } + + @Override + public void run() { + if ("systemstore".equals(this.mode)) { + this.loadFromSystemStore(); + } else if ("buffer".equals(this.mode)) { + this.loadFromBuffer(); + } else { + this.disableClientAuth(); + } + } + + private void loadFromSystemStore() { + if (this.aliasString == null) { + KeyChain.choosePrivateKeyAlias(this.activity, this, null, null, null, -1, null); + } else { + this.alias(this.aliasString); + } + } + + private void loadFromBuffer() { + try { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + String keyManagerFactoryAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm); + ByteArrayInputStream stream = new ByteArrayInputStream(this.rawPkcs); + + keyStore.load(stream, this.pkcsPassword.toCharArray()); + keyManagerFactory.init(keyStore, this.pkcsPassword.toCharArray()); + + this.tlsConfiguration.setKeyManagers(keyManagerFactory.getKeyManagers()); + this.callbackContext.success(); + } catch (Exception e) { + Log.e(TAG, "Couldn't load given PKCS12 container for authentication", e); + this.callbackContext.error("Couldn't load given PKCS12 container for authentication"); + } + } + + private void disableClientAuth() { + this.tlsConfiguration.setKeyManagers(null); + this.callbackContext.success(); + } + + @Override + public void alias(final String alias) { + try { + if (alias == null) { + throw new Exception("Couldn't get a consent for private key access"); + } + + PrivateKey key = KeyChain.getPrivateKey(this.context, alias); + X509Certificate[] chain = KeyChain.getCertificateChain(this.context, alias); + KeyManager keyManager = new KeyChainKeyManager(alias, key, chain); + + this.tlsConfiguration.setKeyManagers(new KeyManager[] { keyManager }); + + this.callbackContext.success(alias); + } catch (Exception e) { + Log.e(TAG, "Couldn't load private key and certificate pair with given alias \"" + alias + "\" for authentication", + e); + this.callbackContext.error( + "Couldn't load private key and certificate pair with given alias \"" + alias + "\" for authentication"); + } + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpBase.java b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpBase.java new file mode 100644 index 0000000000..50090f1f47 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpBase.java @@ -0,0 +1,234 @@ +package com.foxdebug.acode.http; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import java.io.InterruptedIOException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; + +import javax.net.ssl.SSLException; + +import com.silkimen.http.HttpBodyDecoder; +import com.silkimen.http.HttpRequest; +import com.silkimen.http.HttpRequest.HttpRequestException; +import com.silkimen.http.JsonUtils; +import com.silkimen.http.TLSConfiguration; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import android.util.Base64; +import android.util.Log; + +abstract class NativeHttpBase implements Runnable { + protected static final String TAG = "Native-Plugin-HTTP"; + + protected String method; + protected String url; + protected String serializer = "none"; + protected String responseType; + protected Object data; + protected JSONObject headers; + protected int connectTimeout; + protected int readTimeout; + protected boolean followRedirects; + protected TLSConfiguration tlsConfiguration; + protected NativeObservableCallbackContext callbackContext; + + public NativeHttpBase(String method, String url, String serializer, Object data, JSONObject headers, int connectTimeout, + int readTimeout, boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration, + NativeObservableCallbackContext callbackContext) { + + this.method = method; + this.url = url; + this.serializer = serializer; + this.data = data; + this.headers = headers; + this.connectTimeout = connectTimeout; + this.readTimeout = readTimeout; + this.followRedirects = followRedirects; + this.responseType = responseType; + this.tlsConfiguration = tlsConfiguration; + this.callbackContext = callbackContext; + } + + public NativeHttpBase(String method, String url, JSONObject headers, int connectTimeout, int readTimeout, boolean followRedirects, + String responseType, TLSConfiguration tlsConfiguration, NativeObservableCallbackContext callbackContext) { + + this.method = method; + this.url = url; + this.headers = headers; + this.connectTimeout = connectTimeout; + this.readTimeout = readTimeout; + this.followRedirects = followRedirects; + this.responseType = responseType; + this.tlsConfiguration = tlsConfiguration; + this.callbackContext = callbackContext; + } + + @Override + public void run() { + NativeHttpResponse response = new NativeHttpResponse(); + HttpRequest request = null; + + try { + request = this.createRequest(); + this.prepareRequest(request); + this.sendBody(request); + this.processResponse(request, response); + request.disconnect(); + } catch (HttpRequestException e) { + Throwable cause = e.getCause(); + String message = cause.getMessage(); + + if (cause instanceof SSLException) { + response.setStatus(-2); + response.setErrorMessage("TLS connection could not be established: " + e.getMessage()); + Log.w(TAG, "TLS connection could not be established", e); + } else if (cause instanceof UnknownHostException) { + response.setStatus(-3); + response.setErrorMessage("Host could not be resolved: " + e.getMessage()); + Log.w(TAG, "Host could not be resolved", e); + } else if (cause instanceof SocketTimeoutException) { + response.setStatus(-4); + response.setErrorMessage("Request timed out: " + e.getMessage()); + Log.w(TAG, "Request timed out", e); + } else if (cause instanceof InterruptedIOException && "thread interrupted".equals(message.toLowerCase())) { + this.setAborted(request, response); + } else { + response.setStatus(-1); + response.setErrorMessage("There was an error with the request: " + message); + Log.w(TAG, "Generic request error", e); + } + } catch (InterruptedException ie) { + this.setAborted(request, response); + } catch (Exception e) { + response.setStatus(-1); + response.setErrorMessage(e.getMessage()); + Log.e(TAG, "An unexpected error occured", e); + } + + try { + if (response.hasFailed()) { + this.callbackContext.error(response.toJSON()); + } else { + this.callbackContext.success(response.toJSON()); + } + } catch (JSONException e) { + Log.e(TAG, "An unexpected error occured while creating HTTP response object", e); + } + } + + protected HttpRequest createRequest() throws JSONException { + return new HttpRequest(this.url, this.method); + } + + protected void prepareRequest(HttpRequest request) throws JSONException, IOException { + request.followRedirects(this.followRedirects); + request.connectTimeout(this.connectTimeout); + request.readTimeout(this.readTimeout); + request.acceptCharset("UTF-8"); + request.uncompress(true); + + if (this.tlsConfiguration.getHostnameVerifier() != null) { + request.setHostnameVerifier(this.tlsConfiguration.getHostnameVerifier()); + } + + request.setSSLSocketFactory(this.tlsConfiguration.getTLSSocketFactory()); + + // setup content type before applying headers, so user can override it + this.setContentType(request); + + request.headers(JsonUtils.getStringMap(this.headers)); + } + + protected void setContentType(HttpRequest request) { + if ("json".equals(this.serializer)) { + request.contentType("application/json", "UTF-8"); + } else if ("utf8".equals(this.serializer)) { + request.contentType("text/plain", "UTF-8"); + } else if ("raw".equals(this.serializer)) { + request.contentType("application/octet-stream"); + } else if ("urlencoded".equals(this.serializer)) { + // intentionally left blank, because content type is set in HttpRequest.form() + } else if ("multipart".equals(this.serializer)) { + // intentionally left blank, because content type is set in HttpRequest.part() + } + } + + protected void sendBody(HttpRequest request) throws Exception { + if (this.data == null) { + return; + } + + if ("json".equals(this.serializer)) { + request.send(this.data.toString()); + } else if ("utf8".equals(this.serializer)) { + request.send(((JSONObject) this.data).getString("text")); + } else if ("raw".equals(this.serializer)) { + request.send(Base64.decode((String)this.data, Base64.DEFAULT)); + } else if ("urlencoded".equals(this.serializer)) { + request.form(JsonUtils.getObjectMap((JSONObject) this.data)); + } else if ("multipart".equals(this.serializer)) { + JSONArray buffers = ((JSONObject) this.data).getJSONArray("buffers"); + JSONArray names = ((JSONObject) this.data).getJSONArray("names"); + JSONArray fileNames = ((JSONObject) this.data).getJSONArray("fileNames"); + JSONArray types = ((JSONObject) this.data).getJSONArray("types"); + + for (int i = 0; i < buffers.length(); ++i) { + byte[] bytes = Base64.decode(buffers.getString(i), Base64.DEFAULT); + String name = names.getString(i); + + if (fileNames.isNull(i)) { + request.part(name, new String(bytes, "UTF-8")); + } else { + request.part(name, fileNames.getString(i), types.getString(i), new ByteArrayInputStream(bytes)); + } + } + + // prevent sending malformed empty multipart requests (#372) + if (buffers.length() == 0) { + request.contentType("multipart/form-data; boundary=00content0boundary00"); + request.send("\r\n--00content0boundary00--\r\n"); + } + } + } + + protected void processResponse(HttpRequest request, NativeHttpResponse response) throws Exception { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + request.receive(outputStream); + + response.setStatus(request.code()); + response.setUrl(request.url().toString()); + response.setHeaders(request.headers()); + + if (request.code() >= 200 && request.code() < 300) { + if ("text".equals(this.responseType) || "json".equals(this.responseType)) { + String decoded = HttpBodyDecoder.decodeBody(outputStream.toByteArray(), request.charset()); + response.setBody(decoded); + } else { + response.setData(outputStream.toByteArray()); + } + } else { + response.setErrorMessage(HttpBodyDecoder.decodeBody(outputStream.toByteArray(), request.charset())); + } + } + + protected void setAborted(HttpRequest request, NativeHttpResponse response) { + response.setStatus(-8); + response.setErrorMessage("Request was aborted"); + + if (request != null) { + try { + request.disconnect(); + } catch(Exception any){ + Log.w(TAG, "Failed to close aborted request", any); + } + } + + Log.i(TAG, "Request was aborted"); + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpDownload.java b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpDownload.java new file mode 100644 index 0000000000..223bfa558a --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpDownload.java @@ -0,0 +1,38 @@ +package com.foxdebug.acode.http; + +import java.io.File; +import java.net.URI; + +import com.silkimen.http.HttpRequest; +import com.silkimen.http.TLSConfiguration; + +import com.foxdebug.acode.file.FileUtils; +import org.json.JSONObject; + +class NativeHttpDownload extends NativeHttpBase { + private String filePath; + + public NativeHttpDownload(String url, JSONObject headers, String filePath, int connectTimeout, int readTimeout, + boolean followRedirects, TLSConfiguration tlsConfiguration, NativeObservableCallbackContext callbackContext) { + + super("GET", url, headers, connectTimeout, readTimeout, followRedirects, "text", tlsConfiguration, callbackContext); + this.filePath = filePath; + } + + @Override + protected void processResponse(HttpRequest request, NativeHttpResponse response) throws Exception { + response.setStatus(request.code()); + response.setUrl(request.url().toString()); + response.setHeaders(request.headers()); + + if (request.code() >= 200 && request.code() < 300) { + File file = new File(new URI(this.filePath)); + JSONObject fileEntry = FileUtils.getFilePlugin().getEntryForFile(file); + + request.receive(file); + response.setFileEntry(fileEntry); + } else { + response.setErrorMessage("There was an error downloading the file"); + } + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpOperation.java b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpOperation.java new file mode 100644 index 0000000000..9b97e5384d --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpOperation.java @@ -0,0 +1,21 @@ +package com.foxdebug.acode.http; + +import com.silkimen.http.TLSConfiguration; + +import org.json.JSONObject; + +class NativeHttpOperation extends NativeHttpBase { + public NativeHttpOperation(String method, String url, String serializer, Object data, JSONObject headers, + int connectTimeout, int readTimeout, boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration, + NativeObservableCallbackContext callbackContext) { + + super(method, url, serializer, data, headers, connectTimeout, readTimeout, followRedirects, responseType, tlsConfiguration, + callbackContext); + } + + public NativeHttpOperation(String method, String url, JSONObject headers, int connectTimeout, int readTimeout, boolean followRedirects, + String responseType, TLSConfiguration tlsConfiguration, NativeObservableCallbackContext callbackContext) { + + super(method, url, headers, connectTimeout, readTimeout, followRedirects, responseType, tlsConfiguration, callbackContext); + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpPlugin.java b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpPlugin.java new file mode 100644 index 0000000000..16f764234d --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpPlugin.java @@ -0,0 +1,298 @@ +package com.foxdebug.acode.http; + +import java.security.KeyStore; +import java.util.HashMap; +import java.util.Observable; +import java.util.Observer; +import java.util.concurrent.Future; + +import com.silkimen.http.TLSConfiguration; + +import com.foxdebug.acode.runtime.BridgeContext; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Service; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import android.content.Context; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.util.Log; +import android.util.Base64; + +import javax.net.ssl.TrustManagerFactory; + +public class NativeHttpPlugin extends Service implements Observer { + private static final String TAG = "Native-Plugin-HTTP"; + + private TLSConfiguration tlsConfiguration; + + private HashMap<Integer, Future<?>> reqMap; + private final Object reqMapLock = new Object(); + + @Override + public void initialize(BridgeContext bridgeContext) { + super.initialize(bridgeContext); + + this.tlsConfiguration = new TLSConfiguration(); + + this.reqMap = new HashMap<Integer, Future<?>>(); + + try { + KeyStore store = KeyStore.getInstance("AndroidCAStore"); + String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); + TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); + + store.load(null); + tmf.init(store); + + this.tlsConfiguration.setHostnameVerifier(null); + this.tlsConfiguration.setTrustManagers(tmf.getTrustManagers()); + + if (this.preferences.contains("androidblacklistsecuresocketprotocols")) { + this.tlsConfiguration.setBlacklistedProtocols( + this.preferences.getString("androidblacklistsecuresocketprotocols", "").split(",") + ); + } + + } catch (Exception e) { + Log.e(TAG, "An error occured while loading system's CA certificates", e); + } + } + + @Override + public boolean execute(String action, final JSONArray args, final Callback callbackContext) + throws JSONException { + + if (action == null) { + return false; + } + + if ("setServerTrustMode".equals(action)) { + return this.setServerTrustMode(args, callbackContext); + } else if ("setClientAuthMode".equals(action)) { + return this.setClientAuthMode(args, callbackContext); + } else if ("abort".equals(action)) { + return this.abort(args, callbackContext); + } + + boolean isLocal = false; + try { + if (args != null && args.length() > 0) { + String urlString = args.getString(0); + if (urlString != null) { + try { + java.net.URL url = new java.net.URL(urlString); + String host = url.getHost(); + if (host != null) { + host = host.toLowerCase().trim(); + if (host.equals("localhost") || host.equals("127.0.0.1") || host.equals("[::1]") || host.equals("::1") || host.startsWith("127.")) { + isLocal = true; + } + } + } catch (Exception e) { + String lower = urlString.toLowerCase(); + if (lower.contains("://localhost") || lower.contains("://127.0.0.1") || lower.contains("://[::1]") || lower.contains("://127.")) { + isLocal = true; + } + } + } + } + } catch (Exception e) { + // ignore + } + + if (!isLocal && !isNetworkAvailable()) { + NativeHttpResponse response = new NativeHttpResponse(); + response.setStatus(-6); + response.setErrorMessage("No network connection available"); + callbackContext.error(response.toJSON()); + + return true; + } + + if ("get".equals(action)) { + return this.executeHttpRequestWithoutData(action, args, callbackContext); + } else if ("head".equals(action)) { + return this.executeHttpRequestWithoutData(action, args, callbackContext); + } else if ("delete".equals(action)) { + return this.executeHttpRequestWithoutData(action, args, callbackContext); + } else if ("options".equals(action)) { + return this.executeHttpRequestWithoutData(action, args, callbackContext); + } else if ("post".equals(action)) { + return this.executeHttpRequestWithData(action, args, callbackContext); + } else if ("put".equals(action)) { + return this.executeHttpRequestWithData(action, args, callbackContext); + } else if ("patch".equals(action)) { + return this.executeHttpRequestWithData(action, args, callbackContext); + } else if ("uploadFiles".equals(action)) { + return this.uploadFiles(args, callbackContext); + } else if ("downloadFile".equals(action)) { + return this.downloadFile(args, callbackContext); + } else { + return false; + } + } + + private boolean executeHttpRequestWithoutData(final String method, final JSONArray args, + final Callback callbackContext) throws JSONException { + + String url = args.getString(0); + JSONObject headers = args.getJSONObject(1); + int connectTimeout = args.getInt(2) * 1000; + int readTimeout = args.getInt(3) * 1000; + boolean followRedirect = args.getBoolean(4); + String responseType = args.getString(5); + Integer reqId = args.getInt(6); + + NativeObservableCallbackContext observableCallbackContext = new NativeObservableCallbackContext(callbackContext, reqId); + + NativeHttpOperation request = new NativeHttpOperation(method.toUpperCase(), url, headers, connectTimeout, readTimeout, + followRedirect, responseType, this.tlsConfiguration, observableCallbackContext); + + startRequest(reqId, observableCallbackContext, request); + + return true; + } + + private boolean executeHttpRequestWithData(final String method, final JSONArray args, + final Callback callbackContext) throws JSONException { + + String url = args.getString(0); + Object data = args.get(1); + String serializer = args.getString(2); + JSONObject headers = args.getJSONObject(3); + int connectTimeout = args.getInt(4) * 1000; + int readTimeout = args.getInt(5) * 1000; + boolean followRedirect = args.getBoolean(6); + String responseType = args.getString(7); + Integer reqId = args.getInt(8); + + NativeObservableCallbackContext observableCallbackContext = new NativeObservableCallbackContext(callbackContext, reqId); + + NativeHttpOperation request = new NativeHttpOperation(method.toUpperCase(), url, serializer, data, headers, + connectTimeout, readTimeout, followRedirect, responseType, this.tlsConfiguration, observableCallbackContext); + + startRequest(reqId, observableCallbackContext, request); + + return true; + } + + private boolean uploadFiles(final JSONArray args, final Callback callbackContext) throws JSONException { + String url = args.getString(0); + JSONObject headers = args.getJSONObject(1); + JSONArray filePaths = args.getJSONArray(2); + JSONArray uploadNames = args.getJSONArray(3); + int connectTimeout = args.getInt(4) * 1000; + int readTimeout = args.getInt(5) * 1000; + boolean followRedirect = args.getBoolean(6); + String responseType = args.getString(7); + Integer reqId = args.getInt(8); + + NativeObservableCallbackContext observableCallbackContext = new NativeObservableCallbackContext(callbackContext, reqId); + + NativeHttpUpload upload = new NativeHttpUpload(url, headers, filePaths, uploadNames, connectTimeout, readTimeout, followRedirect, + responseType, this.tlsConfiguration, this.host.getActivity().getApplicationContext(), observableCallbackContext); + + startRequest(reqId, observableCallbackContext, upload); + + return true; + } + + private boolean downloadFile(final JSONArray args, final Callback callbackContext) throws JSONException { + String url = args.getString(0); + JSONObject headers = args.getJSONObject(1); + String filePath = args.getString(2); + int connectTimeout = args.getInt(3) * 1000; + int readTimeout = args.getInt(4) * 1000; + boolean followRedirect = args.getBoolean(5); + Integer reqId = args.getInt(6); + + NativeObservableCallbackContext observableCallbackContext = new NativeObservableCallbackContext(callbackContext, reqId); + + NativeHttpDownload download = new NativeHttpDownload(url, headers, filePath, connectTimeout, readTimeout, + followRedirect, this.tlsConfiguration, observableCallbackContext); + + startRequest(reqId, observableCallbackContext, download); + + return true; + } + + private void startRequest(Integer reqId, NativeObservableCallbackContext observableCallbackContext, NativeHttpBase request) { + synchronized (reqMapLock) { + observableCallbackContext.setObserver(this); + Future<?> task = host.getThreadPool().submit(request); + this.addReq(reqId, task, observableCallbackContext); + } + } + + private boolean setServerTrustMode(final JSONArray args, final Callback callbackContext) throws JSONException { + NativeServerTrust runnable = new NativeServerTrust(args.getString(0), this.host.getActivity(), + this.tlsConfiguration, callbackContext); + + host.getThreadPool().execute(runnable); + + return true; + } + + private boolean setClientAuthMode(final JSONArray args, final Callback callbackContext) throws JSONException { + byte[] pkcs = args.isNull(2) ? null : Base64.decode(args.getString(2), Base64.DEFAULT); + + NativeClientAuth runnable = new NativeClientAuth(args.getString(0), args.isNull(1) ? null : args.getString(1), + pkcs, args.getString(3), this.host.getActivity(), this.host.getActivity().getApplicationContext(), + this.tlsConfiguration, callbackContext); + + host.getThreadPool().execute(runnable); + + return true; + } + + private boolean abort(final JSONArray args, final Callback callbackContext) throws JSONException { + int reqId = args.getInt(0); + boolean result = false; + // NOTE no synchronized (reqMapLock), since even if the req was already removed from reqMap, + // the worst that would happen calling task.cancel(true) is a result of false + // (i.e. same result as locking & not finding the req in reqMap) + Future<?> task = this.reqMap.get(reqId); + + if (task != null && !task.isDone()) { + result = task.cancel(true); + } + + callbackContext.success(new JSONObject().put("aborted", result)); + + return true; + } + + private void addReq(final Integer reqId, final Future<?> task, final NativeObservableCallbackContext observableCallbackContext) { + synchronized (reqMapLock) { + if (!task.isDone()){ + this.reqMap.put(reqId, task); + } + } + } + + private void removeReq(final Integer reqId) { + synchronized (reqMapLock) { + this.reqMap.remove(reqId); + } + } + + @Override + public void update(Observable o, Object arg) { + synchronized (reqMapLock) { + NativeObservableCallbackContext c = (NativeObservableCallbackContext) arg; + if (c.getCallbackContext().isFinished()) { + removeReq(c.getRequestId()); + } + } + } + + private boolean isNetworkAvailable() { + ConnectivityManager connectivityManager = (ConnectivityManager) host.getContext().getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); + + return activeNetworkInfo != null && activeNetworkInfo.isConnected(); + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpResponse.java b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpResponse.java new file mode 100644 index 0000000000..4f3e8bf815 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpResponse.java @@ -0,0 +1,100 @@ +package com.foxdebug.acode.http; + +import java.nio.ByteBuffer; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.json.JSONException; +import org.json.JSONObject; + +import android.text.TextUtils; +import android.util.Log; +import android.util.Base64; + +class NativeHttpResponse { + private int status; + private String url; + private Map<String, List<String>> headers; + private String body; + private byte[] rawData; + private JSONObject fileEntry; + private boolean hasFailed; + private boolean isFileOperation; + private boolean isRawResponse; + private String error; + + public void setStatus(int status) { + this.status = status; + } + + public void setUrl(String url) { + this.url = url; + } + + public void setHeaders(Map<String, List<String>> headers) { + this.headers = headers; + } + + public void setBody(String body) { + this.body = body; + } + + public void setData(byte[] rawData) { + this.isRawResponse = true; + this.rawData = rawData; + } + + public void setFileEntry(JSONObject entry) { + this.isFileOperation = true; + this.fileEntry = entry; + } + + public void setErrorMessage(String message) { + this.hasFailed = true; + this.error = message; + } + + public boolean hasFailed() { + return this.hasFailed; + } + + public JSONObject toJSON() throws JSONException { + JSONObject json = new JSONObject(); + + json.put("status", this.status); + json.put("url", this.url); + + if (this.headers != null && !this.headers.isEmpty()) { + json.put("headers", new JSONObject(getFilteredHeaders())); + } + + if (this.hasFailed) { + json.put("error", this.error); + } else if (this.isFileOperation) { + json.put("file", this.fileEntry); + } else if (this.isRawResponse) { + json.put("data", Base64.encodeToString(this.rawData, Base64.DEFAULT)); + } else { + json.put("data", this.body); + } + + return json; + } + + private Map<String, String> getFilteredHeaders() throws JSONException { + Map<String, String> filteredHeaders = new HashMap<String, String>(); + + for (Map.Entry<String, List<String>> entry : this.headers.entrySet()) { + String key = entry.getKey(); + List<String> value = entry.getValue(); + + if ((key != null) && (!value.isEmpty())) { + filteredHeaders.put(key.toLowerCase(), TextUtils.join(", ", value)); + } + } + + return filteredHeaders; + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpUpload.java b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpUpload.java new file mode 100644 index 0000000000..a13178d6d5 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeHttpUpload.java @@ -0,0 +1,88 @@ +package com.foxdebug.acode.http; + +import android.content.ContentResolver; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.provider.OpenableColumns; +import android.webkit.MimeTypeMap; + +import com.silkimen.http.HttpRequest; +import com.silkimen.http.TLSConfiguration; + +import java.io.File; +import java.io.InputStream; +import java.net.URI; + +import org.json.JSONArray; +import org.json.JSONObject; + +class NativeHttpUpload extends NativeHttpBase { + private JSONArray filePaths; + private JSONArray uploadNames; + private Context applicationContext; + + public NativeHttpUpload(String url, JSONObject headers, JSONArray filePaths, JSONArray uploadNames, int connectTimeout, int readTimeout, + boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration, + Context applicationContext, NativeObservableCallbackContext callbackContext) { + + super("POST", url, headers, connectTimeout, readTimeout, followRedirects, responseType, tlsConfiguration, callbackContext); + this.filePaths = filePaths; + this.uploadNames = uploadNames; + this.applicationContext = applicationContext; + } + + @Override + protected void sendBody(HttpRequest request) throws Exception { + for (int i = 0; i < this.filePaths.length(); ++i) { + String uploadName = this.uploadNames.getString(i); + String filePath = this.filePaths.getString(i); + + Uri fileUri = Uri.parse(filePath); + + // File Scheme + if (ContentResolver.SCHEME_FILE.equals(fileUri.getScheme())) { + File file = new File(new URI(filePath)); + String fileName = file.getName().trim(); + String mimeType = this.getMimeTypeFromFileName(fileName); + + request.part(uploadName, fileName, mimeType, file); + } + + // Content Scheme + if (ContentResolver.SCHEME_CONTENT.equals(fileUri.getScheme())) { + InputStream inputStream = this.applicationContext.getContentResolver().openInputStream(fileUri); + String fileName = this.getFileNameFromContentScheme(fileUri, this.applicationContext).trim(); + String mimeType = this.getMimeTypeFromFileName(fileName); + + request.part(uploadName, fileName, mimeType, inputStream); + } + } + } + + private String getFileNameFromContentScheme(Uri contentSchemeUri, Context applicationContext) { + Cursor returnCursor = applicationContext.getContentResolver().query(contentSchemeUri, null, null, null, null); + + if (returnCursor == null || !returnCursor.moveToFirst()) { + return null; + } + + int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); + String fileName = returnCursor.getString(nameIndex); + returnCursor.close(); + + return fileName; + } + + private String getMimeTypeFromFileName(String fileName) { + if (fileName == null || !fileName.contains(".")) { + return null; + } + + MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); + int extIndex = fileName.lastIndexOf('.') + 1; + String extension = fileName.substring(extIndex).toLowerCase(); + + return mimeTypeMap.getMimeTypeFromExtension(extension); + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeObservableCallbackContext.java b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeObservableCallbackContext.java new file mode 100644 index 0000000000..c40f238828 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeObservableCallbackContext.java @@ -0,0 +1,58 @@ +package com.foxdebug.acode.http; + +import com.foxdebug.acode.runtime.Callback; +import org.json.JSONObject; + +import java.util.Observer; + +public class NativeObservableCallbackContext { + + private Callback callbackContext; + private Integer requestId; + private Observer observer; + + public NativeObservableCallbackContext(Callback callbackContext, Integer requestId) { + this.callbackContext = callbackContext; + this.requestId = requestId; + } + + public void success(JSONObject message) { + this.callbackContext.success(message); + this.notifyObserver(); + } + + public void error(JSONObject message) { + this.callbackContext.error(message); + this.notifyObserver(); + } + + public Integer getRequestId() { + return this.requestId; + } + + public Callback getCallbackContext() { + return callbackContext; + } + + public Observer getObserver() { + return observer; + } + + protected void notifyObserver() { + if(this.observer != null){ + this.observer.update(null, this); + } + } + + /** + * Set an observer that is notified, when {@link #success(JSONObject)} + * or {@link #error(JSONObject)} are called. + * + * NOTE the observer is notified with + * <pre>observer.update(null, BridgeObservableCallbackContext)</pre> + * @param observer + */ + public void setObserver(Observer observer) { + this.observer = observer; + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeServerTrust.java b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeServerTrust.java new file mode 100644 index 0000000000..27b578e2d3 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/http/NativeServerTrust.java @@ -0,0 +1,124 @@ +package com.foxdebug.acode.http; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + +import com.silkimen.http.TLSConfiguration; + +import com.foxdebug.acode.runtime.Callback; + +import android.app.Activity; +import android.util.Log; +import android.content.res.AssetManager; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +class NativeServerTrust implements Runnable { + private static final String TAG = "Native-Plugin-HTTP"; + + private final TrustManager[] noOpTrustManagers; + private final HostnameVerifier noOpVerifier; + + private String mode; + private Activity activity; + private TLSConfiguration tlsConfiguration; + private Callback callbackContext; + + public NativeServerTrust(final String mode, final Activity activity, final TLSConfiguration configContainer, + final Callback callbackContext) { + + this.mode = mode; + this.activity = activity; + this.tlsConfiguration = configContainer; + this.callbackContext = callbackContext; + + this.noOpTrustManagers = new TrustManager[] { new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + public void checkClientTrusted(X509Certificate[] chain, String authType) { + // intentionally left blank + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) { + // intentionally left blank + } + } }; + + this.noOpVerifier = new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + } + + @Override + public void run() { + try { + if ("legacy".equals(this.mode)) { + this.tlsConfiguration.setHostnameVerifier(null); + this.tlsConfiguration.setTrustManagers(null); + } else if ("nocheck".equals(this.mode)) { + this.tlsConfiguration.setHostnameVerifier(this.noOpVerifier); + this.tlsConfiguration.setTrustManagers(this.noOpTrustManagers); + } else if ("pinned".equals(this.mode)) { + this.tlsConfiguration.setHostnameVerifier(null); + this.tlsConfiguration.setTrustManagers(this.getTrustManagers(this.getCertsFromBundle("bundle/certificates"))); + } else { + this.tlsConfiguration.setHostnameVerifier(null); + this.tlsConfiguration.setTrustManagers(this.getTrustManagers(this.getCertsFromKeyStore("AndroidCAStore"))); + } + + callbackContext.success(); + } catch (Exception e) { + Log.e(TAG, "An error occured while configuring SSL cert mode", e); + callbackContext.error("An error occured while configuring SSL cert mode"); + } + } + + private TrustManager[] getTrustManagers(KeyStore store) throws GeneralSecurityException { + String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); + TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); + tmf.init(store); + + return tmf.getTrustManagers(); + } + + private KeyStore getCertsFromBundle(String path) throws GeneralSecurityException, IOException { + AssetManager assetManager = this.activity.getAssets(); + String[] files = assetManager.list(path); + + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + String keyStoreType = KeyStore.getDefaultType(); + KeyStore keyStore = KeyStore.getInstance(keyStoreType); + + keyStore.load(null, null); + + for (int i = 0; i < files.length; i++) { + int index = files[i].lastIndexOf('.'); + + if (index == -1 || !files[i].substring(index).equals(".cer")) { + continue; + } + + keyStore.setCertificateEntry("CA" + i, cf.generateCertificate(assetManager.open(path + "/" + files[i]))); + } + + return keyStore; + } + + private KeyStore getCertsFromKeyStore(String storeType) throws GeneralSecurityException, IOException { + KeyStore store = KeyStore.getInstance(storeType); + store.load(null); + + return store; + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/App.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/App.kt new file mode 100644 index 0000000000..91754302a0 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/App.kt @@ -0,0 +1,105 @@ +package com.foxdebug.acode.runtime + +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import androidx.core.app.ActivityCompat +import org.json.JSONArray +import org.json.JSONException +import java.util.concurrent.ExecutorService + +class App : Service() { + private lateinit var bridgeContext: BridgeContext + + override fun initialize(bridgeContext: BridgeContext) { + super.initialize(bridgeContext) + this.bridgeContext = bridgeContext + } + + @Throws(JSONException::class) + override fun execute(action: String, args: JSONArray, callback: Callback): Boolean { + val webView = bridgeContext.webView + when (action) { + "exitApp" -> host!!.activity.runOnUiThread(Runnable { host!!.activity.finish() }) + "overrideButton" -> host!!.activity + .overrideButton(args.getString(0), args.getBoolean(1)) + + "clearCache" -> webView.post(Runnable { webView.clearCache(true) }) + "clearHistory" -> webView.post(Runnable { webView.clearHistory() }) + "backHistory" -> webView.post(Runnable { webView.goBack() }) + else -> return false + } + callback.success() + return true + } +} + +class Host(val activity: BaseWebActivity) { + val preferences: Preferences = Preferences() + private val permissionRequests: MutableMap<Int?, Request?> = HashMap<Int?, Request?>() + private val activityRequests: MutableMap<Int?, Request?> = HashMap<Int?, Request?>() + private var requestId = 40000 + + init { + preferences.set("AndroidPersistentFileLocation", "Compatibility") + preferences.set("AndroidBlacklistSecureSocketProtocols", "SSLv3,TLSv1") + preferences.set("scheme", "https") + preferences.set("hostname", "localhost") + preferences.set("BackgroundColor", -0xcececf) + } + + val context: Context + get() = activity + + val threadPool: ExecutorService? + get() = RuntimeBaseApplication.instance!!.threadPool + + fun hasPermission(permission: String): Boolean { + return (ActivityCompat.checkSelfPermission(activity, permission) == + PackageManager.PERMISSION_GRANTED + ) + } + + fun requestPermission(service: Service, code: Int, permission: String?) { + requestPermissions(service, code, arrayOf<String?>(permission)) + } + + fun requestPermissions( + service: Service, + code: Int, + permissions: Array<String?> + ) { + activity.runOnUiThread(Runnable { + val id = requestId++ + permissionRequests[id] = Request(service, code) + ActivityCompat.requestPermissions(activity, permissions, id) + }) + } + + fun startActivityForResult(service: Service, intent: Intent, code: Int) { + activity.runOnUiThread(Runnable { + val id = requestId++ + activityRequests[id] = Request(service, code) + activity.startActivityForResult(intent, id) + }) + } + + @Throws(JSONException::class) + fun onPermissionsResult(id: Int, permissions: Array<String?>?, grants: IntArray?): Boolean { + val request = permissionRequests.remove(id) ?: return false + request.service.onRequestPermissionResult( + request.code, + permissions, + grants + ) + return true + } + + fun onActivityResult(id: Int, result: Int, data: Intent?): Boolean { + val request = activityRequests.remove(id) ?: return false + request.service.onActivityResult(request.code, result, data) + return true + } + + private class Request(val service: Service, val code: Int) +} \ No newline at end of file diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/BaseWebActivity.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/BaseWebActivity.kt new file mode 100644 index 0000000000..282ae6e5d1 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/BaseWebActivity.kt @@ -0,0 +1,242 @@ +package com.foxdebug.acode.runtime + +import android.annotation.SuppressLint +import android.content.Context +import android.content.Intent +import android.content.res.Configuration +import android.os.Bundle +import android.util.Log +import android.view.Gravity +import android.view.KeyEvent +import android.view.View +import android.webkit.CookieManager +import android.webkit.WebView +import android.widget.FrameLayout +import androidx.activity.OnBackPressedCallback +import androidx.activity.OnBackPressedDispatcher +import androidx.appcompat.app.AppCompatActivity +import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen +import androidx.core.view.OnApplyWindowInsetsListener +import androidx.core.view.ViewCompat +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import com.foxdebug.acode.BuildConfig +import com.foxdebug.acode.runtime.webview.AppWebView +import com.foxdebug.acode.runtime.webview.AcodeChromeClient +import com.foxdebug.acode.runtime.webview.AcodeWebViewClient +import org.json.JSONException +import java.lang.ref.WeakReference +import java.util.concurrent.ConcurrentHashMap +import kotlin.math.max + +open class BaseWebActivity : AppCompatActivity() { + private var appWebView: AppWebView? = null + private var host: Host? = null + private var bridge: Bridge? = null + private var acodeChromeClient: AcodeChromeClient? = null + private var content: FrameLayout? = null + private var hasPaused = false + private val overriddenButtons: MutableSet<String?> = ConcurrentHashMap.newKeySet<String?>() + + @SuppressLint("SetJavaScriptEnabled") + public override fun onCreate(state: Bundle?) { + installSplashScreen() + super.onCreate(state) + context = WeakReference<Context?>(this) + WindowCompat.setDecorFitsSystemWindows(window, false) + host = Host(this) + content = FrameLayout(this) + appWebView = AppWebView(this) + bridge = Bridge(appWebView!!,this) + appWebView!!.initialize(bridge!!) + acodeChromeClient = AcodeChromeClient(this, appWebView!!) + appWebView!!.webViewClient = AcodeWebViewClient(this, bridge!!) + appWebView!!.webChromeClient = acodeChromeClient!! + appWebView!!.setFullscreenController(acodeChromeClient!!) + appWebView!!.addJavascriptInterface(bridge!!, "Android") + appWebView!!.isVerticalScrollBarEnabled = false + appWebView!!.settings.javaScriptEnabled = true + appWebView!!.settings.javaScriptCanOpenWindowsAutomatically = true + appWebView!!.settings.setSaveFormData(false) + appWebView!!.settings.setGeolocationEnabled(true) + CookieManager.getInstance().setAcceptThirdPartyCookies( + appWebView, + true + ) + appWebView!!.settings.domStorageEnabled = true + appWebView!!.settings.setDatabaseEnabled(true) + appWebView!!.settings.allowFileAccess = true + appWebView!!.settings.allowContentAccess = true + appWebView!!.settings.mediaPlaybackRequiresUserGesture = false + appWebView!!.overScrollMode = View.OVER_SCROLL_NEVER + appWebView!!.setBackgroundColor(-0xcececf) + WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG) + content!!.addView(appWebView, FrameLayout.LayoutParams(-1, -1)) + val statusBar = View(this) + statusBar.tag = "statusBarView" + content!!.addView(statusBar) + setContentView(content) + ViewCompat.setOnApplyWindowInsetsListener( + content!!, + OnApplyWindowInsetsListener { view: View?, insets: WindowInsetsCompat? -> + val bars = insets!!.getInsets( + WindowInsetsCompat.Type.systemBars() or + WindowInsetsCompat.Type.displayCutout() + ) + val keyboard = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom + val fullscreen = acodeChromeClient!!.isFullscreen + val top = + if (!fullscreen && statusBar.visibility != View.GONE) bars.top else 0 + val params = + appWebView!!.layoutParams as FrameLayout.LayoutParams + val left = if (fullscreen) 0 else bars.left + val right = if (fullscreen) 0 else bars.right + val bottom = if (fullscreen) 0 else max(bars.bottom, keyboard) + if (params.leftMargin != left || params.topMargin != top || params.rightMargin != right || params.bottomMargin != bottom + ) { + params.setMargins(left, top, right, bottom) + appWebView!!.layoutParams = params + } + statusBar.layoutParams = FrameLayout.LayoutParams(-1, top, Gravity.TOP) + insets + }) + + OnBackPressedDispatcher().addCallback( + this, + object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() { + dispatchBack() + } + } + ) + bridge!!.initialize() + appWebView!!.loadUrl("https://localhost/index.html") + } + + fun overrideButton(button: String, enabled: Boolean) { + var button = button + if (button == "volumeup" || button == "volumedown") button += + "button" + if (enabled) overriddenButtons.add(button) + else overriddenButtons.remove(button) + } + + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + if (appWebView == null) return super.dispatchKeyEvent(event) + val code = event.keyCode + if (code == KeyEvent.KEYCODE_BACK && + (acodeChromeClient!!.isFullscreen || overriddenButtons.contains("backbutton")) + ) { + if (event.action == KeyEvent.ACTION_UP) dispatchBack() + return true + } + val name = + if (code == KeyEvent.KEYCODE_MENU) + "menubutton" + else + if (code == KeyEvent.KEYCODE_VOLUME_UP) + "volumeupbutton" + else + if (code == KeyEvent.KEYCODE_VOLUME_DOWN) + "volumedownbutton" + else + null + if (name != null && overriddenButtons.contains(name)) { + if (event.action == KeyEvent.ACTION_UP + ) appWebView!!.fireDocumentEvent(name) + return true + } + return super.dispatchKeyEvent(event) + } + + private fun dispatchBack() { + if (acodeChromeClient!!.handleBack()) return + if (overriddenButtons.contains("backbutton")) appWebView!!.fireDocumentEvent( + "backbutton" + ) + else if (appWebView!!.canGoBack()) appWebView!!.goBack() + else finish() + } + + fun getHost(): Host { + return host!! + } + + val contentView: FrameLayout + get() = content!! + + override fun onConfigurationChanged( + configuration: Configuration + ) { + super.onConfigurationChanged(configuration) + for (service in bridge!!.activeServices) service.onConfigurationChanged(configuration) + } + + public override fun onNewIntent(intent: Intent?) { + super.onNewIntent(intent) + setIntent(intent) + for (service in bridge!!.activeServices) service.onNewIntent(intent) + } + + override fun onPause() { + super.onPause() + if (appWebView == null) return + hasPaused = true + appWebView!!.fireDocumentEvent("pause") + for (service in bridge!!.activeServices) service.onPause(true) + acodeChromeClient!!.pause() + } + + override fun onResume() { + super.onResume() + if (appWebView == null) return + appWebView!!.onResume() + appWebView!!.resumeTimers() + acodeChromeClient!!.resume() + for (service in bridge!!.activeServices) service.onResume(true) + if (hasPaused) appWebView!!.fireDocumentEvent("resume") + } + + override fun onActivityResult(code: Int, result: Int, data: Intent?) { + super.onActivityResult(code, result, data) + if (!host!!.onActivityResult(code, result, data)) { + for (service in bridge!!.activeServices) service.onActivityResult(code, result, data) + } + } + + override fun onRequestPermissionsResult( + code: Int, + permissions: Array<String?>, + grants: IntArray + ) { + super.onRequestPermissionsResult(code, permissions, grants) + try { + if (!host!!.onPermissionsResult(code, permissions, grants)) { + for (service in bridge!!.activeServices) service.onRequestPermissionResult( + code, + permissions, + grants + ) + } + } catch (exception: JSONException) { + Log.e("Acode", "Permission callback failed", exception) + } + } + + override fun onDestroy() { + if (bridge != null) bridge!!.destroy() + if (acodeChromeClient != null) acodeChromeClient!!.reset() + if (appWebView != null) { + content!!.removeView(appWebView) + appWebView!!.destroy() + } + super.onDestroy() + } + + companion object { + private var context: WeakReference<Context?>? = null + fun getContext(): Context? { + return if (context == null) null else context!!.get() + } + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Bridge.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Bridge.kt new file mode 100644 index 0000000000..8aabd9b870 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Bridge.kt @@ -0,0 +1,112 @@ +package com.foxdebug.acode.runtime + +import android.net.Uri +import android.util.Log +import android.webkit.JavascriptInterface +import com.foxdebug.acode.runtime.RuntimeBaseApplication.Companion.instance +import com.foxdebug.acode.runtime.webview.AppWebView +import kotlin.collections.LinkedHashMap + +data class BridgeContext(val webView: AppWebView,val webActivity: BaseWebActivity) + +class Bridge(private val webView: AppWebView, private val webActivity: BaseWebActivity) { + private val definitions: Map<ServiceName, ServiceDefinition> = + ServiceRegistry.definitions.associateBy { definition -> definition.name } + + private val definitionsByKey: Map<String, ServiceDefinition> = + ServiceRegistry.definitions.associateBy { definition -> definition.name.key } + + private val services: MutableMap<String, Service> = LinkedHashMap() + + @Volatile + var generation: Long = 0 + private set + + /** Services created so far, in the order they were requested. */ + val activeServices: List<Service> + get() = services.values.toList() + + fun initialize() { + definitions.values + .filter { definition -> definition.loadOnStart } + .forEach { definition -> getService(definition) } + } + + @Synchronized + fun getService(definition: ServiceDefinition): Service { + return services.getOrPut(definition.name.key) { + definition.factory.create().also { service -> + service.initialize(BridgeContext(webView, webActivity)) + service.serviceInitialize() + } + } + } + + @Synchronized + fun getService(name: ServiceName): Service? { + return definitions[name]?.let { definition -> getService(definition) } + } + + @JavascriptInterface + fun exec(name: String?, action: String, args: String, id: Long): Boolean { + val callback = Callback(id, webView) + val definition = name?.let { definitionsByKey[it] } + if (definition == null) { + callback.error("Unknown native service: $name") + return true + } + val requestGeneration = generation + webView.post { + if (generation != requestGeneration) return@post + try { + val service = getService(definition) + instance!! + .threadPoolSingle!! + .execute { + if (generation != requestGeneration) return@execute + try { + if (!service.execute(action, args, callback)) { + callback.sendPayload( + Payload(Payload.Status.INVALID_ACTION, action) + ) + } + } catch (exception: Exception) { + Log.e(TAG, "Service $name failed to execute $action", exception) + callback.error(exception.toString()) + } + } + } catch (exception: Exception) { + Log.e(TAG, "Unable to run service $name", exception) + callback.error(exception.toString()) + } + } + return true + } + + fun remapUri(uri: Uri?): Uri? { + for (service in activeServices) { + val result = service.remapUri(uri) + if (result != null) return result + } + return null + } + + fun postMessage(name: String?, value: Any?) { + for (service in activeServices) service.onMessage(name, value) + } + + fun reset() { + generation++ + for (service in activeServices) service.onReset() + } + + fun destroy() { + generation++ + for (service in activeServices) service.onDestroy() + services.clear() + } + + companion object { + private const val TAG = "Bridge" + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Callback.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Callback.kt new file mode 100644 index 0000000000..1f2fc3d717 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Callback.kt @@ -0,0 +1,50 @@ +package com.foxdebug.acode.runtime + +import android.util.Log +import com.foxdebug.acode.runtime.webview.AppWebView +import org.json.JSONException + +open class Callback(private val id: Long, private val webView: AppWebView) { + private val generation: Long = webView.bridge!!.generation + + @get:Synchronized + var isFinished: Boolean = false + private set + + val callbackId: String + get() = id.toString() + + fun success() { + sendPayload(Payload(Payload.Status.OK)) + } + + fun success(data: Any?) { + sendPayload(Payload(Payload.Status.OK, data)) + } + + fun error(data: Any?) { + sendPayload(Payload(Payload.Status.ERROR, data)) + } + + @Synchronized + open fun sendPayload(payload: Payload) { + if (this.isFinished) return + this.isFinished = !payload.keepCallback + if (payload.getStatus() == Payload.Status.NO_RESULT.ordinal && + payload.keepCallback + ) return + try { + val json = payload.toJSON(id, generation).toString() + webView.post(Runnable { + if (generation == webView.bridge!!.generation) { + webView.evaluateJavascript( + "window.Android.callback($json);", + null + ) + } + }) + } catch (exception: JSONException) { + Log.e("Acode", "Unable to serialize callback", exception) + } + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Payload.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Payload.kt new file mode 100644 index 0000000000..f314e6ff95 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Payload.kt @@ -0,0 +1,90 @@ +package com.foxdebug.acode.runtime + +import android.util.Base64 +import org.json.JSONArray +import org.json.JSONException +import org.json.JSONObject + +class Payload @JvmOverloads constructor( + private val status: Status, + private val data: Any? = STATUS_MESSAGES[status.ordinal] +) { + enum class Status { + NO_RESULT, + OK, + CLASS_NOT_FOUND_EXCEPTION, + ILLEGAL_ACCESS_EXCEPTION, + INSTANTIATION_EXCEPTION, + MALFORMED_URL_EXCEPTION, + IO_EXCEPTION, + INVALID_ACTION, + JSON_EXCEPTION, + ERROR, + } + + var keepCallback: Boolean = false + + constructor(status: Status, data: ByteArray?, binaryString: Boolean) : this( + status, + encodeBinary(data, binaryString) + ) + + constructor(data: Any?) : this(Status.OK, data) + + fun getStatus(): Int { + return status.ordinal + } + + @Throws(JSONException::class) + fun toJSON(id: Long, generation: Long): JSONObject { + val result = JSONObject() + result.put("id", id) + result.put("generation", generation) + result.put("type", if (status == Status.OK) 0 else 1) + result.put("status", status.ordinal) + result.put("keep", this.keepCallback) + result.put("data", encode(data)) + return result + } + + companion object { + const val MESSAGE_TYPE_STRING: Int = 1 + const val MESSAGE_TYPE_ARRAYBUFFER: Int = 6 + const val MESSAGE_TYPE_BINARYSTRING: Int = 7 + + private val STATUS_MESSAGES = arrayOf<String?>( + "No result", + "OK", + "Class not found", + "Illegal access", + "Instantiation error", + "Malformed url", + "IO error", + "Invalid action", + "JSON error", + "Error", + ) + + @Throws(JSONException::class) + private fun encode(value: Any?): Any { + if (value == null) return JSONObject.NULL + if (value is ByteArray) return encodeBinary(value, false) + if (value is MutableList<*>) { + val parts = JSONArray() + for (part in value) parts.put(encode((part as Payload).data)) + return JSONObject().put("kind", "multipart").put("data", parts) + } + return value + } + + private fun encodeBinary(bytes: ByteArray?, binaryString: Boolean): JSONObject { + try { + return JSONObject() + .put("kind", if (binaryString) "binaryString" else "arrayBuffer") + .put("data", Base64.encodeToString(bytes, Base64.NO_WRAP)) + } catch (exception: JSONException) { + throw IllegalArgumentException(exception) + } + } + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Preferences.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Preferences.kt new file mode 100644 index 0000000000..b8b20845bc --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Preferences.kt @@ -0,0 +1,97 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package com.foxdebug.acode.runtime + +import java.lang.Long +import kotlin.Boolean +import kotlin.Double +import kotlin.Int +import kotlin.String + +class Preferences { + private val prefs = HashMap<String?, String?>(20) + + fun set(name: String, value: String?) { + prefs[name.lowercase()] = value + } + + fun set(name: String, value: Boolean) { + set(name, "" + value) + } + + fun set(name: String, value: Int) { + set(name, "" + value) + } + + fun set(name: String, value: Double) { + set(name, "" + value) + } + + val all: MutableMap<String?, String?> + get() = prefs + + fun getBoolean(name: String, defaultValue: Boolean): Boolean { + var name = name + name = name.lowercase() + val value = prefs.get(name) + if (value != null) { + return value.toBoolean() + } + return defaultValue + } + + // Added in 4.0.0 + fun contains(name: String): Boolean { + return getString(name, null) != null + } + + fun getInteger(name: String, defaultValue: Int): Int { + var name = name + name = name.lowercase() + val value = prefs[name] + if (value != null) { + // Some 32-bit hex values (for example, 0x80000000) are valid int bit patterns + // but exceed Integer.MAX_VALUE when read as positive numbers. Integer.decode() + // rejects such values with NumberFormatException, so decode as long first and + // cast to int to preserve the intended 32-bit value. + return (Long.decode(value) as kotlin.Long).toInt() + } + return defaultValue + } + + fun getDouble(name: String, defaultValue: Double): Double { + var name = name + name = name.lowercase() + val value = prefs[name] + if (value != null) { + return value.toDouble() + } + return defaultValue + } + + fun getString(name: String, defaultValue: String?): String? { + var name = name + name = name.lowercase() + val value = prefs[name] + if (value != null) { + return value + } + return defaultValue + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ResourceApi.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ResourceApi.kt new file mode 100644 index 0000000000..b15107c897 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ResourceApi.kt @@ -0,0 +1,433 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package com.foxdebug.acode.runtime + +import android.content.ContentResolver +import android.content.Context +import android.content.res.AssetFileDescriptor +import android.content.res.AssetManager +import android.net.Uri +import android.os.Looper +import android.util.Base64 +import android.webkit.MimeTypeMap +import java.io.ByteArrayInputStream +import java.io.File +import java.io.FileInputStream +import java.io.FileNotFoundException +import java.io.FileOutputStream +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.io.UnsupportedEncodingException +import java.net.HttpURLConnection +import java.net.URL +import java.util.Locale +import java.util.zip.GZIPInputStream + + +class ResourceApi(context: Context, private val pluginManager: Bridge) { + private val assetManager: AssetManager = context.assets + private val contentResolver: ContentResolver = context.contentResolver + var isThreadCheckingEnabled: Boolean = true + + + fun remapUri(uri: Uri): Uri { + assertNonRelative(uri) + val pluginUri = pluginManager.remapUri(uri) + return pluginUri ?: uri + } + + fun remapPath(path: String): String? { + return remapUri(Uri.fromFile(File(path))).path + } + + /** + * @return A file that points to the resource, or null if the resource is not on the local filesystem. + */ + fun mapUriToFile(uri: Uri): File? { + assertBackgroundThread() + when (getUriType(uri)) { + URI_TYPE_FILE -> return File(uri.path!!) + URI_TYPE_CONTENT -> { + val cursor = contentResolver.query(uri, LOCAL_FILE_PROJECTION, null, null, null) + cursor?.use { cursor -> + val columnIndex = cursor.getColumnIndex(LOCAL_FILE_PROJECTION[0]) + if (columnIndex != -1 && cursor.count > 0) { + cursor.moveToFirst() + val realPath = cursor.getString(columnIndex) + if (realPath != null) { + return File(realPath) + } + } + } + } + } + return null + } + + fun getMimeType(uri: Uri): String? { + when (getUriType(uri)) { + URI_TYPE_FILE, URI_TYPE_ASSET -> return getMimeTypeFromPath(uri.path!!) + URI_TYPE_CONTENT, URI_TYPE_RESOURCE -> return contentResolver.getType(uri) + URI_TYPE_DATA -> { + return getDataUriMimeType(uri) + } + + URI_TYPE_HTTP, URI_TYPE_HTTPS -> { + try { + val conn = URL(uri.toString()).openConnection() as HttpURLConnection + conn.setDoInput(false) + conn.requestMethod = "HEAD" + var mimeType = conn.getHeaderField("Content-Type") + if (mimeType != null) { + mimeType = mimeType.split(";".toRegex()).dropLastWhile { it.isEmpty() } + .toTypedArray()[0] + } + return mimeType + } catch (e: IOException) { + } + } + } + + return null + } + + + //This already exists + private fun getMimeTypeFromPath(path: String): String? { + var extension = path + val lastDot = extension.lastIndexOf('.') + if (lastDot != -1) { + extension = extension.substring(lastDot + 1) + } + // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185). + extension = extension.lowercase(Locale.getDefault()) + if (extension == "3ga") { + return "audio/3gpp" + } else if (extension == "js") { + // Missing from the map :(. + return "text/javascript" + } + return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) + } + + /** + * Opens a stream to the given URI, also providing the MIME type & length. + * + * @return Never returns null. + * @throws IllegalArgumentException For relative URIs. Relative URIs should be resolved before + * being passed into this function. + * @throws IOException If the URI cannot be opened. + * @throws IllegalStateException If called on a foreground thread and skipThreadCheck is false. + */ + /** + * Opens a stream to the given URI, also providing the MIME type & length. + * + * @return Never returns null. + * @throws IllegalArgumentException For relative URIs. Relative URIs should be resolved before + * being passed into this function. + * @throws IOException If the URI cannot be opened. + * @throws IllegalStateException If called on a foreground thread. + */ + @JvmOverloads + @Throws(IOException::class) + fun openForRead(uri: Uri, skipThreadCheck: Boolean = false): OpenForReadResult? { + if (!skipThreadCheck) { + assertBackgroundThread() + } + when (getUriType(uri)) { + URI_TYPE_FILE -> { + val inputStream = FileInputStream(uri.path) + val mimeType = getMimeTypeFromPath(uri.path!!) + val length = inputStream.channel.size() + return OpenForReadResult(uri, inputStream, mimeType, length, null) + } + + URI_TYPE_ASSET -> { + val assetPath = uri.path!!.substring(15) + var assetFd: AssetFileDescriptor? = null + var inputStream: InputStream + var length: Long = -1 + try { + assetFd = assetManager.openFd(assetPath) + inputStream = assetFd.createInputStream() + length = assetFd.length + } catch (e: FileNotFoundException) { + // Will occur if the file is compressed. + inputStream = assetManager.open(assetPath) + length = inputStream.available().toLong() + } + val mimeType = getMimeTypeFromPath(assetPath) + return OpenForReadResult(uri, inputStream, mimeType, length, assetFd) + } + + URI_TYPE_CONTENT, URI_TYPE_RESOURCE -> { + val mimeType = contentResolver.getType(uri) + val assetFd = contentResolver.openAssetFileDescriptor(uri, "r") + val inputStream: InputStream = assetFd!!.createInputStream() + val length = assetFd.length + return OpenForReadResult(uri, inputStream, mimeType, length, assetFd) + } + + URI_TYPE_DATA -> { + val ret = readDataUri(uri) + return ret + } + + URI_TYPE_HTTP, URI_TYPE_HTTPS -> { + val conn = URL(uri.toString()).openConnection() as HttpURLConnection + conn.setRequestProperty("Accept-Encoding", "gzip") + conn.setDoInput(true) + var mimeType = conn.getHeaderField("Content-Type") + if (mimeType != null) { + mimeType = mimeType.split(";".toRegex()).dropLastWhile { it.isEmpty() } + .toTypedArray()[0] + } + val length = conn.contentLength + val inputStream: InputStream + if ("gzip" == conn.contentEncoding) { + inputStream = GZIPInputStream(conn.getInputStream()) + } else { + inputStream = conn.getInputStream() + } + return OpenForReadResult(uri, inputStream, mimeType, length.toLong(), null) + } + + URI_TYPE_PLUGIN -> { + //wtf is this? + //i am commenting this for now + //probably break uri stuff + +// val plugin = ServiceName.fromKey(uri.host)?.let { name -> +// pluginManager.getService(name) +// } ?: throw FileNotFoundException("Invalid plugin ID in URI: $uri") +// return plugin.openForRead(uri) + } + } + throw FileNotFoundException("URI not supported by ResourceApi: $uri") + } + + /** + * Opens a stream to the given URI. + * + * @return Never returns null. + * @throws IllegalArgumentException For relative URIs. Relative URIs should be resolved before + * being passed into this function. + * @throws IOException If the URI cannot be opened. + */ + @JvmOverloads + @Throws(IOException::class) + fun openOutputStream(uri: Uri, append: Boolean = false): OutputStream? { + assertBackgroundThread() + when (getUriType(uri)) { + URI_TYPE_FILE -> { + val localFile = File(uri.path!!) + val parent = localFile.parentFile + if (parent != null) { + parent.mkdirs() + } + return FileOutputStream(localFile, append) + } + + URI_TYPE_CONTENT, URI_TYPE_RESOURCE -> { + val assetFd = + contentResolver.openAssetFileDescriptor(uri, if (append) "wa" else "w") + return assetFd!!.createOutputStream() + } + } + throw FileNotFoundException("URI not supported by ResourceApi: $uri") + } + + @Throws(IOException::class) + fun createHttpConnection(uri: Uri): HttpURLConnection? { + assertBackgroundThread() + return URL(uri.toString()).openConnection() as HttpURLConnection? + } + + // Copies the input to the output in the most efficient manner possible. + // Closes both streams. + @Throws(IOException::class) + fun copyResource(input: OpenForReadResult, outputStream: OutputStream?) { + assertBackgroundThread() + try { + val inputStream = input.inputStream + if (inputStream is FileInputStream && outputStream is FileOutputStream) { + val inChannel = input.inputStream.channel + val outChannel = outputStream.channel + var offset: Long = 0 + val length = input.length + if (input.assetFd != null) { + offset = input.assetFd.startOffset + } + // transferFrom()'s 2nd arg is a relative position. Need to set the absolute + // position first. + inChannel.position(offset) + outChannel.transferFrom(inChannel, 0, length) + } else { + val BUFFER_SIZE = 8192 + val buffer = ByteArray(BUFFER_SIZE) + + while (true) { + val bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE) + + if (bytesRead <= 0) { + break + } + outputStream!!.write(buffer, 0, bytesRead) + } + } + } finally { + input.inputStream.close() + outputStream?.close() + } + } + + @Throws(IOException::class) + fun copyResource(sourceUri: Uri, outputStream: OutputStream?) { + copyResource(openForRead(sourceUri)!!, outputStream) + } + + // Added in 3.5.0. + @Throws(IOException::class) + fun copyResource(sourceUri: Uri, dstUri: Uri) { + copyResource(openForRead(sourceUri)!!, openOutputStream(dstUri)) + } + + private fun assertBackgroundThread() { + if (this.isThreadCheckingEnabled) { + val curThread = Thread.currentThread() + check( + curThread !== Looper.getMainLooper().thread + ) { "Do not perform IO operations on the UI thread. Use Host.getThreadPool() instead." } + check(curThread !== jsThread) { "Tried to perform an IO operation on the WebCore thread. Use Host.getThreadPool() instead." } + } + } + + private fun getDataUriMimeType(uri: Uri): String? { + val uriAsString = uri.schemeSpecificPart + val commaPos = uriAsString.indexOf(',') + if (commaPos == -1) { + return null + } + val mimeParts: Array<String?> = + uriAsString.substring(0, commaPos).split(";".toRegex()).dropLastWhile { it.isEmpty() } + .toTypedArray() + if (mimeParts.isNotEmpty()) { + return mimeParts[0] + } + return null + } + + private fun readDataUri(uri: Uri): OpenForReadResult? { + val uriAsString = uri.schemeSpecificPart + val commaPos = uriAsString.indexOf(',') + if (commaPos == -1) { + return null + } + val mimeParts: Array<String?> = + uriAsString.substring(0, commaPos).split(";".toRegex()).dropLastWhile { it.isEmpty() } + .toTypedArray() + var contentType: String? = null + var base64 = false + if (mimeParts.isNotEmpty()) { + contentType = mimeParts[0] + } + for (i in 1..<mimeParts.size) { + if ("base64".equals(mimeParts[i], ignoreCase = true)) { + base64 = true + } + } + val dataPartAsString = uriAsString.substring(commaPos + 1) + var data: ByteArray + if (base64) { + data = Base64.decode(dataPartAsString, Base64.DEFAULT) + } else { + try { + data = dataPartAsString.toByteArray(charset("UTF-8")) + } catch (e: UnsupportedEncodingException) { + data = dataPartAsString.toByteArray() + } + } + val inputStream: InputStream = ByteArrayInputStream(data) + return OpenForReadResult(uri, inputStream, contentType, data.size.toLong(), null) + } + + class OpenForReadResult( + val uri: Uri?, + @JvmField val inputStream: InputStream, + @JvmField val mimeType: String?, + @JvmField val length: Long, + val assetFd: AssetFileDescriptor? + ) + + companion object { + @Suppress("unused") + private const val LOG_TAG = "ResourceApi" + + const val URI_TYPE_FILE: Int = 0 + const val URI_TYPE_ASSET: Int = 1 + const val URI_TYPE_CONTENT: Int = 2 + const val URI_TYPE_RESOURCE: Int = 3 + const val URI_TYPE_DATA: Int = 4 + const val URI_TYPE_HTTP: Int = 5 + const val URI_TYPE_HTTPS: Int = 6 + const val URI_TYPE_PLUGIN: Int = 7 + const val URI_TYPE_UNKNOWN: Int = -1 + + const val PLUGIN_URI_SCHEME: String = "cdvplugin" + + private val LOCAL_FILE_PROJECTION = arrayOf<String?>("_data") + + var jsThread: Thread? = null + + fun getUriType(uri: Uri): Int { + assertNonRelative(uri) + val scheme = uri.scheme + if (ContentResolver.SCHEME_CONTENT.equals(scheme, ignoreCase = true)) { + return URI_TYPE_CONTENT + } + if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme, ignoreCase = true)) { + return URI_TYPE_RESOURCE + } + if (ContentResolver.SCHEME_FILE.equals(scheme, ignoreCase = true)) { + if (uri.path!!.startsWith("/android_asset/")) { + return URI_TYPE_ASSET + } + return URI_TYPE_FILE + } + if ("data".equals(scheme, ignoreCase = true)) { + return URI_TYPE_DATA + } + if ("http".equals(scheme, ignoreCase = true)) { + return URI_TYPE_HTTP + } + if ("https".equals(scheme, ignoreCase = true)) { + return URI_TYPE_HTTPS + } + if (PLUGIN_URI_SCHEME.equals(scheme, ignoreCase = true)) { + return URI_TYPE_PLUGIN + } + return URI_TYPE_UNKNOWN + } + + private fun assertNonRelative(uri: Uri) { + require(uri.isAbsolute) { "Relative URIs are not supported." } + } + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/RuntimeBaseApplication.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/RuntimeBaseApplication.kt new file mode 100644 index 0000000000..e0506e3603 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/RuntimeBaseApplication.kt @@ -0,0 +1,38 @@ +package com.foxdebug.acode.runtime + +import android.app.Application +import kotlinx.coroutines.CoroutineScope +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors + +open class RuntimeBaseApplication : Application() { + private var executorService: ExecutorService? = null + private var executorServiceSingle: ExecutorService? = null + + override fun onCreate() { + super.onCreate() + instance = this + executorService = Executors.newCachedThreadPool() + executorServiceSingle = Executors.newSingleThreadExecutor() + } + + @Deprecated(message = "Directly using System threads or threadPools is not reccomended", replaceWith = ReplaceWith("Coroutines")) + val threadPool: ExecutorService? + get() = executorService + + @Deprecated(message = "Directly using System threads or threadPools is not reccomended", replaceWith = ReplaceWith("Coroutines")) + val threadPoolSingle: ExecutorService? + get() = executorServiceSingle + + override fun onTerminate() { + executorService!!.shutdownNow() + executorServiceSingle!!.shutdownNow() + super.onTerminate() + } + + companion object { + @JvmStatic + var instance: RuntimeBaseApplication? = null + private set + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Service.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Service.kt new file mode 100644 index 0000000000..8b9f46a37a --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/Service.kt @@ -0,0 +1,82 @@ +package com.foxdebug.acode.runtime + +import android.content.Intent +import android.content.res.Configuration +import android.net.Uri +import com.foxdebug.acode.runtime.ResourceApi.OpenForReadResult +import com.foxdebug.acode.runtime.webview.AppWebView +import org.json.JSONArray +import org.json.JSONException +import java.io.FileNotFoundException +import java.io.IOException + +abstract class Service { + @JvmField + var host: Host? = null + + @JvmField + var webView: AppWebView? = null + + @JvmField + var preferences: Preferences? = null + + open fun initialize(bridgeContext: BridgeContext) { + val webActivity = bridgeContext.webActivity + host = webActivity.getHost() + webView = bridgeContext.webView + preferences = host?.preferences + } + + open fun serviceInitialize() {} + + @Throws(JSONException::class) + open fun execute(action: String, args: String, callback: Callback): Boolean { + return execute(action, JSONArray(args), callback) + } + + @Throws(JSONException::class) + open fun execute(action: String, args: JSONArray, callback: Callback): Boolean { + return false + } + + @Throws(JSONException::class) + open fun onRequestPermissionResult( + requestCode: Int, + permissions: Array<String?>?, + grants: IntArray? + ) { + } + + open fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {} + + open fun onMessage(id: String?, data: Any?): Any? { + return null + } + + open fun onNewIntent(intent: Intent?) {} + + open fun onPause(multitasking: Boolean) {} + + open fun onResume(multitasking: Boolean) {} + + open fun onReset() {} + + open fun onConfigurationChanged( + configuration: Configuration? + ) { + } + + open fun onDestroy() {} + + open fun remapUri(uri: Uri?): Uri? { + return null + } + + open val pathHandler: ServicePathHandler? + get() = null + + @Throws(IOException::class) + fun openForRead(uri: Uri): OpenForReadResult? { + throw FileNotFoundException(uri.toString()) + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServiceDefinition.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServiceDefinition.kt new file mode 100644 index 0000000000..fa8c7b3aaa --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServiceDefinition.kt @@ -0,0 +1,18 @@ +package com.foxdebug.acode.runtime + +/** Creates one instance of the service bound to a [ServiceName]. */ +fun interface ServiceFactory { + fun create(): Service +} + +/** Binds a transport name to the class serving it, so no lookup happens at runtime. */ +class ServiceDefinition( + val name: ServiceName, + val loadOnStart: Boolean = false, + val factory: ServiceFactory, +) + +/** Services a build variant contributes on top of the shared catalogue. */ +interface ServiceModule { + val services: List<ServiceDefinition> +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServiceName.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServiceName.kt new file mode 100644 index 0000000000..0c767084c1 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServiceName.kt @@ -0,0 +1,29 @@ +package com.foxdebug.acode.runtime + +/** Transport keys the JavaScript bridge uses to address native services. */ +enum class ServiceName(val key: String) { + AD_MOB("AdMob"), + AUTHENTICATOR("Authenticator"), + BROWSER("Browser"), + CLIPBOARD("Clipboard"), + NATIVE_HTTP("NativeHttpPlugin"), + BUILD_INFO("BuildInfo"), + CRASH_HANDLER("CrashHandler"), + CUSTOM_TABS("CustomTabs"), + DEVICE("Device"), + FILE("File"), + FTP("Ftp"), + IAP("Iap"), + TEE("Tee"), + SD_CARD("SDcard"), + SERVER("Server"), + SFTP("Sftp"), + SYSTEM("System"), + EXECUTOR("Executor"), + BACKGROUND_EXECUTOR("BackgroundExecutor"), + WEB_SOCKET("WebSocketPlugin"), + ACODE_WEB_VIEW("AcodeWebView"), + APP("App"), + SYSTEM_BAR("SystemBarPlugin"); + +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServicePathHandler.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServicePathHandler.kt new file mode 100644 index 0000000000..ccc28dbf32 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServicePathHandler.kt @@ -0,0 +1,26 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package com.foxdebug.acode.runtime + +import androidx.webkit.WebViewAssetLoader.PathHandler + +/** + * Wrapper class for path and handler + */ +class ServicePathHandler(val pathHandler: PathHandler?) diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServicePlugin.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServicePlugin.kt new file mode 100644 index 0000000000..01ee4c252f --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServicePlugin.kt @@ -0,0 +1,4 @@ +package com.foxdebug.acode.runtime + +abstract class ServicePlugin { +} \ No newline at end of file diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServiceRegistry.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServiceRegistry.kt new file mode 100644 index 0000000000..2e1e97b58a --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/ServiceRegistry.kt @@ -0,0 +1,50 @@ +package com.foxdebug.acode.runtime + +import com.foxdebug.acode.auth.Authenticator +import com.foxdebug.acode.browser.Plugin +import com.foxdebug.acode.buildinfo.BuildInfo +import com.foxdebug.acode.crashhandler.CrashHandler +import com.foxdebug.acode.customtabs.CustomTabsPlugin +import com.foxdebug.acode.device.Device +import com.foxdebug.acode.file.FileUtils +import com.foxdebug.acode.ftp.Ftp +import com.foxdebug.acode.http.NativeHttpPlugin +import com.foxdebug.acode.sdcard.SDcard +import com.foxdebug.acode.security.Tee +import com.foxdebug.acode.server.Server +import com.foxdebug.acode.sftp.Sftp +import com.foxdebug.acode.system.System as SystemService +import com.foxdebug.acode.terminal.BackgroundExecutor +import com.foxdebug.acode.terminal.Executor +import com.foxdebug.acode.websocket.WebSocketPlugin +import com.foxdebug.acode.webview.WebViewPlugin +import com.verso.clipboard.Clipboard + +object ServiceRegistry { + private val mainServices: List<ServiceDefinition> = listOf( + ServiceDefinition(ServiceName.AUTHENTICATOR, loadOnStart = true) { Authenticator() }, + ServiceDefinition(ServiceName.BROWSER) { Plugin() }, + ServiceDefinition(ServiceName.CLIPBOARD) { Clipboard() }, + ServiceDefinition(ServiceName.NATIVE_HTTP) { NativeHttpPlugin() }, + ServiceDefinition(ServiceName.BUILD_INFO) { BuildInfo() }, + ServiceDefinition(ServiceName.CRASH_HANDLER, loadOnStart = true) { CrashHandler() }, + ServiceDefinition(ServiceName.CUSTOM_TABS) { CustomTabsPlugin() }, + ServiceDefinition(ServiceName.DEVICE) { Device() }, + ServiceDefinition(ServiceName.FILE, loadOnStart = true) { FileUtils() }, + ServiceDefinition(ServiceName.FTP) { Ftp() }, + ServiceDefinition(ServiceName.TEE) { Tee() }, + ServiceDefinition(ServiceName.SD_CARD) { SDcard() }, + ServiceDefinition(ServiceName.SERVER) { Server() }, + ServiceDefinition(ServiceName.SFTP) { Sftp() }, + ServiceDefinition(ServiceName.SYSTEM) { SystemService() }, + ServiceDefinition(ServiceName.EXECUTOR) { Executor() }, + ServiceDefinition(ServiceName.BACKGROUND_EXECUTOR) { BackgroundExecutor() }, + ServiceDefinition(ServiceName.WEB_SOCKET) { WebSocketPlugin() }, + ServiceDefinition(ServiceName.ACODE_WEB_VIEW) { WebViewPlugin() }, + ServiceDefinition(ServiceName.APP) { App() }, + ServiceDefinition(ServiceName.SYSTEM_BAR, loadOnStart = true) { SystemBarPlugin() }, + ) + + val definitions: List<ServiceDefinition> = + mainServices + EditionServices.services + ChannelServices.services +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/SystemBarPlugin.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/SystemBarPlugin.kt new file mode 100644 index 0000000000..aeb52eaa12 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/SystemBarPlugin.kt @@ -0,0 +1,393 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package com.foxdebug.acode.runtime + +import android.R +import android.annotation.SuppressLint +import android.content.Context +import android.content.res.Configuration +import android.content.res.Resources +import android.graphics.Color +import android.os.Build +import android.util.Log +import android.view.View +import android.view.WindowInsetsController +import android.widget.FrameLayout +import androidx.core.content.ContextCompat +import androidx.core.view.ViewCompat +import androidx.core.view.WindowCompat +import com.foxdebug.acode.runtime.webview.AppWebView +import org.json.JSONArray +import org.json.JSONException +import java.util.Objects +import kotlin.math.roundToInt +import androidx.core.view.size +import androidx.core.graphics.toColorInt +import com.foxdebug.acode.settings.AppPreferences +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.DelicateCoroutinesApi +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch +import okhttp3.Dispatcher + +class SystemBarPlugin : Service() { + // Internal variables + private var context: Context? = null + private var resources: Resources? = null + private var overrideStatusBarBackgroundColor: Int? = null + + private var canEdgeToEdge = false + + private lateinit var bridgeContext: BridgeContext + + override fun initialize(bridgeContext: BridgeContext) { + super.initialize(bridgeContext) + this.bridgeContext = bridgeContext + context = bridgeContext.webActivity + resources = bridgeContext.webActivity.resources + canEdgeToEdge = AppPreferences.getBoolean("AndroidEdgeToEdge", false) + } + + @OptIn(DelicateCoroutinesApi::class) + override fun execute(action: String, args: JSONArray, callback: Callback): Boolean { + when (action) { + "setStatusBarVisible" -> { + val visible = args.getBoolean(0) + GlobalScope.launch(Dispatchers.Main) { setStatusBarVisible(visible) } + } + "setStatusBarBackgroundColor" -> { + GlobalScope.launch(Dispatchers.Main) { setStatusBarBackgroundColor(args!!)} + } + else -> { + return false + } + } + + callback.success() + return true + } + + + public override fun onConfigurationChanged(newConfig: Configuration?) { + super.onConfigurationChanged(newConfig) + GlobalScope.launch(Dispatchers.Main) { + updateSystemBars() + } + } + + public override fun onResume(multitasking: Boolean) { + super.onResume(multitasking) + GlobalScope.launch(Dispatchers.Main) { + updateSystemBars() + } + + } + + override fun onMessage(id: String?, data: Any?): Any? { + if (id == "updateSystemBars") { + GlobalScope.launch(Dispatchers.Main) { + updateSystemBars() + } + } + return null + } + + /** + * Allow the app to override the status bar visibility from JS API. + * If for some reason the statusBarView could not be discovered, it will silently ignore + * the change request + * + * @param visible should the status bar be visible? + */ + private fun setStatusBarVisible(visible: Boolean) { + val statusBar = getStatusBarView(bridgeContext.webView) + if (statusBar != null) { + statusBar.visibility = if (visible) View.VISIBLE else View.GONE + + val rootLayout = getRootLayout(bridgeContext.webView) + if (rootLayout != null) { + ViewCompat.requestApplyInsets(rootLayout) + } + } + } + + /** + * Allow the app to override the status bar background color from JS API. + * If the supplied ARGB is invalid or fails to parse, it will silently ignore + * the change request. + * + * @param argbVals {R, G, B, A} + */ + private fun setStatusBarBackgroundColor(argbVals: JSONArray) { + try { + val r = argbVals.getInt(0) + val g = argbVals.getInt(1) + val b = argbVals.getInt(2) + val a = (255 * argbVals.optDouble(3, 1.0).toFloat()).roundToInt() + + overrideStatusBarBackgroundColor = Color.argb(a, r, g, b) + updateStatusBar(overrideStatusBarBackgroundColor!!) + } catch (e: JSONException) { + // Silently skip + } + } + + /** + * Attempt to update all system bars (status, navigation and gesture bars) in various points + * of the apps life cycle. + * For example: + * 1. Device configurations between (E.g. between dark and light mode) + * 2. User resumes the app + * 3. App transitions from SplashScreen Theme to App's Theme + */ + private fun updateSystemBars() { + // Update Root View Background Color + var rootViewBackgroundColor = this.preferenceBackgroundColor + if (rootViewBackgroundColor == null) { + rootViewBackgroundColor = if (canEdgeToEdge) Color.TRANSPARENT else this.uiModeColor + } + updateRootView(rootViewBackgroundColor) + + // Update StatusBar Background Color + val statusBarBackgroundColor: Int? + if (overrideStatusBarBackgroundColor != null) { + statusBarBackgroundColor = overrideStatusBarBackgroundColor + } else if (AppPreferences.contains("StatusBarBackgroundColor")) { + statusBarBackgroundColor = this.preferenceStatusBarBackgroundColor + } else if (AppPreferences.contains("BackgroundColor")) { + statusBarBackgroundColor = rootViewBackgroundColor + } else { + statusBarBackgroundColor = if (canEdgeToEdge) Color.TRANSPARENT else this.uiModeColor + } + + updateStatusBar(statusBarBackgroundColor!!) + } + + /** + * Updates the root layout's background color with the supplied color int. + * It will also determine if the background color is light or dark to properly adjust the + * appearance of the navigation/gesture bar's icons so it will not clash with the background. + * + * + * System bars (navigation & gesture) on SDK 25 or lower is forced to black as the appearance + * of the fonts can not be updated. + * System bars (navigation & gesture) on SDK 26 or greater allows custom background color. + * + * + * + * @param bgColor Background color + */ + @Suppress("deprecation") + private fun updateRootView(bgColor: Int) { + val window = bridgeContext.webActivity.getWindow() + + // Set the root view's background color. Works on SDK 36+ + val root = bridgeContext.webActivity.findViewById<View?>(R.id.content) + if (root != null) root.setBackgroundColor(bgColor) + + // Automatically set the font and icon color of the system bars based on background color. + val isBackgroundColorLight: Boolean + if (bgColor == Color.TRANSPARENT) { + isBackgroundColorLight = isColorLight(this.uiModeColor) + } else { + isBackgroundColorLight = isColorLight(bgColor) + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val controller = window.insetsController + if (controller != null) { + val appearance = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS + if (isBackgroundColorLight) { + controller.setSystemBarsAppearance(appearance, appearance) + } else { + controller.setSystemBarsAppearance(0, appearance) + } + } + } + val controllerCompat = WindowCompat.getInsetsController(window, window.getDecorView()) + controllerCompat.isAppearanceLightNavigationBars = isBackgroundColorLight + + window.navigationBarColor = bgColor + } + + /** + * Updates the statusBarView background color with the supplied color int. + * It will also determine if the background color is light or dark to properly adjust the + * appearance of the status bar so the font will not clash with the background. + * + * @param bgColor Background color + */ + private fun updateStatusBar(bgColor: Int) { + val window = bridgeContext.webActivity.window + + val statusBar = getStatusBarView(bridgeContext.webView) + statusBar?.setBackgroundColor(bgColor) + + // Automatically set the font and icon color of the system bars based on background color. + val isStatusBarBackgroundColorLight: Boolean + if (bgColor == Color.TRANSPARENT) { + isStatusBarBackgroundColorLight = isColorLight(this.uiModeColor) + } else { + isStatusBarBackgroundColorLight = isColorLight(bgColor) + } + val controllerCompat = WindowCompat.getInsetsController(window, window.decorView) + controllerCompat.isAppearanceLightStatusBars = isStatusBarBackgroundColorLight + } + + private val preferenceStatusBarBackgroundColor: Int + /** + * Returns the StatusBarBackgroundColor preference value or [.getUiModeColor] as fallback. + * + * @return Integer + */ + get() { + val colorString = + AppPreferences.getString("StatusBarBackgroundColor", null) + return Objects.requireNonNullElse<Int>( + parseColorFromString(colorString), + this.uiModeColor + ) + } + + private val preferenceBackgroundColor: Int? + /** + * Returns the BackgroundColor preference value. + * If the value is missing or fails to decode, null is returned. + * + * @return Integer|null + */ + get() { + if (!AppPreferences.contains("BackgroundColor")) { + return null + } + + try { + return AppPreferences.getInteger("BackgroundColor", 0) + } catch (e: NumberFormatException) { + Log.e( + PLUGIN_NAME, + "Invalid background color argument. Example valid string: '0x00000000'" + ) + return null + } + } + + /** + * Tries to find and return the rootLayout. + * + * @param webView AppView + * @return FrameLayout|null + */ + private fun getRootLayout(webView: AppWebView): FrameLayout? { + val parent = webView.view.parent + if (parent is FrameLayout) { + return parent + } + + return null + } + + /** + * Tries to find and return the statusBarView. + * + * @param webView AppView + * @return View|null + */ + private fun getStatusBarView(webView: AppWebView): View? { + val rootView = getRootLayout(webView) ?: return null + + for (i in 0..<rootView.size) { + val child = rootView.getChildAt(i) + val tag = child.tag + if ("statusBarView" == tag) { + return child + } + } + return null + } + + @get:SuppressLint("DiscouragedApi") + private val uiModeColor: Int + /** + * Determines the background color for status bar & root layer. + * The color will come from the app's R.color.cdv_background_color. + * If for some reason the resource is missing, it will try to fallback on the uiMode. + * + * + * The uiMode as follows. + * If night mode: "#121318" (android.R.color.system_background_dark) + * If day mode: "#FAF8FF" (android.R.color.system_background_light) + * If all fails, light mode will be returned. + * + * The hex values are supplied instead of "android.R.color" for backwards compatibility. + * + * @return int color + */ + get() { + val isNightMode = + (resources!!.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES + val fallbackColor = if (isNightMode) "#121318" else "#FAF8FF" + val colorResId = + resources!!.getIdentifier( + "cdv_background_color", + "color", + context!!.packageName + ) + return if (colorResId != 0) + ContextCompat.getColor(context!!, colorResId) + else + fallbackColor.toColorInt() + } + + /** + * Parses a color string provided by app developers. + * If the color string is empty or unable to parse, null is returned. + * + * @param colorPref hex string value, #AARRGGBB or #RRGGBB + * @return Integer|null + */ + private fun parseColorFromString(colorPref: String?): Int? { + if (colorPref.isNullOrEmpty()) return null + + try { + return colorPref.toColorInt() + } catch (ignore: IllegalArgumentException) { + Log.e(PLUGIN_NAME, "Invalid color hex code. Valid format: #RRGGBB or #AARRGGBB") + return null + } + } + + companion object { + const val PLUGIN_NAME: String = "SystemBarPlugin" + + /** + * Determines if the supplied color's appearance is light. + * + * @param color color + * @return boolean value true is returned when the color is light. + */ + private fun isColorLight(color: Int): Boolean { + val r = Color.red(color) / 255.0 + val g = Color.green(color) / 255.0 + val b = Color.blue(color) / 255.0 + val luminance = 0.299 * r + 0.587 * g + 0.114 * b + return luminance > 0.5 + } + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/AcodeChromeClient.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/AcodeChromeClient.kt new file mode 100644 index 0000000000..6d28bf7eb8 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/AcodeChromeClient.kt @@ -0,0 +1,198 @@ +package com.foxdebug.acode.runtime.webview + +import android.Manifest +import android.graphics.Color +import android.net.Uri +import android.util.Log +import android.view.View +import android.webkit.ConsoleMessage +import android.webkit.GeolocationPermissions +import android.webkit.JsPromptResult +import android.webkit.JsResult +import android.webkit.PermissionRequest +import android.webkit.ValueCallback +import android.webkit.WebChromeClient +import android.webkit.WebView +import android.widget.FrameLayout +import androidx.activity.result.ActivityResultLauncher +import androidx.activity.result.contract.ActivityResultContracts +import androidx.core.view.ViewCompat +import com.foxdebug.acode.runtime.BaseWebActivity + +class AcodeChromeClient( + private val activity: BaseWebActivity, + private val webView: AppWebView, +) : WebChromeClient() { + private val dialogs = Dialogs(activity) + private val fileChooser = FileChooser(activity.getHost()) + private var pendingPermission: PermissionRequest? = null + private var fullscreenCallback: WebChromeClient.CustomViewCallback? = null + private var fullscreenView: FrameLayout? = null + private var backHandler = false + + private val permissionLauncher: ActivityResultLauncher<Array<String>> = + activity.registerForActivityResult( + ActivityResultContracts.RequestMultiplePermissions() + ) { grants -> + val request = pendingPermission + pendingPermission = null + if (request == null) return@registerForActivityResult + if (grants.isNotEmpty() && !grants.containsValue(false)) { + request.grant(request.resources) + } else { + request.deny() + } + } + + private val immersive = ImmersiveFullscreen(activity, true) { backHandler = false } + + val isFullscreen: Boolean + get() = fullscreenView != null + + fun pause() { + immersive.pause() + } + + fun resume() { + immersive.resume() + } + + fun setBackHandler(enabled: Boolean) { + if (enabled && !isFullscreen) { + throw IllegalStateException("Fullscreen is not active.") + } + backHandler = enabled + } + + fun setOrientation(orientation: String?) { + if (orientation == null) immersive.unlockOrientation() + else immersive.lockOrientation(orientation) + } + + fun handleBack(): Boolean { + if (!isFullscreen) return false + if (backHandler) webView.fireDocumentEvent("fullscreenbackbutton") + else onHideCustomView() + return true + } + + fun reset() { + onHideCustomView() + dialogs.destroyLastDialog() + } + + override fun onShowCustomView( + view: View, + callback: CustomViewCallback, + ) { + if (isFullscreen) { + callback.onCustomViewHidden() + return + } + val container = FrameLayout(activity) + container.setBackgroundColor(Color.BLACK) + container.addView(view, FrameLayout.LayoutParams(-1, -1)) + fullscreenCallback = callback + fullscreenView = container + activity.contentView.addView(container, FrameLayout.LayoutParams(-1, -1)) + webView.visibility = View.INVISIBLE + immersive.enter(container) + ViewCompat.requestApplyInsets(activity.contentView) + } + + override fun onHideCustomView() { + val container = fullscreenView ?: return + immersive.exit() + activity.contentView.removeView(container) + fullscreenView = null + webView.visibility = View.VISIBLE + val callback = fullscreenCallback + fullscreenCallback = null + callback?.onCustomViewHidden() + ViewCompat.requestApplyInsets(activity.contentView) + } + + override fun onShowFileChooser( + view: WebView?, + filePathCallback: ValueCallback<Array<Uri?>?>?, + fileChooserParams: WebChromeClient.FileChooserParams?, + ): Boolean = fileChooser.show(view!!, filePathCallback!!, fileChooserParams!!) + + override fun onJsAlert( + view: WebView?, + url: String?, + message: String?, + result: JsResult, + ): Boolean { + dialogs.showAlert(message) { success, _ -> + if (success) result.confirm() else result.cancel() + } + return true + } + + override fun onJsConfirm( + view: WebView?, + url: String?, + message: String?, + result: JsResult, + ): Boolean { + dialogs.showConfirm(message) { success, _ -> + if (success) result.confirm() else result.cancel() + } + return true + } + + override fun onJsPrompt( + view: WebView?, + url: String?, + message: String?, + defaultValue: String?, + result: JsPromptResult, + ): Boolean { + dialogs.showPrompt(message, defaultValue) { success, input -> + if (success) result.confirm(input) else result.cancel() + } + return true + } + + override fun onGeolocationPermissionsShowPrompt( + origin: String?, + callback: GeolocationPermissions.Callback, + ) { + callback.invoke(origin, true, false) + } + + override fun onPermissionRequest(request: PermissionRequest) { + val permissions = mutableListOf<String>() + for (resource in request.resources) { + when (resource) { + PermissionRequest.RESOURCE_VIDEO_CAPTURE -> + permissions.add(Manifest.permission.CAMERA) + + PermissionRequest.RESOURCE_AUDIO_CAPTURE -> { + permissions.add(Manifest.permission.MODIFY_AUDIO_SETTINGS) + permissions.add(Manifest.permission.RECORD_AUDIO) + } + } + } + if (permissions.isEmpty()) { + request.grant(request.resources) + } else { + pendingPermission?.deny() + pendingPermission = request + permissionLauncher.launch(permissions.toTypedArray()) + } + } + + override fun onPermissionRequestCanceled(request: PermissionRequest?) { + if (pendingPermission === request) pendingPermission = null + } + + override fun onConsoleMessage(message: ConsoleMessage): Boolean { + Log.d( + "AcodeWebView", + "${message.message()} at ${message.sourceId()}:${message.lineNumber()}", + ) + return true + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/AcodeWebViewClient.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/AcodeWebViewClient.kt new file mode 100644 index 0000000000..462383ed37 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/AcodeWebViewClient.kt @@ -0,0 +1,118 @@ +package com.foxdebug.acode.runtime.webview + +import android.content.ActivityNotFoundException +import android.content.Intent +import android.graphics.Bitmap +import android.net.http.SslError +import android.util.Log +import android.webkit.RenderProcessGoneDetail +import android.webkit.SslErrorHandler +import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse +import android.webkit.WebView +import android.webkit.WebViewClient +import com.foxdebug.acode.BuildConfig +import com.foxdebug.acode.runtime.BaseWebActivity +import com.foxdebug.acode.runtime.Bridge +import com.foxdebug.acode.runtime.ServiceName +import java.io.ByteArrayInputStream +import java.io.IOException +import java.net.URLConnection +import java.util.Arrays + +class AcodeWebViewClient(private val activity: BaseWebActivity, private val bridge: Bridge) : + WebViewClient() { + override fun onReceivedSslError( + view: WebView?, + handler: SslErrorHandler, + error: SslError? + ) { + if (BuildConfig.DEBUG) handler.proceed() + else handler.cancel() + } + + override fun onRenderProcessGone(view: WebView?, detail: RenderProcessGoneDetail?): Boolean { + Log.e("AcodeWebViewClient","RenderProcessGone details: $detail") + return super.onRenderProcessGone(view, detail) + } + + override fun onPageStarted( + view: WebView, + url: String?, + icon: Bitmap? + ) { + (view as AppWebView).resetChrome() + bridge.reset() + super.onPageStarted(view, url, icon) + } + + override fun shouldOverrideUrlLoading( + view: WebView?, + request: WebResourceRequest + ): Boolean { + val uri = request.getUrl() + if ("https" == uri.getScheme() || "http" == uri.getScheme() + ) return false + if (!request.isForMainFrame()) return false + try { + activity.startActivity(Intent(Intent.ACTION_VIEW, uri)) + } catch (ignored: ActivityNotFoundException) { + } + return true + } + + override fun shouldInterceptRequest( + view: WebView?, + request: WebResourceRequest + ): WebResourceResponse? { + val uri = request.getUrl() + if ("https" != uri.getScheme() || "localhost" != uri.getHost() + ) return null + var path = uri.getPath() + if (path == null || path == "/") path = "/index.html" + val file = bridge.getService(ServiceName.FILE) + val handler = file!!.pathHandler + val response = handler!! + .pathHandler!! + .handle(path.substring(1)) + if (response != null) return response + if (listOf(*path.split("/".toRegex()).dropLastWhile { it.isEmpty() } + .toTypedArray()).contains("..") || + path.indexOf('\u0000') != -1 + ) return missing() + try { + val stream = activity.getAssets().open("bundle" + path) + var mime = if (path.endsWith(".js")) + "application/javascript" + else + if (path.endsWith(".wasm")) + "application/wasm" + else + URLConnection.guessContentTypeFromName(path) + if (mime == null) mime = "application/octet-stream" + return WebResourceResponse( + mime, + if (mime.startsWith("text/") || mime == "application/javascript") + "UTF-8" + else + null, + stream + ) + } catch (exception: IOException) { + return missing() + } + } + + companion object { + private fun missing(): WebResourceResponse { + return WebResourceResponse( + "text/plain", + "UTF-8", + 404, + "Not Found", + mutableMapOf<String?, String?>(), + ByteArrayInputStream(ByteArray(0)) + ) + } + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/AppWebView.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/AppWebView.kt new file mode 100644 index 0000000000..734c3be0cd --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/AppWebView.kt @@ -0,0 +1,154 @@ +package com.foxdebug.acode.runtime.webview + +import android.content.Context +import android.graphics.Rect +import android.text.InputType +import android.view.ActionMode +import android.view.Menu +import android.view.MenuItem +import android.view.View +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputConnection +import android.webkit.WebView +import com.foxdebug.acode.runtime.Bridge +import com.foxdebug.acode.runtime.ResourceApi +import org.json.JSONObject + +class AppWebView(context: Context) : WebView(context) { + private var inputType = -1 + private var nativeContextMenuDisabled = false + var bridge: Bridge? = null + private set + var resourceApi: ResourceApi? = null + private set + private var fullscreen: AcodeChromeClient? = null + + fun initialize(bridge: Bridge) { + this.bridge = bridge + resourceApi = ResourceApi(getContext(), bridge) + } + + val view: AppWebView + get() = this + + val engine: AppWebView + get() = this + + fun setInputType(type: Int) { + inputType = type + } + + fun setNativeContextMenuDisabled(disabled: Boolean) { + nativeContextMenuDisabled = disabled + } + + fun setFullscreenController(fullscreen: AcodeChromeClient) { + this.fullscreen = fullscreen + } + + fun resetChrome() { + fullscreen!!.reset() + } + + fun setFullscreenBackHandler(enabled: Boolean) { + fullscreen!!.setBackHandler(enabled) + } + + fun setFullscreenOrientation(orientation: String?) { + fullscreen!!.setOrientation(orientation) + } + + fun fireDocumentEvent(event: String?) { + evaluateJavascript( + "window.Bridge && Bridge.fireDocumentEvent(" + + JSONObject.quote(event) + + ");", + null + ) + } + + override fun onCreateInputConnection(attrs: EditorInfo): InputConnection? { + val connection = super.onCreateInputConnection(attrs) + if (inputType == 0) attrs.inputType = attrs.inputType or + InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS + else if (inputType == 1) attrs.inputType = + InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or + InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD + return connection + } + + override fun startActionMode(callback: ActionMode.Callback?): ActionMode? { + return suppress(super.startActionMode(wrap(callback))) + } + + override fun startActionMode(callback: ActionMode.Callback?, type: Int): ActionMode? { + return suppress(super.startActionMode(wrap(callback), type)) + } + + override fun startActionModeForChild( + child: View?, + callback: ActionMode.Callback? + ): ActionMode? { + return suppress(super.startActionModeForChild(child, wrap(callback))) + } + + override fun startActionModeForChild( + child: View?, + callback: ActionMode.Callback?, + type: Int + ): ActionMode? { + return suppress(super.startActionModeForChild(child, wrap(callback), type)) + } + + private fun wrap(callback: ActionMode.Callback?): ActionMode.Callback? { + if (!nativeContextMenuDisabled || callback == null) return callback + return object : ActionMode.Callback2() { + override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean { + val created = callback.onCreateActionMode(mode, menu) + if (created) suppressUi(mode, menu) + return created + } + + override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean { + val prepared = callback.onPrepareActionMode(mode, menu) + suppressUi(mode, menu) + return prepared + } + + override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean { + return callback.onActionItemClicked(mode, item) + } + + override fun onDestroyActionMode(mode: ActionMode?) { + callback.onDestroyActionMode(mode) + } + + override fun onGetContentRect(mode: ActionMode?, view: View?, rect: Rect?) { + if (callback is ActionMode.Callback2) callback.onGetContentRect(mode, view, rect) + else super.onGetContentRect(mode, view, rect) + } + } + } + + private fun suppress(mode: ActionMode?): ActionMode? { + if (nativeContextMenuDisabled && mode != null) suppressUi( + mode, + mode.menu + ) + return mode + } + + private fun suppressUi(mode: ActionMode?, menu: Menu?) { + if (mode == null || !nativeContextMenuDisabled || menu == null) return + menu.clear() + mode.title = null + mode.subtitle = null + post { + if (!nativeContextMenuDisabled) return@post + try { + mode.hide(0) + } catch (ignored: Throwable) { + } + } + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/Dialogs.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/Dialogs.kt new file mode 100644 index 0000000000..622c5172a2 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/Dialogs.kt @@ -0,0 +1,120 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package com.foxdebug.acode.runtime.webview + +import android.R +import android.app.AlertDialog +import android.content.Context +import android.content.DialogInterface +import android.view.KeyEvent +import android.widget.EditText + +/** + * Helper class for WebViews to implement prompt(), alert(), confirm() dialogs. + */ +class Dialogs(private val context: Context?) { + private var lastHandledDialog: AlertDialog? = null + + fun showAlert(message: String?, result: Result) { + val dlg = AlertDialog.Builder(context) + dlg.setMessage(message) + dlg.setTitle("Alert") + //Don't let alerts break the back button + dlg.setCancelable(true) + dlg.setPositiveButton( + R.string.ok + ) { dialog, which -> result.gotResult(true, null) } + dlg.setOnCancelListener { result.gotResult(false, null) } + dlg.setOnKeyListener(object : DialogInterface.OnKeyListener { + //DO NOTHING + override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent?): Boolean { + if (keyCode == KeyEvent.KEYCODE_BACK) { + result.gotResult(true, null) + return false + } else return true + } + }) + lastHandledDialog = dlg.show() + } + + fun showConfirm(message: String?, result: Result) { + val dlg = AlertDialog.Builder(context) + dlg.setMessage(message) + dlg.setTitle("Confirm") + dlg.setCancelable(true) + dlg.setPositiveButton( + R.string.ok + ) { dialog, which -> result.gotResult(true, null) } + dlg.setNegativeButton( + R.string.cancel + ) { dialog, which -> result.gotResult(false, null) } + dlg.setOnCancelListener { result.gotResult(false, null) } + dlg.setOnKeyListener(object : DialogInterface.OnKeyListener { + //DO NOTHING + override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent?): Boolean { + if (keyCode == KeyEvent.KEYCODE_BACK) { + result.gotResult(false, null) + return false + } else return true + } + }) + lastHandledDialog = dlg.show() + } + + /** + * Tell the client to display a prompt dialog to the user. + * If the client returns true, WebView will assume that the client will + * handle the prompt dialog and call the appropriate JsPromptResult method. + * + * + * Since we are hacking prompts for our own purposes, we should not be using them for + * this purpose, perhaps we should hack console.log to do this instead! + */ + fun showPrompt(message: String?, defaultValue: String?, result: Result) { + // Returning false would also show a dialog, but the default one shows the origin (ugly). + val dlg = AlertDialog.Builder(context) + dlg.setMessage(message) + val input = EditText(context) + if (defaultValue != null) { + input.setText(defaultValue) + } + dlg.setView(input) + dlg.setCancelable(false) + dlg.setPositiveButton( + R.string.ok + ) { dialog, which -> + val userText = input.text.toString() + result.gotResult(true, userText) + } + dlg.setNegativeButton( + R.string.cancel + ) { dialog, which -> result.gotResult(false, null) } + lastHandledDialog = dlg.show() + } + + fun destroyLastDialog() { + if (lastHandledDialog != null) { + lastHandledDialog!!.cancel() + } + } + + fun interface Result { + fun gotResult(success: Boolean, value: String?) + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/FileChooser.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/FileChooser.kt new file mode 100644 index 0000000000..f8b275bf7d --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/FileChooser.kt @@ -0,0 +1,179 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package com.foxdebug.acode.runtime.webview + +import android.app.Activity +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.provider.MediaStore +import android.util.Log +import android.webkit.ValueCallback +import android.webkit.WebChromeClient.FileChooserParams +import android.webkit.WebView +import androidx.core.content.FileProvider +import com.foxdebug.acode.runtime.Host +import com.foxdebug.acode.runtime.Service +import java.io.File +import java.io.IOException + +internal class FileChooser(private val host: Host) { + fun show( + webView: WebView, + filePathsCallback: ValueCallback<Array<Uri?>?>, + fileChooserParams: FileChooserParams + ): Boolean { + val fileIntent = fileChooserParams.createIntent() + + // Check if multiple-select is specified + var selectMultiple = false + if (fileChooserParams.getMode() == + FileChooserParams.MODE_OPEN_MULTIPLE + ) { + selectMultiple = true + } + fileIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, selectMultiple) + + // Uses Intent.EXTRA_MIME_TYPES to pass multiple mime types. + val acceptTypes = fileChooserParams.getAcceptTypes() + if (acceptTypes.size > 1) { + fileIntent.setType("*/*") // Accept all, filter mime types by Intent.EXTRA_MIME_TYPES. + fileIntent.putExtra(Intent.EXTRA_MIME_TYPES, acceptTypes) + } + + // Image from camera intent + var tempUri: Uri? = null + var captureIntent: Intent? = null + if (fileChooserParams.isCaptureEnabled()) { + captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) + val context = webView.getContext() + if (context + .getPackageManager() + .hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY) && + captureIntent.resolveActivity(context.getPackageManager()) != null + ) { + try { + val tempFile = createTempFile(context) + Log.d(LOG_TAG, "Temporary photo capture file: " + tempFile) + tempUri = createUriForFile(context, tempFile) + Log.d(LOG_TAG, "Temporary photo capture URI: " + tempUri) + captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri) + } catch (e: IOException) { + Log.e( + LOG_TAG, + "Unable to create temporary file for photo capture", + e + ) + captureIntent = null + } + } else { + Log.w(LOG_TAG, "Device does not support photo capture") + captureIntent = null + } + } + val captureUri = tempUri + + // Chooser intent + val chooserIntent = Intent.createChooser(fileIntent, null) + if (captureIntent != null) { + chooserIntent.putExtra( + Intent.EXTRA_INITIAL_INTENTS, arrayOf<Intent>( + captureIntent, + ) + ) + } + + try { + Log.i(LOG_TAG, "Starting intent for file chooser") + host.startActivityForResult( + object : Service() { + public override fun onActivityResult( + requestCode: Int, + resultCode: Int, + intent: Intent? + ) { + // Handle result + var result: Array<Uri?>? = null + if (resultCode == Activity.RESULT_OK) { + val uris: MutableList<Uri?> = ArrayList<Uri?>() + + if (intent != null && intent.getData() != null) { + // single file + Log.v( + LOG_TAG, + "Adding file (single): " + intent.getData() + ) + uris.add(intent.getData()) + } else if (captureUri != null) { + // camera + Log.v(LOG_TAG, "Adding camera capture: " + captureUri) + uris.add(captureUri) + } else if (intent != null && intent.getClipData() != null) { + // multiple files + val clipData = intent.getClipData() + val count = clipData!!.getItemCount() + for (i in 0..<count) { + val uri = clipData.getItemAt(i).getUri() + Log.v(LOG_TAG, "Adding file (multiple): " + uri) + if (uri != null) { + uris.add(uri) + } + } + } + + if (!uris.isEmpty()) { + Log.d(LOG_TAG, "Receive file chooser URL: " + uris) + result = uris.toTypedArray<Uri?>() + } + } + filePathsCallback.onReceiveValue(result) + } + }, + chooserIntent, + 0 + ) + } catch (e: ActivityNotFoundException) { + Log.w( + LOG_TAG, + "No activity found to handle file chooser intent.", + e + ) + filePathsCallback.onReceiveValue(null) + } + return true + } + + @Throws(IOException::class) + private fun createTempFile(context: Context): File { + // Create an image file name + return File.createTempFile("temp", ".jpg", context.getCacheDir()) + } + + @Throws(IOException::class) + private fun createUriForFile(context: Context, tempFile: File): Uri? { + val appId = context.getPackageName() + return FileProvider.getUriForFile(context, appId + ".provider", tempFile) + } + + companion object { + private const val LOG_TAG = "AcodeFileChooser" + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/ImmersiveFullscreen.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/ImmersiveFullscreen.kt new file mode 100644 index 0000000000..b3e1e043a0 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/runtime/webview/ImmersiveFullscreen.kt @@ -0,0 +1,208 @@ +package com.foxdebug.acode.runtime.webview + +import android.app.Activity +import android.content.pm.ActivityInfo +import android.os.Build +import android.view.View +import android.view.View.OnAttachStateChangeListener +import android.view.ViewTreeObserver +import android.view.ViewTreeObserver.OnWindowFocusChangeListener +import android.view.Window +import android.view.WindowManager +import androidx.core.view.OnApplyWindowInsetsListener +import androidx.core.view.ViewCompat +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.WindowInsetsControllerCompat + +/** Owns window state only while Acode is displaying a browser fullscreen view. */ +internal class ImmersiveFullscreen + (private val activity: Activity, private var resumed: Boolean, private val onExit: Runnable) : + OnWindowFocusChangeListener, OnAttachStateChangeListener { + private val window: Window + private val decor: View + private val controller: WindowInsetsControllerCompat + private var fullscreenView: View? = null + private var focusObserver: ViewTreeObserver? = null + private var statusBarVisible = false + private var navigationBarVisible = false + private var previousBehavior = 0 + private var previousCutoutMode = 0 + private var previousLegacyFlags = 0 + private var requestedOrientation: Int? = null + private var previousOrientation = 0 + private var orientationApplied = false + + init { + window = activity.getWindow() + decor = window.getDecorView() + controller = WindowCompat.getInsetsController(window, decor) + } + + @Suppress("deprecation") + fun enter(view: View) { + if (fullscreenView != null) return + + val insets = ViewCompat.getRootWindowInsets(decor) + val flags = decor.getSystemUiVisibility() + statusBarVisible = + if (insets != null) + insets.isVisible(WindowInsetsCompat.Type.statusBars()) + else + (flags and View.SYSTEM_UI_FLAG_FULLSCREEN) == 0 && + (window.getAttributes().flags and + WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0 + navigationBarVisible = + if (insets != null) + insets.isVisible(WindowInsetsCompat.Type.navigationBars()) + else + (flags and View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0 + previousBehavior = controller.getSystemBarsBehavior() + previousLegacyFlags = flags and LEGACY_FULLSCREEN_FLAGS + if (Build.VERSION.SDK_INT >= 28) { + val attributes = window.getAttributes() + previousCutoutMode = attributes.layoutInDisplayCutoutMode + attributes.layoutInDisplayCutoutMode = + if (Build.VERSION.SDK_INT >= 30) + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS + else + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES + window.setAttributes(attributes) + } + + fullscreenView = view + // The wrapper fills Acode's root, with no status/navigation bar margins. + // Only the keyboard should shrink the usable area. Leave the root's inset + // listener alone so normal editor layout is unchanged on exit. + ViewCompat.setOnApplyWindowInsetsListener( + view, + OnApplyWindowInsetsListener { target: View?, appliedInsets: WindowInsetsCompat? -> + val bottom = appliedInsets!! + .getInsets(WindowInsetsCompat.Type.ime()) + .bottom + target!!.setPadding(0, 0, 0, bottom) + appliedInsets + }) + view.addOnAttachStateChangeListener(this) + focusObserver = decor.getViewTreeObserver() + focusObserver!!.addOnWindowFocusChangeListener(this) + reapply() + ViewCompat.requestApplyInsets(view) + } + + fun reapply() { + if (!resumed || fullscreenView == null || !fullscreenView!!.isAttachedToWindow() || !decor.hasWindowFocus() + ) return + controller.setSystemBarsBehavior( + WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + ) + controller.hide(WindowInsetsCompat.Type.systemBars()) + } + + fun lockOrientation(orientation: String?) { + val requested: Int + if ("landscape" == orientation) { + requested = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE + } else if ("portrait" == orientation) { + requested = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT + } else { + throw IllegalArgumentException( + "Orientation must be landscape or portrait." + ) + } + check( + !(!resumed || fullscreenView == null || !fullscreenView!!.isAttachedToWindow() + ) + ) { "Orientation requires foreground fullscreen." } + + val previous = activity.getRequestedOrientation() + activity.setRequestedOrientation(requested) + // Only a successful first request owns the restoration state. Changing + // modes or resuming this session must not replace it with our own override. + if (requestedOrientation == null) previousOrientation = previous + requestedOrientation = requested + orientationApplied = true + } + + fun unlockOrientation() { + restoreOrientation() + requestedOrientation = null + } + + fun pause() { + resumed = false + restoreOrientation() + } + + fun resume() { + resumed = true + if (fullscreenView != null && + fullscreenView!!.isAttachedToWindow() && requestedOrientation != null + ) { + activity.setRequestedOrientation(requestedOrientation!!) + orientationApplied = true + } + reapply() + } + + private fun restoreOrientation() { + if (!orientationApplied) return + activity.setRequestedOrientation(previousOrientation) + orientationApplied = false + } + + @Suppress("deprecation") + fun exit() { + if (fullscreenView == null) return + val view = fullscreenView + fullscreenView = null + onExit.run() + unlockOrientation() + view!!.removeOnAttachStateChangeListener(this) + ViewCompat.setOnApplyWindowInsetsListener(view, null) + view.setPadding(0, 0, 0, 0) + if (focusObserver!!.isAlive() + ) focusObserver!!.removeOnWindowFocusChangeListener(this) + focusObserver = null + + controller.setSystemBarsBehavior(previousBehavior) + restoreBar(WindowInsetsCompat.Type.statusBars(), statusBarVisible) + restoreBar(WindowInsetsCompat.Type.navigationBars(), navigationBarVisible) + if (Build.VERSION.SDK_INT < 30) { + // Restore only the bits we own; keep any theme changes made meanwhile. + decor.setSystemUiVisibility( + (decor.getSystemUiVisibility() and LEGACY_FULLSCREEN_FLAGS.inv()) or + previousLegacyFlags + ) + } + if (Build.VERSION.SDK_INT >= 28) { + val attributes = window.getAttributes() + attributes.layoutInDisplayCutoutMode = previousCutoutMode + window.setAttributes(attributes) + } + ViewCompat.requestApplyInsets(decor) + } + + private fun restoreBar(type: Int, visible: Boolean) { + if (visible) controller.show(type) + else controller.hide(type) + } + + override fun onWindowFocusChanged(hasFocus: Boolean) { + if (hasFocus) reapply() + } + + override fun onViewAttachedToWindow(view: View) {} + + override fun onViewDetachedFromWindow(view: View) { + exit() + } + + companion object { + @Deprecated("Using old methods, needs rewrite") + private const val LEGACY_FULLSCREEN_FLAGS = View.SYSTEM_UI_FLAG_FULLSCREEN or + View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or + View.SYSTEM_UI_FLAG_IMMERSIVE or + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY + } +} diff --git a/src/plugins/sdcard/src/android/SDcard.java b/platforms/android/app/src/main/java/com/foxdebug/acode/sdcard/SDcard.java similarity index 93% rename from src/plugins/sdcard/src/android/SDcard.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/sdcard/SDcard.java index 578d33dda3..5e902b4eb7 100644 --- a/src/plugins/sdcard/src/android/SDcard.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/sdcard/SDcard.java @@ -1,4 +1,4 @@ -package com.foxdebug.sdcard; +package com.foxdebug.acode.sdcard; import android.app.Activity; import android.content.ContentResolver; @@ -6,7 +6,6 @@ import android.content.Intent; import android.database.Cursor; import android.net.Uri; -import android.os.Build; import android.os.Environment; import android.os.FileObserver; import android.os.storage.StorageManager; @@ -32,19 +31,19 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; -import java.util.Map; + import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaInterface; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.CordovaWebView; -import org.apache.cordova.PluginResult; + +import com.foxdebug.acode.runtime.BridgeContext; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Service; +import com.foxdebug.acode.runtime.Payload; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -public class SDcard extends CordovaPlugin { +public class SDcard extends Service { private int mode; private int SDK_INT = android.os.Build.VERSION.SDK_INT; @@ -59,15 +58,15 @@ public class SDcard extends CordovaPlugin { private Activity activity; private ContentResolver contentResolver; private DocumentFile originalRootFile; - private CallbackContext activityResultCallback; + private Callback activityResultCallback; private HashMap<String, MyFileObserver> fileObservers = new HashMap(); private WorkspaceIndex workspaceIndex; - public void initialize(CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); + public void initialize(BridgeContext bridgeContext) { + super.initialize(bridgeContext); this.REQUEST_CODE = this.ACCESS_INTENT; - this.context = cordova.getContext(); - this.activity = cordova.getActivity(); + this.context = bridgeContext.getWebActivity(); + this.activity = bridgeContext.getWebActivity(); this.contentResolver = this.context.getContentResolver(); this.workspaceIndex = new WorkspaceIndex(this.context); this.storageManager = (StorageManager) this.activity.getSystemService( @@ -78,7 +77,7 @@ public void initialize(CordovaInterface cordova, CordovaWebView webView) { public boolean execute( String action, JSONArray args, - CallbackContext callback + Callback callback ) throws JSONException { String arg1 = null, arg2 = null, arg3 = null, arg4 = null; int argLen = args.length(); @@ -225,7 +224,7 @@ private String formatUri(String filename) { private void watchFile( final String fileUri, final String id, - final CallbackContext listener + final Callback listener ) { activity.runOnUiThread( new Runnable() { @@ -260,7 +259,7 @@ private void unwatchFile(String id) { fileObservers.remove(id); } - public void openDocumentFile(String mimeType, CallbackContext callback) { + public void openDocumentFile(String mimeType, Callback callback) { Intent intent = new Intent(); if (mimeType == null) mimeType = "*/*"; intent.setAction(Intent.ACTION_OPEN_DOCUMENT); @@ -272,20 +271,20 @@ public void openDocumentFile(String mimeType, CallbackContext callback) { Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION ); activityResultCallback = callback; - cordova.startActivityForResult(this, intent, this.OPEN_DOCUMENT); + host.startActivityForResult(this, intent, this.OPEN_DOCUMENT); } - public void getImage(String mimeType, CallbackContext callback) { + public void getImage(String mimeType, Callback callback) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); if (mimeType == null) mimeType = "image/*"; intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType(mimeType); activityResultCallback = callback; - cordova.startActivityForResult(this, intent, this.PICK_FROM_GALLERY); + host.startActivityForResult(this, intent, this.PICK_FROM_GALLERY); } - public void getStorageVolumes(CallbackContext callback) { + public void getStorageVolumes(Callback callback) { try { JSONArray result = new JSONArray(); @@ -329,7 +328,7 @@ public void getStorageVolumes(CallbackContext callback) { } } - public void getStorageAccess(String SDCardUUID, CallbackContext callback) { + public void getStorageAccess(String SDCardUUID, Callback callback) { Intent intent = null; if (SDK_INT >= 24) { @@ -357,7 +356,7 @@ public void getStorageAccess(String SDCardUUID, CallbackContext callback) { } activityResultCallback = callback; - cordova.startActivityForResult(this, intent, REQUEST_CODE); + host.startActivityForResult(this, intent, REQUEST_CODE); } public void onActivityResult(int requestCode, int resultCode, Intent data) { @@ -473,8 +472,8 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) { } } - private void readFile(String filename, CallbackContext callback) { - cordova + private void readFile(String filename, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -506,8 +505,8 @@ public void run() { ); } - private void readAsText(final String filename, final String encoding, final CallbackContext callback) { - cordova + private void readAsText(final String filename, final String encoding, final Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -556,11 +555,11 @@ private void writeText( final String filename, final String content, final String encoding, - final CallbackContext callback + final Callback callback ) { final Context context = this.context; - cordova + host .getThreadPool() .execute( new Runnable() { @@ -606,11 +605,11 @@ private void writeFile( final String filename, final String content, final Boolean isArrayBuffer, - final CallbackContext callback + final Callback callback ) { final Context context = this.context; - cordova + host .getThreadPool() .execute( new Runnable() { @@ -651,14 +650,14 @@ public void run() { ); } - private void createDir(String parent, String name, CallbackContext callback) { + private void createDir(String parent, String name, Callback callback) { create(parent, name, Document.MIME_TYPE_DIR, callback); } private void createFile( String parent, String name, - CallbackContext callback + Callback callback ) { String mimeType = URLConnection.guessContentTypeFromName(name); String ext = FilenameUtils.getExtension(name); @@ -673,9 +672,9 @@ private void create( String parent, String name, String mimeType, - CallbackContext callback + Callback callback ) { - cordova + host .getThreadPool() .execute( new Runnable() { @@ -733,9 +732,9 @@ public void run() { private void rename( String filename, String newFile, - CallbackContext callback + Callback callback ) { - cordova + host .getThreadPool() .execute( new Runnable() { @@ -775,10 +774,10 @@ public void run() { ); } - private void delete(String filename, CallbackContext callback) { + private void delete(String filename, Callback callback) { final ContentResolver contentResolver = context.getContentResolver(); - cordova + host .getThreadPool() .execute( new Runnable() { @@ -804,14 +803,14 @@ public void run() { ); } - private void move(String src, String dest, final CallbackContext callback) { + private void move(String src, String dest, final Callback callback) { final ContentResolver contentResolver = this.context.getContentResolver(); final String splittedStr[] = src.split(SEPARATOR, 2); final String rootUri = splittedStr[0]; final String srcId = splittedStr[1]; final String destId = dest.split(SEPARATOR, 2)[1]; - cordova + host .getThreadPool() .execute( new Runnable() { @@ -837,13 +836,13 @@ public void run() { ); } - private void copy(String src, String dest, final CallbackContext callback) { + private void copy(String src, String dest, final Callback callback) { final String splittedStr[] = src.split(SEPARATOR, 2); final String srcUri = splittedStr[0]; final String srcId = splittedStr[1]; final String destId = dest.split(SEPARATOR, 2)[1]; - cordova + host .getThreadPool() .execute( new Runnable() { @@ -943,8 +942,8 @@ private Uri copyFile(DocumentFile src, DocumentFile dest) } } - private void listDir(String src, String parentId, CallbackContext callback) { - cordova + private void listDir(String src, String parentId, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -1039,8 +1038,8 @@ private boolean isDirectory(String mimeType) { return DocumentsContract.Document.MIME_TYPE_DIR.equals(mimeType); } - private void getStats(String filename, CallbackContext callback) { - cordova + private void getStats(String filename, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -1079,7 +1078,7 @@ private Uri getUri(String src, String docId) { return DocumentsContract.buildDocumentUriUsingTree(srcUri, docId); } - private void exists(String path, CallbackContext callback) { + private void exists(String path, Callback callback) { DocumentFile file = DocumentFile.fromSingleUri(context, Uri.parse(path)); if (file == null) { @@ -1093,11 +1092,11 @@ private void exists(String path, CallbackContext callback) { } } - private void error(String err, CallbackContext callback) { + private void error(String err, Callback callback) { callback.error("ERROR: " + err); } - private void getPath(String uriString, String src, CallbackContext callback) { + private void getPath(String uriString, String src, Callback callback) { try { DocumentFile file = geRelativeDocumentFile(uriString, src); @@ -1202,17 +1201,17 @@ public boolean canWrite(Uri uri) { class MyFileObserver extends FileObserver { - private CallbackContext listener; + private Callback listener; private static final int mask = (FileObserver.DELETE_SELF | FileObserver.MODIFY | FileObserver.MOVE_SELF); - public MyFileObserver(String path, CallbackContext listener) { + public MyFileObserver(String path, Callback listener) { super(path, mask); this.listener = listener; Log.d("MyFileObserver", "MyFileObserver: " + path); } - public MyFileObserver(File file, CallbackContext listener) { + public MyFileObserver(File file, Callback listener) { super(file, mask); this.listener = listener; Log.d("MyFileObserver", "MyFileObserver: " + file.getAbsolutePath()); @@ -1221,9 +1220,9 @@ public MyFileObserver(File file, CallbackContext listener) { @Override public void onEvent(int event, String path) { Log.d("MyFileObserver", "onEvent: " + event); - PluginResult result = new PluginResult(PluginResult.Status.OK); + Payload result = new Payload(Payload.Status.OK); result.setKeepCallback(true); - listener.sendPluginResult(result); + listener.sendPayload(result); } public void startObserving() { diff --git a/src/plugins/sdcard/src/android/WorkspaceIndex.java b/platforms/android/app/src/main/java/com/foxdebug/acode/sdcard/WorkspaceIndex.java similarity index 98% rename from src/plugins/sdcard/src/android/WorkspaceIndex.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/sdcard/WorkspaceIndex.java index 8215bee157..eb23a64eb1 100644 --- a/src/plugins/sdcard/src/android/WorkspaceIndex.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/sdcard/WorkspaceIndex.java @@ -1,4 +1,4 @@ -package com.foxdebug.sdcard; +package com.foxdebug.acode.sdcard; import android.content.ContentResolver; import android.content.ContentValues; @@ -33,8 +33,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.PluginResult; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Payload; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -211,7 +211,7 @@ class WorkspaceIndex { this.db = new DB(this.context); } - void scan(JSONObject options, CallbackContext callback) { + void scan(JSONObject options, Callback callback) { final String id = options.optString("id", UUID.randomUUID().toString()); final Job job = new Job(id); jobs.put(id, job); @@ -229,7 +229,7 @@ void scan(JSONObject options, CallbackContext callback) { ); } - void update(JSONObject options, CallbackContext callback) { + void update(JSONObject options, Callback callback) { indexExecutor.execute( () -> { try { @@ -241,7 +241,7 @@ void update(JSONObject options, CallbackContext callback) { ); } - void search(JSONObject options, CallbackContext callback) { + void search(JSONObject options, Callback callback) { final String id = options.optString("id", UUID.randomUUID().toString()); final Job job = new Job(id); jobs.put(id, job); @@ -259,7 +259,7 @@ void search(JSONObject options, CallbackContext callback) { ); } - void query(JSONObject options, CallbackContext callback) { + void query(JSONObject options, Callback callback) { executor.execute( () -> { try { @@ -303,7 +303,7 @@ void clear(JSONArray roots) { } } - private void runScan(Job job, JSONObject options, CallbackContext callback) + private void runScan(Job job, JSONObject options, Callback callback) throws Exception { if (job.cancelled) { send(callback, baseEvent(job.id, "cancelled"), false); @@ -664,7 +664,7 @@ private int deleteIndexedSubtree( private void scanFileDir( Job job, - CallbackContext callback, + Callback callback, String rootUrl, File dir, String parentUrl, @@ -743,7 +743,7 @@ private void scanFileDir( private void scanSafDir( Job job, - CallbackContext callback, + Callback callback, String treeUrl, String rootUrl, String parentDocId, @@ -854,7 +854,7 @@ private void scanSafDir( } private void addEntry( - CallbackContext callback, + Callback callback, String id, JSONArray batch, FileEntry entry, @@ -938,7 +938,7 @@ private JSONObject runQuery(JSONObject options) throws Exception { return result; } - private void flushBatch(CallbackContext callback, String id, JSONArray batch) + private void flushBatch(Callback callback, String id, JSONArray batch) throws JSONException { if (batch.length() == 0) return; JSONObject event = baseEvent(id, "batch"); @@ -947,7 +947,7 @@ private void flushBatch(CallbackContext callback, String id, JSONArray batch) while (batch.length() > 0) batch.remove(0); } - private void runSearch(Job job, JSONObject options, CallbackContext callback) + private void runSearch(Job job, JSONObject options, Callback callback) throws Exception { JSONArray files = options.optJSONArray("files"); if (files == null) files = new JSONArray(); @@ -1177,7 +1177,7 @@ private void searchInContent( String content, Pattern pattern, Job job, - CallbackContext callback, + Callback callback, boolean batchResults ) throws JSONException { SearchInput input = new SearchInput(content, job); @@ -1237,7 +1237,7 @@ private void searchInContent( sendSearchMatches(callback, job.id, file, matches, batchResults, false); } - private void sendSearchMatches(CallbackContext callback, String id, JSONObject file, + private void sendSearchMatches(Callback callback, String id, JSONObject file, JSONArray matches, boolean batchResults, boolean limited) throws JSONException { if (matches.length() == 0) return; JSONObject data = new JSONObject(); @@ -1754,7 +1754,7 @@ private String[] getSurrounding(String content, String word, int start, int end) } private void sendStatus( - CallbackContext callback, + Callback callback, String id, String state, String message, @@ -1768,7 +1768,7 @@ private void sendStatus( send(callback, event, keep); } - private void sendProgress(CallbackContext callback, String id, int progress) + private void sendProgress(Callback callback, String id, int progress) throws JSONException { JSONObject event = baseEvent(id, "progress"); event.put("data", progress); @@ -1783,13 +1783,13 @@ private JSONObject baseEvent(String id, String type) throws JSONException { return event; } - private void send(CallbackContext callback, JSONObject event, boolean keep) { - PluginResult result = new PluginResult(PluginResult.Status.OK, event); + private void send(Callback callback, JSONObject event, boolean keep) { + Payload result = new Payload(Payload.Status.OK, event); result.setKeepCallback(keep); - callback.sendPluginResult(result); + callback.sendPayload(result); } - private void sendError(CallbackContext callback, String id, Exception error) { + private void sendError(Callback callback, String id, Exception error) { try { JSONObject event = baseEvent(id, "error"); event.put("error", error.getMessage() == null ? error.toString() : error.getMessage()); diff --git a/src/plugins/pluginContext/src/android/Tee.java b/platforms/android/app/src/main/java/com/foxdebug/acode/security/Tee.java similarity index 95% rename from src/plugins/pluginContext/src/android/Tee.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/security/Tee.java index 22e5bdea36..445509a8d4 100644 --- a/src/plugins/pluginContext/src/android/Tee.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/security/Tee.java @@ -1,7 +1,7 @@ -package com.foxdebug.acode.rk.plugin; +package com.foxdebug.acode.security; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaPlugin; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Service; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -14,12 +14,12 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import android.content.Context; -import org.apache.cordova.*; +import com.foxdebug.acode.runtime.*; //auth plugin -import com.foxdebug.acode.rk.auth.EncryptedPreferenceManager; +import com.foxdebug.acode.auth.EncryptedPreferenceManager; -public class Tee extends CordovaPlugin { +public class Tee extends Service { // pluginId : token private final Map<String, String> tokenStore = new ConcurrentHashMap<>(); @@ -38,9 +38,9 @@ public class Tee extends CordovaPlugin { private Context context; - public void initialize(CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); - this.context = cordova.getContext(); + public void initialize(BridgeContext bridgeContext) { + super.initialize(bridgeContext); + this.context = host.getContext(); } @Override @@ -52,7 +52,7 @@ public void onReset() { } @Override - public boolean execute(String action, JSONArray args, CallbackContext callback) + public boolean execute(String action, JSONArray args, Callback callback) throws JSONException { if ("establishConnection".equals(action)) { @@ -257,7 +257,7 @@ public List<String> listAllPermissions(String token) { private synchronized void handleTokenRequest( String pluginId, String pluginJson, - CallbackContext callback + Callback callback ) { String token = tokenStore.get(pluginId); diff --git a/src/plugins/server/src/android/com/foxdebug/server/NanoHTTPDWebserver.java b/platforms/android/app/src/main/java/com/foxdebug/acode/server/NanoHTTPDWebserver.java similarity index 94% rename from src/plugins/server/src/android/com/foxdebug/server/NanoHTTPDWebserver.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/server/NanoHTTPDWebserver.java index c6f1a0fa0d..da9e469933 100644 --- a/src/plugins/server/src/android/com/foxdebug/server/NanoHTTPDWebserver.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/server/NanoHTTPDWebserver.java @@ -1,121 +1,121 @@ -package com.foxdebug.server; - -import android.content.ContentResolver; -import android.content.Context; -import android.net.Uri; -import android.util.Log; -import androidx.documentfile.provider.DocumentFile; -import fi.iki.elonen.NanoHTTPD; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Method; -import java.net.URLConnection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.UUID; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.PluginResult; -import org.json.JSONException; -import org.json.JSONObject; - -public class NanoHTTPDWebserver extends NanoHTTPD { - - public HashMap<String, Object> responses; - public CallbackContext onRequestCallbackContext; - Context context; - - public NanoHTTPDWebserver(int port, Context context) { - super(port); - this.context = context; - this.responses = new HashMap<String, Object>(); - } - - private String getBodyText(IHTTPSession session) { - Map<String, String> files = new HashMap<String, String>(); - Method method = session.getMethod(); - if (Method.PUT.equals(method) || Method.POST.equals(method)) { - try { - session.parseBody(files); - } catch (IOException ioe) { - return "{}"; - } catch (ResponseException re) { - return "{}"; - } - } - // get the POST body - return files.get("postData"); - } - - /** - * Create a request object - * <p> - * [ "requestId": requestUUID, " body": request.jsonObject ?? "", " headers": - * request.headers, " method": request.method, " path": request.url.path, " - * query": request.url.query ?? "" ] - * - * @param session - * @return - */ - private JSONObject createJSONRequest(String requestId, IHTTPSession session) - throws JSONException { - JSONObject jsonRequest = new JSONObject(); - jsonRequest.put("requestId", requestId); - jsonRequest.put("body", this.getBodyText(session)); - jsonRequest.put("headers", session.getHeaders()); - jsonRequest.put("method", session.getMethod()); - jsonRequest.put("path", session.getUri()); - jsonRequest.put("query", session.getQueryParameterString()); - return jsonRequest; - } - - private String getContentType(JSONObject responseObject) - throws JSONException { - if ( - responseObject.has("headers") && - responseObject.getJSONObject("headers").has("Content-Type") - ) { - return responseObject.getJSONObject("headers").getString("Content-Type"); - } else { - return "text/plain"; - } - } - - private Response newFixedFileResponse(DocumentFile file, String mime) - throws FileNotFoundException, IOException { - Response res; - res = - newFixedLengthResponse( - Response.Status.OK, - mime, - getInputStream(file), - (int) file.length() - ); - res.addHeader("Accept-Ranges", "bytes"); - return res; - } - - Response serveFile( - Map<String, String> header, - DocumentFile file, - String mime - ) { - Response res; - try { - // Calculate etag - long fileLen = file.length(); - String path = file.getUri().toString(); - String etag = Integer.toHexString( - (path + file.lastModified() + "" + fileLen).hashCode() - ); - - // Support (simple) skipping: - long startFrom = 0; - long endAt = -1; - String range = header.get("range"); - if (range != null) { +package com.foxdebug.acode.server; + +import android.content.ContentResolver; +import android.content.Context; +import android.net.Uri; +import android.util.Log; +import androidx.documentfile.provider.DocumentFile; +import fi.iki.elonen.NanoHTTPD; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.net.URLConnection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Payload; +import org.json.JSONException; +import org.json.JSONObject; + +public class NanoHTTPDWebserver extends NanoHTTPD { + + public HashMap<String, Object> responses; + public Callback onRequestCallbackContext; + Context context; + + public NanoHTTPDWebserver(int port, Context context) { + super(port); + this.context = context; + this.responses = new HashMap<String, Object>(); + } + + private String getBodyText(IHTTPSession session) { + Map<String, String> files = new HashMap<String, String>(); + Method method = session.getMethod(); + if (Method.PUT.equals(method) || Method.POST.equals(method)) { + try { + session.parseBody(files); + } catch (IOException ioe) { + return "{}"; + } catch (ResponseException re) { + return "{}"; + } + } + // get the POST body + return files.get("postData"); + } + + /** + * Create a request object + * <p> + * [ "requestId": requestUUID, " body": request.jsonObject ?? "", " headers": + * request.headers, " method": request.method, " path": request.url.path, " + * query": request.url.query ?? "" ] + * + * @param session + * @return + */ + private JSONObject createJSONRequest(String requestId, IHTTPSession session) + throws JSONException { + JSONObject jsonRequest = new JSONObject(); + jsonRequest.put("requestId", requestId); + jsonRequest.put("body", this.getBodyText(session)); + jsonRequest.put("headers", session.getHeaders()); + jsonRequest.put("method", session.getMethod()); + jsonRequest.put("path", session.getUri()); + jsonRequest.put("query", session.getQueryParameterString()); + return jsonRequest; + } + + private String getContentType(JSONObject responseObject) + throws JSONException { + if ( + responseObject.has("headers") && + responseObject.getJSONObject("headers").has("Content-Type") + ) { + return responseObject.getJSONObject("headers").getString("Content-Type"); + } else { + return "text/plain"; + } + } + + private Response newFixedFileResponse(DocumentFile file, String mime) + throws FileNotFoundException, IOException { + Response res; + res = + newFixedLengthResponse( + Response.Status.OK, + mime, + getInputStream(file), + (int) file.length() + ); + res.addHeader("Accept-Ranges", "bytes"); + return res; + } + + Response serveFile( + Map<String, String> header, + DocumentFile file, + String mime + ) { + Response res; + try { + // Calculate etag + long fileLen = file.length(); + String path = file.getUri().toString(); + String etag = Integer.toHexString( + (path + file.lastModified() + "" + fileLen).hashCode() + ); + + // Support (simple) skipping: + long startFrom = 0; + long endAt = -1; + String range = header.get("range"); + if (range != null) { if (range.startsWith("bytes=")) { range = range.substring("bytes=".length()); int minus = range.indexOf('-'); @@ -129,213 +129,213 @@ Response serveFile( } } } - - // get if-range header. If present, it must match etag or else we - // should ignore the range request - String ifRange = header.get("if-range"); - boolean headerIfRangeMissingOrMatching = - (ifRange == null || etag.equals(ifRange)); - - String ifNoneMatch = header.get("if-none-match"); - boolean headerIfNoneMatchPresentAndMatching = - ifNoneMatch != null && - ("*".equals(ifNoneMatch) || ifNoneMatch.equals(etag)); - - if ( - headerIfRangeMissingOrMatching && - range != null && - startFrom >= 0 && - startFrom < fileLen - ) { - // range request that matches current etag - // and the startFrom of the range is satisfiable - if (headerIfNoneMatchPresentAndMatching) { - // range request that matches current etag - // and the startFrom of the range is satisfiable - // would return range from file - // respond with not-modified - res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, ""); - res.addHeader("ETag", etag); - } else { - if (endAt < 0) { - endAt = fileLen - 1; - } - long newLen = endAt - startFrom + 1; - if (newLen < 0) { - newLen = 0; - } - - InputStream is = getInputStream(file); - is.skip(startFrom); - - res = - newFixedLengthResponse( - Response.Status.PARTIAL_CONTENT, - mime, - is, - newLen - ); - res.addHeader("Accept-Ranges", "bytes"); - res.addHeader("Content-Length", "" + newLen); - - String contentRange = - "bytes " + startFrom + "-" + endAt + "/" + fileLen; - res.addHeader("Content-Range", contentRange); - res.addHeader("ETag", etag); - } - } else { - if ( - headerIfRangeMissingOrMatching && - range != null && - startFrom >= fileLen - ) { - // return the size of the file - // 4xx responses are not trumped by if-none-match - res = - newFixedLengthResponse( - Response.Status.RANGE_NOT_SATISFIABLE, - NanoHTTPD.MIME_PLAINTEXT, - "" - ); - res.addHeader("Content-Range", "bytes */" + fileLen); - res.addHeader("ETag", etag); - } else if (range == null && headerIfNoneMatchPresentAndMatching) { - // full-file-fetch request - // would return entire file - // respond with not-modified - res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, ""); - res.addHeader("ETag", etag); - } else if ( - !headerIfRangeMissingOrMatching && headerIfNoneMatchPresentAndMatching - ) { - // range request that doesn't match current etag - // would return entire (different) file - // respond with not-modified - - res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, ""); - res.addHeader("ETag", etag); - } else { - // supply the file - res = newFixedFileResponse(file, mime); - res.addHeader("Content-Length", "" + fileLen); - res.addHeader("ETag", etag); - } - } - } catch (Exception e) { - Log.d("ServeFileError", e.getMessage()); - String type = e.getClass().getName(); - if (type.equals("FileNotFoundException")) res = - newFixedLengthResponse( - Response.Status.NOT_FOUND, - NanoHTTPD.MIME_PLAINTEXT, - e.getMessage() - ); else res = - newFixedLengthResponse( - Response.Status.FORBIDDEN, - NanoHTTPD.MIME_PLAINTEXT, - e.getMessage() - ); - } - - return res; - } - - @Override - public Response serve(IHTTPSession session) { - String requestUUID = UUID.randomUUID().toString(); - - PluginResult pluginResult = null; - try { - pluginResult = - new PluginResult( - PluginResult.Status.OK, - this.createJSONRequest(requestUUID, session) - ); - } catch (JSONException e) { - e.printStackTrace(); - } - pluginResult.setKeepCallback(true); - this.onRequestCallbackContext.sendPluginResult(pluginResult); - - while (!this.responses.containsKey(requestUUID)) { - try { - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - JSONObject responseObject = (JSONObject) this.responses.get(requestUUID); - Response response = null; - - if (responseObject.has("path")) { - try { - String path = responseObject.getString("path"); - DocumentFile file = getFile(path); - String mimeType = URLConnection.guessContentTypeFromName(path); - Response res = serveFile(session.getHeaders(), file, mimeType); - JSONObject headers = getJSONObject(responseObject, "headers"); - // JSONObject headers = responseObject.getJSONObject("headers"); - if (headers != null) { - Iterator<String> keys = headers.keys(); - while (keys.hasNext()) { - String key = (String) keys.next(); - res.addHeader( - key, - responseObject.getJSONObject("headers").getString(key) - ); - } - } - return res; - } catch (JSONException e) { - e.printStackTrace(); - } - return response; - } else { - try { - response = - newFixedLengthResponse( - Response.Status.lookup(responseObject.getInt("status")), - getContentType(responseObject), - responseObject.getString("body") - ); - - Iterator<?> keys = responseObject.getJSONObject("headers").keys(); - while (keys.hasNext()) { - String key = (String) keys.next(); - response.addHeader( - key, - responseObject.getJSONObject("headers").getString(key) - ); - } - } catch (JSONException e) { - e.printStackTrace(); - } - return response; - } - } - - private DocumentFile getFile(String filePath) { - Uri fileUri = Uri.parse(filePath); - DocumentFile documentFile = null; - if (filePath.matches("file:///(.*)")) { - File file = new File(fileUri.getPath()); - documentFile = DocumentFile.fromFile(file); - } else { - documentFile = - DocumentFile.fromSingleUri(this.context, Uri.parse(filePath)); - } - - return documentFile; - } - - private InputStream getInputStream(DocumentFile file) - throws FileNotFoundException, IOException { - Uri uri = file.getUri(); - ContentResolver contentResolver = context.getContentResolver(); - return contentResolver.openInputStream(uri); - } - + + // get if-range header. If present, it must match etag or else we + // should ignore the range request + String ifRange = header.get("if-range"); + boolean headerIfRangeMissingOrMatching = + (ifRange == null || etag.equals(ifRange)); + + String ifNoneMatch = header.get("if-none-match"); + boolean headerIfNoneMatchPresentAndMatching = + ifNoneMatch != null && + ("*".equals(ifNoneMatch) || ifNoneMatch.equals(etag)); + + if ( + headerIfRangeMissingOrMatching && + range != null && + startFrom >= 0 && + startFrom < fileLen + ) { + // range request that matches current etag + // and the startFrom of the range is satisfiable + if (headerIfNoneMatchPresentAndMatching) { + // range request that matches current etag + // and the startFrom of the range is satisfiable + // would return range from file + // respond with not-modified + res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, ""); + res.addHeader("ETag", etag); + } else { + if (endAt < 0) { + endAt = fileLen - 1; + } + long newLen = endAt - startFrom + 1; + if (newLen < 0) { + newLen = 0; + } + + InputStream is = getInputStream(file); + is.skip(startFrom); + + res = + newFixedLengthResponse( + Response.Status.PARTIAL_CONTENT, + mime, + is, + newLen + ); + res.addHeader("Accept-Ranges", "bytes"); + res.addHeader("Content-Length", "" + newLen); + + String contentRange = + "bytes " + startFrom + "-" + endAt + "/" + fileLen; + res.addHeader("Content-Range", contentRange); + res.addHeader("ETag", etag); + } + } else { + if ( + headerIfRangeMissingOrMatching && + range != null && + startFrom >= fileLen + ) { + // return the size of the file + // 4xx responses are not trumped by if-none-match + res = + newFixedLengthResponse( + Response.Status.RANGE_NOT_SATISFIABLE, + NanoHTTPD.MIME_PLAINTEXT, + "" + ); + res.addHeader("Content-Range", "bytes */" + fileLen); + res.addHeader("ETag", etag); + } else if (range == null && headerIfNoneMatchPresentAndMatching) { + // full-file-fetch request + // would return entire file + // respond with not-modified + res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, ""); + res.addHeader("ETag", etag); + } else if ( + !headerIfRangeMissingOrMatching && headerIfNoneMatchPresentAndMatching + ) { + // range request that doesn't match current etag + // would return entire (different) file + // respond with not-modified + + res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, ""); + res.addHeader("ETag", etag); + } else { + // supply the file + res = newFixedFileResponse(file, mime); + res.addHeader("Content-Length", "" + fileLen); + res.addHeader("ETag", etag); + } + } + } catch (Exception e) { + Log.d("ServeFileError", e.getMessage()); + String type = e.getClass().getName(); + if (type.equals("FileNotFoundException")) res = + newFixedLengthResponse( + Response.Status.NOT_FOUND, + NanoHTTPD.MIME_PLAINTEXT, + e.getMessage() + ); else res = + newFixedLengthResponse( + Response.Status.FORBIDDEN, + NanoHTTPD.MIME_PLAINTEXT, + e.getMessage() + ); + } + + return res; + } + + @Override + public Response serve(IHTTPSession session) { + String requestUUID = UUID.randomUUID().toString(); + + Payload pluginResult = null; + try { + pluginResult = + new Payload( + Payload.Status.OK, + this.createJSONRequest(requestUUID, session) + ); + } catch (JSONException e) { + e.printStackTrace(); + } + pluginResult.setKeepCallback(true); + this.onRequestCallbackContext.sendPayload(pluginResult); + + while (!this.responses.containsKey(requestUUID)) { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + JSONObject responseObject = (JSONObject) this.responses.get(requestUUID); + Response response = null; + + if (responseObject.has("path")) { + try { + String path = responseObject.getString("path"); + DocumentFile file = getFile(path); + String mimeType = URLConnection.guessContentTypeFromName(path); + Response res = serveFile(session.getHeaders(), file, mimeType); + JSONObject headers = getJSONObject(responseObject, "headers"); + // JSONObject headers = responseObject.getJSONObject("headers"); + if (headers != null) { + Iterator<String> keys = headers.keys(); + while (keys.hasNext()) { + String key = (String) keys.next(); + res.addHeader( + key, + responseObject.getJSONObject("headers").getString(key) + ); + } + } + return res; + } catch (JSONException e) { + e.printStackTrace(); + } + return response; + } else { + try { + response = + newFixedLengthResponse( + Response.Status.lookup(responseObject.getInt("status")), + getContentType(responseObject), + responseObject.getString("body") + ); + + Iterator<?> keys = responseObject.getJSONObject("headers").keys(); + while (keys.hasNext()) { + String key = (String) keys.next(); + response.addHeader( + key, + responseObject.getJSONObject("headers").getString(key) + ); + } + } catch (JSONException e) { + e.printStackTrace(); + } + return response; + } + } + + private DocumentFile getFile(String filePath) { + Uri fileUri = Uri.parse(filePath); + DocumentFile documentFile = null; + if (filePath.matches("file:///(.*)")) { + File file = new File(fileUri.getPath()); + documentFile = DocumentFile.fromFile(file); + } else { + documentFile = + DocumentFile.fromSingleUri(this.context, Uri.parse(filePath)); + } + + return documentFile; + } + + private InputStream getInputStream(DocumentFile file) + throws FileNotFoundException, IOException { + Uri uri = file.getUri(); + ContentResolver contentResolver = context.getContentResolver(); + return contentResolver.openInputStream(uri); + } + private JSONObject getJSONObject(JSONObject ob, String key) { JSONObject jsonObject = null; try { diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/server/Server.java b/platforms/android/app/src/main/java/com/foxdebug/acode/server/Server.java new file mode 100644 index 0000000000..3a15b7726a --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/server/Server.java @@ -0,0 +1,134 @@ +package com.foxdebug.acode.server; + +import java.io.IOException; +import java.util.HashMap; +import com.foxdebug.acode.runtime.*; +import org.json.JSONArray; +import org.json.JSONException; + +public class Server extends Service { + + public HashMap<Integer, NanoHTTPDWebserver> servers; + + @Override + public void initialize(BridgeContext bridgeContext) { + super.initialize(bridgeContext); + servers = new HashMap<Integer, NanoHTTPDWebserver>(); + } + + @Override + public boolean execute( + String action, + JSONArray args, + Callback callbackContext + ) + throws JSONException { + if ("start".equals(action)) { + try { + this.start(args, callbackContext); + } catch (IOException e) { + e.printStackTrace(); + } + return true; + } + if ("setOnRequestHandler".equals(action)) { + this.setOnRequestHandler(args, callbackContext); + return true; + } + if ("stop".equals(action)) { + this.stop(args, callbackContext); + return true; + } + if ("send".equals(action)) { + this.send(args, callbackContext); + return true; + } + return false; // Returning false results in a "MethodNotFound" error. + } + + /** + * Starts the server + * + * @param args + * @param callbackContext + */ + private void start(JSONArray args, Callback callbackContext) + throws JSONException, IOException { + Integer port = 8080; + + if (args.length() == 1) { + port = args.getInt(0); + } + + NanoHTTPDWebserver server = servers.get(port); + if (server != null) { + callbackContext.success("Server started on port " + port); + return; + } + + try { + server = new NanoHTTPDWebserver(port, host.getContext()); + server.start(); + servers.put(port, server); + callbackContext.success("Server started on port " + port); + } catch (Exception e) { + callbackContext.sendPayload( + new Payload(Payload.Status.ERROR, e.getMessage()) + ); + } + } + + private void setOnRequestHandler( + JSONArray args, + Callback callbackContext + ) + throws JSONException { + Integer port = args.getInt(0); + NanoHTTPDWebserver server = servers.get(port); + if (server == null) { + callbackContext.error("Server not started on port " + port); + return; + } + server.onRequestCallbackContext = callbackContext; + } + + /** + * Stops the server + * + * @param args + * @param callbackContext + */ + private void stop(JSONArray args, Callback callbackContext) + throws JSONException { + Integer port = args.getInt(0); + NanoHTTPDWebserver server = servers.get(port); + if (server == null) { + callbackContext.error("Server not started on port " + port); + return; + } + server.stop(); + servers.remove(port); + callbackContext.sendPayload(new Payload(Payload.Status.OK)); + } + + /** + * Will be called if the js context sends an response to the webserver + * + * @param args {UUID: {...}} + * @param callbackContext + * @throws JSONException + */ + private void send(JSONArray args, Callback callbackContext) + throws JSONException { + Integer port = args.getInt(0); + NanoHTTPDWebserver server = this.servers.get(port); + if (server == null) { + callbackContext.sendPayload( + new Payload(Payload.Status.ERROR, "Server not running") + ); + return; + } + server.responses.put(args.getString(1), args.get(2)); + callbackContext.sendPayload(new Payload(Payload.Status.OK)); + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/settings/AppPreferences.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/settings/AppPreferences.kt new file mode 100644 index 0000000000..8e2e5aae3c --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/settings/AppPreferences.kt @@ -0,0 +1,80 @@ +package com.foxdebug.acode.settings + +import android.content.Context +import android.content.SharedPreferences +import com.foxdebug.acode.runtime.RuntimeBaseApplication +import androidx.core.content.edit + +object AppPreferences { + //do not change this name + private const val PREFERENCES_NAME = "Settings" + + private val preferences: SharedPreferences by lazy { + val application = RuntimeBaseApplication.instance + ?: error("AppPreferences requires RuntimeBaseApplication to be initialized") + application.applicationContext.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE) + } + + fun set(name: String, value: String?) { + preferences.edit { putString(name, value) } + } + + fun set(name: String, value: Boolean) { + preferences.edit { putBoolean(name, value) } + } + + fun set(name: String, value: Int) { + preferences.edit { putInt(name, value) } + } + + fun set(name: String, value: Long) { + preferences.edit { putLong(name, value) } + } + + fun set(name: String, value: Float) { + preferences.edit { putFloat(name, value) } + } + + fun set(name: String, value: Set<String>) { + preferences.edit { putStringSet(name, value) } + } + + fun getString(name: String, defaultValue: String? = null): String? = + preferences.getString(name, defaultValue) + + fun getBoolean(name: String, defaultValue: Boolean = false): Boolean = + preferences.getBoolean(name, defaultValue) + + fun getInteger(name: String, defaultValue: Int = 0): Int = + preferences.getInt(name, defaultValue) + + fun getLong(name: String, defaultValue: Long = 0L): Long = + preferences.getLong(name, defaultValue) + + fun getFloat(name: String, defaultValue: Float = 0f): Float = + preferences.getFloat(name, defaultValue) + + fun getStringSet(name: String, defaultValue: Set<String> = emptySet()): Set<String> = + preferences.getStringSet(name, defaultValue) ?: defaultValue + + fun contains(name: String): Boolean = preferences.contains(name) + + fun remove(name: String) { + preferences.edit { remove(name) } + } + + fun clear() { + preferences.edit { clear() } + } + + fun registerChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) { + preferences.registerOnSharedPreferenceChangeListener(listener) + } + + fun unregisterChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) { + preferences.unregisterOnSharedPreferenceChangeListener(listener) + } + + val all: Map<String, *> + get() = preferences.all +} diff --git a/src/plugins/sftp/src/com/foxdebug/sftp/Sftp.java b/platforms/android/app/src/main/java/com/foxdebug/acode/sftp/Sftp.java similarity index 94% rename from src/plugins/sftp/src/com/foxdebug/sftp/Sftp.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/sftp/Sftp.java index a72466607d..f1822e13c5 100644 --- a/src/plugins/sftp/src/com/foxdebug/sftp/Sftp.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/sftp/Sftp.java @@ -1,4 +1,4 @@ -package com.foxdebug.sftp; +package com.foxdebug.acode.sftp; import android.app.Activity; import android.app.AlertDialog; @@ -44,7 +44,6 @@ import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.ByteBuffer; -import java.nio.channels.UnresolvedAddressException; import java.nio.charset.StandardCharsets; import java.security.Security; import java.util.Map; @@ -57,17 +56,16 @@ import java.util.concurrent.FutureTask; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicBoolean; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaInterface; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.CordovaWebView; -import org.apache.cordova.PluginResult; +import com.foxdebug.acode.runtime.BridgeContext; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Service; +import com.foxdebug.acode.runtime.Payload; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.bouncycastle.jce.provider.BouncyCastleProvider; -public class Sftp extends CordovaPlugin { +public class Sftp extends Service { private static final String TAG = "SFTP"; // Maverick's 16 MB default is allocated in full for every SFTP subsystem. @@ -91,12 +89,12 @@ public class Sftp extends CordovaPlugin { private final class ConnectionAttempt { - private final CallbackContext callback; + private final Callback callback; private final AtomicBoolean cancelled = new AtomicBoolean(false); private final AtomicBoolean completed = new AtomicBoolean(false); private volatile Future<?> future; - private ConnectionAttempt(CallbackContext callback) { + private ConnectionAttempt(Callback callback) { this.callback = callback; } @@ -212,7 +210,7 @@ public boolean verifyHost(String host, SshPublicKey publicKey) ); } - private boolean report(CallbackContext callback) { + private boolean report(Callback callback) { JSONObject error = takeFailure(); if (error == null) return false; callback.error(error); @@ -231,7 +229,7 @@ private final class RemoteShell { private final String id; private final SshClient client; private final SessionChannelNG channel; - private final CallbackContext streamCallback; + private final Callback streamCallback; private final AtomicBoolean finished = new AtomicBoolean(false); private final ExecutorService inputWriter = Executors.newSingleThreadExecutor(); @@ -239,7 +237,7 @@ private RemoteShell( String id, SshClient client, SessionChannelNG channel, - CallbackContext streamCallback + Callback streamCallback ) { this.id = id; this.client = client; @@ -290,7 +288,7 @@ private void finish(Integer exitCode, String error) { } } - private void write(String input, CallbackContext callback) { + private void write(String input, Callback callback) { if (finished.get()) { callback.error("SSH shell is not connected"); return; @@ -319,10 +317,10 @@ public void run() { } } - public void initialize(CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); - context = cordova.getContext(); - activity = cordova.getActivity(); + public void initialize(BridgeContext bridgeContext) { + super.initialize(bridgeContext); + context = host.getContext(); + activity = host.getActivity(); securityStore = new SftpSecurityStore(context); System.setProperty("maverick.log.nothread", "true"); configureCryptoProvider(); @@ -412,13 +410,13 @@ private boolean establishConnection( } private static void sendShellEvent( - CallbackContext callback, + Callback callback, JSONObject event, boolean keepCallback ) { - PluginResult result = new PluginResult(PluginResult.Status.OK, event); + Payload result = new Payload(Payload.Status.OK, event); result.setKeepCallback(keepCallback); - callback.sendPluginResult(result); + callback.sendPayload(result); } private static JSONObject hostKeyFailure( @@ -593,7 +591,7 @@ private void openRemoteShell( SshClient shellClient, int columns, int rows, - CallbackContext callback + Callback callback ) throws SshException, JSONException, IOException { if (!shellClient.isConnected()) { shellClient.close(); @@ -665,8 +663,8 @@ public void onChannelError(Channel source, Throwable error) { sendShellEvent(callback, ready, true); } - public void openShellUsingProfile(JSONArray args, CallbackContext callback) { - cordova + public void openShellUsingProfile(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -702,8 +700,8 @@ public void run() { ); } - public void saveProfile(JSONArray args, CallbackContext callback) { - cordova + public void saveProfile(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -739,8 +737,8 @@ public void run() { ); } - public void editProfile(JSONArray args, CallbackContext callback) { - cordova + public void editProfile(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -818,8 +816,8 @@ public void run() { ); } - public void getProfileInfo(JSONArray args, CallbackContext callback) { - cordova + public void getProfileInfo(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -861,7 +859,7 @@ private static String nullableProfileID(JSONArray args) { return value; } - public void deleteProfile(JSONArray args, CallbackContext callback) { + public void deleteProfile(JSONArray args, Callback callback) { String profileID = args.optString(0); try { JSONObject profile = securityStore.getProfile(profileID); @@ -896,7 +894,7 @@ public void deleteProfile(JSONArray args, CallbackContext callback) { } } - public void writeShell(JSONArray args, CallbackContext callback) { + public void writeShell(JSONArray args, Callback callback) { RemoteShell shell = remoteShells.get(args.optString(0)); if (shell == null || shell.finished.get()) { callback.error("SSH shell is not connected"); @@ -905,7 +903,7 @@ public void writeShell(JSONArray args, CallbackContext callback) { shell.write(args.optString(1), callback); } - public void resizeShell(JSONArray args, CallbackContext callback) { + public void resizeShell(JSONArray args, Callback callback) { String shellID = args.optString(0); RemoteShell shell = remoteShells.get(shellID); if (shell == null || shell.finished.get()) { @@ -921,7 +919,7 @@ public void resizeShell(JSONArray args, CallbackContext callback) { callback.success(); } - public void closeShell(JSONArray args, CallbackContext callback) { + public void closeShell(JSONArray args, Callback callback) { RemoteShell shell = remoteShells.get(args.optString(0)); if (shell != null) shell.finish(null, null); callback.success(); @@ -930,7 +928,7 @@ public void closeShell(JSONArray args, CallbackContext callback) { public boolean execute( String action, JSONArray args, - CallbackContext callback + Callback callback ) { if (!isAllowedAction(action)) { callback.error("SFTP action is not available: " + action); @@ -938,7 +936,7 @@ public boolean execute( } try { Method method = getClass() - .getDeclaredMethod(action, JSONArray.class, CallbackContext.class); + .getDeclaredMethod(action, JSONArray.class, Callback.class); if (method != null) { method.invoke(this, args, callback); @@ -989,15 +987,15 @@ private static boolean isAllowedAction(String action) { } } - public void connectUsingProfile(JSONArray args, CallbackContext callback) { + public void connectUsingProfile(JSONArray args, Callback callback) { startProfileConnection(args, callback, false); } - public void testProfile(JSONArray args, CallbackContext callback) { + public void testProfile(JSONArray args, Callback callback) { startProfileConnection(args, callback, true); } - public void cancelConnection(JSONArray args, CallbackContext callback) { + public void cancelConnection(JSONArray args, Callback callback) { ConnectionAttempt attempt = connectionAttempts.get(args.optString(0)); if (attempt != null) attempt.cancel(); callback.success(); @@ -1005,7 +1003,7 @@ public void cancelConnection(JSONArray args, CallbackContext callback) { private void startProfileConnection( JSONArray args, - CallbackContext callback, + Callback callback, boolean returnWorkingDirectory ) { String suppliedRequestID = args.optString(1); @@ -1115,11 +1113,11 @@ protected void done() { }; attempt.setFuture(task); - cordova.getThreadPool().execute(task); + host.getThreadPool().execute(task); } - public void exec(JSONArray args, CallbackContext callback) { - cordova + public void exec(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -1145,8 +1143,8 @@ public void run() { ); } - public void getFile(JSONArray args, CallbackContext callback) { - cordova + public void getFile(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -1199,8 +1197,8 @@ public void run() { ); } - public void putFile(JSONArray args, CallbackContext callback) { - cordova + public void putFile(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -1252,8 +1250,8 @@ public void run() { ); } - public void lsDir(JSONArray args, CallbackContext callback) { - cordova + public void lsDir(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -1354,8 +1352,8 @@ private void invalidateSftpConnection( } } - public void stat(JSONArray args, CallbackContext callback) { - cordova + public void stat(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -1438,8 +1436,8 @@ public void run() { ); } - public void mkdir(JSONArray args, CallbackContext callback) { - cordova + public void mkdir(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -1460,8 +1458,8 @@ public void run() { ); } - public void rm(JSONArray args, CallbackContext callback) { - cordova + public void rm(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -1485,8 +1483,8 @@ public void run() { ); } - public void createFile(JSONArray args, CallbackContext callback) { - cordova + public void createFile(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -1529,8 +1527,8 @@ public void run() { ); } - public void rename(JSONArray args, CallbackContext callback) { - cordova + public void rename(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -1553,8 +1551,8 @@ public void run() { ); } - public void pwd(JSONArray args, CallbackContext callback) { - cordova + public void pwd(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -1594,8 +1592,8 @@ private String sanitizePath(String path) { } } - public void close(JSONArray args, CallbackContext callback) { - cordova + public void close(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { @@ -1613,8 +1611,8 @@ public void run() { ); } - public void isConnected(JSONArray args, CallbackContext callback) { - cordova + public void isConnected(JSONArray args, Callback callback) { + host .getThreadPool() .execute( new Runnable() { diff --git a/src/plugins/sftp/src/com/foxdebug/sftp/SftpSecurityStore.java b/platforms/android/app/src/main/java/com/foxdebug/acode/sftp/SftpSecurityStore.java similarity index 96% rename from src/plugins/sftp/src/com/foxdebug/sftp/SftpSecurityStore.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/sftp/SftpSecurityStore.java index 9951566fcc..425eca5be7 100644 --- a/src/plugins/sftp/src/com/foxdebug/sftp/SftpSecurityStore.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/sftp/SftpSecurityStore.java @@ -1,7 +1,7 @@ -package com.foxdebug.sftp; +package com.foxdebug.acode.sftp; import android.content.Context; -import com.foxdebug.acode.rk.auth.EncryptedPreferenceManager; +import com.foxdebug.acode.auth.EncryptedPreferenceManager; import java.security.GeneralSecurityException; import java.util.UUID; import org.json.JSONException; diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/system/RewardPassManager.java b/platforms/android/app/src/main/java/com/foxdebug/acode/system/RewardPassManager.java new file mode 100644 index 0000000000..fc45f4df62 --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/system/RewardPassManager.java @@ -0,0 +1,129 @@ +package com.foxdebug.acode.system; + +import android.content.Context; +import android.util.Log; +import com.foxdebug.acode.auth.EncryptedPreferenceManager; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import org.json.JSONException; +import org.json.JSONObject; + +public class RewardPassManager { + private static final String TAG = "SystemRewardPass"; + private static final String ADS_PREFS_FILENAME = "ads"; + private static final String KEY_REWARD_STATE = "reward_state"; + private static final long ONE_HOUR_MS = 60L * 60L * 1000L; + private static final long MAX_ACTIVE_PASS_MS = 10L * ONE_HOUR_MS; + private static final int MAX_REDEMPTIONS_PER_DAY = 3; + + private final EncryptedPreferenceManager adsPrefManager; + + public RewardPassManager(Context context) { + this.adsPrefManager = new EncryptedPreferenceManager(context, ADS_PREFS_FILENAME); + } + + public String getRewardStatus() throws JSONException { + String previous = adsPrefManager.getString(KEY_REWARD_STATE, ""); + JSONObject state = syncRewardState(loadRewardState(previous)); + JSONObject status = buildRewardStatus(state); + + if (status.optBoolean("hasPendingExpiryNotice")) { + state.put("expiryNoticePendingUntil", 0L); + } + + if (!RewardPassStorage.isUnchanged(previous, state)) saveRewardState(state); + return status.toString(); + } + + private JSONObject loadRewardState(String raw) { + if (raw == null || raw.isEmpty()) { + return defaultRewardState(); + } + + try { + return mergeRewardState(new JSONObject(raw)); + } catch (JSONException error) { + Log.w(TAG, "Failed to parse reward state, resetting.", error); + return defaultRewardState(); + } + } + + private JSONObject defaultRewardState() { + JSONObject state = new JSONObject(); + try { + state.put("adFreeUntil", 0L); + state.put("lastExpiredRewardUntil", 0L); + state.put("expiryNoticePendingUntil", 0L); + state.put("redemptionDay", getTodayKey()); + state.put("redemptionsToday", 0); + } catch (JSONException ignored) { + } + return state; + } + + private JSONObject mergeRewardState(JSONObject parsed) { + JSONObject state = defaultRewardState(); + try { + state.put("adFreeUntil", parsed.optLong("adFreeUntil", 0L)); + state.put("lastExpiredRewardUntil", parsed.optLong("lastExpiredRewardUntil", 0L)); + state.put("expiryNoticePendingUntil", parsed.optLong("expiryNoticePendingUntil", 0L)); + state.put("redemptionDay", parsed.optString("redemptionDay", getTodayKey())); + state.put("redemptionsToday", parsed.optInt("redemptionsToday", 0)); + } catch (JSONException ignored) { + } + return state; + } + + private void saveRewardState(JSONObject state) { + adsPrefManager.setString(KEY_REWARD_STATE, state.toString()); + } + + private JSONObject syncRewardState(JSONObject state) throws JSONException { + String todayKey = getTodayKey(); + if (!todayKey.equals(state.optString("redemptionDay", todayKey))) { + state.put("redemptionDay", todayKey); + state.put("redemptionsToday", 0); + } + + long adFreeUntil = state.optLong("adFreeUntil", 0L); + long now = java.lang.System.currentTimeMillis(); + if (adFreeUntil > 0L && adFreeUntil <= now) { + if (state.optLong("expiryNoticePendingUntil", 0L) != adFreeUntil) { + state.put("expiryNoticePendingUntil", adFreeUntil); + } + state.put("lastExpiredRewardUntil", adFreeUntil); + state.put("adFreeUntil", 0L); + } + + return state; + } + + private JSONObject buildRewardStatus(JSONObject state) throws JSONException { + long now = java.lang.System.currentTimeMillis(); + long adFreeUntil = state.optLong("adFreeUntil", 0L); + int redemptionsToday = state.optInt("redemptionsToday", 0); + long remainingMs = Math.max(0L, adFreeUntil - now); + int remainingRedemptions = Math.max(0, MAX_REDEMPTIONS_PER_DAY - redemptionsToday); + + JSONObject status = new JSONObject(); + status.put("adFreeUntil", adFreeUntil); + status.put("lastExpiredRewardUntil", state.optLong("lastExpiredRewardUntil", 0L)); + status.put("isActive", adFreeUntil > now); + status.put("remainingMs", remainingMs); + status.put("redemptionsToday", redemptionsToday); + status.put("remainingRedemptions", remainingRedemptions); + status.put("maxRedemptionsPerDay", MAX_REDEMPTIONS_PER_DAY); + status.put("maxActivePassMs", MAX_ACTIVE_PASS_MS); + status.put("hasPendingExpiryNotice", state.optLong("expiryNoticePendingUntil", 0L) > 0L); + status.put("expiryNoticePendingUntil", state.optLong("expiryNoticePendingUntil", 0L)); + + status.put("canRedeem", false); + status.put("redeemDisabledReason", "Ad-free passes are no longer available."); + return status; + } + + private String getTodayKey() { + return new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(new Date()); + } +} diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/system/RewardPassStorage.kt b/platforms/android/app/src/main/java/com/foxdebug/acode/system/RewardPassStorage.kt new file mode 100644 index 0000000000..01d70502ae --- /dev/null +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/system/RewardPassStorage.kt @@ -0,0 +1,22 @@ +package com.foxdebug.acode.system + +import org.json.JSONException +import org.json.JSONObject + +internal object RewardPassStorage { + @JvmStatic + fun isUnchanged(raw: String?, state: JSONObject): Boolean { + if (raw.isNullOrEmpty()) return false + return try { + val previous = JSONObject(raw) + previous.length() == state.length() && state.keys().asSequence().all { key -> + val old = previous.opt(key) + val new = state.get(key) + if (old is Number && new is Number) old.toString() == new.toString() + else old == new + } + } catch (error: JSONException) { + false + } + } +} diff --git a/src/plugins/system/android/com/foxdebug/system/StreamHttp.java b/platforms/android/app/src/main/java/com/foxdebug/acode/system/StreamHttp.java similarity index 96% rename from src/plugins/system/android/com/foxdebug/system/StreamHttp.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/system/StreamHttp.java index d59bb2f52d..2eeb4940d6 100644 --- a/src/plugins/system/android/com/foxdebug/system/StreamHttp.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/system/StreamHttp.java @@ -1,4 +1,4 @@ -package com.foxdebug.system; +package com.foxdebug.acode.system; import android.util.Base64; import android.util.Log; @@ -14,8 +14,8 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.PluginResult; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Payload; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -68,7 +68,7 @@ public class StreamHttp implements Runnable { private final int connectTimeout; private final int readTimeout; private final int chunkSize; - private final CallbackContext callback; + private final Callback callback; private final Object creditLock = new Object(); private volatile boolean cancelled; @@ -89,7 +89,7 @@ public StreamHttp( int connectTimeout, int readTimeout, int chunkSize, - CallbackContext callback + Callback callback ) { this.requestId = requestId; this.url = url; @@ -117,7 +117,7 @@ public static void start( int connectTimeout, int readTimeout, int chunkSize, - CallbackContext callback + Callback callback ) { StreamHttp stream = new StreamHttp( requestId, @@ -192,9 +192,9 @@ private void release() { if (finished) return; finished = true; try { - PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); + Payload result = new Payload(Payload.Status.NO_RESULT); result.setKeepCallback(false); - callback.sendPluginResult(result); + callback.sendPayload(result); } catch (Exception e) { Log.w(TAG, "Failed to release stream callback " + requestId, e); } @@ -377,9 +377,9 @@ private void sendError(String message) throws JSONException { private void sendEvent(JSONObject event, boolean keepCallback) { if (finished) return; if (!keepCallback) finished = true; - PluginResult result = new PluginResult(PluginResult.Status.OK, event); + Payload result = new Payload(Payload.Status.OK, event); result.setKeepCallback(keepCallback); - callback.sendPluginResult(result); + callback.sendPayload(result); } private void cleanup() { diff --git a/src/plugins/system/android/com/foxdebug/system/System.java b/platforms/android/app/src/main/java/com/foxdebug/acode/system/System.java similarity index 95% rename from src/plugins/system/android/com/foxdebug/system/System.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/system/System.java index 5b70487e8a..aeb7c21220 100644 --- a/src/plugins/system/android/com/foxdebug/system/System.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/system/System.java @@ -1,4 +1,4 @@ -package com.foxdebug.system; +package com.foxdebug.acode.system; import static android.os.Build.VERSION.SDK_INT; @@ -39,7 +39,7 @@ import androidx.core.content.pm.ShortcutManagerCompat; import androidx.core.graphics.drawable.IconCompat; import androidx.documentfile.provider.DocumentFile; -import com.foxdebug.system.Ui.Theme; +import com.foxdebug.acode.BuildConfig; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -62,21 +62,21 @@ import java.nio.file.StandardOpenOption; import java.security.MessageDigest; import java.util.*; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaInterface; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.CordovaWebView; -import org.apache.cordova.CordovaWebViewImpl; -import org.apache.cordova.PluginResult; +import com.foxdebug.acode.runtime.BridgeContext; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Service; +import com.foxdebug.acode.runtime.webview.AppWebView; +import com.foxdebug.acode.runtime.Payload; +import com.foxdebug.acode.settings.AppPreferences; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -public class System extends CordovaPlugin { +public class System extends Service { private static final String TAG = "SystemPlugin"; - private CallbackContext requestPermissionCallback; + private Callback requestPermissionCallback; private static final Map<String, String> APP_ICON_ALIASES; static { @@ -105,17 +105,14 @@ public class System extends CordovaPlugin { private int REQ_PERMISSIONS = 1; private int REQ_PERMISSION = 2; private int systemBarColor = 0xFF000000; - private Theme theme; - private CallbackContext intentHandler; - private CordovaWebView webView; + private Callback intentHandler; private String fileProviderAuthority; private RewardPassManager rewardPassManager; - public void initialize(CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); - this.context = cordova.getContext(); - this.activity = cordova.getActivity(); - this.webView = webView; + public void initialize(BridgeContext bridgeContext) { + super.initialize(bridgeContext); + this.context = host.getContext(); + this.activity = host.getActivity(); this.rewardPassManager = new RewardPassManager(this.context); this.activity.runOnUiThread( new Runnable() { @@ -143,7 +140,7 @@ public void onDestroy() { public boolean execute( String action, final JSONArray args, - final CallbackContext callbackContext + final Callback callbackContext ) throws JSONException { final String arg1 = args.optString(0); final String arg2 = args.optString(1); @@ -186,7 +183,7 @@ public boolean execute( final boolean fullscreenBackHandler = args.getBoolean(0); activity.runOnUiThread(() -> { try { - ((CordovaWebViewImpl) webView).setFullscreenBackHandler(fullscreenBackHandler); + ((AppWebView) webView).setFullscreenBackHandler(fullscreenBackHandler); callbackContext.success(); } catch (RuntimeException error) { callbackContext.error(error.getMessage()); @@ -197,7 +194,7 @@ public boolean execute( final String orientation = args.isNull(0) ? null : args.getString(0); activity.runOnUiThread(() -> { try { - ((CordovaWebViewImpl) webView).setFullscreenOrientation(orientation); + ((AppWebView) webView).setFullscreenOrientation(orientation); callbackContext.success(); } catch (RuntimeException error) { callbackContext.error(error.getMessage()); @@ -220,7 +217,7 @@ public boolean execute( callbackContext.success(); return true; case "set-native-context-menu-disabled": - this.cordova.getActivity().runOnUiThread( + this.host.getActivity().runOnUiThread( new Runnable() { @Override public void run() { @@ -233,8 +230,8 @@ public void run() { case "set-app-icon": setAppIcon(arg1, callbackContext); return true; - case "get-cordova-intent": - getCordovaIntent(callbackContext); + case "get-intent": + getIntent(callbackContext); return true; case "set-intent-handler": setIntentHandler(callbackContext); @@ -242,14 +239,13 @@ public void run() { case "shareText": String text = args.getString(0); - cordova.getActivity().runOnUiThread(() -> { + host.getActivity().runOnUiThread(() -> { try { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, text); - cordova - .getActivity() + host.getActivity() .startActivity(Intent.createChooser(shareIntent, "Share")); callbackContext.success(); @@ -259,7 +255,7 @@ public void run() { }); return true; case "set-ui-theme": - this.cordova.getActivity().runOnUiThread( + this.host.getActivity().runOnUiThread( new Runnable() { public void run() { setUiTheme(arg1, args.optJSONObject(1), callbackContext); @@ -268,7 +264,7 @@ public void run() { ); return true; case "clear-cache": - this.cordova.getActivity().runOnUiThread( + this.host.getActivity().runOnUiThread( new Runnable() { public void run() { clearCache(callbackContext); @@ -294,11 +290,6 @@ public void run() { case "getRewardStatus": callbackContext.success(rewardPassManager.getRewardStatus()); return true; - case "redeemReward": - callbackContext.success( - rewardPassManager.redeemReward(args.getString(0)) - ); - return true; case "getParentPath": callbackContext.success(getParentPath(args.getString(0))); return true; @@ -426,7 +417,7 @@ public void run() { return false; } - cordova.getThreadPool().execute( + host.getThreadPool().execute( new Runnable() { public void run() { switch (action) { @@ -640,7 +631,7 @@ public void run() { compareTexts(arg1, arg2, callbackContext); break; case "checksumText": - cordova.getThreadPool().execute(() -> { + host.getThreadPool().execute(() -> { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); @@ -690,7 +681,7 @@ private void sendLogToJavaScript(String level, String message) { JSONObject.quote(message) + ");"; - cordova.getActivity().runOnUiThread(() -> { + host.getActivity().runOnUiThread(() -> { try { ( (android.webkit.WebView) webView.getEngine().getView() @@ -728,7 +719,7 @@ private String getMimeTypeFromExtension(String fileName) { * connectTimeout, readTimeout, chunkSize</li> * </ol> */ - private void httpStreamStart(JSONArray args, CallbackContext callbackContext) { + private void httpStreamStart(JSONArray args, Callback callbackContext) { try { final String requestId = args.getString(0); final String url = args.getString(1); @@ -761,7 +752,7 @@ private void httpStreamStart(JSONArray args, CallbackContext callbackContext) { } } - private void getConfiguration(CallbackContext callback) { + private void getConfiguration(Callback callback) { try { JSONObject result = new JSONObject(); Configuration config = context.getResources().getConfiguration(); @@ -796,7 +787,7 @@ private void getConfiguration(CallbackContext callback) { private void decode( String content, // base64 encoded string String charSetName, - CallbackContext callback + Callback callback ) { try { byte[] bytes = Base64.decode(content, Base64.DEFAULT); @@ -818,7 +809,7 @@ private void decode( private void encode( String content, // string to encode String charSetName, - CallbackContext callback + Callback callback ) { try { if (Charset.isSupported(charSetName) == false) { @@ -849,7 +840,7 @@ private void compareFileText( String fileUri, String encoding, String currentText, - CallbackContext callback + Callback callback ) { try { if (fileUri == null || fileUri.isEmpty()) { @@ -989,7 +980,7 @@ private void compareFileText( private void compareTexts( String text1, String text2, - CallbackContext callback + Callback callback ) { try { if (text1 == null) text1 = ""; @@ -1012,7 +1003,7 @@ private void compareTexts( } } - private void getAvailableEncodings(CallbackContext callback) { + private void getAvailableEncodings(Callback callback) { try { Map<String, Charset> charsets = Charset.availableCharsets(); JSONObject result = new JSONObject(); @@ -1030,7 +1021,7 @@ private void getAvailableEncodings(CallbackContext callback) { } } - private void requestPermissions(JSONArray arr, CallbackContext callback) { + private void requestPermissions(JSONArray arr, Callback callback) { try { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { int[] res = new int[arr.length()]; @@ -1045,7 +1036,7 @@ private void requestPermissions(JSONArray arr, CallbackContext callback) { if (permissions.length > 0) { requestPermissionCallback = callback; - cordova.requestPermissions(this, REQ_PERMISSIONS, permissions); + host.requestPermissions(this, REQ_PERMISSIONS, permissions); return; } callback.success(new JSONArray()); @@ -1054,16 +1045,16 @@ private void requestPermissions(JSONArray arr, CallbackContext callback) { } } - private void requestPermission(String permission, CallbackContext callback) { + private void requestPermission(String permission, Callback callback) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { callback.success(1); return; } if (permission != null || !permission.equals("")) { - if (!cordova.hasPermission(permission)) { + if (!host.hasPermission(permission)) { requestPermissionCallback = callback; - cordova.requestPermission(this, REQ_PERMISSION, permission); + host.requestPermission(this, REQ_PERMISSION, permission); return; } @@ -1074,10 +1065,10 @@ private void requestPermission(String permission, CallbackContext callback) { callback.error("No permission passed to request."); } - private void hasPermission(String permission, CallbackContext callback) { + private void hasPermission(String permission, Callback callback) { if (permission != null || !permission.equals("")) { int res = 0; - if (cordova.hasPermission(permission)) { + if (host.hasPermission(permission)) { res = 1; } @@ -1191,7 +1182,7 @@ private String[] checkPermissions(JSONArray arr) throws Exception { if (permission == null || permission.equals("")) { throw new Exception("Permission cannot be null or empty"); } - if (!cordova.hasPermission(permission)) { + if (!host.hasPermission(permission)) { list.add(permission); } } catch (JSONException e) { @@ -1203,11 +1194,11 @@ private String[] checkPermissions(JSONArray arr) throws Exception { return list.toArray(res); } - private void getAndroidVersion(CallbackContext callback) { + private void getAndroidVersion(Callback callback) { callback.success(Build.VERSION.SDK_INT); } - private void getWebkitInfo(CallbackContext callback) { + private void getWebkitInfo(Callback callback) { PackageInfo info = null; JSONObject res = new JSONObject(); @@ -1250,7 +1241,7 @@ private void getWebkitInfo(CallbackContext callback) { } } - private void isPowerSaveMode(CallbackContext callback) { + private void isPowerSaveMode(Callback callback) { PowerManager powerManager = (PowerManager) context.getSystemService( Context.POWER_SERVICE ); @@ -1261,7 +1252,7 @@ private void isPowerSaveMode(CallbackContext callback) { private void pinFileShortcut( JSONObject shortcutJson, - CallbackContext callback + Callback callback ) { if (shortcutJson == null) { callback.error("Invalid shortcut data"); @@ -1570,7 +1561,7 @@ private void fileAction( String filename, String action, String mimeType, - CallbackContext callback + Callback callback ) { Activity activity = this.activity; Context context = this.context; @@ -1661,7 +1652,7 @@ private void fileAction( } } - private void getAppInfo(CallbackContext callback) { + private void getAppInfo(Callback callback) { JSONObject res = new JSONObject(); try { PackageManager pm = activity.getPackageManager(); @@ -1685,7 +1676,7 @@ private void getAppInfo(CallbackContext callback) { } } - private void openInBrowser(String src, CallbackContext callback) { + private void openInBrowser(String src, Callback callback) { if (src == null || src.isEmpty()) { callback.error("No URL provided."); return; @@ -1712,7 +1703,7 @@ private void launchApp( String appId, String className, JSONObject extras, - CallbackContext callback + Callback callback ) { if (appId == null || appId.equals("")) { callback.error("No package name provided."); @@ -1896,7 +1887,7 @@ private void putArrayExtra(Intent intent, String key, JSONArray array) { * - several files: the default action becomes {@code SEND_MULTIPLE}. * - no files: the default action becomes {@code MAIN}, i.e. a plain app launch. */ - private void launchAppWithFile(JSONObject options, CallbackContext callback) { + private void launchAppWithFile(JSONObject options, Callback callback) { if (options == null) { callback.error("No options provided."); return; @@ -2414,7 +2405,7 @@ private void addShortcut( String iconSrc, String action, String data, - CallbackContext callback + Callback callback ) { try { Intent intent; @@ -2448,7 +2439,7 @@ private void addShortcut( } } - private void pinShortcut(String id, CallbackContext callback) { + private void pinShortcut(String id, Callback callback) { ShortcutManager shortcutManager = context.getSystemService( ShortcutManager.class ); @@ -2481,7 +2472,7 @@ private void pinShortcut(String id, CallbackContext callback) { callback.error("Not supported"); } - private void removeShortcut(String id, CallbackContext callback) { + private void removeShortcut(String id, Callback callback) { try { List<String> list = new ArrayList<String>(); list.add(id); @@ -2495,14 +2486,13 @@ private void removeShortcut(String id, CallbackContext callback) { private void setUiTheme( final String systemBarColor, final JSONObject scheme, - final CallbackContext callback + final Callback callback ) { try { this.systemBarColor = Color.parseColor(systemBarColor); - this.theme = new Theme(scheme); - preferences.set("BackgroundColor", this.systemBarColor); - webView.getPluginManager().postMessage("updateSystemBars", null); + AppPreferences.INSTANCE.set("BackgroundColor", this.systemBarColor); + webView.getBridge().postMessage("updateSystemBars", null); applySystemBarTheme(); if (scheme != null) { @@ -2532,7 +2522,7 @@ private void applySystemBarTheme() { final Window window = activity.getWindow(); final View decorView = window.getDecorView(); - // Keep Cordova's BackgroundColor flow for API 36+, but also apply the + // Keep the status bar BackgroundColor flow for API 36+, but also apply the // window colors directly so OEM variants do not leave stale system-bar // colors behind after a theme switch. window.clearFlags(0x04000000 | 0x08000000); // FLAG_TRANSLUCENT_STATUS | FLAG_TRANSLUCENT_NAVIGATION @@ -2560,7 +2550,7 @@ private void applySystemBarTheme() { } private void setStatusBarStyle(final Window window) { - String themeType = theme.getType(); + boolean lightBackground = isColorLight(this.systemBarColor); View decorView = window.getDecorView(); int uiOptions; int lightStatusBar; @@ -2569,7 +2559,7 @@ private void setStatusBarStyle(final Window window) { uiOptions = getDeprecatedSystemUiVisibility(decorView); lightStatusBar = deprecatedFlagUiLightStatusBar(); - if (themeType.equals("light")) { + if (lightBackground) { setDeprecatedSystemUiVisibility(decorView, uiOptions | lightStatusBar); return; } @@ -2582,7 +2572,7 @@ private void setStatusBarStyle(final Window window) { ).getSystemBarsAppearance(); lightStatusBar = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS; - if (themeType.equals("light")) { + if (lightBackground) { decorView .getWindowInsetsController() .setSystemBarsAppearance(uiOptions | lightStatusBar, lightStatusBar); @@ -2595,7 +2585,7 @@ private void setStatusBarStyle(final Window window) { } private void setNavigationBarStyle(final Window window) { - String themeType = theme.getType(); + boolean lightBackground = isColorLight(this.systemBarColor); View decorView = window.getDecorView(); int uiOptions; int lightNavigationBar; @@ -2604,7 +2594,7 @@ private void setNavigationBarStyle(final Window window) { uiOptions = getDeprecatedSystemUiVisibility(decorView); lightNavigationBar = View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR; - if (themeType.equals("light")) { + if (lightBackground) { setDeprecatedSystemUiVisibility( decorView, uiOptions | lightNavigationBar @@ -2624,7 +2614,7 @@ private void setNavigationBarStyle(final Window window) { lightNavigationBar = WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS; - if (themeType.equals("light")) { + if (lightBackground) { decorView .getWindowInsetsController() .setSystemBarsAppearance( @@ -2642,6 +2632,13 @@ private void setNavigationBarStyle(final Window window) { ); } + private boolean isColorLight(int color) { + double r = Color.red(color) / 255.0; + double g = Color.green(color) / 255.0; + double b = Color.blue(color) / 255.0; + return 0.299 * r + 0.587 * g + 0.114 * b > 0.5; + } + private int deprecatedFlagUiLightStatusBar() { return View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } @@ -2654,24 +2651,24 @@ private void setDeprecatedSystemUiVisibility(View decorView, int visibility) { decorView.setSystemUiVisibility(visibility); } - private void getCordovaIntent(CallbackContext callback) { + private void getIntent(Callback callback) { Intent intent = activity.getIntent(); if (isReservedAuthIntent(intent)) { - callback.sendPluginResult( - new PluginResult(PluginResult.Status.OK, new JSONObject()) + callback.sendPayload( + new Payload(Payload.Status.OK, new JSONObject()) ); return; } - callback.sendPluginResult( - new PluginResult(PluginResult.Status.OK, getIntentJson(intent)) + callback.sendPayload( + new Payload(Payload.Status.OK, getIntentJson(intent)) ); } - private void setIntentHandler(CallbackContext callback) { + private void setIntentHandler(Callback callback) { intentHandler = callback; - PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); + Payload result = new Payload(Payload.Status.NO_RESULT); result.setKeepCallback(true); - callback.sendPluginResult(result); + callback.sendPayload(result); } @Override @@ -2680,12 +2677,12 @@ public void onNewIntent(Intent intent) { return; } if (intentHandler != null) { - PluginResult result = new PluginResult( - PluginResult.Status.OK, + Payload result = new Payload( + Payload.Status.OK, getIntentJson(intent) ); result.setKeepCallback(true); - intentHandler.sendPluginResult(result); + intentHandler.sendPayload(result); } } @@ -3106,7 +3103,7 @@ private String getFileProviderAuthority() { private boolean isPackageInstalled( String packageName, PackageManager packageManager, - CallbackContext callback + Callback callback ) { try { packageManager.getPackageInfo(packageName, 0); @@ -3116,7 +3113,7 @@ private boolean isPackageInstalled( } } - private void getGlobalSetting(String setting, CallbackContext callback) { + private void getGlobalSetting(String setting, Callback callback) { int value = (int) Global.getFloat( context.getContentResolver(), setting, @@ -3125,7 +3122,7 @@ private void getGlobalSetting(String setting, CallbackContext callback) { callback.success(value); } - private void clearCache(CallbackContext callback) { + private void clearCache(Callback callback) { webView.clearCache(true); callback.success("Cache cleared"); } @@ -3159,9 +3156,11 @@ private void setNativeContextMenuDisabled(boolean disabled) { * the original launcher icon. * @param callback Callback invoked with the result. */ - private void setAppIcon(String iconName, CallbackContext callback) { + private void setAppIcon(String iconName, Callback callback) { try { String packageName = context.getPackageName(); + // Alias components sit in the namespace package, not the application id. + String componentPackage = BuildConfig.class.getPackage().getName(); PackageManager pm = context.getPackageManager(); String key = iconName == null ? "default" : iconName.toLowerCase(); @@ -3172,7 +3171,7 @@ private void setAppIcon(String iconName, CallbackContext callback) { } pm.setComponentEnabledSetting( - new ComponentName(packageName, packageName + "." + targetAlias), + new ComponentName(packageName, componentPackage + "." + targetAlias), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP ); @@ -3182,7 +3181,7 @@ private void setAppIcon(String iconName, CallbackContext callback) { continue; } pm.setComponentEnabledSetting( - new ComponentName(packageName, packageName + "." + entry.getValue()), + new ComponentName(packageName, componentPackage + "." + entry.getValue()), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP ); @@ -3196,7 +3195,7 @@ private void setAppIcon(String iconName, CallbackContext callback) { private void extractAsset( String assetName, String destinationPath, - CallbackContext callback + Callback callback ) { try ( InputStream in = context.getAssets().open(assetName); diff --git a/src/plugins/system/android/com/foxdebug/system/Ui.java b/platforms/android/app/src/main/java/com/foxdebug/acode/system/Ui.java similarity index 99% rename from src/plugins/system/android/com/foxdebug/system/Ui.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/system/Ui.java index 4cdf19c636..e478ad3b9c 100644 --- a/src/plugins/system/android/com/foxdebug/system/Ui.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/system/Ui.java @@ -1,4 +1,4 @@ -package com.foxdebug.system; +package com.foxdebug.acode.system; import android.content.Context; import android.graphics.Bitmap; diff --git a/src/plugins/terminal/src/android/AlpineDocumentProvider.java b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/AlpineDocumentProvider.java similarity index 99% rename from src/plugins/terminal/src/android/AlpineDocumentProvider.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/terminal/AlpineDocumentProvider.java index 97a4dd50ab..193891eda6 100644 --- a/src/plugins/terminal/src/android/AlpineDocumentProvider.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/AlpineDocumentProvider.java @@ -1,4 +1,4 @@ -package com.foxdebug.acode.rk.exec.terminal; +package com.foxdebug.acode.terminal; import android.content.ComponentName; import android.content.Context; @@ -20,7 +20,6 @@ import java.util.LinkedList; import java.util.Locale; import com.foxdebug.acode.R; -import com.foxdebug.acode.rk.exec.terminal.*; public class AlpineDocumentProvider extends DocumentsProvider { diff --git a/src/plugins/terminal/src/android/BackgroundExecutor.java b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/BackgroundExecutor.java similarity index 82% rename from src/plugins/terminal/src/android/BackgroundExecutor.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/terminal/BackgroundExecutor.java index 3230473af2..ae5c243bb7 100644 --- a/src/plugins/terminal/src/android/BackgroundExecutor.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/BackgroundExecutor.java @@ -1,28 +1,27 @@ -package com.foxdebug.acode.rk.exec.terminal; +package com.foxdebug.acode.terminal; -import org.apache.cordova.*; +import com.foxdebug.acode.runtime.*; import org.json.*; import java.io.*; import java.util.*; import java.util.concurrent.*; -import com.foxdebug.acode.rk.exec.terminal.*; -public class BackgroundExecutor extends CordovaPlugin { +public class BackgroundExecutor extends Service { private final Map<String, Process> processes = new ConcurrentHashMap<>(); private final Map<String, OutputStream> processInputs = new ConcurrentHashMap<>(); - private final Map<String, CallbackContext> processCallbacks = new ConcurrentHashMap<>(); + private final Map<String, Callback> processCallbacks = new ConcurrentHashMap<>(); private final Map<String, ProcessDetails> processDetails = new ConcurrentHashMap<>(); private ProcessManager processManager; @Override - public void initialize(CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); - this.processManager = new ProcessManager(cordova.getContext()); + public void initialize(BridgeContext bridgeContext) { + super.initialize(bridgeContext); + this.processManager = new ProcessManager(host.getContext()); } @Override - public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { + public boolean execute(String action, JSONArray args, Callback callbackContext) throws JSONException { switch (action) { case "start": String pid = UUID.randomUUID().toString(); @@ -62,8 +61,8 @@ public boolean execute(String action, JSONArray args, CallbackContext callbackCo } } - private void exec(String cmd, boolean useAlpine, CallbackContext callbackContext) { - cordova.getThreadPool().execute(() -> { + private void exec(String cmd, boolean useAlpine, Callback callbackContext) { + host.getThreadPool().execute(() -> { try { ProcessManager.ExecResult result = processManager.executeCommand(cmd, useAlpine); @@ -78,8 +77,8 @@ private void exec(String cmd, boolean useAlpine, CallbackContext callbackContext }); } - private void startProcess(String pid, String cmd, boolean useAlpine, CallbackContext callbackContext) { - cordova.getThreadPool().execute(() -> { + private void startProcess(String pid, String cmd, boolean useAlpine, Callback callbackContext) { + host.getThreadPool().execute(() -> { try { ProcessBuilder builder = processManager.createProcessBuilder(cmd, useAlpine); Process process = builder.start(); @@ -90,7 +89,7 @@ private void startProcess(String pid, String cmd, boolean useAlpine, CallbackCon processCallbacks.put(pid, callbackContext); processDetails.put(pid, new ProcessDetails(cmd, useAlpine, pidVal)); - sendPluginResult(callbackContext, pid, true); + sendPayload(callbackContext, pid, true); // Stream stdout new Thread(() -> StreamHandler.streamOutput( @@ -113,7 +112,7 @@ private void startProcess(String pid, String cmd, boolean useAlpine, CallbackCon }); } - private void writeToProcess(String pid, String input, CallbackContext callbackContext) { + private void writeToProcess(String pid, String input, Callback callbackContext) { try { OutputStream os = processInputs.get(pid); if (os != null) { @@ -127,7 +126,7 @@ private void writeToProcess(String pid, String input, CallbackContext callbackCo } } - private void stopProcess(String pid, CallbackContext callbackContext) { + private void stopProcess(String pid, Callback callbackContext) { Process process = processes.get(pid); if (process != null) { ProcessUtils.killProcessTree(process); @@ -138,7 +137,7 @@ private void stopProcess(String pid, CallbackContext callbackContext) { } } - private void isProcessRunning(String pid, CallbackContext callbackContext) { + private void isProcessRunning(String pid, Callback callbackContext) { Process process = processes.get(pid); if (process != null) { @@ -150,7 +149,7 @@ private void isProcessRunning(String pid, CallbackContext callbackContext) { } } - private void listProcesses(CallbackContext callbackContext) { + private void listProcesses(Callback callbackContext) { JSONArray result = new JSONArray(); for (Map.Entry<String, Process> entry : processes.entrySet()) { @@ -177,7 +176,7 @@ private void listProcesses(CallbackContext callbackContext) { callbackContext.success(result); } - private void loadLibrary(String path, CallbackContext callbackContext) { + private void loadLibrary(String path, Callback callbackContext) { callbackContext.error("This feature is no longer supported. Loading native libraries directly from JavaScript is no longer allowed due to security reasons."); /*try { System.load(path); @@ -187,16 +186,16 @@ private void loadLibrary(String path, CallbackContext callbackContext) { }*/ } - private void sendPluginResult(CallbackContext ctx, String message, boolean keepCallback) { - PluginResult result = new PluginResult(PluginResult.Status.OK, message); + private void sendPayload(Callback ctx, String message, boolean keepCallback) { + Payload result = new Payload(Payload.Status.OK, message); result.setKeepCallback(keepCallback); - ctx.sendPluginResult(result); + ctx.sendPayload(result); } private void sendPluginMessage(String pid, String message) { - CallbackContext ctx = processCallbacks.get(pid); + Callback ctx = processCallbacks.get(pid); if (ctx != null) { - sendPluginResult(ctx, message, true); + sendPayload(ctx, message, true); } } @@ -207,7 +206,7 @@ private void cleanup(String pid) { processDetails.remove(pid); } - private void listAllProcesses(CallbackContext callbackContext) { + private void listAllProcesses(Callback callbackContext) { try { callbackContext.success(ProcessUtils.getAllProcesses()); } catch (Exception e) { @@ -215,7 +214,7 @@ private void listAllProcesses(CallbackContext callbackContext) { } } - private void killProcess(int pid, CallbackContext callbackContext) { + private void killProcess(int pid, Callback callbackContext) { try { ProcessUtils.killProcess(pid); callbackContext.success("Process terminated"); diff --git a/src/plugins/terminal/src/android/Executor.java b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/Executor.java similarity index 90% rename from src/plugins/terminal/src/android/Executor.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/terminal/Executor.java index 0fd14cee8b..19e0f464ec 100644 --- a/src/plugins/terminal/src/android/Executor.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/Executor.java @@ -1,6 +1,6 @@ -package com.foxdebug.acode.rk.exec.terminal; +package com.foxdebug.acode.terminal; -import org.apache.cordova.*; +import com.foxdebug.acode.runtime.*; import org.json.*; import android.content.ComponentName; @@ -22,18 +22,15 @@ import android.content.pm.PackageManager; import android.os.Build; -import androidx.annotation.NonNull; -import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.app.Activity; -import com.foxdebug.acode.rk.exec.terminal.*; import java.net.ServerSocket; -public class Executor extends CordovaPlugin { +public class Executor extends Service { private Messenger serviceMessenger; private boolean isServiceBound; @@ -42,7 +39,7 @@ public class Executor extends CordovaPlugin { private Activity activity; private final Messenger handlerMessenger = new Messenger(new IncomingHandler()); private CountDownLatch serviceConnectedLatch; - private final java.util.Map<String, CallbackContext> callbackContextMap = new java.util.concurrent.ConcurrentHashMap<>(); + private final java.util.Map<String, Callback> callbackContextMap = new java.util.concurrent.ConcurrentHashMap<>(); private static final int REQUEST_POST_NOTIFICATIONS = 1001; @@ -71,10 +68,10 @@ private void askNotificationPermission(Activity context) { } @Override - public void initialize(CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); - this.context = cordova.getContext(); - this.activity = cordova.getActivity(); + public void initialize(BridgeContext bridgeContext) { + super.initialize(bridgeContext); + this.context = host.getContext(); + this.activity = host.getActivity(); askNotificationPermission(activity); // Don't bind service immediately - wait until needed @@ -85,7 +82,7 @@ public void initialize(CordovaInterface cordova, CordovaWebView webView) { * Ensure service is bound and ready for communication * Returns true if service is ready, false if binding failed */ - private boolean ensureServiceBound(CallbackContext callbackContext) { + private boolean ensureServiceBound(Callback callbackContext) { // If already bound, return immediately if (isServiceBound && serviceMessenger != null) { return true; @@ -115,7 +112,7 @@ private boolean ensureServiceBound(CallbackContext callbackContext) { /** * Immediately bind to service */ - private boolean bindServiceNow(CallbackContext callbackContext) { + private boolean bindServiceNow(Callback callbackContext) { if (isServiceBinding) { return false; // Already binding } @@ -188,7 +185,7 @@ public void handleMessage(Message msg) { String data = bundle.getString("data"); if (action.equals("exec_result")) { - CallbackContext callbackContext = getCallbackContext(id); + com.foxdebug.acode.runtime.Callback callbackContext = getCallbackContext(id); if (callbackContext != null) { if (bundle.getBoolean("isSuccess", false)) { callbackContext.success(data); @@ -199,15 +196,15 @@ public void handleMessage(Message msg) { } } else { String pid = id; - CallbackContext callbackContext = getCallbackContext(pid); + com.foxdebug.acode.runtime.Callback callbackContext = getCallbackContext(pid); if (callbackContext != null) { switch (action) { case "stdout": case "stderr": - PluginResult result = new PluginResult(PluginResult.Status.OK, action + ":" + data); + Payload result = new Payload(Payload.Status.OK, action + ":" + data); result.setKeepCallback(true); - callbackContext.sendPluginResult(result); + callbackContext.sendPayload(result); break; case "exit": cleanupCallback(pid); @@ -232,7 +229,7 @@ public void handleMessage(Message msg) { } @Override - public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { + public boolean execute(String action, JSONArray args, Callback callbackContext) throws JSONException { // For actions that don't need the service, handle them directly if (action.equals("loadLibrary")) { callbackContext.error("This feature is no longer supported. Loading native libraries directly from JavaScript is no longer allowed due to security reasons."); @@ -395,11 +392,11 @@ private void stopServiceNow() { } private void startProcess(String pid, String cmd, String alpine) { - CallbackContext callbackContext = getCallbackContext(pid); + com.foxdebug.acode.runtime.Callback callbackContext = getCallbackContext(pid); if (callbackContext != null) { - PluginResult result = new PluginResult(PluginResult.Status.OK, pid); + Payload result = new Payload(Payload.Status.OK, pid); result.setKeepCallback(true); - callbackContext.sendPluginResult(result); + callbackContext.sendPayload(result); } Message msg = Message.obtain(null, TerminalService.MSG_START_PROCESS); @@ -412,7 +409,7 @@ private void startProcess(String pid, String cmd, String alpine) { try { serviceMessenger.send(msg); } catch (RemoteException e) { - CallbackContext errorContext = getCallbackContext(pid); + Callback errorContext = getCallbackContext(pid); if (errorContext != null) { errorContext.error("Failed to start process: " + e.getMessage()); cleanupCallback(pid); @@ -431,7 +428,7 @@ private void exec(String execId, String cmd, String alpine) { try { serviceMessenger.send(msg); } catch (RemoteException e) { - CallbackContext callbackContext = getCallbackContext(execId); + com.foxdebug.acode.runtime.Callback callbackContext = getCallbackContext(execId); if (callbackContext != null) { callbackContext.error("Failed to execute command: " + e.getMessage()); cleanupCallback(execId); @@ -439,7 +436,7 @@ private void exec(String execId, String cmd, String alpine) { } } - private void writeToProcess(String pid, String input, CallbackContext callbackContext) { + private void writeToProcess(String pid, String input, Callback callbackContext) { Message msg = Message.obtain(null, TerminalService.MSG_WRITE_TO_PROCESS); Bundle bundle = new Bundle(); bundle.putString("id", pid); @@ -453,7 +450,7 @@ private void writeToProcess(String pid, String input, CallbackContext callbackCo } } - private void stopProcess(String pid, CallbackContext callbackContext) { + private void stopProcess(String pid, Callback callbackContext) { Message msg = Message.obtain(null, TerminalService.MSG_STOP_PROCESS); Bundle bundle = new Bundle(); bundle.putString("id", pid); @@ -475,7 +472,7 @@ private void isProcessRunning(String pid) { try { serviceMessenger.send(msg); } catch (RemoteException e) { - CallbackContext callbackContext = getCallbackContext(pid); + com.foxdebug.acode.runtime.Callback callbackContext = getCallbackContext(pid); if (callbackContext != null) { callbackContext.error("Check running error: " + e.getMessage()); cleanupCallback(pid); @@ -492,7 +489,7 @@ private void listProcesses(String requestId) { try { serviceMessenger.send(msg); } catch (RemoteException e) { - CallbackContext callbackContext = getCallbackContext(requestId); + com.foxdebug.acode.runtime.Callback callbackContext = getCallbackContext(requestId); if (callbackContext != null) { callbackContext.error("List processes error: " + e.getMessage()); cleanupCallback(requestId); @@ -500,7 +497,7 @@ private void listProcesses(String requestId) { } } - private CallbackContext getCallbackContext(String id) { + private Callback getCallbackContext(String id) { return callbackContextMap.get(id); } diff --git a/src/plugins/terminal/src/android/ProcessManager.java b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/ProcessManager.java similarity index 98% rename from src/plugins/terminal/src/android/ProcessManager.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/terminal/ProcessManager.java index 51c94d25f7..458c3b2e2d 100644 --- a/src/plugins/terminal/src/android/ProcessManager.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/ProcessManager.java @@ -1,4 +1,4 @@ -package com.foxdebug.acode.rk.exec.terminal; +package com.foxdebug.acode.terminal; import android.content.Context; import android.content.pm.PackageManager; @@ -9,7 +9,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import com.foxdebug.acode.rk.exec.terminal.*; public class ProcessManager { diff --git a/src/plugins/terminal/src/android/ProcessServer.java b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/ProcessServer.java similarity index 98% rename from src/plugins/terminal/src/android/ProcessServer.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/terminal/ProcessServer.java index c6c264164b..ad6b07854f 100644 --- a/src/plugins/terminal/src/android/ProcessServer.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/ProcessServer.java @@ -1,4 +1,4 @@ -package com.foxdebug.acode.rk.exec.terminal; +package com.foxdebug.acode.terminal; import org.java_websocket.WebSocket; import org.java_websocket.handshake.ClientHandshake; diff --git a/src/plugins/terminal/src/android/ProcessUtils.java b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/ProcessUtils.java similarity index 98% rename from src/plugins/terminal/src/android/ProcessUtils.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/terminal/ProcessUtils.java index 003084f81e..21d0cec28d 100644 --- a/src/plugins/terminal/src/android/ProcessUtils.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/ProcessUtils.java @@ -1,4 +1,4 @@ -package com.foxdebug.acode.rk.exec.terminal; +package com.foxdebug.acode.terminal; import java.lang.reflect.Field; import java.io.*; @@ -6,7 +6,6 @@ import org.json.JSONArray; import org.json.JSONObject; import android.util.Log; -import com.foxdebug.acode.rk.exec.terminal.*; public class ProcessUtils { diff --git a/src/plugins/terminal/src/android/StreamHandler.java b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/StreamHandler.java similarity index 90% rename from src/plugins/terminal/src/android/StreamHandler.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/terminal/StreamHandler.java index ab4c643c73..07afdacb79 100644 --- a/src/plugins/terminal/src/android/StreamHandler.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/StreamHandler.java @@ -1,7 +1,6 @@ -package com.foxdebug.acode.rk.exec.terminal; +package com.foxdebug.acode.terminal; import java.io.*; -import com.foxdebug.acode.rk.exec.terminal.*; public class StreamHandler { public interface OutputListener { diff --git a/src/plugins/terminal/src/android/TerminalService.java b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/TerminalService.java similarity index 99% rename from src/plugins/terminal/src/android/TerminalService.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/terminal/TerminalService.java index f662664ce1..b0815745c1 100644 --- a/src/plugins/terminal/src/android/TerminalService.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/terminal/TerminalService.java @@ -1,4 +1,4 @@ -package com.foxdebug.acode.rk.exec.terminal; +package com.foxdebug.acode.terminal; import android.app.Notification; import android.app.NotificationChannel; @@ -24,7 +24,6 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; -import com.foxdebug.acode.rk.exec.terminal.*; public class TerminalService extends Service { diff --git a/src/plugins/websocket/src/android/WebSocketInstance.java b/platforms/android/app/src/main/java/com/foxdebug/acode/websocket/WebSocketInstance.java similarity index 77% rename from src/plugins/websocket/src/android/WebSocketInstance.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/websocket/WebSocketInstance.java index dd9241aead..9dbd377cae 100644 --- a/src/plugins/websocket/src/android/WebSocketInstance.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/websocket/WebSocketInstance.java @@ -1,16 +1,19 @@ -package com.foxdebug.websocket; +package com.foxdebug.acode.websocket; import android.util.Base64; import android.util.Log; import androidx.annotation.NonNull; -import org.apache.cordova.*; +import com.foxdebug.acode.runtime.*; +import com.foxdebug.acode.runtime.Callback; + import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Iterator; +import java.util.ArrayDeque; import java.util.concurrent.TimeUnit; import okhttp3.*; @@ -23,8 +26,9 @@ public class WebSocketInstance extends WebSocketListener { private static final String DEFAULT_CLOSE_REASON = "Normal closure"; private WebSocket webSocket; - private CallbackContext callbackContext; - private final CordovaInterface cordova; + private Callback callbackContext; + private final ArrayDeque<Payload> pendingEvents = new ArrayDeque<>(); + private final Host host; private final String instanceId; private String extensions = ""; private String protocol = ""; @@ -32,15 +36,16 @@ public class WebSocketInstance extends WebSocketListener { private int readyState = 0; // CONNECTING // okHttpMainClient parameter is used. To have a single main client(singleton), with per-websocket configuration using newBuilder method. - public WebSocketInstance(String url, JSONArray protocols, JSONObject headers, String binaryType, OkHttpClient okHttpMainClient, CordovaInterface cordova, String instanceId) { - this.cordova = cordova; + public WebSocketInstance(String url, JSONArray protocols, JSONObject headers, String binaryType, OkHttpClient okHttpMainClient, Host host, String instanceId) { + this(url, protocols, headers, binaryType, (WebSocket.Factory) okHttpMainClient.newBuilder() + .connectTimeout(10, TimeUnit.SECONDS).build(), host, instanceId); + } + + WebSocketInstance(String url, JSONArray protocols, JSONObject headers, String binaryType, WebSocket.Factory client, Host host, String instanceId) { + this.host = host; this.instanceId = instanceId; this.binaryType = binaryType; - OkHttpClient client = okHttpMainClient.newBuilder() - .connectTimeout(10, TimeUnit.SECONDS) - .build(); - Request.Builder requestBuilder = new Request.Builder().url(url); // custom headers support. @@ -68,11 +73,13 @@ public WebSocketInstance(String url, JSONArray protocols, JSONObject headers, St client.newWebSocket(requestBuilder.build(), this); } - public void setCallback(CallbackContext callbackContext) { + public synchronized void setCallback(Callback callbackContext) { this.callbackContext = callbackContext; - PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); + Payload result = new Payload(Payload.Status.NO_RESULT); result.setKeepCallback(true); - callbackContext.sendPluginResult(result); + callbackContext.sendPayload(result); + while (!pendingEvents.isEmpty()) callbackContext.sendPayload(pendingEvents.removeFirst()); + if (readyState == 3) WebSocketPlugin.removeInstance(instanceId); } public void send(String message, boolean isBinary) { @@ -180,8 +187,6 @@ public void onClosed(@NonNull WebSocket webSocket, int code, @NonNull String rea Log.e(TAG, "Error creating close event", e); } sendEvent("close", closedEvent.toString(), false, false); - // remove instance after receiving close. - WebSocketPlugin.removeInstance(this.instanceId); } @Override @@ -195,23 +200,26 @@ public void setBinaryType(String binaryType) { this.binaryType = binaryType; } - private void sendEvent(String type, String data, boolean isBinary, boolean parseAsText) { - if (callbackContext != null) { - try { - JSONObject event = new JSONObject(); - event.put("type", type); - event.put("extensions", this.extensions); - event.put("readyState", this.readyState); - event.put("isBinary", isBinary); - event.put("parseAsText", parseAsText); - if (data != null) event.put("data", data); - Log.d(TAG, "sending event: " + type + " eventObj " + event.toString()); - PluginResult result = new PluginResult(PluginResult.Status.OK, event); - result.setKeepCallback(true); - callbackContext.sendPluginResult(result); - } catch (Exception e) { - Log.e(TAG, "Error sending event", e); + private synchronized void sendEvent(String type, String data, boolean isBinary, boolean parseAsText) { + try { + JSONObject event = new JSONObject(); + event.put("type", type); + event.put("extensions", this.extensions); + event.put("readyState", this.readyState); + event.put("isBinary", isBinary); + event.put("parseAsText", parseAsText); + if (data != null) event.put("data", data); + Log.d(TAG, "sending event: " + type + " eventObj " + event.toString()); + Payload result = new Payload(Payload.Status.OK, event); + result.setKeepCallback(readyState != 3); + // The connection can open before JS receives its ID and registers a listener. + if (callbackContext == null) pendingEvents.addLast(result); + else { + callbackContext.sendPayload(result); + if (readyState == 3) WebSocketPlugin.removeInstance(instanceId); } + } catch (Exception e) { + Log.e(TAG, "Error sending event", e); } } } diff --git a/src/plugins/websocket/src/android/WebSocketPlugin.java b/platforms/android/app/src/main/java/com/foxdebug/acode/websocket/WebSocketPlugin.java similarity index 94% rename from src/plugins/websocket/src/android/WebSocketPlugin.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/websocket/WebSocketPlugin.java index c8fb832f33..8c087ec9e1 100644 --- a/src/plugins/websocket/src/android/WebSocketPlugin.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/websocket/WebSocketPlugin.java @@ -1,8 +1,9 @@ -package com.foxdebug.websocket; +package com.foxdebug.acode.websocket; import android.util.Log; -import org.apache.cordova.*; +import com.foxdebug.acode.runtime.*; + import org.json.*; import java.util.UUID; @@ -11,18 +12,18 @@ import okhttp3.OkHttpClient; // TODO: plugin init & plugin destroy(closing okhttp clients) lifecycles. (✅) -public class WebSocketPlugin extends CordovaPlugin { +public class WebSocketPlugin extends Service { private static final ConcurrentHashMap<String, WebSocketInstance> instances = new ConcurrentHashMap<>(); public OkHttpClient okHttpMainClient = null; @Override - protected void pluginInitialize() { + public void serviceInitialize() { this.okHttpMainClient = new OkHttpClient(); } @Override - public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { - cordova.getThreadPool().execute(new Runnable() { + public boolean execute(String action, JSONArray args, final Callback callbackContext) throws JSONException { + host.getThreadPool().execute(new Runnable() { @Override public void run() { @@ -33,7 +34,7 @@ public void run() { JSONObject headers = args.optJSONObject(2); String binaryType = args.optString(3, null); String id = UUID.randomUUID().toString(); - WebSocketInstance instance = new WebSocketInstance(url, protocols, headers, binaryType, okHttpMainClient, cordova, id); + WebSocketInstance instance = new WebSocketInstance(url, protocols, headers, binaryType, okHttpMainClient, host, id); instances.put(id, instance); callbackContext.success(id); return; diff --git a/src/plugins/webview/src/android/com/foxdebug/webview/ProfileManager.java b/platforms/android/app/src/main/java/com/foxdebug/acode/webview/ProfileManager.java similarity index 99% rename from src/plugins/webview/src/android/com/foxdebug/webview/ProfileManager.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/webview/ProfileManager.java index 1968d6aebd..058630aade 100644 --- a/src/plugins/webview/src/android/com/foxdebug/webview/ProfileManager.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/webview/ProfileManager.java @@ -1,4 +1,4 @@ -package com.foxdebug.webview; +package com.foxdebug.acode.webview; import android.util.Log; import android.webkit.CookieManager; diff --git a/src/plugins/webview/src/android/com/foxdebug/webview/WebViewActivity.java b/platforms/android/app/src/main/java/com/foxdebug/acode/webview/WebViewActivity.java similarity index 95% rename from src/plugins/webview/src/android/com/foxdebug/webview/WebViewActivity.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/webview/WebViewActivity.java index 849eaea57f..0e8631d8e0 100644 --- a/src/plugins/webview/src/android/com/foxdebug/webview/WebViewActivity.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/webview/WebViewActivity.java @@ -1,4 +1,4 @@ -package com.foxdebug.webview; +package com.foxdebug.acode.webview; import android.app.Activity; import android.os.Build; @@ -25,7 +25,7 @@ public void onCreate(Bundle savedInstanceState) { webviewId = getIntent().getStringExtra("webviewId"); - // The plugin registers itself in pluginInitialize(), so the singleton is + // The plugin registers itself in serviceInitialize(), so the singleton is // always available while the app is alive. WebViewPlugin plugin = WebViewPlugin.getInstance(); WebViewInstance instance = plugin != null ? plugin.getInstance(webviewId) : null; @@ -132,7 +132,7 @@ protected void onDestroy() { instance.destroy(); plugin.removeInstance(webviewId); } - plugin.sendEventToCordova(webviewId, "closed", null); + plugin.sendEventToBridge(webviewId, "closed", null); } webView = null; diff --git a/src/plugins/webview/src/android/com/foxdebug/webview/WebViewInstance.java b/platforms/android/app/src/main/java/com/foxdebug/acode/webview/WebViewInstance.java similarity index 95% rename from src/plugins/webview/src/android/com/foxdebug/webview/WebViewInstance.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/webview/WebViewInstance.java index 770dd0accd..ed9714b24e 100644 --- a/src/plugins/webview/src/android/com/foxdebug/webview/WebViewInstance.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/webview/WebViewInstance.java @@ -1,4 +1,4 @@ -package com.foxdebug.webview; +package com.foxdebug.acode.webview; import android.app.Activity; import android.app.AlertDialog; @@ -45,8 +45,7 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.PluginResult; +import com.foxdebug.acode.runtime.Callback; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; @@ -359,7 +358,7 @@ private void loadHtmlNow(String html, JSONObject htmlOptions) { // Page actions // --------------------------------------------------------------------------- - void loadURL(String url, JSONObject headers, final CallbackContext callbackContext) { + void loadURL(String url, JSONObject headers, final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; final String safeUrl = sanitizeUrl(url); @@ -389,7 +388,7 @@ void loadURL(String url, JSONObject headers, final CallbackContext callbackConte }); } - void loadHTML(String html, JSONObject htmlOptions, final CallbackContext callbackContext) { + void loadHTML(String html, JSONObject htmlOptions, final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; if (webView == null) { @@ -407,7 +406,7 @@ void loadHTML(String html, JSONObject htmlOptions, final CallbackContext callbac }); } - void evaluate(String js, final CallbackContext callbackContext) { + void evaluate(String js, final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; if (rejectIfNotReady(callbackContext)) return; @@ -432,7 +431,7 @@ private static String decodeJsResult(String value) { } } - void postMessage(String message, final CallbackContext callbackContext) { + void postMessage(String message, final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; if (rejectIfNotReady(callbackContext)) return; @@ -453,7 +452,7 @@ void postMessage(String message, final CallbackContext callbackContext) { }); } - void show(final CallbackContext callbackContext) { + void show(final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; if (!isFullscreen()) { callbackContext.error( @@ -465,7 +464,7 @@ void show(final CallbackContext callbackContext) { callbackContext.success(); } - void hide(final CallbackContext callbackContext) { + void hide(final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; if (!isFullscreen()) { // A hidden (headless) WebView is already hidden. @@ -481,7 +480,7 @@ void hide(final CallbackContext callbackContext) { * back with its page state intact. The instance is only destroyed when the * user actually closes it (back button/task removal) or destroy() is called. */ - private void hideFullscreen(CallbackContext callbackContext) { + private void hideFullscreen(Callback callbackContext) { runOnUiThread(() -> { if (hostingActivity != null && !hostingActivity.isFinishing() @@ -492,7 +491,7 @@ private void hideFullscreen(CallbackContext callbackContext) { callbackContext.success(); } - void reload(final CallbackContext callbackContext) { + void reload(final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; if (rejectIfNotReady(callbackContext)) return; runOnUiThread(() -> { @@ -501,7 +500,7 @@ void reload(final CallbackContext callbackContext) { }); } - void stopLoading(final CallbackContext callbackContext) { + void stopLoading(final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; if (rejectIfNotReady(callbackContext)) return; runOnUiThread(() -> { @@ -510,7 +509,7 @@ void stopLoading(final CallbackContext callbackContext) { }); } - void goBack(final CallbackContext callbackContext) { + void goBack(final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; if (rejectIfNotReady(callbackContext)) return; runOnUiThread(() -> { @@ -520,7 +519,7 @@ void goBack(final CallbackContext callbackContext) { }); } - void goForward(final CallbackContext callbackContext) { + void goForward(final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; if (rejectIfNotReady(callbackContext)) return; runOnUiThread(() -> { @@ -530,19 +529,19 @@ void goForward(final CallbackContext callbackContext) { }); } - void canGoBack(final CallbackContext callbackContext) { + void canGoBack(final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; if (rejectIfNotReady(callbackContext)) return; runOnUiThread(() -> sendBooleanResult(callbackContext, webView.canGoBack())); } - void canGoForward(final CallbackContext callbackContext) { + void canGoForward(final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; if (rejectIfNotReady(callbackContext)) return; runOnUiThread(() -> sendBooleanResult(callbackContext, webView.canGoForward())); } - void clearCache(final boolean includeDiskFiles, final CallbackContext callbackContext) { + void clearCache(final boolean includeDiskFiles, final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; if (rejectIfNotReady(callbackContext)) return; runOnUiThread(() -> { @@ -551,7 +550,7 @@ void clearCache(final boolean includeDiskFiles, final CallbackContext callbackCo }); } - void clearHistory(final CallbackContext callbackContext) { + void clearHistory(final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; if (rejectIfNotReady(callbackContext)) return; runOnUiThread(() -> { @@ -560,7 +559,7 @@ void clearHistory(final CallbackContext callbackContext) { }); } - void clearFormData(final CallbackContext callbackContext) { + void clearFormData(final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; if (rejectIfNotReady(callbackContext)) return; runOnUiThread(() -> { @@ -569,7 +568,7 @@ void clearFormData(final CallbackContext callbackContext) { }); } - void setUserAgent(final String userAgent, final String mode, final CallbackContext callbackContext) { + void setUserAgent(final String userAgent, final String mode, final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; final JSONObject partial = new JSONObject(); @@ -586,7 +585,7 @@ void setUserAgent(final String userAgent, final String mode, final CallbackConte applySettings(partial, callbackContext); } - void getUserAgent(final CallbackContext callbackContext) { + void getUserAgent(final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; runOnUiThread(() -> { if (destroyed) { @@ -603,7 +602,7 @@ void getUserAgent(final CallbackContext callbackContext) { }); } - void updateSettings(final JSONObject partial, final CallbackContext callbackContext) { + void updateSettings(final JSONObject partial, final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; applySettings(partial, callbackContext); } @@ -612,7 +611,7 @@ void updateSettings(final JSONObject partial, final CallbackContext callbackCont * Applies a settings batch on the UI thread — WebSettings and WebView methods * must be touched there — and completes the callback once it is applied. */ - private void applySettings(final JSONObject partial, final CallbackContext callbackContext) { + private void applySettings(final JSONObject partial, final Callback callbackContext) { runOnUiThread(() -> { if (destroyed) { callbackContext.error("WebView has been destroyed"); @@ -627,7 +626,7 @@ private void applySettings(final JSONObject partial, final CallbackContext callb }); } - void getSettings(final CallbackContext callbackContext) { + void getSettings(final Callback callbackContext) { if (rejectIfDestroyed(callbackContext)) return; runOnUiThread(() -> { if (destroyed) { @@ -638,7 +637,7 @@ void getSettings(final CallbackContext callbackContext) { }); } - void getInfo(final CallbackContext callbackContext) { + void getInfo(final Callback callbackContext) { try { final JSONObject info = new JSONObject(); info.put("id", id); @@ -837,20 +836,22 @@ void exitCustomView() { // --------------------------------------------------------------------------- /** - * Cordova's boolean callback overload is not available on every supported - * Android platform version, so send the boolean explicitly. + * Callback has no boolean success overload, so send the boolean in an + * explicit payload. */ - private static void sendBooleanResult(CallbackContext callbackContext, boolean value) { - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, value)); + private static void sendBooleanResult(Callback callbackContext, boolean value) { + callbackContext.sendPayload( + new com.foxdebug.acode.runtime.Payload(com.foxdebug.acode.runtime.Payload.Status.OK, value) + ); } - private boolean rejectIfDestroyed(CallbackContext callbackContext) { + private boolean rejectIfDestroyed(Callback callbackContext) { if (!destroyed) return false; callbackContext.error("WebView has been destroyed"); return true; } - private boolean rejectIfNotReady(CallbackContext callbackContext) { + private boolean rejectIfNotReady(Callback callbackContext) { if (webView != null) return false; callbackContext.error("WebView is not ready"); return true; @@ -865,7 +866,7 @@ private Context appContext() { } private void emit(String event, Payload data) { - plugin.sendEventToCordova(id, event, data.json); + plugin.sendEventToBridge(id, event, data.json); } private static Payload data() { @@ -1343,7 +1344,7 @@ public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) { public class JsBridge { @JavascriptInterface public void postMessage(String message) { - plugin.sendMessageToCordova(id, message); + plugin.sendMessageToBridge(id, message); } } } diff --git a/src/plugins/webview/src/android/com/foxdebug/webview/WebViewOptions.java b/platforms/android/app/src/main/java/com/foxdebug/acode/webview/WebViewOptions.java similarity index 99% rename from src/plugins/webview/src/android/com/foxdebug/webview/WebViewOptions.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/webview/WebViewOptions.java index a2ea79216f..31f24498ac 100644 --- a/src/plugins/webview/src/android/com/foxdebug/webview/WebViewOptions.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/webview/WebViewOptions.java @@ -1,4 +1,4 @@ -package com.foxdebug.webview; +package com.foxdebug.acode.webview; import android.content.Context; import android.graphics.Color; diff --git a/src/plugins/webview/src/android/com/foxdebug/webview/WebViewPlugin.java b/platforms/android/app/src/main/java/com/foxdebug/acode/webview/WebViewPlugin.java similarity index 85% rename from src/plugins/webview/src/android/com/foxdebug/webview/WebViewPlugin.java rename to platforms/android/app/src/main/java/com/foxdebug/acode/webview/WebViewPlugin.java index 068134d29a..5fe56f66fd 100644 --- a/src/plugins/webview/src/android/com/foxdebug/webview/WebViewPlugin.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/webview/WebViewPlugin.java @@ -1,4 +1,4 @@ -package com.foxdebug.webview; +package com.foxdebug.acode.webview; import android.app.DownloadManager; import android.content.Context; @@ -12,31 +12,31 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.UUID; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.PluginResult; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Service; +import com.foxdebug.acode.runtime.Payload; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** - * Cordova entry point for the Acode WebView API. + * Bridge service entry point for the Acode WebView API. * * <p>Owns the instance registry, routes each JS call to the matching * {@link WebViewInstance}, and forwards page/lifecycle events back over the * single long-lived "setMessageCallback" channel. */ -public class WebViewPlugin extends CordovaPlugin { +public class WebViewPlugin extends Service { private static final String TAG = "AcodeWebView"; private static final String PLUGIN_VERSION = "2.0.0"; private static WebViewPlugin instance; private final HashMap<String, WebViewInstance> instances = new HashMap<>(); - private CallbackContext messageCallback; + private Callback messageCallback; @Override - protected void pluginInitialize() { + public void serviceInitialize() { instance = this; // Remove incognito profiles left behind if the process was killed before // their instance could be destroyed. @@ -48,7 +48,7 @@ public static WebViewPlugin getInstance() { } @Override - public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { + public boolean execute(String action, JSONArray args, Callback callbackContext) { try { switch (action) { case "setMessageCallback": @@ -139,11 +139,11 @@ public boolean execute(String action, JSONArray args, CallbackContext callbackCo return true; } - private void setMessageCallback(CallbackContext callbackContext) { + private void setMessageCallback(Callback callbackContext) { this.messageCallback = callbackContext; - PluginResult keepResult = new PluginResult(PluginResult.Status.NO_RESULT); + Payload keepResult = new Payload(Payload.Status.NO_RESULT); keepResult.setKeepCallback(true); - callbackContext.sendPluginResult(keepResult); + callbackContext.sendPayload(keepResult); } /** @@ -161,7 +161,7 @@ private String generateId() { return "wv_" + UUID.randomUUID().toString().replace("-", "").substring(0, 12); } - private void create(final JSONObject rawOptions, final CallbackContext callbackContext) { + private void create(final JSONObject rawOptions, final Callback callbackContext) { final WebViewOptions options; try { options = WebViewOptions.fromJson(rawOptions); @@ -172,7 +172,7 @@ private void create(final JSONObject rawOptions, final CallbackContext callbackC final String id = generateId(); - cordova.getActivity().runOnUiThread(() -> { + host.getActivity().runOnUiThread(() -> { WebViewInstance instance = new WebViewInstance(id, options, WebViewPlugin.this); instances.put(id, instance); @@ -186,7 +186,7 @@ private void create(final JSONObject rawOptions, final CallbackContext callbackC } } else { // "hidden" mode: a headless WebView that is never displayed. - instance.createWebView(cordova.getActivity()); + instance.createWebView(host.getActivity()); } JSONObject result = new JSONObject(); @@ -222,14 +222,14 @@ private void create(final JSONObject rawOptions, final CallbackContext callbackC * backgrounded it), preserving the WebView's page state. */ void showFullscreenActivity(String id) { - Intent intent = new Intent(cordova.getActivity(), WebViewActivity.class); + Intent intent = new Intent(host.getActivity(), WebViewActivity.class); intent.putExtra("webviewId", id); WebViewInstance target = getInstance(id); WebViewActivity hosting = target != null ? target.getHostingActivity() : null; if (hosting != null && !hosting.isFinishing() && !hosting.isDestroyed()) { intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); } - cordova.getActivity().startActivity(intent); + host.getActivity().startActivity(intent); } public WebViewInstance getInstance(String id) { @@ -242,10 +242,10 @@ public void removeInstance(String id) { /** Context used for options that need a Context even before the WebView exists. */ public Context getContext() { - return cordova.getContext(); + return host.getActivity(); } - private WebViewInstance requireInstance(String id, CallbackContext callbackContext) { + private WebViewInstance requireInstance(String id, Callback callbackContext) { WebViewInstance instance = getInstance(id); if (instance == null) { callbackContext.error("WebView not found: " + id); @@ -257,7 +257,7 @@ private void loadURL( String id, String url, JSONObject headers, - CallbackContext callbackContext + Callback callbackContext ) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; @@ -268,86 +268,86 @@ private void loadHTML( String id, String html, JSONObject htmlOptions, - CallbackContext callbackContext + Callback callbackContext ) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.loadHTML(html, htmlOptions, callbackContext); } - private void evaluate(String id, String js, CallbackContext callbackContext) { + private void evaluate(String id, String js, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.evaluate(js, callbackContext); } - private void postMessage(String id, String message, CallbackContext callbackContext) { + private void postMessage(String id, String message, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.postMessage(message, callbackContext); } - private void show(String id, CallbackContext callbackContext) { + private void show(String id, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.show(callbackContext); } - private void hide(String id, CallbackContext callbackContext) { + private void hide(String id, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.hide(callbackContext); } - private void reload(String id, CallbackContext callbackContext) { + private void reload(String id, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.reload(callbackContext); } - private void stopLoading(String id, CallbackContext callbackContext) { + private void stopLoading(String id, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.stopLoading(callbackContext); } - private void goBack(String id, CallbackContext callbackContext) { + private void goBack(String id, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.goBack(callbackContext); } - private void goForward(String id, CallbackContext callbackContext) { + private void goForward(String id, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.goForward(callbackContext); } - private void canGoBack(String id, CallbackContext callbackContext) { + private void canGoBack(String id, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.canGoBack(callbackContext); } - private void canGoForward(String id, CallbackContext callbackContext) { + private void canGoForward(String id, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.canGoForward(callbackContext); } - private void clearCache(String id, boolean includeDiskFiles, CallbackContext callbackContext) { + private void clearCache(String id, boolean includeDiskFiles, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.clearCache(includeDiskFiles, callbackContext); } - private void clearHistory(String id, CallbackContext callbackContext) { + private void clearHistory(String id, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.clearHistory(callbackContext); } - private void clearFormData(String id, CallbackContext callbackContext) { + private void clearFormData(String id, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.clearFormData(callbackContext); @@ -357,45 +357,45 @@ private void setUserAgent( String id, String userAgent, String mode, - CallbackContext callbackContext + Callback callbackContext ) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.setUserAgent(userAgent, mode, callbackContext); } - private void getUserAgent(String id, CallbackContext callbackContext) { + private void getUserAgent(String id, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.getUserAgent(callbackContext); } - private void updateSettings(String id, JSONObject settings, CallbackContext callbackContext) { + private void updateSettings(String id, JSONObject settings, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.updateSettings(settings, callbackContext); } - private void getSettings(String id, CallbackContext callbackContext) { + private void getSettings(String id, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.getSettings(callbackContext); } - private void getInfo(String id, CallbackContext callbackContext) { + private void getInfo(String id, Callback callbackContext) { WebViewInstance instance = requireInstance(id, callbackContext); if (instance == null) return; instance.getInfo(callbackContext); } - private void destroy(String id, final CallbackContext callbackContext) { + private void destroy(String id, final Callback callbackContext) { final WebViewInstance instance = instances.remove(id); if (instance == null) { callbackContext.error("WebView not found: " + id); return; } - cordova.getActivity().runOnUiThread(() -> { + host.getActivity().runOnUiThread(() -> { instance.destroy(); callbackContext.success(); }); @@ -438,7 +438,7 @@ boolean download( String mimeType, String fileName ) { - Context context = cordova.getActivity(); + Context context = host.getActivity(); try { DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setMimeType(mimeType); @@ -472,7 +472,7 @@ boolean download( } } - public void sendMessageToCordova(String id, String message) { + public void sendMessageToBridge(String id, String message) { try { JSONObject payload = new JSONObject(); payload.put("id", id); @@ -483,7 +483,7 @@ public void sendMessageToCordova(String id, String message) { } } - public void sendEventToCordova(String id, String event, JSONObject data) { + public void sendEventToBridge(String id, String event, JSONObject data) { try { JSONObject payload = new JSONObject(); payload.put("id", id); @@ -499,9 +499,9 @@ public void sendEventToCordova(String id, String event, JSONObject data) { private void sendPayload(JSONObject payload) { if (messageCallback == null) return; - PluginResult result = new PluginResult(PluginResult.Status.OK, payload); + Payload result = new Payload(Payload.Status.OK, payload); result.setKeepCallback(true); - messageCallback.sendPluginResult(result); + messageCallback.sendPayload(result); } @Override diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpBodyDecoder.java b/platforms/android/app/src/main/java/com/silkimen/http/HttpBodyDecoder.java similarity index 100% rename from src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpBodyDecoder.java rename to platforms/android/app/src/main/java/com/silkimen/http/HttpBodyDecoder.java diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpRequest.java b/platforms/android/app/src/main/java/com/silkimen/http/HttpRequest.java similarity index 99% rename from src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpRequest.java rename to platforms/android/app/src/main/java/com/silkimen/http/HttpRequest.java index 7e638bb141..f8e01bbe71 100644 --- a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpRequest.java +++ b/platforms/android/app/src/main/java/com/silkimen/http/HttpRequest.java @@ -1,6 +1,6 @@ /* * Copyright (c) 2014 Kevin Sawicki <kevinsawicki@gmail.com> - * modified by contributors of cordova-plugin-advanced-http + * modified by upstream contributors; see licenses/NOTICE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/JsonUtils.java b/platforms/android/app/src/main/java/com/silkimen/http/JsonUtils.java similarity index 100% rename from src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/JsonUtils.java rename to platforms/android/app/src/main/java/com/silkimen/http/JsonUtils.java diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/KeyChainKeyManager.java b/platforms/android/app/src/main/java/com/silkimen/http/KeyChainKeyManager.java similarity index 100% rename from src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/KeyChainKeyManager.java rename to platforms/android/app/src/main/java/com/silkimen/http/KeyChainKeyManager.java diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSConfiguration.java b/platforms/android/app/src/main/java/com/silkimen/http/TLSConfiguration.java similarity index 100% rename from src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSConfiguration.java rename to platforms/android/app/src/main/java/com/silkimen/http/TLSConfiguration.java diff --git a/src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSSocketFactory.java b/platforms/android/app/src/main/java/com/silkimen/http/TLSSocketFactory.java similarity index 100% rename from src/plugins/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSSocketFactory.java rename to platforms/android/app/src/main/java/com/silkimen/http/TLSSocketFactory.java diff --git a/platforms/android/app/src/main/java/com/verso/clipboard/Clipboard.java b/platforms/android/app/src/main/java/com/verso/clipboard/Clipboard.java new file mode 100644 index 0000000000..c15242158d --- /dev/null +++ b/platforms/android/app/src/main/java/com/verso/clipboard/Clipboard.java @@ -0,0 +1,72 @@ +package com.verso.clipboard; + +import com.foxdebug.acode.runtime.Service; +import com.foxdebug.acode.runtime.Payload; +import com.foxdebug.acode.runtime.Callback; + +import org.json.JSONArray; +import org.json.JSONException; + +import android.content.Context; +import android.content.ClipboardManager; +import android.content.ClipData; +import android.content.ClipDescription; + +public class Clipboard extends Service { + + private static final String actionCopy = "copy"; + private static final String actionPaste = "paste"; + private static final String actionClear = "clear"; + + @Override + public boolean execute(String action, JSONArray args, Callback callbackContext) throws JSONException { + ClipboardManager clipboard = (ClipboardManager) host.getActivity().getSystemService(Context.CLIPBOARD_SERVICE); + + if (action.equals(actionCopy)) { + try { + String text = args.getString(0); + ClipData clip = ClipData.newPlainText("Text", text); + + clipboard.setPrimaryClip(clip); + + callbackContext.success(text); + + return true; + } catch (JSONException e) { + callbackContext.sendPayload(new Payload(Payload.Status.JSON_EXCEPTION)); + } catch (Exception e) { + callbackContext.sendPayload(new Payload(Payload.Status.ERROR, e.toString())); + } + } else if (action.equals(actionPaste)) { + try { + String text = ""; + + ClipData clip = clipboard.getPrimaryClip(); + if (clip != null) { + ClipData.Item item = clip.getItemAt(0); + text = item.getText().toString(); + } + callbackContext.success(text); + + return true; + } catch (Exception e) { + callbackContext.sendPayload(new Payload(Payload.Status.ERROR, e.toString())); + } + } else if (action.equals(actionClear)) { + try { + ClipData clip = ClipData.newPlainText("", ""); + clipboard.setPrimaryClip(clip); + + callbackContext.sendPayload(new Payload(Payload.Status.OK)); + + return true; + } catch (Exception e) { + callbackContext.sendPayload(new Payload(Payload.Status.ERROR, e.toString())); + } + } + + return false; + } +} + + diff --git a/src/plugins/browser/res/android/menu_enter.xml b/platforms/android/app/src/main/res/anim/menu_enter.xml similarity index 100% rename from src/plugins/browser/res/android/menu_enter.xml rename to platforms/android/app/src/main/res/anim/menu_enter.xml diff --git a/src/plugins/browser/res/android/menu_exit.xml b/platforms/android/app/src/main/res/anim/menu_exit.xml similarity index 100% rename from src/plugins/browser/res/android/menu_exit.xml rename to platforms/android/app/src/main/res/anim/menu_exit.xml diff --git a/res/android/drawable-xxxhdpi/ic_acode_cobalt_background.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_cobalt_background.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_cobalt_background.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_cobalt_background.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_cobalt_foreground.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_cobalt_foreground.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_cobalt_foreground.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_cobalt_foreground.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_glacier_background.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_glacier_background.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_glacier_background.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_glacier_background.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_glacier_foreground.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_glacier_foreground.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_glacier_foreground.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_glacier_foreground.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_lilac_background.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_lilac_background.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_lilac_background.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_lilac_background.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_lilac_foreground.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_lilac_foreground.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_lilac_foreground.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_lilac_foreground.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_porcelain_background.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_porcelain_background.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_porcelain_background.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_porcelain_background.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_porcelain_foreground.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_porcelain_foreground.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_porcelain_foreground.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_porcelain_foreground.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_prism_background.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_prism_background.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_prism_background.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_prism_background.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_prism_foreground.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_prism_foreground.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_prism_foreground.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_prism_foreground.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_tangerine_background.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_tangerine_background.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_tangerine_background.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_tangerine_background.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_tangerine_foreground.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_tangerine_foreground.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_tangerine_foreground.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_tangerine_foreground.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_tidal_background.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_tidal_background.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_tidal_background.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_tidal_background.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_tidal_foreground.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_tidal_foreground.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_tidal_foreground.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_tidal_foreground.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_volt_background.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_volt_background.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_volt_background.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_volt_background.webp diff --git a/res/android/drawable-xxxhdpi/ic_acode_volt_foreground.webp b/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_volt_foreground.webp similarity index 100% rename from res/android/drawable-xxxhdpi/ic_acode_volt_foreground.webp rename to platforms/android/app/src/main/res/drawable-xxxhdpi/ic_acode_volt_foreground.webp diff --git a/res/android/drawable/ic_acode_aurora_pulse_background.xml b/platforms/android/app/src/main/res/drawable/ic_acode_aurora_pulse_background.xml similarity index 100% rename from res/android/drawable/ic_acode_aurora_pulse_background.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_aurora_pulse_background.xml diff --git a/res/android/drawable/ic_acode_aurora_pulse_foreground.xml b/platforms/android/app/src/main/res/drawable/ic_acode_aurora_pulse_foreground.xml similarity index 100% rename from res/android/drawable/ic_acode_aurora_pulse_foreground.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_aurora_pulse_foreground.xml diff --git a/res/android/drawable/ic_acode_blueprint_background.xml b/platforms/android/app/src/main/res/drawable/ic_acode_blueprint_background.xml similarity index 100% rename from res/android/drawable/ic_acode_blueprint_background.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_blueprint_background.xml diff --git a/res/android/drawable/ic_acode_blueprint_foreground.xml b/platforms/android/app/src/main/res/drawable/ic_acode_blueprint_foreground.xml similarity index 100% rename from res/android/drawable/ic_acode_blueprint_foreground.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_blueprint_foreground.xml diff --git a/res/android/drawable/ic_acode_collection_monochrome.xml b/platforms/android/app/src/main/res/drawable/ic_acode_collection_monochrome.xml similarity index 100% rename from res/android/drawable/ic_acode_collection_monochrome.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_collection_monochrome.xml diff --git a/res/android/drawable/ic_acode_midnight_circuit_background.xml b/platforms/android/app/src/main/res/drawable/ic_acode_midnight_circuit_background.xml similarity index 100% rename from res/android/drawable/ic_acode_midnight_circuit_background.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_midnight_circuit_background.xml diff --git a/res/android/drawable/ic_acode_midnight_circuit_foreground.xml b/platforms/android/app/src/main/res/drawable/ic_acode_midnight_circuit_foreground.xml similarity index 100% rename from res/android/drawable/ic_acode_midnight_circuit_foreground.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_midnight_circuit_foreground.xml diff --git a/res/android/drawable/ic_acode_monochrome.xml b/platforms/android/app/src/main/res/drawable/ic_acode_monochrome.xml similarity index 100% rename from res/android/drawable/ic_acode_monochrome.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_monochrome.xml diff --git a/res/android/drawable/ic_acode_pixel_party_background.xml b/platforms/android/app/src/main/res/drawable/ic_acode_pixel_party_background.xml similarity index 100% rename from res/android/drawable/ic_acode_pixel_party_background.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_pixel_party_background.xml diff --git a/res/android/drawable/ic_acode_pixel_party_foreground.xml b/platforms/android/app/src/main/res/drawable/ic_acode_pixel_party_foreground.xml similarity index 100% rename from res/android/drawable/ic_acode_pixel_party_foreground.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_pixel_party_foreground.xml diff --git a/res/android/drawable/ic_acode_pro_background.xml b/platforms/android/app/src/main/res/drawable/ic_acode_pro_background.xml similarity index 100% rename from res/android/drawable/ic_acode_pro_background.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_pro_background.xml diff --git a/res/android/drawable/ic_acode_pro_foreground.xml b/platforms/android/app/src/main/res/drawable/ic_acode_pro_foreground.xml similarity index 100% rename from res/android/drawable/ic_acode_pro_foreground.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_pro_foreground.xml diff --git a/res/android/drawable/ic_acode_solar_flare_background.xml b/platforms/android/app/src/main/res/drawable/ic_acode_solar_flare_background.xml similarity index 100% rename from res/android/drawable/ic_acode_solar_flare_background.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_solar_flare_background.xml diff --git a/res/android/drawable/ic_acode_solar_flare_foreground.xml b/platforms/android/app/src/main/res/drawable/ic_acode_solar_flare_foreground.xml similarity index 100% rename from res/android/drawable/ic_acode_solar_flare_foreground.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_solar_flare_foreground.xml diff --git a/res/android/drawable/ic_acode_terminal_glow_background.xml b/platforms/android/app/src/main/res/drawable/ic_acode_terminal_glow_background.xml similarity index 100% rename from res/android/drawable/ic_acode_terminal_glow_background.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_terminal_glow_background.xml diff --git a/res/android/drawable/ic_acode_terminal_glow_foreground.xml b/platforms/android/app/src/main/res/drawable/ic_acode_terminal_glow_foreground.xml similarity index 100% rename from res/android/drawable/ic_acode_terminal_glow_foreground.xml rename to platforms/android/app/src/main/res/drawable/ic_acode_terminal_glow_foreground.xml diff --git a/res/android/drawable/ic_launcher_background.xml b/platforms/android/app/src/main/res/drawable/ic_launcher_background.xml similarity index 100% rename from res/android/drawable/ic_launcher_background.xml rename to platforms/android/app/src/main/res/drawable/ic_launcher_background.xml diff --git a/res/android/drawable/ic_launcher_foreground.xml b/platforms/android/app/src/main/res/drawable/ic_launcher_foreground.xml similarity index 100% rename from res/android/drawable/ic_launcher_foreground.xml rename to platforms/android/app/src/main/res/drawable/ic_launcher_foreground.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_aurora_pulse.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_aurora_pulse.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_aurora_pulse.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_aurora_pulse.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_aurora_pulse_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_aurora_pulse_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_aurora_pulse_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_aurora_pulse_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_blueprint.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_blueprint.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_blueprint.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_blueprint.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_blueprint_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_blueprint_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_blueprint_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_blueprint_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_cobalt.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_cobalt.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_cobalt.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_cobalt.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_cobalt_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_cobalt_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_cobalt_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_cobalt_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_glacier.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_glacier.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_glacier.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_glacier.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_glacier_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_glacier_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_glacier_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_glacier_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_lilac.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_lilac.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_lilac.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_lilac.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_lilac_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_lilac_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_lilac_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_lilac_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_midnight_circuit.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_midnight_circuit.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_midnight_circuit.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_midnight_circuit.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_midnight_circuit_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_midnight_circuit_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_midnight_circuit_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_midnight_circuit_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_pixel_party.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_pixel_party.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_pixel_party.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_pixel_party.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_pixel_party_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_pixel_party_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_pixel_party_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_pixel_party_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_porcelain.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_porcelain.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_porcelain.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_porcelain.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_porcelain_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_porcelain_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_porcelain_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_porcelain_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_prism.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_prism.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_prism.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_prism.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_prism_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_prism_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_prism_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_prism_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_pro.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_pro.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_pro.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_pro.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_pro_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_pro_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_pro_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_pro_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_solar_flare.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_solar_flare.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_solar_flare.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_solar_flare.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_solar_flare_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_solar_flare_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_solar_flare_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_solar_flare_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_tangerine.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_tangerine.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_tangerine.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_tangerine.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_tangerine_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_tangerine_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_tangerine_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_tangerine_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_terminal_glow.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_terminal_glow.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_terminal_glow.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_terminal_glow.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_terminal_glow_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_terminal_glow_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_terminal_glow_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_terminal_glow_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_tidal.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_tidal.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_tidal.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_tidal.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_tidal_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_tidal_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_tidal_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_tidal_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_volt.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_volt.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_volt.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_volt.xml diff --git a/res/android/mipmap-anydpi-v26/ic_acode_volt_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_volt_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_acode_volt_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_acode_volt_round.xml diff --git a/res/android/mipmap-anydpi-v26/ic_launcher.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_launcher.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml diff --git a/res/android/mipmap-anydpi-v26/ic_launcher_round.xml b/platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml similarity index 100% rename from res/android/mipmap-anydpi-v26/ic_launcher_round.xml rename to platforms/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml diff --git a/res/android/mipmap-hdpi/ic_acode_aurora_pulse.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_aurora_pulse.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_aurora_pulse.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_aurora_pulse.webp diff --git a/res/android/mipmap-hdpi/ic_acode_aurora_pulse_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_aurora_pulse_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_aurora_pulse_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_aurora_pulse_round.webp diff --git a/res/android/mipmap-hdpi/ic_acode_blueprint.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_blueprint.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_blueprint.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_blueprint.webp diff --git a/res/android/mipmap-hdpi/ic_acode_blueprint_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_blueprint_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_blueprint_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_blueprint_round.webp diff --git a/res/android/mipmap-hdpi/ic_acode_cobalt.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_cobalt.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_cobalt.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_cobalt.webp diff --git a/res/android/mipmap-hdpi/ic_acode_cobalt_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_cobalt_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_cobalt_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_cobalt_round.webp diff --git a/res/android/mipmap-hdpi/ic_acode_glacier.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_glacier.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_glacier.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_glacier.webp diff --git a/res/android/mipmap-hdpi/ic_acode_glacier_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_glacier_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_glacier_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_glacier_round.webp diff --git a/res/android/mipmap-hdpi/ic_acode_lilac.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_lilac.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_lilac.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_lilac.webp diff --git a/res/android/mipmap-hdpi/ic_acode_lilac_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_lilac_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_lilac_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_lilac_round.webp diff --git a/res/android/mipmap-hdpi/ic_acode_midnight_circuit.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_midnight_circuit.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_midnight_circuit.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_midnight_circuit.webp diff --git a/res/android/mipmap-hdpi/ic_acode_midnight_circuit_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_midnight_circuit_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_midnight_circuit_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_midnight_circuit_round.webp diff --git a/res/android/mipmap-hdpi/ic_acode_pixel_party.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_pixel_party.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_pixel_party.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_pixel_party.webp diff --git a/res/android/mipmap-hdpi/ic_acode_pixel_party_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_pixel_party_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_pixel_party_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_pixel_party_round.webp diff --git a/res/android/mipmap-hdpi/ic_acode_porcelain.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_porcelain.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_porcelain.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_porcelain.webp diff --git a/res/android/mipmap-hdpi/ic_acode_porcelain_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_porcelain_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_porcelain_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_porcelain_round.webp diff --git a/res/android/mipmap-hdpi/ic_acode_prism.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_prism.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_prism.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_prism.webp diff --git a/res/android/mipmap-hdpi/ic_acode_prism_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_prism_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_prism_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_prism_round.webp diff --git a/res/android/mipmap-hdpi/ic_acode_solar_flare.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_solar_flare.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_solar_flare.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_solar_flare.webp diff --git a/res/android/mipmap-hdpi/ic_acode_solar_flare_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_solar_flare_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_solar_flare_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_solar_flare_round.webp diff --git a/res/android/mipmap-hdpi/ic_acode_tangerine.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_tangerine.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_tangerine.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_tangerine.webp diff --git a/res/android/mipmap-hdpi/ic_acode_tangerine_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_tangerine_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_tangerine_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_tangerine_round.webp diff --git a/res/android/mipmap-hdpi/ic_acode_terminal_glow.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_terminal_glow.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_terminal_glow.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_terminal_glow.webp diff --git a/res/android/mipmap-hdpi/ic_acode_terminal_glow_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_terminal_glow_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_terminal_glow_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_terminal_glow_round.webp diff --git a/res/android/mipmap-hdpi/ic_acode_tidal.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_tidal.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_tidal.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_tidal.webp diff --git a/res/android/mipmap-hdpi/ic_acode_tidal_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_tidal_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_tidal_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_tidal_round.webp diff --git a/res/android/mipmap-hdpi/ic_acode_volt.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_volt.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_volt.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_volt.webp diff --git a/res/android/mipmap-hdpi/ic_acode_volt_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_volt_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_acode_volt_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_acode_volt_round.webp diff --git a/res/android/mipmap-hdpi/ic_launcher.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_launcher.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp diff --git a/res/android/mipmap-hdpi/ic_launcher_round.webp b/platforms/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp similarity index 100% rename from res/android/mipmap-hdpi/ic_launcher_round.webp rename to platforms/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp diff --git a/res/android/mipmap-mdpi/ic_acode_aurora_pulse.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_aurora_pulse.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_aurora_pulse.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_aurora_pulse.webp diff --git a/res/android/mipmap-mdpi/ic_acode_aurora_pulse_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_aurora_pulse_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_aurora_pulse_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_aurora_pulse_round.webp diff --git a/res/android/mipmap-mdpi/ic_acode_blueprint.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_blueprint.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_blueprint.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_blueprint.webp diff --git a/res/android/mipmap-mdpi/ic_acode_blueprint_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_blueprint_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_blueprint_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_blueprint_round.webp diff --git a/res/android/mipmap-mdpi/ic_acode_cobalt.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_cobalt.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_cobalt.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_cobalt.webp diff --git a/res/android/mipmap-mdpi/ic_acode_cobalt_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_cobalt_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_cobalt_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_cobalt_round.webp diff --git a/res/android/mipmap-mdpi/ic_acode_glacier.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_glacier.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_glacier.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_glacier.webp diff --git a/res/android/mipmap-mdpi/ic_acode_glacier_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_glacier_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_glacier_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_glacier_round.webp diff --git a/res/android/mipmap-mdpi/ic_acode_lilac.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_lilac.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_lilac.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_lilac.webp diff --git a/res/android/mipmap-mdpi/ic_acode_lilac_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_lilac_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_lilac_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_lilac_round.webp diff --git a/res/android/mipmap-mdpi/ic_acode_midnight_circuit.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_midnight_circuit.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_midnight_circuit.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_midnight_circuit.webp diff --git a/res/android/mipmap-mdpi/ic_acode_midnight_circuit_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_midnight_circuit_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_midnight_circuit_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_midnight_circuit_round.webp diff --git a/res/android/mipmap-mdpi/ic_acode_pixel_party.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_pixel_party.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_pixel_party.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_pixel_party.webp diff --git a/res/android/mipmap-mdpi/ic_acode_pixel_party_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_pixel_party_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_pixel_party_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_pixel_party_round.webp diff --git a/res/android/mipmap-mdpi/ic_acode_porcelain.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_porcelain.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_porcelain.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_porcelain.webp diff --git a/res/android/mipmap-mdpi/ic_acode_porcelain_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_porcelain_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_porcelain_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_porcelain_round.webp diff --git a/res/android/mipmap-mdpi/ic_acode_prism.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_prism.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_prism.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_prism.webp diff --git a/res/android/mipmap-mdpi/ic_acode_prism_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_prism_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_prism_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_prism_round.webp diff --git a/res/android/mipmap-mdpi/ic_acode_solar_flare.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_solar_flare.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_solar_flare.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_solar_flare.webp diff --git a/res/android/mipmap-mdpi/ic_acode_solar_flare_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_solar_flare_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_solar_flare_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_solar_flare_round.webp diff --git a/res/android/mipmap-mdpi/ic_acode_tangerine.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_tangerine.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_tangerine.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_tangerine.webp diff --git a/res/android/mipmap-mdpi/ic_acode_tangerine_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_tangerine_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_tangerine_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_tangerine_round.webp diff --git a/res/android/mipmap-mdpi/ic_acode_terminal_glow.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_terminal_glow.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_terminal_glow.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_terminal_glow.webp diff --git a/res/android/mipmap-mdpi/ic_acode_terminal_glow_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_terminal_glow_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_terminal_glow_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_terminal_glow_round.webp diff --git a/res/android/mipmap-mdpi/ic_acode_tidal.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_tidal.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_tidal.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_tidal.webp diff --git a/res/android/mipmap-mdpi/ic_acode_tidal_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_tidal_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_tidal_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_tidal_round.webp diff --git a/res/android/mipmap-mdpi/ic_acode_volt.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_volt.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_volt.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_volt.webp diff --git a/res/android/mipmap-mdpi/ic_acode_volt_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_volt_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_acode_volt_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_acode_volt_round.webp diff --git a/res/android/mipmap-mdpi/ic_launcher.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_launcher.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp diff --git a/res/android/mipmap-mdpi/ic_launcher_round.webp b/platforms/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp similarity index 100% rename from res/android/mipmap-mdpi/ic_launcher_round.webp rename to platforms/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_aurora_pulse.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_aurora_pulse.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_aurora_pulse.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_aurora_pulse.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_aurora_pulse_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_aurora_pulse_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_aurora_pulse_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_aurora_pulse_round.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_blueprint.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_blueprint.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_blueprint.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_blueprint.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_blueprint_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_blueprint_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_blueprint_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_blueprint_round.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_cobalt.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_cobalt.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_cobalt.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_cobalt.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_cobalt_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_cobalt_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_cobalt_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_cobalt_round.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_glacier.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_glacier.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_glacier.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_glacier.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_glacier_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_glacier_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_glacier_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_glacier_round.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_lilac.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_lilac.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_lilac.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_lilac.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_lilac_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_lilac_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_lilac_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_lilac_round.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_midnight_circuit.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_midnight_circuit.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_midnight_circuit.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_midnight_circuit.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_midnight_circuit_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_midnight_circuit_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_midnight_circuit_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_midnight_circuit_round.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_pixel_party.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_pixel_party.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_pixel_party.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_pixel_party.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_pixel_party_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_pixel_party_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_pixel_party_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_pixel_party_round.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_porcelain.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_porcelain.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_porcelain.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_porcelain.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_porcelain_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_porcelain_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_porcelain_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_porcelain_round.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_prism.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_prism.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_prism.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_prism.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_prism_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_prism_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_prism_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_prism_round.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_solar_flare.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_solar_flare.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_solar_flare.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_solar_flare.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_solar_flare_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_solar_flare_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_solar_flare_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_solar_flare_round.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_tangerine.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_tangerine.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_tangerine.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_tangerine.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_tangerine_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_tangerine_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_tangerine_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_tangerine_round.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_terminal_glow.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_terminal_glow.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_terminal_glow.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_terminal_glow.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_terminal_glow_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_terminal_glow_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_terminal_glow_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_terminal_glow_round.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_tidal.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_tidal.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_tidal.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_tidal.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_tidal_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_tidal_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_tidal_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_tidal_round.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_volt.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_volt.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_volt.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_volt.webp diff --git a/res/android/mipmap-xhdpi/ic_acode_volt_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_volt_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_acode_volt_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_acode_volt_round.webp diff --git a/res/android/mipmap-xhdpi/ic_launcher.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_launcher.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp diff --git a/res/android/mipmap-xhdpi/ic_launcher_round.webp b/platforms/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp similarity index 100% rename from res/android/mipmap-xhdpi/ic_launcher_round.webp rename to platforms/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_aurora_pulse.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_aurora_pulse.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_aurora_pulse.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_aurora_pulse.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_aurora_pulse_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_aurora_pulse_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_aurora_pulse_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_aurora_pulse_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_blueprint.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_blueprint.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_blueprint.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_blueprint.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_blueprint_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_blueprint_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_blueprint_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_blueprint_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_cobalt.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_cobalt.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_cobalt.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_cobalt.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_cobalt_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_cobalt_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_cobalt_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_cobalt_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_glacier.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_glacier.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_glacier.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_glacier.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_glacier_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_glacier_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_glacier_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_glacier_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_lilac.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_lilac.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_lilac.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_lilac.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_lilac_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_lilac_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_lilac_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_lilac_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_midnight_circuit.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_midnight_circuit.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_midnight_circuit.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_midnight_circuit.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_midnight_circuit_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_midnight_circuit_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_midnight_circuit_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_midnight_circuit_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_pixel_party.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_pixel_party.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_pixel_party.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_pixel_party.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_pixel_party_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_pixel_party_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_pixel_party_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_pixel_party_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_porcelain.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_porcelain.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_porcelain.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_porcelain.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_porcelain_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_porcelain_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_porcelain_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_porcelain_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_prism.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_prism.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_prism.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_prism.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_prism_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_prism_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_prism_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_prism_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_solar_flare.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_solar_flare.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_solar_flare.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_solar_flare.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_solar_flare_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_solar_flare_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_solar_flare_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_solar_flare_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_tangerine.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_tangerine.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_tangerine.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_tangerine.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_tangerine_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_tangerine_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_tangerine_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_tangerine_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_terminal_glow.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_terminal_glow.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_terminal_glow.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_terminal_glow.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_terminal_glow_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_terminal_glow_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_terminal_glow_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_terminal_glow_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_tidal.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_tidal.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_tidal.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_tidal.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_tidal_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_tidal_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_tidal_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_tidal_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_volt.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_volt.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_volt.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_volt.webp diff --git a/res/android/mipmap-xxhdpi/ic_acode_volt_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_volt_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_acode_volt_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_acode_volt_round.webp diff --git a/res/android/mipmap-xxhdpi/ic_launcher.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_launcher.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp diff --git a/res/android/mipmap-xxhdpi/ic_launcher_round.webp b/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp similarity index 100% rename from res/android/mipmap-xxhdpi/ic_launcher_round.webp rename to platforms/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_aurora_pulse.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_aurora_pulse.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_aurora_pulse.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_aurora_pulse.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_aurora_pulse_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_aurora_pulse_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_aurora_pulse_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_aurora_pulse_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_blueprint.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_blueprint.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_blueprint.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_blueprint.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_blueprint_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_blueprint_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_blueprint_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_blueprint_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_cobalt.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_cobalt.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_cobalt.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_cobalt.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_cobalt_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_cobalt_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_cobalt_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_cobalt_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_glacier.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_glacier.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_glacier.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_glacier.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_glacier_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_glacier_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_glacier_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_glacier_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_lilac.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_lilac.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_lilac.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_lilac.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_lilac_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_lilac_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_lilac_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_lilac_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_midnight_circuit.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_midnight_circuit.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_midnight_circuit.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_midnight_circuit.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_midnight_circuit_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_midnight_circuit_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_midnight_circuit_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_midnight_circuit_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_pixel_party.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_pixel_party.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_pixel_party.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_pixel_party.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_pixel_party_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_pixel_party_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_pixel_party_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_pixel_party_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_porcelain.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_porcelain.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_porcelain.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_porcelain.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_porcelain_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_porcelain_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_porcelain_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_porcelain_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_prism.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_prism.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_prism.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_prism.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_prism_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_prism_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_prism_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_prism_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_solar_flare.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_solar_flare.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_solar_flare.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_solar_flare.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_solar_flare_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_solar_flare_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_solar_flare_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_solar_flare_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_tangerine.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_tangerine.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_tangerine.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_tangerine.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_tangerine_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_tangerine_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_tangerine_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_tangerine_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_terminal_glow.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_terminal_glow.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_terminal_glow.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_terminal_glow.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_terminal_glow_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_terminal_glow_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_terminal_glow_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_terminal_glow_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_tidal.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_tidal.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_tidal.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_tidal.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_tidal_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_tidal_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_tidal_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_tidal_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_volt.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_volt.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_volt.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_volt.webp diff --git a/res/android/mipmap-xxxhdpi/ic_acode_volt_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_volt_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_acode_volt_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_acode_volt_round.webp diff --git a/res/android/mipmap-xxxhdpi/ic_launcher.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_launcher.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp diff --git a/res/android/mipmap-xxxhdpi/ic_launcher_round.webp b/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp similarity index 100% rename from res/android/mipmap-xxxhdpi/ic_launcher_round.webp rename to platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp diff --git a/res/android/values/colors.xml b/platforms/android/app/src/main/res/values/colors.xml similarity index 100% rename from res/android/values/colors.xml rename to platforms/android/app/src/main/res/values/colors.xml diff --git a/res/android/values/ic_launcher_background.xml b/platforms/android/app/src/main/res/values/ic_launcher_background.xml similarity index 100% rename from res/android/values/ic_launcher_background.xml rename to platforms/android/app/src/main/res/values/ic_launcher_background.xml diff --git a/platforms/android/app/src/main/res/values/strings.xml b/platforms/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000000..979916496b --- /dev/null +++ b/platforms/android/app/src/main/res/values/strings.xml @@ -0,0 +1 @@ +<resources><string name="app_name">Acode</string></resources> diff --git a/src/plugins/browser/res/android/styles.xml b/platforms/android/app/src/main/res/values/styles.xml similarity index 100% rename from src/plugins/browser/res/android/styles.xml rename to platforms/android/app/src/main/res/values/styles.xml diff --git a/platforms/android/app/src/main/res/values/themes.xml b/platforms/android/app/src/main/res/values/themes.xml new file mode 100644 index 0000000000..d054565fa6 --- /dev/null +++ b/platforms/android/app/src/main/res/values/themes.xml @@ -0,0 +1,15 @@ +<?xml version='1.0' encoding='utf-8'?> +<resources> + <style name="Theme.App.Activity" parent="Theme.AppCompat.DayNight.NoActionBar"> + <item name="colorAccent">@color/teardrop</item> + <item name="android:colorAccent">@color/teardrop</item> + <item name="colorControlActivated">@color/teardrop</item> + <item name="android:colorControlActivated">@color/teardrop</item> + <item name="android:windowOptOutEdgeToEdgeEnforcement">true</item> + </style> + <style name="Theme.App.SplashScreen" parent="Theme.SplashScreen"> + <item name="windowSplashScreenBackground">@color/ic_splash_background</item> + <item name="windowSplashScreenAnimatedIcon">@drawable/ic_launcher_foreground</item> + <item name="postSplashScreenTheme">@style/Theme.App.Activity</item> + </style> +</resources> diff --git a/src/plugins/system/res/android/file_provider.xml b/platforms/android/app/src/main/res/xml/file_provider.xml similarity index 100% rename from src/plugins/system/res/android/file_provider.xml rename to platforms/android/app/src/main/res/xml/file_provider.xml diff --git a/res/android/xml/network_security_config.xml b/platforms/android/app/src/main/res/xml/network_security_config.xml similarity index 100% rename from res/android/xml/network_security_config.xml rename to platforms/android/app/src/main/res/xml/network_security_config.xml diff --git a/platforms/android/app/src/paid/java/com/foxdebug/acode/runtime/EditionServices.kt b/platforms/android/app/src/paid/java/com/foxdebug/acode/runtime/EditionServices.kt new file mode 100644 index 0000000000..b8cd96e816 --- /dev/null +++ b/platforms/android/app/src/paid/java/com/foxdebug/acode/runtime/EditionServices.kt @@ -0,0 +1,5 @@ +package com.foxdebug.acode.runtime + +internal object EditionServices : ServiceModule { + override val services: List<ServiceDefinition> = emptyList() +} diff --git a/platforms/android/app/src/store/AndroidManifest.xml b/platforms/android/app/src/store/AndroidManifest.xml new file mode 100644 index 0000000000..8957cded0e --- /dev/null +++ b/platforms/android/app/src/store/AndroidManifest.xml @@ -0,0 +1,5 @@ +<manifest xmlns:tools="http://schemas.android.com/tools" + xmlns:android="http://schemas.android.com/apk/res/android"> + <uses-permission android:name="com.android.vending.BILLING" /> + <application tools:ignore="MissingApplicationIcon" /> +</manifest> diff --git a/src/plugins/proot/assets/alpine_assets/arm32/alpine.rootfs b/platforms/android/app/src/store/assets/alpine_assets/arm32/alpine.rootfs similarity index 100% rename from src/plugins/proot/assets/alpine_assets/arm32/alpine.rootfs rename to platforms/android/app/src/store/assets/alpine_assets/arm32/alpine.rootfs diff --git a/src/plugins/proot/assets/alpine_assets/arm64/alpine.rootfs b/platforms/android/app/src/store/assets/alpine_assets/arm64/alpine.rootfs similarity index 100% rename from src/plugins/proot/assets/alpine_assets/arm64/alpine.rootfs rename to platforms/android/app/src/store/assets/alpine_assets/arm64/alpine.rootfs diff --git a/src/plugins/proot/assets/alpine_assets/x64/alpine.rootfs b/platforms/android/app/src/store/assets/alpine_assets/x64/alpine.rootfs similarity index 100% rename from src/plugins/proot/assets/alpine_assets/x64/alpine.rootfs rename to platforms/android/app/src/store/assets/alpine_assets/x64/alpine.rootfs diff --git a/platforms/android/app/src/store/java/com/foxdebug/acode/runtime/ChannelServices.kt b/platforms/android/app/src/store/java/com/foxdebug/acode/runtime/ChannelServices.kt new file mode 100644 index 0000000000..b3f60bcf0f --- /dev/null +++ b/platforms/android/app/src/store/java/com/foxdebug/acode/runtime/ChannelServices.kt @@ -0,0 +1,9 @@ +package com.foxdebug.acode.runtime + +import com.foxdebug.iap.Iap + +internal object ChannelServices : ServiceModule { + override val services: List<ServiceDefinition> = listOf( + ServiceDefinition(ServiceName.IAP) { Iap() }, + ) +} diff --git a/src/plugins/iap/src/com/foxdebug/iap/Iap.java b/platforms/android/app/src/store/java/com/foxdebug/iap/Iap.java similarity index 90% rename from src/plugins/iap/src/com/foxdebug/iap/Iap.java rename to platforms/android/app/src/store/java/com/foxdebug/iap/Iap.java index 469443986f..1172a3b083 100644 --- a/src/plugins/iap/src/com/foxdebug/iap/Iap.java +++ b/platforms/android/app/src/store/java/com/foxdebug/iap/Iap.java @@ -2,7 +2,7 @@ import android.app.Activity; import android.content.Context; -import android.util.Log; + import com.android.billingclient.api.AcknowledgePurchaseParams; import com.android.billingclient.api.AcknowledgePurchaseResponseListener; import com.android.billingclient.api.BillingClient; @@ -25,26 +25,25 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaInterface; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.CordovaWebView; -import org.apache.cordova.PluginResult; +import com.foxdebug.acode.runtime.BridgeContext; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.Service; +import com.foxdebug.acode.runtime.Payload; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -public class Iap extends CordovaPlugin { +public class Iap extends Service { private BillingClient billingClient; private WeakReference<Context> contextRef; private WeakReference<Activity> activityRef; - private CallbackContext purchaseUpdated; + private Callback purchaseUpdated; - public void initialize(CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); - contextRef = new WeakReference<>(cordova.getContext()); - activityRef = new WeakReference<>(cordova.getActivity()); + public void initialize(BridgeContext bridgeContext) { + super.initialize(bridgeContext); + contextRef = new WeakReference<>(host.getContext()); + activityRef = new WeakReference<>(host.getActivity()); billingClient = getBillingClient(); } @@ -52,7 +51,7 @@ public void initialize(CordovaInterface cordova, CordovaWebView webView) { public boolean execute( String action, JSONArray args, - CallbackContext callbackContext + Callback callbackContext ) throws JSONException { String arg1 = getString(args, 0); switch (action) { @@ -68,7 +67,7 @@ public boolean execute( return false; } - cordova + host .getThreadPool() .execute( new Runnable() { @@ -122,16 +121,16 @@ public void onPurchasesUpdated( result.put(purchaseToJson(purchase)); } sendPurchasePluginResult( - new PluginResult(PluginResult.Status.OK, result) + new Payload(Payload.Status.OK, result) ); } else { sendPurchasePluginResult( - new PluginResult(PluginResult.Status.ERROR, responseCode) + new Payload(Payload.Status.ERROR, responseCode) ); } } catch (JSONException e) { sendPurchasePluginResult( - new PluginResult(PluginResult.Status.ERROR, e.getMessage()) + new Payload(Payload.Status.ERROR, e.getMessage()) ); } } @@ -140,11 +139,11 @@ public void onPurchasesUpdated( .build(); } - private void setPurchaseUpdatedListener(CallbackContext callbackContext) { + private void setPurchaseUpdatedListener(Callback callbackContext) { purchaseUpdated = callbackContext; } - private void consume(String token, CallbackContext callbackContext) { + private void consume(String token, Callback callbackContext) { ConsumeParams consumeParams = ConsumeParams.newBuilder() .setPurchaseToken(token) .build(); @@ -166,7 +165,7 @@ public void onConsumeResponse( ); } - private void startConnection(CallbackContext callbackContext) { + private void startConnection(Callback callbackContext) { try { if (billingClient == null) { billingClient = getBillingClient(); @@ -194,7 +193,7 @@ public void onBillingServiceDisconnected() { private void getProducts( List<String> idList, - CallbackContext callbackContext + Callback callbackContext ) { if (billingClient == null) { billingClient = getBillingClient(); @@ -258,7 +257,7 @@ public void onProductDetailsResponse( ); } - private void purchase(String productIdOrJson, CallbackContext callbackContext) { + private void purchase(String productIdOrJson, Callback callbackContext) { try { if (productIdOrJson == null || productIdOrJson.trim().isEmpty()) { callbackContext.error("Product ID cannot be null or empty"); @@ -319,7 +318,7 @@ public void onProductDetailsResponse( } } - private void getPurchases(CallbackContext callbackContext) { + private void getPurchases(Callback callbackContext) { if (billingClient == null) { billingClient = getBillingClient(); callbackContext.error("Billing client is not connected"); @@ -357,7 +356,7 @@ public void onQueryPurchasesResponse( private void acknowledgePurchase( String purchaseToken, - CallbackContext callbackContext + Callback callbackContext ) { if (billingClient == null) { billingClient = getBillingClient(); @@ -402,10 +401,10 @@ private JSONObject purchaseToJson(Purchase purchase) throws JSONException { return item; } - private void sendPurchasePluginResult(PluginResult result) { + private void sendPurchasePluginResult(Payload result) { if (purchaseUpdated != null) { result.setKeepCallback(true); - purchaseUpdated.sendPluginResult(result); + purchaseUpdated.sendPayload(result); } } diff --git a/src/plugins/proot/libs/arm64/libaxs.so b/platforms/android/app/src/store/jniLibs/arm64-v8a/libaxs.so similarity index 100% rename from src/plugins/proot/libs/arm64/libaxs.so rename to platforms/android/app/src/store/jniLibs/arm64-v8a/libaxs.so diff --git a/src/plugins/proot/libs/arm64/libproot-xed.so b/platforms/android/app/src/store/jniLibs/arm64-v8a/libproot-xed.so similarity index 100% rename from src/plugins/proot/libs/arm64/libproot-xed.so rename to platforms/android/app/src/store/jniLibs/arm64-v8a/libproot-xed.so diff --git a/src/plugins/proot/libs/arm64/libproot.so b/platforms/android/app/src/store/jniLibs/arm64-v8a/libproot.so similarity index 100% rename from src/plugins/proot/libs/arm64/libproot.so rename to platforms/android/app/src/store/jniLibs/arm64-v8a/libproot.so diff --git a/src/plugins/proot/libs/arm64/libproot32.so b/platforms/android/app/src/store/jniLibs/arm64-v8a/libproot32.so similarity index 100% rename from src/plugins/proot/libs/arm64/libproot32.so rename to platforms/android/app/src/store/jniLibs/arm64-v8a/libproot32.so diff --git a/src/plugins/proot/libs/arm64/libtalloc.so b/platforms/android/app/src/store/jniLibs/arm64-v8a/libtalloc.so similarity index 100% rename from src/plugins/proot/libs/arm64/libtalloc.so rename to platforms/android/app/src/store/jniLibs/arm64-v8a/libtalloc.so diff --git a/src/plugins/proot/libs/arm32/libaxs.so b/platforms/android/app/src/store/jniLibs/armeabi-v7a/libaxs.so similarity index 100% rename from src/plugins/proot/libs/arm32/libaxs.so rename to platforms/android/app/src/store/jniLibs/armeabi-v7a/libaxs.so diff --git a/src/plugins/proot/libs/arm32/libproot-xed.so b/platforms/android/app/src/store/jniLibs/armeabi-v7a/libproot-xed.so similarity index 100% rename from src/plugins/proot/libs/arm32/libproot-xed.so rename to platforms/android/app/src/store/jniLibs/armeabi-v7a/libproot-xed.so diff --git a/src/plugins/proot/libs/arm32/libproot.so b/platforms/android/app/src/store/jniLibs/armeabi-v7a/libproot.so similarity index 100% rename from src/plugins/proot/libs/arm32/libproot.so rename to platforms/android/app/src/store/jniLibs/armeabi-v7a/libproot.so diff --git a/src/plugins/proot/libs/arm32/libtalloc.so b/platforms/android/app/src/store/jniLibs/armeabi-v7a/libtalloc.so similarity index 100% rename from src/plugins/proot/libs/arm32/libtalloc.so rename to platforms/android/app/src/store/jniLibs/armeabi-v7a/libtalloc.so diff --git a/src/plugins/proot/libs/x64/libaxs.so b/platforms/android/app/src/store/jniLibs/x86_64/libaxs.so similarity index 100% rename from src/plugins/proot/libs/x64/libaxs.so rename to platforms/android/app/src/store/jniLibs/x86_64/libaxs.so diff --git a/src/plugins/proot/libs/x64/libproot-xed.so b/platforms/android/app/src/store/jniLibs/x86_64/libproot-xed.so similarity index 100% rename from src/plugins/proot/libs/x64/libproot-xed.so rename to platforms/android/app/src/store/jniLibs/x86_64/libproot-xed.so diff --git a/src/plugins/proot/libs/x64/libproot.so b/platforms/android/app/src/store/jniLibs/x86_64/libproot.so similarity index 100% rename from src/plugins/proot/libs/x64/libproot.so rename to platforms/android/app/src/store/jniLibs/x86_64/libproot.so diff --git a/src/plugins/proot/libs/x64/libproot32.so b/platforms/android/app/src/store/jniLibs/x86_64/libproot32.so similarity index 100% rename from src/plugins/proot/libs/x64/libproot32.so rename to platforms/android/app/src/store/jniLibs/x86_64/libproot32.so diff --git a/src/plugins/proot/libs/x64/libtalloc.so b/platforms/android/app/src/store/jniLibs/x86_64/libtalloc.so similarity index 100% rename from src/plugins/proot/libs/x64/libtalloc.so rename to platforms/android/app/src/store/jniLibs/x86_64/libtalloc.so diff --git a/platforms/android/app/src/test/java/com/foxdebug/acode/runtime/FileResourceTest.java b/platforms/android/app/src/test/java/com/foxdebug/acode/runtime/FileResourceTest.java new file mode 100644 index 0000000000..99ebd7d37f --- /dev/null +++ b/platforms/android/app/src/test/java/com/foxdebug/acode/runtime/FileResourceTest.java @@ -0,0 +1,83 @@ +package com.foxdebug.acode.runtime; + +import static org.junit.Assert.*; + +import android.net.Uri; +import android.webkit.WebResourceRequest; +import android.webkit.WebResourceResponse; +import com.foxdebug.acode.MainActivity; +import com.foxdebug.acode.runtime.webview.AppWebView; +import java.io.File; +import java.io.InputStream; +import java.nio.file.Files; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +@RunWith(RobolectricTestRunner.class) +@Config(sdk = 29) +public class FileResourceTest { + + @Test + public void servesEncodedFileNamesWithoutReinterpretingTheirCharacters() + throws Exception { + Thread.UncaughtExceptionHandler previous = + Thread.getDefaultUncaughtExceptionHandler(); + try ( + org.robolectric.android.controller.ActivityController< + MainActivity + > controller = Robolectric.buildActivity(MainActivity.class).setup() + ) { + MainActivity activity = controller.get(); + AppWebView view = (AppWebView) activity.getContentView().getChildAt(0); + android.webkit.WebViewClient client = view.getWebViewClient(); + byte[] bytes = {0, 127, (byte) 128, (byte) 255}; + for (String name : new String[] { + "plain.txt", + "hash # question ? 50% 日本語.txt", + "literal %23.txt", + }) { + File file = new File(activity.getCacheDir(), name); + Files.write(file.toPath(), bytes); + try { + Uri uri = Uri.parse("https://localhost/__cdvfile_cache__/") + .buildUpon() + .appendPath(name) + .build(); + WebResourceResponse response = activity + .getHost() + .getThreadPool() + .submit(() -> client.shouldInterceptRequest(view, request(uri))) + .get(5, TimeUnit.SECONDS); + assertNotNull(name, response); + assertNotEquals(name, 404, response.getStatusCode()); + try (InputStream stream = response.getData()) { + assertArrayEquals(name, bytes, stream.readAllBytes()); + } + } finally { + Files.deleteIfExists(file.toPath()); + } + } + } finally { + Thread.setDefaultUncaughtExceptionHandler(previous); + } + } + + private static WebResourceRequest request(Uri uri) { + return new WebResourceRequest() { + public Uri getUrl() { return uri; } + public boolean isForMainFrame() { return false; } + public boolean isRedirect() { return false; } + public boolean hasGesture() { return false; } + public String getMethod() { return "GET"; } + public Map<String, String> getRequestHeaders() { + return Collections.emptyMap(); + } + }; + } +} diff --git a/platforms/android/app/src/test/java/com/foxdebug/acode/runtime/PayloadTest.java b/platforms/android/app/src/test/java/com/foxdebug/acode/runtime/PayloadTest.java new file mode 100644 index 0000000000..b798feb11f --- /dev/null +++ b/platforms/android/app/src/test/java/com/foxdebug/acode/runtime/PayloadTest.java @@ -0,0 +1,63 @@ +package com.foxdebug.acode.runtime; + +import static org.junit.Assert.*; + +import org.json.JSONObject; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +@RunWith(RobolectricTestRunner.class) +@Config(sdk = 29, manifest = Config.NONE) +public class PayloadTest { + + @Test + public void preservesDefaultStatusMessagesAndExplicitNull() throws Exception { + assertEquals("OK", new Payload(Payload.Status.OK).toJSON(1, 0).get("data")); + assertEquals( + "Invalid action", + new Payload(Payload.Status.INVALID_ACTION).toJSON(1, 0).get("data") + ); + assertTrue( + new Payload(Payload.Status.OK, null).toJSON(1, 0).isNull("data") + ); + } + + @Test + public void preservesEmptyErrorsAndCallbackRetention() throws Exception { + Payload payload = new Payload(Payload.Status.ERROR, ""); + payload.setKeepCallback(true); + JSONObject result = payload.toJSON(7, 3); + assertEquals(9, result.getInt("status")); + assertEquals("", result.getString("data")); + assertTrue(result.getBoolean("keep")); + assertEquals(3, result.getLong("generation")); + } + + @Test + public void encodesBinaryWithoutLosingZeroOrHighBytes() throws Exception { + Payload payload = new Payload(Payload.Status.OK, new byte[] { + 0, + (byte) 255, + }); + JSONObject data = payload.toJSON(1, 0).getJSONObject("data"); + assertEquals("arrayBuffer", data.getString("kind")); + assertEquals("AP8=", data.getString("data")); + } + + @Test + public void preservesMultipartArgumentOrder() throws Exception { + Payload payload = new Payload( + Payload.Status.OK, + java.util.Arrays.asList( + new Payload(Payload.Status.OK, "data"), + new Payload(Payload.Status.OK, 42) + ) + ); + JSONObject result = payload.toJSON(1, 0).getJSONObject("data"); + assertEquals("multipart", result.getString("kind")); + assertEquals("data", result.getJSONArray("data").getString(0)); + assertEquals(42, result.getJSONArray("data").getInt(1)); + } +} diff --git a/platforms/android/app/src/test/java/com/foxdebug/acode/runtime/StartupTest.java b/platforms/android/app/src/test/java/com/foxdebug/acode/runtime/StartupTest.java new file mode 100644 index 0000000000..ed08c4f495 --- /dev/null +++ b/platforms/android/app/src/test/java/com/foxdebug/acode/runtime/StartupTest.java @@ -0,0 +1,213 @@ +package com.foxdebug.acode.runtime; + +import static org.junit.Assert.*; + +import android.os.Looper; +import com.foxdebug.acode.BuildConfig; +import com.foxdebug.acode.runtime.webview.AppWebView; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.Shadows; +import org.robolectric.annotation.Config; + +@RunWith(RobolectricTestRunner.class) +@Config(sdk = 29) +public class StartupTest { + + @Test + public void startsAndResumesWithoutReloadingTheEditor() throws Exception { + Thread.UncaughtExceptionHandler previous = + Thread.getDefaultUncaughtExceptionHandler(); + try ( + org.robolectric.android.controller.ActivityController< + BaseWebActivity + > controller = Robolectric.buildActivity(activityClass()) + ) { + BaseWebActivity activity = controller.create().start().resume().get(); + AppWebView view = (AppWebView) activity + .getContentView() + .getChildAt(0); + assertEquals("https://localhost/index.html", view.getUrl()); + android.content.pm.ActivityInfo info = activity + .getPackageManager() + .getActivityInfo(activity.getComponentName(), 0); + assertEquals(activityClass().getName(), info.name); + assertNotNull(view.getBridge().getService(ServiceName.FILE)); + assertNotNull(view.getBridge().getService(ServiceName.AUTHENTICATOR)); + assertNotNull(view.getBridge().getService(ServiceName.SYSTEM)); + if (BuildConfig.FLAVOR_edition.equals("free")) assertNotNull( + view.getBridge().getService(ServiceName.AD_MOB) + ); + else assertNull(view.getBridge().getService(ServiceName.AD_MOB)); + long generation = view.getBridge().getGeneration(); + controller.pause().resume(); + assertEquals(generation, view.getBridge().getGeneration()); + } finally { + Thread.setDefaultUncaughtExceptionHandler(previous); + } + } + + @Test + public void exposesEveryTransportKeyOnce() { + java.util.HashSet<String> keys = new java.util.HashSet<>(); + for (ServiceName name : ServiceName.values()) { + assertTrue("duplicate key " + name.getKey(), keys.add(name.getKey())); + } + } + + @Test + public void routesOverlappingActivityRequestsToTheirOwners() + throws Exception { + Thread.UncaughtExceptionHandler previous = + Thread.getDefaultUncaughtExceptionHandler(); + try ( + org.robolectric.android.controller.ActivityController< + BaseWebActivity + > controller = Robolectric.buildActivity(activityClass()).setup() + ) { + BaseWebActivity activity = controller.get(); + int[] received = new int[2]; + Service first = new Service() { + @Override + public void onActivityResult( + int code, + int result, + android.content.Intent data + ) { + received[0] = code + result; + } + }; + Service second = new Service() { + @Override + public void onActivityResult( + int code, + int result, + android.content.Intent data + ) { + received[1] = code + result; + } + }; + org.robolectric.shadows.ShadowActivity shadow = Shadows.shadowOf( + activity + ); + activity + .getHost() + .startActivityForResult( + first, + new android.content.Intent(android.content.Intent.ACTION_GET_CONTENT), + 7 + ); + int firstId = shadow.getNextStartedActivityForResult().requestCode; + activity + .getHost() + .startActivityForResult( + second, + new android.content.Intent(android.content.Intent.ACTION_GET_CONTENT), + 7 + ); + int secondId = shadow.getNextStartedActivityForResult().requestCode; + assertNotEquals(firstId, secondId); + activity.getHost().onActivityResult(secondId, 20, null); + activity.getHost().onActivityResult(firstId, 10, null); + assertArrayEquals(new int[] {17, 27}, received); + } finally { + Thread.setDefaultUncaughtExceptionHandler(previous); + } + } + + @Test + public void discardsCallbacksFromPreviousPageGenerations() throws Exception { + Thread.UncaughtExceptionHandler previous = + Thread.getDefaultUncaughtExceptionHandler(); + try ( + org.robolectric.android.controller.ActivityController< + BaseWebActivity + > controller = Robolectric.buildActivity(activityClass()).setup() + ) { + AppWebView view = (AppWebView) controller + .get() + .getContentView() + .getChildAt(0); + Callback old = new Callback(42, view); + view.getBridge().reset(); + String before = Shadows.shadowOf(view).getLastEvaluatedJavascript(); + old.success("stale"); + Shadows.shadowOf(Looper.getMainLooper()).idle(); + assertEquals(before, Shadows.shadowOf(view).getLastEvaluatedJavascript()); + new Callback(42, view).success("current"); + Shadows.shadowOf(Looper.getMainLooper()).idle(); + assertTrue( + Shadows.shadowOf(view).getLastEvaluatedJavascript().contains("current") + ); + } finally { + Thread.setDefaultUncaughtExceptionHandler(previous); + } + } + + @Test + public void hardwareBackReachesFullscreenOwnerBeforeWebView() + throws Exception { + Thread.UncaughtExceptionHandler previous = + Thread.getDefaultUncaughtExceptionHandler(); + try ( + org.robolectric.android.controller.ActivityController< + BaseWebActivity + > controller = Robolectric.buildActivity(activityClass()).setup() + ) { + BaseWebActivity activity = controller.get(); + AppWebView view = (AppWebView) activity + .getContentView() + .getChildAt(0); + com.foxdebug.acode.runtime.webview.AcodeChromeClient chrome = + (com.foxdebug.acode.runtime.webview.AcodeChromeClient) view.getWebChromeClient(); + int[] hidden = {0}; + chrome.onShowCustomView( + new android.view.View(activity), + () -> hidden[0]++ + ); + chrome.setBackHandler(true); + assertTrue( + activity.dispatchKeyEvent( + new android.view.KeyEvent( + android.view.KeyEvent.ACTION_DOWN, + android.view.KeyEvent.KEYCODE_BACK + ) + ) + ); + assertTrue( + activity.dispatchKeyEvent( + new android.view.KeyEvent( + android.view.KeyEvent.ACTION_UP, + android.view.KeyEvent.KEYCODE_BACK + ) + ) + ); + assertTrue(chrome.isFullscreen()); + assertEquals(0, hidden[0]); + assertTrue( + Shadows.shadowOf(view) + .getLastEvaluatedJavascript() + .contains("fullscreenbackbutton") + ); + chrome.setBackHandler(false); + activity.dispatchKeyEvent( + new android.view.KeyEvent( + android.view.KeyEvent.ACTION_UP, + android.view.KeyEvent.KEYCODE_BACK + ) + ); + assertFalse(chrome.isFullscreen()); + assertEquals(1, hidden[0]); + } finally { + Thread.setDefaultUncaughtExceptionHandler(previous); + } + } + + @SuppressWarnings("unchecked") + private static Class<BaseWebActivity> activityClass() { + return (Class<BaseWebActivity>) (Class<?>) com.foxdebug.acode.MainActivity.class; + } +} diff --git a/platforms/android/app/src/test/java/com/foxdebug/acode/system/RewardPassManagerTest.kt b/platforms/android/app/src/test/java/com/foxdebug/acode/system/RewardPassManagerTest.kt new file mode 100644 index 0000000000..963b77c1b1 --- /dev/null +++ b/platforms/android/app/src/test/java/com/foxdebug/acode/system/RewardPassManagerTest.kt @@ -0,0 +1,60 @@ +package com.foxdebug.acode.system + +import com.foxdebug.acode.auth.EncryptedPreferenceManager +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE, sdk = [28]) +class RewardPassManagerTest { + @Test + fun unchangedStatusPreservesJsonFormattingAndKeyOrder() { + val context = RuntimeEnvironment.getApplication() + val store = EncryptedPreferenceManager(context, "ads") + val today = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US).format(java.util.Date()) + val raw = """{ "redemptionsToday": 2, "redemptionDay": "$today", + "expiryNoticePendingUntil": 0, "lastExpiredRewardUntil": 0, "adFreeUntil": 0 }""" + try { + store.setString("reward_state", raw) + RewardPassManager(context).getRewardStatus() + assertEquals(raw, store.getString("reward_state", "")) + assertFalse(RewardPassStorage.isUnchanged("invalid", JSONObject())) + assertFalse(RewardPassStorage.isUnchanged("{}", JSONObject().put("adFreeUntil", 0L))) + } finally { + store.clear() + } + } + + @Test + fun existingTimeSurvivesAndExpiryIsReportedOnceWithoutNewRedemptions() { + val context = RuntimeEnvironment.getApplication() + val store = EncryptedPreferenceManager(context, "ads") + try { + val expiry = java.lang.System.currentTimeMillis() + 3_600_000 + store.setString("reward_state", JSONObject().put("adFreeUntil", expiry).toString()) + val active = JSONObject(RewardPassManager(context).getRewardStatus()) + assertTrue(active.getBoolean("isActive")) + assertFalse(active.getBoolean("canRedeem")) + assertEquals(expiry, active.getLong("adFreeUntil")) + + val pastExpiry = java.lang.System.currentTimeMillis() - 1 + store.setString("reward_state", JSONObject().put("adFreeUntil", pastExpiry).toString()) + val rewards = RewardPassManager(context) + val expired = JSONObject(rewards.getRewardStatus()) + assertFalse(expired.getBoolean("isActive")) + assertFalse(expired.getBoolean("canRedeem")) + assertTrue(expired.getBoolean("hasPendingExpiryNotice")) + assertEquals(pastExpiry, expired.getLong("expiryNoticePendingUntil")) + assertFalse(JSONObject(rewards.getRewardStatus()).getBoolean("hasPendingExpiryNotice")) + } finally { + store.clear() + } + } +} diff --git a/platforms/android/app/src/test/java/com/foxdebug/acode/websocket/WebSocketInstanceTest.java b/platforms/android/app/src/test/java/com/foxdebug/acode/websocket/WebSocketInstanceTest.java new file mode 100644 index 0000000000..f598d99c40 --- /dev/null +++ b/platforms/android/app/src/test/java/com/foxdebug/acode/websocket/WebSocketInstanceTest.java @@ -0,0 +1,65 @@ +package com.foxdebug.acode.websocket; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.WebSocket; +import okio.ByteString; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; +import com.foxdebug.acode.runtime.Callback; +import com.foxdebug.acode.runtime.BaseWebActivity; +import com.foxdebug.acode.runtime.Payload; +import com.foxdebug.acode.runtime.webview.AppWebView; + +@RunWith(RobolectricTestRunner.class) +@Config(sdk = 29) +public class WebSocketInstanceTest { + @Test + @SuppressWarnings("unchecked") + public void deliversEarlyOpenMessageAndCloseInOrder() throws Exception { + Thread.UncaughtExceptionHandler previous = Thread.getDefaultUncaughtExceptionHandler(); + Class<BaseWebActivity> activityClass = (Class<BaseWebActivity>) (Class<?>) com.foxdebug.acode.MainActivity.class; + try (org.robolectric.android.controller.ActivityController<BaseWebActivity> controller = Robolectric.buildActivity(activityClass).setup()) { + BaseWebActivity activity = controller.get(); + AppWebView view = (AppWebView) activity.getContentView().getChildAt(0); + Request[] requests = new Request[1]; + WebSocket.Factory factory = (request, listener) -> { requests[0] = request; return null; }; + WebSocketInstance socket = new WebSocketInstance("ws://localhost/test", new JSONArray().put("test"), new JSONObject().put("Authorization", "token"), "arraybuffer", factory, activity.getHost(), "early"); + assertEquals("token", requests[0].header("Authorization")); + assertEquals("test", requests[0].header("Sec-WebSocket-Protocol")); + socket.onOpen(null, new Response.Builder().request(requests[0]).protocol(Protocol.HTTP_1_1).code(101).message("Switching Protocols").build()); + socket.onMessage(null, ByteString.of((byte) 0, (byte) 255)); + socket.onClosed(null, 1000, "done"); + + List<JSONObject> events = new ArrayList<>(); + List<Boolean> retained = new ArrayList<>(); + socket.setCallback(new Callback(1, view) { + @Override public synchronized void sendPayload(Payload payload) { + if (payload.getStatus() == Payload.Status.NO_RESULT.ordinal()) return; + retained.add(payload.getKeepCallback()); + try { events.add(payload.toJSON(1, 0).getJSONObject("data")); } + catch (Exception error) { throw new AssertionError(error); } + } + }); + assertEquals(3, events.size()); + assertEquals(java.util.Arrays.asList(true, true, false), retained); + assertEquals("open", events.get(0).getString("type")); + assertEquals("AP8=", events.get(1).getString("data")); + assertTrue(events.get(1).getBoolean("isBinary")); + assertEquals("close", events.get(2).getString("type")); + assertEquals(1000, new JSONObject(events.get(2).getString("data")).getInt("code")); + } finally { + Thread.setDefaultUncaughtExceptionHandler(previous); + } + } +} diff --git a/src/plugins/admob/src/androidTest/AdDispatchTest.kt b/platforms/android/app/src/testFree/java/app/acode/ads/AdDispatchTest.kt similarity index 96% rename from src/plugins/admob/src/androidTest/AdDispatchTest.kt rename to platforms/android/app/src/testFree/java/app/acode/ads/AdDispatchTest.kt index bfd64338ba..5c166a5607 100644 --- a/src/plugins/admob/src/androidTest/AdDispatchTest.kt +++ b/platforms/android/app/src/testFree/java/app/acode/ads/AdDispatchTest.kt @@ -1,4 +1,4 @@ -package admob.plus.cordova +package app.acode.ads import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue diff --git a/platforms/android/app/src/testFree/java/app/acode/ads/AdRecoveryTest.kt b/platforms/android/app/src/testFree/java/app/acode/ads/AdRecoveryTest.kt new file mode 100644 index 0000000000..23205427a3 --- /dev/null +++ b/platforms/android/app/src/testFree/java/app/acode/ads/AdRecoveryTest.kt @@ -0,0 +1,38 @@ +package app.acode.ads + +import androidx.activity.ComponentActivity +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE, sdk = [28]) +class AdRecoveryTest { + @Test + fun missingAdIsRecoverableOnlyWhenTheHostHasResumedAndRegainedFocus() { + val controller = Robolectric.buildActivity(RecoveryActivity::class.java).setup() + val activity = controller.get() + try { + assertFalse(recoverAdPresentation(activity, "removed-ad")) + activity.focused = true + assertTrue(recoverAdPresentation(activity, "removed-ad")) + controller.pause() + assertFalse(recoverAdPresentation(activity, "removed-ad")) + controller.resume() + assertTrue(recoverAdPresentation(activity, "removed-ad")) + activity.finish() + assertFalse(recoverAdPresentation(activity, "removed-ad")) + } finally { + controller.pause().stop().destroy() + } + } + + class RecoveryActivity : ComponentActivity() { + var focused = false + override fun hasWindowFocus(): Boolean = focused + } +} diff --git a/src/plugins/admob/src/androidTest/PrivacyStateTest.kt b/platforms/android/app/src/testFree/java/app/acode/ads/PrivacyStateTest.kt similarity index 98% rename from src/plugins/admob/src/androidTest/PrivacyStateTest.kt rename to platforms/android/app/src/testFree/java/app/acode/ads/PrivacyStateTest.kt index 7989a15f00..27ed8eedf9 100644 --- a/src/plugins/admob/src/androidTest/PrivacyStateTest.kt +++ b/platforms/android/app/src/testFree/java/app/acode/ads/PrivacyStateTest.kt @@ -1,4 +1,4 @@ -package admob.plus.cordova +package app.acode.ads import com.google.android.ump.ConsentInformation import org.junit.Assert.assertEquals diff --git a/src/plugins/admob/src/androidTest/BannerLayoutTest.kt b/platforms/android/app/src/testFree/java/app/acode/ads/ads/BannerLayoutTest.kt similarity index 99% rename from src/plugins/admob/src/androidTest/BannerLayoutTest.kt rename to platforms/android/app/src/testFree/java/app/acode/ads/ads/BannerLayoutTest.kt index ff4ace6dbd..fb5edb8c9b 100644 --- a/src/plugins/admob/src/androidTest/BannerLayoutTest.kt +++ b/platforms/android/app/src/testFree/java/app/acode/ads/ads/BannerLayoutTest.kt @@ -1,4 +1,4 @@ -package admob.plus.cordova.ads +package app.acode.ads.ads import admob.plus.core.pxToDp import org.junit.Assert.assertEquals diff --git a/platforms/android/build.gradle.kts b/platforms/android/build.gradle.kts new file mode 100644 index 0000000000..d052920bdc --- /dev/null +++ b/platforms/android/build.gradle.kts @@ -0,0 +1,4 @@ +//Project level build file do not add deps here +plugins { + alias(libs.plugins.android.application) apply false +} diff --git a/platforms/android/gradle.properties b/platforms/android/gradle.properties new file mode 100644 index 0000000000..abe3507da9 --- /dev/null +++ b/platforms/android/gradle.properties @@ -0,0 +1,9 @@ +# More than 2gb is a waste +org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 +android.useAndroidX=true +android.nonTransitiveRClass=true + +#using all cpu cores may freeze old computer when building +org.gradle.parallel=true +# Enabled parallel sync for Gradle 9.4+ +org.gradle.tooling.parallel=true diff --git a/platforms/android/gradle/gradle-daemon-jvm.properties b/platforms/android/gradle/gradle-daemon-jvm.properties new file mode 100644 index 0000000000..a7a6ee282f --- /dev/null +++ b/platforms/android/gradle/gradle-daemon-jvm.properties @@ -0,0 +1,2 @@ +#This file is generated by :updateDaemonJvm +toolchainVersion=26 diff --git a/platforms/android/gradle/libs.versions.toml b/platforms/android/gradle/libs.versions.toml new file mode 100644 index 0000000000..608f310c94 --- /dev/null +++ b/platforms/android/gradle/libs.versions.toml @@ -0,0 +1,54 @@ +[versions] +agp = "9.4.1" + + +#needs more attention +billing = "8.0.0" +playServicesAds = "25.4.0" + +appcompat = "1.8.0" +bouncycastle = "1.86" +browser = "1.10.0" +commonsCodec = "1.22.1" +commonsIo = "2.22.0" +commonsNet = "3.13.0" +core = "1.19.1" +coreGoogleShortcuts = "1.1.0" +coreSplashscreen = "1.2.0" +documentfile = "1.1.0" +javaWebsocket = "1.6.0" +junit = "4.13.2" +maverick = "3.1.4" +nanohttpd = "2.3.1" +okhttp = "5.5.0" +robolectric = "4.17" +securityCrypto = "1.1.0" +userMessagingPlatform = "4.0.0" +webkit = "1.17.1" + +[libraries] +androidx-appcompat = { module = "androidx.appcompat:appcompat", version.ref = "appcompat" } +androidx-browser = { module = "androidx.browser:browser", version.ref = "browser" } +androidx-core = { module = "androidx.core:core", version.ref = "core" } +androidx-core-google-shortcuts = { module = "androidx.core:core-google-shortcuts", version.ref = "coreGoogleShortcuts" } +androidx-core-splashscreen = { module = "androidx.core:core-splashscreen", version.ref = "coreSplashscreen" } +androidx-documentfile = { module = "androidx.documentfile:documentfile", version.ref = "documentfile" } +androidx-security-crypto = { module = "androidx.security:security-crypto", version.ref = "securityCrypto" } +androidx-webkit = { module = "androidx.webkit:webkit", version.ref = "webkit" } +billing-client = { module = "com.android.billingclient:billing", version.ref = "billing" } +bouncycastle-bcpkix = { module = "org.bouncycastle:bcpkix-jdk15to18", version.ref = "bouncycastle" } +bouncycastle-bcprov = { module = "org.bouncycastle:bcprov-jdk15to18", version.ref = "bouncycastle" } +commons-codec = { module = "commons-codec:commons-codec", version.ref = "commonsCodec" } +commons-io = { module = "commons-io:commons-io", version.ref = "commonsIo" } +commons-net = { module = "commons-net:commons-net", version.ref = "commonsNet" } +java-websocket = { module = "org.java-websocket:Java-WebSocket", version.ref = "javaWebsocket" } +junit = { module = "junit:junit", version.ref = "junit" } +maverick-synergy-client = { module = "com.sshtools:maverick-synergy-client", version.ref = "maverick" } +nanohttpd = { module = "org.nanohttpd:nanohttpd", version.ref = "nanohttpd" } +okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } +play-services-ads = { module = "com.google.android.gms:play-services-ads", version.ref = "playServicesAds" } +robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectric" } +user-messaging-platform = { module = "com.google.android.ump:user-messaging-platform", version.ref = "userMessagingPlatform" } + +[plugins] +android-application = { id = "com.android.application", version.ref = "agp" } diff --git a/platforms/android/gradle/wrapper/gradle-wrapper.jar b/platforms/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..5097068a8d Binary files /dev/null and b/platforms/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/platforms/android/gradle/wrapper/gradle-wrapper.properties b/platforms/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..16d33ddf98 --- /dev/null +++ b/platforms/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,10 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=a068e9c506ea61501c689900aec9010eda810b112e682146b1ae4291df3dab6a +distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.0-rc-3-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/platforms/android/gradlew b/platforms/android/gradlew new file mode 100755 index 0000000000..249efbb032 --- /dev/null +++ b/platforms/android/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/platforms/android/gradlew.bat b/platforms/android/gradlew.bat new file mode 100644 index 0000000000..03754c4c3d --- /dev/null +++ b/platforms/android/gradlew.bat @@ -0,0 +1,112 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel + +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/platforms/android/settings.gradle.kts b/platforms/android/settings.gradle.kts new file mode 100644 index 0000000000..10858f48ba --- /dev/null +++ b/platforms/android/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "Acode" +include(":app") diff --git a/platforms/ios/Alpine/Assets/axs b/platforms/ios/Alpine/Assets/axs new file mode 100644 index 0000000000..ef1999771c Binary files /dev/null and b/platforms/ios/Alpine/Assets/axs differ diff --git a/platforms/ios/Alpine/Bridge/AlpineArchive.c b/platforms/ios/Alpine/Bridge/AlpineArchive.c new file mode 100644 index 0000000000..509de118c3 --- /dev/null +++ b/platforms/ios/Alpine/Bridge/AlpineArchive.c @@ -0,0 +1,15 @@ +#include "AcodeAlpine.h" +#include <stdio.h> +#include <stdlib.h> +#include "tools/fakefs.h" + +bool alpine_import(const char *archive, const char *root, char *error, size_t capacity) { + struct fakefsify_error failure = {0}; + bool result = fakefs_import(archive, root, &failure, (struct progress){0}); + if (!result) { + snprintf(error, capacity, "%s", failure.message ? failure.message : "Could not extract Alpine"); + free(failure.message); + } + return result; +} + diff --git a/platforms/ios/Alpine/Bridge/AlpineFaults.c b/platforms/ios/Alpine/Bridge/AlpineFaults.c new file mode 100644 index 0000000000..254891dd14 --- /dev/null +++ b/platforms/ios/Alpine/Bridge/AlpineFaults.c @@ -0,0 +1,115 @@ +// Guest fault recovery from ios-linuxkit main.c; see Vendor/ios-linuxkit/LICENSE.md. +#include "AcodeAlpine.h" +#include <signal.h> +#include <stddef.h> +#include <unistd.h> +#include "kernel/task.h" +#include "asbestos/frame.h" +#include "platform/host_context_aarch64.h" + +static struct sigaction previous_segv, previous_bus; +static void crash_handler(int sig, siginfo_t *info, void *ctx); + +void alpine_install_fault_handlers(void) { + struct sigaction action = {.sa_sigaction = crash_handler, .sa_flags = SA_SIGINFO}; + sigemptyset(&action.sa_mask); + sigaction(SIGSEGV, &action, &previous_segv); + sigaction(SIGBUS, &action, &previous_bus); +} + +// Thread-local JIT recovery state (defined in asbestos.c) +extern __thread volatile sig_atomic_t in_jit; +extern __thread volatile uint64_t jit_saved_pc; + +// Diagnostic: JIT crash info (defined in calls.c) +extern __thread volatile uint64_t jit_last_host_fault; +extern __thread volatile uint64_t jit_last_x7; +extern __thread volatile uint64_t jit_last_x10; +extern __thread volatile int jit_crash_count; +extern volatile bool g_trace_highbits; +extern volatile bool g_trace_faults; + +int fakefs_bind_mount(const char *linux_path, const char *host_path, bool read_only); + +// Assembly trampoline: returns INT_JIT_CRASH via fiber_exit (defined in entry.S) +extern void jit_crash_trampoline(void); + +// Offsets needed by the async crash handler. Keep these derived from the C +// structs instead of hard-coding cpu-offsets.h values; the signal handler runs +// in C, and stale constants here corrupt JIT crash recovery when cpu_state or +// fiber_frame changes. +#define CRASH_CPU_pc offsetof(struct cpu_state, pc) +#define CRASH_CPU_segfault_addr offsetof(struct cpu_state, segfault_addr) +#define CRASH_CPU_segfault_was_write offsetof(struct cpu_state, segfault_was_write) +#define CRASH_LOCAL_jit_exit_sp offsetof(struct fiber_frame, jit_exit_sp) +#define CRASH_LOCAL_jit_saved_pc offsetof(struct fiber_frame, jit_saved_pc) + +static void crash_handler(int sig, siginfo_t *info, void *ctx) { +#ifdef __aarch64__ + // If we're inside JIT code and got SIGSEGV/SIGBUS, recover by redirecting + // execution to jit_crash_trampoline via ucontext PC manipulation. + // This avoids the overhead of _setjmp on every block entry. + if ((sig == SIGSEGV || sig == SIGBUS) && in_jit) { + ucontext_t *uc = (ucontext_t *)ctx; + + // _cpu is in x1 — pointer to cpu_state within fiber_frame + uint64_t cpu_ptr = host_ctx_aarch64_reg(uc, 1); + + // Reconstruct guest segfault_addr from registers. + // x7 = _addr (host pointer = data_minus_addr + guest_addr) + // x10 may hold data_minus_addr from TLB lookup (but only on TLB HIT path) + uint64_t x7 = host_ctx_aarch64_reg(uc, 7); + uint64_t x10 = host_ctx_aarch64_reg(uc, 10); + uint64_t guest_addr = (x7 - x10) & 0xffffffffffffULL; + + // Store diagnostic info for handle_interrupt to read + jit_last_host_fault = (uint64_t)info->si_addr; + jit_last_x7 = x7; + jit_last_x10 = x10; + jit_crash_count++; + + // Determine read/write from the host signal ABI when available. + int was_write = host_ctx_aarch64_fault_was_write(uc, info); + + // Write crash info directly to cpu_state via _cpu pointer + *(uint64_t *)(cpu_ptr + CRASH_CPU_segfault_addr) = guest_addr; + *(int *)(cpu_ptr + CRASH_CPU_segfault_was_write) = was_write; + // Restore guest PC to the latest faultable guest instruction for + // re-execution. This is usually more precise than the block-start TLS + // fallback and avoids re-running earlier side effects in the block. + uint64_t retry_pc = *(uint64_t *)(cpu_ptr + CRASH_LOCAL_jit_saved_pc); + if (retry_pc == 0) + retry_pc = (uint64_t)jit_saved_pc; + *(uint64_t *)(cpu_ptr + CRASH_CPU_pc) = retry_pc; + + // Restore SP to the value saved by fiber_enter, so fiber_exit + // can correctly pop the callee-saved register frame. + uint64_t exit_sp = *(uint64_t *)(cpu_ptr + CRASH_LOCAL_jit_exit_sp); + host_ctx_aarch64_set_sp(uc, exit_sp); + + // Redirect execution to crash trampoline (returns INT_JIT_CRASH) + host_ctx_aarch64_set_pc(uc, (uint64_t)jit_crash_trampoline); + + // Unblock signal so it can fire again on next crash + sigset_t unblock; + sigemptyset(&unblock); + sigaddset(&unblock, sig); + sigprocmask(SIG_UNBLOCK, &unblock, NULL); + + // Signal handler returns; execution resumes at jit_crash_trampoline + return; + } +#endif + + // Faults outside the emulator retain the host application's signal behavior. + struct sigaction previous = sig == SIGSEGV ? previous_segv : previous_bus; + if (previous.sa_handler == SIG_IGN) return; + if (previous.sa_handler == SIG_DFL) { + sigaction(sig, &previous, NULL); + raise(sig); + } else if (previous.sa_flags & SA_SIGINFO) { + previous.sa_sigaction(sig, info, ctx); + } else { + previous.sa_handler(sig); + } +} diff --git a/platforms/ios/Alpine/Bridge/AlpineRuntime.c b/platforms/ios/Alpine/Bridge/AlpineRuntime.c new file mode 100644 index 0000000000..f24edba64d --- /dev/null +++ b/platforms/ios/Alpine/Bridge/AlpineRuntime.c @@ -0,0 +1,240 @@ +#include "AcodeAlpine.h" +#include <signal.h> +#include <stdio.h> +#include <string.h> +#include <sys/stat.h> +#include <unistd.h> +#include "kernel/calls.h" +#include "kernel/init.h" +#include "kernel/task.h" +#include "fs/dev.h" +#include "fs/devices.h" +#include "fs/path.h" +#include "fs/real.h" +#include "fs/sockrestart.h" +#include "AlpineSpawn.h" + +extern int fakefs_bind_mount(const char *, const char *, bool); +extern int do_wait(int, pid_t_, struct siginfo_ *, struct rusage_ *, int); +static struct task *init_task; +static AlpineExitCallback on_exit; +static int attach_descriptors(void *argument); +static void process_exit(struct task *task, int status); +static struct fd *host_descriptor(int number); +static void *failed_process(void *task); +static void *idle_init(void *task); + +int alpine_boot(const char *root, AlpineExitCallback callback) { + int result = mount_root(&fakefs, root); + if (result < 0) return result; + if (init_task == NULL) { + result = become_first_process(); + if (result < 0) return result; + init_task = current; + int thread_error = pthread_create(&init_task->thread, NULL, idle_init, init_task); + if (thread_error != 0) return -thread_error; + pthread_detach(init_task->thread); + alpine_install_fault_handlers(); + } else { + current = init_task; + current->fs->root = generic_open("/", O_RDONLY_, 0); + if (IS_ERR(current->fs->root)) return (int) PTR_ERR(current->fs->root); + current->fs->pwd = fd_retain(current->fs->root); + } + on_exit = callback; + exit_hook = process_exit; + generic_mkdirat(AT_PWD, "/dev", 0755); + generic_mkdirat(AT_PWD, "/dev/pts", 0755); + generic_mkdirat(AT_PWD, "/dev/shm", 01777); + generic_mkdirat(AT_PWD, "/proc", 0755); + generic_mkdirat(AT_PWD, "/tmp", 01777); + generic_mkdirat(AT_PWD, "/run", 0755); + generic_mkdirat(AT_PWD, "/sys", 0755); + const struct { const char *path; int major; int minor; } devices[] = { + {"/dev/null", MEM_MAJOR, DEV_NULL_MINOR}, + {"/dev/zero", MEM_MAJOR, DEV_ZERO_MINOR}, + {"/dev/full", MEM_MAJOR, DEV_FULL_MINOR}, + {"/dev/random", MEM_MAJOR, DEV_RANDOM_MINOR}, + {"/dev/urandom", MEM_MAJOR, DEV_URANDOM_MINOR}, + {"/dev/tty", TTY_ALTERNATE_MAJOR, DEV_TTY_MINOR}, + {"/dev/console", TTY_ALTERNATE_MAJOR, DEV_CONSOLE_MINOR}, + {"/dev/ptmx", TTY_ALTERNATE_MAJOR, DEV_PTMX_MINOR}, + }; + for (size_t index = 0; index < sizeof(devices) / sizeof(devices[0]); index++) { + generic_mknodat(AT_PWD, devices[index].path, S_IFCHR | 0666, + dev_make(devices[index].major, devices[index].minor)); + } + result = do_mount(&procfs, "proc", "/proc", "", 0); + if (result >= 0) result = do_mount(&devptsfs, "devpts", "/dev/pts", "", 0); + current = NULL; + return result; +} + +int alpine_bind(const char *guest, const char *host, bool readOnly) { + current = init_task; + char *parent = strdup(guest); + for (char *slash = strchr(parent + 1, '/'); slash != NULL; slash = strchr(slash + 1, '/')) { + *slash = '\0'; + int result = generic_mkdirat(AT_PWD, parent, 0755); + *slash = '/'; + if (result < 0 && result != _EEXIST) { free(parent); current = NULL; return result; } + } + free(parent); + int result = fakefs_bind_mount(guest, host, readOnly); + current = NULL; + return result; +} + +int alpine_chmod(const char *path, unsigned int mode) { + current = init_task; + int result = generic_setattrat(AT_PWD, path, (struct attr) {.type = attr_mode, .mode = mode}, true); + current = NULL; + return result; +} + +int alpine_start(const char *command, const char *environment, int input, int output, int error) { + int descriptors[] = {input, output, error}; + return alpine_spawn(command, environment, attach_descriptors, descriptors); +} + +int alpine_spawn(const char *command, const char *environment, int (*attach)(void *), void *argument) { + current = init_task; + int result = become_new_init_child(); + if (result < 0) { current = NULL; return result; } + result = attach(argument); + if (result >= 0) { + size_t length = strlen(command); + char *arguments = calloc(1, length + 14); + memcpy(arguments, "/bin/sh\0-c\0", 11); + memcpy(arguments + 11, command, length); + result = do_execve("/bin/sh", 3, arguments, environment); + free(arguments); + } + int pid = current->pid; + sigset_t wake, previous; + sigemptyset(&wake); + sigaddset(&wake, SIGUSR1); + // GCD workers block SIGUSR1; guest threads must inherit an unblocked mask. + pthread_sigmask(SIG_UNBLOCK, &wake, &previous); + if (result < 0) { + pthread_t thread; + pthread_create(&thread, NULL, failed_process, current); + pthread_detach(thread); + } else { + task_start(current); + } + pthread_sigmask(SIG_SETMASK, &previous, NULL); + current = NULL; + return result < 0 ? result : pid; +} + +int alpine_kill(int pid) { + if (pid <= 1) return -22; + lock(&pids_lock); + struct task *task = pid_get_task(pid); + bool group = task != NULL && task->group->pgid == pid; + if (task != NULL && !group) send_signal(task, SIGKILL_, SIGINFO_NIL); + unlock(&pids_lock); + if (task == NULL) return _ESRCH; + return group ? send_group_signal(pid, SIGKILL_, SIGINFO_NIL) : 0; +} + +bool alpine_running(int pid) { + lock(&pids_lock); + struct task *task = pid_get_task(pid); + bool running = task != NULL && !task->exiting; + unlock(&pids_lock); + return running; +} + +void alpine_reap(void) { + if (init_task == NULL) return; + current = init_task; + struct siginfo_ info = {0}; + // P_ALL=0, WNOHANG=1, WEXITED=4 (Linux wait ABI). + while (do_wait(0, 0, &info, NULL, 5) == 0 && info.child.pid != 0) { + memset(&info, 0, sizeof(info)); + } + current = NULL; +} + +void alpine_stop_all(void) { + lock(&pids_lock); + for (int pid = 2; pid < MAX_PID; pid++) { + struct task *task = pid_get_task(pid); + if (task != NULL && !task->exiting) send_signal(task, SIGKILL_, SIGINFO_NIL); + } + unlock(&pids_lock); +} + +bool alpine_idle(void) { + bool idle = true; + lock(&pids_lock); + for (int pid = 2; pid < MAX_PID; pid++) { + struct task *task = pid_get_task(pid); + if (task != NULL && !task->exiting) { idle = false; break; } + } + unlock(&pids_lock); + return idle; +} + +int alpine_unmount(void) { + if (!alpine_idle()) return -16; + alpine_reap(); + current = init_task; + fd_close(current->fs->pwd); + fd_close(current->fs->root); + current->fs->pwd = current->fs->root = NULL; + int result = do_umount("/dev/pts"); + if (result == 0) result = do_umount("/proc"); + if (result == 0) result = do_umount(""); + current = NULL; + return result; +} + +void alpine_suspend(void) { + sockrestart_on_suspend(); +} + +void alpine_resume(void) { + sockrestart_on_resume(); +} + +static int attach_descriptors(void *argument) { + int *descriptors = argument; + for (int index = 0; index < 3; index++) { + current->files->files[index] = host_descriptor(descriptors[index]); + } + return 0; +} + +static void process_exit(struct task *task, int status) { + if (on_exit != NULL) on_exit(task->tgid, (status & 0x7f) ? 128 + (status & 0x7f) : status >> 8); +} + +static struct fd *host_descriptor(int number) { + struct fd *descriptor = adhoc_fd_create(&realfs_fdops); + descriptor->real_fd = dup(number); + descriptor->dir = NULL; + descriptor->flags = O_RDWR_; + struct stat info; + fstat(number, &info); + descriptor->stat.mode = info.st_mode; + descriptor->stat.inode = info.st_ino; + return descriptor; +} + +static void *failed_process(void *task) { + current = task; + do_exit(127 << 8); +} + +static void *idle_init(void *task) { + current = task; + // Keep a stable signal target for PID 1; Swift's serial queue reaps its + // orphaned children after exit notifications without running a guest init. + sigset_t mask; + sigfillset(&mask); + sigdelset(&mask, SIGUSR1); + for (;;) sigsuspend(&mask); +} diff --git a/platforms/ios/Alpine/Bridge/AlpineSpawn.h b/platforms/ios/Alpine/Bridge/AlpineSpawn.h new file mode 100644 index 0000000000..b79841a6e1 --- /dev/null +++ b/platforms/ios/Alpine/Bridge/AlpineSpawn.h @@ -0,0 +1,5 @@ +#pragma once + +// Runs `/bin/sh -c command` as a new child of PID 1. `attach` runs as the new +// task before exec to install its stdio; a negative result fails the spawn. +int alpine_spawn(const char *command, const char *environment, int (*attach)(void *), void *argument); diff --git a/platforms/ios/Alpine/Bridge/AlpineTerminal.c b/platforms/ios/Alpine/Bridge/AlpineTerminal.c new file mode 100644 index 0000000000..f7bf0f8438 --- /dev/null +++ b/platforms/ios/Alpine/Bridge/AlpineTerminal.c @@ -0,0 +1,136 @@ +#include "AcodeAlpine.h" +#include <stdio.h> +#include <stdlib.h> +#include "kernel/errno.h" +#include "kernel/init.h" +#include "kernel/signal.h" +#include "kernel/task.h" +#include "fs/devices.h" +#include "fs/tty.h" +#include "AlpineSpawn.h" + +// The guest side is a regular /dev/pts slave, so shells get job control, +// termios and SIGWINCH. The host side is this driver instead of a pty master, +// which keeps terminal I/O out of emulated sockets and polling. +struct AlpineTerminal { + struct tty *tty; + int rows; + int cols; + void *context; + AlpineTerminalCallbacks callbacks; + lock_t lock; + cond_t drained; + bool closed; +}; + +static int terminal_write(struct tty *tty, const void *data, size_t length, bool blocking); +static void terminal_cleanup(struct tty *tty); +static int attach_terminal(void *argument); + +static const struct tty_driver_ops terminal_ops = { + .write = terminal_write, + .cleanup = terminal_cleanup, +}; +// pty_open_fake fills in the slot table and major number. +static struct tty_driver terminal_driver = {.ops = &terminal_ops}; + +int alpine_terminal_start(const char *command, const char *environment, int rows, int cols, + void *context, AlpineTerminalCallbacks callbacks, AlpineTerminal **handle) { + *handle = NULL; + AlpineTerminal *terminal = calloc(1, sizeof(AlpineTerminal)); + if (terminal == NULL) { callbacks.release(context); return _ENOMEM; } + *terminal = (AlpineTerminal) {.rows = rows, .cols = cols, .context = context, .callbacks = callbacks}; + lock_init(&terminal->lock); + cond_init(&terminal->drained); + int pid = alpine_spawn(command, environment, attach_terminal, terminal); + if (terminal->tty == NULL) { + callbacks.release(context); + cond_destroy(&terminal->drained); + free(terminal); + } else if (pid < 0) { + alpine_terminal_close(terminal); + } else { + *handle = terminal; + } + return pid; +} + +long alpine_terminal_input(AlpineTerminal *terminal, const char *data, size_t length) { + return tty_input(terminal->tty, data, length, false); +} + +void alpine_terminal_resize(AlpineTerminal *terminal, int rows, int cols) { + struct tty *tty = terminal->tty; + lock(&tty->lock); + tty->winsize = (struct winsize_) {.row = rows, .col = cols}; + pid_t_ foreground = tty->fg_group; + unlock(&tty->lock); + if (foreground != 0) send_group_signal(foreground, SIGWINCH_, SIGINFO_NIL); +} + +void alpine_terminal_drained(AlpineTerminal *terminal) { + lock(&terminal->lock); + notify(&terminal->drained); + unlock(&terminal->lock); +} + +void alpine_terminal_close(AlpineTerminal *terminal) { + lock(&terminal->lock); + terminal->closed = true; + notify(&terminal->drained); + unlock(&terminal->lock); + struct tty *tty = terminal->tty; + lock(&tty->lock); + pid_t_ session = tty->session; + pid_t_ foreground = tty->fg_group; + tty_hangup(tty); + unlock(&tty->lock); + // Matches Linux when the master side of a pty goes away. + if (foreground != 0) send_group_signal(foreground, SIGHUP_, SIGINFO_NIL); + if (session != 0 && session != foreground) send_group_signal(session, SIGHUP_, SIGINFO_NIL); + lock(&ttys_lock); + tty_release(tty); + unlock(&ttys_lock); +} + +// Runs on guest threads. The tty lock may be held (echo), so it must not re-enter the tty. +// A blocking writer waits like on a full pipe while the client is behind. wait_for +// returns _EINTR for pending guest signals, so Ctrl-C and SIGKILL still get through, +// and nothing has been written yet when it does. +static int terminal_write(struct tty *tty, const void *data, size_t length, bool blocking) { + AlpineTerminal *terminal = tty->data; + if (blocking) { + int result = 0; + lock(&terminal->lock); + while (result == 0 && !terminal->closed && terminal->callbacks.congested(terminal->context)) { + struct timespec recheck = {.tv_nsec = 100 * 1000 * 1000}; + result = wait_for(&terminal->drained, &terminal->lock, &recheck); + if (result == _ETIMEDOUT) result = 0; + } + unlock(&terminal->lock); + if (result < 0) return result; + } + terminal->callbacks.output(terminal->context, data, length); + return 0; +} + +// Runs once the host and every guest descriptor have released the tty. +static void terminal_cleanup(struct tty *tty) { + AlpineTerminal *terminal = tty->data; + terminal->callbacks.release(terminal->context); + cond_destroy(&terminal->drained); + free(terminal); +} + +// Runs as the new session leader, so opening the slave makes it the controlling tty. +static int attach_terminal(void *argument) { + AlpineTerminal *terminal = argument; + struct tty *tty = pty_open_fake(&terminal_driver); + if (IS_ERR(tty)) return (int) PTR_ERR(tty); + tty->data = terminal; + tty->winsize = (struct winsize_) {.row = terminal->rows, .col = terminal->cols}; + terminal->tty = tty; + char path[32]; + snprintf(path, sizeof(path), "/dev/pts/%d", tty->num); + return create_stdio(path, TTY_PSEUDO_SLAVE_MAJOR, tty->num); +} diff --git a/platforms/ios/Alpine/GPL-3.0.txt b/platforms/ios/Alpine/GPL-3.0.txt new file mode 100644 index 0000000000..f288702d2f --- /dev/null +++ b/platforms/ios/Alpine/GPL-3.0.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/platforms/ios/Alpine/README.md b/platforms/ios/Alpine/README.md new file mode 100644 index 0000000000..7eb1871014 --- /dev/null +++ b/platforms/ios/Alpine/README.md @@ -0,0 +1,136 @@ +# Acode iOS Alpine runtime + +The existing Acode xterm UI connects to the same AXS HTTP/WebSocket API used on +Android. ARM64 Linux programs run inside ios-linuxkit's interpreter; they are not +launched as unsigned iOS executables. + +On iOS that API is served by the app, not by AXS inside the guest. Only the +shells are emulated: + +``` +xterm.js ──ws/http──▶ TerminalServer (Swift, 127.0.0.1:8767) + └─ TerminalSession ──▶ Bridge/AlpineTerminal.c ──▶ /dev/pts/N ──▶ bash +``` + +`AlpineTerminal.c` registers a tty driver whose output goes straight to Swift +and whose input, resize and hangup go straight to the guest tty. Terminal I/O +therefore never uses emulated sockets, epoll or threads, and the guest pty still +provides job control, termios and `SIGWINCH`. `init-alpine.sh --prepare` runs +once per boot; each terminal then starts `bash --rcfile /initrc -i` directly. +The AXS binary stays in the guest as `axs` for users and plugins. + +The native Executor services use guest processes and pipes. Apple +Network.framework supplies the raw process WebSocket transport for +`Executor.spawnStream`. + +## Sources + +| Component | Pinned source | +| --- | --- | +| Kernel, ARM64 interpreter, fakefs | [rcarmo/ios-linuxkit](https://github.com/rcarmo/ios-linuxkit/tree/61719f8177499f789fc2f7f421ea919ac7780608), `61719f8177499f789fc2f7f421ea919ac7780608` | +| libarchive | `deps/libarchive` and `deps/config.h` from that same revision; BSD notices retained | +| AXS | [bajrangCoder/acodex_server v0.2.17](https://github.com/bajrangCoder/acodex_server/releases/tag/v0.2.17), asset `axs-musl-android-arm64` | +| Alpine rootfs | The existing Android ARM64 Alpine 3.21.0 asset, copied at build time | +| Shell setup | The existing Android `init-alpine.sh`, with `ALPINE_ROOT=/` on iOS | + +AXS SHA-256: `2f2f07e388fd5701eec4d008e67f2a9a2c05564dbd09a3fea96c9dc1cee42765`. +Its upstream Rust source revision is `2fb966607893e3b8f0e243d71c83a505c06951b3`. +To replace it, build the pinned source with `cross build --release --locked +--target aarch64-unknown-linux-musl`, or verify the published asset's checksum. + +The vendored runtime includes its GPL attribution and iOS distribution exception. +`GPL-3.0.txt` contains the license text. Distributions linking this runtime must +provide corresponding source under the applicable GPL terms; existing notices +for Acode and other dependencies still apply. + +## Build + +On an Apple Silicon Mac, install `brew install meson ninja llvm lld`, then use the +normal Acode iOS commands or build in Xcode. The **Build Alpine** phase compiles +the static runtime and Linux VDSO, then copies the existing rootfs and startup +script into the app. No Meson build products or developer paths are committed. +`ACODE_BUILD_TOOLS` and `ACODE_LLD_BIN` can point to alternative tool directories. +ARM64 devices and ARM64 simulators are supported. + +Both shared Xcode schemes load `Alpine/lldbinit` for Run and Test. It passes +`SIGUSR1` to the runtime without stopping the debugger; Alpine uses this signal +to wake guest threads. With LLDB's default handling, Xcode pauses the entire app +during installation, and returning to the paused app can show a black screen. +For an already-paused session, run `process handle -p true -s false -n false +SIGUSR1` in Xcode's debug console, then `continue`. + +## Local adaptations + +- `platform/darwin.c` imports Dispatch for `dispatch_once`. +- `meson.build` builds the selected upstream libarchive sources and Acode bridge; + command-line utilities and upstream e2e tests are excluded from cross builds. +- `fs/fake.c` releases its host root descriptor and bind table when unmounted. +- `fs/real.c` translates Darwin directory-unlink `EPERM` to Linux `EISDIR`, + allowing Bun to remove directory locks. +- `/proc/stat` includes all ten CPU counters and `/proc/<pid>/stat` reports + immutable process start ticks for process inspection and daemon identity checks. +- `kernel/group.c` handles the last terminal session member exiting after its + session leader has been reaped. +- Synchronous memory and illegal-instruction faults restore default handling if + their signals are blocked or ignored, preventing infinite fault retries. +- ARM64 halfword lane loads and stores decode the lane index correctly, including + post-indexed addressing. This fixes Bun's hybrid TLS key exchange failures. +- The code-cache page table has 65,536 buckets to reduce unrelated code + invalidation during Bun's JIT writes, using 2 MiB per guest address space. +- Block-cache hashing removes ARM64 instruction-alignment bits so all existing + buckets are used, without increasing cache allocation. +- `kernel/exit.c` clears the exiting leader's thread-local pointer before its + parent can reap it, preventing pthread cleanup from accessing a freed task. +- `Bridge/AlpineFaults.c` reuses upstream ARM64 fault recovery and delegates faults + outside the guest to the app's previous signal handlers. +- `Bridge/AlpineRuntime.c` owns guest init, stdio, process cleanup and mounts. + SIGUSR1 is unblocked only while creating guest threads, then the host worker's + signal mask is restored. +- `Bridge/AlpineTerminal.c` connects guest pseudo-terminals to Swift through + `pty_open_fake`, as iSH does for its terminal view. +- `alpine_suspend`/`alpine_resume` run upstream `sockrestart` when the app moves + to the background and back, so guest servers keep their listening sockets. + +The guest root lives at `Library/Alpine`, outside every host bind mount. `/public`, +`/home` and `/root` share Acode's Terminal Public directory. `/acode` maps app data, +and authorized Files roots are also mapped at their native paths for language +servers. Linux filesystem metadata is owned by fakefs; do not edit its `data/` +directory with FileManager. The `alpine://localhost/` filesystem provider performs +guest file operations through the existing Executor API. + +## Compatibility limits + +This is Linux userspace emulation, not Android proot. APK packages run as ARM64 +Linux programs, but support still depends on the emulator's instructions and +syscalls. Upstream forces Node to run without JIT and with a 512 MiB old-space +limit; V8 WebAssembly and packages requiring unsupported syscalls may not work. +The injected `--no-expose-wasm` flag suppresses V8's conflicting-flag warning; +it does not enable WebAssembly. +Bun (including compiled CLIs such as OpenCode) keeps baseline JIT for FFI, while +optimizing/concurrent JIT and concurrent garbage collection are disabled through +`BUN_JSC_` guest settings. iOS shell setup installs +`procps-ng` because daemon-based CLIs require process inspection options missing +from BusyBox `ps`. GNU `tar` and `gzip` replace BusyBox archive extraction to +reduce the CPU cost of unpacking large CLI binaries. The upstream optional +WebAssembly polyfills are not bundled. iOS may suspend or terminate the app in +the background. PRoot debug mode has no effect on iOS. +Physical-device performance, memory pressure and background behavior need their +own validation. iOS backups preserve Linux metadata and exclude host mounts; +Android proot backup archives have a different layout. + +### Pi coding agent + +The npm package `pi` is a numeric calculator. The coding agent is +`@earendil-works/pi-coding-agent`. Its Node entry point requires WebAssembly, +so launch it explicitly with Bun on iOS: + +```sh +npm uninstall -g pi # Only if the unrelated calculator was installed. +npm install -g bun@1.4.2 +npm install -g --ignore-scripts @earendil-works/pi-coding-agent@0.99.1 +bun --bun "$(command -v pi)" +``` + +The published CLI's startup, terminal input, and a local streaming HTTP response +passed simulator checks with the official ARM64 musl Bun binary. Physical-device +authentication, provider requests, and coding tasks still need validation. diff --git a/platforms/ios/Alpine/Tests/fault-signals.S b/platforms/ios/Alpine/Tests/fault-signals.S new file mode 100644 index 0000000000..ff146bedce --- /dev/null +++ b/platforms/ios/Alpine/Tests/fault-signals.S @@ -0,0 +1,96 @@ +.text +.global _start +_start: + ldr x0, [sp] + cmp x0, #3 + b.ne fail + ldr x0, [sp, #16] + ldrb w19, [x0] + ldr x0, [sp, #24] + ldrb w0, [x0] + mov x20, #11 + cmp w0, #'i' + b.ne configure + mov x20, #4 +configure: + adr x1, action + adr x0, handled + cmp w19, #'i' + b.ne install + mov x0, #1 +install: + str x0, [x1] + mov x0, x20 + mov x2, #0 + mov x3, #8 + mov x8, #134 + svc #0 + cbnz x0, fail + + cmp w19, #'b' + b.eq block + cmp w19, #'q' + b.ne fault +block: + sub x0, x20, #1 + mov x21, #1 + lsl x21, x21, x0 + adr x1, mask + str x21, [x1] + mov x0, #0 + mov x2, #0 + mov x3, #8 + mov x8, #135 + svc #0 + cbnz x0, fail + cmp w19, #'q' + b.ne fault + + mov x8, #172 + svc #0 + mov x1, x20 + mov x8, #129 + svc #0 + cbnz x0, fail + adr x0, pending + mov x1, #8 + mov x8, #136 + svc #0 + cbnz x0, fail + adr x0, pending + ldr x0, [x0] + cmp x0, x21 + b.ne fail + mov x0, #1 + adr x1, mask + mov x2, #0 + mov x3, #8 + mov x8, #135 + svc #0 + b fail +fault: + cmp x20, #4 + b.eq illegal + mov x0, #0 + ldrh w1, [x0, #0xba] + b fail +illegal: + .inst 0 + b fail +handled: + mov x0, #42 + b finish +fail: + mov x0, #1 +finish: + mov x8, #93 + svc #0 + +.data +.balign 8 +action: + .zero 32 +mask: + .quad 0 +pending: + .quad 0 diff --git a/platforms/ios/Alpine/Tests/halfword-lanes.S b/platforms/ios/Alpine/Tests/halfword-lanes.S new file mode 100644 index 0000000000..2cd31a7b2d --- /dev/null +++ b/platforms/ios/Alpine/Tests/halfword-lanes.S @@ -0,0 +1,83 @@ +.text +.global _start +_start: + adr x0, values + adr x1, result + mov x8, #2 + +.macro check_result + ldp x10, x11, [x0] + ldp x12, x13, [x1] + cmp x10, x12 + b.ne fail + cmp x11, x13 + b.ne fail +.endm + +.macro load_lanes mode + movi v0.16b, #0 + mov x9, x0 + .irp lane, 0, 1, 2, 3, 4, 5, 6, 7 + .if \mode == 0 + ld1 {v0.h}[\lane], [x9] + add x9, x9, #2 + .elseif \mode == 1 + ld1 {v0.h}[\lane], [x9], #2 + .else + ld1 {v0.h}[\lane], [x9], x8 + .endif + .endr + str q0, [x1] + check_result +.endm + +.macro store_lanes mode + ldr q0, [x0] + stp xzr, xzr, [x1] + mov x9, x1 + .irp lane, 0, 1, 2, 3, 4, 5, 6, 7 + .if \mode == 0 + st1 {v0.h}[\lane], [x9] + add x9, x9, #2 + .elseif \mode == 1 + st1 {v0.h}[\lane], [x9], #2 + .else + st1 {v0.h}[\lane], [x9], x8 + .endif + .endr + check_result +.endm + + load_lanes 0 + load_lanes 1 + load_lanes 2 + store_lanes 0 + store_lanes 1 + store_lanes 2 + + adr x1, pass_text + mov x2, #9 + mov x3, #0 + b finish +fail: + adr x1, fail_text + mov x2, #9 + mov x3, #1 +finish: + mov x0, #1 + mov x8, #64 + svc #0 + mov x0, x3 + mov x8, #93 + svc #0 + +.data +.balign 16 +values: + .hword 0x1111, 0x2222, 0x3333, 0x4444, 0x5555, 0x6666, 0x7777, 0x8888 +result: + .zero 16 +pass_text: + .ascii "SIMD_PASS" +fail_text: + .ascii "SIMD_FAIL" diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/LICENSE.IOS b/platforms/ios/Alpine/Vendor/ios-linuxkit/LICENSE.IOS new file mode 100644 index 0000000000..106cfd4667 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/LICENSE.IOS @@ -0,0 +1,12 @@ +The iSH developers are aware that the terms of service that apply to +apps distributed via Apple's App Store services may conflict with +rights granted under the iSH license, the GNU General Public License, +version 2 or 3. The copyright holders of the iSH app do not wish this +conflict to prevent the otherwise-compliant distribution of derived +apps via the App Store. Therefore, we have committed not to pursue +any license violation that results solely from the conflict between +the GNU GPLv2 or v3 and the Apple App Store terms of service. In other +words, as long as you comply with the GPL in all other respects, +including its requirements to provide users with source code and the +text of the license, we will not object to your distribution of the +iSH app through the App Store. diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/LICENSE.md b/platforms/ios/Alpine/Vendor/ios-linuxkit/LICENSE.md new file mode 100644 index 0000000000..21ee4d545a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/LICENSE.md @@ -0,0 +1,35 @@ +iSH is licensed under the [GPLv3][]. The additional terms in LICENSE.IOS also apply. + +Contributions made after commit 0e3a4144f93135c4fd618c8397d2cfd87194f69f are +additionally licensed under the [GPLv2][]. This is intended to allow linking +with GPLv2 licensed projects such as Linux and QEMU. + +The following authors have agreed to relicense their past contributions under GPLv2: +- Theodore Dubois <tblodt@icloud.com> +- Saagar Jha <saagar@saagarjha.com> +- Christoffer Tønnessen <christoffertonnessen@icloud.com> <christoffer.tonnessen@gmail.com> +- Philipp Wallisch <philipp.wallisch@inode.at> +- Ed Luff <beartechtalks@gmail.com> +- David Southgate <d@davidsouthgate.co.uk> +- Charlie Melbye <charles.melbye@gmail.com> +- David <0b101@users.noreply.github.com> +- [as@irc](https://gist.github.com/tbodt/45ccbea8d3c095258d63f611654f05b4) +- asdfugil (name was "Assfugil" when last contributed) <towinchenmi@gmail.com> <42699250+Assfugil@users.noreply.github.com> +- AngeloHYang <38714377+AngeloHYang@users.noreply.github.com> +- Matthew Merrill <mattmerr47@gmail.com> +- Siddharth Dushantha <siddharth.dushantha@gmail.com> +- Lorenzo De Linares <lorenzo.linares@icloud.com> +- Christopher Albert <albert@alumni.tugraz.at> +- Stephen Leaf <stephenaleaf@gmail.com> +- Noah Peeters <noah@noahpeeters.de> +- Alexis Marquis <alexis@marquis.me> +- Brian Almeida <bma@thunderkeys.net> +- Viktor Oreshkin <imselfish@stek29.rocks> +- Ryan Hileman <lunixbochs@gmail.com> +- Christoforos Charalambous <chrischaralambous14@gmail.com> +- Kenta Kubo <kabuto669@icloud.com> +- Zhuowei Zhang +- never_released <24752637+woachk@users.noreply.github.com> + +[GPLv3]: https://www.gnu.org/licenses/gpl-3.0.html +[GPLv2]: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/asbestos.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/asbestos.c new file mode 100644 index 0000000000..c76631d758 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/asbestos.c @@ -0,0 +1,1183 @@ +#define DEFAULT_CHANNEL instr +#include "debug.h" +#include <signal.h> +#include <stdatomic.h> +#include <stdbool.h> +#include <stdint.h> +#include <stddef.h> +#include <time.h> +#include <string.h> +#include <stdlib.h> +#include "asbestos/asbestos.h" +#include "asbestos/gen.h" +#include "asbestos/frame.h" +#include "emu/cpu.h" +#include "emu/interrupt.h" +#include "emu/tlb.h" +#include "kernel/memory.h" +#include "util/list.h" + +// Thread-local recovery state for JIT crash handling. +// When a host SIGSEGV occurs inside JIT code (due to a stale TLB pointer +// from a concurrent CoW), the signal handler redirects PC to +// jit_crash_trampoline via ucontext, which returns INT_GPF to the +// dispatch loop. handle_interrupt resolves via mem_ptr (CoW/GROWSDOWN). +// +// This avoids the overhead of _setjmp on every block entry (~1.5% of +// total execution time). The signal handler writes crash info directly +// to cpu_state via the _cpu pointer (x1) from ucontext. +__thread volatile sig_atomic_t in_jit; +__thread volatile addr_t jit_saved_pc; // block start PC, read by signal handler +// Marker set to 1 on iSH execution threads so the signal handler can distinguish +// iSH threads from app threads (Swift async, networking, UI). +__thread int ish_thread_marker; + +// Architecture-specific instruction pointer access +#if defined(GUEST_ARM64) +#define CPU_IP(cpu) ((cpu)->pc) +#define CPU_HAS_SINGLE_STEP 0 +#else +#define CPU_IP(cpu) ((cpu)->eip) +#define CPU_HAS_SINGLE_STEP ((cpu)->tf) +#endif + +extern int current_pid(void); + +#ifdef GUEST_ARM64 +__attribute__((weak)) void *mem_ptr(struct mem *mem, addr_t addr, int type) { + (void) mem; + (void) addr; + (void) type; + return NULL; +} +#endif + +#ifdef GUEST_ARM64 +bool arm64_block_stats_enabled; +static bool arm64_block_stats_dumped; +static bool arm64_eager_prechain_enabled; +static bool arm64_eager_prechain_incoming_enabled; +static _Atomic uint64_t arm64_block_stats_entries; +static _Atomic uint64_t arm64_block_stats_cache_hits; +static _Atomic uint64_t arm64_block_stats_cache_misses; +static _Atomic uint64_t arm64_block_stats_compiled; +static _Atomic uint64_t arm64_block_stats_code_words; +static _Atomic uint64_t arm64_block_stats_guest_bytes; +static _Atomic uint64_t arm64_block_stats_jump0; +static _Atomic uint64_t arm64_block_stats_jump1; +static _Atomic uint64_t arm64_block_stats_chain_attempts; +static _Atomic uint64_t arm64_block_stats_chain_patches; +static _Atomic uint64_t arm64_block_stats_chain_patch_slot0; +static _Atomic uint64_t arm64_block_stats_chain_patch_slot1; +static _Atomic uint64_t arm64_block_stats_chain_patch_same_page; +static _Atomic uint64_t arm64_block_stats_chain_patch_cross_page; +static _Atomic uint64_t arm64_block_stats_chain_entries; +static _Atomic uint64_t arm64_block_stats_chain_entry_slot0; +static _Atomic uint64_t arm64_block_stats_chain_entry_slot1; +static _Atomic uint64_t arm64_block_stats_chain_entry_unknown_slot; +static _Atomic uint64_t arm64_block_stats_chain_entry_same_page; +static _Atomic uint64_t arm64_block_stats_chain_entry_cross_page; +static _Atomic uint64_t arm64_block_stats_prechain_attempts; +static _Atomic uint64_t arm64_block_stats_prechain_patches; +static _Atomic uint64_t arm64_block_stats_prechain_outgoing_attempts; +static _Atomic uint64_t arm64_block_stats_prechain_outgoing_patches; +static _Atomic uint64_t arm64_block_stats_prechain_incoming_attempts; +static _Atomic uint64_t arm64_block_stats_prechain_incoming_patches; + +static bool env_enabled(const char *env) { + return env != NULL && env[0] != '\0' && strcmp(env, "0") != 0; +} + +static bool env_enabled_default(const char *env, bool default_enabled) { + if (env == NULL) + return default_enabled; + return env[0] != '\0' && strcmp(env, "0") != 0; +} +void arm64_block_stats_set_enabled_from_env(const char *env) { + arm64_block_stats_enabled = env_enabled(env); +} + +void arm64_eager_prechain_set_enabled_from_env(const char *env) { + arm64_eager_prechain_enabled = env_enabled_default(env, true); +} + +void arm64_eager_prechain_incoming_set_enabled_from_env(const char *env) { + // Incoming prechain is default-on again after hardening: only still-fake + // slots are patched, and older-block incoming patching is skipped while + // multiple guest threads are active. Keep ISH_ARM64_EAGER_PRECHAIN_INCOMING=0 + // as an explicit diagnostic/safety opt-out. + arm64_eager_prechain_incoming_enabled = env_enabled_default(env, true); +} + +void arm64_block_stats_dump_if_enabled(void) { + if (!arm64_block_stats_enabled || arm64_block_stats_dumped) + return; + arm64_block_stats_dumped = true; + fprintf(stderr, + "ARM64_BLOCK_STATS entries=%llu cache_hits=%llu cache_misses=%llu compiled=%llu code_words=%llu guest_bytes=%llu jump0=%llu jump1=%llu chain_attempts=%llu chain_patches=%llu chain_patch_slot0=%llu chain_patch_slot1=%llu chain_patch_same_page=%llu chain_patch_cross_page=%llu chain_entries=%llu chain_entry_slot0=%llu chain_entry_slot1=%llu chain_entry_unknown_slot=%llu chain_entry_same_page=%llu chain_entry_cross_page=%llu prechain_attempts=%llu prechain_patches=%llu prechain_outgoing_attempts=%llu prechain_outgoing_patches=%llu prechain_incoming_attempts=%llu prechain_incoming_patches=%llu\n", + (unsigned long long)atomic_load_explicit(&arm64_block_stats_entries, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_cache_hits, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_cache_misses, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_compiled, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_code_words, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_guest_bytes, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_jump0, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_jump1, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_chain_attempts, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_chain_patches, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_chain_patch_slot0, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_chain_patch_slot1, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_chain_patch_same_page, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_chain_patch_cross_page, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_chain_entries, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_chain_entry_slot0, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_chain_entry_slot1, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_chain_entry_unknown_slot, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_chain_entry_same_page, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_chain_entry_cross_page, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_prechain_attempts, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_prechain_patches, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_prechain_outgoing_attempts, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_prechain_outgoing_patches, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_prechain_incoming_attempts, memory_order_relaxed), + (unsigned long long)atomic_load_explicit(&arm64_block_stats_prechain_incoming_patches, memory_order_relaxed)); + fflush(stderr); +} + +#define ARM64_BLOCK_STAT_INC(counter) do { \ + if (arm64_block_stats_enabled) \ + atomic_fetch_add_explicit(&(counter), 1, memory_order_relaxed); \ +} while (0) +#define ARM64_BLOCK_STAT_ADD(counter, value) do { \ + if (arm64_block_stats_enabled) \ + atomic_fetch_add_explicit(&(counter), (uint64_t)(value), memory_order_relaxed); \ +} while (0) + +void arm64_block_stats_count_chained_entry(struct fiber_block *from, unsigned long to_code) { + if (!arm64_block_stats_enabled || from == NULL) + return; + + struct fiber_block *to = (struct fiber_block *)((char *)to_code - offsetof(struct fiber_block, code)); + atomic_fetch_add_explicit(&arm64_block_stats_chain_entries, 1, memory_order_relaxed); + if (PAGE(from->addr) == PAGE(to->addr)) + atomic_fetch_add_explicit(&arm64_block_stats_chain_entry_same_page, 1, memory_order_relaxed); + else + atomic_fetch_add_explicit(&arm64_block_stats_chain_entry_cross_page, 1, memory_order_relaxed); + + bool matched_slot = false; + for (int i = 0; i <= 1; i++) { + if (from->jump_ip[i] != NULL && *from->jump_ip[i] == to_code) { + if (i == 0) + atomic_fetch_add_explicit(&arm64_block_stats_chain_entry_slot0, 1, memory_order_relaxed); + else + atomic_fetch_add_explicit(&arm64_block_stats_chain_entry_slot1, 1, memory_order_relaxed); + matched_slot = true; + } + } + if (!matched_slot) + atomic_fetch_add_explicit(&arm64_block_stats_chain_entry_unknown_slot, 1, memory_order_relaxed); +} +#else +#define ARM64_BLOCK_STAT_INC(counter) do {} while (0) +#define ARM64_BLOCK_STAT_ADD(counter, value) do {} while (0) +#endif + +// Stubs / debug hooks referenced from assembly/gen.c/tlb.c +// High-bit tracing is an opt-in diagnostic. It is useful when chasing W/X +// register-extension bugs, but it is not a valid invariant for normal AArch64 +// execution: the dynamic linker and language runtimes legitimately keep tagged +// and maskable 64-bit values in general-purpose registers. +volatile bool g_trace_highbits = false; +volatile addr_t g_watch_page_val = 0; + +#define TRACE_PC_MAX 16 +volatile bool g_trace_guest_pc = false; +static addr_t g_trace_pc_vals[TRACE_PC_MAX]; +static addr_t g_trace_pc_masks[TRACE_PC_MAX]; +static int g_trace_pc_count = 0; + +static bool g_trace_gate_enabled = false; +static addr_t g_trace_gate_pc = 0; +static addr_t g_trace_gate_mask = ~(addr_t) 0; +static bool g_trace_gate_x4_enabled = false; +static uint64_t g_trace_gate_x4 = 0; +static int g_trace_gate_budget = 0; // 0 = unlimited after first gate hit + +static __thread bool t_trace_gate_open = false; +static __thread int t_trace_gate_left = 0; + +bool asbestos_should_trace_guest_pc(addr_t pc) { + if (!g_trace_guest_pc) + return false; + for (int i = 0; i < g_trace_pc_count; i++) { + if ((pc & g_trace_pc_masks[i]) == (g_trace_pc_vals[i] & g_trace_pc_masks[i])) + return true; + } + return false; +} + +void asbestos_set_trace_pcs(const char *spec) { + g_trace_guest_pc = false; + g_trace_pc_count = 0; + if (spec == NULL || spec[0] == '\0') + return; + + char *copy = strdup(spec); + if (copy == NULL) + return; + + for (char *tok = strtok(copy, ", "); tok != NULL; tok = strtok(NULL, ", ")) { + if (*tok == '\0' || g_trace_pc_count >= TRACE_PC_MAX) + continue; + + char *slash = strchr(tok, '/'); + addr_t value = 0; + addr_t mask = ~(addr_t) 0; + + if (slash != NULL) { + *slash = '\0'; + value = (addr_t) strtoull(tok, NULL, 0); + mask = (addr_t) strtoull(slash + 1, NULL, 0); + } else { + value = (addr_t) strtoull(tok, NULL, 0); + // Convenience: small values are treated as guest-offset matchers + // (e.g., 0x170aec matches pc&0xffffff). + if (value <= 0xffffff) + mask = 0xffffff; + } + + g_trace_pc_vals[g_trace_pc_count] = value; + g_trace_pc_masks[g_trace_pc_count] = mask; + g_trace_pc_count++; + } + + free(copy); + g_trace_guest_pc = g_trace_pc_count > 0; + if (g_trace_guest_pc) { + fprintf(stderr, "TRACEPC enabled (%d matchers) via ISH_TRACE_PCS\n", g_trace_pc_count); + } +} + +void asbestos_set_trace_gate(const char *pc_spec, const char *x4_spec, const char *budget_spec) { + g_trace_gate_enabled = false; + g_trace_gate_pc = 0; + g_trace_gate_mask = ~(addr_t) 0; + g_trace_gate_x4_enabled = false; + g_trace_gate_x4 = 0; + g_trace_gate_budget = 0; + t_trace_gate_open = false; + t_trace_gate_left = 0; + + if (pc_spec == NULL || pc_spec[0] == '\0') + return; + + char *copy = strdup(pc_spec); + if (copy == NULL) + return; + + char *slash = strchr(copy, '/'); + if (slash != NULL) { + *slash = '\0'; + g_trace_gate_pc = (addr_t) strtoull(copy, NULL, 0); + g_trace_gate_mask = (addr_t) strtoull(slash + 1, NULL, 0); + } else { + g_trace_gate_pc = (addr_t) strtoull(copy, NULL, 0); + if (g_trace_gate_pc <= 0xffffff) + g_trace_gate_mask = 0xffffff; + } + free(copy); + + if (x4_spec != NULL && x4_spec[0] != '\0') { + g_trace_gate_x4 = strtoull(x4_spec, NULL, 0); + g_trace_gate_x4_enabled = true; + } + + if (budget_spec != NULL && budget_spec[0] != '\0') { + long budget = strtol(budget_spec, NULL, 0); + if (budget > 0) + g_trace_gate_budget = (int) budget; + } + + g_trace_gate_enabled = true; + fprintf(stderr, "TRACEGATE enabled pc=%#llx/%#llx", + (unsigned long long) g_trace_gate_pc, + (unsigned long long) g_trace_gate_mask); + if (g_trace_gate_x4_enabled) + fprintf(stderr, " x4=%#llx", (unsigned long long) g_trace_gate_x4); + if (g_trace_gate_budget > 0) + fprintf(stderr, " budget=%d", g_trace_gate_budget); + fputc('\n', stderr); +} + +static bool trace_gate_allow(struct cpu_state *cpu) { + if (!g_trace_gate_enabled) + return true; + + if (t_trace_gate_open && g_trace_gate_budget > 0 && t_trace_gate_left == 0) + t_trace_gate_open = false; + + if (!t_trace_gate_open) { + if ((cpu->pc & g_trace_gate_mask) != (g_trace_gate_pc & g_trace_gate_mask)) + return false; + if (g_trace_gate_x4_enabled && cpu->x4 != g_trace_gate_x4) + return false; + + t_trace_gate_open = true; + t_trace_gate_left = g_trace_gate_budget; + fprintf(stderr, "TRACEGATE open pc=%#llx x4=%#llx\n", + (unsigned long long) cpu->pc, + (unsigned long long) cpu->x4); + } + + if (g_trace_gate_budget > 0 && t_trace_gate_left > 0) + t_trace_gate_left--; + + return true; +} + +static bool trace_read_u64(struct cpu_state *cpu, addr_t addr, uint64_t *out) { + struct mem *mem = container_of(cpu->mmu, struct mem, mmu); + void *ptr = mem_ptr(mem, addr, MEM_READ); + if (ptr == NULL) + return false; + memcpy(out, ptr, sizeof(*out)); + return true; +} + +static bool trace_read_u32(struct cpu_state *cpu, addr_t addr, uint32_t *out) { + struct mem *mem = container_of(cpu->mmu, struct mem, mmu); + void *ptr = mem_ptr(mem, addr, MEM_READ); + if (ptr == NULL) + return false; + memcpy(out, ptr, sizeof(*out)); + return true; +} + +static void trace_dump_obj(struct cpu_state *cpu, const char *name, addr_t addr) { + uint64_t q0 = 0, q1 = 0, q2 = 0, q3 = 0; + bool ok0 = trace_read_u64(cpu, addr + 0, &q0); + bool ok1 = trace_read_u64(cpu, addr + 8, &q1); + bool ok2 = trace_read_u64(cpu, addr + 16, &q2); + bool ok3 = trace_read_u64(cpu, addr + 24, &q3); + fprintf(stderr, "TRACEOBJ %s=%#llx +0=%s%#llx +8=%s%#llx +16=%s%#llx +24=%s%#llx\n", + name, + (unsigned long long) addr, + ok0 ? "" : "!", (unsigned long long) q0, + ok1 ? "" : "!", (unsigned long long) q1, + ok2 ? "" : "!", (unsigned long long) q2, + ok3 ? "" : "!", (unsigned long long) q3); +} + +void jit_trace_regs(struct cpu_state *cpu) { + if (!trace_gate_allow(cpu)) + return; + + fprintf(stderr, + "TRACEPC pc=%#llx x0=%#llx x1=%#llx x2=%#llx x3=%#llx x4=%#llx x5=%#llx x19=%#llx x20=%#llx x21=%#llx x22=%#llx x23=%#llx x24=%#llx x25=%#llx x26=%#llx x27=%#llx x30=%#llx\n", + (unsigned long long) cpu->pc, + (unsigned long long) cpu->x0, + (unsigned long long) cpu->x1, + (unsigned long long) cpu->x2, + (unsigned long long) cpu->x3, + (unsigned long long) cpu->x4, + (unsigned long long) cpu->x5, + (unsigned long long) cpu->x19, + (unsigned long long) cpu->x20, + (unsigned long long) cpu->x21, + (unsigned long long) cpu->x22, + (unsigned long long) cpu->x23, + (unsigned long long) cpu->x24, + (unsigned long long) cpu->x25, + (unsigned long long) cpu->x26, + (unsigned long long) cpu->x27, + (unsigned long long) cpu->x30); + + // HotSpot replay triage around libjvm+0x170aec path: dump key objects. + addr_t off = cpu->pc & 0xffffff; + if (off == 0x170aec || off == 0x170b50 || off == 0x170b58 || + off == 0x170b64 || off == 0x170b70 || off == 0x170b74 || + off == 0xe5aaec || off == 0xe5ab50 || off == 0xe5ab58 || + off == 0xe5ab64 || off == 0xe5ab70 || off == 0xe5ab74) { + trace_dump_obj(cpu, "x19", cpu->x19); + trace_dump_obj(cpu, "x20", cpu->x20); + trace_dump_obj(cpu, "x1", cpu->x1); + trace_dump_obj(cpu, "x0", cpu->x0); + } + + // Replay triage around the libjvm+0x80334c crash sequence (absolute low24 + // around 0x4ed2xx/0x4ed3xx for this mmap layout): inspect the x26 object + // and the just-loaded x0 pointer chain. + if (off == 0x24f580 || off == 0x250400 || off == 0x250464 || + off == 0x2504b0 || off == 0x2504fc || off == 0x250550 || + off == 0x250564 || off == 0x25057c || off == 0x4ebad4 || + off == 0x4ed15c || off == 0x4ed220 || off == 0x4ed230 || + off == 0x4ed250 || off == 0x4ed344 || off == 0x4ed348) { + trace_dump_obj(cpu, "x24", cpu->x24); + trace_dump_obj(cpu, "x26", cpu->x26); + trace_dump_obj(cpu, "x0", cpu->x0); + if (off == 0x250400 || off == 0x250464 || off == 0x2504b0 || + off == 0x2504fc || off == 0x250550 || off == 0x250564 || + off == 0x25057c) { + uint32_t idx1 = 0, idx19 = 0, idx20 = 0, idx22 = 0; + bool ok_idx1 = trace_read_u32(cpu, cpu->x1 + 40, &idx1); + bool ok_idx19 = trace_read_u32(cpu, cpu->x19 + 40, &idx19); + bool ok_idx20 = trace_read_u32(cpu, cpu->x20 + 40, &idx20); + bool ok_idx22 = trace_read_u32(cpu, cpu->x22 + 40, &idx22); + fprintf(stderr, + "TRACE566400 pc=%#llx x0=%#llx x1=%#llx(+40=%s%u) x19=%#llx(+40=%s%u) x20=%#llx(+40=%s%u) x22=%#llx(+40=%s%u) x2=%#llx x3=%#llx x4=%#llx\n", + (unsigned long long) cpu->pc, + (unsigned long long) cpu->x0, + (unsigned long long) cpu->x1, ok_idx1 ? "" : "!", ok_idx1 ? idx1 : 0, + (unsigned long long) cpu->x19, ok_idx19 ? "" : "!", ok_idx19 ? idx19 : 0, + (unsigned long long) cpu->x20, ok_idx20 ? "" : "!", ok_idx20 ? idx20 : 0, + (unsigned long long) cpu->x22, ok_idx22 ? "" : "!", ok_idx22 ? idx22 : 0, + (unsigned long long) cpu->x2, + (unsigned long long) cpu->x3, + (unsigned long long) cpu->x4); + trace_dump_obj(cpu, "f566400_x1", cpu->x1); + trace_dump_obj(cpu, "f566400_x19", cpu->x19); + trace_dump_obj(cpu, "f566400_x20", cpu->x20); + trace_dump_obj(cpu, "f566400_x22", cpu->x22); + } + + if (off == 0x24f580) { + uint32_t idx1 = 0, idx3 = 0; + bool ok_idx1 = trace_read_u32(cpu, cpu->x1 + 40, &idx1); + bool ok_idx3 = trace_read_u32(cpu, cpu->x3 + 40, &idx3); + fprintf(stderr, + "TRACE565580 x1=%#llx +40=%s%u x3=%#llx +40=%s%u x4=%#llx\n", + (unsigned long long) cpu->x1, + ok_idx1 ? "" : "!", ok_idx1 ? idx1 : 0, + (unsigned long long) cpu->x3, + ok_idx3 ? "" : "!", ok_idx3 ? idx3 : 0, + (unsigned long long) cpu->x4); + trace_dump_obj(cpu, "f565580_x1", cpu->x1); + trace_dump_obj(cpu, "f565580_x3", cpu->x3); + } + + if (off == 0x4ebad4) { + uint32_t in_idx40 = 0; + bool ok_in_idx40 = trace_read_u32(cpu, cpu->x1 + 40, &in_idx40); + fprintf(stderr, "TRACECALL x1=%#llx +40=%s%u\n", + (unsigned long long) cpu->x1, + ok_in_idx40 ? "" : "!", + ok_in_idx40 ? in_idx40 : 0); + trace_dump_obj(cpu, "call_x1", cpu->x1); + } + + if (off == 0x4ed15c) { + uint32_t idx40 = 0; + bool ok_idx40 = trace_read_u32(cpu, cpu->x0 + 40, &idx40); + fprintf(stderr, "TRACERET x0=%#llx +40=%s%u\n", + (unsigned long long) cpu->x0, + ok_idx40 ? "" : "!", + ok_idx40 ? idx40 : 0); + } + + if (off == 0x4ed220) { + uint64_t t0 = 0, t1 = 0, t2 = 0; + bool ok0 = trace_read_u64(cpu, cpu->x0 + 0, &t0); + bool ok1 = trace_read_u64(cpu, cpu->x0 + 8, &t1); + bool ok2 = trace_read_u64(cpu, cpu->x0 + 16, &t2); + fprintf(stderr, + "TRACEARR x0=%#llx [0]=%s%#llx [1]=%s%#llx [2]=%s%#llx\n", + (unsigned long long) cpu->x0, + ok0 ? "" : "!", (unsigned long long) t0, + ok1 ? "" : "!", (unsigned long long) t1, + ok2 ? "" : "!", (unsigned long long) t2); + if (ok0 && t0 != 0) + trace_dump_obj(cpu, "arr0", (addr_t) t0); + if (ok1 && t1 != 0) + trace_dump_obj(cpu, "arr1", (addr_t) t1); + if (ok2 && t2 != 0) + trace_dump_obj(cpu, "arr2", (addr_t) t2); + } + } + + // Hash-slot replay triage around libjvm+0x34710c..+0x3471ec. + if (off == 0x3110c || off == 0x311e4 || off == 0x311e8 || off == 0x311ec) { + uint64_t slot_key = 0, table_ptr = 0; + uint32_t slot_index = 0; + bool ok_key = trace_read_u64(cpu, cpu->x5 + 928, &slot_key); + bool ok_idx = trace_read_u32(cpu, cpu->x5 + 936, &slot_index); + bool ok_tab = trace_read_u64(cpu, cpu->x0 + 912, &table_ptr); + fprintf(stderr, + "TRACESLOT pc=%#llx x0=%#llx x1=%#llx x5=%#llx slot_key=%s%#llx slot_idx=%s%u table=%s%#llx\n", + (unsigned long long) cpu->pc, + (unsigned long long) cpu->x0, + (unsigned long long) cpu->x1, + (unsigned long long) cpu->x5, + ok_key ? "" : "!", (unsigned long long) slot_key, + ok_idx ? "" : "!", ok_idx ? slot_index : 0, + ok_tab ? "" : "!", (unsigned long long) table_ptr); + if (ok_tab && table_ptr != 0) { + uint64_t e0 = 0, e1 = 0, e2 = 0; + bool ok_e0 = trace_read_u64(cpu, table_ptr + 0, &e0); + bool ok_e1 = trace_read_u64(cpu, table_ptr + 8, &e1); + bool ok_e2 = trace_read_u64(cpu, table_ptr + 16, &e2); + fprintf(stderr, + "TRACESLOT entries base=%#llx [0]=%s%#llx [1]=%s%#llx [2]=%s%#llx\n", + (unsigned long long) table_ptr, + ok_e0 ? "" : "!", (unsigned long long) e0, + ok_e1 ? "" : "!", (unsigned long long) e1, + ok_e2 ? "" : "!", (unsigned long long) e2); + if (ok_e0 && e0 != 0) + trace_dump_obj(cpu, "slot_e0", (addr_t) e0); + if (ok_e1 && e1 != 0) + trace_dump_obj(cpu, "slot_e1", (addr_t) e1); + if (ok_e2 && e2 != 0) + trace_dump_obj(cpu, "slot_e2", (addr_t) e2); + } + } +} +void c_watch_write_hit(addr_t addr, const char *caller) { (void)addr; (void)caller; } +void jit_watch_write_hit(struct cpu_state *cpu, addr_t store_addr, unsigned long *code_ptr) { + (void)cpu; (void)store_addr; (void)code_ptr; +} +void jit_highbit_alert(struct cpu_state *cpu) { + static int reported = 0; + if (reported++) + return; + fprintf(stderr, "HIGHBITS pc=%#llx sp=%#llx\n", + (unsigned long long)cpu->pc, + (unsigned long long)cpu->sp); + for (int i = 0; i < 31; i++) { + if ((cpu->regs[i] >> 32) != 0) { + fprintf(stderr, " x%d=%#llx\n", i, (unsigned long long)cpu->regs[i]); + } + } +} + +static void fiber_block_disconnect(struct asbestos *asbestos, struct fiber_block *block); +static void fiber_block_free(struct asbestos *asbestos, struct fiber_block *block); +static void fiber_free_jetsam(struct asbestos *asbestos); +static void fiber_resize_hash(struct asbestos *asbestos, size_t new_size); +static inline size_t fiber_block_hash(addr_t addr, size_t hash_size); + +struct asbestos *asbestos_new(struct mmu *mmu) { + struct asbestos *asbestos = calloc(1, sizeof(struct asbestos)); + asbestos->mmu = mmu; + fiber_resize_hash(asbestos, FIBER_INITIAL_HASH_SIZE); + asbestos->page_hash = calloc(FIBER_PAGE_HASH_SIZE, sizeof(*asbestos->page_hash)); + list_init(&asbestos->jetsam); + lock_init(&asbestos->lock); + wrlock_init(&asbestos->jetsam_lock); + atomic_init(&asbestos->invalidate_gen, 0); + atomic_init(&asbestos->jit_active_threads, 0); + atomic_init(&asbestos->jetsam_gen, 0); + return asbestos; +} + +void asbestos_free(struct asbestos *asbestos) { + for (size_t i = 0; i < asbestos->hash_size; i++) { + struct fiber_block *block, *tmp; + if (list_null(&asbestos->hash[i])) + continue; + list_for_each_entry_safe(&asbestos->hash[i], block, tmp, chain) { + fiber_block_free(asbestos, block); + } + } + fiber_free_jetsam(asbestos); + free(asbestos->page_hash); + free(asbestos->hash); + free(asbestos); +} + +static inline struct list *blocks_list(struct asbestos *asbestos, page_t page, int i) { + // TODO is this a good hash function? + return &asbestos->page_hash[page % FIBER_PAGE_HASH_SIZE].blocks[i]; +} + +void asbestos_invalidate_range(struct asbestos *absestos, page_t start, page_t end) { + // [T-ish-mm-double-destroy-crash] Under CLONE_VM exit_group races the + // second cleanup path may run pt_unmap_always after asbestos has already + // been freed and nulled (see mem_destroy). Treat as no-op — the freed + // asbestos had already been invalidated by the winning cleanup. + if (absestos == NULL) return; + lock(&absestos->lock); + bool did_invalidate = false; + struct fiber_block *block, *tmp; + for (page_t page = start; page < end; page++) { + for (int i = 0; i <= 1; i++) { + struct list *blocks = blocks_list(absestos, page, i); + if (list_null(blocks)) + continue; + list_for_each_entry_safe(blocks, block, tmp, page[i]) { + fiber_block_disconnect(absestos, block); + block->is_jetsam = true; + list_add(&absestos->jetsam, &block->jetsam); + did_invalidate = true; + } + } + } + if (did_invalidate) + atomic_fetch_add_explicit(&absestos->invalidate_gen, 1, memory_order_release); + unlock(&absestos->lock); +} + +void asbestos_invalidate_page(struct asbestos *asbestos, page_t page) { + // [T-ish-mm-double-destroy-crash] See asbestos_invalidate_range — + // a racing exit_group cleanup can reach this after asbestos was freed. + if (asbestos == NULL) return; + // Fast path: skip lock if no blocks exist on this page. + // page_hash is only modified under asbestos->lock, and list_null is a + // single pointer read, so a racy false-negative just means we take + // the slow path unnecessarily (safe). A false-positive is impossible + // because blocks are always added before being linked into page_hash. + for (int i = 0; i <= 1; i++) { + struct list *blocks = blocks_list(asbestos, page, i); + if (!list_null(blocks)) + goto slow_path; + } + return; +slow_path: + asbestos_invalidate_range(asbestos, page, page + 1); +} +void asbestos_invalidate_all(struct asbestos *asbestos) { + // [T-ish-mm-double-destroy-crash] Safe no-op after cleanup race. + if (asbestos == NULL) return; + lock(&asbestos->lock); + bool did_invalidate = false; + struct fiber_block *block, *tmp; + for (size_t bucket = 0; bucket < FIBER_PAGE_HASH_SIZE; bucket++) { + for (int i = 0; i <= 1; i++) { + struct list *blocks = &asbestos->page_hash[bucket].blocks[i]; + if (list_null(blocks)) + continue; + list_for_each_entry_safe(blocks, block, tmp, page[i]) { + fiber_block_disconnect(asbestos, block); + block->is_jetsam = true; + list_add(&asbestos->jetsam, &block->jetsam); + did_invalidate = true; + } + } + } + if (did_invalidate) + atomic_fetch_add_explicit(&asbestos->invalidate_gen, 1, memory_order_release); + unlock(&asbestos->lock); +} + +static struct fiber_block *fiber_lookup(struct asbestos *asbestos, addr_t addr); +#ifdef GUEST_ARM64 +static void fiber_prechain_same_page(struct asbestos *asbestos, struct fiber_block *block); +#endif + +static void fiber_resize_hash(struct asbestos *asbestos, size_t new_size) { + TRACE_(verbose, "%d resizing hash to %lu, using %lu bytes for gadgets\n", current_pid(), new_size, asbestos->mem_used); + struct list *new_hash = calloc(new_size, sizeof(struct list)); + for (size_t i = 0; i < asbestos->hash_size; i++) { + if (list_null(&asbestos->hash[i])) + continue; + struct fiber_block *block, *tmp; + list_for_each_entry_safe(&asbestos->hash[i], block, tmp, chain) { + list_remove(&block->chain); + list_init_add(&new_hash[fiber_block_hash(block->addr, new_size)], &block->chain); + } + } + free(asbestos->hash); + asbestos->hash = new_hash; + asbestos->hash_size = new_size; +} + +static void fiber_insert(struct asbestos *asbestos, struct fiber_block *block) { + asbestos->mem_used += block->used; + asbestos->num_blocks++; + // target an average hash chain length of 1-2 + if (asbestos->num_blocks >= asbestos->hash_size * 2) + fiber_resize_hash(asbestos, asbestos->hash_size * 2); + + list_init_add(&asbestos->hash[fiber_block_hash(block->addr, asbestos->hash_size)], &block->chain); + list_init_add(blocks_list(asbestos, PAGE(block->addr), 0), &block->page[0]); + if (PAGE(block->addr) != PAGE(block->end_addr)) + list_init_add(blocks_list(asbestos, PAGE(block->end_addr), 1), &block->page[1]); +#ifdef GUEST_ARM64 + if (arm64_eager_prechain_enabled) + fiber_prechain_same_page(asbestos, block); +#endif +} + +static struct fiber_block *fiber_lookup(struct asbestos *asbestos, addr_t addr) { + struct list *bucket = &asbestos->hash[fiber_block_hash(addr, asbestos->hash_size)]; + if (list_null(bucket)) + return NULL; + struct fiber_block *block; + list_for_each_entry(bucket, block, chain) { + if (block->addr == addr) + return block; + } + return NULL; +} + +#ifdef GUEST_ARM64 +#define ARM64_FAKE_IP_MASK UINT64_C(0x0000ffffffffffff) +#define ARM64_FAKE_IP_TAG (UINT64_C(1) << 63) +#define ARM64_EAGER_PRECHAIN_INCOMING_SCAN_LIMIT 2 + +static bool arm64_fake_jump_target(unsigned long jump_ip, addr_t *target_addr) { + if ((jump_ip & ARM64_FAKE_IP_TAG) == 0) + return false; + *target_addr = (addr_t)(jump_ip & ARM64_FAKE_IP_MASK); + return true; +} + +static bool fiber_prechain_patch_slot(struct fiber_block *source, int i, struct fiber_block *target) { + if (source->jump_ip[i] == NULL || !source->jump_ip_is_fake[i] || + source->is_jetsam || target->is_jetsam) + return false; + addr_t target_addr; + if (!arm64_fake_jump_target(*source->jump_ip[i], &target_addr)) + return false; + if (target_addr != target->addr || PAGE(source->addr) != PAGE(target->addr)) + return false; + *source->jump_ip[i] = (unsigned long) target->code; + source->jump_ip_is_fake[i] = false; + list_add(&target->jumps_from[i], &source->jumps_from_links[i]); + return true; +} + +static void fiber_prechain_outgoing_same_page(struct asbestos *asbestos, struct fiber_block *block) { + // Patch newly inserted same-page outgoing edges to already-compiled + // whole-block starts. This deliberately writes only block->code pointers + // into existing jump_ip slots; it does not create interior targets. + for (int i = 0; i <= 1; i++) { + if (block->jump_ip[i] == NULL) + continue; + addr_t target_addr; + if (!arm64_fake_jump_target(*block->jump_ip[i], &target_addr)) + continue; + if (PAGE(block->addr) != PAGE(target_addr)) + continue; + ARM64_BLOCK_STAT_INC(arm64_block_stats_prechain_attempts); + ARM64_BLOCK_STAT_INC(arm64_block_stats_prechain_outgoing_attempts); + struct fiber_block *target = fiber_lookup(asbestos, target_addr); + if (target == NULL) + continue; + if (fiber_prechain_patch_slot(block, i, target)) { + ARM64_BLOCK_STAT_INC(arm64_block_stats_prechain_patches); + ARM64_BLOCK_STAT_INC(arm64_block_stats_prechain_outgoing_patches); + } + } +} + +static void fiber_prechain_incoming_same_page(struct asbestos *asbestos, struct fiber_block *block) { + // Patch existing same-page source blocks that were compiled before this + // target. Keep the scan bounded to avoid O(blocks-per-page^2) compile-time + // behavior on dense code pages; the newest blocks are at the list head and + // are the most likely direct predecessors. Only still-fake slots are + // considered, so each source link is owned by at most one target list. + // Unlike outgoing prechain, this mutates older blocks that another guest + // thread may already be executing. Keep the opt-in path single-threaded. + if (__atomic_load_n(&asbestos->active_threads, __ATOMIC_RELAXED) > 1) + return; + struct list *sources = blocks_list(asbestos, PAGE(block->addr), 0); + if (list_null(sources)) + return; + struct fiber_block *source; + unsigned scanned = 0; + list_for_each_entry(sources, source, page[0]) { + if (source == block) + continue; + if (scanned++ >= ARM64_EAGER_PRECHAIN_INCOMING_SCAN_LIMIT) + break; + for (int i = 0; i <= 1; i++) { + if (source->jump_ip[i] == NULL) + continue; + addr_t target_addr; + if (!arm64_fake_jump_target(*source->jump_ip[i], &target_addr)) + continue; + if (target_addr != block->addr) + continue; + ARM64_BLOCK_STAT_INC(arm64_block_stats_prechain_attempts); + ARM64_BLOCK_STAT_INC(arm64_block_stats_prechain_incoming_attempts); + if (fiber_prechain_patch_slot(source, i, block)) { + ARM64_BLOCK_STAT_INC(arm64_block_stats_prechain_patches); + ARM64_BLOCK_STAT_INC(arm64_block_stats_prechain_incoming_patches); + } + } + } +} + +static void fiber_prechain_same_page(struct asbestos *asbestos, struct fiber_block *block) { + fiber_prechain_outgoing_same_page(asbestos, block); + if (arm64_eager_prechain_incoming_enabled) + fiber_prechain_incoming_same_page(asbestos, block); +} +#endif + +static struct fiber_block *fiber_block_compile(addr_t ip, struct tlb *tlb) { + struct gen_state state; + TRACE("%d %08x --- compiling:\n", current_pid(), ip); + gen_start(ip, &state); + while (true) { + if (!gen_step(&state, tlb)) + break; + // no block should span more than 2 pages + // guarantee this by limiting total block size to 1 page + // TODO refuse to decode implausibly long gadget streams +#ifdef GUEST_ARM64 + if (state.internal_continue_segment_budget != 0 && + state.ip - state.internal_continue_segment_start >= + state.internal_continue_segment_budget * 4) { + gen_exit(&state); + break; + } +#endif + if (state.ip - ip >= PAGE_SIZE - 15) { + gen_exit(&state); + break; + } + } + gen_end(&state); + assert(state.ip - ip <= PAGE_SIZE); +#ifdef GUEST_ARM64 + ARM64_BLOCK_STAT_INC(arm64_block_stats_compiled); + ARM64_BLOCK_STAT_ADD(arm64_block_stats_code_words, state.size); + ARM64_BLOCK_STAT_ADD(arm64_block_stats_guest_bytes, state.ip - ip); + if (state.jump_ip[0] != 0) + ARM64_BLOCK_STAT_INC(arm64_block_stats_jump0); + if (state.jump_ip[1] != 0) + ARM64_BLOCK_STAT_INC(arm64_block_stats_jump1); +#endif + state.block->used = state.capacity; + return state.block; +} + +// Remove all pointers to the block. It can't be freed yet because another +// thread may be executing it. +static void fiber_block_disconnect(struct asbestos *asbestos, struct fiber_block *block) { + if (asbestos != NULL) { + asbestos->mem_used -= block->used; + asbestos->num_blocks--; + } + list_remove(&block->chain); + for (int i = 0; i <= 1; i++) { + list_remove_safe(&block->page[i]); + if (!list_null(&block->jumps_from_links[i])) { + if (block->jump_ip[i] != NULL) { + *block->jump_ip[i] = block->old_jump_ip[i]; +#ifdef GUEST_ARM64 + block->jump_ip_is_fake[i] = true; +#endif + } + list_remove(&block->jumps_from_links[i]); + } + + struct fiber_block *prev_block, *tmp; + list_for_each_entry_safe(&block->jumps_from[i], prev_block, tmp, jumps_from_links[i]) { + if (prev_block->jump_ip[i] != NULL) { + *prev_block->jump_ip[i] = prev_block->old_jump_ip[i]; +#ifdef GUEST_ARM64 + prev_block->jump_ip_is_fake[i] = true; +#endif + } + list_remove(&prev_block->jumps_from_links[i]); + } + } +} + +static void fiber_block_free(struct asbestos *asbestos, struct fiber_block *block) { + fiber_block_disconnect(asbestos, block); + free(block); +} + +static void fiber_free_jetsam(struct asbestos *asbestos) { + struct fiber_block *block, *tmp; + list_for_each_entry_safe(&asbestos->jetsam, block, tmp, jetsam) { + list_remove(&block->jetsam); + free(block); + } +} + +int fiber_enter(struct fiber_block *block, struct fiber_frame *frame, struct tlb *tlb); +static int cpu_single_step(struct cpu_state *cpu, struct tlb *tlb); + +static inline size_t fiber_cache_hash(addr_t ip) { + return (ip ^ (ip >> 12)) & (FIBER_CACHE_SIZE - 1); +} + +static inline unsigned asbestos_invalidate_gen_load(struct asbestos *asbestos) { + return atomic_load_explicit(&asbestos->invalidate_gen, memory_order_acquire); +} + +static int cpu_step_to_interrupt(struct cpu_state *cpu, struct tlb *tlb) { + struct asbestos *asbestos = cpu->mmu->asbestos; + + // Hold jetsam_lock read during JIT execution. + // This prevents jetsam cleanup from freeing blocks while we're executing them. + read_wrlock(&asbestos->jetsam_lock); + + // Use persistent block cache and frame from TLB; invalidate when blocks are jetsam'd. + unsigned invalidate_gen = asbestos_invalidate_gen_load(asbestos); + bool caches_stale = (tlb->block_cache_gen != invalidate_gen); + struct fiber_block **cache = tlb->block_cache; + if (caches_stale) { + memset(cache, 0, sizeof(tlb->block_cache)); + tlb->block_cache_gen = invalidate_gen; + } + + // Use persistent frame from TLB (avoids malloc/free + ret_cache zeroing) + struct fiber_frame *frame = tlb->frame; + if (frame == NULL) { + frame = calloc(1, sizeof(struct fiber_frame)); + tlb->frame = frame; + } else if (caches_stale) { + // ret_cache holds pointers into block->code; must clear on invalidation + memset(frame->ret_cache, 0, sizeof(frame->ret_cache)); + } + frame->last_block = NULL; + frame->cpu = *cpu; + assert(asbestos->mmu == cpu->mmu); + + int interrupt = INT_NONE; + int crash_retry_count = 0; + while (interrupt == INT_NONE) { + // Check if blocks were invalidated since last check (e.g. CoW by another thread). + // This must be inside the loop, not just at function entry, because invalidation + // can happen while we're in the JIT cycle (between fiber_enter calls). + invalidate_gen = asbestos_invalidate_gen_load(asbestos); + if (tlb->block_cache_gen != invalidate_gen) { + memset(cache, 0, sizeof(tlb->block_cache)); + tlb->block_cache_gen = invalidate_gen; + memset(frame->ret_cache, 0, sizeof(frame->ret_cache)); + // Any last_block pointer may now refer to a jetsam'd/stale fiber. + // Drop it whenever invalidate_gen changes, just like other cache + // invalidation paths below. + frame->last_block = NULL; + } + + addr_t ip = CPU_IP(&frame->cpu); + // Guard: null guest PC means corrupted state (e.g., branch to unmapped + // address 0). Return INT_GPF instead of trying to compile/execute. + if (ip == 0) { + frame->cpu.segfault_addr = 0; + interrupt = INT_GPF; + break; + } + + // Optional tracepoint at block entry. This complements per-instruction + // trace gadgets and helps when a targeted PC only appears as a block + // entry (or when the matching instruction exits the block). + if (asbestos_should_trace_guest_pc(ip)) + jit_trace_regs(&frame->cpu); + size_t cache_index = fiber_cache_hash(ip); + struct fiber_block *block = cache[cache_index]; + ARM64_BLOCK_STAT_INC(arm64_block_stats_entries); + if (block == NULL || block->addr != ip) { + ARM64_BLOCK_STAT_INC(arm64_block_stats_cache_misses); + lock(&asbestos->lock); + block = fiber_lookup(asbestos, ip); + if (block == NULL) { + block = fiber_block_compile(ip, tlb); + fiber_insert(asbestos, block); + } else { + TRACE("%d %08x --- missed cache\n", current_pid(), ip); + } + cache[cache_index] = block; + unlock(&asbestos->lock); + } else { + ARM64_BLOCK_STAT_INC(arm64_block_stats_cache_hits); + } + struct fiber_block *last_block = frame->last_block; + if (last_block != NULL && + !last_block->is_jetsam && !block->is_jetsam && +#ifdef GUEST_ARM64 + (last_block->jump_ip_is_fake[0] || + last_block->jump_ip_is_fake[1]) +#else + (last_block->jump_ip[0] != NULL || + last_block->jump_ip[1] != NULL) +#endif + ) { + ARM64_BLOCK_STAT_INC(arm64_block_stats_chain_attempts); + if (trylock(&asbestos->lock) == 0) { + // can't mint new pointers to a block that has been marked jetsam + // and is thus assumed to have no pointers left + if (!last_block->is_jetsam && !block->is_jetsam) { + for (int i = 0; i <= 1; i++) { + if (last_block->jump_ip[i] == NULL) + continue; +#ifdef GUEST_ARM64 + if (!last_block->jump_ip_is_fake[i]) + continue; + addr_t target_addr; + if (!arm64_fake_jump_target(*last_block->jump_ip[i], &target_addr) || + target_addr != block->addr) + continue; +#else + if ((*last_block->jump_ip[i] & 0xffffffff) != block->addr) + continue; +#endif + *last_block->jump_ip[i] = (unsigned long) block->code; +#ifdef GUEST_ARM64 + last_block->jump_ip_is_fake[i] = false; +#endif + ARM64_BLOCK_STAT_INC(arm64_block_stats_chain_patches); + if (i == 0) + ARM64_BLOCK_STAT_INC(arm64_block_stats_chain_patch_slot0); + else + ARM64_BLOCK_STAT_INC(arm64_block_stats_chain_patch_slot1); + if (PAGE(last_block->addr) == PAGE(block->addr)) + ARM64_BLOCK_STAT_INC(arm64_block_stats_chain_patch_same_page); + else + ARM64_BLOCK_STAT_INC(arm64_block_stats_chain_patch_cross_page); + list_add(&block->jumps_from[i], &last_block->jumps_from_links[i]); + } + } + unlock(&asbestos->lock); + } + } + frame->last_block = block; + + // block may be jetsam, but that's ok, because it can't be freed until + // every thread on this asbestos is not executing anything + + TRACE("%d %08x --- cycle %ld\n", current_pid(), ip, frame->cpu.cycle); + + // Save a fallback block-start PC for crash recovery. Memory gadgets + // update frame->jit_saved_pc to the precise faultable instruction so + // host SIGSEGV/SIGBUS recovery does not re-run earlier side effects. + jit_saved_pc = frame->cpu.pc; + frame->jit_saved_pc = frame->cpu.pc; + + in_jit = 1; + interrupt = fiber_enter(block, frame, tlb); + in_jit = 0; + + // Check if fiber_enter returned due to a JIT crash (signal handler + // redirected PC to jit_crash_trampoline which returns INT_JIT_CRASH). + // The signal handler already set cpu->segfault_addr, cpu->pc, etc. + if (interrupt == INT_JIT_CRASH) { + // Flush all caches to get fresh host pointers. + tlb_flush(tlb); + memset(cache, 0, sizeof(tlb->block_cache)); + tlb->block_cache_gen = asbestos_invalidate_gen_load(asbestos); + memset(frame->ret_cache, 0, sizeof(frame->ret_cache)); + frame->last_block = NULL; + + crash_retry_count++; + if (crash_retry_count >= 16) { + // Too many consecutive crashes — escalate to INT_GPF for handle_interrupt + interrupt = INT_GPF; + crash_retry_count = 0; + } else { + // Retry: convert to INT_NONE so the loop continues + interrupt = INT_NONE; + } + } else { + crash_retry_count = 0; + } + + // Guest writes may modify code (HotSpot inline-cache/nmethod patching, + // JITs, trampolines). Drop compiled blocks for the last written page at + // block boundaries so later execution sees freshly translated bytes. + // tlb->dirty_page is page-aligned (not PAGE()-shifted). + if (tlb->dirty_page != TLB_PAGE_EMPTY) { + asbestos_invalidate_page(asbestos, PAGE(tlb->dirty_page)); + tlb->dirty_page = TLB_PAGE_EMPTY; + } + + // (debug trace removed) + + // Check if page table changed (mmap/munmap by another thread) EVERY BLOCK. + if (tlb->mem_changes != __atomic_load_n(&tlb->mmu->changes, __ATOMIC_ACQUIRE)) { + tlb_flush(tlb); + memset(cache, 0, sizeof(tlb->block_cache)); + tlb->block_cache_gen = asbestos_invalidate_gen_load(asbestos); + memset(frame->ret_cache, 0, sizeof(frame->ret_cache)); + frame->last_block = NULL; + } + + // Most block boundaries have no pending poke. Avoid an exclusive + // read/modify/write in that case; the exchange still consumes a real + // poke with acquire ordering. A poke arriving after a false load stays + // set for the next boundary, just as one arriving after the exchange. + if (interrupt == INT_NONE && + __atomic_load_n(frame->cpu.poked_ptr, __ATOMIC_RELAXED) && + __atomic_exchange_n(frame->cpu.poked_ptr, false, __ATOMIC_ACQUIRE)) + interrupt = INT_TIMER; + if (interrupt == INT_NONE && (++frame->cpu.cycle & ((1 << 10) - 1)) == 0) + interrupt = INT_TIMER; + } + // _poked is owned by the live poked_ptr channel. Do not restore the stale + // snapshot captured when this fiber frame was entered. + bool live_poked = cpu->_poked; + *cpu = frame->cpu; + cpu->_poked = live_poked; + + // Release jetsam_lock read. Jetsam cleanup can now proceed. + read_wrunlock(&asbestos->jetsam_lock); + + return interrupt; +} + +static int cpu_single_step(struct cpu_state *cpu, struct tlb *tlb) { + struct gen_state state; + gen_start(CPU_IP(cpu), &state); + gen_step(&state, tlb); + gen_exit(&state); + gen_end(&state); + + struct fiber_block *block = state.block; + struct fiber_frame frame = {.cpu = *cpu}; + int interrupt = fiber_enter(block, &frame, tlb); + bool live_poked = cpu->_poked; + *cpu = frame.cpu; + cpu->_poked = live_poked; + fiber_block_free(NULL, block); + if (interrupt == INT_NONE) + interrupt = INT_DEBUG; + return interrupt; +} + +int cpu_run_to_interrupt(struct cpu_state *cpu, struct tlb *tlb) { + ish_thread_marker = 1; + if (cpu->poked_ptr == NULL) + cpu->poked_ptr = &cpu->_poked; +#ifdef GUEST_ARM64 + // NOTE: Do NOT invalidate exclusive monitor here. + // This function is called once, but the inner loop (cpu_step_to_interrupt) + // calls fiber_enter repeatedly. The LDXR/STXR pair may span multiple + // fiber_enter calls (unchained blocks). Invalidating here would break + // LDXR/STXR atomicity across block boundaries. + // The exclusive monitor is invalidated by STXR itself (success or fail) + // and by context switches / signal delivery. +#endif + struct asbestos *asbestos = cpu->mmu->asbestos; + __atomic_add_fetch(&asbestos->active_threads, 1, __ATOMIC_RELAXED); + tlb_refresh(tlb, cpu->mmu); + int interrupt = (CPU_HAS_SINGLE_STEP ? cpu_single_step : cpu_step_to_interrupt)(cpu, tlb); + cpu->trapno = interrupt; + __atomic_sub_fetch(&asbestos->active_threads, 1, __ATOMIC_RELAXED); + + lock(&asbestos->lock); + if (!list_empty(&asbestos->jetsam)) { + unlock(&asbestos->lock); + + // This runs while task_run_current still holds mem->lock for reading. + // Do not block here: a concurrent page-fault handler may be queued for + // mem->lock write, which makes new/read re-entry block on glibc's + // writer-preferred rwlock and can deadlock with JIT fault retry. + if (write_wrtrylock(&asbestos->jetsam_lock)) { + lock(&asbestos->lock); + fiber_free_jetsam(asbestos); + unlock(&asbestos->lock); + write_wrunlock(&asbestos->jetsam_lock); + } + } else { + unlock(&asbestos->lock); + } + + return interrupt; +} + +void cpu_poke(struct cpu_state *cpu) { + __atomic_store_n(cpu->poked_ptr, true, __ATOMIC_SEQ_CST); +} + +static inline size_t fiber_block_hash(addr_t addr, size_t hash_size) { +#ifdef GUEST_ARM64 + // Instruction alignment otherwise leaves three quarters of buckets unused. + addr >>= 2; +#endif + return addr % hash_size; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/asbestos.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/asbestos.h new file mode 100644 index 0000000000..2af8463721 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/asbestos.h @@ -0,0 +1,108 @@ +#ifndef ASBESTOS_H +#define ASBESTOS_H +#include "misc.h" +#include "emu/mmu.h" +#include "util/list.h" +#include "util/sync.h" + +#define FIBER_INITIAL_HASH_SIZE (1 << 10) +#define FIBER_CACHE_SIZE (1 << 12) // 4096 entries +#define FIBER_PAGE_HASH_SIZE (1 << 16) + +struct asbestos { + // there is one asbestos per address space + struct mmu *mmu; + size_t mem_used; + size_t num_blocks; + + struct list *hash; + size_t hash_size; + + // list of fiber_blocks that should be freed soon (at the next RCU grace + // period, if we had such a thing) + struct list jetsam; + + // A way to look up blocks in a page + struct { + struct list blocks[2]; + } *page_hash; + + // Incremented on every block invalidation; used to invalidate persistent + // per-thread block caches (which may hold pointers to jetsam'd blocks). + // Atomic because readers check it without asbestos->lock in the hot JIT path. + _Atomic unsigned invalidate_gen; + + // Number of threads currently inside cpu_run_to_interrupt. + // When 1, we can skip jetsam_lock (no other thread to synchronize with). + unsigned active_threads; + + // === RCU-like Optimization === + // Atomic counter: number of threads currently executing JIT code. + // Jetsam cleanup waits until this reaches 0 before freeing blocks. + // This avoids read lock overhead on every JIT enter/exit. + _Atomic unsigned jit_active_threads; + + // Generation number for jetsam cleanup. Incremented when jetsam list + // becomes non-empty. Threads check this to know when cleanup is needed. + _Atomic unsigned jetsam_gen; + + lock_t lock; + wrlock_t jetsam_lock; +}; + +// this is roughly the average number of instructions in a basic block according to anonymous sources +// times 4, roughly the average number of gadgets/parameters in an instruction, according to anonymous sources +#define FIBER_BLOCK_INITIAL_CAPACITY 16 + +struct fiber_block { + addr_t addr; + addr_t end_addr; + size_t used; + + // pointers to the ip values in the last gadget + unsigned long *jump_ip[2]; + // original values of *jump_ip[] + unsigned long old_jump_ip[2]; +#ifdef GUEST_ARM64 + // True while jump_ip[i] still contains an ARM64 fake IP. Once patched to a + // whole-block code pointer, the C dispatcher can skip lock-heavy chaining + // attempts for that slot. + bool jump_ip_is_fake[2]; +#endif + // blocks that jump to this block + struct list jumps_from[2]; + + // hashtable bucket links + struct list chain; + // list of blocks in a page + struct list page[2]; + // links for jumps_from + struct list jumps_from_links[2]; + // links for free list + struct list jetsam; + bool is_jetsam; + + unsigned long code[]; +}; + +// High-bit tracing: detect emulation bugs that leave bits 32+ dirty in guest regs +extern volatile bool g_trace_highbits; + +// Optional per-guest-PC trace hooks (used for targeted replay debugging). +extern volatile bool g_trace_guest_pc; +void asbestos_set_trace_pcs(const char *spec); +void asbestos_set_trace_gate(const char *pc_spec, const char *x4_spec, const char *budget_spec); +bool asbestos_should_trace_guest_pc(addr_t pc); + +// Create a new asbestos +struct asbestos *asbestos_new(struct mmu *mmu); +void asbestos_free(struct asbestos *asbestos); + +// Invalidate all fiber blocks in pages start (inclusive) to end (exclusive). +// Locks the asbestos. Should only be called by memory.c in conjunction with +// mem_changed. +void asbestos_invalidate_range(struct asbestos *asbestos, page_t start, page_t end); +void asbestos_invalidate_page(struct asbestos *asbestos, page_t page); +void asbestos_invalidate_all(struct asbestos *asbestos); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/frame.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/frame.h new file mode 100644 index 0000000000..08c3de99e3 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/frame.h @@ -0,0 +1,17 @@ +#include <stdatomic.h> +#include "emu/cpu.h" + +// keep in sync with asm +#define FIBER_RETURN_CACHE_SIZE 4096 +#define FIBER_RETURN_CACHE_HASH(x) ((x) & 0xFFF0) >> 4) + +struct fiber_frame { + struct cpu_state cpu; + void *bp; + addr_t value_addr; + uint64_t value[4]; // buffer for crosspage crap (must hold up to 32 bytes) + struct fiber_block *last_block; + uint64_t jit_exit_sp; // host sp value that fiber_exit expects (set by fiber_enter) + addr_t jit_saved_pc; // precise guest PC to retry after an async JIT host fault + long ret_cache[FIBER_RETURN_CACHE_SIZE]; // a map of ip to pointer-to-call-gadget-arguments +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/gadgets-generic.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/gadgets-generic.h new file mode 100644 index 0000000000..11b52a18ec --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/gadgets-generic.h @@ -0,0 +1,93 @@ +#include "cpu-offsets.h" + +#define ifin(thing, ...) _ifin(thing, __COUNTER__, __VA_ARGS__) +#define _ifin(thing, line, ...) __ifin(thing, line, __VA_ARGS__) +#define __ifin(thing, line, ...) irp da_op##line, __VA_ARGS__ N .ifc thing,\da_op##line +#define endifin endif N .endr + +# sync with enum reg +#define REG_LIST reg_a,reg_c,reg_d,reg_b,reg_sp,reg_bp,reg_si,reg_di +# sync with enum arg +#define GADGET_LIST REG_LIST,imm,mem,addr,gs +# sync with enum size +#define SIZE_LIST 8,16,32 + +# darwin/linux compatibility +.macro .pushsection_rodata +#if __APPLE__ + .pushsection __DATA,__const +#else + .pushsection .data.rel.ro +#endif +.endm +.macro .pushsection_bullshit +#if __APPLE__ + .pushsection __TEXT,__text_bullshit,regular,pure_instructions +#else + .pushsection .text.bullshit +#endif +.endm + +#if __APPLE__ +#define NAME(x) _##x +#else +#define NAME(x) x +#endif +.macro .global.name name + .global NAME(\name) + NAME(\name)\(): +.endm + +.macro .type_compat type:vararg +#if !__APPLE__ + .type \type +#endif +.endm + +# an array of gadgets +.macro _gadget_array_start name + .pushsection_rodata + .type_compat \name\()_gadgets,@object + .global.name \name\()_gadgets +.endm + +.macro gadgets type, list:vararg + .irp arg, \list + .ifndef NAME(gadget_\type\()_\arg) + .set NAME(gadget_\type\()_\arg), 0 + .endif + .quad NAME(gadget_\type\()_\arg) + .endr +.endm + +.macro .gadget_list type, list:vararg + _gadget_array_start \type + gadgets \type, \list + .popsection +.endm + +.macro .gadget_list_size type, list:vararg + _gadget_array_start \type + # sync with enum size + gadgets \type\()8, \list + gadgets \type\()16, \list + gadgets \type\()32, \list + gadgets \type\()64, \list + gadgets \type\()80, \list + .popsection +.endm + +.macro .gadget_array type + .gadget_list_size \type, GADGET_LIST +.endm + +# jfc +# https://github.com/llvm-mirror/llvm/blob/release_80/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp#L41 +# https://bugs.llvm.org/show_bug.cgi?id=39010#c4 +#if defined(__APPLE__) && defined(__arm64__) +#define N %% +#else +#define N ; +#endif + +# vim: ft=gas diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/gen.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/gen.h new file mode 100644 index 0000000000..dffbe0e3cd --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/gen.h @@ -0,0 +1,42 @@ +#ifndef EMU_GEN_H +#define EMU_GEN_H + +#include <stdint.h> + +#include "asbestos/asbestos.h" +#include "emu/tlb.h" + +#define GEN_INTERNAL_CONTINUE_MAX 6 +#define GEN_INTERNAL_CONTINUE_BUDGET_INSNS 2 + +struct gen_state { + addr_t ip; + addr_t orig_ip; + unsigned long orig_ip_extra; + struct fiber_block *block; + unsigned size; + unsigned capacity; + unsigned jump_ip[2]; + unsigned block_patch_ip; // for call/call_indir gadgets + // Dormant true-superblock scaffold: internal continue operands store code + // offsets while state->block is reallocatable, then gen_end patches them + // to final absolute code-stream pointers. These are not normal jump_ip + // slots and must never be consumed by fiber_ret_chain/block chaining. + unsigned internal_continue_count; + unsigned internal_continue_patch_ip[GEN_INTERNAL_CONTINUE_MAX]; + unsigned internal_continue_target_ip[GEN_INTERNAL_CONTINUE_MAX]; + unsigned internal_continue_used; + addr_t internal_continue_segment_start; + unsigned internal_continue_segment_budget; + uint32_t last_insn; + struct tlb *tlb; // for peephole optimization (peek at next instruction) + unsigned b_follow_depth; // how many unconditional B's we've followed inline +}; + +void gen_start(addr_t addr, struct gen_state *state); +void gen_exit(struct gen_state *state); +void gen_end(struct gen_state *state); + +int gen_step(struct gen_state *state, struct tlb *tlb); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/crypto_helpers.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/crypto_helpers.c new file mode 100644 index 0000000000..6e1cd5c4ed --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/crypto_helpers.c @@ -0,0 +1,1295 @@ +/* + * ARM64 Cryptographic Extension Helper Functions + * + * These are software implementations of the ARMv8 crypto instructions. + * They're called from the gadgets in crypto.S. + */ + +#include <stdint.h> +#include <string.h> +#include <stdio.h> + +/* AES S-box */ +static const uint8_t aes_sbox[256] = { + 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, + 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, + 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, + 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, + 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, + 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, + 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, + 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, + 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, + 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, + 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, + 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, + 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, + 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, + 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, + 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 +}; + +/* AES inverse S-box */ +static const uint8_t aes_inv_sbox[256] = { + 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, + 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, + 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, + 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, + 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, + 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, + 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, + 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, + 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, + 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, + 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, + 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, + 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, + 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, + 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, + 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d +}; + +/* SM4 S-box */ +static const uint8_t sm4_sbox[256] = { + 0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05, + 0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99, + 0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62, + 0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6, + 0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8, + 0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35, + 0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87, + 0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e, + 0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1, + 0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3, + 0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f, + 0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51, + 0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8, + 0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0, + 0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84, + 0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48 +}; + +/* + * AES ShiftRows transformation + * Row 0: no shift + * Row 1: shift left by 1 + * Row 2: shift left by 2 + * Row 3: shift left by 3 + */ +static void aes_shiftrows(uint8_t *state) { + uint8_t tmp; + + // Row 1: shift left by 1 + tmp = state[1]; + state[1] = state[5]; + state[5] = state[9]; + state[9] = state[13]; + state[13] = tmp; + + // Row 2: shift left by 2 + tmp = state[2]; + state[2] = state[10]; + state[10] = tmp; + tmp = state[6]; + state[6] = state[14]; + state[14] = tmp; + + // Row 3: shift left by 3 (= right by 1) + tmp = state[15]; + state[15] = state[11]; + state[11] = state[7]; + state[7] = state[3]; + state[3] = tmp; +} + +/* + * AES Inverse ShiftRows transformation + */ +static void aes_inv_shiftrows(uint8_t *state) { + uint8_t tmp; + + // Row 1: shift right by 1 + tmp = state[13]; + state[13] = state[9]; + state[9] = state[5]; + state[5] = state[1]; + state[1] = tmp; + + // Row 2: shift right by 2 + tmp = state[2]; + state[2] = state[10]; + state[10] = tmp; + tmp = state[6]; + state[6] = state[14]; + state[14] = tmp; + + // Row 3: shift right by 3 (= left by 1) + tmp = state[3]; + state[3] = state[7]; + state[7] = state[11]; + state[11] = state[15]; + state[15] = tmp; +} + +/* Galois field multiplication */ +static uint8_t gmul(uint8_t a, uint8_t b) { + uint8_t p = 0; + for (int i = 0; i < 8; i++) { + if (b & 1) + p ^= a; + int hi_bit = a & 0x80; + a <<= 1; + if (hi_bit) + a ^= 0x1b; // x^8 + x^4 + x^3 + x + 1 + b >>= 1; + } + return p; +} + +/* + * AESE: ShiftRows + SubBytes + * Called from gadget after XOR with round key + * + * ARM specification order (from QEMU and ARM pseudocode): + * 1. AddRoundKey (done in gadget before calling this) + * 2. ShiftRows + * 3. SubBytes + */ +void aes_subbytes_shiftrows(uint8_t *state) { + // ShiftRows FIRST (per ARM specification) + aes_shiftrows(state); + // SubBytes SECOND + for (int i = 0; i < 16; i++) { + state[i] = aes_sbox[state[i]]; + } +} + +/* + * AESD: InvShiftRows + InvSubBytes + * Called from gadget after XOR with round key + * + * ARM specification order (from QEMU and ARM pseudocode): + * 1. AddRoundKey (done in gadget before calling this) + * 2. InvShiftRows + * 3. InvSubBytes + */ +void aes_inv_subbytes_shiftrows(uint8_t *state) { + // InvShiftRows FIRST (per ARM specification) + aes_inv_shiftrows(state); + // InvSubBytes SECOND + for (int i = 0; i < 16; i++) { + state[i] = aes_inv_sbox[state[i]]; + } +} + +/* + * AESMC: MixColumns + */ +void aes_mixcolumns(uint8_t *state) { + for (int c = 0; c < 4; c++) { + uint8_t *col = &state[c * 4]; + uint8_t a0 = col[0], a1 = col[1], a2 = col[2], a3 = col[3]; + + col[0] = gmul(a0, 2) ^ gmul(a1, 3) ^ a2 ^ a3; + col[1] = a0 ^ gmul(a1, 2) ^ gmul(a2, 3) ^ a3; + col[2] = a0 ^ a1 ^ gmul(a2, 2) ^ gmul(a3, 3); + col[3] = gmul(a0, 3) ^ a1 ^ a2 ^ gmul(a3, 2); + } +} + +/* + * AESIMC: Inverse MixColumns + */ +void aes_inv_mixcolumns(uint8_t *state) { + for (int c = 0; c < 4; c++) { + uint8_t *col = &state[c * 4]; + uint8_t a0 = col[0], a1 = col[1], a2 = col[2], a3 = col[3]; + + col[0] = gmul(a0, 0x0e) ^ gmul(a1, 0x0b) ^ gmul(a2, 0x0d) ^ gmul(a3, 0x09); + col[1] = gmul(a0, 0x09) ^ gmul(a1, 0x0e) ^ gmul(a2, 0x0b) ^ gmul(a3, 0x0d); + col[2] = gmul(a0, 0x0d) ^ gmul(a1, 0x09) ^ gmul(a2, 0x0e) ^ gmul(a3, 0x0b); + col[3] = gmul(a0, 0x0b) ^ gmul(a1, 0x0d) ^ gmul(a2, 0x09) ^ gmul(a3, 0x0e); + } +} + +/* + * SHA-1 helper functions + */ + +static inline uint32_t rotl32(uint32_t x, int n) { + return (x << n) | (x >> (32 - n)); +} + +static inline uint64_t ror64(uint64_t x, unsigned n) { + n &= 63; + if (n == 0) + return x; + return (x >> n) | (x << (64 - n)); +} + +static inline uint32_t rol32(uint32_t x, unsigned n) { + return (x << n) | (x >> (32 - n)); +} + +/* SHA1 Choose function: (B & C) | (~B & D) */ +static uint32_t sha1_choose(uint32_t b, uint32_t c, uint32_t d) { + return (b & c) | (~b & d); +} + +/* SHA1 Parity function: B ^ C ^ D */ +static uint32_t sha1_parity(uint32_t b, uint32_t c, uint32_t d) { + return b ^ c ^ d; +} + +/* SHA1 Majority function: (B & C) | (B & D) | (C & D) */ +static uint32_t sha1_majority(uint32_t b, uint32_t c, uint32_t d) { + return (b & c) | (b & d) | (c & d); +} + +/* + * SHA1C: SHA1 hash update with Choose function + * Qd = SHA1 update using Choose + * Sn = hash value (e rotated) + * Vm.4S = working variables and message schedule + */ +void sha1c_helper(uint32_t *qd, uint32_t sn, uint32_t *vm) { + // ARM layout: qd[0]=a (bits 31:0), qd[1]=b (bits 63:32), qd[2]=c (bits 95:64), qd[3]=d (bits 127:96) + // Note: vm[] contains W[i]+K already combined, K is NOT added here + uint32_t a = qd[0], b = qd[1], c = qd[2], d = qd[3]; + uint32_t e = sn; + + for (int i = 0; i < 4; i++) { + uint32_t f = sha1_choose(b, c, d); + uint32_t t = rotl32(a, 5) + f + e + vm[i]; // vm[i] = W[i] + K[i] + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; + } + + qd[0] = a; + qd[1] = b; + qd[2] = c; + qd[3] = d; +} + +/* + * SHA1M: SHA1 hash update with Majority function + */ +void sha1m_helper(uint32_t *qd, uint32_t sn, uint32_t *vm) { + // ARM layout: qd[0]=a (bits 31:0), qd[1]=b (bits 63:32), qd[2]=c (bits 95:64), qd[3]=d (bits 127:96) + // Note: vm[] contains W[i]+K already combined, K is NOT added here + uint32_t a = qd[0], b = qd[1], c = qd[2], d = qd[3]; + uint32_t e = sn; + + for (int i = 0; i < 4; i++) { + uint32_t f = sha1_majority(b, c, d); + uint32_t t = rotl32(a, 5) + f + e + vm[i]; // vm[i] = W[i] + K[i] + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; + } + + qd[0] = a; + qd[1] = b; + qd[2] = c; + qd[3] = d; +} + +/* + * SHA1P: SHA1 hash update with Parity function + */ +void sha1p_helper(uint32_t *qd, uint32_t sn, uint32_t *vm) { + // ARM layout: qd[0]=a (bits 31:0), qd[1]=b (bits 63:32), qd[2]=c (bits 95:64), qd[3]=d (bits 127:96) + // Note: vm[] contains W[i]+K already combined, K is NOT added here + uint32_t a = qd[0], b = qd[1], c = qd[2], d = qd[3]; + uint32_t e = sn; + + for (int i = 0; i < 4; i++) { + uint32_t f = sha1_parity(b, c, d); + uint32_t t = rotl32(a, 5) + f + e + vm[i]; // vm[i] = W[i] + K[i] + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; + } + + qd[0] = a; + qd[1] = b; + qd[2] = c; + qd[3] = d; +} + +/* + * SHA1SU0: SHA1 schedule update 0 + * result = (Vn[1]:Vn[0]:Vd[3]:Vd[2]) XOR Vd XOR Vm + * Where the rearranged value has: + * bits 127:96 = Vn[1], bits 95:64 = Vn[0], bits 63:32 = Vd[3], bits 31:0 = Vd[2] + */ +void sha1su0_helper(uint32_t *vd, uint32_t *vn, uint32_t *vm) { + uint32_t r0 = vd[2] ^ vd[0] ^ vm[0]; + uint32_t r1 = vd[3] ^ vd[1] ^ vm[1]; + uint32_t r2 = vn[0] ^ vd[2] ^ vm[2]; + uint32_t r3 = vn[1] ^ vd[3] ^ vm[3]; + + vd[0] = r0; + vd[1] = r1; + vd[2] = r2; + vd[3] = r3; +} + +/* + * SHA1SU1: SHA1 schedule update 1 + * T = Vd XOR (Vn >> 32) + * Result[i] = ROL(T[i], 1), except Result[3] also XORed with ROL(T[0], 2) + */ +void sha1su1_helper(uint32_t *vd, uint32_t *vn) { + // Vn >> 32 gives us: [0, vn[3], vn[2], vn[1]] in lanes [3,2,1,0] + uint32_t t0 = vd[0] ^ vn[1]; // d0 XOR n1 + uint32_t t1 = vd[1] ^ vn[2]; // d1 XOR n2 + uint32_t t2 = vd[2] ^ vn[3]; // d2 XOR n3 + uint32_t t3 = vd[3]; // d3 XOR 0 + + vd[0] = rotl32(t0, 1); + vd[1] = rotl32(t1, 1); + vd[2] = rotl32(t2, 1); + // T[3] rotated by 1, then XORed with T[0] rotated by 1+2=3 + vd[3] = rotl32(t3, 1) ^ rotl32(t0, 3); +} + +/* + * SHA-256 helper functions + */ + +static inline uint32_t rotr32(uint32_t x, int n) { + return (x >> n) | (x << (32 - n)); +} + +/* SHA256 Sigma0 */ +static uint32_t sha256_sigma0(uint32_t x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); +} + +/* SHA256 Sigma1 */ +static uint32_t sha256_sigma1(uint32_t x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); +} + +/* SHA256 sigma0 (message schedule) */ +static uint32_t sha256_sig0(uint32_t x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >> 3); +} + +/* SHA256 sigma1 (message schedule) */ +static uint32_t sha256_sig1(uint32_t x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >> 10); +} + +/* SHA256 Choose: (E & F) ^ (~E & G) */ +static uint32_t sha256_ch(uint32_t e, uint32_t f, uint32_t g) { + return (e & f) ^ (~e & g); +} + +/* SHA256 Majority: (A & B) ^ (A & C) ^ (B & C) */ +static uint32_t sha256_maj(uint32_t a, uint32_t b, uint32_t c) { + return (a & b) ^ (a & c) ^ (b & c); +} + +/* + * SHA256H: SHA256 hash update (part 1) + */ +void sha256h_helper(uint32_t *qd, uint32_t *qn, uint32_t *vm) { + // ARM layout: lane 0 = bits 31:0, lane 3 = bits 127:96 + // qd[0..3] maps to lanes 0..3 = a,b,c,d + // qn[0..3] maps to lanes 0..3 = e,f,g,h + // vm contains 4 words of (W[i] + K[i]) + + uint32_t a = qd[0], b = qd[1], c = qd[2], d = qd[3]; + uint32_t e = qn[0], f = qn[1], g = qn[2], h = qn[3]; + + for (int i = 0; i < 4; i++) { + uint32_t t1 = h + sha256_sigma1(e) + sha256_ch(e, f, g) + vm[i]; + uint32_t t2 = sha256_sigma0(a) + sha256_maj(a, b, c); + h = g; + g = f; + f = e; + e = d + t1; + d = c; + c = b; + b = a; + a = t1 + t2; + } + + qd[0] = a; + qd[1] = b; + qd[2] = c; + qd[3] = d; +} + +/* + * SHA256H2: SHA256 hash update (part 2) + */ +void sha256h2_helper(uint32_t *qd, uint32_t *qn, uint32_t *vm) { + // Similar to SHA256H but updates the other half (e,f,g,h) + // ARM layout: qn holds (a,b,c,d), qd holds (e,f,g,h) + uint32_t a = qn[0], b = qn[1], c = qn[2], d = qn[3]; + uint32_t e = qd[0], f = qd[1], g = qd[2], h = qd[3]; + + for (int i = 0; i < 4; i++) { + uint32_t t1 = h + sha256_sigma1(e) + sha256_ch(e, f, g) + vm[i]; + uint32_t t2 = sha256_sigma0(a) + sha256_maj(a, b, c); + h = g; + g = f; + f = e; + e = d + t1; + d = c; + c = b; + b = a; + a = t1 + t2; + } + + qd[0] = e; + qd[1] = f; + qd[2] = g; + qd[3] = h; +} + +/* + * SHA256SU0: SHA256 schedule update 0 + * Vd[i] = Vd[i] + sigma0(Vd[i+1]) (with wrap around) + */ +void sha256su0_helper(uint32_t *vd, uint32_t *vn) { + uint32_t t[4]; + t[0] = vd[0] + sha256_sig0(vd[1]); + t[1] = vd[1] + sha256_sig0(vd[2]); + t[2] = vd[2] + sha256_sig0(vd[3]); + t[3] = vd[3] + sha256_sig0(vn[0]); + + vd[0] = t[0]; + vd[1] = t[1]; + vd[2] = t[2]; + vd[3] = t[3]; +} + +/* + * SHA256SU1: SHA256 schedule update 1 + * Vd[i] = Vd[i] + sigma1(Vm[i-2]) + Vn[i-7] (with appropriate indexing) + */ +void sha256su1_helper(uint32_t *vd, uint32_t *vn, uint32_t *vm) { + vd[0] = vd[0] + sha256_sig1(vm[2]) + vn[1]; + vd[1] = vd[1] + sha256_sig1(vm[3]) + vn[2]; + vd[2] = vd[2] + sha256_sig1(vd[0]) + vn[3]; + vd[3] = vd[3] + sha256_sig1(vd[1]) + vm[0]; +} + +/* + * SHA512SU0: SHA-512 schedule update 0 + * Vd[0] = Vd[0] + s0(Vd[1]) + * Vd[1] = Vd[1] + s0(Vn[0]) + */ +static inline uint64_t sha512_s0(uint64_t x) { + return ror64(x, 1) ^ ror64(x, 8) ^ (x >> 7); +} + +void sha512su0_helper(uint64_t *vd, uint64_t *vn) { + uint64_t d0 = vd[0]; + uint64_t d1 = vd[1]; + uint64_t n0 = vn[0]; + vd[0] = d0 + sha512_s0(d1); + vd[1] = d1 + sha512_s0(n0); +} + +/* + * SHA512SU1: SHA-512 schedule update 1 + * Vd[0] = Vd[0] + s1(Vn[0]) + Vm[0] + * Vd[1] = Vd[1] + s1(Vn[1]) + Vm[1] + */ +static inline uint64_t sha512_s1(uint64_t x) { + return ror64(x, 19) ^ ror64(x, 61) ^ (x >> 6); +} + +void sha512su1_helper(uint64_t *vd, uint64_t *vn, uint64_t *vm) { + uint64_t d0 = vd[0]; + uint64_t d1 = vd[1]; + vd[0] = d0 + sha512_s1(vn[0]) + vm[0]; + vd[1] = d1 + sha512_s1(vn[1]) + vm[1]; +} + +/* + * SHA512H: SHA-512 hash update (part 1) + * Qd = Qd + Sum1(Qn[1]) + Ch(Qn[1], Vm[0], Vm[1]) + Qn[0] + * + * Where: + * - Sum1(x) = ROR(x,14) XOR ROR(x,18) XOR ROR(x,41) + * - Ch(x,y,z) = (x AND y) XOR (NOT x AND z) + */ +static inline uint64_t sha512_sum1(uint64_t x) { + return ror64(x, 14) ^ ror64(x, 18) ^ ror64(x, 41); +} + +static inline uint64_t sha512_ch(uint64_t x, uint64_t y, uint64_t z) { + return (x & y) ^ (~x & z); +} + +void sha512h_helper(uint64_t *vd, uint64_t *vn, uint64_t *vm) { + // SHA512H performs two SHA-512 hash rounds + // x = Vn (in ARM terminology: x<127:64>=Vn[1], x<63:0>=Vn[0]) + // y = Vm (y<127:64>=Vm[1], y<63:0>=Vm[0]) + // w = Vd (w<127:64>=Vd[1], w<63:0>=Vd[0]) + + uint64_t x0 = vn[0]; // x<63:0> + uint64_t x1 = vn[1]; // x<127:64> + uint64_t y0 = vm[0]; // y<63:0> + uint64_t y1 = vm[1]; // y<127:64> + uint64_t w0 = vd[0]; // w<63:0> + uint64_t w1 = vd[1]; // w<127:64> + + // First round: + // MSigma1 = Sum1(y<127:64>) = Sum1(y1) + // Vtmp<127:64> = Ch(y1, x0, x1) + MSigma1 + w<127:64> + // tmp = Vtmp<127:64> + y<63:0> + uint64_t msigma1 = sha512_sum1(y1); + uint64_t vtmp1 = sha512_ch(y1, x0, x1) + msigma1 + w1; + uint64_t tmp = vtmp1 + y0; + + // Second round: + // MSigma1 = Sum1(tmp) + // Vtmp<63:0> = Ch(tmp, y1, x0) + MSigma1 + w<63:0> + msigma1 = sha512_sum1(tmp); + uint64_t vtmp0 = sha512_ch(tmp, y1, x0) + msigma1 + w0; + + vd[0] = vtmp0; + vd[1] = vtmp1; +} + +/* + * SHA512H2: SHA-512 hash update (part 2) + * Qd = Qd + Sum0(Vm[1]) + Maj(Vm[1], Vn[0], Vn[1]) + * + * Where: + * - Sum0(x) = ROR(x,28) XOR ROR(x,34) XOR ROR(x,39) + * - Maj(x,y,z) = (x AND y) XOR (x AND z) XOR (y AND z) + */ +static inline uint64_t sha512_sum0(uint64_t x) { + return ror64(x, 28) ^ ror64(x, 34) ^ ror64(x, 39); +} + +static inline uint64_t sha512_maj(uint64_t x, uint64_t y, uint64_t z) { + return (x & y) ^ (x & z) ^ (y & z); +} + +void sha512h2_helper(uint64_t *vd, uint64_t *vn, uint64_t *vm) { + // SHA512H2 performs two SHA-512 hash rounds + // x = Vn (x<127:64>=Vn[1], x<63:0>=Vn[0]) + // y = Vm (y<127:64>=Vm[1], y<63:0>=Vm[0]) + // w = Vd (w<127:64>=Vd[1], w<63:0>=Vd[0]) + + uint64_t x0 = vn[0]; // x<63:0> + uint64_t y0 = vm[0]; // y<63:0> + uint64_t y1 = vm[1]; // y<127:64> + uint64_t w0 = vd[0]; // w<63:0> + uint64_t w1 = vd[1]; // w<127:64> + + // First round (produces Vtmp<127:64>): + // NSigma0 = Sum0(y<63:0>) = Sum0(y0) + // Vtmp<127:64> = Maj(x0, y1, y0) + NSigma0 + w1 + uint64_t nsigma0 = sha512_sum0(y0); + uint64_t vtmp1 = sha512_maj(x0, y1, y0) + nsigma0 + w1; + + // Second round (produces Vtmp<63:0>): + // NSigma0 = Sum0(Vtmp<127:64>) = Sum0(vtmp1) + // Vtmp<63:0> = Maj(vtmp1, y0, y1) + NSigma0 + w0 + nsigma0 = sha512_sum0(vtmp1); + uint64_t vtmp0 = sha512_maj(vtmp1, y0, y1) + nsigma0 + w0; + + vd[0] = vtmp0; + vd[1] = vtmp1; +} + +/* + * EOR3: bitwise XOR of three vectors + * Vd = Vn ^ Vm ^ Va + */ +void eor3_helper(uint8_t *vd, uint8_t *vn, uint8_t *vm, uint8_t *va) { + for (int i = 0; i < 16; i++) { + vd[i] = vn[i] ^ vm[i] ^ va[i]; + } +} + +/* + * SM3PARTW1: SM3 message schedule update (part 1) + */ +void sm3partw1_helper(uint32_t *vd, uint32_t *vn, uint32_t *vm) { + uint32_t t0 = vd[0] ^ vn[0]; + uint32_t t1 = vd[1] ^ vn[1]; + uint32_t t2 = vd[2] ^ vn[2]; + uint32_t t3 = vd[3] ^ vn[3]; + + uint32_t r0 = t0 ^ rol32(vm[1], 15); + uint32_t r1 = t1 ^ rol32(vm[2], 15); + uint32_t r2 = t2 ^ rol32(vm[3], 15); + uint32_t r3 = t3 ^ rol32(r0, 15); + + r0 = r0 ^ rol32(r0, 15) ^ rol32(r0, 23); + r1 = r1 ^ rol32(r1, 15) ^ rol32(r1, 23); + r2 = r2 ^ rol32(r2, 15) ^ rol32(r2, 23); + r3 = r3 ^ rol32(r3, 15) ^ rol32(r3, 23); + + vd[0] = r0; + vd[1] = r1; + vd[2] = r2; + vd[3] = r3; +} + +static inline uint32_t sm4_sbox_sub(uint32_t x) { + uint32_t y = 0; + y |= (uint32_t)sm4_sbox[x & 0xff]; + y |= (uint32_t)sm4_sbox[(x >> 8) & 0xff] << 8; + y |= (uint32_t)sm4_sbox[(x >> 16) & 0xff] << 16; + y |= (uint32_t)sm4_sbox[(x >> 24) & 0xff] << 24; + return y; +} + +/* + * SM4E: SM4 round (4 rounds at once on vector lanes) + */ +void sm4e_helper(uint32_t *vd, uint32_t *vn) { + uint32_t r0 = vd[0]; + uint32_t r1 = vd[1]; + uint32_t r2 = vd[2]; + uint32_t r3 = vd[3]; + + for (int i = 0; i < 4; i++) { + uint32_t rk = vn[i]; + uint32_t x = r1 ^ r2 ^ r3 ^ rk; + x = sm4_sbox_sub(x); + x = x ^ rol32(x, 2) ^ rol32(x, 10) ^ rol32(x, 18) ^ rol32(x, 24); + x ^= r0; + r0 = r1; + r1 = r2; + r2 = r3; + r3 = x; + } + + vd[0] = r0; + vd[1] = r1; + vd[2] = r2; + vd[3] = r3; +} + +/* + * SVE helpers (modeled as 128-bit vectors) + */ +void sve_eor_d_helper(uint64_t *vd, uint64_t *vn, uint64_t *vm) { + vd[0] = vn[0] ^ vm[0]; + vd[1] = vn[1] ^ vm[1]; +} + +void sve_xar_d_helper(uint64_t *vd, uint64_t *vn, uint64_t *vm, uint32_t imm) { + // XAR: Vd = ROR(Vn XOR Vm, imm) - XOR first, then rotate + unsigned n = imm & 63; + vd[0] = ror64(vn[0] ^ vm[0], n); + vd[1] = ror64(vn[1] ^ vm[1], n); +} + +/* + * PMULL: Polynomial Multiply Long + * Performs carry-less multiplication (used in GCM mode of AES) + * + * For size=0 (8-bit elements): multiplies 8 pairs of bytes + * For size=3 (64-bit elements): multiplies one pair of 64-bit values + */ +static __uint128_t pmull64_full(uint64_t a, uint64_t b) { + __uint128_t result = 0; + for (int i = 0; i < 64; i++) { + if (b & (1ULL << i)) { + result ^= ((__uint128_t)a) << i; + } + } + return result; +} + +void pmull_helper(uint8_t *rd, uint8_t *rn, uint8_t *rm, uint32_t Q, uint32_t size) { + if (size == 0) { + // 8-bit polynomial multiply: 8 pairs of bytes -> 8 halfwords + uint16_t *dst = (uint16_t *)rd; + uint8_t *src_n = Q ? &rn[8] : rn; + uint8_t *src_m = Q ? &rm[8] : rm; + + for (int i = 0; i < 8; i++) { + uint16_t a = src_n[i]; + uint16_t b = src_m[i]; + uint16_t result = 0; + for (int j = 0; j < 8; j++) { + if (b & (1 << j)) { + result ^= a << j; + } + } + dst[i] = result; + } + } else if (size == 3) { + // 64-bit polynomial multiply: 1 pair of 64-bit -> 128-bit + uint64_t *src_n = (uint64_t *)rn; + uint64_t *src_m = (uint64_t *)rm; + __uint128_t *dst = (__uint128_t *)rd; + + uint64_t a = Q ? src_n[1] : src_n[0]; + uint64_t b = Q ? src_m[1] : src_m[0]; + + *dst = pmull64_full(a, b); + } +} + +/* + * TBL - Table lookup + * + * Each byte of the index vector (rm) is used as an index into the table + * formed by concatenating 1-4 consecutive vector registers starting at rn. + * If the index is out of range, 0 is written to the destination. + * + * len: 0=1 register (16 bytes), 1=2 regs (32 bytes), 2=3 regs (48 bytes), 3=4 regs (64 bytes) + * Q: 0=8-byte operation, 1=16-byte operation + */ +void tbl_helper(uint8_t *rd, uint8_t *rn, uint8_t *rm, int len, int Q, uint8_t *fp_base) { + int num_elements = Q ? 16 : 8; + int table_size = (len + 1) * 16; // 16, 32, 48, or 64 bytes + + uint8_t result[16]; + + for (int i = 0; i < num_elements; i++) { + uint8_t index = rm[i]; + if (index < table_size) { + // Calculate which register and offset within that register + int reg_offset = index / 16; + int byte_offset = index % 16; + // Handle register wrap-around (V31 + 1 = V0) + uint8_t *table_reg = rn + (reg_offset * 16); + // Check if we've wrapped around the register file + // fp_base points to V0, so check if we've gone past V31 + if (table_reg >= fp_base + 32 * 16) { + table_reg -= 32 * 16; // Wrap to V0 + } + result[i] = table_reg[byte_offset]; + } else { + result[i] = 0; + } + } + + // Copy result to destination + for (int i = 0; i < num_elements; i++) { + rd[i] = result[i]; + } + // Clear upper bytes if 8-byte operation + if (!Q) { + for (int i = 8; i < 16; i++) { + rd[i] = 0; + } + } +} + +/* + * TBX - Table lookup with extend + * + * Same as TBL, but out-of-range indices preserve the original destination value + * instead of being set to 0. + */ +void tbx_helper(uint8_t *rd, uint8_t *rn, uint8_t *rm, int len, int Q, uint8_t *fp_base) { + int num_elements = Q ? 16 : 8; + int table_size = (len + 1) * 16; + + uint8_t result[16]; + + // Copy original destination first (for TBX, out-of-range keeps original) + for (int i = 0; i < 16; i++) { + result[i] = rd[i]; + } + + for (int i = 0; i < num_elements; i++) { + uint8_t index = rm[i]; + if (index < table_size) { + int reg_offset = index / 16; + int byte_offset = index % 16; + uint8_t *table_reg = rn + (reg_offset * 16); + if (table_reg >= fp_base + 32 * 16) { + table_reg -= 32 * 16; + } + result[i] = table_reg[byte_offset]; + } + // For TBX, if index >= table_size, we keep the original rd[i] + } + + // Copy result to destination + for (int i = 0; i < num_elements; i++) { + rd[i] = result[i]; + } + if (!Q) { + for (int i = 8; i < 16; i++) { + rd[i] = 0; + } + } +} + +/* + * SHL immediate helper for 32-bit and 64-bit element sizes + */ +void shl_imm_helper(uint8_t *rd, uint8_t *rn, int shift, int esize, int Q) { + if (esize == 2) { + // 32-bit elements + uint32_t *src = (uint32_t *)rn; + uint32_t *dst = (uint32_t *)rd; + int count = Q ? 4 : 2; + for (int i = 0; i < count; i++) { + dst[i] = src[i] << shift; + } + if (!Q) { + dst[2] = 0; + dst[3] = 0; + } + } else if (esize == 3) { + // 64-bit elements + uint64_t *src = (uint64_t *)rn; + uint64_t *dst = (uint64_t *)rd; + int count = Q ? 2 : 1; + for (int i = 0; i < count; i++) { + dst[i] = src[i] << shift; + } + if (!Q) { + dst[1] = 0; + } + } +} + +/* + * USHR immediate helper - unsigned shift right + */ +void ushr_imm_helper(uint8_t *rd, uint8_t *rn, int shift, int esize, int Q) { + if (esize == 0) { + // 8-bit elements + int count = Q ? 16 : 8; + for (int i = 0; i < count; i++) { + rd[i] = rn[i] >> shift; + } + if (!Q) { + for (int i = 8; i < 16; i++) rd[i] = 0; + } + } else if (esize == 1) { + // 16-bit elements + uint16_t *src = (uint16_t *)rn; + uint16_t *dst = (uint16_t *)rd; + int count = Q ? 8 : 4; + for (int i = 0; i < count; i++) { + dst[i] = src[i] >> shift; + } + if (!Q) { + for (int i = 4; i < 8; i++) dst[i] = 0; + } + } else if (esize == 2) { + // 32-bit elements + uint32_t *src = (uint32_t *)rn; + uint32_t *dst = (uint32_t *)rd; + int count = Q ? 4 : 2; + for (int i = 0; i < count; i++) { + dst[i] = src[i] >> shift; + } + if (!Q) { + dst[2] = 0; + dst[3] = 0; + } + } else if (esize == 3) { + // 64-bit elements + uint64_t *src = (uint64_t *)rn; + uint64_t *dst = (uint64_t *)rd; + int count = Q ? 2 : 1; + for (int i = 0; i < count; i++) { + dst[i] = src[i] >> shift; + } + if (!Q) { + dst[1] = 0; + } + } +} + +/* + * SSHR immediate helper - signed shift right + */ +void sshr_imm_helper(uint8_t *rd, uint8_t *rn, int shift, int esize, int Q) { + if (esize == 0) { + // 8-bit signed elements + int8_t *src = (int8_t *)rn; + int8_t *dst = (int8_t *)rd; + int count = Q ? 16 : 8; + for (int i = 0; i < count; i++) { + dst[i] = src[i] >> shift; + } + if (!Q) { + for (int i = 8; i < 16; i++) ((uint8_t *)rd)[i] = 0; + } + } else if (esize == 1) { + // 16-bit signed elements + int16_t *src = (int16_t *)rn; + int16_t *dst = (int16_t *)rd; + int count = Q ? 8 : 4; + for (int i = 0; i < count; i++) { + dst[i] = src[i] >> shift; + } + if (!Q) { + for (int i = 4; i < 8; i++) ((uint16_t *)rd)[i] = 0; + } + } else if (esize == 2) { + // 32-bit signed elements + int32_t *src = (int32_t *)rn; + int32_t *dst = (int32_t *)rd; + int count = Q ? 4 : 2; + for (int i = 0; i < count; i++) { + dst[i] = src[i] >> shift; + } + if (!Q) { + ((uint32_t *)rd)[2] = 0; + ((uint32_t *)rd)[3] = 0; + } + } else if (esize == 3) { + // 64-bit signed elements + int64_t *src = (int64_t *)rn; + int64_t *dst = (int64_t *)rd; + int count = Q ? 2 : 1; + for (int i = 0; i < count; i++) { + dst[i] = src[i] >> shift; + } + if (!Q) { + ((uint64_t *)rd)[1] = 0; + } + } +} + +/* + * USRA (vector, immediate) - Unsigned Shift Right and Accumulate + * rd = rd + (rn >> shift) (unsigned) + */ +void usra_imm_helper(uint8_t *rd, uint8_t *rn, int shift, int esize, int Q) { + if (esize == 0) { + // 8-bit elements + int count = Q ? 16 : 8; + for (int i = 0; i < count; i++) { + rd[i] = rd[i] + (rn[i] >> shift); + } + } else if (esize == 1) { + // 16-bit elements + uint16_t *src = (uint16_t *)rn; + uint16_t *dst = (uint16_t *)rd; + int count = Q ? 8 : 4; + for (int i = 0; i < count; i++) { + dst[i] = dst[i] + (src[i] >> shift); + } + } else if (esize == 2) { + // 32-bit elements + uint32_t *src = (uint32_t *)rn; + uint32_t *dst = (uint32_t *)rd; + int count = Q ? 4 : 2; + for (int i = 0; i < count; i++) { + dst[i] = dst[i] + (src[i] >> shift); + } + } else if (esize == 3) { + // 64-bit elements + uint64_t *src = (uint64_t *)rn; + uint64_t *dst = (uint64_t *)rd; + int count = Q ? 2 : 1; + for (int i = 0; i < count; i++) { + dst[i] = dst[i] + (src[i] >> shift); + } + } +} + +/* + * SSRA (vector, immediate) - Signed Shift Right and Accumulate + * rd = rd + (rn >> shift) (signed) + */ +void ssra_imm_helper(uint8_t *rd, uint8_t *rn, int shift, int esize, int Q) { + if (esize == 0) { + // 8-bit signed elements + int8_t *src = (int8_t *)rn; + int8_t *dst = (int8_t *)rd; + int count = Q ? 16 : 8; + for (int i = 0; i < count; i++) { + dst[i] = dst[i] + (src[i] >> shift); + } + } else if (esize == 1) { + // 16-bit signed elements + int16_t *src = (int16_t *)rn; + int16_t *dst = (int16_t *)rd; + int count = Q ? 8 : 4; + for (int i = 0; i < count; i++) { + dst[i] = dst[i] + (src[i] >> shift); + } + } else if (esize == 2) { + // 32-bit signed elements + int32_t *src = (int32_t *)rn; + int32_t *dst = (int32_t *)rd; + int count = Q ? 4 : 2; + for (int i = 0; i < count; i++) { + dst[i] = dst[i] + (src[i] >> shift); + } + } else if (esize == 3) { + // 64-bit signed elements + int64_t *src = (int64_t *)rn; + int64_t *dst = (int64_t *)rd; + int count = Q ? 2 : 1; + for (int i = 0; i < count; i++) { + dst[i] = dst[i] + (src[i] >> shift); + } + } +} + +/* + * USRA (scalar) - Unsigned Shift Right and Accumulate (scalar D register) + */ +void usra_scalar_helper(uint64_t *rd, uint64_t *rn, int shift) { + *rd = *rd + (*rn >> shift); +} + +/* + * SSRA (scalar) - Signed Shift Right and Accumulate (scalar D register) + */ +void ssra_scalar_helper(int64_t *rd, int64_t *rn, int shift) { + *rd = *rd + (*rn >> shift); +} + +/* + * SRI (vector, immediate) - Shift Right and Insert + * For each element: rd = (rd & ~mask) | ((rn >> shift) & mask) + * where mask = (1 << (element_bits - shift)) - 1 + * i.e., the lower (element_bits - shift) bits are inserted from the shifted source + */ +void sri_imm_helper(uint8_t *rd, uint8_t *rn, int shift, int esize, int Q) { + if (esize == 0) { + // 8-bit elements + int count = Q ? 16 : 8; + uint8_t mask = (1 << (8 - shift)) - 1; // Mask for inserted bits + for (int i = 0; i < count; i++) { + uint8_t shifted = rn[i] >> shift; + rd[i] = (rd[i] & ~mask) | (shifted & mask); + } + } else if (esize == 1) { + // 16-bit elements + uint16_t *src = (uint16_t *)rn; + uint16_t *dst = (uint16_t *)rd; + int count = Q ? 8 : 4; + uint16_t mask = (1 << (16 - shift)) - 1; + for (int i = 0; i < count; i++) { + uint16_t shifted = src[i] >> shift; + dst[i] = (dst[i] & ~mask) | (shifted & mask); + } + } else if (esize == 2) { + // 32-bit elements + uint32_t *src = (uint32_t *)rn; + uint32_t *dst = (uint32_t *)rd; + int count = Q ? 4 : 2; + uint32_t mask = (1UL << (32 - shift)) - 1; + for (int i = 0; i < count; i++) { + uint32_t shifted = src[i] >> shift; + dst[i] = (dst[i] & ~mask) | (shifted & mask); + } + } else if (esize == 3) { + // 64-bit elements + uint64_t *src = (uint64_t *)rn; + uint64_t *dst = (uint64_t *)rd; + int count = Q ? 2 : 1; + uint64_t mask = (1ULL << (64 - shift)) - 1; + for (int i = 0; i < count; i++) { + uint64_t shifted = src[i] >> shift; + dst[i] = (dst[i] & ~mask) | (shifted & mask); + } + } +} + +/* + * SLI (vector, immediate) - Shift Left and Insert + * For each element: rd = (rd & ~mask) | ((rn << shift) & mask) + * where mask = ~((1 << shift) - 1) + * i.e., the upper (element_bits - shift) bits are inserted from the shifted source + */ +void sli_imm_helper(uint8_t *rd, uint8_t *rn, int shift, int esize, int Q) { + if (esize == 0) { + // 8-bit elements + int count = Q ? 16 : 8; + uint8_t mask = ~((1 << shift) - 1); // Mask for inserted bits (upper bits) + for (int i = 0; i < count; i++) { + uint8_t shifted = rn[i] << shift; + rd[i] = (rd[i] & ~mask) | (shifted & mask); + } + } else if (esize == 1) { + // 16-bit elements + uint16_t *src = (uint16_t *)rn; + uint16_t *dst = (uint16_t *)rd; + int count = Q ? 8 : 4; + uint16_t mask = ~((1 << shift) - 1); + for (int i = 0; i < count; i++) { + uint16_t shifted = src[i] << shift; + dst[i] = (dst[i] & ~mask) | (shifted & mask); + } + } else if (esize == 2) { + // 32-bit elements + uint32_t *src = (uint32_t *)rn; + uint32_t *dst = (uint32_t *)rd; + int count = Q ? 4 : 2; + uint32_t mask = ~((1UL << shift) - 1); + for (int i = 0; i < count; i++) { + uint32_t shifted = src[i] << shift; + dst[i] = (dst[i] & ~mask) | (shifted & mask); + } + } else if (esize == 3) { + // 64-bit elements + uint64_t *src = (uint64_t *)rn; + uint64_t *dst = (uint64_t *)rd; + int count = Q ? 2 : 1; + uint64_t mask = ~((1ULL << shift) - 1); + for (int i = 0; i < count; i++) { + uint64_t shifted = src[i] << shift; + dst[i] = (dst[i] & ~mask) | (shifted & mask); + } + } +} + +/* + * Permute instruction helpers (UZP1, UZP2, TRN1, TRN2, ZIP1, ZIP2) + * These interleave/deinterleave elements from two source vectors. + * + * size: 0=8-bit, 1=16-bit, 2=32-bit, 3=64-bit elements + * Q: 0=8-byte operation, 1=16-byte operation + */ + +// UZP1: Unzip even elements (deinterleave, selecting elements at even indices) +void uzp1_helper(uint8_t *rd, uint8_t *rn, uint8_t *rm, int size, int Q) { + uint8_t result[16] = {0}; + int esize = 1 << size; // Element size in bytes + int elements = (Q ? 16 : 8) / esize; + + // Take even-indexed elements from Vn and Vm + for (int i = 0; i < elements / 2; i++) { + for (int b = 0; b < esize; b++) { + result[i * esize + b] = rn[(i * 2) * esize + b]; + result[(elements / 2 + i) * esize + b] = rm[(i * 2) * esize + b]; + } + } + + for (int i = 0; i < (Q ? 16 : 8); i++) { + rd[i] = result[i]; + } + if (!Q) { + for (int i = 8; i < 16; i++) rd[i] = 0; + } +} + +// UZP2: Unzip odd elements (deinterleave, selecting elements at odd indices) +void uzp2_helper(uint8_t *rd, uint8_t *rn, uint8_t *rm, int size, int Q) { + uint8_t result[16] = {0}; + int esize = 1 << size; + int elements = (Q ? 16 : 8) / esize; + + // Take odd-indexed elements from Vn and Vm + for (int i = 0; i < elements / 2; i++) { + for (int b = 0; b < esize; b++) { + result[i * esize + b] = rn[(i * 2 + 1) * esize + b]; + result[(elements / 2 + i) * esize + b] = rm[(i * 2 + 1) * esize + b]; + } + } + + for (int i = 0; i < (Q ? 16 : 8); i++) { + rd[i] = result[i]; + } + if (!Q) { + for (int i = 8; i < 16; i++) rd[i] = 0; + } +} + +// TRN1: Transpose even pairs (interleave even-indexed elements) +void trn1_helper(uint8_t *rd, uint8_t *rn, uint8_t *rm, int size, int Q) { + uint8_t result[16] = {0}; + int esize = 1 << size; + int elements = (Q ? 16 : 8) / esize; + + // For each pair, take even element from Vn and even element from Vm + for (int i = 0; i < elements / 2; i++) { + for (int b = 0; b < esize; b++) { + result[(i * 2) * esize + b] = rn[(i * 2) * esize + b]; + result[(i * 2 + 1) * esize + b] = rm[(i * 2) * esize + b]; + } + } + + for (int i = 0; i < (Q ? 16 : 8); i++) { + rd[i] = result[i]; + } + if (!Q) { + for (int i = 8; i < 16; i++) rd[i] = 0; + } +} + +// TRN2: Transpose odd pairs (interleave odd-indexed elements) +void trn2_helper(uint8_t *rd, uint8_t *rn, uint8_t *rm, int size, int Q) { + uint8_t result[16] = {0}; + int esize = 1 << size; + int elements = (Q ? 16 : 8) / esize; + + // For each pair, take odd element from Vn and odd element from Vm + for (int i = 0; i < elements / 2; i++) { + for (int b = 0; b < esize; b++) { + result[(i * 2) * esize + b] = rn[(i * 2 + 1) * esize + b]; + result[(i * 2 + 1) * esize + b] = rm[(i * 2 + 1) * esize + b]; + } + } + + for (int i = 0; i < (Q ? 16 : 8); i++) { + rd[i] = result[i]; + } + if (!Q) { + for (int i = 8; i < 16; i++) rd[i] = 0; + } +} + +// ZIP1: Interleave elements from lower halves +void zip1_helper(uint8_t *rd, uint8_t *rn, uint8_t *rm, int size, int Q) { + uint8_t result[16] = {0}; + int esize = 1 << size; + int elements = (Q ? 16 : 8) / esize; + + // Interleave lower half elements + for (int i = 0; i < elements / 2; i++) { + for (int b = 0; b < esize; b++) { + result[(i * 2) * esize + b] = rn[i * esize + b]; + result[(i * 2 + 1) * esize + b] = rm[i * esize + b]; + } + } + + for (int i = 0; i < (Q ? 16 : 8); i++) { + rd[i] = result[i]; + } + if (!Q) { + for (int i = 8; i < 16; i++) rd[i] = 0; + } +} + +// ZIP2: Interleave elements from upper halves +void zip2_helper(uint8_t *rd, uint8_t *rn, uint8_t *rm, int size, int Q) { + uint8_t result[16] = {0}; + int esize = 1 << size; + int elements = (Q ? 16 : 8) / esize; + int half = elements / 2; + + // Interleave upper half elements + for (int i = 0; i < elements / 2; i++) { + for (int b = 0; b < esize; b++) { + result[(i * 2) * esize + b] = rn[(half + i) * esize + b]; + result[(i * 2 + 1) * esize + b] = rm[(half + i) * esize + b]; + } + } + + for (int i = 0; i < (Q ? 16 : 8); i++) { + rd[i] = result[i]; + } + if (!Q) { + for (int i = 8; i < 16; i++) rd[i] = 0; + } +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/bits.S b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/bits.S new file mode 100644 index 0000000000..fdc8f220a2 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/bits.S @@ -0,0 +1,180 @@ +/* + * ARM64 Guest Bit Manipulation Gadgets + * + * These gadgets implement bit manipulation and shift operations. + */ + +#include "gadgets.h" + +.text + +/* + * Shift operations (64-bit) + */ + +// LSL Xd, Xn, Xm - Logical shift left +.gadget lsl64 + lsl _tmp, _tmp, _tmp2 + gret + +// LSR Xd, Xn, Xm - Logical shift right +.gadget lsr64 + lsr _tmp, _tmp, _tmp2 + gret + +// ASR Xd, Xn, Xm - Arithmetic shift right +.gadget asr64 + asr _tmp, _tmp, _tmp2 + gret + +// ROR Xd, Xn, Xm - Rotate right +.gadget ror64 + ror _tmp, _tmp, _tmp2 + gret + +/* + * Shift operations (32-bit) + */ + +.gadget lsl32 + lsl w0, w0, w8 + mov _tmp, x0 + gret + +.gadget lsr32 + lsr w0, w0, w8 + mov _tmp, x0 + gret + +.gadget asr32 + asr w0, w0, w8 + mov _tmp, x0 + gret + +.gadget ror32 + ror w0, w0, w8 + mov _tmp, x0 + gret + +/* + * Bit field operations + */ + +// BFM Xd, Xn, #immr, #imms - Bitfield move +.gadget bfm64 + // Complex operation, needs immediate encoding + // TODO: Implement properly + gret + +// SBFM Xd, Xn, #immr, #imms - Signed bitfield move +.gadget sbfm64 + gret + +// UBFM Xd, Xn, #immr, #imms - Unsigned bitfield move +.gadget ubfm64 + gret + +// EXTR Xd, Xn, Xm, #lsb - Extract register +.gadget extr64 + // Concatenate Xn:Xm and extract bits + gret + +/* + * Sign/zero extension + */ + +// SXTB Xd, Wn - Sign extend byte +.gadget sxtb64 + sxtb _tmp, w0 + gret + +.gadget sxtb32 + sxtb w0, w0 + mov _tmp, x0 + gret + +// SXTH Xd, Wn - Sign extend halfword +.gadget sxth64 + sxth _tmp, w0 + gret + +.gadget sxth32 + sxth w0, w0 + mov _tmp, x0 + gret + +// SXTW Xd, Wn - Sign extend word +.gadget sxtw + sxtw _tmp, w0 + gret + +// UXTB Xd, Wn - Zero extend byte +.gadget uxtb + uxtb w0, w0 + mov _tmp, x0 + gret + +// UXTH Xd, Wn - Zero extend halfword +.gadget uxth + uxth w0, w0 + mov _tmp, x0 + gret + +/* + * Bit counting operations + */ + +// CLZ Xd, Xn - Count leading zeros +.gadget clz64 + clz _tmp, _tmp + gret + +.gadget clz32 + clz w0, w0 + mov _tmp, x0 + gret + +// CLS Xd, Xn - Count leading sign bits +.gadget cls64 + cls _tmp, _tmp + gret + +.gadget cls32 + cls w0, w0 + mov _tmp, x0 + gret + +// RBIT Xd, Xn - Reverse bits +.gadget rbit64 + rbit _tmp, _tmp + gret + +.gadget rbit32 + rbit w0, w0 + mov _tmp, x0 + gret + +// REV Xd, Xn - Reverse bytes +.gadget rev64 + rev _tmp, _tmp + gret + +.gadget rev32 + rev w0, w0 + mov _tmp, x0 + gret + +// REV16 Xd, Xn - Reverse bytes in halfwords +.gadget rev16_64 + rev16 _tmp, _tmp + gret + +.gadget rev16_32 + rev16 w0, w0 + mov _tmp, x0 + gret + +// REV32 Xd, Xn - Reverse bytes in words (64-bit only) +.gadget rev32_64 + rev32 _tmp, _tmp + gret diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/control.S b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/control.S new file mode 100644 index 0000000000..1f5b5858d7 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/control.S @@ -0,0 +1,1869 @@ +/* + * ARM64 Guest Control Flow Gadgets + * + * These gadgets handle branches, calls, and returns for ARM64 guest code. + * + * Block chaining works by storing a fake_ip (guest PC with bit 63 set) in the + * code stream. When a block is chained, this value is replaced with a pointer + * to the target block's code. The fiber_ret_chain routine checks bit 63 to + * determine whether to continue executing gadgets or return to the main loop. + */ + +#include "gadgets.h" +#include "emu/interrupt.h" + +// External symbols from entry.S +.extern fiber_ret_chain +.extern fiber_ret +.extern fiber_exit + +.text + +/* + * Macro: inline_chain reg + * Inlines the fiber_ret_chain fast path for a chained block pointer in \reg. + * Avoids the overhead of branching to fiber_ret_chain and its redundant tbnz check. + * + * \reg must contain either: + * - A chained block->code pointer (bit 63 clear) + * - A fake_ip (bit 63 set) — handled by branching to unchained label + * + * Uses labels: \@ generates unique labels via local label suffix. + * CPU_pc is set from block->addr (not truncated pointer). + */ +.macro inline_chain reg, unchained_label +#ifdef DISABLE_BLOCK_CHAINING + // Block chaining disabled — always go through main loop + b \unchained_label +#else + tbnz \reg, #63, \unchained_label + // Chained fast path — poke check + periodic timer + ldr x11, [\reg, #(-FIBER_BLOCK_code + FIBER_BLOCK_addr)] + str x11, [_cpu, #CPU_pc] + // Increment cycle counter; exit to main loop every 1024 cycles for timer check + ldr w8, [_cpu, #CPU_cycle] + add w8, w8, #1 + str w8, [_cpu, #CPU_cycle] + tst w8, #0x3ff + b.eq 7778f + // Check poke flag + ldr x8, [_cpu, #CPU_poked_ptr] + ldrb w8, [x8] + cbnz w8, 7778f + sub x8, \reg, #FIBER_BLOCK_code + str x8, [_cpu, #LOCAL_last_block] + mov _pc, \reg + gret +7778: // poke or timer — exit to main loop + mov _pc, \reg + b fiber_ret +#endif +.endm + +/* + * Internal continue for future true-superblock segments. + * Code stream: [gadget addr][guest_pc (64-bit)][internal_code_ptr (64-bit)] + * + * This is deliberately not a normal chained pointer path: the continuation + * pointer is consumed only by this gadget, is never stored in jump_ip, and is + * never passed to fiber_ret_chain. The generator should store an offset while + * the block is reallocatable and patch this operand to a final code pointer in + * gen_end. + */ +.gadget internal_continue + ldr x8, [_pc], #8 // guest PC for observability/timer exits + ldr x9, [_pc] // internal continuation code-stream pointer + str x8, [_cpu, #CPU_pc] + mov _pc, x9 + gret + +/* + * Unconditional branch (B) + * Code stream: [gadget addr][fake_target (64-bit)] + * + * The target is stored as (guest_pc | (1<<63)) initially. + * When chained, it becomes a pointer to the target block's code. + */ +.gadget branch + // Load the target (either fake_ip or block->code pointer) + ldr x9, [_pc] + inline_chain x9, 1f +1: // Unchained: guest PC is low 32 bits of fake_ip + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +/* + * Branch with link (BL) + * Code stream: [gadget addr][block_self_ptr][return_addr][fake_return_cont][fake_target] + * + * _pc layout after gret: + * _pc[0] = block self-pointer (for RET to set last_block) + * _pc[1] = return address (next instruction after BL) + * _pc[2] = return continuation (fake_ip or chained return-site block->code) + * _pc[3] = call target (fake_ip or chained callee block->code) + * + * ret_cache stores _pc so RET can find all fields. + */ +.gadget branch_link + // Load return address from _pc[1] + ldr x8, [_pc, #8] + // Save return address to X30 + str x8, [_cpu, #(CPU_x0 + 30*8)] +#ifndef DISABLE_RET_CACHE + // Store _pc in ret_cache keyed by return address + ubfx w12, w8, #4, #12 + add x13, _cpu, #LOCAL_ret_cache + str _pc, [x13, x12, lsl #3] +#endif + // Load call target from _pc[3] + ldr x9, [_pc, #24] + inline_chain x9, 1f +1: // Unchained: guest PC is low 32 bits of fake_ip + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +/* + * Branch to register (BR) + * Code stream: [gadget addr][rn (64-bit)] + * + * Indirect branch - always returns to main loop since we don't know the target. + */ +.gadget branch_reg + ldr x8, [_pc] // rn + and x8, x8, #0x1f + add x9, _cpu, #CPU_x0 + ldr x10, [x9, x8, lsl #3] + + // Store guest PC (full 48-bit address) + str x10, [_cpu, #CPU_pc] + // Indirect branch: always return to main loop + b fiber_ret + +/* + * Branch to register with link (BLR) + * Code stream: [gadget addr][rn (64-bit)][return addr (64-bit)] + */ +.gadget branch_link_reg + ldr x8, [_pc] // rn + add _pc, _pc, #8 + ldr x11, [_pc] // return address + + and x8, x8, #0x1f + add x9, _cpu, #CPU_x0 + ldr x10, [x9, x8, lsl #3] + + // Save return address to X30 + str x11, [_cpu, #(CPU_x0 + 30*8)] + + // Store guest PC (full 48-bit address) + str x10, [_cpu, #CPU_pc] + // Indirect branch: always return to main loop + b fiber_ret + +/* + * Return (RET) + * Code stream: [gadget addr][rn (64-bit, usually 30)] + * + * Uses return address cache to stay in JIT when possible. + * BL stores _pc in ret_cache, where: + * _pc[0] = block_self_ptr (BL's block, for last_block when unchained) + * _pc[1] = return_addr (for validation) + * _pc[2] = return_cont (return-site block->code or fake_ip) + */ +.gadget ret + ldr x8, [_pc] // rn + and x8, x8, #0x1f + add x9, _cpu, #CPU_x0 + ldr x10, [x9, x8, lsl #3] // x10 = return address (guest PC) + // Always set CPU_pc first (full 48-bit address) + str x10, [_cpu, #CPU_pc] +#ifndef DISABLE_RET_CACHE + // Look up return address in ret_cache + ubfx w12, w10, #4, #12 + add x13, _cpu, #LOCAL_ret_cache + ldr x14, [x13, x12, lsl #3] // x14 = saved _pc from BL + // Cache miss? + cbz x14, ret_no_cache + // Validate: saved return_addr must match actual return address + ldr x9, [x14, #8] // x14[1] = return_addr + cmp x10, x9 + b.ne ret_no_cache + // Cache hit — load return continuation + ldr _pc, [x14, #16] // x14[2] = return_cont (block->code or fake_ip) + // Check if return_cont is chained (bit 63 clear = valid block->code) + tbnz _pc, #63, ret_unchained + // Chained cache hit — continue immediately (no poke check) + // Poke will be caught at the next branch via inline_chain + sub x8, _pc, #FIBER_BLOCK_code + str x8, [_cpu, #LOCAL_last_block] + gret +ret_unchained: + // Return continuation not yet chained — set last_block to BL's block + // so main loop can patch the return_cont on next dispatch + ldr x8, [x14] // x14[0] = block_self_ptr + str x8, [_cpu, #LOCAL_last_block] + b fiber_ret +ret_no_cache: +#endif + b fiber_ret + +/* + * Compare and branch if zero (CBZ) + * Code stream: [gadget addr][rt | sf<<8 (64-bit)][fake_target (64-bit)][fake_fallthrough (64-bit)] + */ +.gadget cbz + ldr x8, [_pc] // rt | sf<<8 + add _pc, _pc, #8 + ldr x9, [_pc] // target (fake_ip or chained) + add _pc, _pc, #8 + ldr x10, [_pc] // fallthrough (fake_ip or chained) + + and x11, x8, #0x1f // rt + ubfx x12, x8, #8, #1 // sf + + // Load register value + add x13, _cpu, #CPU_x0 + cmp x11, #31 + b.eq 1f + ldr x14, [x13, x11, lsl #3] + b 2f +1: mov x14, #0 +2: + // For 32-bit, only check low 32 bits + cbz x12, 3f + b 4f +3: and x14, x14, #0xffffffff +4: + // Check if zero and select target + cbz x14, cbz_taken + // Not zero - use fallthrough (x10) + inline_chain x10, cbz_nt_unchained +cbz_nt_unchained: + and x11, x10, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x10 + b fiber_ret_chain +cbz_taken: + // Zero - use target (x9) + inline_chain x9, cbz_t_unchained +cbz_t_unchained: + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +/* + * Compare and branch if not zero (CBNZ) + * Code stream: [gadget addr][rt | sf<<8 (64-bit)][fake_target (64-bit)][fake_fallthrough (64-bit)] + */ +.gadget cbnz + ldr x8, [_pc] + add _pc, _pc, #8 + ldr x9, [_pc] // target + add _pc, _pc, #8 + ldr x10, [_pc] // fallthrough + + and x11, x8, #0x1f + ubfx x12, x8, #8, #1 + + add x13, _cpu, #CPU_x0 + cmp x11, #31 + b.eq 1f + ldr x14, [x13, x11, lsl #3] + b 2f +1: mov x14, #0 +2: + cbz x12, 3f + b 4f +3: and x14, x14, #0xffffffff +4: + cbnz x14, cbnz_taken + // Zero - use fallthrough (x10) + inline_chain x10, cbnz_nt_unchained +cbnz_nt_unchained: + and x11, x10, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x10 + b fiber_ret_chain +cbnz_taken: + // Not zero - use target (x9) + inline_chain x9, cbnz_t_unchained +cbnz_t_unchained: + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +/* + * Specialized CBZ/CBNZ gadgets (rt!=31, sf known at compile time) + * + * Saves ~8 instructions vs generic by eliminating XZR check and sf check. + * Code stream: [gadget addr][rt (64-bit)][fake_target (64-bit)][fake_fallthrough (64-bit)] + * gen.c emits these when rt!=31, falls back to generic gadget_cbz/gadget_cbnz for rt==31. + */ + +// CBZ Xt, target (64-bit, rt!=31) +.gadget cbz_64 + ldr x8, [_pc] // rt + add _pc, _pc, #8 + ldr x9, [_pc] // target + add _pc, _pc, #8 + ldr x10, [_pc] // fallthrough + add x13, _cpu, #CPU_x0 + ldr x14, [x13, x8, lsl #3] // load 64-bit register value + cbz x14, cbz_64_taken + inline_chain x10, cbz_64_nt_unchained +cbz_64_nt_unchained: + and x11, x10, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x10 + b fiber_ret_chain +cbz_64_taken: + inline_chain x9, cbz_64_t_unchained +cbz_64_t_unchained: + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +// CBZ Wt, target (32-bit, rt!=31) +.gadget cbz_32 + ldr x8, [_pc] + add _pc, _pc, #8 + ldr x9, [_pc] + add _pc, _pc, #8 + ldr x10, [_pc] + add x13, _cpu, #CPU_x0 + ldr x14, [x13, x8, lsl #3] // load 64-bit, check only low 32 + cbz w14, cbz_32_taken // w14 tests only lower 32 bits + inline_chain x10, cbz_32_nt_unchained +cbz_32_nt_unchained: + and x11, x10, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x10 + b fiber_ret_chain +cbz_32_taken: + inline_chain x9, cbz_32_t_unchained +cbz_32_t_unchained: + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +// CBNZ Xt, target (64-bit, rt!=31) +.gadget cbnz_64 + ldr x8, [_pc] + add _pc, _pc, #8 + ldr x9, [_pc] + add _pc, _pc, #8 + ldr x10, [_pc] + add x13, _cpu, #CPU_x0 + ldr x14, [x13, x8, lsl #3] + cbnz x14, cbnz_64_taken + inline_chain x10, cbnz_64_nt_unchained +cbnz_64_nt_unchained: + and x11, x10, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x10 + b fiber_ret_chain +cbnz_64_taken: + inline_chain x9, cbnz_64_t_unchained +cbnz_64_t_unchained: + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +// CBNZ Wt, target (32-bit, rt!=31) +.gadget cbnz_32 + ldr x8, [_pc] + add _pc, _pc, #8 + ldr x9, [_pc] + add _pc, _pc, #8 + ldr x10, [_pc] + add x13, _cpu, #CPU_x0 + ldr x14, [x13, x8, lsl #3] + cbnz w14, cbnz_32_taken + inline_chain x10, cbnz_32_nt_unchained +cbnz_32_nt_unchained: + and x11, x10, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x10 + b fiber_ret_chain +cbnz_32_taken: + inline_chain x9, cbnz_32_t_unchained +cbnz_32_t_unchained: + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +/* + * CBZ/CBNZ with external taken edge and internal fallthrough edge. + * Code stream: [gadget addr][rt | sf<<8 | is_cbnz<<9] + * [fake_target][internal_continue_ptr] + * + * The taken edge uses the normal external fake-IP/block->code chain path. + * The not-taken edge jumps to a private internal-continue record and never + * passes the interior pointer to fiber_ret_chain. + */ +.gadget cbz_fallthrough_internal + ldr x8, [_pc], #8 // rt | sf<<8 | is_cbnz<<9 + ldr x9, [_pc], #8 // taken target (fake_ip or chained) + ldr x10, [_pc] // internal_continue record pointer + + and x11, x8, #0x1f // rt + ubfx x12, x8, #8, #1 // sf + ubfx x13, x8, #9, #1 // is_cbnz + add x14, _cpu, #CPU_x0 + cmp x11, #31 + b.eq cbz_fi_xzr + ldr x15, [x14, x11, lsl #3] + b cbz_fi_test +cbz_fi_xzr: + mov x15, #0 +cbz_fi_test: + cbnz x12, cbz_fi_test64 + cmp w15, #0 + b cbz_fi_select +cbz_fi_test64: + cmp x15, #0 +cbz_fi_select: + cset w16, ne // nonzero = 1, zero = 0 + cmp w16, w13 // CBNZ takes when nonzero; CBZ takes when zero + b.eq cbz_fi_taken +cbz_fi_not_taken: + mov _pc, x10 + gret +cbz_fi_taken: + inline_chain x9, cbz_fi_taken_unchained +cbz_fi_taken_unchained: + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +/* + * CBZ/CBNZ with internal taken edge and external fallthrough edge. + * Code stream: [gadget addr][rt | sf<<8 | is_cbnz<<9] + * [internal_continue_ptr][fake_fallthrough] + * + * The taken edge jumps to a private internal-continue record and never passes + * the interior pointer to fiber_ret_chain. The not-taken edge uses the normal + * external fake-IP/block->code chain path. + */ +.gadget cbz_taken_internal + ldr x8, [_pc], #8 // rt | sf<<8 | is_cbnz<<9 + ldr x9, [_pc], #8 // internal_continue record pointer + ldr x10, [_pc] // fallthrough target (fake_ip or chained) + + and x11, x8, #0x1f // rt + ubfx x12, x8, #8, #1 // sf + ubfx x13, x8, #9, #1 // is_cbnz + add x14, _cpu, #CPU_x0 + cmp x11, #31 + b.eq cbz_ti_xzr + ldr x15, [x14, x11, lsl #3] + b cbz_ti_test +cbz_ti_xzr: + mov x15, #0 +cbz_ti_test: + cbnz x12, cbz_ti_test64 + cmp w15, #0 + b cbz_ti_select +cbz_ti_test64: + cmp x15, #0 +cbz_ti_select: + cset w16, ne // nonzero = 1, zero = 0 + cmp w16, w13 // CBNZ takes when nonzero; CBZ takes when zero + b.eq cbz_ti_taken +cbz_ti_not_taken: + inline_chain x10, cbz_ti_not_taken_unchained +cbz_ti_not_taken_unchained: + and x11, x10, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x10 + b fiber_ret_chain +cbz_ti_taken: + mov _pc, x9 + gret + +/* + * Fused ADD/SUB immediate + CBZ/CBNZ of the result. + * Code stream: [gadget addr][rd | rn<<8 | imm12<<16 | op<<28 | sf<<29 | test_sf<<30] + * [fake_target][fake_fallthrough] + * op=0 ADD, op=1 SUB. sf is the ADD/SUB width; test_sf is the CBZ/CBNZ width. + */ +.gadget fused_addsub_cbz + ldr x8, [_pc] + add _pc, _pc, #8 + ldr x9, [_pc] + add _pc, _pc, #8 + ldr x10, [_pc] + and x12, x8, #0x1f // rd + ubfx x13, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x13, lsl #3] + tbnz x8, #29, fused_addsub_cbz_64 + tbnz x8, #28, fused_addsub_cbz_sub32 + add w16, w15, w11 + b fused_addsub_cbz_store +fused_addsub_cbz_sub32: + sub w16, w15, w11 + b fused_addsub_cbz_store +fused_addsub_cbz_64: + tbnz x8, #28, fused_addsub_cbz_sub64 + add x16, x15, x11 + b fused_addsub_cbz_store +fused_addsub_cbz_sub64: + sub x16, x15, x11 +fused_addsub_cbz_store: + str x16, [x14, x12, lsl #3] + tbnz x8, #30, fused_addsub_cbz_test64 + cbz w16, fused_addsub_cbz_taken + b fused_addsub_cbz_not_taken +fused_addsub_cbz_test64: + cbz x16, fused_addsub_cbz_taken +fused_addsub_cbz_not_taken: + inline_chain x10, fused_addsub_cbz_nt_unchained +fused_addsub_cbz_nt_unchained: + and x11, x10, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x10 + b fiber_ret_chain +fused_addsub_cbz_taken: + inline_chain x9, fused_addsub_cbz_t_unchained +fused_addsub_cbz_t_unchained: + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +.gadget fused_addsub_cbnz + ldr x8, [_pc] + add _pc, _pc, #8 + ldr x9, [_pc] + add _pc, _pc, #8 + ldr x10, [_pc] + and x12, x8, #0x1f + ubfx x13, x8, #8, #5 + ubfx x11, x8, #16, #12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x13, lsl #3] + tbnz x8, #29, fused_addsub_cbnz_64 + tbnz x8, #28, fused_addsub_cbnz_sub32 + add w16, w15, w11 + b fused_addsub_cbnz_store +fused_addsub_cbnz_sub32: + sub w16, w15, w11 + b fused_addsub_cbnz_store +fused_addsub_cbnz_64: + tbnz x8, #28, fused_addsub_cbnz_sub64 + add x16, x15, x11 + b fused_addsub_cbnz_store +fused_addsub_cbnz_sub64: + sub x16, x15, x11 +fused_addsub_cbnz_store: + str x16, [x14, x12, lsl #3] + tbnz x8, #30, fused_addsub_cbnz_test64 + cbnz w16, fused_addsub_cbnz_taken + b fused_addsub_cbnz_not_taken +fused_addsub_cbnz_test64: + cbnz x16, fused_addsub_cbnz_taken +fused_addsub_cbnz_not_taken: + inline_chain x10, fused_addsub_cbnz_nt_unchained +fused_addsub_cbnz_nt_unchained: + and x11, x10, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x10 + b fiber_ret_chain +fused_addsub_cbnz_taken: + inline_chain x9, fused_addsub_cbnz_t_unchained +fused_addsub_cbnz_t_unchained: + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +/* + * Conditional branch (B.cond) + * Code stream: [gadget addr][cond (64-bit)][fake_target (64-bit)][fake_fallthrough (64-bit)] + * + * Condition codes (cond field): + * 0000 (0) EQ - Equal (Z==1) + * 0001 (1) NE - Not equal (Z==0) + * 0010 (2) CS/HS - Carry set / Unsigned higher or same (C==1) + * 0011 (3) CC/LO - Carry clear / Unsigned lower (C==0) + * 0100 (4) MI - Minus / Negative (N==1) + * 0101 (5) PL - Plus / Positive or zero (N==0) + * 0110 (6) VS - Overflow set (V==1) + * 0111 (7) VC - Overflow clear (V==0) + * 1000 (8) HI - Unsigned higher (C==1 && Z==0) + * 1001 (9) LS - Unsigned lower or same (C==0 || Z==1) + * 1010 (10) GE - Signed greater or equal (N==V) + * 1011 (11) LT - Signed less than (N!=V) + * 1100 (12) GT - Signed greater than (Z==0 && N==V) + * 1101 (13) LE - Signed less than or equal (Z==1 || N!=V) + * 1110 (14) AL - Always (unconditional) + * 1111 (15) NV - (reserved, treated as AL) + */ +.gadget bcond + ldr x8, [_pc] // cond + add _pc, _pc, #8 + ldr x9, [_pc] // target (fake_ip or chained) + add _pc, _pc, #8 + ldr x10, [_pc] // fallthrough (fake_ip or chained) + + // Extract condition code BEFORE loading flags + and x8, x8, #0xf + adr x11, bcond_table + add x11, x11, x8, lsl #2 // Each branch is 4 bytes + + // Load NZCV flags from cpu state into host NZCV register + // This must be the LAST thing before the conditional branch + load_flags + + br x11 + + .align 2 +bcond_table: + b bcond_eq // 0: EQ + b bcond_ne // 1: NE + b bcond_cs // 2: CS/HS + b bcond_cc // 3: CC/LO + b bcond_mi // 4: MI + b bcond_pl // 5: PL + b bcond_vs // 6: VS + b bcond_vc // 7: VC + b bcond_hi // 8: HI + b bcond_ls // 9: LS + b bcond_ge // 10: GE + b bcond_lt // 11: LT + b bcond_gt // 12: GT + b bcond_le // 13: LE + b bcond_al // 14: AL + b bcond_al // 15: NV (treat as AL) + +bcond_eq: + b.eq bcond_taken + b bcond_not_taken +bcond_ne: + b.ne bcond_taken + b bcond_not_taken +bcond_cs: + b.cs bcond_taken + b bcond_not_taken +bcond_cc: + b.cc bcond_taken + b bcond_not_taken +bcond_mi: + b.mi bcond_taken + b bcond_not_taken +bcond_pl: + b.pl bcond_taken + b bcond_not_taken +bcond_vs: + b.vs bcond_taken + b bcond_not_taken +bcond_vc: + b.vc bcond_taken + b bcond_not_taken +bcond_hi: + b.hi bcond_taken + b bcond_not_taken +bcond_ls: + b.ls bcond_taken + b bcond_not_taken +bcond_ge: + b.ge bcond_taken + b bcond_not_taken +bcond_lt: + b.lt bcond_taken + b bcond_not_taken +bcond_gt: + b.gt bcond_taken + b bcond_not_taken +bcond_le: + b.le bcond_taken + b bcond_not_taken +bcond_al: + b bcond_taken + +bcond_taken: + // x9 = target (fake_ip or chained block->code) + inline_chain x9, bcond_taken_unchained +bcond_taken_unchained: + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +bcond_not_taken: + // x10 = fallthrough (fake_ip or chained block->code) + inline_chain x10, bcond_not_taken_unchained +bcond_not_taken_unchained: + and x11, x10, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x10 + b fiber_ret_chain + +/* + * Conditional branch with external taken edge and internal fallthrough edge. + * Code stream: [gadget addr][cond][fake_target][internal_continue_ptr] + * + * The taken edge uses the normal external fake-IP/block->code chain path. + * The not-taken edge jumps to a private internal-continue record and never + * passes the interior pointer to fiber_ret_chain. + */ +.gadget bcond_fallthrough_internal + ldr x8, [_pc], #8 // cond + ldr x9, [_pc], #8 // taken target (fake_ip or chained) + ldr x10, [_pc] // internal_continue record pointer + + and x8, x8, #0xf + adr x11, bcond_fallthrough_internal_table + add x11, x11, x8, lsl #2 + load_flags + br x11 + + .align 2 +bcond_fallthrough_internal_table: + b bcond_fi_eq + b bcond_fi_ne + b bcond_fi_cs + b bcond_fi_cc + b bcond_fi_mi + b bcond_fi_pl + b bcond_fi_vs + b bcond_fi_vc + b bcond_fi_hi + b bcond_fi_ls + b bcond_fi_ge + b bcond_fi_lt + b bcond_fi_gt + b bcond_fi_le + b bcond_fi_taken + b bcond_fi_taken +bcond_fi_eq: + b.eq bcond_fi_taken + b bcond_fi_not_taken +bcond_fi_ne: + b.ne bcond_fi_taken + b bcond_fi_not_taken +bcond_fi_cs: + b.cs bcond_fi_taken + b bcond_fi_not_taken +bcond_fi_cc: + b.cc bcond_fi_taken + b bcond_fi_not_taken +bcond_fi_mi: + b.mi bcond_fi_taken + b bcond_fi_not_taken +bcond_fi_pl: + b.pl bcond_fi_taken + b bcond_fi_not_taken +bcond_fi_vs: + b.vs bcond_fi_taken + b bcond_fi_not_taken +bcond_fi_vc: + b.vc bcond_fi_taken + b bcond_fi_not_taken +bcond_fi_hi: + b.hi bcond_fi_taken + b bcond_fi_not_taken +bcond_fi_ls: + b.ls bcond_fi_taken + b bcond_fi_not_taken +bcond_fi_ge: + b.ge bcond_fi_taken + b bcond_fi_not_taken +bcond_fi_lt: + b.lt bcond_fi_taken + b bcond_fi_not_taken +bcond_fi_gt: + b.gt bcond_fi_taken + b bcond_fi_not_taken +bcond_fi_le: + b.le bcond_fi_taken + b bcond_fi_not_taken +bcond_fi_taken: + inline_chain x9, bcond_fi_taken_unchained +bcond_fi_taken_unchained: + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain +bcond_fi_not_taken: + mov _pc, x10 + gret + +/* + * Conditional branch with internal taken edge and external fallthrough edge. + * Code stream: [gadget addr][cond][internal_continue_ptr][fake_fallthrough] + * + * The taken edge jumps to a private internal-continue record and never passes + * the interior pointer to fiber_ret_chain. The not-taken edge uses the normal + * external fake-IP/block->code chain path. + */ +.gadget bcond_taken_internal + ldr x8, [_pc], #8 // cond + ldr x9, [_pc], #8 // internal_continue record pointer + ldr x10, [_pc] // fallthrough target (fake_ip or chained) + + and x8, x8, #0xf + adr x11, bcond_taken_internal_table + add x11, x11, x8, lsl #2 + load_flags + br x11 + + .align 2 +bcond_taken_internal_table: + b bcond_ti_eq + b bcond_ti_ne + b bcond_ti_cs + b bcond_ti_cc + b bcond_ti_mi + b bcond_ti_pl + b bcond_ti_vs + b bcond_ti_vc + b bcond_ti_hi + b bcond_ti_ls + b bcond_ti_ge + b bcond_ti_lt + b bcond_ti_gt + b bcond_ti_le + b bcond_ti_taken + b bcond_ti_taken +bcond_ti_eq: + b.eq bcond_ti_taken + b bcond_ti_not_taken +bcond_ti_ne: + b.ne bcond_ti_taken + b bcond_ti_not_taken +bcond_ti_cs: + b.cs bcond_ti_taken + b bcond_ti_not_taken +bcond_ti_cc: + b.cc bcond_ti_taken + b bcond_ti_not_taken +bcond_ti_mi: + b.mi bcond_ti_taken + b bcond_ti_not_taken +bcond_ti_pl: + b.pl bcond_ti_taken + b bcond_ti_not_taken +bcond_ti_vs: + b.vs bcond_ti_taken + b bcond_ti_not_taken +bcond_ti_vc: + b.vc bcond_ti_taken + b bcond_ti_not_taken +bcond_ti_hi: + b.hi bcond_ti_taken + b bcond_ti_not_taken +bcond_ti_ls: + b.ls bcond_ti_taken + b bcond_ti_not_taken +bcond_ti_ge: + b.ge bcond_ti_taken + b bcond_ti_not_taken +bcond_ti_lt: + b.lt bcond_ti_taken + b bcond_ti_not_taken +bcond_ti_gt: + b.gt bcond_ti_taken + b bcond_ti_not_taken +bcond_ti_le: + b.le bcond_ti_taken + b bcond_ti_not_taken +bcond_ti_taken: + mov _pc, x9 + gret +bcond_ti_not_taken: + inline_chain x10, bcond_ti_not_taken_unchained +bcond_ti_not_taken_unchained: + and x11, x10, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x10 + b fiber_ret_chain + +/* + * System call (SVC) + * Code stream: [gadget addr][next_pc (64-bit)] + * + * Sets guest PC to next instruction before exiting. + */ +.gadget svc + ldr x8, [_pc] // Load next instruction address + str x8, [_cpu, #CPU_pc] // Store as guest PC + mov w0, #INT_SYSCALL + b fiber_exit + +/* + * Conditional select (CSEL) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | cond<<24 | sf<<28] + * + * CSEL Xd, Xn, Xm, cond + * If condition is true: Xd = Xn + * If condition is false: Xd = Xm + */ +.gadget csel + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #4 // cond + ubfx x13, x8, #28, #1 // sf + + add x14, _cpu, #CPU_x0 + + // Load rn value + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + // Load rm value + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + // Build jump table address for condition + // Use x3 (was x18) for jump address since load_flags uses x17 + adr x3, csel_table + add x3, x3, x12, lsl #2 + + // Load NZCV flags - MUST be last thing before conditional + load_flags + + br x3 + + .align 2 +csel_table: + b csel_eq // 0: EQ + b csel_ne // 1: NE + b csel_cs // 2: CS/HS + b csel_cc // 3: CC/LO + b csel_mi // 4: MI + b csel_pl // 5: PL + b csel_vs // 6: VS + b csel_vc // 7: VC + b csel_hi // 8: HI + b csel_ls // 9: LS + b csel_ge // 10: GE + b csel_lt // 11: LT + b csel_gt // 12: GT + b csel_le // 13: LE + b csel_al // 14: AL + b csel_al // 15: NV + +csel_eq: + csel x17, x15, x16, eq + b csel_store +csel_ne: + csel x17, x15, x16, ne + b csel_store +csel_cs: + csel x17, x15, x16, cs + b csel_store +csel_cc: + csel x17, x15, x16, cc + b csel_store +csel_mi: + csel x17, x15, x16, mi + b csel_store +csel_pl: + csel x17, x15, x16, pl + b csel_store +csel_vs: + csel x17, x15, x16, vs + b csel_store +csel_vc: + csel x17, x15, x16, vc + b csel_store +csel_hi: + csel x17, x15, x16, hi + b csel_store +csel_ls: + csel x17, x15, x16, ls + b csel_store +csel_ge: + csel x17, x15, x16, ge + b csel_store +csel_lt: + csel x17, x15, x16, lt + b csel_store +csel_gt: + csel x17, x15, x16, gt + b csel_store +csel_le: + csel x17, x15, x16, le + b csel_store +csel_al: + mov x17, x15 + b csel_store + +csel_store: + // For 32-bit, truncate result + cbz x13, 5f + b 6f +5: and x17, x17, #0xffffffff +6: + // Store result + cmp x9, #31 + b.eq 7f + str x17, [x14, x9, lsl #3] +7: gret + +/* + * Test bit and branch if zero (TBZ) + * Code stream: [gadget addr][rt | bit<<8 (64-bit)][fake_target (64-bit)][fake_fallthrough (64-bit)] + * + * TBZ Rt, #imm, label + * If bit[imm] of Rt is 0: branch to label + * Otherwise: continue to next instruction + */ +.gadget tbz + ldr x8, [_pc] // rt | bit<<8 + add _pc, _pc, #8 + ldr x9, [_pc] // target (fake_ip or chained) + add _pc, _pc, #8 + ldr x10, [_pc] // fallthrough (fake_ip or chained) + + and x11, x8, #0x1f // rt + ubfx x12, x8, #8, #6 // bit position (0-63) + + // Load register value + add x13, _cpu, #CPU_x0 + cmp x11, #31 + b.eq 1f + ldr x14, [x13, x11, lsl #3] + b 2f +1: mov x14, #0 +2: + // Create mask for the bit position + mov x15, #1 + lsl x15, x15, x12 // x15 = 1 << bit_position + + // Test the bit + tst x14, x15 + b.ne tbz_not_taken // bit is set (1) - not zero, fall through + // Bit is zero - take branch (x9) + inline_chain x9, tbz_t_unchained +tbz_t_unchained: + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +tbz_not_taken: + // bit is set - fall through (x10) + inline_chain x10, tbz_nt_unchained +tbz_nt_unchained: + and x11, x10, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x10 + b fiber_ret_chain + +/* + * Test bit and branch if not zero (TBNZ) + * Code stream: [gadget addr][rt | bit<<8 (64-bit)][fake_target (64-bit)][fake_fallthrough (64-bit)] + * + * TBNZ Rt, #imm, label + * If bit[imm] of Rt is 1: branch to label + * Otherwise: continue to next instruction + */ +.gadget tbnz + ldr x8, [_pc] // rt | bit<<8 + add _pc, _pc, #8 + ldr x9, [_pc] // target + add _pc, _pc, #8 + ldr x10, [_pc] // fallthrough + + and x11, x8, #0x1f // rt + ubfx x12, x8, #8, #6 // bit position + + add x13, _cpu, #CPU_x0 + cmp x11, #31 + b.eq 1f + ldr x14, [x13, x11, lsl #3] + b 2f +1: mov x14, #0 +2: + mov x15, #1 + lsl x15, x15, x12 + + tst x14, x15 + b.eq tbnz_not_taken // bit is zero - fall through + // Bit is set - take branch (x9) + inline_chain x9, tbnz_t_unchained +tbnz_t_unchained: + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +tbnz_not_taken: + // bit is zero - fall through (x10) + inline_chain x10, tbnz_nt_unchained +tbnz_nt_unchained: + and x11, x10, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x10 + b fiber_ret_chain + +/* + * TBZ/TBNZ with external taken edge and internal fallthrough edge. + * Code stream: [gadget addr][rt | bit<<8 | is_tbnz<<14] + * [fake_target][internal_continue_ptr] + * + * The taken edge uses the normal external fake-IP/block->code chain path. + * The not-taken edge jumps to a private internal-continue record and never + * passes the interior pointer to fiber_ret_chain. + */ +.gadget tbz_fallthrough_internal + ldr x8, [_pc], #8 // rt | bit<<8 | is_tbnz<<14 + ldr x9, [_pc], #8 // taken target (fake_ip or chained) + ldr x10, [_pc] // internal_continue record pointer + + and x11, x8, #0x1f // rt + ubfx x12, x8, #8, #6 // bit position (0-63) + ubfx x13, x8, #14, #1 // is_tbnz + add x14, _cpu, #CPU_x0 + cmp x11, #31 + b.eq tbz_fi_xzr + ldr x15, [x14, x11, lsl #3] + b tbz_fi_test +tbz_fi_xzr: + mov x15, #0 +tbz_fi_test: + mov x16, #1 + lsl x16, x16, x12 + tst x15, x16 + cset w17, ne // bit set = 1, bit clear = 0 + cmp w17, w13 // TBNZ takes when set; TBZ takes when clear + b.eq tbz_fi_taken +tbz_fi_not_taken: + mov _pc, x10 + gret +tbz_fi_taken: + inline_chain x9, tbz_fi_taken_unchained +tbz_fi_taken_unchained: + and x11, x9, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x9 + b fiber_ret_chain + +/* + * TBZ/TBNZ with internal taken edge and external fallthrough edge. + * Code stream: [gadget addr][rt | bit<<8 | is_tbnz<<14] + * [internal_continue_ptr][fake_fallthrough] + * + * The taken edge jumps to a private internal-continue record and never passes + * the interior pointer to fiber_ret_chain. The not-taken edge uses the normal + * external fake-IP/block->code chain path. + */ +.gadget tbz_taken_internal + ldr x8, [_pc], #8 // rt | bit<<8 | is_tbnz<<14 + ldr x9, [_pc], #8 // internal_continue record pointer + ldr x10, [_pc] // fallthrough target (fake_ip or chained) + + and x11, x8, #0x1f // rt + ubfx x12, x8, #8, #6 // bit position (0-63) + ubfx x13, x8, #14, #1 // is_tbnz + add x14, _cpu, #CPU_x0 + cmp x11, #31 + b.eq tbz_ti_xzr + ldr x15, [x14, x11, lsl #3] + b tbz_ti_test +tbz_ti_xzr: + mov x15, #0 +tbz_ti_test: + mov x16, #1 + lsl x16, x16, x12 + tst x15, x16 + cset w17, ne // bit set = 1, bit clear = 0 + cmp w17, w13 // TBNZ takes when set; TBZ takes when clear + b.eq tbz_ti_taken +tbz_ti_not_taken: + inline_chain x10, tbz_ti_not_taken_unchained +tbz_ti_not_taken_unchained: + and x11, x10, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x10 + b fiber_ret_chain +tbz_ti_taken: + mov _pc, x9 + gret + +/* + * CSINC - Conditional Select Increment + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | cond<<24 | sf<<28] + * + * CSINC Xd, Xn, Xm, cond + * If condition is true: Xd = Xn + * If condition is false: Xd = Xm + 1 + * + * Common aliases: + * CINC Xd, Xn, cond -> CSINC Xd, Xn, Xn, invert(cond) + * CSET Xd, cond -> CSINC Xd, XZR, XZR, invert(cond) + */ +.gadget csinc + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #4 // cond + ubfx x13, x8, #28, #1 // sf + + add x14, _cpu, #CPU_x0 + + // Load rn value + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + // Load rm value + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + // rm + 1 for false case + add x16, x16, #1 + + adr x3, csinc_table + add x3, x3, x12, lsl #2 + + load_flags + br x3 + + .align 2 +csinc_table: + b csinc_eq + b csinc_ne + b csinc_cs + b csinc_cc + b csinc_mi + b csinc_pl + b csinc_vs + b csinc_vc + b csinc_hi + b csinc_ls + b csinc_ge + b csinc_lt + b csinc_gt + b csinc_le + b csinc_al + b csinc_al + +csinc_eq: + csel x17, x15, x16, eq + b csinc_store +csinc_ne: + csel x17, x15, x16, ne + b csinc_store +csinc_cs: + csel x17, x15, x16, cs + b csinc_store +csinc_cc: + csel x17, x15, x16, cc + b csinc_store +csinc_mi: + csel x17, x15, x16, mi + b csinc_store +csinc_pl: + csel x17, x15, x16, pl + b csinc_store +csinc_vs: + csel x17, x15, x16, vs + b csinc_store +csinc_vc: + csel x17, x15, x16, vc + b csinc_store +csinc_hi: + csel x17, x15, x16, hi + b csinc_store +csinc_ls: + csel x17, x15, x16, ls + b csinc_store +csinc_ge: + csel x17, x15, x16, ge + b csinc_store +csinc_lt: + csel x17, x15, x16, lt + b csinc_store +csinc_gt: + csel x17, x15, x16, gt + b csinc_store +csinc_le: + csel x17, x15, x16, le + b csinc_store +csinc_al: + mov x17, x15 + b csinc_store + +csinc_store: + cbz x13, 5f + b 6f +5: and x17, x17, #0xffffffff +6: + cmp x9, #31 + b.eq 7f + str x17, [x14, x9, lsl #3] +7: gret + +/* + * CSINV - Conditional Select Invert + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | cond<<24 | sf<<28] + * + * If condition is true: Xd = Xn + * If condition is false: Xd = NOT(Xm) + */ +.gadget csinv + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + ubfx x12, x8, #24, #4 + ubfx x13, x8, #28, #1 + + add x14, _cpu, #CPU_x0 + + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + // NOT(rm) for false case + mvn x16, x16 + + adr x3, csinv_table + add x3, x3, x12, lsl #2 + + load_flags + br x3 + + .align 2 +csinv_table: + b csinv_eq + b csinv_ne + b csinv_cs + b csinv_cc + b csinv_mi + b csinv_pl + b csinv_vs + b csinv_vc + b csinv_hi + b csinv_ls + b csinv_ge + b csinv_lt + b csinv_gt + b csinv_le + b csinv_al + b csinv_al + +csinv_eq: + csel x17, x15, x16, eq + b csinv_store +csinv_ne: + csel x17, x15, x16, ne + b csinv_store +csinv_cs: + csel x17, x15, x16, cs + b csinv_store +csinv_cc: + csel x17, x15, x16, cc + b csinv_store +csinv_mi: + csel x17, x15, x16, mi + b csinv_store +csinv_pl: + csel x17, x15, x16, pl + b csinv_store +csinv_vs: + csel x17, x15, x16, vs + b csinv_store +csinv_vc: + csel x17, x15, x16, vc + b csinv_store +csinv_hi: + csel x17, x15, x16, hi + b csinv_store +csinv_ls: + csel x17, x15, x16, ls + b csinv_store +csinv_ge: + csel x17, x15, x16, ge + b csinv_store +csinv_lt: + csel x17, x15, x16, lt + b csinv_store +csinv_gt: + csel x17, x15, x16, gt + b csinv_store +csinv_le: + csel x17, x15, x16, le + b csinv_store +csinv_al: + mov x17, x15 + b csinv_store + +csinv_store: + cbz x13, 5f + b 6f +5: and x17, x17, #0xffffffff +6: + cmp x9, #31 + b.eq 7f + str x17, [x14, x9, lsl #3] +7: gret + +/* + * CSNEG - Conditional Select Negate + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | cond<<24 | sf<<28] + * + * If condition is true: Xd = Xn + * If condition is false: Xd = -Xm + */ +.gadget csneg + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + ubfx x12, x8, #24, #4 + ubfx x13, x8, #28, #1 + + add x14, _cpu, #CPU_x0 + + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + // NEG(rm) for false case + neg x16, x16 + + adr x3, csneg_table + add x3, x3, x12, lsl #2 + + load_flags + br x3 + + .align 2 +csneg_table: + b csneg_eq + b csneg_ne + b csneg_cs + b csneg_cc + b csneg_mi + b csneg_pl + b csneg_vs + b csneg_vc + b csneg_hi + b csneg_ls + b csneg_ge + b csneg_lt + b csneg_gt + b csneg_le + b csneg_al + b csneg_al + +csneg_eq: + csel x17, x15, x16, eq + b csneg_store +csneg_ne: + csel x17, x15, x16, ne + b csneg_store +csneg_cs: + csel x17, x15, x16, cs + b csneg_store +csneg_cc: + csel x17, x15, x16, cc + b csneg_store +csneg_mi: + csel x17, x15, x16, mi + b csneg_store +csneg_pl: + csel x17, x15, x16, pl + b csneg_store +csneg_vs: + csel x17, x15, x16, vs + b csneg_store +csneg_vc: + csel x17, x15, x16, vc + b csneg_store +csneg_hi: + csel x17, x15, x16, hi + b csneg_store +csneg_ls: + csel x17, x15, x16, ls + b csneg_store +csneg_ge: + csel x17, x15, x16, ge + b csneg_store +csneg_lt: + csel x17, x15, x16, lt + b csneg_store +csneg_gt: + csel x17, x15, x16, gt + b csneg_store +csneg_le: + csel x17, x15, x16, le + b csneg_store +csneg_al: + mov x17, x15 + b csneg_store + +csneg_store: + cbz x13, 5f + b 6f +5: and x17, x17, #0xffffffff +6: + cmp x9, #31 + b.eq 7f + str x17, [x14, x9, lsl #3] +7: gret + +/* + * ============================================================ + * Per-condition bcond gadgets + * + * Each gadget handles one specific condition code, eliminating the + * indirect branch (br x11) through the jump table in the generic bcond. + * Code stream: [gadget addr][target][fallthrough] — no condition word. + * Reuses existing bcond_taken / bcond_not_taken shared tails. + * ============================================================ + */ + +.macro make_bcond name, cond +.gadget bcond_\name + ldr x9, [_pc] // target (fake_ip or chained) + add _pc, _pc, #8 + ldr x10, [_pc] // fallthrough (fake_ip or chained) + load_flags + b.\cond bcond_taken + b bcond_not_taken +.endm + +make_bcond eq, eq +make_bcond ne, ne +make_bcond cs, cs +make_bcond cc, cc +make_bcond mi, mi +make_bcond pl, pl +make_bcond vs, vs +make_bcond vc, vc +make_bcond hi, hi +make_bcond ls, ls +make_bcond ge, ge +make_bcond lt, lt +make_bcond gt, gt +make_bcond le, le + +/* + * ============================================================ + * Fused CMP-imm + B.cond gadgets (OP-4) + * + * Combines SUBS(64-bit, rd=31, no-shift) + B.cond into a single + * gadget dispatch, eliminating 1 gret (2 host insns) per iteration + * of compare-and-branch loops. + * + * Code stream: [gadget addr][rn | imm12<<8][fake_target][fake_fallthrough] + * rn: bits 0-4 (base register, must not be 31) + * imm12: bits 8-19 (12-bit unsigned immediate) + * + * Also handles SUBS with result register (rd != 31): + * Code stream: [gadget addr][rd | rn<<8 | imm12<<16][fake_target][fake_fallthrough] + * ============================================================ + */ + +/* + * Fused CMP Xn, #imm + B.cond (rd=31, result discarded) + * Only sets flags, no result stored. + */ +.macro make_fused_cmp_bcond name, cond +.gadget fused_cmp_bcond_\name + ldr x8, [_pc] // rn | imm12<<8 + add _pc, _pc, #8 + ldr x9, [_pc] // target (fake_ip or chained) + add _pc, _pc, #8 + ldr x10, [_pc] // fallthrough (fake_ip or chained) + and x11, x8, #0x1f // rn + ubfx x12, x8, #8, #12 // imm12 + // Load rn value + add x13, _cpu, #CPU_x0 + ldr x14, [x13, x11, lsl #3] + // Compare: SUBS with result discarded (CMP) + subs x15, x14, x12 + // Store flags (N, Z, C, V from host NZCV) + mrs x16, nzcv + str w16, [_cpu, #CPU_nzcv] + // Now do conditional branch using host flags (still live) + b.\cond bcond_taken + b bcond_not_taken +.endm + +make_fused_cmp_bcond eq, eq +make_fused_cmp_bcond ne, ne +make_fused_cmp_bcond cs, cs +make_fused_cmp_bcond cc, cc +make_fused_cmp_bcond mi, mi +make_fused_cmp_bcond pl, pl +make_fused_cmp_bcond vs, vs +make_fused_cmp_bcond vc, vc +make_fused_cmp_bcond hi, hi +make_fused_cmp_bcond ls, ls +make_fused_cmp_bcond ge, ge +make_fused_cmp_bcond lt, lt +make_fused_cmp_bcond gt, gt +make_fused_cmp_bcond le, le + +/* + * Fused SUBS Xd, Xn, #imm + B.cond (rd != 31, result stored) + * Stores result AND sets flags, then conditional branch. + * Code stream: [gadget addr][rd | rn<<8 | imm12<<16][fake_target][fake_fallthrough] + */ +.macro make_fused_subs_bcond name, cond +.gadget fused_subs_bcond_\name + ldr x8, [_pc] // rd | rn<<8 | imm12<<16 + add _pc, _pc, #8 + ldr x9, [_pc] // target + add _pc, _pc, #8 + ldr x10, [_pc] // fallthrough + and x11, x8, #0x1f // rd + ubfx x12, x8, #8, #5 // rn + lsr x13, x8, #16 // imm12 + // Load rn value + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x12, lsl #3] + // SUBS: subtract and set flags + subs x15, x15, x13 + // Store result to rd (before mrs clobbers flags info is preserved) + str x15, [x14, x11, lsl #3] + // Store flags (subs flags still live, mrs/str don't affect NZCV) + mrs x15, nzcv + str w15, [_cpu, #CPU_nzcv] + // Conditional branch using host flags (still live from subs) + b.\cond bcond_taken + b bcond_not_taken +.endm + +make_fused_subs_bcond eq, eq +make_fused_subs_bcond ne, ne +make_fused_subs_bcond cs, cs +make_fused_subs_bcond cc, cc +make_fused_subs_bcond mi, mi +make_fused_subs_bcond pl, pl +make_fused_subs_bcond vs, vs +make_fused_subs_bcond vc, vc +make_fused_subs_bcond hi, hi +make_fused_subs_bcond ls, ls +make_fused_subs_bcond ge, ge +make_fused_subs_bcond lt, lt +make_fused_subs_bcond gt, gt +make_fused_subs_bcond le, le + +/* + * ============================================================ + * 32-bit Fused CMP/SUBS + B.cond gadgets (OP-9) + * + * Same as 64-bit versions but uses w-register (32-bit) SUBS. + * Code stream layout is identical to 64-bit variants. + * ============================================================ + */ + +/* + * Fused CMP Wn, #imm + B.cond (32-bit, rd=31, result discarded) + * Code stream: [gadget addr][rn | imm12<<8][fake_target][fake_fallthrough] + */ +.macro make_fused_cmp32_bcond name, cond +.gadget fused_cmp32_bcond_\name + ldr x8, [_pc] // rn | imm12<<8 + add _pc, _pc, #8 + ldr x9, [_pc] // target + add _pc, _pc, #8 + ldr x10, [_pc] // fallthrough + and x11, x8, #0x1f // rn + ubfx x12, x8, #8, #12 // imm12 + add x13, _cpu, #CPU_x0 + ldr x14, [x13, x11, lsl #3] + // 32-bit CMP + subs w15, w14, w12 + mrs x16, nzcv + str w16, [_cpu, #CPU_nzcv] + b.\cond bcond_taken + b bcond_not_taken +.endm + +make_fused_cmp32_bcond eq, eq +make_fused_cmp32_bcond ne, ne +make_fused_cmp32_bcond cs, cs +make_fused_cmp32_bcond cc, cc +make_fused_cmp32_bcond mi, mi +make_fused_cmp32_bcond pl, pl +make_fused_cmp32_bcond vs, vs +make_fused_cmp32_bcond vc, vc +make_fused_cmp32_bcond hi, hi +make_fused_cmp32_bcond ls, ls +make_fused_cmp32_bcond ge, ge +make_fused_cmp32_bcond lt, lt +make_fused_cmp32_bcond gt, gt +make_fused_cmp32_bcond le, le + +/* + * Fused SUBS Wd, Wn, #imm + B.cond (32-bit, rd!=31, result stored) + * Code stream: [gadget addr][rd | rn<<8 | imm12<<16][fake_target][fake_fallthrough] + */ +.macro make_fused_subs32_bcond name, cond +.gadget fused_subs32_bcond_\name + ldr x8, [_pc] // rd | rn<<8 | imm12<<16 + add _pc, _pc, #8 + ldr x9, [_pc] // target + add _pc, _pc, #8 + ldr x10, [_pc] // fallthrough + and x11, x8, #0x1f // rd + ubfx x12, x8, #8, #5 // rn + lsr x13, x8, #16 // imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x12, lsl #3] + // 32-bit SUBS + subs w15, w15, w13 + // Store zero-extended 32-bit result + // (w-register SUBS already zero-extends to x15) + str x15, [x14, x11, lsl #3] + mrs x15, nzcv + str w15, [_cpu, #CPU_nzcv] + b.\cond bcond_taken + b bcond_not_taken +.endm + +make_fused_subs32_bcond eq, eq +make_fused_subs32_bcond ne, ne +make_fused_subs32_bcond cs, cs +make_fused_subs32_bcond cc, cc +make_fused_subs32_bcond mi, mi +make_fused_subs32_bcond pl, pl +make_fused_subs32_bcond vs, vs +make_fused_subs32_bcond vc, vc +make_fused_subs32_bcond hi, hi +make_fused_subs32_bcond ls, ls +make_fused_subs32_bcond ge, ge +make_fused_subs32_bcond lt, lt +make_fused_subs32_bcond gt, gt +make_fused_subs32_bcond le, le + +/* + * ============================================================ + * Fused CMP_reg + B.cond gadgets (64-bit, rd=31) + * + * Combines SUBS X31, Xn, Xm (CMP) + B.cond into a single dispatch. + * Code stream: [gadget addr][rn | rm<<8][fake_target][fake_fallthrough] + * ============================================================ + */ +.macro make_fused_cmp_reg_bcond name, cond +.gadget fused_cmp_reg_bcond_\name + ldr x8, [_pc] // rn | rm<<8 + add _pc, _pc, #8 + ldr x9, [_pc] // target + add _pc, _pc, #8 + ldr x10, [_pc] // fallthrough + and x11, x8, #0x1f // rn + ubfx x12, x8, #8, #5 // rm + add x13, _cpu, #CPU_x0 + ldr x14, [x13, x11, lsl #3] + ldr x15, [x13, x12, lsl #3] + subs xzr, x14, x15 + mrs x16, nzcv + str w16, [_cpu, #CPU_nzcv] + b.\cond bcond_taken + b bcond_not_taken +.endm + +make_fused_cmp_reg_bcond eq, eq +make_fused_cmp_reg_bcond ne, ne +make_fused_cmp_reg_bcond cs, cs +make_fused_cmp_reg_bcond cc, cc +make_fused_cmp_reg_bcond mi, mi +make_fused_cmp_reg_bcond pl, pl +make_fused_cmp_reg_bcond vs, vs +make_fused_cmp_reg_bcond vc, vc +make_fused_cmp_reg_bcond hi, hi +make_fused_cmp_reg_bcond ls, ls +make_fused_cmp_reg_bcond ge, ge +make_fused_cmp_reg_bcond lt, lt +make_fused_cmp_reg_bcond gt, gt +make_fused_cmp_reg_bcond le, le + +/* + * Fused SUBS Xd, Xn, Xm + B.cond (64-bit, rd!=31, result stored) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16][fake_target][fake_fallthrough] + */ +.macro make_fused_subs_reg_bcond name, cond +.gadget fused_subs_reg_bcond_\name + ldr x8, [_pc] // rd | rn<<8 | rm<<16 + add _pc, _pc, #8 + ldr x9, [_pc] // target + add _pc, _pc, #8 + ldr x10, [_pc] // fallthrough + and x11, x8, #0x1f // rd + ubfx x12, x8, #8, #5 // rn + ubfx x13, x8, #16, #5 // rm + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x12, lsl #3] + ldr x16, [x14, x13, lsl #3] + subs x15, x15, x16 + str x15, [x14, x11, lsl #3] + mrs x15, nzcv + str w15, [_cpu, #CPU_nzcv] + b.\cond bcond_taken + b bcond_not_taken +.endm + +make_fused_subs_reg_bcond eq, eq +make_fused_subs_reg_bcond ne, ne +make_fused_subs_reg_bcond cs, cs +make_fused_subs_reg_bcond cc, cc +make_fused_subs_reg_bcond mi, mi +make_fused_subs_reg_bcond pl, pl +make_fused_subs_reg_bcond vs, vs +make_fused_subs_reg_bcond vc, vc +make_fused_subs_reg_bcond hi, hi +make_fused_subs_reg_bcond ls, ls +make_fused_subs_reg_bcond ge, ge +make_fused_subs_reg_bcond lt, lt +make_fused_subs_reg_bcond gt, gt +make_fused_subs_reg_bcond le, le diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/crypto.S b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/crypto.S new file mode 100644 index 0000000000..09e3022c36 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/crypto.S @@ -0,0 +1,829 @@ +/* + * ARM64 Cryptographic Extension Gadgets + * + * AES, SHA1, SHA256, and SHA512 gadgets use native .inst instructions + * for near-native performance. Other crypto gadgets (EOR3, SM3, SM4, + * PMULL, TBL/TBX, SVE) still use C helper functions. + */ + +#include "gadgets.h" + +.text + +/* + * AESE - AES single round encryption + * Performs AddRoundKey, SubBytes, and ShiftRows + * Code stream: [gadget addr][rd | rn<<8] + * + * Native AESE does XOR(Vd,Vn) then SubBytes+ShiftRows in one instruction + */ +.gadget aese + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Vd + lsl x14, x10, #4 + ldr q1, [x12, x14] // q1 = Vn (round key) + + // Native AESE: v0 = SubBytes(ShiftRows(v0 XOR v1)) + .inst 0x4e284820 // aese v0.16b, v1.16b + + str q0, [x12, x13] + + gret + +/* + * AESD - AES single round decryption + * Performs AddRoundKey, InvSubBytes, and InvShiftRows + * Code stream: [gadget addr][rd | rn<<8] + */ +.gadget aesd + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Vd + lsl x14, x10, #4 + ldr q1, [x12, x14] // q1 = Vn + + // Native AESD: v0 = InvSubBytes(InvShiftRows(v0 XOR v1)) + .inst 0x4e285820 // aesd v0.16b, v1.16b + + str q0, [x12, x13] + + gret + +/* + * AESMC - AES MixColumns + * Code stream: [gadget addr][rd | rn<<8] + */ +.gadget aesmc + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + lsl x14, x10, #4 + ldr q0, [x12, x14] // q0 = Vn + + // Native AESMC: v0 = MixColumns(v0) + .inst 0x4e286800 // aesmc v0.16b, v0.16b + + str q0, [x12, x13] // store to Vd + + gret + +/* + * AESIMC - AES Inverse MixColumns + * Code stream: [gadget addr][rd | rn<<8] + */ +.gadget aesimc + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + lsl x14, x10, #4 + ldr q0, [x12, x14] // q0 = Vn + + // Native AESIMC: v0 = InvMixColumns(v0) + .inst 0x4e287800 // aesimc v0.16b, v0.16b + + str q0, [x12, x13] // store to Vd + + gret + +/* + * SHA1 instructions - native .inst implementations + */ + +// SHA1H Sd, Sn - SHA1 fixed rotate +// Code stream: [gadget addr][rd | rn<<8] +.gadget sha1h + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + + add x12, _cpu, #CPU_fp + lsl x14, x10, #4 + ldr s0, [x12, x14] // s0 = Sn (32-bit scalar) + + // Native SHA1H: s0 = FixedRotate(s1) + // Encoding: SHA1H Sd, Sn = 0101_1110_0010_1000_0000_10nn_nnnd_dddd + // sha1h s0, s0 → 0x5e280800 + .inst 0x5e280800 // sha1h s0, s0 + + // Store s0 to Sd and clear upper bits + lsl x13, x9, #4 + add x15, x12, x13 + str s0, [x15] // store 32-bit result + str xzr, [x15, #4] // clear bits 32-63 + str xzr, [x15, #8] // clear bits 64-127 + + gret + +// SHA1C Qd, Sn, Vm.4S - SHA1 hash update (Choose) +// Code stream: [gadget addr][rd | rn<<8 | rm<<16] +.gadget sha1c + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Qd + lsl x14, x10, #4 + ldr s1, [x12, x14] // s1 = Sn (32-bit hash state) + lsl x15, x11, #4 + ldr q2, [x12, x15] // q2 = Vm.4S + + .inst 0x5e020020 // sha1c q0, s1, v2.4s + + str q0, [x12, x13] // store result to Qd + + gret + +// SHA1M Qd, Sn, Vm.4S - SHA1 hash update (Majority) +.gadget sha1m + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Qd + lsl x14, x10, #4 + ldr s1, [x12, x14] // s1 = Sn + lsl x15, x11, #4 + ldr q2, [x12, x15] // q2 = Vm.4S + + .inst 0x5e022020 // sha1m q0, s1, v2.4s + + str q0, [x12, x13] + + gret + +// SHA1P Qd, Sn, Vm.4S - SHA1 hash update (Parity) +.gadget sha1p + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Qd + lsl x14, x10, #4 + ldr s1, [x12, x14] // s1 = Sn + lsl x15, x11, #4 + ldr q2, [x12, x15] // q2 = Vm.4S + + .inst 0x5e021020 // sha1p q0, s1, v2.4s + + str q0, [x12, x13] + + gret + +// SHA1SU0 Vd.4S, Vn.4S, Vm.4S - SHA1 schedule update 0 +.gadget sha1su0 + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Vd + lsl x14, x10, #4 + ldr q1, [x12, x14] // q1 = Vn + lsl x15, x11, #4 + ldr q2, [x12, x15] // q2 = Vm + + .inst 0x5e023020 // sha1su0 v0.4s, v1.4s, v2.4s + + str q0, [x12, x13] + + gret + +// SHA1SU1 Vd.4S, Vn.4S - SHA1 schedule update 1 +.gadget sha1su1 + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Vd + lsl x14, x10, #4 + ldr q1, [x12, x14] // q1 = Vn + + .inst 0x5e281820 // sha1su1 v0.4s, v1.4s + + str q0, [x12, x13] + + gret + +/* + * SHA256 instructions + */ + +// SHA256H Qd, Qn, Vm.4S +.gadget sha256h + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Qd + lsl x14, x10, #4 + ldr q1, [x12, x14] // q1 = Qn + lsl x15, x11, #4 + ldr q2, [x12, x15] // q2 = Vm.4S + + .inst 0x5e024020 // sha256h q0, q1, v2.4s + + str q0, [x12, x13] + + gret + +// SHA256H2 Qd, Qn, Vm.4S +.gadget sha256h2 + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Qd + lsl x14, x10, #4 + ldr q1, [x12, x14] // q1 = Qn + lsl x15, x11, #4 + ldr q2, [x12, x15] // q2 = Vm.4S + + .inst 0x5e025020 // sha256h2 q0, q1, v2.4s + + str q0, [x12, x13] + + gret + +// SHA256SU0 Vd.4S, Vn.4S +.gadget sha256su0 + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Vd + lsl x14, x10, #4 + ldr q1, [x12, x14] // q1 = Vn + + .inst 0x5e282820 // sha256su0 v0.4s, v1.4s + + str q0, [x12, x13] + + gret + +// SHA256SU1 Vd.4S, Vn.4S, Vm.4S +.gadget sha256su1 + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Vd + lsl x14, x10, #4 + ldr q1, [x12, x14] // q1 = Vn + lsl x15, x11, #4 + ldr q2, [x12, x15] // q2 = Vm + + .inst 0x5e026020 // sha256su1 v0.4s, v1.4s, v2.4s + + str q0, [x12, x13] + + gret + +/* + * SHA512SU0 Vd.2D, Vn.2D + * Code stream: [gadget addr][rd | rn<<8] + */ +.gadget sha512su0 + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + + add x12, _cpu, #CPU_fp + + // Load Vd, Vn from emulated register file + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Vd + lsl x14, x10, #4 + ldr q1, [x12, x14] // q1 = Vn + + // Execute native SHA512SU0 instruction + // SHA512SU0 V0.2D, V1.2D + .inst 0xcec08020 // sha512su0 v0.2d, v1.2d + + // Store result back to Vd + str q0, [x12, x13] + + gret + +/* + * SHA512SU1 Vd.2D, Vn.2D, Vm.2D + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ +.gadget sha512su1 + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + + add x12, _cpu, #CPU_fp + + // Load Vd, Vn, Vm from emulated register file + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Vd + lsl x14, x10, #4 + ldr q1, [x12, x14] // q1 = Vn + lsl x15, x11, #4 + ldr q2, [x12, x15] // q2 = Vm + + // Execute native SHA512SU1 instruction + // SHA512SU1 V0.2D, V1.2D, V2.2D + .inst 0xce628820 // sha512su1 v0.2d, v1.2d, v2.2d + + // Store result back to Vd + str q0, [x12, x13] + + gret + +/* + * SHA512H Qd, Qn, Vm.2D + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ +.gadget sha512h + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + + add x12, _cpu, #CPU_fp + + // Load Vd, Vn, Vm from emulated register file + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Vd + lsl x14, x10, #4 + ldr q1, [x12, x14] // q1 = Vn + lsl x15, x11, #4 + ldr q2, [x12, x15] // q2 = Vm + + // Execute native SHA512H instruction + // SHA512H Qd, Qn, Vm.2D -> SHA512H Q0, Q1, V2.2D + .inst 0xce628020 // sha512h q0, q1, v2.2d + + // Store result back to Vd + str q0, [x12, x13] + + gret + +/* + * SHA512H2 Qd, Qn, Vm.2D + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ +.gadget sha512h2 + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + + add x12, _cpu, #CPU_fp + + // Load Vd, Vn, Vm from emulated register file + lsl x13, x9, #4 + ldr q0, [x12, x13] // q0 = Vd + lsl x14, x10, #4 + ldr q1, [x12, x14] // q1 = Vn + lsl x15, x11, #4 + ldr q2, [x12, x15] // q2 = Vm + + // Execute native SHA512H2 instruction + // SHA512H2 Q0, Q1, V2.2D + .inst 0xce628420 // sha512h2 q0, q1, v2.2d + + // Store result back to Vd + str q0, [x12, x13] + + gret + +/* + * EOR3 Vd.16B, Vn.16B, Vm.16B, Va.16B + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | ra<<24] + */ +.gadget eor3 + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + ubfx x12, x8, #24, #5 + + add x13, _cpu, #CPU_fp + + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + save_c + lsl x0, x9, #4 + add x0, x13, x0 // rd_ptr + lsl x1, x10, #4 + add x1, x13, x1 // rn_ptr + lsl x2, x11, #4 + add x2, x13, x2 // rm_ptr + lsl x3, x12, #4 + add x3, x13, x3 // ra_ptr + bl NAME(eor3_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + + gret + +/* + * SM3PARTW1 Vd.4S, Vn.4S, Vm.4S + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ +.gadget sm3partw1 + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + + add x12, _cpu, #CPU_fp + + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + save_c + lsl x0, x9, #4 + add x0, x12, x0 // rd_ptr + lsl x1, x10, #4 + add x1, x12, x1 // rn_ptr + lsl x2, x11, #4 + add x2, x12, x2 // rm_ptr + bl NAME(sm3partw1_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + + gret + +/* + * SM4E Vd.4S, Vn.4S + * Code stream: [gadget addr][rd | rn<<8] + */ +.gadget sm4e + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + + add x12, _cpu, #CPU_fp + + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + save_c + lsl x0, x9, #4 + add x0, x12, x0 // rd_ptr + lsl x1, x10, #4 + add x1, x12, x1 // rn_ptr + bl NAME(sm4e_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + + gret + +/* + * SVE EOR ZD.D, ZN.D, ZM.D (modeled as 128-bit vectors) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ +.gadget sve_eor_d + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + + add x12, _cpu, #CPU_fp + + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + save_c + lsl x0, x9, #4 + add x0, x12, x0 // rd_ptr + lsl x1, x10, #4 + add x1, x12, x1 // rn_ptr + lsl x2, x11, #4 + add x2, x12, x2 // rm_ptr + bl NAME(sve_eor_d_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + + gret + +/* + * SVE XAR ZD.D, ZD.D, ZM.D, #imm (modeled as 128-bit vectors) + * Code stream: [gadget addr][rd | rn<<8 | imm<<16] + */ +.gadget sve_xar_d + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #8 // imm + + add x12, _cpu, #CPU_fp + + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + save_c + lsl x0, x9, #4 + add x0, x12, x0 // rd_ptr (also zn) + lsl x1, x9, #4 + add x1, x12, x1 // zn_ptr (same as rd) + lsl x2, x10, #4 + add x2, x12, x2 // zm_ptr + mov w3, w11 // imm + bl NAME(sve_xar_d_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + + gret + +/* + * PMULL - Polynomial Multiply Long + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | Q<<24 | size<<26] + */ +.gadget pmull + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x21, x8, #24, #1 // Q + ubfx x22, x8, #26, #2 // size + + add x12, _cpu, #CPU_fp + + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + save_c + lsl x0, x9, #4 + add x0, x12, x0 // rd_ptr + lsl x1, x10, #4 + add x1, x12, x1 // rn_ptr + lsl x2, x11, #4 + add x2, x12, x2 // rm_ptr + mov w3, w21 // Q + mov w4, w22 // size + bl NAME(pmull_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + + gret + +/* + * TBL - Table lookup + * TBL Vd.<Ta>, {Vn.16B...Vn+len.16B}, Vm.<Ta> + * + * Each byte of Vm is used as an index into the table formed by + * Vn..Vn+len (concatenated). If index < table_size, the corresponding + * byte is placed in Vd. Otherwise, 0 is placed in Vd. + * + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | len<<24 | Q<<28] + */ +.gadget tbl + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn (first table register) + ubfx x11, x8, #16, #5 // rm (indices) + ubfx x20, x8, #24, #3 // len (0-3 means 1-4 registers) + ubfx x21, x8, #28, #1 // Q (0=8B, 1=16B) + + add x12, _cpu, #CPU_fp + + // Save callee-saved registers + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + // Recalculate from saved x8 (clobbered by saves) + and x19, x8, #0x1f // rd + ubfx x20, x8, #8, #5 // rn + ubfx x21, x8, #16, #5 // rm + ubfx x22, x8, #24, #3 // len + ubfx x23, x8, #28, #1 // Q + + save_c + // tbl_helper(rd_ptr, rn_ptr, rm_ptr, len, Q, fp_base) + lsl x0, x19, #4 + add x0, x12, x0 // rd_ptr + lsl x1, x20, #4 + add x1, x12, x1 // rn_ptr (table start) + lsl x2, x21, #4 + add x2, x12, x2 // rm_ptr (indices) + mov w3, w22 // len + mov w4, w23 // Q + mov x5, x12 // fp_base (for register wrap) + bl NAME(tbl_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + + gret + +/* + * TBX - Table lookup with extend + * Same as TBL but out-of-range indices preserve the original Vd value + * instead of being set to 0. + * + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | len<<24 | Q<<28] + */ +.gadget tbx + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn (first table register) + ubfx x11, x8, #16, #5 // rm (indices) + ubfx x20, x8, #24, #3 // len (0-3 means 1-4 registers) + ubfx x21, x8, #28, #1 // Q (0=8B, 1=16B) + + add x12, _cpu, #CPU_fp + + // Save callee-saved registers + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + // Recalculate from saved x8 (clobbered by saves) + and x19, x8, #0x1f // rd + ubfx x20, x8, #8, #5 // rn + ubfx x21, x8, #16, #5 // rm + ubfx x22, x8, #24, #3 // len + ubfx x23, x8, #28, #1 // Q + + save_c + // tbx_helper(rd_ptr, rn_ptr, rm_ptr, len, Q, fp_base) + lsl x0, x19, #4 + add x0, x12, x0 // rd_ptr + lsl x1, x20, #4 + add x1, x12, x1 // rn_ptr (table start) + lsl x2, x21, #4 + add x2, x12, x2 // rm_ptr (indices) + mov w3, w22 // len + mov w4, w23 // Q + mov x5, x12 // fp_base (for register wrap) + bl NAME(tbx_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + + gret diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/entry.S b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/entry.S new file mode 100644 index 0000000000..1d88e0bb42 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/entry.S @@ -0,0 +1,593 @@ +/* + * ARM64 Guest Entry/Exit Code + * + * This file contains the entry and exit points for transitioning between + * the host (native) code and the emulated ARM64 guest code. + * + * Calling convention used by the ARM64 guest backend: + * fiber_enter(block, frame, tlb) + * - x0 = block (pointer to fiber_block) + * - x1 = frame (pointer to fiber_frame, contains cpu_state) + * - x2 = tlb + * + * Register assignments during gadget execution: + * _cpu (x1) = pointer to cpu_state within fiber_frame + * _tlb (x2) = pointer to tlb entries + * _pc (x28) = instruction pointer (gadget stream) + * _tmp (x0) = return value / scratch + */ + +#include "gadgets.h" +#include "emu/interrupt.h" + +.text + +/* + * fiber_enter - Enter the fiber (guest) execution context + * + * Arguments: + * x0 - Pointer to fiber_block + * x1 - Pointer to fiber_frame (contains cpu_state at offset 0) + * x2 - Pointer to tlb + * + * Returns (in x0): + * Interrupt number (reason for returning to caller) + */ +.global NAME(fiber_enter) +.type_compat fiber_enter,function +NAME(fiber_enter): + // Save callee-saved registers + stp x18, x19, [sp, #-0x80]! // 0x80 to make room for original _cpu + stp x20, x21, [sp, #0x10] + stp x22, x23, [sp, #0x20] + stp x24, x25, [sp, #0x30] + stp x26, x27, [sp, #0x40] + stp x28, x29, [sp, #0x50] + str lr, [sp, #0x60] + str x1, [sp, #0x70] // Save original _cpu for verification + + // Save SP for crash recovery: signal handler restores SP to this value + // so fiber_exit can correctly pop the callee-saved register frame. + mov x8, sp + str x8, [x1, #LOCAL_jit_exit_sp] + + // Setup gadget instruction pointer from block + add _pc, x0, #FIBER_BLOCK_code + + // _cpu is already x1 (frame pointer, cpu_state is at offset 0) + // _tlb needs to point to TLB_entries + add _tlb, x2, #TLB_entries + + // Jump to first gadget (gret equivalent) + gret + +/* + * fiber_ret_chain - Return from a block that wants to chain to another + * + * _pc contains either: + * - A fake_ip (bit 63 set): unchained, must return to main loop for dispatch + * - A block->code pointer (bit 63 clear): chained, can continue in JIT + * + * This is the hot path for block transitions. Staying in JIT avoids the + * expensive fiber_exit → main loop → fiber_enter round-trip. + */ +.global fiber_ret_chain +fiber_ret_chain: +#ifdef DISABLE_BLOCK_CHAINING + // Block chaining disabled — always return to main loop + // Clear last_block so the C main loop doesn't patch fake_ip values + // (patched values are host code pointers, not guest PCs) + str xzr, [_cpu, #LOCAL_last_block] + b fiber_ret +#else + // Check bit 63: if set, it's a fake_ip (unchained) → return to main loop + tbnz _pc, #63, fiber_ret + // Check if we've been poked (timer interrupt pending) + ldr x8, [_cpu, #CPU_poked_ptr] + ldrb w8, [x8] + cbnz w8, poke + // Adjacent-block fast path: if the target block immediately follows the + // source block in guest memory (target->addr == from->end_addr + 4) and + // both are on the same 4 KB page, the TLB mapping for the page cannot + // have changed since the source block was compiled (any mmap/munmap would + // have invalidated both blocks). Skip the mem_changes check and go + // directly to execution. This covers ~69 % of chained forward transitions. + ldr x9, [_cpu, #LOCAL_last_block] // x9 = from fiber_block* + cbz x9, fiber_ret_chain_memcheck // no prior block → full check + ldr x10, [x9, #FIBER_BLOCK_end_addr] // x10 = from->end_addr + sub x11, _pc, #FIBER_BLOCK_code // x11 = target fiber_block* + ldr x12, [x11, #FIBER_BLOCK_addr] // x12 = target->addr + // Adjacent: target->addr == from->end_addr + 4 + sub x12, x12, x10 + cmp x12, #4 + b.ne fiber_ret_chain_memcheck + // Same page: PAGE(from->end_addr) == PAGE(target->addr) + ldr x12, [x11, #FIBER_BLOCK_addr] // reload target->addr + eor x10, x10, x12 // XOR end_addr ^ target->addr + lsr x10, x10, #12 // non-zero iff different pages + cbnz x10, fiber_ret_chain_memcheck + // Adjacent same-page: safe to skip mem_changes, fall to execute + b fiber_ret_chain_execute +fiber_ret_chain_memcheck: + // Check if page table changed (mem_changes mismatch). + // On macOS, munmap+mmap reuses host virtual addresses, so stale TLB entries + // silently read/write wrong data (no SIGSEGV). Must return to main loop + // for TLB flush when the page table has changed. + ldr x8, [_tlb, #(-TLB_entries + 16)] // tlb->mem_changes (unsigned, at offset 16) + ldr x9, [_tlb, #-TLB_entries] // tlb->mmu + ldr x9, [x9, #16] // mmu->changes (uint64_t, at offset 16) + cmp w8, w9 // compare as 32-bit (mem_changes is unsigned) + b.ne poke // if changed, return to main loop for flush +fiber_ret_chain_execute: + // Optional block-stats probe for chained block-entry execution. This is + // measurement-only and runs only when ISH_ARM64_BLOCK_STATS is enabled. +#if __APPLE__ + adrp x8, NAME(arm64_block_stats_enabled)@GOTPAGE + ldr x8, [x8, NAME(arm64_block_stats_enabled)@GOTPAGEOFF] + ldrb w8, [x8] +#else + adrp x8, NAME(arm64_block_stats_enabled) + ldrb w8, [x8, #:lo12:NAME(arm64_block_stats_enabled)] +#endif + cbz w8, 1f + save_c + ldr x0, [_cpu, #LOCAL_last_block] + mov x1, _pc + bl NAME(arm64_block_stats_count_chained_entry) + restore_c +1: + // Record last_block for block chaining in main loop + sub x8, _pc, #FIBER_BLOCK_code + str x8, [_cpu, #LOCAL_last_block] + // Continue executing in JIT — this is the fast path + // Guard: check that the next gadget pointer is not null (stale/freed block) + ldr x8, [_pc], #8 + cbz x8, chain_null_gadget + br x8 +#endif + +chain_null_gadget: + // Null gadget pointer detected in chained block — the block was likely + // freed/jetsammed and its memory zeroed. Return to main loop safely. + // _pc was already incremented past the null entry by the post-index load. + // Recompute block pointer and load guest PC from block->addr. + sub x8, _pc, #(FIBER_BLOCK_code + 8) // undo post-increment to get block base + ldr x9, [x8, #FIBER_BLOCK_addr] + str x9, [_cpu, #CPU_pc] + str xzr, [_cpu, #LOCAL_last_block] // clear last_block to prevent further chaining + mov w0, #INT_GPF + b fiber_exit + +poke: + // Timer interrupt pending — load guest PC from block->addr and return + ldr x8, [_pc, #(-FIBER_BLOCK_code + FIBER_BLOCK_addr)] + str x8, [_cpu, #CPU_pc] + sub x8, _pc, #FIBER_BLOCK_code + str x8, [_cpu, #LOCAL_last_block] + // fallthrough to fiber_ret + +/* + * fiber_ret - Return from fiber with INT_NONE + */ +.global fiber_ret +fiber_ret: + mvn w0, wzr // w0 = -1 (INT_NONE) + // fallthrough to fiber_exit + +/* + * fiber_exit - Exit the fiber execution context + * + * Expected state: + * _tmp (x0) = interrupt number to return + * _cpu = pointer to cpu_state (already saved if needed) + * + * DEBUG: Store a marker value to help debug PC issues + * We store the _pc value (from control flow gadgets) to LOCAL_value + * so we can see what _pc was when we returned + */ +.global fiber_exit +fiber_exit: + // Restore callee-saved registers + ldr lr, [sp, #0x60] + ldp x28, x29, [sp, #0x50] + ldp x26, x27, [sp, #0x40] + ldp x24, x25, [sp, #0x30] + ldp x22, x23, [sp, #0x20] + ldp x20, x21, [sp, #0x10] + ldp x18, x19, [sp], #0x80 // 0x80 to match fiber_enter (includes saved _cpu) + + // x0 (_tmp) already contains return value + ret + +/* + * handle_read_miss - Handle a TLB read miss + * Returns: translated host address in x0 (0 = segfault) + * + * IMPORTANT: Save and restore callee-saved registers x19-x28 because + * the C code we call might use them. Our gadget code uses these registers + * to hold data across the TLB miss call. + */ +.global NAME(handle_read_miss) +NAME(handle_read_miss): + // Save callee-saved registers that gadgets might be using + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + save_c + sub x0, _tlb, #TLB_entries // pass tlb base, not tlb+entries + mov x1, x7 // guest address (64-bit) from _addr (x7) + mov x2, #0 // MEM_READ + bl NAME(tlb_handle_miss) + mov x20, x0 // save result in a callee-saved register + restore_c + mov x0, x20 // return result in x0 + + // Restore callee-saved registers + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + ret + +/* + * handle_write_miss - Handle a TLB write miss + * Returns: translated host address in x0 (0 = segfault) + * + * IMPORTANT: Save and restore callee-saved registers x19-x28 because + * the C code we call might use them. Our gadget code uses these registers + * to hold data across the TLB miss call. + */ +.global NAME(handle_write_miss) +NAME(handle_write_miss): + // Save callee-saved registers that gadgets might be using + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + // Store current JIT code stream pointer for watchpoint debugging + str _pc, [_cpu, #LOCAL_value] + save_c + sub x0, _tlb, #TLB_entries // pass tlb base, not tlb+entries + mov x1, x7 // guest address (64-bit) from _addr (x7) + mov x2, #1 // MEM_WRITE + bl NAME(tlb_handle_miss) + mov x20, x0 // save result in a callee-saved register + restore_c + mov x0, x20 // return result + + // Restore callee-saved registers + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + ret + +/* + * crosspage_load - Handle a load that crosses a page boundary + * + * Entry: x19 = size in bytes, _addr (x7) = guest address + * Exit: _addr (x7) points to LOCAL_value buffer with data loaded + * + * Calls __tlb_read_cross_page(tlb, addr, buf, size) to do the actual work. + * + * IMPORTANT: Save and restore callee-saved registers. + */ +.global NAME(crosspage_load) +NAME(crosspage_load): + // Save callee-saved registers (x19 has size, save it first to temp) + mov x8, x19 // save size to temp + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + save_c + sub x0, _tlb, #TLB_entries // x0 = tlb base + add x2, _cpu, #LOCAL_value // x2 = buffer for data + mov x1, x7 // x1 = guest address (64-bit) + mov x3, x8 // x3 = size (from temp) + bl NAME(__tlb_read_cross_page) + mov x20, x0 // save result + restore_c + + cbz x20, segfault_read_cp + str x7, [_cpu, #LOCAL_value_addr] // save guest address (64-bit) + add _addr, _cpu, #LOCAL_value // _addr points to buffer + + // Restore callee-saved registers + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + ret + +segfault_read_cp: + // Handle segfault for cross-page read + // First restore callee-saved registers + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + + ldr x8, [_tlb, #(-TLB_entries+TLB_segfault_addr)] + str x8, [_cpu, #CPU_segfault_addr] + strb wzr, [_cpu, #CPU_segfault_was_write] + ldr x8, [_cpu, #LOCAL_jit_saved_pc] + str x8, [_cpu, #CPU_pc] + mov w0, #INT_GPF + b fiber_exit + +/* + * crosspage_store - Handle a store that crosses a page boundary + * + * Entry: x19 = size in bytes, _addr (x7) = LOCAL_value buffer + * Exit: data from LOCAL_value written to guest memory + * + * Note: The guest address is in LOCAL_value_addr (saved earlier) + * + * IMPORTANT: Save and restore callee-saved registers. + */ +.global NAME(crosspage_store) +NAME(crosspage_store): + // Save callee-saved registers (x19 has size, save it first to temp) + mov x8, x19 // save size to temp + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + save_c + sub x0, _tlb, #TLB_entries // x0 = tlb base + add x2, _cpu, #LOCAL_value // x2 = buffer with data + ldr x1, [_cpu, #LOCAL_value_addr] // x1 = guest address (64-bit, saved earlier) + mov x3, x8 // x3 = size (from temp) + bl NAME(__tlb_write_cross_page) + mov x20, x0 + restore_c + + cbz x20, segfault_write_cp + + // Restore callee-saved registers + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + ret + +segfault_write_cp: + // Handle segfault for cross-page write + // First restore callee-saved registers + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + + ldr x8, [_tlb, #(-TLB_entries+TLB_segfault_addr)] + str x8, [_cpu, #CPU_segfault_addr] + mov w9, #1 + strb w9, [_cpu, #CPU_segfault_was_write] + ldr x8, [_cpu, #LOCAL_jit_saved_pc] + str x8, [_cpu, #CPU_pc] + mov w0, #INT_GPF + b fiber_exit + +/* + * Debug gadget: record guest PC for crash diagnosis + * Code stream: [gadget_set_pc addr][guest_pc (64-bit)] + */ +.gadget set_pc + ldr x8, [_pc] + str x8, [_cpu, #CPU_pc] + add _pc, _pc, #8 + gret + +/* + * Record the precise guest PC to retry if a host SIGSEGV/SIGBUS is raised while + * executing a faultable JIT memory access. This intentionally does not update + * CPU_pc, because normal successful block execution should keep CPU_pc at the + * block/branch dispatch PC. + * Code stream: [gadget_set_jit_saved_pc addr][guest_pc (64-bit)] + */ +.gadget set_jit_saved_pc + ldr x8, [_pc] + str x8, [_cpu, #LOCAL_jit_saved_pc] + add _pc, _pc, #8 + gret + +/* + * Gadgets for block termination + */ + +// gadget_interrupt - Generate an interrupt and exit +// Code stream: [gadget_interrupt addr][interrupt type (32-bit)] +.gadget interrupt + ldr w0, [_pc] // Load interrupt type from code stream + b fiber_exit + +// gadget_exit - Exit the block and return to dispatcher +// Code stream: [gadget_exit addr][next IP (64-bit)] +.gadget exit + ldr x8, [_pc] // Load next IP from code stream (64-bit) + str x8, [_cpu, #CPU_pc] // Store as guest PC + mvn w0, wzr // Return INT_NONE (-1) + b fiber_exit + +// Debug: trace gadget - calls C function to log registers at specific PCs +// Code stream: [gadget_trace addr][guest_pc (64-bit)] +.gadget trace + ldr x8, [_pc] // Load guest PC from stream + str x8, [_cpu, #CPU_pc] // Update guest PC for the trace function + + // Save callee-saved registers (gadgets use x19-x28) + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + save_c + mov x0, _cpu // arg0: cpu_state pointer + bl NAME(jit_trace_regs) + restore_c + + // Restore callee-saved registers + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + + add _pc, _pc, #8 // Skip past the 64-bit guest PC data + gret + +/* + * gadget_check_highbits - Fast check for dirty bits 32-63 in guest registers + * + * All guest register values should fit in 32 bits in the current memory layout. + * If any register has bits 32+ set, it indicates an emulation bug. + * + * Fast path (~35 cycles): OR together bits 32-63 of all 32 GP regs (x0-x30 + SP). + * If all zero, skip ahead. No function call overhead. + * + * Slow path (detection only): Call jit_highbit_alert(cpu) to log the offender. + * + * Code stream: [gadget_check_highbits addr][guest_pc (64-bit)] + */ +.gadget check_highbits + // Fast path: OR bits 32-63 of all guest registers + // x0-x30 are at [_cpu + CPU_x0] through [_cpu + CPU_x0 + 30*8] + // SP is at [_cpu + CPU_sp] + // Load pairs and accumulate high bits via OR + ldp x9, x10, [_cpu, #CPU_x0] // x0, x1 + orr x9, x9, x10 + ldp x10, x11, [_cpu, #(CPU_x0 + 16)] // x2, x3 + orr x9, x9, x10 + orr x9, x9, x11 + ldp x10, x11, [_cpu, #(CPU_x0 + 32)] // x4, x5 + orr x9, x9, x10 + orr x9, x9, x11 + ldp x10, x11, [_cpu, #(CPU_x0 + 48)] // x6, x7 + orr x9, x9, x10 + orr x9, x9, x11 + ldp x10, x11, [_cpu, #(CPU_x0 + 64)] // x8, x9 + orr x9, x9, x10 + orr x9, x9, x11 + ldp x10, x11, [_cpu, #(CPU_x0 + 80)] // x10, x11 + orr x9, x9, x10 + orr x9, x9, x11 + ldp x10, x11, [_cpu, #(CPU_x0 + 96)] // x12, x13 + orr x9, x9, x10 + orr x9, x9, x11 + ldp x10, x11, [_cpu, #(CPU_x0 + 112)] // x14, x15 + orr x9, x9, x10 + orr x9, x9, x11 + ldp x10, x11, [_cpu, #(CPU_x0 + 128)] // x16, x17 + orr x9, x9, x10 + orr x9, x9, x11 + ldp x10, x11, [_cpu, #(CPU_x0 + 144)] // x18, x19 + orr x9, x9, x10 + orr x9, x9, x11 + ldp x10, x11, [_cpu, #(CPU_x0 + 160)] // x20, x21 + orr x9, x9, x10 + orr x9, x9, x11 + ldp x10, x11, [_cpu, #(CPU_x0 + 176)] // x22, x23 + orr x9, x9, x10 + orr x9, x9, x11 + ldp x10, x11, [_cpu, #(CPU_x0 + 192)] // x24, x25 + orr x9, x9, x10 + orr x9, x9, x11 + ldp x10, x11, [_cpu, #(CPU_x0 + 208)] // x26, x27 + orr x9, x9, x10 + orr x9, x9, x11 + ldp x10, x11, [_cpu, #(CPU_x0 + 224)] // x28, x29 + orr x9, x9, x10 + orr x9, x9, x11 + ldr x10, [_cpu, #(CPU_x0 + 240)] // x30 + orr x9, x9, x10 + ldr x10, [_cpu, #CPU_sp] // SP + orr x9, x9, x10 + + // Check if any bit 32+ is set + lsr x9, x9, #32 + cbnz x9, check_highbits_alert + + // Fast path: no dirty bits, skip past the 64-bit guest PC data + add _pc, _pc, #8 + gret + +check_highbits_alert: + // Slow path: save state and call C function + ldr x8, [_pc] + str x8, [_cpu, #CPU_pc] // Set guest PC for the alert function + + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + save_c + mov x0, _cpu + bl NAME(jit_highbit_alert) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + + add _pc, _pc, #8 + gret + +// Convenience gadgets for specific interrupts +.gadget syscall + mov w0, #INT_SYSCALL + b fiber_exit + +.gadget undefined + mov w0, #INT_UNDEFINED + b fiber_exit + +/* + * jit_crash_trampoline - Signal handler redirects PC here after JIT SIGSEGV + * + * The crash_handler has already: + * 1. Written segfault_addr and segfault_was_write to cpu_state via _cpu (x1) + * 2. Restored cpu->pc to the block start PC (from jit_saved_pc TLS) + * 3. Restored SP from frame->jit_exit_sp so fiber_exit can pop correctly + * 4. Set x0 to a crash marker value + * + * We just need to return INT_GPF to the dispatch loop via fiber_exit. + */ +.global NAME(jit_crash_trampoline) +NAME(jit_crash_trampoline): + mov w0, #0x100 // INT_JIT_CRASH + b fiber_exit diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/gadgets.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/gadgets.h new file mode 100644 index 0000000000..ccba4adb44 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/gadgets.h @@ -0,0 +1,321 @@ +#include "../../gadgets-generic.h" +#include "cpu-offsets.h" + +// === DEBUG ISOLATION SWITCHES === +// Uncomment to disable specific JIT optimizations for debugging: +// #define DISABLE_RET_CACHE 1 // RET always returns to main loop +// #define DISABLE_BLOCK_CHAINING 1 // All branches return to main loop +// #define ENABLE_HIGHBIT_CHECK 1 // Check for dirty bits 32-63 after each insn +// #define ENABLE_WRITE_WATCHPOINT 1 // Check every store against watched page +// ================================= + +// Interrupt types (from emu/interrupt.h) +#define INT_NONE -1 +#define INT_DIV 0 +#define INT_DEBUG 1 +#define INT_NMI 2 +#define INT_BREAKPOINT 3 +#define INT_OVERFLOW 4 +#define INT_BOUND 5 +#define INT_UNDEFINED 6 +#define INT_FPU 7 +#define INT_DOUBLE 8 +#define INT_GPF 13 +#define INT_TIMER 32 +#define INT_SYSCALL 0x80 + +/* + * ARM64-on-ARM64 Register Mapping + * + * When running ARM64 guest code on an ARM64 host, we can use a near-direct + * mapping of registers. However, we still need to reserve some registers + * for internal use: + * + * Host registers: + * x0-x7 - Scratch / function arguments + * x8 - Indirect result location (scratch for us) + * x9-x15 - Caller-saved temporaries + * x16-x17 - IP0/IP1, linker scratch + * x18 - Platform register (reserved on some platforms) + * x19-x28 - Callee-saved (we use these for guest state) + * x29 - Frame pointer + * x30 - Link register + * sp - Stack pointer + * + * Guest register mapping: + * Since we need to preserve guest x0-x30 plus SP and PC, we use + * a combination of in-memory storage and cached hot registers. + */ + +// CPU state pointer (always in x1 for ARM64 guest gadgets) +_cpu .req x1 +_tlb .req x2 + +// Current instruction pointer (guest PC) +_pc .req x28 + +// Temporary registers for gadget use +_tmp .req x0 +_tmp2 .req x8 +_addr .req x7 // Changed from x3/x4 to x7 to avoid conflict with guest low registers + +// For compatibility, we use memory-based access for most guest registers +// Only a few hot registers are cached in host registers + +.extern fiber_exit + +.macro .gadget name + .global NAME(gadget_\()\name) + .align 4 + NAME(gadget_\()\name) : +.endm + +.macro gret pop=0 +.if \pop == 0 + ldr x8, [_pc], #8 +.else + ldr x8, [_pc, \pop*8]! + add _pc, _pc, 8 +.endif + br x8 +.endm + +/* + * Memory Access Helpers + * + * These macros handle TLB lookups and memory access for the guest. + */ +.irp type, read,write + +.macro \type\()_prep size, id +#ifdef ENABLE_WRITE_WATCHPOINT + .ifc \type,write + // Write watchpoint: compare guest page against watched page + // x7 = guest address at this point (before TLB translation) + // g_watch_page_val is loaded from a nearby literal pool + adrp x8, NAME(g_watch_page_val)@PAGE + ldr x8, [x8, NAME(g_watch_page_val)@PAGEOFF] + cbz x8, 9f // skip if no watchpoint set + and x9, x7, #0xfffffffffffff000 // guest page + cmp x9, x8 + b.eq watch_hit_\id +9: + .endif +#endif + // Cross-page check: if page offset > (0x1000 - access_size), need special handling + and w8, w7, #0xfff + cmp x8, #(0x1000-(\size/8)) + .ifc \type,read + b.hi crosspage_load_\id + .else + b.hi crosspage_write_prep_\id + .endif + + // Extract page-aligned address (48-bit address space, clear low 12 bits) + and x8, x7, #0xfffffffffffff000 + .ifc \type,write + str x8, [_tlb, #(-TLB_entries+TLB_dirty_page)] + .endif + + // TLB index calculation: (addr >> 12) ^ (addr >> 26) masked to TLB_SIZE-1 + ubfx x9, x7, #12, #13 // (addr >> 12) & 0x1fff (TLB_BITS=13) + eor x9, x9, x7, lsr #25 // XOR with (addr >> 25) = (addr >> (12+13)) + and w9, w9, #0x1fff // mask to TLB_SIZE-1 + lsl x9, x9, #5 + add x9, x9, _tlb + + .ifc \type,read + ldr x10, [x9, #TLB_ENTRY_page] + .else + ldr x10, [x9, #TLB_ENTRY_page_if_writable] + .endif + + cmp x8, x10 + b.ne handle_miss_\id + + // Coherence check: this cached entry's host pointer is only valid while + // mmu->changes still equals the generation captured when it was filled. + // If another thread remapped the page (CoW/mmap/munmap) mmu->changes has + // advanced and data_minus_addr points at the stale host backing — treat + // it as a miss and re-translate. Fixes JSC reading a null methodTable / + // stale Structure after a concurrent GC/allocator remap. + ldr x10, [x9, #TLB_ENTRY_gen] + ldr x8, [_tlb, #(-TLB_entries+TLB_mmu)] + ldr x8, [x8, #MMU_changes] + cmp x10, x8 + b.ne handle_miss_\id + + ldr x10, [x9, #TLB_ENTRY_data_minus_addr] + + // NOTE: segfault_addr is NOT stored here for performance. + // On JIT crash (stale TLB SIGSEGV), crash_handler reconstructs + // guest_addr = (x7 - x10) & 0xffffffffffff from ucontext registers. + add x7, x10, x7 // host_addr = data_minus_addr + guest_addr +back_\id: +.endm + +.macro \type\()_bullshit size, id +handle_miss_\id : + bl NAME(handle_\type\()_miss) + cbz x0, segfault_\type\()_\id + mov _addr, x0 + b back_\id +segfault_\type\()_\id : + ldr x8, [_tlb, #(-TLB_entries+TLB_segfault_addr)] + str x8, [_cpu, #CPU_segfault_addr] + .ifc \type,read + strb wzr, [_cpu, #CPU_segfault_was_write] + .else + mov w9, #1 + strb w9, [_cpu, #CPU_segfault_was_write] + .endif + // Retry the faulting guest memory instruction, not the containing block + // start. Earlier gadgets in the block may already have mutated registers. + ldr x8, [_cpu, #LOCAL_jit_saved_pc] + str x8, [_cpu, #CPU_pc] + str _pc, [_cpu, #LOCAL_value] + mov w0, #INT_GPF + b fiber_exit +crosspage_load_\id : + mov x19, #(\size/8) + bl NAME(crosspage_load) + b back_\id +.ifc \type,write +crosspage_write_prep_\id : + str x7, [_cpu, #LOCAL_value_addr] + add _addr, _cpu, #LOCAL_value + b back_\id +crosspage_store_\id : + mov x19, #(\size/8) + bl NAME(crosspage_store) + b back_write_done_\id +.endif +#ifdef ENABLE_WRITE_WATCHPOINT +.ifc \type,write +watch_hit_\id : + // Write watchpoint hit: guest addr in x7 matches watched page + // Save all state and call C handler + // x24 = saved guest addr (set by caller before write_prep) + // _pc = current position in code stream + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + save_c + mov x0, _cpu // arg0: cpu_state + mov x1, x7 // arg1: guest store address (still in x7) + mov x2, _pc // arg2: code stream pointer (for PC recovery) + bl NAME(jit_watch_write_hit) + restore_c + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + // Fall through to the normal write_prep path (re-do the cross-page check) + and w8, w7, #0xfff + cmp x8, #(0x1000-(\size/8)) + b.hi crosspage_write_prep_\id + and x8, x7, #0xfffffffffffff000 + str x8, [_tlb, #(-TLB_entries+TLB_dirty_page)] + ubfx x9, x7, #12, #13 + eor x9, x9, x7, lsr #25 + and w9, w9, #0x1fff + lsl x9, x9, #5 + add x9, x9, _tlb + ldr x10, [x9, #TLB_ENTRY_page_if_writable] + cmp x8, x10 + b.ne handle_miss_\id + ldr x10, [x9, #TLB_ENTRY_data_minus_addr] + add x7, x10, x7 + b back_\id +.endif +#endif +.endm + +.endr + +.macro write_done size, id + add x8, _cpu, #LOCAL_value + cmp x8, x7 + b.eq crosspage_store_\id +back_write_done_\id : +.endm + +/* + * Guest Register Access Macros + * + * For ARM64 guest, we access registers directly from the cpu_state structure. + */ +.macro load_guest_reg host_reg, guest_idx + ldr \host_reg, [_cpu, #(CPU_x0 + \guest_idx * 8)] +.endm + +.macro store_guest_reg host_reg, guest_idx + str \host_reg, [_cpu, #(CPU_x0 + \guest_idx * 8)] +.endm + +.macro load_guest_sp host_reg + ldr \host_reg, [_cpu, #CPU_sp] +.endm + +.macro store_guest_sp host_reg + str \host_reg, [_cpu, #CPU_sp] +.endm + +.macro load_guest_pc host_reg + ldr \host_reg, [_cpu, #CPU_pc] +.endm + +.macro store_guest_pc host_reg + str \host_reg, [_cpu, #CPU_pc] +.endm + +/* + * Flag manipulation + * Note: These must not use x8-x15 as they might be in use by calling code + */ +.macro load_flags + ldr w17, [_cpu, #CPU_nzcv] + msr nzcv, x17 +.endm + +.macro store_flags + mrs x17, nzcv + str w17, [_cpu, #CPU_nzcv] +.endm + +/* + * Context save/restore for calling C functions + * Must save all caller-saved registers (x0-x18) + LR + */ +.macro save_c + stp x0, x1, [sp, -0xa0]! + stp x2, x3, [sp, 0x10] + stp x4, x5, [sp, 0x20] + stp x6, x7, [sp, 0x30] + stp x8, x9, [sp, 0x40] + stp x10, x11, [sp, 0x50] + stp x12, x13, [sp, 0x60] + stp x14, x15, [sp, 0x70] + stp x16, x17, [sp, 0x80] + stp x18, lr, [sp, 0x90] +.endm + +.macro restore_c + ldp x18, lr, [sp, 0x90] + ldp x16, x17, [sp, 0x80] + ldp x14, x15, [sp, 0x70] + ldp x12, x13, [sp, 0x60] + ldp x10, x11, [sp, 0x50] + ldp x8, x9, [sp, 0x40] + ldp x6, x7, [sp, 0x30] + ldp x4, x5, [sp, 0x20] + ldp x2, x3, [sp, 0x10] + ldp x0, x1, [sp], 0xa0 +.endm + +# vim: ft=gas diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/math.S b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/math.S new file mode 100644 index 0000000000..e9efa78a74 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/math.S @@ -0,0 +1,16179 @@ +/* + * ARM64 Guest Data Processing Gadgets + * + * These gadgets implement arithmetic, logical, and move operations. + * Parameters are packed in the code stream following the gadget address. + */ + +#include "gadgets.h" + +.text + +/* + * Register load/store helpers + * These load/store guest registers from/to cpu_state + */ + +// Load a guest register into _tmp (x0) +// Code stream: [gadget addr][reg_index] +.gadget load_reg + ldr x8, [_pc] + add _pc, _pc, #8 + and x8, x8, #0x1f + add x9, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + ldr _tmp, [x9, x8, lsl #3] + gret +1: mov _tmp, #0 // XZR + gret + +// Store _tmp (x0) to a guest register +// Code stream: [gadget addr][reg_index] +.gadget store_reg + ldr x8, [_pc] + and x8, x8, #0x1f + add x9, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f // XZR - discard + str _tmp, [x9, x8, lsl #3] +1: add _pc, _pc, #8 + gret + +// Store _addr (x7) to guest register - used for writeback in pre/post-indexed addressing +.gadget store_addr_to_reg + ldr x8, [_pc] + and x8, x8, #0x1f + add x9, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f // XZR/SP - handle specially + // For regular registers, store 64-bit address (ARM64 guest uses 64-bit addresses) + str _addr, [x9, x8, lsl #3] + b 2f +1: // For x31, update SP (mask to 48 bits) + and x9, _addr, #0xffffffffffff + str x9, [_cpu, #CPU_sp] +2: add _pc, _pc, #8 + gret + +/* + * Move wide immediate (MOVZ, MOVK, MOVN) + * Code stream: [gadget addr][rd | hw<<8 | imm16<<16 | sf<<32] + */ + +// MOVZ - Move wide with zeros +.gadget movz + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #2 // hw + ubfx x11, x8, #16, #16 // imm16 + ubfx x12, x8, #32, #1 // sf + + // Shift imm16 by hw*16 + lsl x10, x10, #4 // hw * 16 + lsl x11, x11, x10 // imm16 << (hw*16) + + // For 32-bit, zero-extend + cbz x12, 1f + b 2f +1: and x11, x11, #0xffffffff +2: + // Store to register + add x13, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 3f + str x11, [x13, x9, lsl #3] +3: gret + +// MOVK - Move wide with keep +.gadget movk + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #2 // hw + ubfx x11, x8, #16, #16 // imm16 + ubfx x12, x8, #32, #1 // sf + + // Load current value + add x13, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 3f + ldr x14, [x13, x9, lsl #3] + + // For 32-bit operations, only keep lower 32 bits of current value + cbz x12, 1f + b 2f +1: and x14, x14, #0xffffffff +2: + + // Create mask for the 16-bit field + lsl x10, x10, #4 // hw * 16 + mov x15, #0xffff + lsl x15, x15, x10 // mask at position + lsl x11, x11, x10 // value at position + + // Clear and insert + bic x14, x14, x15 + orr x14, x14, x11 + + // For 32-bit, zero-extend result (clear upper 32 bits) + cbz x12, 4f + b 5f +4: and x14, x14, #0xffffffff +5: + + // Store back + str x14, [x13, x9, lsl #3] +3: gret + +// MOVN - Move wide with NOT +.gadget movn + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #2 // hw + ubfx x11, x8, #16, #16 // imm16 + ubfx x12, x8, #32, #1 // sf + + lsl x10, x10, #4 + lsl x11, x11, x10 + mvn x11, x11 // NOT + + cbz x12, 1f + b 2f +1: and x11, x11, #0xffffffff +2: + add x13, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 3f + str x11, [x13, x9, lsl #3] +3: gret + +/* + * ADR/ADRP - PC-relative address + * Code stream: [gadget addr][rd(0:4) | target(8:55)] + * Target is a 48-bit guest address packed in bits 8-55. + */ +.gadget adr + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #48 // target (48-bit) + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + str x10, [x11, x9, lsl #3] + gret +1: gret + +/* + * ADD/SUB immediate + * Code stream: [gadget addr][rd | rn<<8 | imm12<<16 | sf<<28 | S<<29] + */ +.gadget add_imm + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + ubfx x12, x8, #28, #1 // sf (0=32-bit, 1=64-bit) + ubfx x13, x8, #29, #1 // S (set flags) + ubfx x17, x8, #30, #1 // sh (0=no shift, 1=LSL #12) + + // Apply shift if sh=1 + cbz x17, 0f + lsl x11, x11, #12 +0: + // Load Rn (or SP if rn == 31) + add x14, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: ldr x15, [_cpu, #CPU_sp] +2: + // Check if we need to set flags + cbz x13, add_imm_no_flags + + // ADDS - set flags. Use adds to generate correct NZCV + cbz x12, add_imm_adds_32 + // 64-bit ADDS + adds x16, x15, x11 + b add_imm_store_flags + +add_imm_adds_32: + // 32-bit ADDS + adds w16, w15, w11 + // Result is already zero-extended + +add_imm_store_flags: + store_flags + b add_imm_store_result + +add_imm_no_flags: + // ADD without flags + add x16, x15, x11 + cbz x12, 3f + b add_imm_store_result +3: and x16, x16, #0xffffffff + +add_imm_store_result: + cmp x9, #31 + b.eq 5f + str x16, [x14, x9, lsl #3] + gret +5: // rd == 31 (XZR or SP) + cbz x13, 7f // If not setting flags, write to SP + gret // If setting flags (CMN), discard result +7: // Mask to 48 bits before writing to SP + and x16, x16, #0xffffffffffff + str x16, [_cpu, #CPU_sp] + gret + +.gadget sub_imm + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + ubfx x12, x8, #28, #1 // sf (0=32-bit, 1=64-bit) + ubfx x13, x8, #29, #1 // S (set flags) + ubfx x17, x8, #30, #1 // sh (0=no shift, 1=LSL #12) + + // Apply shift if sh=1 + cbz x17, 0f + lsl x11, x11, #12 +0: + add x14, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: ldr x15, [_cpu, #CPU_sp] +2: + // Check if we need to set flags + cbz x13, sub_imm_no_flags + + // SUBS - set flags. Use subs to generate correct NZCV + cbz x12, sub_imm_subs_32 + // 64-bit SUBS + subs x16, x15, x11 + b sub_imm_store_flags + +sub_imm_subs_32: + // 32-bit SUBS + subs w16, w15, w11 + // Result is already zero-extended + +sub_imm_store_flags: + store_flags + b sub_imm_store_result + +sub_imm_no_flags: + // SUB without flags + sub x16, x15, x11 + cbz x12, 3f + b sub_imm_store_result +3: and x16, x16, #0xffffffff + +sub_imm_store_result: + cmp x9, #31 + b.eq 5f + str x16, [x14, x9, lsl #3] + gret +5: // rd == 31 (XZR or SP) + cbz x13, 7f // If not setting flags, write to SP + gret // If setting flags (CMP), discard result +7: // Mask to 48 bits before writing to SP + and x16, x16, #0xffffffffffff + str x16, [_cpu, #CPU_sp] + gret + +/* + * ADD/SUB register + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | sf<<24 | S<<25] + */ +// ADD (register, with optional shift) +// Code stream: [gadget addr][rd | rn<<8 | rm<<16 | sf<<24 | S<<25 | shift_type<<26 | imm6<<32] +.gadget add_reg + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + // ubfx x13, x8, #25, #1 // S (not used yet for flag setting) + ubfx x17, x8, #26, #2 // shift_type + lsr x3, x8, #32 // imm6 (shift amount) + and x3, x3, #0x3f + + add x14, _cpu, #CPU_x0 + + // Load Rn (XZR if rn == 31) + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + // Load Rm + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + // Apply shift to Rm + // For 32-bit ops (sf=0), ASR must use w-register to sign-extend correctly + cbz x3, 5f // No shift if imm6 == 0 + cmp x17, #0 // LSL + b.eq shift_lsl + cmp x17, #1 // LSR + b.eq shift_lsr + cmp x17, #2 // ASR + b.eq shift_asr + b 5f // ROR not valid for ADD +shift_lsl: + cbz x12, add_shift_lsl32 + lsl x16, x16, x3 + b 5f +add_shift_lsl32: + lsl w16, w16, w3 + b 5f +shift_lsr: + cbz x12, add_shift_lsr32 + lsr x16, x16, x3 + b 5f +add_shift_lsr32: + lsr w16, w16, w3 + b 5f +shift_asr: + cbz x12, add_shift_asr32 + asr x16, x16, x3 + b 5f +add_shift_asr32: + asr w16, w16, w3 +5: + // Add + add x17, x15, x16 + + // 32-bit + cbz x12, 6f + b 7f +6: and x17, x17, #0xffffffff +7: + // Store + cmp x9, #31 + b.eq 8f + str x17, [x14, x9, lsl #3] + gret +8: // rd == 31 (SP) + cbz x12, 9f + b 10f +9: and x17, x17, #0xffffffff +10: // Mask to 48 bits before writing to SP + and x17, x17, #0xffffffffffff + str x17, [_cpu, #CPU_sp] + gret + +// SUB (register, with optional shift) +// Code stream: [gadget addr][rd | rn<<8 | rm<<16 | sf<<24 | S<<25 | shift_type<<26 | imm6<<32] +.gadget sub_reg + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + // ubfx x13, x8, #25, #1 // S (not used yet for flag setting) + ubfx x17, x8, #26, #2 // shift_type + lsr x3, x8, #32 // imm6 (shift amount) + and x3, x3, #0x3f + + add x14, _cpu, #CPU_x0 + + // Load Rn (XZR if rn == 31) + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + // Load Rm + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + // Apply shift to Rm + // For 32-bit ops (sf=0), ASR must use w-register to sign-extend correctly + cbz x3, 5f // No shift if imm6 == 0 + cmp x17, #0 // LSL + b.eq sub_shift_lsl + cmp x17, #1 // LSR + b.eq sub_shift_lsr + cmp x17, #2 // ASR + b.eq sub_shift_asr + b 5f // ROR not valid for SUB +sub_shift_lsl: + cbz x12, sub_shift_lsl32 + lsl x16, x16, x3 + b 5f +sub_shift_lsl32: + lsl w16, w16, w3 + b 5f +sub_shift_lsr: + cbz x12, sub_shift_lsr32 + lsr x16, x16, x3 + b 5f +sub_shift_lsr32: + lsr w16, w16, w3 + b 5f +sub_shift_asr: + cbz x12, sub_shift_asr32 + asr x16, x16, x3 + b 5f +sub_shift_asr32: + asr w16, w16, w3 +5: + // Subtract + sub x17, x15, x16 + + // 32-bit + cbz x12, 6f + b 7f +6: and x17, x17, #0xffffffff +7: + // Store + cmp x9, #31 + b.eq 8f + str x17, [x14, x9, lsl #3] + gret +8: // rd == 31 (SP) + cbz x12, 9f + b 10f +9: and x17, x17, #0xffffffff +10: // Mask to 48 bits before writing to SP + and x17, x17, #0xffffffffffff + str x17, [_cpu, #CPU_sp] + gret + +/* + * ADDS (register with shift) - sets NZCV flags + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | sf<<24 | S<<25 | shift_type<<26 | imm6<<32] + * Used for: ADDS, CMN (when rd=XZR) + */ +.gadget adds_reg + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + ubfx x17, x8, #26, #2 // shift_type + lsr x3, x8, #32 + and x3, x3, #0x3f // imm6 + + add x14, _cpu, #CPU_x0 + + // Load Rn (XZR if rn == 31, NOT SP - ADDS uses zero register) + // Note: For ADDS/SUBS with S flag set, x31 is XZR, not SP + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 // XZR for ADDS (not SP) +2: + // Load Rm (XZR if rm == 31) + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + // Apply shift + // For 32-bit ops (sf=0), ASR must use w-register to sign-extend correctly + cbz x3, 5f + cmp x17, #0 + b.eq adds_shift_lsl + cmp x17, #1 + b.eq adds_shift_lsr + cmp x17, #2 + b.eq adds_shift_asr + b 5f +adds_shift_lsl: + cbz x12, adds_shift_lsl32 + lsl x16, x16, x3 + b 5f +adds_shift_lsl32: + lsl w16, w16, w3 + b 5f +adds_shift_lsr: + cbz x12, adds_shift_lsr32 + lsr x16, x16, x3 + b 5f +adds_shift_lsr32: + lsr w16, w16, w3 + b 5f +adds_shift_asr: + cbz x12, adds_shift_asr32 + asr x16, x16, x3 + b 5f +adds_shift_asr32: + asr w16, w16, w3 +5: + // Perform add and set flags - use x3 for result since store_flags clobbers x17 + cbz x12, adds_32bit + // 64-bit: adds sets flags directly + adds x3, x15, x16 + b adds_store_flags + +adds_32bit: + // 32-bit: need to use 32-bit operands for correct flag generation + adds w3, w15, w16 + // Result is already zero-extended + +adds_store_flags: + // Store NZCV flags + store_flags + + // Store result + cmp x9, #31 + b.eq 6f + str x3, [x14, x9, lsl #3] +6: gret + +/* + * SUBS (register with shift) - sets NZCV flags + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | sf<<24 | S<<25 | shift_type<<26 | imm6<<32] + * Used for: SUBS, CMP (when rd=XZR) + */ +.gadget subs_reg + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + ubfx x17, x8, #26, #2 // shift_type + lsr x3, x8, #32 + and x3, x3, #0x3f // imm6 + + add x14, _cpu, #CPU_x0 + + // Load Rn (XZR if rn == 31, NOT SP - SUBS uses zero register) + // Note: For SUBS/ADDS with S flag set, x31 is XZR, not SP + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 // XZR for SUBS (not SP) +2: + // Load Rm (XZR if rm == 31) + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + // Apply shift + // For 32-bit ops (sf=0), ASR must use w-register to sign-extend correctly + cbz x3, 5f + cmp x17, #0 + b.eq subs_shift_lsl + cmp x17, #1 + b.eq subs_shift_lsr + cmp x17, #2 + b.eq subs_shift_asr + b 5f +subs_shift_lsl: + cbz x12, subs_shift_lsl32 + lsl x16, x16, x3 + b 5f +subs_shift_lsl32: + lsl w16, w16, w3 + b 5f +subs_shift_lsr: + cbz x12, subs_shift_lsr32 + lsr x16, x16, x3 + b 5f +subs_shift_lsr32: + lsr w16, w16, w3 + b 5f +subs_shift_asr: + cbz x12, subs_shift_asr32 + asr x16, x16, x3 + b 5f +subs_shift_asr32: + asr w16, w16, w3 +5: + // Perform sub and set flags - use x3 for result since store_flags clobbers x17 + cbz x12, subs_32bit + // 64-bit: subs sets flags directly + subs x3, x15, x16 + b subs_store_flags + +subs_32bit: + // 32-bit: need to use 32-bit operands for correct flag generation + subs w3, w15, w16 + // Result is already zero-extended + +subs_store_flags: + store_flags + + // Store result + cmp x9, #31 + b.eq 6f + str x3, [x14, x9, lsl #3] +6: gret + +/* + * ADC (register) - add with carry, optional flag update + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | sf<<24 | S<<25] + * Used for: ADC, ADCS + */ +.gadget adc_reg + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + ubfx x13, x8, #25, #1 // S (update flags) + + add x14, _cpu, #CPU_x0 + + // Load Rn + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + // Load Rm + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + // Load NZCV for carry-in + load_flags + + cbz x12, adc_32bit + // 64-bit + cbz x13, adc_64_noflags + adcs x3, x15, x16 + b adc_store_flags +adc_64_noflags: + adc x3, x15, x16 + b adc_store + +adc_32bit: + cbz x13, adc_32_noflags + adcs w3, w15, w16 + b adc_store_flags +adc_32_noflags: + adc w3, w15, w16 + +adc_store_flags: + // Store NZCV flags if updated + cbz x13, adc_store + store_flags + +adc_store: + cmp x9, #31 + b.eq adc_done + str x3, [x14, x9, lsl #3] +adc_done: + gret + +/* + * SBC (register) - subtract with carry, optional flag update + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | sf<<24 | S<<25] + * Used for: SBC, SBCS + */ +.gadget sbc_reg + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + ubfx x13, x8, #25, #1 // S (update flags) + + add x14, _cpu, #CPU_x0 + + // Load Rn + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + // Load Rm + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + // Load NZCV for carry-in + load_flags + + cbz x12, sbc_32bit + // 64-bit + cbz x13, sbc_64_noflags + sbcs x3, x15, x16 + b sbc_store_flags +sbc_64_noflags: + sbc x3, x15, x16 + b sbc_store + +sbc_32bit: + cbz x13, sbc_32_noflags + sbcs w3, w15, w16 + b sbc_store_flags +sbc_32_noflags: + sbc w3, w15, w16 + +sbc_store_flags: + // Store NZCV flags if updated + cbz x13, sbc_store + store_flags + +sbc_store: + cmp x9, #31 + b.eq sbc_done + str x3, [x14, x9, lsl #3] +sbc_done: + gret + +/* + * Logical register operations + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | sf<<24 | S<<25] + */ +.gadget and_reg + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + ubfx x13, x8, #25, #1 // S (set flags) + ubfx x19, x8, #26, #1 // N (invert rm for BIC) + + add x14, _cpu, #CPU_x0 + + // Load rn (or 0 if rn==31) + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + // Load rm (or 0 if rm==31) + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + // If N=1 (BIC/BICS), invert rm + cbz x19, and_reg_no_invert + mvn x16, x16 +and_reg_no_invert: + + // Check S flag - if set, use ands to set flags + cbz x13, and_reg_no_flags + + // ANDS/BICS - set flags (use x3 for result since store_flags clobbers x17) + cbz x12, and_reg_ands_32 + ands x3, x15, x16 + b and_reg_store_flags +and_reg_ands_32: + ands w3, w15, w16 +and_reg_store_flags: + store_flags + mov x17, x3 + b and_reg_store_result + +and_reg_no_flags: + // AND/BIC - no flags + and x17, x15, x16 + cbz x12, 5f + b and_reg_store_result +5: and x17, x17, #0xffffffff + +and_reg_store_result: + cmp x9, #31 + b.eq 7f + str x17, [x14, x9, lsl #3] +7: gret + +// AND/ANDS (shifted register) +// param[0]: rd(0-4), rn(8-12), rm(16-20), sf(24), S(25), N(26), shift_type(27-28) +// param[1]: shift_amount (imm6) +.gadget and_reg_shifted + ldr x8, [_pc] + ldr x20, [_pc, #8] // shift_amount + add _pc, _pc, #16 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + ubfx x13, x8, #25, #1 // S (set flags) + ubfx x19, x8, #26, #1 // N (invert rm for BIC) + ubfx x21, x8, #27, #2 // shift_type + + add x14, _cpu, #CPU_x0 + + // Load rn (or 0 if rn==31) + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + // Load rm (or 0 if rm==31) + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + // If 32-bit, use W operations for shifts + cbz x12, and_shifted_32 + + // 64-bit shift + cbz x20, and_shifted_no_shift64 + cmp x21, #0 + b.eq and_shift_lsl64 + cmp x21, #1 + b.eq and_shift_lsr64 + cmp x21, #2 + b.eq and_shift_asr64 + ror x16, x16, x20 + b and_shifted_no_shift64 +and_shift_lsl64: + lsl x16, x16, x20 + b and_shifted_no_shift64 +and_shift_lsr64: + lsr x16, x16, x20 + b and_shifted_no_shift64 +and_shift_asr64: + asr x16, x16, x20 + +and_shifted_no_shift64: + // If N=1 (BIC/BICS), invert rm + cbz x19, and_shifted_no_invert64 + mvn x16, x16 +and_shifted_no_invert64: + cbz x13, and_shifted_no_flags64 + ands x3, x15, x16 + store_flags + mov x17, x3 + b and_shifted_store +and_shifted_no_flags64: + and x17, x15, x16 + b and_shifted_store + +and_shifted_32: + cbz x20, and_shifted_no_shift32 + cmp x21, #0 + b.eq and_shift_lsl32 + cmp x21, #1 + b.eq and_shift_lsr32 + cmp x21, #2 + b.eq and_shift_asr32 + ror w16, w16, w20 + b and_shifted_no_shift32 +and_shift_lsl32: + lsl w16, w16, w20 + b and_shifted_no_shift32 +and_shift_lsr32: + lsr w16, w16, w20 + b and_shifted_no_shift32 +and_shift_asr32: + asr w16, w16, w20 + +and_shifted_no_shift32: + cbz x19, and_shifted_no_invert32 + mvn w16, w16 +and_shifted_no_invert32: + cbz x13, and_shifted_no_flags32 + ands w3, w15, w16 + store_flags + mov w17, w3 + b and_shifted_store +and_shifted_no_flags32: + and w17, w15, w16 + +and_shifted_store: + cmp x9, #31 + b.eq 7f + str x17, [x14, x9, lsl #3] +7: gret + +// ORR (shifted register) +// param[0]: rd(0-4), rn(8-12), rm(16-20), sf(24), N(26), shift_type(27-28) +// param[1]: shift_amount (imm6) +.gadget orr_reg_shifted + ldr x8, [_pc] + ldr x20, [_pc, #8] // shift_amount + add _pc, _pc, #16 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + ubfx x19, x8, #26, #1 // N + ubfx x21, x8, #27, #2 // shift_type + + add x14, _cpu, #CPU_x0 + + // Load Rn (or 0 if XZR) + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + // Load Rm (or 0 if XZR) + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + cbz x12, orr_shifted_32 + + // 64-bit shift + cbz x20, orr_shifted_no_shift64 + cmp x21, #0 + b.eq orr_shift_lsl64 + cmp x21, #1 + b.eq orr_shift_lsr64 + cmp x21, #2 + b.eq orr_shift_asr64 + ror x16, x16, x20 + b orr_shifted_no_shift64 +orr_shift_lsl64: + lsl x16, x16, x20 + b orr_shifted_no_shift64 +orr_shift_lsr64: + lsr x16, x16, x20 + b orr_shifted_no_shift64 +orr_shift_asr64: + asr x16, x16, x20 + +orr_shifted_no_shift64: + cbz x19, orr_shifted_no_invert64 + mvn x16, x16 +orr_shifted_no_invert64: + orr x17, x15, x16 + b orr_shifted_store + +orr_shifted_32: + cbz x20, orr_shifted_no_shift32 + cmp x21, #0 + b.eq orr_shift_lsl32 + cmp x21, #1 + b.eq orr_shift_lsr32 + cmp x21, #2 + b.eq orr_shift_asr32 + ror w16, w16, w20 + b orr_shifted_no_shift32 +orr_shift_lsl32: + lsl w16, w16, w20 + b orr_shifted_no_shift32 +orr_shift_lsr32: + lsr w16, w16, w20 + b orr_shifted_no_shift32 +orr_shift_asr32: + asr w16, w16, w20 + +orr_shifted_no_shift32: + cbz x19, orr_shifted_no_invert32 + mvn w16, w16 +orr_shifted_no_invert32: + orr w17, w15, w16 + +orr_shifted_store: + // Store result (unless rd is XZR) + cmp x9, #31 + b.eq 7f + str x17, [x14, x9, lsl #3] +7: gret + +// EOR (shifted register) +// param[0]: rd(0-4), rn(8-12), rm(16-20), sf(24), N(26), shift_type(27-28) +// param[1]: shift_amount (imm6) +.gadget eor_reg_shifted + ldr x8, [_pc] + ldr x20, [_pc, #8] // shift_amount + add _pc, _pc, #16 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + ubfx x19, x8, #26, #1 // N (invert rm for EON) + ubfx x21, x8, #27, #2 // shift_type + + add x14, _cpu, #CPU_x0 + + // Load rn (or 0 if rn==31) + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + // Load rm (or 0 if rm==31) + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + cbz x12, eor_shifted_32 + + // 64-bit shift + cbz x20, eor_shifted_no_shift64 + cmp x21, #0 + b.eq eor_shift_lsl64 + cmp x21, #1 + b.eq eor_shift_lsr64 + cmp x21, #2 + b.eq eor_shift_asr64 + ror x16, x16, x20 + b eor_shifted_no_shift64 +eor_shift_lsl64: + lsl x16, x16, x20 + b eor_shifted_no_shift64 +eor_shift_lsr64: + lsr x16, x16, x20 + b eor_shifted_no_shift64 +eor_shift_asr64: + asr x16, x16, x20 + +eor_shifted_no_shift64: + cbz x19, eor_shifted_no_invert64 + mvn x16, x16 +eor_shifted_no_invert64: + eor x17, x15, x16 + b eor_shifted_store + +eor_shifted_32: + cbz x20, eor_shifted_no_shift32 + cmp x21, #0 + b.eq eor_shift_lsl32 + cmp x21, #1 + b.eq eor_shift_lsr32 + cmp x21, #2 + b.eq eor_shift_asr32 + ror w16, w16, w20 + b eor_shifted_no_shift32 +eor_shift_lsl32: + lsl w16, w16, w20 + b eor_shifted_no_shift32 +eor_shift_lsr32: + lsr w16, w16, w20 + b eor_shifted_no_shift32 +eor_shift_asr32: + asr w16, w16, w20 + +eor_shifted_no_shift32: + cbz x19, eor_shifted_no_invert32 + mvn w16, w16 +eor_shifted_no_invert32: + eor w17, w15, w16 + +eor_shifted_store: + cmp x9, #31 + b.eq 7f + str x17, [x14, x9, lsl #3] +7: gret + +// Legacy unshifted ORR +.gadget orr_reg + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + ubfx x12, x8, #24, #1 + ubfx x19, x8, #26, #1 // N (invert rm for ORN) + + add x14, _cpu, #CPU_x0 + + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + // If N=1 (ORN), invert rm + cbz x19, orr_reg_no_invert + mvn x16, x16 +orr_reg_no_invert: + orr x17, x15, x16 + + cbz x12, 5f + b 6f +5: and x17, x17, #0xffffffff +6: + cmp x9, #31 + b.eq 7f + str x17, [x14, x9, lsl #3] +7: gret + +// MOV Xd, Xm (64-bit) — fast path for ORR Xd, XZR, Xm +// gen.c guarantees rd!=31 and rm!=31, so no SP/XZR checks needed +// Code stream: [gadget addr][rd | rm<<16] +.gadget mov_reg + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x11, x8, #16, #5 // rm + add x14, _cpu, #CPU_x0 + ldr x16, [x14, x11, lsl #3] + str x16, [x14, x9, lsl #3] + gret + +// MOV Wd, Wm (32-bit) — fast path for ORR Wd, WZR, Wm +// Code stream: [gadget addr][rd | rm<<16] +.gadget mov_reg32 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x11, x8, #16, #5 // rm + add x14, _cpu, #CPU_x0 + ldr x16, [x14, x11, lsl #3] // load full 64-bit reg + and x16, x16, #0xffffffff // zero-extend 32→64 + str x16, [x14, x9, lsl #3] + gret + +.gadget eor_reg + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + ubfx x12, x8, #24, #1 + ubfx x19, x8, #26, #1 // N (invert rm for EON) + + add x14, _cpu, #CPU_x0 + + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + // If N=1 (EON), invert rm + cbz x19, eor_reg_no_invert + mvn x16, x16 +eor_reg_no_invert: + eor x17, x15, x16 + + cbz x12, 5f + b 6f +5: and x17, x17, #0xffffffff +6: + cmp x9, #31 + b.eq 7f + str x17, [x14, x9, lsl #3] +7: gret + +/* + * Logical immediate operations + * Code stream: [gadget addr][rd | rn<<8 | sf<<16 | S<<17][imm64] + * + * AND/ANDS - if S=1 (bit 17), set NZCV flags based on result: + * N = result[63] for 64-bit, result[31] for 32-bit + * Z = (result == 0) ? 1 : 0 + * C = 0 + * V = 0 + */ +.gadget and_imm + ldr x8, [_pc] + add _pc, _pc, #8 + ldr x9, [_pc] // imm64 + add _pc, _pc, #8 + + and x10, x8, #0x1f // rd + ubfx x11, x8, #8, #5 // rn + ubfx x12, x8, #16, #1 // sf + ubfx x13, x8, #17, #1 // S (set flags?) + + add x14, _cpu, #CPU_x0 + + cmp x11, #31 + b.eq 1f + ldr x15, [x14, x11, lsl #3] + b 2f +1: mov x15, #0 +2: + // If S=1, use ands to set flags correctly + cbz x13, and_imm_no_flags + + // ANDS with flag setting - use x16 for result since store_flags clobbers x17 + cbz x12, and_imm_ands_32 + // 64-bit ANDS + ands x16, x15, x9 + b and_imm_store_flags + +and_imm_ands_32: + // 32-bit ANDS + ands w16, w15, w9 + // Result in w16 is already zero-extended to x16 + +and_imm_store_flags: + store_flags + mov x17, x16 // save result immediately before any function calls + b and_imm_store_result + +and_imm_no_flags: + // AND without flags + and x17, x15, x9 + cbz x12, 3f + b and_imm_store_result +3: and x17, x17, #0xffffffff + +and_imm_store_result: + // Store result + cmp x10, #31 + b.eq 4f + str x17, [x14, x10, lsl #3] + gret +4: // rd=31: For AND/ANDS, rd=31 has different meanings: + // ANDS (S=1) with rd=31 → discard result (TST instruction), rd=31 means XZR + // AND (S=0) with rd=31 → write to SP + cbnz x13, 5f // If S=1 (ANDS/TST), discard result + // AND with rd=31: write to SP + and x17, x17, #0xffffffffffff // Mask to 48-bit address space + str x17, [_cpu, #CPU_sp] +5: gret + +.gadget orr_imm + ldr x8, [_pc] + add _pc, _pc, #8 + ldr x9, [_pc] + add _pc, _pc, #8 + + and x10, x8, #0x1f + ubfx x11, x8, #8, #5 + ubfx x12, x8, #16, #1 + + add x14, _cpu, #CPU_x0 + + cmp x11, #31 + b.eq 1f + ldr x15, [x14, x11, lsl #3] + b 2f +1: mov x15, #0 +2: + orr x17, x15, x9 + + cbz x12, 3f + b 4f +3: and x17, x17, #0xffffffff +4: + cmp x10, #31 + b.eq 6f + str x17, [x14, x10, lsl #3] + gret +6: // rd=31 for ORR (immediate): writes SP, not XZR (only ANDS uses XZR). + and x17, x17, #0xffffffffffff // Mask to 48-bit address space + str x17, [_cpu, #CPU_sp] + gret + +.gadget eor_imm + ldr x8, [_pc] + add _pc, _pc, #8 + ldr x9, [_pc] + add _pc, _pc, #8 + + and x10, x8, #0x1f + ubfx x11, x8, #8, #5 + ubfx x12, x8, #16, #1 + + add x14, _cpu, #CPU_x0 + + cmp x11, #31 + b.eq 1f + ldr x15, [x14, x11, lsl #3] + b 2f +1: mov x15, #0 +2: + eor x17, x15, x9 + + cbz x12, 3f + b 4f +3: and x17, x17, #0xffffffff +4: + cmp x10, #31 + b.eq 6f + str x17, [x14, x10, lsl #3] + gret +6: // rd=31 for EOR (immediate): writes SP, not XZR (only ANDS uses XZR). + and x17, x17, #0xffffffffffff // Mask to 48-bit address space + str x17, [_cpu, #CPU_sp] + gret + +/* + * EXTR - Extract register (concatenate and shift) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | imm<<24 | sf<<30] + */ +.gadget extr + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #6 // imm + ubfx x13, x8, #30, #1 // sf (0=32, 1=64) + + // Load Rn + add x14, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr x15, [x14, x10, lsl #3] + b 2f +1: mov x15, #0 +2: + // Load Rm + cmp x11, #31 + b.eq 3f + ldr x16, [x14, x11, lsl #3] + b 4f +3: mov x16, #0 +4: + cbz x13, .Lextr_32 + + // 64-bit EXTR + cbz x12, .Lextr_64_store_rm + lsr x17, x16, x12 + mov x3, #64 + sub x3, x3, x12 + lsl x19, x15, x3 + orr x17, x17, x19 + b .Lextr_store +.Lextr_64_store_rm: + mov x17, x16 + b .Lextr_store + +.Lextr_32: + // 32-bit EXTR + and x15, x15, #0xffffffff + and x16, x16, #0xffffffff + cbz x12, .Lextr_32_store_rm + lsr w17, w16, w12 + mov w3, #32 + sub w3, w3, w12 + lsl w19, w15, w3 + orr w17, w17, w19 + and x17, x17, #0xffffffff + b .Lextr_store +.Lextr_32_store_rm: + mov w17, w16 + and x17, x17, #0xffffffff + +.Lextr_store: + cmp x9, #31 + b.eq .Lextr_done + str x17, [x14, x9, lsl #3] +.Lextr_done: + gret + +/* + * Sign-extend operations + * These operate on _tmp (x0) which should already have the source value loaded + */ + +// SXTW: Sign-extend word (32-bit) to doubleword (64-bit) +// _tmp = sign_extend(_tmp[31:0]) +.gadget sxtw + sxtw _tmp, w0 + gret + +// SXTH: Sign-extend halfword (16-bit) to 32 or 64-bit +// Code stream: [gadget addr][sf] (0=32-bit dest, 1=64-bit dest) +.gadget sxth + ldr x8, [_pc] + add _pc, _pc, #8 + cbz x8, 1f + sxth _tmp, w0 // 64-bit + gret +1: sxth w0, w0 // 32-bit + gret + +// SXTB: Sign-extend byte (8-bit) to 32 or 64-bit +// Code stream: [gadget addr][sf] +.gadget sxtb + ldr x8, [_pc] + add _pc, _pc, #8 + cbz x8, 1f + sxtb _tmp, w0 // 64-bit + gret +1: sxtb w0, w0 // 32-bit + gret + +// UXTW: Zero-extend word (32-bit) to doubleword (64-bit) +.gadget uxtw + // Clear upper 32 bits explicitly + and x0, x0, #0xffffffff + gret + +// UXTH: Zero-extend halfword (16-bit) +// Code stream: [gadget addr][sf] +.gadget uxth + ldr x8, [_pc] + add _pc, _pc, #8 + cbz x8, 1f + uxth _tmp, w0 // to 64-bit (x0) + gret +1: uxth w0, w0 // to 32-bit (w0) + gret + +// UXTB: Zero-extend byte (8-bit) +// Code stream: [gadget addr][sf] +.gadget uxtb + ldr x8, [_pc] + add _pc, _pc, #8 + cbz x8, 1f + uxtb _tmp, w0 // to 64-bit + gret +1: uxtb w0, w0 // to 32-bit + gret + +/* + * CCMP/CCMN - Conditional Compare (register) + * Code stream: [gadget addr][rn | rm<<8 | cond<<16 | nzcv<<20 | sf<<24] + * + * If condition is true: performs CMP/CMN and sets flags from result + * If condition is false: sets flags to the immediate nzcv value + */ + +// CCMP: Conditional Compare (subtracts rm from rn) +.gadget ccmp_reg + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rn + ubfx x10, x8, #8, #5 // rm + ubfx x11, x8, #16, #4 // cond + ubfx x12, x8, #20, #4 // nzcv (flags if condition false) + ubfx x13, x8, #24, #1 // sf + + // Load current flags + ldr w14, [_cpu, #CPU_nzcv] + + // Check condition + // We need to evaluate the condition based on current flags + // x14 has NZCV in bits 31:28 + // x11 has condition code (0-15) + + // Extract individual flags from x14 + // N = bit 31, Z = bit 30, C = bit 29, V = bit 28 + lsr x15, x14, #28 // x15 = bits 31:28 in low 4 bits + + // Load Rn value + add x16, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x17, [x16, x9, lsl #3] + b 2f +1: mov x17, #0 +2: + // Load Rm value + cmp x10, #31 + b.eq 3f + ldr x3, [x16, x10, lsl #3] + b 4f +3: mov x3, #0 +4: + // Evaluate condition + // Set NZCV from x14 and use conditional branches + msr nzcv, x14 + + // Use bcond to check the condition + // cond is in x11 (0-15) + // We'll use a jump table + + adr x16, ccmp_cond_table + add x16, x16, x11, lsl #3 // each entry is 8 bytes (2 instructions) + br x16 + +.align 3 +ccmp_cond_table: + b.eq ccmp_do_compare // 0: EQ + b ccmp_set_nzcv + b.ne ccmp_do_compare // 1: NE + b ccmp_set_nzcv + b.cs ccmp_do_compare // 2: CS/HS + b ccmp_set_nzcv + b.cc ccmp_do_compare // 3: CC/LO + b ccmp_set_nzcv + b.mi ccmp_do_compare // 4: MI + b ccmp_set_nzcv + b.pl ccmp_do_compare // 5: PL + b ccmp_set_nzcv + b.vs ccmp_do_compare // 6: VS + b ccmp_set_nzcv + b.vc ccmp_do_compare // 7: VC + b ccmp_set_nzcv + b.hi ccmp_do_compare // 8: HI + b ccmp_set_nzcv + b.ls ccmp_do_compare // 9: LS + b ccmp_set_nzcv + b.ge ccmp_do_compare // 10: GE + b ccmp_set_nzcv + b.lt ccmp_do_compare // 11: LT + b ccmp_set_nzcv + b.gt ccmp_do_compare // 12: GT + b ccmp_set_nzcv + b.le ccmp_do_compare // 13: LE + b ccmp_set_nzcv + b ccmp_do_compare // 14: AL (always) + nop + b ccmp_do_compare // 15: NV (AArch64 treats NV as always true here) + nop + +ccmp_do_compare: + // Condition true: perform CMP (Rn - Rm) and set flags + cbz x13, ccmp_cmp_32 + // 64-bit compare + subs xzr, x17, x3 + b ccmp_store_flags +ccmp_cmp_32: + // 32-bit compare + subs wzr, w17, w3 + +ccmp_store_flags: + store_flags + gret + +ccmp_set_nzcv: + // Condition false: set flags to immediate nzcv value + lsl x12, x12, #28 // Move nzcv to bits 31:28 + str w12, [_cpu, #CPU_nzcv] + gret + +/* + * CCMP - Conditional Compare (immediate) + * Code stream: [gadget addr][rn | imm5<<8 | cond<<16 | nzcv<<20 | sf<<24] + * + * If condition is true: performs CMP (Rn - imm) and sets flags from result + * If condition is false: sets flags to the immediate nzcv value + */ +.gadget ccmp_imm + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rn + ubfx x10, x8, #8, #5 // imm5 + ubfx x11, x8, #16, #4 // cond + ubfx x12, x8, #20, #4 // nzcv (flags if condition false) + ubfx x13, x8, #24, #1 // sf + + // Load current flags + ldr w14, [_cpu, #CPU_nzcv] + + // Load Rn value + add x16, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x17, [x16, x9, lsl #3] + b 2f +1: mov x17, #0 +2: + // Evaluate condition based on current flags + msr nzcv, x14 + + adr x16, ccmpi_cond_table + add x16, x16, x11, lsl #3 + br x16 + +.align 3 +ccmpi_cond_table: + b.eq ccmpi_do_compare // 0: EQ + b ccmpi_set_nzcv + b.ne ccmpi_do_compare // 1: NE + b ccmpi_set_nzcv + b.cs ccmpi_do_compare // 2: CS/HS + b ccmpi_set_nzcv + b.cc ccmpi_do_compare // 3: CC/LO + b ccmpi_set_nzcv + b.mi ccmpi_do_compare // 4: MI + b ccmpi_set_nzcv + b.pl ccmpi_do_compare // 5: PL + b ccmpi_set_nzcv + b.vs ccmpi_do_compare // 6: VS + b ccmpi_set_nzcv + b.vc ccmpi_do_compare // 7: VC + b ccmpi_set_nzcv + b.hi ccmpi_do_compare // 8: HI + b ccmpi_set_nzcv + b.ls ccmpi_do_compare // 9: LS + b ccmpi_set_nzcv + b.ge ccmpi_do_compare // 10: GE + b ccmpi_set_nzcv + b.lt ccmpi_do_compare // 11: LT + b ccmpi_set_nzcv + b.gt ccmpi_do_compare // 12: GT + b ccmpi_set_nzcv + b.le ccmpi_do_compare // 13: LE + b ccmpi_set_nzcv + b ccmpi_do_compare // 14: AL (always) + nop + b ccmpi_do_compare // 15: NV (AArch64 treats NV as always true here) + nop + +ccmpi_do_compare: + // Condition true: perform CMP (Rn - imm) and set flags + cbz x13, ccmpi_cmp_32 + subs xzr, x17, x10 + b ccmpi_store_flags +ccmpi_cmp_32: + subs wzr, w17, w10 + +ccmpi_store_flags: + store_flags + gret + +ccmpi_set_nzcv: + lsl x12, x12, #28 + str w12, [_cpu, #CPU_nzcv] + gret + +// CCMN: Conditional Compare Negative (adds rm to rn) +.gadget ccmn_reg + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rn + ubfx x10, x8, #8, #5 // rm + ubfx x11, x8, #16, #4 // cond + ubfx x12, x8, #20, #4 // nzcv (flags if condition false) + ubfx x13, x8, #24, #1 // sf + + // Load current flags + ldr w14, [_cpu, #CPU_nzcv] + + // Load Rn value + add x16, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x17, [x16, x9, lsl #3] + b 2f +1: mov x17, #0 +2: + // Load Rm value + cmp x10, #31 + b.eq 3f + ldr x3, [x16, x10, lsl #3] + b 4f +3: mov x3, #0 +4: + // Evaluate condition + msr nzcv, x14 + + adr x16, ccmn_cond_table + add x16, x16, x11, lsl #3 + br x16 + +.align 3 +ccmn_cond_table: + b.eq ccmn_do_compare // 0: EQ + b ccmn_set_nzcv + b.ne ccmn_do_compare // 1: NE + b ccmn_set_nzcv + b.cs ccmn_do_compare // 2: CS/HS + b ccmn_set_nzcv + b.cc ccmn_do_compare // 3: CC/LO + b ccmn_set_nzcv + b.mi ccmn_do_compare // 4: MI + b ccmn_set_nzcv + b.pl ccmn_do_compare // 5: PL + b ccmn_set_nzcv + b.vs ccmn_do_compare // 6: VS + b ccmn_set_nzcv + b.vc ccmn_do_compare // 7: VC + b ccmn_set_nzcv + b.hi ccmn_do_compare // 8: HI + b ccmn_set_nzcv + b.ls ccmn_do_compare // 9: LS + b ccmn_set_nzcv + b.ge ccmn_do_compare // 10: GE + b ccmn_set_nzcv + b.lt ccmn_do_compare // 11: LT + b ccmn_set_nzcv + b.gt ccmn_do_compare // 12: GT + b ccmn_set_nzcv + b.le ccmn_do_compare // 13: LE + b ccmn_set_nzcv + b ccmn_do_compare // 14: AL (always) + nop + b ccmn_do_compare // 15: NV (AArch64 treats NV as always true here) + nop + +ccmn_do_compare: + // Condition true: perform CMN (Rn + Rm) and set flags + cbz x13, ccmn_cmn_32 + // 64-bit compare + adds xzr, x17, x3 + b ccmn_store_flags +ccmn_cmn_32: + // 32-bit compare + adds wzr, w17, w3 + +ccmn_store_flags: + store_flags + gret + +ccmn_set_nzcv: + // Condition false: set flags to immediate nzcv value + lsl x12, x12, #28 // Move nzcv to bits 31:28 + str w12, [_cpu, #CPU_nzcv] + gret + +/* + * CCMN - Conditional Compare Negative (immediate) + * Code stream: [gadget addr][rn | imm5<<8 | cond<<16 | nzcv<<20 | sf<<24] + * + * If condition is true: performs CMN (Rn + imm) and sets flags from result + * If condition is false: sets flags to the immediate nzcv value + */ +.gadget ccmn_imm + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rn + ubfx x10, x8, #8, #5 // imm5 + ubfx x11, x8, #16, #4 // cond + ubfx x12, x8, #20, #4 // nzcv (flags if condition false) + ubfx x13, x8, #24, #1 // sf + + // Load current flags + ldr w14, [_cpu, #CPU_nzcv] + + // Load Rn value + add x16, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x17, [x16, x9, lsl #3] + b 2f +1: mov x17, #0 +2: + // Evaluate condition based on current flags + msr nzcv, x14 + + adr x16, ccmni_cond_table + add x16, x16, x11, lsl #3 + br x16 + +.align 3 +ccmni_cond_table: + b.eq ccmni_do_compare // 0: EQ + b ccmni_set_nzcv + b.ne ccmni_do_compare // 1: NE + b ccmni_set_nzcv + b.cs ccmni_do_compare // 2: CS/HS + b ccmni_set_nzcv + b.cc ccmni_do_compare // 3: CC/LO + b ccmni_set_nzcv + b.mi ccmni_do_compare // 4: MI + b ccmni_set_nzcv + b.pl ccmni_do_compare // 5: PL + b ccmni_set_nzcv + b.vs ccmni_do_compare // 6: VS + b ccmni_set_nzcv + b.vc ccmni_do_compare // 7: VC + b ccmni_set_nzcv + b.hi ccmni_do_compare // 8: HI + b ccmni_set_nzcv + b.ls ccmni_do_compare // 9: LS + b ccmni_set_nzcv + b.ge ccmni_do_compare // 10: GE + b ccmni_set_nzcv + b.lt ccmni_do_compare // 11: LT + b ccmni_set_nzcv + b.gt ccmni_do_compare // 12: GT + b ccmni_set_nzcv + b.le ccmni_do_compare // 13: LE + b ccmni_set_nzcv + b ccmni_do_compare // 14: AL (always) + nop + b ccmni_do_compare // 15: NV (AArch64 treats NV as always true here) + nop + +ccmni_do_compare: + // Condition true: perform CMN (Rn + imm) and set flags + cbz x13, ccmni_cmn_32 + adds xzr, x17, x10 + b ccmni_store_flags +ccmni_cmn_32: + adds wzr, w17, w10 + +ccmni_store_flags: + store_flags + gret + +ccmni_set_nzcv: + lsl x12, x12, #28 + str w12, [_cpu, #CPU_nzcv] + gret + +/* + * Fast-path variable shifts (sf=1, rd/rn/rm != 31) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ + +// LSLV 64-bit fast path +.gadget lslv_64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] + ldr x16, [x14, x11, lsl #3] + and x16, x16, #63 + lsl x17, x15, x16 + str x17, [x14, x9, lsl #3] + gret + +// LSRV 64-bit fast path +.gadget lsrv_64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] + ldr x16, [x14, x11, lsl #3] + and x16, x16, #63 + lsr x17, x15, x16 + str x17, [x14, x9, lsl #3] + gret + +// ASRV 64-bit fast path +.gadget asrv_64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] + ldr x16, [x14, x11, lsl #3] + and x16, x16, #63 + asr x17, x15, x16 + str x17, [x14, x9, lsl #3] + gret + +/* + * Data Processing (2 source) - Variable shifts and divides + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | sf<<24] + */ + +// LSLV: Logical Shift Left Variable +.gadget lslv + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + + add x14, _cpu, #CPU_x0 + + // Load Rn + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: + // Load Rm (shift amount) + cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: + // Perform shift - only low 6 bits of Rm matter for 64-bit, 5 bits for 32-bit + cbz x12, lslv_32 + // 64-bit + and x16, x16, #63 + lsl x17, x15, x16 + b lslv_store +lslv_32: + and x16, x16, #31 + lsl w17, w15, w16 + // w-reg operations implicitly zero-extend to 64 bits + +lslv_store: + cmp x9, #31 + b.eq 3f + str x17, [x14, x9, lsl #3] +3: gret + +// LSRV: Logical Shift Right Variable +.gadget lsrv + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + + add x14, _cpu, #CPU_x0 + + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: + cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: + cbz x12, lsrv_32 + and x16, x16, #63 + lsr x17, x15, x16 + b lsrv_store +lsrv_32: + // w15 is already the lower 32 bits when using w-register form + and x16, x16, #31 + lsr w17, w15, w16 + +lsrv_store: + cmp x9, #31 + b.eq 3f + str x17, [x14, x9, lsl #3] +3: gret + +// ASRV: Arithmetic Shift Right Variable +.gadget asrv + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + + add x14, _cpu, #CPU_x0 + + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: + cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: + cbz x12, asrv_32 + and x16, x16, #63 + asr x17, x15, x16 + b asrv_store +asrv_32: + and x16, x16, #31 + asr w17, w15, w16 + +asrv_store: + cmp x9, #31 + b.eq 3f + str x17, [x14, x9, lsl #3] +3: gret + +// RORV: Rotate Right Variable +.gadget rorv + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + + add x14, _cpu, #CPU_x0 + + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: + cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: + cbz x12, rorv_32 + and x16, x16, #63 + ror x17, x15, x16 + b rorv_store +rorv_32: + and x16, x16, #31 + ror w17, w15, w16 + +rorv_store: + cmp x9, #31 + b.eq 3f + str x17, [x14, x9, lsl #3] +3: gret + +// UDIV: Unsigned Divide +.gadget udiv + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + + add x14, _cpu, #CPU_x0 + + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: + cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: + cbz x12, udiv_32 + udiv x17, x15, x16 + b udiv_store +udiv_32: + udiv w17, w15, w16 + +udiv_store: + cmp x9, #31 + b.eq 3f + str x17, [x14, x9, lsl #3] +3: gret + +// SDIV: Signed Divide +.gadget sdiv + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #1 // sf + + add x14, _cpu, #CPU_x0 + + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: + cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: + cbz x12, sdiv_32 + sdiv x17, x15, x16 + b sdiv_store +sdiv_32: + sdiv w17, w15, w16 + +sdiv_store: + cmp x9, #31 + b.eq 3f + str x17, [x14, x9, lsl #3] +3: gret + +// CRC32 instructions +// All CRC32 variants: result is always 32-bit (stored in w-reg) +// Packing: rd | rn<<8 | rm<<16 | sf<<24 +// sf is only relevant for CRC32X/CRC32CX (64-bit source operand) +// +// CRC is an optional ARMv8.0 extension — gate with .arch_extension so the +// assembler accepts these mnemonics regardless of the build's -march setting. +// Apple clang defaults include +crc on Apple Silicon; GNU as on armv8-a does not. +.arch_extension crc + +// CRC32B +.gadget crc32b + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x14, _cpu, #CPU_x0 + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: crc32b w17, w15, w16 + cmp x9, #31 + b.eq 3f + str x17, [x14, x9, lsl #3] +3: gret + +// CRC32H +.gadget crc32h + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x14, _cpu, #CPU_x0 + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: crc32h w17, w15, w16 + cmp x9, #31 + b.eq 3f + str x17, [x14, x9, lsl #3] +3: gret + +// CRC32W +.gadget crc32w + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x14, _cpu, #CPU_x0 + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: crc32w w17, w15, w16 + cmp x9, #31 + b.eq 3f + str x17, [x14, x9, lsl #3] +3: gret + +// CRC32X (64-bit source, sf=1 only) +.gadget crc32x + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x14, _cpu, #CPU_x0 + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: crc32x w17, w15, x16 + cmp x9, #31 + b.eq 3f + str x17, [x14, x9, lsl #3] +3: gret + +// CRC32CB +.gadget crc32cb + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x14, _cpu, #CPU_x0 + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: crc32cb w17, w15, w16 + cmp x9, #31 + b.eq 3f + str x17, [x14, x9, lsl #3] +3: gret + +// CRC32CH +.gadget crc32ch + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x14, _cpu, #CPU_x0 + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: crc32ch w17, w15, w16 + cmp x9, #31 + b.eq 3f + str x17, [x14, x9, lsl #3] +3: gret + +// CRC32CW +.gadget crc32cw + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x14, _cpu, #CPU_x0 + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: crc32cw w17, w15, w16 + cmp x9, #31 + b.eq 3f + str x17, [x14, x9, lsl #3] +3: gret + +// CRC32CX (64-bit source, sf=1 only) +.gadget crc32cx + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x14, _cpu, #CPU_x0 + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: crc32cx w17, w15, x16 + cmp x9, #31 + b.eq 3f + str x17, [x14, x9, lsl #3] +3: gret + +.arch_extension nocrc + +/* + * UBFM - Unsigned Bitfield Move + * Code stream: [gadget addr][immr | imms<<8 | sf<<16] + * Input: value in _tmp (x0) + * Output: result in _tmp (x0) + * + * UBFM performs: Rd = ROR(Rn, R) AND mask(s) + * Where R is immr and the mask is derived from imms + * This handles LSL, LSR, UBFX, UBFIZ aliases + */ +.gadget ubfm + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x3f // immr + ubfx x10, x8, #8, #6 // imms + ubfx x11, x8, #16, #1 // sf + + // _tmp (x0) already has the source value + + // For sf=1 (64-bit): + // datasize = 64, R = immr, S = imms + // if imms >= immr: result = (src >> R) & mask(S-R+1 bits) (LSR/UBFX) + // else: result = (src << (64-R)) & mask(S+1 bits) (LSL/UBFIZ) + // For sf=0 (32-bit): + // datasize = 32, similar but with 32-bit values + + cbz x11, ubfm_32 + + // 64-bit + cmp x10, x9 + b.lt ubfm_64_insert + + // UBFX/LSR case: imms >= immr + // result = (src >> immr) with bits [imms-immr:0] kept + sub x12, x10, x9 // width - 1 + add x12, x12, #1 // width + lsr x0, x0, x9 // shift right by immr + // If width == 64, mask should be all-ones (no masking needed) + cmp x12, #64 + b.eq ubfm_64_fullwidth + // Create mask of 'width' bits: (1 << width) - 1 = ~((-1) << width) + mov x13, #-1 + lsl x13, x13, x12 // -1 << width + mvn x13, x13 // x13 = (1 << width) - 1 + and x0, x0, x13 + gret + +ubfm_64_fullwidth: + // width == 64: result already in x0 after shift + gret + +ubfm_64_insert: + // UBFIZ/LSL case: imms < immr + // result = (src & ((1 << width) - 1)) << (64 - immr) + // where width = imms + 1, lsb = 64 - immr + mov x12, #64 + sub x12, x12, x9 // shift amount = 64 - immr + add x13, x10, #1 // width = imms + 1 + // Create mask of 'width' bits: (1 << width) - 1 = ~((-1) << width) + mov x14, #-1 + lsl x14, x14, x13 // -1 << width + mvn x14, x14 // (1 << width) - 1 + and x0, x0, x14 // mask source to keep only width bits + lsl x0, x0, x12 // shift left to final position + gret + +ubfm_32: + // 32-bit version + cmp x10, x9 + b.lt ubfm_32_insert + + // UBFX/LSR for 32-bit + sub w12, w10, w9 + add w12, w12, #1 + lsr w0, w0, w9 + // If width == 32, mask should be all-ones (no masking needed) + cmp w12, #32 + b.eq ubfm_32_fullwidth + // Create mask of 'width' bits: (1 << width) - 1 = ~((-1) << width) + mov w13, #-1 + lsl w13, w13, w12 + mvn w13, w13 + and w0, w0, w13 + gret + +ubfm_32_fullwidth: + // width == 32: result already in w0 after shift + gret + +ubfm_32_insert: + // UBFIZ/LSL for 32-bit + mov w12, #32 + sub w12, w12, w9 + add w13, w10, #1 + // Create mask of 'width' bits: (1 << width) - 1 = ~((-1) << width) + mov w14, #-1 + lsl w14, w14, w13 + mvn w14, w14 + and w0, w0, w14 + lsl w0, w0, w12 + gret + +/* + * Fused UBFM - loads rn and stores to rd internally (no load_reg/store_reg dispatch) + * Code stream: [gadget addr][immr(0:5) | imms(8:13) | sf(16) | rn(20:24) | rd(28:32)] + * gen.c emits this when rn!=31 and rd!=31. + */ +.gadget ubfm_fused + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x3f // immr + ubfx x10, x8, #8, #6 // imms + ubfx x11, x8, #16, #1 // sf + ubfx x3, x8, #20, #5 // rn + ubfx x4, x8, #28, #5 // rd + // Load source register rn + add x14, _cpu, #CPU_x0 + ldr x0, [x14, x3, lsl #3] + // Execute UBFM logic (same as gadget_ubfm) + cbz x11, ubfm_f_32 + // 64-bit + cmp x10, x9 + b.lt ubfm_f_64_insert + sub x12, x10, x9 + add x12, x12, #1 + lsr x0, x0, x9 + cmp x12, #64 + b.eq ubfm_f_store + mov x13, #-1 + lsl x13, x13, x12 + mvn x13, x13 + and x0, x0, x13 + b ubfm_f_store +ubfm_f_64_insert: + mov x12, #64 + sub x12, x12, x9 + add x13, x10, #1 + mov x5, #-1 + lsl x5, x5, x13 + mvn x5, x5 + and x0, x0, x5 + lsl x0, x0, x12 + b ubfm_f_store +ubfm_f_32: + cmp x10, x9 + b.lt ubfm_f_32_insert + sub w12, w10, w9 + add w12, w12, #1 + lsr w0, w0, w9 + cmp w12, #32 + b.eq ubfm_f_store + mov w13, #-1 + lsl w13, w13, w12 + mvn w13, w13 + and w0, w0, w13 + b ubfm_f_store +ubfm_f_32_insert: + mov w12, #32 + sub w12, w12, w9 + add w13, w10, #1 + mov w5, #-1 + lsl w5, w5, w13 + mvn w5, w5 + and w0, w0, w5 + lsl w0, w0, w12 +ubfm_f_store: + str x0, [x14, x4, lsl #3] + gret + +/* + * Fused SBFM - loads rn and stores to rd internally + * Code stream: [gadget addr][immr(0:5) | imms(8:13) | sf(16) | rn(20:24) | rd(28:32)] + */ +.gadget sbfm_fused + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x3f // immr + ubfx x10, x8, #8, #6 // imms + ubfx x11, x8, #16, #1 // sf + ubfx x3, x8, #20, #5 // rn + ubfx x4, x8, #28, #5 // rd + add x14, _cpu, #CPU_x0 + ldr x0, [x14, x3, lsl #3] + cbz x11, sbfm_f_32 + // 64-bit + cmp x10, x9 + b.lt sbfm_f_64_insert + sub x12, x10, x9 + add x12, x12, #1 + asr x0, x0, x9 + mov x13, #64 + sub x13, x13, x12 + lsl x0, x0, x13 + asr x0, x0, x13 + b sbfm_f_store +sbfm_f_64_insert: + mov x12, #64 + sub x12, x12, x9 + add x13, x10, #1 + mov x5, #64 + sub x5, x5, x13 + lsl x0, x0, x5 + asr x0, x0, x5 + lsl x0, x0, x12 + b sbfm_f_store +sbfm_f_32: + cmp x10, x9 + b.lt sbfm_f_32_insert + sub w12, w10, w9 + add w12, w12, #1 + asr w0, w0, w9 + mov w13, #32 + sub w13, w13, w12 + lsl w0, w0, w13 + asr w0, w0, w13 + b sbfm_f_store +sbfm_f_32_insert: + mov w12, #32 + sub w12, w12, w9 + add w13, w10, #1 + mov w5, #32 + sub w5, w5, w13 + lsl w0, w0, w5 + asr w0, w0, w5 + lsl w0, w0, w12 +sbfm_f_store: + str x0, [x14, x4, lsl #3] + gret + +/* + * SBFM - Signed Bitfield Move + * Code stream: [gadget addr][immr | imms<<8 | sf<<16] + * Input: value in _tmp (x0) + * Output: result in _tmp (x0) + * + * SBFM is similar to UBFM but with sign extension + * Handles ASR, SBFX, SBFIZ aliases + */ +.gadget sbfm + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x3f // immr + ubfx x10, x8, #8, #6 // imms + ubfx x11, x8, #16, #1 // sf + + cbz x11, sbfm_32 + + // 64-bit + cmp x10, x9 + b.lt sbfm_64_insert + + // SBFX/ASR case: imms >= immr + // Extract field and sign-extend + sub x12, x10, x9 // width - 1 + add x12, x12, #1 // width + // Shift right to position, then sign-extend + asr x0, x0, x9 // arithmetic shift right by immr + // Now shift left then asr to sign extend the width-bit field + mov x13, #64 + sub x13, x13, x12 // 64 - width + lsl x0, x0, x13 + asr x0, x0, x13 + gret + +sbfm_64_insert: + // SBFIZ case: imms < immr + // For SBFIZ Xd, Xn, #lsb, #width: + // immr = (-lsb) MOD 64 + // imms = width - 1 + // We need to: + // 1. Extract bits [0:width-1] from source + // 2. Sign-extend to 64 bits + // 3. Shift left by lsb (= 64 - immr for 64-bit) + mov x12, #64 + sub x12, x12, x9 // x12 = lsb = 64 - immr + add x13, x10, #1 // x13 = width = imms + 1 + + // Sign-extend the lower 'width' bits + // Shift left to move MSB of field to bit 63, then ASR back + mov x14, #64 + sub x14, x14, x13 // x14 = 64 - width + lsl x0, x0, x14 // Move MSB of field to bit 63 + asr x0, x0, x14 // Arithmetic shift right to sign-extend + + // Now shift left by lsb + lsl x0, x0, x12 + gret + +sbfm_32: + cmp x10, x9 + b.lt sbfm_32_insert + + // SBFX/ASR for 32-bit + sub w12, w10, w9 + add w12, w12, #1 + asr w0, w0, w9 + mov w13, #32 + sub w13, w13, w12 + lsl w0, w0, w13 + asr w0, w0, w13 + gret + +sbfm_32_insert: + // SBFIZ 32-bit case: imms < immr + // Sign-extend then shift left + mov w12, #32 + sub w12, w12, w9 // w12 = lsb = 32 - immr (for 32-bit encoding) + add w13, w10, #1 // w13 = width = imms + 1 + + // Sign-extend the lower 'width' bits + mov w14, #32 + sub w14, w14, w13 // w14 = 32 - width + lsl w0, w0, w14 // Move MSB of field to bit 31 + asr w0, w0, w14 // Arithmetic shift right to sign-extend + + // Now shift left by lsb + lsl w0, w0, w12 + gret + +/* + * BFM - Bitfield Move (preserves destination bits outside the field) + * Code stream: [gadget addr][immr | imms<<8 | sf<<16 | rd<<24] + * Input: source value in _tmp (x0) + * Output: result in _tmp (x0) = destination with bitfield from source inserted + * + * BFM copies a bitfield from Rn to Rd, preserving other bits in Rd. + * Uses ROR(src, immr) & wmask to extract field, inserts into dest. + * If imms >= immr (BFXIL): extract bits [imms:immr] from Rn, insert at bits [imms-immr:0] of Rd + * If imms < immr (BFI): copy bits [imms:0] of Rn to bits [datasize-1-immr+imms:datasize-immr] of Rd + * (wrap around behavior) + */ +.gadget bfm + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x3f // immr + ubfx x10, x8, #8, #6 // imms + ubfx x11, x8, #16, #1 // sf + ubfx x12, x8, #24, #5 // rd + + // Save source value + mov x13, x0 // x13 = source (Rn value) + + // Load destination register value (Rd) + add x14, _cpu, #CPU_x0 + cmp x12, #31 + b.eq bfm_rd_zero + ldr x15, [x14, x12, lsl #3] + b bfm_have_dest +bfm_rd_zero: + mov x15, #0 // XZR is always zero +bfm_have_dest: + // x15 = current destination (Rd) value + + cbz x11, bfm_32 + + // 64-bit BFM + cmp x10, x9 + b.lt bfm_64_wrap + + // Case: imms >= immr (BFXIL) + // Extract bits [imms:immr] from src, insert at bits [imms-immr:0] of dest + // width = imms - immr + 1 + sub x16, x10, x9 // width - 1 + add x16, x16, #1 // width + // If width == 64, result is just the source value + cmp x16, #64 + b.eq bfm_64_fullwidth + // Create mask of 'width' bits at position 0 + mov x17, #-1 + lsl x17, x17, x16 // -1 << width + mvn x17, x17 // (1 << width) - 1 = mask for width bits + + // Extract field from source: src_field = (src >> immr) & mask + lsr x13, x13, x9 // src >> immr + and x13, x13, x17 // src_field = (src >> immr) & mask + + // Clear low 'width' bits of destination and insert source field + bic x15, x15, x17 // dest & ~mask (clear low width bits) + orr x0, x15, x13 // result = (dest & ~mask) | src_field + gret + +bfm_64_fullwidth: + // width == 64: full-field move -> result is source + mov x0, x13 + gret + +bfm_64_wrap: + // Case: imms < immr (wrap around) + // Copy bits [imms:0] from src to bits [datasize-1-immr+imms:datasize-immr] in dest + // width = imms + 1, dst_lsb = 64 - immr + add x16, x10, #1 // width = imms + 1 + mov x17, #64 + sub x3, x17, x9 // dst_lsb = 64 - immr + + // Create mask of 'width' bits + mov x17, #-1 + lsl x17, x17, x16 // -1 << width + mvn x17, x17 // mask for width bits + + // Extract field from source + and x13, x13, x17 // src_field = source & mask + + // Create dest_mask at destination position + lsl x17, x17, x3 // dest_mask = mask << dst_lsb + + // Clear destination bits and insert source field + bic x15, x15, x17 + lsl x13, x13, x3 // src_field << dst_lsb + orr x0, x15, x13 + gret + +bfm_32: + // 32-bit BFM + cmp w10, w9 + b.lt bfm_32_wrap + + // Case: imms >= immr (BFXIL) + // Extract bits [imms:immr] from src, insert at bits [imms-immr:0] of dest + sub w16, w10, w9 + add w16, w16, #1 + // If width == 32, result is just the source value + cmp w16, #32 + b.eq bfm_32_fullwidth + mov w17, #-1 + lsl w17, w17, w16 + mvn w17, w17 + + // Extract field from source: src_field = (src >> immr) & mask + lsr w13, w13, w9 + and w13, w13, w17 + // Clear low 'width' bits of dest and insert + bic w15, w15, w17 + orr w0, w15, w13 + gret + +bfm_32_fullwidth: + // width == 32: full-field move -> result is source + mov w0, w13 + gret + +bfm_32_wrap: + // Case: imms < immr (wrap around) + add w16, w10, #1 + mov w17, #32 + sub w3, w17, w9 + + mov w17, #-1 + lsl w17, w17, w16 + mvn w17, w17 + + and w13, w13, w17 + lsl w17, w17, w3 + bic w15, w15, w17 + lsl w13, w13, w3 + orr w0, w15, w13 + gret + +/* + * ADD/SUB (extended register) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | option<<24 | imm3<<27 | sf<<30 | S<<31] + * + * option encodes the extension type: + * 000 = UXTB (zero-extend byte) + * 001 = UXTH (zero-extend halfword) + * 010 = UXTW (zero-extend word) / LSL if sf=0 or rm=WSP + * 011 = UXTX (64-bit, no extension) / LSL if sf=1 + * 100 = SXTB (sign-extend byte) + * 101 = SXTH (sign-extend halfword) + * 110 = SXTW (sign-extend word) + * 111 = SXTX (sign-extend doubleword) + */ +.gadget add_ext + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #3 // option + ubfx x13, x8, #27, #3 // imm3 (shift amount) + ubfx x14, x8, #30, #1 // sf + ubfx x15, x8, #31, #1 // S + + add x16, _cpu, #CPU_x0 + + // Load Rn (or SP if rn == 31) + cmp x10, #31 + b.eq add_ext_load_sp_rn + ldr x17, [x16, x10, lsl #3] + b add_ext_load_rm +add_ext_load_sp_rn: + ldr x17, [_cpu, #CPU_sp] + +add_ext_load_rm: + // Load Rm (or XZR if rm == 31) + cmp x11, #31 + mov x3, #0 + b.eq add_ext_apply + ldr x3, [x16, x11, lsl #3] + +add_ext_apply: + // Apply extension based on option + // Jump table for extension type + adr x19, add_ext_option_table + add x19, x19, x12, lsl #3 // 8 bytes per entry (2 instructions) + br x19 + +.align 3 +add_ext_option_table: + uxtb w3, w3 // 0: UXTB + b add_ext_shift + uxth w3, w3 // 1: UXTH + b add_ext_shift + mov w3, w3 // 2: UXTW (32-bit, or same as LSL for sf=0) + b add_ext_shift + b add_ext_shift // 3: UXTX (no extension needed for 64-bit) + nop + sxtb x3, w3 // 4: SXTB + b add_ext_shift + sxth x3, w3 // 5: SXTH + b add_ext_shift + sxtw x3, w3 // 6: SXTW + b add_ext_shift + b add_ext_shift // 7: SXTX (no extension needed) + nop + +add_ext_shift: + // Apply shift (imm3) + lsl x3, x3, x13 + + // Add + add x19, x17, x3 + + // Handle 32-bit + cbz x14, add_ext_32 + b add_ext_store +add_ext_32: + and x19, x19, #0xffffffff + +add_ext_store: + // Store result + cmp x9, #31 + b.eq add_ext_store_sp + str x19, [x16, x9, lsl #3] + gret +add_ext_store_sp: + // Mask to 48 bits before writing to SP + and x19, x19, #0xffffffffffff + str x19, [_cpu, #CPU_sp] + gret + +.gadget sub_ext + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #3 // option + ubfx x13, x8, #27, #3 // imm3 (shift amount) + ubfx x14, x8, #30, #1 // sf + ubfx x15, x8, #31, #1 // S + + add x16, _cpu, #CPU_x0 + + // Load Rn (or SP if rn == 31) + cmp x10, #31 + b.eq sub_ext_load_sp_rn + ldr x17, [x16, x10, lsl #3] + b sub_ext_load_rm +sub_ext_load_sp_rn: + ldr x17, [_cpu, #CPU_sp] + +sub_ext_load_rm: + // Load Rm + cmp x11, #31 + mov x3, #0 + b.eq sub_ext_apply + ldr x3, [x16, x11, lsl #3] + +sub_ext_apply: + // Apply extension + adr x19, sub_ext_option_table + add x19, x19, x12, lsl #3 + br x19 + +.align 3 +sub_ext_option_table: + uxtb w3, w3 // 0: UXTB + b sub_ext_shift + uxth w3, w3 // 1: UXTH + b sub_ext_shift + mov w3, w3 // 2: UXTW + b sub_ext_shift + b sub_ext_shift // 3: UXTX + nop + sxtb x3, w3 // 4: SXTB + b sub_ext_shift + sxth x3, w3 // 5: SXTH + b sub_ext_shift + sxtw x3, w3 // 6: SXTW + b sub_ext_shift + b sub_ext_shift // 7: SXTX + nop + +sub_ext_shift: + lsl x3, x3, x13 + + // Subtract + sub x19, x17, x3 + + // Handle 32-bit + cbz x14, sub_ext_32 + b sub_ext_store +sub_ext_32: + and x19, x19, #0xffffffff + +sub_ext_store: + cmp x9, #31 + b.eq sub_ext_store_sp + str x19, [x16, x9, lsl #3] + gret +sub_ext_store_sp: + // Mask to 48 bits before writing to SP + and x19, x19, #0xffffffffffff + str x19, [_cpu, #CPU_sp] + gret + +/* + * SUBS (extended register) - with flag setting + * Used for CMP with extended register operand + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | option<<24 | imm3<<27 | sf<<30] + */ +.gadget subs_ext + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #3 // option + ubfx x13, x8, #27, #3 // imm3 (shift amount) + ubfx x14, x8, #30, #1 // sf + + add x16, _cpu, #CPU_x0 + + // Load Rn (or SP if rn == 31) + cmp x10, #31 + b.eq subs_ext_load_sp_rn + ldr x17, [x16, x10, lsl #3] + b subs_ext_load_rm +subs_ext_load_sp_rn: + ldr x17, [_cpu, #CPU_sp] + +subs_ext_load_rm: + // Load Rm + cmp x11, #31 + mov x3, #0 + b.eq subs_ext_apply + ldr x3, [x16, x11, lsl #3] + +subs_ext_apply: + // Apply extension based on option field + adr x19, subs_ext_option_table + add x19, x19, x12, lsl #3 + br x19 + +.align 3 +subs_ext_option_table: + uxtb w3, w3 // 0: UXTB + b subs_ext_shift + uxth w3, w3 // 1: UXTH + b subs_ext_shift + mov w3, w3 // 2: UXTW + b subs_ext_shift + b subs_ext_shift // 3: UXTX + nop + sxtb x3, w3 // 4: SXTB + b subs_ext_shift + sxth x3, w3 // 5: SXTH + b subs_ext_shift + sxtw x3, w3 // 6: SXTW + b subs_ext_shift + b subs_ext_shift // 7: SXTX + nop + +subs_ext_shift: + lsl x3, x3, x13 + + // Subtract with flag setting + cbz x14, subs_ext_32 + // 64-bit + subs x19, x17, x3 + b subs_ext_store_flags + +subs_ext_32: + // 32-bit: use 32-bit subs for correct flag generation + subs w19, w17, w3 + // Result is already zero-extended + +subs_ext_store_flags: + // Store NZCV flags + store_flags + + // Store result (only if rd != 31, i.e., not CMP) + cmp x9, #31 + b.eq subs_ext_done // rd=31 means ZR (CMP), discard result + str x19, [x16, x9, lsl #3] +subs_ext_done: + gret + +/* + * ADDS (extended register) - with flag setting + * Used for CMN with extended register operand + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | option<<24 | imm3<<27 | sf<<30] + */ +.gadget adds_ext + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #3 // option + ubfx x13, x8, #27, #3 // imm3 (shift amount) + ubfx x14, x8, #30, #1 // sf + + add x16, _cpu, #CPU_x0 + + // Load Rn (or SP if rn == 31) + cmp x10, #31 + b.eq adds_ext_load_sp_rn + ldr x17, [x16, x10, lsl #3] + b adds_ext_load_rm +adds_ext_load_sp_rn: + ldr x17, [_cpu, #CPU_sp] + +adds_ext_load_rm: + // Load Rm + cmp x11, #31 + mov x3, #0 + b.eq adds_ext_apply + ldr x3, [x16, x11, lsl #3] + +adds_ext_apply: + // Apply extension based on option field + adr x19, adds_ext_option_table + add x19, x19, x12, lsl #3 + br x19 + +.align 3 +adds_ext_option_table: + uxtb w3, w3 // 0: UXTB + b adds_ext_shift + uxth w3, w3 // 1: UXTH + b adds_ext_shift + mov w3, w3 // 2: UXTW + b adds_ext_shift + b adds_ext_shift // 3: UXTX + nop + sxtb x3, w3 // 4: SXTB + b adds_ext_shift + sxth x3, w3 // 5: SXTH + b adds_ext_shift + sxtw x3, w3 // 6: SXTW + b adds_ext_shift + b adds_ext_shift // 7: SXTX + nop + +adds_ext_shift: + lsl x3, x3, x13 + + // Add with flag setting + cbz x14, adds_ext_32 + // 64-bit + adds x19, x17, x3 + b adds_ext_store_flags + +adds_ext_32: + // 32-bit: use 32-bit adds for correct flag generation + adds w19, w17, w3 + // Result is already zero-extended + +adds_ext_store_flags: + // Store NZCV flags + store_flags + + // Store result (only if rd != 31, i.e., not CMN) + cmp x9, #31 + b.eq adds_ext_done + str x19, [x16, x9, lsl #3] +adds_ext_done: + gret + +/* + * Multiply instructions (3-source) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | ra<<24 | sf<<29] + */ + +// MADD: Xd = Xa + (Xn * Xm) +// MUL is MADD with Ra=XZR (31) +.gadget madd + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #5 // ra + ubfx x13, x8, #29, #1 // sf + + add x14, _cpu, #CPU_x0 + + // Load Rn + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: + // Load Rm + cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: + // Load Ra + cmp x12, #31 + mov x17, #0 + b.eq 3f + ldr x17, [x14, x12, lsl #3] +3: + // Compute: result = Ra + (Rn * Rm) + cbz x13, madd_32 + // 64-bit + madd x3, x15, x16, x17 + b madd_store + +madd_32: + // 32-bit + madd w3, w15, w16, w17 + // Result already zero-extended + +madd_store: + cmp x9, #31 + b.eq 4f + str x3, [x14, x9, lsl #3] +4: gret + +// MSUB: Xd = Xa - (Xn * Xm) +// MNEG is MSUB with Ra=XZR (31) +.gadget msub + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #5 // ra + ubfx x13, x8, #29, #1 // sf + + add x14, _cpu, #CPU_x0 + + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: + cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: + cmp x12, #31 + mov x17, #0 + b.eq 3f + ldr x17, [x14, x12, lsl #3] +3: + // Compute: result = Ra - (Rn * Rm) + cbz x13, msub_32 + // 64-bit + msub x3, x15, x16, x17 + b msub_store + +msub_32: + // 32-bit + msub w3, w15, w16, w17 + +msub_store: + cmp x9, #31 + b.eq 4f + str x3, [x14, x9, lsl #3] +4: gret + +// SMADDL: Xd = Xa + (sign_extend(Wn) * sign_extend(Wm)) +// SMULL is SMADDL with Ra=XZR (31) +.gadget smaddl + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #5 // ra + + add x14, _cpu, #CPU_x0 + + // Load Rn (use full register, smaddl will take low 32 bits) + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: + // Load Rm + cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: + // Load Xa (64-bit) + cmp x12, #31 + mov x17, #0 + b.eq 3f + ldr x17, [x14, x12, lsl #3] +3: + // Compute: result = Xa + (sign_extend(Wn) * sign_extend(Wm)) + smaddl x3, w15, w16, x17 + + cmp x9, #31 + b.eq 4f + str x3, [x14, x9, lsl #3] +4: gret + +// SMSUBL: Xd = Xa - (sign_extend(Wn) * sign_extend(Wm)) +// SMNEGL is SMSUBL with Ra=XZR (31) +.gadget smsubl + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #5 // ra + + add x14, _cpu, #CPU_x0 + + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: + cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: + cmp x12, #31 + mov x17, #0 + b.eq 3f + ldr x17, [x14, x12, lsl #3] +3: + smsubl x3, w15, w16, x17 + + cmp x9, #31 + b.eq 4f + str x3, [x14, x9, lsl #3] +4: gret + +// UMADDL: Xd = Xa + (zero_extend(Wn) * zero_extend(Wm)) +// UMULL is UMADDL with Ra=XZR (31) +.gadget umaddl + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #5 // ra + + add x14, _cpu, #CPU_x0 + + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: + cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: + cmp x12, #31 + mov x17, #0 + b.eq 3f + ldr x17, [x14, x12, lsl #3] +3: + umaddl x3, w15, w16, x17 + + cmp x9, #31 + b.eq 4f + str x3, [x14, x9, lsl #3] +4: gret + +// UMSUBL: Xd = Xa - (zero_extend(Wn) * zero_extend(Wm)) +// UMNEGL is UMSUBL with Ra=XZR (31) +.gadget umsubl + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #5 // ra + + add x14, _cpu, #CPU_x0 + + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: + cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: + cmp x12, #31 + mov x17, #0 + b.eq 3f + ldr x17, [x14, x12, lsl #3] +3: + umsubl x3, w15, w16, x17 + + cmp x9, #31 + b.eq 4f + str x3, [x14, x9, lsl #3] +4: gret + + +/* + * Byte reverse gadgets (REV, REV16, REV32) + * Code stream: [gadget addr][rd | rn<<8 | sf<<24] + */ + +// REV - Reverse bytes (64-bit or 32-bit) +.gadget rev + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #24, #1 // sf + + add x13, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr _tmp, [x13, x10, lsl #3] + b 2f +1: mov _tmp, #0 +2: + // Byte reverse using rev instruction + cbz x12, .Lrev_32 + rev _tmp, _tmp + b .Lrev_store +.Lrev_32: + rev w0, w0 // _tmp is x0 +.Lrev_store: + cmp x9, #31 + b.eq 3f + str _tmp, [x13, x9, lsl #3] +3: gret + +// REV16 - Reverse bytes in each 16-bit halfword +.gadget rev16 + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #24, #1 // sf + + add x13, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr _tmp, [x13, x10, lsl #3] + b 2f +1: mov _tmp, #0 +2: + cbz x12, .Lrev16_32 + rev16 _tmp, _tmp + b .Lrev16_store +.Lrev16_32: + rev16 w0, w0 +.Lrev16_store: + cmp x9, #31 + b.eq 3f + str _tmp, [x13, x9, lsl #3] +3: gret + +// REV32 - Reverse bytes in each 32-bit word (64-bit only) +.gadget rev32 + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + + add x13, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr _tmp, [x13, x10, lsl #3] + b 2f +1: mov _tmp, #0 +2: + rev32 _tmp, _tmp + cmp x9, #31 + b.eq 3f + str _tmp, [x13, x9, lsl #3] +3: gret + +// CLZ - Count Leading Zeros +.gadget clz + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #24, #1 // sf + + add x13, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr _tmp, [x13, x10, lsl #3] + b 2f +1: mov _tmp, #0 +2: + cbz x12, .Lclz_32 + clz _tmp, _tmp + b .Lclz_store +.Lclz_32: + clz w0, w0 +.Lclz_store: + cmp x9, #31 + b.eq 3f + str _tmp, [x13, x9, lsl #3] +3: gret + +// CLS - Count Leading Sign bits +.gadget cls + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #24, #1 // sf + + add x13, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr _tmp, [x13, x10, lsl #3] + b 2f +1: mov _tmp, #0 +2: + cbz x12, .Lcls_32 + cls _tmp, _tmp + b .Lcls_store +.Lcls_32: + cls w0, w0 +.Lcls_store: + cmp x9, #31 + b.eq 3f + str _tmp, [x13, x9, lsl #3] +3: gret + +// RBIT - Reverse Bits +.gadget rbit + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #24, #1 // sf + + add x13, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr _tmp, [x13, x10, lsl #3] + b 2f +1: mov _tmp, #0 +2: + cbz x12, .Lrbit_32 + rbit _tmp, _tmp + b .Lrbit_store +.Lrbit_32: + rbit w0, w0 +.Lrbit_store: + cmp x9, #31 + b.eq 3f + str _tmp, [x13, x9, lsl #3] +3: gret + +/* + * System register gadgets + */ + +// MSR TPIDR_EL0, Xt - write TLS pointer +// Code stream: [gadget addr][rt] +.gadget msr_tpidr + ldr x8, [_pc] + add _pc, _pc, #8 + + and x8, x8, #0x1f // rt + + add x9, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + ldr x10, [x9, x8, lsl #3] + b 2f +1: mov x10, #0 +2: + str x10, [_cpu, #CPU_tls_ptr] + gret + +// MRS Xt, TPIDR_EL0 - read TLS pointer +// Code stream: [gadget addr][rt] +.gadget mrs_tpidr + ldr x8, [_pc] + add _pc, _pc, #8 + + and x8, x8, #0x1f // rt + + ldr x10, [_cpu, #CPU_tls_ptr] + + add x9, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + str x10, [x9, x8, lsl #3] +1: gret + +// MRS Xt, NZCV - read condition flags register +// Code stream: [gadget addr][rt] +// NZCV value is in bits [31:28] of the word +.gadget mrs_nzcv + ldr x8, [_pc] + add _pc, _pc, #8 + and x8, x8, #0x1f // rt + + ldr w10, [_cpu, #CPU_nzcv] + + add x9, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + // Zero-extend to 64-bit and store + mov x11, x10 + str x11, [x9, x8, lsl #3] +1: gret + +// MSR NZCV, Xt - write condition flags register +// Code stream: [gadget addr][rt] +.gadget msr_nzcv + ldr x8, [_pc] + add _pc, _pc, #8 + and x8, x8, #0x1f // rt + + add x9, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + ldr x10, [x9, x8, lsl #3] + b 2f +1: mov x10, #0 +2: + str w10, [_cpu, #CPU_nzcv] + gret + +// MSR FPCR, Xt - write floating-point control register +// Code stream: [gadget addr][rt] +.gadget msr_fpcr + ldr x8, [_pc] + add _pc, _pc, #8 + and x8, x8, #0x1f // rt + + add x9, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + ldr x10, [x9, x8, lsl #3] + b 2f +1: mov x10, #0 +2: + str w10, [_cpu, #CPU_fpcr] + gret + +// MSR FPSR, Xt - write floating-point status register +// Code stream: [gadget addr][rt] +.gadget msr_fpsr + ldr x8, [_pc] + add _pc, _pc, #8 + and x8, x8, #0x1f // rt + + add x9, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + ldr x10, [x9, x8, lsl #3] + b 2f +1: mov x10, #0 +2: + str w10, [_cpu, #CPU_fpsr] + gret + +// MSR DAIF, Xt - write interrupt mask register (NOP in emulation) +// Go runtime uses this for async preemption control. +// Code stream: [gadget addr][rt] +.gadget msr_daif + ldr x8, [_pc] + add _pc, _pc, #8 + // NOP — we don't emulate interrupt masking + gret + +// DC ZVA, Xt - zero a 64-byte naturally aligned data-cache block. +// Code stream: [gadget addr][rt] +.gadget dc_zva + ldr x8, [_pc] // rt + add _pc, _pc, #8 + and x8, x8, #0x1f + + add x9, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + ldr x12, [x9, x8, lsl #3] + b 2f +1: mov x12, #0 // XZR as the address operand if rt==31 +2: and x12, x12, #0xffffffffffff + and x12, x12, #0xffffffffffffffc0 + + stp x19, x20, [sp, #-16]! + mov x19, x12 + save_c + sub x0, _tlb, #TLB_entries + mov x1, x19 + mov x2, #64 + bl NAME(__tlb_zero) + mov x20, x0 + restore_c + cbz x20, 3f + ldp x19, x20, [sp], #16 + gret + +3: ldp x19, x20, [sp], #16 + ldr x8, [_tlb, #(-TLB_entries+TLB_segfault_addr)] + str x8, [_cpu, #CPU_segfault_addr] + mov w9, #1 + strb w9, [_cpu, #CPU_segfault_was_write] + ldr x8, [_cpu, #LOCAL_jit_saved_pc] + str x8, [_cpu, #CPU_pc] + mov w0, #INT_GPF + b fiber_exit + +// MRS Xt, <sysreg> - generic system register read +// Code stream: [gadget addr][rt][sysreg_id] +// sysreg_id values: +// 0 = TPIDR_EL0 (TLS pointer) +// 1 = CTR_EL0 (Cache Type Register) +// 2 = DCZID_EL0 (Data Cache Zero ID) +// 3 = FPCR (Floating-Point Control Register) +// 4 = FPSR (Floating-Point Status Register) +// 5 = RNDR (Random Number register) +// 6 = RNDRRS (Reseeded Random Number register) +// 7 = ID_AA64PFR0_EL1 +// 8 = ID_AA64PFR1_EL1 +// 9 = ID_AA64ISAR0_EL1 +// 10 = ID_AA64ISAR1_EL1 +// 11 = ID_AA64ZFR0_EL1 +// 12 = CNTVCT_EL0 +// 13 = CNTFRQ_EL0 +// 14 = MIDR_EL1 +// 15 = zero-valued feature/debug ID register +.gadget mrs_sysreg + ldr x8, [_pc] // rt + ldr x11, [_pc, #8] // sysreg_id + add _pc, _pc, #16 + + and x8, x8, #0x1f // rt + + // Load value based on sysreg_id + cmp x11, #0 + b.eq .Lmrs_tpidr_el0 + cmp x11, #1 + b.eq .Lmrs_ctr_el0 + cmp x11, #2 + b.eq .Lmrs_dczid_el0 + cmp x11, #3 + b.eq .Lmrs_fpcr + cmp x11, #4 + b.eq .Lmrs_fpsr + cmp x11, #5 + b.eq .Lmrs_rndr + cmp x11, #6 + b.eq .Lmrs_rndrrs + cmp x11, #7 + b.eq .Lmrs_id_aa64pfr0 + cmp x11, #8 + b.eq .Lmrs_id_aa64pfr1 + cmp x11, #9 + b.eq .Lmrs_id_aa64isar0 + cmp x11, #10 + b.eq .Lmrs_id_aa64isar1 + cmp x11, #11 + b.eq .Lmrs_id_aa64zfr0 + cmp x11, #12 + b.eq .Lmrs_cntvct_el0 + cmp x11, #13 + b.eq .Lmrs_cntfrq_el0 + cmp x11, #14 + b.eq .Lmrs_midr_el1 + cmp x11, #15 + b.eq .Lmrs_zero + // Unknown sysreg - return 0 + mov x10, #0 + b .Lmrs_store + +.Lmrs_tpidr_el0: + ldr x10, [_cpu, #CPU_tls_ptr] + b .Lmrs_store + +.Lmrs_ctr_el0: + // Cache Type Register - return typical ARM64 values + // IminLine = 4 (2^4 = 16 words = 64 bytes) + // DminLine = 4 (same) + // L1Ip = 3 (PIPT) + // ERG = 4 (64 bytes) + // CWG = 4 (64 bytes) + // Format: L1Ip[31:28]=3, ERG[27:24]=4, CWG[23:20]=4, DminLine[19:16]=4, IminLine[3:0]=4 + movz x10, #0x8444, lsl #16 + movk x10, #0x8004 + b .Lmrs_store + +.Lmrs_dczid_el0: + // Advertise DC ZVA with a 64-byte block (BS=4 => 4 << 4). + // HotSpot probes this register during startup and emits DC ZVA stubs when + // block zeroing is available; gadget_dc_zva implements the zeroing. + mov x10, #0x4 + b .Lmrs_store + +.Lmrs_fpcr: + ldr w10, [_cpu, #CPU_fpcr] + b .Lmrs_store + +.Lmrs_fpsr: + ldr w10, [_cpu, #CPU_fpsr] + b .Lmrs_store + +.Lmrs_rndr: + // RNDR - Random Number register (ARMv8.5-RNG) + // Return 0 and set Z=1 to indicate failure (no RNG available). + mov x10, #0 + movz w17, #0x4000, lsl #16 + msr nzcv, x17 + b .Lmrs_store + +.Lmrs_rndrrs: + // RNDRRS - Reseeded Random Number register (ARMv8.5-RNG) + // Return 0 and set Z=1 to indicate failure (no RNG available). + mov x10, #0 + movz w17, #0x4000, lsl #16 + msr nzcv, x17 + b .Lmrs_store + +.Lmrs_id_aa64pfr0: + // ID_AA64PFR0_EL1: + // EL0/EL1 AArch64 supported (bits [3:0]=1, [7:4]=1), SVE=0. + mov x10, #0x11 + b .Lmrs_store + +.Lmrs_id_aa64pfr1: + // ID_AA64PFR1_EL1: report no optional features. + mov x10, #0 + b .Lmrs_store + +.Lmrs_id_aa64isar0: + // ID_AA64ISAR0_EL1: report no optional crypto/SVE-related extensions. + mov x10, #0 + b .Lmrs_store + +.Lmrs_id_aa64isar1: + // ID_AA64ISAR1_EL1: report no optional extensions. + mov x10, #0 + b .Lmrs_store + +.Lmrs_id_aa64zfr0: + // ID_AA64ZFR0_EL1: SVE not supported. + mov x10, #0 + b .Lmrs_store + +.Lmrs_cntvct_el0: + // CNTVCT_EL0 - Virtual counter timer + // Read the host's virtual counter directly (same hardware) + mrs x10, cntvct_el0 + b .Lmrs_store + +.Lmrs_cntfrq_el0: + // CNTFRQ_EL0 - Counter-timer frequency + mrs x10, cntfrq_el0 + b .Lmrs_store + +.Lmrs_midr_el1: + // MIDR_EL1 - expose a generic ARMv8 Cortex-A53-class ID. Optional + // features remain governed by HWCAP/ID_AA64* registers above. + movz x10, #0xd034 + movk x10, #0x410f, lsl #16 + b .Lmrs_store + +.Lmrs_zero: + mov x10, #0 + b .Lmrs_store + +.Lmrs_store: + add x9, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + str x10, [x9, x8, lsl #3] +1: gret + +/* + * SIMD Gadgets (minimal set for musl memset) + * + * These implement just enough SIMD to support musl's optimized memset. + */ + +/* + * DUP Vd.16B, Wn - Duplicate byte from GPR to all 16 lanes + * Code stream: [gadget addr][rd | rn<<8] + * + * This duplicates the low 8 bits of GPR Rn to all 16 bytes of vector Vd. + */ +.gadget dup_gpr_to_v16b + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (vector) + ubfx x10, x8, #8, #5 // rn (gpr) + + // Load GPR value + add x11, _cpu, #CPU_x0 + ldr x12, [x11, x10, lsl #3] + + // Extract low byte and replicate to all 16 bytes + and x12, x12, #0xff + // Create pattern: 0x0101010101010101 * byte_value + mov x13, #0x0101010101010101 + mul x14, x12, x13 + + // Store to vector register (both 64-bit halves) + add x15, _cpu, #CPU_fp + lsl x16, x9, #4 // each V reg is 16 bytes + add x15, x15, x16 // x15 = base of vector register + str x14, [x15] + str x14, [x15, #8] + gret + +/* + * DUP Vd.<T>, Wn - Duplicate element from GPR to all vector lanes (general) + * Code stream: [gadget addr][rd | rn<<8 | elem_size<<16 | Q<<24] + * + * elem_size: 0=B (byte), 1=H (halfword), 2=S (word), 3=D (doubleword) + * Q: 0=64-bit vector (lower half only), 1=128-bit vector + */ +.gadget dup_gpr_to_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (vector) + ubfx x10, x8, #8, #5 // rn (gpr) + ubfx x11, x8, #16, #4 // elem_size + ubfx x17, x8, #24, #1 // Q + + // Load GPR value + add x12, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr x13, [x12, x10, lsl #3] + b 2f +1: mov x13, #0 // XZR +2: + // Get vector register base + add x15, _cpu, #CPU_fp + lsl x16, x9, #4 // each V reg is 16 bytes + add x15, x15, x16 // x15 = base of vector register + + // Branch based on element size + cmp x11, #0 + b.eq .Ldup_byte + cmp x11, #1 + b.eq .Ldup_halfword + cmp x11, #2 + b.eq .Ldup_word + b .Ldup_doubleword + +.Ldup_byte: + // Replicate byte to all 8 bytes in a 64-bit word + and x13, x13, #0xff + mov x14, #0x0101010101010101 + mul x14, x13, x14 + str x14, [x15] // low 64 bits + cbz x17, .Ldup_clear_high + str x14, [x15, #8] // high 64 bits (only if Q=1) + gret + +.Ldup_halfword: + // Replicate halfword to all 4 halfwords in a 64-bit word + and x13, x13, #0xffff + mov x14, #0x0001000100010001 + mul x14, x13, x14 + str x14, [x15] + cbz x17, .Ldup_clear_high + str x14, [x15, #8] + gret + +.Ldup_word: + // Replicate word to both words in a 64-bit value + and x13, x13, #0xffffffff + orr x14, x13, x13, lsl #32 + str x14, [x15] + cbz x17, .Ldup_clear_high + str x14, [x15, #8] + gret + +.Ldup_doubleword: + // Just duplicate the 64-bit value + str x13, [x15] + cbz x17, .Ldup_clear_high + str x13, [x15, #8] + gret + +.Ldup_clear_high: + // For Q=0, clear the high 64 bits + str xzr, [x15, #8] + gret + +/* + * DUP Vd.<T>, Vn.<Ts>[idx] - Duplicate element from vector to all lanes + * Code stream: [gadget addr][rd | rn<<8 | elem_size<<16 | index<<20 | Q<<24] + * + * elem_size: 0=B (byte), 1=H (halfword), 2=S (word), 3=D (doubleword) + * index: element index to duplicate + * Q: 0=64-bit vector (lower half only), 1=128-bit vector + */ +.gadget dup_elem_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (vector) + ubfx x10, x8, #8, #5 // rn (vector) + ubfx x11, x8, #16, #4 // elem_size + ubfx x12, x8, #20, #4 // index + ubfx x17, x8, #24, #1 // Q + + // Get source and destination vector register bases + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 // source offset + add x14, x13, x14 // x14 = &Vn + lsl x15, x9, #4 // dest offset + add x15, x13, x15 // x15 = &Vd + + // Load the source vector into v0 + ldr q0, [x14] + + // Branch based on element size + cmp x11, #0 + b.eq .Ldup_elem_byte + cmp x11, #1 + b.eq .Ldup_elem_half + cmp x11, #2 + b.eq .Ldup_elem_word + b .Ldup_elem_dword + +.Ldup_elem_byte: + // DUP Vd.xB, Vn.B[idx] + // Use native dup instruction by loading index into vector and using TBL + // Simpler: extract byte and broadcast manually + // x12 = index (0-15) + // Extract the byte at index into x13 + and x12, x12, #0xf + lsr x16, x12, #3 // which 64-bit half (0 or 1) + and x12, x12, #7 // byte offset within half + cbz x16, .Ldup_elem_byte_lo + mov x13, v0.d[1] + b .Ldup_elem_byte_extract +.Ldup_elem_byte_lo: + mov x13, v0.d[0] +.Ldup_elem_byte_extract: + lsl x12, x12, #3 // bit offset + lsr x13, x13, x12 + and x13, x13, #0xff + // Broadcast byte to all lanes + mov x14, #0x0101010101010101 + mul x14, x13, x14 + str x14, [x15] + cbz x17, .Ldup_elem_clear_high + str x14, [x15, #8] + gret + +.Ldup_elem_half: + // DUP Vd.xH, Vn.H[idx] + and x12, x12, #0x7 + lsr x16, x12, #2 // which 64-bit half + and x12, x12, #3 // halfword offset within half + cbz x16, .Ldup_elem_half_lo + mov x13, v0.d[1] + b .Ldup_elem_half_extract +.Ldup_elem_half_lo: + mov x13, v0.d[0] +.Ldup_elem_half_extract: + lsl x12, x12, #4 // bit offset (16 bits per element) + lsr x13, x13, x12 + and x13, x13, #0xffff + mov x14, #0x0001000100010001 + mul x14, x13, x14 + str x14, [x15] + cbz x17, .Ldup_elem_clear_high + str x14, [x15, #8] + gret + +.Ldup_elem_word: + // DUP Vd.xS, Vn.S[idx] + and x12, x12, #0x3 + lsr x16, x12, #1 // which 64-bit half + and x12, x12, #1 // word offset within half + cbz x16, .Ldup_elem_word_lo + mov x13, v0.d[1] + b .Ldup_elem_word_extract +.Ldup_elem_word_lo: + mov x13, v0.d[0] +.Ldup_elem_word_extract: + cbz x12, .Ldup_elem_word_done + lsr x13, x13, #32 // get high word +.Ldup_elem_word_done: + and x13, x13, #0xffffffff + orr x14, x13, x13, lsl #32 + str x14, [x15] + cbz x17, .Ldup_elem_clear_high + str x14, [x15, #8] + gret + +.Ldup_elem_dword: + // DUP Vd.2D, Vn.D[idx] + and x12, x12, #0x1 + cbz x12, .Ldup_elem_dword_lo + mov x13, v0.d[1] + b .Ldup_elem_dword_store +.Ldup_elem_dword_lo: + mov x13, v0.d[0] +.Ldup_elem_dword_store: + str x13, [x15] + cbz x17, .Ldup_elem_clear_high + str x13, [x15, #8] + gret + +.Ldup_elem_clear_high: + str xzr, [x15, #8] + gret + +/* + * DUP <V>d, Vn.<T>[idx] - Duplicate element from vector to scalar register + * Code stream: [gadget addr][rd | rn<<8 | elem_size<<16 | index<<20] + * + * elem_size: 0=B (byte), 1=H (halfword), 2=S (word), 3=D (doubleword) + * index: element index to duplicate + * Result is stored in a scalar register (B/H/S/D) with upper bits cleared + */ +.gadget dup_elem_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (scalar dest) + ubfx x10, x8, #8, #5 // rn (vector source) + ubfx x11, x8, #16, #4 // elem_size + ubfx x12, x8, #20, #4 // index + + // Get source vector register base + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x14, x13, x14 // x14 = &Vn + + // Get destination register base + lsl x15, x9, #4 + add x15, x13, x15 // x15 = &Vd + + // Load the source vector into v0 + ldr q0, [x14] + + // Branch based on element size + cmp x11, #0 + b.eq .Ldup_scalar_byte + cmp x11, #1 + b.eq .Ldup_scalar_half + cmp x11, #2 + b.eq .Ldup_scalar_word + b .Ldup_scalar_dword + +.Ldup_scalar_byte: + // DUP Bd, Vn.B[idx] + and x12, x12, #0xf + lsr x16, x12, #3 // which 64-bit half (0 or 1) + and x12, x12, #7 // byte offset within half + cbz x16, .Ldup_scalar_byte_lo + mov x13, v0.d[1] + b .Ldup_scalar_byte_extract +.Ldup_scalar_byte_lo: + mov x13, v0.d[0] +.Ldup_scalar_byte_extract: + lsl x12, x12, #3 // bit offset + lsr x13, x13, x12 + and x13, x13, #0xff + // Store byte to scalar, clear rest + str x13, [x15] + str xzr, [x15, #8] + gret + +.Ldup_scalar_half: + // DUP Hd, Vn.H[idx] + and x12, x12, #0x7 + lsr x16, x12, #2 // which 64-bit half + and x12, x12, #3 // halfword offset within half + cbz x16, .Ldup_scalar_half_lo + mov x13, v0.d[1] + b .Ldup_scalar_half_extract +.Ldup_scalar_half_lo: + mov x13, v0.d[0] +.Ldup_scalar_half_extract: + lsl x12, x12, #4 // bit offset (16 bits per element) + lsr x13, x13, x12 + and x13, x13, #0xffff + str x13, [x15] + str xzr, [x15, #8] + gret + +.Ldup_scalar_word: + // DUP Sd, Vn.S[idx] + and x12, x12, #0x3 + lsr x16, x12, #1 // which 64-bit half + and x12, x12, #1 // word offset within half + cbz x16, .Ldup_scalar_word_lo + mov x13, v0.d[1] + b .Ldup_scalar_word_extract +.Ldup_scalar_word_lo: + mov x13, v0.d[0] +.Ldup_scalar_word_extract: + cbz x12, .Ldup_scalar_word_done + lsr x13, x13, #32 // get high word +.Ldup_scalar_word_done: + and x13, x13, #0xffffffff + str x13, [x15] + str xzr, [x15, #8] + gret + +.Ldup_scalar_dword: + // DUP Dd, Vn.D[idx] + and x12, x12, #0x1 + cbz x12, .Ldup_scalar_dword_lo + mov x13, v0.d[1] + b .Ldup_scalar_dword_store +.Ldup_scalar_dword_lo: + mov x13, v0.d[0] +.Ldup_scalar_dword_store: + str x13, [x15] + str xzr, [x15, #8] + gret + +/* + * INS Vd.<T>[dst_idx], Vn.<T>[src_idx] - Insert element from one vector to another + * Code stream: [gadget addr][rd | rn<<8 | elem_size<<16 | dst_idx<<20 | src_idx<<24] + * + * elem_size: 0=B, 1=H, 2=S, 3=D + */ +.gadget ins_elem_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (vector) + ubfx x10, x8, #8, #5 // rn (vector) + ubfx x11, x8, #16, #4 // elem_size + ubfx x12, x8, #20, #4 // dst_idx + ubfx x13, x8, #24, #4 // src_idx + + // Get source and destination vector register bases + add x14, _cpu, #CPU_fp + lsl x15, x10, #4 + add x15, x14, x15 // x15 = &Vn (source) + lsl x16, x9, #4 + add x16, x14, x16 // x16 = &Vd (destination) + + // Load source vector + ldr q0, [x15] + // Load destination vector (we'll modify one element) + ldr q1, [x16] + + // Branch based on element size + cmp x11, #0 + b.eq .Lins_elem_byte + cmp x11, #1 + b.eq .Lins_elem_half + cmp x11, #2 + b.eq .Lins_elem_word + b .Lins_elem_dword + +.Lins_elem_byte: + // Extract source byte at src_idx + and x13, x13, #0xf + lsr x17, x13, #3 // which half + and x13, x13, #7 // byte within half + cbz x17, .Lins_byte_src_lo + mov x3, v0.d[1] + b .Lins_byte_src_done +.Lins_byte_src_lo: + mov x3, v0.d[0] +.Lins_byte_src_done: + lsl x13, x13, #3 + lsr x3, x3, x13 + and x3, x3, #0xff // x3 = source byte + + // Insert into destination at dst_idx + and x12, x12, #0xf + lsr x17, x12, #3 // which half + and x12, x12, #7 // byte within half + lsl x12, x12, #3 // bit offset + + mov x19, #0xff + lsl x19, x19, x12 // mask for target byte + lsl x3, x3, x12 // shift source to position + + cbz x17, .Lins_byte_dst_lo + mov x20, v1.d[1] + bic x20, x20, x19 // clear target byte + orr x20, x20, x3 // insert source + mov v1.d[1], x20 + b .Lins_byte_store +.Lins_byte_dst_lo: + mov x20, v1.d[0] + bic x20, x20, x19 + orr x20, x20, x3 + mov v1.d[0], x20 +.Lins_byte_store: + str q1, [x16] + gret + +.Lins_elem_half: + // Extract source halfword at src_idx + and x13, x13, #0x7 + lsr x17, x13, #2 + and x13, x13, #3 + cbz x17, .Lins_half_src_lo + mov x3, v0.d[1] + b .Lins_half_src_done +.Lins_half_src_lo: + mov x3, v0.d[0] +.Lins_half_src_done: + lsl x13, x13, #4 + lsr x3, x3, x13 + and x3, x3, #0xffff + + and x12, x12, #0x7 + lsr x17, x12, #2 + and x12, x12, #3 + lsl x12, x12, #4 + + mov x19, #0xffff + lsl x19, x19, x12 + lsl x3, x3, x12 + + cbz x17, .Lins_half_dst_lo + mov x20, v1.d[1] + bic x20, x20, x19 + orr x20, x20, x3 + mov v1.d[1], x20 + b .Lins_half_store +.Lins_half_dst_lo: + mov x20, v1.d[0] + bic x20, x20, x19 + orr x20, x20, x3 + mov v1.d[0], x20 +.Lins_half_store: + str q1, [x16] + gret + +.Lins_elem_word: + // Extract source word at src_idx + and x13, x13, #0x3 + lsr x17, x13, #1 + and x13, x13, #1 + cbz x17, .Lins_word_src_lo + mov x3, v0.d[1] + b .Lins_word_src_done +.Lins_word_src_lo: + mov x3, v0.d[0] +.Lins_word_src_done: + cbz x13, .Lins_word_src_shifted + lsr x3, x3, #32 +.Lins_word_src_shifted: + and x3, x3, #0xffffffff + + and x12, x12, #0x3 + lsr x17, x12, #1 + and x12, x12, #1 + + cbz x17, .Lins_word_dst_lo + mov x20, v1.d[1] + cbz x12, .Lins_word_dst_hi_lo + // Insert into high word of high half + and x20, x20, #0xffffffff + orr x20, x20, x3, lsl #32 + b .Lins_word_dst_hi_done +.Lins_word_dst_hi_lo: + // Insert into low word of high half + and x20, x20, #0xffffffff00000000 + orr x20, x20, x3 +.Lins_word_dst_hi_done: + mov v1.d[1], x20 + b .Lins_word_store +.Lins_word_dst_lo: + mov x20, v1.d[0] + cbz x12, .Lins_word_dst_lo_lo + // Insert into high word of low half + and x20, x20, #0xffffffff + orr x20, x20, x3, lsl #32 + b .Lins_word_dst_lo_done +.Lins_word_dst_lo_lo: + // Insert into low word of low half + and x20, x20, #0xffffffff00000000 + orr x20, x20, x3 +.Lins_word_dst_lo_done: + mov v1.d[0], x20 +.Lins_word_store: + str q1, [x16] + gret + +.Lins_elem_dword: + // Extract source doubleword at src_idx + and x13, x13, #0x1 + cbz x13, .Lins_dword_src_lo + mov x3, v0.d[1] + b .Lins_dword_src_done +.Lins_dword_src_lo: + mov x3, v0.d[0] +.Lins_dword_src_done: + + and x12, x12, #0x1 + cbz x12, .Lins_dword_dst_lo + mov v1.d[1], x3 + b .Lins_dword_store +.Lins_dword_dst_lo: + mov v1.d[0], x3 +.Lins_dword_store: + str q1, [x16] + gret + +/* + * MOV Xd, Vn.D[0] - Move low 64 bits of vector to GPR + * Code stream: [gadget addr][rd | rn<<8] + */ +.gadget mov_v_to_gpr + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (gpr) + ubfx x10, x8, #8, #5 // rn (vector) + + // Load low 64 bits of vector + add x11, _cpu, #CPU_fp + lsl x12, x10, #4 // each V reg is 16 bytes + ldr x13, [x11, x12] + + // Store to GPR (check for XZR) + cmp x9, #31 + b.eq 1f // XZR - discard + add x14, _cpu, #CPU_x0 + str x13, [x14, x9, lsl #3] +1: gret + +/* + * UMOV/MOV - Move vector element to GPR (zero-extend) + * Code stream: [gadget addr][rd | rn<<8 | elem_size<<16 | index<<20] + * + * elem_size: 0=B, 1=H, 2=S, 3=D + * index: element index within 128-bit vector + */ +.gadget umov_vec_to_gpr + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #2 // elem_size + ubfx x12, x8, #20, #4 // index + + // Load vector register + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x14, x13, x14 // &Vn + ldr x15, [x14] // low 64 + ldr x16, [x14, #8] // high 64 + + // Extract element based on size/index + cmp x11, #0 + b.eq .Lumov_b + cmp x11, #1 + b.eq .Lumov_h + cmp x11, #2 + b.eq .Lumov_s + // size == 3 (D) + b .Lumov_d + +.Lumov_b: + cmp x12, #8 + b.lt .Lumov_b_low + sub x12, x12, #8 + lsl x17, x12, #3 + lsr x3, x16, x17 + and x3, x3, #0xff + b .Lumov_store +.Lumov_b_low: + lsl x17, x12, #3 + lsr x3, x15, x17 + and x3, x3, #0xff + b .Lumov_store + +.Lumov_h: + cmp x12, #4 + b.lt .Lumov_h_low + sub x12, x12, #4 + lsl x17, x12, #4 + lsr x3, x16, x17 + and x3, x3, #0xffff + b .Lumov_store +.Lumov_h_low: + lsl x17, x12, #4 + lsr x3, x15, x17 + and x3, x3, #0xffff + b .Lumov_store + +.Lumov_s: + cmp x12, #2 + b.lt .Lumov_s_low + sub x12, x12, #2 + lsl x17, x12, #5 + lsr x3, x16, x17 + and x3, x3, #0xffffffff + b .Lumov_store +.Lumov_s_low: + lsl x17, x12, #5 + lsr x3, x15, x17 + and x3, x3, #0xffffffff + b .Lumov_store + +.Lumov_d: + cbz x12, .Lumov_d_low + mov x3, x16 + b .Lumov_store +.Lumov_d_low: + mov x3, x15 + +.Lumov_store: + add x14, _cpu, #CPU_x0 + cmp x9, #31 + b.eq .Lumov_done + str x3, [x14, x9, lsl #3] +.Lumov_done: + gret + +/* + * MOV/INS - Insert GPR into vector element (S size) + * Code stream: [gadget addr][rd | rn<<8 | index<<16] + * + * rd: destination vector register + * rn: source GPR (Wn) + * index: S element index (0..3) + */ +.gadget ins_gpr_to_vec_s + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (vector) + ubfx x10, x8, #8, #5 // rn (gpr) + ubfx x11, x8, #16, #2 // index + + // Load 32-bit value from GPR + add x12, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr x13, [x12, x10, lsl #3] + b 2f +1: mov w13, #0 +2: + // Compute address of destination vector element + add x14, _cpu, #CPU_fp + lsl x15, x9, #4 + add x14, x14, x15 + add x14, x14, x11, lsl #2 + + // Store element + str w13, [x14] + gret + +/* + * MOV/INS - Insert GPR into vector element (D size) + * Code stream: [gadget addr][rd | rn<<8 | index<<16] + * + * rd: destination vector register + * rn: source GPR (Xn) + * index: D element index (0..1) + */ +.gadget ins_gpr_to_vec_d + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (vector) + ubfx x10, x8, #8, #5 // rn (gpr) + ubfx x11, x8, #16, #1 // index (0 or 1) + + // Load 64-bit value from GPR + add x12, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr x13, [x12, x10, lsl #3] + b 2f +1: mov x13, #0 +2: + // Compute address of destination vector element + add x14, _cpu, #CPU_fp + lsl x15, x9, #4 + add x14, x14, x15 + add x14, x14, x11, lsl #3 // D element is 8 bytes + + // Store element + str x13, [x14] + gret + +/* + * MOV/INS - Insert GPR into vector element (H/halfword size) + * Code stream: [gadget addr][rd | rn<<8 | index<<16] + */ +.gadget ins_gpr_to_vec_h + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (vector) + ubfx x10, x8, #8, #5 // rn (gpr) + ubfx x11, x8, #16, #3 // index (0..7) + + add x12, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr x13, [x12, x10, lsl #3] + b 2f +1: mov w13, #0 +2: + add x14, _cpu, #CPU_fp + lsl x15, x9, #4 + add x14, x14, x15 + add x14, x14, x11, lsl #1 // H element is 2 bytes + + strh w13, [x14] + gret + +/* + * MOV/INS - Insert GPR into vector element (B/byte size) + * Code stream: [gadget addr][rd | rn<<8 | index<<16] + */ +.gadget ins_gpr_to_vec_b + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (vector) + ubfx x10, x8, #8, #5 // rn (gpr) + ubfx x11, x8, #16, #4 // index (0..15) + + add x12, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr x13, [x12, x10, lsl #3] + b 2f +1: mov w13, #0 +2: + add x14, _cpu, #CPU_fp + lsl x15, x9, #4 + add x14, x14, x15 + add x14, x14, x11 // B element is 1 byte + + strb w13, [x14] + gret + +/* + * SSHLL - Signed shift left long (B->H) + * Code stream: [gadget addr][rd | rn<<8 | shift<<16] + * Extends 8 bytes to 8 halfwords (sign-extend), then shift left + */ +.gadget sshll_vec_b_to_h + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #4 // shift (0..7) + + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 // &Vn + + // Load 8 source bytes + ldr x14, [x12] + + // Sign-extend each byte to halfword and shift + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 // &Vd + + // Element 0 + sbfx x15, x14, #0, #8 + lsl x15, x15, x11 + strh w15, [x17, #0] + // Element 1 + sbfx x15, x14, #8, #8 + lsl x15, x15, x11 + strh w15, [x17, #2] + // Element 2 + sbfx x15, x14, #16, #8 + lsl x15, x15, x11 + strh w15, [x17, #4] + // Element 3 + sbfx x15, x14, #24, #8 + lsl x15, x15, x11 + strh w15, [x17, #6] + // Element 4 + sbfx x15, x14, #32, #8 + lsl x15, x15, x11 + strh w15, [x17, #8] + // Element 5 + sbfx x15, x14, #40, #8 + lsl x15, x15, x11 + strh w15, [x17, #10] + // Element 6 + sbfx x15, x14, #48, #8 + lsl x15, x15, x11 + strh w15, [x17, #12] + // Element 7 + sbfx x15, x14, #56, #8 + lsl x15, x15, x11 + strh w15, [x17, #14] + gret + +/* + * USHLL - Unsigned shift left long (B->H) + * Code stream: [gadget addr][rd | rn<<8 | shift<<16] + */ +.gadget ushll_vec_b_to_h + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #4 + + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + + ldr x14, [x12] + + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + + // Zero-extend each byte to halfword and shift + ubfx x15, x14, #0, #8 + lsl x15, x15, x11 + strh w15, [x17, #0] + ubfx x15, x14, #8, #8 + lsl x15, x15, x11 + strh w15, [x17, #2] + ubfx x15, x14, #16, #8 + lsl x15, x15, x11 + strh w15, [x17, #4] + ubfx x15, x14, #24, #8 + lsl x15, x15, x11 + strh w15, [x17, #6] + ubfx x15, x14, #32, #8 + lsl x15, x15, x11 + strh w15, [x17, #8] + ubfx x15, x14, #40, #8 + lsl x15, x15, x11 + strh w15, [x17, #10] + ubfx x15, x14, #48, #8 + lsl x15, x15, x11 + strh w15, [x17, #12] + ubfx x15, x14, #56, #8 + lsl x15, x15, x11 + strh w15, [x17, #14] + gret + +/* + * SSHLL - Signed shift left long (H->S) + * Code stream: [gadget addr][rd | rn<<8 | shift<<16] + * Extends 4 halfwords to 4 words (sign-extend), then shift left + */ +.gadget sshll_vec_h_to_s + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #4 // shift (0..15) + + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + + ldr x14, [x12] // 4 halfwords in 64 bits + + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + + // Sign-extend each halfword to word and shift + sbfx x15, x14, #0, #16 + lsl w15, w15, w11 + str w15, [x17, #0] + sbfx x15, x14, #16, #16 + lsl w15, w15, w11 + str w15, [x17, #4] + sbfx x15, x14, #32, #16 + lsl w15, w15, w11 + str w15, [x17, #8] + sbfx x15, x14, #48, #16 + lsl w15, w15, w11 + str w15, [x17, #12] + gret + +/* + * USHLL - Unsigned shift left long (H->S) + * Code stream: [gadget addr][rd | rn<<8 | shift<<16] + */ +.gadget ushll_vec_h_to_s + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #4 + + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + + ldr x14, [x12] + + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + + // Zero-extend each halfword to word and shift + ubfx x15, x14, #0, #16 + lsl w15, w15, w11 + str w15, [x17, #0] + ubfx x15, x14, #16, #16 + lsl w15, w15, w11 + str w15, [x17, #4] + ubfx x15, x14, #32, #16 + lsl w15, w15, w11 + str w15, [x17, #8] + ubfx x15, x14, #48, #16 + lsl w15, w15, w11 + str w15, [x17, #12] + gret + +/* + * SSHLL2 - Signed shift left long (B->H, upper half) + * Code stream: [gadget addr][rd | rn<<8 | shift<<16] + * Reads bytes 8..15, sign-extends to 8 halfwords + */ +.gadget sshll2_vec_b_to_h + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #4 + + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + ldr x14, [x12, #8] // upper 8 bytes + + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + + sbfx x15, x14, #0, #8 + lsl x15, x15, x11 + strh w15, [x17, #0] + sbfx x15, x14, #8, #8 + lsl x15, x15, x11 + strh w15, [x17, #2] + sbfx x15, x14, #16, #8 + lsl x15, x15, x11 + strh w15, [x17, #4] + sbfx x15, x14, #24, #8 + lsl x15, x15, x11 + strh w15, [x17, #6] + sbfx x15, x14, #32, #8 + lsl x15, x15, x11 + strh w15, [x17, #8] + sbfx x15, x14, #40, #8 + lsl x15, x15, x11 + strh w15, [x17, #10] + sbfx x15, x14, #48, #8 + lsl x15, x15, x11 + strh w15, [x17, #12] + sbfx x15, x14, #56, #8 + lsl x15, x15, x11 + strh w15, [x17, #14] + gret + +.gadget ushll2_vec_b_to_h + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #4 + + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + ldr x14, [x12, #8] + + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + + ubfx x15, x14, #0, #8 + lsl x15, x15, x11 + strh w15, [x17, #0] + ubfx x15, x14, #8, #8 + lsl x15, x15, x11 + strh w15, [x17, #2] + ubfx x15, x14, #16, #8 + lsl x15, x15, x11 + strh w15, [x17, #4] + ubfx x15, x14, #24, #8 + lsl x15, x15, x11 + strh w15, [x17, #6] + ubfx x15, x14, #32, #8 + lsl x15, x15, x11 + strh w15, [x17, #8] + ubfx x15, x14, #40, #8 + lsl x15, x15, x11 + strh w15, [x17, #10] + ubfx x15, x14, #48, #8 + lsl x15, x15, x11 + strh w15, [x17, #12] + ubfx x15, x14, #56, #8 + lsl x15, x15, x11 + strh w15, [x17, #14] + gret + +.gadget sshll2_vec_h_to_s + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #4 + + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + ldr x14, [x12, #8] // upper 4 halfwords + + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + + sbfx x15, x14, #0, #16 + lsl w15, w15, w11 + str w15, [x17, #0] + sbfx x15, x14, #16, #16 + lsl w15, w15, w11 + str w15, [x17, #4] + sbfx x15, x14, #32, #16 + lsl w15, w15, w11 + str w15, [x17, #8] + sbfx x15, x14, #48, #16 + lsl w15, w15, w11 + str w15, [x17, #12] + gret + +.gadget ushll2_vec_h_to_s + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #4 + + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + ldr x14, [x12, #8] + + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + + ubfx x15, x14, #0, #16 + lsl w15, w15, w11 + str w15, [x17, #0] + ubfx x15, x14, #16, #16 + lsl w15, w15, w11 + str w15, [x17, #4] + ubfx x15, x14, #32, #16 + lsl w15, w15, w11 + str w15, [x17, #8] + ubfx x15, x14, #48, #16 + lsl w15, w15, w11 + str w15, [x17, #12] + gret + +.gadget sshll2_vec_s_to_d + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + ldr x14, [x12, #8] // upper 2 words + + sxtw x15, w14 + asr x16, x14, #32 + + lsl x15, x15, x11 + lsl x16, x16, x11 + + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + str x15, [x17] + str x16, [x17, #8] + gret + +.gadget ushll2_vec_s_to_d + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + ldr x14, [x12, #8] + + uxtw x15, w14 + lsr x16, x14, #32 + + lsl x15, x15, x11 + lsl x16, x16, x11 + + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + str x15, [x17] + str x16, [x17, #8] + gret + +/* + * SSHLL - Signed shift left long (S->D) + * Code stream: [gadget addr][rd | rn<<8 | shift<<16] + * + * rd: destination vector register (Vd.2D) + * rn: source vector register (Vn.2S) + * shift: immediate shift (0..31) + */ +.gadget sshll_vec_s_to_d + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // shift + + // Load source vector low 64 bits (two 32-bit elements) + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + ldr x14, [x12] + + // Sign-extend each 32-bit element + sxtw x15, w14 // element 0 + asr x16, x14, #32 // element 1 (sign-extended) + + // Shift left by immediate + lsl x15, x15, x11 + lsl x16, x16, x11 + + // Store to destination vector + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + str x15, [x17] + str x16, [x17, #8] + gret + +/* + * USHLL - Unsigned shift left long (S->D) + * Code stream: [gadget addr][rd | rn<<8 | shift<<16] + * + * rd: destination vector register (Vd.2D) + * rn: source vector register (Vn.2S) + * shift: immediate shift (0..31) + */ +.gadget ushll_vec_s_to_d + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // shift + + // Load source vector low 64 bits (two 32-bit elements) + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + ldr x14, [x12] + + // Zero-extend each 32-bit element + uxtw x15, w14 // element 0 + lsr x16, x14, #32 // element 1 + + // Shift left by immediate + lsl x15, x15, x11 + lsl x16, x16, x11 + + // Store to destination vector + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + str x15, [x17] + str x16, [x17, #8] + gret + +/* + * SHLL/SHLL2 - Shift left long by element size (two-reg misc) + * Code stream: [gadget addr][rd | rn<<8] + * Shift is fixed at element size (8 for B->H, 16 for H->S, 32 for S->D) + */ + +// SHLL B->H: each byte << 8, result is halfword +.gadget shll_vec_b_to_h + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + ldr x14, [x12] // lower 8 bytes + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + ubfx x15, x14, #0, #8 + lsl x15, x15, #8 + strh w15, [x17, #0] + ubfx x15, x14, #8, #8 + lsl x15, x15, #8 + strh w15, [x17, #2] + ubfx x15, x14, #16, #8 + lsl x15, x15, #8 + strh w15, [x17, #4] + ubfx x15, x14, #24, #8 + lsl x15, x15, #8 + strh w15, [x17, #6] + ubfx x15, x14, #32, #8 + lsl x15, x15, #8 + strh w15, [x17, #8] + ubfx x15, x14, #40, #8 + lsl x15, x15, #8 + strh w15, [x17, #10] + ubfx x15, x14, #48, #8 + lsl x15, x15, #8 + strh w15, [x17, #12] + ubfx x15, x14, #56, #8 + lsl x15, x15, #8 + strh w15, [x17, #14] + gret + +// SHLL2 B->H: upper 8 bytes << 8 +.gadget shll2_vec_b_to_h + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + ldr x14, [x12, #8] // upper 8 bytes + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + ubfx x15, x14, #0, #8 + lsl x15, x15, #8 + strh w15, [x17, #0] + ubfx x15, x14, #8, #8 + lsl x15, x15, #8 + strh w15, [x17, #2] + ubfx x15, x14, #16, #8 + lsl x15, x15, #8 + strh w15, [x17, #4] + ubfx x15, x14, #24, #8 + lsl x15, x15, #8 + strh w15, [x17, #6] + ubfx x15, x14, #32, #8 + lsl x15, x15, #8 + strh w15, [x17, #8] + ubfx x15, x14, #40, #8 + lsl x15, x15, #8 + strh w15, [x17, #10] + ubfx x15, x14, #48, #8 + lsl x15, x15, #8 + strh w15, [x17, #12] + ubfx x15, x14, #56, #8 + lsl x15, x15, #8 + strh w15, [x17, #14] + gret + +// SHLL H->S: each halfword << 16 +.gadget shll_vec_h_to_s + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + ldr x14, [x12] + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + ubfx x15, x14, #0, #16 + lsl w15, w15, #16 + str w15, [x17, #0] + ubfx x15, x14, #16, #16 + lsl w15, w15, #16 + str w15, [x17, #4] + ubfx x15, x14, #32, #16 + lsl w15, w15, #16 + str w15, [x17, #8] + ubfx x15, x14, #48, #16 + lsl w15, w15, #16 + str w15, [x17, #12] + gret + +// SHLL2 H->S: upper 4 halfwords << 16 +.gadget shll2_vec_h_to_s + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + ldr x14, [x12, #8] + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + ubfx x15, x14, #0, #16 + lsl w15, w15, #16 + str w15, [x17, #0] + ubfx x15, x14, #16, #16 + lsl w15, w15, #16 + str w15, [x17, #4] + ubfx x15, x14, #32, #16 + lsl w15, w15, #16 + str w15, [x17, #8] + ubfx x15, x14, #48, #16 + lsl w15, w15, #16 + str w15, [x17, #12] + gret + +// SHLL S->D: each word << 32 +.gadget shll_vec_s_to_d + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + ldr x14, [x12] + uxtw x15, w14 + lsl x15, x15, #32 + lsr x16, x14, #32 + lsl x16, x16, #32 + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + str x15, [x17] + str x16, [x17, #8] + gret + +// SHLL2 S->D: upper 2 words << 32 +.gadget shll2_vec_s_to_d + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + ldr x14, [x12, #8] + uxtw x15, w14 + lsl x15, x15, #32 + lsr x16, x14, #32 + lsl x16, x16, #32 + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + str x15, [x17] + str x16, [x17, #8] + gret + +/* + * XTN/XTN2 - Narrow vector elements + * Code stream: [gadget addr][rd | rn<<8 | size<<16 | hi<<18] + * + * size: 0=B (8-bit), 1=H (16-bit), 2=S (32-bit) + * hi: 0=XTN (write low half, clear high), 1=XTN2 (write high half) + */ +.gadget xtn_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #2 // size + ubfx x12, x8, #18, #1 // hi (xtn2) + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + // Load source vector into v1 + ldr q1, [x15] + + // For XTN2, preserve low half of destination in v0 + cbz x12, .Lxtn_no_preserve + ldr q0, [x14] +.Lxtn_no_preserve: + + cmp x11, #0 + b.eq .Lxtn_size_b + cmp x11, #1 + b.eq .Lxtn_size_h + // size == 2 + b .Lxtn_size_s + +.Lxtn_size_b: + cbz x12, .Lxtn_b_low + xtn2 v0.16b, v1.8h + b .Lxtn_store_q +.Lxtn_b_low: + xtn v0.8b, v1.8h + b .Lxtn_store_low + +.Lxtn_size_h: + cbz x12, .Lxtn_h_low + xtn2 v0.8h, v1.4s + b .Lxtn_store_q +.Lxtn_h_low: + xtn v0.4h, v1.4s + b .Lxtn_store_low + +.Lxtn_size_s: + cbz x12, .Lxtn_s_low + xtn2 v0.4s, v1.2d + b .Lxtn_store_q +.Lxtn_s_low: + xtn v0.2s, v1.2d + b .Lxtn_store_low + +.Lxtn_store_q: + str q0, [x14] + gret + +.Lxtn_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * UZP1 - Unzip even elements + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * + * size: 0=B, 1=H, 2=S, 3=D + * Q: 0=64-bit vector, 1=128-bit vector + */ +.gadget uzp1_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + // Load vectors into v0 (Vn) and v1 (Vm) + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .Luzp1_size_b + cmp x12, #1 + b.eq .Luzp1_size_h + cmp x12, #2 + b.eq .Luzp1_size_s + // size == 3 (D) + b .Luzp1_size_d + +.Luzp1_size_b: + cbz x17, .Luzp1_b_q0 + uzp1 v0.16b, v0.16b, v1.16b + b .Luzp1_store_q +.Luzp1_b_q0: + uzp1 v0.8b, v0.8b, v1.8b + b .Luzp1_store_low + +.Luzp1_size_h: + cbz x17, .Luzp1_h_q0 + uzp1 v0.8h, v0.8h, v1.8h + b .Luzp1_store_q +.Luzp1_h_q0: + uzp1 v0.4h, v0.4h, v1.4h + b .Luzp1_store_low + +.Luzp1_size_s: + cbz x17, .Luzp1_s_q0 + uzp1 v0.4s, v0.4s, v1.4s + b .Luzp1_store_q +.Luzp1_s_q0: + uzp1 v0.2s, v0.2s, v1.2s + b .Luzp1_store_low + +.Luzp1_size_d: + cbz x17, .Luzp1_invalid + uzp1 v0.2d, v0.2d, v1.2d + b .Luzp1_store_q + +.Luzp1_invalid: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.Luzp1_store_q: + str q0, [x14] + gret + +.Luzp1_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * UZP2 - Unzip odd elements + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + */ +.gadget uzp2_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .Luzp2_size_b + cmp x12, #1 + b.eq .Luzp2_size_h + cmp x12, #2 + b.eq .Luzp2_size_s + b .Luzp2_size_d + +.Luzp2_size_b: + cbz x17, .Luzp2_b_q0 + uzp2 v0.16b, v0.16b, v1.16b + b .Luzp2_store_q +.Luzp2_b_q0: + uzp2 v0.8b, v0.8b, v1.8b + b .Luzp2_store_low + +.Luzp2_size_h: + cbz x17, .Luzp2_h_q0 + uzp2 v0.8h, v0.8h, v1.8h + b .Luzp2_store_q +.Luzp2_h_q0: + uzp2 v0.4h, v0.4h, v1.4h + b .Luzp2_store_low + +.Luzp2_size_s: + cbz x17, .Luzp2_s_q0 + uzp2 v0.4s, v0.4s, v1.4s + b .Luzp2_store_q +.Luzp2_s_q0: + uzp2 v0.2s, v0.2s, v1.2s + b .Luzp2_store_low + +.Luzp2_size_d: + cbz x17, .Luzp2_invalid + uzp2 v0.2d, v0.2d, v1.2d + b .Luzp2_store_q + +.Luzp2_invalid: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.Luzp2_store_q: + str q0, [x14] + gret + +.Luzp2_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * TRN1 - Transpose even pairs + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + */ +.gadget trn1_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .Ltrn1_size_b + cmp x12, #1 + b.eq .Ltrn1_size_h + cmp x12, #2 + b.eq .Ltrn1_size_s + b .Ltrn1_size_d + +.Ltrn1_size_b: + cbz x17, .Ltrn1_b_q0 + trn1 v0.16b, v0.16b, v1.16b + b .Ltrn1_store_q +.Ltrn1_b_q0: + trn1 v0.8b, v0.8b, v1.8b + b .Ltrn1_store_low + +.Ltrn1_size_h: + cbz x17, .Ltrn1_h_q0 + trn1 v0.8h, v0.8h, v1.8h + b .Ltrn1_store_q +.Ltrn1_h_q0: + trn1 v0.4h, v0.4h, v1.4h + b .Ltrn1_store_low + +.Ltrn1_size_s: + cbz x17, .Ltrn1_s_q0 + trn1 v0.4s, v0.4s, v1.4s + b .Ltrn1_store_q +.Ltrn1_s_q0: + trn1 v0.2s, v0.2s, v1.2s + b .Ltrn1_store_low + +.Ltrn1_size_d: + cbz x17, .Ltrn1_invalid + trn1 v0.2d, v0.2d, v1.2d + b .Ltrn1_store_q + +.Ltrn1_invalid: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.Ltrn1_store_q: + str q0, [x14] + gret + +.Ltrn1_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * TRN2 - Transpose odd pairs + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + */ +.gadget trn2_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .Ltrn2_size_b + cmp x12, #1 + b.eq .Ltrn2_size_h + cmp x12, #2 + b.eq .Ltrn2_size_s + b .Ltrn2_size_d + +.Ltrn2_size_b: + cbz x17, .Ltrn2_b_q0 + trn2 v0.16b, v0.16b, v1.16b + b .Ltrn2_store_q +.Ltrn2_b_q0: + trn2 v0.8b, v0.8b, v1.8b + b .Ltrn2_store_low + +.Ltrn2_size_h: + cbz x17, .Ltrn2_h_q0 + trn2 v0.8h, v0.8h, v1.8h + b .Ltrn2_store_q +.Ltrn2_h_q0: + trn2 v0.4h, v0.4h, v1.4h + b .Ltrn2_store_low + +.Ltrn2_size_s: + cbz x17, .Ltrn2_s_q0 + trn2 v0.4s, v0.4s, v1.4s + b .Ltrn2_store_q +.Ltrn2_s_q0: + trn2 v0.2s, v0.2s, v1.2s + b .Ltrn2_store_low + +.Ltrn2_size_d: + cbz x17, .Ltrn2_invalid + trn2 v0.2d, v0.2d, v1.2d + b .Ltrn2_store_q + +.Ltrn2_invalid: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.Ltrn2_store_q: + str q0, [x14] + gret + +.Ltrn2_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * ZIP1 - Interleave lower halves + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + */ +.gadget zip1_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .Lzip1_size_b + cmp x12, #1 + b.eq .Lzip1_size_h + cmp x12, #2 + b.eq .Lzip1_size_s + b .Lzip1_size_d + +.Lzip1_size_b: + cbz x17, .Lzip1_b_q0 + zip1 v0.16b, v0.16b, v1.16b + b .Lzip1_store_q +.Lzip1_b_q0: + zip1 v0.8b, v0.8b, v1.8b + b .Lzip1_store_low + +.Lzip1_size_h: + cbz x17, .Lzip1_h_q0 + zip1 v0.8h, v0.8h, v1.8h + b .Lzip1_store_q +.Lzip1_h_q0: + zip1 v0.4h, v0.4h, v1.4h + b .Lzip1_store_low + +.Lzip1_size_s: + cbz x17, .Lzip1_s_q0 + zip1 v0.4s, v0.4s, v1.4s + b .Lzip1_store_q +.Lzip1_s_q0: + zip1 v0.2s, v0.2s, v1.2s + b .Lzip1_store_low + +.Lzip1_size_d: + cbz x17, .Lzip1_invalid + zip1 v0.2d, v0.2d, v1.2d + b .Lzip1_store_q + +.Lzip1_invalid: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.Lzip1_store_q: + str q0, [x14] + gret + +.Lzip1_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * ZIP2 - Interleave upper halves + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + */ +.gadget zip2_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .Lzip2_size_b + cmp x12, #1 + b.eq .Lzip2_size_h + cmp x12, #2 + b.eq .Lzip2_size_s + b .Lzip2_size_d + +.Lzip2_size_b: + cbz x17, .Lzip2_b_q0 + zip2 v0.16b, v0.16b, v1.16b + b .Lzip2_store_q +.Lzip2_b_q0: + zip2 v0.8b, v0.8b, v1.8b + b .Lzip2_store_low + +.Lzip2_size_h: + cbz x17, .Lzip2_h_q0 + zip2 v0.8h, v0.8h, v1.8h + b .Lzip2_store_q +.Lzip2_h_q0: + zip2 v0.4h, v0.4h, v1.4h + b .Lzip2_store_low + +.Lzip2_size_s: + cbz x17, .Lzip2_s_q0 + zip2 v0.4s, v0.4s, v1.4s + b .Lzip2_store_q +.Lzip2_s_q0: + zip2 v0.2s, v0.2s, v1.2s + b .Lzip2_store_low + +.Lzip2_size_d: + cbz x17, .Lzip2_invalid + zip2 v0.2d, v0.2d, v1.2d + b .Lzip2_store_q + +.Lzip2_invalid: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.Lzip2_store_q: + str q0, [x14] + gret + +.Lzip2_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * REV16 - Reverse bytes in 16-bit elements (vector) + * Code stream: [gadget addr][rd | rn<<8 | Q<<16] + * Q: 0=64-bit vector (.8B), 1=128-bit vector (.16B) + */ +.gadget rev16_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #1 // Q + + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x13, x12, x13 // &Vn + lsl x14, x9, #4 + add x14, x12, x14 // &Vd + + ldr q0, [x13] + cbz x11, .Lrev16_vec_8b + rev16 v0.16b, v0.16b + str q0, [x14] + gret +.Lrev16_vec_8b: + rev16 v0.8b, v0.8b + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * REV32 - Reverse bytes in 32-bit elements (vector) + * Code stream: [gadget addr][rd | rn<<8 | size<<16 | Q<<24] + * + * size: 0=B (reverse bytes), 1=H (reverse halfwords) + * Q: 0=64-bit vector, 1=128-bit vector + */ +.gadget rev32_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #2 // size + ubfx x12, x8, #24, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + // Load source vector + ldr q0, [x15] + + // size=0: REV32 (reverse bytes within each 32-bit element) + // size=1: REV32 (reverse halfwords within each 32-bit element) + cmp x11, #0 + b.eq .Lrev32_size_b + // size == 1 + b .Lrev32_size_h + +.Lrev32_size_b: + cbz x12, .Lrev32_b_low + rev32 v0.16b, v0.16b + b .Lrev32_store_q +.Lrev32_b_low: + rev32 v0.8b, v0.8b + b .Lrev32_store_low + +.Lrev32_size_h: + cbz x12, .Lrev32_h_low + rev32 v0.8h, v0.8h + b .Lrev32_store_q +.Lrev32_h_low: + rev32 v0.4h, v0.4h + b .Lrev32_store_low + +.Lrev32_store_q: + str q0, [x14] + gret + +.Lrev32_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * REV64 - Reverse bytes in 64-bit elements (vector) + * Code stream: [gadget addr][rd | rn<<8 | size<<16 | Q<<24] + * + * size: 0=B (reverse bytes), 1=H (reverse halfwords), 2=S (reverse words) + * Q: 0=64-bit vector, 1=128-bit vector + */ +.gadget rev64_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #2 // size + ubfx x12, x8, #24, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + // Load source vector + ldr q0, [x15] + + cmp x11, #0 + b.eq .Lrev64_size_b + cmp x11, #1 + b.eq .Lrev64_size_h + // size == 2 + b .Lrev64_size_s + +.Lrev64_size_b: + cbz x12, .Lrev64_b_low + rev64 v0.16b, v0.16b + b .Lrev64_store_q +.Lrev64_b_low: + rev64 v0.8b, v0.8b + b .Lrev64_store_low + +.Lrev64_size_h: + cbz x12, .Lrev64_h_low + rev64 v0.8h, v0.8h + b .Lrev64_store_q +.Lrev64_h_low: + rev64 v0.4h, v0.4h + b .Lrev64_store_low + +.Lrev64_size_s: + cbz x12, .Lrev64_s_low + rev64 v0.4s, v0.4s + b .Lrev64_store_q +.Lrev64_s_low: + rev64 v0.2s, v0.2s + b .Lrev64_store_low + +.Lrev64_store_q: + str q0, [x14] + gret + +.Lrev64_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * RBIT (vector) - reverse bits in each byte + * Code stream: [gadget addr][rd | rn<<8 | Q<<16] + * + * Q: 0=8-byte (.8B), 1=16-byte (.16B) + */ +.gadget rbit_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x17, x8, #16, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + // Load source vector + ldr q0, [x15] + + // Use native RBIT instruction + cbz x17, .Lrbit_vec_8b + rbit v0.16b, v0.16b + str q0, [x14] + gret + +.Lrbit_vec_8b: + rbit v0.8b, v0.8b + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * Vector FP two-register misc conversion instructions + * Code stream: [gadget addr][rd | rn<<8 | sz<<16 | Q<<24] + * sz: 0=single, 1=double + * Q: 0=lower half, 1=full + * + * Macro: generates gadgets for FP conversions (pass-through to native NEON) + */ +.macro make_fp_vec_two_reg_misc name, insn +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #1 // sz (0=single, 1=double) + ubfx x17, x8, #24, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + ldr q0, [x15] + + cbnz x11, .L\name\()_double + // Single-precision + cbz x17, .L\name\()_2s + \insn v0.4s, v0.4s + str q0, [x14] + gret +.L\name\()_2s: + \insn v0.2s, v0.2s + str d0, [x14] + str xzr, [x14, #8] + gret +.L\name\()_double: + // Double-precision (always Q=1 for .2d) + \insn v0.2d, v0.2d + str q0, [x14] + gret +.endm + +make_fp_vec_two_reg_misc scvtf_int, scvtf +make_fp_vec_two_reg_misc ucvtf_int, ucvtf +make_fp_vec_two_reg_misc fcvtzs_int, fcvtzs +make_fp_vec_two_reg_misc fcvtzu_int, fcvtzu +make_fp_vec_two_reg_misc fcvtns_int, fcvtns +make_fp_vec_two_reg_misc fcvtnu_int, fcvtnu +make_fp_vec_two_reg_misc fcvtms_int, fcvtms +make_fp_vec_two_reg_misc fcvtmu_int, fcvtmu +make_fp_vec_two_reg_misc fcvtps_int, fcvtps +make_fp_vec_two_reg_misc fcvtpu_int, fcvtpu +make_fp_vec_two_reg_misc fcvtas_int, fcvtas +make_fp_vec_two_reg_misc fcvtau_int, fcvtau +make_fp_vec_two_reg_misc frintn_vec, frintn +make_fp_vec_two_reg_misc frinta_vec, frinta +make_fp_vec_two_reg_misc frintp_vec, frintp +make_fp_vec_two_reg_misc frintm_vec, frintm +make_fp_vec_two_reg_misc frintx_vec, frintx +make_fp_vec_two_reg_misc frintz_vec, frintz +make_fp_vec_two_reg_misc frinti_vec, frinti + +/* + * Run a native FP instruction under the guest FPCR/FPSR, then restore the + * host thread's state. The conversion gadgets below can round, quiet NaNs and + * raise cumulative exceptions, so using the process FP state is incorrect. + */ +.macro fp_guest_enter host_fpcr, host_fpsr, scratch_x, scratch_w + mrs \host_fpcr, fpcr + mrs \host_fpsr, fpsr + ldr \scratch_w, [_cpu, #CPU_fpcr] + msr fpcr, \scratch_x + ldr \scratch_w, [_cpu, #CPU_fpsr] + msr fpsr, \scratch_x +.endm + +.macro fp_guest_leave host_fpcr, host_fpsr, scratch_x, scratch_w + mrs \scratch_x, fpsr + str \scratch_w, [_cpu, #CPU_fpsr] + msr fpcr, \host_fpcr + msr fpsr, \host_fpsr +.endm + +/* + * FCVTN/FCVTN2 - floating-point narrowing conversion. + * Code stream: [gadget addr][rd | rn<<8 | size<<16 | Q<<24] + * size: 0 = single->half, 1 = double->single + * Q: 0 = FCVTN (write lower half, zero upper), 1 = FCVTN2 (preserve lower) + */ +.gadget fcvtn_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #1 // size + ubfx x17, x8, #24, #1 // Q / upper destination half + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + // Load the source before Vd so rn==rd works for both lower and upper forms. + ldr q0, [x15] + fp_guest_enter x12, x16, x8, w8 + cbnz x11, .Lfcvtn_d_to_s + + // Single -> half. + cbnz x17, .Lfcvtn2_s_to_h + fcvtn v0.4h, v0.4s + fp_guest_leave x12, x16, x8, w8 + str d0, [x14] + str xzr, [x14, #8] + gret +.Lfcvtn2_s_to_h: + ldr q1, [x14] + fcvtn2 v1.8h, v0.4s + fp_guest_leave x12, x16, x8, w8 + str q1, [x14] + gret + +.Lfcvtn_d_to_s: + cbnz x17, .Lfcvtn2_d_to_s + fcvtn v0.2s, v0.2d + fp_guest_leave x12, x16, x8, w8 + str d0, [x14] + str xzr, [x14, #8] + gret +.Lfcvtn2_d_to_s: + ldr q1, [x14] + fcvtn2 v1.4s, v0.2d + fp_guest_leave x12, x16, x8, w8 + str q1, [x14] + gret + +/* + * FCVTL/FCVTL2 - floating-point widening conversion. + * Code stream: [gadget addr][rd | rn<<8 | size<<16 | Q<<24] + * size: 0 = half->single, 1 = single->double + * Q: 0 = FCVTL (lower half), 1 = FCVTL2 (upper half) + */ +.gadget fcvtl_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #1 // size + ubfx x17, x8, #24, #1 // Q / upper half + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + ldr q0, [x15] + fp_guest_enter x12, x16, x8, w8 + + cbnz x11, .Lfcvtl_s_to_d + cbnz x17, .Lfcvtl2_h_to_s + fcvtl v0.4s, v0.4h + fp_guest_leave x12, x16, x8, w8 + str q0, [x14] + gret +.Lfcvtl2_h_to_s: + fcvtl2 v0.4s, v0.8h + fp_guest_leave x12, x16, x8, w8 + str q0, [x14] + gret +.Lfcvtl_s_to_d: + cbnz x17, .Lfcvtl2_s_to_d + fcvtl v0.2d, v0.2s + fp_guest_leave x12, x16, x8, w8 + str q0, [x14] + gret +.Lfcvtl2_s_to_d: + fcvtl2 v0.2d, v0.4s + fp_guest_leave x12, x16, x8, w8 + str q0, [x14] + gret + +/* + * FCVTXN/FCVTXN2 - double-to-single round-to-odd narrowing conversion. + * Code stream: [gadget addr][rd | rn<<8 | Q<<24] + * Q: 0 = FCVTXN (write lower half, zero upper), 1 = FCVTXN2 (preserve lower) + */ +.gadget fcvtxn_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x17, x8, #24, #1 // Q / upper destination half + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + ldr q0, [x15] // source first for rn==rd + fp_guest_enter x12, x16, x8, w8 + cbnz x17, .Lfcvtxn2_d_to_s + fcvtxn v0.2s, v0.2d + fp_guest_leave x12, x16, x8, w8 + str d0, [x14] + str xzr, [x14, #8] + gret +.Lfcvtxn2_d_to_s: + ldr q1, [x14] + fcvtxn2 v1.4s, v0.2d + fp_guest_leave x12, x16, x8, w8 + str q1, [x14] + gret + +/* + * Vector FP compare-with-zero instructions + * Code stream: [gadget addr][rd | rn<<8 | sz<<16 | Q<<24] + */ +.macro make_fp_vec_cmp_zero name, insn +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #1 // sz (0=single, 1=double) + ubfx x17, x8, #24, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + ldr q0, [x15] + + cbnz x11, .L\name\()_double + cbz x17, .L\name\()_2s + \insn v0.4s, v0.4s, #0.0 + str q0, [x14] + gret +.L\name\()_2s: + \insn v0.2s, v0.2s, #0.0 + str d0, [x14] + str xzr, [x14, #8] + gret +.L\name\()_double: + \insn v0.2d, v0.2d, #0.0 + str q0, [x14] + gret +.endm + +make_fp_vec_cmp_zero fcmeq_zero, fcmeq +make_fp_vec_cmp_zero fcmge_zero, fcmge +make_fp_vec_cmp_zero fcmgt_zero, fcmgt +make_fp_vec_cmp_zero fcmle_zero, fcmle +make_fp_vec_cmp_zero fcmlt_zero, fcmlt + +/* + * Vector FP absolute value / negate + * Code stream: [gadget addr][rd | rn<<8 | sz<<16 | Q<<24] + */ +.macro make_fp_vec_unary name, insn +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #1 // sz (0=single, 1=double) + ubfx x17, x8, #24, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + ldr q0, [x15] + + cbnz x11, .L\name\()_double + cbz x17, .L\name\()_2s + \insn v0.4s, v0.4s + str q0, [x14] + gret +.L\name\()_2s: + \insn v0.2s, v0.2s + str d0, [x14] + str xzr, [x14, #8] + gret +.L\name\()_double: + \insn v0.2d, v0.2d + str q0, [x14] + gret +.endm + +make_fp_vec_unary fabs_vec, fabs +make_fp_vec_unary fneg_vec, fneg +make_fp_vec_unary fsqrt_vec, fsqrt +make_fp_vec_unary frecpe_vec, frecpe +make_fp_vec_unary frsqrte_vec, frsqrte + +/* + * Integer vector compare-with-zero instructions + * Code stream: [gadget addr][rd | rn<<8 | size<<16 | Q<<24] + */ +.macro make_int_vec_cmp_zero name, insn +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #2 // size + ubfx x17, x8, #24, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + ldr q0, [x15] + + cmp x11, #0 + b.eq .L\name\()_b + cmp x11, #1 + b.eq .L\name\()_h + cmp x11, #2 + b.eq .L\name\()_s + // size == 3 (.2d, always Q=1) + \insn v0.2d, v0.2d, #0 + str q0, [x14] + gret +.L\name\()_b: + cbz x17, .L\name\()_8b + \insn v0.16b, v0.16b, #0 + str q0, [x14] + gret +.L\name\()_8b: + \insn v0.8b, v0.8b, #0 + str d0, [x14] + str xzr, [x14, #8] + gret +.L\name\()_h: + cbz x17, .L\name\()_4h + \insn v0.8h, v0.8h, #0 + str q0, [x14] + gret +.L\name\()_4h: + \insn v0.4h, v0.4h, #0 + str d0, [x14] + str xzr, [x14, #8] + gret +.L\name\()_s: + cbz x17, .L\name\()_2s + \insn v0.4s, v0.4s, #0 + str q0, [x14] + gret +.L\name\()_2s: + \insn v0.2s, v0.2s, #0 + str d0, [x14] + str xzr, [x14, #8] + gret +.endm + +make_int_vec_cmp_zero cmgt_zero, cmgt +make_int_vec_cmp_zero cmge_zero, cmge +make_int_vec_cmp_zero cmlt_zero, cmlt +make_int_vec_cmp_zero cmle_zero, cmle +make_int_vec_cmp_zero cmeq_zero, cmeq + +// CLZ/CLS/ABS/NEG/NOT/RBIT vector gadgets use make_twomis_native macro (defined later in this file) + +/* + * CNT - Vector population count (count set bits per byte) + * Code stream: [gadget addr][rd | rn<<8 | Q<<16] + * Only valid for .8B (Q=0) and .16B (Q=1) + */ +.gadget cnt_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x17, x8, #16, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + // Load source vector + ldr q0, [x15] + + // Use native CNT instruction + cbz x17, .Lcnt_vec_8b + cnt v0.16b, v0.16b + str q0, [x14] + gret + +.Lcnt_vec_8b: + cnt v0.8b, v0.8b + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * ADDV - Add across vector (sum all elements into scalar) + * Code stream: [gadget addr][rd | rn<<8 | size<<16 | Q<<24] + * size: 0=B, 1=H, 2=S (no 3=D for ADDV) + * Q: 0=64-bit vector, 1=128-bit vector + * Result is scalar: Vd.element = sum of all Vn elements + */ +.gadget addv_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #16, #2 // size + ubfx x17, x8, #24, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + // Load source vector + ldr q0, [x15] + + // Use native ADDV instruction, dispatch by size and Q + cmp x12, #2 + b.eq .Laddv_32 + cmp x12, #1 + b.eq .Laddv_16 + // size=0 (bytes) + cbz x17, .Laddv_8b + addv b1, v0.16b + b .Laddv_store_b +.Laddv_8b: + addv b1, v0.8b +.Laddv_store_b: + stp xzr, xzr, [x14] // zero destination + st1 {v1.b}[0], [x14] // store scalar byte result + gret + +.Laddv_16: + cbz x17, .Laddv_4h + addv h1, v0.8h + b .Laddv_store_h +.Laddv_4h: + addv h1, v0.4h +.Laddv_store_h: + stp xzr, xzr, [x14] + st1 {v1.h}[0], [x14] + gret + +.Laddv_32: + cbz x17, .Laddv_2s + addv s1, v0.4s + b .Laddv_store_s +.Laddv_2s: + // ADDV doesn't exist for 2S, use ADDP instead + addp v1.2s, v0.2s, v0.2s +.Laddv_store_s: + stp xzr, xzr, [x14] + str s1, [x14] + gret + +/* + * SADDLV/UADDLV - Signed/Unsigned Add Long Across Vector + * Code stream: [gadget addr][rd | rn<<8 | size<<16 | Q<<24] + * size: 0=B→H, 1=H→S, 2=S→D (result is one size wider) + * Q: 0=64-bit vector, 1=128-bit vector + */ +.macro make_across_addlv name, insn_b_16, insn_b_8, insn_h_8, insn_h_4, insn_s_4 +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #16, #2 // size + ubfx x17, x8, #24, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + ldr q0, [x15] + + cmp x12, #2 + b.eq .L\name\()_32 + cmp x12, #1 + b.eq .L\name\()_16 + // size=0 (bytes → halfword result) + cbz x17, .L\name\()_8b + \insn_b_16 + b .L\name\()_store_h +.L\name\()_8b: + \insn_b_8 +.L\name\()_store_h: + stp xzr, xzr, [x14] + st1 {v1.h}[0], [x14] + gret + +.L\name\()_16: + // size=1 (halfwords → word result) + cbz x17, .L\name\()_4h + \insn_h_8 + b .L\name\()_store_s +.L\name\()_4h: + \insn_h_4 +.L\name\()_store_s: + stp xzr, xzr, [x14] + str s1, [x14] + gret + +.L\name\()_32: + // size=2 (words → doubleword result) + // SADDLV/UADDLV for 4S only (Q=1); 2S not encodable + \insn_s_4 + stp xzr, xzr, [x14] + str d1, [x14] + gret +.endm + +make_across_addlv saddlv, "saddlv h1, v0.16b", "saddlv h1, v0.8b", "saddlv s1, v0.8h", "saddlv s1, v0.4h", "saddlv d1, v0.4s" +make_across_addlv uaddlv, "uaddlv h1, v0.16b", "uaddlv h1, v0.8b", "uaddlv s1, v0.8h", "uaddlv s1, v0.4h", "uaddlv d1, v0.4s" + +/* + * UMAXV/UMINV/SMAXV/SMINV - Min/Max across vector lanes + * Code stream: [gadget addr][rd | rn<<8 | size<<16 | Q<<24] + * size: 0=B, 1=H, 2=S (no 3=D) + * Q: 0=64-bit vector, 1=128-bit vector + * Result is scalar: Vd.element = min/max of all Vn elements + */ +.macro make_across_minmax name, insn_b_16, insn_b_8, insn_h_8, insn_h_4, insn_s_4, insn_s_2 +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #16, #2 // size + ubfx x17, x8, #24, #1 // Q + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + ldr q0, [x15] + cmp x12, #2 + b.eq .L\name\()_32 + cmp x12, #1 + b.eq .L\name\()_16 + // size=0 (bytes) + cbz x17, .L\name\()_8b + \insn_b_16 + b .L\name\()_store_b +.L\name\()_8b: + \insn_b_8 +.L\name\()_store_b: + stp xzr, xzr, [x14] + st1 {v1.b}[0], [x14] + gret +.L\name\()_16: + cbz x17, .L\name\()_4h + \insn_h_8 + b .L\name\()_store_h +.L\name\()_4h: + \insn_h_4 +.L\name\()_store_h: + stp xzr, xzr, [x14] + st1 {v1.h}[0], [x14] + gret +.L\name\()_32: + cbz x17, .L\name\()_2s + \insn_s_4 + b .L\name\()_store_s +.L\name\()_2s: + \insn_s_2 +.L\name\()_store_s: + stp xzr, xzr, [x14] + str s1, [x14] + gret +.endm + +make_across_minmax umaxv, "umaxv b1, v0.16b", "umaxv b1, v0.8b", "umaxv h1, v0.8h", "umaxv h1, v0.4h", "umaxv s1, v0.4s", "umaxp v1.2s, v0.2s, v0.2s" +make_across_minmax uminv, "uminv b1, v0.16b", "uminv b1, v0.8b", "uminv h1, v0.8h", "uminv h1, v0.4h", "uminv s1, v0.4s", "uminp v1.2s, v0.2s, v0.2s" +make_across_minmax smaxv, "smaxv b1, v0.16b", "smaxv b1, v0.8b", "smaxv h1, v0.8h", "smaxv h1, v0.4h", "smaxv s1, v0.4s", "smaxp v1.2s, v0.2s, v0.2s" +make_across_minmax sminv, "sminv b1, v0.16b", "sminv b1, v0.8b", "sminv h1, v0.8h", "sminv h1, v0.4h", "sminv s1, v0.4s", "sminp v1.2s, v0.2s, v0.2s" + +/* + * FMAXV/FMINV/FMAXNMV/FMINNMV - FP max/min across vector lanes + * Only valid for .4s (Q=1, single precision) + * Code stream: [gadget addr][rd | rn<<8] + */ +.macro make_fp_across name, op +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + ldr q0, [x15] + \op s1, v0.4s + stp xzr, xzr, [x14] + str s1, [x14] + gret +.endm + +make_fp_across fmaxv, fmaxv +make_fp_across fminv, fminv +make_fp_across fmaxnmv, fmaxnmv +make_fp_across fminnmv, fminnmv + +/* + * ADD - Vector add + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * + * size: 0=B, 1=H, 2=S, 3=D + * Q: 0=64-bit vector, 1=128-bit vector + */ +.gadget add_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + // Load vectors into v0 (Vn) and v1 (Vm) + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .Ladd_size_b + cmp x12, #1 + b.eq .Ladd_size_h + cmp x12, #2 + b.eq .Ladd_size_s + // size == 3 (D) + b .Ladd_size_d + +.Ladd_size_b: + cbz x17, .Ladd_b_q0 + add v0.16b, v0.16b, v1.16b + b .Ladd_store_q +.Ladd_b_q0: + add v0.8b, v0.8b, v1.8b + b .Ladd_store_low + +.Ladd_size_h: + cbz x17, .Ladd_h_q0 + add v0.8h, v0.8h, v1.8h + b .Ladd_store_q +.Ladd_h_q0: + add v0.4h, v0.4h, v1.4h + b .Ladd_store_low + +.Ladd_size_s: + cbz x17, .Ladd_s_q0 + add v0.4s, v0.4s, v1.4s + b .Ladd_store_q +.Ladd_s_q0: + add v0.2s, v0.2s, v1.2s + b .Ladd_store_low + +.Ladd_size_d: + cbz x17, .Ladd_invalid + add v0.2d, v0.2d, v1.2d + b .Ladd_store_q + +.Ladd_invalid: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.Ladd_store_q: + str q0, [x14] + gret + +.Ladd_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * SUB - Vector subtract + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + */ +.gadget sub_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .Lsub_size_b + cmp x12, #1 + b.eq .Lsub_size_h + cmp x12, #2 + b.eq .Lsub_size_s + b .Lsub_size_d + +.Lsub_size_b: + cbz x17, .Lsub_b_q0 + sub v0.16b, v0.16b, v1.16b + b .Lsub_store_q +.Lsub_b_q0: + sub v0.8b, v0.8b, v1.8b + b .Lsub_store_low + +.Lsub_size_h: + cbz x17, .Lsub_h_q0 + sub v0.8h, v0.8h, v1.8h + b .Lsub_store_q +.Lsub_h_q0: + sub v0.4h, v0.4h, v1.4h + b .Lsub_store_low + +.Lsub_size_s: + cbz x17, .Lsub_s_q0 + sub v0.4s, v0.4s, v1.4s + b .Lsub_store_q +.Lsub_s_q0: + sub v0.2s, v0.2s, v1.2s + b .Lsub_store_low + +.Lsub_size_d: + cbz x17, .Lsub_invalid + sub v0.2d, v0.2d, v1.2d + b .Lsub_store_q + +.Lsub_invalid: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.Lsub_store_q: + str q0, [x14] + gret + +.Lsub_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * SHADD - Signed halving add + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * + * result = (Vn + Vm) >> 1 (signed, no overflow) + */ +.gadget shadd_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .Lshadd_size_b + cmp x12, #1 + b.eq .Lshadd_size_h + cmp x12, #2 + b.eq .Lshadd_size_s + b .Lshadd_invalid + +.Lshadd_size_b: + cbz x17, .Lshadd_b_q0 + shadd v0.16b, v0.16b, v1.16b + b .Lshadd_store_q +.Lshadd_b_q0: + shadd v0.8b, v0.8b, v1.8b + b .Lshadd_store_low + +.Lshadd_size_h: + cbz x17, .Lshadd_h_q0 + shadd v0.8h, v0.8h, v1.8h + b .Lshadd_store_q +.Lshadd_h_q0: + shadd v0.4h, v0.4h, v1.4h + b .Lshadd_store_low + +.Lshadd_size_s: + cbz x17, .Lshadd_s_q0 + shadd v0.4s, v0.4s, v1.4s + b .Lshadd_store_q +.Lshadd_s_q0: + shadd v0.2s, v0.2s, v1.2s + b .Lshadd_store_low + +.Lshadd_invalid: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.Lshadd_store_q: + str q0, [x14] + gret + +.Lshadd_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * UHADD - Unsigned halving add + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + */ +.gadget uhadd_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .Luhadd_size_b + cmp x12, #1 + b.eq .Luhadd_size_h + cmp x12, #2 + b.eq .Luhadd_size_s + b .Luhadd_invalid + +.Luhadd_size_b: + cbz x17, .Luhadd_b_q0 + uhadd v0.16b, v0.16b, v1.16b + b .Luhadd_store_q +.Luhadd_b_q0: + uhadd v0.8b, v0.8b, v1.8b + b .Luhadd_store_low + +.Luhadd_size_h: + cbz x17, .Luhadd_h_q0 + uhadd v0.8h, v0.8h, v1.8h + b .Luhadd_store_q +.Luhadd_h_q0: + uhadd v0.4h, v0.4h, v1.4h + b .Luhadd_store_low + +.Luhadd_size_s: + cbz x17, .Luhadd_s_q0 + uhadd v0.4s, v0.4s, v1.4s + b .Luhadd_store_q +.Luhadd_s_q0: + uhadd v0.2s, v0.2s, v1.2s + b .Luhadd_store_low + +.Luhadd_invalid: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.Luhadd_store_q: + str q0, [x14] + gret + +.Luhadd_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * SRHADD - Signed rounding halving add + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + */ +.gadget srhadd_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .Lsrhadd_size_b + cmp x12, #1 + b.eq .Lsrhadd_size_h + cmp x12, #2 + b.eq .Lsrhadd_size_s + b .Lsrhadd_invalid + +.Lsrhadd_size_b: + cbz x17, .Lsrhadd_b_q0 + srhadd v0.16b, v0.16b, v1.16b + b .Lsrhadd_store_q +.Lsrhadd_b_q0: + srhadd v0.8b, v0.8b, v1.8b + b .Lsrhadd_store_low + +.Lsrhadd_size_h: + cbz x17, .Lsrhadd_h_q0 + srhadd v0.8h, v0.8h, v1.8h + b .Lsrhadd_store_q +.Lsrhadd_h_q0: + srhadd v0.4h, v0.4h, v1.4h + b .Lsrhadd_store_low + +.Lsrhadd_size_s: + cbz x17, .Lsrhadd_s_q0 + srhadd v0.4s, v0.4s, v1.4s + b .Lsrhadd_store_q +.Lsrhadd_s_q0: + srhadd v0.2s, v0.2s, v1.2s + b .Lsrhadd_store_low + +.Lsrhadd_invalid: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.Lsrhadd_store_q: + str q0, [x14] + gret + +.Lsrhadd_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * URHADD - Unsigned rounding halving add + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + */ +.gadget urhadd_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .Lurhadd_size_b + cmp x12, #1 + b.eq .Lurhadd_size_h + cmp x12, #2 + b.eq .Lurhadd_size_s + b .Lurhadd_invalid + +.Lurhadd_size_b: + cbz x17, .Lurhadd_b_q0 + urhadd v0.16b, v0.16b, v1.16b + b .Lurhadd_store_q +.Lurhadd_b_q0: + urhadd v0.8b, v0.8b, v1.8b + b .Lurhadd_store_low + +.Lurhadd_size_h: + cbz x17, .Lurhadd_h_q0 + urhadd v0.8h, v0.8h, v1.8h + b .Lurhadd_store_q +.Lurhadd_h_q0: + urhadd v0.4h, v0.4h, v1.4h + b .Lurhadd_store_low + +.Lurhadd_size_s: + cbz x17, .Lurhadd_s_q0 + urhadd v0.4s, v0.4s, v1.4s + b .Lurhadd_store_q +.Lurhadd_s_q0: + urhadd v0.2s, v0.2s, v1.2s + b .Lurhadd_store_low + +.Lurhadd_invalid: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.Lurhadd_store_q: + str q0, [x14] + gret + +.Lurhadd_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * STR Qn, [addr] - Store 128-bit vector (address in _addr) + * Code stream: [gadget addr][rt] + * + * Note: Address must already be computed in _addr by calc_addr_imm + */ +.gadget str_q + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rt (vector register index) + + // Load vector value + add x10, _cpu, #CPU_fp + lsl x11, x9, #4 // each V reg is 16 bytes + add x10, x10, x11 // x10 = base of vector register + ldr x12, [x10] // low 64 bits + ldr x13, [x10, #8] // high 64 bits + + // Translate address for write. Preserve the guest address in _addr so + // pre-indexed writeback (and callers following the load/store convention) + // do not see the translated host pointer left by write_prep. + mov x23, _addr + mov x24, x12 + mov x25, x13 + write_prep 128, str_q_1 + mov x12, x24 + mov x13, x25 + + // Store both halves + str x12, [_addr] + str x13, [_addr, #8] + + write_done 128, str_q_1 + mov _addr, x23 + gret + write_bullshit 128, str_q_1 + +/* + * STUR Qn, [addr] - Same as STR Q but address already includes offset + * This is just an alias for str_q since we pre-compute the address + */ +.gadget stur_q + b NAME(gadget_str_q) + +/* + * STP Qn, Qm, [addr] - Store pair of 128-bit vectors + * Code stream: [gadget addr][rt | rt2<<8] + */ +.gadget stp_q + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rt (first vector) + ubfx x10, x8, #8, #5 // rt2 (second vector) + + // Load first vector + add x11, _cpu, #CPU_fp + lsl x12, x9, #4 + add x12, x11, x12 // x12 = base of first vector + ldr x13, [x12] // rt low + ldr x14, [x12, #8] // rt high + + // Load second vector + lsl x15, x10, #4 + add x15, x11, x15 // x15 = base of second vector + ldr x16, [x15] // rt2 low + ldr x17, [x15, #8] // rt2 high + + // Save guest address and values (write_prep may destroy _addr/x0-x3). + mov x23, _addr + mov x19, x13 + mov x20, x14 + mov x21, x16 + mov x22, x17 + + write_prep 256, stp_q_1 + + // Restore and store first vector + str x19, [_addr] + str x20, [_addr, #8] + // Store second vector + str x21, [_addr, #16] + str x22, [_addr, #24] + + write_done 256, stp_q_1 + mov _addr, x23 + gret + write_bullshit 256, stp_q_1 + +/* + * ========================================================================== + * SIMD/FP Load/Store Gadgets + * ========================================================================== + * These implement SIMD register loads/stores (V bit = 1) + * Address must already be computed in _addr by calc_addr_imm/reg + * Code stream: [gadget addr][rt (vector reg index)] + */ + +/* + * STR Bt, [Xn, #imm] - Store byte from SIMD register + * Stores low 8 bits of Vt + */ +.gadget str_simd_b + ldr x8, [_pc] + add _pc, _pc, #8 + and x8, x8, #0x1f // rt (vector reg index) + + // Get low 64 bits of vector register + add x9, _cpu, #CPU_fp + lsl x10, x8, #4 // each V reg is 16 bytes + ldr x11, [x9, x10] // load low 64 bits + and x11, x11, #0xff // keep only low byte + + mov x24, _addr // Save guest address for writeback + write_prep 8, str_simd_b_1 + strb w11, [_addr] + write_done 8, str_simd_b_1 + mov _addr, x24 // Restore guest address + gret + write_bullshit 8, str_simd_b_1 + +/* + * STR Ht, [Xn, #imm] - Store halfword from SIMD register + * Stores low 16 bits of Vt + */ +.gadget str_simd_h + ldr x8, [_pc] + add _pc, _pc, #8 + and x8, x8, #0x1f + + add x9, _cpu, #CPU_fp + lsl x10, x8, #4 + ldr x11, [x9, x10] + and x11, x11, #0xffff + + mov x24, _addr // Save guest address for writeback + write_prep 16, str_simd_h_1 + strh w11, [_addr] + write_done 16, str_simd_h_1 + mov _addr, x24 // Restore guest address + gret + write_bullshit 16, str_simd_h_1 + +/* + * STR St, [Xn, #imm] - Store single (32-bit) from SIMD register + */ +.gadget str_simd_s + ldr x8, [_pc] + add _pc, _pc, #8 + and x8, x8, #0x1f + + add x9, _cpu, #CPU_fp + lsl x10, x8, #4 + ldr x11, [x9, x10] // load low 64 bits + + mov x24, _addr // Save guest address for writeback + write_prep 32, str_simd_s_1 + str w11, [_addr] + write_done 32, str_simd_s_1 + mov _addr, x24 // Restore guest address + gret + write_bullshit 32, str_simd_s_1 + +/* + * STR Dt, [Xn, #imm] - Store double (64-bit) from SIMD register + */ +.gadget str_simd_d + ldr x8, [_pc] + add _pc, _pc, #8 + and x8, x8, #0x1f + + add x9, _cpu, #CPU_fp + lsl x10, x8, #4 + ldr x11, [x9, x10] + + mov x24, _addr // Save guest address for writeback + write_prep 64, str_simd_d_1 + str x11, [_addr] + write_done 64, str_simd_d_1 + mov _addr, x24 // Restore guest address + gret + write_bullshit 64, str_simd_d_1 + +/* + * STR Qt, [Xn, #imm] - Store quad (128-bit) from SIMD register + */ +.gadget str_simd_q + ldr x8, [_pc] + add _pc, _pc, #8 + and x8, x8, #0x1f + + add x9, _cpu, #CPU_fp + lsl x10, x8, #4 + add x9, x9, x10 + ldr x11, [x9] // low 64 bits + ldr x12, [x9, #8] // high 64 bits + + mov x23, _addr // Save guest address for writeback + mov x24, x11 + mov x25, x12 + write_prep 128, str_simd_q_1 + str x24, [_addr] + str x25, [_addr, #8] + write_done 128, str_simd_q_1 + mov _addr, x23 // Restore guest address + gret + write_bullshit 128, str_simd_q_1 + +/* + * LDR Bt, [Xn, #imm] - Load byte into SIMD register + * Note: read_prep destroys x8-x10, so save rt to x23 (callee-saved) + */ +.gadget ldr_simd_b + ldr x23, [_pc] + add _pc, _pc, #8 + and x23, x23, #0x1f // rt saved in x23 + + mov x24, _addr // Save guest address for writeback + read_prep 8, ldr_simd_b_1 + ldrb w11, [_addr] + + // Store to vector register (zero extend to 128 bits) + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + str x11, [x9] + str xzr, [x9, #8] + mov _addr, x24 // Restore guest address + gret + read_bullshit 8, ldr_simd_b_1 + +/* + * LDR Ht, [Xn, #imm] - Load halfword into SIMD register + */ +.gadget ldr_simd_h + ldr x23, [_pc] + add _pc, _pc, #8 + and x23, x23, #0x1f + + mov x24, _addr // Save guest address for writeback + read_prep 16, ldr_simd_h_1 + ldrh w11, [_addr] + + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + str x11, [x9] + str xzr, [x9, #8] + mov _addr, x24 // Restore guest address + gret + read_bullshit 16, ldr_simd_h_1 + +/* + * LDR St, [Xn, #imm] - Load single into SIMD register + */ +.gadget ldr_simd_s + ldr x23, [_pc] + add _pc, _pc, #8 + and x23, x23, #0x1f + + mov x24, _addr // Save guest address for writeback + read_prep 32, ldr_simd_s_1 + ldr w11, [_addr] + + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + str x11, [x9] + str xzr, [x9, #8] + mov _addr, x24 // Restore guest address + gret + read_bullshit 32, ldr_simd_s_1 + +/* + * LDR Dt, [Xn, #imm] - Load double into SIMD register + */ +.gadget ldr_simd_d + ldr x23, [_pc] + add _pc, _pc, #8 + and x23, x23, #0x1f + + mov x24, _addr // Save guest address for writeback + read_prep 64, ldr_simd_d_1 + ldr x11, [_addr] + + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + str x11, [x9] + str xzr, [x9, #8] + mov _addr, x24 // Restore guest address + gret + read_bullshit 64, ldr_simd_d_1 + +/* + * LDR Qt, [Xn, #imm] - Load quad into SIMD register + */ +.gadget ldr_simd_q + ldr x23, [_pc] + add _pc, _pc, #8 + and x23, x23, #0x1f + + mov x24, _addr // Save guest address for writeback + read_prep 128, ldr_simd_q_1 + ldr x11, [_addr] + ldr x12, [_addr, #8] + + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + str x11, [x9] + str x12, [x9, #8] + +#if 0 // Debug: detect all-ones pattern + // Check if this is loading all 1s (both lo and hi are -1) + adds xzr, x11, #1 // check if lo == -1 + b.ne .Lldr_simd_q_done + adds xzr, x12, #1 // check if hi == -1 + b.ne .Lldr_simd_q_done + // Both are all 1s - call helper + sub sp, sp, #96 + stp x0, x1, [sp] + stp x2, x3, [sp, #16] + stp x11, x12, [sp, #32] + stp x23, x24, [sp, #48] + str x30, [sp, #64] + stp _cpu, _pc, [sp, #72] + mov x0, x23 // rd + mov x1, x11 // lo + mov x2, x12 // hi + mov x3, #3 // op_type = LDR_Q + bl NAME(helper_check_all_ones) + ldp x0, x1, [sp] + ldp x2, x3, [sp, #16] + ldp x11, x12, [sp, #32] + ldp x23, x24, [sp, #48] + ldr x30, [sp, #64] + ldp _cpu, _pc, [sp, #72] + add sp, sp, #96 +.Lldr_simd_q_done: +#endif + + mov _addr, x24 // Restore guest address + gret + read_bullshit 128, ldr_simd_q_1 + +/* + * ========================================================================== + * SIMD Load/Store Pair Gadgets + * ========================================================================== + * Code stream: [gadget addr][rt | rt2<<8] + * Address must already be computed in _addr + */ + +/* + * STP St, St2, [addr] - Store pair of 32-bit SIMD registers + */ +.gadget stp_simd_s + ldr x8, [_pc] + add _pc, _pc, #8 + and x23, x8, #0x1f // rt + ubfx x24, x8, #8, #5 // rt2 + + // Save guest address for possible writeback + mov x25, _addr + + // Load first S register (low 32 bits of V register) + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + ldr w11, [x9, x10] // rt value + + // Load second S register + lsl x10, x24, #4 + ldr w12, [x9, x10] // rt2 value + + write_prep 64, stp_simd_s_1 + str w11, [_addr] + str w12, [_addr, #4] + write_done 64, stp_simd_s_1 + mov _addr, x25 + gret + write_bullshit 64, stp_simd_s_1 + +/* + * STP Dt, Dt2, [addr] - Store pair of 64-bit SIMD registers + */ +.gadget stp_simd_d + ldr x8, [_pc] + add _pc, _pc, #8 + and x23, x8, #0x1f + ubfx x24, x8, #8, #5 + + // Save guest address for possible writeback + mov x25, _addr + + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + ldr x11, [x9, x10] + + lsl x10, x24, #4 + ldr x12, [x9, x10] + + write_prep 128, stp_simd_d_1 + str x11, [_addr] + str x12, [_addr, #8] + write_done 128, stp_simd_d_1 + mov _addr, x25 + gret + write_bullshit 128, stp_simd_d_1 + + +/* + * STP Qt, Qt2, [addr] - Store pair of 128-bit SIMD registers + * Each Q register is 16 bytes, so total is 32 bytes + */ +.gadget stp_simd_q + ldr x8, [_pc] + add _pc, _pc, #8 + and x23, x8, #0x1f // rt + ubfx x24, x8, #8, #5 // rt2 + + // Save guest address for possible writeback (write_prep destroys _addr) + mov x25, _addr + + // Load first Q register (both halves) + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x10, x9, x10 + ldr x19, [x10] // rt low + ldr x20, [x10, #8] // rt high + + // Load second Q register + lsl x10, x24, #4 + add x10, x9, x10 + ldr x21, [x10] // rt2 low + ldr x22, [x10, #8] // rt2 high + + write_prep 256, stp_simd_q_1 + str x19, [_addr] + str x20, [_addr, #8] + str x21, [_addr, #16] + str x22, [_addr, #24] + write_done 256, stp_simd_q_1 + + // Restore guest address for writeback + mov _addr, x25 + gret + write_bullshit 256, stp_simd_q_1 + +/* + * LDP St, St2, [addr] - Load pair of 32-bit SIMD registers + */ +.gadget ldp_simd_s + ldr x8, [_pc] + add _pc, _pc, #8 + and x23, x8, #0x1f // rt + ubfx x24, x8, #8, #5 // rt2 + + // Preserve guest address for pre-indexed pair writeback; read_prep + // translates _addr to a host pointer. + mov x25, _addr + read_prep 64, ldp_simd_s_1 + ldr w11, [_addr] + ldr w12, [_addr, #4] + + // Store to first S register (zero-extend to 128 bits) + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x10, x9, x10 + str x11, [x10] + str xzr, [x10, #8] + + // Store to second S register + lsl x10, x24, #4 + add x10, x9, x10 + str x12, [x10] + str xzr, [x10, #8] + mov _addr, x25 + gret + read_bullshit 64, ldp_simd_s_1 + +/* + * LDP Dt, Dt2, [addr] - Load pair of 64-bit SIMD registers + */ +.gadget ldp_simd_d + ldr x8, [_pc] + add _pc, _pc, #8 + and x23, x8, #0x1f + ubfx x24, x8, #8, #5 + + mov x25, _addr + read_prep 128, ldp_simd_d_1 + ldr x11, [_addr] + ldr x12, [_addr, #8] + + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x10, x9, x10 + str x11, [x10] + str xzr, [x10, #8] + + lsl x10, x24, #4 + add x10, x9, x10 + str x12, [x10] + str xzr, [x10, #8] + mov _addr, x25 + gret + read_bullshit 128, ldp_simd_d_1 + +/* + * LDP Qt, Qt2, [addr] - Load pair of 128-bit SIMD registers + */ +.gadget ldp_simd_q + ldr x8, [_pc] + add _pc, _pc, #8 + and x23, x8, #0x1f + ubfx x24, x8, #8, #5 + + mov x25, _addr + read_prep 256, ldp_simd_q_1 + ldr x11, [_addr] + ldr x12, [_addr, #8] + ldr x13, [_addr, #16] + ldr x14, [_addr, #24] + + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x10, x9, x10 + str x11, [x10] + str x12, [x10, #8] + + lsl x10, x24, #4 + add x10, x9, x10 + str x13, [x10] + str x14, [x10, #8] + mov _addr, x25 + gret + read_bullshit 256, ldp_simd_q_1 + +/* + * MOVI/MVNI - Move immediate to vector + * Code stream: [gadget][rd | Q<<8 | op<<9 | imm8<<16 | cmode<<24] + * + * For simplicity, we implement the common cases: + * - imm8=0, cmode=0, op=0 -> MOVI Vd, #0 (zeros) + * - imm8=0, cmode=0, op=1 -> MVNI Vd, #0 (all ones) + */ +.gadget movi_v + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #1 // Q + ubfx x11, x8, #9, #1 // op (0=MOVI, 1=MVNI) + ubfx x12, x8, #16, #8 // imm8 + ubfx x13, x8, #24, #4 // cmode + + add x14, _cpu, #CPU_fp + lsl x15, x9, #4 // offset = rd * 16 + add x14, x14, x15 // address of Vd + + // For now, just handle the simple cases + // MOVI with imm8=0 -> zeros + // MVNI with imm8=0 -> all ones + cbz x11, movi_zero + + // MVNI: fill with ones + mov x16, #-1 + str x16, [x14] + // Check Q bit: Q=0 means 64-bit vector, Q=1 means 128-bit + cbz x10, movi_mvni_clear_high + str x16, [x14, #8] + gret +movi_mvni_clear_high: + str xzr, [x14, #8] // Clear upper 64 bits for 64-bit vectors + gret + +movi_zero: + // MOVI with imm8=0: fill with zeros (or expand imm8 based on cmode) + // For simplicity, if imm8=0, just zero the register + cbz x12, movi_really_zero + + // TODO: implement proper immediate expansion based on cmode + // For now, treat any non-zero imm8 as undefined + mov w0, #INT_UNDEFINED + b fiber_exit + +movi_really_zero: + str xzr, [x14] + str xzr, [x14, #8] + gret + +/* + * SET_VEC_IMM - Load immediate vector value + * Code stream: [gadget][rd][imm_lo][imm_hi] + */ +.gadget set_vec_imm + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ldr x10, [_pc] // imm_lo + add _pc, _pc, #8 + ldr x11, [_pc] // imm_hi + add _pc, _pc, #8 + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + add x12, x12, x13 + str x10, [x12] + str x11, [x12, #8] + +#if 0 // Debug: detect all-ones pattern + // Check if this is setting all 1s (both lo and hi are -1) + adds xzr, x10, #1 // check if lo == -1 + b.ne .Lset_vec_imm_done + adds xzr, x11, #1 // check if hi == -1 + b.ne .Lset_vec_imm_done + // Both are all 1s - call helper + sub sp, sp, #96 + stp x0, x1, [sp] + stp x2, x3, [sp, #16] + stp x9, x10, [sp, #32] + stp x11, x12, [sp, #48] + str x30, [sp, #64] + stp _cpu, _pc, [sp, #72] + mov x0, x9 // rd + mov x1, x10 // lo + mov x2, x11 // hi + mov x3, #1 // op_type = SET_VEC_IMM + bl NAME(helper_check_all_ones) + ldp x0, x1, [sp] + ldp x2, x3, [sp, #16] + ldp x9, x10, [sp, #32] + ldp x11, x12, [sp, #48] + ldr x30, [sp, #64] + ldp _cpu, _pc, [sp, #72] + add sp, sp, #96 +.Lset_vec_imm_done: +#endif + gret + +/* + * ORR (immediate) - Bitwise OR with immediate vector + * Code stream: [gadget][rd | Q<<8][imm_lo][imm_hi] + */ +.gadget orr_imm_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x17, x8, #8, #1 // Q + ldr x10, [_pc] // imm_lo + add _pc, _pc, #8 + ldr x11, [_pc] // imm_hi + add _pc, _pc, #8 + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + add x12, x12, x13 + + ldr x14, [x12] + orr x14, x14, x10 + str x14, [x12] + + cbz x17, .Lorr_imm_clear_high + + ldr x15, [x12, #8] + orr x15, x15, x11 + str x15, [x12, #8] + gret + +.Lorr_imm_clear_high: + str xzr, [x12, #8] + gret + +/* + * BIC (immediate) - Bit clear with immediate vector + * Code stream: [gadget][rd | Q<<8][imm_lo][imm_hi] + */ +.gadget bic_imm_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x17, x8, #8, #1 // Q + ldr x10, [_pc] // imm_lo + add _pc, _pc, #8 + ldr x11, [_pc] // imm_hi + add _pc, _pc, #8 + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + add x12, x12, x13 + + ldr x14, [x12] + bic x14, x14, x10 + str x14, [x12] + + cbz x17, .Lbic_imm_clear_high + + ldr x15, [x12, #8] + bic x15, x15, x11 + str x15, [x12, #8] + gret + +.Lbic_imm_clear_high: + str xzr, [x12, #8] + gret + +/* + * USHL - Unsigned shift left (vector) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * + * For each element: Vd[i] = Vn[i] << Vm[i] (if Vm[i] >= 0) + * Vn[i] >> -Vm[i] (if Vm[i] < 0, unsigned right shift) + * + * For simplicity, we implement element-by-element operations. + */ +.gadget ushl_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (vector dest) + ubfx x10, x8, #8, #5 // rn (vector src1) + ubfx x11, x8, #16, #5 // rm (vector shift amounts) + ubfx x12, x8, #24, #2 // size (0=8b, 1=16b, 2=32b, 3=64b) + ubfx x17, x8, #26, #1 // Q (0=64-bit vec, 1=128-bit vec) + + // Get vector register base addresses + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 // Vd offset + add x14, x13, x14 // &Vd + lsl x15, x10, #4 // Vn offset + add x15, x13, x15 // &Vn + lsl x16, x11, #4 // Vm offset + add x16, x13, x16 // &Vm + + // Branch based on element size + cmp x12, #3 + b.eq .Lushl_64 + cmp x12, #2 + b.eq .Lushl_32 + cmp x12, #1 + b.eq .Lushl_16 + b .Lushl_8 + +.Lushl_8: + // 8-bit elements: 8 or 16 elements + ldr x20, [x15] // Vn low 64 bits + ldr x21, [x16] // Vm low 64 bits + mov x22, #0 // result low + mov x23, #8 // loop count + mov x24, #0 // bit position + +.Lushl_8_loop: + lsr x25, x20, x24 // shift to get element at bit position x24 + and x25, x25, #0xff // extract byte from Vn + lsr x26, x21, x24 + sbfx x26, x26, #0, #8 // extract signed shift amount from Vm + cmp x26, #0 + b.lt .Lushl_8_right + lsl x25, x25, x26 // left shift + and x25, x25, #0xff + b .Lushl_8_store +.Lushl_8_right: + neg x26, x26 + lsr x25, x25, x26 // right shift +.Lushl_8_store: + lsl x25, x25, x24 // position in result + orr x22, x22, x25 + add x24, x24, #8 + subs x23, x23, #1 + b.ne .Lushl_8_loop + + str x22, [x14] // store low result + cbz x17, .Lushl_clear_high + + // Process high 64 bits if Q=1 + ldr x20, [x15, #8] + ldr x21, [x16, #8] + mov x22, #0 + mov x23, #8 + mov x24, #0 + +.Lushl_8_hi_loop: + lsr x25, x20, x24 + and x25, x25, #0xff + lsr x26, x21, x24 + sbfx x26, x26, #0, #8 + cmp x26, #0 + b.lt .Lushl_8_hi_right + lsl x25, x25, x26 + and x25, x25, #0xff + b .Lushl_8_hi_store +.Lushl_8_hi_right: + neg x26, x26 + lsr x25, x25, x26 +.Lushl_8_hi_store: + lsl x25, x25, x24 + orr x22, x22, x25 + add x24, x24, #8 + subs x23, x23, #1 + b.ne .Lushl_8_hi_loop + + str x22, [x14, #8] + gret + +.Lushl_16: + // 16-bit elements: 4 or 8 elements + ldr x20, [x15] + ldr x21, [x16] + mov x22, #0 + mov x23, #4 + mov x24, #0 + +.Lushl_16_loop: + lsr x25, x20, x24 + and x25, x25, #0xffff + lsr x26, x21, x24 + sbfx x26, x26, #0, #16 + cmp x26, #0 + b.lt .Lushl_16_right + lsl x25, x25, x26 + and x25, x25, #0xffff + b .Lushl_16_store +.Lushl_16_right: + neg x26, x26 + lsr x25, x25, x26 +.Lushl_16_store: + lsl x25, x25, x24 + orr x22, x22, x25 + add x24, x24, #16 + subs x23, x23, #1 + b.ne .Lushl_16_loop + + str x22, [x14] + cbz x17, .Lushl_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + mov x22, #0 + mov x23, #4 + mov x24, #0 + +.Lushl_16_hi_loop: + lsr x25, x20, x24 + and x25, x25, #0xffff + lsr x26, x21, x24 + sbfx x26, x26, #0, #16 + cmp x26, #0 + b.lt .Lushl_16_hi_right + lsl x25, x25, x26 + and x25, x25, #0xffff + b .Lushl_16_hi_store +.Lushl_16_hi_right: + neg x26, x26 + lsr x25, x25, x26 +.Lushl_16_hi_store: + lsl x25, x25, x24 + orr x22, x22, x25 + add x24, x24, #16 + subs x23, x23, #1 + b.ne .Lushl_16_hi_loop + + str x22, [x14, #8] + gret + +.Lushl_32: + // 32-bit elements: 2 or 4 elements + ldr x20, [x15] + ldr x21, [x16] + + // First 32-bit element + and x25, x20, #0xffffffff + sbfx x26, x21, #0, #32 + cmp x26, #0 + b.lt .Lushl_32_0_right + lsl x25, x25, x26 + and x25, x25, #0xffffffff + b .Lushl_32_0_done +.Lushl_32_0_right: + neg x26, x26 + lsr x25, x25, x26 +.Lushl_32_0_done: + mov x22, x25 + + // Second 32-bit element + lsr x25, x20, #32 + sbfx x26, x21, #32, #32 + cmp x26, #0 + b.lt .Lushl_32_1_right + lsl x25, x25, x26 + and x25, x25, #0xffffffff + b .Lushl_32_1_done +.Lushl_32_1_right: + neg x26, x26 + lsr x25, x25, x26 +.Lushl_32_1_done: + orr x22, x22, x25, lsl #32 + + str x22, [x14] + cbz x17, .Lushl_clear_high + + // High 64 bits if Q=1 + ldr x20, [x15, #8] + ldr x21, [x16, #8] + + and x25, x20, #0xffffffff + sbfx x26, x21, #0, #32 + cmp x26, #0 + b.lt .Lushl_32_2_right + lsl x25, x25, x26 + and x25, x25, #0xffffffff + b .Lushl_32_2_done +.Lushl_32_2_right: + neg x26, x26 + lsr x25, x25, x26 +.Lushl_32_2_done: + mov x22, x25 + + lsr x25, x20, #32 + sbfx x26, x21, #32, #32 + cmp x26, #0 + b.lt .Lushl_32_3_right + lsl x25, x25, x26 + and x25, x25, #0xffffffff + b .Lushl_32_3_done +.Lushl_32_3_right: + neg x26, x26 + lsr x25, x25, x26 +.Lushl_32_3_done: + orr x22, x22, x25, lsl #32 + + str x22, [x14, #8] + gret + +.Lushl_64: + // 64-bit elements: 1 or 2 elements + ldr x20, [x15] + ldr x21, [x16] + sbfx x26, x21, #0, #8 // shift amount (signed, only 8 bits matter) + cmp x26, #0 + b.lt .Lushl_64_right + lsl x22, x20, x26 + b .Lushl_64_done +.Lushl_64_right: + neg x26, x26 + lsr x22, x20, x26 +.Lushl_64_done: + str x22, [x14] + cbz x17, .Lushl_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + sbfx x26, x21, #0, #8 + cmp x26, #0 + b.lt .Lushl_64_hi_right + lsl x22, x20, x26 + b .Lushl_64_hi_done +.Lushl_64_hi_right: + neg x26, x26 + lsr x22, x20, x26 +.Lushl_64_hi_done: + str x22, [x14, #8] + gret + +.Lushl_clear_high: + str xzr, [x14, #8] + gret + +/* + * Macro for NEON three-same register shift instructions. + * All of SRSHL, URSHL, SQSHL, UQSHL, SQRSHL, UQRSHL are native NEON instructions + * and support all element sizes including 64-bit (2D with Q=1). + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + */ +.macro make_vec_shift_three_same name, insn +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .L\name\()_size_b + cmp x12, #1 + b.eq .L\name\()_size_h + cmp x12, #2 + b.eq .L\name\()_size_s + // size == 3: 64-bit elements (only valid with Q=1) + \insn v0.2d, v0.2d, v1.2d + b .L\name\()_store_q + +.L\name\()_size_b: + cbz x17, .L\name\()_b_q0 + \insn v0.16b, v0.16b, v1.16b + b .L\name\()_store_q +.L\name\()_b_q0: + \insn v0.8b, v0.8b, v1.8b + b .L\name\()_store_low + +.L\name\()_size_h: + cbz x17, .L\name\()_h_q0 + \insn v0.8h, v0.8h, v1.8h + b .L\name\()_store_q +.L\name\()_h_q0: + \insn v0.4h, v0.4h, v1.4h + b .L\name\()_store_low + +.L\name\()_size_s: + cbz x17, .L\name\()_s_q0 + \insn v0.4s, v0.4s, v1.4s + b .L\name\()_store_q +.L\name\()_s_q0: + \insn v0.2s, v0.2s, v1.2s + b .L\name\()_store_low + +.L\name\()_store_q: + str q0, [x14] + gret + +.L\name\()_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret +.endm + +// SSHL - Signed shift left (uses arithmetic right shift for negative shift values) +make_vec_shift_three_same sshl, sshl +make_vec_shift_three_same srshl, srshl +make_vec_shift_three_same urshl, urshl +make_vec_shift_three_same sqshl, sqshl +make_vec_shift_three_same uqshl, uqshl +make_vec_shift_three_same sqrshl, sqrshl +make_vec_shift_three_same uqrshl, uqrshl + +// Saturating add/sub (support B/H/S/D) +make_vec_shift_three_same sqadd, sqadd +make_vec_shift_three_same uqadd, uqadd +make_vec_shift_three_same sqsub, sqsub +make_vec_shift_three_same uqsub, uqsub + +// Halving sub (B/H/S only — no D variant; gen.c rejects size=3) +// Use a dedicated macro that omits the .2d path +.macro make_vec_three_same_noD name, insn +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + lsl x16, x11, #4 + add x16, x13, x16 + ldr q0, [x15] + ldr q1, [x16] + cmp x12, #0 + b.eq .L\name\()_size_b + cmp x12, #1 + b.eq .L\name\()_size_h + // size == 2: 32-bit + cbz x17, .L\name\()_s_q0 + \insn v0.4s, v0.4s, v1.4s + b .L\name\()_store_q +.L\name\()_s_q0: + \insn v0.2s, v0.2s, v1.2s + b .L\name\()_store_low +.L\name\()_size_b: + cbz x17, .L\name\()_b_q0 + \insn v0.16b, v0.16b, v1.16b + b .L\name\()_store_q +.L\name\()_b_q0: + \insn v0.8b, v0.8b, v1.8b + b .L\name\()_store_low +.L\name\()_size_h: + cbz x17, .L\name\()_h_q0 + \insn v0.8h, v0.8h, v1.8h + b .L\name\()_store_q +.L\name\()_h_q0: + \insn v0.4h, v0.4h, v1.4h + b .L\name\()_store_low +.L\name\()_store_q: + str q0, [x14] + gret +.L\name\()_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret +.endm + +make_vec_three_same_noD shsub, shsub +make_vec_three_same_noD uhsub, uhsub + +// Compare register (B/H/S/D) +make_vec_shift_three_same cmgt_reg, cmgt +make_vec_shift_three_same cmge_reg, cmge + +/* + * Macro for FP vector three-same instructions. + * These use sz (0=single, 1=double) instead of integer size field. + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | sz<<24 | Q<<26] + * Single: .2s (Q=0) or .4s (Q=1) + * Double: .2d (Q=1 only; Q=0 is undefined for most) + */ +.macro make_fp_vec_three_same name, insn +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // sz (0=single, 1=double) + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cbnz x12, .L\name\()_double + // Single precision + cbz x17, .L\name\()_s_q0 + \insn v0.4s, v0.4s, v1.4s + b .L\name\()_store_q +.L\name\()_s_q0: + \insn v0.2s, v0.2s, v1.2s + b .L\name\()_store_low + +.L\name\()_double: + // Double precision (Q must be 1) + \insn v0.2d, v0.2d, v1.2d + b .L\name\()_store_q + +.L\name\()_store_q: + str q0, [x14] + gret + +.L\name\()_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret +.endm + +// FP vector three-same operations +make_fp_vec_three_same fp_fadd, fadd +make_fp_vec_three_same fp_fsub, fsub +make_fp_vec_three_same fp_fmul, fmul +make_fp_vec_three_same fp_fdiv, fdiv +make_fp_vec_three_same fp_fmulx, fmulx +/* + * FMLA/FMLS need a separate macro because they accumulate into Vd: + * FMLA Vd, Vn, Vm => Vd = Vd + Vn*Vm + * The standard make_fp_vec_three_same macro loads Vn→v0, Vm→v1 and + * stores v0, which computes Vn + Vn*Vm (wrong). + */ +.macro make_fp_vec_three_same_accum name, insn +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // sz (0=single, 1=double) + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] // Vn + ldr q1, [x16] // Vm + ldr q2, [x14] // Vd (accumulator) + + cbnz x12, .L\name\()_double + // Single precision + cbz x17, .L\name\()_s_q0 + \insn v2.4s, v0.4s, v1.4s + b .L\name\()_store_q +.L\name\()_s_q0: + \insn v2.2s, v0.2s, v1.2s + b .L\name\()_store_low + +.L\name\()_double: + // Double precision (Q must be 1) + \insn v2.2d, v0.2d, v1.2d + b .L\name\()_store_q + +.L\name\()_store_q: + str q2, [x14] + gret + +.L\name\()_store_low: + str d2, [x14] + str xzr, [x14, #8] + gret +.endm + +make_fp_vec_three_same_accum fp_fmla, fmla +make_fp_vec_three_same_accum fp_fmls, fmls +make_fp_vec_three_same fp_fmax, fmax +make_fp_vec_three_same fp_fmin, fmin +make_fp_vec_three_same fp_fmaxnm, fmaxnm +make_fp_vec_three_same fp_fminnm, fminnm +make_fp_vec_three_same fp_faddp, faddp +make_fp_vec_three_same fp_fmaxp, fmaxp +make_fp_vec_three_same fp_fminp, fminp +make_fp_vec_three_same fp_frecps, frecps +make_fp_vec_three_same fp_frsqrts, frsqrts +make_fp_vec_three_same fp_fcmeq, fcmeq +make_fp_vec_three_same fp_fcmge, fcmge +make_fp_vec_three_same fp_fcmgt, fcmgt +make_fp_vec_three_same fp_facge, facge +make_fp_vec_three_same fp_facgt, facgt +make_fp_vec_three_same fp_fabd, fabd + +/* + * CMHI - Compare higher (unsigned greater than) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * + * For each element: Vd[i] = (Vn[i] > Vm[i]) ? -1 : 0 + */ +.gadget cmhi_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + cmp x12, #3 + b.eq .Lcmhi_64 + cmp x12, #2 + b.eq .Lcmhi_32 + cmp x12, #1 + b.eq .Lcmhi_16 + b .Lcmhi_8 + +.Lcmhi_8: + ldr x20, [x15] + ldr x21, [x16] + mov x22, #0 + mov x23, #8 + mov x24, #0 + +.Lcmhi_8_loop: + lsr x25, x20, x24 + and x25, x25, #0xff + lsr x26, x21, x24 + and x26, x26, #0xff + cmp x25, x26 + cset x19, hi // set 1 if Vn > Vm (use x19 to avoid clobbering _addr/x7) + neg x19, x19 // -1 if true, 0 if false + and x19, x19, #0xff + lsl x19, x19, x24 + orr x22, x22, x19 + add x24, x24, #8 + subs x23, x23, #1 + b.ne .Lcmhi_8_loop + + str x22, [x14] + cbz x17, .Lcmhi_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + mov x22, #0 + mov x23, #8 + mov x24, #0 + +.Lcmhi_8_hi_loop: + lsr x25, x20, x24 + and x25, x25, #0xff + lsr x26, x21, x24 + and x26, x26, #0xff + cmp x25, x26 + cset x19, hi + neg x19, x19 + and x19, x19, #0xff + lsl x19, x19, x24 + orr x22, x22, x19 + add x24, x24, #8 + subs x23, x23, #1 + b.ne .Lcmhi_8_hi_loop + + str x22, [x14, #8] + gret + +.Lcmhi_16: + ldr x20, [x15] + ldr x21, [x16] + mov x22, #0 + mov x23, #4 + mov x24, #0 + +.Lcmhi_16_loop: + lsr x25, x20, x24 + and x25, x25, #0xffff + lsr x26, x21, x24 + and x26, x26, #0xffff + cmp x25, x26 + cset x19, hi + neg x19, x19 + and x19, x19, #0xffff + lsl x19, x19, x24 + orr x22, x22, x19 + add x24, x24, #16 + subs x23, x23, #1 + b.ne .Lcmhi_16_loop + + str x22, [x14] + cbz x17, .Lcmhi_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + mov x22, #0 + mov x23, #4 + mov x24, #0 + +.Lcmhi_16_hi_loop: + lsr x25, x20, x24 + and x25, x25, #0xffff + lsr x26, x21, x24 + and x26, x26, #0xffff + cmp x25, x26 + cset x19, hi + neg x19, x19 + and x19, x19, #0xffff + lsl x19, x19, x24 + orr x22, x22, x19 + add x24, x24, #16 + subs x23, x23, #1 + b.ne .Lcmhi_16_hi_loop + + str x22, [x14, #8] + gret + +.Lcmhi_32: + ldr x20, [x15] + ldr x21, [x16] + + // First element + and x25, x20, #0xffffffff + and x26, x21, #0xffffffff + cmp x25, x26 + cset x19, hi + neg x19, x19 + and x22, x19, #0xffffffff + + // Second element + lsr x25, x20, #32 + lsr x26, x21, #32 + cmp x25, x26 + cset x19, hi + neg x19, x19 + and x19, x19, #0xffffffff + orr x22, x22, x19, lsl #32 + + str x22, [x14] + cbz x17, .Lcmhi_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + + and x25, x20, #0xffffffff + and x26, x21, #0xffffffff + cmp x25, x26 + cset x19, hi + neg x19, x19 + and x22, x19, #0xffffffff + + lsr x25, x20, #32 + lsr x26, x21, #32 + cmp x25, x26 + cset x19, hi + neg x19, x19 + and x19, x19, #0xffffffff + orr x22, x22, x19, lsl #32 + + str x22, [x14, #8] + gret + +.Lcmhi_64: + ldr x20, [x15] + ldr x21, [x16] + cmp x20, x21 + cset x22, hi + neg x22, x22 + str x22, [x14] + cbz x17, .Lcmhi_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + cmp x20, x21 + cset x22, hi + neg x22, x22 + str x22, [x14, #8] + gret + +.Lcmhi_clear_high: + str xzr, [x14, #8] + gret + +/* + * CMHS - Compare higher or same (unsigned greater or equal) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * + * For each element: Vd[i] = (Vn[i] >= Vm[i]) ? -1 : 0 + */ +.gadget cmhs_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + cmp x12, #3 + b.eq .Lcmhs_64 + cmp x12, #2 + b.eq .Lcmhs_32 + cmp x12, #1 + b.eq .Lcmhs_16 + b .Lcmhs_8 + +.Lcmhs_8: + // Use x20-x27 to avoid clobbering _cpu (x1) and _tlb (x2) + ldr x20, [x15] // Vn low + ldr x21, [x16] // Vm low + mov x22, #0 // result + mov x23, #8 // loop count + mov x24, #0 // bit position + +.Lcmhs_8_loop: + lsr x25, x20, x24 + and x25, x25, #0xff + lsr x26, x21, x24 + and x26, x26, #0xff + cmp x25, x26 + cset x19, hs // set 1 if Vn >= Vm (unsigned) + neg x19, x19 // -1 if true, 0 if false + and x19, x19, #0xff + lsl x19, x19, x24 + orr x22, x22, x19 + add x24, x24, #8 + subs x23, x23, #1 + b.ne .Lcmhs_8_loop + + str x22, [x14] + cbz x17, .Lcmhs_clear_high + + ldr x20, [x15, #8] // Vn high + ldr x21, [x16, #8] // Vm high + mov x22, #0 + mov x23, #8 + mov x24, #0 + +.Lcmhs_8_hi_loop: + lsr x25, x20, x24 + and x25, x25, #0xff + lsr x26, x21, x24 + and x26, x26, #0xff + cmp x25, x26 + cset x19, hs + neg x19, x19 + and x19, x19, #0xff + lsl x19, x19, x24 + orr x22, x22, x19 + add x24, x24, #8 + subs x23, x23, #1 + b.ne .Lcmhs_8_hi_loop + + str x22, [x14, #8] + gret + +.Lcmhs_16: + ldr x20, [x15] + ldr x21, [x16] + mov x22, #0 + mov x23, #4 + mov x24, #0 + +.Lcmhs_16_loop: + lsr x25, x20, x24 + and x25, x25, #0xffff + lsr x26, x21, x24 + and x26, x26, #0xffff + cmp x25, x26 + cset x19, hs + neg x19, x19 + and x19, x19, #0xffff + lsl x19, x19, x24 + orr x22, x22, x19 + add x24, x24, #16 + subs x23, x23, #1 + b.ne .Lcmhs_16_loop + + str x22, [x14] + cbz x17, .Lcmhs_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + mov x22, #0 + mov x23, #4 + mov x24, #0 + +.Lcmhs_16_hi_loop: + lsr x25, x20, x24 + and x25, x25, #0xffff + lsr x26, x21, x24 + and x26, x26, #0xffff + cmp x25, x26 + cset x19, hs + neg x19, x19 + and x19, x19, #0xffff + lsl x19, x19, x24 + orr x22, x22, x19 + add x24, x24, #16 + subs x23, x23, #1 + b.ne .Lcmhs_16_hi_loop + + str x22, [x14, #8] + gret + +.Lcmhs_32: + ldr x20, [x15] + ldr x21, [x16] + + // First element + and x25, x20, #0xffffffff + and x26, x21, #0xffffffff + cmp x25, x26 + cset x19, hs + neg x19, x19 + and x22, x19, #0xffffffff + + // Second element + lsr x25, x20, #32 + lsr x26, x21, #32 + cmp x25, x26 + cset x19, hs + neg x19, x19 + and x19, x19, #0xffffffff + orr x22, x22, x19, lsl #32 + + str x22, [x14] + cbz x17, .Lcmhs_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + + and x25, x20, #0xffffffff + and x26, x21, #0xffffffff + cmp x25, x26 + cset x19, hs + neg x19, x19 + and x22, x19, #0xffffffff + + lsr x25, x20, #32 + lsr x26, x21, #32 + cmp x25, x26 + cset x19, hs + neg x19, x19 + and x19, x19, #0xffffffff + orr x22, x22, x19, lsl #32 + + str x22, [x14, #8] + gret + +.Lcmhs_64: + ldr x20, [x15] + ldr x21, [x16] + cmp x20, x21 + cset x22, hs + neg x22, x22 + str x22, [x14] + cbz x17, .Lcmhs_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + cmp x20, x21 + cset x22, hs + neg x22, x22 + str x22, [x14, #8] + gret + +.Lcmhs_clear_high: + str xzr, [x14, #8] + gret + +/* + * CMEQ - Compare equal (vector) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * + * For each element: Vd[i] = (Vn[i] == Vm[i]) ? -1 : 0 + */ +.gadget cmeq_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + cmp x12, #3 + b.eq .Lcmeq_64 + cmp x12, #2 + b.eq .Lcmeq_32 + cmp x12, #1 + b.eq .Lcmeq_16 + b .Lcmeq_8 + +.Lcmeq_8: + ldr x20, [x15] + ldr x21, [x16] + // XOR to check equality - each byte is 0 if equal + eor x22, x20, x21 + mov x23, #0 + mov x24, #8 + mov x25, #0 + +.Lcmeq_8_loop: + lsr x26, x22, x25 + and x26, x26, #0xff + cmp x26, #0 + cset x19, eq + neg x19, x19 + and x19, x19, #0xff + lsl x19, x19, x25 + orr x23, x23, x19 + add x25, x25, #8 + subs x24, x24, #1 + b.ne .Lcmeq_8_loop + + str x23, [x14] + cbz x17, .Lcmeq_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + eor x22, x20, x21 + mov x23, #0 + mov x24, #8 + mov x25, #0 + +.Lcmeq_8_hi_loop: + lsr x26, x22, x25 + and x26, x26, #0xff + cmp x26, #0 + cset x19, eq + neg x19, x19 + and x19, x19, #0xff + lsl x19, x19, x25 + orr x23, x23, x19 + add x25, x25, #8 + subs x24, x24, #1 + b.ne .Lcmeq_8_hi_loop + + str x23, [x14, #8] + gret + +.Lcmeq_16: + ldr x20, [x15] + ldr x21, [x16] + eor x22, x20, x21 + mov x23, #0 + mov x24, #4 + mov x25, #0 + +.Lcmeq_16_loop: + lsr x26, x22, x25 + and x26, x26, #0xffff + cmp x26, #0 + cset x19, eq + neg x19, x19 + and x19, x19, #0xffff + lsl x19, x19, x25 + orr x23, x23, x19 + add x25, x25, #16 + subs x24, x24, #1 + b.ne .Lcmeq_16_loop + + str x23, [x14] + cbz x17, .Lcmeq_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + eor x22, x20, x21 + mov x23, #0 + mov x24, #4 + mov x25, #0 + +.Lcmeq_16_hi_loop: + lsr x26, x22, x25 + and x26, x26, #0xffff + cmp x26, #0 + cset x19, eq + neg x19, x19 + and x19, x19, #0xffff + lsl x19, x19, x25 + orr x23, x23, x19 + add x25, x25, #16 + subs x24, x24, #1 + b.ne .Lcmeq_16_hi_loop + + str x23, [x14, #8] + gret + +.Lcmeq_32: + ldr x20, [x15] + ldr x21, [x16] + + and x25, x20, #0xffffffff + and x26, x21, #0xffffffff + cmp x25, x26 + cset x19, eq + neg x19, x19 + and x22, x19, #0xffffffff + + lsr x25, x20, #32 + lsr x26, x21, #32 + cmp x25, x26 + cset x19, eq + neg x19, x19 + and x19, x19, #0xffffffff + orr x22, x22, x19, lsl #32 + + str x22, [x14] + cbz x17, .Lcmeq_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + + and x25, x20, #0xffffffff + and x26, x21, #0xffffffff + cmp x25, x26 + cset x19, eq + neg x19, x19 + and x22, x19, #0xffffffff + + lsr x25, x20, #32 + lsr x26, x21, #32 + cmp x25, x26 + cset x19, eq + neg x19, x19 + and x19, x19, #0xffffffff + orr x22, x22, x19, lsl #32 + + str x22, [x14, #8] + gret + +.Lcmeq_64: + ldr x20, [x15] + ldr x21, [x16] + cmp x20, x21 + cset x22, eq + neg x22, x22 + str x22, [x14] + cbz x17, .Lcmeq_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + cmp x20, x21 + cset x22, eq + neg x22, x22 + str x22, [x14, #8] + gret + +.Lcmeq_clear_high: + str xzr, [x14, #8] + gret + +// Old manual cmeq_zero_vec replaced by native NEON macro (make_int_vec_cmp_zero) above + +/* + * XTN/SQXTUN/SQXTN/UQXTN - Narrowing instructions + * Code stream: [gadget addr][rd | rn<<8 | size<<16 | Q<<24] + * size: 0=8H→8B, 1=4S→4H, 2=2D→2S + * Q: 0=lower half (XTN), 1=upper half (XTN2) + * Uses native NEON narrowing instructions. + */ +.macro make_narrow_vec name, insn_b_lo, insn_b_hi, insn_h_lo, insn_h_hi, insn_s_lo, insn_s_hi +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #16, #2 // size + ubfx x17, x8, #24, #1 // Q + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + ldr q0, [x15] // load source (wide) + ldr q1, [x14] // load dest (for Q=1, preserve lower half) + cmp x12, #2 + b.eq .L\name\()_2d + cmp x12, #1 + b.eq .L\name\()_4s + // size=0: 8H→8B + cbz x17, .L\name\()_8h_lo + \insn_b_hi // XTN2/etc: narrow into upper half of v1 + b .L\name\()_store128 +.L\name\()_8h_lo: + \insn_b_lo // XTN: narrow into lower half of v1 + b .L\name\()_store64 +.L\name\()_4s: + cbz x17, .L\name\()_4s_lo + \insn_h_hi + b .L\name\()_store128 +.L\name\()_4s_lo: + \insn_h_lo + b .L\name\()_store64 +.L\name\()_2d: + cbz x17, .L\name\()_2d_lo + \insn_s_hi + b .L\name\()_store128 +.L\name\()_2d_lo: + \insn_s_lo +.L\name\()_store64: + stp xzr, xzr, [x14] // clear destination + str d1, [x14] // store lower 64 bits only + gret +.L\name\()_store128: + str q1, [x14] // store full 128 bits (upper half inserted) + gret +.endm + +/* + * UADDLP/SADDLP/UADALP/SADALP - Pairwise add long + * Code stream: [gadget addr][rd | rn<<8 | size<<16 | Q<<24] + * size: 0=B→H, 1=H→S, 2=S→D + * Uses native NEON pairwise instructions. + */ +.macro make_pairwise_addl name, insn_b_8, insn_b_16, insn_h_4, insn_h_8, insn_s_2, insn_s_4 +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #16, #2 // size + ubfx x17, x8, #24, #1 // Q + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + ldr q0, [x15] // load source + ldr q2, [x14] // load dest (for accumulate variants) + cmp x12, #2 + b.eq .L\name\()_s + cmp x12, #1 + b.eq .L\name\()_h + cbz x17, .L\name\()_b8 + \insn_b_16 + str q1, [x14] + gret +.L\name\()_b8: + \insn_b_8 + str d1, [x14] + str xzr, [x14, #8] + gret +.L\name\()_h: + cbz x17, .L\name\()_h4 + \insn_h_8 + str q1, [x14] + gret +.L\name\()_h4: + \insn_h_4 + str d1, [x14] + str xzr, [x14, #8] + gret +.L\name\()_s: + cbz x17, .L\name\()_s2 + \insn_s_4 + str q1, [x14] + gret +.L\name\()_s2: + \insn_s_2 + str d1, [x14] + str xzr, [x14, #8] + gret +.endm + +/* + * SHRN/RSHRN - Shift Right Narrow (and rounding variant) + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24 | Q<<28] + * esize: 0=8H→8B, 1=4S→4H, 2=2D→2S (source element size code, not actual) + * Q=0: write lower half, Q=1: write upper half (SHRN2/RSHRN2) + * Uses urshl/srshl (variable shift with negative amount) + xtn to narrow. + */ +.macro make_shrn_vec name, sh8h, sh4s, sh2d +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #8 // shift amount + ubfx x12, x8, #24, #4 // esize (0=B, 1=H, 2=S - narrow target) + ubfx x17, x8, #28, #1 // Q + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + ldr q0, [x15] // load source (wide elements) + ldr q2, [x14] // load dest (for Q=1 preserve lower) + neg x11, x11 // negative shift for right shift + cmp x12, #2 + b.eq .L\name\()_2d + cmp x12, #1 + b.eq .L\name\()_4s + // esize=0: 8H→8B + dup v1.8h, w11 + \sh8h + cbz x17, .L\name\()_8h_lo + xtn2 v2.16b, v0.8h + str q2, [x14] + gret +.L\name\()_8h_lo: + xtn v2.8b, v0.8h + str d2, [x14] + str xzr, [x14, #8] + gret +.L\name\()_4s: + dup v1.4s, w11 + \sh4s + cbz x17, .L\name\()_4s_lo + xtn2 v2.8h, v0.4s + str q2, [x14] + gret +.L\name\()_4s_lo: + xtn v2.4h, v0.4s + str d2, [x14] + str xzr, [x14, #8] + gret +.L\name\()_2d: + dup v1.2d, x11 + \sh2d + cbz x17, .L\name\()_2d_lo + xtn2 v2.4s, v0.2d + str q2, [x14] + gret +.L\name\()_2d_lo: + xtn v2.2s, v0.2d + str d2, [x14] + str xzr, [x14, #8] + gret +.endm + +// SHRN: unsigned shift right (truncate) then narrow — ushl (non-rounding) +make_shrn_vec shrn, "ushl v0.8h, v0.8h, v1.8h", "ushl v0.4s, v0.4s, v1.4s", "ushl v0.2d, v0.2d, v1.2d" +// RSHRN: unsigned rounding shift right then narrow — urshl (unsigned rounding) +make_shrn_vec rshrn, "urshl v0.8h, v0.8h, v1.8h", "urshl v0.4s, v0.4s, v1.4s", "urshl v0.2d, v0.2d, v1.2d" + +make_pairwise_addl uaddlp, "uaddlp v1.4h, v0.8b", "uaddlp v1.8h, v0.16b", "uaddlp v1.2s, v0.4h", "uaddlp v1.4s, v0.8h", "uaddlp v1.1d, v0.2s", "uaddlp v1.2d, v0.4s" +make_pairwise_addl saddlp, "saddlp v1.4h, v0.8b", "saddlp v1.8h, v0.16b", "saddlp v1.2s, v0.4h", "saddlp v1.4s, v0.8h", "saddlp v1.1d, v0.2s", "saddlp v1.2d, v0.4s" + +// For accumulate variants, load dest into v1 first (native insn accumulates into v1) +.macro make_pairwise_accl name, insn_b_8, insn_b_16, insn_h_4, insn_h_8, insn_s_2, insn_s_4 +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #16, #2 // size + ubfx x17, x8, #24, #1 // Q + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + ldr q0, [x15] // load source + ldr q1, [x14] // load dest into v1 (accumulate target) + cmp x12, #2 + b.eq .L\name\()_s + cmp x12, #1 + b.eq .L\name\()_h + cbz x17, .L\name\()_b8 + \insn_b_16 + str q1, [x14] + gret +.L\name\()_b8: + \insn_b_8 + str d1, [x14] + str xzr, [x14, #8] + gret +.L\name\()_h: + cbz x17, .L\name\()_h4 + \insn_h_8 + str q1, [x14] + gret +.L\name\()_h4: + \insn_h_4 + str d1, [x14] + str xzr, [x14, #8] + gret +.L\name\()_s: + cbz x17, .L\name\()_s2 + \insn_s_4 + str q1, [x14] + gret +.L\name\()_s2: + \insn_s_2 + str d1, [x14] + str xzr, [x14, #8] + gret +.endm + +make_pairwise_accl uadalp, "uadalp v1.4h, v0.8b", "uadalp v1.8h, v0.16b", "uadalp v1.2s, v0.4h", "uadalp v1.4s, v0.8h", "uadalp v1.1d, v0.2s", "uadalp v1.2d, v0.4s" +make_pairwise_accl sadalp, "sadalp v1.4h, v0.8b", "sadalp v1.8h, v0.16b", "sadalp v1.2s, v0.4h", "sadalp v1.4s, v0.8h", "sadalp v1.1d, v0.2s", "sadalp v1.2d, v0.4s" + +make_narrow_vec sqxtun, "sqxtun v1.8b, v0.8h", "sqxtun2 v1.16b, v0.8h", "sqxtun v1.4h, v0.4s", "sqxtun2 v1.8h, v0.4s", "sqxtun v1.2s, v0.2d", "sqxtun2 v1.4s, v0.2d" +make_narrow_vec sqxtn, "sqxtn v1.8b, v0.8h", "sqxtn2 v1.16b, v0.8h", "sqxtn v1.4h, v0.4s", "sqxtn2 v1.8h, v0.4s", "sqxtn v1.2s, v0.2d", "sqxtn2 v1.4s, v0.2d" +make_narrow_vec uqxtn, "uqxtn v1.8b, v0.8h", "uqxtn2 v1.16b, v0.8h", "uqxtn v1.4h, v0.4s", "uqxtn2 v1.8h, v0.4s", "uqxtn v1.2s, v0.2d", "uqxtn2 v1.4s, v0.2d" + +// Old make_cmpzero_vec cmgt/cmge/cmlt/cmle removed — replaced by make_int_vec_cmp_zero above + +/* + * Vector Logical Operations + * These operate on the entire 64-bit or 128-bit vector as a bitwise operation. + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * Note: size is ignored for logical ops (they work on the whole vector) + */ + +/* + * AND - Bitwise AND vector + */ +.gadget and_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + // Low 64 bits + ldr x20, [x15] + ldr x21, [x16] + and x22, x20, x21 + str x22, [x14] + + cbz x17, .Land_clear_high + + // High 64 bits if Q=1 + ldr x20, [x15, #8] + ldr x21, [x16, #8] + and x22, x20, x21 + str x22, [x14, #8] + gret + +.Land_clear_high: + str xzr, [x14, #8] + gret + +/* + * ORR - Bitwise OR vector + */ +.gadget orr_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + lsl x16, x11, #4 + add x16, x13, x16 + + ldr x20, [x15] + ldr x21, [x16] + orr x22, x20, x21 + str x22, [x14] + + cbz x17, .Lorr_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + orr x22, x20, x21 + str x22, [x14, #8] + gret + +.Lorr_clear_high: + str xzr, [x14, #8] + gret + +/* + * EOR - Bitwise exclusive OR vector + */ +.gadget eor_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + lsl x16, x11, #4 + add x16, x13, x16 + + ldr x20, [x15] + ldr x21, [x16] + eor x22, x20, x21 + str x22, [x14] + + cbz x17, .Leor_clear_high + + ldr x20, [x15, #8] + ldr x21, [x16, #8] + eor x22, x20, x21 + str x22, [x14, #8] + gret + +.Leor_clear_high: + str xzr, [x14, #8] + gret + +/* + * BSL - Bitwise select + * Vd = (Vn & Vd) | (Vm & ~Vd) + */ +.gadget bsl_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + lsl x16, x11, #4 + add x16, x13, x16 + + // Low 64 bits + ldr x20, [x14] // Vd (mask) + ldr x21, [x15] // Vn + ldr x22, [x16] // Vm + and x23, x21, x20 // Vn & Vd + mvn x24, x20 // ~Vd + and x24, x22, x24 // Vm & ~Vd + orr x23, x23, x24 + str x23, [x14] + + cbz x17, .Lbsl_clear_high + + // High 64 bits + ldr x20, [x14, #8] + ldr x21, [x15, #8] + ldr x22, [x16, #8] + and x23, x21, x20 + mvn x24, x20 + and x24, x22, x24 + orr x23, x23, x24 + str x23, [x14, #8] + gret + +.Lbsl_clear_high: + str xzr, [x14, #8] + gret + +/* + * BIT - Bitwise insert + * Vd = (Vn & Vm) | (Vd & ~Vm) + */ +.gadget bit_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + lsl x16, x11, #4 + add x16, x13, x16 + + // Low 64 bits + ldr x20, [x14] // Vd + ldr x21, [x15] // Vn + ldr x22, [x16] // Vm (mask) + and x23, x21, x22 // Vn & Vm + mvn x24, x22 // ~Vm + and x24, x20, x24 // Vd & ~Vm + orr x23, x23, x24 + str x23, [x14] + + cbz x17, .Lbit_clear_high + + // High 64 bits + ldr x20, [x14, #8] + ldr x21, [x15, #8] + ldr x22, [x16, #8] + and x23, x21, x22 + mvn x24, x22 + and x24, x20, x24 + orr x23, x23, x24 + str x23, [x14, #8] + gret + +.Lbit_clear_high: + str xzr, [x14, #8] + gret + +/* + * BIF - Bitwise insert if false + * Vd = (Vn & ~Vm) | (Vd & Vm) + */ +.gadget bif_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + lsl x16, x11, #4 + add x16, x13, x16 + + // Low 64 bits + ldr x20, [x14] // Vd + ldr x21, [x15] // Vn + ldr x22, [x16] // Vm (mask) + mvn x24, x22 // ~Vm + and x23, x21, x24 // Vn & ~Vm + and x24, x20, x22 // Vd & Vm + orr x23, x23, x24 + str x23, [x14] + + cbz x17, .Lbif_clear_high + + // High 64 bits + ldr x20, [x14, #8] + ldr x21, [x15, #8] + ldr x22, [x16, #8] + mvn x24, x22 + and x23, x21, x24 + and x24, x20, x22 + orr x23, x23, x24 + str x23, [x14, #8] + gret + +.Lbif_clear_high: + str xzr, [x14, #8] + gret + +/* + * BIC - Bit clear (Vn AND NOT Vm) + */ +.gadget bic_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + lsl x16, x11, #4 + add x16, x13, x16 + + ldr x0, [x15] + ldr x3, [x16] + bic x19, x0, x3 // x19 = x0 AND NOT x3 (NOT x2 — x2 is _tlb!) + str x19, [x14] + + cbz x17, .Lbic_clear_high + + ldr x0, [x15, #8] + ldr x3, [x16, #8] + bic x19, x0, x3 + str x19, [x14, #8] + gret + +.Lbic_clear_high: + str xzr, [x14, #8] + gret + +// ORN - Bitwise OR NOT (Vd = Vn OR NOT Vm) +.gadget orn_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + lsl x16, x11, #4 + add x16, x13, x16 + + ldr x0, [x15] + ldr x3, [x16] + orn x4, x0, x3 // x4 = x0 OR NOT x3 + str x4, [x14] + + cbz x17, .Lorn_clear_high + + ldr x0, [x15, #8] + ldr x3, [x16, #8] + orn x4, x0, x3 + str x4, [x14, #8] + gret + +.Lorn_clear_high: + str xzr, [x14, #8] + gret + +// SABA/UABA - Signed/Unsigned absolute difference accumulate +// Vd = Vd + |Vn - Vm| (accumulate into Vd, so must read Vd first) +.macro make_vec_aba name, insn +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] // Vn + ldr q1, [x16] // Vm + ldr q2, [x14] // Vd (accumulator) + + cmp x12, #0 + b.eq .L\name\()_size_b + cmp x12, #1 + b.eq .L\name\()_size_h + // size == 2: 32-bit (no 64-bit for saba/uaba) + cbz x17, .L\name\()_s_q0 + \insn v2.4s, v0.4s, v1.4s + b .L\name\()_store_q +.L\name\()_s_q0: + \insn v2.2s, v0.2s, v1.2s + b .L\name\()_store_low + +.L\name\()_size_b: + cbz x17, .L\name\()_b_q0 + \insn v2.16b, v0.16b, v1.16b + b .L\name\()_store_q +.L\name\()_b_q0: + \insn v2.8b, v0.8b, v1.8b + b .L\name\()_store_low + +.L\name\()_size_h: + cbz x17, .L\name\()_h_q0 + \insn v2.8h, v0.8h, v1.8h + b .L\name\()_store_q +.L\name\()_h_q0: + \insn v2.4h, v0.4h, v1.4h + b .L\name\()_store_low + +.L\name\()_store_q: + str q2, [x14] + gret +.L\name\()_store_low: + str d2, [x14] + str xzr, [x14, #8] + gret +.endm + +make_vec_aba saba, saba +make_vec_aba uaba, uaba + +/* + * EXT - Extract from pair of vectors + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | imm4<<24 | Q<<28] + * + * Conceptually concatenates Vm:Vn (Vm is high, Vn is low) and extracts + * a vector starting at byte position imm4. + * + * For Q=1 (128-bit): result[i] = concat[imm4+i] for i=0..15 + * For Q=0 (64-bit): result[i] = concat[imm4+i] for i=0..7, imm4 must be 0-7 + */ +.gadget ext_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #4 // imm4 (byte index) + ubfx x17, x8, #28, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + // Load Vn and Vm + ldr q0, [x15] // Vn (low part of concatenation) + ldr q1, [x16] // Vm (high part of concatenation) + + // Branch on Q: 8B and 16B use different native EXT arrangements + cbnz x17, .Lext_16b + + // Q=0 (8B): must use ext .8b to only consider lower 8 bytes of each reg + adr x3, .Lext_table_8b + add x3, x3, x12, lsl #3 // each case is 8 bytes (2 instructions) + br x3 + + .align 3 +.Lext_table_8b: + ext v2.8b, v0.8b, v1.8b, #0 + b .Lext_store_8b + ext v2.8b, v0.8b, v1.8b, #1 + b .Lext_store_8b + ext v2.8b, v0.8b, v1.8b, #2 + b .Lext_store_8b + ext v2.8b, v0.8b, v1.8b, #3 + b .Lext_store_8b + ext v2.8b, v0.8b, v1.8b, #4 + b .Lext_store_8b + ext v2.8b, v0.8b, v1.8b, #5 + b .Lext_store_8b + ext v2.8b, v0.8b, v1.8b, #6 + b .Lext_store_8b + ext v2.8b, v0.8b, v1.8b, #7 + b .Lext_store_8b + +.Lext_store_8b: + str d2, [x14] + str xzr, [x14, #8] + gret + +.Lext_16b: + // Q=1 (16B): use ext .16b + adr x3, .Lext_table_16b + add x3, x3, x12, lsl #3 // each case is 8 bytes (2 instructions) + br x3 + + .align 3 +.Lext_table_16b: + ext v2.16b, v0.16b, v1.16b, #0 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #1 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #2 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #3 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #4 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #5 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #6 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #7 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #8 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #9 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #10 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #11 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #12 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #13 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #14 + b .Lext_store_16b + ext v2.16b, v0.16b, v1.16b, #15 + b .Lext_store_16b + +.Lext_store_16b: + str q2, [x14] + gret + +/* + * SHL (vector, immediate) - shift left immediate + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24 | Q<<28] + * + * Each element is shifted left by the immediate value. + */ +.gadget shl_imm_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #8 // shift amount + ubfx x12, x8, #24, #4 // esize (0=8, 1=16, 2=32, 3=64) + ubfx x17, x8, #28, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + // Load source + ldr q0, [x15] + + // Dispatch based on element size + cmp x12, #3 + b.eq .Lshl_imm_64 + cmp x12, #2 + b.eq .Lshl_imm_32 + cmp x12, #1 + b.eq .Lshl_imm_16 + b .Lshl_imm_8 + +.Lshl_imm_8: + // Use a jump table for 8-bit SHL (0-7 shift values) + adr x3, .Lshl8_table + and x19, x11, #7 // shift & 7 + add x3, x3, x19, lsl #3 + br x3 + .align 3 +.Lshl8_table: + shl v0.16b, v0.16b, #0 + b .Lshl_store + shl v0.16b, v0.16b, #1 + b .Lshl_store + shl v0.16b, v0.16b, #2 + b .Lshl_store + shl v0.16b, v0.16b, #3 + b .Lshl_store + shl v0.16b, v0.16b, #4 + b .Lshl_store + shl v0.16b, v0.16b, #5 + b .Lshl_store + shl v0.16b, v0.16b, #6 + b .Lshl_store + shl v0.16b, v0.16b, #7 + b .Lshl_store + +.Lshl_imm_16: + adr x3, .Lshl16_table + and x19, x11, #15 + add x3, x3, x19, lsl #3 + br x3 + .align 3 +.Lshl16_table: + shl v0.8h, v0.8h, #0 + b .Lshl_store + shl v0.8h, v0.8h, #1 + b .Lshl_store + shl v0.8h, v0.8h, #2 + b .Lshl_store + shl v0.8h, v0.8h, #3 + b .Lshl_store + shl v0.8h, v0.8h, #4 + b .Lshl_store + shl v0.8h, v0.8h, #5 + b .Lshl_store + shl v0.8h, v0.8h, #6 + b .Lshl_store + shl v0.8h, v0.8h, #7 + b .Lshl_store + shl v0.8h, v0.8h, #8 + b .Lshl_store + shl v0.8h, v0.8h, #9 + b .Lshl_store + shl v0.8h, v0.8h, #10 + b .Lshl_store + shl v0.8h, v0.8h, #11 + b .Lshl_store + shl v0.8h, v0.8h, #12 + b .Lshl_store + shl v0.8h, v0.8h, #13 + b .Lshl_store + shl v0.8h, v0.8h, #14 + b .Lshl_store + shl v0.8h, v0.8h, #15 + b .Lshl_store + +.Lshl_imm_32: + // For 32-bit elements, use C helper due to many shift values + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + mov x19, x14 // save rd ptr + mov x20, x11 // save shift + mov x21, x17 // save Q + + save_c + mov x0, x14 // rd_ptr + mov x1, x15 // rn_ptr + mov w2, w20 // shift + mov w3, #2 // esize (32-bit) + mov w4, w21 // Q + bl NAME(shl_imm_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + gret + +.Lshl_imm_64: + // For 64-bit elements, use C helper + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + mov x19, x14 + mov x20, x11 + mov x21, x17 + + save_c + mov x0, x14 + mov x1, x15 + mov w2, w20 + mov w3, #3 // esize (64-bit) + mov w4, w21 + bl NAME(shl_imm_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + gret + +.Lshl_store: + cbnz x17, .Lshl_store_16b + str d0, [x14] + str xzr, [x14, #8] + gret +.Lshl_store_16b: + str q0, [x14] + gret + +/* + * USHR (vector, immediate) - unsigned shift right immediate + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24 | Q<<28] + */ +.gadget ushr_imm_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #8 + ubfx x12, x8, #24, #4 + ubfx x17, x8, #28, #1 + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + + // Use C helper for all sizes + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + mov x19, x14 + mov x20, x11 + mov x21, x12 + mov x22, x17 + + save_c + mov x0, x14 // rd_ptr + mov x1, x15 // rn_ptr + mov w2, w20 // shift + mov w3, w21 // esize + mov w4, w22 // Q + bl NAME(ushr_imm_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + gret + +/* + * SSHR (vector, immediate) - signed shift right immediate + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24 | Q<<28] + */ +.gadget sshr_imm_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #8 + ubfx x12, x8, #24, #4 + ubfx x17, x8, #28, #1 + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + + // Use C helper + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + mov x19, x14 + mov x20, x11 + mov x21, x12 + mov x22, x17 + + save_c + mov x0, x14 + mov x1, x15 + mov w2, w20 + mov w3, w21 + mov w4, w22 + bl NAME(sshr_imm_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + gret + +/* + * SRSHR/URSHR/SRSRA/URSRA (vector, immediate) - Rounding shift right (and accumulate) + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24 | Q<<28] + * Uses native NEON srshl/urshl with negative shift vector for efficiency. + * + * srshl/urshl Vd, Vn, Vm does: Vd[i] = round_shift(Vn[i], Vm[i]) + * where positive Vm = left shift, negative Vm = right shift with rounding + */ +.macro make_rounding_shift name, insn_b_8, insn_b_16, insn_h_4, insn_h_8, insn_s_2, insn_s_4, insn_d_2, accumulate=0 +.gadget \name\()_imm_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #8 // shift amount + ubfx x12, x8, #24, #4 // esize + ubfx x17, x8, #28, #1 // Q + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + ldr q0, [x15] // load source +.if \accumulate + ldr q2, [x14] // load existing dest for accumulate +.endif + // Create shift vector with -shift replicated to all elements + neg x11, x11 + dup v1.16b, w11 // replicate -shift as bytes (works for all sizes since + // srshl/urshl reads shift per element as signed byte-sized) + cmp x12, #3 + b.eq .L\name\()_64 + cmp x12, #2 + b.eq .L\name\()_32 + cmp x12, #1 + b.eq .L\name\()_16 + // size=0 (bytes): shift vector is already correct + cbz x17, .L\name\()_8b + \insn_b_16 + b .L\name\()_store +.L\name\()_8b: + \insn_b_8 + b .L\name\()_store_lo +.L\name\()_16: + // For 16-bit elements, need shift replicated per 16-bit lane + dup v1.8h, w11 + cbz x17, .L\name\()_4h + \insn_h_8 + b .L\name\()_store +.L\name\()_4h: + \insn_h_4 + b .L\name\()_store_lo +.L\name\()_32: + dup v1.4s, w11 + cbz x17, .L\name\()_2s + \insn_s_4 + b .L\name\()_store +.L\name\()_2s: + \insn_s_2 + b .L\name\()_store_lo +.L\name\()_64: + dup v1.2d, x11 + \insn_d_2 +.L\name\()_store: +.if \accumulate + // For accumulate variants, we computed shifted result in v3, now add to dest + // The caller macros put result in v3 for accumulate, v3 for non-accumulate + add_placeholder_\name: +.endif + str q3, [x14] + gret +.L\name\()_store_lo: +.if \accumulate + add_placeholder2_\name: +.endif + str d3, [x14] + str xzr, [x14, #8] + gret +.endm + +// SRSHR: Signed Rounding Shift Right +// srshl does signed rounding shift by variable amount (negative = right) +make_rounding_shift srshr, "srshl v3.8b, v0.8b, v1.8b", "srshl v3.16b, v0.16b, v1.16b", "srshl v3.4h, v0.4h, v1.4h", "srshl v3.8h, v0.8h, v1.8h", "srshl v3.2s, v0.2s, v1.2s", "srshl v3.4s, v0.4s, v1.4s", "srshl v3.2d, v0.2d, v1.2d" + +// URSHR: Unsigned Rounding Shift Right +make_rounding_shift urshr, "urshl v3.8b, v0.8b, v1.8b", "urshl v3.16b, v0.16b, v1.16b", "urshl v3.4h, v0.4h, v1.4h", "urshl v3.8h, v0.8h, v1.8h", "urshl v3.2s, v0.2s, v1.2s", "urshl v3.4s, v0.4s, v1.4s", "urshl v3.2d, v0.2d, v1.2d" + +/* + * SRSRA/URSRA (vector, immediate) - Rounding shift right and accumulate + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24 | Q<<28] + * rd = rd + rounding_shift_right(rn, shift) + */ +.macro make_rounding_sra name, shift_insn_b_8, shift_insn_b_16, shift_insn_h_4, shift_insn_h_8, shift_insn_s_2, shift_insn_s_4, shift_insn_d_2 +.gadget \name\()_imm_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #8 // shift amount + ubfx x12, x8, #24, #4 // esize + ubfx x17, x8, #28, #1 // Q + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + ldr q0, [x15] // load source + ldr q2, [x14] // load existing dest for accumulate + neg x11, x11 + cmp x12, #3 + b.eq .L\name\()_64 + cmp x12, #2 + b.eq .L\name\()_32 + cmp x12, #1 + b.eq .L\name\()_16 + // size=0 (bytes) + dup v1.16b, w11 + cbz x17, .L\name\()_8b + \shift_insn_b_16 + add v3.16b, v3.16b, v2.16b + str q3, [x14] + gret +.L\name\()_8b: + \shift_insn_b_8 + add v3.8b, v3.8b, v2.8b + str d3, [x14] + str xzr, [x14, #8] + gret +.L\name\()_16: + dup v1.8h, w11 + cbz x17, .L\name\()_4h + \shift_insn_h_8 + add v3.8h, v3.8h, v2.8h + str q3, [x14] + gret +.L\name\()_4h: + \shift_insn_h_4 + add v3.4h, v3.4h, v2.4h + str d3, [x14] + str xzr, [x14, #8] + gret +.L\name\()_32: + dup v1.4s, w11 + cbz x17, .L\name\()_2s + \shift_insn_s_4 + add v3.4s, v3.4s, v2.4s + str q3, [x14] + gret +.L\name\()_2s: + \shift_insn_s_2 + add v3.2s, v3.2s, v2.2s + str d3, [x14] + str xzr, [x14, #8] + gret +.L\name\()_64: + dup v1.2d, x11 + \shift_insn_d_2 + add v3.2d, v3.2d, v2.2d + str q3, [x14] + gret +.endm + +make_rounding_sra srsra, "srshl v3.8b, v0.8b, v1.8b", "srshl v3.16b, v0.16b, v1.16b", "srshl v3.4h, v0.4h, v1.4h", "srshl v3.8h, v0.8h, v1.8h", "srshl v3.2s, v0.2s, v1.2s", "srshl v3.4s, v0.4s, v1.4s", "srshl v3.2d, v0.2d, v1.2d" +make_rounding_sra ursra, "urshl v3.8b, v0.8b, v1.8b", "urshl v3.16b, v0.16b, v1.16b", "urshl v3.4h, v0.4h, v1.4h", "urshl v3.8h, v0.8h, v1.8h", "urshl v3.2s, v0.2s, v1.2s", "urshl v3.4s, v0.4s, v1.4s", "urshl v3.2d, v0.2d, v1.2d" + +/* + * SHL (scalar, immediate) - Scalar shift left immediate + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24] + * + * For scalar, we only support 64-bit (D register) as that's what TLS uses. + * Result is stored in scalar register with upper bits cleared. + */ +.gadget shl_imm_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #8 // shift amount + // esize at bits 24:27, but we only support 64-bit + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Dd + lsl x15, x10, #4 + add x15, x13, x15 // &Dn + + // Load source value (64-bit) + ldr x16, [x15] + + // Shift left by variable amount + lsl x16, x16, x11 + + // Store result and clear upper bits + str x16, [x14] + str xzr, [x14, #8] + gret + +/* + * USHR (scalar, immediate) - Scalar unsigned shift right immediate + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24] + */ +.gadget ushr_imm_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #8 + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + + ldr x16, [x15] + lsr x16, x16, x11 + str x16, [x14] + str xzr, [x14, #8] + gret + +/* + * SSHR (scalar, immediate) - Scalar signed shift right immediate + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24] + */ +.gadget sshr_imm_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #8 + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + + ldr x16, [x15] + asr x16, x16, x11 // arithmetic (signed) shift right + str x16, [x14] + str xzr, [x14, #8] + gret + +/* + * USRA (vector, immediate) - Unsigned shift right and accumulate + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24 | Q<<28] + * rd = rd + (rn >> shift) (unsigned) + */ +.gadget usra_imm_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #8 + ubfx x12, x8, #24, #4 + ubfx x17, x8, #28, #1 + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + + // Use C helper + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + mov x19, x14 + mov x20, x11 + mov x21, x12 + mov x22, x17 + + save_c + mov x0, x14 // rd_ptr + mov x1, x15 // rn_ptr + mov w2, w20 // shift + mov w3, w21 // esize + mov w4, w22 // Q + bl NAME(usra_imm_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + gret + +/* + * SSRA (vector, immediate) - Signed shift right and accumulate + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24 | Q<<28] + * rd = rd + (rn >> shift) (signed) + */ +.gadget ssra_imm_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #8 + ubfx x12, x8, #24, #4 + ubfx x17, x8, #28, #1 + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + + // Use C helper + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + mov x19, x14 + mov x20, x11 + mov x21, x12 + mov x22, x17 + + save_c + mov x0, x14 + mov x1, x15 + mov w2, w20 + mov w3, w21 + mov w4, w22 + bl NAME(ssra_imm_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + gret + +/* + * USRA (scalar, immediate) - Unsigned shift right and accumulate (scalar D) + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24] + * rd = rd + (rn >> shift) + */ +.gadget usra_imm_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #8 + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Dd + lsl x15, x10, #4 + add x15, x13, x15 // &Dn + + ldr x16, [x14] // current Dd value + ldr x17, [x15] // Dn value + lsr x17, x17, x11 // unsigned shift right + add x16, x16, x17 // accumulate + str x16, [x14] + // Don't clear upper bits - accumulate preserves scalar nature + gret + +/* + * SSRA (scalar, immediate) - Signed shift right and accumulate (scalar D) + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24] + * rd = rd + (rn >> shift) (signed) + */ +.gadget ssra_imm_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #8 + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + + ldr x16, [x14] + ldr x17, [x15] + asr x17, x17, x11 // arithmetic (signed) shift right + add x16, x16, x17 + str x16, [x14] + gret + +/* + * ADD (scalar, 64-bit integer) - Add two 64-bit integers in SIMD registers + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ +.gadget add_scalar_i64 + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + + add x13, _cpu, #CPU_fp + add x15, x13, x10, lsl #4 // &Dn + add x16, x13, x11, lsl #4 // &Dm + ldr x17, [x15] // Dn + ldr x3, [x16] // Dm + add x17, x17, x3 + add x14, x13, x9, lsl #4 // &Dd + str x17, [x14] // store result + str xzr, [x14, #8] // clear upper 64 bits + gret + +/* + * SUB (scalar, 64-bit integer) - Subtract two 64-bit integers in SIMD registers + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ +.gadget sub_scalar_i64 + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + + add x13, _cpu, #CPU_fp + add x15, x13, x10, lsl #4 + add x16, x13, x11, lsl #4 + ldr x17, [x15] + ldr x3, [x16] + sub x17, x17, x3 + add x14, x13, x9, lsl #4 + str x17, [x14] + str xzr, [x14, #8] + gret + +/* + * USHL (scalar, 64-bit) - Unsigned shift left D = Dn << Dm (mod 64) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ +.gadget ushl_scalar_i64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x13, _cpu, #CPU_fp + add x15, x13, x10, lsl #4 + add x16, x13, x11, lsl #4 + ldr d0, [x15] + ldr d1, [x16] + ushl d0, d0, d1 + add x14, x13, x9, lsl #4 + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * SSHL (scalar, 64-bit) - Signed shift left D = Dn << Dm (mod 64) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ +.gadget sshl_scalar_i64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x13, _cpu, #CPU_fp + add x15, x13, x10, lsl #4 + add x16, x13, x11, lsl #4 + ldr d0, [x15] + ldr d1, [x16] + sshl d0, d0, d1 + add x14, x13, x9, lsl #4 + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * CMHI (scalar, 64-bit) - Compare higher unsigned + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ +.gadget cmhi_scalar_i64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x13, _cpu, #CPU_fp + add x15, x13, x10, lsl #4 + add x16, x13, x11, lsl #4 + ldr d0, [x15] + ldr d1, [x16] + cmhi d0, d0, d1 + add x14, x13, x9, lsl #4 + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * CMHS (scalar, 64-bit) - Compare higher or same unsigned + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ +.gadget cmhs_scalar_i64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x13, _cpu, #CPU_fp + add x15, x13, x10, lsl #4 + add x16, x13, x11, lsl #4 + ldr d0, [x15] + ldr d1, [x16] + cmhs d0, d0, d1 + add x14, x13, x9, lsl #4 + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * CMGT (scalar, 64-bit) - Compare greater than signed + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ +.gadget cmgt_scalar_i64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x13, _cpu, #CPU_fp + add x15, x13, x10, lsl #4 + add x16, x13, x11, lsl #4 + ldr d0, [x15] + ldr d1, [x16] + cmgt d0, d0, d1 + add x14, x13, x9, lsl #4 + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * CMGE (scalar, 64-bit) - Compare greater or equal signed + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ +.gadget cmge_scalar_i64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x13, _cpu, #CPU_fp + add x15, x13, x10, lsl #4 + add x16, x13, x11, lsl #4 + ldr d0, [x15] + ldr d1, [x16] + cmge d0, d0, d1 + add x14, x13, x9, lsl #4 + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * CMEQ (scalar, 64-bit) - Compare equal + * Code stream: [gadget addr][rd | rn<<8 | rm<<16] + */ +.gadget cmeq_scalar_i64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + add x13, _cpu, #CPU_fp + add x15, x13, x10, lsl #4 + add x16, x13, x11, lsl #4 + ldr d0, [x15] + ldr d1, [x16] + cmeq d0, d0, d1 + add x14, x13, x9, lsl #4 + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * SCVTF (scalar, fixed-point) - Signed integer to FP with fractional bits + * Code stream: [gadget addr][rd | rn<<8 | fbits<<16 | esize<<24] + * Converts signed int in Dn/Sn to FP in Dd/Sd, dividing by 2^fbits + */ +.gadget scvtf_fixpt_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #8 // fbits + ubfx x12, x8, #24, #4 // esize + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Dd/Sd + lsl x15, x10, #4 + add x15, x13, x15 // &Dn/Sn + + cmp x12, #3 + b.eq 1f + // 32-bit: SCVTF Sd, Sn, #fbits + ldr s0, [x15] + // We need to build the SCVTF instruction dynamically since fbits is variable + // Instead, convert integer to float then divide by 2^fbits + fmov w16, s0 + scvtf s0, w16 + // Now divide by 2^fbits: multiply by 2^(-fbits) + mov w17, #1 + lsl w17, w17, w11 + scvtf s1, w17 + fdiv s0, s0, s1 + str s0, [x14] + str wzr, [x14, #4] + str xzr, [x14, #8] + gret + +1: // 64-bit: SCVTF Dd, Dn, #fbits + ldr x16, [x15] + scvtf d0, x16 + // Divide by 2^fbits + mov x17, #1 + lsl x17, x17, x11 + ucvtf d1, x17 + fdiv d0, d0, d1 + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * UCVTF (scalar, fixed-point) - Unsigned integer to FP with fractional bits + * Code stream: [gadget addr][rd | rn<<8 | fbits<<16 | esize<<24] + */ +.gadget ucvtf_fixpt_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #8 + ubfx x12, x8, #24, #4 + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + + cmp x12, #3 + b.eq 1f + // 32-bit + ldr w16, [x15] + ucvtf s0, w16 + mov w17, #1 + lsl w17, w17, w11 + scvtf s1, w17 + fdiv s0, s0, s1 + str s0, [x14] + str wzr, [x14, #4] + str xzr, [x14, #8] + gret + +1: // 64-bit + ldr x16, [x15] + ucvtf d0, x16 + mov x17, #1 + lsl x17, x17, x11 + ucvtf d1, x17 + fdiv d0, d0, d1 + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * FCVTZS (scalar, fixed-point) - FP to signed integer with fractional bits + * Code stream: [gadget addr][rd | rn<<8 | fbits<<16 | esize<<24] + * Multiplies FP value by 2^fbits, then converts to signed int (round toward zero) + */ +.gadget fcvtzs_fixpt_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #8 + ubfx x12, x8, #24, #4 + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + + cmp x12, #3 + b.eq 1f + // 32-bit + ldr s0, [x15] + mov w17, #1 + lsl w17, w17, w11 + scvtf s1, w17 + fmul s0, s0, s1 + fcvtzs w16, s0 + str w16, [x14] + str wzr, [x14, #4] + str xzr, [x14, #8] + gret + +1: // 64-bit + ldr d0, [x15] + mov x17, #1 + lsl x17, x17, x11 + ucvtf d1, x17 + fmul d0, d0, d1 + fcvtzs x16, d0 + str x16, [x14] + str xzr, [x14, #8] + gret + +/* + * FCVTZU (scalar, fixed-point) - FP to unsigned integer with fractional bits + * Code stream: [gadget addr][rd | rn<<8 | fbits<<16 | esize<<24] + */ +.gadget fcvtzu_fixpt_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #8 + ubfx x12, x8, #24, #4 + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + + cmp x12, #3 + b.eq 1f + // 32-bit + ldr s0, [x15] + mov w17, #1 + lsl w17, w17, w11 + scvtf s1, w17 + fmul s0, s0, s1 + fcvtzu w16, s0 + str w16, [x14] + str wzr, [x14, #4] + str xzr, [x14, #8] + gret + +1: // 64-bit + ldr d0, [x15] + mov x17, #1 + lsl x17, x17, x11 + ucvtf d1, x17 + fmul d0, d0, d1 + fcvtzu x16, d0 + str x16, [x14] + str xzr, [x14, #8] + gret + +/* + * SRI (vector, immediate) - Shift right and insert + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24 | Q<<28] + * For each element: rd = (rd & highmask) | (rn >> shift) + */ +.gadget sri_imm_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #8 + ubfx x12, x8, #24, #4 + ubfx x17, x8, #28, #1 + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + mov x19, x14 + mov x20, x11 + mov x21, x12 + mov x22, x17 + + save_c + mov x0, x14 // rd_ptr + mov x1, x15 // rn_ptr + mov w2, w20 // shift + mov w3, w21 // esize + mov w4, w22 // Q + bl NAME(sri_imm_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + gret + +/* + * SLI (vector, immediate) - Shift left and insert + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24 | Q<<28] + * For each element: rd = (rd & lowmask) | (rn << shift) + */ +.gadget sli_imm_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #8 + ubfx x12, x8, #24, #4 + ubfx x17, x8, #28, #1 + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + + stp x19, x20, [sp, #-0x60]! + stp x21, x22, [sp, #0x10] + stp x23, x24, [sp, #0x20] + stp x25, x26, [sp, #0x30] + stp x27, x28, [sp, #0x40] + str lr, [sp, #0x50] + + mov x19, x14 + mov x20, x11 + mov x21, x12 + mov x22, x17 + + save_c + mov x0, x14 // rd_ptr + mov x1, x15 // rn_ptr + mov w2, w20 // shift + mov w3, w21 // esize + mov w4, w22 // Q + bl NAME(sli_imm_helper) + restore_c + + ldr lr, [sp, #0x50] + ldp x27, x28, [sp, #0x40] + ldp x25, x26, [sp, #0x30] + ldp x23, x24, [sp, #0x20] + ldp x21, x22, [sp, #0x10] + ldp x19, x20, [sp], #0x60 + gret + +/* + * ADDP - Add pairwise + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * + * For each pair of adjacent elements, add them and place result in destination. + * Result[i] = Vn[2i] + Vn[2i+1] for first half + * Result[i] = Vm[2i] + Vm[2i+1] for second half + */ +.gadget addp_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + cmp x12, #3 + b.eq .Laddp_64 + cmp x12, #2 + b.eq .Laddp_32 + cmp x12, #1 + b.eq .Laddp_16 + b .Laddp_8 + +.Laddp_8: + cbnz x17, .Laddp_8_q1 + + // Q=0: 4 pairs from Vn low -> result[0..3], 4 pairs from Vm low -> result[4..7] + ldr x20, [x15] // Vn low + mov x22, #0 // result + + // Process pairs 0,1 and 2,3 from Vn low + ubfx x23, x20, #0, #8 // byte 0 + ubfx x24, x20, #8, #8 // byte 1 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23 // result[0] + + ubfx x23, x20, #16, #8 // byte 2 + ubfx x24, x20, #24, #8 // byte 3 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #8 // result[1] + + ubfx x23, x20, #32, #8 // byte 4 + ubfx x24, x20, #40, #8 // byte 5 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #16 // result[2] + + ubfx x23, x20, #48, #8 // byte 6 + ubfx x24, x20, #56, #8 // byte 7 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #24 // result[3] + + // Process pairs from Vm low + ldr x21, [x16] // Vm low + ubfx x23, x21, #0, #8 + ubfx x24, x21, #8, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #32 // result[4] + + ubfx x23, x21, #16, #8 + ubfx x24, x21, #24, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #40 // result[5] + + ubfx x23, x21, #32, #8 + ubfx x24, x21, #40, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #48 // result[6] + + ubfx x23, x21, #48, #8 + ubfx x24, x21, #56, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #56 // result[7] + + str x22, [x14] + b .Laddp_clear_high + +.Laddp_8_q1: + // Q=1: 8 pairs from Vn (low+high) -> result[0..7] + // Pre-load Vm before writing Vd (handles Vd==Vm aliasing, e.g. vpaddq(x,x)) + ldr x3, [x16] // Vm low (pre-loaded before Vd write) + ldr x4, [x16, #8] // Vm high (pre-loaded before Vd write) + ldr x20, [x15] // Vn low + ldr x21, [x15, #8] // Vn high + mov x22, #0 + + ubfx x23, x20, #0, #8 + ubfx x24, x20, #8, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23 + + ubfx x23, x20, #16, #8 + ubfx x24, x20, #24, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #8 + + ubfx x23, x20, #32, #8 + ubfx x24, x20, #40, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #16 + + ubfx x23, x20, #48, #8 + ubfx x24, x20, #56, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #24 + + ubfx x23, x21, #0, #8 + ubfx x24, x21, #8, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #16, #8 + ubfx x24, x21, #24, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #40 + + ubfx x23, x21, #32, #8 + ubfx x24, x21, #40, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #48 + + ubfx x23, x21, #48, #8 + ubfx x24, x21, #56, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #56 + + str x22, [x14] + + // Q=1: 8 pairs from Vm (low+high) -> result[8..15] + // Use pre-loaded Vm values (x3/x4) instead of re-reading from [x16] + mov x20, x3 // Vm low (from pre-load) + mov x21, x4 // Vm high (from pre-load) + mov x22, #0 + + ubfx x23, x20, #0, #8 + ubfx x24, x20, #8, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23 + + ubfx x23, x20, #16, #8 + ubfx x24, x20, #24, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #8 + + ubfx x23, x20, #32, #8 + ubfx x24, x20, #40, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #16 + + ubfx x23, x20, #48, #8 + ubfx x24, x20, #56, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #24 + + ubfx x23, x21, #0, #8 + ubfx x24, x21, #8, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #16, #8 + ubfx x24, x21, #24, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #40 + + ubfx x23, x21, #32, #8 + ubfx x24, x21, #40, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #48 + + ubfx x23, x21, #48, #8 + ubfx x24, x21, #56, #8 + add x23, x23, x24 + and x23, x23, #0xff + orr x22, x22, x23, lsl #56 + + str x22, [x14, #8] + gret + +.Laddp_16: + cbnz x17, .Laddp_16_q1 + + // Q=0: 2 pairs from Vn low -> result[0..1], 2 pairs from Vm low -> result[2..3] + ldr x20, [x15] + ldr x21, [x16] + mov x22, #0 + + // Pairs from Vn + ubfx x23, x20, #0, #16 + ubfx x24, x20, #16, #16 + add x23, x23, x24 + and x23, x23, #0xffff + orr x22, x22, x23 + + ubfx x23, x20, #32, #16 + ubfx x24, x20, #48, #16 + add x23, x23, x24 + and x23, x23, #0xffff + orr x22, x22, x23, lsl #16 + + // Pairs from Vm + ubfx x23, x21, #0, #16 + ubfx x24, x21, #16, #16 + add x23, x23, x24 + and x23, x23, #0xffff + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #32, #16 + ubfx x24, x21, #48, #16 + add x23, x23, x24 + and x23, x23, #0xffff + orr x22, x22, x23, lsl #48 + + str x22, [x14] + b .Laddp_clear_high + +.Laddp_16_q1: + // Q=1: 4 pairs from Vn (low+high) -> result[0..3] + // Pre-load Vm before writing Vd (handles Vd==Vm aliasing) + ldr x3, [x16] // Vm low (pre-loaded) + ldr x4, [x16, #8] // Vm high (pre-loaded) + ldr x20, [x15] + ldr x21, [x15, #8] + mov x22, #0 + + ubfx x23, x20, #0, #16 + ubfx x24, x20, #16, #16 + add x23, x23, x24 + and x23, x23, #0xffff + orr x22, x22, x23 + + ubfx x23, x20, #32, #16 + ubfx x24, x20, #48, #16 + add x23, x23, x24 + and x23, x23, #0xffff + orr x22, x22, x23, lsl #16 + + ubfx x23, x21, #0, #16 + ubfx x24, x21, #16, #16 + add x23, x23, x24 + and x23, x23, #0xffff + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #32, #16 + ubfx x24, x21, #48, #16 + add x23, x23, x24 + and x23, x23, #0xffff + orr x22, x22, x23, lsl #48 + + str x22, [x14] + + // Q=1: 4 pairs from Vm (low+high) -> result[4..7] + mov x20, x3 // Vm low (from pre-load) + mov x21, x4 // Vm high (from pre-load) + mov x22, #0 + + ubfx x23, x20, #0, #16 + ubfx x24, x20, #16, #16 + add x23, x23, x24 + and x23, x23, #0xffff + orr x22, x22, x23 + + ubfx x23, x20, #32, #16 + ubfx x24, x20, #48, #16 + add x23, x23, x24 + and x23, x23, #0xffff + orr x22, x22, x23, lsl #16 + + ubfx x23, x21, #0, #16 + ubfx x24, x21, #16, #16 + add x23, x23, x24 + and x23, x23, #0xffff + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #32, #16 + ubfx x24, x21, #48, #16 + add x23, x23, x24 + and x23, x23, #0xffff + orr x22, x22, x23, lsl #48 + + str x22, [x14, #8] + gret + +.Laddp_32: + cbnz x17, .Laddp_32_q1 + + // Q=0: Vn low pair -> result[0], Vm low pair -> result[1] + ldr x20, [x15] + ldr x21, [x16] + + // Pair 0,1 from Vn -> result[0] + and x23, x20, #0xffffffff + lsr x24, x20, #32 + add x23, x23, x24 + and x22, x23, #0xffffffff + + // Pair 0,1 from Vm -> result[1] + and x23, x21, #0xffffffff + lsr x24, x21, #32 + add x23, x23, x24 + and x23, x23, #0xffffffff + orr x22, x22, x23, lsl #32 + + str x22, [x14] + b .Laddp_clear_high + +.Laddp_32_q1: + // Q=1: Vn low pair -> result[0], Vn high pair -> result[1] + // Pre-load Vm before writing Vd (handles Vd==Vm aliasing) + ldr x3, [x16] // Vm low (pre-loaded) + ldr x4, [x16, #8] // Vm high (pre-loaded) + ldr x20, [x15] + ldr x21, [x15, #8] + + and x23, x20, #0xffffffff + lsr x24, x20, #32 + add x23, x23, x24 + and x22, x23, #0xffffffff + + and x23, x21, #0xffffffff + lsr x24, x21, #32 + add x23, x23, x24 + and x23, x23, #0xffffffff + orr x22, x22, x23, lsl #32 + + str x22, [x14] + + // Q=1: Vm low pair -> result[2], Vm high pair -> result[3] + mov x20, x3 // Vm low (from pre-load) + mov x21, x4 // Vm high (from pre-load) + + and x23, x20, #0xffffffff + lsr x24, x20, #32 + add x23, x23, x24 + and x22, x23, #0xffffffff + + and x23, x21, #0xffffffff + lsr x24, x21, #32 + add x23, x23, x24 + and x23, x23, #0xffffffff + orr x22, x22, x23, lsl #32 + + str x22, [x14, #8] + gret + +.Laddp_64: + // 64-bit elements - only valid for Q=1 (128-bit vectors) + // Pre-load Vm before writing Vd (handles Vd==Vm aliasing) + ldr x3, [x16] // Vm[0] (pre-loaded) + ldr x4, [x16, #8] // Vm[1] (pre-loaded) + ldr x20, [x15] // Vn[0] + ldr x23, [x15, #8] // Vn[1] + add x22, x20, x23 // result[0] = Vn[0] + Vn[1] + str x22, [x14] + + mov x20, x3 // Vm[0] (from pre-load) + mov x23, x4 // Vm[1] (from pre-load) + add x22, x20, x23 // result[1] = Vm[0] + Vm[1] + str x22, [x14, #8] + gret + +.Laddp_clear_high: + str xzr, [x14, #8] + gret + +/* + * UMAXP - Unsigned Maximum Pairwise (vector) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * + * Result[i] = MAX(A[2i], A[2i+1]) where A is concatenation of Vn and Vm + */ +.gadget umaxp_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + cmp x12, #3 + b.eq .Lumaxp_64 + cmp x12, #2 + b.eq .Lumaxp_32 + cmp x12, #1 + b.eq .Lumaxp_16 + b .Lumaxp_8 + +.Lumaxp_8: + cbnz x17, .Lumaxp_8_q1 + + // Q=0: 4 pairs from Vn low -> result[0..3], 4 pairs from Vm low -> result[4..7] + ldr x20, [x15] // Vn low + mov x22, #0 // result + + ubfx x23, x20, #0, #8 + ubfx x24, x20, #8, #8 + cmp x23, x24 + csel x23, x23, x24, hs // max(x23, x24) + orr x22, x22, x23 + + ubfx x23, x20, #16, #8 + ubfx x24, x20, #24, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #8 + + ubfx x23, x20, #32, #8 + ubfx x24, x20, #40, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #16 + + ubfx x23, x20, #48, #8 + ubfx x24, x20, #56, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #24 + + // Process pairs from Vm low: result[4..7] + ldr x21, [x16] // Vm low + ubfx x23, x21, #0, #8 + ubfx x24, x21, #8, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #16, #8 + ubfx x24, x21, #24, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #40 + + ubfx x23, x21, #32, #8 + ubfx x24, x21, #40, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #48 + + ubfx x23, x21, #48, #8 + ubfx x24, x21, #56, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #56 + + str x22, [x14] + b .Lumaxp_clear_high + +.Lumaxp_8_q1: + // Q=1: 8 pairs from Vn (low+high) -> result[0..7] + // Pre-load Vm before writing Vd (handles Vd==Vm aliasing) + ldr x3, [x16] // Vm low (pre-loaded) + ldr x4, [x16, #8] // Vm high (pre-loaded) + ldr x20, [x15] // Vn low + ldr x21, [x15, #8] // Vn high + mov x22, #0 + + ubfx x23, x20, #0, #8 + ubfx x24, x20, #8, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23 + + ubfx x23, x20, #16, #8 + ubfx x24, x20, #24, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #8 + + ubfx x23, x20, #32, #8 + ubfx x24, x20, #40, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #16 + + ubfx x23, x20, #48, #8 + ubfx x24, x20, #56, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #24 + + ubfx x23, x21, #0, #8 + ubfx x24, x21, #8, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #16, #8 + ubfx x24, x21, #24, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #40 + + ubfx x23, x21, #32, #8 + ubfx x24, x21, #40, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #48 + + ubfx x23, x21, #48, #8 + ubfx x24, x21, #56, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #56 + + str x22, [x14] + + // Q=1: 8 pairs from Vm (low+high) -> result[8..15] + // Use pre-loaded Vm values (x3/x4) instead of re-reading from [x16] + mov x20, x3 // Vm low (from pre-load) + mov x21, x4 // Vm high (from pre-load) + mov x22, #0 + + ubfx x23, x20, #0, #8 + ubfx x24, x20, #8, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23 + + ubfx x23, x20, #16, #8 + ubfx x24, x20, #24, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #8 + + ubfx x23, x20, #32, #8 + ubfx x24, x20, #40, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #16 + + ubfx x23, x20, #48, #8 + ubfx x24, x20, #56, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #24 + + ubfx x23, x21, #0, #8 + ubfx x24, x21, #8, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #16, #8 + ubfx x24, x21, #24, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #40 + + ubfx x23, x21, #32, #8 + ubfx x24, x21, #40, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #48 + + ubfx x23, x21, #48, #8 + ubfx x24, x21, #56, #8 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #56 + + str x22, [x14, #8] + gret + +.Lumaxp_16: + cbnz x17, .Lumaxp_16_q1 + + // Q=0: 2 pairs from Vn low -> result[0..1], 2 pairs from Vm low -> result[2..3] + ldr x20, [x15] + ldr x21, [x16] + mov x22, #0 + + ubfx x23, x20, #0, #16 + ubfx x24, x20, #16, #16 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23 + + ubfx x23, x20, #32, #16 + ubfx x24, x20, #48, #16 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #16 + + ubfx x23, x21, #0, #16 + ubfx x24, x21, #16, #16 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #32, #16 + ubfx x24, x21, #48, #16 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #48 + + str x22, [x14] + b .Lumaxp_clear_high + +.Lumaxp_16_q1: + // Q=1: 4 pairs from Vn (low+high) -> result[0..3] + // Pre-load Vm before writing Vd (handles Vd==Vm aliasing) + ldr x3, [x16] // Vm low (pre-loaded) + ldr x4, [x16, #8] // Vm high (pre-loaded) + ldr x20, [x15] + ldr x21, [x15, #8] + mov x22, #0 + + ubfx x23, x20, #0, #16 + ubfx x24, x20, #16, #16 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23 + + ubfx x23, x20, #32, #16 + ubfx x24, x20, #48, #16 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #16 + + ubfx x23, x21, #0, #16 + ubfx x24, x21, #16, #16 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #32, #16 + ubfx x24, x21, #48, #16 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #48 + + str x22, [x14] + + // Q=1: 4 pairs from Vm (low+high) -> result[4..7] + // Use pre-loaded Vm values (x3/x4) instead of re-reading from [x16] + mov x20, x3 // Vm low (from pre-load) + mov x21, x4 // Vm high (from pre-load) + mov x22, #0 + + ubfx x23, x20, #0, #16 + ubfx x24, x20, #16, #16 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23 + + ubfx x23, x20, #32, #16 + ubfx x24, x20, #48, #16 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #16 + + ubfx x23, x21, #0, #16 + ubfx x24, x21, #16, #16 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #32, #16 + ubfx x24, x21, #48, #16 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #48 + + str x22, [x14, #8] + gret + +.Lumaxp_32: + cbnz x17, .Lumaxp_32_q1 + + // Q=0: Vn low pair -> result[0], Vm low pair -> result[1] + ldr x20, [x15] + ldr x21, [x16] + + and x23, x20, #0xffffffff + lsr x24, x20, #32 + cmp x23, x24 + csel x22, x23, x24, hs + + and x23, x21, #0xffffffff + lsr x24, x21, #32 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #32 + + str x22, [x14] + b .Lumaxp_clear_high + +.Lumaxp_32_q1: + // Q=1: Vn low pair -> result[0], Vn high pair -> result[1] + // Pre-load Vm before writing Vd (handles Vd==Vm aliasing) + ldr x3, [x16] // Vm low (pre-loaded) + ldr x4, [x16, #8] // Vm high (pre-loaded) + ldr x20, [x15] + ldr x21, [x15, #8] + + and x23, x20, #0xffffffff + lsr x24, x20, #32 + cmp x23, x24 + csel x22, x23, x24, hs + + and x23, x21, #0xffffffff + lsr x24, x21, #32 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #32 + + str x22, [x14] + + // Q=1: Vm low pair -> result[2], Vm high pair -> result[3] + // Use pre-loaded Vm values (x3/x4) instead of re-reading from [x16] + mov x20, x3 // Vm low (from pre-load) + mov x21, x4 // Vm high (from pre-load) + + and x23, x20, #0xffffffff + lsr x24, x20, #32 + cmp x23, x24 + csel x22, x23, x24, hs + + and x23, x21, #0xffffffff + lsr x24, x21, #32 + cmp x23, x24 + csel x23, x23, x24, hs + orr x22, x22, x23, lsl #32 + + str x22, [x14, #8] + gret + +.Lumaxp_64: + // 64-bit elements (only valid for Q=1) + // Pre-load Vm before writing Vd (handles Vd==Vm aliasing) + ldr x3, [x16] // Vm[0] (pre-loaded) + ldr x4, [x16, #8] // Vm[1] (pre-loaded) + ldr x20, [x15] // Vn[0] + ldr x23, [x15, #8] // Vn[1] + cmp x20, x23 + csel x22, x20, x23, hs // result[0] = max(Vn[0], Vn[1]) + str x22, [x14] + + mov x20, x3 // Vm[0] (from pre-load) + mov x23, x4 // Vm[1] (from pre-load) + cmp x20, x23 + csel x22, x20, x23, hs // result[1] = max(Vm[0], Vm[1]) + str x22, [x14, #8] + gret + +.Lumaxp_clear_high: + str xzr, [x14, #8] + gret + +/* + * UMINP - Unsigned Minimum Pairwise (vector) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * + * Result[i] = MIN(A[2i], A[2i+1]) where A is concatenation of Vn and Vm + */ +.gadget uminp_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + cmp x12, #3 + b.eq .Luminp_64 + cmp x12, #2 + b.eq .Luminp_32 + cmp x12, #1 + b.eq .Luminp_16 + b .Luminp_8 + +.Luminp_8: + cbnz x17, .Luminp_8_q1 + + // Q=0: 4 pairs from Vn low -> result[0..3], 4 pairs from Vm low -> result[4..7] + ldr x20, [x15] // Vn low + mov x22, #0 // result + + ubfx x23, x20, #0, #8 + ubfx x24, x20, #8, #8 + cmp x23, x24 + csel x23, x23, x24, lo // min(x23, x24) + orr x22, x22, x23 + + ubfx x23, x20, #16, #8 + ubfx x24, x20, #24, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #8 + + ubfx x23, x20, #32, #8 + ubfx x24, x20, #40, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #16 + + ubfx x23, x20, #48, #8 + ubfx x24, x20, #56, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #24 + + // Process pairs from Vm low: result[4..7] + ldr x21, [x16] // Vm low + ubfx x23, x21, #0, #8 + ubfx x24, x21, #8, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #16, #8 + ubfx x24, x21, #24, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #40 + + ubfx x23, x21, #32, #8 + ubfx x24, x21, #40, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #48 + + ubfx x23, x21, #48, #8 + ubfx x24, x21, #56, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #56 + + str x22, [x14] + b .Luminp_clear_high + +.Luminp_8_q1: + // Q=1: 8 pairs from Vn (low+high) -> result[0..7] + // Pre-load Vm before writing Vd (handles Vd==Vm aliasing) + ldr x3, [x16] // Vm low (pre-loaded) + ldr x4, [x16, #8] // Vm high (pre-loaded) + ldr x20, [x15] // Vn low + ldr x21, [x15, #8] // Vn high + mov x22, #0 + + ubfx x23, x20, #0, #8 + ubfx x24, x20, #8, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23 + + ubfx x23, x20, #16, #8 + ubfx x24, x20, #24, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #8 + + ubfx x23, x20, #32, #8 + ubfx x24, x20, #40, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #16 + + ubfx x23, x20, #48, #8 + ubfx x24, x20, #56, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #24 + + ubfx x23, x21, #0, #8 + ubfx x24, x21, #8, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #16, #8 + ubfx x24, x21, #24, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #40 + + ubfx x23, x21, #32, #8 + ubfx x24, x21, #40, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #48 + + ubfx x23, x21, #48, #8 + ubfx x24, x21, #56, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #56 + + str x22, [x14] + + // Q=1: 8 pairs from Vm (low+high) -> result[8..15] + // Use pre-loaded Vm values (x3/x4) instead of re-reading from [x16] + mov x20, x3 // Vm low (from pre-load) + mov x21, x4 // Vm high (from pre-load) + mov x22, #0 + + ubfx x23, x20, #0, #8 + ubfx x24, x20, #8, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23 + + ubfx x23, x20, #16, #8 + ubfx x24, x20, #24, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #8 + + ubfx x23, x20, #32, #8 + ubfx x24, x20, #40, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #16 + + ubfx x23, x20, #48, #8 + ubfx x24, x20, #56, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #24 + + ubfx x23, x21, #0, #8 + ubfx x24, x21, #8, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #16, #8 + ubfx x24, x21, #24, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #40 + + ubfx x23, x21, #32, #8 + ubfx x24, x21, #40, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #48 + + ubfx x23, x21, #48, #8 + ubfx x24, x21, #56, #8 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #56 + + str x22, [x14, #8] + gret + +.Luminp_16: + cbnz x17, .Luminp_16_q1 + + // Q=0: 2 pairs from Vn low -> result[0..1], 2 pairs from Vm low -> result[2..3] + ldr x20, [x15] + ldr x21, [x16] + mov x22, #0 + + ubfx x23, x20, #0, #16 + ubfx x24, x20, #16, #16 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23 + + ubfx x23, x20, #32, #16 + ubfx x24, x20, #48, #16 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #16 + + ubfx x23, x21, #0, #16 + ubfx x24, x21, #16, #16 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #32, #16 + ubfx x24, x21, #48, #16 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #48 + + str x22, [x14] + b .Luminp_clear_high + +.Luminp_16_q1: + // Q=1: 4 pairs from Vn (low+high) -> result[0..3] + // Pre-load Vm before writing Vd (handles Vd==Vm aliasing) + ldr x3, [x16] // Vm low (pre-loaded) + ldr x4, [x16, #8] // Vm high (pre-loaded) + ldr x20, [x15] + ldr x21, [x15, #8] + mov x22, #0 + + ubfx x23, x20, #0, #16 + ubfx x24, x20, #16, #16 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23 + + ubfx x23, x20, #32, #16 + ubfx x24, x20, #48, #16 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #16 + + ubfx x23, x21, #0, #16 + ubfx x24, x21, #16, #16 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #32, #16 + ubfx x24, x21, #48, #16 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #48 + + str x22, [x14] + + // Q=1: 4 pairs from Vm (low+high) -> result[4..7] + // Use pre-loaded Vm values (x3/x4) instead of re-reading from [x16] + mov x20, x3 // Vm low (from pre-load) + mov x21, x4 // Vm high (from pre-load) + mov x22, #0 + + ubfx x23, x20, #0, #16 + ubfx x24, x20, #16, #16 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23 + + ubfx x23, x20, #32, #16 + ubfx x24, x20, #48, #16 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #16 + + ubfx x23, x21, #0, #16 + ubfx x24, x21, #16, #16 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #32 + + ubfx x23, x21, #32, #16 + ubfx x24, x21, #48, #16 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #48 + + str x22, [x14, #8] + gret + +.Luminp_32: + cbnz x17, .Luminp_32_q1 + + // Q=0: Vn low pair -> result[0], Vm low pair -> result[1] + ldr x20, [x15] + ldr x21, [x16] + + and x23, x20, #0xffffffff + lsr x24, x20, #32 + cmp x23, x24 + csel x22, x23, x24, lo + + and x23, x21, #0xffffffff + lsr x24, x21, #32 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #32 + + str x22, [x14] + b .Luminp_clear_high + +.Luminp_32_q1: + // Q=1: Vn low pair -> result[0], Vn high pair -> result[1] + // Pre-load Vm before writing Vd (handles Vd==Vm aliasing) + ldr x3, [x16] // Vm low (pre-loaded) + ldr x4, [x16, #8] // Vm high (pre-loaded) + ldr x20, [x15] + ldr x21, [x15, #8] + + and x23, x20, #0xffffffff + lsr x24, x20, #32 + cmp x23, x24 + csel x22, x23, x24, lo + + and x23, x21, #0xffffffff + lsr x24, x21, #32 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #32 + + str x22, [x14] + + // Q=1: Vm low pair -> result[2], Vm high pair -> result[3] + // Use pre-loaded Vm values (x3/x4) instead of re-reading from [x16] + mov x20, x3 // Vm low (from pre-load) + mov x21, x4 // Vm high (from pre-load) + + and x23, x20, #0xffffffff + lsr x24, x20, #32 + cmp x23, x24 + csel x22, x23, x24, lo + + and x23, x21, #0xffffffff + lsr x24, x21, #32 + cmp x23, x24 + csel x23, x23, x24, lo + orr x22, x22, x23, lsl #32 + + str x22, [x14, #8] + gret + +.Luminp_64: + // 64-bit elements (only valid for Q=1) + // Pre-load Vm before writing Vd (handles Vd==Vm aliasing) + ldr x3, [x16] // Vm[0] (pre-loaded) + ldr x4, [x16, #8] // Vm[1] (pre-loaded) + ldr x20, [x15] // Vn[0] + ldr x23, [x15, #8] // Vn[1] + cmp x20, x23 + csel x22, x20, x23, lo // result[0] = min(Vn[0], Vn[1]) + str x22, [x14] + + mov x20, x3 // Vm[0] (from pre-load) + mov x23, x4 // Vm[1] (from pre-load) + cmp x20, x23 + csel x22, x20, x23, lo // result[1] = min(Vm[0], Vm[1]) + str x22, [x14, #8] + gret + +.Luminp_clear_high: + str xzr, [x14, #8] + gret + +/* + * Floating-point / Integer Conversion (scalar) + * + * These convert between integer GPRs and floating-point registers. + * We store FP values in the cpu_state fp array. + * + * Code stream: [gadget addr][rd | rn<<8 | type<<16 | sf<<18] + * type: 00=single (32-bit), 01=double (64-bit) + * sf: 0=32-bit int (W reg), 1=64-bit int (X reg) + */ + +/* + * UCVTF - Unsigned integer to floating-point + * UCVTF Sd, Wn / UCVTF Dd, Xn + */ +.gadget ucvtf_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (fp reg) + ubfx x10, x8, #8, #5 // rn (gpr) + ubfx x11, x8, #16, #2 // type (0=single, 1=double) + ubfx x12, x8, #18, #1 // sf (0=32-bit, 1=64-bit) + + // Load integer value from GPR + add x13, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr x14, [x13, x10, lsl #3] + b 2f +1: mov x14, #0 // XZR +2: + // If sf=0, zero-extend to 32-bit + cbz x12, .Lucvtf_32bit_int + // 64-bit integer -> convert to float + b .Lucvtf_convert + +.Lucvtf_32bit_int: + and x14, x14, #0xffffffff + +.Lucvtf_convert: + // Convert unsigned integer to float + // We use the host's UCVTF instruction + ucvtf d0, x14 // convert to double first + + // Store result to FP register + add x15, _cpu, #CPU_fp + lsl x16, x9, #4 // each V reg is 16 bytes + add x15, x15, x16 + + cbz x11, .Lucvtf_single + // type=1: double + str d0, [x15] + str xzr, [x15, #8] // clear upper + gret + +.Lucvtf_single: + // type=0: single - convert double to single + fcvt s0, d0 + str s0, [x15] + str xzr, [x15, #4] // clear rest of 128-bit reg + str xzr, [x15, #8] + gret + +/* + * SCVTF - Signed integer to floating-point + */ +.gadget scvtf_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (fp reg) + ubfx x10, x8, #8, #5 // rn (gpr) + ubfx x11, x8, #16, #2 // type + ubfx x12, x8, #18, #1 // sf + + add x13, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr x14, [x13, x10, lsl #3] + b 2f +1: mov x14, #0 +2: + cbz x12, .Lscvtf_32bit_int + b .Lscvtf_convert + +.Lscvtf_32bit_int: + // Sign-extend 32-bit to 64-bit + sxtw x14, w14 + +.Lscvtf_convert: + scvtf d0, x14 + + add x15, _cpu, #CPU_fp + lsl x16, x9, #4 + add x15, x15, x16 + + cbz x11, .Lscvtf_single + str d0, [x15] + str xzr, [x15, #8] + gret + +.Lscvtf_single: + fcvt s0, d0 + str s0, [x15] + str xzr, [x15, #4] + str xzr, [x15, #8] + gret + +/* + * FCVTZU - Floating-point to unsigned integer (round toward zero) + */ +.gadget fcvtzu_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (gpr) + ubfx x10, x8, #8, #5 // rn (fp reg) + ubfx x11, x8, #16, #2 // type + ubfx x12, x8, #18, #1 // sf + + // Load FP value + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x13, x13, x14 + + cbz x11, .Lfcvtzu_single + // type=1: double + ldr d0, [x13] + b .Lfcvtzu_convert + +.Lfcvtzu_single: + ldr s0, [x13] + fcvt d0, s0 // convert to double for uniform handling + +.Lfcvtzu_convert: + fcvtzu x14, d0 // convert to unsigned 64-bit + + cbz x12, .Lfcvtzu_32bit + b .Lfcvtzu_store + +.Lfcvtzu_32bit: + and x14, x14, #0xffffffff + +.Lfcvtzu_store: + cmp x9, #31 + b.eq .Lfcvtzu_done // XZR - discard + add x15, _cpu, #CPU_x0 + str x14, [x15, x9, lsl #3] +.Lfcvtzu_done: + gret + +// Macro for FCVT (FP->int) with different rounding modes +// \name: gadget name suffix, \cvt_x_d: 64-bit convert insn, \cvt_w_d: 32-bit convert insn +.macro make_fcvt_to_int name, cvt_x_d, cvt_w_d, cvt_x_s, cvt_w_s +.gadget \name\()_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd (gpr) + ubfx x10, x8, #8, #5 // rn (fp reg) + ubfx x11, x8, #16, #2 // type + ubfx x12, x8, #18, #1 // sf + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x13, x13, x14 + cbz x12, .L\name\()_32 + // 64-bit result + cbz x11, .L\name\()_x_s + ldr d0, [x13] + \cvt_x_d x14, d0 + b .L\name\()_store +.L\name\()_x_s: + ldr s0, [x13] + \cvt_x_s x14, s0 + b .L\name\()_store +.L\name\()_32: + // 32-bit result + cbz x11, .L\name\()_w_s + ldr d0, [x13] + \cvt_w_d w14, d0 + b .L\name\()_store32 +.L\name\()_w_s: + ldr s0, [x13] + \cvt_w_s w14, s0 +.L\name\()_store32: + // Zero-extend 32-bit to 64-bit + mov w14, w14 +.L\name\()_store: + cmp x9, #31 + b.eq .L\name\()_done + add x15, _cpu, #CPU_x0 + str x14, [x15, x9, lsl #3] +.L\name\()_done: + gret +.endm + +make_fcvt_to_int fcvtns, fcvtns, fcvtns, fcvtns, fcvtns +make_fcvt_to_int fcvtps, fcvtps, fcvtps, fcvtps, fcvtps +make_fcvt_to_int fcvtms, fcvtms, fcvtms, fcvtms, fcvtms +make_fcvt_to_int fcvtnu, fcvtnu, fcvtnu, fcvtnu, fcvtnu +make_fcvt_to_int fcvtpu, fcvtpu, fcvtpu, fcvtpu, fcvtpu +make_fcvt_to_int fcvtmu, fcvtmu, fcvtmu, fcvtmu, fcvtmu +make_fcvt_to_int fcvtas, fcvtas, fcvtas, fcvtas, fcvtas +make_fcvt_to_int fcvtau, fcvtau, fcvtau, fcvtau, fcvtau + +/* + * FCVTZS - Floating-point to signed integer (round toward zero) + * (kept for backward compatibility — same as make_fcvt_to_int but uses fcvtzs) + */ +.gadget fcvtzs_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (gpr) + ubfx x10, x8, #8, #5 // rn (fp reg) + ubfx x11, x8, #16, #2 // type + ubfx x12, x8, #18, #1 // sf + + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x13, x13, x14 + + cbz x11, .Lfcvtzs_single + ldr d0, [x13] + b .Lfcvtzs_convert + +.Lfcvtzs_single: + ldr s0, [x13] + fcvt d0, s0 + +.Lfcvtzs_convert: + fcvtzs x14, d0 + + cbz x12, .Lfcvtzs_32bit + b .Lfcvtzs_store + +.Lfcvtzs_32bit: + // Truncate to 32-bit signed + sxtw x14, w14 + +.Lfcvtzs_store: + cmp x9, #31 + b.eq .Lfcvtzs_done + add x15, _cpu, #CPU_x0 + str x14, [x15, x9, lsl #3] +.Lfcvtzs_done: + gret + +/* + * FCVTZS (GPR, fixed-point) - FP to signed int with scale factor (result in GPR) + * Code stream: [gadget addr][rd | rn<<8 | type<<16 | sf<<18 | fbits<<20] + * Computes: Rd = (int)(Fn * 2^fbits) truncated toward zero + */ +.gadget fcvtzs_fixpt_gpr + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (gpr) + ubfx x10, x8, #8, #5 // rn (fp reg) + ubfx x11, x8, #16, #2 // type (0=S, 1=D) + ubfx x12, x8, #18, #2 // sf (0=32-bit, 1=64-bit) + ubfx x13, x8, #20, #7 // fbits + + // Load FP source + add x14, _cpu, #CPU_fp + lsl x15, x10, #4 + add x14, x14, x15 + + cbz x11, .Lfcvtzs_fg_single + ldr d0, [x14] // double source + b .Lfcvtzs_fg_scale +.Lfcvtzs_fg_single: + ldr s0, [x14] + fcvt d0, s0 // convert single to double for uniform handling + +.Lfcvtzs_fg_scale: + // Multiply by 2^fbits: convert fbits to double, use scvtf then fmul + // Actually: use fcvtzs with shift directly + // ARM64 has: fcvtzs x0, d0, #fbits — but we can't use variable fbits directly + // Instead: scale the double by 2^fbits, then convert + // Build 2^fbits as a double: exponent = fbits + 1023 + add x16, x13, #1023 // biased exponent + lsl x16, x16, #52 // shift to exponent position + fmov d1, x16 // d1 = 2^fbits + fmul d0, d0, d1 // d0 = d0 * 2^fbits + + cbz x12, .Lfcvtzs_fg_32bit + // 64-bit result + fcvtzs x14, d0 + b .Lfcvtzs_fg_store +.Lfcvtzs_fg_32bit: + fcvtzs w14, d0 + sxtw x14, w14 + +.Lfcvtzs_fg_store: + cmp x9, #31 + b.eq .Lfcvtzs_fg_done + add x15, _cpu, #CPU_x0 + str x14, [x15, x9, lsl #3] +.Lfcvtzs_fg_done: + gret + +/* + * FCVTZU (GPR, fixed-point) - FP to unsigned int with scale factor (result in GPR) + * Code stream: [gadget addr][rd | rn<<8 | type<<16 | sf<<18 | fbits<<20] + * Computes: Rd = (uint)(Fn * 2^fbits) truncated toward zero + */ +.gadget fcvtzu_fixpt_gpr + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (gpr) + ubfx x10, x8, #8, #5 // rn (fp reg) + ubfx x11, x8, #16, #2 // type + ubfx x12, x8, #18, #2 // sf + ubfx x13, x8, #20, #7 // fbits + + add x14, _cpu, #CPU_fp + lsl x15, x10, #4 + add x14, x14, x15 + + cbz x11, .Lfcvtzu_fg_single + ldr d0, [x14] + b .Lfcvtzu_fg_scale +.Lfcvtzu_fg_single: + ldr s0, [x14] + fcvt d0, s0 + +.Lfcvtzu_fg_scale: + add x16, x13, #1023 + lsl x16, x16, #52 + fmov d1, x16 + fmul d0, d0, d1 + + cbz x12, .Lfcvtzu_fg_32bit + fcvtzu x14, d0 + b .Lfcvtzu_fg_store +.Lfcvtzu_fg_32bit: + fcvtzu w14, d0 + mov w14, w14 // zero-extend + +.Lfcvtzu_fg_store: + cmp x9, #31 + b.eq .Lfcvtzu_fg_done + add x15, _cpu, #CPU_x0 + str x14, [x15, x9, lsl #3] +.Lfcvtzu_fg_done: + gret + +/* + * SCVTF (GPR, fixed-point) - Signed int to FP with scale factor (source in GPR) + * Code stream: [gadget addr][rd | rn<<8 | type<<16 | sf<<18 | fbits<<20] + * Computes: Fd = (double)Rn / 2^fbits + */ +.gadget scvtf_fixpt_gpr + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (fp reg) + ubfx x10, x8, #8, #5 // rn (gpr) + ubfx x11, x8, #16, #2 // type (0=S, 1=D) + ubfx x12, x8, #18, #2 // sf + ubfx x13, x8, #20, #7 // fbits + + // Load GPR source + add x14, _cpu, #CPU_x0 + cmp x10, #31 + b.eq .Lscvtf_fg_zero + ldr x15, [x14, x10, lsl #3] + b .Lscvtf_fg_convert +.Lscvtf_fg_zero: + mov x15, #0 + +.Lscvtf_fg_convert: + cbz x12, .Lscvtf_fg_32bit + scvtf d0, x15 + b .Lscvtf_fg_scale +.Lscvtf_fg_32bit: + scvtf d0, w15 + +.Lscvtf_fg_scale: + // Divide by 2^fbits: multiply by 2^(-fbits) + mov x16, #1023 + sub x16, x16, x13 // biased exponent = 1023 - fbits + lsl x16, x16, #52 + fmov d1, x16 // d1 = 2^(-fbits) + fmul d0, d0, d1 + + // Store to FP register + add x14, _cpu, #CPU_fp + lsl x15, x9, #4 + add x14, x14, x15 + + cbz x11, .Lscvtf_fg_store_single + str d0, [x14] + str xzr, [x14, #8] + gret +.Lscvtf_fg_store_single: + fcvt s0, d0 + str s0, [x14] + str wzr, [x14, #4] + str xzr, [x14, #8] + gret + +/* + * UCVTF (GPR, fixed-point) - Unsigned int to FP with scale factor (source in GPR) + * Code stream: [gadget addr][rd | rn<<8 | type<<16 | sf<<18 | fbits<<20] + * Computes: Fd = (double)(uint)Rn / 2^fbits + */ +.gadget ucvtf_fixpt_gpr + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (fp reg) + ubfx x10, x8, #8, #5 // rn (gpr) + ubfx x11, x8, #16, #2 // type + ubfx x12, x8, #18, #2 // sf + ubfx x13, x8, #20, #7 // fbits + + add x14, _cpu, #CPU_x0 + cmp x10, #31 + b.eq .Lucvtf_fg_zero + ldr x15, [x14, x10, lsl #3] + b .Lucvtf_fg_convert +.Lucvtf_fg_zero: + mov x15, #0 + +.Lucvtf_fg_convert: + cbz x12, .Lucvtf_fg_32bit + ucvtf d0, x15 + b .Lucvtf_fg_scale +.Lucvtf_fg_32bit: + ucvtf d0, w15 + +.Lucvtf_fg_scale: + mov x16, #1023 + sub x16, x16, x13 + lsl x16, x16, #52 + fmov d1, x16 + fmul d0, d0, d1 + + add x14, _cpu, #CPU_fp + lsl x15, x9, #4 + add x14, x14, x15 + + cbz x11, .Lucvtf_fg_store_single + str d0, [x14] + str xzr, [x14, #8] + gret +.Lucvtf_fg_store_single: + fcvt s0, d0 + str s0, [x14] + str wzr, [x14, #4] + str xzr, [x14, #8] + gret + +/* + * FCVTZS (SIMD scalar) - Floating-point to signed integer (result in SIMD register) + * FCVTZS Dd, Dn (sz=1) or FCVTZS Sd, Sn (sz=0) + * Code stream: [gadget addr][rd | rn<<8 | sz<<16] + */ +.gadget fcvtzs_simd_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (fp reg) + ubfx x10, x8, #8, #5 // rn (fp reg) + ubfx x11, x8, #16, #1 // sz (0=single, 1=double) + + // Load source FP value + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x13, x13, x14 + + cbz x11, .Lfcvtzs_simd_single + // sz=1: double -> 64-bit signed int stored in D register + ldr d0, [x13] + fcvtzs x15, d0 + b .Lfcvtzs_simd_store + +.Lfcvtzs_simd_single: + // sz=0: single -> 32-bit signed int stored in S register + ldr s0, [x13] + fcvtzs w15, s0 + // Result needs to be zero-extended (already in w15) + +.Lfcvtzs_simd_store: + // Store result to destination FP register + add x16, _cpu, #CPU_fp + lsl x17, x9, #4 + add x16, x16, x17 + + cbz x11, .Lfcvtzs_simd_store_single + // 64-bit result + str x15, [x16] + str xzr, [x16, #8] // clear upper 64 bits + gret + +.Lfcvtzs_simd_store_single: + // 32-bit result + str w15, [x16] + str xzr, [x16, #4] // clear upper 96 bits + str xzr, [x16, #8] + gret + +/* + * FCVTZU (SIMD scalar) - Floating-point to unsigned integer (result in SIMD register) + * FCVTZU Dd, Dn (sz=1) or FCVTZU Sd, Sn (sz=0) + * Code stream: [gadget addr][rd | rn<<8 | sz<<16] + */ +.gadget fcvtzu_simd_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (fp reg) + ubfx x10, x8, #8, #5 // rn (fp reg) + ubfx x11, x8, #16, #1 // sz (0=single, 1=double) + + // Load source FP value + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x13, x13, x14 + + cbz x11, .Lfcvtzu_simd_single + // sz=1: double -> 64-bit unsigned int stored in D register + ldr d0, [x13] + fcvtzu x15, d0 + b .Lfcvtzu_simd_store + +.Lfcvtzu_simd_single: + // sz=0: single -> 32-bit unsigned int stored in S register + ldr s0, [x13] + fcvtzu w15, s0 + +.Lfcvtzu_simd_store: + // Store result to destination FP register + add x16, _cpu, #CPU_fp + lsl x17, x9, #4 + add x16, x16, x17 + + cbz x11, .Lfcvtzu_simd_store_single + // 64-bit result + str x15, [x16] + str xzr, [x16, #8] + gret + +.Lfcvtzu_simd_store_single: + // 32-bit result + str w15, [x16] + str xzr, [x16, #4] + str xzr, [x16, #8] + gret + +/* + * UCVTF (SIMD scalar) - Unsigned integer to floating-point (SIMD to SIMD) + * UCVTF Dd, Dn (sz=1) or UCVTF Sd, Sn (sz=0) + * Code stream: [gadget addr][rd | rn<<8 | sz<<16] + */ +.gadget ucvtf_simd_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (fp reg) + ubfx x10, x8, #8, #5 // rn (fp reg) + ubfx x11, x8, #16, #1 // sz (0=single, 1=double) + + // Load source integer value from FP register + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x13, x13, x14 + + cbz x11, .Lucvtf_simd_single + // sz=1: 64-bit unsigned int -> double + ldr x15, [x13] + ucvtf d0, x15 + b .Lucvtf_simd_store + +.Lucvtf_simd_single: + // sz=0: 32-bit unsigned int -> single + ldr w15, [x13] + ucvtf s0, w15 + +.Lucvtf_simd_store: + // Store result to destination FP register + add x16, _cpu, #CPU_fp + lsl x17, x9, #4 + add x16, x16, x17 + + cbz x11, .Lucvtf_simd_store_single + // 64-bit result (double) + str d0, [x16] + str xzr, [x16, #8] // clear upper 64 bits + gret + +.Lucvtf_simd_store_single: + // 32-bit result (single) + str s0, [x16] + str xzr, [x16, #4] // clear upper 96 bits + str xzr, [x16, #8] + gret + +/* + * SCVTF (SIMD scalar) - Signed integer to floating-point (SIMD to SIMD) + * SCVTF Dd, Dn (sz=1) or SCVTF Sd, Sn (sz=0) + * Code stream: [gadget addr][rd | rn<<8 | sz<<16] + */ +.gadget scvtf_simd_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (fp reg) + ubfx x10, x8, #8, #5 // rn (fp reg) + ubfx x11, x8, #16, #1 // sz (0=single, 1=double) + + // Load source integer value from FP register + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x13, x13, x14 + + cbz x11, .Lscvtf_simd_single + // sz=1: 64-bit signed int -> double + ldr x15, [x13] + scvtf d0, x15 + b .Lscvtf_simd_store + +.Lscvtf_simd_single: + // sz=0: 32-bit signed int -> single + ldr w15, [x13] + scvtf s0, w15 + +.Lscvtf_simd_store: + // Store result to destination FP register + add x16, _cpu, #CPU_fp + lsl x17, x9, #4 + add x16, x16, x17 + + cbz x11, .Lscvtf_simd_store_single + // 64-bit result (double) + str d0, [x16] + str xzr, [x16, #8] // clear upper 64 bits + gret + +.Lscvtf_simd_store_single: + // 32-bit result (single) + str s0, [x16] + str xzr, [x16, #4] // clear upper 96 bits + str xzr, [x16, #8] + gret + +/* + * FMOV - Move bits from GPR to FP register (no conversion) + * Code stream: [gadget addr][rd | rn<<8 | type<<16 | sf<<18] + */ +.gadget fmov_gpr_to_fp + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (fp reg) + ubfx x10, x8, #8, #5 // rn (gpr) + ubfx x11, x8, #16, #2 // type (0=single, 1=double) + ubfx x12, x8, #18, #1 // sf + + // Load integer value from GPR + add x13, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr x14, [x13, x10, lsl #3] + b 2f +1: mov x14, #0 +2: + +#if 0 // DEBUG FMOV GPR->FP + stp x0, x1, [sp, #-96]! + stp x2, x3, [sp, #16] + stp x9, x10, [sp, #32] + stp x11, x14, [sp, #48] + str x30, [sp, #64] + stp _cpu, _pc, [sp, #72] + + mov x0, #6 // op = FMOV_G2F + mov x1, x9 // rd (fp) + mov x2, x10 // rn (gpr) + mov x3, #0 // rm (unused) + mov x4, x14 // val1 (gpr value) + mov x5, x11 // val2 (type) + bl NAME(helper_debug_fp) + + ldp x0, x1, [sp] + ldp x2, x3, [sp, #16] + ldp x9, x10, [sp, #32] + ldp x11, x14, [sp, #48] + ldr x30, [sp, #64] + ldp _cpu, _pc, [sp, #72] + add sp, sp, #96 +#endif + + // Store to FP register as bits (no conversion) + add x15, _cpu, #CPU_fp + lsl x16, x9, #4 + add x15, x15, x16 + + cbz x11, .Lfmov_g2f_single + // type=1: 64-bit (double) + str x14, [x15] + str xzr, [x15, #8] // clear upper + gret + +.Lfmov_g2f_single: + // type=0: 32-bit (single) + str w14, [x15] + str xzr, [x15, #4] + str xzr, [x15, #8] + gret + +/* + * FMOV - Move bits from GPR to vector upper D lane (no conversion) + * Code stream: [gadget addr][rd | rn<<8 | type<<16 | sf<<18] + * Only X registers and Vd.D[1] supported here. + */ +.gadget fmov_gpr_to_fp_hi + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (fp reg) + ubfx x10, x8, #8, #5 // rn (gpr) + + // Load integer value from GPR + add x13, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr x14, [x13, x10, lsl #3] + b 2f +1: mov x14, #0 +2: + // Store to upper 64 bits of vector register + add x15, _cpu, #CPU_fp + lsl x16, x9, #4 + add x15, x15, x16 + str x14, [x15, #8] + gret + +/* + * FMOV - Move bits from FP register to GPR (no conversion) + * Code stream: [gadget addr][rd | rn<<8 | type<<16 | sf<<18] + */ +.gadget fmov_fp_to_gpr + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (gpr) + ubfx x10, x8, #8, #5 // rn (fp reg) + ubfx x11, x8, #16, #2 // type + ubfx x12, x8, #18, #1 // sf + + // Load from FP register + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x13, x13, x14 + + cbz x11, .Lfmov_f2g_single + // type=1: 64-bit + ldr x14, [x13] + b .Lfmov_f2g_store + +.Lfmov_f2g_single: + // type=0: 32-bit + ldr w14, [x13] + // zero-extend to 64-bit + and x14, x14, #0xffffffff + +.Lfmov_f2g_store: + cmp x9, #31 + b.eq .Lfmov_f2g_done // XZR - discard + add x15, _cpu, #CPU_x0 + str x14, [x15, x9, lsl #3] +.Lfmov_f2g_done: + gret + +/* + * FMOV - Move bits from vector upper D lane to GPR (no conversion) + * Code stream: [gadget addr][rd | rn<<8 | type<<16 | sf<<18] + * Only X registers and Vn.D[1] supported here. + */ +.gadget fmov_fp_to_gpr_hi + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (gpr) + ubfx x10, x8, #8, #5 // rn (fp reg) + + // Load from upper 64 bits of FP register + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x13, x13, x14 + ldr x14, [x13, #8] + + cmp x9, #31 + b.eq .Lfmov_f2g_hi_done // XZR - discard + add x15, _cpu, #CPU_x0 + str x14, [x15, x9, lsl #3] +.Lfmov_f2g_hi_done: + gret + +/* + * FMOV - Move scalar FP register to FP register (no conversion) + * Code stream: [gadget addr][rd | rn<<8 | type<<16] + * type: 0=single, 1=double + */ +.gadget fmov_fp_to_fp + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (fp reg) + ubfx x10, x8, #8, #5 // rn (fp reg) + ubfx x11, x8, #16, #1 // type + + // Load source FP register + add x12, _cpu, #CPU_fp + lsl x13, x10, #4 + add x12, x12, x13 + + cbz x11, .Lfmov_f2f_single + ldr d0, [x12] + b .Lfmov_f2f_store +.Lfmov_f2f_single: + ldr s0, [x12] + +.Lfmov_f2f_store: + // Store to destination FP register, zero upper lanes + add x14, _cpu, #CPU_fp + lsl x15, x9, #4 + add x14, x14, x15 + + cbz x11, .Lfmov_f2f_store_single + str d0, [x14] + str xzr, [x14, #8] + gret +.Lfmov_f2f_store_single: + str s0, [x14] + str xzr, [x14, #4] + str xzr, [x14, #8] + gret + +/* + * FMOV (scalar, immediate) - Load FP constant into register + * Code stream: [gadget addr][rd | ftype<<8][fpbits_lo][fpbits_hi] + * ftype: 0=single, 1=double + */ +.gadget fmov_fp_imm + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x11, x8, #8, #2 // ftype + + // Load the 64-bit immediate from code stream + ldr x16, [_pc] + add _pc, _pc, #8 + + // Store to destination FP register + add x14, _cpu, #CPU_fp + lsl x15, x9, #4 + add x14, x14, x15 + + cbz x11, .Lfmov_imm_single + // Double: store full 64 bits + str x16, [x14] + str xzr, [x14, #8] + gret +.Lfmov_imm_single: + // Single: store lower 32 bits, zero rest + str w16, [x14] + str wzr, [x14, #4] + str xzr, [x14, #8] + gret + +/* + * FCMP/FCMPE - Floating-point compare (scalar) + * + * Code stream: [gadget addr][rn | rm<<8 | type<<16] + * type: 0=single (32-bit), 1=double (64-bit) + */ +.gadget fcmp_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rn (fp reg) + ubfx x10, x8, #8, #5 // rm (fp reg) + ubfx x11, x8, #16, #2 // type + + // Load Rn + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + add x12, x12, x13 + + cbz x11, .Lfcmp_rn_single + ldr d0, [x12] + b .Lfcmp_load_rm +.Lfcmp_rn_single: + ldr s0, [x12] + +.Lfcmp_load_rm: + // Load Rm + add x14, _cpu, #CPU_fp + lsl x15, x10, #4 + add x14, x14, x15 + + cbz x11, .Lfcmp_rm_single + ldr d1, [x14] + b .Lfcmp_do +.Lfcmp_rm_single: + ldr s1, [x14] + +.Lfcmp_do: + cbz x11, .Lfcmp_do_single + fcmp d0, d1 + b .Lfcmp_store +.Lfcmp_do_single: + fcmp s0, s1 + +.Lfcmp_store: + mrs x17, nzcv + str w17, [_cpu, #CPU_nzcv] + gret + +/* + * FCMP/FCMPE - Floating-point compare with zero (scalar) + * + * Code stream: [gadget addr][rn | type<<16] + * type: 0=single (32-bit), 1=double (64-bit) + */ +.gadget fcmp_zero_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rn (fp reg) + ubfx x11, x8, #16, #2 // type + + add x12, _cpu, #CPU_fp + lsl x13, x9, #4 + add x12, x12, x13 + + cbz x11, .Lfcmp_zero_single + ldr d0, [x12] + fcmp d0, #0.0 + b .Lfcmp_zero_store +.Lfcmp_zero_single: + ldr s0, [x12] + fcmp s0, #0.0 + +.Lfcmp_zero_store: + mrs x17, nzcv + str w17, [_cpu, #CPU_nzcv] + gret + +/* + * Floating-point arithmetic (scalar) + * + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | type<<24] + * type: 0=single (32-bit), 1=double (64-bit) + */ +.gadget fmul_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd (fp reg) + ubfx x10, x8, #8, #5 // rn (fp reg) + ubfx x11, x8, #16, #5 // rm (fp reg) + ubfx x12, x8, #24, #2 // type + + // Load Rn and Rm + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x13, x13, x14 + + add x15, _cpu, #CPU_fp + lsl x16, x11, #4 + add x15, x15, x16 + + cbz x12, .Lfmul_single + ldr d0, [x13] + ldr d1, [x15] + fmul d0, d0, d1 + b .Lfmul_store +.Lfmul_single: + ldr s0, [x13] + ldr s1, [x15] + fmul s0, s0, s1 + +.Lfmul_store: + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + + cbz x12, .Lfmul_store_single + str d0, [x17] + str xzr, [x17, #8] + gret +.Lfmul_store_single: + str s0, [x17] + str xzr, [x17, #4] + str xzr, [x17, #8] + gret + +.gadget fdiv_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + ubfx x12, x8, #24, #2 + + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x13, x13, x14 + + add x15, _cpu, #CPU_fp + lsl x16, x11, #4 + add x15, x15, x16 + + cbz x12, .Lfdiv_single + ldr d0, [x13] + ldr d1, [x15] + fdiv d0, d0, d1 + b .Lfdiv_store +.Lfdiv_single: + ldr s0, [x13] + ldr s1, [x15] + fdiv s0, s0, s1 + +.Lfdiv_store: + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + + cbz x12, .Lfdiv_store_single + str d0, [x17] + str xzr, [x17, #8] + gret +.Lfdiv_store_single: + str s0, [x17] + str xzr, [x17, #4] + str xzr, [x17, #8] + gret + +.gadget fadd_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + ubfx x12, x8, #24, #2 + + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x13, x13, x14 + + add x15, _cpu, #CPU_fp + lsl x16, x11, #4 + add x15, x15, x16 + + cbz x12, .Lfadd_single + ldr d0, [x13] + ldr d1, [x15] + +#if 0 // DEBUG FADD double + stp x0, x1, [sp, #-128]! + stp x2, x3, [sp, #16] + stp x9, x10, [sp, #32] + stp x11, x12, [sp, #48] + stp x13, x15, [sp, #64] + str x30, [sp, #80] + str d0, [sp, #88] + str d1, [sp, #96] + stp _cpu, _pc, [sp, #104] + + // Print debug info: op=2 (FADD), rd=x9, rn=x10, rm=x11, val1=d0, val2=d1 + mov x0, #2 // op = FADD + mov x1, x9 // rd + mov x2, x10 // rn + mov x3, x11 // rm + fmov x4, d0 // val1 + fmov x5, d1 // val2 + bl NAME(helper_debug_fp) + + ldp x0, x1, [sp] + ldp x2, x3, [sp, #16] + ldp x9, x10, [sp, #32] + ldp x11, x12, [sp, #48] + ldp x13, x15, [sp, #64] + ldr x30, [sp, #80] + ldr d0, [sp, #88] + ldr d1, [sp, #96] + ldp _cpu, _pc, [sp, #104] + add sp, sp, #128 +#endif + + fadd d0, d0, d1 + b .Lfadd_store +.Lfadd_single: + ldr s0, [x13] + ldr s1, [x15] + +#if 0 // DEBUG FADD single + stp x0, x1, [sp, #-128]! + stp x2, x3, [sp, #16] + stp x9, x10, [sp, #32] + stp x11, x12, [sp, #48] + stp x13, x15, [sp, #64] + str x30, [sp, #80] + str s0, [sp, #88] + str s1, [sp, #96] + stp _cpu, _pc, [sp, #104] + + // Print debug info for single + mov x0, #2 // op = FADD + mov x1, x9 // rd + mov x2, x10 // rn + mov x3, x11 // rm + fmov w4, s0 + mov x4, x4 // val1 (bits) + fmov w5, s1 + mov x5, x5 // val2 (bits) + bl NAME(helper_debug_fp) + + ldp x0, x1, [sp] + ldp x2, x3, [sp, #16] + ldp x9, x10, [sp, #32] + ldp x11, x12, [sp, #48] + ldp x13, x15, [sp, #64] + ldr x30, [sp, #80] + ldr s0, [sp, #88] + ldr s1, [sp, #96] + ldp _cpu, _pc, [sp, #104] + add sp, sp, #128 +#endif + + fadd s0, s0, s1 + +.Lfadd_store: + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + + cbz x12, .Lfadd_store_single + str d0, [x17] + str xzr, [x17, #8] + gret +.Lfadd_store_single: + str s0, [x17] + str xzr, [x17, #4] + str xzr, [x17, #8] + gret + +/* + * FMADD - Fused multiply-add scalar + * Code stream: [gadget][rd | rn<<8 | rm<<16 | ra<<24][ftype (0=single, 1=double)] + * Computes: Fd = Fn * Fm + Fa + */ +.gadget fmadd_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #5 // ra + + ldr x13, [_pc] // ftype + add _pc, _pc, #8 + + // Load operands + add x14, _cpu, #CPU_fp + lsl x15, x10, #4 + add x15, x14, x15 // &Vn + + lsl x16, x11, #4 + add x16, x14, x16 // &Vm + + lsl x17, x12, #4 + add x17, x14, x17 // &Va + + cbz x13, .Lfmadd_single + // Double precision + ldr d0, [x15] // Fn + ldr d1, [x16] // Fm + ldr d2, [x17] // Fa + fmadd d0, d0, d1, d2 // d0 = d0 * d1 + d2 + + // Store result + lsl x3, x9, #4 + add x3, x14, x3 // &Vd + str d0, [x3] + str xzr, [x3, #8] // Clear upper half + gret + +.Lfmadd_single: + // Single precision + ldr s0, [x15] // Fn + ldr s1, [x16] // Fm + ldr s2, [x17] // Fa + fmadd s0, s0, s1, s2 // s0 = s0 * s1 + s2 + + // Store result + lsl x3, x9, #4 + add x3, x14, x3 // &Vd + str s0, [x3] + str xzr, [x3, #4] // Clear upper 32 bits of low half + str xzr, [x3, #8] // Clear upper half + gret + +/* + * FMSUB - Fused multiply-subtract scalar + * Code stream: [gadget][rd | rn<<8 | rm<<16 | ra<<24][ftype (0=single, 1=double)] + * Computes: Fd = Fn * Fm - Fa + */ +.gadget fmsub_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #5 // ra + + ldr x13, [_pc] // ftype + add _pc, _pc, #8 + + // Load operands + add x14, _cpu, #CPU_fp + lsl x15, x10, #4 + add x15, x14, x15 // &Vn + + lsl x16, x11, #4 + add x16, x14, x16 // &Vm + + lsl x17, x12, #4 + add x17, x14, x17 // &Va + + cbz x13, .Lfmsub_single + // Double precision + ldr d0, [x15] // Fn + ldr d1, [x16] // Fm + ldr d2, [x17] // Fa + fmsub d0, d0, d1, d2 // d0 = d0 * d1 - d2 + + // Store result + lsl x3, x9, #4 + add x3, x14, x3 // &Vd + str d0, [x3] + str xzr, [x3, #8] // Clear upper half + gret + +.Lfmsub_single: + // Single precision + ldr s0, [x15] // Fn + ldr s1, [x16] // Fm + ldr s2, [x17] // Fa + fmsub s0, s0, s1, s2 // s0 = s0 * s1 - s2 + + // Store result + lsl x3, x9, #4 + add x3, x14, x3 // &Vd + str s0, [x3] + str xzr, [x3, #4] // Clear upper 32 bits of low half + str xzr, [x3, #8] // Clear upper half + gret + +/* + * FNMADD - Fused negate multiply-add scalar + * Code stream: [gadget][rd | rn<<8 | rm<<16 | ra<<24][ftype (0=single, 1=double)] + * Computes: Fd = -(Fn * Fm) - Fa = -(Fn * Fm + Fa) + */ +.gadget fnmadd_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #5 // ra + + ldr x13, [_pc] // ftype + add _pc, _pc, #8 + + // Load operands + add x14, _cpu, #CPU_fp + lsl x15, x10, #4 + add x15, x14, x15 // &Vn + + lsl x16, x11, #4 + add x16, x14, x16 // &Vm + + lsl x17, x12, #4 + add x17, x14, x17 // &Va + + cbz x13, .Lfnmadd_single + // Double precision + ldr d0, [x15] // Fn + ldr d1, [x16] // Fm + ldr d2, [x17] // Fa + fnmadd d0, d0, d1, d2 // d0 = -(d0 * d1) - d2 + + // Store result + lsl x3, x9, #4 + add x3, x14, x3 // &Vd + str d0, [x3] + str xzr, [x3, #8] // Clear upper half + gret + +.Lfnmadd_single: + // Single precision + ldr s0, [x15] // Fn + ldr s1, [x16] // Fm + ldr s2, [x17] // Fa + fnmadd s0, s0, s1, s2 // s0 = -(s0 * s1) - s2 + + // Store result + lsl x3, x9, #4 + add x3, x14, x3 // &Vd + str s0, [x3] + str xzr, [x3, #4] // Clear upper 32 bits of low half + str xzr, [x3, #8] // Clear upper half + gret + +/* + * FNMSUB - Fused negate multiply-subtract scalar + * Code stream: [gadget][rd | rn<<8 | rm<<16 | ra<<24][ftype (0=single, 1=double)] + * Computes: Fd = -(Fn * Fm) + Fa = Fa - Fn * Fm + */ +.gadget fnmsub_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #5 // ra + + ldr x13, [_pc] // ftype + add _pc, _pc, #8 + + // Load operands + add x14, _cpu, #CPU_fp + lsl x15, x10, #4 + add x15, x14, x15 // &Vn + + lsl x16, x11, #4 + add x16, x14, x16 // &Vm + + lsl x17, x12, #4 + add x17, x14, x17 // &Va + + cbz x13, .Lfnmsub_single + // Double precision + ldr d0, [x15] // Fn + ldr d1, [x16] // Fm + ldr d2, [x17] // Fa + fnmsub d0, d0, d1, d2 // d0 = -(d0 * d1) + d2 + + // Store result + lsl x3, x9, #4 + add x3, x14, x3 // &Vd + str d0, [x3] + str xzr, [x3, #8] // Clear upper half + gret + +.Lfnmsub_single: + // Single precision + ldr s0, [x15] // Fn + ldr s1, [x16] // Fm + ldr s2, [x17] // Fa + fnmsub s0, s0, s1, s2 // s0 = -(s0 * s1) + s2 + + // Store result + lsl x3, x9, #4 + add x3, x14, x3 // &Vd + str s0, [x3] + str xzr, [x3, #4] // Clear upper 32 bits of low half + str xzr, [x3, #8] // Clear upper half + gret + +.gadget fsub_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x11, x8, #16, #5 + ubfx x12, x8, #24, #2 + + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x13, x13, x14 + + add x15, _cpu, #CPU_fp + lsl x16, x11, #4 + add x15, x15, x16 + + cbz x12, .Lfsub_single + ldr d0, [x13] + ldr d1, [x15] + fsub d0, d0, d1 + b .Lfsub_store +.Lfsub_single: + ldr s0, [x13] + ldr s1, [x15] + fsub s0, s0, s1 + +.Lfsub_store: + add x17, _cpu, #CPU_fp + lsl x3, x9, #4 + add x17, x17, x3 + + cbz x12, .Lfsub_store_single + str d0, [x17] + str xzr, [x17, #8] + gret +.Lfsub_store_single: + str s0, [x17] + str xzr, [x17, #4] + str xzr, [x17, #8] + gret +/* + * FCCMP - Floating-point conditional compare + * Code stream: [gadget addr][rn | rm<<8 | ftype<<16 | cond<<20 | nzcv<<24] + * If cond is true: compare Vn vs Vm and set NZCV from result + * If cond is false: set NZCV to immediate nzcv value + */ +.gadget fccmp_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rn + ubfx x10, x8, #8, #5 // rm + ubfx x12, x8, #16, #4 // ftype + ubfx x17, x8, #20, #4 // cond + ubfx x20, x8, #24, #4 // nzcv (immediate) + + // Read current NZCV flags from memory (not hardware, which may be + // clobbered by TLB lookups in intervening load/store gadgets) + ldr w21, [_cpu, #CPU_nzcv] + + // Check if condition is true + // We need to test the condition. Use a conditional branch trick: + // Branch over the "set immediate" path if condition is met + // Encode condition check using csel + cmp x17, #0 + b.eq .Lfccmp_check_eq + cmp x17, #1 + b.eq .Lfccmp_check_ne + cmp x17, #2 + b.eq .Lfccmp_check_cs + cmp x17, #3 + b.eq .Lfccmp_check_cc + cmp x17, #4 + b.eq .Lfccmp_check_mi + cmp x17, #5 + b.eq .Lfccmp_check_pl + cmp x17, #8 + b.eq .Lfccmp_check_hi + cmp x17, #9 + b.eq .Lfccmp_check_ls + cmp x17, #10 + b.eq .Lfccmp_check_ge + cmp x17, #11 + b.eq .Lfccmp_check_lt + cmp x17, #12 + b.eq .Lfccmp_check_gt + cmp x17, #13 + b.eq .Lfccmp_check_le + cmp x17, #14 + b.eq .Lfccmp_check_al + // VS(6), VC(7) and AL(14)/NV(15) + cmp x17, #6 + b.eq .Lfccmp_check_vs + cmp x17, #7 + b.eq .Lfccmp_check_vc + b .Lfccmp_check_al // default: always + + // Each check: restore NZCV, test condition, branch +.Lfccmp_check_eq: + msr nzcv, x21 + b.eq .Lfccmp_do_compare + b .Lfccmp_set_imm +.Lfccmp_check_ne: + msr nzcv, x21 + b.ne .Lfccmp_do_compare + b .Lfccmp_set_imm +.Lfccmp_check_cs: + msr nzcv, x21 + b.cs .Lfccmp_do_compare + b .Lfccmp_set_imm +.Lfccmp_check_cc: + msr nzcv, x21 + b.cc .Lfccmp_do_compare + b .Lfccmp_set_imm +.Lfccmp_check_mi: + msr nzcv, x21 + b.mi .Lfccmp_do_compare + b .Lfccmp_set_imm +.Lfccmp_check_pl: + msr nzcv, x21 + b.pl .Lfccmp_do_compare + b .Lfccmp_set_imm +.Lfccmp_check_vs: + msr nzcv, x21 + b.vs .Lfccmp_do_compare + b .Lfccmp_set_imm +.Lfccmp_check_vc: + msr nzcv, x21 + b.vc .Lfccmp_do_compare + b .Lfccmp_set_imm +.Lfccmp_check_hi: + msr nzcv, x21 + b.hi .Lfccmp_do_compare + b .Lfccmp_set_imm +.Lfccmp_check_ls: + msr nzcv, x21 + b.ls .Lfccmp_do_compare + b .Lfccmp_set_imm +.Lfccmp_check_ge: + msr nzcv, x21 + b.ge .Lfccmp_do_compare + b .Lfccmp_set_imm +.Lfccmp_check_lt: + msr nzcv, x21 + b.lt .Lfccmp_do_compare + b .Lfccmp_set_imm +.Lfccmp_check_gt: + msr nzcv, x21 + b.gt .Lfccmp_do_compare + b .Lfccmp_set_imm +.Lfccmp_check_le: + msr nzcv, x21 + b.le .Lfccmp_do_compare + b .Lfccmp_set_imm +.Lfccmp_check_al: + b .Lfccmp_do_compare + +.Lfccmp_set_imm: + // Condition was false: set NZCV from immediate + lsl x20, x20, #28 // shift nzcv into position + str w20, [_cpu, #CPU_nzcv] + gret + +.Lfccmp_do_compare: + // Condition was true: do the actual FP compare + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vn + lsl x15, x10, #4 + add x15, x13, x15 // &Vm + + cbz x12, .Lfccmp_single + ldr d0, [x14] + ldr d1, [x15] + fcmp d0, d1 + store_flags + gret +.Lfccmp_single: + ldr s0, [x14] + ldr s1, [x15] + fcmp s0, s1 + store_flags + gret + +/* + * FCSEL - Floating-point conditional select + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | ftype<<24][cond] + * Rd = cond ? Rn : Rm + */ +.gadget fcsel_scalar + ldr x8, [_pc] + ldr x20, [_pc, #8] // cond (save in x20, callee-saved won't be clobbered) + add _pc, _pc, #16 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #4 // ftype + + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x14, x13, x14 // &Vn + lsl x15, x11, #4 + add x15, x13, x15 // &Vm + lsl x16, x9, #4 + add x16, x13, x16 // &Vd + + // Load both operands + cbz x12, .Lfcsel_single + ldr d0, [x14] // Vn (double) + ldr d1, [x15] // Vm (double) + b .Lfcsel_select +.Lfcsel_single: + ldr s0, [x14] // Vn (single) + ldr s1, [x15] // Vm (single) + +.Lfcsel_select: + // Load guest NZCV from memory (not hardware, which may be clobbered by + // TLB lookups in intervening load/store gadgets). + // The dispatch uses cmp which also clobbers hardware flags, so we restore + // guest NZCV from x17 at each condition label before testing. + ldr w17, [_cpu, #CPU_nzcv] + + cmp x20, #0 + b.eq .Lfcsel_eq + cmp x20, #1 + b.eq .Lfcsel_ne + cmp x20, #10 + b.eq .Lfcsel_ge + cmp x20, #11 + b.eq .Lfcsel_lt + cmp x20, #12 + b.eq .Lfcsel_gt + cmp x20, #13 + b.eq .Lfcsel_le + cmp x20, #2 + b.eq .Lfcsel_cs + cmp x20, #3 + b.eq .Lfcsel_cc + cmp x20, #4 + b.eq .Lfcsel_mi + cmp x20, #5 + b.eq .Lfcsel_pl + cmp x20, #6 + b.eq .Lfcsel_vs + cmp x20, #7 + b.eq .Lfcsel_vc + cmp x20, #8 + b.eq .Lfcsel_hi + cmp x20, #9 + b.eq .Lfcsel_ls + b .Lfcsel_true // AL/NV: always true + + // Each label: restore guest NZCV, test condition, branch to true/false +.Lfcsel_eq: + msr nzcv, x17 + b.eq .Lfcsel_true + b .Lfcsel_false +.Lfcsel_ne: + msr nzcv, x17 + b.ne .Lfcsel_true + b .Lfcsel_false +.Lfcsel_cs: + msr nzcv, x17 + b.cs .Lfcsel_true + b .Lfcsel_false +.Lfcsel_cc: + msr nzcv, x17 + b.cc .Lfcsel_true + b .Lfcsel_false +.Lfcsel_mi: + msr nzcv, x17 + b.mi .Lfcsel_true + b .Lfcsel_false +.Lfcsel_pl: + msr nzcv, x17 + b.pl .Lfcsel_true + b .Lfcsel_false +.Lfcsel_vs: + msr nzcv, x17 + b.vs .Lfcsel_true + b .Lfcsel_false +.Lfcsel_vc: + msr nzcv, x17 + b.vc .Lfcsel_true + b .Lfcsel_false +.Lfcsel_hi: + msr nzcv, x17 + b.hi .Lfcsel_true + b .Lfcsel_false +.Lfcsel_ls: + msr nzcv, x17 + b.ls .Lfcsel_true + b .Lfcsel_false +.Lfcsel_ge: + msr nzcv, x17 + b.ge .Lfcsel_true + b .Lfcsel_false +.Lfcsel_lt: + msr nzcv, x17 + b.lt .Lfcsel_true + b .Lfcsel_false +.Lfcsel_gt: + msr nzcv, x17 + b.gt .Lfcsel_true + b .Lfcsel_false +.Lfcsel_le: + msr nzcv, x17 + b.le .Lfcsel_true + b .Lfcsel_false + +.Lfcsel_true: + // Condition met: Rd = Rn (d0/s0) + cbz x12, .Lfcsel_store_s_true + str d0, [x16] + str xzr, [x16, #8] + gret +.Lfcsel_store_s_true: + str s0, [x16] + str xzr, [x16, #4] + str xzr, [x16, #8] + gret + +.Lfcsel_false: + // Condition not met: Rd = Rm (d1/s1) + cbz x12, .Lfcsel_store_s_false + str d1, [x16] + str xzr, [x16, #8] + gret +.Lfcsel_store_s_false: + str s1, [x16] + str xzr, [x16, #4] + str xzr, [x16, #8] + gret + +/* + * FP data-processing (1 source) - generic dispatcher + * Code stream: [gadget addr][rd | rn<<8 | ftype<<16 | opcode<<20] + * ftype: 0=single, 1=double + * opcode: 0=FMOV, 1=FABS, 2=FNEG, 3=FSQRT, 4=FCVT(->S), 5=FCVT(->D), + * 8=FRINTN, 9=FRINTP, 10=FRINTM, 11=FRINTZ, 12=FRINTA, 14=FRINTX, 15=FRINTI + */ +.gadget fp_dp1 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #16, #4 // ftype + ubfx x17, x8, #20, #6 // opcode + + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x14, x13, x14 // &Vn + lsl x15, x9, #4 + add x15, x13, x15 // &Vd + + // Load source (always load as Q to cover both S and D) + ldr q0, [x14] + + // Dispatch on opcode + cmp x17, #1 + b.eq .Lfp_dp1_fabs + cmp x17, #2 + b.eq .Lfp_dp1_fneg + cmp x17, #3 + b.eq .Lfp_dp1_fsqrt + cmp x17, #5 + b.eq .Lfp_dp1_fcvt_to_d + cmp x17, #4 + b.eq .Lfp_dp1_fcvt_to_s + cmp x17, #8 + b.eq .Lfp_dp1_frintn + cmp x17, #9 + b.eq .Lfp_dp1_frintp + cmp x17, #10 + b.eq .Lfp_dp1_frintm + cmp x17, #11 + b.eq .Lfp_dp1_frintz + cmp x17, #12 + b.eq .Lfp_dp1_frinta + cmp x17, #14 + b.eq .Lfp_dp1_frintx + cmp x17, #15 + b.eq .Lfp_dp1_frinti + // opcode 0 = FMOV (same type copy) - just store source to dest + b .Lfp_dp1_store + +.Lfp_dp1_fabs: + cbz x12, 1f + fabs d0, d0 + b .Lfp_dp1_store +1: fabs s0, s0 + b .Lfp_dp1_store + +.Lfp_dp1_fneg: + cbz x12, 1f + fneg d0, d0 + b .Lfp_dp1_store +1: fneg s0, s0 + b .Lfp_dp1_store + +.Lfp_dp1_fsqrt: + cbz x12, 1f + fsqrt d0, d0 + b .Lfp_dp1_store +1: fsqrt s0, s0 + b .Lfp_dp1_store + +.Lfp_dp1_fcvt_to_d: + // FCVT Dd, Sn (single to double) + fcvt d0, s0 + mov w12, #1 // result is double + b .Lfp_dp1_store + +.Lfp_dp1_fcvt_to_s: + // FCVT Sd, Dn (double to single) + fcvt s0, d0 + mov w12, #0 // result is single + b .Lfp_dp1_store + +.Lfp_dp1_frintn: + cbz x12, 1f + frintn d0, d0 + b .Lfp_dp1_store +1: frintn s0, s0 + b .Lfp_dp1_store + +.Lfp_dp1_frintp: + cbz x12, 1f + frintp d0, d0 + b .Lfp_dp1_store +1: frintp s0, s0 + b .Lfp_dp1_store + +.Lfp_dp1_frintm: + cbz x12, 1f + frintm d0, d0 + b .Lfp_dp1_store +1: frintm s0, s0 + b .Lfp_dp1_store + +.Lfp_dp1_frintz: + cbz x12, 1f + frintz d0, d0 + b .Lfp_dp1_store +1: frintz s0, s0 + b .Lfp_dp1_store + +.Lfp_dp1_frinta: + cbz x12, 1f + frinta d0, d0 + b .Lfp_dp1_store +1: frinta s0, s0 + b .Lfp_dp1_store + +.Lfp_dp1_frintx: + cbz x12, 1f + frintx d0, d0 + b .Lfp_dp1_store +1: frintx s0, s0 + b .Lfp_dp1_store + +.Lfp_dp1_frinti: + cbz x12, 1f + frinti d0, d0 + b .Lfp_dp1_store +1: frinti s0, s0 + b .Lfp_dp1_store + +.Lfp_dp1_store: + cbz x12, .Lfp_dp1_store_s + str d0, [x15] + str xzr, [x15, #8] + gret +.Lfp_dp1_store_s: + str s0, [x15] + str xzr, [x15, #4] + str xzr, [x15, #8] + gret + +/* + * FCVT Sd, Hn / FCVT Dd, Hn - scalar FP16 to FP32/FP64 conversion. + * Code stream: [gadget addr][rd | rn<<8] + */ +.gadget fcvt_h_to_s_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x14, x13, x14 + ldr h0, [x14] + fcvt s0, h0 + + lsl x15, x9, #4 + add x15, x13, x15 + str s0, [x15] + str xzr, [x15, #4] + str xzr, [x15, #8] + gret + +.gadget fcvt_h_to_d_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x14, x13, x14 + ldr h0, [x14] + fcvt d0, h0 + + lsl x15, x9, #4 + add x15, x13, x15 + str d0, [x15] + str xzr, [x15, #8] + gret + +// Macro for FP two-source scalar operations +// All have same structure: load Vn and Vm, do op, store to Vd +.macro make_fp2_scalar name, op_d, op_s +.gadget \name\()_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // type (0=single, 1=double) + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x14, x13, x14 // &Vn + lsl x15, x11, #4 + add x15, x13, x15 // &Vm + lsl x16, x9, #4 + add x16, x13, x16 // &Vd + cbz x12, .L\name\()_single + ldr d0, [x14] + ldr d1, [x15] + \op_d d0, d0, d1 + str d0, [x16] + str xzr, [x16, #8] + gret +.L\name\()_single: + ldr s0, [x14] + ldr s1, [x15] + \op_s s0, s0, s1 + str s0, [x16] + str xzr, [x16, #4] + str xzr, [x16, #8] + gret +.endm + +make_fp2_scalar fmax, fmax, fmax +make_fp2_scalar fmin, fmin, fmin +make_fp2_scalar fmaxnm, fmaxnm, fmaxnm +make_fp2_scalar fminnm, fminnm, fminnm +make_fp2_scalar fnmul, fnmul, fnmul +make_fp2_scalar fabd, fabd, fabd + +/* + * FADDP (scalar) - Floating-point Add Pair of elements + * Code stream: [gadget addr][rd | rn<<8 | sz<<16] + * sz=0: FADDP Sd, Vn.2S (add two single-precision elements) + * sz=1: FADDP Dd, Vn.2D (add two double-precision elements) + */ +.gadget faddp_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #16, #2 // sz (0=single, 1=double) + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x14, x13, x14 // &Vn + lsl x16, x9, #4 + add x16, x13, x16 // &Vd + cbz x12, .Lfaddp_scalar_single + // Double: add pair from 128-bit register + ldr q0, [x14] + faddp d0, v0.2d + str d0, [x16] + str xzr, [x16, #8] + gret +.Lfaddp_scalar_single: + // Single: add pair from low 64 bits + ldr d0, [x14] + faddp s0, v0.2s + str s0, [x16] + str xzr, [x16, #4] + str xzr, [x16, #8] + gret + +/* + * FMAXP (scalar) - Floating-point Maximum Pair of elements + * Code stream: [gadget addr][rd | rn<<8 | sz<<16] + * sz=0: FMAXP Sd, Vn.2S, sz=1: FMAXP Dd, Vn.2D + */ +.gadget fmaxp_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #16, #2 // sz + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x14, x13, x14 // &Vn + lsl x16, x9, #4 + add x16, x13, x16 // &Vd + cbz x12, .Lfmaxp_scalar_single + ldr q0, [x14] + fmaxp d0, v0.2d + str d0, [x16] + str xzr, [x16, #8] + gret +.Lfmaxp_scalar_single: + ldr d0, [x14] + fmaxp s0, v0.2s + str s0, [x16] + str xzr, [x16, #4] + str xzr, [x16, #8] + gret + +/* + * FMINP (scalar) - Floating-point Minimum Pair of elements + * Code stream: [gadget addr][rd | rn<<8 | sz<<16] + * sz=0: FMINP Sd, Vn.2S, sz=1: FMINP Dd, Vn.2D + */ +.gadget fminp_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #16, #2 // sz + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x14, x13, x14 // &Vn + lsl x16, x9, #4 + add x16, x13, x16 // &Vd + cbz x12, .Lfminp_scalar_single + ldr q0, [x14] + fminp d0, v0.2d + str d0, [x16] + str xzr, [x16, #8] + gret +.Lfminp_scalar_single: + ldr d0, [x14] + fminp s0, v0.2s + str s0, [x16] + str xzr, [x16, #4] + str xzr, [x16, #8] + gret + +/* + * FMAXNMP (scalar) - Floating-point Maximum Number Pair of elements + * Code stream: [gadget addr][rd | rn<<8 | sz<<16] + */ +.gadget fmaxnmp_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #16, #2 // sz + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x14, x13, x14 // &Vn + lsl x16, x9, #4 + add x16, x13, x16 // &Vd + cbz x12, .Lfmaxnmp_scalar_single + ldr q0, [x14] + fmaxnmp d0, v0.2d + str d0, [x16] + str xzr, [x16, #8] + gret +.Lfmaxnmp_scalar_single: + ldr d0, [x14] + fmaxnmp s0, v0.2s + str s0, [x16] + str xzr, [x16, #4] + str xzr, [x16, #8] + gret + +/* + * FMINNMP (scalar) - Floating-point Minimum Number Pair of elements + * Code stream: [gadget addr][rd | rn<<8 | sz<<16] + */ +.gadget fminnmp_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #16, #2 // sz + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x14, x13, x14 // &Vn + lsl x16, x9, #4 + add x16, x13, x16 // &Vd + cbz x12, .Lfminnmp_scalar_single + ldr q0, [x14] + fminnmp d0, v0.2d + str d0, [x16] + str xzr, [x16, #8] + gret +.Lfminnmp_scalar_single: + ldr d0, [x14] + fminnmp s0, v0.2s + str s0, [x16] + str xzr, [x16, #4] + str xzr, [x16, #8] + gret + +// ADDP (scalar, integer) - Add pair of 64-bit elements to scalar +// ADDP Dd, Vn.2D: adds two 64-bit elements of Vn, stores in Dd +// Code stream: [gadget addr][rd | rn<<8] +.gadget addp_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + add x13, _cpu, #CPU_fp + lsl x14, x10, #4 + add x14, x13, x14 // &Vn + lsl x16, x9, #4 + add x16, x13, x16 // &Vd + ldr q0, [x14] + addp d0, v0.2d + str d0, [x16] + str xzr, [x16, #8] + gret + +// UMULH: Xd = (Xn * Xm) >> 64 (unsigned high multiply) +.gadget umulh + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + + add x14, _cpu, #CPU_x0 + + // Load Rn + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: + // Load Rm + cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: + // Compute: result = (Rn * Rm) >> 64 (high bits) + umulh x3, x15, x16 + + // Store result + cmp x9, #31 + b.eq 3f + str x3, [x14, x9, lsl #3] +3: gret + +// SMULH: Xd = (Xn * Xm) >> 64 (signed high multiply) +.gadget smulh + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + + add x14, _cpu, #CPU_x0 + + // Load Rn + cmp x10, #31 + mov x15, #0 + b.eq 1f + ldr x15, [x14, x10, lsl #3] +1: + // Load Rm + cmp x11, #31 + mov x16, #0 + b.eq 2f + ldr x16, [x14, x11, lsl #3] +2: + // Compute: result = (Xn * Xm) >> 64 (signed high bits) + smulh x3, x15, x16 + + // Store result + cmp x9, #31 + b.eq 3f + str x3, [x14, x9, lsl #3] +3: gret + +/* + * SADDW - Signed add wide (vector) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * + * SADDW{2} Vd.<Ta>, Vn.<Ta>, Vm.<Tb> + * Adds wide vector Vn (2x element size) to narrow vector Vm, producing wide result + * + * size: 0=B->H, 1=H->S, 2=S->D (narrow source size) + * Q: 0=lower half (SADDW), 1=upper half (SADDW2) + */ +.gadget saddw_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn (wide) + lsl x16, x11, #4 + add x16, x13, x16 // &Vm (narrow) + + // Load wide vector Vn into v0 + ldr q0, [x15] + // Load narrow vector Vm into v1 + ldr q1, [x16] + + cmp x12, #0 + b.eq .Lsaddw_size_b + cmp x12, #1 + b.eq .Lsaddw_size_h + // size == 2 (S->D) + b .Lsaddw_size_s + +.Lsaddw_size_b: + // B->H: Vn.8H + Vm.8B (or .16B upper half) + cbz x17, .Lsaddw_b_lo + // SADDW2: upper half + saddw2 v0.8h, v0.8h, v1.16b + b .Lsaddw_store +.Lsaddw_b_lo: + // SADDW: lower half + saddw v0.8h, v0.8h, v1.8b + b .Lsaddw_store + +.Lsaddw_size_h: + // H->S: Vn.4S + Vm.4H (or .8H upper half) + cbz x17, .Lsaddw_h_lo + // SADDW2: upper half + saddw2 v0.4s, v0.4s, v1.8h + b .Lsaddw_store +.Lsaddw_h_lo: + // SADDW: lower half + saddw v0.4s, v0.4s, v1.4h + b .Lsaddw_store + +.Lsaddw_size_s: + // S->D: Vn.2D + Vm.2S (or .4S upper half) + cbz x17, .Lsaddw_s_lo + // SADDW2: upper half + saddw2 v0.2d, v0.2d, v1.4s + b .Lsaddw_store +.Lsaddw_s_lo: + // SADDW: lower half + saddw v0.2d, v0.2d, v1.2s + b .Lsaddw_store + +.Lsaddw_store: + str q0, [x14] + gret + +/* + * UADDW - Unsigned add wide (vector) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * + * UADDW{2} Vd.<Ta>, Vn.<Ta>, Vm.<Tb> + * Adds wide vector Vn (2x element size) to narrow vector Vm, producing wide result + * + * size: 0=B->H, 1=H->S, 2=S->D (narrow source size) + * Q: 0=lower half (UADDW), 1=upper half (UADDW2) + */ +.gadget uaddw_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn (wide) + lsl x16, x11, #4 + add x16, x13, x16 // &Vm (narrow) + + // Load wide vector Vn into v0 + ldr q0, [x15] + // Load narrow vector Vm into v1 + ldr q1, [x16] + + cmp x12, #0 + b.eq .Luaddw_size_b + cmp x12, #1 + b.eq .Luaddw_size_h + // size == 2 (S->D) + b .Luaddw_size_s + +.Luaddw_size_b: + // B->H: Vn.8H + Vm.8B (or .16B upper half) + cbz x17, .Luaddw_b_lo + // UADDW2: upper half + uaddw2 v0.8h, v0.8h, v1.16b + b .Luaddw_store +.Luaddw_b_lo: + // UADDW: lower half + uaddw v0.8h, v0.8h, v1.8b + b .Luaddw_store + +.Luaddw_size_h: + // H->S: Vn.4S + Vm.4H (or .8H upper half) + cbz x17, .Luaddw_h_lo + // UADDW2: upper half + uaddw2 v0.4s, v0.4s, v1.8h + b .Luaddw_store +.Luaddw_h_lo: + // UADDW: lower half + uaddw v0.4s, v0.4s, v1.4h + b .Luaddw_store + +.Luaddw_size_s: + // S->D: Vn.2D + Vm.2S (or .4S upper half) + cbz x17, .Luaddw_s_lo + // UADDW2: upper half + uaddw2 v0.2d, v0.2d, v1.4s + b .Luaddw_store +.Luaddw_s_lo: + // UADDW: lower half + uaddw v0.2d, v0.2d, v1.2s + b .Luaddw_store + +.Luaddw_store: + str q0, [x14] + gret + +/* + * SSUBW - Signed subtract wide (vector) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * + * SSUBW{2} Vd.<Ta>, Vn.<Ta>, Vm.<Tb> + * Subtracts sign-extended narrow vector Vm from wide vector Vn + * Vd[i] = Vn[i] - sext(Vm[i]) + * + * size: 0=B->H, 1=H->S, 2=S->D (narrow source size) + * Q: 0=lower half (SSUBW), 1=upper half (SSUBW2) + */ +.gadget ssubw_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn (wide) + lsl x16, x11, #4 + add x16, x13, x16 // &Vm (narrow) + + // Load wide vector Vn into v0 + ldr q0, [x15] + // Load narrow vector Vm into v1 + ldr q1, [x16] + + cmp x12, #0 + b.eq .Lssubw_size_b + cmp x12, #1 + b.eq .Lssubw_size_h + // size == 2 (S->D) + b .Lssubw_size_s + +.Lssubw_size_b: + // B->H: Vn.8H - sext(Vm.8B) (or .16B upper half) + cbz x17, .Lssubw_b_lo + // SSUBW2: upper half + ssubw2 v0.8h, v0.8h, v1.16b + b .Lssubw_store +.Lssubw_b_lo: + // SSUBW: lower half + ssubw v0.8h, v0.8h, v1.8b + b .Lssubw_store + +.Lssubw_size_h: + // H->S: Vn.4S - sext(Vm.4H) (or .8H upper half) + cbz x17, .Lssubw_h_lo + // SSUBW2: upper half + ssubw2 v0.4s, v0.4s, v1.8h + b .Lssubw_store +.Lssubw_h_lo: + // SSUBW: lower half + ssubw v0.4s, v0.4s, v1.4h + b .Lssubw_store + +.Lssubw_size_s: + // S->D: Vn.2D - sext(Vm.2S) (or .4S upper half) + cbz x17, .Lssubw_s_lo + // SSUBW2: upper half + ssubw2 v0.2d, v0.2d, v1.4s + b .Lssubw_store +.Lssubw_s_lo: + // SSUBW: lower half + ssubw v0.2d, v0.2d, v1.2s + b .Lssubw_store + +.Lssubw_store: + str q0, [x14] + gret + +/* + * USUBW - Unsigned subtract wide (vector) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * + * USUBW{2} Vd.<Ta>, Vn.<Ta>, Vm.<Tb> + * Subtracts zero-extended narrow vector Vm from wide vector Vn + * Vd[i] = Vn[i] - zext(Vm[i]) + * + * size: 0=B->H, 1=H->S, 2=S->D (narrow source size) + * Q: 0=lower half (USUBW), 1=upper half (USUBW2) + */ +.gadget usubw_vec + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn (wide) + lsl x16, x11, #4 + add x16, x13, x16 // &Vm (narrow) + + // Load wide vector Vn into v0 + ldr q0, [x15] + // Load narrow vector Vm into v1 + ldr q1, [x16] + + cmp x12, #0 + b.eq .Lusubw_size_b + cmp x12, #1 + b.eq .Lusubw_size_h + // size == 2 (S->D) + b .Lusubw_size_s + +.Lusubw_size_b: + // B->H: Vn.8H - zext(Vm.8B) (or .16B upper half) + cbz x17, .Lusubw_b_lo + // USUBW2: upper half + usubw2 v0.8h, v0.8h, v1.16b + b .Lusubw_store +.Lusubw_b_lo: + // USUBW: lower half + usubw v0.8h, v0.8h, v1.8b + b .Lusubw_store + +.Lusubw_size_h: + // H->S: Vn.4S - zext(Vm.4H) (or .8H upper half) + cbz x17, .Lusubw_h_lo + // USUBW2: upper half + usubw2 v0.4s, v0.4s, v1.8h + b .Lusubw_store +.Lusubw_h_lo: + // USUBW: lower half + usubw v0.4s, v0.4s, v1.4h + b .Lusubw_store + +.Lusubw_size_s: + // S->D: Vn.2D - zext(Vm.2S) (or .4S upper half) + cbz x17, .Lusubw_s_lo + // USUBW2: upper half + usubw2 v0.2d, v0.2d, v1.4s + b .Lusubw_store +.Lusubw_s_lo: + // USUBW: lower half + usubw v0.2d, v0.2d, v1.2s + b .Lusubw_store + +.Lusubw_store: + str q0, [x14] + gret + +/* + * ============================================================ + * Specialized ALU gadgets for common 64-bit cases + * + * These eliminate runtime conditional branches by handling only + * the most common case: 64-bit, no shift, no SP, no XZR operands. + * gen.c selects these at decode time when conditions are met; + * all other cases fall through to the generic gadgets above. + * + * Param packing: rd | rn<<8 | imm12_or_rm<<16 + * ============================================================ + */ + +// ADD (immediate, 64-bit, no flags, no SP, no LSL#12) +// Condition: sf=1, S=0, sh=0, rd!=31, rn!=31 +.gadget add_imm_64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + add x16, x15, x11 + str x16, [x14, x9, lsl #3] // Rd + gret + +// SUB (immediate, 64-bit, no flags, no SP, no LSL#12) +// Condition: sf=1, S=0, sh=0, rd!=31, rn!=31 +.gadget sub_imm_64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + sub x16, x15, x11 + str x16, [x14, x9, lsl #3] // Rd + gret + +// ADD (immediate, 64-bit, no flags, SP source, no LSL#12) +// Condition: sf=1, S=0, sh=0, rn==31, rd!=31 +// Code stream: [gadget addr][rd | imm12<<16] +.gadget add_imm_sp_src_64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x11, x8, #16, #12 // imm12 + ldr x15, [_cpu, #CPU_sp] // load SP directly + add x16, x15, x11 + add x14, _cpu, #CPU_x0 + str x16, [x14, x9, lsl #3] // Rd + gret + +// SUB (immediate, 64-bit, no flags, SP source, no LSL#12) +// Condition: sf=1, S=0, sh=0, rn==31, rd!=31 +.gadget sub_imm_sp_src_64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x11, x8, #16, #12 + ldr x15, [_cpu, #CPU_sp] + sub x16, x15, x11 + add x14, _cpu, #CPU_x0 + str x16, [x14, x9, lsl #3] + gret + +// ADDS (immediate, 64-bit, flag-setting, no SP source, no LSL#12) +// Condition: sf=1, S=1, sh=0, rn!=31 (rd=31 allowed for CMN) +.gadget adds_imm_64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + adds x16, x15, x11 + store_flags + cmp x9, #31 + b.eq 1f + str x16, [x14, x9, lsl #3] // Rd +1: gret + +// SUBS (immediate, 64-bit, flag-setting, no SP source, no LSL#12) +// Condition: sf=1, S=1, sh=0, rn!=31 (rd=31 allowed for CMP) +.gadget subs_imm_64 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + subs x16, x15, x11 + store_flags + cmp x9, #31 + b.eq 1f + str x16, [x14, x9, lsl #3] // Rd +1: gret + +// ADDS (immediate, 64-bit, flag-setting, LSL#12) +// Condition: sf=1, S=1, sh=1, rn!=31 +// Param: rd | rn<<8 | imm12<<16 +.gadget adds_imm_64_sh + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + lsl x11, x11, #12 // apply LSL#12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + adds x16, x15, x11 + store_flags + cmp x9, #31 + b.eq 1f + str x16, [x14, x9, lsl #3] // Rd +1: gret + +// SUBS (immediate, 64-bit, flag-setting, LSL#12) +// Condition: sf=1, S=1, sh=1, rn!=31 +// Param: rd | rn<<8 | imm12<<16 +.gadget subs_imm_64_sh + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + lsl x11, x11, #12 // apply LSL#12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + subs x16, x15, x11 + store_flags + cmp x9, #31 + b.eq 1f + str x16, [x14, x9, lsl #3] // Rd +1: gret + +// ADD (immediate, 64-bit, no flags, LSL#12) +// Condition: sf=1, S=0, sh=1, rd!=31, rn!=31 +// Param: rd | rn<<8 | imm12<<16 +.gadget add_imm_64_sh + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + lsl x11, x11, #12 // apply LSL#12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + add x16, x15, x11 + str x16, [x14, x9, lsl #3] // Rd + gret + +// SUB (immediate, 64-bit, no flags, LSL#12) +// Condition: sf=1, S=0, sh=1, rd!=31, rn!=31 +// Param: rd | rn<<8 | imm12<<16 +.gadget sub_imm_64_sh + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + lsl x11, x11, #12 // apply LSL#12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + sub x16, x15, x11 + str x16, [x14, x9, lsl #3] // Rd + gret + +// ============================================================ +// 32-bit specialized add/sub immediate gadgets (OP-10) +// ============================================================ + +// ADD (immediate, 32-bit, no flags, no SP, no LSL#12) +// Condition: sf=0, S=0, sh=0, rd!=31, rn!=31 +// Param: rd | rn<<8 | imm12<<16 +.gadget add_imm_32 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + add w16, w15, w11 // 32-bit add (zero-extends result) + str x16, [x14, x9, lsl #3] // Rd + gret + +// SUB (immediate, 32-bit, no flags, no SP, no LSL#12) +// Condition: sf=0, S=0, sh=0, rd!=31, rn!=31 +// Param: rd | rn<<8 | imm12<<16 +.gadget sub_imm_32 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + sub w16, w15, w11 // 32-bit sub (zero-extends result) + str x16, [x14, x9, lsl #3] // Rd + gret + +// ADDS (immediate, 32-bit, flag-setting, no SP source, no LSL#12) +// Condition: sf=0, S=1, sh=0, rn!=31 (rd=31 allowed for CMN) +// Param: rd | rn<<8 | imm12<<16 +.gadget adds_imm_32 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + adds w16, w15, w11 // 32-bit adds (zero-extends, sets 32-bit flags) + store_flags + cmp x9, #31 + b.eq 1f + str x16, [x14, x9, lsl #3] // Rd (already zero-extended by w-reg op) +1: gret + +// SUBS (immediate, 32-bit, flag-setting, no SP source, no LSL#12) +// Condition: sf=0, S=1, sh=0, rn!=31 (rd=31 allowed for CMP) +// Param: rd | rn<<8 | imm12<<16 +.gadget subs_imm_32 + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #12 // imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + subs w16, w15, w11 // 32-bit subs (zero-extends, sets 32-bit flags) + store_flags + cmp x9, #31 + b.eq 1f + str x16, [x14, x9, lsl #3] // Rd (already zero-extended by w-reg op) +1: gret + +// ADDS (register, 64-bit, flag-setting, no shift, no XZR) +// Condition: sf=1, S=1, imm6=0, rn!=31, rm!=31 +// Param: rd | rn<<8 | rm<<16 (rd=31 allowed for CMN) +.gadget adds_reg_64_nshift + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + ldr x16, [x14, x11, lsl #3] // Rm + adds x3, x15, x16 + store_flags + cmp x9, #31 + b.eq 1f + str x3, [x14, x9, lsl #3] // Rd +1: gret + +// SUBS (register, 64-bit, flag-setting, no shift, no XZR) +// Condition: sf=1, S=1, imm6=0, rn!=31, rm!=31 +// Param: rd | rn<<8 | rm<<16 (rd=31 allowed for CMP) +.gadget subs_reg_64_nshift + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + ldr x16, [x14, x11, lsl #3] // Rm + subs x3, x15, x16 + store_flags + cmp x9, #31 + b.eq 1f + str x3, [x14, x9, lsl #3] // Rd +1: gret + +// ADD (register, 64-bit, no flags, no shift, no XZR/SP) +// Condition: sf=1, S=0, imm6=0, rn!=31, rm!=31, rd!=31 +// Param: rd | rn<<8 | rm<<16 +.gadget add_reg_64_nshift + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + ldr x16, [x14, x11, lsl #3] // Rm + add x17, x15, x16 + str x17, [x14, x9, lsl #3] // Rd + gret + +// SUB (register, 64-bit, no flags, no shift, no XZR/SP) +// Condition: sf=1, S=0, imm6=0, rn!=31, rm!=31, rd!=31 +// Param: rd | rn<<8 | rm<<16 +.gadget sub_reg_64_nshift + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] // Rn + ldr x16, [x14, x11, lsl #3] // Rm + sub x17, x15, x16 + str x17, [x14, x9, lsl #3] // Rd + gret + +/* + * Three-same NEON ops using native instructions (MUL, PMUL, MLA, MLS, + * SMAX, UMAX, SMIN, UMIN). + * + * Macro: make_threesame_native name, op, has_d + * name: gadget name (e.g. mul) + * op: native instruction mnemonic + * has_d: 1 if D-size supported, 0 if not (B/H/S only) + * + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + */ +.macro make_threesame_native name, op, has_d=0 +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .L\name\()_b + cmp x12, #1 + b.eq .L\name\()_h + cmp x12, #2 + b.eq .L\name\()_s +.if \has_d + b .L\name\()_d +.else + b .L\name\()_inv +.endif + +.L\name\()_b: + cbz x17, .L\name\()_b_q0 + \op v0.16b, v0.16b, v1.16b + b .L\name\()_store_q +.L\name\()_b_q0: + \op v0.8b, v0.8b, v1.8b + b .L\name\()_store_low + +.L\name\()_h: + cbz x17, .L\name\()_h_q0 + \op v0.8h, v0.8h, v1.8h + b .L\name\()_store_q +.L\name\()_h_q0: + \op v0.4h, v0.4h, v1.4h + b .L\name\()_store_low + +.L\name\()_s: + cbz x17, .L\name\()_s_q0 + \op v0.4s, v0.4s, v1.4s + b .L\name\()_store_q +.L\name\()_s_q0: + \op v0.2s, v0.2s, v1.2s + b .L\name\()_store_low + +.if \has_d +.L\name\()_d: + cbz x17, .L\name\()_inv + \op v0.2d, v0.2d, v1.2d + b .L\name\()_store_q +.endif + +.L\name\()_inv: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.L\name\()_store_q: + str q0, [x14] + gret + +.L\name\()_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret +.endm + +/* + * Three-same accumulate ops (MLA, MLS). Rd = Rd op Vn * Vm. + * Need to load Vd into v2 first. + * + * Macro: make_threesame_accum name, op + */ +.macro make_threesame_accum name, op +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] // Vn + ldr q1, [x16] // Vm + ldr q2, [x14] // Vd (accumulator) + + cmp x12, #0 + b.eq .L\name\()_b + cmp x12, #1 + b.eq .L\name\()_h + // size=2: S + cbz x17, .L\name\()_s_q0 + \op v2.4s, v0.4s, v1.4s + str q2, [x14] + gret +.L\name\()_s_q0: + \op v2.2s, v0.2s, v1.2s + str d2, [x14] + str xzr, [x14, #8] + gret + +.L\name\()_b: + cbz x17, .L\name\()_b_q0 + \op v2.16b, v0.16b, v1.16b + str q2, [x14] + gret +.L\name\()_b_q0: + \op v2.8b, v0.8b, v1.8b + str d2, [x14] + str xzr, [x14, #8] + gret + +.L\name\()_h: + cbz x17, .L\name\()_h_q0 + \op v2.8h, v0.8h, v1.8h + str q2, [x14] + gret +.L\name\()_h_q0: + \op v2.4h, v0.4h, v1.4h + str d2, [x14] + str xzr, [x14, #8] + gret +.endm + +// Integer multiply (B/H/S only, no D) +make_threesame_native mul, mul, 0 + +// Polynomial multiply (B only — special gadget, gen.c validates size=0) +.gadget pmul_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cbz x17, .Lpmul_q0 + pmul v0.16b, v0.16b, v1.16b + str q0, [x14] + gret +.Lpmul_q0: + pmul v0.8b, v0.8b, v1.8b + str d0, [x14] + str xzr, [x14, #8] + gret + +// Signed/unsigned max/min (B/H/S only, no D) +make_threesame_native smax, smax, 0 +make_threesame_native umax, umax, 0 +make_threesame_native smin, smin, 0 +make_threesame_native umin, umin, 0 + +// Signed max/min pairwise (B/H/S only, no D) +make_threesame_native smaxp, smaxp, 0 +make_threesame_native sminp, sminp, 0 + +/* + * Macro: make_threesame_native_hs name, op + * Like make_threesame_native but only H (size=1) and S (size=2) are valid. + * Used for SQDMULH/SQRDMULH which have no byte or doubleword variants. + */ +.macro make_threesame_native_hs name, op +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #1 + b.eq .L\name\()_h + cmp x12, #2 + b.eq .L\name\()_s + // size 0 (B) and 3 (D) are invalid + b .L\name\()_inv + +.L\name\()_h: + cbz x17, .L\name\()_h_q0 + \op v0.8h, v0.8h, v1.8h + b .L\name\()_store_q +.L\name\()_h_q0: + \op v0.4h, v0.4h, v1.4h + b .L\name\()_store_low + +.L\name\()_s: + cbz x17, .L\name\()_s_q0 + \op v0.4s, v0.4s, v1.4s + b .L\name\()_store_q +.L\name\()_s_q0: + \op v0.2s, v0.2s, v1.2s + b .L\name\()_store_low + +.L\name\()_inv: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.L\name\()_store_q: + str q0, [x14] + gret + +.L\name\()_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret +.endm + +// Signed saturating doubling multiply high (H/S only) +make_threesame_native_hs sqdmulh, sqdmulh +make_threesame_native_hs sqrdmulh, sqrdmulh + +// Signed/unsigned absolute difference (B/H/S only, no D) +make_threesame_native sabd, sabd, 0 +make_threesame_native uabd, uabd, 0 + +// Compare bitwise test (B/H/S/D) +make_threesame_native cmtst, cmtst, 1 + +// Multiply-accumulate and multiply-subtract (B/H/S only) +make_threesame_accum mla, mla +make_threesame_accum mls, mls + +/* + * Two-reg misc native ops (ABS, NEG, CLS, CLZ, etc.) + * + * Macro: make_twomis_native name, op, has_d + * name: gadget name + * op: native instruction mnemonic + * has_d: 1 if D-size supported, 0 if not + * + * Code stream: [gadget addr][rd | rn<<8 | size<<16 | Q<<24] + */ +.macro make_twomis_native name, op, has_d=1 +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #16, #2 // size + ubfx x17, x8, #24, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + ldr q0, [x15] + + cmp x12, #0 + b.eq .L\name\()_b + cmp x12, #1 + b.eq .L\name\()_h + cmp x12, #2 + b.eq .L\name\()_s +.if \has_d + b .L\name\()_d +.else + b .L\name\()_inv +.endif + +.L\name\()_b: + cbz x17, .L\name\()_b_q0 + \op v0.16b, v0.16b + b .L\name\()_store_q +.L\name\()_b_q0: + \op v0.8b, v0.8b + b .L\name\()_store_low + +.L\name\()_h: + cbz x17, .L\name\()_h_q0 + \op v0.8h, v0.8h + b .L\name\()_store_q +.L\name\()_h_q0: + \op v0.4h, v0.4h + b .L\name\()_store_low + +.L\name\()_s: + cbz x17, .L\name\()_s_q0 + \op v0.4s, v0.4s + b .L\name\()_store_q +.L\name\()_s_q0: + \op v0.2s, v0.2s + b .L\name\()_store_low + +.if \has_d +.L\name\()_d: + cbz x17, .L\name\()_inv + \op v0.2d, v0.2d + b .L\name\()_store_q +.endif + +.L\name\()_inv: + str xzr, [x14] + str xzr, [x14, #8] + gret + +.L\name\()_store_q: + str q0, [x14] + gret + +.L\name\()_store_low: + str d0, [x14] + str xzr, [x14, #8] + gret +.endm + +make_twomis_native abs, abs, 1 +make_twomis_native neg, neg, 1 +make_twomis_native clz, clz, 0 +make_twomis_native cls, cls, 0 + +/* + * NOT/RBIT vector (bytes only: .8B/.16B) + * Code stream: [gadget addr][rd | rn<<8 | Q<<16] + */ +.macro make_byte_vec_unary name, insn +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x17, x8, #16, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + + ldr q0, [x15] + + cbz x17, .L\name\()_8b + \insn v0.16b, v0.16b + str q0, [x14] + gret +.L\name\()_8b: + \insn v0.8b, v0.8b + str d0, [x14] + str xzr, [x14, #8] + gret +.endm + +make_byte_vec_unary not, not +// rbit_vec already defined above (line ~5408) + +/* + * Three-different widening "long" ops (UADDL, SADDL, USUBL, SSUBL, UMULL, SMULL, UABDL, SABDL). + * Both Vn and Vm are narrow; Vd is wide. + * Q=0: lower half, Q=1: upper half (op2 variant). + * + * Macro: make_widening_long name, op + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + */ +.macro make_widening_long name, op +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] + ldr q1, [x16] + + cmp x12, #0 + b.eq .L\name\()_b + cmp x12, #1 + b.eq .L\name\()_h + // size == 2 (S->D) + cbz x17, .L\name\()_s_lo + \op\()2 v0.2d, v0.4s, v1.4s + b .L\name\()_store +.L\name\()_s_lo: + \op v0.2d, v0.2s, v1.2s + b .L\name\()_store + +.L\name\()_b: + cbz x17, .L\name\()_b_lo + \op\()2 v0.8h, v0.16b, v1.16b + b .L\name\()_store +.L\name\()_b_lo: + \op v0.8h, v0.8b, v1.8b + b .L\name\()_store + +.L\name\()_h: + cbz x17, .L\name\()_h_lo + \op\()2 v0.4s, v0.8h, v1.8h + b .L\name\()_store +.L\name\()_h_lo: + \op v0.4s, v0.4h, v1.4h + // fall through + +.L\name\()_store: + str q0, [x14] + gret +.endm + +/* + * Saturating shift-right-and-narrow instructions (UQRSHRN, SQRSHRN, etc.) + * Similar to SHRN but uses saturating narrowing (uqxtn/sqxtn/sqxtun). + * + * Macro: make_sat_shrn name, shift_op_prefix, narrow_8b, narrow_16b, narrow_4h, narrow_8h, narrow_2s, narrow_4s + * name: gadget name + * shift_op_prefix: urshl or srshl (for rounding) or ushl/sshl (non-rounding) + * narrow_*: native saturating narrow instruction for each size + * + * Code stream: [gadget addr][rd | rn<<8 | shift<<16 | esize<<24 | Q<<28] + */ +.macro make_sat_shrn name, sop, n8b, n16b, n4h, n8h, n2s, n4s +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #8 // shift amount + ubfx x12, x8, #24, #4 // esize (0=B, 1=H, 2=S - narrow target) + ubfx x17, x8, #28, #1 // Q + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + ldr q0, [x15] // load source (wide elements) + ldr q2, [x14] // load dest (for Q=1 preserve lower) + neg x11, x11 // negative shift for right shift + cmp x12, #2 + b.eq .L\name\()_2d + cmp x12, #1 + b.eq .L\name\()_4s + // esize=0: 8H→8B + dup v1.8h, w11 + \sop v0.8h, v0.8h, v1.8h + cbz x17, .L\name\()_8h_lo + \n16b + str q2, [x14] + gret +.L\name\()_8h_lo: + \n8b + str d2, [x14] + str xzr, [x14, #8] + gret +.L\name\()_4s: + dup v1.4s, w11 + \sop v0.4s, v0.4s, v1.4s + cbz x17, .L\name\()_4s_lo + \n8h + str q2, [x14] + gret +.L\name\()_4s_lo: + \n4h + str d2, [x14] + str xzr, [x14, #8] + gret +.L\name\()_2d: + dup v1.2d, x11 + \sop v0.2d, v0.2d, v1.2d + cbz x17, .L\name\()_2d_lo + \n4s + str q2, [x14] + gret +.L\name\()_2d_lo: + \n2s + str d2, [x14] + str xzr, [x14, #8] + gret +.endm + +// UQRSHRN: unsigned rounding shift right + unsigned saturating narrow +make_sat_shrn uqrshrn, urshl, "uqxtn v2.8b, v0.8h", "uqxtn2 v2.16b, v0.8h", "uqxtn v2.4h, v0.4s", "uqxtn2 v2.8h, v0.4s", "uqxtn v2.2s, v0.2d", "uqxtn2 v2.4s, v0.2d" +// SQRSHRN: signed rounding shift right + signed saturating narrow +make_sat_shrn sqrshrn, srshl, "sqxtn v2.8b, v0.8h", "sqxtn2 v2.16b, v0.8h", "sqxtn v2.4h, v0.4s", "sqxtn2 v2.8h, v0.4s", "sqxtn v2.2s, v0.2d", "sqxtn2 v2.4s, v0.2d" +// UQSHRN: unsigned shift right (truncate) + unsigned saturating narrow +make_sat_shrn uqshrn, ushl, "uqxtn v2.8b, v0.8h", "uqxtn2 v2.16b, v0.8h", "uqxtn v2.4h, v0.4s", "uqxtn2 v2.8h, v0.4s", "uqxtn v2.2s, v0.2d", "uqxtn2 v2.4s, v0.2d" +// SQSHRN: signed shift right (truncate) + signed saturating narrow +make_sat_shrn sqshrn, sshl, "sqxtn v2.8b, v0.8h", "sqxtn2 v2.16b, v0.8h", "sqxtn v2.4h, v0.4s", "sqxtn2 v2.8h, v0.4s", "sqxtn v2.2s, v0.2d", "sqxtn2 v2.4s, v0.2d" +// SQSHRUN: signed rounding shift right + unsigned saturating narrow from signed +make_sat_shrn sqshrun, sshl, "sqxtun v2.8b, v0.8h", "sqxtun2 v2.16b, v0.8h", "sqxtun v2.4h, v0.4s", "sqxtun2 v2.8h, v0.4s", "sqxtun v2.2s, v0.2d", "sqxtun2 v2.4s, v0.2d" +// SQRSHRUN: signed rounding shift right + unsigned saturating narrow from signed +make_sat_shrn sqrshrun, srshl, "sqxtun v2.8b, v0.8h", "sqxtun2 v2.16b, v0.8h", "sqxtun v2.4h, v0.4s", "sqxtun2 v2.8h, v0.4s", "sqxtun v2.2s, v0.2d", "sqxtun2 v2.4s, v0.2d" + +/* + * Indexed-element helpers: extract element[index] from Vm and DUP to v1. + * + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | index<<21 | size<<24 | Q<<26] + * + * Helper macro: elem_setup name + * Parses code stream, loads Vn→v0, extracts Vm[index]→v1 (dup'd). + * Sets x14→&Vd, x17=Q, x12=size. + */ +.macro elem_setup name +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x20, x8, #21, #3 // index + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] // Vn + ldr q1, [x16] // Vm (will be replaced by dup of element) + + // DUP element from v1 based on size and index + cmp x12, #1 + b.eq .L\name\()_dup_h + cmp x12, #2 + b.eq .L\name\()_dup_s + // size=3: D + cbnz x20, .L\name\()_dup_d1 + dup v1.2d, v1.d[0] + b .L\name\()_op +.L\name\()_dup_d1: + dup v1.2d, v1.d[1] + b .L\name\()_op +.L\name\()_dup_h: + cmp x20, #0 + b.eq .L\name\()_dup_h0 + cmp x20, #1 + b.eq .L\name\()_dup_h1 + cmp x20, #2 + b.eq .L\name\()_dup_h2 + cmp x20, #3 + b.eq .L\name\()_dup_h3 + cmp x20, #4 + b.eq .L\name\()_dup_h4 + cmp x20, #5 + b.eq .L\name\()_dup_h5 + cmp x20, #6 + b.eq .L\name\()_dup_h6 + dup v1.8h, v1.h[7] + b .L\name\()_op +.L\name\()_dup_h0: + dup v1.8h, v1.h[0] + b .L\name\()_op +.L\name\()_dup_h1: + dup v1.8h, v1.h[1] + b .L\name\()_op +.L\name\()_dup_h2: + dup v1.8h, v1.h[2] + b .L\name\()_op +.L\name\()_dup_h3: + dup v1.8h, v1.h[3] + b .L\name\()_op +.L\name\()_dup_h4: + dup v1.8h, v1.h[4] + b .L\name\()_op +.L\name\()_dup_h5: + dup v1.8h, v1.h[5] + b .L\name\()_op +.L\name\()_dup_h6: + dup v1.8h, v1.h[6] + b .L\name\()_op +.L\name\()_dup_s: + cmp x20, #0 + b.eq .L\name\()_dup_s0 + cmp x20, #1 + b.eq .L\name\()_dup_s1 + cmp x20, #2 + b.eq .L\name\()_dup_s2 + dup v1.4s, v1.s[3] + b .L\name\()_op +.L\name\()_dup_s0: + dup v1.4s, v1.s[0] + b .L\name\()_op +.L\name\()_dup_s1: + dup v1.4s, v1.s[1] + b .L\name\()_op +.L\name\()_dup_s2: + dup v1.4s, v1.s[2] + b .L\name\()_op +.endm + +/* + * Macro: elem_op_store name, op — perform the operation and store + * v0=Vn, v1=Vm[idx] dup'd, x14=&Vd, x12=size, x17=Q + */ +.macro elem_op_store name, op +.L\name\()_op: + cmp x12, #1 + b.eq .L\name\()_op_h + // size=2: S + cbz x17, .L\name\()_op_s_q0 + \op v0.4s, v0.4s, v1.4s + str q0, [x14] + gret +.L\name\()_op_s_q0: + \op v0.2s, v0.2s, v1.2s + str d0, [x14] + str xzr, [x14, #8] + gret +.L\name\()_op_h: + cbz x17, .L\name\()_op_h_q0 + \op v0.8h, v0.8h, v1.8h + str q0, [x14] + gret +.L\name\()_op_h_q0: + \op v0.4h, v0.4h, v1.4h + str d0, [x14] + str xzr, [x14, #8] + gret +.endm + +// MUL by element +elem_setup mul_elem +elem_op_store mul_elem, mul + +/* + * MLA/MLS by element — accumulate variants need Vd loaded into v2. + */ +.macro elem_accum_op_store name, op +.L\name\()_op: + ldr q2, [x14] // Vd (accumulator) + cmp x12, #1 + b.eq .L\name\()_op_h + cbz x17, .L\name\()_op_s_q0 + \op v2.4s, v0.4s, v1.4s + str q2, [x14] + gret +.L\name\()_op_s_q0: + \op v2.2s, v0.2s, v1.2s + str d2, [x14] + str xzr, [x14, #8] + gret +.L\name\()_op_h: + cbz x17, .L\name\()_op_h_q0 + \op v2.8h, v0.8h, v1.8h + str q2, [x14] + gret +.L\name\()_op_h_q0: + \op v2.4h, v0.4h, v1.4h + str d2, [x14] + str xzr, [x14, #8] + gret +.endm + +elem_setup mla_elem +elem_accum_op_store mla_elem, mla + +elem_setup mls_elem +elem_accum_op_store mls_elem, mls + +/* + * FP multiply by element (FMUL/FMLA/FMLS by element) + * Uses elem_setup for parameter parsing and element DUP. + * size=2: float (S), size=3: double (D) + */ +.macro elem_fp_op_store name, op +.L\name\()_op: + cmp x12, #3 + b.eq .L\name\()_op_d + // size=2: S (float) + cbz x17, .L\name\()_op_s_q0 + \op v0.4s, v0.4s, v1.4s + str q0, [x14] + gret +.L\name\()_op_s_q0: + \op v0.2s, v0.2s, v1.2s + str d0, [x14] + str xzr, [x14, #8] + gret +.L\name\()_op_d: + // size=3: D (double), Q must be 1 for 2D + \op v0.2d, v0.2d, v1.2d + str q0, [x14] + gret +.endm + +.macro elem_fp_accum_op_store name, op +.L\name\()_op: + ldr q2, [x14] // Vd (accumulator) + cmp x12, #3 + b.eq .L\name\()_op_d + // size=2: S (float) + cbz x17, .L\name\()_op_s_q0 + \op v2.4s, v0.4s, v1.4s + str q2, [x14] + gret +.L\name\()_op_s_q0: + \op v2.2s, v0.2s, v1.2s + str d2, [x14] + str xzr, [x14, #8] + gret +.L\name\()_op_d: + // size=3: D (double), Q must be 1 for 2D + \op v2.2d, v0.2d, v1.2d + str q2, [x14] + gret +.endm + +// FMUL by element +elem_setup fmul_elem +elem_fp_op_store fmul_elem, fmul + +// FMLA by element +elem_setup fmla_elem +elem_fp_accum_op_store fmla_elem, fmla + +// FMLS by element +elem_setup fmls_elem +elem_fp_accum_op_store fmls_elem, fmls + +/* + * Scalar FP multiply by element (FMUL/FMLA/FMLS/FMULX Sd/Dd, Sn/Dn, Vm[idx]) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | index<<21 | size<<24] + * size=2: single, size=3: double + */ +.macro scalar_elem_setup name +.gadget \name\()_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x20, x8, #21, #3 // index + ubfx x12, x8, #24, #2 // size + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + cmp x12, #3 + b.eq .L\name\()_scalar_d + + // size=2: single precision + ldr s0, [x15] // Sn + // Extract Vm.s[index] + ldr q1, [x16] + cmp x20, #0 + b.eq .L\name\()_scalar_s_idx0 + cmp x20, #1 + b.eq .L\name\()_scalar_s_idx1 + cmp x20, #2 + b.eq .L\name\()_scalar_s_idx2 + mov s1, v1.s[3] + b .L\name\()_scalar_s_op +.L\name\()_scalar_s_idx0: + // s1 already has v1.s[0] from ldr q1 + mov s1, v1.s[0] + b .L\name\()_scalar_s_op +.L\name\()_scalar_s_idx1: + mov s1, v1.s[1] + b .L\name\()_scalar_s_op +.L\name\()_scalar_s_idx2: + mov s1, v1.s[2] + b .L\name\()_scalar_s_op + +.L\name\()_scalar_d: + // size=3: double precision + ldr d0, [x15] // Dn + ldr q1, [x16] + cbz x20, .L\name\()_scalar_d_idx0 + mov d1, v1.d[1] + b .L\name\()_scalar_d_op +.L\name\()_scalar_d_idx0: + mov d1, v1.d[0] + b .L\name\()_scalar_d_op +.endm + +.macro scalar_elem_fp_op name, op +.L\name\()_scalar_s_op: + \op s0, s0, s1 + str s0, [x14] + str xzr, [x14, #4] + str xzr, [x14, #8] + gret +.L\name\()_scalar_d_op: + \op d0, d0, d1 + str d0, [x14] + str xzr, [x14, #8] + gret +.endm + +.macro scalar_elem_fp_fmadd_op name +.L\name\()_scalar_s_op: + ldr s2, [x14] // Sd (accumulator) + fmadd s2, s0, s1, s2 // Sd = Sn * Sm[idx] + Sd + str s2, [x14] + str xzr, [x14, #4] + str xzr, [x14, #8] + gret +.L\name\()_scalar_d_op: + ldr d2, [x14] // Dd (accumulator) + fmadd d2, d0, d1, d2 // Dd = Dn * Dm[idx] + Dd + str d2, [x14] + str xzr, [x14, #8] + gret +.endm + +.macro scalar_elem_fp_fmsub_op name +.L\name\()_scalar_s_op: + ldr s2, [x14] // Sd (accumulator) + fmsub s2, s0, s1, s2 // Sd = -(Sn * Sm[idx]) + Sd = Sd - Sn*Sm[idx] + str s2, [x14] + str xzr, [x14, #4] + str xzr, [x14, #8] + gret +.L\name\()_scalar_d_op: + ldr d2, [x14] // Dd (accumulator) + fmsub d2, d0, d1, d2 // Dd = -(Dn * Dm[idx]) + Dd + str d2, [x14] + str xzr, [x14, #8] + gret +.endm + +// FMUL scalar by element +scalar_elem_setup fmul_elem +scalar_elem_fp_op fmul_elem, fmul + +// FMLA scalar by element: Sd += Sn * Vm.s[idx] +scalar_elem_setup fmla_elem +scalar_elem_fp_fmadd_op fmla_elem + +// FMLS scalar by element: Sd -= Sn * Vm.s[idx] +scalar_elem_setup fmls_elem +scalar_elem_fp_fmsub_op fmls_elem + +// FMULX scalar by element +scalar_elem_setup fmulx_elem +scalar_elem_fp_op fmulx_elem, fmulx + +/* + * Widening multiply by element (SMULL/UMULL/SMLAL/UMLAL/SMLSL/UMLSL by element) + * v0=Vn (narrow), v1=Vm[idx] dup'd, x14=&Vd (wide result), x12=size, x17=Q + */ +.macro elem_widen_op_store name, op +.L\name\()_op: + cmp x12, #1 + b.eq .L\name\()_op_h + cmp x12, #2 + b.eq .L\name\()_op_s + // size=3 not valid for widening + str xzr, [x14] + str xzr, [x14, #8] + gret +.L\name\()_op_h: + cbz x17, .L\name\()_op_h_lo + \op\()2 v0.4s, v0.8h, v1.8h + b .L\name\()_op_store +.L\name\()_op_h_lo: + \op v0.4s, v0.4h, v1.4h + b .L\name\()_op_store +.L\name\()_op_s: + cbz x17, .L\name\()_op_s_lo + \op\()2 v0.2d, v0.4s, v1.4s + b .L\name\()_op_store +.L\name\()_op_s_lo: + \op v0.2d, v0.2s, v1.2s +.L\name\()_op_store: + str q0, [x14] + gret +.endm + +elem_setup smull_elem +elem_widen_op_store smull_elem, smull + +elem_setup umull_elem +elem_widen_op_store umull_elem, umull + +/* + * Widening multiply-accumulate by element (SMLAL/UMLAL/SMLSL/UMLSL by element) + * Need to load Vd (wide accumulator) into v2 first. + */ +.macro elem_widen_accum_op_store name, op +.L\name\()_op: + ldr q2, [x14] // Vd (wide accumulator) + cmp x12, #1 + b.eq .L\name\()_op_h + cmp x12, #2 + b.eq .L\name\()_op_s + str xzr, [x14] + str xzr, [x14, #8] + gret +.L\name\()_op_h: + cbz x17, .L\name\()_op_h_lo + \op\()2 v2.4s, v0.8h, v1.8h + b .L\name\()_op_store +.L\name\()_op_h_lo: + \op v2.4s, v0.4h, v1.4h + b .L\name\()_op_store +.L\name\()_op_s: + cbz x17, .L\name\()_op_s_lo + \op\()2 v2.2d, v0.4s, v1.4s + b .L\name\()_op_store +.L\name\()_op_s_lo: + \op v2.2d, v0.2s, v1.2s +.L\name\()_op_store: + str q2, [x14] + gret +.endm + +elem_setup smlal_elem +elem_widen_accum_op_store smlal_elem, smlal + +elem_setup umlal_elem +elem_widen_accum_op_store umlal_elem, umlal + +elem_setup smlsl_elem +elem_widen_accum_op_store smlsl_elem, smlsl + +elem_setup umlsl_elem +elem_widen_accum_op_store umlsl_elem, umlsl + +// SQDMULH by element (H/S only, non-widening) +elem_setup sqdmulh_elem +elem_op_store sqdmulh_elem, sqdmulh + +// SQRDMULH by element (H/S only, non-widening) +elem_setup sqrdmulh_elem +elem_op_store sqrdmulh_elem, sqrdmulh + +// SQDMULL by element (widening: H→S, S→D) +elem_setup sqdmull_elem +elem_widen_op_store sqdmull_elem, sqdmull + +// SQDMLAL by element (widening accumulate) +elem_setup sqdmlal_elem +elem_widen_accum_op_store sqdmlal_elem, sqdmlal + +// SQDMLSL by element (widening subtract-accumulate) +elem_setup sqdmlsl_elem +elem_widen_accum_op_store sqdmlsl_elem, sqdmlsl + +make_widening_long saddl, saddl +make_widening_long uaddl, uaddl +make_widening_long ssubl, ssubl +make_widening_long usubl, usubl +make_widening_long smull, smull +make_widening_long umull, umull +make_widening_long sabdl, sabdl +make_widening_long uabdl, uabdl + +/* + * Macro: make_narrowing_high name, op + * ADDHN/SUBHN/RADDHN/RSUBHN - add/sub wide operands, return high narrow result + * Direction: Vn(wide) op Vm(wide) → Vd(narrow, high half) + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * size: narrow target element size (0=B, 1=H, 2=S) + * Q: 0=lower half, 1=upper half (writes to upper half of Vd) + */ +.macro make_narrowing_high name, op +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size (narrow target) + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x15] // Vn (wide) + ldr q1, [x16] // Vm (wide) + ldr q2, [x14] // Vd (preserve for Q=1) + + cmp x12, #0 + b.eq .L\name\()_b + cmp x12, #1 + b.eq .L\name\()_h + // size == 2: S narrow (D+D→S) + cbz x17, .L\name\()_s_lo + \op\()2 v2.4s, v0.2d, v1.2d + b .L\name\()_store +.L\name\()_s_lo: + \op v2.2s, v0.2d, v1.2d + b .L\name\()_store_lo + +.L\name\()_b: + // size == 0: B narrow (H+H→B) + cbz x17, .L\name\()_b_lo + \op\()2 v2.16b, v0.8h, v1.8h + b .L\name\()_store +.L\name\()_b_lo: + \op v2.8b, v0.8h, v1.8h + b .L\name\()_store_lo + +.L\name\()_h: + // size == 1: H narrow (S+S→H) + cbz x17, .L\name\()_h_lo + \op\()2 v2.8h, v0.4s, v1.4s + b .L\name\()_store +.L\name\()_h_lo: + \op v2.4h, v0.4s, v1.4s + // fall through + +.L\name\()_store_lo: + str d2, [x14] + str xzr, [x14, #8] + gret + +.L\name\()_store: + str q2, [x14] + gret +.endm + +make_narrowing_high addhn, addhn +make_narrowing_high subhn, subhn +make_narrowing_high raddhn, raddhn +make_narrowing_high rsubhn, rsubhn + +/* + * Macro: make_widening_accum name, op + * SABAL/UABAL/SMLAL/UMLAL/SMLSL/UMLSL (three-different accumulating) + * Accumulate: Vd += op(Vn, Vm) with widening + * Code stream: [gadget addr][rd | rn<<8 | rm<<16 | size<<24 | Q<<26] + * size: narrow source element size (0=B, 1=H, 2=S) + * Q: 0=lower half, 1=upper half of narrow source + */ +.macro make_widening_accum name, op +.gadget \name\()_vec + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x11, x8, #16, #5 // rm + ubfx x12, x8, #24, #2 // size + ubfx x17, x8, #26, #1 // Q + + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + lsl x16, x11, #4 + add x16, x13, x16 // &Vm + + ldr q0, [x14] // Vd (accumulator, wide) + ldr q1, [x15] // Vn (narrow source) + ldr q2, [x16] // Vm (narrow source) + + cmp x12, #0 + b.eq .L\name\()_b + cmp x12, #1 + b.eq .L\name\()_h + // size == 2 (S->D) + cbz x17, .L\name\()_s_lo + \op\()2 v0.2d, v1.4s, v2.4s + b .L\name\()_store +.L\name\()_s_lo: + \op v0.2d, v1.2s, v2.2s + b .L\name\()_store + +.L\name\()_b: + cbz x17, .L\name\()_b_lo + \op\()2 v0.8h, v1.16b, v2.16b + b .L\name\()_store +.L\name\()_b_lo: + \op v0.8h, v1.8b, v2.8b + b .L\name\()_store + +.L\name\()_h: + cbz x17, .L\name\()_h_lo + \op\()2 v0.4s, v1.8h, v2.8h + b .L\name\()_store +.L\name\()_h_lo: + \op v0.4s, v1.4h, v2.4h + // fall through + +.L\name\()_store: + str q0, [x14] + gret +.endm + +make_widening_accum sabal, sabal +make_widening_accum uabal, uabal +make_widening_accum smlal, smlal +make_widening_accum umlal, umlal +make_widening_accum smlsl, smlsl +make_widening_accum umlsl, umlsl + +/* + * Scalar two-register miscellaneous (integer, 64-bit only) + * Compare-against-zero and unary operations on a single D register. + * Code stream: [gadget addr][rd | rn<<8] + */ + +// CMGT D, D, #0 — each element set to all-ones if > 0, else all-zeros +.gadget cmgt_scalar_zero + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + ldr d0, [x15] + cmgt d0, d0, #0 + str d0, [x14] + str xzr, [x14, #8] // clear upper 64 bits + gret + +// CMGE D, D, #0 +.gadget cmge_scalar_zero + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + ldr d0, [x15] + cmge d0, d0, #0 + str d0, [x14] + str xzr, [x14, #8] + gret + +// CMEQ D, D, #0 +.gadget cmeq_scalar_zero + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + ldr d0, [x15] + cmeq d0, d0, #0 + str d0, [x14] + str xzr, [x14, #8] + gret + +// CMLE D, D, #0 +.gadget cmle_scalar_zero + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + ldr d0, [x15] + cmle d0, d0, #0 + str d0, [x14] + str xzr, [x14, #8] + gret + +// CMLT D, D, #0 +.gadget cmlt_scalar_zero + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + ldr d0, [x15] + cmlt d0, d0, #0 + str d0, [x14] + str xzr, [x14, #8] + gret + +// ABS D, D — absolute value +.gadget abs_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + ldr d0, [x15] + abs d0, d0 + str d0, [x14] + str xzr, [x14, #8] + gret + +// NEG D, D — negate +.gadget neg_scalar + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + ldr d0, [x15] + neg d0, d0 + str d0, [x14] + str xzr, [x14, #8] + gret + +/* + * FP scalar two-register miscellaneous — compare against zero + * Code stream: [gadget addr][rd | rn<<8 | sz<<16] + * sz=0: single precision, sz=1: double precision + */ + +// FCMGT S/D, S/D, #0.0 +.gadget fcmgt_scalar_zero + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rd + ubfx x10, x8, #8, #5 // rn + ubfx x12, x8, #16, #1 // sz (0=single, 1=double) + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 // &Vd + lsl x15, x10, #4 + add x15, x13, x15 // &Vn + cbnz x12, .Lfcmgt_scalar_zero_double + ldr s0, [x15] + fcmgt s0, s0, #0.0 + str s0, [x14] + str xzr, [x14, #4] + str xzr, [x14, #8] + gret +.Lfcmgt_scalar_zero_double: + ldr d0, [x15] + fcmgt d0, d0, #0.0 + str d0, [x14] + str xzr, [x14, #8] + gret + +// FCMGE S/D, S/D, #0.0 +.gadget fcmge_scalar_zero + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x12, x8, #16, #1 + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + cbnz x12, .Lfcmge_scalar_zero_double + ldr s0, [x15] + fcmge s0, s0, #0.0 + str s0, [x14] + str xzr, [x14, #4] + str xzr, [x14, #8] + gret +.Lfcmge_scalar_zero_double: + ldr d0, [x15] + fcmge d0, d0, #0.0 + str d0, [x14] + str xzr, [x14, #8] + gret + +// FCMEQ S/D, S/D, #0.0 +.gadget fcmeq_scalar_zero + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x12, x8, #16, #1 + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + cbnz x12, .Lfcmeq_scalar_zero_double + ldr s0, [x15] + fcmeq s0, s0, #0.0 + str s0, [x14] + str xzr, [x14, #4] + str xzr, [x14, #8] + gret +.Lfcmeq_scalar_zero_double: + ldr d0, [x15] + fcmeq d0, d0, #0.0 + str d0, [x14] + str xzr, [x14, #8] + gret + +// FCMLE S/D, S/D, #0.0 +.gadget fcmle_scalar_zero + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x12, x8, #16, #1 + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + cbnz x12, .Lfcmle_scalar_zero_double + ldr s0, [x15] + fcmle s0, s0, #0.0 + str s0, [x14] + str xzr, [x14, #4] + str xzr, [x14, #8] + gret +.Lfcmle_scalar_zero_double: + ldr d0, [x15] + fcmle d0, d0, #0.0 + str d0, [x14] + str xzr, [x14, #8] + gret + +// FCMLT S/D, S/D, #0.0 +.gadget fcmlt_scalar_zero + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f + ubfx x10, x8, #8, #5 + ubfx x12, x8, #16, #1 + add x13, _cpu, #CPU_fp + lsl x14, x9, #4 + add x14, x13, x14 + lsl x15, x10, #4 + add x15, x13, x15 + cbnz x12, .Lfcmlt_scalar_zero_double + ldr s0, [x15] + fcmlt s0, s0, #0.0 + str s0, [x14] + str xzr, [x14, #4] + str xzr, [x14, #8] + gret +.Lfcmlt_scalar_zero_double: + ldr d0, [x15] + fcmlt d0, d0, #0.0 + str d0, [x14] + str xzr, [x14, #8] + gret diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/memory.S b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/memory.S new file mode 100644 index 0000000000..a1baee04ac --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gadgets-aarch64/memory.S @@ -0,0 +1,4040 @@ +/* + * ARM64 Guest Memory Access Gadgets + * + * These gadgets handle memory load and store operations for ARM64 guest code. + * Address is calculated and stored in _addr (x7) before load/store gadgets. + * + * Most operations use inline TLB lookup for fast-path performance. + * Cross-page accesses and TLB misses fall through to C helpers. + */ + +#include "gadgets.h" + +.text + +/* + * Address calculation gadgets + */ + +// Calculate address from base register + immediate offset +// Code stream: [gadget addr][rn | offset<<8] +// offset is a signed immediate starting at bit 8 +// The width varies: imm9 for pre/post-indexed, larger for LDP/STP +// Using 16-bit signed extraction to handle all cases (max ±32K) +.gadget calc_addr_imm + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rn + // Extract offset from bits 8+ (arithmetic shift right preserves sign for negative offsets, + // and handles large unsigned offsets like SIMD Q-class up to 65520) + asr x10, x8, #8 + + // Load base register (or SP if rn == 31) + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x12, [x11, x9, lsl #3] + b 2f +1: ldr x12, [_cpu, #CPU_sp] +2: + // Calculate address (64-bit for 48-bit address space) + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + + // Save guest address for writeback_addr (read_prep will clobber _addr + // with a host pointer, but pre-indexed LDP/STP need the guest address) + str _addr, [_cpu, #LOCAL_value_addr] + + gret + +// Calculate address for PC-relative literal loads +// Code stream: [gadget addr][64-bit target address] +// Used for LDR (literal) instructions +.gadget calc_addr_pc_rel + ldr _addr, [_pc] + add _pc, _pc, #8 + gret + +// Calculate address from base register + register offset +// Code stream: [gadget addr][rn | rm<<8 | extend<<16 | shift<<24] +.gadget calc_addr_reg + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rn + ubfx x10, x8, #8, #5 // rm + ubfx x11, x8, #16, #3 // extend type + ubfx x12, x8, #24, #3 // shift amount + + // Load base register (or SP if rn == 31) + add x13, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x14, [x13, x9, lsl #3] + b 2f +1: ldr x14, [_cpu, #CPU_sp] +2: + // Load index register + cmp x10, #31 + b.eq 3f + ldr x15, [x13, x10, lsl #3] + b 4f +3: mov x15, #0 +4: + // Apply extend based on option + // option values: 0=UXTB,1=UXTH,2=UXTW,3=UXTX,4=SXTB,5=SXTH,6=SXTW,7=SXTX + cmp x11, #4 + b.ge 6f + cmp x11, #0 + b.eq 5f + cmp x11, #1 + b.eq 7f + cmp x11, #2 + b.eq 8f + b 9f // option==3 (UXTX) no-op +5: and x15, x15, #0xff + b 9f +7: and x15, x15, #0xffff + b 9f +8: and x15, x15, #0xffffffff + b 9f +6: cmp x11, #4 + b.eq 10f + cmp x11, #5 + b.eq 11f + cmp x11, #6 + b.eq 12f + b 9f // option==7 (SXTX) no-op +10: sxtb x15, w15 + b 9f +11: sxth x15, w15 + b 9f +12: sxtw x15, w15 +9: + // Apply shift + lsl x15, x15, x12 + + // Calculate address (64-bit for 48-bit address space) + add _addr, x14, x15 + and _addr, _addr, #0xffffffffffff + gret + +/* + * Load gadgets with inline TLB lookup + * Address should be in _addr (x7) + * Result goes to _tmp (x0) + * + * Fast path: inline TLB lookup (~12 instructions on TLB hit) + * Slow path: call handle_read_miss on TLB miss, crosspage_load on page crossing + */ + +// LDR Xn, [addr] - 64-bit load (inline TLB) +.gadget load64 + mov x24, _addr + read_prep 64, load64_1 + ldr _tmp, [_addr] + mov _addr, x24 + gret + read_bullshit 64, load64_1 + +// LDR Wn, [addr] - 32-bit load (inline TLB) +.gadget load32 + mov x24, _addr + read_prep 32, load32_1 + ldr w0, [_addr] + mov _addr, x24 + gret + read_bullshit 32, load32_1 + +// LDRH Wn, [addr] - 16-bit load (inline TLB) +.gadget load16 + mov x24, _addr + read_prep 16, load16_1 + ldrh w0, [_addr] + mov _addr, x24 + gret + read_bullshit 16, load16_1 + +// LDRB Wn, [addr] - 8-bit load (inline TLB) +.gadget load8 + mov x24, _addr + read_prep 8, load8_1 + ldrb w0, [_addr] + mov _addr, x24 + gret + read_bullshit 8, load8_1 + +// LDRSW Xn, [addr] - 32-bit load with sign-extend to 64 (inline TLB) +.gadget load32_sx + mov x24, _addr + read_prep 32, load32_sx_1 + ldrsw _tmp, [_addr] + mov _addr, x24 + gret + read_bullshit 32, load32_sx_1 + +// LDRSH Wn, [addr] - 16-bit load with sign-extend to 32 (inline TLB) +.gadget load16_sx32 + mov x24, _addr + read_prep 16, load16_sx32_1 + ldrsh w0, [_addr] + mov _addr, x24 + gret + read_bullshit 16, load16_sx32_1 + +// LDRSH Xn, [addr] - 16-bit load with sign-extend to 64 (inline TLB) +.gadget load16_sx64 + mov x24, _addr + read_prep 16, load16_sx64_1 + ldrsh _tmp, [_addr] + mov _addr, x24 + gret + read_bullshit 16, load16_sx64_1 + +// LDRSB Wn, [addr] - 8-bit load with sign-extend to 32 (inline TLB) +.gadget load8_sx32 + mov x24, _addr + read_prep 8, load8_sx32_1 + ldrsb w0, [_addr] + mov _addr, x24 + gret + read_bullshit 8, load8_sx32_1 + +// LDRSB Xn, [addr] - 8-bit load with sign-extend to 64 (inline TLB) +.gadget load8_sx64 + mov x24, _addr + read_prep 8, load8_sx64_1 + ldrsb _tmp, [_addr] + mov _addr, x24 + gret + read_bullshit 8, load8_sx64_1 + +/* + * Store gadgets with inline TLB lookup + * Address should be in _addr (x7), value in _tmp (x0) + * write_prep uses x8-x10, preserving x0 (the value) and x11+ + */ + +// STR Xn, [addr] - 64-bit store (inline TLB) +.gadget store64 + mov x24, _addr + mov x11, x0 // save 64-bit value (x11 not clobbered by write_prep) + write_prep 64, store64_1 + str x11, [_addr] + write_done 64, store64_1 + mov _addr, x24 + gret + write_bullshit 64, store64_1 + +// STR Wn, [addr] - 32-bit store (inline TLB) +.gadget store32 + mov x24, _addr + mov w11, w0 + write_prep 32, store32_1 + str w11, [_addr] + write_done 32, store32_1 + mov _addr, x24 + gret + write_bullshit 32, store32_1 + +// STRH Wn, [addr] - 16-bit store (inline TLB) +.gadget store16 + mov x24, _addr + mov w11, w0 + write_prep 16, store16_1 + strh w11, [_addr] + write_done 16, store16_1 + mov _addr, x24 + gret + write_bullshit 16, store16_1 + +// STRB Wn, [addr] - 8-bit store (inline TLB) +.gadget store8 + mov x24, _addr + mov w11, w0 + write_prep 8, store8_1 + strb w11, [_addr] + write_done 8, store8_1 + mov _addr, x24 + gret + write_bullshit 8, store8_1 + +/* + * Fused load/store gadgets for unsigned-offset addressing + * + * These combine calc_addr_imm + load/store + store_reg/load_reg into a single + * gadget dispatch, eliminating 2 gret calls (4 host instructions) per operation. + * + * Code stream: [gadget addr][rd_or_rt | rn<<8 | offset<<16] + * bits 0-4: rd (load dest) or rt (store source) + * bits 8-12: rn (base register) + * bits 16-31: offset (unsigned, already scaled by gen.c) + * + * Register usage: + * x22: packed parameter (callee-saved, survives TLB miss) + * x23: store value (callee-saved, survives TLB miss) + * x24: saved guest _addr (callee-saved, survives TLB miss) + * x11: _cpu + CPU_x0 (scratch, used before TLB macros) + * x8-x10, x12: scratch (used before TLB macros) + */ + +// LDR Xd, [Xn, #imm] - fused 64-bit load with unsigned offset +.gadget load64_imm + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #8, #5 // rn + lsr x10, x22, #16 // offset (unsigned) + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x12, [x11, x9, lsl #3] + b 2f +1: ldr x12, [_cpu, #CPU_sp] +2: add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 64, load64_imm_1 + ldr _tmp, [_addr] + and x8, x22, #0x1f // rd + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 3f + str _tmp, [x11, x8, lsl #3] +3: mov _addr, x24 + gret + read_bullshit 64, load64_imm_1 + +// LDR Wd, [Xn, #imm] - fused 32-bit load with unsigned offset +.gadget load32_imm + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #8, #5 + lsr x10, x22, #16 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x12, [x11, x9, lsl #3] + b 2f +1: ldr x12, [_cpu, #CPU_sp] +2: add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 32, load32_imm_1 + ldr w0, [_addr] + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 3f + str x0, [x11, x8, lsl #3] // zero-extended 32→64 +3: mov _addr, x24 + gret + read_bullshit 32, load32_imm_1 + +// LDRH Wd, [Xn, #imm] - fused 16-bit load with unsigned offset +.gadget load16_imm + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #8, #5 + lsr x10, x22, #16 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x12, [x11, x9, lsl #3] + b 2f +1: ldr x12, [_cpu, #CPU_sp] +2: add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 16, load16_imm_1 + ldrh w0, [_addr] + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 3f + str x0, [x11, x8, lsl #3] // zero-extended 16→64 +3: mov _addr, x24 + gret + read_bullshit 16, load16_imm_1 + +// LDRB Wd, [Xn, #imm] - fused 8-bit load with unsigned offset +.gadget load8_imm + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #8, #5 + lsr x10, x22, #16 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x12, [x11, x9, lsl #3] + b 2f +1: ldr x12, [_cpu, #CPU_sp] +2: add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 8, load8_imm_1 + ldrb w0, [_addr] + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 3f + str x0, [x11, x8, lsl #3] // zero-extended 8→64 +3: mov _addr, x24 + gret + read_bullshit 8, load8_imm_1 + +// LDRSW Xd, [Xn, #imm] - fused 32-bit sign-extending load with unsigned offset +.gadget load32_sx_imm + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #8, #5 + lsr x10, x22, #16 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x12, [x11, x9, lsl #3] + b 2f +1: ldr x12, [_cpu, #CPU_sp] +2: add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 32, load32_sx_imm_1 + ldrsw _tmp, [_addr] + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 3f + str _tmp, [x11, x8, lsl #3] +3: mov _addr, x24 + gret + read_bullshit 32, load32_sx_imm_1 + +// STR Xt, [Xn, #imm] - fused 64-bit store with unsigned offset +.gadget store64_imm + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f // rt (source register) + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + ldr x23, [x11, x8, lsl #3] + b 2f +1: mov x23, #0 // XZR +2: ubfx x9, x22, #8, #5 // rn + lsr x10, x22, #16 // offset + cmp x9, #31 + b.eq 3f + ldr x12, [x11, x9, lsl #3] + b 4f +3: ldr x12, [_cpu, #CPU_sp] +4: add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 64, store64_imm_1 + str x23, [_addr] + write_done 64, store64_imm_1 + mov _addr, x24 + gret + write_bullshit 64, store64_imm_1 + +// STR Wt, [Xn, #imm] - fused 32-bit store with unsigned offset +.gadget store32_imm + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + ldr x23, [x11, x8, lsl #3] + b 2f +1: mov x23, #0 +2: ubfx x9, x22, #8, #5 + lsr x10, x22, #16 + cmp x9, #31 + b.eq 3f + ldr x12, [x11, x9, lsl #3] + b 4f +3: ldr x12, [_cpu, #CPU_sp] +4: add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 32, store32_imm_1 + str w23, [_addr] + write_done 32, store32_imm_1 + mov _addr, x24 + gret + write_bullshit 32, store32_imm_1 + +// STRH Wt, [Xn, #imm] - fused 16-bit store with unsigned offset +.gadget store16_imm + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + ldr x23, [x11, x8, lsl #3] + b 2f +1: mov x23, #0 +2: ubfx x9, x22, #8, #5 + lsr x10, x22, #16 + cmp x9, #31 + b.eq 3f + ldr x12, [x11, x9, lsl #3] + b 4f +3: ldr x12, [_cpu, #CPU_sp] +4: add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 16, store16_imm_1 + strh w23, [_addr] + write_done 16, store16_imm_1 + mov _addr, x24 + gret + write_bullshit 16, store16_imm_1 + +// STRB Wt, [Xn, #imm] - fused 8-bit store with unsigned offset +.gadget store8_imm + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + ldr x23, [x11, x8, lsl #3] + b 2f +1: mov x23, #0 +2: ubfx x9, x22, #8, #5 + lsr x10, x22, #16 + cmp x9, #31 + b.eq 3f + ldr x12, [x11, x9, lsl #3] + b 4f +3: ldr x12, [_cpu, #CPU_sp] +4: add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 8, store8_imm_1 + strb w23, [_addr] + write_done 8, store8_imm_1 + mov _addr, x24 + gret + write_bullshit 8, store8_imm_1 + +/* + * Fast-path fused load/store gadgets (no SP/XZR checks) + * + * gen.c guarantees rn!=31 (not SP) and rd/rt!=31 (not XZR/WZR). + * Saves ~4 instructions per operation by skipping the cmp+b.eq pairs. + * Same code-stream format: [gadget addr][rd_or_rt | rn<<8 | offset<<16] + */ + +// LDR Xd, [Xn, #imm] - fast path (rn!=31, rd!=31) +// Stream: [gadget addr][rd | rn<<8 | offset<<16][precise LDR guest PC]. +// Save the retry PC here instead of dispatching a separate PC-save gadget. +.gadget load64_imm_fast + ldp x22, x8, [_pc], #16 + str x8, [_cpu, #LOCAL_jit_saved_pc] + ubfx x9, x22, #8, #5 // rn (guaranteed != 31) + lsr x10, x22, #16 // offset (unsigned) + add x11, _cpu, #CPU_x0 + ldr x12, [x11, x9, lsl #3] // load base (no SP check) + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr // save for crosspage slow path + read_prep 64, load64_imm_fast_1 + ldr _tmp, [_addr] + and x8, x22, #0x1f // rd (guaranteed != 31) + add x11, _cpu, #CPU_x0 // read miss calls C and may clobber x11 + str _tmp, [x11, x8, lsl #3] + gret + read_bullshit 64, load64_imm_fast_1 + +// LDR Wd, [Xn, #imm] - fast path (rn!=31, rd!=31) +.gadget load32_imm_fast + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #8, #5 + lsr x10, x22, #16 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq fused_ldr32_cbz_sp_base + ldr x12, [x11, x9, lsl #3] + b fused_ldr32_cbz_have_base +fused_ldr32_cbz_sp_base: + ldr x12, [_cpu, #CPU_sp] +fused_ldr32_cbz_have_base: + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 32, load32_imm_fast_1 + ldr w0, [_addr] + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 // read miss calls C and may clobber x11 + str x0, [x11, x8, lsl #3] + gret + read_bullshit 32, load32_imm_fast_1 + +// STR Xt, [Xn, #imm] - fast path (rn!=31, rt!=31) +.gadget store64_imm_fast + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f // rt (guaranteed != 31) + add x11, _cpu, #CPU_x0 + ldr x23, [x11, x8, lsl #3] // load value (no XZR check) + ubfx x9, x22, #8, #5 // rn (guaranteed != 31) + lsr x10, x22, #16 // offset + ldr x12, [x11, x9, lsl #3] // load base (no SP check) + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 64, store64_imm_fast_1 + str x23, [_addr] + write_done 64, store64_imm_fast_1 + gret + write_bullshit 64, store64_imm_fast_1 + +// STR Wt, [Xn, #imm] - fast path (rn!=31, rt!=31) +.gadget store32_imm_fast + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f // rt (guaranteed != 31) + add x11, _cpu, #CPU_x0 + ldr x23, [x11, x8, lsl #3] + ubfx x9, x22, #8, #5 + lsr x10, x22, #16 + ldr x12, [x11, x9, lsl #3] + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 32, store32_imm_fast_1 + str w23, [_addr] + write_done 32, store32_imm_fast_1 + gret + write_bullshit 32, store32_imm_fast_1 + +// LDRH Wd, [Xn, #imm] - fast path (rn!=31, rd!=31) +.gadget load16_imm_fast + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #8, #5 // rn (guaranteed != 31) + lsr x10, x22, #16 // offset (unsigned) + add x11, _cpu, #CPU_x0 + ldr x12, [x11, x9, lsl #3] // load base (no SP check) + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 16, load16_imm_fast_1 + ldrh w0, [_addr] + and x8, x22, #0x1f // rd (guaranteed != 31) + add x11, _cpu, #CPU_x0 // read miss calls C and may clobber x11 + str x0, [x11, x8, lsl #3] + gret + read_bullshit 16, load16_imm_fast_1 + +// LDRB Wd, [Xn, #imm] - fast path (rn!=31, rd!=31) +.gadget load8_imm_fast + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #8, #5 + lsr x10, x22, #16 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq fused_ldr32_cbnz_sp_base + ldr x12, [x11, x9, lsl #3] + b fused_ldr32_cbnz_have_base +fused_ldr32_cbnz_sp_base: + ldr x12, [_cpu, #CPU_sp] +fused_ldr32_cbnz_have_base: + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 8, load8_imm_fast_1 + ldrb w0, [_addr] + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 // read miss calls C and may clobber x11 + str x0, [x11, x8, lsl #3] + gret + read_bullshit 8, load8_imm_fast_1 + +// STRH Wt, [Xn, #imm] - fast path (rn!=31, rt!=31) +.gadget store16_imm_fast + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f // rt (guaranteed != 31) + add x11, _cpu, #CPU_x0 + ldr x23, [x11, x8, lsl #3] // load value (no XZR check) + ubfx x9, x22, #8, #5 // rn (guaranteed != 31) + lsr x10, x22, #16 // offset + ldr x12, [x11, x9, lsl #3] // load base (no SP check) + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 16, store16_imm_fast_1 + strh w23, [_addr] + write_done 16, store16_imm_fast_1 + gret + write_bullshit 16, store16_imm_fast_1 + +// STRB Wt, [Xn, #imm] - fast path (rn!=31, rt!=31) +.gadget store8_imm_fast + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + ldr x23, [x11, x8, lsl #3] + ubfx x9, x22, #8, #5 + lsr x10, x22, #16 + ldr x12, [x11, x9, lsl #3] + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 8, store8_imm_fast_1 + strb w23, [_addr] + write_done 8, store8_imm_fast_1 + gret + write_bullshit 8, store8_imm_fast_1 + +/* + * SP-relative fused load/store gadgets + * + * For rn==31 (SP-relative) with rd/rt!=31, we skip both the rn==31 branch + * and the rd==31 check. Directly loads SP from CPU_sp. + * Same code-stream format: [gadget addr][rd_or_rt | rn<<8 | offset<<16] + * (rn field is always 31, but we ignore it and load SP directly) + */ + +// LDR Xd, [SP, #imm] - SP-relative 64-bit load (rd!=31) +.gadget load64_sp_imm + ldr x22, [_pc] + add _pc, _pc, #8 + lsr x10, x22, #16 // offset (unsigned) + ldr x12, [_cpu, #CPU_sp] // direct SP load + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 64, load64_sp_imm_1 + ldr _tmp, [_addr] + and x8, x22, #0x1f // rd (guaranteed != 31) + add x11, _cpu, #CPU_x0 // read miss calls C and may clobber x11 + str _tmp, [x11, x8, lsl #3] + gret + read_bullshit 64, load64_sp_imm_1 + +// LDR Wd, [SP, #imm] - SP-relative 32-bit load (rd!=31) +.gadget load32_sp_imm + ldr x22, [_pc] + add _pc, _pc, #8 + lsr x10, x22, #16 + ldr x12, [_cpu, #CPU_sp] + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 32, load32_sp_imm_1 + ldr w0, [_addr] + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 // read miss calls C and may clobber x11 + str x0, [x11, x8, lsl #3] // zero-extended 32→64 + gret + read_bullshit 32, load32_sp_imm_1 + +// STR Xt, [SP, #imm] - SP-relative 64-bit store (rt!=31) +.gadget store64_sp_imm + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f // rt (guaranteed != 31) + add x11, _cpu, #CPU_x0 + ldr x23, [x11, x8, lsl #3] // load value (no XZR check) + lsr x10, x22, #16 // offset + ldr x12, [_cpu, #CPU_sp] // direct SP load + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 64, store64_sp_imm_1 + str x23, [_addr] + write_done 64, store64_sp_imm_1 + gret + write_bullshit 64, store64_sp_imm_1 + +// STR Wt, [SP, #imm] - SP-relative 32-bit store (rt!=31) +.gadget store32_sp_imm + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + ldr x23, [x11, x8, lsl #3] + lsr x10, x22, #16 + ldr x12, [_cpu, #CPU_sp] + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 32, store32_sp_imm_1 + str w23, [_addr] + write_done 32, store32_sp_imm_1 + gret + write_bullshit 32, store32_sp_imm_1 + +/* + * Fused register-offset load/store gadgets + * + * Combine calc_addr_reg + load/store + store_reg/load_reg into a single dispatch + * for the common case: option=3 (UXTX/LSL, no extend on index register). + * + * Code stream: [gadget addr][rd_or_rt | rn<<8 | rm<<16 | shift<<24] + * bits 0-4: rd (load dest) or rt (store source) + * bits 8-12: rn (base register) + * bits 16-20: rm (index register) + * bits 24-26: shift amount (0-4) + * + * Register usage: + * x22: packed parameter (callee-saved) + * x23: store value (callee-saved) + * x24: saved guest _addr (callee-saved) + * x11: scratch (base of CPU_x0), used before TLB macros + * x8-x10, x12-x15: scratch, used before TLB macros + */ + +// LDRSW Xd, [Xn, Xm{, LSL #shift}] - fused sign-extending 32-bit load, register offset +.gadget load32_sx_reg + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #8, #5 // rn + ubfx x10, x22, #16, #5 // rm + ubfx x12, x22, #24, #3 // shift + add x11, _cpu, #CPU_x0 + // Load base register (or SP if rn == 31) + cmp x9, #31 + b.eq 1f + ldr x14, [x11, x9, lsl #3] + b 2f +1: ldr x14, [_cpu, #CPU_sp] +2: // Load index as 32-bit (auto zero-extends) + cmp x10, #31 + b.eq 3f + ldr x15, [x11, x10, lsl #3] + b 4f +3: mov x15, #0 +4: lsl x15, x15, x12 // apply shift + add _addr, x14, x15 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 32, load32_sx_reg_1 + ldrsw _tmp, [_addr] + and x8, x22, #0x1f // rd + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 5f + str _tmp, [x11, x8, lsl #3] +5: mov _addr, x24 + gret + read_bullshit 32, load32_sx_reg_1 + +// LDR Xd, [Xn, Xm{, LSL #shift}] - fused 64-bit load, register offset +.gadget load64_reg + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #8, #5 + ubfx x10, x22, #16, #5 + ubfx x12, x22, #24, #3 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x14, [x11, x9, lsl #3] + b 2f +1: ldr x14, [_cpu, #CPU_sp] +2: cmp x10, #31 + b.eq 3f + ldr x15, [x11, x10, lsl #3] + b 4f +3: mov x15, #0 +4: lsl x15, x15, x12 + add _addr, x14, x15 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 64, load64_reg_1 + ldr _tmp, [_addr] + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 5f + str _tmp, [x11, x8, lsl #3] +5: mov _addr, x24 + gret + read_bullshit 64, load64_reg_1 + +// LDR Wd, [Xn, Xm{, LSL #shift}] - fused 32-bit load, register offset +.gadget load32_reg + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #8, #5 + ubfx x10, x22, #16, #5 + ubfx x12, x22, #24, #3 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x14, [x11, x9, lsl #3] + b 2f +1: ldr x14, [_cpu, #CPU_sp] +2: cmp x10, #31 + b.eq 3f + ldr x15, [x11, x10, lsl #3] + b 4f +3: mov x15, #0 +4: lsl x15, x15, x12 + add _addr, x14, x15 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 32, load32_reg_1 + ldr w0, [_addr] + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 5f + str x0, [x11, x8, lsl #3] // zero-extended 32→64 +5: mov _addr, x24 + gret + read_bullshit 32, load32_reg_1 + +// LDRH Wd, [Xn, Xm{, LSL #shift}] - fused 16-bit load, register offset +.gadget load16_reg + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #8, #5 + ubfx x10, x22, #16, #5 + ubfx x12, x22, #24, #3 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x14, [x11, x9, lsl #3] + b 2f +1: ldr x14, [_cpu, #CPU_sp] +2: cmp x10, #31 + b.eq 3f + ldr x15, [x11, x10, lsl #3] + b 4f +3: mov x15, #0 +4: lsl x15, x15, x12 + add _addr, x14, x15 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 16, load16_reg_1 + ldrh w0, [_addr] + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 5f + str x0, [x11, x8, lsl #3] +5: mov _addr, x24 + gret + read_bullshit 16, load16_reg_1 + +// LDRB Wd, [Xn, Xm{, LSL #shift}] - fused 8-bit load, register offset +.gadget load8_reg + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #8, #5 + ubfx x10, x22, #16, #5 + ubfx x12, x22, #24, #3 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x14, [x11, x9, lsl #3] + b 2f +1: ldr x14, [_cpu, #CPU_sp] +2: cmp x10, #31 + b.eq 3f + ldr x15, [x11, x10, lsl #3] + b 4f +3: mov x15, #0 +4: lsl x15, x15, x12 + add _addr, x14, x15 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 8, load8_reg_1 + ldrb w0, [_addr] + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 5f + str x0, [x11, x8, lsl #3] +5: mov _addr, x24 + gret + read_bullshit 8, load8_reg_1 + +// STR Xt, [Xn, Xm{, LSL #shift}] - fused 64-bit store, register offset +.gadget store64_reg + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f // rt (source register) + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + ldr x23, [x11, x8, lsl #3] + b 2f +1: mov x23, #0 +2: ubfx x9, x22, #8, #5 // rn + ubfx x10, x22, #16, #5 // rm + ubfx x12, x22, #24, #3 // shift + cmp x9, #31 + b.eq 3f + ldr x14, [x11, x9, lsl #3] + b 4f +3: ldr x14, [_cpu, #CPU_sp] +4: cmp x10, #31 + b.eq 5f + ldr x15, [x11, x10, lsl #3] + b 6f +5: mov x15, #0 +6: lsl x15, x15, x12 + add _addr, x14, x15 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 64, store64_reg_1 + str x23, [_addr] + write_done 64, store64_reg_1 + mov _addr, x24 + gret + write_bullshit 64, store64_reg_1 + +// STR Wt, [Xn, Xm{, LSL #shift}] - fused 32-bit store, register offset +.gadget store32_reg + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + ldr x23, [x11, x8, lsl #3] + b 2f +1: mov x23, #0 +2: ubfx x9, x22, #8, #5 + ubfx x10, x22, #16, #5 + ubfx x12, x22, #24, #3 + cmp x9, #31 + b.eq 3f + ldr x14, [x11, x9, lsl #3] + b 4f +3: ldr x14, [_cpu, #CPU_sp] +4: cmp x10, #31 + b.eq 5f + ldr x15, [x11, x10, lsl #3] + b 6f +5: mov x15, #0 +6: lsl x15, x15, x12 + add _addr, x14, x15 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 32, store32_reg_1 + str w23, [_addr] + write_done 32, store32_reg_1 + mov _addr, x24 + gret + write_bullshit 32, store32_reg_1 + +// STRH Wt, [Xn, Xm{, LSL #shift}] - fused 16-bit store, register offset +.gadget store16_reg + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + ldr x23, [x11, x8, lsl #3] + b 2f +1: mov x23, #0 +2: ubfx x9, x22, #8, #5 + ubfx x10, x22, #16, #5 + ubfx x12, x22, #24, #3 + cmp x9, #31 + b.eq 3f + ldr x14, [x11, x9, lsl #3] + b 4f +3: ldr x14, [_cpu, #CPU_sp] +4: cmp x10, #31 + b.eq 5f + ldr x15, [x11, x10, lsl #3] + b 6f +5: mov x15, #0 +6: lsl x15, x15, x12 + add _addr, x14, x15 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 16, store16_reg_1 + strh w23, [_addr] + write_done 16, store16_reg_1 + mov _addr, x24 + gret + write_bullshit 16, store16_reg_1 + +// STRB Wt, [Xn, Xm{, LSL #shift}] - fused 8-bit store, register offset +.gadget store8_reg + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + ldr x23, [x11, x8, lsl #3] + b 2f +1: mov x23, #0 +2: ubfx x9, x22, #8, #5 + ubfx x10, x22, #16, #5 + ubfx x12, x22, #24, #3 + cmp x9, #31 + b.eq 3f + ldr x14, [x11, x9, lsl #3] + b 4f +3: ldr x14, [_cpu, #CPU_sp] +4: cmp x10, #31 + b.eq 5f + ldr x15, [x11, x10, lsl #3] + b 6f +5: mov x15, #0 +6: lsl x15, x15, x12 + add _addr, x14, x15 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 8, store8_reg_1 + strb w23, [_addr] + write_done 8, store8_reg_1 + mov _addr, x24 + gret + write_bullshit 8, store8_reg_1 + +/* + * Atomic memory operations (LSE) + * Address should be in _addr (x7) + * + * atomic_rmw code stream: [gadget addr][rs | size<<8 | op<<16] + * size: 0=8-bit, 1=16-bit, 2=32-bit, 3=64-bit + * op: 0=LDADD, 1=LDCLR, 2=LDEOR, 3=LDSET, 4=LDSMAX, 5=LDSMIN, 6=LDUMAX, 7=LDUMIN, 8=SWP + * + * atomic_cas code stream: [gadget addr][rs | rt<<8 | size<<16] + * rs: expected (and result) register + * rt: new value register + */ + +.gadget atomic_rmw + mov x23, _addr // save address + ldr x22, [_pc] // load params + add _pc, _pc, #8 + + and x9, x22, #0x1f // rs + ubfx x10, x22, #8, #2 // size + ubfx x11, x22, #16, #4 // op + + // Load Rs value (or zero for XZR) + add x12, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x13, [x12, x9, lsl #3] + b 2f +1: mov x13, #0 +2: + // Call C helper: c_atomic_rmw(tlb, addr, value, size, op, &old) + sub sp, sp, #16 + save_c + sub x0, _tlb, #TLB_entries + mov x1, x23 // address (64-bit) + mov x2, x13 // value + mov w3, w10 // size + mov w4, w11 // op + add x5, sp, #0xa0 // &old (adjust for save_c) + bl NAME(c_atomic_rmw) + mov w19, w0 + restore_c + mov _addr, x23 // restore _addr (restore_c clobbers x7) + + cbnz w19, atomic_rmw_segfault + ldr _tmp, [sp] // old value + add sp, sp, #16 + gret + +atomic_rmw_segfault: + add sp, sp, #16 + str x23, [_cpu, #CPU_segfault_addr] // 64-bit address for ARM64 guest + mov w8, #1 + strb w8, [_cpu, #CPU_segfault_was_write] + mov w0, #INT_GPF + b fiber_exit + +.gadget atomic_cas + mov x23, _addr // save address + ldr x22, [_pc] // load params + add _pc, _pc, #8 + + and x9, x22, #0x1f // rs (expected/result) + ubfx x10, x22, #8, #5 // rt (new value) + ubfx x11, x22, #16, #2 // size + + add x12, _cpu, #CPU_x0 + // Load expected value (rs) + cmp x9, #31 + b.eq 3f + ldr x13, [x12, x9, lsl #3] + b 4f +3: mov x13, #0 +4: + // Load desired value (rt) + cmp x10, #31 + b.eq 5f + ldr x14, [x12, x10, lsl #3] + b 6f +5: mov x14, #0 +6: + // Call C helper: c_atomic_cas(tlb, addr, expected, desired, size, &old) + sub sp, sp, #16 + save_c + sub x0, _tlb, #TLB_entries + mov x1, x23 // address (64-bit) + mov x2, x13 // expected + mov x3, x14 // desired + mov w4, w11 // size + add x5, sp, #0xa0 // &old + bl NAME(c_atomic_cas) + mov w19, w0 + restore_c + mov _addr, x23 // restore _addr (restore_c clobbers x7) + + cbnz w19, atomic_cas_segfault + ldr _tmp, [sp] // old value + add sp, sp, #16 + gret + +atomic_cas_segfault: + add sp, sp, #16 + str x23, [_cpu, #CPU_segfault_addr] // 64-bit address for ARM64 guest + mov w8, #1 + strb w8, [_cpu, #CPU_segfault_was_write] + mov w0, #INT_GPF + b fiber_exit + +.gadget atomic_casp + mov x23, _addr // save address + ldr x22, [_pc] // rs | rt<<8 | size<<16 (size 2=32-pair, 3=64-pair) + add _pc, _pc, #8 + + and x9, x22, #0x1f // rs (expected/result lo; hi is rs+1) + ubfx x10, x22, #8, #5 // rt (desired lo; hi is rt+1) + ubfx x11, x22, #16, #2 // element size + add x12, _cpu, #CPU_x0 + + // Load expected pair from Rs/Rs+1 + cmp x9, #31 + b.eq 1f + ldr x13, [x12, x9, lsl #3] + add x15, x9, #1 + cmp x15, #31 + b.eq 2f + ldr x14, [x12, x15, lsl #3] + b 3f +1: mov x13, #0 +2: mov x14, #0 +3: + // Load desired pair from Rt/Rt+1 + cmp x10, #31 + b.eq 4f + ldr x20, [x12, x10, lsl #3] + add x15, x10, #1 + cmp x15, #31 + b.eq 5f + ldr x21, [x12, x15, lsl #3] + b 6f +4: mov x20, #0 +5: mov x21, #0 +6: + sub sp, sp, #16 + str x13, [sp] + str x14, [sp, #8] + save_c + sub x0, _tlb, #TLB_entries + mov x1, x23 + add x2, sp, #0xa0 // &old_lo / expected_lo + add x3, sp, #0xa8 // &old_hi / expected_hi + mov x4, x20 + mov x5, x21 + mov w6, w11 + bl NAME(c_casp_pair) + mov w19, w0 + restore_c + mov _addr, x23 + + cbnz w19, atomic_casp_segfault + + ldr x13, [sp] + ldr x14, [sp, #8] + add sp, sp, #16 + add x12, _cpu, #CPU_x0 + and x9, x22, #0x1f + cmp x9, #31 + b.eq 7f + str x13, [x12, x9, lsl #3] + add x15, x9, #1 + cmp x15, #31 + b.eq 7f + str x14, [x12, x15, lsl #3] +7: gret + +atomic_casp_segfault: + add sp, sp, #16 + str x23, [_cpu, #CPU_segfault_addr] + mov w8, #1 + strb w8, [_cpu, #CPU_segfault_was_write] + mov w0, #INT_GPF + b fiber_exit + +/* + * Memory barrier/system-synchronization gadgets. + * Since guest threads run as real host threads sharing the same physical + * memory, guest memory ordering must be enforced with real host barriers. + */ +.gadget dmb + // Decode currently folds all DMB CRm domains into one gadget; use the + // strongest host domain so DMB SY/LD/ST are never under-serialized. + dmb sy + gret + +.gadget dsb + // Decode currently folds all DSB CRm domains into one gadget; use the + // strongest host domain so DSB SY/LD/ST are never under-serialized. + dsb sy + gret + +.gadget isb + isb + gret + +/* + * CLREX — clear single/pair exclusive monitor state. + */ +.gadget clrex + movn x8, #0 + str x8, [_cpu, #CPU_excl_addr] + str x8, [_cpu, #CPU_excl_pair_addr] + str wzr, [_cpu, #CPU_excl_pair_size] + str xzr, [_cpu, #CPU_excl_val] + str xzr, [_cpu, #CPU_excl_pair_val_lo] + str xzr, [_cpu, #CPU_excl_pair_val_hi] + gret + +/* + * IC IVAU — guest invalidates its instruction cache after modifying code. + * The architectural contract is "code at [Xt] changed; refetch it", so we + * must drop any translated blocks for that page or the JIT keeps running + * the stale pre-patch translation (JSC repatches its JIT code in place). + * Code stream: [gadget addr][rt] + */ +.gadget ic_ivau + ldr x8, [_pc] + add _pc, _pc, #8 + and x9, x8, #0x1f // rt + add x10, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x11, [x10, x9, lsl #3] + b 2f +1: mov x11, #0 +2: + save_c + sub x0, _tlb, #TLB_entries + mov x1, x11 // VA to invalidate + bl NAME(c_ic_ivau) + restore_c + gret + +/* + * Base register update gadget for post/pre-indexed addressing + * Code stream: [gadget addr][rn | offset<<8] + * Updates: Rn = Rn + offset + * The offset can be imm9 for pre/post load/store or imm7*scale for LDP/STP + * Using 16-bit signed extraction to handle all cases + */ +.gadget update_base + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rn + asr x10, x8, #8 // offset (sign-extended from gen.c packing) + + // Load current base register and update with offset + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x12, [x11, x9, lsl #3] + add x12, x12, x10 + and x12, x12, #0xffffffffffff + str x12, [x11, x9, lsl #3] + gret +1: // SP update + ldr x12, [_cpu, #CPU_sp] + add x12, x12, x10 + and x12, x12, #0xffffffffffff + str x12, [_cpu, #CPU_sp] + gret + +/* + * Writeback address to base register (for pre-indexed) + * Code stream: [gadget addr][rn] + * + * Uses the guest address saved in LOCAL_value_addr by calc_addr_imm, + * NOT _addr which has been transformed to a host pointer by read_prep. + */ +.gadget writeback_addr + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rn + ldr x10, [_cpu, #LOCAL_value_addr] // guest address from calc_addr_imm + + // Store guest address to register + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + str x10, [x11, x9, lsl #3] + gret +1: // SP writeback + str x10, [_cpu, #CPU_sp] + gret + +/* + * Calculate address from base register only (for pre/post-indexed) + * Code stream: [gadget addr][rn] + */ +.gadget calc_addr_base + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rn + + // Load base register (or SP if rn == 31) + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr _addr, [x11, x9, lsl #3] + gret +1: ldr _addr, [_cpu, #CPU_sp] + gret + +/* + * Load/Store Pair gadgets (LDP/STP) with inline TLB lookup + * Address should be in _addr (x7) + * Code stream: [gadget addr][rt | rt2<<8] + * Single TLB lookup covers both values when on same page. + */ + +// LDP Xn, Xm, [addr] - 64-bit load pair (inline TLB) +.gadget ldp64 + ldr x22, [_pc] // rt | rt2<<8 + add _pc, _pc, #8 + mov x24, _addr + read_prep 128, ldp64_1 // 16 bytes: cross-page if offset > 0xff0 + ldr x23, [_addr] // val1 + ldr x25, [_addr, #8] // val2 + and x8, x22, #0x1f // rt + ubfx x9, x22, #8, #5 // rt2 + add x10, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + str x23, [x10, x8, lsl #3] +1: cmp x9, #31 + b.eq 2f + str x25, [x10, x9, lsl #3] +2: mov _addr, x24 + gret + read_bullshit 128, ldp64_1 + +// LDP Wn, Wm, [addr] - 32-bit load pair (inline TLB) +.gadget ldp32 + ldr x22, [_pc] + add _pc, _pc, #8 + mov x24, _addr + read_prep 64, ldp32_1 // 8 bytes total (2x4): cross-page if offset > 0xff8 + ldr w23, [_addr] // val1 (32-bit, zero-extended to x23) + ldr w25, [_addr, #4] // val2 (32-bit, zero-extended to x25) + and x8, x22, #0x1f // rt + ubfx x9, x22, #8, #5 // rt2 + add x10, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + str x23, [x10, x8, lsl #3] // store zero-extended 64-bit +1: cmp x9, #31 + b.eq 2f + str x25, [x10, x9, lsl #3] +2: mov _addr, x24 + gret + read_bullshit 64, ldp32_1 + +// LDPSW Xt, Xt2, [addr] - load pair of signed words into X registers (inline TLB) +.gadget ldpsw + ldr x22, [_pc] + add _pc, _pc, #8 + mov x24, _addr + read_prep 64, ldpsw_1 // 8 bytes total (2x4): cross-page if offset > 0xff8 + ldrsw x23, [_addr] // val1 (32-bit sign-extended to x23) + ldrsw x25, [_addr, #4] // val2 (32-bit sign-extended to x25) + and x8, x22, #0x1f // rt + ubfx x9, x22, #8, #5 // rt2 + add x10, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 1f + str x23, [x10, x8, lsl #3] +1: cmp x9, #31 + b.eq 2f + str x25, [x10, x9, lsl #3] +2: mov _addr, x24 + gret + read_bullshit 64, ldpsw_1 + +// STP Xn, Xm, [addr] - 64-bit store pair (inline TLB) +.gadget stp64 + ldr x22, [_pc] + add _pc, _pc, #8 + // Load register values before write_prep (which clobbers x8-x10) + and x8, x22, #0x1f // rt + ubfx x9, x22, #8, #5 // rt2 + add x10, _cpu, #CPU_x0 + mov x23, #0 + cmp x8, #31 + b.eq 1f + ldr x23, [x10, x8, lsl #3] +1: mov x25, #0 + cmp x9, #31 + b.eq 2f + ldr x25, [x10, x9, lsl #3] +2: mov x24, _addr + write_prep 128, stp64_1 // 16 bytes + str x23, [_addr] + str x25, [_addr, #8] + write_done 128, stp64_1 + mov _addr, x24 + gret + write_bullshit 128, stp64_1 + +// STP Wn, Wm, [addr] - 32-bit store pair (inline TLB) +.gadget stp32 + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f // rt + ubfx x9, x22, #8, #5 // rt2 + add x10, _cpu, #CPU_x0 + mov x23, #0 + cmp x8, #31 + b.eq 1f + ldr x23, [x10, x8, lsl #3] // load full 64-bit (upper 32 bits zero for W-reg ops) +1: mov x25, #0 + cmp x9, #31 + b.eq 2f + ldr x25, [x10, x9, lsl #3] +2: mov x24, _addr + write_prep 64, stp32_1 // 8 bytes total (2x4) + str w23, [_addr] // store only low 32 bits + str w25, [_addr, #4] + write_done 64, stp32_1 + mov _addr, x24 + gret + write_bullshit 64, stp32_1 + +/* + * Fused LDP/STP with signed-offset addressing (mode==2) + * + * Combines calc_addr_imm + ldp/stp into a single gadget dispatch. + * Used for the most common LDP/STP encoding: signed offset mode. + * + * Code stream: [gadget addr][rt | rt2<<8 | rn<<16 | offset<<24] + * bits 0-4: rt (5 bits) + * bits 8-12: rt2 (5 bits) + * bits 16-20: rn (5 bits) + * bits 24-39: signed offset in bytes (16-bit, sign-extracted via sbfx) + * + * Register usage: + * x22: packed parameter (callee-saved) + * x23, x25: load/store values (callee-saved) + * x24: saved _addr (callee-saved) + * x8-x12: scratch + */ + +// Fast-path LDP Xt, Xt2, [Xn, #imm] (rn!=31, rt!=31, rt2!=31) +.gadget ldp64_imm_fast + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #16, #5 // rn + sbfx x10, x22, #24, #16 // signed offset + add x11, _cpu, #CPU_x0 + ldr x12, [x11, x9, lsl #3] // base (no SP check) + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 128, ldp64_imm_fast_1 + ldr x23, [_addr] + ldr x25, [_addr, #8] + and x8, x22, #0x1f // rt + ubfx x9, x22, #8, #5 // rt2 + add x11, _cpu, #CPU_x0 // read miss calls C and may clobber x11 + str x23, [x11, x8, lsl #3] + str x25, [x11, x9, lsl #3] + gret + read_bullshit 128, ldp64_imm_fast_1 + +// Fast-path STP Xt, Xt2, [Xn, #imm] (rn!=31, rt!=31, rt2!=31) +.gadget stp64_imm_fast + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f // rt + ubfx x9, x22, #8, #5 // rt2 + add x10, _cpu, #CPU_x0 + ldr x23, [x10, x8, lsl #3] // no XZR check + ldr x25, [x10, x9, lsl #3] + ubfx x9, x22, #16, #5 // rn + sbfx x10, x22, #24, #16 // signed offset + add x11, _cpu, #CPU_x0 + ldr x12, [x11, x9, lsl #3] // no SP check + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 128, stp64_imm_fast_1 + str x23, [_addr] + str x25, [_addr, #8] + write_done 128, stp64_imm_fast_1 + gret + write_bullshit 128, stp64_imm_fast_1 + +// Fast-path LDP Wt, Wt2, [Xn, #imm] (rn!=31, rt!=31, rt2!=31) +.gadget ldp32_imm_fast + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #16, #5 // rn + sbfx x10, x22, #24, #16 // signed offset + add x11, _cpu, #CPU_x0 + ldr x12, [x11, x9, lsl #3] // base (no SP check) + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 64, ldp32_imm_fast_1 // 8 bytes (2x4) + ldr w23, [_addr] + ldr w25, [_addr, #4] + and x8, x22, #0x1f // rt + ubfx x9, x22, #8, #5 // rt2 + add x11, _cpu, #CPU_x0 // read miss calls C and may clobber x11 + str x23, [x11, x8, lsl #3] + str x25, [x11, x9, lsl #3] + gret + read_bullshit 64, ldp32_imm_fast_1 + +// Fast-path LDPSW Xt, Xt2, [Xn, #imm] (rn!=31, rt!=31, rt2!=31) +.gadget ldpsw_imm_fast + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #16, #5 // rn + ubfx x10, x22, #24, #16 + sxth x10, w10 // sign-extend offset + add x11, _cpu, #CPU_x0 + ldr x12, [x11, x9, lsl #3] + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 64, ldpsw_imm_fast_1 // 8 bytes (2x4) + ldrsw x23, [_addr] + ldrsw x25, [_addr, #4] + and x8, x22, #0x1f // rt + ubfx x9, x22, #8, #5 // rt2 + str x23, [x11, x8, lsl #3] + str x25, [x11, x9, lsl #3] + gret + read_bullshit 64, ldpsw_imm_fast_1 + +// Fast-path STP Wt, Wt2, [Xn, #imm] (rn!=31, rt!=31, rt2!=31) +.gadget stp32_imm_fast + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f // rt + ubfx x9, x22, #8, #5 // rt2 + add x10, _cpu, #CPU_x0 + ldr x23, [x10, x8, lsl #3] // no XZR check + ldr x25, [x10, x9, lsl #3] + ubfx x9, x22, #16, #5 // rn + sbfx x10, x22, #24, #16 // signed offset + add x11, _cpu, #CPU_x0 + ldr x12, [x11, x9, lsl #3] // no SP check + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 64, stp32_imm_fast_1 // 8 bytes (2x4) + str w23, [_addr] + str w25, [_addr, #4] + write_done 64, stp32_imm_fast_1 + gret + write_bullshit 64, stp32_imm_fast_1 + +// Fused LDP Xt, Xt2, [Xn, #imm] - 64-bit load pair with signed offset +.gadget ldp64_imm + ldr x22, [_pc] + add _pc, _pc, #8 + // Unpack parameters + ubfx x9, x22, #16, #5 // rn + sbfx x10, x22, #24, #16 // signed offset in bytes + // Load base register or SP + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x12, [x11, x9, lsl #3] + b 2f +1: ldr x12, [_cpu, #CPU_sp] +2: add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 128, ldp64_imm_1 // 16 bytes + ldr x23, [_addr] // val1 + ldr x25, [_addr, #8] // val2 + and x8, x22, #0x1f // rt + ubfx x9, x22, #8, #5 // rt2 + add x10, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 3f + str x23, [x10, x8, lsl #3] +3: cmp x9, #31 + b.eq 4f + str x25, [x10, x9, lsl #3] +4: mov _addr, x24 + gret + read_bullshit 128, ldp64_imm_1 + +// Fused LDP Wt, Wt2, [Xn, #imm] - 32-bit load pair with signed offset +.gadget ldp32_imm + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #16, #5 + sbfx x10, x22, #24, #16 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x12, [x11, x9, lsl #3] + b 2f +1: ldr x12, [_cpu, #CPU_sp] +2: add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 64, ldp32_imm_1 // 8 bytes (2x4) + ldr w23, [_addr] // val1 (zero-extended) + ldr w25, [_addr, #4] // val2 (zero-extended) + and x8, x22, #0x1f + ubfx x9, x22, #8, #5 + add x10, _cpu, #CPU_x0 + cmp x8, #31 + b.eq 3f + str x23, [x10, x8, lsl #3] // store zero-extended 64-bit +3: cmp x9, #31 + b.eq 4f + str x25, [x10, x9, lsl #3] +4: mov _addr, x24 + gret + read_bullshit 64, ldp32_imm_1 + +// Fused LDPSW Xt, Xt2, [Xn, #imm] - sign-extending word load pair with signed offset +.gadget ldpsw_imm + ldr x22, [_pc] + add _pc, _pc, #8 + ubfx x9, x22, #16, #5 + ubfx x10, x22, #24, #16 + sxth x10, w10 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 1f + ldr x12, [x11, x9, lsl #3] + b 2f +1: ldr x12, [_cpu, #CPU_sp] +2: add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + read_prep 64, ldpsw_imm_1 // 8 bytes (2x4) + ldrsw x23, [_addr] // val1 (sign-extended) + ldrsw x25, [_addr, #4] // val2 (sign-extended) + and x8, x22, #0x1f + ubfx x9, x22, #8, #5 + cmp x8, #31 + b.eq 3f + str x23, [x11, x8, lsl #3] +3: cmp x9, #31 + b.eq 4f + str x25, [x11, x9, lsl #3] +4: mov _addr, x24 + gret + read_bullshit 64, ldpsw_imm_1 + +// Fused STP Xt, Xt2, [Xn, #imm] - 64-bit store pair with signed offset +.gadget stp64_imm + ldr x22, [_pc] + add _pc, _pc, #8 + // Load register values before write_prep (which clobbers x8-x10) + and x8, x22, #0x1f // rt + ubfx x9, x22, #8, #5 // rt2 + add x10, _cpu, #CPU_x0 + mov x23, #0 + cmp x8, #31 + b.eq 1f + ldr x23, [x10, x8, lsl #3] +1: mov x25, #0 + cmp x9, #31 + b.eq 2f + ldr x25, [x10, x9, lsl #3] +2: // Calculate address + ubfx x9, x22, #16, #5 // rn + sbfx x10, x22, #24, #16 // signed offset + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 3f + ldr x12, [x11, x9, lsl #3] + b 4f +3: ldr x12, [_cpu, #CPU_sp] +4: add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 128, stp64_imm_1 // 16 bytes + str x23, [_addr] + str x25, [_addr, #8] + write_done 128, stp64_imm_1 + mov _addr, x24 + gret + write_bullshit 128, stp64_imm_1 + +// Fused STP Wt, Wt2, [Xn, #imm] - 32-bit store pair with signed offset +.gadget stp32_imm + ldr x22, [_pc] + add _pc, _pc, #8 + and x8, x22, #0x1f + ubfx x9, x22, #8, #5 + add x10, _cpu, #CPU_x0 + mov x23, #0 + cmp x8, #31 + b.eq 1f + ldr x23, [x10, x8, lsl #3] +1: mov x25, #0 + cmp x9, #31 + b.eq 2f + ldr x25, [x10, x9, lsl #3] +2: ubfx x9, x22, #16, #5 + sbfx x10, x22, #24, #16 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq 3f + ldr x12, [x11, x9, lsl #3] + b 4f +3: ldr x12, [_cpu, #CPU_sp] +4: add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + write_prep 64, stp32_imm_1 // 8 bytes (2x4) + str w23, [_addr] + str w25, [_addr, #4] + write_done 64, stp32_imm_1 + mov _addr, x24 + gret + write_bullshit 64, stp32_imm_1 + +/* + * Fused ADRP+LDR64 gadget + * When ADRP Xd, #page is immediately followed by LDR Xt, [Xd, #offset], + * we can compute the final address directly and do a single TLB lookup. + * Code stream: [gadget addr][ldr_rt(0:4) | rd(5:9) | ldr_offset(16:31)][adrp_target (48-bit)] + */ +.gadget fused_adrp_ldr64 + ldr x22, [_pc] + ldr x23, [_pc, #8] // adrp_target (48-bit address in 64-bit word) + add _pc, _pc, #16 + + // Store ADRP result to rd (so subsequent code can use it) + ubfx x9, x22, #5, #5 // rd (ADRP destination register) + add x11, _cpu, #CPU_x0 + str x23, [x11, x9, lsl #3] // cpu->x[rd] = adrp_target + + // Compute final address = adrp_target + ldr_offset + ubfx x10, x22, #16, #16 // ldr_offset (unsigned, scaled) + add _addr, x23, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + // TLB read lookup + load 64-bit + read_prep 64, fused_adrp_ldr64_1 + ldr _tmp, [_addr] + + // Store to guest ldr_rt + and x8, x22, #0x1f // ldr_rt + add x11, _cpu, #CPU_x0 + str _tmp, [x11, x8, lsl #3] + mov _addr, x24 + gret + read_bullshit 64, fused_adrp_ldr64_1 + +/* + * Fused ADD/SUB (immediate, 64-bit, no flags) + LDR Xt, [Xd, #imm] + * Code stream: [gadget addr] + * [rd | add_rn<<8 | add_imm12<<16 | op<<28 | ldr_rt<<32 | ldr_imm12<<40] + * [ldr_guest_pc] + * Stores the ADD/SUB result before the load, matching architectural ordering + * if the load faults. The LDR guest PC is written to LOCAL_jit_saved_pc before + * the faultable memory access so guest signals report the precise LDR PC. + */ +.gadget fused_addsub_ldr64_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] // precise LDR guest PC for fault recovery + add _pc, _pc, #16 + + and x9, x22, #0x1f // rd = ADD/SUB destination and LDR base + ubfx x10, x22, #8, #5 // add/sub rn + ubfx x11, x22, #16, #12 // add/sub imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] + tbnz x22, #28, fused_addsub_ldr64_sub + add x16, x15, x11 + b fused_addsub_ldr64_store_base +fused_addsub_ldr64_sub: + sub x16, x15, x11 +fused_addsub_ldr64_store_base: + str x16, [x14, x9, lsl #3] // ADD/SUB side effect is visible before LDR + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x10, x22, #40, #12 // LDR imm12, scaled by 8 + lsl x10, x10, #3 + add _addr, x16, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 64, fused_addsub_ldr64_imm_1 + ldr _tmp, [_addr] + + ubfx x8, x22, #32, #5 // ldr_rt + add x11, _cpu, #CPU_x0 + str _tmp, [x11, x8, lsl #3] + mov _addr, x24 + gret + read_bullshit 64, fused_addsub_ldr64_imm_1 + +/* + * Fused ADD/SUB (immediate, 64-bit, no flags) + LDR Wt, [Xd, #imm] + * Code stream: [gadget addr] + * [rd | add_rn<<8 | add_imm12<<16 | op<<28 | ldr_rt<<32 | ldr_imm12<<40] + * [ldr_guest_pc] + * Stores the ADD/SUB result before the load, matching architectural ordering + * if the load faults. The LDR guest PC is written to LOCAL_jit_saved_pc before + * the faultable memory access so guest signals report the precise LDR PC. The + * 32-bit load result is zero-extended into the architectural X register. + */ +.gadget fused_addsub_ldr32_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] // precise LDR guest PC for fault recovery + add _pc, _pc, #16 + + and x9, x22, #0x1f // rd = ADD/SUB destination and LDR base + ubfx x10, x22, #8, #5 // add/sub rn + ubfx x11, x22, #16, #12 // add/sub imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] + tbnz x22, #28, fused_addsub_ldr32_sub + add x16, x15, x11 + b fused_addsub_ldr32_store_base +fused_addsub_ldr32_sub: + sub x16, x15, x11 +fused_addsub_ldr32_store_base: + str x16, [x14, x9, lsl #3] // ADD/SUB side effect is visible before LDR + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x10, x22, #40, #12 // LDR imm12, scaled by 4 + lsl x10, x10, #2 + add _addr, x16, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 32, fused_addsub_ldr32_imm_1 + ldr w0, [_addr] + + ubfx x8, x22, #32, #5 // ldr_rt + add x11, _cpu, #CPU_x0 + str x0, [x11, x8, lsl #3] // zero-extended 32→64 + mov _addr, x24 + gret + read_bullshit 32, fused_addsub_ldr32_imm_1 + +/* + * Fused ADD/SUB (immediate, 64-bit, no flags) + LDRH Wt, [Xd, #imm] + * Code stream: [gadget addr] + * [rd | add_rn<<8 | add_imm12<<16 | op<<28 | ldr_rt<<32 | ldr_imm12<<40] + * [ldr_guest_pc] + * Stores the ADD/SUB result before the load, matching architectural ordering + * if the load faults. The LDR guest PC is written to LOCAL_jit_saved_pc before + * the faultable memory access so guest signals report the precise LDR PC. The + * 16-bit load result is zero-extended into the architectural X register. + */ +.gadget fused_addsub_ldr16_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] // precise LDR guest PC for fault recovery + add _pc, _pc, #16 + + and x9, x22, #0x1f // rd = ADD/SUB destination and LDR base + ubfx x10, x22, #8, #5 // add/sub rn + ubfx x11, x22, #16, #12 // add/sub imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] + tbnz x22, #28, fused_addsub_ldr16_sub + add x16, x15, x11 + b fused_addsub_ldr16_store_base +fused_addsub_ldr16_sub: + sub x16, x15, x11 +fused_addsub_ldr16_store_base: + str x16, [x14, x9, lsl #3] // ADD/SUB side effect is visible before LDR + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x10, x22, #40, #12 // LDRH imm12, scaled by 2 + lsl x10, x10, #1 + add _addr, x16, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 16, fused_addsub_ldr16_imm_1 + ldrh w0, [_addr] + + ubfx x8, x22, #32, #5 // ldr_rt + add x11, _cpu, #CPU_x0 + str x0, [x11, x8, lsl #3] // zero-extended 16→64 + mov _addr, x24 + gret + read_bullshit 16, fused_addsub_ldr16_imm_1 + +/* + * Fused ADD/SUB (immediate, 64-bit, no flags) + LDRB Wt, [Xd, #imm] + * Code stream: [gadget addr] + * [rd | add_rn<<8 | add_imm12<<16 | op<<28 | ldr_rt<<32 | ldr_imm12<<40] + * [ldr_guest_pc] + * Stores the ADD/SUB result before the load, matching architectural ordering + * if the load faults. The LDR guest PC is written to LOCAL_jit_saved_pc before + * the faultable memory access so guest signals report the precise LDR PC. The + * 8-bit load result is zero-extended into the architectural X register. + */ +.gadget fused_addsub_ldr8_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] // precise LDR guest PC for fault recovery + add _pc, _pc, #16 + + and x9, x22, #0x1f // rd = ADD/SUB destination and LDR base + ubfx x10, x22, #8, #5 // add/sub rn + ubfx x11, x22, #16, #12 // add/sub imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] + tbnz x22, #28, fused_addsub_ldr8_sub + add x16, x15, x11 + b fused_addsub_ldr8_store_base +fused_addsub_ldr8_sub: + sub x16, x15, x11 +fused_addsub_ldr8_store_base: + str x16, [x14, x9, lsl #3] // ADD/SUB side effect is visible before LDR + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x10, x22, #40, #12 // LDRB imm12, scaled by 1 + add _addr, x16, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 8, fused_addsub_ldr8_imm_1 + ldrb w0, [_addr] + + ubfx x8, x22, #32, #5 // ldr_rt + add x11, _cpu, #CPU_x0 + str x0, [x11, x8, lsl #3] // zero-extended 8→64 + mov _addr, x24 + gret + read_bullshit 8, fused_addsub_ldr8_imm_1 + +/* + * Fused ADD/SUB (immediate, 64-bit, no flags) + STR Xt, [Xd, #imm] + * Code stream: [gadget addr] + * [rd | add_rn<<8 | add_imm12<<16 | op<<28 | str_rt<<32 | str_imm12<<40] + * [str_guest_pc] + * Stores the ADD/SUB result before the store, matching architectural ordering + * if the store faults. The STR guest PC is written to LOCAL_jit_saved_pc before + * the faultable memory access so guest signals report the precise STR PC. + */ +.gadget fused_addsub_str64_imm + ldr x22, [_pc] + ldr x25, [_pc, #8] // precise STR guest PC for fault recovery + add _pc, _pc, #16 + + and x9, x22, #0x1f // rd = ADD/SUB destination and STR base + ubfx x10, x22, #8, #5 // add/sub rn + ubfx x11, x22, #16, #12 // add/sub imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] + tbnz x22, #28, fused_addsub_str64_sub + add x16, x15, x11 + b fused_addsub_str64_store_base +fused_addsub_str64_sub: + sub x16, x15, x11 +fused_addsub_str64_store_base: + str x16, [x14, x9, lsl #3] // ADD/SUB side effect is visible before STR + + str x25, [_cpu, #LOCAL_jit_saved_pc] + ubfx x8, x22, #32, #5 // str_rt + ldr x23, [x14, x8, lsl #3] // store value after ADD/SUB, so rt==rd is correct + ubfx x10, x22, #40, #12 // STR imm12, scaled by 8 + lsl x10, x10, #3 + add _addr, x16, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + write_prep 64, fused_addsub_str64_imm_1 + str x23, [_addr] + write_done 64, fused_addsub_str64_imm_1 + mov _addr, x24 + gret + write_bullshit 64, fused_addsub_str64_imm_1 + +/* + * Fused ADD/SUB (immediate, 64-bit, no flags) + STR Wt, [Xd, #imm] + * Code stream: [gadget addr] + * [rd | add_rn<<8 | add_imm12<<16 | op<<28 | str_rt<<32 | str_imm12<<40] + * [str_guest_pc] + * Stores the ADD/SUB result before the store, matching architectural ordering + * if the store faults. The STR guest PC is written to LOCAL_jit_saved_pc before + * the faultable memory access so guest signals report the precise STR PC. The + * store source is read after the ADD/SUB side effect so rt==rd is correct. + */ +.gadget fused_addsub_str32_imm + ldr x22, [_pc] + ldr x25, [_pc, #8] // precise STR guest PC for fault recovery + add _pc, _pc, #16 + + and x9, x22, #0x1f // rd = ADD/SUB destination and STR base + ubfx x10, x22, #8, #5 // add/sub rn + ubfx x11, x22, #16, #12 // add/sub imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] + tbnz x22, #28, fused_addsub_str32_sub + add x16, x15, x11 + b fused_addsub_str32_store_base +fused_addsub_str32_sub: + sub x16, x15, x11 +fused_addsub_str32_store_base: + str x16, [x14, x9, lsl #3] // ADD/SUB side effect is visible before STR + + str x25, [_cpu, #LOCAL_jit_saved_pc] + ubfx x8, x22, #32, #5 // str_rt + ldr x23, [x14, x8, lsl #3] // store value after ADD/SUB, so rt==rd is correct + ubfx x10, x22, #40, #12 // STR imm12, scaled by 4 + lsl x10, x10, #2 + add _addr, x16, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + write_prep 32, fused_addsub_str32_imm_1 + str w23, [_addr] + write_done 32, fused_addsub_str32_imm_1 + mov _addr, x24 + gret + write_bullshit 32, fused_addsub_str32_imm_1 + +/* + * Fused ADD/SUB (immediate, 64-bit, no flags) + STRH Wt, [Xd, #imm] + * Code stream: [gadget addr] + * [rd | add_rn<<8 | add_imm12<<16 | op<<28 | str_rt<<32 | str_imm12<<40] + * [str_guest_pc] + * Stores the ADD/SUB result before the store, matching architectural ordering + * if the store faults. The STR guest PC is written to LOCAL_jit_saved_pc before + * the faultable memory access so guest signals report the precise STR PC. The + * store source is read after the ADD/SUB side effect so rt==rd is correct. + */ +.gadget fused_addsub_str16_imm + ldr x22, [_pc] + ldr x25, [_pc, #8] // precise STR guest PC for fault recovery + add _pc, _pc, #16 + + and x9, x22, #0x1f // rd = ADD/SUB destination and STR base + ubfx x10, x22, #8, #5 // add/sub rn + ubfx x11, x22, #16, #12 // add/sub imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] + tbnz x22, #28, fused_addsub_str16_sub + add x16, x15, x11 + b fused_addsub_str16_store_base +fused_addsub_str16_sub: + sub x16, x15, x11 +fused_addsub_str16_store_base: + str x16, [x14, x9, lsl #3] // ADD/SUB side effect is visible before STR + + str x25, [_cpu, #LOCAL_jit_saved_pc] + ubfx x8, x22, #32, #5 // str_rt + ldr x23, [x14, x8, lsl #3] // store value after ADD/SUB, so rt==rd is correct + ubfx x10, x22, #40, #12 // STRH imm12, scaled by 2 + lsl x10, x10, #1 + add _addr, x16, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + write_prep 16, fused_addsub_str16_imm_1 + strh w23, [_addr] + write_done 16, fused_addsub_str16_imm_1 + mov _addr, x24 + gret + write_bullshit 16, fused_addsub_str16_imm_1 + +/* + * Fused ADD/SUB (immediate, 64-bit, no flags) + STRB Wt, [Xd, #imm] + * Code stream: [gadget addr] + * [rd | add_rn<<8 | add_imm12<<16 | op<<28 | str_rt<<32 | str_imm12<<40] + * [str_guest_pc] + * Stores the ADD/SUB result before the store, matching architectural ordering + * if the store faults. The STR guest PC is written to LOCAL_jit_saved_pc before + * the faultable memory access so guest signals report the precise STR PC. The + * store source is read after the ADD/SUB side effect so rt==rd is correct. + */ +.gadget fused_addsub_str8_imm + ldr x22, [_pc] + ldr x25, [_pc, #8] // precise STR guest PC for fault recovery + add _pc, _pc, #16 + + and x9, x22, #0x1f // rd = ADD/SUB destination and STR base + ubfx x10, x22, #8, #5 // add/sub rn + ubfx x11, x22, #16, #12 // add/sub imm12 + add x14, _cpu, #CPU_x0 + ldr x15, [x14, x10, lsl #3] + tbnz x22, #28, fused_addsub_str8_sub + add x16, x15, x11 + b fused_addsub_str8_store_base +fused_addsub_str8_sub: + sub x16, x15, x11 +fused_addsub_str8_store_base: + str x16, [x14, x9, lsl #3] // ADD/SUB side effect is visible before STR + + str x25, [_cpu, #LOCAL_jit_saved_pc] + ubfx x8, x22, #32, #5 // str_rt + ldr x23, [x14, x8, lsl #3] // store value after ADD/SUB, so rt==rd is correct + ubfx x10, x22, #40, #12 // STRB imm12, scaled by 1 + add _addr, x16, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + write_prep 8, fused_addsub_str8_imm_1 + strb w23, [_addr] + write_done 8, fused_addsub_str8_imm_1 + mov _addr, x24 + gret + write_bullshit 8, fused_addsub_str8_imm_1 + +/* + * Fused LDR Xt, [Xn, #imm] + CBZ/CBNZ Xt. + * Code stream: [gadget addr][rt | rn<<8 | ldr_imm12<<16][ldr_guest_pc][target][fallthrough] + * The loaded register is stored before branching. LOCAL_jit_saved_pc is set to + * the LDR PC before the faultable access so guest signals report the load. + */ +.gadget fused_ldr64_cbz_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] // precise LDR guest PC + ldr x25, [_pc, #16] // target (fake_ip or chained) + ldr x26, [_pc, #24] // fallthrough (fake_ip or chained) + add _pc, _pc, #32 + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x9, x22, #8, #5 // rn + ubfx x10, x22, #16, #12 // imm12, scaled by 8 + lsl x10, x10, #3 + add x11, _cpu, #CPU_x0 + ldr x12, [x11, x9, lsl #3] + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 64, fused_ldr64_cbz_imm_1 + ldr _tmp, [_addr] + + and x8, x22, #0x1f // rt + add x11, _cpu, #CPU_x0 + str _tmp, [x11, x8, lsl #3] + mov _addr, x24 + cbz _tmp, fused_ldr64_cbz_taken +fused_ldr64_cbz_not_taken: + tbnz x26, #63, fused_ldr64_cbz_nt_unchained + mov _pc, x26 + b fiber_ret_chain +fused_ldr64_cbz_nt_unchained: + and x11, x26, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x26 + b fiber_ret_chain +fused_ldr64_cbz_taken: + tbnz x25, #63, fused_ldr64_cbz_t_unchained + mov _pc, x25 + b fiber_ret_chain +fused_ldr64_cbz_t_unchained: + and x11, x25, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x25 + b fiber_ret_chain + read_bullshit 64, fused_ldr64_cbz_imm_1 + +.gadget fused_ldr64_cbnz_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] + ldr x25, [_pc, #16] + ldr x26, [_pc, #24] + add _pc, _pc, #32 + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x9, x22, #8, #5 + ubfx x10, x22, #16, #12 + lsl x10, x10, #3 + add x11, _cpu, #CPU_x0 + ldr x12, [x11, x9, lsl #3] + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 64, fused_ldr64_cbnz_imm_1 + ldr _tmp, [_addr] + + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + str _tmp, [x11, x8, lsl #3] + mov _addr, x24 + cbnz _tmp, fused_ldr64_cbnz_taken +fused_ldr64_cbnz_not_taken: + tbnz x26, #63, fused_ldr64_cbnz_nt_unchained + mov _pc, x26 + b fiber_ret_chain +fused_ldr64_cbnz_nt_unchained: + and x11, x26, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x26 + b fiber_ret_chain +fused_ldr64_cbnz_taken: + tbnz x25, #63, fused_ldr64_cbnz_t_unchained + mov _pc, x25 + b fiber_ret_chain +fused_ldr64_cbnz_t_unchained: + and x11, x25, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x25 + b fiber_ret_chain + read_bullshit 64, fused_ldr64_cbnz_imm_1 + +/* + * Fused LDR Xt, [SP, #imm] + CBZ/CBNZ Xt. + * Code stream: [gadget addr][rt | ldr_imm12<<16][ldr_guest_pc][target][fallthrough] + * This is the SP-base counterpart to the non-SP LDR64+CBZ/CBNZ fusion. The + * loaded register is stored before branching. LOCAL_jit_saved_pc is set to the + * LDR PC before the faultable access so guest signals report the load. + */ +.gadget fused_ldr64_sp_cbz_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] // precise LDR guest PC + ldr x25, [_pc, #16] // target (fake_ip or chained) + ldr x26, [_pc, #24] // fallthrough (fake_ip or chained) + add _pc, _pc, #32 + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x10, x22, #16, #12 // imm12, scaled by 8 + lsl x10, x10, #3 + ldr x12, [_cpu, #CPU_sp] + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 64, fused_ldr64_sp_cbz_imm_1 + ldr _tmp, [_addr] + + and x8, x22, #0x1f // rt, guaranteed != 31 + add x11, _cpu, #CPU_x0 + str _tmp, [x11, x8, lsl #3] + mov _addr, x24 + cbz _tmp, fused_ldr64_sp_cbz_taken +fused_ldr64_sp_cbz_not_taken: + tbnz x26, #63, fused_ldr64_sp_cbz_nt_unchained + mov _pc, x26 + b fiber_ret_chain +fused_ldr64_sp_cbz_nt_unchained: + and x11, x26, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x26 + b fiber_ret_chain +fused_ldr64_sp_cbz_taken: + tbnz x25, #63, fused_ldr64_sp_cbz_t_unchained + mov _pc, x25 + b fiber_ret_chain +fused_ldr64_sp_cbz_t_unchained: + and x11, x25, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x25 + b fiber_ret_chain + read_bullshit 64, fused_ldr64_sp_cbz_imm_1 + +.gadget fused_ldr64_sp_cbnz_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] + ldr x25, [_pc, #16] + ldr x26, [_pc, #24] + add _pc, _pc, #32 + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x10, x22, #16, #12 + lsl x10, x10, #3 + ldr x12, [_cpu, #CPU_sp] + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 64, fused_ldr64_sp_cbnz_imm_1 + ldr _tmp, [_addr] + + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + str _tmp, [x11, x8, lsl #3] + mov _addr, x24 + cbnz _tmp, fused_ldr64_sp_cbnz_taken +fused_ldr64_sp_cbnz_not_taken: + tbnz x26, #63, fused_ldr64_sp_cbnz_nt_unchained + mov _pc, x26 + b fiber_ret_chain +fused_ldr64_sp_cbnz_nt_unchained: + and x11, x26, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x26 + b fiber_ret_chain +fused_ldr64_sp_cbnz_taken: + tbnz x25, #63, fused_ldr64_sp_cbnz_t_unchained + mov _pc, x25 + b fiber_ret_chain +fused_ldr64_sp_cbnz_t_unchained: + and x11, x25, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x25 + b fiber_ret_chain + read_bullshit 64, fused_ldr64_sp_cbnz_imm_1 + +/* + * Fused LDR Wt, [Xn, #imm] + CBZ/CBNZ Wt. + * Code stream: [gadget addr][rt | rn<<8 | ldr_imm12<<16][ldr_guest_pc][target][fallthrough] + * The loaded register is zero-extended and stored before branching. + * LOCAL_jit_saved_pc is set to the LDR PC before the faultable access so guest + * signals report the load. + */ +.gadget fused_ldr32_cbz_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] // precise LDR guest PC + ldr x25, [_pc, #16] // target (fake_ip or chained) + ldr x26, [_pc, #24] // fallthrough (fake_ip or chained) + add _pc, _pc, #32 + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x9, x22, #8, #5 // rn + ubfx x10, x22, #16, #12 // imm12, scaled by 4 + lsl x10, x10, #2 + add x11, _cpu, #CPU_x0 + ldr x12, [x11, x9, lsl #3] + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 32, fused_ldr32_cbz_imm_1 + ldr w0, [_addr] + + and x8, x22, #0x1f // rt + add x11, _cpu, #CPU_x0 + str x0, [x11, x8, lsl #3] + mov _addr, x24 + cbz x0, fused_ldr32_cbz_taken +fused_ldr32_cbz_not_taken: + tbnz x26, #63, fused_ldr32_cbz_nt_unchained + mov _pc, x26 + b fiber_ret_chain +fused_ldr32_cbz_nt_unchained: + and x11, x26, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x26 + b fiber_ret_chain +fused_ldr32_cbz_taken: + tbnz x25, #63, fused_ldr32_cbz_t_unchained + mov _pc, x25 + b fiber_ret_chain +fused_ldr32_cbz_t_unchained: + and x11, x25, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x25 + b fiber_ret_chain + read_bullshit 32, fused_ldr32_cbz_imm_1 + +.gadget fused_ldr32_cbnz_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] + ldr x25, [_pc, #16] + ldr x26, [_pc, #24] + add _pc, _pc, #32 + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x9, x22, #8, #5 + ubfx x10, x22, #16, #12 + lsl x10, x10, #2 + add x11, _cpu, #CPU_x0 + ldr x12, [x11, x9, lsl #3] + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 32, fused_ldr32_cbnz_imm_1 + ldr w0, [_addr] + + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + str x0, [x11, x8, lsl #3] + mov _addr, x24 + cbnz x0, fused_ldr32_cbnz_taken +fused_ldr32_cbnz_not_taken: + tbnz x26, #63, fused_ldr32_cbnz_nt_unchained + mov _pc, x26 + b fiber_ret_chain +fused_ldr32_cbnz_nt_unchained: + and x11, x26, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x26 + b fiber_ret_chain +fused_ldr32_cbnz_taken: + tbnz x25, #63, fused_ldr32_cbnz_t_unchained + mov _pc, x25 + b fiber_ret_chain +fused_ldr32_cbnz_t_unchained: + and x11, x25, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x25 + b fiber_ret_chain + read_bullshit 32, fused_ldr32_cbnz_imm_1 + +/* + * Fused LDRSW Xt, [Xn/SP, #imm] + CBZ/CBNZ Xt. + * Code stream: [gadget addr][rt | rn<<8 | ldr_imm12<<16][ldr_guest_pc][target][fallthrough] + * The loaded register is sign-extended to 64 bits and stored before branching. + * LOCAL_jit_saved_pc is set to the LDRSW PC before the faultable access so + * guest signals report the load. + */ +.gadget fused_ldr32_sx_cbz_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] // precise LDRSW guest PC + ldr x25, [_pc, #16] // target (fake_ip or chained) + ldr x26, [_pc, #24] // fallthrough (fake_ip or chained) + add _pc, _pc, #32 + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x9, x22, #8, #5 // rn, 31 means SP + ubfx x10, x22, #16, #12 // imm12, scaled by 4 + lsl x10, x10, #2 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq fused_ldr32_sx_cbz_sp_base + ldr x12, [x11, x9, lsl #3] + b fused_ldr32_sx_cbz_have_base +fused_ldr32_sx_cbz_sp_base: + ldr x12, [_cpu, #CPU_sp] +fused_ldr32_sx_cbz_have_base: + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 32, fused_ldr32_sx_cbz_imm_1 + ldrsw _tmp, [_addr] + + and x8, x22, #0x1f // rt, guaranteed != 31 + add x11, _cpu, #CPU_x0 + str _tmp, [x11, x8, lsl #3] + mov _addr, x24 + cbz _tmp, fused_ldr32_sx_cbz_taken +fused_ldr32_sx_cbz_not_taken: + tbnz x26, #63, fused_ldr32_sx_cbz_nt_unchained + mov _pc, x26 + b fiber_ret_chain +fused_ldr32_sx_cbz_nt_unchained: + and x11, x26, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x26 + b fiber_ret_chain +fused_ldr32_sx_cbz_taken: + tbnz x25, #63, fused_ldr32_sx_cbz_t_unchained + mov _pc, x25 + b fiber_ret_chain +fused_ldr32_sx_cbz_t_unchained: + and x11, x25, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x25 + b fiber_ret_chain + read_bullshit 32, fused_ldr32_sx_cbz_imm_1 + +.gadget fused_ldr32_sx_cbnz_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] + ldr x25, [_pc, #16] + ldr x26, [_pc, #24] + add _pc, _pc, #32 + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x9, x22, #8, #5 + ubfx x10, x22, #16, #12 + lsl x10, x10, #2 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq fused_ldr32_sx_cbnz_sp_base + ldr x12, [x11, x9, lsl #3] + b fused_ldr32_sx_cbnz_have_base +fused_ldr32_sx_cbnz_sp_base: + ldr x12, [_cpu, #CPU_sp] +fused_ldr32_sx_cbnz_have_base: + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 32, fused_ldr32_sx_cbnz_imm_1 + ldrsw _tmp, [_addr] + + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + str _tmp, [x11, x8, lsl #3] + mov _addr, x24 + cbnz _tmp, fused_ldr32_sx_cbnz_taken +fused_ldr32_sx_cbnz_not_taken: + tbnz x26, #63, fused_ldr32_sx_cbnz_nt_unchained + mov _pc, x26 + b fiber_ret_chain +fused_ldr32_sx_cbnz_nt_unchained: + and x11, x26, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x26 + b fiber_ret_chain +fused_ldr32_sx_cbnz_taken: + tbnz x25, #63, fused_ldr32_sx_cbnz_t_unchained + mov _pc, x25 + b fiber_ret_chain +fused_ldr32_sx_cbnz_t_unchained: + and x11, x25, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x25 + b fiber_ret_chain + read_bullshit 32, fused_ldr32_sx_cbnz_imm_1 + +/* + * Fused LDRSB/LDRSH Xt/Wt, [Xn/SP, #imm] + matching CBZ/CBNZ Xt/Wt. + * Code stream: [gadget addr] + * [rt | rn<<8 | ldr_imm12<<16 | size<<28 | extend64<<29] + * [ldr_guest_pc][target][fallthrough] + * size 0 = byte, size 1 = halfword. extend64 selects Xt vs Wt sign-extension + * and must match the branch width. LOCAL_jit_saved_pc is set to the load PC + * before the faultable access so guest signals report the load. + */ +.gadget fused_ldr_sx_cbz_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] // precise LDRSB/LDRSH guest PC + ldr x25, [_pc, #16] // target (fake_ip or chained) + ldr x26, [_pc, #24] // fallthrough (fake_ip or chained) + add _pc, _pc, #32 + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x9, x22, #8, #5 // rn, 31 means SP + ubfx x10, x22, #16, #12 // imm12, scaled by size + tbz x22, #28, fused_ldr_sx_cbz_unscaled + lsl x10, x10, #1 +fused_ldr_sx_cbz_unscaled: + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq fused_ldr_sx_cbz_sp_base + ldr x12, [x11, x9, lsl #3] + b fused_ldr_sx_cbz_have_base +fused_ldr_sx_cbz_sp_base: + ldr x12, [_cpu, #CPU_sp] +fused_ldr_sx_cbz_have_base: + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + tbnz x22, #28, fused_ldr_sx_cbz_load16 +fused_ldr_sx_cbz_load8: + read_prep 8, fused_ldr_sx_cbz_imm_8 + tbnz x22, #29, fused_ldr_sx_cbz_load8_64 + ldrsb w0, [_addr] + b fused_ldr_sx_cbz_after_load +fused_ldr_sx_cbz_load8_64: + ldrsb _tmp, [_addr] + b fused_ldr_sx_cbz_after_load +fused_ldr_sx_cbz_load16: + read_prep 16, fused_ldr_sx_cbz_imm_16 + tbnz x22, #29, fused_ldr_sx_cbz_load16_64 + ldrsh w0, [_addr] + b fused_ldr_sx_cbz_after_load +fused_ldr_sx_cbz_load16_64: + ldrsh _tmp, [_addr] + +fused_ldr_sx_cbz_after_load: + and x8, x22, #0x1f // rt, guaranteed != 31 + add x11, _cpu, #CPU_x0 + str _tmp, [x11, x8, lsl #3] + mov _addr, x24 + cbz _tmp, fused_ldr_sx_cbz_taken +fused_ldr_sx_cbz_not_taken: + tbnz x26, #63, fused_ldr_sx_cbz_nt_unchained + mov _pc, x26 + b fiber_ret_chain +fused_ldr_sx_cbz_nt_unchained: + and x11, x26, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x26 + b fiber_ret_chain +fused_ldr_sx_cbz_taken: + tbnz x25, #63, fused_ldr_sx_cbz_t_unchained + mov _pc, x25 + b fiber_ret_chain +fused_ldr_sx_cbz_t_unchained: + and x11, x25, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x25 + b fiber_ret_chain + read_bullshit 8, fused_ldr_sx_cbz_imm_8 + read_bullshit 16, fused_ldr_sx_cbz_imm_16 + +.gadget fused_ldr_sx_cbnz_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] + ldr x25, [_pc, #16] + ldr x26, [_pc, #24] + add _pc, _pc, #32 + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x9, x22, #8, #5 + ubfx x10, x22, #16, #12 + tbz x22, #28, fused_ldr_sx_cbnz_unscaled + lsl x10, x10, #1 +fused_ldr_sx_cbnz_unscaled: + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq fused_ldr_sx_cbnz_sp_base + ldr x12, [x11, x9, lsl #3] + b fused_ldr_sx_cbnz_have_base +fused_ldr_sx_cbnz_sp_base: + ldr x12, [_cpu, #CPU_sp] +fused_ldr_sx_cbnz_have_base: + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + tbnz x22, #28, fused_ldr_sx_cbnz_load16 +fused_ldr_sx_cbnz_load8: + read_prep 8, fused_ldr_sx_cbnz_imm_8 + tbnz x22, #29, fused_ldr_sx_cbnz_load8_64 + ldrsb w0, [_addr] + b fused_ldr_sx_cbnz_after_load +fused_ldr_sx_cbnz_load8_64: + ldrsb _tmp, [_addr] + b fused_ldr_sx_cbnz_after_load +fused_ldr_sx_cbnz_load16: + read_prep 16, fused_ldr_sx_cbnz_imm_16 + tbnz x22, #29, fused_ldr_sx_cbnz_load16_64 + ldrsh w0, [_addr] + b fused_ldr_sx_cbnz_after_load +fused_ldr_sx_cbnz_load16_64: + ldrsh _tmp, [_addr] + +fused_ldr_sx_cbnz_after_load: + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + str _tmp, [x11, x8, lsl #3] + mov _addr, x24 + cbnz _tmp, fused_ldr_sx_cbnz_taken +fused_ldr_sx_cbnz_not_taken: + tbnz x26, #63, fused_ldr_sx_cbnz_nt_unchained + mov _pc, x26 + b fiber_ret_chain +fused_ldr_sx_cbnz_nt_unchained: + and x11, x26, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x26 + b fiber_ret_chain +fused_ldr_sx_cbnz_taken: + tbnz x25, #63, fused_ldr_sx_cbnz_t_unchained + mov _pc, x25 + b fiber_ret_chain +fused_ldr_sx_cbnz_t_unchained: + and x11, x25, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x25 + b fiber_ret_chain + read_bullshit 8, fused_ldr_sx_cbnz_imm_8 + read_bullshit 16, fused_ldr_sx_cbnz_imm_16 + +/* + * Fused LDRH Wt, [Xn, #imm] + CBZ/CBNZ Wt. + * Code stream: [gadget addr][rt | rn<<8 | ldr_imm12<<16][ldr_guest_pc][target][fallthrough] + * The loaded register is zero-extended and stored before branching. + * LOCAL_jit_saved_pc is set to the LDRH PC before the faultable access so + * guest signals report the load. + */ +.gadget fused_ldr16_cbz_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] // precise LDR guest PC + ldr x25, [_pc, #16] // target (fake_ip or chained) + ldr x26, [_pc, #24] // fallthrough (fake_ip or chained) + add _pc, _pc, #32 + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x9, x22, #8, #5 // rn + ubfx x10, x22, #16, #12 // imm12, scaled by 2 + lsl x10, x10, #1 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq fused_ldr16_cbz_sp_base + ldr x12, [x11, x9, lsl #3] + b fused_ldr16_cbz_have_base +fused_ldr16_cbz_sp_base: + ldr x12, [_cpu, #CPU_sp] +fused_ldr16_cbz_have_base: + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 16, fused_ldr16_cbz_imm_1 + ldrh w0, [_addr] + + and x8, x22, #0x1f // rt + add x11, _cpu, #CPU_x0 + str x0, [x11, x8, lsl #3] + mov _addr, x24 + cbz x0, fused_ldr16_cbz_taken +fused_ldr16_cbz_not_taken: + tbnz x26, #63, fused_ldr16_cbz_nt_unchained + mov _pc, x26 + b fiber_ret_chain +fused_ldr16_cbz_nt_unchained: + and x11, x26, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x26 + b fiber_ret_chain +fused_ldr16_cbz_taken: + tbnz x25, #63, fused_ldr16_cbz_t_unchained + mov _pc, x25 + b fiber_ret_chain +fused_ldr16_cbz_t_unchained: + and x11, x25, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x25 + b fiber_ret_chain + read_bullshit 16, fused_ldr16_cbz_imm_1 + +.gadget fused_ldr16_cbnz_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] + ldr x25, [_pc, #16] + ldr x26, [_pc, #24] + add _pc, _pc, #32 + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x9, x22, #8, #5 + ubfx x10, x22, #16, #12 + lsl x10, x10, #1 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq fused_ldr16_cbnz_sp_base + ldr x12, [x11, x9, lsl #3] + b fused_ldr16_cbnz_have_base +fused_ldr16_cbnz_sp_base: + ldr x12, [_cpu, #CPU_sp] +fused_ldr16_cbnz_have_base: + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 16, fused_ldr16_cbnz_imm_1 + ldrh w0, [_addr] + + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + str x0, [x11, x8, lsl #3] + mov _addr, x24 + cbnz x0, fused_ldr16_cbnz_taken +fused_ldr16_cbnz_not_taken: + tbnz x26, #63, fused_ldr16_cbnz_nt_unchained + mov _pc, x26 + b fiber_ret_chain +fused_ldr16_cbnz_nt_unchained: + and x11, x26, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x26 + b fiber_ret_chain +fused_ldr16_cbnz_taken: + tbnz x25, #63, fused_ldr16_cbnz_t_unchained + mov _pc, x25 + b fiber_ret_chain +fused_ldr16_cbnz_t_unchained: + and x11, x25, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x25 + b fiber_ret_chain + read_bullshit 16, fused_ldr16_cbnz_imm_1 + +/* + * Fused LDRB Wt, [Xn, #imm] + CBZ/CBNZ Wt. + * Code stream: [gadget addr][rt | rn<<8 | ldr_imm12<<16][ldr_guest_pc][target][fallthrough] + * The loaded register is zero-extended and stored before branching. + * LOCAL_jit_saved_pc is set to the LDRB PC before the faultable access so + * guest signals report the load. + */ +.gadget fused_ldr8_cbz_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] // precise LDR guest PC + ldr x25, [_pc, #16] // target (fake_ip or chained) + ldr x26, [_pc, #24] // fallthrough (fake_ip or chained) + add _pc, _pc, #32 + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x9, x22, #8, #5 // rn + ubfx x10, x22, #16, #12 // imm12, scaled by 1 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq fused_ldr8_cbz_sp_base + ldr x12, [x11, x9, lsl #3] + b fused_ldr8_cbz_have_base +fused_ldr8_cbz_sp_base: + ldr x12, [_cpu, #CPU_sp] +fused_ldr8_cbz_have_base: + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 8, fused_ldr8_cbz_imm_1 + ldrb w0, [_addr] + + and x8, x22, #0x1f // rt + add x11, _cpu, #CPU_x0 + str x0, [x11, x8, lsl #3] + mov _addr, x24 + cbz x0, fused_ldr8_cbz_taken +fused_ldr8_cbz_not_taken: + tbnz x26, #63, fused_ldr8_cbz_nt_unchained + mov _pc, x26 + b fiber_ret_chain +fused_ldr8_cbz_nt_unchained: + and x11, x26, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x26 + b fiber_ret_chain +fused_ldr8_cbz_taken: + tbnz x25, #63, fused_ldr8_cbz_t_unchained + mov _pc, x25 + b fiber_ret_chain +fused_ldr8_cbz_t_unchained: + and x11, x25, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x25 + b fiber_ret_chain + read_bullshit 8, fused_ldr8_cbz_imm_1 + +.gadget fused_ldr8_cbnz_imm + ldr x22, [_pc] + ldr x23, [_pc, #8] + ldr x25, [_pc, #16] + ldr x26, [_pc, #24] + add _pc, _pc, #32 + + str x23, [_cpu, #LOCAL_jit_saved_pc] + ubfx x9, x22, #8, #5 + ubfx x10, x22, #16, #12 + add x11, _cpu, #CPU_x0 + cmp x9, #31 + b.eq fused_ldr8_cbnz_sp_base + ldr x12, [x11, x9, lsl #3] + b fused_ldr8_cbnz_have_base +fused_ldr8_cbnz_sp_base: + ldr x12, [_cpu, #CPU_sp] +fused_ldr8_cbnz_have_base: + add _addr, x12, x10 + and _addr, _addr, #0xffffffffffff + mov x24, _addr + + read_prep 8, fused_ldr8_cbnz_imm_1 + ldrb w0, [_addr] + + and x8, x22, #0x1f + add x11, _cpu, #CPU_x0 + str x0, [x11, x8, lsl #3] + mov _addr, x24 + cbnz x0, fused_ldr8_cbnz_taken +fused_ldr8_cbnz_not_taken: + tbnz x26, #63, fused_ldr8_cbnz_nt_unchained + mov _pc, x26 + b fiber_ret_chain +fused_ldr8_cbnz_nt_unchained: + and x11, x26, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x26 + b fiber_ret_chain +fused_ldr8_cbnz_taken: + tbnz x25, #63, fused_ldr8_cbnz_t_unchained + mov _pc, x25 + b fiber_ret_chain +fused_ldr8_cbnz_t_unchained: + and x11, x25, #0xffffffffffff + str x11, [_cpu, #CPU_pc] + mov _pc, x25 + b fiber_ret_chain + read_bullshit 8, fused_ldr8_cbnz_imm_1 + +/* + * Fused ADRP+ADD gadget + * When ADRP Xd, #page is immediately followed by ADD Xd, Xd, #imm12, + * we compute the final address directly without intermediate register writes. + * Code stream: [gadget addr][rd(0:4) | imm12(8:19)][adrp_target (48-bit)] + */ +.gadget fused_adrp_add + ldr x22, [_pc] + ldr x23, [_pc, #8] // adrp_target (48-bit) + add _pc, _pc, #16 + + // Compute final address = adrp_target + imm12 + ubfx x10, x22, #8, #12 // imm12 + add x8, x23, x10 + and x8, x8, #0xffffffffffff + + // Store to rd + and x9, x22, #0x1f // rd + add x11, _cpu, #CPU_x0 + str x8, [x11, x9, lsl #3] + gret + +/* + * Interleaved SIMD load/store gadgets (LD2/LD3/LD4, ST2/ST3/ST4) + * These call C helper functions for the deinterleaving/interleaving logic. + * Code stream: [gadget addr][rt | (num_regs<<8) | (elem_size<<16) | (Q<<24)] + * _addr must contain the guest base address. + */ + +.gadget simd_load_interleaved + ldr x22, [_pc] + add _pc, _pc, #8 + mov x23, _addr // save address + + save_c + mov x0, _cpu // cpu + sub x1, _tlb, #TLB_entries // tlb (base pointer) + mov x2, x23 // addr + and w3, w22, #0xff // rt + ubfx w4, w22, #8, #8 // num_regs + ubfx w5, w22, #16, #8 // elem_size + ubfx w6, w22, #24, #8 // Q + bl NAME(c_simd_load_interleaved) + mov w19, w0 + restore_c + mov _addr, x23 // restore _addr + + cbnz w19, simd_interleaved_read_segfault + gret + +simd_interleaved_read_segfault: + str x23, [_cpu, #CPU_segfault_addr] + strb wzr, [_cpu, #CPU_segfault_was_write] + mov w0, #INT_GPF + b fiber_exit + +.gadget simd_store_interleaved + ldr x22, [_pc] + add _pc, _pc, #8 + mov x23, _addr // save address + + save_c + mov x0, _cpu // cpu + sub x1, _tlb, #TLB_entries // tlb (base pointer) + mov x2, x23 // addr + and w3, w22, #0xff // rt + ubfx w4, w22, #8, #8 // num_regs + ubfx w5, w22, #16, #8 // elem_size + ubfx w6, w22, #24, #8 // Q + bl NAME(c_simd_store_interleaved) + mov w19, w0 + restore_c + mov _addr, x23 // restore _addr + + cbnz w19, simd_interleaved_write_segfault + gret + +simd_interleaved_write_segfault: + str x23, [_cpu, #CPU_segfault_addr] + mov w8, #1 + strb w8, [_cpu, #CPU_segfault_was_write] + mov w0, #INT_GPF + b fiber_exit + +/* + * Address manipulation gadgets + */ + +// Advance _addr by immediate value +// Code stream: [gadget addr][imm] +.gadget advance_addr + ldr x8, [_pc] + add _pc, _pc, #8 + add _addr, _addr, x8 + gret + +// Update base register from another register (for post-indexed addressing) +// Code stream: [gadget addr][rn | rm<<8] +.gadget update_base_reg + ldr x8, [_pc] + add _pc, _pc, #8 + + and x9, x8, #0x1f // rn (base register to update) + ubfx x10, x8, #8, #5 // rm (offset register) + + // Load offset from Rm + add x11, _cpu, #CPU_x0 + cmp x10, #31 + b.eq 1f + ldr x12, [x11, x10, lsl #3] + b 2f +1: mov x12, #0 +2: + // Load current base and update + cmp x9, #31 + b.eq 3f + ldr x13, [x11, x9, lsl #3] + add x13, x13, x12 + and x13, x13, #0xffffffffffff + str x13, [x11, x9, lsl #3] + gret +3: // Update SP + ldr x13, [_cpu, #CPU_sp] + add x13, x13, x12 + and x13, x13, #0xffffffffffff + str x13, [_cpu, #CPU_sp] + gret + +/* + * Advance _addr by immediate + * Code stream: [gadget addr][imm] + * Used between multi-element single-structure load/stores (LD2/ST2/LD3/ST3/LD4/ST4) + */ +.gadget addr_add_imm + ldr x8, [_pc] + add _pc, _pc, #8 + add _addr, _addr, x8 + and _addr, _addr, #0xffffffffffff + gret + +/* + * LD1/ST1 Single Structure Gadgets + * + * These load/store a single element from memory to/from a specific lane + * within a vector register. + * + * Code stream: [gadget addr][rt | (lane_offset << 8)] + * rt: vector register index (0-31) + * lane_offset: byte offset within the vector (0-15) + * + * Address should already be in _addr (x7) + */ + +/* + * LD1 {Vt.B}[lane], [Xn] - Load single byte to vector lane + */ +.gadget ld1_single_b + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f // rt (vector reg index) + ubfx x25, x22, #8, #8 // lane_offset (byte offset) + + mov x24, _addr // Save guest address + read_prep 8, ld1_single_b_1 + ldrb w11, [_addr] + + // Calculate address of byte within vector + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 // each V reg is 16 bytes + add x9, x9, x10 // base of vector + add x9, x9, x25 // add lane offset + strb w11, [x9] // store byte to lane + mov _addr, x24 + gret + read_bullshit 8, ld1_single_b_1 + +/* + * LD1 {Vt.H}[lane], [Xn] - Load single halfword to vector lane + */ +.gadget ld1_single_h + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f + ubfx x25, x22, #8, #8 + + mov x24, _addr + read_prep 16, ld1_single_h_1 + ldrh w11, [_addr] + + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + add x9, x9, x25 + strh w11, [x9] + mov _addr, x24 + gret + read_bullshit 16, ld1_single_h_1 + +/* + * LD1 {Vt.S}[lane], [Xn] - Load single word to vector lane + */ +.gadget ld1_single_s + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f + ubfx x25, x22, #8, #8 + + mov x24, _addr + read_prep 32, ld1_single_s_1 + ldr w11, [_addr] + + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + add x9, x9, x25 + str w11, [x9] + mov _addr, x24 + gret + read_bullshit 32, ld1_single_s_1 + +/* + * LD1 {Vt.D}[lane], [Xn] - Load single doubleword to vector lane + */ +.gadget ld1_single_d + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f + ubfx x25, x22, #8, #8 + + mov x24, _addr + read_prep 64, ld1_single_d_1 + ldr x11, [_addr] + + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + add x9, x9, x25 + str x11, [x9] + mov _addr, x24 + gret + read_bullshit 64, ld1_single_d_1 + +/* + * LD1R {Vt.T}, [Xn] - Load single element and replicate to all lanes + * + * Code stream: [gadget addr][rt | (size << 8) | (Q << 16)] + * rt: vector register index (0-31) + * size: element size (0=B, 1=H, 2=S, 3=D) + * Q: 0=64-bit (lower half), 1=128-bit (full vector) + * + * Address should already be in _addr (x7) from calc_addr_imm + */ +.gadget ld1r_vec + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f // rt (vector reg index) + ubfx x25, x22, #8, #8 // size (0=B, 1=H, 2=S, 3=D) + ubfx x26, x22, #16, #8 // Q + + mov x24, _addr // Save guest address + + // Dispatch on element size for read_prep and load + cmp x25, #0 + b.eq ld1r_byte + cmp x25, #1 + b.eq ld1r_half + cmp x25, #2 + b.eq ld1r_word + // else: doubleword + +ld1r_dword: + read_prep 64, ld1r_dword_1 + ldr x11, [_addr] + dup v0.2d, x11 + b ld1r_store + + read_bullshit 64, ld1r_dword_1 + +ld1r_word: + read_prep 32, ld1r_word_1 + ldr w11, [_addr] + dup v0.4s, w11 + b ld1r_store + + read_bullshit 32, ld1r_word_1 + +ld1r_half: + read_prep 16, ld1r_half_1 + ldrh w11, [_addr] + dup v0.8h, w11 + b ld1r_store + + read_bullshit 16, ld1r_half_1 + +ld1r_byte: + read_prep 8, ld1r_byte_1 + ldrb w11, [_addr] + dup v0.16b, w11 + b ld1r_store + + read_bullshit 8, ld1r_byte_1 + +ld1r_store: + // Store replicated vector to cpu->fp[rt] + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 // each V reg is 16 bytes + add x9, x9, x10 + + cbz x26, ld1r_store_64 + // Q=1: store full 128-bit vector + str q0, [x9] + mov _addr, x24 + gret + +ld1r_store_64: + // Q=0: store lower 64 bits, zero upper 64 bits + str d0, [x9] + str xzr, [x9, #8] // zero upper 64 bits + mov _addr, x24 + gret + +/* + * LD2R {Vt.T, Vt2.T}, [Xn] - Load 2 elements and replicate to all lanes + * + * Code stream: [gadget addr][rt | (size << 8) | (Q << 16)] + * Reads 2 consecutive elements, replicates each to Vt and V(t+1) mod 32 + */ +.gadget ld2r_vec + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f // rt + ubfx x25, x22, #8, #8 // size + ubfx x26, x22, #16, #8 // Q + + mov x24, _addr + + cmp x25, #0 + b.eq ld2r_byte + cmp x25, #1 + b.eq ld2r_half + cmp x25, #2 + b.eq ld2r_word + +ld2r_dword: + read_prep 128, ld2r_dword_1 + ldr x11, [_addr] + ldr x12, [_addr, #8] + dup v0.2d, x11 + dup v1.2d, x12 + b ld2r_store + read_bullshit 128, ld2r_dword_1 + +ld2r_word: + read_prep 64, ld2r_word_1 + ldr w11, [_addr] + ldr w12, [_addr, #4] + dup v0.4s, w11 + dup v1.4s, w12 + b ld2r_store + read_bullshit 64, ld2r_word_1 + +ld2r_half: + read_prep 32, ld2r_half_1 + ldrh w11, [_addr] + ldrh w12, [_addr, #2] + dup v0.8h, w11 + dup v1.8h, w12 + b ld2r_store + read_bullshit 32, ld2r_half_1 + +ld2r_byte: + read_prep 16, ld2r_byte_1 + ldrb w11, [_addr] + ldrb w12, [_addr, #1] + dup v0.16b, w11 + dup v1.16b, w12 + b ld2r_store + read_bullshit 16, ld2r_byte_1 + +ld2r_store: + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + // rt2 = (rt + 1) % 32 + add x14, x23, #1 + and x14, x14, #0x1f + add x15, _cpu, #CPU_fp + lsl x14, x14, #4 + add x15, x15, x14 + + cbz x26, ld2r_store_64 + str q0, [x9] + str q1, [x15] + mov _addr, x24 + gret + +ld2r_store_64: + str d0, [x9] + str xzr, [x9, #8] + str d1, [x15] + str xzr, [x15, #8] + mov _addr, x24 + gret + +/* + * LD3R {Vt.T, Vt2.T, Vt3.T}, [Xn] - Load 3 elements and replicate + */ +.gadget ld3r_vec + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f // rt + ubfx x25, x22, #8, #8 // size + ubfx x26, x22, #16, #8 // Q + + mov x24, _addr + + cmp x25, #0 + b.eq ld3r_byte + cmp x25, #1 + b.eq ld3r_half + cmp x25, #2 + b.eq ld3r_word + +ld3r_dword: + read_prep 192, ld3r_dword_1 + ldr x11, [_addr] + ldr x12, [_addr, #8] + ldr x13, [_addr, #16] + dup v0.2d, x11 + dup v1.2d, x12 + dup v2.2d, x13 + b ld3r_store + read_bullshit 192, ld3r_dword_1 + +ld3r_word: + read_prep 96, ld3r_word_1 + ldr w11, [_addr] + ldr w12, [_addr, #4] + ldr w13, [_addr, #8] + dup v0.4s, w11 + dup v1.4s, w12 + dup v2.4s, w13 + b ld3r_store + read_bullshit 96, ld3r_word_1 + +ld3r_half: + read_prep 48, ld3r_half_1 + ldrh w11, [_addr] + ldrh w12, [_addr, #2] + ldrh w13, [_addr, #4] + dup v0.8h, w11 + dup v1.8h, w12 + dup v2.8h, w13 + b ld3r_store + read_bullshit 48, ld3r_half_1 + +ld3r_byte: + read_prep 24, ld3r_byte_1 + ldrb w11, [_addr] + ldrb w12, [_addr, #1] + ldrb w13, [_addr, #2] + dup v0.16b, w11 + dup v1.16b, w12 + dup v2.16b, w13 + b ld3r_store + read_bullshit 24, ld3r_byte_1 + +ld3r_store: + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + + // Calculate rt2 and rt3 offsets + add x14, x23, #1 + and x14, x14, #0x1f + add x15, x23, #2 + and x15, x15, #0x1f + + add x16, _cpu, #CPU_fp + add x17, _cpu, #CPU_fp + lsl x14, x14, #4 + lsl x15, x15, #4 + add x16, x16, x14 + add x17, x17, x15 + + cbz x26, ld3r_store_64 + str q0, [x9] + str q1, [x16] + str q2, [x17] + mov _addr, x24 + gret + +ld3r_store_64: + str d0, [x9] + str xzr, [x9, #8] + str d1, [x16] + str xzr, [x16, #8] + str d2, [x17] + str xzr, [x17, #8] + mov _addr, x24 + gret + +/* + * LD4R {Vt.T, Vt2.T, Vt3.T, Vt4.T}, [Xn] - Load 4 elements and replicate + */ +.gadget ld4r_vec + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f // rt + ubfx x25, x22, #8, #8 // size + ubfx x26, x22, #16, #8 // Q + + mov x24, _addr + + cmp x25, #0 + b.eq ld4r_byte + cmp x25, #1 + b.eq ld4r_half + cmp x25, #2 + b.eq ld4r_word + +ld4r_dword: + read_prep 256, ld4r_dword_1 + ldr x11, [_addr] + ldr x12, [_addr, #8] + ldr x13, [_addr, #16] + ldr x14, [_addr, #24] + dup v0.2d, x11 + dup v1.2d, x12 + dup v2.2d, x13 + dup v3.2d, x14 + b ld4r_store + read_bullshit 256, ld4r_dword_1 + +ld4r_word: + read_prep 128, ld4r_word_1 + ldr w11, [_addr] + ldr w12, [_addr, #4] + ldr w13, [_addr, #8] + ldr w14, [_addr, #12] + dup v0.4s, w11 + dup v1.4s, w12 + dup v2.4s, w13 + dup v3.4s, w14 + b ld4r_store + read_bullshit 128, ld4r_word_1 + +ld4r_half: + read_prep 64, ld4r_half_1 + ldrh w11, [_addr] + ldrh w12, [_addr, #2] + ldrh w13, [_addr, #4] + ldrh w14, [_addr, #6] + dup v0.8h, w11 + dup v1.8h, w12 + dup v2.8h, w13 + dup v3.8h, w14 + b ld4r_store + read_bullshit 64, ld4r_half_1 + +ld4r_byte: + read_prep 32, ld4r_byte_1 + ldrb w11, [_addr] + ldrb w12, [_addr, #1] + ldrb w13, [_addr, #2] + ldrb w14, [_addr, #3] + dup v0.16b, w11 + dup v1.16b, w12 + dup v2.16b, w13 + dup v3.16b, w14 + b ld4r_store + read_bullshit 32, ld4r_byte_1 + +ld4r_store: + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + + // Calculate rt2, rt3, rt4 offsets + add x10, x23, #1 + and x10, x10, #0x1f + add x11, x23, #2 + and x11, x11, #0x1f + add x12, x23, #3 + and x12, x12, #0x1f + + lsl x10, x10, #4 + lsl x11, x11, #4 + lsl x12, x12, #4 + add x10, x10, _cpu + add x11, x11, _cpu + add x12, x12, _cpu + add x10, x10, #CPU_fp + add x11, x11, #CPU_fp + add x12, x12, #CPU_fp + + cbz x26, ld4r_store_64 + str q0, [x9] + str q1, [x10] + str q2, [x11] + str q3, [x12] + mov _addr, x24 + gret + +ld4r_store_64: + str d0, [x9] + str xzr, [x9, #8] + str d1, [x10] + str xzr, [x10, #8] + str d2, [x11] + str xzr, [x11, #8] + str d3, [x12] + str xzr, [x12, #8] + mov _addr, x24 + gret + +/* + * ST1 {Vt.B}[lane], [Xn] - Store single byte from vector lane + */ +.gadget st1_single_b + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f // rt + ubfx x25, x22, #8, #8 // lane_offset + + // Load byte from vector lane + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + add x9, x9, x25 + ldrb w11, [x9] + + mov x24, _addr + write_prep 8, st1_single_b_1 + strb w11, [_addr] + write_done 8, st1_single_b_1 + mov _addr, x24 + gret + write_bullshit 8, st1_single_b_1 + +/* + * ST1 {Vt.H}[lane], [Xn] - Store single halfword from vector lane + */ +.gadget st1_single_h + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f + ubfx x25, x22, #8, #8 + + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + add x9, x9, x25 + ldrh w11, [x9] + + mov x24, _addr + write_prep 16, st1_single_h_1 + strh w11, [_addr] + write_done 16, st1_single_h_1 + mov _addr, x24 + gret + write_bullshit 16, st1_single_h_1 + +/* + * ST1 {Vt.S}[lane], [Xn] - Store single word from vector lane + */ +.gadget st1_single_s + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f + ubfx x25, x22, #8, #8 + + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + add x9, x9, x25 + ldr w11, [x9] + + mov x24, _addr + write_prep 32, st1_single_s_1 + str w11, [_addr] + write_done 32, st1_single_s_1 + mov _addr, x24 + gret + write_bullshit 32, st1_single_s_1 + +/* + * ST1 {Vt.D}[lane], [Xn] - Store single doubleword from vector lane + */ +.gadget st1_single_d + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f + ubfx x25, x22, #8, #8 + + add x9, _cpu, #CPU_fp + lsl x10, x23, #4 + add x9, x9, x10 + add x9, x9, x25 + ldr x11, [x9] + + mov x24, _addr + write_prep 64, st1_single_d_1 + str x11, [_addr] + write_done 64, st1_single_d_1 + mov _addr, x24 + gret + write_bullshit 64, st1_single_d_1 + +/* + * LDXR — Load exclusive with exclusive monitor save + * Code stream: [gadget addr][rt | (size << 8)] + * Expects _addr = guest address (from calc_addr_imm) + * Loads value, saves addr+value to cpu excl_addr/excl_val, stores to Rt + */ +.gadget ldxr + ldr x22, [_pc] + add _pc, _pc, #8 + + and x23, x22, #0x1f // rt + ubfx x11, x22, #8, #2 // size (0=8b, 1=16b, 2=32b, 3=64b) + + mov x24, _addr + + // Use an access-size-matched TLB prep/cross-page path. + cmp x11, #3 + b.eq ldxr_load64 + cmp x11, #2 + b.eq ldxr_load32 + cmp x11, #1 + b.eq ldxr_load16 + + // size 0: 8-bit + read_prep 8, ldxr_8 + ldrb w0, [_addr] + b ldxr_done + +ldxr_load16: + read_prep 16, ldxr_16 + ldrh w0, [_addr] + b ldxr_done + +ldxr_load32: + read_prep 32, ldxr_32 + ldr w0, [_addr] + b ldxr_done + +ldxr_load64: + read_prep 64, ldxr_64 + ldr x0, [_addr] + +ldxr_done: + mov _addr, x24 // restore _addr + + // Save to exclusive monitor + str _addr, [_cpu, #CPU_excl_addr] + str _tmp, [_cpu, #CPU_excl_val] // _tmp = x0 = loaded value + movn x8, #0 + str x8, [_cpu, #CPU_excl_pair_addr] + str wzr, [_cpu, #CPU_excl_pair_size] + + // Store to Rt (unless Rt == 31 / XZR) + cmp x23, #31 + b.eq 1f + add x9, _cpu, #CPU_x0 + str _tmp, [x9, x23, lsl #3] +1: gret + + read_bullshit 8, ldxr_8 + read_bullshit 16, ldxr_16 + read_bullshit 32, ldxr_32 + read_bullshit 64, ldxr_64 + +/* + * STXR — Store exclusive via atomic CAS + * Code stream: [gadget addr][rt | (rs << 8) | (size << 16)] + * Expects _addr = guest address (from calc_addr_imm) + * Checks excl_addr match, does atomic CAS, stores result to Rs + */ +.gadget stxr + ldr x22, [_pc] + add _pc, _pc, #8 + + and x23, x22, #0x1f // rt (new value register) + ubfx x25, x22, #8, #5 // rs (status result register) + ubfx x26, x22, #16, #2 // size + + mov x24, _addr // save guest address + + // Check exclusive monitor: does excl_addr match current address? + ldr x8, [_cpu, #CPU_excl_addr] + cmp x8, _addr + b.ne stxr_fail // mismatch -> fail + + // Load the new value from Rt + add x12, _cpu, #CPU_x0 + cmp x23, #31 + b.eq 1f + ldr x13, [x12, x23, lsl #3] + b 2f +1: mov x13, #0 // XZR +2: + // Load expected value from exclusive monitor + ldr x14, [_cpu, #CPU_excl_val] + + // Call C helper: c_stxr_cas(tlb, addr, expected_val, new_val, size) + save_c + sub x0, _tlb, #TLB_entries // tlb struct pointer + mov x1, x24 // guest address + mov x2, x14 // expected value (from LDXR) + mov x3, x13 // new value (from Rt) + mov w4, w26 // size + bl NAME(c_stxr_cas) + mov w19, w0 // save result (0=success, 1=fail, -1=segfault) + restore_c + mov _addr, x24 // restore _addr + + // Check for segfault + cmn w19, #1 + b.eq stxr_segfault + + // Invalidate exclusive monitor + movn x8, #0 + str x8, [_cpu, #CPU_excl_addr] + + // Store result to Rs (w19 = 0 or 1) + cmp x25, #31 + b.eq 3f // Rs == XZR, discard + add x9, _cpu, #CPU_x0 + and x8, x19, #0xff // zero-extend w19 to 64-bit + str x8, [x9, x25, lsl #3] // store to Rs +3: gret + +stxr_fail: + // Exclusive monitor mismatch — store failed + movn x8, #0 + str x8, [_cpu, #CPU_excl_addr] + cmp x25, #31 + b.eq 4f + add x9, _cpu, #CPU_x0 + mov x8, #1 + str x8, [x9, x25, lsl #3] // Rs = 1 (failure) +4: gret + +stxr_segfault: + // Invalidate exclusive monitor + movn x8, #0 + str x8, [_cpu, #CPU_excl_addr] + str x24, [_cpu, #CPU_segfault_addr] + mov w8, #1 + strb w8, [_cpu, #CPU_segfault_was_write] + mov w0, #INT_GPF + b fiber_exit + +/* + * LDXP via C helper — avoids assembly TLB for pair exclusive loads. + * Code stream: [gadget addr][rt | (rt2 << 8) | (size << 16)] + * Expects _addr = guest address (from calc_addr_imm) + */ +.gadget ldxp_c + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f // rt + ubfx x25, x22, #8, #5 // rt2 + ubfx x26, x22, #16, #2 // size + mov x24, _addr // save guest address + + save_c + sub sp, sp, #16 // allocate stack space for outputs + sub x0, _tlb, #TLB_entries // tlb struct pointer + mov x1, x24 // guest address + mov x2, sp // val1 output + add x3, sp, #8 // val2 output + cmp x26, #3 + b.eq ldxp_c_64 + bl NAME(c_ldp32) + mov w19, w0 // save result + ldr w20, [sp] // val1 (32-bit LDXP zero-extends) + ldr w21, [sp, #8] // val2 (32-bit LDXP zero-extends) + b ldxp_c_done +ldxp_c_64: + bl NAME(c_ldp64) + mov w19, w0 // save result + ldr x20, [sp] // val1 + ldr x21, [sp, #8] // val2 +ldxp_c_done: + add sp, sp, #16 + restore_c + mov _addr, x24 // restore _addr + + // Check for segfault + cmn w19, #1 + b.eq ldxp_c_segfault + + // Save pair exclusive monitor state + str x24, [_cpu, #CPU_excl_pair_addr] + str x20, [_cpu, #CPU_excl_pair_val_lo] + str x21, [_cpu, #CPU_excl_pair_val_hi] + str w26, [_cpu, #CPU_excl_pair_size] + movn x8, #0 + str x8, [_cpu, #CPU_excl_addr] + + // Store to Rt + add x9, _cpu, #CPU_x0 + cmp x23, #31 + b.eq 1f + str x20, [x9, x23, lsl #3] +1: cmp x25, #31 + b.eq 2f + str x21, [x9, x25, lsl #3] +2: gret + +ldxp_c_segfault: + str x24, [_cpu, #CPU_segfault_addr] + strb wzr, [_cpu, #CPU_segfault_was_write] + mov w0, #INT_GPF + b fiber_exit + +/* + * STXP/STLXP via C helper. + * Code stream: [gadget addr][rs | (rt << 8) | (rt2 << 16) | (size << 24)] + * Expects _addr = guest address (from calc_addr_imm) + */ +.gadget stxp_c + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f // rs (status result) + ubfx x24, x22, #8, #5 // rt (new lo) + ubfx x25, x22, #16, #5 // rt2 (new hi) + ubfx x26, x22, #24, #2 // size + mov x27, _addr // save guest address + + // Load new values from guest regs + add x9, _cpu, #CPU_x0 + cmp x24, #31 + b.eq 1f + ldr x20, [x9, x24, lsl #3] + b 2f +1: mov x20, #0 +2: cmp x25, #31 + b.eq 3f + ldr x21, [x9, x25, lsl #3] + b 4f +3: mov x21, #0 +4: + // Check exclusive monitor state from the preceding LDXP/LDAXP + ldr x10, [_cpu, #CPU_excl_pair_addr] + ldr w11, [_cpu, #CPU_excl_pair_size] + cmp x10, x27 + b.ne stxp_c_fail + cmp w11, w26 + b.ne stxp_c_fail + + // Call C helper: c_stxp_pair(tlb, addr, old_lo, old_hi, new_lo, new_hi, size) + ldr x19, [_cpu, #CPU_excl_pair_val_lo] + ldr x22, [_cpu, #CPU_excl_pair_val_hi] + save_c + sub x0, _tlb, #TLB_entries + mov x1, x27 + mov x2, x19 + mov x3, x22 + mov x4, x20 + mov x5, x21 + mov w6, w26 + bl NAME(c_stxp_pair) + mov w19, w0 + restore_c + mov _addr, x27 + + // Invalidate pair exclusive monitor after the attempt + movn x8, #0 + str x8, [_cpu, #CPU_excl_pair_addr] + str wzr, [_cpu, #CPU_excl_pair_size] + + cmn w19, #1 + b.eq stxp_c_segfault + + // Store status to Rs (0=success, 1=failure) + add x9, _cpu, #CPU_x0 + cmp x23, #31 + b.eq 6f + and x8, x19, #0xffffffff + str x8, [x9, x23, lsl #3] +6: gret + +stxp_c_fail: + movn x8, #0 + str x8, [_cpu, #CPU_excl_pair_addr] + str wzr, [_cpu, #CPU_excl_pair_size] + add x9, _cpu, #CPU_x0 + cmp x23, #31 + b.eq 7f + mov x8, #1 + str x8, [x9, x23, lsl #3] +7: gret + +stxp_c_segfault: + str x27, [_cpu, #CPU_segfault_addr] + mov w8, #1 + strb w8, [_cpu, #CPU_segfault_was_write] + mov w0, #INT_GPF + b fiber_exit + +// 32-bit CASP (sz=0): an 8-byte atomic over the {Ws,W(s+1)} / {Wt,W(t+1)} +// register pairs. Ws is the low word, W(s+1) the high word of a 64-bit value. +// We assemble the two 32-bit halves into 64-bit expected/desired words and do +// a single 8-byte CAS via c_atomic_cas (size=3), then split the old value back +// into Ws / W(s+1). This is NOT a 128-bit op (that would be the 64-bit CASP). +.gadget atomic_casp32 + ldr x22, [_pc] + add _pc, _pc, #8 + and x23, x22, #0x1f // rs + ubfx x25, x22, #8, #5 // rt + mov x24, _addr // save guest address + + add x12, _cpu, #CPU_x0 + // expected = W(s+1):Ws (Rs=31 => WZR pair = 0). The register file is + // 8-byte strided, so compute each element's byte address (reg<<3) and do a + // 32-bit load — `ldr w, [base, reg, lsl #3]` is not a legal addressing mode. + cmp x23, #31 + b.eq 1f + add x9, x12, x23, lsl #3 // &Ws + ldr w13, [x9] // exp_lo (Ws, zero-extended) + ldr w15, [x9, #8] // exp_hi (W(s+1)) + orr x13, x13, x15, lsl #32 + b 2f +1: mov x13, #0 +2: + // desired = W(t+1):Wt (Rt=31 => WZR pair = 0) + cmp x25, #31 + b.eq 3f + add x10, x12, x25, lsl #3 // &Wt + ldr w14, [x10] // des_lo (Wt) + ldr w15, [x10, #8] // des_hi (W(t+1)) + orr x14, x14, x15, lsl #32 + b 4f +3: mov x14, #0 +4: + sub sp, sp, #16 + save_c + sub x0, _tlb, #TLB_entries // tlb + mov x1, x24 // guest address + mov x2, x13 // expected (packed 64-bit) + mov x3, x14 // desired (packed 64-bit) + mov w4, #3 // size = 3 (8 bytes) + add x5, sp, #0xa0 // &old + bl NAME(c_atomic_cas) + mov w19, w0 + restore_c + mov _addr, x24 + cbnz w19, atomic_casp_segfault + ldr x20, [sp] // old packed value + add sp, sp, #16 + + // Write old value back into Ws, W(s+1) (32-bit writes zero the top half) + cmp x23, #31 + b.eq 5f + add x9, _cpu, #CPU_x0 + add x9, x9, x23, lsl #3 // &Ws + str w20, [x9] // Ws = old_lo + lsr x20, x20, #32 + str w20, [x9, #8] // W(s+1) = old_hi +5: gret + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gen.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gen.c new file mode 100644 index 0000000000..b038c6ee44 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/guest-arm64/gen.c @@ -0,0 +1,7454 @@ +/* + * ARM64 Guest Instruction Generator + * + * This file translates ARM64 guest instructions into gadget sequences + * that can be executed by the asbestos JIT engine. + * + * ARM64 uses fixed-width 32-bit instructions. The instruction encoding + * follows a consistent pattern based on the top 4 bits (op0 field). + * + * Return value convention: + * - return 1 (true): instruction compiled, continue with next instruction + * - return 0 (false): block ended (branch, syscall, or error) + * + * Gadget calling convention: + * - _cpu (x1) points to cpu_state + * - _tlb (x2) points to TLB + * - _pc (x28) is the gadget instruction pointer + * - Guest registers are accessed via memory at CPU_x0 + reg * 8 + */ + +#include <assert.h> +#include <stdlib.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> +#include "asbestos/gen.h" +#include "emu/arch/arm64/decode.h" +#include "emu/interrupt.h" + +// Gadget declarations +extern void gadget_interrupt(void); +extern void gadget_exit(void); +extern void gadget_set_pc(void); +extern void gadget_set_jit_saved_pc(void); +extern void gadget_trace(void); +extern void gadget_check_highbits(void); + +static bool arm64_fusion_stats_enabled; +static bool arm64_internal_continue_enabled; +static bool arm64_internal_continue_taken_enabled; +static uint64_t arm64_fusion_cmp_bcond_count; +static uint64_t arm64_fusion_subs_bcond_count; +static uint64_t arm64_fusion_adrp_add_count; +static uint64_t arm64_fusion_adrp_ldr64_count; +static uint64_t arm64_fusion_addsub_fast_count; +static uint64_t arm64_fusion_addsub_cbz_count; +static uint64_t arm64_fusion_addsub_ldr64_count; +static uint64_t arm64_fusion_addsub_ldr32_count; +static uint64_t arm64_fusion_addsub_ldr16_count; +static uint64_t arm64_fusion_addsub_ldr8_count; +static uint64_t arm64_fusion_addsub_str64_count; +static uint64_t arm64_fusion_addsub_str32_count; +static uint64_t arm64_fusion_addsub_str16_count; +static uint64_t arm64_fusion_addsub_str8_count; +static uint64_t arm64_fusion_ldr64_cbz64_count; +static uint64_t arm64_fusion_ldr64_sp_cbz64_count; +static uint64_t arm64_fusion_ldr32_sx_cbz64_count; +static uint64_t arm64_fusion_ldr16_sx_cbz_count; +static uint64_t arm64_fusion_ldr8_sx_cbz_count; +static uint64_t arm64_fusion_ldr32_cbz32_count; +static uint64_t arm64_fusion_ldr16_cbz32_count; +static uint64_t arm64_fusion_ldr8_cbz32_count; +static uint64_t arm64_fusion_addsub_ldr_candidate_count; +static uint64_t arm64_fusion_addsub_str_candidate_count; +static uint64_t arm64_fusion_ldr_cbz_candidate_count; +static uint64_t arm64_fusion_ldr64_cbz64_candidate_count; +static uint64_t arm64_fusion_ldr64_sp_cbz64_candidate_count; +static uint64_t arm64_fusion_ldr32_sx_cbz64_candidate_count; +static uint64_t arm64_fusion_ldr16_sx_cbz_candidate_count; +static uint64_t arm64_fusion_ldr8_sx_cbz_candidate_count; +static uint64_t arm64_internal_continue_count; +static uint64_t arm64_internal_continue_bcond_fallthrough_count; +static uint64_t arm64_internal_continue_bcond_taken_count; +static uint64_t arm64_internal_continue_cbz_fallthrough_count; +static uint64_t arm64_internal_continue_cbz_taken_count; +static uint64_t arm64_internal_continue_tbz_fallthrough_count; +static uint64_t arm64_internal_continue_tbz_taken_count; +static bool arm64_fusion_stats_dumped; + +void arm64_fusion_stats_dump_if_enabled(void) { + if (!arm64_fusion_stats_enabled || arm64_fusion_stats_dumped) + return; + arm64_fusion_stats_dumped = true; + fprintf(stderr, + "ARM64_FUSION_STATS cmp_bcond=%llu subs_bcond=%llu adrp_add=%llu adrp_ldr64=%llu addsub_fast=%llu addsub_cbz=%llu addsub_ldr64=%llu addsub_ldr32=%llu addsub_ldr16=%llu addsub_ldr8=%llu addsub_str64=%llu addsub_str32=%llu addsub_str16=%llu addsub_str8=%llu ldr64_cbz64=%llu ldr64_sp_cbz64=%llu ldr32_sx_cbz64=%llu ldr16_sx_cbz=%llu ldr8_sx_cbz=%llu ldr32_cbz32=%llu ldr16_cbz32=%llu ldr8_cbz32=%llu addsub_ldr_cand=%llu addsub_str_cand=%llu ldr_cbz_cand=%llu ldr64_cbz64_cand=%llu ldr64_sp_cbz64_cand=%llu ldr32_sx_cbz64_cand=%llu ldr16_sx_cbz_cand=%llu ldr8_sx_cbz_cand=%llu internal_continue=%llu internal_continue_bcond_fallthrough=%llu internal_continue_bcond_taken=%llu internal_continue_cbz_fallthrough=%llu internal_continue_cbz_taken=%llu internal_continue_tbz_fallthrough=%llu internal_continue_tbz_taken=%llu\n", + (unsigned long long)arm64_fusion_cmp_bcond_count, + (unsigned long long)arm64_fusion_subs_bcond_count, + (unsigned long long)arm64_fusion_adrp_add_count, + (unsigned long long)arm64_fusion_adrp_ldr64_count, + (unsigned long long)arm64_fusion_addsub_fast_count, + (unsigned long long)arm64_fusion_addsub_cbz_count, + (unsigned long long)arm64_fusion_addsub_ldr64_count, + (unsigned long long)arm64_fusion_addsub_ldr32_count, + (unsigned long long)arm64_fusion_addsub_ldr16_count, + (unsigned long long)arm64_fusion_addsub_ldr8_count, + (unsigned long long)arm64_fusion_addsub_str64_count, + (unsigned long long)arm64_fusion_addsub_str32_count, + (unsigned long long)arm64_fusion_addsub_str16_count, + (unsigned long long)arm64_fusion_addsub_str8_count, + (unsigned long long)arm64_fusion_ldr64_cbz64_count, + (unsigned long long)arm64_fusion_ldr64_sp_cbz64_count, + (unsigned long long)arm64_fusion_ldr32_sx_cbz64_count, + (unsigned long long)arm64_fusion_ldr16_sx_cbz_count, + (unsigned long long)arm64_fusion_ldr8_sx_cbz_count, + (unsigned long long)arm64_fusion_ldr32_cbz32_count, + (unsigned long long)arm64_fusion_ldr16_cbz32_count, + (unsigned long long)arm64_fusion_ldr8_cbz32_count, + (unsigned long long)arm64_fusion_addsub_ldr_candidate_count, + (unsigned long long)arm64_fusion_addsub_str_candidate_count, + (unsigned long long)arm64_fusion_ldr_cbz_candidate_count, + (unsigned long long)arm64_fusion_ldr64_cbz64_candidate_count, + (unsigned long long)arm64_fusion_ldr64_sp_cbz64_candidate_count, + (unsigned long long)arm64_fusion_ldr32_sx_cbz64_candidate_count, + (unsigned long long)arm64_fusion_ldr16_sx_cbz_candidate_count, + (unsigned long long)arm64_fusion_ldr8_sx_cbz_candidate_count, + (unsigned long long)arm64_internal_continue_count, + (unsigned long long)arm64_internal_continue_bcond_fallthrough_count, + (unsigned long long)arm64_internal_continue_bcond_taken_count, + (unsigned long long)arm64_internal_continue_cbz_fallthrough_count, + (unsigned long long)arm64_internal_continue_cbz_taken_count, + (unsigned long long)arm64_internal_continue_tbz_fallthrough_count, + (unsigned long long)arm64_internal_continue_tbz_taken_count); + fflush(stderr); +} + +void arm64_fusion_stats_set_enabled_from_env(const char *env) { + arm64_fusion_stats_enabled = env != NULL && env[0] != '\0' && strcmp(env, "0") != 0; +} + +void arm64_internal_continue_set_enabled_from_env(const char *env) { + arm64_internal_continue_enabled = env != NULL && env[0] != '\0' && strcmp(env, "0") != 0; +} + +void arm64_internal_continue_taken_set_enabled_from_env(const char *env) { + arm64_internal_continue_taken_enabled = env != NULL && env[0] != '\0' && strcmp(env, "0") != 0; +} + +#define ARM64_FUSION_STAT_INC(counter) do { \ + if (arm64_fusion_stats_enabled) \ + (counter)++; \ +} while (0) + +#define ARM64_INTERNAL_CONTINUE_STAT_INC(counter) do { \ + ARM64_FUSION_STAT_INC(arm64_internal_continue_count); \ + ARM64_FUSION_STAT_INC(counter); \ +} while (0) + +// Data processing gadgets +extern void gadget_load_reg(void); +extern void gadget_store_reg(void); +extern void gadget_store_addr_to_reg(void); // Store _addr to guest register +extern void gadget_movz(void); +extern void gadget_movk(void); +extern void gadget_movn(void); +extern void gadget_add_imm(void); +extern void gadget_sub_imm(void); +extern void gadget_add_reg(void); +extern void gadget_sub_reg(void); +extern void gadget_adc_reg(void); +extern void gadget_sbc_reg(void); +extern void gadget_and_reg(void); +extern void gadget_orr_reg(void); +extern void gadget_orr_reg_shifted(void); +extern void gadget_and_reg_shifted(void); +extern void gadget_eor_reg_shifted(void); +extern void gadget_eor_reg(void); +extern void gadget_mov_reg(void); +extern void gadget_mov_reg32(void); +extern void gadget_and_imm(void); +extern void gadget_orr_imm(void); +extern void gadget_eor_imm(void); +extern void gadget_adr(void); +extern void gadget_adrp(void); +extern void gadget_fused_adrp_ldr64(void); +extern void gadget_sxtw(void); +extern void gadget_sxth(void); +extern void gadget_sxtb(void); +extern void gadget_uxtw(void); +extern void gadget_uxth(void); +extern void gadget_uxtb(void); +extern void gadget_ubfm(void); +extern void gadget_sbfm(void); +extern void gadget_ubfm_fused(void); +extern void gadget_sbfm_fused(void); +extern void gadget_bfm(void); +extern void gadget_extr(void); + +// Branch gadgets +extern void gadget_branch(void); +extern void gadget_branch_link(void); +extern void gadget_branch_reg(void); +extern void gadget_branch_link_reg(void); +extern void gadget_ret(void); +extern void gadget_cbz(void); +extern void gadget_cbnz(void); +extern void gadget_cbz_64(void); +extern void gadget_cbz_32(void); +extern void gadget_cbnz_64(void); +extern void gadget_cbnz_32(void); +extern void gadget_cbz_fallthrough_internal(void); +extern void gadget_cbz_taken_internal(void); +extern void gadget_tbz(void); +extern void gadget_tbnz(void); +extern void gadget_tbz_fallthrough_internal(void); +extern void gadget_tbz_taken_internal(void); +extern void gadget_bcond(void); +extern void gadget_svc(void); + +// Flag-setting gadgets +extern void gadget_subs_reg(void); +extern void gadget_adds_reg(void); + +// Specialized ALU gadgets (64-bit fast paths) +extern void gadget_add_imm_64(void); +extern void gadget_sub_imm_64(void); +extern void gadget_add_imm_sp_src_64(void); +extern void gadget_sub_imm_sp_src_64(void); +extern void gadget_adds_imm_64(void); +extern void gadget_subs_imm_64(void); +extern void gadget_adds_imm_64_sh(void); +extern void gadget_subs_imm_64_sh(void); +extern void gadget_add_imm_64_sh(void); +extern void gadget_sub_imm_64_sh(void); +// 32-bit specialized add/sub immediate gadgets +extern void gadget_add_imm_32(void); +extern void gadget_sub_imm_32(void); +extern void gadget_adds_imm_32(void); +extern void gadget_subs_imm_32(void); +extern void gadget_fused_addsub_cbz(void); +extern void gadget_fused_addsub_cbnz(void); +extern void gadget_fused_addsub_ldr64_imm(void); +extern void gadget_fused_addsub_ldr32_imm(void); +extern void gadget_fused_addsub_ldr16_imm(void); +extern void gadget_fused_addsub_ldr8_imm(void); +extern void gadget_fused_addsub_str64_imm(void); +extern void gadget_fused_addsub_str32_imm(void); +extern void gadget_fused_addsub_str16_imm(void); +extern void gadget_fused_addsub_str8_imm(void); +extern void gadget_fused_ldr64_cbz_imm(void); +extern void gadget_fused_ldr64_cbnz_imm(void); +extern void gadget_fused_ldr64_sp_cbz_imm(void); +extern void gadget_fused_ldr64_sp_cbnz_imm(void); +extern void gadget_fused_ldr32_sx_cbz_imm(void); +extern void gadget_fused_ldr32_sx_cbnz_imm(void); +extern void gadget_fused_ldr_sx_cbz_imm(void); +extern void gadget_fused_ldr_sx_cbnz_imm(void); +extern void gadget_fused_ldr32_cbz_imm(void); +extern void gadget_fused_ldr32_cbnz_imm(void); +extern void gadget_fused_ldr16_cbz_imm(void); +extern void gadget_fused_ldr16_cbnz_imm(void); +extern void gadget_fused_ldr8_cbz_imm(void); +extern void gadget_fused_ldr8_cbnz_imm(void); +extern void gadget_adds_reg_64_nshift(void); +extern void gadget_subs_reg_64_nshift(void); +extern void gadget_add_reg_64_nshift(void); +extern void gadget_sub_reg_64_nshift(void); + +// Per-condition bcond gadgets +extern void gadget_bcond_eq(void); +extern void gadget_bcond_ne(void); +extern void gadget_bcond_cs(void); +extern void gadget_bcond_cc(void); +extern void gadget_bcond_mi(void); +extern void gadget_bcond_pl(void); +extern void gadget_bcond_vs(void); +extern void gadget_bcond_vc(void); +extern void gadget_bcond_hi(void); +extern void gadget_bcond_ls(void); +extern void gadget_bcond_ge(void); +extern void gadget_bcond_lt(void); +extern void gadget_bcond_gt(void); +extern void gadget_bcond_le(void); +extern void gadget_bcond_fallthrough_internal(void); +extern void gadget_bcond_taken_internal(void); +extern void gadget_internal_continue(void); + +// Fused CMP-imm + B.cond gadgets (rd=31, CMP only sets flags) +extern void gadget_fused_cmp_bcond_eq(void); +extern void gadget_fused_cmp_bcond_ne(void); +extern void gadget_fused_cmp_bcond_cs(void); +extern void gadget_fused_cmp_bcond_cc(void); +extern void gadget_fused_cmp_bcond_mi(void); +extern void gadget_fused_cmp_bcond_pl(void); +extern void gadget_fused_cmp_bcond_vs(void); +extern void gadget_fused_cmp_bcond_vc(void); +extern void gadget_fused_cmp_bcond_hi(void); +extern void gadget_fused_cmp_bcond_ls(void); +extern void gadget_fused_cmp_bcond_ge(void); +extern void gadget_fused_cmp_bcond_lt(void); +extern void gadget_fused_cmp_bcond_gt(void); +extern void gadget_fused_cmp_bcond_le(void); + +// Fused SUBS-imm + B.cond gadgets (rd!=31, stores result AND sets flags) +extern void gadget_fused_subs_bcond_eq(void); +extern void gadget_fused_subs_bcond_ne(void); +extern void gadget_fused_subs_bcond_cs(void); +extern void gadget_fused_subs_bcond_cc(void); +extern void gadget_fused_subs_bcond_mi(void); +extern void gadget_fused_subs_bcond_pl(void); +extern void gadget_fused_subs_bcond_vs(void); +extern void gadget_fused_subs_bcond_vc(void); +extern void gadget_fused_subs_bcond_hi(void); +extern void gadget_fused_subs_bcond_ls(void); +extern void gadget_fused_subs_bcond_ge(void); +extern void gadget_fused_subs_bcond_lt(void); +extern void gadget_fused_subs_bcond_gt(void); +extern void gadget_fused_subs_bcond_le(void); + +// 32-bit fused CMP-imm + B.cond gadgets (rd=31, 32-bit compare) +extern void gadget_fused_cmp32_bcond_eq(void); +extern void gadget_fused_cmp32_bcond_ne(void); +extern void gadget_fused_cmp32_bcond_cs(void); +extern void gadget_fused_cmp32_bcond_cc(void); +extern void gadget_fused_cmp32_bcond_mi(void); +extern void gadget_fused_cmp32_bcond_pl(void); +extern void gadget_fused_cmp32_bcond_vs(void); +extern void gadget_fused_cmp32_bcond_vc(void); +extern void gadget_fused_cmp32_bcond_hi(void); +extern void gadget_fused_cmp32_bcond_ls(void); +extern void gadget_fused_cmp32_bcond_ge(void); +extern void gadget_fused_cmp32_bcond_lt(void); +extern void gadget_fused_cmp32_bcond_gt(void); +extern void gadget_fused_cmp32_bcond_le(void); + +// 32-bit fused SUBS-imm + B.cond gadgets (rd!=31, 32-bit subtract) +extern void gadget_fused_subs32_bcond_eq(void); +extern void gadget_fused_subs32_bcond_ne(void); +extern void gadget_fused_subs32_bcond_cs(void); +extern void gadget_fused_subs32_bcond_cc(void); +extern void gadget_fused_subs32_bcond_mi(void); +extern void gadget_fused_subs32_bcond_pl(void); +extern void gadget_fused_subs32_bcond_vs(void); +extern void gadget_fused_subs32_bcond_vc(void); +extern void gadget_fused_subs32_bcond_hi(void); +extern void gadget_fused_subs32_bcond_ls(void); +extern void gadget_fused_subs32_bcond_ge(void); +extern void gadget_fused_subs32_bcond_lt(void); +extern void gadget_fused_subs32_bcond_gt(void); +extern void gadget_fused_subs32_bcond_le(void); + +// Conditional select +extern void gadget_csel(void); +extern void gadget_csinc(void); +extern void gadget_csinv(void); +extern void gadget_csneg(void); + +// Conditional compare +extern void gadget_ccmp_reg(void); +extern void gadget_ccmn_reg(void); +extern void gadget_ccmp_imm(void); +extern void gadget_ccmn_imm(void); + +// SIMD gadgets (minimal set for memset) +extern void gadget_dup_gpr_to_v16b(void); // DUP Vd.16B, Wn +extern void gadget_dup_gpr_to_vec(void); // DUP Vd.<T>, Wn (general - all element sizes) +extern void gadget_dup_elem_vec(void); // DUP Vd.<T>, Vn.<Ts>[idx] (element to vector) +extern void gadget_dup_elem_scalar(void); // DUP <V>d, Vn.<T>[idx] (element to scalar) +extern void gadget_ins_elem_vec(void); // INS Vd.<T>[idx1], Vn.<T>[idx2] (element to element) +extern void gadget_mov_v_to_gpr(void); // MOV Xd, Vn.D[0] +extern void gadget_umov_vec_to_gpr(void); // UMOV/MOV Wd, Vn.<T>[idx] +extern void gadget_ins_gpr_to_vec_s(void); // MOV Vd.S[idx], Wn (INS from GPR) +extern void gadget_ins_gpr_to_vec_d(void); // MOV Vd.D[idx], Xn (INS from GPR) +extern void gadget_ins_gpr_to_vec_b(void); // MOV Vd.B[idx], Wn (INS from GPR, byte) +extern void gadget_ins_gpr_to_vec_h(void); // MOV Vd.H[idx], Wn (INS from GPR, halfword) +extern void gadget_str_q(void); // STR Qn, [addr] +extern void gadget_stur_q(void); // STUR Qn, [addr, #imm] +extern void gadget_stp_q(void); // STP Qn, Qm, [addr] +extern void gadget_movi_v(void); // MOVI/MVNI Vd, #imm +extern void gadget_set_vec_imm(void); // Set vector immediate (raw 128-bit) +extern void gadget_orr_imm_vec(void); // ORR Vd, #imm (vector) +extern void gadget_bic_imm_vec(void); // BIC Vd, #imm (vector) +extern void gadget_ushl_vec(void); // USHL Vd, Vn, Vm (vector shift left) +extern void gadget_sshl_vec(void); // SSHL Vd, Vn, Vm (signed shift left) +extern void gadget_sshll_vec_s_to_d(void); // SSHLL Vd.2D, Vn.2S, #imm +extern void gadget_ushll_vec_s_to_d(void); // USHLL Vd.2D, Vn.2S, #imm +extern void gadget_sshll_vec_b_to_h(void); // SSHLL Vd.8H, Vn.8B, #imm +extern void gadget_ushll_vec_b_to_h(void); // USHLL Vd.8H, Vn.8B, #imm +extern void gadget_sshll_vec_h_to_s(void); // SSHLL Vd.4S, Vn.4H, #imm +extern void gadget_ushll_vec_h_to_s(void); // USHLL Vd.4S, Vn.4H, #imm +extern void gadget_sshll2_vec_b_to_h(void); // SSHLL2 Vd.8H, Vn.16B, #imm +extern void gadget_ushll2_vec_b_to_h(void); // USHLL2 Vd.8H, Vn.16B, #imm +extern void gadget_sshll2_vec_h_to_s(void); // SSHLL2 Vd.4S, Vn.8H, #imm +extern void gadget_ushll2_vec_h_to_s(void); // USHLL2 Vd.4S, Vn.8H, #imm +extern void gadget_sshll2_vec_s_to_d(void); // SSHLL2 Vd.2D, Vn.4S, #imm +extern void gadget_ushll2_vec_s_to_d(void); // USHLL2 Vd.2D, Vn.4S, #imm +extern void gadget_shll_vec_b_to_h(void); // SHLL Vd.8H, Vn.8B, #8 +extern void gadget_shll_vec_h_to_s(void); // SHLL Vd.4S, Vn.4H, #16 +extern void gadget_shll_vec_s_to_d(void); // SHLL Vd.2D, Vn.2S, #32 +extern void gadget_shll2_vec_b_to_h(void); // SHLL2 Vd.8H, Vn.16B, #8 +extern void gadget_shll2_vec_h_to_s(void); // SHLL2 Vd.4S, Vn.8H, #16 +extern void gadget_shll2_vec_s_to_d(void); // SHLL2 Vd.2D, Vn.4S, #32 +extern void gadget_shl_imm_vec(void); // SHL Vd, Vn, #imm (shift left immediate) +extern void gadget_shl_imm_scalar(void); // SHL Dd, Dn, #imm (scalar shift left immediate) +extern void gadget_sshr_imm_vec(void); // SSHR Vd, Vn, #imm (signed shift right immediate) +extern void gadget_sshr_imm_scalar(void); // SSHR Dd, Dn, #imm (scalar signed shift right) +extern void gadget_ushr_imm_vec(void); // USHR Vd, Vn, #imm (unsigned shift right immediate) +extern void gadget_ushr_imm_scalar(void); // USHR Dd, Dn, #imm (scalar unsigned shift right) +extern void gadget_ssra_imm_vec(void); // SSRA Vd, Vn, #imm (signed shift right and accumulate) +extern void gadget_ssra_imm_scalar(void); // SSRA Dd, Dn, #imm (scalar signed shift right and accumulate) +extern void gadget_usra_imm_vec(void); // USRA Vd, Vn, #imm (unsigned shift right and accumulate) +extern void gadget_usra_imm_scalar(void); // USRA Dd, Dn, #imm (scalar unsigned shift right and accumulate) +extern void gadget_srshr_imm_vec(void); // SRSHR Vd, Vn, #imm (signed rounding shift right) +extern void gadget_urshr_imm_vec(void); // URSHR Vd, Vn, #imm (unsigned rounding shift right) +extern void gadget_srsra_imm_vec(void); // SRSRA Vd, Vn, #imm (signed rounding shift right and accumulate) +extern void gadget_ursra_imm_vec(void); // URSRA Vd, Vn, #imm (unsigned rounding shift right and accumulate) +extern void gadget_scvtf_fixpt_scalar(void); // SCVTF Dd/Sd, Dn/Sn, #fbits (signed int to FP fixed-point) +extern void gadget_ucvtf_fixpt_scalar(void); // UCVTF Dd/Sd, Dn/Sn, #fbits (unsigned int to FP fixed-point) +extern void gadget_fcvtzs_fixpt_scalar(void); // FCVTZS Dd/Sd, Dn/Sn, #fbits (FP to signed int fixed-point, SIMD) +extern void gadget_fcvtzu_fixpt_scalar(void); // FCVTZU Dd/Sd, Dn/Sn, #fbits (FP to unsigned int fixed-point, SIMD) +extern void gadget_fcvtzs_fixpt_gpr(void); // FCVTZS Wd/Xd, Sn/Dn, #fbits (FP to signed int fixed-point, GPR) +extern void gadget_fcvtzu_fixpt_gpr(void); // FCVTZU Wd/Xd, Sn/Dn, #fbits (FP to unsigned int fixed-point, GPR) +extern void gadget_scvtf_fixpt_gpr(void); // SCVTF Sd/Dd, Wn/Xn, #fbits (signed int to FP fixed-point, GPR) +extern void gadget_ucvtf_fixpt_gpr(void); // UCVTF Sd/Dd, Wn/Xn, #fbits (unsigned int to FP fixed-point, GPR) +extern void gadget_add_scalar_i64(void); // ADD Dd, Dn, Dm (scalar 64-bit integer) +extern void gadget_sub_scalar_i64(void); // SUB Dd, Dn, Dm (scalar 64-bit integer) +// FP vector three-same +extern void gadget_fp_fadd_vec(void); +extern void gadget_fp_fsub_vec(void); +extern void gadget_fp_fmul_vec(void); +extern void gadget_fp_fdiv_vec(void); +extern void gadget_fp_fmulx_vec(void); +extern void gadget_fp_fmla_vec(void); +extern void gadget_fp_fmls_vec(void); +extern void gadget_fp_fmax_vec(void); +extern void gadget_fp_fmin_vec(void); +extern void gadget_fp_fmaxnm_vec(void); +extern void gadget_fp_fminnm_vec(void); +extern void gadget_fp_faddp_vec(void); +extern void gadget_fp_fmaxp_vec(void); +extern void gadget_fp_fminp_vec(void); +extern void gadget_fp_frecps_vec(void); +extern void gadget_fp_frsqrts_vec(void); +extern void gadget_fp_fcmeq_vec(void); +extern void gadget_fp_fcmge_vec(void); +extern void gadget_fp_fcmgt_vec(void); +extern void gadget_fp_facge_vec(void); +extern void gadget_fp_facgt_vec(void); +extern void gadget_fp_fabd_vec(void); +// Integer vector three-same shifts +extern void gadget_srshl_vec(void); // SRSHL Vd, Vn, Vm (signed rounding shift left) +extern void gadget_urshl_vec(void); // URSHL Vd, Vn, Vm (unsigned rounding shift left) +extern void gadget_sqshl_vec(void); // SQSHL Vd, Vn, Vm (signed saturating shift left) +extern void gadget_uqshl_vec(void); // UQSHL Vd, Vn, Vm (unsigned saturating shift left) +extern void gadget_sqrshl_vec(void); // SQRSHL Vd, Vn, Vm (signed saturating rounding shift left) +extern void gadget_uqrshl_vec(void); // UQRSHL Vd, Vn, Vm (unsigned saturating rounding shift left) +extern void gadget_ushl_scalar_i64(void); // USHL Dd, Dn, Dm (scalar unsigned shift left) +extern void gadget_sshl_scalar_i64(void); // SSHL Dd, Dn, Dm (scalar signed shift left) +extern void gadget_cmhi_scalar_i64(void); // CMHI Dd, Dn, Dm (scalar compare higher unsigned) +extern void gadget_cmhs_scalar_i64(void); // CMHS Dd, Dn, Dm (scalar compare higher or same) +extern void gadget_cmgt_scalar_i64(void); // CMGT Dd, Dn, Dm (scalar compare greater than) +extern void gadget_cmge_scalar_i64(void); // CMGE Dd, Dn, Dm (scalar compare greater or equal) +extern void gadget_cmeq_scalar_i64(void); // CMEQ Dd, Dn, Dm (scalar compare equal) +extern void gadget_sri_imm_vec(void); // SRI Vd, Vn, #imm (shift right and insert) +extern void gadget_sli_imm_vec(void); // SLI Vd, Vn, #imm (shift left and insert) +extern void gadget_cmhi_vec(void); // CMHI Vd, Vn, Vm (unsigned compare greater) +extern void gadget_cmhs_vec(void); // CMHS Vd, Vn, Vm (unsigned compare greater or equal) +extern void gadget_cmeq_vec(void); // CMEQ Vd, Vn, Vm (compare equal) +extern void gadget_cmeq_zero_vec(void); // CMEQ Vd, Vn, #0 (compare equal to zero) +extern void gadget_ld1r_vec(void); // LD1R {Vt.T}, [Xn] (load single and replicate) +extern void gadget_ld2r_vec(void); // LD2R {Vt.T, Vt2.T}, [Xn] +extern void gadget_ld3r_vec(void); // LD3R {Vt.T, Vt2.T, Vt3.T}, [Xn] +extern void gadget_ld4r_vec(void); // LD4R {Vt.T, Vt2.T, Vt3.T, Vt4.T}, [Xn] +extern void gadget_shrn_vec(void); // SHRN/SHRN2 Vd, Vn, #shift (shift right narrow) +extern void gadget_rshrn_vec(void); // RSHRN/RSHRN2 Vd, Vn, #shift (rounding shift right narrow) +extern void gadget_uqrshrn_vec(void); // UQRSHRN - unsigned saturating rounding shift right narrow +extern void gadget_sqrshrn_vec(void); // SQRSHRN - signed saturating rounding shift right narrow +extern void gadget_uqshrn_vec(void); // UQSHRN - unsigned saturating shift right narrow +extern void gadget_sqshrn_vec(void); // SQSHRN - signed saturating shift right narrow +extern void gadget_sqshrun_vec(void); // SQSHRUN - signed saturating shift right unsigned narrow +extern void gadget_sqrshrun_vec(void); // SQRSHRUN - signed saturating rounding shift right unsigned narrow +extern void gadget_uaddlp_vec(void); // UADDLP Vd, Vn (unsigned add long pairwise) +extern void gadget_saddlp_vec(void); // SADDLP Vd, Vn (signed add long pairwise) +extern void gadget_uadalp_vec(void); // UADALP Vd, Vn (unsigned add and accumulate long pairwise) +extern void gadget_sadalp_vec(void); // SADALP Vd, Vn (signed add and accumulate long pairwise) +extern void gadget_sqxtun_vec(void); // SQXTUN Vd, Vn (signed sat extract unsigned narrow) +extern void gadget_sqxtn_vec(void); // SQXTN Vd, Vn (signed sat extract narrow) +extern void gadget_uqxtn_vec(void); // UQXTN Vd, Vn (unsigned sat extract narrow) +extern void gadget_cmgt_zero_vec(void); // CMGT Vd, Vn, #0 (compare greater than zero) +extern void gadget_cmge_zero_vec(void); // CMGE Vd, Vn, #0 (compare greater or equal zero) +extern void gadget_cmlt_zero_vec(void); // CMLT Vd, Vn, #0 (compare less than zero) +extern void gadget_cmle_zero_vec(void); // CMLE Vd, Vn, #0 (compare less or equal zero) +extern void gadget_and_vec(void); // AND Vd, Vn, Vm (bitwise AND) +extern void gadget_orr_vec(void); // ORR Vd, Vn, Vm (bitwise OR) +extern void gadget_eor_vec(void); // EOR Vd, Vn, Vm (bitwise XOR) +extern void gadget_bic_vec(void); // BIC Vd, Vn, Vm (bit clear) +extern void gadget_bsl_vec(void); // BSL Vd, Vn, Vm (bitwise select) +extern void gadget_bit_vec(void); // BIT Vd, Vn, Vm (bitwise insert) +extern void gadget_bif_vec(void); // BIF Vd, Vn, Vm (bitwise insert if false) +extern void gadget_addp_vec(void); // ADDP Vd, Vn, Vm (add pairwise) +extern void gadget_umaxp_vec(void); // UMAXP Vd, Vn, Vm (unsigned max pairwise) +extern void gadget_uminp_vec(void); // UMINP Vd, Vn, Vm (unsigned min pairwise) +extern void gadget_smaxp_vec(void); // SMAXP Vd, Vn, Vm (signed max pairwise) +extern void gadget_sminp_vec(void); // SMINP Vd, Vn, Vm (signed min pairwise) +extern void gadget_sqdmulh_vec(void); // SQDMULH Vd, Vn, Vm (signed sat doubling mul high) +extern void gadget_sqrdmulh_vec(void); // SQRDMULH Vd, Vn, Vm (signed sat rounding doubling mul high) +extern void gadget_abs_vec(void); // ABS Vd, Vn (absolute value) +extern void gadget_neg_vec(void); // NEG Vd, Vn (negate) +extern void gadget_clz_vec(void); // CLZ Vd, Vn (count leading zeros) +extern void gadget_cls_vec(void); // CLS Vd, Vn (count leading sign bits) +extern void gadget_not_vec(void); // NOT Vd, Vn (bitwise NOT, bytes only) +extern void gadget_rbit_vec(void); // RBIT Vd, Vn (reverse bits, bytes only) +extern void gadget_mul_vec(void); // MUL Vd, Vn, Vm (integer multiply) +extern void gadget_pmul_vec(void); // PMUL Vd.16B, Vn.16B, Vm.16B (polynomial multiply) +extern void gadget_mla_vec(void); // MLA Vd, Vn, Vm (multiply-accumulate) +extern void gadget_mls_vec(void); // MLS Vd, Vn, Vm (multiply-subtract) +extern void gadget_smax_vec(void); // SMAX Vd, Vn, Vm (signed maximum) +extern void gadget_umax_vec(void); // UMAX Vd, Vn, Vm (unsigned maximum) +extern void gadget_smin_vec(void); // SMIN Vd, Vn, Vm (signed minimum) +extern void gadget_umin_vec(void); // UMIN Vd, Vn, Vm (unsigned minimum) +extern void gadget_mul_elem_vec(void); // MUL Vd, Vn, Vm[idx] (multiply by element) +extern void gadget_mla_elem_vec(void); // MLA Vd, Vn, Vm[idx] (multiply-accumulate by element) +extern void gadget_mls_elem_vec(void); // MLS Vd, Vn, Vm[idx] (multiply-subtract by element) +extern void gadget_smull_elem_vec(void); // SMULL Vd, Vn, Vm[idx] (signed multiply long by element) +extern void gadget_umull_elem_vec(void); // UMULL Vd, Vn, Vm[idx] (unsigned multiply long by element) +extern void gadget_smlal_elem_vec(void); // SMLAL Vd, Vn, Vm[idx] (signed multiply-accumulate long by element) +extern void gadget_umlal_elem_vec(void); // UMLAL Vd, Vn, Vm[idx] (unsigned multiply-accumulate long by element) +extern void gadget_smlsl_elem_vec(void); // SMLSL Vd, Vn, Vm[idx] (signed multiply-subtract long by element) +extern void gadget_umlsl_elem_vec(void); // UMLSL Vd, Vn, Vm[idx] (unsigned multiply-subtract long by element) +extern void gadget_fmul_elem_vec(void); // FMUL Vd, Vn, Vm[idx] (FP multiply by element) +extern void gadget_fmla_elem_vec(void); // FMLA Vd, Vn, Vm[idx] (FP multiply-accumulate by element) +extern void gadget_fmls_elem_vec(void); // FMLS Vd, Vn, Vm[idx] (FP multiply-subtract by element) +extern void gadget_fmul_elem_scalar(void); // FMUL Sd/Dd, Sn/Dn, Vm[idx] (scalar FP mul by element) +extern void gadget_fmla_elem_scalar(void); // FMLA Sd/Dd, Sn/Dn, Vm[idx] (scalar FP mul-accum by element) +extern void gadget_fmls_elem_scalar(void); // FMLS Sd/Dd, Sn/Dn, Vm[idx] (scalar FP mul-sub by element) +extern void gadget_fmulx_elem_scalar(void);// FMULX Sd/Dd, Sn/Dn, Vm[idx] (scalar FP mulx by element) +extern void gadget_sqdmulh_elem_vec(void); // SQDMULH Vd, Vn, Vm[idx] (sat doubling mul high by element) +extern void gadget_sqrdmulh_elem_vec(void);// SQRDMULH Vd, Vn, Vm[idx] (sat rounding doubling mul high by element) +extern void gadget_sqdmull_elem_vec(void); // SQDMULL Vd, Vn, Vm[idx] (sat doubling mul long by element) +extern void gadget_sqdmlal_elem_vec(void); // SQDMLAL Vd, Vn, Vm[idx] (sat doubling mul-accum long by element) +extern void gadget_sqdmlsl_elem_vec(void); // SQDMLSL Vd, Vn, Vm[idx] (sat doubling mul-subtract long by element) +extern void gadget_sabd_vec(void); // SABD Vd, Vn, Vm (signed abs diff) +extern void gadget_uabd_vec(void); // UABD Vd, Vn, Vm (unsigned abs diff) +extern void gadget_cmtst_vec(void); // CMTST Vd, Vn, Vm (compare bitwise test) +extern void gadget_aese(void); // AESE Vd.16B, Vn.16B (AES encrypt) +extern void gadget_aesd(void); // AESD Vd.16B, Vn.16B (AES decrypt) +extern void gadget_aesmc(void); // AESMC Vd.16B, Vn.16B (AES mix columns) +extern void gadget_aesimc(void); // AESIMC Vd.16B, Vn.16B (AES inverse mix columns) +extern void gadget_tbl(void); // TBL Vd, {Vn..Vn+len}, Vm (table lookup) +extern void gadget_tbx(void); // TBX Vd, {Vn..Vn+len}, Vm (table lookup extend) +extern void gadget_ext_vec(void); // EXT Vd, Vn, Vm, #index (extract from pair) +extern void gadget_sha1c(void); // SHA1C Qd, Sn, Vm.4S +extern void gadget_sha1h(void); // SHA1H Sd, Sn +extern void gadget_sha1m(void); // SHA1M Qd, Sn, Vm.4S +extern void gadget_sha1p(void); // SHA1P Qd, Sn, Vm.4S +extern void gadget_sha1su0(void); // SHA1SU0 Vd.4S, Vn.4S, Vm.4S +extern void gadget_sha1su1(void); // SHA1SU1 Vd.4S, Vn.4S +extern void gadget_sha256h(void); // SHA256H Qd, Qn, Vm.4S +extern void gadget_sha256h2(void); // SHA256H2 Qd, Qn, Vm.4S +extern void gadget_sha256su0(void); // SHA256SU0 Vd.4S, Vn.4S +extern void gadget_sha256su1(void); // SHA256SU1 Vd.4S, Vn.4S, Vm.4S +extern void gadget_sha512su0(void); // SHA512SU0 Vd.2D, Vn.2D +extern void gadget_sha512su1(void); // SHA512SU1 Vd.2D, Vn.2D, Vm.2D +extern void gadget_sha512h(void); // SHA512H Qd, Qn, Vm.2D +extern void gadget_sha512h2(void); // SHA512H2 Qd, Qn, Vm.2D +extern void gadget_eor3(void); // EOR3 Vd.16B, Vn.16B, Vm.16B, Va.16B +extern void gadget_sm3partw1(void); // SM3PARTW1 Vd.4S, Vn.4S, Vm.4S +extern void gadget_sm4e(void); // SM4E Vd.4S, Vn.4S +extern void gadget_sve_eor_d(void); // SVE EOR Zd.D, Zn.D, Zm.D (128-bit modeled) +extern void gadget_sve_xar_d(void); // SVE XAR Zd.D, Zd.D, Zm.D, #imm (128-bit modeled) +extern void gadget_pmull(void); // PMULL Vd, Vn, Vm (polynomial multiply long) +extern void gadget_xtn_vec(void); // XTN/XTN2 Vd, Vn (narrow) +extern void gadget_uzp1_vec(void); // UZP1 Vd, Vn, Vm (unzip even elements) +extern void gadget_uzp2_vec(void); // UZP2 Vd, Vn, Vm (unzip odd elements) +extern void gadget_trn1_vec(void); // TRN1 Vd, Vn, Vm (transpose even) +extern void gadget_trn2_vec(void); // TRN2 Vd, Vn, Vm (transpose odd) +extern void gadget_zip1_vec(void); // ZIP1 Vd, Vn, Vm (zip lower halves) +extern void gadget_zip2_vec(void); // ZIP2 Vd, Vn, Vm (zip upper halves) +extern void gadget_rev16_vec(void); // REV16 Vd, Vn (reverse bytes in 16-bit elements) +extern void gadget_rev32_vec(void); // REV32 Vd, Vn (reverse bytes in 32-bit elements) +extern void gadget_rev64_vec(void); // REV64 Vd, Vn (reverse bytes in 64-bit elements) +extern void gadget_rbit_vec(void); // RBIT Vd.xB, Vn.xB (reverse bits in each byte) +extern void gadget_cnt_vec(void); // CNT Vd.xB, Vn.xB (count set bits per byte) +extern void gadget_addv_vec(void); // ADDV Vd, Vn (add across vector lanes) +extern void gadget_saddlv_vec(void); // SADDLV Vd, Vn (signed add long across vector) +extern void gadget_uaddlv_vec(void); // UADDLV Vd, Vn (unsigned add long across vector) +extern void gadget_umaxv_vec(void); // UMAXV Vd, Vn (unsigned max across vector) +extern void gadget_uminv_vec(void); // UMINV Vd, Vn (unsigned min across vector) +extern void gadget_smaxv_vec(void); // SMAXV Vd, Vn (signed max across vector) +extern void gadget_sminv_vec(void); // SMINV Vd, Vn (signed min across vector) +extern void gadget_fmaxv_vec(void); // FMAXV Sd, Vn.4S (FP max across vector) +extern void gadget_fminv_vec(void); // FMINV Sd, Vn.4S (FP min across vector) +extern void gadget_fmaxnmv_vec(void); // FMAXNMV Sd, Vn.4S (FP maxnum across vector) +extern void gadget_fminnmv_vec(void); // FMINNMV Sd, Vn.4S (FP minnum across vector) +extern void gadget_add_vec(void); // ADD Vd, Vn, Vm (vector add) +extern void gadget_sub_vec(void); // SUB Vd, Vn, Vm (vector subtract) +extern void gadget_shadd_vec(void); // SHADD Vd, Vn, Vm (signed halving add) +extern void gadget_uhadd_vec(void); // UHADD Vd, Vn, Vm (unsigned halving add) +extern void gadget_srhadd_vec(void); // SRHADD Vd, Vn, Vm (signed rounding halving add) +extern void gadget_urhadd_vec(void); // URHADD Vd, Vn, Vm (unsigned rounding halving add) +extern void gadget_saddw_vec(void); // SADDW Vd, Vn, Vm (signed add wide) +extern void gadget_uaddw_vec(void); // UADDW Vd, Vn, Vm (unsigned add wide) +extern void gadget_saddl_vec(void); // SADDL Vd, Vn, Vm (signed add long) +extern void gadget_uaddl_vec(void); // UADDL Vd, Vn, Vm (unsigned add long) +extern void gadget_ssubl_vec(void); // SSUBL Vd, Vn, Vm (signed sub long) +extern void gadget_usubl_vec(void); // USUBL Vd, Vn, Vm (unsigned sub long) +extern void gadget_smull_vec(void); // SMULL Vd, Vn, Vm (signed multiply long) +extern void gadget_umull_vec(void); // UMULL Vd, Vn, Vm (unsigned multiply long) +extern void gadget_sabdl_vec(void); // SABDL Vd, Vn, Vm (signed abs diff long) +extern void gadget_uabdl_vec(void); // UABDL Vd, Vn, Vm (unsigned abs diff long) +extern void gadget_addhn_vec(void); // ADDHN Vd, Vn, Vm (add returning high narrow) +extern void gadget_subhn_vec(void); // SUBHN Vd, Vn, Vm (sub returning high narrow) +extern void gadget_raddhn_vec(void); // RADDHN Vd, Vn, Vm (rounding add returning high narrow) +extern void gadget_rsubhn_vec(void); // RSUBHN Vd, Vn, Vm (rounding sub returning high narrow) +extern void gadget_sabal_vec(void); // SABAL Vd, Vn, Vm (signed abs diff accumulate long) +extern void gadget_uabal_vec(void); // UABAL Vd, Vn, Vm (unsigned abs diff accumulate long) +extern void gadget_smlal_vec(void); // SMLAL Vd, Vn, Vm (signed multiply-accumulate long) +extern void gadget_umlal_vec(void); // UMLAL Vd, Vn, Vm (unsigned multiply-accumulate long) +extern void gadget_smlsl_vec(void); // SMLSL Vd, Vn, Vm (signed multiply-subtract long) +extern void gadget_umlsl_vec(void); // UMLSL Vd, Vn, Vm (unsigned multiply-subtract long) +extern void gadget_ssubw_vec(void); // SSUBW Vd, Vn, Vm (signed subtract wide) +extern void gadget_usubw_vec(void); // USUBW Vd, Vn, Vm (unsigned subtract wide) +extern void gadget_sqadd_vec(void); // SQADD Vd, Vn, Vm (signed saturating add) +extern void gadget_uqadd_vec(void); // UQADD Vd, Vn, Vm (unsigned saturating add) +extern void gadget_sqsub_vec(void); // SQSUB Vd, Vn, Vm (signed saturating sub) +extern void gadget_uqsub_vec(void); // UQSUB Vd, Vn, Vm (unsigned saturating sub) +extern void gadget_shsub_vec(void); // SHSUB Vd, Vn, Vm (signed halving sub) +extern void gadget_uhsub_vec(void); // UHSUB Vd, Vn, Vm (unsigned halving sub) +extern void gadget_cmgt_reg_vec(void); // CMGT Vd, Vn, Vm (signed compare greater than) +extern void gadget_cmge_reg_vec(void); // CMGE Vd, Vn, Vm (signed compare greater or equal) +extern void gadget_orn_vec(void); // ORN Vd, Vn, Vm (bitwise OR NOT) +extern void gadget_saba_vec(void); // SABA Vd, Vn, Vm (signed abs diff accumulate) +extern void gadget_uaba_vec(void); // UABA Vd, Vn, Vm (unsigned abs diff accumulate) + +// Vector FP two-register misc conversions +extern void gadget_scvtf_int_vec(void); // SCVTF Vd.xS/Vd.2D, Vn.xS/Vn.2D (signed int to FP) +extern void gadget_ucvtf_int_vec(void); // UCVTF Vd.xS/Vd.2D, Vn.xS/Vn.2D (unsigned int to FP) +extern void gadget_fcvtzs_int_vec(void); // FCVTZS Vd.xS/Vd.2D, Vn.xS/Vn.2D (FP to signed int, toward zero) +extern void gadget_fcvtzu_int_vec(void); // FCVTZU Vd.xS/Vd.2D, Vn.xS/Vn.2D (FP to unsigned int, toward zero) +extern void gadget_fcvtns_int_vec(void); // FCVTNS (nearest, ties to even) +extern void gadget_fcvtnu_int_vec(void); // FCVTNU (nearest, unsigned) +extern void gadget_fcvtms_int_vec(void); // FCVTMS (toward -inf, signed) +extern void gadget_fcvtmu_int_vec(void); // FCVTMU (toward -inf, unsigned) +extern void gadget_fcvtps_int_vec(void); // FCVTPS (toward +inf, signed) +extern void gadget_fcvtpu_int_vec(void); // FCVTPU (toward +inf, unsigned) +extern void gadget_fcvtas_int_vec(void); // FCVTAS (ties away, signed) +extern void gadget_fcvtau_int_vec(void); // FCVTAU (ties away, unsigned) +extern void gadget_frintn_vec_vec(void); // FRINTN (round to nearest, ties to even) +extern void gadget_frinta_vec_vec(void); // FRINTA (round to nearest, ties away) +extern void gadget_frintp_vec_vec(void); // FRINTP (round toward +inf) +extern void gadget_frintm_vec_vec(void); // FRINTM (round toward -inf) +extern void gadget_frintx_vec_vec(void); // FRINTX (round to integral, exact) +extern void gadget_frintz_vec_vec(void); // FRINTZ (round toward zero) +extern void gadget_frinti_vec_vec(void); // FRINTI (round using FPCR rounding mode) +extern void gadget_fcvtn_vec(void); // FCVTN/FCVTN2 (narrow FP conversion) +extern void gadget_fcvtl_vec(void); // FCVTL/FCVTL2 (widen FP conversion) +extern void gadget_fcvtxn_vec(void); // FCVTXN/FCVTXN2 (round-to-odd narrow conversion) +// Vector FP compare-with-zero +extern void gadget_fcmeq_zero_vec(void); // FCMEQ Vd, Vn, #0.0 +extern void gadget_fcmge_zero_vec(void); // FCMGE Vd, Vn, #0.0 +extern void gadget_fcmgt_zero_vec(void); // FCMGT Vd, Vn, #0.0 +extern void gadget_fcmle_zero_vec(void); // FCMLE Vd, Vn, #0.0 +extern void gadget_fcmlt_zero_vec(void); // FCMLT Vd, Vn, #0.0 +// Vector FP unary ops +extern void gadget_fabs_vec_vec(void); // FABS Vd, Vn (vector absolute) +extern void gadget_fneg_vec_vec(void); // FNEG Vd, Vn (vector negate) +extern void gadget_fsqrt_vec_vec(void); // FSQRT Vd, Vn (vector square root) +extern void gadget_frecpe_vec_vec(void); // FRECPE Vd, Vn (vector reciprocal estimate) +extern void gadget_frsqrte_vec_vec(void); // FRSQRTE Vd, Vn (vector rsqrt estimate) +// Integer compare-with-zero +extern void gadget_cmeq_zero_vec(void); // CMEQ Vd, Vn, #0 + +// Floating-point conversions +extern void gadget_ucvtf_scalar(void); // UCVTF Sd, Wn / UCVTF Dd, Xn +extern void gadget_scvtf_scalar(void); // SCVTF Sd, Wn / SCVTF Dd, Xn +extern void gadget_fcvtzu_scalar(void); // FCVTZU Wd, Sn / FCVTZU Xd, Dn +extern void gadget_fcvtzs_scalar(void); // FCVTZS Wd, Sn / FCVTZS Xd, Dn +extern void gadget_fcvtns_scalar(void); // FCVTNS (round to nearest, ties to even) +extern void gadget_fcvtps_scalar(void); // FCVTPS (round toward +inf) +extern void gadget_fcvtms_scalar(void); // FCVTMS (round toward -inf) +extern void gadget_fcvtnu_scalar(void); // FCVTNU (unsigned, round to nearest) +extern void gadget_fcvtpu_scalar(void); // FCVTPU (unsigned, round toward +inf) +extern void gadget_fcvtmu_scalar(void); // FCVTMU (unsigned, round toward -inf) +extern void gadget_fcvtas_scalar(void); // FCVTAS (round to nearest, ties to away) +extern void gadget_fcvtau_scalar(void); // FCVTAU (unsigned, ties to away) +extern void gadget_fcvtzs_simd_scalar(void); // FCVTZS Dd, Dn (SIMD scalar) +extern void gadget_fcvtzu_simd_scalar(void); // FCVTZU Dd, Dn (SIMD scalar) +extern void gadget_ucvtf_simd_scalar(void); // UCVTF Sd, Sn / UCVTF Dd, Dn (SIMD scalar) +extern void gadget_scvtf_simd_scalar(void); // SCVTF Sd, Sn / SCVTF Dd, Dn (SIMD scalar) +extern void gadget_fmov_gpr_to_fp(void); // FMOV Sd, Wn / FMOV Dd, Xn +extern void gadget_fmov_gpr_to_fp_hi(void); // FMOV Vd.D[1], Xn +extern void gadget_fmov_fp_to_gpr(void); // FMOV Wd, Sn / FMOV Xd, Dn +extern void gadget_fmov_fp_to_gpr_hi(void); // FMOV Xd, Vn.D[1] +extern void gadget_fmov_fp_to_fp(void); // FMOV Sd, Sn / FMOV Dd, Dn (scalar reg copy) +extern void gadget_fmov_fp_imm(void); // FMOV Sd/Dd, #imm (FP immediate) +extern void gadget_fcmp_scalar(void); // FCMP/FCMPE Sn, Sm / Dn, Dm +extern void gadget_fcmp_zero_scalar(void); // FCMP/FCMPE Sn, #0.0 / Dn, #0.0 +extern void gadget_fadd_scalar(void); // FADD Sn, Sm, Sd / Dn, Dm, Dd +extern void gadget_fsub_scalar(void); // FSUB Sn, Sm, Sd / Dn, Dm, Dd +extern void gadget_fmul_scalar(void); // FMUL Sn, Sm, Sd / Dn, Dm, Dd +extern void gadget_fdiv_scalar(void); // FDIV Sn, Sm, Sd / Dn, Dm, Dd +extern void gadget_fmax_scalar(void); // FMAX Sn, Sm, Sd / Dn, Dm, Dd +extern void gadget_fmin_scalar(void); // FMIN Sn, Sm, Sd / Dn, Dm, Dd +extern void gadget_fmaxnm_scalar(void); // FMAXNM Sn, Sm, Sd / Dn, Dm, Dd +extern void gadget_fminnm_scalar(void); // FMINNM Sn, Sm, Sd / Dn, Dm, Dd +extern void gadget_fnmul_scalar(void); // FNMUL Sn, Sm, Sd / Dn, Dm, Dd +extern void gadget_fabd_scalar(void); // FABD Sn, Sm, Sd / Dn, Dm, Dd (scalar) +extern void gadget_faddp_scalar(void); // FADDP Sd, Vn.2S / Dd, Vn.2D (scalar pairwise add) +extern void gadget_fmaxp_scalar(void); // FMAXP Sd, Vn.2S / Dd, Vn.2D (scalar pairwise max) +extern void gadget_fminp_scalar(void); // FMINP Sd, Vn.2S / Dd, Vn.2D (scalar pairwise min) +extern void gadget_fmaxnmp_scalar(void); // FMAXNMP Sd, Vn.2S / Dd, Vn.2D (scalar pairwise maxnum) +extern void gadget_fminnmp_scalar(void); // FMINNMP Sd, Vn.2S / Dd, Vn.2D (scalar pairwise minnum) +extern void gadget_addp_scalar(void); // ADDP Dd, Vn.2D (integer scalar pairwise add) +extern void gadget_cmgt_scalar_zero(void); // CMGT Dd, Dn, #0 (scalar compare > 0) +extern void gadget_cmge_scalar_zero(void); // CMGE Dd, Dn, #0 (scalar compare >= 0) +extern void gadget_cmeq_scalar_zero(void); // CMEQ Dd, Dn, #0 (scalar compare == 0) +extern void gadget_cmle_scalar_zero(void); // CMLE Dd, Dn, #0 (scalar compare <= 0) +extern void gadget_cmlt_scalar_zero(void); // CMLT Dd, Dn, #0 (scalar compare < 0) +extern void gadget_abs_scalar(void); // ABS Dd, Dn (scalar absolute value) +extern void gadget_neg_scalar(void); // NEG Dd, Dn (scalar negate) +extern void gadget_fcmgt_scalar_zero(void); // FCMGT Sd/Dd, Sn/Dn, #0.0 (FP scalar compare > 0) +extern void gadget_fcmge_scalar_zero(void); // FCMGE Sd/Dd, Sn/Dn, #0.0 (FP scalar compare >= 0) +extern void gadget_fcmeq_scalar_zero(void); // FCMEQ Sd/Dd, Sn/Dn, #0.0 (FP scalar compare == 0) +extern void gadget_fcmle_scalar_zero(void); // FCMLE Sd/Dd, Sn/Dn, #0.0 (FP scalar compare <= 0) +extern void gadget_fcmlt_scalar_zero(void); // FCMLT Sd/Dd, Sn/Dn, #0.0 (FP scalar compare < 0) +extern void gadget_fp_dp1(void); // FP single-source: FABS/FNEG/FSQRT/FRINT*/FCVT +extern void gadget_fcvt_h_to_s_scalar(void); // FCVT Sd, Hn +extern void gadget_fcvt_h_to_d_scalar(void); // FCVT Dd, Hn +extern void gadget_fccmp_scalar(void); // FCCMP/FCCMPE (conditional FP compare) +extern void gadget_fcsel_scalar(void); // FCSEL (conditional FP select) +extern void gadget_fmadd_scalar(void); // FMADD Fd, Fn, Fm, Fa +extern void gadget_fmsub_scalar(void); // FMSUB Fd, Fn, Fm, Fa +extern void gadget_fnmadd_scalar(void); // FNMADD Fd, Fn, Fm, Fa +extern void gadget_fnmsub_scalar(void); // FNMSUB Fd, Fn, Fm, Fa + +// SIMD load/store gadgets (V bit set) +extern void gadget_str_simd_b(void); // STR Bt, [Xn, #imm] +extern void gadget_str_simd_h(void); // STR Ht, [Xn, #imm] +extern void gadget_str_simd_s(void); // STR St, [Xn, #imm] +extern void gadget_str_simd_d(void); // STR Dt, [Xn, #imm] +extern void gadget_str_simd_q(void); // STR Qt, [Xn, #imm] +extern void gadget_ldr_simd_b(void); // LDR Bt, [Xn, #imm] +extern void gadget_ldr_simd_h(void); // LDR Ht, [Xn, #imm] +extern void gadget_ldr_simd_s(void); // LDR St, [Xn, #imm] +extern void gadget_ldr_simd_d(void); // LDR Dt, [Xn, #imm] +extern void gadget_ldr_simd_q(void); // LDR Qt, [Xn, #imm] +extern void gadget_stp_simd_s(void); // STP St, St2, [Xn, #imm] +extern void gadget_stp_simd_d(void); // STP Dt, Dt2, [Xn, #imm] +extern void gadget_stp_simd_q(void); // STP Qt, Qt2, [Xn, #imm] +extern void gadget_ldp_simd_s(void); // LDP St, St2, [Xn, #imm] +extern void gadget_ldp_simd_d(void); // LDP Dt, Dt2, [Xn, #imm] +extern void gadget_ldp_simd_q(void); // LDP Qt, Qt2, [Xn, #imm] +// LD1/ST1 single structure (single element to/from lane) +extern void gadget_ld1_single_b(void); // LD1 {Vt.B}[lane], [Xn] +extern void gadget_ld1_single_h(void); // LD1 {Vt.H}[lane], [Xn] +extern void gadget_ld1_single_s(void); // LD1 {Vt.S}[lane], [Xn] +extern void gadget_ld1_single_d(void); // LD1 {Vt.D}[lane], [Xn] +extern void gadget_st1_single_b(void); // ST1 {Vt.B}[lane], [Xn] +extern void gadget_st1_single_h(void); // ST1 {Vt.H}[lane], [Xn] +extern void gadget_st1_single_s(void); // ST1 {Vt.S}[lane], [Xn] +extern void gadget_st1_single_d(void); // ST1 {Vt.D}[lane], [Xn] +extern void gadget_addr_add_imm(void); // _addr += imm (for multi-element single structure) + +// Decode ARM64 FP immediate encoding to IEEE bits. +// Encoding uses imm8 with bit6 inverted in the instruction encoding. +// Value is: (-1)^sign * (16+frac) * 2^(exp-7) +static uint64_t arm64_fpimm_to_bits(bool is_double, uint8_t imm8) { + int sign = (imm8 >> 7) & 1; + int exp = (imm8 >> 4) & 0x7; + int frac = imm8 & 0xf; + double value = (double)(16 + frac) / (double)(1 << (7 - exp)); + if (sign) + value = -value; + if (is_double) { + union { double d; uint64_t u; } conv; + conv.d = value; + return conv.u; + } else { + union { float f; uint32_t u; } conv; + conv.f = (float)value; + return (uint64_t)conv.u; + } +} + +// Interleaved SIMD load/store gadgets (LD2/LD3/LD4, ST2/ST3/ST4) +extern void gadget_simd_load_interleaved(void); +extern void gadget_simd_store_interleaved(void); + +// Address manipulation gadgets +extern void gadget_advance_addr(void); // Add immediate to _addr +extern void gadget_update_base_reg(void); // Update base register from Rm + +// Multiply gadgets +extern void gadget_madd(void); +extern void gadget_msub(void); +extern void gadget_smaddl(void); +extern void gadget_smsubl(void); +extern void gadget_umaddl(void); +extern void gadget_umsubl(void); +extern void gadget_umulh(void); +extern void gadget_smulh(void); + +// Data processing (2 source) +extern void gadget_udiv(void); +extern void gadget_sdiv(void); +extern void gadget_lslv(void); +extern void gadget_lsrv(void); +extern void gadget_asrv(void); +extern void gadget_rorv(void); +extern void gadget_crc32b(void); +extern void gadget_crc32h(void); +extern void gadget_crc32w(void); +extern void gadget_crc32x(void); +extern void gadget_crc32cb(void); +extern void gadget_crc32ch(void); +extern void gadget_crc32cw(void); +extern void gadget_crc32cx(void); +extern void gadget_lslv_64(void); +extern void gadget_lsrv_64(void); +extern void gadget_asrv_64(void); + +// Add/subtract extended register +extern void gadget_add_ext(void); +extern void gadget_sub_ext(void); +extern void gadget_adds_ext(void); +extern void gadget_subs_ext(void); + +// System register gadgets +extern void gadget_msr_tpidr(void); +extern void gadget_mrs_tpidr(void); +extern void gadget_mrs_sysreg(void); +extern void gadget_mrs_nzcv(void); +extern void gadget_msr_nzcv(void); +extern void gadget_msr_fpcr(void); +extern void gadget_msr_fpsr(void); +extern void gadget_msr_daif(void); +extern void gadget_dc_zva(void); + +// Byte reverse and bit manipulation gadgets +extern void gadget_rev(void); +extern void gadget_rev16(void); +extern void gadget_rev32(void); +extern void gadget_clz(void); +extern void gadget_cls(void); +extern void gadget_rbit(void); + +// System register IDs for gadget_mrs_sysreg +#define SYSREG_ID_TPIDR_EL0 0 +#define SYSREG_ID_CTR_EL0 1 +#define SYSREG_ID_DCZID_EL0 2 +#define SYSREG_ID_FPCR 3 +#define SYSREG_ID_FPSR 4 +#define SYSREG_ID_RNDR 5 // Random Number (ARMv8.5-RNG) +#define SYSREG_ID_RNDRRS 6 // Reseeded Random Number (ARMv8.5-RNG) +#define SYSREG_ID_ID_AA64PFR0_EL1 7 +#define SYSREG_ID_ID_AA64PFR1_EL1 8 +#define SYSREG_ID_ID_AA64ISAR0_EL1 9 +#define SYSREG_ID_ID_AA64ISAR1_EL1 10 +#define SYSREG_ID_ID_AA64ZFR0_EL1 11 +#define SYSREG_ID_CNTVCT_EL0 12 // Virtual counter timer +#define SYSREG_ID_CNTFRQ_EL0 13 // Counter frequency +#define SYSREG_ID_MIDR_EL1 14 // Main ID Register +#define SYSREG_ID_ZERO 15 // Known-readable feature/debug ID register with no advertised features + +// Memory gadgets +extern void gadget_load64(void); +extern void gadget_load32(void); +extern void gadget_load16(void); +extern void gadget_load8(void); +extern void gadget_load32_sx(void); +extern void gadget_load16_sx32(void); +extern void gadget_load16_sx64(void); +extern void gadget_load8_sx32(void); +extern void gadget_load8_sx64(void); +extern void gadget_store64(void); +extern void gadget_store32(void); +extern void gadget_store16(void); +extern void gadget_store8(void); +extern void gadget_calc_addr_imm(void); +extern void gadget_calc_addr_reg(void); +extern void gadget_calc_addr_base(void); +extern void gadget_calc_addr_pc_rel(void); +// Fused load/store gadgets (calc_addr_imm + load/store + reg transfer in one dispatch) +extern void gadget_load64_imm(void); +extern void gadget_load32_imm(void); +extern void gadget_load16_imm(void); +extern void gadget_load8_imm(void); +extern void gadget_load32_sx_imm(void); +extern void gadget_load64_imm_fast(void); +extern void gadget_load32_imm_fast(void); +extern void gadget_load16_imm_fast(void); +extern void gadget_load8_imm_fast(void); +extern void gadget_store64_imm(void); +extern void gadget_store32_imm(void); +extern void gadget_store64_imm_fast(void); +extern void gadget_store32_imm_fast(void); +extern void gadget_store16_imm_fast(void); +extern void gadget_store8_imm_fast(void); +extern void gadget_store16_imm(void); +extern void gadget_store8_imm(void); +// Fused register-offset load/store gadgets (option=3/UXTX only) +extern void gadget_load64_reg(void); +extern void gadget_load32_reg(void); +extern void gadget_load16_reg(void); +extern void gadget_load8_reg(void); +extern void gadget_load32_sx_reg(void); +extern void gadget_store64_reg(void); +extern void gadget_store32_reg(void); +extern void gadget_store16_reg(void); +extern void gadget_store8_reg(void); +// LDXR/STXR exclusive gadgets +extern void gadget_ldxr(void); // Load exclusive + save to monitor +extern void gadget_stxr(void); // Store exclusive via atomic CAS +extern void gadget_update_base(void); +extern void gadget_writeback_addr(void); +// Atomic memory operation helpers +extern void gadget_atomic_rmw(void); +extern void gadget_atomic_cas(void); +extern void gadget_atomic_casp(void); + +// Memory barrier/system-synchronization gadgets +extern void gadget_dmb(void); +extern void gadget_dsb(void); +extern void gadget_isb(void); +extern void gadget_clrex(void); +extern void gadget_ic_ivau(void); // invalidate translated code for a page (SMC) + +// Load/store pair gadgets +extern void gadget_ldp64(void); +extern void gadget_ldp32(void); +extern void gadget_ldpsw(void); +extern void gadget_ldxp_c(void); +extern void gadget_stxp_c(void); +extern void gadget_stp64(void); +extern void gadget_stp32(void); +// Fused load/store pair with signed-offset addressing +extern void gadget_ldp64_imm(void); +extern void gadget_ldp32_imm(void); +extern void gadget_ldpsw_imm(void); +extern void gadget_stp64_imm(void); +extern void gadget_stp32_imm(void); +extern void gadget_ldp64_imm_fast(void); +extern void gadget_stp64_imm_fast(void); +extern void gadget_ldp32_imm_fast(void); +extern void gadget_ldpsw_imm_fast(void); +extern void gadget_stp32_imm_fast(void); +// SP-relative fused load/store gadgets (rn==31, rd/rt!=31) +extern void gadget_load64_sp_imm(void); +extern void gadget_load32_sp_imm(void); +extern void gadget_store64_sp_imm(void); +extern void gadget_store32_sp_imm(void); +// Fused ADRP+ADD gadget +extern void gadget_fused_adrp_add(void); +// Fused CMP_reg + B.cond gadgets (64-bit, rd=31) +extern void gadget_fused_cmp_reg_bcond_eq(void); +extern void gadget_fused_cmp_reg_bcond_ne(void); +extern void gadget_fused_cmp_reg_bcond_cs(void); +extern void gadget_fused_cmp_reg_bcond_cc(void); +extern void gadget_fused_cmp_reg_bcond_mi(void); +extern void gadget_fused_cmp_reg_bcond_pl(void); +extern void gadget_fused_cmp_reg_bcond_vs(void); +extern void gadget_fused_cmp_reg_bcond_vc(void); +extern void gadget_fused_cmp_reg_bcond_hi(void); +extern void gadget_fused_cmp_reg_bcond_ls(void); +extern void gadget_fused_cmp_reg_bcond_ge(void); +extern void gadget_fused_cmp_reg_bcond_lt(void); +extern void gadget_fused_cmp_reg_bcond_gt(void); +extern void gadget_fused_cmp_reg_bcond_le(void); +// Fused SUBS_reg + B.cond gadgets (64-bit, rd!=31) +extern void gadget_fused_subs_reg_bcond_eq(void); +extern void gadget_fused_subs_reg_bcond_ne(void); +extern void gadget_fused_subs_reg_bcond_cs(void); +extern void gadget_fused_subs_reg_bcond_cc(void); +extern void gadget_fused_subs_reg_bcond_mi(void); +extern void gadget_fused_subs_reg_bcond_pl(void); +extern void gadget_fused_subs_reg_bcond_vs(void); +extern void gadget_fused_subs_reg_bcond_vc(void); +extern void gadget_fused_subs_reg_bcond_hi(void); +extern void gadget_fused_subs_reg_bcond_ls(void); +extern void gadget_fused_subs_reg_bcond_ge(void); +extern void gadget_fused_subs_reg_bcond_lt(void); +extern void gadget_fused_subs_reg_bcond_gt(void); +extern void gadget_fused_subs_reg_bcond_le(void); + +static void gen(struct gen_state *state, unsigned long thing) { + assert(state->size <= state->capacity); + if (state->size >= state->capacity) { + state->capacity *= 2; + struct fiber_block *new_block = realloc(state->block, + sizeof(*new_block) + state->capacity * sizeof(unsigned long)); + if (new_block == NULL) { + abort(); + } + state->block = new_block; + } + state->block->code[state->size++] = thing; +} + +static bool gen_record_internal_continue_patch(struct gen_state *state, unsigned patch_ip, unsigned target_ip) { + if (state->internal_continue_count >= GEN_INTERNAL_CONTINUE_MAX) + return false; + unsigned i = state->internal_continue_count++; + state->internal_continue_patch_ip[i] = patch_ip; + state->internal_continue_target_ip[i] = target_ip; + return true; +} + +static bool gen_emit_internal_continue_record(struct gen_state *state, addr_t guest_pc) { + if (state->internal_continue_count >= GEN_INTERNAL_CONTINUE_MAX) + return false; + gen(state, (unsigned long) gadget_internal_continue); + gen(state, guest_pc); + unsigned patch_ip = state->size; + gen(state, 0); + return gen_record_internal_continue_patch(state, patch_ip, state->size); +} + +// Generate interrupt and end the block +static void gen_interrupt(struct gen_state *state, int interrupt_type) { + // Set guest PC to the faulting instruction so signal handlers see the correct address + gen(state, (unsigned long) gadget_set_pc); + gen(state, state->orig_ip); + gen(state, (unsigned long) gadget_interrupt); + gen(state, interrupt_type); +} + +void gen_start(addr_t addr, struct gen_state *state) { + state->capacity = FIBER_BLOCK_INITIAL_CAPACITY; + state->size = 0; + state->ip = addr; + state->last_insn = 0; + state->b_follow_depth = 0; + for (int i = 0; i <= 1; i++) { + state->jump_ip[i] = 0; + } + state->block_patch_ip = 0; + state->internal_continue_count = 0; + state->internal_continue_used = 0; + state->internal_continue_segment_start = 0; + state->internal_continue_segment_budget = 0; + for (int i = 0; i < GEN_INTERNAL_CONTINUE_MAX; i++) { + state->internal_continue_patch_ip[i] = 0; + state->internal_continue_target_ip[i] = 0; + } + + struct fiber_block *block = malloc(sizeof(struct fiber_block) + state->capacity * sizeof(unsigned long)); + state->block = block; + block->addr = addr; +} + +void gen_end(struct gen_state *state) { + struct fiber_block *block = state->block; + for (int i = 0; i <= 1; i++) { + if (state->jump_ip[i] != 0) { + block->jump_ip[i] = &block->code[state->jump_ip[i]]; + block->old_jump_ip[i] = *block->jump_ip[i]; + block->jump_ip_is_fake[i] = true; + } else { + block->jump_ip[i] = NULL; + block->jump_ip_is_fake[i] = false; + } + + list_init(&block->jumps_from[i]); + list_init(&block->jumps_from_links[i]); + } + if (state->block_patch_ip != 0) { + block->code[state->block_patch_ip] = (unsigned long) block; + } + for (unsigned i = 0; i < state->internal_continue_count; i++) { + block->code[state->internal_continue_patch_ip[i]] = + (unsigned long) &block->code[state->internal_continue_target_ip[i]]; + } + if (block->addr != state->ip) + block->end_addr = state->ip - 1; + else + block->end_addr = block->addr; + list_init(&block->chain); + block->is_jetsam = false; + for (int i = 0; i <= 1; i++) { + list_init(&block->page[i]); + } +} + +void gen_exit(struct gen_state *state) { + gen(state, (unsigned long) gadget_exit); + gen(state, state->ip); +} + +// Forward declarations +static int gen_dp_imm(struct gen_state *state, uint32_t insn); +static int gen_branch(struct gen_state *state, uint32_t insn); +static int gen_ldst(struct gen_state *state, uint32_t insn); +static int gen_dp_reg(struct gen_state *state, uint32_t insn); +static int gen_simd_fp(struct gen_state *state, uint32_t insn); + +extern volatile bool g_trace_highbits; +extern bool asbestos_should_trace_guest_pc(addr_t pc); + +static void gen_trace_pc(struct gen_state *state) { + gen(state, (unsigned long)gadget_trace); + gen(state, (uint64_t)state->orig_ip); +} + +static void gen_trace_highbits(struct gen_state *state) { + gen(state, (unsigned long)gadget_check_highbits); + gen(state, (uint64_t)state->orig_ip); // guest PC for this instruction +} + +int gen_step(struct gen_state *state, struct tlb *tlb) { + state->orig_ip = state->ip; + state->orig_ip_extra = 0; + state->tlb = tlb; + + uint32_t insn; + if (!arm64_read_insn(&state->ip, tlb, &insn)) { + gen_interrupt(state, INT_GPF); + return 0; + } + state->last_insn = insn; + + // Handle a small subset of SVE/SVE2 instructions (modeled as 128-bit vectors). + // Some PyPI musllinux aarch64 wheels contain unguarded SVE CNT* probes even + // though the guest does not advertise SVE. Model a conservative 128-bit VL + // so those probes can continue through baseline code paths. + // SVE CNTB/CNTH/CNTW/CNTD Xdn, pattern, MUL #imm + if ((insn & 0xff30e000) == 0x0420e000) { + uint32_t rd = insn & 0x1f; + uint32_t size = (insn >> 22) & 0x3; // 0=B, 1=H, 2=W, 3=D + uint32_t mul = ((insn >> 16) & 0xf) + 1; + uint32_t count = (16u >> size) * mul; + if (rd != 31) { + gen(state, (unsigned long) gadget_movz); + gen(state, rd | ((uint64_t)count << 16) | (1ULL << 32)); + } + return 1; + } + // SVE EOR Zd.D, Zn.D, Zm.D + if ((insn & 0xffe0fc00) == 0x04a03000) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rm = (insn >> 16) & 0x1f; + gen(state, (unsigned long) gadget_sve_eor_d); + gen(state, rd | (rn << 8) | (rm << 16)); + return 1; + } + // SVE XAR Zd.D, Zd.D, Zm.D, #imm + if ((insn & 0xffe0fc00) == 0x04e03400 || (insn & 0xffe0fc00) == 0x04a03400) { + uint32_t rd = insn & 0x1f; + uint32_t zm = (insn >> 5) & 0x1f; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t imm_low = (32 - rm) & 0x1f; + if (imm_low == 0) { + imm_low = 32; + } + uint32_t imm = imm_low + (((insn >> 22) & 1) ? 0 : 32); + gen(state, (unsigned long) gadget_sve_xar_d); + gen(state, rd | (zm << 8) | (imm << 16)); + return 1; + } + + enum arm64_insn_type type = arm64_classify_insn(insn); + + int result; + switch (type) { + case INSN_DP_IMM: + result = gen_dp_imm(state, insn); break; + case INSN_BRANCH: + case INSN_EXCEPTION: + case INSN_SYSTEM: + result = gen_branch(state, insn); break; + case INSN_LD_ST: + result = gen_ldst(state, insn); break; + case INSN_DP_REG: + result = gen_dp_reg(state, insn); break; + case INSN_SIMD_FP: + result = gen_simd_fp(state, insn); break; + default: + gen_interrupt(state, INT_UNDEFINED); + result = 0; break; + } + + if (result == 1 && asbestos_should_trace_guest_pc(state->orig_ip)) + gen_trace_pc(state); + if (result == 1 && g_trace_highbits) + gen_trace_highbits(state); + + return result; +} + +/* + * Helper: Decode bitmask immediate + * ARM64 uses a complex encoding for bitmask immediates. + * Returns false if the encoding is invalid. + */ +static bool decode_bitmask_imm(uint32_t n, uint32_t imms, uint32_t immr, bool is64, uint64_t *result) { + uint32_t len = 0; + + // Find the highest bit set in (n:~imms) + uint32_t combined = (n << 6) | (~imms & 0x3f); + for (int i = 6; i >= 0; i--) { + if (combined & (1 << i)) { + len = i; + break; + } + } + + if (len < 1) return false; + + uint32_t size = 1 << len; + uint32_t s = imms & (size - 1); + uint32_t r = immr & (size - 1); + + if (s == size - 1) return false; + + // Create the base pattern + uint64_t pattern = (1ULL << (s + 1)) - 1; + + // Rotate right (handle r=0 case to avoid shifting by size bits) + if (r > 0) { + pattern = (pattern >> r) | (pattern << (size - r)); + pattern &= (size < 64) ? ((1ULL << size) - 1) : ~0ULL; + } + + // Replicate to 64 bits + *result = 0; + for (uint32_t i = 0; i < 64; i += size) { + *result |= pattern << i; + } + + if (!is64) { + *result &= 0xFFFFFFFF; + } + + return true; +} + +// Expand Advanced SIMD modified immediate (integer) into a 64-bit pattern. +// Returns false if cmode is not supported. +static bool simd_modimm_pattern(uint32_t cmode, uint8_t imm8, uint64_t *pattern) { + uint64_t elem; + switch (cmode) { + // 32-bit elements, shift 0/8/16/24 + case 0x0: case 0x2: case 0x4: case 0x6: { + uint32_t shift = (cmode >> 1) * 8; + elem = (uint64_t)imm8 << shift; + *pattern = elem | (elem << 32); + return true; + } + // 16-bit elements, shift 0/8 + case 0x8: case 0xa: { + uint32_t shift = ((cmode >> 1) & 1) * 8; + elem = (uint64_t)imm8 << shift; + *pattern = elem | (elem << 16) | (elem << 32) | (elem << 48); + return true; + } + // 8-bit elements + case 0xe: + elem = imm8; + *pattern = elem * 0x0101010101010101ULL; + return true; + default: + return false; + } +} + +/* + * Peek at the next instruction without advancing state->ip. + * Returns true if successful, false if read fails. + */ +static bool gen_peek_next_insn(struct gen_state *state, uint32_t *next_insn) { + return tlb_read(state->tlb, state->ip, next_insn, sizeof(*next_insn)); +} + +/* + * Fused CMP/SUBS + B.cond gadget tables (initialized lazily) + */ +static void *fused_cmp_bcond_gadgets[14]; +static void *fused_subs_bcond_gadgets[14]; +static void *fused_cmp32_bcond_gadgets[14]; +static void *fused_subs32_bcond_gadgets[14]; +static void *fused_cmp_reg_bcond_gadgets[14]; +static void *fused_subs_reg_bcond_gadgets[14]; +static bool fused_bcond_tables_init = false; + +static void init_fused_bcond_tables(void) { + if (fused_bcond_tables_init) return; + fused_cmp_bcond_gadgets[0] = gadget_fused_cmp_bcond_eq; + fused_cmp_bcond_gadgets[1] = gadget_fused_cmp_bcond_ne; + fused_cmp_bcond_gadgets[2] = gadget_fused_cmp_bcond_cs; + fused_cmp_bcond_gadgets[3] = gadget_fused_cmp_bcond_cc; + fused_cmp_bcond_gadgets[4] = gadget_fused_cmp_bcond_mi; + fused_cmp_bcond_gadgets[5] = gadget_fused_cmp_bcond_pl; + fused_cmp_bcond_gadgets[6] = gadget_fused_cmp_bcond_vs; + fused_cmp_bcond_gadgets[7] = gadget_fused_cmp_bcond_vc; + fused_cmp_bcond_gadgets[8] = gadget_fused_cmp_bcond_hi; + fused_cmp_bcond_gadgets[9] = gadget_fused_cmp_bcond_ls; + fused_cmp_bcond_gadgets[10] = gadget_fused_cmp_bcond_ge; + fused_cmp_bcond_gadgets[11] = gadget_fused_cmp_bcond_lt; + fused_cmp_bcond_gadgets[12] = gadget_fused_cmp_bcond_gt; + fused_cmp_bcond_gadgets[13] = gadget_fused_cmp_bcond_le; + fused_subs_bcond_gadgets[0] = gadget_fused_subs_bcond_eq; + fused_subs_bcond_gadgets[1] = gadget_fused_subs_bcond_ne; + fused_subs_bcond_gadgets[2] = gadget_fused_subs_bcond_cs; + fused_subs_bcond_gadgets[3] = gadget_fused_subs_bcond_cc; + fused_subs_bcond_gadgets[4] = gadget_fused_subs_bcond_mi; + fused_subs_bcond_gadgets[5] = gadget_fused_subs_bcond_pl; + fused_subs_bcond_gadgets[6] = gadget_fused_subs_bcond_vs; + fused_subs_bcond_gadgets[7] = gadget_fused_subs_bcond_vc; + fused_subs_bcond_gadgets[8] = gadget_fused_subs_bcond_hi; + fused_subs_bcond_gadgets[9] = gadget_fused_subs_bcond_ls; + fused_subs_bcond_gadgets[10] = gadget_fused_subs_bcond_ge; + fused_subs_bcond_gadgets[11] = gadget_fused_subs_bcond_lt; + fused_subs_bcond_gadgets[12] = gadget_fused_subs_bcond_gt; + fused_subs_bcond_gadgets[13] = gadget_fused_subs_bcond_le; + // 32-bit variants + fused_cmp32_bcond_gadgets[0] = gadget_fused_cmp32_bcond_eq; + fused_cmp32_bcond_gadgets[1] = gadget_fused_cmp32_bcond_ne; + fused_cmp32_bcond_gadgets[2] = gadget_fused_cmp32_bcond_cs; + fused_cmp32_bcond_gadgets[3] = gadget_fused_cmp32_bcond_cc; + fused_cmp32_bcond_gadgets[4] = gadget_fused_cmp32_bcond_mi; + fused_cmp32_bcond_gadgets[5] = gadget_fused_cmp32_bcond_pl; + fused_cmp32_bcond_gadgets[6] = gadget_fused_cmp32_bcond_vs; + fused_cmp32_bcond_gadgets[7] = gadget_fused_cmp32_bcond_vc; + fused_cmp32_bcond_gadgets[8] = gadget_fused_cmp32_bcond_hi; + fused_cmp32_bcond_gadgets[9] = gadget_fused_cmp32_bcond_ls; + fused_cmp32_bcond_gadgets[10] = gadget_fused_cmp32_bcond_ge; + fused_cmp32_bcond_gadgets[11] = gadget_fused_cmp32_bcond_lt; + fused_cmp32_bcond_gadgets[12] = gadget_fused_cmp32_bcond_gt; + fused_cmp32_bcond_gadgets[13] = gadget_fused_cmp32_bcond_le; + fused_subs32_bcond_gadgets[0] = gadget_fused_subs32_bcond_eq; + fused_subs32_bcond_gadgets[1] = gadget_fused_subs32_bcond_ne; + fused_subs32_bcond_gadgets[2] = gadget_fused_subs32_bcond_cs; + fused_subs32_bcond_gadgets[3] = gadget_fused_subs32_bcond_cc; + fused_subs32_bcond_gadgets[4] = gadget_fused_subs32_bcond_mi; + fused_subs32_bcond_gadgets[5] = gadget_fused_subs32_bcond_pl; + fused_subs32_bcond_gadgets[6] = gadget_fused_subs32_bcond_vs; + fused_subs32_bcond_gadgets[7] = gadget_fused_subs32_bcond_vc; + fused_subs32_bcond_gadgets[8] = gadget_fused_subs32_bcond_hi; + fused_subs32_bcond_gadgets[9] = gadget_fused_subs32_bcond_ls; + fused_subs32_bcond_gadgets[10] = gadget_fused_subs32_bcond_ge; + fused_subs32_bcond_gadgets[11] = gadget_fused_subs32_bcond_lt; + fused_subs32_bcond_gadgets[12] = gadget_fused_subs32_bcond_gt; + fused_subs32_bcond_gadgets[13] = gadget_fused_subs32_bcond_le; + // 64-bit register CMP/SUBS + B.cond + fused_cmp_reg_bcond_gadgets[0] = gadget_fused_cmp_reg_bcond_eq; + fused_cmp_reg_bcond_gadgets[1] = gadget_fused_cmp_reg_bcond_ne; + fused_cmp_reg_bcond_gadgets[2] = gadget_fused_cmp_reg_bcond_cs; + fused_cmp_reg_bcond_gadgets[3] = gadget_fused_cmp_reg_bcond_cc; + fused_cmp_reg_bcond_gadgets[4] = gadget_fused_cmp_reg_bcond_mi; + fused_cmp_reg_bcond_gadgets[5] = gadget_fused_cmp_reg_bcond_pl; + fused_cmp_reg_bcond_gadgets[6] = gadget_fused_cmp_reg_bcond_vs; + fused_cmp_reg_bcond_gadgets[7] = gadget_fused_cmp_reg_bcond_vc; + fused_cmp_reg_bcond_gadgets[8] = gadget_fused_cmp_reg_bcond_hi; + fused_cmp_reg_bcond_gadgets[9] = gadget_fused_cmp_reg_bcond_ls; + fused_cmp_reg_bcond_gadgets[10] = gadget_fused_cmp_reg_bcond_ge; + fused_cmp_reg_bcond_gadgets[11] = gadget_fused_cmp_reg_bcond_lt; + fused_cmp_reg_bcond_gadgets[12] = gadget_fused_cmp_reg_bcond_gt; + fused_cmp_reg_bcond_gadgets[13] = gadget_fused_cmp_reg_bcond_le; + fused_subs_reg_bcond_gadgets[0] = gadget_fused_subs_reg_bcond_eq; + fused_subs_reg_bcond_gadgets[1] = gadget_fused_subs_reg_bcond_ne; + fused_subs_reg_bcond_gadgets[2] = gadget_fused_subs_reg_bcond_cs; + fused_subs_reg_bcond_gadgets[3] = gadget_fused_subs_reg_bcond_cc; + fused_subs_reg_bcond_gadgets[4] = gadget_fused_subs_reg_bcond_mi; + fused_subs_reg_bcond_gadgets[5] = gadget_fused_subs_reg_bcond_pl; + fused_subs_reg_bcond_gadgets[6] = gadget_fused_subs_reg_bcond_vs; + fused_subs_reg_bcond_gadgets[7] = gadget_fused_subs_reg_bcond_vc; + fused_subs_reg_bcond_gadgets[8] = gadget_fused_subs_reg_bcond_hi; + fused_subs_reg_bcond_gadgets[9] = gadget_fused_subs_reg_bcond_ls; + fused_subs_reg_bcond_gadgets[10] = gadget_fused_subs_reg_bcond_ge; + fused_subs_reg_bcond_gadgets[11] = gadget_fused_subs_reg_bcond_lt; + fused_subs_reg_bcond_gadgets[12] = gadget_fused_subs_reg_bcond_gt; + fused_subs_reg_bcond_gadgets[13] = gadget_fused_subs_reg_bcond_le; + fused_bcond_tables_init = true; +} + +/* + * Try to fuse SUBS/CMP imm with a following B.cond. + * Returns 0 (block ended) if fused, -1 if not fuseable. + * Handles both 32-bit (sf=0) and 64-bit (sf=1), sh=0, rn!=31 + */ +static int try_fuse_subs_bcond(struct gen_state *state, uint32_t sf, uint32_t rd, uint32_t rn, uint32_t imm12) { + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + // Check if next instruction is B.cond (encoding: 0101 0100 xxxx xxxx xxxx xxxx xxx0 xxxx) + if ((next_insn & 0xff000010) != 0x54000000) + return -1; + uint32_t cond = next_insn & 0xf; + if (cond >= 14) // AL/NV — not worth fusing + return -1; + + init_fused_bcond_tables(); + + // Consume the B.cond instruction + state->ip += 4; + + int64_t offset = arm64_branch_imm19(next_insn); + addr_t target = (state->ip - 4) + offset; + unsigned long fake_target = (unsigned long)target | (1UL << 63); + unsigned long fake_fallthrough = (unsigned long)state->ip | (1UL << 63); + + if (rd == 31) { + // CMP: no result register, only flags + ARM64_FUSION_STAT_INC(arm64_fusion_cmp_bcond_count); + gen(state, (unsigned long)(sf ? fused_cmp_bcond_gadgets[cond] : fused_cmp32_bcond_gadgets[cond])); + gen(state, rn | ((uint64_t)imm12 << 8)); + } else { + // SUBS: result register + flags + ARM64_FUSION_STAT_INC(arm64_fusion_subs_bcond_count); + gen(state, (unsigned long)(sf ? fused_subs_bcond_gadgets[cond] : fused_subs32_bcond_gadgets[cond])); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16)); + } + gen(state, fake_target); + gen(state, fake_fallthrough); + state->jump_ip[0] = state->size - 2; // target + state->jump_ip[1] = state->size - 1; // fallthrough + return 0; // block ended (branch) +} + +/* + * Try to fuse SUBS/CMP reg (64-bit, no shift) with a following B.cond. + * Returns 0 (block ended) if fused, -1 if not fuseable. + * Only for sf=1, imm6=0, rn!=31, rm!=31 + */ +static int try_fuse_subs_reg_bcond(struct gen_state *state, uint32_t rd, uint32_t rn, uint32_t rm) { + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + if ((next_insn & 0xff000010) != 0x54000000) + return -1; + uint32_t cond = next_insn & 0xf; + if (cond >= 14) + return -1; + + init_fused_bcond_tables(); + + state->ip += 4; + + int64_t offset = arm64_branch_imm19(next_insn); + addr_t target = (state->ip - 4) + offset; + unsigned long fake_target = (unsigned long)target | (1UL << 63); + unsigned long fake_fallthrough = (unsigned long)state->ip | (1UL << 63); + + if (rd == 31) { + // CMP reg: no result, only flags + ARM64_FUSION_STAT_INC(arm64_fusion_cmp_bcond_count); + gen(state, (unsigned long)fused_cmp_reg_bcond_gadgets[cond]); + gen(state, rn | (rm << 8)); + } else { + // SUBS reg: result + flags + ARM64_FUSION_STAT_INC(arm64_fusion_subs_bcond_count); + gen(state, (unsigned long)fused_subs_reg_bcond_gadgets[cond]); + gen(state, rd | (rn << 8) | (rm << 16)); + } + gen(state, fake_target); + gen(state, fake_fallthrough); + state->jump_ip[0] = state->size - 2; + state->jump_ip[1] = state->size - 1; + return 0; +} + +/* + * Try to fuse ADD/SUB immediate with a following CBZ/CBNZ of the result. + * This is a pure register/control-flow peephole: it writes the ADD/SUB result, + * tests that same architectural register, and ends the block at the branch. + */ +static int try_fuse_addsub_cbz(struct gen_state *state, uint32_t sf, uint32_t op, + uint32_t rd, uint32_t rn, uint32_t imm12) { + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + if ((next_insn & 0x7e000000) != 0x34000000) + return -1; + + bool is_cbnz = (next_insn >> 24) & 1; + uint32_t test_sf = (next_insn >> 31) & 1; + uint32_t rt = next_insn & 0x1f; + if (rt != rd || rt == 31) + return -1; + + state->ip += 4; + + int64_t offset = arm64_branch_imm19(next_insn); + addr_t target = (state->ip - 4) + offset; + unsigned long fake_target = (unsigned long)target | (1UL << 63); + unsigned long fake_fallthrough = (unsigned long)state->ip | (1UL << 63); + + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_cbz_count); + gen(state, (unsigned long)(is_cbnz ? gadget_fused_addsub_cbnz : gadget_fused_addsub_cbz)); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16) | + ((uint64_t)op << 28) | ((uint64_t)sf << 29) | ((uint64_t)test_sf << 30)); + gen(state, fake_target); + gen(state, fake_fallthrough); + state->jump_ip[0] = state->size - 2; + state->jump_ip[1] = state->size - 1; + return 0; +} + +static bool arm64_decode_int_unsigned_imm_ldst(uint32_t insn, bool *is_load, + bool *sign_extend, uint32_t *rn, + uint32_t *rt, uint32_t *size) { + if ((insn & 0x3b000000) != 0x39000000) + return false; + uint32_t V = (insn >> 26) & 1; + if (V) + return false; + uint32_t opc = (insn >> 22) & 0x3; + uint32_t decoded_size = (insn >> 30) & 0x3; + if (decoded_size == 3 && opc == 2) // PRFM + return false; + *is_load = (opc & 1) == 1 || (opc & 2) == 2; + *sign_extend = (opc & 2) != 0; + *rn = (insn >> 5) & 0x1f; + *rt = insn & 0x1f; + *size = decoded_size; + return true; +} + +static void count_addsub_ldst_candidates(struct gen_state *state, uint32_t rd) { + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return; + + bool is_load, sign_extend; + uint32_t mem_rn, mem_rt, mem_size; + if (!arm64_decode_int_unsigned_imm_ldst(next_insn, &is_load, &sign_extend, &mem_rn, &mem_rt, &mem_size)) + return; + if (mem_rn != rd || mem_rt == 31) + return; + + if (is_load) + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_ldr_candidate_count); + else + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_str_candidate_count); +} + +static int try_fuse_addsub_ldr64(struct gen_state *state, uint32_t op, uint32_t rd, + uint32_t rn, uint32_t imm12) { + if (PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + + bool is_load, sign_extend; + uint32_t mem_rn, mem_rt, mem_size; + if (!arm64_decode_int_unsigned_imm_ldst(next_insn, &is_load, &sign_extend, &mem_rn, &mem_rt, &mem_size)) + return -1; + if (!is_load || sign_extend || mem_size != 3 || mem_rn != rd || mem_rt == 31) + return -1; + + uint32_t ldr_imm12 = (next_insn >> 10) & 0xfff; + addr_t ldr_pc = state->ip; + state->ip += 4; + + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_ldr64_count); + gen(state, (unsigned long)gadget_fused_addsub_ldr64_imm); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16) | + ((uint64_t)op << 28) | ((uint64_t)mem_rt << 32) | + ((uint64_t)ldr_imm12 << 40)); + gen(state, (unsigned long)ldr_pc); + return 1; +} + +static int try_fuse_addsub_ldr32(struct gen_state *state, uint32_t op, uint32_t rd, + uint32_t rn, uint32_t imm12) { + if (PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + + bool is_load, sign_extend; + uint32_t mem_rn, mem_rt, mem_size; + if (!arm64_decode_int_unsigned_imm_ldst(next_insn, &is_load, &sign_extend, &mem_rn, &mem_rt, &mem_size)) + return -1; + if (!is_load || sign_extend || mem_size != 2 || mem_rn != rd || mem_rt == 31) + return -1; + + uint32_t ldr_imm12 = (next_insn >> 10) & 0xfff; + addr_t ldr_pc = state->ip; + state->ip += 4; + + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_ldr32_count); + gen(state, (unsigned long)gadget_fused_addsub_ldr32_imm); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16) | + ((uint64_t)op << 28) | ((uint64_t)mem_rt << 32) | + ((uint64_t)ldr_imm12 << 40)); + gen(state, (unsigned long)ldr_pc); + return 1; +} + +static int try_fuse_addsub_ldr16(struct gen_state *state, uint32_t op, uint32_t rd, + uint32_t rn, uint32_t imm12) { + if (PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + + bool is_load, sign_extend; + uint32_t mem_rn, mem_rt, mem_size; + if (!arm64_decode_int_unsigned_imm_ldst(next_insn, &is_load, &sign_extend, &mem_rn, &mem_rt, &mem_size)) + return -1; + if (!is_load || sign_extend || mem_size != 1 || mem_rn != rd || mem_rt == 31) + return -1; + + uint32_t ldr_imm12 = (next_insn >> 10) & 0xfff; + addr_t ldr_pc = state->ip; + state->ip += 4; + + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_ldr16_count); + gen(state, (unsigned long)gadget_fused_addsub_ldr16_imm); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16) | + ((uint64_t)op << 28) | ((uint64_t)mem_rt << 32) | + ((uint64_t)ldr_imm12 << 40)); + gen(state, (unsigned long)ldr_pc); + return 1; +} + +static int try_fuse_addsub_ldr8(struct gen_state *state, uint32_t op, uint32_t rd, + uint32_t rn, uint32_t imm12) { + if (PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + + bool is_load, sign_extend; + uint32_t mem_rn, mem_rt, mem_size; + if (!arm64_decode_int_unsigned_imm_ldst(next_insn, &is_load, &sign_extend, &mem_rn, &mem_rt, &mem_size)) + return -1; + if (!is_load || sign_extend || mem_size != 0 || mem_rn != rd || mem_rt == 31) + return -1; + + uint32_t ldr_imm12 = (next_insn >> 10) & 0xfff; + addr_t ldr_pc = state->ip; + state->ip += 4; + + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_ldr8_count); + gen(state, (unsigned long)gadget_fused_addsub_ldr8_imm); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16) | + ((uint64_t)op << 28) | ((uint64_t)mem_rt << 32) | + ((uint64_t)ldr_imm12 << 40)); + gen(state, (unsigned long)ldr_pc); + return 1; +} + +static int try_fuse_addsub_str64(struct gen_state *state, uint32_t op, uint32_t rd, + uint32_t rn, uint32_t imm12) { + if (PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + + bool is_load, sign_extend; + uint32_t mem_rn, mem_rt, mem_size; + if (!arm64_decode_int_unsigned_imm_ldst(next_insn, &is_load, &sign_extend, &mem_rn, &mem_rt, &mem_size)) + return -1; + if (is_load || sign_extend || mem_size != 3 || mem_rn != rd || mem_rt == 31) + return -1; + + uint32_t str_imm12 = (next_insn >> 10) & 0xfff; + addr_t str_pc = state->ip; + state->ip += 4; + + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_str64_count); + gen(state, (unsigned long)gadget_fused_addsub_str64_imm); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16) | + ((uint64_t)op << 28) | ((uint64_t)mem_rt << 32) | + ((uint64_t)str_imm12 << 40)); + gen(state, (unsigned long)str_pc); + return 1; +} + +static int try_fuse_addsub_str32(struct gen_state *state, uint32_t op, uint32_t rd, + uint32_t rn, uint32_t imm12) { + if (PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + + bool is_load, sign_extend; + uint32_t mem_rn, mem_rt, mem_size; + if (!arm64_decode_int_unsigned_imm_ldst(next_insn, &is_load, &sign_extend, &mem_rn, &mem_rt, &mem_size)) + return -1; + if (is_load || sign_extend || mem_size != 2 || mem_rn != rd || mem_rt == 31) + return -1; + + uint32_t str_imm12 = (next_insn >> 10) & 0xfff; + addr_t str_pc = state->ip; + state->ip += 4; + + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_str32_count); + gen(state, (unsigned long)gadget_fused_addsub_str32_imm); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16) | + ((uint64_t)op << 28) | ((uint64_t)mem_rt << 32) | + ((uint64_t)str_imm12 << 40)); + gen(state, (unsigned long)str_pc); + return 1; +} + +static int try_fuse_addsub_str16(struct gen_state *state, uint32_t op, uint32_t rd, + uint32_t rn, uint32_t imm12) { + if (PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + + bool is_load, sign_extend; + uint32_t mem_rn, mem_rt, mem_size; + if (!arm64_decode_int_unsigned_imm_ldst(next_insn, &is_load, &sign_extend, &mem_rn, &mem_rt, &mem_size)) + return -1; + if (is_load || sign_extend || mem_size != 1 || mem_rn != rd || mem_rt == 31) + return -1; + + uint32_t str_imm12 = (next_insn >> 10) & 0xfff; + addr_t str_pc = state->ip; + state->ip += 4; + + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_str16_count); + gen(state, (unsigned long)gadget_fused_addsub_str16_imm); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16) | + ((uint64_t)op << 28) | ((uint64_t)mem_rt << 32) | + ((uint64_t)str_imm12 << 40)); + gen(state, (unsigned long)str_pc); + return 1; +} + +static int try_fuse_addsub_str8(struct gen_state *state, uint32_t op, uint32_t rd, + uint32_t rn, uint32_t imm12) { + if (PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + + bool is_load, sign_extend; + uint32_t mem_rn, mem_rt, mem_size; + if (!arm64_decode_int_unsigned_imm_ldst(next_insn, &is_load, &sign_extend, &mem_rn, &mem_rt, &mem_size)) + return -1; + if (is_load || sign_extend || mem_size != 0 || mem_rn != rd || mem_rt == 31) + return -1; + + uint32_t str_imm12 = (next_insn >> 10) & 0xfff; + addr_t str_pc = state->ip; + state->ip += 4; + + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_str8_count); + gen(state, (unsigned long)gadget_fused_addsub_str8_imm); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16) | + ((uint64_t)op << 28) | ((uint64_t)mem_rt << 32) | + ((uint64_t)str_imm12 << 40)); + gen(state, (unsigned long)str_pc); + return 1; +} + +static void count_ldr_cbz_candidate(struct gen_state *state, uint32_t rn, uint32_t rt, + uint32_t size, bool sign_extend) { + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return; + if ((next_insn & 0x7e000000) != 0x34000000) + return; + if ((next_insn & 0x1f) != rt || rt == 31) + return; + ARM64_FUSION_STAT_INC(arm64_fusion_ldr_cbz_candidate_count); + if (size == 3 && !sign_extend && ((next_insn >> 31) & 1)) { + ARM64_FUSION_STAT_INC(arm64_fusion_ldr64_cbz64_candidate_count); + if (rn == 31) + ARM64_FUSION_STAT_INC(arm64_fusion_ldr64_sp_cbz64_candidate_count); + } + if (size == 2 && sign_extend) + ARM64_FUSION_STAT_INC(arm64_fusion_ldr32_sx_cbz64_candidate_count); + if (size == 1 && sign_extend) + ARM64_FUSION_STAT_INC(arm64_fusion_ldr16_sx_cbz_candidate_count); + if (size == 0 && sign_extend) + ARM64_FUSION_STAT_INC(arm64_fusion_ldr8_sx_cbz_candidate_count); +} + +static int try_fuse_ldr64_cbz64(struct gen_state *state, uint32_t rn, uint32_t rt, uint32_t imm12) { + if (rn == 31 || rt == 31 || PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + if ((next_insn & 0x7e000000) != 0x34000000) + return -1; + if ((next_insn & 0x1f) != rt || ((next_insn >> 31) & 1) == 0) + return -1; + + bool is_cbnz = (next_insn >> 24) & 1; + addr_t cbz_pc = state->ip; + state->ip += 4; + + int64_t offset = arm64_branch_imm19(next_insn); + addr_t target = cbz_pc + offset; + unsigned long fake_target = (unsigned long)target | (1UL << 63); + unsigned long fake_fallthrough = (unsigned long)state->ip | (1UL << 63); + + ARM64_FUSION_STAT_INC(arm64_fusion_ldr64_cbz64_count); + gen(state, (unsigned long)(is_cbnz ? gadget_fused_ldr64_cbnz_imm : gadget_fused_ldr64_cbz_imm)); + gen(state, rt | (rn << 8) | ((uint64_t)imm12 << 16)); + gen(state, state->orig_ip); + gen(state, fake_target); + gen(state, fake_fallthrough); + state->jump_ip[0] = state->size - 2; + state->jump_ip[1] = state->size - 1; + return 0; +} + +static int try_fuse_ldr64_sp_cbz64(struct gen_state *state, uint32_t rn, uint32_t rt, uint32_t imm12) { + if (rn != 31 || rt == 31 || PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + if ((next_insn & 0x7e000000) != 0x34000000) + return -1; + if ((next_insn & 0x1f) != rt || ((next_insn >> 31) & 1) == 0) + return -1; + + bool is_cbnz = (next_insn >> 24) & 1; + addr_t cbz_pc = state->ip; + state->ip += 4; + + int64_t offset = arm64_branch_imm19(next_insn); + addr_t target = cbz_pc + offset; + unsigned long fake_target = (unsigned long)target | (1UL << 63); + unsigned long fake_fallthrough = (unsigned long)state->ip | (1UL << 63); + + ARM64_FUSION_STAT_INC(arm64_fusion_ldr64_sp_cbz64_count); + gen(state, (unsigned long)(is_cbnz ? gadget_fused_ldr64_sp_cbnz_imm : gadget_fused_ldr64_sp_cbz_imm)); + gen(state, rt | ((uint64_t)imm12 << 16)); + gen(state, state->orig_ip); + gen(state, fake_target); + gen(state, fake_fallthrough); + state->jump_ip[0] = state->size - 2; + state->jump_ip[1] = state->size - 1; + return 0; +} + +static int try_fuse_ldr32_sx_cbz64(struct gen_state *state, uint32_t rn, uint32_t rt, uint32_t imm12) { + if (rt == 31 || PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + if ((next_insn & 0x7e000000) != 0x34000000) + return -1; + if ((next_insn & 0x1f) != rt) + return -1; + + bool is_cbnz = (next_insn >> 24) & 1; + addr_t cbz_pc = state->ip; + state->ip += 4; + + int64_t offset = arm64_branch_imm19(next_insn); + addr_t target = cbz_pc + offset; + unsigned long fake_target = (unsigned long)target | (1UL << 63); + unsigned long fake_fallthrough = (unsigned long)state->ip | (1UL << 63); + + ARM64_FUSION_STAT_INC(arm64_fusion_ldr32_sx_cbz64_count); + gen(state, (unsigned long)(is_cbnz ? gadget_fused_ldr32_sx_cbnz_imm : gadget_fused_ldr32_sx_cbz_imm)); + gen(state, rt | (rn << 8) | ((uint64_t)imm12 << 16)); + gen(state, state->orig_ip); + gen(state, fake_target); + gen(state, fake_fallthrough); + state->jump_ip[0] = state->size - 2; + state->jump_ip[1] = state->size - 1; + return 0; +} + +static int try_fuse_ldr32_cbz32(struct gen_state *state, uint32_t rn, uint32_t rt, uint32_t imm12) { + if (rt == 31 || PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + if ((next_insn & 0x7e000000) != 0x34000000) + return -1; + if ((next_insn & 0x1f) != rt || ((next_insn >> 31) & 1) != 0) + return -1; + + bool is_cbnz = (next_insn >> 24) & 1; + addr_t cbz_pc = state->ip; + state->ip += 4; + + int64_t offset = arm64_branch_imm19(next_insn); + addr_t target = cbz_pc + offset; + unsigned long fake_target = (unsigned long)target | (1UL << 63); + unsigned long fake_fallthrough = (unsigned long)state->ip | (1UL << 63); + + ARM64_FUSION_STAT_INC(arm64_fusion_ldr32_cbz32_count); + gen(state, (unsigned long)(is_cbnz ? gadget_fused_ldr32_cbnz_imm : gadget_fused_ldr32_cbz_imm)); + gen(state, rt | (rn << 8) | ((uint64_t)imm12 << 16)); + gen(state, state->orig_ip); + gen(state, fake_target); + gen(state, fake_fallthrough); + state->jump_ip[0] = state->size - 2; + state->jump_ip[1] = state->size - 1; + return 0; +} + +static int try_fuse_ldr_sx_cbz(struct gen_state *state, uint32_t rn, uint32_t rt, + uint32_t imm12, uint32_t size, bool extend64) { + if (rt == 31 || PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + if (size > 1) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + if ((next_insn & 0x7e000000) != 0x34000000) + return -1; + if ((next_insn & 0x1f) != rt) + return -1; + + bool is_cbnz = (next_insn >> 24) & 1; + addr_t cbz_pc = state->ip; + state->ip += 4; + + int64_t offset = arm64_branch_imm19(next_insn); + addr_t target = cbz_pc + offset; + unsigned long fake_target = (unsigned long)target | (1UL << 63); + unsigned long fake_fallthrough = (unsigned long)state->ip | (1UL << 63); + + if (size == 1) + ARM64_FUSION_STAT_INC(arm64_fusion_ldr16_sx_cbz_count); + else + ARM64_FUSION_STAT_INC(arm64_fusion_ldr8_sx_cbz_count); + gen(state, (unsigned long)(is_cbnz ? gadget_fused_ldr_sx_cbnz_imm : gadget_fused_ldr_sx_cbz_imm)); + gen(state, rt | (rn << 8) | ((uint64_t)imm12 << 16) | ((uint64_t)size << 28) | ((uint64_t)extend64 << 29)); + gen(state, state->orig_ip); + gen(state, fake_target); + gen(state, fake_fallthrough); + state->jump_ip[0] = state->size - 2; + state->jump_ip[1] = state->size - 1; + return 0; +} + +static int try_fuse_ldr16_cbz32(struct gen_state *state, uint32_t rn, uint32_t rt, uint32_t imm12) { + if (rt == 31 || PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + if ((next_insn & 0x7e000000) != 0x34000000) + return -1; + if ((next_insn & 0x1f) != rt || ((next_insn >> 31) & 1) != 0) + return -1; + + bool is_cbnz = (next_insn >> 24) & 1; + addr_t cbz_pc = state->ip; + state->ip += 4; + + int64_t offset = arm64_branch_imm19(next_insn); + addr_t target = cbz_pc + offset; + unsigned long fake_target = (unsigned long)target | (1UL << 63); + unsigned long fake_fallthrough = (unsigned long)state->ip | (1UL << 63); + + ARM64_FUSION_STAT_INC(arm64_fusion_ldr16_cbz32_count); + gen(state, (unsigned long)(is_cbnz ? gadget_fused_ldr16_cbnz_imm : gadget_fused_ldr16_cbz_imm)); + gen(state, rt | (rn << 8) | ((uint64_t)imm12 << 16)); + gen(state, state->orig_ip); + gen(state, fake_target); + gen(state, fake_fallthrough); + state->jump_ip[0] = state->size - 2; + state->jump_ip[1] = state->size - 1; + return 0; +} + +static int try_fuse_ldr8_cbz32(struct gen_state *state, uint32_t rn, uint32_t rt, uint32_t imm12) { + if (rt == 31 || PAGE(state->orig_ip) != PAGE(state->ip)) + return -1; + + uint32_t next_insn; + if (!gen_peek_next_insn(state, &next_insn)) + return -1; + if ((next_insn & 0x7e000000) != 0x34000000) + return -1; + if ((next_insn & 0x1f) != rt || ((next_insn >> 31) & 1) != 0) + return -1; + + bool is_cbnz = (next_insn >> 24) & 1; + addr_t cbz_pc = state->ip; + state->ip += 4; + + int64_t offset = arm64_branch_imm19(next_insn); + addr_t target = cbz_pc + offset; + unsigned long fake_target = (unsigned long)target | (1UL << 63); + unsigned long fake_fallthrough = (unsigned long)state->ip | (1UL << 63); + + ARM64_FUSION_STAT_INC(arm64_fusion_ldr8_cbz32_count); + gen(state, (unsigned long)(is_cbnz ? gadget_fused_ldr8_cbnz_imm : gadget_fused_ldr8_cbz_imm)); + gen(state, rt | (rn << 8) | ((uint64_t)imm12 << 16)); + gen(state, state->orig_ip); + gen(state, fake_target); + gen(state, fake_fallthrough); + state->jump_ip[0] = state->size - 2; + state->jump_ip[1] = state->size - 1; + return 0; +} + +/* + * Data Processing (Immediate) + */ +static int gen_dp_imm(struct gen_state *state, uint32_t insn) { + uint32_t op0 = (insn >> 23) & 0x7; + + // PC-relative addressing (ADR, ADRP) + if ((insn & 0x1f000000) == 0x10000000) { + uint32_t rd = insn & 0x1f; + bool is_adrp = (insn >> 31) & 1; + int64_t imm = arm64_adr_imm(insn); + + addr_t target; + if (is_adrp) { + target = (state->orig_ip & ~0xFFF) + (imm << 12); + } else { + target = state->orig_ip + imm; + } + + // Try fused ADRP+LDR64: ADRP Xd, #page; LDR Xt, [Xd, #imm] + if (is_adrp && rd != 31) { + uint32_t next; + if (gen_peek_next_insn(state, &next)) { + // LDR Xt (64-bit, unsigned offset): 1111 1001 01 imm12 Rn Rt + if ((next & 0xffc00000) == 0xf9400000) { + uint32_t ldr_rt = next & 0x1f; + uint32_t ldr_rn = (next >> 5) & 0x1f; + uint32_t ldr_imm12 = (next >> 10) & 0xfff; + uint32_t ldr_offset = ldr_imm12 << 3; // scale by 8 for 64-bit + if (ldr_rn == rd && ldr_rt != 31) { + // Fuse: emit single gadget, consume the LDR + // Param 1: ldr_rt[0:4] | rd[5:9] | ldr_offset[16:31] + // Param 2: adrp_target (32-bit, zero-extended) + state->ip += 4; + ARM64_FUSION_STAT_INC(arm64_fusion_adrp_ldr64_count); + gen(state, (unsigned long) gadget_fused_adrp_ldr64); + gen(state, ldr_rt | ((uint64_t)rd << 5) | ((uint64_t)ldr_offset << 16)); + gen(state, target & 0xffffffffffffULL); + return 1; + } + } + // Try fused ADRP+ADD: ADD Xd, Xd, #imm12 (no shift) + // Encoding: 1001 0001 00 imm12 Rn Rd (sf=1, op=0, S=0, sh=0) + if ((next & 0xffc00000) == 0x91000000) { + uint32_t add_rd = next & 0x1f; + uint32_t add_rn = (next >> 5) & 0x1f; + uint32_t add_imm12 = (next >> 10) & 0xfff; + if (add_rn == rd && add_rd == rd) { + state->ip += 4; + ARM64_FUSION_STAT_INC(arm64_fusion_adrp_add_count); + gen(state, (unsigned long) gadget_fused_adrp_add); + gen(state, rd | ((uint64_t)add_imm12 << 8)); + gen(state, target & 0xffffffffffffULL); + return 1; + } + } + } + } + + // Generate: store immediate to register + // Pack rd(0:4) | target(8:55) in single code-stream word + gen(state, (unsigned long) gadget_adr); + gen(state, rd | ((uint64_t)(target & 0xffffffffffffULL) << 8)); + return 1; + } + + // Add/subtract (immediate) + if ((op0 & 0x6) == 0x2) { + uint32_t sf = (insn >> 31) & 1; // 0=32-bit, 1=64-bit + uint32_t op = (insn >> 30) & 1; // 0=ADD, 1=SUB + uint32_t S = (insn >> 29) & 1; // Set flags + uint32_t sh = (insn >> 22) & 1; // Shift (0=none, 1=LSL #12) + uint32_t imm12 = (insn >> 10) & 0xfff; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + // Don't pre-shift imm12 - pass sh flag to gadget instead + // This avoids overflow when imm12 << 12 > 12 bits + + // Try fused SUBS/CMP + B.cond peephole for both 32-bit and 64-bit + // (only for SUB with flags, no shift, rn!=31) + if (!sh && rn != 31 && S && op == 1) { + int fused = try_fuse_subs_bcond(state, sf, rd, rn, imm12); + if (fused == 0) return 0; // fused and block ended + } + + // Try ADD/SUB imm + CBZ/CBNZ of the result before the single-insn fast path. + if (!sh && !S && rd != 31 && rn != 31) { + int fused = try_fuse_addsub_cbz(state, sf, op, rd, rn, imm12); + if (fused == 0) return 0; // fused and block ended + count_addsub_ldst_candidates(state, rd); + if (sf && try_fuse_addsub_ldr64(state, op, rd, rn, imm12) == 1) + return 1; + if (sf && try_fuse_addsub_ldr32(state, op, rd, rn, imm12) == 1) + return 1; + if (sf && try_fuse_addsub_ldr16(state, op, rd, rn, imm12) == 1) + return 1; + if (sf && try_fuse_addsub_ldr8(state, op, rd, rn, imm12) == 1) + return 1; + if (sf && try_fuse_addsub_str64(state, op, rd, rn, imm12) == 1) + return 1; + if (sf && try_fuse_addsub_str32(state, op, rd, rn, imm12) == 1) + return 1; + if (sf && try_fuse_addsub_str16(state, op, rd, rn, imm12) == 1) + return 1; + if (sf && try_fuse_addsub_str8(state, op, rd, rn, imm12) == 1) + return 1; + } + + // Try specialized 64-bit fast paths (no SP/XZR source) + bool can_specialize_imm = sf && !sh && rn != 31; + bool can_specialize_imm_sh = sf && sh && rn != 31; + if (can_specialize_imm && S) { + // ADDS/SUBS imm 64-bit (rd=31 allowed for CMP/CMN) + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_fast_count); + gen(state, (unsigned long)(op ? gadget_subs_imm_64 : gadget_adds_imm_64)); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16)); + return 1; + } + if (can_specialize_imm_sh && S) { + // ADDS/SUBS imm 64-bit with LSL#12 (rd=31 allowed for CMP/CMN) + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_fast_count); + gen(state, (unsigned long)(op ? gadget_subs_imm_64_sh : gadget_adds_imm_64_sh)); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16)); + return 1; + } + if (can_specialize_imm && !S && rd != 31) { + // ADD/SUB imm 64-bit, no flags, no SP + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_fast_count); + gen(state, (unsigned long)(op ? gadget_sub_imm_64 : gadget_add_imm_64)); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16)); + return 1; + } + if (can_specialize_imm_sh && !S && rd != 31) { + // ADD/SUB imm 64-bit with LSL#12, no flags, no SP + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_fast_count); + gen(state, (unsigned long)(op ? gadget_sub_imm_64_sh : gadget_add_imm_64_sh)); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16)); + return 1; + } + + // Try specialized 32-bit fast paths (no SP/XZR source, no shift) + bool can_specialize_32 = !sf && !sh && rn != 31; + if (can_specialize_32 && S) { + // ADDS/SUBS imm 32-bit (rd=31 allowed for CMP/CMN) + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_fast_count); + gen(state, (unsigned long)(op ? gadget_subs_imm_32 : gadget_adds_imm_32)); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16)); + return 1; + } + if (can_specialize_32 && !S && rd != 31) { + // ADD/SUB imm 32-bit, no flags, no SP + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_fast_count); + gen(state, (unsigned long)(op ? gadget_sub_imm_32 : gadget_add_imm_32)); + gen(state, rd | (rn << 8) | ((uint64_t)imm12 << 16)); + return 1; + } + + // SP-source specialization: ADD/SUB Xd, SP, #imm (sf=1, S=0, sh=0, rn==31, rd!=31) + if (sf && !sh && rn == 31 && !S && rd != 31) { + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_fast_count); + gen(state, (unsigned long)(op ? gadget_sub_imm_sp_src_64 : gadget_add_imm_sp_src_64)); + gen(state, rd | ((uint64_t)imm12 << 16)); + return 1; + } + + // Generic path: handles remaining SP cases, LSL#12 with 32-bit, etc. + if (op == 0) { + gen(state, (unsigned long) gadget_add_imm); + } else { + gen(state, (unsigned long) gadget_sub_imm); + } + // Pack parameters: rd, rn, imm12, sf, S, sh + // Layout: [0:4]=rd, [8:12]=rn, [16:27]=imm12, [28]=sf, [29]=S, [30]=sh + uint64_t packed = rd | (rn << 8) | ((uint64_t)imm12 << 16) | ((uint64_t)sf << 28) | ((uint64_t)S << 29) | ((uint64_t)sh << 30); + gen(state, packed); + return 1; + } + + // EXTR - Extract register (concatenate and shift) + // Matches: 0b10010011110xxxxx (64-bit) / 0b00010011110xxxxx (32-bit) + if ((insn & 0xffe00000) == 0x93c00000 || (insn & 0xffe00000) == 0x13800000) { + uint32_t sf = (insn >> 31) & 1; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t imm = (insn >> 10) & 0x3f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + gen(state, (unsigned long) gadget_extr); + gen(state, rd | (rn << 8) | (rm << 16) | ((uint64_t)imm << 24) | ((uint64_t)sf << 30)); + return 1; + } + + // Logical (immediate) - only op0 == 0b100 + if (op0 == 0x4) { + uint32_t sf = (insn >> 31) & 1; + uint32_t opc = (insn >> 29) & 0x3; + uint32_t N = (insn >> 22) & 1; + uint32_t immr = (insn >> 16) & 0x3f; + uint32_t imms = (insn >> 10) & 0x3f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + uint64_t imm; + if (!decode_bitmask_imm(N, imms, immr, sf, &imm)) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget; + switch (opc) { + case 0: gadget = gadget_and_imm; break; // AND + case 1: gadget = gadget_orr_imm; break; // ORR + case 2: gadget = gadget_eor_imm; break; // EOR + case 3: gadget = gadget_and_imm; break; // ANDS (sets flags) + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | ((uint64_t)sf << 16) | ((opc == 3) ? (1UL << 17) : 0)); + gen(state, imm); + return 1; + } + + // Move wide (immediate) - MOVN, MOVZ, MOVK + // Pattern: x00x0101xxxxxxxxxxxxxxxxxxxxxxxx + if ((insn & 0x1f800000) == 0x12800000) { + uint32_t sf = (insn >> 31) & 1; + uint32_t opc = (insn >> 29) & 0x3; + uint32_t hw = (insn >> 21) & 0x3; + uint32_t imm16 = (insn >> 5) & 0xffff; + uint32_t rd = insn & 0x1f; + + + if (!sf && hw >= 2) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget; + switch (opc) { + case 0: gadget = gadget_movn; break; + case 2: gadget = gadget_movz; break; + case 3: gadget = gadget_movk; break; + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen(state, (unsigned long) gadget); + gen(state, rd | (hw << 8) | ((uint64_t)imm16 << 16) | ((uint64_t)sf << 32)); + return 1; + } + + // Bitfield operations (SBFM, BFM, UBFM) - includes LSL, LSR, ASR, SXTB, SXTW, etc. + // Pattern: x00x0110xxxxxxxxxxxxxxxxxxxxxxxx + if ((insn & 0x1f800000) == 0x13000000) { + uint32_t sf = (insn >> 31) & 1; + uint32_t opc = (insn >> 29) & 0x3; + // uint32_t N = (insn >> 22) & 1; // Not used for common aliases + uint32_t immr = (insn >> 16) & 0x3f; + uint32_t imms = (insn >> 10) & 0x3f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + // Fused parameter for UBFM/SBFM: immr | imms<<8 | sf<<16 | rn<<20 | rd<<28 + uint64_t fused_param = immr | (imms << 8) | ((uint64_t)sf << 16) + | ((uint64_t)rn << 20) | ((uint64_t)rd << 28); + bool can_fuse = (rn != 31 && rd != 31 && opc != 1); + + // Handle SBFM (opc=0) and UBFM (opc=2) with fused fast path + if (opc == 0) { + if (can_fuse) { + gen(state, (unsigned long) gadget_sbfm_fused); + gen(state, fused_param); + return 1; + } + // Fallback: load_reg + alias/generic + store_reg + gen(state, (unsigned long) gadget_load_reg); + gen(state, rn); + if (immr == 0 && imms == 31 && sf == 1) + gen(state, (unsigned long) gadget_sxtw); + else if (immr == 0 && imms == 15) { + gen(state, (unsigned long) gadget_sxth); + gen(state, sf); + } else if (immr == 0 && imms == 7) { + gen(state, (unsigned long) gadget_sxtb); + gen(state, sf); + } else { + gen(state, (unsigned long) gadget_sbfm); + gen(state, immr | (imms << 8) | ((uint64_t)sf << 16)); + } + } else if (opc == 2) { + if (can_fuse) { + gen(state, (unsigned long) gadget_ubfm_fused); + gen(state, fused_param); + return 1; + } + gen(state, (unsigned long) gadget_load_reg); + gen(state, rn); + if (immr == 0 && imms == 31 && sf == 1) + gen(state, (unsigned long) gadget_uxtw); + else if (immr == 0 && imms == 15) { + gen(state, (unsigned long) gadget_uxth); + gen(state, sf); + } else if (immr == 0 && imms == 7) { + gen(state, (unsigned long) gadget_uxtb); + gen(state, sf); + } else { + gen(state, (unsigned long) gadget_ubfm); + gen(state, immr | (imms << 8) | ((uint64_t)sf << 16)); + } + } else if (opc == 1) { + // BFM needs both source and destination — not fused + gen(state, (unsigned long) gadget_load_reg); + gen(state, rn); + gen(state, (unsigned long) gadget_bfm); + gen(state, immr | (imms << 8) | ((uint64_t)sf << 16) | ((uint64_t)rd << 24)); + } else { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + // Store result for non-fused paths + gen(state, (unsigned long) gadget_store_reg); + gen(state, rd); + return 1; + } + + gen_interrupt(state, INT_UNDEFINED); + return 0; +} + +/* + * Branches, Exceptions, and System Instructions + */ +static int gen_branch(struct gen_state *state, uint32_t insn) { + // SVC (system call) + if ((insn & 0xffe0001f) == 0xd4000001) { + gen(state, (unsigned long) gadget_svc); + gen(state, state->ip); // Next instruction address for resuming after syscall + gen_interrupt(state, INT_SYSCALL); + return 0; + } + + // BRK (breakpoint) - 11010100 001 imm16 000 00 + // Encoding: 0xd4200000 with mask 0xffe0001f + // This typically signals SIGTRAP. For now, treat as debug breakpoint. + if ((insn & 0xffe0001f) == 0xd4200000) { + gen_interrupt(state, INT_BREAKPOINT); + return 0; + } + + // Unconditional branch immediate (B, BL) + if ((insn & 0x7c000000) == 0x14000000) { + bool is_bl = (insn >> 31) & 1; + int64_t offset = arm64_branch_imm26(insn); + addr_t target = state->orig_ip + offset; + // Use fake_ip (with bit 63 set) so fiber_ret_chain can detect unchained blocks + unsigned long fake_target = (unsigned long)target | (1UL << 63); + + if (is_bl) { + // BL: save return address to X30 + // Code stream: [gadget][block_self_ptr][return_addr][fake_return_cont][fake_target] + unsigned long fake_return = (unsigned long)state->ip | (1UL << 63); + gen(state, (unsigned long) gadget_branch_link); + gen(state, 0); // block self-pointer (patched by gen_end) + gen(state, state->ip); // return address (next instruction) + gen(state, fake_return); // return continuation (patched to return-site block) + gen(state, fake_target); // call target (patched to callee block) + state->block_patch_ip = state->size - 4; // patch slot for block self-pointer + // jump_ip[0] = return continuation, jump_ip[1] = call target + state->jump_ip[0] = state->size - 2; + state->jump_ip[1] = state->size - 1; + } else { + // Extended basic block: follow unconditional B inline if safe + // Same-page + forward-only prevents infinite loops and page-tracking issues + if (PAGE(target) == PAGE(state->block->addr) && + target > state->orig_ip && + state->b_follow_depth < 3) { + state->ip = target; + state->b_follow_depth++; + return 1; // continue compiling from target + } + gen(state, (unsigned long) gadget_branch); + gen(state, fake_target); + state->jump_ip[0] = state->size - 1; + } + + return 0; + } + + // Conditional branch (B.cond) + if ((insn & 0xff000010) == 0x54000000) { + uint32_t cond = insn & 0xf; + int64_t offset = arm64_branch_imm19(insn); + addr_t target = state->orig_ip + offset; + unsigned long fake_target = (unsigned long)target | (1UL << 63); + unsigned long fake_fallthrough = (unsigned long)state->ip | (1UL << 63); + + // Per-condition gadgets eliminate indirect branch through jump table + static void *bcond_gadgets[16] = { + [0] = NULL, [1] = NULL, [2] = NULL, [3] = NULL, + [4] = NULL, [5] = NULL, [6] = NULL, [7] = NULL, + [8] = NULL, [9] = NULL, [10] = NULL, [11] = NULL, + [12] = NULL, [13] = NULL, [14] = NULL, [15] = NULL, + }; + if (!bcond_gadgets[0]) { + bcond_gadgets[0] = gadget_bcond_eq; + bcond_gadgets[1] = gadget_bcond_ne; + bcond_gadgets[2] = gadget_bcond_cs; + bcond_gadgets[3] = gadget_bcond_cc; + bcond_gadgets[4] = gadget_bcond_mi; + bcond_gadgets[5] = gadget_bcond_pl; + bcond_gadgets[6] = gadget_bcond_vs; + bcond_gadgets[7] = gadget_bcond_vc; + bcond_gadgets[8] = gadget_bcond_hi; + bcond_gadgets[9] = gadget_bcond_ls; + bcond_gadgets[10] = gadget_bcond_ge; + bcond_gadgets[11] = gadget_bcond_lt; + bcond_gadgets[12] = gadget_bcond_gt; + bcond_gadgets[13] = gadget_bcond_le; + bcond_gadgets[14] = NULL; // AL + bcond_gadgets[15] = NULL; // NV (treat as AL) + } + + if (cond >= 14) { + // AL/NV: always taken — emit unconditional branch + gen(state, (unsigned long) gadget_branch); + gen(state, fake_target); + state->jump_ip[0] = state->size - 1; + } else if (arm64_internal_continue_enabled && !state->internal_continue_used && + state->internal_continue_count + 2 <= GEN_INTERNAL_CONTINUE_MAX && + PAGE(state->ip) == PAGE(state->block->addr) && + ((arm64_internal_continue_taken_enabled && PAGE(target) == PAGE(state->block->addr) && + target > state->ip && target - state->ip <= 8) || target < state->ip)) { + if (arm64_internal_continue_taken_enabled && PAGE(target) == PAGE(state->block->addr) && target > state->ip && target - state->ip <= 8) { + // Phase 3B second prototype: taken edge continues through a + // private internal-continue record; fallthrough exits normally. + // The only public chain slot remains the external fake fallthrough. + gen(state, (unsigned long) gadget_bcond_taken_internal); + gen(state, cond); + unsigned internal_patch_ip = state->size; + gen(state, 0); + gen(state, fake_fallthrough); + state->jump_ip[0] = state->size - 1; // external fallthrough + unsigned internal_continue_ip = state->size; + if (!gen_record_internal_continue_patch(state, internal_patch_ip, internal_continue_ip) || + !gen_emit_internal_continue_record(state, target)) { + abort(); + } + ARM64_INTERNAL_CONTINUE_STAT_INC(arm64_internal_continue_bcond_taken_count); + state->internal_continue_used = 1; + state->internal_continue_segment_start = target; + state->internal_continue_segment_budget = GEN_INTERNAL_CONTINUE_BUDGET_INSNS; + state->ip = target; + return 1; + } + + // Phase 3B first prototype: taken edge exits normally; fallthrough + // continues through a private internal-continue record. The only + // public chain slot remains the external fake target. + gen(state, (unsigned long) gadget_bcond_fallthrough_internal); + gen(state, cond); + gen(state, fake_target); + state->jump_ip[0] = state->size - 1; // external taken target + unsigned internal_patch_ip = state->size; + gen(state, 0); + unsigned internal_continue_ip = state->size; + if (!gen_record_internal_continue_patch(state, internal_patch_ip, internal_continue_ip) || + !gen_emit_internal_continue_record(state, state->ip)) { + abort(); + } + ARM64_INTERNAL_CONTINUE_STAT_INC(arm64_internal_continue_bcond_fallthrough_count); + state->internal_continue_used = 1; + state->internal_continue_segment_start = state->ip; + state->internal_continue_segment_budget = GEN_INTERNAL_CONTINUE_BUDGET_INSNS; + return 1; + } else { + // Per-condition gadget: code stream is [gadget][target][fallthrough] + gen(state, (unsigned long) bcond_gadgets[cond]); + gen(state, fake_target); + gen(state, fake_fallthrough); + state->jump_ip[0] = state->size - 2; // target + state->jump_ip[1] = state->size - 1; // fallthrough + } + return 0; + } + + // Compare and branch (CBZ, CBNZ) + if ((insn & 0x7e000000) == 0x34000000) { + bool is_cbnz = (insn >> 24) & 1; + bool sf = (insn >> 31) & 1; + uint32_t rt = insn & 0x1f; + int64_t offset = arm64_branch_imm19(insn); + addr_t target = state->orig_ip + offset; + // Use fake_ip for both target and fallthrough + unsigned long fake_target = (unsigned long)target | (1UL << 63); + unsigned long fake_fallthrough = (unsigned long)state->ip | (1UL << 63); + + if (arm64_internal_continue_enabled && !state->internal_continue_used && + state->internal_continue_count + 2 <= GEN_INTERNAL_CONTINUE_MAX && + PAGE(state->ip) == PAGE(state->block->addr) && + ((arm64_internal_continue_taken_enabled && PAGE(target) == PAGE(state->block->addr) && + target > state->ip && target - state->ip <= 8) || target < state->ip)) { + uint64_t op = rt | ((uint64_t)sf << 8) | ((uint64_t)is_cbnz << 9); + if (arm64_internal_continue_taken_enabled && PAGE(target) == PAGE(state->block->addr) && + target > state->ip && target - state->ip <= 8) { + // Taken edge continues through a private internal-continue record; + // fallthrough exits normally through fake-IP/block dispatch. + gen(state, (unsigned long) gadget_cbz_taken_internal); + gen(state, op); + unsigned internal_patch_ip = state->size; + gen(state, 0); + gen(state, fake_fallthrough); + state->jump_ip[0] = state->size - 1; // external fallthrough + unsigned internal_continue_ip = state->size; + if (!gen_record_internal_continue_patch(state, internal_patch_ip, internal_continue_ip) || + !gen_emit_internal_continue_record(state, target)) { + abort(); + } + ARM64_INTERNAL_CONTINUE_STAT_INC(arm64_internal_continue_cbz_taken_count); + state->internal_continue_used = 1; + state->internal_continue_segment_start = target; + state->internal_continue_segment_budget = GEN_INTERNAL_CONTINUE_BUDGET_INSNS; + state->ip = target; + return 1; + } + + // Taken edge exits normally; fallthrough continues through a private + // internal-continue record. The only public chain slot is the target. + gen(state, (unsigned long) gadget_cbz_fallthrough_internal); + gen(state, op); + gen(state, fake_target); + state->jump_ip[0] = state->size - 1; // external taken target + unsigned internal_patch_ip = state->size; + gen(state, 0); + unsigned internal_continue_ip = state->size; + if (!gen_record_internal_continue_patch(state, internal_patch_ip, internal_continue_ip) || + !gen_emit_internal_continue_record(state, state->ip)) { + abort(); + } + ARM64_INTERNAL_CONTINUE_STAT_INC(arm64_internal_continue_cbz_fallthrough_count); + state->internal_continue_used = 1; + state->internal_continue_segment_start = state->ip; + state->internal_continue_segment_budget = GEN_INTERNAL_CONTINUE_BUDGET_INSNS; + return 1; + } else { + if (rt != 31) { + // Fast path: specialized gadgets skip XZR check and sf check + void *gadget; + if (is_cbnz) + gadget = sf ? gadget_cbnz_64 : gadget_cbnz_32; + else + gadget = sf ? gadget_cbz_64 : gadget_cbz_32; + gen(state, (unsigned long) gadget); + gen(state, (uint64_t)rt); + } else { + // Fallback: generic gadget handles XZR (rt==31) + gen(state, (unsigned long)(is_cbnz ? gadget_cbnz : gadget_cbz)); + gen(state, rt | ((uint64_t)sf << 8)); + } + gen(state, fake_target); + gen(state, fake_fallthrough); + + // Record both jump targets for potential block chaining + state->jump_ip[0] = state->size - 2; // target + state->jump_ip[1] = state->size - 1; // fallthrough + return 0; + } + } + + // Test and branch (TBZ, TBNZ) + // Encoding: b5:011011:op:b40:imm14:Rt + if ((insn & 0x7e000000) == 0x36000000) { + bool is_tbnz = (insn >> 24) & 1; + uint32_t b5 = (insn >> 31) & 1; + uint32_t b40 = (insn >> 19) & 0x1f; + uint32_t bit_pos = (b5 << 5) | b40; + uint32_t rt = insn & 0x1f; + int64_t imm14 = (insn >> 5) & 0x3fff; + if (imm14 & 0x2000) imm14 |= ~0x3fffLL; // sign-extend + int64_t offset = imm14 * 4; + addr_t target = state->orig_ip + offset; + + unsigned long fake_target = (unsigned long)target | (1UL << 63); + unsigned long fake_fallthrough = (unsigned long)state->ip | (1UL << 63); + + if (arm64_internal_continue_enabled && !state->internal_continue_used && + state->internal_continue_count + 2 <= GEN_INTERNAL_CONTINUE_MAX && + PAGE(state->ip) == PAGE(state->block->addr) && + ((arm64_internal_continue_taken_enabled && PAGE(target) == PAGE(state->block->addr) && + target > state->ip && target - state->ip <= 8) || target < state->ip)) { + uint64_t op = rt | ((uint64_t)bit_pos << 8) | ((uint64_t)is_tbnz << 14); + if (arm64_internal_continue_taken_enabled && PAGE(target) == PAGE(state->block->addr) && + target > state->ip && target - state->ip <= 8) { + // Taken edge continues through a private internal-continue record; + // fallthrough exits normally through fake-IP/block dispatch. + gen(state, (unsigned long) gadget_tbz_taken_internal); + gen(state, op); + unsigned internal_patch_ip = state->size; + gen(state, 0); + gen(state, fake_fallthrough); + state->jump_ip[0] = state->size - 1; // external fallthrough + unsigned internal_continue_ip = state->size; + if (!gen_record_internal_continue_patch(state, internal_patch_ip, internal_continue_ip) || + !gen_emit_internal_continue_record(state, target)) { + abort(); + } + ARM64_INTERNAL_CONTINUE_STAT_INC(arm64_internal_continue_tbz_taken_count); + state->internal_continue_used = 1; + state->internal_continue_segment_start = target; + state->internal_continue_segment_budget = GEN_INTERNAL_CONTINUE_BUDGET_INSNS; + state->ip = target; + return 1; + } + + // Taken edge exits normally; fallthrough continues through a private + // internal-continue record. The only public chain slot is the target. + gen(state, (unsigned long) gadget_tbz_fallthrough_internal); + gen(state, op); + gen(state, fake_target); + state->jump_ip[0] = state->size - 1; // external taken target + unsigned internal_patch_ip = state->size; + gen(state, 0); + unsigned internal_continue_ip = state->size; + if (!gen_record_internal_continue_patch(state, internal_patch_ip, internal_continue_ip) || + !gen_emit_internal_continue_record(state, state->ip)) { + abort(); + } + ARM64_INTERNAL_CONTINUE_STAT_INC(arm64_internal_continue_tbz_fallthrough_count); + state->internal_continue_used = 1; + state->internal_continue_segment_start = state->ip; + state->internal_continue_segment_budget = GEN_INTERNAL_CONTINUE_BUDGET_INSNS; + return 1; + } else { + if (is_tbnz) { + gen(state, (unsigned long) gadget_tbnz); + } else { + gen(state, (unsigned long) gadget_tbz); + } + gen(state, rt | (bit_pos << 8)); + gen(state, fake_target); + gen(state, fake_fallthrough); + + state->jump_ip[0] = state->size - 2; // target + state->jump_ip[1] = state->size - 1; // fallthrough + return 0; + } + } + + // Unconditional branch register (BR, BLR, RET) + if ((insn & 0xfe000000) == 0xd6000000) { + uint32_t opc = (insn >> 21) & 0xf; + uint32_t rn = (insn >> 5) & 0x1f; + + switch (opc) { + case 0: // BR + gen(state, (unsigned long) gadget_branch_reg); + gen(state, rn); + break; + case 1: // BLR + gen(state, (unsigned long) gadget_branch_link_reg); + gen(state, rn); + gen(state, state->ip); // return address + break; + case 2: // RET + gen(state, (unsigned long) gadget_ret); + gen(state, rn); // usually X30 + break; + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + return 0; + } + + // System instructions (MSR, MRS, HINT, etc.) + if ((insn & 0xffc00000) == 0xd5000000) { + // HINT instructions (including NOP) + // Encoding: 1101 0101 0000 0011 0010 xxxx xxx1 1111 + if ((insn & 0xfffff01f) == 0xd503201f) { + // NOP, YIELD, WFE, WFI, SEV, SEVL, etc. + // Just do nothing and continue to next instruction + return 1; + } + + // Barrier instructions (DMB, DSB, ISB) + // DMB: 1101 0101 0000 0011 0011 CRm 1011 1111 = 0xd50330bf | (CRm << 8) + // DSB: 1101 0101 0000 0011 0011 CRm 1001 1111 = 0xd503309f | (CRm << 8) + // ISB: 1101 0101 0000 0011 0011 CRm 1101 1111 = 0xd50330df | (CRm << 8) + // Guest threads run as real host threads sharing host memory, so guest + // barriers must issue real host barriers. Keep DSB/ISB distinct: DSB + // is stronger than DMB, and ISB is an instruction-synchronization event. + if ((insn & 0xfffff0ff) == 0xd50330bf) { // DMB + gen(state, (unsigned long) gadget_dmb); + return 1; + } + if ((insn & 0xfffff0ff) == 0xd503309f) { // DSB + gen(state, (unsigned long) gadget_dsb); + return 1; + } + if ((insn & 0xfffff0ff) == 0xd50330df) { // ISB + gen(state, (unsigned long) gadget_isb); + return 1; + } + + // CLREX — Clear Exclusive Monitor + // Encoding: 1101 0101 0000 0011 0011 CRm 0101 1111 = 0xd503305f | (CRm << 8) + if ((insn & 0xfffff0ff) == 0xd503305f) { + // Must clear both single and pair exclusive monitor state. + // Treating CLREX as NOP lets a subsequent STXR/STXP succeed + // when architecture requires failure. + gen(state, (unsigned long) gadget_clrex); + return 1; + } + + // Data cache zero by VA. DCZID_EL0 below advertises a 64-byte block. + if ((insn & 0xffffffe0) == 0xd50b7420) { // DC ZVA + uint32_t rt = insn & 0x1f; + gen(state, (unsigned long) gadget_dc_zva); + gen(state, rt); + return 1; + } + + // IC IVAU (Invalidate icache by VA to PoU): d50b752x + // This is the architectural signal that the guest modified code at + // the given address (self-modifying code: JIT repatching, inline + // cache updates, lazy stub linking). It must NOT be a NOP: iSH only + // invalidates translated blocks on a write-TLB-miss, so a store + // through an already-writable TLB entry to a page with compiled + // blocks leaves them stale. JSC/bun repatches JIT code in place and + // then issues DC CVAU + IC IVAU per cache line; treating IC IVAU as + // a NOP left the pre-patch translation running (observed: FTL lazy + // slow path compiled twice -> RELEASE_ASSERT(!m_stub) abort, inline + // caches returning stale property values). + if ((insn & 0xffffffe0) == 0xd50b7520) { // IC IVAU + uint32_t rt = insn & 0x1f; + gen(state, (unsigned long) gadget_ic_ivau); + gen(state, rt); + return 1; + } + + // Data-cache maintenance (DC) — NOP in emulation (host memory is + // coherent; only the *instruction* side needs retranslation, which + // IC IVAU above handles). + // DC CIVAC (Clean and Invalidate by VA to PoC): d50b7e2x + // DC CVAU (Clean by VA to PoU): d50b7b2x + // DC CVAC (Clean by VA to PoC): d50b7a2x + if ((insn & 0xffffffe0) == 0xd50b7e20 || // DC CIVAC + (insn & 0xffffffe0) == 0xd50b7b20 || // DC CVAU + (insn & 0xffffffe0) == 0xd50b7a20) { // DC CVAC + return 1; // NOP — no cache to maintain + } + + // MRS/MSR NZCV (condition flags register) + // MRS Xt, NZCV: d53b4200 | Rt (op0=3, op1=3, CRn=4, CRm=2, op2=0) + // MSR NZCV, Xt: d51b4200 | Rt + if ((insn & 0xffffffe0) == 0xd53b4200) { + // MRS Xt, NZCV - read condition flags + uint32_t rt = insn & 0x1f; + gen(state, (unsigned long) gadget_mrs_nzcv); + gen(state, rt); + return 1; + } + if ((insn & 0xffffffe0) == 0xd51b4200) { + // MSR NZCV, Xt - write condition flags + uint32_t rt = insn & 0x1f; + gen(state, (unsigned long) gadget_msr_nzcv); + gen(state, rt); + return 1; + } + + // MSR FPCR, Xt: d51b4400 (op0=3, op1=3, CRn=4, CRm=4, op2=0) + if ((insn & 0xffffffe0) == 0xd51b4400) { + uint32_t rt = insn & 0x1f; + gen(state, (unsigned long) gadget_msr_fpcr); + gen(state, rt); + return 1; + } + // MSR FPSR, Xt: d51b4420 (op0=3, op1=3, CRn=4, CRm=4, op2=1) + if ((insn & 0xffffffe0) == 0xd51b4420) { + uint32_t rt = insn & 0x1f; + gen(state, (unsigned long) gadget_msr_fpsr); + gen(state, rt); + return 1; + } + // MSR DAIF, Xt: d51b4220 (op0=3, op1=3, CRn=4, CRm=2, op2=1) + // Go runtime uses this for async preemption control. NOP in emulation. + if ((insn & 0xffffffe0) == 0xd51b4220) { + uint32_t rt = insn & 0x1f; + gen(state, (unsigned long) gadget_msr_daif); + gen(state, rt); + return 1; + } + + // MSR/MRS for TPIDR_EL0 (TLS pointer) + // MSR: d51bd04t (write Xt to TPIDR_EL0) + // MRS: d53bd04t (read TPIDR_EL0 to Xt) + // Check for TPIDR_EL0 encoding: op0=3, op1=3, CRn=13, CRm=0, op2=2 + // Bits: L=0/1, op0=11, op1=011, CRn=1101, CRm=0000, op2=010 + if ((insn & 0xffffffe0) == 0xd51bd040) { + // MSR TPIDR_EL0, Xt - write TLS pointer + uint32_t rt = insn & 0x1f; + gen(state, (unsigned long) gadget_msr_tpidr); + gen(state, rt); + return 1; + } + if ((insn & 0xffffffe0) == 0xd53bd040) { + // MRS Xt, TPIDR_EL0 - read TLS pointer + uint32_t rt = insn & 0x1f; + gen(state, (unsigned long) gadget_mrs_tpidr); + gen(state, rt); + return 1; + } + + // General MRS instruction: d53x xxxx + // Format: 1101 0101 0011 op0 op1 CRn CRm op2 Rt + if ((insn & 0xfff00000) == 0xd5300000) { + uint32_t rt = insn & 0x1f; + // Extract system register encoding + // op0[20:19], op1[18:16], CRn[15:12], CRm[11:8], op2[7:5] + uint32_t op0 = (insn >> 19) & 0x3; + uint32_t op1 = (insn >> 16) & 0x7; + uint32_t CRn = (insn >> 12) & 0xf; + uint32_t CRm = (insn >> 8) & 0xf; + uint32_t op2 = (insn >> 5) & 0x7; + + int sysreg_id = -1; + + // MIDR_EL1: op0=3, op1=0, CRn=0, CRm=0, op2=0 + // User runtimes such as Zig probe this in CPU model detection paths. + if (op0 == 3 && op1 == 0 && CRn == 0 && CRm == 0 && op2 == 0) { + sysreg_id = SYSREG_ID_MIDR_EL1; + } + // CTR_EL0: op0=3, op1=3, CRn=0, CRm=0, op2=1 (insn & 0xffffffe0 == 0xd53b00e0) + else if (op0 == 3 && op1 == 3 && CRn == 0 && CRm == 0 && op2 == 1) { + sysreg_id = SYSREG_ID_CTR_EL0; + } + // DCZID_EL0: op0=3, op1=3, CRn=0, CRm=0, op2=7 (insn & 0xffffffe0 == 0xd53b00e0) + else if (op0 == 3 && op1 == 3 && CRn == 0 && CRm == 0 && op2 == 7) { + sysreg_id = SYSREG_ID_DCZID_EL0; + } + // FPCR: op0=3, op1=3, CRn=4, CRm=4, op2=0 + else if (op0 == 3 && op1 == 3 && CRn == 4 && CRm == 4 && op2 == 0) { + sysreg_id = SYSREG_ID_FPCR; + } + // FPSR: op0=3, op1=3, CRn=4, CRm=4, op2=1 + else if (op0 == 3 && op1 == 3 && CRn == 4 && CRm == 4 && op2 == 1) { + sysreg_id = SYSREG_ID_FPSR; + } + // RNDR: op0=3, op1=3, CRn=2, CRm=4, op2=0 (ARMv8.5-RNG Random Number) + else if (op0 == 3 && op1 == 3 && CRn == 2 && CRm == 4 && op2 == 0) { + sysreg_id = SYSREG_ID_RNDR; + } + // RNDRRS: op0=3, op1=3, CRn=2, CRm=4, op2=1 (ARMv8.5-RNG Reseeded Random Number) + else if (op0 == 3 && op1 == 3 && CRn == 2 && CRm == 4 && op2 == 1) { + sysreg_id = SYSREG_ID_RNDRRS; + } + // ID_AA64DFR0/DFR1_EL1: op0=3, op1=0, CRn=0, CRm=5, op2=0/1 + // User runtimes probe these for CPU feature models; report no optional debug features. + else if (op0 == 3 && op1 == 0 && CRn == 0 && CRm == 5 && op2 <= 1) { + sysreg_id = SYSREG_ID_ZERO; + } + // ID_AA64PFR0_EL1: op0=3, op1=0, CRn=0, CRm=4, op2=0 + else if (op0 == 3 && op1 == 0 && CRn == 0 && CRm == 4 && op2 == 0) { + sysreg_id = SYSREG_ID_ID_AA64PFR0_EL1; + } + // ID_AA64PFR1_EL1: op0=3, op1=0, CRn=0, CRm=4, op2=1 + else if (op0 == 3 && op1 == 0 && CRn == 0 && CRm == 4 && op2 == 1) { + sysreg_id = SYSREG_ID_ID_AA64PFR1_EL1; + } + // ID_AA64ZFR0_EL1: op0=3, op1=0, CRn=0, CRm=4, op2=4 + else if (op0 == 3 && op1 == 0 && CRn == 0 && CRm == 4 && op2 == 4) { + sysreg_id = SYSREG_ID_ID_AA64ZFR0_EL1; + } + // ID_AA64ISAR0_EL1: op0=3, op1=0, CRn=0, CRm=6, op2=0 + else if (op0 == 3 && op1 == 0 && CRn == 0 && CRm == 6 && op2 == 0) { + sysreg_id = SYSREG_ID_ID_AA64ISAR0_EL1; + } + // ID_AA64ISAR1_EL1: op0=3, op1=0, CRn=0, CRm=6, op2=1 + else if (op0 == 3 && op1 == 0 && CRn == 0 && CRm == 6 && op2 == 1) { + sysreg_id = SYSREG_ID_ID_AA64ISAR1_EL1; + } + // ID_AA64MMFR0..3_EL1: op0=3, op1=0, CRn=0, CRm=7, op2=0..3 + // Report no optional memory-model extensions beyond the base ABI. + else if (op0 == 3 && op1 == 0 && CRn == 0 && CRm == 7 && op2 <= 3) { + sysreg_id = SYSREG_ID_ZERO; + } + // CNTVCT_EL0: op0=3, op1=3, CRn=14, CRm=0, op2=2 + else if (op0 == 3 && op1 == 3 && CRn == 14 && CRm == 0 && op2 == 2) { + sysreg_id = SYSREG_ID_CNTVCT_EL0; + } + // CNTFRQ_EL0: op0=3, op1=3, CRn=14, CRm=0, op2=0 + else if (op0 == 3 && op1 == 3 && CRn == 14 && CRm == 0 && op2 == 0) { + sysreg_id = SYSREG_ID_CNTFRQ_EL0; + } + + if (sysreg_id >= 0) { + gen(state, (unsigned long) gadget_mrs_sysreg); + gen(state, rt); + gen(state, sysreg_id); + return 1; + } + + } + + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen_interrupt(state, INT_UNDEFINED); + return 0; +} + +/* + * Loads and Stores + */ +static int gen_ldst(struct gen_state *state, uint32_t insn) { + // Normal-register LDR X unsigned-immediate saves its retry PC in the load + // gadget itself (as does its LDR+CBZ/CBNZ fusion). Avoid a separate gadget + // dispatch and code-stream pointer for this common case. All other memory + // instructions retain the standalone precise-PC save. + bool inline_load64_pc = (insn & 0xffc00000) == 0xf9400000 && + ((insn >> 5) & 0x1f) != 31 && (insn & 0x1f) != 31; + if (!inline_load64_pc) { + gen(state, (unsigned long) gadget_set_jit_saved_pc); + gen(state, state->orig_ip); + } + uint32_t op0 = (insn >> 28) & 0xf; + + // Atomic memory operations (LSE): LDADD/LDCLR/LDEOR/LDSET/LDUMAX/LDUMIN/LDSMAX/LDSMIN/SWP + // Encoding: size:111000:A:R:1:Rs:op:Rn:Rt (bits29-24=111000, bit21=1, bits11-10=00) + // A=acquire (bit23), R=release (bit22) + if ((insn & 0x3f200c00) == 0x38200000) { + uint32_t size = (insn >> 30) & 0x3; + uint32_t A = (insn >> 23) & 1; // acquire + uint32_t R = (insn >> 22) & 1; // release + uint32_t rs = (insn >> 16) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rt = insn & 0x1f; + uint32_t op = (insn >> 12) & 0xf; + + // Supported ops: 0-8 (LDADD, LDCLR, LDEOR, LDSET, LDSMAX, LDSMIN, LDUMAX, LDUMIN, SWP) + if (op > 0x8) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + // Generate address from Rn + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); // offset = 0 + + if (R) gen(state, (unsigned long) gadget_dmb); // release barrier before + // Perform atomic RMW (returns old value in _tmp) + gen(state, (unsigned long) gadget_atomic_rmw); + gen(state, rs | ((uint64_t)size << 8) | ((uint64_t)op << 16)); + if (A) gen(state, (unsigned long) gadget_dmb); // acquire barrier after + + // Store old value to Rt + gen(state, (unsigned long) gadget_store_reg); + gen(state, rt); + return 1; + } + + // Atomic compare-and-swap pair (CASP/CASPA/CASPL/CASPAL) + // Encoding overlaps single CAS, but bit23 is clear and size selects + // pair width: 0 = two 32-bit words, 1 = two 64-bit words. + if ((insn & 0x3f200c00) == 0x08200c00 && ((insn >> 23) & 1) == 0 && + ((insn >> 30) & 0x3) <= 1) { + uint32_t pair_size = ((insn >> 30) & 0x1) + 2; + uint32_t A = (insn >> 22) & 1; + uint32_t R = (insn >> 15) & 1; + uint32_t rs = (insn >> 16) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rt = insn & 0x1f; + + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); + if (R) gen(state, (unsigned long) gadget_dmb); + gen(state, (unsigned long) gadget_atomic_casp); + gen(state, rs | ((uint64_t)rt << 8) | ((uint64_t)pair_size << 16)); + if (A) gen(state, (unsigned long) gadget_dmb); + return 1; + } + + // Atomic compare-and-swap (CAS/CASA/CASL/CASAL) + // Encoding: size:001000:1:A:1:Rs:R:11111:Rn:Rt + // bit23 is fixed 1 for single-register CAS; A=acquire is bit22, + // R=release is bit15. Pair exclusives (LDXP/STXP) have the same broad + // opcode mask but bit23=0 and size=2/3, so keep this predicate narrow. + if ((insn & 0x3f200c00) == 0x08200c00 && ((insn >> 23) & 1) == 1) { + uint32_t size = (insn >> 30) & 0x3; + uint32_t A = (insn >> 22) & 1; // acquire + uint32_t R = (insn >> 15) & 1; // release + uint32_t rs = (insn >> 16) & 0x1f; // expected value (and result) + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rt = insn & 0x1f; // new value + + // Generate address from Rn + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); // offset = 0 + + if (R) gen(state, (unsigned long) gadget_dmb); // release barrier before + // Perform CAS (returns old value in _tmp) + gen(state, (unsigned long) gadget_atomic_cas); + gen(state, rs | ((uint64_t)rt << 8) | ((uint64_t)size << 16)); + if (A) gen(state, (unsigned long) gadget_dmb); // acquire barrier after + + // Store old value back to Rs (CAS writes old value to expected register) + gen(state, (unsigned long) gadget_store_reg); + gen(state, rs); + return 1; + } + + // LDR (literal) - PC-relative load + // Encoding: opc 011 V 00 imm19 Rt + // opc=00: LDR Wt (32-bit) - mask 0xff000000, value 0x18000000 + // opc=01: LDR Xt (64-bit) - mask 0xff000000, value 0x58000000 + // opc=10: LDRSW Xt (signed word) - mask 0xff000000, value 0x98000000 + // V=1 means SIMD/FP register + if ((insn & 0x3b000000) == 0x18000000) { + uint32_t opc = (insn >> 30) & 0x3; + uint32_t V = (insn >> 26) & 1; + uint32_t rt = insn & 0x1f; + int32_t imm19 = (insn >> 5) & 0x7ffff; + // Sign-extend imm19 and multiply by 4 + if (imm19 & 0x40000) imm19 |= (int32_t)~0x7ffff; + int32_t offset = imm19 << 2; + // Compute target as full-width address + addr_t target = state->orig_ip + offset; + + + if (V) { + // SIMD/FP literal load + // opc=00: LDR St (32-bit float) + // opc=01: LDR Dt (64-bit float) + // opc=10: LDR Qt (128-bit) + gen(state, (unsigned long) gadget_calc_addr_pc_rel); + gen(state, (unsigned long) target); // 32-bit guest address + + void *gadget; + switch (opc) { + case 0: gadget = gadget_ldr_simd_s; break; + case 1: gadget = gadget_ldr_simd_d; break; + case 2: gadget = gadget_ldr_simd_q; break; + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gen(state, (unsigned long) gadget); + gen(state, rt); + return 1; + } else { + // GPR literal load + gen(state, (unsigned long) gadget_calc_addr_pc_rel); + gen(state, (unsigned long) target); // 32-bit guest address + + void *gadget; + switch (opc) { + case 0: gadget = gadget_load32; break; // LDR Wt + case 1: gadget = gadget_load64; break; // LDR Xt + case 2: gadget = gadget_load32_sx; break; // LDRSW Xt + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gen(state, (unsigned long) gadget); + gen(state, (unsigned long) gadget_store_reg); + gen(state, rt); + return 1; + } + } + + // Load/store register (unsigned immediate) + if ((insn & 0x3b000000) == 0x39000000) { + uint32_t size = (insn >> 30) & 0x3; + uint32_t V = (insn >> 26) & 1; + uint32_t opc = (insn >> 22) & 0x3; + uint32_t imm12 = (insn >> 10) & 0xfff; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rt = insn & 0x1f; + + if (V) { + // SIMD/FP load/store unsigned immediate + // For SIMD, size encodes: 00=B, 01=H, 10=S, 11=D + // But for Q (128-bit), size=00 and opc[1]=1 + uint32_t scale; + if (size == 0 && (opc & 2)) { + // 128-bit (Q register) + scale = 4; // 16 bytes = 2^4 + } else { + scale = size; + } + uint64_t offset = imm12 << scale; + + // Generate address calculation + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (offset << 8)); + + bool is_load = (opc & 1) == 1; + + if (is_load) { + // LDR Bt/Ht/St/Dt/Qt + void *gadget; + if (size == 0 && (opc & 2)) { + gadget = gadget_ldr_simd_q; + } else { + switch (size) { + case 0: gadget = gadget_ldr_simd_b; break; + case 1: gadget = gadget_ldr_simd_h; break; + case 2: gadget = gadget_ldr_simd_s; break; + case 3: gadget = gadget_ldr_simd_d; break; + default: gen_interrupt(state, INT_UNDEFINED); return 0; + } + } + gen(state, (unsigned long) gadget); + gen(state, rt); + } else { + // STR Bt/Ht/St/Dt/Qt + void *gadget; + if (size == 0 && (opc & 2)) { + gadget = gadget_str_simd_q; + } else { + switch (size) { + case 0: gadget = gadget_str_simd_b; break; + case 1: gadget = gadget_str_simd_h; break; + case 2: gadget = gadget_str_simd_s; break; + case 3: gadget = gadget_str_simd_d; break; + default: gen_interrupt(state, INT_UNDEFINED); return 0; + } + } + gen(state, (unsigned long) gadget); + gen(state, rt); + } + return 1; + } + + // PRFM (prefetch memory) - treat as NOP + if (size == 3 && opc == 2 && V == 0) + return 1; + + // Calculate scaled offset + uint64_t offset = imm12 << size; + + bool is_load = (opc & 1) == 1 || (opc & 2) == 2; + bool sign_extend = (opc & 2) != 0; + bool extend64 = sign_extend && opc == 2; + if (is_load) { + count_ldr_cbz_candidate(state, rn, rt, size, sign_extend); + if (!sign_extend && size == 3 && try_fuse_ldr64_cbz64(state, rn, rt, imm12) == 0) + return 0; + if (!sign_extend && size == 3 && try_fuse_ldr64_sp_cbz64(state, rn, rt, imm12) == 0) + return 0; + if (sign_extend && size == 2 && try_fuse_ldr32_sx_cbz64(state, rn, rt, imm12) == 0) + return 0; + if (sign_extend && size < 2 && try_fuse_ldr_sx_cbz(state, rn, rt, imm12, size, extend64) == 0) + return 0; + if (!sign_extend && size == 2 && try_fuse_ldr32_cbz32(state, rn, rt, imm12) == 0) + return 0; + if (!sign_extend && size == 1 && try_fuse_ldr16_cbz32(state, rn, rt, imm12) == 0) + return 0; + if (!sign_extend && size == 0 && try_fuse_ldr8_cbz32(state, rn, rt, imm12) == 0) + return 0; + } + + // Use fused gadgets for non-sign-extending loads and all stores + // Sign-extending 8/16-bit loads are less common, keep as 3-gadget + bool use_fused = true; + if (is_load && sign_extend && size < 2) + use_fused = false; + + if (use_fused) { + // Fused gadget: [gadget addr][rd_or_rt | rn<<8 | offset<<16] + uint64_t fused_param = (is_load ? rt : rt) | ((uint64_t)rn << 8) | ((uint64_t)offset << 16); + + bool fast = (rn != 31 && rt != 31); + bool sp_fast = (rn == 31 && rt != 31); + if (is_load) { + void *gadget; + switch (size) { + case 0: gadget = fast ? gadget_load8_imm_fast : gadget_load8_imm; break; + case 1: gadget = fast ? gadget_load16_imm_fast : gadget_load16_imm; break; + case 2: gadget = sign_extend ? gadget_load32_sx_imm : + (fast ? gadget_load32_imm_fast : + (sp_fast ? gadget_load32_sp_imm : gadget_load32_imm)); break; + case 3: gadget = fast ? gadget_load64_imm_fast : + (sp_fast ? gadget_load64_sp_imm : gadget_load64_imm); break; + default: gen_interrupt(state, INT_UNDEFINED); return 0; + } + gen(state, (unsigned long) gadget); + gen(state, fused_param); + if (gadget == gadget_load64_imm_fast) + gen(state, state->orig_ip); + } else { + void *gadget; + switch (size) { + case 0: gadget = fast ? gadget_store8_imm_fast : gadget_store8_imm; break; + case 1: gadget = fast ? gadget_store16_imm_fast : gadget_store16_imm; break; + case 2: gadget = fast ? gadget_store32_imm_fast : + (sp_fast ? gadget_store32_sp_imm : gadget_store32_imm); break; + case 3: gadget = fast ? gadget_store64_imm_fast : + (sp_fast ? gadget_store64_sp_imm : gadget_store64_imm); break; + default: gen_interrupt(state, INT_UNDEFINED); return 0; + } + gen(state, (unsigned long) gadget); + gen(state, fused_param); + } + } else { + // Fallback 3-gadget path for sign-extending 8/16-bit loads + gen(state, (unsigned long) gadget_calc_addr_imm); + uint64_t param = rn | ((uint64_t)offset << 8); + gen(state, param); + + bool extend_to_64 = (opc == 2); + void *gadget; + switch (size) { + case 0: + gadget = extend_to_64 ? gadget_load8_sx64 : gadget_load8_sx32; + break; + case 1: + gadget = extend_to_64 ? gadget_load16_sx64 : gadget_load16_sx32; + break; + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gen(state, (unsigned long) gadget); + gen(state, (unsigned long) gadget_store_reg); + gen(state, rt); + } + return 1; + } + + // Load/store register (register offset) + // Pattern: xx111000xx1xxxxx1xx10xxxxxxxxxxx + if ((insn & 0x3b200c00) == 0x38200800) { + uint32_t size = (insn >> 30) & 0x3; + uint32_t V = (insn >> 26) & 1; + uint32_t opc = (insn >> 22) & 0x3; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t option = (insn >> 13) & 0x7; + uint32_t S = (insn >> 12) & 1; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rt = insn & 0x1f; + + if (V) { + // SIMD/FP load/store (register offset) + bool is_load = (opc & 1); + bool is_128bit = (size == 0 && (opc & 2)); // Q register + uint32_t size_bytes = is_128bit ? 16 : (1u << size); + uint32_t shift = S ? (is_128bit ? 4 : size) : 0; + + // Generate address calculation with register offset + gen(state, (unsigned long) gadget_calc_addr_reg); + gen(state, rn | (rm << 8) | (option << 16) | (shift << 24)); + + void *gadget; + if (is_load) { + switch (size_bytes) { + case 1: gadget = gadget_ldr_simd_b; break; + case 2: gadget = gadget_ldr_simd_h; break; + case 4: gadget = gadget_ldr_simd_s; break; + case 8: gadget = gadget_ldr_simd_d; break; + case 16: gadget = gadget_ldr_simd_q; break; + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + } else { + switch (size_bytes) { + case 1: gadget = gadget_str_simd_b; break; + case 2: gadget = gadget_str_simd_h; break; + case 4: gadget = gadget_str_simd_s; break; + case 8: gadget = gadget_str_simd_d; break; + case 16: gadget = gadget_str_simd_q; break; + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + } + + gen(state, (unsigned long) gadget); + gen(state, rt); // SIMD register number + return 1; + } + + // PRFM (prefetch memory, register offset) - treat as NOP + if (size == 3 && opc == 2 && V == 0) + return 1; + + // Calculate shift amount based on size and S bit + uint32_t shift = S ? size : 0; + + bool is_load = (opc == 1) || (opc == 2) || (opc == 3); + bool sign_extend = (opc >= 2); + bool extend_to_64 = (opc == 2); + + // Use fused reg-offset gadgets for option==3 (UXTX/LSL, no extend) + // Sign-extending 8/16-bit loads are rare with register offset, keep as 3-gadget + bool use_fused_reg = (option == 3); + if (is_load && sign_extend && size < 2) + use_fused_reg = false; + + if (use_fused_reg) { + uint64_t fused_param = rt | ((uint64_t)rn << 8) | ((uint64_t)rm << 16) | ((uint64_t)shift << 24); + + if (is_load) { + void *gadget; + switch (size) { + case 0: gadget = gadget_load8_reg; break; + case 1: gadget = gadget_load16_reg; break; + case 2: gadget = sign_extend ? gadget_load32_sx_reg : gadget_load32_reg; break; + case 3: gadget = gadget_load64_reg; break; + default: gen_interrupt(state, INT_UNDEFINED); return 0; + } + gen(state, (unsigned long) gadget); + gen(state, fused_param); + } else { + void *gadget; + switch (size) { + case 0: gadget = gadget_store8_reg; break; + case 1: gadget = gadget_store16_reg; break; + case 2: gadget = gadget_store32_reg; break; + case 3: gadget = gadget_store64_reg; break; + default: gen_interrupt(state, INT_UNDEFINED); return 0; + } + gen(state, (unsigned long) gadget); + gen(state, fused_param); + } + } else { + // Fallback 3-gadget path for extend types other than UXTX, + // and for sign-extending 8/16-bit loads + gen(state, (unsigned long) gadget_calc_addr_reg); + gen(state, rn | (rm << 8) | (option << 16) | (shift << 24)); + + if (is_load) { + void *gadget; + switch (size) { + case 0: + gadget = sign_extend ? (extend_to_64 ? gadget_load8_sx64 : gadget_load8_sx32) : gadget_load8; + break; + case 1: + gadget = sign_extend ? (extend_to_64 ? gadget_load16_sx64 : gadget_load16_sx32) : gadget_load16; + break; + case 2: + gadget = sign_extend ? gadget_load32_sx : gadget_load32; + break; + case 3: + gadget = gadget_load64; + break; + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gen(state, (unsigned long) gadget); + gen(state, (unsigned long) gadget_store_reg); + gen(state, rt); + } else { + gen(state, (unsigned long) gadget_load_reg); + gen(state, rt); + + void *gadget; + switch (size) { + case 0: gadget = gadget_store8; break; + case 1: gadget = gadget_store16; break; + case 2: gadget = gadget_store32; break; + case 3: gadget = gadget_store64; break; + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gen(state, (unsigned long) gadget); + } + } + return 1; + } + + // Load/store pair (LDP/STP) + // Encoding: xx101xxx_xxxxxxxx_xxxxxxxx_xxxxxxxx + if ((insn & 0x3a000000) == 0x28000000) { + uint32_t opc = (insn >> 30) & 0x3; // size: 00=32-bit, 10=64-bit + uint32_t V = (insn >> 26) & 1; + uint32_t mode = (insn >> 23) & 0x7; // 001=post, 010=signed offset, 011=pre + uint32_t L = (insn >> 22) & 1; // 0=store, 1=load + int32_t imm7 = (int32_t)((insn >> 15) & 0x7f); + if (imm7 & 0x40) imm7 |= ~0x7f; // sign-extend + uint32_t rt2 = (insn >> 10) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rt = insn & 0x1f; + + // Compute actual offset (scaled by element size). For GPR pairs, + // opc=00 is W LDP/STP, opc=10 is X LDP/STP, and opc=01 with L=1 + // is LDPSW (two sign-extending 32-bit loads into X registers). + // opc=01 stores and opc=11 GPR pairs are unallocated. + bool is_ldpsw = (!V && L && opc == 1); + bool is64 = (V && opc == 1) || (!V && opc == 2); // SIMD D or GPR X pair + int64_t offset = (int64_t)imm7 * (is64 ? 8 : 4); + + if (!V && (opc == 3 || (opc == 1 && !L))) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + if (V) { + // SIMD/FP load/store pair + // opc=00 -> 32-bit (S), opc=01 -> 64-bit (D), opc=10 -> 128-bit (Q) + uint32_t size_bytes = (opc == 0) ? 4 : (opc == 1) ? 8 : 16; + int64_t simd_offset = (int64_t)imm7 * size_bytes; + + bool is_pre = (mode == 3); + bool is_post = (mode == 1); + bool is_offset = (mode == 2 || mode == 0); // 000=LDNP/STNP, 010=LDP/STP signed offset + + if (!is_pre && !is_post && !is_offset) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + // Calculate address + if (is_post) { + gen(state, (unsigned long) gadget_calc_addr_base); + gen(state, rn); + } else { + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | ((uint64_t)simd_offset << 8)); + } + + // Perform load/store + void *gadget; + if (L) { + switch (opc) { + case 0: gadget = gadget_ldp_simd_s; break; + case 1: gadget = gadget_ldp_simd_d; break; + case 2: gadget = gadget_ldp_simd_q; break; + default: gen_interrupt(state, INT_UNDEFINED); return 0; + } + } else { + switch (opc) { + case 0: gadget = gadget_stp_simd_s; break; + case 1: gadget = gadget_stp_simd_d; break; + case 2: gadget = gadget_stp_simd_q; break; + default: gen_interrupt(state, INT_UNDEFINED); return 0; + } + } + gen(state, (unsigned long) gadget); + gen(state, rt | (rt2 << 8)); + + // Writeback for pre/post-indexed + if (is_pre || is_post) { + if (is_post) { + gen(state, (unsigned long) gadget_update_base); + gen(state, rn | ((uint64_t)simd_offset << 8)); + } else { + gen(state, (unsigned long) gadget_writeback_addr); + gen(state, rn); + } + } + + return 1; + } + + // For signed offset mode (010), just calculate address + // For post-indexed (001), use base first, then update + // For pre-indexed (011), calculate address first, then use and update + + bool is_pre = (mode == 3); + bool is_post = (mode == 1); + bool is_offset = (mode == 2 || mode == 0); // 000=LDNP/STNP, 010=LDP/STP signed offset + + if (!is_pre && !is_post && !is_offset) { + // Unsupported mode + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + // Fused path for signed-offset mode (most common LDP/STP encoding) + if (is_offset) { + int16_t off16 = (int16_t)offset; + uint64_t param = (uint64_t)(rt & 0x1f) + | ((uint64_t)(rt2 & 0x1f) << 8) + | ((uint64_t)(rn & 0x1f) << 16) + | (((uint64_t)(uint16_t)off16) << 24); + bool fast_pair = rn != 31 && rt != 31 && rt2 != 31; + void *gadget; + if (L) { + if (is_ldpsw) + gadget = fast_pair ? gadget_ldpsw_imm_fast : gadget_ldpsw_imm; + else + gadget = fast_pair ? (is64 ? gadget_ldp64_imm_fast : gadget_ldp32_imm_fast) + : (is64 ? gadget_ldp64_imm : gadget_ldp32_imm); + } else { + gadget = fast_pair ? (is64 ? gadget_stp64_imm_fast : gadget_stp32_imm_fast) + : (is64 ? gadget_stp64_imm : gadget_stp32_imm); + } + gen(state, (unsigned long) gadget); + gen(state, param); + return 1; + } + + // Pre/post-indexed: use separate calc_addr + ldp/stp + writeback + + // Step 1: Calculate address + if (is_post) { + // Post-indexed: use base register directly + gen(state, (unsigned long) gadget_calc_addr_base); + gen(state, rn); + } else { + // Pre-indexed: add offset to base + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | ((uint64_t)offset << 8)); + } + + // Step 2: Perform the load/store pair + if (L) { + gen(state, (unsigned long) (is_ldpsw ? gadget_ldpsw : (is64 ? gadget_ldp64 : gadget_ldp32))); + } else { + gen(state, (unsigned long) (is64 ? gadget_stp64 : gadget_stp32)); + } + gen(state, rt | (rt2 << 8)); + + // Step 3: Writeback for pre/post-indexed + if (is_post) { + gen(state, (unsigned long) gadget_update_base); + gen(state, rn | ((uint64_t)offset << 8)); + } else { + // Pre-indexed: writeback calculated address + gen(state, (unsigned long) gadget_writeback_addr); + gen(state, rn); + } + + return 1; + } + + // Load/store register (immediate pre/post-indexed) + // Pattern: xx111000xx0xxxxxxxxx[01|11]xxxxxxxxxx + if ((insn & 0x3b200000) == 0x38000000) { + uint32_t size = (insn >> 30) & 0x3; + uint32_t V = (insn >> 26) & 1; + uint32_t opc = (insn >> 22) & 0x3; + int32_t imm9 = (int32_t)((insn >> 12) & 0x1ff); + // Sign-extend imm9 from 9 bits + if (imm9 & 0x100) imm9 |= ~0x1ff; + uint32_t mode = (insn >> 10) & 0x3; // 01=post-indexed, 11=pre-indexed + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rt = insn & 0x1f; + + + if (V) { + // SIMD/FP load/store with unscaled immediate or pre/post-indexed + // size: 00=B, 01=H, 10=S, 11=D + // opc: 00=store, 01=load, 10=store (128-bit if size=00), 11=load (128-bit if size=00) + bool is_load = (opc & 1); + bool is_128bit = (size == 0 && (opc & 2)); // Q register + + uint32_t size_bytes; + if (is_128bit) { + size_bytes = 16; + } else { + size_bytes = (1 << size); // 1, 2, 4, or 8 bytes + } + + // Calculate address (same as GPR case) + bool is_unscaled = (mode == 0); + bool is_pre = (mode == 3); + + if (is_pre || is_unscaled) { + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | ((int64_t)(int32_t)imm9 << 8)); + } else if (mode == 1) { + // Post-indexed + gen(state, (unsigned long) gadget_calc_addr_base); + gen(state, rn); + } else { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget; + if (is_load) { + switch (size_bytes) { + case 1: gadget = gadget_ldr_simd_b; break; + case 2: gadget = gadget_ldr_simd_h; break; + case 4: gadget = gadget_ldr_simd_s; break; + case 8: gadget = gadget_ldr_simd_d; break; + case 16: gadget = gadget_ldr_simd_q; break; + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + } else { + switch (size_bytes) { + case 1: gadget = gadget_str_simd_b; break; + case 2: gadget = gadget_str_simd_h; break; + case 4: gadget = gadget_str_simd_s; break; + case 8: gadget = gadget_str_simd_d; break; + case 16: gadget = gadget_str_simd_q; break; + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + } + + gen(state, (unsigned long) gadget); + gen(state, rt); // SIMD register number + + // Handle writeback for pre/post-indexed modes + // Use update_base to preserve full 64-bit register semantics + if (mode == 1 || mode == 3) { + gen(state, (unsigned long) gadget_update_base); + gen(state, rn | ((int64_t)(int32_t)imm9 << 8)); + } + + return 1; + } + + // mode: 0=unscaled(STUR/LDUR), 1=post-indexed, 2=unprivileged, 3=pre-indexed + + // PRFM (prefetch memory, unscaled/pre/post) - treat as NOP + if (size == 3 && opc == 2 && V == 0) + return 1; + + if (mode == 2) { + // Unprivileged access - not implemented + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + bool is_pre_indexed = (mode == 3); + bool is_unscaled = (mode == 0); // STUR/LDUR - offset applied, no writeback + bool is_load = (opc == 1) || (opc == 2) || (opc == 3); + + // Calculate address: + // - mode=0 (unscaled): address = base + offset (no writeback) + // - mode=1 (post-indexed): address = base (base+offset for writeback) + // - mode=3 (pre-indexed): address = base + offset (same for writeback) + if (is_pre_indexed || is_unscaled) { + // Pre-indexed or unscaled: address = base + offset + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | ((int64_t)(int32_t)imm9 << 8)); + } else { + // Post-indexed: address = base only + gen(state, (unsigned long) gadget_calc_addr_base); + gen(state, rn); + } + + if (is_load) { + void *gadget; + bool sign_extend = (opc >= 2); + bool extend_to_64 = (opc == 2); + + switch (size) { + case 0: // Byte + gadget = sign_extend ? (extend_to_64 ? gadget_load8_sx64 : gadget_load8_sx32) : gadget_load8; + break; + case 1: // Halfword + gadget = sign_extend ? (extend_to_64 ? gadget_load16_sx64 : gadget_load16_sx32) : gadget_load16; + break; + case 2: // Word + gadget = sign_extend ? gadget_load32_sx : gadget_load32; + break; + case 3: // Doubleword + gadget = gadget_load64; + break; + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gen(state, (unsigned long) gadget); + gen(state, (unsigned long) gadget_store_reg); + gen(state, rt); + } else { + // Store + gen(state, (unsigned long) gadget_load_reg); + gen(state, rt); + + void *gadget; + switch (size) { + case 0: gadget = gadget_store8; break; + case 1: gadget = gadget_store16; break; + case 2: gadget = gadget_store32; break; + case 3: gadget = gadget_store64; break; + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gen(state, (unsigned long) gadget); + } + + // Writeback to base register (only for pre/post-indexed, not unscaled) + if (!is_unscaled) { + if (is_pre_indexed) { + // Pre-indexed: base = address (which is base + offset) + gen(state, (unsigned long) gadget_writeback_addr); + gen(state, rn); + } else { + // Post-indexed: base = base + offset + gen(state, (unsigned long) gadget_update_base); + gen(state, rn | ((int64_t)(int32_t)imm9 << 8)); + } + } + + return 1; + } + + // Load/store exclusive (LDXR, STXR, LDAXR, STLXR, etc.) + // Encoding: size:001000:o2:L:o1:Rs:o0:Rt2:Rn:Rt + // For single-threaded emulation, we can treat these as simple loads/stores + if ((insn & 0x3f000000) == 0x08000000) { + uint32_t size = (insn >> 30) & 0x3; + uint32_t o2 = (insn >> 23) & 1; + uint32_t L = (insn >> 22) & 1; + uint32_t o1 = (insn >> 21) & 1; + uint32_t rs = (insn >> 16) & 0x1f; + uint32_t o0 = (insn >> 15) & 1; + uint32_t rt2 = (insn >> 10) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rt = insn & 0x1f; + + // o0: acquire/release flag — o0=1 means LDAXR/STLXR (with barrier) + + // o2=1: STLR/LDAR/LDLAR/STLLR — non-exclusive, non-pair load/store with + // acquire/release semantics (always have barrier). + // o2=0, o1=1: STXP/LDXP/STLXP/LDAXP — exclusive pair operations. + // o2=0, o1=0: STXR/LDXR/STLXR/LDAXR — exclusive register operations. + + // Handle pair exclusives (LDXP/STXP/LDAXP/STLXP): o2=0, o1=1 + if (o2 == 0 && o1 == 1) { + // Generate address from Rn + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); // offset = 0 + + if (L) { + // LDXP/LDAXP - Load pair via C helper + if (size != 2 && size != 3) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gen(state, (unsigned long) gadget_ldxp_c); + gen(state, rt | ((uint64_t)rt2 << 8) | ((uint64_t)size << 16)); + if (o0) gen(state, (unsigned long) gadget_dmb); // LDAXP: acquire + } else { + if (o0) gen(state, (unsigned long) gadget_dmb); // STLXP: release + // STXP/STLXP - Pair store exclusive with status result in Rs + gen(state, (unsigned long) gadget_stxp_c); + gen(state, rs | ((uint64_t)rt << 8) | ((uint64_t)rt2 << 16) | ((uint64_t)size << 24)); + } + return 1; + } + + // For non-pair operations (o2=0, o1=0 OR o2=1), fall through to + // load/store handling. Ignore Rt2 field (it should be 11111 + // for non-pair, but some compilers emit non-standard values). + + if (o2 == 1) { + // STLR/LDAR/LDLAR/STLLR — non-exclusive, non-pair + // With acquire/release memory ordering via DMB barriers. + // Guest threads share host memory, so real barriers are required. + if (L) { + // LDAR (load-acquire): load + DMB after + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); + void (*load_gadget)(void) = NULL; + switch (size) { + case 0: load_gadget = gadget_load8; break; + case 1: load_gadget = gadget_load16; break; + case 2: load_gadget = gadget_load32; break; + case 3: load_gadget = gadget_load64; break; + } + gen(state, (unsigned long) load_gadget); + gen(state, (unsigned long) gadget_dmb); + gen(state, (unsigned long) gadget_store_reg); + gen(state, rt); + } else { + // STLR (store-release): DMB before + store + gen(state, (unsigned long) gadget_load_reg); + gen(state, rt); + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); + gen(state, (unsigned long) gadget_dmb); + void (*store_gadget)(void) = NULL; + switch (size) { + case 0: store_gadget = gadget_store8; break; + case 1: store_gadget = gadget_store16; break; + case 2: store_gadget = gadget_store32; break; + case 3: store_gadget = gadget_store64; break; + } + gen(state, (unsigned long) store_gadget); + // No Rs writeback for STLR/STLLR (non-exclusive) + } + } else if (L) { + // LDXR/LDAXR - Load exclusive + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); // offset = 0 + gen(state, (unsigned long) gadget_ldxr); + gen(state, rt | ((uint64_t)size << 8)); + if (o0) gen(state, (unsigned long) gadget_dmb); // LDAXR: acquire + } else { + // STXR/STLXR - Store exclusive + if (o0) gen(state, (unsigned long) gadget_dmb); // STLXR: release + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); // offset = 0 + gen(state, (unsigned long) gadget_stxr); + gen(state, rt | ((uint64_t)rs << 8) | ((uint64_t)size << 16)); + } + return 1; + } + + // AdvSIMD load/store multiple structures (no post-index) + // Handles both non-interleaved (LD1/ST1) and interleaved (LD2/ST2/LD3/ST3/LD4/ST4) + // Pattern: 0 Q 001100 0 L 0 00000 opcode size Rn Rt + if ((insn & 0xbfbf0000) == 0x0c000000) { + uint32_t Q = (insn >> 30) & 1; + uint32_t L = (insn >> 22) & 1; + uint32_t opcode = (insn >> 12) & 0xf; + uint32_t size = (insn >> 10) & 3; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rt = insn & 0x1f; + + // Non-interleaved: LD1/ST1 + int num_regs = 0; + if (opcode == 0x7) num_regs = 1; + else if (opcode == 0xa) num_regs = 2; + else if (opcode == 0x6) num_regs = 3; + else if (opcode == 0x2) num_regs = 4; + + if (num_regs > 0) { + int bytes_per_reg = Q ? 16 : 8; + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); + for (int i = 0; i < num_regs; i++) { + uint32_t vt = (rt + i) & 0x1f; + if (L) { + gen(state, (unsigned long) (Q ? gadget_ldr_simd_q : gadget_ldr_simd_d)); + gen(state, vt); + } else { + gen(state, (unsigned long) (Q ? gadget_str_simd_q : gadget_str_simd_d)); + gen(state, vt); + } + if (i < num_regs - 1) { + gen(state, (unsigned long) gadget_advance_addr); + gen(state, bytes_per_reg); + } + } + return 1; + } + + // Interleaved: LD2/ST2 (opcode=0x8), LD3/ST3 (opcode=0x4), LD4/ST4 (opcode=0x0) + int interleave_regs = 0; + if (opcode == 0x8) interleave_regs = 2; + else if (opcode == 0x4) interleave_regs = 3; + else if (opcode == 0x0) interleave_regs = 4; + + if (interleave_regs > 0) { + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); + uint64_t param = rt | ((uint64_t)interleave_regs << 8) | + ((uint64_t)size << 16) | ((uint64_t)Q << 24); + if (L) { + gen(state, (unsigned long) gadget_simd_load_interleaved); + } else { + gen(state, (unsigned long) gadget_simd_store_interleaved); + } + gen(state, param); + return 1; + } + + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + // AdvSIMD load/store multiple structures (post-indexed) + // Handles both non-interleaved (LD1/ST1) and interleaved (LD2-4/ST2-4) + if ((insn & 0xbfa00000) == 0x0c800000) { + uint32_t Q = (insn >> 30) & 1; + uint32_t L = (insn >> 22) & 1; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t opcode = (insn >> 12) & 0xf; + uint32_t size = (insn >> 10) & 3; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rt = insn & 0x1f; + + // Non-interleaved: LD1/ST1 + int num_regs = 0; + if (opcode == 0x7) num_regs = 1; + else if (opcode == 0xa) num_regs = 2; + else if (opcode == 0x6) num_regs = 3; + else if (opcode == 0x2) num_regs = 4; + + int interleave_regs = 0; + if (opcode == 0x8) interleave_regs = 2; + else if (opcode == 0x4) interleave_regs = 3; + else if (opcode == 0x0) interleave_regs = 4; + + int effective_regs = num_regs ? num_regs : interleave_regs; + if (effective_regs == 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + int bytes_per_reg = Q ? 16 : 8; + int total_bytes = bytes_per_reg * effective_regs; + + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); + + if (num_regs > 0) { + // Non-interleaved path + for (int i = 0; i < num_regs; i++) { + uint32_t vt = (rt + i) & 0x1f; + if (L) { + gen(state, (unsigned long) (Q ? gadget_ldr_simd_q : gadget_ldr_simd_d)); + gen(state, vt); + } else { + gen(state, (unsigned long) (Q ? gadget_str_simd_q : gadget_str_simd_d)); + gen(state, vt); + } + if (i < num_regs - 1) { + gen(state, (unsigned long) gadget_advance_addr); + gen(state, bytes_per_reg); + } + } + } else { + // Interleaved path + uint64_t param = rt | ((uint64_t)interleave_regs << 8) | + ((uint64_t)size << 16) | ((uint64_t)Q << 24); + if (L) { + gen(state, (unsigned long) gadget_simd_load_interleaved); + } else { + gen(state, (unsigned long) gadget_simd_store_interleaved); + } + gen(state, param); + } + + // Post-index writeback + if (rm == 31) { + gen(state, (unsigned long) gadget_update_base); + gen(state, rn | ((uint64_t)total_bytes << 8)); + } else { + gen(state, (unsigned long) gadget_update_base_reg); + gen(state, rn | (rm << 8)); + } + return 1; + } + + // LD/ST (single structure) - Advanced SIMD load/store single element + // Pattern: 0 Q 001101 0 L R 0 xxxx opcode S size Rn Rt + // Includes LD1/ST1 single element + LDnR (load and replicate) + // Fixed bits: bit[31]=0, bits[29:24]=001101, bit[23]=0 + // Mask: 0xbf800000, expected: 0x0d000000 + if ((insn & 0xbf800000) == 0x0d000000) { + uint32_t Q = (insn >> 30) & 1; + uint32_t L = (insn >> 22) & 1; + uint32_t R = (insn >> 21) & 1; + uint32_t opcode = (insn >> 13) & 0x7; + uint32_t S = (insn >> 12) & 1; + uint32_t size = (insn >> 10) & 0x3; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rt = insn & 0x1f; + + // LDnR: Load single element and replicate to all lanes of n registers + // opcode=6,R=0 → LD1R; opcode=6,R=1 → LD2R + // opcode=7,R=0 → LD3R; opcode=7,R=1 → LD4R + if ((opcode == 6 || opcode == 7) && S == 0 && L == 1) { + void *gadget; + if (opcode == 6 && R == 0) { gadget = gadget_ld1r_vec; } + else if (opcode == 6 && R == 1) { gadget = gadget_ld2r_vec; } + else if (opcode == 7 && R == 0) { gadget = gadget_ld3r_vec; } + else { gadget = gadget_ld4r_vec; } + + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); + gen(state, (unsigned long) gadget); + gen(state, rt | (size << 8) | (Q << 16)); + return 1; + } + + // Number of registers from R and opcode: + // R=0, even opcode(0/2/4): LD1/ST1 (1 reg) + // R=1, even opcode(0/2/4): LD2/ST2 (2 regs) + // R=0, odd opcode(1/3/5): LD3/ST3 (3 regs) + // R=1, odd opcode(1/3/5): LD4/ST4 (4 regs) + int num_regs; + int base_opcode = opcode; + if (opcode & 1) { + num_regs = R ? 4 : 3; + base_opcode = opcode - 1; + } else { + num_regs = R ? 2 : 1; + } + + int elem_size = 0; + int lane = 0; + + if (base_opcode == 0) { + elem_size = 1; + lane = (Q << 3) | (S << 2) | size; + } else if (base_opcode == 2 && (size & 1) == 0) { + elem_size = 2; + lane = (Q << 2) | (S << 1) | (size >> 1); + } else if (base_opcode == 4 && size == 0) { + elem_size = 4; + lane = (Q << 1) | S; + } else if (base_opcode == 4 && size == 1) { + elem_size = 8; + lane = Q; + } else { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + int lane_offset = lane * elem_size; + + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); + + for (int i = 0; i < num_regs; i++) { + if (i > 0) { + gen(state, (unsigned long) gadget_addr_add_imm); + gen(state, (uint64_t)elem_size); + } + uint32_t vr = (rt + i) % 32; + if (L) { + if (elem_size == 1) + gen(state, (unsigned long) gadget_ld1_single_b); + else if (elem_size == 2) + gen(state, (unsigned long) gadget_ld1_single_h); + else if (elem_size == 4) + gen(state, (unsigned long) gadget_ld1_single_s); + else + gen(state, (unsigned long) gadget_ld1_single_d); + } else { + if (elem_size == 1) + gen(state, (unsigned long) gadget_st1_single_b); + else if (elem_size == 2) + gen(state, (unsigned long) gadget_st1_single_h); + else if (elem_size == 4) + gen(state, (unsigned long) gadget_st1_single_s); + else + gen(state, (unsigned long) gadget_st1_single_d); + } + gen(state, vr | (lane_offset << 8)); + } + return 1; + } + + // LD/ST (single structure, post-indexed) - with register or immediate post-index + // Pattern: 0 Q 001101 1 L R Rm opcode S size Rn Rt (bit23=1) + // Mask: 0xbf800000, expected: 0x0d800000 + if ((insn & 0xbf800000) == 0x0d800000) { + uint32_t Q = (insn >> 30) & 1; + uint32_t L = (insn >> 22) & 1; + uint32_t R = (insn >> 21) & 1; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t opcode = (insn >> 13) & 0x7; + uint32_t S = (insn >> 12) & 1; + uint32_t size = (insn >> 10) & 0x3; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rt = insn & 0x1f; + + // LDnR post-indexed: Load single element and replicate to all lanes + if ((opcode == 6 || opcode == 7) && S == 0 && L == 1) { + int num_regs; + void *gadget; + if (opcode == 6 && R == 0) { num_regs = 1; gadget = gadget_ld1r_vec; } + else if (opcode == 6 && R == 1) { num_regs = 2; gadget = gadget_ld2r_vec; } + else if (opcode == 7 && R == 0) { num_regs = 3; gadget = gadget_ld3r_vec; } + else { num_regs = 4; gadget = gadget_ld4r_vec; } + + int ldnr_elem_size = 1 << size; + int total_bytes = ldnr_elem_size * num_regs; + + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); + gen(state, (unsigned long) gadget); + gen(state, rt | (size << 8) | (Q << 16)); + + // Post-index writeback + if (rm == 31) { + gen(state, (unsigned long) gadget_update_base); + gen(state, rn | ((uint64_t)total_bytes << 8)); + } else { + gen(state, (unsigned long) gadget_update_base_reg); + gen(state, rn | (rm << 8)); + } + return 1; + } + + // Number of registers (same logic as non-post-indexed) + int num_regs; + int base_opcode = opcode; + if (opcode & 1) { + num_regs = R ? 4 : 3; + base_opcode = opcode - 1; + } else { + num_regs = R ? 2 : 1; + } + + int elem_size = 0; + int lane = 0; + + if (base_opcode == 0) { + elem_size = 1; + lane = (Q << 3) | (S << 2) | size; + } else if (base_opcode == 2 && (size & 1) == 0) { + elem_size = 2; + lane = (Q << 2) | (S << 1) | (size >> 1); + } else if (base_opcode == 4 && size == 0) { + elem_size = 4; + lane = (Q << 1) | S; + } else if (base_opcode == 4 && size == 1) { + elem_size = 8; + lane = Q; + } else { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + int lane_offset = lane * elem_size; + int total_bytes = elem_size * num_regs; + + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (0ULL << 8)); + + for (int i = 0; i < num_regs; i++) { + if (i > 0) { + gen(state, (unsigned long) gadget_addr_add_imm); + gen(state, (uint64_t)elem_size); + } + uint32_t vr = (rt + i) % 32; + if (L) { + if (elem_size == 1) + gen(state, (unsigned long) gadget_ld1_single_b); + else if (elem_size == 2) + gen(state, (unsigned long) gadget_ld1_single_h); + else if (elem_size == 4) + gen(state, (unsigned long) gadget_ld1_single_s); + else + gen(state, (unsigned long) gadget_ld1_single_d); + } else { + if (elem_size == 1) + gen(state, (unsigned long) gadget_st1_single_b); + else if (elem_size == 2) + gen(state, (unsigned long) gadget_st1_single_h); + else if (elem_size == 4) + gen(state, (unsigned long) gadget_st1_single_s); + else + gen(state, (unsigned long) gadget_st1_single_d); + } + gen(state, vr | (lane_offset << 8)); + } + + // Post-index writeback + if (rm == 31) { + // Immediate: increment by total bytes (num_regs * elem_size) + gen(state, (unsigned long) gadget_update_base); + gen(state, rn | ((uint64_t)total_bytes << 8)); + } else { + // Register: increment by Xm + gen(state, (unsigned long) gadget_update_base_reg); + gen(state, rn | (rm << 8)); + } + return 1; + } + + (void)op0; + gen_interrupt(state, INT_UNDEFINED); + return 0; +} + +/* + * Data Processing (Register) + */ +static int gen_dp_reg(struct gen_state *state, uint32_t insn) { + uint32_t op0 = (insn >> 30) & 1; + uint32_t op1 = (insn >> 28) & 1; + uint32_t op2 = (insn >> 21) & 0xf; + + // Logical (shifted register) + if (op1 == 0 && (op2 & 0x8) == 0) { + uint32_t sf = (insn >> 31) & 1; + uint32_t opc = (insn >> 29) & 0x3; + uint32_t shift = (insn >> 22) & 0x3; + uint32_t N = (insn >> 21) & 1; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t imm6 = (insn >> 10) & 0x3f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + if (!sf && imm6 >= 32) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + // Handle shifted case for logical ops + if (shift != 0 || imm6 != 0) { + void *gadget = NULL; + switch (opc) { + case 0: gadget = gadget_and_reg_shifted; break; // AND/BIC + case 1: gadget = gadget_orr_reg_shifted; break; // ORR/ORN + case 2: gadget = gadget_eor_reg_shifted; break; // EOR/EON + case 3: gadget = gadget_and_reg_shifted; break; // ANDS/BICS + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen(state, (unsigned long) gadget); + // Pack: rd(0-4), rn(8-12), rm(16-20), sf(24), S(25), N(26), shift_type(27-28) + uint64_t param = rd | (rn << 8) | (rm << 16) | ((uint64_t)sf << 24) + | ((opc == 3) ? (1UL << 25) : 0) | ((uint64_t)N << 26) | ((uint64_t)shift << 27); + gen(state, param); + gen(state, imm6); // shift amount as second parameter + return 1; + } + + // Fast path: MOV Xd, Xm is ORR Xd, XZR, Xm (opc=1, N=0, rn=31) + if (opc == 1 && N == 0 && rn == 31 && rd != 31 && rm != 31) { + gen(state, (unsigned long)(sf ? gadget_mov_reg : gadget_mov_reg32)); + gen(state, rd | (rm << 16)); + return 1; + } + + // Fast path: EOR/ORR/AND Xd, Xn, Xn (rn==rm, N=0) → known result + // EOR: Xd = Xn ^ Xn = 0 (clear register) + // ORR: Xd = Xn | Xn = Xn (MOV) + // AND: Xd = Xn & Xn = Xn (MOV) + if (rn == rm && N == 0 && opc != 3) { + if (opc == 2 && rd != 31) { + // EOR Xd, Xn, Xn → Xd = 0 + gen(state, (unsigned long) gadget_movz); + gen(state, rd | (0 << 8) | (0ULL << 16) | ((uint64_t)sf << 32)); + return 1; + } + if ((opc == 0 || opc == 1) && rd != 31 && rn != 31) { + // AND/ORR Xd, Xn, Xn → Xd = Xn (MOV) + gen(state, (unsigned long)(sf ? gadget_mov_reg : gadget_mov_reg32)); + gen(state, rd | (rn << 16)); + return 1; + } + } + + void *gadget; + switch (opc) { + case 0: gadget = N ? gadget_and_reg : gadget_and_reg; break; // AND/BIC + case 1: gadget = N ? gadget_orr_reg : gadget_orr_reg; break; // ORR/ORN + case 2: gadget = N ? gadget_eor_reg : gadget_eor_reg; break; // EOR/EON + case 3: gadget = N ? gadget_and_reg : gadget_and_reg; break; // ANDS/BICS + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen(state, (unsigned long) gadget); + // Pack: rd(0-4), rn(8-12), rm(16-20), sf(24), S(25), N(26) + uint64_t param = rd | (rn << 8) | (rm << 16) | ((uint64_t)sf << 24) | ((opc == 3) ? (1UL << 25) : 0) | ((uint64_t)N << 26); + gen(state, param); + return 1; + } + + // Add/subtract (shifted register) + if (op1 == 0 && (op2 & 0x9) == 0x8) { + uint32_t sf = (insn >> 31) & 1; + uint32_t op = (insn >> 30) & 1; + uint32_t S = (insn >> 29) & 1; + uint32_t shift = (insn >> 22) & 0x3; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t imm6 = (insn >> 10) & 0x3f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + if (shift == 3) { + // shift == 3 is reserved for ADD/SUB shifted register + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + // imm6 validation: for 32-bit, imm6 must be < 32 + if (!sf && imm6 >= 32) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + // Try specialized 64-bit fast paths (no shift, no XZR operands) + bool can_spec_reg = sf && imm6 == 0 && rn != 31 && rm != 31; + if (can_spec_reg && S && op == 1) { + // Try fused SUBS_reg + B.cond + int fused = try_fuse_subs_reg_bcond(state, rd, rn, rm); + if (fused == 0) return 0; + } + if (can_spec_reg && S) { + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_fast_count); + gen(state, (unsigned long)(op ? gadget_subs_reg_64_nshift : gadget_adds_reg_64_nshift)); + gen(state, rd | (rn << 8) | (rm << 16)); + return 1; + } + if (can_spec_reg && !S && rd != 31) { + ARM64_FUSION_STAT_INC(arm64_fusion_addsub_fast_count); + gen(state, (unsigned long)(op ? gadget_sub_reg_64_nshift : gadget_add_reg_64_nshift)); + gen(state, rd | (rn << 8) | (rm << 16)); + return 1; + } + + // Generic path: handles 32-bit, shifted, XZR/SP cases + void *gadget; + if (S) { + // Flag-setting versions (ADDS, SUBS, CMP, CMN) + gadget = op ? gadget_subs_reg : gadget_adds_reg; + } else { + gadget = op ? gadget_sub_reg : gadget_add_reg; + } + gen(state, (unsigned long) gadget); + // Pack: rd | rn<<8 | rm<<16 | sf<<24 | S<<25 | shift_type<<26 | imm6<<32 + gen(state, rd | (rn << 8) | (rm << 16) | ((uint64_t)sf << 24) | ((uint64_t)S << 25) | ((uint64_t)shift << 26) | ((uint64_t)imm6 << 32)); + return 1; + } + + // Add/subtract (extended register) + // Pattern: sf:op:S:01011:00:1:Rm:option:imm3:Rn:Rd + if ((insn & 0x1f200000) == 0x0b200000) { + uint32_t sf = (insn >> 31) & 1; + uint32_t op = (insn >> 30) & 1; // 0=ADD, 1=SUB + uint32_t S = (insn >> 29) & 1; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t option = (insn >> 13) & 0x7; + uint32_t imm3 = (insn >> 10) & 0x7; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + // Select gadget based on op and S bits + void *gadget; + if (S) { + // Flag-setting versions (ADDS_ext, SUBS_ext, CMN_ext, CMP_ext) + gadget = op ? gadget_subs_ext : gadget_adds_ext; + } else { + gadget = op ? gadget_sub_ext : gadget_add_ext; + } + gen(state, (unsigned long) gadget); + // Pack: rd | rn<<8 | rm<<16 | option<<24 | imm3<<27 | sf<<30 + gen(state, rd | (rn << 8) | (rm << 16) | ((uint64_t)option << 24) | ((uint64_t)imm3 << 27) | ((uint64_t)sf << 30)); + return 1; + } + + // Add/subtract with carry (ADC/ADCS/SBC/SBCS) + // Pattern: sf:op:S:11010000:Rm:000000:Rn:Rd + // Mask: bits[28:21]=0xd0 and bits[15:10]=0x00 -> (insn & 0x1fe0fc00) == 0x1a000000 + if ((insn & 0x1fe0fc00) == 0x1a000000) { + uint32_t sf = (insn >> 31) & 1; + uint32_t op = (insn >> 30) & 1; // 0=ADC/ADCS, 1=SBC/SBCS + uint32_t S = (insn >> 29) & 1; // 1=update flags + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + void *gadget = op ? gadget_sbc_reg : gadget_adc_reg; + gen(state, (unsigned long) gadget); + // Pack: rd | rn<<8 | rm<<16 | sf<<24 | S<<25 + gen(state, rd | (rn << 8) | (rm << 16) | ((uint64_t)sf << 24) | ((uint64_t)S << 25)); + return 1; + } + + // Conditional compare (CCMP, CCMN) register/immediate + // Pattern: sf:op:S:11010010:Rm/imm5:cond:o2:0:Rn:0:nzcv + // bits[28:21]=0xd2, bit[29]=1 (S), bit[10]=0, bit[4]=0 + // bit 11 distinguishes register (0) vs immediate (1) form + if ((insn & 0x3fe00410) == 0x3a400000) { + uint32_t sf = (insn >> 31) & 1; + uint32_t op = (insn >> 30) & 1; // 0=CCMN, 1=CCMP + uint32_t is_imm = (insn >> 11) & 1; + uint32_t rm_or_imm5 = (insn >> 16) & 0x1f; + uint32_t cond = (insn >> 12) & 0xf; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t nzcv = insn & 0xf; + + void *gadget = NULL; + if (is_imm) { + gadget = op ? gadget_ccmp_imm : gadget_ccmn_imm; + } else { + gadget = op ? gadget_ccmp_reg : gadget_ccmn_reg; + } + gen(state, (unsigned long) gadget); + // Pack: rn | (rm/imm5)<<8 | cond<<16 | nzcv<<20 | sf<<24 + gen(state, rn | (rm_or_imm5 << 8) | (cond << 16) | (nzcv << 20) | ((uint64_t)sf << 24)); + return 1; + } + + // Conditional select (CSEL, CSINC, CSINV, CSNEG) + // Pattern: sf:op:S:11010100:Rm:cond:op2:Rn:Rd + // Mask out: sf, op, Rm, cond, op2, Rn, Rd - only check S=0 and fixed bits + if ((insn & 0x1fe00000) == 0x1a800000) { + uint32_t sf = (insn >> 31) & 1; + uint32_t op = (insn >> 30) & 1; + uint32_t S = (insn >> 29) & 1; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t cond = (insn >> 12) & 0xf; + uint32_t op2_sel = (insn >> 10) & 0x3; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + if (S != 0) { + // S must be 0 for conditional select + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget = NULL; + uint32_t variant = (op << 1) | op2_sel; + switch (variant) { + case 0: gadget = gadget_csel; break; // op=0, op2=0: CSEL + case 1: gadget = gadget_csinc; break; // op=0, op2=1: CSINC + case 2: gadget = gadget_csinv; break; // op=1, op2=0: CSINV + case 3: gadget = gadget_csneg; break; // op=1, op2=1: CSNEG + } + + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (rm << 16) | (cond << 24) | ((uint64_t)sf << 28)); + return 1; + } + + // Data-processing (2 source) + // Pattern: sf:0:S:11010110:Rm:opcode[5:0]:Rn:Rd + if ((insn & 0x5fe00000) == 0x1ac00000) { + uint32_t sf = (insn >> 31) & 1; + uint32_t S = (insn >> 29) & 1; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t opcode = (insn >> 10) & 0x3f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + if (S != 0) { + // S must be 0 for these instructions + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + // Try 64-bit fast path for shifts (sf=1, rd/rn/rm != 31) + bool shift_fast = sf && rd != 31 && rn != 31 && rm != 31; + if (shift_fast) { + void *fast = NULL; + switch (opcode) { + case 0x08: fast = gadget_lslv_64; break; + case 0x09: fast = gadget_lsrv_64; break; + case 0x0a: fast = gadget_asrv_64; break; + } + if (fast) { + gen(state, (unsigned long) fast); + gen(state, rd | (rn << 8) | (rm << 16)); + return 1; + } + } + + // Generic path + void *gadget = NULL; + switch (opcode) { + case 0x02: gadget = gadget_udiv; break; // UDIV + case 0x03: gadget = gadget_sdiv; break; // SDIV + case 0x08: gadget = gadget_lslv; break; // LSLV (LSL register) + case 0x09: gadget = gadget_lsrv; break; // LSRV (LSR register) + case 0x0a: gadget = gadget_asrv; break; // ASRV (ASR register) + case 0x0b: gadget = gadget_rorv; break; // RORV (ROR register) + case 0x10: gadget = gadget_crc32b; break; + case 0x11: gadget = gadget_crc32h; break; + case 0x12: gadget = gadget_crc32w; break; + case 0x13: if (!sf) { gen_interrupt(state, INT_UNDEFINED); return 0; } gadget = gadget_crc32x; break; + case 0x14: gadget = gadget_crc32cb; break; + case 0x15: gadget = gadget_crc32ch; break; + case 0x16: gadget = gadget_crc32cw; break; + case 0x17: if (!sf) { gen_interrupt(state, INT_UNDEFINED); return 0; } gadget = gadget_crc32cx; break; + default: + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen(state, (unsigned long) gadget); + // Pack: rd | rn<<8 | rm<<16 | sf<<24 + gen(state, rd | (rn << 8) | (rm << 16) | ((uint64_t)sf << 24)); + return 1; + } + + // Data-processing (1 source) + // Encoding: sf:1:S:11010110:opcode2:opcode:rn:rd + // op0 (bit 30) = 1 distinguishes from 2-source (op0=0) + // bits 28:21 = 11010110 = 0xd6, so op2 (bits 24:21) = 0x6 + if (op0 == 1 && op1 == 1 && op2 == 0x6) { + uint32_t sf = (insn >> 31) & 1; + uint32_t S = (insn >> 29) & 1; + uint32_t opcode2 = (insn >> 16) & 0x1f; + uint32_t opcode = (insn >> 10) & 0x3f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + // S must be 0 for valid 1-source instructions + if (S != 0 || opcode2 != 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void (*gadget)(void) = NULL; + + switch (opcode) { + case 0x00: // RBIT + gadget = gadget_rbit; + break; + case 0x01: // REV16 + gadget = gadget_rev16; + break; + case 0x02: // REV (32-bit) / REV32 (64-bit) + if (sf == 0) + gadget = gadget_rev; // REV for 32-bit + else + gadget = gadget_rev32; // REV32 for 64-bit (reverses 32-bit halves) + break; + case 0x03: // REV (64-bit only) + if (sf == 1) + gadget = gadget_rev; + break; + case 0x04: // CLZ + gadget = gadget_clz; + break; + case 0x05: // CLS + gadget = gadget_cls; + break; + default: + break; + } + + if (gadget == NULL) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen(state, (unsigned long) gadget); + // Pack: rd | rn<<8 | sf<<24 + gen(state, rd | (rn << 8) | ((uint64_t)sf << 24)); + return 1; + } + + // Data-processing (3 source) - MUL, MADD, MSUB, SMULL, UMULL, etc. + // Encoding: sf:0:op54:11011:op31:rm:o0:Ra:rn:rd + if (op1 == 1 && (op2 & 0x8) == 0x8) { + uint32_t sf = (insn >> 31) & 1; + uint32_t op54 = (insn >> 29) & 0x3; + uint32_t op31 = (insn >> 21) & 0x7; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t o0 = (insn >> 15) & 1; + uint32_t ra = (insn >> 10) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + void *gadget = NULL; + + if (op54 == 0) { + if (sf == 1 && op31 == 0) { + // 64-bit MADD/MSUB + gadget = o0 ? gadget_msub : gadget_madd; + } else if (sf == 0 && op31 == 0) { + // 32-bit MADD/MSUB + gadget = o0 ? gadget_msub : gadget_madd; + } else if (sf == 1 && op31 == 1) { + // SMADDL/SMSUBL (signed 32x32->64) + gadget = o0 ? gadget_smsubl : gadget_smaddl; + } else if (sf == 1 && op31 == 2) { + // SMULH (signed high multiply) + gadget = gadget_smulh; + // For SMULH, ra is not used but we still pack rd, rn, rm + } else if (sf == 1 && op31 == 5) { + // UMADDL/UMSUBL (unsigned 32x32->64) + gadget = o0 ? gadget_umsubl : gadget_umaddl; + } else if (sf == 1 && op31 == 6) { + // UMULH (unsigned high multiply) + gadget = gadget_umulh; + // For UMULH, ra is not used but we still pack rd, rn, rm + } + } + + if (gadget == NULL) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen(state, (unsigned long) gadget); + // Pack: rd | rn<<8 | rm<<16 | ra<<24 | sf<<29 + gen(state, rd | (rn << 8) | (rm << 16) | ((uint64_t)ra << 24) | ((uint64_t)sf << 29)); + return 1; + } + + (void)op0; + gen_interrupt(state, INT_UNDEFINED); + return 0; +} + +/* + * SIMD and Floating-Point + * + * This implements a minimal subset needed for musl's memset: + * - DUP Vd.16B, Wn (or Xn) + * - MOV Xd, Vn.D[0] + * - STR Qn, [Xbase, #imm] + * - STUR Qn, [Xbase, #imm] + * - STP Qn, Qm, [Xbase, #imm] + */ +static int gen_simd_fp(struct gen_state *state, uint32_t insn) { + // FMOV (immediate) - scalar floating-point immediate + // Pattern: 0b00011110 0/1 1 0 imm8 10000 Rd + // Mask 0xffa07fe0 ignores imm8 (bits 20-13), Rd (bits 4-0), and type (bit 22) + if ((insn & 0xffa07fe0) == 0x1e201000) { + uint32_t rd = insn & 0x1f; + bool is_double = (insn & 0x00400000) != 0; // type bit: 1=double, 0=single + uint8_t imm8_raw = (insn >> 13) & 0xff; + uint8_t imm8 = imm8_raw ^ 0x40; // Invert bit6 per ARM FP immediate encoding + uint64_t bits = arm64_fpimm_to_bits(is_double, imm8); + uint64_t lo = is_double ? bits : (uint64_t)(uint32_t)bits; + + gen(state, (unsigned long) gadget_set_vec_imm); + gen(state, rd); + gen(state, lo); + gen(state, 0); + return 1; + } + + // FMOV (register) - scalar FP register copy + // Matches: 0b00011110 type 1 00 0 0 0 0 0 Rn Rd (FMOV scalar) + // Mask 0xffbffc00 ignores Rn/Rd and type + if ((insn & 0xffbffc00) == 0x1e204000) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + bool is_double = (insn & 0x00400000) != 0; // type bit: 1=double, 0=single + gen(state, (unsigned long) gadget_fmov_fp_to_fp); + gen(state, rd | (rn << 8) | ((uint64_t)is_double << 16)); + return 1; + } + + // MOV/INS (element) - insert GPR into vector element (D size) + // Encoding: 0100_1110_000x_1000_0001_1100_Rn_Rd (MOV Vd.D[idx], Xn) + // imm5 = x1000 for D elements (bit 3 set, bits 2:0 clear), x = index + // Mask 0xffe0fc00 keeps bits 31:21 and 15:10 + // Also check bits 19:16 = 1000 (0x8) for D size + if ((insn & 0xffe0fc00) == 0x4e001c00 && ((insn >> 16) & 0xf) == 0x8) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t idx = (insn >> 20) & 0x1; // D element index (0 or 1) + gen(state, (unsigned long) gadget_ins_gpr_to_vec_d); + gen(state, rd | (rn << 8) | (idx << 16)); + return 1; + } + + // MOV/INS (element) - insert GPR into vector element (S size) + // Matches: 0b01001110 0001 1xx0 0001 1100 Rn Rd (MOV Vd.S[idx], Wn) + // Mask 0xffe7fc00 ignores Rd/Rn/index bits + if ((insn & 0xffe7fc00) == 0x4e041c00) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t idx = (insn >> 19) & 0x3; // S element index + gen(state, (unsigned long) gadget_ins_gpr_to_vec_s); + gen(state, rd | (rn << 8) | (idx << 16)); + return 1; + } + + // MOV/INS (general) - insert GPR into vector element (H size) + // imm5 bit pattern: xxx10 for H elements (bit 1 set, bit 0 clear) + // Encoding: 0100 1110 000 imm5 0 0011 1 Rn Rd, where imm5 & 3 == 2 + if ((insn & 0xffe0fc00) == 0x4e001c00 && ((insn >> 16) & 0x3) == 0x2) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t imm5 = (insn >> 16) & 0x1f; + uint32_t idx = (imm5 >> 2) & 0x7; // H element index (0..7) + gen(state, (unsigned long) gadget_ins_gpr_to_vec_h); + gen(state, rd | (rn << 8) | (idx << 16)); + return 1; + } + + // MOV/INS (general) - insert GPR into vector element (B size) + // imm5 bit pattern: xxxx1 for B elements (bit 0 set) + if ((insn & 0xffe0fc00) == 0x4e001c00 && ((insn >> 16) & 0x1) == 0x1) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t imm5 = (insn >> 16) & 0x1f; + uint32_t idx = (imm5 >> 1) & 0xf; // B element index (0..15) + gen(state, (unsigned long) gadget_ins_gpr_to_vec_b); + gen(state, rd | (rn << 8) | (idx << 16)); + return 1; + } + + // SHL (vector, immediate) - shift left immediate + // 0 Q U 0 1 1 1 1 0 immh immb 0 1 0 1 0 1 Rn Rd (U=0 for SHL) + // immh:immb encodes the shift and element size + // For 16B/8B (bytes): immh=0001, shift = immh:immb - 8 (0-7) + // For 8H/4H (halfwords): immh=001x, shift = immh:immb - 16 (0-15) + // For 4S/2S (words): immh=01xx, shift = immh:immb - 32 (0-31) + // For 2D/1D (doublewords): immh=1xxx, shift = immh:immb - 64 (0-63) + // Mask: 0xbf80fc00 keeps bit 31, U, bits 28-23, and opcode; Value: 0x0f005400 + // NOTE: immh must be non-zero for SHL; immh=0 encodes MOVI/MVNI instead + if ((insn & 0xbf80fc00) == 0x0f005400) { + uint32_t immh = (insn >> 19) & 0xf; + if (immh != 0) { + uint32_t Q = (insn >> 30) & 1; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + + // Determine element size and shift from immh + uint32_t esize, shift; + if (immh & 0x8) { // 64-bit + esize = 3; + shift = ((immh << 3) | immb) - 64; + } else if (immh & 0x4) { // 32-bit + esize = 2; + shift = ((immh << 3) | immb) - 32; + } else if (immh & 0x2) { // 16-bit + esize = 1; + shift = ((immh << 3) | immb) - 16; + } else { // 8-bit (immh & 0x1) + esize = 0; + shift = ((immh << 3) | immb) - 8; + } + + gen(state, (unsigned long) gadget_shl_imm_vec); + // Pack: rd | rn<<8 | shift<<16 | esize<<24 | Q<<28 + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24) | (Q << 28)); + return 1; + } + // Fall through to MOVI/MVNI handler when immh=0 + } + + // USHR (vector, immediate) - unsigned shift right immediate + // 0 Q U 0 1 1 1 1 0 immh immb 0 0 0 0 0 1 Rn Rd (U=1 for USHR) + // Mask: 0xbf80fc00, Value: 0x2f000400 + // NOTE: immh must be non-zero for USHR; immh=0 encodes MOVI/MVNI instead + if ((insn & 0xbf80fc00) == 0x2f000400) { + uint32_t immh = (insn >> 19) & 0xf; + // immh=0 is not a valid shift encoding - this is MOVI/MVNI, not USHR + if (immh != 0) { + uint32_t Q = (insn >> 30) & 1; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + + uint32_t esize, shift; + if (immh & 0x8) { + esize = 3; + shift = 128 - ((immh << 3) | immb); // USHR: shift = 2*esize - imm + } else if (immh & 0x4) { + esize = 2; + shift = 64 - ((immh << 3) | immb); + } else if (immh & 0x2) { + esize = 1; + shift = 32 - ((immh << 3) | immb); + } else { + esize = 0; + shift = 16 - ((immh << 3) | immb); + } + + gen(state, (unsigned long) gadget_ushr_imm_vec); + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24) | (Q << 28)); + return 1; + } + // Fall through to MOVI/MVNI handler when immh=0 + } + + // SSHR (vector, immediate) - signed shift right immediate + // 0 Q U 0 1 1 1 1 0 immh immb 0 0 0 0 0 1 Rn Rd (U=0 for SSHR) + // Mask: 0xbf80fc00, Value: 0x0f000400 + // IMPORTANT: immh must be non-zero for SSHR; immh=0 encodes MOVI/MVNI instead + if ((insn & 0xbf80fc00) == 0x0f000400) { + uint32_t immh = (insn >> 19) & 0xf; + // immh=0 is not a valid shift encoding - this is MOVI/MVNI, not SSHR + if (immh != 0) { + uint32_t Q = (insn >> 30) & 1; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + + uint32_t esize, shift; + if (immh & 0x8) { + esize = 3; + shift = 128 - ((immh << 3) | immb); + } else if (immh & 0x4) { + esize = 2; + shift = 64 - ((immh << 3) | immb); + } else if (immh & 0x2) { + esize = 1; + shift = 32 - ((immh << 3) | immb); + } else { + esize = 0; + shift = 16 - ((immh << 3) | immb); + } + + gen(state, (unsigned long) gadget_sshr_imm_vec); + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24) | (Q << 28)); + return 1; + } + // Fall through to MOVI/MVNI handler when immh=0 + } + + // USRA (vector, immediate) - unsigned shift right and accumulate + // 0 Q 1 0 1 1 1 1 0 immh immb 0 0 0 1 0 1 Rn Rd (U=1, opcode=00010) + // Mask: 0xbf80fc00, Value: 0x2f001400 + // NOTE: immh must be non-zero (immh=0 encodes other instructions) + if ((insn & 0xbf80fc00) == 0x2f001400) { + uint32_t immh = (insn >> 19) & 0xf; + if (immh != 0) { + uint32_t Q = (insn >> 30) & 1; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + + uint32_t esize, shift; + if (immh & 0x8) { + esize = 3; + shift = 128 - ((immh << 3) | immb); + } else if (immh & 0x4) { + esize = 2; + shift = 64 - ((immh << 3) | immb); + } else if (immh & 0x2) { + esize = 1; + shift = 32 - ((immh << 3) | immb); + } else { + esize = 0; + shift = 16 - ((immh << 3) | immb); + } + + gen(state, (unsigned long) gadget_usra_imm_vec); + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24) | (Q << 28)); + return 1; + } + // Fall through when immh=0 - might be another instruction + } + + // SSRA (vector, immediate) - signed shift right and accumulate + // 0 Q 0 0 1 1 1 1 0 immh immb 0 0 0 1 0 1 Rn Rd (U=0, opcode=00010) + // Mask: 0xbf80fc00, Value: 0x0f001400 + // NOTE: Like SSHR, immh must be non-zero (immh=0 encodes other instructions) + if ((insn & 0xbf80fc00) == 0x0f001400) { + uint32_t immh = (insn >> 19) & 0xf; + if (immh != 0) { + uint32_t Q = (insn >> 30) & 1; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + + uint32_t esize, shift; + if (immh & 0x8) { + esize = 3; + shift = 128 - ((immh << 3) | immb); + } else if (immh & 0x4) { + esize = 2; + shift = 64 - ((immh << 3) | immb); + } else if (immh & 0x2) { + esize = 1; + shift = 32 - ((immh << 3) | immb); + } else { + esize = 0; + shift = 16 - ((immh << 3) | immb); + } + + gen(state, (unsigned long) gadget_ssra_imm_vec); + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24) | (Q << 28)); + return 1; + } + } + + // SRSHR (vector, immediate) - signed rounding shift right + // 0 Q 0 01111 0 immh immb 00100 1 Rn Rd (U=0, opcode=00100) + // Mask: 0xbf80fc00, Value: 0x0f002400 + if ((insn & 0xbf80fc00) == 0x0f002400) { + uint32_t immh = (insn >> 19) & 0xf; + if (immh != 0) { + uint32_t Q = (insn >> 30) & 1; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t esize, shift; + if (immh & 0x8) { esize = 3; shift = 128 - ((immh << 3) | immb); } + else if (immh & 0x4) { esize = 2; shift = 64 - ((immh << 3) | immb); } + else if (immh & 0x2) { esize = 1; shift = 32 - ((immh << 3) | immb); } + else { esize = 0; shift = 16 - ((immh << 3) | immb); } + gen(state, (unsigned long) gadget_srshr_imm_vec); + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24) | (Q << 28)); + return 1; + } + } + + // URSHR (vector, immediate) - unsigned rounding shift right + // 0 Q 1 01111 0 immh immb 00100 1 Rn Rd (U=1, opcode=00100) + // Mask: 0xbf80fc00, Value: 0x2f002400 + if ((insn & 0xbf80fc00) == 0x2f002400) { + uint32_t immh = (insn >> 19) & 0xf; + if (immh != 0) { + uint32_t Q = (insn >> 30) & 1; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t esize, shift; + if (immh & 0x8) { esize = 3; shift = 128 - ((immh << 3) | immb); } + else if (immh & 0x4) { esize = 2; shift = 64 - ((immh << 3) | immb); } + else if (immh & 0x2) { esize = 1; shift = 32 - ((immh << 3) | immb); } + else { esize = 0; shift = 16 - ((immh << 3) | immb); } + gen(state, (unsigned long) gadget_urshr_imm_vec); + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24) | (Q << 28)); + return 1; + } + } + + // SRSRA (vector, immediate) - signed rounding shift right and accumulate + // 0 Q 0 01111 0 immh immb 00110 1 Rn Rd (U=0, opcode=00110) + // Mask: 0xbf80fc00, Value: 0x0f003400 + if ((insn & 0xbf80fc00) == 0x0f003400) { + uint32_t immh = (insn >> 19) & 0xf; + if (immh != 0) { + uint32_t Q = (insn >> 30) & 1; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t esize, shift; + if (immh & 0x8) { esize = 3; shift = 128 - ((immh << 3) | immb); } + else if (immh & 0x4) { esize = 2; shift = 64 - ((immh << 3) | immb); } + else if (immh & 0x2) { esize = 1; shift = 32 - ((immh << 3) | immb); } + else { esize = 0; shift = 16 - ((immh << 3) | immb); } + gen(state, (unsigned long) gadget_srsra_imm_vec); + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24) | (Q << 28)); + return 1; + } + } + + // URSRA (vector, immediate) - unsigned rounding shift right and accumulate + // 0 Q 1 01111 0 immh immb 00110 1 Rn Rd (U=1, opcode=00110) + // Mask: 0xbf80fc00, Value: 0x2f003400 + if ((insn & 0xbf80fc00) == 0x2f003400) { + uint32_t immh = (insn >> 19) & 0xf; + if (immh != 0) { + uint32_t Q = (insn >> 30) & 1; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t esize, shift; + if (immh & 0x8) { esize = 3; shift = 128 - ((immh << 3) | immb); } + else if (immh & 0x4) { esize = 2; shift = 64 - ((immh << 3) | immb); } + else if (immh & 0x2) { esize = 1; shift = 32 - ((immh << 3) | immb); } + else { esize = 0; shift = 16 - ((immh << 3) | immb); } + gen(state, (unsigned long) gadget_ursra_imm_vec); + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24) | (Q << 28)); + return 1; + } + } + + // SHRN/SHRN2 (vector, immediate) - shift right narrow + // 0 Q 0 01111 0 immh immb 10000 1 Rn Rd (U=0, opcode=10000) + // Mask: 0xbf80fc00, Value: 0x0f008400 + if ((insn & 0xbf80fc00) == 0x0f008400) { + uint32_t immh = (insn >> 19) & 0xf; + if (immh != 0) { + uint32_t Q = (insn >> 30) & 1; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t esize, shift; + if (immh & 0x4) { esize = 2; shift = 64 - ((immh << 3) | immb); } + else if (immh & 0x2) { esize = 1; shift = 32 - ((immh << 3) | immb); } + else { esize = 0; shift = 16 - ((immh << 3) | immb); } + gen(state, (unsigned long) gadget_shrn_vec); + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24) | (Q << 28)); + return 1; + } + } + + // RSHRN/RSHRN2 (vector, immediate) - rounding shift right narrow + // 0 Q 0 01111 0 immh immb 10001 1 Rn Rd (U=0, opcode=10001) + // Mask: 0xbf80fc00, Value: 0x0f008c00 + if ((insn & 0xbf80fc00) == 0x0f008c00) { + uint32_t immh = (insn >> 19) & 0xf; + if (immh != 0) { + uint32_t Q = (insn >> 30) & 1; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t esize, shift; + if (immh & 0x4) { esize = 2; shift = 64 - ((immh << 3) | immb); } + else if (immh & 0x2) { esize = 1; shift = 32 - ((immh << 3) | immb); } + else { esize = 0; shift = 16 - ((immh << 3) | immb); } + gen(state, (unsigned long) gadget_rshrn_vec); + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24) | (Q << 28)); + return 1; + } + } + + // Saturating shift-right-narrow instructions (shift-by-immediate) + // All use mask 0xbf80fc00, immh != 0 + // UQRSHRN: 0x2f009c00, SQRSHRN: 0x0f009c00 + // UQSHRN: 0x2f009400, SQSHRN: 0x0f009400 + // SQSHRUN: 0x2f008400, SQRSHRUN: 0x2f008c00 + { + uint32_t masked = insn & 0xbf80fc00; + void *sat_gadget = NULL; + if (masked == 0x2f009c00) sat_gadget = gadget_uqrshrn_vec; + else if (masked == 0x0f009c00) sat_gadget = gadget_sqrshrn_vec; + else if (masked == 0x2f009400) sat_gadget = gadget_uqshrn_vec; + else if (masked == 0x0f009400) sat_gadget = gadget_sqshrn_vec; + else if (masked == 0x2f008400) sat_gadget = gadget_sqshrun_vec; + else if (masked == 0x2f008c00) sat_gadget = gadget_sqrshrun_vec; + if (sat_gadget) { + uint32_t immh = (insn >> 19) & 0xf; + if (immh != 0) { + uint32_t Q = (insn >> 30) & 1; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t esize, shift; + if (immh & 0x4) { esize = 2; shift = 64 - ((immh << 3) | immb); } + else if (immh & 0x2) { esize = 1; shift = 32 - ((immh << 3) | immb); } + else { esize = 0; shift = 16 - ((immh << 3) | immb); } + gen(state, (unsigned long) sat_gadget); + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24) | (Q << 28)); + return 1; + } + } + } + + // SRI (vector, immediate) - shift right and insert + // 0 Q 1 01111 0 immh immb 01000 1 Rn Rd (U=1, opcode=01000) + // Mask: 0xbf80fc00, Value: 0x2f004400 + if ((insn & 0xbf80fc00) == 0x2f004400) { + uint32_t immh = (insn >> 19) & 0xf; + if (immh != 0) { + uint32_t Q = (insn >> 30) & 1; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + + uint32_t esize, shift; + if (immh & 0x8) { + esize = 3; + shift = 128 - ((immh << 3) | immb); + } else if (immh & 0x4) { + esize = 2; + shift = 64 - ((immh << 3) | immb); + } else if (immh & 0x2) { + esize = 1; + shift = 32 - ((immh << 3) | immb); + } else { + esize = 0; + shift = 16 - ((immh << 3) | immb); + } + + gen(state, (unsigned long) gadget_sri_imm_vec); + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24) | (Q << 28)); + return 1; + } + } + + // SLI (vector, immediate) - shift left and insert + // 0 Q 1 01111 0 immh immb 01010 1 Rn Rd (U=1, opcode=01010) + // Mask: 0xbf80fc00, Value: 0x2f005400 + if ((insn & 0xbf80fc00) == 0x2f005400) { + uint32_t immh = (insn >> 19) & 0xf; + if (immh != 0) { + uint32_t Q = (insn >> 30) & 1; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + + uint32_t esize, shift; + if (immh & 0x8) { + esize = 3; + shift = ((immh << 3) | immb) - 64; + } else if (immh & 0x4) { + esize = 2; + shift = ((immh << 3) | immb) - 32; + } else if (immh & 0x2) { + esize = 1; + shift = ((immh << 3) | immb) - 16; + } else { + esize = 0; + shift = ((immh << 3) | immb) - 8; + } + + gen(state, (unsigned long) gadget_sli_imm_vec); + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24) | (Q << 28)); + return 1; + } + } + + // SSHLL/USHLL/SSHLL2/USHLL2 (vector, immediate) - signed/unsigned shift left long + // Encoding: 0 Q U 011110 immh immb 10100 1 Rn Rd + // Mask 0x8f80fc00 checks bit31=0,bits[28:23]=011110,opcode=10100,bit10=1 + // Q at bit 30: 0=lower half (SSHLL/USHLL), 1=upper half (SSHLL2/USHLL2) + // U at bit 29 distinguishes signed/unsigned + // immh determines size: 0001=B->H, 001x=H->S, 01xx=S->D + if ((insn & 0x8f80fc00) == 0x0f00a400) { + uint32_t Q = (insn >> 30) & 1; + uint32_t U = (insn >> 29) & 1; + uint32_t immh = (insn >> 19) & 0xf; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + int immhb = (immh << 3) | immb; + int shift = 0; + void *gadget = NULL; + + if (immh & 0x4) { + // S->D: immh=01xx + shift = immhb - 32; + if (Q == 0) + gadget = U ? gadget_ushll_vec_s_to_d : gadget_sshll_vec_s_to_d; + else + gadget = U ? gadget_ushll2_vec_s_to_d : gadget_sshll2_vec_s_to_d; + } else if (immh & 0x2) { + // H->S: immh=001x + shift = immhb - 16; + if (Q == 0) + gadget = U ? gadget_ushll_vec_h_to_s : gadget_sshll_vec_h_to_s; + else + gadget = U ? gadget_ushll2_vec_h_to_s : gadget_sshll2_vec_h_to_s; + } else if (immh & 0x1) { + // B->H: immh=0001 + shift = immhb - 8; + if (Q == 0) + gadget = U ? gadget_ushll_vec_b_to_h : gadget_sshll_vec_b_to_h; + else + gadget = U ? gadget_ushll2_vec_b_to_h : gadget_sshll2_vec_b_to_h; + } + + if (gadget) { + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (shift << 16)); + return 1; + } + } + + // DUP (element) - duplicate vector element to vector + // Pattern: 0 Q 0 0 1 1 1 0 0 0 0 imm5 0 0 0 0 0 1 Rn Rd + // imm5[4:0] determines element size and index: + // xxxx1 = B, index = imm5[4:1] + // xxx10 = H, index = imm5[4:2] + // xx100 = S, index = imm5[4:3] + // x1000 = D, index = imm5[4] + if ((insn & 0xbfe0fc00) == 0x0e000400) { + uint32_t Q = (insn >> 30) & 1; + uint32_t imm5 = (insn >> 16) & 0x1f; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + + // Determine element size and index from imm5 + int elem_size = -1; + int index = 0; + if (imm5 & 0x1) { + elem_size = 0; // B + index = (imm5 >> 1) & 0xf; + } else if (imm5 & 0x2) { + elem_size = 1; // H + index = (imm5 >> 2) & 0x7; + } else if (imm5 & 0x4) { + elem_size = 2; // S + index = (imm5 >> 3) & 0x3; + } else if (imm5 & 0x8) { + elem_size = 3; // D + index = (imm5 >> 4) & 0x1; + } + + if (elem_size < 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen(state, (unsigned long) gadget_dup_elem_vec); + // Pack: rd | rn<<8 | elem_size<<16 | index<<20 | Q<<24 + gen(state, rd | (rn << 8) | (elem_size << 16) | (index << 20) | (Q << 24)); + return 1; + } + + // DUP (element, scalar) - duplicate vector element to scalar register + // Pattern: 01 0 11110 000 imm5 0 00001 Rn Rd + // Mask 0xffe0fc00 checks fixed bits, ignores imm5, Rn, Rd + if ((insn & 0xffe0fc00) == 0x5e000400) { + uint32_t imm5 = (insn >> 16) & 0x1f; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + + // Determine element size and index from imm5 + int elem_size = -1; + int index = 0; + if (imm5 & 0x1) { + elem_size = 0; // B + index = (imm5 >> 1) & 0xf; + } else if (imm5 & 0x2) { + elem_size = 1; // H + index = (imm5 >> 2) & 0x7; + } else if (imm5 & 0x4) { + elem_size = 2; // S + index = (imm5 >> 3) & 0x3; + } else if (imm5 & 0x8) { + elem_size = 3; // D + index = (imm5 >> 4) & 0x1; + } + + if (elem_size < 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen(state, (unsigned long) gadget_dup_elem_scalar); + // Pack: rd | rn<<8 | elem_size<<16 | index<<20 + gen(state, rd | (rn << 8) | (elem_size << 16) | (index << 20)); + return 1; + } + + // INS (element) - insert vector element into another vector element + // Pattern: 0 1 1 0 1 1 1 0 0 0 0 imm5 0 imm4 1 Rn Rd + // imm5 determines dst element size and index + // imm4 determines src element index + if ((insn & 0xffe08400) == 0x6e000400) { + uint32_t imm5 = (insn >> 16) & 0x1f; + uint32_t imm4 = (insn >> 11) & 0xf; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + + // Determine element size and indices + int elem_size = -1; + int dst_idx = 0; + int src_idx = 0; + if (imm5 & 0x1) { + elem_size = 0; // B + dst_idx = (imm5 >> 1) & 0xf; + src_idx = imm4 & 0xf; + } else if (imm5 & 0x2) { + elem_size = 1; // H + dst_idx = (imm5 >> 2) & 0x7; + src_idx = (imm4 >> 1) & 0x7; + } else if (imm5 & 0x4) { + elem_size = 2; // S + dst_idx = (imm5 >> 3) & 0x3; + src_idx = (imm4 >> 2) & 0x3; + } else if (imm5 & 0x8) { + elem_size = 3; // D + dst_idx = (imm5 >> 4) & 0x1; + src_idx = (imm4 >> 3) & 0x1; + } + + if (elem_size < 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen(state, (unsigned long) gadget_ins_elem_vec); + // Pack: rd | rn<<8 | elem_size<<16 | dst_idx<<20 | src_idx<<24 + gen(state, rd | (rn << 8) | (elem_size << 16) | (dst_idx << 20) | (src_idx << 24)); + return 1; + } + + // DUP (general) - duplicate general-purpose register to vector + // Pattern: 0 Q 0 0 1 1 1 0 0 0 0 imm5 0 0 0 0 1 1 Rn Rd + // imm5[4:0] determines element size: + // xxxxx1 = B (byte) + // xxxx10 = H (halfword) + // xxx100 = S (word) + // xx1000 = D (doubleword) + if ((insn & 0xbfe0fc00) == 0x0e000c00) { + uint32_t Q = (insn >> 30) & 1; + uint32_t imm5 = (insn >> 16) & 0x1f; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + + // Determine element size from imm5 + int elem_size = -1; + if (imm5 & 0x1) elem_size = 0; // B (byte) + else if (imm5 & 0x2) elem_size = 1; // H (halfword) + else if (imm5 & 0x4) elem_size = 2; // S (word) + else if (imm5 & 0x8) elem_size = 3; // D (doubleword) + + if (elem_size < 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + // Generate a general DUP gadget that takes element size as parameter + gen(state, (unsigned long) gadget_dup_gpr_to_vec); + gen(state, rd | (rn << 8) | (elem_size << 16) | (Q << 24)); + return 1; + } + + // UMOV/MOV (to general) - extract vector element to GPR + // For MOV Xd, Vn.D[0]: 0x4e083c00 | (Rn << 5) | Rd + // Pattern: 0Q001110 imm5 0 01111 Rn Rd + // Q=1, imm5[4:0]=01000 means D[0] + if ((insn & 0xffe0fc00) == 0x4e083c00) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + gen(state, (unsigned long) gadget_mov_v_to_gpr); + gen(state, rd | (rn << 8)); + return 1; + } + + // SMOV (to general) - extract vector element to GPR with sign extension + // Matches: 0Q001110 0imm5 0 01011 Rn Rd + if ((insn & 0xbfe0fc00) == 0x0e002c00) { + uint32_t Q = (insn >> 30) & 1; + uint32_t imm5 = (insn >> 16) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + int elem_size = -1; + if (imm5 & 0x1) elem_size = 0; // B + else if (imm5 & 0x2) elem_size = 1; // H + else if (imm5 & 0x4) elem_size = 2; // S + + if (elem_size < 0 || (elem_size == 2 && !Q)) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + uint32_t index = imm5 >> (elem_size + 1); + uint32_t max_elems = 16u >> elem_size; + if (index >= max_elems) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen(state, (unsigned long) gadget_umov_vec_to_gpr); + gen(state, rd | (rn << 8) | (elem_size << 16) | (index << 20)); + gen(state, (unsigned long) gadget_load_reg); + gen(state, rd); + if (elem_size == 0) { + gen(state, (unsigned long) gadget_sxtb); + gen(state, Q); + } else if (elem_size == 1) { + gen(state, (unsigned long) gadget_sxth); + gen(state, Q); + } else { + gen(state, (unsigned long) gadget_sxtw); + } + gen(state, (unsigned long) gadget_store_reg); + gen(state, rd); + return 1; + } + + // UMOV/MOV (to general) - extract vector element to GPR + // Matches: 0Q001110 0imm5 0 01111 Rn Rd (UMOV/MOV scalar from vector) + if ((insn & 0xbfe0fc00) == 0x0e003c00) { + uint32_t imm5 = (insn >> 16) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + int elem_size = -1; + if (imm5 & 0x1) elem_size = 0; // B + else if (imm5 & 0x2) elem_size = 1; // H + else if (imm5 & 0x4) elem_size = 2; // S + else if (imm5 & 0x8) elem_size = 3; // D + + if (elem_size < 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + uint32_t index = imm5 >> (elem_size + 1); + uint32_t max_elems = 16u >> elem_size; + if (index >= max_elems) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen(state, (unsigned long) gadget_umov_vec_to_gpr); + // Pack: rd | rn<<8 | elem_size<<16 | index<<20 + gen(state, rd | (rn << 8) | (elem_size << 16) | (index << 20)); + return 1; + } + + // STR (vector, immediate) - store 128-bit + // Pattern: 00111101 10 imm12 Rn Rt (scaled offset) + // Mask: check bits 31:30=00, 29:22=0x3d8 for Q variant + if ((insn & 0xffc00000) == 0x3d800000) { + uint32_t rt = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t imm12 = (insn >> 10) & 0xfff; + // Offset is imm12 * 16 for Q register + int64_t offset = (int64_t)imm12 * 16; + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (offset << 8)); + gen(state, (unsigned long) gadget_str_q); + gen(state, rt); + return 1; + } + + // STUR (vector, unscaled) - store 128-bit with unscaled offset + // Pattern: 00111100 10 0 imm9 00 Rn Rt + if ((insn & 0xffe00c00) == 0x3c800000) { + uint32_t rt = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + int32_t imm9 = ((int32_t)(insn >> 12) << 23) >> 23; // Sign-extend + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | ((int64_t)imm9 << 8)); + gen(state, (unsigned long) gadget_str_q); + gen(state, rt); + return 1; + } + + // STP (vector, signed offset) - store pair of 128-bit + // Pattern: 10101101 opc imm7 Rt2 Rn Rt + // opc=01 for signed offset + if ((insn & 0xffc00000) == 0xad000000) { + uint32_t rt = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rt2 = (insn >> 10) & 0x1f; + int32_t imm7 = ((int32_t)(insn >> 15) << 25) >> 25; // Sign-extend + // Offset is imm7 * 16 for Q registers + int64_t offset = (int64_t)imm7 * 16; + gen(state, (unsigned long) gadget_calc_addr_imm); + gen(state, rn | (offset << 8)); + gen(state, (unsigned long) gadget_stp_q); + gen(state, rt | (rt2 << 8)); + return 1; + } + + // MOVI/MVNI - Modified immediate (for zeroing vectors) + // Pattern: 0 Q op 0111100000 a b c cmode 01 d e f g h Rd + // For MOVI/MVNI with imm=0: the main variants are: + // Advanced SIMD modified immediate (MOVI/MVNI/ORR/BIC) + // Mask: 0x9ff80c00 - preserves bit 31, 28-19, 11-10; ignores Q(30), op(29), abc(18-16), cmode(15-12), defgh(9-5), Rd(4-0) + if ((insn & 0x9ff80c00) == 0x0f000400) { + uint32_t Q = (insn >> 30) & 1; + uint32_t op = (insn >> 29) & 1; // 0=MOVI/ORR, 1=MVNI/BIC (except for cmode=0xe/0xf) + uint32_t cmode = (insn >> 12) & 0xf; + uint32_t rd = insn & 0x1f; + + // Extract immediate from abc:defgh + uint32_t a = (insn >> 18) & 1; + uint32_t b = (insn >> 17) & 1; + uint32_t c = (insn >> 16) & 1; + uint32_t d = (insn >> 9) & 1; + uint32_t e = (insn >> 8) & 1; + uint32_t f = (insn >> 7) & 1; + uint32_t g = (insn >> 6) & 1; + uint32_t h = (insn >> 5) & 1; + uint8_t imm8 = (a << 7) | (b << 6) | (c << 5) | (d << 4) | (e << 3) | (f << 2) | (g << 1) | h; + + // Special handling for cmode=0xe/0xf with op=1: + // - cmode=0xe, op=1: MOVI with 64-bit element (byte expansion) + // - cmode=0xf, op=0: FMOV (immediate) + // - cmode=0xf, op=1: Reserved + if (cmode == 0xe && op == 1) { + // MOVI (64-bit scalar): Each bit of imm8 is expanded to a byte + // imm8 bit i (0-7) -> result byte i is 0xFF if set, 0x00 if clear + uint64_t elem64 = 0; + for (int i = 0; i < 8; i++) { + if (imm8 & (1 << i)) { + elem64 |= (0xFFULL << (i * 8)); + } + } + gen(state, (unsigned long) gadget_set_vec_imm); + gen(state, rd); + gen(state, elem64); // lo = expanded 64-bit value + gen(state, Q ? elem64 : 0); // hi = same if Q=1, else 0 + return 1; + } + + if (cmode == 0xf) { + // cmode=0xf: FMOV (immediate) for floating-point vectors + // VFPExpandImm expands imm8 to a FP constant at compile time. + if (op == 0) { + // FMOV single-precision: Vd.2S (Q=0) or Vd.4S (Q=1) + // VFPExpandImm for single: aBBBBBbcdefgh0..0 (32-bit) + uint32_t a = (imm8 >> 7) & 1; + uint32_t b = (imm8 >> 6) & 1; + uint32_t cdefgh = imm8 & 0x3f; + uint32_t exp = ((1 - b) << 7) | ((b * 0x1f) << 2) | ((cdefgh >> 4) & 3); + uint32_t frac = (cdefgh & 0xf) << 19; + uint32_t fp32 = (a << 31) | (exp << 23) | frac; + uint64_t elem64 = ((uint64_t)fp32 << 32) | fp32; + gen(state, (unsigned long) gadget_set_vec_imm); + gen(state, rd); + gen(state, elem64); + gen(state, Q ? elem64 : 0); + return 1; + } else { + // op=1: FMOV double-precision: Vd.2D (Q must be 1) + if (!Q) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + // VFPExpandImm for double: aBBBBBBBBbcdefgh0..0 (64-bit) + uint64_t a = (imm8 >> 7) & 1; + uint64_t b = (imm8 >> 6) & 1; + uint64_t cdefgh = imm8 & 0x3f; + uint64_t exp = ((1 - b) << 10) | ((b * 0xff) << 2) | ((cdefgh >> 4) & 3); + uint64_t frac = (cdefgh & 0xfULL) << 48; + uint64_t fp64 = (a << 63) | (exp << 52) | frac; + gen(state, (unsigned long) gadget_set_vec_imm); + gen(state, rd); + gen(state, fp64); + gen(state, fp64); + return 1; + } + } + + // ORR/BIC use odd cmode values for integer immediates (e.g., 0x1/0x3/0x5/0x7/0x9/0xb). + // MOVI/MVNI with MSL uses cmode=0xc (MSL #8) and 0xd (MSL #16). + bool is_orr_bic = ((cmode & 1) != 0) && (cmode != 0xd); + uint32_t base_cmode = is_orr_bic ? (cmode - 1) : cmode; + + uint64_t pattern = 0; + bool ok = false; + if (cmode == 0xc) { + // MOVI/MVNI (MSL #8): imm8 shifted left 8, low 8 bits set to ones + uint64_t elem = ((uint64_t)imm8 << 8) | 0xff; + pattern = elem | (elem << 32); + ok = true; + } else if (cmode == 0xd) { + // MOVI/MVNI (MSL #16): imm8 shifted left 16, low 16 bits set to ones + uint64_t elem = ((uint64_t)imm8 << 16) | 0xffff; + pattern = elem | (elem << 32); + ok = true; + } else { + ok = simd_modimm_pattern(base_cmode, imm8, &pattern); + } + if (!ok) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + uint64_t lo = pattern; + uint64_t hi = Q ? pattern : 0; + + if (!is_orr_bic) { + if (op) { + // MVNI: invert the pattern + lo = ~lo; + if (Q) hi = ~hi; + } + gen(state, (unsigned long) gadget_set_vec_imm); + gen(state, rd); + gen(state, lo); + gen(state, hi); + } else { + gen(state, (unsigned long) (op ? gadget_bic_imm_vec : gadget_orr_imm_vec)); + gen(state, rd | (Q << 8)); + gen(state, lo); + gen(state, hi); + } + return 1; + } + + // Note: LD1/ST1 instructions are now handled in gen_ldst() since they + // are classified as load/store instructions by arm64_classify_insn() + + // Advanced SIMD three same - vector arithmetic operations + // Pattern: 0 Q U 0 1 1 1 0 size 1 Rm opcode 1 Rn Rd + // Fixed bits: bit[31]=0, bits[28:24]=01110, bit[21]=1, bit[10]=1 + // Mask 0x9f200400 checks only fixed bits (excludes Q, U, size, Rm, opcode, Rn, Rd) + if ((insn & 0x9f200400) == 0x0e200400) { + uint32_t Q = (insn >> 30) & 1; + uint32_t U = (insn >> 29) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t opcode = (insn >> 11) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + void *gadget = NULL; + if (U == 0 && opcode == 0x00) { + // SHADD - Signed halving add + gadget = gadget_shadd_vec; + } else if (U == 1 && opcode == 0x00) { + // UHADD - Unsigned halving add + gadget = gadget_uhadd_vec; + } else if (U == 0 && opcode == 0x02) { + // SRHADD - Signed rounding halving add + gadget = gadget_srhadd_vec; + } else if (U == 1 && opcode == 0x02) { + // URHADD - Unsigned rounding halving add + gadget = gadget_urhadd_vec; + } else if (U == 0 && opcode == 0x08) { + // SSHL - Signed shift left (by register) + gadget = gadget_sshl_vec; + } else if (U == 1 && opcode == 0x08) { + // USHL - Unsigned shift left (by register) + gadget = gadget_ushl_vec; + } else if (U == 0 && opcode == 0x09) { + // SQSHL - Signed saturating shift left (by register) + gadget = gadget_sqshl_vec; + } else if (U == 1 && opcode == 0x09) { + // UQSHL - Unsigned saturating shift left (by register) + gadget = gadget_uqshl_vec; + } else if (U == 0 && opcode == 0x0a) { + // SRSHL - Signed rounding shift left (by register) + gadget = gadget_srshl_vec; + } else if (U == 1 && opcode == 0x0a) { + // URSHL - Unsigned rounding shift left (by register) + gadget = gadget_urshl_vec; + } else if (U == 0 && opcode == 0x0b) { + // SQRSHL - Signed saturating rounding shift left (by register) + gadget = gadget_sqrshl_vec; + } else if (U == 1 && opcode == 0x0b) { + // UQRSHL - Unsigned saturating rounding shift left (by register) + gadget = gadget_uqrshl_vec; + } else if (U == 0 && opcode == 0x10) { + // ADD - Vector add + if (size == 3 && Q == 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gadget = gadget_add_vec; + } else if (U == 1 && opcode == 0x10) { + // SUB - Vector subtract + if (size == 3 && Q == 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gadget = gadget_sub_vec; + } else if (U == 1 && opcode == 0x06) { + // CMHI - Compare higher (unsigned >) + gadget = gadget_cmhi_vec; + } else if (U == 1 && opcode == 0x07) { + // CMHS - Compare higher or same (unsigned >=) + gadget = gadget_cmhs_vec; + } else if (U == 1 && opcode == 0x11) { + // CMEQ - Compare equal + gadget = gadget_cmeq_vec; + } else if (U == 0 && opcode == 0x01) { + // SQADD - Signed saturating add + gadget = gadget_sqadd_vec; + } else if (U == 1 && opcode == 0x01) { + // UQADD - Unsigned saturating add + gadget = gadget_uqadd_vec; + } else if (opcode == 0x03) { + // Logic group: distinguished by U and size + if (U == 0) { + if (size == 0) gadget = gadget_and_vec; // AND + else if (size == 1) gadget = gadget_bic_vec; // BIC + else if (size == 2) gadget = gadget_orr_vec; // ORR + else gadget = gadget_orn_vec; // ORN + } else { + if (size == 0) gadget = gadget_eor_vec; // EOR + else if (size == 1) gadget = gadget_bsl_vec; // BSL + else if (size == 2) gadget = gadget_bit_vec; // BIT + else gadget = gadget_bif_vec; // BIF + } + } else if (U == 0 && opcode == 0x04) { + // SHSUB - Signed halving subtract (not for size=3) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_shsub_vec; + } else if (U == 1 && opcode == 0x04) { + // UHSUB - Unsigned halving subtract (not for size=3) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_uhsub_vec; + } else if (U == 0 && opcode == 0x05) { + // SQSUB - Signed saturating subtract + gadget = gadget_sqsub_vec; + } else if (U == 1 && opcode == 0x05) { + // UQSUB - Unsigned saturating subtract + gadget = gadget_uqsub_vec; + } else if (U == 0 && opcode == 0x06) { + // CMGT - Signed compare greater than (register) + gadget = gadget_cmgt_reg_vec; + } else if (U == 0 && opcode == 0x07) { + // CMGE - Signed compare greater or equal (register) + gadget = gadget_cmge_reg_vec; + } else if (U == 0 && opcode == 0x17) { + // ADDP - Add pairwise + gadget = gadget_addp_vec; + } else if (U == 1 && opcode == 0x14) { + // UMAXP - Unsigned maximum pairwise + gadget = gadget_umaxp_vec; + } else if (U == 1 && opcode == 0x15) { + // UMINP - Unsigned minimum pairwise + gadget = gadget_uminp_vec; + } else if (U == 0 && opcode == 0x14) { + // SMAXP - Signed maximum pairwise (not for size=3/D) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_smaxp_vec; + } else if (U == 0 && opcode == 0x15) { + // SMINP - Signed minimum pairwise (not for size=3/D) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_sminp_vec; + } else if (U == 0 && opcode == 0x16) { + // SQDMULH - Signed saturating doubling multiply high (H/S only) + if (size == 0 || size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_sqdmulh_vec; + } else if (U == 1 && opcode == 0x16) { + // SQRDMULH - Signed saturating rounding doubling multiply high (H/S only) + if (size == 0 || size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_sqrdmulh_vec; + } else if (U == 0 && opcode == 0x13) { + // MUL - Integer multiply (not for size=3/D) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_mul_vec; + } else if (U == 1 && opcode == 0x13) { + // PMUL - Polynomial multiply (size must be 0/bytes) + if (size != 0) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_pmul_vec; + } else if (U == 0 && opcode == 0x12) { + // MLA - Multiply-accumulate (not for size=3/D) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_mla_vec; + } else if (U == 1 && opcode == 0x12) { + // MLS - Multiply-subtract (not for size=3/D) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_mls_vec; + } else if (U == 0 && opcode == 0x0c) { + // SMAX - Signed maximum (not for size=3/D) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_smax_vec; + } else if (U == 1 && opcode == 0x0c) { + // UMAX - Unsigned maximum (not for size=3/D) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_umax_vec; + } else if (U == 0 && opcode == 0x0d) { + // SMIN - Signed minimum (not for size=3/D) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_smin_vec; + } else if (U == 1 && opcode == 0x0d) { + // UMIN - Unsigned minimum (not for size=3/D) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_umin_vec; + } else if (U == 0 && opcode == 0x0e) { + // SABD - Signed absolute difference (not for size=3/D) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_sabd_vec; + } else if (U == 1 && opcode == 0x0e) { + // UABD - Unsigned absolute difference (not for size=3/D) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_uabd_vec; + } else if (U == 0 && opcode == 0x0f) { + // SABA - Signed absolute difference accumulate (not for size=3/D) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_saba_vec; + } else if (U == 1 && opcode == 0x0f) { + // UABA - Unsigned absolute difference accumulate (not for size=3/D) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_uaba_vec; + } else if (U == 0 && opcode == 0x11) { + // CMTST - Compare bitwise test (Vn AND Vm != 0) + gadget = gadget_cmtst_vec; + } + + if (gadget) { + gen(state, (unsigned long) gadget); + // Pack: rd | rn<<8 | rm<<16 | size<<24 | Q<<26 + gen(state, rd | (rn << 8) | (rm << 16) | (size << 24) | (Q << 26)); + return 1; + } + + // FP vector three-same: opcodes 0x18-0x1f + // size[1] (bit[23]) = 'a' selects operation variant + // size[0] (bit[22]) = sz selects single(0)/double(1) precision + // Encoding table (ARM ARM C7.2): + // opc | U=0,a=0 | U=0,a=1 | U=1,a=0 | U=1,a=1 + // 0x18 | FMAXNM | FMINNM | - | - + // 0x19 | FMLA | FMLS | - | - + // 0x1a | FADD | FSUB | FADDP | FABD + // 0x1b | FMULX | - | FMUL | - + // 0x1c | FCMEQ | - | FCMGE | FCMGT + // 0x1d | - | - | FACGE | FACGT + // 0x1e | FMAX | FMIN | FMAXP | FMINP + // 0x1f | FRECPS | FRSQRTS | FDIV | - + if (opcode >= 0x18) { + uint32_t sz = size & 1; // 0=single, 1=double + uint32_t a = (size >> 1) & 1; // bit[23] + void *fp_gadget = NULL; + + if (opcode == 0x18 && !U) { + fp_gadget = a ? gadget_fp_fminnm_vec : gadget_fp_fmaxnm_vec; + } else if (opcode == 0x19 && !U) { + fp_gadget = a ? gadget_fp_fmls_vec : gadget_fp_fmla_vec; + } else if (opcode == 0x1a) { + if (!U) fp_gadget = a ? gadget_fp_fsub_vec : gadget_fp_fadd_vec; + else fp_gadget = a ? gadget_fp_fabd_vec : gadget_fp_faddp_vec; + } else if (opcode == 0x1b && !a) { + fp_gadget = U ? gadget_fp_fmul_vec : gadget_fp_fmulx_vec; + } else if (opcode == 0x1c) { + if (!U && !a) fp_gadget = gadget_fp_fcmeq_vec; + else if (U) fp_gadget = a ? gadget_fp_fcmgt_vec : gadget_fp_fcmge_vec; + } else if (opcode == 0x1d && U) { + fp_gadget = a ? gadget_fp_facgt_vec : gadget_fp_facge_vec; + } else if (opcode == 0x1e) { + if (!U) fp_gadget = a ? gadget_fp_fmin_vec : gadget_fp_fmax_vec; + else fp_gadget = a ? gadget_fp_fminp_vec : gadget_fp_fmaxp_vec; + } else if (opcode == 0x1f) { + if (!U) fp_gadget = a ? gadget_fp_frsqrts_vec : gadget_fp_frecps_vec; + else if (!a) fp_gadget = gadget_fp_fdiv_vec; + } + + if (fp_gadget) { + gen(state, (unsigned long) fp_gadget); + // Pack: rd | rn<<8 | rm<<16 | sz<<24 | Q<<26 + gen(state, rd | (rn << 8) | (rm << 16) | (sz << 24) | (Q << 26)); + return 1; + } + } + + // Unimplemented three-same NEON instruction — must not silently fall through + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + // AdvSIMD three different - widening/narrowing operations + // Pattern: 0 Q U 01110 size 1 Rm opcode 00 Rn Rd + // Fixed bits: bit[31]=0, bits[28:24]=01110, bit[21]=1, bits[11:10]=00 + // Mask: 0x9f200c00 checks fixed bits + if ((insn & 0x9f200c00) == 0x0e200000) { + uint32_t Q = (insn >> 30) & 1; + uint32_t U = (insn >> 29) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t opcode = (insn >> 12) & 0xf; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + void *gadget = NULL; + + // PMULL uses opcode=0xe, U=0 with size=0 (8B→8H) or size=3 (1D→1Q). + // These must skip three-different and fall through to the PMULL handler. + if (opcode == 0xe && U == 0 && (size == 0 || size == 3)) + goto skip_three_different; + + // Size 3 is reserved for most three-different instructions + if (size == 3) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + if (U == 0) { + switch (opcode) { + case 0x0: gadget = gadget_saddl_vec; break; // SADDL + case 0x1: gadget = gadget_saddw_vec; break; // SADDW + case 0x2: gadget = gadget_ssubl_vec; break; // SSUBL + case 0x3: gadget = gadget_ssubw_vec; break; // SSUBW + case 0x4: gadget = gadget_addhn_vec; break; // ADDHN + case 0x5: gadget = gadget_sabal_vec; break; // SABAL + case 0x6: gadget = gadget_subhn_vec; break; // SUBHN + case 0x7: gadget = gadget_sabdl_vec; break; // SABDL + case 0x8: gadget = gadget_smlal_vec; break; // SMLAL + case 0xa: gadget = gadget_smlsl_vec; break; // SMLSL + case 0xc: gadget = gadget_smull_vec; break; // SMULL + } + } else { + switch (opcode) { + case 0x0: gadget = gadget_uaddl_vec; break; // UADDL + case 0x1: gadget = gadget_uaddw_vec; break; // UADDW + case 0x2: gadget = gadget_usubl_vec; break; // USUBL + case 0x3: gadget = gadget_usubw_vec; break; // USUBW + case 0x4: gadget = gadget_raddhn_vec; break; // RADDHN + case 0x5: gadget = gadget_uabal_vec; break; // UABAL + case 0x6: gadget = gadget_rsubhn_vec; break; // RSUBHN + case 0x7: gadget = gadget_uabdl_vec; break; // UABDL + case 0x8: gadget = gadget_umlal_vec; break; // UMLAL + case 0xa: gadget = gadget_umlsl_vec; break; // UMLSL + case 0xc: gadget = gadget_umull_vec; break; // UMULL + } + } + + if (gadget) { + gen(state, (unsigned long) gadget); + // Pack: rd | rn<<8 | rm<<16 | size<<24 | Q<<26 + gen(state, rd | (rn << 8) | (rm << 16) | (size << 24) | (Q << 26)); + return 1; + } + // Unimplemented three-different NEON instruction — must not silently fall through + gen_interrupt(state, INT_UNDEFINED); + return 0; + } +skip_three_different: + + // XTN/XTN2 - narrow (vector) + // Matches: 0Q0011100ss10000 101000 Rn Rd (XTN/XTN2) + // Mask ignores Q to cover both XTN and XTN2. + if ((insn & 0xbf3ffc00) == 0x0e212800) { + uint32_t Q = (insn >> 30) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + if (size == 3) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gen(state, (unsigned long) gadget_xtn_vec); + // Pack: rd | rn<<8 | size<<16 | hi<<18 (hi=Q for XTN2) + gen(state, rd | (rn << 8) | (size << 16) | (Q << 18)); + return 1; + } + + // Permute instructions: UZP1, UZP2, TRN1, TRN2, ZIP1, ZIP2 + // Format: 0 Q 0 01110 size 0 Rm 0 op2 10 Rn Rd + // op2: 001=UZP1, 101=UZP2, 010=TRN1, 110=TRN2, 011=ZIP1, 111=ZIP2 + // Mask: 0xbf208c00, Value: 0x0e000800 + if ((insn & 0xbf208c00) == 0x0e000800) { + uint32_t Q = (insn >> 30) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t op2 = (insn >> 12) & 0x7; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + // size == 3 (64-bit elements) requires Q == 1 + if (size == 3 && Q == 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget = NULL; + switch (op2) { + case 1: gadget = gadget_uzp1_vec; break; // UZP1 + case 5: gadget = gadget_uzp2_vec; break; // UZP2 + case 2: gadget = gadget_trn1_vec; break; // TRN1 + case 6: gadget = gadget_trn2_vec; break; // TRN2 + case 3: gadget = gadget_zip1_vec; break; // ZIP1 + case 7: gadget = gadget_zip2_vec; break; // ZIP2 + } + + if (gadget) { + gen(state, (unsigned long) gadget); + // Pack: rd | rn<<8 | rm<<16 | size<<24 | Q<<26 + gen(state, rd | (rn << 8) | (rm << 16) | (size << 24) | (Q << 26)); + return 1; + } + } + + // UADDLP/SADDLP/UADALP/SADALP - Pairwise add long (two-reg misc) + // SADDLP: 0 Q 0 01110 size 10000 00010 10 Rn Rd (U=0, opcode=0x02) + // UADDLP: 0 Q 1 01110 size 10000 00010 10 Rn Rd (U=1, opcode=0x02) + // SADALP: 0 Q 0 01110 size 10000 00110 10 Rn Rd (U=0, opcode=0x06) + // UADALP: 0 Q 1 01110 size 10000 00110 10 Rn Rd (U=1, opcode=0x06) + if ((insn & 0xbf3ffc00) == 0x0e202800 || // SADDLP + (insn & 0xbf3ffc00) == 0x2e202800 || // UADDLP + (insn & 0xbf3ffc00) == 0x0e206800 || // SADALP + (insn & 0xbf3ffc00) == 0x2e206800) { // UADALP + uint32_t Q = (insn >> 30) & 1; + uint32_t U = (insn >> 29) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t opcode = (insn >> 12) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + if (size == 3) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget = NULL; + if (U == 0 && opcode == 0x02) gadget = gadget_saddlp_vec; + else if (U == 1 && opcode == 0x02) gadget = gadget_uaddlp_vec; + else if (U == 0 && opcode == 0x06) gadget = gadget_sadalp_vec; + else if (U == 1 && opcode == 0x06) gadget = gadget_uadalp_vec; + + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (size << 16) | (Q << 24)); + return 1; + } + + // SQXTUN/SQXTN/UQXTN - Saturating narrowing instructions (two-reg misc) + // Note: XTN is already handled by separate decoder above + // SQXTUN: 0 Q 1 01110 size 10000 10010 10 Rn Rd (U=1, opcode=0x12) + // SQXTN: 0 Q 0 01110 size 10000 10100 10 Rn Rd (U=0, opcode=0x14) + // UQXTN: 0 Q 1 01110 size 10000 10100 10 Rn Rd (U=1, opcode=0x14) + if ((insn & 0xbf3ffc00) == 0x2e212800 || // SQXTUN + (insn & 0xbf3ffc00) == 0x0e214800 || // SQXTN + (insn & 0xbf3ffc00) == 0x2e214800) { // UQXTN + uint32_t Q = (insn >> 30) & 1; + uint32_t U = (insn >> 29) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t opcode = (insn >> 12) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + // size=3 is reserved + if (size == 3) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget = NULL; + if (U == 1 && opcode == 0x12) gadget = gadget_sqxtun_vec; + else if (U == 0 && opcode == 0x14) gadget = gadget_sqxtn_vec; + else if (U == 1 && opcode == 0x14) gadget = gadget_uqxtn_vec; + + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (size << 16) | (Q << 24)); + return 1; + } + + // CMEQ with zero - pattern: 0 Q 0 0 1 1 1 0 size 1 0 0 0 0 0 10011 1 Rn Rd + // Binary: 0Q0_0111_0ss1_0000_0100_11Rn_nnRd_dddd + if ((insn & 0xbf3ffc00) == 0x0e209800) { + uint32_t Q = (insn >> 30) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + gen(state, (unsigned long) gadget_cmeq_zero_vec); + gen(state, rd | (rn << 8) | (size << 16) | (Q << 24)); + return 1; + } + + // CMGT/CMLT/CMGE/CMLE with zero - AdvSIMD two-register misc + // CMGT #0: 0 Q 0 01110 size 10000 01000 10 Rn Rd (U=0, opcode=01000) + // CMLT #0: 0 Q 0 01110 size 10000 01010 10 Rn Rd (U=0, opcode=01010) + // CMGE #0: 0 Q 1 01110 size 10000 01000 10 Rn Rd (U=1, opcode=01000) + // CMLE #0: 0 Q 1 01110 size 10000 01001 10 Rn Rd (U=1, opcode=01001) + if ((insn & 0xbf3ffc00) == 0x0e208800 || // CMGT #0 + (insn & 0xbf3ffc00) == 0x0e20a800 || // CMLT #0 + (insn & 0xbf3ffc00) == 0x2e208800 || // CMGE #0 + (insn & 0xbf3ffc00) == 0x2e209800) { // CMLE #0 + uint32_t Q = (insn >> 30) & 1; + uint32_t U = (insn >> 29) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t opcode = (insn >> 12) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + // size=3 (D) requires Q=1 + if (size == 3 && Q == 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget = NULL; + if (U == 0 && opcode == 0x08) gadget = gadget_cmgt_zero_vec; + else if (U == 0 && opcode == 0x0a) gadget = gadget_cmlt_zero_vec; + else if (U == 1 && opcode == 0x08) gadget = gadget_cmge_zero_vec; + else if (U == 1 && opcode == 0x09) gadget = gadget_cmle_zero_vec; + + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (size << 16) | (Q << 24)); + return 1; + } + + // ABS/NEG (vector) - AdvSIMD two-register misc + // ABS: 0 Q 0 01110 size 10000 01011 10 Rn Rd (U=0, opcode=0x0b) + // NEG: 0 Q 1 01110 size 10000 01011 10 Rn Rd (U=1, opcode=0x0b) + if ((insn & 0xbf3ffc00) == 0x0e20b800 || // ABS + (insn & 0xbf3ffc00) == 0x2e20b800) { // NEG + uint32_t Q = (insn >> 30) & 1; + uint32_t U = (insn >> 29) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + if (size == 3 && Q == 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget = (U == 0) ? gadget_abs_vec : gadget_neg_vec; + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (size << 16) | (Q << 24)); + return 1; + } + + // CLZ/CLS (vector) - AdvSIMD two-register misc + // CLS: 0 Q 0 01110 size 10000 00100 10 Rn Rd (U=0, opcode=0x04) + // CLZ: 0 Q 1 01110 size 10000 00100 10 Rn Rd (U=1, opcode=0x04) + // Only B/H/S sizes supported (size=3 is UNDEF) + if ((insn & 0xbf3ffc00) == 0x0e204800 || // CLS + (insn & 0xbf3ffc00) == 0x2e204800) { // CLZ + uint32_t Q = (insn >> 30) & 1; + uint32_t U = (insn >> 29) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + if (size == 3) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget = (U == 0) ? gadget_cls_vec : gadget_clz_vec; + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (size << 16) | (Q << 24)); + return 1; + } + + // NOT/RBIT (vector) - AdvSIMD two-register misc (bytes only) + // NOT: 0 Q 1 01110 00 10000 00101 10 Rn Rd (U=1, size=00, opcode=0x05) + // RBIT: 0 Q 1 01110 01 10000 00101 10 Rn Rd (U=1, size=01, opcode=0x05) + if ((insn & 0xbf3ffc00) == 0x2e205800) { // NOT (size=00) + uint32_t Q = (insn >> 30) & 1; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + gen(state, (unsigned long) gadget_not_vec); + gen(state, rd | (rn << 8) | (Q << 16)); + return 1; + } + if ((insn & 0xbf3ffc00) == 0x2e605800) { // RBIT (size=01) + uint32_t Q = (insn >> 30) & 1; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + gen(state, (unsigned long) gadget_rbit_vec); + gen(state, rd | (rn << 8) | (Q << 16)); + return 1; + } + + // AdvSIMD two-register misc: FP conversions, rounding, unary, compare-with-zero + // Format: 0 Q U 01110 size 10000 opcode 10 Rn Rd + // Mask 0xbfbbfc00 ignores Q(bit30) and sz(bit22), matches U+size[1]+opcode + // For FP ops: size[0]=sz selects precision (0=single, 1=double) + { + uint32_t Q = (insn >> 30) & 1; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + uint32_t sz = (insn >> 22) & 1; // precision: 0=single, 1=double + uint32_t base = insn & 0xbfbbfc00; // mask out Q and sz (keep size[1]=bit23) + void *gadget = NULL; + + // Integer to FP conversions (size[1]=0, opcode=0x1b) + if (base == 0x0e21d800) gadget = gadget_scvtf_int_vec; + else if (base == 0x2e21d800) gadget = gadget_ucvtf_int_vec; + // FP to integer conversions toward zero (size[1]=1, opcode=0x1b) + else if (base == 0x0ea1b800) gadget = gadget_fcvtzs_int_vec; + else if (base == 0x2ea1b800) gadget = gadget_fcvtzu_int_vec; + // FCVTN[SU] - nearest even (size[1]=0, opcode=0x0a) + else if (base == 0x0e21a800) gadget = gadget_fcvtns_int_vec; + else if (base == 0x2e21a800) gadget = gadget_fcvtnu_int_vec; + // FCVTM[SU] - toward -inf (size[1]=0, opcode=0x0b) + else if (base == 0x0e21b800) gadget = gadget_fcvtms_int_vec; + else if (base == 0x2e21b800) gadget = gadget_fcvtmu_int_vec; + // FCVTP[SU] - toward +inf (size[1]=1, opcode=0x0a) + else if (base == 0x0ea1a800) gadget = gadget_fcvtps_int_vec; + else if (base == 0x2ea1a800) gadget = gadget_fcvtpu_int_vec; + // FCVTA[SU] - ties away (size[1]=0, opcode=0x19) + else if (base == 0x0e21c800) gadget = gadget_fcvtas_int_vec; + else if (base == 0x2e21c800) gadget = gadget_fcvtau_int_vec; + // FRINT rounding variants + else if (base == 0x0e218800) gadget = gadget_frintn_vec_vec; + else if (base == 0x2e218800) gadget = gadget_frinta_vec_vec; + else if (base == 0x0ea18800) gadget = gadget_frintp_vec_vec; + else if (base == 0x0e219800) gadget = gadget_frintm_vec_vec; + else if (base == 0x2e219800) gadget = gadget_frintx_vec_vec; + else if (base == 0x0ea19800) gadget = gadget_frintz_vec_vec; + else if (base == 0x2ea19800) gadget = gadget_frinti_vec_vec; + // FP unary: FABS, FNEG, FSQRT, FRECPE, FRSQRTE (size[1]=1) + else if (base == 0x0ea0f800) gadget = gadget_fabs_vec_vec; + else if (base == 0x2ea0f800) gadget = gadget_fneg_vec_vec; + else if (base == 0x2ea1f800) gadget = gadget_fsqrt_vec_vec; + else if (base == 0x0ea1d800) gadget = gadget_frecpe_vec_vec; + else if (base == 0x2ea1d800) gadget = gadget_frsqrte_vec_vec; + // FP compare-with-zero (size[1]=1) + else if (base == 0x0ea0d800) gadget = gadget_fcmeq_zero_vec; + else if (base == 0x2ea0c800) gadget = gadget_fcmge_zero_vec; + else if (base == 0x0ea0c800) gadget = gadget_fcmgt_zero_vec; + else if (base == 0x2ea0d800) gadget = gadget_fcmle_zero_vec; + else if (base == 0x0ea0e800) gadget = gadget_fcmlt_zero_vec; + + if (gadget) { + // Double precision (.2d) requires Q=1 + if (sz == 1 && Q == 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (sz << 16) | (Q << 24)); + return 1; + } + } + + // FCVTN/FCVTN2 - floating-point narrow (two-register misc) + // FCVTN: 0 0 0 01110 size 10000 10110 10 Rn Rd + // FCVTN2: 0 1 0 01110 size 10000 10110 10 Rn Rd + // size=0: S->H, size=1: D->S; Q selects lower/upper destination half. + if ((insn & 0xbfbffc00) == 0x0e216800) { + uint32_t Q = (insn >> 30) & 1; + uint32_t size = (insn >> 22) & 0x1; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + gen(state, (unsigned long) gadget_fcvtn_vec); + gen(state, rd | (rn << 8) | (size << 16) | (Q << 24)); + return 1; + } + + // FCVTL/FCVTL2 - floating-point widen long (two-register misc) + // FCVTL: 0 0 0 01110 size 10000 10111 10 Rn Rd + // FCVTL2: 0 1 0 01110 size 10000 10111 10 Rn Rd + // size=0: H->S, size=1: S->D; size[1] must be 0. + if ((insn & 0xbfbffc00) == 0x0e217800) { + uint32_t Q = (insn >> 30) & 1; + uint32_t size = (insn >> 22) & 0x1; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + gen(state, (unsigned long) gadget_fcvtl_vec); + gen(state, rd | (rn << 8) | (size << 16) | (Q << 24)); + return 1; + } + + // FCVTXN/FCVTXN2 - double-to-single round-to-odd narrow conversion. + // Q=0 writes the lower half and zeros the upper half; Q=1 preserves the + // lower half and writes the converted lanes to the upper half. + if ((insn & 0xbffffc00) == 0x2e616800) { + uint32_t Q = (insn >> 30) & 1; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + gen(state, (unsigned long) gadget_fcvtxn_vec); + gen(state, rd | (rn << 8) | (Q << 24)); + return 1; + } + + // Integer CMEQ #0 (U=0, opcode=0x09) + if ((insn & 0xbf3ffc00) == 0x0e209800) { + uint32_t Q = (insn >> 30) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + if (size == 3 && Q == 0) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gen(state, (unsigned long) gadget_cmeq_zero_vec); + gen(state, rd | (rn << 8) | (size << 16) | (Q << 24)); + return 1; + } + + // SHLL/SHLL2 - Shift left long (by element size) - AdvSIMD two-register misc + // SHLL: 0 0 1 01110 size 10000 10011 10 Rn Rd (Q=0, U=1, opcode=0x13) + // SHLL2: 0 1 1 01110 size 10000 10011 10 Rn Rd (Q=1, U=1, opcode=0x13) + // Shift amount is fixed at element size (8/16/32), unlike USHLL which uses immediate + if ((insn & 0xbf3ffc00) == 0x2e213800) { + uint32_t Q = (insn >> 30) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + // size=3 is reserved + if (size == 3) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget = NULL; + if (size == 2) { + gadget = Q ? gadget_shll2_vec_s_to_d : gadget_shll_vec_s_to_d; + } else if (size == 1) { + gadget = Q ? gadget_shll2_vec_h_to_s : gadget_shll_vec_h_to_s; + } else { + gadget = Q ? gadget_shll2_vec_b_to_h : gadget_shll_vec_b_to_h; + } + + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8)); + return 1; + } + + // REV16 (vector) - reverse bytes in 16-bit elements + // 0 Q 0 01110 00 10000 00001 10 Rn Rd + if ((insn & 0xbf3ffc00) == 0x0e201800) { + uint32_t Q = (insn >> 30) & 1; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + gen(state, (unsigned long) gadget_rev16_vec); + gen(state, rd | (rn << 8) | (Q << 16)); + return 1; + } + + // REV32/REV64 (vector) - AdvSIMD two-register misc + // REV64: 0 Q 0 01110 size 10000 00000 10 Rn Rd (U=0, opcode=00000) + // REV32: 0 Q 1 01110 size 10000 00000 10 Rn Rd (U=1, opcode=00000) + // Binary: 0QuU_0111_0ss1_0000_0000_010R_nnnn_dddd + // Mask: 0xbf3ffc00 checks Q, U, fixed bits, size, opcode fields + // REV64: 0x0e200800 (U=0) + // REV32: 0x2e200800 (U=1) + if ((insn & 0xbf3ffc00) == 0x0e200800 || (insn & 0xbf3ffc00) == 0x2e200800) { + uint32_t Q = (insn >> 30) & 1; + uint32_t U = (insn >> 29) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + void *gadget = NULL; + if (U == 0) { + // REV64 - reverses bytes in 64-bit elements + // size must be < 3 (64-bit elements don't need REV64) + if (size >= 3) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gadget = gadget_rev64_vec; + } else { + // REV32 - reverses bytes in 32-bit elements + // size must be < 2 (32-bit elements need byte or halfword reversal) + if (size >= 2) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gadget = gadget_rev32_vec; + } + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (size << 16) | (Q << 24)); + return 1; + } + + // RBIT (vector) - reverse bits in each byte + // 0 Q 1 01110 sz 10000 00101 10 Rn Rd + // Mask 0xbf3ffc00 checks fixed bits, ignores Q, sz, Rn, Rd + // Value: sz must be 00 for .8B/.16B + if ((insn & 0xbf3ffc00) == 0x2e205800) { + uint32_t Q = (insn >> 30) & 1; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + gen(state, (unsigned long) gadget_rbit_vec); + gen(state, rd | (rn << 8) | (Q << 16)); + return 1; + } + + // ADDV (across lanes) - add all vector elements into scalar + // 0 Q U 01110 size 11000 1 10110 10 Rn Rd (U=0, opcode=11011) + // Mask: 0xbf3ffc00 checks fixed bits, Value: 0x0e31b800 + if ((insn & 0xbf3ffc00) == 0x0e31b800) { + uint32_t Q = (insn >> 30) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + // ADDV is not valid for size=3 (D), and 2S requires Q=1 + if (size == 3) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen(state, (unsigned long) gadget_addv_vec); + gen(state, rd | (rn << 8) | (size << 16) | (Q << 24)); + return 1; + } + + // SADDLV/UADDLV (across lanes) - signed/unsigned add long across vector + // 0 Q U 01110 size 11000 00011 10 Rn Rd + // SADDLV: U=0, UADDLV: U=1 + // Mask: 0x9f3ffc00 (ignore Q and U), Value: 0x0e303800 + if ((insn & 0x9f3ffc00) == 0x0e303800) { + uint32_t Q = (insn >> 30) & 1; + uint32_t U = (insn >> 29) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + // Not valid for size=3 (D) + if (size == 3) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + gen(state, (unsigned long) (U ? gadget_uaddlv_vec : gadget_saddlv_vec)); + gen(state, rd | (rn << 8) | (size << 16) | (Q << 24)); + return 1; + } + + // UMAXV/UMINV/SMAXV/SMINV (across lanes) - min/max reduction + // SMAXV: 0 Q 0 01110 size 11000 01010 10 Rn Rd (U=0, opcode=01010) + // SMINV: 0 Q 0 01110 size 11000 11010 10 Rn Rd (U=0, opcode=11010) + // UMAXV: 0 Q 1 01110 size 11000 01010 10 Rn Rd (U=1, opcode=01010) + // UMINV: 0 Q 1 01110 size 11000 11010 10 Rn Rd (U=1, opcode=11010) + if ((insn & 0xbf3ffc00) == 0x0e30a800 || // SMAXV + (insn & 0xbf3ffc00) == 0x0e31a800 || // SMINV + (insn & 0xbf3ffc00) == 0x2e30a800 || // UMAXV + (insn & 0xbf3ffc00) == 0x2e31a800) { // UMINV + uint32_t Q = (insn >> 30) & 1; + uint32_t U = (insn >> 29) & 1; + uint32_t size = (insn >> 22) & 0x3; + uint32_t opcode = (insn >> 12) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + // Not valid for size=3 (D) + if (size == 3) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget = NULL; + if (U == 0 && opcode == 0x0a) gadget = gadget_smaxv_vec; + else if (U == 0 && opcode == 0x1a) gadget = gadget_sminv_vec; + else if (U == 1 && opcode == 0x0a) gadget = gadget_umaxv_vec; + else if (U == 1 && opcode == 0x1a) gadget = gadget_uminv_vec; + + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (size << 16) | (Q << 24)); + return 1; + } + + // FMAXV/FMINV/FMAXNMV/FMINNMV (across lanes) - FP max/min reduction + // These only exist for .4s (Q=1, single precision) + // FMAXV: 0 1 1 01110 00 110000 11111 10 Rn Rd → 0x6e30f800 + // FMINV: 0 1 1 01110 10 110000 11111 10 Rn Rd → 0x6eb0f800 + // FMAXNMV: 0 1 1 01110 00 110000 01100 10 Rn Rd → 0x6e30c800 + // FMINNMV: 0 1 1 01110 10 110000 01100 10 Rn Rd → 0x6eb0c800 + // Mask 0xfffffc00 (exact match since Q=1 always) + if ((insn & 0xfffffc00) == 0x6e30f800 || + (insn & 0xfffffc00) == 0x6eb0f800 || + (insn & 0xfffffc00) == 0x6e30c800 || + (insn & 0xfffffc00) == 0x6eb0c800) { + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + uint32_t base_val = insn & 0xfffffc00; + void *gadget = NULL; + if (base_val == 0x6e30f800) gadget = gadget_fmaxv_vec; + else if (base_val == 0x6eb0f800) gadget = gadget_fminv_vec; + else if (base_val == 0x6e30c800) gadget = gadget_fmaxnmv_vec; + else gadget = gadget_fminnmv_vec; + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8)); + return 1; + } + + // CNT (vector) - count set bits per byte + // 0 Q 0 01110 size 10000 00101 10 Rn Rd (U=0, opcode=00101) + // Same as RBIT but U=0 instead of U=1; size must be 00 + // Mask 0xbf3ffc00, Value: 0x0e205800 + if ((insn & 0xbf3ffc00) == 0x0e205800) { + uint32_t Q = (insn >> 30) & 1; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + gen(state, (unsigned long) gadget_cnt_vec); + gen(state, rd | (rn << 8) | (Q << 16)); + return 1; + } + + // Floating-point/integer conversion (scalar) + // UCVTF/SCVTF/FCVTZU/FCVTZS + // Pattern: sf 0 0 1 1 1 1 0 type 1 rmode opcode 0 0 0 0 0 0 Rn Rd + // Fixed bits: 30-29=00, 28-24=11110, 21=1, 15-10=000000 + // Mask: 0x7f20fc00 checks fixed bits + if ((insn & 0x7f20fc00) == 0x1e200000) { + uint32_t sf = (insn >> 31) & 1; + uint32_t type = (insn >> 22) & 3; + uint32_t rmode = (insn >> 19) & 3; + uint32_t opcode = (insn >> 16) & 7; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + + void *gadget = NULL; + if (rmode == 0 && opcode == 3) { + // UCVTF - unsigned int to float + gadget = gadget_ucvtf_scalar; + } else if (rmode == 0 && opcode == 2) { + // SCVTF - signed int to float + gadget = gadget_scvtf_scalar; + } else if (rmode == 3 && opcode == 1) { + // FCVTZU - float to unsigned int (round toward zero) + gadget = gadget_fcvtzu_scalar; + } else if (rmode == 3 && opcode == 0) { + // FCVTZS - float to signed int (round toward zero) + gadget = gadget_fcvtzs_scalar; + } else if (rmode == 0 && opcode == 0) { + // FCVTNS - float to signed int (round to nearest, ties to even) + gadget = gadget_fcvtns_scalar; + } else if (rmode == 0 && opcode == 1) { + // FCVTNU - float to unsigned int (round to nearest) + gadget = gadget_fcvtnu_scalar; + } else if (rmode == 1 && opcode == 0) { + // FCVTPS - float to signed int (round toward +inf) + gadget = gadget_fcvtps_scalar; + } else if (rmode == 1 && opcode == 1) { + // FCVTPU - float to unsigned int (round toward +inf) + gadget = gadget_fcvtpu_scalar; + } else if (rmode == 2 && opcode == 0) { + // FCVTMS - float to signed int (round toward -inf) + gadget = gadget_fcvtms_scalar; + } else if (rmode == 2 && opcode == 1) { + // FCVTMU - float to unsigned int (round toward -inf) + gadget = gadget_fcvtmu_scalar; + } else if (rmode == 0 && opcode == 4) { + // FCVTAS - float to signed int (round to nearest, ties to away) + gadget = gadget_fcvtas_scalar; + } else if (rmode == 0 && opcode == 5) { + // FCVTAU - float to unsigned int (round to nearest, ties to away) + gadget = gadget_fcvtau_scalar; + } else if (rmode == 0 && opcode == 6) { + // FMOV - move bits from FP register to GPR (opcode bit 0 = 0) + gadget = gadget_fmov_fp_to_gpr; + } else if (rmode == 0 && opcode == 7) { + // FMOV - move bits from GPR to FP register (opcode bit 0 = 1) + gadget = gadget_fmov_gpr_to_fp; + } else if (rmode == 1 && opcode == 6 && type == 2 && sf == 1) { + // FMOV - move bits from vector upper D lane to GPR (Vn.D[1] -> Xd) + gadget = gadget_fmov_fp_to_gpr_hi; + } else if (rmode == 1 && opcode == 7 && type == 2 && sf == 1) { + // FMOV - move bits from GPR to vector upper D lane (Xd -> Vd.D[1]) + gadget = gadget_fmov_gpr_to_fp_hi; + } + + if (gadget) { + gen(state, (unsigned long) gadget); + // Pack: rd | rn<<8 | type<<16 | sf<<18 + gen(state, rd | (rn << 8) | (type << 16) | (sf << 18)); + return 1; + } + } + + // FCVTZS/FCVTZU/SCVTF/UCVTF (scalar, fixed-point, GPR <-> FP) + // Encoding: sf 0 0 11110 type 0 rmode opcode scale Rn Rd + // This is the GPR-to/from-FP fixed-point conversion (NOT the SIMD scalar form) + // rmode=11, opcode=000 -> FCVTZS; rmode=11, opcode=001 -> FCVTZU + // rmode=00, opcode=010 -> SCVTF; rmode=00, opcode=011 -> UCVTF + // scale = 64 - fbits (sf=1) or 32 - fbits (sf=0) + // Mask: 0x7f200000 checks bits 30:29=00, 28:24=11110, 21=0 + if ((insn & 0x7f200000) == 0x1e000000) { + uint32_t sf = (insn >> 31) & 1; + uint32_t type = (insn >> 22) & 3; + uint32_t rmode = (insn >> 19) & 3; + uint32_t opcode = (insn >> 16) & 7; + uint32_t scale = (insn >> 10) & 0x3f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + if (type <= 1) { + uint32_t fbits = 64 - scale; + void *gadget = NULL; + if (rmode == 3 && opcode == 0) { + gadget = gadget_fcvtzs_fixpt_gpr; // FCVTZS Wd/Xd, Sn/Dn, #fbits + } else if (rmode == 3 && opcode == 1) { + gadget = gadget_fcvtzu_fixpt_gpr; // FCVTZU Wd/Xd, Sn/Dn, #fbits + } else if (rmode == 0 && opcode == 2) { + gadget = gadget_scvtf_fixpt_gpr; // SCVTF Sd/Dd, Wn/Xn, #fbits + } else if (rmode == 0 && opcode == 3) { + gadget = gadget_ucvtf_fixpt_gpr; // UCVTF Sd/Dd, Wn/Xn, #fbits + } + + if (gadget) { + gen(state, (unsigned long) gadget); + // Pack: rd | rn<<8 | type<<16 | sf<<18 | fbits<<20 + gen(state, rd | (rn << 8) | (type << 16) | (sf << 18) | (fbits << 20)); + return 1; + } + } + } + + // FMOV (scalar, immediate) - load FP constant + // Encoding: 000 11110 ftype 1 imm8 100 00000 Rd + // ftype: 00=S, 01=D + // Mask 0xff201fe0 checks fixed bits, ignores ftype, imm8, Rd + if ((insn & 0xff201fe0) == 0x1e201000) { + uint32_t ftype = (insn >> 22) & 3; + uint32_t imm8 = (insn >> 13) & 0xff; + uint32_t rd = insn & 0x1f; + bool is_double = (ftype == 1); + + uint64_t fpbits = arm64_fpimm_to_bits(is_double, imm8); + + gen(state, (unsigned long) gadget_fmov_fp_imm); + gen(state, rd | (ftype << 8)); + // Emit the 64-bit FP value as a single unsigned long + gen(state, (unsigned long) fpbits); + return 1; + } + + // FCMP/FCMPE (scalar) + // Register form: 000 11110 type 1 Rm 00 1000 Rn 0 opc 000 (bit 3 = 0) + // Zero form: 000 11110 type 1 Rm 00 1000 Rn 1 opc 000 (bit 3 = 1) + // Mask 0xff20fc17 checks fixed bits including bit 4 (part of opc) + // Bit 3 distinguishes register (0) from zero (1) comparison + if ((insn & 0xff20fc00) == 0x1e202000) { + uint32_t type = (insn >> 22) & 3; + uint32_t rn = (insn >> 5) & 0x1f; + if (type > 1) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + if (insn & 0x08) { + // Bit 3 set: FCMP/FCMPE with zero + gen(state, (unsigned long) gadget_fcmp_zero_scalar); + // Pack: rn | type<<16 + gen(state, rn | (type << 16)); + } else { + // Bit 3 clear: FCMP/FCMPE with register + uint32_t rm = (insn >> 16) & 0x1f; + gen(state, (unsigned long) gadget_fcmp_scalar); + // Pack: rn | rm<<8 | type<<16 + gen(state, rn | (rm << 8) | (type << 16)); + } + return 1; + } + + // FCCMP/FCCMPE - Floating-point conditional compare + // Encoding: 0 0 0 11110 ftype 1 Rm cond 01 Rn op nzcv + // Mask 0xff200c00 checks M,S,fixed,bit21; bits 11:10=01 + if ((insn & 0xff200c00) == 0x1e200400) { + uint32_t ftype = (insn >> 22) & 3; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t cond = (insn >> 12) & 0xf; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t nzcv = insn & 0xf; + if (ftype > 1) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gen(state, (unsigned long) gadget_fccmp_scalar); + // Pack: rn | rm<<8 | ftype<<16 | cond<<20 | nzcv<<24 + gen(state, rn | (rm << 8) | (ftype << 16) | (cond << 20) | (nzcv << 24)); + return 1; + } + + // FCSEL - Floating-point conditional select + // Encoding: 0 0 0 11110 ftype 1 Rm cond 11 Rn Rd + // Mask 0xff200c00 checks M,S,fixed,bit21; bits 11:10=11 + if ((insn & 0xff200c00) == 0x1e200c00) { + uint32_t ftype = (insn >> 22) & 3; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t cond = (insn >> 12) & 0xf; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + if (ftype > 1) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + gen(state, (unsigned long) gadget_fcsel_scalar); + // Pack two words: [rd | rn<<8 | rm<<16 | ftype<<24] [cond] + gen(state, rd | (rn << 8) | (rm << 16) | (ftype << 24)); + gen(state, cond); + return 1; + } + + // Floating-point data-processing (1 source), scalar + // Pattern: M=0 S=0 1 1 1 1 0 ftype 1 opcode 10000 Rn Rd + // Mask 0xff207c00: M,S,fixed,ftype,bit21,bits14:10=10000 + if ((insn & 0xff207c00) == 0x1e204000) { + uint32_t ftype = (insn >> 22) & 3; + uint32_t opcode = (insn >> 15) & 0x3f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + // Validate: ftype 0=single, 1=double; opcode must be valid + // We handle all common single/double dp1 ops via a generic gadget that + // re-executes the instruction natively on the host (with emulated FP + // reg operands). Zig probes scalar FP16 conversion through FCVT Sd,Hn, + // so keep that one half-precision form explicit. + if (ftype <= 1 && opcode <= 15) { + gen(state, (unsigned long) gadget_fp_dp1); + // Pack: rd | rn<<8 | ftype<<16 | opcode<<20 + gen(state, rd | (rn << 8) | (ftype << 16) | (opcode << 20)); + return 1; + } + if (ftype == 3 && opcode == 4) { + gen(state, (unsigned long) gadget_fcvt_h_to_s_scalar); + gen(state, rd | (rn << 8)); + return 1; + } + if (ftype == 3 && opcode == 5) { + gen(state, (unsigned long) gadget_fcvt_h_to_d_scalar); + gen(state, rd | (rn << 8)); + return 1; + } + } + + // Floating-point data-processing (2 source), scalar + // Pattern: M=0 S=0 1 1 1 1 0 type 1 Rm opcode 10 Rn Rd + // Mask 0xff20c000 checks M,S,fixed,bit21; bits 15:12 = opcode + if ((insn & 0xff200000) == 0x1e200000 && ((insn >> 10) & 3) == 2) { + uint32_t type = (insn >> 22) & 3; + uint32_t opcode = (insn >> 12) & 0xf; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + if (type > 1) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget = NULL; + switch (opcode) { + case 0x0: gadget = gadget_fmul_scalar; break; // FMUL + case 0x1: gadget = gadget_fdiv_scalar; break; // FDIV + case 0x2: gadget = gadget_fadd_scalar; break; // FADD + case 0x3: gadget = gadget_fsub_scalar; break; // FSUB + case 0x4: gadget = gadget_fmax_scalar; break; // FMAX + case 0x5: gadget = gadget_fmin_scalar; break; // FMIN + case 0x6: gadget = gadget_fmaxnm_scalar; break; // FMAXNM + case 0x7: gadget = gadget_fminnm_scalar; break; // FMINNM + case 0x8: gadget = gadget_fnmul_scalar; break; // FNMUL + default: break; + } + + if (gadget) { + gen(state, (unsigned long) gadget); + // Pack: rd | rn<<8 | rm<<16 | type<<24 + gen(state, rd | (rn << 8) | (rm << 16) | (type << 24)); + return 1; + } + } + + // Floating-point data-processing (3 source) - FMADD/FMSUB/FNMADD/FNMSUB + // Pattern: M=0 S=0 1 1 1 1 1 ftype o1 Rm o0 Ra Rn Rd + // ftype: 00=single, 01=double + // o1:o0 = 00: FMADD (Fd = Fn * Fm + Fa) + // = 01: FMSUB (Fd = Fn * Fm - Fa) + // = 10: FNMADD (Fd = -(Fn * Fm) - Fa) + // = 11: FNMSUB (Fd = -(Fn * Fm) + Fa) + if ((insn & 0x5f000000) == 0x1f000000) { + uint32_t M = (insn >> 31) & 1; + uint32_t S = (insn >> 29) & 1; + uint32_t ftype = (insn >> 22) & 3; + uint32_t o1 = (insn >> 21) & 1; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t o0 = (insn >> 15) & 1; + uint32_t ra = (insn >> 10) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + // M and S must be 0 for scalar FP data-processing (3 source) + if (M != 0 || S != 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + // Only single (ftype=0) and double (ftype=1) precision supported + if (ftype > 1) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + uint32_t op = (o1 << 1) | o0; + void *gadget = NULL; + switch (op) { + case 0: gadget = gadget_fmadd_scalar; break; + case 1: gadget = gadget_fmsub_scalar; break; + case 2: gadget = gadget_fnmadd_scalar; break; + case 3: gadget = gadget_fnmsub_scalar; break; + } + + gen(state, (unsigned long) gadget); + // Pack: rd | rn<<8 | rm<<16 | ra<<24 + gen(state, rd | (rn << 8) | (rm << 16) | (ra << 24)); + // ftype as second word + gen(state, ftype); + return 1; + } + + // TBL/TBX - Table lookup + // TBL: 0 Q 00 1110 000 Rm 0 len 0 0 Rn Rd + // TBX: 0 Q 00 1110 000 Rm 0 len 1 0 Rn Rd + // Mask: 0xbfe08c00 = 1011_1111_1110_0000_1000_1100_0000_0000 + // Value: 0x0e000000 + if ((insn & 0xbfe08c00) == 0x0e000000) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t op = (insn >> 12) & 0x1; // 0=TBL, 1=TBX + uint32_t len = (insn >> 13) & 0x3; // table size: 0=1reg, 1=2reg, 2=3reg, 3=4reg + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t Q = (insn >> 30) & 0x1; // 0=64-bit, 1=128-bit + + void *gadget = op ? gadget_tbx : gadget_tbl; + gen(state, (unsigned long) gadget); + // Pack: rd | rn<<8 | rm<<16 | len<<24 | Q<<28 + gen(state, rd | (rn << 8) | (rm << 16) | (len << 24) | (Q << 28)); + return 1; + } + + // EXT - Extract from pair of vectors + // 0 Q 10 1110 00 0 Rm 0 imm4 0 Rn Rd + // Mask: 0xbfe08400 Value: 0x2e000000 + if ((insn & 0xbfe08400) == 0x2e000000) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t imm4 = (insn >> 11) & 0xf; // byte index + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t Q = (insn >> 30) & 0x1; // 0=8B, 1=16B + + gen(state, (unsigned long) gadget_ext_vec); + // Pack: rd | rn<<8 | rm<<16 | imm4<<24 | Q<<28 + gen(state, rd | (rn << 8) | (rm << 16) | (imm4 << 24) | (Q << 28)); + return 1; + } + + // Cryptographic AES instructions + // AESE/AESD/AESMC/AESIMC: 0100_1110_0010_1000_opcode_10_Rn_Rd + // AESE: 0x4e284800 (opcode=0100) + // AESD: 0x4e285800 (opcode=0101) + // AESMC: 0x4e286800 (opcode=0110) + // AESIMC: 0x4e287800 (opcode=0111) + // Mask 0xff3f0c00 keeps bits 31:22, 11:10, ignores opcode (15:12), Rn, Rd + if ((insn & 0xff3f0c00) == 0x4e280800) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t opcode = (insn >> 12) & 0xf; + + void *gadget = NULL; + switch (opcode) { + case 4: gadget = gadget_aese; break; // 0100 -> AESE + case 5: gadget = gadget_aesd; break; // 0101 -> AESD + case 6: gadget = gadget_aesmc; break; // 0110 -> AESMC + case 7: gadget = gadget_aesimc; break; // 0111 -> AESIMC + } + if (gadget) { + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8)); + return 1; + } + } + + // SHA1 and SHA256 two-register crypto + // SHA1H: 0101 1110 0010 1000 0000 10 Rn Rd (0x5e280800) + // SHA1SU1: 0101 1110 0010 1000 0001 10 Rn Rd (0x5e281800) + // SHA256SU0: 0101 1110 0010 1000 0010 10 Rn Rd (0x5e282800) + // Mask 0xffffcc00 keeps bits 31:14 and 11:10, ignores opcode (13:12), Rn, Rd + if ((insn & 0xffffcc00) == 0x5e280800) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t opcode = (insn >> 12) & 0x3; + + void *gadget = NULL; + switch (opcode) { + case 0: gadget = gadget_sha1h; break; // SHA1H + case 1: gadget = gadget_sha1su1; break; // SHA1SU1 + case 2: gadget = gadget_sha256su0; break; // SHA256SU0 + } + if (gadget) { + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8)); + return 1; + } + } + + // SHA1 three-register: SHA1C, SHA1M, SHA1P, SHA1SU0 + // Pattern: 0101 1110 000 Rm 0 opcode 00 Rn Rd (bit 14=0 for SHA1) + // SHA1C: 0x5e000000 (opcode=00) + // SHA1P: 0x5e001000 (opcode=01) + // SHA1M: 0x5e002000 (opcode=10) + // SHA1SU0: 0x5e003000 (opcode=11) + // Mask 0xffe04c00 includes bit 14 to distinguish from SHA256 (bit14=1) + if ((insn & 0xffe04c00) == 0x5e000000) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t opcode = (insn >> 12) & 0x3; + + void *gadget = NULL; + switch (opcode) { + case 0: gadget = gadget_sha1c; break; + case 1: gadget = gadget_sha1p; break; + case 2: gadget = gadget_sha1m; break; + case 3: gadget = gadget_sha1su0; break; + } + if (gadget) { + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (rm << 16)); + return 1; + } + } + + // SHA256 three-register: SHA256H, SHA256H2, SHA256SU1 + // Pattern: 0101 1110 000 Rm 0 opcode 00 Rn Rd (opcode in bits 13-12, bit 14=1 for SHA256) + // SHA256H: 0x5e004000 (opcode=00) + // SHA256H2: 0x5e005000 (opcode=01) + // SHA256SU1: 0x5e006000 (opcode=10) + // Mask 0xffe04c00 includes bit 14 to distinguish from SHA1 (bit14=0) + if ((insn & 0xffe04c00) == 0x5e004000) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t opcode = (insn >> 12) & 0x3; + + void *gadget = NULL; + switch (opcode) { + case 0: gadget = gadget_sha256h; break; + case 1: gadget = gadget_sha256h2; break; + case 2: gadget = gadget_sha256su1; break; + } + if (gadget) { + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (rm << 16)); + return 1; + } + } + + // SHA512SU0: SHA512 schedule update 0 (two-register) + // Pattern: 1100 1110 1100 0000 1000 0 Rn Rd (0xcec08000) + if ((insn & 0xfffffc00) == 0xcec08000) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + gen(state, (unsigned long) gadget_sha512su0); + gen(state, rd | (rn << 8)); + return 1; + } + + // SHA512H: SHA512 hash update part 1 (three-register) + // Pattern: 1100 1110 011 Rm 1000 00 Rn Rd (0xce608000) + if ((insn & 0xffe0fc00) == 0xce608000) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rm = (insn >> 16) & 0x1f; + gen(state, (unsigned long) gadget_sha512h); + gen(state, rd | (rn << 8) | (rm << 16)); + return 1; + } + + // SHA512H2: SHA512 hash update part 2 (three-register) + // Pattern: 1100 1110 011 Rm 1000 01 Rn Rd (0xce608400) + if ((insn & 0xffe0fc00) == 0xce608400) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rm = (insn >> 16) & 0x1f; + gen(state, (unsigned long) gadget_sha512h2); + gen(state, rd | (rn << 8) | (rm << 16)); + return 1; + } + + // SHA512SU1: SHA512 schedule update 1 (three-register) + // Pattern: 1100 1110 011 Rm 1000 10 Rn Rd (0xce608800) + if ((insn & 0xffe0fc00) == 0xce608800) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rm = (insn >> 16) & 0x1f; + gen(state, (unsigned long) gadget_sha512su1); + gen(state, rd | (rn << 8) | (rm << 16)); + return 1; + } + + // SM4E: SM4 round (two-register) + // Pattern: 1100 1110 1100 0000 1000 01 Rn Rd (0xcec08400) + if ((insn & 0xfffffc00) == 0xcec08400) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + gen(state, (unsigned long) gadget_sm4e); + gen(state, rd | (rn << 8)); + return 1; + } + + // SM3PARTW1: SM3 message schedule update (three-register) + // Pattern: 1100 1110 0110 0000 1100 00 Rm Rn Rd (0xce60c000) + if ((insn & 0xffe0fc00) == 0xce60c000) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rm = (insn >> 16) & 0x1f; + gen(state, (unsigned long) gadget_sm3partw1); + gen(state, rd | (rn << 8) | (rm << 16)); + return 1; + } + + // EOR3: XOR of three vectors (four-register) + // Pattern: 1100 1110 0000 0000 1000 00 Rm Ra Rn Rd (0xce000000) + if ((insn & 0xffe08000) == 0xce000000) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t ra = (insn >> 10) & 0x1f; + uint32_t rm = (insn >> 16) & 0x1f; + gen(state, (unsigned long) gadget_eor3); + gen(state, rd | (rn << 8) | (rm << 16) | (ra << 24)); + return 1; + } + + // PMULL: Polynomial Multiply Long + // Pattern: 0 Q 00 1110 size 1 Rm 1110 00 Rn Rd + // PMULL (8B): 0x0e20e000 (Q=0, size=00) + // PMULL2 (16B): 0x4e20e000 (Q=1, size=00) + // PMULL (1D): 0x0ee0e000 (Q=0, size=11) + // PMULL2 (2D): 0x4ee0e000 (Q=1, size=11) + if ((insn & 0xbf20fc00) == 0x0e20e000) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rm = (insn >> 16) & 0x1f; + uint32_t Q = (insn >> 30) & 1; + uint32_t size = (insn >> 22) & 0x3; + + + gen(state, (unsigned long) gadget_pmull); + gen(state, rd | (rn << 8) | (rm << 16) | (Q << 24) | (size << 26)); + return 1; + } + + // AdvSIMD scalar x indexed element + // Pattern: 01 op 11111 size L M Rm opcode H 0 Rn Rd + // Fixed: bits[31:30]=01, bits[28:24]=11111, bit[10]=0 + // Mask: 0xff000400, Value: 0x5f000000 + if ((insn & 0xff000400) == 0x5f000000) { + uint32_t U = (insn >> 29) & 1; + uint32_t size = (insn >> 22) & 3; + uint32_t L = (insn >> 21) & 1; + uint32_t M = (insn >> 20) & 1; + uint32_t Rm4 = (insn >> 16) & 0xf; + uint32_t opcode_elem = (insn >> 12) & 0xf; + uint32_t H = (insn >> 11) & 1; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + uint32_t rm, index; + if (size == 2) { + rm = (M << 4) | Rm4; + index = (H << 1) | L; + } else if (size == 3) { + rm = (M << 4) | Rm4; + index = H; + } else { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget = NULL; + // Pack: rd | rn<<8 | rm<<16 | index<<21 | size<<24 + uint64_t packed = rd | (rn << 8) | (rm << 16) | (index << 21) | (size << 24); + + if (U == 0 && opcode_elem == 0x9) { + gadget = gadget_fmul_elem_scalar; + } else if (U == 0 && opcode_elem == 0x1) { + gadget = gadget_fmla_elem_scalar; + } else if (U == 0 && opcode_elem == 0x5) { + gadget = gadget_fmls_elem_scalar; + } else if (U == 1 && opcode_elem == 0x9) { + gadget = gadget_fmulx_elem_scalar; + } + + if (gadget) { + gen(state, (unsigned long) gadget); + gen(state, packed); + return 1; + } + } + + // AdvSIMD vector x indexed element + // Pattern: 0 Q U 01111 size L M Rm opcode H 0 Rn Rd + // Fixed: bit[31]=0, bits[28:24]=01111, bit[10]=0 + // Mask: 0x9f000400, Value: 0x0f000000 + if ((insn & 0x9f000400) == 0x0f000000) { + uint32_t Q = (insn >> 30) & 1; + uint32_t U = (insn >> 29) & 1; + uint32_t size = (insn >> 22) & 3; + uint32_t L = (insn >> 21) & 1; + uint32_t M = (insn >> 20) & 1; + uint32_t Rm4 = (insn >> 16) & 0xf; + uint32_t opcode_elem = (insn >> 12) & 0xf; + uint32_t H = (insn >> 11) & 1; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + + uint32_t rm, index; + if (size == 1) { // H: index = H:L:M, Rm = Rm4 + rm = Rm4; + index = (H << 2) | (L << 1) | M; + } else if (size == 2) { // S: index = H:L, Rm = M:Rm4 + rm = (M << 4) | Rm4; + index = (H << 1) | L; + } else if (size == 3) { // D: index = H, Rm = M:Rm4 + rm = (M << 4) | Rm4; + index = H; + } else { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget = NULL; + // Pack: rd | rn<<8 | rm<<16 | index<<21 | size<<24 | Q<<26 + uint64_t packed = rd | (rn << 8) | (rm << 16) | (index << 21) | (size << 24) | (Q << 26); + + if (U == 0 && opcode_elem == 0x8) { + // MUL by element (H/S only) + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_mul_elem_vec; + } else if (U == 1 && opcode_elem == 0x0) { + // MLA by element (H/S only) — U=1, opcode=0x0 + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_mla_elem_vec; + } else if (U == 1 && opcode_elem == 0x4) { + // MLS by element (H/S only) — U=1, opcode=0x4 + if (size == 3) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_mls_elem_vec; + } else if (U == 0 && opcode_elem == 0xa) { + // SMULL by element + gadget = gadget_smull_elem_vec; + } else if (U == 1 && opcode_elem == 0xa) { + // UMULL by element + gadget = gadget_umull_elem_vec; + } else if (U == 0 && opcode_elem == 0x2) { + // SMLAL by element + gadget = gadget_smlal_elem_vec; + } else if (U == 1 && opcode_elem == 0x2) { + // UMLAL by element + gadget = gadget_umlal_elem_vec; + } else if (U == 0 && opcode_elem == 0x6) { + // SMLSL by element + gadget = gadget_smlsl_elem_vec; + } else if (U == 1 && opcode_elem == 0x6) { + // UMLSL by element + gadget = gadget_umlsl_elem_vec; + } else if (U == 0 && opcode_elem == 0x9) { + // FMUL by element (size=2:S, size=3:D; size<2 is FP16/invalid) + if (size < 2) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_fmul_elem_vec; + } else if (U == 0 && opcode_elem == 0x1) { + // FMLA by element (size=2:S, size=3:D) + if (size < 2) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_fmla_elem_vec; + } else if (U == 0 && opcode_elem == 0x5) { + // FMLS by element (size=2:S, size=3:D) + if (size < 2) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_fmls_elem_vec; + } else if (U == 0 && opcode_elem == 0xc) { + // SQDMULH by element (H/S only) + if (size < 1 || size > 2) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_sqdmulh_elem_vec; + } else if (U == 0 && opcode_elem == 0xd) { + // SQRDMULH by element (H/S only) + if (size < 1 || size > 2) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_sqrdmulh_elem_vec; + } else if (U == 0 && opcode_elem == 0xb) { + // SQDMULL by element (H→S, S→D widening) + if (size < 1 || size > 2) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_sqdmull_elem_vec; + } else if (U == 0 && opcode_elem == 0x3) { + // SQDMLAL by element (widening multiply-accumulate) + if (size < 1 || size > 2) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_sqdmlal_elem_vec; + } else if (U == 0 && opcode_elem == 0x7) { + // SQDMLSL by element (widening multiply-subtract) + if (size < 1 || size > 2) { gen_interrupt(state, INT_UNDEFINED); return 0; } + gadget = gadget_sqdmlsl_elem_vec; + } + + if (gadget) { + gen(state, (unsigned long) gadget); + gen(state, packed); + return 1; + } + // Fall through to try other decoders for unimplemented opcodes + } + + // AdvSIMD scalar three-same: 01 U 11110 sz 1 Rm opcode 1 Rn Rd + // ADD (scalar, 64-bit integer): U=0, opcode=10000 + // SUB (scalar, 64-bit integer): U=1, opcode=10000 + // Mask: 0xdf200400, Value: 0x5e200400 + if ((insn & 0xdf200400) == 0x5e200400) { + uint32_t U = (insn >> 29) & 1; + uint32_t sz = (insn >> 22) & 3; + uint32_t Rm = (insn >> 16) & 0x1f; + uint32_t opcode = (insn >> 11) & 0x1f; + uint32_t Rn = (insn >> 5) & 0x1f; + uint32_t Rd = insn & 0x1f; + + void *gadget = NULL; + if (sz == 3 && opcode == 0x10 && U == 0) { + // ADD d, d, d (64-bit integer) + gadget = gadget_add_scalar_i64; + } else if (sz == 3 && opcode == 0x10 && U == 1) { + // SUB d, d, d (64-bit integer) + gadget = gadget_sub_scalar_i64; + } else if (sz == 3 && opcode == 0x08 && U == 1) { + // USHL d, d, d (unsigned shift left) + gadget = gadget_ushl_scalar_i64; + } else if (sz == 3 && opcode == 0x08 && U == 0) { + // SSHL d, d, d (signed shift left) + gadget = gadget_sshl_scalar_i64; + } else if (sz == 3 && opcode == 0x06 && U == 1) { + // CMHI d, d, d (compare higher unsigned) + gadget = gadget_cmhi_scalar_i64; + } else if (sz == 3 && opcode == 0x07 && U == 1) { + // CMHS d, d, d (compare higher or same unsigned) + gadget = gadget_cmhs_scalar_i64; + } else if (sz == 3 && opcode == 0x06 && U == 0) { + // CMGT d, d, d (compare greater than signed) + gadget = gadget_cmgt_scalar_i64; + } else if (sz == 3 && opcode == 0x07 && U == 0) { + // CMGE d, d, d (compare greater or equal signed) + gadget = gadget_cmge_scalar_i64; + } else if (sz == 3 && opcode == 0x11 && U == 1) { + // CMEQ d, d, d (compare equal) + gadget = gadget_cmeq_scalar_i64; + } + + if (gadget) { + gen(state, (unsigned long) gadget); + gen(state, Rd | (Rn << 8) | (Rm << 16)); + return 1; + } + + // FABD (scalar): U=1, bit23=1, opcode=11010 (0x1A) + // Floating-point absolute difference: Vd = |Vn - Vm| + // bit22 = 0: single, bit22 = 1: double + if (U == 1 && (sz & 2) && opcode == 0x1a) { + uint32_t type = sz & 1; // bit 22: 0=single, 1=double + gen(state, (unsigned long) gadget_fabd_scalar); + gen(state, Rd | (Rn << 8) | (Rm << 16) | (type << 24)); + return 1; + } + } + + // FADDP (scalar) - Floating-point Add Pair of elements + // Encoding: 0111111 0 0 sz 110000 110110 Rn Rd + // sz=0: single (FADDP Sd, Vn.2S), sz=1: double (FADDP Dd, Vn.2D) + // Mask: 0xffbffc00, Value: 0x7e30d800 + if ((insn & 0xffbffc00) == 0x7e30d800) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t sz = (insn >> 22) & 1; + gen(state, (unsigned long) gadget_faddp_scalar); + gen(state, rd | (rn << 8) | (sz << 16)); + return 1; + } + + // FMAXP/FMINP (scalar) - Floating-point Max/Min Pair of elements + // FMAXP: 0111 1110 0 sz 11000 01111 10 Rn Rd (U=1, size[1]=0) + // FMINP: 0111 1110 1 sz 11000 01111 10 Rn Rd (U=1, size[1]=1) + // Mask: 0xffbffc00 (ignores sz=bit22) + if ((insn & 0xffbffc00) == 0x7e30f800) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t sz = (insn >> 22) & 1; + gen(state, (unsigned long) gadget_fmaxp_scalar); + gen(state, rd | (rn << 8) | (sz << 16)); + return 1; + } + if ((insn & 0xffbffc00) == 0x7eb0f800) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t sz = (insn >> 22) & 1; + gen(state, (unsigned long) gadget_fminp_scalar); + gen(state, rd | (rn << 8) | (sz << 16)); + return 1; + } + + // FMAXNMP/FMINNMP (scalar) - Floating-point MaxNum/MinNum Pair of elements + // FMAXNMP: 0111 1110 0 sz 11000 01100 10 Rn Rd (bit23=0, opcode=01100) + // FMINNMP: 0111 1110 1 sz 11000 01100 10 Rn Rd (bit23=1, opcode=01100) + if ((insn & 0xffbffc00) == 0x7e30c800) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t sz = (insn >> 22) & 1; + gen(state, (unsigned long) gadget_fmaxnmp_scalar); + gen(state, rd | (rn << 8) | (sz << 16)); + return 1; + } + if ((insn & 0xffbffc00) == 0x7eb0c800) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t sz = (insn >> 22) & 1; + gen(state, (unsigned long) gadget_fminnmp_scalar); + gen(state, rd | (rn << 8) | (sz << 16)); + return 1; + } + + // ADDP (scalar) - Integer Add Pair of elements (64-bit only) + // Encoding: 0101 1110 1111 0001 1011 1000 Rn Rd + // Mask: 0xfffffc00, Value: 0x5ef1b800 + if ((insn & 0xfffffc00) == 0x5ef1b800) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + gen(state, (unsigned long) gadget_addp_scalar); + gen(state, rd | (rn << 8)); + return 1; + } + + // Scalar integer two-register miscellaneous (size=11, 64-bit only) + // Encoding: 01 U 11110 11 10000 opcode 10 Rn Rd + // CMGT D,D,#0: U=0, opcode=01000 (0x08) + // CMGE D,D,#0: U=1, opcode=01000 (0x08) + // CMEQ D,D,#0: U=0, opcode=01001 (0x09) + // CMLE D,D,#0: U=1, opcode=01001 (0x09) + // CMLT D,D,#0: U=0, opcode=01010 (0x0a) + // ABS D,D: U=0, opcode=01011 (0x0b) + // NEG D,D: U=1, opcode=01011 (0x0b) + // Mask: 0xdffe0c00, Value: 0x5ee00800 + if ((insn & 0xdffe0c00) == 0x5ee00800) { + uint32_t U = (insn >> 29) & 1; + uint32_t opcode = (insn >> 12) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + void *gadget = NULL; + + if (opcode == 0x08 && U == 0) gadget = gadget_cmgt_scalar_zero; + else if (opcode == 0x08 && U == 1) gadget = gadget_cmge_scalar_zero; + else if (opcode == 0x09 && U == 0) gadget = gadget_cmeq_scalar_zero; + else if (opcode == 0x09 && U == 1) gadget = gadget_cmle_scalar_zero; + else if (opcode == 0x0a && U == 0) gadget = gadget_cmlt_scalar_zero; + else if (opcode == 0x0b && U == 0) gadget = gadget_abs_scalar; + else if (opcode == 0x0b && U == 1) gadget = gadget_neg_scalar; + + if (gadget) { + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8)); + return 1; + } + } + + // FP scalar two-register miscellaneous — compare against zero + // Encoding: 01 U 11110 1 sz 10000 opcode 10 Rn Rd + // bit[23]=1 (FP range), bit[22]=sz (0=single, 1=double) + // FCMGT: U=0, opcode=01100 (0x0c) + // FCMGE: U=1, opcode=01100 (0x0c) + // FCMEQ: U=0, opcode=01101 (0x0d) + // FCMLE: U=1, opcode=01101 (0x0d) + // FCMLT: U=0, opcode=01110 (0x0e) + // Mask: 0xdfbe0c00 (ignores U=bit29, sz=bit22), Value: 0x5ea00800 + if ((insn & 0xdfbe0c00) == 0x5ea00800) { + uint32_t U = (insn >> 29) & 1; + uint32_t sz = (insn >> 22) & 1; + uint32_t opcode = (insn >> 12) & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t rd = insn & 0x1f; + void *gadget = NULL; + + if (opcode == 0x0c && U == 0) gadget = gadget_fcmgt_scalar_zero; + else if (opcode == 0x0c && U == 1) gadget = gadget_fcmge_scalar_zero; + else if (opcode == 0x0d && U == 0) gadget = gadget_fcmeq_scalar_zero; + else if (opcode == 0x0d && U == 1) gadget = gadget_fcmle_scalar_zero; + else if (opcode == 0x0e && U == 0) gadget = gadget_fcmlt_scalar_zero; + + if (gadget) { + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (sz << 16)); + return 1; + } + } + + // FCVTZS/FCVTZU (scalar, integer) - SIMD scalar form + // Convert floating-point to integer (result in SIMD register) + // Encoding: 01 U 11110 1 sz 100001 opcode Rn Rd + // FCVTZS: U=0, opcode=101110 (0x2e) + // FCVTZU: U=1, opcode=101110 (0x2e) + // sz=0: single (S), sz=1: double (D) + // Mask 0xdfbffc00 checks fixed bits, ignores U (bit29), sz (bit22), Rn, Rd + if ((insn & 0xdfbffc00) == 0x5ea1b800) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t sz = (insn >> 22) & 1; + uint32_t U = (insn >> 29) & 1; + + void *gadget = U ? gadget_fcvtzu_simd_scalar : gadget_fcvtzs_simd_scalar; + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (sz << 16)); + return 1; + } + + // UCVTF/SCVTF (scalar, integer) - SIMD scalar form + // Convert integer to floating-point (result in SIMD register) + // Encoding: 01 U 11110 0 sz 1 00001 110110 Rn Rd + // SCVTF: U=0 (signed) + // UCVTF: U=1 (unsigned) + // sz=0: single (S), sz=1: double (D) + // Mask 0xdfbffc00 checks fixed bits, ignores U (bit29), sz (bit22), Rn, Rd + if ((insn & 0xdfbffc00) == 0x5e21d800) { + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + uint32_t sz = (insn >> 22) & 1; + uint32_t U = (insn >> 29) & 1; + + void *gadget = U ? gadget_ucvtf_simd_scalar : gadget_scvtf_simd_scalar; + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (sz << 16)); + return 1; + } + + // SHL/SSHR/USHR (scalar, immediate) - Scalar shift by immediate + // Encoding: 01 U 11111 0 immh immb opcode Rn Rd + // SHL: U=0, opcode=01010 (0x0a) + // SSHR: U=0, opcode=00000 (0x00) + // USHR: U=1, opcode=00000 (0x00) + // immh determines element size: 1xxx=64-bit, 01xx=32-bit, 001x=16-bit, 0001=8-bit + // Mask 0xdf800400 checks bits 31:30, 28:24, 23, 10 (fixed bits) + if ((insn & 0xdf800400) == 0x5f000400) { + uint32_t U = (insn >> 29) & 1; + uint32_t immh = (insn >> 19) & 0xf; + uint32_t immb = (insn >> 16) & 0x7; + uint32_t opcode = (insn >> 11) & 0x1f; + uint32_t rd = insn & 0x1f; + uint32_t rn = (insn >> 5) & 0x1f; + + // Determine element size and shift amount from immh:immb + int esize = -1; + int shift = 0; + int immhb = (immh << 3) | immb; + + if (immh & 0x8) { + esize = 3; // 64-bit + shift = immhb - 64; // For SHL: shift = immh:immb - 64 + } else if (immh & 0x4) { + esize = 2; // 32-bit + shift = immhb - 32; + } else if (immh & 0x2) { + esize = 1; // 16-bit + shift = immhb - 16; + } else if (immh & 0x1) { + esize = 0; // 8-bit + shift = immhb - 8; + } + + if (esize < 0) { + gen_interrupt(state, INT_UNDEFINED); + return 0; + } + + void *gadget = NULL; + if (U == 0 && opcode == 0x0a) { + // SHL (scalar) + gadget = gadget_shl_imm_scalar; + } else if (U == 0 && opcode == 0x00) { + // SSHR (scalar) - for SSHR, shift = (esize*8*2) - immh:immb + if (esize == 3) shift = 128 - immhb; + else if (esize == 2) shift = 64 - immhb; + else if (esize == 1) shift = 32 - immhb; + else shift = 16 - immhb; + gadget = gadget_sshr_imm_scalar; + } else if (U == 1 && opcode == 0x00) { + // USHR (scalar) + if (esize == 3) shift = 128 - immhb; + else if (esize == 2) shift = 64 - immhb; + else if (esize == 1) shift = 32 - immhb; + else shift = 16 - immhb; + gadget = gadget_ushr_imm_scalar; + } else if (U == 0 && opcode == 0x02) { + // SSRA (scalar) - signed shift right and accumulate + if (esize == 3) shift = 128 - immhb; + else if (esize == 2) shift = 64 - immhb; + else if (esize == 1) shift = 32 - immhb; + else shift = 16 - immhb; + gadget = gadget_ssra_imm_scalar; + } else if (U == 1 && opcode == 0x02) { + // USRA (scalar) - unsigned shift right and accumulate + if (esize == 3) shift = 128 - immhb; + else if (esize == 2) shift = 64 - immhb; + else if (esize == 1) shift = 32 - immhb; + else shift = 16 - immhb; + gadget = gadget_usra_imm_scalar; + } else if (U == 0 && opcode == 0x1c) { + // SCVTF (scalar, fixed-point) - signed int to FP + // fbits = (esize*2*8) - immh:immb + if (esize == 3) shift = 128 - immhb; + else if (esize == 2) shift = 64 - immhb; + else if (esize == 1) shift = 32 - immhb; + else shift = 16 - immhb; + gadget = gadget_scvtf_fixpt_scalar; + } else if (U == 1 && opcode == 0x1c) { + // UCVTF (scalar, fixed-point) - unsigned int to FP + if (esize == 3) shift = 128 - immhb; + else if (esize == 2) shift = 64 - immhb; + else if (esize == 1) shift = 32 - immhb; + else shift = 16 - immhb; + gadget = gadget_ucvtf_fixpt_scalar; + } else if (U == 0 && opcode == 0x1f) { + // FCVTZS (scalar, fixed-point) - FP to signed int, round toward zero + if (esize == 3) shift = 128 - immhb; + else if (esize == 2) shift = 64 - immhb; + else if (esize == 1) shift = 32 - immhb; + else shift = 16 - immhb; + gadget = gadget_fcvtzs_fixpt_scalar; + } else if (U == 1 && opcode == 0x1f) { + // FCVTZU (scalar, fixed-point) - FP to unsigned int, round toward zero + if (esize == 3) shift = 128 - immhb; + else if (esize == 2) shift = 64 - immhb; + else if (esize == 1) shift = 32 - immhb; + else shift = 16 - immhb; + gadget = gadget_fcvtzu_fixpt_scalar; + } + + if (gadget) { + gen(state, (unsigned long) gadget); + gen(state, rd | (rn << 8) | (shift << 16) | (esize << 24)); + return 1; + } + } + + // SIMD/FP instructions not implemented yet + gen_interrupt(state, INT_UNDEFINED); + return 0; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/helpers.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/helpers.c new file mode 100644 index 0000000000..607d6a0edf --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/helpers.c @@ -0,0 +1,24 @@ +#include <time.h> +#include <stdio.h> +#include "emu/cpu.h" + +// ARM64 doesn't have CPUID - this is a stub for compatibility +void helper_cpuid(dword_t *a, dword_t *b, dword_t *c, dword_t *d) { + (void)a; (void)b; (void)c; (void)d; +} + +// ARM64 counter register access +void helper_rdtsc(struct cpu_state *cpu) { + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + uint64_t tsc = now.tv_sec * 1000000000l + now.tv_nsec; + cpu->regs[0] = tsc; +} + +void helper_expand_flags(struct cpu_state *cpu) { + expand_flags(cpu); +} + +void helper_collapse_flags(struct cpu_state *cpu) { + collapse_flags(cpu); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/offsets.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/offsets.c new file mode 100644 index 0000000000..a535bdb774 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/asbestos/offsets.c @@ -0,0 +1,98 @@ +#include "asbestos/asbestos.h" +#include "asbestos/frame.h" +#include "emu/cpu.h" +#include "emu/tlb.h" + +void cpu() { + // ARM64 register offsets + OFFSET(CPU, cpu_state, x0); + OFFSET(CPU, cpu_state, x1); + OFFSET(CPU, cpu_state, x2); + OFFSET(CPU, cpu_state, x3); + OFFSET(CPU, cpu_state, x4); + OFFSET(CPU, cpu_state, x5); + OFFSET(CPU, cpu_state, x6); + OFFSET(CPU, cpu_state, x7); + OFFSET(CPU, cpu_state, x8); + OFFSET(CPU, cpu_state, x9); + OFFSET(CPU, cpu_state, x10); + OFFSET(CPU, cpu_state, x11); + OFFSET(CPU, cpu_state, x12); + OFFSET(CPU, cpu_state, x13); + OFFSET(CPU, cpu_state, x14); + OFFSET(CPU, cpu_state, x15); + OFFSET(CPU, cpu_state, x16); + OFFSET(CPU, cpu_state, x17); + OFFSET(CPU, cpu_state, x18); + OFFSET(CPU, cpu_state, x19); + OFFSET(CPU, cpu_state, x20); + OFFSET(CPU, cpu_state, x21); + OFFSET(CPU, cpu_state, x22); + OFFSET(CPU, cpu_state, x23); + OFFSET(CPU, cpu_state, x24); + OFFSET(CPU, cpu_state, x25); + OFFSET(CPU, cpu_state, x26); + OFFSET(CPU, cpu_state, x27); + OFFSET(CPU, cpu_state, x28); + OFFSET(CPU, cpu_state, x29); + OFFSET(CPU, cpu_state, x30); + OFFSET(CPU, cpu_state, sp); + OFFSET(CPU, cpu_state, pc); + OFFSET(CPU, cpu_state, tls_ptr); + + // ARM64 flags (NZCV) + OFFSET(CPU, cpu_state, nf); + OFFSET(CPU, cpu_state, zf); + OFFSET(CPU, cpu_state, cf); + OFFSET(CPU, cpu_state, vf); + OFFSET(CPU, cpu_state, nzcv); + + // FP registers + OFFSET(CPU, cpu_state, fp); + OFFSET(CPU, cpu_state, fpcr); + OFFSET(CPU, cpu_state, fpsr); + + // Exclusive monitor + OFFSET(CPU, cpu_state, excl_addr); + OFFSET(CPU, cpu_state, excl_val); + OFFSET(CPU, cpu_state, excl_pair_addr); + OFFSET(CPU, cpu_state, excl_pair_val_lo); + OFFSET(CPU, cpu_state, excl_pair_val_hi); + OFFSET(CPU, cpu_state, excl_pair_size); + + // Cycle counter (for timer interrupts in chained blocks) + OFFSET(CPU, cpu_state, cycle); + + // Common offsets + OFFSET(LOCAL, fiber_frame, bp); + OFFSET(LOCAL, fiber_frame, value); + OFFSET(LOCAL, fiber_frame, value_addr); + OFFSET(LOCAL, fiber_frame, last_block); + OFFSET(LOCAL, fiber_frame, jit_exit_sp); + OFFSET(LOCAL, fiber_frame, jit_saved_pc); + OFFSET(LOCAL, fiber_frame, ret_cache); + OFFSET(CPU, cpu_state, segfault_addr); + OFFSET(CPU, cpu_state, segfault_was_write); + OFFSET(CPU, cpu_state, poked_ptr); + OFFSET(CPU, cpu_state, cycle); + MACRO(MEM_READ); + MACRO(MEM_WRITE); + + OFFSET(FIBER_BLOCK, fiber_block, addr); + OFFSET(FIBER_BLOCK, fiber_block, end_addr); + OFFSET(FIBER_BLOCK, fiber_block, code); + + OFFSET(TLB, tlb, entries); + OFFSET(TLB, tlb, mmu); + OFFSET(TLB, tlb, dirty_page); + OFFSET(TLB, tlb, segfault_addr); + OFFSET(TLB, tlb, block_cache); // inline indirect-branch target cache + OFFSET(TLB, tlb, block_cache_gen); + OFFSET(TLB_ENTRY, tlb_entry, page); + OFFSET(TLB_ENTRY, tlb_entry, page_if_writable); + OFFSET(TLB_ENTRY, tlb_entry, data_minus_addr); +#ifdef GUEST_ARM64 + OFFSET(TLB_ENTRY, tlb_entry, gen); + OFFSET(MMU, mmu, changes); +#endif +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/debug.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/debug.h new file mode 100644 index 0000000000..743e3397e3 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/debug.h @@ -0,0 +1,84 @@ +#ifndef UTIL_DEBUG_H +#define UTIL_DEBUG_H +#include <stdio.h> +#include <stdlib.h> + +void ish_printk(const char *msg, ...); +void ish_vprintk(const char *msg, va_list args); +#undef printk +#define printk ish_printk + +// debug output utilities +// save me + +#ifndef DEBUG_all +#define DEBUG_all 0 +#endif +#ifndef DEBUG_verbose +#define DEBUG_verbose DEBUG_all +#endif +#ifndef DEBUG_instr +#define DEBUG_instr DEBUG_all +#endif +#ifndef DEBUG_debug +#define DEBUG_debug DEBUG_all +#endif +#ifndef DEBUG_strace +#define DEBUG_strace DEBUG_all +#endif +#ifndef DEBUG_memory +#define DEBUG_memory DEBUG_all +#endif + +#if DEBUG_verbose +#define TRACE_verbose TRACE__ +#else +#define TRACE_verbose TRACE__NOP +#endif +#if DEBUG_instr +#define TRACE_instr TRACE__ +#else +#define TRACE_instr TRACE__NOP +#endif +#if DEBUG_debug +#define TRACE_debug TRACE__ +#else +#define TRACE_debug TRACE__NOP +#endif +#if DEBUG_strace +#define TRACE_strace TRACE__ +#else +#define TRACE_strace TRACE__NOP +#endif +#if DEBUG_memory +#define TRACE_memory TRACE__ +#else +#define TRACE_memory TRACE__NOP +#endif + +#ifdef LOG_OVERRIDE +extern int log_override; +#define TRACE__NOP(msg, ...) if (log_override) { TRACE__(msg, ##__VA_ARGS__); } +#else +#define TRACE__NOP(msg, ...) use(__VA_ARGS__) +#endif +#define TRACE__(msg, ...) printk(msg, ##__VA_ARGS__) + +#define TRACE_(chan, msg, ...) glue(TRACE_, chan)(msg, ##__VA_ARGS__) +#define TRACE(msg, ...) TRACE_(DEFAULT_CHANNEL, msg, ##__VA_ARGS__) +#ifndef DEFAULT_CHANNEL +#define DEFAULT_CHANNEL verbose +#endif + +#define TODO(msg, ...) die("TODO: " msg, ##__VA_ARGS__) +#define FIXME(msg, ...) printk("FIXME " msg "\n", ##__VA_ARGS__) +#define ERRNO_DIE(msg) { perror(msg); abort(); } +extern void (*die_handler)(const char *msg); +_Noreturn void die(const char *msg, ...); + +#define STRACE(msg, ...) TRACE_(strace, msg, ##__VA_ARGS__) + +#include <signal.h> +#define debugger raise(SIGTRAP) + +#endif \ No newline at end of file diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/config.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/config.h new file mode 100644 index 0000000000..2cdd249ed2 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/config.h @@ -0,0 +1,1429 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.ac by autoheader. */ + +/* Darwin ACL support */ +#define ARCHIVE_ACL_DARWIN 1 + +/* FreeBSD ACL support */ +/* #undef ARCHIVE_ACL_FREEBSD */ + +/* FreeBSD NFSv4 ACL support */ +/* #undef ARCHIVE_ACL_FREEBSD_NFS4 */ + +/* Linux POSIX.1e ACL support via libacl */ +/* #undef ARCHIVE_ACL_LIBACL */ + +/* Linux NFSv4 ACL support via librichacl */ +/* #undef ARCHIVE_ACL_LIBRICHACL */ + +/* Solaris ACL support */ +/* #undef ARCHIVE_ACL_SUNOS */ + +/* Solaris NFSv4 ACL support */ +/* #undef ARCHIVE_ACL_SUNOS_NFS4 */ + +/* MD5 via ARCHIVE_CRYPTO_MD5_LIBC supported. */ +/* #undef ARCHIVE_CRYPTO_MD5_LIBC */ + +/* MD5 via ARCHIVE_CRYPTO_MD5_LIBMD supported. */ +/* #undef ARCHIVE_CRYPTO_MD5_LIBMD */ + +/* MD5 via ARCHIVE_CRYPTO_MD5_LIBSYSTEM supported. */ +#define ARCHIVE_CRYPTO_MD5_LIBSYSTEM 1 + +/* MD5 via ARCHIVE_CRYPTO_MD5_MBEDTLS supported. */ +/* #undef ARCHIVE_CRYPTO_MD5_MBEDTLS */ + +/* MD5 via ARCHIVE_CRYPTO_MD5_NETTLE supported. */ +/* #undef ARCHIVE_CRYPTO_MD5_NETTLE */ + +/* MD5 via ARCHIVE_CRYPTO_MD5_OPENSSL supported. */ +/* #undef ARCHIVE_CRYPTO_MD5_OPENSSL */ + +/* MD5 via ARCHIVE_CRYPTO_MD5_WIN supported. */ +/* #undef ARCHIVE_CRYPTO_MD5_WIN */ + +/* RMD160 via ARCHIVE_CRYPTO_RMD160_LIBC supported. */ +/* #undef ARCHIVE_CRYPTO_RMD160_LIBC */ + +/* RMD160 via ARCHIVE_CRYPTO_RMD160_LIBMD supported. */ +/* #undef ARCHIVE_CRYPTO_RMD160_LIBMD */ + +/* RMD160 via ARCHIVE_CRYPTO_RMD160_MBEDTLS supported. */ +/* #undef ARCHIVE_CRYPTO_RMD160_MBEDTLS */ + +/* RMD160 via ARCHIVE_CRYPTO_RMD160_NETTLE supported. */ +/* #undef ARCHIVE_CRYPTO_RMD160_NETTLE */ + +/* RMD160 via ARCHIVE_CRYPTO_RMD160_OPENSSL supported. */ +/* #undef ARCHIVE_CRYPTO_RMD160_OPENSSL */ + +/* SHA1 via ARCHIVE_CRYPTO_SHA1_LIBC supported. */ +/* #undef ARCHIVE_CRYPTO_SHA1_LIBC */ + +/* SHA1 via ARCHIVE_CRYPTO_SHA1_LIBMD supported. */ +/* #undef ARCHIVE_CRYPTO_SHA1_LIBMD */ + +/* SHA1 via ARCHIVE_CRYPTO_SHA1_LIBSYSTEM supported. */ +#define ARCHIVE_CRYPTO_SHA1_LIBSYSTEM 1 + +/* SHA1 via ARCHIVE_CRYPTO_SHA1_MBEDTLS supported. */ +/* #undef ARCHIVE_CRYPTO_SHA1_MBEDTLS */ + +/* SHA1 via ARCHIVE_CRYPTO_SHA1_NETTLE supported. */ +/* #undef ARCHIVE_CRYPTO_SHA1_NETTLE */ + +/* SHA1 via ARCHIVE_CRYPTO_SHA1_OPENSSL supported. */ +/* #undef ARCHIVE_CRYPTO_SHA1_OPENSSL */ + +/* SHA1 via ARCHIVE_CRYPTO_SHA1_WIN supported. */ +/* #undef ARCHIVE_CRYPTO_SHA1_WIN */ + +/* SHA256 via ARCHIVE_CRYPTO_SHA256_LIBC supported. */ +/* #undef ARCHIVE_CRYPTO_SHA256_LIBC */ + +/* SHA256 via ARCHIVE_CRYPTO_SHA256_LIBC2 supported. */ +/* #undef ARCHIVE_CRYPTO_SHA256_LIBC2 */ + +/* SHA256 via ARCHIVE_CRYPTO_SHA256_LIBC3 supported. */ +/* #undef ARCHIVE_CRYPTO_SHA256_LIBC3 */ + +/* SHA256 via ARCHIVE_CRYPTO_SHA256_LIBMD supported. */ +/* #undef ARCHIVE_CRYPTO_SHA256_LIBMD */ + +/* SHA256 via ARCHIVE_CRYPTO_SHA256_LIBSYSTEM supported. */ +#define ARCHIVE_CRYPTO_SHA256_LIBSYSTEM 1 + +/* SHA256 via ARCHIVE_CRYPTO_SHA256_MBEDTLS supported. */ +/* #undef ARCHIVE_CRYPTO_SHA256_MBEDTLS */ + +/* SHA256 via ARCHIVE_CRYPTO_SHA256_NETTLE supported. */ +/* #undef ARCHIVE_CRYPTO_SHA256_NETTLE */ + +/* SHA256 via ARCHIVE_CRYPTO_SHA256_OPENSSL supported. */ +/* #undef ARCHIVE_CRYPTO_SHA256_OPENSSL */ + +/* SHA256 via ARCHIVE_CRYPTO_SHA256_WIN supported. */ +/* #undef ARCHIVE_CRYPTO_SHA256_WIN */ + +/* SHA384 via ARCHIVE_CRYPTO_SHA384_LIBC supported. */ +/* #undef ARCHIVE_CRYPTO_SHA384_LIBC */ + +/* SHA384 via ARCHIVE_CRYPTO_SHA384_LIBC2 supported. */ +/* #undef ARCHIVE_CRYPTO_SHA384_LIBC2 */ + +/* SHA384 via ARCHIVE_CRYPTO_SHA384_LIBC3 supported. */ +/* #undef ARCHIVE_CRYPTO_SHA384_LIBC3 */ + +/* SHA384 via ARCHIVE_CRYPTO_SHA384_LIBSYSTEM supported. */ +#define ARCHIVE_CRYPTO_SHA384_LIBSYSTEM 1 + +/* SHA384 via ARCHIVE_CRYPTO_SHA384_MBEDTLS supported. */ +/* #undef ARCHIVE_CRYPTO_SHA384_MBEDTLS */ + +/* SHA384 via ARCHIVE_CRYPTO_SHA384_NETTLE supported. */ +/* #undef ARCHIVE_CRYPTO_SHA384_NETTLE */ + +/* SHA384 via ARCHIVE_CRYPTO_SHA384_OPENSSL supported. */ +/* #undef ARCHIVE_CRYPTO_SHA384_OPENSSL */ + +/* SHA384 via ARCHIVE_CRYPTO_SHA384_WIN supported. */ +/* #undef ARCHIVE_CRYPTO_SHA384_WIN */ + +/* SHA512 via ARCHIVE_CRYPTO_SHA512_LIBC supported. */ +/* #undef ARCHIVE_CRYPTO_SHA512_LIBC */ + +/* SHA512 via ARCHIVE_CRYPTO_SHA512_LIBC2 supported. */ +/* #undef ARCHIVE_CRYPTO_SHA512_LIBC2 */ + +/* SHA512 via ARCHIVE_CRYPTO_SHA512_LIBC3 supported. */ +/* #undef ARCHIVE_CRYPTO_SHA512_LIBC3 */ + +/* SHA512 via ARCHIVE_CRYPTO_SHA512_LIBMD supported. */ +/* #undef ARCHIVE_CRYPTO_SHA512_LIBMD */ + +/* SHA512 via ARCHIVE_CRYPTO_SHA512_LIBSYSTEM supported. */ +#define ARCHIVE_CRYPTO_SHA512_LIBSYSTEM 1 + +/* SHA512 via ARCHIVE_CRYPTO_SHA512_MBEDTLS supported. */ +/* #undef ARCHIVE_CRYPTO_SHA512_MBEDTLS */ + +/* SHA512 via ARCHIVE_CRYPTO_SHA512_NETTLE supported. */ +/* #undef ARCHIVE_CRYPTO_SHA512_NETTLE */ + +/* SHA512 via ARCHIVE_CRYPTO_SHA512_OPENSSL supported. */ +/* #undef ARCHIVE_CRYPTO_SHA512_OPENSSL */ + +/* SHA512 via ARCHIVE_CRYPTO_SHA512_WIN supported. */ +/* #undef ARCHIVE_CRYPTO_SHA512_WIN */ + +/* AIX xattr support */ +/* #undef ARCHIVE_XATTR_AIX */ + +/* Darwin xattr support */ +#define ARCHIVE_XATTR_DARWIN 1 + +/* FreeBSD xattr support */ +/* #undef ARCHIVE_XATTR_FREEBSD */ + +/* Linux xattr support */ +/* #undef ARCHIVE_XATTR_LINUX */ + +/* Version number of bsdcat */ +#define BSDCAT_VERSION_STRING "3.4.3" + +/* Version number of bsdcpio */ +#define BSDCPIO_VERSION_STRING "3.4.3" + +/* Version number of bsdtar */ +#define BSDTAR_VERSION_STRING "3.4.3" + +/* Define to 1 if the system has the type `ace_t'. */ +/* #undef HAVE_ACE_T */ + +/* Define to 1 if you have the `acl' function. */ +/* #undef HAVE_ACL */ + +/* Define to 1 if the system has the type `aclent_t'. */ +/* #undef HAVE_ACLENT_T */ + +/* Define to 1 if you have the `acl_add_flag_np' function. */ +#define HAVE_ACL_ADD_FLAG_NP 1 + +/* Define to 1 if you have the `acl_add_perm' function. */ +#define HAVE_ACL_ADD_PERM 1 + +/* Define to 1 if you have the `acl_clear_flags_np' function. */ +#define HAVE_ACL_CLEAR_FLAGS_NP 1 + +/* Define to 1 if you have the `acl_clear_perms' function. */ +#define HAVE_ACL_CLEAR_PERMS 1 + +/* Define to 1 if you have the `acl_create_entry' function. */ +#define HAVE_ACL_CREATE_ENTRY 1 + +/* Define to 1 if you have the `acl_delete_def_file' function. */ +#define HAVE_ACL_DELETE_DEF_FILE 1 + +/* Define to 1 if the system has the type `acl_entry_t'. */ +#define HAVE_ACL_ENTRY_T 1 + +/* Define to 1 if you have the `acl_free' function. */ +#define HAVE_ACL_FREE 1 + +/* Define to 1 if you have the `acl_get_brand_np' function. */ +/* #undef HAVE_ACL_GET_BRAND_NP */ + +/* Define to 1 if you have the `acl_get_entry' function. */ +#define HAVE_ACL_GET_ENTRY 1 + +/* Define to 1 if you have the `acl_get_entry_type_np' function. */ +/* #undef HAVE_ACL_GET_ENTRY_TYPE_NP */ + +/* Define to 1 if you have the `acl_get_fd' function. */ +#define HAVE_ACL_GET_FD 1 + +/* Define to 1 if you have the `acl_get_fd_np' function. */ +#define HAVE_ACL_GET_FD_NP 1 + +/* Define to 1 if you have the `acl_get_file' function. */ +#define HAVE_ACL_GET_FILE 1 + +/* Define to 1 if you have the `acl_get_flagset_np' function. */ +#define HAVE_ACL_GET_FLAGSET_NP 1 + +/* Define to 1 if you have the `acl_get_flag_np' function. */ +#define HAVE_ACL_GET_FLAG_NP 1 + +/* Define to 1 if you have the `acl_get_link_np' function. */ +#define HAVE_ACL_GET_LINK_NP 1 + +/* Define to 1 if you have the `acl_get_perm' function. */ +/* #undef HAVE_ACL_GET_PERM */ + +/* Define to 1 if you have the `acl_get_permset' function. */ +#define HAVE_ACL_GET_PERMSET 1 + +/* Define to 1 if you have the `acl_get_perm_np' function. */ +#define HAVE_ACL_GET_PERM_NP 1 + +/* Define to 1 if you have the `acl_get_qualifier' function. */ +#define HAVE_ACL_GET_QUALIFIER 1 + +/* Define to 1 if you have the `acl_get_tag_type' function. */ +#define HAVE_ACL_GET_TAG_TYPE 1 + +/* Define to 1 if you have the `acl_init' function. */ +#define HAVE_ACL_INIT 1 + +/* Define to 1 if you have the `acl_is_trivial_np' function. */ +/* #undef HAVE_ACL_IS_TRIVIAL_NP */ + +/* Define to 1 if you have the <acl/libacl.h> header file. */ +/* #undef HAVE_ACL_LIBACL_H */ + +/* Define to 1 if the system has the type `acl_permset_t'. */ +#define HAVE_ACL_PERMSET_T 1 + +/* Define to 1 if you have the `acl_set_entry_type_np' function. */ +/* #undef HAVE_ACL_SET_ENTRY_TYPE_NP */ + +/* Define to 1 if you have the `acl_set_fd' function. */ +#define HAVE_ACL_SET_FD 1 + +/* Define to 1 if you have the `acl_set_fd_np' function. */ +#define HAVE_ACL_SET_FD_NP 1 + +/* Define to 1 if you have the `acl_set_file' function. */ +#define HAVE_ACL_SET_FILE 1 + +/* Define to 1 if you have the `acl_set_link_np' function. */ +#define HAVE_ACL_SET_LINK_NP 1 + +/* Define to 1 if you have the `acl_set_qualifier' function. */ +#define HAVE_ACL_SET_QUALIFIER 1 + +/* Define to 1 if you have the `acl_set_tag_type' function. */ +#define HAVE_ACL_SET_TAG_TYPE 1 + +/* Define to 1 if the system has the type `acl_t'. */ +#define HAVE_ACL_T 1 + +/* Define to 1 if the system has the type `acl_tag_t'. */ +#define HAVE_ACL_TAG_T 1 + +/* Define to 1 if you have the `arc4random_buf' function. */ +#define HAVE_ARC4RANDOM_BUF 1 + +/* Define to 1 if you have the <attr/xattr.h> header file. */ +/* #undef HAVE_ATTR_XATTR_H */ + +/* Define to 1 if you have the <bcrypt.h> header file. */ +/* #undef HAVE_BCRYPT_H */ + +/* Define to 1 if you have the <blake2.h> header file. */ +/* #undef HAVE_BLAKE2_H */ + +/* Define to 1 if you have the <bzlib.h> header file. */ +#define HAVE_BZLIB_H 1 + +/* Define to 1 if you have the `chflags' function. */ +#define HAVE_CHFLAGS 1 + +/* Define to 1 if you have the `chown' function. */ +#define HAVE_CHOWN 1 + +/* Define to 1 if you have the `chroot' function. */ +#define HAVE_CHROOT 1 + +/* Define to 1 if you have the <copyfile.h> header file. */ +#define HAVE_COPYFILE_H 1 + +/* Define to 1 if you have the `ctime_r' function. */ +#define HAVE_CTIME_R 1 + +/* Define to 1 if you have the <ctype.h> header file. */ +#define HAVE_CTYPE_H 1 + +/* Define to 1 if you have the `cygwin_conv_path' function. */ +/* #undef HAVE_CYGWIN_CONV_PATH */ + +/* Define to 1 if you have the declaration of `ACE_GETACL', and to 0 if you + don't. */ +/* #undef HAVE_DECL_ACE_GETACL */ + +/* Define to 1 if you have the declaration of `ACE_GETACLCNT', and to 0 if you + don't. */ +/* #undef HAVE_DECL_ACE_GETACLCNT */ + +/* Define to 1 if you have the declaration of `ACE_SETACL', and to 0 if you + don't. */ +/* #undef HAVE_DECL_ACE_SETACL */ + +/* Define to 1 if you have the declaration of `ACL_SYNCHRONIZE', and to 0 if + you don't. */ +#define HAVE_DECL_ACL_SYNCHRONIZE 1 + +/* Define to 1 if you have the declaration of `ACL_TYPE_EXTENDED', and to 0 if + you don't. */ +#define HAVE_DECL_ACL_TYPE_EXTENDED 1 + +/* Define to 1 if you have the declaration of `ACL_TYPE_NFS4', and to 0 if you + don't. */ +#define HAVE_DECL_ACL_TYPE_NFS4 0 + +/* Define to 1 if you have the declaration of `ACL_USER', and to 0 if you + don't. */ +#define HAVE_DECL_ACL_USER 0 + +/* Define to 1 if you have the declaration of `EXTATTR_NAMESPACE_USER', and to + 0 if you don't. */ +#define HAVE_DECL_EXTATTR_NAMESPACE_USER 0 + +/* Define to 1 if you have the declaration of `GETACL', and to 0 if you don't. + */ +/* #undef HAVE_DECL_GETACL */ + +/* Define to 1 if you have the declaration of `GETACLCNT', and to 0 if you + don't. */ +/* #undef HAVE_DECL_GETACLCNT */ + +/* Define to 1 if you have the declaration of `INT32_MAX', and to 0 if you + don't. */ +#define HAVE_DECL_INT32_MAX 1 + +/* Define to 1 if you have the declaration of `INT32_MIN', and to 0 if you + don't. */ +#define HAVE_DECL_INT32_MIN 1 + +/* Define to 1 if you have the declaration of `INT64_MAX', and to 0 if you + don't. */ +#define HAVE_DECL_INT64_MAX 1 + +/* Define to 1 if you have the declaration of `INT64_MIN', and to 0 if you + don't. */ +#define HAVE_DECL_INT64_MIN 1 + +/* Define to 1 if you have the declaration of `INTMAX_MAX', and to 0 if you + don't. */ +#define HAVE_DECL_INTMAX_MAX 1 + +/* Define to 1 if you have the declaration of `INTMAX_MIN', and to 0 if you + don't. */ +#define HAVE_DECL_INTMAX_MIN 1 + +/* Define to 1 if you have the declaration of `SETACL', and to 0 if you don't. + */ +/* #undef HAVE_DECL_SETACL */ + +/* Define to 1 if you have the declaration of `SIZE_MAX', and to 0 if you + don't. */ +#define HAVE_DECL_SIZE_MAX 1 + +/* Define to 1 if you have the declaration of `SSIZE_MAX', and to 0 if you + don't. */ +#define HAVE_DECL_SSIZE_MAX 1 + +/* Define to 1 if you have the declaration of `strerror_r', and to 0 if you + don't. */ +#define HAVE_DECL_STRERROR_R 1 + +/* Define to 1 if you have the declaration of `UINT32_MAX', and to 0 if you + don't. */ +#define HAVE_DECL_UINT32_MAX 1 + +/* Define to 1 if you have the declaration of `UINT64_MAX', and to 0 if you + don't. */ +#define HAVE_DECL_UINT64_MAX 1 + +/* Define to 1 if you have the declaration of `UINTMAX_MAX', and to 0 if you + don't. */ +#define HAVE_DECL_UINTMAX_MAX 1 + +/* Define to 1 if you have the declaration of `XATTR_NOFOLLOW', and to 0 if + you don't. */ +#define HAVE_DECL_XATTR_NOFOLLOW 1 + +/* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'. + */ +#define HAVE_DIRENT_H 1 + +/* Define to 1 if you have a dirfd function or macro */ +#define HAVE_DIRFD 1 + +/* Define to 1 if you have the <dlfcn.h> header file. */ +#define HAVE_DLFCN_H 1 + +/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */ +/* #undef HAVE_DOPRNT */ + +/* Define to 1 if nl_langinfo supports D_MD_ORDER */ +#define HAVE_D_MD_ORDER 1 + +/* A possible errno value for invalid file format errors */ +#define HAVE_EFTYPE 1 + +/* A possible errno value for invalid file format errors */ +#define HAVE_EILSEQ 1 + +/* Define to 1 if you have the <errno.h> header file. */ +#define HAVE_ERRNO_H 1 + +/* Define to 1 if you have the <expat.h> header file. */ +/* #undef HAVE_EXPAT_H */ + +/* Define to 1 if you have the <ext2fs/ext2_fs.h> header file. */ +/* #undef HAVE_EXT2FS_EXT2_FS_H */ + +/* Define to 1 if you have the `extattr_get_fd' function. */ +/* #undef HAVE_EXTATTR_GET_FD */ + +/* Define to 1 if you have the `extattr_get_file' function. */ +/* #undef HAVE_EXTATTR_GET_FILE */ + +/* Define to 1 if you have the `extattr_get_link' function. */ +/* #undef HAVE_EXTATTR_GET_LINK */ + +/* Define to 1 if you have the `extattr_list_fd' function. */ +/* #undef HAVE_EXTATTR_LIST_FD */ + +/* Define to 1 if you have the `extattr_list_file' function. */ +/* #undef HAVE_EXTATTR_LIST_FILE */ + +/* Define to 1 if you have the `extattr_list_link' function. */ +/* #undef HAVE_EXTATTR_LIST_LINK */ + +/* Define to 1 if you have the `extattr_set_fd' function. */ +/* #undef HAVE_EXTATTR_SET_FD */ + +/* Define to 1 if you have the `extattr_set_link' function. */ +/* #undef HAVE_EXTATTR_SET_LINK */ + +/* Define to 1 if you have the `facl' function. */ +/* #undef HAVE_FACL */ + +/* Define to 1 if you have the `fchdir' function. */ +#define HAVE_FCHDIR 1 + +/* Define to 1 if you have the `fchflags' function. */ +#define HAVE_FCHFLAGS 1 + +/* Define to 1 if you have the `fchmod' function. */ +#define HAVE_FCHMOD 1 + +/* Define to 1 if you have the `fchown' function. */ +#define HAVE_FCHOWN 1 + +/* Define to 1 if you have the `fcntl' function. */ +#define HAVE_FCNTL 1 + +/* Define to 1 if you have the <fcntl.h> header file. */ +#define HAVE_FCNTL_H 1 + +/* Define to 1 if you have the `fdopendir' function. */ +#define HAVE_FDOPENDIR 1 + +/* Define to 1 if you have the `fgetea' function. */ +/* #undef HAVE_FGETEA */ + +/* Define to 1 if you have the `fgetxattr' function. */ +#define HAVE_FGETXATTR 1 + +/* Define to 1 if you have the `flistea' function. */ +/* #undef HAVE_FLISTEA */ + +/* Define to 1 if you have the `flistxattr' function. */ +#define HAVE_FLISTXATTR 1 + +/* Define to 1 if you have the `fork' function. */ +#define HAVE_FORK 1 + +/* Define to 1 if fseeko (and presumably ftello) exists and is declared. */ +#define HAVE_FSEEKO 1 + +/* Define to 1 if you have the `fsetea' function. */ +/* #undef HAVE_FSETEA */ + +/* Define to 1 if you have the `fsetxattr' function. */ +#define HAVE_FSETXATTR 1 + +/* Define to 1 if you have the `fstat' function. */ +#define HAVE_FSTAT 1 + +/* Define to 1 if you have the `fstatat' function. */ +#define HAVE_FSTATAT 1 + +/* Define to 1 if you have the `fstatfs' function. */ +#define HAVE_FSTATFS 1 + +/* Define to 1 if you have the `fstatvfs' function. */ +#define HAVE_FSTATVFS 1 + +/* Define to 1 if you have the `ftruncate' function. */ +#define HAVE_FTRUNCATE 1 + +/* Define to 1 if you have the `futimens' function. */ +#define HAVE_FUTIMENS 1 + +/* Define to 1 if you have the `futimes' function. */ +#define HAVE_FUTIMES 1 + +/* Define to 1 if you have the `futimesat' function. */ +/* #undef HAVE_FUTIMESAT */ + +/* Define to 1 if you have the `getea' function. */ +/* #undef HAVE_GETEA */ + +/* Define to 1 if you have the `geteuid' function. */ +#define HAVE_GETEUID 1 + +/* Define to 1 if you have the `getgrgid_r' function. */ +#define HAVE_GETGRGID_R 1 + +/* Define to 1 if you have the `getgrnam_r' function. */ +#define HAVE_GETGRNAM_R 1 + +/* Define to 1 if you have the `getpid' function. */ +#define HAVE_GETPID 1 + +/* Define to 1 if you have the `getpwnam_r' function. */ +#define HAVE_GETPWNAM_R 1 + +/* Define to 1 if you have the `getpwuid_r' function. */ +#define HAVE_GETPWUID_R 1 + +/* Define to 1 if you have the `getvfsbyname' function. */ +#define HAVE_GETVFSBYNAME 1 + +/* Define to 1 if you have the `getxattr' function. */ +#define HAVE_GETXATTR 1 + +/* Define to 1 if you have the `gmtime_r' function. */ +#define HAVE_GMTIME_R 1 + +/* Define to 1 if you have the <grp.h> header file. */ +#define HAVE_GRP_H 1 + +/* Define if you have the iconv() function and it works. */ +#define HAVE_ICONV 1 + +/* Define to 1 if you have the <iconv.h> header file. */ +#define HAVE_ICONV_H 1 + +/* Define to 1 if the system has the type `intmax_t'. */ +#define HAVE_INTMAX_T 1 + +/* Define to 1 if you have the <inttypes.h> header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the <io.h> header file. */ +/* #undef HAVE_IO_H */ + +/* Define to 1 if you have the <langinfo.h> header file. */ +#define HAVE_LANGINFO_H 1 + +/* Define to 1 if you have the `lchflags' function. */ +#define HAVE_LCHFLAGS 1 + +/* Define to 1 if you have the `lchmod' function. */ +#define HAVE_LCHMOD 1 + +/* Define to 1 if you have the `lchown' function. */ +#define HAVE_LCHOWN 1 + +/* Define to 1 if you have the `lgetea' function. */ +/* #undef HAVE_LGETEA */ + +/* Define to 1 if you have the `lgetxattr' function. */ +/* #undef HAVE_LGETXATTR */ + +/* Define to 1 if you have the `acl' library (-lacl). */ +/* #undef HAVE_LIBACL */ + +/* Define to 1 if you have the `b2' library (-lb2). */ +/* #undef HAVE_LIBB2 */ + +/* Define to 1 if you have the `bz2' library (-lbz2). */ +#define HAVE_LIBBZ2 1 + +/* Define to 1 if you have the `charset' library (-lcharset). */ +/* #undef HAVE_LIBCHARSET */ + +/* Define to 1 if you have the `crypto' library (-lcrypto). */ +/* #undef HAVE_LIBCRYPTO */ + +/* Define to 1 if you have the `eay32' library (-leay32). */ +/* #undef HAVE_LIBEAY32 */ + +/* Define to 1 if you have the `eay64' library (-leay64). */ +/* #undef HAVE_LIBEAY64 */ + +/* Define to 1 if you have the `expat' library (-lexpat). */ +/* #undef HAVE_LIBEXPAT */ + +/* Define to 1 if you have the `lz4' library (-llz4). */ +/* #undef HAVE_LIBLZ4 */ + +/* Define to 1 if you have the `lzma' library (-llzma). */ +#define HAVE_LIBLZMA 1 + +/* Define to 1 if you have the `lzo2' library (-llzo2). */ +/* #undef HAVE_LIBLZO2 */ + +/* Define to 1 if you have the `mbedcrypto' library (-lmbedcrypto). */ +/* #undef HAVE_LIBMBEDCRYPTO */ + +/* Define to 1 if you have the `md' library (-lmd). */ +/* #undef HAVE_LIBMD */ + +/* Define to 1 if you have the `nettle' library (-lnettle). */ +/* #undef HAVE_LIBNETTLE */ + +/* Define to 1 if you have the `pcre' library (-lpcre). */ +/* #undef HAVE_LIBPCRE */ + +/* Define to 1 if you have the `pcreposix' library (-lpcreposix). */ +/* #undef HAVE_LIBPCREPOSIX */ + +/* Define to 1 if you have the `regex' library (-lregex). */ +/* #undef HAVE_LIBREGEX */ + +/* Define to 1 if you have the `richacl' library (-lrichacl). */ +/* #undef HAVE_LIBRICHACL */ + +/* Define to 1 if you have the `xml2' library (-lxml2). */ +/* #undef HAVE_LIBXML2 */ + +/* Define to 1 if you have the <libxml/xmlreader.h> header file. */ +#define HAVE_LIBXML_XMLREADER_H 1 + +/* Define to 1 if you have the <libxml/xmlwriter.h> header file. */ +#define HAVE_LIBXML_XMLWRITER_H 1 + +/* Define to 1 if you have the `z' library (-lz). */ +#define HAVE_LIBZ 1 + +/* Define to 1 if you have the `zstd' library (-lzstd). */ +/* #undef HAVE_LIBZSTD */ + +/* Define to 1 if you have the <limits.h> header file. */ +#define HAVE_LIMITS_H 1 + +/* Define to 1 if you have the `link' function. */ +#define HAVE_LINK 1 + +/* Define to 1 if you have the <linux/fiemap.h> header file. */ +/* #undef HAVE_LINUX_FIEMAP_H */ + +/* Define to 1 if you have the <linux/fs.h> header file. */ +/* #undef HAVE_LINUX_FS_H */ + +/* Define to 1 if you have the <linux/magic.h> header file. */ +/* #undef HAVE_LINUX_MAGIC_H */ + +/* Define to 1 if you have the <linux/types.h> header file. */ +/* #undef HAVE_LINUX_TYPES_H */ + +/* Define to 1 if you have the `listea' function. */ +/* #undef HAVE_LISTEA */ + +/* Define to 1 if you have the `listxattr' function. */ +#define HAVE_LISTXATTR 1 + +/* Define to 1 if you have the `llistea' function. */ +/* #undef HAVE_LLISTEA */ + +/* Define to 1 if you have the `llistxattr' function. */ +/* #undef HAVE_LLISTXATTR */ + +/* Define to 1 if you have the <localcharset.h> header file. */ +/* #undef HAVE_LOCALCHARSET_H */ + +/* Define to 1 if you have the `locale_charset' function. */ +#define HAVE_LOCALE_CHARSET 1 + +/* Define to 1 if you have the <locale.h> header file. */ +#define HAVE_LOCALE_H 1 + +/* Define to 1 if you have the `localtime_r' function. */ +#define HAVE_LOCALTIME_R 1 + +/* Define to 1 if the system has the type `long long int'. */ +#define HAVE_LONG_LONG_INT 1 + +/* Define to 1 if you have the `lsetea' function. */ +/* #undef HAVE_LSETEA */ + +/* Define to 1 if you have the `lsetxattr' function. */ +/* #undef HAVE_LSETXATTR */ + +/* Define to 1 if you have the `lstat' function. */ +#define HAVE_LSTAT 1 + +/* Define to 1 if `lstat' has the bug that it succeeds when given the + zero-length file name argument. */ +#define HAVE_LSTAT_EMPTY_STRING_BUG 1 + +/* Define to 1 if you have the `lutimes' function. */ +#define HAVE_LUTIMES 1 + +/* Define to 1 if you have the <lz4hc.h> header file. */ +/* #undef HAVE_LZ4HC_H */ + +/* Define to 1 if you have the <lz4.h> header file. */ +/* #undef HAVE_LZ4_H */ + +/* Define to 1 if you have the <lzma.h> header file. */ +/* #undef HAVE_LZMA_H */ + +/* Define to 1 if you have the `lzma_stream_encoder_mt' function. */ +/* #undef HAVE_LZMA_STREAM_ENCODER_MT */ + +/* Define to 1 if you have the <lzo/lzo1x.h> header file. */ +/* #undef HAVE_LZO_LZO1X_H */ + +/* Define to 1 if you have the <lzo/lzoconf.h> header file. */ +/* #undef HAVE_LZO_LZOCONF_H */ + +/* Define to 1 if you have the <mbedtls/aes.h> header file. */ +/* #undef HAVE_MBEDTLS_AES_H */ + +/* Define to 1 if you have the <mbedtls/md.h> header file. */ +/* #undef HAVE_MBEDTLS_MD_H */ + +/* Define to 1 if you have the <mbedtls/pkcs5.h> header file. */ +/* #undef HAVE_MBEDTLS_PKCS5_H */ + +/* Define to 1 if you have the `mbrtowc' function. */ +#define HAVE_MBRTOWC 1 + +/* Define to 1 if you have the `mbr_gid_to_uuid' function. */ +#define HAVE_MBR_GID_TO_UUID 1 + +/* Define to 1 if you have the `mbr_uid_to_uuid' function. */ +#define HAVE_MBR_UID_TO_UUID 1 + +/* Define to 1 if you have the `mbr_uuid_to_id' function. */ +#define HAVE_MBR_UUID_TO_ID 1 + +/* Define to 1 if you have the <md5.h> header file. */ +/* #undef HAVE_MD5_H */ + +/* Define to 1 if you have the <membership.h> header file. */ +#define HAVE_MEMBERSHIP_H 1 + +/* Define to 1 if you have the `memmove' function. */ +#define HAVE_MEMMOVE 1 + +/* Define to 1 if you have the <memory.h> header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the `memset' function. */ +#define HAVE_MEMSET 1 + +/* Define to 1 if you have the `mkdir' function. */ +#define HAVE_MKDIR 1 + +/* Define to 1 if you have the `mkfifo' function. */ +#define HAVE_MKFIFO 1 + +/* Define to 1 if you have the `mknod' function. */ +#define HAVE_MKNOD 1 + +/* Define to 1 if you have the `mkstemp' function. */ +#define HAVE_MKSTEMP 1 + +/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */ +/* #undef HAVE_NDIR_H */ + +/* Define to 1 if you have the <nettle/aes.h> header file. */ +/* #undef HAVE_NETTLE_AES_H */ + +/* Define to 1 if you have the <nettle/hmac.h> header file. */ +/* #undef HAVE_NETTLE_HMAC_H */ + +/* Define to 1 if you have the <nettle/md5.h> header file. */ +/* #undef HAVE_NETTLE_MD5_H */ + +/* Define to 1 if you have the <nettle/pbkdf2.h> header file. */ +/* #undef HAVE_NETTLE_PBKDF2_H */ + +/* Define to 1 if you have the <nettle/ripemd160.h> header file. */ +/* #undef HAVE_NETTLE_RIPEMD160_H */ + +/* Define to 1 if you have the <nettle/sha.h> header file. */ +/* #undef HAVE_NETTLE_SHA_H */ + +/* Define to 1 if you have the `nl_langinfo' function. */ +#define HAVE_NL_LANGINFO 1 + +/* Define to 1 if you have the `openat' function. */ +#define HAVE_OPENAT 1 + +/* Define to 1 if you have the <openssl/evp.h> header file. */ +/* #undef HAVE_OPENSSL_EVP_H */ + +/* Define to 1 if you have the <paths.h> header file. */ +#define HAVE_PATHS_H 1 + +/* Define to 1 if you have the <pcreposix.h> header file. */ +/* #undef HAVE_PCREPOSIX_H */ + +/* Define to 1 if you have the `pipe' function. */ +#define HAVE_PIPE 1 + +/* Define to 1 if you have the `PKCS5_PBKDF2_HMAC_SHA1' function. */ +/* #undef HAVE_PKCS5_PBKDF2_HMAC_SHA1 */ + +/* Define to 1 if you have the `poll' function. */ +#define HAVE_POLL 1 + +/* Define to 1 if you have the <poll.h> header file. */ +#define HAVE_POLL_H 1 + +/* Define to 1 if you have the `posix_spawnp' function. */ +#define HAVE_POSIX_SPAWNP 1 + +/* Define to 1 if you have the <pthread.h> header file. */ +#define HAVE_PTHREAD_H 1 + +/* Define to 1 if you have the <pwd.h> header file. */ +#define HAVE_PWD_H 1 + +/* Define to 1 if you have a POSIX compatible readdir_r */ +#define HAVE_READDIR_R 1 + +/* Define to 1 if you have the `readlink' function. */ +#define HAVE_READLINK 1 + +/* Define to 1 if you have the `readlinkat' function. */ +#define HAVE_READLINKAT 1 + +/* Define to 1 if you have the `readpassphrase' function. */ +#define HAVE_READPASSPHRASE 1 + +/* Define to 1 if you have the <readpassphrase.h> header file. */ +#define HAVE_READPASSPHRASE_H 1 + +/* Define to 1 if you have the <regex.h> header file. */ +#define HAVE_REGEX_H 1 + +/* Define to 1 if you have the `richacl_alloc' function. */ +/* #undef HAVE_RICHACL_ALLOC */ + +/* Define to 1 if you have the `richacl_equiv_mode' function. */ +/* #undef HAVE_RICHACL_EQUIV_MODE */ + +/* Define to 1 if you have the `richacl_free' function. */ +/* #undef HAVE_RICHACL_FREE */ + +/* Define to 1 if you have the `richacl_get_fd' function. */ +/* #undef HAVE_RICHACL_GET_FD */ + +/* Define to 1 if you have the `richacl_get_file' function. */ +/* #undef HAVE_RICHACL_GET_FILE */ + +/* Define to 1 if you have the `richacl_set_fd' function. */ +/* #undef HAVE_RICHACL_SET_FD */ + +/* Define to 1 if you have the `richacl_set_file' function. */ +/* #undef HAVE_RICHACL_SET_FILE */ + +/* Define to 1 if you have the <ripemd.h> header file. */ +/* #undef HAVE_RIPEMD_H */ + +/* Define to 1 if you have the `select' function. */ +#define HAVE_SELECT 1 + +/* Define to 1 if you have the `setenv' function. */ +#define HAVE_SETENV 1 + +/* Define to 1 if you have the `setlocale' function. */ +#define HAVE_SETLOCALE 1 + +/* Define to 1 if you have the `setxattr' function. */ +#define HAVE_SETXATTR 1 + +/* Define to 1 if you have the <sha256.h> header file. */ +/* #undef HAVE_SHA256_H */ + +/* Define to 1 if you have the <sha512.h> header file. */ +/* #undef HAVE_SHA512_H */ + +/* Define to 1 if you have the <sha.h> header file. */ +/* #undef HAVE_SHA_H */ + +/* Define to 1 if you have the `sigaction' function. */ +#define HAVE_SIGACTION 1 + +/* Define to 1 if you have the <signal.h> header file. */ +#define HAVE_SIGNAL_H 1 + +/* Define to 1 if you have the <spawn.h> header file. */ +#define HAVE_SPAWN_H 1 + +/* Define to 1 if you have the `statfs' function. */ +#define HAVE_STATFS 1 + +/* Define to 1 if you have the `statvfs' function. */ +#define HAVE_STATVFS 1 + +/* Define to 1 if `stat' has the bug that it succeeds when given the + zero-length file name argument. */ +#define HAVE_STAT_EMPTY_STRING_BUG 1 + +/* Define to 1 if you have the <stdarg.h> header file. */ +#define HAVE_STDARG_H 1 + +/* Define to 1 if you have the <stdint.h> header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the <stdlib.h> header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the `strchr' function. */ +#define HAVE_STRCHR 1 + +/* Define to 1 if you have the `strdup' function. */ +#define HAVE_STRDUP 1 + +/* Define to 1 if you have the `strerror' function. */ +#define HAVE_STRERROR 1 + +/* Define to 1 if you have the `strerror_r' function. */ +#define HAVE_STRERROR_R 1 + +/* Define to 1 if you have the `strftime' function. */ +#define HAVE_STRFTIME 1 + +/* Define to 1 if you have the <strings.h> header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the <string.h> header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the `strncpy_s' function. */ +/* #undef HAVE_STRNCPY_S */ + +/* Define to 1 if you have the `strrchr' function. */ +#define HAVE_STRRCHR 1 + +/* Define to 1 if the system has the type `struct richace'. */ +/* #undef HAVE_STRUCT_RICHACE */ + +/* Define to 1 if the system has the type `struct richacl'. */ +/* #undef HAVE_STRUCT_RICHACL */ + +/* Define to 1 if `f_namemax' is a member of `struct statfs'. */ +/* #undef HAVE_STRUCT_STATFS_F_NAMEMAX */ + +/* Define to 1 if `f_iosize' is a member of `struct statvfs'. */ +/* #undef HAVE_STRUCT_STATVFS_F_IOSIZE */ + +/* Define to 1 if `st_birthtime' is a member of `struct stat'. */ +#define HAVE_STRUCT_STAT_ST_BIRTHTIME 1 + +/* Define to 1 if `st_birthtimespec.tv_nsec' is a member of `struct stat'. */ +#define HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC 1 + +/* Define to 1 if `st_blksize' is a member of `struct stat'. */ +#define HAVE_STRUCT_STAT_ST_BLKSIZE 1 + +/* Define to 1 if `st_flags' is a member of `struct stat'. */ +#define HAVE_STRUCT_STAT_ST_FLAGS 1 + +/* Define to 1 if `st_mtimespec.tv_nsec' is a member of `struct stat'. */ +#define HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC 1 + +/* Define to 1 if `st_mtime_n' is a member of `struct stat'. */ +/* #undef HAVE_STRUCT_STAT_ST_MTIME_N */ + +/* Define to 1 if `st_mtime_usec' is a member of `struct stat'. */ +/* #undef HAVE_STRUCT_STAT_ST_MTIME_USEC */ + +/* Define to 1 if `st_mtim.tv_nsec' is a member of `struct stat'. */ +/* #undef HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC */ + +/* Define to 1 if `st_umtime' is a member of `struct stat'. */ +/* #undef HAVE_STRUCT_STAT_ST_UMTIME */ + +/* Define to 1 if `tm_gmtoff' is a member of `struct tm'. */ +#define HAVE_STRUCT_TM_TM_GMTOFF 1 + +/* Define to 1 if `__tm_gmtoff' is a member of `struct tm'. */ +/* #undef HAVE_STRUCT_TM___TM_GMTOFF */ + +/* Define to 1 if the system has the type `struct vfsconf'. */ +#define HAVE_STRUCT_VFSCONF 1 + +/* Define to 1 if the system has the type `struct xvfsconf'. */ +/* #undef HAVE_STRUCT_XVFSCONF */ + +/* Define to 1 if you have the `symlink' function. */ +#define HAVE_SYMLINK 1 + +/* Define to 1 if you have the <sys/acl.h> header file. */ +#define HAVE_SYS_ACL_H 1 + +/* Define to 1 if you have the <sys/cdefs.h> header file. */ +#define HAVE_SYS_CDEFS_H 1 + +/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'. + */ +/* #undef HAVE_SYS_DIR_H */ + +/* Define to 1 if you have the <sys/ea.h> header file. */ +/* #undef HAVE_SYS_EA_H */ + +/* Define to 1 if you have the <sys/extattr.h> header file. */ +/* #undef HAVE_SYS_EXTATTR_H */ + +/* Define to 1 if you have the <sys/ioctl.h> header file. */ +#define HAVE_SYS_IOCTL_H 1 + +/* Define to 1 if you have the <sys/mkdev.h> header file. */ +/* #undef HAVE_SYS_MKDEV_H */ + +/* Define to 1 if you have the <sys/mount.h> header file. */ +#define HAVE_SYS_MOUNT_H 1 + +/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'. + */ +/* #undef HAVE_SYS_NDIR_H */ + +/* Define to 1 if you have the <sys/param.h> header file. */ +#define HAVE_SYS_PARAM_H 1 + +/* Define to 1 if you have the <sys/poll.h> header file. */ +#define HAVE_SYS_POLL_H 1 + +/* Define to 1 if you have the <sys/richacl.h> header file. */ +/* #undef HAVE_SYS_RICHACL_H */ + +/* Define to 1 if you have the <sys/select.h> header file. */ +#define HAVE_SYS_SELECT_H 1 + +/* Define to 1 if you have the <sys/statfs.h> header file. */ +/* #undef HAVE_SYS_STATFS_H */ + +/* Define to 1 if you have the <sys/statvfs.h> header file. */ +#define HAVE_SYS_STATVFS_H 1 + +/* Define to 1 if you have the <sys/stat.h> header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the <sys/sysmacros.h> header file. */ +/* #undef HAVE_SYS_SYSMACROS_H */ + +/* Define to 1 if you have the <sys/time.h> header file. */ +#define HAVE_SYS_TIME_H 1 + +/* Define to 1 if you have the <sys/types.h> header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the <sys/utime.h> header file. */ +/* #undef HAVE_SYS_UTIME_H */ + +/* Define to 1 if you have the <sys/utsname.h> header file. */ +#define HAVE_SYS_UTSNAME_H 1 + +/* Define to 1 if you have the <sys/vfs.h> header file. */ +/* #undef HAVE_SYS_VFS_H */ + +/* Define to 1 if you have <sys/wait.h> that is POSIX.1 compatible. */ +#define HAVE_SYS_WAIT_H 1 + +/* Define to 1 if you have the <sys/xattr.h> header file. */ +#define HAVE_SYS_XATTR_H 1 + +/* Define to 1 if you have the `timegm' function. */ +#define HAVE_TIMEGM 1 + +/* Define to 1 if you have the <time.h> header file. */ +#define HAVE_TIME_H 1 + +/* Define to 1 if you have the `tzset' function. */ +#define HAVE_TZSET 1 + +/* Define to 1 if the system has the type `uintmax_t'. */ +#define HAVE_UINTMAX_T 1 + +/* Define to 1 if you have the <unistd.h> header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if you have the `unlinkat' function. */ +#define HAVE_UNLINKAT 1 + +/* Define to 1 if you have the `unsetenv' function. */ +#define HAVE_UNSETENV 1 + +/* Define to 1 if the system has the type `unsigned long long'. */ +#define HAVE_UNSIGNED_LONG_LONG 1 + +/* Define to 1 if the system has the type `unsigned long long int'. */ +#define HAVE_UNSIGNED_LONG_LONG_INT 1 + +/* Define to 1 if you have the `utime' function. */ +#define HAVE_UTIME 1 + +/* Define to 1 if you have the `utimensat' function. */ +#define HAVE_UTIMENSAT 1 + +/* Define to 1 if you have the `utimes' function. */ +#define HAVE_UTIMES 1 + +/* Define to 1 if you have the <utime.h> header file. */ +#define HAVE_UTIME_H 1 + +/* Define to 1 if you have the `vfork' function. */ +#define HAVE_VFORK 1 + +/* Define to 1 if you have the `vprintf' function. */ +#define HAVE_VPRINTF 1 + +/* Define to 1 if you have the <wchar.h> header file. */ +#define HAVE_WCHAR_H 1 + +/* Define to 1 if the system has the type `wchar_t'. */ +#define HAVE_WCHAR_T 1 + +/* Define to 1 if you have the `wcrtomb' function. */ +#define HAVE_WCRTOMB 1 + +/* Define to 1 if you have the `wcscmp' function. */ +#define HAVE_WCSCMP 1 + +/* Define to 1 if you have the `wcscpy' function. */ +#define HAVE_WCSCPY 1 + +/* Define to 1 if you have the `wcslen' function. */ +#define HAVE_WCSLEN 1 + +/* Define to 1 if you have the `wctomb' function. */ +#define HAVE_WCTOMB 1 + +/* Define to 1 if you have the <wctype.h> header file. */ +#define HAVE_WCTYPE_H 1 + +/* Define to 1 if you have the <wincrypt.h> header file. */ +/* #undef HAVE_WINCRYPT_H */ + +/* Define to 1 if you have the <windows.h> header file. */ +/* #undef HAVE_WINDOWS_H */ + +/* Define to 1 if you have the <winioctl.h> header file. */ +/* #undef HAVE_WINIOCTL_H */ + +/* Define to 1 if you have the `wmemcmp' function. */ +#define HAVE_WMEMCMP 1 + +/* Define to 1 if you have the `wmemcpy' function. */ +#define HAVE_WMEMCPY 1 + +/* Define to 1 if you have the `wmemmove' function. */ +#define HAVE_WMEMMOVE 1 + +/* Define to 1 if you have a working EXT2_IOC_GETFLAGS */ +/* #undef HAVE_WORKING_EXT2_IOC_GETFLAGS */ + +/* Define to 1 if you have a working FS_IOC_GETFLAGS */ +/* #undef HAVE_WORKING_FS_IOC_GETFLAGS */ + +/* Define to 1 if you have the <zlib.h> header file. */ +#define HAVE_ZLIB_H 1 + +/* Define to 1 if you have the <zstd.h> header file. */ +/* #undef HAVE_ZSTD_H */ + +/* Define to 1 if you have the `_ctime64_s' function. */ +/* #undef HAVE__CTIME64_S */ + +/* Define to 1 if you have the `_fseeki64' function. */ +/* #undef HAVE__FSEEKI64 */ + +/* Define to 1 if you have the `_get_timezone' function. */ +/* #undef HAVE__GET_TIMEZONE */ + +/* Define to 1 if you have the `_gmtime64_s' function. */ +/* #undef HAVE__GMTIME64_S */ + +/* Define to 1 if you have the `_localtime64_s' function. */ +/* #undef HAVE__LOCALTIME64_S */ + +/* Define to 1 if you have the `_mkgmtime64' function. */ +/* #undef HAVE__MKGMTIME64 */ + +/* Define as const if the declaration of iconv() needs const. */ +#define ICONV_CONST + +/* Version number of libarchive as a single integer */ +#define LIBARCHIVE_VERSION_NUMBER "3004003" + +/* Version number of libarchive */ +#define LIBARCHIVE_VERSION_STRING "3.4.3" + +/* Define to 1 if `lstat' dereferences a symlink specified with a trailing + slash. */ +/* #undef LSTAT_FOLLOWS_SLASHED_SYMLINK */ + +/* Define to the sub-directory where libtool stores uninstalled libraries. */ +#define LT_OBJDIR ".libs/" + +/* Define to 1 if `major', `minor', and `makedev' are declared in <mkdev.h>. + */ +/* #undef MAJOR_IN_MKDEV */ + +/* Define to 1 if `major', `minor', and `makedev' are declared in + <sysmacros.h>. */ +/* #undef MAJOR_IN_SYSMACROS */ + +/* Define to '0x05020000' for Windows Server 2003 APIs. */ +/* #undef NTDDI_VERSION */ + +/* Name of package */ +#define PACKAGE "libarchive" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "libarchive-discuss@googlegroups.com" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "libarchive" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "libarchive 3.4.3" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "libarchive" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "3.4.3" + +/* Define to 1 if PCRE_STATIC needs to be defined. */ +/* #undef PCRE_STATIC */ + +/* The size of `wchar_t', as computed by sizeof. */ +#define SIZEOF_WCHAR_T 4 + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define to 1 if strerror_r returns char *. */ +/* #undef STRERROR_R_CHAR_P */ + +/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */ +#define TIME_WITH_SYS_TIME 1 + +/* Enable extensions on AIX 3, Interix. */ +#ifndef _ALL_SOURCE +# define _ALL_SOURCE 1 +#endif +/* Enable GNU extensions on systems that have them. */ +#ifndef _GNU_SOURCE +# define _GNU_SOURCE 1 +#endif +/* Enable threading extensions on Solaris. */ +#ifndef _POSIX_PTHREAD_SEMANTICS +# define _POSIX_PTHREAD_SEMANTICS 1 +#endif +/* Enable extensions on HP NonStop. */ +#ifndef _TANDEM_SOURCE +# define _TANDEM_SOURCE 1 +#endif +/* Enable general extensions on Solaris. */ +#ifndef __EXTENSIONS__ +# define __EXTENSIONS__ 1 +#endif + + +/* Version number of package */ +#define VERSION "3.4.3" + +/* Define to '0x0502' for Windows Server 2003 APIs. */ +/* #undef WINVER */ + +/* Enable large inode numbers on Mac OS X 10.5. */ +#ifndef _DARWIN_USE_64_BIT_INODE +# define _DARWIN_USE_64_BIT_INODE 1 +#endif + +/* Number of bits in a file offset, on hosts where this is settable. */ +/* #undef _FILE_OFFSET_BITS */ + +/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */ +/* #undef _LARGEFILE_SOURCE */ + +/* Define for large files, on AIX-style hosts. */ +/* #undef _LARGE_FILES */ + +/* Define to 1 if on MINIX. */ +/* #undef _MINIX */ + +/* Define to 2 if the system does not provide POSIX.1 features except with + this defined. */ +/* #undef _POSIX_1_SOURCE */ + +/* Define to 1 if you need to in order for `stat' and other things to work. */ +/* #undef _POSIX_SOURCE */ + +/* Define for Solaris 2.5.1 so the uint32_t typedef from <sys/synch.h>, + <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the + #define below would cause a syntax error. */ +/* #undef _UINT32_T */ + +/* Define for Solaris 2.5.1 so the uint64_t typedef from <sys/synch.h>, + <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the + #define below would cause a syntax error. */ +/* #undef _UINT64_T */ + +/* Define for Solaris 2.5.1 so the uint8_t typedef from <sys/synch.h>, + <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the + #define below would cause a syntax error. */ +/* #undef _UINT8_T */ + +/* Define to '0x0502' for Windows Server 2003 APIs. */ +/* #undef _WIN32_WINNT */ + +/* Define to empty if `const' does not conform to ANSI C. */ +/* #undef const */ + +/* Define to match typeof st_gid field of struct stat if <sys/types.h> doesn't + define. */ +/* #undef gid_t */ + +/* Define to `unsigned long' if <sys/types.h> does not define. */ +/* #undef id_t */ + +/* Define to the type of a signed integer type of width exactly 16 bits if + such a type exists and the standard includes do not define it. */ +/* #undef int16_t */ + +/* Define to the type of a signed integer type of width exactly 32 bits if + such a type exists and the standard includes do not define it. */ +/* #undef int32_t */ + +/* Define to the type of a signed integer type of width exactly 64 bits if + such a type exists and the standard includes do not define it. */ +/* #undef int64_t */ + +/* Define to the widest signed integer type if <stdint.h> and <inttypes.h> do + not define. */ +/* #undef intmax_t */ + +/* Define to `int' if <sys/types.h> does not define. */ +/* #undef mode_t */ + +/* Define to `long long' if <sys/types.h> does not define. */ +/* #undef off_t */ + +/* Define to `unsigned int' if <sys/types.h> does not define. */ +/* #undef size_t */ + +/* Define to match typeof st_uid field of struct stat if <sys/types.h> doesn't + define. */ +/* #undef uid_t */ + +/* Define to the type of an unsigned integer type of width exactly 16 bits if + such a type exists and the standard includes do not define it. */ +/* #undef uint16_t */ + +/* Define to the type of an unsigned integer type of width exactly 32 bits if + such a type exists and the standard includes do not define it. */ +/* #undef uint32_t */ + +/* Define to the type of an unsigned integer type of width exactly 64 bits if + such a type exists and the standard includes do not define it. */ +/* #undef uint64_t */ + +/* Define to the type of an unsigned integer type of width exactly 8 bits if + such a type exists and the standard includes do not define it. */ +/* #undef uint8_t */ + +/* Define to the widest unsigned integer type if <stdint.h> and <inttypes.h> + do not define. */ +/* #undef uintmax_t */ + +/* Define to `unsigned int' if <sys/types.h> does not define. */ +/* #undef uintptr_t */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/COPYING b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/COPYING new file mode 100644 index 0000000000..14bbefa0d5 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/COPYING @@ -0,0 +1,66 @@ +The libarchive distribution as a whole is Copyright by Tim Kientzle +and is subject to the copyright notice reproduced at the bottom of +this file. + +Each individual file in this distribution should have a clear +copyright/licensing statement at the beginning of the file. If any do +not, please let me know and I will rectify it. The following is +intended to summarize the copyright status of the individual files; +the actual statements in the files are controlling. + +* Except as listed below, all C sources (including .c and .h files) + and documentation files are subject to the copyright notice reproduced + at the bottom of this file. + +* The following source files are also subject in whole or in part to + a 3-clause UC Regents copyright; please read the individual source + files for details: + libarchive/archive_entry.c + libarchive/archive_read_support_filter_compress.c + libarchive/archive_write_add_filter_compress.c + libarchive/mtree.5 + +* The following source files are in the public domain: + libarchive/archive_getdate.c + +* The following source files are triple-licensed with the ability to choose + from CC0 1.0 Universal, OpenSSL or Apache 2.0 licenses: + libarchive/archive_blake2.h + libarchive/archive_blake2_impl.h + libarchive/archive_blake2s_ref.c + libarchive/archive_blake2sp_ref.c + +* The build files---including Makefiles, configure scripts, + and auxiliary scripts used as part of the compile process---have + widely varying licensing terms. Please check individual files before + distributing them to see if those restrictions apply to you. + +I intend for all new source code to use the license below and hope over +time to replace code with other licenses with new implementations that +do use the license below. The varying licensing of the build scripts +seems to be an unavoidable mess. + + +Copyright (c) 2003-2018 <author(s)> +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 + in this position and unchanged. +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(S) ``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(S) 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. diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/README.md b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/README.md new file mode 100644 index 0000000000..56cd723daa --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/README.md @@ -0,0 +1,224 @@ +# Welcome to libarchive! + +The libarchive project develops a portable, efficient C library that +can read and write streaming archives in a variety of formats. It +also includes implementations of the common `tar`, `cpio`, and `zcat` +command-line tools that use the libarchive library. + +## Questions? Issues? + +* http://www.libarchive.org is the home for ongoing + libarchive development, including documentation, + and links to the libarchive mailing lists. +* To report an issue, use the issue tracker at + https://github.com/libarchive/libarchive/issues +* To submit an enhancement to libarchive, please + submit a pull request via GitHub: https://github.com/libarchive/libarchive/pulls + +## Contents of the Distribution + +This distribution bundle includes the following major components: + +* **libarchive**: a library for reading and writing streaming archives +* **tar**: the 'bsdtar' program is a full-featured 'tar' implementation built on libarchive +* **cpio**: the 'bsdcpio' program is a different interface to essentially the same functionality +* **cat**: the 'bsdcat' program is a simple replacement tool for zcat, bzcat, xzcat, and such +* **examples**: Some small example programs that you may find useful. +* **examples/minitar**: a compact sample demonstrating use of libarchive. +* **contrib**: Various items sent to me by third parties; please contact the authors with any questions. + +The top-level directory contains the following information files: + +* **NEWS** - highlights of recent changes +* **COPYING** - what you can do with this +* **INSTALL** - installation instructions +* **README** - this file +* **CMakeLists.txt** - input for "cmake" build tool, see INSTALL +* **configure** - configuration script, see INSTALL for details. If your copy of the source lacks a `configure` script, you can try to construct it by running the script in `build/autogen.sh` (or use `cmake`). + +The following files in the top-level directory are used by the 'configure' script: +* `Makefile.am`, `aclocal.m4`, `configure.ac` - used to build this distribution, only needed by maintainers +* `Makefile.in`, `config.h.in` - templates used by configure script + +## Documentation + +In addition to the informational articles and documentation +in the online [libarchive Wiki](https://github.com/libarchive/libarchive/wiki), +the distribution also includes a number of manual pages: + + * bsdtar.1 explains the use of the bsdtar program + * bsdcpio.1 explains the use of the bsdcpio program + * bsdcat.1 explains the use of the bsdcat program + * libarchive.3 gives an overview of the library as a whole + * archive_read.3, archive_write.3, archive_write_disk.3, and + archive_read_disk.3 provide detailed calling sequences for the read + and write APIs + * archive_entry.3 details the "struct archive_entry" utility class + * archive_internals.3 provides some insight into libarchive's + internal structure and operation. + * libarchive-formats.5 documents the file formats supported by the library + * cpio.5, mtree.5, and tar.5 provide detailed information about these + popular archive formats, including hard-to-find details about + modern cpio and tar variants. + +The manual pages above are provided in the 'doc' directory in +a number of different formats. + +You should also read the copious comments in `archive.h` and the +source code for the sample programs for more details. Please let us +know about any errors or omissions you find. + +## Supported Formats + +Currently, the library automatically detects and reads the following formats: + * Old V7 tar archives + * POSIX ustar + * GNU tar format (including GNU long filenames, long link names, and sparse files) + * Solaris 9 extended tar format (including ACLs) + * POSIX pax interchange format + * POSIX octet-oriented cpio + * SVR4 ASCII cpio + * Binary cpio (big-endian or little-endian) + * ISO9660 CD-ROM images (with optional Rockridge or Joliet extensions) + * ZIP archives (with uncompressed or "deflate" compressed entries, including support for encrypted Zip archives) + * ZIPX archives (with support for bzip2, ppmd8, lzma and xz compressed entries) + * GNU and BSD 'ar' archives + * 'mtree' format + * 7-Zip archives + * Microsoft CAB format + * LHA and LZH archives + * RAR and RAR 5.0 archives (with some limitations due to RAR's proprietary status) + * XAR archives + +The library also detects and handles any of the following before evaluating the archive: + * uuencoded files + * files with RPM wrapper + * gzip compression + * bzip2 compression + * compress/LZW compression + * lzma, lzip, and xz compression + * lz4 compression + * lzop compression + * zstandard compression + +The library can create archives in any of the following formats: + * POSIX ustar + * POSIX pax interchange format + * "restricted" pax format, which will create ustar archives except for + entries that require pax extensions (for long filenames, ACLs, etc). + * Old GNU tar format + * Old V7 tar format + * POSIX octet-oriented cpio + * SVR4 "newc" cpio + * shar archives + * ZIP archives (with uncompressed or "deflate" compressed entries) + * GNU and BSD 'ar' archives + * 'mtree' format + * ISO9660 format + * 7-Zip archives + * XAR archives + +When creating archives, the result can be filtered with any of the following: + * uuencode + * gzip compression + * bzip2 compression + * compress/LZW compression + * lzma, lzip, and xz compression + * lz4 compression + * lzop compression + * zstandard compression + +## Notes about the Library Design + +The following notes address many of the most common +questions we are asked about libarchive: + +* This is a heavily stream-oriented system. That means that + it is optimized to read or write the archive in a single + pass from beginning to end. For example, this allows + libarchive to process archives too large to store on disk + by processing them on-the-fly as they are read from or + written to a network or tape drive. This also makes + libarchive useful for tools that need to produce + archives on-the-fly (such as webservers that provide + archived contents of a users account). + +* In-place modification and random access to the contents + of an archive are not directly supported. For some formats, + this is not an issue: For example, tar.gz archives are not + designed for random access. In some other cases, libarchive + can re-open an archive and scan it from the beginning quickly + enough to provide the needed abilities even without true + random access. Of course, some applications do require true + random access; those applications should consider alternatives + to libarchive. + +* The library is designed to be extended with new compression and + archive formats. The only requirement is that the format be + readable or writable as a stream and that each archive entry be + independent. There are articles on the libarchive Wiki explaining + how to extend libarchive. + +* On read, compression and format are always detected automatically. + +* The same API is used for all formats; it should be very + easy for software using libarchive to transparently handle + any of libarchive's archiving formats. + +* Libarchive's automatic support for decompression can be used + without archiving by explicitly selecting the "raw" and "empty" + formats. + +* I've attempted to minimize static link pollution. If you don't + explicitly invoke a particular feature (such as support for a + particular compression or format), it won't get pulled in to + statically-linked programs. In particular, if you don't explicitly + enable a particular compression or decompression support, you won't + need to link against the corresponding compression or decompression + libraries. This also reduces the size of statically-linked + binaries in environments where that matters. + +* The library is generally _thread safe_ depending on the platform: + it does not define any global variables of its own. However, some + platforms do not provide fully thread-safe versions of key C library + functions. On those platforms, libarchive will use the non-thread-safe + functions. Patches to improve this are of great interest to us. + +* In particular, libarchive's modules to read or write a directory + tree do use `chdir()` to optimize the directory traversals. This + can cause problems for programs that expect to do disk access from + multiple threads. Of course, those modules are completely + optional and you can use the rest of libarchive without them. + +* The library is _not_ thread aware, however. It does no locking + or thread management of any kind. If you create a libarchive + object and need to access it from multiple threads, you will + need to provide your own locking. + +* On read, the library accepts whatever blocks you hand it. + Your read callback is free to pass the library a byte at a time + or mmap the entire archive and give it to the library at once. + On write, the library always produces correctly-blocked output. + +* The object-style approach allows you to have multiple archive streams + open at once. bsdtar uses this in its "@archive" extension. + +* The archive itself is read/written using callback functions. + You can read an archive directly from an in-memory buffer or + write it to a socket, if you wish. There are some utility + functions to provide easy-to-use "open file," etc, capabilities. + +* The read/write APIs are designed to allow individual entries + to be read or written to any data source: You can create + a block of data in memory and add it to a tar archive without + first writing a temporary file. You can also read an entry from + an archive and write the data directly to a socket. If you want + to read/write entries to disk, there are convenience functions to + make this especially easy. + +* Note: The "pax interchange format" is a POSIX standard extended tar + format that should be used when the older _ustar_ format is not + appropriate. It has many advantages over other tar formats + (including the legacy GNU tar format) and is widely supported by + current tar implementations. + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/CMakeLists.txt b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/CMakeLists.txt new file mode 100644 index 0000000000..9389bbc9a9 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/CMakeLists.txt @@ -0,0 +1,264 @@ + +############################################ +# +# How to build libarchive +# +############################################ + +# Public headers +SET(include_HEADERS + archive.h + archive_entry.h +) + +# Sources and private headers +SET(libarchive_SOURCES + archive_acl.c + archive_acl_private.h + archive_check_magic.c + archive_cmdline.c + archive_cmdline_private.h + archive_crc32.h + archive_cryptor.c + archive_cryptor_private.h + archive_digest.c + archive_digest_private.h + archive_endian.h + archive_entry.c + archive_entry.h + archive_entry_copy_stat.c + archive_entry_link_resolver.c + archive_entry_locale.h + archive_entry_private.h + archive_entry_sparse.c + archive_entry_stat.c + archive_entry_strmode.c + archive_entry_xattr.c + archive_getdate.c + archive_getdate.h + archive_hmac.c + archive_hmac_private.h + archive_match.c + archive_openssl_evp_private.h + archive_openssl_hmac_private.h + archive_options.c + archive_options_private.h + archive_pack_dev.h + archive_pack_dev.c + archive_pathmatch.c + archive_pathmatch.h + archive_platform.h + archive_platform_acl.h + archive_platform_xattr.h + archive_ppmd_private.h + archive_ppmd8.c + archive_ppmd8_private.h + archive_ppmd7.c + archive_ppmd7_private.h + archive_private.h + archive_random.c + archive_random_private.h + archive_rb.c + archive_rb.h + archive_read.c + archive_read_add_passphrase.c + archive_read_append_filter.c + archive_read_data_into_fd.c + archive_read_disk_entry_from_file.c + archive_read_disk_posix.c + archive_read_disk_private.h + archive_read_disk_set_standard_lookup.c + archive_read_extract.c + archive_read_extract2.c + archive_read_open_fd.c + archive_read_open_file.c + archive_read_open_filename.c + archive_read_open_memory.c + archive_read_private.h + archive_read_set_format.c + archive_read_set_options.c + archive_read_support_filter_all.c + archive_read_support_filter_bzip2.c + archive_read_support_filter_compress.c + archive_read_support_filter_gzip.c + archive_read_support_filter_grzip.c + archive_read_support_filter_lrzip.c + archive_read_support_filter_lz4.c + archive_read_support_filter_lzop.c + archive_read_support_filter_none.c + archive_read_support_filter_program.c + archive_read_support_filter_rpm.c + archive_read_support_filter_uu.c + archive_read_support_filter_xz.c + archive_read_support_filter_zstd.c + archive_read_support_format_7zip.c + archive_read_support_format_all.c + archive_read_support_format_ar.c + archive_read_support_format_by_code.c + archive_read_support_format_cab.c + archive_read_support_format_cpio.c + archive_read_support_format_empty.c + archive_read_support_format_iso9660.c + archive_read_support_format_lha.c + archive_read_support_format_mtree.c + archive_read_support_format_rar.c + archive_read_support_format_rar5.c + archive_read_support_format_raw.c + archive_read_support_format_tar.c + archive_read_support_format_warc.c + archive_read_support_format_xar.c + archive_read_support_format_zip.c + archive_string.c + archive_string.h + archive_string_composition.h + archive_string_sprintf.c + archive_util.c + archive_version_details.c + archive_virtual.c + archive_write.c + archive_write_disk_posix.c + archive_write_disk_private.h + archive_write_disk_set_standard_lookup.c + archive_write_private.h + archive_write_open_fd.c + archive_write_open_file.c + archive_write_open_filename.c + archive_write_open_memory.c + archive_write_add_filter.c + archive_write_add_filter_b64encode.c + archive_write_add_filter_by_name.c + archive_write_add_filter_bzip2.c + archive_write_add_filter_compress.c + archive_write_add_filter_grzip.c + archive_write_add_filter_gzip.c + archive_write_add_filter_lrzip.c + archive_write_add_filter_lz4.c + archive_write_add_filter_lzop.c + archive_write_add_filter_none.c + archive_write_add_filter_program.c + archive_write_add_filter_uuencode.c + archive_write_add_filter_xz.c + archive_write_add_filter_zstd.c + archive_write_set_format.c + archive_write_set_format_7zip.c + archive_write_set_format_ar.c + archive_write_set_format_by_name.c + archive_write_set_format_cpio.c + archive_write_set_format_cpio_newc.c + archive_write_set_format_filter_by_ext.c + archive_write_set_format_gnutar.c + archive_write_set_format_iso9660.c + archive_write_set_format_mtree.c + archive_write_set_format_pax.c + archive_write_set_format_private.h + archive_write_set_format_raw.c + archive_write_set_format_shar.c + archive_write_set_format_ustar.c + archive_write_set_format_v7tar.c + archive_write_set_format_warc.c + archive_write_set_format_xar.c + archive_write_set_format_zip.c + archive_write_set_options.c + archive_write_set_passphrase.c + archive_xxhash.h + filter_fork_posix.c + filter_fork.h + xxhash.c +) + +# Man pages +SET(libarchive_MANS + archive_entry.3 + archive_entry_acl.3 + archive_entry_linkify.3 + archive_entry_misc.3 + archive_entry_paths.3 + archive_entry_perms.3 + archive_entry_stat.3 + archive_entry_time.3 + archive_read.3 + archive_read_add_passphrase.3 + archive_read_data.3 + archive_read_disk.3 + archive_read_extract.3 + archive_read_filter.3 + archive_read_format.3 + archive_read_free.3 + archive_read_header.3 + archive_read_new.3 + archive_read_open.3 + archive_read_set_options.3 + archive_util.3 + archive_write.3 + archive_write_blocksize.3 + archive_write_data.3 + archive_write_disk.3 + archive_write_filter.3 + archive_write_finish_entry.3 + archive_write_format.3 + archive_write_free.3 + archive_write_header.3 + archive_write_new.3 + archive_write_open.3 + archive_write_set_options.3 + archive_write_set_passphrase.3 + cpio.5 + libarchive.3 + libarchive_changes.3 + libarchive_internals.3 + libarchive-formats.5 + mtree.5 + tar.5 +) + +IF(WIN32 AND NOT CYGWIN) + LIST(APPEND libarchive_SOURCES archive_entry_copy_bhfi.c) + LIST(APPEND libarchive_SOURCES archive_read_disk_windows.c) + LIST(APPEND libarchive_SOURCES archive_windows.c) + LIST(APPEND libarchive_SOURCES archive_windows.h) + LIST(APPEND libarchive_SOURCES archive_write_disk_windows.c) + LIST(APPEND libarchive_SOURCES filter_fork_windows.c) +ENDIF(WIN32 AND NOT CYGWIN) + +IF(ARCHIVE_BLAKE2) + LIST(APPEND libarchive_SOURCES archive_blake2sp_ref.c) + LIST(APPEND libarchive_SOURCES archive_blake2s_ref.c) +ENDIF(ARCHIVE_BLAKE2) + +IF(ARCHIVE_ACL_DARWIN) + LIST(APPEND libarchive_SOURCES archive_disk_acl_darwin.c) +ELSEIF(ARCHIVE_ACL_FREEBSD) + LIST(APPEND libarchive_SOURCES archive_disk_acl_freebsd.c) +ELSEIF(ARCHIVE_ACL_LIBACL) + LIST(APPEND libarchive_SOURCES archive_disk_acl_linux.c) +ELSEIF(ARCHIVE_ACL_SUNOS) + LIST(APPEND libarchive_SOURCES archive_disk_acl_sunos.c) +ENDIF() + +# Libarchive is a shared library +ADD_LIBRARY(archive SHARED ${libarchive_SOURCES} ${include_HEADERS}) +TARGET_INCLUDE_DIRECTORIES(archive PUBLIC .) +TARGET_LINK_LIBRARIES(archive ${ADDITIONAL_LIBS}) +SET_TARGET_PROPERTIES(archive PROPERTIES SOVERSION ${SOVERSION}) + +# archive_static is a static library +ADD_LIBRARY(archive_static STATIC ${libarchive_SOURCES} ${include_HEADERS}) +TARGET_LINK_LIBRARIES(archive_static ${ADDITIONAL_LIBS}) +SET_TARGET_PROPERTIES(archive_static PROPERTIES COMPILE_DEFINITIONS + LIBARCHIVE_STATIC) +# On Posix systems, libarchive.so and libarchive.a can co-exist. +IF(NOT WIN32 OR CYGWIN) + SET_TARGET_PROPERTIES(archive_static PROPERTIES OUTPUT_NAME archive) +ENDIF(NOT WIN32 OR CYGWIN) + +IF(ENABLE_INSTALL) + # How to install the libraries + INSTALL(TARGETS archive archive_static + RUNTIME DESTINATION bin + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib) + INSTALL_MAN(${libarchive_MANS}) + INSTALL(FILES ${include_HEADERS} DESTINATION include) +ENDIF() + +add_subdirectory(test) diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive.h new file mode 100644 index 0000000000..9791eb3876 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive.h @@ -0,0 +1,1197 @@ +/*- + * Copyright (c) 2003-2010 Tim Kientzle + * 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(S) ``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(S) 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. + * + * $FreeBSD: src/lib/libarchive/archive.h.in,v 1.50 2008/05/26 17:00:22 kientzle Exp $ + */ + +#ifndef ARCHIVE_H_INCLUDED +#define ARCHIVE_H_INCLUDED + +/* + * The version number is expressed as a single integer that makes it + * easy to compare versions at build time: for version a.b.c, the + * version number is printf("%d%03d%03d",a,b,c). For example, if you + * know your application requires version 2.12.108 or later, you can + * assert that ARCHIVE_VERSION_NUMBER >= 2012108. + */ +/* Note: Compiler will complain if this does not match archive_entry.h! */ +#define ARCHIVE_VERSION_NUMBER 3004003 + +#include <sys/stat.h> +#include <stddef.h> /* for wchar_t */ +#include <stdio.h> /* For FILE * */ +#include <time.h> /* For time_t */ + +/* + * Note: archive.h is for use outside of libarchive; the configuration + * headers (config.h, archive_platform.h, etc.) are purely internal. + * Do NOT use HAVE_XXX configuration macros to control the behavior of + * this header! If you must conditionalize, use predefined compiler and/or + * platform macros. + */ +#if defined(__BORLANDC__) && __BORLANDC__ >= 0x560 +# include <stdint.h> +#elif !defined(__WATCOMC__) && !defined(_MSC_VER) && !defined(__INTERIX) && !defined(__BORLANDC__) && !defined(_SCO_DS) && !defined(__osf__) && !defined(__CLANG_INTTYPES_H) +# include <inttypes.h> +#endif + +/* Get appropriate definitions of 64-bit integer */ +#if !defined(__LA_INT64_T_DEFINED) +/* Older code relied on the __LA_INT64_T macro; after 4.0 we'll switch to the typedef exclusively. */ +# if ARCHIVE_VERSION_NUMBER < 4000000 +#define __LA_INT64_T la_int64_t +# endif +#define __LA_INT64_T_DEFINED +# if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__WATCOMC__) +typedef __int64 la_int64_t; +# else +# include <unistd.h> /* ssize_t */ +# if defined(_SCO_DS) || defined(__osf__) +typedef long long la_int64_t; +# else +typedef int64_t la_int64_t; +# endif +# endif +#endif + +/* The la_ssize_t should match the type used in 'struct stat' */ +#if !defined(__LA_SSIZE_T_DEFINED) +/* Older code relied on the __LA_SSIZE_T macro; after 4.0 we'll switch to the typedef exclusively. */ +# if ARCHIVE_VERSION_NUMBER < 4000000 +#define __LA_SSIZE_T la_ssize_t +# endif +#define __LA_SSIZE_T_DEFINED +# if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__WATCOMC__) +# if defined(_SSIZE_T_DEFINED) || defined(_SSIZE_T_) +typedef ssize_t la_ssize_t; +# elif defined(_WIN64) +typedef __int64 la_ssize_t; +# else +typedef long la_ssize_t; +# endif +# else +# include <unistd.h> /* ssize_t */ +typedef ssize_t la_ssize_t; +# endif +#endif + +/* Large file support for Android */ +#ifdef __ANDROID__ +#include "android_lf.h" +#endif + +/* + * On Windows, define LIBARCHIVE_STATIC if you're building or using a + * .lib. The default here assumes you're building a DLL. Only + * libarchive source should ever define __LIBARCHIVE_BUILD. + */ +#if ((defined __WIN32__) || (defined _WIN32) || defined(__CYGWIN__)) && (!defined LIBARCHIVE_STATIC) +# ifdef __LIBARCHIVE_BUILD +# ifdef __GNUC__ +# define __LA_DECL __attribute__((dllexport)) extern +# else +# define __LA_DECL __declspec(dllexport) +# endif +# else +# ifdef __GNUC__ +# define __LA_DECL +# else +# define __LA_DECL __declspec(dllimport) +# endif +# endif +#else +/* Static libraries or non-Windows needs no special declaration. */ +# define __LA_DECL +#endif + +#if defined(__GNUC__) && __GNUC__ >= 3 && !defined(__MINGW32__) +#define __LA_PRINTF(fmtarg, firstvararg) \ + __attribute__((__format__ (__printf__, fmtarg, firstvararg))) +#else +#define __LA_PRINTF(fmtarg, firstvararg) /* nothing */ +#endif + +#if defined(__GNUC__) && __GNUC__ >= 3 && __GNUC_MINOR__ >= 1 +# define __LA_DEPRECATED __attribute__((deprecated)) +#else +# define __LA_DEPRECATED +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * The version number is provided as both a macro and a function. + * The macro identifies the installed header; the function identifies + * the library version (which may not be the same if you're using a + * dynamically-linked version of the library). Of course, if the + * header and library are very different, you should expect some + * strangeness. Don't do that. + */ +__LA_DECL int archive_version_number(void); + +/* + * Textual name/version of the library, useful for version displays. + */ +#define ARCHIVE_VERSION_ONLY_STRING "3.4.3" +#define ARCHIVE_VERSION_STRING "libarchive " ARCHIVE_VERSION_ONLY_STRING +__LA_DECL const char * archive_version_string(void); + +/* + * Detailed textual name/version of the library and its dependencies. + * This has the form: + * "libarchive x.y.z zlib/a.b.c liblzma/d.e.f ... etc ..." + * the list of libraries described here will vary depending on how + * libarchive was compiled. + */ +__LA_DECL const char * archive_version_details(void); + +/* + * Returns NULL if libarchive was compiled without the associated library. + * Otherwise, returns the version number that libarchive was compiled + * against. + */ +__LA_DECL const char * archive_zlib_version(void); +__LA_DECL const char * archive_liblzma_version(void); +__LA_DECL const char * archive_bzlib_version(void); +__LA_DECL const char * archive_liblz4_version(void); +__LA_DECL const char * archive_libzstd_version(void); + +/* Declare our basic types. */ +struct archive; +struct archive_entry; + +/* + * Error codes: Use archive_errno() and archive_error_string() + * to retrieve details. Unless specified otherwise, all functions + * that return 'int' use these codes. + */ +#define ARCHIVE_EOF 1 /* Found end of archive. */ +#define ARCHIVE_OK 0 /* Operation was successful. */ +#define ARCHIVE_RETRY (-10) /* Retry might succeed. */ +#define ARCHIVE_WARN (-20) /* Partial success. */ +/* For example, if write_header "fails", then you can't push data. */ +#define ARCHIVE_FAILED (-25) /* Current operation cannot complete. */ +/* But if write_header is "fatal," then this archive is dead and useless. */ +#define ARCHIVE_FATAL (-30) /* No more operations are possible. */ + +/* + * As far as possible, archive_errno returns standard platform errno codes. + * Of course, the details vary by platform, so the actual definitions + * here are stored in "archive_platform.h". The symbols are listed here + * for reference; as a rule, clients should not need to know the exact + * platform-dependent error code. + */ +/* Unrecognized or invalid file format. */ +/* #define ARCHIVE_ERRNO_FILE_FORMAT */ +/* Illegal usage of the library. */ +/* #define ARCHIVE_ERRNO_PROGRAMMER_ERROR */ +/* Unknown or unclassified error. */ +/* #define ARCHIVE_ERRNO_MISC */ + +/* + * Callbacks are invoked to automatically read/skip/write/open/close the + * archive. You can provide your own for complex tasks (like breaking + * archives across multiple tapes) or use standard ones built into the + * library. + */ + +/* Returns pointer and size of next block of data from archive. */ +typedef la_ssize_t archive_read_callback(struct archive *, + void *_client_data, const void **_buffer); + +/* Skips at most request bytes from archive and returns the skipped amount. + * This may skip fewer bytes than requested; it may even skip zero bytes. + * If you do skip fewer bytes than requested, libarchive will invoke your + * read callback and discard data as necessary to make up the full skip. + */ +typedef la_int64_t archive_skip_callback(struct archive *, + void *_client_data, la_int64_t request); + +/* Seeks to specified location in the file and returns the position. + * Whence values are SEEK_SET, SEEK_CUR, SEEK_END from stdio.h. + * Return ARCHIVE_FATAL if the seek fails for any reason. + */ +typedef la_int64_t archive_seek_callback(struct archive *, + void *_client_data, la_int64_t offset, int whence); + +/* Returns size actually written, zero on EOF, -1 on error. */ +typedef la_ssize_t archive_write_callback(struct archive *, + void *_client_data, + const void *_buffer, size_t _length); + +typedef int archive_open_callback(struct archive *, void *_client_data); + +typedef int archive_close_callback(struct archive *, void *_client_data); + +/* Switches from one client data object to the next/prev client data object. + * This is useful for reading from different data blocks such as a set of files + * that make up one large file. + */ +typedef int archive_switch_callback(struct archive *, void *_client_data1, + void *_client_data2); + +/* + * Returns a passphrase used for encryption or decryption, NULL on nothing + * to do and give it up. + */ +typedef const char *archive_passphrase_callback(struct archive *, + void *_client_data); + +/* + * Codes to identify various stream filters. + */ +#define ARCHIVE_FILTER_NONE 0 +#define ARCHIVE_FILTER_GZIP 1 +#define ARCHIVE_FILTER_BZIP2 2 +#define ARCHIVE_FILTER_COMPRESS 3 +#define ARCHIVE_FILTER_PROGRAM 4 +#define ARCHIVE_FILTER_LZMA 5 +#define ARCHIVE_FILTER_XZ 6 +#define ARCHIVE_FILTER_UU 7 +#define ARCHIVE_FILTER_RPM 8 +#define ARCHIVE_FILTER_LZIP 9 +#define ARCHIVE_FILTER_LRZIP 10 +#define ARCHIVE_FILTER_LZOP 11 +#define ARCHIVE_FILTER_GRZIP 12 +#define ARCHIVE_FILTER_LZ4 13 +#define ARCHIVE_FILTER_ZSTD 14 + +#if ARCHIVE_VERSION_NUMBER < 4000000 +#define ARCHIVE_COMPRESSION_NONE ARCHIVE_FILTER_NONE +#define ARCHIVE_COMPRESSION_GZIP ARCHIVE_FILTER_GZIP +#define ARCHIVE_COMPRESSION_BZIP2 ARCHIVE_FILTER_BZIP2 +#define ARCHIVE_COMPRESSION_COMPRESS ARCHIVE_FILTER_COMPRESS +#define ARCHIVE_COMPRESSION_PROGRAM ARCHIVE_FILTER_PROGRAM +#define ARCHIVE_COMPRESSION_LZMA ARCHIVE_FILTER_LZMA +#define ARCHIVE_COMPRESSION_XZ ARCHIVE_FILTER_XZ +#define ARCHIVE_COMPRESSION_UU ARCHIVE_FILTER_UU +#define ARCHIVE_COMPRESSION_RPM ARCHIVE_FILTER_RPM +#define ARCHIVE_COMPRESSION_LZIP ARCHIVE_FILTER_LZIP +#define ARCHIVE_COMPRESSION_LRZIP ARCHIVE_FILTER_LRZIP +#endif + +/* + * Codes returned by archive_format. + * + * Top 16 bits identifies the format family (e.g., "tar"); lower + * 16 bits indicate the variant. This is updated by read_next_header. + * Note that the lower 16 bits will often vary from entry to entry. + * In some cases, this variation occurs as libarchive learns more about + * the archive (for example, later entries might utilize extensions that + * weren't necessary earlier in the archive; in this case, libarchive + * will change the format code to indicate the extended format that + * was used). In other cases, it's because different tools have + * modified the archive and so different parts of the archive + * actually have slightly different formats. (Both tar and cpio store + * format codes in each entry, so it is quite possible for each + * entry to be in a different format.) + */ +#define ARCHIVE_FORMAT_BASE_MASK 0xff0000 +#define ARCHIVE_FORMAT_CPIO 0x10000 +#define ARCHIVE_FORMAT_CPIO_POSIX (ARCHIVE_FORMAT_CPIO | 1) +#define ARCHIVE_FORMAT_CPIO_BIN_LE (ARCHIVE_FORMAT_CPIO | 2) +#define ARCHIVE_FORMAT_CPIO_BIN_BE (ARCHIVE_FORMAT_CPIO | 3) +#define ARCHIVE_FORMAT_CPIO_SVR4_NOCRC (ARCHIVE_FORMAT_CPIO | 4) +#define ARCHIVE_FORMAT_CPIO_SVR4_CRC (ARCHIVE_FORMAT_CPIO | 5) +#define ARCHIVE_FORMAT_CPIO_AFIO_LARGE (ARCHIVE_FORMAT_CPIO | 6) +#define ARCHIVE_FORMAT_SHAR 0x20000 +#define ARCHIVE_FORMAT_SHAR_BASE (ARCHIVE_FORMAT_SHAR | 1) +#define ARCHIVE_FORMAT_SHAR_DUMP (ARCHIVE_FORMAT_SHAR | 2) +#define ARCHIVE_FORMAT_TAR 0x30000 +#define ARCHIVE_FORMAT_TAR_USTAR (ARCHIVE_FORMAT_TAR | 1) +#define ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE (ARCHIVE_FORMAT_TAR | 2) +#define ARCHIVE_FORMAT_TAR_PAX_RESTRICTED (ARCHIVE_FORMAT_TAR | 3) +#define ARCHIVE_FORMAT_TAR_GNUTAR (ARCHIVE_FORMAT_TAR | 4) +#define ARCHIVE_FORMAT_ISO9660 0x40000 +#define ARCHIVE_FORMAT_ISO9660_ROCKRIDGE (ARCHIVE_FORMAT_ISO9660 | 1) +#define ARCHIVE_FORMAT_ZIP 0x50000 +#define ARCHIVE_FORMAT_EMPTY 0x60000 +#define ARCHIVE_FORMAT_AR 0x70000 +#define ARCHIVE_FORMAT_AR_GNU (ARCHIVE_FORMAT_AR | 1) +#define ARCHIVE_FORMAT_AR_BSD (ARCHIVE_FORMAT_AR | 2) +#define ARCHIVE_FORMAT_MTREE 0x80000 +#define ARCHIVE_FORMAT_RAW 0x90000 +#define ARCHIVE_FORMAT_XAR 0xA0000 +#define ARCHIVE_FORMAT_LHA 0xB0000 +#define ARCHIVE_FORMAT_CAB 0xC0000 +#define ARCHIVE_FORMAT_RAR 0xD0000 +#define ARCHIVE_FORMAT_7ZIP 0xE0000 +#define ARCHIVE_FORMAT_WARC 0xF0000 +#define ARCHIVE_FORMAT_RAR_V5 0x100000 + +/* + * Codes returned by archive_read_format_capabilities(). + * + * This list can be extended with values between 0 and 0xffff. + * The original purpose of this list was to let different archive + * format readers expose their general capabilities in terms of + * encryption. + */ +#define ARCHIVE_READ_FORMAT_CAPS_NONE (0) /* no special capabilities */ +#define ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA (1<<0) /* reader can detect encrypted data */ +#define ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA (1<<1) /* reader can detect encryptable metadata (pathname, mtime, etc.) */ + +/* + * Codes returned by archive_read_has_encrypted_entries(). + * + * In case the archive does not support encryption detection at all + * ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED is returned. If the reader + * for some other reason (e.g. not enough bytes read) cannot say if + * there are encrypted entries, ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW + * is returned. + */ +#define ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED -2 +#define ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW -1 + +/*- + * Basic outline for reading an archive: + * 1) Ask archive_read_new for an archive reader object. + * 2) Update any global properties as appropriate. + * In particular, you'll certainly want to call appropriate + * archive_read_support_XXX functions. + * 3) Call archive_read_open_XXX to open the archive + * 4) Repeatedly call archive_read_next_header to get information about + * successive archive entries. Call archive_read_data to extract + * data for entries of interest. + * 5) Call archive_read_free to end processing. + */ +__LA_DECL struct archive *archive_read_new(void); + +/* + * The archive_read_support_XXX calls enable auto-detect for this + * archive handle. They also link in the necessary support code. + * For example, if you don't want bzlib linked in, don't invoke + * support_compression_bzip2(). The "all" functions provide the + * obvious shorthand. + */ + +#if ARCHIVE_VERSION_NUMBER < 4000000 +__LA_DECL int archive_read_support_compression_all(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_read_support_compression_bzip2(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_read_support_compression_compress(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_read_support_compression_gzip(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_read_support_compression_lzip(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_read_support_compression_lzma(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_read_support_compression_none(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_read_support_compression_program(struct archive *, + const char *command) __LA_DEPRECATED; +__LA_DECL int archive_read_support_compression_program_signature + (struct archive *, const char *, + const void * /* match */, size_t) __LA_DEPRECATED; + +__LA_DECL int archive_read_support_compression_rpm(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_read_support_compression_uu(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_read_support_compression_xz(struct archive *) + __LA_DEPRECATED; +#endif + +__LA_DECL int archive_read_support_filter_all(struct archive *); +__LA_DECL int archive_read_support_filter_bzip2(struct archive *); +__LA_DECL int archive_read_support_filter_compress(struct archive *); +__LA_DECL int archive_read_support_filter_gzip(struct archive *); +__LA_DECL int archive_read_support_filter_grzip(struct archive *); +__LA_DECL int archive_read_support_filter_lrzip(struct archive *); +__LA_DECL int archive_read_support_filter_lz4(struct archive *); +__LA_DECL int archive_read_support_filter_lzip(struct archive *); +__LA_DECL int archive_read_support_filter_lzma(struct archive *); +__LA_DECL int archive_read_support_filter_lzop(struct archive *); +__LA_DECL int archive_read_support_filter_none(struct archive *); +__LA_DECL int archive_read_support_filter_program(struct archive *, + const char *command); +__LA_DECL int archive_read_support_filter_program_signature + (struct archive *, const char * /* cmd */, + const void * /* match */, size_t); +__LA_DECL int archive_read_support_filter_rpm(struct archive *); +__LA_DECL int archive_read_support_filter_uu(struct archive *); +__LA_DECL int archive_read_support_filter_xz(struct archive *); +__LA_DECL int archive_read_support_filter_zstd(struct archive *); + +__LA_DECL int archive_read_support_format_7zip(struct archive *); +__LA_DECL int archive_read_support_format_all(struct archive *); +__LA_DECL int archive_read_support_format_ar(struct archive *); +__LA_DECL int archive_read_support_format_by_code(struct archive *, int); +__LA_DECL int archive_read_support_format_cab(struct archive *); +__LA_DECL int archive_read_support_format_cpio(struct archive *); +__LA_DECL int archive_read_support_format_empty(struct archive *); +__LA_DECL int archive_read_support_format_gnutar(struct archive *); +__LA_DECL int archive_read_support_format_iso9660(struct archive *); +__LA_DECL int archive_read_support_format_lha(struct archive *); +__LA_DECL int archive_read_support_format_mtree(struct archive *); +__LA_DECL int archive_read_support_format_rar(struct archive *); +__LA_DECL int archive_read_support_format_rar5(struct archive *); +__LA_DECL int archive_read_support_format_raw(struct archive *); +__LA_DECL int archive_read_support_format_tar(struct archive *); +__LA_DECL int archive_read_support_format_warc(struct archive *); +__LA_DECL int archive_read_support_format_xar(struct archive *); +/* archive_read_support_format_zip() enables both streamable and seekable + * zip readers. */ +__LA_DECL int archive_read_support_format_zip(struct archive *); +/* Reads Zip archives as stream from beginning to end. Doesn't + * correctly handle SFX ZIP files or ZIP archives that have been modified + * in-place. */ +__LA_DECL int archive_read_support_format_zip_streamable(struct archive *); +/* Reads starting from central directory; requires seekable input. */ +__LA_DECL int archive_read_support_format_zip_seekable(struct archive *); + +/* Functions to manually set the format and filters to be used. This is + * useful to bypass the bidding process when the format and filters to use + * is known in advance. + */ +__LA_DECL int archive_read_set_format(struct archive *, int); +__LA_DECL int archive_read_append_filter(struct archive *, int); +__LA_DECL int archive_read_append_filter_program(struct archive *, + const char *); +__LA_DECL int archive_read_append_filter_program_signature + (struct archive *, const char *, const void * /* match */, size_t); + +/* Set various callbacks. */ +__LA_DECL int archive_read_set_open_callback(struct archive *, + archive_open_callback *); +__LA_DECL int archive_read_set_read_callback(struct archive *, + archive_read_callback *); +__LA_DECL int archive_read_set_seek_callback(struct archive *, + archive_seek_callback *); +__LA_DECL int archive_read_set_skip_callback(struct archive *, + archive_skip_callback *); +__LA_DECL int archive_read_set_close_callback(struct archive *, + archive_close_callback *); +/* Callback used to switch between one data object to the next */ +__LA_DECL int archive_read_set_switch_callback(struct archive *, + archive_switch_callback *); + +/* This sets the first data object. */ +__LA_DECL int archive_read_set_callback_data(struct archive *, void *); +/* This sets data object at specified index */ +__LA_DECL int archive_read_set_callback_data2(struct archive *, void *, + unsigned int); +/* This adds a data object at the specified index. */ +__LA_DECL int archive_read_add_callback_data(struct archive *, void *, + unsigned int); +/* This appends a data object to the end of list */ +__LA_DECL int archive_read_append_callback_data(struct archive *, void *); +/* This prepends a data object to the beginning of list */ +__LA_DECL int archive_read_prepend_callback_data(struct archive *, void *); + +/* Opening freezes the callbacks. */ +__LA_DECL int archive_read_open1(struct archive *); + +/* Convenience wrappers around the above. */ +__LA_DECL int archive_read_open(struct archive *, void *_client_data, + archive_open_callback *, archive_read_callback *, + archive_close_callback *); +__LA_DECL int archive_read_open2(struct archive *, void *_client_data, + archive_open_callback *, archive_read_callback *, + archive_skip_callback *, archive_close_callback *); + +/* + * A variety of shortcuts that invoke archive_read_open() with + * canned callbacks suitable for common situations. The ones that + * accept a block size handle tape blocking correctly. + */ +/* Use this if you know the filename. Note: NULL indicates stdin. */ +__LA_DECL int archive_read_open_filename(struct archive *, + const char *_filename, size_t _block_size); +/* Use this for reading multivolume files by filenames. + * NOTE: Must be NULL terminated. Sorting is NOT done. */ +__LA_DECL int archive_read_open_filenames(struct archive *, + const char **_filenames, size_t _block_size); +__LA_DECL int archive_read_open_filename_w(struct archive *, + const wchar_t *_filename, size_t _block_size); +/* archive_read_open_file() is a deprecated synonym for ..._open_filename(). */ +__LA_DECL int archive_read_open_file(struct archive *, + const char *_filename, size_t _block_size) __LA_DEPRECATED; +/* Read an archive that's stored in memory. */ +__LA_DECL int archive_read_open_memory(struct archive *, + const void * buff, size_t size); +/* A more involved version that is only used for internal testing. */ +__LA_DECL int archive_read_open_memory2(struct archive *a, const void *buff, + size_t size, size_t read_size); +/* Read an archive that's already open, using the file descriptor. */ +__LA_DECL int archive_read_open_fd(struct archive *, int _fd, + size_t _block_size); +/* Read an archive that's already open, using a FILE *. */ +/* Note: DO NOT use this with tape drives. */ +__LA_DECL int archive_read_open_FILE(struct archive *, FILE *_file); + +/* Parses and returns next entry header. */ +__LA_DECL int archive_read_next_header(struct archive *, + struct archive_entry **); + +/* Parses and returns next entry header using the archive_entry passed in */ +__LA_DECL int archive_read_next_header2(struct archive *, + struct archive_entry *); + +/* + * Retrieve the byte offset in UNCOMPRESSED data where last-read + * header started. + */ +__LA_DECL la_int64_t archive_read_header_position(struct archive *); + +/* + * Returns 1 if the archive contains at least one encrypted entry. + * If the archive format not support encryption at all + * ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED is returned. + * If for any other reason (e.g. not enough data read so far) + * we cannot say whether there are encrypted entries, then + * ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW is returned. + * In general, this function will return values below zero when the + * reader is uncertain or totally incapable of encryption support. + * When this function returns 0 you can be sure that the reader + * supports encryption detection but no encrypted entries have + * been found yet. + * + * NOTE: If the metadata/header of an archive is also encrypted, you + * cannot rely on the number of encrypted entries. That is why this + * function does not return the number of encrypted entries but# + * just shows that there are some. + */ +__LA_DECL int archive_read_has_encrypted_entries(struct archive *); + +/* + * Returns a bitmask of capabilities that are supported by the archive format reader. + * If the reader has no special capabilities, ARCHIVE_READ_FORMAT_CAPS_NONE is returned. + */ +__LA_DECL int archive_read_format_capabilities(struct archive *); + +/* Read data from the body of an entry. Similar to read(2). */ +__LA_DECL la_ssize_t archive_read_data(struct archive *, + void *, size_t); + +/* Seek within the body of an entry. Similar to lseek(2). */ +__LA_DECL la_int64_t archive_seek_data(struct archive *, la_int64_t, int); + +/* + * A zero-copy version of archive_read_data that also exposes the file offset + * of each returned block. Note that the client has no way to specify + * the desired size of the block. The API does guarantee that offsets will + * be strictly increasing and that returned blocks will not overlap. + */ +__LA_DECL int archive_read_data_block(struct archive *a, + const void **buff, size_t *size, la_int64_t *offset); + +/*- + * Some convenience functions that are built on archive_read_data: + * 'skip': skips entire entry + * 'into_buffer': writes data into memory buffer that you provide + * 'into_fd': writes data to specified filedes + */ +__LA_DECL int archive_read_data_skip(struct archive *); +__LA_DECL int archive_read_data_into_fd(struct archive *, int fd); + +/* + * Set read options. + */ +/* Apply option to the format only. */ +__LA_DECL int archive_read_set_format_option(struct archive *_a, + const char *m, const char *o, + const char *v); +/* Apply option to the filter only. */ +__LA_DECL int archive_read_set_filter_option(struct archive *_a, + const char *m, const char *o, + const char *v); +/* Apply option to both the format and the filter. */ +__LA_DECL int archive_read_set_option(struct archive *_a, + const char *m, const char *o, + const char *v); +/* Apply option string to both the format and the filter. */ +__LA_DECL int archive_read_set_options(struct archive *_a, + const char *opts); + +/* + * Add a decryption passphrase. + */ +__LA_DECL int archive_read_add_passphrase(struct archive *, const char *); +__LA_DECL int archive_read_set_passphrase_callback(struct archive *, + void *client_data, archive_passphrase_callback *); + + +/*- + * Convenience function to recreate the current entry (whose header + * has just been read) on disk. + * + * This does quite a bit more than just copy data to disk. It also: + * - Creates intermediate directories as required. + * - Manages directory permissions: non-writable directories will + * be initially created with write permission enabled; when the + * archive is closed, dir permissions are edited to the values specified + * in the archive. + * - Checks hardlinks: hardlinks will not be extracted unless the + * linked-to file was also extracted within the same session. (TODO) + */ + +/* The "flags" argument selects optional behavior, 'OR' the flags you want. */ + +/* Default: Do not try to set owner/group. */ +#define ARCHIVE_EXTRACT_OWNER (0x0001) +/* Default: Do obey umask, do not restore SUID/SGID/SVTX bits. */ +#define ARCHIVE_EXTRACT_PERM (0x0002) +/* Default: Do not restore mtime/atime. */ +#define ARCHIVE_EXTRACT_TIME (0x0004) +/* Default: Replace existing files. */ +#define ARCHIVE_EXTRACT_NO_OVERWRITE (0x0008) +/* Default: Try create first, unlink only if create fails with EEXIST. */ +#define ARCHIVE_EXTRACT_UNLINK (0x0010) +/* Default: Do not restore ACLs. */ +#define ARCHIVE_EXTRACT_ACL (0x0020) +/* Default: Do not restore fflags. */ +#define ARCHIVE_EXTRACT_FFLAGS (0x0040) +/* Default: Do not restore xattrs. */ +#define ARCHIVE_EXTRACT_XATTR (0x0080) +/* Default: Do not try to guard against extracts redirected by symlinks. */ +/* Note: With ARCHIVE_EXTRACT_UNLINK, will remove any intermediate symlink. */ +#define ARCHIVE_EXTRACT_SECURE_SYMLINKS (0x0100) +/* Default: Do not reject entries with '..' as path elements. */ +#define ARCHIVE_EXTRACT_SECURE_NODOTDOT (0x0200) +/* Default: Create parent directories as needed. */ +#define ARCHIVE_EXTRACT_NO_AUTODIR (0x0400) +/* Default: Overwrite files, even if one on disk is newer. */ +#define ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER (0x0800) +/* Detect blocks of 0 and write holes instead. */ +#define ARCHIVE_EXTRACT_SPARSE (0x1000) +/* Default: Do not restore Mac extended metadata. */ +/* This has no effect except on Mac OS. */ +#define ARCHIVE_EXTRACT_MAC_METADATA (0x2000) +/* Default: Use HFS+ compression if it was compressed. */ +/* This has no effect except on Mac OS v10.6 or later. */ +#define ARCHIVE_EXTRACT_NO_HFS_COMPRESSION (0x4000) +/* Default: Do not use HFS+ compression if it was not compressed. */ +/* This has no effect except on Mac OS v10.6 or later. */ +#define ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED (0x8000) +/* Default: Do not reject entries with absolute paths */ +#define ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS (0x10000) +/* Default: Do not clear no-change flags when unlinking object */ +#define ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS (0x20000) +/* Default: Do not extract atomically (using rename) */ +#define ARCHIVE_EXTRACT_SAFE_WRITES (0x40000) + +__LA_DECL int archive_read_extract(struct archive *, struct archive_entry *, + int flags); +__LA_DECL int archive_read_extract2(struct archive *, struct archive_entry *, + struct archive * /* dest */); +__LA_DECL void archive_read_extract_set_progress_callback(struct archive *, + void (*_progress_func)(void *), void *_user_data); + +/* Record the dev/ino of a file that will not be written. This is + * generally set to the dev/ino of the archive being read. */ +__LA_DECL void archive_read_extract_set_skip_file(struct archive *, + la_int64_t, la_int64_t); + +/* Close the file and release most resources. */ +__LA_DECL int archive_read_close(struct archive *); +/* Release all resources and destroy the object. */ +/* Note that archive_read_free will call archive_read_close for you. */ +__LA_DECL int archive_read_free(struct archive *); +#if ARCHIVE_VERSION_NUMBER < 4000000 +/* Synonym for archive_read_free() for backwards compatibility. */ +__LA_DECL int archive_read_finish(struct archive *) __LA_DEPRECATED; +#endif + +/*- + * To create an archive: + * 1) Ask archive_write_new for an archive writer object. + * 2) Set any global properties. In particular, you should set + * the compression and format to use. + * 3) Call archive_write_open to open the file (most people + * will use archive_write_open_file or archive_write_open_fd, + * which provide convenient canned I/O callbacks for you). + * 4) For each entry: + * - construct an appropriate struct archive_entry structure + * - archive_write_header to write the header + * - archive_write_data to write the entry data + * 5) archive_write_close to close the output + * 6) archive_write_free to cleanup the writer and release resources + */ +__LA_DECL struct archive *archive_write_new(void); +__LA_DECL int archive_write_set_bytes_per_block(struct archive *, + int bytes_per_block); +__LA_DECL int archive_write_get_bytes_per_block(struct archive *); +/* XXX This is badly misnamed; suggestions appreciated. XXX */ +__LA_DECL int archive_write_set_bytes_in_last_block(struct archive *, + int bytes_in_last_block); +__LA_DECL int archive_write_get_bytes_in_last_block(struct archive *); + +/* The dev/ino of a file that won't be archived. This is used + * to avoid recursively adding an archive to itself. */ +__LA_DECL int archive_write_set_skip_file(struct archive *, + la_int64_t, la_int64_t); + +#if ARCHIVE_VERSION_NUMBER < 4000000 +__LA_DECL int archive_write_set_compression_bzip2(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_write_set_compression_compress(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_write_set_compression_gzip(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_write_set_compression_lzip(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_write_set_compression_lzma(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_write_set_compression_none(struct archive *) + __LA_DEPRECATED; +__LA_DECL int archive_write_set_compression_program(struct archive *, + const char *cmd) __LA_DEPRECATED; +__LA_DECL int archive_write_set_compression_xz(struct archive *) + __LA_DEPRECATED; +#endif + +/* A convenience function to set the filter based on the code. */ +__LA_DECL int archive_write_add_filter(struct archive *, int filter_code); +__LA_DECL int archive_write_add_filter_by_name(struct archive *, + const char *name); +__LA_DECL int archive_write_add_filter_b64encode(struct archive *); +__LA_DECL int archive_write_add_filter_bzip2(struct archive *); +__LA_DECL int archive_write_add_filter_compress(struct archive *); +__LA_DECL int archive_write_add_filter_grzip(struct archive *); +__LA_DECL int archive_write_add_filter_gzip(struct archive *); +__LA_DECL int archive_write_add_filter_lrzip(struct archive *); +__LA_DECL int archive_write_add_filter_lz4(struct archive *); +__LA_DECL int archive_write_add_filter_lzip(struct archive *); +__LA_DECL int archive_write_add_filter_lzma(struct archive *); +__LA_DECL int archive_write_add_filter_lzop(struct archive *); +__LA_DECL int archive_write_add_filter_none(struct archive *); +__LA_DECL int archive_write_add_filter_program(struct archive *, + const char *cmd); +__LA_DECL int archive_write_add_filter_uuencode(struct archive *); +__LA_DECL int archive_write_add_filter_xz(struct archive *); +__LA_DECL int archive_write_add_filter_zstd(struct archive *); + + +/* A convenience function to set the format based on the code or name. */ +__LA_DECL int archive_write_set_format(struct archive *, int format_code); +__LA_DECL int archive_write_set_format_by_name(struct archive *, + const char *name); +/* To minimize link pollution, use one or more of the following. */ +__LA_DECL int archive_write_set_format_7zip(struct archive *); +__LA_DECL int archive_write_set_format_ar_bsd(struct archive *); +__LA_DECL int archive_write_set_format_ar_svr4(struct archive *); +__LA_DECL int archive_write_set_format_cpio(struct archive *); +__LA_DECL int archive_write_set_format_cpio_newc(struct archive *); +__LA_DECL int archive_write_set_format_gnutar(struct archive *); +__LA_DECL int archive_write_set_format_iso9660(struct archive *); +__LA_DECL int archive_write_set_format_mtree(struct archive *); +__LA_DECL int archive_write_set_format_mtree_classic(struct archive *); +/* TODO: int archive_write_set_format_old_tar(struct archive *); */ +__LA_DECL int archive_write_set_format_pax(struct archive *); +__LA_DECL int archive_write_set_format_pax_restricted(struct archive *); +__LA_DECL int archive_write_set_format_raw(struct archive *); +__LA_DECL int archive_write_set_format_shar(struct archive *); +__LA_DECL int archive_write_set_format_shar_dump(struct archive *); +__LA_DECL int archive_write_set_format_ustar(struct archive *); +__LA_DECL int archive_write_set_format_v7tar(struct archive *); +__LA_DECL int archive_write_set_format_warc(struct archive *); +__LA_DECL int archive_write_set_format_xar(struct archive *); +__LA_DECL int archive_write_set_format_zip(struct archive *); +__LA_DECL int archive_write_set_format_filter_by_ext(struct archive *a, const char *filename); +__LA_DECL int archive_write_set_format_filter_by_ext_def(struct archive *a, const char *filename, const char * def_ext); +__LA_DECL int archive_write_zip_set_compression_deflate(struct archive *); +__LA_DECL int archive_write_zip_set_compression_store(struct archive *); +__LA_DECL int archive_write_open(struct archive *, void *, + archive_open_callback *, archive_write_callback *, + archive_close_callback *); +__LA_DECL int archive_write_open_fd(struct archive *, int _fd); +__LA_DECL int archive_write_open_filename(struct archive *, const char *_file); +__LA_DECL int archive_write_open_filename_w(struct archive *, + const wchar_t *_file); +/* A deprecated synonym for archive_write_open_filename() */ +__LA_DECL int archive_write_open_file(struct archive *, const char *_file) + __LA_DEPRECATED; +__LA_DECL int archive_write_open_FILE(struct archive *, FILE *); +/* _buffSize is the size of the buffer, _used refers to a variable that + * will be updated after each write into the buffer. */ +__LA_DECL int archive_write_open_memory(struct archive *, + void *_buffer, size_t _buffSize, size_t *_used); + +/* + * Note that the library will truncate writes beyond the size provided + * to archive_write_header or pad if the provided data is short. + */ +__LA_DECL int archive_write_header(struct archive *, + struct archive_entry *); +__LA_DECL la_ssize_t archive_write_data(struct archive *, + const void *, size_t); + +/* This interface is currently only available for archive_write_disk handles. */ +__LA_DECL la_ssize_t archive_write_data_block(struct archive *, + const void *, size_t, la_int64_t); + +__LA_DECL int archive_write_finish_entry(struct archive *); +__LA_DECL int archive_write_close(struct archive *); +/* Marks the archive as FATAL so that a subsequent free() operation + * won't try to close() cleanly. Provides a fast abort capability + * when the client discovers that things have gone wrong. */ +__LA_DECL int archive_write_fail(struct archive *); +/* This can fail if the archive wasn't already closed, in which case + * archive_write_free() will implicitly call archive_write_close(). */ +__LA_DECL int archive_write_free(struct archive *); +#if ARCHIVE_VERSION_NUMBER < 4000000 +/* Synonym for archive_write_free() for backwards compatibility. */ +__LA_DECL int archive_write_finish(struct archive *) __LA_DEPRECATED; +#endif + +/* + * Set write options. + */ +/* Apply option to the format only. */ +__LA_DECL int archive_write_set_format_option(struct archive *_a, + const char *m, const char *o, + const char *v); +/* Apply option to the filter only. */ +__LA_DECL int archive_write_set_filter_option(struct archive *_a, + const char *m, const char *o, + const char *v); +/* Apply option to both the format and the filter. */ +__LA_DECL int archive_write_set_option(struct archive *_a, + const char *m, const char *o, + const char *v); +/* Apply option string to both the format and the filter. */ +__LA_DECL int archive_write_set_options(struct archive *_a, + const char *opts); + +/* + * Set a encryption passphrase. + */ +__LA_DECL int archive_write_set_passphrase(struct archive *_a, const char *p); +__LA_DECL int archive_write_set_passphrase_callback(struct archive *, + void *client_data, archive_passphrase_callback *); + +/*- + * ARCHIVE_WRITE_DISK API + * + * To create objects on disk: + * 1) Ask archive_write_disk_new for a new archive_write_disk object. + * 2) Set any global properties. In particular, you probably + * want to set the options. + * 3) For each entry: + * - construct an appropriate struct archive_entry structure + * - archive_write_header to create the file/dir/etc on disk + * - archive_write_data to write the entry data + * 4) archive_write_free to cleanup the writer and release resources + * + * In particular, you can use this in conjunction with archive_read() + * to pull entries out of an archive and create them on disk. + */ +__LA_DECL struct archive *archive_write_disk_new(void); +/* This file will not be overwritten. */ +__LA_DECL int archive_write_disk_set_skip_file(struct archive *, + la_int64_t, la_int64_t); +/* Set flags to control how the next item gets created. + * This accepts a bitmask of ARCHIVE_EXTRACT_XXX flags defined above. */ +__LA_DECL int archive_write_disk_set_options(struct archive *, + int flags); +/* + * The lookup functions are given uname/uid (or gname/gid) pairs and + * return a uid (gid) suitable for this system. These are used for + * restoring ownership and for setting ACLs. The default functions + * are naive, they just return the uid/gid. These are small, so reasonable + * for applications that don't need to preserve ownership; they + * are probably also appropriate for applications that are doing + * same-system backup and restore. + */ +/* + * The "standard" lookup functions use common system calls to lookup + * the uname/gname, falling back to the uid/gid if the names can't be + * found. They cache lookups and are reasonably fast, but can be very + * large, so they are not used unless you ask for them. In + * particular, these match the specifications of POSIX "pax" and old + * POSIX "tar". + */ +__LA_DECL int archive_write_disk_set_standard_lookup(struct archive *); +/* + * If neither the default (naive) nor the standard (big) functions suit + * your needs, you can write your own and register them. Be sure to + * include a cleanup function if you have allocated private data. + */ +__LA_DECL int archive_write_disk_set_group_lookup(struct archive *, + void * /* private_data */, + la_int64_t (*)(void *, const char *, la_int64_t), + void (* /* cleanup */)(void *)); +__LA_DECL int archive_write_disk_set_user_lookup(struct archive *, + void * /* private_data */, + la_int64_t (*)(void *, const char *, la_int64_t), + void (* /* cleanup */)(void *)); +__LA_DECL la_int64_t archive_write_disk_gid(struct archive *, const char *, la_int64_t); +__LA_DECL la_int64_t archive_write_disk_uid(struct archive *, const char *, la_int64_t); + +/* + * ARCHIVE_READ_DISK API + * + * This is still evolving and somewhat experimental. + */ +__LA_DECL struct archive *archive_read_disk_new(void); +/* The names for symlink modes here correspond to an old BSD + * command-line argument convention: -L, -P, -H */ +/* Follow all symlinks. */ +__LA_DECL int archive_read_disk_set_symlink_logical(struct archive *); +/* Follow no symlinks. */ +__LA_DECL int archive_read_disk_set_symlink_physical(struct archive *); +/* Follow symlink initially, then not. */ +__LA_DECL int archive_read_disk_set_symlink_hybrid(struct archive *); +/* TODO: Handle Linux stat32/stat64 ugliness. <sigh> */ +__LA_DECL int archive_read_disk_entry_from_file(struct archive *, + struct archive_entry *, int /* fd */, const struct stat *); +/* Look up gname for gid or uname for uid. */ +/* Default implementations are very, very stupid. */ +__LA_DECL const char *archive_read_disk_gname(struct archive *, la_int64_t); +__LA_DECL const char *archive_read_disk_uname(struct archive *, la_int64_t); +/* "Standard" implementation uses getpwuid_r, getgrgid_r and caches the + * results for performance. */ +__LA_DECL int archive_read_disk_set_standard_lookup(struct archive *); +/* You can install your own lookups if you like. */ +__LA_DECL int archive_read_disk_set_gname_lookup(struct archive *, + void * /* private_data */, + const char *(* /* lookup_fn */)(void *, la_int64_t), + void (* /* cleanup_fn */)(void *)); +__LA_DECL int archive_read_disk_set_uname_lookup(struct archive *, + void * /* private_data */, + const char *(* /* lookup_fn */)(void *, la_int64_t), + void (* /* cleanup_fn */)(void *)); +/* Start traversal. */ +__LA_DECL int archive_read_disk_open(struct archive *, const char *); +__LA_DECL int archive_read_disk_open_w(struct archive *, const wchar_t *); +/* + * Request that current entry be visited. If you invoke it on every + * directory, you'll get a physical traversal. This is ignored if the + * current entry isn't a directory or a link to a directory. So, if + * you invoke this on every returned path, you'll get a full logical + * traversal. + */ +__LA_DECL int archive_read_disk_descend(struct archive *); +__LA_DECL int archive_read_disk_can_descend(struct archive *); +__LA_DECL int archive_read_disk_current_filesystem(struct archive *); +__LA_DECL int archive_read_disk_current_filesystem_is_synthetic(struct archive *); +__LA_DECL int archive_read_disk_current_filesystem_is_remote(struct archive *); +/* Request that the access time of the entry visited by traversal be restored. */ +__LA_DECL int archive_read_disk_set_atime_restored(struct archive *); +/* + * Set behavior. The "flags" argument selects optional behavior. + */ +/* Request that the access time of the entry visited by traversal be restored. + * This is the same as archive_read_disk_set_atime_restored. */ +#define ARCHIVE_READDISK_RESTORE_ATIME (0x0001) +/* Default: Do not skip an entry which has nodump flags. */ +#define ARCHIVE_READDISK_HONOR_NODUMP (0x0002) +/* Default: Skip a mac resource fork file whose prefix is "._" because of + * using copyfile. */ +#define ARCHIVE_READDISK_MAC_COPYFILE (0x0004) +/* Default: Traverse mount points. */ +#define ARCHIVE_READDISK_NO_TRAVERSE_MOUNTS (0x0008) +/* Default: Xattrs are read from disk. */ +#define ARCHIVE_READDISK_NO_XATTR (0x0010) +/* Default: ACLs are read from disk. */ +#define ARCHIVE_READDISK_NO_ACL (0x0020) +/* Default: File flags are read from disk. */ +#define ARCHIVE_READDISK_NO_FFLAGS (0x0040) + +__LA_DECL int archive_read_disk_set_behavior(struct archive *, + int flags); + +/* + * Set archive_match object that will be used in archive_read_disk to + * know whether an entry should be skipped. The callback function + * _excluded_func will be invoked when an entry is skipped by the result + * of archive_match. + */ +__LA_DECL int archive_read_disk_set_matching(struct archive *, + struct archive *_matching, void (*_excluded_func) + (struct archive *, void *, struct archive_entry *), + void *_client_data); +__LA_DECL int archive_read_disk_set_metadata_filter_callback(struct archive *, + int (*_metadata_filter_func)(struct archive *, void *, + struct archive_entry *), void *_client_data); + +/* Simplified cleanup interface; + * This calls archive_read_free() or archive_write_free() as needed. */ +__LA_DECL int archive_free(struct archive *); + +/* + * Accessor functions to read/set various information in + * the struct archive object: + */ + +/* Number of filters in the current filter pipeline. */ +/* Filter #0 is the one closest to the format, -1 is a synonym for the + * last filter, which is always the pseudo-filter that wraps the + * client callbacks. */ +__LA_DECL int archive_filter_count(struct archive *); +__LA_DECL la_int64_t archive_filter_bytes(struct archive *, int); +__LA_DECL int archive_filter_code(struct archive *, int); +__LA_DECL const char * archive_filter_name(struct archive *, int); + +#if ARCHIVE_VERSION_NUMBER < 4000000 +/* These don't properly handle multiple filters, so are deprecated and + * will eventually be removed. */ +/* As of libarchive 3.0, this is an alias for archive_filter_bytes(a, -1); */ +__LA_DECL la_int64_t archive_position_compressed(struct archive *) + __LA_DEPRECATED; +/* As of libarchive 3.0, this is an alias for archive_filter_bytes(a, 0); */ +__LA_DECL la_int64_t archive_position_uncompressed(struct archive *) + __LA_DEPRECATED; +/* As of libarchive 3.0, this is an alias for archive_filter_name(a, 0); */ +__LA_DECL const char *archive_compression_name(struct archive *) + __LA_DEPRECATED; +/* As of libarchive 3.0, this is an alias for archive_filter_code(a, 0); */ +__LA_DECL int archive_compression(struct archive *) + __LA_DEPRECATED; +#endif + +__LA_DECL int archive_errno(struct archive *); +__LA_DECL const char *archive_error_string(struct archive *); +__LA_DECL const char *archive_format_name(struct archive *); +__LA_DECL int archive_format(struct archive *); +__LA_DECL void archive_clear_error(struct archive *); +__LA_DECL void archive_set_error(struct archive *, int _err, + const char *fmt, ...) __LA_PRINTF(3, 4); +__LA_DECL void archive_copy_error(struct archive *dest, + struct archive *src); +__LA_DECL int archive_file_count(struct archive *); + +/* + * ARCHIVE_MATCH API + */ +__LA_DECL struct archive *archive_match_new(void); +__LA_DECL int archive_match_free(struct archive *); + +/* + * Test if archive_entry is excluded. + * This is a convenience function. This is the same as calling all + * archive_match_path_excluded, archive_match_time_excluded + * and archive_match_owner_excluded. + */ +__LA_DECL int archive_match_excluded(struct archive *, + struct archive_entry *); + +/* + * Test if pathname is excluded. The conditions are set by following functions. + */ +__LA_DECL int archive_match_path_excluded(struct archive *, + struct archive_entry *); +/* Control recursive inclusion of directory content when directory is included. Default on. */ +__LA_DECL int archive_match_set_inclusion_recursion(struct archive *, int); +/* Add exclusion pathname pattern. */ +__LA_DECL int archive_match_exclude_pattern(struct archive *, const char *); +__LA_DECL int archive_match_exclude_pattern_w(struct archive *, + const wchar_t *); +/* Add exclusion pathname pattern from file. */ +__LA_DECL int archive_match_exclude_pattern_from_file(struct archive *, + const char *, int _nullSeparator); +__LA_DECL int archive_match_exclude_pattern_from_file_w(struct archive *, + const wchar_t *, int _nullSeparator); +/* Add inclusion pathname pattern. */ +__LA_DECL int archive_match_include_pattern(struct archive *, const char *); +__LA_DECL int archive_match_include_pattern_w(struct archive *, + const wchar_t *); +/* Add inclusion pathname pattern from file. */ +__LA_DECL int archive_match_include_pattern_from_file(struct archive *, + const char *, int _nullSeparator); +__LA_DECL int archive_match_include_pattern_from_file_w(struct archive *, + const wchar_t *, int _nullSeparator); +/* + * How to get statistic information for inclusion patterns. + */ +/* Return the amount number of unmatched inclusion patterns. */ +__LA_DECL int archive_match_path_unmatched_inclusions(struct archive *); +/* Return the pattern of unmatched inclusion with ARCHIVE_OK. + * Return ARCHIVE_EOF if there is no inclusion pattern. */ +__LA_DECL int archive_match_path_unmatched_inclusions_next( + struct archive *, const char **); +__LA_DECL int archive_match_path_unmatched_inclusions_next_w( + struct archive *, const wchar_t **); + +/* + * Test if a file is excluded by its time stamp. + * The conditions are set by following functions. + */ +__LA_DECL int archive_match_time_excluded(struct archive *, + struct archive_entry *); + +/* + * Flags to tell a matching type of time stamps. These are used for + * following functions. + */ +/* Time flag: mtime to be tested. */ +#define ARCHIVE_MATCH_MTIME (0x0100) +/* Time flag: ctime to be tested. */ +#define ARCHIVE_MATCH_CTIME (0x0200) +/* Comparison flag: Match the time if it is newer than. */ +#define ARCHIVE_MATCH_NEWER (0x0001) +/* Comparison flag: Match the time if it is older than. */ +#define ARCHIVE_MATCH_OLDER (0x0002) +/* Comparison flag: Match the time if it is equal to. */ +#define ARCHIVE_MATCH_EQUAL (0x0010) +/* Set inclusion time. */ +__LA_DECL int archive_match_include_time(struct archive *, int _flag, + time_t _sec, long _nsec); +/* Set inclusion time by a date string. */ +__LA_DECL int archive_match_include_date(struct archive *, int _flag, + const char *_datestr); +__LA_DECL int archive_match_include_date_w(struct archive *, int _flag, + const wchar_t *_datestr); +/* Set inclusion time by a particular file. */ +__LA_DECL int archive_match_include_file_time(struct archive *, + int _flag, const char *_pathname); +__LA_DECL int archive_match_include_file_time_w(struct archive *, + int _flag, const wchar_t *_pathname); +/* Add exclusion entry. */ +__LA_DECL int archive_match_exclude_entry(struct archive *, + int _flag, struct archive_entry *); + +/* + * Test if a file is excluded by its uid ,gid, uname or gname. + * The conditions are set by following functions. + */ +__LA_DECL int archive_match_owner_excluded(struct archive *, + struct archive_entry *); +/* Add inclusion uid, gid, uname and gname. */ +__LA_DECL int archive_match_include_uid(struct archive *, la_int64_t); +__LA_DECL int archive_match_include_gid(struct archive *, la_int64_t); +__LA_DECL int archive_match_include_uname(struct archive *, const char *); +__LA_DECL int archive_match_include_uname_w(struct archive *, + const wchar_t *); +__LA_DECL int archive_match_include_gname(struct archive *, const char *); +__LA_DECL int archive_match_include_gname_w(struct archive *, + const wchar_t *); + +/* Utility functions */ +/* Convenience function to sort a NULL terminated list of strings */ +__LA_DECL int archive_utility_string_sort(char **); + +#ifdef __cplusplus +} +#endif + +/* These are meaningless outside of this header. */ +#undef __LA_DECL + +#endif /* !ARCHIVE_H_INCLUDED */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_acl.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_acl.c new file mode 100644 index 0000000000..952e20df4d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_acl.c @@ -0,0 +1,2097 @@ +/*- + * Copyright (c) 2003-2010 Tim Kientzle + * Copyright (c) 2016 Martin Matuska + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#ifdef HAVE_WCHAR_H +#include <wchar.h> +#endif + +#include "archive_acl_private.h" +#include "archive_entry.h" +#include "archive_private.h" + +#undef max +#define max(a, b) ((a)>(b)?(a):(b)) + +#ifndef HAVE_WMEMCMP +/* Good enough for simple equality testing, but not for sorting. */ +#define wmemcmp(a,b,i) memcmp((a), (b), (i) * sizeof(wchar_t)) +#endif + +static int acl_special(struct archive_acl *acl, + int type, int permset, int tag); +static struct archive_acl_entry *acl_new_entry(struct archive_acl *acl, + int type, int permset, int tag, int id); +static int archive_acl_add_entry_len_l(struct archive_acl *acl, + int type, int permset, int tag, int id, const char *name, + size_t len, struct archive_string_conv *sc); +static int archive_acl_text_want_type(struct archive_acl *acl, int flags); +static ssize_t archive_acl_text_len(struct archive_acl *acl, int want_type, + int flags, int wide, struct archive *a, + struct archive_string_conv *sc); +static int isint_w(const wchar_t *start, const wchar_t *end, int *result); +static int ismode_w(const wchar_t *start, const wchar_t *end, int *result); +static int is_nfs4_flags_w(const wchar_t *start, const wchar_t *end, + int *result); +static int is_nfs4_perms_w(const wchar_t *start, const wchar_t *end, + int *result); +static void next_field_w(const wchar_t **wp, const wchar_t **start, + const wchar_t **end, wchar_t *sep); +static void append_entry_w(wchar_t **wp, const wchar_t *prefix, int type, + int tag, int flags, const wchar_t *wname, int perm, int id); +static void append_id_w(wchar_t **wp, int id); +static int isint(const char *start, const char *end, int *result); +static int ismode(const char *start, const char *end, int *result); +static int is_nfs4_flags(const char *start, const char *end, + int *result); +static int is_nfs4_perms(const char *start, const char *end, + int *result); +static void next_field(const char **p, const char **start, + const char **end, char *sep); +static void append_entry(char **p, const char *prefix, int type, + int tag, int flags, const char *name, int perm, int id); +static void append_id(char **p, int id); + +static const struct { + const int perm; + const char c; + const wchar_t wc; +} nfsv4_acl_perm_map[] = { + { ARCHIVE_ENTRY_ACL_READ_DATA | ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, 'r', + L'r' }, + { ARCHIVE_ENTRY_ACL_WRITE_DATA | ARCHIVE_ENTRY_ACL_ADD_FILE, 'w', + L'w' }, + { ARCHIVE_ENTRY_ACL_EXECUTE, 'x', L'x' }, + { ARCHIVE_ENTRY_ACL_APPEND_DATA | ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, + 'p', L'p' }, + { ARCHIVE_ENTRY_ACL_DELETE, 'd', L'd' }, + { ARCHIVE_ENTRY_ACL_DELETE_CHILD, 'D', L'D' }, + { ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, 'a', L'a' }, + { ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, 'A', L'A' }, + { ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, 'R', L'R' }, + { ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, 'W', L'W' }, + { ARCHIVE_ENTRY_ACL_READ_ACL, 'c', L'c' }, + { ARCHIVE_ENTRY_ACL_WRITE_ACL, 'C', L'C' }, + { ARCHIVE_ENTRY_ACL_WRITE_OWNER, 'o', L'o' }, + { ARCHIVE_ENTRY_ACL_SYNCHRONIZE, 's', L's' } +}; + +static const int nfsv4_acl_perm_map_size = (int)(sizeof(nfsv4_acl_perm_map) / + sizeof(nfsv4_acl_perm_map[0])); + +static const struct { + const int perm; + const char c; + const wchar_t wc; +} nfsv4_acl_flag_map[] = { + { ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, 'f', L'f' }, + { ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, 'd', L'd' }, + { ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, 'i', L'i' }, + { ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, 'n', L'n' }, + { ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS, 'S', L'S' }, + { ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS, 'F', L'F' }, + { ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, 'I', L'I' } +}; + +static const int nfsv4_acl_flag_map_size = (int)(sizeof(nfsv4_acl_flag_map) / + sizeof(nfsv4_acl_flag_map[0])); + +void +archive_acl_clear(struct archive_acl *acl) +{ + struct archive_acl_entry *ap; + + while (acl->acl_head != NULL) { + ap = acl->acl_head->next; + archive_mstring_clean(&acl->acl_head->name); + free(acl->acl_head); + acl->acl_head = ap; + } + free(acl->acl_text_w); + acl->acl_text_w = NULL; + free(acl->acl_text); + acl->acl_text = NULL; + acl->acl_p = NULL; + acl->acl_types = 0; + acl->acl_state = 0; /* Not counting. */ +} + +void +archive_acl_copy(struct archive_acl *dest, struct archive_acl *src) +{ + struct archive_acl_entry *ap, *ap2; + + archive_acl_clear(dest); + + dest->mode = src->mode; + ap = src->acl_head; + while (ap != NULL) { + ap2 = acl_new_entry(dest, + ap->type, ap->permset, ap->tag, ap->id); + if (ap2 != NULL) + archive_mstring_copy(&ap2->name, &ap->name); + ap = ap->next; + } +} + +int +archive_acl_add_entry(struct archive_acl *acl, + int type, int permset, int tag, int id, const char *name) +{ + struct archive_acl_entry *ap; + + if (acl_special(acl, type, permset, tag) == 0) + return ARCHIVE_OK; + ap = acl_new_entry(acl, type, permset, tag, id); + if (ap == NULL) { + /* XXX Error XXX */ + return ARCHIVE_FAILED; + } + if (name != NULL && *name != '\0') + archive_mstring_copy_mbs(&ap->name, name); + else + archive_mstring_clean(&ap->name); + return ARCHIVE_OK; +} + +int +archive_acl_add_entry_w_len(struct archive_acl *acl, + int type, int permset, int tag, int id, const wchar_t *name, size_t len) +{ + struct archive_acl_entry *ap; + + if (acl_special(acl, type, permset, tag) == 0) + return ARCHIVE_OK; + ap = acl_new_entry(acl, type, permset, tag, id); + if (ap == NULL) { + /* XXX Error XXX */ + return ARCHIVE_FAILED; + } + if (name != NULL && *name != L'\0' && len > 0) + archive_mstring_copy_wcs_len(&ap->name, name, len); + else + archive_mstring_clean(&ap->name); + return ARCHIVE_OK; +} + +static int +archive_acl_add_entry_len_l(struct archive_acl *acl, + int type, int permset, int tag, int id, const char *name, size_t len, + struct archive_string_conv *sc) +{ + struct archive_acl_entry *ap; + int r; + + if (acl_special(acl, type, permset, tag) == 0) + return ARCHIVE_OK; + ap = acl_new_entry(acl, type, permset, tag, id); + if (ap == NULL) { + /* XXX Error XXX */ + return ARCHIVE_FAILED; + } + if (name != NULL && *name != '\0' && len > 0) { + r = archive_mstring_copy_mbs_len_l(&ap->name, name, len, sc); + } else { + r = 0; + archive_mstring_clean(&ap->name); + } + if (r == 0) + return (ARCHIVE_OK); + else if (errno == ENOMEM) + return (ARCHIVE_FATAL); + else + return (ARCHIVE_WARN); +} + +/* + * If this ACL entry is part of the standard POSIX permissions set, + * store the permissions in the stat structure and return zero. + */ +static int +acl_special(struct archive_acl *acl, int type, int permset, int tag) +{ + if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS + && ((permset & ~007) == 0)) { + switch (tag) { + case ARCHIVE_ENTRY_ACL_USER_OBJ: + acl->mode &= ~0700; + acl->mode |= (permset & 7) << 6; + return (0); + case ARCHIVE_ENTRY_ACL_GROUP_OBJ: + acl->mode &= ~0070; + acl->mode |= (permset & 7) << 3; + return (0); + case ARCHIVE_ENTRY_ACL_OTHER: + acl->mode &= ~0007; + acl->mode |= permset & 7; + return (0); + } + } + return (1); +} + +/* + * Allocate and populate a new ACL entry with everything but the + * name. + */ +static struct archive_acl_entry * +acl_new_entry(struct archive_acl *acl, + int type, int permset, int tag, int id) +{ + struct archive_acl_entry *ap, *aq; + + /* Type argument must be a valid NFS4 or POSIX.1e type. + * The type must agree with anything already set and + * the permset must be compatible. */ + if (type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + if (acl->acl_types & ~ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + return (NULL); + } + if (permset & + ~(ARCHIVE_ENTRY_ACL_PERMS_NFS4 + | ARCHIVE_ENTRY_ACL_INHERITANCE_NFS4)) { + return (NULL); + } + } else if (type & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) { + if (acl->acl_types & ~ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) { + return (NULL); + } + if (permset & ~ARCHIVE_ENTRY_ACL_PERMS_POSIX1E) { + return (NULL); + } + } else { + return (NULL); + } + + /* Verify the tag is valid and compatible with NFS4 or POSIX.1e. */ + switch (tag) { + case ARCHIVE_ENTRY_ACL_USER: + case ARCHIVE_ENTRY_ACL_USER_OBJ: + case ARCHIVE_ENTRY_ACL_GROUP: + case ARCHIVE_ENTRY_ACL_GROUP_OBJ: + /* Tags valid in both NFS4 and POSIX.1e */ + break; + case ARCHIVE_ENTRY_ACL_MASK: + case ARCHIVE_ENTRY_ACL_OTHER: + /* Tags valid only in POSIX.1e. */ + if (type & ~ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) { + return (NULL); + } + break; + case ARCHIVE_ENTRY_ACL_EVERYONE: + /* Tags valid only in NFS4. */ + if (type & ~ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + return (NULL); + } + break; + default: + /* No other values are valid. */ + return (NULL); + } + + free(acl->acl_text_w); + acl->acl_text_w = NULL; + free(acl->acl_text); + acl->acl_text = NULL; + + /* + * If there's a matching entry already in the list, overwrite it. + * NFSv4 entries may be repeated and are not overwritten. + * + * TODO: compare names of no id is provided (needs more rework) + */ + ap = acl->acl_head; + aq = NULL; + while (ap != NULL) { + if (((type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) == 0) && + ap->type == type && ap->tag == tag && ap->id == id) { + if (id != -1 || (tag != ARCHIVE_ENTRY_ACL_USER && + tag != ARCHIVE_ENTRY_ACL_GROUP)) { + ap->permset = permset; + return (ap); + } + } + aq = ap; + ap = ap->next; + } + + /* Add a new entry to the end of the list. */ + ap = (struct archive_acl_entry *)calloc(1, sizeof(*ap)); + if (ap == NULL) + return (NULL); + if (aq == NULL) + acl->acl_head = ap; + else + aq->next = ap; + ap->type = type; + ap->tag = tag; + ap->id = id; + ap->permset = permset; + acl->acl_types |= type; + return (ap); +} + +/* + * Return a count of entries matching "want_type". + */ +int +archive_acl_count(struct archive_acl *acl, int want_type) +{ + int count; + struct archive_acl_entry *ap; + + count = 0; + ap = acl->acl_head; + while (ap != NULL) { + if ((ap->type & want_type) != 0) + count++; + ap = ap->next; + } + + if (count > 0 && ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0)) + count += 3; + return (count); +} + +/* + * Return a bitmask of stored ACL types in an ACL list + */ +int +archive_acl_types(struct archive_acl *acl) +{ + return (acl->acl_types); +} + +/* + * Prepare for reading entries from the ACL data. Returns a count + * of entries matching "want_type", or zero if there are no + * non-extended ACL entries of that type. + */ +int +archive_acl_reset(struct archive_acl *acl, int want_type) +{ + int count, cutoff; + + count = archive_acl_count(acl, want_type); + + /* + * If the only entries are the three standard ones, + * then don't return any ACL data. (In this case, + * client can just use chmod(2) to set permissions.) + */ + if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) + cutoff = 3; + else + cutoff = 0; + + if (count > cutoff) + acl->acl_state = ARCHIVE_ENTRY_ACL_USER_OBJ; + else + acl->acl_state = 0; + acl->acl_p = acl->acl_head; + return (count); +} + + +/* + * Return the next ACL entry in the list. Fake entries for the + * standard permissions and include them in the returned list. + */ +int +archive_acl_next(struct archive *a, struct archive_acl *acl, int want_type, + int *type, int *permset, int *tag, int *id, const char **name) +{ + *name = NULL; + *id = -1; + + /* + * The acl_state is either zero (no entries available), -1 + * (reading from list), or an entry type (retrieve that type + * from ae_stat.aest_mode). + */ + if (acl->acl_state == 0) + return (ARCHIVE_WARN); + + /* The first three access entries are special. */ + if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) { + switch (acl->acl_state) { + case ARCHIVE_ENTRY_ACL_USER_OBJ: + *permset = (acl->mode >> 6) & 7; + *type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; + *tag = ARCHIVE_ENTRY_ACL_USER_OBJ; + acl->acl_state = ARCHIVE_ENTRY_ACL_GROUP_OBJ; + return (ARCHIVE_OK); + case ARCHIVE_ENTRY_ACL_GROUP_OBJ: + *permset = (acl->mode >> 3) & 7; + *type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; + *tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; + acl->acl_state = ARCHIVE_ENTRY_ACL_OTHER; + return (ARCHIVE_OK); + case ARCHIVE_ENTRY_ACL_OTHER: + *permset = acl->mode & 7; + *type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; + *tag = ARCHIVE_ENTRY_ACL_OTHER; + acl->acl_state = -1; + acl->acl_p = acl->acl_head; + return (ARCHIVE_OK); + default: + break; + } + } + + while (acl->acl_p != NULL && (acl->acl_p->type & want_type) == 0) + acl->acl_p = acl->acl_p->next; + if (acl->acl_p == NULL) { + acl->acl_state = 0; + *type = 0; + *permset = 0; + *tag = 0; + *id = -1; + *name = NULL; + return (ARCHIVE_EOF); /* End of ACL entries. */ + } + *type = acl->acl_p->type; + *permset = acl->acl_p->permset; + *tag = acl->acl_p->tag; + *id = acl->acl_p->id; + if (archive_mstring_get_mbs(a, &acl->acl_p->name, name) != 0) { + if (errno == ENOMEM) + return (ARCHIVE_FATAL); + *name = NULL; + } + acl->acl_p = acl->acl_p->next; + return (ARCHIVE_OK); +} + +/* + * Determine what type of ACL do we want + */ +static int +archive_acl_text_want_type(struct archive_acl *acl, int flags) +{ + int want_type; + + /* Check if ACL is NFSv4 */ + if ((acl->acl_types & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { + /* NFSv4 should never mix with POSIX.1e */ + if ((acl->acl_types & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) + return (0); + else + return (ARCHIVE_ENTRY_ACL_TYPE_NFS4); + } + + /* Now deal with POSIX.1e ACLs */ + + want_type = 0; + if ((flags & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) + want_type |= ARCHIVE_ENTRY_ACL_TYPE_ACCESS; + if ((flags & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0) + want_type |= ARCHIVE_ENTRY_ACL_TYPE_DEFAULT; + + /* By default we want both access and default ACLs */ + if (want_type == 0) + return (ARCHIVE_ENTRY_ACL_TYPE_POSIX1E); + + return (want_type); +} + +/* + * Calculate ACL text string length + */ +static ssize_t +archive_acl_text_len(struct archive_acl *acl, int want_type, int flags, + int wide, struct archive *a, struct archive_string_conv *sc) { + struct archive_acl_entry *ap; + const char *name; + const wchar_t *wname; + int count, idlen, tmp, r; + ssize_t length; + size_t len; + + count = 0; + length = 0; + for (ap = acl->acl_head; ap != NULL; ap = ap->next) { + if ((ap->type & want_type) == 0) + continue; + /* + * Filemode-mapping ACL entries are stored exclusively in + * ap->mode so they should not be in the list + */ + if ((ap->type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS) + && (ap->tag == ARCHIVE_ENTRY_ACL_USER_OBJ + || ap->tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ + || ap->tag == ARCHIVE_ENTRY_ACL_OTHER)) + continue; + count++; + if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0 + && (ap->type & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0) + length += 8; /* "default:" */ + switch (ap->tag) { + case ARCHIVE_ENTRY_ACL_USER_OBJ: + if (want_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + length += 6; /* "owner@" */ + break; + } + /* FALLTHROUGH */ + case ARCHIVE_ENTRY_ACL_USER: + case ARCHIVE_ENTRY_ACL_MASK: + length += 4; /* "user", "mask" */ + break; + case ARCHIVE_ENTRY_ACL_GROUP_OBJ: + if (want_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + length += 6; /* "group@" */ + break; + } + /* FALLTHROUGH */ + case ARCHIVE_ENTRY_ACL_GROUP: + case ARCHIVE_ENTRY_ACL_OTHER: + length += 5; /* "group", "other" */ + break; + case ARCHIVE_ENTRY_ACL_EVERYONE: + length += 9; /* "everyone@" */ + break; + } + length += 1; /* colon after tag */ + if (ap->tag == ARCHIVE_ENTRY_ACL_USER || + ap->tag == ARCHIVE_ENTRY_ACL_GROUP) { + if (wide) { + r = archive_mstring_get_wcs(a, &ap->name, + &wname); + if (r == 0 && wname != NULL) + length += wcslen(wname); + else if (r < 0 && errno == ENOMEM) + return (0); + else + length += sizeof(uid_t) * 3 + 1; + } else { + r = archive_mstring_get_mbs_l(&ap->name, &name, + &len, sc); + if (r != 0) + return (0); + if (len > 0 && name != NULL) + length += len; + else + length += sizeof(uid_t) * 3 + 1; + } + length += 1; /* colon after user or group name */ + } else if (want_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) + length += 1; /* 2nd colon empty user,group or other */ + + if (((flags & ARCHIVE_ENTRY_ACL_STYLE_SOLARIS) != 0) + && ((want_type & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) + && (ap->tag == ARCHIVE_ENTRY_ACL_OTHER + || ap->tag == ARCHIVE_ENTRY_ACL_MASK)) { + /* Solaris has no colon after other: and mask: */ + length = length - 1; + } + + if (want_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + /* rwxpdDaARWcCos:fdinSFI:deny */ + length += 27; + if ((ap->type & ARCHIVE_ENTRY_ACL_TYPE_DENY) == 0) + length += 1; /* allow, alarm, audit */ + } else + length += 3; /* rwx */ + + if ((ap->tag == ARCHIVE_ENTRY_ACL_USER || + ap->tag == ARCHIVE_ENTRY_ACL_GROUP) && + (flags & ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID) != 0) { + length += 1; /* colon */ + /* ID digit count */ + idlen = 1; + tmp = ap->id; + while (tmp > 9) { + tmp = tmp / 10; + idlen++; + } + length += idlen; + } + length ++; /* entry separator */ + } + + /* Add filemode-mapping access entries to the length */ + if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) { + if ((flags & ARCHIVE_ENTRY_ACL_STYLE_SOLARIS) != 0) { + /* "user::rwx\ngroup::rwx\nother:rwx\n" */ + length += 31; + } else { + /* "user::rwx\ngroup::rwx\nother::rwx\n" */ + length += 32; + } + } else if (count == 0) + return (0); + + /* The terminating character is included in count */ + return (length); +} + +/* + * Generate a wide text version of the ACL. The flags parameter controls + * the type and style of the generated ACL. + */ +wchar_t * +archive_acl_to_text_w(struct archive_acl *acl, ssize_t *text_len, int flags, + struct archive *a) +{ + int count; + ssize_t length; + size_t len; + const wchar_t *wname; + const wchar_t *prefix; + wchar_t separator; + struct archive_acl_entry *ap; + int id, r, want_type; + wchar_t *wp, *ws; + + want_type = archive_acl_text_want_type(acl, flags); + + /* Both NFSv4 and POSIX.1 types found */ + if (want_type == 0) + return (NULL); + + if (want_type == ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) + flags |= ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT; + + length = archive_acl_text_len(acl, want_type, flags, 1, a, NULL); + + if (length == 0) + return (NULL); + + if (flags & ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA) + separator = L','; + else + separator = L'\n'; + + /* Now, allocate the string and actually populate it. */ + wp = ws = (wchar_t *)malloc(length * sizeof(wchar_t)); + if (wp == NULL) { + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); + } + count = 0; + + if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) { + append_entry_w(&wp, NULL, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, + ARCHIVE_ENTRY_ACL_USER_OBJ, flags, NULL, + acl->mode & 0700, -1); + *wp++ = separator; + append_entry_w(&wp, NULL, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, + ARCHIVE_ENTRY_ACL_GROUP_OBJ, flags, NULL, + acl->mode & 0070, -1); + *wp++ = separator; + append_entry_w(&wp, NULL, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, + ARCHIVE_ENTRY_ACL_OTHER, flags, NULL, + acl->mode & 0007, -1); + count += 3; + } + + for (ap = acl->acl_head; ap != NULL; ap = ap->next) { + if ((ap->type & want_type) == 0) + continue; + /* + * Filemode-mapping ACL entries are stored exclusively in + * ap->mode so they should not be in the list + */ + if ((ap->type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS) + && (ap->tag == ARCHIVE_ENTRY_ACL_USER_OBJ + || ap->tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ + || ap->tag == ARCHIVE_ENTRY_ACL_OTHER)) + continue; + if (ap->type == ARCHIVE_ENTRY_ACL_TYPE_DEFAULT && + (flags & ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT) != 0) + prefix = L"default:"; + else + prefix = NULL; + r = archive_mstring_get_wcs(a, &ap->name, &wname); + if (r == 0) { + if (count > 0) + *wp++ = separator; + if (flags & ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID) + id = ap->id; + else + id = -1; + append_entry_w(&wp, prefix, ap->type, ap->tag, flags, + wname, ap->permset, id); + count++; + } else if (r < 0 && errno == ENOMEM) { + free(ws); + return (NULL); + } + } + + /* Add terminating character */ + *wp++ = L'\0'; + + len = wcslen(ws); + + if ((ssize_t)len > (length - 1)) + __archive_errx(1, "Buffer overrun"); + + if (text_len != NULL) + *text_len = len; + + return (ws); +} + +static void +append_id_w(wchar_t **wp, int id) +{ + if (id < 0) + id = 0; + if (id > 9) + append_id_w(wp, id / 10); + *(*wp)++ = L"0123456789"[id % 10]; +} + +static void +append_entry_w(wchar_t **wp, const wchar_t *prefix, int type, + int tag, int flags, const wchar_t *wname, int perm, int id) +{ + int i; + + if (prefix != NULL) { + wcscpy(*wp, prefix); + *wp += wcslen(*wp); + } + switch (tag) { + case ARCHIVE_ENTRY_ACL_USER_OBJ: + wname = NULL; + id = -1; + if ((type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { + wcscpy(*wp, L"owner@"); + break; + } + /* FALLTHROUGH */ + case ARCHIVE_ENTRY_ACL_USER: + wcscpy(*wp, L"user"); + break; + case ARCHIVE_ENTRY_ACL_GROUP_OBJ: + wname = NULL; + id = -1; + if ((type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { + wcscpy(*wp, L"group@"); + break; + } + /* FALLTHROUGH */ + case ARCHIVE_ENTRY_ACL_GROUP: + wcscpy(*wp, L"group"); + break; + case ARCHIVE_ENTRY_ACL_MASK: + wcscpy(*wp, L"mask"); + wname = NULL; + id = -1; + break; + case ARCHIVE_ENTRY_ACL_OTHER: + wcscpy(*wp, L"other"); + wname = NULL; + id = -1; + break; + case ARCHIVE_ENTRY_ACL_EVERYONE: + wcscpy(*wp, L"everyone@"); + wname = NULL; + id = -1; + break; + } + *wp += wcslen(*wp); + *(*wp)++ = L':'; + if (((type & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) || + tag == ARCHIVE_ENTRY_ACL_USER || + tag == ARCHIVE_ENTRY_ACL_GROUP) { + if (wname != NULL) { + wcscpy(*wp, wname); + *wp += wcslen(*wp); + } else if (tag == ARCHIVE_ENTRY_ACL_USER + || tag == ARCHIVE_ENTRY_ACL_GROUP) { + append_id_w(wp, id); + if ((type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) == 0) + id = -1; + } + /* Solaris style has no second colon after other and mask */ + if (((flags & ARCHIVE_ENTRY_ACL_STYLE_SOLARIS) == 0) + || (tag != ARCHIVE_ENTRY_ACL_OTHER + && tag != ARCHIVE_ENTRY_ACL_MASK)) + *(*wp)++ = L':'; + } + if ((type & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) { + /* POSIX.1e ACL perms */ + *(*wp)++ = (perm & 0444) ? L'r' : L'-'; + *(*wp)++ = (perm & 0222) ? L'w' : L'-'; + *(*wp)++ = (perm & 0111) ? L'x' : L'-'; + } else { + /* NFSv4 ACL perms */ + for (i = 0; i < nfsv4_acl_perm_map_size; i++) { + if (perm & nfsv4_acl_perm_map[i].perm) + *(*wp)++ = nfsv4_acl_perm_map[i].wc; + else if ((flags & ARCHIVE_ENTRY_ACL_STYLE_COMPACT) == 0) + *(*wp)++ = L'-'; + } + *(*wp)++ = L':'; + for (i = 0; i < nfsv4_acl_flag_map_size; i++) { + if (perm & nfsv4_acl_flag_map[i].perm) + *(*wp)++ = nfsv4_acl_flag_map[i].wc; + else if ((flags & ARCHIVE_ENTRY_ACL_STYLE_COMPACT) == 0) + *(*wp)++ = L'-'; + } + *(*wp)++ = L':'; + switch (type) { + case ARCHIVE_ENTRY_ACL_TYPE_ALLOW: + wcscpy(*wp, L"allow"); + break; + case ARCHIVE_ENTRY_ACL_TYPE_DENY: + wcscpy(*wp, L"deny"); + break; + case ARCHIVE_ENTRY_ACL_TYPE_AUDIT: + wcscpy(*wp, L"audit"); + break; + case ARCHIVE_ENTRY_ACL_TYPE_ALARM: + wcscpy(*wp, L"alarm"); + break; + default: + break; + } + *wp += wcslen(*wp); + } + if (id != -1) { + *(*wp)++ = L':'; + append_id_w(wp, id); + } +} + +/* + * Generate a text version of the ACL. The flags parameter controls + * the type and style of the generated ACL. + */ +char * +archive_acl_to_text_l(struct archive_acl *acl, ssize_t *text_len, int flags, + struct archive_string_conv *sc) +{ + int count; + ssize_t length; + size_t len; + const char *name; + const char *prefix; + char separator; + struct archive_acl_entry *ap; + int id, r, want_type; + char *p, *s; + + want_type = archive_acl_text_want_type(acl, flags); + + /* Both NFSv4 and POSIX.1 types found */ + if (want_type == 0) + return (NULL); + + if (want_type == ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) + flags |= ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT; + + length = archive_acl_text_len(acl, want_type, flags, 0, NULL, sc); + + if (length == 0) + return (NULL); + + if (flags & ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA) + separator = ','; + else + separator = '\n'; + + /* Now, allocate the string and actually populate it. */ + p = s = (char *)malloc(length * sizeof(char)); + if (p == NULL) { + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); + } + count = 0; + + if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) { + append_entry(&p, NULL, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, + ARCHIVE_ENTRY_ACL_USER_OBJ, flags, NULL, + acl->mode & 0700, -1); + *p++ = separator; + append_entry(&p, NULL, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, + ARCHIVE_ENTRY_ACL_GROUP_OBJ, flags, NULL, + acl->mode & 0070, -1); + *p++ = separator; + append_entry(&p, NULL, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, + ARCHIVE_ENTRY_ACL_OTHER, flags, NULL, + acl->mode & 0007, -1); + count += 3; + } + + for (ap = acl->acl_head; ap != NULL; ap = ap->next) { + if ((ap->type & want_type) == 0) + continue; + /* + * Filemode-mapping ACL entries are stored exclusively in + * ap->mode so they should not be in the list + */ + if ((ap->type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS) + && (ap->tag == ARCHIVE_ENTRY_ACL_USER_OBJ + || ap->tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ + || ap->tag == ARCHIVE_ENTRY_ACL_OTHER)) + continue; + if (ap->type == ARCHIVE_ENTRY_ACL_TYPE_DEFAULT && + (flags & ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT) != 0) + prefix = "default:"; + else + prefix = NULL; + r = archive_mstring_get_mbs_l( + &ap->name, &name, &len, sc); + if (r != 0) { + free(s); + return (NULL); + } + if (count > 0) + *p++ = separator; + if (name == NULL || + (flags & ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID)) { + id = ap->id; + } else { + id = -1; + } + append_entry(&p, prefix, ap->type, ap->tag, flags, name, + ap->permset, id); + count++; + } + + /* Add terminating character */ + *p++ = '\0'; + + len = strlen(s); + + if ((ssize_t)len > (length - 1)) + __archive_errx(1, "Buffer overrun"); + + if (text_len != NULL) + *text_len = len; + + return (s); +} + +static void +append_id(char **p, int id) +{ + if (id < 0) + id = 0; + if (id > 9) + append_id(p, id / 10); + *(*p)++ = "0123456789"[id % 10]; +} + +static void +append_entry(char **p, const char *prefix, int type, + int tag, int flags, const char *name, int perm, int id) +{ + int i; + + if (prefix != NULL) { + strcpy(*p, prefix); + *p += strlen(*p); + } + switch (tag) { + case ARCHIVE_ENTRY_ACL_USER_OBJ: + name = NULL; + id = -1; + if ((type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { + strcpy(*p, "owner@"); + break; + } + /* FALLTHROUGH */ + case ARCHIVE_ENTRY_ACL_USER: + strcpy(*p, "user"); + break; + case ARCHIVE_ENTRY_ACL_GROUP_OBJ: + name = NULL; + id = -1; + if ((type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { + strcpy(*p, "group@"); + break; + } + /* FALLTHROUGH */ + case ARCHIVE_ENTRY_ACL_GROUP: + strcpy(*p, "group"); + break; + case ARCHIVE_ENTRY_ACL_MASK: + strcpy(*p, "mask"); + name = NULL; + id = -1; + break; + case ARCHIVE_ENTRY_ACL_OTHER: + strcpy(*p, "other"); + name = NULL; + id = -1; + break; + case ARCHIVE_ENTRY_ACL_EVERYONE: + strcpy(*p, "everyone@"); + name = NULL; + id = -1; + break; + } + *p += strlen(*p); + *(*p)++ = ':'; + if (((type & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) || + tag == ARCHIVE_ENTRY_ACL_USER || + tag == ARCHIVE_ENTRY_ACL_GROUP) { + if (name != NULL) { + strcpy(*p, name); + *p += strlen(*p); + } else if (tag == ARCHIVE_ENTRY_ACL_USER + || tag == ARCHIVE_ENTRY_ACL_GROUP) { + append_id(p, id); + if ((type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) == 0) + id = -1; + } + /* Solaris style has no second colon after other and mask */ + if (((flags & ARCHIVE_ENTRY_ACL_STYLE_SOLARIS) == 0) + || (tag != ARCHIVE_ENTRY_ACL_OTHER + && tag != ARCHIVE_ENTRY_ACL_MASK)) + *(*p)++ = ':'; + } + if ((type & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) { + /* POSIX.1e ACL perms */ + *(*p)++ = (perm & 0444) ? 'r' : '-'; + *(*p)++ = (perm & 0222) ? 'w' : '-'; + *(*p)++ = (perm & 0111) ? 'x' : '-'; + } else { + /* NFSv4 ACL perms */ + for (i = 0; i < nfsv4_acl_perm_map_size; i++) { + if (perm & nfsv4_acl_perm_map[i].perm) + *(*p)++ = nfsv4_acl_perm_map[i].c; + else if ((flags & ARCHIVE_ENTRY_ACL_STYLE_COMPACT) == 0) + *(*p)++ = '-'; + } + *(*p)++ = ':'; + for (i = 0; i < nfsv4_acl_flag_map_size; i++) { + if (perm & nfsv4_acl_flag_map[i].perm) + *(*p)++ = nfsv4_acl_flag_map[i].c; + else if ((flags & ARCHIVE_ENTRY_ACL_STYLE_COMPACT) == 0) + *(*p)++ = '-'; + } + *(*p)++ = ':'; + switch (type) { + case ARCHIVE_ENTRY_ACL_TYPE_ALLOW: + strcpy(*p, "allow"); + break; + case ARCHIVE_ENTRY_ACL_TYPE_DENY: + strcpy(*p, "deny"); + break; + case ARCHIVE_ENTRY_ACL_TYPE_AUDIT: + strcpy(*p, "audit"); + break; + case ARCHIVE_ENTRY_ACL_TYPE_ALARM: + strcpy(*p, "alarm"); + break; + } + *p += strlen(*p); + } + if (id != -1) { + *(*p)++ = ':'; + append_id(p, id); + } +} + +/* + * Parse a wide ACL text string. + * + * The want_type argument may be one of the following: + * ARCHIVE_ENTRY_ACL_TYPE_ACCESS - text is a POSIX.1e ACL of type ACCESS + * ARCHIVE_ENTRY_ACL_TYPE_DEFAULT - text is a POSIX.1e ACL of type DEFAULT + * ARCHIVE_ENTRY_ACL_TYPE_NFS4 - text is as a NFSv4 ACL + * + * POSIX.1e ACL entries prefixed with "default:" are treated as + * ARCHIVE_ENTRY_ACL_TYPE_DEFAULT unless type is ARCHIVE_ENTRY_ACL_TYPE_NFS4 + */ +int +archive_acl_from_text_w(struct archive_acl *acl, const wchar_t *text, + int want_type) +{ + struct { + const wchar_t *start; + const wchar_t *end; + } field[6], name; + + const wchar_t *s, *st; + + int numfields, fields, n, r, sol, ret; + int type, types, tag, permset, id; + size_t len; + wchar_t sep; + + ret = ARCHIVE_OK; + types = 0; + + switch (want_type) { + case ARCHIVE_ENTRY_ACL_TYPE_POSIX1E: + want_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; + __LA_FALLTHROUGH; + case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: + case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: + numfields = 5; + break; + case ARCHIVE_ENTRY_ACL_TYPE_NFS4: + numfields = 6; + break; + default: + return (ARCHIVE_FATAL); + } + + while (text != NULL && *text != L'\0') { + /* + * Parse the fields out of the next entry, + * advance 'text' to start of next entry. + */ + fields = 0; + do { + const wchar_t *start, *end; + next_field_w(&text, &start, &end, &sep); + if (fields < numfields) { + field[fields].start = start; + field[fields].end = end; + } + ++fields; + } while (sep == L':'); + + /* Set remaining fields to blank. */ + for (n = fields; n < numfields; ++n) + field[n].start = field[n].end = NULL; + + if (field[0].start != NULL && *(field[0].start) == L'#') { + /* Comment, skip entry */ + continue; + } + + n = 0; + sol = 0; + id = -1; + permset = 0; + name.start = name.end = NULL; + + if (want_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + /* POSIX.1e ACLs */ + /* + * Default keyword "default:user::rwx" + * if found, we have one more field + * + * We also support old Solaris extension: + * "defaultuser::rwx" is the default ACL corresponding + * to "user::rwx", etc. valid only for first field + */ + s = field[0].start; + len = field[0].end - field[0].start; + if (*s == L'd' && (len == 1 || (len >= 7 + && wmemcmp((s + 1), L"efault", 6) == 0))) { + type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT; + if (len > 7) + field[0].start += 7; + else + n = 1; + } else + type = want_type; + + /* Check for a numeric ID in field n+1 or n+3. */ + isint_w(field[n + 1].start, field[n + 1].end, &id); + /* Field n+3 is optional. */ + if (id == -1 && fields > n+3) + isint_w(field[n + 3].start, field[n + 3].end, + &id); + + tag = 0; + s = field[n].start; + st = field[n].start + 1; + len = field[n].end - field[n].start; + + switch (*s) { + case L'u': + if (len == 1 || (len == 4 + && wmemcmp(st, L"ser", 3) == 0)) + tag = ARCHIVE_ENTRY_ACL_USER_OBJ; + break; + case L'g': + if (len == 1 || (len == 5 + && wmemcmp(st, L"roup", 4) == 0)) + tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; + break; + case L'o': + if (len == 1 || (len == 5 + && wmemcmp(st, L"ther", 4) == 0)) + tag = ARCHIVE_ENTRY_ACL_OTHER; + break; + case L'm': + if (len == 1 || (len == 4 + && wmemcmp(st, L"ask", 3) == 0)) + tag = ARCHIVE_ENTRY_ACL_MASK; + break; + default: + break; + } + + switch (tag) { + case ARCHIVE_ENTRY_ACL_OTHER: + case ARCHIVE_ENTRY_ACL_MASK: + if (fields == (n + 2) + && field[n + 1].start < field[n + 1].end + && ismode_w(field[n + 1].start, + field[n + 1].end, &permset)) { + /* This is Solaris-style "other:rwx" */ + sol = 1; + } else if (fields == (n + 3) && + field[n + 1].start < field[n + 1].end) { + /* Invalid mask or other field */ + ret = ARCHIVE_WARN; + continue; + } + break; + case ARCHIVE_ENTRY_ACL_USER_OBJ: + case ARCHIVE_ENTRY_ACL_GROUP_OBJ: + if (id != -1 || + field[n + 1].start < field[n + 1].end) { + name = field[n + 1]; + if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ) + tag = ARCHIVE_ENTRY_ACL_USER; + else + tag = ARCHIVE_ENTRY_ACL_GROUP; + } + break; + default: + /* Invalid tag, skip entry */ + ret = ARCHIVE_WARN; + continue; + } + + /* + * Without "default:" we expect mode in field 2 + * Exception: Solaris other and mask fields + */ + if (permset == 0 && !ismode_w(field[n + 2 - sol].start, + field[n + 2 - sol].end, &permset)) { + /* Invalid mode, skip entry */ + ret = ARCHIVE_WARN; + continue; + } + } else { + /* NFS4 ACLs */ + s = field[0].start; + len = field[0].end - field[0].start; + tag = 0; + + switch (len) { + case 4: + if (wmemcmp(s, L"user", 4) == 0) + tag = ARCHIVE_ENTRY_ACL_USER; + break; + case 5: + if (wmemcmp(s, L"group", 5) == 0) + tag = ARCHIVE_ENTRY_ACL_GROUP; + break; + case 6: + if (wmemcmp(s, L"owner@", 6) == 0) + tag = ARCHIVE_ENTRY_ACL_USER_OBJ; + else if (wmemcmp(s, L"group@", len) == 0) + tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; + break; + case 9: + if (wmemcmp(s, L"everyone@", 9) == 0) + tag = ARCHIVE_ENTRY_ACL_EVERYONE; + default: + break; + } + + if (tag == 0) { + /* Invalid tag, skip entry */ + ret = ARCHIVE_WARN; + continue; + } else if (tag == ARCHIVE_ENTRY_ACL_USER || + tag == ARCHIVE_ENTRY_ACL_GROUP) { + n = 1; + name = field[1]; + isint_w(name.start, name.end, &id); + } else + n = 0; + + if (!is_nfs4_perms_w(field[1 + n].start, + field[1 + n].end, &permset)) { + /* Invalid NFSv4 perms, skip entry */ + ret = ARCHIVE_WARN; + continue; + } + if (!is_nfs4_flags_w(field[2 + n].start, + field[2 + n].end, &permset)) { + /* Invalid NFSv4 flags, skip entry */ + ret = ARCHIVE_WARN; + continue; + } + s = field[3 + n].start; + len = field[3 + n].end - field[3 + n].start; + type = 0; + if (len == 4) { + if (wmemcmp(s, L"deny", 4) == 0) + type = ARCHIVE_ENTRY_ACL_TYPE_DENY; + } else if (len == 5) { + if (wmemcmp(s, L"allow", 5) == 0) + type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW; + else if (wmemcmp(s, L"audit", 5) == 0) + type = ARCHIVE_ENTRY_ACL_TYPE_AUDIT; + else if (wmemcmp(s, L"alarm", 5) == 0) + type = ARCHIVE_ENTRY_ACL_TYPE_ALARM; + } + if (type == 0) { + /* Invalid entry type, skip entry */ + ret = ARCHIVE_WARN; + continue; + } + isint_w(field[4 + n].start, field[4 + n].end, &id); + } + + /* Add entry to the internal list. */ + r = archive_acl_add_entry_w_len(acl, type, permset, + tag, id, name.start, name.end - name.start); + if (r < ARCHIVE_WARN) + return (r); + if (r != ARCHIVE_OK) + ret = ARCHIVE_WARN; + types |= type; + } + + /* Reset ACL */ + archive_acl_reset(acl, types); + + return (ret); +} + +/* + * Parse a string to a positive decimal integer. Returns true if + * the string is non-empty and consists only of decimal digits, + * false otherwise. + */ +static int +isint_w(const wchar_t *start, const wchar_t *end, int *result) +{ + int n = 0; + if (start >= end) + return (0); + while (start < end) { + if (*start < '0' || *start > '9') + return (0); + if (n > (INT_MAX / 10) || + (n == INT_MAX / 10 && (*start - '0') > INT_MAX % 10)) { + n = INT_MAX; + } else { + n *= 10; + n += *start - '0'; + } + start++; + } + *result = n; + return (1); +} + +/* + * Parse a string as a mode field. Returns true if + * the string is non-empty and consists only of mode characters, + * false otherwise. + */ +static int +ismode_w(const wchar_t *start, const wchar_t *end, int *permset) +{ + const wchar_t *p; + + if (start >= end) + return (0); + p = start; + *permset = 0; + while (p < end) { + switch (*p++) { + case L'r': case L'R': + *permset |= ARCHIVE_ENTRY_ACL_READ; + break; + case L'w': case L'W': + *permset |= ARCHIVE_ENTRY_ACL_WRITE; + break; + case L'x': case L'X': + *permset |= ARCHIVE_ENTRY_ACL_EXECUTE; + break; + case L'-': + break; + default: + return (0); + } + } + return (1); +} + +/* + * Parse a string as a NFS4 ACL permission field. + * Returns true if the string is non-empty and consists only of NFS4 ACL + * permission characters, false otherwise + */ +static int +is_nfs4_perms_w(const wchar_t *start, const wchar_t *end, int *permset) +{ + const wchar_t *p = start; + + while (p < end) { + switch (*p++) { + case L'r': + *permset |= ARCHIVE_ENTRY_ACL_READ_DATA; + break; + case L'w': + *permset |= ARCHIVE_ENTRY_ACL_WRITE_DATA; + break; + case L'x': + *permset |= ARCHIVE_ENTRY_ACL_EXECUTE; + break; + case L'p': + *permset |= ARCHIVE_ENTRY_ACL_APPEND_DATA; + break; + case L'D': + *permset |= ARCHIVE_ENTRY_ACL_DELETE_CHILD; + break; + case L'd': + *permset |= ARCHIVE_ENTRY_ACL_DELETE; + break; + case L'a': + *permset |= ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES; + break; + case L'A': + *permset |= ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES; + break; + case L'R': + *permset |= ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS; + break; + case L'W': + *permset |= ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS; + break; + case L'c': + *permset |= ARCHIVE_ENTRY_ACL_READ_ACL; + break; + case L'C': + *permset |= ARCHIVE_ENTRY_ACL_WRITE_ACL; + break; + case L'o': + *permset |= ARCHIVE_ENTRY_ACL_WRITE_OWNER; + break; + case L's': + *permset |= ARCHIVE_ENTRY_ACL_SYNCHRONIZE; + break; + case L'-': + break; + default: + return(0); + } + } + return (1); +} + +/* + * Parse a string as a NFS4 ACL flags field. + * Returns true if the string is non-empty and consists only of NFS4 ACL + * flag characters, false otherwise + */ +static int +is_nfs4_flags_w(const wchar_t *start, const wchar_t *end, int *permset) +{ + const wchar_t *p = start; + + while (p < end) { + switch(*p++) { + case L'f': + *permset |= ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT; + break; + case L'd': + *permset |= ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT; + break; + case L'i': + *permset |= ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY; + break; + case L'n': + *permset |= + ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT; + break; + case L'S': + *permset |= ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS; + break; + case L'F': + *permset |= ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS; + break; + case L'I': + *permset |= ARCHIVE_ENTRY_ACL_ENTRY_INHERITED; + break; + case L'-': + break; + default: + return (0); + } + } + return (1); +} + +/* + * Match "[:whitespace:]*(.*)[:whitespace:]*[:,\n]". *wp is updated + * to point to just after the separator. *start points to the first + * character of the matched text and *end just after the last + * character of the matched identifier. In particular *end - *start + * is the length of the field body, not including leading or trailing + * whitespace. + */ +static void +next_field_w(const wchar_t **wp, const wchar_t **start, + const wchar_t **end, wchar_t *sep) +{ + /* Skip leading whitespace to find start of field. */ + while (**wp == L' ' || **wp == L'\t' || **wp == L'\n') { + (*wp)++; + } + *start = *wp; + + /* Scan for the separator. */ + while (**wp != L'\0' && **wp != L',' && **wp != L':' && + **wp != L'\n' && **wp != L'#') { + (*wp)++; + } + *sep = **wp; + + /* Locate end of field, trim trailing whitespace if necessary */ + if (*wp == *start) { + *end = *wp; + } else { + *end = *wp - 1; + while (**end == L' ' || **end == L'\t' || **end == L'\n') { + (*end)--; + } + (*end)++; + } + + /* Handle in-field comments */ + if (*sep == L'#') { + while (**wp != L'\0' && **wp != L',' && **wp != L'\n') { + (*wp)++; + } + *sep = **wp; + } + + /* Adjust scanner location. */ + if (**wp != L'\0') + (*wp)++; +} + +/* + * Parse an ACL text string. + * + * The want_type argument may be one of the following: + * ARCHIVE_ENTRY_ACL_TYPE_ACCESS - text is a POSIX.1e ACL of type ACCESS + * ARCHIVE_ENTRY_ACL_TYPE_DEFAULT - text is a POSIX.1e ACL of type DEFAULT + * ARCHIVE_ENTRY_ACL_TYPE_NFS4 - text is as a NFSv4 ACL + * + * POSIX.1e ACL entries prefixed with "default:" are treated as + * ARCHIVE_ENTRY_ACL_TYPE_DEFAULT unless type is ARCHIVE_ENTRY_ACL_TYPE_NFS4 + */ +int +archive_acl_from_text_l(struct archive_acl *acl, const char *text, + int want_type, struct archive_string_conv *sc) +{ + struct { + const char *start; + const char *end; + } field[6], name; + + const char *s, *st; + int numfields, fields, n, r, sol, ret; + int type, types, tag, permset, id; + size_t len; + char sep; + + switch (want_type) { + case ARCHIVE_ENTRY_ACL_TYPE_POSIX1E: + want_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; + __LA_FALLTHROUGH; + case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: + case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: + numfields = 5; + break; + case ARCHIVE_ENTRY_ACL_TYPE_NFS4: + numfields = 6; + break; + default: + return (ARCHIVE_FATAL); + } + + ret = ARCHIVE_OK; + types = 0; + + while (text != NULL && *text != '\0') { + /* + * Parse the fields out of the next entry, + * advance 'text' to start of next entry. + */ + fields = 0; + do { + const char *start, *end; + next_field(&text, &start, &end, &sep); + if (fields < numfields) { + field[fields].start = start; + field[fields].end = end; + } + ++fields; + } while (sep == ':'); + + /* Set remaining fields to blank. */ + for (n = fields; n < numfields; ++n) + field[n].start = field[n].end = NULL; + + if (field[0].start != NULL && *(field[0].start) == '#') { + /* Comment, skip entry */ + continue; + } + + n = 0; + sol = 0; + id = -1; + permset = 0; + name.start = name.end = NULL; + + if (want_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + /* POSIX.1e ACLs */ + /* + * Default keyword "default:user::rwx" + * if found, we have one more field + * + * We also support old Solaris extension: + * "defaultuser::rwx" is the default ACL corresponding + * to "user::rwx", etc. valid only for first field + */ + s = field[0].start; + len = field[0].end - field[0].start; + if (*s == 'd' && (len == 1 || (len >= 7 + && memcmp((s + 1), "efault", 6) == 0))) { + type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT; + if (len > 7) + field[0].start += 7; + else + n = 1; + } else + type = want_type; + + /* Check for a numeric ID in field n+1 or n+3. */ + isint(field[n + 1].start, field[n + 1].end, &id); + /* Field n+3 is optional. */ + if (id == -1 && fields > (n + 3)) + isint(field[n + 3].start, field[n + 3].end, + &id); + + tag = 0; + s = field[n].start; + st = field[n].start + 1; + len = field[n].end - field[n].start; + + if (len == 0) { + ret = ARCHIVE_WARN; + continue; + } + + switch (*s) { + case 'u': + if (len == 1 || (len == 4 + && memcmp(st, "ser", 3) == 0)) + tag = ARCHIVE_ENTRY_ACL_USER_OBJ; + break; + case 'g': + if (len == 1 || (len == 5 + && memcmp(st, "roup", 4) == 0)) + tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; + break; + case 'o': + if (len == 1 || (len == 5 + && memcmp(st, "ther", 4) == 0)) + tag = ARCHIVE_ENTRY_ACL_OTHER; + break; + case 'm': + if (len == 1 || (len == 4 + && memcmp(st, "ask", 3) == 0)) + tag = ARCHIVE_ENTRY_ACL_MASK; + break; + default: + break; + } + + switch (tag) { + case ARCHIVE_ENTRY_ACL_OTHER: + case ARCHIVE_ENTRY_ACL_MASK: + if (fields == (n + 2) + && field[n + 1].start < field[n + 1].end + && ismode(field[n + 1].start, + field[n + 1].end, &permset)) { + /* This is Solaris-style "other:rwx" */ + sol = 1; + } else if (fields == (n + 3) && + field[n + 1].start < field[n + 1].end) { + /* Invalid mask or other field */ + ret = ARCHIVE_WARN; + continue; + } + break; + case ARCHIVE_ENTRY_ACL_USER_OBJ: + case ARCHIVE_ENTRY_ACL_GROUP_OBJ: + if (id != -1 || + field[n + 1].start < field[n + 1].end) { + name = field[n + 1]; + if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ) + tag = ARCHIVE_ENTRY_ACL_USER; + else + tag = ARCHIVE_ENTRY_ACL_GROUP; + } + break; + default: + /* Invalid tag, skip entry */ + ret = ARCHIVE_WARN; + continue; + } + + /* + * Without "default:" we expect mode in field 3 + * Exception: Solaris other and mask fields + */ + if (permset == 0 && !ismode(field[n + 2 - sol].start, + field[n + 2 - sol].end, &permset)) { + /* Invalid mode, skip entry */ + ret = ARCHIVE_WARN; + continue; + } + } else { + /* NFS4 ACLs */ + s = field[0].start; + len = field[0].end - field[0].start; + tag = 0; + + switch (len) { + case 4: + if (memcmp(s, "user", 4) == 0) + tag = ARCHIVE_ENTRY_ACL_USER; + break; + case 5: + if (memcmp(s, "group", 5) == 0) + tag = ARCHIVE_ENTRY_ACL_GROUP; + break; + case 6: + if (memcmp(s, "owner@", 6) == 0) + tag = ARCHIVE_ENTRY_ACL_USER_OBJ; + else if (memcmp(s, "group@", 6) == 0) + tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; + break; + case 9: + if (memcmp(s, "everyone@", 9) == 0) + tag = ARCHIVE_ENTRY_ACL_EVERYONE; + break; + default: + break; + } + + if (tag == 0) { + /* Invalid tag, skip entry */ + ret = ARCHIVE_WARN; + continue; + } else if (tag == ARCHIVE_ENTRY_ACL_USER || + tag == ARCHIVE_ENTRY_ACL_GROUP) { + n = 1; + name = field[1]; + isint(name.start, name.end, &id); + } else + n = 0; + + if (!is_nfs4_perms(field[1 + n].start, + field[1 + n].end, &permset)) { + /* Invalid NFSv4 perms, skip entry */ + ret = ARCHIVE_WARN; + continue; + } + if (!is_nfs4_flags(field[2 + n].start, + field[2 + n].end, &permset)) { + /* Invalid NFSv4 flags, skip entry */ + ret = ARCHIVE_WARN; + continue; + } + s = field[3 + n].start; + len = field[3 + n].end - field[3 + n].start; + type = 0; + if (len == 4) { + if (memcmp(s, "deny", 4) == 0) + type = ARCHIVE_ENTRY_ACL_TYPE_DENY; + } else if (len == 5) { + if (memcmp(s, "allow", 5) == 0) + type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW; + else if (memcmp(s, "audit", 5) == 0) + type = ARCHIVE_ENTRY_ACL_TYPE_AUDIT; + else if (memcmp(s, "alarm", 5) == 0) + type = ARCHIVE_ENTRY_ACL_TYPE_ALARM; + } + if (type == 0) { + /* Invalid entry type, skip entry */ + ret = ARCHIVE_WARN; + continue; + } + isint(field[4 + n].start, field[4 + n].end, + &id); + } + + /* Add entry to the internal list. */ + r = archive_acl_add_entry_len_l(acl, type, permset, + tag, id, name.start, name.end - name.start, sc); + if (r < ARCHIVE_WARN) + return (r); + if (r != ARCHIVE_OK) + ret = ARCHIVE_WARN; + types |= type; + } + + /* Reset ACL */ + archive_acl_reset(acl, types); + + return (ret); +} + +/* + * Parse a string to a positive decimal integer. Returns true if + * the string is non-empty and consists only of decimal digits, + * false otherwise. + */ +static int +isint(const char *start, const char *end, int *result) +{ + int n = 0; + if (start >= end) + return (0); + while (start < end) { + if (*start < '0' || *start > '9') + return (0); + if (n > (INT_MAX / 10) || + (n == INT_MAX / 10 && (*start - '0') > INT_MAX % 10)) { + n = INT_MAX; + } else { + n *= 10; + n += *start - '0'; + } + start++; + } + *result = n; + return (1); +} + +/* + * Parse a string as a mode field. Returns true if + * the string is non-empty and consists only of mode characters, + * false otherwise. + */ +static int +ismode(const char *start, const char *end, int *permset) +{ + const char *p; + + if (start >= end) + return (0); + p = start; + *permset = 0; + while (p < end) { + switch (*p++) { + case 'r': case 'R': + *permset |= ARCHIVE_ENTRY_ACL_READ; + break; + case 'w': case 'W': + *permset |= ARCHIVE_ENTRY_ACL_WRITE; + break; + case 'x': case 'X': + *permset |= ARCHIVE_ENTRY_ACL_EXECUTE; + break; + case '-': + break; + default: + return (0); + } + } + return (1); +} + +/* + * Parse a string as a NFS4 ACL permission field. + * Returns true if the string is non-empty and consists only of NFS4 ACL + * permission characters, false otherwise + */ +static int +is_nfs4_perms(const char *start, const char *end, int *permset) +{ + const char *p = start; + + while (p < end) { + switch (*p++) { + case 'r': + *permset |= ARCHIVE_ENTRY_ACL_READ_DATA; + break; + case 'w': + *permset |= ARCHIVE_ENTRY_ACL_WRITE_DATA; + break; + case 'x': + *permset |= ARCHIVE_ENTRY_ACL_EXECUTE; + break; + case 'p': + *permset |= ARCHIVE_ENTRY_ACL_APPEND_DATA; + break; + case 'D': + *permset |= ARCHIVE_ENTRY_ACL_DELETE_CHILD; + break; + case 'd': + *permset |= ARCHIVE_ENTRY_ACL_DELETE; + break; + case 'a': + *permset |= ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES; + break; + case 'A': + *permset |= ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES; + break; + case 'R': + *permset |= ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS; + break; + case 'W': + *permset |= ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS; + break; + case 'c': + *permset |= ARCHIVE_ENTRY_ACL_READ_ACL; + break; + case 'C': + *permset |= ARCHIVE_ENTRY_ACL_WRITE_ACL; + break; + case 'o': + *permset |= ARCHIVE_ENTRY_ACL_WRITE_OWNER; + break; + case 's': + *permset |= ARCHIVE_ENTRY_ACL_SYNCHRONIZE; + break; + case '-': + break; + default: + return(0); + } + } + return (1); +} + +/* + * Parse a string as a NFS4 ACL flags field. + * Returns true if the string is non-empty and consists only of NFS4 ACL + * flag characters, false otherwise + */ +static int +is_nfs4_flags(const char *start, const char *end, int *permset) +{ + const char *p = start; + + while (p < end) { + switch(*p++) { + case 'f': + *permset |= ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT; + break; + case 'd': + *permset |= ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT; + break; + case 'i': + *permset |= ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY; + break; + case 'n': + *permset |= + ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT; + break; + case 'S': + *permset |= ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS; + break; + case 'F': + *permset |= ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS; + break; + case 'I': + *permset |= ARCHIVE_ENTRY_ACL_ENTRY_INHERITED; + break; + case '-': + break; + default: + return (0); + } + } + return (1); +} + +/* + * Match "[:whitespace:]*(.*)[:whitespace:]*[:,\n]". *wp is updated + * to point to just after the separator. *start points to the first + * character of the matched text and *end just after the last + * character of the matched identifier. In particular *end - *start + * is the length of the field body, not including leading or trailing + * whitespace. + */ +static void +next_field(const char **p, const char **start, + const char **end, char *sep) +{ + /* Skip leading whitespace to find start of field. */ + while (**p == ' ' || **p == '\t' || **p == '\n') { + (*p)++; + } + *start = *p; + + /* Scan for the separator. */ + while (**p != '\0' && **p != ',' && **p != ':' && **p != '\n' && + **p != '#') { + (*p)++; + } + *sep = **p; + + /* Locate end of field, trim trailing whitespace if necessary */ + if (*p == *start) { + *end = *p; + } else { + *end = *p - 1; + while (**end == ' ' || **end == '\t' || **end == '\n') { + (*end)--; + } + (*end)++; + } + + /* Handle in-field comments */ + if (*sep == '#') { + while (**p != '\0' && **p != ',' && **p != '\n') { + (*p)++; + } + *sep = **p; + } + + /* Adjust scanner location. */ + if (**p != '\0') + (*p)++; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_acl_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_acl_private.h new file mode 100644 index 0000000000..af108162c6 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_acl_private.h @@ -0,0 +1,83 @@ +/*- + * Copyright (c) 2003-2010 Tim Kientzle + * 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(S) ``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(S) 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. + * + * $FreeBSD$ + */ + +#ifndef ARCHIVE_ACL_PRIVATE_H_INCLUDED +#define ARCHIVE_ACL_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +#include "archive_string.h" + +struct archive_acl_entry { + struct archive_acl_entry *next; + int type; /* E.g., access or default */ + int tag; /* E.g., user/group/other/mask */ + int permset; /* r/w/x bits */ + int id; /* uid/gid for user/group */ + struct archive_mstring name; /* uname/gname */ +}; + +struct archive_acl { + mode_t mode; + struct archive_acl_entry *acl_head; + struct archive_acl_entry *acl_p; + int acl_state; /* See acl_next for details. */ + wchar_t *acl_text_w; + char *acl_text; + int acl_types; +}; + +void archive_acl_clear(struct archive_acl *); +void archive_acl_copy(struct archive_acl *, struct archive_acl *); +int archive_acl_count(struct archive_acl *, int); +int archive_acl_types(struct archive_acl *); +int archive_acl_reset(struct archive_acl *, int); +int archive_acl_next(struct archive *, struct archive_acl *, int, + int *, int *, int *, int *, const char **); + +int archive_acl_add_entry(struct archive_acl *, int, int, int, int, const char *); +int archive_acl_add_entry_w_len(struct archive_acl *, + int, int, int, int, const wchar_t *, size_t); +int archive_acl_add_entry_len(struct archive_acl *, + int, int, int, int, const char *, size_t); + +wchar_t *archive_acl_to_text_w(struct archive_acl *, ssize_t *, int, + struct archive *); +char *archive_acl_to_text_l(struct archive_acl *, ssize_t *, int, + struct archive_string_conv *); + +/* + * ACL text parser. + */ +int archive_acl_from_text_w(struct archive_acl *, const wchar_t * /* wtext */, + int /* type */); +int archive_acl_from_text_l(struct archive_acl *, const char * /* text */, + int /* type */, struct archive_string_conv *); + +#endif /* ARCHIVE_ENTRY_PRIVATE_H_INCLUDED */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_blake2.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_blake2.h new file mode 100644 index 0000000000..dd6fe6fe5a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_blake2.h @@ -0,0 +1,195 @@ +/* + BLAKE2 reference source code package - reference C implementations + + Copyright 2012, Samuel Neves <sneves@dei.uc.pt>. You may use this under the + terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at + your option. The terms of these licenses can be found at: + + - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0 + - OpenSSL license : https://www.openssl.org/source/license.html + - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0 + + More information about the BLAKE2 hash function can be found at + https://blake2.net. +*/ + +#ifndef ARCHIVE_BLAKE2_H +#define ARCHIVE_BLAKE2_H + +#include <stddef.h> +#include <stdint.h> + +#if defined(_MSC_VER) +#define BLAKE2_PACKED(x) __pragma(pack(push, 1)) x __pragma(pack(pop)) +#else +#define BLAKE2_PACKED(x) x __attribute__((packed)) +#endif + +#if defined(__cplusplus) +extern "C" { +#endif + + enum blake2s_constant + { + BLAKE2S_BLOCKBYTES = 64, + BLAKE2S_OUTBYTES = 32, + BLAKE2S_KEYBYTES = 32, + BLAKE2S_SALTBYTES = 8, + BLAKE2S_PERSONALBYTES = 8 + }; + + enum blake2b_constant + { + BLAKE2B_BLOCKBYTES = 128, + BLAKE2B_OUTBYTES = 64, + BLAKE2B_KEYBYTES = 64, + BLAKE2B_SALTBYTES = 16, + BLAKE2B_PERSONALBYTES = 16 + }; + + typedef struct blake2s_state__ + { + uint32_t h[8]; + uint32_t t[2]; + uint32_t f[2]; + uint8_t buf[BLAKE2S_BLOCKBYTES]; + size_t buflen; + size_t outlen; + uint8_t last_node; + } blake2s_state; + + typedef struct blake2b_state__ + { + uint64_t h[8]; + uint64_t t[2]; + uint64_t f[2]; + uint8_t buf[BLAKE2B_BLOCKBYTES]; + size_t buflen; + size_t outlen; + uint8_t last_node; + } blake2b_state; + + typedef struct blake2sp_state__ + { + blake2s_state S[8][1]; + blake2s_state R[1]; + uint8_t buf[8 * BLAKE2S_BLOCKBYTES]; + size_t buflen; + size_t outlen; + } blake2sp_state; + + typedef struct blake2bp_state__ + { + blake2b_state S[4][1]; + blake2b_state R[1]; + uint8_t buf[4 * BLAKE2B_BLOCKBYTES]; + size_t buflen; + size_t outlen; + } blake2bp_state; + + BLAKE2_PACKED(struct blake2s_param__ + { + uint8_t digest_length; /* 1 */ + uint8_t key_length; /* 2 */ + uint8_t fanout; /* 3 */ + uint8_t depth; /* 4 */ + uint32_t leaf_length; /* 8 */ + uint32_t node_offset; /* 12 */ + uint16_t xof_length; /* 14 */ + uint8_t node_depth; /* 15 */ + uint8_t inner_length; /* 16 */ + /* uint8_t reserved[0]; */ + uint8_t salt[BLAKE2S_SALTBYTES]; /* 24 */ + uint8_t personal[BLAKE2S_PERSONALBYTES]; /* 32 */ + }); + + typedef struct blake2s_param__ blake2s_param; + + BLAKE2_PACKED(struct blake2b_param__ + { + uint8_t digest_length; /* 1 */ + uint8_t key_length; /* 2 */ + uint8_t fanout; /* 3 */ + uint8_t depth; /* 4 */ + uint32_t leaf_length; /* 8 */ + uint32_t node_offset; /* 12 */ + uint32_t xof_length; /* 16 */ + uint8_t node_depth; /* 17 */ + uint8_t inner_length; /* 18 */ + uint8_t reserved[14]; /* 32 */ + uint8_t salt[BLAKE2B_SALTBYTES]; /* 48 */ + uint8_t personal[BLAKE2B_PERSONALBYTES]; /* 64 */ + }); + + typedef struct blake2b_param__ blake2b_param; + + typedef struct blake2xs_state__ + { + blake2s_state S[1]; + blake2s_param P[1]; + } blake2xs_state; + + typedef struct blake2xb_state__ + { + blake2b_state S[1]; + blake2b_param P[1]; + } blake2xb_state; + + /* Padded structs result in a compile-time error */ + enum { + BLAKE2_DUMMY_1 = 1/(sizeof(blake2s_param) == BLAKE2S_OUTBYTES), + BLAKE2_DUMMY_2 = 1/(sizeof(blake2b_param) == BLAKE2B_OUTBYTES) + }; + + /* Streaming API */ + int blake2s_init( blake2s_state *S, size_t outlen ); + int blake2s_init_key( blake2s_state *S, size_t outlen, const void *key, size_t keylen ); + int blake2s_init_param( blake2s_state *S, const blake2s_param *P ); + int blake2s_update( blake2s_state *S, const void *in, size_t inlen ); + int blake2s_final( blake2s_state *S, void *out, size_t outlen ); + + int blake2b_init( blake2b_state *S, size_t outlen ); + int blake2b_init_key( blake2b_state *S, size_t outlen, const void *key, size_t keylen ); + int blake2b_init_param( blake2b_state *S, const blake2b_param *P ); + int blake2b_update( blake2b_state *S, const void *in, size_t inlen ); + int blake2b_final( blake2b_state *S, void *out, size_t outlen ); + + int blake2sp_init( blake2sp_state *S, size_t outlen ); + int blake2sp_init_key( blake2sp_state *S, size_t outlen, const void *key, size_t keylen ); + int blake2sp_update( blake2sp_state *S, const void *in, size_t inlen ); + int blake2sp_final( blake2sp_state *S, void *out, size_t outlen ); + + int blake2bp_init( blake2bp_state *S, size_t outlen ); + int blake2bp_init_key( blake2bp_state *S, size_t outlen, const void *key, size_t keylen ); + int blake2bp_update( blake2bp_state *S, const void *in, size_t inlen ); + int blake2bp_final( blake2bp_state *S, void *out, size_t outlen ); + + /* Variable output length API */ + int blake2xs_init( blake2xs_state *S, const size_t outlen ); + int blake2xs_init_key( blake2xs_state *S, const size_t outlen, const void *key, size_t keylen ); + int blake2xs_update( blake2xs_state *S, const void *in, size_t inlen ); + int blake2xs_final(blake2xs_state *S, void *out, size_t outlen); + + int blake2xb_init( blake2xb_state *S, const size_t outlen ); + int blake2xb_init_key( blake2xb_state *S, const size_t outlen, const void *key, size_t keylen ); + int blake2xb_update( blake2xb_state *S, const void *in, size_t inlen ); + int blake2xb_final(blake2xb_state *S, void *out, size_t outlen); + + /* Simple API */ + int blake2s( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen ); + int blake2b( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen ); + + int blake2sp( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen ); + int blake2bp( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen ); + + int blake2xs( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen ); + int blake2xb( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen ); + + /* This is simply an alias for blake2b */ + int blake2( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen ); + +#if defined(__cplusplus) +} +#endif + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_blake2_impl.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_blake2_impl.h new file mode 100644 index 0000000000..0f05defea3 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_blake2_impl.h @@ -0,0 +1,161 @@ +/* + BLAKE2 reference source code package - reference C implementations + + Copyright 2012, Samuel Neves <sneves@dei.uc.pt>. You may use this under the + terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at + your option. The terms of these licenses can be found at: + + - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0 + - OpenSSL license : https://www.openssl.org/source/license.html + - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0 + + More information about the BLAKE2 hash function can be found at + https://blake2.net. +*/ + +#ifndef ARCHIVE_BLAKE2_IMPL_H +#define ARCHIVE_BLAKE2_IMPL_H + +#include <stdint.h> +#include <string.h> + +#if !defined(__cplusplus) && (!defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L) + #if defined(_MSC_VER) + #define BLAKE2_INLINE __inline + #elif defined(__GNUC__) + #define BLAKE2_INLINE __inline__ + #else + #define BLAKE2_INLINE + #endif +#else + #define BLAKE2_INLINE inline +#endif + +static BLAKE2_INLINE uint32_t load32( const void *src ) +{ +#if defined(NATIVE_LITTLE_ENDIAN) + uint32_t w; + memcpy(&w, src, sizeof w); + return w; +#else + const uint8_t *p = ( const uint8_t * )src; + return (( uint32_t )( p[0] ) << 0) | + (( uint32_t )( p[1] ) << 8) | + (( uint32_t )( p[2] ) << 16) | + (( uint32_t )( p[3] ) << 24) ; +#endif +} + +static BLAKE2_INLINE uint64_t load64( const void *src ) +{ +#if defined(NATIVE_LITTLE_ENDIAN) + uint64_t w; + memcpy(&w, src, sizeof w); + return w; +#else + const uint8_t *p = ( const uint8_t * )src; + return (( uint64_t )( p[0] ) << 0) | + (( uint64_t )( p[1] ) << 8) | + (( uint64_t )( p[2] ) << 16) | + (( uint64_t )( p[3] ) << 24) | + (( uint64_t )( p[4] ) << 32) | + (( uint64_t )( p[5] ) << 40) | + (( uint64_t )( p[6] ) << 48) | + (( uint64_t )( p[7] ) << 56) ; +#endif +} + +static BLAKE2_INLINE uint16_t load16( const void *src ) +{ +#if defined(NATIVE_LITTLE_ENDIAN) + uint16_t w; + memcpy(&w, src, sizeof w); + return w; +#else + const uint8_t *p = ( const uint8_t * )src; + return ( uint16_t )((( uint32_t )( p[0] ) << 0) | + (( uint32_t )( p[1] ) << 8)); +#endif +} + +static BLAKE2_INLINE void store16( void *dst, uint16_t w ) +{ +#if defined(NATIVE_LITTLE_ENDIAN) + memcpy(dst, &w, sizeof w); +#else + uint8_t *p = ( uint8_t * )dst; + *p++ = ( uint8_t )w; w >>= 8; + *p++ = ( uint8_t )w; +#endif +} + +static BLAKE2_INLINE void store32( void *dst, uint32_t w ) +{ +#if defined(NATIVE_LITTLE_ENDIAN) + memcpy(dst, &w, sizeof w); +#else + uint8_t *p = ( uint8_t * )dst; + p[0] = (uint8_t)(w >> 0); + p[1] = (uint8_t)(w >> 8); + p[2] = (uint8_t)(w >> 16); + p[3] = (uint8_t)(w >> 24); +#endif +} + +static BLAKE2_INLINE void store64( void *dst, uint64_t w ) +{ +#if defined(NATIVE_LITTLE_ENDIAN) + memcpy(dst, &w, sizeof w); +#else + uint8_t *p = ( uint8_t * )dst; + p[0] = (uint8_t)(w >> 0); + p[1] = (uint8_t)(w >> 8); + p[2] = (uint8_t)(w >> 16); + p[3] = (uint8_t)(w >> 24); + p[4] = (uint8_t)(w >> 32); + p[5] = (uint8_t)(w >> 40); + p[6] = (uint8_t)(w >> 48); + p[7] = (uint8_t)(w >> 56); +#endif +} + +static BLAKE2_INLINE uint64_t load48( const void *src ) +{ + const uint8_t *p = ( const uint8_t * )src; + return (( uint64_t )( p[0] ) << 0) | + (( uint64_t )( p[1] ) << 8) | + (( uint64_t )( p[2] ) << 16) | + (( uint64_t )( p[3] ) << 24) | + (( uint64_t )( p[4] ) << 32) | + (( uint64_t )( p[5] ) << 40) ; +} + +static BLAKE2_INLINE void store48( void *dst, uint64_t w ) +{ + uint8_t *p = ( uint8_t * )dst; + p[0] = (uint8_t)(w >> 0); + p[1] = (uint8_t)(w >> 8); + p[2] = (uint8_t)(w >> 16); + p[3] = (uint8_t)(w >> 24); + p[4] = (uint8_t)(w >> 32); + p[5] = (uint8_t)(w >> 40); +} + +static BLAKE2_INLINE uint32_t rotr32( const uint32_t w, const unsigned c ) +{ + return ( w >> c ) | ( w << ( 32 - c ) ); +} + +static BLAKE2_INLINE uint64_t rotr64( const uint64_t w, const unsigned c ) +{ + return ( w >> c ) | ( w << ( 64 - c ) ); +} + +/* prevents compiler optimizing out memset() */ +static BLAKE2_INLINE void secure_zero_memory(void *v, size_t n) +{ + static void *(*const volatile memset_v)(void *, int, size_t) = &memset; + memset_v(v, 0, n); +} + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_blake2s_ref.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_blake2s_ref.c new file mode 100644 index 0000000000..d92ffd0fc5 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_blake2s_ref.c @@ -0,0 +1,367 @@ +/* + BLAKE2 reference source code package - reference C implementations + + Copyright 2012, Samuel Neves <sneves@dei.uc.pt>. You may use this under the + terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at + your option. The terms of these licenses can be found at: + + - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0 + - OpenSSL license : https://www.openssl.org/source/license.html + - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0 + + More information about the BLAKE2 hash function can be found at + https://blake2.net. +*/ + +#include <stdint.h> +#include <string.h> +#include <stdio.h> + +#include "archive_blake2.h" +#include "archive_blake2_impl.h" + +static const uint32_t blake2s_IV[8] = +{ + 0x6A09E667UL, 0xBB67AE85UL, 0x3C6EF372UL, 0xA54FF53AUL, + 0x510E527FUL, 0x9B05688CUL, 0x1F83D9ABUL, 0x5BE0CD19UL +}; + +static const uint8_t blake2s_sigma[10][16] = +{ + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } , + { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 } , + { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 } , + { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 } , + { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 } , + { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 } , + { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 } , + { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 } , + { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 } , + { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13 , 0 } , +}; + +static void blake2s_set_lastnode( blake2s_state *S ) +{ + S->f[1] = (uint32_t)-1; +} + +/* Some helper functions, not necessarily useful */ +static int blake2s_is_lastblock( const blake2s_state *S ) +{ + return S->f[0] != 0; +} + +static void blake2s_set_lastblock( blake2s_state *S ) +{ + if( S->last_node ) blake2s_set_lastnode( S ); + + S->f[0] = (uint32_t)-1; +} + +static void blake2s_increment_counter( blake2s_state *S, const uint32_t inc ) +{ + S->t[0] += inc; + S->t[1] += ( S->t[0] < inc ); +} + +static void blake2s_init0( blake2s_state *S ) +{ + size_t i; + memset( S, 0, sizeof( blake2s_state ) ); + + for( i = 0; i < 8; ++i ) S->h[i] = blake2s_IV[i]; +} + +/* init2 xors IV with input parameter block */ +int blake2s_init_param( blake2s_state *S, const blake2s_param *P ) +{ + const unsigned char *p = ( const unsigned char * )( P ); + size_t i; + + blake2s_init0( S ); + + /* IV XOR ParamBlock */ + for( i = 0; i < 8; ++i ) + S->h[i] ^= load32( &p[i * 4] ); + + S->outlen = P->digest_length; + return 0; +} + + +/* Sequential blake2s initialization */ +int blake2s_init( blake2s_state *S, size_t outlen ) +{ + blake2s_param P[1]; + + /* Move interval verification here? */ + if ( ( !outlen ) || ( outlen > BLAKE2S_OUTBYTES ) ) return -1; + + P->digest_length = (uint8_t)outlen; + P->key_length = 0; + P->fanout = 1; + P->depth = 1; + store32( &P->leaf_length, 0 ); + store32( &P->node_offset, 0 ); + store16( &P->xof_length, 0 ); + P->node_depth = 0; + P->inner_length = 0; + /* memset(P->reserved, 0, sizeof(P->reserved) ); */ + memset( P->salt, 0, sizeof( P->salt ) ); + memset( P->personal, 0, sizeof( P->personal ) ); + return blake2s_init_param( S, P ); +} + +int blake2s_init_key( blake2s_state *S, size_t outlen, const void *key, size_t keylen ) +{ + blake2s_param P[1]; + + if ( ( !outlen ) || ( outlen > BLAKE2S_OUTBYTES ) ) return -1; + + if ( !key || !keylen || keylen > BLAKE2S_KEYBYTES ) return -1; + + P->digest_length = (uint8_t)outlen; + P->key_length = (uint8_t)keylen; + P->fanout = 1; + P->depth = 1; + store32( &P->leaf_length, 0 ); + store32( &P->node_offset, 0 ); + store16( &P->xof_length, 0 ); + P->node_depth = 0; + P->inner_length = 0; + /* memset(P->reserved, 0, sizeof(P->reserved) ); */ + memset( P->salt, 0, sizeof( P->salt ) ); + memset( P->personal, 0, sizeof( P->personal ) ); + + if( blake2s_init_param( S, P ) < 0 ) return -1; + + { + uint8_t block[BLAKE2S_BLOCKBYTES]; + memset( block, 0, BLAKE2S_BLOCKBYTES ); + memcpy( block, key, keylen ); + blake2s_update( S, block, BLAKE2S_BLOCKBYTES ); + secure_zero_memory( block, BLAKE2S_BLOCKBYTES ); /* Burn the key from stack */ + } + return 0; +} + +#define G(r,i,a,b,c,d) \ + do { \ + a = a + b + m[blake2s_sigma[r][2*i+0]]; \ + d = rotr32(d ^ a, 16); \ + c = c + d; \ + b = rotr32(b ^ c, 12); \ + a = a + b + m[blake2s_sigma[r][2*i+1]]; \ + d = rotr32(d ^ a, 8); \ + c = c + d; \ + b = rotr32(b ^ c, 7); \ + } while(0) + +#define ROUND(r) \ + do { \ + G(r,0,v[ 0],v[ 4],v[ 8],v[12]); \ + G(r,1,v[ 1],v[ 5],v[ 9],v[13]); \ + G(r,2,v[ 2],v[ 6],v[10],v[14]); \ + G(r,3,v[ 3],v[ 7],v[11],v[15]); \ + G(r,4,v[ 0],v[ 5],v[10],v[15]); \ + G(r,5,v[ 1],v[ 6],v[11],v[12]); \ + G(r,6,v[ 2],v[ 7],v[ 8],v[13]); \ + G(r,7,v[ 3],v[ 4],v[ 9],v[14]); \ + } while(0) + +static void blake2s_compress( blake2s_state *S, const uint8_t in[BLAKE2S_BLOCKBYTES] ) +{ + uint32_t m[16]; + uint32_t v[16]; + size_t i; + + for( i = 0; i < 16; ++i ) { + m[i] = load32( in + i * sizeof( m[i] ) ); + } + + for( i = 0; i < 8; ++i ) { + v[i] = S->h[i]; + } + + v[ 8] = blake2s_IV[0]; + v[ 9] = blake2s_IV[1]; + v[10] = blake2s_IV[2]; + v[11] = blake2s_IV[3]; + v[12] = S->t[0] ^ blake2s_IV[4]; + v[13] = S->t[1] ^ blake2s_IV[5]; + v[14] = S->f[0] ^ blake2s_IV[6]; + v[15] = S->f[1] ^ blake2s_IV[7]; + + ROUND( 0 ); + ROUND( 1 ); + ROUND( 2 ); + ROUND( 3 ); + ROUND( 4 ); + ROUND( 5 ); + ROUND( 6 ); + ROUND( 7 ); + ROUND( 8 ); + ROUND( 9 ); + + for( i = 0; i < 8; ++i ) { + S->h[i] = S->h[i] ^ v[i] ^ v[i + 8]; + } +} + +#undef G +#undef ROUND + +int blake2s_update( blake2s_state *S, const void *pin, size_t inlen ) +{ + const unsigned char * in = (const unsigned char *)pin; + if( inlen > 0 ) + { + size_t left = S->buflen; + size_t fill = BLAKE2S_BLOCKBYTES - left; + if( inlen > fill ) + { + S->buflen = 0; + memcpy( S->buf + left, in, fill ); /* Fill buffer */ + blake2s_increment_counter( S, BLAKE2S_BLOCKBYTES ); + blake2s_compress( S, S->buf ); /* Compress */ + in += fill; inlen -= fill; + while(inlen > BLAKE2S_BLOCKBYTES) { + blake2s_increment_counter(S, BLAKE2S_BLOCKBYTES); + blake2s_compress( S, in ); + in += BLAKE2S_BLOCKBYTES; + inlen -= BLAKE2S_BLOCKBYTES; + } + } + memcpy( S->buf + S->buflen, in, inlen ); + S->buflen += inlen; + } + return 0; +} + +int blake2s_final( blake2s_state *S, void *out, size_t outlen ) +{ + uint8_t buffer[BLAKE2S_OUTBYTES] = {0}; + size_t i; + + if( out == NULL || outlen < S->outlen ) + return -1; + + if( blake2s_is_lastblock( S ) ) + return -1; + + blake2s_increment_counter( S, ( uint32_t )S->buflen ); + blake2s_set_lastblock( S ); + memset( S->buf + S->buflen, 0, BLAKE2S_BLOCKBYTES - S->buflen ); /* Padding */ + blake2s_compress( S, S->buf ); + + for( i = 0; i < 8; ++i ) /* Output full hash to temp buffer */ + store32( buffer + sizeof( S->h[i] ) * i, S->h[i] ); + + memcpy( out, buffer, outlen ); + secure_zero_memory(buffer, sizeof(buffer)); + return 0; +} + +int blake2s( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen ) +{ + blake2s_state S[1]; + + /* Verify parameters */ + if ( NULL == in && inlen > 0 ) return -1; + + if ( NULL == out ) return -1; + + if ( NULL == key && keylen > 0) return -1; + + if( !outlen || outlen > BLAKE2S_OUTBYTES ) return -1; + + if( keylen > BLAKE2S_KEYBYTES ) return -1; + + if( keylen > 0 ) + { + if( blake2s_init_key( S, outlen, key, keylen ) < 0 ) return -1; + } + else + { + if( blake2s_init( S, outlen ) < 0 ) return -1; + } + + blake2s_update( S, ( const uint8_t * )in, inlen ); + blake2s_final( S, out, outlen ); + return 0; +} + +#if defined(SUPERCOP) +int crypto_hash( unsigned char *out, unsigned char *in, unsigned long long inlen ) +{ + return blake2s( out, BLAKE2S_OUTBYTES, in, inlen, NULL, 0 ); +} +#endif + +#if defined(BLAKE2S_SELFTEST) +#include <string.h> +#include "blake2-kat.h" +int main( void ) +{ + uint8_t key[BLAKE2S_KEYBYTES]; + uint8_t buf[BLAKE2_KAT_LENGTH]; + size_t i, step; + + for( i = 0; i < BLAKE2S_KEYBYTES; ++i ) + key[i] = ( uint8_t )i; + + for( i = 0; i < BLAKE2_KAT_LENGTH; ++i ) + buf[i] = ( uint8_t )i; + + /* Test simple API */ + for( i = 0; i < BLAKE2_KAT_LENGTH; ++i ) + { + uint8_t hash[BLAKE2S_OUTBYTES]; + blake2s( hash, BLAKE2S_OUTBYTES, buf, i, key, BLAKE2S_KEYBYTES ); + + if( 0 != memcmp( hash, blake2s_keyed_kat[i], BLAKE2S_OUTBYTES ) ) + { + goto fail; + } + } + + /* Test streaming API */ + for(step = 1; step < BLAKE2S_BLOCKBYTES; ++step) { + for (i = 0; i < BLAKE2_KAT_LENGTH; ++i) { + uint8_t hash[BLAKE2S_OUTBYTES]; + blake2s_state S; + uint8_t * p = buf; + size_t mlen = i; + int err = 0; + + if( (err = blake2s_init_key(&S, BLAKE2S_OUTBYTES, key, BLAKE2S_KEYBYTES)) < 0 ) { + goto fail; + } + + while (mlen >= step) { + if ( (err = blake2s_update(&S, p, step)) < 0 ) { + goto fail; + } + mlen -= step; + p += step; + } + if ( (err = blake2s_update(&S, p, mlen)) < 0) { + goto fail; + } + if ( (err = blake2s_final(&S, hash, BLAKE2S_OUTBYTES)) < 0) { + goto fail; + } + + if (0 != memcmp(hash, blake2s_keyed_kat[i], BLAKE2S_OUTBYTES)) { + goto fail; + } + } + } + + puts( "ok" ); + return 0; +fail: + puts("error"); + return -1; +} +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_blake2sp_ref.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_blake2sp_ref.c new file mode 100644 index 0000000000..aef101084a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_blake2sp_ref.c @@ -0,0 +1,359 @@ +/* + BLAKE2 reference source code package - reference C implementations + + Copyright 2012, Samuel Neves <sneves@dei.uc.pt>. You may use this under the + terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at + your option. The terms of these licenses can be found at: + + - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0 + - OpenSSL license : https://www.openssl.org/source/license.html + - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0 + + More information about the BLAKE2 hash function can be found at + https://blake2.net. +*/ + +#include <stdlib.h> +#include <string.h> +#include <stdio.h> + +#if defined(_OPENMP) +#include <omp.h> +#endif + +#include "archive_blake2.h" +#include "archive_blake2_impl.h" + +#define PARALLELISM_DEGREE 8 + +/* + blake2sp_init_param defaults to setting the expecting output length + from the digest_length parameter block field. + + In some cases, however, we do not want this, as the output length + of these instances is given by inner_length instead. +*/ +static int blake2sp_init_leaf_param( blake2s_state *S, const blake2s_param *P ) +{ + int err = blake2s_init_param(S, P); + S->outlen = P->inner_length; + return err; +} + +static int blake2sp_init_leaf( blake2s_state *S, size_t outlen, size_t keylen, uint32_t offset ) +{ + blake2s_param P[1]; + P->digest_length = (uint8_t)outlen; + P->key_length = (uint8_t)keylen; + P->fanout = PARALLELISM_DEGREE; + P->depth = 2; + store32( &P->leaf_length, 0 ); + store32( &P->node_offset, offset ); + store16( &P->xof_length, 0 ); + P->node_depth = 0; + P->inner_length = BLAKE2S_OUTBYTES; + memset( P->salt, 0, sizeof( P->salt ) ); + memset( P->personal, 0, sizeof( P->personal ) ); + return blake2sp_init_leaf_param( S, P ); +} + +static int blake2sp_init_root( blake2s_state *S, size_t outlen, size_t keylen ) +{ + blake2s_param P[1]; + P->digest_length = (uint8_t)outlen; + P->key_length = (uint8_t)keylen; + P->fanout = PARALLELISM_DEGREE; + P->depth = 2; + store32( &P->leaf_length, 0 ); + store32( &P->node_offset, 0 ); + store16( &P->xof_length, 0 ); + P->node_depth = 1; + P->inner_length = BLAKE2S_OUTBYTES; + memset( P->salt, 0, sizeof( P->salt ) ); + memset( P->personal, 0, sizeof( P->personal ) ); + return blake2s_init_param( S, P ); +} + + +int blake2sp_init( blake2sp_state *S, size_t outlen ) +{ + size_t i; + + if( !outlen || outlen > BLAKE2S_OUTBYTES ) return -1; + + memset( S->buf, 0, sizeof( S->buf ) ); + S->buflen = 0; + S->outlen = outlen; + + if( blake2sp_init_root( S->R, outlen, 0 ) < 0 ) + return -1; + + for( i = 0; i < PARALLELISM_DEGREE; ++i ) + if( blake2sp_init_leaf( S->S[i], outlen, 0, (uint32_t)i ) < 0 ) return -1; + + S->R->last_node = 1; + S->S[PARALLELISM_DEGREE - 1]->last_node = 1; + return 0; +} + +int blake2sp_init_key( blake2sp_state *S, size_t outlen, const void *key, size_t keylen ) +{ + size_t i; + + if( !outlen || outlen > BLAKE2S_OUTBYTES ) return -1; + + if( !key || !keylen || keylen > BLAKE2S_KEYBYTES ) return -1; + + memset( S->buf, 0, sizeof( S->buf ) ); + S->buflen = 0; + S->outlen = outlen; + + if( blake2sp_init_root( S->R, outlen, keylen ) < 0 ) + return -1; + + for( i = 0; i < PARALLELISM_DEGREE; ++i ) + if( blake2sp_init_leaf( S->S[i], outlen, keylen, (uint32_t)i ) < 0 ) return -1; + + S->R->last_node = 1; + S->S[PARALLELISM_DEGREE - 1]->last_node = 1; + { + uint8_t block[BLAKE2S_BLOCKBYTES]; + memset( block, 0, BLAKE2S_BLOCKBYTES ); + memcpy( block, key, keylen ); + + for( i = 0; i < PARALLELISM_DEGREE; ++i ) + blake2s_update( S->S[i], block, BLAKE2S_BLOCKBYTES ); + + secure_zero_memory( block, BLAKE2S_BLOCKBYTES ); /* Burn the key from stack */ + } + return 0; +} + + +int blake2sp_update( blake2sp_state *S, const void *pin, size_t inlen ) +{ + const unsigned char * in = (const unsigned char *)pin; + size_t left = S->buflen; + size_t fill = sizeof( S->buf ) - left; + size_t i; + + if( left && inlen >= fill ) + { + memcpy( S->buf + left, in, fill ); + + for( i = 0; i < PARALLELISM_DEGREE; ++i ) + blake2s_update( S->S[i], S->buf + i * BLAKE2S_BLOCKBYTES, BLAKE2S_BLOCKBYTES ); + + in += fill; + inlen -= fill; + left = 0; + } + +#if defined(_OPENMP) + #pragma omp parallel shared(S), num_threads(PARALLELISM_DEGREE) +#else + for( i = 0; i < PARALLELISM_DEGREE; ++i ) +#endif + { +#if defined(_OPENMP) + size_t i = omp_get_thread_num(); +#endif + size_t inlen__ = inlen; + const unsigned char *in__ = ( const unsigned char * )in; + in__ += i * BLAKE2S_BLOCKBYTES; + + while( inlen__ >= PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES ) + { + blake2s_update( S->S[i], in__, BLAKE2S_BLOCKBYTES ); + in__ += PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES; + inlen__ -= PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES; + } + } + + in += inlen - inlen % ( PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES ); + inlen %= PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES; + + if( inlen > 0 ) + memcpy( S->buf + left, in, inlen ); + + S->buflen = left + inlen; + return 0; +} + + +int blake2sp_final( blake2sp_state *S, void *out, size_t outlen ) +{ + uint8_t hash[PARALLELISM_DEGREE][BLAKE2S_OUTBYTES]; + size_t i; + + if(out == NULL || outlen < S->outlen) { + return -1; + } + + for( i = 0; i < PARALLELISM_DEGREE; ++i ) + { + if( S->buflen > i * BLAKE2S_BLOCKBYTES ) + { + size_t left = S->buflen - i * BLAKE2S_BLOCKBYTES; + + if( left > BLAKE2S_BLOCKBYTES ) left = BLAKE2S_BLOCKBYTES; + + blake2s_update( S->S[i], S->buf + i * BLAKE2S_BLOCKBYTES, left ); + } + + blake2s_final( S->S[i], hash[i], BLAKE2S_OUTBYTES ); + } + + for( i = 0; i < PARALLELISM_DEGREE; ++i ) + blake2s_update( S->R, hash[i], BLAKE2S_OUTBYTES ); + + return blake2s_final( S->R, out, S->outlen ); +} + + +int blake2sp( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen ) +{ + uint8_t hash[PARALLELISM_DEGREE][BLAKE2S_OUTBYTES]; + blake2s_state S[PARALLELISM_DEGREE][1]; + blake2s_state FS[1]; + size_t i; + + /* Verify parameters */ + if ( NULL == in && inlen > 0 ) return -1; + + if ( NULL == out ) return -1; + + if ( NULL == key && keylen > 0) return -1; + + if( !outlen || outlen > BLAKE2S_OUTBYTES ) return -1; + + if( keylen > BLAKE2S_KEYBYTES ) return -1; + + for( i = 0; i < PARALLELISM_DEGREE; ++i ) + if( blake2sp_init_leaf( S[i], outlen, keylen, (uint32_t)i ) < 0 ) return -1; + + S[PARALLELISM_DEGREE - 1]->last_node = 1; /* mark last node */ + + if( keylen > 0 ) + { + uint8_t block[BLAKE2S_BLOCKBYTES]; + memset( block, 0, BLAKE2S_BLOCKBYTES ); + memcpy( block, key, keylen ); + + for( i = 0; i < PARALLELISM_DEGREE; ++i ) + blake2s_update( S[i], block, BLAKE2S_BLOCKBYTES ); + + secure_zero_memory( block, BLAKE2S_BLOCKBYTES ); /* Burn the key from stack */ + } + +#if defined(_OPENMP) + #pragma omp parallel shared(S,hash), num_threads(PARALLELISM_DEGREE) +#else + + for( i = 0; i < PARALLELISM_DEGREE; ++i ) +#endif + { +#if defined(_OPENMP) + size_t i = omp_get_thread_num(); +#endif + size_t inlen__ = inlen; + const unsigned char *in__ = ( const unsigned char * )in; + in__ += i * BLAKE2S_BLOCKBYTES; + + while( inlen__ >= PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES ) + { + blake2s_update( S[i], in__, BLAKE2S_BLOCKBYTES ); + in__ += PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES; + inlen__ -= PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES; + } + + if( inlen__ > i * BLAKE2S_BLOCKBYTES ) + { + const size_t left = inlen__ - i * BLAKE2S_BLOCKBYTES; + const size_t len = left <= BLAKE2S_BLOCKBYTES ? left : BLAKE2S_BLOCKBYTES; + blake2s_update( S[i], in__, len ); + } + + blake2s_final( S[i], hash[i], BLAKE2S_OUTBYTES ); + } + + if( blake2sp_init_root( FS, outlen, keylen ) < 0 ) + return -1; + + FS->last_node = 1; + + for( i = 0; i < PARALLELISM_DEGREE; ++i ) + blake2s_update( FS, hash[i], BLAKE2S_OUTBYTES ); + + return blake2s_final( FS, out, outlen ); +} + + + +#if defined(BLAKE2SP_SELFTEST) +#include <string.h> +#include "blake2-kat.h" +int main( void ) +{ + uint8_t key[BLAKE2S_KEYBYTES]; + uint8_t buf[BLAKE2_KAT_LENGTH]; + size_t i, step; + + for( i = 0; i < BLAKE2S_KEYBYTES; ++i ) + key[i] = ( uint8_t )i; + + for( i = 0; i < BLAKE2_KAT_LENGTH; ++i ) + buf[i] = ( uint8_t )i; + + /* Test simple API */ + for( i = 0; i < BLAKE2_KAT_LENGTH; ++i ) + { + uint8_t hash[BLAKE2S_OUTBYTES]; + blake2sp( hash, BLAKE2S_OUTBYTES, buf, i, key, BLAKE2S_KEYBYTES ); + + if( 0 != memcmp( hash, blake2sp_keyed_kat[i], BLAKE2S_OUTBYTES ) ) + { + goto fail; + } + } + + /* Test streaming API */ + for(step = 1; step < BLAKE2S_BLOCKBYTES; ++step) { + for (i = 0; i < BLAKE2_KAT_LENGTH; ++i) { + uint8_t hash[BLAKE2S_OUTBYTES]; + blake2sp_state S; + uint8_t * p = buf; + size_t mlen = i; + int err = 0; + + if( (err = blake2sp_init_key(&S, BLAKE2S_OUTBYTES, key, BLAKE2S_KEYBYTES)) < 0 ) { + goto fail; + } + + while (mlen >= step) { + if ( (err = blake2sp_update(&S, p, step)) < 0 ) { + goto fail; + } + mlen -= step; + p += step; + } + if ( (err = blake2sp_update(&S, p, mlen)) < 0) { + goto fail; + } + if ( (err = blake2sp_final(&S, hash, BLAKE2S_OUTBYTES)) < 0) { + goto fail; + } + + if (0 != memcmp(hash, blake2sp_keyed_kat[i], BLAKE2S_OUTBYTES)) { + goto fail; + } + } + } + + puts( "ok" ); + return 0; +fail: + puts("error"); + return -1; +} +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_check_magic.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_check_magic.c new file mode 100644 index 0000000000..288ce23385 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_check_magic.c @@ -0,0 +1,175 @@ +/*- + * Copyright (c) 2003-2010 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_check_magic.c 201089 2009-12-28 02:20:23Z kientzle $"); + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif + +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#if defined(_WIN32) && !defined(__CYGWIN__) +#include <windows.h> +#include <winbase.h> +#endif + +#include "archive_private.h" + +static void +errmsg(const char *m) +{ + size_t s = strlen(m); + ssize_t written; + + while (s > 0) { + written = write(2, m, strlen(m)); + if (written <= 0) + return; + m += written; + s -= written; + } +} + +static __LA_DEAD void +diediedie(void) +{ +#if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG) + /* Cause a breakpoint exception */ + DebugBreak(); +#endif + abort(); /* Terminate the program abnormally. */ +} + +static const char * +state_name(unsigned s) +{ + switch (s) { + case ARCHIVE_STATE_NEW: return ("new"); + case ARCHIVE_STATE_HEADER: return ("header"); + case ARCHIVE_STATE_DATA: return ("data"); + case ARCHIVE_STATE_EOF: return ("eof"); + case ARCHIVE_STATE_CLOSED: return ("closed"); + case ARCHIVE_STATE_FATAL: return ("fatal"); + default: return ("??"); + } +} + +static const char * +archive_handle_type_name(unsigned m) +{ + switch (m) { + case ARCHIVE_WRITE_MAGIC: return ("archive_write"); + case ARCHIVE_READ_MAGIC: return ("archive_read"); + case ARCHIVE_WRITE_DISK_MAGIC: return ("archive_write_disk"); + case ARCHIVE_READ_DISK_MAGIC: return ("archive_read_disk"); + case ARCHIVE_MATCH_MAGIC: return ("archive_match"); + default: return NULL; + } +} + + +static char * +write_all_states(char *buff, unsigned int states) +{ + unsigned int lowbit; + + buff[0] = '\0'; + + /* A trick for computing the lowest set bit. */ + while ((lowbit = states & (1 + ~states)) != 0) { + states &= ~lowbit; /* Clear the low bit. */ + strcat(buff, state_name(lowbit)); + if (states != 0) + strcat(buff, "/"); + } + return buff; +} + +/* + * Check magic value and current state. + * Magic value mismatches are fatal and result in calls to abort(). + * State mismatches return ARCHIVE_FATAL. + * Otherwise, returns ARCHIVE_OK. + * + * This is designed to catch serious programming errors that violate + * the libarchive API. + */ +int +__archive_check_magic(struct archive *a, unsigned int magic, + unsigned int state, const char *function) +{ + char states1[64]; + char states2[64]; + const char *handle_type; + + /* + * If this isn't some form of archive handle, + * then the library user has screwed up so bad that + * we don't even have a reliable way to report an error. + */ + handle_type = archive_handle_type_name(a->magic); + + if (!handle_type) { + errmsg("PROGRAMMER ERROR: Function "); + errmsg(function); + errmsg(" invoked with invalid archive handle.\n"); + diediedie(); + } + + if (a->magic != magic) { + archive_set_error(a, -1, + "PROGRAMMER ERROR: Function '%s' invoked" + " on '%s' archive object, which is not supported.", + function, + handle_type); + a->state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + + if ((a->state & state) == 0) { + /* If we're already FATAL, don't overwrite the error. */ + if (a->state != ARCHIVE_STATE_FATAL) + archive_set_error(a, -1, + "INTERNAL ERROR: Function '%s' invoked with" + " archive structure in state '%s'," + " should be in state '%s'", + function, + write_all_states(states1, a->state), + write_all_states(states2, state)); + a->state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + return ARCHIVE_OK; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_cmdline.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_cmdline.c new file mode 100644 index 0000000000..5c519cd17f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_cmdline.c @@ -0,0 +1,227 @@ +/*- + * Copyright (c) 2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_STRING_H +# include <string.h> +#endif +#ifdef HAVE_STDLIB_H +# include <stdlib.h> +#endif + +#include "archive.h" +#include "archive_cmdline_private.h" +#include "archive_string.h" + +static int cmdline_set_path(struct archive_cmdline *, const char *); +static int cmdline_add_arg(struct archive_cmdline *, const char *); + +static ssize_t +extract_quotation(struct archive_string *as, const char *p) +{ + const char *s; + + for (s = p + 1; *s;) { + if (*s == '\\') { + if (s[1] != '\0') { + archive_strappend_char(as, s[1]); + s += 2; + } else + s++; + } else if (*s == '"') + break; + else { + archive_strappend_char(as, s[0]); + s++; + } + } + if (*s != '"') + return (ARCHIVE_FAILED);/* Invalid sequence. */ + return ((ssize_t)(s + 1 - p)); +} + +static ssize_t +get_argument(struct archive_string *as, const char *p) +{ + const char *s = p; + + archive_string_empty(as); + + /* Skip beginning space characters. */ + while (*s != '\0' && *s == ' ') + s++; + /* Copy non-space characters. */ + while (*s != '\0' && *s != ' ') { + if (*s == '\\') { + if (s[1] != '\0') { + archive_strappend_char(as, s[1]); + s += 2; + } else { + s++;/* Ignore this character.*/ + break; + } + } else if (*s == '"') { + ssize_t q = extract_quotation(as, s); + if (q < 0) + return (ARCHIVE_FAILED);/* Invalid sequence. */ + s += q; + } else { + archive_strappend_char(as, s[0]); + s++; + } + } + return ((ssize_t)(s - p)); +} + +/* + * Set up command line arguments. + * Returns ARCHIVE_OK if everything okey. + * Returns ARCHIVE_FAILED if there is a lack of the `"' terminator or an + * empty command line. + * Returns ARCHIVE_FATAL if no memory. + */ +int +__archive_cmdline_parse(struct archive_cmdline *data, const char *cmd) +{ + struct archive_string as; + const char *p; + ssize_t al; + int r; + + archive_string_init(&as); + + /* Get first argument as a command path. */ + al = get_argument(&as, cmd); + if (al < 0) { + r = ARCHIVE_FAILED;/* Invalid sequence. */ + goto exit_function; + } + if (archive_strlen(&as) == 0) { + r = ARCHIVE_FAILED;/* An empty command path. */ + goto exit_function; + } + r = cmdline_set_path(data, as.s); + if (r != ARCHIVE_OK) + goto exit_function; + p = strrchr(as.s, '/'); + if (p == NULL) + p = as.s; + else + p++; + r = cmdline_add_arg(data, p); + if (r != ARCHIVE_OK) + goto exit_function; + cmd += al; + + for (;;) { + al = get_argument(&as, cmd); + if (al < 0) { + r = ARCHIVE_FAILED;/* Invalid sequence. */ + goto exit_function; + } + if (al == 0) + break; + cmd += al; + if (archive_strlen(&as) == 0 && *cmd == '\0') + break; + r = cmdline_add_arg(data, as.s); + if (r != ARCHIVE_OK) + goto exit_function; + } + r = ARCHIVE_OK; +exit_function: + archive_string_free(&as); + return (r); +} + +/* + * Set the program path. + */ +static int +cmdline_set_path(struct archive_cmdline *data, const char *path) +{ + char *newptr; + + newptr = realloc(data->path, strlen(path) + 1); + if (newptr == NULL) + return (ARCHIVE_FATAL); + data->path = newptr; + strcpy(data->path, path); + return (ARCHIVE_OK); +} + +/* + * Add a argument for the program. + */ +static int +cmdline_add_arg(struct archive_cmdline *data, const char *arg) +{ + char **newargv; + + if (data->path == NULL) + return (ARCHIVE_FAILED); + + newargv = realloc(data->argv, (data->argc + 2) * sizeof(char *)); + if (newargv == NULL) + return (ARCHIVE_FATAL); + data->argv = newargv; + data->argv[data->argc] = strdup(arg); + if (data->argv[data->argc] == NULL) + return (ARCHIVE_FATAL); + /* Set the terminator of argv. */ + data->argv[++data->argc] = NULL; + return (ARCHIVE_OK); +} + +struct archive_cmdline * +__archive_cmdline_allocate(void) +{ + return (struct archive_cmdline *) + calloc(1, sizeof(struct archive_cmdline)); +} + +/* + * Release the resources. + */ +int +__archive_cmdline_free(struct archive_cmdline *data) +{ + + if (data) { + free(data->path); + if (data->argv != NULL) { + int i; + for (i = 0; data->argv[i] != NULL; i++) + free(data->argv[i]); + free(data->argv); + } + free(data); + } + return (ARCHIVE_OK); +} + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_cmdline_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_cmdline_private.h new file mode 100644 index 0000000000..57a19494fd --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_cmdline_private.h @@ -0,0 +1,47 @@ +/*- + * Copyright (c) 2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + * + * $FreeBSD$ + */ + +#ifndef ARCHIVE_CMDLINE_PRIVATE_H +#define ARCHIVE_CMDLINE_PRIVATE_H + +#ifndef __LIBARCHIVE_BUILD +#ifndef __LIBARCHIVE_TEST +#error This header is only to be used internally to libarchive. +#endif +#endif + +struct archive_cmdline { + char *path; + char **argv; + int argc; +}; + +struct archive_cmdline *__archive_cmdline_allocate(void); +int __archive_cmdline_parse(struct archive_cmdline *, const char *); +int __archive_cmdline_free(struct archive_cmdline *); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_crc32.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_crc32.h new file mode 100644 index 0000000000..4f1aed3059 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_crc32.h @@ -0,0 +1,83 @@ +/*- + * Copyright (c) 2009 Joerg Sonnenberger + * 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(S) ``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(S) 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. + * + * $FreeBSD: head/lib/libarchive/archive_crc32.h 201102 2009-12-28 03:11:36Z kientzle $ + */ + +#ifndef ARCHIVE_CRC32_H +#define ARCHIVE_CRC32_H + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +/* + * When zlib is unavailable, we should still be able to validate + * uncompressed zip archives. That requires us to be able to compute + * the CRC32 check value. This is a drop-in compatible replacement + * for crc32() from zlib. It's slower than the zlib implementation, + * but still pretty fast: This runs about 300MB/s on my 3GHz P4 + * compared to about 800MB/s for the zlib implementation. + */ +static unsigned long +crc32(unsigned long crc, const void *_p, size_t len) +{ + unsigned long crc2, b, i; + const unsigned char *p = _p; + static volatile int crc_tbl_inited = 0; + static unsigned long crc_tbl[256]; + + if (!crc_tbl_inited) { + for (b = 0; b < 256; ++b) { + crc2 = b; + for (i = 8; i > 0; --i) { + if (crc2 & 1) + crc2 = (crc2 >> 1) ^ 0xedb88320UL; + else + crc2 = (crc2 >> 1); + } + crc_tbl[b] = crc2; + } + crc_tbl_inited = 1; + } + + crc = crc ^ 0xffffffffUL; + /* A use of this loop is about 20% - 30% faster than + * no use version in any optimization option of gcc. */ + for (;len >= 8; len -= 8) { + crc = crc_tbl[(crc ^ *p++) & 0xff] ^ (crc >> 8); + crc = crc_tbl[(crc ^ *p++) & 0xff] ^ (crc >> 8); + crc = crc_tbl[(crc ^ *p++) & 0xff] ^ (crc >> 8); + crc = crc_tbl[(crc ^ *p++) & 0xff] ^ (crc >> 8); + crc = crc_tbl[(crc ^ *p++) & 0xff] ^ (crc >> 8); + crc = crc_tbl[(crc ^ *p++) & 0xff] ^ (crc >> 8); + crc = crc_tbl[(crc ^ *p++) & 0xff] ^ (crc >> 8); + crc = crc_tbl[(crc ^ *p++) & 0xff] ^ (crc >> 8); + } + while (len--) + crc = crc_tbl[(crc ^ *p++) & 0xff] ^ (crc >> 8); + return (crc ^ 0xffffffffUL); +} + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_cryptor.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_cryptor.c new file mode 100644 index 0000000000..8ab2b09796 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_cryptor.c @@ -0,0 +1,519 @@ +/*- +* Copyright (c) 2014 Michihiro NAKAJIMA +* 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(S) ``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(S) 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. +*/ + +#include "archive_platform.h" + +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#include "archive.h" +#include "archive_cryptor_private.h" + +/* + * On systems that do not support any recognized crypto libraries, + * this file will normally define no usable symbols. + * + * But some compilers and linkers choke on empty object files, so + * define a public symbol that will always exist. This could + * be removed someday if this file gains another always-present + * symbol definition. + */ +int __libarchive_cryptor_build_hack(void) { + return 0; +} + +#ifdef ARCHIVE_CRYPTOR_USE_Apple_CommonCrypto + +static int +pbkdf2_sha1(const char *pw, size_t pw_len, const uint8_t *salt, + size_t salt_len, unsigned rounds, uint8_t *derived_key, + size_t derived_key_len) +{ + CCKeyDerivationPBKDF(kCCPBKDF2, (const char *)pw, + pw_len, salt, salt_len, kCCPRFHmacAlgSHA1, rounds, + derived_key, derived_key_len); + return 0; +} + +#elif defined(_WIN32) && !defined(__CYGWIN__) && defined(HAVE_BCRYPT_H) +#ifdef _MSC_VER +#pragma comment(lib, "Bcrypt.lib") +#endif + +static int +pbkdf2_sha1(const char *pw, size_t pw_len, const uint8_t *salt, + size_t salt_len, unsigned rounds, uint8_t *derived_key, + size_t derived_key_len) +{ + NTSTATUS status; + BCRYPT_ALG_HANDLE hAlg; + + status = BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_SHA1_ALGORITHM, + MS_PRIMITIVE_PROVIDER, BCRYPT_ALG_HANDLE_HMAC_FLAG); + if (!BCRYPT_SUCCESS(status)) + return -1; + + status = BCryptDeriveKeyPBKDF2(hAlg, + (PUCHAR)(uintptr_t)pw, (ULONG)pw_len, + (PUCHAR)(uintptr_t)salt, (ULONG)salt_len, rounds, + (PUCHAR)derived_key, (ULONG)derived_key_len, 0); + + BCryptCloseAlgorithmProvider(hAlg, 0); + + return (BCRYPT_SUCCESS(status)) ? 0: -1; +} + +#elif defined(HAVE_LIBMBEDCRYPTO) && defined(HAVE_MBEDTLS_PKCS5_H) + +static int +pbkdf2_sha1(const char *pw, size_t pw_len, const uint8_t *salt, + size_t salt_len, unsigned rounds, uint8_t *derived_key, + size_t derived_key_len) +{ + mbedtls_md_context_t ctx; + const mbedtls_md_info_t *info; + int ret; + + mbedtls_md_init(&ctx); + info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1); + if (info == NULL) { + mbedtls_md_free(&ctx); + return (-1); + } + ret = mbedtls_md_setup(&ctx, info, 1); + if (ret != 0) { + mbedtls_md_free(&ctx); + return (-1); + } + ret = mbedtls_pkcs5_pbkdf2_hmac(&ctx, (const unsigned char *)pw, + pw_len, salt, salt_len, rounds, derived_key_len, derived_key); + + mbedtls_md_free(&ctx); + return (ret); +} + +#elif defined(HAVE_LIBNETTLE) && defined(HAVE_NETTLE_PBKDF2_H) + +static int +pbkdf2_sha1(const char *pw, size_t pw_len, const uint8_t *salt, + size_t salt_len, unsigned rounds, uint8_t *derived_key, + size_t derived_key_len) { + pbkdf2_hmac_sha1((unsigned)pw_len, (const uint8_t *)pw, rounds, + salt_len, salt, derived_key_len, derived_key); + return 0; +} + +#elif defined(HAVE_LIBCRYPTO) && defined(HAVE_PKCS5_PBKDF2_HMAC_SHA1) + +static int +pbkdf2_sha1(const char *pw, size_t pw_len, const uint8_t *salt, + size_t salt_len, unsigned rounds, uint8_t *derived_key, + size_t derived_key_len) { + + PKCS5_PBKDF2_HMAC_SHA1(pw, pw_len, salt, salt_len, rounds, + derived_key_len, derived_key); + return 0; +} + +#else + +/* Stub */ +static int +pbkdf2_sha1(const char *pw, size_t pw_len, const uint8_t *salt, + size_t salt_len, unsigned rounds, uint8_t *derived_key, + size_t derived_key_len) { + (void)pw; /* UNUSED */ + (void)pw_len; /* UNUSED */ + (void)salt; /* UNUSED */ + (void)salt_len; /* UNUSED */ + (void)rounds; /* UNUSED */ + (void)derived_key; /* UNUSED */ + (void)derived_key_len; /* UNUSED */ + return -1; /* UNSUPPORTED */ +} + +#endif + +#ifdef ARCHIVE_CRYPTOR_USE_Apple_CommonCrypto +# if MAC_OS_X_VERSION_MAX_ALLOWED < 1090 +# define kCCAlgorithmAES kCCAlgorithmAES128 +# endif + +static int +aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len) +{ + CCCryptorStatus r; + + ctx->key_len = key_len; + memcpy(ctx->key, key, key_len); + memset(ctx->nonce, 0, sizeof(ctx->nonce)); + ctx->encr_pos = AES_BLOCK_SIZE; + r = CCCryptorCreateWithMode(kCCEncrypt, kCCModeECB, kCCAlgorithmAES, + ccNoPadding, NULL, key, key_len, NULL, 0, 0, 0, &ctx->ctx); + return (r == kCCSuccess)? 0: -1; +} + +static int +aes_ctr_encrypt_counter(archive_crypto_ctx *ctx) +{ + CCCryptorRef ref = ctx->ctx; + CCCryptorStatus r; + + r = CCCryptorReset(ref, NULL); + if (r != kCCSuccess && r != kCCUnimplemented) + return -1; + r = CCCryptorUpdate(ref, ctx->nonce, AES_BLOCK_SIZE, ctx->encr_buf, + AES_BLOCK_SIZE, NULL); + return (r == kCCSuccess)? 0: -1; +} + +static int +aes_ctr_release(archive_crypto_ctx *ctx) +{ + memset(ctx->key, 0, ctx->key_len); + memset(ctx->nonce, 0, sizeof(ctx->nonce)); + return 0; +} + +#elif defined(_WIN32) && !defined(__CYGWIN__) && defined(HAVE_BCRYPT_H) + +static int +aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len) +{ + BCRYPT_ALG_HANDLE hAlg; + BCRYPT_KEY_HANDLE hKey; + DWORD keyObj_len, aes_key_len; + PBYTE keyObj; + ULONG result; + NTSTATUS status; + BCRYPT_KEY_LENGTHS_STRUCT key_lengths; + + ctx->hAlg = NULL; + ctx->hKey = NULL; + ctx->keyObj = NULL; + switch (key_len) { + case 16: aes_key_len = 128; break; + case 24: aes_key_len = 192; break; + case 32: aes_key_len = 256; break; + default: return -1; + } + status = BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_AES_ALGORITHM, + MS_PRIMITIVE_PROVIDER, 0); + if (!BCRYPT_SUCCESS(status)) + return -1; + status = BCryptGetProperty(hAlg, BCRYPT_KEY_LENGTHS, (PUCHAR)&key_lengths, + sizeof(key_lengths), &result, 0); + if (!BCRYPT_SUCCESS(status)) { + BCryptCloseAlgorithmProvider(hAlg, 0); + return -1; + } + if (key_lengths.dwMinLength > aes_key_len + || key_lengths.dwMaxLength < aes_key_len) { + BCryptCloseAlgorithmProvider(hAlg, 0); + return -1; + } + status = BCryptGetProperty(hAlg, BCRYPT_OBJECT_LENGTH, (PUCHAR)&keyObj_len, + sizeof(keyObj_len), &result, 0); + if (!BCRYPT_SUCCESS(status)) { + BCryptCloseAlgorithmProvider(hAlg, 0); + return -1; + } + keyObj = (PBYTE)HeapAlloc(GetProcessHeap(), 0, keyObj_len); + if (keyObj == NULL) { + BCryptCloseAlgorithmProvider(hAlg, 0); + return -1; + } + status = BCryptSetProperty(hAlg, BCRYPT_CHAINING_MODE, + (PUCHAR)BCRYPT_CHAIN_MODE_ECB, sizeof(BCRYPT_CHAIN_MODE_ECB), 0); + if (!BCRYPT_SUCCESS(status)) { + BCryptCloseAlgorithmProvider(hAlg, 0); + HeapFree(GetProcessHeap(), 0, keyObj); + return -1; + } + status = BCryptGenerateSymmetricKey(hAlg, &hKey, + keyObj, keyObj_len, + (PUCHAR)(uintptr_t)key, (ULONG)key_len, 0); + if (!BCRYPT_SUCCESS(status)) { + BCryptCloseAlgorithmProvider(hAlg, 0); + HeapFree(GetProcessHeap(), 0, keyObj); + return -1; + } + + ctx->hAlg = hAlg; + ctx->hKey = hKey; + ctx->keyObj = keyObj; + ctx->keyObj_len = keyObj_len; + ctx->encr_pos = AES_BLOCK_SIZE; + + return 0; +} + +static int +aes_ctr_encrypt_counter(archive_crypto_ctx *ctx) +{ + NTSTATUS status; + ULONG result; + + status = BCryptEncrypt(ctx->hKey, (PUCHAR)ctx->nonce, AES_BLOCK_SIZE, + NULL, NULL, 0, (PUCHAR)ctx->encr_buf, AES_BLOCK_SIZE, + &result, 0); + return BCRYPT_SUCCESS(status) ? 0 : -1; +} + +static int +aes_ctr_release(archive_crypto_ctx *ctx) +{ + + if (ctx->hAlg != NULL) { + BCryptCloseAlgorithmProvider(ctx->hAlg, 0); + ctx->hAlg = NULL; + BCryptDestroyKey(ctx->hKey); + ctx->hKey = NULL; + HeapFree(GetProcessHeap(), 0, ctx->keyObj); + ctx->keyObj = NULL; + } + memset(ctx, 0, sizeof(*ctx)); + return 0; +} + +#elif defined(HAVE_LIBMBEDCRYPTO) && defined(HAVE_MBEDTLS_AES_H) + +static int +aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len) +{ + mbedtls_aes_init(&ctx->ctx); + ctx->key_len = key_len; + memcpy(ctx->key, key, key_len); + memset(ctx->nonce, 0, sizeof(ctx->nonce)); + ctx->encr_pos = AES_BLOCK_SIZE; + return 0; +} + +static int +aes_ctr_encrypt_counter(archive_crypto_ctx *ctx) +{ + if (mbedtls_aes_setkey_enc(&ctx->ctx, ctx->key, + ctx->key_len * 8) != 0) + return (-1); + if (mbedtls_aes_crypt_ecb(&ctx->ctx, MBEDTLS_AES_ENCRYPT, ctx->nonce, + ctx->encr_buf) != 0) + return (-1); + return 0; +} + +static int +aes_ctr_release(archive_crypto_ctx *ctx) +{ + mbedtls_aes_free(&ctx->ctx); + memset(ctx, 0, sizeof(*ctx)); + return 0; +} + +#elif defined(HAVE_LIBNETTLE) && defined(HAVE_NETTLE_AES_H) + +static int +aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len) +{ + ctx->key_len = key_len; + memcpy(ctx->key, key, key_len); + memset(ctx->nonce, 0, sizeof(ctx->nonce)); + ctx->encr_pos = AES_BLOCK_SIZE; + memset(&ctx->ctx, 0, sizeof(ctx->ctx)); + return 0; +} + +static int +aes_ctr_encrypt_counter(archive_crypto_ctx *ctx) +{ + aes_set_encrypt_key(&ctx->ctx, ctx->key_len, ctx->key); + aes_encrypt(&ctx->ctx, AES_BLOCK_SIZE, ctx->encr_buf, ctx->nonce); + return 0; +} + +static int +aes_ctr_release(archive_crypto_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); + return 0; +} + +#elif defined(HAVE_LIBCRYPTO) + +static int +aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len) +{ + if ((ctx->ctx = EVP_CIPHER_CTX_new()) == NULL) + return -1; + + switch (key_len) { + case 16: ctx->type = EVP_aes_128_ecb(); break; + case 24: ctx->type = EVP_aes_192_ecb(); break; + case 32: ctx->type = EVP_aes_256_ecb(); break; + default: ctx->type = NULL; return -1; + } + + ctx->key_len = key_len; + memcpy(ctx->key, key, key_len); + memset(ctx->nonce, 0, sizeof(ctx->nonce)); + ctx->encr_pos = AES_BLOCK_SIZE; +#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER) + if (!EVP_CIPHER_CTX_reset(ctx->ctx)) { + EVP_CIPHER_CTX_free(ctx->ctx); + ctx->ctx = NULL; + } +#else + EVP_CIPHER_CTX_init(ctx->ctx); +#endif + return 0; +} + +static int +aes_ctr_encrypt_counter(archive_crypto_ctx *ctx) +{ + int outl = 0; + int r; + + r = EVP_EncryptInit_ex(ctx->ctx, ctx->type, NULL, ctx->key, NULL); + if (r == 0) + return -1; + r = EVP_EncryptUpdate(ctx->ctx, ctx->encr_buf, &outl, ctx->nonce, + AES_BLOCK_SIZE); + if (r == 0 || outl != AES_BLOCK_SIZE) + return -1; + return 0; +} + +static int +aes_ctr_release(archive_crypto_ctx *ctx) +{ + EVP_CIPHER_CTX_free(ctx->ctx); + memset(ctx->key, 0, ctx->key_len); + memset(ctx->nonce, 0, sizeof(ctx->nonce)); + return 0; +} + +#else + +#define ARCHIVE_CRYPTOR_STUB +/* Stub */ +static int +aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len) +{ + (void)ctx; /* UNUSED */ + (void)key; /* UNUSED */ + (void)key_len; /* UNUSED */ + return -1; +} + +static int +aes_ctr_encrypt_counter(archive_crypto_ctx *ctx) +{ + (void)ctx; /* UNUSED */ + return -1; +} + +static int +aes_ctr_release(archive_crypto_ctx *ctx) +{ + (void)ctx; /* UNUSED */ + return 0; +} + +#endif + +#ifdef ARCHIVE_CRYPTOR_STUB +static int +aes_ctr_update(archive_crypto_ctx *ctx, const uint8_t * const in, + size_t in_len, uint8_t * const out, size_t *out_len) +{ + (void)ctx; /* UNUSED */ + (void)in; /* UNUSED */ + (void)in_len; /* UNUSED */ + (void)out; /* UNUSED */ + (void)out_len; /* UNUSED */ + aes_ctr_encrypt_counter(ctx); /* UNUSED */ /* Fix unused function warning */ + return -1; +} + +#else +static void +aes_ctr_increase_counter(archive_crypto_ctx *ctx) +{ + uint8_t *const nonce = ctx->nonce; + int j; + + for (j = 0; j < 8; j++) { + if (++nonce[j]) + break; + } +} + +static int +aes_ctr_update(archive_crypto_ctx *ctx, const uint8_t * const in, + size_t in_len, uint8_t * const out, size_t *out_len) +{ + uint8_t *const ebuf = ctx->encr_buf; + unsigned pos = ctx->encr_pos; + unsigned max = (unsigned)((in_len < *out_len)? in_len: *out_len); + unsigned i; + + for (i = 0; i < max; ) { + if (pos == AES_BLOCK_SIZE) { + aes_ctr_increase_counter(ctx); + if (aes_ctr_encrypt_counter(ctx) != 0) + return -1; + while (max -i >= AES_BLOCK_SIZE) { + for (pos = 0; pos < AES_BLOCK_SIZE; pos++) + out[i+pos] = in[i+pos] ^ ebuf[pos]; + i += AES_BLOCK_SIZE; + aes_ctr_increase_counter(ctx); + if (aes_ctr_encrypt_counter(ctx) != 0) + return -1; + } + pos = 0; + if (i >= max) + break; + } + out[i] = in[i] ^ ebuf[pos++]; + i++; + } + ctx->encr_pos = pos; + *out_len = i; + + return 0; +} +#endif /* ARCHIVE_CRYPTOR_STUB */ + + +const struct archive_cryptor __archive_cryptor = +{ + &pbkdf2_sha1, + &aes_ctr_init, + &aes_ctr_update, + &aes_ctr_release, + &aes_ctr_init, + &aes_ctr_update, + &aes_ctr_release, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_cryptor_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_cryptor_private.h new file mode 100644 index 0000000000..64a20556a3 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_cryptor_private.h @@ -0,0 +1,179 @@ +/*- +* Copyright (c) 2014 Michihiro NAKAJIMA +* 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(S) ``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(S) 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. +*/ + +#ifndef ARCHIVE_CRYPTOR_PRIVATE_H_INCLUDED +#define ARCHIVE_CRYPTOR_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif +/* + * On systems that do not support any recognized crypto libraries, + * the archive_cryptor.c file will normally define no usable symbols. + * + * But some compilers and linkers choke on empty object files, so + * define a public symbol that will always exist. This could + * be removed someday if this file gains another always-present + * symbol definition. + */ +int __libarchive_cryptor_build_hack(void); + +#ifdef __APPLE__ +# include <AvailabilityMacros.h> +# if MAC_OS_X_VERSION_MAX_ALLOWED >= 1080 +# define ARCHIVE_CRYPTOR_USE_Apple_CommonCrypto +# endif +#endif + +#ifdef ARCHIVE_CRYPTOR_USE_Apple_CommonCrypto +#include <CommonCrypto/CommonCryptor.h> +#include <CommonCrypto/CommonKeyDerivation.h> +#define AES_BLOCK_SIZE 16 +#define AES_MAX_KEY_SIZE kCCKeySizeAES256 + +typedef struct { + CCCryptorRef ctx; + uint8_t key[AES_MAX_KEY_SIZE]; + unsigned key_len; + uint8_t nonce[AES_BLOCK_SIZE]; + uint8_t encr_buf[AES_BLOCK_SIZE]; + unsigned encr_pos; +} archive_crypto_ctx; + +#elif defined(_WIN32) && !defined(__CYGWIN__) && defined(HAVE_BCRYPT_H) +#include <bcrypt.h> + +/* Common in other bcrypt implementations, but missing from VS2008. */ +#ifndef BCRYPT_SUCCESS +#define BCRYPT_SUCCESS(r) ((NTSTATUS)(r) == STATUS_SUCCESS) +#endif + +#define AES_MAX_KEY_SIZE 32 +#define AES_BLOCK_SIZE 16 +typedef struct { + BCRYPT_ALG_HANDLE hAlg; + BCRYPT_KEY_HANDLE hKey; + PBYTE keyObj; + DWORD keyObj_len; + uint8_t nonce[AES_BLOCK_SIZE]; + uint8_t encr_buf[AES_BLOCK_SIZE]; + unsigned encr_pos; +} archive_crypto_ctx; + +#elif defined(HAVE_LIBMBEDCRYPTO) && defined(HAVE_MBEDTLS_AES_H) +#include <mbedtls/aes.h> +#include <mbedtls/md.h> +#include <mbedtls/pkcs5.h> + +#define AES_MAX_KEY_SIZE 32 +#define AES_BLOCK_SIZE 16 + +typedef struct { + mbedtls_aes_context ctx; + uint8_t key[AES_MAX_KEY_SIZE]; + unsigned key_len; + uint8_t nonce[AES_BLOCK_SIZE]; + uint8_t encr_buf[AES_BLOCK_SIZE]; + unsigned encr_pos; +} archive_crypto_ctx; + +#elif defined(HAVE_LIBNETTLE) && defined(HAVE_NETTLE_AES_H) +#if defined(HAVE_NETTLE_PBKDF2_H) +#include <nettle/pbkdf2.h> +#endif +#include <nettle/aes.h> + +typedef struct { + struct aes_ctx ctx; + uint8_t key[AES_MAX_KEY_SIZE]; + unsigned key_len; + uint8_t nonce[AES_BLOCK_SIZE]; + uint8_t encr_buf[AES_BLOCK_SIZE]; + unsigned encr_pos; +} archive_crypto_ctx; + +#elif defined(HAVE_LIBCRYPTO) +#include "archive_openssl_evp_private.h" +#define AES_BLOCK_SIZE 16 +#define AES_MAX_KEY_SIZE 32 + +typedef struct { + EVP_CIPHER_CTX *ctx; + const EVP_CIPHER *type; + uint8_t key[AES_MAX_KEY_SIZE]; + unsigned key_len; + uint8_t nonce[AES_BLOCK_SIZE]; + uint8_t encr_buf[AES_BLOCK_SIZE]; + unsigned encr_pos; +} archive_crypto_ctx; + +#else + +#define AES_BLOCK_SIZE 16 +#define AES_MAX_KEY_SIZE 32 +typedef int archive_crypto_ctx; + +#endif + +/* defines */ +#define archive_pbkdf2_sha1(pw, pw_len, salt, salt_len, rounds, dk, dk_len)\ + __archive_cryptor.pbkdf2sha1(pw, pw_len, salt, salt_len, rounds, dk, dk_len) + +#define archive_decrypto_aes_ctr_init(ctx, key, key_len) \ + __archive_cryptor.decrypto_aes_ctr_init(ctx, key, key_len) +#define archive_decrypto_aes_ctr_update(ctx, in, in_len, out, out_len) \ + __archive_cryptor.decrypto_aes_ctr_update(ctx, in, in_len, out, out_len) +#define archive_decrypto_aes_ctr_release(ctx) \ + __archive_cryptor.decrypto_aes_ctr_release(ctx) + +#define archive_encrypto_aes_ctr_init(ctx, key, key_len) \ + __archive_cryptor.encrypto_aes_ctr_init(ctx, key, key_len) +#define archive_encrypto_aes_ctr_update(ctx, in, in_len, out, out_len) \ + __archive_cryptor.encrypto_aes_ctr_update(ctx, in, in_len, out, out_len) +#define archive_encrypto_aes_ctr_release(ctx) \ + __archive_cryptor.encrypto_aes_ctr_release(ctx) + +/* Minimal interface to cryptographic functionality for internal use in + * libarchive */ +struct archive_cryptor +{ + /* PKCS5 PBKDF2 HMAC-SHA1 */ + int (*pbkdf2sha1)(const char *pw, size_t pw_len, const uint8_t *salt, + size_t salt_len, unsigned rounds, uint8_t *derived_key, + size_t derived_key_len); + /* AES CTR mode(little endian version) */ + int (*decrypto_aes_ctr_init)(archive_crypto_ctx *, const uint8_t *, size_t); + int (*decrypto_aes_ctr_update)(archive_crypto_ctx *, const uint8_t *, + size_t, uint8_t *, size_t *); + int (*decrypto_aes_ctr_release)(archive_crypto_ctx *); + int (*encrypto_aes_ctr_init)(archive_crypto_ctx *, const uint8_t *, size_t); + int (*encrypto_aes_ctr_update)(archive_crypto_ctx *, const uint8_t *, + size_t, uint8_t *, size_t *); + int (*encrypto_aes_ctr_release)(archive_crypto_ctx *); +}; + +extern const struct archive_cryptor __archive_cryptor; + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_digest.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_digest.c new file mode 100644 index 0000000000..410df01563 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_digest.c @@ -0,0 +1,1499 @@ +/*- +* Copyright (c) 2003-2007 Tim Kientzle +* Copyright (c) 2011 Andres Mejia +* Copyright (c) 2011 Michihiro NAKAJIMA +* 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(S) ``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(S) 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. +*/ + +#include "archive_platform.h" + +#include "archive.h" +#include "archive_digest_private.h" + +/* In particular, force the configure probe to break if it tries + * to test a combination of OpenSSL and libmd. */ +#if defined(ARCHIVE_CRYPTO_OPENSSL) && defined(ARCHIVE_CRYPTO_LIBMD) +#error Cannot use both OpenSSL and libmd. +#endif + +/* + * Message digest functions for Windows platform. + */ +#if defined(ARCHIVE_CRYPTO_MD5_WIN) ||\ + defined(ARCHIVE_CRYPTO_SHA1_WIN) ||\ + defined(ARCHIVE_CRYPTO_SHA256_WIN) ||\ + defined(ARCHIVE_CRYPTO_SHA384_WIN) ||\ + defined(ARCHIVE_CRYPTO_SHA512_WIN) + +/* + * Initialize a Message digest. + */ +static int +win_crypto_init(Digest_CTX *ctx, ALG_ID algId) +{ + + ctx->valid = 0; + if (!CryptAcquireContext(&ctx->cryptProv, NULL, NULL, + PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { + if (GetLastError() != (DWORD)NTE_BAD_KEYSET) + return (ARCHIVE_FAILED); + if (!CryptAcquireContext(&ctx->cryptProv, NULL, NULL, + PROV_RSA_FULL, CRYPT_NEWKEYSET)) + return (ARCHIVE_FAILED); + } + + if (!CryptCreateHash(ctx->cryptProv, algId, 0, 0, &ctx->hash)) { + CryptReleaseContext(ctx->cryptProv, 0); + return (ARCHIVE_FAILED); + } + + ctx->valid = 1; + return (ARCHIVE_OK); +} + +/* + * Update a Message digest. + */ +static int +win_crypto_Update(Digest_CTX *ctx, const unsigned char *buf, size_t len) +{ + + if (!ctx->valid) + return (ARCHIVE_FAILED); + + CryptHashData(ctx->hash, + (unsigned char *)(uintptr_t)buf, + (DWORD)len, 0); + return (ARCHIVE_OK); +} + +static int +win_crypto_Final(unsigned char *buf, size_t bufsize, Digest_CTX *ctx) +{ + DWORD siglen = (DWORD)bufsize; + + if (!ctx->valid) + return (ARCHIVE_FAILED); + + CryptGetHashParam(ctx->hash, HP_HASHVAL, buf, &siglen, 0); + CryptDestroyHash(ctx->hash); + CryptReleaseContext(ctx->cryptProv, 0); + ctx->valid = 0; + return (ARCHIVE_OK); +} + +#endif /* defined(ARCHIVE_CRYPTO_*_WIN) */ + + +/* MD5 implementations */ +#if defined(ARCHIVE_CRYPTO_MD5_LIBC) + +static int +__archive_md5init(archive_md5_ctx *ctx) +{ + MD5Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_md5update(archive_md5_ctx *ctx, const void *indata, + size_t insize) +{ + MD5Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_md5final(archive_md5_ctx *ctx, void *md) +{ + MD5Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_MD5_LIBMD) + +static int +__archive_md5init(archive_md5_ctx *ctx) +{ + MD5Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_md5update(archive_md5_ctx *ctx, const void *indata, + size_t insize) +{ + MD5Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_md5final(archive_md5_ctx *ctx, void *md) +{ + MD5Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_MD5_LIBSYSTEM) + +static int +__archive_md5init(archive_md5_ctx *ctx) +{ + CC_MD5_Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_md5update(archive_md5_ctx *ctx, const void *indata, + size_t insize) +{ + CC_MD5_Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_md5final(archive_md5_ctx *ctx, void *md) +{ + CC_MD5_Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_MD5_MBEDTLS) + +static int +__archive_md5init(archive_md5_ctx *ctx) +{ + mbedtls_md5_init(ctx); + if (mbedtls_md5_starts_ret(ctx) == 0) + return (ARCHIVE_OK); + else + return (ARCHIVE_FATAL); +} + +static int +__archive_md5update(archive_md5_ctx *ctx, const void *indata, + size_t insize) +{ + if (mbedtls_md5_update_ret(ctx, indata, insize) == 0) + return (ARCHIVE_OK); + else + return (ARCHIVE_FATAL); +} + +static int +__archive_md5final(archive_md5_ctx *ctx, void *md) +{ + if (mbedtls_md5_finish_ret(ctx, md) == 0) { + mbedtls_md5_free(ctx); + return (ARCHIVE_OK); + } else { + mbedtls_md5_free(ctx); + return (ARCHIVE_FATAL); + } +} + +#elif defined(ARCHIVE_CRYPTO_MD5_NETTLE) + +static int +__archive_md5init(archive_md5_ctx *ctx) +{ + md5_init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_md5update(archive_md5_ctx *ctx, const void *indata, + size_t insize) +{ + md5_update(ctx, insize, indata); + return (ARCHIVE_OK); +} + +static int +__archive_md5final(archive_md5_ctx *ctx, void *md) +{ + md5_digest(ctx, MD5_DIGEST_SIZE, md); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_MD5_OPENSSL) + +static int +__archive_md5init(archive_md5_ctx *ctx) +{ + if ((*ctx = EVP_MD_CTX_new()) == NULL) + return (ARCHIVE_FAILED); + EVP_DigestInit(*ctx, EVP_md5()); + return (ARCHIVE_OK); +} + +static int +__archive_md5update(archive_md5_ctx *ctx, const void *indata, + size_t insize) +{ + EVP_DigestUpdate(*ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_md5final(archive_md5_ctx *ctx, void *md) +{ + /* HACK: archive_write_set_format_xar.c is finalizing empty contexts, so + * this is meant to cope with that. Real fix is probably to fix + * archive_write_set_format_xar.c + */ + if (*ctx) { + EVP_DigestFinal(*ctx, md, NULL); + EVP_MD_CTX_free(*ctx); + *ctx = NULL; + } + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_MD5_WIN) + +static int +__archive_md5init(archive_md5_ctx *ctx) +{ + return (win_crypto_init(ctx, CALG_MD5)); +} + +static int +__archive_md5update(archive_md5_ctx *ctx, const void *indata, + size_t insize) +{ + return (win_crypto_Update(ctx, indata, insize)); +} + +static int +__archive_md5final(archive_md5_ctx *ctx, void *md) +{ + return (win_crypto_Final(md, 16, ctx)); +} + +#else + +static int +__archive_md5init(archive_md5_ctx *ctx) +{ + (void)ctx; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +static int +__archive_md5update(archive_md5_ctx *ctx, const void *indata, + size_t insize) +{ + (void)ctx; /* UNUSED */ + (void)indata; /* UNUSED */ + (void)insize; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +static int +__archive_md5final(archive_md5_ctx *ctx, void *md) +{ + (void)ctx; /* UNUSED */ + (void)md; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +#endif + +/* RIPEMD160 implementations */ +#if defined(ARCHIVE_CRYPTO_RMD160_LIBC) + +static int +__archive_ripemd160init(archive_rmd160_ctx *ctx) +{ + RMD160Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_ripemd160update(archive_rmd160_ctx *ctx, const void *indata, + size_t insize) +{ + RMD160Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_ripemd160final(archive_rmd160_ctx *ctx, void *md) +{ + RMD160Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_RMD160_LIBMD) + +static int +__archive_ripemd160init(archive_rmd160_ctx *ctx) +{ + RIPEMD160_Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_ripemd160update(archive_rmd160_ctx *ctx, const void *indata, + size_t insize) +{ + RIPEMD160_Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_ripemd160final(archive_rmd160_ctx *ctx, void *md) +{ + RIPEMD160_Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_RMD160_MBEDTLS) + +static int +__archive_ripemd160init(archive_rmd160_ctx *ctx) +{ + mbedtls_ripemd160_init(ctx); + if (mbedtls_ripemd160_starts_ret(ctx) == 0) + return (ARCHIVE_OK); + else + return (ARCHIVE_FATAL); +} + +static int +__archive_ripemd160update(archive_rmd160_ctx *ctx, const void *indata, + size_t insize) +{ + if (mbedtls_ripemd160_update_ret(ctx, indata, insize) == 0) + return (ARCHIVE_OK); + else + return (ARCHIVE_FATAL); +} + +static int +__archive_ripemd160final(archive_rmd160_ctx *ctx, void *md) +{ + if (mbedtls_ripemd160_finish_ret(ctx, md) == 0) { + mbedtls_ripemd160_free(ctx); + return (ARCHIVE_OK); + } else { + mbedtls_ripemd160_free(ctx); + return (ARCHIVE_FATAL); + } +} + +#elif defined(ARCHIVE_CRYPTO_RMD160_NETTLE) + +static int +__archive_ripemd160init(archive_rmd160_ctx *ctx) +{ + ripemd160_init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_ripemd160update(archive_rmd160_ctx *ctx, const void *indata, + size_t insize) +{ + ripemd160_update(ctx, insize, indata); + return (ARCHIVE_OK); +} + +static int +__archive_ripemd160final(archive_rmd160_ctx *ctx, void *md) +{ + ripemd160_digest(ctx, RIPEMD160_DIGEST_SIZE, md); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_RMD160_OPENSSL) + +static int +__archive_ripemd160init(archive_rmd160_ctx *ctx) +{ + if ((*ctx = EVP_MD_CTX_new()) == NULL) + return (ARCHIVE_FAILED); + EVP_DigestInit(*ctx, EVP_ripemd160()); + return (ARCHIVE_OK); +} + +static int +__archive_ripemd160update(archive_rmd160_ctx *ctx, const void *indata, + size_t insize) +{ + EVP_DigestUpdate(*ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_ripemd160final(archive_rmd160_ctx *ctx, void *md) +{ + if (*ctx) { + EVP_DigestFinal(*ctx, md, NULL); + EVP_MD_CTX_free(*ctx); + *ctx = NULL; + } + return (ARCHIVE_OK); +} + +#else + +static int +__archive_ripemd160init(archive_rmd160_ctx *ctx) +{ + (void)ctx; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +static int +__archive_ripemd160update(archive_rmd160_ctx *ctx, const void *indata, + size_t insize) +{ + (void)ctx; /* UNUSED */ + (void)indata; /* UNUSED */ + (void)insize; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +static int +__archive_ripemd160final(archive_rmd160_ctx *ctx, void *md) +{ + (void)ctx; /* UNUSED */ + (void)md; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +#endif + +/* SHA1 implementations */ +#if defined(ARCHIVE_CRYPTO_SHA1_LIBC) + +static int +__archive_sha1init(archive_sha1_ctx *ctx) +{ + SHA1Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha1update(archive_sha1_ctx *ctx, const void *indata, + size_t insize) +{ + SHA1Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha1final(archive_sha1_ctx *ctx, void *md) +{ + SHA1Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA1_LIBMD) + +static int +__archive_sha1init(archive_sha1_ctx *ctx) +{ + SHA1_Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha1update(archive_sha1_ctx *ctx, const void *indata, + size_t insize) +{ + SHA1_Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha1final(archive_sha1_ctx *ctx, void *md) +{ + SHA1_Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA1_LIBSYSTEM) + +static int +__archive_sha1init(archive_sha1_ctx *ctx) +{ + CC_SHA1_Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha1update(archive_sha1_ctx *ctx, const void *indata, + size_t insize) +{ + CC_SHA1_Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha1final(archive_sha1_ctx *ctx, void *md) +{ + CC_SHA1_Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA1_MBEDTLS) + +static int +__archive_sha1init(archive_sha1_ctx *ctx) +{ + mbedtls_sha1_init(ctx); + if (mbedtls_sha1_starts_ret(ctx) == 0) + return (ARCHIVE_OK); + else + return (ARCHIVE_FATAL); +} + +static int +__archive_sha1update(archive_sha1_ctx *ctx, const void *indata, + size_t insize) +{ + if (mbedtls_sha1_update_ret(ctx, indata, insize) == 0) + return (ARCHIVE_OK); + else + return (ARCHIVE_FATAL); +} + +static int +__archive_sha1final(archive_sha1_ctx *ctx, void *md) +{ + if (mbedtls_sha1_finish_ret(ctx, md) == 0) { + mbedtls_sha1_free(ctx); + return (ARCHIVE_OK); + } else { + mbedtls_sha1_free(ctx); + return (ARCHIVE_FATAL); + } +} + +#elif defined(ARCHIVE_CRYPTO_SHA1_NETTLE) + +static int +__archive_sha1init(archive_sha1_ctx *ctx) +{ + sha1_init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha1update(archive_sha1_ctx *ctx, const void *indata, + size_t insize) +{ + sha1_update(ctx, insize, indata); + return (ARCHIVE_OK); +} + +static int +__archive_sha1final(archive_sha1_ctx *ctx, void *md) +{ + sha1_digest(ctx, SHA1_DIGEST_SIZE, md); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA1_OPENSSL) + +static int +__archive_sha1init(archive_sha1_ctx *ctx) +{ + if ((*ctx = EVP_MD_CTX_new()) == NULL) + return (ARCHIVE_FAILED); + EVP_DigestInit(*ctx, EVP_sha1()); + return (ARCHIVE_OK); +} + +static int +__archive_sha1update(archive_sha1_ctx *ctx, const void *indata, + size_t insize) +{ + EVP_DigestUpdate(*ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha1final(archive_sha1_ctx *ctx, void *md) +{ + /* HACK: archive_write_set_format_xar.c is finalizing empty contexts, so + * this is meant to cope with that. Real fix is probably to fix + * archive_write_set_format_xar.c + */ + if (*ctx) { + EVP_DigestFinal(*ctx, md, NULL); + EVP_MD_CTX_free(*ctx); + *ctx = NULL; + } + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA1_WIN) + +static int +__archive_sha1init(archive_sha1_ctx *ctx) +{ + return (win_crypto_init(ctx, CALG_SHA1)); +} + +static int +__archive_sha1update(archive_sha1_ctx *ctx, const void *indata, + size_t insize) +{ + return (win_crypto_Update(ctx, indata, insize)); +} + +static int +__archive_sha1final(archive_sha1_ctx *ctx, void *md) +{ + return (win_crypto_Final(md, 20, ctx)); +} + +#else + +static int +__archive_sha1init(archive_sha1_ctx *ctx) +{ + (void)ctx; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +static int +__archive_sha1update(archive_sha1_ctx *ctx, const void *indata, + size_t insize) +{ + (void)ctx; /* UNUSED */ + (void)indata; /* UNUSED */ + (void)insize; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +static int +__archive_sha1final(archive_sha1_ctx *ctx, void *md) +{ + (void)ctx; /* UNUSED */ + (void)md; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +#endif + +/* SHA256 implementations */ +#if defined(ARCHIVE_CRYPTO_SHA256_LIBC) + +static int +__archive_sha256init(archive_sha256_ctx *ctx) +{ + SHA256_Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha256update(archive_sha256_ctx *ctx, const void *indata, + size_t insize) +{ + SHA256_Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha256final(archive_sha256_ctx *ctx, void *md) +{ + SHA256_Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA256_LIBC2) + +static int +__archive_sha256init(archive_sha256_ctx *ctx) +{ + SHA256Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha256update(archive_sha256_ctx *ctx, const void *indata, + size_t insize) +{ + SHA256Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha256final(archive_sha256_ctx *ctx, void *md) +{ + SHA256Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA256_LIBC3) + +static int +__archive_sha256init(archive_sha256_ctx *ctx) +{ + SHA256Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha256update(archive_sha256_ctx *ctx, const void *indata, + size_t insize) +{ + SHA256Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha256final(archive_sha256_ctx *ctx, void *md) +{ + SHA256Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA256_LIBMD) + +static int +__archive_sha256init(archive_sha256_ctx *ctx) +{ + SHA256_Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha256update(archive_sha256_ctx *ctx, const void *indata, + size_t insize) +{ + SHA256_Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha256final(archive_sha256_ctx *ctx, void *md) +{ + SHA256_Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA256_LIBSYSTEM) + +static int +__archive_sha256init(archive_sha256_ctx *ctx) +{ + CC_SHA256_Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha256update(archive_sha256_ctx *ctx, const void *indata, + size_t insize) +{ + CC_SHA256_Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha256final(archive_sha256_ctx *ctx, void *md) +{ + CC_SHA256_Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA256_MBEDTLS) + +static int +__archive_sha256init(archive_sha256_ctx *ctx) +{ + mbedtls_sha256_init(ctx); + if (mbedtls_sha256_starts_ret(ctx, 0) == 0) + return (ARCHIVE_OK); + else + return (ARCHIVE_FATAL); +} + +static int +__archive_sha256update(archive_sha256_ctx *ctx, const void *indata, + size_t insize) +{ + if (mbedtls_sha256_update_ret(ctx, indata, insize) == 0) + return (ARCHIVE_OK); + else + return (ARCHIVE_FATAL); +} + +static int +__archive_sha256final(archive_sha256_ctx *ctx, void *md) +{ + if (mbedtls_sha256_finish_ret(ctx, md) == 0) { + mbedtls_sha256_free(ctx); + return (ARCHIVE_OK); + } else { + mbedtls_sha256_free(ctx); + return (ARCHIVE_FATAL); + } +} + +#elif defined(ARCHIVE_CRYPTO_SHA256_NETTLE) + +static int +__archive_sha256init(archive_sha256_ctx *ctx) +{ + sha256_init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha256update(archive_sha256_ctx *ctx, const void *indata, + size_t insize) +{ + sha256_update(ctx, insize, indata); + return (ARCHIVE_OK); +} + +static int +__archive_sha256final(archive_sha256_ctx *ctx, void *md) +{ + sha256_digest(ctx, SHA256_DIGEST_SIZE, md); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA256_OPENSSL) + +static int +__archive_sha256init(archive_sha256_ctx *ctx) +{ + if ((*ctx = EVP_MD_CTX_new()) == NULL) + return (ARCHIVE_FAILED); + EVP_DigestInit(*ctx, EVP_sha256()); + return (ARCHIVE_OK); +} + +static int +__archive_sha256update(archive_sha256_ctx *ctx, const void *indata, + size_t insize) +{ + EVP_DigestUpdate(*ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha256final(archive_sha256_ctx *ctx, void *md) +{ + if (*ctx) { + EVP_DigestFinal(*ctx, md, NULL); + EVP_MD_CTX_free(*ctx); + *ctx = NULL; + } + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA256_WIN) + +static int +__archive_sha256init(archive_sha256_ctx *ctx) +{ + return (win_crypto_init(ctx, CALG_SHA_256)); +} + +static int +__archive_sha256update(archive_sha256_ctx *ctx, const void *indata, + size_t insize) +{ + return (win_crypto_Update(ctx, indata, insize)); +} + +static int +__archive_sha256final(archive_sha256_ctx *ctx, void *md) +{ + return (win_crypto_Final(md, 32, ctx)); +} + +#else + +static int +__archive_sha256init(archive_sha256_ctx *ctx) +{ + (void)ctx; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +static int +__archive_sha256update(archive_sha256_ctx *ctx, const void *indata, + size_t insize) +{ + (void)ctx; /* UNUSED */ + (void)indata; /* UNUSED */ + (void)insize; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +static int +__archive_sha256final(archive_sha256_ctx *ctx, void *md) +{ + (void)ctx; /* UNUSED */ + (void)md; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +#endif + +/* SHA384 implementations */ +#if defined(ARCHIVE_CRYPTO_SHA384_LIBC) + +static int +__archive_sha384init(archive_sha384_ctx *ctx) +{ + SHA384_Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha384update(archive_sha384_ctx *ctx, const void *indata, + size_t insize) +{ + SHA384_Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha384final(archive_sha384_ctx *ctx, void *md) +{ + SHA384_Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA384_LIBC2) + +static int +__archive_sha384init(archive_sha384_ctx *ctx) +{ + SHA384Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha384update(archive_sha384_ctx *ctx, const void *indata, + size_t insize) +{ + SHA384Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha384final(archive_sha384_ctx *ctx, void *md) +{ + SHA384Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA384_LIBC3) + +static int +__archive_sha384init(archive_sha384_ctx *ctx) +{ + SHA384Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha384update(archive_sha384_ctx *ctx, const void *indata, + size_t insize) +{ + SHA384Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha384final(archive_sha384_ctx *ctx, void *md) +{ + SHA384Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA384_LIBSYSTEM) + +static int +__archive_sha384init(archive_sha384_ctx *ctx) +{ + CC_SHA384_Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha384update(archive_sha384_ctx *ctx, const void *indata, + size_t insize) +{ + CC_SHA384_Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha384final(archive_sha384_ctx *ctx, void *md) +{ + CC_SHA384_Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA384_MBEDTLS) + +static int +__archive_sha384init(archive_sha384_ctx *ctx) +{ + mbedtls_sha512_init(ctx); + if (mbedtls_sha512_starts_ret(ctx, 1) == 0) + return (ARCHIVE_OK); + else + return (ARCHIVE_FATAL); +} + +static int +__archive_sha384update(archive_sha384_ctx *ctx, const void *indata, + size_t insize) +{ + if (mbedtls_sha512_update_ret(ctx, indata, insize) == 0) + return (ARCHIVE_OK); + else + return (ARCHIVE_FATAL); +} + +static int +__archive_sha384final(archive_sha384_ctx *ctx, void *md) +{ + if (mbedtls_sha512_finish_ret(ctx, md) == 0) { + mbedtls_sha512_free(ctx); + return (ARCHIVE_OK); + } else { + mbedtls_sha512_free(ctx); + return (ARCHIVE_FATAL); + } +} + +#elif defined(ARCHIVE_CRYPTO_SHA384_NETTLE) + +static int +__archive_sha384init(archive_sha384_ctx *ctx) +{ + sha384_init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha384update(archive_sha384_ctx *ctx, const void *indata, + size_t insize) +{ + sha384_update(ctx, insize, indata); + return (ARCHIVE_OK); +} + +static int +__archive_sha384final(archive_sha384_ctx *ctx, void *md) +{ + sha384_digest(ctx, SHA384_DIGEST_SIZE, md); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA384_OPENSSL) + +static int +__archive_sha384init(archive_sha384_ctx *ctx) +{ + if ((*ctx = EVP_MD_CTX_new()) == NULL) + return (ARCHIVE_FAILED); + EVP_DigestInit(*ctx, EVP_sha384()); + return (ARCHIVE_OK); +} + +static int +__archive_sha384update(archive_sha384_ctx *ctx, const void *indata, + size_t insize) +{ + EVP_DigestUpdate(*ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha384final(archive_sha384_ctx *ctx, void *md) +{ + if (*ctx) { + EVP_DigestFinal(*ctx, md, NULL); + EVP_MD_CTX_free(*ctx); + *ctx = NULL; + } + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA384_WIN) + +static int +__archive_sha384init(archive_sha384_ctx *ctx) +{ + return (win_crypto_init(ctx, CALG_SHA_384)); +} + +static int +__archive_sha384update(archive_sha384_ctx *ctx, const void *indata, + size_t insize) +{ + return (win_crypto_Update(ctx, indata, insize)); +} + +static int +__archive_sha384final(archive_sha384_ctx *ctx, void *md) +{ + return (win_crypto_Final(md, 48, ctx)); +} + +#else + +static int +__archive_sha384init(archive_sha384_ctx *ctx) +{ + (void)ctx; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +static int +__archive_sha384update(archive_sha384_ctx *ctx, const void *indata, + size_t insize) +{ + (void)ctx; /* UNUSED */ + (void)indata; /* UNUSED */ + (void)insize; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +static int +__archive_sha384final(archive_sha384_ctx *ctx, void *md) +{ + (void)ctx; /* UNUSED */ + (void)md; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +#endif + +/* SHA512 implementations */ +#if defined(ARCHIVE_CRYPTO_SHA512_LIBC) + +static int +__archive_sha512init(archive_sha512_ctx *ctx) +{ + SHA512_Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha512update(archive_sha512_ctx *ctx, const void *indata, + size_t insize) +{ + SHA512_Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha512final(archive_sha512_ctx *ctx, void *md) +{ + SHA512_Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA512_LIBC2) + +static int +__archive_sha512init(archive_sha512_ctx *ctx) +{ + SHA512Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha512update(archive_sha512_ctx *ctx, const void *indata, + size_t insize) +{ + SHA512Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha512final(archive_sha512_ctx *ctx, void *md) +{ + SHA512Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA512_LIBC3) + +static int +__archive_sha512init(archive_sha512_ctx *ctx) +{ + SHA512Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha512update(archive_sha512_ctx *ctx, const void *indata, + size_t insize) +{ + SHA512Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha512final(archive_sha512_ctx *ctx, void *md) +{ + SHA512Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA512_LIBMD) + +static int +__archive_sha512init(archive_sha512_ctx *ctx) +{ + SHA512_Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha512update(archive_sha512_ctx *ctx, const void *indata, + size_t insize) +{ + SHA512_Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha512final(archive_sha512_ctx *ctx, void *md) +{ + SHA512_Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA512_LIBSYSTEM) + +static int +__archive_sha512init(archive_sha512_ctx *ctx) +{ + CC_SHA512_Init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha512update(archive_sha512_ctx *ctx, const void *indata, + size_t insize) +{ + CC_SHA512_Update(ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha512final(archive_sha512_ctx *ctx, void *md) +{ + CC_SHA512_Final(md, ctx); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA512_MBEDTLS) + +static int +__archive_sha512init(archive_sha512_ctx *ctx) +{ + mbedtls_sha512_init(ctx); + if (mbedtls_sha512_starts_ret(ctx, 0) == 0) + return (ARCHIVE_OK); + else + return (ARCHIVE_FATAL); +} + +static int +__archive_sha512update(archive_sha512_ctx *ctx, const void *indata, + size_t insize) +{ + if (mbedtls_sha512_update_ret(ctx, indata, insize) == 0) + return (ARCHIVE_OK); + else + return (ARCHIVE_FATAL); +} + +static int +__archive_sha512final(archive_sha512_ctx *ctx, void *md) +{ + if (mbedtls_sha512_finish_ret(ctx, md) == 0) { + mbedtls_sha512_free(ctx); + return (ARCHIVE_OK); + } else { + mbedtls_sha512_free(ctx); + return (ARCHIVE_FATAL); + } +} + +#elif defined(ARCHIVE_CRYPTO_SHA512_NETTLE) + +static int +__archive_sha512init(archive_sha512_ctx *ctx) +{ + sha512_init(ctx); + return (ARCHIVE_OK); +} + +static int +__archive_sha512update(archive_sha512_ctx *ctx, const void *indata, + size_t insize) +{ + sha512_update(ctx, insize, indata); + return (ARCHIVE_OK); +} + +static int +__archive_sha512final(archive_sha512_ctx *ctx, void *md) +{ + sha512_digest(ctx, SHA512_DIGEST_SIZE, md); + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA512_OPENSSL) + +static int +__archive_sha512init(archive_sha512_ctx *ctx) +{ + if ((*ctx = EVP_MD_CTX_new()) == NULL) + return (ARCHIVE_FAILED); + EVP_DigestInit(*ctx, EVP_sha512()); + return (ARCHIVE_OK); +} + +static int +__archive_sha512update(archive_sha512_ctx *ctx, const void *indata, + size_t insize) +{ + EVP_DigestUpdate(*ctx, indata, insize); + return (ARCHIVE_OK); +} + +static int +__archive_sha512final(archive_sha512_ctx *ctx, void *md) +{ + if (*ctx) { + EVP_DigestFinal(*ctx, md, NULL); + EVP_MD_CTX_free(*ctx); + *ctx = NULL; + } + return (ARCHIVE_OK); +} + +#elif defined(ARCHIVE_CRYPTO_SHA512_WIN) + +static int +__archive_sha512init(archive_sha512_ctx *ctx) +{ + return (win_crypto_init(ctx, CALG_SHA_512)); +} + +static int +__archive_sha512update(archive_sha512_ctx *ctx, const void *indata, + size_t insize) +{ + return (win_crypto_Update(ctx, indata, insize)); +} + +static int +__archive_sha512final(archive_sha512_ctx *ctx, void *md) +{ + return (win_crypto_Final(md, 64, ctx)); +} + +#else + +static int +__archive_sha512init(archive_sha512_ctx *ctx) +{ + (void)ctx; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +static int +__archive_sha512update(archive_sha512_ctx *ctx, const void *indata, + size_t insize) +{ + (void)ctx; /* UNUSED */ + (void)indata; /* UNUSED */ + (void)insize; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +static int +__archive_sha512final(archive_sha512_ctx *ctx, void *md) +{ + (void)ctx; /* UNUSED */ + (void)md; /* UNUSED */ + return (ARCHIVE_FAILED); +} + +#endif + +/* NOTE: Message Digest functions are set based on availability and by the + * following order of preference. + * 1. libc + * 2. libc2 + * 3. libc3 + * 4. libSystem + * 5. Nettle + * 6. OpenSSL + * 7. libmd + * 8. Windows API + */ +const struct archive_digest __archive_digest = +{ +/* MD5 */ + &__archive_md5init, + &__archive_md5update, + &__archive_md5final, + +/* RIPEMD160 */ + &__archive_ripemd160init, + &__archive_ripemd160update, + &__archive_ripemd160final, + +/* SHA1 */ + &__archive_sha1init, + &__archive_sha1update, + &__archive_sha1final, + +/* SHA256 */ + &__archive_sha256init, + &__archive_sha256update, + &__archive_sha256final, + +/* SHA384 */ + &__archive_sha384init, + &__archive_sha384update, + &__archive_sha384final, + +/* SHA512 */ + &__archive_sha512init, + &__archive_sha512update, + &__archive_sha512final +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_digest_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_digest_private.h new file mode 100644 index 0000000000..15312ee9a0 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_digest_private.h @@ -0,0 +1,412 @@ +/*- +* Copyright (c) 2003-2007 Tim Kientzle +* Copyright (c) 2011 Andres Mejia +* 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(S) ``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(S) 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. +*/ + +#ifndef ARCHIVE_DIGEST_PRIVATE_H_INCLUDED +#define ARCHIVE_DIGEST_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif +/* + * Crypto support in various Operating Systems: + * + * NetBSD: + * - MD5 and SHA1 in libc: without _ after algorithm name + * - SHA2 in libc: with _ after algorithm name + * + * OpenBSD: + * - MD5, SHA1 and SHA2 in libc: without _ after algorithm name + * - OpenBSD 4.4 and earlier have SHA2 in libc with _ after algorithm name + * + * DragonFly and FreeBSD: + * - MD5 libmd: without _ after algorithm name + * - SHA1, SHA256 and SHA512 in libmd: with _ after algorithm name + * + * Mac OS X (10.4 and later): + * - MD5, SHA1 and SHA2 in libSystem: with CC_ prefix and _ after algorithm name + * + * OpenSSL: + * - MD5, SHA1 and SHA2 in libcrypto: with _ after algorithm name + * + * Windows: + * - MD5, SHA1 and SHA2 in archive_crypto.c using Windows crypto API + */ + +/* libc crypto headers */ +#if defined(ARCHIVE_CRYPTO_MD5_LIBC) +#include <md5.h> +#endif +#if defined(ARCHIVE_CRYPTO_RMD160_LIBC) +#include <rmd160.h> +#endif +#if defined(ARCHIVE_CRYPTO_SHA1_LIBC) +#include <sha1.h> +#endif +#if defined(ARCHIVE_CRYPTO_SHA256_LIBC) ||\ + defined(ARCHIVE_CRYPTO_SHA256_LIBC2) ||\ + defined(ARCHIVE_CRYPTO_SHA256_LIBC3) ||\ + defined(ARCHIVE_CRYPTO_SHA384_LIBC) ||\ + defined(ARCHIVE_CRYPTO_SHA384_LIBC2) ||\ + defined(ARCHIVE_CRYPTO_SHA384_LIBC3) ||\ + defined(ARCHIVE_CRYPTO_SHA512_LIBC) ||\ + defined(ARCHIVE_CRYPTO_SHA512_LIBC2) ||\ + defined(ARCHIVE_CRYPTO_SHA512_LIBC3) +#include <sha2.h> +#endif + +/* libmd crypto headers */ +#if defined(ARCHIVE_CRYPTO_MD5_LIBMD) ||\ + defined(ARCHIVE_CRYPTO_RMD160_LIBMD) ||\ + defined(ARCHIVE_CRYPTO_SHA1_LIBMD) ||\ + defined(ARCHIVE_CRYPTO_SHA256_LIBMD) ||\ + defined(ARCHIVE_CRYPTO_SHA512_LIBMD) +#define ARCHIVE_CRYPTO_LIBMD 1 +#endif + +#if defined(ARCHIVE_CRYPTO_MD5_LIBMD) +#include <md5.h> +#endif +#if defined(ARCHIVE_CRYPTO_RMD160_LIBMD) +#include <ripemd.h> +#endif +#if defined(ARCHIVE_CRYPTO_SHA1_LIBMD) +#include <sha.h> +#endif +#if defined(ARCHIVE_CRYPTO_SHA256_LIBMD) +#include <sha256.h> +#endif +#if defined(ARCHIVE_CRYPTO_SHA512_LIBMD) +#include <sha512.h> +#endif + +/* libSystem crypto headers */ +#if defined(ARCHIVE_CRYPTO_MD5_LIBSYSTEM) ||\ + defined(ARCHIVE_CRYPTO_SHA1_LIBSYSTEM) ||\ + defined(ARCHIVE_CRYPTO_SHA256_LIBSYSTEM) ||\ + defined(ARCHIVE_CRYPTO_SHA384_LIBSYSTEM) ||\ + defined(ARCHIVE_CRYPTO_SHA512_LIBSYSTEM) +#include <CommonCrypto/CommonDigest.h> +#endif + +/* mbed TLS crypto headers */ +#if defined(ARCHIVE_CRYPTO_MD5_MBEDTLS) +#include <mbedtls/md5.h> +#endif +#if defined(ARCHIVE_CRYPTO_RMD160_MBEDTLS) +#include <mbedtls/ripemd160.h> +#endif +#if defined(ARCHIVE_CRYPTO_SHA1_MBEDTLS) +#include <mbedtls/sha1.h> +#endif +#if defined(ARCHIVE_CRYPTO_SHA256_MBEDTLS) +#include <mbedtls/sha256.h> +#endif +#if defined(ARCHIVE_CRYPTO_SHA384_MBEDTLS) ||\ + defined(ARCHIVE_CRYPTO_SHA512_MBEDTLS) +#include <mbedtls/sha512.h> +#endif + +/* Nettle crypto headers */ +#if defined(ARCHIVE_CRYPTO_MD5_NETTLE) +#include <nettle/md5.h> +#endif +#if defined(ARCHIVE_CRYPTO_RMD160_NETTLE) +#include <nettle/ripemd160.h> +#endif +#if defined(ARCHIVE_CRYPTO_SHA1_NETTLE) ||\ + defined(ARCHIVE_CRYPTO_SHA256_NETTLE) ||\ + defined(ARCHIVE_CRYPTO_SHA384_NETTLE) ||\ + defined(ARCHIVE_CRYPTO_SHA512_NETTLE) +#include <nettle/sha.h> +#endif + +/* OpenSSL crypto headers */ +#if defined(ARCHIVE_CRYPTO_MD5_OPENSSL) ||\ + defined(ARCHIVE_CRYPTO_RMD160_OPENSSL) ||\ + defined(ARCHIVE_CRYPTO_SHA1_OPENSSL) ||\ + defined(ARCHIVE_CRYPTO_SHA256_OPENSSL) ||\ + defined(ARCHIVE_CRYPTO_SHA384_OPENSSL) ||\ + defined(ARCHIVE_CRYPTO_SHA512_OPENSSL) +#define ARCHIVE_CRYPTO_OPENSSL 1 +#include "archive_openssl_evp_private.h" +#endif + +/* Windows crypto headers */ +#if defined(ARCHIVE_CRYPTO_MD5_WIN) ||\ + defined(ARCHIVE_CRYPTO_SHA1_WIN) ||\ + defined(ARCHIVE_CRYPTO_SHA256_WIN) ||\ + defined(ARCHIVE_CRYPTO_SHA384_WIN) ||\ + defined(ARCHIVE_CRYPTO_SHA512_WIN) +#include <windows.h> +#include <wincrypt.h> +typedef struct { + int valid; + HCRYPTPROV cryptProv; + HCRYPTHASH hash; +} Digest_CTX; +#endif + +/* typedefs */ +#if defined(ARCHIVE_CRYPTO_MD5_LIBC) +typedef MD5_CTX archive_md5_ctx; +#elif defined(ARCHIVE_CRYPTO_MD5_LIBMD) +typedef MD5_CTX archive_md5_ctx; +#elif defined(ARCHIVE_CRYPTO_MD5_LIBSYSTEM) +typedef CC_MD5_CTX archive_md5_ctx; +#elif defined(ARCHIVE_CRYPTO_MD5_MBEDTLS) +typedef mbedtls_md5_context archive_md5_ctx; +#elif defined(ARCHIVE_CRYPTO_MD5_NETTLE) +typedef struct md5_ctx archive_md5_ctx; +#elif defined(ARCHIVE_CRYPTO_MD5_OPENSSL) +typedef EVP_MD_CTX *archive_md5_ctx; +#elif defined(ARCHIVE_CRYPTO_MD5_WIN) +typedef Digest_CTX archive_md5_ctx; +#else +typedef unsigned char archive_md5_ctx; +#endif + +#if defined(ARCHIVE_CRYPTO_RMD160_LIBC) +typedef RMD160_CTX archive_rmd160_ctx; +#elif defined(ARCHIVE_CRYPTO_RMD160_LIBMD) +typedef RIPEMD160_CTX archive_rmd160_ctx; +#elif defined(ARCHIVE_CRYPTO_RMD160_MBEDTLS) +typedef mbedtls_ripemd160_context archive_rmd160_ctx; +#elif defined(ARCHIVE_CRYPTO_RMD160_NETTLE) +typedef struct ripemd160_ctx archive_rmd160_ctx; +#elif defined(ARCHIVE_CRYPTO_RMD160_OPENSSL) +typedef EVP_MD_CTX *archive_rmd160_ctx; +#else +typedef unsigned char archive_rmd160_ctx; +#endif + +#if defined(ARCHIVE_CRYPTO_SHA1_LIBC) +typedef SHA1_CTX archive_sha1_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA1_LIBMD) +typedef SHA1_CTX archive_sha1_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA1_LIBSYSTEM) +typedef CC_SHA1_CTX archive_sha1_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA1_MBEDTLS) +typedef mbedtls_sha1_context archive_sha1_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA1_NETTLE) +typedef struct sha1_ctx archive_sha1_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA1_OPENSSL) +typedef EVP_MD_CTX *archive_sha1_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA1_WIN) +typedef Digest_CTX archive_sha1_ctx; +#else +typedef unsigned char archive_sha1_ctx; +#endif + +#if defined(ARCHIVE_CRYPTO_SHA256_LIBC) +typedef SHA256_CTX archive_sha256_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA256_LIBC2) +typedef SHA256_CTX archive_sha256_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA256_LIBC3) +typedef SHA2_CTX archive_sha256_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA256_LIBMD) +typedef SHA256_CTX archive_sha256_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA256_LIBSYSTEM) +typedef CC_SHA256_CTX archive_sha256_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA256_MBEDTLS) +typedef mbedtls_sha256_context archive_sha256_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA256_NETTLE) +typedef struct sha256_ctx archive_sha256_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA256_OPENSSL) +typedef EVP_MD_CTX *archive_sha256_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA256_WIN) +typedef Digest_CTX archive_sha256_ctx; +#else +typedef unsigned char archive_sha256_ctx; +#endif + +#if defined(ARCHIVE_CRYPTO_SHA384_LIBC) +typedef SHA384_CTX archive_sha384_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA384_LIBC2) +typedef SHA384_CTX archive_sha384_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA384_LIBC3) +typedef SHA2_CTX archive_sha384_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA384_LIBSYSTEM) +typedef CC_SHA512_CTX archive_sha384_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA384_MBEDTLS) +typedef mbedtls_sha512_context archive_sha384_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA384_NETTLE) +typedef struct sha384_ctx archive_sha384_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA384_OPENSSL) +typedef EVP_MD_CTX *archive_sha384_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA384_WIN) +typedef Digest_CTX archive_sha384_ctx; +#else +typedef unsigned char archive_sha384_ctx; +#endif + +#if defined(ARCHIVE_CRYPTO_SHA512_LIBC) +typedef SHA512_CTX archive_sha512_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA512_LIBC2) +typedef SHA512_CTX archive_sha512_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA512_LIBC3) +typedef SHA2_CTX archive_sha512_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA512_LIBMD) +typedef SHA512_CTX archive_sha512_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA512_LIBSYSTEM) +typedef CC_SHA512_CTX archive_sha512_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA512_MBEDTLS) +typedef mbedtls_sha512_context archive_sha512_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA512_NETTLE) +typedef struct sha512_ctx archive_sha512_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA512_OPENSSL) +typedef EVP_MD_CTX *archive_sha512_ctx; +#elif defined(ARCHIVE_CRYPTO_SHA512_WIN) +typedef Digest_CTX archive_sha512_ctx; +#else +typedef unsigned char archive_sha512_ctx; +#endif + +/* defines */ +#if defined(ARCHIVE_CRYPTO_MD5_LIBC) ||\ + defined(ARCHIVE_CRYPTO_MD5_LIBMD) || \ + defined(ARCHIVE_CRYPTO_MD5_LIBSYSTEM) ||\ + defined(ARCHIVE_CRYPTO_MD5_MBEDTLS) ||\ + defined(ARCHIVE_CRYPTO_MD5_NETTLE) ||\ + defined(ARCHIVE_CRYPTO_MD5_OPENSSL) ||\ + defined(ARCHIVE_CRYPTO_MD5_WIN) +#define ARCHIVE_HAS_MD5 +#endif +#define archive_md5_init(ctx)\ + __archive_digest.md5init(ctx) +#define archive_md5_final(ctx, md)\ + __archive_digest.md5final(ctx, md) +#define archive_md5_update(ctx, buf, n)\ + __archive_digest.md5update(ctx, buf, n) + +#if defined(ARCHIVE_CRYPTO_RMD160_LIBC) ||\ + defined(ARCHIVE_CRYPTO_RMD160_MBEDTLS) ||\ + defined(ARCHIVE_CRYPTO_RMD160_NETTLE) ||\ + defined(ARCHIVE_CRYPTO_RMD160_OPENSSL) +#define ARCHIVE_HAS_RMD160 +#endif +#define archive_rmd160_init(ctx)\ + __archive_digest.rmd160init(ctx) +#define archive_rmd160_final(ctx, md)\ + __archive_digest.rmd160final(ctx, md) +#define archive_rmd160_update(ctx, buf, n)\ + __archive_digest.rmd160update(ctx, buf, n) + +#if defined(ARCHIVE_CRYPTO_SHA1_LIBC) ||\ + defined(ARCHIVE_CRYPTO_SHA1_LIBMD) || \ + defined(ARCHIVE_CRYPTO_SHA1_LIBSYSTEM) ||\ + defined(ARCHIVE_CRYPTO_SHA1_MBEDTLS) ||\ + defined(ARCHIVE_CRYPTO_SHA1_NETTLE) ||\ + defined(ARCHIVE_CRYPTO_SHA1_OPENSSL) ||\ + defined(ARCHIVE_CRYPTO_SHA1_WIN) +#define ARCHIVE_HAS_SHA1 +#endif +#define archive_sha1_init(ctx)\ + __archive_digest.sha1init(ctx) +#define archive_sha1_final(ctx, md)\ + __archive_digest.sha1final(ctx, md) +#define archive_sha1_update(ctx, buf, n)\ + __archive_digest.sha1update(ctx, buf, n) + +#if defined(ARCHIVE_CRYPTO_SHA256_LIBC) ||\ + defined(ARCHIVE_CRYPTO_SHA256_LIBC2) ||\ + defined(ARCHIVE_CRYPTO_SHA256_LIBC3) ||\ + defined(ARCHIVE_CRYPTO_SHA256_LIBMD) ||\ + defined(ARCHIVE_CRYPTO_SHA256_LIBSYSTEM) ||\ + defined(ARCHIVE_CRYPTO_SHA256_MBEDTLS) ||\ + defined(ARCHIVE_CRYPTO_SHA256_NETTLE) ||\ + defined(ARCHIVE_CRYPTO_SHA256_OPENSSL) ||\ + defined(ARCHIVE_CRYPTO_SHA256_WIN) +#define ARCHIVE_HAS_SHA256 +#endif +#define archive_sha256_init(ctx)\ + __archive_digest.sha256init(ctx) +#define archive_sha256_final(ctx, md)\ + __archive_digest.sha256final(ctx, md) +#define archive_sha256_update(ctx, buf, n)\ + __archive_digest.sha256update(ctx, buf, n) + +#if defined(ARCHIVE_CRYPTO_SHA384_LIBC) ||\ + defined(ARCHIVE_CRYPTO_SHA384_LIBC2) ||\ + defined(ARCHIVE_CRYPTO_SHA384_LIBC3) ||\ + defined(ARCHIVE_CRYPTO_SHA384_LIBSYSTEM) ||\ + defined(ARCHIVE_CRYPTO_SHA384_MBEDTLS) ||\ + defined(ARCHIVE_CRYPTO_SHA384_NETTLE) ||\ + defined(ARCHIVE_CRYPTO_SHA384_OPENSSL) ||\ + defined(ARCHIVE_CRYPTO_SHA384_WIN) +#define ARCHIVE_HAS_SHA384 +#endif +#define archive_sha384_init(ctx)\ + __archive_digest.sha384init(ctx) +#define archive_sha384_final(ctx, md)\ + __archive_digest.sha384final(ctx, md) +#define archive_sha384_update(ctx, buf, n)\ + __archive_digest.sha384update(ctx, buf, n) + +#if defined(ARCHIVE_CRYPTO_SHA512_LIBC) ||\ + defined(ARCHIVE_CRYPTO_SHA512_LIBC2) ||\ + defined(ARCHIVE_CRYPTO_SHA512_LIBC3) ||\ + defined(ARCHIVE_CRYPTO_SHA512_LIBMD) ||\ + defined(ARCHIVE_CRYPTO_SHA512_LIBSYSTEM) ||\ + defined(ARCHIVE_CRYPTO_SHA512_MBEDTLS) ||\ + defined(ARCHIVE_CRYPTO_SHA512_NETTLE) ||\ + defined(ARCHIVE_CRYPTO_SHA512_OPENSSL) ||\ + defined(ARCHIVE_CRYPTO_SHA512_WIN) +#define ARCHIVE_HAS_SHA512 +#endif +#define archive_sha512_init(ctx)\ + __archive_digest.sha512init(ctx) +#define archive_sha512_final(ctx, md)\ + __archive_digest.sha512final(ctx, md) +#define archive_sha512_update(ctx, buf, n)\ + __archive_digest.sha512update(ctx, buf, n) + +/* Minimal interface to digest functionality for internal use in libarchive */ +struct archive_digest +{ + /* Message Digest */ + int (*md5init)(archive_md5_ctx *ctx); + int (*md5update)(archive_md5_ctx *, const void *, size_t); + int (*md5final)(archive_md5_ctx *, void *); + int (*rmd160init)(archive_rmd160_ctx *); + int (*rmd160update)(archive_rmd160_ctx *, const void *, size_t); + int (*rmd160final)(archive_rmd160_ctx *, void *); + int (*sha1init)(archive_sha1_ctx *); + int (*sha1update)(archive_sha1_ctx *, const void *, size_t); + int (*sha1final)(archive_sha1_ctx *, void *); + int (*sha256init)(archive_sha256_ctx *); + int (*sha256update)(archive_sha256_ctx *, const void *, size_t); + int (*sha256final)(archive_sha256_ctx *, void *); + int (*sha384init)(archive_sha384_ctx *); + int (*sha384update)(archive_sha384_ctx *, const void *, size_t); + int (*sha384final)(archive_sha384_ctx *, void *); + int (*sha512init)(archive_sha512_ctx *); + int (*sha512update)(archive_sha512_ctx *, const void *, size_t); + int (*sha512final)(archive_sha512_ctx *, void *); +}; + +extern const struct archive_digest __archive_digest; + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_disk_acl_darwin.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_disk_acl_darwin.c new file mode 100644 index 0000000000..48ad016512 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_disk_acl_darwin.c @@ -0,0 +1,559 @@ +/*- + * Copyright (c) 2017 Martin Matuska + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +#if ARCHIVE_ACL_DARWIN + +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#if HAVE_ERRNO_H +#include <errno.h> +#endif +#if HAVE_MEMBERSHIP_H +#include <membership.h> +#endif +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_ACL_H +#define _ACL_PRIVATE /* For debugging */ +#include <sys/acl.h> +#endif + +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_read_disk_private.h" +#include "archive_write_disk_private.h" + +typedef struct { + const int a_perm; /* Libarchive permission or flag */ + const int p_perm; /* Platform permission or flag */ +} acl_perm_map_t; + +static const acl_perm_map_t acl_nfs4_perm_map[] = { + {ARCHIVE_ENTRY_ACL_READ_DATA, ACL_READ_DATA}, + {ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, ACL_LIST_DIRECTORY}, + {ARCHIVE_ENTRY_ACL_WRITE_DATA, ACL_WRITE_DATA}, + {ARCHIVE_ENTRY_ACL_ADD_FILE, ACL_ADD_FILE}, + {ARCHIVE_ENTRY_ACL_EXECUTE, ACL_EXECUTE}, + {ARCHIVE_ENTRY_ACL_DELETE, ACL_DELETE}, + {ARCHIVE_ENTRY_ACL_APPEND_DATA, ACL_APPEND_DATA}, + {ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, ACL_ADD_SUBDIRECTORY}, + {ARCHIVE_ENTRY_ACL_DELETE_CHILD, ACL_DELETE_CHILD}, + {ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, ACL_READ_ATTRIBUTES}, + {ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, ACL_WRITE_ATTRIBUTES}, + {ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, ACL_READ_EXTATTRIBUTES}, + {ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, ACL_WRITE_EXTATTRIBUTES}, + {ARCHIVE_ENTRY_ACL_READ_ACL, ACL_READ_SECURITY}, + {ARCHIVE_ENTRY_ACL_WRITE_ACL, ACL_WRITE_SECURITY}, + {ARCHIVE_ENTRY_ACL_WRITE_OWNER, ACL_CHANGE_OWNER}, +#if HAVE_DECL_ACL_SYNCHRONIZE + {ARCHIVE_ENTRY_ACL_SYNCHRONIZE, ACL_SYNCHRONIZE} +#endif +}; + +static const int acl_nfs4_perm_map_size = + (int)(sizeof(acl_nfs4_perm_map)/sizeof(acl_nfs4_perm_map[0])); + +static const acl_perm_map_t acl_nfs4_flag_map[] = { + {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, ACL_ENTRY_INHERITED}, + {ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, ACL_ENTRY_FILE_INHERIT}, + {ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, ACL_ENTRY_DIRECTORY_INHERIT}, + {ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, ACL_ENTRY_LIMIT_INHERIT}, + {ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, ACL_ENTRY_ONLY_INHERIT} +}; + +static const int acl_nfs4_flag_map_size = + (int)(sizeof(acl_nfs4_flag_map)/sizeof(acl_nfs4_flag_map[0])); + +static int translate_guid(struct archive *a, acl_entry_t acl_entry, + int *ae_id, int *ae_tag, const char **ae_name) +{ + void *q; + uid_t ugid; + int r, idtype; + + q = acl_get_qualifier(acl_entry); + if (q == NULL) + return (1); + r = mbr_uuid_to_id((const unsigned char *)q, &ugid, &idtype); + if (r != 0) { + acl_free(q); + return (1); + } + if (idtype == ID_TYPE_UID) { + *ae_tag = ARCHIVE_ENTRY_ACL_USER; + *ae_id = ugid; + *ae_name = archive_read_disk_uname(a, *ae_id); + } else if (idtype == ID_TYPE_GID) { + *ae_tag = ARCHIVE_ENTRY_ACL_GROUP; + *ae_id = ugid; + *ae_name = archive_read_disk_gname(a, *ae_id); + } else + r = 1; + + acl_free(q); + return (r); +} + +static void +add_trivial_nfs4_acl(struct archive_entry *entry) +{ + mode_t mode; + int i; + const int rperm = ARCHIVE_ENTRY_ACL_READ_DATA; + const int wperm = ARCHIVE_ENTRY_ACL_WRITE_DATA | + ARCHIVE_ENTRY_ACL_APPEND_DATA; + const int eperm = ARCHIVE_ENTRY_ACL_EXECUTE; + const int pubset = ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES | + ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS | + ARCHIVE_ENTRY_ACL_READ_ACL | + ARCHIVE_ENTRY_ACL_SYNCHRONIZE; + const int ownset = pubset | ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES | + ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS | + ARCHIVE_ENTRY_ACL_WRITE_ACL | + ARCHIVE_ENTRY_ACL_WRITE_OWNER; + + struct { + const int type; + const int tag; + int permset; + } tacl_entry[] = { + {ARCHIVE_ENTRY_ACL_TYPE_ALLOW, ARCHIVE_ENTRY_ACL_USER_OBJ, 0}, + {ARCHIVE_ENTRY_ACL_TYPE_DENY, ARCHIVE_ENTRY_ACL_USER_OBJ, 0}, + {ARCHIVE_ENTRY_ACL_TYPE_DENY, ARCHIVE_ENTRY_ACL_GROUP_OBJ, 0}, + {ARCHIVE_ENTRY_ACL_TYPE_ALLOW, ARCHIVE_ENTRY_ACL_USER_OBJ, ownset}, + {ARCHIVE_ENTRY_ACL_TYPE_ALLOW, ARCHIVE_ENTRY_ACL_GROUP_OBJ, pubset}, + {ARCHIVE_ENTRY_ACL_TYPE_ALLOW, ARCHIVE_ENTRY_ACL_EVERYONE, pubset} + }; + + mode = archive_entry_mode(entry); + + /* Permissions for everyone@ */ + if (mode & 0004) + tacl_entry[5].permset |= rperm; + if (mode & 0002) + tacl_entry[5].permset |= wperm; + if (mode & 0001) + tacl_entry[5].permset |= eperm; + + /* Permissions for group@ */ + if (mode & 0040) + tacl_entry[4].permset |= rperm; + else if (mode & 0004) + tacl_entry[2].permset |= rperm; + if (mode & 0020) + tacl_entry[4].permset |= wperm; + else if (mode & 0002) + tacl_entry[2].permset |= wperm; + if (mode & 0010) + tacl_entry[4].permset |= eperm; + else if (mode & 0001) + tacl_entry[2].permset |= eperm; + + /* Permissions for owner@ */ + if (mode & 0400) { + tacl_entry[3].permset |= rperm; + if (!(mode & 0040) && (mode & 0004)) + tacl_entry[0].permset |= rperm; + } else if ((mode & 0040) || (mode & 0004)) + tacl_entry[1].permset |= rperm; + if (mode & 0200) { + tacl_entry[3].permset |= wperm; + if (!(mode & 0020) && (mode & 0002)) + tacl_entry[0].permset |= wperm; + } else if ((mode & 0020) || (mode & 0002)) + tacl_entry[1].permset |= wperm; + if (mode & 0100) { + tacl_entry[3].permset |= eperm; + if (!(mode & 0010) && (mode & 0001)) + tacl_entry[0].permset |= eperm; + } else if ((mode & 0010) || (mode & 0001)) + tacl_entry[1].permset |= eperm; + + for (i = 0; i < 6; i++) { + if (tacl_entry[i].permset != 0) { + archive_entry_acl_add_entry(entry, + tacl_entry[i].type, tacl_entry[i].permset, + tacl_entry[i].tag, -1, NULL); + } + } + + return; +} + +static int +translate_acl(struct archive_read_disk *a, + struct archive_entry *entry, acl_t acl) +{ + acl_tag_t acl_tag; + acl_flagset_t acl_flagset; + acl_entry_t acl_entry; + acl_permset_t acl_permset; + int i, entry_acl_type; + int r, s, ae_id, ae_tag, ae_perm; + const char *ae_name; + + s = acl_get_entry(acl, ACL_FIRST_ENTRY, &acl_entry); + if (s == -1) { + archive_set_error(&a->archive, errno, + "Failed to get first ACL entry"); + return (ARCHIVE_WARN); + } + + while (s == 0) { + ae_id = -1; + ae_name = NULL; + ae_perm = 0; + + if (acl_get_tag_type(acl_entry, &acl_tag) != 0) { + archive_set_error(&a->archive, errno, + "Failed to get ACL tag type"); + return (ARCHIVE_WARN); + } + switch (acl_tag) { + case ACL_EXTENDED_ALLOW: + entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW; + r = translate_guid(&a->archive, acl_entry, + &ae_id, &ae_tag, &ae_name); + break; + case ACL_EXTENDED_DENY: + entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_DENY; + r = translate_guid(&a->archive, acl_entry, + &ae_id, &ae_tag, &ae_name); + break; + default: + /* Skip types that libarchive can't support. */ + s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry); + continue; + } + + /* Skip if translate_guid() above failed */ + if (r != 0) { + s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry); + continue; + } + + /* + * Libarchive stores "flag" (NFSv4 inheritance bits) + * in the ae_perm bitmap. + * + * acl_get_flagset_np() fails with non-NFSv4 ACLs + */ + if (acl_get_flagset_np(acl_entry, &acl_flagset) != 0) { + archive_set_error(&a->archive, errno, + "Failed to get flagset from a NFSv4 ACL entry"); + return (ARCHIVE_WARN); + } + for (i = 0; i < acl_nfs4_flag_map_size; ++i) { + r = acl_get_flag_np(acl_flagset, + acl_nfs4_flag_map[i].p_perm); + if (r == -1) { + archive_set_error(&a->archive, errno, + "Failed to check flag in a NFSv4 " + "ACL flagset"); + return (ARCHIVE_WARN); + } else if (r) + ae_perm |= acl_nfs4_flag_map[i].a_perm; + } + + if (acl_get_permset(acl_entry, &acl_permset) != 0) { + archive_set_error(&a->archive, errno, + "Failed to get ACL permission set"); + return (ARCHIVE_WARN); + } + + for (i = 0; i < acl_nfs4_perm_map_size; ++i) { + /* + * acl_get_perm() is spelled differently on different + * platforms; see above. + */ + r = acl_get_perm_np(acl_permset, + acl_nfs4_perm_map[i].p_perm); + if (r == -1) { + archive_set_error(&a->archive, errno, + "Failed to check permission in an ACL " + "permission set"); + return (ARCHIVE_WARN); + } else if (r) + ae_perm |= acl_nfs4_perm_map[i].a_perm; + } + +#if !HAVE_DECL_ACL_SYNCHRONIZE + /* On Mac OS X without ACL_SYNCHRONIZE assume it is set */ + ae_perm |= ARCHIVE_ENTRY_ACL_SYNCHRONIZE; +#endif + + archive_entry_acl_add_entry(entry, entry_acl_type, + ae_perm, ae_tag, + ae_id, ae_name); + + s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry); + } + return (ARCHIVE_OK); +} + +static int +set_acl(struct archive *a, int fd, const char *name, + struct archive_acl *abstract_acl, + int ae_requested_type, const char *tname) +{ + acl_t acl; + acl_entry_t acl_entry; + acl_permset_t acl_permset; + acl_flagset_t acl_flagset; + int ret; + int ae_type, ae_permset, ae_tag, ae_id; + uuid_t ae_uuid; + uid_t ae_uid; + gid_t ae_gid; + const char *ae_name; + int entries; + int i; + + ret = ARCHIVE_OK; + entries = archive_acl_reset(abstract_acl, ae_requested_type); + if (entries == 0) + return (ARCHIVE_OK); + + if (ae_requested_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + errno = ENOENT; + archive_set_error(a, errno, "Unsupported ACL type"); + return (ARCHIVE_FAILED); + } + + acl = acl_init(entries); + if (acl == (acl_t)NULL) { + archive_set_error(a, errno, + "Failed to initialize ACL working storage"); + return (ARCHIVE_FAILED); + } + + while (archive_acl_next(a, abstract_acl, ae_requested_type, &ae_type, + &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) { + /* + * Mac OS doesn't support NFSv4 ACLs for + * owner@, group@ and everyone@. + * We skip any of these ACLs found. + */ + if (ae_tag == ARCHIVE_ENTRY_ACL_USER_OBJ || + ae_tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ || + ae_tag == ARCHIVE_ENTRY_ACL_EVERYONE) + continue; + + if (acl_create_entry(&acl, &acl_entry) != 0) { + archive_set_error(a, errno, + "Failed to create a new ACL entry"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + + switch (ae_type) { + case ARCHIVE_ENTRY_ACL_TYPE_ALLOW: + acl_set_tag_type(acl_entry, ACL_EXTENDED_ALLOW); + break; + case ARCHIVE_ENTRY_ACL_TYPE_DENY: + acl_set_tag_type(acl_entry, ACL_EXTENDED_DENY); + break; + default: + /* We don't support any other types on MacOS */ + continue; + } + + switch (ae_tag) { + case ARCHIVE_ENTRY_ACL_USER: + ae_uid = archive_write_disk_uid(a, ae_name, ae_id); + if (mbr_uid_to_uuid(ae_uid, ae_uuid) != 0) + continue; + if (acl_set_qualifier(acl_entry, &ae_uuid) != 0) + continue; + break; + case ARCHIVE_ENTRY_ACL_GROUP: + ae_gid = archive_write_disk_gid(a, ae_name, ae_id); + if (mbr_gid_to_uuid(ae_gid, ae_uuid) != 0) + continue; + if (acl_set_qualifier(acl_entry, &ae_uuid) != 0) + continue; + break; + default: + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Unsupported ACL tag"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + + if (acl_get_permset(acl_entry, &acl_permset) != 0) { + archive_set_error(a, errno, + "Failed to get ACL permission set"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + if (acl_clear_perms(acl_permset) != 0) { + archive_set_error(a, errno, + "Failed to clear ACL permissions"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + + for (i = 0; i < acl_nfs4_perm_map_size; ++i) { + if (ae_permset & acl_nfs4_perm_map[i].a_perm) { + if (acl_add_perm(acl_permset, + acl_nfs4_perm_map[i].p_perm) != 0) { + archive_set_error(a, errno, + "Failed to add ACL permission"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + } + } + + /* + * acl_get_flagset_np() fails with non-NFSv4 ACLs + */ + if (acl_get_flagset_np(acl_entry, &acl_flagset) != 0) { + archive_set_error(a, errno, + "Failed to get flagset from an NFSv4 ACL entry"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + if (acl_clear_flags_np(acl_flagset) != 0) { + archive_set_error(a, errno, + "Failed to clear flags from an NFSv4 ACL flagset"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + + for (i = 0; i < acl_nfs4_flag_map_size; ++i) { + if (ae_permset & acl_nfs4_flag_map[i].a_perm) { + if (acl_add_flag_np(acl_flagset, + acl_nfs4_flag_map[i].p_perm) != 0) { + archive_set_error(a, errno, + "Failed to add flag to " + "NFSv4 ACL flagset"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + } + } + } + + if (fd >= 0) { + if (acl_set_fd_np(fd, acl, ACL_TYPE_EXTENDED) == 0) + ret = ARCHIVE_OK; + else { + if (errno == EOPNOTSUPP) { + /* Filesystem doesn't support ACLs */ + ret = ARCHIVE_OK; + } else { + archive_set_error(a, errno, + "Failed to set acl on fd: %s", tname); + ret = ARCHIVE_WARN; + } + } + } else if (acl_set_link_np(name, ACL_TYPE_EXTENDED, acl) != 0) { + if (errno == EOPNOTSUPP) { + /* Filesystem doesn't support ACLs */ + ret = ARCHIVE_OK; + } else { + archive_set_error(a, errno, "Failed to set acl: %s", + tname); + ret = ARCHIVE_WARN; + } + } +exit_free: + acl_free(acl); + return (ret); +} + +int +archive_read_disk_entry_setup_acls(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + const char *accpath; + acl_t acl; + int r; + + accpath = NULL; + + if (*fd < 0) { + accpath = archive_read_disk_entry_setup_path(a, entry, fd); + if (accpath == NULL) + return (ARCHIVE_WARN); + } + + archive_entry_acl_clear(entry); + + acl = NULL; + + if (*fd >= 0) + acl = acl_get_fd_np(*fd, ACL_TYPE_EXTENDED); + else if (!a->follow_symlinks) + acl = acl_get_link_np(accpath, ACL_TYPE_EXTENDED); + else + acl = acl_get_file(accpath, ACL_TYPE_EXTENDED); + + if (acl != NULL) { + r = translate_acl(a, entry, acl); + acl_free(acl); + acl = NULL; + + if (r != ARCHIVE_OK) { + archive_set_error(&a->archive, errno, + "Couldn't translate NFSv4 ACLs"); + } + + /* + * Because Mac OS doesn't support owner@, group@ and everyone@ + * ACLs we need to add NFSv4 ACLs mirroring the file mode to + * the archive entry. Otherwise extraction on non-Mac platforms + * would lead to an invalid file mode. + */ + if ((archive_entry_acl_types(entry) & + ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) + add_trivial_nfs4_acl(entry); + + return (r); + } + return (ARCHIVE_OK); +} + +int +archive_write_disk_set_acls(struct archive *a, int fd, const char *name, + struct archive_acl *abstract_acl, __LA_MODE_T mode) +{ + int ret = ARCHIVE_OK; + + (void)mode; /* UNUSED */ + + if ((archive_acl_types(abstract_acl) & + ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { + ret = set_acl(a, fd, name, abstract_acl, + ARCHIVE_ENTRY_ACL_TYPE_NFS4, "nfs4"); + } + return (ret); +} +#endif /* ARCHIVE_ACL_DARWIN */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_disk_acl_freebsd.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_disk_acl_freebsd.c new file mode 100644 index 0000000000..aba41e5dab --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_disk_acl_freebsd.c @@ -0,0 +1,702 @@ +/*- + * Copyright (c) 2003-2009 Tim Kientzle + * Copyright (c) 2010-2012 Michihiro NAKAJIMA + * Copyright (c) 2017 Martin Matuska + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +#if ARCHIVE_ACL_FREEBSD + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_ACL_H +#define _ACL_PRIVATE /* For debugging */ +#include <sys/acl.h> +#endif + +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_read_disk_private.h" +#include "archive_write_disk_private.h" + +typedef struct { + const int a_perm; /* Libarchive permission or flag */ + const int p_perm; /* Platform permission or flag */ +} acl_perm_map_t; + +static const acl_perm_map_t acl_posix_perm_map[] = { + {ARCHIVE_ENTRY_ACL_EXECUTE, ACL_EXECUTE}, + {ARCHIVE_ENTRY_ACL_WRITE, ACL_WRITE}, + {ARCHIVE_ENTRY_ACL_READ, ACL_READ}, +}; + +static const int acl_posix_perm_map_size = + (int)(sizeof(acl_posix_perm_map)/sizeof(acl_posix_perm_map[0])); + +#if ARCHIVE_ACL_FREEBSD_NFS4 +static const acl_perm_map_t acl_nfs4_perm_map[] = { + {ARCHIVE_ENTRY_ACL_EXECUTE, ACL_EXECUTE}, + {ARCHIVE_ENTRY_ACL_READ_DATA, ACL_READ_DATA}, + {ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, ACL_LIST_DIRECTORY}, + {ARCHIVE_ENTRY_ACL_WRITE_DATA, ACL_WRITE_DATA}, + {ARCHIVE_ENTRY_ACL_ADD_FILE, ACL_ADD_FILE}, + {ARCHIVE_ENTRY_ACL_APPEND_DATA, ACL_APPEND_DATA}, + {ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, ACL_ADD_SUBDIRECTORY}, + {ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, ACL_READ_NAMED_ATTRS}, + {ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, ACL_WRITE_NAMED_ATTRS}, + {ARCHIVE_ENTRY_ACL_DELETE_CHILD, ACL_DELETE_CHILD}, + {ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, ACL_READ_ATTRIBUTES}, + {ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, ACL_WRITE_ATTRIBUTES}, + {ARCHIVE_ENTRY_ACL_DELETE, ACL_DELETE}, + {ARCHIVE_ENTRY_ACL_READ_ACL, ACL_READ_ACL}, + {ARCHIVE_ENTRY_ACL_WRITE_ACL, ACL_WRITE_ACL}, + {ARCHIVE_ENTRY_ACL_WRITE_OWNER, ACL_WRITE_OWNER}, + {ARCHIVE_ENTRY_ACL_SYNCHRONIZE, ACL_SYNCHRONIZE} +}; + +static const int acl_nfs4_perm_map_size = + (int)(sizeof(acl_nfs4_perm_map)/sizeof(acl_nfs4_perm_map[0])); + +static const acl_perm_map_t acl_nfs4_flag_map[] = { + {ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, ACL_ENTRY_FILE_INHERIT}, + {ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, ACL_ENTRY_DIRECTORY_INHERIT}, + {ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, ACL_ENTRY_NO_PROPAGATE_INHERIT}, + {ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, ACL_ENTRY_INHERIT_ONLY}, + {ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS, ACL_ENTRY_SUCCESSFUL_ACCESS}, + {ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS, ACL_ENTRY_FAILED_ACCESS}, +#ifdef ACL_ENTRY_INHERITED + {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, ACL_ENTRY_INHERITED} +#endif +}; + +static const int acl_nfs4_flag_map_size = + (int)(sizeof(acl_nfs4_flag_map)/sizeof(acl_nfs4_flag_map[0])); +#endif /* ARCHIVE_ACL_FREEBSD_NFS4 */ + +static int +translate_acl(struct archive_read_disk *a, + struct archive_entry *entry, acl_t acl, int default_entry_acl_type) +{ +#if ARCHIVE_ACL_FREEBSD_NFS4 + int brand; + acl_flagset_t acl_flagset; + acl_entry_type_t acl_type; +#endif + acl_tag_t acl_tag; + acl_entry_t acl_entry; + acl_permset_t acl_permset; + int i, entry_acl_type, perm_map_size; + const acl_perm_map_t *perm_map; + int r, s, ae_id, ae_tag, ae_perm; + void *q; + const char *ae_name; + +#if ARCHIVE_ACL_FREEBSD_NFS4 + // FreeBSD "brands" ACLs as POSIX.1e or NFSv4 + // Make sure the "brand" on this ACL is consistent + // with the default_entry_acl_type bits provided. + if (acl_get_brand_np(acl, &brand) != 0) { + archive_set_error(&a->archive, errno, + "Failed to read ACL brand"); + return (ARCHIVE_WARN); + } + switch (brand) { + case ACL_BRAND_POSIX: + switch (default_entry_acl_type) { + case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: + case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid ACL entry type for POSIX.1e ACL"); + return (ARCHIVE_WARN); + } + break; + case ACL_BRAND_NFS4: + if (default_entry_acl_type & ~ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid ACL entry type for NFSv4 ACL"); + return (ARCHIVE_WARN); + } + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Unknown ACL brand"); + return (ARCHIVE_WARN); + } +#endif + + s = acl_get_entry(acl, ACL_FIRST_ENTRY, &acl_entry); + if (s == -1) { + archive_set_error(&a->archive, errno, + "Failed to get first ACL entry"); + return (ARCHIVE_WARN); + } + + while (s == 1) { + ae_id = -1; + ae_name = NULL; + ae_perm = 0; + + if (acl_get_tag_type(acl_entry, &acl_tag) != 0) { + archive_set_error(&a->archive, errno, + "Failed to get ACL tag type"); + return (ARCHIVE_WARN); + } + switch (acl_tag) { + case ACL_USER: + q = acl_get_qualifier(acl_entry); + if (q != NULL) { + ae_id = (int)*(uid_t *)q; + acl_free(q); + ae_name = archive_read_disk_uname(&a->archive, + ae_id); + } + ae_tag = ARCHIVE_ENTRY_ACL_USER; + break; + case ACL_GROUP: + q = acl_get_qualifier(acl_entry); + if (q != NULL) { + ae_id = (int)*(gid_t *)q; + acl_free(q); + ae_name = archive_read_disk_gname(&a->archive, + ae_id); + } + ae_tag = ARCHIVE_ENTRY_ACL_GROUP; + break; + case ACL_MASK: + ae_tag = ARCHIVE_ENTRY_ACL_MASK; + break; + case ACL_USER_OBJ: + ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ; + break; + case ACL_GROUP_OBJ: + ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; + break; + case ACL_OTHER: + ae_tag = ARCHIVE_ENTRY_ACL_OTHER; + break; +#if ARCHIVE_ACL_FREEBSD_NFS4 + case ACL_EVERYONE: + ae_tag = ARCHIVE_ENTRY_ACL_EVERYONE; + break; +#endif + default: + /* Skip types that libarchive can't support. */ + s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry); + continue; + } + + // XXX acl_type maps to allow/deny/audit/YYYY bits + entry_acl_type = default_entry_acl_type; + +#if ARCHIVE_ACL_FREEBSD_NFS4 + if (default_entry_acl_type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + /* + * acl_get_entry_type_np() fails with non-NFSv4 ACLs + */ + if (acl_get_entry_type_np(acl_entry, &acl_type) != 0) { + archive_set_error(&a->archive, errno, "Failed " + "to get ACL type from a NFSv4 ACL entry"); + return (ARCHIVE_WARN); + } + switch (acl_type) { + case ACL_ENTRY_TYPE_ALLOW: + entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW; + break; + case ACL_ENTRY_TYPE_DENY: + entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_DENY; + break; + case ACL_ENTRY_TYPE_AUDIT: + entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_AUDIT; + break; + case ACL_ENTRY_TYPE_ALARM: + entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALARM; + break; + default: + archive_set_error(&a->archive, errno, + "Invalid NFSv4 ACL entry type"); + return (ARCHIVE_WARN); + } + + /* + * Libarchive stores "flag" (NFSv4 inheritance bits) + * in the ae_perm bitmap. + * + * acl_get_flagset_np() fails with non-NFSv4 ACLs + */ + if (acl_get_flagset_np(acl_entry, &acl_flagset) != 0) { + archive_set_error(&a->archive, errno, + "Failed to get flagset from a NFSv4 " + "ACL entry"); + return (ARCHIVE_WARN); + } + for (i = 0; i < acl_nfs4_flag_map_size; ++i) { + r = acl_get_flag_np(acl_flagset, + acl_nfs4_flag_map[i].p_perm); + if (r == -1) { + archive_set_error(&a->archive, errno, + "Failed to check flag in a NFSv4 " + "ACL flagset"); + return (ARCHIVE_WARN); + } else if (r) + ae_perm |= acl_nfs4_flag_map[i].a_perm; + } + } +#endif + + if (acl_get_permset(acl_entry, &acl_permset) != 0) { + archive_set_error(&a->archive, errno, + "Failed to get ACL permission set"); + return (ARCHIVE_WARN); + } + +#if ARCHIVE_ACL_FREEBSD_NFS4 + if (default_entry_acl_type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + perm_map_size = acl_nfs4_perm_map_size; + perm_map = acl_nfs4_perm_map; + } else { +#endif + perm_map_size = acl_posix_perm_map_size; + perm_map = acl_posix_perm_map; +#if ARCHIVE_ACL_FREEBSD_NFS4 + } +#endif + + for (i = 0; i < perm_map_size; ++i) { + r = acl_get_perm_np(acl_permset, perm_map[i].p_perm); + if (r == -1) { + archive_set_error(&a->archive, errno, + "Failed to check permission in an ACL " + "permission set"); + return (ARCHIVE_WARN); + } else if (r) + ae_perm |= perm_map[i].a_perm; + } + + archive_entry_acl_add_entry(entry, entry_acl_type, + ae_perm, ae_tag, + ae_id, ae_name); + + s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry); + if (s == -1) { + archive_set_error(&a->archive, errno, + "Failed to get next ACL entry"); + return (ARCHIVE_WARN); + } + } + return (ARCHIVE_OK); +} + +static int +set_acl(struct archive *a, int fd, const char *name, + struct archive_acl *abstract_acl, + int ae_requested_type, const char *tname) +{ + int acl_type = 0; + acl_t acl; + acl_entry_t acl_entry; + acl_permset_t acl_permset; +#if ARCHIVE_ACL_FREEBSD_NFS4 + acl_flagset_t acl_flagset; + int r; +#endif + int ret; + int ae_type, ae_permset, ae_tag, ae_id; + int perm_map_size; + const acl_perm_map_t *perm_map; + uid_t ae_uid; + gid_t ae_gid; + const char *ae_name; + int entries; + int i; + + ret = ARCHIVE_OK; + entries = archive_acl_reset(abstract_acl, ae_requested_type); + if (entries == 0) + return (ARCHIVE_OK); + + + switch (ae_requested_type) { + case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: + acl_type = ACL_TYPE_ACCESS; + break; + case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: + acl_type = ACL_TYPE_DEFAULT; + break; +#if ARCHIVE_ACL_FREEBSD_NFS4 + case ARCHIVE_ENTRY_ACL_TYPE_NFS4: + acl_type = ACL_TYPE_NFS4; + break; +#endif + default: + errno = ENOENT; + archive_set_error(a, errno, "Unsupported ACL type"); + return (ARCHIVE_FAILED); + } + + acl = acl_init(entries); + if (acl == (acl_t)NULL) { + archive_set_error(a, errno, + "Failed to initialize ACL working storage"); + return (ARCHIVE_FAILED); + } + + while (archive_acl_next(a, abstract_acl, ae_requested_type, &ae_type, + &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) { + if (acl_create_entry(&acl, &acl_entry) != 0) { + archive_set_error(a, errno, + "Failed to create a new ACL entry"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + switch (ae_tag) { + case ARCHIVE_ENTRY_ACL_USER: + ae_uid = archive_write_disk_uid(a, ae_name, ae_id); + acl_set_tag_type(acl_entry, ACL_USER); + acl_set_qualifier(acl_entry, &ae_uid); + break; + case ARCHIVE_ENTRY_ACL_GROUP: + ae_gid = archive_write_disk_gid(a, ae_name, ae_id); + acl_set_tag_type(acl_entry, ACL_GROUP); + acl_set_qualifier(acl_entry, &ae_gid); + break; + case ARCHIVE_ENTRY_ACL_USER_OBJ: + acl_set_tag_type(acl_entry, ACL_USER_OBJ); + break; + case ARCHIVE_ENTRY_ACL_GROUP_OBJ: + acl_set_tag_type(acl_entry, ACL_GROUP_OBJ); + break; + case ARCHIVE_ENTRY_ACL_MASK: + acl_set_tag_type(acl_entry, ACL_MASK); + break; + case ARCHIVE_ENTRY_ACL_OTHER: + acl_set_tag_type(acl_entry, ACL_OTHER); + break; +#if ARCHIVE_ACL_FREEBSD_NFS4 + case ARCHIVE_ENTRY_ACL_EVERYONE: + acl_set_tag_type(acl_entry, ACL_EVERYONE); + break; +#endif + default: + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Unsupported ACL tag"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + +#if ARCHIVE_ACL_FREEBSD_NFS4 + r = 0; + switch (ae_type) { + case ARCHIVE_ENTRY_ACL_TYPE_ALLOW: + r = acl_set_entry_type_np(acl_entry, + ACL_ENTRY_TYPE_ALLOW); + break; + case ARCHIVE_ENTRY_ACL_TYPE_DENY: + r = acl_set_entry_type_np(acl_entry, + ACL_ENTRY_TYPE_DENY); + break; + case ARCHIVE_ENTRY_ACL_TYPE_AUDIT: + r = acl_set_entry_type_np(acl_entry, + ACL_ENTRY_TYPE_AUDIT); + break; + case ARCHIVE_ENTRY_ACL_TYPE_ALARM: + r = acl_set_entry_type_np(acl_entry, + ACL_ENTRY_TYPE_ALARM); + break; + case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: + case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: + // These don't translate directly into the system ACL. + break; + default: + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Unsupported ACL entry type"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + + if (r != 0) { + archive_set_error(a, errno, + "Failed to set ACL entry type"); + ret = ARCHIVE_FAILED; + goto exit_free; + } +#endif + + if (acl_get_permset(acl_entry, &acl_permset) != 0) { + archive_set_error(a, errno, + "Failed to get ACL permission set"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + if (acl_clear_perms(acl_permset) != 0) { + archive_set_error(a, errno, + "Failed to clear ACL permissions"); + ret = ARCHIVE_FAILED; + goto exit_free; + } +#if ARCHIVE_ACL_FREEBSD_NFS4 + if (ae_requested_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + perm_map_size = acl_nfs4_perm_map_size; + perm_map = acl_nfs4_perm_map; + } else { +#endif + perm_map_size = acl_posix_perm_map_size; + perm_map = acl_posix_perm_map; +#if ARCHIVE_ACL_FREEBSD_NFS4 + } +#endif + + for (i = 0; i < perm_map_size; ++i) { + if (ae_permset & perm_map[i].a_perm) { + if (acl_add_perm(acl_permset, + perm_map[i].p_perm) != 0) { + archive_set_error(a, errno, + "Failed to add ACL permission"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + } + } + +#if ARCHIVE_ACL_FREEBSD_NFS4 + if (ae_requested_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + /* + * acl_get_flagset_np() fails with non-NFSv4 ACLs + */ + if (acl_get_flagset_np(acl_entry, &acl_flagset) != 0) { + archive_set_error(a, errno, + "Failed to get flagset from an NFSv4 " + "ACL entry"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + if (acl_clear_flags_np(acl_flagset) != 0) { + archive_set_error(a, errno, + "Failed to clear flags from an NFSv4 " + "ACL flagset"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + for (i = 0; i < acl_nfs4_flag_map_size; ++i) { + if (ae_permset & acl_nfs4_flag_map[i].a_perm) { + if (acl_add_flag_np(acl_flagset, + acl_nfs4_flag_map[i].p_perm) != 0) { + archive_set_error(a, errno, + "Failed to add flag to " + "NFSv4 ACL flagset"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + } + } + } +#endif + } + + /* Try restoring the ACL through 'fd' if we can. */ + if (fd >= 0) { + if (acl_set_fd_np(fd, acl, acl_type) == 0) + ret = ARCHIVE_OK; + else { + if (errno == EOPNOTSUPP) { + /* Filesystem doesn't support ACLs */ + ret = ARCHIVE_OK; + } else { + archive_set_error(a, errno, + "Failed to set acl on fd: %s", tname); + ret = ARCHIVE_WARN; + } + } + } +#if HAVE_ACL_SET_LINK_NP + else if (acl_set_link_np(name, acl_type, acl) != 0) +#else + /* FreeBSD older than 8.0 */ + else if (acl_set_file(name, acl_type, acl) != 0) +#endif + { + if (errno == EOPNOTSUPP) { + /* Filesystem doesn't support ACLs */ + ret = ARCHIVE_OK; + } else { + archive_set_error(a, errno, "Failed to set acl: %s", + tname); + ret = ARCHIVE_WARN; + } + } +exit_free: + acl_free(acl); + return (ret); +} + +int +archive_read_disk_entry_setup_acls(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + const char *accpath; + acl_t acl; + int r; + + accpath = NULL; + + if (*fd < 0) { + accpath = archive_read_disk_entry_setup_path(a, entry, fd); + if (accpath == NULL) + return (ARCHIVE_WARN); + } + + archive_entry_acl_clear(entry); + + acl = NULL; + +#if ARCHIVE_ACL_FREEBSD_NFS4 + /* Try NFSv4 ACL first. */ + if (*fd >= 0) + acl = acl_get_fd_np(*fd, ACL_TYPE_NFS4); + else if (!a->follow_symlinks) + acl = acl_get_link_np(accpath, ACL_TYPE_NFS4); + else + acl = acl_get_file(accpath, ACL_TYPE_NFS4); + + /* Ignore "trivial" ACLs that just mirror the file mode. */ + if (acl != NULL && acl_is_trivial_np(acl, &r) == 0 && r == 1) { + acl_free(acl); + acl = NULL; + return (ARCHIVE_OK); + } + + if (acl != NULL) { + r = translate_acl(a, entry, acl, ARCHIVE_ENTRY_ACL_TYPE_NFS4); + acl_free(acl); + acl = NULL; + + if (r != ARCHIVE_OK) { + archive_set_error(&a->archive, errno, + "Couldn't translate NFSv4 ACLs"); + } + + return (r); + } +#endif + + /* Retrieve access ACL from file. */ + if (*fd >= 0) + acl = acl_get_fd_np(*fd, ACL_TYPE_ACCESS); +#if HAVE_ACL_GET_LINK_NP + else if (!a->follow_symlinks) + acl = acl_get_link_np(accpath, ACL_TYPE_ACCESS); +#else + else if ((!a->follow_symlinks) + && (archive_entry_filetype(entry) == AE_IFLNK)) + /* We can't get the ACL of a symlink, so we assume it can't + have one. */ + acl = NULL; +#endif + else + acl = acl_get_file(accpath, ACL_TYPE_ACCESS); + +#if HAVE_ACL_IS_TRIVIAL_NP + /* Ignore "trivial" ACLs that just mirror the file mode. */ + if (acl != NULL && acl_is_trivial_np(acl, &r) == 0 && r == 1) { + acl_free(acl); + acl = NULL; + } +#endif + + if (acl != NULL) { + r = translate_acl(a, entry, acl, ARCHIVE_ENTRY_ACL_TYPE_ACCESS); + acl_free(acl); + acl = NULL; + + if (r != ARCHIVE_OK) { + archive_set_error(&a->archive, errno, + "Couldn't translate access ACLs"); + return (r); + } + } + + /* Only directories can have default ACLs. */ + if (S_ISDIR(archive_entry_mode(entry))) { + if (*fd >= 0) + acl = acl_get_fd_np(*fd, ACL_TYPE_DEFAULT); + else + acl = acl_get_file(accpath, ACL_TYPE_DEFAULT); + if (acl != NULL) { + r = translate_acl(a, entry, acl, + ARCHIVE_ENTRY_ACL_TYPE_DEFAULT); + acl_free(acl); + if (r != ARCHIVE_OK) { + archive_set_error(&a->archive, errno, + "Couldn't translate default ACLs"); + return (r); + } + } + } + return (ARCHIVE_OK); +} + +int +archive_write_disk_set_acls(struct archive *a, int fd, const char *name, + struct archive_acl *abstract_acl, __LA_MODE_T mode) +{ + int ret = ARCHIVE_OK; + + (void)mode; /* UNUSED */ + + if ((archive_acl_types(abstract_acl) + & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) { + if ((archive_acl_types(abstract_acl) + & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) { + ret = set_acl(a, fd, name, abstract_acl, + ARCHIVE_ENTRY_ACL_TYPE_ACCESS, "access"); + if (ret != ARCHIVE_OK) + return (ret); + } + if ((archive_acl_types(abstract_acl) + & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0) + ret = set_acl(a, fd, name, abstract_acl, + ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, "default"); + + /* Simultaneous POSIX.1e and NFSv4 is not supported */ + return (ret); + } +#if ARCHIVE_ACL_FREEBSD_NFS4 + else if ((archive_acl_types(abstract_acl) & + ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { + ret = set_acl(a, fd, name, abstract_acl, + ARCHIVE_ENTRY_ACL_TYPE_NFS4, "nfs4"); + } +#endif + return (ret); +} +#endif /* ARCHIVE_ACL_FREEBSD */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_disk_acl_linux.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_disk_acl_linux.c new file mode 100644 index 0000000000..3928f3d6fa --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_disk_acl_linux.c @@ -0,0 +1,743 @@ +/*- + * Copyright (c) 2003-2009 Tim Kientzle + * Copyright (c) 2010-2012 Michihiro NAKAJIMA + * Copyright (c) 2017 Martin Matuska + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +#if ARCHIVE_ACL_LIBACL || ARCHIVE_ACL_LIBRICHACL + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#if HAVE_ACL_LIBACL_H +#include <acl/libacl.h> +#endif +#ifdef HAVE_SYS_ACL_H +#include <sys/acl.h> +#endif +#ifdef HAVE_SYS_RICHACL_H +#include <sys/richacl.h> +#endif + +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_read_disk_private.h" +#include "archive_write_disk_private.h" + +typedef struct { + const int a_perm; /* Libarchive permission or flag */ + const int p_perm; /* Platform permission or flag */ +} acl_perm_map_t; + +#if ARCHIVE_ACL_LIBACL +static const acl_perm_map_t acl_posix_perm_map[] = { + {ARCHIVE_ENTRY_ACL_EXECUTE, ACL_EXECUTE}, + {ARCHIVE_ENTRY_ACL_WRITE, ACL_WRITE}, + {ARCHIVE_ENTRY_ACL_READ, ACL_READ}, +}; + +static const int acl_posix_perm_map_size = + (int)(sizeof(acl_posix_perm_map)/sizeof(acl_posix_perm_map[0])); +#endif /* ARCHIVE_ACL_LIBACL */ + +#if ARCHIVE_ACL_LIBRICHACL +static const acl_perm_map_t acl_nfs4_perm_map[] = { + {ARCHIVE_ENTRY_ACL_EXECUTE, RICHACE_EXECUTE}, + {ARCHIVE_ENTRY_ACL_READ_DATA, RICHACE_READ_DATA}, + {ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, RICHACE_LIST_DIRECTORY}, + {ARCHIVE_ENTRY_ACL_WRITE_DATA, RICHACE_WRITE_DATA}, + {ARCHIVE_ENTRY_ACL_ADD_FILE, RICHACE_ADD_FILE}, + {ARCHIVE_ENTRY_ACL_APPEND_DATA, RICHACE_APPEND_DATA}, + {ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, RICHACE_ADD_SUBDIRECTORY}, + {ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, RICHACE_READ_NAMED_ATTRS}, + {ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, RICHACE_WRITE_NAMED_ATTRS}, + {ARCHIVE_ENTRY_ACL_DELETE_CHILD, RICHACE_DELETE_CHILD}, + {ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, RICHACE_READ_ATTRIBUTES}, + {ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, RICHACE_WRITE_ATTRIBUTES}, + {ARCHIVE_ENTRY_ACL_DELETE, RICHACE_DELETE}, + {ARCHIVE_ENTRY_ACL_READ_ACL, RICHACE_READ_ACL}, + {ARCHIVE_ENTRY_ACL_WRITE_ACL, RICHACE_WRITE_ACL}, + {ARCHIVE_ENTRY_ACL_WRITE_OWNER, RICHACE_WRITE_OWNER}, + {ARCHIVE_ENTRY_ACL_SYNCHRONIZE, RICHACE_SYNCHRONIZE} +}; + +static const int acl_nfs4_perm_map_size = + (int)(sizeof(acl_nfs4_perm_map)/sizeof(acl_nfs4_perm_map[0])); + +static const acl_perm_map_t acl_nfs4_flag_map[] = { + {ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, RICHACE_FILE_INHERIT_ACE}, + {ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, RICHACE_DIRECTORY_INHERIT_ACE}, + {ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, RICHACE_NO_PROPAGATE_INHERIT_ACE}, + {ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, RICHACE_INHERIT_ONLY_ACE}, + {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, RICHACE_INHERITED_ACE} +}; + +static const int acl_nfs4_flag_map_size = + (int)(sizeof(acl_nfs4_flag_map)/sizeof(acl_nfs4_flag_map[0])); +#endif /* ARCHIVE_ACL_LIBRICHACL */ + +#if ARCHIVE_ACL_LIBACL +/* + * Translate POSIX.1e ACLs into libarchive internal structure + */ +static int +translate_acl(struct archive_read_disk *a, + struct archive_entry *entry, acl_t acl, int default_entry_acl_type) +{ + acl_tag_t acl_tag; + acl_entry_t acl_entry; + acl_permset_t acl_permset; + int i, entry_acl_type; + int r, s, ae_id, ae_tag, ae_perm; + void *q; + const char *ae_name; + + s = acl_get_entry(acl, ACL_FIRST_ENTRY, &acl_entry); + if (s == -1) { + archive_set_error(&a->archive, errno, + "Failed to get first ACL entry"); + return (ARCHIVE_WARN); + } + + while (s == 1) { + ae_id = -1; + ae_name = NULL; + ae_perm = 0; + + if (acl_get_tag_type(acl_entry, &acl_tag) != 0) { + archive_set_error(&a->archive, errno, + "Failed to get ACL tag type"); + return (ARCHIVE_WARN); + } + switch (acl_tag) { + case ACL_USER: + q = acl_get_qualifier(acl_entry); + if (q != NULL) { + ae_id = (int)*(uid_t *)q; + acl_free(q); + ae_name = archive_read_disk_uname(&a->archive, + ae_id); + } + ae_tag = ARCHIVE_ENTRY_ACL_USER; + break; + case ACL_GROUP: + q = acl_get_qualifier(acl_entry); + if (q != NULL) { + ae_id = (int)*(gid_t *)q; + acl_free(q); + ae_name = archive_read_disk_gname(&a->archive, + ae_id); + } + ae_tag = ARCHIVE_ENTRY_ACL_GROUP; + break; + case ACL_MASK: + ae_tag = ARCHIVE_ENTRY_ACL_MASK; + break; + case ACL_USER_OBJ: + ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ; + break; + case ACL_GROUP_OBJ: + ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; + break; + case ACL_OTHER: + ae_tag = ARCHIVE_ENTRY_ACL_OTHER; + break; + default: + /* Skip types that libarchive can't support. */ + s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry); + continue; + } + + // XXX acl_type maps to allow/deny/audit/YYYY bits + entry_acl_type = default_entry_acl_type; + + if (acl_get_permset(acl_entry, &acl_permset) != 0) { + archive_set_error(&a->archive, errno, + "Failed to get ACL permission set"); + return (ARCHIVE_WARN); + } + + for (i = 0; i < acl_posix_perm_map_size; ++i) { + r = acl_get_perm(acl_permset, + acl_posix_perm_map[i].p_perm); + if (r == -1) { + archive_set_error(&a->archive, errno, + "Failed to check permission in an ACL " + "permission set"); + return (ARCHIVE_WARN); + } else if (r) + ae_perm |= acl_posix_perm_map[i].a_perm; + } + + archive_entry_acl_add_entry(entry, entry_acl_type, + ae_perm, ae_tag, + ae_id, ae_name); + + s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry); + if (s == -1) { + archive_set_error(&a->archive, errno, + "Failed to get next ACL entry"); + return (ARCHIVE_WARN); + } + } + return (ARCHIVE_OK); +} +#endif /* ARCHIVE_ACL_LIBACL */ + +#if ARCHIVE_ACL_LIBRICHACL +/* + * Translate RichACL into libarchive internal ACL + */ +static int +translate_richacl(struct archive_read_disk *a, struct archive_entry *entry, + struct richacl *richacl) +{ + int ae_id, ae_tag, ae_perm; + int entry_acl_type, i; + const char *ae_name; + + struct richace *richace; + + richacl_for_each_entry(richace, richacl) { + ae_name = NULL; + ae_tag = 0; + ae_perm = 0; + ae_id = -1; + + switch (richace->e_type) { + case RICHACE_ACCESS_ALLOWED_ACE_TYPE: + entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW; + break; + case RICHACE_ACCESS_DENIED_ACE_TYPE: + entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_DENY; + break; + default: /* Unknown entry type, skip */ + continue; + } + + /* Unsupported */ + if (richace->e_flags & RICHACE_UNMAPPED_WHO) + continue; + + if (richace->e_flags & RICHACE_SPECIAL_WHO) { + switch (richace->e_id) { + case RICHACE_OWNER_SPECIAL_ID: + ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ; + break; + case RICHACE_GROUP_SPECIAL_ID: + ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; + break; + case RICHACE_EVERYONE_SPECIAL_ID: + ae_tag = ARCHIVE_ENTRY_ACL_EVERYONE; + break; + default: /* Unknown special ID type */ + continue; + } + } else { + ae_id = richace->e_id; + if (richace->e_flags & RICHACE_IDENTIFIER_GROUP) { + ae_tag = ARCHIVE_ENTRY_ACL_GROUP; + ae_name = archive_read_disk_gname(&a->archive, + (gid_t)(richace->e_id)); + } else { + ae_tag = ARCHIVE_ENTRY_ACL_USER; + ae_name = archive_read_disk_uname(&a->archive, + (uid_t)(richace->e_id)); + } + } + for (i = 0; i < acl_nfs4_flag_map_size; ++i) { + if ((richace->e_flags & + acl_nfs4_flag_map[i].p_perm) != 0) + ae_perm |= acl_nfs4_flag_map[i].a_perm; + } + for (i = 0; i < acl_nfs4_perm_map_size; ++i) { + if ((richace->e_mask & + acl_nfs4_perm_map[i].p_perm) != 0) + ae_perm |= + acl_nfs4_perm_map[i].a_perm; + } + + archive_entry_acl_add_entry(entry, entry_acl_type, + ae_perm, ae_tag, ae_id, ae_name); + } + return (ARCHIVE_OK); +} +#endif /* ARCHIVE_ACL_LIBRICHACL */ + +#if ARCHIVE_ACL_LIBRICHACL +static int +_richacl_mode_to_mask(short mode) +{ + int mask = 0; + + if (mode & S_IROTH) + mask |= RICHACE_POSIX_MODE_READ; + if (mode & S_IWOTH) + mask |= RICHACE_POSIX_MODE_WRITE; + if (mode & S_IXOTH) + mask |= RICHACE_POSIX_MODE_EXEC; + + return (mask); +} + +static void +_richacl_mode_to_masks(struct richacl *richacl, __LA_MODE_T mode) +{ + richacl->a_owner_mask = _richacl_mode_to_mask((mode & 0700) >> 6); + richacl->a_group_mask = _richacl_mode_to_mask((mode & 0070) >> 3); + richacl->a_other_mask = _richacl_mode_to_mask(mode & 0007); +} +#endif /* ARCHIVE_ACL_LIBRICHACL */ + +#if ARCHIVE_ACL_LIBRICHACL +static int +set_richacl(struct archive *a, int fd, const char *name, + struct archive_acl *abstract_acl, __LA_MODE_T mode, + int ae_requested_type, const char *tname) +{ + int ae_type, ae_permset, ae_tag, ae_id; + uid_t ae_uid; + gid_t ae_gid; + const char *ae_name; + int entries; + int i; + int ret; + int e = 0; + struct richacl *richacl = NULL; + struct richace *richace; + + ret = ARCHIVE_OK; + entries = archive_acl_reset(abstract_acl, ae_requested_type); + if (entries == 0) + return (ARCHIVE_OK); + + if (ae_requested_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + errno = ENOENT; + archive_set_error(a, errno, "Unsupported ACL type"); + return (ARCHIVE_FAILED); + } + + richacl = richacl_alloc(entries); + if (richacl == NULL) { + archive_set_error(a, errno, + "Failed to initialize RichACL working storage"); + return (ARCHIVE_FAILED); + } + + e = 0; + + while (archive_acl_next(a, abstract_acl, ae_requested_type, &ae_type, + &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) { + richace = &(richacl->a_entries[e]); + + richace->e_flags = 0; + richace->e_mask = 0; + + switch (ae_tag) { + case ARCHIVE_ENTRY_ACL_USER: + ae_uid = archive_write_disk_uid(a, ae_name, ae_id); + richace->e_id = ae_uid; + break; + case ARCHIVE_ENTRY_ACL_GROUP: + ae_gid = archive_write_disk_gid(a, ae_name, ae_id); + richace->e_id = ae_gid; + richace->e_flags |= RICHACE_IDENTIFIER_GROUP; + break; + case ARCHIVE_ENTRY_ACL_USER_OBJ: + richace->e_flags |= RICHACE_SPECIAL_WHO; + richace->e_id = RICHACE_OWNER_SPECIAL_ID; + break; + case ARCHIVE_ENTRY_ACL_GROUP_OBJ: + richace->e_flags |= RICHACE_SPECIAL_WHO; + richace->e_id = RICHACE_GROUP_SPECIAL_ID; + break; + case ARCHIVE_ENTRY_ACL_EVERYONE: + richace->e_flags |= RICHACE_SPECIAL_WHO; + richace->e_id = RICHACE_EVERYONE_SPECIAL_ID; + break; + default: + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Unsupported ACL tag"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + + switch (ae_type) { + case ARCHIVE_ENTRY_ACL_TYPE_ALLOW: + richace->e_type = + RICHACE_ACCESS_ALLOWED_ACE_TYPE; + break; + case ARCHIVE_ENTRY_ACL_TYPE_DENY: + richace->e_type = + RICHACE_ACCESS_DENIED_ACE_TYPE; + break; + case ARCHIVE_ENTRY_ACL_TYPE_AUDIT: + case ARCHIVE_ENTRY_ACL_TYPE_ALARM: + break; + default: + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Unsupported ACL entry type"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + + for (i = 0; i < acl_nfs4_perm_map_size; ++i) { + if (ae_permset & acl_nfs4_perm_map[i].a_perm) + richace->e_mask |= acl_nfs4_perm_map[i].p_perm; + } + + for (i = 0; i < acl_nfs4_flag_map_size; ++i) { + if (ae_permset & + acl_nfs4_flag_map[i].a_perm) + richace->e_flags |= acl_nfs4_flag_map[i].p_perm; + } + e++; + } + + /* Fill RichACL masks */ + _richacl_mode_to_masks(richacl, mode); + + if (fd >= 0) { + if (richacl_set_fd(fd, richacl) == 0) + ret = ARCHIVE_OK; + else { + if (errno == EOPNOTSUPP) { + /* Filesystem doesn't support ACLs */ + ret = ARCHIVE_OK; + } else { + archive_set_error(a, errno, + "Failed to set richacl on fd: %s", tname); + ret = ARCHIVE_WARN; + } + } + } else if (richacl_set_file(name, richacl) != 0) { + if (errno == EOPNOTSUPP) { + /* Filesystem doesn't support ACLs */ + ret = ARCHIVE_OK; + } else { + archive_set_error(a, errno, "Failed to set richacl: %s", + tname); + ret = ARCHIVE_WARN; + } + } +exit_free: + richacl_free(richacl); + return (ret); +} +#endif /* ARCHIVE_ACL_RICHACL */ + +#if ARCHIVE_ACL_LIBACL +static int +set_acl(struct archive *a, int fd, const char *name, + struct archive_acl *abstract_acl, + int ae_requested_type, const char *tname) +{ + int acl_type = 0; + int ae_type, ae_permset, ae_tag, ae_id; + uid_t ae_uid; + gid_t ae_gid; + const char *ae_name; + int entries; + int i; + int ret; + acl_t acl = NULL; + acl_entry_t acl_entry; + acl_permset_t acl_permset; + + ret = ARCHIVE_OK; + entries = archive_acl_reset(abstract_acl, ae_requested_type); + if (entries == 0) + return (ARCHIVE_OK); + + switch (ae_requested_type) { + case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: + acl_type = ACL_TYPE_ACCESS; + break; + case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: + acl_type = ACL_TYPE_DEFAULT; + break; + default: + errno = ENOENT; + archive_set_error(a, errno, "Unsupported ACL type"); + return (ARCHIVE_FAILED); + } + + acl = acl_init(entries); + if (acl == (acl_t)NULL) { + archive_set_error(a, errno, + "Failed to initialize ACL working storage"); + return (ARCHIVE_FAILED); + } + + while (archive_acl_next(a, abstract_acl, ae_requested_type, &ae_type, + &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) { + + if (acl_create_entry(&acl, &acl_entry) != 0) { + archive_set_error(a, errno, + "Failed to create a new ACL entry"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + + switch (ae_tag) { + case ARCHIVE_ENTRY_ACL_USER: + ae_uid = archive_write_disk_uid(a, ae_name, ae_id); + acl_set_tag_type(acl_entry, ACL_USER); + acl_set_qualifier(acl_entry, &ae_uid); + break; + case ARCHIVE_ENTRY_ACL_GROUP: + ae_gid = archive_write_disk_gid(a, ae_name, ae_id); + acl_set_tag_type(acl_entry, ACL_GROUP); + acl_set_qualifier(acl_entry, &ae_gid); + break; + case ARCHIVE_ENTRY_ACL_USER_OBJ: + acl_set_tag_type(acl_entry, ACL_USER_OBJ); + break; + case ARCHIVE_ENTRY_ACL_GROUP_OBJ: + acl_set_tag_type(acl_entry, ACL_GROUP_OBJ); + break; + case ARCHIVE_ENTRY_ACL_MASK: + acl_set_tag_type(acl_entry, ACL_MASK); + break; + case ARCHIVE_ENTRY_ACL_OTHER: + acl_set_tag_type(acl_entry, ACL_OTHER); + break; + default: + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Unsupported ACL tag"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + + if (acl_get_permset(acl_entry, &acl_permset) != 0) { + archive_set_error(a, errno, + "Failed to get ACL permission set"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + if (acl_clear_perms(acl_permset) != 0) { + archive_set_error(a, errno, + "Failed to clear ACL permissions"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + + for (i = 0; i < acl_posix_perm_map_size; ++i) { + if (ae_permset & acl_posix_perm_map[i].a_perm) { + if (acl_add_perm(acl_permset, + acl_posix_perm_map[i].p_perm) != 0) { + archive_set_error(a, errno, + "Failed to add ACL permission"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + } + } + + } + + if (fd >= 0 && ae_requested_type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS) { + if (acl_set_fd(fd, acl) == 0) + ret = ARCHIVE_OK; + else { + if (errno == EOPNOTSUPP) { + /* Filesystem doesn't support ACLs */ + ret = ARCHIVE_OK; + } else { + archive_set_error(a, errno, + "Failed to set acl on fd: %s", tname); + ret = ARCHIVE_WARN; + } + } + } else if (acl_set_file(name, acl_type, acl) != 0) { + if (errno == EOPNOTSUPP) { + /* Filesystem doesn't support ACLs */ + ret = ARCHIVE_OK; + } else { + archive_set_error(a, errno, "Failed to set acl: %s", + tname); + ret = ARCHIVE_WARN; + } + } +exit_free: + acl_free(acl); + return (ret); +} +#endif /* ARCHIVE_ACL_LIBACL */ + +int +archive_read_disk_entry_setup_acls(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + const char *accpath; + int r; +#if ARCHIVE_ACL_LIBACL + acl_t acl; +#endif +#if ARCHIVE_ACL_LIBRICHACL + struct richacl *richacl; + mode_t mode; +#endif + + accpath = NULL; + r = ARCHIVE_OK; + + /* For default ACLs we need reachable accpath */ + if (*fd < 0 || S_ISDIR(archive_entry_mode(entry))) { + accpath = archive_read_disk_entry_setup_path(a, entry, fd); + if (accpath == NULL) + return (ARCHIVE_WARN); + } + + archive_entry_acl_clear(entry); + +#if ARCHIVE_ACL_LIBACL + acl = NULL; +#endif +#if ARCHIVE_ACL_LIBRICHACL + richacl = NULL; +#endif + +#if ARCHIVE_ACL_LIBRICHACL + /* Try NFSv4 ACL first. */ + if (*fd >= 0) + richacl = richacl_get_fd(*fd); + else if ((!a->follow_symlinks) + && (archive_entry_filetype(entry) == AE_IFLNK)) + /* We can't get the ACL of a symlink, so we assume it can't + have one */ + richacl = NULL; + else + richacl = richacl_get_file(accpath); + + /* Ignore "trivial" ACLs that just mirror the file mode. */ + if (richacl != NULL) { + mode = archive_entry_mode(entry); + if (richacl_equiv_mode(richacl, &mode) == 0) { + richacl_free(richacl); + richacl = NULL; + return (ARCHIVE_OK); + } + } + + if (richacl != NULL) { + r = translate_richacl(a, entry, richacl); + richacl_free(richacl); + richacl = NULL; + + if (r != ARCHIVE_OK) { + archive_set_error(&a->archive, errno, + "Couldn't translate NFSv4 ACLs"); + } + + return (r); + } +#endif /* ARCHIVE_ACL_LIBRICHACL */ + +#if ARCHIVE_ACL_LIBACL + /* Retrieve access ACL from file. */ + if (*fd >= 0) + acl = acl_get_fd(*fd); + else if ((!a->follow_symlinks) + && (archive_entry_filetype(entry) == AE_IFLNK)) + /* We can't get the ACL of a symlink, so we assume it can't + have one. */ + acl = NULL; + else + acl = acl_get_file(accpath, ACL_TYPE_ACCESS); + + if (acl != NULL) { + r = translate_acl(a, entry, acl, ARCHIVE_ENTRY_ACL_TYPE_ACCESS); + acl_free(acl); + acl = NULL; + + if (r != ARCHIVE_OK) { + archive_set_error(&a->archive, errno, + "Couldn't translate access ACLs"); + return (r); + } + } + + /* Only directories can have default ACLs. */ + if (S_ISDIR(archive_entry_mode(entry))) { + acl = acl_get_file(accpath, ACL_TYPE_DEFAULT); + if (acl != NULL) { + r = translate_acl(a, entry, acl, + ARCHIVE_ENTRY_ACL_TYPE_DEFAULT); + acl_free(acl); + if (r != ARCHIVE_OK) { + archive_set_error(&a->archive, errno, + "Couldn't translate default ACLs"); + return (r); + } + } + } +#endif /* ARCHIVE_ACL_LIBACL */ + return (r); +} + +int +archive_write_disk_set_acls(struct archive *a, int fd, const char *name, + struct archive_acl *abstract_acl, __LA_MODE_T mode) +{ + int ret = ARCHIVE_OK; + +#if !ARCHIVE_ACL_LIBRICHACL + (void)mode; /* UNUSED */ +#endif + +#if ARCHIVE_ACL_LIBRICHACL + if ((archive_acl_types(abstract_acl) + & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { + ret = set_richacl(a, fd, name, abstract_acl, mode, + ARCHIVE_ENTRY_ACL_TYPE_NFS4, "nfs4"); + } +#if ARCHIVE_ACL_LIBACL + else +#endif +#endif /* ARCHIVE_ACL_LIBRICHACL */ +#if ARCHIVE_ACL_LIBACL + if ((archive_acl_types(abstract_acl) + & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) { + if ((archive_acl_types(abstract_acl) + & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) { + ret = set_acl(a, fd, name, abstract_acl, + ARCHIVE_ENTRY_ACL_TYPE_ACCESS, "access"); + if (ret != ARCHIVE_OK) + return (ret); + } + if ((archive_acl_types(abstract_acl) + & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0) + ret = set_acl(a, fd, name, abstract_acl, + ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, "default"); + } +#endif /* ARCHIVE_ACL_LIBACL */ + return (ret); +} +#endif /* ARCHIVE_ACL_LIBACL || ARCHIVE_ACL_LIBRICHACL */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_disk_acl_sunos.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_disk_acl_sunos.c new file mode 100644 index 0000000000..b0f5dfad9b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_disk_acl_sunos.c @@ -0,0 +1,819 @@ +/*- + * Copyright (c) 2017 Martin Matuska + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +#if ARCHIVE_ACL_SUNOS + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_ACL_H +#define _ACL_PRIVATE /* For debugging */ +#include <sys/acl.h> +#endif + +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_read_disk_private.h" +#include "archive_write_disk_private.h" + +typedef struct { + const int a_perm; /* Libarchive permission or flag */ + const int p_perm; /* Platform permission or flag */ +} acl_perm_map_t; + +static const acl_perm_map_t acl_posix_perm_map[] = { + {ARCHIVE_ENTRY_ACL_EXECUTE, S_IXOTH }, + {ARCHIVE_ENTRY_ACL_WRITE, S_IWOTH }, + {ARCHIVE_ENTRY_ACL_READ, S_IROTH } +}; + +static const int acl_posix_perm_map_size = + (int)(sizeof(acl_posix_perm_map)/sizeof(acl_posix_perm_map[0])); + +#if ARCHIVE_ACL_SUNOS_NFS4 +static const acl_perm_map_t acl_nfs4_perm_map[] = { + {ARCHIVE_ENTRY_ACL_EXECUTE, ACE_EXECUTE}, + {ARCHIVE_ENTRY_ACL_READ_DATA, ACE_READ_DATA}, + {ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, ACE_LIST_DIRECTORY}, + {ARCHIVE_ENTRY_ACL_WRITE_DATA, ACE_WRITE_DATA}, + {ARCHIVE_ENTRY_ACL_ADD_FILE, ACE_ADD_FILE}, + {ARCHIVE_ENTRY_ACL_APPEND_DATA, ACE_APPEND_DATA}, + {ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, ACE_ADD_SUBDIRECTORY}, + {ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, ACE_READ_NAMED_ATTRS}, + {ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, ACE_WRITE_NAMED_ATTRS}, + {ARCHIVE_ENTRY_ACL_DELETE_CHILD, ACE_DELETE_CHILD}, + {ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, ACE_READ_ATTRIBUTES}, + {ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, ACE_WRITE_ATTRIBUTES}, + {ARCHIVE_ENTRY_ACL_DELETE, ACE_DELETE}, + {ARCHIVE_ENTRY_ACL_READ_ACL, ACE_READ_ACL}, + {ARCHIVE_ENTRY_ACL_WRITE_ACL, ACE_WRITE_ACL}, + {ARCHIVE_ENTRY_ACL_WRITE_OWNER, ACE_WRITE_OWNER}, + {ARCHIVE_ENTRY_ACL_SYNCHRONIZE, ACE_SYNCHRONIZE} +}; + +static const int acl_nfs4_perm_map_size = + (int)(sizeof(acl_nfs4_perm_map)/sizeof(acl_nfs4_perm_map[0])); + +static const acl_perm_map_t acl_nfs4_flag_map[] = { + {ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, ACE_FILE_INHERIT_ACE}, + {ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, ACE_DIRECTORY_INHERIT_ACE}, + {ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, ACE_NO_PROPAGATE_INHERIT_ACE}, + {ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, ACE_INHERIT_ONLY_ACE}, + {ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS, ACE_SUCCESSFUL_ACCESS_ACE_FLAG}, + {ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS, ACE_FAILED_ACCESS_ACE_FLAG}, +#ifdef ACE_INHERITED_ACE + {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, ACE_INHERITED_ACE} +#endif +}; + +const int acl_nfs4_flag_map_size = + (int)(sizeof(acl_nfs4_flag_map)/sizeof(acl_nfs4_flag_map[0])); + +#endif /* ARCHIVE_ACL_SUNOS_NFS4 */ + +static void * +sunacl_get(int cmd, int *aclcnt, int fd, const char *path) +{ + int cnt, cntcmd; + size_t size; + void *aclp; + + if (cmd == GETACL) { + cntcmd = GETACLCNT; + size = sizeof(aclent_t); + } +#if ARCHIVE_ACL_SUNOS_NFS4 + else if (cmd == ACE_GETACL) { + cntcmd = ACE_GETACLCNT; + size = sizeof(ace_t); + } +#endif + else { + errno = EINVAL; + *aclcnt = -1; + return (NULL); + } + + aclp = NULL; + cnt = -2; + + while (cnt == -2 || (cnt == -1 && errno == ENOSPC)) { + if (path != NULL) + cnt = acl(path, cntcmd, 0, NULL); + else + cnt = facl(fd, cntcmd, 0, NULL); + + if (cnt > 0) { + if (aclp == NULL) + aclp = malloc(cnt * size); + else + aclp = realloc(NULL, cnt * size); + if (aclp != NULL) { + if (path != NULL) + cnt = acl(path, cmd, cnt, aclp); + else + cnt = facl(fd, cmd, cnt, aclp); + } + } else { + free(aclp); + aclp = NULL; + break; + } + } + + *aclcnt = cnt; + return (aclp); +} + +/* + * Check if acl is trivial + * This is a FreeBSD acl_is_trivial_np() implementation for Solaris + */ +static int +sun_acl_is_trivial(void *aclp, int aclcnt, mode_t mode, int is_nfs4, + int is_dir, int *trivialp) +{ +#if ARCHIVE_ACL_SUNOS_NFS4 + int i, p; + const uint32_t rperm = ACE_READ_DATA; + const uint32_t wperm = ACE_WRITE_DATA | ACE_APPEND_DATA; + const uint32_t eperm = ACE_EXECUTE; + const uint32_t pubset = ACE_READ_ATTRIBUTES | ACE_READ_NAMED_ATTRS | + ACE_READ_ACL | ACE_SYNCHRONIZE; + const uint32_t ownset = pubset | ACE_WRITE_ATTRIBUTES | + ACE_WRITE_NAMED_ATTRS | ACE_WRITE_ACL | ACE_WRITE_OWNER; + + ace_t *ace; + ace_t tace[6]; +#endif + + if (aclp == NULL || trivialp == NULL) + return (-1); + + *trivialp = 0; + + /* + * POSIX.1e ACLs marked with ACL_IS_TRIVIAL are compatible with + * FreeBSD acl_is_trivial_np(). On Solaris they have 4 entries, + * including mask. + */ + if (!is_nfs4) { + if (aclcnt == 4) + *trivialp = 1; + return (0); + } + +#if ARCHIVE_ACL_SUNOS_NFS4 + /* + * Continue with checking NFSv4 ACLs + * + * Create list of trivial ace's to be compared + */ + + /* owner@ allow pre */ + tace[0].a_flags = ACE_OWNER; + tace[0].a_type = ACE_ACCESS_ALLOWED_ACE_TYPE; + tace[0].a_access_mask = 0; + + /* owner@ deny */ + tace[1].a_flags = ACE_OWNER; + tace[1].a_type = ACE_ACCESS_DENIED_ACE_TYPE; + tace[1].a_access_mask = 0; + + /* group@ deny */ + tace[2].a_flags = ACE_GROUP | ACE_IDENTIFIER_GROUP; + tace[2].a_type = ACE_ACCESS_DENIED_ACE_TYPE; + tace[2].a_access_mask = 0; + + /* owner@ allow */ + tace[3].a_flags = ACE_OWNER; + tace[3].a_type = ACE_ACCESS_ALLOWED_ACE_TYPE; + tace[3].a_access_mask = ownset; + + /* group@ allow */ + tace[4].a_flags = ACE_GROUP | ACE_IDENTIFIER_GROUP; + tace[4].a_type = ACE_ACCESS_ALLOWED_ACE_TYPE; + tace[4].a_access_mask = pubset; + + /* everyone@ allow */ + tace[5].a_flags = ACE_EVERYONE; + tace[5].a_type = ACE_ACCESS_ALLOWED_ACE_TYPE; + tace[5].a_access_mask = pubset; + + /* Permissions for everyone@ */ + if (mode & 0004) + tace[5].a_access_mask |= rperm; + if (mode & 0002) + tace[5].a_access_mask |= wperm; + if (mode & 0001) + tace[5].a_access_mask |= eperm; + + /* Permissions for group@ */ + if (mode & 0040) + tace[4].a_access_mask |= rperm; + else if (mode & 0004) + tace[2].a_access_mask |= rperm; + if (mode & 0020) + tace[4].a_access_mask |= wperm; + else if (mode & 0002) + tace[2].a_access_mask |= wperm; + if (mode & 0010) + tace[4].a_access_mask |= eperm; + else if (mode & 0001) + tace[2].a_access_mask |= eperm; + + /* Permissions for owner@ */ + if (mode & 0400) { + tace[3].a_access_mask |= rperm; + if (!(mode & 0040) && (mode & 0004)) + tace[0].a_access_mask |= rperm; + } else if ((mode & 0040) || (mode & 0004)) + tace[1].a_access_mask |= rperm; + if (mode & 0200) { + tace[3].a_access_mask |= wperm; + if (!(mode & 0020) && (mode & 0002)) + tace[0].a_access_mask |= wperm; + } else if ((mode & 0020) || (mode & 0002)) + tace[1].a_access_mask |= wperm; + if (mode & 0100) { + tace[3].a_access_mask |= eperm; + if (!(mode & 0010) && (mode & 0001)) + tace[0].a_access_mask |= eperm; + } else if ((mode & 0010) || (mode & 0001)) + tace[1].a_access_mask |= eperm; + + /* Check if the acl count matches */ + p = 3; + for (i = 0; i < 3; i++) { + if (tace[i].a_access_mask != 0) + p++; + } + if (aclcnt != p) + return (0); + + p = 0; + for (i = 0; i < 6; i++) { + if (tace[i].a_access_mask != 0) { + ace = &((ace_t *)aclp)[p]; + /* + * Illumos added ACE_DELETE_CHILD to write perms for + * directories. We have to check against that, too. + */ + if (ace->a_flags != tace[i].a_flags || + ace->a_type != tace[i].a_type || + (ace->a_access_mask != tace[i].a_access_mask && + (!is_dir || (tace[i].a_access_mask & wperm) == 0 || + ace->a_access_mask != + (tace[i].a_access_mask | ACE_DELETE_CHILD)))) + return (0); + p++; + } + } + + *trivialp = 1; +#else /* !ARCHIVE_ACL_SUNOS_NFS4 */ + (void)is_dir; /* UNUSED */ + (void)aclp; /* UNUSED */ +#endif /* !ARCHIVE_ACL_SUNOS_NFS4 */ + return (0); +} + +/* + * Translate Solaris POSIX.1e and NFSv4 ACLs into libarchive internal ACL + */ +static int +translate_acl(struct archive_read_disk *a, + struct archive_entry *entry, void *aclp, int aclcnt, + int default_entry_acl_type) +{ + int e, i; + int ae_id, ae_tag, ae_perm; + int entry_acl_type; + const char *ae_name; + aclent_t *aclent; +#if ARCHIVE_ACL_SUNOS_NFS4 + ace_t *ace; +#endif + + if (aclcnt <= 0) + return (ARCHIVE_OK); + + for (e = 0; e < aclcnt; e++) { + ae_name = NULL; + ae_tag = 0; + ae_perm = 0; + +#if ARCHIVE_ACL_SUNOS_NFS4 + if (default_entry_acl_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + ace = &((ace_t *)aclp)[e]; + ae_id = ace->a_who; + + switch(ace->a_type) { + case ACE_ACCESS_ALLOWED_ACE_TYPE: + entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW; + break; + case ACE_ACCESS_DENIED_ACE_TYPE: + entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_DENY; + break; + case ACE_SYSTEM_AUDIT_ACE_TYPE: + entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; + break; + case ACE_SYSTEM_ALARM_ACE_TYPE: + entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALARM; + break; + default: + /* Unknown entry type, skip */ + continue; + } + + if ((ace->a_flags & ACE_OWNER) != 0) + ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ; + else if ((ace->a_flags & ACE_GROUP) != 0) + ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; + else if ((ace->a_flags & ACE_EVERYONE) != 0) + ae_tag = ARCHIVE_ENTRY_ACL_EVERYONE; + else if ((ace->a_flags & ACE_IDENTIFIER_GROUP) != 0) { + ae_tag = ARCHIVE_ENTRY_ACL_GROUP; + ae_name = archive_read_disk_gname(&a->archive, + ae_id); + } else { + ae_tag = ARCHIVE_ENTRY_ACL_USER; + ae_name = archive_read_disk_uname(&a->archive, + ae_id); + } + + for (i = 0; i < acl_nfs4_flag_map_size; ++i) { + if ((ace->a_flags & + acl_nfs4_flag_map[i].p_perm) != 0) + ae_perm |= acl_nfs4_flag_map[i].a_perm; + } + + for (i = 0; i < acl_nfs4_perm_map_size; ++i) { + if ((ace->a_access_mask & + acl_nfs4_perm_map[i].p_perm) != 0) + ae_perm |= acl_nfs4_perm_map[i].a_perm; + } + } else +#endif /* ARCHIVE_ACL_SUNOS_NFS4 */ + if (default_entry_acl_type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS) { + aclent = &((aclent_t *)aclp)[e]; + if ((aclent->a_type & ACL_DEFAULT) != 0) + entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT; + else + entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; + ae_id = aclent->a_id; + + switch(aclent->a_type) { + case DEF_USER: + case USER: + ae_name = archive_read_disk_uname(&a->archive, + ae_id); + ae_tag = ARCHIVE_ENTRY_ACL_USER; + break; + case DEF_GROUP: + case GROUP: + ae_name = archive_read_disk_gname(&a->archive, + ae_id); + ae_tag = ARCHIVE_ENTRY_ACL_GROUP; + break; + case DEF_CLASS_OBJ: + case CLASS_OBJ: + ae_tag = ARCHIVE_ENTRY_ACL_MASK; + break; + case DEF_USER_OBJ: + case USER_OBJ: + ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ; + break; + case DEF_GROUP_OBJ: + case GROUP_OBJ: + ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; + break; + case DEF_OTHER_OBJ: + case OTHER_OBJ: + ae_tag = ARCHIVE_ENTRY_ACL_OTHER; + break; + default: + /* Unknown tag type, skip */ + continue; + } + + for (i = 0; i < acl_posix_perm_map_size; ++i) { + if ((aclent->a_perm & + acl_posix_perm_map[i].p_perm) != 0) + ae_perm |= acl_posix_perm_map[i].a_perm; + } + } else + return (ARCHIVE_WARN); + + archive_entry_acl_add_entry(entry, entry_acl_type, + ae_perm, ae_tag, ae_id, ae_name); + } + return (ARCHIVE_OK); +} + +static int +set_acl(struct archive *a, int fd, const char *name, + struct archive_acl *abstract_acl, + int ae_requested_type, const char *tname) +{ + aclent_t *aclent; +#if ARCHIVE_ACL_SUNOS_NFS4 + ace_t *ace; +#endif + int cmd, e, r; + void *aclp; + int ret; + int ae_type, ae_permset, ae_tag, ae_id; + int perm_map_size; + const acl_perm_map_t *perm_map; + uid_t ae_uid; + gid_t ae_gid; + const char *ae_name; + int entries; + int i; + + ret = ARCHIVE_OK; + entries = archive_acl_reset(abstract_acl, ae_requested_type); + if (entries == 0) + return (ARCHIVE_OK); + + + switch (ae_requested_type) { + case ARCHIVE_ENTRY_ACL_TYPE_POSIX1E: + cmd = SETACL; + aclp = malloc(entries * sizeof(aclent_t)); + break; +#if ARCHIVE_ACL_SUNOS_NFS4 + case ARCHIVE_ENTRY_ACL_TYPE_NFS4: + cmd = ACE_SETACL; + aclp = malloc(entries * sizeof(ace_t)); + + break; +#endif + default: + errno = ENOENT; + archive_set_error(a, errno, "Unsupported ACL type"); + return (ARCHIVE_FAILED); + } + + if (aclp == NULL) { + archive_set_error(a, errno, + "Can't allocate memory for acl buffer"); + return (ARCHIVE_FAILED); + } + + e = 0; + + while (archive_acl_next(a, abstract_acl, ae_requested_type, &ae_type, + &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) { + aclent = NULL; +#if ARCHIVE_ACL_SUNOS_NFS4 + ace = NULL; +#endif + if (cmd == SETACL) { + aclent = &((aclent_t *)aclp)[e]; + aclent->a_id = -1; + aclent->a_type = 0; + aclent->a_perm = 0; + } +#if ARCHIVE_ACL_SUNOS_NFS4 + else { /* cmd == ACE_SETACL */ + ace = &((ace_t *)aclp)[e]; + ace->a_who = -1; + ace->a_access_mask = 0; + ace->a_flags = 0; + } +#endif /* ARCHIVE_ACL_SUNOS_NFS4 */ + + switch (ae_tag) { + case ARCHIVE_ENTRY_ACL_USER: + ae_uid = archive_write_disk_uid(a, ae_name, ae_id); + if (aclent != NULL) { + aclent->a_id = ae_uid; + aclent->a_type |= USER; + } +#if ARCHIVE_ACL_SUNOS_NFS4 + else { + ace->a_who = ae_uid; + } +#endif + break; + case ARCHIVE_ENTRY_ACL_GROUP: + ae_gid = archive_write_disk_gid(a, ae_name, ae_id); + if (aclent != NULL) { + aclent->a_id = ae_gid; + aclent->a_type |= GROUP; + } +#if ARCHIVE_ACL_SUNOS_NFS4 + else { + ace->a_who = ae_gid; + ace->a_flags |= ACE_IDENTIFIER_GROUP; + } +#endif + break; + case ARCHIVE_ENTRY_ACL_USER_OBJ: + if (aclent != NULL) + aclent->a_type |= USER_OBJ; +#if ARCHIVE_ACL_SUNOS_NFS4 + else { + ace->a_flags |= ACE_OWNER; + } +#endif + break; + case ARCHIVE_ENTRY_ACL_GROUP_OBJ: + if (aclent != NULL) + aclent->a_type |= GROUP_OBJ; +#if ARCHIVE_ACL_SUNOS_NFS4 + else { + ace->a_flags |= ACE_GROUP; + ace->a_flags |= ACE_IDENTIFIER_GROUP; + } +#endif + break; + case ARCHIVE_ENTRY_ACL_MASK: + if (aclent != NULL) + aclent->a_type |= CLASS_OBJ; + break; + case ARCHIVE_ENTRY_ACL_OTHER: + if (aclent != NULL) + aclent->a_type |= OTHER_OBJ; + break; +#if ARCHIVE_ACL_SUNOS_NFS4 + case ARCHIVE_ENTRY_ACL_EVERYONE: + if (ace != NULL) + ace->a_flags |= ACE_EVERYONE; + break; +#endif + default: + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Unsupported ACL tag"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + + r = 0; + switch (ae_type) { +#if ARCHIVE_ACL_SUNOS_NFS4 + case ARCHIVE_ENTRY_ACL_TYPE_ALLOW: + if (ace != NULL) + ace->a_type = ACE_ACCESS_ALLOWED_ACE_TYPE; + else + r = -1; + break; + case ARCHIVE_ENTRY_ACL_TYPE_DENY: + if (ace != NULL) + ace->a_type = ACE_ACCESS_DENIED_ACE_TYPE; + else + r = -1; + break; + case ARCHIVE_ENTRY_ACL_TYPE_AUDIT: + if (ace != NULL) + ace->a_type = ACE_SYSTEM_AUDIT_ACE_TYPE; + else + r = -1; + break; + case ARCHIVE_ENTRY_ACL_TYPE_ALARM: + if (ace != NULL) + ace->a_type = ACE_SYSTEM_ALARM_ACE_TYPE; + else + r = -1; + break; +#endif + case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: + if (aclent == NULL) + r = -1; + break; + case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: + if (aclent != NULL) + aclent->a_type |= ACL_DEFAULT; + else + r = -1; + break; + default: + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Unsupported ACL entry type"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + + if (r != 0) { + errno = EINVAL; + archive_set_error(a, errno, + "Failed to set ACL entry type"); + ret = ARCHIVE_FAILED; + goto exit_free; + } + +#if ARCHIVE_ACL_SUNOS_NFS4 + if (ae_requested_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + perm_map_size = acl_nfs4_perm_map_size; + perm_map = acl_nfs4_perm_map; + } else { +#endif + perm_map_size = acl_posix_perm_map_size; + perm_map = acl_posix_perm_map; +#if ARCHIVE_ACL_SUNOS_NFS4 + } +#endif + for (i = 0; i < perm_map_size; ++i) { + if (ae_permset & perm_map[i].a_perm) { +#if ARCHIVE_ACL_SUNOS_NFS4 + if (ae_requested_type == + ARCHIVE_ENTRY_ACL_TYPE_NFS4) + ace->a_access_mask |= + perm_map[i].p_perm; + else +#endif + aclent->a_perm |= perm_map[i].p_perm; + } + } + +#if ARCHIVE_ACL_SUNOS_NFS4 + if (ae_requested_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) { + for (i = 0; i < acl_nfs4_flag_map_size; ++i) { + if (ae_permset & acl_nfs4_flag_map[i].a_perm) { + ace->a_flags |= + acl_nfs4_flag_map[i].p_perm; + } + } + } +#endif + e++; + } + + /* Try restoring the ACL through 'fd' if we can. */ + if (fd >= 0) { + if (facl(fd, cmd, entries, aclp) == 0) + ret = ARCHIVE_OK; + else { + if (errno == EOPNOTSUPP) { + /* Filesystem doesn't support ACLs */ + ret = ARCHIVE_OK; + } else { + archive_set_error(a, errno, + "Failed to set acl on fd: %s", tname); + ret = ARCHIVE_WARN; + } + } + } else if (acl(name, cmd, entries, aclp) != 0) { + if (errno == EOPNOTSUPP) { + /* Filesystem doesn't support ACLs */ + ret = ARCHIVE_OK; + } else { + archive_set_error(a, errno, "Failed to set acl: %s", + tname); + ret = ARCHIVE_WARN; + } + } +exit_free: + free(aclp); + return (ret); +} + +int +archive_read_disk_entry_setup_acls(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + const char *accpath; + void *aclp; + int aclcnt; + int r; + + accpath = NULL; + + if (*fd < 0) { + accpath = archive_read_disk_entry_setup_path(a, entry, fd); + if (accpath == NULL) + return (ARCHIVE_WARN); + } + + archive_entry_acl_clear(entry); + + aclp = NULL; + +#if ARCHIVE_ACL_SUNOS_NFS4 + if (*fd >= 0) + aclp = sunacl_get(ACE_GETACL, &aclcnt, *fd, NULL); + else if ((!a->follow_symlinks) + && (archive_entry_filetype(entry) == AE_IFLNK)) + /* We can't get the ACL of a symlink, so we assume it can't + have one. */ + aclp = NULL; + else + aclp = sunacl_get(ACE_GETACL, &aclcnt, 0, accpath); + + if (aclp != NULL && sun_acl_is_trivial(aclp, aclcnt, + archive_entry_mode(entry), 1, S_ISDIR(archive_entry_mode(entry)), + &r) == 0 && r == 1) { + free(aclp); + aclp = NULL; + return (ARCHIVE_OK); + } + + if (aclp != NULL) { + r = translate_acl(a, entry, aclp, aclcnt, + ARCHIVE_ENTRY_ACL_TYPE_NFS4); + free(aclp); + aclp = NULL; + + if (r != ARCHIVE_OK) { + archive_set_error(&a->archive, errno, + "Couldn't translate NFSv4 ACLs"); + } + return (r); + } +#endif /* ARCHIVE_ACL_SUNOS_NFS4 */ + + /* Retrieve POSIX.1e ACLs from file. */ + if (*fd >= 0) + aclp = sunacl_get(GETACL, &aclcnt, *fd, NULL); + else if ((!a->follow_symlinks) + && (archive_entry_filetype(entry) == AE_IFLNK)) + /* We can't get the ACL of a symlink, so we assume it can't + have one. */ + aclp = NULL; + else + aclp = sunacl_get(GETACL, &aclcnt, 0, accpath); + + /* Ignore "trivial" ACLs that just mirror the file mode. */ + if (aclp != NULL && sun_acl_is_trivial(aclp, aclcnt, + archive_entry_mode(entry), 0, S_ISDIR(archive_entry_mode(entry)), + &r) == 0 && r == 1) { + free(aclp); + aclp = NULL; + } + + if (aclp != NULL) + { + r = translate_acl(a, entry, aclp, aclcnt, + ARCHIVE_ENTRY_ACL_TYPE_ACCESS); + free(aclp); + aclp = NULL; + + if (r != ARCHIVE_OK) { + archive_set_error(&a->archive, errno, + "Couldn't translate access ACLs"); + return (r); + } + } + + return (ARCHIVE_OK); +} + +int +archive_write_disk_set_acls(struct archive *a, int fd, const char *name, + struct archive_acl *abstract_acl, __LA_MODE_T mode) +{ + int ret = ARCHIVE_OK; + + (void)mode; /* UNUSED */ + + if ((archive_acl_types(abstract_acl) + & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) { + /* Solaris writes POSIX.1e access and default ACLs together */ + ret = set_acl(a, fd, name, abstract_acl, + ARCHIVE_ENTRY_ACL_TYPE_POSIX1E, "posix1e"); + + /* Simultaneous POSIX.1e and NFSv4 is not supported */ + return (ret); + } +#if ARCHIVE_ACL_SUNOS_NFS4 + else if ((archive_acl_types(abstract_acl) & + ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { + ret = set_acl(a, fd, name, abstract_acl, + ARCHIVE_ENTRY_ACL_TYPE_NFS4, "nfs4"); + } +#endif + return (ret); +} +#endif /* ARCHIVE_ACL_SUNOS */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_endian.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_endian.h new file mode 100644 index 0000000000..e6d3f2ce5e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_endian.h @@ -0,0 +1,195 @@ +/*- + * Copyright (c) 2002 Thomas Moestl <tmm@FreeBSD.org> + * 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. + * + * $FreeBSD: head/lib/libarchive/archive_endian.h 201085 2009-12-28 02:17:15Z kientzle $ + * + * Borrowed from FreeBSD's <sys/endian.h> + */ + +#ifndef ARCHIVE_ENDIAN_H_INCLUDED +#define ARCHIVE_ENDIAN_H_INCLUDED + +/* Note: This is a purely internal header! */ +/* Do not use this outside of libarchive internal code! */ + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +/* + * Disabling inline keyword for compilers known to choke on it: + * - Watcom C++ in C code. (For any version?) + * - SGI MIPSpro + * - Microsoft Visual C++ 6.0 (supposedly newer versions too) + * - IBM VisualAge 6 (XL v6) + * - Sun WorkShop C (SunPro) before 5.9 + */ +#if defined(__WATCOMC__) || defined(__sgi) || defined(__hpux) || defined(__BORLANDC__) +#define inline +#elif defined(__IBMC__) && __IBMC__ < 700 +#define inline +#elif defined(__SUNPRO_C) && __SUNPRO_C < 0x590 +#define inline +#elif defined(_MSC_VER) || defined(__osf__) +#define inline __inline +#endif + +/* Alignment-agnostic encode/decode bytestream to/from little/big endian. */ + +static inline uint16_t +archive_be16dec(const void *pp) +{ + unsigned char const *p = (unsigned char const *)pp; + + /* Store into unsigned temporaries before left shifting, to avoid + promotion to signed int and then left shifting into the sign bit, + which is undefined behaviour. */ + unsigned int p1 = p[1]; + unsigned int p0 = p[0]; + + return ((p0 << 8) | p1); +} + +static inline uint32_t +archive_be32dec(const void *pp) +{ + unsigned char const *p = (unsigned char const *)pp; + + /* Store into unsigned temporaries before left shifting, to avoid + promotion to signed int and then left shifting into the sign bit, + which is undefined behaviour. */ + unsigned int p3 = p[3]; + unsigned int p2 = p[2]; + unsigned int p1 = p[1]; + unsigned int p0 = p[0]; + + return ((p0 << 24) | (p1 << 16) | (p2 << 8) | p3); +} + +static inline uint64_t +archive_be64dec(const void *pp) +{ + unsigned char const *p = (unsigned char const *)pp; + + return (((uint64_t)archive_be32dec(p) << 32) | archive_be32dec(p + 4)); +} + +static inline uint16_t +archive_le16dec(const void *pp) +{ + unsigned char const *p = (unsigned char const *)pp; + + /* Store into unsigned temporaries before left shifting, to avoid + promotion to signed int and then left shifting into the sign bit, + which is undefined behaviour. */ + unsigned int p1 = p[1]; + unsigned int p0 = p[0]; + + return ((p1 << 8) | p0); +} + +static inline uint32_t +archive_le32dec(const void *pp) +{ + unsigned char const *p = (unsigned char const *)pp; + + /* Store into unsigned temporaries before left shifting, to avoid + promotion to signed int and then left shifting into the sign bit, + which is undefined behaviour. */ + unsigned int p3 = p[3]; + unsigned int p2 = p[2]; + unsigned int p1 = p[1]; + unsigned int p0 = p[0]; + + return ((p3 << 24) | (p2 << 16) | (p1 << 8) | p0); +} + +static inline uint64_t +archive_le64dec(const void *pp) +{ + unsigned char const *p = (unsigned char const *)pp; + + return (((uint64_t)archive_le32dec(p + 4) << 32) | archive_le32dec(p)); +} + +static inline void +archive_be16enc(void *pp, uint16_t u) +{ + unsigned char *p = (unsigned char *)pp; + + p[0] = (u >> 8) & 0xff; + p[1] = u & 0xff; +} + +static inline void +archive_be32enc(void *pp, uint32_t u) +{ + unsigned char *p = (unsigned char *)pp; + + p[0] = (u >> 24) & 0xff; + p[1] = (u >> 16) & 0xff; + p[2] = (u >> 8) & 0xff; + p[3] = u & 0xff; +} + +static inline void +archive_be64enc(void *pp, uint64_t u) +{ + unsigned char *p = (unsigned char *)pp; + + archive_be32enc(p, (uint32_t)(u >> 32)); + archive_be32enc(p + 4, (uint32_t)(u & 0xffffffff)); +} + +static inline void +archive_le16enc(void *pp, uint16_t u) +{ + unsigned char *p = (unsigned char *)pp; + + p[0] = u & 0xff; + p[1] = (u >> 8) & 0xff; +} + +static inline void +archive_le32enc(void *pp, uint32_t u) +{ + unsigned char *p = (unsigned char *)pp; + + p[0] = u & 0xff; + p[1] = (u >> 8) & 0xff; + p[2] = (u >> 16) & 0xff; + p[3] = (u >> 24) & 0xff; +} + +static inline void +archive_le64enc(void *pp, uint64_t u) +{ + unsigned char *p = (unsigned char *)pp; + + archive_le32enc(p, (uint32_t)(u & 0xffffffff)); + archive_le32enc(p + 4, (uint32_t)(u >> 32)); +} + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry.3 new file mode 100644 index 0000000000..2f62a4be23 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry.3 @@ -0,0 +1,149 @@ +.\" Copyright (c) 2003-2007 Tim Kientzle +.\" Copyright (c) 2010 Joerg Sonnenberger +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_ENTRY 3 +.Os +.Sh NAME +.Nm archive_entry_clear , +.Nm archive_entry_clone , +.Nm archive_entry_free , +.Nm archive_entry_new +.Nd functions for managing archive entry descriptions +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive_entry.h +.Ft "struct archive_entry *" +.Fn archive_entry_clear "struct archive_entry *" +.Ft struct archive_entry * +.Fn archive_entry_clone "struct archive_entry *" +.Ft void +.Fn archive_entry_free "struct archive_entry *" +.Ft struct archive_entry * +.Fn archive_entry_new "void" +.Sh DESCRIPTION +These functions create and manipulate data objects that +represent entries within an archive. +You can think of a +.Tn struct archive_entry +as a heavy-duty version of +.Tn struct stat : +it includes everything from +.Tn struct stat +plus associated pathname, textual group and user names, etc. +These objects are used by +.Xr libarchive 3 +to represent the metadata associated with a particular +entry in an archive. +.Ss Create and Destroy +There are functions to allocate, destroy, clear, and copy +.Va archive_entry +objects: +.Bl -tag -compact -width indent +.It Fn archive_entry_clear +Erases the object, resetting all internal fields to the +same state as a newly-created object. +This is provided to allow you to quickly recycle objects +without thrashing the heap. +.It Fn archive_entry_clone +A deep copy operation; all text fields are duplicated. +.It Fn archive_entry_free +Releases the +.Tn struct archive_entry +object. +.It Fn archive_entry_new +Allocate and return a blank +.Tn struct archive_entry +object. +.El +.Ss Function groups +Due to high number of functions, the accessor functions can be found in +man pages grouped by the purpose. +.Bl -tag -width ".Xr archive_entry_perms 3" +.It Xr archive_entry_acl 3 +Access Control List manipulation +.It Xr archive_entry_paths 3 +Path name manipulation +.It Xr archive_entry_perms 3 +User, group and mode manipulation +.It Xr archive_entry_stat 3 +Functions not in the other groups and copying to/from +.Vt struct stat . +.It Xr archive_entry_time 3 +Time field manipulation +.El +.Pp +Most of the functions set or read entries in an object. +Such functions have one of the following forms: +.Bl -tag -compact -width indent +.It Fn archive_entry_set_XXXX +Stores the provided data in the object. +In particular, for strings, the pointer is stored, +not the referenced string. +.It Fn archive_entry_copy_XXXX +As above, except that the referenced data is copied +into the object. +.It Fn archive_entry_XXXX +Returns the specified data. +In the case of strings, a const-qualified pointer to +the string is returned. +.El +String data can be set or accessed as wide character strings +or normal +.Va char +strings. +The functions that use wide character strings are suffixed with +.Cm _w . +Note that these are different representations of the same data: +For example, if you store a narrow string and read the corresponding +wide string, the object will transparently convert formats +using the current locale. +Similarly, if you store a wide string and then store a +narrow string for the same data, the previously-set wide string will +be discarded in favor of the new data. +.\" .Sh EXAMPLE +.\" .Sh RETURN VALUES +.\" .Sh ERRORS +.Sh SEE ALSO +.Xr archive_entry_acl 3 , +.Xr archive_entry_paths 3 , +.Xr archive_entry_perms 3 , +.Xr archive_entry_time 3 , +.Xr libarchive 3 +.Sh HISTORY +The +.Nm libarchive +library first appeared in +.Fx 5.3 . +.Sh AUTHORS +.An -nosplit +The +.Nm libarchive +library was written by +.An Tim Kientzle Aq kientzle@acm.org . +.\" .Sh BUGS diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry.c new file mode 100644 index 0000000000..124600c983 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry.c @@ -0,0 +1,2066 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2016 Martin Matuska + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_entry.c 201096 2009-12-28 02:41:27Z kientzle $"); + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#if MAJOR_IN_MKDEV +#include <sys/mkdev.h> +#define HAVE_MAJOR +#elif MAJOR_IN_SYSMACROS +#include <sys/sysmacros.h> +#define HAVE_MAJOR +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#ifdef HAVE_LINUX_FS_H +#include <linux/fs.h> /* for Linux file flags */ +#endif +/* + * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h. + * As the include guards don't agree, the order of include is important. + */ +#ifdef HAVE_LINUX_EXT2_FS_H +#include <linux/ext2_fs.h> /* for Linux file flags */ +#endif +#if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__) +#include <ext2fs/ext2_fs.h> /* for Linux file flags */ +#endif +#include <stddef.h> +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_WCHAR_H +#include <wchar.h> +#endif + +#include "archive.h" +#include "archive_acl_private.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_entry_private.h" + +#if !defined(HAVE_MAJOR) && !defined(major) +/* Replacement for major/minor/makedev. */ +#define major(x) ((int)(0x00ff & ((x) >> 8))) +#define minor(x) ((int)(0xffff00ff & (x))) +#define makedev(maj,min) ((0xff00 & ((maj)<<8)) | (0xffff00ff & (min))) +#endif + +/* Play games to come up with a suitable makedev() definition. */ +#ifdef __QNXNTO__ +/* QNX. <sigh> */ +#include <sys/netmgr.h> +#define ae_makedev(maj, min) makedev(ND_LOCAL_NODE, (maj), (min)) +#elif defined makedev +/* There's a "makedev" macro. */ +#define ae_makedev(maj, min) makedev((maj), (min)) +#elif defined mkdev || ((defined _WIN32 || defined __WIN32__) && !defined(__CYGWIN__)) +/* Windows. <sigh> */ +#define ae_makedev(maj, min) mkdev((maj), (min)) +#else +/* There's a "makedev" function. */ +#define ae_makedev(maj, min) makedev((maj), (min)) +#endif + +/* + * This adjustment is needed to support the following idiom for adding + * 1000ns to the stored time: + * archive_entry_set_atime(archive_entry_atime(), + * archive_entry_atime_nsec() + 1000) + * The additional if() here compensates for ambiguity in the C standard, + * which permits two possible interpretations of a % b when a is negative. + */ +#define FIX_NS(t,ns) \ + do { \ + t += ns / 1000000000; \ + ns %= 1000000000; \ + if (ns < 0) { --t; ns += 1000000000; } \ + } while (0) + +static char * ae_fflagstostr(unsigned long bitset, unsigned long bitclear); +static const wchar_t *ae_wcstofflags(const wchar_t *stringp, + unsigned long *setp, unsigned long *clrp); +static const char *ae_strtofflags(const char *stringp, + unsigned long *setp, unsigned long *clrp); + +#ifndef HAVE_WCSCPY +static wchar_t * wcscpy(wchar_t *s1, const wchar_t *s2) +{ + wchar_t *dest = s1; + while ((*s1 = *s2) != L'\0') + ++s1, ++s2; + return dest; +} +#endif +#ifndef HAVE_WCSLEN +static size_t wcslen(const wchar_t *s) +{ + const wchar_t *p = s; + while (*p != L'\0') + ++p; + return p - s; +} +#endif +#ifndef HAVE_WMEMCMP +/* Good enough for simple equality testing, but not for sorting. */ +#define wmemcmp(a,b,i) memcmp((a), (b), (i) * sizeof(wchar_t)) +#endif + +/**************************************************************************** + * + * Public Interface + * + ****************************************************************************/ + +struct archive_entry * +archive_entry_clear(struct archive_entry *entry) +{ + if (entry == NULL) + return (NULL); + archive_mstring_clean(&entry->ae_fflags_text); + archive_mstring_clean(&entry->ae_gname); + archive_mstring_clean(&entry->ae_hardlink); + archive_mstring_clean(&entry->ae_pathname); + archive_mstring_clean(&entry->ae_sourcepath); + archive_mstring_clean(&entry->ae_symlink); + archive_mstring_clean(&entry->ae_uname); + archive_entry_copy_mac_metadata(entry, NULL, 0); + archive_acl_clear(&entry->acl); + archive_entry_xattr_clear(entry); + archive_entry_sparse_clear(entry); + free(entry->stat); + entry->ae_symlink_type = AE_SYMLINK_TYPE_UNDEFINED; + memset(entry, 0, sizeof(*entry)); + return entry; +} + +struct archive_entry * +archive_entry_clone(struct archive_entry *entry) +{ + struct archive_entry *entry2; + struct ae_xattr *xp; + struct ae_sparse *sp; + size_t s; + const void *p; + + /* Allocate new structure and copy over all of the fields. */ + /* TODO: Should we copy the archive over? Or require a new archive + * as an argument? */ + entry2 = archive_entry_new2(entry->archive); + if (entry2 == NULL) + return (NULL); + entry2->ae_stat = entry->ae_stat; + entry2->ae_fflags_set = entry->ae_fflags_set; + entry2->ae_fflags_clear = entry->ae_fflags_clear; + + /* TODO: XXX If clone can have a different archive, what do we do here if + * character sets are different? XXX */ + archive_mstring_copy(&entry2->ae_fflags_text, &entry->ae_fflags_text); + archive_mstring_copy(&entry2->ae_gname, &entry->ae_gname); + archive_mstring_copy(&entry2->ae_hardlink, &entry->ae_hardlink); + archive_mstring_copy(&entry2->ae_pathname, &entry->ae_pathname); + archive_mstring_copy(&entry2->ae_sourcepath, &entry->ae_sourcepath); + archive_mstring_copy(&entry2->ae_symlink, &entry->ae_symlink); + entry2->ae_set = entry->ae_set; + archive_mstring_copy(&entry2->ae_uname, &entry->ae_uname); + + /* Copy symlink type */ + entry2->ae_symlink_type = entry->ae_symlink_type; + + /* Copy encryption status */ + entry2->encryption = entry->encryption; + + /* Copy ACL data over. */ + archive_acl_copy(&entry2->acl, &entry->acl); + + /* Copy Mac OS metadata. */ + p = archive_entry_mac_metadata(entry, &s); + archive_entry_copy_mac_metadata(entry2, p, s); + + /* Copy xattr data over. */ + xp = entry->xattr_head; + while (xp != NULL) { + archive_entry_xattr_add_entry(entry2, + xp->name, xp->value, xp->size); + xp = xp->next; + } + + /* Copy sparse data over. */ + sp = entry->sparse_head; + while (sp != NULL) { + archive_entry_sparse_add_entry(entry2, + sp->offset, sp->length); + sp = sp->next; + } + + return (entry2); +} + +void +archive_entry_free(struct archive_entry *entry) +{ + archive_entry_clear(entry); + free(entry); +} + +struct archive_entry * +archive_entry_new(void) +{ + return archive_entry_new2(NULL); +} + +struct archive_entry * +archive_entry_new2(struct archive *a) +{ + struct archive_entry *entry; + + entry = (struct archive_entry *)calloc(1, sizeof(*entry)); + if (entry == NULL) + return (NULL); + entry->archive = a; + entry->ae_symlink_type = AE_SYMLINK_TYPE_UNDEFINED; + return (entry); +} + +/* + * Functions for reading fields from an archive_entry. + */ + +time_t +archive_entry_atime(struct archive_entry *entry) +{ + return (entry->ae_stat.aest_atime); +} + +long +archive_entry_atime_nsec(struct archive_entry *entry) +{ + return (entry->ae_stat.aest_atime_nsec); +} + +int +archive_entry_atime_is_set(struct archive_entry *entry) +{ + return (entry->ae_set & AE_SET_ATIME); +} + +time_t +archive_entry_birthtime(struct archive_entry *entry) +{ + return (entry->ae_stat.aest_birthtime); +} + +long +archive_entry_birthtime_nsec(struct archive_entry *entry) +{ + return (entry->ae_stat.aest_birthtime_nsec); +} + +int +archive_entry_birthtime_is_set(struct archive_entry *entry) +{ + return (entry->ae_set & AE_SET_BIRTHTIME); +} + +time_t +archive_entry_ctime(struct archive_entry *entry) +{ + return (entry->ae_stat.aest_ctime); +} + +int +archive_entry_ctime_is_set(struct archive_entry *entry) +{ + return (entry->ae_set & AE_SET_CTIME); +} + +long +archive_entry_ctime_nsec(struct archive_entry *entry) +{ + return (entry->ae_stat.aest_ctime_nsec); +} + +dev_t +archive_entry_dev(struct archive_entry *entry) +{ + if (entry->ae_stat.aest_dev_is_broken_down) + return ae_makedev(entry->ae_stat.aest_devmajor, + entry->ae_stat.aest_devminor); + else + return (entry->ae_stat.aest_dev); +} + +int +archive_entry_dev_is_set(struct archive_entry *entry) +{ + return (entry->ae_set & AE_SET_DEV); +} + +dev_t +archive_entry_devmajor(struct archive_entry *entry) +{ + if (entry->ae_stat.aest_dev_is_broken_down) + return (entry->ae_stat.aest_devmajor); + else + return major(entry->ae_stat.aest_dev); +} + +dev_t +archive_entry_devminor(struct archive_entry *entry) +{ + if (entry->ae_stat.aest_dev_is_broken_down) + return (entry->ae_stat.aest_devminor); + else + return minor(entry->ae_stat.aest_dev); +} + +__LA_MODE_T +archive_entry_filetype(struct archive_entry *entry) +{ + return (AE_IFMT & entry->acl.mode); +} + +void +archive_entry_fflags(struct archive_entry *entry, + unsigned long *set, unsigned long *clear) +{ + *set = entry->ae_fflags_set; + *clear = entry->ae_fflags_clear; +} + +/* + * Note: if text was provided, this just returns that text. If you + * really need the text to be rebuilt in a canonical form, set the + * text, ask for the bitmaps, then set the bitmaps. (Setting the + * bitmaps clears any stored text.) This design is deliberate: if + * we're editing archives, we don't want to discard flags just because + * they aren't supported on the current system. The bitmap<->text + * conversions are platform-specific (see below). + */ +const char * +archive_entry_fflags_text(struct archive_entry *entry) +{ + const char *f; + char *p; + + if (archive_mstring_get_mbs(entry->archive, + &entry->ae_fflags_text, &f) == 0) { + if (f != NULL) + return (f); + } else if (errno == ENOMEM) + __archive_errx(1, "No memory"); + + if (entry->ae_fflags_set == 0 && entry->ae_fflags_clear == 0) + return (NULL); + + p = ae_fflagstostr(entry->ae_fflags_set, entry->ae_fflags_clear); + if (p == NULL) + return (NULL); + + archive_mstring_copy_mbs(&entry->ae_fflags_text, p); + free(p); + if (archive_mstring_get_mbs(entry->archive, + &entry->ae_fflags_text, &f) == 0) + return (f); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +la_int64_t +archive_entry_gid(struct archive_entry *entry) +{ + return (entry->ae_stat.aest_gid); +} + +const char * +archive_entry_gname(struct archive_entry *entry) +{ + const char *p; + if (archive_mstring_get_mbs(entry->archive, &entry->ae_gname, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +const char * +archive_entry_gname_utf8(struct archive_entry *entry) +{ + const char *p; + if (archive_mstring_get_utf8(entry->archive, &entry->ae_gname, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + + +const wchar_t * +archive_entry_gname_w(struct archive_entry *entry) +{ + const wchar_t *p; + if (archive_mstring_get_wcs(entry->archive, &entry->ae_gname, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +int +_archive_entry_gname_l(struct archive_entry *entry, + const char **p, size_t *len, struct archive_string_conv *sc) +{ + return (archive_mstring_get_mbs_l(&entry->ae_gname, p, len, sc)); +} + +const char * +archive_entry_hardlink(struct archive_entry *entry) +{ + const char *p; + if ((entry->ae_set & AE_SET_HARDLINK) == 0) + return (NULL); + if (archive_mstring_get_mbs( + entry->archive, &entry->ae_hardlink, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +const char * +archive_entry_hardlink_utf8(struct archive_entry *entry) +{ + const char *p; + if ((entry->ae_set & AE_SET_HARDLINK) == 0) + return (NULL); + if (archive_mstring_get_utf8( + entry->archive, &entry->ae_hardlink, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +const wchar_t * +archive_entry_hardlink_w(struct archive_entry *entry) +{ + const wchar_t *p; + if ((entry->ae_set & AE_SET_HARDLINK) == 0) + return (NULL); + if (archive_mstring_get_wcs( + entry->archive, &entry->ae_hardlink, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +int +_archive_entry_hardlink_l(struct archive_entry *entry, + const char **p, size_t *len, struct archive_string_conv *sc) +{ + if ((entry->ae_set & AE_SET_HARDLINK) == 0) { + *p = NULL; + *len = 0; + return (0); + } + return (archive_mstring_get_mbs_l(&entry->ae_hardlink, p, len, sc)); +} + +la_int64_t +archive_entry_ino(struct archive_entry *entry) +{ + return (entry->ae_stat.aest_ino); +} + +int +archive_entry_ino_is_set(struct archive_entry *entry) +{ + return (entry->ae_set & AE_SET_INO); +} + +la_int64_t +archive_entry_ino64(struct archive_entry *entry) +{ + return (entry->ae_stat.aest_ino); +} + +__LA_MODE_T +archive_entry_mode(struct archive_entry *entry) +{ + return (entry->acl.mode); +} + +time_t +archive_entry_mtime(struct archive_entry *entry) +{ + return (entry->ae_stat.aest_mtime); +} + +long +archive_entry_mtime_nsec(struct archive_entry *entry) +{ + return (entry->ae_stat.aest_mtime_nsec); +} + +int +archive_entry_mtime_is_set(struct archive_entry *entry) +{ + return (entry->ae_set & AE_SET_MTIME); +} + +unsigned int +archive_entry_nlink(struct archive_entry *entry) +{ + return (entry->ae_stat.aest_nlink); +} + +const char * +archive_entry_pathname(struct archive_entry *entry) +{ + const char *p; + if (archive_mstring_get_mbs( + entry->archive, &entry->ae_pathname, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +const char * +archive_entry_pathname_utf8(struct archive_entry *entry) +{ + const char *p; + if (archive_mstring_get_utf8( + entry->archive, &entry->ae_pathname, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +const wchar_t * +archive_entry_pathname_w(struct archive_entry *entry) +{ + const wchar_t *p; + if (archive_mstring_get_wcs( + entry->archive, &entry->ae_pathname, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +int +_archive_entry_pathname_l(struct archive_entry *entry, + const char **p, size_t *len, struct archive_string_conv *sc) +{ + return (archive_mstring_get_mbs_l(&entry->ae_pathname, p, len, sc)); +} + +__LA_MODE_T +archive_entry_perm(struct archive_entry *entry) +{ + return (~AE_IFMT & entry->acl.mode); +} + +dev_t +archive_entry_rdev(struct archive_entry *entry) +{ + if (entry->ae_stat.aest_rdev_is_broken_down) + return ae_makedev(entry->ae_stat.aest_rdevmajor, + entry->ae_stat.aest_rdevminor); + else + return (entry->ae_stat.aest_rdev); +} + +dev_t +archive_entry_rdevmajor(struct archive_entry *entry) +{ + if (entry->ae_stat.aest_rdev_is_broken_down) + return (entry->ae_stat.aest_rdevmajor); + else + return major(entry->ae_stat.aest_rdev); +} + +dev_t +archive_entry_rdevminor(struct archive_entry *entry) +{ + if (entry->ae_stat.aest_rdev_is_broken_down) + return (entry->ae_stat.aest_rdevminor); + else + return minor(entry->ae_stat.aest_rdev); +} + +la_int64_t +archive_entry_size(struct archive_entry *entry) +{ + return (entry->ae_stat.aest_size); +} + +int +archive_entry_size_is_set(struct archive_entry *entry) +{ + return (entry->ae_set & AE_SET_SIZE); +} + +const char * +archive_entry_sourcepath(struct archive_entry *entry) +{ + const char *p; + if (archive_mstring_get_mbs( + entry->archive, &entry->ae_sourcepath, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +const wchar_t * +archive_entry_sourcepath_w(struct archive_entry *entry) +{ + const wchar_t *p; + if (archive_mstring_get_wcs( + entry->archive, &entry->ae_sourcepath, &p) == 0) + return (p); + return (NULL); +} + +const char * +archive_entry_symlink(struct archive_entry *entry) +{ + const char *p; + if ((entry->ae_set & AE_SET_SYMLINK) == 0) + return (NULL); + if (archive_mstring_get_mbs( + entry->archive, &entry->ae_symlink, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +int +archive_entry_symlink_type(struct archive_entry *entry) +{ + return (entry->ae_symlink_type); +} + +const char * +archive_entry_symlink_utf8(struct archive_entry *entry) +{ + const char *p; + if ((entry->ae_set & AE_SET_SYMLINK) == 0) + return (NULL); + if (archive_mstring_get_utf8( + entry->archive, &entry->ae_symlink, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +const wchar_t * +archive_entry_symlink_w(struct archive_entry *entry) +{ + const wchar_t *p; + if ((entry->ae_set & AE_SET_SYMLINK) == 0) + return (NULL); + if (archive_mstring_get_wcs( + entry->archive, &entry->ae_symlink, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +int +_archive_entry_symlink_l(struct archive_entry *entry, + const char **p, size_t *len, struct archive_string_conv *sc) +{ + if ((entry->ae_set & AE_SET_SYMLINK) == 0) { + *p = NULL; + *len = 0; + return (0); + } + return (archive_mstring_get_mbs_l( &entry->ae_symlink, p, len, sc)); +} + +la_int64_t +archive_entry_uid(struct archive_entry *entry) +{ + return (entry->ae_stat.aest_uid); +} + +const char * +archive_entry_uname(struct archive_entry *entry) +{ + const char *p; + if (archive_mstring_get_mbs(entry->archive, &entry->ae_uname, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +const char * +archive_entry_uname_utf8(struct archive_entry *entry) +{ + const char *p; + if (archive_mstring_get_utf8(entry->archive, &entry->ae_uname, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +const wchar_t * +archive_entry_uname_w(struct archive_entry *entry) +{ + const wchar_t *p; + if (archive_mstring_get_wcs(entry->archive, &entry->ae_uname, &p) == 0) + return (p); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (NULL); +} + +int +_archive_entry_uname_l(struct archive_entry *entry, + const char **p, size_t *len, struct archive_string_conv *sc) +{ + return (archive_mstring_get_mbs_l(&entry->ae_uname, p, len, sc)); +} + +int +archive_entry_is_data_encrypted(struct archive_entry *entry) +{ + return ((entry->encryption & AE_ENCRYPTION_DATA) == AE_ENCRYPTION_DATA); +} + +int +archive_entry_is_metadata_encrypted(struct archive_entry *entry) +{ + return ((entry->encryption & AE_ENCRYPTION_METADATA) == AE_ENCRYPTION_METADATA); +} + +int +archive_entry_is_encrypted(struct archive_entry *entry) +{ + return (entry->encryption & (AE_ENCRYPTION_DATA|AE_ENCRYPTION_METADATA)); +} + +/* + * Functions to set archive_entry properties. + */ + +void +archive_entry_set_filetype(struct archive_entry *entry, unsigned int type) +{ + entry->stat_valid = 0; + entry->acl.mode &= ~AE_IFMT; + entry->acl.mode |= AE_IFMT & type; +} + +void +archive_entry_set_fflags(struct archive_entry *entry, + unsigned long set, unsigned long clear) +{ + archive_mstring_clean(&entry->ae_fflags_text); + entry->ae_fflags_set = set; + entry->ae_fflags_clear = clear; +} + +const char * +archive_entry_copy_fflags_text(struct archive_entry *entry, + const char *flags) +{ + archive_mstring_copy_mbs(&entry->ae_fflags_text, flags); + return (ae_strtofflags(flags, + &entry->ae_fflags_set, &entry->ae_fflags_clear)); +} + +const wchar_t * +archive_entry_copy_fflags_text_w(struct archive_entry *entry, + const wchar_t *flags) +{ + archive_mstring_copy_wcs(&entry->ae_fflags_text, flags); + return (ae_wcstofflags(flags, + &entry->ae_fflags_set, &entry->ae_fflags_clear)); +} + +void +archive_entry_set_gid(struct archive_entry *entry, la_int64_t g) +{ + entry->stat_valid = 0; + entry->ae_stat.aest_gid = g; +} + +void +archive_entry_set_gname(struct archive_entry *entry, const char *name) +{ + archive_mstring_copy_mbs(&entry->ae_gname, name); +} + +void +archive_entry_set_gname_utf8(struct archive_entry *entry, const char *name) +{ + archive_mstring_copy_utf8(&entry->ae_gname, name); +} + +void +archive_entry_copy_gname(struct archive_entry *entry, const char *name) +{ + archive_mstring_copy_mbs(&entry->ae_gname, name); +} + +void +archive_entry_copy_gname_w(struct archive_entry *entry, const wchar_t *name) +{ + archive_mstring_copy_wcs(&entry->ae_gname, name); +} + +int +archive_entry_update_gname_utf8(struct archive_entry *entry, const char *name) +{ + if (archive_mstring_update_utf8(entry->archive, + &entry->ae_gname, name) == 0) + return (1); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (0); +} + +int +_archive_entry_copy_gname_l(struct archive_entry *entry, + const char *name, size_t len, struct archive_string_conv *sc) +{ + return (archive_mstring_copy_mbs_len_l(&entry->ae_gname, name, len, sc)); +} + +void +archive_entry_set_ino(struct archive_entry *entry, la_int64_t ino) +{ + entry->stat_valid = 0; + entry->ae_set |= AE_SET_INO; + entry->ae_stat.aest_ino = ino; +} + +void +archive_entry_set_ino64(struct archive_entry *entry, la_int64_t ino) +{ + entry->stat_valid = 0; + entry->ae_set |= AE_SET_INO; + entry->ae_stat.aest_ino = ino; +} + +void +archive_entry_set_hardlink(struct archive_entry *entry, const char *target) +{ + archive_mstring_copy_mbs(&entry->ae_hardlink, target); + if (target != NULL) + entry->ae_set |= AE_SET_HARDLINK; + else + entry->ae_set &= ~AE_SET_HARDLINK; +} + +void +archive_entry_set_hardlink_utf8(struct archive_entry *entry, const char *target) +{ + archive_mstring_copy_utf8(&entry->ae_hardlink, target); + if (target != NULL) + entry->ae_set |= AE_SET_HARDLINK; + else + entry->ae_set &= ~AE_SET_HARDLINK; +} + +void +archive_entry_copy_hardlink(struct archive_entry *entry, const char *target) +{ + archive_mstring_copy_mbs(&entry->ae_hardlink, target); + if (target != NULL) + entry->ae_set |= AE_SET_HARDLINK; + else + entry->ae_set &= ~AE_SET_HARDLINK; +} + +void +archive_entry_copy_hardlink_w(struct archive_entry *entry, const wchar_t *target) +{ + archive_mstring_copy_wcs(&entry->ae_hardlink, target); + if (target != NULL) + entry->ae_set |= AE_SET_HARDLINK; + else + entry->ae_set &= ~AE_SET_HARDLINK; +} + +int +archive_entry_update_hardlink_utf8(struct archive_entry *entry, const char *target) +{ + if (target != NULL) + entry->ae_set |= AE_SET_HARDLINK; + else + entry->ae_set &= ~AE_SET_HARDLINK; + if (archive_mstring_update_utf8(entry->archive, + &entry->ae_hardlink, target) == 0) + return (1); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (0); +} + +int +_archive_entry_copy_hardlink_l(struct archive_entry *entry, + const char *target, size_t len, struct archive_string_conv *sc) +{ + int r; + + r = archive_mstring_copy_mbs_len_l(&entry->ae_hardlink, + target, len, sc); + if (target != NULL && r == 0) + entry->ae_set |= AE_SET_HARDLINK; + else + entry->ae_set &= ~AE_SET_HARDLINK; + return (r); +} + +void +archive_entry_set_atime(struct archive_entry *entry, time_t t, long ns) +{ + FIX_NS(t, ns); + entry->stat_valid = 0; + entry->ae_set |= AE_SET_ATIME; + entry->ae_stat.aest_atime = t; + entry->ae_stat.aest_atime_nsec = ns; +} + +void +archive_entry_unset_atime(struct archive_entry *entry) +{ + archive_entry_set_atime(entry, 0, 0); + entry->ae_set &= ~AE_SET_ATIME; +} + +void +archive_entry_set_birthtime(struct archive_entry *entry, time_t t, long ns) +{ + FIX_NS(t, ns); + entry->stat_valid = 0; + entry->ae_set |= AE_SET_BIRTHTIME; + entry->ae_stat.aest_birthtime = t; + entry->ae_stat.aest_birthtime_nsec = ns; +} + +void +archive_entry_unset_birthtime(struct archive_entry *entry) +{ + archive_entry_set_birthtime(entry, 0, 0); + entry->ae_set &= ~AE_SET_BIRTHTIME; +} + +void +archive_entry_set_ctime(struct archive_entry *entry, time_t t, long ns) +{ + FIX_NS(t, ns); + entry->stat_valid = 0; + entry->ae_set |= AE_SET_CTIME; + entry->ae_stat.aest_ctime = t; + entry->ae_stat.aest_ctime_nsec = ns; +} + +void +archive_entry_unset_ctime(struct archive_entry *entry) +{ + archive_entry_set_ctime(entry, 0, 0); + entry->ae_set &= ~AE_SET_CTIME; +} + +void +archive_entry_set_dev(struct archive_entry *entry, dev_t d) +{ + entry->stat_valid = 0; + entry->ae_set |= AE_SET_DEV; + entry->ae_stat.aest_dev_is_broken_down = 0; + entry->ae_stat.aest_dev = d; +} + +void +archive_entry_set_devmajor(struct archive_entry *entry, dev_t m) +{ + entry->stat_valid = 0; + entry->ae_set |= AE_SET_DEV; + entry->ae_stat.aest_dev_is_broken_down = 1; + entry->ae_stat.aest_devmajor = m; +} + +void +archive_entry_set_devminor(struct archive_entry *entry, dev_t m) +{ + entry->stat_valid = 0; + entry->ae_set |= AE_SET_DEV; + entry->ae_stat.aest_dev_is_broken_down = 1; + entry->ae_stat.aest_devminor = m; +} + +/* Set symlink if symlink is already set, else set hardlink. */ +void +archive_entry_set_link(struct archive_entry *entry, const char *target) +{ + if (entry->ae_set & AE_SET_SYMLINK) + archive_mstring_copy_mbs(&entry->ae_symlink, target); + else + archive_mstring_copy_mbs(&entry->ae_hardlink, target); +} + +void +archive_entry_set_link_utf8(struct archive_entry *entry, const char *target) +{ + if (entry->ae_set & AE_SET_SYMLINK) + archive_mstring_copy_utf8(&entry->ae_symlink, target); + else + archive_mstring_copy_utf8(&entry->ae_hardlink, target); +} + +/* Set symlink if symlink is already set, else set hardlink. */ +void +archive_entry_copy_link(struct archive_entry *entry, const char *target) +{ + if (entry->ae_set & AE_SET_SYMLINK) + archive_mstring_copy_mbs(&entry->ae_symlink, target); + else + archive_mstring_copy_mbs(&entry->ae_hardlink, target); +} + +/* Set symlink if symlink is already set, else set hardlink. */ +void +archive_entry_copy_link_w(struct archive_entry *entry, const wchar_t *target) +{ + if (entry->ae_set & AE_SET_SYMLINK) + archive_mstring_copy_wcs(&entry->ae_symlink, target); + else + archive_mstring_copy_wcs(&entry->ae_hardlink, target); +} + +int +archive_entry_update_link_utf8(struct archive_entry *entry, const char *target) +{ + int r; + if (entry->ae_set & AE_SET_SYMLINK) + r = archive_mstring_update_utf8(entry->archive, + &entry->ae_symlink, target); + else + r = archive_mstring_update_utf8(entry->archive, + &entry->ae_hardlink, target); + if (r == 0) + return (1); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (0); +} + +int +_archive_entry_copy_link_l(struct archive_entry *entry, + const char *target, size_t len, struct archive_string_conv *sc) +{ + int r; + + if (entry->ae_set & AE_SET_SYMLINK) + r = archive_mstring_copy_mbs_len_l(&entry->ae_symlink, + target, len, sc); + else + r = archive_mstring_copy_mbs_len_l(&entry->ae_hardlink, + target, len, sc); + return (r); +} + +void +archive_entry_set_mode(struct archive_entry *entry, mode_t m) +{ + entry->stat_valid = 0; + entry->acl.mode = m; +} + +void +archive_entry_set_mtime(struct archive_entry *entry, time_t t, long ns) +{ + FIX_NS(t, ns); + entry->stat_valid = 0; + entry->ae_set |= AE_SET_MTIME; + entry->ae_stat.aest_mtime = t; + entry->ae_stat.aest_mtime_nsec = ns; +} + +void +archive_entry_unset_mtime(struct archive_entry *entry) +{ + archive_entry_set_mtime(entry, 0, 0); + entry->ae_set &= ~AE_SET_MTIME; +} + +void +archive_entry_set_nlink(struct archive_entry *entry, unsigned int nlink) +{ + entry->stat_valid = 0; + entry->ae_stat.aest_nlink = nlink; +} + +void +archive_entry_set_pathname(struct archive_entry *entry, const char *name) +{ + archive_mstring_copy_mbs(&entry->ae_pathname, name); +} + +void +archive_entry_set_pathname_utf8(struct archive_entry *entry, const char *name) +{ + archive_mstring_copy_utf8(&entry->ae_pathname, name); +} + +void +archive_entry_copy_pathname(struct archive_entry *entry, const char *name) +{ + archive_mstring_copy_mbs(&entry->ae_pathname, name); +} + +void +archive_entry_copy_pathname_w(struct archive_entry *entry, const wchar_t *name) +{ + archive_mstring_copy_wcs(&entry->ae_pathname, name); +} + +int +archive_entry_update_pathname_utf8(struct archive_entry *entry, const char *name) +{ + if (archive_mstring_update_utf8(entry->archive, + &entry->ae_pathname, name) == 0) + return (1); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (0); +} + +int +_archive_entry_copy_pathname_l(struct archive_entry *entry, + const char *name, size_t len, struct archive_string_conv *sc) +{ + return (archive_mstring_copy_mbs_len_l(&entry->ae_pathname, + name, len, sc)); +} + +void +archive_entry_set_perm(struct archive_entry *entry, mode_t p) +{ + entry->stat_valid = 0; + entry->acl.mode &= AE_IFMT; + entry->acl.mode |= ~AE_IFMT & p; +} + +void +archive_entry_set_rdev(struct archive_entry *entry, dev_t m) +{ + entry->stat_valid = 0; + entry->ae_stat.aest_rdev = m; + entry->ae_stat.aest_rdev_is_broken_down = 0; +} + +void +archive_entry_set_rdevmajor(struct archive_entry *entry, dev_t m) +{ + entry->stat_valid = 0; + entry->ae_stat.aest_rdev_is_broken_down = 1; + entry->ae_stat.aest_rdevmajor = m; +} + +void +archive_entry_set_rdevminor(struct archive_entry *entry, dev_t m) +{ + entry->stat_valid = 0; + entry->ae_stat.aest_rdev_is_broken_down = 1; + entry->ae_stat.aest_rdevminor = m; +} + +void +archive_entry_set_size(struct archive_entry *entry, la_int64_t s) +{ + entry->stat_valid = 0; + entry->ae_stat.aest_size = s; + entry->ae_set |= AE_SET_SIZE; +} + +void +archive_entry_unset_size(struct archive_entry *entry) +{ + archive_entry_set_size(entry, 0); + entry->ae_set &= ~AE_SET_SIZE; +} + +void +archive_entry_copy_sourcepath(struct archive_entry *entry, const char *path) +{ + archive_mstring_copy_mbs(&entry->ae_sourcepath, path); +} + +void +archive_entry_copy_sourcepath_w(struct archive_entry *entry, const wchar_t *path) +{ + archive_mstring_copy_wcs(&entry->ae_sourcepath, path); +} + +void +archive_entry_set_symlink(struct archive_entry *entry, const char *linkname) +{ + archive_mstring_copy_mbs(&entry->ae_symlink, linkname); + if (linkname != NULL) + entry->ae_set |= AE_SET_SYMLINK; + else + entry->ae_set &= ~AE_SET_SYMLINK; +} + +void +archive_entry_set_symlink_type(struct archive_entry *entry, int type) +{ + entry->ae_symlink_type = type; +} + +void +archive_entry_set_symlink_utf8(struct archive_entry *entry, const char *linkname) +{ + archive_mstring_copy_utf8(&entry->ae_symlink, linkname); + if (linkname != NULL) + entry->ae_set |= AE_SET_SYMLINK; + else + entry->ae_set &= ~AE_SET_SYMLINK; +} + +void +archive_entry_copy_symlink(struct archive_entry *entry, const char *linkname) +{ + archive_mstring_copy_mbs(&entry->ae_symlink, linkname); + if (linkname != NULL) + entry->ae_set |= AE_SET_SYMLINK; + else + entry->ae_set &= ~AE_SET_SYMLINK; +} + +void +archive_entry_copy_symlink_w(struct archive_entry *entry, const wchar_t *linkname) +{ + archive_mstring_copy_wcs(&entry->ae_symlink, linkname); + if (linkname != NULL) + entry->ae_set |= AE_SET_SYMLINK; + else + entry->ae_set &= ~AE_SET_SYMLINK; +} + +int +archive_entry_update_symlink_utf8(struct archive_entry *entry, const char *linkname) +{ + if (linkname != NULL) + entry->ae_set |= AE_SET_SYMLINK; + else + entry->ae_set &= ~AE_SET_SYMLINK; + if (archive_mstring_update_utf8(entry->archive, + &entry->ae_symlink, linkname) == 0) + return (1); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (0); +} + +int +_archive_entry_copy_symlink_l(struct archive_entry *entry, + const char *linkname, size_t len, struct archive_string_conv *sc) +{ + int r; + + r = archive_mstring_copy_mbs_len_l(&entry->ae_symlink, + linkname, len, sc); + if (linkname != NULL && r == 0) + entry->ae_set |= AE_SET_SYMLINK; + else + entry->ae_set &= ~AE_SET_SYMLINK; + return (r); +} + +void +archive_entry_set_uid(struct archive_entry *entry, la_int64_t u) +{ + entry->stat_valid = 0; + entry->ae_stat.aest_uid = u; +} + +void +archive_entry_set_uname(struct archive_entry *entry, const char *name) +{ + archive_mstring_copy_mbs(&entry->ae_uname, name); +} + +void +archive_entry_set_uname_utf8(struct archive_entry *entry, const char *name) +{ + archive_mstring_copy_utf8(&entry->ae_uname, name); +} + +void +archive_entry_copy_uname(struct archive_entry *entry, const char *name) +{ + archive_mstring_copy_mbs(&entry->ae_uname, name); +} + +void +archive_entry_copy_uname_w(struct archive_entry *entry, const wchar_t *name) +{ + archive_mstring_copy_wcs(&entry->ae_uname, name); +} + +int +archive_entry_update_uname_utf8(struct archive_entry *entry, const char *name) +{ + if (archive_mstring_update_utf8(entry->archive, + &entry->ae_uname, name) == 0) + return (1); + if (errno == ENOMEM) + __archive_errx(1, "No memory"); + return (0); +} + +void +archive_entry_set_is_data_encrypted(struct archive_entry *entry, char is_encrypted) +{ + if (is_encrypted) { + entry->encryption |= AE_ENCRYPTION_DATA; + } else { + entry->encryption &= ~AE_ENCRYPTION_DATA; + } +} + +void +archive_entry_set_is_metadata_encrypted(struct archive_entry *entry, char is_encrypted) +{ + if (is_encrypted) { + entry->encryption |= AE_ENCRYPTION_METADATA; + } else { + entry->encryption &= ~AE_ENCRYPTION_METADATA; + } +} + +int +_archive_entry_copy_uname_l(struct archive_entry *entry, + const char *name, size_t len, struct archive_string_conv *sc) +{ + return (archive_mstring_copy_mbs_len_l(&entry->ae_uname, + name, len, sc)); +} + +const void * +archive_entry_mac_metadata(struct archive_entry *entry, size_t *s) +{ + *s = entry->mac_metadata_size; + return entry->mac_metadata; +} + +void +archive_entry_copy_mac_metadata(struct archive_entry *entry, + const void *p, size_t s) +{ + free(entry->mac_metadata); + if (p == NULL || s == 0) { + entry->mac_metadata = NULL; + entry->mac_metadata_size = 0; + } else { + entry->mac_metadata_size = s; + entry->mac_metadata = malloc(s); + if (entry->mac_metadata == NULL) + abort(); + memcpy(entry->mac_metadata, p, s); + } +} + +/* + * ACL management. The following would, of course, be a lot simpler + * if: 1) the last draft of POSIX.1e were a really thorough and + * complete standard that addressed the needs of ACL archiving and 2) + * everyone followed it faithfully. Alas, neither is true, so the + * following is a lot more complex than might seem necessary to the + * uninitiated. + */ + +struct archive_acl * +archive_entry_acl(struct archive_entry *entry) +{ + return &entry->acl; +} + +void +archive_entry_acl_clear(struct archive_entry *entry) +{ + archive_acl_clear(&entry->acl); +} + +/* + * Add a single ACL entry to the internal list of ACL data. + */ +int +archive_entry_acl_add_entry(struct archive_entry *entry, + int type, int permset, int tag, int id, const char *name) +{ + return archive_acl_add_entry(&entry->acl, type, permset, tag, id, name); +} + +/* + * As above, but with a wide-character name. + */ +int +archive_entry_acl_add_entry_w(struct archive_entry *entry, + int type, int permset, int tag, int id, const wchar_t *name) +{ + return archive_acl_add_entry_w_len(&entry->acl, + type, permset, tag, id, name, wcslen(name)); +} + +/* + * Return a bitmask of ACL types in an archive entry ACL list + */ +int +archive_entry_acl_types(struct archive_entry *entry) +{ + return (archive_acl_types(&entry->acl)); +} + +/* + * Return a count of entries matching "want_type". + */ +int +archive_entry_acl_count(struct archive_entry *entry, int want_type) +{ + return archive_acl_count(&entry->acl, want_type); +} + +/* + * Prepare for reading entries from the ACL data. Returns a count + * of entries matching "want_type", or zero if there are no + * non-extended ACL entries of that type. + */ +int +archive_entry_acl_reset(struct archive_entry *entry, int want_type) +{ + return archive_acl_reset(&entry->acl, want_type); +} + +/* + * Return the next ACL entry in the list. Fake entries for the + * standard permissions and include them in the returned list. + */ +int +archive_entry_acl_next(struct archive_entry *entry, int want_type, int *type, + int *permset, int *tag, int *id, const char **name) +{ + int r; + r = archive_acl_next(entry->archive, &entry->acl, want_type, type, + permset, tag, id, name); + if (r == ARCHIVE_FATAL && errno == ENOMEM) + __archive_errx(1, "No memory"); + return (r); +} + +/* + * Generate a text version of the ACL. The flags parameter controls + * the style of the generated ACL. + */ +wchar_t * +archive_entry_acl_to_text_w(struct archive_entry *entry, la_ssize_t *len, + int flags) +{ + return (archive_acl_to_text_w(&entry->acl, len, flags, + entry->archive)); +} + +char * +archive_entry_acl_to_text(struct archive_entry *entry, la_ssize_t *len, + int flags) +{ + return (archive_acl_to_text_l(&entry->acl, len, flags, NULL)); +} + +char * +_archive_entry_acl_to_text_l(struct archive_entry *entry, ssize_t *len, + int flags, struct archive_string_conv *sc) +{ + return (archive_acl_to_text_l(&entry->acl, len, flags, sc)); +} + +/* + * ACL text parser. + */ +int +archive_entry_acl_from_text_w(struct archive_entry *entry, + const wchar_t *wtext, int type) +{ + return (archive_acl_from_text_w(&entry->acl, wtext, type)); +} + +int +archive_entry_acl_from_text(struct archive_entry *entry, + const char *text, int type) +{ + return (archive_acl_from_text_l(&entry->acl, text, type, NULL)); +} + +int +_archive_entry_acl_from_text_l(struct archive_entry *entry, const char *text, + int type, struct archive_string_conv *sc) +{ + return (archive_acl_from_text_l(&entry->acl, text, type, sc)); +} + +/* Deprecated */ +static int +archive_entry_acl_text_compat(int *flags) +{ + if ((*flags & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) == 0) + return (1); + + /* ABI compat with old ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID */ + if ((*flags & OLD_ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID) != 0) + *flags |= ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID; + + /* ABI compat with old ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT */ + if ((*flags & OLD_ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT) != 0) + *flags |= ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT; + + *flags |= ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA; + + return (0); +} + +/* Deprecated */ +const wchar_t * +archive_entry_acl_text_w(struct archive_entry *entry, int flags) +{ + free(entry->acl.acl_text_w); + entry->acl.acl_text_w = NULL; + if (archive_entry_acl_text_compat(&flags) == 0) + entry->acl.acl_text_w = archive_acl_to_text_w(&entry->acl, + NULL, flags, entry->archive); + return (entry->acl.acl_text_w); +} + +/* Deprecated */ +const char * +archive_entry_acl_text(struct archive_entry *entry, int flags) +{ + free(entry->acl.acl_text); + entry->acl.acl_text = NULL; + if (archive_entry_acl_text_compat(&flags) == 0) + entry->acl.acl_text = archive_acl_to_text_l(&entry->acl, NULL, + flags, NULL); + + return (entry->acl.acl_text); +} + +/* Deprecated */ +int +_archive_entry_acl_text_l(struct archive_entry *entry, int flags, + const char **acl_text, size_t *len, struct archive_string_conv *sc) +{ + free(entry->acl.acl_text); + entry->acl.acl_text = NULL; + + if (archive_entry_acl_text_compat(&flags) == 0) + entry->acl.acl_text = archive_acl_to_text_l(&entry->acl, + (ssize_t *)len, flags, sc); + + *acl_text = entry->acl.acl_text; + + return (0); +} + +/* + * Following code is modified from UC Berkeley sources, and + * is subject to the following copyright notice. + */ + +/*- + * Copyright (c) 1993 + * The Regents of the University of California. 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. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. + */ + +/* + * Supported file flags on FreeBSD and Mac OS: + * sappnd,sappend SF_APPEND + * arch,archived SF_ARCHIVED + * schg,schange,simmutable SF_IMMUTABLE + * sunlnk,sunlink SF_NOUNLINK (FreeBSD only) + * uappnd,uappend UF_APPEND + * compressed UF_COMPRESSED (Mac OS only) + * hidden,uhidden UF_HIDDEN + * uchg,uchange,uimmutable UF_IMMUTABLE + * nodump UF_NODUMP + * uunlnk,uunlink UF_NOUNLINK (FreeBSD only) + * offline,uoffline UF_OFFLINE (FreeBSD only) + * opaque UF_OPAQUE + * rdonly,urdonly,readonly UF_READONLY (FreeBSD only) + * reparse,ureparse UF_REPARSE (FreeBSD only) + * sparse,usparse UF_SPARSE (FreeBSD only) + * system,usystem UF_SYSTEM (FreeBSD only) + * + * See chflags(2) for more information + * + * Supported file attributes on Linux: + * a append only FS_APPEND_FL sappnd + * A no atime updates FS_NOATIME_FL atime + * c compress FS_COMPR_FL compress + * C no copy on write FS_NOCOW_FL cow + * d no dump FS_NODUMP_FL dump + * D synchronous directory updates FS_DIRSYNC_FL dirsync + * i immutable FS_IMMUTABLE_FL schg + * j data journalling FS_JOURNAL_DATA_FL journal + * P project hierarchy FS_PROJINHERIT_FL projinherit + * s secure deletion FS_SECRM_FL securedeletion + * S synchronous updates FS_SYNC_FL sync + * t no tail-merging FS_NOTAIL_FL tail + * T top of directory hierarchy FS_TOPDIR_FL topdir + * u undeletable FS_UNRM_FL undel + * + * See ioctl_iflags(2) for more information + * + * Equivalent file flags supported on FreeBSD / Mac OS and Linux: + * SF_APPEND FS_APPEND_FL sappnd + * SF_IMMUTABLE FS_IMMUTABLE_FL schg + * UF_NODUMP FS_NODUMP_FL nodump + */ + +static const struct flag { + const char *name; + const wchar_t *wname; + unsigned long set; + unsigned long clear; +} fileflags[] = { + /* Preferred (shorter) names per flag first, all prefixed by "no" */ +#ifdef SF_APPEND + { "nosappnd", L"nosappnd", SF_APPEND, 0}, + { "nosappend", L"nosappend", SF_APPEND, 0}, +#endif +#if defined(FS_APPEND_FL) /* 'a' */ + { "nosappnd", L"nosappnd", FS_APPEND_FL, 0}, + { "nosappend", L"nosappend", FS_APPEND_FL, 0}, +#elif defined(EXT2_APPEND_FL) /* 'a' */ + { "nosappnd", L"nosappnd", EXT2_APPEND_FL, 0}, + { "nosappend", L"nosappend", EXT2_APPEND_FL, 0}, +#endif +#ifdef SF_ARCHIVED + { "noarch", L"noarch", SF_ARCHIVED, 0}, + { "noarchived", L"noarchived", SF_ARCHIVED, 0}, +#endif +#ifdef SF_IMMUTABLE + { "noschg", L"noschg", SF_IMMUTABLE, 0}, + { "noschange", L"noschange", SF_IMMUTABLE, 0}, + { "nosimmutable", L"nosimmutable", SF_IMMUTABLE, 0}, +#endif +#if defined(FS_IMMUTABLE_FL) /* 'i' */ + { "noschg", L"noschg", FS_IMMUTABLE_FL, 0}, + { "noschange", L"noschange", FS_IMMUTABLE_FL, 0}, + { "nosimmutable", L"nosimmutable", FS_IMMUTABLE_FL, 0}, +#elif defined(EXT2_IMMUTABLE_FL) /* 'i' */ + { "noschg", L"noschg", EXT2_IMMUTABLE_FL, 0}, + { "noschange", L"noschange", EXT2_IMMUTABLE_FL, 0}, + { "nosimmutable", L"nosimmutable", EXT2_IMMUTABLE_FL, 0}, +#endif +#ifdef SF_NOUNLINK + { "nosunlnk", L"nosunlnk", SF_NOUNLINK, 0}, + { "nosunlink", L"nosunlink", SF_NOUNLINK, 0}, +#endif +#ifdef UF_APPEND + { "nouappnd", L"nouappnd", UF_APPEND, 0}, + { "nouappend", L"nouappend", UF_APPEND, 0}, +#endif +#ifdef UF_IMMUTABLE + { "nouchg", L"nouchg", UF_IMMUTABLE, 0}, + { "nouchange", L"nouchange", UF_IMMUTABLE, 0}, + { "nouimmutable", L"nouimmutable", UF_IMMUTABLE, 0}, +#endif +#ifdef UF_NODUMP + { "nodump", L"nodump", 0, UF_NODUMP}, +#endif +#if defined(FS_NODUMP_FL) /* 'd' */ + { "nodump", L"nodump", 0, FS_NODUMP_FL}, +#elif defined(EXT2_NODUMP_FL) + { "nodump", L"nodump", 0, EXT2_NODUMP_FL}, +#endif +#ifdef UF_OPAQUE + { "noopaque", L"noopaque", UF_OPAQUE, 0}, +#endif +#ifdef UF_NOUNLINK + { "nouunlnk", L"nouunlnk", UF_NOUNLINK, 0}, + { "nouunlink", L"nouunlink", UF_NOUNLINK, 0}, +#endif +#ifdef UF_COMPRESSED + /* Mac OS */ + { "nocompressed", L"nocompressed", UF_COMPRESSED, 0}, +#endif +#ifdef UF_HIDDEN + { "nohidden", L"nohidden", UF_HIDDEN, 0}, + { "nouhidden", L"nouhidden", UF_HIDDEN, 0}, +#endif +#ifdef FILE_ATTRIBUTE_HIDDEN + { "nohidden", L"nohidden", FILE_ATTRIBUTE_HIDDEN, 0}, + { "nouhidden", L"nouhidden", FILE_ATTRIBUTE_HIDDEN, 0}, +#endif +#ifdef UF_OFFLINE + { "nooffline", L"nooffline", UF_OFFLINE, 0}, + { "nouoffline", L"nouoffline", UF_OFFLINE, 0}, +#endif +#ifdef UF_READONLY + { "nordonly", L"nordonly", UF_READONLY, 0}, + { "nourdonly", L"nourdonly", UF_READONLY, 0}, + { "noreadonly", L"noreadonly", UF_READONLY, 0}, +#endif +#ifdef FILE_ATTRIBUTE_READONLY + { "nordonly", L"nordonly", FILE_ATTRIBUTE_READONLY, 0}, + { "nourdonly", L"nourdonly", FILE_ATTRIBUTE_READONLY, 0}, + { "noreadonly", L"noreadonly", FILE_ATTRIBUTE_READONLY, 0}, +#endif +#ifdef UF_SPARSE + { "nosparse", L"nosparse", UF_SPARSE, 0}, + { "nousparse", L"nousparse", UF_SPARSE, 0}, +#endif +#ifdef UF_REPARSE + { "noreparse", L"noreparse", UF_REPARSE, 0}, + { "noureparse", L"noureparse", UF_REPARSE, 0}, +#endif +#ifdef UF_SYSTEM + { "nosystem", L"nosystem", UF_SYSTEM, 0}, + { "nousystem", L"nousystem", UF_SYSTEM, 0}, +#endif +#ifdef FILE_ATTRIBUTE_SYSTEM + { "nosystem", L"nosystem", FILE_ATTRIBUTE_SYSTEM, 0}, + { "nousystem", L"nousystem", FILE_ATTRIBUTE_SYSTEM, 0}, +#endif +#if defined(FS_UNRM_FL) /* 'u' */ + { "noundel", L"noundel", FS_UNRM_FL, 0}, +#elif defined(EXT2_UNRM_FL) + { "noundel", L"noundel", EXT2_UNRM_FL, 0}, +#endif + +#if defined(FS_COMPR_FL) /* 'c' */ + { "nocompress", L"nocompress", FS_COMPR_FL, 0}, +#elif defined(EXT2_COMPR_FL) + { "nocompress", L"nocompress", EXT2_COMPR_FL, 0}, +#endif + +#if defined(FS_NOATIME_FL) /* 'A' */ + { "noatime", L"noatime", 0, FS_NOATIME_FL}, +#elif defined(EXT2_NOATIME_FL) + { "noatime", L"noatime", 0, EXT2_NOATIME_FL}, +#endif +#if defined(FS_DIRSYNC_FL) /* 'D' */ + { "nodirsync", L"nodirsync", FS_DIRSYNC_FL, 0}, +#elif defined(EXT2_DIRSYNC_FL) + { "nodirsync", L"nodirsync", EXT2_DIRSYNC_FL, 0}, +#endif +#if defined(FS_JOURNAL_DATA_FL) /* 'j' */ + { "nojournal-data",L"nojournal-data", FS_JOURNAL_DATA_FL, 0}, + { "nojournal", L"nojournal", FS_JOURNAL_DATA_FL, 0}, +#elif defined(EXT3_JOURNAL_DATA_FL) + { "nojournal-data",L"nojournal-data", EXT3_JOURNAL_DATA_FL, 0}, + { "nojournal", L"nojournal", EXT3_JOURNAL_DATA_FL, 0}, +#endif +#if defined(FS_SECRM_FL) /* 's' */ + { "nosecdel", L"nosecdel", FS_SECRM_FL, 0}, + { "nosecuredeletion",L"nosecuredeletion",FS_SECRM_FL, 0}, +#elif defined(EXT2_SECRM_FL) + { "nosecdel", L"nosecdel", EXT2_SECRM_FL, 0}, + { "nosecuredeletion",L"nosecuredeletion",EXT2_SECRM_FL, 0}, +#endif +#if defined(FS_SYNC_FL) /* 'S' */ + { "nosync", L"nosync", FS_SYNC_FL, 0}, +#elif defined(EXT2_SYNC_FL) + { "nosync", L"nosync", EXT2_SYNC_FL, 0}, +#endif +#if defined(FS_NOTAIL_FL) /* 't' */ + { "notail", L"notail", 0, FS_NOTAIL_FL}, +#elif defined(EXT2_NOTAIL_FL) + { "notail", L"notail", 0, EXT2_NOTAIL_FL}, +#endif +#if defined(FS_TOPDIR_FL) /* 'T' */ + { "notopdir", L"notopdir", FS_TOPDIR_FL, 0}, +#elif defined(EXT2_TOPDIR_FL) + { "notopdir", L"notopdir", EXT2_TOPDIR_FL, 0}, +#endif +#ifdef FS_NOCOW_FL /* 'C' */ + { "nocow", L"nocow", 0, FS_NOCOW_FL}, +#endif +#ifdef FS_PROJINHERIT_FL /* 'P' */ + { "noprojinherit",L"noprojinherit", FS_PROJINHERIT_FL, 0}, +#endif + { NULL, NULL, 0, 0} +}; + +/* + * fflagstostr -- + * Convert file flags to a comma-separated string. If no flags + * are set, return the empty string. + */ +static char * +ae_fflagstostr(unsigned long bitset, unsigned long bitclear) +{ + char *string, *dp; + const char *sp; + unsigned long bits; + const struct flag *flag; + size_t length; + + bits = bitset | bitclear; + length = 0; + for (flag = fileflags; flag->name != NULL; flag++) + if (bits & (flag->set | flag->clear)) { + length += strlen(flag->name) + 1; + bits &= ~(flag->set | flag->clear); + } + + if (length == 0) + return (NULL); + string = (char *)malloc(length); + if (string == NULL) + return (NULL); + + dp = string; + for (flag = fileflags; flag->name != NULL; flag++) { + if (bitset & flag->set || bitclear & flag->clear) { + sp = flag->name + 2; + } else if (bitset & flag->clear || bitclear & flag->set) { + sp = flag->name; + } else + continue; + bitset &= ~(flag->set | flag->clear); + bitclear &= ~(flag->set | flag->clear); + if (dp > string) + *dp++ = ','; + while ((*dp++ = *sp++) != '\0') + ; + dp--; + } + + *dp = '\0'; + return (string); +} + +/* + * strtofflags -- + * Take string of arguments and return file flags. This + * version works a little differently than strtofflags(3). + * In particular, it always tests every token, skipping any + * unrecognized tokens. It returns a pointer to the first + * unrecognized token, or NULL if every token was recognized. + * This version is also const-correct and does not modify the + * provided string. + */ +static const char * +ae_strtofflags(const char *s, unsigned long *setp, unsigned long *clrp) +{ + const char *start, *end; + const struct flag *flag; + unsigned long set, clear; + const char *failed; + + set = clear = 0; + start = s; + failed = NULL; + /* Find start of first token. */ + while (*start == '\t' || *start == ' ' || *start == ',') + start++; + while (*start != '\0') { + size_t length; + /* Locate end of token. */ + end = start; + while (*end != '\0' && *end != '\t' && + *end != ' ' && *end != ',') + end++; + length = end - start; + for (flag = fileflags; flag->name != NULL; flag++) { + size_t flag_length = strlen(flag->name); + if (length == flag_length + && memcmp(start, flag->name, length) == 0) { + /* Matched "noXXXX", so reverse the sense. */ + clear |= flag->set; + set |= flag->clear; + break; + } else if (length == flag_length - 2 + && memcmp(start, flag->name + 2, length) == 0) { + /* Matched "XXXX", so don't reverse. */ + set |= flag->set; + clear |= flag->clear; + break; + } + } + /* Ignore unknown flag names. */ + if (flag->name == NULL && failed == NULL) + failed = start; + + /* Find start of next token. */ + start = end; + while (*start == '\t' || *start == ' ' || *start == ',') + start++; + + } + + if (setp) + *setp = set; + if (clrp) + *clrp = clear; + + /* Return location of first failure. */ + return (failed); +} + +/* + * wcstofflags -- + * Take string of arguments and return file flags. This + * version works a little differently than strtofflags(3). + * In particular, it always tests every token, skipping any + * unrecognized tokens. It returns a pointer to the first + * unrecognized token, or NULL if every token was recognized. + * This version is also const-correct and does not modify the + * provided string. + */ +static const wchar_t * +ae_wcstofflags(const wchar_t *s, unsigned long *setp, unsigned long *clrp) +{ + const wchar_t *start, *end; + const struct flag *flag; + unsigned long set, clear; + const wchar_t *failed; + + set = clear = 0; + start = s; + failed = NULL; + /* Find start of first token. */ + while (*start == L'\t' || *start == L' ' || *start == L',') + start++; + while (*start != L'\0') { + size_t length; + /* Locate end of token. */ + end = start; + while (*end != L'\0' && *end != L'\t' && + *end != L' ' && *end != L',') + end++; + length = end - start; + for (flag = fileflags; flag->wname != NULL; flag++) { + size_t flag_length = wcslen(flag->wname); + if (length == flag_length + && wmemcmp(start, flag->wname, length) == 0) { + /* Matched "noXXXX", so reverse the sense. */ + clear |= flag->set; + set |= flag->clear; + break; + } else if (length == flag_length - 2 + && wmemcmp(start, flag->wname + 2, length) == 0) { + /* Matched "XXXX", so don't reverse. */ + set |= flag->set; + clear |= flag->clear; + break; + } + } + /* Ignore unknown flag names. */ + if (flag->wname == NULL && failed == NULL) + failed = start; + + /* Find start of next token. */ + start = end; + while (*start == L'\t' || *start == L' ' || *start == L',') + start++; + + } + + if (setp) + *setp = set; + if (clrp) + *clrp = clear; + + /* Return location of first failure. */ + return (failed); +} + + +#ifdef TEST +#include <stdio.h> +int +main(int argc, char **argv) +{ + struct archive_entry *entry = archive_entry_new(); + unsigned long set, clear; + const wchar_t *remainder; + + remainder = archive_entry_copy_fflags_text_w(entry, L"nosappnd dump archive,,,,,,,"); + archive_entry_fflags(entry, &set, &clear); + + wprintf(L"set=0x%lX clear=0x%lX remainder='%ls'\n", set, clear, remainder); + + wprintf(L"new flags='%s'\n", archive_entry_fflags_text(entry)); + return (0); +} +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry.h new file mode 100644 index 0000000000..90768256ef --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry.h @@ -0,0 +1,708 @@ +/*- + * Copyright (c) 2003-2008 Tim Kientzle + * Copyright (c) 2016 Martin Matuska + * 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(S) ``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(S) 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. + * + * $FreeBSD: head/lib/libarchive/archive_entry.h 201096 2009-12-28 02:41:27Z kientzle $ + */ + +#ifndef ARCHIVE_ENTRY_H_INCLUDED +#define ARCHIVE_ENTRY_H_INCLUDED + +/* Note: Compiler will complain if this does not match archive.h! */ +#define ARCHIVE_VERSION_NUMBER 3004003 + +/* + * Note: archive_entry.h is for use outside of libarchive; the + * configuration headers (config.h, archive_platform.h, etc.) are + * purely internal. Do NOT use HAVE_XXX configuration macros to + * control the behavior of this header! If you must conditionalize, + * use predefined compiler and/or platform macros. + */ + +#include <sys/types.h> +#include <stddef.h> /* for wchar_t */ +#include <stdint.h> +#include <time.h> + +#if defined(_WIN32) && !defined(__CYGWIN__) +#include <windows.h> +#endif + +/* Get a suitable 64-bit integer type. */ +#if !defined(__LA_INT64_T_DEFINED) +# if ARCHIVE_VERSION_NUMBER < 4000000 +#define __LA_INT64_T la_int64_t +# endif +#define __LA_INT64_T_DEFINED +# if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__WATCOMC__) +typedef __int64 la_int64_t; +# else +#include <unistd.h> +# if defined(_SCO_DS) || defined(__osf__) +typedef long long la_int64_t; +# else +typedef int64_t la_int64_t; +# endif +# endif +#endif + +/* The la_ssize_t should match the type used in 'struct stat' */ +#if !defined(__LA_SSIZE_T_DEFINED) +/* Older code relied on the __LA_SSIZE_T macro; after 4.0 we'll switch to the typedef exclusively. */ +# if ARCHIVE_VERSION_NUMBER < 4000000 +#define __LA_SSIZE_T la_ssize_t +# endif +#define __LA_SSIZE_T_DEFINED +# if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__WATCOMC__) +# if defined(_SSIZE_T_DEFINED) || defined(_SSIZE_T_) +typedef ssize_t la_ssize_t; +# elif defined(_WIN64) +typedef __int64 la_ssize_t; +# else +typedef long la_ssize_t; +# endif +# else +# include <unistd.h> /* ssize_t */ +typedef ssize_t la_ssize_t; +# endif +#endif + +/* Get a suitable definition for mode_t */ +#if ARCHIVE_VERSION_NUMBER >= 3999000 +/* Switch to plain 'int' for libarchive 4.0. It's less broken than 'mode_t' */ +# define __LA_MODE_T int +#elif defined(_WIN32) && !defined(__CYGWIN__) && !defined(__BORLANDC__) && !defined(__WATCOMC__) +# define __LA_MODE_T unsigned short +#else +# define __LA_MODE_T mode_t +#endif + +/* Large file support for Android */ +#ifdef __ANDROID__ +#include "android_lf.h" +#endif + +/* + * On Windows, define LIBARCHIVE_STATIC if you're building or using a + * .lib. The default here assumes you're building a DLL. Only + * libarchive source should ever define __LIBARCHIVE_BUILD. + */ +#if ((defined __WIN32__) || (defined _WIN32) || defined(__CYGWIN__)) && (!defined LIBARCHIVE_STATIC) +# ifdef __LIBARCHIVE_BUILD +# ifdef __GNUC__ +# define __LA_DECL __attribute__((dllexport)) extern +# else +# define __LA_DECL __declspec(dllexport) +# endif +# else +# ifdef __GNUC__ +# define __LA_DECL +# else +# define __LA_DECL __declspec(dllimport) +# endif +# endif +#else +/* Static libraries on all platforms and shared libraries on non-Windows. */ +# define __LA_DECL +#endif + +#if defined(__GNUC__) && __GNUC__ >= 3 && __GNUC_MINOR__ >= 1 +# define __LA_DEPRECATED __attribute__((deprecated)) +#else +# define __LA_DEPRECATED +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Description of an archive entry. + * + * You can think of this as "struct stat" with some text fields added in. + * + * TODO: Add "comment", "charset", and possibly other entries that are + * supported by "pax interchange" format. However, GNU, ustar, cpio, + * and other variants don't support these features, so they're not an + * excruciatingly high priority right now. + * + * TODO: "pax interchange" format allows essentially arbitrary + * key/value attributes to be attached to any entry. Supporting + * such extensions may make this library useful for special + * applications (e.g., a package manager could attach special + * package-management attributes to each entry). + */ +struct archive; +struct archive_entry; + +/* + * File-type constants. These are returned from archive_entry_filetype() + * and passed to archive_entry_set_filetype(). + * + * These values match S_XXX defines on every platform I've checked, + * including Windows, AIX, Linux, Solaris, and BSD. They're + * (re)defined here because platforms generally don't define the ones + * they don't support. For example, Windows doesn't define S_IFLNK or + * S_IFBLK. Instead of having a mass of conditional logic and system + * checks to define any S_XXX values that aren't supported locally, + * I've just defined a new set of such constants so that + * libarchive-based applications can manipulate and identify archive + * entries properly even if the hosting platform can't store them on + * disk. + * + * These values are also used directly within some portable formats, + * such as cpio. If you find a platform that varies from these, the + * correct solution is to leave these alone and translate from these + * portable values to platform-native values when entries are read from + * or written to disk. + */ +/* + * In libarchive 4.0, we can drop the casts here. + * They're needed to work around Borland C's broken mode_t. + */ +#define AE_IFMT ((__LA_MODE_T)0170000) +#define AE_IFREG ((__LA_MODE_T)0100000) +#define AE_IFLNK ((__LA_MODE_T)0120000) +#define AE_IFSOCK ((__LA_MODE_T)0140000) +#define AE_IFCHR ((__LA_MODE_T)0020000) +#define AE_IFBLK ((__LA_MODE_T)0060000) +#define AE_IFDIR ((__LA_MODE_T)0040000) +#define AE_IFIFO ((__LA_MODE_T)0010000) + +/* + * Symlink types + */ +#define AE_SYMLINK_TYPE_UNDEFINED 0 +#define AE_SYMLINK_TYPE_FILE 1 +#define AE_SYMLINK_TYPE_DIRECTORY 2 + +/* + * Basic object manipulation + */ + +__LA_DECL struct archive_entry *archive_entry_clear(struct archive_entry *); +/* The 'clone' function does a deep copy; all of the strings are copied too. */ +__LA_DECL struct archive_entry *archive_entry_clone(struct archive_entry *); +__LA_DECL void archive_entry_free(struct archive_entry *); +__LA_DECL struct archive_entry *archive_entry_new(void); + +/* + * This form of archive_entry_new2() will pull character-set + * conversion information from the specified archive handle. The + * older archive_entry_new(void) form is equivalent to calling + * archive_entry_new2(NULL) and will result in the use of an internal + * default character-set conversion. + */ +__LA_DECL struct archive_entry *archive_entry_new2(struct archive *); + +/* + * Retrieve fields from an archive_entry. + * + * There are a number of implicit conversions among these fields. For + * example, if a regular string field is set and you read the _w wide + * character field, the entry will implicitly convert narrow-to-wide + * using the current locale. Similarly, dev values are automatically + * updated when you write devmajor or devminor and vice versa. + * + * In addition, fields can be "set" or "unset." Unset string fields + * return NULL, non-string fields have _is_set() functions to test + * whether they've been set. You can "unset" a string field by + * assigning NULL; non-string fields have _unset() functions to + * unset them. + * + * Note: There is one ambiguity in the above; string fields will + * also return NULL when implicit character set conversions fail. + * This is usually what you want. + */ +__LA_DECL time_t archive_entry_atime(struct archive_entry *); +__LA_DECL long archive_entry_atime_nsec(struct archive_entry *); +__LA_DECL int archive_entry_atime_is_set(struct archive_entry *); +__LA_DECL time_t archive_entry_birthtime(struct archive_entry *); +__LA_DECL long archive_entry_birthtime_nsec(struct archive_entry *); +__LA_DECL int archive_entry_birthtime_is_set(struct archive_entry *); +__LA_DECL time_t archive_entry_ctime(struct archive_entry *); +__LA_DECL long archive_entry_ctime_nsec(struct archive_entry *); +__LA_DECL int archive_entry_ctime_is_set(struct archive_entry *); +__LA_DECL dev_t archive_entry_dev(struct archive_entry *); +__LA_DECL int archive_entry_dev_is_set(struct archive_entry *); +__LA_DECL dev_t archive_entry_devmajor(struct archive_entry *); +__LA_DECL dev_t archive_entry_devminor(struct archive_entry *); +__LA_DECL __LA_MODE_T archive_entry_filetype(struct archive_entry *); +__LA_DECL void archive_entry_fflags(struct archive_entry *, + unsigned long * /* set */, + unsigned long * /* clear */); +__LA_DECL const char *archive_entry_fflags_text(struct archive_entry *); +__LA_DECL la_int64_t archive_entry_gid(struct archive_entry *); +__LA_DECL const char *archive_entry_gname(struct archive_entry *); +__LA_DECL const char *archive_entry_gname_utf8(struct archive_entry *); +__LA_DECL const wchar_t *archive_entry_gname_w(struct archive_entry *); +__LA_DECL const char *archive_entry_hardlink(struct archive_entry *); +__LA_DECL const char *archive_entry_hardlink_utf8(struct archive_entry *); +__LA_DECL const wchar_t *archive_entry_hardlink_w(struct archive_entry *); +__LA_DECL la_int64_t archive_entry_ino(struct archive_entry *); +__LA_DECL la_int64_t archive_entry_ino64(struct archive_entry *); +__LA_DECL int archive_entry_ino_is_set(struct archive_entry *); +__LA_DECL __LA_MODE_T archive_entry_mode(struct archive_entry *); +__LA_DECL time_t archive_entry_mtime(struct archive_entry *); +__LA_DECL long archive_entry_mtime_nsec(struct archive_entry *); +__LA_DECL int archive_entry_mtime_is_set(struct archive_entry *); +__LA_DECL unsigned int archive_entry_nlink(struct archive_entry *); +__LA_DECL const char *archive_entry_pathname(struct archive_entry *); +__LA_DECL const char *archive_entry_pathname_utf8(struct archive_entry *); +__LA_DECL const wchar_t *archive_entry_pathname_w(struct archive_entry *); +__LA_DECL __LA_MODE_T archive_entry_perm(struct archive_entry *); +__LA_DECL dev_t archive_entry_rdev(struct archive_entry *); +__LA_DECL dev_t archive_entry_rdevmajor(struct archive_entry *); +__LA_DECL dev_t archive_entry_rdevminor(struct archive_entry *); +__LA_DECL const char *archive_entry_sourcepath(struct archive_entry *); +__LA_DECL const wchar_t *archive_entry_sourcepath_w(struct archive_entry *); +__LA_DECL la_int64_t archive_entry_size(struct archive_entry *); +__LA_DECL int archive_entry_size_is_set(struct archive_entry *); +__LA_DECL const char *archive_entry_strmode(struct archive_entry *); +__LA_DECL const char *archive_entry_symlink(struct archive_entry *); +__LA_DECL const char *archive_entry_symlink_utf8(struct archive_entry *); +__LA_DECL int archive_entry_symlink_type(struct archive_entry *); +__LA_DECL const wchar_t *archive_entry_symlink_w(struct archive_entry *); +__LA_DECL la_int64_t archive_entry_uid(struct archive_entry *); +__LA_DECL const char *archive_entry_uname(struct archive_entry *); +__LA_DECL const char *archive_entry_uname_utf8(struct archive_entry *); +__LA_DECL const wchar_t *archive_entry_uname_w(struct archive_entry *); +__LA_DECL int archive_entry_is_data_encrypted(struct archive_entry *); +__LA_DECL int archive_entry_is_metadata_encrypted(struct archive_entry *); +__LA_DECL int archive_entry_is_encrypted(struct archive_entry *); + +/* + * Set fields in an archive_entry. + * + * Note: Before libarchive 2.4, there were 'set' and 'copy' versions + * of the string setters. 'copy' copied the actual string, 'set' just + * stored the pointer. In libarchive 2.4 and later, strings are + * always copied. + */ + +__LA_DECL void archive_entry_set_atime(struct archive_entry *, time_t, long); +__LA_DECL void archive_entry_unset_atime(struct archive_entry *); +#if defined(_WIN32) && !defined(__CYGWIN__) +__LA_DECL void archive_entry_copy_bhfi(struct archive_entry *, BY_HANDLE_FILE_INFORMATION *); +#endif +__LA_DECL void archive_entry_set_birthtime(struct archive_entry *, time_t, long); +__LA_DECL void archive_entry_unset_birthtime(struct archive_entry *); +__LA_DECL void archive_entry_set_ctime(struct archive_entry *, time_t, long); +__LA_DECL void archive_entry_unset_ctime(struct archive_entry *); +__LA_DECL void archive_entry_set_dev(struct archive_entry *, dev_t); +__LA_DECL void archive_entry_set_devmajor(struct archive_entry *, dev_t); +__LA_DECL void archive_entry_set_devminor(struct archive_entry *, dev_t); +__LA_DECL void archive_entry_set_filetype(struct archive_entry *, unsigned int); +__LA_DECL void archive_entry_set_fflags(struct archive_entry *, + unsigned long /* set */, unsigned long /* clear */); +/* Returns pointer to start of first invalid token, or NULL if none. */ +/* Note that all recognized tokens are processed, regardless. */ +__LA_DECL const char *archive_entry_copy_fflags_text(struct archive_entry *, + const char *); +__LA_DECL const wchar_t *archive_entry_copy_fflags_text_w(struct archive_entry *, + const wchar_t *); +__LA_DECL void archive_entry_set_gid(struct archive_entry *, la_int64_t); +__LA_DECL void archive_entry_set_gname(struct archive_entry *, const char *); +__LA_DECL void archive_entry_set_gname_utf8(struct archive_entry *, const char *); +__LA_DECL void archive_entry_copy_gname(struct archive_entry *, const char *); +__LA_DECL void archive_entry_copy_gname_w(struct archive_entry *, const wchar_t *); +__LA_DECL int archive_entry_update_gname_utf8(struct archive_entry *, const char *); +__LA_DECL void archive_entry_set_hardlink(struct archive_entry *, const char *); +__LA_DECL void archive_entry_set_hardlink_utf8(struct archive_entry *, const char *); +__LA_DECL void archive_entry_copy_hardlink(struct archive_entry *, const char *); +__LA_DECL void archive_entry_copy_hardlink_w(struct archive_entry *, const wchar_t *); +__LA_DECL int archive_entry_update_hardlink_utf8(struct archive_entry *, const char *); +__LA_DECL void archive_entry_set_ino(struct archive_entry *, la_int64_t); +__LA_DECL void archive_entry_set_ino64(struct archive_entry *, la_int64_t); +__LA_DECL void archive_entry_set_link(struct archive_entry *, const char *); +__LA_DECL void archive_entry_set_link_utf8(struct archive_entry *, const char *); +__LA_DECL void archive_entry_copy_link(struct archive_entry *, const char *); +__LA_DECL void archive_entry_copy_link_w(struct archive_entry *, const wchar_t *); +__LA_DECL int archive_entry_update_link_utf8(struct archive_entry *, const char *); +__LA_DECL void archive_entry_set_mode(struct archive_entry *, __LA_MODE_T); +__LA_DECL void archive_entry_set_mtime(struct archive_entry *, time_t, long); +__LA_DECL void archive_entry_unset_mtime(struct archive_entry *); +__LA_DECL void archive_entry_set_nlink(struct archive_entry *, unsigned int); +__LA_DECL void archive_entry_set_pathname(struct archive_entry *, const char *); +__LA_DECL void archive_entry_set_pathname_utf8(struct archive_entry *, const char *); +__LA_DECL void archive_entry_copy_pathname(struct archive_entry *, const char *); +__LA_DECL void archive_entry_copy_pathname_w(struct archive_entry *, const wchar_t *); +__LA_DECL int archive_entry_update_pathname_utf8(struct archive_entry *, const char *); +__LA_DECL void archive_entry_set_perm(struct archive_entry *, __LA_MODE_T); +__LA_DECL void archive_entry_set_rdev(struct archive_entry *, dev_t); +__LA_DECL void archive_entry_set_rdevmajor(struct archive_entry *, dev_t); +__LA_DECL void archive_entry_set_rdevminor(struct archive_entry *, dev_t); +__LA_DECL void archive_entry_set_size(struct archive_entry *, la_int64_t); +__LA_DECL void archive_entry_unset_size(struct archive_entry *); +__LA_DECL void archive_entry_copy_sourcepath(struct archive_entry *, const char *); +__LA_DECL void archive_entry_copy_sourcepath_w(struct archive_entry *, const wchar_t *); +__LA_DECL void archive_entry_set_symlink(struct archive_entry *, const char *); +__LA_DECL void archive_entry_set_symlink_type(struct archive_entry *, int); +__LA_DECL void archive_entry_set_symlink_utf8(struct archive_entry *, const char *); +__LA_DECL void archive_entry_copy_symlink(struct archive_entry *, const char *); +__LA_DECL void archive_entry_copy_symlink_w(struct archive_entry *, const wchar_t *); +__LA_DECL int archive_entry_update_symlink_utf8(struct archive_entry *, const char *); +__LA_DECL void archive_entry_set_uid(struct archive_entry *, la_int64_t); +__LA_DECL void archive_entry_set_uname(struct archive_entry *, const char *); +__LA_DECL void archive_entry_set_uname_utf8(struct archive_entry *, const char *); +__LA_DECL void archive_entry_copy_uname(struct archive_entry *, const char *); +__LA_DECL void archive_entry_copy_uname_w(struct archive_entry *, const wchar_t *); +__LA_DECL int archive_entry_update_uname_utf8(struct archive_entry *, const char *); +__LA_DECL void archive_entry_set_is_data_encrypted(struct archive_entry *, char is_encrypted); +__LA_DECL void archive_entry_set_is_metadata_encrypted(struct archive_entry *, char is_encrypted); +/* + * Routines to bulk copy fields to/from a platform-native "struct + * stat." Libarchive used to just store a struct stat inside of each + * archive_entry object, but this created issues when trying to + * manipulate archives on systems different than the ones they were + * created on. + * + * TODO: On Linux and other LFS systems, provide both stat32 and + * stat64 versions of these functions and all of the macro glue so + * that archive_entry_stat is magically defined to + * archive_entry_stat32 or archive_entry_stat64 as appropriate. + */ +__LA_DECL const struct stat *archive_entry_stat(struct archive_entry *); +__LA_DECL void archive_entry_copy_stat(struct archive_entry *, const struct stat *); + +/* + * Storage for Mac OS-specific AppleDouble metadata information. + * Apple-format tar files store a separate binary blob containing + * encoded metadata with ACL, extended attributes, etc. + * This provides a place to store that blob. + */ + +__LA_DECL const void * archive_entry_mac_metadata(struct archive_entry *, size_t *); +__LA_DECL void archive_entry_copy_mac_metadata(struct archive_entry *, const void *, size_t); + +/* + * ACL routines. This used to simply store and return text-format ACL + * strings, but that proved insufficient for a number of reasons: + * = clients need control over uname/uid and gname/gid mappings + * = there are many different ACL text formats + * = would like to be able to read/convert archives containing ACLs + * on platforms that lack ACL libraries + * + * This last point, in particular, forces me to implement a reasonably + * complete set of ACL support routines. + */ + +/* + * Permission bits. + */ +#define ARCHIVE_ENTRY_ACL_EXECUTE 0x00000001 +#define ARCHIVE_ENTRY_ACL_WRITE 0x00000002 +#define ARCHIVE_ENTRY_ACL_READ 0x00000004 +#define ARCHIVE_ENTRY_ACL_READ_DATA 0x00000008 +#define ARCHIVE_ENTRY_ACL_LIST_DIRECTORY 0x00000008 +#define ARCHIVE_ENTRY_ACL_WRITE_DATA 0x00000010 +#define ARCHIVE_ENTRY_ACL_ADD_FILE 0x00000010 +#define ARCHIVE_ENTRY_ACL_APPEND_DATA 0x00000020 +#define ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY 0x00000020 +#define ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS 0x00000040 +#define ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS 0x00000080 +#define ARCHIVE_ENTRY_ACL_DELETE_CHILD 0x00000100 +#define ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES 0x00000200 +#define ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES 0x00000400 +#define ARCHIVE_ENTRY_ACL_DELETE 0x00000800 +#define ARCHIVE_ENTRY_ACL_READ_ACL 0x00001000 +#define ARCHIVE_ENTRY_ACL_WRITE_ACL 0x00002000 +#define ARCHIVE_ENTRY_ACL_WRITE_OWNER 0x00004000 +#define ARCHIVE_ENTRY_ACL_SYNCHRONIZE 0x00008000 + +#define ARCHIVE_ENTRY_ACL_PERMS_POSIX1E \ + (ARCHIVE_ENTRY_ACL_EXECUTE \ + | ARCHIVE_ENTRY_ACL_WRITE \ + | ARCHIVE_ENTRY_ACL_READ) + +#define ARCHIVE_ENTRY_ACL_PERMS_NFS4 \ + (ARCHIVE_ENTRY_ACL_EXECUTE \ + | ARCHIVE_ENTRY_ACL_READ_DATA \ + | ARCHIVE_ENTRY_ACL_LIST_DIRECTORY \ + | ARCHIVE_ENTRY_ACL_WRITE_DATA \ + | ARCHIVE_ENTRY_ACL_ADD_FILE \ + | ARCHIVE_ENTRY_ACL_APPEND_DATA \ + | ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY \ + | ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS \ + | ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS \ + | ARCHIVE_ENTRY_ACL_DELETE_CHILD \ + | ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES \ + | ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES \ + | ARCHIVE_ENTRY_ACL_DELETE \ + | ARCHIVE_ENTRY_ACL_READ_ACL \ + | ARCHIVE_ENTRY_ACL_WRITE_ACL \ + | ARCHIVE_ENTRY_ACL_WRITE_OWNER \ + | ARCHIVE_ENTRY_ACL_SYNCHRONIZE) + +/* + * Inheritance values (NFS4 ACLs only); included in permset. + */ +#define ARCHIVE_ENTRY_ACL_ENTRY_INHERITED 0x01000000 +#define ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT 0x02000000 +#define ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT 0x04000000 +#define ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT 0x08000000 +#define ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY 0x10000000 +#define ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS 0x20000000 +#define ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS 0x40000000 + +#define ARCHIVE_ENTRY_ACL_INHERITANCE_NFS4 \ + (ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT \ + | ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT \ + | ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT \ + | ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY \ + | ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS \ + | ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS \ + | ARCHIVE_ENTRY_ACL_ENTRY_INHERITED) + +/* We need to be able to specify combinations of these. */ +#define ARCHIVE_ENTRY_ACL_TYPE_ACCESS 0x00000100 /* POSIX.1e only */ +#define ARCHIVE_ENTRY_ACL_TYPE_DEFAULT 0x00000200 /* POSIX.1e only */ +#define ARCHIVE_ENTRY_ACL_TYPE_ALLOW 0x00000400 /* NFS4 only */ +#define ARCHIVE_ENTRY_ACL_TYPE_DENY 0x00000800 /* NFS4 only */ +#define ARCHIVE_ENTRY_ACL_TYPE_AUDIT 0x00001000 /* NFS4 only */ +#define ARCHIVE_ENTRY_ACL_TYPE_ALARM 0x00002000 /* NFS4 only */ +#define ARCHIVE_ENTRY_ACL_TYPE_POSIX1E (ARCHIVE_ENTRY_ACL_TYPE_ACCESS \ + | ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) +#define ARCHIVE_ENTRY_ACL_TYPE_NFS4 (ARCHIVE_ENTRY_ACL_TYPE_ALLOW \ + | ARCHIVE_ENTRY_ACL_TYPE_DENY \ + | ARCHIVE_ENTRY_ACL_TYPE_AUDIT \ + | ARCHIVE_ENTRY_ACL_TYPE_ALARM) + +/* Tag values mimic POSIX.1e */ +#define ARCHIVE_ENTRY_ACL_USER 10001 /* Specified user. */ +#define ARCHIVE_ENTRY_ACL_USER_OBJ 10002 /* User who owns the file. */ +#define ARCHIVE_ENTRY_ACL_GROUP 10003 /* Specified group. */ +#define ARCHIVE_ENTRY_ACL_GROUP_OBJ 10004 /* Group who owns the file. */ +#define ARCHIVE_ENTRY_ACL_MASK 10005 /* Modify group access (POSIX.1e only) */ +#define ARCHIVE_ENTRY_ACL_OTHER 10006 /* Public (POSIX.1e only) */ +#define ARCHIVE_ENTRY_ACL_EVERYONE 10107 /* Everyone (NFS4 only) */ + +/* + * Set the ACL by clearing it and adding entries one at a time. + * Unlike the POSIX.1e ACL routines, you must specify the type + * (access/default) for each entry. Internally, the ACL data is just + * a soup of entries. API calls here allow you to retrieve just the + * entries of interest. This design (which goes against the spirit of + * POSIX.1e) is useful for handling archive formats that combine + * default and access information in a single ACL list. + */ +__LA_DECL void archive_entry_acl_clear(struct archive_entry *); +__LA_DECL int archive_entry_acl_add_entry(struct archive_entry *, + int /* type */, int /* permset */, int /* tag */, + int /* qual */, const char * /* name */); +__LA_DECL int archive_entry_acl_add_entry_w(struct archive_entry *, + int /* type */, int /* permset */, int /* tag */, + int /* qual */, const wchar_t * /* name */); + +/* + * To retrieve the ACL, first "reset", then repeatedly ask for the + * "next" entry. The want_type parameter allows you to request only + * certain types of entries. + */ +__LA_DECL int archive_entry_acl_reset(struct archive_entry *, int /* want_type */); +__LA_DECL int archive_entry_acl_next(struct archive_entry *, int /* want_type */, + int * /* type */, int * /* permset */, int * /* tag */, + int * /* qual */, const char ** /* name */); + +/* + * Construct a text-format ACL. The flags argument is a bitmask that + * can include any of the following: + * + * Flags only for archive entries with POSIX.1e ACL: + * ARCHIVE_ENTRY_ACL_TYPE_ACCESS - Include POSIX.1e "access" entries. + * ARCHIVE_ENTRY_ACL_TYPE_DEFAULT - Include POSIX.1e "default" entries. + * ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT - Include "default:" before each + * default ACL entry. + * ARCHIVE_ENTRY_ACL_STYLE_SOLARIS - Output only one colon after "other" and + * "mask" entries. + * + * Flags only for archive entries with NFSv4 ACL: + * ARCHIVE_ENTRY_ACL_STYLE_COMPACT - Do not output the minus character for + * unset permissions and flags in NFSv4 ACL permission and flag fields + * + * Flags for for archive entries with POSIX.1e ACL or NFSv4 ACL: + * ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID - Include extra numeric ID field in + * each ACL entry. + * ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA - Separate entries with comma + * instead of newline. + */ +#define ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID 0x00000001 +#define ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT 0x00000002 +#define ARCHIVE_ENTRY_ACL_STYLE_SOLARIS 0x00000004 +#define ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA 0x00000008 +#define ARCHIVE_ENTRY_ACL_STYLE_COMPACT 0x00000010 + +__LA_DECL wchar_t *archive_entry_acl_to_text_w(struct archive_entry *, + la_ssize_t * /* len */, int /* flags */); +__LA_DECL char *archive_entry_acl_to_text(struct archive_entry *, + la_ssize_t * /* len */, int /* flags */); +__LA_DECL int archive_entry_acl_from_text_w(struct archive_entry *, + const wchar_t * /* wtext */, int /* type */); +__LA_DECL int archive_entry_acl_from_text(struct archive_entry *, + const char * /* text */, int /* type */); + +/* Deprecated constants */ +#define OLD_ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID 1024 +#define OLD_ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT 2048 + +/* Deprecated functions */ +__LA_DECL const wchar_t *archive_entry_acl_text_w(struct archive_entry *, + int /* flags */) __LA_DEPRECATED; +__LA_DECL const char *archive_entry_acl_text(struct archive_entry *, + int /* flags */) __LA_DEPRECATED; + +/* Return bitmask of ACL types in an archive entry */ +__LA_DECL int archive_entry_acl_types(struct archive_entry *); + +/* Return a count of entries matching 'want_type' */ +__LA_DECL int archive_entry_acl_count(struct archive_entry *, int /* want_type */); + +/* Return an opaque ACL object. */ +/* There's not yet anything clients can actually do with this... */ +struct archive_acl; +__LA_DECL struct archive_acl *archive_entry_acl(struct archive_entry *); + +/* + * extended attributes + */ + +__LA_DECL void archive_entry_xattr_clear(struct archive_entry *); +__LA_DECL void archive_entry_xattr_add_entry(struct archive_entry *, + const char * /* name */, const void * /* value */, + size_t /* size */); + +/* + * To retrieve the xattr list, first "reset", then repeatedly ask for the + * "next" entry. + */ + +__LA_DECL int archive_entry_xattr_count(struct archive_entry *); +__LA_DECL int archive_entry_xattr_reset(struct archive_entry *); +__LA_DECL int archive_entry_xattr_next(struct archive_entry *, + const char ** /* name */, const void ** /* value */, size_t *); + +/* + * sparse + */ + +__LA_DECL void archive_entry_sparse_clear(struct archive_entry *); +__LA_DECL void archive_entry_sparse_add_entry(struct archive_entry *, + la_int64_t /* offset */, la_int64_t /* length */); + +/* + * To retrieve the xattr list, first "reset", then repeatedly ask for the + * "next" entry. + */ + +__LA_DECL int archive_entry_sparse_count(struct archive_entry *); +__LA_DECL int archive_entry_sparse_reset(struct archive_entry *); +__LA_DECL int archive_entry_sparse_next(struct archive_entry *, + la_int64_t * /* offset */, la_int64_t * /* length */); + +/* + * Utility to match up hardlinks. + * + * The 'struct archive_entry_linkresolver' is a cache of archive entries + * for files with multiple links. Here's how to use it: + * 1. Create a lookup object with archive_entry_linkresolver_new() + * 2. Tell it the archive format you're using. + * 3. Hand each archive_entry to archive_entry_linkify(). + * That function will return 0, 1, or 2 entries that should + * be written. + * 4. Call archive_entry_linkify(resolver, NULL) until + * no more entries are returned. + * 5. Call archive_entry_linkresolver_free(resolver) to free resources. + * + * The entries returned have their hardlink and size fields updated + * appropriately. If an entry is passed in that does not refer to + * a file with multiple links, it is returned unchanged. The intention + * is that you should be able to simply filter all entries through + * this machine. + * + * To make things more efficient, be sure that each entry has a valid + * nlinks value. The hardlink cache uses this to track when all links + * have been found. If the nlinks value is zero, it will keep every + * name in the cache indefinitely, which can use a lot of memory. + * + * Note that archive_entry_size() is reset to zero if the file + * body should not be written to the archive. Pay attention! + */ +struct archive_entry_linkresolver; + +/* + * There are three different strategies for marking hardlinks. + * The descriptions below name them after the best-known + * formats that rely on each strategy: + * + * "Old cpio" is the simplest, it always returns any entry unmodified. + * As far as I know, only cpio formats use this. Old cpio archives + * store every link with the full body; the onus is on the dearchiver + * to detect and properly link the files as they are restored. + * "tar" is also pretty simple; it caches a copy the first time it sees + * any link. Subsequent appearances are modified to be hardlink + * references to the first one without any body. Used by all tar + * formats, although the newest tar formats permit the "old cpio" strategy + * as well. This strategy is very simple for the dearchiver, + * and reasonably straightforward for the archiver. + * "new cpio" is trickier. It stores the body only with the last + * occurrence. The complication is that we might not + * see every link to a particular file in a single session, so + * there's no easy way to know when we've seen the last occurrence. + * The solution here is to queue one link until we see the next. + * At the end of the session, you can enumerate any remaining + * entries by calling archive_entry_linkify(NULL) and store those + * bodies. If you have a file with three links l1, l2, and l3, + * you'll get the following behavior if you see all three links: + * linkify(l1) => NULL (the resolver stores l1 internally) + * linkify(l2) => l1 (resolver stores l2, you write l1) + * linkify(l3) => l2, l3 (all links seen, you can write both). + * If you only see l1 and l2, you'll get this behavior: + * linkify(l1) => NULL + * linkify(l2) => l1 + * linkify(NULL) => l2 (at end, you retrieve remaining links) + * As the name suggests, this strategy is used by newer cpio variants. + * It's noticeably more complex for the archiver, slightly more complex + * for the dearchiver than the tar strategy, but makes it straightforward + * to restore a file using any link by simply continuing to scan until + * you see a link that is stored with a body. In contrast, the tar + * strategy requires you to rescan the archive from the beginning to + * correctly extract an arbitrary link. + */ + +__LA_DECL struct archive_entry_linkresolver *archive_entry_linkresolver_new(void); +__LA_DECL void archive_entry_linkresolver_set_strategy( + struct archive_entry_linkresolver *, int /* format_code */); +__LA_DECL void archive_entry_linkresolver_free(struct archive_entry_linkresolver *); +__LA_DECL void archive_entry_linkify(struct archive_entry_linkresolver *, + struct archive_entry **, struct archive_entry **); +__LA_DECL struct archive_entry *archive_entry_partial_links( + struct archive_entry_linkresolver *res, unsigned int *links); +#ifdef __cplusplus +} +#endif + +/* This is meaningless outside of this header. */ +#undef __LA_DECL + +#endif /* !ARCHIVE_ENTRY_H_INCLUDED */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_acl.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_acl.3 new file mode 100644 index 0000000000..50dd642c20 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_acl.3 @@ -0,0 +1,458 @@ +.\" Copyright (c) 2010 Joerg Sonnenberger +.\" Copyright (c) 2016 Martin Matuska +.\" 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. +.\" +.Dd February 15, 2017 +.Dt ARCHIVE_ENTRY_ACL 3 +.Os +.Sh NAME +.Nm archive_entry_acl_add_entry , +.Nm archive_entry_acl_add_entry_w , +.Nm archive_entry_acl_clear , +.Nm archive_entry_acl_count , +.Nm archive_entry_acl_from_text , +.Nm archive_entry_acl_from_text_w , +.Nm archive_entry_acl_next , +.Nm archive_entry_acl_reset , +.Nm archive_entry_acl_to_text , +.Nm archive_entry_acl_to_text_w , +.Nm archive_entry_acl_types +.Nd functions for manipulating Access Control Lists in archive entry descriptions +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive_entry.h +.Ft void +.Fo archive_entry_acl_add_entry +.Fa "struct archive_entry *a" +.Fa "int type" +.Fa "int permset" +.Fa "int tag" +.Fa "int qualifier" +.Fa "const char *name" +.Fc +.Ft void +.Fo archive_entry_acl_add_entry_w +.Fa "struct archive_entry *a" +.Fa "int type" +.Fa "int permset" +.Fa "int tag" +.Fa "int qualifier" +.Fa "const wchar_t *name" +.Fc +.Ft void +.Fn archive_entry_acl_clear "struct archive_entry *a" +.Ft int +.Fn archive_entry_acl_count "struct archive_entry *a" "int type" +.Ft int +.Fo archive_entry_acl_from_text +.Fa "struct archive_entry *a" +.Fa "const char *text" +.Fa "int type" +.Fc +.Ft int +.Fo archive_entry_acl_from_text_w +.Fa "struct archive_entry *a" +.Fa "const wchar_t *text" +.Fa "int type" +.Fc +.Ft int +.Fo archive_entry_acl_next +.Fa "struct archive_entry *a" +.Fa "int type" +.Fa "int *ret_type" +.Fa "int *ret_permset" +.Fa "int *ret_tag" +.Fa "int *ret_qual" +.Fa "const char **ret_name" +.Fc +.Ft int +.Fn archive_entry_acl_reset "struct archive_entry *a" "int type" +.Ft char * +.Fo archive_entry_acl_to_text +.Fa "struct archive_entry *a" +.Fa "ssize_t *len_p" +.Fa "int flags" +.Fc +.Ft wchar_t * +.Fo archive_entry_acl_to_text_w +.Fa "struct archive_entry *a" +.Fa "ssize_t *len_p" +.Fa "int flags" +.Fc +.Ft int +.Fn archive_entry_acl_types "struct archive_entry *a" +.\" enum? +.Sh DESCRIPTION +The +.Dq Access Control Lists (ACLs) +extend the standard Unix permission model. +The ACL interface of +.Nm libarchive +supports both POSIX.1e and NFSv4 style ACLs. +Use of ACLs is restricted by +various levels of ACL support in operating systems, file systems and archive +formats. +.Ss POSIX.1e Access Control Lists +A POSIX.1e ACL consists of a number of independent entries. +Each entry specifies the permission set as a bitmask of basic permissions. +Valid permissions in the +.Fa permset +are: +.Bl -tag -offset indent -compact -width "ARCHIVE_ENTRY_ACL_EXECUTE" +.It Dv ARCHIVE_ENTRY_ACL_READ ( Sy r ) +.It Dv ARCHIVE_ENTRY_ACL_WRITE ( Sy w ) +.It Dv ARCHIVE_ENTRY_ACL_EXECUTE ( Sy x ) +.El +The permissions correspond to the normal Unix permissions. +.Pp +The +.Fa tag +specifies the principal to which the permission applies. +Valid values are: +.Bl -hang -offset indent -compact -width "ARCHIVE_ENTRY_ACL_GROUP_OBJ" +.It Dv ARCHIVE_ENTRY_ACL_USER +The user specified by the name field. +.It Dv ARCHIVE_ENTRY_ACL_USER_OBJ +The owner of the file. +.It Dv ARCHIVE_ENTRY_ACL_GROUP +The group specified by the name field. +.It Dv ARCHIVE_ENTRY_ACL_GROUP_OBJ +The group which owns the file. +.It Dv ARCHIVE_ENTRY_ACL_MASK +The maximum permissions to be obtained via group permissions. +.It Dv ARCHIVE_ENTRY_ACL_OTHER +Any principal who is not the file owner or a member of the owning group. +.El +.Pp +The principals +.Dv ARCHIVE_ENTRY_ACL_USER_OBJ , +.Dv ARCHIVE_ENTRY_ACL_GROUP_OBJ +and +.Dv ARCHIVE_ENTRY_ACL_OTHER +are equivalent to user, group and other in the classic Unix permission +model and specify non-extended ACL entries. +.Pp +All files have an access ACL +.Pq Dv ARCHIVE_ENTRY_ACL_TYPE_ACCESS . +This specifies the permissions required for access to the file itself. +Directories have an additional ACL +.Pq Dv ARCHIVE_ENTRY_ACL_TYPE_DEFAULT , +which controls the initial access ACL for newly-created directory entries. +.Ss NFSv4 Access Control Lists +A NFSv4 ACL consists of multiple individual entries called Access Control +Entries (ACEs). +.Pp +There are four possible types of a NFSv4 ACE: +.Bl -hang -offset indent -compact -width "ARCHIVE_ENTRY_ACL_TYE_ALLOW" +.It Dv ARCHIVE_ENTRY_ACL_TYPE_ALLOW +Allow principal to perform actions requiring given permissions. +.It Dv ARCHIVE_ENTRY_ACL_TYPE_DENY +Prevent principal from performing actions requiring given permissions. +.It Dv ARCHIVE_ENTRY_ACL_TYPE_AUDIT +Log access attempts by principal which require given permissions. +.It Dv ARCHIVE_ENTRY_ACL_TYPE_ALARM +Trigger a system alarm on access attempts by principal which require given +permissions. +.El +.Pp +The +.Fa tag +specifies the principal to which the permission applies. +Valid values are: +.Bl -hang -offset indent -compact -width "ARCHIVE_ENTRY_ACL_GROUP_OBJ" +.It Dv ARCHIVE_ENTRY_ACL_USER +The user specified by the name field. +.It Dv ARCHIVE_ENTRY_ACL_USER_OBJ +The owner of the file. +.It Dv ARCHIVE_ENTRY_ACL_GROUP +The group specified by the name field. +.It Dv ARCHIVE_ENTRY_ACL_GROUP_OBJ +The group which owns the file. +.It Dv ARCHIVE_ENTRY_ACL_EVERYONE +Any principal who is not the file owner or a member of the owning group. +.El +.Pp +Entries with the +.Dv ARCHIVE_ENTRY_ACL_USER +or +.Dv ARCHIVE_ENTRY_ACL_GROUP +tag store the user and group name in the +.Fa name +string and optionally the user or group ID in the +.Fa qualifier +integer. +.Pp +NFSv4 ACE permissions and flags are stored in the same +.Fa permset +bitfield. +Some permissions share the same constant and permission character +but have different effect on directories than on files. +The following ACE permissions are supported: +.Bl -tag -offset indent -compact -width ARCHIV +.It Dv ARCHIVE_ENTRY_ACL_READ_DATA ( Sy r ) +Read data (file). +.It Dv ARCHIVE_ENTRY_ACL_LIST_DIRECTORY ( Sy r ) +List entries (directory). +.It ARCHIVE_ENTRY_ACL_WRITE_DATA ( Sy w ) +Write data (file). +.It ARCHIVE_ENTRY_ACL_ADD_FILE ( Sy w ) +Create files (directory). +.It Dv ARCHIVE_ENTRY_ACL_EXECUTE ( Sy x ) +Execute file or change into a directory. +.It Dv ARCHIVE_ENTRY_ACL_APPEND_DATA ( Sy p ) +Append data (file). +.It Dv ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY ( Sy p ) +Create subdirectories (directory). +.It Dv ARCHIVE_ENTRY_ACL_DELETE_CHILD ( Sy D ) +Remove files and subdirectories inside a directory. +.It Dv ARCHIVE_ENTRY_ACL_DELETE ( Sy d ) +Remove file or directory. +.It Dv ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES ( Sy a ) +Read file or directory attributes. +.It Dv ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES ( Sy A ) +Write file or directory attributes. +.It Dv ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS ( Sy R ) +Read named file or directory attributes. +.It Dv ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS ( Sy W ) +Write named file or directory attributes. +.It Dv ARCHIVE_ENTRY_ACL_READ_ACL ( Sy c ) +Read file or directory ACL. +.It Dv ARCHIVE_ENTRY_ACL_WRITE_ACL ( Sy C ) +Write file or directory ACL. +.It Dv ARCHIVE_ENTRY_ACL_WRITE_OWNER ( Sy o ) +Change owner of a file or directory. +.It Dv ARCHIVE_ENTRY_ACL_SYNCHRONIZE ( Sy s ) +Use synchronous I/O. +.El +.Pp +The following NFSv4 ACL inheritance flags are supported: +.Bl -tag -offset indent -compact -width ARCHIV +.It Dv ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT ( Sy f ) +Inherit parent directory ACE to files. +.It Dv ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT ( Sy d ) +Inherit parent directory ACE to subdirectories. +.It Dv ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY ( Sy i ) +Only inherit, do not apply the permission on the directory itself. +.It Dv ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT ( Sy n ) +Do not propagate inherit flags. +Only first-level entries inherit ACLs. +.It Dv ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS ( Sy S ) +Trigger alarm or audit on successful access. +.It Dv ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS ( Sy F ) +Trigger alarm or audit on failed access. +.It Dv ARCHIVE_ENTRY_ACL_ENTRY_INHERITED ( Sy I ) +Mark that ACE was inherited. +.El +.Ss Functions +.Fn archive_entry_acl_add_entry +and +.Fn archive_entry_acl_add_entry_w +add a single ACL entry. +For the access ACL and non-extended principals, the classic Unix permissions +are updated. +An archive entry cannot contain both POSIX.1e and NFSv4 ACL entries. +.Pp +.Fn archive_entry_acl_clear +removes all ACL entries and resets the enumeration pointer. +.Pp +.Fn archive_entry_acl_count +counts the ACL entries that have the given type mask. +.Fa type +can be the bitwise-or of +.Bl -tag -offset indent -compact -width "ARCHIVE_ENTRY_ACL_TYPE_DEFAULT" +.It Dv ARCHIVE_ENTRY_ACL_TYPE_ACCESS +.It Dv ARCHIVE_ENTRY_ACL_TYPE_DEFAULT +.El +for POSIX.1e ACLs and +.Bl -tag -offset indent -compact -width "ARCHIVE_ENTRY_ACL_TYPE_ALLOW" +.It Dv ARCHIVE_ENTRY_ACL_TYPE_ALLOW +.It Dv ARCHIVE_ENTRY_ACL_TYPE_DENY +.It Dv ARCHIVE_ENTRY_ACL_TYPE_AUDIT +.It Dv ARCHIVE_ENTRY_ACL_TYPE_ALARM +.El +for NFSv4 ACLs. +For POSIX.1e ACLs if +.Dv ARCHIVE_ENTRY_ACL_TYPE_ACCESS +is included and at least one extended ACL entry is found, +the three non-extended ACLs are added. +.Pp +.Fn archive_entry_acl_from_text +and +.Fn archive_entry_acl_from_text_w +add new +.Pq or merge with existing +ACL entries from +.Pq wide +text. +The argument +.Fa type +may take one of the following values: +.Bl -tag -offset indent -compact -width "ARCHIVE_ENTRY_ACL_TYPE_DEFAULT" +.It Dv ARCHIVE_ENTRY_ACL_TYPE_ACCESS +.It Dv ARCHIVE_ENTRY_ACL_TYPE_DEFAULT +.It Dv ARCHIVE_ENTRY_ACL_TYPE_NFS4 +.El +Supports all formats that can be created with +.Fn archive_entry_acl_to_text +or respectively +.Fn archive_entry_acl_to_text_w . +Existing ACL entries are preserved. +To get a clean new ACL from text +.Fn archive_entry_acl_clear +must be called first. +Entries prefixed with +.Dq default: +are treated as +.Dv ARCHIVE_ENTRY_ACL_TYPE_DEFAULT +unless +.Fa type +is +.Dv ARCHIVE_ENTRY_ACL_TYPE_NFS4 . +Invalid entries, non-parseable ACL entries and entries beginning with +the +.Sq # +character +.Pq comments +are skipped. +.Pp +.Fn archive_entry_acl_next +return the next entry of the ACL list. +This functions may only be called after +.Fn archive_entry_acl_reset +has indicated the presence of extended ACL entries. +.Pp +.Fn archive_entry_acl_reset +prepare reading the list of ACL entries with +.Fn archive_entry_acl_next . +The function returns 0 if no non-extended ACLs are found. +In this case, the access permissions should be obtained by +.Xr archive_entry_mode 3 +or set using +.Xr chmod 2 . +Otherwise, the function returns the same value as +.Fn archive_entry_acl_count . +.Pp +.Fn archive_entry_acl_to_text +and +.Fn archive_entry_acl_to_text_w +convert the ACL entries for the given type into a +.Pq wide +string of ACL entries separated by newline. +If the pointer +.Fa len_p +is not NULL, then the function shall return the length of the string +.Pq not including the NULL terminator +in the location pointed to by +.Fa len_p . +The +.Fa flag +argument is a bitwise-or. +.Pp +The following flags are effective only on POSIX.1e ACL: +.Bl -tag -offset indent -compact -width ARCHIV +.It Dv ARCHIVE_ENTRY_ACL_TYPE_ACCESS +Output access ACLs. +.It Dv ARCHIVE_ENTRY_ACL_TYPE_DEFAULT +Output POSIX.1e default ACLs. +.It Dv ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT +Prefix each default ACL entry with the word +.Dq default: . +.It Dv ARCHIVE_ENTRY_ACL_STYLE_SOLARIS +The mask and other ACLs don not contain a double colon. +.El +.Pp +The following flags are effecive only on NFSv4 ACL: +.Bl -tag -offset indent -compact -width ARCHIV +.It Dv ARCHIVE_ENTRY_ACL_STYLE_COMPACT +Do not output minus characters for unset permissions and flags in NFSv4 ACL +permission and flag fields. +.El +.Pp +The following flags are effective on both POSIX.1e and NFSv4 ACL: +.Bl -tag -offset indent -compact -width ARCHIV +.It Dv ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID +Add an additional colon-separated field containing the user or group id. +.It Dv ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA +Separate ACL entries with comma instead of newline. +.El +.Pp +If the archive entry contains NFSv4 ACLs, all types of NFSv4 ACLs are returned. +It the entry contains POSIX.1e ACLs and none of the flags +.Dv ARCHIVE_ENTRY_ACL_TYPE_ACCESS +or +.Dv ARCHIVE_ENTRY_ACL_TYPE_DEFAULT +are specified, both access and default entries are returned and default entries +are prefixed with +.Dq default: . +.Pp +.Fn archive_entry_acl_types +get ACL entry types contained in an archive entry's ACL. +As POSIX.1e and NFSv4 +ACL entries cannot be mixed, this function is a very efficient way to detect if +an ACL already contains POSIX.1e or NFSv4 ACL entries. +.Sh RETURN VALUES +.Fn archive_entry_acl_count +and +.Fn archive_entry_acl_reset +returns the number of ACL entries that match the given type mask. +For POSIX.1e ACLS if the type mask includes +.Dv ARCHIVE_ENTRY_ACL_TYPE_ACCESS +and at least one extended ACL entry exists, the three classic Unix +permissions are counted. +.Pp +.Fn archive_entry_acl_from_text +and +.Fn archive_entry_acl_from_text_w +return +.Dv ARCHIVE_OK +if all entries were successfully parsed and +.Dv ARCHIVE_WARN +if one or more entries were invalid or non-parseable. +.Pp +.Fn archive_entry_acl_next +returns +.Dv ARCHIVE_OK +on success, +.Dv ARCHIVE_EOF +if no more ACL entries exist +and +.Dv ARCHIVE_WARN +if +.Fn archive_entry_acl_reset +has not been called first. +.Pp +.Fn archive_entry_acl_to_text +returns a string representing the ACL entries matching the given type and +flags on success or NULL on error. +.Pp +.Fn archive_entry_acl_to_text_w +returns a wide string representing the ACL entries matching the given type +and flags on success or NULL on error. +.Pp +.Fn archive_entry_acl_types +returns a bitmask of ACL entry types or 0 if archive entry has no ACL entries. +.Sh SEE ALSO +.Xr archive_entry 3 , +.Xr libarchive 3 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_copy_bhfi.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_copy_bhfi.c new file mode 100644 index 0000000000..77bf38e450 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_copy_bhfi.c @@ -0,0 +1,75 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#include "archive_private.h" +#include "archive_entry.h" + +#if defined(_WIN32) && !defined(__CYGWIN__) + +#define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000) + +__inline static void +fileTimeToUtc(const FILETIME *filetime, time_t *t, long *ns) +{ + ULARGE_INTEGER utc; + + utc.HighPart = filetime->dwHighDateTime; + utc.LowPart = filetime->dwLowDateTime; + if (utc.QuadPart >= EPOC_TIME) { + utc.QuadPart -= EPOC_TIME; + *t = (time_t)(utc.QuadPart / 10000000); /* milli seconds base */ + *ns = (long)(utc.QuadPart % 10000000) * 100;/* nano seconds base */ + } else { + *t = 0; + *ns = 0; + } +} + +void +archive_entry_copy_bhfi(struct archive_entry *entry, + BY_HANDLE_FILE_INFORMATION *bhfi) +{ + time_t secs; + long nsecs; + + fileTimeToUtc(&bhfi->ftLastAccessTime, &secs, &nsecs); + archive_entry_set_atime(entry, secs, nsecs); + fileTimeToUtc(&bhfi->ftLastWriteTime, &secs, &nsecs); + archive_entry_set_mtime(entry, secs, nsecs); + fileTimeToUtc(&bhfi->ftCreationTime, &secs, &nsecs); + archive_entry_set_birthtime(entry, secs, nsecs); + archive_entry_set_ctime(entry, secs, nsecs); + archive_entry_set_dev(entry, bhfi->dwVolumeSerialNumber); + archive_entry_set_ino64(entry, (((int64_t)bhfi->nFileIndexHigh) << 32) + + bhfi->nFileIndexLow); + archive_entry_set_nlink(entry, bhfi->nNumberOfLinks); + archive_entry_set_size(entry, (((int64_t)bhfi->nFileSizeHigh) << 32) + + bhfi->nFileSizeLow); + /* archive_entry_set_mode(entry, st->st_mode); */ +} +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_copy_stat.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_copy_stat.c new file mode 100644 index 0000000000..ac83868e8f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_copy_stat.c @@ -0,0 +1,83 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_entry_copy_stat.c 189466 2009-03-07 00:52:02Z kientzle $"); + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif + +#include "archive.h" +#include "archive_entry.h" + +void +archive_entry_copy_stat(struct archive_entry *entry, const struct stat *st) +{ +#if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC + archive_entry_set_atime(entry, st->st_atime, st->st_atimespec.tv_nsec); + archive_entry_set_ctime(entry, st->st_ctime, st->st_ctimespec.tv_nsec); + archive_entry_set_mtime(entry, st->st_mtime, st->st_mtimespec.tv_nsec); +#elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC + archive_entry_set_atime(entry, st->st_atime, st->st_atim.tv_nsec); + archive_entry_set_ctime(entry, st->st_ctime, st->st_ctim.tv_nsec); + archive_entry_set_mtime(entry, st->st_mtime, st->st_mtim.tv_nsec); +#elif HAVE_STRUCT_STAT_ST_MTIME_NSEC + archive_entry_set_atime(entry, st->st_atime, st->st_atime_nsec); + archive_entry_set_ctime(entry, st->st_ctime, st->st_ctime_nsec); + archive_entry_set_mtime(entry, st->st_mtime, st->st_mtime_nsec); +#elif HAVE_STRUCT_STAT_ST_MTIME_N + archive_entry_set_atime(entry, st->st_atime, st->st_atime_n); + archive_entry_set_ctime(entry, st->st_ctime, st->st_ctime_n); + archive_entry_set_mtime(entry, st->st_mtime, st->st_mtime_n); +#elif HAVE_STRUCT_STAT_ST_UMTIME + archive_entry_set_atime(entry, st->st_atime, st->st_uatime * 1000); + archive_entry_set_ctime(entry, st->st_ctime, st->st_uctime * 1000); + archive_entry_set_mtime(entry, st->st_mtime, st->st_umtime * 1000); +#elif HAVE_STRUCT_STAT_ST_MTIME_USEC + archive_entry_set_atime(entry, st->st_atime, st->st_atime_usec * 1000); + archive_entry_set_ctime(entry, st->st_ctime, st->st_ctime_usec * 1000); + archive_entry_set_mtime(entry, st->st_mtime, st->st_mtime_usec * 1000); +#else + archive_entry_set_atime(entry, st->st_atime, 0); + archive_entry_set_ctime(entry, st->st_ctime, 0); + archive_entry_set_mtime(entry, st->st_mtime, 0); +#endif +#if HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC + archive_entry_set_birthtime(entry, st->st_birthtime, st->st_birthtimespec.tv_nsec); +#elif HAVE_STRUCT_STAT_ST_BIRTHTIME + archive_entry_set_birthtime(entry, st->st_birthtime, 0); +#else + archive_entry_unset_birthtime(entry); +#endif + archive_entry_set_dev(entry, st->st_dev); + archive_entry_set_gid(entry, st->st_gid); + archive_entry_set_uid(entry, st->st_uid); + archive_entry_set_ino(entry, st->st_ino); + archive_entry_set_nlink(entry, st->st_nlink); + archive_entry_set_rdev(entry, st->st_rdev); + archive_entry_set_size(entry, st->st_size); + archive_entry_set_mode(entry, st->st_mode); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_link_resolver.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_link_resolver.c new file mode 100644 index 0000000000..c7d59497a7 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_link_resolver.c @@ -0,0 +1,447 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_entry_link_resolver.c 201100 2009-12-28 03:05:31Z kientzle $"); + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_entry.h" + +/* + * This is mostly a pretty straightforward hash table implementation. + * The only interesting bit is the different strategies used to + * match up links. These strategies match those used by various + * archiving formats: + * tar - content stored with first link, remainder refer back to it. + * This requires us to match each subsequent link up with the + * first appearance. + * cpio - Old cpio just stored body with each link, match-ups were + * implicit. This is trivial. + * new cpio - New cpio only stores body with last link, match-ups + * are implicit. This is actually quite tricky; see the notes + * below. + */ + +/* Users pass us a format code, we translate that into a strategy here. */ +#define ARCHIVE_ENTRY_LINKIFY_LIKE_TAR 0 +#define ARCHIVE_ENTRY_LINKIFY_LIKE_MTREE 1 +#define ARCHIVE_ENTRY_LINKIFY_LIKE_OLD_CPIO 2 +#define ARCHIVE_ENTRY_LINKIFY_LIKE_NEW_CPIO 3 + +/* Initial size of link cache. */ +#define links_cache_initial_size 1024 + +struct links_entry { + struct links_entry *next; + struct links_entry *previous; + struct archive_entry *canonical; + struct archive_entry *entry; + size_t hash; + unsigned int links; /* # links not yet seen */ +}; + +struct archive_entry_linkresolver { + struct links_entry **buckets; + struct links_entry *spare; + unsigned long number_entries; + size_t number_buckets; + int strategy; +}; + +#define NEXT_ENTRY_DEFERRED 1 +#define NEXT_ENTRY_PARTIAL 2 +#define NEXT_ENTRY_ALL (NEXT_ENTRY_DEFERRED | NEXT_ENTRY_PARTIAL) + +static struct links_entry *find_entry(struct archive_entry_linkresolver *, + struct archive_entry *); +static void grow_hash(struct archive_entry_linkresolver *); +static struct links_entry *insert_entry(struct archive_entry_linkresolver *, + struct archive_entry *); +static struct links_entry *next_entry(struct archive_entry_linkresolver *, + int); + +struct archive_entry_linkresolver * +archive_entry_linkresolver_new(void) +{ + struct archive_entry_linkresolver *res; + + /* Check for positive power-of-two */ + if (links_cache_initial_size == 0 || + (links_cache_initial_size & (links_cache_initial_size - 1)) != 0) + return (NULL); + + res = calloc(1, sizeof(struct archive_entry_linkresolver)); + if (res == NULL) + return (NULL); + res->number_buckets = links_cache_initial_size; + res->buckets = calloc(res->number_buckets, sizeof(res->buckets[0])); + if (res->buckets == NULL) { + free(res); + return (NULL); + } + return (res); +} + +void +archive_entry_linkresolver_set_strategy(struct archive_entry_linkresolver *res, + int fmt) +{ + int fmtbase = fmt & ARCHIVE_FORMAT_BASE_MASK; + + switch (fmtbase) { + case ARCHIVE_FORMAT_7ZIP: + case ARCHIVE_FORMAT_AR: + case ARCHIVE_FORMAT_ZIP: + res->strategy = ARCHIVE_ENTRY_LINKIFY_LIKE_OLD_CPIO; + break; + case ARCHIVE_FORMAT_CPIO: + switch (fmt) { + case ARCHIVE_FORMAT_CPIO_SVR4_NOCRC: + case ARCHIVE_FORMAT_CPIO_SVR4_CRC: + res->strategy = ARCHIVE_ENTRY_LINKIFY_LIKE_NEW_CPIO; + break; + default: + res->strategy = ARCHIVE_ENTRY_LINKIFY_LIKE_OLD_CPIO; + break; + } + break; + case ARCHIVE_FORMAT_MTREE: + res->strategy = ARCHIVE_ENTRY_LINKIFY_LIKE_MTREE; + break; + case ARCHIVE_FORMAT_ISO9660: + case ARCHIVE_FORMAT_SHAR: + case ARCHIVE_FORMAT_TAR: + case ARCHIVE_FORMAT_XAR: + res->strategy = ARCHIVE_ENTRY_LINKIFY_LIKE_TAR; + break; + default: + res->strategy = ARCHIVE_ENTRY_LINKIFY_LIKE_OLD_CPIO; + break; + } +} + +void +archive_entry_linkresolver_free(struct archive_entry_linkresolver *res) +{ + struct links_entry *le; + + if (res == NULL) + return; + + while ((le = next_entry(res, NEXT_ENTRY_ALL)) != NULL) + archive_entry_free(le->entry); + free(res->buckets); + free(res); +} + +void +archive_entry_linkify(struct archive_entry_linkresolver *res, + struct archive_entry **e, struct archive_entry **f) +{ + struct links_entry *le; + struct archive_entry *t; + + *f = NULL; /* Default: Don't return a second entry. */ + + if (*e == NULL) { + le = next_entry(res, NEXT_ENTRY_DEFERRED); + if (le != NULL) { + *e = le->entry; + le->entry = NULL; + } + return; + } + + /* If it has only one link, then we're done. */ + if (archive_entry_nlink(*e) == 1) + return; + /* Directories, devices never have hardlinks. */ + if (archive_entry_filetype(*e) == AE_IFDIR + || archive_entry_filetype(*e) == AE_IFBLK + || archive_entry_filetype(*e) == AE_IFCHR) + return; + + switch (res->strategy) { + case ARCHIVE_ENTRY_LINKIFY_LIKE_TAR: + le = find_entry(res, *e); + if (le != NULL) { + archive_entry_unset_size(*e); + archive_entry_copy_hardlink(*e, + archive_entry_pathname(le->canonical)); + } else + insert_entry(res, *e); + return; + case ARCHIVE_ENTRY_LINKIFY_LIKE_MTREE: + le = find_entry(res, *e); + if (le != NULL) { + archive_entry_copy_hardlink(*e, + archive_entry_pathname(le->canonical)); + } else + insert_entry(res, *e); + return; + case ARCHIVE_ENTRY_LINKIFY_LIKE_OLD_CPIO: + /* This one is trivial. */ + return; + case ARCHIVE_ENTRY_LINKIFY_LIKE_NEW_CPIO: + le = find_entry(res, *e); + if (le != NULL) { + /* + * Put the new entry in le, return the + * old entry from le. + */ + t = *e; + *e = le->entry; + le->entry = t; + /* Make the old entry into a hardlink. */ + archive_entry_unset_size(*e); + archive_entry_copy_hardlink(*e, + archive_entry_pathname(le->canonical)); + /* If we ran out of links, return the + * final entry as well. */ + if (le->links == 0) { + *f = le->entry; + le->entry = NULL; + } + } else { + /* + * If we haven't seen it, tuck it away + * for future use. + */ + le = insert_entry(res, *e); + if (le == NULL) + /* XXX We should return an error code XXX */ + return; + le->entry = *e; + *e = NULL; + } + return; + default: + break; + } + return; +} + +static struct links_entry * +find_entry(struct archive_entry_linkresolver *res, + struct archive_entry *entry) +{ + struct links_entry *le; + size_t hash, bucket; + dev_t dev; + int64_t ino; + + /* Free a held entry. */ + if (res->spare != NULL) { + archive_entry_free(res->spare->canonical); + archive_entry_free(res->spare->entry); + free(res->spare); + res->spare = NULL; + } + + dev = archive_entry_dev(entry); + ino = archive_entry_ino64(entry); + hash = (size_t)(dev ^ ino); + + /* Try to locate this entry in the links cache. */ + bucket = hash & (res->number_buckets - 1); + for (le = res->buckets[bucket]; le != NULL; le = le->next) { + if (le->hash == hash + && dev == archive_entry_dev(le->canonical) + && ino == archive_entry_ino64(le->canonical)) { + /* + * Decrement link count each time and release + * the entry if it hits zero. This saves + * memory and is necessary for detecting + * missed links. + */ + --le->links; + if (le->links > 0) + return (le); + /* Remove it from this hash bucket. */ + if (le->previous != NULL) + le->previous->next = le->next; + if (le->next != NULL) + le->next->previous = le->previous; + if (res->buckets[bucket] == le) + res->buckets[bucket] = le->next; + res->number_entries--; + /* Defer freeing this entry. */ + res->spare = le; + return (le); + } + } + return (NULL); +} + +static struct links_entry * +next_entry(struct archive_entry_linkresolver *res, int mode) +{ + struct links_entry *le; + size_t bucket; + + /* Free a held entry. */ + if (res->spare != NULL) { + archive_entry_free(res->spare->canonical); + archive_entry_free(res->spare->entry); + free(res->spare); + res->spare = NULL; + } + + /* Look for next non-empty bucket in the links cache. */ + for (bucket = 0; bucket < res->number_buckets; bucket++) { + for (le = res->buckets[bucket]; le != NULL; le = le->next) { + if (le->entry != NULL && + (mode & NEXT_ENTRY_DEFERRED) == 0) + continue; + if (le->entry == NULL && + (mode & NEXT_ENTRY_PARTIAL) == 0) + continue; + /* Remove it from this hash bucket. */ + if (le->next != NULL) + le->next->previous = le->previous; + if (le->previous != NULL) + le->previous->next = le->next; + else + res->buckets[bucket] = le->next; + res->number_entries--; + /* Defer freeing this entry. */ + res->spare = le; + return (le); + } + } + return (NULL); +} + +static struct links_entry * +insert_entry(struct archive_entry_linkresolver *res, + struct archive_entry *entry) +{ + struct links_entry *le; + size_t hash, bucket; + + /* Add this entry to the links cache. */ + le = calloc(1, sizeof(struct links_entry)); + if (le == NULL) + return (NULL); + le->canonical = archive_entry_clone(entry); + + /* If the links cache is getting too full, enlarge the hash table. */ + if (res->number_entries > res->number_buckets * 2) + grow_hash(res); + + hash = (size_t)(archive_entry_dev(entry) ^ archive_entry_ino64(entry)); + bucket = hash & (res->number_buckets - 1); + + /* If we could allocate the entry, record it. */ + if (res->buckets[bucket] != NULL) + res->buckets[bucket]->previous = le; + res->number_entries++; + le->next = res->buckets[bucket]; + le->previous = NULL; + res->buckets[bucket] = le; + le->hash = hash; + le->links = archive_entry_nlink(entry) - 1; + return (le); +} + +static void +grow_hash(struct archive_entry_linkresolver *res) +{ + struct links_entry *le, **new_buckets; + size_t new_size; + size_t i, bucket; + + /* Try to enlarge the bucket list. */ + new_size = res->number_buckets * 2; + if (new_size < res->number_buckets) + return; + new_buckets = calloc(new_size, sizeof(struct links_entry *)); + + if (new_buckets == NULL) + return; + + for (i = 0; i < res->number_buckets; i++) { + while (res->buckets[i] != NULL) { + /* Remove entry from old bucket. */ + le = res->buckets[i]; + res->buckets[i] = le->next; + + /* Add entry to new bucket. */ + bucket = le->hash & (new_size - 1); + + if (new_buckets[bucket] != NULL) + new_buckets[bucket]->previous = le; + le->next = new_buckets[bucket]; + le->previous = NULL; + new_buckets[bucket] = le; + } + } + free(res->buckets); + res->buckets = new_buckets; + res->number_buckets = new_size; +} + +struct archive_entry * +archive_entry_partial_links(struct archive_entry_linkresolver *res, + unsigned int *links) +{ + struct archive_entry *e; + struct links_entry *le; + + /* Free a held entry. */ + if (res->spare != NULL) { + archive_entry_free(res->spare->canonical); + archive_entry_free(res->spare->entry); + free(res->spare); + res->spare = NULL; + } + + le = next_entry(res, NEXT_ENTRY_PARTIAL); + if (le != NULL) { + e = le->canonical; + if (links != NULL) + *links = le->links; + le->canonical = NULL; + } else { + e = NULL; + if (links != NULL) + *links = 0; + } + return (e); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_linkify.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_linkify.3 new file mode 100644 index 0000000000..8c19fddb6e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_linkify.3 @@ -0,0 +1,224 @@ +.\" Copyright (c) 2010 Joerg Sonnenberger +.\" 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. +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_ENTRY_LINKIFY 3 +.Os +.Sh NAME +.Nm archive_entry_linkresolver , +.Nm archive_entry_linkresolver_new , +.Nm archive_entry_linkresolver_set_strategy , +.Nm archive_entry_linkresolver_free , +.Nm archive_entry_linkify +.Nd hardlink resolver functions +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive_entry.h +.Ft struct archive_entry_linkresolver * +.Fn archive_entry_linkresolver_new void +.Ft void +.Fo archive_entry_linkresolver_set_strategy +.Fa "struct archive_entry_linkresolver *resolver" +.Fa "int format" +.Fc +.Ft void +.Fo archive_entry_linkresolver_free +.Fa "struct archive_entry_linkresolver *resolver" +.Fc +.Ft void +.Fo archive_entry_linkify +.Fa "struct archive_entry_linkresolver *resolver" +.Fa "struct archive_entry **entry" +.Fa "struct archive_entry **sparse" +.Fc +.Sh DESCRIPTION +Programs that want to create archives have to deal with hardlinks. +Hardlinks are handled in different ways by the archive formats. +The basic strategies are: +.Bl -enum +.It +Ignore hardlinks and store the body for each reference (old cpio, zip). +.It +Store the body the first time an inode is seen (ustar, pax). +.It +Store the body the last time an inode is seen (new cpio). +.El +.Pp +The +.Nm +functions help by providing a unified interface and handling the complexity +behind the scene. +.Pp +The +.Nm +functions assume that +.Vt archive_entry +instances have valid nlinks, inode and device values. +The inode and device value is used to match entries. +The nlinks value is used to determined if all references have been found and +if the internal references can be recycled. +.Pp +The +.Fn archive_entry_linkresolver_new +function allocates a new link resolver. +The instance can be freed using +.Fn archive_entry_linkresolver_free . +All deferred entries are flushed and the internal storage is freed. +.Pp +The +.Fn archive_entry_linkresolver_set_strategy +function selects the optimal hardlink strategy for the given format. +The format code can be obtained from +.Xr archive_format 3 . +The function can be called more than once, but it is recommended to +flush all deferred entries first. +.Pp +The +.Fn archive_entry_linkify +function is the core of +.Nm . +The +.Fn entry +argument points to the +.Vt archive_entry +that should be written. +Depending on the strategy one of the following actions is taken: +.Bl -enum +.It +For the simple archive formats +.Va *entry +is left unmodified and +.Va *sparse +is set to +.Dv NULL . +.It +For tar like archive formats, +.Va *sparse +is set to +.Dv NULL . +If +.Va *entry +is +.Dv NULL , +no action is taken. +If the hardlink count of +.Va *entry +is larger than 1 and the file type is a regular file or symbolic link, +the internal list is searched for a matching inode. +If such an inode is found, the link count is decremented and the file size +of +.Va *entry +is set to 0 to notify that no body should be written. +If no such inode is found, a copy of the entry is added to the internal cache +with a link count reduced by one. +.It +For new cpio like archive formats a value for +.Va *entry +of +.Dv NULL +is used to flush deferred entries. +In that case +.Va *entry +is set to an arbitrary deferred entry and the entry itself is removed from the +internal list. +If the internal list is empty, +.Va *entry +is set to +.Dv NULL . +In either case, +.Va *sparse +is set to +.Dv NULL +and the function returns. +If the hardlink count of +.Va *entry +is one or the file type is a directory or device, +.Va *sparse +is set to +.Dv NULL +and no further action is taken. +Otherwise, the internal list is searched for a matching inode. +If such an inode is not found, the entry is added to the internal list, +both +.Va *entry +and +.Va *sparse +are set to +.Dv NULL +and the function returns. +If such an inode is found, the link count is decremented. +If it remains larger than one, the existing entry on the internal list +is swapped with +.Va *entry +after retaining the link count. +The existing entry is returned in +.Va *entry . +If the link count reached one, the new entry is also removed from the +internal list and returned in +.Va *sparse . +Otherwise +.Va *sparse +is set to +.Dv NULL . +.El +.Pp +The general usage is therefore: +.Bl -enum +.It +For each new archive entry, call +.Fn archive_entry_linkify . +.It +Keep in mind that the entries returned may have a size of 0 now. +.It +If +.Va *entry +is not +.Dv NULL , +archive it. +.It +If +.Va *sparse +is not +.Dv NULL , +archive it. +.It +After all entries have been written to disk, call +.Fn archive_entry_linkify +with +.Va *entry +set to +.Dv NULL +and archive the returned entry as long as it is not +.Dv NULL . +.El +.Sh RETURN VALUES +.Fn archive_entry_linkresolver_new +returns +.Dv NULL +on +.Xr malloc 3 +failures. +.Sh SEE ALSO +.Xr archive_entry 3 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_locale.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_locale.h new file mode 100644 index 0000000000..803c0368bb --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_locale.h @@ -0,0 +1,92 @@ +/*- + * Copyright (c) 2011 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + * + * $FreeBSD$ + */ + +#ifndef ARCHIVE_ENTRY_LOCALE_H_INCLUDED +#define ARCHIVE_ENTRY_LOCALE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +struct archive_entry; +struct archive_string_conv; + +/* + * Utility functions to set and get entry attributes by translating + * character-set. These are designed for use in format readers and writers. + * + * The return code and interface of these are quite different from other + * functions for archive_entry defined in archive_entry.h. + * Common return code are: + * Return 0 if the string conversion succeeded. + * Return -1 if the string conversion failed. + */ + +#define archive_entry_gname_l _archive_entry_gname_l +int _archive_entry_gname_l(struct archive_entry *, + const char **, size_t *, struct archive_string_conv *); +#define archive_entry_hardlink_l _archive_entry_hardlink_l +int _archive_entry_hardlink_l(struct archive_entry *, + const char **, size_t *, struct archive_string_conv *); +#define archive_entry_pathname_l _archive_entry_pathname_l +int _archive_entry_pathname_l(struct archive_entry *, + const char **, size_t *, struct archive_string_conv *); +#define archive_entry_symlink_l _archive_entry_symlink_l +int _archive_entry_symlink_l(struct archive_entry *, + const char **, size_t *, struct archive_string_conv *); +#define archive_entry_uname_l _archive_entry_uname_l +int _archive_entry_uname_l(struct archive_entry *, + const char **, size_t *, struct archive_string_conv *); +#define archive_entry_acl_text_l _archive_entry_acl_text_l +int _archive_entry_acl_text_l(struct archive_entry *, int, +const char **, size_t *, struct archive_string_conv *) __LA_DEPRECATED; +#define archive_entry_acl_to_text_l _archive_entry_acl_to_text_l +char *_archive_entry_acl_to_text_l(struct archive_entry *, ssize_t *, int, + struct archive_string_conv *); +#define archive_entry_acl_from_text_l _archive_entry_acl_from_text_l +int _archive_entry_acl_from_text_l(struct archive_entry *, const char* text, + int type, struct archive_string_conv *); +#define archive_entry_copy_gname_l _archive_entry_copy_gname_l +int _archive_entry_copy_gname_l(struct archive_entry *, + const char *, size_t, struct archive_string_conv *); +#define archive_entry_copy_hardlink_l _archive_entry_copy_hardlink_l +int _archive_entry_copy_hardlink_l(struct archive_entry *, + const char *, size_t, struct archive_string_conv *); +#define archive_entry_copy_link_l _archive_entry_copy_link_l +int _archive_entry_copy_link_l(struct archive_entry *, + const char *, size_t, struct archive_string_conv *); +#define archive_entry_copy_pathname_l _archive_entry_copy_pathname_l +int _archive_entry_copy_pathname_l(struct archive_entry *, + const char *, size_t, struct archive_string_conv *); +#define archive_entry_copy_symlink_l _archive_entry_copy_symlink_l +int _archive_entry_copy_symlink_l(struct archive_entry *, + const char *, size_t, struct archive_string_conv *); +#define archive_entry_copy_uname_l _archive_entry_copy_uname_l +int _archive_entry_copy_uname_l(struct archive_entry *, + const char *, size_t, struct archive_string_conv *); + +#endif /* ARCHIVE_ENTRY_LOCALE_H_INCLUDED */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_misc.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_misc.3 new file mode 100644 index 0000000000..dfab7ddb55 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_misc.3 @@ -0,0 +1,63 @@ +.\" Copyright (c) 2019 Martin Matuska +.\" 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. +.\" +.Dd April 15, 2019 +.Dt ARCHIVE_ENTRY_MISC 3 +.Os +.Sh NAME +.Nm archive_entry_symlink_type , +.Nm archive_entry_set_symlink_type +.Nd miscellaneous functions for manipulating properties of archive_entry +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive_entry.h +.Ft int +.Fn archive_entry_symlink_type "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_symlink_type "struct archive_entry *a" "int" +.Sh DESCRIPTION +The function +.Fn archive_entry_symlink_type +returns and the function +.Fn archive_entry_set_symlink_type +sets the type of the symbolic link stored in an archive entry. +These functions +have special meaning on operating systems that support multiple symbolic link +types (e.g. Microsoft Windows). +.Pp +Supported values are: +.Bl -tag -width "AE_SYMLINK_TYPE_DIRECTORY" -compact +.It AE_SYMLINK_TYPE_UNDEFINED +Symbolic link target type is not defined (default on unix systems) +.It AE_SYMLINK_TYPE_FILE +Symbolic link points to a file +.It AE_SYMLINK_TYPE_DIRECTORY +Symbolic link points to a directory +.El +.Sh SEE ALSO +.Xr archive_entry 3 , +.Xr archive_entry_paths 3 , +.Xr archive_entry_stat 3 , +.Xr libarchive 3 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_paths.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_paths.3 new file mode 100644 index 0000000000..0f849c9ebb --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_paths.3 @@ -0,0 +1,153 @@ +.\" Copyright (c) 2010 Joerg Sonnenberger +.\" 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. +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_ENTRY_PATHS 3 +.Os +.Sh NAME +.Nm archive_entry_hardlink , +.Nm archive_entry_hardlink_w , +.Nm archive_entry_set_hardlink , +.Nm archive_entry_copy_hardlink , +.Nm archive_entry_copy_hardlink_w , +.Nm archive_entry_update_hardlink_utf8 , +.Nm archive_entry_set_link , +.Nm archive_entry_copy_link , +.Nm archive_entry_copy_link_w , +.Nm archive_entry_update_link_utf8 , +.Nm archive_entry_pathname , +.Nm archive_entry_pathname_w , +.Nm archive_entry_set_pathname , +.Nm archive_entry_copy_pathname , +.Nm archive_entry_copy_pathname_w , +.Nm archive_entry_update_pathname_utf8 , +.Nm archive_entry_sourcepath , +.Nm archive_entry_copy_sourcepath , +.Nm archive_entry_symlink , +.Nm archive_entry_symlink_w , +.Nm archive_entry_set_symlink , +.Nm archive_entry_copy_symlink , +.Nm archive_entry_copy_symlink_w , +.Nm archive_entry_update_symlink_utf8 +.Nd functions for manipulating path names in archive entry descriptions +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive_entry.h +.Ft const char * +.Fn archive_entry_hardlink "struct archive_entry *a" +.Ft const wchar_t * +.Fn archive_entry_hardlink_w "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_hardlink "struct archive_entry *a" "const char *path" +.Ft void +.Fn archive_entry_copy_hardlink "struct archive_entry *a" "const char *path" +.Ft void +.Fn archive_entry_copy_hardlink_w "struct archive_entry *a "const wchar_t *path" +.Ft int +.Fn archive_entry_update_hardlink_utf8 "struct archive_entry *a" "const char *path" +.Ft void +.Fn archive_entry_set_link "struct archive_entry *a" "const char *path" +.Ft void +.Fn archive_entry_copy_link "struct archive_entry *a" " const char *path" +.Ft void +.Fn archive_entry_copy_link_w "struct archive_entry *a" " const wchar_t *path" +.Ft int +.Fn archive_entry_update_link_utf8 "struct archive_entry *a" " const char *path" +.Ft const char * +.Fn archive_entry_pathname "struct archive_entry *a" +.Ft const wchar_t * +.Fn archive_entry_pathname_w "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_pathname "struct archive_entry *a" "const char *path" +.Ft void +.Fn archive_entry_copy_pathname "struct archive_entry *a" "const char *path" +.Ft void +.Fn archive_entry_copy_pathname_w "struct archive_entry *a" "const wchar_t *path" +.Ft int +.Fn archive_entry_update_pathname_utf8 "struct archive_entry *a" "const char *path" +.Ft const char * +.Fn archive_entry_sourcepath "struct archive_entry *a" +.Ft void +.Fn archive_entry_copy_sourcepath "struct archive_entry *a" "const char *path" +.Ft const char * +.Fn archive_entry_symlink "struct archive_entry *a" +.Ft const wchar_t * +.Fn archive_entry_symlink_w "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_symlink "struct archive_entry *a" "const char *path" +.Ft void +.Fn archive_entry_copy_symlink "struct archive_entry *a" "const char *path" +.Ft void +.Fn archive_entry_copy_symlink_w "struct archive_entry *a" "const wchar_t *path" +.Ft int +.Fn archive_entry_update_symlink_utf8 "struct archive_entry *a" "const char *path" +.Sh DESCRIPTION +Path names supported by +.Xr archive_entry 3 : +.Bl -tag -width "sourcepath" -compact +.It hardlink +Destination of the hardlink. +.It link +Update only. +For a symlink, update the destination. +Otherwise, make the entry a hardlink and alter +the destination for that. +.It pathname +Path in the archive +.It sourcepath +Path on the disk for use by +.Xr archive_read_disk 3 . +.It symlink +Destination of the symbolic link. +.El +.Pp +Path names can be provided in one of three different ways: +.Bl -tag -width "wchar_t *" +.It char * +Multibyte strings in the current locale. +.It wchar_t * +Wide character strings in the current locale. +The accessor functions are named +.Fn XXX_w . +.It UTF-8 +Unicode strings encoded as UTF-8. +These are convenience functions to update both the multibyte and wide +character strings at the same time. +.El +.Pp +The sourcepath is a pure filesystem concept and never stored in an +archive directly. +.Pp +For that reason, it is only available as multibyte string. +The link path is a convenience function for conditionally setting +hardlink or symlink destination. +It doesn't have a corresponding get accessor function. +.Pp +.Fn archive_entry_set_XXX +is an alias for +.Fn archive_entry_copy_XXX . +.Sh SEE ALSO +.Xr archive_entry 3 , +.Xr libarchive 3 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_perms.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_perms.3 new file mode 100644 index 0000000000..0291b7b498 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_perms.3 @@ -0,0 +1,209 @@ +.\" Copyright (c) 2003-2007 Tim Kientzle +.\" Copyright (c) 2010 Joerg Sonnenberger +.\" 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. +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_ENTRY_PERMS 3 +.Os +.Sh NAME +.Nm archive_entry_gid , +.Nm archive_entry_set_gid , +.Nm archive_entry_uid , +.Nm archive_entry_set_uid , +.Nm archive_entry_perm , +.Nm archive_entry_set_perm , +.Nm archive_entry_strmode , +.Nm archive_entry_uname , +.Nm archive_entry_uname_w , +.Nm archive_entry_set_uname , +.Nm archive_entry_copy_uname , +.Nm archive_entry_copy_uname_w , +.Nm archive_entry_update_uname_utf8 , +.Nm archive_entry_gname , +.Nm archive_entry_gname_w , +.Nm archive_entry_set_gname , +.Nm archive_entry_copy_gname , +.Nm archive_entry_copy_gname_w , +.Nm archive_entry_update_gname_utf8 , +.Nm archive_entry_fflags , +.Nm archive_entry_fflags_text , +.Nm archive_entry_set_fflags , +.Nm archive_entry_copy_fflags_text , +.Nm archive_entry_copy_fflags_text_w +.Nd functions for manipulating ownership and permissions in archive entry descriptions +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive_entry.h +.Ft gid_t +.Fn archive_entry_gid "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_gid "struct archive_entry *a" "gid_t gid" +.Ft uid_t +.Fn archive_entry_uid "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_uid "struct archive_entry *a" "uid_t uid" +.Ft mode_t +.Fn archive_entry_perm "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_perm "struct archive_entry *a" "mode_t mode" +.Ft const char * +.Fn archive_entry_strmode "struct archive_entry *a" +.Ft const char * +.Fn archive_entry_gname "struct archive_entry *a" +.Ft const wchar_t * +.Fn archive_entry_gname_w "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_gname "struct archive_entry *a" "const char *a" +.Ft void +.Fn archive_entry_copy_gname "struct archive_entry *a" "const char *name" +.Ft void +.Fn archive_entry_copy_gname_w "struct archive_entry *a" "const wchar_t *name" +.Ft int +.Fn archive_entry_update_gname_utf8 "struct archive_entry *a" "const char *name" +.Ft const char * +.Fn archive_entry_uname "struct archive_entry *a" +.Ft const wchar_t * +.Fn archive_entry_uname_w "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_uname "struct archive_entry *a" "const char *name" +.Ft void +.Fn archive_entry_copy_uname "struct archive_entry *a" "const char *name" +.Ft void +.Fn archive_entry_copy_uname_w "struct archive_entry *a" "const wchar_t *name" +.Ft int +.Fn archive_entry_update_uname_utf8 "struct archive_entry *a" "const char *name" +.Ft void +.Fo archive_entry_fflags +.Fa "struct archive_entry *a" +.Fa "unsigned long *set_bits" +.Fa "unsigned long *clear_bits" +.Fc +.Ft const char * +.Fn archive_entry_fflags_text "struct archive_entry *a" +.Ft void +.Fo archive_entry_set_fflags +.Fa "struct archive_entry *a" +.Fa "unsigned long set_bits" +.Fa "unsigned long clear_bits" +.Fc +.Ft const char * +.Fn archive_entry_copy_fflags_text "struct archive_entry *a" "const char *text" +.Ft const wchar_t * +.Fn archive_entry_copy_fflags_text_w "struct archive_entry *a" "const wchar_t *text" +.Sh DESCRIPTION +.Ss User id, group id and mode +The functions +.Fn archive_entry_uid , +.Fn archive_entry_gid , +and +.Fn archive_entry_perm +can be used to extract the user id, group id and permission from the given entry. +The corresponding functions +.Fn archive_entry_set_uid , +.Fn archive_entry_set_gid , +and +.Fn archive_entry_set_perm +store the given user id, group id and permission in the entry. +The permission is also set as a side effect of calling +.Fn archive_entry_set_mode . +.Pp +.Fn archive_entry_strmode +returns a string representation of the permission as used by the long mode of +.Xr ls 1 . +.Ss User and group name +User and group names can be provided in one of three different ways: +.Bl -tag -width "wchar_t *" +.It char * +Multibyte strings in the current locale. +.It wchar_t * +Wide character strings in the current locale. +The accessor functions are named +.Fn XXX_w . +.It UTF-8 +Unicode strings encoded as UTF-8. +These are convenience functions to update both the multibyte and wide +character strings at the same time. +.El +.Pp +.Fn archive_entry_set_XXX +is an alias for +.Fn archive_entry_copy_XXX . +.Ss File Flags +File flags are transparently converted between a bitmap +representation and a textual format. +For example, if you set the bitmap and ask for text, the library +will build a canonical text format. +However, if you set a text format and request a text format, +you will get back the same text, even if it is ill-formed. +If you need to canonicalize a textual flags string, you should first set the +text form, then request the bitmap form, then use that to set the bitmap form. +Setting the bitmap format will clear the internal text representation +and force it to be reconstructed when you next request the text form. +.Pp +The bitmap format consists of two integers, one containing bits +that should be set, the other specifying bits that should be +cleared. +Bits not mentioned in either bitmap will be ignored. +Usually, the bitmap of bits to be cleared will be set to zero. +In unusual circumstances, you can force a fully-specified set +of file flags by setting the bitmap of flags to clear to the complement +of the bitmap of flags to set. +(This differs from +.Xr fflagstostr 3 , +which only includes names for set bits.) +Converting a bitmap to a textual string is a platform-specific +operation; bits that are not meaningful on the current platform +will be ignored. +.Pp +The canonical text format is a comma-separated list of flag names. +The +.Fn archive_entry_copy_fflags_text +and +.Fn archive_entry_copy_fflags_text_w +functions parse the provided text and set the internal bitmap values. +This is a platform-specific operation; names that are not meaningful +on the current platform will be ignored. +The function returns a pointer to the start of the first name that was not +recognized, or NULL if every name was recognized. +Note that every name \(em including names that follow an unrecognized +name \(em will be evaluated, and the bitmaps will be set to reflect +every name that is recognized. +(In particular, this differs from +.Xr strtofflags 3 , +which stops parsing at the first unrecognized name.) +.Sh SEE ALSO +.Xr archive_entry 3 , +.Xr archive_entry_acl 3 , +.Xr archive_read_disk 3 , +.Xr archive_write_disk 3 , +.Xr libarchive 3 +.Sh BUGS +The platform types +.Vt uid_t +and +.Vt gid_t +are often 16 or 32 bit wide. +In this case it is possible that the ids can not be correctly restored +from archives and get truncated. diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_private.h new file mode 100644 index 0000000000..2b9a084ca1 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_private.h @@ -0,0 +1,184 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + * + * $FreeBSD: head/lib/libarchive/archive_entry_private.h 201096 2009-12-28 02:41:27Z kientzle $ + */ + +#ifndef ARCHIVE_ENTRY_PRIVATE_H_INCLUDED +#define ARCHIVE_ENTRY_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +#include "archive_acl_private.h" +#include "archive_string.h" + +struct ae_xattr { + struct ae_xattr *next; + + char *name; + void *value; + size_t size; +}; + +struct ae_sparse { + struct ae_sparse *next; + + int64_t offset; + int64_t length; +}; + +/* + * Description of an archive entry. + * + * Basically, this is a "struct stat" with a few text fields added in. + * + * TODO: Add "comment", "charset", and possibly other entries + * that are supported by "pax interchange" format. However, GNU, ustar, + * cpio, and other variants don't support these features, so they're not an + * excruciatingly high priority right now. + * + * TODO: "pax interchange" format allows essentially arbitrary + * key/value attributes to be attached to any entry. Supporting + * such extensions may make this library useful for special + * applications (e.g., a package manager could attach special + * package-management attributes to each entry). There are tricky + * API issues involved, so this is not going to happen until + * there's a real demand for it. + * + * TODO: Design a good API for handling sparse files. + */ +struct archive_entry { + struct archive *archive; + + /* + * Note that ae_stat.st_mode & AE_IFMT can be 0! + * + * This occurs when the actual file type of the object is not + * in the archive. For example, 'tar' archives store + * hardlinks without marking the type of the underlying + * object. + */ + + /* + * We have a "struct aest" for holding file metadata rather than just + * a "struct stat" because on some platforms the "struct stat" has + * fields which are too narrow to hold the range of possible values; + * we don't want to lose information if we read an archive and write + * out another (e.g., in "tar -cf new.tar @old.tar"). + * + * The "stat" pointer points to some form of platform-specific struct + * stat; it is declared as a void * rather than a struct stat * as + * some platforms have multiple varieties of stat structures. + */ + void *stat; + int stat_valid; /* Set to 0 whenever a field in aest changes. */ + + struct aest { + int64_t aest_atime; + uint32_t aest_atime_nsec; + int64_t aest_ctime; + uint32_t aest_ctime_nsec; + int64_t aest_mtime; + uint32_t aest_mtime_nsec; + int64_t aest_birthtime; + uint32_t aest_birthtime_nsec; + int64_t aest_gid; + int64_t aest_ino; + uint32_t aest_nlink; + uint64_t aest_size; + int64_t aest_uid; + /* + * Because converting between device codes and + * major/minor values is platform-specific and + * inherently a bit risky, we only do that conversion + * lazily. That way, we will do a better job of + * preserving information in those cases where no + * conversion is actually required. + */ + int aest_dev_is_broken_down; + dev_t aest_dev; + dev_t aest_devmajor; + dev_t aest_devminor; + int aest_rdev_is_broken_down; + dev_t aest_rdev; + dev_t aest_rdevmajor; + dev_t aest_rdevminor; + } ae_stat; + + int ae_set; /* bitmap of fields that are currently set */ +#define AE_SET_HARDLINK 1 +#define AE_SET_SYMLINK 2 +#define AE_SET_ATIME 4 +#define AE_SET_CTIME 8 +#define AE_SET_MTIME 16 +#define AE_SET_BIRTHTIME 32 +#define AE_SET_SIZE 64 +#define AE_SET_INO 128 +#define AE_SET_DEV 256 + + /* + * Use aes here so that we get transparent mbs<->wcs conversions. + */ + struct archive_mstring ae_fflags_text; /* Text fflags per fflagstostr(3) */ + unsigned long ae_fflags_set; /* Bitmap fflags */ + unsigned long ae_fflags_clear; + struct archive_mstring ae_gname; /* Name of owning group */ + struct archive_mstring ae_hardlink; /* Name of target for hardlink */ + struct archive_mstring ae_pathname; /* Name of entry */ + struct archive_mstring ae_symlink; /* symlink contents */ + struct archive_mstring ae_uname; /* Name of owner */ + + /* Not used within libarchive; useful for some clients. */ + struct archive_mstring ae_sourcepath; /* Path this entry is sourced from. */ + +#define AE_ENCRYPTION_NONE 0 +#define AE_ENCRYPTION_DATA 1 +#define AE_ENCRYPTION_METADATA 2 + char encryption; + + void *mac_metadata; + size_t mac_metadata_size; + + /* ACL support. */ + struct archive_acl acl; + + /* extattr support. */ + struct ae_xattr *xattr_head; + struct ae_xattr *xattr_p; + + /* sparse support. */ + struct ae_sparse *sparse_head; + struct ae_sparse *sparse_tail; + struct ae_sparse *sparse_p; + + /* Miscellaneous. */ + char strmode[12]; + + /* Symlink type support */ + int ae_symlink_type; +}; + +#endif /* ARCHIVE_ENTRY_PRIVATE_H_INCLUDED */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_sparse.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_sparse.c new file mode 100644 index 0000000000..74917b37b8 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_sparse.c @@ -0,0 +1,156 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2010-2011 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_entry_private.h" + +/* + * sparse handling + */ + +void +archive_entry_sparse_clear(struct archive_entry *entry) +{ + struct ae_sparse *sp; + + while (entry->sparse_head != NULL) { + sp = entry->sparse_head->next; + free(entry->sparse_head); + entry->sparse_head = sp; + } + entry->sparse_tail = NULL; +} + +void +archive_entry_sparse_add_entry(struct archive_entry *entry, + la_int64_t offset, la_int64_t length) +{ + struct ae_sparse *sp; + + if (offset < 0 || length < 0) + /* Invalid value */ + return; + if (offset > INT64_MAX - length || + offset + length > archive_entry_size(entry)) + /* A value of "length" parameter is too large. */ + return; + if ((sp = entry->sparse_tail) != NULL) { + if (sp->offset + sp->length > offset) + /* Invalid value. */ + return; + if (sp->offset + sp->length == offset) { + if (sp->offset + sp->length + length < 0) + /* A value of "length" parameter is + * too large. */ + return; + /* Expand existing sparse block size. */ + sp->length += length; + return; + } + } + + if ((sp = (struct ae_sparse *)malloc(sizeof(*sp))) == NULL) + /* XXX Error XXX */ + return; + + sp->offset = offset; + sp->length = length; + sp->next = NULL; + + if (entry->sparse_head == NULL) + entry->sparse_head = entry->sparse_tail = sp; + else { + /* Add a new sparse block to the tail of list. */ + if (entry->sparse_tail != NULL) + entry->sparse_tail->next = sp; + entry->sparse_tail = sp; + } +} + + +/* + * returns number of the sparse entries + */ +int +archive_entry_sparse_count(struct archive_entry *entry) +{ + struct ae_sparse *sp; + int count = 0; + + for (sp = entry->sparse_head; sp != NULL; sp = sp->next) + count++; + + /* + * Sanity check if this entry is exactly sparse. + * If amount of sparse blocks is just one and it indicates the whole + * file data, we should remove it and return zero. + */ + if (count == 1) { + sp = entry->sparse_head; + if (sp->offset == 0 && + sp->length >= archive_entry_size(entry)) { + count = 0; + archive_entry_sparse_clear(entry); + } + } + + return (count); +} + +int +archive_entry_sparse_reset(struct archive_entry * entry) +{ + entry->sparse_p = entry->sparse_head; + + return archive_entry_sparse_count(entry); +} + +int +archive_entry_sparse_next(struct archive_entry * entry, + la_int64_t *offset, la_int64_t *length) +{ + if (entry->sparse_p) { + *offset = entry->sparse_p->offset; + *length = entry->sparse_p->length; + + entry->sparse_p = entry->sparse_p->next; + + return (ARCHIVE_OK); + } else { + *offset = 0; + *length = 0; + return (ARCHIVE_WARN); + } +} + +/* + * end of sparse handling + */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_stat.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_stat.3 new file mode 100644 index 0000000000..29a53f7560 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_stat.3 @@ -0,0 +1,274 @@ +.\" Copyright (c) 2010 Joerg Sonnenberger +.\" 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. +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_ENTRY_STAT 3 +.Os +.Sh NAME +.Nm archive_entry_stat , +.Nm archive_entry_copy_stat , +.Nm archive_entry_filetype , +.Nm archive_entry_set_filetype , +.Nm archive_entry_mode , +.Nm archive_entry_set_mode , +.Nm archive_entry_size , +.Nm archive_entry_size_is_set , +.Nm archive_entry_set_size , +.Nm archive_entry_unset_size , +.Nm archive_entry_dev , +.Nm archive_entry_set_dev , +.Nm archive_entry_dev_is_set , +.Nm archive_entry_devmajor , +.Nm archive_entry_set_devmajor , +.Nm archive_entry_devminor , +.Nm archive_entry_set_devminor , +.Nm archive_entry_ino , +.Nm archive_entry_set_ino , +.Nm archive_entry_ino_is_set , +.Nm archive_entry_ino64 , +.Nm archive_entry_set_ino64 , +.Nm archive_entry_nlink , +.Nm archive_entry_rdev , +.Nm archive_entry_set_rdev , +.Nm archive_entry_rdevmajor , +.Nm archive_entry_set_rdevmajor , +.Nm archive_entry_rdevminor , +.Nm archive_entry_set_rdevminor +.Nd accessor functions for manipulating archive entry descriptions +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive_entry.h +.Ft const struct stat * +.Fn archive_entry_stat "struct archive_entry *a" +.Ft void +.Fn archive_entry_copy_stat "struct archive_entry *a" "const struct stat *sb" +.Ft mode_t +.Fn archive_entry_filetype "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_filetype "struct archive_entry *a" "unsigned int type" +.Ft mode_t +.Fn archive_entry_mode "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_mode "struct archive_entry *a" "mode_t mode" +.Ft int64_t +.Fn archive_entry_size "struct archive_entry *a" +.Ft int +.Fn archive_entry_size_is_set "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_size "struct archive_entry *a" "int64_t size" +.Ft void +.Fn archive_entry_unset_size "struct archive_entry *a" +.Ft dev_t +.Fn archive_entry_dev "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_dev "struct archive_entry *a" "dev_t dev" +.Ft int +.Fn archive_entry_dev_is_set "struct archive_entry *a" +.Ft dev_t +.Fn archive_entry_devmajor "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_devmajor "struct archive_entry *a" "dev_t major" +.Ft dev_t +.Fn archive_entry_devminor "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_devminor "struct archive_entry *a" "dev_t minor" +.Ft ino_t +.Fn archive_entry_ino "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_ino "struct archive_entry *a" "unsigned long ino" +.Ft int +.Fn archive_entry_ino_is_set "struct archive_entry *a" +.Ft int64_t +.Fn archive_entry_ino64 "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_ino64 "struct archive_entry *a" "int64_t ino" +.Ft unsigned int +.Fn archive_entry_nlink "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_nlink "struct archive_entry *a" "unsigned int count" +.Ft dev_t +.Fn archive_entry_rdev "struct archive_entry *a" +.Ft dev_t +.Fn archive_entry_rdevmajor "struct archive_entry *a" +.Ft dev_t +.Fn archive_entry_rdevminor "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_rdev "struct archive_entry *a" "dev_t dev" +.Ft void +.Fn archive_entry_set_rdevmajor "struct archive_entry *a" "dev_t major" +.Ft void +.Fn archive_entry_set_rdevminor "struct archive_entry *a" "dev_t minor" +.Sh DESCRIPTION +.Ss Copying to and from Vt struct stat +The function +.Fn archive_entry_stat +converts the various fields stored in the archive entry to the format +used by +.Xr stat 2 . +The return value remains valid until either +.Fn archive_entry_clear +or +.Fn archive_entry_free +is called. +It is not affected by calls to the set accessor functions. +It currently sets the following values in +.Vt struct stat : +.Vt st_atime , +.Vt st_ctime , +.Vt st_dev , +.Vt st_gid , +.Vt st_ino , +.Vt st_mode , +.Vt st_mtime , +.Vt st_nlink , +.Vt st_rdev , +.Vt st_size , +.Vt st_uid . +In addition, +.Vt st_birthtime +and high-precision information for time-related fields +will be included on platforms that support it. +.Pp +The function +.Fn archive_entry_copy_stat +copies fields from the platform's +.Vt struct stat . +Fields not provided by +.Vt struct stat +are unchanged. +.Ss General accessor functions +The functions +.Fn archive_entry_filetype +and +.Fn archive_entry_set_filetype +get respectively set the filetype. +The file type is one of the following constants: +.Bl -tag -width "AE_IFSOCK" -compact -offset indent +.It AE_IFREG +Regular file +.It AE_IFLNK +Symbolic link +.It AE_IFSOCK +Socket +.It AE_IFCHR +Character device +.It AE_IFBLK +Block device +.It AE_IFDIR +Directory +.It AE_IFIFO +Named pipe (fifo) +.El +Not all file types are supported by all platforms. +The constants used by +.Xr stat 2 +may have different numeric values from the +corresponding constants above. +.Pp +The functions +.Fn archive_entry_mode +and +.Fn archive_entry_set_mode +get/set a combination of file type and permissions and provide the +equivalent of +.Va st_mode . +Use of +.Fn archive_entry_filetype +and +.Fn archive_entry_perm +for getting and +.Fn archive_entry_set_filetype +and +.Fn archive_entry_set_perm +for setting is recommended. +.Pp +The function +.Fn archive_entry_size +returns the file size, if it has been set, and 0 otherwise. +.Fn archive_entry_size +can be used to query that status. +.Fn archive_entry_set_size +and +.Fn archive_entry_unset_size +set and unset the size, respectively. +.Pp +The number of references (hardlinks) can be obtained by calling +.Fn archive_entry_nlink +and set with +.Fn archive_entry_set_nlink . +.Ss Identifying unique files +The functions +.Fn archive_entry_dev +and +.Fn archive_entry_ino64 +are used by +.Xr archive_entry_linkify 3 +to find hardlinks. +The pair of device and inode is supposed to identify hardlinked files. +.Pp +The device major and minor number can be obtained independently using +.Fn archive_entry_devmajor +and +.Fn archive_entry_devminor . +The device can be set either via +.Fn archive_entry_set_dev +or by the combination of major and minor number using +.Fn archive_entry_set_devmajor +and +.Fn archive_entry_set_devminor . +.Pp +The inode number can be obtained using +.Fn archive_entry_ino . +This is a legacy interface that uses the platform +.Vt ino_t , +which may be very small. +To set the inode number, +.Fn archive_entry_set_ino64 +is the preferred interface. +.Ss Accessor functions for block and character devices +Block and character devices are characterised either using a device number +or a pair of major and minor number. +The combined device number can be obtained with +.Fn archive_device_rdev +and set with +.Fn archive_device_set_rdev . +The major and minor numbers are accessed by +.Fn archive_device_rdevmajor , +.Fn archive_device_rdevminor +.Fn archive_device_set_rdevmajor +and +.Fn archive_device_set_rdevminor . +.Pp +The process of splitting the combined device number into major and +minor number and the reverse process of combing them differs between +platforms. +Some archive formats use the combined form, while other formats use +the split form. +.Sh SEE ALSO +.Xr stat 2 , +.Xr archive_entry_acl 3 , +.Xr archive_entry_perms 3 , +.Xr archive_entry_time 3 , +.Xr libarchive 3 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_stat.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_stat.c new file mode 100644 index 0000000000..71a407b1f8 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_stat.c @@ -0,0 +1,118 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_entry_stat.c 201100 2009-12-28 03:05:31Z kientzle $"); + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif + +#include "archive_entry.h" +#include "archive_entry_private.h" + +const struct stat * +archive_entry_stat(struct archive_entry *entry) +{ + struct stat *st; + if (entry->stat == NULL) { + entry->stat = calloc(1, sizeof(*st)); + if (entry->stat == NULL) + return (NULL); + entry->stat_valid = 0; + } + + /* + * If none of the underlying fields have been changed, we + * don't need to regenerate. In theory, we could use a bitmap + * here to flag only those items that have changed, but the + * extra complexity probably isn't worth it. It will be very + * rare for anyone to change just one field then request a new + * stat structure. + */ + if (entry->stat_valid) + return (entry->stat); + + st = entry->stat; + /* + * Use the public interfaces to extract items, so that + * the appropriate conversions get invoked. + */ + st->st_atime = archive_entry_atime(entry); +#if HAVE_STRUCT_STAT_ST_BIRTHTIME + st->st_birthtime = archive_entry_birthtime(entry); +#endif + st->st_ctime = archive_entry_ctime(entry); + st->st_mtime = archive_entry_mtime(entry); + st->st_dev = archive_entry_dev(entry); + st->st_gid = (gid_t)archive_entry_gid(entry); + st->st_uid = (uid_t)archive_entry_uid(entry); + st->st_ino = (ino_t)archive_entry_ino64(entry); + st->st_nlink = archive_entry_nlink(entry); + st->st_rdev = archive_entry_rdev(entry); + st->st_size = (off_t)archive_entry_size(entry); + st->st_mode = archive_entry_mode(entry); + + /* + * On systems that support high-res timestamps, copy that + * information into struct stat. + */ +#if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC + st->st_atimespec.tv_nsec = archive_entry_atime_nsec(entry); + st->st_ctimespec.tv_nsec = archive_entry_ctime_nsec(entry); + st->st_mtimespec.tv_nsec = archive_entry_mtime_nsec(entry); +#elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC + st->st_atim.tv_nsec = archive_entry_atime_nsec(entry); + st->st_ctim.tv_nsec = archive_entry_ctime_nsec(entry); + st->st_mtim.tv_nsec = archive_entry_mtime_nsec(entry); +#elif HAVE_STRUCT_STAT_ST_MTIME_N + st->st_atime_n = archive_entry_atime_nsec(entry); + st->st_ctime_n = archive_entry_ctime_nsec(entry); + st->st_mtime_n = archive_entry_mtime_nsec(entry); +#elif HAVE_STRUCT_STAT_ST_UMTIME + st->st_uatime = archive_entry_atime_nsec(entry) / 1000; + st->st_uctime = archive_entry_ctime_nsec(entry) / 1000; + st->st_umtime = archive_entry_mtime_nsec(entry) / 1000; +#elif HAVE_STRUCT_STAT_ST_MTIME_USEC + st->st_atime_usec = archive_entry_atime_nsec(entry) / 1000; + st->st_ctime_usec = archive_entry_ctime_nsec(entry) / 1000; + st->st_mtime_usec = archive_entry_mtime_nsec(entry) / 1000; +#endif +#if HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC + st->st_birthtimespec.tv_nsec = archive_entry_birthtime_nsec(entry); +#endif + + /* + * TODO: On Linux, store 32 or 64 here depending on whether + * the cached stat structure is a stat32 or a stat64. This + * will allow us to support both variants interchangeably. + */ + entry->stat_valid = 1; + + return (st); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_strmode.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_strmode.c new file mode 100644 index 0000000000..af2517a321 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_strmode.c @@ -0,0 +1,87 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: src/lib/libarchive/archive_entry_strmode.c,v 1.4 2008/06/15 05:14:01 kientzle Exp $"); + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive_entry.h" +#include "archive_entry_private.h" + +const char * +archive_entry_strmode(struct archive_entry *entry) +{ + static const mode_t permbits[] = + { 0400, 0200, 0100, 0040, 0020, 0010, 0004, 0002, 0001 }; + char *bp = entry->strmode; + mode_t mode; + int i; + + /* Fill in a default string, then selectively override. */ + strcpy(bp, "?rwxrwxrwx "); + + mode = archive_entry_mode(entry); + switch (archive_entry_filetype(entry)) { + case AE_IFREG: bp[0] = '-'; break; + case AE_IFBLK: bp[0] = 'b'; break; + case AE_IFCHR: bp[0] = 'c'; break; + case AE_IFDIR: bp[0] = 'd'; break; + case AE_IFLNK: bp[0] = 'l'; break; + case AE_IFSOCK: bp[0] = 's'; break; + case AE_IFIFO: bp[0] = 'p'; break; + default: + if (archive_entry_hardlink(entry) != NULL) { + bp[0] = 'h'; + break; + } + } + + for (i = 0; i < 9; i++) + if (!(mode & permbits[i])) + bp[i+1] = '-'; + + if (mode & S_ISUID) { + if (mode & 0100) bp[3] = 's'; + else bp[3] = 'S'; + } + if (mode & S_ISGID) { + if (mode & 0010) bp[6] = 's'; + else bp[6] = 'S'; + } + if (mode & S_ISVTX) { + if (mode & 0001) bp[9] = 't'; + else bp[9] = 'T'; + } + if (archive_entry_acl_types(entry) != 0) + bp[10] = '+'; + + return (bp); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_time.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_time.3 new file mode 100644 index 0000000000..d0563eaef4 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_time.3 @@ -0,0 +1,129 @@ +.\" Copyright (c) 2003-2007 Tim Kientzle +.\" Copyright (c) 2010 Joerg Sonnenberger +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_ENTRY_TIME 3 +.Os +.Sh NAME +.Nm archive_entry_atime , +.Nm archive_entry_atime_nsec , +.Nm archive_entry_atime_is_set , +.Nm archive_entry_set_atime , +.Nm archive_entry_unset_atime , +.Nm archive_entry_birthtime , +.Nm archive_entry_birthtime_nsec , +.Nm archive_entry_birthtime_is_set , +.Nm archive_entry_set_birthtime , +.Nm archive_entry_unset_birthtime , +.Nm archive_entry_ctime , +.Nm archive_entry_ctime_nsec , +.Nm archive_entry_ctime_is_set , +.Nm archive_entry_set_ctime , +.Nm archive_entry_unset_ctime , +.Nm archive_entry_mtime , +.Nm archive_entry_mtime_nsec , +.Nm archive_entry_mtime_is_set , +.Nm archive_entry_set_mtime , +.Nm archive_entry_unset_mtime +.Nd functions for manipulating times in archive entry descriptions +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive_entry.h +.Ft time_t +.Fn archive_entry_atime "struct archive_entry *a" +.Ft long +.Fn archive_entry_atime_nsec "struct archive_entry *a" +.Ft int +.Fn archive_entry_atime_is_set "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_atime "struct archive_entry *a" "time_t sec" "long nanosec" +.Ft void +.Fn archive_entry_unset_atime "struct archive_entry *a" +.Ft time_t +.Fn archive_entry_birthtime "struct archive_entry *a" +.Ft long +.Fn archive_entry_birthtime_nsec "struct archive_entry *a" +.Ft int +.Fn archive_entry_birthtime_is_set "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_birthtime "struct archive_entry *a" "time_t sec" "long nanosec" +.Ft void +.Fn archive_entry_unset_birthtime "struct archive_entry *a" +.Ft time_t +.Fn archive_entry_ctime "struct archive_entry *a" +.Ft long +.Fn archive_entry_ctime_nsec "struct archive_entry *a" +.Ft int +.Fn archive_entry_ctime_is_set "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_ctime "struct archive_entry *a" "time_t sec" "long nanosec" +.Ft void +.Fn archive_entry_unset_ctime "struct archive_entry *a" +.Ft time_t +.Fn archive_entry_mtime "struct archive_entry *a" +.Ft long +.Fn archive_entry_mtime_nsec "struct archive_entry *a" +.Ft int +.Fn archive_entry_mtime_is_set "struct archive_entry *a" +.Ft void +.Fn archive_entry_set_mtime "struct archive_entry *a" "time_t sec" "long nanosec" +.Ft void +.Fn archive_entry_unset_mtime "struct archive_entry *a" +.Sh DESCRIPTION +These functions create and manipulate the time fields in an +.Vt archive_entry . +Supported time fields are atime (access time), birthtime (creation time), +ctime (last time an inode property was changed) and mtime (modification time). +.Pp +.Xr libarchive 3 +provides a high-resolution interface. +The timestamps are truncated automatically depending on the archive format +(for archiving) or the filesystem capabilities (for restoring). +.Pp +All timestamp fields are optional. +The +.Fn XXX_unset +functions can be used to mark the corresponding field as missing. +The current state can be queried using +.Fn XXX_is_set . +Unset time fields have a second and nanosecond field of 0. +.Sh SEE ALSO +.Xr archive_entry 3 , +.Xr libarchive 3 +.Sh HISTORY +The +.Nm libarchive +library first appeared in +.Fx 5.3 . +.Sh AUTHORS +.An -nosplit +The +.Nm libarchive +library was written by +.An Tim Kientzle Aq kientzle@acm.org . +.\" .Sh BUGS diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_xattr.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_xattr.c new file mode 100644 index 0000000000..5fe726b99d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_entry_xattr.c @@ -0,0 +1,156 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_entry_xattr.c 201096 2009-12-28 02:41:27Z kientzle $"); + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#ifdef HAVE_LINUX_FS_H +#include <linux/fs.h> /* for Linux file flags */ +#endif +/* + * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h. + * As the include guards don't agree, the order of include is important. + */ +#ifdef HAVE_LINUX_EXT2_FS_H +#include <linux/ext2_fs.h> /* for Linux file flags */ +#endif +#if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__) +#include <ext2fs/ext2_fs.h> /* for Linux file flags */ +#endif +#include <stddef.h> +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_WCHAR_H +#include <wchar.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_entry_private.h" + +/* + * extended attribute handling + */ + +void +archive_entry_xattr_clear(struct archive_entry *entry) +{ + struct ae_xattr *xp; + + while (entry->xattr_head != NULL) { + xp = entry->xattr_head->next; + free(entry->xattr_head->name); + free(entry->xattr_head->value); + free(entry->xattr_head); + entry->xattr_head = xp; + } + + entry->xattr_head = NULL; +} + +void +archive_entry_xattr_add_entry(struct archive_entry *entry, + const char *name, const void *value, size_t size) +{ + struct ae_xattr *xp; + + if ((xp = (struct ae_xattr *)malloc(sizeof(struct ae_xattr))) == NULL) + __archive_errx(1, "Out of memory"); + + if ((xp->name = strdup(name)) == NULL) + __archive_errx(1, "Out of memory"); + + if ((xp->value = malloc(size)) != NULL) { + memcpy(xp->value, value, size); + xp->size = size; + } else + xp->size = 0; + + xp->next = entry->xattr_head; + entry->xattr_head = xp; +} + + +/* + * returns number of the extended attribute entries + */ +int +archive_entry_xattr_count(struct archive_entry *entry) +{ + struct ae_xattr *xp; + int count = 0; + + for (xp = entry->xattr_head; xp != NULL; xp = xp->next) + count++; + + return count; +} + +int +archive_entry_xattr_reset(struct archive_entry * entry) +{ + entry->xattr_p = entry->xattr_head; + + return archive_entry_xattr_count(entry); +} + +int +archive_entry_xattr_next(struct archive_entry * entry, + const char **name, const void **value, size_t *size) +{ + if (entry->xattr_p) { + *name = entry->xattr_p->name; + *value = entry->xattr_p->value; + *size = entry->xattr_p->size; + + entry->xattr_p = entry->xattr_p->next; + + return (ARCHIVE_OK); + } else { + *name = NULL; + *value = NULL; + *size = (size_t)0; + return (ARCHIVE_WARN); + } +} + +/* + * end of xattr handling + */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_getdate.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_getdate.c new file mode 100644 index 0000000000..3ec5bba888 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_getdate.c @@ -0,0 +1,1165 @@ +/* + * This code is in the public domain and has no copyright. + * + * This is a plain C recursive-descent translation of an old + * public-domain YACC grammar that has been used for parsing dates in + * very many open-source projects. + * + * Since the original authors were generous enough to donate their + * work to the public domain, I feel compelled to match their + * generosity. + * + * Tim Kientzle, February 2009. + */ + +/* + * Header comment from original getdate.y: + */ + +/* +** Originally written by Steven M. Bellovin <smb@research.att.com> while +** at the University of North Carolina at Chapel Hill. Later tweaked by +** a couple of people on Usenet. Completely overhauled by Rich $alz +** <rsalz@bbn.com> and Jim Berets <jberets@bbn.com> in August, 1990; +** +** This grammar has 10 shift/reduce conflicts. +** +** This code is in the public domain and has no copyright. +*/ + +#include "archive_platform.h" +#ifdef __FreeBSD__ +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); +#endif + +#include <ctype.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> + +#define __LIBARCHIVE_BUILD 1 +#include "archive_getdate.h" + +/* Basic time units. */ +#define EPOCH 1970 +#define MINUTE (60L) +#define HOUR (60L * MINUTE) +#define DAY (24L * HOUR) + +/* Daylight-savings mode: on, off, or not yet known. */ +enum DSTMODE { DSTon, DSToff, DSTmaybe }; +/* Meridian: am or pm. */ +enum { tAM, tPM }; +/* Token types returned by nexttoken() */ +enum { tAGO = 260, tDAY, tDAYZONE, tAMPM, tMONTH, tMONTH_UNIT, tSEC_UNIT, + tUNUMBER, tZONE, tDST }; +struct token { int token; time_t value; }; + +/* + * Parser state. + */ +struct gdstate { + struct token *tokenp; /* Pointer to next token. */ + /* HaveXxxx counts how many of this kind of phrase we've seen; + * it's a fatal error to have more than one time, zone, day, + * or date phrase. */ + int HaveYear; + int HaveMonth; + int HaveDay; + int HaveWeekDay; /* Day of week */ + int HaveTime; /* Hour/minute/second */ + int HaveZone; /* timezone and/or DST info */ + int HaveRel; /* time offset; we can have more than one */ + /* Absolute time values. */ + time_t Timezone; /* Seconds offset from GMT */ + time_t Day; + time_t Hour; + time_t Minutes; + time_t Month; + time_t Seconds; + time_t Year; + /* DST selection */ + enum DSTMODE DSTmode; + /* Day of week accounting, e.g., "3rd Tuesday" */ + time_t DayOrdinal; /* "3" in "3rd Tuesday" */ + time_t DayNumber; /* "Tuesday" in "3rd Tuesday" */ + /* Relative time values: hour/day/week offsets are measured in + * seconds, month/year are counted in months. */ + time_t RelMonth; + time_t RelSeconds; +}; + +/* + * A series of functions that recognize certain common time phrases. + * Each function returns 1 if it managed to make sense of some of the + * tokens, zero otherwise. + */ + +/* + * hour:minute or hour:minute:second with optional AM, PM, or numeric + * timezone offset + */ +static int +timephrase(struct gdstate *gds) +{ + if (gds->tokenp[0].token == tUNUMBER + && gds->tokenp[1].token == ':' + && gds->tokenp[2].token == tUNUMBER + && gds->tokenp[3].token == ':' + && gds->tokenp[4].token == tUNUMBER) { + /* "12:14:18" or "22:08:07" */ + ++gds->HaveTime; + gds->Hour = gds->tokenp[0].value; + gds->Minutes = gds->tokenp[2].value; + gds->Seconds = gds->tokenp[4].value; + gds->tokenp += 5; + } + else if (gds->tokenp[0].token == tUNUMBER + && gds->tokenp[1].token == ':' + && gds->tokenp[2].token == tUNUMBER) { + /* "12:14" or "22:08" */ + ++gds->HaveTime; + gds->Hour = gds->tokenp[0].value; + gds->Minutes = gds->tokenp[2].value; + gds->Seconds = 0; + gds->tokenp += 3; + } + else if (gds->tokenp[0].token == tUNUMBER + && gds->tokenp[1].token == tAMPM) { + /* "7" is a time if it's followed by "am" or "pm" */ + ++gds->HaveTime; + gds->Hour = gds->tokenp[0].value; + gds->Minutes = gds->Seconds = 0; + /* We'll handle the AM/PM below. */ + gds->tokenp += 1; + } else { + /* We can't handle this. */ + return 0; + } + + if (gds->tokenp[0].token == tAMPM) { + /* "7:12pm", "12:20:13am" */ + if (gds->Hour == 12) + gds->Hour = 0; + if (gds->tokenp[0].value == tPM) + gds->Hour += 12; + gds->tokenp += 1; + } + if (gds->tokenp[0].token == '+' + && gds->tokenp[1].token == tUNUMBER) { + /* "7:14+0700" */ + gds->HaveZone++; + gds->DSTmode = DSToff; + gds->Timezone = - ((gds->tokenp[1].value / 100) * HOUR + + (gds->tokenp[1].value % 100) * MINUTE); + gds->tokenp += 2; + } + if (gds->tokenp[0].token == '-' + && gds->tokenp[1].token == tUNUMBER) { + /* "19:14:12-0530" */ + gds->HaveZone++; + gds->DSTmode = DSToff; + gds->Timezone = + ((gds->tokenp[1].value / 100) * HOUR + + (gds->tokenp[1].value % 100) * MINUTE); + gds->tokenp += 2; + } + return 1; +} + +/* + * Timezone name, possibly including DST. + */ +static int +zonephrase(struct gdstate *gds) +{ + if (gds->tokenp[0].token == tZONE + && gds->tokenp[1].token == tDST) { + gds->HaveZone++; + gds->Timezone = gds->tokenp[0].value; + gds->DSTmode = DSTon; + gds->tokenp += 1; + return 1; + } + + if (gds->tokenp[0].token == tZONE) { + gds->HaveZone++; + gds->Timezone = gds->tokenp[0].value; + gds->DSTmode = DSToff; + gds->tokenp += 1; + return 1; + } + + if (gds->tokenp[0].token == tDAYZONE) { + gds->HaveZone++; + gds->Timezone = gds->tokenp[0].value; + gds->DSTmode = DSTon; + gds->tokenp += 1; + return 1; + } + return 0; +} + +/* + * Year/month/day in various combinations. + */ +static int +datephrase(struct gdstate *gds) +{ + if (gds->tokenp[0].token == tUNUMBER + && gds->tokenp[1].token == '/' + && gds->tokenp[2].token == tUNUMBER + && gds->tokenp[3].token == '/' + && gds->tokenp[4].token == tUNUMBER) { + gds->HaveYear++; + gds->HaveMonth++; + gds->HaveDay++; + if (gds->tokenp[0].value >= 13) { + /* First number is big: 2004/01/29, 99/02/17 */ + gds->Year = gds->tokenp[0].value; + gds->Month = gds->tokenp[2].value; + gds->Day = gds->tokenp[4].value; + } else if ((gds->tokenp[4].value >= 13) + || (gds->tokenp[2].value >= 13)) { + /* Last number is big: 01/07/98 */ + /* Middle number is big: 01/29/04 */ + gds->Month = gds->tokenp[0].value; + gds->Day = gds->tokenp[2].value; + gds->Year = gds->tokenp[4].value; + } else { + /* No significant clues: 02/03/04 */ + gds->Month = gds->tokenp[0].value; + gds->Day = gds->tokenp[2].value; + gds->Year = gds->tokenp[4].value; + } + gds->tokenp += 5; + return 1; + } + + if (gds->tokenp[0].token == tUNUMBER + && gds->tokenp[1].token == '/' + && gds->tokenp[2].token == tUNUMBER) { + /* "1/15" */ + gds->HaveMonth++; + gds->HaveDay++; + gds->Month = gds->tokenp[0].value; + gds->Day = gds->tokenp[2].value; + gds->tokenp += 3; + return 1; + } + + if (gds->tokenp[0].token == tUNUMBER + && gds->tokenp[1].token == '-' + && gds->tokenp[2].token == tUNUMBER + && gds->tokenp[3].token == '-' + && gds->tokenp[4].token == tUNUMBER) { + /* ISO 8601 format. yyyy-mm-dd. */ + gds->HaveYear++; + gds->HaveMonth++; + gds->HaveDay++; + gds->Year = gds->tokenp[0].value; + gds->Month = gds->tokenp[2].value; + gds->Day = gds->tokenp[4].value; + gds->tokenp += 5; + return 1; + } + + if (gds->tokenp[0].token == tUNUMBER + && gds->tokenp[1].token == '-' + && gds->tokenp[2].token == tMONTH + && gds->tokenp[3].token == '-' + && gds->tokenp[4].token == tUNUMBER) { + gds->HaveYear++; + gds->HaveMonth++; + gds->HaveDay++; + if (gds->tokenp[0].value > 31) { + /* e.g. 1992-Jun-17 */ + gds->Year = gds->tokenp[0].value; + gds->Month = gds->tokenp[2].value; + gds->Day = gds->tokenp[4].value; + } else { + /* e.g. 17-JUN-1992. */ + gds->Day = gds->tokenp[0].value; + gds->Month = gds->tokenp[2].value; + gds->Year = gds->tokenp[4].value; + } + gds->tokenp += 5; + return 1; + } + + if (gds->tokenp[0].token == tMONTH + && gds->tokenp[1].token == tUNUMBER + && gds->tokenp[2].token == ',' + && gds->tokenp[3].token == tUNUMBER) { + /* "June 17, 2001" */ + gds->HaveYear++; + gds->HaveMonth++; + gds->HaveDay++; + gds->Month = gds->tokenp[0].value; + gds->Day = gds->tokenp[1].value; + gds->Year = gds->tokenp[3].value; + gds->tokenp += 4; + return 1; + } + + if (gds->tokenp[0].token == tMONTH + && gds->tokenp[1].token == tUNUMBER) { + /* "May 3" */ + gds->HaveMonth++; + gds->HaveDay++; + gds->Month = gds->tokenp[0].value; + gds->Day = gds->tokenp[1].value; + gds->tokenp += 2; + return 1; + } + + if (gds->tokenp[0].token == tUNUMBER + && gds->tokenp[1].token == tMONTH + && gds->tokenp[2].token == tUNUMBER) { + /* "12 Sept 1997" */ + gds->HaveYear++; + gds->HaveMonth++; + gds->HaveDay++; + gds->Day = gds->tokenp[0].value; + gds->Month = gds->tokenp[1].value; + gds->Year = gds->tokenp[2].value; + gds->tokenp += 3; + return 1; + } + + if (gds->tokenp[0].token == tUNUMBER + && gds->tokenp[1].token == tMONTH) { + /* "12 Sept" */ + gds->HaveMonth++; + gds->HaveDay++; + gds->Day = gds->tokenp[0].value; + gds->Month = gds->tokenp[1].value; + gds->tokenp += 2; + return 1; + } + + return 0; +} + +/* + * Relative time phrase: "tomorrow", "yesterday", "+1 hour", etc. + */ +static int +relunitphrase(struct gdstate *gds) +{ + if (gds->tokenp[0].token == '-' + && gds->tokenp[1].token == tUNUMBER + && gds->tokenp[2].token == tSEC_UNIT) { + /* "-3 hours" */ + gds->HaveRel++; + gds->RelSeconds -= gds->tokenp[1].value * gds->tokenp[2].value; + gds->tokenp += 3; + return 1; + } + if (gds->tokenp[0].token == '+' + && gds->tokenp[1].token == tUNUMBER + && gds->tokenp[2].token == tSEC_UNIT) { + /* "+1 minute" */ + gds->HaveRel++; + gds->RelSeconds += gds->tokenp[1].value * gds->tokenp[2].value; + gds->tokenp += 3; + return 1; + } + if (gds->tokenp[0].token == tUNUMBER + && gds->tokenp[1].token == tSEC_UNIT) { + /* "1 day" */ + gds->HaveRel++; + gds->RelSeconds += gds->tokenp[0].value * gds->tokenp[1].value; + gds->tokenp += 2; + return 1; + } + if (gds->tokenp[0].token == '-' + && gds->tokenp[1].token == tUNUMBER + && gds->tokenp[2].token == tMONTH_UNIT) { + /* "-3 months" */ + gds->HaveRel++; + gds->RelMonth -= gds->tokenp[1].value * gds->tokenp[2].value; + gds->tokenp += 3; + return 1; + } + if (gds->tokenp[0].token == '+' + && gds->tokenp[1].token == tUNUMBER + && gds->tokenp[2].token == tMONTH_UNIT) { + /* "+5 years" */ + gds->HaveRel++; + gds->RelMonth += gds->tokenp[1].value * gds->tokenp[2].value; + gds->tokenp += 3; + return 1; + } + if (gds->tokenp[0].token == tUNUMBER + && gds->tokenp[1].token == tMONTH_UNIT) { + /* "2 years" */ + gds->HaveRel++; + gds->RelMonth += gds->tokenp[0].value * gds->tokenp[1].value; + gds->tokenp += 2; + return 1; + } + if (gds->tokenp[0].token == tSEC_UNIT) { + /* "now", "tomorrow" */ + gds->HaveRel++; + gds->RelSeconds += gds->tokenp[0].value; + gds->tokenp += 1; + return 1; + } + if (gds->tokenp[0].token == tMONTH_UNIT) { + /* "month" */ + gds->HaveRel++; + gds->RelMonth += gds->tokenp[0].value; + gds->tokenp += 1; + return 1; + } + return 0; +} + +/* + * Day of the week specification. + */ +static int +dayphrase(struct gdstate *gds) +{ + if (gds->tokenp[0].token == tDAY) { + /* "tues", "wednesday," */ + gds->HaveWeekDay++; + gds->DayOrdinal = 1; + gds->DayNumber = gds->tokenp[0].value; + gds->tokenp += 1; + if (gds->tokenp[0].token == ',') + gds->tokenp += 1; + return 1; + } + if (gds->tokenp[0].token == tUNUMBER + && gds->tokenp[1].token == tDAY) { + /* "second tues" "3 wed" */ + gds->HaveWeekDay++; + gds->DayOrdinal = gds->tokenp[0].value; + gds->DayNumber = gds->tokenp[1].value; + gds->tokenp += 2; + return 1; + } + return 0; +} + +/* + * Try to match a phrase using one of the above functions. + * This layer also deals with a couple of generic issues. + */ +static int +phrase(struct gdstate *gds) +{ + if (timephrase(gds)) + return 1; + if (zonephrase(gds)) + return 1; + if (datephrase(gds)) + return 1; + if (dayphrase(gds)) + return 1; + if (relunitphrase(gds)) { + if (gds->tokenp[0].token == tAGO) { + gds->RelSeconds = -gds->RelSeconds; + gds->RelMonth = -gds->RelMonth; + gds->tokenp += 1; + } + return 1; + } + + /* Bare numbers sometimes have meaning. */ + if (gds->tokenp[0].token == tUNUMBER) { + if (gds->HaveTime && !gds->HaveYear && !gds->HaveRel) { + gds->HaveYear++; + gds->Year = gds->tokenp[0].value; + gds->tokenp += 1; + return 1; + } + + if(gds->tokenp[0].value > 10000) { + /* "20040301" */ + gds->HaveYear++; + gds->HaveMonth++; + gds->HaveDay++; + gds->Day= (gds->tokenp[0].value)%100; + gds->Month= (gds->tokenp[0].value/100)%100; + gds->Year = gds->tokenp[0].value/10000; + gds->tokenp += 1; + return 1; + } + + if (gds->tokenp[0].value < 24) { + gds->HaveTime++; + gds->Hour = gds->tokenp[0].value; + gds->Minutes = 0; + gds->Seconds = 0; + gds->tokenp += 1; + return 1; + } + + if ((gds->tokenp[0].value / 100 < 24) + && (gds->tokenp[0].value % 100 < 60)) { + /* "513" is same as "5:13" */ + gds->Hour = gds->tokenp[0].value / 100; + gds->Minutes = gds->tokenp[0].value % 100; + gds->Seconds = 0; + gds->tokenp += 1; + return 1; + } + } + + return 0; +} + +/* + * A dictionary of time words. + */ +static struct LEXICON { + size_t abbrev; + const char *name; + int type; + time_t value; +} const TimeWords[] = { + /* am/pm */ + { 0, "am", tAMPM, tAM }, + { 0, "pm", tAMPM, tPM }, + + /* Month names. */ + { 3, "january", tMONTH, 1 }, + { 3, "february", tMONTH, 2 }, + { 3, "march", tMONTH, 3 }, + { 3, "april", tMONTH, 4 }, + { 3, "may", tMONTH, 5 }, + { 3, "june", tMONTH, 6 }, + { 3, "july", tMONTH, 7 }, + { 3, "august", tMONTH, 8 }, + { 3, "september", tMONTH, 9 }, + { 3, "october", tMONTH, 10 }, + { 3, "november", tMONTH, 11 }, + { 3, "december", tMONTH, 12 }, + + /* Days of the week. */ + { 2, "sunday", tDAY, 0 }, + { 3, "monday", tDAY, 1 }, + { 2, "tuesday", tDAY, 2 }, + { 3, "wednesday", tDAY, 3 }, + { 2, "thursday", tDAY, 4 }, + { 2, "friday", tDAY, 5 }, + { 2, "saturday", tDAY, 6 }, + + /* Timezones: Offsets are in seconds. */ + { 0, "gmt", tZONE, 0*HOUR }, /* Greenwich Mean */ + { 0, "ut", tZONE, 0*HOUR }, /* Universal (Coordinated) */ + { 0, "utc", tZONE, 0*HOUR }, + { 0, "wet", tZONE, 0*HOUR }, /* Western European */ + { 0, "bst", tDAYZONE, 0*HOUR }, /* British Summer */ + { 0, "wat", tZONE, 1*HOUR }, /* West Africa */ + { 0, "at", tZONE, 2*HOUR }, /* Azores */ + /* { 0, "bst", tZONE, 3*HOUR }, */ /* Brazil Standard: Conflict */ + /* { 0, "gst", tZONE, 3*HOUR }, */ /* Greenland Standard: Conflict*/ + { 0, "nft", tZONE, 3*HOUR+30*MINUTE }, /* Newfoundland */ + { 0, "nst", tZONE, 3*HOUR+30*MINUTE }, /* Newfoundland Standard */ + { 0, "ndt", tDAYZONE, 3*HOUR+30*MINUTE }, /* Newfoundland Daylight */ + { 0, "ast", tZONE, 4*HOUR }, /* Atlantic Standard */ + { 0, "adt", tDAYZONE, 4*HOUR }, /* Atlantic Daylight */ + { 0, "est", tZONE, 5*HOUR }, /* Eastern Standard */ + { 0, "edt", tDAYZONE, 5*HOUR }, /* Eastern Daylight */ + { 0, "cst", tZONE, 6*HOUR }, /* Central Standard */ + { 0, "cdt", tDAYZONE, 6*HOUR }, /* Central Daylight */ + { 0, "mst", tZONE, 7*HOUR }, /* Mountain Standard */ + { 0, "mdt", tDAYZONE, 7*HOUR }, /* Mountain Daylight */ + { 0, "pst", tZONE, 8*HOUR }, /* Pacific Standard */ + { 0, "pdt", tDAYZONE, 8*HOUR }, /* Pacific Daylight */ + { 0, "yst", tZONE, 9*HOUR }, /* Yukon Standard */ + { 0, "ydt", tDAYZONE, 9*HOUR }, /* Yukon Daylight */ + { 0, "hst", tZONE, 10*HOUR }, /* Hawaii Standard */ + { 0, "hdt", tDAYZONE, 10*HOUR }, /* Hawaii Daylight */ + { 0, "cat", tZONE, 10*HOUR }, /* Central Alaska */ + { 0, "ahst", tZONE, 10*HOUR }, /* Alaska-Hawaii Standard */ + { 0, "nt", tZONE, 11*HOUR }, /* Nome */ + { 0, "idlw", tZONE, 12*HOUR }, /* Intl Date Line West */ + { 0, "cet", tZONE, -1*HOUR }, /* Central European */ + { 0, "met", tZONE, -1*HOUR }, /* Middle European */ + { 0, "mewt", tZONE, -1*HOUR }, /* Middle European Winter */ + { 0, "mest", tDAYZONE, -1*HOUR }, /* Middle European Summer */ + { 0, "swt", tZONE, -1*HOUR }, /* Swedish Winter */ + { 0, "sst", tDAYZONE, -1*HOUR }, /* Swedish Summer */ + { 0, "fwt", tZONE, -1*HOUR }, /* French Winter */ + { 0, "fst", tDAYZONE, -1*HOUR }, /* French Summer */ + { 0, "eet", tZONE, -2*HOUR }, /* Eastern Eur, USSR Zone 1 */ + { 0, "bt", tZONE, -3*HOUR }, /* Baghdad, USSR Zone 2 */ + { 0, "it", tZONE, -3*HOUR-30*MINUTE },/* Iran */ + { 0, "zp4", tZONE, -4*HOUR }, /* USSR Zone 3 */ + { 0, "zp5", tZONE, -5*HOUR }, /* USSR Zone 4 */ + { 0, "ist", tZONE, -5*HOUR-30*MINUTE },/* Indian Standard */ + { 0, "zp6", tZONE, -6*HOUR }, /* USSR Zone 5 */ + /* { 0, "nst", tZONE, -6.5*HOUR }, */ /* North Sumatra: Conflict */ + /* { 0, "sst", tZONE, -7*HOUR }, */ /* So Sumatra, USSR 6: Conflict */ + { 0, "wast", tZONE, -7*HOUR }, /* West Australian Standard */ + { 0, "wadt", tDAYZONE, -7*HOUR }, /* West Australian Daylight */ + { 0, "jt", tZONE, -7*HOUR-30*MINUTE },/* Java (3pm in Cronusland!)*/ + { 0, "cct", tZONE, -8*HOUR }, /* China Coast, USSR Zone 7 */ + { 0, "jst", tZONE, -9*HOUR }, /* Japan Std, USSR Zone 8 */ + { 0, "cast", tZONE, -9*HOUR-30*MINUTE },/* Ctrl Australian Std */ + { 0, "cadt", tDAYZONE, -9*HOUR-30*MINUTE },/* Ctrl Australian Daylt */ + { 0, "east", tZONE, -10*HOUR }, /* Eastern Australian Std */ + { 0, "eadt", tDAYZONE, -10*HOUR }, /* Eastern Australian Daylt */ + { 0, "gst", tZONE, -10*HOUR }, /* Guam Std, USSR Zone 9 */ + { 0, "nzt", tZONE, -12*HOUR }, /* New Zealand */ + { 0, "nzst", tZONE, -12*HOUR }, /* New Zealand Standard */ + { 0, "nzdt", tDAYZONE, -12*HOUR }, /* New Zealand Daylight */ + { 0, "idle", tZONE, -12*HOUR }, /* Intl Date Line East */ + + { 0, "dst", tDST, 0 }, + + /* Time units. */ + { 4, "years", tMONTH_UNIT, 12 }, + { 5, "months", tMONTH_UNIT, 1 }, + { 9, "fortnights", tSEC_UNIT, 14 * DAY }, + { 4, "weeks", tSEC_UNIT, 7 * DAY }, + { 3, "days", tSEC_UNIT, DAY }, + { 4, "hours", tSEC_UNIT, HOUR }, + { 3, "minutes", tSEC_UNIT, MINUTE }, + { 3, "seconds", tSEC_UNIT, 1 }, + + /* Relative-time words. */ + { 0, "tomorrow", tSEC_UNIT, DAY }, + { 0, "yesterday", tSEC_UNIT, -DAY }, + { 0, "today", tSEC_UNIT, 0 }, + { 0, "now", tSEC_UNIT, 0 }, + { 0, "last", tUNUMBER, -1 }, + { 0, "this", tSEC_UNIT, 0 }, + { 0, "next", tUNUMBER, 2 }, + { 0, "first", tUNUMBER, 1 }, + { 0, "1st", tUNUMBER, 1 }, +/* { 0, "second", tUNUMBER, 2 }, */ + { 0, "2nd", tUNUMBER, 2 }, + { 0, "third", tUNUMBER, 3 }, + { 0, "3rd", tUNUMBER, 3 }, + { 0, "fourth", tUNUMBER, 4 }, + { 0, "4th", tUNUMBER, 4 }, + { 0, "fifth", tUNUMBER, 5 }, + { 0, "5th", tUNUMBER, 5 }, + { 0, "sixth", tUNUMBER, 6 }, + { 0, "seventh", tUNUMBER, 7 }, + { 0, "eighth", tUNUMBER, 8 }, + { 0, "ninth", tUNUMBER, 9 }, + { 0, "tenth", tUNUMBER, 10 }, + { 0, "eleventh", tUNUMBER, 11 }, + { 0, "twelfth", tUNUMBER, 12 }, + { 0, "ago", tAGO, 1 }, + + /* Military timezones. */ + { 0, "a", tZONE, 1*HOUR }, + { 0, "b", tZONE, 2*HOUR }, + { 0, "c", tZONE, 3*HOUR }, + { 0, "d", tZONE, 4*HOUR }, + { 0, "e", tZONE, 5*HOUR }, + { 0, "f", tZONE, 6*HOUR }, + { 0, "g", tZONE, 7*HOUR }, + { 0, "h", tZONE, 8*HOUR }, + { 0, "i", tZONE, 9*HOUR }, + { 0, "k", tZONE, 10*HOUR }, + { 0, "l", tZONE, 11*HOUR }, + { 0, "m", tZONE, 12*HOUR }, + { 0, "n", tZONE, -1*HOUR }, + { 0, "o", tZONE, -2*HOUR }, + { 0, "p", tZONE, -3*HOUR }, + { 0, "q", tZONE, -4*HOUR }, + { 0, "r", tZONE, -5*HOUR }, + { 0, "s", tZONE, -6*HOUR }, + { 0, "t", tZONE, -7*HOUR }, + { 0, "u", tZONE, -8*HOUR }, + { 0, "v", tZONE, -9*HOUR }, + { 0, "w", tZONE, -10*HOUR }, + { 0, "x", tZONE, -11*HOUR }, + { 0, "y", tZONE, -12*HOUR }, + { 0, "z", tZONE, 0*HOUR }, + + /* End of table. */ + { 0, NULL, 0, 0 } +}; + +/* + * Year is either: + * = A number from 0 to 99, which means a year from 1970 to 2069, or + * = The actual year (>=100). + */ +static time_t +Convert(time_t Month, time_t Day, time_t Year, + time_t Hours, time_t Minutes, time_t Seconds, + time_t Timezone, enum DSTMODE DSTmode) +{ + signed char DaysInMonth[12] = { + 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 + }; + time_t Julian; + int i; + struct tm *ltime; +#if defined(HAVE_LOCALTIME_R) || defined(HAVE__LOCALTIME64_S) + struct tm tmbuf; +#endif +#if defined(HAVE__LOCALTIME64_S) + errno_t terr; + __time64_t tmptime; +#endif + + if (Year < 69) + Year += 2000; + else if (Year < 100) + Year += 1900; + DaysInMonth[1] = Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0) + ? 29 : 28; + /* Checking for 2038 bogusly assumes that time_t is 32 bits. But + I'm too lazy to try to check for time_t overflow in another way. */ + if (Year < EPOCH || Year > 2038 + || Month < 1 || Month > 12 + /* Lint fluff: "conversion from long may lose accuracy" */ + || Day < 1 || Day > DaysInMonth[(int)--Month] + || Hours < 0 || Hours > 23 + || Minutes < 0 || Minutes > 59 + || Seconds < 0 || Seconds > 59) + return -1; + + Julian = Day - 1; + for (i = 0; i < Month; i++) + Julian += DaysInMonth[i]; + for (i = EPOCH; i < Year; i++) + Julian += 365 + (i % 4 == 0); + Julian *= DAY; + Julian += Timezone; + Julian += Hours * HOUR + Minutes * MINUTE + Seconds; +#if defined(HAVE_LOCALTIME_R) + ltime = localtime_r(&Julian, &tmbuf); +#elif defined(HAVE__LOCALTIME64_S) + tmptime = Julian; + terr = _localtime64_s(&tmbuf, &tmptime); + if (terr) + ltime = NULL; + else + ltime = &tmbuf; +#else + ltime = localtime(&Julian); +#endif + if (DSTmode == DSTon + || (DSTmode == DSTmaybe && ltime->tm_isdst)) + Julian -= HOUR; + return Julian; +} + +static time_t +DSTcorrect(time_t Start, time_t Future) +{ + time_t StartDay; + time_t FutureDay; + struct tm *ltime; +#if defined(HAVE_LOCALTIME_R) || defined(HAVE__LOCALTIME64_S) + struct tm tmbuf; +#endif +#if defined(HAVE__LOCALTIME64_S) + errno_t terr; + __time64_t tmptime; +#endif + +#if defined(HAVE_LOCALTIME_R) + ltime = localtime_r(&Start, &tmbuf); +#elif defined(HAVE__LOCALTIME64_S) + tmptime = Start; + terr = _localtime64_s(&tmbuf, &tmptime); + if (terr) + ltime = NULL; + else + ltime = &tmbuf; +#else + ltime = localtime(&Start); +#endif + StartDay = (ltime->tm_hour + 1) % 24; +#if defined(HAVE_LOCALTIME_R) + ltime = localtime_r(&Future, &tmbuf); +#elif defined(HAVE__LOCALTIME64_S) + tmptime = Future; + terr = _localtime64_s(&tmbuf, &tmptime); + if (terr) + ltime = NULL; + else + ltime = &tmbuf; +#else + ltime = localtime(&Future); +#endif + FutureDay = (ltime->tm_hour + 1) % 24; + return (Future - Start) + (StartDay - FutureDay) * HOUR; +} + + +static time_t +RelativeDate(time_t Start, time_t zone, int dstmode, + time_t DayOrdinal, time_t DayNumber) +{ + struct tm *tm; + time_t t, now; +#if defined(HAVE_GMTIME_R) || defined(HAVE__GMTIME64_S) + struct tm tmbuf; +#endif +#if defined(HAVE__GMTIME64_S) + errno_t terr; + __time64_t tmptime; +#endif + + t = Start - zone; +#if defined(HAVE_GMTIME_R) + tm = gmtime_r(&t, &tmbuf); +#elif defined(HAVE__GMTIME64_S) + tmptime = t; + terr = _gmtime64_s(&tmbuf, &tmptime); + if (terr) + tm = NULL; + else + tm = &tmbuf; +#else + tm = gmtime(&t); +#endif + now = Start; + now += DAY * ((DayNumber - tm->tm_wday + 7) % 7); + now += 7 * DAY * (DayOrdinal <= 0 ? DayOrdinal : DayOrdinal - 1); + if (dstmode == DSTmaybe) + return DSTcorrect(Start, now); + return now - Start; +} + + +static time_t +RelativeMonth(time_t Start, time_t Timezone, time_t RelMonth) +{ + struct tm *tm; + time_t Month; + time_t Year; +#if defined(HAVE_LOCALTIME_R) || defined(HAVE__LOCALTIME64_S) + struct tm tmbuf; +#endif +#if defined(HAVE__LOCALTIME64_S) + errno_t terr; + __time64_t tmptime; +#endif + + if (RelMonth == 0) + return 0; +#if defined(HAVE_LOCALTIME_R) + tm = localtime_r(&Start, &tmbuf); +#elif defined(HAVE__LOCALTIME64_S) + tmptime = Start; + terr = _localtime64_s(&tmbuf, &tmptime); + if (terr) + tm = NULL; + else + tm = &tmbuf; +#else + tm = localtime(&Start); +#endif + Month = 12 * (tm->tm_year + 1900) + tm->tm_mon + RelMonth; + Year = Month / 12; + Month = Month % 12 + 1; + return DSTcorrect(Start, + Convert(Month, (time_t)tm->tm_mday, Year, + (time_t)tm->tm_hour, (time_t)tm->tm_min, (time_t)tm->tm_sec, + Timezone, DSTmaybe)); +} + +/* + * Tokenizer. + */ +static int +nexttoken(const char **in, time_t *value) +{ + char c; + char buff[64]; + + for ( ; ; ) { + while (isspace((unsigned char)**in)) + ++*in; + + /* Skip parenthesized comments. */ + if (**in == '(') { + int Count = 0; + do { + c = *(*in)++; + if (c == '\0') + return c; + if (c == '(') + Count++; + else if (c == ')') + Count--; + } while (Count > 0); + continue; + } + + /* Try the next token in the word table first. */ + /* This allows us to match "2nd", for example. */ + { + const char *src = *in; + const struct LEXICON *tp; + unsigned i = 0; + + /* Force to lowercase and strip '.' characters. */ + while (*src != '\0' + && (isalnum((unsigned char)*src) || *src == '.') + && i < sizeof(buff)-1) { + if (*src != '.') { + if (isupper((unsigned char)*src)) + buff[i++] = tolower((unsigned char)*src); + else + buff[i++] = *src; + } + src++; + } + buff[i] = '\0'; + + /* + * Find the first match. If the word can be + * abbreviated, make sure we match at least + * the minimum abbreviation. + */ + for (tp = TimeWords; tp->name; tp++) { + size_t abbrev = tp->abbrev; + if (abbrev == 0) + abbrev = strlen(tp->name); + if (strlen(buff) >= abbrev + && strncmp(tp->name, buff, strlen(buff)) + == 0) { + /* Skip over token. */ + *in = src; + /* Return the match. */ + *value = tp->value; + return tp->type; + } + } + } + + /* + * Not in the word table, maybe it's a number. Note: + * Because '-' and '+' have other special meanings, I + * don't deal with signed numbers here. + */ + if (isdigit((unsigned char)(c = **in))) { + for (*value = 0; isdigit((unsigned char)(c = *(*in)++)); ) + *value = 10 * *value + c - '0'; + (*in)--; + return (tUNUMBER); + } + + return *(*in)++; + } +} + +#define TM_YEAR_ORIGIN 1900 + +/* Yield A - B, measured in seconds. */ +static long +difftm (struct tm *a, struct tm *b) +{ + int ay = a->tm_year + (TM_YEAR_ORIGIN - 1); + int by = b->tm_year + (TM_YEAR_ORIGIN - 1); + int days = ( + /* difference in day of year */ + a->tm_yday - b->tm_yday + /* + intervening leap days */ + + ((ay >> 2) - (by >> 2)) + - (ay/100 - by/100) + + ((ay/100 >> 2) - (by/100 >> 2)) + /* + difference in years * 365 */ + + (long)(ay-by) * 365 + ); + return (days * DAY + (a->tm_hour - b->tm_hour) * HOUR + + (a->tm_min - b->tm_min) * MINUTE + + (a->tm_sec - b->tm_sec)); +} + +/* + * + * The public function. + * + * TODO: tokens[] array should be dynamically sized. + */ +time_t +__archive_get_date(time_t now, const char *p) +{ + struct token tokens[256]; + struct gdstate _gds; + struct token *lasttoken; + struct gdstate *gds; + struct tm local, *tm; + struct tm gmt, *gmt_ptr; + time_t Start; + time_t tod; + long tzone; +#if defined(HAVE__LOCALTIME64_S) || defined(HAVE__GMTIME64_S) + errno_t terr; + __time64_t tmptime; +#endif + + /* Clear out the parsed token array. */ + memset(tokens, 0, sizeof(tokens)); + /* Initialize the parser state. */ + memset(&_gds, 0, sizeof(_gds)); + gds = &_gds; + + /* Look up the current time. */ +#if defined(HAVE_LOCALTIME_R) + tm = localtime_r(&now, &local); +#elif defined(HAVE__LOCALTIME64_S) + tmptime = now; + terr = _localtime64_s(&local, &tmptime); + if (terr) + tm = NULL; + else + tm = &local; +#else + memset(&local, 0, sizeof(local)); + tm = localtime(&now); +#endif + if (tm == NULL) + return -1; +#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE__LOCALTIME64_S) + local = *tm; +#endif + + /* Look up UTC if we can and use that to determine the current + * timezone offset. */ +#if defined(HAVE_GMTIME_R) + gmt_ptr = gmtime_r(&now, &gmt); +#elif defined(HAVE__GMTIME64_S) + tmptime = now; + terr = _gmtime64_s(&gmt, &tmptime); + if (terr) + gmt_ptr = NULL; + else + gmt_ptr = &gmt; +#else + memset(&gmt, 0, sizeof(gmt)); + gmt_ptr = gmtime(&now); + if (gmt_ptr != NULL) { + /* Copy, in case localtime and gmtime use the same buffer. */ + gmt = *gmt_ptr; + } +#endif + if (gmt_ptr != NULL) + tzone = difftm (&gmt, &local); + else + /* This system doesn't understand timezones; fake it. */ + tzone = 0; + if(local.tm_isdst) + tzone += HOUR; + + /* Tokenize the input string. */ + lasttoken = tokens; + while ((lasttoken->token = nexttoken(&p, &lasttoken->value)) != 0) { + ++lasttoken; + if (lasttoken > tokens + 255) + return -1; + } + gds->tokenp = tokens; + + /* Match phrases until we run out of input tokens. */ + while (gds->tokenp < lasttoken) { + if (!phrase(gds)) + return -1; + } + + /* Use current local timezone if none was specified. */ + if (!gds->HaveZone) { + gds->Timezone = tzone; + gds->DSTmode = DSTmaybe; + } + + /* If a timezone was specified, use that for generating the default + * time components instead of the local timezone. */ + if (gds->HaveZone && gmt_ptr != NULL) { + now -= gds->Timezone; +#if defined(HAVE_GMTIME_R) + gmt_ptr = gmtime_r(&now, &gmt); +#elif defined(HAVE__GMTIME64_S) + tmptime = now; + terr = _gmtime64_s(&gmt, &tmptime); + if (terr) + gmt_ptr = NULL; + else + gmt_ptr = &gmt; +#else + gmt_ptr = gmtime(&now); +#endif + if (gmt_ptr != NULL) + local = *gmt_ptr; + now += gds->Timezone; + } + + if (!gds->HaveYear) + gds->Year = local.tm_year + 1900; + if (!gds->HaveMonth) + gds->Month = local.tm_mon + 1; + if (!gds->HaveDay) + gds->Day = local.tm_mday; + /* Note: No default for hour/min/sec; a specifier that just + * gives date always refers to 00:00 on that date. */ + + /* If we saw more than one time, timezone, weekday, year, month, + * or day, then give up. */ + if (gds->HaveTime > 1 || gds->HaveZone > 1 || gds->HaveWeekDay > 1 + || gds->HaveYear > 1 || gds->HaveMonth > 1 || gds->HaveDay > 1) + return -1; + + /* Compute an absolute time based on whatever absolute information + * we collected. */ + if (gds->HaveYear || gds->HaveMonth || gds->HaveDay + || gds->HaveTime || gds->HaveWeekDay) { + Start = Convert(gds->Month, gds->Day, gds->Year, + gds->Hour, gds->Minutes, gds->Seconds, + gds->Timezone, gds->DSTmode); + if (Start < 0) + return -1; + } else { + Start = now; + if (!gds->HaveRel) + Start -= local.tm_hour * HOUR + local.tm_min * MINUTE + + local.tm_sec; + } + + /* Add the relative offset. */ + Start += gds->RelSeconds; + Start += RelativeMonth(Start, gds->Timezone, gds->RelMonth); + + /* Adjust for day-of-week offsets. */ + if (gds->HaveWeekDay + && !(gds->HaveYear || gds->HaveMonth || gds->HaveDay)) { + tod = RelativeDate(Start, gds->Timezone, + gds->DSTmode, gds->DayOrdinal, gds->DayNumber); + Start += tod; + } + + /* -1 is an error indicator, so return 0 instead of -1 if + * that's the actual time. */ + return Start == -1 ? 0 : Start; +} + + +#if defined(TEST) + +/* ARGSUSED */ +int +main(int argc, char **argv) +{ + time_t d; + time_t now = time(NULL); + + while (*++argv != NULL) { + (void)printf("Input: %s\n", *argv); + d = get_date(now, *argv); + if (d == -1) + (void)printf("Bad format - couldn't convert.\n"); + else + (void)printf("Output: %s\n", ctime(&d)); + } + exit(0); + /* NOTREACHED */ +} +#endif /* defined(TEST) */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_getdate.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_getdate.h new file mode 100644 index 0000000000..900a8f692e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_getdate.h @@ -0,0 +1,39 @@ +/*- + * Copyright (c) 2003-2015 Tim Kientzle + * 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(S) ``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(S) 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. + * + * $FreeBSD$ + */ + +#ifndef ARCHIVE_GETDATE_H_INCLUDED +#define ARCHIVE_GETDATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +#include <time.h> + +time_t __archive_get_date(time_t now, const char *); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_hmac.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_hmac.c new file mode 100644 index 0000000000..2a9d04c8d8 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_hmac.c @@ -0,0 +1,305 @@ +/*- +* Copyright (c) 2014 Michihiro NAKAJIMA +* 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(S) ``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(S) 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. +*/ + +#include "archive_platform.h" + +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#include "archive.h" +#include "archive_hmac_private.h" + +/* + * On systems that do not support any recognized crypto libraries, + * the archive_hmac.c file is expected to define no usable symbols. + * + * But some compilers and linkers choke on empty object files, so + * define a public symbol that will always exist. This could + * be removed someday if this file gains another always-present + * symbol definition. + */ +int __libarchive_hmac_build_hack(void) { + return 0; +} + + +#ifdef ARCHIVE_HMAC_USE_Apple_CommonCrypto + +static int +__hmac_sha1_init(archive_hmac_sha1_ctx *ctx, const uint8_t *key, size_t key_len) +{ + CCHmacInit(ctx, kCCHmacAlgSHA1, key, key_len); + return 0; +} + +static void +__hmac_sha1_update(archive_hmac_sha1_ctx *ctx, const uint8_t *data, + size_t data_len) +{ + CCHmacUpdate(ctx, data, data_len); +} + +static void +__hmac_sha1_final(archive_hmac_sha1_ctx *ctx, uint8_t *out, size_t *out_len) +{ + CCHmacFinal(ctx, out); + *out_len = 20; +} + +static void +__hmac_sha1_cleanup(archive_hmac_sha1_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); +} + +#elif defined(_WIN32) && !defined(__CYGWIN__) && defined(HAVE_BCRYPT_H) + +#ifndef BCRYPT_HASH_REUSABLE_FLAG +# define BCRYPT_HASH_REUSABLE_FLAG 0x00000020 +#endif + +static int +__hmac_sha1_init(archive_hmac_sha1_ctx *ctx, const uint8_t *key, size_t key_len) +{ +#ifdef __GNUC__ +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif + BCRYPT_ALG_HANDLE hAlg; + BCRYPT_HASH_HANDLE hHash; + DWORD hash_len; + PBYTE hash; + ULONG result; + NTSTATUS status; + + ctx->hAlg = NULL; + status = BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_SHA1_ALGORITHM, + MS_PRIMITIVE_PROVIDER, BCRYPT_ALG_HANDLE_HMAC_FLAG); + if (!BCRYPT_SUCCESS(status)) + return -1; + status = BCryptGetProperty(hAlg, BCRYPT_HASH_LENGTH, (PUCHAR)&hash_len, + sizeof(hash_len), &result, 0); + if (!BCRYPT_SUCCESS(status)) { + BCryptCloseAlgorithmProvider(hAlg, 0); + return -1; + } + hash = (PBYTE)HeapAlloc(GetProcessHeap(), 0, hash_len); + if (hash == NULL) { + BCryptCloseAlgorithmProvider(hAlg, 0); + return -1; + } + status = BCryptCreateHash(hAlg, &hHash, NULL, 0, + (PUCHAR)key, (ULONG)key_len, BCRYPT_HASH_REUSABLE_FLAG); + if (!BCRYPT_SUCCESS(status)) { + BCryptCloseAlgorithmProvider(hAlg, 0); + HeapFree(GetProcessHeap(), 0, hash); + return -1; + } + + ctx->hAlg = hAlg; + ctx->hHash = hHash; + ctx->hash_len = hash_len; + ctx->hash = hash; + + return 0; +} + +static void +__hmac_sha1_update(archive_hmac_sha1_ctx *ctx, const uint8_t *data, + size_t data_len) +{ + BCryptHashData(ctx->hHash, (PUCHAR)(uintptr_t)data, (ULONG)data_len, 0); +} + +static void +__hmac_sha1_final(archive_hmac_sha1_ctx *ctx, uint8_t *out, size_t *out_len) +{ + BCryptFinishHash(ctx->hHash, ctx->hash, ctx->hash_len, 0); + if (ctx->hash_len == *out_len) + memcpy(out, ctx->hash, *out_len); +} + +static void +__hmac_sha1_cleanup(archive_hmac_sha1_ctx *ctx) +{ + if (ctx->hAlg != NULL) { + BCryptCloseAlgorithmProvider(ctx->hAlg, 0); + HeapFree(GetProcessHeap(), 0, ctx->hash); + ctx->hAlg = NULL; + } +} + +#elif defined(HAVE_LIBMBEDCRYPTO) && defined(HAVE_MBEDTLS_MD_H) + +static int +__hmac_sha1_init(archive_hmac_sha1_ctx *ctx, const uint8_t *key, size_t key_len) +{ + const mbedtls_md_info_t *info; + int ret; + + mbedtls_md_init(ctx); + info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1); + if (info == NULL) { + mbedtls_md_free(ctx); + return (-1); + } + ret = mbedtls_md_setup(ctx, info, 1); + if (ret != 0) { + mbedtls_md_free(ctx); + return (-1); + } + ret = mbedtls_md_hmac_starts(ctx, key, key_len); + if (ret != 0) { + mbedtls_md_free(ctx); + return (-1); + } + return 0; +} + +static void +__hmac_sha1_update(archive_hmac_sha1_ctx *ctx, const uint8_t *data, + size_t data_len) +{ + mbedtls_md_hmac_update(ctx, data, data_len); +} + +static void __hmac_sha1_final(archive_hmac_sha1_ctx *ctx, uint8_t *out, size_t *out_len) +{ + (void)out_len; /* UNUSED */ + + mbedtls_md_hmac_finish(ctx, out); +} + +static void __hmac_sha1_cleanup(archive_hmac_sha1_ctx *ctx) +{ + mbedtls_md_free(ctx); + memset(ctx, 0, sizeof(*ctx)); +} + +#elif defined(HAVE_LIBNETTLE) && defined(HAVE_NETTLE_HMAC_H) + +static int +__hmac_sha1_init(archive_hmac_sha1_ctx *ctx, const uint8_t *key, size_t key_len) +{ + hmac_sha1_set_key(ctx, key_len, key); + return 0; +} + +static void +__hmac_sha1_update(archive_hmac_sha1_ctx *ctx, const uint8_t *data, + size_t data_len) +{ + hmac_sha1_update(ctx, data_len, data); +} + +static void +__hmac_sha1_final(archive_hmac_sha1_ctx *ctx, uint8_t *out, size_t *out_len) +{ + hmac_sha1_digest(ctx, (unsigned)*out_len, out); +} + +static void +__hmac_sha1_cleanup(archive_hmac_sha1_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); +} + +#elif defined(HAVE_LIBCRYPTO) + +static int +__hmac_sha1_init(archive_hmac_sha1_ctx *ctx, const uint8_t *key, size_t key_len) +{ + *ctx = HMAC_CTX_new(); + if (*ctx == NULL) + return -1; + HMAC_Init_ex(*ctx, key, key_len, EVP_sha1(), NULL); + return 0; +} + +static void +__hmac_sha1_update(archive_hmac_sha1_ctx *ctx, const uint8_t *data, + size_t data_len) +{ + HMAC_Update(*ctx, data, data_len); +} + +static void +__hmac_sha1_final(archive_hmac_sha1_ctx *ctx, uint8_t *out, size_t *out_len) +{ + unsigned int len = (unsigned int)*out_len; + + HMAC_Final(*ctx, out, &len); + *out_len = len; +} + +static void +__hmac_sha1_cleanup(archive_hmac_sha1_ctx *ctx) +{ + HMAC_CTX_free(*ctx); + *ctx = NULL; +} + +#else + +/* Stub */ +static int +__hmac_sha1_init(archive_hmac_sha1_ctx *ctx, const uint8_t *key, size_t key_len) +{ + (void)ctx;/* UNUSED */ + (void)key;/* UNUSED */ + (void)key_len;/* UNUSED */ + return -1; +} + +static void +__hmac_sha1_update(archive_hmac_sha1_ctx *ctx, const uint8_t *data, + size_t data_len) +{ + (void)ctx;/* UNUSED */ + (void)data;/* UNUSED */ + (void)data_len;/* UNUSED */ +} + +static void +__hmac_sha1_final(archive_hmac_sha1_ctx *ctx, uint8_t *out, size_t *out_len) +{ + (void)ctx;/* UNUSED */ + (void)out;/* UNUSED */ + (void)out_len;/* UNUSED */ +} + +static void +__hmac_sha1_cleanup(archive_hmac_sha1_ctx *ctx) +{ + (void)ctx;/* UNUSED */ +} + +#endif + +const struct archive_hmac __archive_hmac = { + &__hmac_sha1_init, + &__hmac_sha1_update, + &__hmac_sha1_final, + &__hmac_sha1_cleanup, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_hmac_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_hmac_private.h new file mode 100644 index 0000000000..13a67d4955 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_hmac_private.h @@ -0,0 +1,110 @@ +/*- +* Copyright (c) 2014 Michihiro NAKAJIMA +* 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(S) ``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(S) 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. +*/ + +#ifndef ARCHIVE_HMAC_PRIVATE_H_INCLUDED +#define ARCHIVE_HMAC_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif +/* + * On systems that do not support any recognized crypto libraries, + * the archive_hmac.c file is expected to define no usable symbols. + * + * But some compilers and linkers choke on empty object files, so + * define a public symbol that will always exist. This could + * be removed someday if this file gains another always-present + * symbol definition. + */ +int __libarchive_hmac_build_hack(void); + +#ifdef __APPLE__ +# include <AvailabilityMacros.h> +# if MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 +# define ARCHIVE_HMAC_USE_Apple_CommonCrypto +# endif +#endif + +#ifdef ARCHIVE_HMAC_USE_Apple_CommonCrypto +#include <CommonCrypto/CommonHMAC.h> + +typedef CCHmacContext archive_hmac_sha1_ctx; + +#elif defined(_WIN32) && !defined(__CYGWIN__) && defined(HAVE_BCRYPT_H) +#include <bcrypt.h> + +typedef struct { + BCRYPT_ALG_HANDLE hAlg; + BCRYPT_HASH_HANDLE hHash; + DWORD hash_len; + PBYTE hash; + +} archive_hmac_sha1_ctx; + +#elif defined(HAVE_LIBMBEDCRYPTO) && defined(HAVE_MBEDTLS_MD_H) +#include <mbedtls/md.h> + +typedef mbedtls_md_context_t archive_hmac_sha1_ctx; + +#elif defined(HAVE_LIBNETTLE) && defined(HAVE_NETTLE_HMAC_H) +#include <nettle/hmac.h> + +typedef struct hmac_sha1_ctx archive_hmac_sha1_ctx; + +#elif defined(HAVE_LIBCRYPTO) +#include "archive_openssl_hmac_private.h" + +typedef HMAC_CTX* archive_hmac_sha1_ctx; + +#else + +typedef int archive_hmac_sha1_ctx; + +#endif + + +/* HMAC */ +#define archive_hmac_sha1_init(ctx, key, key_len)\ + __archive_hmac.__hmac_sha1_init(ctx, key, key_len) +#define archive_hmac_sha1_update(ctx, data, data_len)\ + __archive_hmac.__hmac_sha1_update(ctx, data, data_len) +#define archive_hmac_sha1_final(ctx, out, out_len)\ + __archive_hmac.__hmac_sha1_final(ctx, out, out_len) +#define archive_hmac_sha1_cleanup(ctx)\ + __archive_hmac.__hmac_sha1_cleanup(ctx) + + +struct archive_hmac { + /* HMAC */ + int (*__hmac_sha1_init)(archive_hmac_sha1_ctx *, const uint8_t *, + size_t); + void (*__hmac_sha1_update)(archive_hmac_sha1_ctx *, const uint8_t *, + size_t); + void (*__hmac_sha1_final)(archive_hmac_sha1_ctx *, uint8_t *, size_t *); + void (*__hmac_sha1_cleanup)(archive_hmac_sha1_ctx *); +}; + +extern const struct archive_hmac __archive_hmac; +#endif /* ARCHIVE_HMAC_PRIVATE_H_INCLUDED */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_match.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_match.c new file mode 100644 index 0000000000..04747b1f66 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_match.c @@ -0,0 +1,1875 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_entry.h" +#include "archive_getdate.h" +#include "archive_pathmatch.h" +#include "archive_rb.h" +#include "archive_string.h" + +struct match { + struct match *next; + int matches; + struct archive_mstring pattern; +}; + +struct match_list { + struct match *first; + struct match **last; + int count; + int unmatched_count; + struct match *unmatched_next; + int unmatched_eof; +}; + +struct match_file { + struct archive_rb_node node; + struct match_file *next; + struct archive_mstring pathname; + int flag; + time_t mtime_sec; + long mtime_nsec; + time_t ctime_sec; + long ctime_nsec; +}; + +struct entry_list { + struct match_file *first; + struct match_file **last; + int count; +}; + +struct id_array { + size_t size;/* Allocated size */ + size_t count; + int64_t *ids; +}; + +#define PATTERN_IS_SET 1 +#define TIME_IS_SET 2 +#define ID_IS_SET 4 + +struct archive_match { + struct archive archive; + + /* exclusion/inclusion set flag. */ + int setflag; + + /* Recursively include directory content? */ + int recursive_include; + + /* + * Matching filename patterns. + */ + struct match_list exclusions; + struct match_list inclusions; + + /* + * Matching time stamps. + */ + time_t now; + int newer_mtime_filter; + time_t newer_mtime_sec; + long newer_mtime_nsec; + int newer_ctime_filter; + time_t newer_ctime_sec; + long newer_ctime_nsec; + int older_mtime_filter; + time_t older_mtime_sec; + long older_mtime_nsec; + int older_ctime_filter; + time_t older_ctime_sec; + long older_ctime_nsec; + /* + * Matching time stamps with its filename. + */ + struct archive_rb_tree exclusion_tree; + struct entry_list exclusion_entry_list; + + /* + * Matching file owners. + */ + struct id_array inclusion_uids; + struct id_array inclusion_gids; + struct match_list inclusion_unames; + struct match_list inclusion_gnames; +}; + +static int add_pattern_from_file(struct archive_match *, + struct match_list *, int, const void *, int); +static int add_entry(struct archive_match *, int, + struct archive_entry *); +static int add_owner_id(struct archive_match *, struct id_array *, + int64_t); +static int add_owner_name(struct archive_match *, struct match_list *, + int, const void *); +static int add_pattern_mbs(struct archive_match *, struct match_list *, + const char *); +static int add_pattern_wcs(struct archive_match *, struct match_list *, + const wchar_t *); +static int cmp_key_mbs(const struct archive_rb_node *, const void *); +static int cmp_key_wcs(const struct archive_rb_node *, const void *); +static int cmp_node_mbs(const struct archive_rb_node *, + const struct archive_rb_node *); +static int cmp_node_wcs(const struct archive_rb_node *, + const struct archive_rb_node *); +static void entry_list_add(struct entry_list *, struct match_file *); +static void entry_list_free(struct entry_list *); +static void entry_list_init(struct entry_list *); +static int error_nomem(struct archive_match *); +static void match_list_add(struct match_list *, struct match *); +static void match_list_free(struct match_list *); +static void match_list_init(struct match_list *); +static int match_list_unmatched_inclusions_next(struct archive_match *, + struct match_list *, int, const void **); +static int match_owner_id(struct id_array *, int64_t); +#if !defined(_WIN32) || defined(__CYGWIN__) +static int match_owner_name_mbs(struct archive_match *, + struct match_list *, const char *); +#else +static int match_owner_name_wcs(struct archive_match *, + struct match_list *, const wchar_t *); +#endif +static int match_path_exclusion(struct archive_match *, + struct match *, int, const void *); +static int match_path_inclusion(struct archive_match *, + struct match *, int, const void *); +static int owner_excluded(struct archive_match *, + struct archive_entry *); +static int path_excluded(struct archive_match *, int, const void *); +static int set_timefilter(struct archive_match *, int, time_t, long, + time_t, long); +static int set_timefilter_pathname_mbs(struct archive_match *, + int, const char *); +static int set_timefilter_pathname_wcs(struct archive_match *, + int, const wchar_t *); +static int set_timefilter_date(struct archive_match *, int, const char *); +static int set_timefilter_date_w(struct archive_match *, int, + const wchar_t *); +static int time_excluded(struct archive_match *, + struct archive_entry *); +static int validate_time_flag(struct archive *, int, const char *); + +#define get_date __archive_get_date + +static const struct archive_rb_tree_ops rb_ops_mbs = { + cmp_node_mbs, cmp_key_mbs +}; + +static const struct archive_rb_tree_ops rb_ops_wcs = { + cmp_node_wcs, cmp_key_wcs +}; + +/* + * The matching logic here needs to be re-thought. I started out to + * try to mimic gtar's matching logic, but it's not entirely + * consistent. In particular 'tar -t' and 'tar -x' interpret patterns + * on the command line as anchored, but --exclude doesn't. + */ + +static int +error_nomem(struct archive_match *a) +{ + archive_set_error(&(a->archive), ENOMEM, "No memory"); + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); +} + +/* + * Create an ARCHIVE_MATCH object. + */ +struct archive * +archive_match_new(void) +{ + struct archive_match *a; + + a = (struct archive_match *)calloc(1, sizeof(*a)); + if (a == NULL) + return (NULL); + a->archive.magic = ARCHIVE_MATCH_MAGIC; + a->archive.state = ARCHIVE_STATE_NEW; + a->recursive_include = 1; + match_list_init(&(a->inclusions)); + match_list_init(&(a->exclusions)); + __archive_rb_tree_init(&(a->exclusion_tree), &rb_ops_mbs); + entry_list_init(&(a->exclusion_entry_list)); + match_list_init(&(a->inclusion_unames)); + match_list_init(&(a->inclusion_gnames)); + time(&a->now); + return (&(a->archive)); +} + +/* + * Free an ARCHIVE_MATCH object. + */ +int +archive_match_free(struct archive *_a) +{ + struct archive_match *a; + + if (_a == NULL) + return (ARCHIVE_OK); + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_match_free"); + a = (struct archive_match *)_a; + match_list_free(&(a->inclusions)); + match_list_free(&(a->exclusions)); + entry_list_free(&(a->exclusion_entry_list)); + free(a->inclusion_uids.ids); + free(a->inclusion_gids.ids); + match_list_free(&(a->inclusion_unames)); + match_list_free(&(a->inclusion_gnames)); + free(a); + return (ARCHIVE_OK); +} + +/* + * Convenience function to perform all exclusion tests. + * + * Returns 1 if archive entry is excluded. + * Returns 0 if archive entry is not excluded. + * Returns <0 if something error happened. + */ +int +archive_match_excluded(struct archive *_a, struct archive_entry *entry) +{ + struct archive_match *a; + int r; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_excluded_ae"); + + a = (struct archive_match *)_a; + if (entry == NULL) { + archive_set_error(&(a->archive), EINVAL, "entry is NULL"); + return (ARCHIVE_FAILED); + } + + r = 0; + if (a->setflag & PATTERN_IS_SET) { +#if defined(_WIN32) && !defined(__CYGWIN__) + r = path_excluded(a, 0, archive_entry_pathname_w(entry)); +#else + r = path_excluded(a, 1, archive_entry_pathname(entry)); +#endif + if (r != 0) + return (r); + } + + if (a->setflag & TIME_IS_SET) { + r = time_excluded(a, entry); + if (r != 0) + return (r); + } + + if (a->setflag & ID_IS_SET) + r = owner_excluded(a, entry); + return (r); +} + +/* + * Utility functions to manage exclusion/inclusion patterns + */ + +int +archive_match_exclude_pattern(struct archive *_a, const char *pattern) +{ + struct archive_match *a; + int r; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_exclude_pattern"); + a = (struct archive_match *)_a; + + if (pattern == NULL || *pattern == '\0') { + archive_set_error(&(a->archive), EINVAL, "pattern is empty"); + return (ARCHIVE_FAILED); + } + if ((r = add_pattern_mbs(a, &(a->exclusions), pattern)) != ARCHIVE_OK) + return (r); + return (ARCHIVE_OK); +} + +int +archive_match_exclude_pattern_w(struct archive *_a, const wchar_t *pattern) +{ + struct archive_match *a; + int r; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_exclude_pattern_w"); + a = (struct archive_match *)_a; + + if (pattern == NULL || *pattern == L'\0') { + archive_set_error(&(a->archive), EINVAL, "pattern is empty"); + return (ARCHIVE_FAILED); + } + if ((r = add_pattern_wcs(a, &(a->exclusions), pattern)) != ARCHIVE_OK) + return (r); + return (ARCHIVE_OK); +} + +int +archive_match_exclude_pattern_from_file(struct archive *_a, + const char *pathname, int nullSeparator) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_exclude_pattern_from_file"); + a = (struct archive_match *)_a; + + return add_pattern_from_file(a, &(a->exclusions), 1, pathname, + nullSeparator); +} + +int +archive_match_exclude_pattern_from_file_w(struct archive *_a, + const wchar_t *pathname, int nullSeparator) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_exclude_pattern_from_file_w"); + a = (struct archive_match *)_a; + + return add_pattern_from_file(a, &(a->exclusions), 0, pathname, + nullSeparator); +} + +int +archive_match_include_pattern(struct archive *_a, const char *pattern) +{ + struct archive_match *a; + int r; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_include_pattern"); + a = (struct archive_match *)_a; + + if (pattern == NULL || *pattern == '\0') { + archive_set_error(&(a->archive), EINVAL, "pattern is empty"); + return (ARCHIVE_FAILED); + } + if ((r = add_pattern_mbs(a, &(a->inclusions), pattern)) != ARCHIVE_OK) + return (r); + return (ARCHIVE_OK); +} + +int +archive_match_include_pattern_w(struct archive *_a, const wchar_t *pattern) +{ + struct archive_match *a; + int r; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_include_pattern_w"); + a = (struct archive_match *)_a; + + if (pattern == NULL || *pattern == L'\0') { + archive_set_error(&(a->archive), EINVAL, "pattern is empty"); + return (ARCHIVE_FAILED); + } + if ((r = add_pattern_wcs(a, &(a->inclusions), pattern)) != ARCHIVE_OK) + return (r); + return (ARCHIVE_OK); +} + +int +archive_match_include_pattern_from_file(struct archive *_a, + const char *pathname, int nullSeparator) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_include_pattern_from_file"); + a = (struct archive_match *)_a; + + return add_pattern_from_file(a, &(a->inclusions), 1, pathname, + nullSeparator); +} + +int +archive_match_include_pattern_from_file_w(struct archive *_a, + const wchar_t *pathname, int nullSeparator) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_include_pattern_from_file_w"); + a = (struct archive_match *)_a; + + return add_pattern_from_file(a, &(a->inclusions), 0, pathname, + nullSeparator); +} + +/* + * Test functions for pathname patterns. + * + * Returns 1 if archive entry is excluded. + * Returns 0 if archive entry is not excluded. + * Returns <0 if something error happened. + */ +int +archive_match_path_excluded(struct archive *_a, + struct archive_entry *entry) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_path_excluded"); + + a = (struct archive_match *)_a; + if (entry == NULL) { + archive_set_error(&(a->archive), EINVAL, "entry is NULL"); + return (ARCHIVE_FAILED); + } + + /* If we don't have exclusion/inclusion pattern set at all, + * the entry is always not excluded. */ + if ((a->setflag & PATTERN_IS_SET) == 0) + return (0); +#if defined(_WIN32) && !defined(__CYGWIN__) + return (path_excluded(a, 0, archive_entry_pathname_w(entry))); +#else + return (path_excluded(a, 1, archive_entry_pathname(entry))); +#endif +} + +/* + * When recursive inclusion of directory content is enabled, + * an inclusion pattern that matches a directory will also + * include everything beneath that directory. Enabled by default. + * + * For compatibility with GNU tar, exclusion patterns always + * match if a subset of the full patch matches (i.e., they are + * are not rooted at the beginning of the path) and thus there + * is no corresponding non-recursive exclusion mode. + */ +int +archive_match_set_inclusion_recursion(struct archive *_a, int enabled) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_set_inclusion_recursion"); + a = (struct archive_match *)_a; + a->recursive_include = enabled; + return (ARCHIVE_OK); +} + +/* + * Utility functions to get statistic information for inclusion patterns. + */ +int +archive_match_path_unmatched_inclusions(struct archive *_a) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_unmatched_inclusions"); + a = (struct archive_match *)_a; + + return (a->inclusions.unmatched_count); +} + +int +archive_match_path_unmatched_inclusions_next(struct archive *_a, + const char **_p) +{ + struct archive_match *a; + const void *v; + int r; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_unmatched_inclusions_next"); + a = (struct archive_match *)_a; + + r = match_list_unmatched_inclusions_next(a, &(a->inclusions), 1, &v); + *_p = (const char *)v; + return (r); +} + +int +archive_match_path_unmatched_inclusions_next_w(struct archive *_a, + const wchar_t **_p) +{ + struct archive_match *a; + const void *v; + int r; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_unmatched_inclusions_next_w"); + a = (struct archive_match *)_a; + + r = match_list_unmatched_inclusions_next(a, &(a->inclusions), 0, &v); + *_p = (const wchar_t *)v; + return (r); +} + +/* + * Add inclusion/exclusion patterns. + */ +static int +add_pattern_mbs(struct archive_match *a, struct match_list *list, + const char *pattern) +{ + struct match *match; + size_t len; + + match = calloc(1, sizeof(*match)); + if (match == NULL) + return (error_nomem(a)); + /* Both "foo/" and "foo" should match "foo/bar". */ + len = strlen(pattern); + if (len && pattern[len - 1] == '/') + --len; + archive_mstring_copy_mbs_len(&(match->pattern), pattern, len); + match_list_add(list, match); + a->setflag |= PATTERN_IS_SET; + return (ARCHIVE_OK); +} + +static int +add_pattern_wcs(struct archive_match *a, struct match_list *list, + const wchar_t *pattern) +{ + struct match *match; + size_t len; + + match = calloc(1, sizeof(*match)); + if (match == NULL) + return (error_nomem(a)); + /* Both "foo/" and "foo" should match "foo/bar". */ + len = wcslen(pattern); + if (len && pattern[len - 1] == L'/') + --len; + archive_mstring_copy_wcs_len(&(match->pattern), pattern, len); + match_list_add(list, match); + a->setflag |= PATTERN_IS_SET; + return (ARCHIVE_OK); +} + +static int +add_pattern_from_file(struct archive_match *a, struct match_list *mlist, + int mbs, const void *pathname, int nullSeparator) +{ + struct archive *ar; + struct archive_entry *ae; + struct archive_string as; + const void *buff; + size_t size; + int64_t offset; + int r; + + ar = archive_read_new(); + if (ar == NULL) { + archive_set_error(&(a->archive), ENOMEM, "No memory"); + return (ARCHIVE_FATAL); + } + r = archive_read_support_format_raw(ar); + r = archive_read_support_format_empty(ar); + if (r != ARCHIVE_OK) { + archive_copy_error(&(a->archive), ar); + archive_read_free(ar); + return (r); + } + if (mbs) + r = archive_read_open_filename(ar, pathname, 512*20); + else + r = archive_read_open_filename_w(ar, pathname, 512*20); + if (r != ARCHIVE_OK) { + archive_copy_error(&(a->archive), ar); + archive_read_free(ar); + return (r); + } + r = archive_read_next_header(ar, &ae); + if (r != ARCHIVE_OK) { + archive_read_free(ar); + if (r == ARCHIVE_EOF) { + return (ARCHIVE_OK); + } else { + archive_copy_error(&(a->archive), ar); + return (r); + } + } + + archive_string_init(&as); + + while ((r = archive_read_data_block(ar, &buff, &size, &offset)) + == ARCHIVE_OK) { + const char *b = (const char *)buff; + + while (size) { + const char *s = (const char *)b; + size_t length = 0; + int found_separator = 0; + + while (length < size) { + if (nullSeparator) { + if (*b == '\0') { + found_separator = 1; + break; + } + } else { + if (*b == 0x0d || *b == 0x0a) { + found_separator = 1; + break; + } + } + b++; + length++; + } + if (!found_separator) { + archive_strncat(&as, s, length); + /* Read next data block. */ + break; + } + b++; + size -= length + 1; + archive_strncat(&as, s, length); + + /* If the line is not empty, add the pattern. */ + if (archive_strlen(&as) > 0) { + /* Add pattern. */ + r = add_pattern_mbs(a, mlist, as.s); + if (r != ARCHIVE_OK) { + archive_read_free(ar); + archive_string_free(&as); + return (r); + } + archive_string_empty(&as); + } + } + } + + /* If an error occurred, report it immediately. */ + if (r < ARCHIVE_OK) { + archive_copy_error(&(a->archive), ar); + archive_read_free(ar); + archive_string_free(&as); + return (r); + } + + /* If the line is not empty, add the pattern. */ + if (r == ARCHIVE_EOF && archive_strlen(&as) > 0) { + /* Add pattern. */ + r = add_pattern_mbs(a, mlist, as.s); + if (r != ARCHIVE_OK) { + archive_read_free(ar); + archive_string_free(&as); + return (r); + } + } + archive_read_free(ar); + archive_string_free(&as); + return (ARCHIVE_OK); +} + +/* + * Test if pathname is excluded by inclusion/exclusion patterns. + */ +static int +path_excluded(struct archive_match *a, int mbs, const void *pathname) +{ + struct match *match; + struct match *matched; + int r; + + if (a == NULL) + return (0); + + /* Mark off any unmatched inclusions. */ + /* In particular, if a filename does appear in the archive and + * is explicitly included and excluded, then we don't report + * it as missing even though we don't extract it. + */ + matched = NULL; + for (match = a->inclusions.first; match != NULL; + match = match->next){ + if (match->matches == 0 && + (r = match_path_inclusion(a, match, mbs, pathname)) != 0) { + if (r < 0) + return (r); + a->inclusions.unmatched_count--; + match->matches++; + matched = match; + } + } + + /* Exclusions take priority */ + for (match = a->exclusions.first; match != NULL; + match = match->next){ + r = match_path_exclusion(a, match, mbs, pathname); + if (r) + return (r); + } + + /* It's not excluded and we found an inclusion above, so it's + * included. */ + if (matched != NULL) + return (0); + + + /* We didn't find an unmatched inclusion, check the remaining ones. */ + for (match = a->inclusions.first; match != NULL; + match = match->next){ + /* We looked at previously-unmatched inclusions already. */ + if (match->matches > 0 && + (r = match_path_inclusion(a, match, mbs, pathname)) != 0) { + if (r < 0) + return (r); + match->matches++; + return (0); + } + } + + /* If there were inclusions, default is to exclude. */ + if (a->inclusions.first != NULL) + return (1); + + /* No explicit inclusions, default is to match. */ + return (0); +} + +/* + * This is a little odd, but it matches the default behavior of + * gtar. In particular, 'a*b' will match 'foo/a1111/222b/bar' + * + */ +static int +match_path_exclusion(struct archive_match *a, struct match *m, + int mbs, const void *pn) +{ + int flag = PATHMATCH_NO_ANCHOR_START | PATHMATCH_NO_ANCHOR_END; + int r; + + if (mbs) { + const char *p; + r = archive_mstring_get_mbs(&(a->archive), &(m->pattern), &p); + if (r == 0) + return (archive_pathmatch(p, (const char *)pn, flag)); + } else { + const wchar_t *p; + r = archive_mstring_get_wcs(&(a->archive), &(m->pattern), &p); + if (r == 0) + return (archive_pathmatch_w(p, (const wchar_t *)pn, + flag)); + } + if (errno == ENOMEM) + return (error_nomem(a)); + return (0); +} + +/* + * Again, mimic gtar: inclusions are always anchored (have to match + * the beginning of the path) even though exclusions are not anchored. + */ +static int +match_path_inclusion(struct archive_match *a, struct match *m, + int mbs, const void *pn) +{ + /* Recursive operation requires only a prefix match. */ + int flag = a->recursive_include ? + PATHMATCH_NO_ANCHOR_END : + 0; + int r; + + if (mbs) { + const char *p; + r = archive_mstring_get_mbs(&(a->archive), &(m->pattern), &p); + if (r == 0) + return (archive_pathmatch(p, (const char *)pn, flag)); + } else { + const wchar_t *p; + r = archive_mstring_get_wcs(&(a->archive), &(m->pattern), &p); + if (r == 0) + return (archive_pathmatch_w(p, (const wchar_t *)pn, + flag)); + } + if (errno == ENOMEM) + return (error_nomem(a)); + return (0); +} + +static void +match_list_init(struct match_list *list) +{ + list->first = NULL; + list->last = &(list->first); + list->count = 0; +} + +static void +match_list_free(struct match_list *list) +{ + struct match *p, *q; + + for (p = list->first; p != NULL; ) { + q = p; + p = p->next; + archive_mstring_clean(&(q->pattern)); + free(q); + } +} + +static void +match_list_add(struct match_list *list, struct match *m) +{ + *list->last = m; + list->last = &(m->next); + list->count++; + list->unmatched_count++; +} + +static int +match_list_unmatched_inclusions_next(struct archive_match *a, + struct match_list *list, int mbs, const void **vp) +{ + struct match *m; + + *vp = NULL; + if (list->unmatched_eof) { + list->unmatched_eof = 0; + return (ARCHIVE_EOF); + } + if (list->unmatched_next == NULL) { + if (list->unmatched_count == 0) + return (ARCHIVE_EOF); + list->unmatched_next = list->first; + } + + for (m = list->unmatched_next; m != NULL; m = m->next) { + int r; + + if (m->matches) + continue; + if (mbs) { + const char *p; + r = archive_mstring_get_mbs(&(a->archive), + &(m->pattern), &p); + if (r < 0 && errno == ENOMEM) + return (error_nomem(a)); + if (p == NULL) + p = ""; + *vp = p; + } else { + const wchar_t *p; + r = archive_mstring_get_wcs(&(a->archive), + &(m->pattern), &p); + if (r < 0 && errno == ENOMEM) + return (error_nomem(a)); + if (p == NULL) + p = L""; + *vp = p; + } + list->unmatched_next = m->next; + if (list->unmatched_next == NULL) + /* To return EOF next time. */ + list->unmatched_eof = 1; + return (ARCHIVE_OK); + } + list->unmatched_next = NULL; + return (ARCHIVE_EOF); +} + +/* + * Utility functions to manage inclusion timestamps. + */ +int +archive_match_include_time(struct archive *_a, int flag, time_t sec, + long nsec) +{ + int r; + + r = validate_time_flag(_a, flag, "archive_match_include_time"); + if (r != ARCHIVE_OK) + return (r); + return set_timefilter((struct archive_match *)_a, flag, + sec, nsec, sec, nsec); +} + +int +archive_match_include_date(struct archive *_a, int flag, + const char *datestr) +{ + int r; + + r = validate_time_flag(_a, flag, "archive_match_include_date"); + if (r != ARCHIVE_OK) + return (r); + return set_timefilter_date((struct archive_match *)_a, flag, datestr); +} + +int +archive_match_include_date_w(struct archive *_a, int flag, + const wchar_t *datestr) +{ + int r; + + r = validate_time_flag(_a, flag, "archive_match_include_date_w"); + if (r != ARCHIVE_OK) + return (r); + + return set_timefilter_date_w((struct archive_match *)_a, flag, datestr); +} + +int +archive_match_include_file_time(struct archive *_a, int flag, + const char *pathname) +{ + int r; + + r = validate_time_flag(_a, flag, "archive_match_include_file_time"); + if (r != ARCHIVE_OK) + return (r); + return set_timefilter_pathname_mbs((struct archive_match *)_a, + flag, pathname); +} + +int +archive_match_include_file_time_w(struct archive *_a, int flag, + const wchar_t *pathname) +{ + int r; + + r = validate_time_flag(_a, flag, "archive_match_include_file_time_w"); + if (r != ARCHIVE_OK) + return (r); + return set_timefilter_pathname_wcs((struct archive_match *)_a, + flag, pathname); +} + +int +archive_match_exclude_entry(struct archive *_a, int flag, + struct archive_entry *entry) +{ + struct archive_match *a; + int r; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_time_include_entry"); + a = (struct archive_match *)_a; + + if (entry == NULL) { + archive_set_error(&(a->archive), EINVAL, "entry is NULL"); + return (ARCHIVE_FAILED); + } + r = validate_time_flag(_a, flag, "archive_match_exclude_entry"); + if (r != ARCHIVE_OK) + return (r); + return (add_entry(a, flag, entry)); +} + +/* + * Test function for time stamps. + * + * Returns 1 if archive entry is excluded. + * Returns 0 if archive entry is not excluded. + * Returns <0 if something error happened. + */ +int +archive_match_time_excluded(struct archive *_a, + struct archive_entry *entry) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_time_excluded_ae"); + + a = (struct archive_match *)_a; + if (entry == NULL) { + archive_set_error(&(a->archive), EINVAL, "entry is NULL"); + return (ARCHIVE_FAILED); + } + + /* If we don't have inclusion time set at all, the entry is always + * not excluded. */ + if ((a->setflag & TIME_IS_SET) == 0) + return (0); + return (time_excluded(a, entry)); +} + +static int +validate_time_flag(struct archive *_a, int flag, const char *_fn) +{ + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, _fn); + + /* Check a type of time. */ + if (flag & + ((~(ARCHIVE_MATCH_MTIME | ARCHIVE_MATCH_CTIME)) & 0xff00)) { + archive_set_error(_a, EINVAL, "Invalid time flag"); + return (ARCHIVE_FAILED); + } + if ((flag & (ARCHIVE_MATCH_MTIME | ARCHIVE_MATCH_CTIME)) == 0) { + archive_set_error(_a, EINVAL, "No time flag"); + return (ARCHIVE_FAILED); + } + + /* Check a type of comparison. */ + if (flag & + ((~(ARCHIVE_MATCH_NEWER | ARCHIVE_MATCH_OLDER + | ARCHIVE_MATCH_EQUAL)) & 0x00ff)) { + archive_set_error(_a, EINVAL, "Invalid comparison flag"); + return (ARCHIVE_FAILED); + } + if ((flag & (ARCHIVE_MATCH_NEWER | ARCHIVE_MATCH_OLDER + | ARCHIVE_MATCH_EQUAL)) == 0) { + archive_set_error(_a, EINVAL, "No comparison flag"); + return (ARCHIVE_FAILED); + } + + return (ARCHIVE_OK); +} + +#define JUST_EQUAL(t) (((t) & (ARCHIVE_MATCH_EQUAL |\ + ARCHIVE_MATCH_NEWER | ARCHIVE_MATCH_OLDER)) == ARCHIVE_MATCH_EQUAL) +static int +set_timefilter(struct archive_match *a, int timetype, + time_t mtime_sec, long mtime_nsec, time_t ctime_sec, long ctime_nsec) +{ + if (timetype & ARCHIVE_MATCH_MTIME) { + if ((timetype & ARCHIVE_MATCH_NEWER) || JUST_EQUAL(timetype)) { + a->newer_mtime_filter = timetype; + a->newer_mtime_sec = mtime_sec; + a->newer_mtime_nsec = mtime_nsec; + a->setflag |= TIME_IS_SET; + } + if ((timetype & ARCHIVE_MATCH_OLDER) || JUST_EQUAL(timetype)) { + a->older_mtime_filter = timetype; + a->older_mtime_sec = mtime_sec; + a->older_mtime_nsec = mtime_nsec; + a->setflag |= TIME_IS_SET; + } + } + if (timetype & ARCHIVE_MATCH_CTIME) { + if ((timetype & ARCHIVE_MATCH_NEWER) || JUST_EQUAL(timetype)) { + a->newer_ctime_filter = timetype; + a->newer_ctime_sec = ctime_sec; + a->newer_ctime_nsec = ctime_nsec; + a->setflag |= TIME_IS_SET; + } + if ((timetype & ARCHIVE_MATCH_OLDER) || JUST_EQUAL(timetype)) { + a->older_ctime_filter = timetype; + a->older_ctime_sec = ctime_sec; + a->older_ctime_nsec = ctime_nsec; + a->setflag |= TIME_IS_SET; + } + } + return (ARCHIVE_OK); +} + +static int +set_timefilter_date(struct archive_match *a, int timetype, const char *datestr) +{ + time_t t; + + if (datestr == NULL || *datestr == '\0') { + archive_set_error(&(a->archive), EINVAL, "date is empty"); + return (ARCHIVE_FAILED); + } + t = get_date(a->now, datestr); + if (t == (time_t)-1) { + archive_set_error(&(a->archive), EINVAL, "invalid date string"); + return (ARCHIVE_FAILED); + } + return set_timefilter(a, timetype, t, 0, t, 0); +} + +static int +set_timefilter_date_w(struct archive_match *a, int timetype, + const wchar_t *datestr) +{ + struct archive_string as; + time_t t; + + if (datestr == NULL || *datestr == L'\0') { + archive_set_error(&(a->archive), EINVAL, "date is empty"); + return (ARCHIVE_FAILED); + } + + archive_string_init(&as); + if (archive_string_append_from_wcs(&as, datestr, wcslen(datestr)) < 0) { + archive_string_free(&as); + if (errno == ENOMEM) + return (error_nomem(a)); + archive_set_error(&(a->archive), -1, + "Failed to convert WCS to MBS"); + return (ARCHIVE_FAILED); + } + t = get_date(a->now, as.s); + archive_string_free(&as); + if (t == (time_t)-1) { + archive_set_error(&(a->archive), EINVAL, "invalid date string"); + return (ARCHIVE_FAILED); + } + return set_timefilter(a, timetype, t, 0, t, 0); +} + +#if defined(_WIN32) && !defined(__CYGWIN__) +#define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000) +static int +set_timefilter_find_data(struct archive_match *a, int timetype, + DWORD ftLastWriteTime_dwHighDateTime, DWORD ftLastWriteTime_dwLowDateTime, + DWORD ftCreationTime_dwHighDateTime, DWORD ftCreationTime_dwLowDateTime) +{ + ULARGE_INTEGER utc; + time_t ctime_sec, mtime_sec; + long ctime_ns, mtime_ns; + + utc.HighPart = ftCreationTime_dwHighDateTime; + utc.LowPart = ftCreationTime_dwLowDateTime; + if (utc.QuadPart >= EPOC_TIME) { + utc.QuadPart -= EPOC_TIME; + ctime_sec = (time_t)(utc.QuadPart / 10000000); + ctime_ns = (long)(utc.QuadPart % 10000000) * 100; + } else { + ctime_sec = 0; + ctime_ns = 0; + } + utc.HighPart = ftLastWriteTime_dwHighDateTime; + utc.LowPart = ftLastWriteTime_dwLowDateTime; + if (utc.QuadPart >= EPOC_TIME) { + utc.QuadPart -= EPOC_TIME; + mtime_sec = (time_t)(utc.QuadPart / 10000000); + mtime_ns = (long)(utc.QuadPart % 10000000) * 100; + } else { + mtime_sec = 0; + mtime_ns = 0; + } + return set_timefilter(a, timetype, + mtime_sec, mtime_ns, ctime_sec, ctime_ns); +} + +static int +set_timefilter_pathname_mbs(struct archive_match *a, int timetype, + const char *path) +{ + /* NOTE: stat() on Windows cannot handle nano seconds. */ + HANDLE h; + WIN32_FIND_DATAA d; + + if (path == NULL || *path == '\0') { + archive_set_error(&(a->archive), EINVAL, "pathname is empty"); + return (ARCHIVE_FAILED); + } + h = FindFirstFileA(path, &d); + if (h == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + archive_set_error(&(a->archive), errno, + "Failed to FindFirstFileA"); + return (ARCHIVE_FAILED); + } + FindClose(h); + return set_timefilter_find_data(a, timetype, + d.ftLastWriteTime.dwHighDateTime, d.ftLastWriteTime.dwLowDateTime, + d.ftCreationTime.dwHighDateTime, d.ftCreationTime.dwLowDateTime); +} + +static int +set_timefilter_pathname_wcs(struct archive_match *a, int timetype, + const wchar_t *path) +{ + HANDLE h; + WIN32_FIND_DATAW d; + + if (path == NULL || *path == L'\0') { + archive_set_error(&(a->archive), EINVAL, "pathname is empty"); + return (ARCHIVE_FAILED); + } + h = FindFirstFileW(path, &d); + if (h == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + archive_set_error(&(a->archive), errno, + "Failed to FindFirstFile"); + return (ARCHIVE_FAILED); + } + FindClose(h); + return set_timefilter_find_data(a, timetype, + d.ftLastWriteTime.dwHighDateTime, d.ftLastWriteTime.dwLowDateTime, + d.ftCreationTime.dwHighDateTime, d.ftCreationTime.dwLowDateTime); +} + +#else /* _WIN32 && !__CYGWIN__ */ + +static int +set_timefilter_stat(struct archive_match *a, int timetype, struct stat *st) +{ + struct archive_entry *ae; + time_t ctime_sec, mtime_sec; + long ctime_ns, mtime_ns; + + ae = archive_entry_new(); + if (ae == NULL) + return (error_nomem(a)); + archive_entry_copy_stat(ae, st); + ctime_sec = archive_entry_ctime(ae); + ctime_ns = archive_entry_ctime_nsec(ae); + mtime_sec = archive_entry_mtime(ae); + mtime_ns = archive_entry_mtime_nsec(ae); + archive_entry_free(ae); + return set_timefilter(a, timetype, mtime_sec, mtime_ns, + ctime_sec, ctime_ns); +} + +static int +set_timefilter_pathname_mbs(struct archive_match *a, int timetype, + const char *path) +{ + struct stat st; + + if (path == NULL || *path == '\0') { + archive_set_error(&(a->archive), EINVAL, "pathname is empty"); + return (ARCHIVE_FAILED); + } + if (la_stat(path, &st) != 0) { + archive_set_error(&(a->archive), errno, "Failed to stat()"); + return (ARCHIVE_FAILED); + } + return (set_timefilter_stat(a, timetype, &st)); +} + +static int +set_timefilter_pathname_wcs(struct archive_match *a, int timetype, + const wchar_t *path) +{ + struct archive_string as; + int r; + + if (path == NULL || *path == L'\0') { + archive_set_error(&(a->archive), EINVAL, "pathname is empty"); + return (ARCHIVE_FAILED); + } + + /* Convert WCS filename to MBS filename. */ + archive_string_init(&as); + if (archive_string_append_from_wcs(&as, path, wcslen(path)) < 0) { + archive_string_free(&as); + if (errno == ENOMEM) + return (error_nomem(a)); + archive_set_error(&(a->archive), -1, + "Failed to convert WCS to MBS"); + return (ARCHIVE_FAILED); + } + + r = set_timefilter_pathname_mbs(a, timetype, as.s); + archive_string_free(&as); + + return (r); +} +#endif /* _WIN32 && !__CYGWIN__ */ + +/* + * Call back functions for archive_rb. + */ +static int +cmp_node_mbs(const struct archive_rb_node *n1, + const struct archive_rb_node *n2) +{ + struct match_file *f1 = (struct match_file *)(uintptr_t)n1; + struct match_file *f2 = (struct match_file *)(uintptr_t)n2; + const char *p1, *p2; + + archive_mstring_get_mbs(NULL, &(f1->pathname), &p1); + archive_mstring_get_mbs(NULL, &(f2->pathname), &p2); + if (p1 == NULL) + return (1); + if (p2 == NULL) + return (-1); + return (strcmp(p1, p2)); +} + +static int +cmp_key_mbs(const struct archive_rb_node *n, const void *key) +{ + struct match_file *f = (struct match_file *)(uintptr_t)n; + const char *p; + + archive_mstring_get_mbs(NULL, &(f->pathname), &p); + if (p == NULL) + return (-1); + return (strcmp(p, (const char *)key)); +} + +static int +cmp_node_wcs(const struct archive_rb_node *n1, + const struct archive_rb_node *n2) +{ + struct match_file *f1 = (struct match_file *)(uintptr_t)n1; + struct match_file *f2 = (struct match_file *)(uintptr_t)n2; + const wchar_t *p1, *p2; + + archive_mstring_get_wcs(NULL, &(f1->pathname), &p1); + archive_mstring_get_wcs(NULL, &(f2->pathname), &p2); + if (p1 == NULL) + return (1); + if (p2 == NULL) + return (-1); + return (wcscmp(p1, p2)); +} + +static int +cmp_key_wcs(const struct archive_rb_node *n, const void *key) +{ + struct match_file *f = (struct match_file *)(uintptr_t)n; + const wchar_t *p; + + archive_mstring_get_wcs(NULL, &(f->pathname), &p); + if (p == NULL) + return (-1); + return (wcscmp(p, (const wchar_t *)key)); +} + +static void +entry_list_init(struct entry_list *list) +{ + list->first = NULL; + list->last = &(list->first); + list->count = 0; +} + +static void +entry_list_free(struct entry_list *list) +{ + struct match_file *p, *q; + + for (p = list->first; p != NULL; ) { + q = p; + p = p->next; + archive_mstring_clean(&(q->pathname)); + free(q); + } +} + +static void +entry_list_add(struct entry_list *list, struct match_file *file) +{ + *list->last = file; + list->last = &(file->next); + list->count++; +} + +static int +add_entry(struct archive_match *a, int flag, + struct archive_entry *entry) +{ + struct match_file *f; + const void *pathname; + int r; + + f = calloc(1, sizeof(*f)); + if (f == NULL) + return (error_nomem(a)); + +#if defined(_WIN32) && !defined(__CYGWIN__) + pathname = archive_entry_pathname_w(entry); + if (pathname == NULL) { + free(f); + archive_set_error(&(a->archive), EINVAL, "pathname is NULL"); + return (ARCHIVE_FAILED); + } + archive_mstring_copy_wcs(&(f->pathname), pathname); + a->exclusion_tree.rbt_ops = &rb_ops_wcs; +#else + (void)rb_ops_wcs; + pathname = archive_entry_pathname(entry); + if (pathname == NULL) { + free(f); + archive_set_error(&(a->archive), EINVAL, "pathname is NULL"); + return (ARCHIVE_FAILED); + } + archive_mstring_copy_mbs(&(f->pathname), pathname); + a->exclusion_tree.rbt_ops = &rb_ops_mbs; +#endif + f->flag = flag; + f->mtime_sec = archive_entry_mtime(entry); + f->mtime_nsec = archive_entry_mtime_nsec(entry); + f->ctime_sec = archive_entry_ctime(entry); + f->ctime_nsec = archive_entry_ctime_nsec(entry); + r = __archive_rb_tree_insert_node(&(a->exclusion_tree), &(f->node)); + if (!r) { + struct match_file *f2; + + /* Get the duplicated file. */ + f2 = (struct match_file *)__archive_rb_tree_find_node( + &(a->exclusion_tree), pathname); + + /* + * We always overwrite comparison condition. + * If you do not want to overwrite it, you should not + * call archive_match_exclude_entry(). We cannot know + * what behavior you really expect since overwriting + * condition might be different with the flag. + */ + if (f2 != NULL) { + f2->flag = f->flag; + f2->mtime_sec = f->mtime_sec; + f2->mtime_nsec = f->mtime_nsec; + f2->ctime_sec = f->ctime_sec; + f2->ctime_nsec = f->ctime_nsec; + } + /* Release the duplicated file. */ + archive_mstring_clean(&(f->pathname)); + free(f); + return (ARCHIVE_OK); + } + entry_list_add(&(a->exclusion_entry_list), f); + a->setflag |= TIME_IS_SET; + return (ARCHIVE_OK); +} + +/* + * Test if entry is excluded by its timestamp. + */ +static int +time_excluded(struct archive_match *a, struct archive_entry *entry) +{ + struct match_file *f; + const void *pathname; + time_t sec; + long nsec; + + /* + * If this file/dir is excluded by a time comparison, skip it. + */ + if (a->newer_ctime_filter) { + /* If ctime is not set, use mtime instead. */ + if (archive_entry_ctime_is_set(entry)) + sec = archive_entry_ctime(entry); + else + sec = archive_entry_mtime(entry); + if (sec < a->newer_ctime_sec) + return (1); /* Too old, skip it. */ + if (sec == a->newer_ctime_sec) { + if (archive_entry_ctime_is_set(entry)) + nsec = archive_entry_ctime_nsec(entry); + else + nsec = archive_entry_mtime_nsec(entry); + if (nsec < a->newer_ctime_nsec) + return (1); /* Too old, skip it. */ + if (nsec == a->newer_ctime_nsec && + (a->newer_ctime_filter & ARCHIVE_MATCH_EQUAL) + == 0) + return (1); /* Equal, skip it. */ + } + } + if (a->older_ctime_filter) { + /* If ctime is not set, use mtime instead. */ + if (archive_entry_ctime_is_set(entry)) + sec = archive_entry_ctime(entry); + else + sec = archive_entry_mtime(entry); + if (sec > a->older_ctime_sec) + return (1); /* Too new, skip it. */ + if (sec == a->older_ctime_sec) { + if (archive_entry_ctime_is_set(entry)) + nsec = archive_entry_ctime_nsec(entry); + else + nsec = archive_entry_mtime_nsec(entry); + if (nsec > a->older_ctime_nsec) + return (1); /* Too new, skip it. */ + if (nsec == a->older_ctime_nsec && + (a->older_ctime_filter & ARCHIVE_MATCH_EQUAL) + == 0) + return (1); /* Equal, skip it. */ + } + } + if (a->newer_mtime_filter) { + sec = archive_entry_mtime(entry); + if (sec < a->newer_mtime_sec) + return (1); /* Too old, skip it. */ + if (sec == a->newer_mtime_sec) { + nsec = archive_entry_mtime_nsec(entry); + if (nsec < a->newer_mtime_nsec) + return (1); /* Too old, skip it. */ + if (nsec == a->newer_mtime_nsec && + (a->newer_mtime_filter & ARCHIVE_MATCH_EQUAL) + == 0) + return (1); /* Equal, skip it. */ + } + } + if (a->older_mtime_filter) { + sec = archive_entry_mtime(entry); + if (sec > a->older_mtime_sec) + return (1); /* Too new, skip it. */ + nsec = archive_entry_mtime_nsec(entry); + if (sec == a->older_mtime_sec) { + if (nsec > a->older_mtime_nsec) + return (1); /* Too new, skip it. */ + if (nsec == a->older_mtime_nsec && + (a->older_mtime_filter & ARCHIVE_MATCH_EQUAL) + == 0) + return (1); /* Equal, skip it. */ + } + } + + /* If there is no exclusion list, include the file. */ + if (a->exclusion_entry_list.count == 0) + return (0); + +#if defined(_WIN32) && !defined(__CYGWIN__) + pathname = archive_entry_pathname_w(entry); + a->exclusion_tree.rbt_ops = &rb_ops_wcs; +#else + (void)rb_ops_wcs; + pathname = archive_entry_pathname(entry); + a->exclusion_tree.rbt_ops = &rb_ops_mbs; +#endif + if (pathname == NULL) + return (0); + + f = (struct match_file *)__archive_rb_tree_find_node( + &(a->exclusion_tree), pathname); + /* If the file wasn't rejected, include it. */ + if (f == NULL) + return (0); + + if (f->flag & ARCHIVE_MATCH_CTIME) { + sec = archive_entry_ctime(entry); + if (f->ctime_sec > sec) { + if (f->flag & ARCHIVE_MATCH_OLDER) + return (1); + } else if (f->ctime_sec < sec) { + if (f->flag & ARCHIVE_MATCH_NEWER) + return (1); + } else { + nsec = archive_entry_ctime_nsec(entry); + if (f->ctime_nsec > nsec) { + if (f->flag & ARCHIVE_MATCH_OLDER) + return (1); + } else if (f->ctime_nsec < nsec) { + if (f->flag & ARCHIVE_MATCH_NEWER) + return (1); + } else if (f->flag & ARCHIVE_MATCH_EQUAL) + return (1); + } + } + if (f->flag & ARCHIVE_MATCH_MTIME) { + sec = archive_entry_mtime(entry); + if (f->mtime_sec > sec) { + if (f->flag & ARCHIVE_MATCH_OLDER) + return (1); + } else if (f->mtime_sec < sec) { + if (f->flag & ARCHIVE_MATCH_NEWER) + return (1); + } else { + nsec = archive_entry_mtime_nsec(entry); + if (f->mtime_nsec > nsec) { + if (f->flag & ARCHIVE_MATCH_OLDER) + return (1); + } else if (f->mtime_nsec < nsec) { + if (f->flag & ARCHIVE_MATCH_NEWER) + return (1); + } else if (f->flag & ARCHIVE_MATCH_EQUAL) + return (1); + } + } + return (0); +} + +/* + * Utility functions to manage inclusion owners + */ + +int +archive_match_include_uid(struct archive *_a, la_int64_t uid) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_include_uid"); + a = (struct archive_match *)_a; + return (add_owner_id(a, &(a->inclusion_uids), uid)); +} + +int +archive_match_include_gid(struct archive *_a, la_int64_t gid) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_include_gid"); + a = (struct archive_match *)_a; + return (add_owner_id(a, &(a->inclusion_gids), gid)); +} + +int +archive_match_include_uname(struct archive *_a, const char *uname) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_include_uname"); + a = (struct archive_match *)_a; + return (add_owner_name(a, &(a->inclusion_unames), 1, uname)); +} + +int +archive_match_include_uname_w(struct archive *_a, const wchar_t *uname) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_include_uname_w"); + a = (struct archive_match *)_a; + return (add_owner_name(a, &(a->inclusion_unames), 0, uname)); +} + +int +archive_match_include_gname(struct archive *_a, const char *gname) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_include_gname"); + a = (struct archive_match *)_a; + return (add_owner_name(a, &(a->inclusion_gnames), 1, gname)); +} + +int +archive_match_include_gname_w(struct archive *_a, const wchar_t *gname) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_include_gname_w"); + a = (struct archive_match *)_a; + return (add_owner_name(a, &(a->inclusion_gnames), 0, gname)); +} + +/* + * Test function for owner(uid, gid, uname, gname). + * + * Returns 1 if archive entry is excluded. + * Returns 0 if archive entry is not excluded. + * Returns <0 if something error happened. + */ +int +archive_match_owner_excluded(struct archive *_a, + struct archive_entry *entry) +{ + struct archive_match *a; + + archive_check_magic(_a, ARCHIVE_MATCH_MAGIC, + ARCHIVE_STATE_NEW, "archive_match_id_excluded_ae"); + + a = (struct archive_match *)_a; + if (entry == NULL) { + archive_set_error(&(a->archive), EINVAL, "entry is NULL"); + return (ARCHIVE_FAILED); + } + + /* If we don't have inclusion id set at all, the entry is always + * not excluded. */ + if ((a->setflag & ID_IS_SET) == 0) + return (0); + return (owner_excluded(a, entry)); +} + +static int +add_owner_id(struct archive_match *a, struct id_array *ids, int64_t id) +{ + unsigned i; + + if (ids->count + 1 >= ids->size) { + void *p; + + if (ids->size == 0) + ids->size = 8; + else + ids->size *= 2; + p = realloc(ids->ids, sizeof(*ids->ids) * ids->size); + if (p == NULL) + return (error_nomem(a)); + ids->ids = (int64_t *)p; + } + + /* Find an insert point. */ + for (i = 0; i < ids->count; i++) { + if (ids->ids[i] >= id) + break; + } + + /* Add owner id. */ + if (i == ids->count) + ids->ids[ids->count++] = id; + else if (ids->ids[i] != id) { + memmove(&(ids->ids[i+1]), &(ids->ids[i]), + (ids->count - i) * sizeof(ids->ids[0])); + ids->ids[i] = id; + ids->count++; + } + a->setflag |= ID_IS_SET; + return (ARCHIVE_OK); +} + +static int +match_owner_id(struct id_array *ids, int64_t id) +{ + unsigned b, m, t; + + t = 0; + b = (unsigned)ids->count; + while (t < b) { + m = (t + b)>>1; + if (ids->ids[m] == id) + return (1); + if (ids->ids[m] < id) + t = m + 1; + else + b = m; + } + return (0); +} + +static int +add_owner_name(struct archive_match *a, struct match_list *list, + int mbs, const void *name) +{ + struct match *match; + + match = calloc(1, sizeof(*match)); + if (match == NULL) + return (error_nomem(a)); + if (mbs) + archive_mstring_copy_mbs(&(match->pattern), name); + else + archive_mstring_copy_wcs(&(match->pattern), name); + match_list_add(list, match); + a->setflag |= ID_IS_SET; + return (ARCHIVE_OK); +} + +#if !defined(_WIN32) || defined(__CYGWIN__) +static int +match_owner_name_mbs(struct archive_match *a, struct match_list *list, + const char *name) +{ + struct match *m; + const char *p; + + if (name == NULL || *name == '\0') + return (0); + for (m = list->first; m; m = m->next) { + if (archive_mstring_get_mbs(&(a->archive), &(m->pattern), &p) + < 0 && errno == ENOMEM) + return (error_nomem(a)); + if (p != NULL && strcmp(p, name) == 0) { + m->matches++; + return (1); + } + } + return (0); +} +#else +static int +match_owner_name_wcs(struct archive_match *a, struct match_list *list, + const wchar_t *name) +{ + struct match *m; + const wchar_t *p; + + if (name == NULL || *name == L'\0') + return (0); + for (m = list->first; m; m = m->next) { + if (archive_mstring_get_wcs(&(a->archive), &(m->pattern), &p) + < 0 && errno == ENOMEM) + return (error_nomem(a)); + if (p != NULL && wcscmp(p, name) == 0) { + m->matches++; + return (1); + } + } + return (0); +} +#endif + +/* + * Test if entry is excluded by uid, gid, uname or gname. + */ +static int +owner_excluded(struct archive_match *a, struct archive_entry *entry) +{ + int r; + + if (a->inclusion_uids.count) { + if (!match_owner_id(&(a->inclusion_uids), + archive_entry_uid(entry))) + return (1); + } + + if (a->inclusion_gids.count) { + if (!match_owner_id(&(a->inclusion_gids), + archive_entry_gid(entry))) + return (1); + } + + if (a->inclusion_unames.count) { +#if defined(_WIN32) && !defined(__CYGWIN__) + r = match_owner_name_wcs(a, &(a->inclusion_unames), + archive_entry_uname_w(entry)); +#else + r = match_owner_name_mbs(a, &(a->inclusion_unames), + archive_entry_uname(entry)); +#endif + if (!r) + return (1); + else if (r < 0) + return (r); + } + + if (a->inclusion_gnames.count) { +#if defined(_WIN32) && !defined(__CYGWIN__) + r = match_owner_name_wcs(a, &(a->inclusion_gnames), + archive_entry_gname_w(entry)); +#else + r = match_owner_name_mbs(a, &(a->inclusion_gnames), + archive_entry_gname(entry)); +#endif + if (!r) + return (1); + else if (r < 0) + return (r); + } + return (0); +} + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_openssl_evp_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_openssl_evp_private.h new file mode 100644 index 0000000000..ebb06702d0 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_openssl_evp_private.h @@ -0,0 +1,53 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#ifndef ARCHIVE_OPENSSL_EVP_PRIVATE_H_INCLUDED +#define ARCHIVE_OPENSSL_EVP_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +#include <openssl/evp.h> +#include <openssl/opensslv.h> + +#if OPENSSL_VERSION_NUMBER < 0x10100000L +#include <stdlib.h> /* malloc, free */ +#include <string.h> /* memset */ +static inline EVP_MD_CTX *EVP_MD_CTX_new(void) +{ + EVP_MD_CTX *ctx = (EVP_MD_CTX *)calloc(1, sizeof(EVP_MD_CTX)); + return ctx; +} + +static inline void EVP_MD_CTX_free(EVP_MD_CTX *ctx) +{ + EVP_MD_CTX_cleanup(ctx); + memset(ctx, 0, sizeof(*ctx)); + free(ctx); +} +#endif + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_openssl_hmac_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_openssl_hmac_private.h new file mode 100644 index 0000000000..25c8dda654 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_openssl_hmac_private.h @@ -0,0 +1,54 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#ifndef ARCHIVE_OPENSSL_HMAC_PRIVATE_H_INCLUDED +#define ARCHIVE_OPENSSL_HMAC_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +#include <openssl/hmac.h> +#include <openssl/opensslv.h> + +#if OPENSSL_VERSION_NUMBER < 0x10100000L || \ + (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L) +#include <stdlib.h> /* malloc, free */ +#include <string.h> /* memset */ +static inline HMAC_CTX *HMAC_CTX_new(void) +{ + HMAC_CTX *ctx = (HMAC_CTX *)calloc(1, sizeof(HMAC_CTX)); + return ctx; +} + +static inline void HMAC_CTX_free(HMAC_CTX *ctx) +{ + HMAC_CTX_cleanup(ctx); + memset(ctx, 0, sizeof(*ctx)); + free(ctx); +} +#endif + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_options.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_options.c new file mode 100644 index 0000000000..6496025a5f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_options.c @@ -0,0 +1,218 @@ +/*- + * Copyright (c) 2011 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif + +#include "archive_options_private.h" + +static const char * +parse_option(const char **str, + const char **mod, const char **opt, const char **val); + +int +_archive_set_option(struct archive *a, + const char *m, const char *o, const char *v, + int magic, const char *fn, option_handler use_option) +{ + const char *mp, *op, *vp; + int r; + + archive_check_magic(a, magic, ARCHIVE_STATE_NEW, fn); + + mp = (m != NULL && m[0] != '\0') ? m : NULL; + op = (o != NULL && o[0] != '\0') ? o : NULL; + vp = (v != NULL && v[0] != '\0') ? v : NULL; + + if (op == NULL && vp == NULL) + return (ARCHIVE_OK); + if (op == NULL) { + archive_set_error(a, ARCHIVE_ERRNO_MISC, "Empty option"); + return (ARCHIVE_FAILED); + } + + r = use_option(a, mp, op, vp); + if (r == ARCHIVE_WARN - 1) { + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Unknown module name: `%s'", mp); + return (ARCHIVE_FAILED); + } + if (r == ARCHIVE_WARN) { + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Undefined option: `%s%s%s%s%s%s'", + vp?"":"!", mp?mp:"", mp?":":"", op, vp?"=":"", vp?vp:""); + return (ARCHIVE_FAILED); + } + return (r); +} + +int +_archive_set_either_option(struct archive *a, const char *m, const char *o, const char *v, + option_handler use_format_option, option_handler use_filter_option) +{ + int r1, r2; + + if (o == NULL && v == NULL) + return (ARCHIVE_OK); + if (o == NULL) + return (ARCHIVE_FAILED); + + r1 = use_format_option(a, m, o, v); + if (r1 == ARCHIVE_FATAL) + return (ARCHIVE_FATAL); + + r2 = use_filter_option(a, m, o, v); + if (r2 == ARCHIVE_FATAL) + return (ARCHIVE_FATAL); + + if (r2 == ARCHIVE_WARN - 1) + return r1; + return r1 > r2 ? r1 : r2; +} + +int +_archive_set_options(struct archive *a, const char *options, + int magic, const char *fn, option_handler use_option) +{ + int allok = 1, anyok = 0, ignore_mod_err = 0, r; + char *data; + const char *s, *mod, *opt, *val; + + archive_check_magic(a, magic, ARCHIVE_STATE_NEW, fn); + + if (options == NULL || options[0] == '\0') + return ARCHIVE_OK; + + if ((data = strdup(options)) == NULL) { + archive_set_error(a, + ENOMEM, "Out of memory adding file to list"); + return (ARCHIVE_FATAL); + } + s = (const char *)data; + + do { + mod = opt = val = NULL; + + parse_option(&s, &mod, &opt, &val); + if (mod == NULL && opt != NULL && + strcmp("__ignore_wrong_module_name__", opt) == 0) { + /* Ignore module name error */ + if (val != NULL) { + ignore_mod_err = 1; + anyok = 1; + } + continue; + } + + r = use_option(a, mod, opt, val); + if (r == ARCHIVE_FATAL) { + free(data); + return (ARCHIVE_FATAL); + } + if (r == ARCHIVE_FAILED && mod != NULL) { + free(data); + return (ARCHIVE_FAILED); + } + if (r == ARCHIVE_WARN - 1) { + if (ignore_mod_err) + continue; + /* The module name is wrong. */ + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Unknown module name: `%s'", mod); + free(data); + return (ARCHIVE_FAILED); + } + if (r == ARCHIVE_WARN) { + /* The option name is wrong. No-one used this. */ + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Undefined option: `%s%s%s'", + mod?mod:"", mod?":":"", opt); + free(data); + return (ARCHIVE_FAILED); + } + if (r == ARCHIVE_OK) + anyok = 1; + else + allok = 0; + } while (s != NULL); + + free(data); + return allok ? ARCHIVE_OK : anyok ? ARCHIVE_WARN : ARCHIVE_FAILED; +} + +static const char * +parse_option(const char **s, const char **m, const char **o, const char **v) +{ + const char *end, *mod, *opt, *val; + char *p; + + end = NULL; + mod = NULL; + opt = *s; + val = "1"; + + p = strchr(opt, ','); + + if (p != NULL) { + *p = '\0'; + end = ((const char *)p) + 1; + } + + if (0 == strlen(opt)) { + *s = end; + *m = NULL; + *o = NULL; + *v = NULL; + return end; + } + + p = strchr(opt, ':'); + if (p != NULL) { + *p = '\0'; + mod = opt; + opt = ++p; + } + + p = strchr(opt, '='); + if (p != NULL) { + *p = '\0'; + val = ++p; + } else if (opt[0] == '!') { + ++opt; + val = NULL; + } + + *s = end; + *m = mod; + *o = opt; + *v = val; + + return end; +} + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_options_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_options_private.h new file mode 100644 index 0000000000..9a7f8080d2 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_options_private.h @@ -0,0 +1,51 @@ +/*- + * Copyright (c) 2011 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#ifndef ARCHIVE_OPTIONS_PRIVATE_H_INCLUDED +#define ARCHIVE_OPTIONS_PRIVATE_H_INCLUDED + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#include "archive_private.h" + +typedef int (*option_handler)(struct archive *a, + const char *mod, const char *opt, const char *val); + +int +_archive_set_option(struct archive *a, + const char *mod, const char *opt, const char *val, + int magic, const char *fn, option_handler use_option); + +int +_archive_set_options(struct archive *a, const char *options, + int magic, const char *fn, option_handler use_option); + +int +_archive_set_either_option(struct archive *a, + const char *m, const char *o, const char *v, + option_handler use_format_option, option_handler use_filter_option); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_pack_dev.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_pack_dev.c new file mode 100644 index 0000000000..f8286d8218 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_pack_dev.c @@ -0,0 +1,336 @@ +/* $NetBSD: pack_dev.c,v 1.12 2013/06/14 16:28:20 tsutsui Exp $ */ + +/*- + * Copyright (c) 1998, 2001 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Charles M. Hannum. + * + * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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. + */ + +/* Originally from NetBSD's mknod(8) source. */ + +#include "archive_platform.h" + +#if HAVE_SYS_CDEFS_H +#include <sys/cdefs.h> +#endif +#if !defined(lint) +__RCSID("$NetBSD$"); +#endif /* not lint */ + +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif + +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#if MAJOR_IN_MKDEV +#include <sys/mkdev.h> +#define HAVE_MAJOR +#elif MAJOR_IN_SYSMACROS +#include <sys/sysmacros.h> +#define HAVE_MAJOR +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#include "archive_pack_dev.h" + +static pack_t pack_netbsd; +static pack_t pack_freebsd; +static pack_t pack_8_8; +static pack_t pack_12_20; +static pack_t pack_14_18; +static pack_t pack_8_24; +static pack_t pack_bsdos; +static int compare_format(const void *, const void *); + +static const char iMajorError[] = "invalid major number"; +static const char iMinorError[] = "invalid minor number"; +static const char tooManyFields[] = "too many fields for format"; + +/* This is blatantly stolen from libarchive/archive_entry.c, + * in an attempt to get this to play nice on MinGW... */ +#if !defined(HAVE_MAJOR) && !defined(major) +/* Replacement for major/minor/makedev. */ +#define major(x) ((int)(0x00ff & ((x) >> 8))) +#define minor(x) ((int)(0xffff00ff & (x))) +#define makedev(maj,min) ((0xff00 & ((maj)<<8)) | (0xffff00ff & (min))) +#endif + +/* Play games to come up with a suitable makedev() definition. */ +#ifdef __QNXNTO__ +/* QNX. <sigh> */ +#include <sys/netmgr.h> +#define apd_makedev(maj, min) makedev(ND_LOCAL_NODE, (maj), (min)) +#elif defined makedev +/* There's a "makedev" macro. */ +#define apd_makedev(maj, min) makedev((maj), (min)) +#elif defined mkdev || ((defined _WIN32 || defined __WIN32__) && !defined(__CYGWIN__)) +/* Windows. <sigh> */ +#define apd_makedev(maj, min) mkdev((maj), (min)) +#else +/* There's a "makedev" function. */ +#define apd_makedev(maj, min) makedev((maj), (min)) +#endif + +/* exported */ +dev_t +pack_native(int n, unsigned long numbers[], const char **error) +{ + dev_t dev = 0; + + if (n == 2) { + dev = apd_makedev(numbers[0], numbers[1]); + if ((unsigned long)major(dev) != numbers[0]) + *error = iMajorError; + else if ((unsigned long)minor(dev) != numbers[1]) + *error = iMinorError; + } else + *error = tooManyFields; + return (dev); +} + + +static dev_t +pack_netbsd(int n, unsigned long numbers[], const char **error) +{ + dev_t dev = 0; + + if (n == 2) { + dev = makedev_netbsd(numbers[0], numbers[1]); + if ((unsigned long)major_netbsd(dev) != numbers[0]) + *error = iMajorError; + else if ((unsigned long)minor_netbsd(dev) != numbers[1]) + *error = iMinorError; + } else + *error = tooManyFields; + return (dev); +} + + +#define major_freebsd(x) ((int32_t)(((x) & 0x0000ff00) >> 8)) +#define minor_freebsd(x) ((int32_t)(((x) & 0xffff00ff) >> 0)) +#define makedev_freebsd(x,y) ((dev_t)((((x) << 8) & 0x0000ff00) | \ + (((y) << 0) & 0xffff00ff))) + +static dev_t +pack_freebsd(int n, unsigned long numbers[], const char **error) +{ + dev_t dev = 0; + + if (n == 2) { + dev = makedev_freebsd(numbers[0], numbers[1]); + if ((unsigned long)major_freebsd(dev) != numbers[0]) + *error = iMajorError; + if ((unsigned long)minor_freebsd(dev) != numbers[1]) + *error = iMinorError; + } else + *error = tooManyFields; + return (dev); +} + + +#define major_8_8(x) ((int32_t)(((x) & 0x0000ff00) >> 8)) +#define minor_8_8(x) ((int32_t)(((x) & 0x000000ff) >> 0)) +#define makedev_8_8(x,y) ((dev_t)((((x) << 8) & 0x0000ff00) | \ + (((y) << 0) & 0x000000ff))) + +static dev_t +pack_8_8(int n, unsigned long numbers[], const char **error) +{ + dev_t dev = 0; + + if (n == 2) { + dev = makedev_8_8(numbers[0], numbers[1]); + if ((unsigned long)major_8_8(dev) != numbers[0]) + *error = iMajorError; + if ((unsigned long)minor_8_8(dev) != numbers[1]) + *error = iMinorError; + } else + *error = tooManyFields; + return (dev); +} + + +#define major_12_20(x) ((int32_t)(((x) & 0xfff00000) >> 20)) +#define minor_12_20(x) ((int32_t)(((x) & 0x000fffff) >> 0)) +#define makedev_12_20(x,y) ((dev_t)((((x) << 20) & 0xfff00000) | \ + (((y) << 0) & 0x000fffff))) + +static dev_t +pack_12_20(int n, unsigned long numbers[], const char **error) +{ + dev_t dev = 0; + + if (n == 2) { + dev = makedev_12_20(numbers[0], numbers[1]); + if ((unsigned long)major_12_20(dev) != numbers[0]) + *error = iMajorError; + if ((unsigned long)minor_12_20(dev) != numbers[1]) + *error = iMinorError; + } else + *error = tooManyFields; + return (dev); +} + + +#define major_14_18(x) ((int32_t)(((x) & 0xfffc0000) >> 18)) +#define minor_14_18(x) ((int32_t)(((x) & 0x0003ffff) >> 0)) +#define makedev_14_18(x,y) ((dev_t)((((x) << 18) & 0xfffc0000) | \ + (((y) << 0) & 0x0003ffff))) + +static dev_t +pack_14_18(int n, unsigned long numbers[], const char **error) +{ + dev_t dev = 0; + + if (n == 2) { + dev = makedev_14_18(numbers[0], numbers[1]); + if ((unsigned long)major_14_18(dev) != numbers[0]) + *error = iMajorError; + if ((unsigned long)minor_14_18(dev) != numbers[1]) + *error = iMinorError; + } else + *error = tooManyFields; + return (dev); +} + + +#define major_8_24(x) ((int32_t)(((x) & 0xff000000) >> 24)) +#define minor_8_24(x) ((int32_t)(((x) & 0x00ffffff) >> 0)) +#define makedev_8_24(x,y) ((dev_t)((((x) << 24) & 0xff000000) | \ + (((y) << 0) & 0x00ffffff))) + +static dev_t +pack_8_24(int n, unsigned long numbers[], const char **error) +{ + dev_t dev = 0; + + if (n == 2) { + dev = makedev_8_24(numbers[0], numbers[1]); + if ((unsigned long)major_8_24(dev) != numbers[0]) + *error = iMajorError; + if ((unsigned long)minor_8_24(dev) != numbers[1]) + *error = iMinorError; + } else + *error = tooManyFields; + return (dev); +} + + +#define major_12_12_8(x) ((int32_t)(((x) & 0xfff00000) >> 20)) +#define unit_12_12_8(x) ((int32_t)(((x) & 0x000fff00) >> 8)) +#define subunit_12_12_8(x) ((int32_t)(((x) & 0x000000ff) >> 0)) +#define makedev_12_12_8(x,y,z) ((dev_t)((((x) << 20) & 0xfff00000) | \ + (((y) << 8) & 0x000fff00) | \ + (((z) << 0) & 0x000000ff))) + +static dev_t +pack_bsdos(int n, unsigned long numbers[], const char **error) +{ + dev_t dev = 0; + + if (n == 2) { + dev = makedev_12_20(numbers[0], numbers[1]); + if ((unsigned long)major_12_20(dev) != numbers[0]) + *error = iMajorError; + if ((unsigned long)minor_12_20(dev) != numbers[1]) + *error = iMinorError; + } else if (n == 3) { + dev = makedev_12_12_8(numbers[0], numbers[1], numbers[2]); + if ((unsigned long)major_12_12_8(dev) != numbers[0]) + *error = iMajorError; + if ((unsigned long)unit_12_12_8(dev) != numbers[1]) + *error = "invalid unit number"; + if ((unsigned long)subunit_12_12_8(dev) != numbers[2]) + *error = "invalid subunit number"; + } else + *error = tooManyFields; + return (dev); +} + + + /* list of formats and pack functions */ + /* this list must be sorted lexically */ +static const struct format { + const char *name; + pack_t *pack; +} formats[] = { + {"386bsd", pack_8_8}, + {"4bsd", pack_8_8}, + {"bsdos", pack_bsdos}, + {"freebsd", pack_freebsd}, + {"hpux", pack_8_24}, + {"isc", pack_8_8}, + {"linux", pack_8_8}, + {"native", pack_native}, + {"netbsd", pack_netbsd}, + {"osf1", pack_12_20}, + {"sco", pack_8_8}, + {"solaris", pack_14_18}, + {"sunos", pack_8_8}, + {"svr3", pack_8_8}, + {"svr4", pack_14_18}, + {"ultrix", pack_8_8}, +}; + +static int +compare_format(const void *key, const void *element) +{ + const char *name; + const struct format *format; + + name = key; + format = element; + + return (strcmp(name, format->name)); +} + + +pack_t * +pack_find(const char *name) +{ + struct format *format; + + format = bsearch(name, formats, + sizeof(formats)/sizeof(formats[0]), + sizeof(formats[0]), compare_format); + if (format == 0) + return (NULL); + return (format->pack); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_pack_dev.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_pack_dev.h new file mode 100644 index 0000000000..eaf23e3883 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_pack_dev.h @@ -0,0 +1,49 @@ +/* $NetBSD: pack_dev.h,v 1.8 2013/06/14 16:28:20 tsutsui Exp $ */ + +/*- + * Copyright (c) 1998, 2001 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Charles M. Hannum. + * + * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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. + */ + +/* Originally from NetBSD's mknod(8) source. */ + +#ifndef ARCHIVE_PACK_DEV_H +#define ARCHIVE_PACK_DEV_H + +typedef dev_t pack_t(int, unsigned long [], const char **); + +pack_t *pack_find(const char *); +pack_t pack_native; + +#define major_netbsd(x) ((int32_t)((((x) & 0x000fff00) >> 8))) +#define minor_netbsd(x) ((int32_t)((((x) & 0xfff00000) >> 12) | \ + (((x) & 0x000000ff) >> 0))) +#define makedev_netbsd(x,y) ((dev_t)((((x) << 8) & 0x000fff00) | \ + (((y) << 12) & 0xfff00000) | \ + (((y) << 0) & 0x000000ff))) + +#endif /* ARCHIVE_PACK_DEV_H */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_pathmatch.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_pathmatch.c new file mode 100644 index 0000000000..619e2b622a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_pathmatch.c @@ -0,0 +1,459 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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 + * in this position and unchanged. + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_WCHAR_H +#include <wchar.h> +#endif + +#include "archive_pathmatch.h" + +/* + * Check whether a character 'c' is matched by a list specification [...]: + * * Leading '!' or '^' negates the class. + * * <char>-<char> is a range of characters + * * \<char> removes any special meaning for <char> + * + * Some interesting boundary cases: + * a-d-e is one range (a-d) followed by two single characters - and e. + * \a-\d is same as a-d + * a\-d is three single characters: a, d, - + * Trailing - is not special (so [a-] is two characters a and -). + * Initial - is not special ([a-] is same as [-a] is same as [\\-a]) + * This function never sees a trailing \. + * [] always fails + * [!] always succeeds + */ +static int +pm_list(const char *start, const char *end, const char c, int flags) +{ + const char *p = start; + char rangeStart = '\0', nextRangeStart; + int match = 1, nomatch = 0; + + /* This will be used soon... */ + (void)flags; /* UNUSED */ + + /* If this is a negated class, return success for nomatch. */ + if ((*p == '!' || *p == '^') && p < end) { + match = 0; + nomatch = 1; + ++p; + } + + while (p < end) { + nextRangeStart = '\0'; + switch (*p) { + case '-': + /* Trailing or initial '-' is not special. */ + if ((rangeStart == '\0') || (p == end - 1)) { + if (*p == c) + return (match); + } else { + char rangeEnd = *++p; + if (rangeEnd == '\\') + rangeEnd = *++p; + if ((rangeStart <= c) && (c <= rangeEnd)) + return (match); + } + break; + case '\\': + ++p; + /* Fall through */ + default: + if (*p == c) + return (match); + nextRangeStart = *p; /* Possible start of range. */ + } + rangeStart = nextRangeStart; + ++p; + } + return (nomatch); +} + +static int +pm_list_w(const wchar_t *start, const wchar_t *end, const wchar_t c, int flags) +{ + const wchar_t *p = start; + wchar_t rangeStart = L'\0', nextRangeStart; + int match = 1, nomatch = 0; + + /* This will be used soon... */ + (void)flags; /* UNUSED */ + + /* If this is a negated class, return success for nomatch. */ + if ((*p == L'!' || *p == L'^') && p < end) { + match = 0; + nomatch = 1; + ++p; + } + + while (p < end) { + nextRangeStart = L'\0'; + switch (*p) { + case L'-': + /* Trailing or initial '-' is not special. */ + if ((rangeStart == L'\0') || (p == end - 1)) { + if (*p == c) + return (match); + } else { + wchar_t rangeEnd = *++p; + if (rangeEnd == L'\\') + rangeEnd = *++p; + if ((rangeStart <= c) && (c <= rangeEnd)) + return (match); + } + break; + case L'\\': + ++p; + /* Fall through */ + default: + if (*p == c) + return (match); + nextRangeStart = *p; /* Possible start of range. */ + } + rangeStart = nextRangeStart; + ++p; + } + return (nomatch); +} + +/* + * If s is pointing to "./", ".//", "./././" or the like, skip it. + */ +static const char * +pm_slashskip(const char *s) { + while ((*s == '/') + || (s[0] == '.' && s[1] == '/') + || (s[0] == '.' && s[1] == '\0')) + ++s; + return (s); +} + +static const wchar_t * +pm_slashskip_w(const wchar_t *s) { + while ((*s == L'/') + || (s[0] == L'.' && s[1] == L'/') + || (s[0] == L'.' && s[1] == L'\0')) + ++s; + return (s); +} + +static int +pm(const char *p, const char *s, int flags) +{ + const char *end; + + /* + * Ignore leading './', './/', '././', etc. + */ + if (s[0] == '.' && s[1] == '/') + s = pm_slashskip(s + 1); + if (p[0] == '.' && p[1] == '/') + p = pm_slashskip(p + 1); + + for (;;) { + switch (*p) { + case '\0': + if (s[0] == '/') { + if (flags & PATHMATCH_NO_ANCHOR_END) + return (1); + /* "dir" == "dir/" == "dir/." */ + s = pm_slashskip(s); + } + return (*s == '\0'); + case '?': + /* ? always succeeds, unless we hit end of 's' */ + if (*s == '\0') + return (0); + break; + case '*': + /* "*" == "**" == "***" ... */ + while (*p == '*') + ++p; + /* Trailing '*' always succeeds. */ + if (*p == '\0') + return (1); + while (*s) { + if (archive_pathmatch(p, s, flags)) + return (1); + ++s; + } + return (0); + case '[': + /* + * Find the end of the [...] character class, + * ignoring \] that might occur within the class. + */ + end = p + 1; + while (*end != '\0' && *end != ']') { + if (*end == '\\' && end[1] != '\0') + ++end; + ++end; + } + if (*end == ']') { + /* We found [...], try to match it. */ + if (!pm_list(p + 1, end, *s, flags)) + return (0); + p = end; /* Jump to trailing ']' char. */ + break; + } else + /* No final ']', so just match '['. */ + if (*p != *s) + return (0); + break; + case '\\': + /* Trailing '\\' matches itself. */ + if (p[1] == '\0') { + if (*s != '\\') + return (0); + } else { + ++p; + if (*p != *s) + return (0); + } + break; + case '/': + if (*s != '/' && *s != '\0') + return (0); + /* Note: pattern "/\./" won't match "/"; + * pm_slashskip() correctly stops at backslash. */ + p = pm_slashskip(p); + s = pm_slashskip(s); + if (*p == '\0' && (flags & PATHMATCH_NO_ANCHOR_END)) + return (1); + --p; /* Counteract the increment below. */ + --s; + break; + case '$': + /* '$' is special only at end of pattern and only + * if PATHMATCH_NO_ANCHOR_END is specified. */ + if (p[1] == '\0' && (flags & PATHMATCH_NO_ANCHOR_END)){ + /* "dir" == "dir/" == "dir/." */ + return (*pm_slashskip(s) == '\0'); + } + /* Otherwise, '$' is not special. */ + /* FALL THROUGH */ + default: + if (*p != *s) + return (0); + break; + } + ++p; + ++s; + } +} + +static int +pm_w(const wchar_t *p, const wchar_t *s, int flags) +{ + const wchar_t *end; + + /* + * Ignore leading './', './/', '././', etc. + */ + if (s[0] == L'.' && s[1] == L'/') + s = pm_slashskip_w(s + 1); + if (p[0] == L'.' && p[1] == L'/') + p = pm_slashskip_w(p + 1); + + for (;;) { + switch (*p) { + case L'\0': + if (s[0] == L'/') { + if (flags & PATHMATCH_NO_ANCHOR_END) + return (1); + /* "dir" == "dir/" == "dir/." */ + s = pm_slashskip_w(s); + } + return (*s == L'\0'); + case L'?': + /* ? always succeeds, unless we hit end of 's' */ + if (*s == L'\0') + return (0); + break; + case L'*': + /* "*" == "**" == "***" ... */ + while (*p == L'*') + ++p; + /* Trailing '*' always succeeds. */ + if (*p == L'\0') + return (1); + while (*s) { + if (archive_pathmatch_w(p, s, flags)) + return (1); + ++s; + } + return (0); + case L'[': + /* + * Find the end of the [...] character class, + * ignoring \] that might occur within the class. + */ + end = p + 1; + while (*end != L'\0' && *end != L']') { + if (*end == L'\\' && end[1] != L'\0') + ++end; + ++end; + } + if (*end == L']') { + /* We found [...], try to match it. */ + if (!pm_list_w(p + 1, end, *s, flags)) + return (0); + p = end; /* Jump to trailing ']' char. */ + break; + } else + /* No final ']', so just match '['. */ + if (*p != *s) + return (0); + break; + case L'\\': + /* Trailing '\\' matches itself. */ + if (p[1] == L'\0') { + if (*s != L'\\') + return (0); + } else { + ++p; + if (*p != *s) + return (0); + } + break; + case L'/': + if (*s != L'/' && *s != L'\0') + return (0); + /* Note: pattern "/\./" won't match "/"; + * pm_slashskip() correctly stops at backslash. */ + p = pm_slashskip_w(p); + s = pm_slashskip_w(s); + if (*p == L'\0' && (flags & PATHMATCH_NO_ANCHOR_END)) + return (1); + --p; /* Counteract the increment below. */ + --s; + break; + case L'$': + /* '$' is special only at end of pattern and only + * if PATHMATCH_NO_ANCHOR_END is specified. */ + if (p[1] == L'\0' && (flags & PATHMATCH_NO_ANCHOR_END)){ + /* "dir" == "dir/" == "dir/." */ + return (*pm_slashskip_w(s) == L'\0'); + } + /* Otherwise, '$' is not special. */ + /* FALL THROUGH */ + default: + if (*p != *s) + return (0); + break; + } + ++p; + ++s; + } +} + +/* Main entry point. */ +int +__archive_pathmatch(const char *p, const char *s, int flags) +{ + /* Empty pattern only matches the empty string. */ + if (p == NULL || *p == '\0') + return (s == NULL || *s == '\0'); + + /* Leading '^' anchors the start of the pattern. */ + if (*p == '^') { + ++p; + flags &= ~PATHMATCH_NO_ANCHOR_START; + } + + if (*p == '/' && *s != '/') + return (0); + + /* Certain patterns anchor implicitly. */ + if (*p == '*' || *p == '/') { + while (*p == '/') + ++p; + while (*s == '/') + ++s; + return (pm(p, s, flags)); + } + + /* If start is unanchored, try to match start of each path element. */ + if (flags & PATHMATCH_NO_ANCHOR_START) { + for ( ; s != NULL; s = strchr(s, '/')) { + if (*s == '/') + s++; + if (pm(p, s, flags)) + return (1); + } + return (0); + } + + /* Default: Match from beginning. */ + return (pm(p, s, flags)); +} + +int +__archive_pathmatch_w(const wchar_t *p, const wchar_t *s, int flags) +{ + /* Empty pattern only matches the empty string. */ + if (p == NULL || *p == L'\0') + return (s == NULL || *s == L'\0'); + + /* Leading '^' anchors the start of the pattern. */ + if (*p == L'^') { + ++p; + flags &= ~PATHMATCH_NO_ANCHOR_START; + } + + if (*p == L'/' && *s != L'/') + return (0); + + /* Certain patterns anchor implicitly. */ + if (*p == L'*' || *p == L'/') { + while (*p == L'/') + ++p; + while (*s == L'/') + ++s; + return (pm_w(p, s, flags)); + } + + /* If start is unanchored, try to match start of each path element. */ + if (flags & PATHMATCH_NO_ANCHOR_START) { + for ( ; s != NULL; s = wcschr(s, L'/')) { + if (*s == L'/') + s++; + if (pm_w(p, s, flags)) + return (1); + } + return (0); + } + + /* Default: Match from beginning. */ + return (pm_w(p, s, flags)); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_pathmatch.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_pathmatch.h new file mode 100644 index 0000000000..9995142921 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_pathmatch.h @@ -0,0 +1,52 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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 + * in this position and unchanged. + * 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(S) ``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(S) 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. + * + * $FreeBSD$ + */ + +#ifndef ARCHIVE_PATHMATCH_H +#define ARCHIVE_PATHMATCH_H + +#ifndef __LIBARCHIVE_BUILD +#ifndef __LIBARCHIVE_TEST +#error This header is only to be used internally to libarchive. +#endif +#endif + +/* Don't anchor at beginning unless the pattern starts with "^" */ +#define PATHMATCH_NO_ANCHOR_START 1 +/* Don't anchor at end unless the pattern ends with "$" */ +#define PATHMATCH_NO_ANCHOR_END 2 + +/* Note that "^" and "$" are not special unless you set the corresponding + * flag above. */ + +int __archive_pathmatch(const char *p, const char *s, int flags); +int __archive_pathmatch_w(const wchar_t *p, const wchar_t *s, int flags); + +#define archive_pathmatch(p, s, f) __archive_pathmatch(p, s, f) +#define archive_pathmatch_w(p, s, f) __archive_pathmatch_w(p, s, f) + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_platform.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_platform.h new file mode 100644 index 0000000000..b8bcb52bc9 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_platform.h @@ -0,0 +1,202 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + * + * $FreeBSD: head/lib/libarchive/archive_platform.h 201090 2009-12-28 02:22:04Z kientzle $ + */ + +/* !!ONLY FOR USE INTERNALLY TO LIBARCHIVE!! */ + +/* + * This header is the first thing included in any of the libarchive + * source files. As far as possible, platform-specific issues should + * be dealt with here and not within individual source files. I'm + * actively trying to minimize #if blocks within the main source, + * since they obfuscate the code. + */ + +#ifndef ARCHIVE_PLATFORM_H_INCLUDED +#define ARCHIVE_PLATFORM_H_INCLUDED + +/* archive.h and archive_entry.h require this. */ +#define __LIBARCHIVE_BUILD 1 + +#if defined(PLATFORM_CONFIG_H) +/* Use hand-built config.h in environments that need it. */ +#include PLATFORM_CONFIG_H +#elif defined(HAVE_CONFIG_H) +/* Most POSIX platforms use the 'configure' script to build config.h */ +#include "config.h" +#else +/* Warn if the library hasn't been (automatically or manually) configured. */ +#error Oops: No config.h and no pre-built configuration in archive_platform.h. +#endif + +/* On macOS check for some symbols based on the deployment target version. */ +#if defined(__APPLE__) +# undef HAVE_FUTIMENS +# undef HAVE_UTIMENSAT +# include <AvailabilityMacros.h> +# if MAC_OS_X_VERSION_MIN_REQUIRED >= 101300 +# define HAVE_FUTIMENS 1 +# define HAVE_UTIMENSAT 1 +# endif +#endif + +/* It should be possible to get rid of this by extending the feature-test + * macros to cover Windows API functions, probably along with non-trivial + * refactoring of code to find structures that sit more cleanly on top of + * either Windows or Posix APIs. */ +#if (defined(__WIN32__) || defined(_WIN32) || defined(__WIN32)) && !defined(__CYGWIN__) +#include "archive_windows.h" +#else +#define la_stat(path,stref) stat(path,stref) +#endif + +/* + * The config files define a lot of feature macros. The following + * uses those macros to select/define replacements and include key + * headers as required. + */ + +/* Get a real definition for __FBSDID or __RCSID if we can */ +#if HAVE_SYS_CDEFS_H +#include <sys/cdefs.h> +#endif + +/* If not, define them so as to avoid dangling semicolons. */ +#ifndef __FBSDID +#define __FBSDID(a) struct _undefined_hack +#endif +#ifndef __RCSID +#define __RCSID(a) struct _undefined_hack +#endif + +/* Try to get standard C99-style integer type definitions. */ +#if HAVE_INTTYPES_H +#include <inttypes.h> +#endif +#if HAVE_STDINT_H +#include <stdint.h> +#endif + +/* Borland warns about its own constants! */ +#if defined(__BORLANDC__) +# if HAVE_DECL_UINT64_MAX +# undef UINT64_MAX +# undef HAVE_DECL_UINT64_MAX +# endif +# if HAVE_DECL_UINT64_MIN +# undef UINT64_MIN +# undef HAVE_DECL_UINT64_MIN +# endif +# if HAVE_DECL_INT64_MAX +# undef INT64_MAX +# undef HAVE_DECL_INT64_MAX +# endif +# if HAVE_DECL_INT64_MIN +# undef INT64_MIN +# undef HAVE_DECL_INT64_MIN +# endif +#endif + +/* Some platforms lack the standard *_MAX definitions. */ +#if !HAVE_DECL_SIZE_MAX +#define SIZE_MAX (~(size_t)0) +#endif +#if !HAVE_DECL_SSIZE_MAX +#define SSIZE_MAX ((ssize_t)(SIZE_MAX >> 1)) +#endif +#if !HAVE_DECL_UINT32_MAX +#define UINT32_MAX (~(uint32_t)0) +#endif +#if !HAVE_DECL_INT32_MAX +#define INT32_MAX ((int32_t)(UINT32_MAX >> 1)) +#endif +#if !HAVE_DECL_INT32_MIN +#define INT32_MIN ((int32_t)(~INT32_MAX)) +#endif +#if !HAVE_DECL_UINT64_MAX +#define UINT64_MAX (~(uint64_t)0) +#endif +#if !HAVE_DECL_INT64_MAX +#define INT64_MAX ((int64_t)(UINT64_MAX >> 1)) +#endif +#if !HAVE_DECL_INT64_MIN +#define INT64_MIN ((int64_t)(~INT64_MAX)) +#endif +#if !HAVE_DECL_UINTMAX_MAX +#define UINTMAX_MAX (~(uintmax_t)0) +#endif +#if !HAVE_DECL_INTMAX_MAX +#define INTMAX_MAX ((intmax_t)(UINTMAX_MAX >> 1)) +#endif +#if !HAVE_DECL_INTMAX_MIN +#define INTMAX_MIN ((intmax_t)(~INTMAX_MAX)) +#endif + +/* + * If we can't restore metadata using a file descriptor, then + * for compatibility's sake, close files before trying to restore metadata. + */ +#if defined(HAVE_FCHMOD) || defined(HAVE_FUTIMES) || defined(HAVE_ACL_SET_FD) || defined(HAVE_ACL_SET_FD_NP) || defined(HAVE_FCHOWN) +#define CAN_RESTORE_METADATA_FD +#endif + +/* + * glibc 2.24 deprecates readdir_r + */ +#if defined(HAVE_READDIR_R) && (!defined(__GLIBC__) || !defined(__GLIBC_MINOR__) || __GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 24)) +#define USE_READDIR_R 1 +#else +#undef USE_READDIR_R +#endif + +/* Set up defaults for internal error codes. */ +#ifndef ARCHIVE_ERRNO_FILE_FORMAT +#if HAVE_EFTYPE +#define ARCHIVE_ERRNO_FILE_FORMAT EFTYPE +#else +#if HAVE_EILSEQ +#define ARCHIVE_ERRNO_FILE_FORMAT EILSEQ +#else +#define ARCHIVE_ERRNO_FILE_FORMAT EINVAL +#endif +#endif +#endif + +#ifndef ARCHIVE_ERRNO_PROGRAMMER +#define ARCHIVE_ERRNO_PROGRAMMER EINVAL +#endif + +#ifndef ARCHIVE_ERRNO_MISC +#define ARCHIVE_ERRNO_MISC (-1) +#endif + +#if defined(__GNUC__) && (__GNUC__ >= 7) +#define __LA_FALLTHROUGH __attribute__((fallthrough)) +#else +#define __LA_FALLTHROUGH +#endif + +#endif /* !ARCHIVE_PLATFORM_H_INCLUDED */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_platform_acl.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_platform_acl.h new file mode 100644 index 0000000000..264e6de375 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_platform_acl.h @@ -0,0 +1,55 @@ +/*- + * Copyright (c) 2017 Martin Matuska + * 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(S) ``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(S) 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. + * + * $FreeBSD$ + */ + +/* !!ONLY FOR USE INTERNALLY TO LIBARCHIVE!! */ + +#ifndef ARCHIVE_PLATFORM_ACL_H_INCLUDED +#define ARCHIVE_PLATFORM_ACL_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#ifndef __LIBARCHIVE_TEST_COMMON +#error This header is only to be used internally to libarchive. +#endif +#endif + +/* + * Determine what ACL types are supported + */ +#if ARCHIVE_ACL_FREEBSD || ARCHIVE_ACL_SUNOS || ARCHIVE_ACL_LIBACL +#define ARCHIVE_ACL_POSIX1E 1 +#endif + +#if ARCHIVE_ACL_FREEBSD_NFS4 || ARCHIVE_ACL_SUNOS_NFS4 || \ + ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL +#define ARCHIVE_ACL_NFS4 1 +#endif + +#if ARCHIVE_ACL_POSIX1E || ARCHIVE_ACL_NFS4 +#define ARCHIVE_ACL_SUPPORT 1 +#endif + +#endif /* ARCHIVE_PLATFORM_ACL_H_INCLUDED */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_platform_xattr.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_platform_xattr.h new file mode 100644 index 0000000000..ad4b90ab7b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_platform_xattr.h @@ -0,0 +1,47 @@ +/*- + * Copyright (c) 2017 Martin Matuska + * 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(S) ``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(S) 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. + * + * $FreeBSD$ + */ + +/* !!ONLY FOR USE INTERNALLY TO LIBARCHIVE!! */ + +#ifndef ARCHIVE_PLATFORM_XATTR_H_INCLUDED +#define ARCHIVE_PLATFORM_XATTR_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#ifndef __LIBARCHIVE_TEST_COMMON +#error This header is only to be used internally to libarchive. +#endif +#endif + +/* + * Determine if we support extended attributes + */ +#if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_FREEBSD || \ + ARCHIVE_XATTR_AIX +#define ARCHIVE_XATTR_SUPPORT 1 +#endif + +#endif /* ARCHIVE_PLATFORM_XATTR_H_INCLUDED */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd7.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd7.c new file mode 100644 index 0000000000..4029395b4c --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd7.c @@ -0,0 +1,1168 @@ +/* Ppmd7.c -- PPMdH codec +2010-03-12 : Igor Pavlov : Public domain +This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */ + +#include "archive_platform.h" + +#include <memory.h> + +#include "archive_ppmd7_private.h" + +#ifdef PPMD_32BIT + #define Ppmd7_GetPtr(p, ptr) (ptr) + #define Ppmd7_GetContext(p, ptr) (ptr) + #define Ppmd7_GetStats(p, ctx) ((ctx)->Stats) +#else + #define Ppmd7_GetPtr(p, offs) ((void *)((p)->Base + (offs))) + #define Ppmd7_GetContext(p, offs) ((CPpmd7_Context *)Ppmd7_GetPtr((p), (offs))) + #define Ppmd7_GetStats(p, ctx) ((CPpmd_State *)Ppmd7_GetPtr((p), ((ctx)->Stats))) +#endif + +#define Ppmd7_GetBinSumm(p) \ + &p->BinSumm[Ppmd7Context_OneState(p->MinContext)->Freq - 1][p->PrevSuccess + \ + p->NS2BSIndx[Ppmd7_GetContext(p, p->MinContext->Suffix)->NumStats - 1] + \ + (p->HiBitsFlag = p->HB2Flag[p->FoundState->Symbol]) + \ + 2 * p->HB2Flag[Ppmd7Context_OneState(p->MinContext)->Symbol] + \ + ((p->RunLength >> 26) & 0x20)] + +#define kTopValue (1 << 24) +#define MAX_FREQ 124 +#define UNIT_SIZE 12 + +#define U2B(nu) ((UInt32)(nu) * UNIT_SIZE) +#define U2I(nu) (p->Units2Indx[(nu) - 1]) +#define I2U(indx) (p->Indx2Units[indx]) + +#ifdef PPMD_32BIT + #define REF(ptr) (ptr) +#else + #define REF(ptr) ((UInt32)((Byte *)(ptr) - (p)->Base)) +#endif + +#define STATS_REF(ptr) ((CPpmd_State_Ref)REF(ptr)) + +#define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref)) +#define STATS(ctx) Ppmd7_GetStats(p, ctx) +#define ONE_STATE(ctx) Ppmd7Context_OneState(ctx) +#define SUFFIX(ctx) CTX((ctx)->Suffix) + +static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; +static const Byte PPMD7_kExpEscape[16] = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; + +typedef CPpmd7_Context * CTX_PTR; + +struct CPpmd7_Node_; + +typedef + #ifdef PPMD_32BIT + struct CPpmd7_Node_ * + #else + UInt32 + #endif + CPpmd7_Node_Ref; + +typedef struct CPpmd7_Node_ +{ + UInt16 Stamp; /* must be at offset 0 as CPpmd7_Context::NumStats. Stamp=0 means free */ + UInt16 NU; + CPpmd7_Node_Ref Next; /* must be at offset >= 4 */ + CPpmd7_Node_Ref Prev; +} CPpmd7_Node; + +#ifdef PPMD_32BIT + #define NODE(ptr) (ptr) +#else + #define NODE(offs) ((CPpmd7_Node *)(p->Base + (offs))) +#endif + +static void Ppmd7_Update1(CPpmd7 *p); +static void Ppmd7_Update1_0(CPpmd7 *p); +static void Ppmd7_Update2(CPpmd7 *p); +static void Ppmd7_UpdateBin(CPpmd7 *p); +static CPpmd_See *Ppmd7_MakeEscFreq(CPpmd7 *p, unsigned numMasked, + UInt32 *scale); + +/* ----------- Base ----------- */ + +static void Ppmd7_Construct(CPpmd7 *p) +{ + unsigned i, k, m; + + p->Base = 0; + + for (i = 0, k = 0; i < PPMD_NUM_INDEXES; i++) + { + unsigned step = (i >= 12 ? 4 : (i >> 2) + 1); + do { p->Units2Indx[k++] = (Byte)i; } while(--step); + p->Indx2Units[i] = (Byte)k; + } + + p->NS2BSIndx[0] = (0 << 1); + p->NS2BSIndx[1] = (1 << 1); + memset(p->NS2BSIndx + 2, (2 << 1), 9); + memset(p->NS2BSIndx + 11, (3 << 1), 256 - 11); + + for (i = 0; i < 3; i++) + p->NS2Indx[i] = (Byte)i; + for (m = i, k = 1; i < 256; i++) + { + p->NS2Indx[i] = (Byte)m; + if (--k == 0) + k = (++m) - 2; + } + + memset(p->HB2Flag, 0, 0x40); + memset(p->HB2Flag + 0x40, 8, 0x100 - 0x40); +} + +static void Ppmd7_Free(CPpmd7 *p) +{ + free(p->Base); + p->Size = 0; + p->Base = 0; +} + +static Bool Ppmd7_Alloc(CPpmd7 *p, UInt32 size) +{ + if (p->Base == 0 || p->Size != size) + { + /* RestartModel() below assumes that p->Size >= UNIT_SIZE + (see the calculation of m->MinContext). */ + if (size < UNIT_SIZE) { + return False; + } + Ppmd7_Free(p); + p->AlignOffset = + #ifdef PPMD_32BIT + (4 - size) & 3; + #else + 4 - (size & 3); + #endif + if ((p->Base = (Byte *)malloc(p->AlignOffset + size + #ifndef PPMD_32BIT + + UNIT_SIZE + #endif + )) == 0) + return False; + p->Size = size; + } + return True; +} + +static void InsertNode(CPpmd7 *p, void *node, unsigned indx) +{ + *((CPpmd_Void_Ref *)node) = p->FreeList[indx]; + p->FreeList[indx] = REF(node); +} + +static void *RemoveNode(CPpmd7 *p, unsigned indx) +{ + CPpmd_Void_Ref *node = (CPpmd_Void_Ref *)Ppmd7_GetPtr(p, p->FreeList[indx]); + p->FreeList[indx] = *node; + return node; +} + +static void SplitBlock(CPpmd7 *p, void *ptr, unsigned oldIndx, unsigned newIndx) +{ + unsigned i, nu = I2U(oldIndx) - I2U(newIndx); + ptr = (Byte *)ptr + U2B(I2U(newIndx)); + if (I2U(i = U2I(nu)) != nu) + { + unsigned k = I2U(--i); + InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1); + } + InsertNode(p, ptr, i); +} + +static void GlueFreeBlocks(CPpmd7 *p) +{ + #ifdef PPMD_32BIT + CPpmd7_Node headItem; + CPpmd7_Node_Ref head = &headItem; + #else + CPpmd7_Node_Ref head = p->AlignOffset + p->Size; + #endif + + CPpmd7_Node_Ref n = head; + unsigned i; + + p->GlueCount = 255; + + /* create doubly-linked list of free blocks */ + for (i = 0; i < PPMD_NUM_INDEXES; i++) + { + UInt16 nu = I2U(i); + CPpmd7_Node_Ref next = (CPpmd7_Node_Ref)p->FreeList[i]; + p->FreeList[i] = 0; + while (next != 0) + { + CPpmd7_Node *node = NODE(next); + node->Next = n; + n = NODE(n)->Prev = next; + next = *(const CPpmd7_Node_Ref *)node; + node->Stamp = 0; + node->NU = (UInt16)nu; + } + } + NODE(head)->Stamp = 1; + NODE(head)->Next = n; + NODE(n)->Prev = head; + if (p->LoUnit != p->HiUnit) + ((CPpmd7_Node *)p->LoUnit)->Stamp = 1; + + /* Glue free blocks */ + while (n != head) + { + CPpmd7_Node *node = NODE(n); + UInt32 nu = (UInt32)node->NU; + for (;;) + { + CPpmd7_Node *node2 = NODE(n) + nu; + nu += node2->NU; + if (node2->Stamp != 0 || nu >= 0x10000) + break; + NODE(node2->Prev)->Next = node2->Next; + NODE(node2->Next)->Prev = node2->Prev; + node->NU = (UInt16)nu; + } + n = node->Next; + } + + /* Fill lists of free blocks */ + for (n = NODE(head)->Next; n != head;) + { + CPpmd7_Node *node = NODE(n); + unsigned nu; + CPpmd7_Node_Ref next = node->Next; + for (nu = node->NU; nu > 128; nu -= 128, node += 128) + InsertNode(p, node, PPMD_NUM_INDEXES - 1); + if (I2U(i = U2I(nu)) != nu) + { + unsigned k = I2U(--i); + InsertNode(p, node + k, nu - k - 1); + } + InsertNode(p, node, i); + n = next; + } +} + +static void *AllocUnitsRare(CPpmd7 *p, unsigned indx) +{ + unsigned i; + void *retVal; + if (p->GlueCount == 0) + { + GlueFreeBlocks(p); + if (p->FreeList[indx] != 0) + return RemoveNode(p, indx); + } + i = indx; + do + { + if (++i == PPMD_NUM_INDEXES) + { + UInt32 numBytes = U2B(I2U(indx)); + p->GlueCount--; + return ((UInt32)(p->UnitsStart - p->Text) > numBytes) ? (p->UnitsStart -= numBytes) : (NULL); + } + } + while (p->FreeList[i] == 0); + retVal = RemoveNode(p, i); + SplitBlock(p, retVal, i, indx); + return retVal; +} + +static void *AllocUnits(CPpmd7 *p, unsigned indx) +{ + UInt32 numBytes; + if (p->FreeList[indx] != 0) + return RemoveNode(p, indx); + numBytes = U2B(I2U(indx)); + if (numBytes <= (UInt32)(p->HiUnit - p->LoUnit)) + { + void *retVal = p->LoUnit; + p->LoUnit += numBytes; + return retVal; + } + return AllocUnitsRare(p, indx); +} + +#define MyMem12Cpy(dest, src, num) \ + { UInt32 *d = (UInt32 *)dest; const UInt32 *s = (const UInt32 *)src; UInt32 n = num; \ + do { d[0] = s[0]; d[1] = s[1]; d[2] = s[2]; s += 3; d += 3; } while(--n); } + +static void *ShrinkUnits(CPpmd7 *p, void *oldPtr, unsigned oldNU, unsigned newNU) +{ + unsigned i0 = U2I(oldNU); + unsigned i1 = U2I(newNU); + if (i0 == i1) + return oldPtr; + if (p->FreeList[i1] != 0) + { + void *ptr = RemoveNode(p, i1); + MyMem12Cpy(ptr, oldPtr, newNU); + InsertNode(p, oldPtr, i0); + return ptr; + } + SplitBlock(p, oldPtr, i0, i1); + return oldPtr; +} + +#define SUCCESSOR(p) ((CPpmd_Void_Ref)((p)->SuccessorLow | ((UInt32)(p)->SuccessorHigh << 16))) + +static void SetSuccessor(CPpmd_State *p, CPpmd_Void_Ref v) +{ + (p)->SuccessorLow = (UInt16)((UInt32)(v) & 0xFFFF); + (p)->SuccessorHigh = (UInt16)(((UInt32)(v) >> 16) & 0xFFFF); +} + +static void RestartModel(CPpmd7 *p) +{ + unsigned i, k, m; + + memset(p->FreeList, 0, sizeof(p->FreeList)); + p->Text = p->Base + p->AlignOffset; + p->HiUnit = p->Text + p->Size; + p->LoUnit = p->UnitsStart = p->HiUnit - p->Size / 8 / UNIT_SIZE * 7 * UNIT_SIZE; + p->GlueCount = 0; + + p->OrderFall = p->MaxOrder; + p->RunLength = p->InitRL = -(Int32)((p->MaxOrder < 12) ? p->MaxOrder : 12) - 1; + p->PrevSuccess = 0; + + p->MinContext = p->MaxContext = (CTX_PTR)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */ + p->MinContext->Suffix = 0; + p->MinContext->NumStats = 256; + p->MinContext->SummFreq = 256 + 1; + p->FoundState = (CPpmd_State *)p->LoUnit; /* AllocUnits(p, PPMD_NUM_INDEXES - 1); */ + p->LoUnit += U2B(256 / 2); + p->MinContext->Stats = REF(p->FoundState); + for (i = 0; i < 256; i++) + { + CPpmd_State *s = &p->FoundState[i]; + s->Symbol = (Byte)i; + s->Freq = 1; + SetSuccessor(s, 0); + } + + for (i = 0; i < 128; i++) + for (k = 0; k < 8; k++) + { + UInt16 *dest = p->BinSumm[i] + k; + UInt16 val = (UInt16)(PPMD_BIN_SCALE - kInitBinEsc[k] / (i + 2)); + for (m = 0; m < 64; m += 8) + dest[m] = val; + } + + for (i = 0; i < 25; i++) + for (k = 0; k < 16; k++) + { + CPpmd_See *s = &p->See[i][k]; + s->Summ = (UInt16)((5 * i + 10) << (s->Shift = PPMD_PERIOD_BITS - 4)); + s->Count = 4; + } +} + +static void Ppmd7_Init(CPpmd7 *p, unsigned maxOrder) +{ + p->MaxOrder = maxOrder; + RestartModel(p); + p->DummySee.Shift = PPMD_PERIOD_BITS; + p->DummySee.Summ = 0; /* unused */ + p->DummySee.Count = 64; /* unused */ +} + +static CTX_PTR CreateSuccessors(CPpmd7 *p, Bool skip) +{ + CPpmd_State upState; + CTX_PTR c = p->MinContext; + CPpmd_Byte_Ref upBranch = (CPpmd_Byte_Ref)SUCCESSOR(p->FoundState); + CPpmd_State *ps[PPMD7_MAX_ORDER]; + unsigned numPs = 0; + + if (!skip) + ps[numPs++] = p->FoundState; + + while (c->Suffix) + { + CPpmd_Void_Ref successor; + CPpmd_State *s; + c = SUFFIX(c); + if (c->NumStats != 1) + { + for (s = STATS(c); s->Symbol != p->FoundState->Symbol; s++); + } + else + s = ONE_STATE(c); + successor = SUCCESSOR(s); + if (successor != upBranch) + { + c = CTX(successor); + if (numPs == 0) + return c; + break; + } + ps[numPs++] = s; + } + + upState.Symbol = *(const Byte *)Ppmd7_GetPtr(p, upBranch); + SetSuccessor(&upState, upBranch + 1); + + if (c->NumStats == 1) + upState.Freq = ONE_STATE(c)->Freq; + else + { + UInt32 cf, s0; + CPpmd_State *s; + for (s = STATS(c); s->Symbol != upState.Symbol; s++); + cf = s->Freq - 1; + s0 = c->SummFreq - c->NumStats - cf; + upState.Freq = (Byte)(1 + ((2 * cf <= s0) ? (5 * cf > s0) : ((2 * cf + 3 * s0 - 1) / (2 * s0)))); + } + + while (numPs != 0) + { + /* Create Child */ + CTX_PTR c1; /* = AllocContext(p); */ + if (p->HiUnit != p->LoUnit) + c1 = (CTX_PTR)(p->HiUnit -= UNIT_SIZE); + else if (p->FreeList[0] != 0) + c1 = (CTX_PTR)RemoveNode(p, 0); + else + { + c1 = (CTX_PTR)AllocUnitsRare(p, 0); + if (!c1) + return NULL; + } + c1->NumStats = 1; + *ONE_STATE(c1) = upState; + c1->Suffix = REF(c); + SetSuccessor(ps[--numPs], REF(c1)); + c = c1; + } + + return c; +} + +static void SwapStates(CPpmd_State *t1, CPpmd_State *t2) +{ + CPpmd_State tmp = *t1; + *t1 = *t2; + *t2 = tmp; +} + +static void UpdateModel(CPpmd7 *p) +{ + CPpmd_Void_Ref successor, fSuccessor = SUCCESSOR(p->FoundState); + CTX_PTR c; + unsigned s0, ns; + + if (p->FoundState->Freq < MAX_FREQ / 4 && p->MinContext->Suffix != 0) + { + c = SUFFIX(p->MinContext); + + if (c->NumStats == 1) + { + CPpmd_State *s = ONE_STATE(c); + if (s->Freq < 32) + s->Freq++; + } + else + { + CPpmd_State *s = STATS(c); + if (s->Symbol != p->FoundState->Symbol) + { + do { s++; } while (s->Symbol != p->FoundState->Symbol); + if (s[0].Freq >= s[-1].Freq) + { + SwapStates(&s[0], &s[-1]); + s--; + } + } + if (s->Freq < MAX_FREQ - 9) + { + s->Freq += 2; + c->SummFreq += 2; + } + } + } + + if (p->OrderFall == 0) + { + p->MinContext = p->MaxContext = CreateSuccessors(p, True); + if (p->MinContext == 0) + { + RestartModel(p); + return; + } + SetSuccessor(p->FoundState, REF(p->MinContext)); + return; + } + + *p->Text++ = p->FoundState->Symbol; + successor = REF(p->Text); + if (p->Text >= p->UnitsStart) + { + RestartModel(p); + return; + } + + if (fSuccessor) + { + if (fSuccessor <= successor) + { + CTX_PTR cs = CreateSuccessors(p, False); + if (cs == NULL) + { + RestartModel(p); + return; + } + fSuccessor = REF(cs); + } + if (--p->OrderFall == 0) + { + successor = fSuccessor; + p->Text -= (p->MaxContext != p->MinContext); + } + } + else + { + SetSuccessor(p->FoundState, successor); + fSuccessor = REF(p->MinContext); + } + + s0 = p->MinContext->SummFreq - (ns = p->MinContext->NumStats) - (p->FoundState->Freq - 1); + + for (c = p->MaxContext; c != p->MinContext; c = SUFFIX(c)) + { + unsigned ns1; + UInt32 cf, sf; + if ((ns1 = c->NumStats) != 1) + { + if ((ns1 & 1) == 0) + { + /* Expand for one UNIT */ + unsigned oldNU = ns1 >> 1; + unsigned i = U2I(oldNU); + if (i != U2I(oldNU + 1)) + { + void *ptr = AllocUnits(p, i + 1); + void *oldPtr; + if (!ptr) + { + RestartModel(p); + return; + } + oldPtr = STATS(c); + MyMem12Cpy(ptr, oldPtr, oldNU); + InsertNode(p, oldPtr, i); + c->Stats = STATS_REF(ptr); + } + } + c->SummFreq = (UInt16)(c->SummFreq + (2 * ns1 < ns) + 2 * ((4 * ns1 <= ns) & (c->SummFreq <= 8 * ns1))); + } + else + { + CPpmd_State *s = (CPpmd_State*)AllocUnits(p, 0); + if (!s) + { + RestartModel(p); + return; + } + *s = *ONE_STATE(c); + c->Stats = REF(s); + if (s->Freq < MAX_FREQ / 4 - 1) + s->Freq <<= 1; + else + s->Freq = MAX_FREQ - 4; + c->SummFreq = (UInt16)(s->Freq + p->InitEsc + (ns > 3)); + } + cf = 2 * (UInt32)p->FoundState->Freq * (c->SummFreq + 6); + sf = (UInt32)s0 + c->SummFreq; + if (cf < 6 * sf) + { + cf = 1 + (cf > sf) + (cf >= 4 * sf); + c->SummFreq += 3; + } + else + { + cf = 4 + (cf >= 9 * sf) + (cf >= 12 * sf) + (cf >= 15 * sf); + c->SummFreq = (UInt16)(c->SummFreq + cf); + } + { + CPpmd_State *s = STATS(c) + ns1; + SetSuccessor(s, successor); + s->Symbol = p->FoundState->Symbol; + s->Freq = (Byte)cf; + c->NumStats = (UInt16)(ns1 + 1); + } + } + p->MaxContext = p->MinContext = CTX(fSuccessor); +} + +static void Rescale(CPpmd7 *p) +{ + unsigned i, adder, sumFreq, escFreq; + CPpmd_State *stats = STATS(p->MinContext); + CPpmd_State *s = p->FoundState; + { + CPpmd_State tmp = *s; + for (; s != stats; s--) + s[0] = s[-1]; + *s = tmp; + } + escFreq = p->MinContext->SummFreq - s->Freq; + s->Freq += 4; + adder = (p->OrderFall != 0); + s->Freq = (Byte)((s->Freq + adder) >> 1); + sumFreq = s->Freq; + + i = p->MinContext->NumStats - 1; + do + { + escFreq -= (++s)->Freq; + s->Freq = (Byte)((s->Freq + adder) >> 1); + sumFreq += s->Freq; + if (s[0].Freq > s[-1].Freq) + { + CPpmd_State *s1 = s; + CPpmd_State tmp = *s1; + do + s1[0] = s1[-1]; + while (--s1 != stats && tmp.Freq > s1[-1].Freq); + *s1 = tmp; + } + } + while (--i); + + if (s->Freq == 0) + { + unsigned numStats = p->MinContext->NumStats; + unsigned n0, n1; + do { i++; } while ((--s)->Freq == 0); + escFreq += i; + p->MinContext->NumStats = (UInt16)(p->MinContext->NumStats - i); + if (p->MinContext->NumStats == 1) + { + CPpmd_State tmp = *stats; + do + { + tmp.Freq = (Byte)(tmp.Freq - (tmp.Freq >> 1)); + escFreq >>= 1; + } + while (escFreq > 1); + InsertNode(p, stats, U2I(((numStats + 1) >> 1))); + *(p->FoundState = ONE_STATE(p->MinContext)) = tmp; + return; + } + n0 = (numStats + 1) >> 1; + n1 = (p->MinContext->NumStats + 1) >> 1; + if (n0 != n1) + p->MinContext->Stats = STATS_REF(ShrinkUnits(p, stats, n0, n1)); + } + p->MinContext->SummFreq = (UInt16)(sumFreq + escFreq - (escFreq >> 1)); + p->FoundState = STATS(p->MinContext); +} + +static CPpmd_See *Ppmd7_MakeEscFreq(CPpmd7 *p, unsigned numMasked, UInt32 *escFreq) +{ + CPpmd_See *see; + unsigned nonMasked = p->MinContext->NumStats - numMasked; + if (p->MinContext->NumStats != 256) + { + see = p->See[p->NS2Indx[nonMasked - 1]] + + (nonMasked < (unsigned)SUFFIX(p->MinContext)->NumStats - p->MinContext->NumStats) + + 2 * (p->MinContext->SummFreq < 11 * p->MinContext->NumStats) + + 4 * (numMasked > nonMasked) + + p->HiBitsFlag; + { + unsigned r = (see->Summ >> see->Shift); + see->Summ = (UInt16)(see->Summ - r); + *escFreq = r + (r == 0); + } + } + else + { + see = &p->DummySee; + *escFreq = 1; + } + return see; +} + +static void NextContext(CPpmd7 *p) +{ + CTX_PTR c = CTX(SUCCESSOR(p->FoundState)); + if (p->OrderFall == 0 && (Byte *)c > p->Text) + p->MinContext = p->MaxContext = c; + else + UpdateModel(p); +} + +static void Ppmd7_Update1(CPpmd7 *p) +{ + CPpmd_State *s = p->FoundState; + s->Freq += 4; + p->MinContext->SummFreq += 4; + if (s[0].Freq > s[-1].Freq) + { + SwapStates(&s[0], &s[-1]); + p->FoundState = --s; + if (s->Freq > MAX_FREQ) + Rescale(p); + } + NextContext(p); +} + +static void Ppmd7_Update1_0(CPpmd7 *p) +{ + p->PrevSuccess = (2 * p->FoundState->Freq > p->MinContext->SummFreq); + p->RunLength += p->PrevSuccess; + p->MinContext->SummFreq += 4; + if ((p->FoundState->Freq += 4) > MAX_FREQ) + Rescale(p); + NextContext(p); +} + +static void Ppmd7_UpdateBin(CPpmd7 *p) +{ + p->FoundState->Freq = (Byte)(p->FoundState->Freq + (p->FoundState->Freq < 128 ? 1: 0)); + p->PrevSuccess = 1; + p->RunLength++; + NextContext(p); +} + +static void Ppmd7_Update2(CPpmd7 *p) +{ + p->MinContext->SummFreq += 4; + if ((p->FoundState->Freq += 4) > MAX_FREQ) + Rescale(p); + p->RunLength = p->InitRL; + UpdateModel(p); +} + +/* ---------- Decode ---------- */ + +static Bool Ppmd_RangeDec_Init(CPpmd7z_RangeDec *p) +{ + unsigned i; + p->Low = p->Bottom = 0; + p->Range = 0xFFFFFFFF; + for (i = 0; i < 4; i++) + p->Code = (p->Code << 8) | p->Stream->Read((void *)p->Stream); + return (p->Code < 0xFFFFFFFF); +} + +static Bool Ppmd7z_RangeDec_Init(CPpmd7z_RangeDec *p) +{ + if (p->Stream->Read((void *)p->Stream) != 0) + return False; + return Ppmd_RangeDec_Init(p); +} + +static Bool PpmdRAR_RangeDec_Init(CPpmd7z_RangeDec *p) +{ + if (!Ppmd_RangeDec_Init(p)) + return False; + p->Bottom = 0x8000; + return True; +} + +static UInt32 Range_GetThreshold(void *pp, UInt32 total) +{ + CPpmd7z_RangeDec *p = (CPpmd7z_RangeDec *)pp; + return (p->Code - p->Low) / (p->Range /= total); +} + +static void Range_Normalize(CPpmd7z_RangeDec *p) +{ + while (1) + { + if((p->Low ^ (p->Low + p->Range)) >= kTopValue) + { + if(p->Range >= p->Bottom) + break; + else + p->Range = ((uint32_t)(-(int32_t)p->Low)) & (p->Bottom - 1); + } + p->Code = (p->Code << 8) | p->Stream->Read((void *)p->Stream); + p->Range <<= 8; + p->Low <<= 8; + } +} + +static void Range_Decode_7z(void *pp, UInt32 start, UInt32 size) +{ + CPpmd7z_RangeDec *p = (CPpmd7z_RangeDec *)pp; + p->Code -= start * p->Range; + p->Range *= size; + Range_Normalize(p); +} + +static void Range_Decode_RAR(void *pp, UInt32 start, UInt32 size) +{ + CPpmd7z_RangeDec *p = (CPpmd7z_RangeDec *)pp; + p->Low += start * p->Range; + p->Range *= size; + Range_Normalize(p); +} + +static UInt32 Range_DecodeBit_7z(void *pp, UInt32 size0) +{ + CPpmd7z_RangeDec *p = (CPpmd7z_RangeDec *)pp; + UInt32 newBound = (p->Range >> 14) * size0; + UInt32 symbol; + if (p->Code < newBound) + { + symbol = 0; + p->Range = newBound; + } + else + { + symbol = 1; + p->Code -= newBound; + p->Range -= newBound; + } + Range_Normalize(p); + return symbol; +} + +static UInt32 Range_DecodeBit_RAR(void *pp, UInt32 size0) +{ + CPpmd7z_RangeDec *p = (CPpmd7z_RangeDec *)pp; + UInt32 bit, value = p->p.GetThreshold(p, PPMD_BIN_SCALE); + if(value < size0) + { + bit = 0; + p->p.Decode(p, 0, size0); + } + else + { + bit = 1; + p->p.Decode(p, size0, PPMD_BIN_SCALE - size0); + } + return bit; +} + +static void Ppmd7z_RangeDec_CreateVTable(CPpmd7z_RangeDec *p) +{ + p->p.GetThreshold = Range_GetThreshold; + p->p.Decode = Range_Decode_7z; + p->p.DecodeBit = Range_DecodeBit_7z; +} + +static void PpmdRAR_RangeDec_CreateVTable(CPpmd7z_RangeDec *p) +{ + p->p.GetThreshold = Range_GetThreshold; + p->p.Decode = Range_Decode_RAR; + p->p.DecodeBit = Range_DecodeBit_RAR; +} + +#define MASK(sym) ((signed char *)charMask)[sym] + +static int Ppmd7_DecodeSymbol(CPpmd7 *p, IPpmd7_RangeDec *rc) +{ + size_t charMask[256 / sizeof(size_t)]; + if (p->MinContext->NumStats != 1) + { + CPpmd_State *s = Ppmd7_GetStats(p, p->MinContext); + unsigned i; + UInt32 count, hiCnt; + if ((count = rc->GetThreshold(rc, p->MinContext->SummFreq)) < (hiCnt = s->Freq)) + { + Byte symbol; + rc->Decode(rc, 0, s->Freq); + p->FoundState = s; + symbol = s->Symbol; + Ppmd7_Update1_0(p); + return symbol; + } + p->PrevSuccess = 0; + i = p->MinContext->NumStats - 1; + do + { + if ((hiCnt += (++s)->Freq) > count) + { + Byte symbol; + rc->Decode(rc, hiCnt - s->Freq, s->Freq); + p->FoundState = s; + symbol = s->Symbol; + Ppmd7_Update1(p); + return symbol; + } + } + while (--i); + if (count >= p->MinContext->SummFreq) + return -2; + p->HiBitsFlag = p->HB2Flag[p->FoundState->Symbol]; + rc->Decode(rc, hiCnt, p->MinContext->SummFreq - hiCnt); + PPMD_SetAllBitsIn256Bytes(charMask); + MASK(s->Symbol) = 0; + i = p->MinContext->NumStats - 1; + do { MASK((--s)->Symbol) = 0; } while (--i); + } + else + { + UInt16 *prob = Ppmd7_GetBinSumm(p); + if (rc->DecodeBit(rc, *prob) == 0) + { + Byte symbol; + *prob = (UInt16)PPMD_UPDATE_PROB_0(*prob); + symbol = (p->FoundState = Ppmd7Context_OneState(p->MinContext))->Symbol; + Ppmd7_UpdateBin(p); + return symbol; + } + *prob = (UInt16)PPMD_UPDATE_PROB_1(*prob); + p->InitEsc = PPMD7_kExpEscape[*prob >> 10]; + PPMD_SetAllBitsIn256Bytes(charMask); + MASK(Ppmd7Context_OneState(p->MinContext)->Symbol) = 0; + p->PrevSuccess = 0; + } + for (;;) + { + CPpmd_State *ps[256], *s; + UInt32 freqSum, count, hiCnt; + CPpmd_See *see; + unsigned i, num, numMasked = p->MinContext->NumStats; + do + { + p->OrderFall++; + if (!p->MinContext->Suffix) + return -1; + p->MinContext = Ppmd7_GetContext(p, p->MinContext->Suffix); + } + while (p->MinContext->NumStats == numMasked); + hiCnt = 0; + s = Ppmd7_GetStats(p, p->MinContext); + i = 0; + num = p->MinContext->NumStats - numMasked; + do + { + int k = (int)(MASK(s->Symbol)); + hiCnt += (s->Freq & k); + ps[i] = s++; + i -= k; + } + while (i != num); + + see = Ppmd7_MakeEscFreq(p, numMasked, &freqSum); + freqSum += hiCnt; + count = rc->GetThreshold(rc, freqSum); + + if (count < hiCnt) + { + Byte symbol; + CPpmd_State **pps = ps; + for (hiCnt = 0; (hiCnt += (*pps)->Freq) <= count; pps++); + s = *pps; + rc->Decode(rc, hiCnt - s->Freq, s->Freq); + Ppmd_See_Update(see); + p->FoundState = s; + symbol = s->Symbol; + Ppmd7_Update2(p); + return symbol; + } + if (count >= freqSum) + return -2; + rc->Decode(rc, hiCnt, freqSum - hiCnt); + see->Summ = (UInt16)(see->Summ + freqSum); + do { MASK(ps[--i]->Symbol) = 0; } while (i != 0); + } +} + +/* ---------- Encode ---------- Ppmd7Enc.c */ + +#define kTopValue (1 << 24) + +static void Ppmd7z_RangeEnc_Init(CPpmd7z_RangeEnc *p) +{ + p->Low = 0; + p->Range = 0xFFFFFFFF; + p->Cache = 0; + p->CacheSize = 1; +} + +static void RangeEnc_ShiftLow(CPpmd7z_RangeEnc *p) +{ + if ((UInt32)p->Low < (UInt32)0xFF000000 || (unsigned)(p->Low >> 32) != 0) + { + Byte temp = p->Cache; + do + { + p->Stream->Write(p->Stream, (Byte)(temp + (Byte)(p->Low >> 32))); + temp = 0xFF; + } + while(--p->CacheSize != 0); + p->Cache = (Byte)((UInt32)p->Low >> 24); + } + p->CacheSize++; + p->Low = ((UInt32)p->Low << 8) & 0xFFFFFFFF; +} + +static void RangeEnc_Encode(CPpmd7z_RangeEnc *p, UInt32 start, UInt32 size, UInt32 total) +{ + p->Low += (UInt64)start * (UInt64)(p->Range /= total); + p->Range *= size; + while (p->Range < kTopValue) + { + p->Range <<= 8; + RangeEnc_ShiftLow(p); + } +} + +static void RangeEnc_EncodeBit_0(CPpmd7z_RangeEnc *p, UInt32 size0) +{ + p->Range = (p->Range >> 14) * size0; + while (p->Range < kTopValue) + { + p->Range <<= 8; + RangeEnc_ShiftLow(p); + } +} + +static void RangeEnc_EncodeBit_1(CPpmd7z_RangeEnc *p, UInt32 size0) +{ + UInt32 newBound = (p->Range >> 14) * size0; + p->Low += newBound; + p->Range -= newBound; + while (p->Range < kTopValue) + { + p->Range <<= 8; + RangeEnc_ShiftLow(p); + } +} + +static void Ppmd7z_RangeEnc_FlushData(CPpmd7z_RangeEnc *p) +{ + unsigned i; + for (i = 0; i < 5; i++) + RangeEnc_ShiftLow(p); +} + + +#define MASK(sym) ((signed char *)charMask)[sym] + +static void Ppmd7_EncodeSymbol(CPpmd7 *p, CPpmd7z_RangeEnc *rc, int symbol) +{ + size_t charMask[256 / sizeof(size_t)]; + if (p->MinContext->NumStats != 1) + { + CPpmd_State *s = Ppmd7_GetStats(p, p->MinContext); + UInt32 sum; + unsigned i; + if (s->Symbol == symbol) + { + RangeEnc_Encode(rc, 0, s->Freq, p->MinContext->SummFreq); + p->FoundState = s; + Ppmd7_Update1_0(p); + return; + } + p->PrevSuccess = 0; + sum = s->Freq; + i = p->MinContext->NumStats - 1; + do + { + if ((++s)->Symbol == symbol) + { + RangeEnc_Encode(rc, sum, s->Freq, p->MinContext->SummFreq); + p->FoundState = s; + Ppmd7_Update1(p); + return; + } + sum += s->Freq; + } + while (--i); + + p->HiBitsFlag = p->HB2Flag[p->FoundState->Symbol]; + PPMD_SetAllBitsIn256Bytes(charMask); + MASK(s->Symbol) = 0; + i = p->MinContext->NumStats - 1; + do { MASK((--s)->Symbol) = 0; } while (--i); + RangeEnc_Encode(rc, sum, p->MinContext->SummFreq - sum, p->MinContext->SummFreq); + } + else + { + UInt16 *prob = Ppmd7_GetBinSumm(p); + CPpmd_State *s = Ppmd7Context_OneState(p->MinContext); + if (s->Symbol == symbol) + { + RangeEnc_EncodeBit_0(rc, *prob); + *prob = (UInt16)PPMD_UPDATE_PROB_0(*prob); + p->FoundState = s; + Ppmd7_UpdateBin(p); + return; + } + else + { + RangeEnc_EncodeBit_1(rc, *prob); + *prob = (UInt16)PPMD_UPDATE_PROB_1(*prob); + p->InitEsc = PPMD7_kExpEscape[*prob >> 10]; + PPMD_SetAllBitsIn256Bytes(charMask); + MASK(s->Symbol) = 0; + p->PrevSuccess = 0; + } + } + for (;;) + { + UInt32 escFreq; + CPpmd_See *see; + CPpmd_State *s; + UInt32 sum; + unsigned i, numMasked = p->MinContext->NumStats; + do + { + p->OrderFall++; + if (!p->MinContext->Suffix) + return; /* EndMarker (symbol = -1) */ + p->MinContext = Ppmd7_GetContext(p, p->MinContext->Suffix); + } + while (p->MinContext->NumStats == numMasked); + + see = Ppmd7_MakeEscFreq(p, numMasked, &escFreq); + s = Ppmd7_GetStats(p, p->MinContext); + sum = 0; + i = p->MinContext->NumStats; + do + { + int cur = s->Symbol; + if (cur == symbol) + { + UInt32 low = sum; + CPpmd_State *s1 = s; + do + { + sum += (s->Freq & (int)(MASK(s->Symbol))); + s++; + } + while (--i); + RangeEnc_Encode(rc, low, s1->Freq, sum + escFreq); + Ppmd_See_Update(see); + p->FoundState = s1; + Ppmd7_Update2(p); + return; + } + sum += (s->Freq & (int)(MASK(cur))); + MASK(cur) = 0; + s++; + } + while (--i); + + RangeEnc_Encode(rc, sum, escFreq, sum + escFreq); + see->Summ = (UInt16)(see->Summ + sum + escFreq); + } +} + +const IPpmd7 __archive_ppmd7_functions = +{ + &Ppmd7_Construct, + &Ppmd7_Alloc, + &Ppmd7_Free, + &Ppmd7_Init, + &Ppmd7z_RangeDec_CreateVTable, + &PpmdRAR_RangeDec_CreateVTable, + &Ppmd7z_RangeDec_Init, + &PpmdRAR_RangeDec_Init, + &Ppmd7_DecodeSymbol, + &Ppmd7z_RangeEnc_Init, + &Ppmd7z_RangeEnc_FlushData, + &Ppmd7_EncodeSymbol +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd7_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd7_private.h new file mode 100644 index 0000000000..71b954458c --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd7_private.h @@ -0,0 +1,119 @@ +/* Ppmd7.h -- PPMdH compression codec +2010-03-12 : Igor Pavlov : Public domain +This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */ + +/* This code supports virtual RangeDecoder and includes the implementation +of RangeCoder from 7z, instead of RangeCoder from original PPMd var.H. +If you need the compatibility with original PPMd var.H, you can use external RangeDecoder */ + +#ifndef ARCHIVE_PPMD7_PRIVATE_H_INCLUDED +#define ARCHIVE_PPMD7_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +#include "archive_ppmd_private.h" + +#define PPMD7_MIN_ORDER 2 +#define PPMD7_MAX_ORDER 64 + +#define PPMD7_MIN_MEM_SIZE (1 << 11) +#define PPMD7_MAX_MEM_SIZE (0xFFFFFFFFu - 12 * 3) + +struct CPpmd7_Context_; + +typedef + #ifdef PPMD_32BIT + struct CPpmd7_Context_ * + #else + UInt32 + #endif + CPpmd7_Context_Ref; + +typedef struct CPpmd7_Context_ +{ + UInt16 NumStats; + UInt16 SummFreq; + CPpmd_State_Ref Stats; + CPpmd7_Context_Ref Suffix; +} CPpmd7_Context; + +#define Ppmd7Context_OneState(p) ((CPpmd_State *)&(p)->SummFreq) + +typedef struct +{ + CPpmd7_Context *MinContext, *MaxContext; + CPpmd_State *FoundState; + unsigned OrderFall, InitEsc, PrevSuccess, MaxOrder, HiBitsFlag; + Int32 RunLength, InitRL; /* must be 32-bit at least */ + + UInt32 Size; + UInt32 GlueCount; + Byte *Base, *LoUnit, *HiUnit, *Text, *UnitsStart; + UInt32 AlignOffset; + + Byte Indx2Units[PPMD_NUM_INDEXES]; + Byte Units2Indx[128]; + CPpmd_Void_Ref FreeList[PPMD_NUM_INDEXES]; + Byte NS2Indx[256], NS2BSIndx[256], HB2Flag[256]; + CPpmd_See DummySee, See[25][16]; + UInt16 BinSumm[128][64]; +} CPpmd7; + +/* ---------- Decode ---------- */ + +typedef struct +{ + UInt32 (*GetThreshold)(void *p, UInt32 total); + void (*Decode)(void *p, UInt32 start, UInt32 size); + UInt32 (*DecodeBit)(void *p, UInt32 size0); +} IPpmd7_RangeDec; + +typedef struct +{ + IPpmd7_RangeDec p; + UInt32 Range; + UInt32 Code; + UInt32 Low; + UInt32 Bottom; + IByteIn *Stream; +} CPpmd7z_RangeDec; + +/* ---------- Encode ---------- */ + +typedef struct +{ + UInt64 Low; + UInt32 Range; + Byte Cache; + UInt64 CacheSize; + IByteOut *Stream; +} CPpmd7z_RangeEnc; + +typedef struct +{ + /* Base Functions */ + void (*Ppmd7_Construct)(CPpmd7 *p); + Bool (*Ppmd7_Alloc)(CPpmd7 *p, UInt32 size); + void (*Ppmd7_Free)(CPpmd7 *p); + void (*Ppmd7_Init)(CPpmd7 *p, unsigned maxOrder); + #define Ppmd7_WasAllocated(p) ((p)->Base != NULL) + + /* Decode Functions */ + void (*Ppmd7z_RangeDec_CreateVTable)(CPpmd7z_RangeDec *p); + void (*PpmdRAR_RangeDec_CreateVTable)(CPpmd7z_RangeDec *p); + Bool (*Ppmd7z_RangeDec_Init)(CPpmd7z_RangeDec *p); + Bool (*PpmdRAR_RangeDec_Init)(CPpmd7z_RangeDec *p); + #define Ppmd7z_RangeDec_IsFinishedOK(p) ((p)->Code == 0) + int (*Ppmd7_DecodeSymbol)(CPpmd7 *p, IPpmd7_RangeDec *rc); + + /* Encode Functions */ + void (*Ppmd7z_RangeEnc_Init)(CPpmd7z_RangeEnc *p); + void (*Ppmd7z_RangeEnc_FlushData)(CPpmd7z_RangeEnc *p); + + void (*Ppmd7_EncodeSymbol)(CPpmd7 *p, CPpmd7z_RangeEnc *rc, int symbol); +} IPpmd7; + +extern const IPpmd7 __archive_ppmd7_functions; +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd8.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd8.c new file mode 100644 index 0000000000..d1779395da --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd8.c @@ -0,0 +1,1287 @@ +/* Ppmd8.c -- PPMdI codec +2016-05-21 : Igor Pavlov : Public domain +This code is based on PPMd var.I (2002): Dmitry Shkarin : Public domain */ + +#include "archive_platform.h" + +#include <string.h> + +#include "archive_ppmd8_private.h" + +const Byte PPMD8_kExpEscape[16] = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; +static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; + +#define MAX_FREQ 124 +#define UNIT_SIZE 12 + +#define U2B(nu) ((UInt32)(nu) * UNIT_SIZE) +#define U2I(nu) (p->Units2Indx[(nu) - 1]) +#define I2U(indx) (p->Indx2Units[indx]) + +#ifdef PPMD_32BIT + #define REF(ptr) (ptr) +#else + #define REF(ptr) ((UInt32)((Byte *)(ptr) - (p)->Base)) +#endif + +#define STATS_REF(ptr) ((CPpmd_State_Ref)REF(ptr)) + +#define CTX(ref) ((CPpmd8_Context *)Ppmd8_GetContext(p, ref)) +#define STATS(ctx) Ppmd8_GetStats(p, ctx) +#define ONE_STATE(ctx) Ppmd8Context_OneState(ctx) +#define SUFFIX(ctx) CTX((ctx)->Suffix) + +#define kTop (1 << 24) +#define kBot (1 << 15) + +typedef CPpmd8_Context * CTX_PTR; + +struct CPpmd8_Node_; + +typedef + #ifdef PPMD_32BIT + struct CPpmd8_Node_ * + #else + UInt32 + #endif + CPpmd8_Node_Ref; + +typedef struct CPpmd8_Node_ +{ + UInt32 Stamp; + CPpmd8_Node_Ref Next; + UInt32 NU; +} CPpmd8_Node; + +#ifdef PPMD_32BIT + #define NODE(ptr) (ptr) +#else + #define NODE(offs) ((CPpmd8_Node *)(p->Base + (offs))) +#endif + +#define EMPTY_NODE 0xFFFFFFFF + +void Ppmd8_Construct(CPpmd8 *p) +{ + unsigned i, k, m; + + p->Base = 0; + + for (i = 0, k = 0; i < PPMD_NUM_INDEXES; i++) + { + unsigned step = (i >= 12 ? 4 : (i >> 2) + 1); + do { p->Units2Indx[k++] = (Byte)i; } while (--step); + p->Indx2Units[i] = (Byte)k; + } + + p->NS2BSIndx[0] = (0 << 1); + p->NS2BSIndx[1] = (1 << 1); + memset(p->NS2BSIndx + 2, (2 << 1), 9); + memset(p->NS2BSIndx + 11, (3 << 1), 256 - 11); + + for (i = 0; i < 5; i++) + p->NS2Indx[i] = (Byte)i; + for (m = i, k = 1; i < 260; i++) + { + p->NS2Indx[i] = (Byte)m; + if (--k == 0) + k = (++m) - 4; + } +} + +void Ppmd8_Free(CPpmd8 *p) +{ + free(p->Base); + p->Size = 0; + p->Base = 0; +} + +Bool Ppmd8_Alloc(CPpmd8 *p, UInt32 size) +{ + if (p->Base == 0 || p->Size != size) + { + Ppmd8_Free(p); + p->AlignOffset = + #ifdef PPMD_32BIT + (4 - size) & 3; + #else + 4 - (size & 3); + #endif + if ((p->Base = (Byte *)malloc(p->AlignOffset + size)) == 0) + return False; + p->Size = size; + } + return True; +} + +static void InsertNode(CPpmd8 *p, void *node, unsigned indx) +{ + ((CPpmd8_Node *)node)->Stamp = EMPTY_NODE; + ((CPpmd8_Node *)node)->Next = (CPpmd8_Node_Ref)p->FreeList[indx]; + ((CPpmd8_Node *)node)->NU = I2U(indx); + p->FreeList[indx] = REF(node); + p->Stamps[indx]++; +} + +static void *RemoveNode(CPpmd8 *p, unsigned indx) +{ + CPpmd8_Node *node = NODE((CPpmd8_Node_Ref)p->FreeList[indx]); + p->FreeList[indx] = node->Next; + p->Stamps[indx]--; + return node; +} + +static void SplitBlock(CPpmd8 *p, void *ptr, unsigned oldIndx, unsigned newIndx) +{ + unsigned i, nu = I2U(oldIndx) - I2U(newIndx); + ptr = (Byte *)ptr + U2B(I2U(newIndx)); + if (I2U(i = U2I(nu)) != nu) + { + unsigned k = I2U(--i); + InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1); + } + InsertNode(p, ptr, i); +} + +static void GlueFreeBlocks(CPpmd8 *p) +{ + CPpmd8_Node_Ref head = 0; + CPpmd8_Node_Ref *prev = &head; + unsigned i; + + p->GlueCount = 1 << 13; + memset(p->Stamps, 0, sizeof(p->Stamps)); + + /* Order-0 context is always at top UNIT, so we don't need guard NODE at the end. + All blocks up to p->LoUnit can be free, so we need guard NODE at LoUnit. */ + if (p->LoUnit != p->HiUnit) + ((CPpmd8_Node *)p->LoUnit)->Stamp = 0; + + /* Glue free blocks */ + for (i = 0; i < PPMD_NUM_INDEXES; i++) + { + CPpmd8_Node_Ref next = (CPpmd8_Node_Ref)p->FreeList[i]; + p->FreeList[i] = 0; + while (next != 0) + { + CPpmd8_Node *node = NODE(next); + if (node->NU != 0) + { + CPpmd8_Node *node2; + *prev = next; + prev = &(node->Next); + while ((node2 = node + node->NU)->Stamp == EMPTY_NODE) + { + node->NU += node2->NU; + node2->NU = 0; + } + } + next = node->Next; + } + } + *prev = 0; + + /* Fill lists of free blocks */ + while (head != 0) + { + CPpmd8_Node *node = NODE(head); + unsigned nu; + head = node->Next; + nu = node->NU; + if (nu == 0) + continue; + for (; nu > 128; nu -= 128, node += 128) + InsertNode(p, node, PPMD_NUM_INDEXES - 1); + if (I2U(i = U2I(nu)) != nu) + { + unsigned k = I2U(--i); + InsertNode(p, node + k, nu - k - 1); + } + InsertNode(p, node, i); + } +} + +static void *AllocUnitsRare(CPpmd8 *p, unsigned indx) +{ + unsigned i; + void *retVal; + if (p->GlueCount == 0) + { + GlueFreeBlocks(p); + if (p->FreeList[indx] != 0) + return RemoveNode(p, indx); + } + i = indx; + do + { + if (++i == PPMD_NUM_INDEXES) + { + UInt32 numBytes = U2B(I2U(indx)); + p->GlueCount--; + return ((UInt32)(p->UnitsStart - p->Text) > numBytes) ? (p->UnitsStart -= numBytes) : (NULL); + } + } + while (p->FreeList[i] == 0); + retVal = RemoveNode(p, i); + SplitBlock(p, retVal, i, indx); + return retVal; +} + +static void *AllocUnits(CPpmd8 *p, unsigned indx) +{ + UInt32 numBytes; + if (p->FreeList[indx] != 0) + return RemoveNode(p, indx); + numBytes = U2B(I2U(indx)); + if (numBytes <= (UInt32)(p->HiUnit - p->LoUnit)) + { + void *retVal = p->LoUnit; + p->LoUnit += numBytes; + return retVal; + } + return AllocUnitsRare(p, indx); +} + +#define MyMem12Cpy(dest, src, num) \ + { UInt32 *d = (UInt32 *)dest; const UInt32 *z = (const UInt32 *)src; UInt32 n = num; \ + do { d[0] = z[0]; d[1] = z[1]; d[2] = z[2]; z += 3; d += 3; } while (--n); } + +static void *ShrinkUnits(CPpmd8 *p, void *oldPtr, unsigned oldNU, unsigned newNU) +{ + unsigned i0 = U2I(oldNU); + unsigned i1 = U2I(newNU); + if (i0 == i1) + return oldPtr; + if (p->FreeList[i1] != 0) + { + void *ptr = RemoveNode(p, i1); + MyMem12Cpy(ptr, oldPtr, newNU); + InsertNode(p, oldPtr, i0); + return ptr; + } + SplitBlock(p, oldPtr, i0, i1); + return oldPtr; +} + +static void FreeUnits(CPpmd8 *p, void *ptr, unsigned nu) +{ + InsertNode(p, ptr, U2I(nu)); +} + +static void SpecialFreeUnit(CPpmd8 *p, void *ptr) +{ + if ((Byte *)ptr != p->UnitsStart) + InsertNode(p, ptr, 0); + else + { + #ifdef PPMD8_FREEZE_SUPPORT + *(UInt32 *)ptr = EMPTY_NODE; /* it's used for (Flags == 0xFF) check in RemoveBinContexts */ + #endif + p->UnitsStart += UNIT_SIZE; + } +} + +static void *MoveUnitsUp(CPpmd8 *p, void *oldPtr, unsigned nu) +{ + unsigned indx = U2I(nu); + void *ptr; + if ((Byte *)oldPtr > p->UnitsStart + 16 * 1024 || REF(oldPtr) > p->FreeList[indx]) + return oldPtr; + ptr = RemoveNode(p, indx); + MyMem12Cpy(ptr, oldPtr, nu); + if ((Byte*)oldPtr != p->UnitsStart) + InsertNode(p, oldPtr, indx); + else + p->UnitsStart += U2B(I2U(indx)); + return ptr; +} + +static void ExpandTextArea(CPpmd8 *p) +{ + UInt32 count[PPMD_NUM_INDEXES]; + unsigned i; + memset(count, 0, sizeof(count)); + if (p->LoUnit != p->HiUnit) + ((CPpmd8_Node *)p->LoUnit)->Stamp = 0; + + { + CPpmd8_Node *node = (CPpmd8_Node *)p->UnitsStart; + for (; node->Stamp == EMPTY_NODE; node += node->NU) + { + node->Stamp = 0; + count[U2I(node->NU)]++; + } + p->UnitsStart = (Byte *)node; + } + + for (i = 0; i < PPMD_NUM_INDEXES; i++) + { + CPpmd8_Node_Ref *next = (CPpmd8_Node_Ref *)&p->FreeList[i]; + while (count[i] != 0) + { + CPpmd8_Node *node = NODE(*next); + while (node->Stamp == 0) + { + *next = node->Next; + node = NODE(*next); + p->Stamps[i]--; + if (--count[i] == 0) + break; + } + next = &node->Next; + } + } +} + +#define SUCCESSOR(p) ((CPpmd_Void_Ref)((p)->SuccessorLow | ((UInt32)(p)->SuccessorHigh << 16))) + +static void SetSuccessor(CPpmd_State *p, CPpmd_Void_Ref v) +{ + (p)->SuccessorLow = (UInt16)((UInt32)(v) & 0xFFFF); + (p)->SuccessorHigh = (UInt16)(((UInt32)(v) >> 16) & 0xFFFF); +} + +#define RESET_TEXT(offs) { p->Text = p->Base + p->AlignOffset + (offs); } + +static void RestartModel(CPpmd8 *p) +{ + unsigned i, k, m, r; + + memset(p->FreeList, 0, sizeof(p->FreeList)); + memset(p->Stamps, 0, sizeof(p->Stamps)); + RESET_TEXT(0); + p->HiUnit = p->Text + p->Size; + p->LoUnit = p->UnitsStart = p->HiUnit - p->Size / 8 / UNIT_SIZE * 7 * UNIT_SIZE; + p->GlueCount = 0; + + p->OrderFall = p->MaxOrder; + p->RunLength = p->InitRL = -(Int32)((p->MaxOrder < 12) ? p->MaxOrder : 12) - 1; + p->PrevSuccess = 0; + + p->MinContext = p->MaxContext = (CTX_PTR)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */ + p->MinContext->Suffix = 0; + p->MinContext->NumStats = 255; + p->MinContext->Flags = 0; + p->MinContext->SummFreq = 256 + 1; + p->FoundState = (CPpmd_State *)p->LoUnit; /* AllocUnits(p, PPMD_NUM_INDEXES - 1); */ + p->LoUnit += U2B(256 / 2); + p->MinContext->Stats = REF(p->FoundState); + for (i = 0; i < 256; i++) + { + CPpmd_State *s = &p->FoundState[i]; + s->Symbol = (Byte)i; + s->Freq = 1; + SetSuccessor(s, 0); + } + + for (i = m = 0; m < 25; m++) + { + while (p->NS2Indx[i] == m) + i++; + for (k = 0; k < 8; k++) + { + UInt16 val = (UInt16)(PPMD_BIN_SCALE - kInitBinEsc[k] / (i + 1)); + UInt16 *dest = p->BinSumm[m] + k; + for (r = 0; r < 64; r += 8) + dest[r] = val; + } + } + + for (i = m = 0; m < 24; m++) + { + while (p->NS2Indx[i + 3] == m + 3) + i++; + for (k = 0; k < 32; k++) + { + CPpmd_See *s = &p->See[m][k]; + s->Summ = (UInt16)((2 * i + 5) << (s->Shift = PPMD_PERIOD_BITS - 4)); + s->Count = 7; + } + } +} + +void Ppmd8_Init(CPpmd8 *p, unsigned maxOrder, unsigned restoreMethod) +{ + p->MaxOrder = maxOrder; + p->RestoreMethod = restoreMethod; + RestartModel(p); + p->DummySee.Shift = PPMD_PERIOD_BITS; + p->DummySee.Summ = 0; /* unused */ + p->DummySee.Count = 64; /* unused */ +} + +static void Refresh(CPpmd8 *p, CTX_PTR ctx, unsigned oldNU, unsigned scale) +{ + unsigned i = ctx->NumStats, escFreq, sumFreq, flags; + CPpmd_State *s = (CPpmd_State *)ShrinkUnits(p, STATS(ctx), oldNU, (i + 2) >> 1); + ctx->Stats = REF(s); + #ifdef PPMD8_FREEZE_SUPPORT + /* fixed over Shkarin's code. Fixed code is not compatible with original code for some files in FREEZE mode. */ + scale |= (ctx->SummFreq >= ((UInt32)1 << 15)); + #endif + flags = (ctx->Flags & (0x10 + 0x04 * scale)) + 0x08 * (s->Symbol >= 0x40); + escFreq = ctx->SummFreq - s->Freq; + sumFreq = (s->Freq = (Byte)((s->Freq + scale) >> scale)); + do + { + escFreq -= (++s)->Freq; + sumFreq += (s->Freq = (Byte)((s->Freq + scale) >> scale)); + flags |= 0x08 * (s->Symbol >= 0x40); + } + while (--i); + ctx->SummFreq = (UInt16)(sumFreq + ((escFreq + scale) >> scale)); + ctx->Flags = (Byte)flags; +} + +static void SwapStates(CPpmd_State *t1, CPpmd_State *t2) +{ + CPpmd_State tmp = *t1; + *t1 = *t2; + *t2 = tmp; +} + +static CPpmd_Void_Ref CutOff(CPpmd8 *p, CTX_PTR ctx, unsigned order) +{ + int i; + unsigned tmp; + CPpmd_State *s; + + if (!ctx->NumStats) + { + s = ONE_STATE(ctx); + if ((Byte *)Ppmd8_GetPtr(p, SUCCESSOR(s)) >= p->UnitsStart) + { + if (order < p->MaxOrder) + SetSuccessor(s, CutOff(p, CTX(SUCCESSOR(s)), order + 1)); + else + SetSuccessor(s, 0); + if (SUCCESSOR(s) || order <= 9) /* O_BOUND */ + return REF(ctx); + } + SpecialFreeUnit(p, ctx); + return 0; + } + + ctx->Stats = STATS_REF(MoveUnitsUp(p, STATS(ctx), tmp = ((unsigned)ctx->NumStats + 2) >> 1)); + + for (s = STATS(ctx) + (i = ctx->NumStats); s >= STATS(ctx); s--) + if ((Byte *)Ppmd8_GetPtr(p, SUCCESSOR(s)) < p->UnitsStart) + { + CPpmd_State *s2 = STATS(ctx) + (i--); + SetSuccessor(s, 0); + SwapStates(s, s2); + } + else if (order < p->MaxOrder) + SetSuccessor(s, CutOff(p, CTX(SUCCESSOR(s)), order + 1)); + else + SetSuccessor(s, 0); + + if (i != ctx->NumStats && order) + { + ctx->NumStats = (Byte)i; + s = STATS(ctx); + if (i < 0) + { + FreeUnits(p, s, tmp); + SpecialFreeUnit(p, ctx); + return 0; + } + if (i == 0) + { + ctx->Flags = (Byte)((ctx->Flags & 0x10) + 0x08 * (s->Symbol >= 0x40)); + *ONE_STATE(ctx) = *s; + FreeUnits(p, s, tmp); + /* 9.31: the code was fixed. It's was not BUG, if Freq <= MAX_FREQ = 124 */ + ONE_STATE(ctx)->Freq = (Byte)(((unsigned)ONE_STATE(ctx)->Freq + 11) >> 3); + } + else + Refresh(p, ctx, tmp, ctx->SummFreq > 16 * i); + } + return REF(ctx); +} + +#ifdef PPMD8_FREEZE_SUPPORT +static CPpmd_Void_Ref RemoveBinContexts(CPpmd8 *p, CTX_PTR ctx, unsigned order) +{ + CPpmd_State *s; + if (!ctx->NumStats) + { + s = ONE_STATE(ctx); + if ((Byte *)Ppmd8_GetPtr(p, SUCCESSOR(s)) >= p->UnitsStart && order < p->MaxOrder) + SetSuccessor(s, RemoveBinContexts(p, CTX(SUCCESSOR(s)), order + 1)); + else + SetSuccessor(s, 0); + /* Suffix context can be removed already, since different (high-order) + Successors may refer to same context. So we check Flags == 0xFF (Stamp == EMPTY_NODE) */ + if (!SUCCESSOR(s) && (!SUFFIX(ctx)->NumStats || SUFFIX(ctx)->Flags == 0xFF)) + { + FreeUnits(p, ctx, 1); + return 0; + } + else + return REF(ctx); + } + + for (s = STATS(ctx) + ctx->NumStats; s >= STATS(ctx); s--) + if ((Byte *)Ppmd8_GetPtr(p, SUCCESSOR(s)) >= p->UnitsStart && order < p->MaxOrder) + SetSuccessor(s, RemoveBinContexts(p, CTX(SUCCESSOR(s)), order + 1)); + else + SetSuccessor(s, 0); + + return REF(ctx); +} +#endif + +static UInt32 GetUsedMemory(const CPpmd8 *p) +{ + UInt32 v = 0; + unsigned i; + for (i = 0; i < PPMD_NUM_INDEXES; i++) + v += p->Stamps[i] * I2U(i); + return p->Size - (UInt32)(p->HiUnit - p->LoUnit) - (UInt32)(p->UnitsStart - p->Text) - U2B(v); +} + +#ifdef PPMD8_FREEZE_SUPPORT + #define RESTORE_MODEL(c1, fSuccessor) RestoreModel(p, c1, fSuccessor) +#else + #define RESTORE_MODEL(c1, fSuccessor) RestoreModel(p, c1) +#endif + +static void RestoreModel(CPpmd8 *p, CTX_PTR c1 + #ifdef PPMD8_FREEZE_SUPPORT + , CTX_PTR fSuccessor + #endif + ) +{ + CTX_PTR c; + CPpmd_State *s; + RESET_TEXT(0); + for (c = p->MaxContext; c != c1; c = SUFFIX(c)) + if (--(c->NumStats) == 0) + { + s = STATS(c); + c->Flags = (Byte)((c->Flags & 0x10) + 0x08 * (s->Symbol >= 0x40)); + *ONE_STATE(c) = *s; + SpecialFreeUnit(p, s); + ONE_STATE(c)->Freq = (Byte)(((unsigned)ONE_STATE(c)->Freq + 11) >> 3); + } + else + Refresh(p, c, (c->NumStats+3) >> 1, 0); + + for (; c != p->MinContext; c = SUFFIX(c)) + if (!c->NumStats) + ONE_STATE(c)->Freq = (Byte)(ONE_STATE(c)->Freq - (ONE_STATE(c)->Freq >> 1)); + else if ((c->SummFreq += 4) > 128 + 4 * c->NumStats) + Refresh(p, c, (c->NumStats + 2) >> 1, 1); + + #ifdef PPMD8_FREEZE_SUPPORT + if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE) + { + p->MaxContext = fSuccessor; + p->GlueCount += !(p->Stamps[1] & 1); + } + else if (p->RestoreMethod == PPMD8_RESTORE_METHOD_FREEZE) + { + while (p->MaxContext->Suffix) + p->MaxContext = SUFFIX(p->MaxContext); + RemoveBinContexts(p, p->MaxContext, 0); + p->RestoreMethod++; + p->GlueCount = 0; + p->OrderFall = p->MaxOrder; + } + else + #endif + if (p->RestoreMethod == PPMD8_RESTORE_METHOD_RESTART || GetUsedMemory(p) < (p->Size >> 1)) + RestartModel(p); + else + { + while (p->MaxContext->Suffix) + p->MaxContext = SUFFIX(p->MaxContext); + do + { + CutOff(p, p->MaxContext, 0); + ExpandTextArea(p); + } + while (GetUsedMemory(p) > 3 * (p->Size >> 2)); + p->GlueCount = 0; + p->OrderFall = p->MaxOrder; + } +} + +static CTX_PTR CreateSuccessors(CPpmd8 *p, Bool skip, CPpmd_State *s1, CTX_PTR c) +{ + CPpmd_State upState; + Byte flags; + CPpmd_Byte_Ref upBranch = (CPpmd_Byte_Ref)SUCCESSOR(p->FoundState); + /* fixed over Shkarin's code. Maybe it could work without + 1 too. */ + CPpmd_State *ps[PPMD8_MAX_ORDER + 1]; + unsigned numPs = 0; + + if (!skip) + ps[numPs++] = p->FoundState; + + while (c->Suffix) + { + CPpmd_Void_Ref successor; + CPpmd_State *s; + c = SUFFIX(c); + if (s1) + { + s = s1; + s1 = NULL; + } + else if (c->NumStats != 0) + { + for (s = STATS(c); s->Symbol != p->FoundState->Symbol; s++); + if (s->Freq < MAX_FREQ - 9) + { + s->Freq++; + c->SummFreq++; + } + } + else + { + s = ONE_STATE(c); + s->Freq = (Byte)(s->Freq + (!SUFFIX(c)->NumStats & (s->Freq < 24))); + } + successor = SUCCESSOR(s); + if (successor != upBranch) + { + c = CTX(successor); + if (numPs == 0) + return c; + break; + } + ps[numPs++] = s; + } + + upState.Symbol = *(const Byte *)Ppmd8_GetPtr(p, upBranch); + SetSuccessor(&upState, upBranch + 1); + flags = (Byte)(0x10 * (p->FoundState->Symbol >= 0x40) + 0x08 * (upState.Symbol >= 0x40)); + + if (c->NumStats == 0) + upState.Freq = ONE_STATE(c)->Freq; + else + { + UInt32 cf, s0; + CPpmd_State *s; + for (s = STATS(c); s->Symbol != upState.Symbol; s++); + cf = s->Freq - 1; + s0 = c->SummFreq - c->NumStats - cf; + upState.Freq = (Byte)(1 + ((2 * cf <= s0) ? (5 * cf > s0) : ((cf + 2 * s0 - 3) / s0))); + } + + do + { + /* Create Child */ + CTX_PTR c1; /* = AllocContext(p); */ + if (p->HiUnit != p->LoUnit) + c1 = (CTX_PTR)(p->HiUnit -= UNIT_SIZE); + else if (p->FreeList[0] != 0) + c1 = (CTX_PTR)RemoveNode(p, 0); + else + { + c1 = (CTX_PTR)AllocUnitsRare(p, 0); + if (!c1) + return NULL; + } + c1->NumStats = 0; + c1->Flags = flags; + *ONE_STATE(c1) = upState; + c1->Suffix = REF(c); + SetSuccessor(ps[--numPs], REF(c1)); + c = c1; + } + while (numPs != 0); + + return c; +} + +static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c) +{ + CPpmd_State *s = NULL; + CTX_PTR c1 = c; + CPpmd_Void_Ref upBranch = REF(p->Text); + + #ifdef PPMD8_FREEZE_SUPPORT + /* The BUG in Shkarin's code was fixed: ps could overflow in CUT_OFF mode. */ + CPpmd_State *ps[PPMD8_MAX_ORDER + 1]; + unsigned numPs = 0; + ps[numPs++] = p->FoundState; + #endif + + SetSuccessor(p->FoundState, upBranch); + p->OrderFall++; + + for (;;) + { + if (s1) + { + c = SUFFIX(c); + s = s1; + s1 = NULL; + } + else + { + if (!c->Suffix) + { + #ifdef PPMD8_FREEZE_SUPPORT + if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE) + { + do { SetSuccessor(ps[--numPs], REF(c)); } while (numPs); + RESET_TEXT(1); + p->OrderFall = 1; + } + #endif + return c; + } + c = SUFFIX(c); + if (c->NumStats) + { + if ((s = STATS(c))->Symbol != p->FoundState->Symbol) + do { s++; } while (s->Symbol != p->FoundState->Symbol); + if (s->Freq < MAX_FREQ - 9) + { + s->Freq += 2; + c->SummFreq += 2; + } + } + else + { + s = ONE_STATE(c); + s->Freq = (Byte)(s->Freq + (s->Freq < 32)); + } + } + if (SUCCESSOR(s)) + break; + #ifdef PPMD8_FREEZE_SUPPORT + ps[numPs++] = s; + #endif + SetSuccessor(s, upBranch); + p->OrderFall++; + } + + #ifdef PPMD8_FREEZE_SUPPORT + if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE) + { + c = CTX(SUCCESSOR(s)); + do { SetSuccessor(ps[--numPs], REF(c)); } while (numPs); + RESET_TEXT(1); + p->OrderFall = 1; + return c; + } + else + #endif + if (SUCCESSOR(s) <= upBranch) + { + CTX_PTR successor; + CPpmd_State *s2 = p->FoundState; + p->FoundState = s; + + successor = CreateSuccessors(p, False, NULL, c); + if (successor == NULL) + SetSuccessor(s, 0); + else + SetSuccessor(s, REF(successor)); + p->FoundState = s2; + } + + if (p->OrderFall == 1 && c1 == p->MaxContext) + { + SetSuccessor(p->FoundState, SUCCESSOR(s)); + p->Text--; + } + if (SUCCESSOR(s) == 0) + return NULL; + return CTX(SUCCESSOR(s)); +} + +static void UpdateModel(CPpmd8 *p) +{ + CPpmd_Void_Ref successor, fSuccessor = SUCCESSOR(p->FoundState); + CTX_PTR c; + unsigned s0, ns, fFreq = p->FoundState->Freq; + Byte flag, fSymbol = p->FoundState->Symbol; + CPpmd_State *s = NULL; + + if (p->FoundState->Freq < MAX_FREQ / 4 && p->MinContext->Suffix != 0) + { + c = SUFFIX(p->MinContext); + + if (c->NumStats == 0) + { + s = ONE_STATE(c); + if (s->Freq < 32) + s->Freq++; + } + else + { + s = STATS(c); + if (s->Symbol != p->FoundState->Symbol) + { + do { s++; } while (s->Symbol != p->FoundState->Symbol); + if (s[0].Freq >= s[-1].Freq) + { + SwapStates(&s[0], &s[-1]); + s--; + } + } + if (s->Freq < MAX_FREQ - 9) + { + s->Freq += 2; + c->SummFreq += 2; + } + } + } + + c = p->MaxContext; + if (p->OrderFall == 0 && fSuccessor) + { + CTX_PTR cs = CreateSuccessors(p, True, s, p->MinContext); + if (cs == 0) + { + SetSuccessor(p->FoundState, 0); + RESTORE_MODEL(c, CTX(fSuccessor)); + } + else + { + SetSuccessor(p->FoundState, REF(cs)); + p->MaxContext = cs; + } + return; + } + + *p->Text++ = p->FoundState->Symbol; + successor = REF(p->Text); + if (p->Text >= p->UnitsStart) + { + RESTORE_MODEL(c, CTX(fSuccessor)); /* check it */ + return; + } + + if (!fSuccessor) + { + CTX_PTR cs = ReduceOrder(p, s, p->MinContext); + if (cs == NULL) + { + RESTORE_MODEL(c, 0); + return; + } + fSuccessor = REF(cs); + } + else if ((Byte *)Ppmd8_GetPtr(p, fSuccessor) < p->UnitsStart) + { + CTX_PTR cs = CreateSuccessors(p, False, s, p->MinContext); + if (cs == NULL) + { + RESTORE_MODEL(c, 0); + return; + } + fSuccessor = REF(cs); + } + + if (--p->OrderFall == 0) + { + successor = fSuccessor; + p->Text -= (p->MaxContext != p->MinContext); + } + #ifdef PPMD8_FREEZE_SUPPORT + else if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE) + { + successor = fSuccessor; + RESET_TEXT(0); + p->OrderFall = 0; + } + #endif + + s0 = p->MinContext->SummFreq - (ns = p->MinContext->NumStats) - fFreq; + flag = (Byte)(0x08 * (fSymbol >= 0x40)); + + for (; c != p->MinContext; c = SUFFIX(c)) + { + unsigned ns1; + UInt32 cf, sf; + if ((ns1 = c->NumStats) != 0) + { + if ((ns1 & 1) != 0) + { + /* Expand for one UNIT */ + unsigned oldNU = (ns1 + 1) >> 1; + unsigned i = U2I(oldNU); + if (i != U2I(oldNU + 1)) + { + void *ptr = AllocUnits(p, i + 1); + void *oldPtr; + if (!ptr) + { + RESTORE_MODEL(c, CTX(fSuccessor)); + return; + } + oldPtr = STATS(c); + MyMem12Cpy(ptr, oldPtr, oldNU); + InsertNode(p, oldPtr, i); + c->Stats = STATS_REF(ptr); + } + } + c->SummFreq = (UInt16)(c->SummFreq + (3 * ns1 + 1 < ns)); + } + else + { + CPpmd_State *s2 = (CPpmd_State*)AllocUnits(p, 0); + if (!s2) + { + RESTORE_MODEL(c, CTX(fSuccessor)); + return; + } + *s2 = *ONE_STATE(c); + c->Stats = REF(s2); + if (s2->Freq < MAX_FREQ / 4 - 1) + s2->Freq <<= 1; + else + s2->Freq = MAX_FREQ - 4; + c->SummFreq = (UInt16)(s2->Freq + p->InitEsc + (ns > 2)); + } + cf = 2 * fFreq * (c->SummFreq + 6); + sf = (UInt32)s0 + c->SummFreq; + if (cf < 6 * sf) + { + cf = 1 + (cf > sf) + (cf >= 4 * sf); + c->SummFreq += 4; + } + else + { + cf = 4 + (cf > 9 * sf) + (cf > 12 * sf) + (cf > 15 * sf); + c->SummFreq = (UInt16)(c->SummFreq + cf); + } + { + CPpmd_State *s2 = STATS(c) + ns1 + 1; + SetSuccessor(s2, successor); + s2->Symbol = fSymbol; + s2->Freq = (Byte)cf; + c->Flags |= flag; + c->NumStats = (Byte)(ns1 + 1); + } + } + p->MaxContext = p->MinContext = CTX(fSuccessor); +} + +static void Rescale(CPpmd8 *p) +{ + unsigned i, adder, sumFreq, escFreq; + CPpmd_State *stats = STATS(p->MinContext); + CPpmd_State *s = p->FoundState; + { + CPpmd_State tmp = *s; + for (; s != stats; s--) + s[0] = s[-1]; + *s = tmp; + } + escFreq = p->MinContext->SummFreq - s->Freq; + s->Freq += 4; + adder = (p->OrderFall != 0 + #ifdef PPMD8_FREEZE_SUPPORT + || p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE + #endif + ); + s->Freq = (Byte)((s->Freq + adder) >> 1); + sumFreq = s->Freq; + + i = p->MinContext->NumStats; + do + { + escFreq -= (++s)->Freq; + s->Freq = (Byte)((s->Freq + adder) >> 1); + sumFreq += s->Freq; + if (s[0].Freq > s[-1].Freq) + { + CPpmd_State *s1 = s; + CPpmd_State tmp = *s1; + do + s1[0] = s1[-1]; + while (--s1 != stats && tmp.Freq > s1[-1].Freq); + *s1 = tmp; + } + } + while (--i); + + if (s->Freq == 0) + { + unsigned numStats = p->MinContext->NumStats; + unsigned n0, n1; + do { i++; } while ((--s)->Freq == 0); + escFreq += i; + p->MinContext->NumStats = (Byte)(p->MinContext->NumStats - i); + if (p->MinContext->NumStats == 0) + { + CPpmd_State tmp = *stats; + tmp.Freq = (Byte)((2 * tmp.Freq + escFreq - 1) / escFreq); + if (tmp.Freq > MAX_FREQ / 3) + tmp.Freq = MAX_FREQ / 3; + InsertNode(p, stats, U2I((numStats + 2) >> 1)); + p->MinContext->Flags = (Byte)((p->MinContext->Flags & 0x10) + 0x08 * (tmp.Symbol >= 0x40)); + *(p->FoundState = ONE_STATE(p->MinContext)) = tmp; + return; + } + n0 = (numStats + 2) >> 1; + n1 = (p->MinContext->NumStats + 2) >> 1; + if (n0 != n1) + p->MinContext->Stats = STATS_REF(ShrinkUnits(p, stats, n0, n1)); + p->MinContext->Flags &= ~0x08; + p->MinContext->Flags |= 0x08 * ((s = STATS(p->MinContext))->Symbol >= 0x40); + i = p->MinContext->NumStats; + do { p->MinContext->Flags |= 0x08*((++s)->Symbol >= 0x40); } while (--i); + } + p->MinContext->SummFreq = (UInt16)(sumFreq + escFreq - (escFreq >> 1)); + p->MinContext->Flags |= 0x4; + p->FoundState = STATS(p->MinContext); +} + +CPpmd_See *Ppmd8_MakeEscFreq(CPpmd8 *p, unsigned numMasked1, UInt32 *escFreq) +{ + CPpmd_See *see; + if (p->MinContext->NumStats != 0xFF) + { + see = p->See[(unsigned)p->NS2Indx[(unsigned)p->MinContext->NumStats + 2] - 3] + + (p->MinContext->SummFreq > 11 * ((unsigned)p->MinContext->NumStats + 1)) + + 2 * (unsigned)(2 * (unsigned)p->MinContext->NumStats < + ((unsigned)SUFFIX(p->MinContext)->NumStats + numMasked1)) + + p->MinContext->Flags; + { + unsigned r = (see->Summ >> see->Shift); + see->Summ = (UInt16)(see->Summ - r); + *escFreq = r + (r == 0); + } + } + else + { + see = &p->DummySee; + *escFreq = 1; + } + return see; +} + +static void NextContext(CPpmd8 *p) +{ + CTX_PTR c = CTX(SUCCESSOR(p->FoundState)); + if (p->OrderFall == 0 && (Byte *)c >= p->UnitsStart) + p->MinContext = p->MaxContext = c; + else + { + UpdateModel(p); + p->MinContext = p->MaxContext; + } +} + +void Ppmd8_Update1(CPpmd8 *p) +{ + CPpmd_State *s = p->FoundState; + s->Freq += 4; + p->MinContext->SummFreq += 4; + if (s[0].Freq > s[-1].Freq) + { + SwapStates(&s[0], &s[-1]); + p->FoundState = --s; + if (s->Freq > MAX_FREQ) + Rescale(p); + } + NextContext(p); +} + +void Ppmd8_Update1_0(CPpmd8 *p) +{ + p->PrevSuccess = (2 * p->FoundState->Freq >= p->MinContext->SummFreq); + p->RunLength += p->PrevSuccess; + p->MinContext->SummFreq += 4; + if ((p->FoundState->Freq += 4) > MAX_FREQ) + Rescale(p); + NextContext(p); +} + +void Ppmd8_UpdateBin(CPpmd8 *p) +{ + p->FoundState->Freq = (Byte)(p->FoundState->Freq + (p->FoundState->Freq < 196)); + p->PrevSuccess = 1; + p->RunLength++; + NextContext(p); +} + +void Ppmd8_Update2(CPpmd8 *p) +{ + p->MinContext->SummFreq += 4; + if ((p->FoundState->Freq += 4) > MAX_FREQ) + Rescale(p); + p->RunLength = p->InitRL; + UpdateModel(p); + p->MinContext = p->MaxContext; +} + +/* Ppmd8Dec.c -- PPMdI Decoder +2010-04-16 : Igor Pavlov : Public domain +This code is based on: + PPMd var.I (2002): Dmitry Shkarin : Public domain + Carryless rangecoder (1999): Dmitry Subbotin : Public domain */ + +Bool Ppmd8_RangeDec_Init(CPpmd8 *p) +{ + unsigned i; + p->Low = 0; + p->Range = 0xFFFFFFFF; + p->Code = 0; + for (i = 0; i < 4; i++) + p->Code = (p->Code << 8) | p->Stream.In->Read(p->Stream.In); + return (p->Code < 0xFFFFFFFF); +} + +static UInt32 RangeDec_GetThreshold(CPpmd8 *p, UInt32 total) +{ + return p->Code / (p->Range /= total); +} + +static void RangeDec_Decode(CPpmd8 *p, UInt32 start, UInt32 size) +{ + start *= p->Range; + p->Low += start; + p->Code -= start; + p->Range *= size; + + while ((p->Low ^ (p->Low + p->Range)) < kTop || + (p->Range < kBot && ((p->Range = (0 - p->Low) & (kBot - 1)), 1))) + { + p->Code = (p->Code << 8) | p->Stream.In->Read(p->Stream.In); + p->Range <<= 8; + p->Low <<= 8; + } +} + +#define MASK(sym) ((signed char *)charMask)[sym] + +int Ppmd8_DecodeSymbol(CPpmd8 *p) +{ + size_t charMask[256 / sizeof(size_t)]; + if (p->MinContext->NumStats != 0) + { + CPpmd_State *s = Ppmd8_GetStats(p, p->MinContext); + unsigned i; + UInt32 count, hiCnt; + if ((count = RangeDec_GetThreshold(p, p->MinContext->SummFreq)) < (hiCnt = s->Freq)) + { + Byte symbol; + RangeDec_Decode(p, 0, s->Freq); + p->FoundState = s; + symbol = s->Symbol; + Ppmd8_Update1_0(p); + return symbol; + } + p->PrevSuccess = 0; + i = p->MinContext->NumStats; + do + { + if ((hiCnt += (++s)->Freq) > count) + { + Byte symbol; + RangeDec_Decode(p, hiCnt - s->Freq, s->Freq); + p->FoundState = s; + symbol = s->Symbol; + Ppmd8_Update1(p); + return symbol; + } + } + while (--i); + if (count >= p->MinContext->SummFreq) + return -2; + RangeDec_Decode(p, hiCnt, p->MinContext->SummFreq - hiCnt); + PPMD_SetAllBitsIn256Bytes(charMask); + MASK(s->Symbol) = 0; + i = p->MinContext->NumStats; + do { MASK((--s)->Symbol) = 0; } while (--i); + } + else + { + UInt16 *prob = Ppmd8_GetBinSumm(p); + if (((p->Code / (p->Range >>= 14)) < *prob)) + { + Byte symbol; + RangeDec_Decode(p, 0, *prob); + *prob = (UInt16)PPMD_UPDATE_PROB_0(*prob); + symbol = (p->FoundState = Ppmd8Context_OneState(p->MinContext))->Symbol; + Ppmd8_UpdateBin(p); + return symbol; + } + RangeDec_Decode(p, *prob, (1 << 14) - *prob); + *prob = (UInt16)PPMD_UPDATE_PROB_1(*prob); + p->InitEsc = PPMD8_kExpEscape[*prob >> 10]; + PPMD_SetAllBitsIn256Bytes(charMask); + MASK(Ppmd8Context_OneState(p->MinContext)->Symbol) = 0; + p->PrevSuccess = 0; + } + for (;;) + { + CPpmd_State *ps[256], *s; + UInt32 freqSum, count, hiCnt; + CPpmd_See *see; + unsigned i, num, numMasked = p->MinContext->NumStats; + do + { + p->OrderFall++; + if (!p->MinContext->Suffix) + return -1; + p->MinContext = Ppmd8_GetContext(p, p->MinContext->Suffix); + } + while (p->MinContext->NumStats == numMasked); + hiCnt = 0; + s = Ppmd8_GetStats(p, p->MinContext); + i = 0; + num = p->MinContext->NumStats - numMasked; + do + { + int k = (int)(MASK(s->Symbol)); + hiCnt += (s->Freq & k); + ps[i] = s++; + i -= k; + } + while (i != num); + + see = Ppmd8_MakeEscFreq(p, numMasked, &freqSum); + freqSum += hiCnt; + count = RangeDec_GetThreshold(p, freqSum); + + if (count < hiCnt) + { + Byte symbol; + CPpmd_State **pps = ps; + for (hiCnt = 0; (hiCnt += (*pps)->Freq) <= count; pps++); + s = *pps; + RangeDec_Decode(p, hiCnt - s->Freq, s->Freq); + Ppmd_See_Update(see); + p->FoundState = s; + symbol = s->Symbol; + Ppmd8_Update2(p); + return symbol; + } + if (count >= freqSum) + return -2; + RangeDec_Decode(p, hiCnt, freqSum - hiCnt); + see->Summ = (UInt16)(see->Summ + freqSum); + do { MASK(ps[--i]->Symbol) = 0; } while (i != 0); + } +} + +/* H->I changes: + NS2Indx + GlewCount, and Glue method + BinSum + See / EscFreq + CreateSuccessors updates more suffix contexts + UpdateModel consts. + PrevSuccess Update +*/ + +const IPpmd8 __archive_ppmd8_functions = +{ + &Ppmd8_Construct, + &Ppmd8_Alloc, + &Ppmd8_Free, + &Ppmd8_Init, + &Ppmd8_RangeDec_Init, + &Ppmd8_DecodeSymbol, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd8_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd8_private.h new file mode 100644 index 0000000000..454b75f41f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd8_private.h @@ -0,0 +1,148 @@ +/* Ppmd8.h -- PPMdI codec +2011-01-27 : Igor Pavlov : Public domain +This code is based on: + PPMd var.I (2002): Dmitry Shkarin : Public domain + Carryless rangecoder (1999): Dmitry Subbotin : Public domain */ + +#ifndef ARCHIVE_PPMD8_PRIVATE_H_INCLUDED +#define ARCHIVE_PPMD8_PRIVATE_H_INCLUDED + +#include "archive_ppmd_private.h" + +#define PPMD8_MIN_ORDER 2 +#define PPMD8_MAX_ORDER 16 + +struct CPpmd8_Context_; + +typedef + #ifdef PPMD_32BIT + struct CPpmd8_Context_ * + #else + UInt32 + #endif + CPpmd8_Context_Ref; + +#pragma pack(push, 1) + +typedef struct CPpmd8_Context_ +{ + Byte NumStats; + Byte Flags; + UInt16 SummFreq; + CPpmd_State_Ref Stats; + CPpmd8_Context_Ref Suffix; +} CPpmd8_Context; + +#pragma pack(pop) + +#define Ppmd8Context_OneState(p) ((CPpmd_State *)&(p)->SummFreq) + +/* The BUG in Shkarin's code for FREEZE mode was fixed, but that fixed + code is not compatible with original code for some files compressed + in FREEZE mode. So we disable FREEZE mode support. */ + +enum +{ + PPMD8_RESTORE_METHOD_RESTART, + PPMD8_RESTORE_METHOD_CUT_OFF + #ifdef PPMD8_FREEZE_SUPPORT + , PPMD8_RESTORE_METHOD_FREEZE + #endif +}; + +typedef struct +{ + CPpmd8_Context *MinContext, *MaxContext; + CPpmd_State *FoundState; + unsigned OrderFall, InitEsc, PrevSuccess, MaxOrder; + Int32 RunLength, InitRL; /* must be 32-bit at least */ + + UInt32 Size; + UInt32 GlueCount; + Byte *Base, *LoUnit, *HiUnit, *Text, *UnitsStart; + UInt32 AlignOffset; + unsigned RestoreMethod; + + /* Range Coder */ + UInt32 Range; + UInt32 Code; + UInt32 Low; + union + { + IByteIn *In; + IByteOut *Out; + } Stream; + + Byte Indx2Units[PPMD_NUM_INDEXES]; + Byte Units2Indx[128]; + CPpmd_Void_Ref FreeList[PPMD_NUM_INDEXES]; + UInt32 Stamps[PPMD_NUM_INDEXES]; + + Byte NS2BSIndx[256], NS2Indx[260]; + CPpmd_See DummySee, See[24][32]; + UInt16 BinSumm[25][64]; +} CPpmd8; + +void Ppmd8_Construct(CPpmd8 *p); +Bool Ppmd8_Alloc(CPpmd8 *p, UInt32 size); +void Ppmd8_Free(CPpmd8 *p); +void Ppmd8_Init(CPpmd8 *p, unsigned maxOrder, unsigned restoreMethod); +#define Ppmd8_WasAllocated(p) ((p)->Base != NULL) + + +/* ---------- Internal Functions ---------- */ + +extern const Byte PPMD8_kExpEscape[16]; + +#ifdef PPMD_32BIT + #define Ppmd8_GetPtr(p, ptr) (ptr) + #define Ppmd8_GetContext(p, ptr) (ptr) + #define Ppmd8_GetStats(p, ctx) ((ctx)->Stats) +#else + #define Ppmd8_GetPtr(p, offs) ((void *)((p)->Base + (offs))) + #define Ppmd8_GetContext(p, offs) ((CPpmd8_Context *)Ppmd8_GetPtr((p), (offs))) + #define Ppmd8_GetStats(p, ctx) ((CPpmd_State *)Ppmd8_GetPtr((p), ((ctx)->Stats))) +#endif + +void Ppmd8_Update1(CPpmd8 *p); +void Ppmd8_Update1_0(CPpmd8 *p); +void Ppmd8_Update2(CPpmd8 *p); +void Ppmd8_UpdateBin(CPpmd8 *p); + +#define Ppmd8_GetBinSumm(p) \ + &p->BinSumm[p->NS2Indx[Ppmd8Context_OneState(p->MinContext)->Freq - 1]][ \ + p->NS2BSIndx[Ppmd8_GetContext(p, p->MinContext->Suffix)->NumStats] + \ + p->PrevSuccess + p->MinContext->Flags + ((p->RunLength >> 26) & 0x20)] + +CPpmd_See *Ppmd8_MakeEscFreq(CPpmd8 *p, unsigned numMasked, UInt32 *scale); + + +/* ---------- Decode ---------- */ + +Bool Ppmd8_RangeDec_Init(CPpmd8 *p); +#define Ppmd8_RangeDec_IsFinishedOK(p) ((p)->Code == 0) +int Ppmd8_DecodeSymbol(CPpmd8 *p); /* returns: -1 as EndMarker, -2 as DataError */ + +/* ---------- Encode ---------- */ + +#define Ppmd8_RangeEnc_Init(p) { (p)->Low = 0; (p)->Range = 0xFFFFFFFF; } +void Ppmd8_RangeEnc_FlushData(CPpmd8 *p); +void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol); /* symbol = -1 means EndMarker */ + +typedef struct +{ + /* Base Functions */ + void (*Ppmd8_Construct)(CPpmd8 *p); + Bool (*Ppmd8_Alloc)(CPpmd8 *p, UInt32 size); + void (*Ppmd8_Free)(CPpmd8 *p); + void (*Ppmd8_Init)(CPpmd8 *p, unsigned max_order, unsigned restore_method); + #define Ppmd7_WasAllocated(p) ((p)->Base != NULL) + + /* Decode Functions */ + int (*Ppmd8_RangeDec_Init)(CPpmd8 *p); + int (*Ppmd8_DecodeSymbol)(CPpmd8 *p); +} IPpmd8; + +extern const IPpmd8 __archive_ppmd8_functions; + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd_private.h new file mode 100644 index 0000000000..582803e5fd --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_ppmd_private.h @@ -0,0 +1,151 @@ +/* Ppmd.h -- PPMD codec common code +2010-03-12 : Igor Pavlov : Public domain +This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */ + +#ifndef ARCHIVE_PPMD_PRIVATE_H_INCLUDED +#define ARCHIVE_PPMD_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +#include <stddef.h> + +#include "archive_read_private.h" + +/*** Begin defined in Types.h ***/ + +#if !defined(ZCONF_H) +typedef unsigned char Byte; +#endif +typedef short Int16; +typedef unsigned short UInt16; + +#ifdef _LZMA_UINT32_IS_ULONG +typedef long Int32; +typedef unsigned long UInt32; +#else +typedef int Int32; +typedef unsigned int UInt32; +#endif + +#ifdef _SZ_NO_INT_64 + +/* define _SZ_NO_INT_64, if your compiler doesn't support 64-bit integers. + NOTES: Some code will work incorrectly in that case! */ + +typedef long Int64; +typedef unsigned long UInt64; + +#else + +#if defined(_MSC_VER) || defined(__BORLANDC__) +typedef __int64 Int64; +typedef unsigned __int64 UInt64; +#define UINT64_CONST(n) n +#else +typedef long long int Int64; +typedef unsigned long long int UInt64; +#define UINT64_CONST(n) n ## ULL +#endif + +#endif + +typedef int Bool; +#define True 1 +#define False 0 + +/* The following interfaces use first parameter as pointer to structure */ + +typedef struct +{ + struct archive_read *a; + Byte (*Read)(void *p); /* reads one byte, returns 0 in case of EOF or error */ +} IByteIn; + +typedef struct +{ + struct archive_write *a; + void (*Write)(void *p, Byte b); +} IByteOut; + +/*** End defined in Types.h ***/ +/*** Begin defined in CpuArch.h ***/ + +#if defined(_M_IX86) || defined(__i386__) +#define MY_CPU_X86 +#endif + +#if defined(MY_CPU_X86) || defined(_M_ARM) +#define MY_CPU_32BIT +#endif + +#ifdef MY_CPU_32BIT +#define PPMD_32BIT +#endif + +/*** End defined in CpuArch.h ***/ + +#define PPMD_INT_BITS 7 +#define PPMD_PERIOD_BITS 7 +#define PPMD_BIN_SCALE (1 << (PPMD_INT_BITS + PPMD_PERIOD_BITS)) + +#define PPMD_GET_MEAN_SPEC(summ, shift, round) (((summ) + (1 << ((shift) - (round)))) >> (shift)) +#define PPMD_GET_MEAN(summ) PPMD_GET_MEAN_SPEC((summ), PPMD_PERIOD_BITS, 2) +#define PPMD_UPDATE_PROB_0(prob) ((prob) + (1 << PPMD_INT_BITS) - PPMD_GET_MEAN(prob)) +#define PPMD_UPDATE_PROB_1(prob) ((prob) - PPMD_GET_MEAN(prob)) + +#define PPMD_N1 4 +#define PPMD_N2 4 +#define PPMD_N3 4 +#define PPMD_N4 ((128 + 3 - 1 * PPMD_N1 - 2 * PPMD_N2 - 3 * PPMD_N3) / 4) +#define PPMD_NUM_INDEXES (PPMD_N1 + PPMD_N2 + PPMD_N3 + PPMD_N4) + +/* SEE-contexts for PPM-contexts with masked symbols */ +typedef struct +{ + UInt16 Summ; /* Freq */ + Byte Shift; /* Speed of Freq change; low Shift is for fast change */ + Byte Count; /* Count to next change of Shift */ +} CPpmd_See; + +#define Ppmd_See_Update(p) if ((p)->Shift < PPMD_PERIOD_BITS && --(p)->Count == 0) \ + { (p)->Summ <<= 1; (p)->Count = (Byte)(3 << (p)->Shift++); } + +typedef struct +{ + Byte Symbol; + Byte Freq; + UInt16 SuccessorLow; + UInt16 SuccessorHigh; +} CPpmd_State; + +typedef + #ifdef PPMD_32BIT + CPpmd_State * + #else + UInt32 + #endif + CPpmd_State_Ref; + +typedef + #ifdef PPMD_32BIT + void * + #else + UInt32 + #endif + CPpmd_Void_Ref; + +typedef + #ifdef PPMD_32BIT + Byte * + #else + UInt32 + #endif + CPpmd_Byte_Ref; + +#define PPMD_SetAllBitsIn256Bytes(p) \ + { unsigned j; for (j = 0; j < 256 / sizeof(p[0]); j += 8) { \ + p[j+7] = p[j+6] = p[j+5] = p[j+4] = p[j+3] = p[j+2] = p[j+1] = p[j+0] = ~(size_t)0; }} + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_private.h new file mode 100644 index 0000000000..937a87bb1e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_private.h @@ -0,0 +1,176 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + * + * $FreeBSD: head/lib/libarchive/archive_private.h 201098 2009-12-28 02:58:14Z kientzle $ + */ + +#ifndef ARCHIVE_PRIVATE_H_INCLUDED +#define ARCHIVE_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +#if HAVE_ICONV_H +#include <iconv.h> +#endif + +#include "archive.h" +#include "archive_string.h" + +#if defined(__GNUC__) && (__GNUC__ > 2 || \ + (__GNUC__ == 2 && __GNUC_MINOR__ >= 5)) +#define __LA_DEAD __attribute__((__noreturn__)) +#else +#define __LA_DEAD +#endif + +#define ARCHIVE_WRITE_MAGIC (0xb0c5c0deU) +#define ARCHIVE_READ_MAGIC (0xdeb0c5U) +#define ARCHIVE_WRITE_DISK_MAGIC (0xc001b0c5U) +#define ARCHIVE_READ_DISK_MAGIC (0xbadb0c5U) +#define ARCHIVE_MATCH_MAGIC (0xcad11c9U) + +#define ARCHIVE_STATE_NEW 1U +#define ARCHIVE_STATE_HEADER 2U +#define ARCHIVE_STATE_DATA 4U +#define ARCHIVE_STATE_EOF 0x10U +#define ARCHIVE_STATE_CLOSED 0x20U +#define ARCHIVE_STATE_FATAL 0x8000U +#define ARCHIVE_STATE_ANY (0xFFFFU & ~ARCHIVE_STATE_FATAL) + +struct archive_vtable { + int (*archive_close)(struct archive *); + int (*archive_free)(struct archive *); + int (*archive_write_header)(struct archive *, + struct archive_entry *); + int (*archive_write_finish_entry)(struct archive *); + ssize_t (*archive_write_data)(struct archive *, + const void *, size_t); + ssize_t (*archive_write_data_block)(struct archive *, + const void *, size_t, int64_t); + + int (*archive_read_next_header)(struct archive *, + struct archive_entry **); + int (*archive_read_next_header2)(struct archive *, + struct archive_entry *); + int (*archive_read_data_block)(struct archive *, + const void **, size_t *, int64_t *); + + int (*archive_filter_count)(struct archive *); + int64_t (*archive_filter_bytes)(struct archive *, int); + int (*archive_filter_code)(struct archive *, int); + const char * (*archive_filter_name)(struct archive *, int); +}; + +struct archive_string_conv; + +struct archive { + /* + * The magic/state values are used to sanity-check the + * client's usage. If an API function is called at a + * ridiculous time, or the client passes us an invalid + * pointer, these values allow me to catch that. + */ + unsigned int magic; + unsigned int state; + + /* + * Some public API functions depend on the "real" type of the + * archive object. + */ + struct archive_vtable *vtable; + + int archive_format; + const char *archive_format_name; + + int compression_code; /* Currently active compression. */ + const char *compression_name; + + /* Number of file entries processed. */ + int file_count; + + int archive_error_number; + const char *error; + struct archive_string error_string; + + char *current_code; + unsigned current_codepage; /* Current ACP(ANSI CodePage). */ + unsigned current_oemcp; /* Current OEMCP(OEM CodePage). */ + struct archive_string_conv *sconv; + + /* + * Used by archive_read_data() to track blocks and copy + * data to client buffers, filling gaps with zero bytes. + */ + const char *read_data_block; + int64_t read_data_offset; + int64_t read_data_output_offset; + size_t read_data_remaining; + + /* + * Used by formats/filters to determine the amount of data + * requested from a call to archive_read_data(). This is only + * useful when the format/filter has seek support. + */ + char read_data_is_posix_read; + size_t read_data_requested; +}; + +/* Check magic value and state; return(ARCHIVE_FATAL) if it isn't valid. */ +int __archive_check_magic(struct archive *, unsigned int magic, + unsigned int state, const char *func); +#define archive_check_magic(a, expected_magic, allowed_states, function_name) \ + do { \ + int magic_test = __archive_check_magic((a), (expected_magic), \ + (allowed_states), (function_name)); \ + if (magic_test == ARCHIVE_FATAL) \ + return ARCHIVE_FATAL; \ + } while (0) + +void __archive_errx(int retvalue, const char *msg) __LA_DEAD; + +void __archive_ensure_cloexec_flag(int fd); +int __archive_mktemp(const char *tmpdir); +#if defined(_WIN32) && !defined(__CYGWIN__) +int __archive_mkstemp(wchar_t *template); +#else +int __archive_mkstemp(char *template); +#endif + +int __archive_clean(struct archive *); + +void __archive_reset_read_data(struct archive *); + +#define err_combine(a,b) ((a) < (b) ? (a) : (b)) + +#if defined(__BORLANDC__) || (defined(_MSC_VER) && _MSC_VER <= 1300) +# define ARCHIVE_LITERAL_LL(x) x##i64 +# define ARCHIVE_LITERAL_ULL(x) x##ui64 +#else +# define ARCHIVE_LITERAL_LL(x) x##ll +# define ARCHIVE_LITERAL_ULL(x) x##ull +#endif + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_random.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_random.c new file mode 100644 index 0000000000..65ea691576 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_random.c @@ -0,0 +1,272 @@ +/*- + * Copyright (c) 2014 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif + +#if !defined(HAVE_ARC4RANDOM_BUF) && (!defined(_WIN32) || defined(__CYGWIN__)) + +#ifdef HAVE_FCNTL +#include <fcntl.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_TIME_H +#include <sys/time.h> +#endif +#ifdef HAVE_PTHREAD_H +#include <pthread.h> +#endif + +static void arc4random_buf(void *, size_t); + +#endif /* HAVE_ARC4RANDOM_BUF */ + +#include "archive.h" +#include "archive_random_private.h" + +#if defined(HAVE_WINCRYPT_H) && !defined(__CYGWIN__) +#include <wincrypt.h> +#endif + +#ifndef O_CLOEXEC +#define O_CLOEXEC 0 +#endif + +/* + * Random number generator function. + * This simply calls arc4random_buf function if the platform provides it. + */ + +int +archive_random(void *buf, size_t nbytes) +{ +#if defined(_WIN32) && !defined(__CYGWIN__) + HCRYPTPROV hProv; + BOOL success; + + success = CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT); + if (!success && GetLastError() == (DWORD)NTE_BAD_KEYSET) { + success = CryptAcquireContext(&hProv, NULL, NULL, + PROV_RSA_FULL, CRYPT_NEWKEYSET); + } + if (success) { + success = CryptGenRandom(hProv, (DWORD)nbytes, (BYTE*)buf); + CryptReleaseContext(hProv, 0); + if (success) + return ARCHIVE_OK; + } + /* TODO: Does this case really happen? */ + return ARCHIVE_FAILED; +#else + arc4random_buf(buf, nbytes); + return ARCHIVE_OK; +#endif +} + +#if !defined(HAVE_ARC4RANDOM_BUF) && (!defined(_WIN32) || defined(__CYGWIN__)) + +/* $OpenBSD: arc4random.c,v 1.24 2013/06/11 16:59:50 deraadt Exp $ */ +/* + * Copyright (c) 1996, David Mazieres <dm@uun.org> + * Copyright (c) 2008, Damien Miller <djm@openbsd.org> + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* + * Arc4 random number generator for OpenBSD. + * + * This code is derived from section 17.1 of Applied Cryptography, + * second edition, which describes a stream cipher allegedly + * compatible with RSA Labs "RC4" cipher (the actual description of + * which is a trade secret). The same algorithm is used as a stream + * cipher called "arcfour" in Tatu Ylonen's ssh package. + * + * RC4 is a registered trademark of RSA Laboratories. + */ + +#ifdef __GNUC__ +#define inline __inline +#else /* !__GNUC__ */ +#define inline +#endif /* !__GNUC__ */ + +struct arc4_stream { + uint8_t i; + uint8_t j; + uint8_t s[256]; +}; + +#define RANDOMDEV "/dev/urandom" +#define KEYSIZE 128 +#ifdef HAVE_PTHREAD_H +static pthread_mutex_t arc4random_mtx = PTHREAD_MUTEX_INITIALIZER; +#define _ARC4_LOCK() pthread_mutex_lock(&arc4random_mtx); +#define _ARC4_UNLOCK() pthread_mutex_unlock(&arc4random_mtx); +#else +#define _ARC4_LOCK() +#define _ARC4_UNLOCK() +#endif + +static int rs_initialized; +static struct arc4_stream rs; +static pid_t arc4_stir_pid; +static int arc4_count; + +static inline uint8_t arc4_getbyte(void); +static void arc4_stir(void); + +static inline void +arc4_init(void) +{ + int n; + + for (n = 0; n < 256; n++) + rs.s[n] = n; + rs.i = 0; + rs.j = 0; +} + +static inline void +arc4_addrandom(u_char *dat, int datlen) +{ + int n; + uint8_t si; + + rs.i--; + for (n = 0; n < 256; n++) { + rs.i = (rs.i + 1); + si = rs.s[rs.i]; + rs.j = (rs.j + si + dat[n % datlen]); + rs.s[rs.i] = rs.s[rs.j]; + rs.s[rs.j] = si; + } + rs.j = rs.i; +} + +static void +arc4_stir(void) +{ + int done, fd, i; + struct { + struct timeval tv; + pid_t pid; + u_char rnd[KEYSIZE]; + } rdat; + + if (!rs_initialized) { + arc4_init(); + rs_initialized = 1; + } + done = 0; + fd = open(RANDOMDEV, O_RDONLY | O_CLOEXEC, 0); + if (fd >= 0) { + if (read(fd, &rdat, KEYSIZE) == KEYSIZE) + done = 1; + (void)close(fd); + } + if (!done) { + (void)gettimeofday(&rdat.tv, NULL); + rdat.pid = getpid(); + /* We'll just take whatever was on the stack too... */ + } + + arc4_addrandom((u_char *)&rdat, KEYSIZE); + + /* + * Discard early keystream, as per recommendations in: + * "(Not So) Random Shuffles of RC4" by Ilya Mironov. + * As per the Network Operations Division, cryptographic requirements + * published on wikileaks on March 2017. + */ + + for (i = 0; i < 3072; i++) + (void)arc4_getbyte(); + arc4_count = 1600000; +} + +static void +arc4_stir_if_needed(void) +{ + pid_t pid = getpid(); + + if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != pid) { + arc4_stir_pid = pid; + arc4_stir(); + } +} + +static inline uint8_t +arc4_getbyte(void) +{ + uint8_t si, sj; + + rs.i = (rs.i + 1); + si = rs.s[rs.i]; + rs.j = (rs.j + si); + sj = rs.s[rs.j]; + rs.s[rs.i] = sj; + rs.s[rs.j] = si; + return (rs.s[(si + sj) & 0xff]); +} + +static void +arc4random_buf(void *_buf, size_t n) +{ + u_char *buf = (u_char *)_buf; + _ARC4_LOCK(); + arc4_stir_if_needed(); + while (n--) { + if (--arc4_count <= 0) + arc4_stir(); + buf[n] = arc4_getbyte(); + } + _ARC4_UNLOCK(); +} + +#endif /* !HAVE_ARC4RANDOM_BUF */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_random_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_random_private.h new file mode 100644 index 0000000000..08b91b3b7a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_random_private.h @@ -0,0 +1,36 @@ +/*- + * Copyright (c) 2014 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#ifndef ARCHIVE_RANDOM_PRIVATE_H_INCLUDED +#define ARCHIVE_RANDOM_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +/* Random number generator. */ +int archive_random(void *buf, size_t nbytes); + +#endif /* ARCHIVE_RANDOM_PRIVATE_H_INCLUDED */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_rb.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_rb.c new file mode 100644 index 0000000000..cf58ac3354 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_rb.c @@ -0,0 +1,709 @@ +/*- + * Copyright (c) 2001 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Matt Thomas <matt@3am-software.com>. + * + * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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. + * + * Based on: NetBSD: rb.c,v 1.6 2010/04/30 13:58:09 joerg Exp + */ + +#include "archive_platform.h" + +#include <stddef.h> + +#include "archive_rb.h" + +/* Keep in sync with archive_rb.h */ +#define RB_DIR_LEFT 0 +#define RB_DIR_RIGHT 1 +#define RB_DIR_OTHER 1 +#define rb_left rb_nodes[RB_DIR_LEFT] +#define rb_right rb_nodes[RB_DIR_RIGHT] + +#define RB_FLAG_POSITION 0x2 +#define RB_FLAG_RED 0x1 +#define RB_FLAG_MASK (RB_FLAG_POSITION|RB_FLAG_RED) +#define RB_FATHER(rb) \ + ((struct archive_rb_node *)((rb)->rb_info & ~RB_FLAG_MASK)) +#define RB_SET_FATHER(rb, father) \ + ((void)((rb)->rb_info = (uintptr_t)(father)|((rb)->rb_info & RB_FLAG_MASK))) + +#define RB_SENTINEL_P(rb) ((rb) == NULL) +#define RB_LEFT_SENTINEL_P(rb) RB_SENTINEL_P((rb)->rb_left) +#define RB_RIGHT_SENTINEL_P(rb) RB_SENTINEL_P((rb)->rb_right) +#define RB_FATHER_SENTINEL_P(rb) RB_SENTINEL_P(RB_FATHER((rb))) +#define RB_CHILDLESS_P(rb) \ + (RB_SENTINEL_P(rb) || (RB_LEFT_SENTINEL_P(rb) && RB_RIGHT_SENTINEL_P(rb))) +#define RB_TWOCHILDREN_P(rb) \ + (!RB_SENTINEL_P(rb) && !RB_LEFT_SENTINEL_P(rb) && !RB_RIGHT_SENTINEL_P(rb)) + +#define RB_POSITION(rb) \ + (((rb)->rb_info & RB_FLAG_POSITION) ? RB_DIR_RIGHT : RB_DIR_LEFT) +#define RB_RIGHT_P(rb) (RB_POSITION(rb) == RB_DIR_RIGHT) +#define RB_LEFT_P(rb) (RB_POSITION(rb) == RB_DIR_LEFT) +#define RB_RED_P(rb) (!RB_SENTINEL_P(rb) && ((rb)->rb_info & RB_FLAG_RED) != 0) +#define RB_BLACK_P(rb) (RB_SENTINEL_P(rb) || ((rb)->rb_info & RB_FLAG_RED) == 0) +#define RB_MARK_RED(rb) ((void)((rb)->rb_info |= RB_FLAG_RED)) +#define RB_MARK_BLACK(rb) ((void)((rb)->rb_info &= ~RB_FLAG_RED)) +#define RB_INVERT_COLOR(rb) ((void)((rb)->rb_info ^= RB_FLAG_RED)) +#define RB_ROOT_P(rbt, rb) ((rbt)->rbt_root == (rb)) +#define RB_SET_POSITION(rb, position) \ + ((void)((position) ? ((rb)->rb_info |= RB_FLAG_POSITION) : \ + ((rb)->rb_info &= ~RB_FLAG_POSITION))) +#define RB_ZERO_PROPERTIES(rb) ((void)((rb)->rb_info &= ~RB_FLAG_MASK)) +#define RB_COPY_PROPERTIES(dst, src) \ + ((void)((dst)->rb_info ^= ((dst)->rb_info ^ (src)->rb_info) & RB_FLAG_MASK)) +#define RB_SWAP_PROPERTIES(a, b) do { \ + uintptr_t xorinfo = ((a)->rb_info ^ (b)->rb_info) & RB_FLAG_MASK; \ + (a)->rb_info ^= xorinfo; \ + (b)->rb_info ^= xorinfo; \ + } while (/*CONSTCOND*/ 0) + +static void __archive_rb_tree_insert_rebalance(struct archive_rb_tree *, + struct archive_rb_node *); +static void __archive_rb_tree_removal_rebalance(struct archive_rb_tree *, + struct archive_rb_node *, unsigned int); + +#define RB_SENTINEL_NODE NULL + +#define T 1 +#define F 0 + +void +__archive_rb_tree_init(struct archive_rb_tree *rbt, + const struct archive_rb_tree_ops *ops) +{ + rbt->rbt_ops = ops; + *((struct archive_rb_node **)&rbt->rbt_root) = RB_SENTINEL_NODE; +} + +struct archive_rb_node * +__archive_rb_tree_find_node(struct archive_rb_tree *rbt, const void *key) +{ + archive_rbto_compare_key_fn compare_key = rbt->rbt_ops->rbto_compare_key; + struct archive_rb_node *parent = rbt->rbt_root; + + while (!RB_SENTINEL_P(parent)) { + const signed int diff = (*compare_key)(parent, key); + if (diff == 0) + return parent; + parent = parent->rb_nodes[diff > 0]; + } + + return NULL; +} + +struct archive_rb_node * +__archive_rb_tree_find_node_geq(struct archive_rb_tree *rbt, const void *key) +{ + archive_rbto_compare_key_fn compare_key = rbt->rbt_ops->rbto_compare_key; + struct archive_rb_node *parent = rbt->rbt_root; + struct archive_rb_node *last = NULL; + + while (!RB_SENTINEL_P(parent)) { + const signed int diff = (*compare_key)(parent, key); + if (diff == 0) + return parent; + if (diff < 0) + last = parent; + parent = parent->rb_nodes[diff > 0]; + } + + return last; +} + +struct archive_rb_node * +__archive_rb_tree_find_node_leq(struct archive_rb_tree *rbt, const void *key) +{ + archive_rbto_compare_key_fn compare_key = rbt->rbt_ops->rbto_compare_key; + struct archive_rb_node *parent = rbt->rbt_root; + struct archive_rb_node *last = NULL; + + while (!RB_SENTINEL_P(parent)) { + const signed int diff = (*compare_key)(parent, key); + if (diff == 0) + return parent; + if (diff > 0) + last = parent; + parent = parent->rb_nodes[diff > 0]; + } + + return last; +} + +int +__archive_rb_tree_insert_node(struct archive_rb_tree *rbt, + struct archive_rb_node *self) +{ + archive_rbto_compare_nodes_fn compare_nodes = rbt->rbt_ops->rbto_compare_nodes; + struct archive_rb_node *parent, *tmp; + unsigned int position; + int rebalance; + + tmp = rbt->rbt_root; + /* + * This is a hack. Because rbt->rbt_root is just a + * struct archive_rb_node *, just like rb_node->rb_nodes[RB_DIR_LEFT], + * we can use this fact to avoid a lot of tests for root and know + * that even at root, updating + * RB_FATHER(rb_node)->rb_nodes[RB_POSITION(rb_node)] will + * update rbt->rbt_root. + */ + parent = (struct archive_rb_node *)(void *)&rbt->rbt_root; + position = RB_DIR_LEFT; + + /* + * Find out where to place this new leaf. + */ + while (!RB_SENTINEL_P(tmp)) { + const signed int diff = (*compare_nodes)(tmp, self); + if (diff == 0) { + /* + * Node already exists; don't insert. + */ + return F; + } + parent = tmp; + position = (diff > 0); + tmp = parent->rb_nodes[position]; + } + + /* + * Initialize the node and insert as a leaf into the tree. + */ + RB_SET_FATHER(self, parent); + RB_SET_POSITION(self, position); + if (parent == (struct archive_rb_node *)(void *)&rbt->rbt_root) { + RB_MARK_BLACK(self); /* root is always black */ + rebalance = F; + } else { + /* + * All new nodes are colored red. We only need to rebalance + * if our parent is also red. + */ + RB_MARK_RED(self); + rebalance = RB_RED_P(parent); + } + self->rb_left = parent->rb_nodes[position]; + self->rb_right = parent->rb_nodes[position]; + parent->rb_nodes[position] = self; + + /* + * Rebalance tree after insertion + */ + if (rebalance) + __archive_rb_tree_insert_rebalance(rbt, self); + + return T; +} + +/* + * Swap the location and colors of 'self' and its child @ which. The child + * can not be a sentinel node. This is our rotation function. However, + * since it preserves coloring, it great simplifies both insertion and + * removal since rotation almost always involves the exchanging of colors + * as a separate step. + */ +/*ARGSUSED*/ +static void +__archive_rb_tree_reparent_nodes( + struct archive_rb_node *old_father, const unsigned int which) +{ + const unsigned int other = which ^ RB_DIR_OTHER; + struct archive_rb_node * const grandpa = RB_FATHER(old_father); + struct archive_rb_node * const old_child = old_father->rb_nodes[which]; + struct archive_rb_node * const new_father = old_child; + struct archive_rb_node * const new_child = old_father; + + if (new_father == NULL) + return; + /* + * Exchange descendant linkages. + */ + grandpa->rb_nodes[RB_POSITION(old_father)] = new_father; + new_child->rb_nodes[which] = old_child->rb_nodes[other]; + new_father->rb_nodes[other] = new_child; + + /* + * Update ancestor linkages + */ + RB_SET_FATHER(new_father, grandpa); + RB_SET_FATHER(new_child, new_father); + + /* + * Exchange properties between new_father and new_child. The only + * change is that new_child's position is now on the other side. + */ + RB_SWAP_PROPERTIES(new_father, new_child); + RB_SET_POSITION(new_child, other); + + /* + * Make sure to reparent the new child to ourself. + */ + if (!RB_SENTINEL_P(new_child->rb_nodes[which])) { + RB_SET_FATHER(new_child->rb_nodes[which], new_child); + RB_SET_POSITION(new_child->rb_nodes[which], which); + } + +} + +static void +__archive_rb_tree_insert_rebalance(struct archive_rb_tree *rbt, + struct archive_rb_node *self) +{ + struct archive_rb_node * father = RB_FATHER(self); + struct archive_rb_node * grandpa; + struct archive_rb_node * uncle; + unsigned int which; + unsigned int other; + + for (;;) { + /* + * We are red and our parent is red, therefore we must have a + * grandfather and he must be black. + */ + grandpa = RB_FATHER(father); + which = (father == grandpa->rb_right); + other = which ^ RB_DIR_OTHER; + uncle = grandpa->rb_nodes[other]; + + if (RB_BLACK_P(uncle)) + break; + + /* + * Case 1: our uncle is red + * Simply invert the colors of our parent and + * uncle and make our grandparent red. And + * then solve the problem up at his level. + */ + RB_MARK_BLACK(uncle); + RB_MARK_BLACK(father); + if (RB_ROOT_P(rbt, grandpa)) { + /* + * If our grandpa is root, don't bother + * setting him to red, just return. + */ + return; + } + RB_MARK_RED(grandpa); + self = grandpa; + father = RB_FATHER(self); + if (RB_BLACK_P(father)) { + /* + * If our great-grandpa is black, we're done. + */ + return; + } + } + + /* + * Case 2&3: our uncle is black. + */ + if (self == father->rb_nodes[other]) { + /* + * Case 2: we are on the same side as our uncle + * Swap ourselves with our parent so this case + * becomes case 3. Basically our parent becomes our + * child. + */ + __archive_rb_tree_reparent_nodes(father, other); + } + /* + * Case 3: we are opposite a child of a black uncle. + * Swap our parent and grandparent. Since our grandfather + * is black, our father will become black and our new sibling + * (former grandparent) will become red. + */ + __archive_rb_tree_reparent_nodes(grandpa, which); + + /* + * Final step: Set the root to black. + */ + RB_MARK_BLACK(rbt->rbt_root); +} + +static void +__archive_rb_tree_prune_node(struct archive_rb_tree *rbt, + struct archive_rb_node *self, int rebalance) +{ + const unsigned int which = RB_POSITION(self); + struct archive_rb_node *father = RB_FATHER(self); + + /* + * Since we are childless, we know that self->rb_left is pointing + * to the sentinel node. + */ + father->rb_nodes[which] = self->rb_left; + + /* + * Rebalance if requested. + */ + if (rebalance) + __archive_rb_tree_removal_rebalance(rbt, father, which); +} + +/* + * When deleting an interior node + */ +static void +__archive_rb_tree_swap_prune_and_rebalance(struct archive_rb_tree *rbt, + struct archive_rb_node *self, struct archive_rb_node *standin) +{ + const unsigned int standin_which = RB_POSITION(standin); + unsigned int standin_other = standin_which ^ RB_DIR_OTHER; + struct archive_rb_node *standin_son; + struct archive_rb_node *standin_father = RB_FATHER(standin); + int rebalance = RB_BLACK_P(standin); + + if (standin_father == self) { + /* + * As a child of self, any children would be opposite of + * our parent. + */ + standin_son = standin->rb_nodes[standin_which]; + } else { + /* + * Since we aren't a child of self, any children would be + * on the same side as our parent. + */ + standin_son = standin->rb_nodes[standin_other]; + } + + if (RB_RED_P(standin_son)) { + /* + * We know we have a red child so if we flip it to black + * we don't have to rebalance. + */ + RB_MARK_BLACK(standin_son); + rebalance = F; + + if (standin_father != self) { + /* + * Change the son's parentage to point to his grandpa. + */ + RB_SET_FATHER(standin_son, standin_father); + RB_SET_POSITION(standin_son, standin_which); + } + } + + if (standin_father == self) { + /* + * If we are about to delete the standin's father, then when + * we call rebalance, we need to use ourselves as our father. + * Otherwise remember our original father. Also, since we are + * our standin's father we only need to reparent the standin's + * brother. + * + * | R --> S | + * | Q S --> Q T | + * | t --> | + * + * Have our son/standin adopt his brother as his new son. + */ + standin_father = standin; + } else { + /* + * | R --> S . | + * | / \ | T --> / \ | / | + * | ..... | S --> ..... | T | + * + * Sever standin's connection to his father. + */ + standin_father->rb_nodes[standin_which] = standin_son; + /* + * Adopt the far son. + */ + standin->rb_nodes[standin_other] = self->rb_nodes[standin_other]; + RB_SET_FATHER(standin->rb_nodes[standin_other], standin); + /* + * Use standin_other because we need to preserve standin_which + * for the removal_rebalance. + */ + standin_other = standin_which; + } + + /* + * Move the only remaining son to our standin. If our standin is our + * son, this will be the only son needed to be moved. + */ + standin->rb_nodes[standin_other] = self->rb_nodes[standin_other]; + RB_SET_FATHER(standin->rb_nodes[standin_other], standin); + + /* + * Now copy the result of self to standin and then replace + * self with standin in the tree. + */ + RB_COPY_PROPERTIES(standin, self); + RB_SET_FATHER(standin, RB_FATHER(self)); + RB_FATHER(standin)->rb_nodes[RB_POSITION(standin)] = standin; + + if (rebalance) + __archive_rb_tree_removal_rebalance(rbt, standin_father, standin_which); +} + +/* + * We could do this by doing + * __archive_rb_tree_node_swap(rbt, self, which); + * __archive_rb_tree_prune_node(rbt, self, F); + * + * But it's more efficient to just evaluate and recolor the child. + */ +static void +__archive_rb_tree_prune_blackred_branch( + struct archive_rb_node *self, unsigned int which) +{ + struct archive_rb_node *father = RB_FATHER(self); + struct archive_rb_node *son = self->rb_nodes[which]; + + /* + * Remove ourselves from the tree and give our former child our + * properties (position, color, root). + */ + RB_COPY_PROPERTIES(son, self); + father->rb_nodes[RB_POSITION(son)] = son; + RB_SET_FATHER(son, father); +} +/* + * + */ +void +__archive_rb_tree_remove_node(struct archive_rb_tree *rbt, + struct archive_rb_node *self) +{ + struct archive_rb_node *standin; + unsigned int which; + + /* + * In the following diagrams, we (the node to be removed) are S. Red + * nodes are lowercase. T could be either red or black. + * + * Remember the major axiom of the red-black tree: the number of + * black nodes from the root to each leaf is constant across all + * leaves, only the number of red nodes varies. + * + * Thus removing a red leaf doesn't require any other changes to a + * red-black tree. So if we must remove a node, attempt to rearrange + * the tree so we can remove a red node. + * + * The simplest case is a childless red node or a childless root node: + * + * | T --> T | or | R --> * | + * | s --> * | + */ + if (RB_CHILDLESS_P(self)) { + const int rebalance = RB_BLACK_P(self) && !RB_ROOT_P(rbt, self); + __archive_rb_tree_prune_node(rbt, self, rebalance); + return; + } + if (!RB_TWOCHILDREN_P(self)) { + /* + * The next simplest case is the node we are deleting is + * black and has one red child. + * + * | T --> T --> T | + * | S --> R --> R | + * | r --> s --> * | + */ + which = RB_LEFT_SENTINEL_P(self) ? RB_DIR_RIGHT : RB_DIR_LEFT; + __archive_rb_tree_prune_blackred_branch(self, which); + return; + } + + /* + * We invert these because we prefer to remove from the inside of + * the tree. + */ + which = RB_POSITION(self) ^ RB_DIR_OTHER; + + /* + * Let's find the node closes to us opposite of our parent + * Now swap it with ourself, "prune" it, and rebalance, if needed. + */ + standin = __archive_rb_tree_iterate(rbt, self, which); + __archive_rb_tree_swap_prune_and_rebalance(rbt, self, standin); +} + +static void +__archive_rb_tree_removal_rebalance(struct archive_rb_tree *rbt, + struct archive_rb_node *parent, unsigned int which) +{ + + while (RB_BLACK_P(parent->rb_nodes[which])) { + unsigned int other = which ^ RB_DIR_OTHER; + struct archive_rb_node *brother = parent->rb_nodes[other]; + + if (brother == NULL) + return;/* The tree may be broken. */ + /* + * For cases 1, 2a, and 2b, our brother's children must + * be black and our father must be black + */ + if (RB_BLACK_P(parent) + && RB_BLACK_P(brother->rb_left) + && RB_BLACK_P(brother->rb_right)) { + if (RB_RED_P(brother)) { + /* + * Case 1: Our brother is red, swap its + * position (and colors) with our parent. + * This should now be case 2b (unless C or E + * has a red child which is case 3; thus no + * explicit branch to case 2b). + * + * B -> D + * A d -> b E + * C E -> A C + */ + __archive_rb_tree_reparent_nodes(parent, other); + brother = parent->rb_nodes[other]; + if (brother == NULL) + return;/* The tree may be broken. */ + } else { + /* + * Both our parent and brother are black. + * Change our brother to red, advance up rank + * and go through the loop again. + * + * B -> *B + * *A D -> A d + * C E -> C E + */ + RB_MARK_RED(brother); + if (RB_ROOT_P(rbt, parent)) + return; /* root == parent == black */ + which = RB_POSITION(parent); + parent = RB_FATHER(parent); + continue; + } + } + /* + * Avoid an else here so that case 2a above can hit either + * case 2b, 3, or 4. + */ + if (RB_RED_P(parent) + && RB_BLACK_P(brother) + && RB_BLACK_P(brother->rb_left) + && RB_BLACK_P(brother->rb_right)) { + /* + * We are black, our father is red, our brother and + * both nephews are black. Simply invert/exchange the + * colors of our father and brother (to black and red + * respectively). + * + * | f --> F | + * | * B --> * b | + * | N N --> N N | + */ + RB_MARK_BLACK(parent); + RB_MARK_RED(brother); + break; /* We're done! */ + } else { + /* + * Our brother must be black and have at least one + * red child (it may have two). + */ + if (RB_BLACK_P(brother->rb_nodes[other])) { + /* + * Case 3: our brother is black, our near + * nephew is red, and our far nephew is black. + * Swap our brother with our near nephew. + * This result in a tree that matches case 4. + * (Our father could be red or black). + * + * | F --> F | + * | x B --> x B | + * | n --> n | + */ + __archive_rb_tree_reparent_nodes(brother, which); + brother = parent->rb_nodes[other]; + } + /* + * Case 4: our brother is black and our far nephew + * is red. Swap our father and brother locations and + * change our far nephew to black. (these can be + * done in either order so we change the color first). + * The result is a valid red-black tree and is a + * terminal case. (again we don't care about the + * father's color) + * + * If the father is red, we will get a red-black-black + * tree: + * | f -> f --> b | + * | B -> B --> F N | + * | n -> N --> | + * + * If the father is black, we will get an all black + * tree: + * | F -> F --> B | + * | B -> B --> F N | + * | n -> N --> | + * + * If we had two red nephews, then after the swap, + * our former father would have a red grandson. + */ + if (brother->rb_nodes[other] == NULL) + return;/* The tree may be broken. */ + RB_MARK_BLACK(brother->rb_nodes[other]); + __archive_rb_tree_reparent_nodes(parent, other); + break; /* We're done! */ + } + } +} + +struct archive_rb_node * +__archive_rb_tree_iterate(struct archive_rb_tree *rbt, + struct archive_rb_node *self, const unsigned int direction) +{ + const unsigned int other = direction ^ RB_DIR_OTHER; + + if (self == NULL) { + self = rbt->rbt_root; + if (RB_SENTINEL_P(self)) + return NULL; + while (!RB_SENTINEL_P(self->rb_nodes[direction])) + self = self->rb_nodes[direction]; + return self; + } + /* + * We can't go any further in this direction. We proceed up in the + * opposite direction until our parent is in direction we want to go. + */ + if (RB_SENTINEL_P(self->rb_nodes[direction])) { + while (!RB_ROOT_P(rbt, self)) { + if (other == (unsigned int)RB_POSITION(self)) + return RB_FATHER(self); + self = RB_FATHER(self); + } + return NULL; + } + + /* + * Advance down one in current direction and go down as far as possible + * in the opposite direction. + */ + self = self->rb_nodes[direction]; + while (!RB_SENTINEL_P(self->rb_nodes[other])) + self = self->rb_nodes[other]; + return self; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_rb.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_rb.h new file mode 100644 index 0000000000..8851f10818 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_rb.h @@ -0,0 +1,113 @@ +/*- + * Copyright (c) 2001 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Matt Thomas <matt@3am-software.com>. + * + * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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. + * + * Based on NetBSD: rb.h,v 1.13 2009/08/16 10:57:01 yamt Exp + */ + +#ifndef ARCHIVE_RB_H_INCLUDED +#define ARCHIVE_RB_H_INCLUDED + +struct archive_rb_node { + struct archive_rb_node *rb_nodes[2]; + /* + * rb_info contains the two flags and the parent back pointer. + * We put the two flags in the low two bits since we know that + * rb_node will have an alignment of 4 or 8 bytes. + */ + uintptr_t rb_info; +}; + +#define ARCHIVE_RB_DIR_LEFT 0 +#define ARCHIVE_RB_DIR_RIGHT 1 + +#define ARCHIVE_RB_TREE_MIN(T) \ + __archive_rb_tree_iterate((T), NULL, ARCHIVE_RB_DIR_LEFT) +#define ARCHIVE_RB_TREE_MAX(T) \ + __archive_rb_tree_iterate((T), NULL, ARCHIVE_RB_DIR_RIGHT) +#define ARCHIVE_RB_TREE_NEXT(T, N) \ + __archive_rb_tree_iterate((T), (N), ARCHIVE_RB_DIR_RIGHT) +#define ARCHIVE_RB_TREE_PREV(T, N) \ + __archive_rb_tree_iterate((T), (N), ARCHIVE_RB_DIR_LEFT) +#define ARCHIVE_RB_TREE_FOREACH(N, T) \ + for ((N) = ARCHIVE_RB_TREE_MIN(T); (N); \ + (N) = ARCHIVE_RB_TREE_NEXT((T), (N))) +#define ARCHIVE_RB_TREE_FOREACH_REVERSE(N, T) \ + for ((N) = ARCHIVE_RB_TREE_MAX(T); (N); \ + (N) = ARCHIVE_RB_TREE_PREV((T), (N))) +#define ARCHIVE_RB_TREE_FOREACH_SAFE(N, T, S) \ + for ((N) = ARCHIVE_RB_TREE_MIN(T); \ + (N) && ((S) = ARCHIVE_RB_TREE_NEXT((T), (N)), 1); \ + (N) = (S)) +#define ARCHIVE_RB_TREE_FOREACH_REVERSE_SAFE(N, T, S) \ + for ((N) = ARCHIVE_RB_TREE_MAX(T); \ + (N) && ((S) = ARCHIVE_RB_TREE_PREV((T), (N)), 1); \ + (N) = (S)) + +/* + * archive_rbto_compare_nodes_fn: + * return a positive value if the first node < the second node. + * return a negative value if the first node > the second node. + * return 0 if they are considered same. + * + * archive_rbto_compare_key_fn: + * return a positive value if the node < the key. + * return a negative value if the node > the key. + * return 0 if they are considered same. + */ + +typedef signed int (*const archive_rbto_compare_nodes_fn)(const struct archive_rb_node *, + const struct archive_rb_node *); +typedef signed int (*const archive_rbto_compare_key_fn)(const struct archive_rb_node *, + const void *); + +struct archive_rb_tree_ops { + archive_rbto_compare_nodes_fn rbto_compare_nodes; + archive_rbto_compare_key_fn rbto_compare_key; +}; + +struct archive_rb_tree { + struct archive_rb_node *rbt_root; + const struct archive_rb_tree_ops *rbt_ops; +}; + +void __archive_rb_tree_init(struct archive_rb_tree *, + const struct archive_rb_tree_ops *); +int __archive_rb_tree_insert_node(struct archive_rb_tree *, + struct archive_rb_node *); +struct archive_rb_node * + __archive_rb_tree_find_node(struct archive_rb_tree *, const void *); +struct archive_rb_node * + __archive_rb_tree_find_node_geq(struct archive_rb_tree *, const void *); +struct archive_rb_node * + __archive_rb_tree_find_node_leq(struct archive_rb_tree *, const void *); +void __archive_rb_tree_remove_node(struct archive_rb_tree *, struct archive_rb_node *); +struct archive_rb_node * + __archive_rb_tree_iterate(struct archive_rb_tree *, + struct archive_rb_node *, const unsigned int); + +#endif /* ARCHIVE_RB_H_*/ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read.3 new file mode 100644 index 0000000000..cbedd0a191 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read.3 @@ -0,0 +1,252 @@ +.\" Copyright (c) 2003-2007 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_READ 3 +.Os +.Sh NAME +.Nm archive_read +.Nd functions for reading streaming archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Sh DESCRIPTION +These functions provide a complete API for reading streaming archives. +The general process is to first create the +.Tn struct archive +object, set options, initialize the reader, iterate over the archive +headers and associated data, then close the archive and release all +resources. +.\" +.Ss Create archive object +See +.Xr archive_read_new 3 . +.Pp +To read an archive, you must first obtain an initialized +.Tn struct archive +object from +.Fn archive_read_new . +.\" +.Ss Enable filters and formats +See +.Xr archive_read_filter 3 +and +.Xr archive_read_format 3 . +.Pp +You can then modify this object for the desired operations with the +various +.Fn archive_read_set_XXX +and +.Fn archive_read_support_XXX +functions. +In particular, you will need to invoke appropriate +.Fn archive_read_support_XXX +functions to enable the corresponding compression and format +support. +Note that these latter functions perform two distinct operations: +they cause the corresponding support code to be linked into your +program, and they enable the corresponding auto-detect code. +Unless you have specific constraints, you will generally want +to invoke +.Fn archive_read_support_filter_all +and +.Fn archive_read_support_format_all +to enable auto-detect for all formats and compression types +currently supported by the library. +.\" +.Ss Set options +See +.Xr archive_read_set_options 3 . +.\" +.Ss Open archive +See +.Xr archive_read_open 3 . +.Pp +Once you have prepared the +.Tn struct archive +object, you call +.Fn archive_read_open +to actually open the archive and prepare it for reading. +There are several variants of this function; +the most basic expects you to provide pointers to several +functions that can provide blocks of bytes from the archive. +There are convenience forms that allow you to +specify a filename, file descriptor, +.Ft "FILE *" +object, or a block of memory from which to read the archive data. +Note that the core library makes no assumptions about the +size of the blocks read; +callback functions are free to read whatever block size is +most appropriate for the medium. +.\" +.Ss Consume archive +See +.Xr archive_read_header 3 , +.Xr archive_read_data 3 +and +.Xr archive_read_extract 3 . +.Pp +Each archive entry consists of a header followed by a certain +amount of data. +You can obtain the next header with +.Fn archive_read_next_header , +which returns a pointer to an +.Tn struct archive_entry +structure with information about the current archive element. +If the entry is a regular file, then the header will be followed +by the file data. +You can use +.Fn archive_read_data +(which works much like the +.Xr read 2 +system call) +to read this data from the archive, or +.Fn archive_read_data_block +which provides a slightly more efficient interface. +You may prefer to use the higher-level +.Fn archive_read_data_skip , +which reads and discards the data for this entry, +.Fn archive_read_data_into_fd , +which copies the data to the provided file descriptor, or +.Fn archive_read_extract , +which recreates the specified entry on disk and copies data +from the archive. +In particular, note that +.Fn archive_read_extract +uses the +.Tn struct archive_entry +structure that you provide it, which may differ from the +entry just read from the archive. +In particular, many applications will want to override the +pathname, file permissions, or ownership. +.\" +.Ss Release resources +See +.Xr archive_read_free 3 . +.Pp +Once you have finished reading data from the archive, you +should call +.Fn archive_read_close +to close the archive, then call +.Fn archive_read_free +to release all resources, including all memory allocated by the library. +.\" +.Sh EXAMPLES +The following illustrates basic usage of the library. +In this example, +the callback functions are simply wrappers around the standard +.Xr open 2 , +.Xr read 2 , +and +.Xr close 2 +system calls. +.Bd -literal -offset indent +void +list_archive(const char *name) +{ + struct mydata *mydata; + struct archive *a; + struct archive_entry *entry; + + mydata = malloc(sizeof(struct mydata)); + a = archive_read_new(); + mydata->name = name; + archive_read_support_filter_all(a); + archive_read_support_format_all(a); + archive_read_open(a, mydata, myopen, myread, myclose); + while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { + printf("%s\en",archive_entry_pathname(entry)); + archive_read_data_skip(a); + } + archive_read_free(a); + free(mydata); +} + +la_ssize_t +myread(struct archive *a, void *client_data, const void **buff) +{ + struct mydata *mydata = client_data; + + *buff = mydata->buff; + return (read(mydata->fd, mydata->buff, 10240)); +} + +int +myopen(struct archive *a, void *client_data) +{ + struct mydata *mydata = client_data; + + mydata->fd = open(mydata->name, O_RDONLY); + return (mydata->fd >= 0 ? ARCHIVE_OK : ARCHIVE_FATAL); +} + +int +myclose(struct archive *a, void *client_data) +{ + struct mydata *mydata = client_data; + + if (mydata->fd > 0) + close(mydata->fd); + return (ARCHIVE_OK); +} +.Ed +.\" .Sh ERRORS +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_read_data 3 , +.Xr archive_read_extract 3 , +.Xr archive_read_filter 3 , +.Xr archive_read_format 3 , +.Xr archive_read_header 3 , +.Xr archive_read_new 3 , +.Xr archive_read_open 3 , +.Xr archive_read_set_options 3 , +.Xr archive_util 3 , +.Xr libarchive 3 , +.Xr tar 5 +.Sh HISTORY +The +.Nm libarchive +library first appeared in +.Fx 5.3 . +.Sh AUTHORS +.An -nosplit +The +.Nm libarchive +library was written by +.An Tim Kientzle Aq kientzle@acm.org . +.Sh BUGS +Many traditional archiver programs treat +empty files as valid empty archives. +For example, many implementations of +.Xr tar 1 +allow you to append entries to an empty file. +Of course, it is impossible to determine the format of an empty file +by inspecting the contents, so this library treats empty files as +having a special +.Dq empty +format. diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read.c new file mode 100644 index 0000000000..c59f051534 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read.c @@ -0,0 +1,1752 @@ +/*- + * Copyright (c) 2003-2011 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +/* + * This file contains the "essential" portions of the read API, that + * is, stuff that will probably always be used by any client that + * actually needs to read an archive. Optional pieces have been, as + * far as possible, separated out into separate files to avoid + * needlessly bloating statically-linked clients. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_read.c 201157 2009-12-29 05:30:23Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_read_private.h" + +#define minimum(a, b) (a < b ? a : b) + +static int choose_filters(struct archive_read *); +static int choose_format(struct archive_read *); +static int close_filters(struct archive_read *); +static struct archive_vtable *archive_read_vtable(void); +static int64_t _archive_filter_bytes(struct archive *, int); +static int _archive_filter_code(struct archive *, int); +static const char *_archive_filter_name(struct archive *, int); +static int _archive_filter_count(struct archive *); +static int _archive_read_close(struct archive *); +static int _archive_read_data_block(struct archive *, + const void **, size_t *, int64_t *); +static int _archive_read_free(struct archive *); +static int _archive_read_next_header(struct archive *, + struct archive_entry **); +static int _archive_read_next_header2(struct archive *, + struct archive_entry *); +static int64_t advance_file_pointer(struct archive_read_filter *, int64_t); + +static struct archive_vtable * +archive_read_vtable(void) +{ + static struct archive_vtable av; + static int inited = 0; + + if (!inited) { + av.archive_filter_bytes = _archive_filter_bytes; + av.archive_filter_code = _archive_filter_code; + av.archive_filter_name = _archive_filter_name; + av.archive_filter_count = _archive_filter_count; + av.archive_read_data_block = _archive_read_data_block; + av.archive_read_next_header = _archive_read_next_header; + av.archive_read_next_header2 = _archive_read_next_header2; + av.archive_free = _archive_read_free; + av.archive_close = _archive_read_close; + inited = 1; + } + return (&av); +} + +/* + * Allocate, initialize and return a struct archive object. + */ +struct archive * +archive_read_new(void) +{ + struct archive_read *a; + + a = (struct archive_read *)calloc(1, sizeof(*a)); + if (a == NULL) + return (NULL); + a->archive.magic = ARCHIVE_READ_MAGIC; + + a->archive.state = ARCHIVE_STATE_NEW; + a->entry = archive_entry_new2(&a->archive); + a->archive.vtable = archive_read_vtable(); + + a->passphrases.last = &a->passphrases.first; + + return (&a->archive); +} + +/* + * Record the do-not-extract-to file. This belongs in archive_read_extract.c. + */ +void +archive_read_extract_set_skip_file(struct archive *_a, la_int64_t d, + la_int64_t i) +{ + struct archive_read *a = (struct archive_read *)_a; + + if (ARCHIVE_OK != __archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_extract_set_skip_file")) + return; + a->skip_file_set = 1; + a->skip_file_dev = d; + a->skip_file_ino = i; +} + +/* + * Open the archive + */ +int +archive_read_open(struct archive *a, void *client_data, + archive_open_callback *client_opener, archive_read_callback *client_reader, + archive_close_callback *client_closer) +{ + /* Old archive_read_open() is just a thin shell around + * archive_read_open1. */ + archive_read_set_open_callback(a, client_opener); + archive_read_set_read_callback(a, client_reader); + archive_read_set_close_callback(a, client_closer); + archive_read_set_callback_data(a, client_data); + return archive_read_open1(a); +} + + +int +archive_read_open2(struct archive *a, void *client_data, + archive_open_callback *client_opener, + archive_read_callback *client_reader, + archive_skip_callback *client_skipper, + archive_close_callback *client_closer) +{ + /* Old archive_read_open2() is just a thin shell around + * archive_read_open1. */ + archive_read_set_callback_data(a, client_data); + archive_read_set_open_callback(a, client_opener); + archive_read_set_read_callback(a, client_reader); + archive_read_set_skip_callback(a, client_skipper); + archive_read_set_close_callback(a, client_closer); + return archive_read_open1(a); +} + +static ssize_t +client_read_proxy(struct archive_read_filter *self, const void **buff) +{ + ssize_t r; + r = (self->archive->client.reader)(&self->archive->archive, + self->data, buff); + return (r); +} + +static int64_t +client_skip_proxy(struct archive_read_filter *self, int64_t request) +{ + if (request < 0) + __archive_errx(1, "Negative skip requested."); + if (request == 0) + return 0; + + if (self->archive->client.skipper != NULL) { + /* Seek requests over 1GiB are broken down into + * multiple seeks. This avoids overflows when the + * requests get passed through 32-bit arguments. */ + int64_t skip_limit = (int64_t)1 << 30; + int64_t total = 0; + for (;;) { + int64_t get, ask = request; + if (ask > skip_limit) + ask = skip_limit; + get = (self->archive->client.skipper) + (&self->archive->archive, self->data, ask); + total += get; + if (get == 0 || get == request) + return (total); + if (get > request) + return ARCHIVE_FATAL; + request -= get; + } + } else if (self->archive->client.seeker != NULL + && request > 64 * 1024) { + /* If the client provided a seeker but not a skipper, + * we can use the seeker to skip forward. + * + * Note: This isn't always a good idea. The client + * skipper is allowed to skip by less than requested + * if it needs to maintain block alignment. The + * seeker is not allowed to play such games, so using + * the seeker here may be a performance loss compared + * to just reading and discarding. That's why we + * only do this for skips of over 64k. + */ + int64_t before = self->position; + int64_t after = (self->archive->client.seeker) + (&self->archive->archive, self->data, request, SEEK_CUR); + if (after != before + request) + return ARCHIVE_FATAL; + return after - before; + } + return 0; +} + +static int64_t +client_seek_proxy(struct archive_read_filter *self, int64_t offset, int whence) +{ + /* DO NOT use the skipper here! If we transparently handled + * forward seek here by using the skipper, that will break + * other libarchive code that assumes a successful forward + * seek means it can also seek backwards. + */ + if (self->archive->client.seeker == NULL) { + archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC, + "Current client reader does not support seeking a device"); + return (ARCHIVE_FAILED); + } + return (self->archive->client.seeker)(&self->archive->archive, + self->data, offset, whence); +} + +static int +client_close_proxy(struct archive_read_filter *self) +{ + int r = ARCHIVE_OK, r2; + unsigned int i; + + if (self->archive->client.closer == NULL) + return (r); + for (i = 0; i < self->archive->client.nodes; i++) + { + r2 = (self->archive->client.closer) + ((struct archive *)self->archive, + self->archive->client.dataset[i].data); + if (r > r2) + r = r2; + } + return (r); +} + +static int +client_open_proxy(struct archive_read_filter *self) +{ + int r = ARCHIVE_OK; + if (self->archive->client.opener != NULL) + r = (self->archive->client.opener)( + (struct archive *)self->archive, self->data); + return (r); +} + +static int +client_switch_proxy(struct archive_read_filter *self, unsigned int iindex) +{ + int r1 = ARCHIVE_OK, r2 = ARCHIVE_OK; + void *data2 = NULL; + + /* Don't do anything if already in the specified data node */ + if (self->archive->client.cursor == iindex) + return (ARCHIVE_OK); + + self->archive->client.cursor = iindex; + data2 = self->archive->client.dataset[self->archive->client.cursor].data; + if (self->archive->client.switcher != NULL) + { + r1 = r2 = (self->archive->client.switcher) + ((struct archive *)self->archive, self->data, data2); + self->data = data2; + } + else + { + /* Attempt to call close and open instead */ + if (self->archive->client.closer != NULL) + r1 = (self->archive->client.closer) + ((struct archive *)self->archive, self->data); + self->data = data2; + if (self->archive->client.opener != NULL) + r2 = (self->archive->client.opener) + ((struct archive *)self->archive, self->data); + } + return (r1 < r2) ? r1 : r2; +} + +int +archive_read_set_open_callback(struct archive *_a, + archive_open_callback *client_opener) +{ + struct archive_read *a = (struct archive_read *)_a; + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, + "archive_read_set_open_callback"); + a->client.opener = client_opener; + return ARCHIVE_OK; +} + +int +archive_read_set_read_callback(struct archive *_a, + archive_read_callback *client_reader) +{ + struct archive_read *a = (struct archive_read *)_a; + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, + "archive_read_set_read_callback"); + a->client.reader = client_reader; + return ARCHIVE_OK; +} + +int +archive_read_set_skip_callback(struct archive *_a, + archive_skip_callback *client_skipper) +{ + struct archive_read *a = (struct archive_read *)_a; + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, + "archive_read_set_skip_callback"); + a->client.skipper = client_skipper; + return ARCHIVE_OK; +} + +int +archive_read_set_seek_callback(struct archive *_a, + archive_seek_callback *client_seeker) +{ + struct archive_read *a = (struct archive_read *)_a; + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, + "archive_read_set_seek_callback"); + a->client.seeker = client_seeker; + return ARCHIVE_OK; +} + +int +archive_read_set_close_callback(struct archive *_a, + archive_close_callback *client_closer) +{ + struct archive_read *a = (struct archive_read *)_a; + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, + "archive_read_set_close_callback"); + a->client.closer = client_closer; + return ARCHIVE_OK; +} + +int +archive_read_set_switch_callback(struct archive *_a, + archive_switch_callback *client_switcher) +{ + struct archive_read *a = (struct archive_read *)_a; + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, + "archive_read_set_switch_callback"); + a->client.switcher = client_switcher; + return ARCHIVE_OK; +} + +int +archive_read_set_callback_data(struct archive *_a, void *client_data) +{ + return archive_read_set_callback_data2(_a, client_data, 0); +} + +int +archive_read_set_callback_data2(struct archive *_a, void *client_data, + unsigned int iindex) +{ + struct archive_read *a = (struct archive_read *)_a; + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, + "archive_read_set_callback_data2"); + + if (a->client.nodes == 0) + { + a->client.dataset = (struct archive_read_data_node *) + calloc(1, sizeof(*a->client.dataset)); + if (a->client.dataset == NULL) + { + archive_set_error(&a->archive, ENOMEM, + "No memory."); + return ARCHIVE_FATAL; + } + a->client.nodes = 1; + } + + if (iindex > a->client.nodes - 1) + { + archive_set_error(&a->archive, EINVAL, + "Invalid index specified."); + return ARCHIVE_FATAL; + } + a->client.dataset[iindex].data = client_data; + a->client.dataset[iindex].begin_position = -1; + a->client.dataset[iindex].total_size = -1; + return ARCHIVE_OK; +} + +int +archive_read_add_callback_data(struct archive *_a, void *client_data, + unsigned int iindex) +{ + struct archive_read *a = (struct archive_read *)_a; + void *p; + unsigned int i; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, + "archive_read_add_callback_data"); + if (iindex > a->client.nodes) { + archive_set_error(&a->archive, EINVAL, + "Invalid index specified."); + return ARCHIVE_FATAL; + } + p = realloc(a->client.dataset, sizeof(*a->client.dataset) + * (++(a->client.nodes))); + if (p == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory."); + return ARCHIVE_FATAL; + } + a->client.dataset = (struct archive_read_data_node *)p; + for (i = a->client.nodes - 1; i > iindex; i--) { + a->client.dataset[i].data = a->client.dataset[i-1].data; + a->client.dataset[i].begin_position = -1; + a->client.dataset[i].total_size = -1; + } + a->client.dataset[iindex].data = client_data; + a->client.dataset[iindex].begin_position = -1; + a->client.dataset[iindex].total_size = -1; + return ARCHIVE_OK; +} + +int +archive_read_append_callback_data(struct archive *_a, void *client_data) +{ + struct archive_read *a = (struct archive_read *)_a; + return archive_read_add_callback_data(_a, client_data, a->client.nodes); +} + +int +archive_read_prepend_callback_data(struct archive *_a, void *client_data) +{ + return archive_read_add_callback_data(_a, client_data, 0); +} + +int +archive_read_open1(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter *filter, *tmp; + int slot, e = ARCHIVE_OK; + unsigned int i; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, + "archive_read_open"); + archive_clear_error(&a->archive); + + if (a->client.reader == NULL) { + archive_set_error(&a->archive, EINVAL, + "No reader function provided to archive_read_open"); + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + + /* Open data source. */ + if (a->client.opener != NULL) { + e = (a->client.opener)(&a->archive, a->client.dataset[0].data); + if (e != 0) { + /* If the open failed, call the closer to clean up. */ + if (a->client.closer) { + for (i = 0; i < a->client.nodes; i++) + (a->client.closer)(&a->archive, + a->client.dataset[i].data); + } + return (e); + } + } + + filter = calloc(1, sizeof(*filter)); + if (filter == NULL) + return (ARCHIVE_FATAL); + filter->bidder = NULL; + filter->upstream = NULL; + filter->archive = a; + filter->data = a->client.dataset[0].data; + filter->open = client_open_proxy; + filter->read = client_read_proxy; + filter->skip = client_skip_proxy; + filter->seek = client_seek_proxy; + filter->close = client_close_proxy; + filter->sswitch = client_switch_proxy; + filter->name = "none"; + filter->code = ARCHIVE_FILTER_NONE; + + a->client.dataset[0].begin_position = 0; + if (!a->filter || !a->bypass_filter_bidding) + { + a->filter = filter; + /* Build out the input pipeline. */ + e = choose_filters(a); + if (e < ARCHIVE_WARN) { + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + } + else + { + /* Need to add "NONE" type filter at the end of the filter chain */ + tmp = a->filter; + while (tmp->upstream) + tmp = tmp->upstream; + tmp->upstream = filter; + } + + if (!a->format) + { + slot = choose_format(a); + if (slot < 0) { + close_filters(a); + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + a->format = &(a->formats[slot]); + } + + a->archive.state = ARCHIVE_STATE_HEADER; + + /* Ensure libarchive starts from the first node in a multivolume set */ + client_switch_proxy(a->filter, 0); + return (e); +} + +/* + * Allow each registered stream transform to bid on whether + * it wants to handle this stream. Repeat until we've finished + * building the pipeline. + */ + +/* We won't build a filter pipeline with more stages than this. */ +#define MAX_NUMBER_FILTERS 25 + +static int +choose_filters(struct archive_read *a) +{ + int number_bidders, i, bid, best_bid, number_filters; + struct archive_read_filter_bidder *bidder, *best_bidder; + struct archive_read_filter *filter; + ssize_t avail; + int r; + + for (number_filters = 0; number_filters < MAX_NUMBER_FILTERS; ++number_filters) { + number_bidders = sizeof(a->bidders) / sizeof(a->bidders[0]); + + best_bid = 0; + best_bidder = NULL; + + bidder = a->bidders; + for (i = 0; i < number_bidders; i++, bidder++) { + if (bidder->bid != NULL) { + bid = (bidder->bid)(bidder, a->filter); + if (bid > best_bid) { + best_bid = bid; + best_bidder = bidder; + } + } + } + + /* If no bidder, we're done. */ + if (best_bidder == NULL) { + /* Verify the filter by asking it for some data. */ + __archive_read_filter_ahead(a->filter, 1, &avail); + if (avail < 0) { + __archive_read_free_filters(a); + return (ARCHIVE_FATAL); + } + a->archive.compression_name = a->filter->name; + a->archive.compression_code = a->filter->code; + return (ARCHIVE_OK); + } + + filter + = (struct archive_read_filter *)calloc(1, sizeof(*filter)); + if (filter == NULL) + return (ARCHIVE_FATAL); + filter->bidder = best_bidder; + filter->archive = a; + filter->upstream = a->filter; + a->filter = filter; + r = (best_bidder->init)(a->filter); + if (r != ARCHIVE_OK) { + __archive_read_free_filters(a); + return (ARCHIVE_FATAL); + } + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Input requires too many filters for decoding"); + return (ARCHIVE_FATAL); +} + +int +__archive_read_header(struct archive_read *a, struct archive_entry *entry) +{ + if (a->filter->read_header) + return a->filter->read_header(a->filter, entry); + else + return (ARCHIVE_OK); +} + +/* + * Read header of next entry. + */ +static int +_archive_read_next_header2(struct archive *_a, struct archive_entry *entry) +{ + struct archive_read *a = (struct archive_read *)_a; + int r1 = ARCHIVE_OK, r2; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_read_next_header"); + + archive_entry_clear(entry); + archive_clear_error(&a->archive); + + /* + * If client didn't consume entire data, skip any remainder + * (This is especially important for GNU incremental directories.) + */ + if (a->archive.state == ARCHIVE_STATE_DATA) { + r1 = archive_read_data_skip(&a->archive); + if (r1 == ARCHIVE_EOF) + archive_set_error(&a->archive, EIO, + "Premature end-of-file."); + if (r1 == ARCHIVE_EOF || r1 == ARCHIVE_FATAL) { + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + } + + /* Record start-of-header offset in uncompressed stream. */ + a->header_position = a->filter->position; + + ++_a->file_count; + r2 = (a->format->read_header)(a, entry); + + /* + * EOF and FATAL are persistent at this layer. By + * modifying the state, we guarantee that future calls to + * read a header or read data will fail. + */ + switch (r2) { + case ARCHIVE_EOF: + a->archive.state = ARCHIVE_STATE_EOF; + --_a->file_count;/* Revert a file counter. */ + break; + case ARCHIVE_OK: + a->archive.state = ARCHIVE_STATE_DATA; + break; + case ARCHIVE_WARN: + a->archive.state = ARCHIVE_STATE_DATA; + break; + case ARCHIVE_RETRY: + break; + case ARCHIVE_FATAL: + a->archive.state = ARCHIVE_STATE_FATAL; + break; + } + + __archive_reset_read_data(&a->archive); + + a->data_start_node = a->client.cursor; + /* EOF always wins; otherwise return the worst error. */ + return (r2 < r1 || r2 == ARCHIVE_EOF) ? r2 : r1; +} + +static int +_archive_read_next_header(struct archive *_a, struct archive_entry **entryp) +{ + int ret; + struct archive_read *a = (struct archive_read *)_a; + *entryp = NULL; + ret = _archive_read_next_header2(_a, a->entry); + *entryp = a->entry; + return ret; +} + +/* + * Allow each registered format to bid on whether it wants to handle + * the next entry. Return index of winning bidder. + */ +static int +choose_format(struct archive_read *a) +{ + int slots; + int i; + int bid, best_bid; + int best_bid_slot; + + slots = sizeof(a->formats) / sizeof(a->formats[0]); + best_bid = -1; + best_bid_slot = -1; + + /* Set up a->format for convenience of bidders. */ + a->format = &(a->formats[0]); + for (i = 0; i < slots; i++, a->format++) { + if (a->format->bid) { + bid = (a->format->bid)(a, best_bid); + if (bid == ARCHIVE_FATAL) + return (ARCHIVE_FATAL); + if (a->filter->position != 0) + __archive_read_seek(a, 0, SEEK_SET); + if ((bid > best_bid) || (best_bid_slot < 0)) { + best_bid = bid; + best_bid_slot = i; + } + } + } + + /* + * There were no bidders; this is a serious programmer error + * and demands a quick and definitive abort. + */ + if (best_bid_slot < 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "No formats registered"); + return (ARCHIVE_FATAL); + } + + /* + * There were bidders, but no non-zero bids; this means we + * can't support this stream. + */ + if (best_bid < 1) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Unrecognized archive format"); + return (ARCHIVE_FATAL); + } + + return (best_bid_slot); +} + +/* + * Return the file offset (within the uncompressed data stream) where + * the last header started. + */ +la_int64_t +archive_read_header_position(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_header_position"); + return (a->header_position); +} + +/* + * Returns 1 if the archive contains at least one encrypted entry. + * If the archive format not support encryption at all + * ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED is returned. + * If for any other reason (e.g. not enough data read so far) + * we cannot say whether there are encrypted entries, then + * ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW is returned. + * In general, this function will return values below zero when the + * reader is uncertain or totally incapable of encryption support. + * When this function returns 0 you can be sure that the reader + * supports encryption detection but no encrypted entries have + * been found yet. + * + * NOTE: If the metadata/header of an archive is also encrypted, you + * cannot rely on the number of encrypted entries. That is why this + * function does not return the number of encrypted entries but# + * just shows that there are some. + */ +int +archive_read_has_encrypted_entries(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + int format_supports_encryption = archive_read_format_capabilities(_a) + & (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA | ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA); + + if (!_a || !format_supports_encryption) { + /* Format in general doesn't support encryption */ + return ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED; + } + + /* A reader potentially has read enough data now. */ + if (a->format && a->format->has_encrypted_entries) { + return (a->format->has_encrypted_entries)(a); + } + + /* For any other reason we cannot say how many entries are there. */ + return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; +} + +/* + * Returns a bitmask of capabilities that are supported by the archive format reader. + * If the reader has no special capabilities, ARCHIVE_READ_FORMAT_CAPS_NONE is returned. + */ +int +archive_read_format_capabilities(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + if (a && a->format && a->format->format_capabilties) { + return (a->format->format_capabilties)(a); + } + return ARCHIVE_READ_FORMAT_CAPS_NONE; +} + +/* + * Read data from an archive entry, using a read(2)-style interface. + * This is a convenience routine that just calls + * archive_read_data_block and copies the results into the client + * buffer, filling any gaps with zero bytes. Clients using this + * API can be completely ignorant of sparse-file issues; sparse files + * will simply be padded with nulls. + * + * DO NOT intermingle calls to this function and archive_read_data_block + * to read a single entry body. + */ +la_ssize_t +archive_read_data(struct archive *_a, void *buff, size_t s) +{ + struct archive *a = (struct archive *)_a; + char *dest; + const void *read_buf; + size_t bytes_read; + size_t len; + int r; + + bytes_read = 0; + dest = (char *)buff; + + while (s > 0) { + if (a->read_data_offset == a->read_data_output_offset && + a->read_data_remaining == 0) { + read_buf = a->read_data_block; + a->read_data_is_posix_read = 1; + a->read_data_requested = s; + r = archive_read_data_block(a, &read_buf, + &a->read_data_remaining, &a->read_data_offset); + a->read_data_block = read_buf; + if (r == ARCHIVE_EOF) + return (bytes_read); + /* + * Error codes are all negative, so the status + * return here cannot be confused with a valid + * byte count. (ARCHIVE_OK is zero.) + */ + if (r < ARCHIVE_OK) + return (r); + } + + if (a->read_data_offset < a->read_data_output_offset) { + archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT, + "Encountered out-of-order sparse blocks"); + return (ARCHIVE_RETRY); + } + + /* Compute the amount of zero padding needed. */ + if (a->read_data_output_offset + (int64_t)s < + a->read_data_offset) { + len = s; + } else if (a->read_data_output_offset < + a->read_data_offset) { + len = (size_t)(a->read_data_offset - + a->read_data_output_offset); + } else + len = 0; + + /* Add zeroes. */ + memset(dest, 0, len); + s -= len; + a->read_data_output_offset += len; + dest += len; + bytes_read += len; + + /* Copy data if there is any space left. */ + if (s > 0) { + len = a->read_data_remaining; + if (len > s) + len = s; + if (len) { + memcpy(dest, a->read_data_block, len); + s -= len; + a->read_data_block += len; + a->read_data_remaining -= len; + a->read_data_output_offset += len; + a->read_data_offset += len; + dest += len; + bytes_read += len; + } + } + } + a->read_data_is_posix_read = 0; + a->read_data_requested = 0; + return (bytes_read); +} + +/* + * Reset the read_data_* variables, used for starting a new entry. + */ +void __archive_reset_read_data(struct archive * a) +{ + a->read_data_output_offset = 0; + a->read_data_remaining = 0; + a->read_data_is_posix_read = 0; + a->read_data_requested = 0; + + /* extra resets, from rar.c */ + a->read_data_block = NULL; + a->read_data_offset = 0; +} + +/* + * Skip over all remaining data in this entry. + */ +int +archive_read_data_skip(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + int r; + const void *buff; + size_t size; + int64_t offset; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_DATA, + "archive_read_data_skip"); + + if (a->format->read_data_skip != NULL) + r = (a->format->read_data_skip)(a); + else { + while ((r = archive_read_data_block(&a->archive, + &buff, &size, &offset)) + == ARCHIVE_OK) + ; + } + + if (r == ARCHIVE_EOF) + r = ARCHIVE_OK; + + a->archive.state = ARCHIVE_STATE_HEADER; + return (r); +} + +la_int64_t +archive_seek_data(struct archive *_a, int64_t offset, int whence) +{ + struct archive_read *a = (struct archive_read *)_a; + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_DATA, + "archive_seek_data_block"); + + if (a->format->seek_data == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Internal error: " + "No format_seek_data_block function registered"); + return (ARCHIVE_FATAL); + } + + return (a->format->seek_data)(a, offset, whence); +} + +/* + * Read the next block of entry data from the archive. + * This is a zero-copy interface; the client receives a pointer, + * size, and file offset of the next available block of data. + * + * Returns ARCHIVE_OK if the operation is successful, ARCHIVE_EOF if + * the end of entry is encountered. + */ +static int +_archive_read_data_block(struct archive *_a, + const void **buff, size_t *size, int64_t *offset) +{ + struct archive_read *a = (struct archive_read *)_a; + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_DATA, + "archive_read_data_block"); + + if (a->format->read_data == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Internal error: " + "No format->read_data function registered"); + return (ARCHIVE_FATAL); + } + + return (a->format->read_data)(a, buff, size, offset); +} + +static int +close_filters(struct archive_read *a) +{ + struct archive_read_filter *f = a->filter; + int r = ARCHIVE_OK; + /* Close each filter in the pipeline. */ + while (f != NULL) { + struct archive_read_filter *t = f->upstream; + if (!f->closed && f->close != NULL) { + int r1 = (f->close)(f); + f->closed = 1; + if (r1 < r) + r = r1; + } + free(f->buffer); + f->buffer = NULL; + f = t; + } + return r; +} + +void +__archive_read_free_filters(struct archive_read *a) +{ + /* Make sure filters are closed and their buffers are freed */ + close_filters(a); + + while (a->filter != NULL) { + struct archive_read_filter *t = a->filter->upstream; + free(a->filter); + a->filter = t; + } +} + +/* + * return the count of # of filters in use + */ +static int +_archive_filter_count(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter *p = a->filter; + int count = 0; + while(p) { + count++; + p = p->upstream; + } + return count; +} + +/* + * Close the file and all I/O. + */ +static int +_archive_read_close(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + int r = ARCHIVE_OK, r1 = ARCHIVE_OK; + + archive_check_magic(&a->archive, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_read_close"); + if (a->archive.state == ARCHIVE_STATE_CLOSED) + return (ARCHIVE_OK); + archive_clear_error(&a->archive); + a->archive.state = ARCHIVE_STATE_CLOSED; + + /* TODO: Clean up the formatters. */ + + /* Release the filter objects. */ + r1 = close_filters(a); + if (r1 < r) + r = r1; + + return (r); +} + +/* + * Release memory and other resources. + */ +static int +_archive_read_free(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_passphrase *p; + int i, n; + int slots; + int r = ARCHIVE_OK; + + if (_a == NULL) + return (ARCHIVE_OK); + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_read_free"); + if (a->archive.state != ARCHIVE_STATE_CLOSED + && a->archive.state != ARCHIVE_STATE_FATAL) + r = archive_read_close(&a->archive); + + /* Call cleanup functions registered by optional components. */ + if (a->cleanup_archive_extract != NULL) + r = (a->cleanup_archive_extract)(a); + + /* Cleanup format-specific data. */ + slots = sizeof(a->formats) / sizeof(a->formats[0]); + for (i = 0; i < slots; i++) { + a->format = &(a->formats[i]); + if (a->formats[i].cleanup) + (a->formats[i].cleanup)(a); + } + + /* Free the filters */ + __archive_read_free_filters(a); + + /* Release the bidder objects. */ + n = sizeof(a->bidders)/sizeof(a->bidders[0]); + for (i = 0; i < n; i++) { + if (a->bidders[i].free != NULL) { + int r1 = (a->bidders[i].free)(&a->bidders[i]); + if (r1 < r) + r = r1; + } + } + + /* Release passphrase list. */ + p = a->passphrases.first; + while (p != NULL) { + struct archive_read_passphrase *np = p->next; + + /* A passphrase should be cleaned. */ + memset(p->passphrase, 0, strlen(p->passphrase)); + free(p->passphrase); + free(p); + p = np; + } + + archive_string_free(&a->archive.error_string); + archive_entry_free(a->entry); + a->archive.magic = 0; + __archive_clean(&a->archive); + free(a->client.dataset); + free(a); + return (r); +} + +static struct archive_read_filter * +get_filter(struct archive *_a, int n) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter *f = a->filter; + /* We use n == -1 for 'the last filter', which is always the + * client proxy. */ + if (n == -1 && f != NULL) { + struct archive_read_filter *last = f; + f = f->upstream; + while (f != NULL) { + last = f; + f = f->upstream; + } + return (last); + } + if (n < 0) + return NULL; + while (n > 0 && f != NULL) { + f = f->upstream; + --n; + } + return (f); +} + +static int +_archive_filter_code(struct archive *_a, int n) +{ + struct archive_read_filter *f = get_filter(_a, n); + return f == NULL ? -1 : f->code; +} + +static const char * +_archive_filter_name(struct archive *_a, int n) +{ + struct archive_read_filter *f = get_filter(_a, n); + return f != NULL ? f->name : NULL; +} + +static int64_t +_archive_filter_bytes(struct archive *_a, int n) +{ + struct archive_read_filter *f = get_filter(_a, n); + return f == NULL ? -1 : f->position; +} + +/* + * Used internally by read format handlers to register their bid and + * initialization functions. + */ +int +__archive_read_register_format(struct archive_read *a, + void *format_data, + const char *name, + int (*bid)(struct archive_read *, int), + int (*options)(struct archive_read *, const char *, const char *), + int (*read_header)(struct archive_read *, struct archive_entry *), + int (*read_data)(struct archive_read *, const void **, size_t *, int64_t *), + int (*read_data_skip)(struct archive_read *), + int64_t (*seek_data)(struct archive_read *, int64_t, int), + int (*cleanup)(struct archive_read *), + int (*format_capabilities)(struct archive_read *), + int (*has_encrypted_entries)(struct archive_read *)) +{ + int i, number_slots; + + archive_check_magic(&a->archive, + ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, + "__archive_read_register_format"); + + number_slots = sizeof(a->formats) / sizeof(a->formats[0]); + + for (i = 0; i < number_slots; i++) { + if (a->formats[i].bid == bid) + return (ARCHIVE_WARN); /* We've already installed */ + if (a->formats[i].bid == NULL) { + a->formats[i].bid = bid; + a->formats[i].options = options; + a->formats[i].read_header = read_header; + a->formats[i].read_data = read_data; + a->formats[i].read_data_skip = read_data_skip; + a->formats[i].seek_data = seek_data; + a->formats[i].cleanup = cleanup; + a->formats[i].data = format_data; + a->formats[i].name = name; + a->formats[i].format_capabilties = format_capabilities; + a->formats[i].has_encrypted_entries = has_encrypted_entries; + return (ARCHIVE_OK); + } + } + + archive_set_error(&a->archive, ENOMEM, + "Not enough slots for format registration"); + return (ARCHIVE_FATAL); +} + +/* + * Used internally by decompression routines to register their bid and + * initialization functions. + */ +int +__archive_read_get_bidder(struct archive_read *a, + struct archive_read_filter_bidder **bidder) +{ + int i, number_slots; + + number_slots = sizeof(a->bidders) / sizeof(a->bidders[0]); + + for (i = 0; i < number_slots; i++) { + if (a->bidders[i].bid == NULL) { + memset(a->bidders + i, 0, sizeof(a->bidders[0])); + *bidder = (a->bidders + i); + return (ARCHIVE_OK); + } + } + + archive_set_error(&a->archive, ENOMEM, + "Not enough slots for filter registration"); + return (ARCHIVE_FATAL); +} + +/* + * The next section implements the peek/consume internal I/O + * system used by archive readers. This system allows simple + * read-ahead for consumers while preserving zero-copy operation + * most of the time. + * + * The two key operations: + * * The read-ahead function returns a pointer to a block of data + * that satisfies a minimum request. + * * The consume function advances the file pointer. + * + * In the ideal case, filters generate blocks of data + * and __archive_read_ahead() just returns pointers directly into + * those blocks. Then __archive_read_consume() just bumps those + * pointers. Only if your request would span blocks does the I/O + * layer use a copy buffer to provide you with a contiguous block of + * data. + * + * A couple of useful idioms: + * * "I just want some data." Ask for 1 byte and pay attention to + * the "number of bytes available" from __archive_read_ahead(). + * Consume whatever you actually use. + * * "I want to output a large block of data." As above, ask for 1 byte, + * emit all that's available (up to whatever limit you have), consume + * it all, then repeat until you're done. This effectively means that + * you're passing along the blocks that came from your provider. + * * "I want to peek ahead by a large amount." Ask for 4k or so, then + * double and repeat until you get an error or have enough. Note + * that the I/O layer will likely end up expanding its copy buffer + * to fit your request, so use this technique cautiously. This + * technique is used, for example, by some of the format tasting + * code that has uncertain look-ahead needs. + */ + +/* + * Looks ahead in the input stream: + * * If 'avail' pointer is provided, that returns number of bytes available + * in the current buffer, which may be much larger than requested. + * * If end-of-file, *avail gets set to zero. + * * If error, *avail gets error code. + * * If request can be met, returns pointer to data. + * * If minimum request cannot be met, returns NULL. + * + * Note: If you just want "some data", ask for 1 byte and pay attention + * to *avail, which will have the actual amount available. If you + * know exactly how many bytes you need, just ask for that and treat + * a NULL return as an error. + * + * Important: This does NOT move the file pointer. See + * __archive_read_consume() below. + */ +const void * +__archive_read_ahead(struct archive_read *a, size_t min, ssize_t *avail) +{ + return (__archive_read_filter_ahead(a->filter, min, avail)); +} + +const void * +__archive_read_filter_ahead(struct archive_read_filter *filter, + size_t min, ssize_t *avail) +{ + ssize_t bytes_read; + size_t tocopy; + + if (filter->fatal) { + if (avail) + *avail = ARCHIVE_FATAL; + return (NULL); + } + + /* + * Keep pulling more data until we can satisfy the request. + */ + for (;;) { + + /* + * If we can satisfy from the copy buffer (and the + * copy buffer isn't empty), we're done. In particular, + * note that min == 0 is a perfectly well-defined + * request. + */ + if (filter->avail >= min && filter->avail > 0) { + if (avail != NULL) + *avail = filter->avail; + return (filter->next); + } + + /* + * We can satisfy directly from client buffer if everything + * currently in the copy buffer is still in the client buffer. + */ + if (filter->client_total >= filter->client_avail + filter->avail + && filter->client_avail + filter->avail >= min) { + /* "Roll back" to client buffer. */ + filter->client_avail += filter->avail; + filter->client_next -= filter->avail; + /* Copy buffer is now empty. */ + filter->avail = 0; + filter->next = filter->buffer; + /* Return data from client buffer. */ + if (avail != NULL) + *avail = filter->client_avail; + return (filter->client_next); + } + + /* Move data forward in copy buffer if necessary. */ + if (filter->next > filter->buffer && + filter->next + min > filter->buffer + filter->buffer_size) { + if (filter->avail > 0) + memmove(filter->buffer, filter->next, + filter->avail); + filter->next = filter->buffer; + } + + /* If we've used up the client data, get more. */ + if (filter->client_avail <= 0) { + if (filter->end_of_file) { + if (avail != NULL) + *avail = 0; + return (NULL); + } + bytes_read = (filter->read)(filter, + &filter->client_buff); + if (bytes_read < 0) { /* Read error. */ + filter->client_total = filter->client_avail = 0; + filter->client_next = + filter->client_buff = NULL; + filter->fatal = 1; + if (avail != NULL) + *avail = ARCHIVE_FATAL; + return (NULL); + } + if (bytes_read == 0) { + /* Check for another client object first */ + if (filter->archive->client.cursor != + filter->archive->client.nodes - 1) { + if (client_switch_proxy(filter, + filter->archive->client.cursor + 1) + == ARCHIVE_OK) + continue; + } + /* Premature end-of-file. */ + filter->client_total = filter->client_avail = 0; + filter->client_next = + filter->client_buff = NULL; + filter->end_of_file = 1; + /* Return whatever we do have. */ + if (avail != NULL) + *avail = filter->avail; + return (NULL); + } + filter->client_total = bytes_read; + filter->client_avail = filter->client_total; + filter->client_next = filter->client_buff; + } else { + /* + * We can't satisfy the request from the copy + * buffer or the existing client data, so we + * need to copy more client data over to the + * copy buffer. + */ + + /* Ensure the buffer is big enough. */ + if (min > filter->buffer_size) { + size_t s, t; + char *p; + + /* Double the buffer; watch for overflow. */ + s = t = filter->buffer_size; + if (s == 0) + s = min; + while (s < min) { + t *= 2; + if (t <= s) { /* Integer overflow! */ + archive_set_error( + &filter->archive->archive, + ENOMEM, + "Unable to allocate copy" + " buffer"); + filter->fatal = 1; + if (avail != NULL) + *avail = ARCHIVE_FATAL; + return (NULL); + } + s = t; + } + /* Now s >= min, so allocate a new buffer. */ + p = (char *)malloc(s); + if (p == NULL) { + archive_set_error( + &filter->archive->archive, + ENOMEM, + "Unable to allocate copy buffer"); + filter->fatal = 1; + if (avail != NULL) + *avail = ARCHIVE_FATAL; + return (NULL); + } + /* Move data into newly-enlarged buffer. */ + if (filter->avail > 0) + memmove(p, filter->next, filter->avail); + free(filter->buffer); + filter->next = filter->buffer = p; + filter->buffer_size = s; + } + + /* We can add client data to copy buffer. */ + /* First estimate: copy to fill rest of buffer. */ + tocopy = (filter->buffer + filter->buffer_size) + - (filter->next + filter->avail); + /* Don't waste time buffering more than we need to. */ + if (tocopy + filter->avail > min) + tocopy = min - filter->avail; + /* Don't copy more than is available. */ + if (tocopy > filter->client_avail) + tocopy = filter->client_avail; + + memcpy(filter->next + filter->avail, + filter->client_next, tocopy); + /* Remove this data from client buffer. */ + filter->client_next += tocopy; + filter->client_avail -= tocopy; + /* add it to copy buffer. */ + filter->avail += tocopy; + } + } +} + +/* + * Move the file pointer forward. + */ +int64_t +__archive_read_consume(struct archive_read *a, int64_t request) +{ + return (__archive_read_filter_consume(a->filter, request)); +} + +int64_t +__archive_read_filter_consume(struct archive_read_filter * filter, + int64_t request) +{ + int64_t skipped; + + if (request < 0) + return ARCHIVE_FATAL; + if (request == 0) + return 0; + + skipped = advance_file_pointer(filter, request); + if (skipped == request) + return (skipped); + /* We hit EOF before we satisfied the skip request. */ + if (skipped < 0) /* Map error code to 0 for error message below. */ + skipped = 0; + archive_set_error(&filter->archive->archive, + ARCHIVE_ERRNO_MISC, + "Truncated input file (needed %jd bytes, only %jd available)", + (intmax_t)request, (intmax_t)skipped); + return (ARCHIVE_FATAL); +} + +/* + * Advance the file pointer by the amount requested. + * Returns the amount actually advanced, which may be less than the + * request if EOF is encountered first. + * Returns a negative value if there's an I/O error. + */ +static int64_t +advance_file_pointer(struct archive_read_filter *filter, int64_t request) +{ + int64_t bytes_skipped, total_bytes_skipped = 0; + ssize_t bytes_read; + size_t min; + + if (filter->fatal) + return (-1); + + /* Use up the copy buffer first. */ + if (filter->avail > 0) { + min = (size_t)minimum(request, (int64_t)filter->avail); + filter->next += min; + filter->avail -= min; + request -= min; + filter->position += min; + total_bytes_skipped += min; + } + + /* Then use up the client buffer. */ + if (filter->client_avail > 0) { + min = (size_t)minimum(request, (int64_t)filter->client_avail); + filter->client_next += min; + filter->client_avail -= min; + request -= min; + filter->position += min; + total_bytes_skipped += min; + } + if (request == 0) + return (total_bytes_skipped); + + /* If there's an optimized skip function, use it. */ + if (filter->skip != NULL) { + bytes_skipped = (filter->skip)(filter, request); + if (bytes_skipped < 0) { /* error */ + filter->fatal = 1; + return (bytes_skipped); + } + filter->position += bytes_skipped; + total_bytes_skipped += bytes_skipped; + request -= bytes_skipped; + if (request == 0) + return (total_bytes_skipped); + } + + /* Use ordinary reads as necessary to complete the request. */ + for (;;) { + bytes_read = (filter->read)(filter, &filter->client_buff); + if (bytes_read < 0) { + filter->client_buff = NULL; + filter->fatal = 1; + return (bytes_read); + } + + if (bytes_read == 0) { + if (filter->archive->client.cursor != + filter->archive->client.nodes - 1) { + if (client_switch_proxy(filter, + filter->archive->client.cursor + 1) + == ARCHIVE_OK) + continue; + } + filter->client_buff = NULL; + filter->end_of_file = 1; + return (total_bytes_skipped); + } + + if (bytes_read >= request) { + filter->client_next = + ((const char *)filter->client_buff) + request; + filter->client_avail = (size_t)(bytes_read - request); + filter->client_total = bytes_read; + total_bytes_skipped += request; + filter->position += request; + return (total_bytes_skipped); + } + + filter->position += bytes_read; + total_bytes_skipped += bytes_read; + request -= bytes_read; + } +} + +/** + * Returns ARCHIVE_FAILED if seeking isn't supported. + */ +int64_t +__archive_read_seek(struct archive_read *a, int64_t offset, int whence) +{ + return __archive_read_filter_seek(a->filter, offset, whence); +} + +int64_t +__archive_read_filter_seek(struct archive_read_filter *filter, int64_t offset, + int whence) +{ + struct archive_read_client *client; + int64_t r; + unsigned int cursor; + + if (filter->closed || filter->fatal) + return (ARCHIVE_FATAL); + if (filter->seek == NULL) + return (ARCHIVE_FAILED); + + client = &(filter->archive->client); + switch (whence) { + case SEEK_CUR: + /* Adjust the offset and use SEEK_SET instead */ + offset += filter->position; + __LA_FALLTHROUGH; + case SEEK_SET: + cursor = 0; + while (1) + { + if (client->dataset[cursor].begin_position < 0 || + client->dataset[cursor].total_size < 0 || + client->dataset[cursor].begin_position + + client->dataset[cursor].total_size - 1 > offset || + cursor + 1 >= client->nodes) + break; + r = client->dataset[cursor].begin_position + + client->dataset[cursor].total_size; + client->dataset[++cursor].begin_position = r; + } + while (1) { + r = client_switch_proxy(filter, cursor); + if (r != ARCHIVE_OK) + return r; + if ((r = client_seek_proxy(filter, 0, SEEK_END)) < 0) + return r; + client->dataset[cursor].total_size = r; + if (client->dataset[cursor].begin_position + + client->dataset[cursor].total_size - 1 > offset || + cursor + 1 >= client->nodes) + break; + r = client->dataset[cursor].begin_position + + client->dataset[cursor].total_size; + client->dataset[++cursor].begin_position = r; + } + offset -= client->dataset[cursor].begin_position; + if (offset < 0 + || offset > client->dataset[cursor].total_size) + return ARCHIVE_FATAL; + if ((r = client_seek_proxy(filter, offset, SEEK_SET)) < 0) + return r; + break; + + case SEEK_END: + cursor = 0; + while (1) { + if (client->dataset[cursor].begin_position < 0 || + client->dataset[cursor].total_size < 0 || + cursor + 1 >= client->nodes) + break; + r = client->dataset[cursor].begin_position + + client->dataset[cursor].total_size; + client->dataset[++cursor].begin_position = r; + } + while (1) { + r = client_switch_proxy(filter, cursor); + if (r != ARCHIVE_OK) + return r; + if ((r = client_seek_proxy(filter, 0, SEEK_END)) < 0) + return r; + client->dataset[cursor].total_size = r; + r = client->dataset[cursor].begin_position + + client->dataset[cursor].total_size; + if (cursor + 1 >= client->nodes) + break; + client->dataset[++cursor].begin_position = r; + } + while (1) { + if (r + offset >= + client->dataset[cursor].begin_position) + break; + offset += client->dataset[cursor].total_size; + if (cursor == 0) + break; + cursor--; + r = client->dataset[cursor].begin_position + + client->dataset[cursor].total_size; + } + offset = (r + offset) - client->dataset[cursor].begin_position; + if ((r = client_switch_proxy(filter, cursor)) != ARCHIVE_OK) + return r; + r = client_seek_proxy(filter, offset, SEEK_SET); + if (r < ARCHIVE_OK) + return r; + break; + + default: + return (ARCHIVE_FATAL); + } + r += client->dataset[cursor].begin_position; + + if (r >= 0) { + /* + * Ouch. Clearing the buffer like this hurts, especially + * at bid time. A lot of our efficiency at bid time comes + * from having bidders reuse the data we've already read. + * + * TODO: If the seek request is in data we already + * have, then don't call the seek callback. + * + * TODO: Zip seeks to end-of-file at bid time. If + * other formats also start doing this, we may need to + * find a way for clients to fudge the seek offset to + * a block boundary. + * + * Hmmm... If whence was SEEK_END, we know the file + * size is (r - offset). Can we use that to simplify + * the TODO items above? + */ + filter->avail = filter->client_avail = 0; + filter->next = filter->buffer; + filter->position = r; + filter->end_of_file = 0; + } + return r; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_add_passphrase.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_add_passphrase.3 new file mode 100644 index 0000000000..ca60d4fc62 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_add_passphrase.3 @@ -0,0 +1,74 @@ +.\" Copyright (c) 2014 Michihiro NAKAJIMA +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd September 14, 2014 +.Dt ARCHIVE_READ_ADD_PASSPHRASE 3 +.Os +.Sh NAME +.Nm archive_read_add_passphrase , +.Nm archive_read_set_passphrase_callback +.Nd functions for reading encrypted archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fo archive_read_add_passphrase +.Fa "struct archive *" +.Fa "const char *passphrase" +.Fc +.Ft int +.Fo archive_read_set_passphrase_callback +.Fa "struct archive *" +.Fa "void *client_data" +.Fa "archive_passphrase_callback *" +.Fc +.Sh DESCRIPTION +.Bl -tag -width indent +.It Fn archive_read_add_passphrase +Register passphrases for reading an encryption archive. +If +.Ar passphrase +is +.Dv NULL +or empty, this function will do nothing and +.Cm ARCHIVE_FAILED +will be returned. +Otherwise, +.Cm ARCHIVE_OK +will be returned. +.It Fn archive_read_set_passphrase_callback +Register a callback function that will be invoked to get a passphrase +for decryption after trying all the passphrases registered by the +.Fn archive_read_add_passphrase +function failed. +.El +.\" .Sh ERRORS +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_read 3 , +.Xr archive_read_set_options 3 , +.Xr libarchive 3 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_add_passphrase.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_add_passphrase.c new file mode 100644 index 0000000000..f0b1ab9330 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_add_passphrase.c @@ -0,0 +1,190 @@ +/*- + * Copyright (c) 2014 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include "archive_read_private.h" + +static void +add_passphrase_to_tail(struct archive_read *a, + struct archive_read_passphrase *p) +{ + *a->passphrases.last = p; + a->passphrases.last = &p->next; + p->next = NULL; +} + +static struct archive_read_passphrase * +remove_passphrases_from_head(struct archive_read *a) +{ + struct archive_read_passphrase *p; + + p = a->passphrases.first; + if (p != NULL) + a->passphrases.first = p->next; + return (p); +} + +static void +insert_passphrase_to_head(struct archive_read *a, + struct archive_read_passphrase *p) +{ + p->next = a->passphrases.first; + a->passphrases.first = p; + if (&a->passphrases.first == a->passphrases.last) { + a->passphrases.last = &p->next; + p->next = NULL; + } +} + +static struct archive_read_passphrase * +new_read_passphrase(struct archive_read *a, const char *passphrase) +{ + struct archive_read_passphrase *p; + + p = malloc(sizeof(*p)); + if (p == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (NULL); + } + p->passphrase = strdup(passphrase); + if (p->passphrase == NULL) { + free(p); + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (NULL); + } + return (p); +} + +int +archive_read_add_passphrase(struct archive *_a, const char *passphrase) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_passphrase *p; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, + "archive_read_add_passphrase"); + + if (passphrase == NULL || passphrase[0] == '\0') { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Empty passphrase is unacceptable"); + return (ARCHIVE_FAILED); + } + + p = new_read_passphrase(a, passphrase); + if (p == NULL) + return (ARCHIVE_FATAL); + add_passphrase_to_tail(a, p); + + return (ARCHIVE_OK); +} + +int +archive_read_set_passphrase_callback(struct archive *_a, void *client_data, + archive_passphrase_callback *cb) +{ + struct archive_read *a = (struct archive_read *)_a; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, + "archive_read_set_passphrase_callback"); + + a->passphrases.callback = cb; + a->passphrases.client_data = client_data; + return (ARCHIVE_OK); +} + +/* + * Call this in advance when you start to get a passphrase for decryption + * for a entry. + */ +void +__archive_read_reset_passphrase(struct archive_read *a) +{ + + a->passphrases.candidate = -1; +} + +/* + * Get a passphrase for decryption. + */ +const char * +__archive_read_next_passphrase(struct archive_read *a) +{ + struct archive_read_passphrase *p; + const char *passphrase; + + if (a->passphrases.candidate < 0) { + /* Count out how many passphrases we have. */ + int cnt = 0; + + for (p = a->passphrases.first; p != NULL; p = p->next) + cnt++; + a->passphrases.candidate = cnt; + p = a->passphrases.first; + } else if (a->passphrases.candidate > 1) { + /* Rotate a passphrase list. */ + a->passphrases.candidate--; + p = remove_passphrases_from_head(a); + add_passphrase_to_tail(a, p); + /* Pick a new passphrase candidate up. */ + p = a->passphrases.first; + } else if (a->passphrases.candidate == 1) { + /* This case is that all candidates failed to decrypt. */ + a->passphrases.candidate = 0; + if (a->passphrases.first->next != NULL) { + /* Rotate a passphrase list. */ + p = remove_passphrases_from_head(a); + add_passphrase_to_tail(a, p); + } + p = NULL; + } else /* There is no passphrase candidate. */ + p = NULL; + + if (p != NULL) + passphrase = p->passphrase; + else if (a->passphrases.callback != NULL) { + /* Get a passphrase through a call-back function + * since we tried all passphrases out or we don't + * have it. */ + passphrase = a->passphrases.callback(&a->archive, + a->passphrases.client_data); + if (passphrase != NULL) { + p = new_read_passphrase(a, passphrase); + if (p == NULL) + return (NULL); + insert_passphrase_to_head(a, p); + a->passphrases.candidate = 1; + } + } else + passphrase = NULL; + + return (passphrase); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_append_filter.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_append_filter.c new file mode 100644 index 0000000000..da7c55b9b0 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_append_filter.c @@ -0,0 +1,204 @@ +/*- + * Copyright (c) 2003-2012 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_read_private.h" + +int +archive_read_append_filter(struct archive *_a, int code) +{ + int r1, r2, number_bidders, i; + char str[20]; + struct archive_read_filter_bidder *bidder; + struct archive_read_filter *filter; + struct archive_read *a = (struct archive_read *)_a; + + r2 = (ARCHIVE_OK); + switch (code) + { + case ARCHIVE_FILTER_NONE: + /* No filter to add, so do nothing. + * NOTE: An initial "NONE" type filter is always set at the end of the + * filter chain. + */ + r1 = (ARCHIVE_OK); + break; + case ARCHIVE_FILTER_GZIP: + strcpy(str, "gzip"); + r1 = archive_read_support_filter_gzip(_a); + break; + case ARCHIVE_FILTER_BZIP2: + strcpy(str, "bzip2"); + r1 = archive_read_support_filter_bzip2(_a); + break; + case ARCHIVE_FILTER_COMPRESS: + strcpy(str, "compress (.Z)"); + r1 = archive_read_support_filter_compress(_a); + break; + case ARCHIVE_FILTER_PROGRAM: + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Cannot append program filter using archive_read_append_filter"); + return (ARCHIVE_FATAL); + case ARCHIVE_FILTER_LZMA: + strcpy(str, "lzma"); + r1 = archive_read_support_filter_lzma(_a); + break; + case ARCHIVE_FILTER_XZ: + strcpy(str, "xz"); + r1 = archive_read_support_filter_xz(_a); + break; + case ARCHIVE_FILTER_UU: + strcpy(str, "uu"); + r1 = archive_read_support_filter_uu(_a); + break; + case ARCHIVE_FILTER_RPM: + strcpy(str, "rpm"); + r1 = archive_read_support_filter_rpm(_a); + break; + case ARCHIVE_FILTER_LZ4: + strcpy(str, "lz4"); + r1 = archive_read_support_filter_lz4(_a); + break; + case ARCHIVE_FILTER_ZSTD: + strcpy(str, "zstd"); + r1 = archive_read_support_filter_zstd(_a); + break; + case ARCHIVE_FILTER_LZIP: + strcpy(str, "lzip"); + r1 = archive_read_support_filter_lzip(_a); + break; + case ARCHIVE_FILTER_LRZIP: + strcpy(str, "lrzip"); + r1 = archive_read_support_filter_lrzip(_a); + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Invalid filter code specified"); + return (ARCHIVE_FATAL); + } + + if (code != ARCHIVE_FILTER_NONE) + { + number_bidders = sizeof(a->bidders) / sizeof(a->bidders[0]); + + bidder = a->bidders; + for (i = 0; i < number_bidders; i++, bidder++) + { + if (!bidder->name || !strcmp(bidder->name, str)) + break; + } + if (!bidder->name || strcmp(bidder->name, str)) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Internal error: Unable to append filter"); + return (ARCHIVE_FATAL); + } + + filter + = (struct archive_read_filter *)calloc(1, sizeof(*filter)); + if (filter == NULL) + { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + filter->bidder = bidder; + filter->archive = a; + filter->upstream = a->filter; + a->filter = filter; + r2 = (bidder->init)(a->filter); + if (r2 != ARCHIVE_OK) { + __archive_read_free_filters(a); + return (ARCHIVE_FATAL); + } + } + + a->bypass_filter_bidding = 1; + return (r1 < r2) ? r1 : r2; +} + +int +archive_read_append_filter_program(struct archive *_a, const char *cmd) +{ + return (archive_read_append_filter_program_signature(_a, cmd, NULL, 0)); +} + +int +archive_read_append_filter_program_signature(struct archive *_a, + const char *cmd, const void *signature, size_t signature_len) +{ + int r, number_bidders, i; + struct archive_read_filter_bidder *bidder; + struct archive_read_filter *filter; + struct archive_read *a = (struct archive_read *)_a; + + if (archive_read_support_filter_program_signature(_a, cmd, signature, + signature_len) != (ARCHIVE_OK)) + return (ARCHIVE_FATAL); + + number_bidders = sizeof(a->bidders) / sizeof(a->bidders[0]); + + bidder = a->bidders; + for (i = 0; i < number_bidders; i++, bidder++) + { + /* Program bidder name set to filter name after initialization */ + if (bidder->data && !bidder->name) + break; + } + if (!bidder->data) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Internal error: Unable to append program filter"); + return (ARCHIVE_FATAL); + } + + filter + = (struct archive_read_filter *)calloc(1, sizeof(*filter)); + if (filter == NULL) + { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + filter->bidder = bidder; + filter->archive = a; + filter->upstream = a->filter; + a->filter = filter; + r = (bidder->init)(a->filter); + if (r != ARCHIVE_OK) { + __archive_read_free_filters(a); + return (ARCHIVE_FATAL); + } + bidder->name = a->filter->name; + + a->bypass_filter_bidding = 1; + return r; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_data.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_data.3 new file mode 100644 index 0000000000..78c0c90004 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_data.3 @@ -0,0 +1,130 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_READ_DATA 3 +.Os +.Sh NAME +.Nm archive_read_data , +.Nm archive_read_data_block , +.Nm archive_read_data_skip , +.Nm archive_read_data_into_fd +.Nd functions for reading streaming archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft la_ssize_t +.Fn archive_read_data "struct archive *" "void *buff" "size_t len" +.Ft int +.Fo archive_read_data_block +.Fa "struct archive *" +.Fa "const void **buff" +.Fa "size_t *len" +.Fa "off_t *offset" +.Fc +.Ft int +.Fn archive_read_data_skip "struct archive *" +.Ft int +.Fn archive_read_data_into_fd "struct archive *" "int fd" +.\" +.Sh DESCRIPTION +.Bl -tag -compact -width indent +.It Fn archive_read_data +Read data associated with the header just read. +Internally, this is a convenience function that calls +.Fn archive_read_data_block +and fills any gaps with nulls so that callers see a single +continuous stream of data. +.It Fn archive_read_data_block +Return the next available block of data for this entry. +Unlike +.Fn archive_read_data , +the +.Fn archive_read_data_block +function avoids copying data and allows you to correctly handle +sparse files, as supported by some archive formats. +The library guarantees that offsets will increase and that blocks +will not overlap. +Note that the blocks returned from this function can be much larger +than the block size read from disk, due to compression +and internal buffer optimizations. +.It Fn archive_read_data_skip +A convenience function that repeatedly calls +.Fn archive_read_data_block +to skip all of the data for this archive entry. +Note that this function is invoked automatically by +.Fn archive_read_next_header2 +if the previous entry was not completely consumed. +.It Fn archive_read_data_into_fd +A convenience function that repeatedly calls +.Fn archive_read_data_block +to copy the entire entry to the provided file descriptor. +.El +.\" +.Sh RETURN VALUES +Most functions return zero on success, non-zero on error. +The possible return codes include: +.Cm ARCHIVE_OK +(the operation succeeded), +.Cm ARCHIVE_WARN +(the operation succeeded but a non-critical error was encountered), +.Cm ARCHIVE_EOF +(end-of-archive was encountered), +.Cm ARCHIVE_RETRY +(the operation failed but can be retried), +and +.Cm ARCHIVE_FATAL +(there was a fatal error; the archive should be closed immediately). +.Pp +.Fn archive_read_data +returns a count of bytes actually read or zero at the end of the entry. +On error, a value of +.Cm ARCHIVE_FATAL , +.Cm ARCHIVE_WARN , +or +.Cm ARCHIVE_RETRY +is returned. +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_read 3 , +.Xr archive_read_extract 3 , +.Xr archive_read_filter 3 , +.Xr archive_read_format 3 , +.Xr archive_read_header 3 , +.Xr archive_read_open 3 , +.Xr archive_read_set_options 3 , +.Xr archive_util 3 , +.Xr libarchive 3 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_data_into_fd.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_data_into_fd.c new file mode 100644 index 0000000000..b4398f1ecc --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_data_into_fd.c @@ -0,0 +1,139 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: src/lib/libarchive/archive_read_data_into_fd.c,v 1.16 2008/05/23 05:01:29 cperciva Exp $"); + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#include "archive.h" +#include "archive_private.h" + +/* Maximum amount of data to write at one time. */ +#define MAX_WRITE (1024 * 1024) + +/* + * This implementation minimizes copying of data and is sparse-file aware. + */ +static int +pad_to(struct archive *a, int fd, int can_lseek, + size_t nulls_size, const char *nulls, + int64_t target_offset, int64_t actual_offset) +{ + size_t to_write; + ssize_t bytes_written; + + if (can_lseek) { + actual_offset = lseek(fd, + target_offset - actual_offset, SEEK_CUR); + if (actual_offset != target_offset) { + archive_set_error(a, errno, "Seek error"); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_OK); + } + while (target_offset > actual_offset) { + to_write = nulls_size; + if (target_offset < actual_offset + (int64_t)nulls_size) + to_write = (size_t)(target_offset - actual_offset); + bytes_written = write(fd, nulls, to_write); + if (bytes_written < 0) { + archive_set_error(a, errno, "Write error"); + return (ARCHIVE_FATAL); + } + actual_offset += bytes_written; + } + return (ARCHIVE_OK); +} + + +int +archive_read_data_into_fd(struct archive *a, int fd) +{ + struct stat st; + int r, r2; + const void *buff; + size_t size, bytes_to_write; + ssize_t bytes_written; + int64_t target_offset; + int64_t actual_offset = 0; + int can_lseek; + char *nulls = NULL; + size_t nulls_size = 16384; + + archive_check_magic(a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_DATA, + "archive_read_data_into_fd"); + + can_lseek = (fstat(fd, &st) == 0) && S_ISREG(st.st_mode); + if (!can_lseek) + nulls = calloc(1, nulls_size); + + while ((r = archive_read_data_block(a, &buff, &size, &target_offset)) == + ARCHIVE_OK) { + const char *p = buff; + if (target_offset > actual_offset) { + r = pad_to(a, fd, can_lseek, nulls_size, nulls, + target_offset, actual_offset); + if (r != ARCHIVE_OK) + break; + actual_offset = target_offset; + } + while (size > 0) { + bytes_to_write = size; + if (bytes_to_write > MAX_WRITE) + bytes_to_write = MAX_WRITE; + bytes_written = write(fd, p, bytes_to_write); + if (bytes_written < 0) { + archive_set_error(a, errno, "Write error"); + r = ARCHIVE_FATAL; + goto cleanup; + } + actual_offset += bytes_written; + p += bytes_written; + size -= bytes_written; + } + } + + if (r == ARCHIVE_EOF && target_offset > actual_offset) { + r2 = pad_to(a, fd, can_lseek, nulls_size, nulls, + target_offset, actual_offset); + if (r2 != ARCHIVE_OK) + r = r2; + } + +cleanup: + free(nulls); + if (r != ARCHIVE_EOF) + return (r); + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk.3 new file mode 100644 index 0000000000..82d6a5c856 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk.3 @@ -0,0 +1,346 @@ +.\" Copyright (c) 2003-2009 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd April 3, 2017 +.Dt ARCHIVE_READ_DISK 3 +.Os +.Sh NAME +.Nm archive_read_disk_new , +.Nm archive_read_disk_set_behavior , +.Nm archive_read_disk_set_symlink_logical , +.Nm archive_read_disk_set_symlink_physical , +.Nm archive_read_disk_set_symlink_hybrid , +.Nm archive_read_disk_entry_from_file , +.Nm archive_read_disk_gname , +.Nm archive_read_disk_uname , +.Nm archive_read_disk_set_uname_lookup , +.Nm archive_read_disk_set_gname_lookup , +.Nm archive_read_disk_set_standard_lookup +.Nd functions for reading objects from disk +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft struct archive * +.Fn archive_read_disk_new "void" +.Ft int +.Fn archive_read_disk_set_behavior "struct archive *" "int" +.Ft int +.Fn archive_read_disk_set_symlink_logical "struct archive *" +.Ft int +.Fn archive_read_disk_set_symlink_physical "struct archive *" +.Ft int +.Fn archive_read_disk_set_symlink_hybrid "struct archive *" +.Ft const char * +.Fn archive_read_disk_gname "struct archive *" "gid_t" +.Ft const char * +.Fn archive_read_disk_uname "struct archive *" "uid_t" +.Ft int +.Fo archive_read_disk_set_gname_lookup +.Fa "struct archive *" +.Fa "void *" +.Fa "const char *(*lookup)(void *, gid_t)" +.Fa "void (*cleanup)(void *)" +.Fc +.Ft int +.Fo archive_read_disk_set_uname_lookup +.Fa "struct archive *" +.Fa "void *" +.Fa "const char *(*lookup)(void *, uid_t)" +.Fa "void (*cleanup)(void *)" +.Fc +.Ft int +.Fn archive_read_disk_set_standard_lookup "struct archive *" +.Ft int +.Fo archive_read_disk_entry_from_file +.Fa "struct archive *" +.Fa "struct archive_entry *" +.Fa "int fd" +.Fa "const struct stat *" +.Fc +.Sh DESCRIPTION +These functions provide an API for reading information about +objects on disk. +In particular, they provide an interface for populating +.Tn struct archive_entry +objects. +.Bl -tag -width indent +.It Fn archive_read_disk_new +Allocates and initializes a +.Tn struct archive +object suitable for reading object information from disk. +.It Fn archive_read_disk_set_behavior +Configures various behavior options when reading entries from disk. +The flags field consists of a bitwise OR of one or more of the +following values: +.Bl -tag -compact -width "indent" +.It Cm ARCHIVE_READDISK_HONOR_NODUMP +Skip files and directories with the nodump file attribute (file flag) set. +By default, the nodump file attribute is ignored. +.It Cm ARCHIVE_READDISK_MAC_COPYFILE +Mac OS X specific. +Read metadata (ACLs and extended attributes) with +.Xr copyfile 3 . +By default, metadata is read using +.Xr copyfile 3 . +.It Cm ARCHIVE_READDISK_NO_ACL +Do not read Access Control Lists. +By default, ACLs are read from disk. +.It Cm ARCHIVE_READDISK_NO_FFLAGS +Do not read file attributes (file flags). +By default, file attributes are read from disk. +See +.Xr chattr 1 +.Pq Linux +or +.Xr chflags 1 +.Pq FreeBSD, Mac OS X +for more information on file attributes. +.It Cm ARCHIVE_READDISK_NO_TRAVERSE_MOUNTS +Do not traverse mount points. +By default, mount points are traversed. +.It Cm ARCHIVE_READDISK_NO_XATTR +Do not read extended file attributes (xattrs). +By default, extended file attributes are read from disk. +See +.Xr xattr 7 +.Pq Linux , +.Xr xattr 2 +.Pq Mac OS X , +or +.Xr getextattr 8 +.Pq FreeBSD +for more information on extended file attributes. +.It Cm ARCHIVE_READDISK_RESTORE_ATIME +Restore access time of traversed files. +By default, access time of traversed files is not restored. +.El +.It Xo +.Fn archive_read_disk_set_symlink_logical , +.Fn archive_read_disk_set_symlink_physical , +.Fn archive_read_disk_set_symlink_hybrid +.Xc +This sets the mode used for handling symbolic links. +The +.Dq logical +mode follows all symbolic links. +The +.Dq physical +mode does not follow any symbolic links. +The +.Dq hybrid +mode currently behaves identically to the +.Dq logical +mode. +.It Xo +.Fn archive_read_disk_gname , +.Fn archive_read_disk_uname +.Xc +Returns a user or group name given a gid or uid value. +By default, these always return a NULL string. +.It Xo +.Fn archive_read_disk_set_gname_lookup , +.Fn archive_read_disk_set_uname_lookup +.Xc +These allow you to override the functions used for +user and group name lookups. +You may also provide a +.Tn void * +pointer to a private data structure and a cleanup function for +that data. +The cleanup function will be invoked when the +.Tn struct archive +object is destroyed or when new lookup functions are registered. +.It Fn archive_read_disk_set_standard_lookup +This convenience function installs a standard set of user +and group name lookup functions. +These functions use +.Xr getpwuid 3 +and +.Xr getgrgid 3 +to convert ids to names, defaulting to NULL if the names cannot +be looked up. +These functions also implement a simple memory cache to reduce +the number of calls to +.Xr getpwuid 3 +and +.Xr getgrgid 3 . +.It Fn archive_read_disk_entry_from_file +Populates a +.Tn struct archive_entry +object with information about a particular file. +The +.Tn archive_entry +object must have already been created with +.Xr archive_entry_new 3 +and at least one of the source path or path fields must already be set. +(If both are set, the source path will be used.) +.Pp +Information is read from disk using the path name from the +.Tn struct archive_entry +object. +If a file descriptor is provided, some information will be obtained using +that file descriptor, on platforms that support the appropriate +system calls. +.Pp +If a pointer to a +.Tn struct stat +is provided, information from that structure will be used instead +of reading from the disk where appropriate. +This can provide performance benefits in scenarios where +.Tn struct stat +information has already been read from the disk as a side effect +of some other operation. +(For example, directory traversal libraries often provide this information.) +.Pp +Where necessary, user and group ids are converted to user and group names +using the currently-registered lookup functions above. +This affects the file ownership fields and ACL values in the +.Tn struct archive_entry +object. +.El +More information about the +.Va struct archive +object and the overall design of the library can be found in the +.Xr libarchive 3 +overview. +.Sh EXAMPLES +The following illustrates basic usage of the library by +showing how to use it to copy an item on disk into an archive. +.Bd -literal -offset indent +void +file_to_archive(struct archive *a, const char *name) +{ + char buff[8192]; + size_t bytes_read; + struct archive *ard; + struct archive_entry *entry; + int fd; + + ard = archive_read_disk_new(); + archive_read_disk_set_standard_lookup(ard); + entry = archive_entry_new(); + fd = open(name, O_RDONLY); + if (fd < 0) + return; + archive_entry_copy_pathname(entry, name); + archive_read_disk_entry_from_file(ard, entry, fd, NULL); + archive_write_header(a, entry); + while ((bytes_read = read(fd, buff, sizeof(buff))) > 0) + archive_write_data(a, buff, bytes_read); + archive_write_finish_entry(a); + archive_read_free(ard); + archive_entry_free(entry); +} +.Ed +.Sh RETURN VALUES +Most functions return +.Cm ARCHIVE_OK +(zero) on success, or one of several negative +error codes for errors. +Specific error codes include: +.Cm ARCHIVE_RETRY +for operations that might succeed if retried, +.Cm ARCHIVE_WARN +for unusual conditions that do not prevent further operations, and +.Cm ARCHIVE_FATAL +for serious errors that make remaining operations impossible. +.Pp +.Fn archive_read_disk_new +returns a pointer to a newly-allocated +.Tn struct archive +object or NULL if the allocation failed for any reason. +.Pp +.Fn archive_read_disk_gname +and +.Fn archive_read_disk_uname +return +.Tn const char * +pointers to the textual name or NULL if the lookup failed for any reason. +The returned pointer points to internal storage that +may be reused on the next call to either of these functions; +callers should copy the string if they need to continue accessing it. +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_read 3 , +.Xr archive_util 3 , +.Xr archive_write 3 , +.Xr archive_write_disk 3 , +.Xr libarchive 3 +.Sh HISTORY +The +.Nm libarchive +library first appeared in +.Fx 5.3 . +The +.Nm archive_read_disk +interface was added to +.Nm libarchive 2.6 +and first appeared in +.Fx 8.0 . +.Sh AUTHORS +.An -nosplit +The +.Nm libarchive +library was written by +.An Tim Kientzle Aq kientzle@FreeBSD.org . +.Sh BUGS +The +.Dq standard +user name and group name lookup functions are not the defaults because +.Xr getgrgid 3 +and +.Xr getpwuid 3 +are sometimes too large for particular applications. +The current design allows the application author to use a more +compact implementation when appropriate. +.Pp +The full list of metadata read from disk by +.Fn archive_read_disk_entry_from_file +is necessarily system-dependent. +.Pp +The +.Fn archive_read_disk_entry_from_file +function reads as much information as it can from disk. +Some method should be provided to limit this so that clients who +do not need ACLs, for instance, can avoid the extra work needed +to look up such information. +.Pp +This API should provide a set of methods for walking a directory tree. +That would make it a direct parallel of the +.Xr archive_read 3 +API. +When such methods are implemented, the +.Dq hybrid +symbolic link mode will make sense. diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_entry_from_file.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_entry_from_file.c new file mode 100644 index 0000000000..2a8cec8d11 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_entry_from_file.c @@ -0,0 +1,1044 @@ +/*- + * Copyright (c) 2003-2009 Tim Kientzle + * Copyright (c) 2010-2012 Michihiro NAKAJIMA + * Copyright (c) 2016 Martin Matuska + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD"); + +/* This is the tree-walking code for POSIX systems. */ +#if !defined(_WIN32) || defined(__CYGWIN__) + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_EXTATTR_H +#include <sys/extattr.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#if defined(HAVE_SYS_XATTR_H) +#include <sys/xattr.h> +#elif defined(HAVE_ATTR_XATTR_H) +#include <attr/xattr.h> +#endif +#ifdef HAVE_SYS_EA_H +#include <sys/ea.h> +#endif +#ifdef HAVE_COPYFILE_H +#include <copyfile.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#ifdef HAVE_LINUX_TYPES_H +#include <linux/types.h> +#endif +#ifdef HAVE_LINUX_FIEMAP_H +#include <linux/fiemap.h> +#endif +#ifdef HAVE_LINUX_FS_H +#include <linux/fs.h> +#endif +/* + * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h. + * As the include guards don't agree, the order of include is important. + */ +#ifdef HAVE_LINUX_EXT2_FS_H +#include <linux/ext2_fs.h> /* for Linux file flags */ +#endif +#if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__) +#include <ext2fs/ext2_fs.h> /* Linux file flags, broken on Cygwin */ +#endif +#ifdef HAVE_PATHS_H +#include <paths.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_read_disk_private.h" + +#ifndef O_CLOEXEC +#define O_CLOEXEC 0 +#endif + +static int setup_mac_metadata(struct archive_read_disk *, + struct archive_entry *, int *fd); +static int setup_xattrs(struct archive_read_disk *, + struct archive_entry *, int *fd); +static int setup_sparse(struct archive_read_disk *, + struct archive_entry *, int *fd); +#if defined(HAVE_LINUX_FIEMAP_H) +static int setup_sparse_fiemap(struct archive_read_disk *, + struct archive_entry *, int *fd); +#endif + +#if !ARCHIVE_ACL_SUPPORT +int +archive_read_disk_entry_setup_acls(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + (void)a; /* UNUSED */ + (void)entry; /* UNUSED */ + (void)fd; /* UNUSED */ + return (ARCHIVE_OK); +} +#endif + +/* + * Enter working directory and return working pathname of archive_entry. + * If a pointer to an integer is provided and its value is below zero + * open a file descriptor on this pathname. + */ +const char * +archive_read_disk_entry_setup_path(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + const char *path; + + path = archive_entry_sourcepath(entry); + + if (path == NULL || (a->tree != NULL && + a->tree_enter_working_dir(a->tree) != 0)) + path = archive_entry_pathname(entry); + if (path == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Couldn't determine path"); + } else if (fd != NULL && *fd < 0 && a->tree != NULL && + (a->follow_symlinks || archive_entry_filetype(entry) != AE_IFLNK)) { + *fd = a->open_on_current_dir(a->tree, path, + O_RDONLY | O_NONBLOCK); + } + return (path); +} + +int +archive_read_disk_entry_from_file(struct archive *_a, + struct archive_entry *entry, + int fd, + const struct stat *st) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + const char *path, *name; + struct stat s; + int initial_fd = fd; + int r, r1; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_ANY, + "archive_read_disk_entry_from_file"); + + archive_clear_error(_a); + path = archive_entry_sourcepath(entry); + if (path == NULL) + path = archive_entry_pathname(entry); + + if (a->tree == NULL) { + if (st == NULL) { +#if HAVE_FSTAT + if (fd >= 0) { + if (fstat(fd, &s) != 0) { + archive_set_error(&a->archive, errno, + "Can't fstat"); + return (ARCHIVE_FAILED); + } + } else +#endif +#if HAVE_LSTAT + if (!a->follow_symlinks) { + if (lstat(path, &s) != 0) { + archive_set_error(&a->archive, errno, + "Can't lstat %s", path); + return (ARCHIVE_FAILED); + } + } else +#endif + if (la_stat(path, &s) != 0) { + archive_set_error(&a->archive, errno, + "Can't stat %s", path); + return (ARCHIVE_FAILED); + } + st = &s; + } + archive_entry_copy_stat(entry, st); + } + + /* Lookup uname/gname */ + name = archive_read_disk_uname(_a, archive_entry_uid(entry)); + if (name != NULL) + archive_entry_copy_uname(entry, name); + name = archive_read_disk_gname(_a, archive_entry_gid(entry)); + if (name != NULL) + archive_entry_copy_gname(entry, name); + +#ifdef HAVE_STRUCT_STAT_ST_FLAGS + /* On FreeBSD, we get flags for free with the stat. */ + /* TODO: Does this belong in copy_stat()? */ + if ((a->flags & ARCHIVE_READDISK_NO_FFLAGS) == 0 && st->st_flags != 0) + archive_entry_set_fflags(entry, st->st_flags, 0); +#endif + +#if (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS)) || \ + (defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS)) + /* Linux requires an extra ioctl to pull the flags. Although + * this is an extra step, it has a nice side-effect: We get an + * open file descriptor which we can use in the subsequent lookups. */ + if ((a->flags & ARCHIVE_READDISK_NO_FFLAGS) == 0 && + (S_ISREG(st->st_mode) || S_ISDIR(st->st_mode))) { + if (fd < 0) { + if (a->tree != NULL) + fd = a->open_on_current_dir(a->tree, path, + O_RDONLY | O_NONBLOCK | O_CLOEXEC); + else + fd = open(path, O_RDONLY | O_NONBLOCK | + O_CLOEXEC); + __archive_ensure_cloexec_flag(fd); + } + if (fd >= 0) { + int stflags; + r = ioctl(fd, +#if defined(FS_IOC_GETFLAGS) + FS_IOC_GETFLAGS, +#else + EXT2_IOC_GETFLAGS, +#endif + &stflags); + if (r == 0 && stflags != 0) + archive_entry_set_fflags(entry, stflags, 0); + } + } +#endif + +#if defined(HAVE_READLINK) || defined(HAVE_READLINKAT) + if (S_ISLNK(st->st_mode)) { + size_t linkbuffer_len = st->st_size; + char *linkbuffer; + int lnklen; + + linkbuffer = malloc(linkbuffer_len + 1); + if (linkbuffer == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Couldn't read link data"); + return (ARCHIVE_FAILED); + } + if (a->tree != NULL) { +#ifdef HAVE_READLINKAT + lnklen = readlinkat(a->tree_current_dir_fd(a->tree), + path, linkbuffer, linkbuffer_len); +#else + if (a->tree_enter_working_dir(a->tree) != 0) { + archive_set_error(&a->archive, errno, + "Couldn't read link data"); + free(linkbuffer); + return (ARCHIVE_FAILED); + } + lnklen = readlink(path, linkbuffer, linkbuffer_len); +#endif /* HAVE_READLINKAT */ + } else + lnklen = readlink(path, linkbuffer, linkbuffer_len); + if (lnklen < 0) { + archive_set_error(&a->archive, errno, + "Couldn't read link data"); + free(linkbuffer); + return (ARCHIVE_FAILED); + } + linkbuffer[lnklen] = '\0'; + archive_entry_set_symlink(entry, linkbuffer); + free(linkbuffer); + } +#endif /* HAVE_READLINK || HAVE_READLINKAT */ + + r = 0; + if ((a->flags & ARCHIVE_READDISK_NO_ACL) == 0) + r = archive_read_disk_entry_setup_acls(a, entry, &fd); + if ((a->flags & ARCHIVE_READDISK_NO_XATTR) == 0) { + r1 = setup_xattrs(a, entry, &fd); + if (r1 < r) + r = r1; + } + if (a->flags & ARCHIVE_READDISK_MAC_COPYFILE) { + r1 = setup_mac_metadata(a, entry, &fd); + if (r1 < r) + r = r1; + } + r1 = setup_sparse(a, entry, &fd); + if (r1 < r) + r = r1; + + /* If we opened the file earlier in this function, close it. */ + if (initial_fd != fd) + close(fd); + return (r); +} + +#if defined(__APPLE__) && defined(HAVE_COPYFILE_H) +/* + * The Mac OS "copyfile()" API copies the extended metadata for a + * file into a separate file in AppleDouble format (see RFC 1740). + * + * Mac OS tar and cpio implementations store this extended + * metadata as a separate entry just before the regular entry + * with a "._" prefix added to the filename. + * + * Note that this is currently done unconditionally; the tar program has + * an option to discard this information before the archive is written. + * + * TODO: If there's a failure, report it and return ARCHIVE_WARN. + */ +static int +setup_mac_metadata(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + int tempfd = -1; + int copyfile_flags = COPYFILE_NOFOLLOW | COPYFILE_ACL | COPYFILE_XATTR; + struct stat copyfile_stat; + int ret = ARCHIVE_OK; + void *buff = NULL; + int have_attrs; + const char *name, *tempdir; + struct archive_string tempfile; + + (void)fd; /* UNUSED */ + + name = archive_read_disk_entry_setup_path(a, entry, NULL); + if (name == NULL) + return (ARCHIVE_WARN); + + /* Short-circuit if there's nothing to do. */ + have_attrs = copyfile(name, NULL, 0, copyfile_flags | COPYFILE_CHECK); + if (have_attrs == -1) { + archive_set_error(&a->archive, errno, + "Could not check extended attributes"); + return (ARCHIVE_WARN); + } + if (have_attrs == 0) + return (ARCHIVE_OK); + + tempdir = NULL; + if (issetugid() == 0) + tempdir = getenv("TMPDIR"); + if (tempdir == NULL) + tempdir = _PATH_TMP; + archive_string_init(&tempfile); + archive_strcpy(&tempfile, tempdir); + archive_strcat(&tempfile, "tar.md.XXXXXX"); + tempfd = mkstemp(tempfile.s); + if (tempfd < 0) { + archive_set_error(&a->archive, errno, + "Could not open extended attribute file"); + ret = ARCHIVE_WARN; + goto cleanup; + } + __archive_ensure_cloexec_flag(tempfd); + + /* XXX I wish copyfile() could pack directly to a memory + * buffer; that would avoid the temp file here. For that + * matter, it would be nice if fcopyfile() actually worked, + * that would reduce the many open/close races here. */ + if (copyfile(name, tempfile.s, 0, copyfile_flags | COPYFILE_PACK)) { + archive_set_error(&a->archive, errno, + "Could not pack extended attributes"); + ret = ARCHIVE_WARN; + goto cleanup; + } + if (fstat(tempfd, ©file_stat)) { + archive_set_error(&a->archive, errno, + "Could not check size of extended attributes"); + ret = ARCHIVE_WARN; + goto cleanup; + } + buff = malloc(copyfile_stat.st_size); + if (buff == NULL) { + archive_set_error(&a->archive, errno, + "Could not allocate memory for extended attributes"); + ret = ARCHIVE_WARN; + goto cleanup; + } + if (copyfile_stat.st_size != read(tempfd, buff, copyfile_stat.st_size)) { + archive_set_error(&a->archive, errno, + "Could not read extended attributes into memory"); + ret = ARCHIVE_WARN; + goto cleanup; + } + archive_entry_copy_mac_metadata(entry, buff, copyfile_stat.st_size); + +cleanup: + if (tempfd >= 0) { + close(tempfd); + unlink(tempfile.s); + } + archive_string_free(&tempfile); + free(buff); + return (ret); +} + +#else + +/* + * Stub implementation for non-Mac systems. + */ +static int +setup_mac_metadata(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + (void)a; /* UNUSED */ + (void)entry; /* UNUSED */ + (void)fd; /* UNUSED */ + return (ARCHIVE_OK); +} +#endif + +#if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_AIX + +/* + * Linux, Darwin and AIX extended attribute support. + * + * TODO: By using a stack-allocated buffer for the first + * call to getxattr(), we might be able to avoid the second + * call entirely. We only need the second call if the + * stack-allocated buffer is too small. But a modest buffer + * of 1024 bytes or so will often be big enough. Same applies + * to listxattr(). + */ + + +static int +setup_xattr(struct archive_read_disk *a, + struct archive_entry *entry, const char *name, int fd, const char *accpath) +{ + ssize_t size; + void *value = NULL; + + + if (fd >= 0) { +#if ARCHIVE_XATTR_LINUX + size = fgetxattr(fd, name, NULL, 0); +#elif ARCHIVE_XATTR_DARWIN + size = fgetxattr(fd, name, NULL, 0, 0, 0); +#elif ARCHIVE_XATTR_AIX + size = fgetea(fd, name, NULL, 0); +#endif + } else if (!a->follow_symlinks) { +#if ARCHIVE_XATTR_LINUX + size = lgetxattr(accpath, name, NULL, 0); +#elif ARCHIVE_XATTR_DARWIN + size = getxattr(accpath, name, NULL, 0, 0, XATTR_NOFOLLOW); +#elif ARCHIVE_XATTR_AIX + size = lgetea(accpath, name, NULL, 0); +#endif + } else { +#if ARCHIVE_XATTR_LINUX + size = getxattr(accpath, name, NULL, 0); +#elif ARCHIVE_XATTR_DARWIN + size = getxattr(accpath, name, NULL, 0, 0, 0); +#elif ARCHIVE_XATTR_AIX + size = getea(accpath, name, NULL, 0); +#endif + } + + if (size == -1) { + archive_set_error(&a->archive, errno, + "Couldn't query extended attribute"); + return (ARCHIVE_WARN); + } + + if (size > 0 && (value = malloc(size)) == NULL) { + archive_set_error(&a->archive, errno, "Out of memory"); + return (ARCHIVE_FATAL); + } + + + if (fd >= 0) { +#if ARCHIVE_XATTR_LINUX + size = fgetxattr(fd, name, value, size); +#elif ARCHIVE_XATTR_DARWIN + size = fgetxattr(fd, name, value, size, 0, 0); +#elif ARCHIVE_XATTR_AIX + size = fgetea(fd, name, value, size); +#endif + } else if (!a->follow_symlinks) { +#if ARCHIVE_XATTR_LINUX + size = lgetxattr(accpath, name, value, size); +#elif ARCHIVE_XATTR_DARWIN + size = getxattr(accpath, name, value, size, 0, XATTR_NOFOLLOW); +#elif ARCHIVE_XATTR_AIX + size = lgetea(accpath, name, value, size); +#endif + } else { +#if ARCHIVE_XATTR_LINUX + size = getxattr(accpath, name, value, size); +#elif ARCHIVE_XATTR_DARWIN + size = getxattr(accpath, name, value, size, 0, 0); +#elif ARCHIVE_XATTR_AIX + size = getea(accpath, name, value, size); +#endif + } + + if (size == -1) { + archive_set_error(&a->archive, errno, + "Couldn't read extended attribute"); + return (ARCHIVE_WARN); + } + + archive_entry_xattr_add_entry(entry, name, value, size); + + free(value); + return (ARCHIVE_OK); +} + +static int +setup_xattrs(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + char *list, *p; + const char *path; + ssize_t list_size; + + path = NULL; + + if (*fd < 0) { + path = archive_read_disk_entry_setup_path(a, entry, fd); + if (path == NULL) + return (ARCHIVE_WARN); + } + + if (*fd >= 0) { +#if ARCHIVE_XATTR_LINUX + list_size = flistxattr(*fd, NULL, 0); +#elif ARCHIVE_XATTR_DARWIN + list_size = flistxattr(*fd, NULL, 0, 0); +#elif ARCHIVE_XATTR_AIX + list_size = flistea(*fd, NULL, 0); +#endif + } else if (!a->follow_symlinks) { +#if ARCHIVE_XATTR_LINUX + list_size = llistxattr(path, NULL, 0); +#elif ARCHIVE_XATTR_DARWIN + list_size = listxattr(path, NULL, 0, XATTR_NOFOLLOW); +#elif ARCHIVE_XATTR_AIX + list_size = llistea(path, NULL, 0); +#endif + } else { +#if ARCHIVE_XATTR_LINUX + list_size = listxattr(path, NULL, 0); +#elif ARCHIVE_XATTR_DARWIN + list_size = listxattr(path, NULL, 0, 0); +#elif ARCHIVE_XATTR_AIX + list_size = listea(path, NULL, 0); +#endif + } + + if (list_size == -1) { + if (errno == ENOTSUP || errno == ENOSYS) + return (ARCHIVE_OK); + archive_set_error(&a->archive, errno, + "Couldn't list extended attributes"); + return (ARCHIVE_WARN); + } + + if (list_size == 0) + return (ARCHIVE_OK); + + if ((list = malloc(list_size)) == NULL) { + archive_set_error(&a->archive, errno, "Out of memory"); + return (ARCHIVE_FATAL); + } + + if (*fd >= 0) { +#if ARCHIVE_XATTR_LINUX + list_size = flistxattr(*fd, list, list_size); +#elif ARCHIVE_XATTR_DARWIN + list_size = flistxattr(*fd, list, list_size, 0); +#elif ARCHIVE_XATTR_AIX + list_size = flistea(*fd, list, list_size); +#endif + } else if (!a->follow_symlinks) { +#if ARCHIVE_XATTR_LINUX + list_size = llistxattr(path, list, list_size); +#elif ARCHIVE_XATTR_DARWIN + list_size = listxattr(path, list, list_size, XATTR_NOFOLLOW); +#elif ARCHIVE_XATTR_AIX + list_size = llistea(path, list, list_size); +#endif + } else { +#if ARCHIVE_XATTR_LINUX + list_size = listxattr(path, list, list_size); +#elif ARCHIVE_XATTR_DARWIN + list_size = listxattr(path, list, list_size, 0); +#elif ARCHIVE_XATTR_AIX + list_size = listea(path, list, list_size); +#endif + } + + if (list_size == -1) { + archive_set_error(&a->archive, errno, + "Couldn't retrieve extended attributes"); + free(list); + return (ARCHIVE_WARN); + } + + for (p = list; (p - list) < list_size; p += strlen(p) + 1) { +#if ARCHIVE_XATTR_LINUX + /* Linux: skip POSIX.1e ACL extended attributes */ + if (strncmp(p, "system.", 7) == 0 && + (strcmp(p + 7, "posix_acl_access") == 0 || + strcmp(p + 7, "posix_acl_default") == 0)) + continue; + if (strncmp(p, "trusted.SGI_", 12) == 0 && + (strcmp(p + 12, "ACL_DEFAULT") == 0 || + strcmp(p + 12, "ACL_FILE") == 0)) + continue; + + /* Linux: xfsroot namespace is obsolete and unsupported */ + if (strncmp(p, "xfsroot.", 8) == 0) + continue; +#endif + setup_xattr(a, entry, p, *fd, path); + } + + free(list); + return (ARCHIVE_OK); +} + +#elif ARCHIVE_XATTR_FREEBSD + +/* + * FreeBSD extattr interface. + */ + +/* TODO: Implement this. Follow the Linux model above, but + * with FreeBSD-specific system calls, of course. Be careful + * to not include the system extattrs that hold ACLs; we handle + * those separately. + */ +static int +setup_xattr(struct archive_read_disk *a, struct archive_entry *entry, + int namespace, const char *name, const char *fullname, int fd, + const char *path); + +static int +setup_xattr(struct archive_read_disk *a, struct archive_entry *entry, + int namespace, const char *name, const char *fullname, int fd, + const char *accpath) +{ + ssize_t size; + void *value = NULL; + + if (fd >= 0) + size = extattr_get_fd(fd, namespace, name, NULL, 0); + else if (!a->follow_symlinks) + size = extattr_get_link(accpath, namespace, name, NULL, 0); + else + size = extattr_get_file(accpath, namespace, name, NULL, 0); + + if (size == -1) { + archive_set_error(&a->archive, errno, + "Couldn't query extended attribute"); + return (ARCHIVE_WARN); + } + + if (size > 0 && (value = malloc(size)) == NULL) { + archive_set_error(&a->archive, errno, "Out of memory"); + return (ARCHIVE_FATAL); + } + + if (fd >= 0) + size = extattr_get_fd(fd, namespace, name, value, size); + else if (!a->follow_symlinks) + size = extattr_get_link(accpath, namespace, name, value, size); + else + size = extattr_get_file(accpath, namespace, name, value, size); + + if (size == -1) { + free(value); + archive_set_error(&a->archive, errno, + "Couldn't read extended attribute"); + return (ARCHIVE_WARN); + } + + archive_entry_xattr_add_entry(entry, fullname, value, size); + + free(value); + return (ARCHIVE_OK); +} + +static int +setup_xattrs(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + char buff[512]; + char *list, *p; + ssize_t list_size; + const char *path; + int namespace = EXTATTR_NAMESPACE_USER; + + path = NULL; + + if (*fd < 0) { + path = archive_read_disk_entry_setup_path(a, entry, fd); + if (path == NULL) + return (ARCHIVE_WARN); + } + + if (*fd >= 0) + list_size = extattr_list_fd(*fd, namespace, NULL, 0); + else if (!a->follow_symlinks) + list_size = extattr_list_link(path, namespace, NULL, 0); + else + list_size = extattr_list_file(path, namespace, NULL, 0); + + if (list_size == -1 && errno == EOPNOTSUPP) + return (ARCHIVE_OK); + if (list_size == -1) { + archive_set_error(&a->archive, errno, + "Couldn't list extended attributes"); + return (ARCHIVE_WARN); + } + + if (list_size == 0) + return (ARCHIVE_OK); + + if ((list = malloc(list_size)) == NULL) { + archive_set_error(&a->archive, errno, "Out of memory"); + return (ARCHIVE_FATAL); + } + + if (*fd >= 0) + list_size = extattr_list_fd(*fd, namespace, list, list_size); + else if (!a->follow_symlinks) + list_size = extattr_list_link(path, namespace, list, list_size); + else + list_size = extattr_list_file(path, namespace, list, list_size); + + if (list_size == -1) { + archive_set_error(&a->archive, errno, + "Couldn't retrieve extended attributes"); + free(list); + return (ARCHIVE_WARN); + } + + p = list; + while ((p - list) < list_size) { + size_t len = 255 & (int)*p; + char *name; + + strcpy(buff, "user."); + name = buff + strlen(buff); + memcpy(name, p + 1, len); + name[len] = '\0'; + setup_xattr(a, entry, namespace, name, buff, *fd, path); + p += 1 + len; + } + + free(list); + return (ARCHIVE_OK); +} + +#else + +/* + * Generic (stub) extended attribute support. + */ +static int +setup_xattrs(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + (void)a; /* UNUSED */ + (void)entry; /* UNUSED */ + (void)fd; /* UNUSED */ + return (ARCHIVE_OK); +} + +#endif + +#if defined(HAVE_LINUX_FIEMAP_H) + +/* + * Linux FIEMAP sparse interface. + * + * The FIEMAP ioctl returns an "extent" for each physical allocation + * on disk. We need to process those to generate a more compact list + * of logical file blocks. We also need to be very careful to use + * FIEMAP_FLAG_SYNC here, since there are reports that Linux sometimes + * does not report allocations for newly-written data that hasn't + * been synced to disk. + * + * It's important to return a minimal sparse file list because we want + * to not trigger sparse file extensions if we don't have to, since + * not all readers support them. + */ + +static int +setup_sparse_fiemap(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + char buff[4096]; + struct fiemap *fm; + struct fiemap_extent *fe; + int64_t size; + int count, do_fiemap, iters; + int exit_sts = ARCHIVE_OK; + const char *path; + + if (archive_entry_filetype(entry) != AE_IFREG + || archive_entry_size(entry) <= 0 + || archive_entry_hardlink(entry) != NULL) + return (ARCHIVE_OK); + + if (*fd < 0) { + path = archive_read_disk_entry_setup_path(a, entry, NULL); + if (path == NULL) + return (ARCHIVE_FAILED); + + if (a->tree != NULL) + *fd = a->open_on_current_dir(a->tree, path, + O_RDONLY | O_NONBLOCK | O_CLOEXEC); + else + *fd = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC); + if (*fd < 0) { + archive_set_error(&a->archive, errno, + "Can't open `%s'", path); + return (ARCHIVE_FAILED); + } + __archive_ensure_cloexec_flag(*fd); + } + + /* Initialize buffer to avoid the error valgrind complains about. */ + memset(buff, 0, sizeof(buff)); + count = (sizeof(buff) - sizeof(*fm))/sizeof(*fe); + fm = (struct fiemap *)buff; + fm->fm_start = 0; + fm->fm_length = ~0ULL;; + fm->fm_flags = FIEMAP_FLAG_SYNC; + fm->fm_extent_count = count; + do_fiemap = 1; + size = archive_entry_size(entry); + for (iters = 0; ; ++iters) { + int i, r; + + r = ioctl(*fd, FS_IOC_FIEMAP, fm); + if (r < 0) { + /* When something error happens, it is better we + * should return ARCHIVE_OK because an earlier + * version(<2.6.28) cannot perform FS_IOC_FIEMAP. */ + goto exit_setup_sparse_fiemap; + } + if (fm->fm_mapped_extents == 0) { + if (iters == 0) { + /* Fully sparse file; insert a zero-length "data" entry */ + archive_entry_sparse_add_entry(entry, 0, 0); + } + break; + } + fe = fm->fm_extents; + for (i = 0; i < (int)fm->fm_mapped_extents; i++, fe++) { + if (!(fe->fe_flags & FIEMAP_EXTENT_UNWRITTEN)) { + /* The fe_length of the last block does not + * adjust itself to its size files. */ + int64_t length = fe->fe_length; + if (fe->fe_logical + length > (uint64_t)size) + length -= fe->fe_logical + length - size; + if (fe->fe_logical == 0 && length == size) { + /* This is not sparse. */ + do_fiemap = 0; + break; + } + if (length > 0) + archive_entry_sparse_add_entry(entry, + fe->fe_logical, length); + } + if (fe->fe_flags & FIEMAP_EXTENT_LAST) + do_fiemap = 0; + } + if (do_fiemap) { + fe = fm->fm_extents + fm->fm_mapped_extents -1; + fm->fm_start = fe->fe_logical + fe->fe_length; + } else + break; + } +exit_setup_sparse_fiemap: + return (exit_sts); +} + +#if !defined(SEEK_HOLE) || !defined(SEEK_DATA) +static int +setup_sparse(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + return setup_sparse_fiemap(a, entry, fd); +} +#endif +#endif /* defined(HAVE_LINUX_FIEMAP_H) */ + +#if defined(SEEK_HOLE) && defined(SEEK_DATA) + +/* + * SEEK_HOLE sparse interface (FreeBSD, Linux, Solaris) + */ + +static int +setup_sparse(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + int64_t size; + off_t initial_off; + off_t off_s, off_e; + int exit_sts = ARCHIVE_OK; + int check_fully_sparse = 0; + const char *path; + + if (archive_entry_filetype(entry) != AE_IFREG + || archive_entry_size(entry) <= 0 + || archive_entry_hardlink(entry) != NULL) + return (ARCHIVE_OK); + + /* Does filesystem support the reporting of hole ? */ + if (*fd < 0) + path = archive_read_disk_entry_setup_path(a, entry, fd); + else + path = NULL; + + if (*fd >= 0) { +#ifdef _PC_MIN_HOLE_SIZE + if (fpathconf(*fd, _PC_MIN_HOLE_SIZE) <= 0) + return (ARCHIVE_OK); +#endif + initial_off = lseek(*fd, 0, SEEK_CUR); + if (initial_off != 0) + lseek(*fd, 0, SEEK_SET); + } else { + if (path == NULL) + return (ARCHIVE_FAILED); +#ifdef _PC_MIN_HOLE_SIZE + if (pathconf(path, _PC_MIN_HOLE_SIZE) <= 0) + return (ARCHIVE_OK); +#endif + *fd = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC); + if (*fd < 0) { + archive_set_error(&a->archive, errno, + "Can't open `%s'", path); + return (ARCHIVE_FAILED); + } + __archive_ensure_cloexec_flag(*fd); + initial_off = 0; + } + +#ifndef _PC_MIN_HOLE_SIZE + /* Check if the underlying filesystem supports seek hole */ + off_s = lseek(*fd, 0, SEEK_HOLE); + if (off_s < 0) +#if defined(HAVE_LINUX_FIEMAP_H) + return setup_sparse_fiemap(a, entry, fd); +#else + goto exit_setup_sparse; +#endif + else if (off_s > 0) + lseek(*fd, 0, SEEK_SET); +#endif + + off_s = 0; + size = archive_entry_size(entry); + while (off_s < size) { + off_s = lseek(*fd, off_s, SEEK_DATA); + if (off_s == (off_t)-1) { + if (errno == ENXIO) { + /* no more hole */ + if (archive_entry_sparse_count(entry) == 0) { + /* Potentially a fully-sparse file. */ + check_fully_sparse = 1; + } + break; + } + archive_set_error(&a->archive, errno, + "lseek(SEEK_HOLE) failed"); + exit_sts = ARCHIVE_FAILED; + goto exit_setup_sparse; + } + off_e = lseek(*fd, off_s, SEEK_HOLE); + if (off_e == (off_t)-1) { + if (errno == ENXIO) { + off_e = lseek(*fd, 0, SEEK_END); + if (off_e != (off_t)-1) + break;/* no more data */ + } + archive_set_error(&a->archive, errno, + "lseek(SEEK_DATA) failed"); + exit_sts = ARCHIVE_FAILED; + goto exit_setup_sparse; + } + if (off_s == 0 && off_e == size) + break;/* This is not sparse. */ + archive_entry_sparse_add_entry(entry, off_s, + off_e - off_s); + off_s = off_e; + } + + if (check_fully_sparse) { + if (lseek(*fd, 0, SEEK_HOLE) == 0 && + lseek(*fd, 0, SEEK_END) == size) { + /* Fully sparse file; insert a zero-length "data" entry */ + archive_entry_sparse_add_entry(entry, 0, 0); + } + } +exit_setup_sparse: + lseek(*fd, initial_off, SEEK_SET); + return (exit_sts); +} + +#elif !defined(HAVE_LINUX_FIEMAP_H) + +/* + * Generic (stub) sparse support. + */ +static int +setup_sparse(struct archive_read_disk *a, + struct archive_entry *entry, int *fd) +{ + (void)a; /* UNUSED */ + (void)entry; /* UNUSED */ + (void)fd; /* UNUSED */ + return (ARCHIVE_OK); +} + +#endif + +#endif /* !defined(_WIN32) || defined(__CYGWIN__) */ + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_posix.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_posix.c new file mode 100644 index 0000000000..2898206951 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_posix.c @@ -0,0 +1,2722 @@ +/*- + * Copyright (c) 2003-2009 Tim Kientzle + * Copyright (c) 2010-2012 Michihiro NAKAJIMA + * 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 + * in this position and unchanged. + * 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(S) ``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(S) 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. + */ + +/* This is the tree-walking code for POSIX systems. */ +#if !defined(_WIN32) || defined(__CYGWIN__) + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif +#ifdef HAVE_SYS_MOUNT_H +#include <sys/mount.h> +#endif +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_SYS_STATFS_H +#include <sys/statfs.h> +#endif +#ifdef HAVE_SYS_STATVFS_H +#include <sys/statvfs.h> +#endif +#ifdef HAVE_SYS_TIME_H +#include <sys/time.h> +#endif +#ifdef HAVE_LINUX_MAGIC_H +#include <linux/magic.h> +#endif +#ifdef HAVE_LINUX_FS_H +#include <linux/fs.h> +#endif +/* + * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h. + * As the include guards don't agree, the order of include is important. + */ +#ifdef HAVE_LINUX_EXT2_FS_H +#include <linux/ext2_fs.h> /* for Linux file flags */ +#endif +#if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__) +#include <ext2fs/ext2_fs.h> /* Linux file flags, broken on Cygwin */ +#endif +#ifdef HAVE_DIRECT_H +#include <direct.h> +#endif +#ifdef HAVE_DIRENT_H +#include <dirent.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif + +#include "archive.h" +#include "archive_string.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_read_disk_private.h" + +#ifndef HAVE_FCHDIR +#error fchdir function required. +#endif +#ifndef O_BINARY +#define O_BINARY 0 +#endif +#ifndef O_CLOEXEC +#define O_CLOEXEC 0 +#endif + +/*- + * This is a new directory-walking system that addresses a number + * of problems I've had with fts(3). In particular, it has no + * pathname-length limits (other than the size of 'int'), handles + * deep logical traversals, uses considerably less memory, and has + * an opaque interface (easier to modify in the future). + * + * Internally, it keeps a single list of "tree_entry" items that + * represent filesystem objects that require further attention. + * Non-directories are not kept in memory: they are pulled from + * readdir(), returned to the client, then freed as soon as possible. + * Any directory entry to be traversed gets pushed onto the stack. + * + * There is surprisingly little information that needs to be kept for + * each item on the stack. Just the name, depth (represented here as the + * string length of the parent directory's pathname), and some markers + * indicating how to get back to the parent (via chdir("..") for a + * regular dir or via fchdir(2) for a symlink). + */ +/* + * TODO: + * 1) Loop checking. + * 3) Arbitrary logical traversals by closing/reopening intermediate fds. + */ + +struct restore_time { + const char *name; + time_t mtime; + long mtime_nsec; + time_t atime; + long atime_nsec; + mode_t filetype; + int noatime; +}; + +struct tree_entry { + int depth; + struct tree_entry *next; + struct tree_entry *parent; + struct archive_string name; + size_t dirname_length; + int64_t dev; + int64_t ino; + int flags; + int filesystem_id; + /* How to return back to the parent of a symlink. */ + int symlink_parent_fd; + /* How to restore time of a directory. */ + struct restore_time restore_time; +}; + +struct filesystem { + int64_t dev; + int synthetic; + int remote; + int noatime; +#if defined(USE_READDIR_R) + size_t name_max; +#endif + long incr_xfer_size; + long max_xfer_size; + long min_xfer_size; + long xfer_align; + + /* + * Buffer used for reading file contents. + */ + /* Exactly allocated memory pointer. */ + unsigned char *allocation_ptr; + /* Pointer adjusted to the filesystem alignment . */ + unsigned char *buff; + size_t buff_size; +}; + +/* Definitions for tree_entry.flags bitmap. */ +#define isDir 1 /* This entry is a regular directory. */ +#define isDirLink 2 /* This entry is a symbolic link to a directory. */ +#define needsFirstVisit 4 /* This is an initial entry. */ +#define needsDescent 8 /* This entry needs to be previsited. */ +#define needsOpen 16 /* This is a directory that needs to be opened. */ +#define needsAscent 32 /* This entry needs to be postvisited. */ + +/* + * Local data for this package. + */ +struct tree { + struct tree_entry *stack; + struct tree_entry *current; + DIR *d; +#define INVALID_DIR_HANDLE NULL + struct dirent *de; +#if defined(USE_READDIR_R) + struct dirent *dirent; + size_t dirent_allocated; +#endif + int flags; + int visit_type; + /* Error code from last failed operation. */ + int tree_errno; + + /* Dynamically-sized buffer for holding path */ + struct archive_string path; + + /* Last path element */ + const char *basename; + /* Leading dir length */ + size_t dirname_length; + + int depth; + int openCount; + int maxOpenCount; + int initial_dir_fd; + int working_dir_fd; + + struct stat lst; + struct stat st; + int descend; + int nlink; + /* How to restore time of a file. */ + struct restore_time restore_time; + + struct entry_sparse { + int64_t length; + int64_t offset; + } *sparse_list, *current_sparse; + int sparse_count; + int sparse_list_size; + + char initial_symlink_mode; + char symlink_mode; + struct filesystem *current_filesystem; + struct filesystem *filesystem_table; + int initial_filesystem_id; + int current_filesystem_id; + int max_filesystem_id; + int allocated_filesystem; + + int entry_fd; + int entry_eof; + int64_t entry_remaining_bytes; + int64_t entry_total; + unsigned char *entry_buff; + size_t entry_buff_size; +}; + +/* Definitions for tree.flags bitmap. */ +#define hasStat 16 /* The st entry is valid. */ +#define hasLstat 32 /* The lst entry is valid. */ +#define onWorkingDir 64 /* We are on the working dir where we are + * reading directory entry at this time. */ +#define needsRestoreTimes 128 +#define onInitialDir 256 /* We are on the initial dir. */ + +static int +tree_dir_next_posix(struct tree *t); + +#ifdef HAVE_DIRENT_D_NAMLEN +/* BSD extension; avoids need for a strlen() call. */ +#define D_NAMELEN(dp) (dp)->d_namlen +#else +#define D_NAMELEN(dp) (strlen((dp)->d_name)) +#endif + +/* Initiate/terminate a tree traversal. */ +static struct tree *tree_open(const char *, int, int); +static struct tree *tree_reopen(struct tree *, const char *, int); +static void tree_close(struct tree *); +static void tree_free(struct tree *); +static void tree_push(struct tree *, const char *, int, int64_t, int64_t, + struct restore_time *); +static int tree_enter_initial_dir(struct tree *); +static int tree_enter_working_dir(struct tree *); +static int tree_current_dir_fd(struct tree *); + +/* + * tree_next() returns Zero if there is no next entry, non-zero if + * there is. Note that directories are visited three times. + * Directories are always visited first as part of enumerating their + * parent; that is a "regular" visit. If tree_descend() is invoked at + * that time, the directory is added to a work list and will + * subsequently be visited two more times: once just after descending + * into the directory ("postdescent") and again just after ascending + * back to the parent ("postascent"). + * + * TREE_ERROR_DIR is returned if the descent failed (because the + * directory couldn't be opened, for instance). This is returned + * instead of TREE_POSTDESCENT/TREE_POSTASCENT. TREE_ERROR_DIR is not a + * fatal error, but it does imply that the relevant subtree won't be + * visited. TREE_ERROR_FATAL is returned for an error that left the + * traversal completely hosed. Right now, this is only returned for + * chdir() failures during ascent. + */ +#define TREE_REGULAR 1 +#define TREE_POSTDESCENT 2 +#define TREE_POSTASCENT 3 +#define TREE_ERROR_DIR -1 +#define TREE_ERROR_FATAL -2 + +static int tree_next(struct tree *); + +/* + * Return information about the current entry. + */ + +/* + * The current full pathname, length of the full pathname, and a name + * that can be used to access the file. Because tree does use chdir + * extensively, the access path is almost never the same as the full + * current path. + * + * TODO: On platforms that support it, use openat()-style operations + * to eliminate the chdir() operations entirely while still supporting + * arbitrarily deep traversals. This makes access_path troublesome to + * support, of course, which means we'll need a rich enough interface + * that clients can function without it. (In particular, we'll need + * tree_current_open() that returns an open file descriptor.) + * + */ +static const char *tree_current_path(struct tree *); +static const char *tree_current_access_path(struct tree *); + +/* + * Request the lstat() or stat() data for the current path. Since the + * tree package needs to do some of this anyway, and caches the + * results, you should take advantage of it here if you need it rather + * than make a redundant stat() or lstat() call of your own. + */ +static const struct stat *tree_current_stat(struct tree *); +static const struct stat *tree_current_lstat(struct tree *); +static int tree_current_is_symblic_link_target(struct tree *); + +/* The following functions use tricks to avoid a certain number of + * stat()/lstat() calls. */ +/* "is_physical_dir" is equivalent to S_ISDIR(tree_current_lstat()->st_mode) */ +static int tree_current_is_physical_dir(struct tree *); +/* "is_dir" is equivalent to S_ISDIR(tree_current_stat()->st_mode) */ +static int tree_current_is_dir(struct tree *); +static int update_current_filesystem(struct archive_read_disk *a, + int64_t dev); +static int setup_current_filesystem(struct archive_read_disk *); +static int tree_target_is_same_as_parent(struct tree *, const struct stat *); + +static int _archive_read_disk_open(struct archive *, const char *); +static int _archive_read_free(struct archive *); +static int _archive_read_close(struct archive *); +static int _archive_read_data_block(struct archive *, + const void **, size_t *, int64_t *); +static int _archive_read_next_header(struct archive *, + struct archive_entry **); +static int _archive_read_next_header2(struct archive *, + struct archive_entry *); +static const char *trivial_lookup_gname(void *, int64_t gid); +static const char *trivial_lookup_uname(void *, int64_t uid); +static int setup_sparse(struct archive_read_disk *, struct archive_entry *); +static int close_and_restore_time(int fd, struct tree *, + struct restore_time *); +static int open_on_current_dir(struct tree *, const char *, int); +static int tree_dup(int); + + +static struct archive_vtable * +archive_read_disk_vtable(void) +{ + static struct archive_vtable av; + static int inited = 0; + + if (!inited) { + av.archive_free = _archive_read_free; + av.archive_close = _archive_read_close; + av.archive_read_data_block = _archive_read_data_block; + av.archive_read_next_header = _archive_read_next_header; + av.archive_read_next_header2 = _archive_read_next_header2; + inited = 1; + } + return (&av); +} + +const char * +archive_read_disk_gname(struct archive *_a, la_int64_t gid) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + if (ARCHIVE_OK != __archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_gname")) + return (NULL); + if (a->lookup_gname == NULL) + return (NULL); + return ((*a->lookup_gname)(a->lookup_gname_data, gid)); +} + +const char * +archive_read_disk_uname(struct archive *_a, la_int64_t uid) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + if (ARCHIVE_OK != __archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_uname")) + return (NULL); + if (a->lookup_uname == NULL) + return (NULL); + return ((*a->lookup_uname)(a->lookup_uname_data, uid)); +} + +int +archive_read_disk_set_gname_lookup(struct archive *_a, + void *private_data, + const char * (*lookup_gname)(void *private, la_int64_t gid), + void (*cleanup_gname)(void *private)) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + archive_check_magic(&a->archive, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_set_gname_lookup"); + + if (a->cleanup_gname != NULL && a->lookup_gname_data != NULL) + (a->cleanup_gname)(a->lookup_gname_data); + + a->lookup_gname = lookup_gname; + a->cleanup_gname = cleanup_gname; + a->lookup_gname_data = private_data; + return (ARCHIVE_OK); +} + +int +archive_read_disk_set_uname_lookup(struct archive *_a, + void *private_data, + const char * (*lookup_uname)(void *private, la_int64_t uid), + void (*cleanup_uname)(void *private)) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + archive_check_magic(&a->archive, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_set_uname_lookup"); + + if (a->cleanup_uname != NULL && a->lookup_uname_data != NULL) + (a->cleanup_uname)(a->lookup_uname_data); + + a->lookup_uname = lookup_uname; + a->cleanup_uname = cleanup_uname; + a->lookup_uname_data = private_data; + return (ARCHIVE_OK); +} + +/* + * Create a new archive_read_disk object and initialize it with global state. + */ +struct archive * +archive_read_disk_new(void) +{ + struct archive_read_disk *a; + + a = (struct archive_read_disk *)calloc(1, sizeof(*a)); + if (a == NULL) + return (NULL); + a->archive.magic = ARCHIVE_READ_DISK_MAGIC; + a->archive.state = ARCHIVE_STATE_NEW; + a->archive.vtable = archive_read_disk_vtable(); + a->entry = archive_entry_new2(&a->archive); + a->lookup_uname = trivial_lookup_uname; + a->lookup_gname = trivial_lookup_gname; + a->flags = ARCHIVE_READDISK_MAC_COPYFILE; + a->open_on_current_dir = open_on_current_dir; + a->tree_current_dir_fd = tree_current_dir_fd; + a->tree_enter_working_dir = tree_enter_working_dir; + return (&a->archive); +} + +static int +_archive_read_free(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + int r; + + if (_a == NULL) + return (ARCHIVE_OK); + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_read_free"); + + if (a->archive.state != ARCHIVE_STATE_CLOSED) + r = _archive_read_close(&a->archive); + else + r = ARCHIVE_OK; + + tree_free(a->tree); + if (a->cleanup_gname != NULL && a->lookup_gname_data != NULL) + (a->cleanup_gname)(a->lookup_gname_data); + if (a->cleanup_uname != NULL && a->lookup_uname_data != NULL) + (a->cleanup_uname)(a->lookup_uname_data); + archive_string_free(&a->archive.error_string); + archive_entry_free(a->entry); + a->archive.magic = 0; + __archive_clean(&a->archive); + free(a); + return (r); +} + +static int +_archive_read_close(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_read_close"); + + if (a->archive.state != ARCHIVE_STATE_FATAL) + a->archive.state = ARCHIVE_STATE_CLOSED; + + tree_close(a->tree); + + return (ARCHIVE_OK); +} + +static void +setup_symlink_mode(struct archive_read_disk *a, char symlink_mode, + int follow_symlinks) +{ + a->symlink_mode = symlink_mode; + a->follow_symlinks = follow_symlinks; + if (a->tree != NULL) { + a->tree->initial_symlink_mode = a->symlink_mode; + a->tree->symlink_mode = a->symlink_mode; + } +} + +int +archive_read_disk_set_symlink_logical(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_set_symlink_logical"); + setup_symlink_mode(a, 'L', 1); + return (ARCHIVE_OK); +} + +int +archive_read_disk_set_symlink_physical(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_set_symlink_physical"); + setup_symlink_mode(a, 'P', 0); + return (ARCHIVE_OK); +} + +int +archive_read_disk_set_symlink_hybrid(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_set_symlink_hybrid"); + setup_symlink_mode(a, 'H', 1);/* Follow symlinks initially. */ + return (ARCHIVE_OK); +} + +int +archive_read_disk_set_atime_restored(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_restore_atime"); +#ifdef HAVE_UTIMES + a->flags |= ARCHIVE_READDISK_RESTORE_ATIME; + if (a->tree != NULL) + a->tree->flags |= needsRestoreTimes; + return (ARCHIVE_OK); +#else + /* Display warning and unset flag */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Cannot restore access time on this system"); + a->flags &= ~ARCHIVE_READDISK_RESTORE_ATIME; + return (ARCHIVE_WARN); +#endif +} + +int +archive_read_disk_set_behavior(struct archive *_a, int flags) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + int r = ARCHIVE_OK; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_honor_nodump"); + + a->flags = flags; + + if (flags & ARCHIVE_READDISK_RESTORE_ATIME) + r = archive_read_disk_set_atime_restored(_a); + else { + if (a->tree != NULL) + a->tree->flags &= ~needsRestoreTimes; + } + return (r); +} + +/* + * Trivial implementations of gname/uname lookup functions. + * These are normally overridden by the client, but these stub + * versions ensure that we always have something that works. + */ +static const char * +trivial_lookup_gname(void *private_data, int64_t gid) +{ + (void)private_data; /* UNUSED */ + (void)gid; /* UNUSED */ + return (NULL); +} + +static const char * +trivial_lookup_uname(void *private_data, int64_t uid) +{ + (void)private_data; /* UNUSED */ + (void)uid; /* UNUSED */ + return (NULL); +} + +/* + * Allocate memory for the reading buffer adjusted to the filesystem + * alignment. + */ +static int +setup_suitable_read_buffer(struct archive_read_disk *a) +{ + struct tree *t = a->tree; + struct filesystem *cf = t->current_filesystem; + size_t asize; + size_t s; + + if (cf->allocation_ptr == NULL) { + /* If we couldn't get a filesystem alignment, + * we use 4096 as default value but we won't use + * O_DIRECT to open() and openat() operations. */ + long xfer_align = (cf->xfer_align == -1)?4096:cf->xfer_align; + + if (cf->max_xfer_size != -1) + asize = cf->max_xfer_size + xfer_align; + else { + long incr = cf->incr_xfer_size; + /* Some platform does not set a proper value to + * incr_xfer_size.*/ + if (incr < 0) + incr = cf->min_xfer_size; + if (cf->min_xfer_size < 0) { + incr = xfer_align; + asize = xfer_align; + } else + asize = cf->min_xfer_size; + + /* Increase a buffer size up to 64K bytes in + * a proper increment size. */ + while (asize < 1024*64) + asize += incr; + /* Take a margin to adjust to the filesystem + * alignment. */ + asize += xfer_align; + } + cf->allocation_ptr = malloc(asize); + if (cf->allocation_ptr == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Couldn't allocate memory"); + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + + /* + * Calculate proper address for the filesystem. + */ + s = (uintptr_t)cf->allocation_ptr; + s %= xfer_align; + if (s > 0) + s = xfer_align - s; + + /* + * Set a read buffer pointer in the proper alignment of + * the current filesystem. + */ + cf->buff = cf->allocation_ptr + s; + cf->buff_size = asize - xfer_align; + } + return (ARCHIVE_OK); +} + +static int +_archive_read_data_block(struct archive *_a, const void **buff, + size_t *size, int64_t *offset) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + struct tree *t = a->tree; + int r; + ssize_t bytes; + int64_t sparse_bytes; + size_t buffbytes; + int empty_sparse_region = 0; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_DATA, + "archive_read_data_block"); + + if (t->entry_eof || t->entry_remaining_bytes <= 0) { + r = ARCHIVE_EOF; + goto abort_read_data; + } + + /* + * Open the current file. + */ + if (t->entry_fd < 0) { + int flags = O_RDONLY | O_BINARY | O_CLOEXEC; + + /* + * Eliminate or reduce cache effects if we can. + * + * Carefully consider this to be enabled. + */ +#if defined(O_DIRECT) && 0/* Disabled for now */ + if (t->current_filesystem->xfer_align != -1 && + t->nlink == 1) + flags |= O_DIRECT; +#endif +#if defined(O_NOATIME) + /* + * Linux has O_NOATIME flag; use it if we need. + */ + if ((t->flags & needsRestoreTimes) != 0 && + t->restore_time.noatime == 0) + flags |= O_NOATIME; +#endif + t->entry_fd = open_on_current_dir(t, + tree_current_access_path(t), flags); + __archive_ensure_cloexec_flag(t->entry_fd); +#if defined(O_NOATIME) + /* + * When we did open the file with O_NOATIME flag, + * if successful, set 1 to t->restore_time.noatime + * not to restore an atime of the file later. + * if failed by EPERM, retry it without O_NOATIME flag. + */ + if (flags & O_NOATIME) { + if (t->entry_fd >= 0) + t->restore_time.noatime = 1; + else if (errno == EPERM) + flags &= ~O_NOATIME; + } +#endif + if (t->entry_fd < 0) { + archive_set_error(&a->archive, errno, + "Couldn't open %s", tree_current_path(t)); + r = ARCHIVE_FAILED; + tree_enter_initial_dir(t); + goto abort_read_data; + } + tree_enter_initial_dir(t); + } + + /* + * Allocate read buffer if not allocated. + */ + if (t->current_filesystem->allocation_ptr == NULL) { + r = setup_suitable_read_buffer(a); + if (r != ARCHIVE_OK) { + a->archive.state = ARCHIVE_STATE_FATAL; + goto abort_read_data; + } + } + t->entry_buff = t->current_filesystem->buff; + t->entry_buff_size = t->current_filesystem->buff_size; + + buffbytes = t->entry_buff_size; + if ((int64_t)buffbytes > t->current_sparse->length) + buffbytes = t->current_sparse->length; + + if (t->current_sparse->length == 0) + empty_sparse_region = 1; + + /* + * Skip hole. + * TODO: Should we consider t->current_filesystem->xfer_align? + */ + if (t->current_sparse->offset > t->entry_total) { + if (lseek(t->entry_fd, + (off_t)t->current_sparse->offset, SEEK_SET) < 0) { + archive_set_error(&a->archive, errno, "Seek error"); + r = ARCHIVE_FATAL; + a->archive.state = ARCHIVE_STATE_FATAL; + goto abort_read_data; + } + sparse_bytes = t->current_sparse->offset - t->entry_total; + t->entry_remaining_bytes -= sparse_bytes; + t->entry_total += sparse_bytes; + } + + /* + * Read file contents. + */ + if (buffbytes > 0) { + bytes = read(t->entry_fd, t->entry_buff, buffbytes); + if (bytes < 0) { + archive_set_error(&a->archive, errno, "Read error"); + r = ARCHIVE_FATAL; + a->archive.state = ARCHIVE_STATE_FATAL; + goto abort_read_data; + } + } else + bytes = 0; + /* + * Return an EOF unless we've read a leading empty sparse region, which + * is used to represent fully-sparse files. + */ + if (bytes == 0 && !empty_sparse_region) { + /* Get EOF */ + t->entry_eof = 1; + r = ARCHIVE_EOF; + goto abort_read_data; + } + *buff = t->entry_buff; + *size = bytes; + *offset = t->entry_total; + t->entry_total += bytes; + t->entry_remaining_bytes -= bytes; + if (t->entry_remaining_bytes == 0) { + /* Close the current file descriptor */ + close_and_restore_time(t->entry_fd, t, &t->restore_time); + t->entry_fd = -1; + t->entry_eof = 1; + } + t->current_sparse->offset += bytes; + t->current_sparse->length -= bytes; + if (t->current_sparse->length == 0 && !t->entry_eof) + t->current_sparse++; + return (ARCHIVE_OK); + +abort_read_data: + *buff = NULL; + *size = 0; + *offset = t->entry_total; + if (t->entry_fd >= 0) { + /* Close the current file descriptor */ + close_and_restore_time(t->entry_fd, t, &t->restore_time); + t->entry_fd = -1; + } + return (r); +} + +static int +next_entry(struct archive_read_disk *a, struct tree *t, + struct archive_entry *entry) +{ + const struct stat *st; /* info to use for this entry */ + const struct stat *lst;/* lstat() information */ + const char *name; + int delayed, delayed_errno, descend, r; + struct archive_string delayed_str; + + delayed = ARCHIVE_OK; + delayed_errno = 0; + archive_string_init(&delayed_str); + + st = NULL; + lst = NULL; + t->descend = 0; + do { + switch (tree_next(t)) { + case TREE_ERROR_FATAL: + archive_set_error(&a->archive, t->tree_errno, + "%s: Unable to continue traversing directory tree", + tree_current_path(t)); + a->archive.state = ARCHIVE_STATE_FATAL; + tree_enter_initial_dir(t); + return (ARCHIVE_FATAL); + case TREE_ERROR_DIR: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "%s: Couldn't visit directory", + tree_current_path(t)); + tree_enter_initial_dir(t); + return (ARCHIVE_FAILED); + case 0: + tree_enter_initial_dir(t); + return (ARCHIVE_EOF); + case TREE_POSTDESCENT: + case TREE_POSTASCENT: + break; + case TREE_REGULAR: + lst = tree_current_lstat(t); + if (lst == NULL) { + if (errno == ENOENT && t->depth > 0) { + delayed = ARCHIVE_WARN; + delayed_errno = errno; + if (delayed_str.length == 0) { + archive_string_sprintf(&delayed_str, + "%s", tree_current_path(t)); + } else { + archive_string_sprintf(&delayed_str, + " %s", tree_current_path(t)); + } + } else { + archive_set_error(&a->archive, errno, + "%s: Cannot stat", + tree_current_path(t)); + tree_enter_initial_dir(t); + return (ARCHIVE_FAILED); + } + } + break; + } + } while (lst == NULL); + +#ifdef __APPLE__ + if (a->flags & ARCHIVE_READDISK_MAC_COPYFILE) { + /* If we're using copyfile(), ignore "._XXX" files. */ + const char *bname = strrchr(tree_current_path(t), '/'); + if (bname == NULL) + bname = tree_current_path(t); + else + ++bname; + if (bname[0] == '.' && bname[1] == '_') + return (ARCHIVE_RETRY); + } +#endif + + archive_entry_copy_pathname(entry, tree_current_path(t)); + /* + * Perform path matching. + */ + if (a->matching) { + r = archive_match_path_excluded(a->matching, entry); + if (r < 0) { + archive_set_error(&(a->archive), errno, + "Failed : %s", archive_error_string(a->matching)); + return (r); + } + if (r) { + if (a->excluded_cb_func) + a->excluded_cb_func(&(a->archive), + a->excluded_cb_data, entry); + return (ARCHIVE_RETRY); + } + } + + /* + * Distinguish 'L'/'P'/'H' symlink following. + */ + switch(t->symlink_mode) { + case 'H': + /* 'H': After the first item, rest like 'P'. */ + t->symlink_mode = 'P'; + /* 'H': First item (from command line) like 'L'. */ + /* FALLTHROUGH */ + case 'L': + /* 'L': Do descend through a symlink to dir. */ + descend = tree_current_is_dir(t); + /* 'L': Follow symlinks to files. */ + a->symlink_mode = 'L'; + a->follow_symlinks = 1; + /* 'L': Archive symlinks as targets, if we can. */ + st = tree_current_stat(t); + if (st != NULL && !tree_target_is_same_as_parent(t, st)) + break; + /* If stat fails, we have a broken symlink; + * in that case, don't follow the link. */ + /* FALLTHROUGH */ + default: + /* 'P': Don't descend through a symlink to dir. */ + descend = tree_current_is_physical_dir(t); + /* 'P': Don't follow symlinks to files. */ + a->symlink_mode = 'P'; + a->follow_symlinks = 0; + /* 'P': Archive symlinks as symlinks. */ + st = lst; + break; + } + + if (update_current_filesystem(a, st->st_dev) != ARCHIVE_OK) { + a->archive.state = ARCHIVE_STATE_FATAL; + tree_enter_initial_dir(t); + return (ARCHIVE_FATAL); + } + if (t->initial_filesystem_id == -1) + t->initial_filesystem_id = t->current_filesystem_id; + if (a->flags & ARCHIVE_READDISK_NO_TRAVERSE_MOUNTS) { + if (t->initial_filesystem_id != t->current_filesystem_id) + descend = 0; + } + t->descend = descend; + + /* + * Honor nodump flag. + * If the file is marked with nodump flag, do not return this entry. + */ + if (a->flags & ARCHIVE_READDISK_HONOR_NODUMP) { +#if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP) + if (st->st_flags & UF_NODUMP) + return (ARCHIVE_RETRY); +#elif (defined(FS_IOC_GETFLAGS) && defined(FS_NODUMP_FL) && \ + defined(HAVE_WORKING_FS_IOC_GETFLAGS)) || \ + (defined(EXT2_IOC_GETFLAGS) && defined(EXT2_NODUMP_FL) && \ + defined(HAVE_WORKING_EXT2_IOC_GETFLAGS)) + if (S_ISREG(st->st_mode) || S_ISDIR(st->st_mode)) { + int stflags; + + t->entry_fd = open_on_current_dir(t, + tree_current_access_path(t), + O_RDONLY | O_NONBLOCK | O_CLOEXEC); + __archive_ensure_cloexec_flag(t->entry_fd); + if (t->entry_fd >= 0) { + r = ioctl(t->entry_fd, +#ifdef FS_IOC_GETFLAGS + FS_IOC_GETFLAGS, +#else + EXT2_IOC_GETFLAGS, +#endif + &stflags); +#ifdef FS_NODUMP_FL + if (r == 0 && (stflags & FS_NODUMP_FL) != 0) +#else + if (r == 0 && (stflags & EXT2_NODUMP_FL) != 0) +#endif + return (ARCHIVE_RETRY); + } + } +#endif + } + + archive_entry_copy_stat(entry, st); + + /* Save the times to be restored. This must be in before + * calling archive_read_disk_descend() or any chance of it, + * especially, invoking a callback. */ + t->restore_time.mtime = archive_entry_mtime(entry); + t->restore_time.mtime_nsec = archive_entry_mtime_nsec(entry); + t->restore_time.atime = archive_entry_atime(entry); + t->restore_time.atime_nsec = archive_entry_atime_nsec(entry); + t->restore_time.filetype = archive_entry_filetype(entry); + t->restore_time.noatime = t->current_filesystem->noatime; + + /* + * Perform time matching. + */ + if (a->matching) { + r = archive_match_time_excluded(a->matching, entry); + if (r < 0) { + archive_set_error(&(a->archive), errno, + "Failed : %s", archive_error_string(a->matching)); + return (r); + } + if (r) { + if (a->excluded_cb_func) + a->excluded_cb_func(&(a->archive), + a->excluded_cb_data, entry); + return (ARCHIVE_RETRY); + } + } + + /* Lookup uname/gname */ + name = archive_read_disk_uname(&(a->archive), archive_entry_uid(entry)); + if (name != NULL) + archive_entry_copy_uname(entry, name); + name = archive_read_disk_gname(&(a->archive), archive_entry_gid(entry)); + if (name != NULL) + archive_entry_copy_gname(entry, name); + + /* + * Perform owner matching. + */ + if (a->matching) { + r = archive_match_owner_excluded(a->matching, entry); + if (r < 0) { + archive_set_error(&(a->archive), errno, + "Failed : %s", archive_error_string(a->matching)); + return (r); + } + if (r) { + if (a->excluded_cb_func) + a->excluded_cb_func(&(a->archive), + a->excluded_cb_data, entry); + return (ARCHIVE_RETRY); + } + } + + /* + * Invoke a meta data filter callback. + */ + if (a->metadata_filter_func) { + if (!a->metadata_filter_func(&(a->archive), + a->metadata_filter_data, entry)) + return (ARCHIVE_RETRY); + } + + /* + * Populate the archive_entry with metadata from the disk. + */ + archive_entry_copy_sourcepath(entry, tree_current_access_path(t)); + r = archive_read_disk_entry_from_file(&(a->archive), entry, + t->entry_fd, st); + + if (r == ARCHIVE_OK) { + r = delayed; + if (r != ARCHIVE_OK) { + archive_string_sprintf(&delayed_str, ": %s", + "File removed before we read it"); + archive_set_error(&(a->archive), delayed_errno, + "%s", delayed_str.s); + } + } + archive_string_free(&delayed_str); + + return (r); +} + +static int +_archive_read_next_header(struct archive *_a, struct archive_entry **entryp) +{ + int ret; + struct archive_read_disk *a = (struct archive_read_disk *)_a; + *entryp = NULL; + ret = _archive_read_next_header2(_a, a->entry); + *entryp = a->entry; + return ret; +} + +static int +_archive_read_next_header2(struct archive *_a, struct archive_entry *entry) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + struct tree *t; + int r; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_read_next_header2"); + + t = a->tree; + if (t->entry_fd >= 0) { + close_and_restore_time(t->entry_fd, t, &t->restore_time); + t->entry_fd = -1; + } + + archive_entry_clear(entry); + + for (;;) { + r = next_entry(a, t, entry); + if (t->entry_fd >= 0) { + close(t->entry_fd); + t->entry_fd = -1; + } + + if (r == ARCHIVE_RETRY) { + archive_entry_clear(entry); + continue; + } + break; + } + + /* Return to the initial directory. */ + tree_enter_initial_dir(t); + + /* + * EOF and FATAL are persistent at this layer. By + * modifying the state, we guarantee that future calls to + * read a header or read data will fail. + */ + switch (r) { + case ARCHIVE_EOF: + a->archive.state = ARCHIVE_STATE_EOF; + break; + case ARCHIVE_OK: + case ARCHIVE_WARN: + /* Overwrite the sourcepath based on the initial directory. */ + archive_entry_copy_sourcepath(entry, tree_current_path(t)); + t->entry_total = 0; + if (archive_entry_filetype(entry) == AE_IFREG) { + t->nlink = archive_entry_nlink(entry); + t->entry_remaining_bytes = archive_entry_size(entry); + t->entry_eof = (t->entry_remaining_bytes == 0)? 1: 0; + if (!t->entry_eof && + setup_sparse(a, entry) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } else { + t->entry_remaining_bytes = 0; + t->entry_eof = 1; + } + a->archive.state = ARCHIVE_STATE_DATA; + break; + case ARCHIVE_RETRY: + break; + case ARCHIVE_FATAL: + a->archive.state = ARCHIVE_STATE_FATAL; + break; + } + + __archive_reset_read_data(&a->archive); + return (r); +} + +static int +setup_sparse(struct archive_read_disk *a, struct archive_entry *entry) +{ + struct tree *t = a->tree; + int64_t length, offset; + int i; + + t->sparse_count = archive_entry_sparse_reset(entry); + if (t->sparse_count+1 > t->sparse_list_size) { + free(t->sparse_list); + t->sparse_list_size = t->sparse_count + 1; + t->sparse_list = malloc(sizeof(t->sparse_list[0]) * + t->sparse_list_size); + if (t->sparse_list == NULL) { + t->sparse_list_size = 0; + archive_set_error(&a->archive, ENOMEM, + "Can't allocate data"); + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + } + for (i = 0; i < t->sparse_count; i++) { + archive_entry_sparse_next(entry, &offset, &length); + t->sparse_list[i].offset = offset; + t->sparse_list[i].length = length; + } + if (i == 0) { + t->sparse_list[i].offset = 0; + t->sparse_list[i].length = archive_entry_size(entry); + } else { + t->sparse_list[i].offset = archive_entry_size(entry); + t->sparse_list[i].length = 0; + } + t->current_sparse = t->sparse_list; + + return (ARCHIVE_OK); +} + +int +archive_read_disk_set_matching(struct archive *_a, struct archive *_ma, + void (*_excluded_func)(struct archive *, void *, struct archive_entry *), + void *_client_data) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_set_matching"); + a->matching = _ma; + a->excluded_cb_func = _excluded_func; + a->excluded_cb_data = _client_data; + return (ARCHIVE_OK); +} + +int +archive_read_disk_set_metadata_filter_callback(struct archive *_a, + int (*_metadata_filter_func)(struct archive *, void *, + struct archive_entry *), void *_client_data) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_ANY, + "archive_read_disk_set_metadata_filter_callback"); + + a->metadata_filter_func = _metadata_filter_func; + a->metadata_filter_data = _client_data; + return (ARCHIVE_OK); +} + +int +archive_read_disk_can_descend(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + struct tree *t = a->tree; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_read_disk_can_descend"); + + return (t->visit_type == TREE_REGULAR && t->descend); +} + +/* + * Called by the client to mark the directory just returned from + * tree_next() as needing to be visited. + */ +int +archive_read_disk_descend(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + struct tree *t = a->tree; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_read_disk_descend"); + + if (t->visit_type != TREE_REGULAR || !t->descend) + return (ARCHIVE_OK); + + /* + * We must not treat the initial specified path as a physical dir, + * because if we do then we will try and ascend out of it by opening + * ".." which is (a) wrong and (b) causes spurious permissions errors + * if ".." is not readable by us. Instead, treat it as if it were a + * symlink. (This uses an extra fd, but it can only happen once at the + * top level of a traverse.) But we can't necessarily assume t->st is + * valid here (though t->lst is), which complicates the logic a + * little. + */ + if (tree_current_is_physical_dir(t)) { + tree_push(t, t->basename, t->current_filesystem_id, + t->lst.st_dev, t->lst.st_ino, &t->restore_time); + if (t->stack->parent->parent != NULL) + t->stack->flags |= isDir; + else + t->stack->flags |= isDirLink; + } else if (tree_current_is_dir(t)) { + tree_push(t, t->basename, t->current_filesystem_id, + t->st.st_dev, t->st.st_ino, &t->restore_time); + t->stack->flags |= isDirLink; + } + t->descend = 0; + return (ARCHIVE_OK); +} + +int +archive_read_disk_open(struct archive *_a, const char *pathname) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_NEW | ARCHIVE_STATE_CLOSED, + "archive_read_disk_open"); + archive_clear_error(&a->archive); + + return (_archive_read_disk_open(_a, pathname)); +} + +int +archive_read_disk_open_w(struct archive *_a, const wchar_t *pathname) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + struct archive_string path; + int ret; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_NEW | ARCHIVE_STATE_CLOSED, + "archive_read_disk_open_w"); + archive_clear_error(&a->archive); + + /* Make a char string from a wchar_t string. */ + archive_string_init(&path); + if (archive_string_append_from_wcs(&path, pathname, + wcslen(pathname)) != 0) { + if (errno == ENOMEM) + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + else + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can't convert a path to a char string"); + a->archive.state = ARCHIVE_STATE_FATAL; + ret = ARCHIVE_FATAL; + } else + ret = _archive_read_disk_open(_a, path.s); + + archive_string_free(&path); + return (ret); +} + +static int +_archive_read_disk_open(struct archive *_a, const char *pathname) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + + if (a->tree != NULL) + a->tree = tree_reopen(a->tree, pathname, + a->flags & ARCHIVE_READDISK_RESTORE_ATIME); + else + a->tree = tree_open(pathname, a->symlink_mode, + a->flags & ARCHIVE_READDISK_RESTORE_ATIME); + if (a->tree == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate tar data"); + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + a->archive.state = ARCHIVE_STATE_HEADER; + + return (ARCHIVE_OK); +} + +/* + * Return a current filesystem ID which is index of the filesystem entry + * you've visited through archive_read_disk. + */ +int +archive_read_disk_current_filesystem(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_DATA, + "archive_read_disk_current_filesystem"); + + return (a->tree->current_filesystem_id); +} + +static int +update_current_filesystem(struct archive_read_disk *a, int64_t dev) +{ + struct tree *t = a->tree; + int i, fid; + + if (t->current_filesystem != NULL && + t->current_filesystem->dev == dev) + return (ARCHIVE_OK); + + for (i = 0; i < t->max_filesystem_id; i++) { + if (t->filesystem_table[i].dev == dev) { + /* There is the filesystem ID we've already generated. */ + t->current_filesystem_id = i; + t->current_filesystem = &(t->filesystem_table[i]); + return (ARCHIVE_OK); + } + } + + /* + * This is the new filesystem which we have to generate a new ID for. + */ + fid = t->max_filesystem_id++; + if (t->max_filesystem_id > t->allocated_filesystem) { + size_t s; + void *p; + + s = t->max_filesystem_id * 2; + p = realloc(t->filesystem_table, + s * sizeof(*t->filesystem_table)); + if (p == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate tar data"); + return (ARCHIVE_FATAL); + } + t->filesystem_table = (struct filesystem *)p; + t->allocated_filesystem = s; + } + t->current_filesystem_id = fid; + t->current_filesystem = &(t->filesystem_table[fid]); + t->current_filesystem->dev = dev; + t->current_filesystem->allocation_ptr = NULL; + t->current_filesystem->buff = NULL; + + /* Setup the current filesystem properties which depend on + * platform specific. */ + return (setup_current_filesystem(a)); +} + +/* + * Returns 1 if current filesystem is generated filesystem, 0 if it is not + * or -1 if it is unknown. + */ +int +archive_read_disk_current_filesystem_is_synthetic(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_DATA, + "archive_read_disk_current_filesystem"); + + return (a->tree->current_filesystem->synthetic); +} + +/* + * Returns 1 if current filesystem is remote filesystem, 0 if it is not + * or -1 if it is unknown. + */ +int +archive_read_disk_current_filesystem_is_remote(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_DATA, + "archive_read_disk_current_filesystem"); + + return (a->tree->current_filesystem->remote); +} + +#if defined(_PC_REC_INCR_XFER_SIZE) && defined(_PC_REC_MAX_XFER_SIZE) &&\ + defined(_PC_REC_MIN_XFER_SIZE) && defined(_PC_REC_XFER_ALIGN) +static int +get_xfer_size(struct tree *t, int fd, const char *path) +{ + t->current_filesystem->xfer_align = -1; + errno = 0; + if (fd >= 0) { + t->current_filesystem->incr_xfer_size = + fpathconf(fd, _PC_REC_INCR_XFER_SIZE); + t->current_filesystem->max_xfer_size = + fpathconf(fd, _PC_REC_MAX_XFER_SIZE); + t->current_filesystem->min_xfer_size = + fpathconf(fd, _PC_REC_MIN_XFER_SIZE); + t->current_filesystem->xfer_align = + fpathconf(fd, _PC_REC_XFER_ALIGN); + } else if (path != NULL) { + t->current_filesystem->incr_xfer_size = + pathconf(path, _PC_REC_INCR_XFER_SIZE); + t->current_filesystem->max_xfer_size = + pathconf(path, _PC_REC_MAX_XFER_SIZE); + t->current_filesystem->min_xfer_size = + pathconf(path, _PC_REC_MIN_XFER_SIZE); + t->current_filesystem->xfer_align = + pathconf(path, _PC_REC_XFER_ALIGN); + } + /* At least we need an alignment size. */ + if (t->current_filesystem->xfer_align == -1) + return ((errno == EINVAL)?1:-1); + else + return (0); +} +#else +static int +get_xfer_size(struct tree *t, int fd, const char *path) +{ + (void)t; /* UNUSED */ + (void)fd; /* UNUSED */ + (void)path; /* UNUSED */ + return (1);/* Not supported */ +} +#endif + +#if defined(HAVE_STATFS) && defined(HAVE_FSTATFS) && defined(MNT_LOCAL) \ + && !defined(ST_LOCAL) + +/* + * Gather current filesystem properties on FreeBSD, OpenBSD and Mac OS X. + */ +static int +setup_current_filesystem(struct archive_read_disk *a) +{ + struct tree *t = a->tree; + struct statfs sfs; +#if defined(HAVE_GETVFSBYNAME) && defined(VFCF_SYNTHETIC) +/* TODO: configure should set GETVFSBYNAME_ARG_TYPE to make + * this accurate; some platforms have both and we need the one that's + * used by getvfsbyname() + * + * Then the following would become: + * #if defined(GETVFSBYNAME_ARG_TYPE) + * GETVFSBYNAME_ARG_TYPE vfc; + * #endif + */ +# if defined(HAVE_STRUCT_XVFSCONF) + struct xvfsconf vfc; +# else + struct vfsconf vfc; +# endif +#endif + int r, xr = 0; +#if !defined(HAVE_STRUCT_STATFS_F_NAMEMAX) + long nm; +#endif + + t->current_filesystem->synthetic = -1; + t->current_filesystem->remote = -1; + if (tree_current_is_symblic_link_target(t)) { +#if defined(HAVE_OPENAT) + /* + * Get file system statistics on any directory + * where current is. + */ + int fd = openat(tree_current_dir_fd(t), + tree_current_access_path(t), O_RDONLY | O_CLOEXEC); + __archive_ensure_cloexec_flag(fd); + if (fd < 0) { + archive_set_error(&a->archive, errno, + "openat failed"); + return (ARCHIVE_FAILED); + } + r = fstatfs(fd, &sfs); + if (r == 0) + xr = get_xfer_size(t, fd, NULL); + close(fd); +#else + if (tree_enter_working_dir(t) != 0) { + archive_set_error(&a->archive, errno, "fchdir failed"); + return (ARCHIVE_FAILED); + } + r = statfs(tree_current_access_path(t), &sfs); + if (r == 0) + xr = get_xfer_size(t, -1, tree_current_access_path(t)); +#endif + } else { + r = fstatfs(tree_current_dir_fd(t), &sfs); + if (r == 0) + xr = get_xfer_size(t, tree_current_dir_fd(t), NULL); + } + if (r == -1 || xr == -1) { + archive_set_error(&a->archive, errno, "statfs failed"); + return (ARCHIVE_FAILED); + } else if (xr == 1) { + /* pathconf(_PC_REX_*) operations are not supported. */ + t->current_filesystem->xfer_align = sfs.f_bsize; + t->current_filesystem->max_xfer_size = -1; + t->current_filesystem->min_xfer_size = sfs.f_iosize; + t->current_filesystem->incr_xfer_size = sfs.f_iosize; + } + if (sfs.f_flags & MNT_LOCAL) + t->current_filesystem->remote = 0; + else + t->current_filesystem->remote = 1; + +#if defined(HAVE_GETVFSBYNAME) && defined(VFCF_SYNTHETIC) + r = getvfsbyname(sfs.f_fstypename, &vfc); + if (r == -1) { + archive_set_error(&a->archive, errno, "getvfsbyname failed"); + return (ARCHIVE_FAILED); + } + if (vfc.vfc_flags & VFCF_SYNTHETIC) + t->current_filesystem->synthetic = 1; + else + t->current_filesystem->synthetic = 0; +#endif + +#if defined(MNT_NOATIME) + if (sfs.f_flags & MNT_NOATIME) + t->current_filesystem->noatime = 1; + else +#endif + t->current_filesystem->noatime = 0; + +#if defined(USE_READDIR_R) + /* Set maximum filename length. */ +#if defined(HAVE_STRUCT_STATFS_F_NAMEMAX) + t->current_filesystem->name_max = sfs.f_namemax; +#else +# if defined(_PC_NAME_MAX) + /* Mac OS X does not have f_namemax in struct statfs. */ + if (tree_current_is_symblic_link_target(t)) { + if (tree_enter_working_dir(t) != 0) { + archive_set_error(&a->archive, errno, "fchdir failed"); + return (ARCHIVE_FAILED); + } + nm = pathconf(tree_current_access_path(t), _PC_NAME_MAX); + } else + nm = fpathconf(tree_current_dir_fd(t), _PC_NAME_MAX); +# else + nm = -1; +# endif + if (nm == -1) + t->current_filesystem->name_max = NAME_MAX; + else + t->current_filesystem->name_max = nm; +#endif +#endif /* USE_READDIR_R */ + return (ARCHIVE_OK); +} + +#elif (defined(HAVE_STATVFS) || defined(HAVE_FSTATVFS)) && defined(ST_LOCAL) + +/* + * Gather current filesystem properties on NetBSD + */ +static int +setup_current_filesystem(struct archive_read_disk *a) +{ + struct tree *t = a->tree; + struct statvfs svfs; + int r, xr = 0; + + t->current_filesystem->synthetic = -1; + if (tree_enter_working_dir(t) != 0) { + archive_set_error(&a->archive, errno, "fchdir failed"); + return (ARCHIVE_FAILED); + } + if (tree_current_is_symblic_link_target(t)) { + r = statvfs(tree_current_access_path(t), &svfs); + if (r == 0) + xr = get_xfer_size(t, -1, tree_current_access_path(t)); + } else { +#ifdef HAVE_FSTATVFS + r = fstatvfs(tree_current_dir_fd(t), &svfs); + if (r == 0) + xr = get_xfer_size(t, tree_current_dir_fd(t), NULL); +#else + r = statvfs(".", &svfs); + if (r == 0) + xr = get_xfer_size(t, -1, "."); +#endif + } + if (r == -1 || xr == -1) { + t->current_filesystem->remote = -1; + archive_set_error(&a->archive, errno, "statvfs failed"); + return (ARCHIVE_FAILED); + } else if (xr == 1) { + /* Usually come here unless NetBSD supports _PC_REC_XFER_ALIGN + * for pathconf() function. */ + t->current_filesystem->xfer_align = svfs.f_frsize; + t->current_filesystem->max_xfer_size = -1; +#if defined(HAVE_STRUCT_STATVFS_F_IOSIZE) + t->current_filesystem->min_xfer_size = svfs.f_iosize; + t->current_filesystem->incr_xfer_size = svfs.f_iosize; +#else + t->current_filesystem->min_xfer_size = svfs.f_bsize; + t->current_filesystem->incr_xfer_size = svfs.f_bsize; +#endif + } + if (svfs.f_flag & ST_LOCAL) + t->current_filesystem->remote = 0; + else + t->current_filesystem->remote = 1; + +#if defined(ST_NOATIME) + if (svfs.f_flag & ST_NOATIME) + t->current_filesystem->noatime = 1; + else +#endif + t->current_filesystem->noatime = 0; + + /* Set maximum filename length. */ + t->current_filesystem->name_max = svfs.f_namemax; + return (ARCHIVE_OK); +} + +#elif defined(HAVE_SYS_STATFS_H) && defined(HAVE_LINUX_MAGIC_H) &&\ + defined(HAVE_STATFS) && defined(HAVE_FSTATFS) +/* + * Note: statfs is deprecated since LSB 3.2 + */ + +#ifndef CIFS_SUPER_MAGIC +#define CIFS_SUPER_MAGIC 0xFF534D42 +#endif +#ifndef DEVFS_SUPER_MAGIC +#define DEVFS_SUPER_MAGIC 0x1373 +#endif + +/* + * Gather current filesystem properties on Linux + */ +static int +setup_current_filesystem(struct archive_read_disk *a) +{ + struct tree *t = a->tree; + struct statfs sfs; +#if defined(HAVE_STATVFS) + struct statvfs svfs; +#endif + int r, vr = 0, xr = 0; + + if (tree_current_is_symblic_link_target(t)) { +#if defined(HAVE_OPENAT) + /* + * Get file system statistics on any directory + * where current is. + */ + int fd = openat(tree_current_dir_fd(t), + tree_current_access_path(t), O_RDONLY | O_CLOEXEC); + __archive_ensure_cloexec_flag(fd); + if (fd < 0) { + archive_set_error(&a->archive, errno, + "openat failed"); + return (ARCHIVE_FAILED); + } +#if defined(HAVE_FSTATVFS) + vr = fstatvfs(fd, &svfs);/* for f_flag, mount flags */ +#endif + r = fstatfs(fd, &sfs); + if (r == 0) + xr = get_xfer_size(t, fd, NULL); + close(fd); +#else + if (tree_enter_working_dir(t) != 0) { + archive_set_error(&a->archive, errno, "fchdir failed"); + return (ARCHIVE_FAILED); + } +#if defined(HAVE_STATVFS) + vr = statvfs(tree_current_access_path(t), &svfs); +#endif + r = statfs(tree_current_access_path(t), &sfs); + if (r == 0) + xr = get_xfer_size(t, -1, tree_current_access_path(t)); +#endif + } else { +#ifdef HAVE_FSTATFS +#if defined(HAVE_FSTATVFS) + vr = fstatvfs(tree_current_dir_fd(t), &svfs); +#endif + r = fstatfs(tree_current_dir_fd(t), &sfs); + if (r == 0) + xr = get_xfer_size(t, tree_current_dir_fd(t), NULL); +#else + if (tree_enter_working_dir(t) != 0) { + archive_set_error(&a->archive, errno, "fchdir failed"); + return (ARCHIVE_FAILED); + } +#if defined(HAVE_STATVFS) + vr = statvfs(".", &svfs); +#endif + r = statfs(".", &sfs); + if (r == 0) + xr = get_xfer_size(t, -1, "."); +#endif + } + if (r == -1 || xr == -1 || vr == -1) { + t->current_filesystem->synthetic = -1; + t->current_filesystem->remote = -1; + archive_set_error(&a->archive, errno, "statfs failed"); + return (ARCHIVE_FAILED); + } else if (xr == 1) { + /* pathconf(_PC_REX_*) operations are not supported. */ +#if defined(HAVE_STATVFS) + t->current_filesystem->xfer_align = svfs.f_frsize; + t->current_filesystem->max_xfer_size = -1; + t->current_filesystem->min_xfer_size = svfs.f_bsize; + t->current_filesystem->incr_xfer_size = svfs.f_bsize; +#else + t->current_filesystem->xfer_align = sfs.f_frsize; + t->current_filesystem->max_xfer_size = -1; + t->current_filesystem->min_xfer_size = sfs.f_bsize; + t->current_filesystem->incr_xfer_size = sfs.f_bsize; +#endif + } + switch (sfs.f_type) { + case AFS_SUPER_MAGIC: + case CIFS_SUPER_MAGIC: + case CODA_SUPER_MAGIC: + case NCP_SUPER_MAGIC:/* NetWare */ + case NFS_SUPER_MAGIC: + case SMB_SUPER_MAGIC: + t->current_filesystem->remote = 1; + t->current_filesystem->synthetic = 0; + break; + case DEVFS_SUPER_MAGIC: + case PROC_SUPER_MAGIC: + case USBDEVICE_SUPER_MAGIC: + t->current_filesystem->remote = 0; + t->current_filesystem->synthetic = 1; + break; + default: + t->current_filesystem->remote = 0; + t->current_filesystem->synthetic = 0; + break; + } + +#if defined(ST_NOATIME) +#if defined(HAVE_STATVFS) + if (svfs.f_flag & ST_NOATIME) +#else + if (sfs.f_flags & ST_NOATIME) +#endif + t->current_filesystem->noatime = 1; + else +#endif + t->current_filesystem->noatime = 0; + +#if defined(USE_READDIR_R) + /* Set maximum filename length. */ + t->current_filesystem->name_max = sfs.f_namelen; +#endif + return (ARCHIVE_OK); +} + +#elif defined(HAVE_SYS_STATVFS_H) &&\ + (defined(HAVE_STATVFS) || defined(HAVE_FSTATVFS)) + +/* + * Gather current filesystem properties on other posix platform. + */ +static int +setup_current_filesystem(struct archive_read_disk *a) +{ + struct tree *t = a->tree; + struct statvfs svfs; + int r, xr = 0; + + t->current_filesystem->synthetic = -1;/* Not supported */ + t->current_filesystem->remote = -1;/* Not supported */ + if (tree_current_is_symblic_link_target(t)) { +#if defined(HAVE_OPENAT) + /* + * Get file system statistics on any directory + * where current is. + */ + int fd = openat(tree_current_dir_fd(t), + tree_current_access_path(t), O_RDONLY | O_CLOEXEC); + __archive_ensure_cloexec_flag(fd); + if (fd < 0) { + archive_set_error(&a->archive, errno, + "openat failed"); + return (ARCHIVE_FAILED); + } + r = fstatvfs(fd, &svfs); + if (r == 0) + xr = get_xfer_size(t, fd, NULL); + close(fd); +#else + if (tree_enter_working_dir(t) != 0) { + archive_set_error(&a->archive, errno, "fchdir failed"); + return (ARCHIVE_FAILED); + } + r = statvfs(tree_current_access_path(t), &svfs); + if (r == 0) + xr = get_xfer_size(t, -1, tree_current_access_path(t)); +#endif + } else { +#ifdef HAVE_FSTATVFS + r = fstatvfs(tree_current_dir_fd(t), &svfs); + if (r == 0) + xr = get_xfer_size(t, tree_current_dir_fd(t), NULL); +#else + if (tree_enter_working_dir(t) != 0) { + archive_set_error(&a->archive, errno, "fchdir failed"); + return (ARCHIVE_FAILED); + } + r = statvfs(".", &svfs); + if (r == 0) + xr = get_xfer_size(t, -1, "."); +#endif + } + if (r == -1 || xr == -1) { + t->current_filesystem->synthetic = -1; + t->current_filesystem->remote = -1; + archive_set_error(&a->archive, errno, "statvfs failed"); + return (ARCHIVE_FAILED); + } else if (xr == 1) { + /* pathconf(_PC_REX_*) operations are not supported. */ + t->current_filesystem->xfer_align = svfs.f_frsize; + t->current_filesystem->max_xfer_size = -1; + t->current_filesystem->min_xfer_size = svfs.f_bsize; + t->current_filesystem->incr_xfer_size = svfs.f_bsize; + } + +#if defined(ST_NOATIME) + if (svfs.f_flag & ST_NOATIME) + t->current_filesystem->noatime = 1; + else +#endif + t->current_filesystem->noatime = 0; + +#if defined(USE_READDIR_R) + /* Set maximum filename length. */ + t->current_filesystem->name_max = svfs.f_namemax; +#endif + return (ARCHIVE_OK); +} + +#else + +/* + * Generic: Gather current filesystem properties. + * TODO: Is this generic function really needed? + */ +static int +setup_current_filesystem(struct archive_read_disk *a) +{ + struct tree *t = a->tree; +#if defined(_PC_NAME_MAX) && defined(USE_READDIR_R) + long nm; +#endif + t->current_filesystem->synthetic = -1;/* Not supported */ + t->current_filesystem->remote = -1;/* Not supported */ + t->current_filesystem->noatime = 0; + (void)get_xfer_size(t, -1, ".");/* Dummy call to avoid build error. */ + t->current_filesystem->xfer_align = -1;/* Unknown */ + t->current_filesystem->max_xfer_size = -1; + t->current_filesystem->min_xfer_size = -1; + t->current_filesystem->incr_xfer_size = -1; + +#if defined(USE_READDIR_R) + /* Set maximum filename length. */ +# if defined(_PC_NAME_MAX) + if (tree_current_is_symblic_link_target(t)) { + if (tree_enter_working_dir(t) != 0) { + archive_set_error(&a->archive, errno, "fchdir failed"); + return (ARCHIVE_FAILED); + } + nm = pathconf(tree_current_access_path(t), _PC_NAME_MAX); + } else + nm = fpathconf(tree_current_dir_fd(t), _PC_NAME_MAX); + if (nm == -1) +# endif /* _PC_NAME_MAX */ + /* + * Some systems (HP-UX or others?) incorrectly defined + * NAME_MAX macro to be a smaller value. + */ +# if defined(NAME_MAX) && NAME_MAX >= 255 + t->current_filesystem->name_max = NAME_MAX; +# else + /* No way to get a trusted value of maximum filename + * length. */ + t->current_filesystem->name_max = PATH_MAX; +# endif /* NAME_MAX */ +# if defined(_PC_NAME_MAX) + else + t->current_filesystem->name_max = nm; +# endif /* _PC_NAME_MAX */ +#endif /* USE_READDIR_R */ + return (ARCHIVE_OK); +} + +#endif + +static int +close_and_restore_time(int fd, struct tree *t, struct restore_time *rt) +{ +#ifndef HAVE_UTIMES + (void)t; /* UNUSED */ + (void)rt; /* UNUSED */ + return (close(fd)); +#else +#if defined(HAVE_FUTIMENS) && !defined(__CYGWIN__) + struct timespec timespecs[2]; +#endif + struct timeval times[2]; + + if ((t->flags & needsRestoreTimes) == 0 || rt->noatime) { + if (fd >= 0) + return (close(fd)); + else + return (0); + } + +#if defined(HAVE_FUTIMENS) && !defined(__CYGWIN__) + timespecs[1].tv_sec = rt->mtime; + timespecs[1].tv_nsec = rt->mtime_nsec; + + timespecs[0].tv_sec = rt->atime; + timespecs[0].tv_nsec = rt->atime_nsec; + /* futimens() is defined in POSIX.1-2008. */ + if (futimens(fd, timespecs) == 0) + return (close(fd)); +#endif + + times[1].tv_sec = rt->mtime; + times[1].tv_usec = rt->mtime_nsec / 1000; + + times[0].tv_sec = rt->atime; + times[0].tv_usec = rt->atime_nsec / 1000; + +#if !defined(HAVE_FUTIMENS) && defined(HAVE_FUTIMES) && !defined(__CYGWIN__) + if (futimes(fd, times) == 0) + return (close(fd)); +#endif + close(fd); +#if defined(HAVE_FUTIMESAT) + if (futimesat(tree_current_dir_fd(t), rt->name, times) == 0) + return (0); +#endif +#ifdef HAVE_LUTIMES + if (lutimes(rt->name, times) != 0) +#else + if (AE_IFLNK != rt->filetype && utimes(rt->name, times) != 0) +#endif + return (-1); +#endif + return (0); +} + +static int +open_on_current_dir(struct tree *t, const char *path, int flags) +{ +#ifdef HAVE_OPENAT + return (openat(tree_current_dir_fd(t), path, flags)); +#else + if (tree_enter_working_dir(t) != 0) + return (-1); + return (open(path, flags)); +#endif +} + +static int +tree_dup(int fd) +{ + int new_fd; +#ifdef F_DUPFD_CLOEXEC + static volatile int can_dupfd_cloexec = 1; + + if (can_dupfd_cloexec) { + new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 0); + if (new_fd != -1) + return (new_fd); + /* Linux 2.6.18 - 2.6.23 declare F_DUPFD_CLOEXEC, + * but it cannot be used. So we have to try dup(). */ + /* We won't try F_DUPFD_CLOEXEC. */ + can_dupfd_cloexec = 0; + } +#endif /* F_DUPFD_CLOEXEC */ + new_fd = dup(fd); + __archive_ensure_cloexec_flag(new_fd); + return (new_fd); +} + +/* + * Add a directory path to the current stack. + */ +static void +tree_push(struct tree *t, const char *path, int filesystem_id, + int64_t dev, int64_t ino, struct restore_time *rt) +{ + struct tree_entry *te; + + te = calloc(1, sizeof(*te)); + te->next = t->stack; + te->parent = t->current; + if (te->parent) + te->depth = te->parent->depth + 1; + t->stack = te; + archive_string_init(&te->name); + te->symlink_parent_fd = -1; + archive_strcpy(&te->name, path); + te->flags = needsDescent | needsOpen | needsAscent; + te->filesystem_id = filesystem_id; + te->dev = dev; + te->ino = ino; + te->dirname_length = t->dirname_length; + te->restore_time.name = te->name.s; + if (rt != NULL) { + te->restore_time.mtime = rt->mtime; + te->restore_time.mtime_nsec = rt->mtime_nsec; + te->restore_time.atime = rt->atime; + te->restore_time.atime_nsec = rt->atime_nsec; + te->restore_time.filetype = rt->filetype; + te->restore_time.noatime = rt->noatime; + } +} + +/* + * Append a name to the current dir path. + */ +static void +tree_append(struct tree *t, const char *name, size_t name_length) +{ + size_t size_needed; + + t->path.s[t->dirname_length] = '\0'; + t->path.length = t->dirname_length; + /* Strip trailing '/' from name, unless entire name is "/". */ + while (name_length > 1 && name[name_length - 1] == '/') + name_length--; + + /* Resize pathname buffer as needed. */ + size_needed = name_length + t->dirname_length + 2; + archive_string_ensure(&t->path, size_needed); + /* Add a separating '/' if it's needed. */ + if (t->dirname_length > 0 && t->path.s[archive_strlen(&t->path)-1] != '/') + archive_strappend_char(&t->path, '/'); + t->basename = t->path.s + archive_strlen(&t->path); + archive_strncat(&t->path, name, name_length); + t->restore_time.name = t->basename; +} + +/* + * Open a directory tree for traversal. + */ +static struct tree * +tree_open(const char *path, int symlink_mode, int restore_time) +{ + struct tree *t; + + if ((t = calloc(1, sizeof(*t))) == NULL) + return (NULL); + archive_string_init(&t->path); + archive_string_ensure(&t->path, 31); + t->initial_symlink_mode = symlink_mode; + return (tree_reopen(t, path, restore_time)); +} + +static struct tree * +tree_reopen(struct tree *t, const char *path, int restore_time) +{ +#if defined(O_PATH) + /* Linux */ + const int o_flag = O_PATH; +#elif defined(O_SEARCH) + /* SunOS */ + const int o_flag = O_SEARCH; +#elif defined(__FreeBSD__) && defined(O_EXEC) + /* FreeBSD */ + const int o_flag = O_EXEC; +#endif + + t->flags = (restore_time != 0)?needsRestoreTimes:0; + t->flags |= onInitialDir; + t->visit_type = 0; + t->tree_errno = 0; + t->dirname_length = 0; + t->depth = 0; + t->descend = 0; + t->current = NULL; + t->d = INVALID_DIR_HANDLE; + t->symlink_mode = t->initial_symlink_mode; + archive_string_empty(&t->path); + t->entry_fd = -1; + t->entry_eof = 0; + t->entry_remaining_bytes = 0; + t->initial_filesystem_id = -1; + + /* First item is set up a lot like a symlink traversal. */ + tree_push(t, path, 0, 0, 0, NULL); + t->stack->flags = needsFirstVisit; + t->maxOpenCount = t->openCount = 1; + t->initial_dir_fd = open(".", O_RDONLY | O_CLOEXEC); +#if defined(O_PATH) || defined(O_SEARCH) || \ + (defined(__FreeBSD__) && defined(O_EXEC)) + /* + * Most likely reason to fail opening "." is that it's not readable, + * so try again for execute. The consequences of not opening this are + * unhelpful and unnecessary errors later. + */ + if (t->initial_dir_fd < 0) + t->initial_dir_fd = open(".", o_flag | O_CLOEXEC); +#endif + __archive_ensure_cloexec_flag(t->initial_dir_fd); + t->working_dir_fd = tree_dup(t->initial_dir_fd); + return (t); +} + +static int +tree_descent(struct tree *t) +{ + int flag, new_fd, r = 0; + + t->dirname_length = archive_strlen(&t->path); + flag = O_RDONLY | O_CLOEXEC; +#if defined(O_DIRECTORY) + flag |= O_DIRECTORY; +#endif + new_fd = open_on_current_dir(t, t->stack->name.s, flag); + __archive_ensure_cloexec_flag(new_fd); + if (new_fd < 0) { + t->tree_errno = errno; + r = TREE_ERROR_DIR; + } else { + t->depth++; + /* If it is a link, set up fd for the ascent. */ + if (t->stack->flags & isDirLink) { + t->stack->symlink_parent_fd = t->working_dir_fd; + t->openCount++; + if (t->openCount > t->maxOpenCount) + t->maxOpenCount = t->openCount; + } else + close(t->working_dir_fd); + /* Renew the current working directory. */ + t->working_dir_fd = new_fd; + t->flags &= ~onWorkingDir; + } + return (r); +} + +/* + * We've finished a directory; ascend back to the parent. + */ +static int +tree_ascend(struct tree *t) +{ + struct tree_entry *te; + int new_fd, r = 0, prev_dir_fd; + + te = t->stack; + prev_dir_fd = t->working_dir_fd; + if (te->flags & isDirLink) + new_fd = te->symlink_parent_fd; + else { + new_fd = open_on_current_dir(t, "..", O_RDONLY | O_CLOEXEC); + __archive_ensure_cloexec_flag(new_fd); + } + if (new_fd < 0) { + t->tree_errno = errno; + r = TREE_ERROR_FATAL; + } else { + /* Renew the current working directory. */ + t->working_dir_fd = new_fd; + t->flags &= ~onWorkingDir; + /* Current directory has been changed, we should + * close an fd of previous working directory. */ + close_and_restore_time(prev_dir_fd, t, &te->restore_time); + if (te->flags & isDirLink) { + t->openCount--; + te->symlink_parent_fd = -1; + } + t->depth--; + } + return (r); +} + +/* + * Return to the initial directory where tree_open() was performed. + */ +static int +tree_enter_initial_dir(struct tree *t) +{ + int r = 0; + + if ((t->flags & onInitialDir) == 0) { + r = fchdir(t->initial_dir_fd); + if (r == 0) { + t->flags &= ~onWorkingDir; + t->flags |= onInitialDir; + } + } + return (r); +} + +/* + * Restore working directory of directory traversals. + */ +static int +tree_enter_working_dir(struct tree *t) +{ + int r = 0; + + /* + * Change the current directory if really needed. + * Sometimes this is unneeded when we did not do + * descent. + */ + if (t->depth > 0 && (t->flags & onWorkingDir) == 0) { + r = fchdir(t->working_dir_fd); + if (r == 0) { + t->flags &= ~onInitialDir; + t->flags |= onWorkingDir; + } + } + return (r); +} + +static int +tree_current_dir_fd(struct tree *t) +{ + return (t->working_dir_fd); +} + +/* + * Pop the working stack. + */ +static void +tree_pop(struct tree *t) +{ + struct tree_entry *te; + + t->path.s[t->dirname_length] = '\0'; + t->path.length = t->dirname_length; + if (t->stack == t->current && t->current != NULL) + t->current = t->current->parent; + te = t->stack; + t->stack = te->next; + t->dirname_length = te->dirname_length; + t->basename = t->path.s + t->dirname_length; + while (t->basename[0] == '/') + t->basename++; + archive_string_free(&te->name); + free(te); +} + +/* + * Get the next item in the tree traversal. + */ +static int +tree_next(struct tree *t) +{ + int r; + + while (t->stack != NULL) { + /* If there's an open dir, get the next entry from there. */ + if (t->d != INVALID_DIR_HANDLE) { + r = tree_dir_next_posix(t); + if (r == 0) + continue; + return (r); + } + + if (t->stack->flags & needsFirstVisit) { + /* Top stack item needs a regular visit. */ + t->current = t->stack; + tree_append(t, t->stack->name.s, + archive_strlen(&(t->stack->name))); + /* t->dirname_length = t->path_length; */ + /* tree_pop(t); */ + t->stack->flags &= ~needsFirstVisit; + return (t->visit_type = TREE_REGULAR); + } else if (t->stack->flags & needsDescent) { + /* Top stack item is dir to descend into. */ + t->current = t->stack; + tree_append(t, t->stack->name.s, + archive_strlen(&(t->stack->name))); + t->stack->flags &= ~needsDescent; + r = tree_descent(t); + if (r != 0) { + tree_pop(t); + t->visit_type = r; + } else + t->visit_type = TREE_POSTDESCENT; + return (t->visit_type); + } else if (t->stack->flags & needsOpen) { + t->stack->flags &= ~needsOpen; + r = tree_dir_next_posix(t); + if (r == 0) + continue; + return (r); + } else if (t->stack->flags & needsAscent) { + /* Top stack item is dir and we're done with it. */ + r = tree_ascend(t); + tree_pop(t); + t->visit_type = r != 0 ? r : TREE_POSTASCENT; + return (t->visit_type); + } else { + /* Top item on stack is dead. */ + tree_pop(t); + t->flags &= ~hasLstat; + t->flags &= ~hasStat; + } + } + return (t->visit_type = 0); +} + +static int +tree_dir_next_posix(struct tree *t) +{ + int r; + const char *name; + size_t namelen; + + if (t->d == NULL) { +#if defined(USE_READDIR_R) + size_t dirent_size; +#endif + +#if defined(HAVE_FDOPENDIR) + t->d = fdopendir(tree_dup(t->working_dir_fd)); +#else /* HAVE_FDOPENDIR */ + if (tree_enter_working_dir(t) == 0) { + t->d = opendir("."); +#if HAVE_DIRFD || defined(dirfd) + __archive_ensure_cloexec_flag(dirfd(t->d)); +#endif + } +#endif /* HAVE_FDOPENDIR */ + if (t->d == NULL) { + r = tree_ascend(t); /* Undo "chdir" */ + tree_pop(t); + t->tree_errno = errno; + t->visit_type = r != 0 ? r : TREE_ERROR_DIR; + return (t->visit_type); + } +#if defined(USE_READDIR_R) + dirent_size = offsetof(struct dirent, d_name) + + t->filesystem_table[t->current->filesystem_id].name_max + 1; + if (t->dirent == NULL || t->dirent_allocated < dirent_size) { + free(t->dirent); + t->dirent = malloc(dirent_size); + if (t->dirent == NULL) { + closedir(t->d); + t->d = INVALID_DIR_HANDLE; + (void)tree_ascend(t); + tree_pop(t); + t->tree_errno = ENOMEM; + t->visit_type = TREE_ERROR_DIR; + return (t->visit_type); + } + t->dirent_allocated = dirent_size; + } +#endif /* USE_READDIR_R */ + } + for (;;) { + errno = 0; +#if defined(USE_READDIR_R) + r = readdir_r(t->d, t->dirent, &t->de); +#ifdef _AIX + /* Note: According to the man page, return value 9 indicates + * that the readdir_r was not successful and the error code + * is set to the global errno variable. And then if the end + * of directory entries was reached, the return value is 9 + * and the third parameter is set to NULL and errno is + * unchanged. */ + if (r == 9) + r = errno; +#endif /* _AIX */ + if (r != 0 || t->de == NULL) { +#else + t->de = readdir(t->d); + if (t->de == NULL) { + r = errno; +#endif + closedir(t->d); + t->d = INVALID_DIR_HANDLE; + if (r != 0) { + t->tree_errno = r; + t->visit_type = TREE_ERROR_DIR; + return (t->visit_type); + } else + return (0); + } + name = t->de->d_name; + namelen = D_NAMELEN(t->de); + t->flags &= ~hasLstat; + t->flags &= ~hasStat; + if (name[0] == '.' && name[1] == '\0') + continue; + if (name[0] == '.' && name[1] == '.' && name[2] == '\0') + continue; + tree_append(t, name, namelen); + return (t->visit_type = TREE_REGULAR); + } +} + + +/* + * Get the stat() data for the entry just returned from tree_next(). + */ +static const struct stat * +tree_current_stat(struct tree *t) +{ + if (!(t->flags & hasStat)) { +#ifdef HAVE_FSTATAT + if (fstatat(tree_current_dir_fd(t), + tree_current_access_path(t), &t->st, 0) != 0) +#else + if (tree_enter_working_dir(t) != 0) + return NULL; + if (la_stat(tree_current_access_path(t), &t->st) != 0) +#endif + return NULL; + t->flags |= hasStat; + } + return (&t->st); +} + +/* + * Get the lstat() data for the entry just returned from tree_next(). + */ +static const struct stat * +tree_current_lstat(struct tree *t) +{ + if (!(t->flags & hasLstat)) { +#ifdef HAVE_FSTATAT + if (fstatat(tree_current_dir_fd(t), + tree_current_access_path(t), &t->lst, + AT_SYMLINK_NOFOLLOW) != 0) +#else + if (tree_enter_working_dir(t) != 0) + return NULL; + if (lstat(tree_current_access_path(t), &t->lst) != 0) +#endif + return NULL; + t->flags |= hasLstat; + } + return (&t->lst); +} + +/* + * Test whether current entry is a dir or link to a dir. + */ +static int +tree_current_is_dir(struct tree *t) +{ + const struct stat *st; + /* + * If we already have lstat() info, then try some + * cheap tests to determine if this is a dir. + */ + if (t->flags & hasLstat) { + /* If lstat() says it's a dir, it must be a dir. */ + st = tree_current_lstat(t); + if (st == NULL) + return 0; + if (S_ISDIR(st->st_mode)) + return 1; + /* Not a dir; might be a link to a dir. */ + /* If it's not a link, then it's not a link to a dir. */ + if (!S_ISLNK(st->st_mode)) + return 0; + /* + * It's a link, but we don't know what it's a link to, + * so we'll have to use stat(). + */ + } + + st = tree_current_stat(t); + /* If we can't stat it, it's not a dir. */ + if (st == NULL) + return 0; + /* Use the definitive test. Hopefully this is cached. */ + return (S_ISDIR(st->st_mode)); +} + +/* + * Test whether current entry is a physical directory. Usually, we + * already have at least one of stat() or lstat() in memory, so we + * use tricks to try to avoid an extra trip to the disk. + */ +static int +tree_current_is_physical_dir(struct tree *t) +{ + const struct stat *st; + + /* + * If stat() says it isn't a dir, then it's not a dir. + * If stat() data is cached, this check is free, so do it first. + */ + if (t->flags & hasStat) { + st = tree_current_stat(t); + if (st == NULL) + return (0); + if (!S_ISDIR(st->st_mode)) + return (0); + } + + /* + * Either stat() said it was a dir (in which case, we have + * to determine whether it's really a link to a dir) or + * stat() info wasn't available. So we use lstat(), which + * hopefully is already cached. + */ + + st = tree_current_lstat(t); + /* If we can't stat it, it's not a dir. */ + if (st == NULL) + return 0; + /* Use the definitive test. Hopefully this is cached. */ + return (S_ISDIR(st->st_mode)); +} + +/* + * Test whether the same file has been in the tree as its parent. + */ +static int +tree_target_is_same_as_parent(struct tree *t, const struct stat *st) +{ + struct tree_entry *te; + + for (te = t->current->parent; te != NULL; te = te->parent) { + if (te->dev == (int64_t)st->st_dev && + te->ino == (int64_t)st->st_ino) + return (1); + } + return (0); +} + +/* + * Test whether the current file is symbolic link target and + * on the other filesystem. + */ +static int +tree_current_is_symblic_link_target(struct tree *t) +{ + static const struct stat *lst, *st; + + lst = tree_current_lstat(t); + st = tree_current_stat(t); + return (st != NULL && lst != NULL && + (int64_t)st->st_dev == t->current_filesystem->dev && + st->st_dev != lst->st_dev); +} + +/* + * Return the access path for the entry just returned from tree_next(). + */ +static const char * +tree_current_access_path(struct tree *t) +{ + return (t->basename); +} + +/* + * Return the full path for the entry just returned from tree_next(). + */ +static const char * +tree_current_path(struct tree *t) +{ + return (t->path.s); +} + +/* + * Terminate the traversal. + */ +static void +tree_close(struct tree *t) +{ + + if (t == NULL) + return; + if (t->entry_fd >= 0) { + close_and_restore_time(t->entry_fd, t, &t->restore_time); + t->entry_fd = -1; + } + /* Close the handle of readdir(). */ + if (t->d != INVALID_DIR_HANDLE) { + closedir(t->d); + t->d = INVALID_DIR_HANDLE; + } + /* Release anything remaining in the stack. */ + while (t->stack != NULL) { + if (t->stack->flags & isDirLink) + close(t->stack->symlink_parent_fd); + tree_pop(t); + } + if (t->working_dir_fd >= 0) { + close(t->working_dir_fd); + t->working_dir_fd = -1; + } + if (t->initial_dir_fd >= 0) { + close(t->initial_dir_fd); + t->initial_dir_fd = -1; + } +} + +/* + * Release any resources. + */ +static void +tree_free(struct tree *t) +{ + int i; + + if (t == NULL) + return; + archive_string_free(&t->path); +#if defined(USE_READDIR_R) + free(t->dirent); +#endif + free(t->sparse_list); + for (i = 0; i < t->max_filesystem_id; i++) + free(t->filesystem_table[i].allocation_ptr); + free(t->filesystem_table); + free(t); +} + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_private.h new file mode 100644 index 0000000000..bc8abc15d1 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_private.h @@ -0,0 +1,98 @@ +/*- + * Copyright (c) 2003-2009 Tim Kientzle + * 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 + * in this position and unchanged. + * 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(S) ``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(S) 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. + * + * $FreeBSD: head/lib/libarchive/archive_read_disk_private.h 201105 2009-12-28 03:20:54Z kientzle $ + */ + +#ifndef ARCHIVE_READ_DISK_PRIVATE_H_INCLUDED +#define ARCHIVE_READ_DISK_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +#include "archive_platform_acl.h" + +struct tree; +struct archive_entry; + +struct archive_read_disk { + struct archive archive; + + /* Reused by archive_read_next_header() */ + struct archive_entry *entry; + + /* + * Symlink mode is one of 'L'ogical, 'P'hysical, or 'H'ybrid, + * following an old BSD convention. 'L' follows all symlinks, + * 'P' follows none, 'H' follows symlinks only for the first + * item. + */ + char symlink_mode; + + /* + * Since symlink interaction changes, we need to track whether + * we're following symlinks for the current item. 'L' mode above + * sets this true, 'P' sets it false, 'H' changes it as we traverse. + */ + char follow_symlinks; /* Either 'L' or 'P'. */ + + /* Directory traversals. */ + struct tree *tree; + int (*open_on_current_dir)(struct tree*, const char *, int); + int (*tree_current_dir_fd)(struct tree*); + int (*tree_enter_working_dir)(struct tree*); + + /* Bitfield with ARCHIVE_READDISK_* tunables */ + int flags; + + const char * (*lookup_gname)(void *private, int64_t gid); + void (*cleanup_gname)(void *private); + void *lookup_gname_data; + const char * (*lookup_uname)(void *private, int64_t uid); + void (*cleanup_uname)(void *private); + void *lookup_uname_data; + + int (*metadata_filter_func)(struct archive *, void *, + struct archive_entry *); + void *metadata_filter_data; + + /* ARCHIVE_MATCH object. */ + struct archive *matching; + /* Callback function, this will be invoked when ARCHIVE_MATCH + * archive_match_*_excluded_ae return true. */ + void (*excluded_cb_func)(struct archive *, void *, + struct archive_entry *); + void *excluded_cb_data; +}; + +const char * +archive_read_disk_entry_setup_path(struct archive_read_disk *, + struct archive_entry *, int *); + +int +archive_read_disk_entry_setup_acls(struct archive_read_disk *, + struct archive_entry *, int *); +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_set_standard_lookup.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_set_standard_lookup.c new file mode 100644 index 0000000000..c7fd2471ec --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_set_standard_lookup.c @@ -0,0 +1,313 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_disk_set_standard_lookup.c 201109 2009-12-28 03:30:31Z kientzle $"); + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_GRP_H +#include <grp.h> +#endif +#ifdef HAVE_PWD_H +#include <pwd.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" + +#if defined(_WIN32) && !defined(__CYGWIN__) +int +archive_read_disk_set_standard_lookup(struct archive *a) +{ + archive_set_error(a, -1, "Standard lookups not available on Windows"); + return (ARCHIVE_FATAL); +} +#else /* ! (_WIN32 && !__CYGWIN__) */ +#define name_cache_size 127 + +static const char * const NO_NAME = "(noname)"; + +struct name_cache { + struct archive *archive; + char *buff; + size_t buff_size; + int probes; + int hits; + size_t size; + struct { + id_t id; + const char *name; + } cache[name_cache_size]; +}; + +static const char * lookup_gname(void *, int64_t); +static const char * lookup_uname(void *, int64_t); +static void cleanup(void *); +static const char * lookup_gname_helper(struct name_cache *, id_t gid); +static const char * lookup_uname_helper(struct name_cache *, id_t uid); + +/* + * Installs functions that use getpwuid()/getgrgid()---along with + * a simple cache to accelerate such lookups---into the archive_read_disk + * object. This is in a separate file because getpwuid()/getgrgid() + * can pull in a LOT of library code (including NIS/LDAP functions, which + * pull in DNS resolvers, etc). This can easily top 500kB, which makes + * it inappropriate for some space-constrained applications. + * + * Applications that are size-sensitive may want to just use the + * real default functions (defined in archive_read_disk.c) that just + * use the uid/gid without the lookup. Or define your own custom functions + * if you prefer. + */ +int +archive_read_disk_set_standard_lookup(struct archive *a) +{ + struct name_cache *ucache = malloc(sizeof(struct name_cache)); + struct name_cache *gcache = malloc(sizeof(struct name_cache)); + + if (ucache == NULL || gcache == NULL) { + archive_set_error(a, ENOMEM, + "Can't allocate uname/gname lookup cache"); + free(ucache); + free(gcache); + return (ARCHIVE_FATAL); + } + + memset(ucache, 0, sizeof(*ucache)); + ucache->archive = a; + ucache->size = name_cache_size; + memset(gcache, 0, sizeof(*gcache)); + gcache->archive = a; + gcache->size = name_cache_size; + + archive_read_disk_set_gname_lookup(a, gcache, lookup_gname, cleanup); + archive_read_disk_set_uname_lookup(a, ucache, lookup_uname, cleanup); + + return (ARCHIVE_OK); +} + +static void +cleanup(void *data) +{ + struct name_cache *cache = (struct name_cache *)data; + size_t i; + + if (cache != NULL) { + for (i = 0; i < cache->size; i++) { + if (cache->cache[i].name != NULL && + cache->cache[i].name != NO_NAME) + free((void *)(uintptr_t)cache->cache[i].name); + } + free(cache->buff); + free(cache); + } +} + +/* + * Lookup uid/gid from uname/gname, return NULL if no match. + */ +static const char * +lookup_name(struct name_cache *cache, + const char * (*lookup_fn)(struct name_cache *, id_t), id_t id) +{ + const char *name; + int slot; + + + cache->probes++; + + slot = id % cache->size; + if (cache->cache[slot].name != NULL) { + if (cache->cache[slot].id == id) { + cache->hits++; + if (cache->cache[slot].name == NO_NAME) + return (NULL); + return (cache->cache[slot].name); + } + if (cache->cache[slot].name != NO_NAME) + free((void *)(uintptr_t)cache->cache[slot].name); + cache->cache[slot].name = NULL; + } + + name = (lookup_fn)(cache, id); + if (name == NULL) { + /* Cache and return the negative response. */ + cache->cache[slot].name = NO_NAME; + cache->cache[slot].id = id; + return (NULL); + } + + cache->cache[slot].name = name; + cache->cache[slot].id = id; + return (cache->cache[slot].name); +} + +static const char * +lookup_uname(void *data, int64_t uid) +{ + struct name_cache *uname_cache = (struct name_cache *)data; + return (lookup_name(uname_cache, + &lookup_uname_helper, (id_t)uid)); +} + +#if HAVE_GETPWUID_R +static const char * +lookup_uname_helper(struct name_cache *cache, id_t id) +{ + struct passwd pwent, *result; + char * nbuff; + size_t nbuff_size; + int r; + + if (cache->buff_size == 0) { + cache->buff_size = 256; + cache->buff = malloc(cache->buff_size); + } + if (cache->buff == NULL) + return (NULL); + for (;;) { + result = &pwent; /* Old getpwuid_r ignores last arg. */ + r = getpwuid_r((uid_t)id, &pwent, + cache->buff, cache->buff_size, &result); + if (r == 0) + break; + if (r != ERANGE) + break; + /* ERANGE means our buffer was too small, but POSIX + * doesn't tell us how big the buffer should be, so + * we just double it and try again. Because the buffer + * is kept around in the cache object, we shouldn't + * have to do this very often. */ + nbuff_size = cache->buff_size * 2; + nbuff = realloc(cache->buff, nbuff_size); + if (nbuff == NULL) + break; + cache->buff = nbuff; + cache->buff_size = nbuff_size; + } + if (r != 0) { + archive_set_error(cache->archive, errno, + "Can't lookup user for id %d", (int)id); + return (NULL); + } + if (result == NULL) + return (NULL); + + return strdup(result->pw_name); +} +#else +static const char * +lookup_uname_helper(struct name_cache *cache, id_t id) +{ + struct passwd *result; + (void)cache; /* UNUSED */ + + result = getpwuid((uid_t)id); + + if (result == NULL) + return (NULL); + + return strdup(result->pw_name); +} +#endif + +static const char * +lookup_gname(void *data, int64_t gid) +{ + struct name_cache *gname_cache = (struct name_cache *)data; + return (lookup_name(gname_cache, + &lookup_gname_helper, (id_t)gid)); +} + +#if HAVE_GETGRGID_R +static const char * +lookup_gname_helper(struct name_cache *cache, id_t id) +{ + struct group grent, *result; + char * nbuff; + size_t nbuff_size; + int r; + + if (cache->buff_size == 0) { + cache->buff_size = 256; + cache->buff = malloc(cache->buff_size); + } + if (cache->buff == NULL) + return (NULL); + for (;;) { + result = &grent; /* Old getgrgid_r ignores last arg. */ + r = getgrgid_r((gid_t)id, &grent, + cache->buff, cache->buff_size, &result); + if (r == 0) + break; + if (r != ERANGE) + break; + /* ERANGE means our buffer was too small, but POSIX + * doesn't tell us how big the buffer should be, so + * we just double it and try again. */ + nbuff_size = cache->buff_size * 2; + nbuff = realloc(cache->buff, nbuff_size); + if (nbuff == NULL) + break; + cache->buff = nbuff; + cache->buff_size = nbuff_size; + } + if (r != 0) { + archive_set_error(cache->archive, errno, + "Can't lookup group for id %d", (int)id); + return (NULL); + } + if (result == NULL) + return (NULL); + + return strdup(result->gr_name); +} +#else +static const char * +lookup_gname_helper(struct name_cache *cache, id_t id) +{ + struct group *result; + (void)cache; /* UNUSED */ + + result = getgrgid((gid_t)id); + + if (result == NULL) + return (NULL); + + return strdup(result->gr_name); +} +#endif + +#endif /* ! (_WIN32 && !__CYGWIN__) */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_windows.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_windows.c new file mode 100644 index 0000000000..fdd376f9b9 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_disk_windows.c @@ -0,0 +1,2477 @@ +/*- + * Copyright (c) 2003-2009 Tim Kientzle + * Copyright (c) 2010-2012 Michihiro NAKAJIMA + * 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 + * in this position and unchanged. + * 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(S) ``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(S) 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. + */ +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#if defined(_WIN32) && !defined(__CYGWIN__) + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#include <winioctl.h> + +#include "archive.h" +#include "archive_string.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_read_disk_private.h" + +#ifndef O_BINARY +#define O_BINARY 0 +#endif +#ifndef IO_REPARSE_TAG_SYMLINK +/* Old SDKs do not provide IO_REPARSE_TAG_SYMLINK */ +#define IO_REPARSE_TAG_SYMLINK 0xA000000CL +#endif + +/*- + * This is a new directory-walking system that addresses a number + * of problems I've had with fts(3). In particular, it has no + * pathname-length limits (other than the size of 'int'), handles + * deep logical traversals, uses considerably less memory, and has + * an opaque interface (easier to modify in the future). + * + * Internally, it keeps a single list of "tree_entry" items that + * represent filesystem objects that require further attention. + * Non-directories are not kept in memory: they are pulled from + * readdir(), returned to the client, then freed as soon as possible. + * Any directory entry to be traversed gets pushed onto the stack. + * + * There is surprisingly little information that needs to be kept for + * each item on the stack. Just the name, depth (represented here as the + * string length of the parent directory's pathname), and some markers + * indicating how to get back to the parent (via chdir("..") for a + * regular dir or via fchdir(2) for a symlink). + */ + +struct restore_time { + const wchar_t *full_path; + FILETIME lastWriteTime; + FILETIME lastAccessTime; + mode_t filetype; +}; + +struct tree_entry { + int depth; + struct tree_entry *next; + struct tree_entry *parent; + size_t full_path_dir_length; + struct archive_wstring name; + struct archive_wstring full_path; + size_t dirname_length; + int64_t dev; + int64_t ino; + int flags; + int filesystem_id; + /* How to restore time of a directory. */ + struct restore_time restore_time; +}; + +struct filesystem { + int64_t dev; + int synthetic; + int remote; + DWORD bytesPerSector; +}; + +/* Definitions for tree_entry.flags bitmap. */ +#define isDir 1 /* This entry is a regular directory. */ +#define isDirLink 2 /* This entry is a symbolic link to a directory. */ +#define needsFirstVisit 4 /* This is an initial entry. */ +#define needsDescent 8 /* This entry needs to be previsited. */ +#define needsOpen 16 /* This is a directory that needs to be opened. */ +#define needsAscent 32 /* This entry needs to be postvisited. */ + +/* + * On Windows, "first visit" is handled as a pattern to be handed to + * _findfirst(). This is consistent with Windows conventions that + * file patterns are handled within the application. On Posix, + * "first visit" is just returned to the client. + */ + +#define MAX_OVERLAPPED 8 +#define READ_BUFFER_SIZE (1024 * 64) /* Default to 64KB per https://technet.microsoft.com/en-us/library/cc938632.aspx */ +#define DIRECT_IO 0/* Disabled */ +#define ASYNC_IO 1/* Enabled */ + +/* + * Local data for this package. + */ +struct tree { + struct tree_entry *stack; + struct tree_entry *current; + HANDLE d; + WIN32_FIND_DATAW _findData; + WIN32_FIND_DATAW *findData; + int flags; + int visit_type; + /* Error code from last failed operation. */ + int tree_errno; + + /* A full path with "\\?\" prefix. */ + struct archive_wstring full_path; + size_t full_path_dir_length; + /* Dynamically-sized buffer for holding path */ + struct archive_wstring path; + + /* Last path element */ + const wchar_t *basename; + /* Leading dir length */ + size_t dirname_length; + + int depth; + + BY_HANDLE_FILE_INFORMATION lst; + BY_HANDLE_FILE_INFORMATION st; + int descend; + /* How to restore time of a file. */ + struct restore_time restore_time; + + struct entry_sparse { + int64_t length; + int64_t offset; + } *sparse_list, *current_sparse; + int sparse_count; + int sparse_list_size; + + char initial_symlink_mode; + char symlink_mode; + struct filesystem *current_filesystem; + struct filesystem *filesystem_table; + int initial_filesystem_id; + int current_filesystem_id; + int max_filesystem_id; + int allocated_filesystem; + + HANDLE entry_fh; + int entry_eof; + int64_t entry_remaining_bytes; + int64_t entry_total; + + int ol_idx_doing; + int ol_idx_done; + int ol_num_doing; + int ol_num_done; + int64_t ol_remaining_bytes; + int64_t ol_total; + struct la_overlapped { + OVERLAPPED ol; + struct archive * _a; + unsigned char *buff; + size_t buff_size; + int64_t offset; + size_t bytes_expected; + size_t bytes_transferred; + } ol[MAX_OVERLAPPED]; + int direct_io; + int async_io; +}; + +#define bhfi_dev(bhfi) ((bhfi)->dwVolumeSerialNumber) +/* Treat FileIndex as i-node. We should remove a sequence number + * which is high-16-bits of nFileIndexHigh. */ +#define bhfi_ino(bhfi) \ + ((((int64_t)((bhfi)->nFileIndexHigh & 0x0000FFFFUL)) << 32) \ + + (bhfi)->nFileIndexLow) + +/* Definitions for tree.flags bitmap. */ +#define hasStat 16 /* The st entry is valid. */ +#define hasLstat 32 /* The lst entry is valid. */ +#define needsRestoreTimes 128 + +static int +tree_dir_next_windows(struct tree *t, const wchar_t *pattern); + +/* Initiate/terminate a tree traversal. */ +static struct tree *tree_open(const wchar_t *, int, int); +static struct tree *tree_reopen(struct tree *, const wchar_t *, int); +static void tree_close(struct tree *); +static void tree_free(struct tree *); +static void tree_push(struct tree *, const wchar_t *, const wchar_t *, + int, int64_t, int64_t, struct restore_time *); + +/* + * tree_next() returns Zero if there is no next entry, non-zero if + * there is. Note that directories are visited three times. + * Directories are always visited first as part of enumerating their + * parent; that is a "regular" visit. If tree_descend() is invoked at + * that time, the directory is added to a work list and will + * subsequently be visited two more times: once just after descending + * into the directory ("postdescent") and again just after ascending + * back to the parent ("postascent"). + * + * TREE_ERROR_DIR is returned if the descent failed (because the + * directory couldn't be opened, for instance). This is returned + * instead of TREE_POSTDESCENT/TREE_POSTASCENT. TREE_ERROR_DIR is not a + * fatal error, but it does imply that the relevant subtree won't be + * visited. TREE_ERROR_FATAL is returned for an error that left the + * traversal completely hosed. Right now, this is only returned for + * chdir() failures during ascent. + */ +#define TREE_REGULAR 1 +#define TREE_POSTDESCENT 2 +#define TREE_POSTASCENT 3 +#define TREE_ERROR_DIR -1 +#define TREE_ERROR_FATAL -2 + +static int tree_next(struct tree *); + +/* + * Return information about the current entry. + */ + +/* + * The current full pathname, length of the full pathname, and a name + * that can be used to access the file. Because tree does use chdir + * extensively, the access path is almost never the same as the full + * current path. + * + */ +static const wchar_t *tree_current_path(struct tree *); +static const wchar_t *tree_current_access_path(struct tree *); + +/* + * Request the lstat() or stat() data for the current path. Since the + * tree package needs to do some of this anyway, and caches the + * results, you should take advantage of it here if you need it rather + * than make a redundant stat() or lstat() call of your own. + */ +static const BY_HANDLE_FILE_INFORMATION *tree_current_stat(struct tree *); +static const BY_HANDLE_FILE_INFORMATION *tree_current_lstat(struct tree *); + +/* The following functions use tricks to avoid a certain number of + * stat()/lstat() calls. */ +/* "is_physical_dir" is equivalent to S_ISDIR(tree_current_lstat()->st_mode) */ +static int tree_current_is_physical_dir(struct tree *); +/* "is_physical_link" is equivalent to S_ISLNK(tree_current_lstat()->st_mode) */ +static int tree_current_is_physical_link(struct tree *); +/* Instead of archive_entry_copy_stat for BY_HANDLE_FILE_INFORMATION */ +static void tree_archive_entry_copy_bhfi(struct archive_entry *, + struct tree *, const BY_HANDLE_FILE_INFORMATION *); +/* "is_dir" is equivalent to S_ISDIR(tree_current_stat()->st_mode) */ +static int tree_current_is_dir(struct tree *); +static int update_current_filesystem(struct archive_read_disk *a, + int64_t dev); +static int setup_current_filesystem(struct archive_read_disk *); +static int tree_target_is_same_as_parent(struct tree *, + const BY_HANDLE_FILE_INFORMATION *); + +static int _archive_read_disk_open_w(struct archive *, const wchar_t *); +static int _archive_read_free(struct archive *); +static int _archive_read_close(struct archive *); +static int _archive_read_data_block(struct archive *, + const void **, size_t *, int64_t *); +static int _archive_read_next_header(struct archive *, + struct archive_entry **); +static int _archive_read_next_header2(struct archive *, + struct archive_entry *); +static const char *trivial_lookup_gname(void *, int64_t gid); +static const char *trivial_lookup_uname(void *, int64_t uid); +static int setup_sparse(struct archive_read_disk *, struct archive_entry *); +static int close_and_restore_time(HANDLE, struct tree *, + struct restore_time *); +static int setup_sparse_from_disk(struct archive_read_disk *, + struct archive_entry *, HANDLE); +static int la_linkname_from_handle(HANDLE, wchar_t **, int *); +static int la_linkname_from_pathw(const wchar_t *, wchar_t **, int *); +static void entry_symlink_from_pathw(struct archive_entry *, + const wchar_t *path); + +typedef struct _REPARSE_DATA_BUFFER { + ULONG ReparseTag; + USHORT ReparseDataLength; + USHORT Reserved; + union { + struct { + USHORT SubstituteNameOffset; + USHORT SubstituteNameLength; + USHORT PrintNameOffset; + USHORT PrintNameLength; + ULONG Flags; + WCHAR PathBuffer[1]; + } SymbolicLinkReparseBuffer; + struct { + USHORT SubstituteNameOffset; + USHORT SubstituteNameLength; + USHORT PrintNameOffset; + USHORT PrintNameLength; + WCHAR PathBuffer[1]; + } MountPointReparseBuffer; + struct { + UCHAR DataBuffer[1]; + } GenericReparseBuffer; + } DUMMYUNIONNAME; +} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER; + +/* + * Reads the target of a symbolic link + * + * Returns 0 on success and -1 on failure + * outbuf is allocated in the function + */ +static int +la_linkname_from_handle(HANDLE h, wchar_t **linkname, int *linktype) +{ + DWORD inbytes; + REPARSE_DATA_BUFFER *buf; + BY_HANDLE_FILE_INFORMATION st; + size_t len; + BOOL ret; + BYTE *indata; + wchar_t *tbuf; + + ret = GetFileInformationByHandle(h, &st); + if (ret == 0 || + (st.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0) { + return (-1); + } + + indata = malloc(MAXIMUM_REPARSE_DATA_BUFFER_SIZE); + ret = DeviceIoControl(h, FSCTL_GET_REPARSE_POINT, NULL, 0, indata, + 1024, &inbytes, NULL); + if (ret == 0) { + la_dosmaperr(GetLastError()); + free(indata); + return (-1); + } + + buf = (REPARSE_DATA_BUFFER *) indata; + if (buf->ReparseTag != IO_REPARSE_TAG_SYMLINK) { + free(indata); + /* File is not a symbolic link */ + errno = EINVAL; + return (-1); + } + + len = buf->SymbolicLinkReparseBuffer.SubstituteNameLength; + if (len <= 0) { + free(indata); + return (-1); + } + + tbuf = malloc(len + 1 * sizeof(wchar_t)); + if (tbuf == NULL) { + free(indata); + return (-1); + } + + memcpy(tbuf, &((BYTE *)buf->SymbolicLinkReparseBuffer.PathBuffer) + [buf->SymbolicLinkReparseBuffer.SubstituteNameOffset], len); + free(indata); + + tbuf[len / sizeof(wchar_t)] = L'\0'; + + *linkname = tbuf; + + /* + * Translate backslashes to slashes for libarchive internal use + */ + while(*tbuf != L'\0') { + if (*tbuf == L'\\') + *tbuf = L'/'; + tbuf++; + } + + if ((st.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) + *linktype = AE_SYMLINK_TYPE_FILE; + else + *linktype = AE_SYMLINK_TYPE_DIRECTORY; + + return (0); +} + +/* + * Returns AE_SYMLINK_TYPE_FILE, AE_SYMLINK_TYPE_DIRECTORY or -1 on error + */ +static int +la_linkname_from_pathw(const wchar_t *path, wchar_t **outbuf, int *linktype) +{ + HANDLE h; + const DWORD flag = FILE_FLAG_BACKUP_SEMANTICS | + FILE_FLAG_OPEN_REPARSE_POINT; + int ret; + + h = CreateFileW(path, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, flag, + NULL); + if (h == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + return (-1); + } + + ret = la_linkname_from_handle(h, outbuf, linktype); + CloseHandle(h); + + return (ret); +} + +static void +entry_symlink_from_pathw(struct archive_entry *entry, const wchar_t *path) +{ + wchar_t *linkname = NULL; + int ret, linktype; + + ret = la_linkname_from_pathw(path, &linkname, &linktype); + if (ret != 0) + return; + if (linktype >= 0) { + archive_entry_copy_symlink_w(entry, linkname); + archive_entry_set_symlink_type(entry, linktype); + } + free(linkname); + + return; +} + +static struct archive_vtable * +archive_read_disk_vtable(void) +{ + static struct archive_vtable av; + static int inited = 0; + + if (!inited) { + av.archive_free = _archive_read_free; + av.archive_close = _archive_read_close; + av.archive_read_data_block = _archive_read_data_block; + av.archive_read_next_header = _archive_read_next_header; + av.archive_read_next_header2 = _archive_read_next_header2; + inited = 1; + } + return (&av); +} + +const char * +archive_read_disk_gname(struct archive *_a, la_int64_t gid) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + if (ARCHIVE_OK != __archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_gname")) + return (NULL); + if (a->lookup_gname == NULL) + return (NULL); + return ((*a->lookup_gname)(a->lookup_gname_data, gid)); +} + +const char * +archive_read_disk_uname(struct archive *_a, la_int64_t uid) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + if (ARCHIVE_OK != __archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_uname")) + return (NULL); + if (a->lookup_uname == NULL) + return (NULL); + return ((*a->lookup_uname)(a->lookup_uname_data, uid)); +} + +int +archive_read_disk_set_gname_lookup(struct archive *_a, + void *private_data, + const char * (*lookup_gname)(void *private, la_int64_t gid), + void (*cleanup_gname)(void *private)) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + archive_check_magic(&a->archive, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_set_gname_lookup"); + + if (a->cleanup_gname != NULL && a->lookup_gname_data != NULL) + (a->cleanup_gname)(a->lookup_gname_data); + + a->lookup_gname = lookup_gname; + a->cleanup_gname = cleanup_gname; + a->lookup_gname_data = private_data; + return (ARCHIVE_OK); +} + +int +archive_read_disk_set_uname_lookup(struct archive *_a, + void *private_data, + const char * (*lookup_uname)(void *private, int64_t uid), + void (*cleanup_uname)(void *private)) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + archive_check_magic(&a->archive, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_set_uname_lookup"); + + if (a->cleanup_uname != NULL && a->lookup_uname_data != NULL) + (a->cleanup_uname)(a->lookup_uname_data); + + a->lookup_uname = lookup_uname; + a->cleanup_uname = cleanup_uname; + a->lookup_uname_data = private_data; + return (ARCHIVE_OK); +} + +/* + * Create a new archive_read_disk object and initialize it with global state. + */ +struct archive * +archive_read_disk_new(void) +{ + struct archive_read_disk *a; + + a = (struct archive_read_disk *)calloc(1, sizeof(*a)); + if (a == NULL) + return (NULL); + a->archive.magic = ARCHIVE_READ_DISK_MAGIC; + a->archive.state = ARCHIVE_STATE_NEW; + a->archive.vtable = archive_read_disk_vtable(); + a->entry = archive_entry_new2(&a->archive); + a->lookup_uname = trivial_lookup_uname; + a->lookup_gname = trivial_lookup_gname; + a->flags = ARCHIVE_READDISK_MAC_COPYFILE; + return (&a->archive); +} + +static int +_archive_read_free(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + int r; + + if (_a == NULL) + return (ARCHIVE_OK); + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_read_free"); + + if (a->archive.state != ARCHIVE_STATE_CLOSED) + r = _archive_read_close(&a->archive); + else + r = ARCHIVE_OK; + + tree_free(a->tree); + if (a->cleanup_gname != NULL && a->lookup_gname_data != NULL) + (a->cleanup_gname)(a->lookup_gname_data); + if (a->cleanup_uname != NULL && a->lookup_uname_data != NULL) + (a->cleanup_uname)(a->lookup_uname_data); + archive_string_free(&a->archive.error_string); + archive_entry_free(a->entry); + a->archive.magic = 0; + free(a); + return (r); +} + +static int +_archive_read_close(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_read_close"); + + if (a->archive.state != ARCHIVE_STATE_FATAL) + a->archive.state = ARCHIVE_STATE_CLOSED; + + tree_close(a->tree); + + return (ARCHIVE_OK); +} + +static void +setup_symlink_mode(struct archive_read_disk *a, char symlink_mode, + int follow_symlinks) +{ + a->symlink_mode = symlink_mode; + a->follow_symlinks = follow_symlinks; + if (a->tree != NULL) { + a->tree->initial_symlink_mode = a->symlink_mode; + a->tree->symlink_mode = a->symlink_mode; + } +} + +int +archive_read_disk_set_symlink_logical(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_set_symlink_logical"); + setup_symlink_mode(a, 'L', 1); + return (ARCHIVE_OK); +} + +int +archive_read_disk_set_symlink_physical(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_set_symlink_physical"); + setup_symlink_mode(a, 'P', 0); + return (ARCHIVE_OK); +} + +int +archive_read_disk_set_symlink_hybrid(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_set_symlink_hybrid"); + setup_symlink_mode(a, 'H', 1);/* Follow symlinks initially. */ + return (ARCHIVE_OK); +} + +int +archive_read_disk_set_atime_restored(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_restore_atime"); + a->flags |= ARCHIVE_READDISK_RESTORE_ATIME; + if (a->tree != NULL) + a->tree->flags |= needsRestoreTimes; + return (ARCHIVE_OK); +} + +int +archive_read_disk_set_behavior(struct archive *_a, int flags) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + int r = ARCHIVE_OK; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_honor_nodump"); + + a->flags = flags; + + if (flags & ARCHIVE_READDISK_RESTORE_ATIME) + r = archive_read_disk_set_atime_restored(_a); + else { + if (a->tree != NULL) + a->tree->flags &= ~needsRestoreTimes; + } + return (r); +} + +/* + * Trivial implementations of gname/uname lookup functions. + * These are normally overridden by the client, but these stub + * versions ensure that we always have something that works. + */ +static const char * +trivial_lookup_gname(void *private_data, int64_t gid) +{ + (void)private_data; /* UNUSED */ + (void)gid; /* UNUSED */ + return (NULL); +} + +static const char * +trivial_lookup_uname(void *private_data, int64_t uid) +{ + (void)private_data; /* UNUSED */ + (void)uid; /* UNUSED */ + return (NULL); +} + +static int64_t +align_num_per_sector(struct tree *t, int64_t size) +{ + int64_t surplus; + + size += t->current_filesystem->bytesPerSector -1; + surplus = size % t->current_filesystem->bytesPerSector; + size -= surplus; + return (size); +} + +static int +start_next_async_read(struct archive_read_disk *a, struct tree *t) +{ + struct la_overlapped *olp; + DWORD buffbytes, rbytes; + + if (t->ol_remaining_bytes == 0) + return (ARCHIVE_EOF); + + olp = &(t->ol[t->ol_idx_doing]); + t->ol_idx_doing = (t->ol_idx_doing + 1) % MAX_OVERLAPPED; + + /* Allocate read buffer. */ + if (olp->buff == NULL) { + void *p; + size_t s = (size_t)align_num_per_sector(t, READ_BUFFER_SIZE); + p = VirtualAlloc(NULL, s, MEM_COMMIT, PAGE_READWRITE); + if (p == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Couldn't allocate memory"); + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + olp->buff = p; + olp->buff_size = s; + olp->_a = &a->archive; + olp->ol.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL); + if (olp->ol.hEvent == NULL) { + la_dosmaperr(GetLastError()); + archive_set_error(&a->archive, errno, + "CreateEvent failed"); + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + } else + ResetEvent(olp->ol.hEvent); + + buffbytes = (DWORD)olp->buff_size; + if (buffbytes > t->current_sparse->length) + buffbytes = (DWORD)t->current_sparse->length; + + /* Skip hole. */ + if (t->current_sparse->offset > t->ol_total) { + t->ol_remaining_bytes -= + t->current_sparse->offset - t->ol_total; + } + + olp->offset = t->current_sparse->offset; + olp->ol.Offset = (DWORD)(olp->offset & 0xffffffff); + olp->ol.OffsetHigh = (DWORD)(olp->offset >> 32); + + if (t->ol_remaining_bytes > buffbytes) { + olp->bytes_expected = buffbytes; + t->ol_remaining_bytes -= buffbytes; + } else { + olp->bytes_expected = (size_t)t->ol_remaining_bytes; + t->ol_remaining_bytes = 0; + } + olp->bytes_transferred = 0; + t->current_sparse->offset += buffbytes; + t->current_sparse->length -= buffbytes; + t->ol_total = t->current_sparse->offset; + if (t->current_sparse->length == 0 && t->ol_remaining_bytes > 0) + t->current_sparse++; + + if (!ReadFile(t->entry_fh, olp->buff, buffbytes, &rbytes, &(olp->ol))) { + DWORD lasterr; + + lasterr = GetLastError(); + if (lasterr == ERROR_HANDLE_EOF) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Reading file truncated"); + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } else if (lasterr != ERROR_IO_PENDING) { + if (lasterr == ERROR_NO_DATA) + errno = EAGAIN; + else if (lasterr == ERROR_ACCESS_DENIED) + errno = EBADF; + else + la_dosmaperr(lasterr); + archive_set_error(&a->archive, errno, "Read error"); + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + } else + olp->bytes_transferred = rbytes; + t->ol_num_doing++; + + return (t->ol_remaining_bytes == 0)? ARCHIVE_EOF: ARCHIVE_OK; +} + +static void +cancel_async(struct tree *t) +{ + if (t->ol_num_doing != t->ol_num_done) { + CancelIo(t->entry_fh); + t->ol_num_doing = t->ol_num_done = 0; + } +} + +static int +_archive_read_data_block(struct archive *_a, const void **buff, + size_t *size, int64_t *offset) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + struct tree *t = a->tree; + struct la_overlapped *olp; + DWORD bytes_transferred; + int r = ARCHIVE_FATAL; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_DATA, + "archive_read_data_block"); + + if (t->entry_eof || t->entry_remaining_bytes <= 0) { + r = ARCHIVE_EOF; + goto abort_read_data; + } + + /* + * Make a request to read the file in asynchronous. + */ + if (t->ol_num_doing == 0) { + do { + r = start_next_async_read(a, t); + if (r == ARCHIVE_FATAL) + goto abort_read_data; + if (!t->async_io) + break; + } while (r == ARCHIVE_OK && t->ol_num_doing < MAX_OVERLAPPED); + } else { + if ((r = start_next_async_read(a, t)) == ARCHIVE_FATAL) + goto abort_read_data; + } + + olp = &(t->ol[t->ol_idx_done]); + t->ol_idx_done = (t->ol_idx_done + 1) % MAX_OVERLAPPED; + if (olp->bytes_transferred) + bytes_transferred = (DWORD)olp->bytes_transferred; + else if (!GetOverlappedResult(t->entry_fh, &(olp->ol), + &bytes_transferred, TRUE)) { + la_dosmaperr(GetLastError()); + archive_set_error(&a->archive, errno, + "GetOverlappedResult failed"); + a->archive.state = ARCHIVE_STATE_FATAL; + r = ARCHIVE_FATAL; + goto abort_read_data; + } + t->ol_num_done++; + + if (bytes_transferred == 0 || + olp->bytes_expected != bytes_transferred) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Reading file truncated"); + a->archive.state = ARCHIVE_STATE_FATAL; + r = ARCHIVE_FATAL; + goto abort_read_data; + } + + *buff = olp->buff; + *size = bytes_transferred; + *offset = olp->offset; + if (olp->offset > t->entry_total) + t->entry_remaining_bytes -= olp->offset - t->entry_total; + t->entry_total = olp->offset + *size; + t->entry_remaining_bytes -= *size; + if (t->entry_remaining_bytes == 0) { + /* Close the current file descriptor */ + close_and_restore_time(t->entry_fh, t, &t->restore_time); + t->entry_fh = INVALID_HANDLE_VALUE; + t->entry_eof = 1; + } + return (ARCHIVE_OK); + +abort_read_data: + *buff = NULL; + *size = 0; + *offset = t->entry_total; + if (t->entry_fh != INVALID_HANDLE_VALUE) { + cancel_async(t); + /* Close the current file descriptor */ + close_and_restore_time(t->entry_fh, t, &t->restore_time); + t->entry_fh = INVALID_HANDLE_VALUE; + } + return (r); +} + +static int +next_entry(struct archive_read_disk *a, struct tree *t, + struct archive_entry *entry) +{ + const BY_HANDLE_FILE_INFORMATION *st; + const BY_HANDLE_FILE_INFORMATION *lst; + const char*name; + int descend, r; + + st = NULL; + lst = NULL; + t->descend = 0; + do { + switch (tree_next(t)) { + case TREE_ERROR_FATAL: + archive_set_error(&a->archive, t->tree_errno, + "%ls: Unable to continue traversing directory tree", + tree_current_path(t)); + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + case TREE_ERROR_DIR: + archive_set_error(&a->archive, t->tree_errno, + "%ls: Couldn't visit directory", + tree_current_path(t)); + return (ARCHIVE_FAILED); + case 0: + return (ARCHIVE_EOF); + case TREE_POSTDESCENT: + case TREE_POSTASCENT: + break; + case TREE_REGULAR: + lst = tree_current_lstat(t); + if (lst == NULL) { + archive_set_error(&a->archive, t->tree_errno, + "%ls: Cannot stat", + tree_current_path(t)); + return (ARCHIVE_FAILED); + } + break; + } + } while (lst == NULL); + + archive_entry_copy_pathname_w(entry, tree_current_path(t)); + + /* + * Perform path matching. + */ + if (a->matching) { + r = archive_match_path_excluded(a->matching, entry); + if (r < 0) { + archive_set_error(&(a->archive), errno, + "Failed : %s", archive_error_string(a->matching)); + return (r); + } + if (r) { + if (a->excluded_cb_func) + a->excluded_cb_func(&(a->archive), + a->excluded_cb_data, entry); + return (ARCHIVE_RETRY); + } + } + + /* + * Distinguish 'L'/'P'/'H' symlink following. + */ + switch(t->symlink_mode) { + case 'H': + /* 'H': After the first item, rest like 'P'. */ + t->symlink_mode = 'P'; + /* 'H': First item (from command line) like 'L'. */ + /* FALLTHROUGH */ + case 'L': + /* 'L': Do descend through a symlink to dir. */ + descend = tree_current_is_dir(t); + /* 'L': Follow symlinks to files. */ + a->symlink_mode = 'L'; + a->follow_symlinks = 1; + /* 'L': Archive symlinks as targets, if we can. */ + st = tree_current_stat(t); + if (st != NULL && !tree_target_is_same_as_parent(t, st)) + break; + /* If stat fails, we have a broken symlink; + * in that case, don't follow the link. */ + /* FALLTHROUGH */ + default: + /* 'P': Don't descend through a symlink to dir. */ + descend = tree_current_is_physical_dir(t); + /* 'P': Don't follow symlinks to files. */ + a->symlink_mode = 'P'; + a->follow_symlinks = 0; + /* 'P': Archive symlinks as symlinks. */ + st = lst; + break; + } + + if (update_current_filesystem(a, bhfi_dev(st)) != ARCHIVE_OK) { + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + if (t->initial_filesystem_id == -1) + t->initial_filesystem_id = t->current_filesystem_id; + if (a->flags & ARCHIVE_READDISK_NO_TRAVERSE_MOUNTS) { + if (t->initial_filesystem_id != t->current_filesystem_id) + return (ARCHIVE_RETRY); + } + t->descend = descend; + + tree_archive_entry_copy_bhfi(entry, t, st); + + /* Save the times to be restored. This must be in before + * calling archive_read_disk_descend() or any chance of it, + * especially, invoking a callback. */ + t->restore_time.lastWriteTime = st->ftLastWriteTime; + t->restore_time.lastAccessTime = st->ftLastAccessTime; + t->restore_time.filetype = archive_entry_filetype(entry); + + /* + * Perform time matching. + */ + if (a->matching) { + r = archive_match_time_excluded(a->matching, entry); + if (r < 0) { + archive_set_error(&(a->archive), errno, + "Failed : %s", archive_error_string(a->matching)); + return (r); + } + if (r) { + if (a->excluded_cb_func) + a->excluded_cb_func(&(a->archive), + a->excluded_cb_data, entry); + return (ARCHIVE_RETRY); + } + } + + /* Lookup uname/gname */ + name = archive_read_disk_uname(&(a->archive), archive_entry_uid(entry)); + if (name != NULL) + archive_entry_copy_uname(entry, name); + name = archive_read_disk_gname(&(a->archive), archive_entry_gid(entry)); + if (name != NULL) + archive_entry_copy_gname(entry, name); + + /* + * Perform owner matching. + */ + if (a->matching) { + r = archive_match_owner_excluded(a->matching, entry); + if (r < 0) { + archive_set_error(&(a->archive), errno, + "Failed : %s", archive_error_string(a->matching)); + return (r); + } + if (r) { + if (a->excluded_cb_func) + a->excluded_cb_func(&(a->archive), + a->excluded_cb_data, entry); + return (ARCHIVE_RETRY); + } + } + + /* + * File attributes + */ + if ((a->flags & ARCHIVE_READDISK_NO_FFLAGS) == 0) { + const int supported_attrs = + FILE_ATTRIBUTE_READONLY | + FILE_ATTRIBUTE_HIDDEN | + FILE_ATTRIBUTE_SYSTEM; + DWORD file_attrs = st->dwFileAttributes & supported_attrs; + if (file_attrs != 0) + archive_entry_set_fflags(entry, file_attrs, 0); + } + + /* + * Invoke a meta data filter callback. + */ + if (a->metadata_filter_func) { + if (!a->metadata_filter_func(&(a->archive), + a->metadata_filter_data, entry)) + return (ARCHIVE_RETRY); + } + + archive_entry_copy_sourcepath_w(entry, tree_current_access_path(t)); + + r = ARCHIVE_OK; + if (archive_entry_filetype(entry) == AE_IFREG && + archive_entry_size(entry) > 0) { + DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; + if (t->async_io) + flags |= FILE_FLAG_OVERLAPPED; + if (t->direct_io) + flags |= FILE_FLAG_NO_BUFFERING; + else + flags |= FILE_FLAG_SEQUENTIAL_SCAN; + t->entry_fh = CreateFileW(tree_current_access_path(t), + GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, flags, NULL); + if (t->entry_fh == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + archive_set_error(&a->archive, errno, + "Couldn't open %ls", tree_current_path(a->tree)); + return (ARCHIVE_FAILED); + } + + /* Find sparse data from the disk. */ + if (archive_entry_hardlink(entry) == NULL && + (st->dwFileAttributes & FILE_ATTRIBUTE_SPARSE_FILE) != 0) + r = setup_sparse_from_disk(a, entry, t->entry_fh); + } + return (r); +} + +static int +_archive_read_next_header(struct archive *_a, struct archive_entry **entryp) +{ + int ret; + struct archive_read_disk *a = (struct archive_read_disk *)_a; + *entryp = NULL; + ret = _archive_read_next_header2(_a, a->entry); + *entryp = a->entry; + return ret; +} + +static int +_archive_read_next_header2(struct archive *_a, struct archive_entry *entry) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + struct tree *t; + int r; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_read_next_header2"); + + t = a->tree; + if (t->entry_fh != INVALID_HANDLE_VALUE) { + cancel_async(t); + close_and_restore_time(t->entry_fh, t, &t->restore_time); + t->entry_fh = INVALID_HANDLE_VALUE; + } + + archive_entry_clear(entry); + + while ((r = next_entry(a, t, entry)) == ARCHIVE_RETRY) + archive_entry_clear(entry); + + /* + * EOF and FATAL are persistent at this layer. By + * modifying the state, we guarantee that future calls to + * read a header or read data will fail. + */ + switch (r) { + case ARCHIVE_EOF: + a->archive.state = ARCHIVE_STATE_EOF; + break; + case ARCHIVE_OK: + case ARCHIVE_WARN: + t->entry_total = 0; + if (archive_entry_filetype(entry) == AE_IFREG) { + t->entry_remaining_bytes = archive_entry_size(entry); + t->entry_eof = (t->entry_remaining_bytes == 0)? 1: 0; + if (!t->entry_eof && + setup_sparse(a, entry) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } else { + t->entry_remaining_bytes = 0; + t->entry_eof = 1; + } + t->ol_idx_doing = t->ol_idx_done = 0; + t->ol_num_doing = t->ol_num_done = 0; + t->ol_remaining_bytes = t->entry_remaining_bytes; + t->ol_total = 0; + a->archive.state = ARCHIVE_STATE_DATA; + break; + case ARCHIVE_RETRY: + break; + case ARCHIVE_FATAL: + a->archive.state = ARCHIVE_STATE_FATAL; + break; + } + + __archive_reset_read_data(&a->archive); + return (r); +} + +static int +setup_sparse(struct archive_read_disk *a, struct archive_entry *entry) +{ + struct tree *t = a->tree; + int64_t aligned, length, offset; + int i; + + t->sparse_count = archive_entry_sparse_reset(entry); + if (t->sparse_count+1 > t->sparse_list_size) { + free(t->sparse_list); + t->sparse_list_size = t->sparse_count + 1; + t->sparse_list = malloc(sizeof(t->sparse_list[0]) * + t->sparse_list_size); + if (t->sparse_list == NULL) { + t->sparse_list_size = 0; + archive_set_error(&a->archive, ENOMEM, + "Can't allocate data"); + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + } + /* + * Get sparse list and make sure those offsets and lengths are + * aligned by a sector size. + */ + for (i = 0; i < t->sparse_count; i++) { + archive_entry_sparse_next(entry, &offset, &length); + aligned = align_num_per_sector(t, offset); + if (aligned != offset) { + aligned -= t->current_filesystem->bytesPerSector; + length += offset - aligned; + } + t->sparse_list[i].offset = aligned; + aligned = align_num_per_sector(t, length); + t->sparse_list[i].length = aligned; + } + + aligned = align_num_per_sector(t, archive_entry_size(entry)); + if (i == 0) { + t->sparse_list[i].offset = 0; + t->sparse_list[i].length = aligned; + } else { + int j, last = i; + + t->sparse_list[i].offset = aligned; + t->sparse_list[i].length = 0; + for (i = 0; i < last; i++) { + if ((t->sparse_list[i].offset + + t->sparse_list[i].length) <= + t->sparse_list[i+1].offset) + continue; + /* + * Now sparse_list[i+1] is overlapped by sparse_list[i]. + * Merge those two. + */ + length = t->sparse_list[i+1].offset - + t->sparse_list[i].offset; + t->sparse_list[i+1].offset = t->sparse_list[i].offset; + t->sparse_list[i+1].length += length; + /* Remove sparse_list[i]. */ + for (j = i; j < last; j++) { + t->sparse_list[j].offset = + t->sparse_list[j+1].offset; + t->sparse_list[j].length = + t->sparse_list[j+1].length; + } + last--; + } + } + t->current_sparse = t->sparse_list; + + return (ARCHIVE_OK); +} + +int +archive_read_disk_set_matching(struct archive *_a, struct archive *_ma, + void (*_excluded_func)(struct archive *, void *, struct archive_entry *), + void *_client_data) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_read_disk_set_matching"); + a->matching = _ma; + a->excluded_cb_func = _excluded_func; + a->excluded_cb_data = _client_data; + return (ARCHIVE_OK); +} + +int +archive_read_disk_set_metadata_filter_callback(struct archive *_a, + int (*_metadata_filter_func)(struct archive *, void *, + struct archive_entry *), void *_client_data) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_ANY, + "archive_read_disk_set_metadata_filter_callback"); + + a->metadata_filter_func = _metadata_filter_func; + a->metadata_filter_data = _client_data; + return (ARCHIVE_OK); +} + +int +archive_read_disk_can_descend(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + struct tree *t = a->tree; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_read_disk_can_descend"); + + return (t->visit_type == TREE_REGULAR && t->descend); +} + +/* + * Called by the client to mark the directory just returned from + * tree_next() as needing to be visited. + */ +int +archive_read_disk_descend(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + struct tree *t = a->tree; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_read_disk_descend"); + + if (t->visit_type != TREE_REGULAR || !t->descend) + return (ARCHIVE_OK); + + if (tree_current_is_physical_dir(t)) { + tree_push(t, t->basename, t->full_path.s, + t->current_filesystem_id, + bhfi_dev(&(t->lst)), bhfi_ino(&(t->lst)), + &t->restore_time); + t->stack->flags |= isDir; + } else if (tree_current_is_dir(t)) { + tree_push(t, t->basename, t->full_path.s, + t->current_filesystem_id, + bhfi_dev(&(t->st)), bhfi_ino(&(t->st)), + &t->restore_time); + t->stack->flags |= isDirLink; + } + t->descend = 0; + return (ARCHIVE_OK); +} + +int +archive_read_disk_open(struct archive *_a, const char *pathname) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + struct archive_wstring wpath; + int ret; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_NEW | ARCHIVE_STATE_CLOSED, + "archive_read_disk_open"); + archive_clear_error(&a->archive); + + /* Make a wchar_t string from a char string. */ + archive_string_init(&wpath); + if (archive_wstring_append_from_mbs(&wpath, pathname, + strlen(pathname)) != 0) { + if (errno == ENOMEM) + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + else + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can't convert a path to a wchar_t string"); + a->archive.state = ARCHIVE_STATE_FATAL; + ret = ARCHIVE_FATAL; + } else + ret = _archive_read_disk_open_w(_a, wpath.s); + + archive_wstring_free(&wpath); + return (ret); +} + +int +archive_read_disk_open_w(struct archive *_a, const wchar_t *pathname) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, + ARCHIVE_STATE_NEW | ARCHIVE_STATE_CLOSED, + "archive_read_disk_open_w"); + archive_clear_error(&a->archive); + + return (_archive_read_disk_open_w(_a, pathname)); +} + +static int +_archive_read_disk_open_w(struct archive *_a, const wchar_t *pathname) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + + if (a->tree != NULL) + a->tree = tree_reopen(a->tree, pathname, + a->flags & ARCHIVE_READDISK_RESTORE_ATIME); + else + a->tree = tree_open(pathname, a->symlink_mode, + a->flags & ARCHIVE_READDISK_RESTORE_ATIME); + if (a->tree == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate directory traversal data"); + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + a->archive.state = ARCHIVE_STATE_HEADER; + + return (ARCHIVE_OK); +} + +/* + * Return a current filesystem ID which is index of the filesystem entry + * you've visited through archive_read_disk. + */ +int +archive_read_disk_current_filesystem(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_DATA, + "archive_read_disk_current_filesystem"); + + return (a->tree->current_filesystem_id); +} + +static int +update_current_filesystem(struct archive_read_disk *a, int64_t dev) +{ + struct tree *t = a->tree; + int i, fid; + + if (t->current_filesystem != NULL && + t->current_filesystem->dev == dev) + return (ARCHIVE_OK); + + for (i = 0; i < t->max_filesystem_id; i++) { + if (t->filesystem_table[i].dev == dev) { + /* There is the filesystem ID we've already generated. */ + t->current_filesystem_id = i; + t->current_filesystem = &(t->filesystem_table[i]); + return (ARCHIVE_OK); + } + } + + /* + * There is a new filesystem, we generate a new ID for. + */ + fid = t->max_filesystem_id++; + if (t->max_filesystem_id > t->allocated_filesystem) { + size_t s; + void *p; + + s = t->max_filesystem_id * 2; + p = realloc(t->filesystem_table, + s * sizeof(*t->filesystem_table)); + if (p == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate tar data"); + return (ARCHIVE_FATAL); + } + t->filesystem_table = (struct filesystem *)p; + t->allocated_filesystem = (int)s; + } + t->current_filesystem_id = fid; + t->current_filesystem = &(t->filesystem_table[fid]); + t->current_filesystem->dev = dev; + + return (setup_current_filesystem(a)); +} + +/* + * Returns 1 if current filesystem is generated filesystem, 0 if it is not + * or -1 if it is unknown. + */ +int +archive_read_disk_current_filesystem_is_synthetic(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_DATA, + "archive_read_disk_current_filesystem"); + + return (a->tree->current_filesystem->synthetic); +} + +/* + * Returns 1 if current filesystem is remote filesystem, 0 if it is not + * or -1 if it is unknown. + */ +int +archive_read_disk_current_filesystem_is_remote(struct archive *_a) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + + archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_DATA, + "archive_read_disk_current_filesystem"); + + return (a->tree->current_filesystem->remote); +} + +/* + * If symlink is broken, statfs or statvfs will fail. + * Use its directory path instead. + */ +static wchar_t * +safe_path_for_statfs(struct tree *t) +{ + const wchar_t *path; + wchar_t *cp, *p = NULL; + + path = tree_current_access_path(t); + if (tree_current_stat(t) == NULL) { + p = _wcsdup(path); + cp = wcsrchr(p, '/'); + if (cp != NULL && wcslen(cp) >= 2) { + cp[1] = '.'; + cp[2] = '\0'; + path = p; + } + } else + p = _wcsdup(path); + return (p); +} + +/* + * Get conditions of synthetic and remote on Windows + */ +static int +setup_current_filesystem(struct archive_read_disk *a) +{ + struct tree *t = a->tree; + wchar_t vol[256]; + wchar_t *path; + + t->current_filesystem->synthetic = -1;/* Not supported */ + path = safe_path_for_statfs(t); + if (!GetVolumePathNameW(path, vol, sizeof(vol)/sizeof(vol[0]))) { + free(path); + t->current_filesystem->remote = -1; + t->current_filesystem->bytesPerSector = 0; + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "GetVolumePathName failed: %d", (int)GetLastError()); + return (ARCHIVE_FAILED); + } + free(path); + switch (GetDriveTypeW(vol)) { + case DRIVE_UNKNOWN: + case DRIVE_NO_ROOT_DIR: + t->current_filesystem->remote = -1; + break; + case DRIVE_REMOTE: + t->current_filesystem->remote = 1; + break; + default: + t->current_filesystem->remote = 0; + break; + } + + if (!GetDiskFreeSpaceW(vol, NULL, + &(t->current_filesystem->bytesPerSector), NULL, NULL)) { + t->current_filesystem->bytesPerSector = 0; + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "GetDiskFreeSpace failed: %d", (int)GetLastError()); + return (ARCHIVE_FAILED); + } + + return (ARCHIVE_OK); +} + +static int +close_and_restore_time(HANDLE h, struct tree *t, struct restore_time *rt) +{ + HANDLE handle; + int r = 0; + + if (h == INVALID_HANDLE_VALUE && AE_IFLNK == rt->filetype) + return (0); + + /* Close a file descriptor. + * It will not be used for SetFileTime() because it has been opened + * by a read only mode. + */ + if (h != INVALID_HANDLE_VALUE) + CloseHandle(h); + if ((t->flags & needsRestoreTimes) == 0) + return (r); + + handle = CreateFileW(rt->full_path, FILE_WRITE_ATTRIBUTES, + 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); + if (handle == INVALID_HANDLE_VALUE) { + errno = EINVAL; + return (-1); + } + + if (SetFileTime(handle, NULL, &rt->lastAccessTime, + &rt->lastWriteTime) == 0) { + errno = EINVAL; + r = -1; + } else + r = 0; + CloseHandle(handle); + return (r); +} + +/* + * Add a directory path to the current stack. + */ +static void +tree_push(struct tree *t, const wchar_t *path, const wchar_t *full_path, + int filesystem_id, int64_t dev, int64_t ino, struct restore_time *rt) +{ + struct tree_entry *te; + + te = calloc(1, sizeof(*te)); + te->next = t->stack; + te->parent = t->current; + if (te->parent) + te->depth = te->parent->depth + 1; + t->stack = te; + archive_string_init(&te->name); + archive_wstrcpy(&te->name, path); + archive_string_init(&te->full_path); + archive_wstrcpy(&te->full_path, full_path); + te->flags = needsDescent | needsOpen | needsAscent; + te->filesystem_id = filesystem_id; + te->dev = dev; + te->ino = ino; + te->dirname_length = t->dirname_length; + te->full_path_dir_length = t->full_path_dir_length; + te->restore_time.full_path = te->full_path.s; + if (rt != NULL) { + te->restore_time.lastWriteTime = rt->lastWriteTime; + te->restore_time.lastAccessTime = rt->lastAccessTime; + te->restore_time.filetype = rt->filetype; + } +} + +/* + * Append a name to the current dir path. + */ +static void +tree_append(struct tree *t, const wchar_t *name, size_t name_length) +{ + size_t size_needed; + + t->path.s[t->dirname_length] = L'\0'; + t->path.length = t->dirname_length; + /* Strip trailing '/' from name, unless entire name is "/". */ + while (name_length > 1 && name[name_length - 1] == L'/') + name_length--; + + /* Resize pathname buffer as needed. */ + size_needed = name_length + t->dirname_length + 2; + archive_wstring_ensure(&t->path, size_needed); + /* Add a separating '/' if it's needed. */ + if (t->dirname_length > 0 && + t->path.s[archive_strlen(&t->path)-1] != L'/') + archive_wstrappend_wchar(&t->path, L'/'); + t->basename = t->path.s + archive_strlen(&t->path); + archive_wstrncat(&t->path, name, name_length); + t->restore_time.full_path = t->basename; + if (t->full_path_dir_length > 0) { + t->full_path.s[t->full_path_dir_length] = L'\0'; + t->full_path.length = t->full_path_dir_length; + size_needed = name_length + t->full_path_dir_length + 2; + archive_wstring_ensure(&t->full_path, size_needed); + /* Add a separating '\' if it's needed. */ + if (t->full_path.s[archive_strlen(&t->full_path)-1] != L'\\') + archive_wstrappend_wchar(&t->full_path, L'\\'); + archive_wstrncat(&t->full_path, name, name_length); + t->restore_time.full_path = t->full_path.s; + } +} + +/* + * Open a directory tree for traversal. + */ +static struct tree * +tree_open(const wchar_t *path, int symlink_mode, int restore_time) +{ + struct tree *t; + + t = calloc(1, sizeof(*t)); + archive_string_init(&(t->full_path)); + archive_string_init(&t->path); + archive_wstring_ensure(&t->path, 15); + t->initial_symlink_mode = symlink_mode; + return (tree_reopen(t, path, restore_time)); +} + +static struct tree * +tree_reopen(struct tree *t, const wchar_t *path, int restore_time) +{ + struct archive_wstring ws; + wchar_t *pathname, *p, *base; + + t->flags = (restore_time != 0)?needsRestoreTimes:0; + t->visit_type = 0; + t->tree_errno = 0; + t->full_path_dir_length = 0; + t->dirname_length = 0; + t->depth = 0; + t->descend = 0; + t->current = NULL; + t->d = INVALID_HANDLE_VALUE; + t->symlink_mode = t->initial_symlink_mode; + archive_string_empty(&(t->full_path)); + archive_string_empty(&t->path); + t->entry_fh = INVALID_HANDLE_VALUE; + t->entry_eof = 0; + t->entry_remaining_bytes = 0; + t->initial_filesystem_id = -1; + + /* Get wchar_t strings from char strings. */ + archive_string_init(&ws); + archive_wstrcpy(&ws, path); + pathname = ws.s; + /* Get a full-path-name. */ + p = __la_win_permissive_name_w(pathname); + if (p == NULL) + goto failed; + archive_wstrcpy(&(t->full_path), p); + free(p); + + /* Convert path separators from '\' to '/' */ + for (p = pathname; *p != L'\0'; ++p) { + if (*p == L'\\') + *p = L'/'; + } + base = pathname; + + /* First item is set up a lot like a symlink traversal. */ + /* printf("Looking for wildcard in %s\n", path); */ + if ((base[0] == L'/' && base[1] == L'/' && + base[2] == L'?' && base[3] == L'/' && + (wcschr(base+4, L'*') || wcschr(base+4, L'?'))) || + (!(base[0] == L'/' && base[1] == L'/' && + base[2] == L'?' && base[3] == L'/') && + (wcschr(base, L'*') || wcschr(base, L'?')))) { + // It has a wildcard in it... + // Separate the last element. + p = wcsrchr(base, L'/'); + if (p != NULL) { + *p = L'\0'; + tree_append(t, base, p - base); + t->dirname_length = archive_strlen(&t->path); + base = p + 1; + } + p = wcsrchr(t->full_path.s, L'\\'); + if (p != NULL) { + *p = L'\0'; + t->full_path.length = wcslen(t->full_path.s); + t->full_path_dir_length = archive_strlen(&t->full_path); + } + } + tree_push(t, base, t->full_path.s, 0, 0, 0, NULL); + archive_wstring_free(&ws); + t->stack->flags = needsFirstVisit; + /* + * Debug flag for Direct IO(No buffering) or Async IO. + * Those dependent on environment variable switches + * will be removed until next release. + */ + { + const char *e; + if ((e = getenv("LIBARCHIVE_DIRECT_IO")) != NULL) { + if (e[0] == '0') + t->direct_io = 0; + else + t->direct_io = 1; + fprintf(stderr, "LIBARCHIVE_DIRECT_IO=%s\n", + (t->direct_io)?"Enabled":"Disabled"); + } else + t->direct_io = DIRECT_IO; + if ((e = getenv("LIBARCHIVE_ASYNC_IO")) != NULL) { + if (e[0] == '0') + t->async_io = 0; + else + t->async_io = 1; + fprintf(stderr, "LIBARCHIVE_ASYNC_IO=%s\n", + (t->async_io)?"Enabled":"Disabled"); + } else + t->async_io = ASYNC_IO; + } + return (t); +failed: + archive_wstring_free(&ws); + tree_free(t); + return (NULL); +} + +static int +tree_descent(struct tree *t) +{ + t->dirname_length = archive_strlen(&t->path); + t->full_path_dir_length = archive_strlen(&t->full_path); + t->depth++; + return (0); +} + +/* + * We've finished a directory; ascend back to the parent. + */ +static int +tree_ascend(struct tree *t) +{ + struct tree_entry *te; + + te = t->stack; + t->depth--; + close_and_restore_time(INVALID_HANDLE_VALUE, t, &te->restore_time); + return (0); +} + +/* + * Pop the working stack. + */ +static void +tree_pop(struct tree *t) +{ + struct tree_entry *te; + + t->full_path.s[t->full_path_dir_length] = L'\0'; + t->full_path.length = t->full_path_dir_length; + t->path.s[t->dirname_length] = L'\0'; + t->path.length = t->dirname_length; + if (t->stack == t->current && t->current != NULL) + t->current = t->current->parent; + te = t->stack; + t->stack = te->next; + t->dirname_length = te->dirname_length; + t->basename = t->path.s + t->dirname_length; + t->full_path_dir_length = te->full_path_dir_length; + while (t->basename[0] == L'/') + t->basename++; + archive_wstring_free(&te->name); + archive_wstring_free(&te->full_path); + free(te); +} + +/* + * Get the next item in the tree traversal. + */ +static int +tree_next(struct tree *t) +{ + int r; + + while (t->stack != NULL) { + /* If there's an open dir, get the next entry from there. */ + if (t->d != INVALID_HANDLE_VALUE) { + r = tree_dir_next_windows(t, NULL); + if (r == 0) + continue; + return (r); + } + + if (t->stack->flags & needsFirstVisit) { + wchar_t *d = t->stack->name.s; + t->stack->flags &= ~needsFirstVisit; + if (!(d[0] == L'/' && d[1] == L'/' && + d[2] == L'?' && d[3] == L'/') && + (wcschr(d, L'*') || wcschr(d, L'?'))) { + r = tree_dir_next_windows(t, d); + if (r == 0) + continue; + return (r); + } else { + HANDLE h = FindFirstFileW(d, &t->_findData); + if (h == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + t->tree_errno = errno; + t->visit_type = TREE_ERROR_DIR; + return (t->visit_type); + } + t->findData = &t->_findData; + FindClose(h); + } + /* Top stack item needs a regular visit. */ + t->current = t->stack; + tree_append(t, t->stack->name.s, + archive_strlen(&(t->stack->name))); + //t->dirname_length = t->path_length; + //tree_pop(t); + t->stack->flags &= ~needsFirstVisit; + return (t->visit_type = TREE_REGULAR); + } else if (t->stack->flags & needsDescent) { + /* Top stack item is dir to descend into. */ + t->current = t->stack; + tree_append(t, t->stack->name.s, + archive_strlen(&(t->stack->name))); + t->stack->flags &= ~needsDescent; + r = tree_descent(t); + if (r != 0) { + tree_pop(t); + t->visit_type = r; + } else + t->visit_type = TREE_POSTDESCENT; + return (t->visit_type); + } else if (t->stack->flags & needsOpen) { + t->stack->flags &= ~needsOpen; + r = tree_dir_next_windows(t, L"*"); + if (r == 0) + continue; + return (r); + } else if (t->stack->flags & needsAscent) { + /* Top stack item is dir and we're done with it. */ + r = tree_ascend(t); + tree_pop(t); + t->visit_type = r != 0 ? r : TREE_POSTASCENT; + return (t->visit_type); + } else { + /* Top item on stack is dead. */ + tree_pop(t); + t->flags &= ~hasLstat; + t->flags &= ~hasStat; + } + } + return (t->visit_type = 0); +} + +static int +tree_dir_next_windows(struct tree *t, const wchar_t *pattern) +{ + const wchar_t *name; + size_t namelen; + int r; + + for (;;) { + if (pattern != NULL) { + struct archive_wstring pt; + + archive_string_init(&pt); + archive_wstring_ensure(&pt, + archive_strlen(&(t->full_path)) + + 2 + wcslen(pattern)); + archive_wstring_copy(&pt, &(t->full_path)); + archive_wstrappend_wchar(&pt, L'\\'); + archive_wstrcat(&pt, pattern); + t->d = FindFirstFileW(pt.s, &t->_findData); + archive_wstring_free(&pt); + if (t->d == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + t->tree_errno = errno; + r = tree_ascend(t); /* Undo "chdir" */ + tree_pop(t); + t->visit_type = r != 0 ? r : TREE_ERROR_DIR; + return (t->visit_type); + } + t->findData = &t->_findData; + pattern = NULL; + } else if (!FindNextFileW(t->d, &t->_findData)) { + FindClose(t->d); + t->d = INVALID_HANDLE_VALUE; + t->findData = NULL; + return (0); + } + name = t->findData->cFileName; + namelen = wcslen(name); + t->flags &= ~hasLstat; + t->flags &= ~hasStat; + if (name[0] == L'.' && name[1] == L'\0') + continue; + if (name[0] == L'.' && name[1] == L'.' && name[2] == L'\0') + continue; + tree_append(t, name, namelen); + return (t->visit_type = TREE_REGULAR); + } +} + +#define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000) +static void +fileTimeToUtc(const FILETIME *filetime, time_t *t, long *ns) +{ + ULARGE_INTEGER utc; + + utc.HighPart = filetime->dwHighDateTime; + utc.LowPart = filetime->dwLowDateTime; + if (utc.QuadPart >= EPOC_TIME) { + utc.QuadPart -= EPOC_TIME; + /* milli seconds base */ + *t = (time_t)(utc.QuadPart / 10000000); + /* nano seconds base */ + *ns = (long)(utc.QuadPart % 10000000) * 100; + } else { + *t = 0; + *ns = 0; + } +} + +static void +entry_copy_bhfi(struct archive_entry *entry, const wchar_t *path, + const WIN32_FIND_DATAW *findData, + const BY_HANDLE_FILE_INFORMATION *bhfi) +{ + time_t secs; + long nsecs; + mode_t mode; + + fileTimeToUtc(&bhfi->ftLastAccessTime, &secs, &nsecs); + archive_entry_set_atime(entry, secs, nsecs); + fileTimeToUtc(&bhfi->ftLastWriteTime, &secs, &nsecs); + archive_entry_set_mtime(entry, secs, nsecs); + fileTimeToUtc(&bhfi->ftCreationTime, &secs, &nsecs); + archive_entry_set_birthtime(entry, secs, nsecs); + archive_entry_set_ctime(entry, secs, nsecs); + archive_entry_set_dev(entry, bhfi_dev(bhfi)); + archive_entry_set_ino64(entry, bhfi_ino(bhfi)); + if (bhfi->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + archive_entry_set_nlink(entry, bhfi->nNumberOfLinks + 1); + else + archive_entry_set_nlink(entry, bhfi->nNumberOfLinks); + archive_entry_set_size(entry, + (((int64_t)bhfi->nFileSizeHigh) << 32) + + bhfi->nFileSizeLow); + archive_entry_set_uid(entry, 0); + archive_entry_set_gid(entry, 0); + archive_entry_set_rdev(entry, 0); + + mode = S_IRUSR | S_IRGRP | S_IROTH; + if ((bhfi->dwFileAttributes & FILE_ATTRIBUTE_READONLY) == 0) + mode |= S_IWUSR | S_IWGRP | S_IWOTH; + if ((bhfi->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) && + findData != NULL && + findData->dwReserved0 == IO_REPARSE_TAG_SYMLINK) { + mode |= S_IFLNK; + entry_symlink_from_pathw(entry, path); + } else if (bhfi->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + mode |= S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH; + else { + const wchar_t *p; + + mode |= S_IFREG; + p = wcsrchr(path, L'.'); + if (p != NULL && wcslen(p) == 4) { + switch (p[1]) { + case L'B': case L'b': + if ((p[2] == L'A' || p[2] == L'a' ) && + (p[3] == L'T' || p[3] == L't' )) + mode |= S_IXUSR | S_IXGRP | S_IXOTH; + break; + case L'C': case L'c': + if (((p[2] == L'M' || p[2] == L'm' ) && + (p[3] == L'D' || p[3] == L'd' ))) + mode |= S_IXUSR | S_IXGRP | S_IXOTH; + break; + case L'E': case L'e': + if ((p[2] == L'X' || p[2] == L'x' ) && + (p[3] == L'E' || p[3] == L'e' )) + mode |= S_IXUSR | S_IXGRP | S_IXOTH; + break; + default: + break; + } + } + } + archive_entry_set_mode(entry, mode); +} + +static void +tree_archive_entry_copy_bhfi(struct archive_entry *entry, struct tree *t, + const BY_HANDLE_FILE_INFORMATION *bhfi) +{ + entry_copy_bhfi(entry, tree_current_path(t), t->findData, bhfi); +} + +static int +tree_current_file_information(struct tree *t, BY_HANDLE_FILE_INFORMATION *st, + int sim_lstat) +{ + HANDLE h; + int r; + DWORD flag = FILE_FLAG_BACKUP_SEMANTICS; + + if (sim_lstat && tree_current_is_physical_link(t)) + flag |= FILE_FLAG_OPEN_REPARSE_POINT; + h = CreateFileW(tree_current_access_path(t), 0, FILE_SHARE_READ, NULL, + OPEN_EXISTING, flag, NULL); + if (h == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + t->tree_errno = errno; + return (0); + } + r = GetFileInformationByHandle(h, st); + CloseHandle(h); + return (r); +} + +/* + * Get the stat() data for the entry just returned from tree_next(). + */ +static const BY_HANDLE_FILE_INFORMATION * +tree_current_stat(struct tree *t) +{ + if (!(t->flags & hasStat)) { + if (!tree_current_file_information(t, &t->st, 0)) + return NULL; + t->flags |= hasStat; + } + return (&t->st); +} + +/* + * Get the lstat() data for the entry just returned from tree_next(). + */ +static const BY_HANDLE_FILE_INFORMATION * +tree_current_lstat(struct tree *t) +{ + if (!(t->flags & hasLstat)) { + if (!tree_current_file_information(t, &t->lst, 1)) + return NULL; + t->flags |= hasLstat; + } + return (&t->lst); +} + +/* + * Test whether current entry is a dir or link to a dir. + */ +static int +tree_current_is_dir(struct tree *t) +{ + if (t->findData) + return (t->findData->dwFileAttributes + & FILE_ATTRIBUTE_DIRECTORY); + return (0); +} + +/* + * Test whether current entry is a physical directory. Usually, we + * already have at least one of stat() or lstat() in memory, so we + * use tricks to try to avoid an extra trip to the disk. + */ +static int +tree_current_is_physical_dir(struct tree *t) +{ + if (tree_current_is_physical_link(t)) + return (0); + return (tree_current_is_dir(t)); +} + +/* + * Test whether current entry is a symbolic link. + */ +static int +tree_current_is_physical_link(struct tree *t) +{ + if (t->findData) + return ((t->findData->dwFileAttributes + & FILE_ATTRIBUTE_REPARSE_POINT) && + (t->findData->dwReserved0 + == IO_REPARSE_TAG_SYMLINK)); + return (0); +} + +/* + * Test whether the same file has been in the tree as its parent. + */ +static int +tree_target_is_same_as_parent(struct tree *t, + const BY_HANDLE_FILE_INFORMATION *st) +{ + struct tree_entry *te; + int64_t dev = bhfi_dev(st); + int64_t ino = bhfi_ino(st); + + for (te = t->current->parent; te != NULL; te = te->parent) { + if (te->dev == dev && te->ino == ino) + return (1); + } + return (0); +} + +/* + * Return the access path for the entry just returned from tree_next(). + */ +static const wchar_t * +tree_current_access_path(struct tree *t) +{ + return (t->full_path.s); +} + +/* + * Return the full path for the entry just returned from tree_next(). + */ +static const wchar_t * +tree_current_path(struct tree *t) +{ + return (t->path.s); +} + +/* + * Terminate the traversal. + */ +static void +tree_close(struct tree *t) +{ + + if (t == NULL) + return; + if (t->entry_fh != INVALID_HANDLE_VALUE) { + cancel_async(t); + close_and_restore_time(t->entry_fh, t, &t->restore_time); + t->entry_fh = INVALID_HANDLE_VALUE; + } + /* Close the handle of FindFirstFileW */ + if (t->d != INVALID_HANDLE_VALUE) { + FindClose(t->d); + t->d = INVALID_HANDLE_VALUE; + t->findData = NULL; + } + /* Release anything remaining in the stack. */ + while (t->stack != NULL) + tree_pop(t); +} + +/* + * Release any resources. + */ +static void +tree_free(struct tree *t) +{ + int i; + + if (t == NULL) + return; + archive_wstring_free(&t->path); + archive_wstring_free(&t->full_path); + free(t->sparse_list); + free(t->filesystem_table); + for (i = 0; i < MAX_OVERLAPPED; i++) { + if (t->ol[i].buff) + VirtualFree(t->ol[i].buff, 0, MEM_RELEASE); + CloseHandle(t->ol[i].ol.hEvent); + } + free(t); +} + + +/* + * Populate the archive_entry with metadata from the disk. + */ +int +archive_read_disk_entry_from_file(struct archive *_a, + struct archive_entry *entry, int fd, const struct stat *st) +{ + struct archive_read_disk *a = (struct archive_read_disk *)_a; + const wchar_t *path; + const wchar_t *wname; + const char *name; + HANDLE h; + BY_HANDLE_FILE_INFORMATION bhfi; + DWORD fileAttributes = 0; + int r; + + archive_clear_error(_a); + wname = archive_entry_sourcepath_w(entry); + if (wname == NULL) + wname = archive_entry_pathname_w(entry); + if (wname == NULL) { + archive_set_error(&a->archive, EINVAL, + "Can't get a wide character version of the path"); + return (ARCHIVE_FAILED); + } + path = __la_win_permissive_name_w(wname); + + if (st == NULL) { + /* + * Get metadata through GetFileInformationByHandle(). + */ + if (fd >= 0) { + h = (HANDLE)_get_osfhandle(fd); + r = GetFileInformationByHandle(h, &bhfi); + if (r == 0) { + la_dosmaperr(GetLastError()); + archive_set_error(&a->archive, errno, + "Can't GetFileInformationByHandle"); + return (ARCHIVE_FAILED); + } + entry_copy_bhfi(entry, path, NULL, &bhfi); + } else { + WIN32_FIND_DATAW findData; + DWORD flag, desiredAccess; + + h = FindFirstFileW(path, &findData); + if (h == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + archive_set_error(&a->archive, errno, + "Can't FindFirstFileW"); + return (ARCHIVE_FAILED); + } + FindClose(h); + + flag = FILE_FLAG_BACKUP_SEMANTICS; + if (!a->follow_symlinks && + (findData.dwFileAttributes + & FILE_ATTRIBUTE_REPARSE_POINT) && + (findData.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) { + flag |= FILE_FLAG_OPEN_REPARSE_POINT; + desiredAccess = 0; + } else if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { + desiredAccess = 0; + } else + desiredAccess = GENERIC_READ; + + h = CreateFileW(path, desiredAccess, FILE_SHARE_READ, NULL, + OPEN_EXISTING, flag, NULL); + if (h == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + archive_set_error(&a->archive, errno, + "Can't CreateFileW"); + return (ARCHIVE_FAILED); + } + r = GetFileInformationByHandle(h, &bhfi); + if (r == 0) { + la_dosmaperr(GetLastError()); + archive_set_error(&a->archive, errno, + "Can't GetFileInformationByHandle"); + CloseHandle(h); + return (ARCHIVE_FAILED); + } + entry_copy_bhfi(entry, path, &findData, &bhfi); + } + fileAttributes = bhfi.dwFileAttributes; + } else { + archive_entry_copy_stat(entry, st); + if (st->st_mode & S_IFLNK) + entry_symlink_from_pathw(entry, path); + h = INVALID_HANDLE_VALUE; + } + + /* Lookup uname/gname */ + name = archive_read_disk_uname(_a, archive_entry_uid(entry)); + if (name != NULL) + archive_entry_copy_uname(entry, name); + name = archive_read_disk_gname(_a, archive_entry_gid(entry)); + if (name != NULL) + archive_entry_copy_gname(entry, name); + + /* + * File attributes + */ + if ((a->flags & ARCHIVE_READDISK_NO_FFLAGS) == 0) { + const int supported_attrs = + FILE_ATTRIBUTE_READONLY | + FILE_ATTRIBUTE_HIDDEN | + FILE_ATTRIBUTE_SYSTEM; + DWORD file_attrs = fileAttributes & supported_attrs; + if (file_attrs != 0) + archive_entry_set_fflags(entry, file_attrs, 0); + } + + /* + * Can this file be sparse file ? + */ + if (archive_entry_filetype(entry) != AE_IFREG + || archive_entry_size(entry) <= 0 + || archive_entry_hardlink(entry) != NULL) { + if (h != INVALID_HANDLE_VALUE && fd < 0) + CloseHandle(h); + return (ARCHIVE_OK); + } + + if (h == INVALID_HANDLE_VALUE) { + if (fd >= 0) { + h = (HANDLE)_get_osfhandle(fd); + } else { + h = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL, + OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); + if (h == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + archive_set_error(&a->archive, errno, + "Can't CreateFileW"); + return (ARCHIVE_FAILED); + } + } + r = GetFileInformationByHandle(h, &bhfi); + if (r == 0) { + la_dosmaperr(GetLastError()); + archive_set_error(&a->archive, errno, + "Can't GetFileInformationByHandle"); + if (h != INVALID_HANDLE_VALUE && fd < 0) + CloseHandle(h); + return (ARCHIVE_FAILED); + } + fileAttributes = bhfi.dwFileAttributes; + } + + /* Sparse file must be set a mark, FILE_ATTRIBUTE_SPARSE_FILE */ + if ((fileAttributes & FILE_ATTRIBUTE_SPARSE_FILE) == 0) { + if (fd < 0) + CloseHandle(h); + return (ARCHIVE_OK); + } + + r = setup_sparse_from_disk(a, entry, h); + if (fd < 0) + CloseHandle(h); + + return (r); +} + +/* + * Windows sparse interface. + */ +#if defined(__MINGW32__) && !defined(FSCTL_QUERY_ALLOCATED_RANGES) +#define FSCTL_QUERY_ALLOCATED_RANGES 0x940CF +typedef struct { + LARGE_INTEGER FileOffset; + LARGE_INTEGER Length; +} FILE_ALLOCATED_RANGE_BUFFER; +#endif + +static int +setup_sparse_from_disk(struct archive_read_disk *a, + struct archive_entry *entry, HANDLE handle) +{ + FILE_ALLOCATED_RANGE_BUFFER range, *outranges = NULL; + size_t outranges_size; + int64_t entry_size = archive_entry_size(entry); + int exit_sts = ARCHIVE_OK; + + range.FileOffset.QuadPart = 0; + range.Length.QuadPart = entry_size; + outranges_size = 2048; + outranges = (FILE_ALLOCATED_RANGE_BUFFER *)malloc(outranges_size); + if (outranges == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Couldn't allocate memory"); + exit_sts = ARCHIVE_FATAL; + goto exit_setup_sparse; + } + + for (;;) { + DWORD retbytes; + BOOL ret; + + for (;;) { + ret = DeviceIoControl(handle, + FSCTL_QUERY_ALLOCATED_RANGES, + &range, sizeof(range), outranges, + (DWORD)outranges_size, &retbytes, NULL); + if (ret == 0 && GetLastError() == ERROR_MORE_DATA) { + free(outranges); + outranges_size *= 2; + outranges = (FILE_ALLOCATED_RANGE_BUFFER *) + malloc(outranges_size); + if (outranges == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Couldn't allocate memory"); + exit_sts = ARCHIVE_FATAL; + goto exit_setup_sparse; + } + continue; + } else + break; + } + if (ret != 0) { + if (retbytes > 0) { + DWORD i, n; + + n = retbytes / sizeof(outranges[0]); + if (n == 1 && + outranges[0].FileOffset.QuadPart == 0 && + outranges[0].Length.QuadPart == entry_size) + break;/* This is not sparse. */ + for (i = 0; i < n; i++) + archive_entry_sparse_add_entry(entry, + outranges[i].FileOffset.QuadPart, + outranges[i].Length.QuadPart); + range.FileOffset.QuadPart = + outranges[n-1].FileOffset.QuadPart + + outranges[n-1].Length.QuadPart; + range.Length.QuadPart = + entry_size - range.FileOffset.QuadPart; + if (range.Length.QuadPart > 0) + continue; + } else { + /* The entire file is a hole. Add one data block of size 0 at the end. */ + archive_entry_sparse_add_entry(entry, + entry_size, + 0); + } + break; + } else { + la_dosmaperr(GetLastError()); + archive_set_error(&a->archive, errno, + "DeviceIoControl Failed: %lu", GetLastError()); + exit_sts = ARCHIVE_FAILED; + goto exit_setup_sparse; + } + } +exit_setup_sparse: + free(outranges); + + return (exit_sts); +} + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_extract.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_extract.3 new file mode 100644 index 0000000000..858f397425 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_extract.3 @@ -0,0 +1,137 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_READ_EXTRACT 3 +.Os +.Sh NAME +.Nm archive_read_extract , +.Nm archive_read_extract2 , +.Nm archive_read_extract_set_progress_callback +.Nd functions for reading streaming archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fo archive_read_extract +.Fa "struct archive *" +.Fa "struct archive_entry *" +.Fa "int flags" +.Fc +.Ft int +.Fo archive_read_extract2 +.Fa "struct archive *src" +.Fa "struct archive_entry *" +.Fa "struct archive *dest" +.Fc +.Ft void +.Fo archive_read_extract_set_progress_callback +.Fa "struct archive *" +.Fa "void (*func)(void *)" +.Fa "void *user_data" +.Fc +.Sh DESCRIPTION +.Bl -tag -compact -width indent +.It Fn archive_read_extract , Fn archive_read_extract_set_skip_file +A convenience function that wraps the corresponding +.Xr archive_write_disk 3 +interfaces. +The first call to +.Fn archive_read_extract +creates a restore object using +.Xr archive_write_disk_new 3 +and +.Xr archive_write_disk_set_standard_lookup 3 , +then transparently invokes +.Xr archive_write_disk_set_options 3 , +.Xr archive_write_header 3 , +.Xr archive_write_data 3 , +and +.Xr archive_write_finish_entry 3 +to create the entry on disk and copy data into it. +The +.Va flags +argument is passed unmodified to +.Xr archive_write_disk_set_options 3 . +.It Fn archive_read_extract2 +This is another version of +.Fn archive_read_extract +that allows you to provide your own restore object. +In particular, this allows you to override the standard lookup functions +using +.Xr archive_write_disk_set_group_lookup 3 , +and +.Xr archive_write_disk_set_user_lookup 3 . +Note that +.Fn archive_read_extract2 +does not accept a +.Va flags +argument; you should use +.Fn archive_write_disk_set_options +to set the restore options yourself. +.It Fn archive_read_extract_set_progress_callback +Sets a pointer to a user-defined callback that can be used +for updating progress displays during extraction. +The progress function will be invoked during the extraction of large +regular files. +The progress function will be invoked with the pointer provided to this call. +Generally, the data pointed to should include a reference to the archive +object and the archive_entry object so that various statistics +can be retrieved for the progress display. +.El +.\" +.Sh RETURN VALUES +Most functions return zero on success, non-zero on error. +The possible return codes include: +.Cm ARCHIVE_OK +(the operation succeeded), +.Cm ARCHIVE_WARN +(the operation succeeded but a non-critical error was encountered), +.Cm ARCHIVE_EOF +(end-of-archive was encountered), +.Cm ARCHIVE_RETRY +(the operation failed but can be retried), +and +.Cm ARCHIVE_FATAL +(there was a fatal error; the archive should be closed immediately). +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_read 3 , +.Xr archive_read_data 3 , +.Xr archive_read_filter 3 , +.Xr archive_read_format 3 , +.Xr archive_read_open 3 , +.Xr archive_read_set_options 3 , +.Xr archive_util 3 , +.Xr libarchive 3 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_extract.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_extract.c new file mode 100644 index 0000000000..b7973fa8e0 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_extract.c @@ -0,0 +1,60 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: src/lib/libarchive/archive_read_extract.c,v 1.61 2008/05/26 17:00:22 kientzle Exp $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_read_private.h" + +int +archive_read_extract(struct archive *_a, struct archive_entry *entry, int flags) +{ + struct archive_read_extract *extract; + struct archive_read * a = (struct archive_read *)_a; + + extract = __archive_read_get_extract(a); + if (extract == NULL) + return (ARCHIVE_FATAL); + + /* If we haven't initialized the archive_write_disk object, do it now. */ + if (extract->ad == NULL) { + extract->ad = archive_write_disk_new(); + if (extract->ad == NULL) { + archive_set_error(&a->archive, ENOMEM, "Can't extract"); + return (ARCHIVE_FATAL); + } + archive_write_disk_set_standard_lookup(extract->ad); + } + + archive_write_disk_set_options(extract->ad, flags); + return (archive_read_extract2(&a->archive, entry, extract->ad)); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_extract2.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_extract2.c new file mode 100644 index 0000000000..4febd8ce05 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_extract2.c @@ -0,0 +1,155 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: src/lib/libarchive/archive_read_extract.c,v 1.61 2008/05/26 17:00:22 kientzle Exp $"); + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_read_private.h" + +static int copy_data(struct archive *ar, struct archive *aw); +static int archive_read_extract_cleanup(struct archive_read *); + + +/* Retrieve an extract object without initialising the associated + * archive_write_disk object. + */ +struct archive_read_extract * +__archive_read_get_extract(struct archive_read *a) +{ + if (a->extract == NULL) { + a->extract = (struct archive_read_extract *)calloc(1, sizeof(*a->extract)); + if (a->extract == NULL) { + archive_set_error(&a->archive, ENOMEM, "Can't extract"); + return (NULL); + } + a->cleanup_archive_extract = archive_read_extract_cleanup; + } + return (a->extract); +} + +/* + * Cleanup function for archive_extract. + */ +static int +archive_read_extract_cleanup(struct archive_read *a) +{ + int ret = ARCHIVE_OK; + + if (a->extract->ad != NULL) { + ret = archive_write_free(a->extract->ad); + } + free(a->extract); + a->extract = NULL; + return (ret); +} + +int +archive_read_extract2(struct archive *_a, struct archive_entry *entry, + struct archive *ad) +{ + struct archive_read *a = (struct archive_read *)_a; + int r, r2; + + /* Set up for this particular entry. */ + if (a->skip_file_set) + archive_write_disk_set_skip_file(ad, + a->skip_file_dev, a->skip_file_ino); + r = archive_write_header(ad, entry); + if (r < ARCHIVE_WARN) + r = ARCHIVE_WARN; + if (r != ARCHIVE_OK) + /* If _write_header failed, copy the error. */ + archive_copy_error(&a->archive, ad); + else if (!archive_entry_size_is_set(entry) || archive_entry_size(entry) > 0) + /* Otherwise, pour data into the entry. */ + r = copy_data(_a, ad); + r2 = archive_write_finish_entry(ad); + if (r2 < ARCHIVE_WARN) + r2 = ARCHIVE_WARN; + /* Use the first message. */ + if (r2 != ARCHIVE_OK && r == ARCHIVE_OK) + archive_copy_error(&a->archive, ad); + /* Use the worst error return. */ + if (r2 < r) + r = r2; + return (r); +} + +void +archive_read_extract_set_progress_callback(struct archive *_a, + void (*progress_func)(void *), void *user_data) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_extract *extract = __archive_read_get_extract(a); + if (extract != NULL) { + extract->extract_progress = progress_func; + extract->extract_progress_user_data = user_data; + } +} + +static int +copy_data(struct archive *ar, struct archive *aw) +{ + int64_t offset; + const void *buff; + struct archive_read_extract *extract; + size_t size; + int r; + + extract = __archive_read_get_extract((struct archive_read *)ar); + if (extract == NULL) + return (ARCHIVE_FATAL); + for (;;) { + r = archive_read_data_block(ar, &buff, &size, &offset); + if (r == ARCHIVE_EOF) + return (ARCHIVE_OK); + if (r != ARCHIVE_OK) + return (r); + r = (int)archive_write_data_block(aw, buff, size, offset); + if (r < ARCHIVE_WARN) + r = ARCHIVE_WARN; + if (r < ARCHIVE_OK) { + archive_set_error(ar, archive_errno(aw), + "%s", archive_error_string(aw)); + return (r); + } + if (extract->extract_progress) + (extract->extract_progress) + (extract->extract_progress_user_data); + } +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_filter.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_filter.3 new file mode 100644 index 0000000000..1ba5fcbd6e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_filter.3 @@ -0,0 +1,154 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd August 14, 2014 +.Dt ARCHIVE_READ_FILTER 3 +.Os +.Sh NAME +.Nm archive_read_support_filter_all , +.Nm archive_read_support_filter_bzip2 , +.Nm archive_read_support_filter_compress , +.Nm archive_read_support_filter_gzip , +.Nm archive_read_support_filter_lz4 , +.Nm archive_read_support_filter_lzma , +.Nm archive_read_support_filter_none , +.Nm archive_read_support_filter_rpm , +.Nm archive_read_support_filter_uu , +.Nm archive_read_support_filter_xz , +.Nm archive_read_support_filter_zstd , +.Nm archive_read_support_filter_program , +.Nm archive_read_support_filter_program_signature +.Nd functions for reading streaming archives +.\" +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fn archive_read_support_filter_all "struct archive *" +.Ft int +.Fn archive_read_support_filter_bzip2 "struct archive *" +.Ft int +.Fn archive_read_support_filter_compress "struct archive *" +.Ft int +.Fn archive_read_support_filter_grzip "struct archive *" +.Ft int +.Fn archive_read_support_filter_gzip "struct archive *" +.Ft int +.Fn archive_read_support_filter_lrzip "struct archive *" +.Ft int +.Fn archive_read_support_filter_lz4 "struct archive *" +.Ft int +.Fn archive_read_support_filter_lzma "struct archive *" +.Ft int +.Fn archive_read_support_filter_lzop "struct archive *" +.Ft int +.Fn archive_read_support_filter_none "struct archive *" +.Ft int +.Fn archive_read_support_filter_rpm "struct archive *" +.Ft int +.Fn archive_read_support_filter_uu "struct archive *" +.Ft int +.Fn archive_read_support_filter_xz "struct archive *" +.Ft int +.Fn archive_read_support_filter_zstd "struct archive *" +.Ft int +.Fo archive_read_support_filter_program +.Fa "struct archive *" +.Fa "const char *cmd" +.Fc +.Ft int +.Fo archive_read_support_filter_program_signature +.Fa "struct archive *" +.Fa "const char *cmd" +.Fa "const void *signature" +.Fa "size_t signature_length" +.Fc +.\" +.Sh DESCRIPTION +.Bl -tag -compact -width indent +.It Xo +.Fn archive_read_support_filter_bzip2 , +.Fn archive_read_support_filter_compress , +.Fn archive_read_support_filter_grzip , +.Fn archive_read_support_filter_gzip , +.Fn archive_read_support_filter_lrzip , +.Fn archive_read_support_filter_lz4 , +.Fn archive_read_support_filter_lzma , +.Fn archive_read_support_filter_lzop , +.Fn archive_read_support_filter_none , +.Fn archive_read_support_filter_rpm , +.Fn archive_read_support_filter_uu , +.Fn archive_read_support_filter_xz , +.Fn archive_read_support_filter_zstd , +.Xc +Enables auto-detection code and decompression support for the +specified compression. +These functions may fall back on external programs if an appropriate +library was not available at build time. +Decompression using an external program is usually slower than +decompression through built-in libraries. +Note that +.Dq none +is always enabled by default. +.It Fn archive_read_support_filter_all +Enables all available decompression filters. +.It Fn archive_read_support_filter_program +Data is fed through the specified external program before being dearchived. +Note that this disables automatic detection of the compression format, +so it makes no sense to specify this in conjunction with any other +decompression option. +.It Fn archive_read_support_filter_program_signature +This feeds data through the specified external program +but only if the initial bytes of the data match the specified +signature value. +.El +.\" +.\". Sh EXAMPLE +.\" +.Sh RETURN VALUES +These functions return +.Cm ARCHIVE_OK +if the compression is fully supported, +.Cm ARCHIVE_WARN +if the compression is supported only through an external program. +.Pp +.Fn archive_read_support_filter_none +always succeeds. +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr archive_read 3 , +.Xr archive_read_data 3 , +.Xr archive_read_format 3 , +.Xr archive_read_format 3 , +.Xr libarchive 3 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_format.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_format.3 new file mode 100644 index 0000000000..f3804ce379 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_format.3 @@ -0,0 +1,177 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_READ_FORMAT 3 +.Os +.Sh NAME +.Nm archive_read_support_format_7zip , +.Nm archive_read_support_format_all , +.Nm archive_read_support_format_ar , +.Nm archive_read_support_format_by_code , +.Nm archive_read_support_format_cab , +.Nm archive_read_support_format_cpio , +.Nm archive_read_support_format_empty , +.Nm archive_read_support_format_iso9660 , +.Nm archive_read_support_format_lha , +.Nm archive_read_support_format_mtree , +.Nm archive_read_support_format_rar , +.Nm archive_read_support_format_raw , +.Nm archive_read_support_format_tar , +.Nm archive_read_support_format_xar , +.Nm archive_read_support_format_zip +.Nd functions for reading streaming archives +.\" +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fn archive_read_support_format_7zip "struct archive *" +.Ft int +.Fn archive_read_support_format_all "struct archive *" +.Ft int +.Fn archive_read_support_format_ar "struct archive *" +.Ft int +.Fn archive_read_support_format_by_code "struct archive *" "int" +.Ft int +.Fn archive_read_support_format_cab "struct archive *" +.Ft int +.Fn archive_read_support_format_cpio "struct archive *" +.Ft int +.Fn archive_read_support_format_empty "struct archive *" +.Ft int +.Fn archive_read_support_format_iso9660 "struct archive *" +.Ft int +.Fn archive_read_support_format_lha "struct archive *" +.Ft int +.Fn archive_read_support_format_mtree "struct archive *" +.Ft int +.Fn archive_read_support_format_rar "struct archive *" +.Ft int +.Fn archive_read_support_format_raw "struct archive *" +.Ft int +.Fn archive_read_support_format_tar "struct archive *" +.Ft int +.Fn archive_read_support_format_xar "struct archive *" +.Ft int +.Fn archive_read_support_format_zip "struct archive *" +.\" +.Sh DESCRIPTION +.Bl -tag -compact -width indent +.It Xo +.Fn archive_read_support_format_7zip , +.Fn archive_read_support_format_ar , +.Fn archive_read_support_format_cab , +.Fn archive_read_support_format_cpio , +.Fn archive_read_support_format_iso9660 , +.Fn archive_read_support_format_lha , +.Fn archive_read_support_format_mtree , +.Fn archive_read_support_format_rar , +.Fn archive_read_support_format_raw , +.Fn archive_read_support_format_tar , +.Fn archive_read_support_format_xar , +.Fn archive_read_support_format_zip +.Xc +Enables support---including auto-detection code---for the +specified archive format. +For example, +.Fn archive_read_support_format_tar +enables support for a variety of standard tar formats, old-style tar, +ustar, pax interchange format, and many common variants. +.It Fn archive_read_support_format_all +Enables support for all available formats except the +.Dq raw +format (see below). +.It Fn archive_read_support_format_by_code +Enables a single format specified by the format code. +This can be useful when reading a single archive twice; +use +.Fn archive_format +after reading the first time and pass the resulting code +to this function to selectively enable only the necessary +format support. +Note: In statically-linked executables, this will cause +your program to include support for every format. +If executable size is a concern, you may wish to avoid +using this function. +.It Fn archive_read_support_format_empty +Enables support for treating empty files as empty archives. +Because empty files are valid for several different formats, +it is not possible to accurately determine a format for +an empty file based purely on contents. +So empty files are treated by libarchive as a distinct +format. +.It Fn archive_read_support_format_raw +The +.Dq raw +format handler allows libarchive to be used to read arbitrary data. +It treats any data stream as an archive with a single entry. +The pathname of this entry is +.Dq data ; +all other entry fields are unset. +This is not enabled by +.Fn archive_read_support_format_all +in order to avoid erroneous handling of damaged archives. +.El +.\" .Sh EXAMPLE +.Sh RETURN VALUES +These functions return +.Cm ARCHIVE_OK +on success, or +.Cm ARCHIVE_FATAL . +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_read_data 3 , +.Xr archive_read_filter 3 , +.Xr archive_read_set_options 3 , +.Xr archive_util 3 , +.Xr libarchive 3 , +.Xr tar 5 +.Sh BUGS +Many traditional archiver programs treat +empty files as valid empty archives. +For example, many implementations of +.Xr tar 1 +allow you to append entries to an empty file. +Of course, it is impossible to determine the format of an empty file +by inspecting the contents, so this library treats empty files as +having a special +.Dq empty +format. +.Pp +Using the +.Dq raw +handler together with any other handler will often work +but can produce surprising results. diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_free.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_free.3 new file mode 100644 index 0000000000..8371c3a0c6 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_free.3 @@ -0,0 +1,93 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_READ_FREE 3 +.Os +.Sh NAME +.Nm archive_read_close , +.Nm archive_read_finish , +.Nm archive_read_free +.Nd functions for reading streaming archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fn archive_read_close "struct archive *" +.Ft int +.Fn archive_read_finish "struct archive *" +.Ft int +.Fn archive_read_free "struct archive *" +.\" +.Sh DESCRIPTION +.Bl -tag -compact -width indent +.It Fn archive_read_close +Complete the archive and invoke the close callback. +.It Fn archive_read_finish +This is a deprecated synonym for +.Fn archive_read_free . +The new name was introduced with libarchive 3.0. +Applications that need to compile with either libarchive 2 +or libarchive 3 should continue to use the +.Fn archive_read_finish +name. +Both names will be supported until libarchive 4.0 is +released, which is not expected to occur earlier +than 2013. +.It Fn archive_read_free +Invokes +.Fn archive_read_close +if it was not invoked manually, then release all resources. +Note: In libarchive 1.x, this function was declared to return +.Ft void , +which made it impossible to detect certain errors when +.Fn archive_read_close +was invoked implicitly from this function. +The declaration is corrected beginning with libarchive 2.0. +.El +.Sh RETURN VALUES +These functions return +.Cm ARCHIVE_OK +on success, or +.Cm ARCHIVE_FATAL . +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr archive_read_data 3 , +.Xr archive_read_filter 3 , +.Xr archive_read_format 3 , +.Xr archive_read_new 3 , +.Xr archive_read_open 3 , +.Xr archive_read_set_options 3 , +.Xr archive_util 3 , +.Xr libarchive 3 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_header.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_header.3 new file mode 100644 index 0000000000..1e97f3a275 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_header.3 @@ -0,0 +1,91 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_READ_HEADER 3 +.Os +.Sh NAME +.Nm archive_read_next_header , +.Nm archive_read_next_header2 +.Nd functions for reading streaming archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fn archive_read_next_header "struct archive *" "struct archive_entry **" +.Ft int +.Fn archive_read_next_header2 "struct archive *" "struct archive_entry *" +.\" +.Sh DESCRIPTION +.Bl -tag -compact -width indent +.It Fn archive_read_next_header +Read the header for the next entry and return a pointer to +a +.Tn struct archive_entry . +This is a convenience wrapper around +.Fn archive_read_next_header2 +that reuses an internal +.Tn struct archive_entry +object for each request. +.It Fn archive_read_next_header2 +Read the header for the next entry and populate the provided +.Tn struct archive_entry . +.El +.\" +.Sh RETURN VALUES +These functions return +.Cm ARCHIVE_OK +(the operation succeeded), +.Cm ARCHIVE_WARN +(the operation succeeded but a non-critical error was encountered), +.Cm ARCHIVE_EOF +(end-of-archive was encountered), +.Cm ARCHIVE_RETRY +(the operation failed but can be retried), +and +.Cm ARCHIVE_FATAL +(there was a fatal error; the archive should be closed immediately). +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_read 3 , +.Xr archive_read_data 3 , +.Xr archive_read_extract 3 , +.Xr archive_read_filter 3 , +.Xr archive_read_format 3 , +.Xr archive_read_open 3 , +.Xr archive_read_set_options 3 , +.Xr archive_util 3 , +.Xr libarchive 3 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_new.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_new.3 new file mode 100644 index 0000000000..8bb6b848b0 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_new.3 @@ -0,0 +1,59 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_READ_NEW 3 +.Os +.Sh NAME +.Nm archive_read_new +.Nd functions for reading streaming archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft struct archive * +.Fn archive_read_new "void" +.Sh DESCRIPTION +Allocates and initializes a +.Tn struct archive +object suitable for reading from an archive. +.Dv NULL +is returned on error. +.Pp +A complete description of the +.Tn struct archive +object can be found in the overview manual page for +.Xr libarchive 3 . +.\" .Sh ERRORS +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_read_data 3 , +.Xr archive_read_filter 3 , +.Xr archive_read_format 3 , +.Xr archive_read_set_options 3 , +.Xr archive_util 3 , +.Xr libarchive 3 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open.3 new file mode 100644 index 0000000000..f67677823b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open.3 @@ -0,0 +1,233 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_READ_OPEN 3 +.Os +.Sh NAME +.Nm archive_read_open , +.Nm archive_read_open2 , +.Nm archive_read_open_fd , +.Nm archive_read_open_FILE , +.Nm archive_read_open_filename , +.Nm archive_read_open_memory +.Nd functions for reading streaming archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fo archive_read_open +.Fa "struct archive *" +.Fa "void *client_data" +.Fa "archive_open_callback *" +.Fa "archive_read_callback *" +.Fa "archive_close_callback *" +.Fc +.Ft int +.Fo archive_read_open2 +.Fa "struct archive *" +.Fa "void *client_data" +.Fa "archive_open_callback *" +.Fa "archive_read_callback *" +.Fa "archive_skip_callback *" +.Fa "archive_close_callback *" +.Fc +.Ft int +.Fn archive_read_open_FILE "struct archive *" "FILE *file" +.Ft int +.Fn archive_read_open_fd "struct archive *" "int fd" "size_t block_size" +.Ft int +.Fo archive_read_open_filename +.Fa "struct archive *" +.Fa "const char *filename" +.Fa "size_t block_size" +.Fc +.Ft int +.Fn archive_read_open_memory "struct archive *" "const void *buff" "size_t size" +.Sh DESCRIPTION +.Bl -tag -compact -width indent +.It Fn archive_read_open +The same as +.Fn archive_read_open2 , +except that the skip callback is assumed to be +.Dv NULL . +.It Fn archive_read_open2 +Freeze the settings, open the archive, and prepare for reading entries. +This is the most generic version of this call, which accepts +four callback functions. +Most clients will want to use +.Fn archive_read_open_filename , +.Fn archive_read_open_FILE , +.Fn archive_read_open_fd , +or +.Fn archive_read_open_memory +instead. +The library invokes the client-provided functions to obtain +raw bytes from the archive. +.It Fn archive_read_open_FILE +Like +.Fn archive_read_open , +except that it accepts a +.Ft "FILE *" +pointer. +This function should not be used with tape drives or other devices +that require strict I/O blocking. +.It Fn archive_read_open_fd +Like +.Fn archive_read_open , +except that it accepts a file descriptor and block size rather than +a set of function pointers. +Note that the file descriptor will not be automatically closed at +end-of-archive. +This function is safe for use with tape drives or other blocked devices. +.It Fn archive_read_open_file +This is a deprecated synonym for +.Fn archive_read_open_filename . +.It Fn archive_read_open_filename +Like +.Fn archive_read_open , +except that it accepts a simple filename and a block size. +A NULL filename represents standard input. +This function is safe for use with tape drives or other blocked devices. +.It Fn archive_read_open_memory +Like +.Fn archive_read_open , +except that it accepts a pointer and size of a block of +memory containing the archive data. +.El +.Pp +A complete description of the +.Tn struct archive +and +.Tn struct archive_entry +objects can be found in the overview manual page for +.Xr libarchive 3 . +.Sh CLIENT CALLBACKS +The callback functions must match the following prototypes: +.Bl -item -offset indent +.It +.Ft typedef la_ssize_t +.Fo archive_read_callback +.Fa "struct archive *" +.Fa "void *client_data" +.Fa "const void **buffer" +.Fc +.It +.Ft typedef la_int64_t +.Fo archive_skip_callback +.Fa "struct archive *" +.Fa "void *client_data" +.Fa "off_t request" +.Fc +.It +.Ft typedef int +.Fn archive_open_callback "struct archive *" "void *client_data" +.It +.Ft typedef int +.Fn archive_close_callback "struct archive *" "void *client_data" +.El +.Pp +The open callback is invoked by +.Fn archive_open . +It should return +.Cm ARCHIVE_OK +if the underlying file or data source is successfully +opened. +If the open fails, it should call +.Fn archive_set_error +to register an error code and message and return +.Cm ARCHIVE_FATAL . +.Pp +The read callback is invoked whenever the library +requires raw bytes from the archive. +The read callback should read data into a buffer, +set the +.Li const void **buffer +argument to point to the available data, and +return a count of the number of bytes available. +The library will invoke the read callback again +only after it has consumed this data. +The library imposes no constraints on the size +of the data blocks returned. +On end-of-file, the read callback should +return zero. +On error, the read callback should invoke +.Fn archive_set_error +to register an error code and message and +return -1. +.Pp +The skip callback is invoked when the +library wants to ignore a block of data. +The return value is the number of bytes actually +skipped, which may differ from the request. +If the callback cannot skip data, it should return +zero. +If the skip callback is not provided (the +function pointer is +.Dv NULL ), +the library will invoke the read function +instead and simply discard the result. +A skip callback can provide significant +performance gains when reading uncompressed +archives from slow disk drives or other media +that can skip quickly. +.Pp +The close callback is invoked by archive_close when +the archive processing is complete. +The callback should return +.Cm ARCHIVE_OK +on success. +On failure, the callback should invoke +.Fn archive_set_error +to register an error code and message and +return +.Cm ARCHIVE_FATAL . +.\" .Sh EXAMPLE +.\" +.Sh RETURN VALUES +These functions return +.Cm ARCHIVE_OK +on success, or +.Cm ARCHIVE_FATAL . +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_read 3 , +.Xr archive_read_data 3 , +.Xr archive_read_filter 3 , +.Xr archive_read_format 3 , +.Xr archive_read_set_options 3 , +.Xr archive_util 3 , +.Xr libarchive 3 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open_fd.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open_fd.c new file mode 100644 index 0000000000..f59cd07fe6 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open_fd.c @@ -0,0 +1,211 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_open_fd.c 201103 2009-12-28 03:13:49Z kientzle $"); + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_IO_H +#include <io.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#include "archive.h" + +struct read_fd_data { + int fd; + size_t block_size; + char use_lseek; + void *buffer; +}; + +static int file_close(struct archive *, void *); +static ssize_t file_read(struct archive *, void *, const void **buff); +static int64_t file_seek(struct archive *, void *, int64_t request, int); +static int64_t file_skip(struct archive *, void *, int64_t request); + +int +archive_read_open_fd(struct archive *a, int fd, size_t block_size) +{ + struct stat st; + struct read_fd_data *mine; + void *b; + + archive_clear_error(a); + if (fstat(fd, &st) != 0) { + archive_set_error(a, errno, "Can't stat fd %d", fd); + return (ARCHIVE_FATAL); + } + + mine = (struct read_fd_data *)calloc(1, sizeof(*mine)); + b = malloc(block_size); + if (mine == NULL || b == NULL) { + archive_set_error(a, ENOMEM, "No memory"); + free(mine); + free(b); + return (ARCHIVE_FATAL); + } + mine->block_size = block_size; + mine->buffer = b; + mine->fd = fd; + /* + * Skip support is a performance optimization for anything + * that supports lseek(). On FreeBSD, only regular files and + * raw disk devices support lseek() and there's no portable + * way to determine if a device is a raw disk device, so we + * only enable this optimization for regular files. + */ + if (S_ISREG(st.st_mode)) { + archive_read_extract_set_skip_file(a, st.st_dev, st.st_ino); + mine->use_lseek = 1; + } +#if defined(__CYGWIN__) || defined(_WIN32) + setmode(mine->fd, O_BINARY); +#endif + + archive_read_set_read_callback(a, file_read); + archive_read_set_skip_callback(a, file_skip); + archive_read_set_seek_callback(a, file_seek); + archive_read_set_close_callback(a, file_close); + archive_read_set_callback_data(a, mine); + return (archive_read_open1(a)); +} + +static ssize_t +file_read(struct archive *a, void *client_data, const void **buff) +{ + struct read_fd_data *mine = (struct read_fd_data *)client_data; + ssize_t bytes_read; + + *buff = mine->buffer; + for (;;) { + bytes_read = read(mine->fd, mine->buffer, mine->block_size); + if (bytes_read < 0) { + if (errno == EINTR) + continue; + archive_set_error(a, errno, "Error reading fd %d", + mine->fd); + } + return (bytes_read); + } +} + +static int64_t +file_skip(struct archive *a, void *client_data, int64_t request) +{ + struct read_fd_data *mine = (struct read_fd_data *)client_data; + int64_t skip = request; + int64_t old_offset, new_offset; + int skip_bits = sizeof(skip) * 8 - 1; /* off_t is a signed type. */ + + if (!mine->use_lseek) + return (0); + + /* Reduce a request that would overflow the 'skip' variable. */ + if (sizeof(request) > sizeof(skip)) { + int64_t max_skip = + (((int64_t)1 << (skip_bits - 1)) - 1) * 2 + 1; + if (request > max_skip) + skip = max_skip; + } + + /* Reduce request to the next smallest multiple of block_size */ + request = (request / mine->block_size) * mine->block_size; + if (request == 0) + return (0); + + if (((old_offset = lseek(mine->fd, 0, SEEK_CUR)) >= 0) && + ((new_offset = lseek(mine->fd, skip, SEEK_CUR)) >= 0)) + return (new_offset - old_offset); + + /* If seek failed once, it will probably fail again. */ + mine->use_lseek = 0; + + /* Let libarchive recover with read+discard. */ + if (errno == ESPIPE) + return (0); + + /* + * There's been an error other than ESPIPE. This is most + * likely caused by a programmer error (too large request) + * or a corrupted archive file. + */ + archive_set_error(a, errno, "Error seeking"); + return (-1); +} + +/* + * TODO: Store the offset and use it in the read callback. + */ +static int64_t +file_seek(struct archive *a, void *client_data, int64_t request, int whence) +{ + struct read_fd_data *mine = (struct read_fd_data *)client_data; + int64_t r; + + /* We use off_t here because lseek() is declared that way. */ + /* See above for notes about when off_t is less than 64 bits. */ + r = lseek(mine->fd, request, whence); + if (r >= 0) + return r; + + if (errno == ESPIPE) { + archive_set_error(a, errno, + "A file descriptor(%d) is not seekable(PIPE)", mine->fd); + return (ARCHIVE_FAILED); + } else { + /* If the input is corrupted or truncated, fail. */ + archive_set_error(a, errno, + "Error seeking in a file descriptor(%d)", mine->fd); + return (ARCHIVE_FATAL); + } +} + +static int +file_close(struct archive *a, void *client_data) +{ + struct read_fd_data *mine = (struct read_fd_data *)client_data; + + (void)a; /* UNUSED */ + free(mine->buffer); + free(mine); + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open_file.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open_file.c new file mode 100644 index 0000000000..101dae6cd9 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open_file.c @@ -0,0 +1,180 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_open_file.c 201093 2009-12-28 02:28:44Z kientzle $"); + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_IO_H +#include <io.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#include "archive.h" + +struct read_FILE_data { + FILE *f; + size_t block_size; + void *buffer; + char can_skip; +}; + +static int file_close(struct archive *, void *); +static ssize_t file_read(struct archive *, void *, const void **buff); +static int64_t file_skip(struct archive *, void *, int64_t request); + +int +archive_read_open_FILE(struct archive *a, FILE *f) +{ + struct stat st; + struct read_FILE_data *mine; + size_t block_size = 128 * 1024; + void *b; + + archive_clear_error(a); + mine = (struct read_FILE_data *)malloc(sizeof(*mine)); + b = malloc(block_size); + if (mine == NULL || b == NULL) { + archive_set_error(a, ENOMEM, "No memory"); + free(mine); + free(b); + return (ARCHIVE_FATAL); + } + mine->block_size = block_size; + mine->buffer = b; + mine->f = f; + /* + * If we can't fstat() the file, it may just be that it's not + * a file. (On some platforms, FILE * objects can wrap I/O + * streams that don't support fileno()). As a result, fileno() + * should be used cautiously.) + */ + if (fstat(fileno(mine->f), &st) == 0 && S_ISREG(st.st_mode)) { + archive_read_extract_set_skip_file(a, st.st_dev, st.st_ino); + /* Enable the seek optimization only for regular files. */ + mine->can_skip = 1; + } else + mine->can_skip = 0; + +#if defined(__CYGWIN__) || defined(_WIN32) + setmode(fileno(mine->f), O_BINARY); +#endif + + archive_read_set_read_callback(a, file_read); + archive_read_set_skip_callback(a, file_skip); + archive_read_set_close_callback(a, file_close); + archive_read_set_callback_data(a, mine); + return (archive_read_open1(a)); +} + +static ssize_t +file_read(struct archive *a, void *client_data, const void **buff) +{ + struct read_FILE_data *mine = (struct read_FILE_data *)client_data; + size_t bytes_read; + + *buff = mine->buffer; + bytes_read = fread(mine->buffer, 1, mine->block_size, mine->f); + if (bytes_read < mine->block_size && ferror(mine->f)) { + archive_set_error(a, errno, "Error reading file"); + } + return (bytes_read); +} + +static int64_t +file_skip(struct archive *a, void *client_data, int64_t request) +{ + struct read_FILE_data *mine = (struct read_FILE_data *)client_data; +#if HAVE_FSEEKO + off_t skip = (off_t)request; +#elif HAVE__FSEEKI64 + int64_t skip = request; +#else + long skip = (long)request; +#endif + int skip_bits = sizeof(skip) * 8 - 1; + + (void)a; /* UNUSED */ + + /* + * If we can't skip, return 0 as the amount we did step and + * the caller will work around by reading and discarding. + */ + if (!mine->can_skip) + return (0); + if (request == 0) + return (0); + + /* If request is too big for a long or an off_t, reduce it. */ + if (sizeof(request) > sizeof(skip)) { + int64_t max_skip = + (((int64_t)1 << (skip_bits - 1)) - 1) * 2 + 1; + if (request > max_skip) + skip = max_skip; + } + +#ifdef __ANDROID__ + /* fileno() isn't safe on all platforms ... see above. */ + if (lseek(fileno(mine->f), skip, SEEK_CUR) < 0) +#elif HAVE_FSEEKO + if (fseeko(mine->f, skip, SEEK_CUR) != 0) +#elif HAVE__FSEEKI64 + if (_fseeki64(mine->f, skip, SEEK_CUR) != 0) +#else + if (fseek(mine->f, skip, SEEK_CUR) != 0) +#endif + { + mine->can_skip = 0; + return (0); + } + return (request); +} + +static int +file_close(struct archive *a, void *client_data) +{ + struct read_FILE_data *mine = (struct read_FILE_data *)client_data; + + (void)a; /* UNUSED */ + free(mine->buffer); + free(mine); + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open_filename.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open_filename.c new file mode 100644 index 0000000000..561289b694 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open_filename.c @@ -0,0 +1,586 @@ +/*- + * Copyright (c) 2003-2010 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_open_filename.c 201093 2009-12-28 02:28:44Z kientzle $"); + +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_IO_H +#include <io.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) +#include <sys/disk.h> +#elif defined(__NetBSD__) || defined(__OpenBSD__) +#include <sys/disklabel.h> +#include <sys/dkio.h> +#elif defined(__DragonFly__) +#include <sys/diskslice.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_string.h" + +#ifndef O_BINARY +#define O_BINARY 0 +#endif +#ifndef O_CLOEXEC +#define O_CLOEXEC 0 +#endif + +struct read_file_data { + int fd; + size_t block_size; + void *buffer; + mode_t st_mode; /* Mode bits for opened file. */ + char use_lseek; + enum fnt_e { FNT_STDIN, FNT_MBS, FNT_WCS } filename_type; + union { + char m[1];/* MBS filename. */ + wchar_t w[1];/* WCS filename. */ + } filename; /* Must be last! */ +}; + +static int file_open(struct archive *, void *); +static int file_close(struct archive *, void *); +static int file_close2(struct archive *, void *); +static int file_switch(struct archive *, void *, void *); +static ssize_t file_read(struct archive *, void *, const void **buff); +static int64_t file_seek(struct archive *, void *, int64_t request, int); +static int64_t file_skip(struct archive *, void *, int64_t request); +static int64_t file_skip_lseek(struct archive *, void *, int64_t request); + +int +archive_read_open_file(struct archive *a, const char *filename, + size_t block_size) +{ + return (archive_read_open_filename(a, filename, block_size)); +} + +int +archive_read_open_filename(struct archive *a, const char *filename, + size_t block_size) +{ + const char *filenames[2]; + filenames[0] = filename; + filenames[1] = NULL; + return archive_read_open_filenames(a, filenames, block_size); +} + +int +archive_read_open_filenames(struct archive *a, const char **filenames, + size_t block_size) +{ + struct read_file_data *mine; + const char *filename = NULL; + if (filenames) + filename = *(filenames++); + + archive_clear_error(a); + do + { + if (filename == NULL) + filename = ""; + mine = (struct read_file_data *)calloc(1, + sizeof(*mine) + strlen(filename)); + if (mine == NULL) + goto no_memory; + strcpy(mine->filename.m, filename); + mine->block_size = block_size; + mine->fd = -1; + mine->buffer = NULL; + mine->st_mode = mine->use_lseek = 0; + if (filename == NULL || filename[0] == '\0') { + mine->filename_type = FNT_STDIN; + } else + mine->filename_type = FNT_MBS; + if (archive_read_append_callback_data(a, mine) != (ARCHIVE_OK)) + return (ARCHIVE_FATAL); + if (filenames == NULL) + break; + filename = *(filenames++); + } while (filename != NULL && filename[0] != '\0'); + archive_read_set_open_callback(a, file_open); + archive_read_set_read_callback(a, file_read); + archive_read_set_skip_callback(a, file_skip); + archive_read_set_close_callback(a, file_close); + archive_read_set_switch_callback(a, file_switch); + archive_read_set_seek_callback(a, file_seek); + + return (archive_read_open1(a)); +no_memory: + archive_set_error(a, ENOMEM, "No memory"); + return (ARCHIVE_FATAL); +} + +int +archive_read_open_filename_w(struct archive *a, const wchar_t *wfilename, + size_t block_size) +{ + struct read_file_data *mine = (struct read_file_data *)calloc(1, + sizeof(*mine) + wcslen(wfilename) * sizeof(wchar_t)); + if (!mine) + { + archive_set_error(a, ENOMEM, "No memory"); + return (ARCHIVE_FATAL); + } + mine->fd = -1; + mine->block_size = block_size; + + if (wfilename == NULL || wfilename[0] == L'\0') { + mine->filename_type = FNT_STDIN; + } else { +#if defined(_WIN32) && !defined(__CYGWIN__) + mine->filename_type = FNT_WCS; + wcscpy(mine->filename.w, wfilename); +#else + /* + * POSIX system does not support a wchar_t interface for + * open() system call, so we have to translate a wchar_t + * filename to multi-byte one and use it. + */ + struct archive_string fn; + + archive_string_init(&fn); + if (archive_string_append_from_wcs(&fn, wfilename, + wcslen(wfilename)) != 0) { + if (errno == ENOMEM) + archive_set_error(a, errno, + "Can't allocate memory"); + else + archive_set_error(a, EINVAL, + "Failed to convert a wide-character" + " filename to a multi-byte filename"); + archive_string_free(&fn); + free(mine); + return (ARCHIVE_FATAL); + } + mine->filename_type = FNT_MBS; + strcpy(mine->filename.m, fn.s); + archive_string_free(&fn); +#endif + } + if (archive_read_append_callback_data(a, mine) != (ARCHIVE_OK)) + return (ARCHIVE_FATAL); + archive_read_set_open_callback(a, file_open); + archive_read_set_read_callback(a, file_read); + archive_read_set_skip_callback(a, file_skip); + archive_read_set_close_callback(a, file_close); + archive_read_set_switch_callback(a, file_switch); + archive_read_set_seek_callback(a, file_seek); + + return (archive_read_open1(a)); +} + +static int +file_open(struct archive *a, void *client_data) +{ + struct stat st; + struct read_file_data *mine = (struct read_file_data *)client_data; + void *buffer; + const char *filename = NULL; +#if defined(_WIN32) && !defined(__CYGWIN__) + const wchar_t *wfilename = NULL; +#endif + int fd = -1; + int is_disk_like = 0; +#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) + off_t mediasize = 0; /* FreeBSD-specific, so off_t okay here. */ +#elif defined(__NetBSD__) || defined(__OpenBSD__) + struct disklabel dl; +#elif defined(__DragonFly__) + struct partinfo pi; +#endif + + archive_clear_error(a); + if (mine->filename_type == FNT_STDIN) { + /* We used to delegate stdin support by + * directly calling archive_read_open_fd(a,0,block_size) + * here, but that doesn't (and shouldn't) handle the + * end-of-file flush when reading stdout from a pipe. + * Basically, read_open_fd() is intended for folks who + * are willing to handle such details themselves. This + * API is intended to be a little smarter for folks who + * want easy handling of the common case. + */ + fd = 0; +#if defined(__CYGWIN__) || defined(_WIN32) + setmode(0, O_BINARY); +#endif + filename = ""; + } else if (mine->filename_type == FNT_MBS) { + filename = mine->filename.m; + fd = open(filename, O_RDONLY | O_BINARY | O_CLOEXEC); + __archive_ensure_cloexec_flag(fd); + if (fd < 0) { + archive_set_error(a, errno, + "Failed to open '%s'", filename); + return (ARCHIVE_FATAL); + } + } else { +#if defined(_WIN32) && !defined(__CYGWIN__) + wfilename = mine->filename.w; + fd = _wopen(wfilename, O_RDONLY | O_BINARY); + if (fd < 0 && errno == ENOENT) { + wchar_t *fullpath; + fullpath = __la_win_permissive_name_w(wfilename); + if (fullpath != NULL) { + fd = _wopen(fullpath, O_RDONLY | O_BINARY); + free(fullpath); + } + } + if (fd < 0) { + archive_set_error(a, errno, + "Failed to open '%S'", wfilename); + return (ARCHIVE_FATAL); + } +#else + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Unexpedted operation in archive_read_open_filename"); + goto fail; +#endif + } + if (fstat(fd, &st) != 0) { +#if defined(_WIN32) && !defined(__CYGWIN__) + if (mine->filename_type == FNT_WCS) + archive_set_error(a, errno, "Can't stat '%S'", + wfilename); + else +#endif + archive_set_error(a, errno, "Can't stat '%s'", + filename); + goto fail; + } + + /* + * Determine whether the input looks like a disk device or a + * tape device. The results are used below to select an I/O + * strategy: + * = "disk-like" devices support arbitrary lseek() and will + * support I/O requests of any size. So we get easy skipping + * and can cheat on block sizes to get better performance. + * = "tape-like" devices require strict blocking and use + * specialized ioctls for seeking. + * = "socket-like" devices cannot seek at all but can improve + * performance by using nonblocking I/O to read "whatever is + * available right now". + * + * Right now, we only specially recognize disk-like devices, + * but it should be straightforward to add probes and strategy + * here for tape-like and socket-like devices. + */ + if (S_ISREG(st.st_mode)) { + /* Safety: Tell the extractor not to overwrite the input. */ + archive_read_extract_set_skip_file(a, st.st_dev, st.st_ino); + /* Regular files act like disks. */ + is_disk_like = 1; + } +#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) + /* FreeBSD: if it supports DIOCGMEDIASIZE ioctl, it's disk-like. */ + else if (S_ISCHR(st.st_mode) && + ioctl(fd, DIOCGMEDIASIZE, &mediasize) == 0 && + mediasize > 0) { + is_disk_like = 1; + } +#elif defined(__NetBSD__) || defined(__OpenBSD__) + /* Net/OpenBSD: if it supports DIOCGDINFO ioctl, it's disk-like. */ + else if ((S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) && + ioctl(fd, DIOCGDINFO, &dl) == 0 && + dl.d_partitions[DISKPART(st.st_rdev)].p_size > 0) { + is_disk_like = 1; + } +#elif defined(__DragonFly__) + /* DragonFly BSD: if it supports DIOCGPART ioctl, it's disk-like. */ + else if (S_ISCHR(st.st_mode) && + ioctl(fd, DIOCGPART, &pi) == 0 && + pi.media_size > 0) { + is_disk_like = 1; + } +#elif defined(__linux__) + /* Linux: All block devices are disk-like. */ + else if (S_ISBLK(st.st_mode) && + lseek(fd, 0, SEEK_CUR) == 0 && + lseek(fd, 0, SEEK_SET) == 0 && + lseek(fd, 0, SEEK_END) > 0 && + lseek(fd, 0, SEEK_SET) == 0) { + is_disk_like = 1; + } +#endif + /* TODO: Add an "is_tape_like" variable and appropriate tests. */ + + /* Disk-like devices prefer power-of-two block sizes. */ + /* Use provided block_size as a guide so users have some control. */ + if (is_disk_like) { + size_t new_block_size = 64 * 1024; + while (new_block_size < mine->block_size + && new_block_size < 64 * 1024 * 1024) + new_block_size *= 2; + mine->block_size = new_block_size; + } + buffer = malloc(mine->block_size); + if (buffer == NULL) { + archive_set_error(a, ENOMEM, "No memory"); + goto fail; + } + mine->buffer = buffer; + mine->fd = fd; + /* Remember mode so close can decide whether to flush. */ + mine->st_mode = st.st_mode; + + /* Disk-like inputs can use lseek(). */ + if (is_disk_like) + mine->use_lseek = 1; + + return (ARCHIVE_OK); +fail: + /* + * Don't close file descriptors not opened or ones pointing referring + * to `FNT_STDIN`. + */ + if (fd != -1 && fd != 0) + close(fd); + return (ARCHIVE_FATAL); +} + +static ssize_t +file_read(struct archive *a, void *client_data, const void **buff) +{ + struct read_file_data *mine = (struct read_file_data *)client_data; + ssize_t bytes_read; + + /* TODO: If a recent lseek() operation has left us + * mis-aligned, read and return a short block to try to get + * us back in alignment. */ + + /* TODO: Someday, try mmap() here; if that succeeds, give + * the entire file to libarchive as a single block. That + * could be a lot faster than block-by-block manual I/O. */ + + /* TODO: We might be able to improve performance on pipes and + * sockets by setting non-blocking I/O and just accepting + * whatever we get here instead of waiting for a full block + * worth of data. */ + + *buff = mine->buffer; + for (;;) { + bytes_read = read(mine->fd, mine->buffer, mine->block_size); + if (bytes_read < 0) { + if (errno == EINTR) + continue; + else if (mine->filename_type == FNT_STDIN) + archive_set_error(a, errno, + "Error reading stdin"); + else if (mine->filename_type == FNT_MBS) + archive_set_error(a, errno, + "Error reading '%s'", mine->filename.m); + else + archive_set_error(a, errno, + "Error reading '%S'", mine->filename.w); + } + return (bytes_read); + } +} + +/* + * Regular files and disk-like block devices can use simple lseek + * without needing to round the request to the block size. + * + * TODO: This can leave future reads mis-aligned. Since we know the + * offset here, we should store it and use it in file_read() above + * to determine whether we should perform a short read to get back + * into alignment. Long series of mis-aligned reads can negatively + * impact disk throughput. (Of course, the performance impact should + * be carefully tested; extra code complexity is only worthwhile if + * it does provide measurable improvement.) + * + * TODO: Be lazy about the actual seek. There are a few pathological + * cases where libarchive makes a bunch of seek requests in a row + * without any intervening reads. This isn't a huge performance + * problem, since the kernel handles seeks lazily already, but + * it would be very slightly faster if we simply remembered the + * seek request here and then actually performed the seek at the + * top of the read callback above. + */ +static int64_t +file_skip_lseek(struct archive *a, void *client_data, int64_t request) +{ + struct read_file_data *mine = (struct read_file_data *)client_data; +#if defined(_WIN32) && !defined(__CYGWIN__) + /* We use _lseeki64() on Windows. */ + int64_t old_offset, new_offset; +#else + off_t old_offset, new_offset; +#endif + + /* We use off_t here because lseek() is declared that way. */ + + /* TODO: Deal with case where off_t isn't 64 bits. + * This shouldn't be a problem on Linux or other POSIX + * systems, since the configuration logic for libarchive + * tries to obtain a 64-bit off_t. + */ + if ((old_offset = lseek(mine->fd, 0, SEEK_CUR)) >= 0 && + (new_offset = lseek(mine->fd, request, SEEK_CUR)) >= 0) + return (new_offset - old_offset); + + /* If lseek() fails, don't bother trying again. */ + mine->use_lseek = 0; + + /* Let libarchive recover with read+discard */ + if (errno == ESPIPE) + return (0); + + /* If the input is corrupted or truncated, fail. */ + if (mine->filename_type == FNT_STDIN) + archive_set_error(a, errno, "Error seeking in stdin"); + else if (mine->filename_type == FNT_MBS) + archive_set_error(a, errno, "Error seeking in '%s'", + mine->filename.m); + else + archive_set_error(a, errno, "Error seeking in '%S'", + mine->filename.w); + return (-1); +} + + +/* + * TODO: Implement another file_skip_XXXX that uses MTIO ioctls to + * accelerate operation on tape drives. + */ + +static int64_t +file_skip(struct archive *a, void *client_data, int64_t request) +{ + struct read_file_data *mine = (struct read_file_data *)client_data; + + /* Delegate skip requests. */ + if (mine->use_lseek) + return (file_skip_lseek(a, client_data, request)); + + /* If we can't skip, return 0; libarchive will read+discard instead. */ + return (0); +} + +/* + * TODO: Store the offset and use it in the read callback. + */ +static int64_t +file_seek(struct archive *a, void *client_data, int64_t request, int whence) +{ + struct read_file_data *mine = (struct read_file_data *)client_data; + int64_t r; + + /* We use off_t here because lseek() is declared that way. */ + /* See above for notes about when off_t is less than 64 bits. */ + r = lseek(mine->fd, request, whence); + if (r >= 0) + return r; + + /* If the input is corrupted or truncated, fail. */ + if (mine->filename_type == FNT_STDIN) + archive_set_error(a, errno, "Error seeking in stdin"); + else if (mine->filename_type == FNT_MBS) + archive_set_error(a, errno, "Error seeking in '%s'", + mine->filename.m); + else + archive_set_error(a, errno, "Error seeking in '%S'", + mine->filename.w); + return (ARCHIVE_FATAL); +} + +static int +file_close2(struct archive *a, void *client_data) +{ + struct read_file_data *mine = (struct read_file_data *)client_data; + + (void)a; /* UNUSED */ + + /* Only flush and close if open succeeded. */ + if (mine->fd >= 0) { + /* + * Sometimes, we should flush the input before closing. + * Regular files: faster to just close without flush. + * Disk-like devices: Ditto. + * Tapes: must not flush (user might need to + * read the "next" item on a non-rewind device). + * Pipes and sockets: must flush (otherwise, the + * program feeding the pipe or socket may complain). + * Here, I flush everything except for regular files and + * device nodes. + */ + if (!S_ISREG(mine->st_mode) + && !S_ISCHR(mine->st_mode) + && !S_ISBLK(mine->st_mode)) { + ssize_t bytesRead; + do { + bytesRead = read(mine->fd, mine->buffer, + mine->block_size); + } while (bytesRead > 0); + } + /* If a named file was opened, then it needs to be closed. */ + if (mine->filename_type != FNT_STDIN) + close(mine->fd); + } + free(mine->buffer); + mine->buffer = NULL; + mine->fd = -1; + return (ARCHIVE_OK); +} + +static int +file_close(struct archive *a, void *client_data) +{ + struct read_file_data *mine = (struct read_file_data *)client_data; + file_close2(a, client_data); + free(mine); + return (ARCHIVE_OK); +} + +static int +file_switch(struct archive *a, void *client_data1, void *client_data2) +{ + file_close2(a, client_data1); + return file_open(a, client_data2); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open_memory.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open_memory.c new file mode 100644 index 0000000000..311be47046 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_open_memory.c @@ -0,0 +1,186 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: src/lib/libarchive/archive_read_open_memory.c,v 1.6 2007/07/06 15:51:59 kientzle Exp $"); + +#include <errno.h> +#include <stdlib.h> +#include <string.h> + +#include "archive.h" + +/* + * Glue to read an archive from a block of memory. + * + * This is mostly a huge help in building test harnesses; + * test programs can build archives in memory and read them + * back again without having to mess with files on disk. + */ + +struct read_memory_data { + const unsigned char *start; + const unsigned char *p; + const unsigned char *end; + ssize_t read_size; +}; + +static int memory_read_close(struct archive *, void *); +static int memory_read_open(struct archive *, void *); +static int64_t memory_read_seek(struct archive *, void *, int64_t offset, int whence); +static int64_t memory_read_skip(struct archive *, void *, int64_t request); +static ssize_t memory_read(struct archive *, void *, const void **buff); + +int +archive_read_open_memory(struct archive *a, const void *buff, size_t size) +{ + return archive_read_open_memory2(a, buff, size, size); +} + +/* + * Don't use _open_memory2() in production code; the archive_read_open_memory() + * version is the one you really want. This is just here so that + * test harnesses can exercise block operations inside the library. + */ +int +archive_read_open_memory2(struct archive *a, const void *buff, + size_t size, size_t read_size) +{ + struct read_memory_data *mine; + + mine = (struct read_memory_data *)calloc(1, sizeof(*mine)); + if (mine == NULL) { + archive_set_error(a, ENOMEM, "No memory"); + return (ARCHIVE_FATAL); + } + mine->start = mine->p = (const unsigned char *)buff; + mine->end = mine->start + size; + mine->read_size = read_size; + archive_read_set_open_callback(a, memory_read_open); + archive_read_set_read_callback(a, memory_read); + archive_read_set_seek_callback(a, memory_read_seek); + archive_read_set_skip_callback(a, memory_read_skip); + archive_read_set_close_callback(a, memory_read_close); + archive_read_set_callback_data(a, mine); + return (archive_read_open1(a)); +} + +/* + * There's nothing to open. + */ +static int +memory_read_open(struct archive *a, void *client_data) +{ + (void)a; /* UNUSED */ + (void)client_data; /* UNUSED */ + return (ARCHIVE_OK); +} + +/* + * This is scary simple: Just advance a pointer. Limiting + * to read_size is not technically necessary, but it exercises + * more of the internal logic when used with a small block size + * in a test harness. Production use should not specify a block + * size; then this is much faster. + */ +static ssize_t +memory_read(struct archive *a, void *client_data, const void **buff) +{ + struct read_memory_data *mine = (struct read_memory_data *)client_data; + ssize_t size; + + (void)a; /* UNUSED */ + *buff = mine->p; + size = mine->end - mine->p; + if (size > mine->read_size) + size = mine->read_size; + mine->p += size; + return (size); +} + +/* + * Advancing is just as simple. Again, this is doing more than + * necessary in order to better exercise internal code when used + * as a test harness. + */ +static int64_t +memory_read_skip(struct archive *a, void *client_data, int64_t skip) +{ + struct read_memory_data *mine = (struct read_memory_data *)client_data; + + (void)a; /* UNUSED */ + if ((int64_t)skip > (int64_t)(mine->end - mine->p)) + skip = mine->end - mine->p; + /* Round down to block size. */ + skip /= mine->read_size; + skip *= mine->read_size; + mine->p += skip; + return (skip); +} + +/* + * Seeking. + */ +static int64_t +memory_read_seek(struct archive *a, void *client_data, int64_t offset, int whence) +{ + struct read_memory_data *mine = (struct read_memory_data *)client_data; + + (void)a; /* UNUSED */ + switch (whence) { + case SEEK_SET: + mine->p = mine->start + offset; + break; + case SEEK_CUR: + mine->p += offset; + break; + case SEEK_END: + mine->p = mine->end + offset; + break; + default: + return ARCHIVE_FATAL; + } + if (mine->p < mine->start) { + mine->p = mine->start; + return ARCHIVE_FAILED; + } + if (mine->p > mine->end) { + mine->p = mine->end; + return ARCHIVE_FAILED; + } + return (mine->p - mine->start); +} + +/* + * Close is just cleaning up our one small bit of data. + */ +static int +memory_read_close(struct archive *a, void *client_data) +{ + struct read_memory_data *mine = (struct read_memory_data *)client_data; + (void)a; /* UNUSED */ + free(mine); + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_private.h new file mode 100644 index 0000000000..c842e6f09a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_private.h @@ -0,0 +1,266 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + * + * $FreeBSD: head/lib/libarchive/archive_read_private.h 201088 2009-12-28 02:18:55Z kientzle $ + */ + +#ifndef ARCHIVE_READ_PRIVATE_H_INCLUDED +#define ARCHIVE_READ_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#ifndef __LIBARCHIVE_TEST +#error This header is only to be used internally to libarchive. +#endif +#endif + +#include "archive.h" +#include "archive_string.h" +#include "archive_private.h" + +struct archive_read; +struct archive_read_filter_bidder; +struct archive_read_filter; + +/* + * How bidding works for filters: + * * The bid manager initializes the client-provided reader as the + * first filter. + * * It invokes the bidder for each registered filter with the + * current head filter. + * * The bidders can use archive_read_filter_ahead() to peek ahead + * at the incoming data to compose their bids. + * * The bid manager creates a new filter structure for the winning + * bidder and gives the winning bidder a chance to initialize it. + * * The new filter becomes the new top filter and we repeat the + * process. + * This ends only when no bidder provides a non-zero bid. Then + * we perform a similar dance with the registered format handlers. + */ +struct archive_read_filter_bidder { + /* Configuration data for the bidder. */ + void *data; + /* Name of the filter */ + const char *name; + /* Taste the upstream filter to see if we handle this. */ + int (*bid)(struct archive_read_filter_bidder *, + struct archive_read_filter *); + /* Initialize a newly-created filter. */ + int (*init)(struct archive_read_filter *); + /* Set an option for the filter bidder. */ + int (*options)(struct archive_read_filter_bidder *, + const char *key, const char *value); + /* Release the bidder's configuration data. */ + int (*free)(struct archive_read_filter_bidder *); +}; + +/* + * This structure is allocated within the archive_read core + * and initialized by archive_read and the init() method of the + * corresponding bidder above. + */ +struct archive_read_filter { + int64_t position; + /* Essentially all filters will need these values, so + * just declare them here. */ + struct archive_read_filter_bidder *bidder; /* My bidder. */ + struct archive_read_filter *upstream; /* Who I read from. */ + struct archive_read *archive; /* Associated archive. */ + /* Open a block for reading */ + int (*open)(struct archive_read_filter *self); + /* Return next block. */ + ssize_t (*read)(struct archive_read_filter *, const void **); + /* Skip forward this many bytes. */ + int64_t (*skip)(struct archive_read_filter *self, int64_t request); + /* Seek to an absolute location. */ + int64_t (*seek)(struct archive_read_filter *self, int64_t offset, int whence); + /* Close (just this filter) and free(self). */ + int (*close)(struct archive_read_filter *self); + /* Function that handles switching from reading one block to the next/prev */ + int (*sswitch)(struct archive_read_filter *self, unsigned int iindex); + /* Read any header metadata if available. */ + int (*read_header)(struct archive_read_filter *self, struct archive_entry *entry); + /* My private data. */ + void *data; + + const char *name; + int code; + + /* Used by reblocking logic. */ + char *buffer; + size_t buffer_size; + char *next; /* Current read location. */ + size_t avail; /* Bytes in my buffer. */ + const void *client_buff; /* Client buffer information. */ + size_t client_total; + const char *client_next; + size_t client_avail; + char end_of_file; + char closed; + char fatal; +}; + +/* + * The client looks a lot like a filter, so we just wrap it here. + * + * TODO: Make archive_read_filter and archive_read_client identical so + * that users of the library can easily register their own + * transformation filters. This will probably break the API/ABI and + * so should be deferred at least until libarchive 3.0. + */ +struct archive_read_data_node { + int64_t begin_position; + int64_t total_size; + void *data; +}; +struct archive_read_client { + archive_open_callback *opener; + archive_read_callback *reader; + archive_skip_callback *skipper; + archive_seek_callback *seeker; + archive_close_callback *closer; + archive_switch_callback *switcher; + unsigned int nodes; + unsigned int cursor; + int64_t position; + struct archive_read_data_node *dataset; +}; +struct archive_read_passphrase { + char *passphrase; + struct archive_read_passphrase *next; +}; + +struct archive_read_extract { + struct archive *ad; /* archive_write_disk object */ + + /* Progress function invoked during extract. */ + void (*extract_progress)(void *); + void *extract_progress_user_data; +}; + +struct archive_read { + struct archive archive; + + struct archive_entry *entry; + + /* Dev/ino of the archive being read/written. */ + int skip_file_set; + int64_t skip_file_dev; + int64_t skip_file_ino; + + /* Callbacks to open/read/write/close client archive streams. */ + struct archive_read_client client; + + /* Registered filter bidders. */ + struct archive_read_filter_bidder bidders[16]; + + /* Last filter in chain */ + struct archive_read_filter *filter; + + /* Whether to bypass filter bidding process */ + int bypass_filter_bidding; + + /* File offset of beginning of most recently-read header. */ + int64_t header_position; + + /* Nodes and offsets of compressed data block */ + unsigned int data_start_node; + unsigned int data_end_node; + + /* + * Format detection is mostly the same as compression + * detection, with one significant difference: The bidders + * use the read_ahead calls above to examine the stream rather + * than having the supervisor hand them a block of data to + * examine. + */ + + struct archive_format_descriptor { + void *data; + const char *name; + int (*bid)(struct archive_read *, int best_bid); + int (*options)(struct archive_read *, const char *key, + const char *value); + int (*read_header)(struct archive_read *, struct archive_entry *); + int (*read_data)(struct archive_read *, const void **, size_t *, int64_t *); + int (*read_data_skip)(struct archive_read *); + int64_t (*seek_data)(struct archive_read *, int64_t, int); + int (*cleanup)(struct archive_read *); + int (*format_capabilties)(struct archive_read *); + int (*has_encrypted_entries)(struct archive_read *); + } formats[16]; + struct archive_format_descriptor *format; /* Active format. */ + + /* + * Various information needed by archive_extract. + */ + struct archive_read_extract *extract; + int (*cleanup_archive_extract)(struct archive_read *); + + /* + * Decryption passphrase. + */ + struct { + struct archive_read_passphrase *first; + struct archive_read_passphrase **last; + int candidate; + archive_passphrase_callback *callback; + void *client_data; + } passphrases; +}; + +int __archive_read_register_format(struct archive_read *a, + void *format_data, + const char *name, + int (*bid)(struct archive_read *, int), + int (*options)(struct archive_read *, const char *, const char *), + int (*read_header)(struct archive_read *, struct archive_entry *), + int (*read_data)(struct archive_read *, const void **, size_t *, int64_t *), + int (*read_data_skip)(struct archive_read *), + int64_t (*seek_data)(struct archive_read *, int64_t, int), + int (*cleanup)(struct archive_read *), + int (*format_capabilities)(struct archive_read *), + int (*has_encrypted_entries)(struct archive_read *)); + +int __archive_read_get_bidder(struct archive_read *a, + struct archive_read_filter_bidder **bidder); + +const void *__archive_read_ahead(struct archive_read *, size_t, ssize_t *); +const void *__archive_read_filter_ahead(struct archive_read_filter *, + size_t, ssize_t *); +int64_t __archive_read_seek(struct archive_read*, int64_t, int); +int64_t __archive_read_filter_seek(struct archive_read_filter *, int64_t, int); +int64_t __archive_read_consume(struct archive_read *, int64_t); +int64_t __archive_read_filter_consume(struct archive_read_filter *, int64_t); +int __archive_read_header(struct archive_read *, struct archive_entry *); +int __archive_read_program(struct archive_read_filter *, const char *); +void __archive_read_free_filters(struct archive_read *); +struct archive_read_extract *__archive_read_get_extract(struct archive_read *); + + +/* + * Get a decryption passphrase. + */ +void __archive_read_reset_passphrase(struct archive_read *a); +const char * __archive_read_next_passphrase(struct archive_read *a); +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_set_format.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_set_format.c new file mode 100644 index 0000000000..1d3e49d164 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_set_format.c @@ -0,0 +1,108 @@ +/*- + * Copyright (c) 2003-2012 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_read_private.h" + +int +archive_read_set_format(struct archive *_a, int code) +{ + int r1, r2, slots, i; + char str[10]; + struct archive_read *a = (struct archive_read *)_a; + + if ((r1 = archive_read_support_format_by_code(_a, code)) < (ARCHIVE_OK)) + return r1; + + r1 = r2 = (ARCHIVE_OK); + if (a->format) + r2 = (ARCHIVE_WARN); + switch (code & ARCHIVE_FORMAT_BASE_MASK) + { + case ARCHIVE_FORMAT_7ZIP: + strcpy(str, "7zip"); + break; + case ARCHIVE_FORMAT_AR: + strcpy(str, "ar"); + break; + case ARCHIVE_FORMAT_CAB: + strcpy(str, "cab"); + break; + case ARCHIVE_FORMAT_CPIO: + strcpy(str, "cpio"); + break; + case ARCHIVE_FORMAT_ISO9660: + strcpy(str, "iso9660"); + break; + case ARCHIVE_FORMAT_LHA: + strcpy(str, "lha"); + break; + case ARCHIVE_FORMAT_MTREE: + strcpy(str, "mtree"); + break; + case ARCHIVE_FORMAT_RAR: + strcpy(str, "rar"); + break; + case ARCHIVE_FORMAT_RAR_V5: + strcpy(str, "rar5"); + break; + case ARCHIVE_FORMAT_TAR: + strcpy(str, "tar"); + break; + case ARCHIVE_FORMAT_XAR: + strcpy(str, "xar"); + break; + case ARCHIVE_FORMAT_ZIP: + strcpy(str, "zip"); + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Invalid format code specified"); + return (ARCHIVE_FATAL); + } + + slots = sizeof(a->formats) / sizeof(a->formats[0]); + a->format = &(a->formats[0]); + for (i = 0; i < slots; i++, a->format++) { + if (!a->format->name || !strcmp(a->format->name, str)) + break; + } + if (!a->format->name || strcmp(a->format->name, str)) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Internal error: Unable to set format"); + r1 = (ARCHIVE_FATAL); + } + + return (r1 < r2) ? r1 : r2; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_set_options.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_set_options.3 new file mode 100644 index 0000000000..78d99999cf --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_set_options.3 @@ -0,0 +1,262 @@ +.\" Copyright (c) 2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd January 31, 2020 +.Dt ARCHIVE_READ_OPTIONS 3 +.Os +.Sh NAME +.Nm archive_read_set_filter_option , +.Nm archive_read_set_format_option , +.Nm archive_read_set_option , +.Nm archive_read_set_options +.Nd functions controlling options for reading archives +.\" +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.Ft int +.Fo archive_read_set_filter_option +.Fa "struct archive *" +.Fa "const char *module" +.Fa "const char *option" +.Fa "const char *value" +.Fc +.Ft int +.Fo archive_read_set_format_option +.Fa "struct archive *" +.Fa "const char *module" +.Fa "const char *option" +.Fa "const char *value" +.Fc +.Ft int +.Fo archive_read_set_option +.Fa "struct archive *" +.Fa "const char *module" +.Fa "const char *option" +.Fa "const char *value" +.Fc +.Ft int +.Fo archive_read_set_options +.Fa "struct archive *" +.Fa "const char *options" +.Fc +.Sh DESCRIPTION +These functions provide a way for libarchive clients to configure +specific read modules. +.Bl -tag -width indent +.It Xo +.Fn archive_read_set_filter_option , +.Fn archive_read_set_format_option +.Xc +Specifies an option that will be passed to currently-registered +filters (including decompression filters) or format readers. +.Pp +If +.Ar option +and +.Ar value +are both +.Dv NULL , +these functions will do nothing and +.Cm ARCHIVE_OK +will be returned. +If +.Ar option +is +.Dv NULL +but +.Ar value +is not, these functions will do nothing and +.Cm ARCHIVE_FAILED +will be returned. +.Pp +If +.Ar module +is not +.Dv NULL , +.Ar option +and +.Ar value +will be provided to the filter or reader named +.Ar module . +The return value will be that of the module. +If there is no such module, +.Cm ARCHIVE_FAILED +will be returned. +.Pp +If +.Ar module +is +.Dv NULL , +.Ar option +and +.Ar value +will be provided to every registered module. +If any module returns +.Cm ARCHIVE_FATAL , +this value will be returned immediately. +Otherwise, +.Cm ARCHIVE_OK +will be returned if any module accepts the option, and +.Cm ARCHIVE_FAILED +in all other cases. +.\" +.It Xo +.Fn archive_read_set_option +.Xc +Calls +.Fn archive_read_set_format_option , +then +.Fn archive_read_set_filter_option . +If either function returns +.Cm ARCHIVE_FATAL , +.Cm ARCHIVE_FATAL +will be returned +immediately. +Otherwise, greater of the two values will be returned. +.\" +.It Xo +.Fn archive_read_set_options +.Xc +.Ar options +is a comma-separated list of options. +If +.Ar options +is +.Dv NULL +or empty, +.Cm ARCHIVE_OK +will be returned immediately. +.Pp +Calls +.Fn archive_read_set_option +with each option in turn. +If any +.Fn archive_read_set_option +call returns +.Cm ARCHIVE_FATAL , +.Cm ARCHIVE_FATAL +will be returned immediately. +.Pp +Individual options have one of the following forms: +.Bl -tag -compact -width indent +.It Ar option=value +The option/value pair will be provided to every module. +Modules that do not accept an option with this name will ignore it. +.It Ar option +The option will be provided to every module with a value of +.Dq 1 . +.It Ar !option +The option will be provided to every module with a NULL value. +.It Ar module:option=value , Ar module:option , Ar module:!option +As above, but the corresponding option and value will be provided +only to modules whose name matches +.Ar module . +.El +.El +.\" +.Sh OPTIONS +.Bl -tag -compact -width indent +.It Format cab +.Bl -tag -compact -width indent +.It Cm hdrcharset +The value is used as a character set name that will be +used when translating file names. +.El +.It Format cpio +.Bl -tag -compact -width indent +.It Cm hdrcharset +The value is used as a character set name that will be +used when translating file names. +.El +.It Format iso9660 +.Bl -tag -compact -width indent +.It Cm joliet +Support Joliet extensions. +Defaults to enabled, use +.Cm !joliet +to disable. +.It Cm rockridge +Support RockRidge extensions. +Defaults to enabled, use +.Cm !rockridge +to disable. +.El +.It Format lha +.Bl -tag -compact -width indent +.It Cm hdrcharset +The value is used as a character set name that will be +used when translating file names. +.El +.It Format mtree +.Bl -tag -compact -width indent +.It Cm checkfs +Allow reading information missing from the mtree from the file system. +Disabled by default. +.El +.It Format rar +.Bl -tag -compact -width indent +.It Cm hdrcharset +The value is used as a character set name that will be +used when translating file names. +.El +.It Format tar +.Bl -tag -compact -width indent +.It Cm compat-2x +Libarchive 2.x incorrectly encoded Unicode filenames on +some platforms. +This option mimics the libarchive 2.x filename handling +so that such archives can be read correctly. +.It Cm hdrcharset +The value is used as a character set name that will be +used when translating file names. +.It Cm mac-ext +Support Mac OS metadata extension that records data in special +files beginning with a period and underscore. +Defaults to enabled on Mac OS, disabled on other platforms. +Use +.Cm !mac-ext +to disable. +.It Cm read_concatenated_archives +Ignore zeroed blocks in the archive, which occurs when multiple tar archives +have been concatenated together. +Without this option, only the contents of +the first concatenated archive would be read. +.El +.El +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_read 3 , +.Xr archive_write_set_options 3 , +.Xr libarchive 3 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_set_options.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_set_options.c new file mode 100644 index 0000000000..2e2eea6905 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_set_options.c @@ -0,0 +1,155 @@ +/*- + * Copyright (c) 2011 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#include "archive_read_private.h" +#include "archive_options_private.h" + +static int archive_set_format_option(struct archive *a, + const char *m, const char *o, const char *v); +static int archive_set_filter_option(struct archive *a, + const char *m, const char *o, const char *v); +static int archive_set_option(struct archive *a, + const char *m, const char *o, const char *v); + +int +archive_read_set_format_option(struct archive *a, const char *m, const char *o, + const char *v) +{ + return _archive_set_option(a, m, o, v, + ARCHIVE_READ_MAGIC, "archive_read_set_format_option", + archive_set_format_option); +} + +int +archive_read_set_filter_option(struct archive *a, const char *m, const char *o, + const char *v) +{ + return _archive_set_option(a, m, o, v, + ARCHIVE_READ_MAGIC, "archive_read_set_filter_option", + archive_set_filter_option); +} + +int +archive_read_set_option(struct archive *a, const char *m, const char *o, + const char *v) +{ + return _archive_set_option(a, m, o, v, + ARCHIVE_READ_MAGIC, "archive_read_set_option", + archive_set_option); +} + +int +archive_read_set_options(struct archive *a, const char *options) +{ + return _archive_set_options(a, options, + ARCHIVE_READ_MAGIC, "archive_read_set_options", + archive_set_option); +} + +static int +archive_set_format_option(struct archive *_a, const char *m, const char *o, + const char *v) +{ + struct archive_read *a = (struct archive_read *)_a; + size_t i; + int r, rv = ARCHIVE_WARN, matched_modules = 0; + + for (i = 0; i < sizeof(a->formats)/sizeof(a->formats[0]); i++) { + struct archive_format_descriptor *format = &a->formats[i]; + + if (format->options == NULL || format->name == NULL) + /* This format does not support option. */ + continue; + if (m != NULL) { + if (strcmp(format->name, m) != 0) + continue; + ++matched_modules; + } + + a->format = format; + r = format->options(a, o, v); + a->format = NULL; + + if (r == ARCHIVE_FATAL) + return (ARCHIVE_FATAL); + + if (r == ARCHIVE_OK) + rv = ARCHIVE_OK; + } + /* If the format name didn't match, return a special code for + * _archive_set_option[s]. */ + if (m != NULL && matched_modules == 0) + return ARCHIVE_WARN - 1; + return (rv); +} + +static int +archive_set_filter_option(struct archive *_a, const char *m, const char *o, + const char *v) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter *filter; + struct archive_read_filter_bidder *bidder; + int r, rv = ARCHIVE_WARN, matched_modules = 0; + + for (filter = a->filter; filter != NULL; filter = filter->upstream) { + bidder = filter->bidder; + if (bidder == NULL) + continue; + if (bidder->options == NULL) + /* This bidder does not support option */ + continue; + if (m != NULL) { + if (strcmp(filter->name, m) != 0) + continue; + ++matched_modules; + } + + r = bidder->options(bidder, o, v); + + if (r == ARCHIVE_FATAL) + return (ARCHIVE_FATAL); + + if (r == ARCHIVE_OK) + rv = ARCHIVE_OK; + } + /* If the filter name didn't match, return a special code for + * _archive_set_option[s]. */ + if (m != NULL && matched_modules == 0) + return ARCHIVE_WARN - 1; + return (rv); +} + +static int +archive_set_option(struct archive *a, const char *m, const char *o, + const char *v) +{ + return _archive_set_either_option(a, m, o, v, + archive_set_format_option, + archive_set_filter_option); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_all.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_all.c new file mode 100644 index 0000000000..edb508c1df --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_all.c @@ -0,0 +1,85 @@ +/*- + * Copyright (c) 2003-2011 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#include "archive.h" +#include "archive_private.h" + +#if ARCHIVE_VERSION_NUMBER < 4000000 +/* Deprecated; remove in libarchive 4.0 */ +int +archive_read_support_compression_all(struct archive *a) +{ + return archive_read_support_filter_all(a); +} +#endif + +int +archive_read_support_filter_all(struct archive *a) +{ + archive_check_magic(a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_all"); + + /* Bzip falls back to "bunzip2" command-line */ + archive_read_support_filter_bzip2(a); + /* The decompress code doesn't use an outside library. */ + archive_read_support_filter_compress(a); + /* Gzip decompress falls back to "gzip -d" command-line. */ + archive_read_support_filter_gzip(a); + /* Lzip falls back to "unlzip" command-line program. */ + archive_read_support_filter_lzip(a); + /* The LZMA file format has a very weak signature, so it + * may not be feasible to keep this here, but we'll try. + * This will come back out if there are problems. */ + /* Lzma falls back to "unlzma" command-line program. */ + archive_read_support_filter_lzma(a); + /* Xz falls back to "unxz" command-line program. */ + archive_read_support_filter_xz(a); + /* The decode code doesn't use an outside library. */ + archive_read_support_filter_uu(a); + /* The decode code doesn't use an outside library. */ + archive_read_support_filter_rpm(a); + /* The decode code always uses "lrzip -q -d" command-line. */ + archive_read_support_filter_lrzip(a); + /* Lzop decompress falls back to "lzop -d" command-line. */ + archive_read_support_filter_lzop(a); + /* The decode code always uses "grzip -d" command-line. */ + archive_read_support_filter_grzip(a); + /* Lz4 falls back to "lz4 -d" command-line program. */ + archive_read_support_filter_lz4(a); + /* Zstd falls back to "zstd -d" command-line program. */ + archive_read_support_filter_zstd(a); + + /* Note: We always return ARCHIVE_OK here, even if some of the + * above return ARCHIVE_WARN. The intent here is to enable + * "as much as possible." Clients who need specific + * compression should enable those individually so they can + * verify the level of support. */ + /* Clear any warning messages set by the above functions. */ + archive_clear_error(a); + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_bzip2.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_bzip2.c new file mode 100644 index 0000000000..3885a7cf61 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_bzip2.c @@ -0,0 +1,371 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_BZLIB_H +#include <bzlib.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_read_private.h" + +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) +struct private_data { + bz_stream stream; + char *out_block; + size_t out_block_size; + char valid; /* True = decompressor is initialized */ + char eof; /* True = found end of compressed data. */ +}; + +/* Bzip2 filter */ +static ssize_t bzip2_filter_read(struct archive_read_filter *, const void **); +static int bzip2_filter_close(struct archive_read_filter *); +#endif + +/* + * Note that we can detect bzip2 archives even if we can't decompress + * them. (In fact, we like detecting them because we can give better + * error messages.) So the bid framework here gets compiled even + * if bzlib is unavailable. + */ +static int bzip2_reader_bid(struct archive_read_filter_bidder *, struct archive_read_filter *); +static int bzip2_reader_init(struct archive_read_filter *); +static int bzip2_reader_free(struct archive_read_filter_bidder *); + +#if ARCHIVE_VERSION_NUMBER < 4000000 +/* Deprecated; remove in libarchive 4.0 */ +int +archive_read_support_compression_bzip2(struct archive *a) +{ + return archive_read_support_filter_bzip2(a); +} +#endif + +int +archive_read_support_filter_bzip2(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter_bidder *reader; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_bzip2"); + + if (__archive_read_get_bidder(a, &reader) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + reader->data = NULL; + reader->name = "bzip2"; + reader->bid = bzip2_reader_bid; + reader->init = bzip2_reader_init; + reader->options = NULL; + reader->free = bzip2_reader_free; +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) + return (ARCHIVE_OK); +#else + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "Using external bzip2 program"); + return (ARCHIVE_WARN); +#endif +} + +static int +bzip2_reader_free(struct archive_read_filter_bidder *self){ + (void)self; /* UNUSED */ + return (ARCHIVE_OK); +} + +/* + * Test whether we can handle this data. + * + * This logic returns zero if any part of the signature fails. It + * also tries to Do The Right Thing if a very short buffer prevents us + * from verifying as much as we would like. + */ +static int +bzip2_reader_bid(struct archive_read_filter_bidder *self, struct archive_read_filter *filter) +{ + const unsigned char *buffer; + ssize_t avail; + int bits_checked; + + (void)self; /* UNUSED */ + + /* Minimal bzip2 archive is 14 bytes. */ + buffer = __archive_read_filter_ahead(filter, 14, &avail); + if (buffer == NULL) + return (0); + + /* First three bytes must be "BZh" */ + bits_checked = 0; + if (memcmp(buffer, "BZh", 3) != 0) + return (0); + bits_checked += 24; + + /* Next follows a compression flag which must be an ASCII digit. */ + if (buffer[3] < '1' || buffer[3] > '9') + return (0); + bits_checked += 5; + + /* After BZh[1-9], there must be either a data block + * which begins with 0x314159265359 or an end-of-data + * marker of 0x177245385090. */ + if (memcmp(buffer + 4, "\x31\x41\x59\x26\x53\x59", 6) == 0) + bits_checked += 48; + else if (memcmp(buffer + 4, "\x17\x72\x45\x38\x50\x90", 6) == 0) + bits_checked += 48; + else + return (0); + + return (bits_checked); +} + +#if !defined(HAVE_BZLIB_H) || !defined(BZ_CONFIG_ERROR) + +/* + * If we don't have the library on this system, we can't actually do the + * decompression. We can, however, still detect compressed archives + * and emit a useful message. + */ +static int +bzip2_reader_init(struct archive_read_filter *self) +{ + int r; + + r = __archive_read_program(self, "bzip2 -d"); + /* Note: We set the format here even if __archive_read_program() + * above fails. We do, after all, know what the format is + * even if we weren't able to read it. */ + self->code = ARCHIVE_FILTER_BZIP2; + self->name = "bzip2"; + return (r); +} + + +#else + +/* + * Setup the callbacks. + */ +static int +bzip2_reader_init(struct archive_read_filter *self) +{ + static const size_t out_block_size = 64 * 1024; + void *out_block; + struct private_data *state; + + self->code = ARCHIVE_FILTER_BZIP2; + self->name = "bzip2"; + + state = (struct private_data *)calloc(sizeof(*state), 1); + out_block = (unsigned char *)malloc(out_block_size); + if (state == NULL || out_block == NULL) { + archive_set_error(&self->archive->archive, ENOMEM, + "Can't allocate data for bzip2 decompression"); + free(out_block); + free(state); + return (ARCHIVE_FATAL); + } + + self->data = state; + state->out_block_size = out_block_size; + state->out_block = out_block; + self->read = bzip2_filter_read; + self->skip = NULL; /* not supported */ + self->close = bzip2_filter_close; + + return (ARCHIVE_OK); +} + +/* + * Return the next block of decompressed data. + */ +static ssize_t +bzip2_filter_read(struct archive_read_filter *self, const void **p) +{ + struct private_data *state; + size_t decompressed; + const char *read_buf; + ssize_t ret; + + state = (struct private_data *)self->data; + + if (state->eof) { + *p = NULL; + return (0); + } + + /* Empty our output buffer. */ + state->stream.next_out = state->out_block; + state->stream.avail_out = state->out_block_size; + + /* Try to fill the output buffer. */ + for (;;) { + if (!state->valid) { + if (bzip2_reader_bid(self->bidder, self->upstream) == 0) { + state->eof = 1; + *p = state->out_block; + decompressed = state->stream.next_out + - state->out_block; + return (decompressed); + } + /* Initialize compression library. */ + ret = BZ2_bzDecompressInit(&(state->stream), + 0 /* library verbosity */, + 0 /* don't use low-mem algorithm */); + + /* If init fails, try low-memory algorithm instead. */ + if (ret == BZ_MEM_ERROR) + ret = BZ2_bzDecompressInit(&(state->stream), + 0 /* library verbosity */, + 1 /* do use low-mem algo */); + + if (ret != BZ_OK) { + const char *detail = NULL; + int err = ARCHIVE_ERRNO_MISC; + switch (ret) { + case BZ_PARAM_ERROR: + detail = "invalid setup parameter"; + break; + case BZ_MEM_ERROR: + err = ENOMEM; + detail = "out of memory"; + break; + case BZ_CONFIG_ERROR: + detail = "mis-compiled library"; + break; + } + archive_set_error(&self->archive->archive, err, + "Internal error initializing decompressor%s%s", + detail == NULL ? "" : ": ", + detail); + return (ARCHIVE_FATAL); + } + state->valid = 1; + } + + /* stream.next_in is really const, but bzlib + * doesn't declare it so. <sigh> */ + read_buf = + __archive_read_filter_ahead(self->upstream, 1, &ret); + if (read_buf == NULL) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "truncated bzip2 input"); + return (ARCHIVE_FATAL); + } + state->stream.next_in = (char *)(uintptr_t)read_buf; + state->stream.avail_in = ret; + /* There is no more data, return whatever we have. */ + if (ret == 0) { + state->eof = 1; + *p = state->out_block; + decompressed = state->stream.next_out + - state->out_block; + return (decompressed); + } + + /* Decompress as much as we can in one pass. */ + ret = BZ2_bzDecompress(&(state->stream)); + __archive_read_filter_consume(self->upstream, + state->stream.next_in - read_buf); + + switch (ret) { + case BZ_STREAM_END: /* Found end of stream. */ + switch (BZ2_bzDecompressEnd(&(state->stream))) { + case BZ_OK: + break; + default: + archive_set_error(&(self->archive->archive), + ARCHIVE_ERRNO_MISC, + "Failed to clean up decompressor"); + return (ARCHIVE_FATAL); + } + state->valid = 0; + /* FALLTHROUGH */ + case BZ_OK: /* Decompressor made some progress. */ + /* If we filled our buffer, update stats and return. */ + if (state->stream.avail_out == 0) { + *p = state->out_block; + decompressed = state->stream.next_out + - state->out_block; + return (decompressed); + } + break; + default: /* Return an error. */ + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, "bzip decompression failed"); + return (ARCHIVE_FATAL); + } + } +} + +/* + * Clean up the decompressor. + */ +static int +bzip2_filter_close(struct archive_read_filter *self) +{ + struct private_data *state; + int ret = ARCHIVE_OK; + + state = (struct private_data *)self->data; + + if (state->valid) { + switch (BZ2_bzDecompressEnd(&state->stream)) { + case BZ_OK: + break; + default: + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Failed to clean up decompressor"); + ret = ARCHIVE_FATAL; + } + state->valid = 0; + } + + free(state->out_block); + free(state); + return (ret); +} + +#endif /* HAVE_BZLIB_H && BZ_CONFIG_ERROR */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_compress.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_compress.c new file mode 100644 index 0000000000..e05132dbfa --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_compress.c @@ -0,0 +1,465 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +/* + * This code borrows heavily from "compress" source code, which is + * protected by the following copyright. (Clause 3 dropped by request + * of the Regents.) + */ + +/*- + * Copyright (c) 1985, 1986, 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Diomidis Spinellis and James A. Woods, derived from original + * work by Spencer Thomas and Joseph Orost. + * + * 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. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. + */ + + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_read_private.h" + +/* + * Because LZW decompression is pretty simple, I've just implemented + * the whole decompressor here (cribbing from "compress" source code, + * of course), rather than relying on an external library. I have + * made an effort to clarify and simplify the algorithm, so the + * names and structure here don't exactly match those used by compress. + */ + +struct private_data { + /* Input variables. */ + const unsigned char *next_in; + size_t avail_in; + size_t consume_unnotified; + int bit_buffer; + int bits_avail; + size_t bytes_in_section; + + /* Output variables. */ + size_t out_block_size; + void *out_block; + + /* Decompression status variables. */ + int use_reset_code; + int end_of_stream; /* EOF status. */ + int maxcode; /* Largest code. */ + int maxcode_bits; /* Length of largest code. */ + int section_end_code; /* When to increase bits. */ + int bits; /* Current code length. */ + int oldcode; /* Previous code. */ + int finbyte; /* Last byte of prev code. */ + + /* Dictionary. */ + int free_ent; /* Next dictionary entry. */ + unsigned char suffix[65536]; + uint16_t prefix[65536]; + + /* + * Scratch area for expanding dictionary entries. Note: + * "worst" case here comes from compressing /dev/zero: the + * last code in the dictionary will code a sequence of + * 65536-256 zero bytes. Thus, we need stack space to expand + * a 65280-byte dictionary entry. (Of course, 32640:1 + * compression could also be considered the "best" case. ;-) + */ + unsigned char *stackp; + unsigned char stack[65300]; +}; + +static int compress_bidder_bid(struct archive_read_filter_bidder *, struct archive_read_filter *); +static int compress_bidder_init(struct archive_read_filter *); +static int compress_bidder_free(struct archive_read_filter_bidder *); + +static ssize_t compress_filter_read(struct archive_read_filter *, const void **); +static int compress_filter_close(struct archive_read_filter *); + +static int getbits(struct archive_read_filter *, int n); +static int next_code(struct archive_read_filter *); + +#if ARCHIVE_VERSION_NUMBER < 4000000 +/* Deprecated; remove in libarchive 4.0 */ +int +archive_read_support_compression_compress(struct archive *a) +{ + return archive_read_support_filter_compress(a); +} +#endif + +int +archive_read_support_filter_compress(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter_bidder *bidder; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_compress"); + + if (__archive_read_get_bidder(a, &bidder) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + bidder->data = NULL; + bidder->name = "compress (.Z)"; + bidder->bid = compress_bidder_bid; + bidder->init = compress_bidder_init; + bidder->options = NULL; + bidder->free = compress_bidder_free; + return (ARCHIVE_OK); +} + +/* + * Test whether we can handle this data. + * This logic returns zero if any part of the signature fails. + */ +static int +compress_bidder_bid(struct archive_read_filter_bidder *self, + struct archive_read_filter *filter) +{ + const unsigned char *buffer; + ssize_t avail; + int bits_checked; + + (void)self; /* UNUSED */ + + /* Shortest valid compress file is 3 bytes. */ + buffer = __archive_read_filter_ahead(filter, 3, &avail); + + if (buffer == NULL) + return (0); + + bits_checked = 0; + /* First two bytes are the magic value */ + if (buffer[0] != 0x1F || buffer[1] != 0x9D) + return (0); + /* Third byte holds compression parameters. */ + if (buffer[2] & 0x20) /* Reserved bit, must be zero. */ + return (0); + if (buffer[2] & 0x40) /* Reserved bit, must be zero. */ + return (0); + bits_checked += 18; + + return (bits_checked); +} + +/* + * Setup the callbacks. + */ +static int +compress_bidder_init(struct archive_read_filter *self) +{ + struct private_data *state; + static const size_t out_block_size = 64 * 1024; + void *out_block; + int code; + + self->code = ARCHIVE_FILTER_COMPRESS; + self->name = "compress (.Z)"; + + state = (struct private_data *)calloc(sizeof(*state), 1); + out_block = malloc(out_block_size); + if (state == NULL || out_block == NULL) { + free(out_block); + free(state); + archive_set_error(&self->archive->archive, ENOMEM, + "Can't allocate data for %s decompression", + self->name); + return (ARCHIVE_FATAL); + } + + self->data = state; + state->out_block_size = out_block_size; + state->out_block = out_block; + self->read = compress_filter_read; + self->skip = NULL; /* not supported */ + self->close = compress_filter_close; + + /* XXX MOVE THE FOLLOWING OUT OF INIT() XXX */ + + (void)getbits(self, 8); /* Skip first signature byte. */ + (void)getbits(self, 8); /* Skip second signature byte. */ + + /* Get compression parameters. */ + code = getbits(self, 8); + if ((code & 0x1f) > 16) { + archive_set_error(&self->archive->archive, -1, + "Invalid compressed data"); + return (ARCHIVE_FATAL); + } + state->maxcode_bits = code & 0x1f; + state->maxcode = (1 << state->maxcode_bits); + state->use_reset_code = code & 0x80; + + /* Initialize decompressor. */ + state->free_ent = 256; + state->stackp = state->stack; + if (state->use_reset_code) + state->free_ent++; + state->bits = 9; + state->section_end_code = (1<<state->bits) - 1; + state->oldcode = -1; + for (code = 255; code >= 0; code--) { + state->prefix[code] = 0; + state->suffix[code] = code; + } + next_code(self); + + return (ARCHIVE_OK); +} + +/* + * Return a block of data from the decompression buffer. Decompress more + * as necessary. + */ +static ssize_t +compress_filter_read(struct archive_read_filter *self, const void **pblock) +{ + struct private_data *state; + unsigned char *p, *start, *end; + int ret; + + state = (struct private_data *)self->data; + if (state->end_of_stream) { + *pblock = NULL; + return (0); + } + p = start = (unsigned char *)state->out_block; + end = start + state->out_block_size; + + while (p < end && !state->end_of_stream) { + if (state->stackp > state->stack) { + *p++ = *--state->stackp; + } else { + ret = next_code(self); + if (ret == -1) + state->end_of_stream = ret; + else if (ret != ARCHIVE_OK) + return (ret); + } + } + + *pblock = start; + return (p - start); +} + +/* + * Clean up the reader. + */ +static int +compress_bidder_free(struct archive_read_filter_bidder *self) +{ + self->data = NULL; + return (ARCHIVE_OK); +} + +/* + * Close and release the filter. + */ +static int +compress_filter_close(struct archive_read_filter *self) +{ + struct private_data *state = (struct private_data *)self->data; + + free(state->out_block); + free(state); + return (ARCHIVE_OK); +} + +/* + * Process the next code and fill the stack with the expansion + * of the code. Returns ARCHIVE_FATAL if there is a fatal I/O or + * format error, ARCHIVE_EOF if we hit end of data, ARCHIVE_OK otherwise. + */ +static int +next_code(struct archive_read_filter *self) +{ + struct private_data *state = (struct private_data *)self->data; + int code, newcode; + + static int debug_buff[1024]; + static unsigned debug_index; + + code = newcode = getbits(self, state->bits); + if (code < 0) + return (code); + + debug_buff[debug_index++] = code; + if (debug_index >= sizeof(debug_buff)/sizeof(debug_buff[0])) + debug_index = 0; + + /* If it's a reset code, reset the dictionary. */ + if ((code == 256) && state->use_reset_code) { + /* + * The original 'compress' implementation blocked its + * I/O in a manner that resulted in junk bytes being + * inserted after every reset. The next section skips + * this junk. (Yes, the number of *bytes* to skip is + * a function of the current *bit* length.) + */ + int skip_bytes = state->bits - + (state->bytes_in_section % state->bits); + skip_bytes %= state->bits; + state->bits_avail = 0; /* Discard rest of this byte. */ + while (skip_bytes-- > 0) { + code = getbits(self, 8); + if (code < 0) + return (code); + } + /* Now, actually do the reset. */ + state->bytes_in_section = 0; + state->bits = 9; + state->section_end_code = (1 << state->bits) - 1; + state->free_ent = 257; + state->oldcode = -1; + return (next_code(self)); + } + + if (code > state->free_ent + || (code == state->free_ent && state->oldcode < 0)) { + /* An invalid code is a fatal error. */ + archive_set_error(&(self->archive->archive), -1, + "Invalid compressed data"); + return (ARCHIVE_FATAL); + } + + /* Special case for KwKwK string. */ + if (code >= state->free_ent) { + *state->stackp++ = state->finbyte; + code = state->oldcode; + } + + /* Generate output characters in reverse order. */ + while (code >= 256) { + *state->stackp++ = state->suffix[code]; + code = state->prefix[code]; + } + *state->stackp++ = state->finbyte = code; + + /* Generate the new entry. */ + code = state->free_ent; + if (code < state->maxcode && state->oldcode >= 0) { + state->prefix[code] = state->oldcode; + state->suffix[code] = state->finbyte; + ++state->free_ent; + } + if (state->free_ent > state->section_end_code) { + state->bits++; + state->bytes_in_section = 0; + if (state->bits == state->maxcode_bits) + state->section_end_code = state->maxcode; + else + state->section_end_code = (1 << state->bits) - 1; + } + + /* Remember previous code. */ + state->oldcode = newcode; + return (ARCHIVE_OK); +} + +/* + * Return next 'n' bits from stream. + * + * -1 indicates end of available data. + */ +static int +getbits(struct archive_read_filter *self, int n) +{ + struct private_data *state = (struct private_data *)self->data; + int code; + ssize_t ret; + static const int mask[] = { + 0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff, + 0x1ff, 0x3ff, 0x7ff, 0xfff, 0x1fff, 0x3fff, 0x7fff, 0xffff + }; + + while (state->bits_avail < n) { + if (state->avail_in <= 0) { + if (state->consume_unnotified) { + __archive_read_filter_consume(self->upstream, + state->consume_unnotified); + state->consume_unnotified = 0; + } + state->next_in + = __archive_read_filter_ahead(self->upstream, + 1, &ret); + if (ret == 0) + return (-1); + if (ret < 0 || state->next_in == NULL) + return (ARCHIVE_FATAL); + state->consume_unnotified = state->avail_in = ret; + } + state->bit_buffer |= *state->next_in++ << state->bits_avail; + state->avail_in--; + state->bits_avail += 8; + state->bytes_in_section++; + } + + code = state->bit_buffer; + state->bit_buffer >>= n; + state->bits_avail -= n; + + return (code & mask[n]); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_grzip.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_grzip.c new file mode 100644 index 0000000000..84c86aeb43 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_grzip.c @@ -0,0 +1,121 @@ +/*- + * Copyright (c) 2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_read_private.h" + +static const unsigned char grzip_magic[] = { + 0x47, 0x52, 0x5a, 0x69, 0x70, 0x49, 0x49, 0x00, + 0x02, 0x04, 0x3a, 0x29 }; + +static int grzip_bidder_bid(struct archive_read_filter_bidder *, + struct archive_read_filter *); +static int grzip_bidder_init(struct archive_read_filter *); + + +static int +grzip_reader_free(struct archive_read_filter_bidder *self) +{ + (void)self; /* UNUSED */ + return (ARCHIVE_OK); +} + +int +archive_read_support_filter_grzip(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter_bidder *reader; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_grzip"); + + if (__archive_read_get_bidder(a, &reader) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + reader->data = NULL; + reader->bid = grzip_bidder_bid; + reader->init = grzip_bidder_init; + reader->options = NULL; + reader->free = grzip_reader_free; + /* This filter always uses an external program. */ + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "Using external grzip program for grzip decompression"); + return (ARCHIVE_WARN); +} + +/* + * Bidder just verifies the header and returns the number of verified bits. + */ +static int +grzip_bidder_bid(struct archive_read_filter_bidder *self, + struct archive_read_filter *filter) +{ + const unsigned char *p; + ssize_t avail; + + (void)self; /* UNUSED */ + + p = __archive_read_filter_ahead(filter, sizeof(grzip_magic), &avail); + if (p == NULL || avail == 0) + return (0); + + if (memcmp(p, grzip_magic, sizeof(grzip_magic))) + return (0); + + return (sizeof(grzip_magic) * 8); +} + +static int +grzip_bidder_init(struct archive_read_filter *self) +{ + int r; + + r = __archive_read_program(self, "grzip -d"); + /* Note: We set the format here even if __archive_read_program() + * above fails. We do, after all, know what the format is + * even if we weren't able to read it. */ + self->code = ARCHIVE_FILTER_GRZIP; + self->name = "grzip"; + return (r); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_gzip.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_gzip.c new file mode 100644 index 0000000000..9fa9e2b0dd --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_gzip.c @@ -0,0 +1,535 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_ZLIB_H +#include <zlib.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_endian.h" +#include "archive_private.h" +#include "archive_read_private.h" + +#ifdef HAVE_ZLIB_H +struct private_data { + z_stream stream; + char in_stream; + unsigned char *out_block; + size_t out_block_size; + int64_t total_out; + unsigned long crc; + uint32_t mtime; + char *name; + char eof; /* True = found end of compressed data. */ +}; + +/* Gzip Filter. */ +static ssize_t gzip_filter_read(struct archive_read_filter *, const void **); +static int gzip_filter_close(struct archive_read_filter *); +#endif + +/* + * Note that we can detect gzip archives even if we can't decompress + * them. (In fact, we like detecting them because we can give better + * error messages.) So the bid framework here gets compiled even + * if zlib is unavailable. + * + * TODO: If zlib is unavailable, gzip_bidder_init() should + * use the compress_program framework to try to fire up an external + * gzip program. + */ +static int gzip_bidder_bid(struct archive_read_filter_bidder *, + struct archive_read_filter *); +static int gzip_bidder_init(struct archive_read_filter *); + +#if ARCHIVE_VERSION_NUMBER < 4000000 +/* Deprecated; remove in libarchive 4.0 */ +int +archive_read_support_compression_gzip(struct archive *a) +{ + return archive_read_support_filter_gzip(a); +} +#endif + +int +archive_read_support_filter_gzip(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter_bidder *bidder; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_gzip"); + + if (__archive_read_get_bidder(a, &bidder) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + bidder->data = NULL; + bidder->name = "gzip"; + bidder->bid = gzip_bidder_bid; + bidder->init = gzip_bidder_init; + bidder->options = NULL; + bidder->free = NULL; /* No data, so no cleanup necessary. */ + /* Signal the extent of gzip support with the return value here. */ +#if HAVE_ZLIB_H + return (ARCHIVE_OK); +#else + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "Using external gzip program"); + return (ARCHIVE_WARN); +#endif +} + +/* + * Read and verify the header. + * + * Returns zero if the header couldn't be validated, else returns + * number of bytes in header. If pbits is non-NULL, it receives a + * count of bits verified, suitable for use by bidder. + */ +static ssize_t +peek_at_header(struct archive_read_filter *filter, int *pbits, +#ifdef HAVE_ZLIB_H + struct private_data *state +#else + void *state +#endif + ) +{ + const unsigned char *p; + ssize_t avail, len; + int bits = 0; + int header_flags; +#ifndef HAVE_ZLIB_H + (void)state; /* UNUSED */ +#endif + + /* Start by looking at the first ten bytes of the header, which + * is all fixed layout. */ + len = 10; + p = __archive_read_filter_ahead(filter, len, &avail); + if (p == NULL || avail == 0) + return (0); + /* We only support deflation- third byte must be 0x08. */ + if (memcmp(p, "\x1F\x8B\x08", 3) != 0) + return (0); + bits += 24; + if ((p[3] & 0xE0)!= 0) /* No reserved flags set. */ + return (0); + bits += 3; + header_flags = p[3]; + /* Bytes 4-7 are mod time in little endian. */ +#ifdef HAVE_ZLIB_H + if (state) + state->mtime = archive_le32dec(p + 4); +#endif + /* Byte 8 is deflate flags. */ + /* XXXX TODO: return deflate flags back to consume_header for use + in initializing the decompressor. */ + /* Byte 9 is OS. */ + + /* Optional extra data: 2 byte length plus variable body. */ + if (header_flags & 4) { + p = __archive_read_filter_ahead(filter, len + 2, &avail); + if (p == NULL) + return (0); + len += ((int)p[len + 1] << 8) | (int)p[len]; + len += 2; + } + + /* Null-terminated optional filename. */ + if (header_flags & 8) { +#ifdef HAVE_ZLIB_H + ssize_t file_start = len; +#endif + do { + ++len; + if (avail < len) + p = __archive_read_filter_ahead(filter, + len, &avail); + if (p == NULL) + return (0); + } while (p[len - 1] != 0); + +#ifdef HAVE_ZLIB_H + if (state) { + /* Reset the name in case of repeat header reads. */ + free(state->name); + state->name = strdup((const char *)&p[file_start]); + } +#endif + } + + /* Null-terminated optional comment. */ + if (header_flags & 16) { + do { + ++len; + if (avail < len) + p = __archive_read_filter_ahead(filter, + len, &avail); + if (p == NULL) + return (0); + } while (p[len - 1] != 0); + } + + /* Optional header CRC */ + if ((header_flags & 2)) { + p = __archive_read_filter_ahead(filter, len + 2, &avail); + if (p == NULL) + return (0); +#if 0 + int hcrc = ((int)p[len + 1] << 8) | (int)p[len]; + int crc = /* XXX TODO: Compute header CRC. */; + if (crc != hcrc) + return (0); + bits += 16; +#endif + len += 2; + } + + if (pbits != NULL) + *pbits = bits; + return (len); +} + +/* + * Bidder just verifies the header and returns the number of verified bits. + */ +static int +gzip_bidder_bid(struct archive_read_filter_bidder *self, + struct archive_read_filter *filter) +{ + int bits_checked; + + (void)self; /* UNUSED */ + + if (peek_at_header(filter, &bits_checked, NULL)) + return (bits_checked); + return (0); +} + +#ifndef HAVE_ZLIB_H + +/* + * If we don't have the library on this system, we can't do the + * decompression directly. We can, however, try to run "gzip -d" + * in case that's available. + */ +static int +gzip_bidder_init(struct archive_read_filter *self) +{ + int r; + + r = __archive_read_program(self, "gzip -d"); + /* Note: We set the format here even if __archive_read_program() + * above fails. We do, after all, know what the format is + * even if we weren't able to read it. */ + self->code = ARCHIVE_FILTER_GZIP; + self->name = "gzip"; + return (r); +} + +#else + +static int +gzip_read_header(struct archive_read_filter *self, struct archive_entry *entry) +{ + struct private_data *state; + + state = (struct private_data *)self->data; + + /* A mtime of 0 is considered invalid/missing. */ + if (state->mtime != 0) + archive_entry_set_mtime(entry, state->mtime, 0); + + /* If the name is available, extract it. */ + if (state->name) + archive_entry_set_pathname(entry, state->name); + + return (ARCHIVE_OK); +} + +/* + * Initialize the filter object. + */ +static int +gzip_bidder_init(struct archive_read_filter *self) +{ + struct private_data *state; + static const size_t out_block_size = 64 * 1024; + void *out_block; + + self->code = ARCHIVE_FILTER_GZIP; + self->name = "gzip"; + + state = (struct private_data *)calloc(sizeof(*state), 1); + out_block = (unsigned char *)malloc(out_block_size); + if (state == NULL || out_block == NULL) { + free(out_block); + free(state); + archive_set_error(&self->archive->archive, ENOMEM, + "Can't allocate data for gzip decompression"); + return (ARCHIVE_FATAL); + } + + self->data = state; + state->out_block_size = out_block_size; + state->out_block = out_block; + self->read = gzip_filter_read; + self->skip = NULL; /* not supported */ + self->close = gzip_filter_close; +#ifdef HAVE_ZLIB_H + self->read_header = gzip_read_header; +#endif + + state->in_stream = 0; /* We're not actually within a stream yet. */ + + return (ARCHIVE_OK); +} + +static int +consume_header(struct archive_read_filter *self) +{ + struct private_data *state; + ssize_t avail; + size_t len; + int ret; + + state = (struct private_data *)self->data; + + /* If this is a real header, consume it. */ + len = peek_at_header(self->upstream, NULL, state); + if (len == 0) + return (ARCHIVE_EOF); + __archive_read_filter_consume(self->upstream, len); + + /* Initialize CRC accumulator. */ + state->crc = crc32(0L, NULL, 0); + + /* Initialize compression library. */ + state->stream.next_in = (unsigned char *)(uintptr_t) + __archive_read_filter_ahead(self->upstream, 1, &avail); + state->stream.avail_in = (uInt)avail; + ret = inflateInit2(&(state->stream), + -15 /* Don't check for zlib header */); + + /* Decipher the error code. */ + switch (ret) { + case Z_OK: + state->in_stream = 1; + return (ARCHIVE_OK); + case Z_STREAM_ERROR: + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library: " + "invalid setup parameter"); + break; + case Z_MEM_ERROR: + archive_set_error(&self->archive->archive, ENOMEM, + "Internal error initializing compression library: " + "out of memory"); + break; + case Z_VERSION_ERROR: + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library: " + "invalid library version"); + break; + default: + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library: " + " Zlib error %d", ret); + break; + } + return (ARCHIVE_FATAL); +} + +static int +consume_trailer(struct archive_read_filter *self) +{ + struct private_data *state; + const unsigned char *p; + ssize_t avail; + + state = (struct private_data *)self->data; + + state->in_stream = 0; + switch (inflateEnd(&(state->stream))) { + case Z_OK: + break; + default: + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Failed to clean up gzip decompressor"); + return (ARCHIVE_FATAL); + } + + /* GZip trailer is a fixed 8 byte structure. */ + p = __archive_read_filter_ahead(self->upstream, 8, &avail); + if (p == NULL || avail == 0) + return (ARCHIVE_FATAL); + + /* XXX TODO: Verify the length and CRC. */ + + /* We've verified the trailer, so consume it now. */ + __archive_read_filter_consume(self->upstream, 8); + + return (ARCHIVE_OK); +} + +static ssize_t +gzip_filter_read(struct archive_read_filter *self, const void **p) +{ + struct private_data *state; + size_t decompressed; + ssize_t avail_in, max_in; + int ret; + + state = (struct private_data *)self->data; + + /* Empty our output buffer. */ + state->stream.next_out = state->out_block; + state->stream.avail_out = (uInt)state->out_block_size; + + /* Try to fill the output buffer. */ + while (state->stream.avail_out > 0 && !state->eof) { + /* If we're not in a stream, read a header + * and initialize the decompression library. */ + if (!state->in_stream) { + ret = consume_header(self); + if (ret == ARCHIVE_EOF) { + state->eof = 1; + break; + } + if (ret < ARCHIVE_OK) + return (ret); + } + + /* Peek at the next available data. */ + /* ZLib treats stream.next_in as const but doesn't declare + * it so, hence this ugly cast. */ + state->stream.next_in = (unsigned char *)(uintptr_t) + __archive_read_filter_ahead(self->upstream, 1, &avail_in); + if (state->stream.next_in == NULL) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "truncated gzip input"); + return (ARCHIVE_FATAL); + } + if (UINT_MAX >= SSIZE_MAX) + max_in = SSIZE_MAX; + else + max_in = UINT_MAX; + if (avail_in > max_in) + avail_in = max_in; + state->stream.avail_in = (uInt)avail_in; + + /* Decompress and consume some of that data. */ + ret = inflate(&(state->stream), 0); + switch (ret) { + case Z_OK: /* Decompressor made some progress. */ + __archive_read_filter_consume(self->upstream, + avail_in - state->stream.avail_in); + break; + case Z_STREAM_END: /* Found end of stream. */ + __archive_read_filter_consume(self->upstream, + avail_in - state->stream.avail_in); + /* Consume the stream trailer; release the + * decompression library. */ + ret = consume_trailer(self); + if (ret < ARCHIVE_OK) + return (ret); + break; + default: + /* Return an error. */ + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "gzip decompression failed"); + return (ARCHIVE_FATAL); + } + } + + /* We've read as much as we can. */ + decompressed = state->stream.next_out - state->out_block; + state->total_out += decompressed; + if (decompressed == 0) + *p = NULL; + else + *p = state->out_block; + return (decompressed); +} + +/* + * Clean up the decompressor. + */ +static int +gzip_filter_close(struct archive_read_filter *self) +{ + struct private_data *state; + int ret; + + state = (struct private_data *)self->data; + ret = ARCHIVE_OK; + + if (state->in_stream) { + switch (inflateEnd(&(state->stream))) { + case Z_OK: + break; + default: + archive_set_error(&(self->archive->archive), + ARCHIVE_ERRNO_MISC, + "Failed to clean up gzip compressor"); + ret = ARCHIVE_FATAL; + } + } + + free(state->name); + free(state->out_block); + free(state); + return (ret); +} + +#endif /* HAVE_ZLIB_H */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_lrzip.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_lrzip.c new file mode 100644 index 0000000000..c82a8e2f13 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_lrzip.c @@ -0,0 +1,132 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_read_private.h" + +#define LRZIP_HEADER_MAGIC "LRZI" +#define LRZIP_HEADER_MAGIC_LEN 4 + +static int lrzip_bidder_bid(struct archive_read_filter_bidder *, + struct archive_read_filter *); +static int lrzip_bidder_init(struct archive_read_filter *); + + +static int +lrzip_reader_free(struct archive_read_filter_bidder *self) +{ + (void)self; /* UNUSED */ + return (ARCHIVE_OK); +} + +int +archive_read_support_filter_lrzip(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter_bidder *reader; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_lrzip"); + + if (__archive_read_get_bidder(a, &reader) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + reader->data = NULL; + reader->name = "lrzip"; + reader->bid = lrzip_bidder_bid; + reader->init = lrzip_bidder_init; + reader->options = NULL; + reader->free = lrzip_reader_free; + /* This filter always uses an external program. */ + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "Using external lrzip program for lrzip decompression"); + return (ARCHIVE_WARN); +} + +/* + * Bidder just verifies the header and returns the number of verified bits. + */ +static int +lrzip_bidder_bid(struct archive_read_filter_bidder *self, + struct archive_read_filter *filter) +{ + const unsigned char *p; + ssize_t avail, len; + int i; + + (void)self; /* UNUSED */ + /* Start by looking at the first six bytes of the header, which + * is all fixed layout. */ + len = 6; + p = __archive_read_filter_ahead(filter, len, &avail); + if (p == NULL || avail == 0) + return (0); + + if (memcmp(p, LRZIP_HEADER_MAGIC, LRZIP_HEADER_MAGIC_LEN)) + return (0); + + /* current major version is always 0, verify this */ + if (p[LRZIP_HEADER_MAGIC_LEN]) + return 0; + /* support only v0.6+ lrzip for sanity */ + i = p[LRZIP_HEADER_MAGIC_LEN + 1]; + if ((i < 6) || (i > 10)) + return 0; + + return (int)len; +} + +static int +lrzip_bidder_init(struct archive_read_filter *self) +{ + int r; + + r = __archive_read_program(self, "lrzip -d -q"); + /* Note: We set the format here even if __archive_read_program() + * above fails. We do, after all, know what the format is + * even if we weren't able to read it. */ + self->code = ARCHIVE_FILTER_LRZIP; + self->name = "lrzip"; + return (r); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_lz4.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_lz4.c new file mode 100644 index 0000000000..43ee6c2b72 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_lz4.c @@ -0,0 +1,742 @@ +/*- + * Copyright (c) 2014 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_LZ4_H +#include <lz4.h> +#endif + +#include "archive.h" +#include "archive_endian.h" +#include "archive_private.h" +#include "archive_read_private.h" +#include "archive_xxhash.h" + +#define LZ4_MAGICNUMBER 0x184d2204 +#define LZ4_SKIPPABLED 0x184d2a50 +#define LZ4_LEGACY 0x184c2102 + +#if defined(HAVE_LIBLZ4) +struct private_data { + enum { SELECT_STREAM, + READ_DEFAULT_STREAM, + READ_DEFAULT_BLOCK, + READ_LEGACY_STREAM, + READ_LEGACY_BLOCK, + } stage; + struct { + unsigned block_independence:1; + unsigned block_checksum:3; + unsigned stream_size:1; + unsigned stream_checksum:1; + unsigned preset_dictionary:1; + int block_maximum_size; + } flags; + int64_t stream_size; + uint32_t dict_id; + char *out_block; + size_t out_block_size; + + /* Bytes read but not yet consumed via __archive_read_consume() */ + size_t unconsumed; + size_t decoded_size; + void *xxh32_state; + + char valid; /* True = decompressor is initialized */ + char eof; /* True = found end of compressed data. */ +}; + +#define LEGACY_BLOCK_SIZE (8 * 1024 * 1024) + +/* Lz4 filter */ +static ssize_t lz4_filter_read(struct archive_read_filter *, const void **); +static int lz4_filter_close(struct archive_read_filter *); +#endif + +/* + * Note that we can detect lz4 archives even if we can't decompress + * them. (In fact, we like detecting them because we can give better + * error messages.) So the bid framework here gets compiled even + * if liblz4 is unavailable. + */ +static int lz4_reader_bid(struct archive_read_filter_bidder *, struct archive_read_filter *); +static int lz4_reader_init(struct archive_read_filter *); +static int lz4_reader_free(struct archive_read_filter_bidder *); +#if defined(HAVE_LIBLZ4) +static ssize_t lz4_filter_read_default_stream(struct archive_read_filter *, + const void **); +static ssize_t lz4_filter_read_legacy_stream(struct archive_read_filter *, + const void **); +#endif + +int +archive_read_support_filter_lz4(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter_bidder *reader; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_lz4"); + + if (__archive_read_get_bidder(a, &reader) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + reader->data = NULL; + reader->name = "lz4"; + reader->bid = lz4_reader_bid; + reader->init = lz4_reader_init; + reader->options = NULL; + reader->free = lz4_reader_free; +#if defined(HAVE_LIBLZ4) + return (ARCHIVE_OK); +#else + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "Using external lz4 program"); + return (ARCHIVE_WARN); +#endif +} + +static int +lz4_reader_free(struct archive_read_filter_bidder *self){ + (void)self; /* UNUSED */ + return (ARCHIVE_OK); +} + +/* + * Test whether we can handle this data. + * + * This logic returns zero if any part of the signature fails. It + * also tries to Do The Right Thing if a very short buffer prevents us + * from verifying as much as we would like. + */ +static int +lz4_reader_bid(struct archive_read_filter_bidder *self, + struct archive_read_filter *filter) +{ + const unsigned char *buffer; + ssize_t avail; + int bits_checked; + uint32_t number; + + (void)self; /* UNUSED */ + + /* Minimal lz4 archive is 11 bytes. */ + buffer = __archive_read_filter_ahead(filter, 11, &avail); + if (buffer == NULL) + return (0); + + /* First four bytes must be LZ4 magic numbers. */ + bits_checked = 0; + if ((number = archive_le32dec(buffer)) == LZ4_MAGICNUMBER) { + unsigned char flag, BD; + + bits_checked += 32; + /* Next follows a stream descriptor. */ + /* Descriptor Flags. */ + flag = buffer[4]; + /* A version number must be "01". */ + if (((flag & 0xc0) >> 6) != 1) + return (0); + /* A reserved bit must be "0". */ + if (flag & 2) + return (0); + bits_checked += 8; + BD = buffer[5]; + /* A block maximum size should be more than 3. */ + if (((BD & 0x70) >> 4) < 4) + return (0); + /* Reserved bits must be "0". */ + if (BD & ~0x70) + return (0); + bits_checked += 8; + } else if (number == LZ4_LEGACY) { + bits_checked += 32; + } + + return (bits_checked); +} + +#if !defined(HAVE_LIBLZ4) + +/* + * If we don't have the library on this system, we can't actually do the + * decompression. We can, however, still detect compressed archives + * and emit a useful message. + */ +static int +lz4_reader_init(struct archive_read_filter *self) +{ + int r; + + r = __archive_read_program(self, "lz4 -d -q"); + /* Note: We set the format here even if __archive_read_program() + * above fails. We do, after all, know what the format is + * even if we weren't able to read it. */ + self->code = ARCHIVE_FILTER_LZ4; + self->name = "lz4"; + return (r); +} + + +#else + +/* + * Setup the callbacks. + */ +static int +lz4_reader_init(struct archive_read_filter *self) +{ + struct private_data *state; + + self->code = ARCHIVE_FILTER_LZ4; + self->name = "lz4"; + + state = (struct private_data *)calloc(sizeof(*state), 1); + if (state == NULL) { + archive_set_error(&self->archive->archive, ENOMEM, + "Can't allocate data for lz4 decompression"); + return (ARCHIVE_FATAL); + } + + self->data = state; + state->stage = SELECT_STREAM; + self->read = lz4_filter_read; + self->skip = NULL; /* not supported */ + self->close = lz4_filter_close; + + return (ARCHIVE_OK); +} + +static int +lz4_allocate_out_block(struct archive_read_filter *self) +{ + struct private_data *state = (struct private_data *)self->data; + size_t out_block_size = state->flags.block_maximum_size; + void *out_block; + + if (!state->flags.block_independence) + out_block_size += 64 * 1024; + if (state->out_block_size < out_block_size) { + free(state->out_block); + out_block = (unsigned char *)malloc(out_block_size); + state->out_block_size = out_block_size; + if (out_block == NULL) { + archive_set_error(&self->archive->archive, ENOMEM, + "Can't allocate data for lz4 decompression"); + return (ARCHIVE_FATAL); + } + state->out_block = out_block; + } + if (!state->flags.block_independence) + memset(state->out_block, 0, 64 * 1024); + return (ARCHIVE_OK); +} + +static int +lz4_allocate_out_block_for_legacy(struct archive_read_filter *self) +{ + struct private_data *state = (struct private_data *)self->data; + size_t out_block_size = LEGACY_BLOCK_SIZE; + void *out_block; + + if (state->out_block_size < out_block_size) { + free(state->out_block); + out_block = (unsigned char *)malloc(out_block_size); + state->out_block_size = out_block_size; + if (out_block == NULL) { + archive_set_error(&self->archive->archive, ENOMEM, + "Can't allocate data for lz4 decompression"); + return (ARCHIVE_FATAL); + } + state->out_block = out_block; + } + return (ARCHIVE_OK); +} + +/* + * Return the next block of decompressed data. + */ +static ssize_t +lz4_filter_read(struct archive_read_filter *self, const void **p) +{ + struct private_data *state = (struct private_data *)self->data; + ssize_t ret; + + if (state->eof) { + *p = NULL; + return (0); + } + + __archive_read_filter_consume(self->upstream, state->unconsumed); + state->unconsumed = 0; + + switch (state->stage) { + case SELECT_STREAM: + break; + case READ_DEFAULT_STREAM: + case READ_LEGACY_STREAM: + /* Reading a lz4 stream already failed. */ + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, "Invalid sequence."); + return (ARCHIVE_FATAL); + case READ_DEFAULT_BLOCK: + ret = lz4_filter_read_default_stream(self, p); + if (ret != 0 || state->stage != SELECT_STREAM) + return ret; + break; + case READ_LEGACY_BLOCK: + ret = lz4_filter_read_legacy_stream(self, p); + if (ret != 0 || state->stage != SELECT_STREAM) + return ret; + break; + default: + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, "Program error."); + return (ARCHIVE_FATAL); + break; + } + + while (state->stage == SELECT_STREAM) { + const char *read_buf; + + /* Read a magic number. */ + read_buf = __archive_read_filter_ahead(self->upstream, 4, + NULL); + if (read_buf == NULL) { + state->eof = 1; + *p = NULL; + return (0); + } + uint32_t number = archive_le32dec(read_buf); + __archive_read_filter_consume(self->upstream, 4); + if (number == LZ4_MAGICNUMBER) + return lz4_filter_read_default_stream(self, p); + else if (number == LZ4_LEGACY) + return lz4_filter_read_legacy_stream(self, p); + else if ((number & ~0xF) == LZ4_SKIPPABLED) { + read_buf = __archive_read_filter_ahead( + self->upstream, 4, NULL); + if (read_buf == NULL) { + archive_set_error( + &self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Malformed lz4 data"); + return (ARCHIVE_FATAL); + } + uint32_t skip_bytes = archive_le32dec(read_buf); + __archive_read_filter_consume(self->upstream, + 4 + skip_bytes); + } else { + /* Ignore following unrecognized data. */ + state->eof = 1; + *p = NULL; + return (0); + } + } + state->eof = 1; + *p = NULL; + return (0); +} + +static int +lz4_filter_read_descriptor(struct archive_read_filter *self) +{ + struct private_data *state = (struct private_data *)self->data; + const char *read_buf; + ssize_t bytes_remaining; + ssize_t descriptor_bytes; + unsigned char flag, bd; + unsigned int chsum, chsum_verifier; + + /* Make sure we have 2 bytes for flags. */ + read_buf = __archive_read_filter_ahead(self->upstream, 2, + &bytes_remaining); + if (read_buf == NULL) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "truncated lz4 input"); + return (ARCHIVE_FATAL); + } + + /* + Parse flags. + */ + flag = (unsigned char)read_buf[0]; + /* Verify version number. */ + if ((flag & 0xc0) != 1<<6) + goto malformed_error; + /* A reserved bit must be zero. */ + if (flag & 0x02) + goto malformed_error; + state->flags.block_independence = (flag & 0x20) != 0; + state->flags.block_checksum = (flag & 0x10)?4:0; + state->flags.stream_size = (flag & 0x08) != 0; + state->flags.stream_checksum = (flag & 0x04) != 0; + state->flags.preset_dictionary = (flag & 0x01) != 0; + + /* BD */ + bd = (unsigned char)read_buf[1]; + /* Reserved bits must be zero. */ + if (bd & 0x8f) + goto malformed_error; + /* Get a maximum block size. */ + switch (read_buf[1] >> 4) { + case 4: /* 64 KB */ + state->flags.block_maximum_size = 64 * 1024; + break; + case 5: /* 256 KB */ + state->flags.block_maximum_size = 256 * 1024; + break; + case 6: /* 1 MB */ + state->flags.block_maximum_size = 1024 * 1024; + break; + case 7: /* 4 MB */ + state->flags.block_maximum_size = 4 * 1024 * 1024; + break; + default: + goto malformed_error; + } + + /* Read the whole descriptor in a stream block. */ + descriptor_bytes = 3; + if (state->flags.stream_size) + descriptor_bytes += 8; + if (state->flags.preset_dictionary) + descriptor_bytes += 4; + if (bytes_remaining < descriptor_bytes) { + read_buf = __archive_read_filter_ahead(self->upstream, + descriptor_bytes, &bytes_remaining); + if (read_buf == NULL) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "truncated lz4 input"); + return (ARCHIVE_FATAL); + } + } + /* Check if a descriptor is corrupted */ + chsum = __archive_xxhash.XXH32(read_buf, (int)descriptor_bytes -1, 0); + chsum = (chsum >> 8) & 0xff; + chsum_verifier = read_buf[descriptor_bytes-1] & 0xff; + if (chsum != chsum_verifier) + goto malformed_error; + + __archive_read_filter_consume(self->upstream, descriptor_bytes); + + /* Make sure we have a large enough buffer for uncompressed data. */ + if (lz4_allocate_out_block(self) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + if (state->flags.stream_checksum) + state->xxh32_state = __archive_xxhash.XXH32_init(0); + + state->decoded_size = 0; + /* Success */ + return (ARCHIVE_OK); +malformed_error: + archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC, + "malformed lz4 data"); + return (ARCHIVE_FATAL); +} + +static ssize_t +lz4_filter_read_data_block(struct archive_read_filter *self, const void **p) +{ + struct private_data *state = (struct private_data *)self->data; + ssize_t compressed_size; + const char *read_buf; + ssize_t bytes_remaining; + int checksum_size; + ssize_t uncompressed_size; + size_t prefix64k; + + *p = NULL; + + /* Make sure we have 4 bytes for a block size. */ + read_buf = __archive_read_filter_ahead(self->upstream, 4, + &bytes_remaining); + if (read_buf == NULL) + goto truncated_error; + compressed_size = archive_le32dec(read_buf); + if ((compressed_size & 0x7fffffff) > state->flags.block_maximum_size) + goto malformed_error; + /* A compressed size == 0 means the end of stream blocks. */ + if (compressed_size == 0) { + __archive_read_filter_consume(self->upstream, 4); + return 0; + } + + checksum_size = state->flags.block_checksum; + /* Check if the block is uncompressed. */ + if (compressed_size & 0x80000000U) { + compressed_size &= 0x7fffffff; + uncompressed_size = compressed_size; + } else + uncompressed_size = 0;/* Unknown yet. */ + + /* + Unfortunately, lz4 decompression API requires a whole block + for its decompression speed, so we read a whole block and allocate + a huge buffer used for decoded data. + */ + read_buf = __archive_read_filter_ahead(self->upstream, + 4 + compressed_size + checksum_size, &bytes_remaining); + if (read_buf == NULL) + goto truncated_error; + + /* Optional processing, checking a block sum. */ + if (checksum_size) { + unsigned int chsum = __archive_xxhash.XXH32( + read_buf + 4, (int)compressed_size, 0); + unsigned int chsum_block = + archive_le32dec(read_buf + 4 + compressed_size); + if (chsum != chsum_block) + goto malformed_error; + } + + + /* If the block is uncompressed, there is nothing to do. */ + if (uncompressed_size) { + /* Prepare a prefix 64k block for next block. */ + if (!state->flags.block_independence) { + prefix64k = 64 * 1024; + if (uncompressed_size < (ssize_t)prefix64k) { + memcpy(state->out_block + + prefix64k - uncompressed_size, + read_buf + 4, + uncompressed_size); + memset(state->out_block, 0, + prefix64k - uncompressed_size); + } else { + memcpy(state->out_block, + read_buf + 4 + + uncompressed_size - prefix64k, + prefix64k); + } + state->decoded_size = 0; + } + state->unconsumed = 4 + uncompressed_size + checksum_size; + *p = read_buf + 4; + return uncompressed_size; + } + + /* + Decompress a block data. + */ + if (state->flags.block_independence) { + prefix64k = 0; + uncompressed_size = LZ4_decompress_safe(read_buf + 4, + state->out_block, (int)compressed_size, + state->flags.block_maximum_size); + } else { + prefix64k = 64 * 1024; + if (state->decoded_size) { + if (state->decoded_size < prefix64k) { + memmove(state->out_block + + prefix64k - state->decoded_size, + state->out_block + prefix64k, + state->decoded_size); + memset(state->out_block, 0, + prefix64k - state->decoded_size); + } else { + memmove(state->out_block, + state->out_block + state->decoded_size, + prefix64k); + } + } +#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7 + uncompressed_size = LZ4_decompress_safe_usingDict( + read_buf + 4, + state->out_block + prefix64k, (int)compressed_size, + state->flags.block_maximum_size, + state->out_block, + prefix64k); +#else + uncompressed_size = LZ4_decompress_safe_withPrefix64k( + read_buf + 4, + state->out_block + prefix64k, (int)compressed_size, + state->flags.block_maximum_size); +#endif + } + + /* Check if an error occurred in the decompression process. */ + if (uncompressed_size < 0) { + archive_set_error(&(self->archive->archive), + ARCHIVE_ERRNO_MISC, "lz4 decompression failed"); + return (ARCHIVE_FATAL); + } + + state->unconsumed = 4 + compressed_size + checksum_size; + *p = state->out_block + prefix64k; + state->decoded_size = uncompressed_size; + return uncompressed_size; + +malformed_error: + archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC, + "malformed lz4 data"); + return (ARCHIVE_FATAL); +truncated_error: + archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC, + "truncated lz4 input"); + return (ARCHIVE_FATAL); +} + +static ssize_t +lz4_filter_read_default_stream(struct archive_read_filter *self, const void **p) +{ + struct private_data *state = (struct private_data *)self->data; + const char *read_buf; + ssize_t bytes_remaining; + ssize_t ret; + + if (state->stage == SELECT_STREAM) { + state->stage = READ_DEFAULT_STREAM; + /* First, read a descriptor. */ + if((ret = lz4_filter_read_descriptor(self)) != ARCHIVE_OK) + return (ret); + state->stage = READ_DEFAULT_BLOCK; + } + /* Decompress a block. */ + ret = lz4_filter_read_data_block(self, p); + + /* If the end of block is detected, change the filter status + to read next stream. */ + if (ret == 0 && *p == NULL) + state->stage = SELECT_STREAM; + + /* Optional processing, checking a stream sum. */ + if (state->flags.stream_checksum) { + if (state->stage == SELECT_STREAM) { + unsigned int checksum; + unsigned int checksum_stream; + read_buf = __archive_read_filter_ahead(self->upstream, + 4, &bytes_remaining); + if (read_buf == NULL) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, "truncated lz4 input"); + return (ARCHIVE_FATAL); + } + checksum = archive_le32dec(read_buf); + __archive_read_filter_consume(self->upstream, 4); + checksum_stream = __archive_xxhash.XXH32_digest( + state->xxh32_state); + state->xxh32_state = NULL; + if (checksum != checksum_stream) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "lz4 stream checksum error"); + return (ARCHIVE_FATAL); + } + } else if (ret > 0) + __archive_xxhash.XXH32_update(state->xxh32_state, + *p, (int)ret); + } + return (ret); +} + +static ssize_t +lz4_filter_read_legacy_stream(struct archive_read_filter *self, const void **p) +{ + struct private_data *state = (struct private_data *)self->data; + uint32_t compressed; + const char *read_buf; + ssize_t ret; + + *p = NULL; + ret = lz4_allocate_out_block_for_legacy(self); + if (ret != ARCHIVE_OK) + return ret; + + /* Make sure we have 4 bytes for a block size. */ + read_buf = __archive_read_filter_ahead(self->upstream, 4, NULL); + if (read_buf == NULL) { + if (state->stage == SELECT_STREAM) { + state->stage = READ_LEGACY_STREAM; + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "truncated lz4 input"); + return (ARCHIVE_FATAL); + } + state->stage = SELECT_STREAM; + return 0; + } + state->stage = READ_LEGACY_BLOCK; + compressed = archive_le32dec(read_buf); + if (compressed > LZ4_COMPRESSBOUND(LEGACY_BLOCK_SIZE)) { + state->stage = SELECT_STREAM; + return 0; + } + + /* Make sure we have a whole block. */ + read_buf = __archive_read_filter_ahead(self->upstream, + 4 + compressed, NULL); + if (read_buf == NULL) { + archive_set_error(&(self->archive->archive), + ARCHIVE_ERRNO_MISC, "truncated lz4 input"); + return (ARCHIVE_FATAL); + } + ret = LZ4_decompress_safe(read_buf + 4, state->out_block, + compressed, (int)state->out_block_size); + if (ret < 0) { + archive_set_error(&(self->archive->archive), + ARCHIVE_ERRNO_MISC, "lz4 decompression failed"); + return (ARCHIVE_FATAL); + } + *p = state->out_block; + state->unconsumed = 4 + compressed; + return ret; +} + +/* + * Clean up the decompressor. + */ +static int +lz4_filter_close(struct archive_read_filter *self) +{ + struct private_data *state; + int ret = ARCHIVE_OK; + + state = (struct private_data *)self->data; + free(state->xxh32_state); + free(state->out_block); + free(state); + return (ret); +} + +#endif /* HAVE_LIBLZ4 */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_lzop.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_lzop.c new file mode 100644 index 0000000000..a1c392f4f3 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_lzop.c @@ -0,0 +1,494 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_LZO_LZOCONF_H +#include <lzo/lzoconf.h> +#endif +#ifdef HAVE_LZO_LZO1X_H +#include <lzo/lzo1x.h> +#endif +#ifdef HAVE_ZLIB_H +#include <zlib.h> /* for crc32 and adler32 */ +#endif + +#include "archive.h" +#if !defined(HAVE_ZLIB_H) &&\ + defined(HAVE_LZO_LZOCONF_H) && defined(HAVE_LZO_LZO1X_H) +#include "archive_crc32.h" +#endif +#include "archive_endian.h" +#include "archive_private.h" +#include "archive_read_private.h" + +#ifndef HAVE_ZLIB_H +#define adler32 lzo_adler32 +#endif + +#define LZOP_HEADER_MAGIC "\x89\x4c\x5a\x4f\x00\x0d\x0a\x1a\x0a" +#define LZOP_HEADER_MAGIC_LEN 9 + +#if defined(HAVE_LZO_LZOCONF_H) && defined(HAVE_LZO_LZO1X_H) +struct read_lzop { + unsigned char *out_block; + size_t out_block_size; + int64_t total_out; + int flags; + uint32_t compressed_cksum; + uint32_t uncompressed_cksum; + size_t compressed_size; + size_t uncompressed_size; + size_t unconsumed_bytes; + char in_stream; + char eof; /* True = found end of compressed data. */ +}; + +#define FILTER 0x0800 +#define CRC32_HEADER 0x1000 +#define EXTRA_FIELD 0x0040 +#define ADLER32_UNCOMPRESSED 0x0001 +#define ADLER32_COMPRESSED 0x0002 +#define CRC32_UNCOMPRESSED 0x0100 +#define CRC32_COMPRESSED 0x0200 +#define MAX_BLOCK_SIZE (64 * 1024 * 1024) + +static ssize_t lzop_filter_read(struct archive_read_filter *, const void **); +static int lzop_filter_close(struct archive_read_filter *); +#endif + +static int lzop_bidder_bid(struct archive_read_filter_bidder *, + struct archive_read_filter *); +static int lzop_bidder_init(struct archive_read_filter *); + +int +archive_read_support_filter_lzop(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter_bidder *reader; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_lzop"); + + if (__archive_read_get_bidder(a, &reader) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + reader->data = NULL; + reader->bid = lzop_bidder_bid; + reader->init = lzop_bidder_init; + reader->options = NULL; + reader->free = NULL; + /* Signal the extent of lzop support with the return value here. */ +#if defined(HAVE_LZO_LZOCONF_H) && defined(HAVE_LZO_LZO1X_H) + return (ARCHIVE_OK); +#else + /* Return ARCHIVE_WARN since this always uses an external program. */ + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "Using external lzop program for lzop decompression"); + return (ARCHIVE_WARN); +#endif +} + +/* + * Bidder just verifies the header and returns the number of verified bits. + */ +static int +lzop_bidder_bid(struct archive_read_filter_bidder *self, + struct archive_read_filter *filter) +{ + const unsigned char *p; + ssize_t avail; + + (void)self; /* UNUSED */ + + p = __archive_read_filter_ahead(filter, LZOP_HEADER_MAGIC_LEN, &avail); + if (p == NULL || avail == 0) + return (0); + + if (memcmp(p, LZOP_HEADER_MAGIC, LZOP_HEADER_MAGIC_LEN)) + return (0); + + return (LZOP_HEADER_MAGIC_LEN * 8); +} + +#if !defined(HAVE_LZO_LZOCONF_H) || !defined(HAVE_LZO_LZO1X_H) +/* + * If we don't have the library on this system, we can't do the + * decompression directly. We can, however, try to run "lzop -d" + * in case that's available. + */ +static int +lzop_bidder_init(struct archive_read_filter *self) +{ + int r; + + r = __archive_read_program(self, "lzop -d"); + /* Note: We set the format here even if __archive_read_program() + * above fails. We do, after all, know what the format is + * even if we weren't able to read it. */ + self->code = ARCHIVE_FILTER_LZOP; + self->name = "lzop"; + return (r); +} +#else +/* + * Initialize the filter object. + */ +static int +lzop_bidder_init(struct archive_read_filter *self) +{ + struct read_lzop *state; + + self->code = ARCHIVE_FILTER_LZOP; + self->name = "lzop"; + + state = (struct read_lzop *)calloc(sizeof(*state), 1); + if (state == NULL) { + archive_set_error(&self->archive->archive, ENOMEM, + "Can't allocate data for lzop decompression"); + return (ARCHIVE_FATAL); + } + + self->data = state; + self->read = lzop_filter_read; + self->skip = NULL; /* not supported */ + self->close = lzop_filter_close; + + return (ARCHIVE_OK); +} + +static int +consume_header(struct archive_read_filter *self) +{ + struct read_lzop *state = (struct read_lzop *)self->data; + const unsigned char *p, *_p; + unsigned checksum, flags, len, method, version; + + /* + * Check LZOP magic code. + */ + p = __archive_read_filter_ahead(self->upstream, + LZOP_HEADER_MAGIC_LEN, NULL); + if (p == NULL) + return (ARCHIVE_EOF); + + if (memcmp(p, LZOP_HEADER_MAGIC, LZOP_HEADER_MAGIC_LEN)) + return (ARCHIVE_EOF); + __archive_read_filter_consume(self->upstream, + LZOP_HEADER_MAGIC_LEN); + + p = __archive_read_filter_ahead(self->upstream, 29, NULL); + if (p == NULL) + goto truncated; + _p = p; + version = archive_be16dec(p); + p += 4;/* version(2 bytes) + library version(2 bytes) */ + + if (version >= 0x940) { + unsigned reqversion = archive_be16dec(p); p += 2; + if (reqversion < 0x900) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, "Invalid required version"); + return (ARCHIVE_FAILED); + } + } + + method = *p++; + if (method < 1 || method > 3) { + archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC, + "Unsupported method"); + return (ARCHIVE_FAILED); + } + + if (version >= 0x940) { + unsigned level = *p++; +#if 0 + unsigned default_level[] = {0, 3, 1, 9}; +#endif + if (level == 0) + /* Method is 1..3 here due to check above. */ +#if 0 /* Avoid an error Clang Static Analyzer claims + "Value stored to 'level' is never read". */ + level = default_level[method]; +#else + ;/* NOP */ +#endif + else if (level > 9) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, "Invalid level"); + return (ARCHIVE_FAILED); + } + } + + flags = archive_be32dec(p); p += 4; + + if (flags & FILTER) + p += 4; /* Skip filter */ + p += 4; /* Skip mode */ + if (version >= 0x940) + p += 8; /* Skip mtime */ + else + p += 4; /* Skip mtime */ + len = *p++; /* Read filename length */ + len += p - _p; + /* Make sure we have all bytes we need to calculate checksum. */ + p = __archive_read_filter_ahead(self->upstream, len + 4, NULL); + if (p == NULL) + goto truncated; + if (flags & CRC32_HEADER) + checksum = crc32(crc32(0, NULL, 0), p, len); + else + checksum = adler32(adler32(0, NULL, 0), p, len); + if (archive_be32dec(p + len) != checksum) + goto corrupted; + __archive_read_filter_consume(self->upstream, len + 4); + if (flags & EXTRA_FIELD) { + /* Skip extra field */ + p = __archive_read_filter_ahead(self->upstream, 4, NULL); + if (p == NULL) + goto truncated; + len = archive_be32dec(p); + __archive_read_filter_consume(self->upstream, len + 4 + 4); + } + state->flags = flags; + state->in_stream = 1; + return (ARCHIVE_OK); +truncated: + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_FILE_FORMAT, "Truncated lzop data"); + return (ARCHIVE_FAILED); +corrupted: + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_FILE_FORMAT, "Corrupted lzop header"); + return (ARCHIVE_FAILED); +} + +static int +consume_block_info(struct archive_read_filter *self) +{ + struct read_lzop *state = (struct read_lzop *)self->data; + const unsigned char *p; + unsigned flags = state->flags; + + p = __archive_read_filter_ahead(self->upstream, 4, NULL); + if (p == NULL) + goto truncated; + state->uncompressed_size = archive_be32dec(p); + __archive_read_filter_consume(self->upstream, 4); + if (state->uncompressed_size == 0) + return (ARCHIVE_EOF); + if (state->uncompressed_size > MAX_BLOCK_SIZE) + goto corrupted; + + p = __archive_read_filter_ahead(self->upstream, 4, NULL); + if (p == NULL) + goto truncated; + state->compressed_size = archive_be32dec(p); + __archive_read_filter_consume(self->upstream, 4); + if (state->compressed_size > state->uncompressed_size) + goto corrupted; + + if (flags & (CRC32_UNCOMPRESSED | ADLER32_UNCOMPRESSED)) { + p = __archive_read_filter_ahead(self->upstream, 4, NULL); + if (p == NULL) + goto truncated; + state->compressed_cksum = state->uncompressed_cksum = + archive_be32dec(p); + __archive_read_filter_consume(self->upstream, 4); + } + if ((flags & (CRC32_COMPRESSED | ADLER32_COMPRESSED)) && + state->compressed_size < state->uncompressed_size) { + p = __archive_read_filter_ahead(self->upstream, 4, NULL); + if (p == NULL) + goto truncated; + state->compressed_cksum = archive_be32dec(p); + __archive_read_filter_consume(self->upstream, 4); + } + return (ARCHIVE_OK); +truncated: + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_FILE_FORMAT, "Truncated lzop data"); + return (ARCHIVE_FAILED); +corrupted: + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_FILE_FORMAT, "Corrupted lzop header"); + return (ARCHIVE_FAILED); +} + +static ssize_t +lzop_filter_read(struct archive_read_filter *self, const void **p) +{ + struct read_lzop *state = (struct read_lzop *)self->data; + const void *b; + lzo_uint out_size; + uint32_t cksum; + int ret, r; + + if (state->unconsumed_bytes) { + __archive_read_filter_consume(self->upstream, + state->unconsumed_bytes); + state->unconsumed_bytes = 0; + } + if (state->eof) + return (0); + + for (;;) { + if (!state->in_stream) { + ret = consume_header(self); + if (ret < ARCHIVE_OK) + return (ret); + if (ret == ARCHIVE_EOF) { + state->eof = 1; + return (0); + } + } + ret = consume_block_info(self); + if (ret < ARCHIVE_OK) + return (ret); + if (ret == ARCHIVE_EOF) + state->in_stream = 0; + else + break; + } + + if (state->out_block == NULL || + state->out_block_size < state->uncompressed_size) { + void *new_block; + + new_block = realloc(state->out_block, state->uncompressed_size); + if (new_block == NULL) { + archive_set_error(&self->archive->archive, ENOMEM, + "Can't allocate data for lzop decompression"); + return (ARCHIVE_FATAL); + } + state->out_block = new_block; + state->out_block_size = state->uncompressed_size; + } + + b = __archive_read_filter_ahead(self->upstream, + state->compressed_size, NULL); + if (b == NULL) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_FILE_FORMAT, "Truncated lzop data"); + return (ARCHIVE_FATAL); + } + if (state->flags & CRC32_COMPRESSED) + cksum = crc32(crc32(0, NULL, 0), b, state->compressed_size); + else if (state->flags & ADLER32_COMPRESSED) + cksum = adler32(adler32(0, NULL, 0), b, state->compressed_size); + else + cksum = state->compressed_cksum; + if (cksum != state->compressed_cksum) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, "Corrupted data"); + return (ARCHIVE_FATAL); + } + + /* + * If the both uncompressed size and compressed size are the same, + * we do not decompress this block. + */ + if (state->uncompressed_size == state->compressed_size) { + *p = b; + state->total_out += state->compressed_size; + state->unconsumed_bytes = state->compressed_size; + return ((ssize_t)state->uncompressed_size); + } + + /* + * Drive lzo uncompression. + */ + out_size = (lzo_uint)state->uncompressed_size; + r = lzo1x_decompress_safe(b, (lzo_uint)state->compressed_size, + state->out_block, &out_size, NULL); + switch (r) { + case LZO_E_OK: + if (out_size == state->uncompressed_size) + break; + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, "Corrupted data"); + return (ARCHIVE_FATAL); + case LZO_E_OUT_OF_MEMORY: + archive_set_error(&self->archive->archive, ENOMEM, + "lzop decompression failed: out of memory"); + return (ARCHIVE_FATAL); + default: + archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC, + "lzop decompression failed: %d", r); + return (ARCHIVE_FATAL); + } + + if (state->flags & CRC32_UNCOMPRESSED) + cksum = crc32(crc32(0, NULL, 0), state->out_block, + state->uncompressed_size); + else if (state->flags & ADLER32_UNCOMPRESSED) + cksum = adler32(adler32(0, NULL, 0), state->out_block, + state->uncompressed_size); + else + cksum = state->uncompressed_cksum; + if (cksum != state->uncompressed_cksum) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, "Corrupted data"); + return (ARCHIVE_FATAL); + } + + __archive_read_filter_consume(self->upstream, state->compressed_size); + *p = state->out_block; + state->total_out += out_size; + return ((ssize_t)out_size); +} + +/* + * Clean up the decompressor. + */ +static int +lzop_filter_close(struct archive_read_filter *self) +{ + struct read_lzop *state = (struct read_lzop *)self->data; + + free(state->out_block); + free(state); + return (ARCHIVE_OK); +} + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_none.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_none.c new file mode 100644 index 0000000000..95e5cfdb15 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_none.c @@ -0,0 +1,52 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#include "archive.h" +#include "archive_private.h" + +#if ARCHIVE_VERSION_NUMBER < 4000000 +/* Deprecated; remove in libarchive 4.0 */ +int +archive_read_support_compression_none(struct archive *a) +{ + return archive_read_support_filter_none(a); +} +#endif + +/* + * Uncompressed streams are handled implicitly by the read core, + * so this is now a no-op. + */ +int +archive_read_support_filter_none(struct archive *a) +{ + archive_check_magic(a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_none"); + + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_program.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_program.c new file mode 100644 index 0000000000..bf5b6f2b3c --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_program.c @@ -0,0 +1,503 @@ +/*- + * Copyright (c) 2007 Joerg Sonnenberger + * Copyright (c) 2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_SYS_WAIT_H +# include <sys/wait.h> +#endif +#ifdef HAVE_ERRNO_H +# include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +# include <fcntl.h> +#endif +#ifdef HAVE_LIMITS_H +# include <limits.h> +#endif +#ifdef HAVE_SIGNAL_H +# include <signal.h> +#endif +#ifdef HAVE_STDLIB_H +# include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +# include <string.h> +#endif +#ifdef HAVE_UNISTD_H +# include <unistd.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_string.h" +#include "archive_read_private.h" +#include "filter_fork.h" + + +#if ARCHIVE_VERSION_NUMBER < 4000000 +/* Deprecated; remove in libarchive 4.0 */ +int +archive_read_support_compression_program(struct archive *a, const char *cmd) +{ + return archive_read_support_filter_program(a, cmd); +} + +int +archive_read_support_compression_program_signature(struct archive *a, + const char *cmd, const void *signature, size_t signature_len) +{ + return archive_read_support_filter_program_signature(a, + cmd, signature, signature_len); +} +#endif + +int +archive_read_support_filter_program(struct archive *a, const char *cmd) +{ + return (archive_read_support_filter_program_signature(a, cmd, NULL, 0)); +} + +/* + * The bidder object stores the command and the signature to watch for. + * The 'inhibit' entry here is used to ensure that unchecked filters never + * bid twice in the same pipeline. + */ +struct program_bidder { + char *description; + char *cmd; + void *signature; + size_t signature_len; + int inhibit; +}; + +static int program_bidder_bid(struct archive_read_filter_bidder *, + struct archive_read_filter *upstream); +static int program_bidder_init(struct archive_read_filter *); +static int program_bidder_free(struct archive_read_filter_bidder *); + +/* + * The actual filter needs to track input and output data. + */ +struct program_filter { + struct archive_string description; +#if defined(_WIN32) && !defined(__CYGWIN__) + HANDLE child; +#else + pid_t child; +#endif + int exit_status; + int waitpid_return; + int child_stdin, child_stdout; + + char *out_buf; + size_t out_buf_len; +}; + +static ssize_t program_filter_read(struct archive_read_filter *, + const void **); +static int program_filter_close(struct archive_read_filter *); +static void free_state(struct program_bidder *); + +static int +set_bidder_signature(struct archive_read_filter_bidder *bidder, + struct program_bidder *state, const void *signature, size_t signature_len) +{ + + if (signature != NULL && signature_len > 0) { + state->signature_len = signature_len; + state->signature = malloc(signature_len); + memcpy(state->signature, signature, signature_len); + } + + /* + * Fill in the bidder object. + */ + bidder->data = state; + bidder->bid = program_bidder_bid; + bidder->init = program_bidder_init; + bidder->options = NULL; + bidder->free = program_bidder_free; + return (ARCHIVE_OK); +} + +int +archive_read_support_filter_program_signature(struct archive *_a, + const char *cmd, const void *signature, size_t signature_len) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter_bidder *bidder; + struct program_bidder *state; + + /* + * Get a bidder object from the read core. + */ + if (__archive_read_get_bidder(a, &bidder) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* + * Allocate our private state. + */ + state = (struct program_bidder *)calloc(1, sizeof (*state)); + if (state == NULL) + goto memerr; + state->cmd = strdup(cmd); + if (state->cmd == NULL) + goto memerr; + + return set_bidder_signature(bidder, state, signature, signature_len); +memerr: + free_state(state); + archive_set_error(_a, ENOMEM, "Can't allocate memory"); + return (ARCHIVE_FATAL); +} + +static int +program_bidder_free(struct archive_read_filter_bidder *self) +{ + struct program_bidder *state = (struct program_bidder *)self->data; + + free_state(state); + return (ARCHIVE_OK); +} + +static void +free_state(struct program_bidder *state) +{ + + if (state) { + free(state->cmd); + free(state->signature); + free(state); + } +} + +/* + * If we do have a signature, bid only if that matches. + * + * If there's no signature, we bid INT_MAX the first time + * we're called, then never bid again. + */ +static int +program_bidder_bid(struct archive_read_filter_bidder *self, + struct archive_read_filter *upstream) +{ + struct program_bidder *state = self->data; + const char *p; + + /* If we have a signature, use that to match. */ + if (state->signature_len > 0) { + p = __archive_read_filter_ahead(upstream, + state->signature_len, NULL); + if (p == NULL) + return (0); + /* No match, so don't bid. */ + if (memcmp(p, state->signature, state->signature_len) != 0) + return (0); + return ((int)state->signature_len * 8); + } + + /* Otherwise, bid once and then never bid again. */ + if (state->inhibit) + return (0); + state->inhibit = 1; + return (INT_MAX); +} + +/* + * Shut down the child, return ARCHIVE_OK if it exited normally. + * + * Note that the return value is sticky; if we're called again, + * we won't reap the child again, but we will return the same status + * (including error message if the child came to a bad end). + */ +static int +child_stop(struct archive_read_filter *self, struct program_filter *state) +{ + /* Close our side of the I/O with the child. */ + if (state->child_stdin != -1) { + close(state->child_stdin); + state->child_stdin = -1; + } + if (state->child_stdout != -1) { + close(state->child_stdout); + state->child_stdout = -1; + } + + if (state->child != 0) { + /* Reap the child. */ + do { + state->waitpid_return + = waitpid(state->child, &state->exit_status, 0); + } while (state->waitpid_return == -1 && errno == EINTR); +#if defined(_WIN32) && !defined(__CYGWIN__) + CloseHandle(state->child); +#endif + state->child = 0; + } + + if (state->waitpid_return < 0) { + /* waitpid() failed? This is ugly. */ + archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC, + "Child process exited badly"); + return (ARCHIVE_WARN); + } + +#if !defined(_WIN32) || defined(__CYGWIN__) + if (WIFSIGNALED(state->exit_status)) { +#ifdef SIGPIPE + /* If the child died because we stopped reading before + * it was done, that's okay. Some archive formats + * have padding at the end that we routinely ignore. */ + /* The alternative to this would be to add a step + * before close(child_stdout) above to read from the + * child until the child has no more to write. */ + if (WTERMSIG(state->exit_status) == SIGPIPE) + return (ARCHIVE_OK); +#endif + archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC, + "Child process exited with signal %d", + WTERMSIG(state->exit_status)); + return (ARCHIVE_WARN); + } +#endif /* !_WIN32 || __CYGWIN__ */ + + if (WIFEXITED(state->exit_status)) { + if (WEXITSTATUS(state->exit_status) == 0) + return (ARCHIVE_OK); + + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Child process exited with status %d", + WEXITSTATUS(state->exit_status)); + return (ARCHIVE_WARN); + } + + return (ARCHIVE_WARN); +} + +/* + * Use select() to decide whether the child is ready for read or write. + */ +static ssize_t +child_read(struct archive_read_filter *self, char *buf, size_t buf_len) +{ + struct program_filter *state = self->data; + ssize_t ret, requested, avail; + const char *p; +#if defined(_WIN32) && !defined(__CYGWIN__) + HANDLE handle = (HANDLE)_get_osfhandle(state->child_stdout); +#endif + + requested = buf_len > SSIZE_MAX ? SSIZE_MAX : buf_len; + + for (;;) { + do { +#if defined(_WIN32) && !defined(__CYGWIN__) + /* Avoid infinity wait. + * Note: If there is no data in the pipe, ReadFile() + * called in read() never returns and so we won't + * write remaining encoded data to the pipe. + * Note: This way may cause performance problem. + * we are looking forward to great code to resolve + * this. */ + DWORD pipe_avail = -1; + int cnt = 2; + + while (PeekNamedPipe(handle, NULL, 0, NULL, + &pipe_avail, NULL) != 0 && pipe_avail == 0 && + cnt--) + Sleep(5); + if (pipe_avail == 0) { + ret = -1; + errno = EAGAIN; + break; + } +#endif + ret = read(state->child_stdout, buf, requested); + } while (ret == -1 && errno == EINTR); + + if (ret > 0) + return (ret); + if (ret == 0 || (ret == -1 && errno == EPIPE)) + /* Child has closed its output; reap the child + * and return the status. */ + return (child_stop(self, state)); + if (ret == -1 && errno != EAGAIN) + return (-1); + + if (state->child_stdin == -1) { + /* Block until child has some I/O ready. */ + __archive_check_child(state->child_stdin, + state->child_stdout); + continue; + } + + /* Get some more data from upstream. */ + p = __archive_read_filter_ahead(self->upstream, 1, &avail); + if (p == NULL) { + close(state->child_stdin); + state->child_stdin = -1; + fcntl(state->child_stdout, F_SETFL, 0); + if (avail < 0) + return (avail); + continue; + } + + do { + ret = write(state->child_stdin, p, avail); + } while (ret == -1 && errno == EINTR); + + if (ret > 0) { + /* Consume whatever we managed to write. */ + __archive_read_filter_consume(self->upstream, ret); + } else if (ret == -1 && errno == EAGAIN) { + /* Block until child has some I/O ready. */ + __archive_check_child(state->child_stdin, + state->child_stdout); + } else { + /* Write failed. */ + close(state->child_stdin); + state->child_stdin = -1; + fcntl(state->child_stdout, F_SETFL, 0); + /* If it was a bad error, we're done; otherwise + * it was EPIPE or EOF, and we can still read + * from the child. */ + if (ret == -1 && errno != EPIPE) + return (-1); + } + } +} + +int +__archive_read_program(struct archive_read_filter *self, const char *cmd) +{ + struct program_filter *state; + static const size_t out_buf_len = 65536; + char *out_buf; + const char *prefix = "Program: "; + int ret; + size_t l; + + l = strlen(prefix) + strlen(cmd) + 1; + state = (struct program_filter *)calloc(1, sizeof(*state)); + out_buf = (char *)malloc(out_buf_len); + if (state == NULL || out_buf == NULL || + archive_string_ensure(&state->description, l) == NULL) { + archive_set_error(&self->archive->archive, ENOMEM, + "Can't allocate input data"); + if (state != NULL) { + archive_string_free(&state->description); + free(state); + } + free(out_buf); + return (ARCHIVE_FATAL); + } + archive_strcpy(&state->description, prefix); + archive_strcat(&state->description, cmd); + + self->code = ARCHIVE_FILTER_PROGRAM; + self->name = state->description.s; + + state->out_buf = out_buf; + state->out_buf_len = out_buf_len; + + ret = __archive_create_child(cmd, &state->child_stdin, + &state->child_stdout, &state->child); + if (ret != ARCHIVE_OK) { + free(state->out_buf); + archive_string_free(&state->description); + free(state); + archive_set_error(&self->archive->archive, EINVAL, + "Can't initialize filter; unable to run program \"%s\"", + cmd); + return (ARCHIVE_FATAL); + } + + self->data = state; + self->read = program_filter_read; + self->skip = NULL; + self->close = program_filter_close; + + /* XXX Check that we can read at least one byte? */ + return (ARCHIVE_OK); +} + +static int +program_bidder_init(struct archive_read_filter *self) +{ + struct program_bidder *bidder_state; + + bidder_state = (struct program_bidder *)self->bidder->data; + return (__archive_read_program(self, bidder_state->cmd)); +} + +static ssize_t +program_filter_read(struct archive_read_filter *self, const void **buff) +{ + struct program_filter *state; + ssize_t bytes; + size_t total; + char *p; + + state = (struct program_filter *)self->data; + + total = 0; + p = state->out_buf; + while (state->child_stdout != -1 && total < state->out_buf_len) { + bytes = child_read(self, p, state->out_buf_len - total); + if (bytes < 0) + /* No recovery is possible if we can no longer + * read from the child. */ + return (ARCHIVE_FATAL); + if (bytes == 0) + /* We got EOF from the child. */ + break; + total += bytes; + p += bytes; + } + + *buff = state->out_buf; + return (total); +} + +static int +program_filter_close(struct archive_read_filter *self) +{ + struct program_filter *state; + int e; + + state = (struct program_filter *)self->data; + e = child_stop(self, state); + + /* Release our private data. */ + free(state->out_buf); + archive_string_free(&state->description); + free(state); + + return (e); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_rpm.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_rpm.c new file mode 100644 index 0000000000..e7e58e51f3 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_rpm.c @@ -0,0 +1,289 @@ +/*- + * Copyright (c) 2009 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif + +#include "archive.h" +#include "archive_endian.h" +#include "archive_private.h" +#include "archive_read_private.h" + +struct rpm { + int64_t total_in; + size_t hpos; + size_t hlen; + unsigned char header[16]; + enum { + ST_LEAD, /* Skipping 'Lead' section. */ + ST_HEADER, /* Reading 'Header' section; + * first 16 bytes. */ + ST_HEADER_DATA, /* Skipping 'Header' section. */ + ST_PADDING, /* Skipping padding data after the + * 'Header' section. */ + ST_ARCHIVE /* Reading 'Archive' section. */ + } state; + int first_header; +}; +#define RPM_LEAD_SIZE 96 /* Size of 'Lead' section. */ + +static int rpm_bidder_bid(struct archive_read_filter_bidder *, + struct archive_read_filter *); +static int rpm_bidder_init(struct archive_read_filter *); + +static ssize_t rpm_filter_read(struct archive_read_filter *, + const void **); +static int rpm_filter_close(struct archive_read_filter *); + +#if ARCHIVE_VERSION_NUMBER < 4000000 +/* Deprecated; remove in libarchive 4.0 */ +int +archive_read_support_compression_rpm(struct archive *a) +{ + return archive_read_support_filter_rpm(a); +} +#endif + +int +archive_read_support_filter_rpm(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter_bidder *bidder; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_rpm"); + + if (__archive_read_get_bidder(a, &bidder) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + bidder->data = NULL; + bidder->name = "rpm"; + bidder->bid = rpm_bidder_bid; + bidder->init = rpm_bidder_init; + bidder->options = NULL; + bidder->free = NULL; + return (ARCHIVE_OK); +} + +static int +rpm_bidder_bid(struct archive_read_filter_bidder *self, + struct archive_read_filter *filter) +{ + const unsigned char *b; + ssize_t avail; + int bits_checked; + + (void)self; /* UNUSED */ + + b = __archive_read_filter_ahead(filter, 8, &avail); + if (b == NULL) + return (0); + + bits_checked = 0; + /* + * Verify Header Magic Bytes : 0XED 0XAB 0XEE 0XDB + */ + if (memcmp(b, "\xED\xAB\xEE\xDB", 4) != 0) + return (0); + bits_checked += 32; + /* + * Check major version. + */ + if (b[4] != 3 && b[4] != 4) + return (0); + bits_checked += 8; + /* + * Check package type; binary or source. + */ + if (b[6] != 0) + return (0); + bits_checked += 8; + if (b[7] != 0 && b[7] != 1) + return (0); + bits_checked += 8; + + return (bits_checked); +} + +static int +rpm_bidder_init(struct archive_read_filter *self) +{ + struct rpm *rpm; + + self->code = ARCHIVE_FILTER_RPM; + self->name = "rpm"; + self->read = rpm_filter_read; + self->skip = NULL; /* not supported */ + self->close = rpm_filter_close; + + rpm = (struct rpm *)calloc(sizeof(*rpm), 1); + if (rpm == NULL) { + archive_set_error(&self->archive->archive, ENOMEM, + "Can't allocate data for rpm"); + return (ARCHIVE_FATAL); + } + + self->data = rpm; + rpm->state = ST_LEAD; + + return (ARCHIVE_OK); +} + +static ssize_t +rpm_filter_read(struct archive_read_filter *self, const void **buff) +{ + struct rpm *rpm; + const unsigned char *b; + ssize_t avail_in, total; + size_t used, n; + uint32_t section; + uint32_t bytes; + + rpm = (struct rpm *)self->data; + *buff = NULL; + total = avail_in = 0; + b = NULL; + used = 0; + do { + if (b == NULL) { + b = __archive_read_filter_ahead(self->upstream, 1, + &avail_in); + if (b == NULL) { + if (avail_in < 0) + return (ARCHIVE_FATAL); + else + break; + } + } + + switch (rpm->state) { + case ST_LEAD: + if (rpm->total_in + avail_in < RPM_LEAD_SIZE) + used += avail_in; + else { + n = (size_t)(RPM_LEAD_SIZE - rpm->total_in); + used += n; + b += n; + rpm->state = ST_HEADER; + rpm->hpos = 0; + rpm->hlen = 0; + rpm->first_header = 1; + } + break; + case ST_HEADER: + n = 16 - rpm->hpos; + if (n > avail_in - used) + n = avail_in - used; + memcpy(rpm->header+rpm->hpos, b, n); + b += n; + used += n; + rpm->hpos += n; + + if (rpm->hpos == 16) { + if (rpm->header[0] != 0x8e || + rpm->header[1] != 0xad || + rpm->header[2] != 0xe8 || + rpm->header[3] != 0x01) { + if (rpm->first_header) { + archive_set_error( + &self->archive->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Unrecoginized rpm header"); + return (ARCHIVE_FATAL); + } + rpm->state = ST_ARCHIVE; + *buff = rpm->header; + total = rpm->hpos; + break; + } + /* Calculate 'Header' length. */ + section = archive_be32dec(rpm->header+8); + bytes = archive_be32dec(rpm->header+12); + rpm->hlen = 16 + section * 16 + bytes; + rpm->state = ST_HEADER_DATA; + rpm->first_header = 0; + } + break; + case ST_HEADER_DATA: + n = rpm->hlen - rpm->hpos; + if (n > avail_in - used) + n = avail_in - used; + b += n; + used += n; + rpm->hpos += n; + if (rpm->hpos == rpm->hlen) + rpm->state = ST_PADDING; + break; + case ST_PADDING: + while (used < (size_t)avail_in) { + if (*b != 0) { + /* Read next header. */ + rpm->state = ST_HEADER; + rpm->hpos = 0; + rpm->hlen = 0; + break; + } + b++; + used++; + } + break; + case ST_ARCHIVE: + *buff = b; + total = avail_in; + used = avail_in; + break; + } + if (used == (size_t)avail_in) { + rpm->total_in += used; + __archive_read_filter_consume(self->upstream, used); + b = NULL; + used = 0; + } + } while (total == 0 && avail_in > 0); + + if (used > 0 && b != NULL) { + rpm->total_in += used; + __archive_read_filter_consume(self->upstream, used); + } + return (total); +} + +static int +rpm_filter_close(struct archive_read_filter *self) +{ + struct rpm *rpm; + + rpm = (struct rpm *)self->data; + free(rpm); + + return (ARCHIVE_OK); +} + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_uu.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_uu.c new file mode 100644 index 0000000000..67ddffb069 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_uu.c @@ -0,0 +1,685 @@ +/*- + * Copyright (c) 2009-2011 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_read_private.h" + +/* Maximum lookahead during bid phase */ +#define UUENCODE_BID_MAX_READ 128*1024 /* in bytes */ + +struct uudecode { + int64_t total; + unsigned char *in_buff; +#define IN_BUFF_SIZE (1024) + int in_cnt; + size_t in_allocated; + unsigned char *out_buff; +#define OUT_BUFF_SIZE (64 * 1024) + int state; +#define ST_FIND_HEAD 0 +#define ST_READ_UU 1 +#define ST_UUEND 2 +#define ST_READ_BASE64 3 +#define ST_IGNORE 4 +}; + +static int uudecode_bidder_bid(struct archive_read_filter_bidder *, + struct archive_read_filter *filter); +static int uudecode_bidder_init(struct archive_read_filter *); + +static ssize_t uudecode_filter_read(struct archive_read_filter *, + const void **); +static int uudecode_filter_close(struct archive_read_filter *); + +#if ARCHIVE_VERSION_NUMBER < 4000000 +/* Deprecated; remove in libarchive 4.0 */ +int +archive_read_support_compression_uu(struct archive *a) +{ + return archive_read_support_filter_uu(a); +} +#endif + +int +archive_read_support_filter_uu(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter_bidder *bidder; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_uu"); + + if (__archive_read_get_bidder(a, &bidder) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + bidder->data = NULL; + bidder->name = "uu"; + bidder->bid = uudecode_bidder_bid; + bidder->init = uudecode_bidder_init; + bidder->options = NULL; + bidder->free = NULL; + return (ARCHIVE_OK); +} + +static const unsigned char ascii[256] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '\n', 0, 0, '\r', 0, 0, /* 00 - 0F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 1F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 20 - 2F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 30 - 3F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 40 - 4F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 50 - 5F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 60 - 6F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, /* 70 - 7F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F0 - FF */ +}; + +static const unsigned char uuchar[256] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 00 - 0F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 1F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 20 - 2F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 30 - 3F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 40 - 4F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 50 - 5F */ + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 60 - 6F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 70 - 7F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F0 - FF */ +}; + +static const unsigned char base64[256] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 00 - 0F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 1F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, /* 20 - 2F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 30 - 3F */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 40 - 4F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 50 - 5F */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 60 - 6F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 70 - 7F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F0 - FF */ +}; + +static const int base64num[128] = { + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 - 0F */ + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 1F */ + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 62, 0, 0, 0, 63, /* 20 - 2F */ + 52, 53, 54, 55, 56, 57, 58, 59, + 60, 61, 0, 0, 0, 0, 0, 0, /* 30 - 3F */ + 0, 0, 1, 2, 3, 4, 5, 6, + 7, 8, 9, 10, 11, 12, 13, 14, /* 40 - 4F */ + 15, 16, 17, 18, 19, 20, 21, 22, + 23, 24, 25, 0, 0, 0, 0, 0, /* 50 - 5F */ + 0, 26, 27, 28, 29, 30, 31, 32, + 33, 34, 35, 36, 37, 38, 39, 40, /* 60 - 6F */ + 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, 0, 0, 0, 0, 0, /* 70 - 7F */ +}; + +static ssize_t +get_line(const unsigned char *b, ssize_t avail, ssize_t *nlsize) +{ + ssize_t len; + + len = 0; + while (len < avail) { + switch (ascii[*b]) { + case 0: /* Non-ascii character or control character. */ + if (nlsize != NULL) + *nlsize = 0; + return (-1); + case '\r': + if (avail-len > 1 && b[1] == '\n') { + if (nlsize != NULL) + *nlsize = 2; + return (len+2); + } + /* FALL THROUGH */ + case '\n': + if (nlsize != NULL) + *nlsize = 1; + return (len+1); + case 1: + b++; + len++; + break; + } + } + if (nlsize != NULL) + *nlsize = 0; + return (avail); +} + +static ssize_t +bid_get_line(struct archive_read_filter *filter, + const unsigned char **b, ssize_t *avail, ssize_t *ravail, + ssize_t *nl, size_t* nbytes_read) +{ + ssize_t len; + int quit; + + quit = 0; + if (*avail == 0) { + *nl = 0; + len = 0; + } else + len = get_line(*b, *avail, nl); + + /* + * Read bytes more while it does not reach the end of line. + */ + while (*nl == 0 && len == *avail && !quit && + *nbytes_read < UUENCODE_BID_MAX_READ) { + ssize_t diff = *ravail - *avail; + size_t nbytes_req = (*ravail+1023) & ~1023U; + ssize_t tested; + + /* Increase reading bytes if it is not enough to at least + * new two lines. */ + if (nbytes_req < (size_t)*ravail + 160) + nbytes_req <<= 1; + + *b = __archive_read_filter_ahead(filter, nbytes_req, avail); + if (*b == NULL) { + if (*ravail >= *avail) + return (0); + /* Reading bytes reaches the end of a stream. */ + *b = __archive_read_filter_ahead(filter, *avail, avail); + quit = 1; + } + *nbytes_read = *avail; + *ravail = *avail; + *b += diff; + *avail -= diff; + tested = len;/* Skip some bytes we already determinated. */ + len = get_line(*b + tested, *avail - tested, nl); + if (len >= 0) + len += tested; + } + return (len); +} + +#define UUDECODE(c) (((c) - 0x20) & 0x3f) + +static int +uudecode_bidder_bid(struct archive_read_filter_bidder *self, + struct archive_read_filter *filter) +{ + const unsigned char *b; + ssize_t avail, ravail; + ssize_t len, nl; + int l; + int firstline; + size_t nbytes_read; + + (void)self; /* UNUSED */ + + b = __archive_read_filter_ahead(filter, 1, &avail); + if (b == NULL) + return (0); + + firstline = 20; + ravail = avail; + nbytes_read = avail; + for (;;) { + len = bid_get_line(filter, &b, &avail, &ravail, &nl, &nbytes_read); + if (len < 0 || nl == 0) + return (0); /* No match found. */ + if (len - nl >= 11 && memcmp(b, "begin ", 6) == 0) + l = 6; + else if (len -nl >= 18 && memcmp(b, "begin-base64 ", 13) == 0) + l = 13; + else + l = 0; + + if (l > 0 && (b[l] < '0' || b[l] > '7' || + b[l+1] < '0' || b[l+1] > '7' || + b[l+2] < '0' || b[l+2] > '7' || b[l+3] != ' ')) + l = 0; + + b += len; + avail -= len; + if (l) + break; + firstline = 0; + + /* Do not read more than UUENCODE_BID_MAX_READ bytes */ + if (nbytes_read >= UUENCODE_BID_MAX_READ) + return (0); + } + if (!avail) + return (0); + len = bid_get_line(filter, &b, &avail, &ravail, &nl, &nbytes_read); + if (len < 0 || nl == 0) + return (0);/* There are non-ascii characters. */ + avail -= len; + + if (l == 6) { + /* "begin " */ + if (!uuchar[*b]) + return (0); + /* Get a length of decoded bytes. */ + l = UUDECODE(*b++); len--; + if (l > 45) + /* Normally, maximum length is 45(character 'M'). */ + return (0); + if (l > len - nl) + return (0); /* Line too short. */ + while (l) { + if (!uuchar[*b++]) + return (0); + --len; + --l; + } + if (len-nl == 1 && + (uuchar[*b] || /* Check sum. */ + (*b >= 'a' && *b <= 'z'))) {/* Padding data(MINIX). */ + ++b; + --len; + } + b += nl; + if (avail && uuchar[*b]) + return (firstline+30); + } else if (l == 13) { + /* "begin-base64 " */ + while (len-nl > 0) { + if (!base64[*b++]) + return (0); + --len; + } + b += nl; + + if (avail >= 5 && memcmp(b, "====\n", 5) == 0) + return (firstline+40); + if (avail >= 6 && memcmp(b, "====\r\n", 6) == 0) + return (firstline+40); + if (avail > 0 && base64[*b]) + return (firstline+30); + } + + return (0); +} + +static int +uudecode_bidder_init(struct archive_read_filter *self) +{ + struct uudecode *uudecode; + void *out_buff; + void *in_buff; + + self->code = ARCHIVE_FILTER_UU; + self->name = "uu"; + self->read = uudecode_filter_read; + self->skip = NULL; /* not supported */ + self->close = uudecode_filter_close; + + uudecode = (struct uudecode *)calloc(sizeof(*uudecode), 1); + out_buff = malloc(OUT_BUFF_SIZE); + in_buff = malloc(IN_BUFF_SIZE); + if (uudecode == NULL || out_buff == NULL || in_buff == NULL) { + archive_set_error(&self->archive->archive, ENOMEM, + "Can't allocate data for uudecode"); + free(uudecode); + free(out_buff); + free(in_buff); + return (ARCHIVE_FATAL); + } + + self->data = uudecode; + uudecode->in_buff = in_buff; + uudecode->in_cnt = 0; + uudecode->in_allocated = IN_BUFF_SIZE; + uudecode->out_buff = out_buff; + uudecode->state = ST_FIND_HEAD; + + return (ARCHIVE_OK); +} + +static int +ensure_in_buff_size(struct archive_read_filter *self, + struct uudecode *uudecode, size_t size) +{ + + if (size > uudecode->in_allocated) { + unsigned char *ptr; + size_t newsize; + + /* + * Calculate a new buffer size for in_buff. + * Increase its value until it has enough size we need. + */ + newsize = uudecode->in_allocated; + do { + if (newsize < IN_BUFF_SIZE*32) + newsize <<= 1; + else + newsize += IN_BUFF_SIZE; + } while (size > newsize); + /* Allocate the new buffer. */ + ptr = malloc(newsize); + if (ptr == NULL) { + free(ptr); + archive_set_error(&self->archive->archive, + ENOMEM, + "Can't allocate data for uudecode"); + return (ARCHIVE_FATAL); + } + /* Move the remaining data in in_buff into the new buffer. */ + if (uudecode->in_cnt) + memmove(ptr, uudecode->in_buff, uudecode->in_cnt); + /* Replace in_buff with the new buffer. */ + free(uudecode->in_buff); + uudecode->in_buff = ptr; + uudecode->in_allocated = newsize; + } + return (ARCHIVE_OK); +} + +static ssize_t +uudecode_filter_read(struct archive_read_filter *self, const void **buff) +{ + struct uudecode *uudecode; + const unsigned char *b, *d; + unsigned char *out; + ssize_t avail_in, ravail; + ssize_t used; + ssize_t total; + ssize_t len, llen, nl; + + uudecode = (struct uudecode *)self->data; + +read_more: + d = __archive_read_filter_ahead(self->upstream, 1, &avail_in); + if (d == NULL && avail_in < 0) + return (ARCHIVE_FATAL); + /* Quiet a code analyzer; make sure avail_in must be zero + * when d is NULL. */ + if (d == NULL) + avail_in = 0; + used = 0; + total = 0; + out = uudecode->out_buff; + ravail = avail_in; + if (uudecode->state == ST_IGNORE) { + used = avail_in; + goto finish; + } + if (uudecode->in_cnt) { + /* + * If there is remaining data which is saved by + * previous calling, use it first. + */ + if (ensure_in_buff_size(self, uudecode, + avail_in + uudecode->in_cnt) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + memcpy(uudecode->in_buff + uudecode->in_cnt, + d, avail_in); + d = uudecode->in_buff; + avail_in += uudecode->in_cnt; + uudecode->in_cnt = 0; + } + for (;used < avail_in; d += llen, used += llen) { + int64_t l, body; + + b = d; + len = get_line(b, avail_in - used, &nl); + if (len < 0) { + /* Non-ascii character is found. */ + if (uudecode->state == ST_FIND_HEAD && + (uudecode->total > 0 || total > 0)) { + uudecode->state = ST_IGNORE; + used = avail_in; + goto finish; + } + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Insufficient compressed data"); + return (ARCHIVE_FATAL); + } + llen = len; + if ((nl == 0) && (uudecode->state != ST_UUEND)) { + if (total == 0 && ravail <= 0) { + /* There is nothing more to read, fail */ + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Missing format data"); + return (ARCHIVE_FATAL); + } + /* + * Save remaining data which does not contain + * NL('\n','\r'). + */ + if (ensure_in_buff_size(self, uudecode, len) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + if (uudecode->in_buff != b) + memmove(uudecode->in_buff, b, len); + uudecode->in_cnt = (int)len; + if (total == 0) { + /* Do not return 0; it means end-of-file. + * We should try to read bytes more. */ + __archive_read_filter_consume( + self->upstream, ravail); + goto read_more; + } + used += len; + break; + } + switch (uudecode->state) { + default: + case ST_FIND_HEAD: + /* Do not read more than UUENCODE_BID_MAX_READ bytes */ + if (total + len >= UUENCODE_BID_MAX_READ) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid format data"); + return (ARCHIVE_FATAL); + } + if (len - nl >= 11 && memcmp(b, "begin ", 6) == 0) + l = 6; + else if (len - nl >= 18 && + memcmp(b, "begin-base64 ", 13) == 0) + l = 13; + else + l = 0; + if (l != 0 && b[l] >= '0' && b[l] <= '7' && + b[l+1] >= '0' && b[l+1] <= '7' && + b[l+2] >= '0' && b[l+2] <= '7' && b[l+3] == ' ') { + if (l == 6) + uudecode->state = ST_READ_UU; + else + uudecode->state = ST_READ_BASE64; + } + break; + case ST_READ_UU: + if (total + len * 2 > OUT_BUFF_SIZE) + goto finish; + body = len - nl; + if (!uuchar[*b] || body <= 0) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Insufficient compressed data"); + return (ARCHIVE_FATAL); + } + /* Get length of undecoded bytes of current line. */ + l = UUDECODE(*b++); + body--; + if (l > body) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Insufficient compressed data"); + return (ARCHIVE_FATAL); + } + if (l == 0) { + uudecode->state = ST_UUEND; + break; + } + while (l > 0) { + int n = 0; + + if (!uuchar[b[0]] || !uuchar[b[1]]) + break; + n = UUDECODE(*b++) << 18; + n |= UUDECODE(*b++) << 12; + *out++ = n >> 16; total++; + --l; + + if (l > 0) { + if (!uuchar[b[0]]) + break; + n |= UUDECODE(*b++) << 6; + *out++ = (n >> 8) & 0xFF; total++; + --l; + } + if (l > 0) { + if (!uuchar[b[0]]) + break; + n |= UUDECODE(*b++); + *out++ = n & 0xFF; total++; + --l; + } + } + if (l) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Insufficient compressed data"); + return (ARCHIVE_FATAL); + } + break; + case ST_UUEND: + if (len - nl == 3 && memcmp(b, "end ", 3) == 0) + uudecode->state = ST_FIND_HEAD; + else { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Insufficient compressed data"); + return (ARCHIVE_FATAL); + } + break; + case ST_READ_BASE64: + if (total + len * 2 > OUT_BUFF_SIZE) + goto finish; + l = len - nl; + if (l >= 3 && b[0] == '=' && b[1] == '=' && + b[2] == '=') { + uudecode->state = ST_FIND_HEAD; + break; + } + while (l > 0) { + int n = 0; + + if (!base64[b[0]] || !base64[b[1]]) + break; + n = base64num[*b++] << 18; + n |= base64num[*b++] << 12; + *out++ = n >> 16; total++; + l -= 2; + + if (l > 0) { + if (*b == '=') + break; + if (!base64[*b]) + break; + n |= base64num[*b++] << 6; + *out++ = (n >> 8) & 0xFF; total++; + --l; + } + if (l > 0) { + if (*b == '=') + break; + if (!base64[*b]) + break; + n |= base64num[*b++]; + *out++ = n & 0xFF; total++; + --l; + } + } + if (l && *b != '=') { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Insufficient compressed data"); + return (ARCHIVE_FATAL); + } + break; + } + } +finish: + if (ravail < avail_in) + used -= avail_in - ravail; + __archive_read_filter_consume(self->upstream, used); + + *buff = uudecode->out_buff; + uudecode->total += total; + return (total); +} + +static int +uudecode_filter_close(struct archive_read_filter *self) +{ + struct uudecode *uudecode; + + uudecode = (struct uudecode *)self->data; + free(uudecode->in_buff); + free(uudecode->out_buff); + free(uudecode); + + return (ARCHIVE_OK); +} + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_xz.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_xz.c new file mode 100644 index 0000000000..11807cf676 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_xz.c @@ -0,0 +1,796 @@ +/*- + * Copyright (c) 2009-2011 Michihiro NAKAJIMA + * Copyright (c) 2003-2008 Tim Kientzle and Miklos Vajna + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#if HAVE_LZMA_H +#include <lzma.h> +#endif + +#include "archive.h" +#include "archive_endian.h" +#include "archive_private.h" +#include "archive_read_private.h" + +#if HAVE_LZMA_H && HAVE_LIBLZMA + +struct private_data { + lzma_stream stream; + unsigned char *out_block; + size_t out_block_size; + int64_t total_out; + char eof; /* True = found end of compressed data. */ + char in_stream; + + /* Following variables are used for lzip only. */ + char lzip_ver; + uint32_t crc32; + int64_t member_in; + int64_t member_out; +}; + +#if LZMA_VERSION_MAJOR >= 5 +/* Effectively disable the limiter. */ +#define LZMA_MEMLIMIT UINT64_MAX +#else +/* NOTE: This needs to check memory size which running system has. */ +#define LZMA_MEMLIMIT (1U << 30) +#endif + +/* Combined lzip/lzma/xz filter */ +static ssize_t xz_filter_read(struct archive_read_filter *, const void **); +static int xz_filter_close(struct archive_read_filter *); +static int xz_lzma_bidder_init(struct archive_read_filter *); + +#endif + +/* + * Note that we can detect xz and lzma compressed files even if we + * can't decompress them. (In fact, we like detecting them because we + * can give better error messages.) So the bid framework here gets + * compiled even if no lzma library is available. + */ +static int xz_bidder_bid(struct archive_read_filter_bidder *, + struct archive_read_filter *); +static int xz_bidder_init(struct archive_read_filter *); +static int lzma_bidder_bid(struct archive_read_filter_bidder *, + struct archive_read_filter *); +static int lzma_bidder_init(struct archive_read_filter *); +static int lzip_has_member(struct archive_read_filter *); +static int lzip_bidder_bid(struct archive_read_filter_bidder *, + struct archive_read_filter *); +static int lzip_bidder_init(struct archive_read_filter *); + +#if ARCHIVE_VERSION_NUMBER < 4000000 +/* Deprecated; remove in libarchive 4.0 */ +int +archive_read_support_compression_xz(struct archive *a) +{ + return archive_read_support_filter_xz(a); +} +#endif + +int +archive_read_support_filter_xz(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter_bidder *bidder; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_xz"); + + if (__archive_read_get_bidder(a, &bidder) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + bidder->data = NULL; + bidder->name = "xz"; + bidder->bid = xz_bidder_bid; + bidder->init = xz_bidder_init; + bidder->options = NULL; + bidder->free = NULL; +#if HAVE_LZMA_H && HAVE_LIBLZMA + return (ARCHIVE_OK); +#else + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "Using external xz program for xz decompression"); + return (ARCHIVE_WARN); +#endif +} + +#if ARCHIVE_VERSION_NUMBER < 4000000 +int +archive_read_support_compression_lzma(struct archive *a) +{ + return archive_read_support_filter_lzma(a); +} +#endif + +int +archive_read_support_filter_lzma(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter_bidder *bidder; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_lzma"); + + if (__archive_read_get_bidder(a, &bidder) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + bidder->data = NULL; + bidder->name = "lzma"; + bidder->bid = lzma_bidder_bid; + bidder->init = lzma_bidder_init; + bidder->options = NULL; + bidder->free = NULL; +#if HAVE_LZMA_H && HAVE_LIBLZMA + return (ARCHIVE_OK); +#else + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "Using external lzma program for lzma decompression"); + return (ARCHIVE_WARN); +#endif +} + + +#if ARCHIVE_VERSION_NUMBER < 4000000 +int +archive_read_support_compression_lzip(struct archive *a) +{ + return archive_read_support_filter_lzip(a); +} +#endif + +int +archive_read_support_filter_lzip(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter_bidder *bidder; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_lzip"); + + if (__archive_read_get_bidder(a, &bidder) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + bidder->data = NULL; + bidder->name = "lzip"; + bidder->bid = lzip_bidder_bid; + bidder->init = lzip_bidder_init; + bidder->options = NULL; + bidder->free = NULL; +#if HAVE_LZMA_H && HAVE_LIBLZMA + return (ARCHIVE_OK); +#else + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "Using external lzip program for lzip decompression"); + return (ARCHIVE_WARN); +#endif +} + +/* + * Test whether we can handle this data. + */ +static int +xz_bidder_bid(struct archive_read_filter_bidder *self, + struct archive_read_filter *filter) +{ + const unsigned char *buffer; + ssize_t avail; + + (void)self; /* UNUSED */ + + buffer = __archive_read_filter_ahead(filter, 6, &avail); + if (buffer == NULL) + return (0); + + /* + * Verify Header Magic Bytes : FD 37 7A 58 5A 00 + */ + if (memcmp(buffer, "\xFD\x37\x7A\x58\x5A\x00", 6) != 0) + return (0); + + return (48); +} + +/* + * Test whether we can handle this data. + * + * <sigh> LZMA has a rather poor file signature. Zeros do not + * make good signature bytes as a rule, and the only non-zero byte + * here is an ASCII character. For example, an uncompressed tar + * archive whose first file is ']' would satisfy this check. It may + * be necessary to exclude LZMA from compression_all() because of + * this. Clients of libarchive would then have to explicitly enable + * LZMA checking instead of (or in addition to) compression_all() when + * they have other evidence (file name, command-line option) to go on. + */ +static int +lzma_bidder_bid(struct archive_read_filter_bidder *self, + struct archive_read_filter *filter) +{ + const unsigned char *buffer; + ssize_t avail; + uint32_t dicsize; + uint64_t uncompressed_size; + int bits_checked; + + (void)self; /* UNUSED */ + + buffer = __archive_read_filter_ahead(filter, 14, &avail); + if (buffer == NULL) + return (0); + + /* First byte of raw LZMA stream is commonly 0x5d. + * The first byte is a special number, which consists of + * three parameters of LZMA compression, a number of literal + * context bits(which is from 0 to 8, default is 3), a number + * of literal pos bits(which is from 0 to 4, default is 0), + * a number of pos bits(which is from 0 to 4, default is 2). + * The first byte is made by + * (pos bits * 5 + literal pos bit) * 9 + * literal contest bit, + * and so the default value in this field is + * (2 * 5 + 0) * 9 + 3 = 0x5d. + * lzma of LZMA SDK has options to change those parameters. + * It means a range of this field is from 0 to 224. And lzma of + * XZ Utils with option -e records 0x5e in this field. */ + /* NOTE: If this checking of the first byte increases false + * recognition, we should allow only 0x5d and 0x5e for the first + * byte of LZMA stream. */ + bits_checked = 0; + if (buffer[0] > (4 * 5 + 4) * 9 + 8) + return (0); + /* Most likely value in the first byte of LZMA stream. */ + if (buffer[0] == 0x5d || buffer[0] == 0x5e) + bits_checked += 8; + + /* Sixth through fourteenth bytes are uncompressed size, + * stored in little-endian order. `-1' means uncompressed + * size is unknown and lzma of XZ Utils always records `-1' + * in this field. */ + uncompressed_size = archive_le64dec(buffer+5); + if (uncompressed_size == (uint64_t)ARCHIVE_LITERAL_LL(-1)) + bits_checked += 64; + + /* Second through fifth bytes are dictionary size, stored in + * little-endian order. The minimum dictionary size is + * 1 << 12(4KiB) which the lzma of LZMA SDK uses with option + * -d12 and the maximum dictionary size is 1 << 27(128MiB) + * which the one uses with option -d27. + * NOTE: A comment of LZMA SDK source code says this dictionary + * range is from 1 << 12 to 1 << 30. */ + dicsize = archive_le32dec(buffer+1); + switch (dicsize) { + case 0x00001000:/* lzma of LZMA SDK option -d12. */ + case 0x00002000:/* lzma of LZMA SDK option -d13. */ + case 0x00004000:/* lzma of LZMA SDK option -d14. */ + case 0x00008000:/* lzma of LZMA SDK option -d15. */ + case 0x00010000:/* lzma of XZ Utils option -0 and -1. + * lzma of LZMA SDK option -d16. */ + case 0x00020000:/* lzma of LZMA SDK option -d17. */ + case 0x00040000:/* lzma of LZMA SDK option -d18. */ + case 0x00080000:/* lzma of XZ Utils option -2. + * lzma of LZMA SDK option -d19. */ + case 0x00100000:/* lzma of XZ Utils option -3. + * lzma of LZMA SDK option -d20. */ + case 0x00200000:/* lzma of XZ Utils option -4. + * lzma of LZMA SDK option -d21. */ + case 0x00400000:/* lzma of XZ Utils option -5. + * lzma of LZMA SDK option -d22. */ + case 0x00800000:/* lzma of XZ Utils option -6. + * lzma of LZMA SDK option -d23. */ + case 0x01000000:/* lzma of XZ Utils option -7. + * lzma of LZMA SDK option -d24. */ + case 0x02000000:/* lzma of XZ Utils option -8. + * lzma of LZMA SDK option -d25. */ + case 0x04000000:/* lzma of XZ Utils option -9. + * lzma of LZMA SDK option -d26. */ + case 0x08000000:/* lzma of LZMA SDK option -d27. */ + bits_checked += 32; + break; + default: + /* If a memory usage for encoding was not enough on + * the platform where LZMA stream was made, lzma of + * XZ Utils automatically decreased the dictionary + * size to enough memory for encoding by 1Mi bytes + * (1 << 20).*/ + if (dicsize <= 0x03F00000 && dicsize >= 0x00300000 && + (dicsize & ((1 << 20)-1)) == 0 && + bits_checked == 8 + 64) { + bits_checked += 32; + break; + } + /* Otherwise dictionary size is unlikely. But it is + * possible that someone makes lzma stream with + * liblzma/LZMA SDK in one's dictionary size. */ + return (0); + } + + /* TODO: The above test is still very weak. It would be + * good to do better. */ + + return (bits_checked); +} + +static int +lzip_has_member(struct archive_read_filter *filter) +{ + const unsigned char *buffer; + ssize_t avail; + int bits_checked; + int log2dic; + + buffer = __archive_read_filter_ahead(filter, 6, &avail); + if (buffer == NULL) + return (0); + + /* + * Verify Header Magic Bytes : 4C 5A 49 50 (`LZIP') + */ + bits_checked = 0; + if (memcmp(buffer, "LZIP", 4) != 0) + return (0); + bits_checked += 32; + + /* A version number must be 0 or 1 */ + if (buffer[4] != 0 && buffer[4] != 1) + return (0); + bits_checked += 8; + + /* Dictionary size. */ + log2dic = buffer[5] & 0x1f; + if (log2dic < 12 || log2dic > 27) + return (0); + bits_checked += 8; + + return (bits_checked); +} + +static int +lzip_bidder_bid(struct archive_read_filter_bidder *self, + struct archive_read_filter *filter) +{ + + (void)self; /* UNUSED */ + return (lzip_has_member(filter)); +} + +#if HAVE_LZMA_H && HAVE_LIBLZMA + +/* + * liblzma 4.999.7 and later support both lzma and xz streams. + */ +static int +xz_bidder_init(struct archive_read_filter *self) +{ + self->code = ARCHIVE_FILTER_XZ; + self->name = "xz"; + return (xz_lzma_bidder_init(self)); +} + +static int +lzma_bidder_init(struct archive_read_filter *self) +{ + self->code = ARCHIVE_FILTER_LZMA; + self->name = "lzma"; + return (xz_lzma_bidder_init(self)); +} + +static int +lzip_bidder_init(struct archive_read_filter *self) +{ + self->code = ARCHIVE_FILTER_LZIP; + self->name = "lzip"; + return (xz_lzma_bidder_init(self)); +} + +/* + * Set an error code and choose an error message + */ +static void +set_error(struct archive_read_filter *self, int ret) +{ + + switch (ret) { + case LZMA_STREAM_END: /* Found end of stream. */ + case LZMA_OK: /* Decompressor made some progress. */ + break; + case LZMA_MEM_ERROR: + archive_set_error(&self->archive->archive, ENOMEM, + "Lzma library error: Cannot allocate memory"); + break; + case LZMA_MEMLIMIT_ERROR: + archive_set_error(&self->archive->archive, ENOMEM, + "Lzma library error: Out of memory"); + break; + case LZMA_FORMAT_ERROR: + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Lzma library error: format not recognized"); + break; + case LZMA_OPTIONS_ERROR: + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Lzma library error: Invalid options"); + break; + case LZMA_DATA_ERROR: + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Lzma library error: Corrupted input data"); + break; + case LZMA_BUF_ERROR: + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Lzma library error: No progress is possible"); + break; + default: + /* Return an error. */ + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Lzma decompression failed: Unknown error"); + break; + } +} + +/* + * Setup the callbacks. + */ +static int +xz_lzma_bidder_init(struct archive_read_filter *self) +{ + static const size_t out_block_size = 64 * 1024; + void *out_block; + struct private_data *state; + int ret; + + state = (struct private_data *)calloc(sizeof(*state), 1); + out_block = (unsigned char *)malloc(out_block_size); + if (state == NULL || out_block == NULL) { + archive_set_error(&self->archive->archive, ENOMEM, + "Can't allocate data for xz decompression"); + free(out_block); + free(state); + return (ARCHIVE_FATAL); + } + + self->data = state; + state->out_block_size = out_block_size; + state->out_block = out_block; + self->read = xz_filter_read; + self->skip = NULL; /* not supported */ + self->close = xz_filter_close; + + state->stream.avail_in = 0; + + state->stream.next_out = state->out_block; + state->stream.avail_out = state->out_block_size; + + state->crc32 = 0; + if (self->code == ARCHIVE_FILTER_LZIP) { + /* + * We have to read a lzip header and use it to initialize + * compression library, thus we cannot initialize the + * library for lzip here. + */ + state->in_stream = 0; + return (ARCHIVE_OK); + } else + state->in_stream = 1; + + /* Initialize compression library. */ + if (self->code == ARCHIVE_FILTER_XZ) + ret = lzma_stream_decoder(&(state->stream), + LZMA_MEMLIMIT,/* memlimit */ + LZMA_CONCATENATED); + else + ret = lzma_alone_decoder(&(state->stream), + LZMA_MEMLIMIT);/* memlimit */ + + if (ret == LZMA_OK) + return (ARCHIVE_OK); + + /* Library setup failed: Choose an error message and clean up. */ + set_error(self, ret); + + free(state->out_block); + free(state); + self->data = NULL; + return (ARCHIVE_FATAL); +} + +static int +lzip_init(struct archive_read_filter *self) +{ + struct private_data *state; + const unsigned char *h; + lzma_filter filters[2]; + unsigned char props[5]; + ssize_t avail_in; + uint32_t dicsize; + int log2dic, ret; + + state = (struct private_data *)self->data; + h = __archive_read_filter_ahead(self->upstream, 6, &avail_in); + if (h == NULL) + return (ARCHIVE_FATAL); + + /* Get a version number. */ + state->lzip_ver = h[4]; + + /* + * Setup lzma property. + */ + props[0] = 0x5d; + + /* Get dictionary size. */ + log2dic = h[5] & 0x1f; + if (log2dic < 12 || log2dic > 27) + return (ARCHIVE_FATAL); + dicsize = 1U << log2dic; + if (log2dic > 12) + dicsize -= (dicsize / 16) * (h[5] >> 5); + archive_le32enc(props+1, dicsize); + + /* Consume lzip header. */ + __archive_read_filter_consume(self->upstream, 6); + state->member_in = 6; + + filters[0].id = LZMA_FILTER_LZMA1; + filters[0].options = NULL; + filters[1].id = LZMA_VLI_UNKNOWN; + filters[1].options = NULL; + + ret = lzma_properties_decode(&filters[0], NULL, props, sizeof(props)); + if (ret != LZMA_OK) { + set_error(self, ret); + return (ARCHIVE_FATAL); + } + ret = lzma_raw_decoder(&(state->stream), filters); + free(filters[0].options); + if (ret != LZMA_OK) { + set_error(self, ret); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_OK); +} + +static int +lzip_tail(struct archive_read_filter *self) +{ + struct private_data *state; + const unsigned char *f; + ssize_t avail_in; + int tail; + + state = (struct private_data *)self->data; + if (state->lzip_ver == 0) + tail = 12; + else + tail = 20; + f = __archive_read_filter_ahead(self->upstream, tail, &avail_in); + if (f == NULL && avail_in < 0) + return (ARCHIVE_FATAL); + if (f == NULL || avail_in < tail) { + archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC, + "Lzip: Remaining data is less bytes"); + return (ARCHIVE_FAILED); + } + + /* Check the crc32 value of the uncompressed data of the current + * member */ + if (state->crc32 != archive_le32dec(f)) { + archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC, + "Lzip: CRC32 error"); + return (ARCHIVE_FAILED); + } + + /* Check the uncompressed size of the current member */ + if ((uint64_t)state->member_out != archive_le64dec(f + 4)) { + archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC, + "Lzip: Uncompressed size error"); + return (ARCHIVE_FAILED); + } + + /* Check the total size of the current member */ + if (state->lzip_ver == 1 && + (uint64_t)state->member_in + tail != archive_le64dec(f + 12)) { + archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC, + "Lzip: Member size error"); + return (ARCHIVE_FAILED); + } + __archive_read_filter_consume(self->upstream, tail); + + /* If current lzip data consists of multi member, try decompressing + * a next member. */ + if (lzip_has_member(self->upstream) != 0) { + state->in_stream = 0; + state->crc32 = 0; + state->member_out = 0; + state->member_in = 0; + state->eof = 0; + } + return (ARCHIVE_OK); +} + +/* + * Return the next block of decompressed data. + */ +static ssize_t +xz_filter_read(struct archive_read_filter *self, const void **p) +{ + struct private_data *state; + size_t decompressed; + ssize_t avail_in; + int ret; + + state = (struct private_data *)self->data; + + /* Empty our output buffer. */ + state->stream.next_out = state->out_block; + state->stream.avail_out = state->out_block_size; + + /* Try to fill the output buffer. */ + while (state->stream.avail_out > 0 && !state->eof) { + if (!state->in_stream) { + /* + * Initialize liblzma for lzip + */ + ret = lzip_init(self); + if (ret != ARCHIVE_OK) + return (ret); + state->in_stream = 1; + } + state->stream.next_in = + __archive_read_filter_ahead(self->upstream, 1, &avail_in); + if (state->stream.next_in == NULL && avail_in < 0) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "truncated input"); + return (ARCHIVE_FATAL); + } + state->stream.avail_in = avail_in; + + /* Decompress as much as we can in one pass. */ + ret = lzma_code(&(state->stream), + (state->stream.avail_in == 0)? LZMA_FINISH: LZMA_RUN); + switch (ret) { + case LZMA_STREAM_END: /* Found end of stream. */ + state->eof = 1; + /* FALL THROUGH */ + case LZMA_OK: /* Decompressor made some progress. */ + __archive_read_filter_consume(self->upstream, + avail_in - state->stream.avail_in); + state->member_in += + avail_in - state->stream.avail_in; + break; + default: + set_error(self, ret); + return (ARCHIVE_FATAL); + } + } + + decompressed = state->stream.next_out - state->out_block; + state->total_out += decompressed; + state->member_out += decompressed; + if (decompressed == 0) + *p = NULL; + else { + *p = state->out_block; + if (self->code == ARCHIVE_FILTER_LZIP) { + state->crc32 = lzma_crc32(state->out_block, + decompressed, state->crc32); + if (state->eof) { + ret = lzip_tail(self); + if (ret != ARCHIVE_OK) + return (ret); + } + } + } + return (decompressed); +} + +/* + * Clean up the decompressor. + */ +static int +xz_filter_close(struct archive_read_filter *self) +{ + struct private_data *state; + + state = (struct private_data *)self->data; + lzma_end(&(state->stream)); + free(state->out_block); + free(state); + return (ARCHIVE_OK); +} + +#else + +/* + * + * If we have no suitable library on this system, we can't actually do + * the decompression. We can, however, still detect compressed + * archives and emit a useful message. + * + */ +static int +lzma_bidder_init(struct archive_read_filter *self) +{ + int r; + + r = __archive_read_program(self, "lzma -d -qq"); + /* Note: We set the format here even if __archive_read_program() + * above fails. We do, after all, know what the format is + * even if we weren't able to read it. */ + self->code = ARCHIVE_FILTER_LZMA; + self->name = "lzma"; + return (r); +} + +static int +xz_bidder_init(struct archive_read_filter *self) +{ + int r; + + r = __archive_read_program(self, "xz -d -qq"); + /* Note: We set the format here even if __archive_read_program() + * above fails. We do, after all, know what the format is + * even if we weren't able to read it. */ + self->code = ARCHIVE_FILTER_XZ; + self->name = "xz"; + return (r); +} + +static int +lzip_bidder_init(struct archive_read_filter *self) +{ + int r; + + r = __archive_read_program(self, "lzip -d -q"); + /* Note: We set the format here even if __archive_read_program() + * above fails. We do, after all, know what the format is + * even if we weren't able to read it. */ + self->code = ARCHIVE_FILTER_LZIP; + self->name = "lzip"; + return (r); +} + +#endif /* HAVE_LZMA_H */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_zstd.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_zstd.c new file mode 100644 index 0000000000..af7eeb7c1e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_filter_zstd.c @@ -0,0 +1,296 @@ +/*- + * Copyright (c) 2009-2011 Sean Purcell + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#if HAVE_ZSTD_H +#include <zstd.h> +#endif + +#include "archive.h" +#include "archive_endian.h" +#include "archive_private.h" +#include "archive_read_private.h" + +#if HAVE_ZSTD_H && HAVE_LIBZSTD + +struct private_data { + ZSTD_DStream *dstream; + unsigned char *out_block; + size_t out_block_size; + int64_t total_out; + char in_frame; /* True = in the middle of a zstd frame. */ + char eof; /* True = found end of compressed data. */ +}; + +/* Zstd Filter. */ +static ssize_t zstd_filter_read(struct archive_read_filter *, const void**); +static int zstd_filter_close(struct archive_read_filter *); +#endif + +/* + * Note that we can detect zstd compressed files even if we can't decompress + * them. (In fact, we like detecting them because we can give better error + * messages.) So the bid framework here gets compiled even if no zstd library + * is available. + */ +static int zstd_bidder_bid(struct archive_read_filter_bidder *, + struct archive_read_filter *); +static int zstd_bidder_init(struct archive_read_filter *); + +int +archive_read_support_filter_zstd(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct archive_read_filter_bidder *bidder; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_filter_zstd"); + + if (__archive_read_get_bidder(a, &bidder) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + bidder->data = NULL; + bidder->name = "zstd"; + bidder->bid = zstd_bidder_bid; + bidder->init = zstd_bidder_init; + bidder->options = NULL; + bidder->free = NULL; +#if HAVE_ZSTD_H && HAVE_LIBZSTD + return (ARCHIVE_OK); +#else + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "Using external zstd program for zstd decompression"); + return (ARCHIVE_WARN); +#endif +} + +/* + * Test whether we can handle this data. + */ +static int +zstd_bidder_bid(struct archive_read_filter_bidder *self, + struct archive_read_filter *filter) +{ + const unsigned char *buffer; + ssize_t avail; + unsigned prefix; + + /* Zstd frame magic values */ + const unsigned zstd_magic = 0xFD2FB528U; + const unsigned zstd_magic_skippable_start = 0x184D2A50U; + const unsigned zstd_magic_skippable_mask = 0xFFFFFFF0; + + (void) self; /* UNUSED */ + + buffer = __archive_read_filter_ahead(filter, 4, &avail); + if (buffer == NULL) + return (0); + + prefix = archive_le32dec(buffer); + if (prefix == zstd_magic) + return (32); + if ((prefix & zstd_magic_skippable_mask) == zstd_magic_skippable_start) + return (32); + + return (0); +} + +#if !(HAVE_ZSTD_H && HAVE_LIBZSTD) + +/* + * If we don't have the library on this system, we can't do the + * decompression directly. We can, however, try to run "zstd -d" + * in case that's available. + */ +static int +zstd_bidder_init(struct archive_read_filter *self) +{ + int r; + + r = __archive_read_program(self, "zstd -d -qq"); + /* Note: We set the format here even if __archive_read_program() + * above fails. We do, after all, know what the format is + * even if we weren't able to read it. */ + self->code = ARCHIVE_FILTER_ZSTD; + self->name = "zstd"; + return (r); +} + +#else + +/* + * Initialize the filter object + */ +static int +zstd_bidder_init(struct archive_read_filter *self) +{ + struct private_data *state; + const size_t out_block_size = ZSTD_DStreamOutSize(); + void *out_block; + ZSTD_DStream *dstream; + + self->code = ARCHIVE_FILTER_ZSTD; + self->name = "zstd"; + + state = (struct private_data *)calloc(sizeof(*state), 1); + out_block = (unsigned char *)malloc(out_block_size); + dstream = ZSTD_createDStream(); + + if (state == NULL || out_block == NULL || dstream == NULL) { + free(out_block); + free(state); + ZSTD_freeDStream(dstream); /* supports free on NULL */ + archive_set_error(&self->archive->archive, ENOMEM, + "Can't allocate data for zstd decompression"); + return (ARCHIVE_FATAL); + } + + self->data = state; + + state->out_block_size = out_block_size; + state->out_block = out_block; + state->dstream = dstream; + self->read = zstd_filter_read; + self->skip = NULL; /* not supported */ + self->close = zstd_filter_close; + + state->eof = 0; + state->in_frame = 0; + + return (ARCHIVE_OK); +} + +static ssize_t +zstd_filter_read(struct archive_read_filter *self, const void **p) +{ + struct private_data *state; + size_t decompressed; + ssize_t avail_in; + ZSTD_outBuffer out; + ZSTD_inBuffer in; + + state = (struct private_data *)self->data; + + out = (ZSTD_outBuffer) { state->out_block, state->out_block_size, 0 }; + + /* Try to fill the output buffer. */ + while (out.pos < out.size && !state->eof) { + if (!state->in_frame) { + const size_t ret = ZSTD_initDStream(state->dstream); + if (ZSTD_isError(ret)) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Error initializing zstd decompressor: %s", + ZSTD_getErrorName(ret)); + return (ARCHIVE_FATAL); + } + } + in.src = __archive_read_filter_ahead(self->upstream, 1, + &avail_in); + if (avail_in < 0) { + return avail_in; + } + if (in.src == NULL && avail_in == 0) { + if (!state->in_frame) { + /* end of stream */ + state->eof = 1; + break; + } else { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Truncated zstd input"); + return (ARCHIVE_FATAL); + } + } + in.size = avail_in; + in.pos = 0; + + { + const size_t ret = + ZSTD_decompressStream(state->dstream, &out, &in); + + if (ZSTD_isError(ret)) { + archive_set_error(&self->archive->archive, + ARCHIVE_ERRNO_MISC, + "Zstd decompression failed: %s", + ZSTD_getErrorName(ret)); + return (ARCHIVE_FATAL); + } + + /* Decompressor made some progress */ + __archive_read_filter_consume(self->upstream, in.pos); + + /* ret guaranteed to be > 0 if frame isn't done yet */ + state->in_frame = (ret != 0); + } + } + + decompressed = out.pos; + state->total_out += decompressed; + if (decompressed == 0) + *p = NULL; + else + *p = state->out_block; + return (decompressed); +} + +/* + * Clean up the decompressor. + */ +static int +zstd_filter_close(struct archive_read_filter *self) +{ + struct private_data *state; + + state = (struct private_data *)self->data; + + ZSTD_freeDStream(state->dstream); + free(state->out_block); + free(state); + + return (ARCHIVE_OK); +} + +#endif /* HAVE_ZLIB_H && HAVE_LIBZSTD */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_7zip.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_7zip.c new file mode 100644 index 0000000000..6ce9d1a0e1 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_7zip.c @@ -0,0 +1,3873 @@ +/*- + * Copyright (c) 2011 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_BZLIB_H +#include <bzlib.h> +#endif +#ifdef HAVE_LZMA_H +#include <lzma.h> +#endif +#ifdef HAVE_ZLIB_H +#include <zlib.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_ppmd7_private.h" +#include "archive_private.h" +#include "archive_read_private.h" +#include "archive_endian.h" + +#ifndef HAVE_ZLIB_H +#include "archive_crc32.h" +#endif + +#define _7ZIP_SIGNATURE "7z\xBC\xAF\x27\x1C" +#define SFX_MIN_ADDR 0x27000 +#define SFX_MAX_ADDR 0x60000 + + +/* + * Codec ID + */ +#define _7Z_COPY 0 +#define _7Z_LZMA 0x030101 +#define _7Z_LZMA2 0x21 +#define _7Z_DEFLATE 0x040108 +#define _7Z_BZ2 0x040202 +#define _7Z_PPMD 0x030401 +#define _7Z_DELTA 0x03 +#define _7Z_CRYPTO_MAIN_ZIP 0x06F10101 /* Main Zip crypto algo */ +#define _7Z_CRYPTO_RAR_29 0x06F10303 /* Rar29 AES-128 + (modified SHA-1) */ +#define _7Z_CRYPTO_AES_256_SHA_256 0x06F10701 /* AES-256 + SHA-256 */ + + +#define _7Z_X86 0x03030103 +#define _7Z_X86_BCJ2 0x0303011B +#define _7Z_POWERPC 0x03030205 +#define _7Z_IA64 0x03030401 +#define _7Z_ARM 0x03030501 +#define _7Z_ARMTHUMB 0x03030701 +#define _7Z_SPARC 0x03030805 + +/* + * 7-Zip header property IDs. + */ +#define kEnd 0x00 +#define kHeader 0x01 +#define kArchiveProperties 0x02 +#define kAdditionalStreamsInfo 0x03 +#define kMainStreamsInfo 0x04 +#define kFilesInfo 0x05 +#define kPackInfo 0x06 +#define kUnPackInfo 0x07 +#define kSubStreamsInfo 0x08 +#define kSize 0x09 +#define kCRC 0x0A +#define kFolder 0x0B +#define kCodersUnPackSize 0x0C +#define kNumUnPackStream 0x0D +#define kEmptyStream 0x0E +#define kEmptyFile 0x0F +#define kAnti 0x10 +#define kName 0x11 +#define kCTime 0x12 +#define kATime 0x13 +#define kMTime 0x14 +#define kAttributes 0x15 +#define kEncodedHeader 0x17 +#define kDummy 0x19 + +struct _7z_digests { + unsigned char *defineds; + uint32_t *digests; +}; + + +struct _7z_folder { + uint64_t numCoders; + struct _7z_coder { + unsigned long codec; + uint64_t numInStreams; + uint64_t numOutStreams; + uint64_t propertiesSize; + unsigned char *properties; + } *coders; + uint64_t numBindPairs; + struct { + uint64_t inIndex; + uint64_t outIndex; + } *bindPairs; + uint64_t numPackedStreams; + uint64_t *packedStreams; + uint64_t numInStreams; + uint64_t numOutStreams; + uint64_t *unPackSize; + unsigned char digest_defined; + uint32_t digest; + uint64_t numUnpackStreams; + uint32_t packIndex; + /* Unoperated bytes. */ + uint64_t skipped_bytes; +}; + +struct _7z_coders_info { + uint64_t numFolders; + struct _7z_folder *folders; + uint64_t dataStreamIndex; +}; + +struct _7z_pack_info { + uint64_t pos; + uint64_t numPackStreams; + uint64_t *sizes; + struct _7z_digests digest; + /* Calculated from pos and numPackStreams. */ + uint64_t *positions; +}; + +struct _7z_substream_info { + size_t unpack_streams; + uint64_t *unpackSizes; + unsigned char *digestsDefined; + uint32_t *digests; +}; + +struct _7z_stream_info { + struct _7z_pack_info pi; + struct _7z_coders_info ci; + struct _7z_substream_info ss; +}; + +struct _7z_header_info { + uint64_t dataIndex; + + unsigned char *emptyStreamBools; + unsigned char *emptyFileBools; + unsigned char *antiBools; + unsigned char *attrBools; +}; + +struct _7zip_entry { + size_t name_len; + unsigned char *utf16name; +#if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG) + const wchar_t *wname; +#endif + uint32_t folderIndex; + uint32_t ssIndex; + unsigned flg; +#define MTIME_IS_SET (1<<0) +#define ATIME_IS_SET (1<<1) +#define CTIME_IS_SET (1<<2) +#define CRC32_IS_SET (1<<3) +#define HAS_STREAM (1<<4) + + time_t mtime; + time_t atime; + time_t ctime; + long mtime_ns; + long atime_ns; + long ctime_ns; + uint32_t mode; + uint32_t attr; +}; + +struct _7zip { + /* Structural information about the archive. */ + struct _7z_stream_info si; + + int header_is_being_read; + int header_is_encoded; + uint64_t header_bytes_remaining; + unsigned long header_crc32; + /* Header offset to check that reading points of the file contents + * will not exceed the header. */ + uint64_t header_offset; + /* Base offset of the archive file for a seek in case reading SFX. */ + uint64_t seek_base; + + /* List of entries */ + size_t entries_remaining; + uint64_t numFiles; + struct _7zip_entry *entries; + struct _7zip_entry *entry; + unsigned char *entry_names; + + /* entry_bytes_remaining is the number of bytes we expect. */ + int64_t entry_offset; + uint64_t entry_bytes_remaining; + + /* Running CRC32 of the decompressed data */ + unsigned long entry_crc32; + + /* Flags to mark progress of decompression. */ + char end_of_entry; + + /* Uncompressed buffer control. */ +#define UBUFF_SIZE (64 * 1024) + unsigned char *uncompressed_buffer; + unsigned char *uncompressed_buffer_pointer; + size_t uncompressed_buffer_size; + size_t uncompressed_buffer_bytes_remaining; + + /* Offset of the compressed data. */ + int64_t stream_offset; + + /* + * Decompressing control data. + */ + unsigned folder_index; + uint64_t folder_outbytes_remaining; + unsigned pack_stream_index; + unsigned pack_stream_remaining; + uint64_t pack_stream_inbytes_remaining; + size_t pack_stream_bytes_unconsumed; + + /* The codec information of a folder. */ + unsigned long codec; + unsigned long codec2; + + /* + * Decompressor controllers. + */ + /* Decoding LZMA1 and LZMA2 data. */ +#ifdef HAVE_LZMA_H + lzma_stream lzstream; + int lzstream_valid; +#endif + /* Decoding bzip2 data. */ +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) + bz_stream bzstream; + int bzstream_valid; +#endif + /* Decoding deflate data. */ +#ifdef HAVE_ZLIB_H + z_stream stream; + int stream_valid; +#endif + /* Decoding PPMd data. */ + int ppmd7_stat; + CPpmd7 ppmd7_context; + CPpmd7z_RangeDec range_dec; + IByteIn bytein; + struct { + const unsigned char *next_in; + int64_t avail_in; + int64_t total_in; + unsigned char *next_out; + int64_t avail_out; + int64_t total_out; + int overconsumed; + } ppstream; + int ppmd7_valid; + + /* Decoding BCJ and BCJ2 data. */ + uint32_t bcj_state; + size_t odd_bcj_size; + unsigned char odd_bcj[4]; + /* Decoding BCJ data. */ + size_t bcj_prevPosT; + uint32_t bcj_prevMask; + uint32_t bcj_ip; + + /* Decoding BCJ2 data. */ + size_t main_stream_bytes_remaining; + unsigned char *sub_stream_buff[3]; + size_t sub_stream_size[3]; + size_t sub_stream_bytes_remaining[3]; + unsigned char *tmp_stream_buff; + size_t tmp_stream_buff_size; + size_t tmp_stream_bytes_avail; + size_t tmp_stream_bytes_remaining; +#ifdef _LZMA_PROB32 +#define CProb uint32_t +#else +#define CProb uint16_t +#endif + CProb bcj2_p[256 + 2]; + uint8_t bcj2_prevByte; + uint32_t bcj2_range; + uint32_t bcj2_code; + uint64_t bcj2_outPos; + + /* Filename character-set conversion data. */ + struct archive_string_conv *sconv; + + char format_name[64]; + + /* Custom value that is non-zero if this archive contains encrypted entries. */ + int has_encrypted_entries; +}; + +/* Maximum entry size. This limitation prevents reading intentional + * corrupted 7-zip files on assuming there are not so many entries in + * the files. */ +#define UMAX_ENTRY ARCHIVE_LITERAL_ULL(100000000) + +static int archive_read_format_7zip_has_encrypted_entries(struct archive_read *); +static int archive_read_support_format_7zip_capabilities(struct archive_read *a); +static int archive_read_format_7zip_bid(struct archive_read *, int); +static int archive_read_format_7zip_cleanup(struct archive_read *); +static int archive_read_format_7zip_read_data(struct archive_read *, + const void **, size_t *, int64_t *); +static int archive_read_format_7zip_read_data_skip(struct archive_read *); +static int archive_read_format_7zip_read_header(struct archive_read *, + struct archive_entry *); +static int check_7zip_header_in_sfx(const char *); +static unsigned long decode_codec_id(const unsigned char *, size_t); +static int decode_encoded_header_info(struct archive_read *, + struct _7z_stream_info *); +static int decompress(struct archive_read *, struct _7zip *, + void *, size_t *, const void *, size_t *); +static ssize_t extract_pack_stream(struct archive_read *, size_t); +static void fileTimeToUtc(uint64_t, time_t *, long *); +static uint64_t folder_uncompressed_size(struct _7z_folder *); +static void free_CodersInfo(struct _7z_coders_info *); +static void free_Digest(struct _7z_digests *); +static void free_Folder(struct _7z_folder *); +static void free_Header(struct _7z_header_info *); +static void free_PackInfo(struct _7z_pack_info *); +static void free_StreamsInfo(struct _7z_stream_info *); +static void free_SubStreamsInfo(struct _7z_substream_info *); +static int free_decompression(struct archive_read *, struct _7zip *); +static ssize_t get_uncompressed_data(struct archive_read *, const void **, + size_t, size_t); +static const unsigned char * header_bytes(struct archive_read *, size_t); +static int init_decompression(struct archive_read *, struct _7zip *, + const struct _7z_coder *, const struct _7z_coder *); +static int parse_7zip_uint64(struct archive_read *, uint64_t *); +static int read_Bools(struct archive_read *, unsigned char *, size_t); +static int read_CodersInfo(struct archive_read *, + struct _7z_coders_info *); +static int read_Digests(struct archive_read *, struct _7z_digests *, + size_t); +static int read_Folder(struct archive_read *, struct _7z_folder *); +static int read_Header(struct archive_read *, struct _7z_header_info *, + int); +static int read_PackInfo(struct archive_read *, struct _7z_pack_info *); +static int read_StreamsInfo(struct archive_read *, + struct _7z_stream_info *); +static int read_SubStreamsInfo(struct archive_read *, + struct _7z_substream_info *, struct _7z_folder *, size_t); +static int read_Times(struct archive_read *, struct _7z_header_info *, + int); +static void read_consume(struct archive_read *); +static ssize_t read_stream(struct archive_read *, const void **, size_t, + size_t); +static int seek_pack(struct archive_read *); +static int64_t skip_stream(struct archive_read *, size_t); +static int skip_sfx(struct archive_read *, ssize_t); +static int slurp_central_directory(struct archive_read *, struct _7zip *, + struct _7z_header_info *); +static int setup_decode_folder(struct archive_read *, struct _7z_folder *, + int); +static void x86_Init(struct _7zip *); +static size_t x86_Convert(struct _7zip *, uint8_t *, size_t); +static ssize_t Bcj2_Decode(struct _7zip *, uint8_t *, size_t); + + +int +archive_read_support_format_7zip(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct _7zip *zip; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_7zip"); + + zip = calloc(1, sizeof(*zip)); + if (zip == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate 7zip data"); + return (ARCHIVE_FATAL); + } + + /* + * Until enough data has been read, we cannot tell about + * any encrypted entries yet. + */ + zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; + + + r = __archive_read_register_format(a, + zip, + "7zip", + archive_read_format_7zip_bid, + NULL, + archive_read_format_7zip_read_header, + archive_read_format_7zip_read_data, + archive_read_format_7zip_read_data_skip, + NULL, + archive_read_format_7zip_cleanup, + archive_read_support_format_7zip_capabilities, + archive_read_format_7zip_has_encrypted_entries); + + if (r != ARCHIVE_OK) + free(zip); + return (ARCHIVE_OK); +} + +static int +archive_read_support_format_7zip_capabilities(struct archive_read * a) +{ + (void)a; /* UNUSED */ + return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA | + ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA); +} + + +static int +archive_read_format_7zip_has_encrypted_entries(struct archive_read *_a) +{ + if (_a && _a->format) { + struct _7zip * zip = (struct _7zip *)_a->format->data; + if (zip) { + return zip->has_encrypted_entries; + } + } + return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; +} + +static int +archive_read_format_7zip_bid(struct archive_read *a, int best_bid) +{ + const char *p; + + /* If someone has already bid more than 32, then avoid + trashing the look-ahead buffers with a seek. */ + if (best_bid > 32) + return (-1); + + if ((p = __archive_read_ahead(a, 6, NULL)) == NULL) + return (0); + + /* If first six bytes are the 7-Zip signature, + * return the bid right now. */ + if (memcmp(p, _7ZIP_SIGNATURE, 6) == 0) + return (48); + + /* + * It may a 7-Zip SFX archive file. If first two bytes are + * 'M' and 'Z' available on Windows or first four bytes are + * "\x7F\x45LF" available on posix like system, seek the 7-Zip + * signature. Although we will perform a seek when reading + * a header, what we do not use __archive_read_seek() here is + * due to a bidding performance. + */ + if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) { + ssize_t offset = SFX_MIN_ADDR; + ssize_t window = 4096; + ssize_t bytes_avail; + while (offset + window <= (SFX_MAX_ADDR)) { + const char *buff = __archive_read_ahead(a, + offset + window, &bytes_avail); + if (buff == NULL) { + /* Remaining bytes are less than window. */ + window >>= 1; + if (window < 0x40) + return (0); + continue; + } + p = buff + offset; + while (p + 32 < buff + bytes_avail) { + int step = check_7zip_header_in_sfx(p); + if (step == 0) + return (48); + p += step; + } + offset = p - buff; + } + } + return (0); +} + +static int +check_7zip_header_in_sfx(const char *p) +{ + switch ((unsigned char)p[5]) { + case 0x1C: + if (memcmp(p, _7ZIP_SIGNATURE, 6) != 0) + return (6); + /* + * Test the CRC because its extraction code has 7-Zip + * Magic Code, so we should do this in order not to + * make a mis-detection. + */ + if (crc32(0, (const unsigned char *)p + 12, 20) + != archive_le32dec(p + 8)) + return (6); + /* Hit the header! */ + return (0); + case 0x37: return (5); + case 0x7A: return (4); + case 0xBC: return (3); + case 0xAF: return (2); + case 0x27: return (1); + default: return (6); + } +} + +static int +skip_sfx(struct archive_read *a, ssize_t bytes_avail) +{ + const void *h; + const char *p, *q; + size_t skip, offset; + ssize_t bytes, window; + + /* + * If bytes_avail > SFX_MIN_ADDR we do not have to call + * __archive_read_seek() at this time since we have + * already had enough data. + */ + if (bytes_avail > SFX_MIN_ADDR) + __archive_read_consume(a, SFX_MIN_ADDR); + else if (__archive_read_seek(a, SFX_MIN_ADDR, SEEK_SET) < 0) + return (ARCHIVE_FATAL); + + offset = 0; + window = 1; + while (offset + window <= SFX_MAX_ADDR - SFX_MIN_ADDR) { + h = __archive_read_ahead(a, window, &bytes); + if (h == NULL) { + /* Remaining bytes are less than window. */ + window >>= 1; + if (window < 0x40) + goto fatal; + continue; + } + if (bytes < 6) { + /* This case might happen when window == 1. */ + window = 4096; + continue; + } + p = (const char *)h; + q = p + bytes; + + /* + * Scan ahead until we find something that looks + * like the 7-Zip header. + */ + while (p + 32 < q) { + int step = check_7zip_header_in_sfx(p); + if (step == 0) { + struct _7zip *zip = + (struct _7zip *)a->format->data; + skip = p - (const char *)h; + __archive_read_consume(a, skip); + zip->seek_base = SFX_MIN_ADDR + offset + skip; + return (ARCHIVE_OK); + } + p += step; + } + skip = p - (const char *)h; + __archive_read_consume(a, skip); + offset += skip; + if (window == 1) + window = 4096; + } +fatal: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Couldn't find out 7-Zip header"); + return (ARCHIVE_FATAL); +} + +static int +archive_read_format_7zip_read_header(struct archive_read *a, + struct archive_entry *entry) +{ + struct _7zip *zip = (struct _7zip *)a->format->data; + struct _7zip_entry *zip_entry; + int r, ret = ARCHIVE_OK; + struct _7z_folder *folder = 0; + uint64_t fidx = 0; + + /* + * It should be sufficient to call archive_read_next_header() for + * a reader to determine if an entry is encrypted or not. If the + * encryption of an entry is only detectable when calling + * archive_read_data(), so be it. We'll do the same check there + * as well. + */ + if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { + zip->has_encrypted_entries = 0; + } + + a->archive.archive_format = ARCHIVE_FORMAT_7ZIP; + if (a->archive.archive_format_name == NULL) + a->archive.archive_format_name = "7-Zip"; + + if (zip->entries == NULL) { + struct _7z_header_info header; + + memset(&header, 0, sizeof(header)); + r = slurp_central_directory(a, zip, &header); + free_Header(&header); + if (r != ARCHIVE_OK) + return (r); + zip->entries_remaining = (size_t)zip->numFiles; + zip->entry = zip->entries; + } else { + ++zip->entry; + } + zip_entry = zip->entry; + + if (zip->entries_remaining <= 0 || zip_entry == NULL) + return ARCHIVE_EOF; + --zip->entries_remaining; + + zip->entry_offset = 0; + zip->end_of_entry = 0; + zip->entry_crc32 = crc32(0, NULL, 0); + + /* Setup a string conversion for a filename. */ + if (zip->sconv == NULL) { + zip->sconv = archive_string_conversion_from_charset( + &a->archive, "UTF-16LE", 1); + if (zip->sconv == NULL) + return (ARCHIVE_FATAL); + } + + /* Figure out if the entry is encrypted by looking at the folder + that is associated to the current 7zip entry. If the folder + has a coder with a _7Z_CRYPTO codec then the folder is encrypted. + Hence the entry must also be encrypted. */ + if (zip_entry && zip_entry->folderIndex < zip->si.ci.numFolders) { + folder = &(zip->si.ci.folders[zip_entry->folderIndex]); + for (fidx=0; folder && fidx<folder->numCoders; fidx++) { + switch(folder->coders[fidx].codec) { + case _7Z_CRYPTO_MAIN_ZIP: + case _7Z_CRYPTO_RAR_29: + case _7Z_CRYPTO_AES_256_SHA_256: { + archive_entry_set_is_data_encrypted(entry, 1); + zip->has_encrypted_entries = 1; + break; + } + } + } + } + + /* Now that we've checked for encryption, if there were still no + * encrypted entries found we can say for sure that there are none. + */ + if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { + zip->has_encrypted_entries = 0; + } + + if (archive_entry_copy_pathname_l(entry, + (const char *)zip_entry->utf16name, + zip_entry->name_len, zip->sconv) != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Pathname cannot be converted " + "from %s to current locale.", + archive_string_conversion_charset_name(zip->sconv)); + ret = ARCHIVE_WARN; + } + + /* Populate some additional entry fields: */ + archive_entry_set_mode(entry, zip_entry->mode); + if (zip_entry->flg & MTIME_IS_SET) + archive_entry_set_mtime(entry, zip_entry->mtime, + zip_entry->mtime_ns); + if (zip_entry->flg & CTIME_IS_SET) + archive_entry_set_ctime(entry, zip_entry->ctime, + zip_entry->ctime_ns); + if (zip_entry->flg & ATIME_IS_SET) + archive_entry_set_atime(entry, zip_entry->atime, + zip_entry->atime_ns); + if (zip_entry->ssIndex != (uint32_t)-1) { + zip->entry_bytes_remaining = + zip->si.ss.unpackSizes[zip_entry->ssIndex]; + archive_entry_set_size(entry, zip->entry_bytes_remaining); + } else { + zip->entry_bytes_remaining = 0; + archive_entry_set_size(entry, 0); + } + + /* If there's no body, force read_data() to return EOF immediately. */ + if (zip->entry_bytes_remaining < 1) + zip->end_of_entry = 1; + + if ((zip_entry->mode & AE_IFMT) == AE_IFLNK) { + unsigned char *symname = NULL; + size_t symsize = 0; + + /* + * Symbolic-name is recorded as its contents. We have to + * read the contents at this time. + */ + while (zip->entry_bytes_remaining > 0) { + const void *buff; + unsigned char *mem; + size_t size; + int64_t offset; + + r = archive_read_format_7zip_read_data(a, &buff, + &size, &offset); + if (r < ARCHIVE_WARN) { + free(symname); + return (r); + } + mem = realloc(symname, symsize + size + 1); + if (mem == NULL) { + free(symname); + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Symname"); + return (ARCHIVE_FATAL); + } + symname = mem; + memcpy(symname+symsize, buff, size); + symsize += size; + } + if (symsize == 0) { + /* If there is no symname, handle it as a regular + * file. */ + zip_entry->mode &= ~AE_IFMT; + zip_entry->mode |= AE_IFREG; + archive_entry_set_mode(entry, zip_entry->mode); + } else { + symname[symsize] = '\0'; + archive_entry_copy_symlink(entry, + (const char *)symname); + } + free(symname); + archive_entry_set_size(entry, 0); + } + + /* Set up a more descriptive format name. */ + sprintf(zip->format_name, "7-Zip"); + a->archive.archive_format_name = zip->format_name; + + return (ret); +} + +static int +archive_read_format_7zip_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + struct _7zip *zip; + ssize_t bytes; + int ret = ARCHIVE_OK; + + zip = (struct _7zip *)(a->format->data); + + if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { + zip->has_encrypted_entries = 0; + } + + if (zip->pack_stream_bytes_unconsumed) + read_consume(a); + + *offset = zip->entry_offset; + *size = 0; + *buff = NULL; + /* + * If we hit end-of-entry last time, clean up and return + * ARCHIVE_EOF this time. + */ + if (zip->end_of_entry) + return (ARCHIVE_EOF); + + bytes = read_stream(a, buff, + (size_t)zip->entry_bytes_remaining, 0); + if (bytes < 0) + return ((int)bytes); + if (bytes == 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated 7-Zip file body"); + return (ARCHIVE_FATAL); + } + zip->entry_bytes_remaining -= bytes; + if (zip->entry_bytes_remaining == 0) + zip->end_of_entry = 1; + + /* Update checksum */ + if ((zip->entry->flg & CRC32_IS_SET) && bytes) + zip->entry_crc32 = crc32(zip->entry_crc32, *buff, + (unsigned)bytes); + + /* If we hit the end, swallow any end-of-data marker. */ + if (zip->end_of_entry) { + /* Check computed CRC against file contents. */ + if ((zip->entry->flg & CRC32_IS_SET) && + zip->si.ss.digests[zip->entry->ssIndex] != + zip->entry_crc32) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "7-Zip bad CRC: 0x%lx should be 0x%lx", + (unsigned long)zip->entry_crc32, + (unsigned long)zip->si.ss.digests[ + zip->entry->ssIndex]); + ret = ARCHIVE_WARN; + } + } + + *size = bytes; + *offset = zip->entry_offset; + zip->entry_offset += bytes; + + return (ret); +} + +static int +archive_read_format_7zip_read_data_skip(struct archive_read *a) +{ + struct _7zip *zip; + int64_t bytes_skipped; + + zip = (struct _7zip *)(a->format->data); + + if (zip->pack_stream_bytes_unconsumed) + read_consume(a); + + /* If we've already read to end of data, we're done. */ + if (zip->end_of_entry) + return (ARCHIVE_OK); + + /* + * If the length is at the beginning, we can skip the + * compressed data much more quickly. + */ + bytes_skipped = skip_stream(a, (size_t)zip->entry_bytes_remaining); + if (bytes_skipped < 0) + return (ARCHIVE_FATAL); + zip->entry_bytes_remaining = 0; + + /* This entry is finished and done. */ + zip->end_of_entry = 1; + return (ARCHIVE_OK); +} + +static int +archive_read_format_7zip_cleanup(struct archive_read *a) +{ + struct _7zip *zip; + + zip = (struct _7zip *)(a->format->data); + free_StreamsInfo(&(zip->si)); + free(zip->entries); + free(zip->entry_names); + free_decompression(a, zip); + free(zip->uncompressed_buffer); + free(zip->sub_stream_buff[0]); + free(zip->sub_stream_buff[1]); + free(zip->sub_stream_buff[2]); + free(zip->tmp_stream_buff); + free(zip); + (a->format->data) = NULL; + return (ARCHIVE_OK); +} + +static void +read_consume(struct archive_read *a) +{ + struct _7zip *zip = (struct _7zip *)a->format->data; + + if (zip->pack_stream_bytes_unconsumed) { + __archive_read_consume(a, zip->pack_stream_bytes_unconsumed); + zip->stream_offset += zip->pack_stream_bytes_unconsumed; + zip->pack_stream_bytes_unconsumed = 0; + } +} + +#ifdef HAVE_LZMA_H + +/* + * Set an error code and choose an error message for liblzma. + */ +static void +set_error(struct archive_read *a, int ret) +{ + + switch (ret) { + case LZMA_STREAM_END: /* Found end of stream. */ + case LZMA_OK: /* Decompressor made some progress. */ + break; + case LZMA_MEM_ERROR: + archive_set_error(&a->archive, ENOMEM, + "Lzma library error: Cannot allocate memory"); + break; + case LZMA_MEMLIMIT_ERROR: + archive_set_error(&a->archive, ENOMEM, + "Lzma library error: Out of memory"); + break; + case LZMA_FORMAT_ERROR: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Lzma library error: format not recognized"); + break; + case LZMA_OPTIONS_ERROR: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Lzma library error: Invalid options"); + break; + case LZMA_DATA_ERROR: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Lzma library error: Corrupted input data"); + break; + case LZMA_BUF_ERROR: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Lzma library error: No progress is possible"); + break; + default: + /* Return an error. */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Lzma decompression failed: Unknown error"); + break; + } +} + +#endif + +static unsigned long +decode_codec_id(const unsigned char *codecId, size_t id_size) +{ + unsigned i; + unsigned long id = 0; + + for (i = 0; i < id_size; i++) { + id <<= 8; + id += codecId[i]; + } + return (id); +} + +static Byte +ppmd_read(void *p) +{ + struct archive_read *a = ((IByteIn*)p)->a; + struct _7zip *zip = (struct _7zip *)(a->format->data); + Byte b; + + if (zip->ppstream.avail_in == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated RAR file data"); + zip->ppstream.overconsumed = 1; + return (0); + } + b = *zip->ppstream.next_in++; + zip->ppstream.avail_in--; + zip->ppstream.total_in++; + return (b); +} + +static int +init_decompression(struct archive_read *a, struct _7zip *zip, + const struct _7z_coder *coder1, const struct _7z_coder *coder2) +{ + int r; + + zip->codec = coder1->codec; + zip->codec2 = -1; + + switch (zip->codec) { + case _7Z_COPY: + case _7Z_BZ2: + case _7Z_DEFLATE: + case _7Z_PPMD: + if (coder2 != NULL) { + if (coder2->codec != _7Z_X86 && + coder2->codec != _7Z_X86_BCJ2) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Unsupported filter %lx for %lx", + coder2->codec, coder1->codec); + return (ARCHIVE_FAILED); + } + zip->codec2 = coder2->codec; + zip->bcj_state = 0; + if (coder2->codec == _7Z_X86) + x86_Init(zip); + } + break; + default: + break; + } + + switch (zip->codec) { + case _7Z_COPY: + break; + + case _7Z_LZMA: case _7Z_LZMA2: +#ifdef HAVE_LZMA_H +#if LZMA_VERSION_MAJOR >= 5 +/* Effectively disable the limiter. */ +#define LZMA_MEMLIMIT UINT64_MAX +#else +/* NOTE: This needs to check memory size which running system has. */ +#define LZMA_MEMLIMIT (1U << 30) +#endif + { + lzma_options_delta delta_opt; + lzma_filter filters[LZMA_FILTERS_MAX], *ff; + int fi = 0; + + if (zip->lzstream_valid) { + lzma_end(&(zip->lzstream)); + zip->lzstream_valid = 0; + } + + /* + * NOTE: liblzma incompletely handle the BCJ+LZMA compressed + * data made by 7-Zip because 7-Zip does not add End-Of- + * Payload Marker(EOPM) at the end of LZMA compressed data, + * and so liblzma cannot know the end of the compressed data + * without EOPM. So consequently liblzma will not return last + * three or four bytes of uncompressed data because + * LZMA_FILTER_X86 filter does not handle input data if its + * data size is less than five bytes. If liblzma detect EOPM + * or know the uncompressed data size, liblzma will flush out + * the remaining that three or four bytes of uncompressed + * data. That is why we have to use our converting program + * for BCJ+LZMA. If we were able to tell the uncompressed + * size to liblzma when using lzma_raw_decoder() liblzma + * could correctly deal with BCJ+LZMA. But unfortunately + * there is no way to do that. + * Discussion about this can be found at XZ Utils forum. + */ + if (coder2 != NULL) { + zip->codec2 = coder2->codec; + + filters[fi].options = NULL; + switch (zip->codec2) { + case _7Z_X86: + if (zip->codec == _7Z_LZMA2) { + filters[fi].id = LZMA_FILTER_X86; + fi++; + } else + /* Use our filter. */ + x86_Init(zip); + break; + case _7Z_X86_BCJ2: + /* Use our filter. */ + zip->bcj_state = 0; + break; + case _7Z_DELTA: + if (coder2->propertiesSize != 1) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Invalid Delta parameter"); + return (ARCHIVE_FAILED); + } + filters[fi].id = LZMA_FILTER_DELTA; + memset(&delta_opt, 0, sizeof(delta_opt)); + delta_opt.type = LZMA_DELTA_TYPE_BYTE; + delta_opt.dist = + (uint32_t)coder2->properties[0] + 1; + filters[fi].options = &delta_opt; + fi++; + break; + /* Following filters have not been tested yet. */ + case _7Z_POWERPC: + filters[fi].id = LZMA_FILTER_POWERPC; + fi++; + break; + case _7Z_IA64: + filters[fi].id = LZMA_FILTER_IA64; + fi++; + break; + case _7Z_ARM: + filters[fi].id = LZMA_FILTER_ARM; + fi++; + break; + case _7Z_ARMTHUMB: + filters[fi].id = LZMA_FILTER_ARMTHUMB; + fi++; + break; + case _7Z_SPARC: + filters[fi].id = LZMA_FILTER_SPARC; + fi++; + break; + default: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Unexpected codec ID: %lX", zip->codec2); + return (ARCHIVE_FAILED); + } + } + + if (zip->codec == _7Z_LZMA2) + filters[fi].id = LZMA_FILTER_LZMA2; + else + filters[fi].id = LZMA_FILTER_LZMA1; + filters[fi].options = NULL; + ff = &filters[fi]; + r = lzma_properties_decode(&filters[fi], NULL, + coder1->properties, (size_t)coder1->propertiesSize); + if (r != LZMA_OK) { + set_error(a, r); + return (ARCHIVE_FAILED); + } + fi++; + + filters[fi].id = LZMA_VLI_UNKNOWN; + filters[fi].options = NULL; + r = lzma_raw_decoder(&(zip->lzstream), filters); + free(ff->options); + if (r != LZMA_OK) { + set_error(a, r); + return (ARCHIVE_FAILED); + } + zip->lzstream_valid = 1; + zip->lzstream.total_in = 0; + zip->lzstream.total_out = 0; + break; + } +#else + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "LZMA codec is unsupported"); + return (ARCHIVE_FAILED); +#endif + case _7Z_BZ2: +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) + if (zip->bzstream_valid) { + BZ2_bzDecompressEnd(&(zip->bzstream)); + zip->bzstream_valid = 0; + } + r = BZ2_bzDecompressInit(&(zip->bzstream), 0, 0); + if (r == BZ_MEM_ERROR) + r = BZ2_bzDecompressInit(&(zip->bzstream), 0, 1); + if (r != BZ_OK) { + int err = ARCHIVE_ERRNO_MISC; + const char *detail = NULL; + switch (r) { + case BZ_PARAM_ERROR: + detail = "invalid setup parameter"; + break; + case BZ_MEM_ERROR: + err = ENOMEM; + detail = "out of memory"; + break; + case BZ_CONFIG_ERROR: + detail = "mis-compiled library"; + break; + } + archive_set_error(&a->archive, err, + "Internal error initializing decompressor: %s", + detail != NULL ? detail : "??"); + zip->bzstream_valid = 0; + return (ARCHIVE_FAILED); + } + zip->bzstream_valid = 1; + zip->bzstream.total_in_lo32 = 0; + zip->bzstream.total_in_hi32 = 0; + zip->bzstream.total_out_lo32 = 0; + zip->bzstream.total_out_hi32 = 0; + break; +#else + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "BZ2 codec is unsupported"); + return (ARCHIVE_FAILED); +#endif + case _7Z_DEFLATE: +#ifdef HAVE_ZLIB_H + if (zip->stream_valid) + r = inflateReset(&(zip->stream)); + else + r = inflateInit2(&(zip->stream), + -15 /* Don't check for zlib header */); + if (r != Z_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Couldn't initialize zlib stream."); + return (ARCHIVE_FAILED); + } + zip->stream_valid = 1; + zip->stream.total_in = 0; + zip->stream.total_out = 0; + break; +#else + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "DEFLATE codec is unsupported"); + return (ARCHIVE_FAILED); +#endif + case _7Z_PPMD: + { + unsigned order; + uint32_t msize; + + if (zip->ppmd7_valid) { + __archive_ppmd7_functions.Ppmd7_Free( + &zip->ppmd7_context); + zip->ppmd7_valid = 0; + } + + if (coder1->propertiesSize < 5) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Malformed PPMd parameter"); + return (ARCHIVE_FAILED); + } + order = coder1->properties[0]; + msize = archive_le32dec(&(coder1->properties[1])); + if (order < PPMD7_MIN_ORDER || order > PPMD7_MAX_ORDER || + msize < PPMD7_MIN_MEM_SIZE || msize > PPMD7_MAX_MEM_SIZE) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Malformed PPMd parameter"); + return (ARCHIVE_FAILED); + } + __archive_ppmd7_functions.Ppmd7_Construct(&zip->ppmd7_context); + r = __archive_ppmd7_functions.Ppmd7_Alloc( + &zip->ppmd7_context, msize); + if (r == 0) { + archive_set_error(&a->archive, ENOMEM, + "Coludn't allocate memory for PPMd"); + return (ARCHIVE_FATAL); + } + __archive_ppmd7_functions.Ppmd7_Init( + &zip->ppmd7_context, order); + __archive_ppmd7_functions.Ppmd7z_RangeDec_CreateVTable( + &zip->range_dec); + zip->ppmd7_valid = 1; + zip->ppmd7_stat = 0; + zip->ppstream.overconsumed = 0; + zip->ppstream.total_in = 0; + zip->ppstream.total_out = 0; + break; + } + case _7Z_X86: + case _7Z_X86_BCJ2: + case _7Z_POWERPC: + case _7Z_IA64: + case _7Z_ARM: + case _7Z_ARMTHUMB: + case _7Z_SPARC: + case _7Z_DELTA: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Unexpected codec ID: %lX", zip->codec); + return (ARCHIVE_FAILED); + case _7Z_CRYPTO_MAIN_ZIP: + case _7Z_CRYPTO_RAR_29: + case _7Z_CRYPTO_AES_256_SHA_256: + if (a->entry) { + archive_entry_set_is_metadata_encrypted(a->entry, 1); + archive_entry_set_is_data_encrypted(a->entry, 1); + zip->has_encrypted_entries = 1; + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Crypto codec not supported yet (ID: 0x%lX)", zip->codec); + return (ARCHIVE_FAILED); + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Unknown codec ID: %lX", zip->codec); + return (ARCHIVE_FAILED); + } + + return (ARCHIVE_OK); +} + +static int +decompress(struct archive_read *a, struct _7zip *zip, + void *buff, size_t *outbytes, const void *b, size_t *used) +{ + const uint8_t *t_next_in; + uint8_t *t_next_out; + size_t o_avail_in, o_avail_out; + size_t t_avail_in, t_avail_out; + uint8_t *bcj2_next_out; + size_t bcj2_avail_out; + int r, ret = ARCHIVE_OK; + + t_avail_in = o_avail_in = *used; + t_avail_out = o_avail_out = *outbytes; + t_next_in = b; + t_next_out = buff; + + if (zip->codec != _7Z_LZMA2 && zip->codec2 == _7Z_X86) { + int i; + + /* Do not copy out the BCJ remaining bytes when the output + * buffer size is less than five bytes. */ + if (o_avail_in != 0 && t_avail_out < 5 && zip->odd_bcj_size) { + *used = 0; + *outbytes = 0; + return (ret); + } + for (i = 0; zip->odd_bcj_size > 0 && t_avail_out; i++) { + *t_next_out++ = zip->odd_bcj[i]; + t_avail_out--; + zip->odd_bcj_size--; + } + if (o_avail_in == 0 || t_avail_out == 0) { + *used = o_avail_in - t_avail_in; + *outbytes = o_avail_out - t_avail_out; + if (o_avail_in == 0) + ret = ARCHIVE_EOF; + return (ret); + } + } + + bcj2_next_out = t_next_out; + bcj2_avail_out = t_avail_out; + if (zip->codec2 == _7Z_X86_BCJ2) { + /* + * Decord a remaining decompressed main stream for BCJ2. + */ + if (zip->tmp_stream_bytes_remaining) { + ssize_t bytes; + size_t remaining = zip->tmp_stream_bytes_remaining; + bytes = Bcj2_Decode(zip, t_next_out, t_avail_out); + if (bytes < 0) { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "BCJ2 conversion Failed"); + return (ARCHIVE_FAILED); + } + zip->main_stream_bytes_remaining -= + remaining - zip->tmp_stream_bytes_remaining; + t_avail_out -= bytes; + if (o_avail_in == 0 || t_avail_out == 0) { + *used = 0; + *outbytes = o_avail_out - t_avail_out; + if (o_avail_in == 0 && + zip->tmp_stream_bytes_remaining) + ret = ARCHIVE_EOF; + return (ret); + } + t_next_out += bytes; + bcj2_next_out = t_next_out; + bcj2_avail_out = t_avail_out; + } + t_next_out = zip->tmp_stream_buff; + t_avail_out = zip->tmp_stream_buff_size; + } + + switch (zip->codec) { + case _7Z_COPY: + { + size_t bytes = + (t_avail_in > t_avail_out)?t_avail_out:t_avail_in; + + memcpy(t_next_out, t_next_in, bytes); + t_avail_in -= bytes; + t_avail_out -= bytes; + if (o_avail_in == 0) + ret = ARCHIVE_EOF; + break; + } +#ifdef HAVE_LZMA_H + case _7Z_LZMA: case _7Z_LZMA2: + zip->lzstream.next_in = t_next_in; + zip->lzstream.avail_in = t_avail_in; + zip->lzstream.next_out = t_next_out; + zip->lzstream.avail_out = t_avail_out; + + r = lzma_code(&(zip->lzstream), LZMA_RUN); + switch (r) { + case LZMA_STREAM_END: /* Found end of stream. */ + lzma_end(&(zip->lzstream)); + zip->lzstream_valid = 0; + ret = ARCHIVE_EOF; + break; + case LZMA_OK: /* Decompressor made some progress. */ + break; + default: + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "Decompression failed(%d)", + r); + return (ARCHIVE_FAILED); + } + t_avail_in = zip->lzstream.avail_in; + t_avail_out = zip->lzstream.avail_out; + break; +#endif +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) + case _7Z_BZ2: + zip->bzstream.next_in = (char *)(uintptr_t)t_next_in; + zip->bzstream.avail_in = t_avail_in; + zip->bzstream.next_out = (char *)(uintptr_t)t_next_out; + zip->bzstream.avail_out = t_avail_out; + r = BZ2_bzDecompress(&(zip->bzstream)); + switch (r) { + case BZ_STREAM_END: /* Found end of stream. */ + switch (BZ2_bzDecompressEnd(&(zip->bzstream))) { + case BZ_OK: + break; + default: + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "Failed to clean up decompressor"); + return (ARCHIVE_FAILED); + } + zip->bzstream_valid = 0; + ret = ARCHIVE_EOF; + break; + case BZ_OK: /* Decompressor made some progress. */ + break; + default: + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "bzip decompression failed"); + return (ARCHIVE_FAILED); + } + t_avail_in = zip->bzstream.avail_in; + t_avail_out = zip->bzstream.avail_out; + break; +#endif +#ifdef HAVE_ZLIB_H + case _7Z_DEFLATE: + zip->stream.next_in = (Bytef *)(uintptr_t)t_next_in; + zip->stream.avail_in = (uInt)t_avail_in; + zip->stream.next_out = t_next_out; + zip->stream.avail_out = (uInt)t_avail_out; + r = inflate(&(zip->stream), 0); + switch (r) { + case Z_STREAM_END: /* Found end of stream. */ + ret = ARCHIVE_EOF; + break; + case Z_OK: /* Decompressor made some progress.*/ + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "File decompression failed (%d)", r); + return (ARCHIVE_FAILED); + } + t_avail_in = zip->stream.avail_in; + t_avail_out = zip->stream.avail_out; + break; +#endif + case _7Z_PPMD: + { + uint64_t flush_bytes; + + if (!zip->ppmd7_valid || zip->ppmd7_stat < 0 || + t_avail_out <= 0) { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "Decompression internal error"); + return (ARCHIVE_FAILED); + } + zip->ppstream.next_in = t_next_in; + zip->ppstream.avail_in = t_avail_in; + zip->ppstream.next_out = t_next_out; + zip->ppstream.avail_out = t_avail_out; + if (zip->ppmd7_stat == 0) { + zip->bytein.a = a; + zip->bytein.Read = &ppmd_read; + zip->range_dec.Stream = &zip->bytein; + r = __archive_ppmd7_functions.Ppmd7z_RangeDec_Init( + &(zip->range_dec)); + if (r == 0) { + zip->ppmd7_stat = -1; + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Failed to initialize PPMd range decorder"); + return (ARCHIVE_FAILED); + } + if (zip->ppstream.overconsumed) { + zip->ppmd7_stat = -1; + return (ARCHIVE_FAILED); + } + zip->ppmd7_stat = 1; + } + + if (t_avail_in == 0) + /* XXX Flush out remaining decoded data XXX */ + flush_bytes = zip->folder_outbytes_remaining; + else + flush_bytes = 0; + + do { + int sym; + + sym = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( + &(zip->ppmd7_context), &(zip->range_dec.p)); + if (sym < 0) { + zip->ppmd7_stat = -1; + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Failed to decode PPMd"); + return (ARCHIVE_FAILED); + } + if (zip->ppstream.overconsumed) { + zip->ppmd7_stat = -1; + return (ARCHIVE_FAILED); + } + *zip->ppstream.next_out++ = (unsigned char)sym; + zip->ppstream.avail_out--; + zip->ppstream.total_out++; + if (flush_bytes) + flush_bytes--; + } while (zip->ppstream.avail_out && + (zip->ppstream.avail_in || flush_bytes)); + + t_avail_in = (size_t)zip->ppstream.avail_in; + t_avail_out = (size_t)zip->ppstream.avail_out; + break; + } + default: + archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, + "Decompression internal error"); + return (ARCHIVE_FAILED); + } + if (ret != ARCHIVE_OK && ret != ARCHIVE_EOF) + return (ret); + + *used = o_avail_in - t_avail_in; + *outbytes = o_avail_out - t_avail_out; + + /* + * Decord BCJ. + */ + if (zip->codec != _7Z_LZMA2 && zip->codec2 == _7Z_X86) { + size_t l = x86_Convert(zip, buff, *outbytes); + zip->odd_bcj_size = *outbytes - l; + if (zip->odd_bcj_size > 0 && zip->odd_bcj_size <= 4 && + o_avail_in && ret != ARCHIVE_EOF) { + memcpy(zip->odd_bcj, ((unsigned char *)buff) + l, + zip->odd_bcj_size); + *outbytes = l; + } else + zip->odd_bcj_size = 0; + } + + /* + * Decord BCJ2 with a decompressed main stream. + */ + if (zip->codec2 == _7Z_X86_BCJ2) { + ssize_t bytes; + + zip->tmp_stream_bytes_avail = + zip->tmp_stream_buff_size - t_avail_out; + if (zip->tmp_stream_bytes_avail > + zip->main_stream_bytes_remaining) + zip->tmp_stream_bytes_avail = + zip->main_stream_bytes_remaining; + zip->tmp_stream_bytes_remaining = zip->tmp_stream_bytes_avail; + bytes = Bcj2_Decode(zip, bcj2_next_out, bcj2_avail_out); + if (bytes < 0) { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, "BCJ2 conversion Failed"); + return (ARCHIVE_FAILED); + } + zip->main_stream_bytes_remaining -= + zip->tmp_stream_bytes_avail + - zip->tmp_stream_bytes_remaining; + bcj2_avail_out -= bytes; + *outbytes = o_avail_out - bcj2_avail_out; + } + + return (ret); +} + +static int +free_decompression(struct archive_read *a, struct _7zip *zip) +{ + int r = ARCHIVE_OK; + +#if !defined(HAVE_ZLIB_H) &&\ + !(defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)) + (void)a;/* UNUSED */ +#endif +#ifdef HAVE_LZMA_H + if (zip->lzstream_valid) + lzma_end(&(zip->lzstream)); +#endif +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) + if (zip->bzstream_valid) { + if (BZ2_bzDecompressEnd(&(zip->bzstream)) != BZ_OK) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Failed to clean up bzip2 decompressor"); + r = ARCHIVE_FATAL; + } + zip->bzstream_valid = 0; + } +#endif +#ifdef HAVE_ZLIB_H + if (zip->stream_valid) { + if (inflateEnd(&(zip->stream)) != Z_OK) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Failed to clean up zlib decompressor"); + r = ARCHIVE_FATAL; + } + zip->stream_valid = 0; + } +#endif + if (zip->ppmd7_valid) { + __archive_ppmd7_functions.Ppmd7_Free( + &zip->ppmd7_context); + zip->ppmd7_valid = 0; + } + return (r); +} + +static int +parse_7zip_uint64(struct archive_read *a, uint64_t *val) +{ + const unsigned char *p; + unsigned char avail, mask; + int i; + + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + avail = *p; + mask = 0x80; + *val = 0; + for (i = 0; i < 8; i++) { + if (avail & mask) { + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + *val |= ((uint64_t)*p) << (8 * i); + mask >>= 1; + continue; + } + *val += ((uint64_t)(avail & (mask -1))) << (8 * i); + break; + } + return (0); +} + +static int +read_Bools(struct archive_read *a, unsigned char *data, size_t num) +{ + const unsigned char *p; + unsigned i, mask = 0, avail = 0; + + for (i = 0; i < num; i++) { + if (mask == 0) { + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + avail = *p; + mask = 0x80; + } + data[i] = (avail & mask)?1:0; + mask >>= 1; + } + return (0); +} + +static void +free_Digest(struct _7z_digests *d) +{ + free(d->defineds); + free(d->digests); +} + +static int +read_Digests(struct archive_read *a, struct _7z_digests *d, size_t num) +{ + const unsigned char *p; + unsigned i; + + if (num == 0) + return (-1); + memset(d, 0, sizeof(*d)); + + d->defineds = malloc(num); + if (d->defineds == NULL) + return (-1); + /* + * Read Bools. + */ + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + if (*p == 0) { + if (read_Bools(a, d->defineds, num) < 0) + return (-1); + } else + /* All are defined */ + memset(d->defineds, 1, num); + + d->digests = calloc(num, sizeof(*d->digests)); + if (d->digests == NULL) + return (-1); + for (i = 0; i < num; i++) { + if (d->defineds[i]) { + if ((p = header_bytes(a, 4)) == NULL) + return (-1); + d->digests[i] = archive_le32dec(p); + } + } + + return (0); +} + +static void +free_PackInfo(struct _7z_pack_info *pi) +{ + free(pi->sizes); + free(pi->positions); + free_Digest(&(pi->digest)); +} + +static int +read_PackInfo(struct archive_read *a, struct _7z_pack_info *pi) +{ + const unsigned char *p; + unsigned i; + + memset(pi, 0, sizeof(*pi)); + + /* + * Read PackPos. + */ + if (parse_7zip_uint64(a, &(pi->pos)) < 0) + return (-1); + + /* + * Read NumPackStreams. + */ + if (parse_7zip_uint64(a, &(pi->numPackStreams)) < 0) + return (-1); + if (pi->numPackStreams == 0) + return (-1); + if (UMAX_ENTRY < pi->numPackStreams) + return (-1); + + /* + * Read PackSizes[num] + */ + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + if (*p == kEnd) + /* PackSizes[num] are not present. */ + return (0); + if (*p != kSize) + return (-1); + pi->sizes = calloc((size_t)pi->numPackStreams, sizeof(uint64_t)); + pi->positions = calloc((size_t)pi->numPackStreams, sizeof(uint64_t)); + if (pi->sizes == NULL || pi->positions == NULL) + return (-1); + + for (i = 0; i < pi->numPackStreams; i++) { + if (parse_7zip_uint64(a, &(pi->sizes[i])) < 0) + return (-1); + } + + /* + * Read PackStreamDigests[num] + */ + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + if (*p == kEnd) { + /* PackStreamDigests[num] are not present. */ + pi->digest.defineds = + calloc((size_t)pi->numPackStreams, sizeof(*pi->digest.defineds)); + pi->digest.digests = + calloc((size_t)pi->numPackStreams, sizeof(*pi->digest.digests)); + if (pi->digest.defineds == NULL || pi->digest.digests == NULL) + return (-1); + return (0); + } + + if (*p != kCRC) + return (-1); + + if (read_Digests(a, &(pi->digest), (size_t)pi->numPackStreams) < 0) + return (-1); + + /* + * Must be marked by kEnd. + */ + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + if (*p != kEnd) + return (-1); + return (0); +} + +static void +free_Folder(struct _7z_folder *f) +{ + unsigned i; + + if (f->coders) { + for (i = 0; i< f->numCoders; i++) { + free(f->coders[i].properties); + } + free(f->coders); + } + free(f->bindPairs); + free(f->packedStreams); + free(f->unPackSize); +} + +static int +read_Folder(struct archive_read *a, struct _7z_folder *f) +{ + struct _7zip *zip = (struct _7zip *)a->format->data; + const unsigned char *p; + uint64_t numInStreamsTotal = 0; + uint64_t numOutStreamsTotal = 0; + unsigned i; + + memset(f, 0, sizeof(*f)); + + /* + * Read NumCoders. + */ + if (parse_7zip_uint64(a, &(f->numCoders)) < 0) + return (-1); + if (f->numCoders > 4) + /* Too many coders. */ + return (-1); + + f->coders = calloc((size_t)f->numCoders, sizeof(*f->coders)); + if (f->coders == NULL) + return (-1); + for (i = 0; i< f->numCoders; i++) { + size_t codec_size; + int simple, attr; + + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + /* + * 0:3 CodecIdSize + * 4: 0 - IsSimple + * 1 - Is not Simple + * 5: 0 - No Attributes + * 1 - There are Attributes; + * 7: Must be zero. + */ + codec_size = *p & 0xf; + simple = (*p & 0x10)?0:1; + attr = *p & 0x20; + if (*p & 0x80) + return (-1);/* Not supported. */ + + /* + * Read Decompression Method IDs. + */ + if ((p = header_bytes(a, codec_size)) == NULL) + return (-1); + + f->coders[i].codec = decode_codec_id(p, codec_size); + + if (simple) { + f->coders[i].numInStreams = 1; + f->coders[i].numOutStreams = 1; + } else { + if (parse_7zip_uint64( + a, &(f->coders[i].numInStreams)) < 0) + return (-1); + if (UMAX_ENTRY < f->coders[i].numInStreams) + return (-1); + if (parse_7zip_uint64( + a, &(f->coders[i].numOutStreams)) < 0) + return (-1); + if (UMAX_ENTRY < f->coders[i].numOutStreams) + return (-1); + } + + if (attr) { + if (parse_7zip_uint64( + a, &(f->coders[i].propertiesSize)) < 0) + return (-1); + if ((p = header_bytes( + a, (size_t)f->coders[i].propertiesSize)) == NULL) + return (-1); + f->coders[i].properties = + malloc((size_t)f->coders[i].propertiesSize); + if (f->coders[i].properties == NULL) + return (-1); + memcpy(f->coders[i].properties, p, + (size_t)f->coders[i].propertiesSize); + } + + numInStreamsTotal += f->coders[i].numInStreams; + numOutStreamsTotal += f->coders[i].numOutStreams; + } + + if (numOutStreamsTotal == 0 || + numInStreamsTotal < numOutStreamsTotal-1) + return (-1); + + f->numBindPairs = numOutStreamsTotal - 1; + if (zip->header_bytes_remaining < f->numBindPairs) + return (-1); + if (f->numBindPairs > 0) { + f->bindPairs = + calloc((size_t)f->numBindPairs, sizeof(*f->bindPairs)); + if (f->bindPairs == NULL) + return (-1); + } else + f->bindPairs = NULL; + for (i = 0; i < f->numBindPairs; i++) { + if (parse_7zip_uint64(a, &(f->bindPairs[i].inIndex)) < 0) + return (-1); + if (UMAX_ENTRY < f->bindPairs[i].inIndex) + return (-1); + if (parse_7zip_uint64(a, &(f->bindPairs[i].outIndex)) < 0) + return (-1); + if (UMAX_ENTRY < f->bindPairs[i].outIndex) + return (-1); + } + + f->numPackedStreams = numInStreamsTotal - f->numBindPairs; + f->packedStreams = + calloc((size_t)f->numPackedStreams, sizeof(*f->packedStreams)); + if (f->packedStreams == NULL) + return (-1); + if (f->numPackedStreams == 1) { + for (i = 0; i < numInStreamsTotal; i++) { + unsigned j; + for (j = 0; j < f->numBindPairs; j++) { + if (f->bindPairs[j].inIndex == i) + break; + } + if (j == f->numBindPairs) + break; + } + if (i == numInStreamsTotal) + return (-1); + f->packedStreams[0] = i; + } else { + for (i = 0; i < f->numPackedStreams; i++) { + if (parse_7zip_uint64(a, &(f->packedStreams[i])) < 0) + return (-1); + if (UMAX_ENTRY < f->packedStreams[i]) + return (-1); + } + } + f->numInStreams = numInStreamsTotal; + f->numOutStreams = numOutStreamsTotal; + + return (0); +} + +static void +free_CodersInfo(struct _7z_coders_info *ci) +{ + unsigned i; + + if (ci->folders) { + for (i = 0; i < ci->numFolders; i++) + free_Folder(&(ci->folders[i])); + free(ci->folders); + } +} + +static int +read_CodersInfo(struct archive_read *a, struct _7z_coders_info *ci) +{ + const unsigned char *p; + struct _7z_digests digest; + unsigned i; + + memset(ci, 0, sizeof(*ci)); + memset(&digest, 0, sizeof(digest)); + + if ((p = header_bytes(a, 1)) == NULL) + goto failed; + if (*p != kFolder) + goto failed; + + /* + * Read NumFolders. + */ + if (parse_7zip_uint64(a, &(ci->numFolders)) < 0) + goto failed; + if (UMAX_ENTRY < ci->numFolders) + return (-1); + + /* + * Read External. + */ + if ((p = header_bytes(a, 1)) == NULL) + goto failed; + switch (*p) { + case 0: + ci->folders = + calloc((size_t)ci->numFolders, sizeof(*ci->folders)); + if (ci->folders == NULL) + return (-1); + for (i = 0; i < ci->numFolders; i++) { + if (read_Folder(a, &(ci->folders[i])) < 0) + goto failed; + } + break; + case 1: + if (parse_7zip_uint64(a, &(ci->dataStreamIndex)) < 0) + return (-1); + if (UMAX_ENTRY < ci->dataStreamIndex) + return (-1); + if (ci->numFolders > 0) { + archive_set_error(&a->archive, -1, + "Malformed 7-Zip archive"); + goto failed; + } + break; + default: + archive_set_error(&a->archive, -1, + "Malformed 7-Zip archive"); + goto failed; + } + + if ((p = header_bytes(a, 1)) == NULL) + goto failed; + if (*p != kCodersUnPackSize) + goto failed; + + for (i = 0; i < ci->numFolders; i++) { + struct _7z_folder *folder = &(ci->folders[i]); + unsigned j; + + folder->unPackSize = + calloc((size_t)folder->numOutStreams, sizeof(*folder->unPackSize)); + if (folder->unPackSize == NULL) + goto failed; + for (j = 0; j < folder->numOutStreams; j++) { + if (parse_7zip_uint64(a, &(folder->unPackSize[j])) < 0) + goto failed; + } + } + + /* + * Read CRCs. + */ + if ((p = header_bytes(a, 1)) == NULL) + goto failed; + if (*p == kEnd) + return (0); + if (*p != kCRC) + goto failed; + if (read_Digests(a, &digest, (size_t)ci->numFolders) < 0) + goto failed; + for (i = 0; i < ci->numFolders; i++) { + ci->folders[i].digest_defined = digest.defineds[i]; + ci->folders[i].digest = digest.digests[i]; + } + + /* + * Must be kEnd. + */ + if ((p = header_bytes(a, 1)) == NULL) + goto failed; + if (*p != kEnd) + goto failed; + free_Digest(&digest); + return (0); +failed: + free_Digest(&digest); + return (-1); +} + +static uint64_t +folder_uncompressed_size(struct _7z_folder *f) +{ + int n = (int)f->numOutStreams; + unsigned pairs = (unsigned)f->numBindPairs; + + while (--n >= 0) { + unsigned i; + for (i = 0; i < pairs; i++) { + if (f->bindPairs[i].outIndex == (uint64_t)n) + break; + } + if (i >= pairs) + return (f->unPackSize[n]); + } + return (0); +} + +static void +free_SubStreamsInfo(struct _7z_substream_info *ss) +{ + free(ss->unpackSizes); + free(ss->digestsDefined); + free(ss->digests); +} + +static int +read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss, + struct _7z_folder *f, size_t numFolders) +{ + const unsigned char *p; + uint64_t *usizes; + size_t unpack_streams; + int type; + unsigned i; + uint32_t numDigests; + + memset(ss, 0, sizeof(*ss)); + + for (i = 0; i < numFolders; i++) + f[i].numUnpackStreams = 1; + + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + type = *p; + + if (type == kNumUnPackStream) { + unpack_streams = 0; + for (i = 0; i < numFolders; i++) { + if (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0) + return (-1); + if (UMAX_ENTRY < f[i].numUnpackStreams) + return (-1); + if (unpack_streams > SIZE_MAX - UMAX_ENTRY) { + return (-1); + } + unpack_streams += (size_t)f[i].numUnpackStreams; + } + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + type = *p; + } else + unpack_streams = numFolders; + + ss->unpack_streams = unpack_streams; + if (unpack_streams) { + ss->unpackSizes = calloc(unpack_streams, + sizeof(*ss->unpackSizes)); + ss->digestsDefined = calloc(unpack_streams, + sizeof(*ss->digestsDefined)); + ss->digests = calloc(unpack_streams, + sizeof(*ss->digests)); + if (ss->unpackSizes == NULL || ss->digestsDefined == NULL || + ss->digests == NULL) + return (-1); + } + + usizes = ss->unpackSizes; + for (i = 0; i < numFolders; i++) { + unsigned pack; + uint64_t sum; + + if (f[i].numUnpackStreams == 0) + continue; + + sum = 0; + if (type == kSize) { + for (pack = 1; pack < f[i].numUnpackStreams; pack++) { + if (parse_7zip_uint64(a, usizes) < 0) + return (-1); + sum += *usizes++; + } + } + *usizes++ = folder_uncompressed_size(&f[i]) - sum; + } + + if (type == kSize) { + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + type = *p; + } + + for (i = 0; i < unpack_streams; i++) { + ss->digestsDefined[i] = 0; + ss->digests[i] = 0; + } + + numDigests = 0; + for (i = 0; i < numFolders; i++) { + if (f[i].numUnpackStreams != 1 || !f[i].digest_defined) + numDigests += (uint32_t)f[i].numUnpackStreams; + } + + if (type == kCRC) { + struct _7z_digests tmpDigests; + unsigned char *digestsDefined = ss->digestsDefined; + uint32_t * digests = ss->digests; + int di = 0; + + memset(&tmpDigests, 0, sizeof(tmpDigests)); + if (read_Digests(a, &(tmpDigests), numDigests) < 0) { + free_Digest(&tmpDigests); + return (-1); + } + for (i = 0; i < numFolders; i++) { + if (f[i].numUnpackStreams == 1 && f[i].digest_defined) { + *digestsDefined++ = 1; + *digests++ = f[i].digest; + } else { + unsigned j; + + for (j = 0; j < f[i].numUnpackStreams; + j++, di++) { + *digestsDefined++ = + tmpDigests.defineds[di]; + *digests++ = + tmpDigests.digests[di]; + } + } + } + free_Digest(&tmpDigests); + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + type = *p; + } + + /* + * Must be kEnd. + */ + if (type != kEnd) + return (-1); + return (0); +} + +static void +free_StreamsInfo(struct _7z_stream_info *si) +{ + free_PackInfo(&(si->pi)); + free_CodersInfo(&(si->ci)); + free_SubStreamsInfo(&(si->ss)); +} + +static int +read_StreamsInfo(struct archive_read *a, struct _7z_stream_info *si) +{ + struct _7zip *zip = (struct _7zip *)a->format->data; + const unsigned char *p; + unsigned i; + + memset(si, 0, sizeof(*si)); + + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + if (*p == kPackInfo) { + uint64_t packPos; + + if (read_PackInfo(a, &(si->pi)) < 0) + return (-1); + + if (si->pi.positions == NULL || si->pi.sizes == NULL) + return (-1); + /* + * Calculate packed stream positions. + */ + packPos = si->pi.pos; + for (i = 0; i < si->pi.numPackStreams; i++) { + si->pi.positions[i] = packPos; + packPos += si->pi.sizes[i]; + if (packPos > zip->header_offset) + return (-1); + } + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + } + if (*p == kUnPackInfo) { + uint32_t packIndex; + struct _7z_folder *f; + + if (read_CodersInfo(a, &(si->ci)) < 0) + return (-1); + + /* + * Calculate packed stream indexes. + */ + packIndex = 0; + f = si->ci.folders; + for (i = 0; i < si->ci.numFolders; i++) { + f[i].packIndex = packIndex; + packIndex += (uint32_t)f[i].numPackedStreams; + if (packIndex > si->pi.numPackStreams) + return (-1); + } + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + } + + if (*p == kSubStreamsInfo) { + if (read_SubStreamsInfo(a, &(si->ss), + si->ci.folders, (size_t)si->ci.numFolders) < 0) + return (-1); + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + } + + /* + * Must be kEnd. + */ + if (*p != kEnd) + return (-1); + return (0); +} + +static void +free_Header(struct _7z_header_info *h) +{ + free(h->emptyStreamBools); + free(h->emptyFileBools); + free(h->antiBools); + free(h->attrBools); +} + +static int +read_Header(struct archive_read *a, struct _7z_header_info *h, + int check_header_id) +{ + struct _7zip *zip = (struct _7zip *)a->format->data; + const unsigned char *p; + struct _7z_folder *folders; + struct _7z_stream_info *si = &(zip->si); + struct _7zip_entry *entries; + uint32_t folderIndex, indexInFolder; + unsigned i; + int eindex, empty_streams, sindex; + + if (check_header_id) { + /* + * Read Header. + */ + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + if (*p != kHeader) + return (-1); + } + + /* + * Read ArchiveProperties. + */ + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + if (*p == kArchiveProperties) { + for (;;) { + uint64_t size; + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + if (*p == 0) + break; + if (parse_7zip_uint64(a, &size) < 0) + return (-1); + } + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + } + + /* + * Read MainStreamsInfo. + */ + if (*p == kMainStreamsInfo) { + if (read_StreamsInfo(a, &(zip->si)) < 0) + return (-1); + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + } + if (*p == kEnd) + return (0); + + /* + * Read FilesInfo. + */ + if (*p != kFilesInfo) + return (-1); + + if (parse_7zip_uint64(a, &(zip->numFiles)) < 0) + return (-1); + if (UMAX_ENTRY < zip->numFiles) + return (-1); + + zip->entries = calloc((size_t)zip->numFiles, sizeof(*zip->entries)); + if (zip->entries == NULL) + return (-1); + entries = zip->entries; + + empty_streams = 0; + for (;;) { + int type; + uint64_t size; + size_t ll; + + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + type = *p; + if (type == kEnd) + break; + + if (parse_7zip_uint64(a, &size) < 0) + return (-1); + if (zip->header_bytes_remaining < size) + return (-1); + ll = (size_t)size; + + switch (type) { + case kEmptyStream: + if (h->emptyStreamBools != NULL) + return (-1); + h->emptyStreamBools = calloc((size_t)zip->numFiles, + sizeof(*h->emptyStreamBools)); + if (h->emptyStreamBools == NULL) + return (-1); + if (read_Bools( + a, h->emptyStreamBools, (size_t)zip->numFiles) < 0) + return (-1); + empty_streams = 0; + for (i = 0; i < zip->numFiles; i++) { + if (h->emptyStreamBools[i]) + empty_streams++; + } + break; + case kEmptyFile: + if (empty_streams <= 0) { + /* Unexcepted sequence. Skip this. */ + if (header_bytes(a, ll) == NULL) + return (-1); + break; + } + if (h->emptyFileBools != NULL) + return (-1); + h->emptyFileBools = calloc(empty_streams, + sizeof(*h->emptyFileBools)); + if (h->emptyFileBools == NULL) + return (-1); + if (read_Bools(a, h->emptyFileBools, empty_streams) < 0) + return (-1); + break; + case kAnti: + if (empty_streams <= 0) { + /* Unexcepted sequence. Skip this. */ + if (header_bytes(a, ll) == NULL) + return (-1); + break; + } + if (h->antiBools != NULL) + return (-1); + h->antiBools = calloc(empty_streams, + sizeof(*h->antiBools)); + if (h->antiBools == NULL) + return (-1); + if (read_Bools(a, h->antiBools, empty_streams) < 0) + return (-1); + break; + case kCTime: + case kATime: + case kMTime: + if (read_Times(a, h, type) < 0) + return (-1); + break; + case kName: + { + unsigned char *np; + size_t nl, nb; + + /* Skip one byte. */ + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + ll--; + + if ((ll & 1) || ll < zip->numFiles * 4) + return (-1); + + if (zip->entry_names != NULL) + return (-1); + zip->entry_names = malloc(ll); + if (zip->entry_names == NULL) + return (-1); + np = zip->entry_names; + nb = ll; + /* + * Copy whole file names. + * NOTE: This loop prevents from expanding + * the uncompressed buffer in order not to + * use extra memory resource. + */ + while (nb) { + size_t b; + if (nb > UBUFF_SIZE) + b = UBUFF_SIZE; + else + b = nb; + if ((p = header_bytes(a, b)) == NULL) + return (-1); + memcpy(np, p, b); + np += b; + nb -= b; + } + np = zip->entry_names; + nl = ll; + + for (i = 0; i < zip->numFiles; i++) { + entries[i].utf16name = np; +#if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG) + entries[i].wname = (wchar_t *)np; +#endif + + /* Find a terminator. */ + while (nl >= 2 && (np[0] || np[1])) { + np += 2; + nl -= 2; + } + if (nl < 2) + return (-1);/* Terminator not found */ + entries[i].name_len = np - entries[i].utf16name; + np += 2; + nl -= 2; + } + break; + } + case kAttributes: + { + int allAreDefined; + + if ((p = header_bytes(a, 2)) == NULL) + return (-1); + allAreDefined = *p; + if (h->attrBools != NULL) + return (-1); + h->attrBools = calloc((size_t)zip->numFiles, + sizeof(*h->attrBools)); + if (h->attrBools == NULL) + return (-1); + if (allAreDefined) + memset(h->attrBools, 1, (size_t)zip->numFiles); + else { + if (read_Bools(a, h->attrBools, + (size_t)zip->numFiles) < 0) + return (-1); + } + for (i = 0; i < zip->numFiles; i++) { + if (h->attrBools[i]) { + if ((p = header_bytes(a, 4)) == NULL) + return (-1); + entries[i].attr = archive_le32dec(p); + } + } + break; + } + case kDummy: + if (ll == 0) + break; + __LA_FALLTHROUGH; + default: + if (header_bytes(a, ll) == NULL) + return (-1); + break; + } + } + + /* + * Set up entry's attributes. + */ + folders = si->ci.folders; + eindex = sindex = 0; + folderIndex = indexInFolder = 0; + for (i = 0; i < zip->numFiles; i++) { + if (h->emptyStreamBools == NULL || h->emptyStreamBools[i] == 0) + entries[i].flg |= HAS_STREAM; + /* The high 16 bits of attributes is a posix file mode. */ + entries[i].mode = entries[i].attr >> 16; + if (entries[i].flg & HAS_STREAM) { + if ((size_t)sindex >= si->ss.unpack_streams) + return (-1); + if (entries[i].mode == 0) + entries[i].mode = AE_IFREG | 0666; + if (si->ss.digestsDefined[sindex]) + entries[i].flg |= CRC32_IS_SET; + entries[i].ssIndex = sindex; + sindex++; + } else { + int dir; + if (h->emptyFileBools == NULL) + dir = 1; + else { + if (h->emptyFileBools[eindex]) + dir = 0; + else + dir = 1; + eindex++; + } + if (entries[i].mode == 0) { + if (dir) + entries[i].mode = AE_IFDIR | 0777; + else + entries[i].mode = AE_IFREG | 0666; + } else if (dir && + (entries[i].mode & AE_IFMT) != AE_IFDIR) { + entries[i].mode &= ~AE_IFMT; + entries[i].mode |= AE_IFDIR; + } + if ((entries[i].mode & AE_IFMT) == AE_IFDIR && + entries[i].name_len >= 2 && + (entries[i].utf16name[entries[i].name_len-2] != '/' || + entries[i].utf16name[entries[i].name_len-1] != 0)) { + entries[i].utf16name[entries[i].name_len] = '/'; + entries[i].utf16name[entries[i].name_len+1] = 0; + entries[i].name_len += 2; + } + entries[i].ssIndex = -1; + } + if (entries[i].attr & 0x01) + entries[i].mode &= ~0222;/* Read only. */ + + if ((entries[i].flg & HAS_STREAM) == 0 && indexInFolder == 0) { + /* + * The entry is an empty file or a directory file, + * those both have no contents. + */ + entries[i].folderIndex = -1; + continue; + } + if (indexInFolder == 0) { + for (;;) { + if (folderIndex >= si->ci.numFolders) + return (-1); + if (folders[folderIndex].numUnpackStreams) + break; + folderIndex++; + } + } + entries[i].folderIndex = folderIndex; + if ((entries[i].flg & HAS_STREAM) == 0) + continue; + indexInFolder++; + if (indexInFolder >= folders[folderIndex].numUnpackStreams) { + folderIndex++; + indexInFolder = 0; + } + } + + return (0); +} + +#define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000) +static void +fileTimeToUtc(uint64_t fileTime, time_t *timep, long *ns) +{ + + if (fileTime >= EPOC_TIME) { + fileTime -= EPOC_TIME; + /* milli seconds base */ + *timep = (time_t)(fileTime / 10000000); + /* nano seconds base */ + *ns = (long)(fileTime % 10000000) * 100; + } else { + *timep = 0; + *ns = 0; + } +} + +static int +read_Times(struct archive_read *a, struct _7z_header_info *h, int type) +{ + struct _7zip *zip = (struct _7zip *)a->format->data; + const unsigned char *p; + struct _7zip_entry *entries = zip->entries; + unsigned char *timeBools; + int allAreDefined; + unsigned i; + + timeBools = calloc((size_t)zip->numFiles, sizeof(*timeBools)); + if (timeBools == NULL) + return (-1); + + /* Read allAreDefined. */ + if ((p = header_bytes(a, 1)) == NULL) + goto failed; + allAreDefined = *p; + if (allAreDefined) + memset(timeBools, 1, (size_t)zip->numFiles); + else { + if (read_Bools(a, timeBools, (size_t)zip->numFiles) < 0) + goto failed; + } + + /* Read external. */ + if ((p = header_bytes(a, 1)) == NULL) + goto failed; + if (*p) { + if (parse_7zip_uint64(a, &(h->dataIndex)) < 0) + goto failed; + if (UMAX_ENTRY < h->dataIndex) + goto failed; + } + + for (i = 0; i < zip->numFiles; i++) { + if (!timeBools[i]) + continue; + if ((p = header_bytes(a, 8)) == NULL) + goto failed; + switch (type) { + case kCTime: + fileTimeToUtc(archive_le64dec(p), + &(entries[i].ctime), + &(entries[i].ctime_ns)); + entries[i].flg |= CTIME_IS_SET; + break; + case kATime: + fileTimeToUtc(archive_le64dec(p), + &(entries[i].atime), + &(entries[i].atime_ns)); + entries[i].flg |= ATIME_IS_SET; + break; + case kMTime: + fileTimeToUtc(archive_le64dec(p), + &(entries[i].mtime), + &(entries[i].mtime_ns)); + entries[i].flg |= MTIME_IS_SET; + break; + } + } + + free(timeBools); + return (0); +failed: + free(timeBools); + return (-1); +} + +static int +decode_encoded_header_info(struct archive_read *a, struct _7z_stream_info *si) +{ + struct _7zip *zip = (struct _7zip *)a->format->data; + + errno = 0; + if (read_StreamsInfo(a, si) < 0) { + if (errno == ENOMEM) + archive_set_error(&a->archive, -1, + "Couldn't allocate memory"); + else + archive_set_error(&a->archive, -1, + "Malformed 7-Zip archive"); + return (ARCHIVE_FATAL); + } + + if (si->pi.numPackStreams == 0 || si->ci.numFolders == 0) { + archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); + return (ARCHIVE_FATAL); + } + + if (zip->header_offset < si->pi.pos + si->pi.sizes[0] || + (int64_t)(si->pi.pos + si->pi.sizes[0]) < 0 || + si->pi.sizes[0] == 0 || (int64_t)si->pi.pos < 0) { + archive_set_error(&a->archive, -1, "Malformed Header offset"); + return (ARCHIVE_FATAL); + } + + return (ARCHIVE_OK); +} + +static const unsigned char * +header_bytes(struct archive_read *a, size_t rbytes) +{ + struct _7zip *zip = (struct _7zip *)a->format->data; + const unsigned char *p; + + if (zip->header_bytes_remaining < rbytes) + return (NULL); + if (zip->pack_stream_bytes_unconsumed) + read_consume(a); + + if (zip->header_is_encoded == 0) { + p = __archive_read_ahead(a, rbytes, NULL); + if (p == NULL) + return (NULL); + zip->header_bytes_remaining -= rbytes; + zip->pack_stream_bytes_unconsumed = rbytes; + } else { + const void *buff; + ssize_t bytes; + + bytes = read_stream(a, &buff, rbytes, rbytes); + if (bytes <= 0) + return (NULL); + zip->header_bytes_remaining -= bytes; + p = buff; + } + + /* Update checksum */ + zip->header_crc32 = crc32(zip->header_crc32, p, (unsigned)rbytes); + return (p); +} + +static int +slurp_central_directory(struct archive_read *a, struct _7zip *zip, + struct _7z_header_info *header) +{ + const unsigned char *p; + uint64_t next_header_offset; + uint64_t next_header_size; + uint32_t next_header_crc; + ssize_t bytes_avail; + int check_header_crc, r; + + if ((p = __archive_read_ahead(a, 32, &bytes_avail)) == NULL) + return (ARCHIVE_FATAL); + + if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) { + /* This is an executable ? Must be self-extracting... */ + r = skip_sfx(a, bytes_avail); + if (r < ARCHIVE_WARN) + return (r); + if ((p = __archive_read_ahead(a, 32, &bytes_avail)) == NULL) + return (ARCHIVE_FATAL); + } + zip->seek_base += 32; + + if (memcmp(p, _7ZIP_SIGNATURE, 6) != 0) { + archive_set_error(&a->archive, -1, "Not 7-Zip archive file"); + return (ARCHIVE_FATAL); + } + + /* CRC check. */ + if (crc32(0, (const unsigned char *)p + 12, 20) + != archive_le32dec(p + 8)) { + archive_set_error(&a->archive, -1, "Header CRC error"); + return (ARCHIVE_FATAL); + } + + next_header_offset = archive_le64dec(p + 12); + next_header_size = archive_le64dec(p + 20); + next_header_crc = archive_le32dec(p + 28); + + if (next_header_size == 0) + /* There is no entry in an archive file. */ + return (ARCHIVE_EOF); + + if (((int64_t)next_header_offset) < 0) { + archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); + return (ARCHIVE_FATAL); + } + __archive_read_consume(a, 32); + if (next_header_offset != 0) { + if (bytes_avail >= (ssize_t)next_header_offset) + __archive_read_consume(a, next_header_offset); + else if (__archive_read_seek(a, + next_header_offset + zip->seek_base, SEEK_SET) < 0) + return (ARCHIVE_FATAL); + } + zip->stream_offset = next_header_offset; + zip->header_offset = next_header_offset; + zip->header_bytes_remaining = next_header_size; + zip->header_crc32 = 0; + zip->header_is_encoded = 0; + zip->header_is_being_read = 1; + zip->has_encrypted_entries = 0; + check_header_crc = 1; + + if ((p = header_bytes(a, 1)) == NULL) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated 7-Zip file body"); + return (ARCHIVE_FATAL); + } + /* Parse ArchiveProperties. */ + switch (p[0]) { + case kEncodedHeader: + /* + * The archive has an encoded header and we have to decode it + * in order to parse the header correctly. + */ + r = decode_encoded_header_info(a, &(zip->si)); + + /* Check the EncodedHeader CRC.*/ + if (r == 0 && zip->header_crc32 != next_header_crc) { + archive_set_error(&a->archive, -1, + "Damaged 7-Zip archive"); + r = -1; + } + if (r == 0) { + if (zip->si.ci.folders[0].digest_defined) + next_header_crc = zip->si.ci.folders[0].digest; + else + check_header_crc = 0; + if (zip->pack_stream_bytes_unconsumed) + read_consume(a); + r = setup_decode_folder(a, zip->si.ci.folders, 1); + if (r == 0) { + zip->header_bytes_remaining = + zip->folder_outbytes_remaining; + r = seek_pack(a); + } + } + /* Clean up StreamsInfo. */ + free_StreamsInfo(&(zip->si)); + memset(&(zip->si), 0, sizeof(zip->si)); + if (r < 0) + return (ARCHIVE_FATAL); + zip->header_is_encoded = 1; + zip->header_crc32 = 0; + /* FALL THROUGH */ + case kHeader: + /* + * Parse the header. + */ + errno = 0; + r = read_Header(a, header, zip->header_is_encoded); + if (r < 0) { + if (errno == ENOMEM) + archive_set_error(&a->archive, -1, + "Couldn't allocate memory"); + else + archive_set_error(&a->archive, -1, + "Damaged 7-Zip archive"); + return (ARCHIVE_FATAL); + } + + /* + * Must be kEnd. + */ + if ((p = header_bytes(a, 1)) == NULL ||*p != kEnd) { + archive_set_error(&a->archive, -1, + "Malformed 7-Zip archive"); + return (ARCHIVE_FATAL); + } + + /* Check the Header CRC.*/ + if (check_header_crc && zip->header_crc32 != next_header_crc) { + archive_set_error(&a->archive, -1, + "Malformed 7-Zip archive"); + return (ARCHIVE_FATAL); + } + break; + default: + archive_set_error(&a->archive, -1, + "Unexpected Property ID = %X", p[0]); + return (ARCHIVE_FATAL); + } + + /* Clean up variables be used for decoding the archive header */ + zip->pack_stream_remaining = 0; + zip->pack_stream_index = 0; + zip->folder_outbytes_remaining = 0; + zip->uncompressed_buffer_bytes_remaining = 0; + zip->pack_stream_bytes_unconsumed = 0; + zip->header_is_being_read = 0; + + return (ARCHIVE_OK); +} + +static ssize_t +get_uncompressed_data(struct archive_read *a, const void **buff, size_t size, + size_t minimum) +{ + struct _7zip *zip = (struct _7zip *)a->format->data; + ssize_t bytes_avail; + + if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) { + /* Copy mode. */ + + *buff = __archive_read_ahead(a, minimum, &bytes_avail); + if (bytes_avail <= 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated 7-Zip file data"); + return (ARCHIVE_FATAL); + } + if ((size_t)bytes_avail > + zip->uncompressed_buffer_bytes_remaining) + bytes_avail = (ssize_t) + zip->uncompressed_buffer_bytes_remaining; + if ((size_t)bytes_avail > size) + bytes_avail = (ssize_t)size; + + zip->pack_stream_bytes_unconsumed = bytes_avail; + } else if (zip->uncompressed_buffer_pointer == NULL) { + /* Decompression has failed. */ + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive"); + return (ARCHIVE_FATAL); + } else { + /* Packed mode. */ + if (minimum > zip->uncompressed_buffer_bytes_remaining) { + /* + * If remaining uncompressed data size is less than + * the minimum size, fill the buffer up to the + * minimum size. + */ + if (extract_pack_stream(a, minimum) < 0) + return (ARCHIVE_FATAL); + } + if (size > zip->uncompressed_buffer_bytes_remaining) + bytes_avail = (ssize_t) + zip->uncompressed_buffer_bytes_remaining; + else + bytes_avail = (ssize_t)size; + *buff = zip->uncompressed_buffer_pointer; + zip->uncompressed_buffer_pointer += bytes_avail; + } + zip->uncompressed_buffer_bytes_remaining -= bytes_avail; + return (bytes_avail); +} + +static ssize_t +extract_pack_stream(struct archive_read *a, size_t minimum) +{ + struct _7zip *zip = (struct _7zip *)a->format->data; + ssize_t bytes_avail; + int r; + + if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) { + if (minimum == 0) + minimum = 1; + if (__archive_read_ahead(a, minimum, &bytes_avail) == NULL + || bytes_avail <= 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated 7-Zip file body"); + return (ARCHIVE_FATAL); + } + if (bytes_avail > (ssize_t)zip->pack_stream_inbytes_remaining) + bytes_avail = (ssize_t)zip->pack_stream_inbytes_remaining; + zip->pack_stream_inbytes_remaining -= bytes_avail; + if (bytes_avail > (ssize_t)zip->folder_outbytes_remaining) + bytes_avail = (ssize_t)zip->folder_outbytes_remaining; + zip->folder_outbytes_remaining -= bytes_avail; + zip->uncompressed_buffer_bytes_remaining = bytes_avail; + return (ARCHIVE_OK); + } + + /* If the buffer hasn't been allocated, allocate it now. */ + if (zip->uncompressed_buffer == NULL) { + zip->uncompressed_buffer_size = UBUFF_SIZE; + if (zip->uncompressed_buffer_size < minimum) { + zip->uncompressed_buffer_size = minimum + 1023; + zip->uncompressed_buffer_size &= ~0x3ff; + } + zip->uncompressed_buffer = + malloc(zip->uncompressed_buffer_size); + if (zip->uncompressed_buffer == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for 7-Zip decompression"); + return (ARCHIVE_FATAL); + } + zip->uncompressed_buffer_bytes_remaining = 0; + } else if (zip->uncompressed_buffer_size < minimum || + zip->uncompressed_buffer_bytes_remaining < minimum) { + /* + * Make sure the uncompressed buffer can have bytes + * at least `minimum' bytes. + * NOTE: This case happen when reading the header. + */ + size_t used; + if (zip->uncompressed_buffer_pointer != 0) + used = zip->uncompressed_buffer_pointer - + zip->uncompressed_buffer; + else + used = 0; + if (zip->uncompressed_buffer_size < minimum) { + /* + * Expand the uncompressed buffer up to + * the minimum size. + */ + void *p; + size_t new_size; + + new_size = minimum + 1023; + new_size &= ~0x3ff; + p = realloc(zip->uncompressed_buffer, new_size); + if (p == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for 7-Zip decompression"); + return (ARCHIVE_FATAL); + } + zip->uncompressed_buffer = (unsigned char *)p; + zip->uncompressed_buffer_size = new_size; + } + /* + * Move unconsumed bytes to the head. + */ + if (used) { + memmove(zip->uncompressed_buffer, + zip->uncompressed_buffer + used, + zip->uncompressed_buffer_bytes_remaining); + } + } else + zip->uncompressed_buffer_bytes_remaining = 0; + zip->uncompressed_buffer_pointer = NULL; + for (;;) { + size_t bytes_in, bytes_out; + const void *buff_in; + unsigned char *buff_out; + int end_of_data; + + /* + * Note: '1' here is a performance optimization. + * Recall that the decompression layer returns a count of + * available bytes; asking for more than that forces the + * decompressor to combine reads by copying data. + */ + buff_in = __archive_read_ahead(a, 1, &bytes_avail); + if (bytes_avail <= 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated 7-Zip file body"); + return (ARCHIVE_FATAL); + } + + buff_out = zip->uncompressed_buffer + + zip->uncompressed_buffer_bytes_remaining; + bytes_out = zip->uncompressed_buffer_size + - zip->uncompressed_buffer_bytes_remaining; + bytes_in = bytes_avail; + if (bytes_in > zip->pack_stream_inbytes_remaining) + bytes_in = (size_t)zip->pack_stream_inbytes_remaining; + /* Drive decompression. */ + r = decompress(a, zip, buff_out, &bytes_out, + buff_in, &bytes_in); + switch (r) { + case ARCHIVE_OK: + end_of_data = 0; + break; + case ARCHIVE_EOF: + end_of_data = 1; + break; + default: + return (ARCHIVE_FATAL); + } + zip->pack_stream_inbytes_remaining -= bytes_in; + if (bytes_out > zip->folder_outbytes_remaining) + bytes_out = (size_t)zip->folder_outbytes_remaining; + zip->folder_outbytes_remaining -= bytes_out; + zip->uncompressed_buffer_bytes_remaining += bytes_out; + zip->pack_stream_bytes_unconsumed = bytes_in; + + /* + * Continue decompression until uncompressed_buffer is full. + */ + if (zip->uncompressed_buffer_bytes_remaining == + zip->uncompressed_buffer_size) + break; + if (zip->codec2 == _7Z_X86 && zip->odd_bcj_size && + zip->uncompressed_buffer_bytes_remaining + 5 > + zip->uncompressed_buffer_size) + break; + if (zip->pack_stream_inbytes_remaining == 0 && + zip->folder_outbytes_remaining == 0) + break; + if (end_of_data || (bytes_in == 0 && bytes_out == 0)) { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive"); + return (ARCHIVE_FATAL); + } + read_consume(a); + } + if (zip->uncompressed_buffer_bytes_remaining < minimum) { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive"); + return (ARCHIVE_FATAL); + } + zip->uncompressed_buffer_pointer = zip->uncompressed_buffer; + return (ARCHIVE_OK); +} + +static int +seek_pack(struct archive_read *a) +{ + struct _7zip *zip = (struct _7zip *)a->format->data; + int64_t pack_offset; + + if (zip->pack_stream_remaining <= 0) { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive"); + return (ARCHIVE_FATAL); + } + zip->pack_stream_inbytes_remaining = + zip->si.pi.sizes[zip->pack_stream_index]; + pack_offset = zip->si.pi.positions[zip->pack_stream_index]; + if (zip->stream_offset != pack_offset) { + if (0 > __archive_read_seek(a, pack_offset + zip->seek_base, + SEEK_SET)) + return (ARCHIVE_FATAL); + zip->stream_offset = pack_offset; + } + zip->pack_stream_index++; + zip->pack_stream_remaining--; + return (ARCHIVE_OK); +} + +static ssize_t +read_stream(struct archive_read *a, const void **buff, size_t size, + size_t minimum) +{ + struct _7zip *zip = (struct _7zip *)a->format->data; + uint64_t skip_bytes = 0; + ssize_t r; + + if (zip->uncompressed_buffer_bytes_remaining == 0) { + if (zip->pack_stream_inbytes_remaining > 0) { + r = extract_pack_stream(a, 0); + if (r < 0) + return (r); + return (get_uncompressed_data(a, buff, size, minimum)); + } else if (zip->folder_outbytes_remaining > 0) { + /* Extract a remaining pack stream. */ + r = extract_pack_stream(a, 0); + if (r < 0) + return (r); + return (get_uncompressed_data(a, buff, size, minimum)); + } + } else + return (get_uncompressed_data(a, buff, size, minimum)); + + /* + * Current pack stream has been consumed. + */ + if (zip->pack_stream_remaining == 0) { + if (zip->header_is_being_read) { + /* Invalid sequence. This might happen when + * reading a malformed archive. */ + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, "Malformed 7-Zip archive"); + return (ARCHIVE_FATAL); + } + + /* + * All current folder's pack streams have been + * consumed. Switch to next folder. + */ + if (zip->folder_index == 0 && + (zip->si.ci.folders[zip->entry->folderIndex].skipped_bytes + || zip->folder_index != zip->entry->folderIndex)) { + zip->folder_index = zip->entry->folderIndex; + skip_bytes = + zip->si.ci.folders[zip->folder_index].skipped_bytes; + } + + if (zip->folder_index >= zip->si.ci.numFolders) { + /* + * We have consumed all folders and its pack streams. + */ + *buff = NULL; + return (0); + } + r = setup_decode_folder(a, + &(zip->si.ci.folders[zip->folder_index]), 0); + if (r != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + zip->folder_index++; + } + + /* + * Switch to next pack stream. + */ + r = seek_pack(a); + if (r < 0) + return (r); + + /* Extract a new pack stream. */ + r = extract_pack_stream(a, 0); + if (r < 0) + return (r); + + /* + * Skip the bytes we already has skipped in skip_stream(). + */ + while (skip_bytes) { + ssize_t skipped; + + if (zip->uncompressed_buffer_bytes_remaining == 0) { + if (zip->pack_stream_inbytes_remaining > 0) { + r = extract_pack_stream(a, 0); + if (r < 0) + return (r); + } else if (zip->folder_outbytes_remaining > 0) { + /* Extract a remaining pack stream. */ + r = extract_pack_stream(a, 0); + if (r < 0) + return (r); + } else { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated 7-Zip file body"); + return (ARCHIVE_FATAL); + } + } + skipped = get_uncompressed_data( + a, buff, (size_t)skip_bytes, 0); + if (skipped < 0) + return (skipped); + skip_bytes -= skipped; + if (zip->pack_stream_bytes_unconsumed) + read_consume(a); + } + + return (get_uncompressed_data(a, buff, size, minimum)); +} + +static int +setup_decode_folder(struct archive_read *a, struct _7z_folder *folder, + int header) +{ + struct _7zip *zip = (struct _7zip *)a->format->data; + const struct _7z_coder *coder1, *coder2; + const char *cname = (header)?"archive header":"file content"; + unsigned i; + int r, found_bcj2 = 0; + + /* + * Release the memory which the previous folder used for BCJ2. + */ + for (i = 0; i < 3; i++) { + free(zip->sub_stream_buff[i]); + zip->sub_stream_buff[i] = NULL; + } + + /* + * Initialize a stream reader. + */ + zip->pack_stream_remaining = (unsigned)folder->numPackedStreams; + zip->pack_stream_index = (unsigned)folder->packIndex; + zip->folder_outbytes_remaining = folder_uncompressed_size(folder); + zip->uncompressed_buffer_bytes_remaining = 0; + + /* + * Check coder types. + */ + for (i = 0; i < folder->numCoders; i++) { + switch(folder->coders[i].codec) { + case _7Z_CRYPTO_MAIN_ZIP: + case _7Z_CRYPTO_RAR_29: + case _7Z_CRYPTO_AES_256_SHA_256: { + /* For entry that is associated with this folder, mark + it as encrypted (data+metadata). */ + zip->has_encrypted_entries = 1; + if (a->entry) { + archive_entry_set_is_data_encrypted(a->entry, 1); + archive_entry_set_is_metadata_encrypted(a->entry, 1); + } + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "The %s is encrypted, " + "but currently not supported", cname); + return (ARCHIVE_FATAL); + } + case _7Z_X86_BCJ2: { + found_bcj2++; + break; + } + } + } + /* Now that we've checked for encryption, if there were still no + * encrypted entries found we can say for sure that there are none. + */ + if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { + zip->has_encrypted_entries = 0; + } + + if ((folder->numCoders > 2 && !found_bcj2) || found_bcj2 > 1) { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "The %s is encoded with many filters, " + "but currently not supported", cname); + return (ARCHIVE_FATAL); + } + coder1 = &(folder->coders[0]); + if (folder->numCoders == 2) + coder2 = &(folder->coders[1]); + else + coder2 = NULL; + + if (found_bcj2) { + /* + * Preparation to decode BCJ2. + * Decoding BCJ2 requires four sources. Those are at least, + * as far as I know, two types of the storage form. + */ + const struct _7z_coder *fc = folder->coders; + static const struct _7z_coder coder_copy = {0, 1, 1, 0, NULL}; + const struct _7z_coder *scoder[3] = + {&coder_copy, &coder_copy, &coder_copy}; + const void *buff; + ssize_t bytes; + unsigned char *b[3] = {NULL, NULL, NULL}; + uint64_t sunpack[3] ={-1, -1, -1}; + size_t s[3] = {0, 0, 0}; + int idx[3] = {0, 1, 2}; + + if (folder->numCoders == 4 && fc[3].codec == _7Z_X86_BCJ2 && + folder->numInStreams == 7 && folder->numOutStreams == 4 && + zip->pack_stream_remaining == 4) { + /* Source type 1 made by 7zr or 7z with -m options. */ + if (folder->bindPairs[0].inIndex == 5) { + /* The form made by 7zr */ + idx[0] = 1; idx[1] = 2; idx[2] = 0; + scoder[1] = &(fc[1]); + scoder[2] = &(fc[0]); + sunpack[1] = folder->unPackSize[1]; + sunpack[2] = folder->unPackSize[0]; + coder1 = &(fc[2]); + } else { + /* + * NOTE: Some patterns do not work. + * work: + * 7z a -m0=BCJ2 -m1=COPY -m2=COPY + * -m3=(any) + * 7z a -m0=BCJ2 -m1=COPY -m2=(any) + * -m3=COPY + * 7z a -m0=BCJ2 -m1=(any) -m2=COPY + * -m3=COPY + * not work: + * other patterns. + * + * We have to handle this like `pipe' or + * our libarchive7s filter frame work, + * decoding the BCJ2 main stream sequentially, + * m3 -> m2 -> m1 -> BCJ2. + * + */ + if (fc[0].codec == _7Z_COPY && + fc[1].codec == _7Z_COPY) + coder1 = &(folder->coders[2]); + else if (fc[0].codec == _7Z_COPY && + fc[2].codec == _7Z_COPY) + coder1 = &(folder->coders[1]); + else if (fc[1].codec == _7Z_COPY && + fc[2].codec == _7Z_COPY) + coder1 = &(folder->coders[0]); + else { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "Unsupported form of " + "BCJ2 streams"); + return (ARCHIVE_FATAL); + } + } + coder2 = &(fc[3]); + zip->main_stream_bytes_remaining = + (size_t)folder->unPackSize[2]; + } else if (coder2 != NULL && coder2->codec == _7Z_X86_BCJ2 && + zip->pack_stream_remaining == 4 && + folder->numInStreams == 5 && folder->numOutStreams == 2) { + /* Source type 0 made by 7z */ + zip->main_stream_bytes_remaining = + (size_t)folder->unPackSize[0]; + } else { + /* We got an unexpected form. */ + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "Unsupported form of BCJ2 streams"); + return (ARCHIVE_FATAL); + } + + /* Skip the main stream at this time. */ + if ((r = seek_pack(a)) < 0) + return (r); + zip->pack_stream_bytes_unconsumed = + (size_t)zip->pack_stream_inbytes_remaining; + read_consume(a); + + /* Read following three sub streams. */ + for (i = 0; i < 3; i++) { + const struct _7z_coder *coder = scoder[i]; + + if ((r = seek_pack(a)) < 0) { + free(b[0]); free(b[1]); free(b[2]); + return (r); + } + + if (sunpack[i] == (uint64_t)-1) + zip->folder_outbytes_remaining = + zip->pack_stream_inbytes_remaining; + else + zip->folder_outbytes_remaining = sunpack[i]; + + r = init_decompression(a, zip, coder, NULL); + if (r != ARCHIVE_OK) { + free(b[0]); free(b[1]); free(b[2]); + return (ARCHIVE_FATAL); + } + + /* Allocate memory for the decoded data of a sub + * stream. */ + b[i] = malloc((size_t)zip->folder_outbytes_remaining); + if (b[i] == NULL) { + free(b[0]); free(b[1]); free(b[2]); + archive_set_error(&a->archive, ENOMEM, + "No memory for 7-Zip decompression"); + return (ARCHIVE_FATAL); + } + + /* Extract a sub stream. */ + while (zip->pack_stream_inbytes_remaining > 0) { + r = (int)extract_pack_stream(a, 0); + if (r < 0) { + free(b[0]); free(b[1]); free(b[2]); + return (r); + } + bytes = get_uncompressed_data(a, &buff, + zip->uncompressed_buffer_bytes_remaining, + 0); + if (bytes < 0) { + free(b[0]); free(b[1]); free(b[2]); + return ((int)bytes); + } + memcpy(b[i]+s[i], buff, bytes); + s[i] += bytes; + if (zip->pack_stream_bytes_unconsumed) + read_consume(a); + } + } + + /* Set the sub streams to the right place. */ + for (i = 0; i < 3; i++) { + zip->sub_stream_buff[i] = b[idx[i]]; + zip->sub_stream_size[i] = s[idx[i]]; + zip->sub_stream_bytes_remaining[i] = s[idx[i]]; + } + + /* Allocate memory used for decoded main stream bytes. */ + if (zip->tmp_stream_buff == NULL) { + zip->tmp_stream_buff_size = 32 * 1024; + zip->tmp_stream_buff = + malloc(zip->tmp_stream_buff_size); + if (zip->tmp_stream_buff == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for 7-Zip decompression"); + return (ARCHIVE_FATAL); + } + } + zip->tmp_stream_bytes_avail = 0; + zip->tmp_stream_bytes_remaining = 0; + zip->odd_bcj_size = 0; + zip->bcj2_outPos = 0; + + /* + * Reset a stream reader in order to read the main stream + * of BCJ2. + */ + zip->pack_stream_remaining = 1; + zip->pack_stream_index = (unsigned)folder->packIndex; + zip->folder_outbytes_remaining = + folder_uncompressed_size(folder); + zip->uncompressed_buffer_bytes_remaining = 0; + } + + /* + * Initialize the decompressor for the new folder's pack streams. + */ + r = init_decompression(a, zip, coder1, coder2); + if (r != ARCHIVE_OK) + return (ARCHIVE_FATAL); + return (ARCHIVE_OK); +} + +static int64_t +skip_stream(struct archive_read *a, size_t skip_bytes) +{ + struct _7zip *zip = (struct _7zip *)a->format->data; + const void *p; + int64_t skipped_bytes; + size_t bytes = skip_bytes; + + if (zip->folder_index == 0) { + /* + * Optimization for a list mode. + * Avoid unnecessary decoding operations. + */ + zip->si.ci.folders[zip->entry->folderIndex].skipped_bytes + += skip_bytes; + return (skip_bytes); + } + + while (bytes) { + skipped_bytes = read_stream(a, &p, bytes, 0); + if (skipped_bytes < 0) + return (skipped_bytes); + if (skipped_bytes == 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated 7-Zip file body"); + return (ARCHIVE_FATAL); + } + bytes -= (size_t)skipped_bytes; + if (zip->pack_stream_bytes_unconsumed) + read_consume(a); + } + return (skip_bytes); +} + +/* + * Brought from LZMA SDK. + * + * Bra86.c -- Converter for x86 code (BCJ) + * 2008-10-04 : Igor Pavlov : Public domain + * + */ + +#define Test86MSByte(b) ((b) == 0 || (b) == 0xFF) + +static void +x86_Init(struct _7zip *zip) +{ + zip->bcj_state = 0; + zip->bcj_prevPosT = (size_t)0 - 1; + zip->bcj_prevMask = 0; + zip->bcj_ip = 5; +} + +static size_t +x86_Convert(struct _7zip *zip, uint8_t *data, size_t size) +{ + static const uint8_t kMaskToAllowedStatus[8] = {1, 1, 1, 0, 1, 0, 0, 0}; + static const uint8_t kMaskToBitNumber[8] = {0, 1, 2, 2, 3, 3, 3, 3}; + size_t bufferPos, prevPosT; + uint32_t ip, prevMask; + + if (size < 5) + return 0; + + bufferPos = 0; + prevPosT = zip->bcj_prevPosT; + prevMask = zip->bcj_prevMask; + ip = zip->bcj_ip; + + for (;;) { + uint8_t *p = data + bufferPos; + uint8_t *limit = data + size - 4; + + for (; p < limit; p++) + if ((*p & 0xFE) == 0xE8) + break; + bufferPos = (size_t)(p - data); + if (p >= limit) + break; + prevPosT = bufferPos - prevPosT; + if (prevPosT > 3) + prevMask = 0; + else { + prevMask = (prevMask << ((int)prevPosT - 1)) & 0x7; + if (prevMask != 0) { + unsigned char b = + p[4 - kMaskToBitNumber[prevMask]]; + if (!kMaskToAllowedStatus[prevMask] || + Test86MSByte(b)) { + prevPosT = bufferPos; + prevMask = ((prevMask << 1) & 0x7) | 1; + bufferPos++; + continue; + } + } + } + prevPosT = bufferPos; + + if (Test86MSByte(p[4])) { + uint32_t src = ((uint32_t)p[4] << 24) | + ((uint32_t)p[3] << 16) | ((uint32_t)p[2] << 8) | + ((uint32_t)p[1]); + uint32_t dest; + for (;;) { + uint8_t b; + int b_index; + + dest = src - (ip + (uint32_t)bufferPos); + if (prevMask == 0) + break; + b_index = kMaskToBitNumber[prevMask] * 8; + b = (uint8_t)(dest >> (24 - b_index)); + if (!Test86MSByte(b)) + break; + src = dest ^ ((1 << (32 - b_index)) - 1); + } + p[4] = (uint8_t)(~(((dest >> 24) & 1) - 1)); + p[3] = (uint8_t)(dest >> 16); + p[2] = (uint8_t)(dest >> 8); + p[1] = (uint8_t)dest; + bufferPos += 5; + } else { + prevMask = ((prevMask << 1) & 0x7) | 1; + bufferPos++; + } + } + zip->bcj_prevPosT = prevPosT; + zip->bcj_prevMask = prevMask; + zip->bcj_ip += (uint32_t)bufferPos; + return (bufferPos); +} + +/* + * Brought from LZMA SDK. + * + * Bcj2.c -- Converter for x86 code (BCJ2) + * 2008-10-04 : Igor Pavlov : Public domain + * + */ + +#define SZ_ERROR_DATA ARCHIVE_FAILED + +#define IsJcc(b0, b1) ((b0) == 0x0F && ((b1) & 0xF0) == 0x80) +#define IsJ(b0, b1) ((b1 & 0xFE) == 0xE8 || IsJcc(b0, b1)) + +#define kNumTopBits 24 +#define kTopValue ((uint32_t)1 << kNumTopBits) + +#define kNumBitModelTotalBits 11 +#define kBitModelTotal (1 << kNumBitModelTotalBits) +#define kNumMoveBits 5 + +#define RC_READ_BYTE (*buffer++) +#define RC_TEST { if (buffer == bufferLim) return SZ_ERROR_DATA; } +#define RC_INIT2 zip->bcj2_code = 0; zip->bcj2_range = 0xFFFFFFFF; \ + { int ii; for (ii = 0; ii < 5; ii++) { RC_TEST; zip->bcj2_code = (zip->bcj2_code << 8) | RC_READ_BYTE; }} + +#define NORMALIZE if (zip->bcj2_range < kTopValue) { RC_TEST; zip->bcj2_range <<= 8; zip->bcj2_code = (zip->bcj2_code << 8) | RC_READ_BYTE; } + +#define IF_BIT_0(p) ttt = *(p); bound = (zip->bcj2_range >> kNumBitModelTotalBits) * ttt; if (zip->bcj2_code < bound) +#define UPDATE_0(p) zip->bcj2_range = bound; *(p) = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); NORMALIZE; +#define UPDATE_1(p) zip->bcj2_range -= bound; zip->bcj2_code -= bound; *(p) = (CProb)(ttt - (ttt >> kNumMoveBits)); NORMALIZE; + +static ssize_t +Bcj2_Decode(struct _7zip *zip, uint8_t *outBuf, size_t outSize) +{ + size_t inPos = 0, outPos = 0; + const uint8_t *buf0, *buf1, *buf2, *buf3; + size_t size0, size1, size2, size3; + const uint8_t *buffer, *bufferLim; + unsigned int i, j; + + size0 = zip->tmp_stream_bytes_remaining; + buf0 = zip->tmp_stream_buff + zip->tmp_stream_bytes_avail - size0; + size1 = zip->sub_stream_bytes_remaining[0]; + buf1 = zip->sub_stream_buff[0] + zip->sub_stream_size[0] - size1; + size2 = zip->sub_stream_bytes_remaining[1]; + buf2 = zip->sub_stream_buff[1] + zip->sub_stream_size[1] - size2; + size3 = zip->sub_stream_bytes_remaining[2]; + buf3 = zip->sub_stream_buff[2] + zip->sub_stream_size[2] - size3; + + buffer = buf3; + bufferLim = buffer + size3; + + if (zip->bcj_state == 0) { + /* + * Initialize. + */ + zip->bcj2_prevByte = 0; + for (i = 0; + i < sizeof(zip->bcj2_p) / sizeof(zip->bcj2_p[0]); i++) + zip->bcj2_p[i] = kBitModelTotal >> 1; + RC_INIT2; + zip->bcj_state = 1; + } + + /* + * Gather the odd bytes of a previous call. + */ + for (i = 0; zip->odd_bcj_size > 0 && outPos < outSize; i++) { + outBuf[outPos++] = zip->odd_bcj[i]; + zip->odd_bcj_size--; + } + + if (outSize == 0) { + zip->bcj2_outPos += outPos; + return (outPos); + } + + for (;;) { + uint8_t b; + CProb *prob; + uint32_t bound; + uint32_t ttt; + + size_t limit = size0 - inPos; + if (outSize - outPos < limit) + limit = outSize - outPos; + + if (zip->bcj_state == 1) { + while (limit != 0) { + uint8_t bb = buf0[inPos]; + outBuf[outPos++] = bb; + if (IsJ(zip->bcj2_prevByte, bb)) { + zip->bcj_state = 2; + break; + } + inPos++; + zip->bcj2_prevByte = bb; + limit--; + } + } + + if (limit == 0 || outPos == outSize) + break; + zip->bcj_state = 1; + + b = buf0[inPos++]; + + if (b == 0xE8) + prob = zip->bcj2_p + zip->bcj2_prevByte; + else if (b == 0xE9) + prob = zip->bcj2_p + 256; + else + prob = zip->bcj2_p + 257; + + IF_BIT_0(prob) { + UPDATE_0(prob) + zip->bcj2_prevByte = b; + } else { + uint32_t dest; + const uint8_t *v; + uint8_t out[4]; + + UPDATE_1(prob) + if (b == 0xE8) { + v = buf1; + if (size1 < 4) + return SZ_ERROR_DATA; + buf1 += 4; + size1 -= 4; + } else { + v = buf2; + if (size2 < 4) + return SZ_ERROR_DATA; + buf2 += 4; + size2 -= 4; + } + dest = (((uint32_t)v[0] << 24) | + ((uint32_t)v[1] << 16) | + ((uint32_t)v[2] << 8) | + ((uint32_t)v[3])) - + ((uint32_t)zip->bcj2_outPos + (uint32_t)outPos + 4); + out[0] = (uint8_t)dest; + out[1] = (uint8_t)(dest >> 8); + out[2] = (uint8_t)(dest >> 16); + out[3] = zip->bcj2_prevByte = (uint8_t)(dest >> 24); + + for (i = 0; i < 4 && outPos < outSize; i++) + outBuf[outPos++] = out[i]; + if (i < 4) { + /* + * Save odd bytes which we could not add into + * the output buffer because of out of space. + */ + zip->odd_bcj_size = 4 -i; + for (; i < 4; i++) { + j = i - 4 + (unsigned)zip->odd_bcj_size; + zip->odd_bcj[j] = out[i]; + } + break; + } + } + } + zip->tmp_stream_bytes_remaining -= inPos; + zip->sub_stream_bytes_remaining[0] = size1; + zip->sub_stream_bytes_remaining[1] = size2; + zip->sub_stream_bytes_remaining[2] = bufferLim - buffer; + zip->bcj2_outPos += outPos; + + return ((ssize_t)outPos); +} + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_all.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_all.c new file mode 100644 index 0000000000..dea558bbfc --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_all.c @@ -0,0 +1,89 @@ +/*- + * Copyright (c) 2003-2011 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_all.c 174991 2007-12-30 04:58:22Z kientzle $"); + +#include "archive.h" +#include "archive_private.h" + +int +archive_read_support_format_all(struct archive *a) +{ + archive_check_magic(a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_all"); + + /* TODO: It would be nice to compute the ordering + * here automatically so that people who enable just + * a few formats can still get the benefits. That + * may just require the format registration to include + * a "maximum read-ahead" value (anything that uses seek + * would be essentially infinite read-ahead). The core + * bid management can then sort the bidders before calling + * them. + * + * If you implement the above, please return the list below + * to alphabetic order. + */ + + /* + * These bidders are all pretty cheap; they just examine a + * small initial part of the archive. If one of these bids + * high, we can maybe avoid running any of the more expensive + * bidders below. + */ + archive_read_support_format_ar(a); + archive_read_support_format_cpio(a); + archive_read_support_format_empty(a); + archive_read_support_format_lha(a); + archive_read_support_format_mtree(a); + archive_read_support_format_tar(a); + archive_read_support_format_xar(a); + archive_read_support_format_warc(a); + + /* + * Install expensive bidders last. By doing them last, we + * increase the chance that a high bid from someone else will + * make it unnecessary for these to do anything at all. + */ + /* These three have potentially large look-ahead. */ + archive_read_support_format_7zip(a); + archive_read_support_format_cab(a); + archive_read_support_format_rar(a); + archive_read_support_format_rar5(a); + archive_read_support_format_iso9660(a); + /* Seek is really bad, since it forces the read-ahead + * logic to discard buffered data. */ + archive_read_support_format_zip(a); + + /* Note: We always return ARCHIVE_OK here, even if some of the + * above return ARCHIVE_WARN. The intent here is to enable + * "as much as possible." Clients who need specific + * compression should enable those individually so they can + * verify the level of support. */ + /* Clear any warning messages set by the above functions. */ + archive_clear_error(a); + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_ar.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_ar.c new file mode 100644 index 0000000000..296b7db041 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_ar.c @@ -0,0 +1,638 @@ +/*- + * Copyright (c) 2007 Kai Wang + * Copyright (c) 2007 Tim Kientzle + * 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 + * in this position and unchanged. + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_ar.c 201101 2009-12-28 03:06:27Z kientzle $"); + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_read_private.h" + +struct ar { + int64_t entry_bytes_remaining; + /* unconsumed is purely to track data we've gotten from readahead, + * but haven't yet marked as consumed. Must be paired with + * entry_bytes_remaining usage/modification. + */ + size_t entry_bytes_unconsumed; + int64_t entry_offset; + int64_t entry_padding; + char *strtab; + size_t strtab_size; + char read_global_header; +}; + +/* + * Define structure of the "ar" header. + */ +#define AR_name_offset 0 +#define AR_name_size 16 +#define AR_date_offset 16 +#define AR_date_size 12 +#define AR_uid_offset 28 +#define AR_uid_size 6 +#define AR_gid_offset 34 +#define AR_gid_size 6 +#define AR_mode_offset 40 +#define AR_mode_size 8 +#define AR_size_offset 48 +#define AR_size_size 10 +#define AR_fmag_offset 58 +#define AR_fmag_size 2 + +static int archive_read_format_ar_bid(struct archive_read *a, int); +static int archive_read_format_ar_cleanup(struct archive_read *a); +static int archive_read_format_ar_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset); +static int archive_read_format_ar_skip(struct archive_read *a); +static int archive_read_format_ar_read_header(struct archive_read *a, + struct archive_entry *e); +static uint64_t ar_atol8(const char *p, unsigned char_cnt); +static uint64_t ar_atol10(const char *p, unsigned char_cnt); +static int ar_parse_gnu_filename_table(struct archive_read *a); +static int ar_parse_common_header(struct ar *ar, struct archive_entry *, + const char *h); + +int +archive_read_support_format_ar(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct ar *ar; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_ar"); + + ar = (struct ar *)calloc(1, sizeof(*ar)); + if (ar == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate ar data"); + return (ARCHIVE_FATAL); + } + ar->strtab = NULL; + + r = __archive_read_register_format(a, + ar, + "ar", + archive_read_format_ar_bid, + NULL, + archive_read_format_ar_read_header, + archive_read_format_ar_read_data, + archive_read_format_ar_skip, + NULL, + archive_read_format_ar_cleanup, + NULL, + NULL); + + if (r != ARCHIVE_OK) { + free(ar); + return (r); + } + return (ARCHIVE_OK); +} + +static int +archive_read_format_ar_cleanup(struct archive_read *a) +{ + struct ar *ar; + + ar = (struct ar *)(a->format->data); + free(ar->strtab); + free(ar); + (a->format->data) = NULL; + return (ARCHIVE_OK); +} + +static int +archive_read_format_ar_bid(struct archive_read *a, int best_bid) +{ + const void *h; + + (void)best_bid; /* UNUSED */ + + /* + * Verify the 8-byte file signature. + * TODO: Do we need to check more than this? + */ + if ((h = __archive_read_ahead(a, 8, NULL)) == NULL) + return (-1); + if (memcmp(h, "!<arch>\n", 8) == 0) { + return (64); + } + return (-1); +} + +static int +_ar_read_header(struct archive_read *a, struct archive_entry *entry, + struct ar *ar, const char *h, size_t *unconsumed) +{ + char filename[AR_name_size + 1]; + uint64_t number; /* Used to hold parsed numbers before validation. */ + size_t bsd_name_length, entry_size; + char *p, *st; + const void *b; + int r; + + /* Verify the magic signature on the file header. */ + if (strncmp(h + AR_fmag_offset, "`\n", 2) != 0) { + archive_set_error(&a->archive, EINVAL, + "Incorrect file header signature"); + return (ARCHIVE_FATAL); + } + + /* Copy filename into work buffer. */ + strncpy(filename, h + AR_name_offset, AR_name_size); + filename[AR_name_size] = '\0'; + + /* + * Guess the format variant based on the filename. + */ + if (a->archive.archive_format == ARCHIVE_FORMAT_AR) { + /* We don't already know the variant, so let's guess. */ + /* + * Biggest clue is presence of '/': GNU starts special + * filenames with '/', appends '/' as terminator to + * non-special names, so anything with '/' should be + * GNU except for BSD long filenames. + */ + if (strncmp(filename, "#1/", 3) == 0) + a->archive.archive_format = ARCHIVE_FORMAT_AR_BSD; + else if (strchr(filename, '/') != NULL) + a->archive.archive_format = ARCHIVE_FORMAT_AR_GNU; + else if (strncmp(filename, "__.SYMDEF", 9) == 0) + a->archive.archive_format = ARCHIVE_FORMAT_AR_BSD; + /* + * XXX Do GNU/SVR4 'ar' programs ever omit trailing '/' + * if name exactly fills 16-byte field? If so, we + * can't assume entries without '/' are BSD. XXX + */ + } + + /* Update format name from the code. */ + if (a->archive.archive_format == ARCHIVE_FORMAT_AR_GNU) + a->archive.archive_format_name = "ar (GNU/SVR4)"; + else if (a->archive.archive_format == ARCHIVE_FORMAT_AR_BSD) + a->archive.archive_format_name = "ar (BSD)"; + else + a->archive.archive_format_name = "ar"; + + /* + * Remove trailing spaces from the filename. GNU and BSD + * variants both pad filename area out with spaces. + * This will only be wrong if GNU/SVR4 'ar' implementations + * omit trailing '/' for 16-char filenames and we have + * a 16-char filename that ends in ' '. + */ + p = filename + AR_name_size - 1; + while (p >= filename && *p == ' ') { + *p = '\0'; + p--; + } + + /* + * Remove trailing slash unless first character is '/'. + * (BSD entries never end in '/', so this will only trim + * GNU-format entries. GNU special entries start with '/' + * and are not terminated in '/', so we don't trim anything + * that starts with '/'.) + */ + if (filename[0] != '/' && p > filename && *p == '/') { + *p = '\0'; + } + + if (p < filename) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Found entry with empty filename"); + return (ARCHIVE_FATAL); + } + + /* + * '//' is the GNU filename table. + * Later entries can refer to names in this table. + */ + if (strcmp(filename, "//") == 0) { + /* This must come before any call to _read_ahead. */ + ar_parse_common_header(ar, entry, h); + archive_entry_copy_pathname(entry, filename); + archive_entry_set_filetype(entry, AE_IFREG); + /* Get the size of the filename table. */ + number = ar_atol10(h + AR_size_offset, AR_size_size); + if (number > SIZE_MAX || number > 1024 * 1024 * 1024) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Filename table too large"); + return (ARCHIVE_FATAL); + } + entry_size = (size_t)number; + if (entry_size == 0) { + archive_set_error(&a->archive, EINVAL, + "Invalid string table"); + return (ARCHIVE_FATAL); + } + if (ar->strtab != NULL) { + archive_set_error(&a->archive, EINVAL, + "More than one string tables exist"); + return (ARCHIVE_FATAL); + } + + /* Read the filename table into memory. */ + st = malloc(entry_size); + if (st == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate filename table buffer"); + return (ARCHIVE_FATAL); + } + ar->strtab = st; + ar->strtab_size = entry_size; + + if (*unconsumed) { + __archive_read_consume(a, *unconsumed); + *unconsumed = 0; + } + + if ((b = __archive_read_ahead(a, entry_size, NULL)) == NULL) + return (ARCHIVE_FATAL); + memcpy(st, b, entry_size); + __archive_read_consume(a, entry_size); + /* All contents are consumed. */ + ar->entry_bytes_remaining = 0; + archive_entry_set_size(entry, ar->entry_bytes_remaining); + + /* Parse the filename table. */ + return (ar_parse_gnu_filename_table(a)); + } + + /* + * GNU variant handles long filenames by storing /<number> + * to indicate a name stored in the filename table. + * XXX TODO: Verify that it's all digits... Don't be fooled + * by "/9xyz" XXX + */ + if (filename[0] == '/' && filename[1] >= '0' && filename[1] <= '9') { + number = ar_atol10(h + AR_name_offset + 1, AR_name_size - 1); + /* + * If we can't look up the real name, warn and return + * the entry with the wrong name. + */ + if (ar->strtab == NULL || number >= ar->strtab_size) { + archive_set_error(&a->archive, EINVAL, + "Can't find long filename for GNU/SVR4 archive entry"); + archive_entry_copy_pathname(entry, filename); + /* Parse the time, owner, mode, size fields. */ + ar_parse_common_header(ar, entry, h); + return (ARCHIVE_FATAL); + } + + archive_entry_copy_pathname(entry, &ar->strtab[(size_t)number]); + /* Parse the time, owner, mode, size fields. */ + return (ar_parse_common_header(ar, entry, h)); + } + + /* + * BSD handles long filenames by storing "#1/" followed by the + * length of filename as a decimal number, then prepends the + * the filename to the file contents. + */ + if (strncmp(filename, "#1/", 3) == 0) { + /* Parse the time, owner, mode, size fields. */ + /* This must occur before _read_ahead is called again. */ + ar_parse_common_header(ar, entry, h); + + /* Parse the size of the name, adjust the file size. */ + number = ar_atol10(h + AR_name_offset + 3, AR_name_size - 3); + /* Sanity check the filename length: + * = Must be <= SIZE_MAX - 1 + * = Must be <= 1MB + * = Cannot be bigger than the entire entry + */ + if (number > SIZE_MAX - 1 + || number > 1024 * 1024 + || (int64_t)number > ar->entry_bytes_remaining) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Bad input file size"); + return (ARCHIVE_FATAL); + } + bsd_name_length = (size_t)number; + ar->entry_bytes_remaining -= bsd_name_length; + /* Adjust file size reported to client. */ + archive_entry_set_size(entry, ar->entry_bytes_remaining); + + if (*unconsumed) { + __archive_read_consume(a, *unconsumed); + *unconsumed = 0; + } + + /* Read the long name into memory. */ + if ((b = __archive_read_ahead(a, bsd_name_length, NULL)) == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Truncated input file"); + return (ARCHIVE_FATAL); + } + /* Store it in the entry. */ + p = (char *)malloc(bsd_name_length + 1); + if (p == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate fname buffer"); + return (ARCHIVE_FATAL); + } + strncpy(p, b, bsd_name_length); + p[bsd_name_length] = '\0'; + + __archive_read_consume(a, bsd_name_length); + + archive_entry_copy_pathname(entry, p); + free(p); + return (ARCHIVE_OK); + } + + /* + * "/" is the SVR4/GNU archive symbol table. + * "/SYM64/" is the SVR4/GNU 64-bit variant archive symbol table. + */ + if (strcmp(filename, "/") == 0 || strcmp(filename, "/SYM64/") == 0) { + archive_entry_copy_pathname(entry, filename); + /* Parse the time, owner, mode, size fields. */ + r = ar_parse_common_header(ar, entry, h); + /* Force the file type to a regular file. */ + archive_entry_set_filetype(entry, AE_IFREG); + return (r); + } + + /* + * "__.SYMDEF" is a BSD archive symbol table. + */ + if (strcmp(filename, "__.SYMDEF") == 0) { + archive_entry_copy_pathname(entry, filename); + /* Parse the time, owner, mode, size fields. */ + return (ar_parse_common_header(ar, entry, h)); + } + + /* + * Otherwise, this is a standard entry. The filename + * has already been trimmed as much as possible, based + * on our current knowledge of the format. + */ + archive_entry_copy_pathname(entry, filename); + return (ar_parse_common_header(ar, entry, h)); +} + +static int +archive_read_format_ar_read_header(struct archive_read *a, + struct archive_entry *entry) +{ + struct ar *ar = (struct ar*)(a->format->data); + size_t unconsumed; + const void *header_data; + int ret; + + if (!ar->read_global_header) { + /* + * We are now at the beginning of the archive, + * so we need first consume the ar global header. + */ + __archive_read_consume(a, 8); + ar->read_global_header = 1; + /* Set a default format code for now. */ + a->archive.archive_format = ARCHIVE_FORMAT_AR; + } + + /* Read the header for the next file entry. */ + if ((header_data = __archive_read_ahead(a, 60, NULL)) == NULL) + /* Broken header. */ + return (ARCHIVE_EOF); + + unconsumed = 60; + + ret = _ar_read_header(a, entry, ar, (const char *)header_data, &unconsumed); + + if (unconsumed) + __archive_read_consume(a, unconsumed); + + return ret; +} + + +static int +ar_parse_common_header(struct ar *ar, struct archive_entry *entry, + const char *h) +{ + uint64_t n; + + /* Copy remaining header */ + archive_entry_set_filetype(entry, AE_IFREG); + archive_entry_set_mtime(entry, + (time_t)ar_atol10(h + AR_date_offset, AR_date_size), 0L); + archive_entry_set_uid(entry, + (uid_t)ar_atol10(h + AR_uid_offset, AR_uid_size)); + archive_entry_set_gid(entry, + (gid_t)ar_atol10(h + AR_gid_offset, AR_gid_size)); + archive_entry_set_mode(entry, + (mode_t)ar_atol8(h + AR_mode_offset, AR_mode_size)); + n = ar_atol10(h + AR_size_offset, AR_size_size); + + ar->entry_offset = 0; + ar->entry_padding = n % 2; + archive_entry_set_size(entry, n); + ar->entry_bytes_remaining = n; + return (ARCHIVE_OK); +} + +static int +archive_read_format_ar_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + ssize_t bytes_read; + struct ar *ar; + + ar = (struct ar *)(a->format->data); + + if (ar->entry_bytes_unconsumed) { + __archive_read_consume(a, ar->entry_bytes_unconsumed); + ar->entry_bytes_unconsumed = 0; + } + + if (ar->entry_bytes_remaining > 0) { + *buff = __archive_read_ahead(a, 1, &bytes_read); + if (bytes_read == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Truncated ar archive"); + return (ARCHIVE_FATAL); + } + if (bytes_read < 0) + return (ARCHIVE_FATAL); + if (bytes_read > ar->entry_bytes_remaining) + bytes_read = (ssize_t)ar->entry_bytes_remaining; + *size = bytes_read; + ar->entry_bytes_unconsumed = bytes_read; + *offset = ar->entry_offset; + ar->entry_offset += bytes_read; + ar->entry_bytes_remaining -= bytes_read; + return (ARCHIVE_OK); + } else { + int64_t skipped = __archive_read_consume(a, ar->entry_padding); + if (skipped >= 0) { + ar->entry_padding -= skipped; + } + if (ar->entry_padding) { + if (skipped >= 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Truncated ar archive- failed consuming padding"); + } + return (ARCHIVE_FATAL); + } + *buff = NULL; + *size = 0; + *offset = ar->entry_offset; + return (ARCHIVE_EOF); + } +} + +static int +archive_read_format_ar_skip(struct archive_read *a) +{ + int64_t bytes_skipped; + struct ar* ar; + + ar = (struct ar *)(a->format->data); + + bytes_skipped = __archive_read_consume(a, + ar->entry_bytes_remaining + ar->entry_padding + + ar->entry_bytes_unconsumed); + if (bytes_skipped < 0) + return (ARCHIVE_FATAL); + + ar->entry_bytes_remaining = 0; + ar->entry_bytes_unconsumed = 0; + ar->entry_padding = 0; + + return (ARCHIVE_OK); +} + +static int +ar_parse_gnu_filename_table(struct archive_read *a) +{ + struct ar *ar; + char *p; + size_t size; + + ar = (struct ar*)(a->format->data); + size = ar->strtab_size; + + for (p = ar->strtab; p < ar->strtab + size - 1; ++p) { + if (*p == '/') { + *p++ = '\0'; + if (*p != '\n') + goto bad_string_table; + *p = '\0'; + } + } + /* + * GNU ar always pads the table to an even size. + * The pad character is either '\n' or '`'. + */ + if (p != ar->strtab + size && *p != '\n' && *p != '`') + goto bad_string_table; + + /* Enforce zero termination. */ + ar->strtab[size - 1] = '\0'; + + return (ARCHIVE_OK); + +bad_string_table: + archive_set_error(&a->archive, EINVAL, + "Invalid string table"); + free(ar->strtab); + ar->strtab = NULL; + return (ARCHIVE_FATAL); +} + +static uint64_t +ar_atol8(const char *p, unsigned char_cnt) +{ + uint64_t l, limit, last_digit_limit; + unsigned int digit, base; + + base = 8; + limit = UINT64_MAX / base; + last_digit_limit = UINT64_MAX % base; + + while ((*p == ' ' || *p == '\t') && char_cnt-- > 0) + p++; + + l = 0; + digit = *p - '0'; + while (*p >= '0' && digit < base && char_cnt-- > 0) { + if (l>limit || (l == limit && digit > last_digit_limit)) { + l = UINT64_MAX; /* Truncate on overflow. */ + break; + } + l = (l * base) + digit; + digit = *++p - '0'; + } + return (l); +} + +static uint64_t +ar_atol10(const char *p, unsigned char_cnt) +{ + uint64_t l, limit, last_digit_limit; + unsigned int base, digit; + + base = 10; + limit = UINT64_MAX / base; + last_digit_limit = UINT64_MAX % base; + + while ((*p == ' ' || *p == '\t') && char_cnt-- > 0) + p++; + l = 0; + digit = *p - '0'; + while (*p >= '0' && digit < base && char_cnt-- > 0) { + if (l > limit || (l == limit && digit > last_digit_limit)) { + l = UINT64_MAX; /* Truncate on overflow. */ + break; + } + l = (l * base) + digit; + digit = *++p - '0'; + } + return (l); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_by_code.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_by_code.c new file mode 100644 index 0000000000..034353d78f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_by_code.c @@ -0,0 +1,77 @@ +/*- + * Copyright (c) 2003-2011 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#include "archive.h" +#include "archive_private.h" + +int +archive_read_support_format_by_code(struct archive *a, int format_code) +{ + archive_check_magic(a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_by_code"); + + switch (format_code & ARCHIVE_FORMAT_BASE_MASK) { + case ARCHIVE_FORMAT_7ZIP: + return archive_read_support_format_7zip(a); + break; + case ARCHIVE_FORMAT_AR: + return archive_read_support_format_ar(a); + break; + case ARCHIVE_FORMAT_CAB: + return archive_read_support_format_cab(a); + break; + case ARCHIVE_FORMAT_CPIO: + return archive_read_support_format_cpio(a); + break; + case ARCHIVE_FORMAT_ISO9660: + return archive_read_support_format_iso9660(a); + break; + case ARCHIVE_FORMAT_LHA: + return archive_read_support_format_lha(a); + break; + case ARCHIVE_FORMAT_MTREE: + return archive_read_support_format_mtree(a); + break; + case ARCHIVE_FORMAT_RAR: + return archive_read_support_format_rar(a); + break; + case ARCHIVE_FORMAT_RAR_V5: + return archive_read_support_format_rar5(a); + break; + case ARCHIVE_FORMAT_TAR: + return archive_read_support_format_tar(a); + break; + case ARCHIVE_FORMAT_XAR: + return archive_read_support_format_xar(a); + break; + case ARCHIVE_FORMAT_ZIP: + return archive_read_support_format_zip(a); + break; + } + return (ARCHIVE_FATAL); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_cab.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_cab.c new file mode 100644 index 0000000000..a6475308e0 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_cab.c @@ -0,0 +1,3227 @@ +/*- + * Copyright (c) 2010-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_ZLIB_H +#include <zlib.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_read_private.h" +#include "archive_endian.h" + + +struct lzx_dec { + /* Decoding status. */ + int state; + + /* + * Window to see last decoded data, from 32KBi to 2MBi. + */ + int w_size; + int w_mask; + /* Window buffer, which is a loop buffer. */ + unsigned char *w_buff; + /* The insert position to the window. */ + int w_pos; + /* The position where we can copy decoded code from the window. */ + int copy_pos; + /* The length how many bytes we can copy decoded code from + * the window. */ + int copy_len; + /* Translation reversal for x86 processor CALL byte sequence(E8). + * This is used for LZX only. */ + uint32_t translation_size; + char translation; + char block_type; +#define VERBATIM_BLOCK 1 +#define ALIGNED_OFFSET_BLOCK 2 +#define UNCOMPRESSED_BLOCK 3 + size_t block_size; + size_t block_bytes_avail; + /* Repeated offset. */ + int r0, r1, r2; + unsigned char rbytes[4]; + int rbytes_avail; + int length_header; + int position_slot; + int offset_bits; + + struct lzx_pos_tbl { + int base; + int footer_bits; + } *pos_tbl; + /* + * Bit stream reader. + */ + struct lzx_br { +#define CACHE_TYPE uint64_t +#define CACHE_BITS (8 * sizeof(CACHE_TYPE)) + /* Cache buffer. */ + CACHE_TYPE cache_buffer; + /* Indicates how many bits avail in cache_buffer. */ + int cache_avail; + unsigned char odd; + char have_odd; + } br; + + /* + * Huffman coding. + */ + struct huffman { + int len_size; + int freq[17]; + unsigned char *bitlen; + + /* + * Use a index table. It's faster than searching a huffman + * coding tree, which is a binary tree. But a use of a large + * index table causes L1 cache read miss many times. + */ + int max_bits; + int tbl_bits; + int tree_used; + /* Direct access table. */ + uint16_t *tbl; + } at, lt, mt, pt; + + int loop; + int error; +}; + +static const int slots[] = { + 30, 32, 34, 36, 38, 42, 50, 66, 98, 162, 290 +}; +#define SLOT_BASE 15 +#define SLOT_MAX 21/*->25*/ + +struct lzx_stream { + const unsigned char *next_in; + int64_t avail_in; + int64_t total_in; + unsigned char *next_out; + int64_t avail_out; + int64_t total_out; + struct lzx_dec *ds; +}; + +/* + * Cabinet file definitions. + */ +/* CFHEADER offset */ +#define CFHEADER_signature 0 +#define CFHEADER_cbCabinet 8 +#define CFHEADER_coffFiles 16 +#define CFHEADER_versionMinor 24 +#define CFHEADER_versionMajor 25 +#define CFHEADER_cFolders 26 +#define CFHEADER_cFiles 28 +#define CFHEADER_flags 30 +#define CFHEADER_setID 32 +#define CFHEADER_iCabinet 34 +#define CFHEADER_cbCFHeader 36 +#define CFHEADER_cbCFFolder 38 +#define CFHEADER_cbCFData 39 + +/* CFFOLDER offset */ +#define CFFOLDER_coffCabStart 0 +#define CFFOLDER_cCFData 4 +#define CFFOLDER_typeCompress 6 +#define CFFOLDER_abReserve 8 + +/* CFFILE offset */ +#define CFFILE_cbFile 0 +#define CFFILE_uoffFolderStart 4 +#define CFFILE_iFolder 8 +#define CFFILE_date_time 10 +#define CFFILE_attribs 14 + +/* CFDATA offset */ +#define CFDATA_csum 0 +#define CFDATA_cbData 4 +#define CFDATA_cbUncomp 6 + +static const char * const compression_name[] = { + "NONE", + "MSZIP", + "Quantum", + "LZX", +}; + +struct cfdata { + /* Sum value of this CFDATA. */ + uint32_t sum; + uint16_t compressed_size; + uint16_t compressed_bytes_remaining; + uint16_t uncompressed_size; + uint16_t uncompressed_bytes_remaining; + /* To know how many bytes we have decompressed. */ + uint16_t uncompressed_avail; + /* Offset from the beginning of compressed data of this CFDATA */ + uint16_t read_offset; + int64_t unconsumed; + /* To keep memory image of this CFDATA to compute the sum. */ + size_t memimage_size; + unsigned char *memimage; + /* Result of calculation of sum. */ + uint32_t sum_calculated; + unsigned char sum_extra[4]; + int sum_extra_avail; + const void *sum_ptr; +}; + +struct cffolder { + uint32_t cfdata_offset_in_cab; + uint16_t cfdata_count; + uint16_t comptype; +#define COMPTYPE_NONE 0x0000 +#define COMPTYPE_MSZIP 0x0001 +#define COMPTYPE_QUANTUM 0x0002 +#define COMPTYPE_LZX 0x0003 + uint16_t compdata; + const char *compname; + /* At the time reading CFDATA */ + struct cfdata cfdata; + int cfdata_index; + /* Flags to mark progress of decompression. */ + char decompress_init; +}; + +struct cffile { + uint32_t uncompressed_size; + uint32_t offset; + time_t mtime; + uint16_t folder; +#define iFoldCONTINUED_FROM_PREV 0xFFFD +#define iFoldCONTINUED_TO_NEXT 0xFFFE +#define iFoldCONTINUED_PREV_AND_NEXT 0xFFFF + unsigned char attr; +#define ATTR_RDONLY 0x01 +#define ATTR_NAME_IS_UTF 0x80 + struct archive_string pathname; +}; + +struct cfheader { + /* Total bytes of all file size in a Cabinet. */ + uint32_t total_bytes; + uint32_t files_offset; + uint16_t folder_count; + uint16_t file_count; + uint16_t flags; +#define PREV_CABINET 0x0001 +#define NEXT_CABINET 0x0002 +#define RESERVE_PRESENT 0x0004 + uint16_t setid; + uint16_t cabinet; + /* Version number. */ + unsigned char major; + unsigned char minor; + unsigned char cffolder; + unsigned char cfdata; + /* All folders in a cabinet. */ + struct cffolder *folder_array; + /* All files in a cabinet. */ + struct cffile *file_array; + int file_index; +}; + +struct cab { + /* entry_bytes_remaining is the number of bytes we expect. */ + int64_t entry_offset; + int64_t entry_bytes_remaining; + int64_t entry_unconsumed; + int64_t entry_compressed_bytes_read; + int64_t entry_uncompressed_bytes_read; + struct cffolder *entry_cffolder; + struct cffile *entry_cffile; + struct cfdata *entry_cfdata; + + /* Offset from beginning of a cabinet file. */ + int64_t cab_offset; + struct cfheader cfheader; + struct archive_wstring ws; + + /* Flag to mark progress that an archive was read their first header.*/ + char found_header; + char end_of_archive; + char end_of_entry; + char end_of_entry_cleanup; + char read_data_invoked; + int64_t bytes_skipped; + + unsigned char *uncompressed_buffer; + size_t uncompressed_buffer_size; + + int init_default_conversion; + struct archive_string_conv *sconv; + struct archive_string_conv *sconv_default; + struct archive_string_conv *sconv_utf8; + char format_name[64]; + +#ifdef HAVE_ZLIB_H + z_stream stream; + char stream_valid; +#endif + struct lzx_stream xstrm; +}; + +static int archive_read_format_cab_bid(struct archive_read *, int); +static int archive_read_format_cab_options(struct archive_read *, + const char *, const char *); +static int archive_read_format_cab_read_header(struct archive_read *, + struct archive_entry *); +static int archive_read_format_cab_read_data(struct archive_read *, + const void **, size_t *, int64_t *); +static int archive_read_format_cab_read_data_skip(struct archive_read *); +static int archive_read_format_cab_cleanup(struct archive_read *); + +static int cab_skip_sfx(struct archive_read *); +static time_t cab_dos_time(const unsigned char *); +static int cab_read_data(struct archive_read *, const void **, + size_t *, int64_t *); +static int cab_read_header(struct archive_read *); +static uint32_t cab_checksum_cfdata_4(const void *, size_t bytes, uint32_t); +static uint32_t cab_checksum_cfdata(const void *, size_t bytes, uint32_t); +static void cab_checksum_update(struct archive_read *, size_t); +static int cab_checksum_finish(struct archive_read *); +static int cab_next_cfdata(struct archive_read *); +static const void *cab_read_ahead_cfdata(struct archive_read *, ssize_t *); +static const void *cab_read_ahead_cfdata_none(struct archive_read *, ssize_t *); +static const void *cab_read_ahead_cfdata_deflate(struct archive_read *, + ssize_t *); +static const void *cab_read_ahead_cfdata_lzx(struct archive_read *, + ssize_t *); +static int64_t cab_consume_cfdata(struct archive_read *, int64_t); +static int64_t cab_minimum_consume_cfdata(struct archive_read *, int64_t); +static int lzx_decode_init(struct lzx_stream *, int); +static int lzx_read_blocks(struct lzx_stream *, int); +static int lzx_decode_blocks(struct lzx_stream *, int); +static void lzx_decode_free(struct lzx_stream *); +static void lzx_translation(struct lzx_stream *, void *, size_t, uint32_t); +static void lzx_cleanup_bitstream(struct lzx_stream *); +static int lzx_decode(struct lzx_stream *, int); +static int lzx_read_pre_tree(struct lzx_stream *); +static int lzx_read_bitlen(struct lzx_stream *, struct huffman *, int); +static int lzx_huffman_init(struct huffman *, size_t, int); +static void lzx_huffman_free(struct huffman *); +static int lzx_make_huffman_table(struct huffman *); +static inline int lzx_decode_huffman(struct huffman *, unsigned); + + +int +archive_read_support_format_cab(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct cab *cab; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_cab"); + + cab = (struct cab *)calloc(1, sizeof(*cab)); + if (cab == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate CAB data"); + return (ARCHIVE_FATAL); + } + archive_string_init(&cab->ws); + archive_wstring_ensure(&cab->ws, 256); + + r = __archive_read_register_format(a, + cab, + "cab", + archive_read_format_cab_bid, + archive_read_format_cab_options, + archive_read_format_cab_read_header, + archive_read_format_cab_read_data, + archive_read_format_cab_read_data_skip, + NULL, + archive_read_format_cab_cleanup, + NULL, + NULL); + + if (r != ARCHIVE_OK) + free(cab); + return (ARCHIVE_OK); +} + +static int +find_cab_magic(const char *p) +{ + switch (p[4]) { + case 0: + /* + * Note: Self-Extraction program has 'MSCF' string in their + * program. If we were finding 'MSCF' string only, we got + * wrong place for Cabinet header, thus, we have to check + * following four bytes which are reserved and must be set + * to zero. + */ + if (memcmp(p, "MSCF\0\0\0\0", 8) == 0) + return 0; + return 5; + case 'F': return 1; + case 'C': return 2; + case 'S': return 3; + case 'M': return 4; + default: return 5; + } +} + +static int +archive_read_format_cab_bid(struct archive_read *a, int best_bid) +{ + const char *p; + ssize_t bytes_avail, offset, window; + + /* If there's already a better bid than we can ever + make, don't bother testing. */ + if (best_bid > 64) + return (-1); + + if ((p = __archive_read_ahead(a, 8, NULL)) == NULL) + return (-1); + + if (memcmp(p, "MSCF\0\0\0\0", 8) == 0) + return (64); + + /* + * Attempt to handle self-extracting archives + * by noting a PE header and searching forward + * up to 128k for a 'MSCF' marker. + */ + if (p[0] == 'M' && p[1] == 'Z') { + offset = 0; + window = 4096; + while (offset < (1024 * 128)) { + const char *h = __archive_read_ahead(a, offset + window, + &bytes_avail); + if (h == NULL) { + /* Remaining bytes are less than window. */ + window >>= 1; + if (window < 128) + return (0); + continue; + } + p = h + offset; + while (p + 8 < h + bytes_avail) { + int next; + if ((next = find_cab_magic(p)) == 0) + return (64); + p += next; + } + offset = p - h; + } + } + return (0); +} + +static int +archive_read_format_cab_options(struct archive_read *a, + const char *key, const char *val) +{ + struct cab *cab; + int ret = ARCHIVE_FAILED; + + cab = (struct cab *)(a->format->data); + if (strcmp(key, "hdrcharset") == 0) { + if (val == NULL || val[0] == 0) + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "cab: hdrcharset option needs a character-set name"); + else { + cab->sconv = archive_string_conversion_from_charset( + &a->archive, val, 0); + if (cab->sconv != NULL) + ret = ARCHIVE_OK; + else + ret = ARCHIVE_FATAL; + } + return (ret); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static int +cab_skip_sfx(struct archive_read *a) +{ + const char *p, *q; + size_t skip; + ssize_t bytes, window; + + window = 4096; + for (;;) { + const char *h = __archive_read_ahead(a, window, &bytes); + if (h == NULL) { + /* Remaining size are less than window. */ + window >>= 1; + if (window < 128) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Couldn't find out CAB header"); + return (ARCHIVE_FATAL); + } + continue; + } + p = h; + q = p + bytes; + + /* + * Scan ahead until we find something that looks + * like the cab header. + */ + while (p + 8 < q) { + int next; + if ((next = find_cab_magic(p)) == 0) { + skip = p - h; + __archive_read_consume(a, skip); + return (ARCHIVE_OK); + } + p += next; + } + skip = p - h; + __archive_read_consume(a, skip); + } +} + +static int +truncated_error(struct archive_read *a) +{ + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated CAB header"); + return (ARCHIVE_FATAL); +} + +static ssize_t +cab_strnlen(const unsigned char *p, size_t maxlen) +{ + size_t i; + + for (i = 0; i <= maxlen; i++) { + if (p[i] == 0) + break; + } + if (i > maxlen) + return (-1);/* invalid */ + return ((ssize_t)i); +} + +/* Read bytes as much as remaining. */ +static const void * +cab_read_ahead_remaining(struct archive_read *a, size_t min, ssize_t *avail) +{ + const void *p; + + while (min > 0) { + p = __archive_read_ahead(a, min, avail); + if (p != NULL) + return (p); + min--; + } + return (NULL); +} + +/* Convert a path separator '\' -> '/' */ +static int +cab_convert_path_separator_1(struct archive_string *fn, unsigned char attr) +{ + size_t i; + int mb; + + /* Easy check if we have '\' in multi-byte string. */ + mb = 0; + for (i = 0; i < archive_strlen(fn); i++) { + if (fn->s[i] == '\\') { + if (mb) { + /* This may be second byte of multi-byte + * character. */ + break; + } + fn->s[i] = '/'; + mb = 0; + } else if ((fn->s[i] & 0x80) && !(attr & ATTR_NAME_IS_UTF)) + mb = 1; + else + mb = 0; + } + if (i == archive_strlen(fn)) + return (0); + return (-1); +} + +/* + * Replace a character '\' with '/' in wide character. + */ +static void +cab_convert_path_separator_2(struct cab *cab, struct archive_entry *entry) +{ + const wchar_t *wp; + size_t i; + + /* If a conversion to wide character failed, force the replacement. */ + if ((wp = archive_entry_pathname_w(entry)) != NULL) { + archive_wstrcpy(&(cab->ws), wp); + for (i = 0; i < archive_strlen(&(cab->ws)); i++) { + if (cab->ws.s[i] == L'\\') + cab->ws.s[i] = L'/'; + } + archive_entry_copy_pathname_w(entry, cab->ws.s); + } +} + +/* + * Read CFHEADER, CFFOLDER and CFFILE. + */ +static int +cab_read_header(struct archive_read *a) +{ + const unsigned char *p; + struct cab *cab; + struct cfheader *hd; + size_t bytes, used; + ssize_t len; + int64_t skip; + int err, i; + int cur_folder, prev_folder; + uint32_t offset32; + + a->archive.archive_format = ARCHIVE_FORMAT_CAB; + if (a->archive.archive_format_name == NULL) + a->archive.archive_format_name = "CAB"; + + if ((p = __archive_read_ahead(a, 42, NULL)) == NULL) + return (truncated_error(a)); + + cab = (struct cab *)(a->format->data); + if (cab->found_header == 0 && + p[0] == 'M' && p[1] == 'Z') { + /* This is an executable? Must be self-extracting... */ + err = cab_skip_sfx(a); + if (err < ARCHIVE_WARN) + return (err); + + /* Re-read header after processing the SFX. */ + if ((p = __archive_read_ahead(a, 42, NULL)) == NULL) + return (truncated_error(a)); + } + + cab->cab_offset = 0; + /* + * Read CFHEADER. + */ + hd = &cab->cfheader; + if (p[CFHEADER_signature+0] != 'M' || p[CFHEADER_signature+1] != 'S' || + p[CFHEADER_signature+2] != 'C' || p[CFHEADER_signature+3] != 'F') { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Couldn't find out CAB header"); + return (ARCHIVE_FATAL); + } + hd->total_bytes = archive_le32dec(p + CFHEADER_cbCabinet); + hd->files_offset = archive_le32dec(p + CFHEADER_coffFiles); + hd->minor = p[CFHEADER_versionMinor]; + hd->major = p[CFHEADER_versionMajor]; + hd->folder_count = archive_le16dec(p + CFHEADER_cFolders); + if (hd->folder_count == 0) + goto invalid; + hd->file_count = archive_le16dec(p + CFHEADER_cFiles); + if (hd->file_count == 0) + goto invalid; + hd->flags = archive_le16dec(p + CFHEADER_flags); + hd->setid = archive_le16dec(p + CFHEADER_setID); + hd->cabinet = archive_le16dec(p + CFHEADER_iCabinet); + used = CFHEADER_iCabinet + 2; + if (hd->flags & RESERVE_PRESENT) { + uint16_t cfheader; + cfheader = archive_le16dec(p + CFHEADER_cbCFHeader); + if (cfheader > 60000U) + goto invalid; + hd->cffolder = p[CFHEADER_cbCFFolder]; + hd->cfdata = p[CFHEADER_cbCFData]; + used += 4;/* cbCFHeader, cbCFFolder and cbCFData */ + used += cfheader;/* abReserve */ + } else + hd->cffolder = 0;/* Avoid compiling warning. */ + if (hd->flags & PREV_CABINET) { + /* How many bytes are used for szCabinetPrev. */ + if ((p = __archive_read_ahead(a, used+256, NULL)) == NULL) + return (truncated_error(a)); + if ((len = cab_strnlen(p + used, 255)) <= 0) + goto invalid; + used += len + 1; + /* How many bytes are used for szDiskPrev. */ + if ((p = __archive_read_ahead(a, used+256, NULL)) == NULL) + return (truncated_error(a)); + if ((len = cab_strnlen(p + used, 255)) <= 0) + goto invalid; + used += len + 1; + } + if (hd->flags & NEXT_CABINET) { + /* How many bytes are used for szCabinetNext. */ + if ((p = __archive_read_ahead(a, used+256, NULL)) == NULL) + return (truncated_error(a)); + if ((len = cab_strnlen(p + used, 255)) <= 0) + goto invalid; + used += len + 1; + /* How many bytes are used for szDiskNext. */ + if ((p = __archive_read_ahead(a, used+256, NULL)) == NULL) + return (truncated_error(a)); + if ((len = cab_strnlen(p + used, 255)) <= 0) + goto invalid; + used += len + 1; + } + __archive_read_consume(a, used); + cab->cab_offset += used; + used = 0; + + /* + * Read CFFOLDER. + */ + hd->folder_array = (struct cffolder *)calloc( + hd->folder_count, sizeof(struct cffolder)); + if (hd->folder_array == NULL) + goto nomem; + + bytes = 8; + if (hd->flags & RESERVE_PRESENT) + bytes += hd->cffolder; + bytes *= hd->folder_count; + if ((p = __archive_read_ahead(a, bytes, NULL)) == NULL) + return (truncated_error(a)); + offset32 = 0; + for (i = 0; i < hd->folder_count; i++) { + struct cffolder *folder = &(hd->folder_array[i]); + folder->cfdata_offset_in_cab = + archive_le32dec(p + CFFOLDER_coffCabStart); + folder->cfdata_count = archive_le16dec(p+CFFOLDER_cCFData); + folder->comptype = + archive_le16dec(p+CFFOLDER_typeCompress) & 0x0F; + folder->compdata = + archive_le16dec(p+CFFOLDER_typeCompress) >> 8; + /* Get a compression name. */ + if (folder->comptype < + sizeof(compression_name) / sizeof(compression_name[0])) + folder->compname = compression_name[folder->comptype]; + else + folder->compname = "UNKNOWN"; + p += 8; + used += 8; + if (hd->flags & RESERVE_PRESENT) { + p += hd->cffolder;/* abReserve */ + used += hd->cffolder; + } + /* + * Sanity check if each data is acceptable. + */ + if (offset32 >= folder->cfdata_offset_in_cab) + goto invalid; + offset32 = folder->cfdata_offset_in_cab; + + /* Set a request to initialize zlib for the CFDATA of + * this folder. */ + folder->decompress_init = 0; + } + __archive_read_consume(a, used); + cab->cab_offset += used; + + /* + * Read CFFILE. + */ + /* Seek read pointer to the offset of CFFILE if needed. */ + skip = (int64_t)hd->files_offset - cab->cab_offset; + if (skip < 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid offset of CFFILE %jd < %jd", + (intmax_t)hd->files_offset, (intmax_t)cab->cab_offset); + return (ARCHIVE_FATAL); + } + if (skip) { + __archive_read_consume(a, skip); + cab->cab_offset += skip; + } + /* Allocate memory for CFDATA */ + hd->file_array = (struct cffile *)calloc( + hd->file_count, sizeof(struct cffile)); + if (hd->file_array == NULL) + goto nomem; + + prev_folder = -1; + for (i = 0; i < hd->file_count; i++) { + struct cffile *file = &(hd->file_array[i]); + ssize_t avail; + + if ((p = __archive_read_ahead(a, 16, NULL)) == NULL) + return (truncated_error(a)); + file->uncompressed_size = archive_le32dec(p + CFFILE_cbFile); + file->offset = archive_le32dec(p + CFFILE_uoffFolderStart); + file->folder = archive_le16dec(p + CFFILE_iFolder); + file->mtime = cab_dos_time(p + CFFILE_date_time); + file->attr = (uint8_t)archive_le16dec(p + CFFILE_attribs); + __archive_read_consume(a, 16); + + cab->cab_offset += 16; + if ((p = cab_read_ahead_remaining(a, 256, &avail)) == NULL) + return (truncated_error(a)); + if ((len = cab_strnlen(p, avail-1)) <= 0) + goto invalid; + + /* Copy a pathname. */ + archive_string_init(&(file->pathname)); + archive_strncpy(&(file->pathname), p, len); + __archive_read_consume(a, len + 1); + cab->cab_offset += len + 1; + + /* + * Sanity check if each data is acceptable. + */ + if (file->uncompressed_size > 0x7FFF8000) + goto invalid;/* Too large */ + if ((int64_t)file->offset + (int64_t)file->uncompressed_size + > ARCHIVE_LITERAL_LL(0x7FFF8000)) + goto invalid;/* Too large */ + switch (file->folder) { + case iFoldCONTINUED_TO_NEXT: + /* This must be last file in a folder. */ + if (i != hd->file_count -1) + goto invalid; + cur_folder = hd->folder_count -1; + break; + case iFoldCONTINUED_PREV_AND_NEXT: + /* This must be only one file in a folder. */ + if (hd->file_count != 1) + goto invalid; + /* FALL THROUGH */ + case iFoldCONTINUED_FROM_PREV: + /* This must be first file in a folder. */ + if (i != 0) + goto invalid; + prev_folder = cur_folder = 0; + offset32 = file->offset; + break; + default: + if (file->folder >= hd->folder_count) + goto invalid; + cur_folder = file->folder; + break; + } + /* Dot not back track. */ + if (cur_folder < prev_folder) + goto invalid; + if (cur_folder != prev_folder) + offset32 = 0; + prev_folder = cur_folder; + + /* Make sure there are not any blanks from last file + * contents. */ + if (offset32 != file->offset) + goto invalid; + offset32 += file->uncompressed_size; + + /* CFDATA is available for file contents. */ + if (file->uncompressed_size > 0 && + hd->folder_array[cur_folder].cfdata_count == 0) + goto invalid; + } + + if (hd->cabinet != 0 || hd->flags & (PREV_CABINET | NEXT_CABINET)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Multivolume cabinet file is unsupported"); + return (ARCHIVE_WARN); + } + return (ARCHIVE_OK); +invalid: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid CAB header"); + return (ARCHIVE_FATAL); +nomem: + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for CAB data"); + return (ARCHIVE_FATAL); +} + +static int +archive_read_format_cab_read_header(struct archive_read *a, + struct archive_entry *entry) +{ + struct cab *cab; + struct cfheader *hd; + struct cffolder *prev_folder; + struct cffile *file; + struct archive_string_conv *sconv; + int err = ARCHIVE_OK, r; + + cab = (struct cab *)(a->format->data); + if (cab->found_header == 0) { + err = cab_read_header(a); + if (err < ARCHIVE_WARN) + return (err); + /* We've found the header. */ + cab->found_header = 1; + } + hd = &cab->cfheader; + + if (hd->file_index >= hd->file_count) { + cab->end_of_archive = 1; + return (ARCHIVE_EOF); + } + file = &hd->file_array[hd->file_index++]; + + cab->end_of_entry = 0; + cab->end_of_entry_cleanup = 0; + cab->entry_compressed_bytes_read = 0; + cab->entry_uncompressed_bytes_read = 0; + cab->entry_unconsumed = 0; + cab->entry_cffile = file; + + /* + * Choose a proper folder. + */ + prev_folder = cab->entry_cffolder; + switch (file->folder) { + case iFoldCONTINUED_FROM_PREV: + case iFoldCONTINUED_PREV_AND_NEXT: + cab->entry_cffolder = &hd->folder_array[0]; + break; + case iFoldCONTINUED_TO_NEXT: + cab->entry_cffolder = &hd->folder_array[hd->folder_count-1]; + break; + default: + cab->entry_cffolder = &hd->folder_array[file->folder]; + break; + } + /* If a cffolder of this file is changed, reset a cfdata to read + * file contents from next cfdata. */ + if (prev_folder != cab->entry_cffolder) + cab->entry_cfdata = NULL; + + /* If a pathname is UTF-8, prepare a string conversion object + * for UTF-8 and use it. */ + if (file->attr & ATTR_NAME_IS_UTF) { + if (cab->sconv_utf8 == NULL) { + cab->sconv_utf8 = + archive_string_conversion_from_charset( + &(a->archive), "UTF-8", 1); + if (cab->sconv_utf8 == NULL) + return (ARCHIVE_FATAL); + } + sconv = cab->sconv_utf8; + } else if (cab->sconv != NULL) { + /* Choose the conversion specified by the option. */ + sconv = cab->sconv; + } else { + /* Choose the default conversion. */ + if (!cab->init_default_conversion) { + cab->sconv_default = + archive_string_default_conversion_for_read( + &(a->archive)); + cab->init_default_conversion = 1; + } + sconv = cab->sconv_default; + } + + /* + * Set a default value and common data + */ + r = cab_convert_path_separator_1(&(file->pathname), file->attr); + if (archive_entry_copy_pathname_l(entry, file->pathname.s, + archive_strlen(&(file->pathname)), sconv) != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Pathname cannot be converted " + "from %s to current locale.", + archive_string_conversion_charset_name(sconv)); + err = ARCHIVE_WARN; + } + if (r < 0) { + /* Convert a path separator '\' -> '/' */ + cab_convert_path_separator_2(cab, entry); + } + + archive_entry_set_size(entry, file->uncompressed_size); + if (file->attr & ATTR_RDONLY) + archive_entry_set_mode(entry, AE_IFREG | 0555); + else + archive_entry_set_mode(entry, AE_IFREG | 0666); + archive_entry_set_mtime(entry, file->mtime, 0); + + cab->entry_bytes_remaining = file->uncompressed_size; + cab->entry_offset = 0; + /* We don't need compress data. */ + if (file->uncompressed_size == 0) + cab->end_of_entry_cleanup = cab->end_of_entry = 1; + + /* Set up a more descriptive format name. */ + sprintf(cab->format_name, "CAB %d.%d (%s)", + hd->major, hd->minor, cab->entry_cffolder->compname); + a->archive.archive_format_name = cab->format_name; + + return (err); +} + +static int +archive_read_format_cab_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + struct cab *cab = (struct cab *)(a->format->data); + int r; + + switch (cab->entry_cffile->folder) { + case iFoldCONTINUED_FROM_PREV: + case iFoldCONTINUED_TO_NEXT: + case iFoldCONTINUED_PREV_AND_NEXT: + *buff = NULL; + *size = 0; + *offset = 0; + archive_clear_error(&a->archive); + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Cannot restore this file split in multivolume."); + return (ARCHIVE_FAILED); + default: + break; + } + if (cab->read_data_invoked == 0) { + if (cab->bytes_skipped) { + if (cab->entry_cfdata == NULL) { + r = cab_next_cfdata(a); + if (r < 0) + return (r); + } + if (cab_consume_cfdata(a, cab->bytes_skipped) < 0) + return (ARCHIVE_FATAL); + cab->bytes_skipped = 0; + } + cab->read_data_invoked = 1; + } + if (cab->entry_unconsumed) { + /* Consume as much as the compressor actually used. */ + r = (int)cab_consume_cfdata(a, cab->entry_unconsumed); + cab->entry_unconsumed = 0; + if (r < 0) + return (r); + } + if (cab->end_of_archive || cab->end_of_entry) { + if (!cab->end_of_entry_cleanup) { + /* End-of-entry cleanup done. */ + cab->end_of_entry_cleanup = 1; + } + *offset = cab->entry_offset; + *size = 0; + *buff = NULL; + return (ARCHIVE_EOF); + } + + return (cab_read_data(a, buff, size, offset)); +} + +static uint32_t +cab_checksum_cfdata_4(const void *p, size_t bytes, uint32_t seed) +{ + const unsigned char *b; + unsigned u32num; + uint32_t sum; + + u32num = (unsigned)bytes / 4; + sum = seed; + b = p; + for (;u32num > 0; --u32num) { + sum ^= archive_le32dec(b); + b += 4; + } + return (sum); +} + +static uint32_t +cab_checksum_cfdata(const void *p, size_t bytes, uint32_t seed) +{ + const unsigned char *b; + uint32_t sum; + uint32_t t; + + sum = cab_checksum_cfdata_4(p, bytes, seed); + b = p; + b += bytes & ~3; + t = 0; + switch (bytes & 3) { + case 3: + t |= ((uint32_t)(*b++)) << 16; + /* FALL THROUGH */ + case 2: + t |= ((uint32_t)(*b++)) << 8; + /* FALL THROUGH */ + case 1: + t |= *b; + /* FALL THROUGH */ + default: + break; + } + sum ^= t; + + return (sum); +} + +static void +cab_checksum_update(struct archive_read *a, size_t bytes) +{ + struct cab *cab = (struct cab *)(a->format->data); + struct cfdata *cfdata = cab->entry_cfdata; + const unsigned char *p; + size_t sumbytes; + + if (cfdata->sum == 0 || cfdata->sum_ptr == NULL) + return; + /* + * Calculate the sum of this CFDATA. + * Make sure CFDATA must be calculated in four bytes. + */ + p = cfdata->sum_ptr; + sumbytes = bytes; + if (cfdata->sum_extra_avail) { + while (cfdata->sum_extra_avail < 4 && sumbytes > 0) { + cfdata->sum_extra[ + cfdata->sum_extra_avail++] = *p++; + sumbytes--; + } + if (cfdata->sum_extra_avail == 4) { + cfdata->sum_calculated = cab_checksum_cfdata_4( + cfdata->sum_extra, 4, cfdata->sum_calculated); + cfdata->sum_extra_avail = 0; + } + } + if (sumbytes) { + int odd = sumbytes & 3; + if (sumbytes - odd > 0) + cfdata->sum_calculated = cab_checksum_cfdata_4( + p, sumbytes - odd, cfdata->sum_calculated); + if (odd) + memcpy(cfdata->sum_extra, p + sumbytes - odd, odd); + cfdata->sum_extra_avail = odd; + } + cfdata->sum_ptr = NULL; +} + +static int +cab_checksum_finish(struct archive_read *a) +{ + struct cab *cab = (struct cab *)(a->format->data); + struct cfdata *cfdata = cab->entry_cfdata; + int l; + + /* Do not need to compute a sum. */ + if (cfdata->sum == 0) + return (ARCHIVE_OK); + + /* + * Calculate the sum of remaining CFDATA. + */ + if (cfdata->sum_extra_avail) { + cfdata->sum_calculated = + cab_checksum_cfdata(cfdata->sum_extra, + cfdata->sum_extra_avail, cfdata->sum_calculated); + cfdata->sum_extra_avail = 0; + } + + l = 4; + if (cab->cfheader.flags & RESERVE_PRESENT) + l += cab->cfheader.cfdata; + cfdata->sum_calculated = cab_checksum_cfdata( + cfdata->memimage + CFDATA_cbData, l, cfdata->sum_calculated); + if (cfdata->sum_calculated != cfdata->sum) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Checksum error CFDATA[%d] %x:%x in %d bytes", + cab->entry_cffolder->cfdata_index -1, + cfdata->sum, cfdata->sum_calculated, + cfdata->compressed_size); + return (ARCHIVE_FAILED); + } + return (ARCHIVE_OK); +} + +/* + * Read CFDATA if needed. + */ +static int +cab_next_cfdata(struct archive_read *a) +{ + struct cab *cab = (struct cab *)(a->format->data); + struct cfdata *cfdata = cab->entry_cfdata; + + /* There are remaining bytes in current CFDATA, use it first. */ + if (cfdata != NULL && cfdata->uncompressed_bytes_remaining > 0) + return (ARCHIVE_OK); + + if (cfdata == NULL) { + int64_t skip; + + cab->entry_cffolder->cfdata_index = 0; + + /* Seek read pointer to the offset of CFDATA if needed. */ + skip = cab->entry_cffolder->cfdata_offset_in_cab + - cab->cab_offset; + if (skip < 0) { + int folder_index; + switch (cab->entry_cffile->folder) { + case iFoldCONTINUED_FROM_PREV: + case iFoldCONTINUED_PREV_AND_NEXT: + folder_index = 0; + break; + case iFoldCONTINUED_TO_NEXT: + folder_index = cab->cfheader.folder_count-1; + break; + default: + folder_index = cab->entry_cffile->folder; + break; + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid offset of CFDATA in folder(%d) %jd < %jd", + folder_index, + (intmax_t)cab->entry_cffolder->cfdata_offset_in_cab, + (intmax_t)cab->cab_offset); + return (ARCHIVE_FATAL); + } + if (skip > 0) { + if (__archive_read_consume(a, skip) < 0) + return (ARCHIVE_FATAL); + cab->cab_offset = + cab->entry_cffolder->cfdata_offset_in_cab; + } + } + + /* + * Read a CFDATA. + */ + if (cab->entry_cffolder->cfdata_index < + cab->entry_cffolder->cfdata_count) { + const unsigned char *p; + int l; + + cfdata = &(cab->entry_cffolder->cfdata); + cab->entry_cffolder->cfdata_index++; + cab->entry_cfdata = cfdata; + cfdata->sum_calculated = 0; + cfdata->sum_extra_avail = 0; + cfdata->sum_ptr = NULL; + l = 8; + if (cab->cfheader.flags & RESERVE_PRESENT) + l += cab->cfheader.cfdata; + if ((p = __archive_read_ahead(a, l, NULL)) == NULL) + return (truncated_error(a)); + cfdata->sum = archive_le32dec(p + CFDATA_csum); + cfdata->compressed_size = archive_le16dec(p + CFDATA_cbData); + cfdata->compressed_bytes_remaining = cfdata->compressed_size; + cfdata->uncompressed_size = + archive_le16dec(p + CFDATA_cbUncomp); + cfdata->uncompressed_bytes_remaining = + cfdata->uncompressed_size; + cfdata->uncompressed_avail = 0; + cfdata->read_offset = 0; + cfdata->unconsumed = 0; + + /* + * Sanity check if data size is acceptable. + */ + if (cfdata->compressed_size == 0 || + cfdata->compressed_size > (0x8000+6144)) + goto invalid; + if (cfdata->uncompressed_size > 0x8000) + goto invalid; + if (cfdata->uncompressed_size == 0) { + switch (cab->entry_cffile->folder) { + case iFoldCONTINUED_PREV_AND_NEXT: + case iFoldCONTINUED_TO_NEXT: + break; + case iFoldCONTINUED_FROM_PREV: + default: + goto invalid; + } + } + /* If CFDATA is not last in a folder, an uncompressed + * size must be 0x8000(32KBi) */ + if ((cab->entry_cffolder->cfdata_index < + cab->entry_cffolder->cfdata_count) && + cfdata->uncompressed_size != 0x8000) + goto invalid; + + /* A compressed data size and an uncompressed data size must + * be the same in no compression mode. */ + if (cab->entry_cffolder->comptype == COMPTYPE_NONE && + cfdata->compressed_size != cfdata->uncompressed_size) + goto invalid; + + /* + * Save CFDATA image for sum check. + */ + if (cfdata->memimage_size < (size_t)l) { + free(cfdata->memimage); + cfdata->memimage = malloc(l); + if (cfdata->memimage == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for CAB data"); + return (ARCHIVE_FATAL); + } + cfdata->memimage_size = l; + } + memcpy(cfdata->memimage, p, l); + + /* Consume bytes as much as we used. */ + __archive_read_consume(a, l); + cab->cab_offset += l; + } else if (cab->entry_cffolder->cfdata_count > 0) { + /* Run out of all CFDATA in a folder. */ + cfdata->compressed_size = 0; + cfdata->uncompressed_size = 0; + cfdata->compressed_bytes_remaining = 0; + cfdata->uncompressed_bytes_remaining = 0; + } else { + /* Current folder does not have any CFDATA. */ + cfdata = &(cab->entry_cffolder->cfdata); + cab->entry_cfdata = cfdata; + memset(cfdata, 0, sizeof(*cfdata)); + } + return (ARCHIVE_OK); +invalid: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid CFDATA"); + return (ARCHIVE_FATAL); +} + +/* + * Read ahead CFDATA. + */ +static const void * +cab_read_ahead_cfdata(struct archive_read *a, ssize_t *avail) +{ + struct cab *cab = (struct cab *)(a->format->data); + int err; + + err = cab_next_cfdata(a); + if (err < ARCHIVE_OK) { + *avail = err; + return (NULL); + } + + switch (cab->entry_cffolder->comptype) { + case COMPTYPE_NONE: + return (cab_read_ahead_cfdata_none(a, avail)); + case COMPTYPE_MSZIP: + return (cab_read_ahead_cfdata_deflate(a, avail)); + case COMPTYPE_LZX: + return (cab_read_ahead_cfdata_lzx(a, avail)); + default: /* Unsupported compression. */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Unsupported CAB compression : %s", + cab->entry_cffolder->compname); + *avail = ARCHIVE_FAILED; + return (NULL); + } +} + +/* + * Read ahead CFDATA as uncompressed data. + */ +static const void * +cab_read_ahead_cfdata_none(struct archive_read *a, ssize_t *avail) +{ + struct cab *cab = (struct cab *)(a->format->data); + struct cfdata *cfdata; + const void *d; + + cfdata = cab->entry_cfdata; + + /* + * Note: '1' here is a performance optimization. + * Recall that the decompression layer returns a count of + * available bytes; asking for more than that forces the + * decompressor to combine reads by copying data. + */ + d = __archive_read_ahead(a, 1, avail); + if (*avail <= 0) { + *avail = truncated_error(a); + return (NULL); + } + if (*avail > cfdata->uncompressed_bytes_remaining) + *avail = cfdata->uncompressed_bytes_remaining; + cfdata->uncompressed_avail = cfdata->uncompressed_size; + cfdata->unconsumed = *avail; + cfdata->sum_ptr = d; + return (d); +} + +/* + * Read ahead CFDATA as deflate data. + */ +#ifdef HAVE_ZLIB_H +static const void * +cab_read_ahead_cfdata_deflate(struct archive_read *a, ssize_t *avail) +{ + struct cab *cab = (struct cab *)(a->format->data); + struct cfdata *cfdata; + const void *d; + int r, mszip; + uint16_t uavail; + char eod = 0; + + cfdata = cab->entry_cfdata; + /* If the buffer hasn't been allocated, allocate it now. */ + if (cab->uncompressed_buffer == NULL) { + cab->uncompressed_buffer_size = 0x8000; + cab->uncompressed_buffer + = (unsigned char *)malloc(cab->uncompressed_buffer_size); + if (cab->uncompressed_buffer == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for CAB reader"); + *avail = ARCHIVE_FATAL; + return (NULL); + } + } + + uavail = cfdata->uncompressed_avail; + if (uavail == cfdata->uncompressed_size) { + d = cab->uncompressed_buffer + cfdata->read_offset; + *avail = uavail - cfdata->read_offset; + return (d); + } + + if (!cab->entry_cffolder->decompress_init) { + cab->stream.next_in = NULL; + cab->stream.avail_in = 0; + cab->stream.total_in = 0; + cab->stream.next_out = NULL; + cab->stream.avail_out = 0; + cab->stream.total_out = 0; + if (cab->stream_valid) + r = inflateReset(&cab->stream); + else + r = inflateInit2(&cab->stream, + -15 /* Don't check for zlib header */); + if (r != Z_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can't initialize deflate decompression."); + *avail = ARCHIVE_FATAL; + return (NULL); + } + /* Stream structure has been set up. */ + cab->stream_valid = 1; + /* We've initialized decompression for this stream. */ + cab->entry_cffolder->decompress_init = 1; + } + + if (cfdata->compressed_bytes_remaining == cfdata->compressed_size) + mszip = 2; + else + mszip = 0; + eod = 0; + cab->stream.total_out = uavail; + /* + * We always uncompress all data in current CFDATA. + */ + while (!eod && cab->stream.total_out < cfdata->uncompressed_size) { + ssize_t bytes_avail; + + cab->stream.next_out = + cab->uncompressed_buffer + cab->stream.total_out; + cab->stream.avail_out = + cfdata->uncompressed_size - cab->stream.total_out; + + d = __archive_read_ahead(a, 1, &bytes_avail); + if (bytes_avail <= 0) { + *avail = truncated_error(a); + return (NULL); + } + if (bytes_avail > cfdata->compressed_bytes_remaining) + bytes_avail = cfdata->compressed_bytes_remaining; + /* + * A bug in zlib.h: stream.next_in should be marked 'const' + * but isn't (the library never alters data through the + * next_in pointer, only reads it). The result: this ugly + * cast to remove 'const'. + */ + cab->stream.next_in = (Bytef *)(uintptr_t)d; + cab->stream.avail_in = (uInt)bytes_avail; + cab->stream.total_in = 0; + + /* Cut out a tow-byte MSZIP signature(0x43, 0x4b). */ + if (mszip > 0) { + if (bytes_avail <= 0) + goto nomszip; + if (bytes_avail <= mszip) { + if (mszip == 2) { + if (cab->stream.next_in[0] != 0x43) + goto nomszip; + if (bytes_avail > 1 && + cab->stream.next_in[1] != 0x4b) + goto nomszip; + } else if (cab->stream.next_in[0] != 0x4b) + goto nomszip; + cfdata->unconsumed = bytes_avail; + cfdata->sum_ptr = d; + if (cab_minimum_consume_cfdata( + a, cfdata->unconsumed) < 0) { + *avail = ARCHIVE_FATAL; + return (NULL); + } + mszip -= (int)bytes_avail; + continue; + } + if (mszip == 1 && cab->stream.next_in[0] != 0x4b) + goto nomszip; + else if (mszip == 2 && (cab->stream.next_in[0] != 0x43 || + cab->stream.next_in[1] != 0x4b)) + goto nomszip; + cab->stream.next_in += mszip; + cab->stream.avail_in -= mszip; + cab->stream.total_in += mszip; + mszip = 0; + } + + r = inflate(&cab->stream, 0); + switch (r) { + case Z_OK: + break; + case Z_STREAM_END: + eod = 1; + break; + default: + goto zlibfailed; + } + cfdata->unconsumed = cab->stream.total_in; + cfdata->sum_ptr = d; + if (cab_minimum_consume_cfdata(a, cfdata->unconsumed) < 0) { + *avail = ARCHIVE_FATAL; + return (NULL); + } + } + uavail = (uint16_t)cab->stream.total_out; + + if (uavail < cfdata->uncompressed_size) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid uncompressed size (%d < %d)", + uavail, cfdata->uncompressed_size); + *avail = ARCHIVE_FATAL; + return (NULL); + } + + /* + * Note: I suspect there is a bug in makecab.exe because, in rare + * case, compressed bytes are still remaining regardless we have + * gotten all uncompressed bytes, which size is recorded in CFDATA, + * as much as we need, and we have to use the garbage so as to + * correctly compute the sum of CFDATA accordingly. + */ + if (cfdata->compressed_bytes_remaining > 0) { + ssize_t bytes_avail; + + d = __archive_read_ahead(a, cfdata->compressed_bytes_remaining, + &bytes_avail); + if (bytes_avail <= 0) { + *avail = truncated_error(a); + return (NULL); + } + cfdata->unconsumed = cfdata->compressed_bytes_remaining; + cfdata->sum_ptr = d; + if (cab_minimum_consume_cfdata(a, cfdata->unconsumed) < 0) { + *avail = ARCHIVE_FATAL; + return (NULL); + } + } + + /* + * Set dictionary data for decompressing of next CFDATA, which + * in the same folder. This is why we always do decompress CFDATA + * even if beginning CFDATA or some of CFDATA are not used in + * skipping file data. + */ + if (cab->entry_cffolder->cfdata_index < + cab->entry_cffolder->cfdata_count) { + r = inflateReset(&cab->stream); + if (r != Z_OK) + goto zlibfailed; + r = inflateSetDictionary(&cab->stream, + cab->uncompressed_buffer, cfdata->uncompressed_size); + if (r != Z_OK) + goto zlibfailed; + } + + d = cab->uncompressed_buffer + cfdata->read_offset; + *avail = uavail - cfdata->read_offset; + cfdata->uncompressed_avail = uavail; + + return (d); + +zlibfailed: + switch (r) { + case Z_MEM_ERROR: + archive_set_error(&a->archive, ENOMEM, + "Out of memory for deflate decompression"); + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Deflate decompression failed (%d)", r); + break; + } + *avail = ARCHIVE_FATAL; + return (NULL); +nomszip: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "CFDATA incorrect(no MSZIP signature)"); + *avail = ARCHIVE_FATAL; + return (NULL); +} + +#else /* HAVE_ZLIB_H */ + +static const void * +cab_read_ahead_cfdata_deflate(struct archive_read *a, ssize_t *avail) +{ + *avail = ARCHIVE_FATAL; + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "libarchive compiled without deflate support (no libz)"); + return (NULL); +} + +#endif /* HAVE_ZLIB_H */ + +static const void * +cab_read_ahead_cfdata_lzx(struct archive_read *a, ssize_t *avail) +{ + struct cab *cab = (struct cab *)(a->format->data); + struct cfdata *cfdata; + const void *d; + int r; + uint16_t uavail; + + cfdata = cab->entry_cfdata; + /* If the buffer hasn't been allocated, allocate it now. */ + if (cab->uncompressed_buffer == NULL) { + cab->uncompressed_buffer_size = 0x8000; + cab->uncompressed_buffer + = (unsigned char *)malloc(cab->uncompressed_buffer_size); + if (cab->uncompressed_buffer == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for CAB reader"); + *avail = ARCHIVE_FATAL; + return (NULL); + } + } + + uavail = cfdata->uncompressed_avail; + if (uavail == cfdata->uncompressed_size) { + d = cab->uncompressed_buffer + cfdata->read_offset; + *avail = uavail - cfdata->read_offset; + return (d); + } + + if (!cab->entry_cffolder->decompress_init) { + r = lzx_decode_init(&cab->xstrm, + cab->entry_cffolder->compdata); + if (r != ARCHIVE_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can't initialize LZX decompression."); + *avail = ARCHIVE_FATAL; + return (NULL); + } + /* We've initialized decompression for this stream. */ + cab->entry_cffolder->decompress_init = 1; + } + + /* Clean up remaining bits of previous CFDATA. */ + lzx_cleanup_bitstream(&cab->xstrm); + cab->xstrm.total_out = uavail; + while (cab->xstrm.total_out < cfdata->uncompressed_size) { + ssize_t bytes_avail; + + cab->xstrm.next_out = + cab->uncompressed_buffer + cab->xstrm.total_out; + cab->xstrm.avail_out = + cfdata->uncompressed_size - cab->xstrm.total_out; + + d = __archive_read_ahead(a, 1, &bytes_avail); + if (bytes_avail <= 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated CAB file data"); + *avail = ARCHIVE_FATAL; + return (NULL); + } + if (bytes_avail > cfdata->compressed_bytes_remaining) + bytes_avail = cfdata->compressed_bytes_remaining; + + cab->xstrm.next_in = d; + cab->xstrm.avail_in = bytes_avail; + cab->xstrm.total_in = 0; + r = lzx_decode(&cab->xstrm, + cfdata->compressed_bytes_remaining == bytes_avail); + switch (r) { + case ARCHIVE_OK: + case ARCHIVE_EOF: + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "LZX decompression failed (%d)", r); + *avail = ARCHIVE_FATAL; + return (NULL); + } + cfdata->unconsumed = cab->xstrm.total_in; + cfdata->sum_ptr = d; + if (cab_minimum_consume_cfdata(a, cfdata->unconsumed) < 0) { + *avail = ARCHIVE_FATAL; + return (NULL); + } + } + + uavail = (uint16_t)cab->xstrm.total_out; + /* + * Make sure a read pointer advances to next CFDATA. + */ + if (cfdata->compressed_bytes_remaining > 0) { + ssize_t bytes_avail; + + d = __archive_read_ahead(a, cfdata->compressed_bytes_remaining, + &bytes_avail); + if (bytes_avail <= 0) { + *avail = truncated_error(a); + return (NULL); + } + cfdata->unconsumed = cfdata->compressed_bytes_remaining; + cfdata->sum_ptr = d; + if (cab_minimum_consume_cfdata(a, cfdata->unconsumed) < 0) { + *avail = ARCHIVE_FATAL; + return (NULL); + } + } + + /* + * Translation reversal of x86 processor CALL byte sequence(E8). + */ + lzx_translation(&cab->xstrm, cab->uncompressed_buffer, + cfdata->uncompressed_size, + (cab->entry_cffolder->cfdata_index-1) * 0x8000); + + d = cab->uncompressed_buffer + cfdata->read_offset; + *avail = uavail - cfdata->read_offset; + cfdata->uncompressed_avail = uavail; + + return (d); +} + +/* + * Consume CFDATA. + * We always decompress CFDATA to consume CFDATA as much as we need + * in uncompressed bytes because all CFDATA in a folder are related + * so we do not skip any CFDATA without decompressing. + * Note: If the folder of a CFFILE is iFoldCONTINUED_PREV_AND_NEXT or + * iFoldCONTINUED_FROM_PREV, we won't decompress because a CFDATA for + * the CFFILE is remaining bytes of previous Multivolume CAB file. + */ +static int64_t +cab_consume_cfdata(struct archive_read *a, int64_t consumed_bytes) +{ + struct cab *cab = (struct cab *)(a->format->data); + struct cfdata *cfdata; + int64_t cbytes, rbytes; + int err; + + rbytes = cab_minimum_consume_cfdata(a, consumed_bytes); + if (rbytes < 0) + return (ARCHIVE_FATAL); + + cfdata = cab->entry_cfdata; + while (rbytes > 0) { + ssize_t avail; + + if (cfdata->compressed_size == 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid CFDATA"); + return (ARCHIVE_FATAL); + } + cbytes = cfdata->uncompressed_bytes_remaining; + if (cbytes > rbytes) + cbytes = rbytes; + rbytes -= cbytes; + + if (cfdata->uncompressed_avail == 0 && + (cab->entry_cffile->folder == iFoldCONTINUED_PREV_AND_NEXT || + cab->entry_cffile->folder == iFoldCONTINUED_FROM_PREV)) { + /* We have not read any data yet. */ + if (cbytes == cfdata->uncompressed_bytes_remaining) { + /* Skip whole current CFDATA. */ + __archive_read_consume(a, + cfdata->compressed_size); + cab->cab_offset += cfdata->compressed_size; + cfdata->compressed_bytes_remaining = 0; + cfdata->uncompressed_bytes_remaining = 0; + err = cab_next_cfdata(a); + if (err < 0) + return (err); + cfdata = cab->entry_cfdata; + if (cfdata->uncompressed_size == 0) { + switch (cab->entry_cffile->folder) { + case iFoldCONTINUED_PREV_AND_NEXT: + case iFoldCONTINUED_TO_NEXT: + case iFoldCONTINUED_FROM_PREV: + rbytes = 0; + break; + default: + break; + } + } + continue; + } + cfdata->read_offset += (uint16_t)cbytes; + cfdata->uncompressed_bytes_remaining -= (uint16_t)cbytes; + break; + } else if (cbytes == 0) { + err = cab_next_cfdata(a); + if (err < 0) + return (err); + cfdata = cab->entry_cfdata; + if (cfdata->uncompressed_size == 0) { + switch (cab->entry_cffile->folder) { + case iFoldCONTINUED_PREV_AND_NEXT: + case iFoldCONTINUED_TO_NEXT: + case iFoldCONTINUED_FROM_PREV: + return (ARCHIVE_FATAL); + default: + break; + } + } + continue; + } + while (cbytes > 0) { + (void)cab_read_ahead_cfdata(a, &avail); + if (avail <= 0) + return (ARCHIVE_FATAL); + if (avail > cbytes) + avail = (ssize_t)cbytes; + if (cab_minimum_consume_cfdata(a, avail) < 0) + return (ARCHIVE_FATAL); + cbytes -= avail; + } + } + return (consumed_bytes); +} + +/* + * Consume CFDATA as much as we have already gotten and + * compute the sum of CFDATA. + */ +static int64_t +cab_minimum_consume_cfdata(struct archive_read *a, int64_t consumed_bytes) +{ + struct cab *cab = (struct cab *)(a->format->data); + struct cfdata *cfdata; + int64_t cbytes, rbytes; + int err; + + cfdata = cab->entry_cfdata; + rbytes = consumed_bytes; + if (cab->entry_cffolder->comptype == COMPTYPE_NONE) { + if (consumed_bytes < cfdata->unconsumed) + cbytes = consumed_bytes; + else + cbytes = cfdata->unconsumed; + rbytes -= cbytes; + cfdata->read_offset += (uint16_t)cbytes; + cfdata->uncompressed_bytes_remaining -= (uint16_t)cbytes; + cfdata->unconsumed -= cbytes; + } else { + cbytes = cfdata->uncompressed_avail - cfdata->read_offset; + if (cbytes > 0) { + if (consumed_bytes < cbytes) + cbytes = consumed_bytes; + rbytes -= cbytes; + cfdata->read_offset += (uint16_t)cbytes; + cfdata->uncompressed_bytes_remaining -= (uint16_t)cbytes; + } + + if (cfdata->unconsumed) { + cbytes = cfdata->unconsumed; + cfdata->unconsumed = 0; + } else + cbytes = 0; + } + if (cbytes) { + /* Compute the sum. */ + cab_checksum_update(a, (size_t)cbytes); + + /* Consume as much as the compressor actually used. */ + __archive_read_consume(a, cbytes); + cab->cab_offset += cbytes; + cfdata->compressed_bytes_remaining -= (uint16_t)cbytes; + if (cfdata->compressed_bytes_remaining == 0) { + err = cab_checksum_finish(a); + if (err < 0) + return (err); + } + } + return (rbytes); +} + +/* + * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets + * cab->end_of_entry if it consumes all of the data. + */ +static int +cab_read_data(struct archive_read *a, const void **buff, + size_t *size, int64_t *offset) +{ + struct cab *cab = (struct cab *)(a->format->data); + ssize_t bytes_avail; + + if (cab->entry_bytes_remaining == 0) { + *buff = NULL; + *size = 0; + *offset = cab->entry_offset; + cab->end_of_entry = 1; + return (ARCHIVE_OK); + } + + *buff = cab_read_ahead_cfdata(a, &bytes_avail); + if (bytes_avail <= 0) { + *buff = NULL; + *size = 0; + *offset = 0; + if (bytes_avail == 0 && + cab->entry_cfdata->uncompressed_size == 0) { + /* All of CFDATA in a folder has been handled. */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, "Invalid CFDATA"); + return (ARCHIVE_FATAL); + } else + return ((int)bytes_avail); + } + if (bytes_avail > cab->entry_bytes_remaining) + bytes_avail = (ssize_t)cab->entry_bytes_remaining; + + *size = bytes_avail; + *offset = cab->entry_offset; + cab->entry_offset += bytes_avail; + cab->entry_bytes_remaining -= bytes_avail; + if (cab->entry_bytes_remaining == 0) + cab->end_of_entry = 1; + cab->entry_unconsumed = bytes_avail; + if (cab->entry_cffolder->comptype == COMPTYPE_NONE) { + /* Don't consume more than current entry used. */ + if (cab->entry_cfdata->unconsumed > cab->entry_unconsumed) + cab->entry_cfdata->unconsumed = cab->entry_unconsumed; + } + return (ARCHIVE_OK); +} + +static int +archive_read_format_cab_read_data_skip(struct archive_read *a) +{ + struct cab *cab; + int64_t bytes_skipped; + int r; + + cab = (struct cab *)(a->format->data); + + if (cab->end_of_archive) + return (ARCHIVE_EOF); + + if (!cab->read_data_invoked) { + cab->bytes_skipped += cab->entry_bytes_remaining; + cab->entry_bytes_remaining = 0; + /* This entry is finished and done. */ + cab->end_of_entry_cleanup = cab->end_of_entry = 1; + return (ARCHIVE_OK); + } + + if (cab->entry_unconsumed) { + /* Consume as much as the compressor actually used. */ + r = (int)cab_consume_cfdata(a, cab->entry_unconsumed); + cab->entry_unconsumed = 0; + if (r < 0) + return (r); + } else if (cab->entry_cfdata == NULL) { + r = cab_next_cfdata(a); + if (r < 0) + return (r); + } + + /* if we've already read to end of data, we're done. */ + if (cab->end_of_entry_cleanup) + return (ARCHIVE_OK); + + /* + * If the length is at the beginning, we can skip the + * compressed data much more quickly. + */ + bytes_skipped = cab_consume_cfdata(a, cab->entry_bytes_remaining); + if (bytes_skipped < 0) + return (ARCHIVE_FATAL); + + /* If the compression type is none(uncompressed), we've already + * consumed data as much as the current entry size. */ + if (cab->entry_cffolder->comptype == COMPTYPE_NONE && + cab->entry_cfdata != NULL) + cab->entry_cfdata->unconsumed = 0; + + /* This entry is finished and done. */ + cab->end_of_entry_cleanup = cab->end_of_entry = 1; + return (ARCHIVE_OK); +} + +static int +archive_read_format_cab_cleanup(struct archive_read *a) +{ + struct cab *cab = (struct cab *)(a->format->data); + struct cfheader *hd = &cab->cfheader; + int i; + + if (hd->folder_array != NULL) { + for (i = 0; i < hd->folder_count; i++) + free(hd->folder_array[i].cfdata.memimage); + free(hd->folder_array); + } + if (hd->file_array != NULL) { + for (i = 0; i < cab->cfheader.file_count; i++) + archive_string_free(&(hd->file_array[i].pathname)); + free(hd->file_array); + } +#ifdef HAVE_ZLIB_H + if (cab->stream_valid) + inflateEnd(&cab->stream); +#endif + lzx_decode_free(&cab->xstrm); + archive_wstring_free(&cab->ws); + free(cab->uncompressed_buffer); + free(cab); + (a->format->data) = NULL; + return (ARCHIVE_OK); +} + +/* Convert an MSDOS-style date/time into Unix-style time. */ +static time_t +cab_dos_time(const unsigned char *p) +{ + int msTime, msDate; + struct tm ts; + + msDate = archive_le16dec(p); + msTime = archive_le16dec(p+2); + + memset(&ts, 0, sizeof(ts)); + ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */ + ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */ + ts.tm_mday = msDate & 0x1f; /* Day of month. */ + ts.tm_hour = (msTime >> 11) & 0x1f; + ts.tm_min = (msTime >> 5) & 0x3f; + ts.tm_sec = (msTime << 1) & 0x3e; + ts.tm_isdst = -1; + return (mktime(&ts)); +} + +/***************************************************************** + * + * LZX decompression code. + * + *****************************************************************/ + +/* + * Initialize LZX decoder. + * + * Returns ARCHIVE_OK if initialization was successful. + * Returns ARCHIVE_FAILED if w_bits has unsupported value. + * Returns ARCHIVE_FATAL if initialization failed; memory allocation + * error occurred. + */ +static int +lzx_decode_init(struct lzx_stream *strm, int w_bits) +{ + struct lzx_dec *ds; + int slot, w_size, w_slot; + int base, footer; + int base_inc[18]; + + if (strm->ds == NULL) { + strm->ds = calloc(1, sizeof(*strm->ds)); + if (strm->ds == NULL) + return (ARCHIVE_FATAL); + } + ds = strm->ds; + ds->error = ARCHIVE_FAILED; + + /* Allow bits from 15(32KBi) up to 21(2MBi) */ + if (w_bits < SLOT_BASE || w_bits > SLOT_MAX) + return (ARCHIVE_FAILED); + + ds->error = ARCHIVE_FATAL; + + /* + * Alloc window + */ + w_size = ds->w_size; + w_slot = slots[w_bits - SLOT_BASE]; + ds->w_size = 1U << w_bits; + ds->w_mask = ds->w_size -1; + if (ds->w_buff == NULL || w_size != ds->w_size) { + free(ds->w_buff); + ds->w_buff = malloc(ds->w_size); + if (ds->w_buff == NULL) + return (ARCHIVE_FATAL); + free(ds->pos_tbl); + ds->pos_tbl = malloc(sizeof(ds->pos_tbl[0]) * w_slot); + if (ds->pos_tbl == NULL) + return (ARCHIVE_FATAL); + lzx_huffman_free(&(ds->mt)); + } + + for (footer = 0; footer < 18; footer++) + base_inc[footer] = 1 << footer; + base = footer = 0; + for (slot = 0; slot < w_slot; slot++) { + int n; + if (footer == 0) + base = slot; + else + base += base_inc[footer]; + if (footer < 17) { + footer = -2; + for (n = base; n; n >>= 1) + footer++; + if (footer <= 0) + footer = 0; + } + ds->pos_tbl[slot].base = base; + ds->pos_tbl[slot].footer_bits = footer; + } + + ds->w_pos = 0; + ds->state = 0; + ds->br.cache_buffer = 0; + ds->br.cache_avail = 0; + ds->r0 = ds->r1 = ds->r2 = 1; + + /* Initialize aligned offset tree. */ + if (lzx_huffman_init(&(ds->at), 8, 8) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Initialize pre-tree. */ + if (lzx_huffman_init(&(ds->pt), 20, 10) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Initialize Main tree. */ + if (lzx_huffman_init(&(ds->mt), 256+(w_slot<<3), 16) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Initialize Length tree. */ + if (lzx_huffman_init(&(ds->lt), 249, 16) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + ds->error = 0; + + return (ARCHIVE_OK); +} + +/* + * Release LZX decoder. + */ +static void +lzx_decode_free(struct lzx_stream *strm) +{ + + if (strm->ds == NULL) + return; + free(strm->ds->w_buff); + free(strm->ds->pos_tbl); + lzx_huffman_free(&(strm->ds->at)); + lzx_huffman_free(&(strm->ds->pt)); + lzx_huffman_free(&(strm->ds->mt)); + lzx_huffman_free(&(strm->ds->lt)); + free(strm->ds); + strm->ds = NULL; +} + +/* + * E8 Call Translation reversal. + */ +static void +lzx_translation(struct lzx_stream *strm, void *p, size_t size, uint32_t offset) +{ + struct lzx_dec *ds = strm->ds; + unsigned char *b, *end; + + if (!ds->translation || size <= 10) + return; + b = p; + end = b + size - 10; + while (b < end && (b = memchr(b, 0xE8, end - b)) != NULL) { + size_t i = b - (unsigned char *)p; + int32_t cp, displacement, value; + + cp = (int32_t)(offset + (uint32_t)i); + value = archive_le32dec(&b[1]); + if (value >= -cp && value < (int32_t)ds->translation_size) { + if (value >= 0) + displacement = value - cp; + else + displacement = value + ds->translation_size; + archive_le32enc(&b[1], (uint32_t)displacement); + } + b += 5; + } +} + +/* + * Bit stream reader. + */ +/* Check that the cache buffer has enough bits. */ +#define lzx_br_has(br, n) ((br)->cache_avail >= n) +/* Get compressed data by bit. */ +#define lzx_br_bits(br, n) \ + (((uint32_t)((br)->cache_buffer >> \ + ((br)->cache_avail - (n)))) & cache_masks[n]) +#define lzx_br_bits_forced(br, n) \ + (((uint32_t)((br)->cache_buffer << \ + ((n) - (br)->cache_avail))) & cache_masks[n]) +/* Read ahead to make sure the cache buffer has enough compressed data we + * will use. + * True : completed, there is enough data in the cache buffer. + * False : we met that strm->next_in is empty, we have to get following + * bytes. */ +#define lzx_br_read_ahead_0(strm, br, n) \ + (lzx_br_has((br), (n)) || lzx_br_fillup(strm, br)) +/* True : the cache buffer has some bits as much as we need. + * False : there are no enough bits in the cache buffer to be used, + * we have to get following bytes if we could. */ +#define lzx_br_read_ahead(strm, br, n) \ + (lzx_br_read_ahead_0((strm), (br), (n)) || lzx_br_has((br), (n))) + +/* Notify how many bits we consumed. */ +#define lzx_br_consume(br, n) ((br)->cache_avail -= (n)) +#define lzx_br_consume_unaligned_bits(br) ((br)->cache_avail &= ~0x0f) + +#define lzx_br_is_unaligned(br) ((br)->cache_avail & 0x0f) + +static const uint32_t cache_masks[] = { + 0x00000000, 0x00000001, 0x00000003, 0x00000007, + 0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F, + 0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF, + 0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF, + 0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF, + 0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF, + 0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, + 0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, + 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* + * Shift away used bits in the cache data and fill it up with following bits. + * Call this when cache buffer does not have enough bits you need. + * + * Returns 1 if the cache buffer is full. + * Returns 0 if the cache buffer is not full; input buffer is empty. + */ +static int +lzx_br_fillup(struct lzx_stream *strm, struct lzx_br *br) +{ +/* + * x86 processor family can read misaligned data without an access error. + */ + int n = CACHE_BITS - br->cache_avail; + + for (;;) { + switch (n >> 4) { + case 4: + if (strm->avail_in >= 8) { + br->cache_buffer = + ((uint64_t)strm->next_in[1]) << 56 | + ((uint64_t)strm->next_in[0]) << 48 | + ((uint64_t)strm->next_in[3]) << 40 | + ((uint64_t)strm->next_in[2]) << 32 | + ((uint32_t)strm->next_in[5]) << 24 | + ((uint32_t)strm->next_in[4]) << 16 | + ((uint32_t)strm->next_in[7]) << 8 | + (uint32_t)strm->next_in[6]; + strm->next_in += 8; + strm->avail_in -= 8; + br->cache_avail += 8 * 8; + return (1); + } + break; + case 3: + if (strm->avail_in >= 6) { + br->cache_buffer = + (br->cache_buffer << 48) | + ((uint64_t)strm->next_in[1]) << 40 | + ((uint64_t)strm->next_in[0]) << 32 | + ((uint32_t)strm->next_in[3]) << 24 | + ((uint32_t)strm->next_in[2]) << 16 | + ((uint32_t)strm->next_in[5]) << 8 | + (uint32_t)strm->next_in[4]; + strm->next_in += 6; + strm->avail_in -= 6; + br->cache_avail += 6 * 8; + return (1); + } + break; + case 0: + /* We have enough compressed data in + * the cache buffer.*/ + return (1); + default: + break; + } + if (strm->avail_in < 2) { + /* There is not enough compressed data to + * fill up the cache buffer. */ + if (strm->avail_in == 1) { + br->odd = *strm->next_in++; + strm->avail_in--; + br->have_odd = 1; + } + return (0); + } + br->cache_buffer = + (br->cache_buffer << 16) | + archive_le16dec(strm->next_in); + strm->next_in += 2; + strm->avail_in -= 2; + br->cache_avail += 16; + n -= 16; + } +} + +static void +lzx_br_fixup(struct lzx_stream *strm, struct lzx_br *br) +{ + int n = CACHE_BITS - br->cache_avail; + + if (br->have_odd && n >= 16 && strm->avail_in > 0) { + br->cache_buffer = + (br->cache_buffer << 16) | + ((uint16_t)(*strm->next_in)) << 8 | br->odd; + strm->next_in++; + strm->avail_in--; + br->cache_avail += 16; + br->have_odd = 0; + } +} + +static void +lzx_cleanup_bitstream(struct lzx_stream *strm) +{ + strm->ds->br.cache_avail = 0; + strm->ds->br.have_odd = 0; +} + +/* + * Decode LZX. + * + * 1. Returns ARCHIVE_OK if output buffer or input buffer are empty. + * Please set available buffer and call this function again. + * 2. Returns ARCHIVE_EOF if decompression has been completed. + * 3. Returns ARCHIVE_FAILED if an error occurred; compressed data + * is broken or you do not set 'last' flag properly. + */ +#define ST_RD_TRANSLATION 0 +#define ST_RD_TRANSLATION_SIZE 1 +#define ST_RD_BLOCK_TYPE 2 +#define ST_RD_BLOCK_SIZE 3 +#define ST_RD_ALIGNMENT 4 +#define ST_RD_R0 5 +#define ST_RD_R1 6 +#define ST_RD_R2 7 +#define ST_COPY_UNCOMP1 8 +#define ST_COPY_UNCOMP2 9 +#define ST_RD_ALIGNED_OFFSET 10 +#define ST_RD_VERBATIM 11 +#define ST_RD_PRE_MAIN_TREE_256 12 +#define ST_MAIN_TREE_256 13 +#define ST_RD_PRE_MAIN_TREE_REM 14 +#define ST_MAIN_TREE_REM 15 +#define ST_RD_PRE_LENGTH_TREE 16 +#define ST_LENGTH_TREE 17 +#define ST_MAIN 18 +#define ST_LENGTH 19 +#define ST_OFFSET 20 +#define ST_REAL_POS 21 +#define ST_COPY 22 + +static int +lzx_decode(struct lzx_stream *strm, int last) +{ + struct lzx_dec *ds = strm->ds; + int64_t avail_in; + int r; + + if (ds->error) + return (ds->error); + + avail_in = strm->avail_in; + lzx_br_fixup(strm, &(ds->br)); + do { + if (ds->state < ST_MAIN) + r = lzx_read_blocks(strm, last); + else { + int64_t bytes_written = strm->avail_out; + r = lzx_decode_blocks(strm, last); + bytes_written -= strm->avail_out; + strm->next_out += bytes_written; + strm->total_out += bytes_written; + } + } while (r == 100); + strm->total_in += avail_in - strm->avail_in; + return (r); +} + +static int +lzx_read_blocks(struct lzx_stream *strm, int last) +{ + struct lzx_dec *ds = strm->ds; + struct lzx_br *br = &(ds->br); + int i, r; + + for (;;) { + switch (ds->state) { + case ST_RD_TRANSLATION: + if (!lzx_br_read_ahead(strm, br, 1)) { + ds->state = ST_RD_TRANSLATION; + if (last) + goto failed; + return (ARCHIVE_OK); + } + ds->translation = lzx_br_bits(br, 1); + lzx_br_consume(br, 1); + /* FALL THROUGH */ + case ST_RD_TRANSLATION_SIZE: + if (ds->translation) { + if (!lzx_br_read_ahead(strm, br, 32)) { + ds->state = ST_RD_TRANSLATION_SIZE; + if (last) + goto failed; + return (ARCHIVE_OK); + } + ds->translation_size = lzx_br_bits(br, 16); + lzx_br_consume(br, 16); + ds->translation_size <<= 16; + ds->translation_size |= lzx_br_bits(br, 16); + lzx_br_consume(br, 16); + } + /* FALL THROUGH */ + case ST_RD_BLOCK_TYPE: + if (!lzx_br_read_ahead(strm, br, 3)) { + ds->state = ST_RD_BLOCK_TYPE; + if (last) + goto failed; + return (ARCHIVE_OK); + } + ds->block_type = lzx_br_bits(br, 3); + lzx_br_consume(br, 3); + /* Check a block type. */ + switch (ds->block_type) { + case VERBATIM_BLOCK: + case ALIGNED_OFFSET_BLOCK: + case UNCOMPRESSED_BLOCK: + break; + default: + goto failed;/* Invalid */ + } + /* FALL THROUGH */ + case ST_RD_BLOCK_SIZE: + if (!lzx_br_read_ahead(strm, br, 24)) { + ds->state = ST_RD_BLOCK_SIZE; + if (last) + goto failed; + return (ARCHIVE_OK); + } + ds->block_size = lzx_br_bits(br, 8); + lzx_br_consume(br, 8); + ds->block_size <<= 16; + ds->block_size |= lzx_br_bits(br, 16); + lzx_br_consume(br, 16); + if (ds->block_size == 0) + goto failed; + ds->block_bytes_avail = ds->block_size; + if (ds->block_type != UNCOMPRESSED_BLOCK) { + if (ds->block_type == VERBATIM_BLOCK) + ds->state = ST_RD_VERBATIM; + else + ds->state = ST_RD_ALIGNED_OFFSET; + break; + } + /* FALL THROUGH */ + case ST_RD_ALIGNMENT: + /* + * Handle an Uncompressed Block. + */ + /* Skip padding to align following field on + * 16-bit boundary. */ + if (lzx_br_is_unaligned(br)) + lzx_br_consume_unaligned_bits(br); + else { + if (lzx_br_read_ahead(strm, br, 16)) + lzx_br_consume(br, 16); + else { + ds->state = ST_RD_ALIGNMENT; + if (last) + goto failed; + return (ARCHIVE_OK); + } + } + /* Preparation to read repeated offsets R0,R1 and R2. */ + ds->rbytes_avail = 0; + ds->state = ST_RD_R0; + /* FALL THROUGH */ + case ST_RD_R0: + case ST_RD_R1: + case ST_RD_R2: + do { + uint16_t u16; + /* Drain bits in the cache buffer of + * bit-stream. */ + if (lzx_br_has(br, 32)) { + u16 = lzx_br_bits(br, 16); + lzx_br_consume(br, 16); + archive_le16enc(ds->rbytes, u16); + u16 = lzx_br_bits(br, 16); + lzx_br_consume(br, 16); + archive_le16enc(ds->rbytes+2, u16); + ds->rbytes_avail = 4; + } else if (lzx_br_has(br, 16)) { + u16 = lzx_br_bits(br, 16); + lzx_br_consume(br, 16); + archive_le16enc(ds->rbytes, u16); + ds->rbytes_avail = 2; + } + if (ds->rbytes_avail < 4 && ds->br.have_odd) { + ds->rbytes[ds->rbytes_avail++] = + ds->br.odd; + ds->br.have_odd = 0; + } + while (ds->rbytes_avail < 4) { + if (strm->avail_in <= 0) { + if (last) + goto failed; + return (ARCHIVE_OK); + } + ds->rbytes[ds->rbytes_avail++] = + *strm->next_in++; + strm->avail_in--; + } + ds->rbytes_avail = 0; + if (ds->state == ST_RD_R0) { + ds->r0 = archive_le32dec(ds->rbytes); + if (ds->r0 < 0) + goto failed; + ds->state = ST_RD_R1; + } else if (ds->state == ST_RD_R1) { + ds->r1 = archive_le32dec(ds->rbytes); + if (ds->r1 < 0) + goto failed; + ds->state = ST_RD_R2; + } else if (ds->state == ST_RD_R2) { + ds->r2 = archive_le32dec(ds->rbytes); + if (ds->r2 < 0) + goto failed; + /* We've gotten all repeated offsets. */ + ds->state = ST_COPY_UNCOMP1; + } + } while (ds->state != ST_COPY_UNCOMP1); + /* FALL THROUGH */ + case ST_COPY_UNCOMP1: + /* + * Copy bytes form next_in to next_out directly. + */ + while (ds->block_bytes_avail) { + int l; + + if (strm->avail_out <= 0) + /* Output buffer is empty. */ + return (ARCHIVE_OK); + if (strm->avail_in <= 0) { + /* Input buffer is empty. */ + if (last) + goto failed; + return (ARCHIVE_OK); + } + l = (int)ds->block_bytes_avail; + if (l > ds->w_size - ds->w_pos) + l = ds->w_size - ds->w_pos; + if (l > strm->avail_out) + l = (int)strm->avail_out; + if (l > strm->avail_in) + l = (int)strm->avail_in; + memcpy(strm->next_out, strm->next_in, l); + memcpy(&(ds->w_buff[ds->w_pos]), + strm->next_in, l); + strm->next_in += l; + strm->avail_in -= l; + strm->next_out += l; + strm->avail_out -= l; + strm->total_out += l; + ds->w_pos = (ds->w_pos + l) & ds->w_mask; + ds->block_bytes_avail -= l; + } + /* FALL THROUGH */ + case ST_COPY_UNCOMP2: + /* Re-align; skip padding byte. */ + if (ds->block_size & 1) { + if (strm->avail_in <= 0) { + /* Input buffer is empty. */ + ds->state = ST_COPY_UNCOMP2; + if (last) + goto failed; + return (ARCHIVE_OK); + } + strm->next_in++; + strm->avail_in --; + } + /* This block ended. */ + ds->state = ST_RD_BLOCK_TYPE; + return (ARCHIVE_EOF); + /********************/ + case ST_RD_ALIGNED_OFFSET: + /* + * Read Aligned offset tree. + */ + if (!lzx_br_read_ahead(strm, br, 3 * ds->at.len_size)) { + ds->state = ST_RD_ALIGNED_OFFSET; + if (last) + goto failed; + return (ARCHIVE_OK); + } + memset(ds->at.freq, 0, sizeof(ds->at.freq)); + for (i = 0; i < ds->at.len_size; i++) { + ds->at.bitlen[i] = lzx_br_bits(br, 3); + ds->at.freq[ds->at.bitlen[i]]++; + lzx_br_consume(br, 3); + } + if (!lzx_make_huffman_table(&ds->at)) + goto failed; + /* FALL THROUGH */ + case ST_RD_VERBATIM: + ds->loop = 0; + /* FALL THROUGH */ + case ST_RD_PRE_MAIN_TREE_256: + /* + * Read Pre-tree for first 256 elements of main tree. + */ + if (!lzx_read_pre_tree(strm)) { + ds->state = ST_RD_PRE_MAIN_TREE_256; + if (last) + goto failed; + return (ARCHIVE_OK); + } + if (!lzx_make_huffman_table(&ds->pt)) + goto failed; + ds->loop = 0; + /* FALL THROUGH */ + case ST_MAIN_TREE_256: + /* + * Get path lengths of first 256 elements of main tree. + */ + r = lzx_read_bitlen(strm, &ds->mt, 256); + if (r < 0) + goto failed; + else if (!r) { + ds->state = ST_MAIN_TREE_256; + if (last) + goto failed; + return (ARCHIVE_OK); + } + ds->loop = 0; + /* FALL THROUGH */ + case ST_RD_PRE_MAIN_TREE_REM: + /* + * Read Pre-tree for remaining elements of main tree. + */ + if (!lzx_read_pre_tree(strm)) { + ds->state = ST_RD_PRE_MAIN_TREE_REM; + if (last) + goto failed; + return (ARCHIVE_OK); + } + if (!lzx_make_huffman_table(&ds->pt)) + goto failed; + ds->loop = 256; + /* FALL THROUGH */ + case ST_MAIN_TREE_REM: + /* + * Get path lengths of remaining elements of main tree. + */ + r = lzx_read_bitlen(strm, &ds->mt, -1); + if (r < 0) + goto failed; + else if (!r) { + ds->state = ST_MAIN_TREE_REM; + if (last) + goto failed; + return (ARCHIVE_OK); + } + if (!lzx_make_huffman_table(&ds->mt)) + goto failed; + ds->loop = 0; + /* FALL THROUGH */ + case ST_RD_PRE_LENGTH_TREE: + /* + * Read Pre-tree for remaining elements of main tree. + */ + if (!lzx_read_pre_tree(strm)) { + ds->state = ST_RD_PRE_LENGTH_TREE; + if (last) + goto failed; + return (ARCHIVE_OK); + } + if (!lzx_make_huffman_table(&ds->pt)) + goto failed; + ds->loop = 0; + /* FALL THROUGH */ + case ST_LENGTH_TREE: + /* + * Get path lengths of remaining elements of main tree. + */ + r = lzx_read_bitlen(strm, &ds->lt, -1); + if (r < 0) + goto failed; + else if (!r) { + ds->state = ST_LENGTH_TREE; + if (last) + goto failed; + return (ARCHIVE_OK); + } + if (!lzx_make_huffman_table(&ds->lt)) + goto failed; + ds->state = ST_MAIN; + return (100); + } + } +failed: + return (ds->error = ARCHIVE_FAILED); +} + +static int +lzx_decode_blocks(struct lzx_stream *strm, int last) +{ + struct lzx_dec *ds = strm->ds; + struct lzx_br bre = ds->br; + struct huffman *at = &(ds->at), *lt = &(ds->lt), *mt = &(ds->mt); + const struct lzx_pos_tbl *pos_tbl = ds->pos_tbl; + unsigned char *noutp = strm->next_out; + unsigned char *endp = noutp + strm->avail_out; + unsigned char *w_buff = ds->w_buff; + unsigned char *at_bitlen = at->bitlen; + unsigned char *lt_bitlen = lt->bitlen; + unsigned char *mt_bitlen = mt->bitlen; + size_t block_bytes_avail = ds->block_bytes_avail; + int at_max_bits = at->max_bits; + int lt_max_bits = lt->max_bits; + int mt_max_bits = mt->max_bits; + int c, copy_len = ds->copy_len, copy_pos = ds->copy_pos; + int w_pos = ds->w_pos, w_mask = ds->w_mask, w_size = ds->w_size; + int length_header = ds->length_header; + int offset_bits = ds->offset_bits; + int position_slot = ds->position_slot; + int r0 = ds->r0, r1 = ds->r1, r2 = ds->r2; + int state = ds->state; + char block_type = ds->block_type; + + for (;;) { + switch (state) { + case ST_MAIN: + for (;;) { + if (block_bytes_avail == 0) { + /* This block ended. */ + ds->state = ST_RD_BLOCK_TYPE; + ds->br = bre; + ds->block_bytes_avail = + block_bytes_avail; + ds->copy_len = copy_len; + ds->copy_pos = copy_pos; + ds->length_header = length_header; + ds->position_slot = position_slot; + ds->r0 = r0; ds->r1 = r1; ds->r2 = r2; + ds->w_pos = w_pos; + strm->avail_out = endp - noutp; + return (ARCHIVE_EOF); + } + if (noutp >= endp) + /* Output buffer is empty. */ + goto next_data; + + if (!lzx_br_read_ahead(strm, &bre, + mt_max_bits)) { + if (!last) + goto next_data; + /* Remaining bits are less than + * maximum bits(mt.max_bits) but maybe + * it still remains as much as we need, + * so we should try to use it with + * dummy bits. */ + c = lzx_decode_huffman(mt, + lzx_br_bits_forced( + &bre, mt_max_bits)); + lzx_br_consume(&bre, mt_bitlen[c]); + if (!lzx_br_has(&bre, 0)) + goto failed;/* Over read. */ + } else { + c = lzx_decode_huffman(mt, + lzx_br_bits(&bre, mt_max_bits)); + lzx_br_consume(&bre, mt_bitlen[c]); + } + if (c > UCHAR_MAX) + break; + /* + * 'c' is exactly literal code. + */ + /* Save a decoded code to reference it + * afterward. */ + w_buff[w_pos] = c; + w_pos = (w_pos + 1) & w_mask; + /* Store the decoded code to output buffer. */ + *noutp++ = c; + block_bytes_avail--; + } + /* + * Get a match code, its length and offset. + */ + c -= UCHAR_MAX + 1; + length_header = c & 7; + position_slot = c >> 3; + /* FALL THROUGH */ + case ST_LENGTH: + /* + * Get a length. + */ + if (length_header == 7) { + if (!lzx_br_read_ahead(strm, &bre, + lt_max_bits)) { + if (!last) { + state = ST_LENGTH; + goto next_data; + } + c = lzx_decode_huffman(lt, + lzx_br_bits_forced( + &bre, lt_max_bits)); + lzx_br_consume(&bre, lt_bitlen[c]); + if (!lzx_br_has(&bre, 0)) + goto failed;/* Over read. */ + } else { + c = lzx_decode_huffman(lt, + lzx_br_bits(&bre, lt_max_bits)); + lzx_br_consume(&bre, lt_bitlen[c]); + } + copy_len = c + 7 + 2; + } else + copy_len = length_header + 2; + if ((size_t)copy_len > block_bytes_avail) + goto failed; + /* + * Get an offset. + */ + switch (position_slot) { + case 0: /* Use repeated offset 0. */ + copy_pos = r0; + state = ST_REAL_POS; + continue; + case 1: /* Use repeated offset 1. */ + copy_pos = r1; + /* Swap repeated offset. */ + r1 = r0; + r0 = copy_pos; + state = ST_REAL_POS; + continue; + case 2: /* Use repeated offset 2. */ + copy_pos = r2; + /* Swap repeated offset. */ + r2 = r0; + r0 = copy_pos; + state = ST_REAL_POS; + continue; + default: + offset_bits = + pos_tbl[position_slot].footer_bits; + break; + } + /* FALL THROUGH */ + case ST_OFFSET: + /* + * Get the offset, which is a distance from + * current window position. + */ + if (block_type == ALIGNED_OFFSET_BLOCK && + offset_bits >= 3) { + int offbits = offset_bits - 3; + + if (!lzx_br_read_ahead(strm, &bre, offbits)) { + state = ST_OFFSET; + if (last) + goto failed; + goto next_data; + } + copy_pos = lzx_br_bits(&bre, offbits) << 3; + + /* Get an aligned number. */ + if (!lzx_br_read_ahead(strm, &bre, + offbits + at_max_bits)) { + if (!last) { + state = ST_OFFSET; + goto next_data; + } + lzx_br_consume(&bre, offbits); + c = lzx_decode_huffman(at, + lzx_br_bits_forced(&bre, + at_max_bits)); + lzx_br_consume(&bre, at_bitlen[c]); + if (!lzx_br_has(&bre, 0)) + goto failed;/* Over read. */ + } else { + lzx_br_consume(&bre, offbits); + c = lzx_decode_huffman(at, + lzx_br_bits(&bre, at_max_bits)); + lzx_br_consume(&bre, at_bitlen[c]); + } + /* Add an aligned number. */ + copy_pos += c; + } else { + if (!lzx_br_read_ahead(strm, &bre, + offset_bits)) { + state = ST_OFFSET; + if (last) + goto failed; + goto next_data; + } + copy_pos = lzx_br_bits(&bre, offset_bits); + lzx_br_consume(&bre, offset_bits); + } + copy_pos += pos_tbl[position_slot].base -2; + + /* Update repeated offset LRU queue. */ + r2 = r1; + r1 = r0; + r0 = copy_pos; + /* FALL THROUGH */ + case ST_REAL_POS: + /* + * Compute a real position in window. + */ + copy_pos = (w_pos - copy_pos) & w_mask; + /* FALL THROUGH */ + case ST_COPY: + /* + * Copy several bytes as extracted data from the window + * into the output buffer. + */ + for (;;) { + const unsigned char *s; + int l; + + l = copy_len; + if (copy_pos > w_pos) { + if (l > w_size - copy_pos) + l = w_size - copy_pos; + } else { + if (l > w_size - w_pos) + l = w_size - w_pos; + } + if (noutp + l >= endp) + l = (int)(endp - noutp); + s = w_buff + copy_pos; + if (l >= 8 && ((copy_pos + l < w_pos) + || (w_pos + l < copy_pos))) { + memcpy(w_buff + w_pos, s, l); + memcpy(noutp, s, l); + } else { + unsigned char *d; + int li; + + d = w_buff + w_pos; + for (li = 0; li < l; li++) + noutp[li] = d[li] = s[li]; + } + noutp += l; + copy_pos = (copy_pos + l) & w_mask; + w_pos = (w_pos + l) & w_mask; + block_bytes_avail -= l; + if (copy_len <= l) + /* A copy of current pattern ended. */ + break; + copy_len -= l; + if (noutp >= endp) { + /* Output buffer is empty. */ + state = ST_COPY; + goto next_data; + } + } + state = ST_MAIN; + break; + } + } +failed: + return (ds->error = ARCHIVE_FAILED); +next_data: + ds->br = bre; + ds->block_bytes_avail = block_bytes_avail; + ds->copy_len = copy_len; + ds->copy_pos = copy_pos; + ds->length_header = length_header; + ds->offset_bits = offset_bits; + ds->position_slot = position_slot; + ds->r0 = r0; ds->r1 = r1; ds->r2 = r2; + ds->state = state; + ds->w_pos = w_pos; + strm->avail_out = endp - noutp; + return (ARCHIVE_OK); +} + +static int +lzx_read_pre_tree(struct lzx_stream *strm) +{ + struct lzx_dec *ds = strm->ds; + struct lzx_br *br = &(ds->br); + int i; + + if (ds->loop == 0) + memset(ds->pt.freq, 0, sizeof(ds->pt.freq)); + for (i = ds->loop; i < ds->pt.len_size; i++) { + if (!lzx_br_read_ahead(strm, br, 4)) { + ds->loop = i; + return (0); + } + ds->pt.bitlen[i] = lzx_br_bits(br, 4); + ds->pt.freq[ds->pt.bitlen[i]]++; + lzx_br_consume(br, 4); + } + ds->loop = i; + return (1); +} + +/* + * Read a bunch of bit-lengths from pre-tree. + */ +static int +lzx_read_bitlen(struct lzx_stream *strm, struct huffman *d, int end) +{ + struct lzx_dec *ds = strm->ds; + struct lzx_br *br = &(ds->br); + int c, i, j, ret, same; + unsigned rbits; + + i = ds->loop; + if (i == 0) + memset(d->freq, 0, sizeof(d->freq)); + ret = 0; + if (end < 0) + end = d->len_size; + while (i < end) { + ds->loop = i; + if (!lzx_br_read_ahead(strm, br, ds->pt.max_bits)) + goto getdata; + rbits = lzx_br_bits(br, ds->pt.max_bits); + c = lzx_decode_huffman(&(ds->pt), rbits); + switch (c) { + case 17:/* several zero lengths, from 4 to 19. */ + if (!lzx_br_read_ahead(strm, br, ds->pt.bitlen[c]+4)) + goto getdata; + lzx_br_consume(br, ds->pt.bitlen[c]); + same = lzx_br_bits(br, 4) + 4; + if (i + same > end) + return (-1);/* Invalid */ + lzx_br_consume(br, 4); + for (j = 0; j < same; j++) + d->bitlen[i++] = 0; + break; + case 18:/* many zero lengths, from 20 to 51. */ + if (!lzx_br_read_ahead(strm, br, ds->pt.bitlen[c]+5)) + goto getdata; + lzx_br_consume(br, ds->pt.bitlen[c]); + same = lzx_br_bits(br, 5) + 20; + if (i + same > end) + return (-1);/* Invalid */ + lzx_br_consume(br, 5); + memset(d->bitlen + i, 0, same); + i += same; + break; + case 19:/* a few same lengths. */ + if (!lzx_br_read_ahead(strm, br, + ds->pt.bitlen[c]+1+ds->pt.max_bits)) + goto getdata; + lzx_br_consume(br, ds->pt.bitlen[c]); + same = lzx_br_bits(br, 1) + 4; + if (i + same > end) + return (-1); + lzx_br_consume(br, 1); + rbits = lzx_br_bits(br, ds->pt.max_bits); + c = lzx_decode_huffman(&(ds->pt), rbits); + lzx_br_consume(br, ds->pt.bitlen[c]); + c = (d->bitlen[i] - c + 17) % 17; + if (c < 0) + return (-1);/* Invalid */ + for (j = 0; j < same; j++) + d->bitlen[i++] = c; + d->freq[c] += same; + break; + default: + lzx_br_consume(br, ds->pt.bitlen[c]); + c = (d->bitlen[i] - c + 17) % 17; + if (c < 0) + return (-1);/* Invalid */ + d->freq[c]++; + d->bitlen[i++] = c; + break; + } + } + ret = 1; +getdata: + ds->loop = i; + return (ret); +} + +static int +lzx_huffman_init(struct huffman *hf, size_t len_size, int tbl_bits) +{ + + if (hf->bitlen == NULL || hf->len_size != (int)len_size) { + free(hf->bitlen); + hf->bitlen = calloc(len_size, sizeof(hf->bitlen[0])); + if (hf->bitlen == NULL) + return (ARCHIVE_FATAL); + hf->len_size = (int)len_size; + } else + memset(hf->bitlen, 0, len_size * sizeof(hf->bitlen[0])); + if (hf->tbl == NULL) { + hf->tbl = malloc(((size_t)1 << tbl_bits) * sizeof(hf->tbl[0])); + if (hf->tbl == NULL) + return (ARCHIVE_FATAL); + hf->tbl_bits = tbl_bits; + } + return (ARCHIVE_OK); +} + +static void +lzx_huffman_free(struct huffman *hf) +{ + free(hf->bitlen); + free(hf->tbl); +} + +/* + * Make a huffman coding table. + */ +static int +lzx_make_huffman_table(struct huffman *hf) +{ + uint16_t *tbl; + const unsigned char *bitlen; + int bitptn[17], weight[17]; + int i, maxbits = 0, ptn, tbl_size, w; + int len_avail; + + /* + * Initialize bit patterns. + */ + ptn = 0; + for (i = 1, w = 1 << 15; i <= 16; i++, w >>= 1) { + bitptn[i] = ptn; + weight[i] = w; + if (hf->freq[i]) { + ptn += hf->freq[i] * w; + maxbits = i; + } + } + if ((ptn & 0xffff) != 0 || maxbits > hf->tbl_bits) + return (0);/* Invalid */ + + hf->max_bits = maxbits; + + /* + * Cut out extra bits which we won't house in the table. + * This preparation reduces the same calculation in the for-loop + * making the table. + */ + if (maxbits < 16) { + int ebits = 16 - maxbits; + for (i = 1; i <= maxbits; i++) { + bitptn[i] >>= ebits; + weight[i] >>= ebits; + } + } + + /* + * Make the table. + */ + tbl_size = 1 << hf->tbl_bits; + tbl = hf->tbl; + bitlen = hf->bitlen; + len_avail = hf->len_size; + hf->tree_used = 0; + for (i = 0; i < len_avail; i++) { + uint16_t *p; + int len, cnt; + + if (bitlen[i] == 0) + continue; + /* Get a bit pattern */ + len = bitlen[i]; + if (len > tbl_size) + return (0); + ptn = bitptn[len]; + cnt = weight[len]; + /* Calculate next bit pattern */ + if ((bitptn[len] = ptn + cnt) > tbl_size) + return (0);/* Invalid */ + /* Update the table */ + p = &(tbl[ptn]); + while (--cnt >= 0) + p[cnt] = (uint16_t)i; + } + return (1); +} + +static inline int +lzx_decode_huffman(struct huffman *hf, unsigned rbits) +{ + int c; + c = hf->tbl[rbits]; + if (c < hf->len_size) + return (c); + return (0); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_cpio.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_cpio.c new file mode 100644 index 0000000000..1c96e6ac19 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_cpio.c @@ -0,0 +1,1086 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2010-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_cpio.c 201163 2009-12-29 05:50:34Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +/* #include <stdint.h> */ /* See archive_platform.h */ +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_read_private.h" + +#define bin_magic_offset 0 +#define bin_magic_size 2 +#define bin_dev_offset 2 +#define bin_dev_size 2 +#define bin_ino_offset 4 +#define bin_ino_size 2 +#define bin_mode_offset 6 +#define bin_mode_size 2 +#define bin_uid_offset 8 +#define bin_uid_size 2 +#define bin_gid_offset 10 +#define bin_gid_size 2 +#define bin_nlink_offset 12 +#define bin_nlink_size 2 +#define bin_rdev_offset 14 +#define bin_rdev_size 2 +#define bin_mtime_offset 16 +#define bin_mtime_size 4 +#define bin_namesize_offset 20 +#define bin_namesize_size 2 +#define bin_filesize_offset 22 +#define bin_filesize_size 4 +#define bin_header_size 26 + +#define odc_magic_offset 0 +#define odc_magic_size 6 +#define odc_dev_offset 6 +#define odc_dev_size 6 +#define odc_ino_offset 12 +#define odc_ino_size 6 +#define odc_mode_offset 18 +#define odc_mode_size 6 +#define odc_uid_offset 24 +#define odc_uid_size 6 +#define odc_gid_offset 30 +#define odc_gid_size 6 +#define odc_nlink_offset 36 +#define odc_nlink_size 6 +#define odc_rdev_offset 42 +#define odc_rdev_size 6 +#define odc_mtime_offset 48 +#define odc_mtime_size 11 +#define odc_namesize_offset 59 +#define odc_namesize_size 6 +#define odc_filesize_offset 65 +#define odc_filesize_size 11 +#define odc_header_size 76 + +#define newc_magic_offset 0 +#define newc_magic_size 6 +#define newc_ino_offset 6 +#define newc_ino_size 8 +#define newc_mode_offset 14 +#define newc_mode_size 8 +#define newc_uid_offset 22 +#define newc_uid_size 8 +#define newc_gid_offset 30 +#define newc_gid_size 8 +#define newc_nlink_offset 38 +#define newc_nlink_size 8 +#define newc_mtime_offset 46 +#define newc_mtime_size 8 +#define newc_filesize_offset 54 +#define newc_filesize_size 8 +#define newc_devmajor_offset 62 +#define newc_devmajor_size 8 +#define newc_devminor_offset 70 +#define newc_devminor_size 8 +#define newc_rdevmajor_offset 78 +#define newc_rdevmajor_size 8 +#define newc_rdevminor_offset 86 +#define newc_rdevminor_size 8 +#define newc_namesize_offset 94 +#define newc_namesize_size 8 +#define newc_checksum_offset 102 +#define newc_checksum_size 8 +#define newc_header_size 110 + +/* + * An afio large ASCII header, which they named itself. + * afio utility uses this header, if a file size is larger than 2G bytes + * or inode/uid/gid is bigger than 65535(0xFFFF) or mtime is bigger than + * 0x7fffffff, which we cannot record to odc header because of its limit. + * If not, uses odc header. + */ +#define afiol_magic_offset 0 +#define afiol_magic_size 6 +#define afiol_dev_offset 6 +#define afiol_dev_size 8 /* hex */ +#define afiol_ino_offset 14 +#define afiol_ino_size 16 /* hex */ +#define afiol_ino_m_offset 30 /* 'm' */ +#define afiol_mode_offset 31 +#define afiol_mode_size 6 /* oct */ +#define afiol_uid_offset 37 +#define afiol_uid_size 8 /* hex */ +#define afiol_gid_offset 45 +#define afiol_gid_size 8 /* hex */ +#define afiol_nlink_offset 53 +#define afiol_nlink_size 8 /* hex */ +#define afiol_rdev_offset 61 +#define afiol_rdev_size 8 /* hex */ +#define afiol_mtime_offset 69 +#define afiol_mtime_size 16 /* hex */ +#define afiol_mtime_n_offset 85 /* 'n' */ +#define afiol_namesize_offset 86 +#define afiol_namesize_size 4 /* hex */ +#define afiol_flag_offset 90 +#define afiol_flag_size 4 /* hex */ +#define afiol_xsize_offset 94 +#define afiol_xsize_size 4 /* hex */ +#define afiol_xsize_s_offset 98 /* 's' */ +#define afiol_filesize_offset 99 +#define afiol_filesize_size 16 /* hex */ +#define afiol_filesize_c_offset 115 /* ':' */ +#define afiol_header_size 116 + + +struct links_entry { + struct links_entry *next; + struct links_entry *previous; + unsigned int links; + dev_t dev; + int64_t ino; + char *name; +}; + +#define CPIO_MAGIC 0x13141516 +struct cpio { + int magic; + int (*read_header)(struct archive_read *, struct cpio *, + struct archive_entry *, size_t *, size_t *); + struct links_entry *links_head; + int64_t entry_bytes_remaining; + int64_t entry_bytes_unconsumed; + int64_t entry_offset; + int64_t entry_padding; + + struct archive_string_conv *opt_sconv; + struct archive_string_conv *sconv_default; + int init_default_conversion; +}; + +static int64_t atol16(const char *, unsigned); +static int64_t atol8(const char *, unsigned); +static int archive_read_format_cpio_bid(struct archive_read *, int); +static int archive_read_format_cpio_options(struct archive_read *, + const char *, const char *); +static int archive_read_format_cpio_cleanup(struct archive_read *); +static int archive_read_format_cpio_read_data(struct archive_read *, + const void **, size_t *, int64_t *); +static int archive_read_format_cpio_read_header(struct archive_read *, + struct archive_entry *); +static int archive_read_format_cpio_skip(struct archive_read *); +static int64_t be4(const unsigned char *); +static int find_odc_header(struct archive_read *); +static int find_newc_header(struct archive_read *); +static int header_bin_be(struct archive_read *, struct cpio *, + struct archive_entry *, size_t *, size_t *); +static int header_bin_le(struct archive_read *, struct cpio *, + struct archive_entry *, size_t *, size_t *); +static int header_newc(struct archive_read *, struct cpio *, + struct archive_entry *, size_t *, size_t *); +static int header_odc(struct archive_read *, struct cpio *, + struct archive_entry *, size_t *, size_t *); +static int header_afiol(struct archive_read *, struct cpio *, + struct archive_entry *, size_t *, size_t *); +static int is_octal(const char *, size_t); +static int is_hex(const char *, size_t); +static int64_t le4(const unsigned char *); +static int record_hardlink(struct archive_read *a, + struct cpio *cpio, struct archive_entry *entry); + +int +archive_read_support_format_cpio(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct cpio *cpio; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_cpio"); + + cpio = (struct cpio *)calloc(1, sizeof(*cpio)); + if (cpio == NULL) { + archive_set_error(&a->archive, ENOMEM, "Can't allocate cpio data"); + return (ARCHIVE_FATAL); + } + cpio->magic = CPIO_MAGIC; + + r = __archive_read_register_format(a, + cpio, + "cpio", + archive_read_format_cpio_bid, + archive_read_format_cpio_options, + archive_read_format_cpio_read_header, + archive_read_format_cpio_read_data, + archive_read_format_cpio_skip, + NULL, + archive_read_format_cpio_cleanup, + NULL, + NULL); + + if (r != ARCHIVE_OK) + free(cpio); + return (ARCHIVE_OK); +} + + +static int +archive_read_format_cpio_bid(struct archive_read *a, int best_bid) +{ + const unsigned char *p; + struct cpio *cpio; + int bid; + + (void)best_bid; /* UNUSED */ + + cpio = (struct cpio *)(a->format->data); + + if ((p = __archive_read_ahead(a, 6, NULL)) == NULL) + return (-1); + + bid = 0; + if (memcmp(p, "070707", 6) == 0) { + /* ASCII cpio archive (odc, POSIX.1) */ + cpio->read_header = header_odc; + bid += 48; + /* + * XXX TODO: More verification; Could check that only octal + * digits appear in appropriate header locations. XXX + */ + } else if (memcmp(p, "070727", 6) == 0) { + /* afio large ASCII cpio archive */ + cpio->read_header = header_odc; + bid += 48; + /* + * XXX TODO: More verification; Could check that almost hex + * digits appear in appropriate header locations. XXX + */ + } else if (memcmp(p, "070701", 6) == 0) { + /* ASCII cpio archive (SVR4 without CRC) */ + cpio->read_header = header_newc; + bid += 48; + /* + * XXX TODO: More verification; Could check that only hex + * digits appear in appropriate header locations. XXX + */ + } else if (memcmp(p, "070702", 6) == 0) { + /* ASCII cpio archive (SVR4 with CRC) */ + /* XXX TODO: Flag that we should check the CRC. XXX */ + cpio->read_header = header_newc; + bid += 48; + /* + * XXX TODO: More verification; Could check that only hex + * digits appear in appropriate header locations. XXX + */ + } else if (p[0] * 256 + p[1] == 070707) { + /* big-endian binary cpio archives */ + cpio->read_header = header_bin_be; + bid += 16; + /* Is more verification possible here? */ + } else if (p[0] + p[1] * 256 == 070707) { + /* little-endian binary cpio archives */ + cpio->read_header = header_bin_le; + bid += 16; + /* Is more verification possible here? */ + } else + return (ARCHIVE_WARN); + + return (bid); +} + +static int +archive_read_format_cpio_options(struct archive_read *a, + const char *key, const char *val) +{ + struct cpio *cpio; + int ret = ARCHIVE_FAILED; + + cpio = (struct cpio *)(a->format->data); + if (strcmp(key, "compat-2x") == 0) { + /* Handle filenames as libarchive 2.x */ + cpio->init_default_conversion = (val != NULL)?1:0; + return (ARCHIVE_OK); + } else if (strcmp(key, "hdrcharset") == 0) { + if (val == NULL || val[0] == 0) + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "cpio: hdrcharset option needs a character-set name"); + else { + cpio->opt_sconv = + archive_string_conversion_from_charset( + &a->archive, val, 0); + if (cpio->opt_sconv != NULL) + ret = ARCHIVE_OK; + else + ret = ARCHIVE_FATAL; + } + return (ret); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static int +archive_read_format_cpio_read_header(struct archive_read *a, + struct archive_entry *entry) +{ + struct cpio *cpio; + const void *h, *hl; + struct archive_string_conv *sconv; + size_t namelength; + size_t name_pad; + int r; + + cpio = (struct cpio *)(a->format->data); + sconv = cpio->opt_sconv; + if (sconv == NULL) { + if (!cpio->init_default_conversion) { + cpio->sconv_default = + archive_string_default_conversion_for_read( + &(a->archive)); + cpio->init_default_conversion = 1; + } + sconv = cpio->sconv_default; + } + + r = (cpio->read_header(a, cpio, entry, &namelength, &name_pad)); + + if (r < ARCHIVE_WARN) + return (r); + + /* Read name from buffer. */ + h = __archive_read_ahead(a, namelength + name_pad, NULL); + if (h == NULL) + return (ARCHIVE_FATAL); + if (archive_entry_copy_pathname_l(entry, + (const char *)h, namelength, sconv) != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Pathname can't be converted from %s to current locale.", + archive_string_conversion_charset_name(sconv)); + r = ARCHIVE_WARN; + } + cpio->entry_offset = 0; + + __archive_read_consume(a, namelength + name_pad); + + /* If this is a symlink, read the link contents. */ + if (archive_entry_filetype(entry) == AE_IFLNK) { + if (cpio->entry_bytes_remaining > 1024 * 1024) { + archive_set_error(&a->archive, ENOMEM, + "Rejecting malformed cpio archive: symlink contents exceed 1 megabyte"); + return (ARCHIVE_FATAL); + } + hl = __archive_read_ahead(a, + (size_t)cpio->entry_bytes_remaining, NULL); + if (hl == NULL) + return (ARCHIVE_FATAL); + if (archive_entry_copy_symlink_l(entry, (const char *)hl, + (size_t)cpio->entry_bytes_remaining, sconv) != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Linkname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Linkname can't be converted from %s to " + "current locale.", + archive_string_conversion_charset_name(sconv)); + r = ARCHIVE_WARN; + } + __archive_read_consume(a, cpio->entry_bytes_remaining); + cpio->entry_bytes_remaining = 0; + } + + /* XXX TODO: If the full mode is 0160200, then this is a Solaris + * ACL description for the following entry. Read this body + * and parse it as a Solaris-style ACL, then read the next + * header. XXX */ + + /* Compare name to "TRAILER!!!" to test for end-of-archive. */ + if (namelength == 11 && strncmp((const char *)h, "TRAILER!!!", + 11) == 0) { + /* TODO: Store file location of start of block. */ + archive_clear_error(&a->archive); + return (ARCHIVE_EOF); + } + + /* Detect and record hardlinks to previously-extracted entries. */ + if (record_hardlink(a, cpio, entry) != ARCHIVE_OK) { + return (ARCHIVE_FATAL); + } + + return (r); +} + +static int +archive_read_format_cpio_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + ssize_t bytes_read; + struct cpio *cpio; + + cpio = (struct cpio *)(a->format->data); + + if (cpio->entry_bytes_unconsumed) { + __archive_read_consume(a, cpio->entry_bytes_unconsumed); + cpio->entry_bytes_unconsumed = 0; + } + + if (cpio->entry_bytes_remaining > 0) { + *buff = __archive_read_ahead(a, 1, &bytes_read); + if (bytes_read <= 0) + return (ARCHIVE_FATAL); + if (bytes_read > cpio->entry_bytes_remaining) + bytes_read = (ssize_t)cpio->entry_bytes_remaining; + *size = bytes_read; + cpio->entry_bytes_unconsumed = bytes_read; + *offset = cpio->entry_offset; + cpio->entry_offset += bytes_read; + cpio->entry_bytes_remaining -= bytes_read; + return (ARCHIVE_OK); + } else { + if (cpio->entry_padding != + __archive_read_consume(a, cpio->entry_padding)) { + return (ARCHIVE_FATAL); + } + cpio->entry_padding = 0; + *buff = NULL; + *size = 0; + *offset = cpio->entry_offset; + return (ARCHIVE_EOF); + } +} + +static int +archive_read_format_cpio_skip(struct archive_read *a) +{ + struct cpio *cpio = (struct cpio *)(a->format->data); + int64_t to_skip = cpio->entry_bytes_remaining + cpio->entry_padding + + cpio->entry_bytes_unconsumed; + + if (to_skip != __archive_read_consume(a, to_skip)) { + return (ARCHIVE_FATAL); + } + cpio->entry_bytes_remaining = 0; + cpio->entry_padding = 0; + cpio->entry_bytes_unconsumed = 0; + return (ARCHIVE_OK); +} + +/* + * Skip forward to the next cpio newc header by searching for the + * 07070[12] string. This should be generalized and merged with + * find_odc_header below. + */ +static int +is_hex(const char *p, size_t len) +{ + while (len-- > 0) { + if ((*p >= '0' && *p <= '9') + || (*p >= 'a' && *p <= 'f') + || (*p >= 'A' && *p <= 'F')) + ++p; + else + return (0); + } + return (1); +} + +static int +find_newc_header(struct archive_read *a) +{ + const void *h; + const char *p, *q; + size_t skip, skipped = 0; + ssize_t bytes; + + for (;;) { + h = __archive_read_ahead(a, newc_header_size, &bytes); + if (h == NULL) + return (ARCHIVE_FATAL); + p = h; + q = p + bytes; + + /* Try the typical case first, then go into the slow search.*/ + if (memcmp("07070", p, 5) == 0 + && (p[5] == '1' || p[5] == '2') + && is_hex(p, newc_header_size)) + return (ARCHIVE_OK); + + /* + * Scan ahead until we find something that looks + * like a newc header. + */ + while (p + newc_header_size <= q) { + switch (p[5]) { + case '1': + case '2': + if (memcmp("07070", p, 5) == 0 + && is_hex(p, newc_header_size)) { + skip = p - (const char *)h; + __archive_read_consume(a, skip); + skipped += skip; + if (skipped > 0) { + archive_set_error(&a->archive, + 0, + "Skipped %d bytes before " + "finding valid header", + (int)skipped); + return (ARCHIVE_WARN); + } + return (ARCHIVE_OK); + } + p += 2; + break; + case '0': + p++; + break; + default: + p += 6; + break; + } + } + skip = p - (const char *)h; + __archive_read_consume(a, skip); + skipped += skip; + } +} + +static int +header_newc(struct archive_read *a, struct cpio *cpio, + struct archive_entry *entry, size_t *namelength, size_t *name_pad) +{ + const void *h; + const char *header; + int r; + + r = find_newc_header(a); + if (r < ARCHIVE_WARN) + return (r); + + /* Read fixed-size portion of header. */ + h = __archive_read_ahead(a, newc_header_size, NULL); + if (h == NULL) + return (ARCHIVE_FATAL); + + /* Parse out hex fields. */ + header = (const char *)h; + + if (memcmp(header + newc_magic_offset, "070701", 6) == 0) { + a->archive.archive_format = ARCHIVE_FORMAT_CPIO_SVR4_NOCRC; + a->archive.archive_format_name = "ASCII cpio (SVR4 with no CRC)"; + } else if (memcmp(header + newc_magic_offset, "070702", 6) == 0) { + a->archive.archive_format = ARCHIVE_FORMAT_CPIO_SVR4_CRC; + a->archive.archive_format_name = "ASCII cpio (SVR4 with CRC)"; + } else { + /* TODO: Abort here? */ + } + + archive_entry_set_devmajor(entry, + (dev_t)atol16(header + newc_devmajor_offset, newc_devmajor_size)); + archive_entry_set_devminor(entry, + (dev_t)atol16(header + newc_devminor_offset, newc_devminor_size)); + archive_entry_set_ino(entry, atol16(header + newc_ino_offset, newc_ino_size)); + archive_entry_set_mode(entry, + (mode_t)atol16(header + newc_mode_offset, newc_mode_size)); + archive_entry_set_uid(entry, atol16(header + newc_uid_offset, newc_uid_size)); + archive_entry_set_gid(entry, atol16(header + newc_gid_offset, newc_gid_size)); + archive_entry_set_nlink(entry, + (unsigned int)atol16(header + newc_nlink_offset, newc_nlink_size)); + archive_entry_set_rdevmajor(entry, + (dev_t)atol16(header + newc_rdevmajor_offset, newc_rdevmajor_size)); + archive_entry_set_rdevminor(entry, + (dev_t)atol16(header + newc_rdevminor_offset, newc_rdevminor_size)); + archive_entry_set_mtime(entry, atol16(header + newc_mtime_offset, newc_mtime_size), 0); + *namelength = (size_t)atol16(header + newc_namesize_offset, newc_namesize_size); + /* Pad name to 2 more than a multiple of 4. */ + *name_pad = (2 - *namelength) & 3; + + /* Make sure that the padded name length fits into size_t. */ + if (*name_pad > SIZE_MAX - *namelength) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "cpio archive has invalid namelength"); + return (ARCHIVE_FATAL); + } + + /* + * Note: entry_bytes_remaining is at least 64 bits and + * therefore guaranteed to be big enough for a 33-bit file + * size. + */ + cpio->entry_bytes_remaining = + atol16(header + newc_filesize_offset, newc_filesize_size); + archive_entry_set_size(entry, cpio->entry_bytes_remaining); + /* Pad file contents to a multiple of 4. */ + cpio->entry_padding = 3 & -cpio->entry_bytes_remaining; + __archive_read_consume(a, newc_header_size); + return (r); +} + +/* + * Skip forward to the next cpio odc header by searching for the + * 070707 string. This is a hand-optimized search that could + * probably be easily generalized to handle all character-based + * cpio variants. + */ +static int +is_octal(const char *p, size_t len) +{ + while (len-- > 0) { + if (*p < '0' || *p > '7') + return (0); + ++p; + } + return (1); +} + +static int +is_afio_large(const char *h, size_t len) +{ + if (len < afiol_header_size) + return (0); + if (h[afiol_ino_m_offset] != 'm' + || h[afiol_mtime_n_offset] != 'n' + || h[afiol_xsize_s_offset] != 's' + || h[afiol_filesize_c_offset] != ':') + return (0); + if (!is_hex(h + afiol_dev_offset, afiol_ino_m_offset - afiol_dev_offset)) + return (0); + if (!is_hex(h + afiol_mode_offset, afiol_mtime_n_offset - afiol_mode_offset)) + return (0); + if (!is_hex(h + afiol_namesize_offset, afiol_xsize_s_offset - afiol_namesize_offset)) + return (0); + if (!is_hex(h + afiol_filesize_offset, afiol_filesize_size)) + return (0); + return (1); +} + +static int +find_odc_header(struct archive_read *a) +{ + const void *h; + const char *p, *q; + size_t skip, skipped = 0; + ssize_t bytes; + + for (;;) { + h = __archive_read_ahead(a, odc_header_size, &bytes); + if (h == NULL) + return (ARCHIVE_FATAL); + p = h; + q = p + bytes; + + /* Try the typical case first, then go into the slow search.*/ + if (memcmp("070707", p, 6) == 0 && is_octal(p, odc_header_size)) + return (ARCHIVE_OK); + if (memcmp("070727", p, 6) == 0 && is_afio_large(p, bytes)) { + a->archive.archive_format = ARCHIVE_FORMAT_CPIO_AFIO_LARGE; + return (ARCHIVE_OK); + } + + /* + * Scan ahead until we find something that looks + * like an odc header. + */ + while (p + odc_header_size <= q) { + switch (p[5]) { + case '7': + if ((memcmp("070707", p, 6) == 0 + && is_octal(p, odc_header_size)) + || (memcmp("070727", p, 6) == 0 + && is_afio_large(p, q - p))) { + skip = p - (const char *)h; + __archive_read_consume(a, skip); + skipped += skip; + if (p[4] == '2') + a->archive.archive_format = + ARCHIVE_FORMAT_CPIO_AFIO_LARGE; + if (skipped > 0) { + archive_set_error(&a->archive, + 0, + "Skipped %d bytes before " + "finding valid header", + (int)skipped); + return (ARCHIVE_WARN); + } + return (ARCHIVE_OK); + } + p += 2; + break; + case '0': + p++; + break; + default: + p += 6; + break; + } + } + skip = p - (const char *)h; + __archive_read_consume(a, skip); + skipped += skip; + } +} + +static int +header_odc(struct archive_read *a, struct cpio *cpio, + struct archive_entry *entry, size_t *namelength, size_t *name_pad) +{ + const void *h; + int r; + const char *header; + + a->archive.archive_format = ARCHIVE_FORMAT_CPIO_POSIX; + a->archive.archive_format_name = "POSIX octet-oriented cpio"; + + /* Find the start of the next header. */ + r = find_odc_header(a); + if (r < ARCHIVE_WARN) + return (r); + + if (a->archive.archive_format == ARCHIVE_FORMAT_CPIO_AFIO_LARGE) { + int r2 = (header_afiol(a, cpio, entry, namelength, name_pad)); + if (r2 == ARCHIVE_OK) + return (r); + else + return (r2); + } + + /* Read fixed-size portion of header. */ + h = __archive_read_ahead(a, odc_header_size, NULL); + if (h == NULL) + return (ARCHIVE_FATAL); + + /* Parse out octal fields. */ + header = (const char *)h; + + archive_entry_set_dev(entry, + (dev_t)atol8(header + odc_dev_offset, odc_dev_size)); + archive_entry_set_ino(entry, atol8(header + odc_ino_offset, odc_ino_size)); + archive_entry_set_mode(entry, + (mode_t)atol8(header + odc_mode_offset, odc_mode_size)); + archive_entry_set_uid(entry, atol8(header + odc_uid_offset, odc_uid_size)); + archive_entry_set_gid(entry, atol8(header + odc_gid_offset, odc_gid_size)); + archive_entry_set_nlink(entry, + (unsigned int)atol8(header + odc_nlink_offset, odc_nlink_size)); + archive_entry_set_rdev(entry, + (dev_t)atol8(header + odc_rdev_offset, odc_rdev_size)); + archive_entry_set_mtime(entry, atol8(header + odc_mtime_offset, odc_mtime_size), 0); + *namelength = (size_t)atol8(header + odc_namesize_offset, odc_namesize_size); + *name_pad = 0; /* No padding of filename. */ + + /* + * Note: entry_bytes_remaining is at least 64 bits and + * therefore guaranteed to be big enough for a 33-bit file + * size. + */ + cpio->entry_bytes_remaining = + atol8(header + odc_filesize_offset, odc_filesize_size); + archive_entry_set_size(entry, cpio->entry_bytes_remaining); + cpio->entry_padding = 0; + __archive_read_consume(a, odc_header_size); + return (r); +} + +/* + * NOTE: if a filename suffix is ".z", it is the file gziped by afio. + * it would be nice that we can show uncompressed file size and we can + * uncompressed file contents automatically, unfortunately we have nothing + * to get a uncompressed file size while reading each header. It means + * we also cannot uncompress file contents under our framework. + */ +static int +header_afiol(struct archive_read *a, struct cpio *cpio, + struct archive_entry *entry, size_t *namelength, size_t *name_pad) +{ + const void *h; + const char *header; + + a->archive.archive_format = ARCHIVE_FORMAT_CPIO_AFIO_LARGE; + a->archive.archive_format_name = "afio large ASCII"; + + /* Read fixed-size portion of header. */ + h = __archive_read_ahead(a, afiol_header_size, NULL); + if (h == NULL) + return (ARCHIVE_FATAL); + + /* Parse out octal fields. */ + header = (const char *)h; + + archive_entry_set_dev(entry, + (dev_t)atol16(header + afiol_dev_offset, afiol_dev_size)); + archive_entry_set_ino(entry, atol16(header + afiol_ino_offset, afiol_ino_size)); + archive_entry_set_mode(entry, + (mode_t)atol8(header + afiol_mode_offset, afiol_mode_size)); + archive_entry_set_uid(entry, atol16(header + afiol_uid_offset, afiol_uid_size)); + archive_entry_set_gid(entry, atol16(header + afiol_gid_offset, afiol_gid_size)); + archive_entry_set_nlink(entry, + (unsigned int)atol16(header + afiol_nlink_offset, afiol_nlink_size)); + archive_entry_set_rdev(entry, + (dev_t)atol16(header + afiol_rdev_offset, afiol_rdev_size)); + archive_entry_set_mtime(entry, atol16(header + afiol_mtime_offset, afiol_mtime_size), 0); + *namelength = (size_t)atol16(header + afiol_namesize_offset, afiol_namesize_size); + *name_pad = 0; /* No padding of filename. */ + + cpio->entry_bytes_remaining = + atol16(header + afiol_filesize_offset, afiol_filesize_size); + archive_entry_set_size(entry, cpio->entry_bytes_remaining); + cpio->entry_padding = 0; + __archive_read_consume(a, afiol_header_size); + return (ARCHIVE_OK); +} + + +static int +header_bin_le(struct archive_read *a, struct cpio *cpio, + struct archive_entry *entry, size_t *namelength, size_t *name_pad) +{ + const void *h; + const unsigned char *header; + + a->archive.archive_format = ARCHIVE_FORMAT_CPIO_BIN_LE; + a->archive.archive_format_name = "cpio (little-endian binary)"; + + /* Read fixed-size portion of header. */ + h = __archive_read_ahead(a, bin_header_size, NULL); + if (h == NULL) { + archive_set_error(&a->archive, 0, + "End of file trying to read next cpio header"); + return (ARCHIVE_FATAL); + } + + /* Parse out binary fields. */ + header = (const unsigned char *)h; + + archive_entry_set_dev(entry, header[bin_dev_offset] + header[bin_dev_offset + 1] * 256); + archive_entry_set_ino(entry, header[bin_ino_offset] + header[bin_ino_offset + 1] * 256); + archive_entry_set_mode(entry, header[bin_mode_offset] + header[bin_mode_offset + 1] * 256); + archive_entry_set_uid(entry, header[bin_uid_offset] + header[bin_uid_offset + 1] * 256); + archive_entry_set_gid(entry, header[bin_gid_offset] + header[bin_gid_offset + 1] * 256); + archive_entry_set_nlink(entry, header[bin_nlink_offset] + header[bin_nlink_offset + 1] * 256); + archive_entry_set_rdev(entry, header[bin_rdev_offset] + header[bin_rdev_offset + 1] * 256); + archive_entry_set_mtime(entry, le4(header + bin_mtime_offset), 0); + *namelength = header[bin_namesize_offset] + header[bin_namesize_offset + 1] * 256; + *name_pad = *namelength & 1; /* Pad to even. */ + + cpio->entry_bytes_remaining = le4(header + bin_filesize_offset); + archive_entry_set_size(entry, cpio->entry_bytes_remaining); + cpio->entry_padding = cpio->entry_bytes_remaining & 1; /* Pad to even. */ + __archive_read_consume(a, bin_header_size); + return (ARCHIVE_OK); +} + +static int +header_bin_be(struct archive_read *a, struct cpio *cpio, + struct archive_entry *entry, size_t *namelength, size_t *name_pad) +{ + const void *h; + const unsigned char *header; + + a->archive.archive_format = ARCHIVE_FORMAT_CPIO_BIN_BE; + a->archive.archive_format_name = "cpio (big-endian binary)"; + + /* Read fixed-size portion of header. */ + h = __archive_read_ahead(a, bin_header_size, NULL); + if (h == NULL) { + archive_set_error(&a->archive, 0, + "End of file trying to read next cpio header"); + return (ARCHIVE_FATAL); + } + + /* Parse out binary fields. */ + header = (const unsigned char *)h; + + archive_entry_set_dev(entry, header[bin_dev_offset] * 256 + header[bin_dev_offset + 1]); + archive_entry_set_ino(entry, header[bin_ino_offset] * 256 + header[bin_ino_offset + 1]); + archive_entry_set_mode(entry, header[bin_mode_offset] * 256 + header[bin_mode_offset + 1]); + archive_entry_set_uid(entry, header[bin_uid_offset] * 256 + header[bin_uid_offset + 1]); + archive_entry_set_gid(entry, header[bin_gid_offset] * 256 + header[bin_gid_offset + 1]); + archive_entry_set_nlink(entry, header[bin_nlink_offset] * 256 + header[bin_nlink_offset + 1]); + archive_entry_set_rdev(entry, header[bin_rdev_offset] * 256 + header[bin_rdev_offset + 1]); + archive_entry_set_mtime(entry, be4(header + bin_mtime_offset), 0); + *namelength = header[bin_namesize_offset] * 256 + header[bin_namesize_offset + 1]; + *name_pad = *namelength & 1; /* Pad to even. */ + + cpio->entry_bytes_remaining = be4(header + bin_filesize_offset); + archive_entry_set_size(entry, cpio->entry_bytes_remaining); + cpio->entry_padding = cpio->entry_bytes_remaining & 1; /* Pad to even. */ + __archive_read_consume(a, bin_header_size); + return (ARCHIVE_OK); +} + +static int +archive_read_format_cpio_cleanup(struct archive_read *a) +{ + struct cpio *cpio; + + cpio = (struct cpio *)(a->format->data); + /* Free inode->name map */ + while (cpio->links_head != NULL) { + struct links_entry *lp = cpio->links_head->next; + + free(cpio->links_head->name); + free(cpio->links_head); + cpio->links_head = lp; + } + free(cpio); + (a->format->data) = NULL; + return (ARCHIVE_OK); +} + +static int64_t +le4(const unsigned char *p) +{ + return ((p[0] << 16) + (((int64_t)p[1]) << 24) + (p[2] << 0) + (p[3] << 8)); +} + + +static int64_t +be4(const unsigned char *p) +{ + return ((((int64_t)p[0]) << 24) + (p[1] << 16) + (p[2] << 8) + (p[3])); +} + +/* + * Note that this implementation does not (and should not!) obey + * locale settings; you cannot simply substitute strtol here, since + * it does obey locale. + */ +static int64_t +atol8(const char *p, unsigned char_cnt) +{ + int64_t l; + int digit; + + l = 0; + while (char_cnt-- > 0) { + if (*p >= '0' && *p <= '7') + digit = *p - '0'; + else + return (l); + p++; + l <<= 3; + l |= digit; + } + return (l); +} + +static int64_t +atol16(const char *p, unsigned char_cnt) +{ + int64_t l; + int digit; + + l = 0; + while (char_cnt-- > 0) { + if (*p >= 'a' && *p <= 'f') + digit = *p - 'a' + 10; + else if (*p >= 'A' && *p <= 'F') + digit = *p - 'A' + 10; + else if (*p >= '0' && *p <= '9') + digit = *p - '0'; + else + return (l); + p++; + l <<= 4; + l |= digit; + } + return (l); +} + +static int +record_hardlink(struct archive_read *a, + struct cpio *cpio, struct archive_entry *entry) +{ + struct links_entry *le; + dev_t dev; + int64_t ino; + + if (archive_entry_nlink(entry) <= 1) + return (ARCHIVE_OK); + + dev = archive_entry_dev(entry); + ino = archive_entry_ino64(entry); + + /* + * First look in the list of multiply-linked files. If we've + * already dumped it, convert this entry to a hard link entry. + */ + for (le = cpio->links_head; le; le = le->next) { + if (le->dev == dev && le->ino == ino) { + archive_entry_copy_hardlink(entry, le->name); + + if (--le->links <= 0) { + if (le->previous != NULL) + le->previous->next = le->next; + if (le->next != NULL) + le->next->previous = le->previous; + if (cpio->links_head == le) + cpio->links_head = le->next; + free(le->name); + free(le); + } + + return (ARCHIVE_OK); + } + } + + le = (struct links_entry *)malloc(sizeof(struct links_entry)); + if (le == NULL) { + archive_set_error(&a->archive, + ENOMEM, "Out of memory adding file to list"); + return (ARCHIVE_FATAL); + } + if (cpio->links_head != NULL) + cpio->links_head->previous = le; + le->next = cpio->links_head; + le->previous = NULL; + cpio->links_head = le; + le->dev = dev; + le->ino = ino; + le->links = archive_entry_nlink(entry) - 1; + le->name = strdup(archive_entry_pathname(entry)); + if (le->name == NULL) { + archive_set_error(&a->archive, + ENOMEM, "Out of memory adding file to list"); + return (ARCHIVE_FATAL); + } + + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_empty.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_empty.c new file mode 100644 index 0000000000..c641eb9b15 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_empty.c @@ -0,0 +1,96 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_empty.c 191524 2009-04-26 18:24:14Z kientzle $"); + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_read_private.h" + +static int archive_read_format_empty_bid(struct archive_read *, int); +static int archive_read_format_empty_read_data(struct archive_read *, + const void **, size_t *, int64_t *); +static int archive_read_format_empty_read_header(struct archive_read *, + struct archive_entry *); +int +archive_read_support_format_empty(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_empty"); + + r = __archive_read_register_format(a, + NULL, + NULL, + archive_read_format_empty_bid, + NULL, + archive_read_format_empty_read_header, + archive_read_format_empty_read_data, + NULL, + NULL, + NULL, + NULL, + NULL); + + return (r); +} + + +static int +archive_read_format_empty_bid(struct archive_read *a, int best_bid) +{ + if (best_bid < 1 && __archive_read_ahead(a, 1, NULL) == NULL) + return (1); + return (-1); +} + +static int +archive_read_format_empty_read_header(struct archive_read *a, + struct archive_entry *entry) +{ + (void)a; /* UNUSED */ + (void)entry; /* UNUSED */ + + a->archive.archive_format = ARCHIVE_FORMAT_EMPTY; + a->archive.archive_format_name = "Empty file"; + + return (ARCHIVE_EOF); +} + +static int +archive_read_format_empty_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + (void)a; /* UNUSED */ + (void)buff; /* UNUSED */ + (void)size; /* UNUSED */ + (void)offset; /* UNUSED */ + + return (ARCHIVE_EOF); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_iso9660.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_iso9660.c new file mode 100644 index 0000000000..db14d41dff --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_iso9660.c @@ -0,0 +1,3278 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2009 Andreas Henriksson <andreas@fatal.se> + * Copyright (c) 2009-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_iso9660.c 201246 2009-12-30 05:30:35Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +/* #include <stdint.h> */ /* See archive_platform.h */ +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#include <time.h> +#ifdef HAVE_ZLIB_H +#include <zlib.h> +#endif + +#include "archive.h" +#include "archive_endian.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_read_private.h" +#include "archive_string.h" + +/* + * An overview of ISO 9660 format: + * + * Each disk is laid out as follows: + * * 32k reserved for private use + * * Volume descriptor table. Each volume descriptor + * is 2k and specifies basic format information. + * The "Primary Volume Descriptor" (PVD) is defined by the + * standard and should always be present; other volume + * descriptors include various vendor-specific extensions. + * * Files and directories. Each file/dir is specified by + * an "extent" (starting sector and length in bytes). + * Dirs are just files with directory records packed one + * after another. The PVD contains a single dir entry + * specifying the location of the root directory. Everything + * else follows from there. + * + * This module works by first reading the volume descriptors, then + * building a list of directory entries, sorted by starting + * sector. At each step, I look for the earliest dir entry that + * hasn't yet been read, seek forward to that location and read + * that entry. If it's a dir, I slurp in the new dir entries and + * add them to the heap; if it's a regular file, I return the + * corresponding archive_entry and wait for the client to request + * the file body. This strategy allows us to read most compliant + * CDs with a single pass through the data, as required by libarchive. + */ +#define LOGICAL_BLOCK_SIZE 2048 +#define SYSTEM_AREA_BLOCK 16 + +/* Structure of on-disk primary volume descriptor. */ +#define PVD_type_offset 0 +#define PVD_type_size 1 +#define PVD_id_offset (PVD_type_offset + PVD_type_size) +#define PVD_id_size 5 +#define PVD_version_offset (PVD_id_offset + PVD_id_size) +#define PVD_version_size 1 +#define PVD_reserved1_offset (PVD_version_offset + PVD_version_size) +#define PVD_reserved1_size 1 +#define PVD_system_id_offset (PVD_reserved1_offset + PVD_reserved1_size) +#define PVD_system_id_size 32 +#define PVD_volume_id_offset (PVD_system_id_offset + PVD_system_id_size) +#define PVD_volume_id_size 32 +#define PVD_reserved2_offset (PVD_volume_id_offset + PVD_volume_id_size) +#define PVD_reserved2_size 8 +#define PVD_volume_space_size_offset (PVD_reserved2_offset + PVD_reserved2_size) +#define PVD_volume_space_size_size 8 +#define PVD_reserved3_offset (PVD_volume_space_size_offset + PVD_volume_space_size_size) +#define PVD_reserved3_size 32 +#define PVD_volume_set_size_offset (PVD_reserved3_offset + PVD_reserved3_size) +#define PVD_volume_set_size_size 4 +#define PVD_volume_sequence_number_offset (PVD_volume_set_size_offset + PVD_volume_set_size_size) +#define PVD_volume_sequence_number_size 4 +#define PVD_logical_block_size_offset (PVD_volume_sequence_number_offset + PVD_volume_sequence_number_size) +#define PVD_logical_block_size_size 4 +#define PVD_path_table_size_offset (PVD_logical_block_size_offset + PVD_logical_block_size_size) +#define PVD_path_table_size_size 8 +#define PVD_type_1_path_table_offset (PVD_path_table_size_offset + PVD_path_table_size_size) +#define PVD_type_1_path_table_size 4 +#define PVD_opt_type_1_path_table_offset (PVD_type_1_path_table_offset + PVD_type_1_path_table_size) +#define PVD_opt_type_1_path_table_size 4 +#define PVD_type_m_path_table_offset (PVD_opt_type_1_path_table_offset + PVD_opt_type_1_path_table_size) +#define PVD_type_m_path_table_size 4 +#define PVD_opt_type_m_path_table_offset (PVD_type_m_path_table_offset + PVD_type_m_path_table_size) +#define PVD_opt_type_m_path_table_size 4 +#define PVD_root_directory_record_offset (PVD_opt_type_m_path_table_offset + PVD_opt_type_m_path_table_size) +#define PVD_root_directory_record_size 34 +#define PVD_volume_set_id_offset (PVD_root_directory_record_offset + PVD_root_directory_record_size) +#define PVD_volume_set_id_size 128 +#define PVD_publisher_id_offset (PVD_volume_set_id_offset + PVD_volume_set_id_size) +#define PVD_publisher_id_size 128 +#define PVD_preparer_id_offset (PVD_publisher_id_offset + PVD_publisher_id_size) +#define PVD_preparer_id_size 128 +#define PVD_application_id_offset (PVD_preparer_id_offset + PVD_preparer_id_size) +#define PVD_application_id_size 128 +#define PVD_copyright_file_id_offset (PVD_application_id_offset + PVD_application_id_size) +#define PVD_copyright_file_id_size 37 +#define PVD_abstract_file_id_offset (PVD_copyright_file_id_offset + PVD_copyright_file_id_size) +#define PVD_abstract_file_id_size 37 +#define PVD_bibliographic_file_id_offset (PVD_abstract_file_id_offset + PVD_abstract_file_id_size) +#define PVD_bibliographic_file_id_size 37 +#define PVD_creation_date_offset (PVD_bibliographic_file_id_offset + PVD_bibliographic_file_id_size) +#define PVD_creation_date_size 17 +#define PVD_modification_date_offset (PVD_creation_date_offset + PVD_creation_date_size) +#define PVD_modification_date_size 17 +#define PVD_expiration_date_offset (PVD_modification_date_offset + PVD_modification_date_size) +#define PVD_expiration_date_size 17 +#define PVD_effective_date_offset (PVD_expiration_date_offset + PVD_expiration_date_size) +#define PVD_effective_date_size 17 +#define PVD_file_structure_version_offset (PVD_effective_date_offset + PVD_effective_date_size) +#define PVD_file_structure_version_size 1 +#define PVD_reserved4_offset (PVD_file_structure_version_offset + PVD_file_structure_version_size) +#define PVD_reserved4_size 1 +#define PVD_application_data_offset (PVD_reserved4_offset + PVD_reserved4_size) +#define PVD_application_data_size 512 +#define PVD_reserved5_offset (PVD_application_data_offset + PVD_application_data_size) +#define PVD_reserved5_size (2048 - PVD_reserved5_offset) + +/* TODO: It would make future maintenance easier to just hardcode the + * above values. In particular, ECMA119 states the offsets as part of + * the standard. That would eliminate the need for the following check.*/ +#if PVD_reserved5_offset != 1395 +#error PVD offset and size definitions are wrong. +#endif + + +/* Structure of optional on-disk supplementary volume descriptor. */ +#define SVD_type_offset 0 +#define SVD_type_size 1 +#define SVD_id_offset (SVD_type_offset + SVD_type_size) +#define SVD_id_size 5 +#define SVD_version_offset (SVD_id_offset + SVD_id_size) +#define SVD_version_size 1 +/* ... */ +#define SVD_reserved1_offset 72 +#define SVD_reserved1_size 8 +#define SVD_volume_space_size_offset 80 +#define SVD_volume_space_size_size 8 +#define SVD_escape_sequences_offset (SVD_volume_space_size_offset + SVD_volume_space_size_size) +#define SVD_escape_sequences_size 32 +/* ... */ +#define SVD_logical_block_size_offset 128 +#define SVD_logical_block_size_size 4 +#define SVD_type_L_path_table_offset 140 +#define SVD_type_M_path_table_offset 148 +/* ... */ +#define SVD_root_directory_record_offset 156 +#define SVD_root_directory_record_size 34 +#define SVD_file_structure_version_offset 881 +#define SVD_reserved2_offset 882 +#define SVD_reserved2_size 1 +#define SVD_reserved3_offset 1395 +#define SVD_reserved3_size 653 +/* ... */ +/* FIXME: validate correctness of last SVD entry offset. */ + +/* Structure of an on-disk directory record. */ +/* Note: ISO9660 stores each multi-byte integer twice, once in + * each byte order. The sizes here are the size of just one + * of the two integers. (This is why the offset of a field isn't + * the same as the offset+size of the previous field.) */ +#define DR_length_offset 0 +#define DR_length_size 1 +#define DR_ext_attr_length_offset 1 +#define DR_ext_attr_length_size 1 +#define DR_extent_offset 2 +#define DR_extent_size 4 +#define DR_size_offset 10 +#define DR_size_size 4 +#define DR_date_offset 18 +#define DR_date_size 7 +#define DR_flags_offset 25 +#define DR_flags_size 1 +#define DR_file_unit_size_offset 26 +#define DR_file_unit_size_size 1 +#define DR_interleave_offset 27 +#define DR_interleave_size 1 +#define DR_volume_sequence_number_offset 28 +#define DR_volume_sequence_number_size 2 +#define DR_name_len_offset 32 +#define DR_name_len_size 1 +#define DR_name_offset 33 + +#ifdef HAVE_ZLIB_H +static const unsigned char zisofs_magic[8] = { + 0x37, 0xE4, 0x53, 0x96, 0xC9, 0xDB, 0xD6, 0x07 +}; + +struct zisofs { + /* Set 1 if this file compressed by paged zlib */ + int pz; + int pz_log2_bs; /* Log2 of block size */ + uint64_t pz_uncompressed_size; + + int initialized; + unsigned char *uncompressed_buffer; + size_t uncompressed_buffer_size; + + uint32_t pz_offset; + unsigned char header[16]; + size_t header_avail; + int header_passed; + unsigned char *block_pointers; + size_t block_pointers_alloc; + size_t block_pointers_size; + size_t block_pointers_avail; + size_t block_off; + uint32_t block_avail; + + z_stream stream; + int stream_valid; +}; +#else +struct zisofs { + /* Set 1 if this file compressed by paged zlib */ + int pz; +}; +#endif + +struct content { + uint64_t offset;/* Offset on disk. */ + uint64_t size; /* File size in bytes. */ + struct content *next; +}; + +/* In-memory storage for a directory record. */ +struct file_info { + struct file_info *use_next; + struct file_info *parent; + struct file_info *next; + struct file_info *re_next; + int subdirs; + uint64_t key; /* Heap Key. */ + uint64_t offset; /* Offset on disk. */ + uint64_t size; /* File size in bytes. */ + uint32_t ce_offset; /* Offset of CE. */ + uint32_t ce_size; /* Size of CE. */ + char rr_moved; /* Flag to rr_moved. */ + char rr_moved_has_re_only; + char re; /* Having RRIP "RE" extension. */ + char re_descendant; + uint64_t cl_offset; /* Having RRIP "CL" extension. */ + int birthtime_is_set; + time_t birthtime; /* File created time. */ + time_t mtime; /* File last modified time. */ + time_t atime; /* File last accessed time. */ + time_t ctime; /* File attribute change time. */ + uint64_t rdev; /* Device number. */ + mode_t mode; + uid_t uid; + gid_t gid; + int64_t number; + int nlinks; + struct archive_string name; /* Pathname */ + unsigned char *utf16be_name; + size_t utf16be_bytes; + char name_continues; /* Non-zero if name continues */ + struct archive_string symlink; + char symlink_continues; /* Non-zero if link continues */ + /* Set 1 if this file compressed by paged zlib(zisofs) */ + int pz; + int pz_log2_bs; /* Log2 of block size */ + uint64_t pz_uncompressed_size; + /* Set 1 if this file is multi extent. */ + int multi_extent; + struct { + struct content *first; + struct content **last; + } contents; + struct { + struct file_info *first; + struct file_info **last; + } rede_files; +}; + +struct heap_queue { + struct file_info **files; + int allocated; + int used; +}; + +struct iso9660 { + int magic; +#define ISO9660_MAGIC 0x96609660 + + int opt_support_joliet; + int opt_support_rockridge; + + struct archive_string pathname; + char seenRockridge; /* Set true if RR extensions are used. */ + char seenSUSP; /* Set true if SUSP is being used. */ + char seenJoliet; + + unsigned char suspOffset; + struct file_info *rr_moved; + struct read_ce_queue { + struct read_ce_req { + uint64_t offset;/* Offset of CE on disk. */ + struct file_info *file; + } *reqs; + int cnt; + int allocated; + } read_ce_req; + + int64_t previous_number; + struct archive_string previous_pathname; + + struct file_info *use_files; + struct heap_queue pending_files; + struct { + struct file_info *first; + struct file_info **last; + } cache_files; + struct { + struct file_info *first; + struct file_info **last; + } re_files; + + uint64_t current_position; + ssize_t logical_block_size; + uint64_t volume_size; /* Total size of volume in bytes. */ + int32_t volume_block;/* Total size of volume in logical blocks. */ + + struct vd { + int location; /* Location of Extent. */ + uint32_t size; + } primary, joliet; + + int64_t entry_sparse_offset; + int64_t entry_bytes_remaining; + size_t entry_bytes_unconsumed; + struct zisofs entry_zisofs; + struct content *entry_content; + struct archive_string_conv *sconv_utf16be; + /* + * Buffers for a full pathname in UTF-16BE in Joliet extensions. + */ +#define UTF16_NAME_MAX 1024 + unsigned char *utf16be_path; + size_t utf16be_path_len; + unsigned char *utf16be_previous_path; + size_t utf16be_previous_path_len; + /* Null buffer used in bidder to improve its performance. */ + unsigned char null[2048]; +}; + +static int archive_read_format_iso9660_bid(struct archive_read *, int); +static int archive_read_format_iso9660_options(struct archive_read *, + const char *, const char *); +static int archive_read_format_iso9660_cleanup(struct archive_read *); +static int archive_read_format_iso9660_read_data(struct archive_read *, + const void **, size_t *, int64_t *); +static int archive_read_format_iso9660_read_data_skip(struct archive_read *); +static int archive_read_format_iso9660_read_header(struct archive_read *, + struct archive_entry *); +static const char *build_pathname(struct archive_string *, struct file_info *, int); +static int build_pathname_utf16be(unsigned char *, size_t, size_t *, + struct file_info *); +#if DEBUG +static void dump_isodirrec(FILE *, const unsigned char *isodirrec); +#endif +static time_t time_from_tm(struct tm *); +static time_t isodate17(const unsigned char *); +static time_t isodate7(const unsigned char *); +static int isBootRecord(struct iso9660 *, const unsigned char *); +static int isVolumePartition(struct iso9660 *, const unsigned char *); +static int isVDSetTerminator(struct iso9660 *, const unsigned char *); +static int isJolietSVD(struct iso9660 *, const unsigned char *); +static int isSVD(struct iso9660 *, const unsigned char *); +static int isEVD(struct iso9660 *, const unsigned char *); +static int isPVD(struct iso9660 *, const unsigned char *); +static int next_cache_entry(struct archive_read *, struct iso9660 *, + struct file_info **); +static int next_entry_seek(struct archive_read *, struct iso9660 *, + struct file_info **); +static struct file_info * + parse_file_info(struct archive_read *a, + struct file_info *parent, const unsigned char *isodirrec, + size_t reclen); +static int parse_rockridge(struct archive_read *a, + struct file_info *file, const unsigned char *start, + const unsigned char *end); +static int register_CE(struct archive_read *a, int32_t location, + struct file_info *file); +static int read_CE(struct archive_read *a, struct iso9660 *iso9660); +static void parse_rockridge_NM1(struct file_info *, + const unsigned char *, int); +static void parse_rockridge_SL1(struct file_info *, + const unsigned char *, int); +static void parse_rockridge_TF1(struct file_info *, + const unsigned char *, int); +static void parse_rockridge_ZF1(struct file_info *, + const unsigned char *, int); +static void register_file(struct iso9660 *, struct file_info *); +static void release_files(struct iso9660 *); +static unsigned toi(const void *p, int n); +static inline void re_add_entry(struct iso9660 *, struct file_info *); +static inline struct file_info * re_get_entry(struct iso9660 *); +static inline int rede_add_entry(struct file_info *); +static inline struct file_info * rede_get_entry(struct file_info *); +static inline void cache_add_entry(struct iso9660 *iso9660, + struct file_info *file); +static inline struct file_info *cache_get_entry(struct iso9660 *iso9660); +static int heap_add_entry(struct archive_read *a, struct heap_queue *heap, + struct file_info *file, uint64_t key); +static struct file_info *heap_get_entry(struct heap_queue *heap); + +#define add_entry(arch, iso9660, file) \ + heap_add_entry(arch, &((iso9660)->pending_files), file, file->offset) +#define next_entry(iso9660) \ + heap_get_entry(&((iso9660)->pending_files)) + +int +archive_read_support_format_iso9660(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct iso9660 *iso9660; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_iso9660"); + + iso9660 = (struct iso9660 *)calloc(1, sizeof(*iso9660)); + if (iso9660 == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate iso9660 data"); + return (ARCHIVE_FATAL); + } + iso9660->magic = ISO9660_MAGIC; + iso9660->cache_files.first = NULL; + iso9660->cache_files.last = &(iso9660->cache_files.first); + iso9660->re_files.first = NULL; + iso9660->re_files.last = &(iso9660->re_files.first); + /* Enable to support Joliet extensions by default. */ + iso9660->opt_support_joliet = 1; + /* Enable to support Rock Ridge extensions by default. */ + iso9660->opt_support_rockridge = 1; + + r = __archive_read_register_format(a, + iso9660, + "iso9660", + archive_read_format_iso9660_bid, + archive_read_format_iso9660_options, + archive_read_format_iso9660_read_header, + archive_read_format_iso9660_read_data, + archive_read_format_iso9660_read_data_skip, + NULL, + archive_read_format_iso9660_cleanup, + NULL, + NULL); + + if (r != ARCHIVE_OK) { + free(iso9660); + return (r); + } + return (ARCHIVE_OK); +} + + +static int +archive_read_format_iso9660_bid(struct archive_read *a, int best_bid) +{ + struct iso9660 *iso9660; + ssize_t bytes_read; + const unsigned char *p; + int seenTerminator; + + /* If there's already a better bid than we can ever + make, don't bother testing. */ + if (best_bid > 48) + return (-1); + + iso9660 = (struct iso9660 *)(a->format->data); + + /* + * Skip the first 32k (reserved area) and get the first + * 8 sectors of the volume descriptor table. Of course, + * if the I/O layer gives us more, we'll take it. + */ +#define RESERVED_AREA (SYSTEM_AREA_BLOCK * LOGICAL_BLOCK_SIZE) + p = __archive_read_ahead(a, + RESERVED_AREA + 8 * LOGICAL_BLOCK_SIZE, + &bytes_read); + if (p == NULL) + return (-1); + + /* Skip the reserved area. */ + bytes_read -= RESERVED_AREA; + p += RESERVED_AREA; + + /* Check each volume descriptor. */ + seenTerminator = 0; + for (; bytes_read > LOGICAL_BLOCK_SIZE; + bytes_read -= LOGICAL_BLOCK_SIZE, p += LOGICAL_BLOCK_SIZE) { + /* Do not handle undefined Volume Descriptor Type. */ + if (p[0] >= 4 && p[0] <= 254) + return (0); + /* Standard Identifier must be "CD001" */ + if (memcmp(p + 1, "CD001", 5) != 0) + return (0); + if (isPVD(iso9660, p)) + continue; + if (!iso9660->joliet.location) { + if (isJolietSVD(iso9660, p)) + continue; + } + if (isBootRecord(iso9660, p)) + continue; + if (isEVD(iso9660, p)) + continue; + if (isSVD(iso9660, p)) + continue; + if (isVolumePartition(iso9660, p)) + continue; + if (isVDSetTerminator(iso9660, p)) { + seenTerminator = 1; + break; + } + return (0); + } + /* + * ISO 9660 format must have Primary Volume Descriptor and + * Volume Descriptor Set Terminator. + */ + if (seenTerminator && iso9660->primary.location > 16) + return (48); + + /* We didn't find a valid PVD; return a bid of zero. */ + return (0); +} + +static int +archive_read_format_iso9660_options(struct archive_read *a, + const char *key, const char *val) +{ + struct iso9660 *iso9660; + + iso9660 = (struct iso9660 *)(a->format->data); + + if (strcmp(key, "joliet") == 0) { + if (val == NULL || strcmp(val, "off") == 0 || + strcmp(val, "ignore") == 0 || + strcmp(val, "disable") == 0 || + strcmp(val, "0") == 0) + iso9660->opt_support_joliet = 0; + else + iso9660->opt_support_joliet = 1; + return (ARCHIVE_OK); + } + if (strcmp(key, "rockridge") == 0 || + strcmp(key, "Rockridge") == 0) { + iso9660->opt_support_rockridge = val != NULL; + return (ARCHIVE_OK); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static int +isNull(struct iso9660 *iso9660, const unsigned char *h, unsigned offset, +unsigned bytes) +{ + + while (bytes >= sizeof(iso9660->null)) { + if (!memcmp(iso9660->null, h + offset, sizeof(iso9660->null))) + return (0); + offset += sizeof(iso9660->null); + bytes -= sizeof(iso9660->null); + } + if (bytes) + return memcmp(iso9660->null, h + offset, bytes) == 0; + else + return (1); +} + +static int +isBootRecord(struct iso9660 *iso9660, const unsigned char *h) +{ + (void)iso9660; /* UNUSED */ + + /* Type of the Volume Descriptor Boot Record must be 0. */ + if (h[0] != 0) + return (0); + + /* Volume Descriptor Version must be 1. */ + if (h[6] != 1) + return (0); + + return (1); +} + +static int +isVolumePartition(struct iso9660 *iso9660, const unsigned char *h) +{ + int32_t location; + + /* Type of the Volume Partition Descriptor must be 3. */ + if (h[0] != 3) + return (0); + + /* Volume Descriptor Version must be 1. */ + if (h[6] != 1) + return (0); + /* Unused Field */ + if (h[7] != 0) + return (0); + + location = archive_le32dec(h + 72); + if (location <= SYSTEM_AREA_BLOCK || + location >= iso9660->volume_block) + return (0); + if ((uint32_t)location != archive_be32dec(h + 76)) + return (0); + + return (1); +} + +static int +isVDSetTerminator(struct iso9660 *iso9660, const unsigned char *h) +{ + (void)iso9660; /* UNUSED */ + + /* Type of the Volume Descriptor Set Terminator must be 255. */ + if (h[0] != 255) + return (0); + + /* Volume Descriptor Version must be 1. */ + if (h[6] != 1) + return (0); + + /* Reserved field must be 0. */ + if (!isNull(iso9660, h, 7, 2048-7)) + return (0); + + return (1); +} + +static int +isJolietSVD(struct iso9660 *iso9660, const unsigned char *h) +{ + const unsigned char *p; + ssize_t logical_block_size; + int32_t volume_block; + + /* Check if current sector is a kind of Supplementary Volume + * Descriptor. */ + if (!isSVD(iso9660, h)) + return (0); + + /* FIXME: do more validations according to joliet spec. */ + + /* check if this SVD contains joliet extension! */ + p = h + SVD_escape_sequences_offset; + /* N.B. Joliet spec says p[1] == '\\', but.... */ + if (p[0] == '%' && p[1] == '/') { + int level = 0; + + if (p[2] == '@') + level = 1; + else if (p[2] == 'C') + level = 2; + else if (p[2] == 'E') + level = 3; + else /* not joliet */ + return (0); + + iso9660->seenJoliet = level; + + } else /* not joliet */ + return (0); + + logical_block_size = + archive_le16dec(h + SVD_logical_block_size_offset); + volume_block = archive_le32dec(h + SVD_volume_space_size_offset); + + iso9660->logical_block_size = logical_block_size; + iso9660->volume_block = volume_block; + iso9660->volume_size = logical_block_size * (uint64_t)volume_block; + /* Read Root Directory Record in Volume Descriptor. */ + p = h + SVD_root_directory_record_offset; + iso9660->joliet.location = archive_le32dec(p + DR_extent_offset); + iso9660->joliet.size = archive_le32dec(p + DR_size_offset); + + return (48); +} + +static int +isSVD(struct iso9660 *iso9660, const unsigned char *h) +{ + const unsigned char *p; + ssize_t logical_block_size; + int32_t volume_block; + int32_t location; + + (void)iso9660; /* UNUSED */ + + /* Type 2 means it's a SVD. */ + if (h[SVD_type_offset] != 2) + return (0); + + /* Reserved field must be 0. */ + if (!isNull(iso9660, h, SVD_reserved1_offset, SVD_reserved1_size)) + return (0); + if (!isNull(iso9660, h, SVD_reserved2_offset, SVD_reserved2_size)) + return (0); + if (!isNull(iso9660, h, SVD_reserved3_offset, SVD_reserved3_size)) + return (0); + + /* File structure version must be 1 for ISO9660/ECMA119. */ + if (h[SVD_file_structure_version_offset] != 1) + return (0); + + logical_block_size = + archive_le16dec(h + SVD_logical_block_size_offset); + if (logical_block_size <= 0) + return (0); + + volume_block = archive_le32dec(h + SVD_volume_space_size_offset); + if (volume_block <= SYSTEM_AREA_BLOCK+4) + return (0); + + /* Location of Occurrence of Type L Path Table must be + * available location, + * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */ + location = archive_le32dec(h+SVD_type_L_path_table_offset); + if (location < SYSTEM_AREA_BLOCK+2 || location >= volume_block) + return (0); + + /* The Type M Path Table must be at a valid location (WinISO + * and probably other programs omit this, so we allow zero) + * + * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */ + location = archive_be32dec(h+SVD_type_M_path_table_offset); + if ((location > 0 && location < SYSTEM_AREA_BLOCK+2) + || location >= volume_block) + return (0); + + /* Read Root Directory Record in Volume Descriptor. */ + p = h + SVD_root_directory_record_offset; + if (p[DR_length_offset] != 34) + return (0); + + return (48); +} + +static int +isEVD(struct iso9660 *iso9660, const unsigned char *h) +{ + const unsigned char *p; + ssize_t logical_block_size; + int32_t volume_block; + int32_t location; + + (void)iso9660; /* UNUSED */ + + /* Type of the Enhanced Volume Descriptor must be 2. */ + if (h[PVD_type_offset] != 2) + return (0); + + /* EVD version must be 2. */ + if (h[PVD_version_offset] != 2) + return (0); + + /* Reserved field must be 0. */ + if (h[PVD_reserved1_offset] != 0) + return (0); + + /* Reserved field must be 0. */ + if (!isNull(iso9660, h, PVD_reserved2_offset, PVD_reserved2_size)) + return (0); + + /* Reserved field must be 0. */ + if (!isNull(iso9660, h, PVD_reserved3_offset, PVD_reserved3_size)) + return (0); + + /* Logical block size must be > 0. */ + /* I've looked at Ecma 119 and can't find any stronger + * restriction on this field. */ + logical_block_size = + archive_le16dec(h + PVD_logical_block_size_offset); + if (logical_block_size <= 0) + return (0); + + volume_block = + archive_le32dec(h + PVD_volume_space_size_offset); + if (volume_block <= SYSTEM_AREA_BLOCK+4) + return (0); + + /* File structure version must be 2 for ISO9660:1999. */ + if (h[PVD_file_structure_version_offset] != 2) + return (0); + + /* Location of Occurrence of Type L Path Table must be + * available location, + * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */ + location = archive_le32dec(h+PVD_type_1_path_table_offset); + if (location < SYSTEM_AREA_BLOCK+2 || location >= volume_block) + return (0); + + /* Location of Occurrence of Type M Path Table must be + * available location, + * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */ + location = archive_be32dec(h+PVD_type_m_path_table_offset); + if ((location > 0 && location < SYSTEM_AREA_BLOCK+2) + || location >= volume_block) + return (0); + + /* Reserved field must be 0. */ + if (!isNull(iso9660, h, PVD_reserved4_offset, PVD_reserved4_size)) + return (0); + + /* Reserved field must be 0. */ + if (!isNull(iso9660, h, PVD_reserved5_offset, PVD_reserved5_size)) + return (0); + + /* Read Root Directory Record in Volume Descriptor. */ + p = h + PVD_root_directory_record_offset; + if (p[DR_length_offset] != 34) + return (0); + + return (48); +} + +static int +isPVD(struct iso9660 *iso9660, const unsigned char *h) +{ + const unsigned char *p; + ssize_t logical_block_size; + int32_t volume_block; + int32_t location; + int i; + + /* Type of the Primary Volume Descriptor must be 1. */ + if (h[PVD_type_offset] != 1) + return (0); + + /* PVD version must be 1. */ + if (h[PVD_version_offset] != 1) + return (0); + + /* Reserved field must be 0. */ + if (h[PVD_reserved1_offset] != 0) + return (0); + + /* Reserved field must be 0. */ + if (!isNull(iso9660, h, PVD_reserved2_offset, PVD_reserved2_size)) + return (0); + + /* Reserved field must be 0. */ + if (!isNull(iso9660, h, PVD_reserved3_offset, PVD_reserved3_size)) + return (0); + + /* Logical block size must be > 0. */ + /* I've looked at Ecma 119 and can't find any stronger + * restriction on this field. */ + logical_block_size = + archive_le16dec(h + PVD_logical_block_size_offset); + if (logical_block_size <= 0) + return (0); + + volume_block = archive_le32dec(h + PVD_volume_space_size_offset); + if (volume_block <= SYSTEM_AREA_BLOCK+4) + return (0); + + /* File structure version must be 1 for ISO9660/ECMA119. */ + if (h[PVD_file_structure_version_offset] != 1) + return (0); + + /* Location of Occurrence of Type L Path Table must be + * available location, + * > SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */ + location = archive_le32dec(h+PVD_type_1_path_table_offset); + if (location < SYSTEM_AREA_BLOCK+2 || location >= volume_block) + return (0); + + /* The Type M Path Table must also be at a valid location + * (although ECMA 119 requires a Type M Path Table, WinISO and + * probably other programs omit it, so we permit a zero here) + * + * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */ + location = archive_be32dec(h+PVD_type_m_path_table_offset); + if ((location > 0 && location < SYSTEM_AREA_BLOCK+2) + || location >= volume_block) + return (0); + + /* Reserved field must be 0. */ + /* But accept NetBSD/FreeBSD "makefs" images with 0x20 here. */ + for (i = 0; i < PVD_reserved4_size; ++i) + if (h[PVD_reserved4_offset + i] != 0 + && h[PVD_reserved4_offset + i] != 0x20) + return (0); + + /* Reserved field must be 0. */ + if (!isNull(iso9660, h, PVD_reserved5_offset, PVD_reserved5_size)) + return (0); + + /* XXX TODO: Check other values for sanity; reject more + * malformed PVDs. XXX */ + + /* Read Root Directory Record in Volume Descriptor. */ + p = h + PVD_root_directory_record_offset; + if (p[DR_length_offset] != 34) + return (0); + + if (!iso9660->primary.location) { + iso9660->logical_block_size = logical_block_size; + iso9660->volume_block = volume_block; + iso9660->volume_size = + logical_block_size * (uint64_t)volume_block; + iso9660->primary.location = + archive_le32dec(p + DR_extent_offset); + iso9660->primary.size = archive_le32dec(p + DR_size_offset); + } + + return (48); +} + +static int +read_children(struct archive_read *a, struct file_info *parent) +{ + struct iso9660 *iso9660; + const unsigned char *b, *p; + struct file_info *multi; + size_t step, skip_size; + + iso9660 = (struct iso9660 *)(a->format->data); + /* flush any remaining bytes from the last round to ensure + * we're positioned */ + if (iso9660->entry_bytes_unconsumed) { + __archive_read_consume(a, iso9660->entry_bytes_unconsumed); + iso9660->entry_bytes_unconsumed = 0; + } + if (iso9660->current_position > parent->offset) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Ignoring out-of-order directory (%s) %jd > %jd", + parent->name.s, + (intmax_t)iso9660->current_position, + (intmax_t)parent->offset); + return (ARCHIVE_WARN); + } + if (parent->offset + parent->size > iso9660->volume_size) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Directory is beyond end-of-media: %s", + parent->name.s); + return (ARCHIVE_WARN); + } + if (iso9660->current_position < parent->offset) { + int64_t skipsize; + + skipsize = parent->offset - iso9660->current_position; + skipsize = __archive_read_consume(a, skipsize); + if (skipsize < 0) + return ((int)skipsize); + iso9660->current_position = parent->offset; + } + + step = (size_t)(((parent->size + iso9660->logical_block_size -1) / + iso9660->logical_block_size) * iso9660->logical_block_size); + b = __archive_read_ahead(a, step, NULL); + if (b == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Failed to read full block when scanning " + "ISO9660 directory list"); + return (ARCHIVE_FATAL); + } + iso9660->current_position += step; + multi = NULL; + skip_size = step; + while (step) { + p = b; + b += iso9660->logical_block_size; + step -= iso9660->logical_block_size; + for (; *p != 0 && p < b && p + *p <= b; p += *p) { + struct file_info *child; + + /* N.B.: these special directory identifiers + * are 8 bit "values" even on a + * Joliet CD with UCS-2 (16bit) encoding. + */ + + /* Skip '.' entry. */ + if (*(p + DR_name_len_offset) == 1 + && *(p + DR_name_offset) == '\0') + continue; + /* Skip '..' entry. */ + if (*(p + DR_name_len_offset) == 1 + && *(p + DR_name_offset) == '\001') + continue; + child = parse_file_info(a, parent, p, b - p); + if (child == NULL) { + __archive_read_consume(a, skip_size); + return (ARCHIVE_FATAL); + } + if (child->cl_offset == 0 && + (child->multi_extent || multi != NULL)) { + struct content *con; + + if (multi == NULL) { + multi = child; + multi->contents.first = NULL; + multi->contents.last = + &(multi->contents.first); + } + con = malloc(sizeof(struct content)); + if (con == NULL) { + archive_set_error( + &a->archive, ENOMEM, + "No memory for multi extent"); + __archive_read_consume(a, skip_size); + return (ARCHIVE_FATAL); + } + con->offset = child->offset; + con->size = child->size; + con->next = NULL; + *multi->contents.last = con; + multi->contents.last = &(con->next); + if (multi == child) { + if (add_entry(a, iso9660, child) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } else { + multi->size += child->size; + if (!child->multi_extent) + multi = NULL; + } + } else + if (add_entry(a, iso9660, child) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + } + + __archive_read_consume(a, skip_size); + + /* Read data which recorded by RRIP "CE" extension. */ + if (read_CE(a, iso9660) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + return (ARCHIVE_OK); +} + +static int +choose_volume(struct archive_read *a, struct iso9660 *iso9660) +{ + struct file_info *file; + int64_t skipsize; + struct vd *vd; + const void *block; + char seenJoliet; + + vd = &(iso9660->primary); + if (!iso9660->opt_support_joliet) + iso9660->seenJoliet = 0; + if (iso9660->seenJoliet && + vd->location > iso9660->joliet.location) + /* This condition is unlikely; by way of caution. */ + vd = &(iso9660->joliet); + + skipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location; + skipsize = __archive_read_consume(a, skipsize); + if (skipsize < 0) + return ((int)skipsize); + iso9660->current_position = skipsize; + + block = __archive_read_ahead(a, vd->size, NULL); + if (block == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Failed to read full block when scanning " + "ISO9660 directory list"); + return (ARCHIVE_FATAL); + } + + /* + * While reading Root Directory, flag seenJoliet must be zero to + * avoid converting special name 0x00(Current Directory) and + * next byte to UCS2. + */ + seenJoliet = iso9660->seenJoliet;/* Save flag. */ + iso9660->seenJoliet = 0; + file = parse_file_info(a, NULL, block, vd->size); + if (file == NULL) + return (ARCHIVE_FATAL); + iso9660->seenJoliet = seenJoliet; + + /* + * If the iso image has both RockRidge and Joliet, we preferentially + * use RockRidge Extensions rather than Joliet ones. + */ + if (vd == &(iso9660->primary) && iso9660->seenRockridge + && iso9660->seenJoliet) + iso9660->seenJoliet = 0; + + if (vd == &(iso9660->primary) && !iso9660->seenRockridge + && iso9660->seenJoliet) { + /* Switch reading data from primary to joliet. */ + vd = &(iso9660->joliet); + skipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location; + skipsize -= iso9660->current_position; + skipsize = __archive_read_consume(a, skipsize); + if (skipsize < 0) + return ((int)skipsize); + iso9660->current_position += skipsize; + + block = __archive_read_ahead(a, vd->size, NULL); + if (block == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Failed to read full block when scanning " + "ISO9660 directory list"); + return (ARCHIVE_FATAL); + } + iso9660->seenJoliet = 0; + file = parse_file_info(a, NULL, block, vd->size); + if (file == NULL) + return (ARCHIVE_FATAL); + iso9660->seenJoliet = seenJoliet; + } + + /* Store the root directory in the pending list. */ + if (add_entry(a, iso9660, file) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + if (iso9660->seenRockridge) { + a->archive.archive_format = ARCHIVE_FORMAT_ISO9660_ROCKRIDGE; + a->archive.archive_format_name = + "ISO9660 with Rockridge extensions"; + } + + return (ARCHIVE_OK); +} + +static int +archive_read_format_iso9660_read_header(struct archive_read *a, + struct archive_entry *entry) +{ + struct iso9660 *iso9660; + struct file_info *file; + int r, rd_r = ARCHIVE_OK; + + iso9660 = (struct iso9660 *)(a->format->data); + + if (!a->archive.archive_format) { + a->archive.archive_format = ARCHIVE_FORMAT_ISO9660; + a->archive.archive_format_name = "ISO9660"; + } + + if (iso9660->current_position == 0) { + r = choose_volume(a, iso9660); + if (r != ARCHIVE_OK) + return (r); + } + + file = NULL;/* Eliminate a warning. */ + /* Get the next entry that appears after the current offset. */ + r = next_entry_seek(a, iso9660, &file); + if (r != ARCHIVE_OK) + return (r); + + if (iso9660->seenJoliet) { + /* + * Convert UTF-16BE of a filename to local locale MBS + * and store the result into a filename field. + */ + if (iso9660->sconv_utf16be == NULL) { + iso9660->sconv_utf16be = + archive_string_conversion_from_charset( + &(a->archive), "UTF-16BE", 1); + if (iso9660->sconv_utf16be == NULL) + /* Couldn't allocate memory */ + return (ARCHIVE_FATAL); + } + if (iso9660->utf16be_path == NULL) { + iso9660->utf16be_path = malloc(UTF16_NAME_MAX); + if (iso9660->utf16be_path == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory"); + return (ARCHIVE_FATAL); + } + } + if (iso9660->utf16be_previous_path == NULL) { + iso9660->utf16be_previous_path = malloc(UTF16_NAME_MAX); + if (iso9660->utf16be_previous_path == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory"); + return (ARCHIVE_FATAL); + } + } + + iso9660->utf16be_path_len = 0; + if (build_pathname_utf16be(iso9660->utf16be_path, + UTF16_NAME_MAX, &(iso9660->utf16be_path_len), file) != 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Pathname is too long"); + return (ARCHIVE_FATAL); + } + + r = archive_entry_copy_pathname_l(entry, + (const char *)iso9660->utf16be_path, + iso9660->utf16be_path_len, + iso9660->sconv_utf16be); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "No memory for Pathname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Pathname cannot be converted " + "from %s to current locale.", + archive_string_conversion_charset_name( + iso9660->sconv_utf16be)); + + rd_r = ARCHIVE_WARN; + } + } else { + const char *path = build_pathname(&iso9660->pathname, file, 0); + if (path == NULL) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Pathname is too long"); + return (ARCHIVE_FATAL); + } else { + archive_string_empty(&iso9660->pathname); + archive_entry_set_pathname(entry, path); + } + } + + iso9660->entry_bytes_remaining = file->size; + /* Offset for sparse-file-aware clients. */ + iso9660->entry_sparse_offset = 0; + + if (file->offset + file->size > iso9660->volume_size) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "File is beyond end-of-media: %s", + archive_entry_pathname(entry)); + iso9660->entry_bytes_remaining = 0; + return (ARCHIVE_WARN); + } + + /* Set up the entry structure with information about this entry. */ + archive_entry_set_mode(entry, file->mode); + archive_entry_set_uid(entry, file->uid); + archive_entry_set_gid(entry, file->gid); + archive_entry_set_nlink(entry, file->nlinks); + if (file->birthtime_is_set) + archive_entry_set_birthtime(entry, file->birthtime, 0); + else + archive_entry_unset_birthtime(entry); + archive_entry_set_mtime(entry, file->mtime, 0); + archive_entry_set_ctime(entry, file->ctime, 0); + archive_entry_set_atime(entry, file->atime, 0); + /* N.B.: Rock Ridge supports 64-bit device numbers. */ + archive_entry_set_rdev(entry, (dev_t)file->rdev); + archive_entry_set_size(entry, iso9660->entry_bytes_remaining); + if (file->symlink.s != NULL) + archive_entry_copy_symlink(entry, file->symlink.s); + + /* Note: If the input isn't seekable, we can't rewind to + * return the same body again, so if the next entry refers to + * the same data, we have to return it as a hardlink to the + * original entry. */ + if (file->number != -1 && + file->number == iso9660->previous_number) { + if (iso9660->seenJoliet) { + r = archive_entry_copy_hardlink_l(entry, + (const char *)iso9660->utf16be_previous_path, + iso9660->utf16be_previous_path_len, + iso9660->sconv_utf16be); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "No memory for Linkname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Linkname cannot be converted " + "from %s to current locale.", + archive_string_conversion_charset_name( + iso9660->sconv_utf16be)); + rd_r = ARCHIVE_WARN; + } + } else + archive_entry_set_hardlink(entry, + iso9660->previous_pathname.s); + archive_entry_unset_size(entry); + iso9660->entry_bytes_remaining = 0; + return (rd_r); + } + + if ((file->mode & AE_IFMT) != AE_IFDIR && + file->offset < iso9660->current_position) { + int64_t r64; + + r64 = __archive_read_seek(a, file->offset, SEEK_SET); + if (r64 != (int64_t)file->offset) { + /* We can't seek backwards to extract it, so issue + * a warning. Note that this can only happen if + * this entry was added to the heap after we passed + * this offset, that is, only if the directory + * mentioning this entry is later than the body of + * the entry. Such layouts are very unusual; most + * ISO9660 writers lay out and record all directory + * information first, then store all file bodies. */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Ignoring out-of-order file @%jx (%s) %jd < %jd", + (intmax_t)file->number, + iso9660->pathname.s, + (intmax_t)file->offset, + (intmax_t)iso9660->current_position); + iso9660->entry_bytes_remaining = 0; + return (ARCHIVE_WARN); + } + iso9660->current_position = (uint64_t)r64; + } + + /* Initialize zisofs variables. */ + iso9660->entry_zisofs.pz = file->pz; + if (file->pz) { +#ifdef HAVE_ZLIB_H + struct zisofs *zisofs; + + zisofs = &iso9660->entry_zisofs; + zisofs->initialized = 0; + zisofs->pz_log2_bs = file->pz_log2_bs; + zisofs->pz_uncompressed_size = file->pz_uncompressed_size; + zisofs->pz_offset = 0; + zisofs->header_avail = 0; + zisofs->header_passed = 0; + zisofs->block_pointers_avail = 0; +#endif + archive_entry_set_size(entry, file->pz_uncompressed_size); + } + + iso9660->previous_number = file->number; + if (iso9660->seenJoliet) { + memcpy(iso9660->utf16be_previous_path, iso9660->utf16be_path, + iso9660->utf16be_path_len); + iso9660->utf16be_previous_path_len = iso9660->utf16be_path_len; + } else + archive_strcpy( + &iso9660->previous_pathname, iso9660->pathname.s); + + /* Reset entry_bytes_remaining if the file is multi extent. */ + iso9660->entry_content = file->contents.first; + if (iso9660->entry_content != NULL) + iso9660->entry_bytes_remaining = iso9660->entry_content->size; + + if (archive_entry_filetype(entry) == AE_IFDIR) { + /* Overwrite nlinks by proper link number which is + * calculated from number of sub directories. */ + archive_entry_set_nlink(entry, 2 + file->subdirs); + /* Directory data has been read completely. */ + iso9660->entry_bytes_remaining = 0; + } + + if (rd_r != ARCHIVE_OK) + return (rd_r); + return (ARCHIVE_OK); +} + +static int +archive_read_format_iso9660_read_data_skip(struct archive_read *a) +{ + /* Because read_next_header always does an explicit skip + * to the next entry, we don't need to do anything here. */ + (void)a; /* UNUSED */ + return (ARCHIVE_OK); +} + +#ifdef HAVE_ZLIB_H + +static int +zisofs_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + struct iso9660 *iso9660; + struct zisofs *zisofs; + const unsigned char *p; + size_t avail; + ssize_t bytes_read; + size_t uncompressed_size; + int r; + + iso9660 = (struct iso9660 *)(a->format->data); + zisofs = &iso9660->entry_zisofs; + + p = __archive_read_ahead(a, 1, &bytes_read); + if (bytes_read <= 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated zisofs file body"); + return (ARCHIVE_FATAL); + } + if (bytes_read > iso9660->entry_bytes_remaining) + bytes_read = (ssize_t)iso9660->entry_bytes_remaining; + avail = bytes_read; + uncompressed_size = 0; + + if (!zisofs->initialized) { + size_t ceil, xsize; + + /* Allocate block pointers buffer. */ + ceil = (size_t)((zisofs->pz_uncompressed_size + + (((int64_t)1) << zisofs->pz_log2_bs) - 1) + >> zisofs->pz_log2_bs); + xsize = (ceil + 1) * 4; + if (zisofs->block_pointers_alloc < xsize) { + size_t alloc; + + if (zisofs->block_pointers != NULL) + free(zisofs->block_pointers); + alloc = ((xsize >> 10) + 1) << 10; + zisofs->block_pointers = malloc(alloc); + if (zisofs->block_pointers == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for zisofs decompression"); + return (ARCHIVE_FATAL); + } + zisofs->block_pointers_alloc = alloc; + } + zisofs->block_pointers_size = xsize; + + /* Allocate uncompressed data buffer. */ + xsize = (size_t)1UL << zisofs->pz_log2_bs; + if (zisofs->uncompressed_buffer_size < xsize) { + if (zisofs->uncompressed_buffer != NULL) + free(zisofs->uncompressed_buffer); + zisofs->uncompressed_buffer = malloc(xsize); + if (zisofs->uncompressed_buffer == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for zisofs decompression"); + return (ARCHIVE_FATAL); + } + } + zisofs->uncompressed_buffer_size = xsize; + + /* + * Read the file header, and check the magic code of zisofs. + */ + if (zisofs->header_avail < sizeof(zisofs->header)) { + xsize = sizeof(zisofs->header) - zisofs->header_avail; + if (avail < xsize) + xsize = avail; + memcpy(zisofs->header + zisofs->header_avail, p, xsize); + zisofs->header_avail += xsize; + avail -= xsize; + p += xsize; + } + if (!zisofs->header_passed && + zisofs->header_avail == sizeof(zisofs->header)) { + int err = 0; + + if (memcmp(zisofs->header, zisofs_magic, + sizeof(zisofs_magic)) != 0) + err = 1; + if (archive_le32dec(zisofs->header + 8) + != zisofs->pz_uncompressed_size) + err = 1; + if (zisofs->header[12] != 4) + err = 1; + if (zisofs->header[13] != zisofs->pz_log2_bs) + err = 1; + if (err) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Illegal zisofs file body"); + return (ARCHIVE_FATAL); + } + zisofs->header_passed = 1; + } + /* + * Read block pointers. + */ + if (zisofs->header_passed && + zisofs->block_pointers_avail < zisofs->block_pointers_size) { + xsize = zisofs->block_pointers_size + - zisofs->block_pointers_avail; + if (avail < xsize) + xsize = avail; + memcpy(zisofs->block_pointers + + zisofs->block_pointers_avail, p, xsize); + zisofs->block_pointers_avail += xsize; + avail -= xsize; + p += xsize; + if (zisofs->block_pointers_avail + == zisofs->block_pointers_size) { + /* We've got all block pointers and initialize + * related variables. */ + zisofs->block_off = 0; + zisofs->block_avail = 0; + /* Complete a initialization */ + zisofs->initialized = 1; + } + } + + if (!zisofs->initialized) + goto next_data; /* We need more data. */ + } + + /* + * Get block offsets from block pointers. + */ + if (zisofs->block_avail == 0) { + uint32_t bst, bed; + + if (zisofs->block_off + 4 >= zisofs->block_pointers_size) { + /* There isn't a pair of offsets. */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Illegal zisofs block pointers"); + return (ARCHIVE_FATAL); + } + bst = archive_le32dec( + zisofs->block_pointers + zisofs->block_off); + if (bst != zisofs->pz_offset + (bytes_read - avail)) { + /* TODO: Should we seek offset of current file + * by bst ? */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Illegal zisofs block pointers(cannot seek)"); + return (ARCHIVE_FATAL); + } + bed = archive_le32dec( + zisofs->block_pointers + zisofs->block_off + 4); + if (bed < bst) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Illegal zisofs block pointers"); + return (ARCHIVE_FATAL); + } + zisofs->block_avail = bed - bst; + zisofs->block_off += 4; + + /* Initialize compression library for new block. */ + if (zisofs->stream_valid) + r = inflateReset(&zisofs->stream); + else + r = inflateInit(&zisofs->stream); + if (r != Z_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can't initialize zisofs decompression."); + return (ARCHIVE_FATAL); + } + zisofs->stream_valid = 1; + zisofs->stream.total_in = 0; + zisofs->stream.total_out = 0; + } + + /* + * Make uncompressed data. + */ + if (zisofs->block_avail == 0) { + memset(zisofs->uncompressed_buffer, 0, + zisofs->uncompressed_buffer_size); + uncompressed_size = zisofs->uncompressed_buffer_size; + } else { + zisofs->stream.next_in = (Bytef *)(uintptr_t)(const void *)p; + if (avail > zisofs->block_avail) + zisofs->stream.avail_in = zisofs->block_avail; + else + zisofs->stream.avail_in = (uInt)avail; + zisofs->stream.next_out = zisofs->uncompressed_buffer; + zisofs->stream.avail_out = + (uInt)zisofs->uncompressed_buffer_size; + + r = inflate(&zisofs->stream, 0); + switch (r) { + case Z_OK: /* Decompressor made some progress.*/ + case Z_STREAM_END: /* Found end of stream. */ + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "zisofs decompression failed (%d)", r); + return (ARCHIVE_FATAL); + } + uncompressed_size = + zisofs->uncompressed_buffer_size - zisofs->stream.avail_out; + avail -= zisofs->stream.next_in - p; + zisofs->block_avail -= (uint32_t)(zisofs->stream.next_in - p); + } +next_data: + bytes_read -= avail; + *buff = zisofs->uncompressed_buffer; + *size = uncompressed_size; + *offset = iso9660->entry_sparse_offset; + iso9660->entry_sparse_offset += uncompressed_size; + iso9660->entry_bytes_remaining -= bytes_read; + iso9660->current_position += bytes_read; + zisofs->pz_offset += (uint32_t)bytes_read; + iso9660->entry_bytes_unconsumed += bytes_read; + + return (ARCHIVE_OK); +} + +#else /* HAVE_ZLIB_H */ + +static int +zisofs_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + + (void)buff;/* UNUSED */ + (void)size;/* UNUSED */ + (void)offset;/* UNUSED */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "zisofs is not supported on this platform."); + return (ARCHIVE_FAILED); +} + +#endif /* HAVE_ZLIB_H */ + +static int +archive_read_format_iso9660_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + ssize_t bytes_read; + struct iso9660 *iso9660; + + iso9660 = (struct iso9660 *)(a->format->data); + + if (iso9660->entry_bytes_unconsumed) { + __archive_read_consume(a, iso9660->entry_bytes_unconsumed); + iso9660->entry_bytes_unconsumed = 0; + } + + if (iso9660->entry_bytes_remaining <= 0) { + if (iso9660->entry_content != NULL) + iso9660->entry_content = iso9660->entry_content->next; + if (iso9660->entry_content == NULL) { + *buff = NULL; + *size = 0; + *offset = iso9660->entry_sparse_offset; + return (ARCHIVE_EOF); + } + /* Seek forward to the start of the entry. */ + if (iso9660->current_position < iso9660->entry_content->offset) { + int64_t step; + + step = iso9660->entry_content->offset - + iso9660->current_position; + step = __archive_read_consume(a, step); + if (step < 0) + return ((int)step); + iso9660->current_position = + iso9660->entry_content->offset; + } + if (iso9660->entry_content->offset < iso9660->current_position) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Ignoring out-of-order file (%s) %jd < %jd", + iso9660->pathname.s, + (intmax_t)iso9660->entry_content->offset, + (intmax_t)iso9660->current_position); + *buff = NULL; + *size = 0; + *offset = iso9660->entry_sparse_offset; + return (ARCHIVE_WARN); + } + iso9660->entry_bytes_remaining = iso9660->entry_content->size; + } + if (iso9660->entry_zisofs.pz) + return (zisofs_read_data(a, buff, size, offset)); + + *buff = __archive_read_ahead(a, 1, &bytes_read); + if (bytes_read == 0) + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Truncated input file"); + if (*buff == NULL) + return (ARCHIVE_FATAL); + if (bytes_read > iso9660->entry_bytes_remaining) + bytes_read = (ssize_t)iso9660->entry_bytes_remaining; + *size = bytes_read; + *offset = iso9660->entry_sparse_offset; + iso9660->entry_sparse_offset += bytes_read; + iso9660->entry_bytes_remaining -= bytes_read; + iso9660->entry_bytes_unconsumed = bytes_read; + iso9660->current_position += bytes_read; + return (ARCHIVE_OK); +} + +static int +archive_read_format_iso9660_cleanup(struct archive_read *a) +{ + struct iso9660 *iso9660; + int r = ARCHIVE_OK; + + iso9660 = (struct iso9660 *)(a->format->data); + release_files(iso9660); + free(iso9660->read_ce_req.reqs); + archive_string_free(&iso9660->pathname); + archive_string_free(&iso9660->previous_pathname); + free(iso9660->pending_files.files); +#ifdef HAVE_ZLIB_H + free(iso9660->entry_zisofs.uncompressed_buffer); + free(iso9660->entry_zisofs.block_pointers); + if (iso9660->entry_zisofs.stream_valid) { + if (inflateEnd(&iso9660->entry_zisofs.stream) != Z_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Failed to clean up zlib decompressor"); + r = ARCHIVE_FATAL; + } + } +#endif + free(iso9660->utf16be_path); + free(iso9660->utf16be_previous_path); + free(iso9660); + (a->format->data) = NULL; + return (r); +} + +/* + * This routine parses a single ISO directory record, makes sense + * of any extensions, and stores the result in memory. + */ +static struct file_info * +parse_file_info(struct archive_read *a, struct file_info *parent, + const unsigned char *isodirrec, size_t reclen) +{ + struct iso9660 *iso9660; + struct file_info *file, *filep; + size_t name_len; + const unsigned char *rr_start, *rr_end; + const unsigned char *p; + size_t dr_len; + uint64_t fsize, offset; + int32_t location; + int flags; + + iso9660 = (struct iso9660 *)(a->format->data); + + if (reclen != 0) + dr_len = (size_t)isodirrec[DR_length_offset]; + /* + * Sanity check that reclen is not zero and dr_len is greater than + * reclen but at least 34 + */ + if (reclen == 0 || reclen < dr_len || dr_len < 34) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid length of directory record"); + return (NULL); + } + name_len = (size_t)isodirrec[DR_name_len_offset]; + location = archive_le32dec(isodirrec + DR_extent_offset); + fsize = toi(isodirrec + DR_size_offset, DR_size_size); + /* Sanity check that name_len doesn't exceed dr_len. */ + if (dr_len - 33 < name_len || name_len == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid length of file identifier"); + return (NULL); + } + /* Sanity check that location doesn't exceed volume block. + * Don't check lower limit of location; it's possibility + * the location has negative value when file type is symbolic + * link or file size is zero. As far as I know latest mkisofs + * do that. + */ + if (location > 0 && + (location + ((fsize + iso9660->logical_block_size -1) + / iso9660->logical_block_size)) + > (uint32_t)iso9660->volume_block) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid location of extent of file"); + return (NULL); + } + /* Sanity check that location doesn't have a negative value + * when the file is not empty. it's too large. */ + if (fsize != 0 && location < 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid location of extent of file"); + return (NULL); + } + + /* Sanity check that this entry does not create a cycle. */ + offset = iso9660->logical_block_size * (uint64_t)location; + for (filep = parent; filep != NULL; filep = filep->parent) { + if (filep->offset == offset) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Directory structure contains loop"); + return (NULL); + } + } + + /* Create a new file entry and copy data from the ISO dir record. */ + file = (struct file_info *)calloc(1, sizeof(*file)); + if (file == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for file entry"); + return (NULL); + } + file->parent = parent; + file->offset = offset; + file->size = fsize; + file->mtime = isodate7(isodirrec + DR_date_offset); + file->ctime = file->atime = file->mtime; + file->rede_files.first = NULL; + file->rede_files.last = &(file->rede_files.first); + + p = isodirrec + DR_name_offset; + /* Rockridge extensions (if any) follow name. Compute this + * before fidgeting the name_len below. */ + rr_start = p + name_len + (name_len & 1 ? 0 : 1); + rr_end = isodirrec + dr_len; + + if (iso9660->seenJoliet) { + /* Joliet names are max 64 chars (128 bytes) according to spec, + * but genisoimage/mkisofs allows recording longer Joliet + * names which are 103 UCS2 characters(206 bytes) by their + * option '-joliet-long'. + */ + if (name_len > 206) + name_len = 206; + name_len &= ~1; + + /* trim trailing first version and dot from filename. + * + * Remember we were in UTF-16BE land! + * SEPARATOR 1 (.) and SEPARATOR 2 (;) are both + * 16 bits big endian characters on Joliet. + * + * TODO: sanitize filename? + * Joliet allows any UCS-2 char except: + * *, /, :, ;, ? and \. + */ + /* Chop off trailing ';1' from files. */ + if (name_len > 4 && p[name_len-4] == 0 && p[name_len-3] == ';' + && p[name_len-2] == 0 && p[name_len-1] == '1') + name_len -= 4; +#if 0 /* XXX: this somehow manages to strip of single-character file extensions, like '.c'. */ + /* Chop off trailing '.' from filenames. */ + if (name_len > 2 && p[name_len-2] == 0 && p[name_len-1] == '.') + name_len -= 2; +#endif + if ((file->utf16be_name = malloc(name_len)) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for file name"); + goto fail; + } + memcpy(file->utf16be_name, p, name_len); + file->utf16be_bytes = name_len; + } else { + /* Chop off trailing ';1' from files. */ + if (name_len > 2 && p[name_len - 2] == ';' && + p[name_len - 1] == '1') + name_len -= 2; + /* Chop off trailing '.' from filenames. */ + if (name_len > 1 && p[name_len - 1] == '.') + --name_len; + + archive_strncpy(&file->name, (const char *)p, name_len); + } + + flags = isodirrec[DR_flags_offset]; + if (flags & 0x02) + file->mode = AE_IFDIR | 0700; + else + file->mode = AE_IFREG | 0400; + if (flags & 0x80) + file->multi_extent = 1; + else + file->multi_extent = 0; + /* + * Use a location for the file number, which is treated as an inode + * number to find out hardlink target. If Rockridge extensions is + * being used, the file number will be overwritten by FILE SERIAL + * NUMBER of RRIP "PX" extension. + * Note: Old mkisofs did not record that FILE SERIAL NUMBER + * in ISO images. + * Note2: xorriso set 0 to the location of a symlink file. + */ + if (file->size == 0 && location >= 0) { + /* If file->size is zero, its location points wrong place, + * and so we should not use it for the file number. + * When the location has negative value, it can be used + * for the file number. + */ + file->number = -1; + /* Do not appear before any directory entries. */ + file->offset = -1; + } else + file->number = (int64_t)(uint32_t)location; + + /* Rockridge extensions overwrite information from above. */ + if (iso9660->opt_support_rockridge) { + if (parent == NULL && rr_end - rr_start >= 7) { + p = rr_start; + if (memcmp(p, "SP\x07\x01\xbe\xef", 6) == 0) { + /* + * SP extension stores the suspOffset + * (Number of bytes to skip between + * filename and SUSP records.) + * It is mandatory by the SUSP standard + * (IEEE 1281). + * + * It allows SUSP to coexist with + * non-SUSP uses of the System + * Use Area by placing non-SUSP data + * before SUSP data. + * + * SP extension must be in the root + * directory entry, disable all SUSP + * processing if not found. + */ + iso9660->suspOffset = p[6]; + iso9660->seenSUSP = 1; + rr_start += 7; + } + } + if (iso9660->seenSUSP) { + int r; + + file->name_continues = 0; + file->symlink_continues = 0; + rr_start += iso9660->suspOffset; + r = parse_rockridge(a, file, rr_start, rr_end); + if (r != ARCHIVE_OK) + goto fail; + /* + * A file size of symbolic link files in ISO images + * made by makefs is not zero and its location is + * the same as those of next regular file. That is + * the same as hard like file and it causes unexpected + * error. + */ + if (file->size > 0 && + (file->mode & AE_IFMT) == AE_IFLNK) { + file->size = 0; + file->number = -1; + file->offset = -1; + } + } else + /* If there isn't SUSP, disable parsing + * rock ridge extensions. */ + iso9660->opt_support_rockridge = 0; + } + + file->nlinks = 1;/* Reset nlink. we'll calculate it later. */ + /* Tell file's parent how many children that parent has. */ + if (parent != NULL && (flags & 0x02)) + parent->subdirs++; + + if (iso9660->seenRockridge) { + if (parent != NULL && parent->parent == NULL && + (flags & 0x02) && iso9660->rr_moved == NULL && + file->name.s && + (strcmp(file->name.s, "rr_moved") == 0 || + strcmp(file->name.s, ".rr_moved") == 0)) { + iso9660->rr_moved = file; + file->rr_moved = 1; + file->rr_moved_has_re_only = 1; + file->re = 0; + parent->subdirs--; + } else if (file->re) { + /* + * Sanity check: file's parent is rr_moved. + */ + if (parent == NULL || parent->rr_moved == 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Invalid Rockridge RE"); + goto fail; + } + /* + * Sanity check: file does not have "CL" extension. + */ + if (file->cl_offset) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Invalid Rockridge RE and CL"); + goto fail; + } + /* + * Sanity check: The file type must be a directory. + */ + if ((flags & 0x02) == 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Invalid Rockridge RE"); + goto fail; + } + } else if (parent != NULL && parent->rr_moved) + file->rr_moved_has_re_only = 0; + else if (parent != NULL && (flags & 0x02) && + (parent->re || parent->re_descendant)) + file->re_descendant = 1; + if (file->cl_offset) { + struct file_info *r; + + if (parent == NULL || parent->parent == NULL) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Invalid Rockridge CL"); + goto fail; + } + /* + * Sanity check: The file type must be a regular file. + */ + if ((flags & 0x02) != 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Invalid Rockridge CL"); + goto fail; + } + parent->subdirs++; + /* Overwrite an offset and a number of this "CL" entry + * to appear before other dirs. "+1" to those is to + * make sure to appear after "RE" entry which this + * "CL" entry should be connected with. */ + file->offset = file->number = file->cl_offset + 1; + + /* + * Sanity check: cl_offset does not point at its + * the parents or itself. + */ + for (r = parent; r; r = r->parent) { + if (r->offset == file->cl_offset) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Invalid Rockridge CL"); + goto fail; + } + } + if (file->cl_offset == file->offset || + parent->rr_moved) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Invalid Rockridge CL"); + goto fail; + } + } + } + +#if DEBUG + /* DEBUGGING: Warn about attributes I don't yet fully support. */ + if ((flags & ~0x02) != 0) { + fprintf(stderr, "\n ** Unrecognized flag: "); + dump_isodirrec(stderr, isodirrec); + fprintf(stderr, "\n"); + } else if (toi(isodirrec + DR_volume_sequence_number_offset, 2) != 1) { + fprintf(stderr, "\n ** Unrecognized sequence number: "); + dump_isodirrec(stderr, isodirrec); + fprintf(stderr, "\n"); + } else if (*(isodirrec + DR_file_unit_size_offset) != 0) { + fprintf(stderr, "\n ** Unexpected file unit size: "); + dump_isodirrec(stderr, isodirrec); + fprintf(stderr, "\n"); + } else if (*(isodirrec + DR_interleave_offset) != 0) { + fprintf(stderr, "\n ** Unexpected interleave: "); + dump_isodirrec(stderr, isodirrec); + fprintf(stderr, "\n"); + } else if (*(isodirrec + DR_ext_attr_length_offset) != 0) { + fprintf(stderr, "\n ** Unexpected extended attribute length: "); + dump_isodirrec(stderr, isodirrec); + fprintf(stderr, "\n"); + } +#endif + register_file(iso9660, file); + return (file); +fail: + archive_string_free(&file->name); + free(file); + return (NULL); +} + +static int +parse_rockridge(struct archive_read *a, struct file_info *file, + const unsigned char *p, const unsigned char *end) +{ + struct iso9660 *iso9660; + int entry_seen = 0; + + iso9660 = (struct iso9660 *)(a->format->data); + + while (p + 4 <= end /* Enough space for another entry. */ + && p[0] >= 'A' && p[0] <= 'Z' /* Sanity-check 1st char of name. */ + && p[1] >= 'A' && p[1] <= 'Z' /* Sanity-check 2nd char of name. */ + && p[2] >= 4 /* Sanity-check length. */ + && p + p[2] <= end) { /* Sanity-check length. */ + const unsigned char *data = p + 4; + int data_length = p[2] - 4; + int version = p[3]; + + switch(p[0]) { + case 'C': + if (p[1] == 'E') { + if (version == 1 && data_length == 24) { + /* + * CE extension comprises: + * 8 byte sector containing extension + * 8 byte offset w/in above sector + * 8 byte length of continuation + */ + int32_t location = + archive_le32dec(data); + file->ce_offset = + archive_le32dec(data+8); + file->ce_size = + archive_le32dec(data+16); + if (register_CE(a, location, file) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + } + else if (p[1] == 'L') { + if (version == 1 && data_length == 8) { + file->cl_offset = (uint64_t) + iso9660->logical_block_size * + (uint64_t)archive_le32dec(data); + iso9660->seenRockridge = 1; + } + } + break; + case 'N': + if (p[1] == 'M') { + if (version == 1) { + parse_rockridge_NM1(file, + data, data_length); + iso9660->seenRockridge = 1; + } + } + break; + case 'P': + /* + * PD extension is padding; + * contents are always ignored. + * + * PL extension won't appear; + * contents are always ignored. + */ + if (p[1] == 'N') { + if (version == 1 && data_length == 16) { + file->rdev = toi(data,4); + file->rdev <<= 32; + file->rdev |= toi(data + 8, 4); + iso9660->seenRockridge = 1; + } + } + else if (p[1] == 'X') { + /* + * PX extension comprises: + * 8 bytes for mode, + * 8 bytes for nlinks, + * 8 bytes for uid, + * 8 bytes for gid, + * 8 bytes for inode. + */ + if (version == 1) { + if (data_length >= 8) + file->mode + = toi(data, 4); + if (data_length >= 16) + file->nlinks + = toi(data + 8, 4); + if (data_length >= 24) + file->uid + = toi(data + 16, 4); + if (data_length >= 32) + file->gid + = toi(data + 24, 4); + if (data_length >= 40) + file->number + = toi(data + 32, 4); + iso9660->seenRockridge = 1; + } + } + break; + case 'R': + if (p[1] == 'E' && version == 1) { + file->re = 1; + iso9660->seenRockridge = 1; + } + else if (p[1] == 'R' && version == 1) { + /* + * RR extension comprises: + * one byte flag value + * This extension is obsolete, + * so contents are always ignored. + */ + } + break; + case 'S': + if (p[1] == 'L') { + if (version == 1) { + parse_rockridge_SL1(file, + data, data_length); + iso9660->seenRockridge = 1; + } + } + else if (p[1] == 'T' + && data_length == 0 && version == 1) { + /* + * ST extension marks end of this + * block of SUSP entries. + * + * It allows SUSP to coexist with + * non-SUSP uses of the System + * Use Area by placing non-SUSP data + * after SUSP data. + */ + iso9660->seenSUSP = 0; + iso9660->seenRockridge = 0; + return (ARCHIVE_OK); + } + break; + case 'T': + if (p[1] == 'F') { + if (version == 1) { + parse_rockridge_TF1(file, + data, data_length); + iso9660->seenRockridge = 1; + } + } + break; + case 'Z': + if (p[1] == 'F') { + if (version == 1) + parse_rockridge_ZF1(file, + data, data_length); + } + break; + default: + break; + } + + p += p[2]; + entry_seen = 1; + } + + if (entry_seen) + return (ARCHIVE_OK); + else { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Tried to parse Rockridge extensions, but none found"); + return (ARCHIVE_WARN); + } +} + +static int +register_CE(struct archive_read *a, int32_t location, + struct file_info *file) +{ + struct iso9660 *iso9660; + struct read_ce_queue *heap; + struct read_ce_req *p; + uint64_t offset, parent_offset; + int hole, parent; + + iso9660 = (struct iso9660 *)(a->format->data); + offset = ((uint64_t)location) * (uint64_t)iso9660->logical_block_size; + if (((file->mode & AE_IFMT) == AE_IFREG && + offset >= file->offset) || + offset < iso9660->current_position || + (((uint64_t)file->ce_offset) + file->ce_size) + > (uint64_t)iso9660->logical_block_size || + offset + file->ce_offset + file->ce_size + > iso9660->volume_size) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid parameter in SUSP \"CE\" extension"); + return (ARCHIVE_FATAL); + } + + /* Expand our CE list as necessary. */ + heap = &(iso9660->read_ce_req); + if (heap->cnt >= heap->allocated) { + int new_size; + + if (heap->allocated < 16) + new_size = 16; + else + new_size = heap->allocated * 2; + /* Overflow might keep us from growing the list. */ + if (new_size <= heap->allocated) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + p = calloc(new_size, sizeof(p[0])); + if (p == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + if (heap->reqs != NULL) { + memcpy(p, heap->reqs, heap->cnt * sizeof(*p)); + free(heap->reqs); + } + heap->reqs = p; + heap->allocated = new_size; + } + + /* + * Start with hole at end, walk it up tree to find insertion point. + */ + hole = heap->cnt++; + while (hole > 0) { + parent = (hole - 1)/2; + parent_offset = heap->reqs[parent].offset; + if (offset >= parent_offset) { + heap->reqs[hole].offset = offset; + heap->reqs[hole].file = file; + return (ARCHIVE_OK); + } + /* Move parent into hole <==> move hole up tree. */ + heap->reqs[hole] = heap->reqs[parent]; + hole = parent; + } + heap->reqs[0].offset = offset; + heap->reqs[0].file = file; + return (ARCHIVE_OK); +} + +static void +next_CE(struct read_ce_queue *heap) +{ + uint64_t a_offset, b_offset, c_offset; + int a, b, c; + struct read_ce_req tmp; + + if (heap->cnt < 1) + return; + + /* + * Move the last item in the heap to the root of the tree + */ + heap->reqs[0] = heap->reqs[--(heap->cnt)]; + + /* + * Rebalance the heap. + */ + a = 0; /* Starting element and its offset */ + a_offset = heap->reqs[a].offset; + for (;;) { + b = a + a + 1; /* First child */ + if (b >= heap->cnt) + return; + b_offset = heap->reqs[b].offset; + c = b + 1; /* Use second child if it is smaller. */ + if (c < heap->cnt) { + c_offset = heap->reqs[c].offset; + if (c_offset < b_offset) { + b = c; + b_offset = c_offset; + } + } + if (a_offset <= b_offset) + return; + tmp = heap->reqs[a]; + heap->reqs[a] = heap->reqs[b]; + heap->reqs[b] = tmp; + a = b; + } +} + + +static int +read_CE(struct archive_read *a, struct iso9660 *iso9660) +{ + struct read_ce_queue *heap; + const unsigned char *b, *p, *end; + struct file_info *file; + size_t step; + int r; + + /* Read data which RRIP "CE" extension points. */ + heap = &(iso9660->read_ce_req); + step = iso9660->logical_block_size; + while (heap->cnt && + heap->reqs[0].offset == iso9660->current_position) { + b = __archive_read_ahead(a, step, NULL); + if (b == NULL) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Failed to read full block when scanning " + "ISO9660 directory list"); + return (ARCHIVE_FATAL); + } + do { + file = heap->reqs[0].file; + if (file->ce_offset + file->ce_size > step) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Malformed CE information"); + return (ARCHIVE_FATAL); + } + p = b + file->ce_offset; + end = p + file->ce_size; + next_CE(heap); + r = parse_rockridge(a, file, p, end); + if (r != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } while (heap->cnt && + heap->reqs[0].offset == iso9660->current_position); + /* NOTE: Do not move this consume's code to front of + * do-while loop. Registration of nested CE extension + * might cause error because of current position. */ + __archive_read_consume(a, step); + iso9660->current_position += step; + } + return (ARCHIVE_OK); +} + +static void +parse_rockridge_NM1(struct file_info *file, + const unsigned char *data, int data_length) +{ + if (!file->name_continues) + archive_string_empty(&file->name); + file->name_continues = 0; + if (data_length < 1) + return; + /* + * NM version 1 extension comprises: + * 1 byte flag, value is one of: + * = 0: remainder is name + * = 1: remainder is name, next NM entry continues name + * = 2: "." + * = 4: ".." + * = 32: Implementation specific + * All other values are reserved. + */ + switch(data[0]) { + case 0: + if (data_length < 2) + return; + archive_strncat(&file->name, + (const char *)data + 1, data_length - 1); + break; + case 1: + if (data_length < 2) + return; + archive_strncat(&file->name, + (const char *)data + 1, data_length - 1); + file->name_continues = 1; + break; + case 2: + archive_strcat(&file->name, "."); + break; + case 4: + archive_strcat(&file->name, ".."); + break; + default: + return; + } + +} + +static void +parse_rockridge_TF1(struct file_info *file, const unsigned char *data, + int data_length) +{ + char flag; + /* + * TF extension comprises: + * one byte flag + * create time (optional) + * modify time (optional) + * access time (optional) + * attribute time (optional) + * Time format and presence of fields + * is controlled by flag bits. + */ + if (data_length < 1) + return; + flag = data[0]; + ++data; + --data_length; + if (flag & 0x80) { + /* Use 17-byte time format. */ + if ((flag & 1) && data_length >= 17) { + /* Create time. */ + file->birthtime_is_set = 1; + file->birthtime = isodate17(data); + data += 17; + data_length -= 17; + } + if ((flag & 2) && data_length >= 17) { + /* Modify time. */ + file->mtime = isodate17(data); + data += 17; + data_length -= 17; + } + if ((flag & 4) && data_length >= 17) { + /* Access time. */ + file->atime = isodate17(data); + data += 17; + data_length -= 17; + } + if ((flag & 8) && data_length >= 17) { + /* Attribute change time. */ + file->ctime = isodate17(data); + } + } else { + /* Use 7-byte time format. */ + if ((flag & 1) && data_length >= 7) { + /* Create time. */ + file->birthtime_is_set = 1; + file->birthtime = isodate7(data); + data += 7; + data_length -= 7; + } + if ((flag & 2) && data_length >= 7) { + /* Modify time. */ + file->mtime = isodate7(data); + data += 7; + data_length -= 7; + } + if ((flag & 4) && data_length >= 7) { + /* Access time. */ + file->atime = isodate7(data); + data += 7; + data_length -= 7; + } + if ((flag & 8) && data_length >= 7) { + /* Attribute change time. */ + file->ctime = isodate7(data); + } + } +} + +static void +parse_rockridge_SL1(struct file_info *file, const unsigned char *data, + int data_length) +{ + const char *separator = ""; + + if (!file->symlink_continues || file->symlink.length < 1) + archive_string_empty(&file->symlink); + file->symlink_continues = 0; + + /* + * Defined flag values: + * 0: This is the last SL record for this symbolic link + * 1: this symbolic link field continues in next SL entry + * All other values are reserved. + */ + if (data_length < 1) + return; + switch(*data) { + case 0: + break; + case 1: + file->symlink_continues = 1; + break; + default: + return; + } + ++data; /* Skip flag byte. */ + --data_length; + + /* + * SL extension body stores "components". + * Basically, this is a complicated way of storing + * a POSIX path. It also interferes with using + * symlinks for storing non-path data. <sigh> + * + * Each component is 2 bytes (flag and length) + * possibly followed by name data. + */ + while (data_length >= 2) { + unsigned char flag = *data++; + unsigned char nlen = *data++; + data_length -= 2; + + archive_strcat(&file->symlink, separator); + separator = "/"; + + switch(flag) { + case 0: /* Usual case, this is text. */ + if (data_length < nlen) + return; + archive_strncat(&file->symlink, + (const char *)data, nlen); + break; + case 0x01: /* Text continues in next component. */ + if (data_length < nlen) + return; + archive_strncat(&file->symlink, + (const char *)data, nlen); + separator = ""; + break; + case 0x02: /* Current dir. */ + archive_strcat(&file->symlink, "."); + break; + case 0x04: /* Parent dir. */ + archive_strcat(&file->symlink, ".."); + break; + case 0x08: /* Root of filesystem. */ + archive_strcat(&file->symlink, "/"); + separator = ""; + break; + case 0x10: /* Undefined (historically "volume root" */ + archive_string_empty(&file->symlink); + archive_strcat(&file->symlink, "ROOT"); + break; + case 0x20: /* Undefined (historically "hostname") */ + archive_strcat(&file->symlink, "hostname"); + break; + default: + /* TODO: issue a warning ? */ + return; + } + data += nlen; + data_length -= nlen; + } +} + +static void +parse_rockridge_ZF1(struct file_info *file, const unsigned char *data, + int data_length) +{ + + if (data[0] == 0x70 && data[1] == 0x7a && data_length == 12) { + /* paged zlib */ + file->pz = 1; + file->pz_log2_bs = data[3]; + file->pz_uncompressed_size = archive_le32dec(&data[4]); + } +} + +static void +register_file(struct iso9660 *iso9660, struct file_info *file) +{ + + file->use_next = iso9660->use_files; + iso9660->use_files = file; +} + +static void +release_files(struct iso9660 *iso9660) +{ + struct content *con, *connext; + struct file_info *file; + + file = iso9660->use_files; + while (file != NULL) { + struct file_info *next = file->use_next; + + archive_string_free(&file->name); + archive_string_free(&file->symlink); + free(file->utf16be_name); + con = file->contents.first; + while (con != NULL) { + connext = con->next; + free(con); + con = connext; + } + free(file); + file = next; + } +} + +static int +next_entry_seek(struct archive_read *a, struct iso9660 *iso9660, + struct file_info **pfile) +{ + struct file_info *file; + int r; + + r = next_cache_entry(a, iso9660, pfile); + if (r != ARCHIVE_OK) + return (r); + file = *pfile; + + /* Don't waste time seeking for zero-length bodies. */ + if (file->size == 0) + file->offset = iso9660->current_position; + + /* flush any remaining bytes from the last round to ensure + * we're positioned */ + if (iso9660->entry_bytes_unconsumed) { + __archive_read_consume(a, iso9660->entry_bytes_unconsumed); + iso9660->entry_bytes_unconsumed = 0; + } + + /* Seek forward to the start of the entry. */ + if (iso9660->current_position < file->offset) { + int64_t step; + + step = file->offset - iso9660->current_position; + step = __archive_read_consume(a, step); + if (step < 0) + return ((int)step); + iso9660->current_position = file->offset; + } + + /* We found body of file; handle it now. */ + return (ARCHIVE_OK); +} + +static int +next_cache_entry(struct archive_read *a, struct iso9660 *iso9660, + struct file_info **pfile) +{ + struct file_info *file; + struct { + struct file_info *first; + struct file_info **last; + } empty_files; + int64_t number; + int count; + + file = cache_get_entry(iso9660); + if (file != NULL) { + *pfile = file; + return (ARCHIVE_OK); + } + + for (;;) { + struct file_info *re, *d; + + *pfile = file = next_entry(iso9660); + if (file == NULL) { + /* + * If directory entries all which are descendant of + * rr_moved are still remaining, expose their. + */ + if (iso9660->re_files.first != NULL && + iso9660->rr_moved != NULL && + iso9660->rr_moved->rr_moved_has_re_only) + /* Expose "rr_moved" entry. */ + cache_add_entry(iso9660, iso9660->rr_moved); + while ((re = re_get_entry(iso9660)) != NULL) { + /* Expose its descendant dirs. */ + while ((d = rede_get_entry(re)) != NULL) + cache_add_entry(iso9660, d); + } + if (iso9660->cache_files.first != NULL) + return (next_cache_entry(a, iso9660, pfile)); + return (ARCHIVE_EOF); + } + + if (file->cl_offset) { + struct file_info *first_re = NULL; + int nexted_re = 0; + + /* + * Find "RE" dir for the current file, which + * has "CL" flag. + */ + while ((re = re_get_entry(iso9660)) + != first_re) { + if (first_re == NULL) + first_re = re; + if (re->offset == file->cl_offset) { + re->parent->subdirs--; + re->parent = file->parent; + re->re = 0; + if (re->parent->re_descendant) { + nexted_re = 1; + re->re_descendant = 1; + if (rede_add_entry(re) < 0) + goto fatal_rr; + /* Move a list of descendants + * to a new ancestor. */ + while ((d = rede_get_entry( + re)) != NULL) + if (rede_add_entry(d) + < 0) + goto fatal_rr; + break; + } + /* Replace the current file + * with "RE" dir */ + *pfile = file = re; + /* Expose its descendant */ + while ((d = rede_get_entry( + file)) != NULL) + cache_add_entry( + iso9660, d); + break; + } else + re_add_entry(iso9660, re); + } + if (nexted_re) { + /* + * Do not expose this at this time + * because we have not gotten its full-path + * name yet. + */ + continue; + } + } else if ((file->mode & AE_IFMT) == AE_IFDIR) { + int r; + + /* Read file entries in this dir. */ + r = read_children(a, file); + if (r != ARCHIVE_OK) + return (r); + + /* + * Handle a special dir of Rockridge extensions, + * "rr_moved". + */ + if (file->rr_moved) { + /* + * If this has only the subdirectories which + * have "RE" flags, do not expose at this time. + */ + if (file->rr_moved_has_re_only) + continue; + /* Otherwise expose "rr_moved" entry. */ + } else if (file->re) { + /* + * Do not expose this at this time + * because we have not gotten its full-path + * name yet. + */ + re_add_entry(iso9660, file); + continue; + } else if (file->re_descendant) { + /* + * If the top level "RE" entry of this entry + * is not exposed, we, accordingly, should not + * expose this entry at this time because + * we cannot make its proper full-path name. + */ + if (rede_add_entry(file) == 0) + continue; + /* Otherwise we can expose this entry because + * it seems its top level "RE" has already been + * exposed. */ + } + } + break; + } + + if ((file->mode & AE_IFMT) != AE_IFREG || file->number == -1) + return (ARCHIVE_OK); + + count = 0; + number = file->number; + iso9660->cache_files.first = NULL; + iso9660->cache_files.last = &(iso9660->cache_files.first); + empty_files.first = NULL; + empty_files.last = &empty_files.first; + /* Collect files which has the same file serial number. + * Peek pending_files so that file which number is different + * is not put back. */ + while (iso9660->pending_files.used > 0 && + (iso9660->pending_files.files[0]->number == -1 || + iso9660->pending_files.files[0]->number == number)) { + if (file->number == -1) { + /* This file has the same offset + * but it's wrong offset which empty files + * and symlink files have. + * NOTE: This wrong offset was recorded by + * old mkisofs utility. If ISO images is + * created by latest mkisofs, this does not + * happen. + */ + file->next = NULL; + *empty_files.last = file; + empty_files.last = &(file->next); + } else { + count++; + cache_add_entry(iso9660, file); + } + file = next_entry(iso9660); + } + + if (count == 0) { + *pfile = file; + return ((file == NULL)?ARCHIVE_EOF:ARCHIVE_OK); + } + if (file->number == -1) { + file->next = NULL; + *empty_files.last = file; + empty_files.last = &(file->next); + } else { + count++; + cache_add_entry(iso9660, file); + } + + if (count > 1) { + /* The count is the same as number of hardlink, + * so much so that each nlinks of files in cache_file + * is overwritten by value of the count. + */ + for (file = iso9660->cache_files.first; + file != NULL; file = file->next) + file->nlinks = count; + } + /* If there are empty files, that files are added + * to the tail of the cache_files. */ + if (empty_files.first != NULL) { + *iso9660->cache_files.last = empty_files.first; + iso9660->cache_files.last = empty_files.last; + } + *pfile = cache_get_entry(iso9660); + return ((*pfile == NULL)?ARCHIVE_EOF:ARCHIVE_OK); + +fatal_rr: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Failed to connect 'CL' pointer to 'RE' rr_moved pointer of " + "Rockridge extensions: current position = %jd, CL offset = %jd", + (intmax_t)iso9660->current_position, (intmax_t)file->cl_offset); + return (ARCHIVE_FATAL); +} + +static inline void +re_add_entry(struct iso9660 *iso9660, struct file_info *file) +{ + file->re_next = NULL; + *iso9660->re_files.last = file; + iso9660->re_files.last = &(file->re_next); +} + +static inline struct file_info * +re_get_entry(struct iso9660 *iso9660) +{ + struct file_info *file; + + if ((file = iso9660->re_files.first) != NULL) { + iso9660->re_files.first = file->re_next; + if (iso9660->re_files.first == NULL) + iso9660->re_files.last = + &(iso9660->re_files.first); + } + return (file); +} + +static inline int +rede_add_entry(struct file_info *file) +{ + struct file_info *re; + + /* + * Find "RE" entry. + */ + re = file->parent; + while (re != NULL && !re->re) + re = re->parent; + if (re == NULL) + return (-1); + + file->re_next = NULL; + *re->rede_files.last = file; + re->rede_files.last = &(file->re_next); + return (0); +} + +static inline struct file_info * +rede_get_entry(struct file_info *re) +{ + struct file_info *file; + + if ((file = re->rede_files.first) != NULL) { + re->rede_files.first = file->re_next; + if (re->rede_files.first == NULL) + re->rede_files.last = + &(re->rede_files.first); + } + return (file); +} + +static inline void +cache_add_entry(struct iso9660 *iso9660, struct file_info *file) +{ + file->next = NULL; + *iso9660->cache_files.last = file; + iso9660->cache_files.last = &(file->next); +} + +static inline struct file_info * +cache_get_entry(struct iso9660 *iso9660) +{ + struct file_info *file; + + if ((file = iso9660->cache_files.first) != NULL) { + iso9660->cache_files.first = file->next; + if (iso9660->cache_files.first == NULL) + iso9660->cache_files.last = + &(iso9660->cache_files.first); + } + return (file); +} + +static int +heap_add_entry(struct archive_read *a, struct heap_queue *heap, + struct file_info *file, uint64_t key) +{ + uint64_t file_key, parent_key; + int hole, parent; + + /* Expand our pending files list as necessary. */ + if (heap->used >= heap->allocated) { + struct file_info **new_pending_files; + int new_size = heap->allocated * 2; + + if (heap->allocated < 1024) + new_size = 1024; + /* Overflow might keep us from growing the list. */ + if (new_size <= heap->allocated) { + archive_set_error(&a->archive, + ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + new_pending_files = (struct file_info **) + malloc(new_size * sizeof(new_pending_files[0])); + if (new_pending_files == NULL) { + archive_set_error(&a->archive, + ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + if (heap->allocated) + memcpy(new_pending_files, heap->files, + heap->allocated * sizeof(new_pending_files[0])); + free(heap->files); + heap->files = new_pending_files; + heap->allocated = new_size; + } + + file_key = file->key = key; + + /* + * Start with hole at end, walk it up tree to find insertion point. + */ + hole = heap->used++; + while (hole > 0) { + parent = (hole - 1)/2; + parent_key = heap->files[parent]->key; + if (file_key >= parent_key) { + heap->files[hole] = file; + return (ARCHIVE_OK); + } + /* Move parent into hole <==> move hole up tree. */ + heap->files[hole] = heap->files[parent]; + hole = parent; + } + heap->files[0] = file; + + return (ARCHIVE_OK); +} + +static struct file_info * +heap_get_entry(struct heap_queue *heap) +{ + uint64_t a_key, b_key, c_key; + int a, b, c; + struct file_info *r, *tmp; + + if (heap->used < 1) + return (NULL); + + /* + * The first file in the list is the earliest; we'll return this. + */ + r = heap->files[0]; + + /* + * Move the last item in the heap to the root of the tree + */ + heap->files[0] = heap->files[--(heap->used)]; + + /* + * Rebalance the heap. + */ + a = 0; /* Starting element and its heap key */ + a_key = heap->files[a]->key; + for (;;) { + b = a + a + 1; /* First child */ + if (b >= heap->used) + return (r); + b_key = heap->files[b]->key; + c = b + 1; /* Use second child if it is smaller. */ + if (c < heap->used) { + c_key = heap->files[c]->key; + if (c_key < b_key) { + b = c; + b_key = c_key; + } + } + if (a_key <= b_key) + return (r); + tmp = heap->files[a]; + heap->files[a] = heap->files[b]; + heap->files[b] = tmp; + a = b; + } +} + +static unsigned int +toi(const void *p, int n) +{ + const unsigned char *v = (const unsigned char *)p; + if (n > 1) + return v[0] + 256 * toi(v + 1, n - 1); + if (n == 1) + return v[0]; + return (0); +} + +static time_t +isodate7(const unsigned char *v) +{ + struct tm tm; + int offset; + time_t t; + + memset(&tm, 0, sizeof(tm)); + tm.tm_year = v[0]; + tm.tm_mon = v[1] - 1; + tm.tm_mday = v[2]; + tm.tm_hour = v[3]; + tm.tm_min = v[4]; + tm.tm_sec = v[5]; + /* v[6] is the signed timezone offset, in 1/4-hour increments. */ + offset = ((const signed char *)v)[6]; + if (offset > -48 && offset < 52) { + tm.tm_hour -= offset / 4; + tm.tm_min -= (offset % 4) * 15; + } + t = time_from_tm(&tm); + if (t == (time_t)-1) + return ((time_t)0); + return (t); +} + +static time_t +isodate17(const unsigned char *v) +{ + struct tm tm; + int offset; + time_t t; + + memset(&tm, 0, sizeof(tm)); + tm.tm_year = (v[0] - '0') * 1000 + (v[1] - '0') * 100 + + (v[2] - '0') * 10 + (v[3] - '0') + - 1900; + tm.tm_mon = (v[4] - '0') * 10 + (v[5] - '0'); + tm.tm_mday = (v[6] - '0') * 10 + (v[7] - '0'); + tm.tm_hour = (v[8] - '0') * 10 + (v[9] - '0'); + tm.tm_min = (v[10] - '0') * 10 + (v[11] - '0'); + tm.tm_sec = (v[12] - '0') * 10 + (v[13] - '0'); + /* v[16] is the signed timezone offset, in 1/4-hour increments. */ + offset = ((const signed char *)v)[16]; + if (offset > -48 && offset < 52) { + tm.tm_hour -= offset / 4; + tm.tm_min -= (offset % 4) * 15; + } + t = time_from_tm(&tm); + if (t == (time_t)-1) + return ((time_t)0); + return (t); +} + +static time_t +time_from_tm(struct tm *t) +{ +#if HAVE_TIMEGM + /* Use platform timegm() if available. */ + return (timegm(t)); +#elif HAVE__MKGMTIME64 + return (_mkgmtime64(t)); +#else + /* Else use direct calculation using POSIX assumptions. */ + /* First, fix up tm_yday based on the year/month/day. */ + if (mktime(t) == (time_t)-1) + return ((time_t)-1); + /* Then we can compute timegm() from first principles. */ + return (t->tm_sec + + t->tm_min * 60 + + t->tm_hour * 3600 + + t->tm_yday * 86400 + + (t->tm_year - 70) * 31536000 + + ((t->tm_year - 69) / 4) * 86400 + - ((t->tm_year - 1) / 100) * 86400 + + ((t->tm_year + 299) / 400) * 86400); +#endif +} + +static const char * +build_pathname(struct archive_string *as, struct file_info *file, int depth) +{ + // Plain ISO9660 only allows 8 dir levels; if we get + // to 1000, then something is very, very wrong. + if (depth > 1000) { + return NULL; + } + if (file->parent != NULL && archive_strlen(&file->parent->name) > 0) { + if (build_pathname(as, file->parent, depth + 1) == NULL) { + return NULL; + } + archive_strcat(as, "/"); + } + if (archive_strlen(&file->name) == 0) + archive_strcat(as, "."); + else + archive_string_concat(as, &file->name); + return (as->s); +} + +static int +build_pathname_utf16be(unsigned char *p, size_t max, size_t *len, + struct file_info *file) +{ + if (file->parent != NULL && file->parent->utf16be_bytes > 0) { + if (build_pathname_utf16be(p, max, len, file->parent) != 0) + return (-1); + p[*len] = 0; + p[*len + 1] = '/'; + *len += 2; + } + if (file->utf16be_bytes == 0) { + if (*len + 2 > max) + return (-1);/* Path is too long! */ + p[*len] = 0; + p[*len + 1] = '.'; + *len += 2; + } else { + if (*len + file->utf16be_bytes > max) + return (-1);/* Path is too long! */ + memcpy(p + *len, file->utf16be_name, file->utf16be_bytes); + *len += file->utf16be_bytes; + } + return (0); +} + +#if DEBUG +static void +dump_isodirrec(FILE *out, const unsigned char *isodirrec) +{ + fprintf(out, " l %d,", + toi(isodirrec + DR_length_offset, DR_length_size)); + fprintf(out, " a %d,", + toi(isodirrec + DR_ext_attr_length_offset, DR_ext_attr_length_size)); + fprintf(out, " ext 0x%x,", + toi(isodirrec + DR_extent_offset, DR_extent_size)); + fprintf(out, " s %d,", + toi(isodirrec + DR_size_offset, DR_extent_size)); + fprintf(out, " f 0x%x,", + toi(isodirrec + DR_flags_offset, DR_flags_size)); + fprintf(out, " u %d,", + toi(isodirrec + DR_file_unit_size_offset, DR_file_unit_size_size)); + fprintf(out, " ilv %d,", + toi(isodirrec + DR_interleave_offset, DR_interleave_size)); + fprintf(out, " seq %d,", + toi(isodirrec + DR_volume_sequence_number_offset, + DR_volume_sequence_number_size)); + fprintf(out, " nl %d:", + toi(isodirrec + DR_name_len_offset, DR_name_len_size)); + fprintf(out, " `%.*s'", + toi(isodirrec + DR_name_len_offset, DR_name_len_size), + isodirrec + DR_name_offset); +} +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_lha.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_lha.c new file mode 100644 index 0000000000..bff0f01f41 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_lha.c @@ -0,0 +1,2912 @@ +/*- + * Copyright (c) 2008-2014 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_read_private.h" +#include "archive_endian.h" + + +#define MAXMATCH 256 /* Maximum match length. */ +#define MINMATCH 3 /* Minimum match length. */ +/* + * Literal table format: + * +0 +256 +510 + * +---------------+-------------------------+ + * | literal code | match length | + * | 0 ... 255 | MINMATCH ... MAXMATCH | + * +---------------+-------------------------+ + * <--- LT_BITLEN_SIZE ---> + */ +/* Literal table size. */ +#define LT_BITLEN_SIZE (UCHAR_MAX + 1 + MAXMATCH - MINMATCH + 1) +/* Position table size. + * Note: this used for both position table and pre literal table.*/ +#define PT_BITLEN_SIZE (3 + 16) + +struct lzh_dec { + /* Decoding status. */ + int state; + + /* + * Window to see last 8Ki(lh5),32Ki(lh6),64Ki(lh7) bytes of decoded + * data. + */ + int w_size; + int w_mask; + /* Window buffer, which is a loop buffer. */ + unsigned char *w_buff; + /* The insert position to the window. */ + int w_pos; + /* The position where we can copy decoded code from the window. */ + int copy_pos; + /* The length how many bytes we can copy decoded code from + * the window. */ + int copy_len; + + /* + * Bit stream reader. + */ + struct lzh_br { +#define CACHE_TYPE uint64_t +#define CACHE_BITS (8 * sizeof(CACHE_TYPE)) + /* Cache buffer. */ + CACHE_TYPE cache_buffer; + /* Indicates how many bits avail in cache_buffer. */ + int cache_avail; + } br; + + /* + * Huffman coding. + */ + struct huffman { + int len_size; + int len_avail; + int len_bits; + int freq[17]; + unsigned char *bitlen; + + /* + * Use a index table. It's faster than searching a huffman + * coding tree, which is a binary tree. But a use of a large + * index table causes L1 cache read miss many times. + */ +#define HTBL_BITS 10 + int max_bits; + int shift_bits; + int tbl_bits; + int tree_used; + int tree_avail; + /* Direct access table. */ + uint16_t *tbl; + /* Binary tree table for extra bits over the direct access. */ + struct htree_t { + uint16_t left; + uint16_t right; + } *tree; + } lt, pt; + + int blocks_avail; + int pos_pt_len_size; + int pos_pt_len_bits; + int literal_pt_len_size; + int literal_pt_len_bits; + int reading_position; + int loop; + int error; +}; + +struct lzh_stream { + const unsigned char *next_in; + int avail_in; + int64_t total_in; + const unsigned char *ref_ptr; + int avail_out; + int64_t total_out; + struct lzh_dec *ds; +}; + +struct lha { + /* entry_bytes_remaining is the number of bytes we expect. */ + int64_t entry_offset; + int64_t entry_bytes_remaining; + int64_t entry_unconsumed; + uint16_t entry_crc_calculated; + + size_t header_size; /* header size */ + unsigned char level; /* header level */ + char method[3]; /* compress type */ + int64_t compsize; /* compressed data size */ + int64_t origsize; /* original file size */ + int setflag; +#define BIRTHTIME_IS_SET 1 +#define ATIME_IS_SET 2 +#define UNIX_MODE_IS_SET 4 +#define CRC_IS_SET 8 + time_t birthtime; + long birthtime_tv_nsec; + time_t mtime; + long mtime_tv_nsec; + time_t atime; + long atime_tv_nsec; + mode_t mode; + int64_t uid; + int64_t gid; + struct archive_string uname; + struct archive_string gname; + uint16_t header_crc; + uint16_t crc; + /* dirname and filename could be in different codepages */ + struct archive_string_conv *sconv_dir; + struct archive_string_conv *sconv_fname; + struct archive_string_conv *opt_sconv; + + struct archive_string dirname; + struct archive_string filename; + struct archive_wstring ws; + + unsigned char dos_attr; + + /* Flag to mark progress that an archive was read their first header.*/ + char found_first_header; + /* Flag to mark that indicates an empty directory. */ + char directory; + + /* Flags to mark progress of decompression. */ + char decompress_init; + char end_of_entry; + char end_of_entry_cleanup; + char entry_is_compressed; + + char format_name[64]; + + struct lzh_stream strm; +}; + +/* + * LHA header common member offset. + */ +#define H_METHOD_OFFSET 2 /* Compress type. */ +#define H_ATTR_OFFSET 19 /* DOS attribute. */ +#define H_LEVEL_OFFSET 20 /* Header Level. */ +#define H_SIZE 22 /* Minimum header size. */ + +static int archive_read_format_lha_bid(struct archive_read *, int); +static int archive_read_format_lha_options(struct archive_read *, + const char *, const char *); +static int archive_read_format_lha_read_header(struct archive_read *, + struct archive_entry *); +static int archive_read_format_lha_read_data(struct archive_read *, + const void **, size_t *, int64_t *); +static int archive_read_format_lha_read_data_skip(struct archive_read *); +static int archive_read_format_lha_cleanup(struct archive_read *); + +static void lha_replace_path_separator(struct lha *, + struct archive_entry *); +static int lha_read_file_header_0(struct archive_read *, struct lha *); +static int lha_read_file_header_1(struct archive_read *, struct lha *); +static int lha_read_file_header_2(struct archive_read *, struct lha *); +static int lha_read_file_header_3(struct archive_read *, struct lha *); +static int lha_read_file_extended_header(struct archive_read *, + struct lha *, uint16_t *, int, size_t, size_t *); +static size_t lha_check_header_format(const void *); +static int lha_skip_sfx(struct archive_read *); +static time_t lha_dos_time(const unsigned char *); +static time_t lha_win_time(uint64_t, long *); +static unsigned char lha_calcsum(unsigned char, const void *, + int, size_t); +static int lha_parse_linkname(struct archive_wstring *, + struct archive_wstring *); +static int lha_read_data_none(struct archive_read *, const void **, + size_t *, int64_t *); +static int lha_read_data_lzh(struct archive_read *, const void **, + size_t *, int64_t *); +static void lha_crc16_init(void); +static uint16_t lha_crc16(uint16_t, const void *, size_t); +static int lzh_decode_init(struct lzh_stream *, const char *); +static void lzh_decode_free(struct lzh_stream *); +static int lzh_decode(struct lzh_stream *, int); +static int lzh_br_fillup(struct lzh_stream *, struct lzh_br *); +static int lzh_huffman_init(struct huffman *, size_t, int); +static void lzh_huffman_free(struct huffman *); +static int lzh_read_pt_bitlen(struct lzh_stream *, int start, int end); +static int lzh_make_fake_table(struct huffman *, uint16_t); +static int lzh_make_huffman_table(struct huffman *); +static inline int lzh_decode_huffman(struct huffman *, unsigned); +static int lzh_decode_huffman_tree(struct huffman *, unsigned, int); + + +int +archive_read_support_format_lha(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct lha *lha; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_lha"); + + lha = (struct lha *)calloc(1, sizeof(*lha)); + if (lha == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate lha data"); + return (ARCHIVE_FATAL); + } + archive_string_init(&lha->ws); + + r = __archive_read_register_format(a, + lha, + "lha", + archive_read_format_lha_bid, + archive_read_format_lha_options, + archive_read_format_lha_read_header, + archive_read_format_lha_read_data, + archive_read_format_lha_read_data_skip, + NULL, + archive_read_format_lha_cleanup, + NULL, + NULL); + + if (r != ARCHIVE_OK) + free(lha); + return (ARCHIVE_OK); +} + +static size_t +lha_check_header_format(const void *h) +{ + const unsigned char *p = h; + size_t next_skip_bytes; + + switch (p[H_METHOD_OFFSET+3]) { + /* + * "-lh0-" ... "-lh7-" "-lhd-" + * "-lzs-" "-lz5-" + */ + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + case 'd': + case 's': + next_skip_bytes = 4; + + /* b0 == 0 means the end of an LHa archive file. */ + if (p[0] == 0) + break; + if (p[H_METHOD_OFFSET] != '-' || p[H_METHOD_OFFSET+1] != 'l' + || p[H_METHOD_OFFSET+4] != '-') + break; + + if (p[H_METHOD_OFFSET+2] == 'h') { + /* "-lh?-" */ + if (p[H_METHOD_OFFSET+3] == 's') + break; + if (p[H_LEVEL_OFFSET] == 0) + return (0); + if (p[H_LEVEL_OFFSET] <= 3 && p[H_ATTR_OFFSET] == 0x20) + return (0); + } + if (p[H_METHOD_OFFSET+2] == 'z') { + /* LArc extensions: -lzs-,-lz4- and -lz5- */ + if (p[H_LEVEL_OFFSET] != 0) + break; + if (p[H_METHOD_OFFSET+3] == 's' + || p[H_METHOD_OFFSET+3] == '4' + || p[H_METHOD_OFFSET+3] == '5') + return (0); + } + break; + case 'h': next_skip_bytes = 1; break; + case 'z': next_skip_bytes = 1; break; + case 'l': next_skip_bytes = 2; break; + case '-': next_skip_bytes = 3; break; + default : next_skip_bytes = 4; break; + } + + return (next_skip_bytes); +} + +static int +archive_read_format_lha_bid(struct archive_read *a, int best_bid) +{ + const char *p; + const void *buff; + ssize_t bytes_avail, offset, window; + size_t next; + + /* If there's already a better bid than we can ever + make, don't bother testing. */ + if (best_bid > 30) + return (-1); + + if ((p = __archive_read_ahead(a, H_SIZE, NULL)) == NULL) + return (-1); + + if (lha_check_header_format(p) == 0) + return (30); + + if (p[0] == 'M' && p[1] == 'Z') { + /* PE file */ + offset = 0; + window = 4096; + while (offset < (1024 * 20)) { + buff = __archive_read_ahead(a, offset + window, + &bytes_avail); + if (buff == NULL) { + /* Remaining bytes are less than window. */ + window >>= 1; + if (window < (H_SIZE + 3)) + return (0); + continue; + } + p = (const char *)buff + offset; + while (p + H_SIZE < (const char *)buff + bytes_avail) { + if ((next = lha_check_header_format(p)) == 0) + return (30); + p += next; + } + offset = p - (const char *)buff; + } + } + return (0); +} + +static int +archive_read_format_lha_options(struct archive_read *a, + const char *key, const char *val) +{ + struct lha *lha; + int ret = ARCHIVE_FAILED; + + lha = (struct lha *)(a->format->data); + if (strcmp(key, "hdrcharset") == 0) { + if (val == NULL || val[0] == 0) + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "lha: hdrcharset option needs a character-set name"); + else { + lha->opt_sconv = + archive_string_conversion_from_charset( + &a->archive, val, 0); + if (lha->opt_sconv != NULL) + ret = ARCHIVE_OK; + else + ret = ARCHIVE_FATAL; + } + return (ret); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static int +lha_skip_sfx(struct archive_read *a) +{ + const void *h; + const char *p, *q; + size_t next, skip; + ssize_t bytes, window; + + window = 4096; + for (;;) { + h = __archive_read_ahead(a, window, &bytes); + if (h == NULL) { + /* Remaining bytes are less than window. */ + window >>= 1; + if (window < (H_SIZE + 3)) + goto fatal; + continue; + } + if (bytes < H_SIZE) + goto fatal; + p = h; + q = p + bytes; + + /* + * Scan ahead until we find something that looks + * like the lha header. + */ + while (p + H_SIZE < q) { + if ((next = lha_check_header_format(p)) == 0) { + skip = p - (const char *)h; + __archive_read_consume(a, skip); + return (ARCHIVE_OK); + } + p += next; + } + skip = p - (const char *)h; + __archive_read_consume(a, skip); + } +fatal: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Couldn't find out LHa header"); + return (ARCHIVE_FATAL); +} + +static int +truncated_error(struct archive_read *a) +{ + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated LHa header"); + return (ARCHIVE_FATAL); +} + +static int +archive_read_format_lha_read_header(struct archive_read *a, + struct archive_entry *entry) +{ + struct archive_wstring linkname; + struct archive_wstring pathname; + struct lha *lha; + const unsigned char *p; + const char *signature; + int err; + struct archive_mstring conv_buffer; + const wchar_t *conv_buffer_p; + + lha_crc16_init(); + + a->archive.archive_format = ARCHIVE_FORMAT_LHA; + if (a->archive.archive_format_name == NULL) + a->archive.archive_format_name = "lha"; + + lha = (struct lha *)(a->format->data); + lha->decompress_init = 0; + lha->end_of_entry = 0; + lha->end_of_entry_cleanup = 0; + lha->entry_unconsumed = 0; + + if ((p = __archive_read_ahead(a, H_SIZE, NULL)) == NULL) { + /* + * LHa archiver added 0 to the tail of its archive file as + * the mark of the end of the archive. + */ + signature = __archive_read_ahead(a, sizeof(signature[0]), NULL); + if (signature == NULL || signature[0] == 0) + return (ARCHIVE_EOF); + return (truncated_error(a)); + } + + signature = (const char *)p; + if (lha->found_first_header == 0 && + signature[0] == 'M' && signature[1] == 'Z') { + /* This is an executable? Must be self-extracting... */ + err = lha_skip_sfx(a); + if (err < ARCHIVE_WARN) + return (err); + + if ((p = __archive_read_ahead(a, sizeof(*p), NULL)) == NULL) + return (truncated_error(a)); + signature = (const char *)p; + } + /* signature[0] == 0 means the end of an LHa archive file. */ + if (signature[0] == 0) + return (ARCHIVE_EOF); + + /* + * Check the header format and method type. + */ + if (lha_check_header_format(p) != 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Bad LHa file"); + return (ARCHIVE_FATAL); + } + + /* We've found the first header. */ + lha->found_first_header = 1; + /* Set a default value and common data */ + lha->header_size = 0; + lha->level = p[H_LEVEL_OFFSET]; + lha->method[0] = p[H_METHOD_OFFSET+1]; + lha->method[1] = p[H_METHOD_OFFSET+2]; + lha->method[2] = p[H_METHOD_OFFSET+3]; + if (memcmp(lha->method, "lhd", 3) == 0) + lha->directory = 1; + else + lha->directory = 0; + if (memcmp(lha->method, "lh0", 3) == 0 || + memcmp(lha->method, "lz4", 3) == 0) + lha->entry_is_compressed = 0; + else + lha->entry_is_compressed = 1; + + lha->compsize = 0; + lha->origsize = 0; + lha->setflag = 0; + lha->birthtime = 0; + lha->birthtime_tv_nsec = 0; + lha->mtime = 0; + lha->mtime_tv_nsec = 0; + lha->atime = 0; + lha->atime_tv_nsec = 0; + lha->mode = (lha->directory)? 0777 : 0666; + lha->uid = 0; + lha->gid = 0; + archive_string_empty(&lha->dirname); + archive_string_empty(&lha->filename); + lha->dos_attr = 0; + if (lha->opt_sconv != NULL) { + lha->sconv_dir = lha->opt_sconv; + lha->sconv_fname = lha->opt_sconv; + } else { + lha->sconv_dir = NULL; + lha->sconv_fname = NULL; + } + + switch (p[H_LEVEL_OFFSET]) { + case 0: + err = lha_read_file_header_0(a, lha); + break; + case 1: + err = lha_read_file_header_1(a, lha); + break; + case 2: + err = lha_read_file_header_2(a, lha); + break; + case 3: + err = lha_read_file_header_3(a, lha); + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Unsupported LHa header level %d", p[H_LEVEL_OFFSET]); + err = ARCHIVE_FATAL; + break; + } + if (err < ARCHIVE_WARN) + return (err); + + + if (!lha->directory && archive_strlen(&lha->filename) == 0) + /* The filename has not been set */ + return (truncated_error(a)); + + /* + * Make a pathname from a dirname and a filename, after converting to Unicode. + * This is because codepages might differ between dirname and filename. + */ + archive_string_init(&pathname); + archive_string_init(&linkname); + archive_string_init(&conv_buffer.aes_mbs); + archive_string_init(&conv_buffer.aes_mbs_in_locale); + archive_string_init(&conv_buffer.aes_utf8); + archive_string_init(&conv_buffer.aes_wcs); + if (0 != archive_mstring_copy_mbs_len_l(&conv_buffer, lha->dirname.s, lha->dirname.length, lha->sconv_dir)) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Pathname cannot be converted " + "from %s to Unicode.", + archive_string_conversion_charset_name(lha->sconv_dir)); + err = ARCHIVE_FATAL; + } else if (0 != archive_mstring_get_wcs(&a->archive, &conv_buffer, &conv_buffer_p)) + err = ARCHIVE_FATAL; + if (err == ARCHIVE_FATAL) { + archive_mstring_clean(&conv_buffer); + archive_wstring_free(&pathname); + archive_wstring_free(&linkname); + return (err); + } + archive_wstring_copy(&pathname, &conv_buffer.aes_wcs); + + archive_string_empty(&conv_buffer.aes_mbs); + archive_string_empty(&conv_buffer.aes_mbs_in_locale); + archive_string_empty(&conv_buffer.aes_utf8); + archive_wstring_empty(&conv_buffer.aes_wcs); + if (0 != archive_mstring_copy_mbs_len_l(&conv_buffer, lha->filename.s, lha->filename.length, lha->sconv_fname)) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Pathname cannot be converted " + "from %s to Unicode.", + archive_string_conversion_charset_name(lha->sconv_fname)); + err = ARCHIVE_FATAL; + } + else if (0 != archive_mstring_get_wcs(&a->archive, &conv_buffer, &conv_buffer_p)) + err = ARCHIVE_FATAL; + if (err == ARCHIVE_FATAL) { + archive_mstring_clean(&conv_buffer); + archive_wstring_free(&pathname); + archive_wstring_free(&linkname); + return (err); + } + archive_wstring_concat(&pathname, &conv_buffer.aes_wcs); + archive_mstring_clean(&conv_buffer); + + if ((lha->mode & AE_IFMT) == AE_IFLNK) { + /* + * Extract the symlink-name if it's included in the pathname. + */ + if (!lha_parse_linkname(&linkname, &pathname)) { + /* We couldn't get the symlink-name. */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Unknown symlink-name"); + archive_wstring_free(&pathname); + archive_wstring_free(&linkname); + return (ARCHIVE_FAILED); + } + } else { + /* + * Make sure a file-type is set. + * The mode has been overridden if it is in the extended data. + */ + lha->mode = (lha->mode & ~AE_IFMT) | + ((lha->directory)? AE_IFDIR: AE_IFREG); + } + if ((lha->setflag & UNIX_MODE_IS_SET) == 0 && + (lha->dos_attr & 1) != 0) + lha->mode &= ~(0222);/* read only. */ + + /* + * Set basic file parameters. + */ + archive_entry_copy_pathname_w(entry, pathname.s); + archive_wstring_free(&pathname); + if (archive_strlen(&linkname) > 0) { + archive_entry_copy_symlink_w(entry, linkname.s); + } else + archive_entry_set_symlink(entry, NULL); + archive_wstring_free(&linkname); + /* + * When a header level is 0, there is a possibility that + * a pathname and a symlink has '\' character, a directory + * separator in DOS/Windows. So we should convert it to '/'. + */ + if (p[H_LEVEL_OFFSET] == 0) + lha_replace_path_separator(lha, entry); + + archive_entry_set_mode(entry, lha->mode); + archive_entry_set_uid(entry, lha->uid); + archive_entry_set_gid(entry, lha->gid); + if (archive_strlen(&lha->uname) > 0) + archive_entry_set_uname(entry, lha->uname.s); + if (archive_strlen(&lha->gname) > 0) + archive_entry_set_gname(entry, lha->gname.s); + if (lha->setflag & BIRTHTIME_IS_SET) { + archive_entry_set_birthtime(entry, lha->birthtime, + lha->birthtime_tv_nsec); + archive_entry_set_ctime(entry, lha->birthtime, + lha->birthtime_tv_nsec); + } else { + archive_entry_unset_birthtime(entry); + archive_entry_unset_ctime(entry); + } + archive_entry_set_mtime(entry, lha->mtime, lha->mtime_tv_nsec); + if (lha->setflag & ATIME_IS_SET) + archive_entry_set_atime(entry, lha->atime, + lha->atime_tv_nsec); + else + archive_entry_unset_atime(entry); + if (lha->directory || archive_entry_symlink(entry) != NULL) + archive_entry_unset_size(entry); + else + archive_entry_set_size(entry, lha->origsize); + + /* + * Prepare variables used to read a file content. + */ + lha->entry_bytes_remaining = lha->compsize; + if (lha->entry_bytes_remaining < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid LHa entry size"); + return (ARCHIVE_FATAL); + } + lha->entry_offset = 0; + lha->entry_crc_calculated = 0; + + /* + * This file does not have a content. + */ + if (lha->directory || lha->compsize == 0) + lha->end_of_entry = 1; + + sprintf(lha->format_name, "lha -%c%c%c-", + lha->method[0], lha->method[1], lha->method[2]); + a->archive.archive_format_name = lha->format_name; + + return (err); +} + +/* + * Replace a DOS path separator '\' by a character '/'. + * Some multi-byte character set have a character '\' in its second byte. + */ +static void +lha_replace_path_separator(struct lha *lha, struct archive_entry *entry) +{ + const wchar_t *wp; + size_t i; + + if ((wp = archive_entry_pathname_w(entry)) != NULL) { + archive_wstrcpy(&(lha->ws), wp); + for (i = 0; i < archive_strlen(&(lha->ws)); i++) { + if (lha->ws.s[i] == L'\\') + lha->ws.s[i] = L'/'; + } + archive_entry_copy_pathname_w(entry, lha->ws.s); + } + + if ((wp = archive_entry_symlink_w(entry)) != NULL) { + archive_wstrcpy(&(lha->ws), wp); + for (i = 0; i < archive_strlen(&(lha->ws)); i++) { + if (lha->ws.s[i] == L'\\') + lha->ws.s[i] = L'/'; + } + archive_entry_copy_symlink_w(entry, lha->ws.s); + } +} + +/* + * Header 0 format + * + * +0 +1 +2 +7 +11 + * +---------------+----------+----------------+-------------------+ + * |header size(*1)|header sum|compression type|compressed size(*2)| + * +---------------+----------+----------------+-------------------+ + * <---------------------(*1)----------* + * + * +11 +15 +17 +19 +20 +21 + * +-----------------+---------+---------+--------------+----------------+ + * |uncompressed size|time(DOS)|date(DOS)|attribute(DOS)|header level(=0)| + * +-----------------+---------+---------+--------------+----------------+ + * *--------------------------------(*1)---------------------------------* + * + * +21 +22 +22+(*3) +22+(*3)+2 +22+(*3)+2+(*4) + * +---------------+---------+----------+----------------+------------------+ + * |name length(*3)|file name|file CRC16|extra header(*4)| compressed data | + * +---------------+---------+----------+----------------+------------------+ + * <--(*3)-> <------(*2)------> + * *----------------------(*1)--------------------------> + * + */ +#define H0_HEADER_SIZE_OFFSET 0 +#define H0_HEADER_SUM_OFFSET 1 +#define H0_COMP_SIZE_OFFSET 7 +#define H0_ORIG_SIZE_OFFSET 11 +#define H0_DOS_TIME_OFFSET 15 +#define H0_NAME_LEN_OFFSET 21 +#define H0_FILE_NAME_OFFSET 22 +#define H0_FIXED_SIZE 24 +static int +lha_read_file_header_0(struct archive_read *a, struct lha *lha) +{ + const unsigned char *p; + int extdsize, namelen; + unsigned char headersum, sum_calculated; + + if ((p = __archive_read_ahead(a, H0_FIXED_SIZE, NULL)) == NULL) + return (truncated_error(a)); + lha->header_size = p[H0_HEADER_SIZE_OFFSET] + 2; + headersum = p[H0_HEADER_SUM_OFFSET]; + lha->compsize = archive_le32dec(p + H0_COMP_SIZE_OFFSET); + lha->origsize = archive_le32dec(p + H0_ORIG_SIZE_OFFSET); + lha->mtime = lha_dos_time(p + H0_DOS_TIME_OFFSET); + namelen = p[H0_NAME_LEN_OFFSET]; + extdsize = (int)lha->header_size - H0_FIXED_SIZE - namelen; + if ((namelen > 221 || extdsize < 0) && extdsize != -2) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid LHa header"); + return (ARCHIVE_FATAL); + } + if ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL) + return (truncated_error(a)); + + archive_strncpy(&lha->filename, p + H0_FILE_NAME_OFFSET, namelen); + /* When extdsize == -2, A CRC16 value is not present in the header. */ + if (extdsize >= 0) { + lha->crc = archive_le16dec(p + H0_FILE_NAME_OFFSET + namelen); + lha->setflag |= CRC_IS_SET; + } + sum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2); + + /* Read an extended header */ + if (extdsize > 0) { + /* This extended data is set by 'LHa for UNIX' only. + * Maybe fixed size. + */ + p += H0_FILE_NAME_OFFSET + namelen + 2; + if (p[0] == 'U' && extdsize == 12) { + /* p[1] is a minor version. */ + lha->mtime = archive_le32dec(&p[2]); + lha->mode = archive_le16dec(&p[6]); + lha->uid = archive_le16dec(&p[8]); + lha->gid = archive_le16dec(&p[10]); + lha->setflag |= UNIX_MODE_IS_SET; + } + } + __archive_read_consume(a, lha->header_size); + + if (sum_calculated != headersum) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "LHa header sum error"); + return (ARCHIVE_FATAL); + } + + return (ARCHIVE_OK); +} + +/* + * Header 1 format + * + * +0 +1 +2 +7 +11 + * +---------------+----------+----------------+-------------+ + * |header size(*1)|header sum|compression type|skip size(*2)| + * +---------------+----------+----------------+-------------+ + * <---------------(*1)----------* + * + * +11 +15 +17 +19 +20 +21 + * +-----------------+---------+---------+--------------+----------------+ + * |uncompressed size|time(DOS)|date(DOS)|attribute(DOS)|header level(=1)| + * +-----------------+---------+---------+--------------+----------------+ + * *-------------------------------(*1)----------------------------------* + * + * +21 +22 +22+(*3) +22+(*3)+2 +22+(*3)+3 +22+(*3)+3+(*4) + * +---------------+---------+----------+-----------+-----------+ + * |name length(*3)|file name|file CRC16| creator |padding(*4)| + * +---------------+---------+----------+-----------+-----------+ + * <--(*3)-> + * *----------------------------(*1)----------------------------* + * + * +22+(*3)+3+(*4) +22+(*3)+3+(*4)+2 +22+(*3)+3+(*4)+2+(*5) + * +----------------+---------------------+------------------------+ + * |next header size| extended header(*5) | compressed data | + * +----------------+---------------------+------------------------+ + * *------(*1)-----> <--------------------(*2)--------------------> + */ +#define H1_HEADER_SIZE_OFFSET 0 +#define H1_HEADER_SUM_OFFSET 1 +#define H1_COMP_SIZE_OFFSET 7 +#define H1_ORIG_SIZE_OFFSET 11 +#define H1_DOS_TIME_OFFSET 15 +#define H1_NAME_LEN_OFFSET 21 +#define H1_FILE_NAME_OFFSET 22 +#define H1_FIXED_SIZE 27 +static int +lha_read_file_header_1(struct archive_read *a, struct lha *lha) +{ + const unsigned char *p; + size_t extdsize; + int i, err, err2; + int namelen, padding; + unsigned char headersum, sum_calculated; + + err = ARCHIVE_OK; + + if ((p = __archive_read_ahead(a, H1_FIXED_SIZE, NULL)) == NULL) + return (truncated_error(a)); + + lha->header_size = p[H1_HEADER_SIZE_OFFSET] + 2; + headersum = p[H1_HEADER_SUM_OFFSET]; + /* Note: An extended header size is included in a compsize. */ + lha->compsize = archive_le32dec(p + H1_COMP_SIZE_OFFSET); + lha->origsize = archive_le32dec(p + H1_ORIG_SIZE_OFFSET); + lha->mtime = lha_dos_time(p + H1_DOS_TIME_OFFSET); + namelen = p[H1_NAME_LEN_OFFSET]; + /* Calculate a padding size. The result will be normally 0 only(?) */ + padding = ((int)lha->header_size) - H1_FIXED_SIZE - namelen; + + if (namelen > 230 || padding < 0) + goto invalid; + + if ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL) + return (truncated_error(a)); + + for (i = 0; i < namelen; i++) { + if (p[i + H1_FILE_NAME_OFFSET] == 0xff) + goto invalid;/* Invalid filename. */ + } + archive_strncpy(&lha->filename, p + H1_FILE_NAME_OFFSET, namelen); + lha->crc = archive_le16dec(p + H1_FILE_NAME_OFFSET + namelen); + lha->setflag |= CRC_IS_SET; + + sum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2); + /* Consume used bytes but not include `next header size' data + * since it will be consumed in lha_read_file_extended_header(). */ + __archive_read_consume(a, lha->header_size - 2); + + /* Read extended headers */ + err2 = lha_read_file_extended_header(a, lha, NULL, 2, + (size_t)(lha->compsize + 2), &extdsize); + if (err2 < ARCHIVE_WARN) + return (err2); + if (err2 < err) + err = err2; + /* Get a real compressed file size. */ + lha->compsize -= extdsize - 2; + + if (lha->compsize < 0) + goto invalid; /* Invalid compressed file size */ + + if (sum_calculated != headersum) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "LHa header sum error"); + return (ARCHIVE_FATAL); + } + return (err); +invalid: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid LHa header"); + return (ARCHIVE_FATAL); +} + +/* + * Header 2 format + * + * +0 +2 +7 +11 +15 + * +---------------+----------------+-------------------+-----------------+ + * |header size(*1)|compression type|compressed size(*2)|uncompressed size| + * +---------------+----------------+-------------------+-----------------+ + * <--------------------------------(*1)---------------------------------* + * + * +15 +19 +20 +21 +23 +24 + * +-----------------+------------+----------------+----------+-----------+ + * |data/time(time_t)| 0x20 fixed |header level(=2)|file CRC16| creator | + * +-----------------+------------+----------------+----------+-----------+ + * *---------------------------------(*1)---------------------------------* + * + * +24 +26 +26+(*3) +26+(*3)+(*4) + * +----------------+-------------------+-------------+-------------------+ + * |next header size|extended header(*3)| padding(*4) | compressed data | + * +----------------+-------------------+-------------+-------------------+ + * *--------------------------(*1)-------------------> <------(*2)-------> + * + */ +#define H2_HEADER_SIZE_OFFSET 0 +#define H2_COMP_SIZE_OFFSET 7 +#define H2_ORIG_SIZE_OFFSET 11 +#define H2_TIME_OFFSET 15 +#define H2_CRC_OFFSET 21 +#define H2_FIXED_SIZE 24 +static int +lha_read_file_header_2(struct archive_read *a, struct lha *lha) +{ + const unsigned char *p; + size_t extdsize; + int err, padding; + uint16_t header_crc; + + if ((p = __archive_read_ahead(a, H2_FIXED_SIZE, NULL)) == NULL) + return (truncated_error(a)); + + lha->header_size =archive_le16dec(p + H2_HEADER_SIZE_OFFSET); + lha->compsize = archive_le32dec(p + H2_COMP_SIZE_OFFSET); + lha->origsize = archive_le32dec(p + H2_ORIG_SIZE_OFFSET); + lha->mtime = archive_le32dec(p + H2_TIME_OFFSET); + lha->crc = archive_le16dec(p + H2_CRC_OFFSET); + lha->setflag |= CRC_IS_SET; + + if (lha->header_size < H2_FIXED_SIZE) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid LHa header size"); + return (ARCHIVE_FATAL); + } + + header_crc = lha_crc16(0, p, H2_FIXED_SIZE); + __archive_read_consume(a, H2_FIXED_SIZE); + + /* Read extended headers */ + err = lha_read_file_extended_header(a, lha, &header_crc, 2, + lha->header_size - H2_FIXED_SIZE, &extdsize); + if (err < ARCHIVE_WARN) + return (err); + + /* Calculate a padding size. The result will be normally 0 or 1. */ + padding = (int)lha->header_size - (int)(H2_FIXED_SIZE + extdsize); + if (padding > 0) { + if ((p = __archive_read_ahead(a, padding, NULL)) == NULL) + return (truncated_error(a)); + header_crc = lha_crc16(header_crc, p, padding); + __archive_read_consume(a, padding); + } + + if (header_crc != lha->header_crc) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "LHa header CRC error"); + return (ARCHIVE_FATAL); + } + return (err); +} + +/* + * Header 3 format + * + * +0 +2 +7 +11 +15 + * +------------+----------------+-------------------+-----------------+ + * | 0x04 fixed |compression type|compressed size(*2)|uncompressed size| + * +------------+----------------+-------------------+-----------------+ + * <-------------------------------(*1)-------------------------------* + * + * +15 +19 +20 +21 +23 +24 + * +-----------------+------------+----------------+----------+-----------+ + * |date/time(time_t)| 0x20 fixed |header level(=3)|file CRC16| creator | + * +-----------------+------------+----------------+----------+-----------+ + * *--------------------------------(*1)----------------------------------* + * + * +24 +28 +32 +32+(*3) + * +---------------+----------------+-------------------+-----------------+ + * |header size(*1)|next header size|extended header(*3)| compressed data | + * +---------------+----------------+-------------------+-----------------+ + * *------------------------(*1)-----------------------> <------(*2)-----> + * + */ +#define H3_FIELD_LEN_OFFSET 0 +#define H3_COMP_SIZE_OFFSET 7 +#define H3_ORIG_SIZE_OFFSET 11 +#define H3_TIME_OFFSET 15 +#define H3_CRC_OFFSET 21 +#define H3_HEADER_SIZE_OFFSET 24 +#define H3_FIXED_SIZE 28 +static int +lha_read_file_header_3(struct archive_read *a, struct lha *lha) +{ + const unsigned char *p; + size_t extdsize; + int err; + uint16_t header_crc; + + if ((p = __archive_read_ahead(a, H3_FIXED_SIZE, NULL)) == NULL) + return (truncated_error(a)); + + if (archive_le16dec(p + H3_FIELD_LEN_OFFSET) != 4) + goto invalid; + lha->header_size =archive_le32dec(p + H3_HEADER_SIZE_OFFSET); + lha->compsize = archive_le32dec(p + H3_COMP_SIZE_OFFSET); + lha->origsize = archive_le32dec(p + H3_ORIG_SIZE_OFFSET); + lha->mtime = archive_le32dec(p + H3_TIME_OFFSET); + lha->crc = archive_le16dec(p + H3_CRC_OFFSET); + lha->setflag |= CRC_IS_SET; + + if (lha->header_size < H3_FIXED_SIZE + 4) + goto invalid; + header_crc = lha_crc16(0, p, H3_FIXED_SIZE); + __archive_read_consume(a, H3_FIXED_SIZE); + + /* Read extended headers */ + err = lha_read_file_extended_header(a, lha, &header_crc, 4, + lha->header_size - H3_FIXED_SIZE, &extdsize); + if (err < ARCHIVE_WARN) + return (err); + + if (header_crc != lha->header_crc) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "LHa header CRC error"); + return (ARCHIVE_FATAL); + } + return (err); +invalid: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid LHa header"); + return (ARCHIVE_FATAL); +} + +/* + * Extended header format + * + * +0 +2 +3 -- used in header 1 and 2 + * +0 +4 +5 -- used in header 3 + * +--------------+---------+-------------------+--------------+-- + * |ex-header size|header id| data |ex-header size| ....... + * +--------------+---------+-------------------+--------------+-- + * <-------------( ex-header size)------------> <-- next extended header --* + * + * If the ex-header size is zero, it is the make of the end of extended + * headers. + * + */ +static int +lha_read_file_extended_header(struct archive_read *a, struct lha *lha, + uint16_t *crc, int sizefield_length, size_t limitsize, size_t *total_size) +{ + const void *h; + const unsigned char *extdheader; + size_t extdsize; + size_t datasize; + unsigned int i; + unsigned char extdtype; + +#define EXT_HEADER_CRC 0x00 /* Header CRC and information*/ +#define EXT_FILENAME 0x01 /* Filename */ +#define EXT_DIRECTORY 0x02 /* Directory name */ +#define EXT_DOS_ATTR 0x40 /* MS-DOS attribute */ +#define EXT_TIMESTAMP 0x41 /* Windows time stamp */ +#define EXT_FILESIZE 0x42 /* Large file size */ +#define EXT_TIMEZONE 0x43 /* Time zone */ +#define EXT_UTF16_FILENAME 0x44 /* UTF-16 filename */ +#define EXT_UTF16_DIRECTORY 0x45 /* UTF-16 directory name */ +#define EXT_CODEPAGE 0x46 /* Codepage */ +#define EXT_UNIX_MODE 0x50 /* File permission */ +#define EXT_UNIX_GID_UID 0x51 /* gid,uid */ +#define EXT_UNIX_GNAME 0x52 /* Group name */ +#define EXT_UNIX_UNAME 0x53 /* User name */ +#define EXT_UNIX_MTIME 0x54 /* Modified time */ +#define EXT_OS2_NEW_ATTR 0x7f /* new attribute(OS/2 only) */ +#define EXT_NEW_ATTR 0xff /* new attribute */ + + *total_size = sizefield_length; + + for (;;) { + /* Read an extended header size. */ + if ((h = + __archive_read_ahead(a, sizefield_length, NULL)) == NULL) + return (truncated_error(a)); + /* Check if the size is the zero indicates the end of the + * extended header. */ + if (sizefield_length == sizeof(uint16_t)) + extdsize = archive_le16dec(h); + else + extdsize = archive_le32dec(h); + if (extdsize == 0) { + /* End of extended header */ + if (crc != NULL) + *crc = lha_crc16(*crc, h, sizefield_length); + __archive_read_consume(a, sizefield_length); + return (ARCHIVE_OK); + } + + /* Sanity check to the extended header size. */ + if (((uint64_t)*total_size + extdsize) > + (uint64_t)limitsize || + extdsize <= (size_t)sizefield_length) + goto invalid; + + /* Read the extended header. */ + if ((h = __archive_read_ahead(a, extdsize, NULL)) == NULL) + return (truncated_error(a)); + *total_size += extdsize; + + extdheader = (const unsigned char *)h; + /* Get the extended header type. */ + extdtype = extdheader[sizefield_length]; + /* Calculate an extended data size. */ + datasize = extdsize - (1 + sizefield_length); + /* Skip an extended header size field and type field. */ + extdheader += sizefield_length + 1; + + if (crc != NULL && extdtype != EXT_HEADER_CRC) + *crc = lha_crc16(*crc, h, extdsize); + switch (extdtype) { + case EXT_HEADER_CRC: + /* We only use a header CRC. Following data will not + * be used. */ + if (datasize >= 2) { + lha->header_crc = archive_le16dec(extdheader); + if (crc != NULL) { + static const char zeros[2] = {0, 0}; + *crc = lha_crc16(*crc, h, + extdsize - datasize); + /* CRC value itself as zero */ + *crc = lha_crc16(*crc, zeros, 2); + *crc = lha_crc16(*crc, + extdheader+2, datasize - 2); + } + } + break; + case EXT_FILENAME: + if (datasize == 0) { + /* maybe directory header */ + archive_string_empty(&lha->filename); + break; + } + if (extdheader[0] == '\0') + goto invalid; + archive_strncpy(&lha->filename, + (const char *)extdheader, datasize); + break; + case EXT_UTF16_FILENAME: + if (datasize == 0) { + /* maybe directory header */ + archive_string_empty(&lha->filename); + break; + } else if (datasize & 1) { + /* UTF-16 characters take always 2 or 4 bytes */ + goto invalid; + } + if (extdheader[0] == '\0') + goto invalid; + archive_string_empty(&lha->filename); + archive_array_append(&lha->filename, + (const char *)extdheader, datasize); + /* Setup a string conversion for a filename. */ + lha->sconv_fname = + archive_string_conversion_from_charset(&a->archive, + "UTF-16LE", 1); + if (lha->sconv_fname == NULL) + return (ARCHIVE_FATAL); + break; + case EXT_DIRECTORY: + if (datasize == 0 || extdheader[0] == '\0') + /* no directory name data. exit this case. */ + goto invalid; + + archive_strncpy(&lha->dirname, + (const char *)extdheader, datasize); + /* + * Convert directory delimiter from 0xFF + * to '/' for local system. + */ + for (i = 0; i < lha->dirname.length; i++) { + if ((unsigned char)lha->dirname.s[i] == 0xFF) + lha->dirname.s[i] = '/'; + } + /* Is last character directory separator? */ + if (lha->dirname.s[lha->dirname.length-1] != '/') + /* invalid directory data */ + goto invalid; + break; + case EXT_UTF16_DIRECTORY: + /* UTF-16 characters take always 2 or 4 bytes */ + if (datasize == 0 || (datasize & 1) || + extdheader[0] == '\0') { + /* no directory name data. exit this case. */ + goto invalid; + } + + archive_string_empty(&lha->dirname); + archive_array_append(&lha->dirname, + (const char *)extdheader, datasize); + lha->sconv_dir = + archive_string_conversion_from_charset(&a->archive, + "UTF-16LE", 1); + if (lha->sconv_dir == NULL) + return (ARCHIVE_FATAL); + else { + /* + * Convert directory delimiter from 0xFFFF + * to '/' for local system. + */ + uint16_t dirSep; + uint16_t d = 1; + if (archive_be16dec(&d) == 1) + dirSep = 0x2F00; + else + dirSep = 0x002F; + + /* UTF-16LE character */ + uint16_t *utf16name = + (uint16_t *)lha->dirname.s; + for (i = 0; i < lha->dirname.length / 2; i++) { + if (utf16name[i] == 0xFFFF) { + utf16name[i] = dirSep; + } + } + /* Is last character directory separator? */ + if (utf16name[lha->dirname.length / 2 - 1] != + dirSep) { + /* invalid directory data */ + goto invalid; + } + } + break; + case EXT_DOS_ATTR: + if (datasize == 2) + lha->dos_attr = (unsigned char) + (archive_le16dec(extdheader) & 0xff); + break; + case EXT_TIMESTAMP: + if (datasize == (sizeof(uint64_t) * 3)) { + lha->birthtime = lha_win_time( + archive_le64dec(extdheader), + &lha->birthtime_tv_nsec); + extdheader += sizeof(uint64_t); + lha->mtime = lha_win_time( + archive_le64dec(extdheader), + &lha->mtime_tv_nsec); + extdheader += sizeof(uint64_t); + lha->atime = lha_win_time( + archive_le64dec(extdheader), + &lha->atime_tv_nsec); + lha->setflag |= BIRTHTIME_IS_SET | + ATIME_IS_SET; + } + break; + case EXT_FILESIZE: + if (datasize == sizeof(uint64_t) * 2) { + lha->compsize = archive_le64dec(extdheader); + extdheader += sizeof(uint64_t); + lha->origsize = archive_le64dec(extdheader); + } + break; + case EXT_CODEPAGE: + /* Get an archived filename charset from codepage. + * This overwrites the charset specified by + * hdrcharset option. */ + if (datasize == sizeof(uint32_t)) { + struct archive_string cp; + const char *charset; + + archive_string_init(&cp); + switch (archive_le32dec(extdheader)) { + case 65001: /* UTF-8 */ + charset = "UTF-8"; + break; + default: + archive_string_sprintf(&cp, "CP%d", + (int)archive_le32dec(extdheader)); + charset = cp.s; + break; + } + lha->sconv_dir = + archive_string_conversion_from_charset( + &(a->archive), charset, 1); + lha->sconv_fname = + archive_string_conversion_from_charset( + &(a->archive), charset, 1); + archive_string_free(&cp); + if (lha->sconv_dir == NULL) + return (ARCHIVE_FATAL); + if (lha->sconv_fname == NULL) + return (ARCHIVE_FATAL); + } + break; + case EXT_UNIX_MODE: + if (datasize == sizeof(uint16_t)) { + lha->mode = archive_le16dec(extdheader); + lha->setflag |= UNIX_MODE_IS_SET; + } + break; + case EXT_UNIX_GID_UID: + if (datasize == (sizeof(uint16_t) * 2)) { + lha->gid = archive_le16dec(extdheader); + lha->uid = archive_le16dec(extdheader+2); + } + break; + case EXT_UNIX_GNAME: + if (datasize > 0) + archive_strncpy(&lha->gname, + (const char *)extdheader, datasize); + break; + case EXT_UNIX_UNAME: + if (datasize > 0) + archive_strncpy(&lha->uname, + (const char *)extdheader, datasize); + break; + case EXT_UNIX_MTIME: + if (datasize == sizeof(uint32_t)) + lha->mtime = archive_le32dec(extdheader); + break; + case EXT_OS2_NEW_ATTR: + /* This extended header is OS/2 depend. */ + if (datasize == 16) { + lha->dos_attr = (unsigned char) + (archive_le16dec(extdheader) & 0xff); + lha->mode = archive_le16dec(extdheader+2); + lha->gid = archive_le16dec(extdheader+4); + lha->uid = archive_le16dec(extdheader+6); + lha->birthtime = archive_le32dec(extdheader+8); + lha->atime = archive_le32dec(extdheader+12); + lha->setflag |= UNIX_MODE_IS_SET + | BIRTHTIME_IS_SET | ATIME_IS_SET; + } + break; + case EXT_NEW_ATTR: + if (datasize == 20) { + lha->mode = (mode_t)archive_le32dec(extdheader); + lha->gid = archive_le32dec(extdheader+4); + lha->uid = archive_le32dec(extdheader+8); + lha->birthtime = archive_le32dec(extdheader+12); + lha->atime = archive_le32dec(extdheader+16); + lha->setflag |= UNIX_MODE_IS_SET + | BIRTHTIME_IS_SET | ATIME_IS_SET; + } + break; + case EXT_TIMEZONE: /* Not supported */ + break; + default: + break; + } + + __archive_read_consume(a, extdsize); + } +invalid: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid extended LHa header"); + return (ARCHIVE_FATAL); +} + +static int +lha_end_of_entry(struct archive_read *a) +{ + struct lha *lha = (struct lha *)(a->format->data); + int r = ARCHIVE_EOF; + + if (!lha->end_of_entry_cleanup) { + if ((lha->setflag & CRC_IS_SET) && + lha->crc != lha->entry_crc_calculated) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "LHa data CRC error"); + r = ARCHIVE_WARN; + } + + /* End-of-entry cleanup done. */ + lha->end_of_entry_cleanup = 1; + } + return (r); +} + +static int +archive_read_format_lha_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + struct lha *lha = (struct lha *)(a->format->data); + int r; + + if (lha->entry_unconsumed) { + /* Consume as much as the decompressor actually used. */ + __archive_read_consume(a, lha->entry_unconsumed); + lha->entry_unconsumed = 0; + } + if (lha->end_of_entry) { + *offset = lha->entry_offset; + *size = 0; + *buff = NULL; + return (lha_end_of_entry(a)); + } + + if (lha->entry_is_compressed) + r = lha_read_data_lzh(a, buff, size, offset); + else + /* No compression. */ + r = lha_read_data_none(a, buff, size, offset); + return (r); +} + +/* + * Read a file content in no compression. + * + * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets + * lha->end_of_entry if it consumes all of the data. + */ +static int +lha_read_data_none(struct archive_read *a, const void **buff, + size_t *size, int64_t *offset) +{ + struct lha *lha = (struct lha *)(a->format->data); + ssize_t bytes_avail; + + if (lha->entry_bytes_remaining == 0) { + *buff = NULL; + *size = 0; + *offset = lha->entry_offset; + lha->end_of_entry = 1; + return (ARCHIVE_OK); + } + /* + * Note: '1' here is a performance optimization. + * Recall that the decompression layer returns a count of + * available bytes; asking for more than that forces the + * decompressor to combine reads by copying data. + */ + *buff = __archive_read_ahead(a, 1, &bytes_avail); + if (bytes_avail <= 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated LHa file data"); + return (ARCHIVE_FATAL); + } + if (bytes_avail > lha->entry_bytes_remaining) + bytes_avail = (ssize_t)lha->entry_bytes_remaining; + lha->entry_crc_calculated = + lha_crc16(lha->entry_crc_calculated, *buff, bytes_avail); + *size = bytes_avail; + *offset = lha->entry_offset; + lha->entry_offset += bytes_avail; + lha->entry_bytes_remaining -= bytes_avail; + if (lha->entry_bytes_remaining == 0) + lha->end_of_entry = 1; + lha->entry_unconsumed = bytes_avail; + return (ARCHIVE_OK); +} + +/* + * Read a file content in LZHUFF encoding. + * + * Returns ARCHIVE_OK if successful, returns ARCHIVE_WARN if compression is + * unsupported, ARCHIVE_FATAL otherwise, sets lha->end_of_entry if it consumes + * all of the data. + */ +static int +lha_read_data_lzh(struct archive_read *a, const void **buff, + size_t *size, int64_t *offset) +{ + struct lha *lha = (struct lha *)(a->format->data); + ssize_t bytes_avail; + int r; + + /* If we haven't yet read any data, initialize the decompressor. */ + if (!lha->decompress_init) { + r = lzh_decode_init(&(lha->strm), lha->method); + switch (r) { + case ARCHIVE_OK: + break; + case ARCHIVE_FAILED: + /* Unsupported compression. */ + *buff = NULL; + *size = 0; + *offset = 0; + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Unsupported lzh compression method -%c%c%c-", + lha->method[0], lha->method[1], lha->method[2]); + /* We know compressed size; just skip it. */ + archive_read_format_lha_read_data_skip(a); + return (ARCHIVE_WARN); + default: + archive_set_error(&a->archive, ENOMEM, + "Couldn't allocate memory " + "for lzh decompression"); + return (ARCHIVE_FATAL); + } + /* We've initialized decompression for this stream. */ + lha->decompress_init = 1; + lha->strm.avail_out = 0; + lha->strm.total_out = 0; + } + + /* + * Note: '1' here is a performance optimization. + * Recall that the decompression layer returns a count of + * available bytes; asking for more than that forces the + * decompressor to combine reads by copying data. + */ + lha->strm.next_in = __archive_read_ahead(a, 1, &bytes_avail); + if (bytes_avail <= 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated LHa file body"); + return (ARCHIVE_FATAL); + } + if (bytes_avail > lha->entry_bytes_remaining) + bytes_avail = (ssize_t)lha->entry_bytes_remaining; + + lha->strm.avail_in = (int)bytes_avail; + lha->strm.total_in = 0; + lha->strm.avail_out = 0; + + r = lzh_decode(&(lha->strm), bytes_avail == lha->entry_bytes_remaining); + switch (r) { + case ARCHIVE_OK: + break; + case ARCHIVE_EOF: + lha->end_of_entry = 1; + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Bad lzh data"); + return (ARCHIVE_FAILED); + } + lha->entry_unconsumed = lha->strm.total_in; + lha->entry_bytes_remaining -= lha->strm.total_in; + + if (lha->strm.avail_out) { + *offset = lha->entry_offset; + *size = lha->strm.avail_out; + *buff = lha->strm.ref_ptr; + lha->entry_crc_calculated = + lha_crc16(lha->entry_crc_calculated, *buff, *size); + lha->entry_offset += *size; + } else { + *offset = lha->entry_offset; + *size = 0; + *buff = NULL; + if (lha->end_of_entry) + return (lha_end_of_entry(a)); + } + return (ARCHIVE_OK); +} + +/* + * Skip a file content. + */ +static int +archive_read_format_lha_read_data_skip(struct archive_read *a) +{ + struct lha *lha; + int64_t bytes_skipped; + + lha = (struct lha *)(a->format->data); + + if (lha->entry_unconsumed) { + /* Consume as much as the decompressor actually used. */ + __archive_read_consume(a, lha->entry_unconsumed); + lha->entry_unconsumed = 0; + } + + /* if we've already read to end of data, we're done. */ + if (lha->end_of_entry_cleanup) + return (ARCHIVE_OK); + + /* + * If the length is at the beginning, we can skip the + * compressed data much more quickly. + */ + bytes_skipped = __archive_read_consume(a, lha->entry_bytes_remaining); + if (bytes_skipped < 0) + return (ARCHIVE_FATAL); + + /* This entry is finished and done. */ + lha->end_of_entry_cleanup = lha->end_of_entry = 1; + return (ARCHIVE_OK); +} + +static int +archive_read_format_lha_cleanup(struct archive_read *a) +{ + struct lha *lha = (struct lha *)(a->format->data); + + lzh_decode_free(&(lha->strm)); + archive_string_free(&(lha->dirname)); + archive_string_free(&(lha->filename)); + archive_string_free(&(lha->uname)); + archive_string_free(&(lha->gname)); + archive_wstring_free(&(lha->ws)); + free(lha); + (a->format->data) = NULL; + return (ARCHIVE_OK); +} + +/* + * 'LHa for UNIX' utility has archived a symbolic-link name after + * a pathname with '|' character. + * This function extracts the symbolic-link name from the pathname. + * + * example. + * 1. a symbolic-name is 'aaa/bb/cc' + * 2. a filename is 'xxx/bbb' + * then a archived pathname is 'xxx/bbb|aaa/bb/cc' + */ +static int +lha_parse_linkname(struct archive_wstring *linkname, + struct archive_wstring *pathname) +{ + wchar_t * linkptr; + size_t symlen; + + linkptr = wcschr(pathname->s, L'|'); + if (linkptr != NULL) { + symlen = wcslen(linkptr + 1); + archive_wstrncpy(linkname, linkptr+1, symlen); + + *linkptr = 0; + pathname->length = wcslen(pathname->s); + + return (1); + } + return (0); +} + +/* Convert an MSDOS-style date/time into Unix-style time. */ +static time_t +lha_dos_time(const unsigned char *p) +{ + int msTime, msDate; + struct tm ts; + + msTime = archive_le16dec(p); + msDate = archive_le16dec(p+2); + + memset(&ts, 0, sizeof(ts)); + ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */ + ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */ + ts.tm_mday = msDate & 0x1f; /* Day of month. */ + ts.tm_hour = (msTime >> 11) & 0x1f; + ts.tm_min = (msTime >> 5) & 0x3f; + ts.tm_sec = (msTime << 1) & 0x3e; + ts.tm_isdst = -1; + return (mktime(&ts)); +} + +/* Convert an MS-Windows-style date/time into Unix-style time. */ +static time_t +lha_win_time(uint64_t wintime, long *ns) +{ +#define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000) + + if (wintime >= EPOC_TIME) { + wintime -= EPOC_TIME; /* 1970-01-01 00:00:00 (UTC) */ + if (ns != NULL) + *ns = (long)(wintime % 10000000) * 100; + return (wintime / 10000000); + } else { + if (ns != NULL) + *ns = 0; + return (0); + } +} + +static unsigned char +lha_calcsum(unsigned char sum, const void *pp, int offset, size_t size) +{ + unsigned char const *p = (unsigned char const *)pp; + + p += offset; + for (;size > 0; --size) + sum += *p++; + return (sum); +} + +static uint16_t crc16tbl[2][256]; +static void +lha_crc16_init(void) +{ + unsigned int i; + static int crc16init = 0; + + if (crc16init) + return; + crc16init = 1; + + for (i = 0; i < 256; i++) { + unsigned int j; + uint16_t crc = (uint16_t)i; + for (j = 8; j; j--) + crc = (crc >> 1) ^ ((crc & 1) * 0xA001); + crc16tbl[0][i] = crc; + } + + for (i = 0; i < 256; i++) { + crc16tbl[1][i] = (crc16tbl[0][i] >> 8) + ^ crc16tbl[0][crc16tbl[0][i] & 0xff]; + } +} + +static uint16_t +lha_crc16(uint16_t crc, const void *pp, size_t len) +{ + const unsigned char *p = (const unsigned char *)pp; + const uint16_t *buff; + const union { + uint32_t i; + char c[4]; + } u = { 0x01020304 }; + + if (len == 0) + return crc; + + /* Process unaligned address. */ + if (((uintptr_t)p) & (uintptr_t)0x1) { + crc = (crc >> 8) ^ crc16tbl[0][(crc ^ *p++) & 0xff]; + len--; + } + buff = (const uint16_t *)p; + /* + * Modern C compiler such as GCC does not unroll automatically yet + * without unrolling pragma, and Clang is so. So we should + * unroll this loop for its performance. + */ + for (;len >= 8; len -= 8) { + /* This if statement expects compiler optimization will + * remove the statement which will not be executed. */ +#undef bswap16 +#if defined(_MSC_VER) && _MSC_VER >= 1400 /* Visual Studio */ +# define bswap16(x) _byteswap_ushort(x) +#elif defined(__GNUC__) && ((__GNUC__ == 4 && __GNUC_MINOR__ >= 8) || __GNUC__ > 4) +/* GCC 4.8 and later has __builtin_bswap16() */ +# define bswap16(x) __builtin_bswap16(x) +#elif defined(__clang__) +/* All clang versions have __builtin_bswap16() */ +# define bswap16(x) __builtin_bswap16(x) +#else +# define bswap16(x) ((((x) >> 8) & 0xff) | ((x) << 8)) +#endif +#define CRC16W do { \ + if(u.c[0] == 1) { /* Big endian */ \ + crc ^= bswap16(*buff); buff++; \ + } else \ + crc ^= *buff++; \ + crc = crc16tbl[1][crc & 0xff] ^ crc16tbl[0][crc >> 8];\ +} while (0) + CRC16W; + CRC16W; + CRC16W; + CRC16W; +#undef CRC16W +#undef bswap16 + } + + p = (const unsigned char *)buff; + for (;len; len--) { + crc = (crc >> 8) ^ crc16tbl[0][(crc ^ *p++) & 0xff]; + } + return crc; +} + +/* + * Initialize LZHUF decoder. + * + * Returns ARCHIVE_OK if initialization was successful. + * Returns ARCHIVE_FAILED if method is unsupported. + * Returns ARCHIVE_FATAL if initialization failed; memory allocation + * error occurred. + */ +static int +lzh_decode_init(struct lzh_stream *strm, const char *method) +{ + struct lzh_dec *ds; + int w_bits, w_size; + + if (strm->ds == NULL) { + strm->ds = calloc(1, sizeof(*strm->ds)); + if (strm->ds == NULL) + return (ARCHIVE_FATAL); + } + ds = strm->ds; + ds->error = ARCHIVE_FAILED; + if (method == NULL || method[0] != 'l' || method[1] != 'h') + return (ARCHIVE_FAILED); + switch (method[2]) { + case '5': + w_bits = 13;/* 8KiB for window */ + break; + case '6': + w_bits = 15;/* 32KiB for window */ + break; + case '7': + w_bits = 16;/* 64KiB for window */ + break; + default: + return (ARCHIVE_FAILED);/* Not supported. */ + } + ds->error = ARCHIVE_FATAL; + /* Expand a window size up to 128 KiB for decompressing process + * performance whatever its original window size is. */ + ds->w_size = 1U << 17; + ds->w_mask = ds->w_size -1; + if (ds->w_buff == NULL) { + ds->w_buff = malloc(ds->w_size); + if (ds->w_buff == NULL) + return (ARCHIVE_FATAL); + } + w_size = 1U << w_bits; + memset(ds->w_buff + ds->w_size - w_size, 0x20, w_size); + ds->w_pos = 0; + ds->state = 0; + ds->pos_pt_len_size = w_bits + 1; + ds->pos_pt_len_bits = (w_bits == 15 || w_bits == 16)? 5: 4; + ds->literal_pt_len_size = PT_BITLEN_SIZE; + ds->literal_pt_len_bits = 5; + ds->br.cache_buffer = 0; + ds->br.cache_avail = 0; + + if (lzh_huffman_init(&(ds->lt), LT_BITLEN_SIZE, 16) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + ds->lt.len_bits = 9; + if (lzh_huffman_init(&(ds->pt), PT_BITLEN_SIZE, 16) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + ds->error = 0; + + return (ARCHIVE_OK); +} + +/* + * Release LZHUF decoder. + */ +static void +lzh_decode_free(struct lzh_stream *strm) +{ + + if (strm->ds == NULL) + return; + free(strm->ds->w_buff); + lzh_huffman_free(&(strm->ds->lt)); + lzh_huffman_free(&(strm->ds->pt)); + free(strm->ds); + strm->ds = NULL; +} + +/* + * Bit stream reader. + */ +/* Check that the cache buffer has enough bits. */ +#define lzh_br_has(br, n) ((br)->cache_avail >= n) +/* Get compressed data by bit. */ +#define lzh_br_bits(br, n) \ + (((uint16_t)((br)->cache_buffer >> \ + ((br)->cache_avail - (n)))) & cache_masks[n]) +#define lzh_br_bits_forced(br, n) \ + (((uint16_t)((br)->cache_buffer << \ + ((n) - (br)->cache_avail))) & cache_masks[n]) +/* Read ahead to make sure the cache buffer has enough compressed data we + * will use. + * True : completed, there is enough data in the cache buffer. + * False : we met that strm->next_in is empty, we have to get following + * bytes. */ +#define lzh_br_read_ahead_0(strm, br, n) \ + (lzh_br_has(br, (n)) || lzh_br_fillup(strm, br)) +/* True : the cache buffer has some bits as much as we need. + * False : there are no enough bits in the cache buffer to be used, + * we have to get following bytes if we could. */ +#define lzh_br_read_ahead(strm, br, n) \ + (lzh_br_read_ahead_0((strm), (br), (n)) || lzh_br_has((br), (n))) + +/* Notify how many bits we consumed. */ +#define lzh_br_consume(br, n) ((br)->cache_avail -= (n)) +#define lzh_br_unconsume(br, n) ((br)->cache_avail += (n)) + +static const uint16_t cache_masks[] = { + 0x0000, 0x0001, 0x0003, 0x0007, + 0x000F, 0x001F, 0x003F, 0x007F, + 0x00FF, 0x01FF, 0x03FF, 0x07FF, + 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, + 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF +}; + +/* + * Shift away used bits in the cache data and fill it up with following bits. + * Call this when cache buffer does not have enough bits you need. + * + * Returns 1 if the cache buffer is full. + * Returns 0 if the cache buffer is not full; input buffer is empty. + */ +static int +lzh_br_fillup(struct lzh_stream *strm, struct lzh_br *br) +{ + int n = CACHE_BITS - br->cache_avail; + + for (;;) { + const int x = n >> 3; + if (strm->avail_in >= x) { + switch (x) { + case 8: + br->cache_buffer = + ((uint64_t)strm->next_in[0]) << 56 | + ((uint64_t)strm->next_in[1]) << 48 | + ((uint64_t)strm->next_in[2]) << 40 | + ((uint64_t)strm->next_in[3]) << 32 | + ((uint32_t)strm->next_in[4]) << 24 | + ((uint32_t)strm->next_in[5]) << 16 | + ((uint32_t)strm->next_in[6]) << 8 | + (uint32_t)strm->next_in[7]; + strm->next_in += 8; + strm->avail_in -= 8; + br->cache_avail += 8 * 8; + return (1); + case 7: + br->cache_buffer = + (br->cache_buffer << 56) | + ((uint64_t)strm->next_in[0]) << 48 | + ((uint64_t)strm->next_in[1]) << 40 | + ((uint64_t)strm->next_in[2]) << 32 | + ((uint32_t)strm->next_in[3]) << 24 | + ((uint32_t)strm->next_in[4]) << 16 | + ((uint32_t)strm->next_in[5]) << 8 | + (uint32_t)strm->next_in[6]; + strm->next_in += 7; + strm->avail_in -= 7; + br->cache_avail += 7 * 8; + return (1); + case 6: + br->cache_buffer = + (br->cache_buffer << 48) | + ((uint64_t)strm->next_in[0]) << 40 | + ((uint64_t)strm->next_in[1]) << 32 | + ((uint32_t)strm->next_in[2]) << 24 | + ((uint32_t)strm->next_in[3]) << 16 | + ((uint32_t)strm->next_in[4]) << 8 | + (uint32_t)strm->next_in[5]; + strm->next_in += 6; + strm->avail_in -= 6; + br->cache_avail += 6 * 8; + return (1); + case 0: + /* We have enough compressed data in + * the cache buffer.*/ + return (1); + default: + break; + } + } + if (strm->avail_in == 0) { + /* There is not enough compressed data to fill up the + * cache buffer. */ + return (0); + } + br->cache_buffer = + (br->cache_buffer << 8) | *strm->next_in++; + strm->avail_in--; + br->cache_avail += 8; + n -= 8; + } +} + +/* + * Decode LZHUF. + * + * 1. Returns ARCHIVE_OK if output buffer or input buffer are empty. + * Please set available buffer and call this function again. + * 2. Returns ARCHIVE_EOF if decompression has been completed. + * 3. Returns ARCHIVE_FAILED if an error occurred; compressed data + * is broken or you do not set 'last' flag properly. + * 4. 'last' flag is very important, you must set 1 to the flag if there + * is no input data. The lha compressed data format does not provide how + * to know the compressed data is really finished. + * Note: lha command utility check if the total size of output bytes is + * reached the uncompressed size recorded in its header. it does not mind + * that the decoding process is properly finished. + * GNU ZIP can decompress another compressed file made by SCO LZH compress. + * it handles EOF as null to fill read buffer with zero until the decoding + * process meet 2 bytes of zeros at reading a size of a next chunk, so the + * zeros are treated as the mark of the end of the data although the zeros + * is dummy, not the file data. + */ +static int lzh_read_blocks(struct lzh_stream *, int); +static int lzh_decode_blocks(struct lzh_stream *, int); +#define ST_RD_BLOCK 0 +#define ST_RD_PT_1 1 +#define ST_RD_PT_2 2 +#define ST_RD_PT_3 3 +#define ST_RD_PT_4 4 +#define ST_RD_LITERAL_1 5 +#define ST_RD_LITERAL_2 6 +#define ST_RD_LITERAL_3 7 +#define ST_RD_POS_DATA_1 8 +#define ST_GET_LITERAL 9 +#define ST_GET_POS_1 10 +#define ST_GET_POS_2 11 +#define ST_COPY_DATA 12 + +static int +lzh_decode(struct lzh_stream *strm, int last) +{ + struct lzh_dec *ds = strm->ds; + int avail_in; + int r; + + if (ds->error) + return (ds->error); + + avail_in = strm->avail_in; + do { + if (ds->state < ST_GET_LITERAL) + r = lzh_read_blocks(strm, last); + else + r = lzh_decode_blocks(strm, last); + } while (r == 100); + strm->total_in += avail_in - strm->avail_in; + return (r); +} + +static void +lzh_emit_window(struct lzh_stream *strm, size_t s) +{ + strm->ref_ptr = strm->ds->w_buff; + strm->avail_out = (int)s; + strm->total_out += s; +} + +static int +lzh_read_blocks(struct lzh_stream *strm, int last) +{ + struct lzh_dec *ds = strm->ds; + struct lzh_br *br = &(ds->br); + int c = 0, i; + unsigned rbits; + + for (;;) { + switch (ds->state) { + case ST_RD_BLOCK: + /* + * Read a block number indicates how many blocks + * we will handle. The block is composed of a + * literal and a match, sometimes a literal only + * in particular, there are no reference data at + * the beginning of the decompression. + */ + if (!lzh_br_read_ahead_0(strm, br, 16)) { + if (!last) + /* We need following data. */ + return (ARCHIVE_OK); + if (lzh_br_has(br, 8)) { + /* + * It seems there are extra bits. + * 1. Compressed data is broken. + * 2. `last' flag does not properly + * set. + */ + goto failed; + } + if (ds->w_pos > 0) { + lzh_emit_window(strm, ds->w_pos); + ds->w_pos = 0; + return (ARCHIVE_OK); + } + /* End of compressed data; we have completely + * handled all compressed data. */ + return (ARCHIVE_EOF); + } + ds->blocks_avail = lzh_br_bits(br, 16); + if (ds->blocks_avail == 0) + goto failed; + lzh_br_consume(br, 16); + /* + * Read a literal table compressed in huffman + * coding. + */ + ds->pt.len_size = ds->literal_pt_len_size; + ds->pt.len_bits = ds->literal_pt_len_bits; + ds->reading_position = 0; + /* FALL THROUGH */ + case ST_RD_PT_1: + /* Note: ST_RD_PT_1, ST_RD_PT_2 and ST_RD_PT_4 are + * used in reading both a literal table and a + * position table. */ + if (!lzh_br_read_ahead(strm, br, ds->pt.len_bits)) { + if (last) + goto failed;/* Truncated data. */ + ds->state = ST_RD_PT_1; + return (ARCHIVE_OK); + } + ds->pt.len_avail = lzh_br_bits(br, ds->pt.len_bits); + lzh_br_consume(br, ds->pt.len_bits); + /* FALL THROUGH */ + case ST_RD_PT_2: + if (ds->pt.len_avail == 0) { + /* There is no bitlen. */ + if (!lzh_br_read_ahead(strm, br, + ds->pt.len_bits)) { + if (last) + goto failed;/* Truncated data.*/ + ds->state = ST_RD_PT_2; + return (ARCHIVE_OK); + } + if (!lzh_make_fake_table(&(ds->pt), + lzh_br_bits(br, ds->pt.len_bits))) + goto failed;/* Invalid data. */ + lzh_br_consume(br, ds->pt.len_bits); + if (ds->reading_position) + ds->state = ST_GET_LITERAL; + else + ds->state = ST_RD_LITERAL_1; + break; + } else if (ds->pt.len_avail > ds->pt.len_size) + goto failed;/* Invalid data. */ + ds->loop = 0; + memset(ds->pt.freq, 0, sizeof(ds->pt.freq)); + if (ds->pt.len_avail < 3 || + ds->pt.len_size == ds->pos_pt_len_size) { + ds->state = ST_RD_PT_4; + break; + } + /* FALL THROUGH */ + case ST_RD_PT_3: + ds->loop = lzh_read_pt_bitlen(strm, ds->loop, 3); + if (ds->loop < 3) { + if (ds->loop < 0 || last) + goto failed;/* Invalid data. */ + /* Not completed, get following data. */ + ds->state = ST_RD_PT_3; + return (ARCHIVE_OK); + } + /* There are some null in bitlen of the literal. */ + if (!lzh_br_read_ahead(strm, br, 2)) { + if (last) + goto failed;/* Truncated data. */ + ds->state = ST_RD_PT_3; + return (ARCHIVE_OK); + } + c = lzh_br_bits(br, 2); + lzh_br_consume(br, 2); + if (c > ds->pt.len_avail - 3) + goto failed;/* Invalid data. */ + for (i = 3; c-- > 0 ;) + ds->pt.bitlen[i++] = 0; + ds->loop = i; + /* FALL THROUGH */ + case ST_RD_PT_4: + ds->loop = lzh_read_pt_bitlen(strm, ds->loop, + ds->pt.len_avail); + if (ds->loop < ds->pt.len_avail) { + if (ds->loop < 0 || last) + goto failed;/* Invalid data. */ + /* Not completed, get following data. */ + ds->state = ST_RD_PT_4; + return (ARCHIVE_OK); + } + if (!lzh_make_huffman_table(&(ds->pt))) + goto failed;/* Invalid data */ + if (ds->reading_position) { + ds->state = ST_GET_LITERAL; + break; + } + /* FALL THROUGH */ + case ST_RD_LITERAL_1: + if (!lzh_br_read_ahead(strm, br, ds->lt.len_bits)) { + if (last) + goto failed;/* Truncated data. */ + ds->state = ST_RD_LITERAL_1; + return (ARCHIVE_OK); + } + ds->lt.len_avail = lzh_br_bits(br, ds->lt.len_bits); + lzh_br_consume(br, ds->lt.len_bits); + /* FALL THROUGH */ + case ST_RD_LITERAL_2: + if (ds->lt.len_avail == 0) { + /* There is no bitlen. */ + if (!lzh_br_read_ahead(strm, br, + ds->lt.len_bits)) { + if (last) + goto failed;/* Truncated data.*/ + ds->state = ST_RD_LITERAL_2; + return (ARCHIVE_OK); + } + if (!lzh_make_fake_table(&(ds->lt), + lzh_br_bits(br, ds->lt.len_bits))) + goto failed;/* Invalid data */ + lzh_br_consume(br, ds->lt.len_bits); + ds->state = ST_RD_POS_DATA_1; + break; + } else if (ds->lt.len_avail > ds->lt.len_size) + goto failed;/* Invalid data */ + ds->loop = 0; + memset(ds->lt.freq, 0, sizeof(ds->lt.freq)); + /* FALL THROUGH */ + case ST_RD_LITERAL_3: + i = ds->loop; + while (i < ds->lt.len_avail) { + if (!lzh_br_read_ahead(strm, br, + ds->pt.max_bits)) { + if (last) + goto failed;/* Truncated data.*/ + ds->loop = i; + ds->state = ST_RD_LITERAL_3; + return (ARCHIVE_OK); + } + rbits = lzh_br_bits(br, ds->pt.max_bits); + c = lzh_decode_huffman(&(ds->pt), rbits); + if (c > 2) { + /* Note: 'c' will never be more than + * eighteen since it's limited by + * PT_BITLEN_SIZE, which is being set + * to ds->pt.len_size through + * ds->literal_pt_len_size. */ + lzh_br_consume(br, ds->pt.bitlen[c]); + c -= 2; + ds->lt.freq[c]++; + ds->lt.bitlen[i++] = c; + } else if (c == 0) { + lzh_br_consume(br, ds->pt.bitlen[c]); + ds->lt.bitlen[i++] = 0; + } else { + /* c == 1 or c == 2 */ + int n = (c == 1)?4:9; + if (!lzh_br_read_ahead(strm, br, + ds->pt.bitlen[c] + n)) { + if (last) /* Truncated data. */ + goto failed; + ds->loop = i; + ds->state = ST_RD_LITERAL_3; + return (ARCHIVE_OK); + } + lzh_br_consume(br, ds->pt.bitlen[c]); + c = lzh_br_bits(br, n); + lzh_br_consume(br, n); + c += (n == 4)?3:20; + if (i + c > ds->lt.len_avail) + goto failed;/* Invalid data */ + memset(&(ds->lt.bitlen[i]), 0, c); + i += c; + } + } + if (i > ds->lt.len_avail || + !lzh_make_huffman_table(&(ds->lt))) + goto failed;/* Invalid data */ + /* FALL THROUGH */ + case ST_RD_POS_DATA_1: + /* + * Read a position table compressed in huffman + * coding. + */ + ds->pt.len_size = ds->pos_pt_len_size; + ds->pt.len_bits = ds->pos_pt_len_bits; + ds->reading_position = 1; + ds->state = ST_RD_PT_1; + break; + case ST_GET_LITERAL: + return (100); + } + } +failed: + return (ds->error = ARCHIVE_FAILED); +} + +static int +lzh_decode_blocks(struct lzh_stream *strm, int last) +{ + struct lzh_dec *ds = strm->ds; + struct lzh_br bre = ds->br; + struct huffman *lt = &(ds->lt); + struct huffman *pt = &(ds->pt); + unsigned char *w_buff = ds->w_buff; + unsigned char *lt_bitlen = lt->bitlen; + unsigned char *pt_bitlen = pt->bitlen; + int blocks_avail = ds->blocks_avail, c = 0; + int copy_len = ds->copy_len, copy_pos = ds->copy_pos; + int w_pos = ds->w_pos, w_mask = ds->w_mask, w_size = ds->w_size; + int lt_max_bits = lt->max_bits, pt_max_bits = pt->max_bits; + int state = ds->state; + + for (;;) { + switch (state) { + case ST_GET_LITERAL: + for (;;) { + if (blocks_avail == 0) { + /* We have decoded all blocks. + * Let's handle next blocks. */ + ds->state = ST_RD_BLOCK; + ds->br = bre; + ds->blocks_avail = 0; + ds->w_pos = w_pos; + ds->copy_pos = 0; + return (100); + } + + /* lzh_br_read_ahead() always try to fill the + * cache buffer up. In specific situation we + * are close to the end of the data, the cache + * buffer will not be full and thus we have to + * determine if the cache buffer has some bits + * as much as we need after lzh_br_read_ahead() + * failed. */ + if (!lzh_br_read_ahead(strm, &bre, + lt_max_bits)) { + if (!last) + goto next_data; + /* Remaining bits are less than + * maximum bits(lt.max_bits) but maybe + * it still remains as much as we need, + * so we should try to use it with + * dummy bits. */ + c = lzh_decode_huffman(lt, + lzh_br_bits_forced(&bre, + lt_max_bits)); + lzh_br_consume(&bre, lt_bitlen[c]); + if (!lzh_br_has(&bre, 0)) + goto failed;/* Over read. */ + } else { + c = lzh_decode_huffman(lt, + lzh_br_bits(&bre, lt_max_bits)); + lzh_br_consume(&bre, lt_bitlen[c]); + } + blocks_avail--; + if (c > UCHAR_MAX) + /* Current block is a match data. */ + break; + /* + * 'c' is exactly a literal code. + */ + /* Save a decoded code to reference it + * afterward. */ + w_buff[w_pos] = c; + if (++w_pos >= w_size) { + w_pos = 0; + lzh_emit_window(strm, w_size); + goto next_data; + } + } + /* 'c' is the length of a match pattern we have + * already extracted, which has be stored in + * window(ds->w_buff). */ + copy_len = c - (UCHAR_MAX + 1) + MINMATCH; + /* FALL THROUGH */ + case ST_GET_POS_1: + /* + * Get a reference position. + */ + if (!lzh_br_read_ahead(strm, &bre, pt_max_bits)) { + if (!last) { + state = ST_GET_POS_1; + ds->copy_len = copy_len; + goto next_data; + } + copy_pos = lzh_decode_huffman(pt, + lzh_br_bits_forced(&bre, pt_max_bits)); + lzh_br_consume(&bre, pt_bitlen[copy_pos]); + if (!lzh_br_has(&bre, 0)) + goto failed;/* Over read. */ + } else { + copy_pos = lzh_decode_huffman(pt, + lzh_br_bits(&bre, pt_max_bits)); + lzh_br_consume(&bre, pt_bitlen[copy_pos]); + } + /* FALL THROUGH */ + case ST_GET_POS_2: + if (copy_pos > 1) { + /* We need an additional adjustment number to + * the position. */ + int p = copy_pos - 1; + if (!lzh_br_read_ahead(strm, &bre, p)) { + if (last) + goto failed;/* Truncated data.*/ + state = ST_GET_POS_2; + ds->copy_len = copy_len; + ds->copy_pos = copy_pos; + goto next_data; + } + copy_pos = (1 << p) + lzh_br_bits(&bre, p); + lzh_br_consume(&bre, p); + } + /* The position is actually a distance from the last + * code we had extracted and thus we have to convert + * it to a position of the window. */ + copy_pos = (w_pos - copy_pos - 1) & w_mask; + /* FALL THROUGH */ + case ST_COPY_DATA: + /* + * Copy `copy_len' bytes as extracted data from + * the window into the output buffer. + */ + for (;;) { + int l; + + l = copy_len; + if (copy_pos > w_pos) { + if (l > w_size - copy_pos) + l = w_size - copy_pos; + } else { + if (l > w_size - w_pos) + l = w_size - w_pos; + } + if ((copy_pos + l < w_pos) + || (w_pos + l < copy_pos)) { + /* No overlap. */ + memcpy(w_buff + w_pos, + w_buff + copy_pos, l); + } else { + const unsigned char *s; + unsigned char *d; + int li; + + d = w_buff + w_pos; + s = w_buff + copy_pos; + for (li = 0; li < l-1;) { + d[li] = s[li];li++; + d[li] = s[li];li++; + } + if (li < l) + d[li] = s[li]; + } + w_pos += l; + if (w_pos == w_size) { + w_pos = 0; + lzh_emit_window(strm, w_size); + if (copy_len <= l) + state = ST_GET_LITERAL; + else { + state = ST_COPY_DATA; + ds->copy_len = copy_len - l; + ds->copy_pos = + (copy_pos + l) & w_mask; + } + goto next_data; + } + if (copy_len <= l) + /* A copy of current pattern ended. */ + break; + copy_len -= l; + copy_pos = (copy_pos + l) & w_mask; + } + state = ST_GET_LITERAL; + break; + } + } +failed: + return (ds->error = ARCHIVE_FAILED); +next_data: + ds->br = bre; + ds->blocks_avail = blocks_avail; + ds->state = state; + ds->w_pos = w_pos; + return (ARCHIVE_OK); +} + +static int +lzh_huffman_init(struct huffman *hf, size_t len_size, int tbl_bits) +{ + int bits; + + if (hf->bitlen == NULL) { + hf->bitlen = malloc(len_size * sizeof(hf->bitlen[0])); + if (hf->bitlen == NULL) + return (ARCHIVE_FATAL); + } + if (hf->tbl == NULL) { + if (tbl_bits < HTBL_BITS) + bits = tbl_bits; + else + bits = HTBL_BITS; + hf->tbl = malloc(((size_t)1 << bits) * sizeof(hf->tbl[0])); + if (hf->tbl == NULL) + return (ARCHIVE_FATAL); + } + if (hf->tree == NULL && tbl_bits > HTBL_BITS) { + hf->tree_avail = 1 << (tbl_bits - HTBL_BITS + 4); + hf->tree = malloc(hf->tree_avail * sizeof(hf->tree[0])); + if (hf->tree == NULL) + return (ARCHIVE_FATAL); + } + hf->len_size = (int)len_size; + hf->tbl_bits = tbl_bits; + return (ARCHIVE_OK); +} + +static void +lzh_huffman_free(struct huffman *hf) +{ + free(hf->bitlen); + free(hf->tbl); + free(hf->tree); +} + +static const char bitlen_tbl[0x400] = { + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, + 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 16, 0 +}; +static int +lzh_read_pt_bitlen(struct lzh_stream *strm, int start, int end) +{ + struct lzh_dec *ds = strm->ds; + struct lzh_br *br = &(ds->br); + int c, i; + + for (i = start; i < end; ) { + /* + * bit pattern the number we need + * 000 -> 0 + * 001 -> 1 + * 010 -> 2 + * ... + * 110 -> 6 + * 1110 -> 7 + * 11110 -> 8 + * ... + * 1111111111110 -> 16 + */ + if (!lzh_br_read_ahead(strm, br, 3)) + return (i); + if ((c = lzh_br_bits(br, 3)) == 7) { + if (!lzh_br_read_ahead(strm, br, 13)) + return (i); + c = bitlen_tbl[lzh_br_bits(br, 13) & 0x3FF]; + if (c) + lzh_br_consume(br, c - 3); + else + return (-1);/* Invalid data. */ + } else + lzh_br_consume(br, 3); + ds->pt.bitlen[i++] = c; + ds->pt.freq[c]++; + } + return (i); +} + +static int +lzh_make_fake_table(struct huffman *hf, uint16_t c) +{ + if (c >= hf->len_size) + return (0); + hf->tbl[0] = c; + hf->max_bits = 0; + hf->shift_bits = 0; + hf->bitlen[hf->tbl[0]] = 0; + return (1); +} + +/* + * Make a huffman coding table. + */ +static int +lzh_make_huffman_table(struct huffman *hf) +{ + uint16_t *tbl; + const unsigned char *bitlen; + int bitptn[17], weight[17]; + int i, maxbits = 0, ptn, tbl_size, w; + int diffbits, len_avail; + + /* + * Initialize bit patterns. + */ + ptn = 0; + for (i = 1, w = 1 << 15; i <= 16; i++, w >>= 1) { + bitptn[i] = ptn; + weight[i] = w; + if (hf->freq[i]) { + ptn += hf->freq[i] * w; + maxbits = i; + } + } + if (ptn != 0x10000 || maxbits > hf->tbl_bits) + return (0);/* Invalid */ + + hf->max_bits = maxbits; + + /* + * Cut out extra bits which we won't house in the table. + * This preparation reduces the same calculation in the for-loop + * making the table. + */ + if (maxbits < 16) { + int ebits = 16 - maxbits; + for (i = 1; i <= maxbits; i++) { + bitptn[i] >>= ebits; + weight[i] >>= ebits; + } + } + if (maxbits > HTBL_BITS) { + unsigned htbl_max; + uint16_t *p; + + diffbits = maxbits - HTBL_BITS; + for (i = 1; i <= HTBL_BITS; i++) { + bitptn[i] >>= diffbits; + weight[i] >>= diffbits; + } + htbl_max = bitptn[HTBL_BITS] + + weight[HTBL_BITS] * hf->freq[HTBL_BITS]; + p = &(hf->tbl[htbl_max]); + while (p < &hf->tbl[1U<<HTBL_BITS]) + *p++ = 0; + } else + diffbits = 0; + hf->shift_bits = diffbits; + + /* + * Make the table. + */ + tbl_size = 1 << HTBL_BITS; + tbl = hf->tbl; + bitlen = hf->bitlen; + len_avail = hf->len_avail; + hf->tree_used = 0; + for (i = 0; i < len_avail; i++) { + uint16_t *p; + int len, cnt; + uint16_t bit; + int extlen; + struct htree_t *ht; + + if (bitlen[i] == 0) + continue; + /* Get a bit pattern */ + len = bitlen[i]; + ptn = bitptn[len]; + cnt = weight[len]; + if (len <= HTBL_BITS) { + /* Calculate next bit pattern */ + if ((bitptn[len] = ptn + cnt) > tbl_size) + return (0);/* Invalid */ + /* Update the table */ + p = &(tbl[ptn]); + if (cnt > 7) { + uint16_t *pc; + + cnt -= 8; + pc = &p[cnt]; + pc[0] = (uint16_t)i; + pc[1] = (uint16_t)i; + pc[2] = (uint16_t)i; + pc[3] = (uint16_t)i; + pc[4] = (uint16_t)i; + pc[5] = (uint16_t)i; + pc[6] = (uint16_t)i; + pc[7] = (uint16_t)i; + if (cnt > 7) { + cnt -= 8; + memcpy(&p[cnt], pc, + 8 * sizeof(uint16_t)); + pc = &p[cnt]; + while (cnt > 15) { + cnt -= 16; + memcpy(&p[cnt], pc, + 16 * sizeof(uint16_t)); + } + } + if (cnt) + memcpy(p, pc, cnt * sizeof(uint16_t)); + } else { + while (cnt > 1) { + p[--cnt] = (uint16_t)i; + p[--cnt] = (uint16_t)i; + } + if (cnt) + p[--cnt] = (uint16_t)i; + } + continue; + } + + /* + * A bit length is too big to be housed to a direct table, + * so we use a tree model for its extra bits. + */ + bitptn[len] = ptn + cnt; + bit = 1U << (diffbits -1); + extlen = len - HTBL_BITS; + + p = &(tbl[ptn >> diffbits]); + if (*p == 0) { + *p = len_avail + hf->tree_used; + ht = &(hf->tree[hf->tree_used++]); + if (hf->tree_used > hf->tree_avail) + return (0);/* Invalid */ + ht->left = 0; + ht->right = 0; + } else { + if (*p < len_avail || + *p >= (len_avail + hf->tree_used)) + return (0);/* Invalid */ + ht = &(hf->tree[*p - len_avail]); + } + while (--extlen > 0) { + if (ptn & bit) { + if (ht->left < len_avail) { + ht->left = len_avail + hf->tree_used; + ht = &(hf->tree[hf->tree_used++]); + if (hf->tree_used > hf->tree_avail) + return (0);/* Invalid */ + ht->left = 0; + ht->right = 0; + } else { + ht = &(hf->tree[ht->left - len_avail]); + } + } else { + if (ht->right < len_avail) { + ht->right = len_avail + hf->tree_used; + ht = &(hf->tree[hf->tree_used++]); + if (hf->tree_used > hf->tree_avail) + return (0);/* Invalid */ + ht->left = 0; + ht->right = 0; + } else { + ht = &(hf->tree[ht->right - len_avail]); + } + } + bit >>= 1; + } + if (ptn & bit) { + if (ht->left != 0) + return (0);/* Invalid */ + ht->left = (uint16_t)i; + } else { + if (ht->right != 0) + return (0);/* Invalid */ + ht->right = (uint16_t)i; + } + } + return (1); +} + +static int +lzh_decode_huffman_tree(struct huffman *hf, unsigned rbits, int c) +{ + struct htree_t *ht; + int extlen; + + ht = hf->tree; + extlen = hf->shift_bits; + while (c >= hf->len_avail) { + c -= hf->len_avail; + if (extlen-- <= 0 || c >= hf->tree_used) + return (0); + if (rbits & (1U << extlen)) + c = ht[c].left; + else + c = ht[c].right; + } + return (c); +} + +static inline int +lzh_decode_huffman(struct huffman *hf, unsigned rbits) +{ + int c; + /* + * At first search an index table for a bit pattern. + * If it fails, search a huffman tree for. + */ + c = hf->tbl[rbits >> hf->shift_bits]; + if (c < hf->len_avail || hf->len_avail == 0) + return (c); + /* This bit pattern needs to be found out at a huffman tree. */ + return (lzh_decode_huffman_tree(hf, rbits, c)); +} + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_mtree.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_mtree.c new file mode 100644 index 0000000000..332944ac51 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_mtree.c @@ -0,0 +1,2025 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2008 Joerg Sonnenberger + * Copyright (c) 2011-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_mtree.c 201165 2009-12-29 05:52:13Z kientzle $"); + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#include <stddef.h> +/* #include <stdint.h> */ /* See archive_platform.h */ +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_CTYPE_H +#include <ctype.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_rb.h" +#include "archive_read_private.h" +#include "archive_string.h" +#include "archive_pack_dev.h" + +#ifndef O_BINARY +#define O_BINARY 0 +#endif +#ifndef O_CLOEXEC +#define O_CLOEXEC 0 +#endif + +#define MTREE_HAS_DEVICE 0x0001 +#define MTREE_HAS_FFLAGS 0x0002 +#define MTREE_HAS_GID 0x0004 +#define MTREE_HAS_GNAME 0x0008 +#define MTREE_HAS_MTIME 0x0010 +#define MTREE_HAS_NLINK 0x0020 +#define MTREE_HAS_PERM 0x0040 +#define MTREE_HAS_SIZE 0x0080 +#define MTREE_HAS_TYPE 0x0100 +#define MTREE_HAS_UID 0x0200 +#define MTREE_HAS_UNAME 0x0400 + +#define MTREE_HAS_OPTIONAL 0x0800 +#define MTREE_HAS_NOCHANGE 0x1000 /* FreeBSD specific */ + +#define MAX_LINE_LEN (1024 * 1024) + +struct mtree_option { + struct mtree_option *next; + char *value; +}; + +struct mtree_entry { + struct archive_rb_node rbnode; + struct mtree_entry *next_dup; + struct mtree_entry *next; + struct mtree_option *options; + char *name; + char full; + char used; +}; + +struct mtree { + struct archive_string line; + size_t buffsize; + char *buff; + int64_t offset; + int fd; + int archive_format; + const char *archive_format_name; + struct mtree_entry *entries; + struct mtree_entry *this_entry; + struct archive_rb_tree entry_rbtree; + struct archive_string current_dir; + struct archive_string contents_name; + + struct archive_entry_linkresolver *resolver; + struct archive_rb_tree rbtree; + + int64_t cur_size; + char checkfs; +}; + +static int bid_keycmp(const char *, const char *, ssize_t); +static int cleanup(struct archive_read *); +static int detect_form(struct archive_read *, int *); +static int mtree_bid(struct archive_read *, int); +static int parse_file(struct archive_read *, struct archive_entry *, + struct mtree *, struct mtree_entry *, int *); +static void parse_escapes(char *, struct mtree_entry *); +static int parse_line(struct archive_read *, struct archive_entry *, + struct mtree *, struct mtree_entry *, int *); +static int parse_keyword(struct archive_read *, struct mtree *, + struct archive_entry *, struct mtree_option *, int *); +static int read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset); +static ssize_t readline(struct archive_read *, struct mtree *, char **, ssize_t); +static int skip(struct archive_read *a); +static int read_header(struct archive_read *, + struct archive_entry *); +static int64_t mtree_atol(char **, int base); + +/* + * There's no standard for TIME_T_MAX/TIME_T_MIN. So we compute them + * here. TODO: Move this to configure time, but be careful + * about cross-compile environments. + */ +static int64_t +get_time_t_max(void) +{ +#if defined(TIME_T_MAX) + return TIME_T_MAX; +#else + /* ISO C allows time_t to be a floating-point type, + but POSIX requires an integer type. The following + should work on any system that follows the POSIX + conventions. */ + if (((time_t)0) < ((time_t)-1)) { + /* Time_t is unsigned */ + return (~(time_t)0); + } else { + /* Time_t is signed. */ + /* Assume it's the same as int64_t or int32_t */ + if (sizeof(time_t) == sizeof(int64_t)) { + return (time_t)INT64_MAX; + } else { + return (time_t)INT32_MAX; + } + } +#endif +} + +static int64_t +get_time_t_min(void) +{ +#if defined(TIME_T_MIN) + return TIME_T_MIN; +#else + if (((time_t)0) < ((time_t)-1)) { + /* Time_t is unsigned */ + return (time_t)0; + } else { + /* Time_t is signed. */ + if (sizeof(time_t) == sizeof(int64_t)) { + return (time_t)INT64_MIN; + } else { + return (time_t)INT32_MIN; + } + } +#endif +} + +static int +archive_read_format_mtree_options(struct archive_read *a, + const char *key, const char *val) +{ + struct mtree *mtree; + + mtree = (struct mtree *)(a->format->data); + if (strcmp(key, "checkfs") == 0) { + /* Allows to read information missing from the mtree from the file system */ + if (val == NULL || val[0] == 0) { + mtree->checkfs = 0; + } else { + mtree->checkfs = 1; + } + return (ARCHIVE_OK); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static void +free_options(struct mtree_option *head) +{ + struct mtree_option *next; + + for (; head != NULL; head = next) { + next = head->next; + free(head->value); + free(head); + } +} + +static int +mtree_cmp_node(const struct archive_rb_node *n1, + const struct archive_rb_node *n2) +{ + const struct mtree_entry *e1 = (const struct mtree_entry *)n1; + const struct mtree_entry *e2 = (const struct mtree_entry *)n2; + + return (strcmp(e1->name, e2->name)); +} + +static int +mtree_cmp_key(const struct archive_rb_node *n, const void *key) +{ + const struct mtree_entry *e = (const struct mtree_entry *)n; + + return (strcmp(e->name, key)); +} + +int +archive_read_support_format_mtree(struct archive *_a) +{ + static const struct archive_rb_tree_ops rb_ops = { + mtree_cmp_node, mtree_cmp_key, + }; + struct archive_read *a = (struct archive_read *)_a; + struct mtree *mtree; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_mtree"); + + mtree = (struct mtree *)calloc(1, sizeof(*mtree)); + if (mtree == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate mtree data"); + return (ARCHIVE_FATAL); + } + mtree->checkfs = 0; + mtree->fd = -1; + + __archive_rb_tree_init(&mtree->rbtree, &rb_ops); + + r = __archive_read_register_format(a, mtree, "mtree", + mtree_bid, archive_read_format_mtree_options, read_header, read_data, skip, NULL, cleanup, NULL, NULL); + + if (r != ARCHIVE_OK) + free(mtree); + return (ARCHIVE_OK); +} + +static int +cleanup(struct archive_read *a) +{ + struct mtree *mtree; + struct mtree_entry *p, *q; + + mtree = (struct mtree *)(a->format->data); + + p = mtree->entries; + while (p != NULL) { + q = p->next; + free(p->name); + free_options(p->options); + free(p); + p = q; + } + archive_string_free(&mtree->line); + archive_string_free(&mtree->current_dir); + archive_string_free(&mtree->contents_name); + archive_entry_linkresolver_free(mtree->resolver); + + free(mtree->buff); + free(mtree); + (a->format->data) = NULL; + return (ARCHIVE_OK); +} + +static ssize_t +get_line_size(const char *b, ssize_t avail, ssize_t *nlsize) +{ + ssize_t len; + + len = 0; + while (len < avail) { + switch (*b) { + case '\0':/* Non-ascii character or control character. */ + if (nlsize != NULL) + *nlsize = 0; + return (-1); + case '\r': + if (avail-len > 1 && b[1] == '\n') { + if (nlsize != NULL) + *nlsize = 2; + return (len+2); + } + /* FALL THROUGH */ + case '\n': + if (nlsize != NULL) + *nlsize = 1; + return (len+1); + default: + b++; + len++; + break; + } + } + if (nlsize != NULL) + *nlsize = 0; + return (avail); +} + +/* + * <---------------- ravail ---------------------> + * <-- diff ------> <--- avail -----------------> + * <---- len -----------> + * | Previous lines | line being parsed nl extra | + * ^ + * b + * + */ +static ssize_t +next_line(struct archive_read *a, + const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl) +{ + ssize_t len; + int quit; + + quit = 0; + if (*avail == 0) { + *nl = 0; + len = 0; + } else + len = get_line_size(*b, *avail, nl); + /* + * Read bytes more while it does not reach the end of line. + */ + while (*nl == 0 && len == *avail && !quit) { + ssize_t diff = *ravail - *avail; + size_t nbytes_req = (*ravail+1023) & ~1023U; + ssize_t tested; + + /* + * Place an arbitrary limit on the line length. + * mtree is almost free-form input and without line length limits, + * it can consume a lot of memory. + */ + if (len >= MAX_LINE_LEN) + return (-1); + + /* Increase reading bytes if it is not enough to at least + * new two lines. */ + if (nbytes_req < (size_t)*ravail + 160) + nbytes_req <<= 1; + + *b = __archive_read_ahead(a, nbytes_req, avail); + if (*b == NULL) { + if (*ravail >= *avail) + return (0); + /* Reading bytes reaches the end of file. */ + *b = __archive_read_ahead(a, *avail, avail); + quit = 1; + } + *ravail = *avail; + *b += diff; + *avail -= diff; + tested = len;/* Skip some bytes we already determinated. */ + len = get_line_size(*b + len, *avail - len, nl); + if (len >= 0) + len += tested; + } + return (len); +} + +/* + * Compare characters with a mtree keyword. + * Returns the length of a mtree keyword if matched. + * Returns 0 if not matched. + */ +static int +bid_keycmp(const char *p, const char *key, ssize_t len) +{ + int match_len = 0; + + while (len > 0 && *p && *key) { + if (*p == *key) { + --len; + ++p; + ++key; + ++match_len; + continue; + } + return (0);/* Not match */ + } + if (*key != '\0') + return (0);/* Not match */ + + /* A following character should be specified characters */ + if (p[0] == '=' || p[0] == ' ' || p[0] == '\t' || + p[0] == '\n' || p[0] == '\r' || + (p[0] == '\\' && (p[1] == '\n' || p[1] == '\r'))) + return (match_len); + return (0);/* Not match */ +} + +/* + * Test whether the characters 'p' has is mtree keyword. + * Returns the length of a detected keyword. + * Returns 0 if any keywords were not found. + */ +static int +bid_keyword(const char *p, ssize_t len) +{ + static const char * const keys_c[] = { + "content", "contents", "cksum", NULL + }; + static const char * const keys_df[] = { + "device", "flags", NULL + }; + static const char * const keys_g[] = { + "gid", "gname", NULL + }; + static const char * const keys_il[] = { + "ignore", "inode", "link", NULL + }; + static const char * const keys_m[] = { + "md5", "md5digest", "mode", NULL + }; + static const char * const keys_no[] = { + "nlink", "nochange", "optional", NULL + }; + static const char * const keys_r[] = { + "resdevice", "rmd160", "rmd160digest", NULL + }; + static const char * const keys_s[] = { + "sha1", "sha1digest", + "sha256", "sha256digest", + "sha384", "sha384digest", + "sha512", "sha512digest", + "size", NULL + }; + static const char * const keys_t[] = { + "tags", "time", "type", NULL + }; + static const char * const keys_u[] = { + "uid", "uname", NULL + }; + const char * const *keys; + int i; + + switch (*p) { + case 'c': keys = keys_c; break; + case 'd': case 'f': keys = keys_df; break; + case 'g': keys = keys_g; break; + case 'i': case 'l': keys = keys_il; break; + case 'm': keys = keys_m; break; + case 'n': case 'o': keys = keys_no; break; + case 'r': keys = keys_r; break; + case 's': keys = keys_s; break; + case 't': keys = keys_t; break; + case 'u': keys = keys_u; break; + default: return (0);/* Unknown key */ + } + + for (i = 0; keys[i] != NULL; i++) { + int l = bid_keycmp(p, keys[i], len); + if (l > 0) + return (l); + } + return (0);/* Unknown key */ +} + +/* + * Test whether there is a set of mtree keywords. + * Returns the number of keyword. + * Returns -1 if we got incorrect sequence. + * This function expects a set of "<space characters>keyword=value". + * When "unset" is specified, expects a set of "<space characters>keyword". + */ +static int +bid_keyword_list(const char *p, ssize_t len, int unset, int last_is_path) +{ + int l; + int keycnt = 0; + + while (len > 0 && *p) { + int blank = 0; + + /* Test whether there are blank characters in the line. */ + while (len >0 && (*p == ' ' || *p == '\t')) { + ++p; + --len; + blank = 1; + } + if (*p == '\n' || *p == '\r') + break; + if (p[0] == '\\' && (p[1] == '\n' || p[1] == '\r')) + break; + if (!blank && !last_is_path) /* No blank character. */ + return (-1); + if (last_is_path && len == 0) + return (keycnt); + + if (unset) { + l = bid_keycmp(p, "all", len); + if (l > 0) + return (1); + } + /* Test whether there is a correct key in the line. */ + l = bid_keyword(p, len); + if (l == 0) + return (-1);/* Unknown keyword was found. */ + p += l; + len -= l; + keycnt++; + + /* Skip value */ + if (*p == '=') { + int value = 0; + ++p; + --len; + while (len > 0 && *p != ' ' && *p != '\t') { + ++p; + --len; + value = 1; + } + /* A keyword should have a its value unless + * "/unset" operation. */ + if (!unset && value == 0) + return (-1); + } + } + return (keycnt); +} + +static int +bid_entry(const char *p, ssize_t len, ssize_t nl, int *last_is_path) +{ + int f = 0; + static const unsigned char safe_char[256] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 00 - 0F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 1F */ + /* !"$%&'()*+,-./ EXCLUSION:( )(#) */ + 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 20 - 2F */ + /* 0123456789:;<>? EXCLUSION:(=) */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, /* 30 - 3F */ + /* @ABCDEFGHIJKLMNO */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 40 - 4F */ + /* PQRSTUVWXYZ[\]^_ */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 50 - 5F */ + /* `abcdefghijklmno */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 60 - 6F */ + /* pqrstuvwxyz{|}~ */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, /* 70 - 7F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F0 - FF */ + }; + ssize_t ll; + const char *pp = p; + const char * const pp_end = pp + len; + + *last_is_path = 0; + /* + * Skip the path-name which is quoted. + */ + for (;pp < pp_end; ++pp) { + if (!safe_char[*(const unsigned char *)pp]) { + if (*pp != ' ' && *pp != '\t' && *pp != '\r' + && *pp != '\n') + f = 0; + break; + } + f = 1; + } + ll = pp_end - pp; + + /* If a path-name was not found at the first, try to check + * a mtree format(a.k.a form D) ``NetBSD's mtree -D'' creates, + * which places the path-name at the last. */ + if (f == 0) { + const char *pb = p + len - nl; + int name_len = 0; + int slash; + + /* The form D accepts only a single line for an entry. */ + if (pb-2 >= p && + pb[-1] == '\\' && (pb[-2] == ' ' || pb[-2] == '\t')) + return (-1); + if (pb-1 >= p && pb[-1] == '\\') + return (-1); + + slash = 0; + while (p <= --pb && *pb != ' ' && *pb != '\t') { + if (!safe_char[*(const unsigned char *)pb]) + return (-1); + name_len++; + /* The pathname should have a slash in this + * format. */ + if (*pb == '/') + slash = 1; + } + if (name_len == 0 || slash == 0) + return (-1); + /* If '/' is placed at the first in this field, this is not + * a valid filename. */ + if (pb[1] == '/') + return (-1); + ll = len - nl - name_len; + pp = p; + *last_is_path = 1; + } + + return (bid_keyword_list(pp, ll, 0, *last_is_path)); +} + +#define MAX_BID_ENTRY 3 + +static int +mtree_bid(struct archive_read *a, int best_bid) +{ + const char *signature = "#mtree"; + const char *p; + + (void)best_bid; /* UNUSED */ + + /* Now let's look at the actual header and see if it matches. */ + p = __archive_read_ahead(a, strlen(signature), NULL); + if (p == NULL) + return (-1); + + if (memcmp(p, signature, strlen(signature)) == 0) + return (8 * (int)strlen(signature)); + + /* + * There is not a mtree signature. Let's try to detect mtree format. + */ + return (detect_form(a, NULL)); +} + +static int +detect_form(struct archive_read *a, int *is_form_d) +{ + const char *p; + ssize_t avail, ravail; + ssize_t detected_bytes = 0, len, nl; + int entry_cnt = 0, multiline = 0; + int form_D = 0;/* The archive is generated by `NetBSD mtree -D' + * (In this source we call it `form D') . */ + + if (is_form_d != NULL) + *is_form_d = 0; + p = __archive_read_ahead(a, 1, &avail); + if (p == NULL) + return (-1); + ravail = avail; + for (;;) { + len = next_line(a, &p, &avail, &ravail, &nl); + /* The terminal character of the line should be + * a new line character, '\r\n' or '\n'. */ + if (len <= 0 || nl == 0) + break; + if (!multiline) { + /* Leading whitespace is never significant, + * ignore it. */ + while (len > 0 && (*p == ' ' || *p == '\t')) { + ++p; + --avail; + --len; + } + /* Skip comment or empty line. */ + if (p[0] == '#' || p[0] == '\n' || p[0] == '\r') { + p += len; + avail -= len; + continue; + } + } else { + /* A continuance line; the terminal + * character of previous line was '\' character. */ + if (bid_keyword_list(p, len, 0, 0) <= 0) + break; + if (multiline == 1) + detected_bytes += len; + if (p[len-nl-1] != '\\') { + if (multiline == 1 && + ++entry_cnt >= MAX_BID_ENTRY) + break; + multiline = 0; + } + p += len; + avail -= len; + continue; + } + if (p[0] != '/') { + int last_is_path, keywords; + + keywords = bid_entry(p, len, nl, &last_is_path); + if (keywords >= 0) { + detected_bytes += len; + if (form_D == 0) { + if (last_is_path) + form_D = 1; + else if (keywords > 0) + /* This line is not `form D'. */ + form_D = -1; + } else if (form_D == 1) { + if (!last_is_path && keywords > 0) + /* This this is not `form D' + * and We cannot accept mixed + * format. */ + break; + } + if (!last_is_path && p[len-nl-1] == '\\') + /* This line continues. */ + multiline = 1; + else { + /* We've got plenty of correct lines + * to assume that this file is a mtree + * format. */ + if (++entry_cnt >= MAX_BID_ENTRY) + break; + } + } else + break; + } else if (len > 4 && strncmp(p, "/set", 4) == 0) { + if (bid_keyword_list(p+4, len-4, 0, 0) <= 0) + break; + /* This line continues. */ + if (p[len-nl-1] == '\\') + multiline = 2; + } else if (len > 6 && strncmp(p, "/unset", 6) == 0) { + if (bid_keyword_list(p+6, len-6, 1, 0) <= 0) + break; + /* This line continues. */ + if (p[len-nl-1] == '\\') + multiline = 2; + } else + break; + + /* Test next line. */ + p += len; + avail -= len; + } + if (entry_cnt >= MAX_BID_ENTRY || (entry_cnt > 0 && len == 0)) { + if (is_form_d != NULL) { + if (form_D == 1) + *is_form_d = 1; + } + return (32); + } + + return (0); +} + +/* + * The extended mtree format permits multiple lines specifying + * attributes for each file. For those entries, only the last line + * is actually used. Practically speaking, that means we have + * to read the entire mtree file into memory up front. + * + * The parsing is done in two steps. First, it is decided if a line + * changes the global defaults and if it is, processed accordingly. + * Otherwise, the options of the line are merged with the current + * global options. + */ +static int +add_option(struct archive_read *a, struct mtree_option **global, + const char *value, size_t len) +{ + struct mtree_option *opt; + + if ((opt = malloc(sizeof(*opt))) == NULL) { + archive_set_error(&a->archive, errno, "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + if ((opt->value = malloc(len + 1)) == NULL) { + free(opt); + archive_set_error(&a->archive, errno, "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + memcpy(opt->value, value, len); + opt->value[len] = '\0'; + opt->next = *global; + *global = opt; + return (ARCHIVE_OK); +} + +static void +remove_option(struct mtree_option **global, const char *value, size_t len) +{ + struct mtree_option *iter, *last; + + last = NULL; + for (iter = *global; iter != NULL; last = iter, iter = iter->next) { + if (strncmp(iter->value, value, len) == 0 && + (iter->value[len] == '\0' || + iter->value[len] == '=')) + break; + } + if (iter == NULL) + return; + if (last == NULL) + *global = iter->next; + else + last->next = iter->next; + + free(iter->value); + free(iter); +} + +static int +process_global_set(struct archive_read *a, + struct mtree_option **global, const char *line) +{ + const char *next, *eq; + size_t len; + int r; + + line += 4; + for (;;) { + next = line + strspn(line, " \t\r\n"); + if (*next == '\0') + return (ARCHIVE_OK); + line = next; + next = line + strcspn(line, " \t\r\n"); + eq = strchr(line, '='); + if (eq > next) + len = next - line; + else + len = eq - line; + + remove_option(global, line, len); + r = add_option(a, global, line, next - line); + if (r != ARCHIVE_OK) + return (r); + line = next; + } +} + +static int +process_global_unset(struct archive_read *a, + struct mtree_option **global, const char *line) +{ + const char *next; + size_t len; + + line += 6; + if (strchr(line, '=') != NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "/unset shall not contain `='"); + return ARCHIVE_FATAL; + } + + for (;;) { + next = line + strspn(line, " \t\r\n"); + if (*next == '\0') + return (ARCHIVE_OK); + line = next; + len = strcspn(line, " \t\r\n"); + + if (len == 3 && strncmp(line, "all", 3) == 0) { + free_options(*global); + *global = NULL; + } else { + remove_option(global, line, len); + } + + line += len; + } +} + +static int +process_add_entry(struct archive_read *a, struct mtree *mtree, + struct mtree_option **global, const char *line, ssize_t line_len, + struct mtree_entry **last_entry, int is_form_d) +{ + struct mtree_entry *entry; + struct mtree_option *iter; + const char *next, *eq, *name, *end; + size_t name_len, len; + int r, i; + + if ((entry = malloc(sizeof(*entry))) == NULL) { + archive_set_error(&a->archive, errno, "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + entry->next = NULL; + entry->options = NULL; + entry->name = NULL; + entry->used = 0; + entry->full = 0; + + /* Add this entry to list. */ + if (*last_entry == NULL) + mtree->entries = entry; + else + (*last_entry)->next = entry; + *last_entry = entry; + + if (is_form_d) { + /* Filename is last item on line. */ + /* Adjust line_len to trim trailing whitespace */ + while (line_len > 0) { + char last_character = line[line_len - 1]; + if (last_character == '\r' + || last_character == '\n' + || last_character == '\t' + || last_character == ' ') { + line_len--; + } else { + break; + } + } + /* Name starts after the last whitespace separator */ + name = line; + for (i = 0; i < line_len; i++) { + if (line[i] == '\r' + || line[i] == '\n' + || line[i] == '\t' + || line[i] == ' ') { + name = line + i + 1; + } + } + name_len = line + line_len - name; + end = name; + } else { + /* Filename is first item on line */ + name_len = strcspn(line, " \t\r\n"); + name = line; + line += name_len; + end = line + line_len; + } + /* name/name_len is the name within the line. */ + /* line..end brackets the entire line except the name */ + + if ((entry->name = malloc(name_len + 1)) == NULL) { + archive_set_error(&a->archive, errno, "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + + memcpy(entry->name, name, name_len); + entry->name[name_len] = '\0'; + parse_escapes(entry->name, entry); + + entry->next_dup = NULL; + if (entry->full) { + if (!__archive_rb_tree_insert_node(&mtree->rbtree, &entry->rbnode)) { + struct mtree_entry *alt; + alt = (struct mtree_entry *)__archive_rb_tree_find_node( + &mtree->rbtree, entry->name); + while (alt->next_dup) + alt = alt->next_dup; + alt->next_dup = entry; + } + } + + for (iter = *global; iter != NULL; iter = iter->next) { + r = add_option(a, &entry->options, iter->value, + strlen(iter->value)); + if (r != ARCHIVE_OK) + return (r); + } + + for (;;) { + next = line + strspn(line, " \t\r\n"); + if (*next == '\0') + return (ARCHIVE_OK); + if (next >= end) + return (ARCHIVE_OK); + line = next; + next = line + strcspn(line, " \t\r\n"); + eq = strchr(line, '='); + if (eq == NULL || eq > next) + len = next - line; + else + len = eq - line; + + remove_option(&entry->options, line, len); + r = add_option(a, &entry->options, line, next - line); + if (r != ARCHIVE_OK) + return (r); + line = next; + } +} + +static int +read_mtree(struct archive_read *a, struct mtree *mtree) +{ + ssize_t len; + uintmax_t counter; + char *p, *s; + struct mtree_option *global; + struct mtree_entry *last_entry; + int r, is_form_d; + + mtree->archive_format = ARCHIVE_FORMAT_MTREE; + mtree->archive_format_name = "mtree"; + + global = NULL; + last_entry = NULL; + + (void)detect_form(a, &is_form_d); + + for (counter = 1; ; ++counter) { + r = ARCHIVE_OK; + len = readline(a, mtree, &p, 65536); + if (len == 0) { + mtree->this_entry = mtree->entries; + free_options(global); + return (ARCHIVE_OK); + } + if (len < 0) { + free_options(global); + return ((int)len); + } + /* Leading whitespace is never significant, ignore it. */ + while (*p == ' ' || *p == '\t') { + ++p; + --len; + } + /* Skip content lines and blank lines. */ + if (*p == '#') + continue; + if (*p == '\r' || *p == '\n' || *p == '\0') + continue; + /* Non-printable characters are not allowed */ + for (s = p;s < p + len - 1; s++) { + if (!isprint(*s)) { + r = ARCHIVE_FATAL; + break; + } + } + if (r != ARCHIVE_OK) + break; + if (*p != '/') { + r = process_add_entry(a, mtree, &global, p, len, + &last_entry, is_form_d); + } else if (len > 4 && strncmp(p, "/set", 4) == 0) { + if (p[4] != ' ' && p[4] != '\t') + break; + r = process_global_set(a, &global, p); + } else if (len > 6 && strncmp(p, "/unset", 6) == 0) { + if (p[6] != ' ' && p[6] != '\t') + break; + r = process_global_unset(a, &global, p); + } else + break; + + if (r != ARCHIVE_OK) { + free_options(global); + return r; + } + } + + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Can't parse line %ju", counter); + free_options(global); + return (ARCHIVE_FATAL); +} + +/* + * Read in the entire mtree file into memory on the first request. + * Then use the next unused file to satisfy each header request. + */ +static int +read_header(struct archive_read *a, struct archive_entry *entry) +{ + struct mtree *mtree; + char *p; + int r, use_next; + + mtree = (struct mtree *)(a->format->data); + + if (mtree->fd >= 0) { + close(mtree->fd); + mtree->fd = -1; + } + + if (mtree->entries == NULL) { + mtree->resolver = archive_entry_linkresolver_new(); + if (mtree->resolver == NULL) + return ARCHIVE_FATAL; + archive_entry_linkresolver_set_strategy(mtree->resolver, + ARCHIVE_FORMAT_MTREE); + r = read_mtree(a, mtree); + if (r != ARCHIVE_OK) + return (r); + } + + a->archive.archive_format = mtree->archive_format; + a->archive.archive_format_name = mtree->archive_format_name; + + for (;;) { + if (mtree->this_entry == NULL) + return (ARCHIVE_EOF); + if (strcmp(mtree->this_entry->name, "..") == 0) { + mtree->this_entry->used = 1; + if (archive_strlen(&mtree->current_dir) > 0) { + /* Roll back current path. */ + p = mtree->current_dir.s + + mtree->current_dir.length - 1; + while (p >= mtree->current_dir.s && *p != '/') + --p; + if (p >= mtree->current_dir.s) + --p; + mtree->current_dir.length + = p - mtree->current_dir.s + 1; + } + } + if (!mtree->this_entry->used) { + use_next = 0; + r = parse_file(a, entry, mtree, mtree->this_entry, + &use_next); + if (use_next == 0) + return (r); + } + mtree->this_entry = mtree->this_entry->next; + } +} + +/* + * A single file can have multiple lines contribute specifications. + * Parse as many lines as necessary, then pull additional information + * from a backing file on disk as necessary. + */ +static int +parse_file(struct archive_read *a, struct archive_entry *entry, + struct mtree *mtree, struct mtree_entry *mentry, int *use_next) +{ + const char *path; + struct stat st_storage, *st; + struct mtree_entry *mp; + struct archive_entry *sparse_entry; + int r = ARCHIVE_OK, r1, parsed_kws; + + mentry->used = 1; + + /* Initialize reasonable defaults. */ + archive_entry_set_filetype(entry, AE_IFREG); + archive_entry_set_size(entry, 0); + archive_string_empty(&mtree->contents_name); + + /* Parse options from this line. */ + parsed_kws = 0; + r = parse_line(a, entry, mtree, mentry, &parsed_kws); + + if (mentry->full) { + archive_entry_copy_pathname(entry, mentry->name); + /* + * "Full" entries are allowed to have multiple lines + * and those lines aren't required to be adjacent. We + * don't support multiple lines for "relative" entries + * nor do we make any attempt to merge data from + * separate "relative" and "full" entries. (Merging + * "relative" and "full" entries would require dealing + * with pathname canonicalization, which is a very + * tricky subject.) + */ + mp = (struct mtree_entry *)__archive_rb_tree_find_node( + &mtree->rbtree, mentry->name); + for (; mp; mp = mp->next_dup) { + if (mp->full && !mp->used) { + /* Later lines override earlier ones. */ + mp->used = 1; + r1 = parse_line(a, entry, mtree, mp, &parsed_kws); + if (r1 < r) + r = r1; + } + } + } else { + /* + * Relative entries require us to construct + * the full path and possibly update the + * current directory. + */ + size_t n = archive_strlen(&mtree->current_dir); + if (n > 0) + archive_strcat(&mtree->current_dir, "/"); + archive_strcat(&mtree->current_dir, mentry->name); + archive_entry_copy_pathname(entry, mtree->current_dir.s); + if (archive_entry_filetype(entry) != AE_IFDIR) + mtree->current_dir.length = n; + } + + if (mtree->checkfs) { + /* + * Try to open and stat the file to get the real size + * and other file info. It would be nice to avoid + * this here so that getting a listing of an mtree + * wouldn't require opening every referenced contents + * file. But then we wouldn't know the actual + * contents size, so I don't see a really viable way + * around this. (Also, we may want to someday pull + * other unspecified info from the contents file on + * disk.) + */ + mtree->fd = -1; + if (archive_strlen(&mtree->contents_name) > 0) + path = mtree->contents_name.s; + else + path = archive_entry_pathname(entry); + + if (archive_entry_filetype(entry) == AE_IFREG || + archive_entry_filetype(entry) == AE_IFDIR) { + mtree->fd = open(path, O_RDONLY | O_BINARY | O_CLOEXEC); + __archive_ensure_cloexec_flag(mtree->fd); + if (mtree->fd == -1 && + (errno != ENOENT || + archive_strlen(&mtree->contents_name) > 0)) { + archive_set_error(&a->archive, errno, + "Can't open %s", path); + r = ARCHIVE_WARN; + } + } + + st = &st_storage; + if (mtree->fd >= 0) { + if (fstat(mtree->fd, st) == -1) { + archive_set_error(&a->archive, errno, + "Could not fstat %s", path); + r = ARCHIVE_WARN; + /* If we can't stat it, don't keep it open. */ + close(mtree->fd); + mtree->fd = -1; + st = NULL; + } + } else if (lstat(path, st) == -1) { + st = NULL; + } + + /* + * Check for a mismatch between the type in the specification + * and the type of the contents object on disk. + */ + if (st != NULL) { + if (((st->st_mode & S_IFMT) == S_IFREG && + archive_entry_filetype(entry) == AE_IFREG) +#ifdef S_IFLNK + ||((st->st_mode & S_IFMT) == S_IFLNK && + archive_entry_filetype(entry) == AE_IFLNK) +#endif +#ifdef S_IFSOCK + ||((st->st_mode & S_IFSOCK) == S_IFSOCK && + archive_entry_filetype(entry) == AE_IFSOCK) +#endif +#ifdef S_IFCHR + ||((st->st_mode & S_IFMT) == S_IFCHR && + archive_entry_filetype(entry) == AE_IFCHR) +#endif +#ifdef S_IFBLK + ||((st->st_mode & S_IFMT) == S_IFBLK && + archive_entry_filetype(entry) == AE_IFBLK) +#endif + ||((st->st_mode & S_IFMT) == S_IFDIR && + archive_entry_filetype(entry) == AE_IFDIR) +#ifdef S_IFIFO + ||((st->st_mode & S_IFMT) == S_IFIFO && + archive_entry_filetype(entry) == AE_IFIFO) +#endif + ) { + /* Types match. */ + } else { + /* Types don't match; bail out gracefully. */ + if (mtree->fd >= 0) + close(mtree->fd); + mtree->fd = -1; + if (parsed_kws & MTREE_HAS_OPTIONAL) { + /* It's not an error for an optional + * entry to not match disk. */ + *use_next = 1; + } else if (r == ARCHIVE_OK) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "mtree specification has different" + " type for %s", + archive_entry_pathname(entry)); + r = ARCHIVE_WARN; + } + return (r); + } + } + + /* + * If there is a contents file on disk, pick some of the + * metadata from that file. For most of these, we only + * set it from the contents if it wasn't already parsed + * from the specification. + */ + if (st != NULL) { + if (((parsed_kws & MTREE_HAS_DEVICE) == 0 || + (parsed_kws & MTREE_HAS_NOCHANGE) != 0) && + (archive_entry_filetype(entry) == AE_IFCHR || + archive_entry_filetype(entry) == AE_IFBLK)) + archive_entry_set_rdev(entry, st->st_rdev); + if ((parsed_kws & (MTREE_HAS_GID | MTREE_HAS_GNAME)) + == 0 || + (parsed_kws & MTREE_HAS_NOCHANGE) != 0) + archive_entry_set_gid(entry, st->st_gid); + if ((parsed_kws & (MTREE_HAS_UID | MTREE_HAS_UNAME)) + == 0 || + (parsed_kws & MTREE_HAS_NOCHANGE) != 0) + archive_entry_set_uid(entry, st->st_uid); + if ((parsed_kws & MTREE_HAS_MTIME) == 0 || + (parsed_kws & MTREE_HAS_NOCHANGE) != 0) { +#if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC + archive_entry_set_mtime(entry, st->st_mtime, + st->st_mtimespec.tv_nsec); +#elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC + archive_entry_set_mtime(entry, st->st_mtime, + st->st_mtim.tv_nsec); +#elif HAVE_STRUCT_STAT_ST_MTIME_N + archive_entry_set_mtime(entry, st->st_mtime, + st->st_mtime_n); +#elif HAVE_STRUCT_STAT_ST_UMTIME + archive_entry_set_mtime(entry, st->st_mtime, + st->st_umtime*1000); +#elif HAVE_STRUCT_STAT_ST_MTIME_USEC + archive_entry_set_mtime(entry, st->st_mtime, + st->st_mtime_usec*1000); +#else + archive_entry_set_mtime(entry, st->st_mtime, 0); +#endif + } + if ((parsed_kws & MTREE_HAS_NLINK) == 0 || + (parsed_kws & MTREE_HAS_NOCHANGE) != 0) + archive_entry_set_nlink(entry, st->st_nlink); + if ((parsed_kws & MTREE_HAS_PERM) == 0 || + (parsed_kws & MTREE_HAS_NOCHANGE) != 0) + archive_entry_set_perm(entry, st->st_mode); + if ((parsed_kws & MTREE_HAS_SIZE) == 0 || + (parsed_kws & MTREE_HAS_NOCHANGE) != 0) + archive_entry_set_size(entry, st->st_size); + archive_entry_set_ino(entry, st->st_ino); + archive_entry_set_dev(entry, st->st_dev); + + archive_entry_linkify(mtree->resolver, &entry, + &sparse_entry); + } else if (parsed_kws & MTREE_HAS_OPTIONAL) { + /* + * Couldn't open the entry, stat it or the on-disk type + * didn't match. If this entry is optional, just + * ignore it and read the next header entry. + */ + *use_next = 1; + return ARCHIVE_OK; + } + } + + mtree->cur_size = archive_entry_size(entry); + mtree->offset = 0; + + return r; +} + +/* + * Each line contains a sequence of keywords. + */ +static int +parse_line(struct archive_read *a, struct archive_entry *entry, + struct mtree *mtree, struct mtree_entry *mp, int *parsed_kws) +{ + struct mtree_option *iter; + int r = ARCHIVE_OK, r1; + + for (iter = mp->options; iter != NULL; iter = iter->next) { + r1 = parse_keyword(a, mtree, entry, iter, parsed_kws); + if (r1 < r) + r = r1; + } + if (r == ARCHIVE_OK && (*parsed_kws & MTREE_HAS_TYPE) == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Missing type keyword in mtree specification"); + return (ARCHIVE_WARN); + } + return (r); +} + +/* + * Device entries have one of the following forms: + * - raw dev_t + * - format,major,minor[,subdevice] + * When parsing succeeded, `pdev' will contain the appropriate dev_t value. + */ + +/* strsep() is not in C90, but strcspn() is. */ +/* Taken from http://unixpapa.com/incnote/string.html */ +static char * +la_strsep(char **sp, const char *sep) +{ + char *p, *s; + if (sp == NULL || *sp == NULL || **sp == '\0') + return(NULL); + s = *sp; + p = s + strcspn(s, sep); + if (*p != '\0') + *p++ = '\0'; + *sp = p; + return(s); +} + +static int +parse_device(dev_t *pdev, struct archive *a, char *val) +{ +#define MAX_PACK_ARGS 3 + unsigned long numbers[MAX_PACK_ARGS]; + char *p, *dev; + int argc; + pack_t *pack; + dev_t result; + const char *error = NULL; + + memset(pdev, 0, sizeof(*pdev)); + if ((dev = strchr(val, ',')) != NULL) { + /* + * Device's major/minor are given in a specified format. + * Decode and pack it accordingly. + */ + *dev++ = '\0'; + if ((pack = pack_find(val)) == NULL) { + archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT, + "Unknown format `%s'", val); + return ARCHIVE_WARN; + } + argc = 0; + while ((p = la_strsep(&dev, ",")) != NULL) { + if (*p == '\0') { + archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT, + "Missing number"); + return ARCHIVE_WARN; + } + if (argc >= MAX_PACK_ARGS) { + archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT, + "Too many arguments"); + return ARCHIVE_WARN; + } + numbers[argc++] = (unsigned long)mtree_atol(&p, 0); + } + if (argc < 2) { + archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT, + "Not enough arguments"); + return ARCHIVE_WARN; + } + result = (*pack)(argc, numbers, &error); + if (error != NULL) { + archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT, + "%s", error); + return ARCHIVE_WARN; + } + } else { + /* file system raw value. */ + result = (dev_t)mtree_atol(&val, 0); + } + *pdev = result; + return ARCHIVE_OK; +#undef MAX_PACK_ARGS +} + +/* + * Parse a single keyword and its value. + */ +static int +parse_keyword(struct archive_read *a, struct mtree *mtree, + struct archive_entry *entry, struct mtree_option *opt, int *parsed_kws) +{ + char *val, *key; + + key = opt->value; + + if (*key == '\0') + return (ARCHIVE_OK); + + if (strcmp(key, "nochange") == 0) { + *parsed_kws |= MTREE_HAS_NOCHANGE; + return (ARCHIVE_OK); + } + if (strcmp(key, "optional") == 0) { + *parsed_kws |= MTREE_HAS_OPTIONAL; + return (ARCHIVE_OK); + } + if (strcmp(key, "ignore") == 0) { + /* + * The mtree processing is not recursive, so + * recursion will only happen for explicitly listed + * entries. + */ + return (ARCHIVE_OK); + } + + val = strchr(key, '='); + if (val == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Malformed attribute \"%s\" (%d)", key, key[0]); + return (ARCHIVE_WARN); + } + + *val = '\0'; + ++val; + + switch (key[0]) { + case 'c': + if (strcmp(key, "content") == 0 + || strcmp(key, "contents") == 0) { + parse_escapes(val, NULL); + archive_strcpy(&mtree->contents_name, val); + break; + } + if (strcmp(key, "cksum") == 0) + break; + __LA_FALLTHROUGH; + case 'd': + if (strcmp(key, "device") == 0) { + /* stat(2) st_rdev field, e.g. the major/minor IDs + * of a char/block special file */ + int r; + dev_t dev; + + *parsed_kws |= MTREE_HAS_DEVICE; + r = parse_device(&dev, &a->archive, val); + if (r == ARCHIVE_OK) + archive_entry_set_rdev(entry, dev); + return r; + } + __LA_FALLTHROUGH; + case 'f': + if (strcmp(key, "flags") == 0) { + *parsed_kws |= MTREE_HAS_FFLAGS; + archive_entry_copy_fflags_text(entry, val); + break; + } + __LA_FALLTHROUGH; + case 'g': + if (strcmp(key, "gid") == 0) { + *parsed_kws |= MTREE_HAS_GID; + archive_entry_set_gid(entry, mtree_atol(&val, 10)); + break; + } + if (strcmp(key, "gname") == 0) { + *parsed_kws |= MTREE_HAS_GNAME; + archive_entry_copy_gname(entry, val); + break; + } + __LA_FALLTHROUGH; + case 'i': + if (strcmp(key, "inode") == 0) { + archive_entry_set_ino(entry, mtree_atol(&val, 10)); + break; + } + __LA_FALLTHROUGH; + case 'l': + if (strcmp(key, "link") == 0) { + archive_entry_copy_symlink(entry, val); + break; + } + __LA_FALLTHROUGH; + case 'm': + if (strcmp(key, "md5") == 0 || strcmp(key, "md5digest") == 0) + break; + if (strcmp(key, "mode") == 0) { + if (val[0] >= '0' && val[0] <= '7') { + *parsed_kws |= MTREE_HAS_PERM; + archive_entry_set_perm(entry, + (mode_t)mtree_atol(&val, 8)); + } else { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Symbolic or non-octal mode \"%s\" unsupported", val); + return ARCHIVE_WARN; + } + break; + } + __LA_FALLTHROUGH; + case 'n': + if (strcmp(key, "nlink") == 0) { + *parsed_kws |= MTREE_HAS_NLINK; + archive_entry_set_nlink(entry, + (unsigned int)mtree_atol(&val, 10)); + break; + } + __LA_FALLTHROUGH; + case 'r': + if (strcmp(key, "resdevice") == 0) { + /* stat(2) st_dev field, e.g. the device ID where the + * inode resides */ + int r; + dev_t dev; + + r = parse_device(&dev, &a->archive, val); + if (r == ARCHIVE_OK) + archive_entry_set_dev(entry, dev); + return r; + } + if (strcmp(key, "rmd160") == 0 || + strcmp(key, "rmd160digest") == 0) + break; + __LA_FALLTHROUGH; + case 's': + if (strcmp(key, "sha1") == 0 || strcmp(key, "sha1digest") == 0) + break; + if (strcmp(key, "sha256") == 0 || + strcmp(key, "sha256digest") == 0) + break; + if (strcmp(key, "sha384") == 0 || + strcmp(key, "sha384digest") == 0) + break; + if (strcmp(key, "sha512") == 0 || + strcmp(key, "sha512digest") == 0) + break; + if (strcmp(key, "size") == 0) { + archive_entry_set_size(entry, mtree_atol(&val, 10)); + break; + } + __LA_FALLTHROUGH; + case 't': + if (strcmp(key, "tags") == 0) { + /* + * Comma delimited list of tags. + * Ignore the tags for now, but the interface + * should be extended to allow inclusion/exclusion. + */ + break; + } + if (strcmp(key, "time") == 0) { + int64_t m; + int64_t my_time_t_max = get_time_t_max(); + int64_t my_time_t_min = get_time_t_min(); + long ns = 0; + + *parsed_kws |= MTREE_HAS_MTIME; + m = mtree_atol(&val, 10); + /* Replicate an old mtree bug: + * 123456789.1 represents 123456789 + * seconds and 1 nanosecond. */ + if (*val == '.') { + ++val; + ns = (long)mtree_atol(&val, 10); + if (ns < 0) + ns = 0; + else if (ns > 999999999) + ns = 999999999; + } + if (m > my_time_t_max) + m = my_time_t_max; + else if (m < my_time_t_min) + m = my_time_t_min; + archive_entry_set_mtime(entry, (time_t)m, ns); + break; + } + if (strcmp(key, "type") == 0) { + switch (val[0]) { + case 'b': + if (strcmp(val, "block") == 0) { + archive_entry_set_filetype(entry, AE_IFBLK); + break; + } + __LA_FALLTHROUGH; + case 'c': + if (strcmp(val, "char") == 0) { + archive_entry_set_filetype(entry, + AE_IFCHR); + break; + } + __LA_FALLTHROUGH; + case 'd': + if (strcmp(val, "dir") == 0) { + archive_entry_set_filetype(entry, + AE_IFDIR); + break; + } + __LA_FALLTHROUGH; + case 'f': + if (strcmp(val, "fifo") == 0) { + archive_entry_set_filetype(entry, + AE_IFIFO); + break; + } + if (strcmp(val, "file") == 0) { + archive_entry_set_filetype(entry, + AE_IFREG); + break; + } + __LA_FALLTHROUGH; + case 'l': + if (strcmp(val, "link") == 0) { + archive_entry_set_filetype(entry, + AE_IFLNK); + break; + } + __LA_FALLTHROUGH; + default: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Unrecognized file type \"%s\"; " + "assuming \"file\"", val); + archive_entry_set_filetype(entry, AE_IFREG); + return (ARCHIVE_WARN); + } + *parsed_kws |= MTREE_HAS_TYPE; + break; + } + __LA_FALLTHROUGH; + case 'u': + if (strcmp(key, "uid") == 0) { + *parsed_kws |= MTREE_HAS_UID; + archive_entry_set_uid(entry, mtree_atol(&val, 10)); + break; + } + if (strcmp(key, "uname") == 0) { + *parsed_kws |= MTREE_HAS_UNAME; + archive_entry_copy_uname(entry, val); + break; + } + __LA_FALLTHROUGH; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Unrecognized key %s=%s", key, val); + return (ARCHIVE_WARN); + } + return (ARCHIVE_OK); +} + +static int +read_data(struct archive_read *a, const void **buff, size_t *size, + int64_t *offset) +{ + size_t bytes_to_read; + ssize_t bytes_read; + struct mtree *mtree; + + mtree = (struct mtree *)(a->format->data); + if (mtree->fd < 0) { + *buff = NULL; + *offset = 0; + *size = 0; + return (ARCHIVE_EOF); + } + if (mtree->buff == NULL) { + mtree->buffsize = 64 * 1024; + mtree->buff = malloc(mtree->buffsize); + if (mtree->buff == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + } + + *buff = mtree->buff; + *offset = mtree->offset; + if ((int64_t)mtree->buffsize > mtree->cur_size - mtree->offset) + bytes_to_read = (size_t)(mtree->cur_size - mtree->offset); + else + bytes_to_read = mtree->buffsize; + bytes_read = read(mtree->fd, mtree->buff, bytes_to_read); + if (bytes_read < 0) { + archive_set_error(&a->archive, errno, "Can't read"); + return (ARCHIVE_WARN); + } + if (bytes_read == 0) { + *size = 0; + return (ARCHIVE_EOF); + } + mtree->offset += bytes_read; + *size = bytes_read; + return (ARCHIVE_OK); +} + +/* Skip does nothing except possibly close the contents file. */ +static int +skip(struct archive_read *a) +{ + struct mtree *mtree; + + mtree = (struct mtree *)(a->format->data); + if (mtree->fd >= 0) { + close(mtree->fd); + mtree->fd = -1; + } + return (ARCHIVE_OK); +} + +/* + * Since parsing backslash sequences always makes strings shorter, + * we can always do this conversion in-place. + */ +static void +parse_escapes(char *src, struct mtree_entry *mentry) +{ + char *dest = src; + char c; + + if (mentry != NULL && strcmp(src, ".") == 0) + mentry->full = 1; + + while (*src != '\0') { + c = *src++; + if (c == '/' && mentry != NULL) + mentry->full = 1; + if (c == '\\') { + switch (src[0]) { + case '0': + if (src[1] < '0' || src[1] > '7') { + c = 0; + ++src; + break; + } + /* FALLTHROUGH */ + case '1': + case '2': + case '3': + if (src[1] >= '0' && src[1] <= '7' && + src[2] >= '0' && src[2] <= '7') { + c = (src[0] - '0') << 6; + c |= (src[1] - '0') << 3; + c |= (src[2] - '0'); + src += 3; + } + break; + case 'a': + c = '\a'; + ++src; + break; + case 'b': + c = '\b'; + ++src; + break; + case 'f': + c = '\f'; + ++src; + break; + case 'n': + c = '\n'; + ++src; + break; + case 'r': + c = '\r'; + ++src; + break; + case 's': + c = ' '; + ++src; + break; + case 't': + c = '\t'; + ++src; + break; + case 'v': + c = '\v'; + ++src; + break; + case '\\': + c = '\\'; + ++src; + break; + } + } + *dest++ = c; + } + *dest = '\0'; +} + +/* Parse a hex digit. */ +static int +parsedigit(char c) +{ + if (c >= '0' && c <= '9') + return c - '0'; + else if (c >= 'a' && c <= 'f') + return c - 'a'; + else if (c >= 'A' && c <= 'F') + return c - 'A'; + else + return -1; +} + +/* + * Note that this implementation does not (and should not!) obey + * locale settings; you cannot simply substitute strtol here, since + * it does obey locale. + */ +static int64_t +mtree_atol(char **p, int base) +{ + int64_t l, limit; + int digit, last_digit_limit; + + if (base == 0) { + if (**p != '0') + base = 10; + else if ((*p)[1] == 'x' || (*p)[1] == 'X') { + *p += 2; + base = 16; + } else { + base = 8; + } + } + + if (**p == '-') { + limit = INT64_MIN / base; + last_digit_limit = INT64_MIN % base; + ++(*p); + + l = 0; + digit = parsedigit(**p); + while (digit >= 0 && digit < base) { + if (l < limit || (l == limit && digit > last_digit_limit)) + return INT64_MIN; + l = (l * base) - digit; + digit = parsedigit(*++(*p)); + } + return l; + } else { + limit = INT64_MAX / base; + last_digit_limit = INT64_MAX % base; + + l = 0; + digit = parsedigit(**p); + while (digit >= 0 && digit < base) { + if (l > limit || (l == limit && digit > last_digit_limit)) + return INT64_MAX; + l = (l * base) + digit; + digit = parsedigit(*++(*p)); + } + return l; + } +} + +/* + * Returns length of line (including trailing newline) + * or negative on error. 'start' argument is updated to + * point to first character of line. + */ +static ssize_t +readline(struct archive_read *a, struct mtree *mtree, char **start, + ssize_t limit) +{ + ssize_t bytes_read; + ssize_t total_size = 0; + ssize_t find_off = 0; + const void *t; + void *nl; + char *u; + + /* Accumulate line in a line buffer. */ + for (;;) { + /* Read some more. */ + t = __archive_read_ahead(a, 1, &bytes_read); + if (t == NULL) + return (0); + if (bytes_read < 0) + return (ARCHIVE_FATAL); + nl = memchr(t, '\n', bytes_read); + /* If we found '\n', trim the read to end exactly there. */ + if (nl != NULL) { + bytes_read = ((const char *)nl) - ((const char *)t) + 1; + } + if (total_size + bytes_read + 1 > limit) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Line too long"); + return (ARCHIVE_FATAL); + } + if (archive_string_ensure(&mtree->line, + total_size + bytes_read + 1) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate working buffer"); + return (ARCHIVE_FATAL); + } + /* Append new bytes to string. */ + memcpy(mtree->line.s + total_size, t, bytes_read); + __archive_read_consume(a, bytes_read); + total_size += bytes_read; + mtree->line.s[total_size] = '\0'; + + for (u = mtree->line.s + find_off; *u; ++u) { + if (u[0] == '\n') { + /* Ends with unescaped newline. */ + *start = mtree->line.s; + return total_size; + } else if (u[0] == '#') { + /* Ends with comment sequence #...\n */ + if (nl == NULL) { + /* But we've not found the \n yet */ + break; + } + } else if (u[0] == '\\') { + if (u[1] == '\n') { + /* Trim escaped newline. */ + total_size -= 2; + mtree->line.s[total_size] = '\0'; + break; + } else if (u[1] != '\0') { + /* Skip the two-char escape sequence */ + ++u; + } + } + } + find_off = u - mtree->line.s; + } +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_rar.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_rar.c new file mode 100644 index 0000000000..98efbb1a6c --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_rar.c @@ -0,0 +1,2999 @@ +/*- +* Copyright (c) 2003-2007 Tim Kientzle +* Copyright (c) 2011 Andres Mejia +* 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(S) ``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(S) 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. +*/ + +#include "archive_platform.h" + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <time.h> +#include <limits.h> +#ifdef HAVE_ZLIB_H +#include <zlib.h> /* crc32 */ +#endif + +#include "archive.h" +#ifndef HAVE_ZLIB_H +#include "archive_crc32.h" +#endif +#include "archive_endian.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_ppmd7_private.h" +#include "archive_private.h" +#include "archive_read_private.h" + +/* RAR signature, also known as the mark header */ +#define RAR_SIGNATURE "\x52\x61\x72\x21\x1A\x07\x00" + +/* Header types */ +#define MARK_HEAD 0x72 +#define MAIN_HEAD 0x73 +#define FILE_HEAD 0x74 +#define COMM_HEAD 0x75 +#define AV_HEAD 0x76 +#define SUB_HEAD 0x77 +#define PROTECT_HEAD 0x78 +#define SIGN_HEAD 0x79 +#define NEWSUB_HEAD 0x7a +#define ENDARC_HEAD 0x7b + +/* Main Header Flags */ +#define MHD_VOLUME 0x0001 +#define MHD_COMMENT 0x0002 +#define MHD_LOCK 0x0004 +#define MHD_SOLID 0x0008 +#define MHD_NEWNUMBERING 0x0010 +#define MHD_AV 0x0020 +#define MHD_PROTECT 0x0040 +#define MHD_PASSWORD 0x0080 +#define MHD_FIRSTVOLUME 0x0100 +#define MHD_ENCRYPTVER 0x0200 + +/* Flags common to all headers */ +#define HD_MARKDELETION 0x4000 +#define HD_ADD_SIZE_PRESENT 0x8000 + +/* File Header Flags */ +#define FHD_SPLIT_BEFORE 0x0001 +#define FHD_SPLIT_AFTER 0x0002 +#define FHD_PASSWORD 0x0004 +#define FHD_COMMENT 0x0008 +#define FHD_SOLID 0x0010 +#define FHD_LARGE 0x0100 +#define FHD_UNICODE 0x0200 +#define FHD_SALT 0x0400 +#define FHD_VERSION 0x0800 +#define FHD_EXTTIME 0x1000 +#define FHD_EXTFLAGS 0x2000 + +/* File dictionary sizes */ +#define DICTIONARY_SIZE_64 0x00 +#define DICTIONARY_SIZE_128 0x20 +#define DICTIONARY_SIZE_256 0x40 +#define DICTIONARY_SIZE_512 0x60 +#define DICTIONARY_SIZE_1024 0x80 +#define DICTIONARY_SIZE_2048 0xA0 +#define DICTIONARY_SIZE_4096 0xC0 +#define FILE_IS_DIRECTORY 0xE0 +#define DICTIONARY_MASK FILE_IS_DIRECTORY + +/* OS Flags */ +#define OS_MSDOS 0 +#define OS_OS2 1 +#define OS_WIN32 2 +#define OS_UNIX 3 +#define OS_MAC_OS 4 +#define OS_BEOS 5 + +/* Compression Methods */ +#define COMPRESS_METHOD_STORE 0x30 +/* LZSS */ +#define COMPRESS_METHOD_FASTEST 0x31 +#define COMPRESS_METHOD_FAST 0x32 +#define COMPRESS_METHOD_NORMAL 0x33 +/* PPMd Variant H */ +#define COMPRESS_METHOD_GOOD 0x34 +#define COMPRESS_METHOD_BEST 0x35 + +#define CRC_POLYNOMIAL 0xEDB88320 + +#define NS_UNIT 10000000 + +#define DICTIONARY_MAX_SIZE 0x400000 + +#define MAINCODE_SIZE 299 +#define OFFSETCODE_SIZE 60 +#define LOWOFFSETCODE_SIZE 17 +#define LENGTHCODE_SIZE 28 +#define HUFFMAN_TABLE_SIZE \ + MAINCODE_SIZE + OFFSETCODE_SIZE + LOWOFFSETCODE_SIZE + LENGTHCODE_SIZE + +#define MAX_SYMBOL_LENGTH 0xF +#define MAX_SYMBOLS 20 + +/* + * Considering L1,L2 cache miss and a calling of write system-call, + * the best size of the output buffer(uncompressed buffer) is 128K. + * If the structure of extracting process is changed, this value + * might be researched again. + */ +#define UNP_BUFFER_SIZE (128 * 1024) + +/* Define this here for non-Windows platforms */ +#if !((defined(__WIN32__) || defined(_WIN32) || defined(__WIN32)) && !defined(__CYGWIN__)) +#define FILE_ATTRIBUTE_DIRECTORY 0x10 +#endif + +#undef minimum +#define minimum(a, b) ((a)<(b)?(a):(b)) + +/* Fields common to all headers */ +struct rar_header +{ + char crc[2]; + char type; + char flags[2]; + char size[2]; +}; + +/* Fields common to all file headers */ +struct rar_file_header +{ + char pack_size[4]; + char unp_size[4]; + char host_os; + char file_crc[4]; + char file_time[4]; + char unp_ver; + char method; + char name_size[2]; + char file_attr[4]; +}; + +struct huffman_tree_node +{ + int branches[2]; +}; + +struct huffman_table_entry +{ + unsigned int length; + int value; +}; + +struct huffman_code +{ + struct huffman_tree_node *tree; + int numentries; + int numallocatedentries; + int minlength; + int maxlength; + int tablesize; + struct huffman_table_entry *table; +}; + +struct lzss +{ + unsigned char *window; + int mask; + int64_t position; +}; + +struct data_block_offsets +{ + int64_t header_size; + int64_t start_offset; + int64_t end_offset; +}; + +struct rar +{ + /* Entries from main RAR header */ + unsigned main_flags; + unsigned long file_crc; + char reserved1[2]; + char reserved2[4]; + char encryptver; + + /* File header entries */ + char compression_method; + unsigned file_flags; + int64_t packed_size; + int64_t unp_size; + time_t mtime; + long mnsec; + mode_t mode; + char *filename; + char *filename_save; + size_t filename_save_size; + size_t filename_allocated; + + /* File header optional entries */ + char salt[8]; + time_t atime; + long ansec; + time_t ctime; + long cnsec; + time_t arctime; + long arcnsec; + + /* Fields to help with tracking decompression of files. */ + int64_t bytes_unconsumed; + int64_t bytes_remaining; + int64_t bytes_uncopied; + int64_t offset; + int64_t offset_outgoing; + int64_t offset_seek; + char valid; + unsigned int unp_offset; + unsigned int unp_buffer_size; + unsigned char *unp_buffer; + unsigned int dictionary_size; + char start_new_block; + char entry_eof; + unsigned long crc_calculated; + int found_first_header; + char has_endarc_header; + struct data_block_offsets *dbo; + unsigned int cursor; + unsigned int nodes; + char filename_must_match; + + /* LZSS members */ + struct huffman_code maincode; + struct huffman_code offsetcode; + struct huffman_code lowoffsetcode; + struct huffman_code lengthcode; + unsigned char lengthtable[HUFFMAN_TABLE_SIZE]; + struct lzss lzss; + char output_last_match; + unsigned int lastlength; + unsigned int lastoffset; + unsigned int oldoffset[4]; + unsigned int lastlowoffset; + unsigned int numlowoffsetrepeats; + int64_t filterstart; + char start_new_table; + + /* PPMd Variant H members */ + char ppmd_valid; + char ppmd_eod; + char is_ppmd_block; + int ppmd_escape; + CPpmd7 ppmd7_context; + CPpmd7z_RangeDec range_dec; + IByteIn bytein; + + /* + * String conversion object. + */ + int init_default_conversion; + struct archive_string_conv *sconv_default; + struct archive_string_conv *opt_sconv; + struct archive_string_conv *sconv_utf8; + struct archive_string_conv *sconv_utf16be; + + /* + * Bit stream reader. + */ + struct rar_br { +#define CACHE_TYPE uint64_t +#define CACHE_BITS (8 * sizeof(CACHE_TYPE)) + /* Cache buffer. */ + CACHE_TYPE cache_buffer; + /* Indicates how many bits avail in cache_buffer. */ + int cache_avail; + ssize_t avail_in; + const unsigned char *next_in; + } br; + + /* + * Custom field to denote that this archive contains encrypted entries + */ + int has_encrypted_entries; +}; + +static int archive_read_support_format_rar_capabilities(struct archive_read *); +static int archive_read_format_rar_has_encrypted_entries(struct archive_read *); +static int archive_read_format_rar_bid(struct archive_read *, int); +static int archive_read_format_rar_options(struct archive_read *, + const char *, const char *); +static int archive_read_format_rar_read_header(struct archive_read *, + struct archive_entry *); +static int archive_read_format_rar_read_data(struct archive_read *, + const void **, size_t *, int64_t *); +static int archive_read_format_rar_read_data_skip(struct archive_read *a); +static int64_t archive_read_format_rar_seek_data(struct archive_read *, int64_t, + int); +static int archive_read_format_rar_cleanup(struct archive_read *); + +/* Support functions */ +static int read_header(struct archive_read *, struct archive_entry *, char); +static time_t get_time(int); +static int read_exttime(const char *, struct rar *, const char *); +static int read_symlink_stored(struct archive_read *, struct archive_entry *, + struct archive_string_conv *); +static int read_data_stored(struct archive_read *, const void **, size_t *, + int64_t *); +static int read_data_compressed(struct archive_read *, const void **, size_t *, + int64_t *); +static int rar_br_preparation(struct archive_read *, struct rar_br *); +static int parse_codes(struct archive_read *); +static void free_codes(struct archive_read *); +static int read_next_symbol(struct archive_read *, struct huffman_code *); +static int create_code(struct archive_read *, struct huffman_code *, + unsigned char *, int, char); +static int add_value(struct archive_read *, struct huffman_code *, int, int, + int); +static int new_node(struct huffman_code *); +static int make_table(struct archive_read *, struct huffman_code *); +static int make_table_recurse(struct archive_read *, struct huffman_code *, int, + struct huffman_table_entry *, int, int); +static int64_t expand(struct archive_read *, int64_t); +static int copy_from_lzss_window(struct archive_read *, const void **, + int64_t, int); +static const void *rar_read_ahead(struct archive_read *, size_t, ssize_t *); + +/* + * Bit stream reader. + */ +/* Check that the cache buffer has enough bits. */ +#define rar_br_has(br, n) ((br)->cache_avail >= n) +/* Get compressed data by bit. */ +#define rar_br_bits(br, n) \ + (((uint32_t)((br)->cache_buffer >> \ + ((br)->cache_avail - (n)))) & cache_masks[n]) +#define rar_br_bits_forced(br, n) \ + (((uint32_t)((br)->cache_buffer << \ + ((n) - (br)->cache_avail))) & cache_masks[n]) +/* Read ahead to make sure the cache buffer has enough compressed data we + * will use. + * True : completed, there is enough data in the cache buffer. + * False : there is no data in the stream. */ +#define rar_br_read_ahead(a, br, n) \ + ((rar_br_has(br, (n)) || rar_br_fillup(a, br)) || rar_br_has(br, (n))) +/* Notify how many bits we consumed. */ +#define rar_br_consume(br, n) ((br)->cache_avail -= (n)) +#define rar_br_consume_unalined_bits(br) ((br)->cache_avail &= ~7) + +static const uint32_t cache_masks[] = { + 0x00000000, 0x00000001, 0x00000003, 0x00000007, + 0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F, + 0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF, + 0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF, + 0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF, + 0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF, + 0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, + 0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, + 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* + * Shift away used bits in the cache data and fill it up with following bits. + * Call this when cache buffer does not have enough bits you need. + * + * Returns 1 if the cache buffer is full. + * Returns 0 if the cache buffer is not full; input buffer is empty. + */ +static int +rar_br_fillup(struct archive_read *a, struct rar_br *br) +{ + struct rar *rar = (struct rar *)(a->format->data); + int n = CACHE_BITS - br->cache_avail; + + for (;;) { + switch (n >> 3) { + case 8: + if (br->avail_in >= 8) { + br->cache_buffer = + ((uint64_t)br->next_in[0]) << 56 | + ((uint64_t)br->next_in[1]) << 48 | + ((uint64_t)br->next_in[2]) << 40 | + ((uint64_t)br->next_in[3]) << 32 | + ((uint32_t)br->next_in[4]) << 24 | + ((uint32_t)br->next_in[5]) << 16 | + ((uint32_t)br->next_in[6]) << 8 | + (uint32_t)br->next_in[7]; + br->next_in += 8; + br->avail_in -= 8; + br->cache_avail += 8 * 8; + rar->bytes_unconsumed += 8; + rar->bytes_remaining -= 8; + return (1); + } + break; + case 7: + if (br->avail_in >= 7) { + br->cache_buffer = + (br->cache_buffer << 56) | + ((uint64_t)br->next_in[0]) << 48 | + ((uint64_t)br->next_in[1]) << 40 | + ((uint64_t)br->next_in[2]) << 32 | + ((uint32_t)br->next_in[3]) << 24 | + ((uint32_t)br->next_in[4]) << 16 | + ((uint32_t)br->next_in[5]) << 8 | + (uint32_t)br->next_in[6]; + br->next_in += 7; + br->avail_in -= 7; + br->cache_avail += 7 * 8; + rar->bytes_unconsumed += 7; + rar->bytes_remaining -= 7; + return (1); + } + break; + case 6: + if (br->avail_in >= 6) { + br->cache_buffer = + (br->cache_buffer << 48) | + ((uint64_t)br->next_in[0]) << 40 | + ((uint64_t)br->next_in[1]) << 32 | + ((uint32_t)br->next_in[2]) << 24 | + ((uint32_t)br->next_in[3]) << 16 | + ((uint32_t)br->next_in[4]) << 8 | + (uint32_t)br->next_in[5]; + br->next_in += 6; + br->avail_in -= 6; + br->cache_avail += 6 * 8; + rar->bytes_unconsumed += 6; + rar->bytes_remaining -= 6; + return (1); + } + break; + case 0: + /* We have enough compressed data in + * the cache buffer.*/ + return (1); + default: + break; + } + if (br->avail_in <= 0) { + + if (rar->bytes_unconsumed > 0) { + /* Consume as much as the decompressor + * actually used. */ + __archive_read_consume(a, rar->bytes_unconsumed); + rar->bytes_unconsumed = 0; + } + br->next_in = rar_read_ahead(a, 1, &(br->avail_in)); + if (br->next_in == NULL) + return (0); + if (br->avail_in == 0) + return (0); + } + br->cache_buffer = + (br->cache_buffer << 8) | *br->next_in++; + br->avail_in--; + br->cache_avail += 8; + n -= 8; + rar->bytes_unconsumed++; + rar->bytes_remaining--; + } +} + +static int +rar_br_preparation(struct archive_read *a, struct rar_br *br) +{ + struct rar *rar = (struct rar *)(a->format->data); + + if (rar->bytes_remaining > 0) { + br->next_in = rar_read_ahead(a, 1, &(br->avail_in)); + if (br->next_in == NULL) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated RAR file data"); + return (ARCHIVE_FATAL); + } + if (br->cache_avail == 0) + (void)rar_br_fillup(a, br); + } + return (ARCHIVE_OK); +} + +/* Find last bit set */ +static inline int +rar_fls(unsigned int word) +{ + word |= (word >> 1); + word |= (word >> 2); + word |= (word >> 4); + word |= (word >> 8); + word |= (word >> 16); + return word - (word >> 1); +} + +/* LZSS functions */ +static inline int64_t +lzss_position(struct lzss *lzss) +{ + return lzss->position; +} + +static inline int +lzss_mask(struct lzss *lzss) +{ + return lzss->mask; +} + +static inline int +lzss_size(struct lzss *lzss) +{ + return lzss->mask + 1; +} + +static inline int +lzss_offset_for_position(struct lzss *lzss, int64_t pos) +{ + return (int)(pos & lzss->mask); +} + +static inline unsigned char * +lzss_pointer_for_position(struct lzss *lzss, int64_t pos) +{ + return &lzss->window[lzss_offset_for_position(lzss, pos)]; +} + +static inline int +lzss_current_offset(struct lzss *lzss) +{ + return lzss_offset_for_position(lzss, lzss->position); +} + +static inline uint8_t * +lzss_current_pointer(struct lzss *lzss) +{ + return lzss_pointer_for_position(lzss, lzss->position); +} + +static inline void +lzss_emit_literal(struct rar *rar, uint8_t literal) +{ + *lzss_current_pointer(&rar->lzss) = literal; + rar->lzss.position++; +} + +static inline void +lzss_emit_match(struct rar *rar, int offset, int length) +{ + int dstoffs = lzss_current_offset(&rar->lzss); + int srcoffs = (dstoffs - offset) & lzss_mask(&rar->lzss); + int l, li, remaining; + unsigned char *d, *s; + + remaining = length; + while (remaining > 0) { + l = remaining; + if (dstoffs > srcoffs) { + if (l > lzss_size(&rar->lzss) - dstoffs) + l = lzss_size(&rar->lzss) - dstoffs; + } else { + if (l > lzss_size(&rar->lzss) - srcoffs) + l = lzss_size(&rar->lzss) - srcoffs; + } + d = &(rar->lzss.window[dstoffs]); + s = &(rar->lzss.window[srcoffs]); + if ((dstoffs + l < srcoffs) || (srcoffs + l < dstoffs)) + memcpy(d, s, l); + else { + for (li = 0; li < l; li++) + d[li] = s[li]; + } + remaining -= l; + dstoffs = (dstoffs + l) & lzss_mask(&(rar->lzss)); + srcoffs = (srcoffs + l) & lzss_mask(&(rar->lzss)); + } + rar->lzss.position += length; +} + +static Byte +ppmd_read(void *p) +{ + struct archive_read *a = ((IByteIn*)p)->a; + struct rar *rar = (struct rar *)(a->format->data); + struct rar_br *br = &(rar->br); + Byte b; + if (!rar_br_read_ahead(a, br, 8)) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated RAR file data"); + rar->valid = 0; + return 0; + } + b = rar_br_bits(br, 8); + rar_br_consume(br, 8); + return b; +} + +int +archive_read_support_format_rar(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct rar *rar; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, + "archive_read_support_format_rar"); + + rar = (struct rar *)calloc(sizeof(*rar), 1); + if (rar == NULL) + { + archive_set_error(&a->archive, ENOMEM, "Can't allocate rar data"); + return (ARCHIVE_FATAL); + } + + /* + * Until enough data has been read, we cannot tell about + * any encrypted entries yet. + */ + rar->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; + + r = __archive_read_register_format(a, + rar, + "rar", + archive_read_format_rar_bid, + archive_read_format_rar_options, + archive_read_format_rar_read_header, + archive_read_format_rar_read_data, + archive_read_format_rar_read_data_skip, + archive_read_format_rar_seek_data, + archive_read_format_rar_cleanup, + archive_read_support_format_rar_capabilities, + archive_read_format_rar_has_encrypted_entries); + + if (r != ARCHIVE_OK) + free(rar); + return (r); +} + +static int +archive_read_support_format_rar_capabilities(struct archive_read * a) +{ + (void)a; /* UNUSED */ + return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA + | ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA); +} + +static int +archive_read_format_rar_has_encrypted_entries(struct archive_read *_a) +{ + if (_a && _a->format) { + struct rar * rar = (struct rar *)_a->format->data; + if (rar) { + return rar->has_encrypted_entries; + } + } + return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; +} + + +static int +archive_read_format_rar_bid(struct archive_read *a, int best_bid) +{ + const char *p; + + /* If there's already a bid > 30, we'll never win. */ + if (best_bid > 30) + return (-1); + + if ((p = __archive_read_ahead(a, 7, NULL)) == NULL) + return (-1); + + if (memcmp(p, RAR_SIGNATURE, 7) == 0) + return (30); + + if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) { + /* This is a PE file */ + ssize_t offset = 0x10000; + ssize_t window = 4096; + ssize_t bytes_avail; + while (offset + window <= (1024 * 128)) { + const char *buff = __archive_read_ahead(a, offset + window, &bytes_avail); + if (buff == NULL) { + /* Remaining bytes are less than window. */ + window >>= 1; + if (window < 0x40) + return (0); + continue; + } + p = buff + offset; + while (p + 7 < buff + bytes_avail) { + if (memcmp(p, RAR_SIGNATURE, 7) == 0) + return (30); + p += 0x10; + } + offset = p - buff; + } + } + return (0); +} + +static int +skip_sfx(struct archive_read *a) +{ + const void *h; + const char *p, *q; + size_t skip, total; + ssize_t bytes, window; + + total = 0; + window = 4096; + while (total + window <= (1024 * 128)) { + h = __archive_read_ahead(a, window, &bytes); + if (h == NULL) { + /* Remaining bytes are less than window. */ + window >>= 1; + if (window < 0x40) + goto fatal; + continue; + } + if (bytes < 0x40) + goto fatal; + p = h; + q = p + bytes; + + /* + * Scan ahead until we find something that looks + * like the RAR header. + */ + while (p + 7 < q) { + if (memcmp(p, RAR_SIGNATURE, 7) == 0) { + skip = p - (const char *)h; + __archive_read_consume(a, skip); + return (ARCHIVE_OK); + } + p += 0x10; + } + skip = p - (const char *)h; + __archive_read_consume(a, skip); + total += skip; + } +fatal: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Couldn't find out RAR header"); + return (ARCHIVE_FATAL); +} + +static int +archive_read_format_rar_options(struct archive_read *a, + const char *key, const char *val) +{ + struct rar *rar; + int ret = ARCHIVE_FAILED; + + rar = (struct rar *)(a->format->data); + if (strcmp(key, "hdrcharset") == 0) { + if (val == NULL || val[0] == 0) + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "rar: hdrcharset option needs a character-set name"); + else { + rar->opt_sconv = + archive_string_conversion_from_charset( + &a->archive, val, 0); + if (rar->opt_sconv != NULL) + ret = ARCHIVE_OK; + else + ret = ARCHIVE_FATAL; + } + return (ret); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static int +archive_read_format_rar_read_header(struct archive_read *a, + struct archive_entry *entry) +{ + const void *h; + const char *p; + struct rar *rar; + size_t skip; + char head_type; + int ret; + unsigned flags; + unsigned long crc32_expected; + + a->archive.archive_format = ARCHIVE_FORMAT_RAR; + if (a->archive.archive_format_name == NULL) + a->archive.archive_format_name = "RAR"; + + rar = (struct rar *)(a->format->data); + + /* + * It should be sufficient to call archive_read_next_header() for + * a reader to determine if an entry is encrypted or not. If the + * encryption of an entry is only detectable when calling + * archive_read_data(), so be it. We'll do the same check there + * as well. + */ + if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { + rar->has_encrypted_entries = 0; + } + + /* RAR files can be generated without EOF headers, so return ARCHIVE_EOF if + * this fails. + */ + if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) + return (ARCHIVE_EOF); + + p = h; + if (rar->found_first_header == 0 && + ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0)) { + /* This is an executable ? Must be self-extracting... */ + ret = skip_sfx(a); + if (ret < ARCHIVE_WARN) + return (ret); + } + rar->found_first_header = 1; + + while (1) + { + unsigned long crc32_val; + + if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) + return (ARCHIVE_FATAL); + p = h; + + head_type = p[2]; + switch(head_type) + { + case MARK_HEAD: + if (memcmp(p, RAR_SIGNATURE, 7) != 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid marker header"); + return (ARCHIVE_FATAL); + } + __archive_read_consume(a, 7); + break; + + case MAIN_HEAD: + rar->main_flags = archive_le16dec(p + 3); + skip = archive_le16dec(p + 5); + if (skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid header size"); + return (ARCHIVE_FATAL); + } + if ((h = __archive_read_ahead(a, skip, NULL)) == NULL) + return (ARCHIVE_FATAL); + p = h; + memcpy(rar->reserved1, p + 7, sizeof(rar->reserved1)); + memcpy(rar->reserved2, p + 7 + sizeof(rar->reserved1), + sizeof(rar->reserved2)); + if (rar->main_flags & MHD_ENCRYPTVER) { + if (skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)+1) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid header size"); + return (ARCHIVE_FATAL); + } + rar->encryptver = *(p + 7 + sizeof(rar->reserved1) + + sizeof(rar->reserved2)); + } + + /* Main header is password encrypted, so we cannot read any + file names or any other info about files from the header. */ + if (rar->main_flags & MHD_PASSWORD) + { + archive_entry_set_is_metadata_encrypted(entry, 1); + archive_entry_set_is_data_encrypted(entry, 1); + rar->has_encrypted_entries = 1; + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "RAR encryption support unavailable."); + return (ARCHIVE_FATAL); + } + + crc32_val = crc32(0, (const unsigned char *)p + 2, (unsigned)skip - 2); + if ((crc32_val & 0xffff) != archive_le16dec(p)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Header CRC error"); + return (ARCHIVE_FATAL); + } + __archive_read_consume(a, skip); + break; + + case FILE_HEAD: + return read_header(a, entry, head_type); + + case COMM_HEAD: + case AV_HEAD: + case SUB_HEAD: + case PROTECT_HEAD: + case SIGN_HEAD: + case ENDARC_HEAD: + flags = archive_le16dec(p + 3); + skip = archive_le16dec(p + 5); + if (skip < 7) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid header size too small"); + return (ARCHIVE_FATAL); + } + if (flags & HD_ADD_SIZE_PRESENT) + { + if (skip < 7 + 4) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid header size too small"); + return (ARCHIVE_FATAL); + } + if ((h = __archive_read_ahead(a, skip, NULL)) == NULL) + return (ARCHIVE_FATAL); + p = h; + skip += archive_le32dec(p + 7); + } + + /* Skip over the 2-byte CRC at the beginning of the header. */ + crc32_expected = archive_le16dec(p); + __archive_read_consume(a, 2); + skip -= 2; + + /* Skim the entire header and compute the CRC. */ + crc32_val = 0; + while (skip > 0) { + size_t to_read = skip; + ssize_t did_read; + if (to_read > 32 * 1024) { + to_read = 32 * 1024; + } + if ((h = __archive_read_ahead(a, to_read, &did_read)) == NULL) { + return (ARCHIVE_FATAL); + } + p = h; + crc32_val = crc32(crc32_val, (const unsigned char *)p, (unsigned)did_read); + __archive_read_consume(a, did_read); + skip -= did_read; + } + if ((crc32_val & 0xffff) != crc32_expected) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Header CRC error"); + return (ARCHIVE_FATAL); + } + if (head_type == ENDARC_HEAD) + return (ARCHIVE_EOF); + break; + + case NEWSUB_HEAD: + if ((ret = read_header(a, entry, head_type)) < ARCHIVE_WARN) + return ret; + break; + + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Bad RAR file"); + return (ARCHIVE_FATAL); + } + } +} + +static int +archive_read_format_rar_read_data(struct archive_read *a, const void **buff, + size_t *size, int64_t *offset) +{ + struct rar *rar = (struct rar *)(a->format->data); + int ret; + + if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { + rar->has_encrypted_entries = 0; + } + + if (rar->bytes_unconsumed > 0) { + /* Consume as much as the decompressor actually used. */ + __archive_read_consume(a, rar->bytes_unconsumed); + rar->bytes_unconsumed = 0; + } + + *buff = NULL; + if (rar->entry_eof || rar->offset_seek >= rar->unp_size) { + *size = 0; + *offset = rar->offset; + if (*offset < rar->unp_size) + *offset = rar->unp_size; + return (ARCHIVE_EOF); + } + + switch (rar->compression_method) + { + case COMPRESS_METHOD_STORE: + ret = read_data_stored(a, buff, size, offset); + break; + + case COMPRESS_METHOD_FASTEST: + case COMPRESS_METHOD_FAST: + case COMPRESS_METHOD_NORMAL: + case COMPRESS_METHOD_GOOD: + case COMPRESS_METHOD_BEST: + ret = read_data_compressed(a, buff, size, offset); + if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN) { + __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context); + rar->start_new_table = 1; + rar->ppmd_valid = 0; + } + break; + + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Unsupported compression method for RAR file."); + ret = ARCHIVE_FATAL; + break; + } + return (ret); +} + +static int +archive_read_format_rar_read_data_skip(struct archive_read *a) +{ + struct rar *rar; + int64_t bytes_skipped; + int ret; + + rar = (struct rar *)(a->format->data); + + if (rar->bytes_unconsumed > 0) { + /* Consume as much as the decompressor actually used. */ + __archive_read_consume(a, rar->bytes_unconsumed); + rar->bytes_unconsumed = 0; + } + + if (rar->bytes_remaining > 0) { + bytes_skipped = __archive_read_consume(a, rar->bytes_remaining); + if (bytes_skipped < 0) + return (ARCHIVE_FATAL); + } + + /* Compressed data to skip must be read from each header in a multivolume + * archive. + */ + if (rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER) + { + ret = archive_read_format_rar_read_header(a, a->entry); + if (ret == (ARCHIVE_EOF)) + ret = archive_read_format_rar_read_header(a, a->entry); + if (ret != (ARCHIVE_OK)) + return ret; + return archive_read_format_rar_read_data_skip(a); + } + + return (ARCHIVE_OK); +} + +static int64_t +archive_read_format_rar_seek_data(struct archive_read *a, int64_t offset, + int whence) +{ + int64_t client_offset, ret; + unsigned int i; + struct rar *rar = (struct rar *)(a->format->data); + + if (rar->compression_method == COMPRESS_METHOD_STORE) + { + /* Modify the offset for use with SEEK_SET */ + switch (whence) + { + case SEEK_CUR: + client_offset = rar->offset_seek; + break; + case SEEK_END: + client_offset = rar->unp_size; + break; + case SEEK_SET: + default: + client_offset = 0; + } + client_offset += offset; + if (client_offset < 0) + { + /* Can't seek past beginning of data block */ + return -1; + } + else if (client_offset > rar->unp_size) + { + /* + * Set the returned offset but only seek to the end of + * the data block. + */ + rar->offset_seek = client_offset; + client_offset = rar->unp_size; + } + + client_offset += rar->dbo[0].start_offset; + i = 0; + while (i < rar->cursor) + { + i++; + client_offset += rar->dbo[i].start_offset - rar->dbo[i-1].end_offset; + } + if (rar->main_flags & MHD_VOLUME) + { + /* Find the appropriate offset among the multivolume archive */ + while (1) + { + if (client_offset < rar->dbo[rar->cursor].start_offset && + rar->file_flags & FHD_SPLIT_BEFORE) + { + /* Search backwards for the correct data block */ + if (rar->cursor == 0) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Attempt to seek past beginning of RAR data block"); + return (ARCHIVE_FAILED); + } + rar->cursor--; + client_offset -= rar->dbo[rar->cursor+1].start_offset - + rar->dbo[rar->cursor].end_offset; + if (client_offset < rar->dbo[rar->cursor].start_offset) + continue; + ret = __archive_read_seek(a, rar->dbo[rar->cursor].start_offset - + rar->dbo[rar->cursor].header_size, SEEK_SET); + if (ret < (ARCHIVE_OK)) + return ret; + ret = archive_read_format_rar_read_header(a, a->entry); + if (ret != (ARCHIVE_OK)) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Error during seek of RAR file"); + return (ARCHIVE_FAILED); + } + rar->cursor--; + break; + } + else if (client_offset > rar->dbo[rar->cursor].end_offset && + rar->file_flags & FHD_SPLIT_AFTER) + { + /* Search forward for the correct data block */ + rar->cursor++; + if (rar->cursor < rar->nodes && + client_offset > rar->dbo[rar->cursor].end_offset) + { + client_offset += rar->dbo[rar->cursor].start_offset - + rar->dbo[rar->cursor-1].end_offset; + continue; + } + rar->cursor--; + ret = __archive_read_seek(a, rar->dbo[rar->cursor].end_offset, + SEEK_SET); + if (ret < (ARCHIVE_OK)) + return ret; + ret = archive_read_format_rar_read_header(a, a->entry); + if (ret == (ARCHIVE_EOF)) + { + rar->has_endarc_header = 1; + ret = archive_read_format_rar_read_header(a, a->entry); + } + if (ret != (ARCHIVE_OK)) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Error during seek of RAR file"); + return (ARCHIVE_FAILED); + } + client_offset += rar->dbo[rar->cursor].start_offset - + rar->dbo[rar->cursor-1].end_offset; + continue; + } + break; + } + } + + ret = __archive_read_seek(a, client_offset, SEEK_SET); + if (ret < (ARCHIVE_OK)) + return ret; + rar->bytes_remaining = rar->dbo[rar->cursor].end_offset - ret; + i = rar->cursor; + while (i > 0) + { + i--; + ret -= rar->dbo[i+1].start_offset - rar->dbo[i].end_offset; + } + ret -= rar->dbo[0].start_offset; + + /* Always restart reading the file after a seek */ + __archive_reset_read_data(&a->archive); + + rar->bytes_unconsumed = 0; + rar->offset = 0; + + /* + * If a seek past the end of file was requested, return the requested + * offset. + */ + if (ret == rar->unp_size && rar->offset_seek > rar->unp_size) + return rar->offset_seek; + + /* Return the new offset */ + rar->offset_seek = ret; + return rar->offset_seek; + } + else + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Seeking of compressed RAR files is unsupported"); + } + return (ARCHIVE_FAILED); +} + +static int +archive_read_format_rar_cleanup(struct archive_read *a) +{ + struct rar *rar; + + rar = (struct rar *)(a->format->data); + free_codes(a); + free(rar->filename); + free(rar->filename_save); + free(rar->dbo); + free(rar->unp_buffer); + free(rar->lzss.window); + __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context); + free(rar); + (a->format->data) = NULL; + return (ARCHIVE_OK); +} + +static int +read_header(struct archive_read *a, struct archive_entry *entry, + char head_type) +{ + const void *h; + const char *p, *endp; + struct rar *rar; + struct rar_header rar_header; + struct rar_file_header file_header; + int64_t header_size; + unsigned filename_size, end; + char *filename; + char *strp; + char packed_size[8]; + char unp_size[8]; + int ttime; + struct archive_string_conv *sconv, *fn_sconv; + unsigned long crc32_val; + int ret = (ARCHIVE_OK), ret2; + + rar = (struct rar *)(a->format->data); + + /* Setup a string conversion object for non-rar-unicode filenames. */ + sconv = rar->opt_sconv; + if (sconv == NULL) { + if (!rar->init_default_conversion) { + rar->sconv_default = + archive_string_default_conversion_for_read( + &(a->archive)); + rar->init_default_conversion = 1; + } + sconv = rar->sconv_default; + } + + + if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) + return (ARCHIVE_FATAL); + p = h; + memcpy(&rar_header, p, sizeof(rar_header)); + rar->file_flags = archive_le16dec(rar_header.flags); + header_size = archive_le16dec(rar_header.size); + if (header_size < (int64_t)sizeof(file_header) + 7) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid header size"); + return (ARCHIVE_FATAL); + } + crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2); + __archive_read_consume(a, 7); + + if (!(rar->file_flags & FHD_SOLID)) + { + rar->compression_method = 0; + rar->packed_size = 0; + rar->unp_size = 0; + rar->mtime = 0; + rar->ctime = 0; + rar->atime = 0; + rar->arctime = 0; + rar->mode = 0; + memset(&rar->salt, 0, sizeof(rar->salt)); + rar->atime = 0; + rar->ansec = 0; + rar->ctime = 0; + rar->cnsec = 0; + rar->mtime = 0; + rar->mnsec = 0; + rar->arctime = 0; + rar->arcnsec = 0; + } + else + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "RAR solid archive support unavailable."); + return (ARCHIVE_FATAL); + } + + if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) + return (ARCHIVE_FATAL); + + /* File Header CRC check. */ + crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7)); + if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Header CRC error"); + return (ARCHIVE_FATAL); + } + /* If no CRC error, Go on parsing File Header. */ + p = h; + endp = p + header_size - 7; + memcpy(&file_header, p, sizeof(file_header)); + p += sizeof(file_header); + + rar->compression_method = file_header.method; + + ttime = archive_le32dec(file_header.file_time); + rar->mtime = get_time(ttime); + + rar->file_crc = archive_le32dec(file_header.file_crc); + + if (rar->file_flags & FHD_PASSWORD) + { + archive_entry_set_is_data_encrypted(entry, 1); + rar->has_encrypted_entries = 1; + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "RAR encryption support unavailable."); + /* Since it is only the data part itself that is encrypted we can at least + extract information about the currently processed entry and don't need + to return ARCHIVE_FATAL here. */ + /*return (ARCHIVE_FATAL);*/ + } + + if (rar->file_flags & FHD_LARGE) + { + memcpy(packed_size, file_header.pack_size, 4); + memcpy(packed_size + 4, p, 4); /* High pack size */ + p += 4; + memcpy(unp_size, file_header.unp_size, 4); + memcpy(unp_size + 4, p, 4); /* High unpack size */ + p += 4; + rar->packed_size = archive_le64dec(&packed_size); + rar->unp_size = archive_le64dec(&unp_size); + } + else + { + rar->packed_size = archive_le32dec(file_header.pack_size); + rar->unp_size = archive_le32dec(file_header.unp_size); + } + + if (rar->packed_size < 0 || rar->unp_size < 0) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid sizes specified."); + return (ARCHIVE_FATAL); + } + + rar->bytes_remaining = rar->packed_size; + + /* TODO: RARv3 subblocks contain comments. For now the complete block is + * consumed at the end. + */ + if (head_type == NEWSUB_HEAD) { + size_t distance = p - (const char *)h; + header_size += rar->packed_size; + /* Make sure we have the extended data. */ + if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) + return (ARCHIVE_FATAL); + p = h; + endp = p + header_size - 7; + p += distance; + } + + filename_size = archive_le16dec(file_header.name_size); + if (p + filename_size > endp) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid filename size"); + return (ARCHIVE_FATAL); + } + if (rar->filename_allocated < filename_size * 2 + 2) { + char *newptr; + size_t newsize = filename_size * 2 + 2; + newptr = realloc(rar->filename, newsize); + if (newptr == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Couldn't allocate memory."); + return (ARCHIVE_FATAL); + } + rar->filename = newptr; + rar->filename_allocated = newsize; + } + filename = rar->filename; + memcpy(filename, p, filename_size); + filename[filename_size] = '\0'; + if (rar->file_flags & FHD_UNICODE) + { + if (filename_size != strlen(filename)) + { + unsigned char highbyte, flagbits, flagbyte; + unsigned fn_end, offset; + + end = filename_size; + fn_end = filename_size * 2; + filename_size = 0; + offset = (unsigned)strlen(filename) + 1; + highbyte = *(p + offset++); + flagbits = 0; + flagbyte = 0; + while (offset < end && filename_size < fn_end) + { + if (!flagbits) + { + flagbyte = *(p + offset++); + flagbits = 8; + } + + flagbits -= 2; + switch((flagbyte >> flagbits) & 3) + { + case 0: + filename[filename_size++] = '\0'; + filename[filename_size++] = *(p + offset++); + break; + case 1: + filename[filename_size++] = highbyte; + filename[filename_size++] = *(p + offset++); + break; + case 2: + filename[filename_size++] = *(p + offset + 1); + filename[filename_size++] = *(p + offset); + offset += 2; + break; + case 3: + { + char extra, high; + uint8_t length = *(p + offset++); + + if (length & 0x80) { + extra = *(p + offset++); + high = (char)highbyte; + } else + extra = high = 0; + length = (length & 0x7f) + 2; + while (length && filename_size < fn_end) { + unsigned cp = filename_size >> 1; + filename[filename_size++] = high; + filename[filename_size++] = p[cp] + extra; + length--; + } + } + break; + } + } + if (filename_size > fn_end) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid filename"); + return (ARCHIVE_FATAL); + } + filename[filename_size++] = '\0'; + /* + * Do not increment filename_size here as the computations below + * add the space for the terminating NUL explicitly. + */ + filename[filename_size] = '\0'; + + /* Decoded unicode form is UTF-16BE, so we have to update a string + * conversion object for it. */ + if (rar->sconv_utf16be == NULL) { + rar->sconv_utf16be = archive_string_conversion_from_charset( + &a->archive, "UTF-16BE", 1); + if (rar->sconv_utf16be == NULL) + return (ARCHIVE_FATAL); + } + fn_sconv = rar->sconv_utf16be; + + strp = filename; + while (memcmp(strp, "\x00\x00", 2)) + { + if (!memcmp(strp, "\x00\\", 2)) + *(strp + 1) = '/'; + strp += 2; + } + p += offset; + } else { + /* + * If FHD_UNICODE is set but no unicode data, this file name form + * is UTF-8, so we have to update a string conversion object for + * it accordingly. + */ + if (rar->sconv_utf8 == NULL) { + rar->sconv_utf8 = archive_string_conversion_from_charset( + &a->archive, "UTF-8", 1); + if (rar->sconv_utf8 == NULL) + return (ARCHIVE_FATAL); + } + fn_sconv = rar->sconv_utf8; + while ((strp = strchr(filename, '\\')) != NULL) + *strp = '/'; + p += filename_size; + } + } + else + { + fn_sconv = sconv; + while ((strp = strchr(filename, '\\')) != NULL) + *strp = '/'; + p += filename_size; + } + + /* Split file in multivolume RAR. No more need to process header. */ + if (rar->filename_save && + filename_size == rar->filename_save_size && + !memcmp(rar->filename, rar->filename_save, filename_size + 1)) + { + __archive_read_consume(a, header_size - 7); + rar->cursor++; + if (rar->cursor >= rar->nodes) + { + rar->nodes++; + if ((rar->dbo = + realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL) + { + archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); + return (ARCHIVE_FATAL); + } + rar->dbo[rar->cursor].header_size = header_size; + rar->dbo[rar->cursor].start_offset = -1; + rar->dbo[rar->cursor].end_offset = -1; + } + if (rar->dbo[rar->cursor].start_offset < 0) + { + rar->dbo[rar->cursor].start_offset = a->filter->position; + rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset + + rar->packed_size; + } + return ret; + } + else if (rar->filename_must_match) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Mismatch of file parts split across multi-volume archive"); + return (ARCHIVE_FATAL); + } + + rar->filename_save = (char*)realloc(rar->filename_save, + filename_size + 1); + memcpy(rar->filename_save, rar->filename, filename_size + 1); + rar->filename_save_size = filename_size; + + /* Set info for seeking */ + free(rar->dbo); + if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL) + { + archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); + return (ARCHIVE_FATAL); + } + rar->dbo[0].header_size = header_size; + rar->dbo[0].start_offset = -1; + rar->dbo[0].end_offset = -1; + rar->cursor = 0; + rar->nodes = 1; + + if (rar->file_flags & FHD_SALT) + { + if (p + 8 > endp) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid header size"); + return (ARCHIVE_FATAL); + } + memcpy(rar->salt, p, 8); + p += 8; + } + + if (rar->file_flags & FHD_EXTTIME) { + if (read_exttime(p, rar, endp) < 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid header size"); + return (ARCHIVE_FATAL); + } + } + + __archive_read_consume(a, header_size - 7); + rar->dbo[0].start_offset = a->filter->position; + rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size; + + switch(file_header.host_os) + { + case OS_MSDOS: + case OS_OS2: + case OS_WIN32: + rar->mode = archive_le32dec(file_header.file_attr); + if (rar->mode & FILE_ATTRIBUTE_DIRECTORY) + rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH; + else + rar->mode = AE_IFREG; + rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; + break; + + case OS_UNIX: + case OS_MAC_OS: + case OS_BEOS: + rar->mode = archive_le32dec(file_header.file_attr); + break; + + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Unknown file attributes from RAR file's host OS"); + return (ARCHIVE_FATAL); + } + + rar->bytes_uncopied = rar->bytes_unconsumed = 0; + rar->lzss.position = rar->offset = 0; + rar->offset_seek = 0; + rar->dictionary_size = 0; + rar->offset_outgoing = 0; + rar->br.cache_avail = 0; + rar->br.avail_in = 0; + rar->crc_calculated = 0; + rar->entry_eof = 0; + rar->valid = 1; + rar->is_ppmd_block = 0; + rar->start_new_table = 1; + free(rar->unp_buffer); + rar->unp_buffer = NULL; + rar->unp_offset = 0; + rar->unp_buffer_size = UNP_BUFFER_SIZE; + memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); + __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context); + rar->ppmd_valid = rar->ppmd_eod = 0; + + /* Don't set any archive entries for non-file header types */ + if (head_type == NEWSUB_HEAD) + return ret; + + archive_entry_set_mtime(entry, rar->mtime, rar->mnsec); + archive_entry_set_ctime(entry, rar->ctime, rar->cnsec); + archive_entry_set_atime(entry, rar->atime, rar->ansec); + archive_entry_set_size(entry, rar->unp_size); + archive_entry_set_mode(entry, rar->mode); + + if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv)) + { + if (errno == ENOMEM) + { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Pathname cannot be converted from %s to current locale.", + archive_string_conversion_charset_name(fn_sconv)); + ret = (ARCHIVE_WARN); + } + + if (((rar->mode) & AE_IFMT) == AE_IFLNK) + { + /* Make sure a symbolic-link file does not have its body. */ + rar->bytes_remaining = 0; + archive_entry_set_size(entry, 0); + + /* Read a symbolic-link name. */ + if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN)) + return ret2; + if (ret > ret2) + ret = ret2; + } + + if (rar->bytes_remaining == 0) + rar->entry_eof = 1; + + return ret; +} + +static time_t +get_time(int ttime) +{ + struct tm tm; + tm.tm_sec = 2 * (ttime & 0x1f); + tm.tm_min = (ttime >> 5) & 0x3f; + tm.tm_hour = (ttime >> 11) & 0x1f; + tm.tm_mday = (ttime >> 16) & 0x1f; + tm.tm_mon = ((ttime >> 21) & 0x0f) - 1; + tm.tm_year = ((ttime >> 25) & 0x7f) + 80; + tm.tm_isdst = -1; + return mktime(&tm); +} + +static int +read_exttime(const char *p, struct rar *rar, const char *endp) +{ + unsigned rmode, flags, rem, j, count; + int ttime, i; + struct tm *tm; + time_t t; + long nsec; +#if defined(HAVE_LOCALTIME_R) || defined(HAVE__LOCALTIME64_S) + struct tm tmbuf; +#endif +#if defined(HAVE__LOCALTIME64_S) + errno_t terr; + __time64_t tmptime; +#endif + + if (p + 2 > endp) + return (-1); + flags = archive_le16dec(p); + p += 2; + + for (i = 3; i >= 0; i--) + { + t = 0; + if (i == 3) + t = rar->mtime; + rmode = flags >> i * 4; + if (rmode & 8) + { + if (!t) + { + if (p + 4 > endp) + return (-1); + ttime = archive_le32dec(p); + t = get_time(ttime); + p += 4; + } + rem = 0; + count = rmode & 3; + if (p + count > endp) + return (-1); + for (j = 0; j < count; j++) + { + rem = (((unsigned)(unsigned char)*p) << 16) | (rem >> 8); + p++; + } +#if defined(HAVE_LOCALTIME_R) + tm = localtime_r(&t, &tmbuf); +#elif defined(HAVE__LOCALTIME64_S) + tmptime = t; + terr = _localtime64_s(&tmbuf, &tmptime); + if (terr) + tm = NULL; + else + tm = &tmbuf; +#else + tm = localtime(&t); +#endif + nsec = tm->tm_sec + rem / NS_UNIT; + if (rmode & 4) + { + tm->tm_sec++; + t = mktime(tm); + } + if (i == 3) + { + rar->mtime = t; + rar->mnsec = nsec; + } + else if (i == 2) + { + rar->ctime = t; + rar->cnsec = nsec; + } + else if (i == 1) + { + rar->atime = t; + rar->ansec = nsec; + } + else + { + rar->arctime = t; + rar->arcnsec = nsec; + } + } + } + return (0); +} + +static int +read_symlink_stored(struct archive_read *a, struct archive_entry *entry, + struct archive_string_conv *sconv) +{ + const void *h; + const char *p; + struct rar *rar; + int ret = (ARCHIVE_OK); + + rar = (struct rar *)(a->format->data); + if ((h = rar_read_ahead(a, (size_t)rar->packed_size, NULL)) == NULL) + return (ARCHIVE_FATAL); + p = h; + + if (archive_entry_copy_symlink_l(entry, + p, (size_t)rar->packed_size, sconv)) + { + if (errno == ENOMEM) + { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for link"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "link cannot be converted from %s to current locale.", + archive_string_conversion_charset_name(sconv)); + ret = (ARCHIVE_WARN); + } + __archive_read_consume(a, rar->packed_size); + return ret; +} + +static int +read_data_stored(struct archive_read *a, const void **buff, size_t *size, + int64_t *offset) +{ + struct rar *rar; + ssize_t bytes_avail; + + rar = (struct rar *)(a->format->data); + if (rar->bytes_remaining == 0 && + !(rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER)) + { + *buff = NULL; + *size = 0; + *offset = rar->offset; + if (rar->file_crc != rar->crc_calculated) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "File CRC error"); + return (ARCHIVE_FATAL); + } + rar->entry_eof = 1; + return (ARCHIVE_EOF); + } + + *buff = rar_read_ahead(a, 1, &bytes_avail); + if (bytes_avail <= 0) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated RAR file data"); + return (ARCHIVE_FATAL); + } + + *size = bytes_avail; + *offset = rar->offset; + rar->offset += bytes_avail; + rar->offset_seek += bytes_avail; + rar->bytes_remaining -= bytes_avail; + rar->bytes_unconsumed = bytes_avail; + /* Calculate File CRC. */ + rar->crc_calculated = crc32(rar->crc_calculated, *buff, + (unsigned)bytes_avail); + return (ARCHIVE_OK); +} + +static int +read_data_compressed(struct archive_read *a, const void **buff, size_t *size, + int64_t *offset) +{ + struct rar *rar; + int64_t start, end, actualend; + size_t bs; + int ret = (ARCHIVE_OK), sym, code, lzss_offset, length, i; + + rar = (struct rar *)(a->format->data); + + do { + if (!rar->valid) + return (ARCHIVE_FATAL); + if (rar->ppmd_eod || + (rar->dictionary_size && rar->offset >= rar->unp_size)) + { + if (rar->unp_offset > 0) { + /* + * We have unprocessed extracted data. write it out. + */ + *buff = rar->unp_buffer; + *size = rar->unp_offset; + *offset = rar->offset_outgoing; + rar->offset_outgoing += *size; + /* Calculate File CRC. */ + rar->crc_calculated = crc32(rar->crc_calculated, *buff, + (unsigned)*size); + rar->unp_offset = 0; + return (ARCHIVE_OK); + } + *buff = NULL; + *size = 0; + *offset = rar->offset; + if (rar->file_crc != rar->crc_calculated) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "File CRC error"); + return (ARCHIVE_FATAL); + } + rar->entry_eof = 1; + return (ARCHIVE_EOF); + } + + if (!rar->is_ppmd_block && rar->dictionary_size && rar->bytes_uncopied > 0) + { + if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset)) + bs = rar->unp_buffer_size - rar->unp_offset; + else + bs = (size_t)rar->bytes_uncopied; + ret = copy_from_lzss_window(a, buff, rar->offset, (int)bs); + if (ret != ARCHIVE_OK) + return (ret); + rar->offset += bs; + rar->bytes_uncopied -= bs; + if (*buff != NULL) { + rar->unp_offset = 0; + *size = rar->unp_buffer_size; + *offset = rar->offset_outgoing; + rar->offset_outgoing += *size; + /* Calculate File CRC. */ + rar->crc_calculated = crc32(rar->crc_calculated, *buff, + (unsigned)*size); + return (ret); + } + continue; + } + + if (!rar->br.next_in && + (ret = rar_br_preparation(a, &(rar->br))) < ARCHIVE_WARN) + return (ret); + if (rar->start_new_table && ((ret = parse_codes(a)) < (ARCHIVE_WARN))) + return (ret); + + if (rar->is_ppmd_block) + { + if ((sym = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( + &rar->ppmd7_context, &rar->range_dec.p)) < 0) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid symbol"); + return (ARCHIVE_FATAL); + } + if(sym != rar->ppmd_escape) + { + lzss_emit_literal(rar, sym); + rar->bytes_uncopied++; + } + else + { + if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( + &rar->ppmd7_context, &rar->range_dec.p)) < 0) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid symbol"); + return (ARCHIVE_FATAL); + } + + switch(code) + { + case 0: + rar->start_new_table = 1; + return read_data_compressed(a, buff, size, offset); + + case 2: + rar->ppmd_eod = 1;/* End Of ppmd Data. */ + continue; + + case 3: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Parsing filters is unsupported."); + return (ARCHIVE_FAILED); + + case 4: + lzss_offset = 0; + for (i = 2; i >= 0; i--) + { + if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( + &rar->ppmd7_context, &rar->range_dec.p)) < 0) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid symbol"); + return (ARCHIVE_FATAL); + } + lzss_offset |= code << (i * 8); + } + if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( + &rar->ppmd7_context, &rar->range_dec.p)) < 0) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid symbol"); + return (ARCHIVE_FATAL); + } + lzss_emit_match(rar, lzss_offset + 2, length + 32); + rar->bytes_uncopied += length + 32; + break; + + case 5: + if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( + &rar->ppmd7_context, &rar->range_dec.p)) < 0) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid symbol"); + return (ARCHIVE_FATAL); + } + lzss_emit_match(rar, 1, length + 4); + rar->bytes_uncopied += length + 4; + break; + + default: + lzss_emit_literal(rar, sym); + rar->bytes_uncopied++; + } + } + } + else + { + start = rar->offset; + end = start + rar->dictionary_size; + rar->filterstart = INT64_MAX; + + if ((actualend = expand(a, end)) < 0) + return ((int)actualend); + + rar->bytes_uncopied = actualend - start; + if (rar->bytes_uncopied == 0) { + /* Broken RAR files cause this case. + * NOTE: If this case were possible on a normal RAR file + * we would find out where it was actually bad and + * what we would do to solve it. */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Internal error extracting RAR file"); + return (ARCHIVE_FATAL); + } + } + if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset)) + bs = rar->unp_buffer_size - rar->unp_offset; + else + bs = (size_t)rar->bytes_uncopied; + ret = copy_from_lzss_window(a, buff, rar->offset, (int)bs); + if (ret != ARCHIVE_OK) + return (ret); + rar->offset += bs; + rar->bytes_uncopied -= bs; + /* + * If *buff is NULL, it means unp_buffer is not full. + * So we have to continue extracting a RAR file. + */ + } while (*buff == NULL); + + rar->unp_offset = 0; + *size = rar->unp_buffer_size; + *offset = rar->offset_outgoing; + rar->offset_outgoing += *size; + /* Calculate File CRC. */ + rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size); + return ret; +} + +static int +parse_codes(struct archive_read *a) +{ + int i, j, val, n, r; + unsigned char bitlengths[MAX_SYMBOLS], zerocount, ppmd_flags; + unsigned int maxorder; + struct huffman_code precode; + struct rar *rar = (struct rar *)(a->format->data); + struct rar_br *br = &(rar->br); + + free_codes(a); + + /* Skip to the next byte */ + rar_br_consume_unalined_bits(br); + + /* PPMd block flag */ + if (!rar_br_read_ahead(a, br, 1)) + goto truncated_data; + if ((rar->is_ppmd_block = rar_br_bits(br, 1)) != 0) + { + rar_br_consume(br, 1); + if (!rar_br_read_ahead(a, br, 7)) + goto truncated_data; + ppmd_flags = rar_br_bits(br, 7); + rar_br_consume(br, 7); + + /* Memory is allocated in MB */ + if (ppmd_flags & 0x20) + { + if (!rar_br_read_ahead(a, br, 8)) + goto truncated_data; + rar->dictionary_size = (rar_br_bits(br, 8) + 1) << 20; + rar_br_consume(br, 8); + } + + if (ppmd_flags & 0x40) + { + if (!rar_br_read_ahead(a, br, 8)) + goto truncated_data; + rar->ppmd_escape = rar->ppmd7_context.InitEsc = rar_br_bits(br, 8); + rar_br_consume(br, 8); + } + else + rar->ppmd_escape = 2; + + if (ppmd_flags & 0x20) + { + maxorder = (ppmd_flags & 0x1F) + 1; + if(maxorder > 16) + maxorder = 16 + (maxorder - 16) * 3; + + if (maxorder == 1) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated RAR file data"); + return (ARCHIVE_FATAL); + } + + /* Make sure ppmd7_contest is freed before Ppmd7_Construct + * because reading a broken file cause this abnormal sequence. */ + __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context); + + rar->bytein.a = a; + rar->bytein.Read = &ppmd_read; + __archive_ppmd7_functions.PpmdRAR_RangeDec_CreateVTable(&rar->range_dec); + rar->range_dec.Stream = &rar->bytein; + __archive_ppmd7_functions.Ppmd7_Construct(&rar->ppmd7_context); + + if (rar->dictionary_size == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid zero dictionary size"); + return (ARCHIVE_FATAL); + } + + if (!__archive_ppmd7_functions.Ppmd7_Alloc(&rar->ppmd7_context, + rar->dictionary_size)) + { + archive_set_error(&a->archive, ENOMEM, + "Out of memory"); + return (ARCHIVE_FATAL); + } + if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec)) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Unable to initialize PPMd range decoder"); + return (ARCHIVE_FATAL); + } + __archive_ppmd7_functions.Ppmd7_Init(&rar->ppmd7_context, maxorder); + rar->ppmd_valid = 1; + } + else + { + if (!rar->ppmd_valid) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid PPMd sequence"); + return (ARCHIVE_FATAL); + } + if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec)) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Unable to initialize PPMd range decoder"); + return (ARCHIVE_FATAL); + } + } + } + else + { + rar_br_consume(br, 1); + + /* Keep existing table flag */ + if (!rar_br_read_ahead(a, br, 1)) + goto truncated_data; + if (!rar_br_bits(br, 1)) + memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); + rar_br_consume(br, 1); + + memset(&bitlengths, 0, sizeof(bitlengths)); + for (i = 0; i < MAX_SYMBOLS;) + { + if (!rar_br_read_ahead(a, br, 4)) + goto truncated_data; + bitlengths[i++] = rar_br_bits(br, 4); + rar_br_consume(br, 4); + if (bitlengths[i-1] == 0xF) + { + if (!rar_br_read_ahead(a, br, 4)) + goto truncated_data; + zerocount = rar_br_bits(br, 4); + rar_br_consume(br, 4); + if (zerocount) + { + i--; + for (j = 0; j < zerocount + 2 && i < MAX_SYMBOLS; j++) + bitlengths[i++] = 0; + } + } + } + + memset(&precode, 0, sizeof(precode)); + r = create_code(a, &precode, bitlengths, MAX_SYMBOLS, MAX_SYMBOL_LENGTH); + if (r != ARCHIVE_OK) { + free(precode.tree); + free(precode.table); + return (r); + } + + for (i = 0; i < HUFFMAN_TABLE_SIZE;) + { + if ((val = read_next_symbol(a, &precode)) < 0) { + free(precode.tree); + free(precode.table); + return (ARCHIVE_FATAL); + } + if (val < 16) + { + rar->lengthtable[i] = (rar->lengthtable[i] + val) & 0xF; + i++; + } + else if (val < 18) + { + if (i == 0) + { + free(precode.tree); + free(precode.table); + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Internal error extracting RAR file."); + return (ARCHIVE_FATAL); + } + + if(val == 16) { + if (!rar_br_read_ahead(a, br, 3)) { + free(precode.tree); + free(precode.table); + goto truncated_data; + } + n = rar_br_bits(br, 3) + 3; + rar_br_consume(br, 3); + } else { + if (!rar_br_read_ahead(a, br, 7)) { + free(precode.tree); + free(precode.table); + goto truncated_data; + } + n = rar_br_bits(br, 7) + 11; + rar_br_consume(br, 7); + } + + for (j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++) + { + rar->lengthtable[i] = rar->lengthtable[i-1]; + i++; + } + } + else + { + if(val == 18) { + if (!rar_br_read_ahead(a, br, 3)) { + free(precode.tree); + free(precode.table); + goto truncated_data; + } + n = rar_br_bits(br, 3) + 3; + rar_br_consume(br, 3); + } else { + if (!rar_br_read_ahead(a, br, 7)) { + free(precode.tree); + free(precode.table); + goto truncated_data; + } + n = rar_br_bits(br, 7) + 11; + rar_br_consume(br, 7); + } + + for(j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++) + rar->lengthtable[i++] = 0; + } + } + free(precode.tree); + free(precode.table); + + r = create_code(a, &rar->maincode, &rar->lengthtable[0], MAINCODE_SIZE, + MAX_SYMBOL_LENGTH); + if (r != ARCHIVE_OK) + return (r); + r = create_code(a, &rar->offsetcode, &rar->lengthtable[MAINCODE_SIZE], + OFFSETCODE_SIZE, MAX_SYMBOL_LENGTH); + if (r != ARCHIVE_OK) + return (r); + r = create_code(a, &rar->lowoffsetcode, + &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE], + LOWOFFSETCODE_SIZE, MAX_SYMBOL_LENGTH); + if (r != ARCHIVE_OK) + return (r); + r = create_code(a, &rar->lengthcode, + &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE + + LOWOFFSETCODE_SIZE], LENGTHCODE_SIZE, MAX_SYMBOL_LENGTH); + if (r != ARCHIVE_OK) + return (r); + } + + if (!rar->dictionary_size || !rar->lzss.window) + { + /* Seems as though dictionary sizes are not used. Even so, minimize + * memory usage as much as possible. + */ + void *new_window; + unsigned int new_size; + + if (rar->unp_size >= DICTIONARY_MAX_SIZE) + new_size = DICTIONARY_MAX_SIZE; + else + new_size = rar_fls((unsigned int)rar->unp_size) << 1; + if (new_size == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Zero window size is invalid."); + return (ARCHIVE_FATAL); + } + new_window = realloc(rar->lzss.window, new_size); + if (new_window == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Unable to allocate memory for uncompressed data."); + return (ARCHIVE_FATAL); + } + rar->lzss.window = (unsigned char *)new_window; + rar->dictionary_size = new_size; + memset(rar->lzss.window, 0, rar->dictionary_size); + rar->lzss.mask = rar->dictionary_size - 1; + } + + rar->start_new_table = 0; + return (ARCHIVE_OK); +truncated_data: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated RAR file data"); + rar->valid = 0; + return (ARCHIVE_FATAL); +} + +static void +free_codes(struct archive_read *a) +{ + struct rar *rar = (struct rar *)(a->format->data); + free(rar->maincode.tree); + free(rar->offsetcode.tree); + free(rar->lowoffsetcode.tree); + free(rar->lengthcode.tree); + free(rar->maincode.table); + free(rar->offsetcode.table); + free(rar->lowoffsetcode.table); + free(rar->lengthcode.table); + memset(&rar->maincode, 0, sizeof(rar->maincode)); + memset(&rar->offsetcode, 0, sizeof(rar->offsetcode)); + memset(&rar->lowoffsetcode, 0, sizeof(rar->lowoffsetcode)); + memset(&rar->lengthcode, 0, sizeof(rar->lengthcode)); +} + + +static int +read_next_symbol(struct archive_read *a, struct huffman_code *code) +{ + unsigned char bit; + unsigned int bits; + int length, value, node; + struct rar *rar; + struct rar_br *br; + + if (!code->table) + { + if (make_table(a, code) != (ARCHIVE_OK)) + return -1; + } + + rar = (struct rar *)(a->format->data); + br = &(rar->br); + + /* Look ahead (peek) at bits */ + if (!rar_br_read_ahead(a, br, code->tablesize)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated RAR file data"); + rar->valid = 0; + return -1; + } + bits = rar_br_bits(br, code->tablesize); + + length = code->table[bits].length; + value = code->table[bits].value; + + if (length < 0) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid prefix code in bitstream"); + return -1; + } + + if (length <= code->tablesize) + { + /* Skip length bits */ + rar_br_consume(br, length); + return value; + } + + /* Skip tablesize bits */ + rar_br_consume(br, code->tablesize); + + node = value; + while (!(code->tree[node].branches[0] == + code->tree[node].branches[1])) + { + if (!rar_br_read_ahead(a, br, 1)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated RAR file data"); + rar->valid = 0; + return -1; + } + bit = rar_br_bits(br, 1); + rar_br_consume(br, 1); + + if (code->tree[node].branches[bit] < 0) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid prefix code in bitstream"); + return -1; + } + node = code->tree[node].branches[bit]; + } + + return code->tree[node].branches[0]; +} + +static int +create_code(struct archive_read *a, struct huffman_code *code, + unsigned char *lengths, int numsymbols, char maxlength) +{ + int i, j, codebits = 0, symbolsleft = numsymbols; + + code->numentries = 0; + code->numallocatedentries = 0; + if (new_node(code) < 0) { + archive_set_error(&a->archive, ENOMEM, + "Unable to allocate memory for node data."); + return (ARCHIVE_FATAL); + } + code->numentries = 1; + code->minlength = INT_MAX; + code->maxlength = INT_MIN; + codebits = 0; + for(i = 1; i <= maxlength; i++) + { + for(j = 0; j < numsymbols; j++) + { + if (lengths[j] != i) continue; + if (add_value(a, code, j, codebits, i) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + codebits++; + if (--symbolsleft <= 0) + break; + } + if (symbolsleft <= 0) + break; + codebits <<= 1; + } + return (ARCHIVE_OK); +} + +static int +add_value(struct archive_read *a, struct huffman_code *code, int value, + int codebits, int length) +{ + int lastnode, bitpos, bit; + /* int repeatpos, repeatnode, nextnode; */ + + free(code->table); + code->table = NULL; + + if(length > code->maxlength) + code->maxlength = length; + if(length < code->minlength) + code->minlength = length; + + /* + * Dead code, repeatpos was is -1 + * + repeatpos = -1; + if (repeatpos == 0 || (repeatpos >= 0 + && (((codebits >> (repeatpos - 1)) & 3) == 0 + || ((codebits >> (repeatpos - 1)) & 3) == 3))) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid repeat position"); + return (ARCHIVE_FATAL); + } + */ + + lastnode = 0; + for (bitpos = length - 1; bitpos >= 0; bitpos--) + { + bit = (codebits >> bitpos) & 1; + + /* Leaf node check */ + if (code->tree[lastnode].branches[0] == + code->tree[lastnode].branches[1]) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Prefix found"); + return (ARCHIVE_FATAL); + } + + /* + * Dead code, repeatpos was -1, bitpos >=0 + * + if (bitpos == repeatpos) + { + * Open branch check * + if (!(code->tree[lastnode].branches[bit] < 0)) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid repeating code"); + return (ARCHIVE_FATAL); + } + + if ((repeatnode = new_node(code)) < 0) { + archive_set_error(&a->archive, ENOMEM, + "Unable to allocate memory for node data."); + return (ARCHIVE_FATAL); + } + if ((nextnode = new_node(code)) < 0) { + archive_set_error(&a->archive, ENOMEM, + "Unable to allocate memory for node data."); + return (ARCHIVE_FATAL); + } + + * Set branches * + code->tree[lastnode].branches[bit] = repeatnode; + code->tree[repeatnode].branches[bit] = repeatnode; + code->tree[repeatnode].branches[bit^1] = nextnode; + lastnode = nextnode; + + bitpos++; * terminating bit already handled, skip it * + } + else + { + */ + /* Open branch check */ + if (code->tree[lastnode].branches[bit] < 0) + { + if (new_node(code) < 0) { + archive_set_error(&a->archive, ENOMEM, + "Unable to allocate memory for node data."); + return (ARCHIVE_FATAL); + } + code->tree[lastnode].branches[bit] = code->numentries++; + } + + /* set to branch */ + lastnode = code->tree[lastnode].branches[bit]; + /* } */ + } + + if (!(code->tree[lastnode].branches[0] == -1 + && code->tree[lastnode].branches[1] == -2)) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Prefix found"); + return (ARCHIVE_FATAL); + } + + /* Set leaf value */ + code->tree[lastnode].branches[0] = value; + code->tree[lastnode].branches[1] = value; + + return (ARCHIVE_OK); +} + +static int +new_node(struct huffman_code *code) +{ + void *new_tree; + if (code->numallocatedentries == code->numentries) { + int new_num_entries = 256; + if (code->numentries > 0) { + new_num_entries = code->numentries * 2; + } + new_tree = realloc(code->tree, new_num_entries * sizeof(*code->tree)); + if (new_tree == NULL) + return (-1); + code->tree = (struct huffman_tree_node *)new_tree; + code->numallocatedentries = new_num_entries; + } + code->tree[code->numentries].branches[0] = -1; + code->tree[code->numentries].branches[1] = -2; + return 1; +} + +static int +make_table(struct archive_read *a, struct huffman_code *code) +{ + if (code->maxlength < code->minlength || code->maxlength > 10) + code->tablesize = 10; + else + code->tablesize = code->maxlength; + + code->table = + (struct huffman_table_entry *)calloc(1, sizeof(*code->table) + * ((size_t)1 << code->tablesize)); + + return make_table_recurse(a, code, 0, code->table, 0, code->tablesize); +} + +static int +make_table_recurse(struct archive_read *a, struct huffman_code *code, int node, + struct huffman_table_entry *table, int depth, + int maxdepth) +{ + int currtablesize, i, ret = (ARCHIVE_OK); + + if (!code->tree) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Huffman tree was not created."); + return (ARCHIVE_FATAL); + } + if (node < 0 || node >= code->numentries) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid location to Huffman tree specified."); + return (ARCHIVE_FATAL); + } + + currtablesize = 1 << (maxdepth - depth); + + if (code->tree[node].branches[0] == + code->tree[node].branches[1]) + { + for(i = 0; i < currtablesize; i++) + { + table[i].length = depth; + table[i].value = code->tree[node].branches[0]; + } + } + /* + * Dead code, node >= 0 + * + else if (node < 0) + { + for(i = 0; i < currtablesize; i++) + table[i].length = -1; + } + */ + else + { + if(depth == maxdepth) + { + table[0].length = maxdepth + 1; + table[0].value = node; + } + else + { + ret |= make_table_recurse(a, code, code->tree[node].branches[0], table, + depth + 1, maxdepth); + ret |= make_table_recurse(a, code, code->tree[node].branches[1], + table + currtablesize / 2, depth + 1, maxdepth); + } + } + return ret; +} + +static int64_t +expand(struct archive_read *a, int64_t end) +{ + static const unsigned char lengthbases[] = + { 0, 1, 2, 3, 4, 5, 6, + 7, 8, 10, 12, 14, 16, 20, + 24, 28, 32, 40, 48, 56, 64, + 80, 96, 112, 128, 160, 192, 224 }; + static const unsigned char lengthbits[] = + { 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 }; + static const int lengthb_min = minimum( + (int)(sizeof(lengthbases)/sizeof(lengthbases[0])), + (int)(sizeof(lengthbits)/sizeof(lengthbits[0])) + ); + static const unsigned int offsetbases[] = + { 0, 1, 2, 3, 4, 6, + 8, 12, 16, 24, 32, 48, + 64, 96, 128, 192, 256, 384, + 512, 768, 1024, 1536, 2048, 3072, + 4096, 6144, 8192, 12288, 16384, 24576, + 32768, 49152, 65536, 98304, 131072, 196608, + 262144, 327680, 393216, 458752, 524288, 589824, + 655360, 720896, 786432, 851968, 917504, 983040, + 1048576, 1310720, 1572864, 1835008, 2097152, 2359296, + 2621440, 2883584, 3145728, 3407872, 3670016, 3932160 }; + static const unsigned char offsetbits[] = + { 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, 14, 14, 15, 15, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18 }; + static const int offsetb_min = minimum( + (int)(sizeof(offsetbases)/sizeof(offsetbases[0])), + (int)(sizeof(offsetbits)/sizeof(offsetbits[0])) + ); + static const unsigned char shortbases[] = + { 0, 4, 8, 16, 32, 64, 128, 192 }; + static const unsigned char shortbits[] = + { 2, 2, 3, 4, 5, 6, 6, 6 }; + + int symbol, offs, len, offsindex, lensymbol, i, offssymbol, lowoffsetsymbol; + unsigned char newfile; + struct rar *rar = (struct rar *)(a->format->data); + struct rar_br *br = &(rar->br); + + if (rar->filterstart < end) + end = rar->filterstart; + + while (1) + { + if (rar->output_last_match && + lzss_position(&rar->lzss) + rar->lastlength <= end) + { + lzss_emit_match(rar, rar->lastoffset, rar->lastlength); + rar->output_last_match = 0; + } + + if(rar->is_ppmd_block || rar->output_last_match || + lzss_position(&rar->lzss) >= end) + return lzss_position(&rar->lzss); + + if ((symbol = read_next_symbol(a, &rar->maincode)) < 0) + return (ARCHIVE_FATAL); + rar->output_last_match = 0; + + if (symbol < 256) + { + lzss_emit_literal(rar, symbol); + continue; + } + else if (symbol == 256) + { + if (!rar_br_read_ahead(a, br, 1)) + goto truncated_data; + newfile = !rar_br_bits(br, 1); + rar_br_consume(br, 1); + + if(newfile) + { + rar->start_new_block = 1; + if (!rar_br_read_ahead(a, br, 1)) + goto truncated_data; + rar->start_new_table = rar_br_bits(br, 1); + rar_br_consume(br, 1); + return lzss_position(&rar->lzss); + } + else + { + if (parse_codes(a) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + continue; + } + } + else if(symbol==257) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Parsing filters is unsupported."); + return (ARCHIVE_FAILED); + } + else if(symbol==258) + { + if(rar->lastlength == 0) + continue; + + offs = rar->lastoffset; + len = rar->lastlength; + } + else if (symbol <= 262) + { + offsindex = symbol - 259; + offs = rar->oldoffset[offsindex]; + + if ((lensymbol = read_next_symbol(a, &rar->lengthcode)) < 0) + goto bad_data; + if (lensymbol > lengthb_min) + goto bad_data; + len = lengthbases[lensymbol] + 2; + if (lengthbits[lensymbol] > 0) { + if (!rar_br_read_ahead(a, br, lengthbits[lensymbol])) + goto truncated_data; + len += rar_br_bits(br, lengthbits[lensymbol]); + rar_br_consume(br, lengthbits[lensymbol]); + } + + for (i = offsindex; i > 0; i--) + rar->oldoffset[i] = rar->oldoffset[i-1]; + rar->oldoffset[0] = offs; + } + else if(symbol<=270) + { + offs = shortbases[symbol-263] + 1; + if(shortbits[symbol-263] > 0) { + if (!rar_br_read_ahead(a, br, shortbits[symbol-263])) + goto truncated_data; + offs += rar_br_bits(br, shortbits[symbol-263]); + rar_br_consume(br, shortbits[symbol-263]); + } + + len = 2; + + for(i = 3; i > 0; i--) + rar->oldoffset[i] = rar->oldoffset[i-1]; + rar->oldoffset[0] = offs; + } + else + { + if (symbol-271 > lengthb_min) + goto bad_data; + len = lengthbases[symbol-271]+3; + if(lengthbits[symbol-271] > 0) { + if (!rar_br_read_ahead(a, br, lengthbits[symbol-271])) + goto truncated_data; + len += rar_br_bits(br, lengthbits[symbol-271]); + rar_br_consume(br, lengthbits[symbol-271]); + } + + if ((offssymbol = read_next_symbol(a, &rar->offsetcode)) < 0) + goto bad_data; + if (offssymbol > offsetb_min) + goto bad_data; + offs = offsetbases[offssymbol]+1; + if(offsetbits[offssymbol] > 0) + { + if(offssymbol > 9) + { + if(offsetbits[offssymbol] > 4) { + if (!rar_br_read_ahead(a, br, offsetbits[offssymbol] - 4)) + goto truncated_data; + offs += rar_br_bits(br, offsetbits[offssymbol] - 4) << 4; + rar_br_consume(br, offsetbits[offssymbol] - 4); + } + + if(rar->numlowoffsetrepeats > 0) + { + rar->numlowoffsetrepeats--; + offs += rar->lastlowoffset; + } + else + { + if ((lowoffsetsymbol = + read_next_symbol(a, &rar->lowoffsetcode)) < 0) + return (ARCHIVE_FATAL); + if(lowoffsetsymbol == 16) + { + rar->numlowoffsetrepeats = 15; + offs += rar->lastlowoffset; + } + else + { + offs += lowoffsetsymbol; + rar->lastlowoffset = lowoffsetsymbol; + } + } + } + else { + if (!rar_br_read_ahead(a, br, offsetbits[offssymbol])) + goto truncated_data; + offs += rar_br_bits(br, offsetbits[offssymbol]); + rar_br_consume(br, offsetbits[offssymbol]); + } + } + + if (offs >= 0x40000) + len++; + if (offs >= 0x2000) + len++; + + for(i = 3; i > 0; i--) + rar->oldoffset[i] = rar->oldoffset[i-1]; + rar->oldoffset[0] = offs; + } + + rar->lastoffset = offs; + rar->lastlength = len; + rar->output_last_match = 1; + } +truncated_data: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated RAR file data"); + rar->valid = 0; + return (ARCHIVE_FATAL); +bad_data: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Bad RAR file data"); + return (ARCHIVE_FATAL); +} + +static int +copy_from_lzss_window(struct archive_read *a, const void **buffer, + int64_t startpos, int length) +{ + int windowoffs, firstpart; + struct rar *rar = (struct rar *)(a->format->data); + + if (!rar->unp_buffer) + { + if ((rar->unp_buffer = malloc(rar->unp_buffer_size)) == NULL) + { + archive_set_error(&a->archive, ENOMEM, + "Unable to allocate memory for uncompressed data."); + return (ARCHIVE_FATAL); + } + } + + windowoffs = lzss_offset_for_position(&rar->lzss, startpos); + if(windowoffs + length <= lzss_size(&rar->lzss)) { + memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs], + length); + } else if (length <= lzss_size(&rar->lzss)) { + firstpart = lzss_size(&rar->lzss) - windowoffs; + if (firstpart < 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Bad RAR file data"); + return (ARCHIVE_FATAL); + } + if (firstpart < length) { + memcpy(&rar->unp_buffer[rar->unp_offset], + &rar->lzss.window[windowoffs], firstpart); + memcpy(&rar->unp_buffer[rar->unp_offset + firstpart], + &rar->lzss.window[0], length - firstpart); + } else { + memcpy(&rar->unp_buffer[rar->unp_offset], + &rar->lzss.window[windowoffs], length); + } + } else { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Bad RAR file data"); + return (ARCHIVE_FATAL); + } + rar->unp_offset += length; + if (rar->unp_offset >= rar->unp_buffer_size) + *buffer = rar->unp_buffer; + else + *buffer = NULL; + return (ARCHIVE_OK); +} + +static const void * +rar_read_ahead(struct archive_read *a, size_t min, ssize_t *avail) +{ + struct rar *rar = (struct rar *)(a->format->data); + const void *h = __archive_read_ahead(a, min, avail); + int ret; + if (avail) + { + if (a->archive.read_data_is_posix_read && *avail > (ssize_t)a->archive.read_data_requested) + *avail = a->archive.read_data_requested; + if (*avail > rar->bytes_remaining) + *avail = (ssize_t)rar->bytes_remaining; + if (*avail < 0) + return NULL; + else if (*avail == 0 && rar->main_flags & MHD_VOLUME && + rar->file_flags & FHD_SPLIT_AFTER) + { + rar->filename_must_match = 1; + ret = archive_read_format_rar_read_header(a, a->entry); + if (ret == (ARCHIVE_EOF)) + { + rar->has_endarc_header = 1; + ret = archive_read_format_rar_read_header(a, a->entry); + } + rar->filename_must_match = 0; + if (ret != (ARCHIVE_OK)) + return NULL; + return rar_read_ahead(a, min, avail); + } + } + return h; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_rar5.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_rar5.c new file mode 100644 index 0000000000..7a308a8d8a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_rar5.c @@ -0,0 +1,4097 @@ +/*- +* Copyright (c) 2018 Grzegorz Antoniak (http://antoniak.org) +* 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(S) ``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(S) 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. +*/ + +#include "archive_platform.h" +#include "archive_endian.h" + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <time.h> +#ifdef HAVE_ZLIB_H +#include <zlib.h> /* crc32 */ +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif + +#include "archive.h" +#ifndef HAVE_ZLIB_H +#include "archive_crc32.h" +#endif + +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_ppmd7_private.h" +#include "archive_entry_private.h" + +#ifdef HAVE_BLAKE2_H +#include <blake2.h> +#else +#include "archive_blake2.h" +#endif + +/*#define CHECK_CRC_ON_SOLID_SKIP*/ +/*#define DONT_FAIL_ON_CRC_ERROR*/ +/*#define DEBUG*/ + +#define rar5_min(a, b) (((a) > (b)) ? (b) : (a)) +#define rar5_max(a, b) (((a) > (b)) ? (a) : (b)) +#define rar5_countof(X) ((const ssize_t) (sizeof(X) / sizeof(*X))) + +#if defined DEBUG +#define DEBUG_CODE if(1) +#define LOG(...) do { printf("rar5: " __VA_ARGS__); puts(""); } while(0) +#else +#define DEBUG_CODE if(0) +#endif + +/* Real RAR5 magic number is: + * + * 0x52, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x01, 0x00 + * "Rar!→•☺·\x00" + * + * Retrieved with `rar5_signature()` by XOR'ing it with 0xA1, because I don't + * want to put this magic sequence in each binary that uses libarchive, so + * applications that scan through the file for this marker won't trigger on + * this "false" one. + * + * The array itself is decrypted in `rar5_init` function. */ + +static unsigned char rar5_signature_xor[] = { 243, 192, 211, 128, 187, 166, 160, 161 }; +static const size_t g_unpack_window_size = 0x20000; + +/* These could have been static const's, but they aren't, because of + * Visual Studio. */ +#define MAX_NAME_IN_CHARS 2048 +#define MAX_NAME_IN_BYTES (4 * MAX_NAME_IN_CHARS) + +struct file_header { + ssize_t bytes_remaining; + ssize_t unpacked_size; + int64_t last_offset; /* Used in sanity checks. */ + int64_t last_size; /* Used in sanity checks. */ + + uint8_t solid : 1; /* Is this a solid stream? */ + uint8_t service : 1; /* Is this file a service data? */ + uint8_t eof : 1; /* Did we finish unpacking the file? */ + uint8_t dir : 1; /* Is this file entry a directory? */ + + /* Optional time fields. */ + uint64_t e_mtime; + uint64_t e_ctime; + uint64_t e_atime; + uint32_t e_unix_ns; + + /* Optional hash fields. */ + uint32_t stored_crc32; + uint32_t calculated_crc32; + uint8_t blake2sp[32]; + blake2sp_state b2state; + char has_blake2; + + /* Optional redir fields */ + uint64_t redir_type; + uint64_t redir_flags; + + ssize_t solid_window_size; /* Used in file format check. */ +}; + +enum EXTRA { + EX_CRYPT = 0x01, + EX_HASH = 0x02, + EX_HTIME = 0x03, + EX_VERSION = 0x04, + EX_REDIR = 0x05, + EX_UOWNER = 0x06, + EX_SUBDATA = 0x07 +}; + +#define REDIR_SYMLINK_IS_DIR 1 + +enum REDIR_TYPE { + REDIR_TYPE_NONE = 0, + REDIR_TYPE_UNIXSYMLINK = 1, + REDIR_TYPE_WINSYMLINK = 2, + REDIR_TYPE_JUNCTION = 3, + REDIR_TYPE_HARDLINK = 4, + REDIR_TYPE_FILECOPY = 5, +}; + +#define OWNER_USER_NAME 0x01 +#define OWNER_GROUP_NAME 0x02 +#define OWNER_USER_UID 0x04 +#define OWNER_GROUP_GID 0x08 +#define OWNER_MAXNAMELEN 256 + +enum FILTER_TYPE { + FILTER_DELTA = 0, /* Generic pattern. */ + FILTER_E8 = 1, /* Intel x86 code. */ + FILTER_E8E9 = 2, /* Intel x86 code. */ + FILTER_ARM = 3, /* ARM code. */ + FILTER_AUDIO = 4, /* Audio filter, not used in RARv5. */ + FILTER_RGB = 5, /* Color palette, not used in RARv5. */ + FILTER_ITANIUM = 6, /* Intel's Itanium, not used in RARv5. */ + FILTER_PPM = 7, /* Predictive pattern matching, not used in + RARv5. */ + FILTER_NONE = 8, +}; + +struct filter_info { + int type; + int channels; + int pos_r; + + int64_t block_start; + ssize_t block_length; + uint16_t width; +}; + +struct data_ready { + char used; + const uint8_t* buf; + size_t size; + int64_t offset; +}; + +struct cdeque { + uint16_t beg_pos; + uint16_t end_pos; + uint16_t cap_mask; + uint16_t size; + size_t* arr; +}; + +struct decode_table { + uint32_t size; + int32_t decode_len[16]; + uint32_t decode_pos[16]; + uint32_t quick_bits; + uint8_t quick_len[1 << 10]; + uint16_t quick_num[1 << 10]; + uint16_t decode_num[306]; +}; + +struct comp_state { + /* Flag used to specify if unpacker needs to reinitialize the + uncompression context. */ + uint8_t initialized : 1; + + /* Flag used when applying filters. */ + uint8_t all_filters_applied : 1; + + /* Flag used to skip file context reinitialization, used when unpacker + is skipping through different multivolume archives. */ + uint8_t switch_multivolume : 1; + + /* Flag used to specify if unpacker has processed the whole data block + or just a part of it. */ + uint8_t block_parsing_finished : 1; + + signed int notused : 4; + + int flags; /* Uncompression flags. */ + int method; /* Uncompression algorithm method. */ + int version; /* Uncompression algorithm version. */ + ssize_t window_size; /* Size of window_buf. */ + uint8_t* window_buf; /* Circular buffer used during + decompression. */ + uint8_t* filtered_buf; /* Buffer used when applying filters. */ + const uint8_t* block_buf; /* Buffer used when merging blocks. */ + size_t window_mask; /* Convenience field; window_size - 1. */ + int64_t write_ptr; /* This amount of data has been unpacked + in the window buffer. */ + int64_t last_write_ptr; /* This amount of data has been stored in + the output file. */ + int64_t last_unstore_ptr; /* Counter of bytes extracted during + unstoring. This is separate from + last_write_ptr because of how SERVICE + base blocks are handled during skipping + in solid multiarchive archives. */ + int64_t solid_offset; /* Additional offset inside the window + buffer, used in unpacking solid + archives. */ + ssize_t cur_block_size; /* Size of current data block. */ + int last_len; /* Flag used in lzss decompression. */ + + /* Decode tables used during lzss uncompression. */ + +#define HUFF_BC 20 + struct decode_table bd; /* huffman bit lengths */ +#define HUFF_NC 306 + struct decode_table ld; /* literals */ +#define HUFF_DC 64 + struct decode_table dd; /* distances */ +#define HUFF_LDC 16 + struct decode_table ldd; /* lower bits of distances */ +#define HUFF_RC 44 + struct decode_table rd; /* repeating distances */ +#define HUFF_TABLE_SIZE (HUFF_NC + HUFF_DC + HUFF_RC + HUFF_LDC) + + /* Circular deque for storing filters. */ + struct cdeque filters; + int64_t last_block_start; /* Used for sanity checking. */ + ssize_t last_block_length; /* Used for sanity checking. */ + + /* Distance cache used during lzss uncompression. */ + int dist_cache[4]; + + /* Data buffer stack. */ + struct data_ready dready[2]; +}; + +/* Bit reader state. */ +struct bit_reader { + int8_t bit_addr; /* Current bit pointer inside current byte. */ + int in_addr; /* Current byte pointer. */ +}; + +/* RARv5 block header structure. Use bf_* functions to get values from + * block_flags_u8 field. I.e. bf_byte_count, etc. */ +struct compressed_block_header { + /* block_flags_u8 contain fields encoded in little-endian bitfield: + * + * - table present flag (shr 7, and 1), + * - last block flag (shr 6, and 1), + * - byte_count (shr 3, and 7), + * - bit_size (shr 0, and 7). + */ + uint8_t block_flags_u8; + uint8_t block_cksum; +}; + +/* RARv5 main header structure. */ +struct main_header { + /* Does the archive contain solid streams? */ + uint8_t solid : 1; + + /* If this a multi-file archive? */ + uint8_t volume : 1; + uint8_t endarc : 1; + uint8_t notused : 5; + + unsigned int vol_no; +}; + +struct generic_header { + uint8_t split_after : 1; + uint8_t split_before : 1; + uint8_t padding : 6; + int size; + int last_header_id; +}; + +struct multivolume { + unsigned int expected_vol_no; + uint8_t* push_buf; +}; + +/* Main context structure. */ +struct rar5 { + int header_initialized; + + /* Set to 1 if current file is positioned AFTER the magic value + * of the archive file. This is used in header reading functions. */ + int skipped_magic; + + /* Set to not zero if we're in skip mode (either by calling + * rar5_data_skip function or when skipping over solid streams). + * Set to 0 when in * extraction mode. This is used during checksum + * calculation functions. */ + int skip_mode; + + /* Set to not zero if we're in block merging mode (i.e. when switching + * to another file in multivolume archive, last block from 1st archive + * needs to be merged with 1st block from 2nd archive). This flag + * guards against recursive use of the merging function, which doesn't + * support recursive calls. */ + int merge_mode; + + /* An offset to QuickOpen list. This is not supported by this unpacker, + * because we're focusing on streaming interface. QuickOpen is designed + * to make things quicker for non-stream interfaces, so it's not our + * use case. */ + uint64_t qlist_offset; + + /* An offset to additional Recovery data. This is not supported by this + * unpacker. Recovery data are additional Reed-Solomon codes that could + * be used to calculate bytes that are missing in archive or are + * corrupted. */ + uint64_t rr_offset; + + /* Various context variables grouped to different structures. */ + struct generic_header generic; + struct main_header main; + struct comp_state cstate; + struct file_header file; + struct bit_reader bits; + struct multivolume vol; + + /* The header of currently processed RARv5 block. Used in main + * decompression logic loop. */ + struct compressed_block_header last_block_hdr; +}; + +/* Forward function declarations. */ + +static void rar5_signature(char *buf); +static int verify_global_checksums(struct archive_read* a); +static int rar5_read_data_skip(struct archive_read *a); +static int push_data_ready(struct archive_read* a, struct rar5* rar, + const uint8_t* buf, size_t size, int64_t offset); + +/* CDE_xxx = Circular Double Ended (Queue) return values. */ +enum CDE_RETURN_VALUES { + CDE_OK, CDE_ALLOC, CDE_PARAM, CDE_OUT_OF_BOUNDS, +}; + +/* Clears the contents of this circular deque. */ +static void cdeque_clear(struct cdeque* d) { + d->size = 0; + d->beg_pos = 0; + d->end_pos = 0; +} + +/* Creates a new circular deque object. Capacity must be power of 2: 8, 16, 32, + * 64, 256, etc. When the user will add another item above current capacity, + * the circular deque will overwrite the oldest entry. */ +static int cdeque_init(struct cdeque* d, int max_capacity_power_of_2) { + if(d == NULL || max_capacity_power_of_2 == 0) + return CDE_PARAM; + + d->cap_mask = max_capacity_power_of_2 - 1; + d->arr = NULL; + + if((max_capacity_power_of_2 & d->cap_mask) != 0) + return CDE_PARAM; + + cdeque_clear(d); + d->arr = malloc(sizeof(void*) * max_capacity_power_of_2); + + return d->arr ? CDE_OK : CDE_ALLOC; +} + +/* Return the current size (not capacity) of circular deque `d`. */ +static size_t cdeque_size(struct cdeque* d) { + return d->size; +} + +/* Returns the first element of current circular deque. Note that this function + * doesn't perform any bounds checking. If you need bounds checking, use + * `cdeque_front()` function instead. */ +static void cdeque_front_fast(struct cdeque* d, void** value) { + *value = (void*) d->arr[d->beg_pos]; +} + +/* Returns the first element of current circular deque. This function + * performs bounds checking. */ +static int cdeque_front(struct cdeque* d, void** value) { + if(d->size > 0) { + cdeque_front_fast(d, value); + return CDE_OK; + } else + return CDE_OUT_OF_BOUNDS; +} + +/* Pushes a new element into the end of this circular deque object. If current + * size will exceed capacity, the oldest element will be overwritten. */ +static int cdeque_push_back(struct cdeque* d, void* item) { + if(d == NULL) + return CDE_PARAM; + + if(d->size == d->cap_mask + 1) + return CDE_OUT_OF_BOUNDS; + + d->arr[d->end_pos] = (size_t) item; + d->end_pos = (d->end_pos + 1) & d->cap_mask; + d->size++; + + return CDE_OK; +} + +/* Pops a front element of this circular deque object and returns its value. + * This function doesn't perform any bounds checking. */ +static void cdeque_pop_front_fast(struct cdeque* d, void** value) { + *value = (void*) d->arr[d->beg_pos]; + d->beg_pos = (d->beg_pos + 1) & d->cap_mask; + d->size--; +} + +/* Pops a front element of this circular deque object and returns its value. + * This function performs bounds checking. */ +static int cdeque_pop_front(struct cdeque* d, void** value) { + if(!d || !value) + return CDE_PARAM; + + if(d->size == 0) + return CDE_OUT_OF_BOUNDS; + + cdeque_pop_front_fast(d, value); + return CDE_OK; +} + +/* Convenience function to cast filter_info** to void **. */ +static void** cdeque_filter_p(struct filter_info** f) { + return (void**) (size_t) f; +} + +/* Convenience function to cast filter_info* to void *. */ +static void* cdeque_filter(struct filter_info* f) { + return (void**) (size_t) f; +} + +/* Destroys this circular deque object. Deallocates the memory of the + * collection buffer, but doesn't deallocate the memory of any pointer passed + * to this deque as a value. */ +static void cdeque_free(struct cdeque* d) { + if(!d) + return; + + if(!d->arr) + return; + + free(d->arr); + + d->arr = NULL; + d->beg_pos = -1; + d->end_pos = -1; + d->cap_mask = 0; +} + +static inline +uint8_t bf_bit_size(const struct compressed_block_header* hdr) { + return hdr->block_flags_u8 & 7; +} + +static inline +uint8_t bf_byte_count(const struct compressed_block_header* hdr) { + return (hdr->block_flags_u8 >> 3) & 7; +} + +static inline +uint8_t bf_is_table_present(const struct compressed_block_header* hdr) { + return (hdr->block_flags_u8 >> 7) & 1; +} + +static inline struct rar5* get_context(struct archive_read* a) { + return (struct rar5*) a->format->data; +} + +/* Convenience functions used by filter implementations. */ +static void circular_memcpy(uint8_t* dst, uint8_t* window, const uint64_t mask, + int64_t start, int64_t end) +{ + if((start & mask) > (end & mask)) { + ssize_t len1 = mask + 1 - (start & mask); + ssize_t len2 = end & mask; + + memcpy(dst, &window[start & mask], len1); + memcpy(dst + len1, window, len2); + } else { + memcpy(dst, &window[start & mask], (size_t) (end - start)); + } +} + +static uint32_t read_filter_data(struct rar5* rar, uint32_t offset) { + uint8_t linear_buf[4]; + circular_memcpy(linear_buf, rar->cstate.window_buf, + rar->cstate.window_mask, offset, offset + 4); + return archive_le32dec(linear_buf); +} + +static void write_filter_data(struct rar5* rar, uint32_t offset, + uint32_t value) +{ + archive_le32enc(&rar->cstate.filtered_buf[offset], value); +} + +/* Allocates a new filter descriptor and adds it to the filter array. */ +static struct filter_info* add_new_filter(struct rar5* rar) { + struct filter_info* f = + (struct filter_info*) calloc(1, sizeof(struct filter_info)); + + if(!f) { + return NULL; + } + + cdeque_push_back(&rar->cstate.filters, cdeque_filter(f)); + return f; +} + +static int run_delta_filter(struct rar5* rar, struct filter_info* flt) { + int i; + ssize_t dest_pos, src_pos = 0; + + for(i = 0; i < flt->channels; i++) { + uint8_t prev_byte = 0; + for(dest_pos = i; + dest_pos < flt->block_length; + dest_pos += flt->channels) + { + uint8_t byte; + + byte = rar->cstate.window_buf[ + (rar->cstate.solid_offset + flt->block_start + + src_pos) & rar->cstate.window_mask]; + + prev_byte -= byte; + rar->cstate.filtered_buf[dest_pos] = prev_byte; + src_pos++; + } + } + + return ARCHIVE_OK; +} + +static int run_e8e9_filter(struct rar5* rar, struct filter_info* flt, + int extended) +{ + const uint32_t file_size = 0x1000000; + ssize_t i; + + circular_memcpy(rar->cstate.filtered_buf, + rar->cstate.window_buf, rar->cstate.window_mask, + rar->cstate.solid_offset + flt->block_start, + rar->cstate.solid_offset + flt->block_start + flt->block_length); + + for(i = 0; i < flt->block_length - 4;) { + uint8_t b = rar->cstate.window_buf[ + (rar->cstate.solid_offset + flt->block_start + + i++) & rar->cstate.window_mask]; + + /* + * 0xE8 = x86's call <relative_addr_uint32> (function call) + * 0xE9 = x86's jmp <relative_addr_uint32> (unconditional jump) + */ + if(b == 0xE8 || (extended && b == 0xE9)) { + + uint32_t addr; + uint32_t offset = (i + flt->block_start) % file_size; + + addr = read_filter_data(rar, + (uint32_t)(rar->cstate.solid_offset + + flt->block_start + i) & rar->cstate.window_mask); + + if(addr & 0x80000000) { + if(((addr + offset) & 0x80000000) == 0) { + write_filter_data(rar, (uint32_t)i, + addr + file_size); + } + } else { + if((addr - file_size) & 0x80000000) { + uint32_t naddr = addr - offset; + write_filter_data(rar, (uint32_t)i, + naddr); + } + } + + i += 4; + } + } + + return ARCHIVE_OK; +} + +static int run_arm_filter(struct rar5* rar, struct filter_info* flt) { + ssize_t i = 0; + uint32_t offset; + + circular_memcpy(rar->cstate.filtered_buf, + rar->cstate.window_buf, rar->cstate.window_mask, + rar->cstate.solid_offset + flt->block_start, + rar->cstate.solid_offset + flt->block_start + flt->block_length); + + for(i = 0; i < flt->block_length - 3; i += 4) { + uint8_t* b = &rar->cstate.window_buf[ + (rar->cstate.solid_offset + + flt->block_start + i + 3) & rar->cstate.window_mask]; + + if(*b == 0xEB) { + /* 0xEB = ARM's BL (branch + link) instruction. */ + offset = read_filter_data(rar, + (rar->cstate.solid_offset + flt->block_start + i) & + rar->cstate.window_mask) & 0x00ffffff; + + offset -= (uint32_t) ((i + flt->block_start) / 4); + offset = (offset & 0x00ffffff) | 0xeb000000; + write_filter_data(rar, (uint32_t)i, offset); + } + } + + return ARCHIVE_OK; +} + +static int run_filter(struct archive_read* a, struct filter_info* flt) { + int ret; + struct rar5* rar = get_context(a); + + free(rar->cstate.filtered_buf); + + rar->cstate.filtered_buf = malloc(flt->block_length); + if(!rar->cstate.filtered_buf) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for filter data."); + return ARCHIVE_FATAL; + } + + switch(flt->type) { + case FILTER_DELTA: + ret = run_delta_filter(rar, flt); + break; + + case FILTER_E8: + /* fallthrough */ + case FILTER_E8E9: + ret = run_e8e9_filter(rar, flt, + flt->type == FILTER_E8E9); + break; + + case FILTER_ARM: + ret = run_arm_filter(rar, flt); + break; + + default: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Unsupported filter type: 0x%x", flt->type); + return ARCHIVE_FATAL; + } + + if(ret != ARCHIVE_OK) { + /* Filter has failed. */ + return ret; + } + + if(ARCHIVE_OK != push_data_ready(a, rar, rar->cstate.filtered_buf, + flt->block_length, rar->cstate.last_write_ptr)) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Stack overflow when submitting unpacked data"); + + return ARCHIVE_FATAL; + } + + rar->cstate.last_write_ptr += flt->block_length; + return ARCHIVE_OK; +} + +/* The `push_data` function submits the selected data range to the user. + * Next call of `use_data` will use the pointer, size and offset arguments + * that are specified here. These arguments are pushed to the FIFO stack here, + * and popped from the stack by the `use_data` function. */ +static void push_data(struct archive_read* a, struct rar5* rar, + const uint8_t* buf, int64_t idx_begin, int64_t idx_end) +{ + const uint64_t wmask = rar->cstate.window_mask; + const ssize_t solid_write_ptr = (rar->cstate.solid_offset + + rar->cstate.last_write_ptr) & wmask; + + idx_begin += rar->cstate.solid_offset; + idx_end += rar->cstate.solid_offset; + + /* Check if our unpacked data is wrapped inside the window circular + * buffer. If it's not wrapped, it can be copied out by using + * a single memcpy, but when it's wrapped, we need to copy the first + * part with one memcpy, and the second part with another memcpy. */ + + if((idx_begin & wmask) > (idx_end & wmask)) { + /* The data is wrapped (begin offset sis bigger than end + * offset). */ + const ssize_t frag1_size = rar->cstate.window_size - + (idx_begin & wmask); + const ssize_t frag2_size = idx_end & wmask; + + /* Copy the first part of the buffer first. */ + push_data_ready(a, rar, buf + solid_write_ptr, frag1_size, + rar->cstate.last_write_ptr); + + /* Copy the second part of the buffer. */ + push_data_ready(a, rar, buf, frag2_size, + rar->cstate.last_write_ptr + frag1_size); + + rar->cstate.last_write_ptr += frag1_size + frag2_size; + } else { + /* Data is not wrapped, so we can just use one call to copy the + * data. */ + push_data_ready(a, rar, + buf + solid_write_ptr, (idx_end - idx_begin) & wmask, + rar->cstate.last_write_ptr); + + rar->cstate.last_write_ptr += idx_end - idx_begin; + } +} + +/* Convenience function that submits the data to the user. It uses the + * unpack window buffer as a source location. */ +static void push_window_data(struct archive_read* a, struct rar5* rar, + int64_t idx_begin, int64_t idx_end) +{ + push_data(a, rar, rar->cstate.window_buf, idx_begin, idx_end); +} + +static int apply_filters(struct archive_read* a) { + struct filter_info* flt; + struct rar5* rar = get_context(a); + int ret; + + rar->cstate.all_filters_applied = 0; + + /* Get the first filter that can be applied to our data. The data + * needs to be fully unpacked before the filter can be run. */ + if(CDE_OK == cdeque_front(&rar->cstate.filters, + cdeque_filter_p(&flt))) { + /* Check if our unpacked data fully covers this filter's + * range. */ + if(rar->cstate.write_ptr > flt->block_start && + rar->cstate.write_ptr >= flt->block_start + + flt->block_length) { + /* Check if we have some data pending to be written + * right before the filter's start offset. */ + if(rar->cstate.last_write_ptr == flt->block_start) { + /* Run the filter specified by descriptor + * `flt`. */ + ret = run_filter(a, flt); + if(ret != ARCHIVE_OK) { + /* Filter failure, return error. */ + return ret; + } + + /* Filter descriptor won't be needed anymore + * after it's used, * so remove it from the + * filter list and free its memory. */ + (void) cdeque_pop_front(&rar->cstate.filters, + cdeque_filter_p(&flt)); + + free(flt); + } else { + /* We can't run filters yet, dump the memory + * right before the filter. */ + push_window_data(a, rar, + rar->cstate.last_write_ptr, + flt->block_start); + } + + /* Return 'filter applied or not needed' state to the + * caller. */ + return ARCHIVE_RETRY; + } + } + + rar->cstate.all_filters_applied = 1; + return ARCHIVE_OK; +} + +static void dist_cache_push(struct rar5* rar, int value) { + int* q = rar->cstate.dist_cache; + + q[3] = q[2]; + q[2] = q[1]; + q[1] = q[0]; + q[0] = value; +} + +static int dist_cache_touch(struct rar5* rar, int idx) { + int* q = rar->cstate.dist_cache; + int i, dist = q[idx]; + + for(i = idx; i > 0; i--) + q[i] = q[i - 1]; + + q[0] = dist; + return dist; +} + +static void free_filters(struct rar5* rar) { + struct cdeque* d = &rar->cstate.filters; + + /* Free any remaining filters. All filters should be naturally + * consumed by the unpacking function, so remaining filters after + * unpacking normally mean that unpacking wasn't successful. + * But still of course we shouldn't leak memory in such case. */ + + /* cdeque_size() is a fast operation, so we can use it as a loop + * expression. */ + while(cdeque_size(d) > 0) { + struct filter_info* f = NULL; + + /* Pop_front will also decrease the collection's size. */ + if (CDE_OK == cdeque_pop_front(d, cdeque_filter_p(&f))) + free(f); + } + + cdeque_clear(d); + + /* Also clear out the variables needed for sanity checking. */ + rar->cstate.last_block_start = 0; + rar->cstate.last_block_length = 0; +} + +static void reset_file_context(struct rar5* rar) { + memset(&rar->file, 0, sizeof(rar->file)); + blake2sp_init(&rar->file.b2state, 32); + + if(rar->main.solid) { + rar->cstate.solid_offset += rar->cstate.write_ptr; + } else { + rar->cstate.solid_offset = 0; + } + + rar->cstate.write_ptr = 0; + rar->cstate.last_write_ptr = 0; + rar->cstate.last_unstore_ptr = 0; + + rar->file.redir_type = REDIR_TYPE_NONE; + rar->file.redir_flags = 0; + + free_filters(rar); +} + +static inline int get_archive_read(struct archive* a, + struct archive_read** ar) +{ + *ar = (struct archive_read*) a; + archive_check_magic(a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, + "archive_read_support_format_rar5"); + + return ARCHIVE_OK; +} + +static int read_ahead(struct archive_read* a, size_t how_many, + const uint8_t** ptr) +{ + ssize_t avail = -1; + if(!ptr) + return 0; + + *ptr = __archive_read_ahead(a, how_many, &avail); + if(*ptr == NULL) { + return 0; + } + + return 1; +} + +static int consume(struct archive_read* a, int64_t how_many) { + int ret; + + ret = how_many == __archive_read_consume(a, how_many) + ? ARCHIVE_OK + : ARCHIVE_FATAL; + + return ret; +} + +/** + * Read a RAR5 variable sized numeric value. This value will be stored in + * `pvalue`. The `pvalue_len` argument points to a variable that will receive + * the byte count that was consumed in order to decode the `pvalue` value, plus + * one. + * + * pvalue_len is optional and can be NULL. + * + * NOTE: if `pvalue_len` is NOT NULL, the caller needs to manually consume + * the number of bytes that `pvalue_len` value contains. If the `pvalue_len` + * is NULL, this consuming operation is done automatically. + * + * Returns 1 if *pvalue was successfully read. + * Returns 0 if there was an error. In this case, *pvalue contains an + * invalid value. + */ + +static int read_var(struct archive_read* a, uint64_t* pvalue, + uint64_t* pvalue_len) +{ + uint64_t result = 0; + size_t shift, i; + const uint8_t* p; + uint8_t b; + + /* We will read maximum of 8 bytes. We don't have to handle the + * situation to read the RAR5 variable-sized value stored at the end of + * the file, because such situation will never happen. */ + if(!read_ahead(a, 8, &p)) + return 0; + + for(shift = 0, i = 0; i < 8; i++, shift += 7) { + b = p[i]; + + /* Strip the MSB from the input byte and add the resulting + * number to the `result`. */ + result += (b & (uint64_t)0x7F) << shift; + + /* MSB set to 1 means we need to continue decoding process. + * MSB set to 0 means we're done. + * + * This conditional checks for the second case. */ + if((b & 0x80) == 0) { + if(pvalue) { + *pvalue = result; + } + + /* If the caller has passed the `pvalue_len` pointer, + * store the number of consumed bytes in it and do NOT + * consume those bytes, since the caller has all the + * information it needs to perform */ + if(pvalue_len) { + *pvalue_len = 1 + i; + } else { + /* If the caller did not provide the + * `pvalue_len` pointer, it will not have the + * possibility to advance the file pointer, + * because it will not know how many bytes it + * needs to consume. This is why we handle + * such situation here automatically. */ + if(ARCHIVE_OK != consume(a, 1 + i)) { + return 0; + } + } + + /* End of decoding process, return success. */ + return 1; + } + } + + /* The decoded value takes the maximum number of 8 bytes. + * It's a maximum number of bytes, so end decoding process here + * even if the first bit of last byte is 1. */ + if(pvalue) { + *pvalue = result; + } + + if(pvalue_len) { + *pvalue_len = 9; + } else { + if(ARCHIVE_OK != consume(a, 9)) { + return 0; + } + } + + return 1; +} + +static int read_var_sized(struct archive_read* a, size_t* pvalue, + size_t* pvalue_len) +{ + uint64_t v; + uint64_t v_size = 0; + + const int ret = pvalue_len ? read_var(a, &v, &v_size) + : read_var(a, &v, NULL); + + if(ret == 1 && pvalue) { + *pvalue = (size_t) v; + } + + if(pvalue_len) { + /* Possible data truncation should be safe. */ + *pvalue_len = (size_t) v_size; + } + + return ret; +} + +static int read_bits_32(struct rar5* rar, const uint8_t* p, uint32_t* value) { + uint32_t bits = ((uint32_t) p[rar->bits.in_addr]) << 24; + bits |= p[rar->bits.in_addr + 1] << 16; + bits |= p[rar->bits.in_addr + 2] << 8; + bits |= p[rar->bits.in_addr + 3]; + bits <<= rar->bits.bit_addr; + bits |= p[rar->bits.in_addr + 4] >> (8 - rar->bits.bit_addr); + *value = bits; + return ARCHIVE_OK; +} + +static int read_bits_16(struct rar5* rar, const uint8_t* p, uint16_t* value) { + int bits = (int) ((uint32_t) p[rar->bits.in_addr]) << 16; + bits |= (int) p[rar->bits.in_addr + 1] << 8; + bits |= (int) p[rar->bits.in_addr + 2]; + bits >>= (8 - rar->bits.bit_addr); + *value = bits & 0xffff; + return ARCHIVE_OK; +} + +static void skip_bits(struct rar5* rar, int bits) { + const int new_bits = rar->bits.bit_addr + bits; + rar->bits.in_addr += new_bits >> 3; + rar->bits.bit_addr = new_bits & 7; +} + +/* n = up to 16 */ +static int read_consume_bits(struct rar5* rar, const uint8_t* p, int n, + int* value) +{ + uint16_t v; + int ret, num; + + if(n == 0 || n > 16) { + /* This is a programmer error and should never happen + * in runtime. */ + return ARCHIVE_FATAL; + } + + ret = read_bits_16(rar, p, &v); + if(ret != ARCHIVE_OK) + return ret; + + num = (int) v; + num >>= 16 - n; + + skip_bits(rar, n); + + if(value) + *value = num; + + return ARCHIVE_OK; +} + +static int read_u32(struct archive_read* a, uint32_t* pvalue) { + const uint8_t* p; + if(!read_ahead(a, 4, &p)) + return 0; + + *pvalue = archive_le32dec(p); + return ARCHIVE_OK == consume(a, 4) ? 1 : 0; +} + +static int read_u64(struct archive_read* a, uint64_t* pvalue) { + const uint8_t* p; + if(!read_ahead(a, 8, &p)) + return 0; + + *pvalue = archive_le64dec(p); + return ARCHIVE_OK == consume(a, 8) ? 1 : 0; +} + +static int bid_standard(struct archive_read* a) { + const uint8_t* p; + char signature[sizeof(rar5_signature_xor)]; + + rar5_signature(signature); + + if(!read_ahead(a, sizeof(rar5_signature_xor), &p)) + return -1; + + if(!memcmp(signature, p, sizeof(rar5_signature_xor))) + return 30; + + return -1; +} + +static int rar5_bid(struct archive_read* a, int best_bid) { + int my_bid; + + if(best_bid > 30) + return -1; + + my_bid = bid_standard(a); + if(my_bid > -1) { + return my_bid; + } + + return -1; +} + +static int rar5_options(struct archive_read *a, const char *key, + const char *val) { + (void) a; + (void) key; + (void) val; + + /* No options supported in this version. Return the ARCHIVE_WARN code + * to signal the options supervisor that the unpacker didn't handle + * setting this option. */ + + return ARCHIVE_WARN; +} + +static void init_header(struct archive_read* a) { + a->archive.archive_format = ARCHIVE_FORMAT_RAR_V5; + a->archive.archive_format_name = "RAR5"; +} + +static void init_window_mask(struct rar5* rar) { + if (rar->cstate.window_size) + rar->cstate.window_mask = rar->cstate.window_size - 1; + else + rar->cstate.window_mask = 0; +} + +enum HEADER_FLAGS { + HFL_EXTRA_DATA = 0x0001, + HFL_DATA = 0x0002, + HFL_SKIP_IF_UNKNOWN = 0x0004, + HFL_SPLIT_BEFORE = 0x0008, + HFL_SPLIT_AFTER = 0x0010, + HFL_CHILD = 0x0020, + HFL_INHERITED = 0x0040 +}; + +static int process_main_locator_extra_block(struct archive_read* a, + struct rar5* rar) +{ + uint64_t locator_flags; + + enum LOCATOR_FLAGS { + QLIST = 0x01, RECOVERY = 0x02, + }; + + if(!read_var(a, &locator_flags, NULL)) { + return ARCHIVE_EOF; + } + + if(locator_flags & QLIST) { + if(!read_var(a, &rar->qlist_offset, NULL)) { + return ARCHIVE_EOF; + } + + /* qlist is not used */ + } + + if(locator_flags & RECOVERY) { + if(!read_var(a, &rar->rr_offset, NULL)) { + return ARCHIVE_EOF; + } + + /* rr is not used */ + } + + return ARCHIVE_OK; +} + +static int parse_file_extra_hash(struct archive_read* a, struct rar5* rar, + ssize_t* extra_data_size) +{ + size_t hash_type = 0; + size_t value_len; + + enum HASH_TYPE { + BLAKE2sp = 0x00 + }; + + if(!read_var_sized(a, &hash_type, &value_len)) + return ARCHIVE_EOF; + + *extra_data_size -= value_len; + if(ARCHIVE_OK != consume(a, value_len)) { + return ARCHIVE_EOF; + } + + /* The file uses BLAKE2sp checksum algorithm instead of plain old + * CRC32. */ + if(hash_type == BLAKE2sp) { + const uint8_t* p; + const int hash_size = sizeof(rar->file.blake2sp); + + if(!read_ahead(a, hash_size, &p)) + return ARCHIVE_EOF; + + rar->file.has_blake2 = 1; + memcpy(&rar->file.blake2sp, p, hash_size); + + if(ARCHIVE_OK != consume(a, hash_size)) { + return ARCHIVE_EOF; + } + + *extra_data_size -= hash_size; + } else { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Unsupported hash type (0x%x)", (int) hash_type); + return ARCHIVE_FATAL; + } + + return ARCHIVE_OK; +} + +static uint64_t time_win_to_unix(uint64_t win_time) { + const size_t ns_in_sec = 10000000; + const uint64_t sec_to_unix = 11644473600LL; + return win_time / ns_in_sec - sec_to_unix; +} + +static int parse_htime_item(struct archive_read* a, char unix_time, + uint64_t* where, ssize_t* extra_data_size) +{ + if(unix_time) { + uint32_t time_val; + if(!read_u32(a, &time_val)) + return ARCHIVE_EOF; + + *extra_data_size -= 4; + *where = (uint64_t) time_val; + } else { + uint64_t windows_time; + if(!read_u64(a, &windows_time)) + return ARCHIVE_EOF; + + *where = time_win_to_unix(windows_time); + *extra_data_size -= 8; + } + + return ARCHIVE_OK; +} + +static int parse_file_extra_version(struct archive_read* a, + struct archive_entry* e, ssize_t* extra_data_size) +{ + size_t flags = 0; + size_t version = 0; + size_t value_len = 0; + struct archive_string version_string; + struct archive_string name_utf8_string; + const char* cur_filename; + + /* Flags are ignored. */ + if(!read_var_sized(a, &flags, &value_len)) + return ARCHIVE_EOF; + + *extra_data_size -= value_len; + if(ARCHIVE_OK != consume(a, value_len)) + return ARCHIVE_EOF; + + if(!read_var_sized(a, &version, &value_len)) + return ARCHIVE_EOF; + + *extra_data_size -= value_len; + if(ARCHIVE_OK != consume(a, value_len)) + return ARCHIVE_EOF; + + /* extra_data_size should be zero here. */ + + cur_filename = archive_entry_pathname_utf8(e); + if(cur_filename == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Version entry without file name"); + return ARCHIVE_FATAL; + } + + archive_string_init(&version_string); + archive_string_init(&name_utf8_string); + + /* Prepare a ;123 suffix for the filename, where '123' is the version + * value of this file. */ + archive_string_sprintf(&version_string, ";%zu", version); + + /* Build the new filename. */ + archive_strcat(&name_utf8_string, cur_filename); + archive_strcat(&name_utf8_string, version_string.s); + + /* Apply the new filename into this file's context. */ + archive_entry_update_pathname_utf8(e, name_utf8_string.s); + + /* Free buffers. */ + archive_string_free(&version_string); + archive_string_free(&name_utf8_string); + return ARCHIVE_OK; +} + +static int parse_file_extra_htime(struct archive_read* a, + struct archive_entry* e, struct rar5* rar, ssize_t* extra_data_size) +{ + char unix_time = 0; + size_t flags = 0; + size_t value_len; + + enum HTIME_FLAGS { + IS_UNIX = 0x01, + HAS_MTIME = 0x02, + HAS_CTIME = 0x04, + HAS_ATIME = 0x08, + HAS_UNIX_NS = 0x10, + }; + + if(!read_var_sized(a, &flags, &value_len)) + return ARCHIVE_EOF; + + *extra_data_size -= value_len; + if(ARCHIVE_OK != consume(a, value_len)) { + return ARCHIVE_EOF; + } + + unix_time = flags & IS_UNIX; + + if(flags & HAS_MTIME) { + parse_htime_item(a, unix_time, &rar->file.e_mtime, + extra_data_size); + archive_entry_set_mtime(e, rar->file.e_mtime, 0); + } + + if(flags & HAS_CTIME) { + parse_htime_item(a, unix_time, &rar->file.e_ctime, + extra_data_size); + archive_entry_set_ctime(e, rar->file.e_ctime, 0); + } + + if(flags & HAS_ATIME) { + parse_htime_item(a, unix_time, &rar->file.e_atime, + extra_data_size); + archive_entry_set_atime(e, rar->file.e_atime, 0); + } + + if(flags & HAS_UNIX_NS) { + if(!read_u32(a, &rar->file.e_unix_ns)) + return ARCHIVE_EOF; + + *extra_data_size -= 4; + } + + return ARCHIVE_OK; +} + +static int parse_file_extra_redir(struct archive_read* a, + struct archive_entry* e, struct rar5* rar, ssize_t* extra_data_size) +{ + uint64_t value_size = 0; + size_t target_size = 0; + char target_utf8_buf[MAX_NAME_IN_BYTES]; + const uint8_t* p; + + if(!read_var(a, &rar->file.redir_type, &value_size)) + return ARCHIVE_EOF; + if(ARCHIVE_OK != consume(a, (int64_t)value_size)) + return ARCHIVE_EOF; + *extra_data_size -= value_size; + + if(!read_var(a, &rar->file.redir_flags, &value_size)) + return ARCHIVE_EOF; + if(ARCHIVE_OK != consume(a, (int64_t)value_size)) + return ARCHIVE_EOF; + *extra_data_size -= value_size; + + if(!read_var_sized(a, &target_size, NULL)) + return ARCHIVE_EOF; + *extra_data_size -= target_size + 1; + + if(!read_ahead(a, target_size, &p)) + return ARCHIVE_EOF; + + if(target_size > (MAX_NAME_IN_CHARS - 1)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Link target is too long"); + return ARCHIVE_FATAL; + } + + if(target_size == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "No link target specified"); + return ARCHIVE_FATAL; + } + + memcpy(target_utf8_buf, p, target_size); + target_utf8_buf[target_size] = 0; + + if(ARCHIVE_OK != consume(a, (int64_t)target_size)) + return ARCHIVE_EOF; + + switch(rar->file.redir_type) { + case REDIR_TYPE_UNIXSYMLINK: + case REDIR_TYPE_WINSYMLINK: + archive_entry_set_filetype(e, AE_IFLNK); + archive_entry_update_symlink_utf8(e, target_utf8_buf); + if (rar->file.redir_flags & REDIR_SYMLINK_IS_DIR) { + archive_entry_set_symlink_type(e, + AE_SYMLINK_TYPE_DIRECTORY); + } else { + archive_entry_set_symlink_type(e, + AE_SYMLINK_TYPE_FILE); + } + break; + + case REDIR_TYPE_HARDLINK: + archive_entry_set_filetype(e, AE_IFREG); + archive_entry_update_hardlink_utf8(e, target_utf8_buf); + break; + + default: + /* Unknown redir type, skip it. */ + break; + } + return ARCHIVE_OK; +} + +static int parse_file_extra_owner(struct archive_read* a, + struct archive_entry* e, ssize_t* extra_data_size) +{ + uint64_t flags = 0; + uint64_t value_size = 0; + uint64_t id = 0; + size_t name_len = 0; + size_t name_size = 0; + char namebuf[OWNER_MAXNAMELEN]; + const uint8_t* p; + + if(!read_var(a, &flags, &value_size)) + return ARCHIVE_EOF; + if(ARCHIVE_OK != consume(a, (int64_t)value_size)) + return ARCHIVE_EOF; + *extra_data_size -= value_size; + + if ((flags & OWNER_USER_NAME) != 0) { + if(!read_var_sized(a, &name_size, NULL)) + return ARCHIVE_EOF; + *extra_data_size -= name_size + 1; + + if(!read_ahead(a, name_size, &p)) + return ARCHIVE_EOF; + + if (name_size >= OWNER_MAXNAMELEN) { + name_len = OWNER_MAXNAMELEN - 1; + } else { + name_len = name_size; + } + + memcpy(namebuf, p, name_len); + namebuf[name_len] = 0; + if(ARCHIVE_OK != consume(a, (int64_t)name_size)) + return ARCHIVE_EOF; + + archive_entry_set_uname(e, namebuf); + } + if ((flags & OWNER_GROUP_NAME) != 0) { + if(!read_var_sized(a, &name_size, NULL)) + return ARCHIVE_EOF; + *extra_data_size -= name_size + 1; + + if(!read_ahead(a, name_size, &p)) + return ARCHIVE_EOF; + + if (name_size >= OWNER_MAXNAMELEN) { + name_len = OWNER_MAXNAMELEN - 1; + } else { + name_len = name_size; + } + + memcpy(namebuf, p, name_len); + namebuf[name_len] = 0; + if(ARCHIVE_OK != consume(a, (int64_t)name_size)) + return ARCHIVE_EOF; + + archive_entry_set_gname(e, namebuf); + } + if ((flags & OWNER_USER_UID) != 0) { + if(!read_var(a, &id, &value_size)) + return ARCHIVE_EOF; + if(ARCHIVE_OK != consume(a, (int64_t)value_size)) + return ARCHIVE_EOF; + *extra_data_size -= value_size; + + archive_entry_set_uid(e, (la_int64_t)id); + } + if ((flags & OWNER_GROUP_GID) != 0) { + if(!read_var(a, &id, &value_size)) + return ARCHIVE_EOF; + if(ARCHIVE_OK != consume(a, (int64_t)value_size)) + return ARCHIVE_EOF; + *extra_data_size -= value_size; + + archive_entry_set_gid(e, (la_int64_t)id); + } + return ARCHIVE_OK; +} + +static int process_head_file_extra(struct archive_read* a, + struct archive_entry* e, struct rar5* rar, ssize_t extra_data_size) +{ + size_t extra_field_size; + size_t extra_field_id = 0; + int ret = ARCHIVE_FATAL; + size_t var_size; + + while(extra_data_size > 0) { + if(!read_var_sized(a, &extra_field_size, &var_size)) + return ARCHIVE_EOF; + + extra_data_size -= var_size; + if(ARCHIVE_OK != consume(a, var_size)) { + return ARCHIVE_EOF; + } + + if(!read_var_sized(a, &extra_field_id, &var_size)) + return ARCHIVE_EOF; + + extra_data_size -= var_size; + if(ARCHIVE_OK != consume(a, var_size)) { + return ARCHIVE_EOF; + } + + switch(extra_field_id) { + case EX_HASH: + ret = parse_file_extra_hash(a, rar, + &extra_data_size); + break; + case EX_HTIME: + ret = parse_file_extra_htime(a, e, rar, + &extra_data_size); + break; + case EX_REDIR: + ret = parse_file_extra_redir(a, e, rar, + &extra_data_size); + break; + case EX_UOWNER: + ret = parse_file_extra_owner(a, e, + &extra_data_size); + break; + case EX_VERSION: + ret = parse_file_extra_version(a, e, + &extra_data_size); + break; + case EX_CRYPT: + /* fallthrough */ + case EX_SUBDATA: + /* fallthrough */ + default: + /* Skip unsupported entry. */ + return consume(a, extra_data_size); + } + } + + if(ret != ARCHIVE_OK) { + /* Attribute not implemented. */ + return ret; + } + + return ARCHIVE_OK; +} + +static int process_head_file(struct archive_read* a, struct rar5* rar, + struct archive_entry* entry, size_t block_flags) +{ + ssize_t extra_data_size = 0; + size_t data_size = 0; + size_t file_flags = 0; + size_t file_attr = 0; + size_t compression_info = 0; + size_t host_os = 0; + size_t name_size = 0; + uint64_t unpacked_size, window_size; + uint32_t mtime = 0, crc = 0; + int c_method = 0, c_version = 0; + char name_utf8_buf[MAX_NAME_IN_BYTES]; + const uint8_t* p; + + enum FILE_FLAGS { + DIRECTORY = 0x0001, UTIME = 0x0002, CRC32 = 0x0004, + UNKNOWN_UNPACKED_SIZE = 0x0008, + }; + + enum FILE_ATTRS { + ATTR_READONLY = 0x1, ATTR_HIDDEN = 0x2, ATTR_SYSTEM = 0x4, + ATTR_DIRECTORY = 0x10, + }; + + enum COMP_INFO_FLAGS { + SOLID = 0x0040, + }; + + enum HOST_OS { + HOST_WINDOWS = 0, + HOST_UNIX = 1, + }; + + archive_entry_clear(entry); + + /* Do not reset file context if we're switching archives. */ + if(!rar->cstate.switch_multivolume) { + reset_file_context(rar); + } + + if(block_flags & HFL_EXTRA_DATA) { + size_t edata_size = 0; + if(!read_var_sized(a, &edata_size, NULL)) + return ARCHIVE_EOF; + + /* Intentional type cast from unsigned to signed. */ + extra_data_size = (ssize_t) edata_size; + } + + if(block_flags & HFL_DATA) { + if(!read_var_sized(a, &data_size, NULL)) + return ARCHIVE_EOF; + + rar->file.bytes_remaining = data_size; + } else { + rar->file.bytes_remaining = 0; + + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "no data found in file/service block"); + return ARCHIVE_FATAL; + } + + if(!read_var_sized(a, &file_flags, NULL)) + return ARCHIVE_EOF; + + if(!read_var(a, &unpacked_size, NULL)) + return ARCHIVE_EOF; + + if(file_flags & UNKNOWN_UNPACKED_SIZE) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Files with unknown unpacked size are not supported"); + return ARCHIVE_FATAL; + } + + rar->file.dir = (uint8_t) ((file_flags & DIRECTORY) > 0); + + if(!read_var_sized(a, &file_attr, NULL)) + return ARCHIVE_EOF; + + if(file_flags & UTIME) { + if(!read_u32(a, &mtime)) + return ARCHIVE_EOF; + } + + if(file_flags & CRC32) { + if(!read_u32(a, &crc)) + return ARCHIVE_EOF; + } + + if(!read_var_sized(a, &compression_info, NULL)) + return ARCHIVE_EOF; + + c_method = (int) (compression_info >> 7) & 0x7; + c_version = (int) (compression_info & 0x3f); + + /* RAR5 seems to limit the dictionary size to 64MB. */ + window_size = (rar->file.dir > 0) ? + 0 : + g_unpack_window_size << ((compression_info >> 10) & 15); + rar->cstate.method = c_method; + rar->cstate.version = c_version + 50; + rar->file.solid = (compression_info & SOLID) > 0; + + /* Archives which declare solid files without initializing the window + * buffer first are invalid. */ + + if(rar->file.solid > 0 && rar->cstate.window_buf == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Declared solid file, but no window buffer " + "initialized yet."); + return ARCHIVE_FATAL; + } + + /* Check if window_size is a sane value. Also, if the file is not + * declared as a directory, disallow window_size == 0. */ + if(window_size > (64 * 1024 * 1024) || + (rar->file.dir == 0 && window_size == 0)) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Declared dictionary size is not supported."); + return ARCHIVE_FATAL; + } + + if(rar->file.solid > 0) { + /* Re-check if current window size is the same as previous + * window size (for solid files only). */ + if(rar->file.solid_window_size > 0 && + rar->file.solid_window_size != (ssize_t) window_size) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Window size for this solid file doesn't match " + "the window size used in previous solid file. "); + return ARCHIVE_FATAL; + } + } + + /* If we're currently switching volumes, ignore the new definition of + * window_size. */ + if(rar->cstate.switch_multivolume == 0) { + /* Values up to 64M should fit into ssize_t on every + * architecture. */ + rar->cstate.window_size = (ssize_t) window_size; + } + + if(rar->file.solid > 0 && rar->file.solid_window_size == 0) { + /* Solid files have to have the same window_size across + whole archive. Remember the window_size parameter + for first solid file found. */ + rar->file.solid_window_size = rar->cstate.window_size; + } + + init_window_mask(rar); + + rar->file.service = 0; + + if(!read_var_sized(a, &host_os, NULL)) + return ARCHIVE_EOF; + + if(host_os == HOST_WINDOWS) { + /* Host OS is Windows */ + + __LA_MODE_T mode; + + if(file_attr & ATTR_DIRECTORY) { + if (file_attr & ATTR_READONLY) { + mode = 0555 | AE_IFDIR; + } else { + mode = 0755 | AE_IFDIR; + } + } else { + if (file_attr & ATTR_READONLY) { + mode = 0444 | AE_IFREG; + } else { + mode = 0644 | AE_IFREG; + } + } + + archive_entry_set_mode(entry, mode); + + if (file_attr & (ATTR_READONLY | ATTR_HIDDEN | ATTR_SYSTEM)) { + char *fflags_text, *ptr; + /* allocate for "rdonly,hidden,system," */ + fflags_text = malloc(22 * sizeof(char)); + if (fflags_text != NULL) { + ptr = fflags_text; + if (file_attr & ATTR_READONLY) { + strcpy(ptr, "rdonly,"); + ptr = ptr + 7; + } + if (file_attr & ATTR_HIDDEN) { + strcpy(ptr, "hidden,"); + ptr = ptr + 7; + } + if (file_attr & ATTR_SYSTEM) { + strcpy(ptr, "system,"); + ptr = ptr + 7; + } + if (ptr > fflags_text) { + /* Delete trailing comma */ + *(ptr - 1) = '\0'; + archive_entry_copy_fflags_text(entry, + fflags_text); + } + free(fflags_text); + } + } + } else if(host_os == HOST_UNIX) { + /* Host OS is Unix */ + archive_entry_set_mode(entry, (__LA_MODE_T) file_attr); + } else { + /* Unknown host OS */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Unsupported Host OS: 0x%x", (int) host_os); + + return ARCHIVE_FATAL; + } + + if(!read_var_sized(a, &name_size, NULL)) + return ARCHIVE_EOF; + + if(!read_ahead(a, name_size, &p)) + return ARCHIVE_EOF; + + if(name_size > (MAX_NAME_IN_CHARS - 1)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Filename is too long"); + + return ARCHIVE_FATAL; + } + + if(name_size == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "No filename specified"); + + return ARCHIVE_FATAL; + } + + memcpy(name_utf8_buf, p, name_size); + name_utf8_buf[name_size] = 0; + if(ARCHIVE_OK != consume(a, name_size)) { + return ARCHIVE_EOF; + } + + archive_entry_update_pathname_utf8(entry, name_utf8_buf); + + if(extra_data_size > 0) { + int ret = process_head_file_extra(a, entry, rar, + extra_data_size); + + /* + * TODO: rewrite or remove useless sanity check + * as extra_data_size is not passed as a pointer + * + if(extra_data_size < 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "File extra data size is not zero"); + return ARCHIVE_FATAL; + } + */ + + if(ret != ARCHIVE_OK) + return ret; + } + + if((file_flags & UNKNOWN_UNPACKED_SIZE) == 0) { + rar->file.unpacked_size = (ssize_t) unpacked_size; + if(rar->file.redir_type == REDIR_TYPE_NONE) + archive_entry_set_size(entry, unpacked_size); + } + + if(file_flags & UTIME) { + archive_entry_set_mtime(entry, (time_t) mtime, 0); + } + + if(file_flags & CRC32) { + rar->file.stored_crc32 = crc; + } + + if(!rar->cstate.switch_multivolume) { + /* Do not reinitialize unpacking state if we're switching + * archives. */ + rar->cstate.block_parsing_finished = 1; + rar->cstate.all_filters_applied = 1; + rar->cstate.initialized = 0; + } + + if(rar->generic.split_before > 0) { + /* If now we're standing on a header that has a 'split before' + * mark, it means we're standing on a 'continuation' file + * header. Signal the caller that if it wants to move to + * another file, it must call rar5_read_header() function + * again. */ + + return ARCHIVE_RETRY; + } else { + return ARCHIVE_OK; + } +} + +static int process_head_service(struct archive_read* a, struct rar5* rar, + struct archive_entry* entry, size_t block_flags) +{ + /* Process this SERVICE block the same way as FILE blocks. */ + int ret = process_head_file(a, rar, entry, block_flags); + if(ret != ARCHIVE_OK) + return ret; + + rar->file.service = 1; + + /* But skip the data part automatically. It's no use for the user + * anyway. It contains only service data, not even needed to + * properly unpack the file. */ + ret = rar5_read_data_skip(a); + if(ret != ARCHIVE_OK) + return ret; + + /* After skipping, try parsing another block automatically. */ + return ARCHIVE_RETRY; +} + +static int process_head_main(struct archive_read* a, struct rar5* rar, + struct archive_entry* entry, size_t block_flags) +{ + int ret; + size_t extra_data_size = 0; + size_t extra_field_size = 0; + size_t extra_field_id = 0; + size_t archive_flags = 0; + + enum MAIN_FLAGS { + VOLUME = 0x0001, /* multi-volume archive */ + VOLUME_NUMBER = 0x0002, /* volume number, first vol doesn't + * have it */ + SOLID = 0x0004, /* solid archive */ + PROTECT = 0x0008, /* contains Recovery info */ + LOCK = 0x0010, /* readonly flag, not used */ + }; + + enum MAIN_EXTRA { + // Just one attribute here. + LOCATOR = 0x01, + }; + + (void) entry; + + if(block_flags & HFL_EXTRA_DATA) { + if(!read_var_sized(a, &extra_data_size, NULL)) + return ARCHIVE_EOF; + } else { + extra_data_size = 0; + } + + if(!read_var_sized(a, &archive_flags, NULL)) { + return ARCHIVE_EOF; + } + + rar->main.volume = (archive_flags & VOLUME) > 0; + rar->main.solid = (archive_flags & SOLID) > 0; + + if(archive_flags & VOLUME_NUMBER) { + size_t v = 0; + if(!read_var_sized(a, &v, NULL)) { + return ARCHIVE_EOF; + } + + if (v > UINT_MAX) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid volume number"); + return ARCHIVE_FATAL; + } + + rar->main.vol_no = (unsigned int) v; + } else { + rar->main.vol_no = 0; + } + + if(rar->vol.expected_vol_no > 0 && + rar->main.vol_no != rar->vol.expected_vol_no) + { + /* Returning EOF instead of FATAL because of strange + * libarchive behavior. When opening multiple files via + * archive_read_open_filenames(), after reading up the whole + * last file, the __archive_read_ahead function wraps up to + * the first archive instead of returning EOF. */ + return ARCHIVE_EOF; + } + + if(extra_data_size == 0) { + /* Early return. */ + return ARCHIVE_OK; + } + + if(!read_var_sized(a, &extra_field_size, NULL)) { + return ARCHIVE_EOF; + } + + if(!read_var_sized(a, &extra_field_id, NULL)) { + return ARCHIVE_EOF; + } + + if(extra_field_size == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid extra field size"); + return ARCHIVE_FATAL; + } + + switch(extra_field_id) { + case LOCATOR: + ret = process_main_locator_extra_block(a, rar); + if(ret != ARCHIVE_OK) { + /* Error while parsing main locator extra + * block. */ + return ret; + } + + break; + default: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Unsupported extra type (0x%x)", + (int) extra_field_id); + return ARCHIVE_FATAL; + } + + return ARCHIVE_OK; +} + +static int skip_unprocessed_bytes(struct archive_read* a) { + struct rar5* rar = get_context(a); + int ret; + + if(rar->file.bytes_remaining) { + /* Use different skipping method in block merging mode than in + * normal mode. If merge mode is active, rar5_read_data_skip + * can't be used, because it could allow recursive use of + * merge_block() * function, and this function doesn't support + * recursive use. */ + if(rar->merge_mode) { + /* Discard whole merged block. This is valid in solid + * mode as well, because the code will discard blocks + * only if those blocks are safe to discard (i.e. + * they're not FILE blocks). */ + ret = consume(a, rar->file.bytes_remaining); + if(ret != ARCHIVE_OK) { + return ret; + } + rar->file.bytes_remaining = 0; + } else { + /* If we're not in merge mode, use safe skipping code. + * This will ensure we'll handle solid archives + * properly. */ + ret = rar5_read_data_skip(a); + if(ret != ARCHIVE_OK) { + return ret; + } + } + } + + return ARCHIVE_OK; +} + +static int scan_for_signature(struct archive_read* a); + +/* Base block processing function. A 'base block' is a RARv5 header block + * that tells the reader what kind of data is stored inside the block. + * + * From the birds-eye view a RAR file looks file this: + * + * <magic><base_block_1><base_block_2>...<base_block_n> + * + * There are a few types of base blocks. Those types are specified inside + * the 'switch' statement in this function. For example purposes, I'll write + * how a standard RARv5 file could look like here: + * + * <magic><MAIN><FILE><FILE><FILE><SERVICE><ENDARC> + * + * The structure above could describe an archive file with 3 files in it, + * one service "QuickOpen" block (that is ignored by this parser), and an + * end of file base block marker. + * + * If the file is stored in multiple archive files ("multiarchive"), it might + * look like this: + * + * .part01.rar: <magic><MAIN><FILE><ENDARC> + * .part02.rar: <magic><MAIN><FILE><ENDARC> + * .part03.rar: <magic><MAIN><FILE><ENDARC> + * + * This example could describe 3 RAR files that contain ONE archived file. + * Or it could describe 3 RAR files that contain 3 different files. Or 3 + * RAR files than contain 2 files. It all depends what metadata is stored in + * the headers of <FILE> blocks. + * + * Each <FILE> block contains info about its size, the name of the file it's + * storing inside, and whether this FILE block is a continuation block of + * previous archive ('split before'), and is this FILE block should be + * continued in another archive ('split after'). By parsing the 'split before' + * and 'split after' flags, we're able to tell if multiple <FILE> base blocks + * are describing one file, or multiple files (with the same filename, for + * example). + * + * One thing to note is that if we're parsing the first <FILE> block, and + * we see 'split after' flag, then we need to jump over to another <FILE> + * block to be able to decompress rest of the data. To do this, we need + * to skip the <ENDARC> block, then switch to another file, then skip the + * <magic> block, <MAIN> block, and then we're standing on the proper + * <FILE> block. + */ + +static int process_base_block(struct archive_read* a, + struct archive_entry* entry) +{ + const size_t SMALLEST_RAR5_BLOCK_SIZE = 3; + + struct rar5* rar = get_context(a); + uint32_t hdr_crc, computed_crc; + size_t raw_hdr_size = 0, hdr_size_len, hdr_size; + size_t header_id = 0; + size_t header_flags = 0; + const uint8_t* p; + int ret; + + enum HEADER_TYPE { + HEAD_MARK = 0x00, HEAD_MAIN = 0x01, HEAD_FILE = 0x02, + HEAD_SERVICE = 0x03, HEAD_CRYPT = 0x04, HEAD_ENDARC = 0x05, + HEAD_UNKNOWN = 0xff, + }; + + /* Skip any unprocessed data for this file. */ + ret = skip_unprocessed_bytes(a); + if(ret != ARCHIVE_OK) + return ret; + + /* Read the expected CRC32 checksum. */ + if(!read_u32(a, &hdr_crc)) { + return ARCHIVE_EOF; + } + + /* Read header size. */ + if(!read_var_sized(a, &raw_hdr_size, &hdr_size_len)) { + return ARCHIVE_EOF; + } + + hdr_size = raw_hdr_size + hdr_size_len; + + /* Sanity check, maximum header size for RAR5 is 2MB. */ + if(hdr_size > (2 * 1024 * 1024)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Base block header is too large"); + + return ARCHIVE_FATAL; + } + + /* Additional sanity checks to weed out invalid files. */ + if(raw_hdr_size == 0 || hdr_size_len == 0 || + hdr_size < SMALLEST_RAR5_BLOCK_SIZE) + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Too small block encountered (%zu bytes)", + raw_hdr_size); + + return ARCHIVE_FATAL; + } + + /* Read the whole header data into memory, maximum memory use here is + * 2MB. */ + if(!read_ahead(a, hdr_size, &p)) { + return ARCHIVE_EOF; + } + + /* Verify the CRC32 of the header data. */ + computed_crc = (uint32_t) crc32(0, p, (int) hdr_size); + if(computed_crc != hdr_crc) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Header CRC error"); + + return ARCHIVE_FATAL; + } + + /* If the checksum is OK, we proceed with parsing. */ + if(ARCHIVE_OK != consume(a, hdr_size_len)) { + return ARCHIVE_EOF; + } + + if(!read_var_sized(a, &header_id, NULL)) + return ARCHIVE_EOF; + + if(!read_var_sized(a, &header_flags, NULL)) + return ARCHIVE_EOF; + + rar->generic.split_after = (header_flags & HFL_SPLIT_AFTER) > 0; + rar->generic.split_before = (header_flags & HFL_SPLIT_BEFORE) > 0; + rar->generic.size = (int)hdr_size; + rar->generic.last_header_id = (int)header_id; + rar->main.endarc = 0; + + /* Those are possible header ids in RARv5. */ + switch(header_id) { + case HEAD_MAIN: + ret = process_head_main(a, rar, entry, header_flags); + + /* Main header doesn't have any files in it, so it's + * pointless to return to the caller. Retry to next + * header, which should be HEAD_FILE/HEAD_SERVICE. */ + if(ret == ARCHIVE_OK) + return ARCHIVE_RETRY; + + return ret; + case HEAD_SERVICE: + ret = process_head_service(a, rar, entry, header_flags); + return ret; + case HEAD_FILE: + ret = process_head_file(a, rar, entry, header_flags); + return ret; + case HEAD_CRYPT: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Encryption is not supported"); + return ARCHIVE_FATAL; + case HEAD_ENDARC: + rar->main.endarc = 1; + + /* After encountering an end of file marker, we need + * to take into consideration if this archive is + * continued in another file (i.e. is it part01.rar: + * is there a part02.rar?) */ + if(rar->main.volume) { + /* In case there is part02.rar, position the + * read pointer in a proper place, so we can + * resume parsing. */ + ret = scan_for_signature(a); + if(ret == ARCHIVE_FATAL) { + return ARCHIVE_EOF; + } else { + if(rar->vol.expected_vol_no == + UINT_MAX) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Header error"); + return ARCHIVE_FATAL; + } + + rar->vol.expected_vol_no = + rar->main.vol_no + 1; + return ARCHIVE_OK; + } + } else { + return ARCHIVE_EOF; + } + case HEAD_MARK: + return ARCHIVE_EOF; + default: + if((header_flags & HFL_SKIP_IF_UNKNOWN) == 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Header type error"); + return ARCHIVE_FATAL; + } else { + /* If the block is marked as 'skip if unknown', + * do as the flag says: skip the block + * instead on failing on it. */ + return ARCHIVE_RETRY; + } + } + +#if !defined WIN32 + // Not reached. + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Internal unpacker error"); + return ARCHIVE_FATAL; +#endif +} + +static int skip_base_block(struct archive_read* a) { + int ret; + struct rar5* rar = get_context(a); + + /* Create a new local archive_entry structure that will be operated on + * by header reader; operations on this archive_entry will be discarded. + */ + struct archive_entry* entry = archive_entry_new(); + ret = process_base_block(a, entry); + + /* Discard operations on this archive_entry structure. */ + archive_entry_free(entry); + if(ret == ARCHIVE_FATAL) + return ret; + + if(rar->generic.last_header_id == 2 && rar->generic.split_before > 0) + return ARCHIVE_OK; + + if(ret == ARCHIVE_OK) + return ARCHIVE_RETRY; + else + return ret; +} + +static int rar5_read_header(struct archive_read *a, + struct archive_entry *entry) +{ + struct rar5* rar = get_context(a); + int ret; + + if(rar->header_initialized == 0) { + init_header(a); + rar->header_initialized = 1; + } + + if(rar->skipped_magic == 0) { + if(ARCHIVE_OK != consume(a, sizeof(rar5_signature_xor))) { + return ARCHIVE_EOF; + } + + rar->skipped_magic = 1; + } + + do { + ret = process_base_block(a, entry); + } while(ret == ARCHIVE_RETRY || + (rar->main.endarc > 0 && ret == ARCHIVE_OK)); + + return ret; +} + +static void init_unpack(struct rar5* rar) { + rar->file.calculated_crc32 = 0; + init_window_mask(rar); + + free(rar->cstate.window_buf); + free(rar->cstate.filtered_buf); + + if(rar->cstate.window_size > 0) { + rar->cstate.window_buf = calloc(1, rar->cstate.window_size); + rar->cstate.filtered_buf = calloc(1, rar->cstate.window_size); + } else { + rar->cstate.window_buf = NULL; + rar->cstate.filtered_buf = NULL; + } + + rar->cstate.write_ptr = 0; + rar->cstate.last_write_ptr = 0; + + memset(&rar->cstate.bd, 0, sizeof(rar->cstate.bd)); + memset(&rar->cstate.ld, 0, sizeof(rar->cstate.ld)); + memset(&rar->cstate.dd, 0, sizeof(rar->cstate.dd)); + memset(&rar->cstate.ldd, 0, sizeof(rar->cstate.ldd)); + memset(&rar->cstate.rd, 0, sizeof(rar->cstate.rd)); +} + +static void update_crc(struct rar5* rar, const uint8_t* p, size_t to_read) { + int verify_crc; + + if(rar->skip_mode) { +#if defined CHECK_CRC_ON_SOLID_SKIP + verify_crc = 1; +#else + verify_crc = 0; +#endif + } else + verify_crc = 1; + + if(verify_crc) { + /* Don't update CRC32 if the file doesn't have the + * `stored_crc32` info filled in. */ + if(rar->file.stored_crc32 > 0) { + rar->file.calculated_crc32 = + crc32(rar->file.calculated_crc32, p, to_read); + } + + /* Check if the file uses an optional BLAKE2sp checksum + * algorithm. */ + if(rar->file.has_blake2 > 0) { + /* Return value of the `update` function is always 0, + * so we can explicitly ignore it here. */ + (void) blake2sp_update(&rar->file.b2state, p, to_read); + } + } +} + +static int create_decode_tables(uint8_t* bit_length, + struct decode_table* table, int size) +{ + int code, upper_limit = 0, i, lc[16]; + uint32_t decode_pos_clone[rar5_countof(table->decode_pos)]; + ssize_t cur_len, quick_data_size; + + memset(&lc, 0, sizeof(lc)); + memset(table->decode_num, 0, sizeof(table->decode_num)); + table->size = size; + table->quick_bits = size == HUFF_NC ? 10 : 7; + + for(i = 0; i < size; i++) { + lc[bit_length[i] & 15]++; + } + + lc[0] = 0; + table->decode_pos[0] = 0; + table->decode_len[0] = 0; + + for(i = 1; i < 16; i++) { + upper_limit += lc[i]; + + table->decode_len[i] = upper_limit << (16 - i); + table->decode_pos[i] = table->decode_pos[i - 1] + lc[i - 1]; + + upper_limit <<= 1; + } + + memcpy(decode_pos_clone, table->decode_pos, sizeof(decode_pos_clone)); + + for(i = 0; i < size; i++) { + uint8_t clen = bit_length[i] & 15; + if(clen > 0) { + int last_pos = decode_pos_clone[clen]; + table->decode_num[last_pos] = i; + decode_pos_clone[clen]++; + } + } + + quick_data_size = (int64_t)1 << table->quick_bits; + cur_len = 1; + for(code = 0; code < quick_data_size; code++) { + int bit_field = code << (16 - table->quick_bits); + int dist, pos; + + while(cur_len < rar5_countof(table->decode_len) && + bit_field >= table->decode_len[cur_len]) { + cur_len++; + } + + table->quick_len[code] = (uint8_t) cur_len; + + dist = bit_field - table->decode_len[cur_len - 1]; + dist >>= (16 - cur_len); + + pos = table->decode_pos[cur_len & 15] + dist; + if(cur_len < rar5_countof(table->decode_pos) && pos < size) { + table->quick_num[code] = table->decode_num[pos]; + } else { + table->quick_num[code] = 0; + } + } + + return ARCHIVE_OK; +} + +static int decode_number(struct archive_read* a, struct decode_table* table, + const uint8_t* p, uint16_t* num) +{ + int i, bits, dist; + uint16_t bitfield; + uint32_t pos; + struct rar5* rar = get_context(a); + + if(ARCHIVE_OK != read_bits_16(rar, p, &bitfield)) { + return ARCHIVE_EOF; + } + + bitfield &= 0xfffe; + + if(bitfield < table->decode_len[table->quick_bits]) { + int code = bitfield >> (16 - table->quick_bits); + skip_bits(rar, table->quick_len[code]); + *num = table->quick_num[code]; + return ARCHIVE_OK; + } + + bits = 15; + + for(i = table->quick_bits + 1; i < 15; i++) { + if(bitfield < table->decode_len[i]) { + bits = i; + break; + } + } + + skip_bits(rar, bits); + + dist = bitfield - table->decode_len[bits - 1]; + dist >>= (16 - bits); + pos = table->decode_pos[bits] + dist; + + if(pos >= table->size) + pos = 0; + + *num = table->decode_num[pos]; + return ARCHIVE_OK; +} + +/* Reads and parses Huffman tables from the beginning of the block. */ +static int parse_tables(struct archive_read* a, struct rar5* rar, + const uint8_t* p) +{ + int ret, value, i, w, idx = 0; + uint8_t bit_length[HUFF_BC], + table[HUFF_TABLE_SIZE], + nibble_mask = 0xF0, + nibble_shift = 4; + + enum { ESCAPE = 15 }; + + /* The data for table generation is compressed using a simple RLE-like + * algorithm when storing zeroes, so we need to unpack it first. */ + for(w = 0, i = 0; w < HUFF_BC;) { + if(i >= rar->cstate.cur_block_size) { + /* Truncated data, can't continue. */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated data in huffman tables"); + return ARCHIVE_FATAL; + } + + value = (p[i] & nibble_mask) >> nibble_shift; + + if(nibble_mask == 0x0F) + ++i; + + nibble_mask ^= 0xFF; + nibble_shift ^= 4; + + /* Values smaller than 15 is data, so we write it directly. + * Value 15 is a flag telling us that we need to unpack more + * bytes. */ + if(value == ESCAPE) { + value = (p[i] & nibble_mask) >> nibble_shift; + if(nibble_mask == 0x0F) + ++i; + nibble_mask ^= 0xFF; + nibble_shift ^= 4; + + if(value == 0) { + /* We sometimes need to write the actual value + * of 15, so this case handles that. */ + bit_length[w++] = ESCAPE; + } else { + int k; + + /* Fill zeroes. */ + for(k = 0; (k < value + 2) && (w < HUFF_BC); + k++) { + bit_length[w++] = 0; + } + } + } else { + bit_length[w++] = value; + } + } + + rar->bits.in_addr = i; + rar->bits.bit_addr = nibble_shift ^ 4; + + ret = create_decode_tables(bit_length, &rar->cstate.bd, HUFF_BC); + if(ret != ARCHIVE_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Decoding huffman tables failed"); + return ARCHIVE_FATAL; + } + + for(i = 0; i < HUFF_TABLE_SIZE;) { + uint16_t num; + + if((rar->bits.in_addr + 6) >= rar->cstate.cur_block_size) { + /* Truncated data, can't continue. */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated data in huffman tables (#2)"); + return ARCHIVE_FATAL; + } + + ret = decode_number(a, &rar->cstate.bd, p, &num); + if(ret != ARCHIVE_OK) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Decoding huffman tables failed"); + return ARCHIVE_FATAL; + } + + if(num < 16) { + /* 0..15: store directly */ + table[i] = (uint8_t) num; + i++; + } else if(num < 18) { + /* 16..17: repeat previous code */ + uint16_t n; + + if(ARCHIVE_OK != read_bits_16(rar, p, &n)) + return ARCHIVE_EOF; + + if(num == 16) { + n >>= 13; + n += 3; + skip_bits(rar, 3); + } else { + n >>= 9; + n += 11; + skip_bits(rar, 7); + } + + if(i > 0) { + while(n-- > 0 && i < HUFF_TABLE_SIZE) { + table[i] = table[i - 1]; + i++; + } + } else { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Unexpected error when decoding " + "huffman tables"); + return ARCHIVE_FATAL; + } + } else { + /* other codes: fill with zeroes `n` times */ + uint16_t n; + + if(ARCHIVE_OK != read_bits_16(rar, p, &n)) + return ARCHIVE_EOF; + + if(num == 18) { + n >>= 13; + n += 3; + skip_bits(rar, 3); + } else { + n >>= 9; + n += 11; + skip_bits(rar, 7); + } + + while(n-- > 0 && i < HUFF_TABLE_SIZE) + table[i++] = 0; + } + } + + ret = create_decode_tables(&table[idx], &rar->cstate.ld, HUFF_NC); + if(ret != ARCHIVE_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Failed to create literal table"); + return ARCHIVE_FATAL; + } + + idx += HUFF_NC; + + ret = create_decode_tables(&table[idx], &rar->cstate.dd, HUFF_DC); + if(ret != ARCHIVE_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Failed to create distance table"); + return ARCHIVE_FATAL; + } + + idx += HUFF_DC; + + ret = create_decode_tables(&table[idx], &rar->cstate.ldd, HUFF_LDC); + if(ret != ARCHIVE_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Failed to create lower bits of distances table"); + return ARCHIVE_FATAL; + } + + idx += HUFF_LDC; + + ret = create_decode_tables(&table[idx], &rar->cstate.rd, HUFF_RC); + if(ret != ARCHIVE_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Failed to create repeating distances table"); + return ARCHIVE_FATAL; + } + + return ARCHIVE_OK; +} + +/* Parses the block header, verifies its CRC byte, and saves the header + * fields inside the `hdr` pointer. */ +static int parse_block_header(struct archive_read* a, const uint8_t* p, + ssize_t* block_size, struct compressed_block_header* hdr) +{ + uint8_t calculated_cksum; + memcpy(hdr, p, sizeof(struct compressed_block_header)); + + if(bf_byte_count(hdr) > 2) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Unsupported block header size (was %d, max is 2)", + bf_byte_count(hdr)); + return ARCHIVE_FATAL; + } + + /* This should probably use bit reader interface in order to be more + * future-proof. */ + *block_size = 0; + switch(bf_byte_count(hdr)) { + /* 1-byte block size */ + case 0: + *block_size = *(const uint8_t*) &p[2]; + break; + + /* 2-byte block size */ + case 1: + *block_size = archive_le16dec(&p[2]); + break; + + /* 3-byte block size */ + case 2: + *block_size = archive_le32dec(&p[2]); + *block_size &= 0x00FFFFFF; + break; + + /* Other block sizes are not supported. This case is not + * reached, because we have an 'if' guard before the switch + * that makes sure of it. */ + default: + return ARCHIVE_FATAL; + } + + /* Verify the block header checksum. 0x5A is a magic value and is + * always * constant. */ + calculated_cksum = 0x5A + ^ (uint8_t) hdr->block_flags_u8 + ^ (uint8_t) *block_size + ^ (uint8_t) (*block_size >> 8) + ^ (uint8_t) (*block_size >> 16); + + if(calculated_cksum != hdr->block_cksum) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Block checksum error: got 0x%x, expected 0x%x", + hdr->block_cksum, calculated_cksum); + + return ARCHIVE_FATAL; + } + + return ARCHIVE_OK; +} + +/* Convenience function used during filter processing. */ +static int parse_filter_data(struct rar5* rar, const uint8_t* p, + uint32_t* filter_data) +{ + int i, bytes; + uint32_t data = 0; + + if(ARCHIVE_OK != read_consume_bits(rar, p, 2, &bytes)) + return ARCHIVE_EOF; + + bytes++; + + for(i = 0; i < bytes; i++) { + uint16_t byte; + + if(ARCHIVE_OK != read_bits_16(rar, p, &byte)) { + return ARCHIVE_EOF; + } + + /* Cast to uint32_t will ensure the shift operation will not + * produce undefined result. */ + data += ((uint32_t) byte >> 8) << (i * 8); + skip_bits(rar, 8); + } + + *filter_data = data; + return ARCHIVE_OK; +} + +/* Function is used during sanity checking. */ +static int is_valid_filter_block_start(struct rar5* rar, + uint32_t start) +{ + const int64_t block_start = (ssize_t) start + rar->cstate.write_ptr; + const int64_t last_bs = rar->cstate.last_block_start; + const ssize_t last_bl = rar->cstate.last_block_length; + + if(last_bs == 0 || last_bl == 0) { + /* We didn't have any filters yet, so accept this offset. */ + return 1; + } + + if(block_start >= last_bs + last_bl) { + /* Current offset is bigger than last block's end offset, so + * accept current offset. */ + return 1; + } + + /* Any other case is not a normal situation and we should fail. */ + return 0; +} + +/* The function will create a new filter, read its parameters from the input + * stream and add it to the filter collection. */ +static int parse_filter(struct archive_read* ar, const uint8_t* p) { + uint32_t block_start, block_length; + uint16_t filter_type; + struct filter_info* filt = NULL; + struct rar5* rar = get_context(ar); + + /* Read the parameters from the input stream. */ + if(ARCHIVE_OK != parse_filter_data(rar, p, &block_start)) + return ARCHIVE_EOF; + + if(ARCHIVE_OK != parse_filter_data(rar, p, &block_length)) + return ARCHIVE_EOF; + + if(ARCHIVE_OK != read_bits_16(rar, p, &filter_type)) + return ARCHIVE_EOF; + + filter_type >>= 13; + skip_bits(rar, 3); + + /* Perform some sanity checks on this filter parameters. Note that we + * allow only DELTA, E8/E9 and ARM filters here, because rest of + * filters are not used in RARv5. */ + + if(block_length < 4 || + block_length > 0x400000 || + filter_type > FILTER_ARM || + !is_valid_filter_block_start(rar, block_start)) + { + archive_set_error(&ar->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid filter encountered"); + return ARCHIVE_FATAL; + } + + /* Allocate a new filter. */ + filt = add_new_filter(rar); + if(filt == NULL) { + archive_set_error(&ar->archive, ENOMEM, + "Can't allocate memory for a filter descriptor."); + return ARCHIVE_FATAL; + } + + filt->type = filter_type; + filt->block_start = rar->cstate.write_ptr + block_start; + filt->block_length = block_length; + + rar->cstate.last_block_start = filt->block_start; + rar->cstate.last_block_length = filt->block_length; + + /* Read some more data in case this is a DELTA filter. Other filter + * types don't require any additional data over what was already + * read. */ + if(filter_type == FILTER_DELTA) { + int channels; + + if(ARCHIVE_OK != read_consume_bits(rar, p, 5, &channels)) + return ARCHIVE_EOF; + + filt->channels = channels + 1; + } + + return ARCHIVE_OK; +} + +static int decode_code_length(struct rar5* rar, const uint8_t* p, + uint16_t code) +{ + int lbits, length = 2; + if(code < 8) { + lbits = 0; + length += code; + } else { + lbits = code / 4 - 1; + length += (4 | (code & 3)) << lbits; + } + + if(lbits > 0) { + int add; + + if(ARCHIVE_OK != read_consume_bits(rar, p, lbits, &add)) + return -1; + + length += add; + } + + return length; +} + +static int copy_string(struct archive_read* a, int len, int dist) { + struct rar5* rar = get_context(a); + const uint64_t cmask = rar->cstate.window_mask; + const uint64_t write_ptr = rar->cstate.write_ptr + + rar->cstate.solid_offset; + int i; + + if (rar->cstate.window_buf == NULL) + return ARCHIVE_FATAL; + + /* The unpacker spends most of the time in this function. It would be + * a good idea to introduce some optimizations here. + * + * Just remember that this loop treats buffers that overlap differently + * than buffers that do not overlap. This is why a simple memcpy(3) + * call will not be enough. */ + + for(i = 0; i < len; i++) { + const ssize_t write_idx = (write_ptr + i) & cmask; + const ssize_t read_idx = (write_ptr + i - dist) & cmask; + rar->cstate.window_buf[write_idx] = + rar->cstate.window_buf[read_idx]; + } + + rar->cstate.write_ptr += len; + return ARCHIVE_OK; +} + +static int do_uncompress_block(struct archive_read* a, const uint8_t* p) { + struct rar5* rar = get_context(a); + uint16_t num; + int ret; + + const uint64_t cmask = rar->cstate.window_mask; + const struct compressed_block_header* hdr = &rar->last_block_hdr; + const uint8_t bit_size = 1 + bf_bit_size(hdr); + + while(1) { + if(rar->cstate.write_ptr - rar->cstate.last_write_ptr > + (rar->cstate.window_size >> 1)) { + /* Don't allow growing data by more than half of the + * window size at a time. In such case, break the loop; + * next call to this function will continue processing + * from this moment. */ + break; + } + + if(rar->bits.in_addr > rar->cstate.cur_block_size - 1 || + (rar->bits.in_addr == rar->cstate.cur_block_size - 1 && + rar->bits.bit_addr >= bit_size)) + { + /* If the program counter is here, it means the + * function has finished processing the block. */ + rar->cstate.block_parsing_finished = 1; + break; + } + + /* Decode the next literal. */ + if(ARCHIVE_OK != decode_number(a, &rar->cstate.ld, p, &num)) { + return ARCHIVE_EOF; + } + + /* Num holds a decompression literal, or 'command code'. + * + * - Values lower than 256 are just bytes. Those codes + * can be stored in the output buffer directly. + * + * - Code 256 defines a new filter, which is later used to + * ransform the data block accordingly to the filter type. + * The data block needs to be fully uncompressed first. + * + * - Code bigger than 257 and smaller than 262 define + * a repetition pattern that should be copied from + * an already uncompressed chunk of data. + */ + + if(num < 256) { + /* Directly store the byte. */ + int64_t write_idx = rar->cstate.solid_offset + + rar->cstate.write_ptr++; + + rar->cstate.window_buf[write_idx & cmask] = + (uint8_t) num; + continue; + } else if(num >= 262) { + uint16_t dist_slot; + int len = decode_code_length(rar, p, num - 262), + dbits, + dist = 1; + + if(len == -1) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_PROGRAMMER, + "Failed to decode the code length"); + + return ARCHIVE_FATAL; + } + + if(ARCHIVE_OK != decode_number(a, &rar->cstate.dd, p, + &dist_slot)) + { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_PROGRAMMER, + "Failed to decode the distance slot"); + + return ARCHIVE_FATAL; + } + + if(dist_slot < 4) { + dbits = 0; + dist += dist_slot; + } else { + dbits = dist_slot / 2 - 1; + + /* Cast to uint32_t will make sure the shift + * left operation won't produce undefined + * result. Then, the uint32_t type will + * be implicitly casted to int. */ + dist += (uint32_t) (2 | + (dist_slot & 1)) << dbits; + } + + if(dbits > 0) { + if(dbits >= 4) { + uint32_t add = 0; + uint16_t low_dist; + + if(dbits > 4) { + if(ARCHIVE_OK != read_bits_32( + rar, p, &add)) { + /* Return EOF if we + * can't read more + * data. */ + return ARCHIVE_EOF; + } + + skip_bits(rar, dbits - 4); + add = (add >> ( + 36 - dbits)) << 4; + dist += add; + } + + if(ARCHIVE_OK != decode_number(a, + &rar->cstate.ldd, p, &low_dist)) + { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_PROGRAMMER, + "Failed to decode the " + "distance slot"); + + return ARCHIVE_FATAL; + } + + if(dist >= INT_MAX - low_dist - 1) { + /* This only happens in + * invalid archives. */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Distance pointer " + "overflow"); + return ARCHIVE_FATAL; + } + + dist += low_dist; + } else { + /* dbits is one of [0,1,2,3] */ + int add; + + if(ARCHIVE_OK != read_consume_bits(rar, + p, dbits, &add)) { + /* Return EOF if we can't read + * more data. */ + return ARCHIVE_EOF; + } + + dist += add; + } + } + + if(dist > 0x100) { + len++; + + if(dist > 0x2000) { + len++; + + if(dist > 0x40000) { + len++; + } + } + } + + dist_cache_push(rar, dist); + rar->cstate.last_len = len; + + if(ARCHIVE_OK != copy_string(a, len, dist)) + return ARCHIVE_FATAL; + + continue; + } else if(num == 256) { + /* Create a filter. */ + ret = parse_filter(a, p); + if(ret != ARCHIVE_OK) + return ret; + + continue; + } else if(num == 257) { + if(rar->cstate.last_len != 0) { + if(ARCHIVE_OK != copy_string(a, + rar->cstate.last_len, + rar->cstate.dist_cache[0])) + { + return ARCHIVE_FATAL; + } + } + + continue; + } else { + /* num < 262 */ + const int idx = num - 258; + const int dist = dist_cache_touch(rar, idx); + + uint16_t len_slot; + int len; + + if(ARCHIVE_OK != decode_number(a, &rar->cstate.rd, p, + &len_slot)) { + return ARCHIVE_FATAL; + } + + len = decode_code_length(rar, p, len_slot); + rar->cstate.last_len = len; + + if(ARCHIVE_OK != copy_string(a, len, dist)) + return ARCHIVE_FATAL; + + continue; + } + } + + return ARCHIVE_OK; +} + +/* Binary search for the RARv5 signature. */ +static int scan_for_signature(struct archive_read* a) { + const uint8_t* p; + const int chunk_size = 512; + ssize_t i; + char signature[sizeof(rar5_signature_xor)]; + + /* If we're here, it means we're on an 'unknown territory' data. + * There's no indication what kind of data we're reading here. + * It could be some text comment, any kind of binary data, + * digital sign, dragons, etc. + * + * We want to find a valid RARv5 magic header inside this unknown + * data. */ + + /* Is it possible in libarchive to just skip everything until the + * end of the file? If so, it would be a better approach than the + * current implementation of this function. */ + + rar5_signature(signature); + + while(1) { + if(!read_ahead(a, chunk_size, &p)) + return ARCHIVE_EOF; + + for(i = 0; i < chunk_size - (int)sizeof(rar5_signature_xor); + i++) { + if(memcmp(&p[i], signature, + sizeof(rar5_signature_xor)) == 0) { + /* Consume the number of bytes we've used to + * search for the signature, as well as the + * number of bytes used by the signature + * itself. After this we should be standing + * on a valid base block header. */ + (void) consume(a, + i + sizeof(rar5_signature_xor)); + return ARCHIVE_OK; + } + } + + consume(a, chunk_size); + } + + return ARCHIVE_FATAL; +} + +/* This function will switch the multivolume archive file to another file, + * i.e. from part03 to part 04. */ +static int advance_multivolume(struct archive_read* a) { + int lret; + struct rar5* rar = get_context(a); + + /* A small state machine that will skip unnecessary data, needed to + * switch from one multivolume to another. Such skipping is needed if + * we want to be an stream-oriented (instead of file-oriented) + * unpacker. + * + * The state machine starts with `rar->main.endarc` == 0. It also + * assumes that current stream pointer points to some base block + * header. + * + * The `endarc` field is being set when the base block parsing + * function encounters the 'end of archive' marker. + */ + + while(1) { + if(rar->main.endarc == 1) { + int looping = 1; + + rar->main.endarc = 0; + + while(looping) { + lret = skip_base_block(a); + switch(lret) { + case ARCHIVE_RETRY: + /* Continue looping. */ + break; + case ARCHIVE_OK: + /* Break loop. */ + looping = 0; + break; + default: + /* Forward any errors to the + * caller. */ + return lret; + } + } + + break; + } else { + /* Skip current base block. In order to properly skip + * it, we really need to simply parse it and discard + * the results. */ + + lret = skip_base_block(a); + if(lret == ARCHIVE_FATAL || lret == ARCHIVE_FAILED) + return lret; + + /* The `skip_base_block` function tells us if we + * should continue with skipping, or we should stop + * skipping. We're trying to skip everything up to + * a base FILE block. */ + + if(lret != ARCHIVE_RETRY) { + /* If there was an error during skipping, or we + * have just skipped a FILE base block... */ + + if(rar->main.endarc == 0) { + return lret; + } else { + continue; + } + } + } + } + + return ARCHIVE_OK; +} + +/* Merges the partial block from the first multivolume archive file, and + * partial block from the second multivolume archive file. The result is + * a chunk of memory containing the whole block, and the stream pointer + * is advanced to the next block in the second multivolume archive file. */ +static int merge_block(struct archive_read* a, ssize_t block_size, + const uint8_t** p) +{ + struct rar5* rar = get_context(a); + ssize_t cur_block_size, partial_offset = 0; + const uint8_t* lp; + int ret; + + if(rar->merge_mode) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Recursive merge is not allowed"); + + return ARCHIVE_FATAL; + } + + /* Set a flag that we're in the switching mode. */ + rar->cstate.switch_multivolume = 1; + + /* Reallocate the memory which will hold the whole block. */ + if(rar->vol.push_buf) + free((void*) rar->vol.push_buf); + + /* Increasing the allocation block by 8 is due to bit reading functions, + * which are using additional 2 or 4 bytes. Allocating the block size + * by exact value would make bit reader perform reads from invalid + * memory block when reading the last byte from the buffer. */ + rar->vol.push_buf = malloc(block_size + 8); + if(!rar->vol.push_buf) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for a merge block buffer."); + return ARCHIVE_FATAL; + } + + /* Valgrind complains if the extension block for bit reader is not + * initialized, so initialize it. */ + memset(&rar->vol.push_buf[block_size], 0, 8); + + /* A single block can span across multiple multivolume archive files, + * so we use a loop here. This loop will consume enough multivolume + * archive files until the whole block is read. */ + + while(1) { + /* Get the size of current block chunk in this multivolume + * archive file and read it. */ + cur_block_size = rar5_min(rar->file.bytes_remaining, + block_size - partial_offset); + + if(cur_block_size == 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Encountered block size == 0 during block merge"); + return ARCHIVE_FATAL; + } + + if(!read_ahead(a, cur_block_size, &lp)) + return ARCHIVE_EOF; + + /* Sanity check; there should never be a situation where this + * function reads more data than the block's size. */ + if(partial_offset + cur_block_size > block_size) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_PROGRAMMER, + "Consumed too much data when merging blocks."); + return ARCHIVE_FATAL; + } + + /* Merge previous block chunk with current block chunk, + * or create first block chunk if this is our first + * iteration. */ + memcpy(&rar->vol.push_buf[partial_offset], lp, cur_block_size); + + /* Advance the stream read pointer by this block chunk size. */ + if(ARCHIVE_OK != consume(a, cur_block_size)) + return ARCHIVE_EOF; + + /* Update the pointers. `partial_offset` contains information + * about the sum of merged block chunks. */ + partial_offset += cur_block_size; + rar->file.bytes_remaining -= cur_block_size; + + /* If `partial_offset` is the same as `block_size`, this means + * we've merged all block chunks and we have a valid full + * block. */ + if(partial_offset == block_size) { + break; + } + + /* If we don't have any bytes to read, this means we should + * switch to another multivolume archive file. */ + if(rar->file.bytes_remaining == 0) { + rar->merge_mode++; + ret = advance_multivolume(a); + rar->merge_mode--; + if(ret != ARCHIVE_OK) { + return ret; + } + } + } + + *p = rar->vol.push_buf; + + /* If we're here, we can resume unpacking by processing the block + * pointed to by the `*p` memory pointer. */ + + return ARCHIVE_OK; +} + +static int process_block(struct archive_read* a) { + const uint8_t* p; + struct rar5* rar = get_context(a); + int ret; + + /* If we don't have any data to be processed, this most probably means + * we need to switch to the next volume. */ + if(rar->main.volume && rar->file.bytes_remaining == 0) { + ret = advance_multivolume(a); + if(ret != ARCHIVE_OK) + return ret; + } + + if(rar->cstate.block_parsing_finished) { + ssize_t block_size; + ssize_t to_skip; + ssize_t cur_block_size; + + /* The header size won't be bigger than 6 bytes. */ + if(!read_ahead(a, 6, &p)) { + /* Failed to prefetch data block header. */ + return ARCHIVE_EOF; + } + + /* + * Read block_size by parsing block header. Validate the header + * by calculating CRC byte stored inside the header. Size of + * the header is not constant (block size can be stored either + * in 1 or 2 bytes), that's why block size is left out from the + * `compressed_block_header` structure and returned by + * `parse_block_header` as the second argument. */ + + ret = parse_block_header(a, p, &block_size, + &rar->last_block_hdr); + if(ret != ARCHIVE_OK) { + return ret; + } + + /* Skip block header. Next data is huffman tables, + * if present. */ + to_skip = sizeof(struct compressed_block_header) + + bf_byte_count(&rar->last_block_hdr) + 1; + + if(ARCHIVE_OK != consume(a, to_skip)) + return ARCHIVE_EOF; + + rar->file.bytes_remaining -= to_skip; + + /* The block size gives information about the whole block size, + * but the block could be stored in split form when using + * multi-volume archives. In this case, the block size will be + * bigger than the actual data stored in this file. Remaining + * part of the data will be in another file. */ + + cur_block_size = + rar5_min(rar->file.bytes_remaining, block_size); + + if(block_size > rar->file.bytes_remaining) { + /* If current blocks' size is bigger than our data + * size, this means we have a multivolume archive. + * In this case, skip all base headers until the end + * of the file, proceed to next "partXXX.rar" volume, + * find its signature, skip all headers up to the first + * FILE base header, and continue from there. + * + * Note that `merge_block` will update the `rar` + * context structure quite extensively. */ + + ret = merge_block(a, block_size, &p); + if(ret != ARCHIVE_OK) { + return ret; + } + + cur_block_size = block_size; + + /* Current stream pointer should be now directly + * *after* the block that spanned through multiple + * archive files. `p` pointer should have the data of + * the *whole* block (merged from partial blocks + * stored in multiple archives files). */ + } else { + rar->cstate.switch_multivolume = 0; + + /* Read the whole block size into memory. This can take + * up to 8 megabytes of memory in theoretical cases. + * Might be worth to optimize this and use a standard + * chunk of 4kb's. */ + if(!read_ahead(a, 4 + cur_block_size, &p)) { + /* Failed to prefetch block data. */ + return ARCHIVE_EOF; + } + } + + rar->cstate.block_buf = p; + rar->cstate.cur_block_size = cur_block_size; + rar->cstate.block_parsing_finished = 0; + + rar->bits.in_addr = 0; + rar->bits.bit_addr = 0; + + if(bf_is_table_present(&rar->last_block_hdr)) { + /* Load Huffman tables. */ + ret = parse_tables(a, rar, p); + if(ret != ARCHIVE_OK) { + /* Error during decompression of Huffman + * tables. */ + return ret; + } + } + } else { + /* Block parsing not finished, reuse previous memory buffer. */ + p = rar->cstate.block_buf; + } + + /* Uncompress the block, or a part of it, depending on how many bytes + * will be generated by uncompressing the block. + * + * In case too many bytes will be generated, calling this function + * again will resume the uncompression operation. */ + ret = do_uncompress_block(a, p); + if(ret != ARCHIVE_OK) { + return ret; + } + + if(rar->cstate.block_parsing_finished && + rar->cstate.switch_multivolume == 0 && + rar->cstate.cur_block_size > 0) + { + /* If we're processing a normal block, consume the whole + * block. We can do this because we've already read the whole + * block to memory. */ + if(ARCHIVE_OK != consume(a, rar->cstate.cur_block_size)) + return ARCHIVE_FATAL; + + rar->file.bytes_remaining -= rar->cstate.cur_block_size; + } else if(rar->cstate.switch_multivolume) { + /* Don't consume the block if we're doing multivolume + * processing. The volume switching function will consume + * the proper count of bytes instead. */ + rar->cstate.switch_multivolume = 0; + } + + return ARCHIVE_OK; +} + +/* Pops the `buf`, `size` and `offset` from the "data ready" stack. + * + * Returns ARCHIVE_OK when those arguments can be used, ARCHIVE_RETRY + * when there is no data on the stack. */ +static int use_data(struct rar5* rar, const void** buf, size_t* size, + int64_t* offset) +{ + int i; + + for(i = 0; i < rar5_countof(rar->cstate.dready); i++) { + struct data_ready *d = &rar->cstate.dready[i]; + + if(d->used) { + if(buf) *buf = d->buf; + if(size) *size = d->size; + if(offset) *offset = d->offset; + + d->used = 0; + return ARCHIVE_OK; + } + } + + return ARCHIVE_RETRY; +} + +/* Pushes the `buf`, `size` and `offset` arguments to the rar->cstate.dready + * FIFO stack. Those values will be popped from this stack by the `use_data` + * function. */ +static int push_data_ready(struct archive_read* a, struct rar5* rar, + const uint8_t* buf, size_t size, int64_t offset) +{ + int i; + + /* Don't push if we're in skip mode. This is needed because solid + * streams need full processing even if we're skipping data. After + * fully processing the stream, we need to discard the generated bytes, + * because we're interested only in the side effect: building up the + * internal window circular buffer. This window buffer will be used + * later during unpacking of requested data. */ + if(rar->skip_mode) + return ARCHIVE_OK; + + /* Sanity check. */ + if(offset != rar->file.last_offset + rar->file.last_size) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Sanity check error: output stream is not continuous"); + return ARCHIVE_FATAL; + } + + for(i = 0; i < rar5_countof(rar->cstate.dready); i++) { + struct data_ready* d = &rar->cstate.dready[i]; + if(!d->used) { + d->used = 1; + d->buf = buf; + d->size = size; + d->offset = offset; + + /* These fields are used only in sanity checking. */ + rar->file.last_offset = offset; + rar->file.last_size = size; + + /* Calculate the checksum of this new block before + * submitting data to libarchive's engine. */ + update_crc(rar, d->buf, d->size); + + return ARCHIVE_OK; + } + } + + /* Program counter will reach this code if the `rar->cstate.data_ready` + * stack will be filled up so that no new entries will be allowed. The + * code shouldn't allow such situation to occur. So we treat this case + * as an internal error. */ + + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Error: premature end of data_ready stack"); + return ARCHIVE_FATAL; +} + +/* This function uncompresses the data that is stored in the <FILE> base + * block. + * + * The FILE base block looks like this: + * + * <header><huffman tables><block_1><block_2>...<block_n> + * + * The <header> is a block header, that is parsed in parse_block_header(). + * It's a "compressed_block_header" structure, containing metadata needed + * to know when we should stop looking for more <block_n> blocks. + * + * <huffman tables> contain data needed to set up the huffman tables, needed + * for the actual decompression. + * + * Each <block_n> consists of series of literals: + * + * <literal><literal><literal>...<literal> + * + * Those literals generate the uncompression data. They operate on a circular + * buffer, sometimes writing raw data into it, sometimes referencing + * some previous data inside this buffer, and sometimes declaring a filter + * that will need to be executed on the data stored in the circular buffer. + * It all depends on the literal that is used. + * + * Sometimes blocks produce output data, sometimes they don't. For example, for + * some huge files that use lots of filters, sometimes a block is filled with + * only filter declaration literals. Such blocks won't produce any data in the + * circular buffer. + * + * Sometimes blocks will produce 4 bytes of data, and sometimes 1 megabyte, + * because a literal can reference previously decompressed data. For example, + * there can be a literal that says: 'append a byte 0xFE here', and after + * it another literal can say 'append 1 megabyte of data from circular buffer + * offset 0x12345'. This is how RAR format handles compressing repeated + * patterns. + * + * The RAR compressor creates those literals and the actual efficiency of + * compression depends on what those literals are. The literals can also + * be seen as a kind of a non-turing-complete virtual machine that simply + * tells the decompressor what it should do. + * */ + +static int do_uncompress_file(struct archive_read* a) { + struct rar5* rar = get_context(a); + int ret; + int64_t max_end_pos; + + if(!rar->cstate.initialized) { + /* Don't perform full context reinitialization if we're + * processing a solid archive. */ + if(!rar->main.solid || !rar->cstate.window_buf) { + init_unpack(rar); + } + + rar->cstate.initialized = 1; + } + + if(rar->cstate.all_filters_applied == 1) { + /* We use while(1) here, but standard case allows for just 1 + * iteration. The loop will iterate if process_block() didn't + * generate any data at all. This can happen if the block + * contains only filter definitions (this is common in big + * files). */ + while(1) { + ret = process_block(a); + if(ret == ARCHIVE_EOF || ret == ARCHIVE_FATAL) + return ret; + + if(rar->cstate.last_write_ptr == + rar->cstate.write_ptr) { + /* The block didn't generate any new data, + * so just process a new block. */ + continue; + } + + /* The block has generated some new data, so break + * the loop. */ + break; + } + } + + /* Try to run filters. If filters won't be applied, it means that + * insufficient data was generated. */ + ret = apply_filters(a); + if(ret == ARCHIVE_RETRY) { + return ARCHIVE_OK; + } else if(ret == ARCHIVE_FATAL) { + return ARCHIVE_FATAL; + } + + /* If apply_filters() will return ARCHIVE_OK, we can continue here. */ + + if(cdeque_size(&rar->cstate.filters) > 0) { + /* Check if we can write something before hitting first + * filter. */ + struct filter_info* flt; + + /* Get the block_start offset from the first filter. */ + if(CDE_OK != cdeque_front(&rar->cstate.filters, + cdeque_filter_p(&flt))) + { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_PROGRAMMER, + "Can't read first filter"); + return ARCHIVE_FATAL; + } + + max_end_pos = rar5_min(flt->block_start, + rar->cstate.write_ptr); + } else { + /* There are no filters defined, or all filters were applied. + * This means we can just store the data without any + * postprocessing. */ + max_end_pos = rar->cstate.write_ptr; + } + + if(max_end_pos == rar->cstate.last_write_ptr) { + /* We can't write anything yet. The block uncompression + * function did not generate enough data, and no filter can be + * applied. At the same time we don't have any data that can be + * stored without filter postprocessing. This means we need to + * wait for more data to be generated, so we can apply the + * filters. + * + * Signal the caller that we need more data to be able to do + * anything. + */ + return ARCHIVE_RETRY; + } else { + /* We can write the data before hitting the first filter. + * So let's do it. The push_window_data() function will + * effectively return the selected data block to the user + * application. */ + push_window_data(a, rar, rar->cstate.last_write_ptr, + max_end_pos); + rar->cstate.last_write_ptr = max_end_pos; + } + + return ARCHIVE_OK; +} + +static int uncompress_file(struct archive_read* a) { + int ret; + + while(1) { + /* Sometimes the uncompression function will return a + * 'retry' signal. If this will happen, we have to retry + * the function. */ + ret = do_uncompress_file(a); + if(ret != ARCHIVE_RETRY) + return ret; + } +} + + +static int do_unstore_file(struct archive_read* a, + struct rar5* rar, const void** buf, size_t* size, int64_t* offset) +{ + size_t to_read; + const uint8_t* p; + + if(rar->file.bytes_remaining == 0 && rar->main.volume > 0 && + rar->generic.split_after > 0) + { + int ret; + + rar->cstate.switch_multivolume = 1; + ret = advance_multivolume(a); + rar->cstate.switch_multivolume = 0; + + if(ret != ARCHIVE_OK) { + /* Failed to advance to next multivolume archive + * file. */ + return ret; + } + } + + to_read = rar5_min(rar->file.bytes_remaining, 64 * 1024); + if(to_read == 0) { + return ARCHIVE_EOF; + } + + if(!read_ahead(a, to_read, &p)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "I/O error when unstoring file"); + return ARCHIVE_FATAL; + } + + if(ARCHIVE_OK != consume(a, to_read)) { + return ARCHIVE_EOF; + } + + if(buf) *buf = p; + if(size) *size = to_read; + if(offset) *offset = rar->cstate.last_unstore_ptr; + + rar->file.bytes_remaining -= to_read; + rar->cstate.last_unstore_ptr += to_read; + + update_crc(rar, p, to_read); + return ARCHIVE_OK; +} + +static int do_unpack(struct archive_read* a, struct rar5* rar, + const void** buf, size_t* size, int64_t* offset) +{ + enum COMPRESSION_METHOD { + STORE = 0, FASTEST = 1, FAST = 2, NORMAL = 3, GOOD = 4, + BEST = 5 + }; + + if(rar->file.service > 0) { + return do_unstore_file(a, rar, buf, size, offset); + } else { + switch(rar->cstate.method) { + case STORE: + return do_unstore_file(a, rar, buf, size, + offset); + case FASTEST: + /* fallthrough */ + case FAST: + /* fallthrough */ + case NORMAL: + /* fallthrough */ + case GOOD: + /* fallthrough */ + case BEST: + return uncompress_file(a); + default: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Compression method not supported: 0x%x", + rar->cstate.method); + + return ARCHIVE_FATAL; + } + } + +#if !defined WIN32 + /* Not reached. */ + return ARCHIVE_OK; +#endif +} + +static int verify_checksums(struct archive_read* a) { + int verify_crc; + struct rar5* rar = get_context(a); + + /* Check checksums only when actually unpacking the data. There's no + * need to calculate checksum when we're skipping data in solid archives + * (skipping in solid archives is the same thing as unpacking compressed + * data and discarding the result). */ + + if(!rar->skip_mode) { + /* Always check checksums if we're not in skip mode */ + verify_crc = 1; + } else { + /* We can override the logic above with a compile-time option + * NO_CRC_ON_SOLID_SKIP. This option is used during debugging, + * and it will check checksums of unpacked data even when + * we're skipping it. */ + +#if defined CHECK_CRC_ON_SOLID_SKIP + /* Debug case */ + verify_crc = 1; +#else + /* Normal case */ + verify_crc = 0; +#endif + } + + if(verify_crc) { + /* During unpacking, on each unpacked block we're calling the + * update_crc() function. Since we are here, the unpacking + * process is already over and we can check if calculated + * checksum (CRC32 or BLAKE2sp) is the same as what is stored + * in the archive. */ + if(rar->file.stored_crc32 > 0) { + /* Check CRC32 only when the file contains a CRC32 + * value for this file. */ + + if(rar->file.calculated_crc32 != + rar->file.stored_crc32) { + /* Checksums do not match; the unpacked file + * is corrupted. */ + + DEBUG_CODE { + printf("Checksum error: CRC32 " + "(was: %08x, expected: %08x)\n", + rar->file.calculated_crc32, + rar->file.stored_crc32); + } + +#ifndef DONT_FAIL_ON_CRC_ERROR + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Checksum error: CRC32"); + return ARCHIVE_FATAL; +#endif + } else { + DEBUG_CODE { + printf("Checksum OK: CRC32 " + "(%08x/%08x)\n", + rar->file.stored_crc32, + rar->file.calculated_crc32); + } + } + } + + if(rar->file.has_blake2 > 0) { + /* BLAKE2sp is an optional checksum algorithm that is + * added to RARv5 archives when using the `-htb` switch + * during creation of archive. + * + * We now finalize the hash calculation by calling the + * `final` function. This will generate the final hash + * value we can use to compare it with the BLAKE2sp + * checksum that is stored in the archive. + * + * The return value of this `final` function is not + * very helpful, as it guards only against improper use. + * This is why we're explicitly ignoring it. */ + + uint8_t b2_buf[32]; + (void) blake2sp_final(&rar->file.b2state, b2_buf, 32); + + if(memcmp(&rar->file.blake2sp, b2_buf, 32) != 0) { +#ifndef DONT_FAIL_ON_CRC_ERROR + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Checksum error: BLAKE2"); + + return ARCHIVE_FATAL; +#endif + } + } + } + + /* Finalization for this file has been successfully completed. */ + return ARCHIVE_OK; +} + +static int verify_global_checksums(struct archive_read* a) { + return verify_checksums(a); +} + +/* + * Decryption function for the magic signature pattern. Check the comment near + * the `rar5_signature_xor` symbol to read the rationale behind this. + */ +static void rar5_signature(char *buf) { + size_t i; + + for(i = 0; i < sizeof(rar5_signature_xor); i++) { + buf[i] = rar5_signature_xor[i] ^ 0xA1; + } +} + +static int rar5_read_data(struct archive_read *a, const void **buff, + size_t *size, int64_t *offset) { + int ret; + struct rar5* rar = get_context(a); + + if(rar->file.dir > 0) { + /* Don't process any data if this file entry was declared + * as a directory. This is needed, because entries marked as + * directory doesn't have any dictionary buffer allocated, so + * it's impossible to perform any decompression. */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Can't decompress an entry marked as a directory"); + return ARCHIVE_FAILED; + } + + if(!rar->skip_mode && (rar->cstate.last_write_ptr > rar->file.unpacked_size)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Unpacker has written too many bytes"); + return ARCHIVE_FATAL; + } + + ret = use_data(rar, buff, size, offset); + if(ret == ARCHIVE_OK) { + return ret; + } + + if(rar->file.eof == 1) { + return ARCHIVE_EOF; + } + + ret = do_unpack(a, rar, buff, size, offset); + if(ret != ARCHIVE_OK) { + return ret; + } + + if(rar->file.bytes_remaining == 0 && + rar->cstate.last_write_ptr == rar->file.unpacked_size) + { + /* If all bytes of current file were processed, run + * finalization. + * + * Finalization will check checksum against proper values. If + * some of the checksums will not match, we'll return an error + * value in the last `archive_read_data` call to signal an error + * to the user. */ + + rar->file.eof = 1; + return verify_global_checksums(a); + } + + return ARCHIVE_OK; +} + +static int rar5_read_data_skip(struct archive_read *a) { + struct rar5* rar = get_context(a); + + if(rar->main.solid) { + /* In solid archives, instead of skipping the data, we need to + * extract it, and dispose the result. The side effect of this + * operation will be setting up the initial window buffer state + * needed to be able to extract the selected file. */ + + int ret; + + /* Make sure to process all blocks in the compressed stream. */ + while(rar->file.bytes_remaining > 0) { + /* Setting the "skip mode" will allow us to skip + * checksum checks during data skipping. Checking the + * checksum of skipped data isn't really necessary and + * it's only slowing things down. + * + * This is incremented instead of setting to 1 because + * this data skipping function can be called + * recursively. */ + rar->skip_mode++; + + /* We're disposing 1 block of data, so we use triple + * NULLs in arguments. */ + ret = rar5_read_data(a, NULL, NULL, NULL); + + /* Turn off "skip mode". */ + rar->skip_mode--; + + if(ret < 0 || ret == ARCHIVE_EOF) { + /* Propagate any potential error conditions + * to the caller. */ + return ret; + } + } + } else { + /* In standard archives, we can just jump over the compressed + * stream. Each file in non-solid archives starts from an empty + * window buffer. */ + + if(ARCHIVE_OK != consume(a, rar->file.bytes_remaining)) { + return ARCHIVE_FATAL; + } + + rar->file.bytes_remaining = 0; + } + + return ARCHIVE_OK; +} + +static int64_t rar5_seek_data(struct archive_read *a, int64_t offset, + int whence) +{ + (void) a; + (void) offset; + (void) whence; + + /* We're a streaming unpacker, and we don't support seeking. */ + + return ARCHIVE_FATAL; +} + +static int rar5_cleanup(struct archive_read *a) { + struct rar5* rar = get_context(a); + + free(rar->cstate.window_buf); + free(rar->cstate.filtered_buf); + + free(rar->vol.push_buf); + + free_filters(rar); + cdeque_free(&rar->cstate.filters); + + free(rar); + a->format->data = NULL; + + return ARCHIVE_OK; +} + +static int rar5_capabilities(struct archive_read * a) { + (void) a; + return 0; +} + +static int rar5_has_encrypted_entries(struct archive_read *_a) { + (void) _a; + + /* Unsupported for now. */ + return ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED; +} + +static int rar5_init(struct rar5* rar) { + memset(rar, 0, sizeof(struct rar5)); + + if(CDE_OK != cdeque_init(&rar->cstate.filters, 8192)) + return ARCHIVE_FATAL; + + return ARCHIVE_OK; +} + +int archive_read_support_format_rar5(struct archive *_a) { + struct archive_read* ar; + int ret; + struct rar5* rar; + + if(ARCHIVE_OK != (ret = get_archive_read(_a, &ar))) + return ret; + + rar = malloc(sizeof(*rar)); + if(rar == NULL) { + archive_set_error(&ar->archive, ENOMEM, + "Can't allocate rar5 data"); + return ARCHIVE_FATAL; + } + + if(ARCHIVE_OK != rar5_init(rar)) { + archive_set_error(&ar->archive, ENOMEM, + "Can't allocate rar5 filter buffer"); + return ARCHIVE_FATAL; + } + + ret = __archive_read_register_format(ar, + rar, + "rar5", + rar5_bid, + rar5_options, + rar5_read_header, + rar5_read_data, + rar5_read_data_skip, + rar5_seek_data, + rar5_cleanup, + rar5_capabilities, + rar5_has_encrypted_entries); + + if(ret != ARCHIVE_OK) { + (void) rar5_cleanup(ar); + } + + return ret; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_raw.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_raw.c new file mode 100644 index 0000000000..ec0520b60a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_raw.c @@ -0,0 +1,192 @@ +/*- + * Copyright (c) 2003-2009 Tim Kientzle + * 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(S) ``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(S) 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. + */ +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_raw.c 201107 2009-12-28 03:25:33Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_read_private.h" + +struct raw_info { + int64_t offset; /* Current position in the file. */ + int64_t unconsumed; + int end_of_file; +}; + +static int archive_read_format_raw_bid(struct archive_read *, int); +static int archive_read_format_raw_cleanup(struct archive_read *); +static int archive_read_format_raw_read_data(struct archive_read *, + const void **, size_t *, int64_t *); +static int archive_read_format_raw_read_data_skip(struct archive_read *); +static int archive_read_format_raw_read_header(struct archive_read *, + struct archive_entry *); + +int +archive_read_support_format_raw(struct archive *_a) +{ + struct raw_info *info; + struct archive_read *a = (struct archive_read *)_a; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_raw"); + + info = (struct raw_info *)calloc(1, sizeof(*info)); + if (info == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate raw_info data"); + return (ARCHIVE_FATAL); + } + + r = __archive_read_register_format(a, + info, + "raw", + archive_read_format_raw_bid, + NULL, + archive_read_format_raw_read_header, + archive_read_format_raw_read_data, + archive_read_format_raw_read_data_skip, + NULL, + archive_read_format_raw_cleanup, + NULL, + NULL); + if (r != ARCHIVE_OK) + free(info); + return (r); +} + +/* + * Bid 1 if this is a non-empty file. Anyone who can really support + * this should outbid us, so it should generally be safe to use "raw" + * in conjunction with other formats. But, this could really confuse + * folks if there are bid errors or minor file damage, so we don't + * include "raw" as part of support_format_all(). + */ +static int +archive_read_format_raw_bid(struct archive_read *a, int best_bid) +{ + if (best_bid < 1 && __archive_read_ahead(a, 1, NULL) != NULL) + return (1); + return (-1); +} + +/* + * Mock up a fake header. + */ +static int +archive_read_format_raw_read_header(struct archive_read *a, + struct archive_entry *entry) +{ + struct raw_info *info; + + info = (struct raw_info *)(a->format->data); + if (info->end_of_file) + return (ARCHIVE_EOF); + + a->archive.archive_format = ARCHIVE_FORMAT_RAW; + a->archive.archive_format_name = "raw"; + archive_entry_set_pathname(entry, "data"); + archive_entry_set_filetype(entry, AE_IFREG); + archive_entry_set_perm(entry, 0644); + /* I'm deliberately leaving most fields unset here. */ + + /* Let the filter fill out any fields it might have. */ + return __archive_read_header(a, entry); +} + +static int +archive_read_format_raw_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + struct raw_info *info; + ssize_t avail; + + info = (struct raw_info *)(a->format->data); + + /* Consume the bytes we read last time. */ + if (info->unconsumed) { + __archive_read_consume(a, info->unconsumed); + info->unconsumed = 0; + } + + if (info->end_of_file) + return (ARCHIVE_EOF); + + /* Get whatever bytes are immediately available. */ + *buff = __archive_read_ahead(a, 1, &avail); + if (avail > 0) { + /* Return the bytes we just read */ + *size = avail; + *offset = info->offset; + info->offset += *size; + info->unconsumed = avail; + return (ARCHIVE_OK); + } else if (0 == avail) { + /* Record and return end-of-file. */ + info->end_of_file = 1; + *size = 0; + *offset = info->offset; + return (ARCHIVE_EOF); + } else { + /* Record and return an error. */ + *size = 0; + *offset = info->offset; + return ((int)avail); + } +} + +static int +archive_read_format_raw_read_data_skip(struct archive_read *a) +{ + struct raw_info *info = (struct raw_info *)(a->format->data); + + /* Consume the bytes we read last time. */ + if (info->unconsumed) { + __archive_read_consume(a, info->unconsumed); + info->unconsumed = 0; + } + info->end_of_file = 1; + return (ARCHIVE_OK); +} + +static int +archive_read_format_raw_cleanup(struct archive_read *a) +{ + struct raw_info *info; + + info = (struct raw_info *)(a->format->data); + free(info); + a->format->data = NULL; + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_tar.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_tar.c new file mode 100644 index 0000000000..96d8101844 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_tar.c @@ -0,0 +1,2922 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2011-2012 Michihiro NAKAJIMA + * Copyright (c) 2016 Martin Matuska + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_tar.c 201161 2009-12-29 05:44:39Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stddef.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_acl_private.h" /* For ACL parsing routines. */ +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_read_private.h" + +#define tar_min(a,b) ((a) < (b) ? (a) : (b)) + +/* + * Layout of POSIX 'ustar' tar header. + */ +struct archive_entry_header_ustar { + char name[100]; + char mode[8]; + char uid[8]; + char gid[8]; + char size[12]; + char mtime[12]; + char checksum[8]; + char typeflag[1]; + char linkname[100]; /* "old format" header ends here */ + char magic[6]; /* For POSIX: "ustar\0" */ + char version[2]; /* For POSIX: "00" */ + char uname[32]; + char gname[32]; + char rdevmajor[8]; + char rdevminor[8]; + char prefix[155]; +}; + +/* + * Structure of GNU tar header + */ +struct gnu_sparse { + char offset[12]; + char numbytes[12]; +}; + +struct archive_entry_header_gnutar { + char name[100]; + char mode[8]; + char uid[8]; + char gid[8]; + char size[12]; + char mtime[12]; + char checksum[8]; + char typeflag[1]; + char linkname[100]; + char magic[8]; /* "ustar \0" (note blank/blank/null at end) */ + char uname[32]; + char gname[32]; + char rdevmajor[8]; + char rdevminor[8]; + char atime[12]; + char ctime[12]; + char offset[12]; + char longnames[4]; + char unused[1]; + struct gnu_sparse sparse[4]; + char isextended[1]; + char realsize[12]; + /* + * Old GNU format doesn't use POSIX 'prefix' field; they use + * the 'L' (longname) entry instead. + */ +}; + +/* + * Data specific to this format. + */ +struct sparse_block { + struct sparse_block *next; + int64_t offset; + int64_t remaining; + int hole; +}; + +struct tar { + struct archive_string acl_text; + struct archive_string entry_pathname; + /* For "GNU.sparse.name" and other similar path extensions. */ + struct archive_string entry_pathname_override; + struct archive_string entry_linkpath; + struct archive_string entry_uname; + struct archive_string entry_gname; + struct archive_string longlink; + struct archive_string longname; + struct archive_string pax_header; + struct archive_string pax_global; + struct archive_string line; + int pax_hdrcharset_binary; + int header_recursion_depth; + int64_t entry_bytes_remaining; + int64_t entry_offset; + int64_t entry_padding; + int64_t entry_bytes_unconsumed; + int64_t realsize; + int sparse_allowed; + struct sparse_block *sparse_list; + struct sparse_block *sparse_last; + int64_t sparse_offset; + int64_t sparse_numbytes; + int sparse_gnu_major; + int sparse_gnu_minor; + char sparse_gnu_pending; + + struct archive_string localname; + struct archive_string_conv *opt_sconv; + struct archive_string_conv *sconv; + struct archive_string_conv *sconv_acl; + struct archive_string_conv *sconv_default; + int init_default_conversion; + int compat_2x; + int process_mac_extensions; + int read_concatenated_archives; + int realsize_override; +}; + +static int archive_block_is_null(const char *p); +static char *base64_decode(const char *, size_t, size_t *); +static int gnu_add_sparse_entry(struct archive_read *, struct tar *, + int64_t offset, int64_t remaining); + +static void gnu_clear_sparse_list(struct tar *); +static int gnu_sparse_old_read(struct archive_read *, struct tar *, + const struct archive_entry_header_gnutar *header, size_t *); +static int gnu_sparse_old_parse(struct archive_read *, struct tar *, + const struct gnu_sparse *sparse, int length); +static int gnu_sparse_01_parse(struct archive_read *, struct tar *, + const char *); +static ssize_t gnu_sparse_10_read(struct archive_read *, struct tar *, + size_t *); +static int header_Solaris_ACL(struct archive_read *, struct tar *, + struct archive_entry *, const void *, size_t *); +static int header_common(struct archive_read *, struct tar *, + struct archive_entry *, const void *); +static int header_old_tar(struct archive_read *, struct tar *, + struct archive_entry *, const void *); +static int header_pax_extensions(struct archive_read *, struct tar *, + struct archive_entry *, const void *, size_t *); +static int header_pax_global(struct archive_read *, struct tar *, + struct archive_entry *, const void *h, size_t *); +static int header_longlink(struct archive_read *, struct tar *, + struct archive_entry *, const void *h, size_t *); +static int header_longname(struct archive_read *, struct tar *, + struct archive_entry *, const void *h, size_t *); +static int read_mac_metadata_blob(struct archive_read *, struct tar *, + struct archive_entry *, const void *h, size_t *); +static int header_volume(struct archive_read *, struct tar *, + struct archive_entry *, const void *h, size_t *); +static int header_ustar(struct archive_read *, struct tar *, + struct archive_entry *, const void *h); +static int header_gnutar(struct archive_read *, struct tar *, + struct archive_entry *, const void *h, size_t *); +static int archive_read_format_tar_bid(struct archive_read *, int); +static int archive_read_format_tar_options(struct archive_read *, + const char *, const char *); +static int archive_read_format_tar_cleanup(struct archive_read *); +static int archive_read_format_tar_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset); +static int archive_read_format_tar_skip(struct archive_read *a); +static int archive_read_format_tar_read_header(struct archive_read *, + struct archive_entry *); +static int checksum(struct archive_read *, const void *); +static int pax_attribute(struct archive_read *, struct tar *, + struct archive_entry *, const char *key, const char *value, + size_t value_length); +static int pax_attribute_acl(struct archive_read *, struct tar *, + struct archive_entry *, const char *, int); +static int pax_attribute_xattr(struct archive_entry *, const char *, + const char *); +static int pax_header(struct archive_read *, struct tar *, + struct archive_entry *, struct archive_string *); +static void pax_time(const char *, int64_t *sec, long *nanos); +static ssize_t readline(struct archive_read *, struct tar *, const char **, + ssize_t limit, size_t *); +static int read_body_to_string(struct archive_read *, struct tar *, + struct archive_string *, const void *h, size_t *); +static int solaris_sparse_parse(struct archive_read *, struct tar *, + struct archive_entry *, const char *); +static int64_t tar_atol(const char *, size_t); +static int64_t tar_atol10(const char *, size_t); +static int64_t tar_atol256(const char *, size_t); +static int64_t tar_atol8(const char *, size_t); +static int tar_read_header(struct archive_read *, struct tar *, + struct archive_entry *, size_t *); +static int tohex(int c); +static char *url_decode(const char *); +static void tar_flush_unconsumed(struct archive_read *, size_t *); + + +int +archive_read_support_format_gnutar(struct archive *a) +{ + archive_check_magic(a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_gnutar"); + return (archive_read_support_format_tar(a)); +} + + +int +archive_read_support_format_tar(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct tar *tar; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_tar"); + + tar = (struct tar *)calloc(1, sizeof(*tar)); + if (tar == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate tar data"); + return (ARCHIVE_FATAL); + } +#ifdef HAVE_COPYFILE_H + /* Set this by default on Mac OS. */ + tar->process_mac_extensions = 1; +#endif + + r = __archive_read_register_format(a, tar, "tar", + archive_read_format_tar_bid, + archive_read_format_tar_options, + archive_read_format_tar_read_header, + archive_read_format_tar_read_data, + archive_read_format_tar_skip, + NULL, + archive_read_format_tar_cleanup, + NULL, + NULL); + + if (r != ARCHIVE_OK) + free(tar); + return (ARCHIVE_OK); +} + +static int +archive_read_format_tar_cleanup(struct archive_read *a) +{ + struct tar *tar; + + tar = (struct tar *)(a->format->data); + gnu_clear_sparse_list(tar); + archive_string_free(&tar->acl_text); + archive_string_free(&tar->entry_pathname); + archive_string_free(&tar->entry_pathname_override); + archive_string_free(&tar->entry_linkpath); + archive_string_free(&tar->entry_uname); + archive_string_free(&tar->entry_gname); + archive_string_free(&tar->line); + archive_string_free(&tar->pax_global); + archive_string_free(&tar->pax_header); + archive_string_free(&tar->longname); + archive_string_free(&tar->longlink); + archive_string_free(&tar->localname); + free(tar); + (a->format->data) = NULL; + return (ARCHIVE_OK); +} + +/* + * Validate number field + * + * This has to be pretty lenient in order to accommodate the enormous + * variety of tar writers in the world: + * = POSIX (IEEE Std 1003.1-1988) ustar requires octal values with leading + * zeros and allows fields to be terminated with space or null characters + * = Many writers use different termination (in particular, libarchive + * omits terminator bytes to squeeze one or two more digits) + * = Many writers pad with space and omit leading zeros + * = GNU tar and star write base-256 values if numbers are too + * big to be represented in octal + * + * Examples of specific tar headers that we should support: + * = Perl Archive::Tar terminates uid, gid, devminor and devmajor with two + * null bytes, pads size with spaces and other numeric fields with zeroes + * = plexus-archiver prior to 2.6.3 (before switching to commons-compress) + * may have uid and gid fields filled with spaces without any octal digits + * at all and pads all numeric fields with spaces + * + * This should tolerate all variants in use. It will reject a field + * where the writer just left garbage after a trailing NUL. + */ +static int +validate_number_field(const char* p_field, size_t i_size) +{ + unsigned char marker = (unsigned char)p_field[0]; + if (marker == 128 || marker == 255 || marker == 0) { + /* Base-256 marker, there's nothing we can check. */ + return 1; + } else { + /* Must be octal */ + size_t i = 0; + /* Skip any leading spaces */ + while (i < i_size && p_field[i] == ' ') { + ++i; + } + /* Skip octal digits. */ + while (i < i_size && p_field[i] >= '0' && p_field[i] <= '7') { + ++i; + } + /* Any remaining characters must be space or NUL padding. */ + while (i < i_size) { + if (p_field[i] != ' ' && p_field[i] != 0) { + return 0; + } + ++i; + } + return 1; + } +} + +static int +archive_read_format_tar_bid(struct archive_read *a, int best_bid) +{ + int bid; + const char *h; + const struct archive_entry_header_ustar *header; + + (void)best_bid; /* UNUSED */ + + bid = 0; + + /* Now let's look at the actual header and see if it matches. */ + h = __archive_read_ahead(a, 512, NULL); + if (h == NULL) + return (-1); + + /* If it's an end-of-archive mark, we can handle it. */ + if (h[0] == 0 && archive_block_is_null(h)) { + /* + * Usually, I bid the number of bits verified, but + * in this case, 4096 seems excessive so I picked 10 as + * an arbitrary but reasonable-seeming value. + */ + return (10); + } + + /* If it's not an end-of-archive mark, it must have a valid checksum.*/ + if (!checksum(a, h)) + return (0); + bid += 48; /* Checksum is usually 6 octal digits. */ + + header = (const struct archive_entry_header_ustar *)h; + + /* Recognize POSIX formats. */ + if ((memcmp(header->magic, "ustar\0", 6) == 0) + && (memcmp(header->version, "00", 2) == 0)) + bid += 56; + + /* Recognize GNU tar format. */ + if ((memcmp(header->magic, "ustar ", 6) == 0) + && (memcmp(header->version, " \0", 2) == 0)) + bid += 56; + + /* Type flag must be null, digit or A-Z, a-z. */ + if (header->typeflag[0] != 0 && + !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') && + !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') && + !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') ) + return (0); + bid += 2; /* 6 bits of variation in an 8-bit field leaves 2 bits. */ + + /* + * Check format of mode/uid/gid/mtime/size/rdevmajor/rdevminor fields. + */ + if (bid > 0 && ( + validate_number_field(header->mode, sizeof(header->mode)) == 0 + || validate_number_field(header->uid, sizeof(header->uid)) == 0 + || validate_number_field(header->gid, sizeof(header->gid)) == 0 + || validate_number_field(header->mtime, sizeof(header->mtime)) == 0 + || validate_number_field(header->size, sizeof(header->size)) == 0 + || validate_number_field(header->rdevmajor, sizeof(header->rdevmajor)) == 0 + || validate_number_field(header->rdevminor, sizeof(header->rdevminor)) == 0)) { + bid = 0; + } + + return (bid); +} + +static int +archive_read_format_tar_options(struct archive_read *a, + const char *key, const char *val) +{ + struct tar *tar; + int ret = ARCHIVE_FAILED; + + tar = (struct tar *)(a->format->data); + if (strcmp(key, "compat-2x") == 0) { + /* Handle UTF-8 filenames as libarchive 2.x */ + tar->compat_2x = (val != NULL && val[0] != 0); + tar->init_default_conversion = tar->compat_2x; + return (ARCHIVE_OK); + } else if (strcmp(key, "hdrcharset") == 0) { + if (val == NULL || val[0] == 0) + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "tar: hdrcharset option needs a character-set name"); + else { + tar->opt_sconv = + archive_string_conversion_from_charset( + &a->archive, val, 0); + if (tar->opt_sconv != NULL) + ret = ARCHIVE_OK; + else + ret = ARCHIVE_FATAL; + } + return (ret); + } else if (strcmp(key, "mac-ext") == 0) { + tar->process_mac_extensions = (val != NULL && val[0] != 0); + return (ARCHIVE_OK); + } else if (strcmp(key, "read_concatenated_archives") == 0) { + tar->read_concatenated_archives = (val != NULL && val[0] != 0); + return (ARCHIVE_OK); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +/* utility function- this exists to centralize the logic of tracking + * how much unconsumed data we have floating around, and to consume + * anything outstanding since we're going to do read_aheads + */ +static void +tar_flush_unconsumed(struct archive_read *a, size_t *unconsumed) +{ + if (*unconsumed) { +/* + void *data = (void *)__archive_read_ahead(a, *unconsumed, NULL); + * this block of code is to poison claimed unconsumed space, ensuring + * things break if it is in use still. + * currently it WILL break things, so enable it only for debugging this issue + if (data) { + memset(data, 0xff, *unconsumed); + } +*/ + __archive_read_consume(a, *unconsumed); + *unconsumed = 0; + } +} + +/* + * The function invoked by archive_read_next_header(). This + * just sets up a few things and then calls the internal + * tar_read_header() function below. + */ +static int +archive_read_format_tar_read_header(struct archive_read *a, + struct archive_entry *entry) +{ + /* + * When converting tar archives to cpio archives, it is + * essential that each distinct file have a distinct inode + * number. To simplify this, we keep a static count here to + * assign fake dev/inode numbers to each tar entry. Note that + * pax format archives may overwrite this with something more + * useful. + * + * Ideally, we would track every file read from the archive so + * that we could assign the same dev/ino pair to hardlinks, + * but the memory required to store a complete lookup table is + * probably not worthwhile just to support the relatively + * obscure tar->cpio conversion case. + */ + static int default_inode; + static int default_dev; + struct tar *tar; + const char *p; + const wchar_t *wp; + int r; + size_t l, unconsumed = 0; + + /* Assign default device/inode values. */ + archive_entry_set_dev(entry, 1 + default_dev); /* Don't use zero. */ + archive_entry_set_ino(entry, ++default_inode); /* Don't use zero. */ + /* Limit generated st_ino number to 16 bits. */ + if (default_inode >= 0xffff) { + ++default_dev; + default_inode = 0; + } + + tar = (struct tar *)(a->format->data); + tar->entry_offset = 0; + gnu_clear_sparse_list(tar); + tar->realsize = -1; /* Mark this as "unset" */ + tar->realsize_override = 0; + + /* Setup default string conversion. */ + tar->sconv = tar->opt_sconv; + if (tar->sconv == NULL) { + if (!tar->init_default_conversion) { + tar->sconv_default = + archive_string_default_conversion_for_read(&(a->archive)); + tar->init_default_conversion = 1; + } + tar->sconv = tar->sconv_default; + } + + r = tar_read_header(a, tar, entry, &unconsumed); + + tar_flush_unconsumed(a, &unconsumed); + + /* + * "non-sparse" files are really just sparse files with + * a single block. + */ + if (tar->sparse_list == NULL) { + if (gnu_add_sparse_entry(a, tar, 0, tar->entry_bytes_remaining) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } else { + struct sparse_block *sb; + + for (sb = tar->sparse_list; sb != NULL; sb = sb->next) { + if (!sb->hole) + archive_entry_sparse_add_entry(entry, + sb->offset, sb->remaining); + } + } + + if (r == ARCHIVE_OK && archive_entry_filetype(entry) == AE_IFREG) { + /* + * "Regular" entry with trailing '/' is really + * directory: This is needed for certain old tar + * variants and even for some broken newer ones. + */ + if ((wp = archive_entry_pathname_w(entry)) != NULL) { + l = wcslen(wp); + if (l > 0 && wp[l - 1] == L'/') { + archive_entry_set_filetype(entry, AE_IFDIR); + } + } else if ((p = archive_entry_pathname(entry)) != NULL) { + l = strlen(p); + if (l > 0 && p[l - 1] == '/') { + archive_entry_set_filetype(entry, AE_IFDIR); + } + } + } + return (r); +} + +static int +archive_read_format_tar_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + ssize_t bytes_read; + struct tar *tar; + struct sparse_block *p; + + tar = (struct tar *)(a->format->data); + + for (;;) { + /* Remove exhausted entries from sparse list. */ + while (tar->sparse_list != NULL && + tar->sparse_list->remaining == 0) { + p = tar->sparse_list; + tar->sparse_list = p->next; + free(p); + } + + if (tar->entry_bytes_unconsumed) { + __archive_read_consume(a, tar->entry_bytes_unconsumed); + tar->entry_bytes_unconsumed = 0; + } + + /* If we're at end of file, return EOF. */ + if (tar->sparse_list == NULL || + tar->entry_bytes_remaining == 0) { + if (__archive_read_consume(a, tar->entry_padding) < 0) + return (ARCHIVE_FATAL); + tar->entry_padding = 0; + *buff = NULL; + *size = 0; + *offset = tar->realsize; + return (ARCHIVE_EOF); + } + + *buff = __archive_read_ahead(a, 1, &bytes_read); + if (bytes_read < 0) + return (ARCHIVE_FATAL); + if (*buff == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Truncated tar archive"); + return (ARCHIVE_FATAL); + } + if (bytes_read > tar->entry_bytes_remaining) + bytes_read = (ssize_t)tar->entry_bytes_remaining; + /* Don't read more than is available in the + * current sparse block. */ + if (tar->sparse_list->remaining < bytes_read) + bytes_read = (ssize_t)tar->sparse_list->remaining; + *size = bytes_read; + *offset = tar->sparse_list->offset; + tar->sparse_list->remaining -= bytes_read; + tar->sparse_list->offset += bytes_read; + tar->entry_bytes_remaining -= bytes_read; + tar->entry_bytes_unconsumed = bytes_read; + + if (!tar->sparse_list->hole) + return (ARCHIVE_OK); + /* Current is hole data and skip this. */ + } +} + +static int +archive_read_format_tar_skip(struct archive_read *a) +{ + int64_t bytes_skipped; + int64_t request; + struct sparse_block *p; + struct tar* tar; + + tar = (struct tar *)(a->format->data); + + /* Do not consume the hole of a sparse file. */ + request = 0; + for (p = tar->sparse_list; p != NULL; p = p->next) { + if (!p->hole) { + if (p->remaining >= INT64_MAX - request) { + return ARCHIVE_FATAL; + } + request += p->remaining; + } + } + if (request > tar->entry_bytes_remaining) + request = tar->entry_bytes_remaining; + request += tar->entry_padding + tar->entry_bytes_unconsumed; + + bytes_skipped = __archive_read_consume(a, request); + if (bytes_skipped < 0) + return (ARCHIVE_FATAL); + + tar->entry_bytes_remaining = 0; + tar->entry_bytes_unconsumed = 0; + tar->entry_padding = 0; + + /* Free the sparse list. */ + gnu_clear_sparse_list(tar); + + return (ARCHIVE_OK); +} + +/* + * This function recursively interprets all of the headers associated + * with a single entry. + */ +static int +tar_read_header(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, size_t *unconsumed) +{ + ssize_t bytes; + int err, eof_vol_header; + const char *h; + const struct archive_entry_header_ustar *header; + const struct archive_entry_header_gnutar *gnuheader; + + eof_vol_header = 0; + + /* Loop until we find a workable header record. */ + for (;;) { + tar_flush_unconsumed(a, unconsumed); + + /* Read 512-byte header record */ + h = __archive_read_ahead(a, 512, &bytes); + if (bytes < 0) + return ((int)bytes); + if (bytes == 0) { /* EOF at a block boundary. */ + /* Some writers do omit the block of nulls. <sigh> */ + return (ARCHIVE_EOF); + } + if (bytes < 512) { /* Short block at EOF; this is bad. */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated tar archive"); + return (ARCHIVE_FATAL); + } + *unconsumed = 512; + + /* Header is workable if it's not an end-of-archive mark. */ + if (h[0] != 0 || !archive_block_is_null(h)) + break; + + /* Ensure format is set for archives with only null blocks. */ + if (a->archive.archive_format_name == NULL) { + a->archive.archive_format = ARCHIVE_FORMAT_TAR; + a->archive.archive_format_name = "tar"; + } + + if (!tar->read_concatenated_archives) { + /* Try to consume a second all-null record, as well. */ + tar_flush_unconsumed(a, unconsumed); + h = __archive_read_ahead(a, 512, NULL); + if (h != NULL && h[0] == 0 && archive_block_is_null(h)) + __archive_read_consume(a, 512); + archive_clear_error(&a->archive); + return (ARCHIVE_EOF); + } + + /* + * We're reading concatenated archives, ignore this block and + * loop to get the next. + */ + } + + /* + * Note: If the checksum fails and we return ARCHIVE_RETRY, + * then the client is likely to just retry. This is a very + * crude way to search for the next valid header! + * + * TODO: Improve this by implementing a real header scan. + */ + if (!checksum(a, h)) { + tar_flush_unconsumed(a, unconsumed); + archive_set_error(&a->archive, EINVAL, "Damaged tar archive"); + return (ARCHIVE_RETRY); /* Retryable: Invalid header */ + } + + if (++tar->header_recursion_depth > 32) { + tar_flush_unconsumed(a, unconsumed); + archive_set_error(&a->archive, EINVAL, "Too many special headers"); + return (ARCHIVE_WARN); + } + + /* Determine the format variant. */ + header = (const struct archive_entry_header_ustar *)h; + + switch(header->typeflag[0]) { + case 'A': /* Solaris tar ACL */ + a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE; + a->archive.archive_format_name = "Solaris tar"; + err = header_Solaris_ACL(a, tar, entry, h, unconsumed); + break; + case 'g': /* POSIX-standard 'g' header. */ + a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE; + a->archive.archive_format_name = "POSIX pax interchange format"; + err = header_pax_global(a, tar, entry, h, unconsumed); + if (err == ARCHIVE_EOF) + return (err); + break; + case 'K': /* Long link name (GNU tar, others) */ + err = header_longlink(a, tar, entry, h, unconsumed); + break; + case 'L': /* Long filename (GNU tar, others) */ + err = header_longname(a, tar, entry, h, unconsumed); + break; + case 'V': /* GNU volume header */ + err = header_volume(a, tar, entry, h, unconsumed); + if (err == ARCHIVE_EOF) + eof_vol_header = 1; + break; + case 'X': /* Used by SUN tar; same as 'x'. */ + a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE; + a->archive.archive_format_name = + "POSIX pax interchange format (Sun variant)"; + err = header_pax_extensions(a, tar, entry, h, unconsumed); + break; + case 'x': /* POSIX-standard 'x' header. */ + a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE; + a->archive.archive_format_name = "POSIX pax interchange format"; + err = header_pax_extensions(a, tar, entry, h, unconsumed); + break; + default: + gnuheader = (const struct archive_entry_header_gnutar *)h; + if (memcmp(gnuheader->magic, "ustar \0", 8) == 0) { + a->archive.archive_format = ARCHIVE_FORMAT_TAR_GNUTAR; + a->archive.archive_format_name = "GNU tar format"; + err = header_gnutar(a, tar, entry, h, unconsumed); + } else if (memcmp(header->magic, "ustar", 5) == 0) { + if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) { + a->archive.archive_format = ARCHIVE_FORMAT_TAR_USTAR; + a->archive.archive_format_name = "POSIX ustar format"; + } + err = header_ustar(a, tar, entry, h); + } else { + a->archive.archive_format = ARCHIVE_FORMAT_TAR; + a->archive.archive_format_name = "tar (non-POSIX)"; + err = header_old_tar(a, tar, entry, h); + } + } + if (err == ARCHIVE_FATAL) + return (err); + + tar_flush_unconsumed(a, unconsumed); + + h = NULL; + header = NULL; + + --tar->header_recursion_depth; + /* Yuck. Apple's design here ends up storing long pathname + * extensions for both the AppleDouble extension entry and the + * regular entry. + */ + if ((err == ARCHIVE_WARN || err == ARCHIVE_OK) && + tar->header_recursion_depth == 0 && + tar->process_mac_extensions) { + int err2 = read_mac_metadata_blob(a, tar, entry, h, unconsumed); + if (err2 < err) + err = err2; + } + + /* We return warnings or success as-is. Anything else is fatal. */ + if (err == ARCHIVE_WARN || err == ARCHIVE_OK) { + if (tar->sparse_gnu_pending) { + if (tar->sparse_gnu_major == 1 && + tar->sparse_gnu_minor == 0) { + ssize_t bytes_read; + + tar->sparse_gnu_pending = 0; + /* Read initial sparse map. */ + bytes_read = gnu_sparse_10_read(a, tar, unconsumed); + if (bytes_read < 0) + return ((int)bytes_read); + tar->entry_bytes_remaining -= bytes_read; + } else { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Unrecognized GNU sparse file format"); + return (ARCHIVE_WARN); + } + tar->sparse_gnu_pending = 0; + } + return (err); + } + if (err == ARCHIVE_EOF) { + if (!eof_vol_header) { + /* EOF when recursively reading a header is bad. */ + archive_set_error(&a->archive, EINVAL, + "Damaged tar archive"); + } else { + /* If we encounter just a GNU volume header treat + * this situation as an empty archive */ + return (ARCHIVE_EOF); + } + } + return (ARCHIVE_FATAL); +} + +/* + * Return true if block checksum is correct. + */ +static int +checksum(struct archive_read *a, const void *h) +{ + const unsigned char *bytes; + const struct archive_entry_header_ustar *header; + int check, sum; + size_t i; + + (void)a; /* UNUSED */ + bytes = (const unsigned char *)h; + header = (const struct archive_entry_header_ustar *)h; + + /* Checksum field must hold an octal number */ + for (i = 0; i < sizeof(header->checksum); ++i) { + char c = header->checksum[i]; + if (c != ' ' && c != '\0' && (c < '0' || c > '7')) + return 0; + } + + /* + * Test the checksum. Note that POSIX specifies _unsigned_ + * bytes for this calculation. + */ + sum = (int)tar_atol(header->checksum, sizeof(header->checksum)); + check = 0; + for (i = 0; i < 148; i++) + check += (unsigned char)bytes[i]; + for (; i < 156; i++) + check += 32; + for (; i < 512; i++) + check += (unsigned char)bytes[i]; + if (sum == check) + return (1); + + /* + * Repeat test with _signed_ bytes, just in case this archive + * was created by an old BSD, Solaris, or HP-UX tar with a + * broken checksum calculation. + */ + check = 0; + for (i = 0; i < 148; i++) + check += (signed char)bytes[i]; + for (; i < 156; i++) + check += 32; + for (; i < 512; i++) + check += (signed char)bytes[i]; + if (sum == check) + return (1); + + return (0); +} + +/* + * Return true if this block contains only nulls. + */ +static int +archive_block_is_null(const char *p) +{ + unsigned i; + + for (i = 0; i < 512; i++) + if (*p++) + return (0); + return (1); +} + +/* + * Interpret 'A' Solaris ACL header + */ +static int +header_Solaris_ACL(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, const void *h, size_t *unconsumed) +{ + const struct archive_entry_header_ustar *header; + size_t size; + int err, acl_type; + int64_t type; + char *acl, *p; + + /* + * read_body_to_string adds a NUL terminator, but we need a little + * more to make sure that we don't overrun acl_text later. + */ + header = (const struct archive_entry_header_ustar *)h; + size = (size_t)tar_atol(header->size, sizeof(header->size)); + err = read_body_to_string(a, tar, &(tar->acl_text), h, unconsumed); + if (err != ARCHIVE_OK) + return (err); + + /* Recursively read next header */ + err = tar_read_header(a, tar, entry, unconsumed); + if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN)) + return (err); + + /* TODO: Examine the first characters to see if this + * is an AIX ACL descriptor. We'll likely never support + * them, but it would be polite to recognize and warn when + * we do see them. */ + + /* Leading octal number indicates ACL type and number of entries. */ + p = acl = tar->acl_text.s; + type = 0; + while (*p != '\0' && p < acl + size) { + if (*p < '0' || *p > '7') { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Malformed Solaris ACL attribute (invalid digit)"); + return(ARCHIVE_WARN); + } + type <<= 3; + type += *p - '0'; + if (type > 077777777) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Malformed Solaris ACL attribute (count too large)"); + return (ARCHIVE_WARN); + } + p++; + } + switch ((int)type & ~0777777) { + case 01000000: + /* POSIX.1e ACL */ + acl_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; + break; + case 03000000: + /* NFSv4 ACL */ + acl_type = ARCHIVE_ENTRY_ACL_TYPE_NFS4; + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Malformed Solaris ACL attribute (unsupported type %o)", + (int)type); + return (ARCHIVE_WARN); + } + p++; + + if (p >= acl + size) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Malformed Solaris ACL attribute (body overflow)"); + return(ARCHIVE_WARN); + } + + /* ACL text is null-terminated; find the end. */ + size -= (p - acl); + acl = p; + + while (*p != '\0' && p < acl + size) + p++; + + if (tar->sconv_acl == NULL) { + tar->sconv_acl = archive_string_conversion_from_charset( + &(a->archive), "UTF-8", 1); + if (tar->sconv_acl == NULL) + return (ARCHIVE_FATAL); + } + archive_strncpy(&(tar->localname), acl, p - acl); + err = archive_acl_from_text_l(archive_entry_acl(entry), + tar->localname.s, acl_type, tar->sconv_acl); + if (err != ARCHIVE_OK) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for ACL"); + } else + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Malformed Solaris ACL attribute (unparsable)"); + } + return (err); +} + +/* + * Interpret 'K' long linkname header. + */ +static int +header_longlink(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, const void *h, size_t *unconsumed) +{ + int err; + + err = read_body_to_string(a, tar, &(tar->longlink), h, unconsumed); + if (err != ARCHIVE_OK) + return (err); + err = tar_read_header(a, tar, entry, unconsumed); + if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN)) + return (err); + /* Set symlink if symlink already set, else hardlink. */ + archive_entry_copy_link(entry, tar->longlink.s); + return (ARCHIVE_OK); +} + +static int +set_conversion_failed_error(struct archive_read *a, + struct archive_string_conv *sconv, const char *name) +{ + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for %s", name); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "%s can't be converted from %s to current locale.", + name, archive_string_conversion_charset_name(sconv)); + return (ARCHIVE_WARN); +} + +/* + * Interpret 'L' long filename header. + */ +static int +header_longname(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, const void *h, size_t *unconsumed) +{ + int err; + + err = read_body_to_string(a, tar, &(tar->longname), h, unconsumed); + if (err != ARCHIVE_OK) + return (err); + /* Read and parse "real" header, then override name. */ + err = tar_read_header(a, tar, entry, unconsumed); + if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN)) + return (err); + if (archive_entry_copy_pathname_l(entry, tar->longname.s, + archive_strlen(&(tar->longname)), tar->sconv) != 0) + err = set_conversion_failed_error(a, tar->sconv, "Pathname"); + return (err); +} + + +/* + * Interpret 'V' GNU tar volume header. + */ +static int +header_volume(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, const void *h, size_t *unconsumed) +{ + (void)h; + + /* Just skip this and read the next header. */ + return (tar_read_header(a, tar, entry, unconsumed)); +} + +/* + * Read body of an archive entry into an archive_string object. + */ +static int +read_body_to_string(struct archive_read *a, struct tar *tar, + struct archive_string *as, const void *h, size_t *unconsumed) +{ + int64_t size; + const struct archive_entry_header_ustar *header; + const void *src; + + (void)tar; /* UNUSED */ + header = (const struct archive_entry_header_ustar *)h; + size = tar_atol(header->size, sizeof(header->size)); + if ((size > 1048576) || (size < 0)) { + archive_set_error(&a->archive, EINVAL, + "Special header too large"); + return (ARCHIVE_FATAL); + } + + /* Fail if we can't make our buffer big enough. */ + if (archive_string_ensure(as, (size_t)size+1) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory"); + return (ARCHIVE_FATAL); + } + + tar_flush_unconsumed(a, unconsumed); + + /* Read the body into the string. */ + *unconsumed = (size_t)((size + 511) & ~ 511); + src = __archive_read_ahead(a, *unconsumed, NULL); + if (src == NULL) { + *unconsumed = 0; + return (ARCHIVE_FATAL); + } + memcpy(as->s, src, (size_t)size); + as->s[size] = '\0'; + as->length = (size_t)size; + return (ARCHIVE_OK); +} + +/* + * Parse out common header elements. + * + * This would be the same as header_old_tar, except that the + * filename is handled slightly differently for old and POSIX + * entries (POSIX entries support a 'prefix'). This factoring + * allows header_old_tar and header_ustar + * to handle filenames differently, while still putting most of the + * common parsing into one place. + */ +static int +header_common(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, const void *h) +{ + const struct archive_entry_header_ustar *header; + char tartype; + int err = ARCHIVE_OK; + + header = (const struct archive_entry_header_ustar *)h; + if (header->linkname[0]) + archive_strncpy(&(tar->entry_linkpath), + header->linkname, sizeof(header->linkname)); + else + archive_string_empty(&(tar->entry_linkpath)); + + /* Parse out the numeric fields (all are octal) */ + archive_entry_set_mode(entry, + (mode_t)tar_atol(header->mode, sizeof(header->mode))); + archive_entry_set_uid(entry, tar_atol(header->uid, sizeof(header->uid))); + archive_entry_set_gid(entry, tar_atol(header->gid, sizeof(header->gid))); + tar->entry_bytes_remaining = tar_atol(header->size, sizeof(header->size)); + if (tar->entry_bytes_remaining < 0) { + tar->entry_bytes_remaining = 0; + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Tar entry has negative size"); + return (ARCHIVE_FATAL); + } + if (tar->entry_bytes_remaining == INT64_MAX) { + /* Note: tar_atol returns INT64_MAX on overflow */ + tar->entry_bytes_remaining = 0; + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Tar entry size overflow"); + return (ARCHIVE_FATAL); + } + tar->realsize = tar->entry_bytes_remaining; + archive_entry_set_size(entry, tar->entry_bytes_remaining); + archive_entry_set_mtime(entry, tar_atol(header->mtime, sizeof(header->mtime)), 0); + + /* Handle the tar type flag appropriately. */ + tartype = header->typeflag[0]; + + switch (tartype) { + case '1': /* Hard link */ + if (archive_entry_copy_hardlink_l(entry, tar->entry_linkpath.s, + archive_strlen(&(tar->entry_linkpath)), tar->sconv) != 0) { + err = set_conversion_failed_error(a, tar->sconv, + "Linkname"); + if (err == ARCHIVE_FATAL) + return (err); + } + /* + * The following may seem odd, but: Technically, tar + * does not store the file type for a "hard link" + * entry, only the fact that it is a hard link. So, I + * leave the type zero normally. But, pax interchange + * format allows hard links to have data, which + * implies that the underlying entry is a regular + * file. + */ + if (archive_entry_size(entry) > 0) + archive_entry_set_filetype(entry, AE_IFREG); + + /* + * A tricky point: Traditionally, tar readers have + * ignored the size field when reading hardlink + * entries, and some writers put non-zero sizes even + * though the body is empty. POSIX blessed this + * convention in the 1988 standard, but broke with + * this tradition in 2001 by permitting hardlink + * entries to store valid bodies in pax interchange + * format, but not in ustar format. Since there is no + * hard and fast way to distinguish pax interchange + * from earlier archives (the 'x' and 'g' entries are + * optional, after all), we need a heuristic. + */ + if (archive_entry_size(entry) == 0) { + /* If the size is already zero, we're done. */ + } else if (a->archive.archive_format + == ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) { + /* Definitely pax extended; must obey hardlink size. */ + } else if (a->archive.archive_format == ARCHIVE_FORMAT_TAR + || a->archive.archive_format == ARCHIVE_FORMAT_TAR_GNUTAR) + { + /* Old-style or GNU tar: we must ignore the size. */ + archive_entry_set_size(entry, 0); + tar->entry_bytes_remaining = 0; + } else if (archive_read_format_tar_bid(a, 50) > 50) { + /* + * We don't know if it's pax: If the bid + * function sees a valid ustar header + * immediately following, then let's ignore + * the hardlink size. + */ + archive_entry_set_size(entry, 0); + tar->entry_bytes_remaining = 0; + } + /* + * TODO: There are still two cases I'd like to handle: + * = a ustar non-pax archive with a hardlink entry at + * end-of-archive. (Look for block of nulls following?) + * = a pax archive that has not seen any pax headers + * and has an entry which is a hardlink entry storing + * a body containing an uncompressed tar archive. + * The first is worth addressing; I don't see any reliable + * way to deal with the second possibility. + */ + break; + case '2': /* Symlink */ + archive_entry_set_filetype(entry, AE_IFLNK); + archive_entry_set_size(entry, 0); + tar->entry_bytes_remaining = 0; + if (archive_entry_copy_symlink_l(entry, tar->entry_linkpath.s, + archive_strlen(&(tar->entry_linkpath)), tar->sconv) != 0) { + err = set_conversion_failed_error(a, tar->sconv, + "Linkname"); + if (err == ARCHIVE_FATAL) + return (err); + } + break; + case '3': /* Character device */ + archive_entry_set_filetype(entry, AE_IFCHR); + archive_entry_set_size(entry, 0); + tar->entry_bytes_remaining = 0; + break; + case '4': /* Block device */ + archive_entry_set_filetype(entry, AE_IFBLK); + archive_entry_set_size(entry, 0); + tar->entry_bytes_remaining = 0; + break; + case '5': /* Dir */ + archive_entry_set_filetype(entry, AE_IFDIR); + archive_entry_set_size(entry, 0); + tar->entry_bytes_remaining = 0; + break; + case '6': /* FIFO device */ + archive_entry_set_filetype(entry, AE_IFIFO); + archive_entry_set_size(entry, 0); + tar->entry_bytes_remaining = 0; + break; + case 'D': /* GNU incremental directory type */ + /* + * No special handling is actually required here. + * It might be nice someday to preprocess the file list and + * provide it to the client, though. + */ + archive_entry_set_filetype(entry, AE_IFDIR); + break; + case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/ + /* + * As far as I can tell, this is just like a regular file + * entry, except that the contents should be _appended_ to + * the indicated file at the indicated offset. This may + * require some API work to fully support. + */ + break; + case 'N': /* Old GNU "long filename" entry. */ + /* The body of this entry is a script for renaming + * previously-extracted entries. Ugh. It will never + * be supported by libarchive. */ + archive_entry_set_filetype(entry, AE_IFREG); + break; + case 'S': /* GNU sparse files */ + /* + * Sparse files are really just regular files with + * sparse information in the extended area. + */ + /* FALLTHROUGH */ + case '0': + /* + * Enable sparse file "read" support only for regular + * files and explicit GNU sparse files. However, we + * don't allow non-standard file types to be sparse. + */ + tar->sparse_allowed = 1; + /* FALLTHROUGH */ + default: /* Regular file and non-standard types */ + /* + * Per POSIX: non-recognized types should always be + * treated as regular files. + */ + archive_entry_set_filetype(entry, AE_IFREG); + break; + } + return (err); +} + +/* + * Parse out header elements for "old-style" tar archives. + */ +static int +header_old_tar(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, const void *h) +{ + const struct archive_entry_header_ustar *header; + int err = ARCHIVE_OK, err2; + + /* Copy filename over (to ensure null termination). */ + header = (const struct archive_entry_header_ustar *)h; + if (archive_entry_copy_pathname_l(entry, + header->name, sizeof(header->name), tar->sconv) != 0) { + err = set_conversion_failed_error(a, tar->sconv, "Pathname"); + if (err == ARCHIVE_FATAL) + return (err); + } + + /* Grab rest of common fields */ + err2 = header_common(a, tar, entry, h); + if (err > err2) + err = err2; + + tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining); + return (err); +} + +/* + * Read a Mac AppleDouble-encoded blob of file metadata, + * if there is one. + */ +static int +read_mac_metadata_blob(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, const void *h, size_t *unconsumed) +{ + int64_t size; + const void *data; + const char *p, *name; + const wchar_t *wp, *wname; + + (void)h; /* UNUSED */ + + wname = wp = archive_entry_pathname_w(entry); + if (wp != NULL) { + /* Find the last path element. */ + for (; *wp != L'\0'; ++wp) { + if (wp[0] == '/' && wp[1] != L'\0') + wname = wp + 1; + } + /* + * If last path element starts with "._", then + * this is a Mac extension. + */ + if (wname[0] != L'.' || wname[1] != L'_' || wname[2] == L'\0') + return ARCHIVE_OK; + } else { + /* Find the last path element. */ + name = p = archive_entry_pathname(entry); + if (p == NULL) + return (ARCHIVE_FAILED); + for (; *p != '\0'; ++p) { + if (p[0] == '/' && p[1] != '\0') + name = p + 1; + } + /* + * If last path element starts with "._", then + * this is a Mac extension. + */ + if (name[0] != '.' || name[1] != '_' || name[2] == '\0') + return ARCHIVE_OK; + } + + /* Read the body as a Mac OS metadata blob. */ + size = archive_entry_size(entry); + + /* + * TODO: Look beyond the body here to peek at the next header. + * If it's a regular header (not an extension header) + * that has the wrong name, just return the current + * entry as-is, without consuming the body here. + * That would reduce the risk of us mis-identifying + * an ordinary file that just happened to have + * a name starting with "._". + * + * Q: Is the above idea really possible? Even + * when there are GNU or pax extension entries? + */ + data = __archive_read_ahead(a, (size_t)size, NULL); + if (data == NULL) { + *unconsumed = 0; + return (ARCHIVE_FATAL); + } + archive_entry_copy_mac_metadata(entry, data, (size_t)size); + *unconsumed = (size_t)((size + 511) & ~ 511); + tar_flush_unconsumed(a, unconsumed); + return (tar_read_header(a, tar, entry, unconsumed)); +} + +/* + * Parse a file header for a pax extended archive entry. + */ +static int +header_pax_global(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, const void *h, size_t *unconsumed) +{ + int err; + + err = read_body_to_string(a, tar, &(tar->pax_global), h, unconsumed); + if (err != ARCHIVE_OK) + return (err); + err = tar_read_header(a, tar, entry, unconsumed); + return (err); +} + +static int +header_pax_extensions(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, const void *h, size_t *unconsumed) +{ + int err, err2; + + err = read_body_to_string(a, tar, &(tar->pax_header), h, unconsumed); + if (err != ARCHIVE_OK) + return (err); + + /* Parse the next header. */ + err = tar_read_header(a, tar, entry, unconsumed); + if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN)) + return (err); + + /* + * TODO: Parse global/default options into 'entry' struct here + * before handling file-specific options. + * + * This design (parse standard header, then overwrite with pax + * extended attribute data) usually works well, but isn't ideal; + * it would be better to parse the pax extended attributes first + * and then skip any fields in the standard header that were + * defined in the pax header. + */ + err2 = pax_header(a, tar, entry, &tar->pax_header); + err = err_combine(err, err2); + tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining); + return (err); +} + + +/* + * Parse a file header for a Posix "ustar" archive entry. This also + * handles "pax" or "extended ustar" entries. + */ +static int +header_ustar(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, const void *h) +{ + const struct archive_entry_header_ustar *header; + struct archive_string *as; + int err = ARCHIVE_OK, r; + + header = (const struct archive_entry_header_ustar *)h; + + /* Copy name into an internal buffer to ensure null-termination. */ + as = &(tar->entry_pathname); + if (header->prefix[0]) { + archive_strncpy(as, header->prefix, sizeof(header->prefix)); + if (as->s[archive_strlen(as) - 1] != '/') + archive_strappend_char(as, '/'); + archive_strncat(as, header->name, sizeof(header->name)); + } else { + archive_strncpy(as, header->name, sizeof(header->name)); + } + if (archive_entry_copy_pathname_l(entry, as->s, archive_strlen(as), + tar->sconv) != 0) { + err = set_conversion_failed_error(a, tar->sconv, "Pathname"); + if (err == ARCHIVE_FATAL) + return (err); + } + + /* Handle rest of common fields. */ + r = header_common(a, tar, entry, h); + if (r == ARCHIVE_FATAL) + return (r); + if (r < err) + err = r; + + /* Handle POSIX ustar fields. */ + if (archive_entry_copy_uname_l(entry, + header->uname, sizeof(header->uname), tar->sconv) != 0) { + err = set_conversion_failed_error(a, tar->sconv, "Uname"); + if (err == ARCHIVE_FATAL) + return (err); + } + + if (archive_entry_copy_gname_l(entry, + header->gname, sizeof(header->gname), tar->sconv) != 0) { + err = set_conversion_failed_error(a, tar->sconv, "Gname"); + if (err == ARCHIVE_FATAL) + return (err); + } + + /* Parse out device numbers only for char and block specials. */ + if (header->typeflag[0] == '3' || header->typeflag[0] == '4') { + archive_entry_set_rdevmajor(entry, (dev_t) + tar_atol(header->rdevmajor, sizeof(header->rdevmajor))); + archive_entry_set_rdevminor(entry, (dev_t) + tar_atol(header->rdevminor, sizeof(header->rdevminor))); + } + + tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining); + + return (err); +} + + +/* + * Parse the pax extended attributes record. + * + * Returns non-zero if there's an error in the data. + */ +static int +pax_header(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, struct archive_string *in_as) +{ + size_t attr_length, l, line_length, value_length; + char *p; + char *key, *value; + struct archive_string *as; + struct archive_string_conv *sconv; + int err, err2; + char *attr = in_as->s; + + attr_length = in_as->length; + tar->pax_hdrcharset_binary = 0; + archive_string_empty(&(tar->entry_gname)); + archive_string_empty(&(tar->entry_linkpath)); + archive_string_empty(&(tar->entry_pathname)); + archive_string_empty(&(tar->entry_pathname_override)); + archive_string_empty(&(tar->entry_uname)); + err = ARCHIVE_OK; + while (attr_length > 0) { + /* Parse decimal length field at start of line. */ + line_length = 0; + l = attr_length; + p = attr; /* Record start of line. */ + while (l>0) { + if (*p == ' ') { + p++; + l--; + break; + } + if (*p < '0' || *p > '9') { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Ignoring malformed pax extended attributes"); + return (ARCHIVE_WARN); + } + line_length *= 10; + line_length += *p - '0'; + if (line_length > 999999) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Rejecting pax extended attribute > 1MB"); + return (ARCHIVE_WARN); + } + p++; + l--; + } + + /* + * Parsed length must be no bigger than available data, + * at least 1, and the last character of the line must + * be '\n'. + */ + if (line_length > attr_length + || line_length < 1 + || attr[line_length - 1] != '\n') + { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Ignoring malformed pax extended attribute"); + return (ARCHIVE_WARN); + } + + /* Null-terminate the line. */ + attr[line_length - 1] = '\0'; + + /* Find end of key and null terminate it. */ + key = p; + if (key[0] == '=') + return (-1); + while (*p && *p != '=') + ++p; + if (*p == '\0') { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid pax extended attributes"); + return (ARCHIVE_WARN); + } + *p = '\0'; + + value = p + 1; + + /* Some values may be binary data */ + value_length = attr + line_length - 1 - value; + + /* Identify this attribute and set it in the entry. */ + err2 = pax_attribute(a, tar, entry, key, value, value_length); + if (err2 == ARCHIVE_FATAL) + return (err2); + err = err_combine(err, err2); + + /* Skip to next line */ + attr += line_length; + attr_length -= line_length; + } + + /* + * PAX format uses UTF-8 as default charset for its metadata + * unless hdrcharset=BINARY is present in its header. + * We apply the charset specified by the hdrcharset option only + * when the hdrcharset attribute(in PAX header) is BINARY because + * we respect the charset described in PAX header and BINARY also + * means that metadata(filename,uname and gname) character-set + * is unknown. + */ + if (tar->pax_hdrcharset_binary) + sconv = tar->opt_sconv; + else { + sconv = archive_string_conversion_from_charset( + &(a->archive), "UTF-8", 1); + if (sconv == NULL) + return (ARCHIVE_FATAL); + if (tar->compat_2x) + archive_string_conversion_set_opt(sconv, + SCONV_SET_OPT_UTF8_LIBARCHIVE2X); + } + + if (archive_strlen(&(tar->entry_gname)) > 0) { + if (archive_entry_copy_gname_l(entry, tar->entry_gname.s, + archive_strlen(&(tar->entry_gname)), sconv) != 0) { + err = set_conversion_failed_error(a, sconv, "Gname"); + if (err == ARCHIVE_FATAL) + return (err); + /* Use a converted an original name. */ + archive_entry_copy_gname(entry, tar->entry_gname.s); + } + } + if (archive_strlen(&(tar->entry_linkpath)) > 0) { + if (archive_entry_copy_link_l(entry, tar->entry_linkpath.s, + archive_strlen(&(tar->entry_linkpath)), sconv) != 0) { + err = set_conversion_failed_error(a, sconv, "Linkname"); + if (err == ARCHIVE_FATAL) + return (err); + /* Use a converted an original name. */ + archive_entry_copy_link(entry, tar->entry_linkpath.s); + } + } + /* + * Some extensions (such as the GNU sparse file extensions) + * deliberately store a synthetic name under the regular 'path' + * attribute and the real file name under a different attribute. + * Since we're supposed to not care about the order, we + * have no choice but to store all of the various filenames + * we find and figure it all out afterwards. This is the + * figuring out part. + */ + as = NULL; + if (archive_strlen(&(tar->entry_pathname_override)) > 0) + as = &(tar->entry_pathname_override); + else if (archive_strlen(&(tar->entry_pathname)) > 0) + as = &(tar->entry_pathname); + if (as != NULL) { + if (archive_entry_copy_pathname_l(entry, as->s, + archive_strlen(as), sconv) != 0) { + err = set_conversion_failed_error(a, sconv, "Pathname"); + if (err == ARCHIVE_FATAL) + return (err); + /* Use a converted an original name. */ + archive_entry_copy_pathname(entry, as->s); + } + } + if (archive_strlen(&(tar->entry_uname)) > 0) { + if (archive_entry_copy_uname_l(entry, tar->entry_uname.s, + archive_strlen(&(tar->entry_uname)), sconv) != 0) { + err = set_conversion_failed_error(a, sconv, "Uname"); + if (err == ARCHIVE_FATAL) + return (err); + /* Use a converted an original name. */ + archive_entry_copy_uname(entry, tar->entry_uname.s); + } + } + return (err); +} + +static int +pax_attribute_xattr(struct archive_entry *entry, + const char *name, const char *value) +{ + char *name_decoded; + void *value_decoded; + size_t value_len; + + if (strlen(name) < 18 || (memcmp(name, "LIBARCHIVE.xattr.", 17)) != 0) + return 3; + + name += 17; + + /* URL-decode name */ + name_decoded = url_decode(name); + if (name_decoded == NULL) + return 2; + + /* Base-64 decode value */ + value_decoded = base64_decode(value, strlen(value), &value_len); + if (value_decoded == NULL) { + free(name_decoded); + return 1; + } + + archive_entry_xattr_add_entry(entry, name_decoded, + value_decoded, value_len); + + free(name_decoded); + free(value_decoded); + return 0; +} + +static int +pax_attribute_schily_xattr(struct archive_entry *entry, + const char *name, const char *value, size_t value_length) +{ + if (strlen(name) < 14 || (memcmp(name, "SCHILY.xattr.", 13)) != 0) + return 1; + + name += 13; + + archive_entry_xattr_add_entry(entry, name, value, value_length); + + return 0; +} + +static int +pax_attribute_rht_security_selinux(struct archive_entry *entry, + const char *value, size_t value_length) +{ + archive_entry_xattr_add_entry(entry, "security.selinux", + value, value_length); + + return 0; +} + +static int +pax_attribute_acl(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, const char *value, int type) +{ + int r; + const char* errstr; + + switch (type) { + case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: + errstr = "SCHILY.acl.access"; + break; + case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: + errstr = "SCHILY.acl.default"; + break; + case ARCHIVE_ENTRY_ACL_TYPE_NFS4: + errstr = "SCHILY.acl.ace"; + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Unknown ACL type: %d", type); + return(ARCHIVE_FATAL); + } + + if (tar->sconv_acl == NULL) { + tar->sconv_acl = + archive_string_conversion_from_charset( + &(a->archive), "UTF-8", 1); + if (tar->sconv_acl == NULL) + return (ARCHIVE_FATAL); + } + + r = archive_acl_from_text_l(archive_entry_acl(entry), value, type, + tar->sconv_acl); + if (r != ARCHIVE_OK) { + if (r == ARCHIVE_FATAL) { + archive_set_error(&a->archive, ENOMEM, + "%s %s", "Can't allocate memory for ", + errstr); + return (r); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, "%s %s", "Parse error: ", errstr); + } + return (r); +} + +/* + * Parse a single key=value attribute. key/value pointers are + * assumed to point into reasonably long-lived storage. + * + * Note that POSIX reserves all-lowercase keywords. Vendor-specific + * extensions should always have keywords of the form "VENDOR.attribute" + * In particular, it's quite feasible to support many different + * vendor extensions here. I'm using "LIBARCHIVE" for extensions + * unique to this library. + * + * Investigate other vendor-specific extensions and see if + * any of them look useful. + */ +static int +pax_attribute(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, const char *key, const char *value, size_t value_length) +{ + int64_t s; + long n; + int err = ARCHIVE_OK, r; + + if (value == NULL) + value = ""; /* Disable compiler warning; do not pass + * NULL pointer to strlen(). */ + switch (key[0]) { + case 'G': + /* Reject GNU.sparse.* headers on non-regular files. */ + if (strncmp(key, "GNU.sparse", 10) == 0 && + !tar->sparse_allowed) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Non-regular file cannot be sparse"); + return (ARCHIVE_FATAL); + } + + /* GNU "0.0" sparse pax format. */ + if (strcmp(key, "GNU.sparse.numblocks") == 0) { + tar->sparse_offset = -1; + tar->sparse_numbytes = -1; + tar->sparse_gnu_major = 0; + tar->sparse_gnu_minor = 0; + } + if (strcmp(key, "GNU.sparse.offset") == 0) { + tar->sparse_offset = tar_atol10(value, strlen(value)); + if (tar->sparse_numbytes != -1) { + if (gnu_add_sparse_entry(a, tar, + tar->sparse_offset, tar->sparse_numbytes) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + tar->sparse_offset = -1; + tar->sparse_numbytes = -1; + } + } + if (strcmp(key, "GNU.sparse.numbytes") == 0) { + tar->sparse_numbytes = tar_atol10(value, strlen(value)); + if (tar->sparse_numbytes != -1) { + if (gnu_add_sparse_entry(a, tar, + tar->sparse_offset, tar->sparse_numbytes) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + tar->sparse_offset = -1; + tar->sparse_numbytes = -1; + } + } + if (strcmp(key, "GNU.sparse.size") == 0) { + tar->realsize = tar_atol10(value, strlen(value)); + archive_entry_set_size(entry, tar->realsize); + tar->realsize_override = 1; + } + + /* GNU "0.1" sparse pax format. */ + if (strcmp(key, "GNU.sparse.map") == 0) { + tar->sparse_gnu_major = 0; + tar->sparse_gnu_minor = 1; + if (gnu_sparse_01_parse(a, tar, value) != ARCHIVE_OK) + return (ARCHIVE_WARN); + } + + /* GNU "1.0" sparse pax format */ + if (strcmp(key, "GNU.sparse.major") == 0) { + tar->sparse_gnu_major = (int)tar_atol10(value, strlen(value)); + tar->sparse_gnu_pending = 1; + } + if (strcmp(key, "GNU.sparse.minor") == 0) { + tar->sparse_gnu_minor = (int)tar_atol10(value, strlen(value)); + tar->sparse_gnu_pending = 1; + } + if (strcmp(key, "GNU.sparse.name") == 0) { + /* + * The real filename; when storing sparse + * files, GNU tar puts a synthesized name into + * the regular 'path' attribute in an attempt + * to limit confusion. ;-) + */ + archive_strcpy(&(tar->entry_pathname_override), value); + } + if (strcmp(key, "GNU.sparse.realsize") == 0) { + tar->realsize = tar_atol10(value, strlen(value)); + archive_entry_set_size(entry, tar->realsize); + tar->realsize_override = 1; + } + break; + case 'L': + /* Our extensions */ +/* TODO: Handle arbitrary extended attributes... */ +/* + if (strcmp(key, "LIBARCHIVE.xxxxxxx") == 0) + archive_entry_set_xxxxxx(entry, value); +*/ + if (strcmp(key, "LIBARCHIVE.creationtime") == 0) { + pax_time(value, &s, &n); + archive_entry_set_birthtime(entry, s, n); + } + if (strcmp(key, "LIBARCHIVE.symlinktype") == 0) { + if (strcmp(value, "file") == 0) { + archive_entry_set_symlink_type(entry, + AE_SYMLINK_TYPE_FILE); + } else if (strcmp(value, "dir") == 0) { + archive_entry_set_symlink_type(entry, + AE_SYMLINK_TYPE_DIRECTORY); + } + } + if (memcmp(key, "LIBARCHIVE.xattr.", 17) == 0) + pax_attribute_xattr(entry, key, value); + break; + case 'R': + /* GNU tar uses RHT.security header to store SELinux xattrs + * SCHILY.xattr.security.selinux == RHT.security.selinux */ + if (strcmp(key, "RHT.security.selinux") == 0) { + pax_attribute_rht_security_selinux(entry, value, + value_length); + } + break; + case 'S': + /* We support some keys used by the "star" archiver */ + if (strcmp(key, "SCHILY.acl.access") == 0) { + r = pax_attribute_acl(a, tar, entry, value, + ARCHIVE_ENTRY_ACL_TYPE_ACCESS); + if (r == ARCHIVE_FATAL) + return (r); + } else if (strcmp(key, "SCHILY.acl.default") == 0) { + r = pax_attribute_acl(a, tar, entry, value, + ARCHIVE_ENTRY_ACL_TYPE_DEFAULT); + if (r == ARCHIVE_FATAL) + return (r); + } else if (strcmp(key, "SCHILY.acl.ace") == 0) { + r = pax_attribute_acl(a, tar, entry, value, + ARCHIVE_ENTRY_ACL_TYPE_NFS4); + if (r == ARCHIVE_FATAL) + return (r); + } else if (strcmp(key, "SCHILY.devmajor") == 0) { + archive_entry_set_rdevmajor(entry, + (dev_t)tar_atol10(value, strlen(value))); + } else if (strcmp(key, "SCHILY.devminor") == 0) { + archive_entry_set_rdevminor(entry, + (dev_t)tar_atol10(value, strlen(value))); + } else if (strcmp(key, "SCHILY.fflags") == 0) { + archive_entry_copy_fflags_text(entry, value); + } else if (strcmp(key, "SCHILY.dev") == 0) { + archive_entry_set_dev(entry, + (dev_t)tar_atol10(value, strlen(value))); + } else if (strcmp(key, "SCHILY.ino") == 0) { + archive_entry_set_ino(entry, + tar_atol10(value, strlen(value))); + } else if (strcmp(key, "SCHILY.nlink") == 0) { + archive_entry_set_nlink(entry, (unsigned) + tar_atol10(value, strlen(value))); + } else if (strcmp(key, "SCHILY.realsize") == 0) { + tar->realsize = tar_atol10(value, strlen(value)); + tar->realsize_override = 1; + archive_entry_set_size(entry, tar->realsize); + } else if (strncmp(key, "SCHILY.xattr.", 13) == 0) { + pax_attribute_schily_xattr(entry, key, value, + value_length); + } else if (strcmp(key, "SUN.holesdata") == 0) { + /* A Solaris extension for sparse. */ + r = solaris_sparse_parse(a, tar, entry, value); + if (r < err) { + if (r == ARCHIVE_FATAL) + return (r); + err = r; + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Parse error: SUN.holesdata"); + } + } + break; + case 'a': + if (strcmp(key, "atime") == 0) { + pax_time(value, &s, &n); + archive_entry_set_atime(entry, s, n); + } + break; + case 'c': + if (strcmp(key, "ctime") == 0) { + pax_time(value, &s, &n); + archive_entry_set_ctime(entry, s, n); + } else if (strcmp(key, "charset") == 0) { + /* TODO: Publish charset information in entry. */ + } else if (strcmp(key, "comment") == 0) { + /* TODO: Publish comment in entry. */ + } + break; + case 'g': + if (strcmp(key, "gid") == 0) { + archive_entry_set_gid(entry, + tar_atol10(value, strlen(value))); + } else if (strcmp(key, "gname") == 0) { + archive_strcpy(&(tar->entry_gname), value); + } + break; + case 'h': + if (strcmp(key, "hdrcharset") == 0) { + if (strcmp(value, "BINARY") == 0) + /* Binary mode. */ + tar->pax_hdrcharset_binary = 1; + else if (strcmp(value, "ISO-IR 10646 2000 UTF-8") == 0) + tar->pax_hdrcharset_binary = 0; + } + break; + case 'l': + /* pax interchange doesn't distinguish hardlink vs. symlink. */ + if (strcmp(key, "linkpath") == 0) { + archive_strcpy(&(tar->entry_linkpath), value); + } + break; + case 'm': + if (strcmp(key, "mtime") == 0) { + pax_time(value, &s, &n); + archive_entry_set_mtime(entry, s, n); + } + break; + case 'p': + if (strcmp(key, "path") == 0) { + archive_strcpy(&(tar->entry_pathname), value); + } + break; + case 'r': + /* POSIX has reserved 'realtime.*' */ + break; + case 's': + /* POSIX has reserved 'security.*' */ + /* Someday: if (strcmp(key, "security.acl") == 0) { ... } */ + if (strcmp(key, "size") == 0) { + /* "size" is the size of the data in the entry. */ + tar->entry_bytes_remaining + = tar_atol10(value, strlen(value)); + /* + * The "size" pax header keyword always overrides the + * "size" field in the tar header. + * GNU.sparse.realsize, GNU.sparse.size and + * SCHILY.realsize override this value. + */ + if (!tar->realsize_override) { + archive_entry_set_size(entry, + tar->entry_bytes_remaining); + tar->realsize + = tar->entry_bytes_remaining; + } + } + break; + case 'u': + if (strcmp(key, "uid") == 0) { + archive_entry_set_uid(entry, + tar_atol10(value, strlen(value))); + } else if (strcmp(key, "uname") == 0) { + archive_strcpy(&(tar->entry_uname), value); + } + break; + } + return (err); +} + + + +/* + * parse a decimal time value, which may include a fractional portion + */ +static void +pax_time(const char *p, int64_t *ps, long *pn) +{ + char digit; + int64_t s; + unsigned long l; + int sign; + int64_t limit, last_digit_limit; + + limit = INT64_MAX / 10; + last_digit_limit = INT64_MAX % 10; + + s = 0; + sign = 1; + if (*p == '-') { + sign = -1; + p++; + } + while (*p >= '0' && *p <= '9') { + digit = *p - '0'; + if (s > limit || + (s == limit && digit > last_digit_limit)) { + s = INT64_MAX; + break; + } + s = (s * 10) + digit; + ++p; + } + + *ps = s * sign; + + /* Calculate nanoseconds. */ + *pn = 0; + + if (*p != '.') + return; + + l = 100000000UL; + do { + ++p; + if (*p >= '0' && *p <= '9') + *pn += (*p - '0') * l; + else + break; + } while (l /= 10); +} + +/* + * Parse GNU tar header + */ +static int +header_gnutar(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, const void *h, size_t *unconsumed) +{ + const struct archive_entry_header_gnutar *header; + int64_t t; + int err = ARCHIVE_OK; + + /* + * GNU header is like POSIX ustar, except 'prefix' is + * replaced with some other fields. This also means the + * filename is stored as in old-style archives. + */ + + /* Grab fields common to all tar variants. */ + err = header_common(a, tar, entry, h); + if (err == ARCHIVE_FATAL) + return (err); + + /* Copy filename over (to ensure null termination). */ + header = (const struct archive_entry_header_gnutar *)h; + if (archive_entry_copy_pathname_l(entry, + header->name, sizeof(header->name), tar->sconv) != 0) { + err = set_conversion_failed_error(a, tar->sconv, "Pathname"); + if (err == ARCHIVE_FATAL) + return (err); + } + + /* Fields common to ustar and GNU */ + /* XXX Can the following be factored out since it's common + * to ustar and gnu tar? Is it okay to move it down into + * header_common, perhaps? */ + if (archive_entry_copy_uname_l(entry, + header->uname, sizeof(header->uname), tar->sconv) != 0) { + err = set_conversion_failed_error(a, tar->sconv, "Uname"); + if (err == ARCHIVE_FATAL) + return (err); + } + + if (archive_entry_copy_gname_l(entry, + header->gname, sizeof(header->gname), tar->sconv) != 0) { + err = set_conversion_failed_error(a, tar->sconv, "Gname"); + if (err == ARCHIVE_FATAL) + return (err); + } + + /* Parse out device numbers only for char and block specials */ + if (header->typeflag[0] == '3' || header->typeflag[0] == '4') { + archive_entry_set_rdevmajor(entry, (dev_t) + tar_atol(header->rdevmajor, sizeof(header->rdevmajor))); + archive_entry_set_rdevminor(entry, (dev_t) + tar_atol(header->rdevminor, sizeof(header->rdevminor))); + } else + archive_entry_set_rdev(entry, 0); + + tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining); + + /* Grab GNU-specific fields. */ + t = tar_atol(header->atime, sizeof(header->atime)); + if (t > 0) + archive_entry_set_atime(entry, t, 0); + t = tar_atol(header->ctime, sizeof(header->ctime)); + if (t > 0) + archive_entry_set_ctime(entry, t, 0); + + if (header->realsize[0] != 0) { + tar->realsize + = tar_atol(header->realsize, sizeof(header->realsize)); + archive_entry_set_size(entry, tar->realsize); + tar->realsize_override = 1; + } + + if (header->sparse[0].offset[0] != 0) { + if (gnu_sparse_old_read(a, tar, header, unconsumed) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } else { + if (header->isextended[0] != 0) { + /* XXX WTF? XXX */ + } + } + + return (err); +} + +static int +gnu_add_sparse_entry(struct archive_read *a, struct tar *tar, + int64_t offset, int64_t remaining) +{ + struct sparse_block *p; + + p = (struct sparse_block *)calloc(1, sizeof(*p)); + if (p == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + if (tar->sparse_last != NULL) + tar->sparse_last->next = p; + else + tar->sparse_list = p; + tar->sparse_last = p; + if (remaining < 0 || offset < 0 || offset > INT64_MAX - remaining) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Malformed sparse map data"); + return (ARCHIVE_FATAL); + } + p->offset = offset; + p->remaining = remaining; + return (ARCHIVE_OK); +} + +static void +gnu_clear_sparse_list(struct tar *tar) +{ + struct sparse_block *p; + + while (tar->sparse_list != NULL) { + p = tar->sparse_list; + tar->sparse_list = p->next; + free(p); + } + tar->sparse_last = NULL; +} + +/* + * GNU tar old-format sparse data. + * + * GNU old-format sparse data is stored in a fixed-field + * format. Offset/size values are 11-byte octal fields (same + * format as 'size' field in ustart header). These are + * stored in the header, allocating subsequent header blocks + * as needed. Extending the header in this way is a pretty + * severe POSIX violation; this design has earned GNU tar a + * lot of criticism. + */ + +static int +gnu_sparse_old_read(struct archive_read *a, struct tar *tar, + const struct archive_entry_header_gnutar *header, size_t *unconsumed) +{ + ssize_t bytes_read; + const void *data; + struct extended { + struct gnu_sparse sparse[21]; + char isextended[1]; + char padding[7]; + }; + const struct extended *ext; + + if (gnu_sparse_old_parse(a, tar, header->sparse, 4) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + if (header->isextended[0] == 0) + return (ARCHIVE_OK); + + do { + tar_flush_unconsumed(a, unconsumed); + data = __archive_read_ahead(a, 512, &bytes_read); + if (bytes_read < 0) + return (ARCHIVE_FATAL); + if (bytes_read < 512) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated tar archive " + "detected while reading sparse file data"); + return (ARCHIVE_FATAL); + } + *unconsumed = 512; + ext = (const struct extended *)data; + if (gnu_sparse_old_parse(a, tar, ext->sparse, 21) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } while (ext->isextended[0] != 0); + if (tar->sparse_list != NULL) + tar->entry_offset = tar->sparse_list->offset; + return (ARCHIVE_OK); +} + +static int +gnu_sparse_old_parse(struct archive_read *a, struct tar *tar, + const struct gnu_sparse *sparse, int length) +{ + while (length > 0 && sparse->offset[0] != 0) { + if (gnu_add_sparse_entry(a, tar, + tar_atol(sparse->offset, sizeof(sparse->offset)), + tar_atol(sparse->numbytes, sizeof(sparse->numbytes))) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + sparse++; + length--; + } + return (ARCHIVE_OK); +} + +/* + * GNU tar sparse format 0.0 + * + * Beginning with GNU tar 1.15, sparse files are stored using + * information in the pax extended header. The GNU tar maintainers + * have gone through a number of variations in the process of working + * out this scheme; fortunately, they're all numbered. + * + * Sparse format 0.0 uses attribute GNU.sparse.numblocks to store the + * number of blocks, and GNU.sparse.offset/GNU.sparse.numbytes to + * store offset/size for each block. The repeated instances of these + * latter fields violate the pax specification (which frowns on + * duplicate keys), so this format was quickly replaced. + */ + +/* + * GNU tar sparse format 0.1 + * + * This version replaced the offset/numbytes attributes with + * a single "map" attribute that stored a list of integers. This + * format had two problems: First, the "map" attribute could be very + * long, which caused problems for some implementations. More + * importantly, the sparse data was lost when extracted by archivers + * that didn't recognize this extension. + */ + +static int +gnu_sparse_01_parse(struct archive_read *a, struct tar *tar, const char *p) +{ + const char *e; + int64_t offset = -1, size = -1; + + for (;;) { + e = p; + while (*e != '\0' && *e != ',') { + if (*e < '0' || *e > '9') + return (ARCHIVE_WARN); + e++; + } + if (offset < 0) { + offset = tar_atol10(p, e - p); + if (offset < 0) + return (ARCHIVE_WARN); + } else { + size = tar_atol10(p, e - p); + if (size < 0) + return (ARCHIVE_WARN); + if (gnu_add_sparse_entry(a, tar, offset, size) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + offset = -1; + } + if (*e == '\0') + return (ARCHIVE_OK); + p = e + 1; + } +} + +/* + * GNU tar sparse format 1.0 + * + * The idea: The offset/size data is stored as a series of base-10 + * ASCII numbers prepended to the file data, so that dearchivers that + * don't support this format will extract the block map along with the + * data and a separate post-process can restore the sparseness. + * + * Unfortunately, GNU tar 1.16 had a bug that added unnecessary + * padding to the body of the file when using this format. GNU tar + * 1.17 corrected this bug without bumping the version number, so + * it's not possible to support both variants. This code supports + * the later variant at the expense of not supporting the former. + * + * This variant also replaced GNU.sparse.size with GNU.sparse.realsize + * and introduced the GNU.sparse.major/GNU.sparse.minor attributes. + */ + +/* + * Read the next line from the input, and parse it as a decimal + * integer followed by '\n'. Returns positive integer value or + * negative on error. + */ +static int64_t +gnu_sparse_10_atol(struct archive_read *a, struct tar *tar, + int64_t *remaining, size_t *unconsumed) +{ + int64_t l, limit, last_digit_limit; + const char *p; + ssize_t bytes_read; + int base, digit; + + base = 10; + limit = INT64_MAX / base; + last_digit_limit = INT64_MAX % base; + + /* + * Skip any lines starting with '#'; GNU tar specs + * don't require this, but they should. + */ + do { + bytes_read = readline(a, tar, &p, + (ssize_t)tar_min(*remaining, 100), unconsumed); + if (bytes_read <= 0) + return (ARCHIVE_FATAL); + *remaining -= bytes_read; + } while (p[0] == '#'); + + l = 0; + while (bytes_read > 0) { + if (*p == '\n') + return (l); + if (*p < '0' || *p >= '0' + base) + return (ARCHIVE_WARN); + digit = *p - '0'; + if (l > limit || (l == limit && digit > last_digit_limit)) + l = INT64_MAX; /* Truncate on overflow. */ + else + l = (l * base) + digit; + p++; + bytes_read--; + } + /* TODO: Error message. */ + return (ARCHIVE_WARN); +} + +/* + * Returns length (in bytes) of the sparse data description + * that was read. + */ +static ssize_t +gnu_sparse_10_read(struct archive_read *a, struct tar *tar, size_t *unconsumed) +{ + ssize_t bytes_read; + int entries; + int64_t offset, size, to_skip, remaining; + + /* Clear out the existing sparse list. */ + gnu_clear_sparse_list(tar); + + remaining = tar->entry_bytes_remaining; + + /* Parse entries. */ + entries = (int)gnu_sparse_10_atol(a, tar, &remaining, unconsumed); + if (entries < 0) + return (ARCHIVE_FATAL); + /* Parse the individual entries. */ + while (entries-- > 0) { + /* Parse offset/size */ + offset = gnu_sparse_10_atol(a, tar, &remaining, unconsumed); + if (offset < 0) + return (ARCHIVE_FATAL); + size = gnu_sparse_10_atol(a, tar, &remaining, unconsumed); + if (size < 0) + return (ARCHIVE_FATAL); + /* Add a new sparse entry. */ + if (gnu_add_sparse_entry(a, tar, offset, size) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + /* Skip rest of block... */ + tar_flush_unconsumed(a, unconsumed); + bytes_read = (ssize_t)(tar->entry_bytes_remaining - remaining); + to_skip = 0x1ff & -bytes_read; + /* Fail if tar->entry_bytes_remaing would get negative */ + if (to_skip > remaining) + return (ARCHIVE_FATAL); + if (to_skip != __archive_read_consume(a, to_skip)) + return (ARCHIVE_FATAL); + return ((ssize_t)(bytes_read + to_skip)); +} + +/* + * Solaris pax extension for a sparse file. This is recorded with the + * data and hole pairs. The way recording sparse information by Solaris' + * pax simply indicates where data and sparse are, so the stored contents + * consist of both data and hole. + */ +static int +solaris_sparse_parse(struct archive_read *a, struct tar *tar, + struct archive_entry *entry, const char *p) +{ + const char *e; + int64_t start, end; + int hole = 1; + + (void)entry; /* UNUSED */ + + end = 0; + if (*p == ' ') + p++; + else + return (ARCHIVE_WARN); + for (;;) { + e = p; + while (*e != '\0' && *e != ' ') { + if (*e < '0' || *e > '9') + return (ARCHIVE_WARN); + e++; + } + start = end; + end = tar_atol10(p, e - p); + if (end < 0) + return (ARCHIVE_WARN); + if (start < end) { + if (gnu_add_sparse_entry(a, tar, start, + end - start) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + tar->sparse_last->hole = hole; + } + if (*e == '\0') + return (ARCHIVE_OK); + p = e + 1; + hole = hole == 0; + } +} + +/*- + * Convert text->integer. + * + * Traditional tar formats (including POSIX) specify base-8 for + * all of the standard numeric fields. This is a significant limitation + * in practice: + * = file size is limited to 8GB + * = rdevmajor and rdevminor are limited to 21 bits + * = uid/gid are limited to 21 bits + * + * There are two workarounds for this: + * = pax extended headers, which use variable-length string fields + * = GNU tar and STAR both allow either base-8 or base-256 in + * most fields. The high bit is set to indicate base-256. + * + * On read, this implementation supports both extensions. + */ +static int64_t +tar_atol(const char *p, size_t char_cnt) +{ + /* + * Technically, GNU tar considers a field to be in base-256 + * only if the first byte is 0xff or 0x80. + */ + if (*p & 0x80) + return (tar_atol256(p, char_cnt)); + return (tar_atol8(p, char_cnt)); +} + +/* + * Note that this implementation does not (and should not!) obey + * locale settings; you cannot simply substitute strtol here, since + * it does obey locale. + */ +static int64_t +tar_atol_base_n(const char *p, size_t char_cnt, int base) +{ + int64_t l, maxval, limit, last_digit_limit; + int digit, sign; + + maxval = INT64_MAX; + limit = INT64_MAX / base; + last_digit_limit = INT64_MAX % base; + + /* the pointer will not be dereferenced if char_cnt is zero + * due to the way the && operator is evaluated. + */ + while (char_cnt != 0 && (*p == ' ' || *p == '\t')) { + p++; + char_cnt--; + } + + sign = 1; + if (char_cnt != 0 && *p == '-') { + sign = -1; + p++; + char_cnt--; + + maxval = INT64_MIN; + limit = -(INT64_MIN / base); + last_digit_limit = INT64_MIN % base; + } + + l = 0; + if (char_cnt != 0) { + digit = *p - '0'; + while (digit >= 0 && digit < base && char_cnt != 0) { + if (l>limit || (l == limit && digit > last_digit_limit)) { + return maxval; /* Truncate on overflow. */ + } + l = (l * base) + digit; + digit = *++p - '0'; + char_cnt--; + } + } + return (sign < 0) ? -l : l; +} + +static int64_t +tar_atol8(const char *p, size_t char_cnt) +{ + return tar_atol_base_n(p, char_cnt, 8); +} + +static int64_t +tar_atol10(const char *p, size_t char_cnt) +{ + return tar_atol_base_n(p, char_cnt, 10); +} + +/* + * Parse a base-256 integer. This is just a variable-length + * twos-complement signed binary value in big-endian order, except + * that the high-order bit is ignored. The values here can be up to + * 12 bytes, so we need to be careful about overflowing 64-bit + * (8-byte) integers. + * + * This code unashamedly assumes that the local machine uses 8-bit + * bytes and twos-complement arithmetic. + */ +static int64_t +tar_atol256(const char *_p, size_t char_cnt) +{ + uint64_t l; + const unsigned char *p = (const unsigned char *)_p; + unsigned char c, neg; + + /* Extend 7-bit 2s-comp to 8-bit 2s-comp, decide sign. */ + c = *p; + if (c & 0x40) { + neg = 0xff; + c |= 0x80; + l = ~ARCHIVE_LITERAL_ULL(0); + } else { + neg = 0; + c &= 0x7f; + l = 0; + } + + /* If more than 8 bytes, check that we can ignore + * high-order bits without overflow. */ + while (char_cnt > sizeof(int64_t)) { + --char_cnt; + if (c != neg) + return neg ? INT64_MIN : INT64_MAX; + c = *++p; + } + + /* c is first byte that fits; if sign mismatch, return overflow */ + if ((c ^ neg) & 0x80) { + return neg ? INT64_MIN : INT64_MAX; + } + + /* Accumulate remaining bytes. */ + while (--char_cnt > 0) { + l = (l << 8) | c; + c = *++p; + } + l = (l << 8) | c; + /* Return signed twos-complement value. */ + return (int64_t)(l); +} + +/* + * Returns length of line (including trailing newline) + * or negative on error. 'start' argument is updated to + * point to first character of line. This avoids copying + * when possible. + */ +static ssize_t +readline(struct archive_read *a, struct tar *tar, const char **start, + ssize_t limit, size_t *unconsumed) +{ + ssize_t bytes_read; + ssize_t total_size = 0; + const void *t; + const char *s; + void *p; + + tar_flush_unconsumed(a, unconsumed); + + t = __archive_read_ahead(a, 1, &bytes_read); + if (bytes_read <= 0) + return (ARCHIVE_FATAL); + s = t; /* Start of line? */ + p = memchr(t, '\n', bytes_read); + /* If we found '\n' in the read buffer, return pointer to that. */ + if (p != NULL) { + bytes_read = 1 + ((const char *)p) - s; + if (bytes_read > limit) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Line too long"); + return (ARCHIVE_FATAL); + } + *unconsumed = bytes_read; + *start = s; + return (bytes_read); + } + *unconsumed = bytes_read; + /* Otherwise, we need to accumulate in a line buffer. */ + for (;;) { + if (total_size + bytes_read > limit) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Line too long"); + return (ARCHIVE_FATAL); + } + if (archive_string_ensure(&tar->line, total_size + bytes_read) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate working buffer"); + return (ARCHIVE_FATAL); + } + memcpy(tar->line.s + total_size, t, bytes_read); + tar_flush_unconsumed(a, unconsumed); + total_size += bytes_read; + /* If we found '\n', clean up and return. */ + if (p != NULL) { + *start = tar->line.s; + return (total_size); + } + /* Read some more. */ + t = __archive_read_ahead(a, 1, &bytes_read); + if (bytes_read <= 0) + return (ARCHIVE_FATAL); + s = t; /* Start of line? */ + p = memchr(t, '\n', bytes_read); + /* If we found '\n', trim the read. */ + if (p != NULL) { + bytes_read = 1 + ((const char *)p) - s; + } + *unconsumed = bytes_read; + } +} + +/* + * base64_decode - Base64 decode + * + * This accepts most variations of base-64 encoding, including: + * * with or without line breaks + * * with or without the final group padded with '=' or '_' characters + * (The most economical Base-64 variant does not pad the last group and + * omits line breaks; RFC1341 used for MIME requires both.) + */ +static char * +base64_decode(const char *s, size_t len, size_t *out_len) +{ + static const unsigned char digits[64] = { + 'A','B','C','D','E','F','G','H','I','J','K','L','M','N', + 'O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b', + 'c','d','e','f','g','h','i','j','k','l','m','n','o','p', + 'q','r','s','t','u','v','w','x','y','z','0','1','2','3', + '4','5','6','7','8','9','+','/' }; + static unsigned char decode_table[128]; + char *out, *d; + const unsigned char *src = (const unsigned char *)s; + + /* If the decode table is not yet initialized, prepare it. */ + if (decode_table[digits[1]] != 1) { + unsigned i; + memset(decode_table, 0xff, sizeof(decode_table)); + for (i = 0; i < sizeof(digits); i++) + decode_table[digits[i]] = i; + } + + /* Allocate enough space to hold the entire output. */ + /* Note that we may not use all of this... */ + out = (char *)malloc(len - len / 4 + 1); + if (out == NULL) { + *out_len = 0; + return (NULL); + } + d = out; + + while (len > 0) { + /* Collect the next group of (up to) four characters. */ + int v = 0; + int group_size = 0; + while (group_size < 4 && len > 0) { + /* '=' or '_' padding indicates final group. */ + if (*src == '=' || *src == '_') { + len = 0; + break; + } + /* Skip illegal characters (including line breaks) */ + if (*src > 127 || *src < 32 + || decode_table[*src] == 0xff) { + len--; + src++; + continue; + } + v <<= 6; + v |= decode_table[*src++]; + len --; + group_size++; + } + /* Align a short group properly. */ + v <<= 6 * (4 - group_size); + /* Unpack the group we just collected. */ + switch (group_size) { + case 4: d[2] = v & 0xff; + /* FALLTHROUGH */ + case 3: d[1] = (v >> 8) & 0xff; + /* FALLTHROUGH */ + case 2: d[0] = (v >> 16) & 0xff; + break; + case 1: /* this is invalid! */ + break; + } + d += group_size * 3 / 4; + } + + *out_len = d - out; + return (out); +} + +static char * +url_decode(const char *in) +{ + char *out, *d; + const char *s; + + out = (char *)malloc(strlen(in) + 1); + if (out == NULL) + return (NULL); + for (s = in, d = out; *s != '\0'; ) { + if (s[0] == '%' && s[1] != '\0' && s[2] != '\0') { + /* Try to convert % escape */ + int digit1 = tohex(s[1]); + int digit2 = tohex(s[2]); + if (digit1 >= 0 && digit2 >= 0) { + /* Looks good, consume three chars */ + s += 3; + /* Convert output */ + *d++ = ((digit1 << 4) | digit2); + continue; + } + /* Else fall through and treat '%' as normal char */ + } + *d++ = *s++; + } + *d = '\0'; + return (out); +} + +static int +tohex(int c) +{ + if (c >= '0' && c <= '9') + return (c - '0'); + else if (c >= 'A' && c <= 'F') + return (c - 'A' + 10); + else if (c >= 'a' && c <= 'f') + return (c - 'a' + 10); + else + return (-1); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_warc.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_warc.c new file mode 100644 index 0000000000..72977b8e07 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_warc.c @@ -0,0 +1,832 @@ +/*- + * Copyright (c) 2014 Sebastian Freundt + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +/** + * WARC is standardised by ISO TC46/SC4/WG12 and currently available as + * ISO 28500:2009. + * For the purposes of this file we used the final draft from: + * http://bibnum.bnf.fr/warc/WARC_ISO_28500_version1_latestdraft.pdf + * + * Todo: + * [ ] real-world warcs can contain resources at endpoints ending in / + * e.g. http://bibnum.bnf.fr/warc/ + * if you're lucky their response contains a Content-Location: header + * pointing to a unix-compliant filename, in the example above it's + * Content-Location: http://bibnum.bnf.fr/warc/index.html + * however, that's not mandated and github for example doesn't follow + * this convention. + * We need a set of archive options to control what to do with + * entries like these, at the moment care is taken to skip them. + * + **/ + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#ifdef HAVE_CTYPE_H +#include <ctype.h> +#endif +#ifdef HAVE_TIME_H +#include <time.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_read_private.h" + +typedef enum { + WT_NONE, + /* warcinfo */ + WT_INFO, + /* metadata */ + WT_META, + /* resource */ + WT_RSRC, + /* request, unsupported */ + WT_REQ, + /* response, unsupported */ + WT_RSP, + /* revisit, unsupported */ + WT_RVIS, + /* conversion, unsupported */ + WT_CONV, + /* continuation, unsupported at the moment */ + WT_CONT, + /* invalid type */ + LAST_WT +} warc_type_t; + +typedef struct { + size_t len; + const char *str; +} warc_string_t; + +typedef struct { + size_t len; + char *str; +} warc_strbuf_t; + +struct warc_s { + /* content length ahead */ + size_t cntlen; + /* and how much we've processed so far */ + size_t cntoff; + /* and how much we need to consume between calls */ + size_t unconsumed; + + /* string pool */ + warc_strbuf_t pool; + /* previous version */ + unsigned int pver; + /* stringified format name */ + struct archive_string sver; +}; + +static int _warc_bid(struct archive_read *a, int); +static int _warc_cleanup(struct archive_read *a); +static int _warc_read(struct archive_read*, const void**, size_t*, int64_t*); +static int _warc_skip(struct archive_read *a); +static int _warc_rdhdr(struct archive_read *a, struct archive_entry *e); + +/* private routines */ +static unsigned int _warc_rdver(const char buf[10], size_t bsz); +static unsigned int _warc_rdtyp(const char *buf, size_t bsz); +static warc_string_t _warc_rduri(const char *buf, size_t bsz); +static ssize_t _warc_rdlen(const char *buf, size_t bsz); +static time_t _warc_rdrtm(const char *buf, size_t bsz); +static time_t _warc_rdmtm(const char *buf, size_t bsz); +static const char *_warc_find_eoh(const char *buf, size_t bsz); +static const char *_warc_find_eol(const char *buf, size_t bsz); + +int +archive_read_support_format_warc(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct warc_s *w; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_warc"); + + if ((w = calloc(1, sizeof(*w))) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate warc data"); + return (ARCHIVE_FATAL); + } + + r = __archive_read_register_format( + a, w, "warc", + _warc_bid, NULL, _warc_rdhdr, _warc_read, + _warc_skip, NULL, _warc_cleanup, NULL, NULL); + + if (r != ARCHIVE_OK) { + free(w); + return (r); + } + return (ARCHIVE_OK); +} + +static int +_warc_cleanup(struct archive_read *a) +{ + struct warc_s *w = a->format->data; + + if (w->pool.len > 0U) { + free(w->pool.str); + } + archive_string_free(&w->sver); + free(w); + a->format->data = NULL; + return (ARCHIVE_OK); +} + +static int +_warc_bid(struct archive_read *a, int best_bid) +{ + const char *hdr; + ssize_t nrd; + unsigned int ver; + + (void)best_bid; /* UNUSED */ + + /* check first line of file, it should be a record already */ + if ((hdr = __archive_read_ahead(a, 12U, &nrd)) == NULL) { + /* no idea what to do */ + return -1; + } else if (nrd < 12) { + /* nah, not for us, our magic cookie is at least 12 bytes */ + return -1; + } + + /* otherwise snarf the record's version number */ + ver = _warc_rdver(hdr, nrd); + if (ver < 1200U || ver > 10000U) { + /* we only support WARC 0.12 to 1.0 */ + return -1; + } + + /* otherwise be confident */ + return (64); +} + +static int +_warc_rdhdr(struct archive_read *a, struct archive_entry *entry) +{ +#define HDR_PROBE_LEN (12U) + struct warc_s *w = a->format->data; + unsigned int ver; + const char *buf; + ssize_t nrd; + const char *eoh; + /* for the file name, saves some strndup()'ing */ + warc_string_t fnam; + /* warc record type, not that we really use it a lot */ + warc_type_t ftyp; + /* content-length+error monad */ + ssize_t cntlen; + /* record time is the WARC-Date time we reinterpret it as ctime */ + time_t rtime; + /* mtime is the Last-Modified time which will be the entry's mtime */ + time_t mtime; + +start_over: + /* just use read_ahead() they keep track of unconsumed + * bits and bobs for us; no need to put an extra shift in + * and reproduce that functionality here */ + buf = __archive_read_ahead(a, HDR_PROBE_LEN, &nrd); + + if (nrd < 0) { + /* no good */ + archive_set_error( + &a->archive, ARCHIVE_ERRNO_MISC, + "Bad record header"); + return (ARCHIVE_FATAL); + } else if (buf == NULL) { + /* there should be room for at least WARC/bla\r\n + * must be EOF therefore */ + return (ARCHIVE_EOF); + } + /* looks good so far, try and find the end of the header now */ + eoh = _warc_find_eoh(buf, nrd); + if (eoh == NULL) { + /* still no good, the header end might be beyond the + * probe we've requested, but then again who'd cram + * so much stuff into the header *and* be 28500-compliant */ + archive_set_error( + &a->archive, ARCHIVE_ERRNO_MISC, + "Bad record header"); + return (ARCHIVE_FATAL); + } + ver = _warc_rdver(buf, eoh - buf); + /* we currently support WARC 0.12 to 1.0 */ + if (ver == 0U) { + archive_set_error( + &a->archive, ARCHIVE_ERRNO_MISC, + "Invalid record version"); + return (ARCHIVE_FATAL); + } else if (ver < 1200U || ver > 10000U) { + archive_set_error( + &a->archive, ARCHIVE_ERRNO_MISC, + "Unsupported record version: %u.%u", + ver / 10000, (ver % 10000) / 100); + return (ARCHIVE_FATAL); + } + cntlen = _warc_rdlen(buf, eoh - buf); + if (cntlen < 0) { + /* nightmare! the specs say content-length is mandatory + * so I don't feel overly bad stopping the reader here */ + archive_set_error( + &a->archive, EINVAL, + "Bad content length"); + return (ARCHIVE_FATAL); + } + rtime = _warc_rdrtm(buf, eoh - buf); + if (rtime == (time_t)-1) { + /* record time is mandatory as per WARC/1.0, + * so just barf here, fast and loud */ + archive_set_error( + &a->archive, EINVAL, + "Bad record time"); + return (ARCHIVE_FATAL); + } + + /* let the world know we're a WARC archive */ + a->archive.archive_format = ARCHIVE_FORMAT_WARC; + if (ver != w->pver) { + /* stringify this entry's version */ + archive_string_sprintf(&w->sver, + "WARC/%u.%u", ver / 10000, (ver % 10000) / 100); + /* remember the version */ + w->pver = ver; + } + /* start off with the type */ + ftyp = _warc_rdtyp(buf, eoh - buf); + /* and let future calls know about the content */ + w->cntlen = cntlen; + w->cntoff = 0U; + mtime = 0;/* Avoid compiling error on some platform. */ + + switch (ftyp) { + case WT_RSRC: + case WT_RSP: + /* only try and read the filename in the cases that are + * guaranteed to have one */ + fnam = _warc_rduri(buf, eoh - buf); + /* check the last character in the URI to avoid creating + * directory endpoints as files, see Todo above */ + if (fnam.len == 0 || fnam.str[fnam.len - 1] == '/') { + /* break here for now */ + fnam.len = 0U; + fnam.str = NULL; + break; + } + /* bang to our string pool, so we save a + * malloc()+free() roundtrip */ + if (fnam.len + 1U > w->pool.len) { + w->pool.len = ((fnam.len + 64U) / 64U) * 64U; + w->pool.str = realloc(w->pool.str, w->pool.len); + } + memcpy(w->pool.str, fnam.str, fnam.len); + w->pool.str[fnam.len] = '\0'; + /* let no one else know about the pool, it's a secret, shhh */ + fnam.str = w->pool.str; + + /* snarf mtime or deduce from rtime + * this is a custom header added by our writer, it's quite + * hard to believe anyone else would go through with it + * (apart from being part of some http responses of course) */ + if ((mtime = _warc_rdmtm(buf, eoh - buf)) == (time_t)-1) { + mtime = rtime; + } + break; + default: + fnam.len = 0U; + fnam.str = NULL; + break; + } + + /* now eat some of those delicious buffer bits */ + __archive_read_consume(a, eoh - buf); + + switch (ftyp) { + case WT_RSRC: + case WT_RSP: + if (fnam.len > 0U) { + /* populate entry object */ + archive_entry_set_filetype(entry, AE_IFREG); + archive_entry_copy_pathname(entry, fnam.str); + archive_entry_set_size(entry, cntlen); + archive_entry_set_perm(entry, 0644); + /* rtime is the new ctime, mtime stays mtime */ + archive_entry_set_ctime(entry, rtime, 0L); + archive_entry_set_mtime(entry, mtime, 0L); + break; + } + /* FALLTHROUGH */ + default: + /* consume the content and start over */ + _warc_skip(a); + goto start_over; + } + return (ARCHIVE_OK); +} + +static int +_warc_read(struct archive_read *a, const void **buf, size_t *bsz, int64_t *off) +{ + struct warc_s *w = a->format->data; + const char *rab; + ssize_t nrd; + + if (w->cntoff >= w->cntlen) { + eof: + /* it's our lucky day, no work, we can leave early */ + *buf = NULL; + *bsz = 0U; + *off = w->cntoff + 4U/*for \r\n\r\n separator*/; + w->unconsumed = 0U; + return (ARCHIVE_EOF); + } + + if (w->unconsumed) { + __archive_read_consume(a, w->unconsumed); + w->unconsumed = 0U; + } + + rab = __archive_read_ahead(a, 1U, &nrd); + if (nrd < 0) { + *bsz = 0U; + /* big catastrophe */ + return (int)nrd; + } else if (nrd == 0) { + goto eof; + } else if ((size_t)nrd > w->cntlen - w->cntoff) { + /* clamp to content-length */ + nrd = w->cntlen - w->cntoff; + } + *off = w->cntoff; + *bsz = nrd; + *buf = rab; + + w->cntoff += nrd; + w->unconsumed = (size_t)nrd; + return (ARCHIVE_OK); +} + +static int +_warc_skip(struct archive_read *a) +{ + struct warc_s *w = a->format->data; + + __archive_read_consume(a, w->cntlen + 4U/*\r\n\r\n separator*/); + w->cntlen = 0U; + w->cntoff = 0U; + return (ARCHIVE_OK); +} + + +/* private routines */ +static void* +deconst(const void *c) +{ + return (char *)0x1 + (((const char *)c) - (const char *)0x1); +} + +static char* +xmemmem(const char *hay, const size_t haysize, + const char *needle, const size_t needlesize) +{ + const char *const eoh = hay + haysize; + const char *const eon = needle + needlesize; + const char *hp; + const char *np; + const char *cand; + unsigned int hsum; + unsigned int nsum; + unsigned int eqp; + + /* trivial checks first + * a 0-sized needle is defined to be found anywhere in haystack + * then run strchr() to find a candidate in HAYSTACK (i.e. a portion + * that happens to begin with *NEEDLE) */ + if (needlesize == 0UL) { + return deconst(hay); + } else if ((hay = memchr(hay, *needle, haysize)) == NULL) { + /* trivial */ + return NULL; + } + + /* First characters of haystack and needle are the same now. Both are + * guaranteed to be at least one character long. Now computes the sum + * of characters values of needle together with the sum of the first + * needle_len characters of haystack. */ + for (hp = hay + 1U, np = needle + 1U, hsum = *hay, nsum = *hay, eqp = 1U; + hp < eoh && np < eon; + hsum ^= *hp, nsum ^= *np, eqp &= *hp == *np, hp++, np++); + + /* HP now references the (NEEDLESIZE + 1)-th character. */ + if (np < eon) { + /* haystack is smaller than needle, :O */ + return NULL; + } else if (eqp) { + /* found a match */ + return deconst(hay); + } + + /* now loop through the rest of haystack, + * updating the sum iteratively */ + for (cand = hay; hp < eoh; hp++) { + hsum ^= *cand++; + hsum ^= *hp; + + /* Since the sum of the characters is already known to be + * equal at that point, it is enough to check just NEEDLESIZE - 1 + * characters for equality, + * also CAND is by design < HP, so no need for range checks */ + if (hsum == nsum && memcmp(cand, needle, needlesize - 1U) == 0) { + return deconst(cand); + } + } + return NULL; +} + +static int +strtoi_lim(const char *str, const char **ep, int llim, int ulim) +{ + int res = 0; + const char *sp; + /* we keep track of the number of digits via rulim */ + int rulim; + + for (sp = str, rulim = ulim > 10 ? ulim : 10; + res * 10 <= ulim && rulim && *sp >= '0' && *sp <= '9'; + sp++, rulim /= 10) { + res *= 10; + res += *sp - '0'; + } + if (sp == str) { + res = -1; + } else if (res < llim || res > ulim) { + res = -2; + } + *ep = (const char*)sp; + return res; +} + +static time_t +time_from_tm(struct tm *t) +{ +#if HAVE_TIMEGM + /* Use platform timegm() if available. */ + return (timegm(t)); +#elif HAVE__MKGMTIME64 + return (_mkgmtime64(t)); +#else + /* Else use direct calculation using POSIX assumptions. */ + /* First, fix up tm_yday based on the year/month/day. */ + if (mktime(t) == (time_t)-1) + return ((time_t)-1); + /* Then we can compute timegm() from first principles. */ + return (t->tm_sec + + t->tm_min * 60 + + t->tm_hour * 3600 + + t->tm_yday * 86400 + + (t->tm_year - 70) * 31536000 + + ((t->tm_year - 69) / 4) * 86400 + - ((t->tm_year - 1) / 100) * 86400 + + ((t->tm_year + 299) / 400) * 86400); +#endif +} + +static time_t +xstrpisotime(const char *s, char **endptr) +{ +/** like strptime() but strictly for ISO 8601 Zulu strings */ + struct tm tm; + time_t res = (time_t)-1; + + /* make sure tm is clean */ + memset(&tm, 0, sizeof(tm)); + + /* as a courtesy to our callers, and since this is a non-standard + * routine, we skip leading whitespace */ + while (*s == ' ' || *s == '\t') + ++s; + + /* read year */ + if ((tm.tm_year = strtoi_lim(s, &s, 1583, 4095)) < 0 || *s++ != '-') { + goto out; + } + /* read month */ + if ((tm.tm_mon = strtoi_lim(s, &s, 1, 12)) < 0 || *s++ != '-') { + goto out; + } + /* read day-of-month */ + if ((tm.tm_mday = strtoi_lim(s, &s, 1, 31)) < 0 || *s++ != 'T') { + goto out; + } + /* read hour */ + if ((tm.tm_hour = strtoi_lim(s, &s, 0, 23)) < 0 || *s++ != ':') { + goto out; + } + /* read minute */ + if ((tm.tm_min = strtoi_lim(s, &s, 0, 59)) < 0 || *s++ != ':') { + goto out; + } + /* read second */ + if ((tm.tm_sec = strtoi_lim(s, &s, 0, 60)) < 0 || *s++ != 'Z') { + goto out; + } + + /* massage TM to fulfill some of POSIX' constraints */ + tm.tm_year -= 1900; + tm.tm_mon--; + + /* now convert our custom tm struct to a unix stamp using UTC */ + res = time_from_tm(&tm); + +out: + if (endptr != NULL) { + *endptr = deconst(s); + } + return res; +} + +static unsigned int +_warc_rdver(const char *buf, size_t bsz) +{ + static const char magic[] = "WARC/"; + const char *c; + unsigned int ver = 0U; + unsigned int end = 0U; + + if (bsz < 12 || memcmp(buf, magic, sizeof(magic) - 1U) != 0) { + /* buffer too small or invalid magic */ + return ver; + } + /* looks good so far, read the version number for a laugh */ + buf += sizeof(magic) - 1U; + + if (isdigit((unsigned char)buf[0U]) && (buf[1U] == '.') && + isdigit((unsigned char)buf[2U])) { + /* we support a maximum of 2 digits in the minor version */ + if (isdigit((unsigned char)buf[3U])) + end = 1U; + /* set up major version */ + ver = (buf[0U] - '0') * 10000U; + /* set up minor version */ + if (end == 1U) { + ver += (buf[2U] - '0') * 1000U; + ver += (buf[3U] - '0') * 100U; + } else + ver += (buf[2U] - '0') * 100U; + /* + * WARC below version 0.12 has a space-separated header + * WARC 0.12 and above terminates the version with a CRLF + */ + c = buf + 3U + end; + if (ver >= 1200U) { + if (memcmp(c, "\r\n", 2U) != 0) + ver = 0U; + } else { + /* ver < 1200U */ + if (*c != ' ' && *c != '\t') + ver = 0U; + } + } + return ver; +} + +static unsigned int +_warc_rdtyp(const char *buf, size_t bsz) +{ + static const char _key[] = "\r\nWARC-Type:"; + const char *val, *eol; + + if ((val = xmemmem(buf, bsz, _key, sizeof(_key) - 1U)) == NULL) { + /* no bother */ + return WT_NONE; + } + val += sizeof(_key) - 1U; + if ((eol = _warc_find_eol(val, buf + bsz - val)) == NULL) { + /* no end of line */ + return WT_NONE; + } + + /* overread whitespace */ + while (val < eol && (*val == ' ' || *val == '\t')) + ++val; + + if (val + 8U == eol) { + if (memcmp(val, "resource", 8U) == 0) + return WT_RSRC; + else if (memcmp(val, "response", 8U) == 0) + return WT_RSP; + } + return WT_NONE; +} + +static warc_string_t +_warc_rduri(const char *buf, size_t bsz) +{ + static const char _key[] = "\r\nWARC-Target-URI:"; + const char *val, *uri, *eol, *p; + warc_string_t res = {0U, NULL}; + + if ((val = xmemmem(buf, bsz, _key, sizeof(_key) - 1U)) == NULL) { + /* no bother */ + return res; + } + /* overread whitespace */ + val += sizeof(_key) - 1U; + if ((eol = _warc_find_eol(val, buf + bsz - val)) == NULL) { + /* no end of line */ + return res; + } + + while (val < eol && (*val == ' ' || *val == '\t')) + ++val; + + /* overread URL designators */ + if ((uri = xmemmem(val, eol - val, "://", 3U)) == NULL) { + /* not touching that! */ + return res; + } + + /* spaces inside uri are not allowed, CRLF should follow */ + for (p = val; p < eol; p++) { + if (isspace((unsigned char)*p)) + return res; + } + + /* there must be at least space for ftp */ + if (uri < (val + 3U)) + return res; + + /* move uri to point to after :// */ + uri += 3U; + + /* now then, inspect the URI */ + if (memcmp(val, "file", 4U) == 0) { + /* perfect, nothing left to do here */ + + } else if (memcmp(val, "http", 4U) == 0 || + memcmp(val, "ftp", 3U) == 0) { + /* overread domain, and the first / */ + while (uri < eol && *uri++ != '/'); + } else { + /* not sure what to do? best to bugger off */ + return res; + } + res.str = uri; + res.len = eol - uri; + return res; +} + +static ssize_t +_warc_rdlen(const char *buf, size_t bsz) +{ + static const char _key[] = "\r\nContent-Length:"; + const char *val, *eol; + char *on = NULL; + long int len; + + if ((val = xmemmem(buf, bsz, _key, sizeof(_key) - 1U)) == NULL) { + /* no bother */ + return -1; + } + val += sizeof(_key) - 1U; + if ((eol = _warc_find_eol(val, buf + bsz - val)) == NULL) { + /* no end of line */ + return -1; + } + + /* skip leading whitespace */ + while (val < eol && (*val == ' ' || *val == '\t')) + val++; + /* there must be at least one digit */ + if (!isdigit((unsigned char)*val)) + return -1; + errno = 0; + len = strtol(val, &on, 10); + if (errno != 0 || on != eol) { + /* line must end here */ + return -1; + } + + return (size_t)len; +} + +static time_t +_warc_rdrtm(const char *buf, size_t bsz) +{ + static const char _key[] = "\r\nWARC-Date:"; + const char *val, *eol; + char *on = NULL; + time_t res; + + if ((val = xmemmem(buf, bsz, _key, sizeof(_key) - 1U)) == NULL) { + /* no bother */ + return (time_t)-1; + } + val += sizeof(_key) - 1U; + if ((eol = _warc_find_eol(val, buf + bsz - val)) == NULL ) { + /* no end of line */ + return -1; + } + + /* xstrpisotime() kindly overreads whitespace for us, so use that */ + res = xstrpisotime(val, &on); + if (on != eol) { + /* line must end here */ + return -1; + } + return res; +} + +static time_t +_warc_rdmtm(const char *buf, size_t bsz) +{ + static const char _key[] = "\r\nLast-Modified:"; + const char *val, *eol; + char *on = NULL; + time_t res; + + if ((val = xmemmem(buf, bsz, _key, sizeof(_key) - 1U)) == NULL) { + /* no bother */ + return (time_t)-1; + } + val += sizeof(_key) - 1U; + if ((eol = _warc_find_eol(val, buf + bsz - val)) == NULL ) { + /* no end of line */ + return -1; + } + + /* xstrpisotime() kindly overreads whitespace for us, so use that */ + res = xstrpisotime(val, &on); + if (on != eol) { + /* line must end here */ + return -1; + } + return res; +} + +static const char* +_warc_find_eoh(const char *buf, size_t bsz) +{ + static const char _marker[] = "\r\n\r\n"; + const char *hit = xmemmem(buf, bsz, _marker, sizeof(_marker) - 1U); + + if (hit != NULL) { + hit += sizeof(_marker) - 1U; + } + return hit; +} + +static const char* +_warc_find_eol(const char *buf, size_t bsz) +{ + static const char _marker[] = "\r\n"; + const char *hit = xmemmem(buf, bsz, _marker, sizeof(_marker) - 1U); + + return hit; +} +/* archive_read_support_format_warc.c ends here */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_xar.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_xar.c new file mode 100644 index 0000000000..503ff58b91 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_xar.c @@ -0,0 +1,3328 @@ +/*- + * Copyright (c) 2009 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#if HAVE_LIBXML_XMLREADER_H +#include <libxml/xmlreader.h> +#elif HAVE_BSDXML_H +#include <bsdxml.h> +#elif HAVE_EXPAT_H +#include <expat.h> +#endif +#ifdef HAVE_BZLIB_H +#include <bzlib.h> +#endif +#if HAVE_LZMA_H +#include <lzma.h> +#endif +#ifdef HAVE_ZLIB_H +#include <zlib.h> +#endif + +#include "archive.h" +#include "archive_digest_private.h" +#include "archive_endian.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_read_private.h" + +#if (!defined(HAVE_LIBXML_XMLREADER_H) && \ + !defined(HAVE_BSDXML_H) && !defined(HAVE_EXPAT_H)) ||\ + !defined(HAVE_ZLIB_H) || \ + !defined(ARCHIVE_HAS_MD5) || !defined(ARCHIVE_HAS_SHA1) +/* + * xar needs several external libraries. + * o libxml2 or expat --- XML parser + * o openssl or MD5/SHA1 hash function + * o zlib + * o bzlib2 (option) + * o liblzma (option) + */ +int +archive_read_support_format_xar(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_xar"); + + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Xar not supported on this platform"); + return (ARCHIVE_WARN); +} + +#else /* Support xar format */ + +/* #define DEBUG 1 */ +/* #define DEBUG_PRINT_TOC 1 */ +#if DEBUG_PRINT_TOC +#define PRINT_TOC(d, outbytes) do { \ + unsigned char *x = (unsigned char *)(uintptr_t)d; \ + unsigned char c = x[outbytes-1]; \ + x[outbytes - 1] = 0; \ + fprintf(stderr, "%s", x); \ + fprintf(stderr, "%c", c); \ + x[outbytes - 1] = c; \ +} while (0) +#else +#define PRINT_TOC(d, outbytes) +#endif + +#define HEADER_MAGIC 0x78617221 +#define HEADER_SIZE 28 +#define HEADER_VERSION 1 +#define CKSUM_NONE 0 +#define CKSUM_SHA1 1 +#define CKSUM_MD5 2 + +#define MD5_SIZE 16 +#define SHA1_SIZE 20 +#define MAX_SUM_SIZE 20 + +enum enctype { + NONE, + GZIP, + BZIP2, + LZMA, + XZ, +}; + +struct chksumval { + int alg; + size_t len; + unsigned char val[MAX_SUM_SIZE]; +}; + +struct chksumwork { + int alg; +#ifdef ARCHIVE_HAS_MD5 + archive_md5_ctx md5ctx; +#endif +#ifdef ARCHIVE_HAS_SHA1 + archive_sha1_ctx sha1ctx; +#endif +}; + +struct xattr { + struct xattr *next; + struct archive_string name; + uint64_t id; + uint64_t length; + uint64_t offset; + uint64_t size; + enum enctype encoding; + struct chksumval a_sum; + struct chksumval e_sum; + struct archive_string fstype; +}; + +struct xar_file { + struct xar_file *next; + struct xar_file *hdnext; + struct xar_file *parent; + int subdirs; + + unsigned int has; +#define HAS_DATA 0x00001 +#define HAS_PATHNAME 0x00002 +#define HAS_SYMLINK 0x00004 +#define HAS_TIME 0x00008 +#define HAS_UID 0x00010 +#define HAS_GID 0x00020 +#define HAS_MODE 0x00040 +#define HAS_TYPE 0x00080 +#define HAS_DEV 0x00100 +#define HAS_DEVMAJOR 0x00200 +#define HAS_DEVMINOR 0x00400 +#define HAS_INO 0x00800 +#define HAS_FFLAGS 0x01000 +#define HAS_XATTR 0x02000 +#define HAS_ACL 0x04000 +#define HAS_CTIME 0x08000 +#define HAS_MTIME 0x10000 +#define HAS_ATIME 0x20000 + + uint64_t id; + uint64_t length; + uint64_t offset; + uint64_t size; + enum enctype encoding; + struct chksumval a_sum; + struct chksumval e_sum; + struct archive_string pathname; + struct archive_string symlink; + time_t ctime; + time_t mtime; + time_t atime; + struct archive_string uname; + int64_t uid; + struct archive_string gname; + int64_t gid; + mode_t mode; + dev_t dev; + dev_t devmajor; + dev_t devminor; + int64_t ino64; + struct archive_string fflags_text; + unsigned int link; + unsigned int nlink; + struct archive_string hardlink; + struct xattr *xattr_list; +}; + +struct hdlink { + struct hdlink *next; + + unsigned int id; + int cnt; + struct xar_file *files; +}; + +struct heap_queue { + struct xar_file **files; + int allocated; + int used; +}; + +enum xmlstatus { + INIT, + XAR, + TOC, + TOC_CREATION_TIME, + TOC_CHECKSUM, + TOC_CHECKSUM_OFFSET, + TOC_CHECKSUM_SIZE, + TOC_FILE, + FILE_DATA, + FILE_DATA_LENGTH, + FILE_DATA_OFFSET, + FILE_DATA_SIZE, + FILE_DATA_ENCODING, + FILE_DATA_A_CHECKSUM, + FILE_DATA_E_CHECKSUM, + FILE_DATA_CONTENT, + FILE_EA, + FILE_EA_LENGTH, + FILE_EA_OFFSET, + FILE_EA_SIZE, + FILE_EA_ENCODING, + FILE_EA_A_CHECKSUM, + FILE_EA_E_CHECKSUM, + FILE_EA_NAME, + FILE_EA_FSTYPE, + FILE_CTIME, + FILE_MTIME, + FILE_ATIME, + FILE_GROUP, + FILE_GID, + FILE_USER, + FILE_UID, + FILE_MODE, + FILE_DEVICE, + FILE_DEVICE_MAJOR, + FILE_DEVICE_MINOR, + FILE_DEVICENO, + FILE_INODE, + FILE_LINK, + FILE_TYPE, + FILE_NAME, + FILE_ACL, + FILE_ACL_DEFAULT, + FILE_ACL_ACCESS, + FILE_ACL_APPLEEXTENDED, + /* BSD file flags. */ + FILE_FLAGS, + FILE_FLAGS_USER_NODUMP, + FILE_FLAGS_USER_IMMUTABLE, + FILE_FLAGS_USER_APPEND, + FILE_FLAGS_USER_OPAQUE, + FILE_FLAGS_USER_NOUNLINK, + FILE_FLAGS_SYS_ARCHIVED, + FILE_FLAGS_SYS_IMMUTABLE, + FILE_FLAGS_SYS_APPEND, + FILE_FLAGS_SYS_NOUNLINK, + FILE_FLAGS_SYS_SNAPSHOT, + /* Linux file flags. */ + FILE_EXT2, + FILE_EXT2_SecureDeletion, + FILE_EXT2_Undelete, + FILE_EXT2_Compress, + FILE_EXT2_Synchronous, + FILE_EXT2_Immutable, + FILE_EXT2_AppendOnly, + FILE_EXT2_NoDump, + FILE_EXT2_NoAtime, + FILE_EXT2_CompDirty, + FILE_EXT2_CompBlock, + FILE_EXT2_NoCompBlock, + FILE_EXT2_CompError, + FILE_EXT2_BTree, + FILE_EXT2_HashIndexed, + FILE_EXT2_iMagic, + FILE_EXT2_Journaled, + FILE_EXT2_NoTail, + FILE_EXT2_DirSync, + FILE_EXT2_TopDir, + FILE_EXT2_Reserved, + UNKNOWN, +}; + +struct unknown_tag { + struct unknown_tag *next; + struct archive_string name; +}; + +struct xar { + uint64_t offset; /* Current position in the file. */ + int64_t total; + uint64_t h_base; + int end_of_file; +#define OUTBUFF_SIZE (1024 * 64) + unsigned char *outbuff; + + enum xmlstatus xmlsts; + enum xmlstatus xmlsts_unknown; + struct unknown_tag *unknowntags; + int base64text; + + /* + * TOC + */ + uint64_t toc_remaining; + uint64_t toc_total; + uint64_t toc_chksum_offset; + uint64_t toc_chksum_size; + + /* + * For Decoding data. + */ + enum enctype rd_encoding; + z_stream stream; + int stream_valid; +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) + bz_stream bzstream; + int bzstream_valid; +#endif +#if HAVE_LZMA_H && HAVE_LIBLZMA + lzma_stream lzstream; + int lzstream_valid; +#endif + /* + * For Checksum data. + */ + struct chksumwork a_sumwrk; + struct chksumwork e_sumwrk; + + struct xar_file *file; /* current reading file. */ + struct xattr *xattr; /* current reading extended attribute. */ + struct heap_queue file_queue; + struct xar_file *hdlink_orgs; + struct hdlink *hdlink_list; + + int entry_init; + uint64_t entry_total; + uint64_t entry_remaining; + size_t entry_unconsumed; + uint64_t entry_size; + enum enctype entry_encoding; + struct chksumval entry_a_sum; + struct chksumval entry_e_sum; + + struct archive_string_conv *sconv; +}; + +struct xmlattr { + struct xmlattr *next; + char *name; + char *value; +}; + +struct xmlattr_list { + struct xmlattr *first; + struct xmlattr **last; +}; + +static int xar_bid(struct archive_read *, int); +static int xar_read_header(struct archive_read *, + struct archive_entry *); +static int xar_read_data(struct archive_read *, + const void **, size_t *, int64_t *); +static int xar_read_data_skip(struct archive_read *); +static int xar_cleanup(struct archive_read *); +static int move_reading_point(struct archive_read *, uint64_t); +static int rd_contents_init(struct archive_read *, + enum enctype, int, int); +static int rd_contents(struct archive_read *, const void **, + size_t *, size_t *, uint64_t); +static uint64_t atol10(const char *, size_t); +static int64_t atol8(const char *, size_t); +static size_t atohex(unsigned char *, size_t, const char *, size_t); +static time_t parse_time(const char *p, size_t n); +static int heap_add_entry(struct archive_read *a, + struct heap_queue *, struct xar_file *); +static struct xar_file *heap_get_entry(struct heap_queue *); +static int add_link(struct archive_read *, + struct xar *, struct xar_file *); +static void checksum_init(struct archive_read *, int, int); +static void checksum_update(struct archive_read *, const void *, + size_t, const void *, size_t); +static int checksum_final(struct archive_read *, const void *, + size_t, const void *, size_t); +static void checksum_cleanup(struct archive_read *); +static int decompression_init(struct archive_read *, enum enctype); +static int decompress(struct archive_read *, const void **, + size_t *, const void *, size_t *); +static int decompression_cleanup(struct archive_read *); +static void xmlattr_cleanup(struct xmlattr_list *); +static int file_new(struct archive_read *, + struct xar *, struct xmlattr_list *); +static void file_free(struct xar_file *); +static int xattr_new(struct archive_read *, + struct xar *, struct xmlattr_list *); +static void xattr_free(struct xattr *); +static int getencoding(struct xmlattr_list *); +static int getsumalgorithm(struct xmlattr_list *); +static int unknowntag_start(struct archive_read *, + struct xar *, const char *); +static void unknowntag_end(struct xar *, const char *); +static int xml_start(struct archive_read *, + const char *, struct xmlattr_list *); +static void xml_end(void *, const char *); +static void xml_data(void *, const char *, int); +static int xml_parse_file_flags(struct xar *, const char *); +static int xml_parse_file_ext2(struct xar *, const char *); +#if defined(HAVE_LIBXML_XMLREADER_H) +static int xml2_xmlattr_setup(struct archive_read *, + struct xmlattr_list *, xmlTextReaderPtr); +static int xml2_read_cb(void *, char *, int); +static int xml2_close_cb(void *); +static void xml2_error_hdr(void *, const char *, xmlParserSeverities, + xmlTextReaderLocatorPtr); +static int xml2_read_toc(struct archive_read *); +#elif defined(HAVE_BSDXML_H) || defined(HAVE_EXPAT_H) +struct expat_userData { + int state; + struct archive_read *archive; +}; +static int expat_xmlattr_setup(struct archive_read *, + struct xmlattr_list *, const XML_Char **); +static void expat_start_cb(void *, const XML_Char *, const XML_Char **); +static void expat_end_cb(void *, const XML_Char *); +static void expat_data_cb(void *, const XML_Char *, int); +static int expat_read_toc(struct archive_read *); +#endif + +int +archive_read_support_format_xar(struct archive *_a) +{ + struct xar *xar; + struct archive_read *a = (struct archive_read *)_a; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_xar"); + + xar = (struct xar *)calloc(1, sizeof(*xar)); + if (xar == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate xar data"); + return (ARCHIVE_FATAL); + } + + /* initialize xar->file_queue */ + xar->file_queue.allocated = 0; + xar->file_queue.used = 0; + xar->file_queue.files = NULL; + + r = __archive_read_register_format(a, + xar, + "xar", + xar_bid, + NULL, + xar_read_header, + xar_read_data, + xar_read_data_skip, + NULL, + xar_cleanup, + NULL, + NULL); + if (r != ARCHIVE_OK) + free(xar); + return (r); +} + +static int +xar_bid(struct archive_read *a, int best_bid) +{ + const unsigned char *b; + int bid; + + (void)best_bid; /* UNUSED */ + + b = __archive_read_ahead(a, HEADER_SIZE, NULL); + if (b == NULL) + return (-1); + + bid = 0; + /* + * Verify magic code + */ + if (archive_be32dec(b) != HEADER_MAGIC) + return (0); + bid += 32; + /* + * Verify header size + */ + if (archive_be16dec(b+4) != HEADER_SIZE) + return (0); + bid += 16; + /* + * Verify header version + */ + if (archive_be16dec(b+6) != HEADER_VERSION) + return (0); + bid += 16; + /* + * Verify type of checksum + */ + switch (archive_be32dec(b+24)) { + case CKSUM_NONE: + case CKSUM_SHA1: + case CKSUM_MD5: + bid += 32; + break; + default: + return (0); + } + + return (bid); +} + +static int +read_toc(struct archive_read *a) +{ + struct xar *xar; + struct xar_file *file; + const unsigned char *b; + uint64_t toc_compressed_size; + uint64_t toc_uncompressed_size; + uint32_t toc_chksum_alg; + ssize_t bytes; + int r; + + xar = (struct xar *)(a->format->data); + + /* + * Read xar header. + */ + b = __archive_read_ahead(a, HEADER_SIZE, &bytes); + if (bytes < 0) + return ((int)bytes); + if (bytes < HEADER_SIZE) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated archive header"); + return (ARCHIVE_FATAL); + } + + if (archive_be32dec(b) != HEADER_MAGIC) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid header magic"); + return (ARCHIVE_FATAL); + } + if (archive_be16dec(b+6) != HEADER_VERSION) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Unsupported header version(%d)", + archive_be16dec(b+6)); + return (ARCHIVE_FATAL); + } + toc_compressed_size = archive_be64dec(b+8); + xar->toc_remaining = toc_compressed_size; + toc_uncompressed_size = archive_be64dec(b+16); + toc_chksum_alg = archive_be32dec(b+24); + __archive_read_consume(a, HEADER_SIZE); + xar->offset += HEADER_SIZE; + xar->toc_total = 0; + + /* + * Read TOC(Table of Contents). + */ + /* Initialize reading contents. */ + r = move_reading_point(a, HEADER_SIZE); + if (r != ARCHIVE_OK) + return (r); + r = rd_contents_init(a, GZIP, toc_chksum_alg, CKSUM_NONE); + if (r != ARCHIVE_OK) + return (r); + +#ifdef HAVE_LIBXML_XMLREADER_H + r = xml2_read_toc(a); +#elif defined(HAVE_BSDXML_H) || defined(HAVE_EXPAT_H) + r = expat_read_toc(a); +#endif + if (r != ARCHIVE_OK) + return (r); + + /* Set 'The HEAP' base. */ + xar->h_base = xar->offset; + if (xar->toc_total != toc_uncompressed_size) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "TOC uncompressed size error"); + return (ARCHIVE_FATAL); + } + + /* + * Checksum TOC + */ + if (toc_chksum_alg != CKSUM_NONE) { + r = move_reading_point(a, xar->toc_chksum_offset); + if (r != ARCHIVE_OK) + return (r); + b = __archive_read_ahead(a, + (size_t)xar->toc_chksum_size, &bytes); + if (bytes < 0) + return ((int)bytes); + if ((uint64_t)bytes < xar->toc_chksum_size) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated archive file"); + return (ARCHIVE_FATAL); + } + r = checksum_final(a, b, + (size_t)xar->toc_chksum_size, NULL, 0); + __archive_read_consume(a, xar->toc_chksum_size); + xar->offset += xar->toc_chksum_size; + if (r != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + + /* + * Connect hardlinked files. + */ + for (file = xar->hdlink_orgs; file != NULL; file = file->hdnext) { + struct hdlink **hdlink; + + for (hdlink = &(xar->hdlink_list); *hdlink != NULL; + hdlink = &((*hdlink)->next)) { + if ((*hdlink)->id == file->id) { + struct hdlink *hltmp; + struct xar_file *f2; + int nlink = (*hdlink)->cnt + 1; + + file->nlink = nlink; + for (f2 = (*hdlink)->files; f2 != NULL; + f2 = f2->hdnext) { + f2->nlink = nlink; + archive_string_copy( + &(f2->hardlink), &(file->pathname)); + } + /* Remove resolved files from hdlist_list. */ + hltmp = *hdlink; + *hdlink = hltmp->next; + free(hltmp); + break; + } + } + } + a->archive.archive_format = ARCHIVE_FORMAT_XAR; + a->archive.archive_format_name = "xar"; + + return (ARCHIVE_OK); +} + +static int +xar_read_header(struct archive_read *a, struct archive_entry *entry) +{ + struct xar *xar; + struct xar_file *file; + struct xattr *xattr; + int r; + + xar = (struct xar *)(a->format->data); + r = ARCHIVE_OK; + + if (xar->offset == 0) { + /* Create a character conversion object. */ + if (xar->sconv == NULL) { + xar->sconv = archive_string_conversion_from_charset( + &(a->archive), "UTF-8", 1); + if (xar->sconv == NULL) + return (ARCHIVE_FATAL); + } + + /* Read TOC. */ + r = read_toc(a); + if (r != ARCHIVE_OK) + return (r); + } + + for (;;) { + file = xar->file = heap_get_entry(&(xar->file_queue)); + if (file == NULL) { + xar->end_of_file = 1; + return (ARCHIVE_EOF); + } + if ((file->mode & AE_IFMT) != AE_IFDIR) + break; + if (file->has != (HAS_PATHNAME | HAS_TYPE)) + break; + /* + * If a file type is a directory and it does not have + * any metadata, do not export. + */ + file_free(file); + } + if (file->has & HAS_ATIME) { + archive_entry_set_atime(entry, file->atime, 0); + } + if (file->has & HAS_CTIME) { + archive_entry_set_ctime(entry, file->ctime, 0); + } + if (file->has & HAS_MTIME) { + archive_entry_set_mtime(entry, file->mtime, 0); + } + archive_entry_set_gid(entry, file->gid); + if (file->gname.length > 0 && + archive_entry_copy_gname_l(entry, file->gname.s, + archive_strlen(&(file->gname)), xar->sconv) != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Gname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Gname cannot be converted from %s to current locale.", + archive_string_conversion_charset_name(xar->sconv)); + r = ARCHIVE_WARN; + } + archive_entry_set_uid(entry, file->uid); + if (file->uname.length > 0 && + archive_entry_copy_uname_l(entry, file->uname.s, + archive_strlen(&(file->uname)), xar->sconv) != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Uname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Uname cannot be converted from %s to current locale.", + archive_string_conversion_charset_name(xar->sconv)); + r = ARCHIVE_WARN; + } + archive_entry_set_mode(entry, file->mode); + if (archive_entry_copy_pathname_l(entry, file->pathname.s, + archive_strlen(&(file->pathname)), xar->sconv) != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Pathname cannot be converted from %s to current locale.", + archive_string_conversion_charset_name(xar->sconv)); + r = ARCHIVE_WARN; + } + + + if (file->symlink.length > 0 && + archive_entry_copy_symlink_l(entry, file->symlink.s, + archive_strlen(&(file->symlink)), xar->sconv) != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Linkname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Linkname cannot be converted from %s to current locale.", + archive_string_conversion_charset_name(xar->sconv)); + r = ARCHIVE_WARN; + } + /* Set proper nlink. */ + if ((file->mode & AE_IFMT) == AE_IFDIR) + archive_entry_set_nlink(entry, file->subdirs + 2); + else + archive_entry_set_nlink(entry, file->nlink); + archive_entry_set_size(entry, file->size); + if (archive_strlen(&(file->hardlink)) > 0) + archive_entry_set_hardlink(entry, file->hardlink.s); + archive_entry_set_ino64(entry, file->ino64); + if (file->has & HAS_DEV) + archive_entry_set_dev(entry, file->dev); + if (file->has & HAS_DEVMAJOR) + archive_entry_set_devmajor(entry, file->devmajor); + if (file->has & HAS_DEVMINOR) + archive_entry_set_devminor(entry, file->devminor); + if (archive_strlen(&(file->fflags_text)) > 0) + archive_entry_copy_fflags_text(entry, file->fflags_text.s); + + xar->entry_init = 1; + xar->entry_total = 0; + xar->entry_remaining = file->length; + xar->entry_size = file->size; + xar->entry_encoding = file->encoding; + xar->entry_a_sum = file->a_sum; + xar->entry_e_sum = file->e_sum; + /* + * Read extended attributes. + */ + xattr = file->xattr_list; + while (xattr != NULL) { + const void *d; + size_t outbytes = 0; + size_t used = 0; + + r = move_reading_point(a, xattr->offset); + if (r != ARCHIVE_OK) + break; + r = rd_contents_init(a, xattr->encoding, + xattr->a_sum.alg, xattr->e_sum.alg); + if (r != ARCHIVE_OK) + break; + d = NULL; + r = rd_contents(a, &d, &outbytes, &used, xattr->length); + if (r != ARCHIVE_OK) + break; + if (outbytes != xattr->size) { + archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, + "Decompressed size error"); + r = ARCHIVE_FATAL; + break; + } + r = checksum_final(a, + xattr->a_sum.val, xattr->a_sum.len, + xattr->e_sum.val, xattr->e_sum.len); + if (r != ARCHIVE_OK) { + archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, + "Xattr checksum error"); + r = ARCHIVE_WARN; + break; + } + if (xattr->name.s == NULL) { + archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, + "Xattr name error"); + r = ARCHIVE_WARN; + break; + } + archive_entry_xattr_add_entry(entry, + xattr->name.s, d, outbytes); + xattr = xattr->next; + } + if (r != ARCHIVE_OK) { + file_free(file); + return (r); + } + + if (xar->entry_remaining > 0) + /* Move reading point to the beginning of current + * file contents. */ + r = move_reading_point(a, file->offset); + else + r = ARCHIVE_OK; + + file_free(file); + return (r); +} + +static int +xar_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + struct xar *xar; + size_t used = 0; + int r; + + xar = (struct xar *)(a->format->data); + + if (xar->entry_unconsumed) { + __archive_read_consume(a, xar->entry_unconsumed); + xar->entry_unconsumed = 0; + } + + if (xar->end_of_file || xar->entry_remaining <= 0) { + r = ARCHIVE_EOF; + goto abort_read_data; + } + + if (xar->entry_init) { + r = rd_contents_init(a, xar->entry_encoding, + xar->entry_a_sum.alg, xar->entry_e_sum.alg); + if (r != ARCHIVE_OK) { + xar->entry_remaining = 0; + return (r); + } + xar->entry_init = 0; + } + + *buff = NULL; + r = rd_contents(a, buff, size, &used, xar->entry_remaining); + if (r != ARCHIVE_OK) + goto abort_read_data; + + *offset = xar->entry_total; + xar->entry_total += *size; + xar->total += *size; + xar->offset += used; + xar->entry_remaining -= used; + xar->entry_unconsumed = used; + + if (xar->entry_remaining == 0) { + if (xar->entry_total != xar->entry_size) { + archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, + "Decompressed size error"); + r = ARCHIVE_FATAL; + goto abort_read_data; + } + r = checksum_final(a, + xar->entry_a_sum.val, xar->entry_a_sum.len, + xar->entry_e_sum.val, xar->entry_e_sum.len); + if (r != ARCHIVE_OK) + goto abort_read_data; + } + + return (ARCHIVE_OK); +abort_read_data: + *buff = NULL; + *size = 0; + *offset = xar->total; + return (r); +} + +static int +xar_read_data_skip(struct archive_read *a) +{ + struct xar *xar; + int64_t bytes_skipped; + + xar = (struct xar *)(a->format->data); + if (xar->end_of_file) + return (ARCHIVE_EOF); + bytes_skipped = __archive_read_consume(a, xar->entry_remaining + + xar->entry_unconsumed); + if (bytes_skipped < 0) + return (ARCHIVE_FATAL); + xar->offset += bytes_skipped; + xar->entry_unconsumed = 0; + return (ARCHIVE_OK); +} + +static int +xar_cleanup(struct archive_read *a) +{ + struct xar *xar; + struct hdlink *hdlink; + int i; + int r; + + xar = (struct xar *)(a->format->data); + checksum_cleanup(a); + r = decompression_cleanup(a); + hdlink = xar->hdlink_list; + while (hdlink != NULL) { + struct hdlink *next = hdlink->next; + + free(hdlink); + hdlink = next; + } + for (i = 0; i < xar->file_queue.used; i++) + file_free(xar->file_queue.files[i]); + free(xar->file_queue.files); + while (xar->unknowntags != NULL) { + struct unknown_tag *tag; + + tag = xar->unknowntags; + xar->unknowntags = tag->next; + archive_string_free(&(tag->name)); + free(tag); + } + free(xar->outbuff); + free(xar); + a->format->data = NULL; + return (r); +} + +static int +move_reading_point(struct archive_read *a, uint64_t offset) +{ + struct xar *xar; + + xar = (struct xar *)(a->format->data); + if (xar->offset - xar->h_base != offset) { + /* Seek forward to the start of file contents. */ + int64_t step; + + step = offset - (xar->offset - xar->h_base); + if (step > 0) { + step = __archive_read_consume(a, step); + if (step < 0) + return ((int)step); + xar->offset += step; + } else { + int64_t pos = __archive_read_seek(a, xar->h_base + offset, SEEK_SET); + if (pos == ARCHIVE_FAILED) { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "Cannot seek."); + return (ARCHIVE_FAILED); + } + xar->offset = pos; + } + } + return (ARCHIVE_OK); +} + +static int +rd_contents_init(struct archive_read *a, enum enctype encoding, + int a_sum_alg, int e_sum_alg) +{ + int r; + + /* Init decompress library. */ + if ((r = decompression_init(a, encoding)) != ARCHIVE_OK) + return (r); + /* Init checksum library. */ + checksum_init(a, a_sum_alg, e_sum_alg); + return (ARCHIVE_OK); +} + +static int +rd_contents(struct archive_read *a, const void **buff, size_t *size, + size_t *used, uint64_t remaining) +{ + const unsigned char *b; + ssize_t bytes; + + /* Get whatever bytes are immediately available. */ + b = __archive_read_ahead(a, 1, &bytes); + if (bytes < 0) + return ((int)bytes); + if (bytes == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Truncated archive file"); + return (ARCHIVE_FATAL); + } + if ((uint64_t)bytes > remaining) + bytes = (ssize_t)remaining; + + /* + * Decompress contents of file. + */ + *used = bytes; + if (decompress(a, buff, size, b, used) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* + * Update checksum of a compressed data and a extracted data. + */ + checksum_update(a, b, *used, *buff, *size); + + return (ARCHIVE_OK); +} + +/* + * Note that this implementation does not (and should not!) obey + * locale settings; you cannot simply substitute strtol here, since + * it does obey locale. + */ + +static uint64_t +atol10(const char *p, size_t char_cnt) +{ + uint64_t l; + int digit; + + if (char_cnt == 0) + return (0); + + l = 0; + digit = *p - '0'; + while (digit >= 0 && digit < 10 && char_cnt-- > 0) { + l = (l * 10) + digit; + digit = *++p - '0'; + } + return (l); +} + +static int64_t +atol8(const char *p, size_t char_cnt) +{ + int64_t l; + int digit; + + if (char_cnt == 0) + return (0); + + l = 0; + while (char_cnt-- > 0) { + if (*p >= '0' && *p <= '7') + digit = *p - '0'; + else + break; + p++; + l <<= 3; + l |= digit; + } + return (l); +} + +static size_t +atohex(unsigned char *b, size_t bsize, const char *p, size_t psize) +{ + size_t fbsize = bsize; + + while (bsize && psize > 1) { + unsigned char x; + + if (p[0] >= 'a' && p[0] <= 'z') + x = (p[0] - 'a' + 0x0a) << 4; + else if (p[0] >= 'A' && p[0] <= 'Z') + x = (p[0] - 'A' + 0x0a) << 4; + else if (p[0] >= '0' && p[0] <= '9') + x = (p[0] - '0') << 4; + else + return (-1); + if (p[1] >= 'a' && p[1] <= 'z') + x |= p[1] - 'a' + 0x0a; + else if (p[1] >= 'A' && p[1] <= 'Z') + x |= p[1] - 'A' + 0x0a; + else if (p[1] >= '0' && p[1] <= '9') + x |= p[1] - '0'; + else + return (-1); + + *b++ = x; + bsize--; + p += 2; + psize -= 2; + } + return (fbsize - bsize); +} + +static time_t +time_from_tm(struct tm *t) +{ +#if HAVE_TIMEGM + /* Use platform timegm() if available. */ + return (timegm(t)); +#elif HAVE__MKGMTIME64 + return (_mkgmtime64(t)); +#else + /* Else use direct calculation using POSIX assumptions. */ + /* First, fix up tm_yday based on the year/month/day. */ + mktime(t); + /* Then we can compute timegm() from first principles. */ + return (t->tm_sec + + t->tm_min * 60 + + t->tm_hour * 3600 + + t->tm_yday * 86400 + + (t->tm_year - 70) * 31536000 + + ((t->tm_year - 69) / 4) * 86400 + - ((t->tm_year - 1) / 100) * 86400 + + ((t->tm_year + 299) / 400) * 86400); +#endif +} + +static time_t +parse_time(const char *p, size_t n) +{ + struct tm tm; + time_t t = 0; + int64_t data; + + memset(&tm, 0, sizeof(tm)); + if (n != 20) + return (t); + data = atol10(p, 4); + if (data < 1900) + return (t); + tm.tm_year = (int)data - 1900; + p += 4; + if (*p++ != '-') + return (t); + data = atol10(p, 2); + if (data < 1 || data > 12) + return (t); + tm.tm_mon = (int)data -1; + p += 2; + if (*p++ != '-') + return (t); + data = atol10(p, 2); + if (data < 1 || data > 31) + return (t); + tm.tm_mday = (int)data; + p += 2; + if (*p++ != 'T') + return (t); + data = atol10(p, 2); + if (data < 0 || data > 23) + return (t); + tm.tm_hour = (int)data; + p += 2; + if (*p++ != ':') + return (t); + data = atol10(p, 2); + if (data < 0 || data > 59) + return (t); + tm.tm_min = (int)data; + p += 2; + if (*p++ != ':') + return (t); + data = atol10(p, 2); + if (data < 0 || data > 60) + return (t); + tm.tm_sec = (int)data; +#if 0 + p += 2; + if (*p != 'Z') + return (t); +#endif + + t = time_from_tm(&tm); + + return (t); +} + +static int +heap_add_entry(struct archive_read *a, + struct heap_queue *heap, struct xar_file *file) +{ + uint64_t file_id, parent_id; + int hole, parent; + + /* Expand our pending files list as necessary. */ + if (heap->used >= heap->allocated) { + struct xar_file **new_pending_files; + int new_size; + + if (heap->allocated < 1024) + new_size = 1024; + else + new_size = heap->allocated * 2; + /* Overflow might keep us from growing the list. */ + if (new_size <= heap->allocated) { + archive_set_error(&a->archive, + ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + new_pending_files = (struct xar_file **) + malloc(new_size * sizeof(new_pending_files[0])); + if (new_pending_files == NULL) { + archive_set_error(&a->archive, + ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + if (heap->allocated) { + memcpy(new_pending_files, heap->files, + heap->allocated * sizeof(new_pending_files[0])); + free(heap->files); + } + heap->files = new_pending_files; + heap->allocated = new_size; + } + + file_id = file->id; + + /* + * Start with hole at end, walk it up tree to find insertion point. + */ + hole = heap->used++; + while (hole > 0) { + parent = (hole - 1)/2; + parent_id = heap->files[parent]->id; + if (file_id >= parent_id) { + heap->files[hole] = file; + return (ARCHIVE_OK); + } + /* Move parent into hole <==> move hole up tree. */ + heap->files[hole] = heap->files[parent]; + hole = parent; + } + heap->files[0] = file; + + return (ARCHIVE_OK); +} + +static struct xar_file * +heap_get_entry(struct heap_queue *heap) +{ + uint64_t a_id, b_id, c_id; + int a, b, c; + struct xar_file *r, *tmp; + + if (heap->used < 1) + return (NULL); + + /* + * The first file in the list is the earliest; we'll return this. + */ + r = heap->files[0]; + + /* + * Move the last item in the heap to the root of the tree + */ + heap->files[0] = heap->files[--(heap->used)]; + + /* + * Rebalance the heap. + */ + a = 0; /* Starting element and its heap key */ + a_id = heap->files[a]->id; + for (;;) { + b = a + a + 1; /* First child */ + if (b >= heap->used) + return (r); + b_id = heap->files[b]->id; + c = b + 1; /* Use second child if it is smaller. */ + if (c < heap->used) { + c_id = heap->files[c]->id; + if (c_id < b_id) { + b = c; + b_id = c_id; + } + } + if (a_id <= b_id) + return (r); + tmp = heap->files[a]; + heap->files[a] = heap->files[b]; + heap->files[b] = tmp; + a = b; + } +} + +static int +add_link(struct archive_read *a, struct xar *xar, struct xar_file *file) +{ + struct hdlink *hdlink; + + for (hdlink = xar->hdlink_list; hdlink != NULL; hdlink = hdlink->next) { + if (hdlink->id == file->link) { + file->hdnext = hdlink->files; + hdlink->cnt++; + hdlink->files = file; + return (ARCHIVE_OK); + } + } + hdlink = malloc(sizeof(*hdlink)); + if (hdlink == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + file->hdnext = NULL; + hdlink->id = file->link; + hdlink->cnt = 1; + hdlink->files = file; + hdlink->next = xar->hdlink_list; + xar->hdlink_list = hdlink; + return (ARCHIVE_OK); +} + +static void +_checksum_init(struct chksumwork *sumwrk, int sum_alg) +{ + sumwrk->alg = sum_alg; + switch (sum_alg) { + case CKSUM_NONE: + break; + case CKSUM_SHA1: + archive_sha1_init(&(sumwrk->sha1ctx)); + break; + case CKSUM_MD5: + archive_md5_init(&(sumwrk->md5ctx)); + break; + } +} + +static void +_checksum_update(struct chksumwork *sumwrk, const void *buff, size_t size) +{ + + switch (sumwrk->alg) { + case CKSUM_NONE: + break; + case CKSUM_SHA1: + archive_sha1_update(&(sumwrk->sha1ctx), buff, size); + break; + case CKSUM_MD5: + archive_md5_update(&(sumwrk->md5ctx), buff, size); + break; + } +} + +static int +_checksum_final(struct chksumwork *sumwrk, const void *val, size_t len) +{ + unsigned char sum[MAX_SUM_SIZE]; + int r = ARCHIVE_OK; + + switch (sumwrk->alg) { + case CKSUM_NONE: + break; + case CKSUM_SHA1: + archive_sha1_final(&(sumwrk->sha1ctx), sum); + if (len != SHA1_SIZE || + memcmp(val, sum, SHA1_SIZE) != 0) + r = ARCHIVE_FAILED; + break; + case CKSUM_MD5: + archive_md5_final(&(sumwrk->md5ctx), sum); + if (len != MD5_SIZE || + memcmp(val, sum, MD5_SIZE) != 0) + r = ARCHIVE_FAILED; + break; + } + return (r); +} + +static void +checksum_init(struct archive_read *a, int a_sum_alg, int e_sum_alg) +{ + struct xar *xar; + + xar = (struct xar *)(a->format->data); + _checksum_init(&(xar->a_sumwrk), a_sum_alg); + _checksum_init(&(xar->e_sumwrk), e_sum_alg); +} + +static void +checksum_update(struct archive_read *a, const void *abuff, size_t asize, + const void *ebuff, size_t esize) +{ + struct xar *xar; + + xar = (struct xar *)(a->format->data); + _checksum_update(&(xar->a_sumwrk), abuff, asize); + _checksum_update(&(xar->e_sumwrk), ebuff, esize); +} + +static int +checksum_final(struct archive_read *a, const void *a_sum_val, + size_t a_sum_len, const void *e_sum_val, size_t e_sum_len) +{ + struct xar *xar; + int r; + + xar = (struct xar *)(a->format->data); + r = _checksum_final(&(xar->a_sumwrk), a_sum_val, a_sum_len); + if (r == ARCHIVE_OK) + r = _checksum_final(&(xar->e_sumwrk), e_sum_val, e_sum_len); + if (r != ARCHIVE_OK) + archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, + "Sumcheck error"); + return (r); +} + +static int +decompression_init(struct archive_read *a, enum enctype encoding) +{ + struct xar *xar; + const char *detail; + int r; + + xar = (struct xar *)(a->format->data); + xar->rd_encoding = encoding; + switch (encoding) { + case NONE: + break; + case GZIP: + if (xar->stream_valid) + r = inflateReset(&(xar->stream)); + else + r = inflateInit(&(xar->stream)); + if (r != Z_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Couldn't initialize zlib stream."); + return (ARCHIVE_FATAL); + } + xar->stream_valid = 1; + xar->stream.total_in = 0; + xar->stream.total_out = 0; + break; +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) + case BZIP2: + if (xar->bzstream_valid) { + BZ2_bzDecompressEnd(&(xar->bzstream)); + xar->bzstream_valid = 0; + } + r = BZ2_bzDecompressInit(&(xar->bzstream), 0, 0); + if (r == BZ_MEM_ERROR) + r = BZ2_bzDecompressInit(&(xar->bzstream), 0, 1); + if (r != BZ_OK) { + int err = ARCHIVE_ERRNO_MISC; + detail = NULL; + switch (r) { + case BZ_PARAM_ERROR: + detail = "invalid setup parameter"; + break; + case BZ_MEM_ERROR: + err = ENOMEM; + detail = "out of memory"; + break; + case BZ_CONFIG_ERROR: + detail = "mis-compiled library"; + break; + } + archive_set_error(&a->archive, err, + "Internal error initializing decompressor: %s", + detail == NULL ? "??" : detail); + xar->bzstream_valid = 0; + return (ARCHIVE_FATAL); + } + xar->bzstream_valid = 1; + xar->bzstream.total_in_lo32 = 0; + xar->bzstream.total_in_hi32 = 0; + xar->bzstream.total_out_lo32 = 0; + xar->bzstream.total_out_hi32 = 0; + break; +#endif +#if defined(HAVE_LZMA_H) && defined(HAVE_LIBLZMA) +#if LZMA_VERSION_MAJOR >= 5 +/* Effectively disable the limiter. */ +#define LZMA_MEMLIMIT UINT64_MAX +#else +/* NOTE: This needs to check memory size which running system has. */ +#define LZMA_MEMLIMIT (1U << 30) +#endif + case XZ: + case LZMA: + if (xar->lzstream_valid) { + lzma_end(&(xar->lzstream)); + xar->lzstream_valid = 0; + } + if (xar->entry_encoding == XZ) + r = lzma_stream_decoder(&(xar->lzstream), + LZMA_MEMLIMIT,/* memlimit */ + LZMA_CONCATENATED); + else + r = lzma_alone_decoder(&(xar->lzstream), + LZMA_MEMLIMIT);/* memlimit */ + if (r != LZMA_OK) { + switch (r) { + case LZMA_MEM_ERROR: + archive_set_error(&a->archive, + ENOMEM, + "Internal error initializing " + "compression library: " + "Cannot allocate memory"); + break; + case LZMA_OPTIONS_ERROR: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Internal error initializing " + "compression library: " + "Invalid or unsupported options"); + break; + default: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Internal error initializing " + "lzma library"); + break; + } + return (ARCHIVE_FATAL); + } + xar->lzstream_valid = 1; + xar->lzstream.total_in = 0; + xar->lzstream.total_out = 0; + break; +#endif + /* + * Unsupported compression. + */ + default: +#if !defined(HAVE_BZLIB_H) || !defined(BZ_CONFIG_ERROR) + case BZIP2: +#endif +#if !defined(HAVE_LZMA_H) || !defined(HAVE_LIBLZMA) + case LZMA: + case XZ: +#endif + switch (xar->entry_encoding) { + case BZIP2: detail = "bzip2"; break; + case LZMA: detail = "lzma"; break; + case XZ: detail = "xz"; break; + default: detail = "??"; break; + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "%s compression not supported on this platform", + detail); + return (ARCHIVE_FAILED); + } + return (ARCHIVE_OK); +} + +static int +decompress(struct archive_read *a, const void **buff, size_t *outbytes, + const void *b, size_t *used) +{ + struct xar *xar; + void *outbuff; + size_t avail_in, avail_out; + int r; + + xar = (struct xar *)(a->format->data); + avail_in = *used; + outbuff = (void *)(uintptr_t)*buff; + if (outbuff == NULL) { + if (xar->outbuff == NULL) { + xar->outbuff = malloc(OUTBUFF_SIZE); + if (xar->outbuff == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Couldn't allocate memory for out buffer"); + return (ARCHIVE_FATAL); + } + } + outbuff = xar->outbuff; + *buff = outbuff; + avail_out = OUTBUFF_SIZE; + } else + avail_out = *outbytes; + switch (xar->rd_encoding) { + case GZIP: + xar->stream.next_in = (Bytef *)(uintptr_t)b; + xar->stream.avail_in = avail_in; + xar->stream.next_out = (unsigned char *)outbuff; + xar->stream.avail_out = avail_out; + r = inflate(&(xar->stream), 0); + switch (r) { + case Z_OK: /* Decompressor made some progress.*/ + case Z_STREAM_END: /* Found end of stream. */ + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "File decompression failed (%d)", r); + return (ARCHIVE_FATAL); + } + *used = avail_in - xar->stream.avail_in; + *outbytes = avail_out - xar->stream.avail_out; + break; +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) + case BZIP2: + xar->bzstream.next_in = (char *)(uintptr_t)b; + xar->bzstream.avail_in = avail_in; + xar->bzstream.next_out = (char *)outbuff; + xar->bzstream.avail_out = avail_out; + r = BZ2_bzDecompress(&(xar->bzstream)); + switch (r) { + case BZ_STREAM_END: /* Found end of stream. */ + switch (BZ2_bzDecompressEnd(&(xar->bzstream))) { + case BZ_OK: + break; + default: + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "Failed to clean up decompressor"); + return (ARCHIVE_FATAL); + } + xar->bzstream_valid = 0; + /* FALLTHROUGH */ + case BZ_OK: /* Decompressor made some progress. */ + break; + default: + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "bzip decompression failed"); + return (ARCHIVE_FATAL); + } + *used = avail_in - xar->bzstream.avail_in; + *outbytes = avail_out - xar->bzstream.avail_out; + break; +#endif +#if defined(HAVE_LZMA_H) && defined(HAVE_LIBLZMA) + case LZMA: + case XZ: + xar->lzstream.next_in = b; + xar->lzstream.avail_in = avail_in; + xar->lzstream.next_out = (unsigned char *)outbuff; + xar->lzstream.avail_out = avail_out; + r = lzma_code(&(xar->lzstream), LZMA_RUN); + switch (r) { + case LZMA_STREAM_END: /* Found end of stream. */ + lzma_end(&(xar->lzstream)); + xar->lzstream_valid = 0; + /* FALLTHROUGH */ + case LZMA_OK: /* Decompressor made some progress. */ + break; + default: + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "%s decompression failed(%d)", + (xar->entry_encoding == XZ)?"xz":"lzma", + r); + return (ARCHIVE_FATAL); + } + *used = avail_in - xar->lzstream.avail_in; + *outbytes = avail_out - xar->lzstream.avail_out; + break; +#endif +#if !defined(HAVE_BZLIB_H) || !defined(BZ_CONFIG_ERROR) + case BZIP2: +#endif +#if !defined(HAVE_LZMA_H) || !defined(HAVE_LIBLZMA) + case LZMA: + case XZ: +#endif + case NONE: + default: + if (outbuff == xar->outbuff) { + *buff = b; + *used = avail_in; + *outbytes = avail_in; + } else { + if (avail_out > avail_in) + avail_out = avail_in; + memcpy(outbuff, b, avail_out); + *used = avail_out; + *outbytes = avail_out; + } + break; + } + return (ARCHIVE_OK); +} + +static int +decompression_cleanup(struct archive_read *a) +{ + struct xar *xar; + int r; + + xar = (struct xar *)(a->format->data); + r = ARCHIVE_OK; + if (xar->stream_valid) { + if (inflateEnd(&(xar->stream)) != Z_OK) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Failed to clean up zlib decompressor"); + r = ARCHIVE_FATAL; + } + } +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) + if (xar->bzstream_valid) { + if (BZ2_bzDecompressEnd(&(xar->bzstream)) != BZ_OK) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Failed to clean up bzip2 decompressor"); + r = ARCHIVE_FATAL; + } + } +#endif +#if defined(HAVE_LZMA_H) && defined(HAVE_LIBLZMA) + if (xar->lzstream_valid) + lzma_end(&(xar->lzstream)); +#elif defined(HAVE_LZMA_H) && defined(HAVE_LIBLZMA) + if (xar->lzstream_valid) { + if (lzmadec_end(&(xar->lzstream)) != LZMADEC_OK) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Failed to clean up lzmadec decompressor"); + r = ARCHIVE_FATAL; + } + } +#endif + return (r); +} + +static void +checksum_cleanup(struct archive_read *a) { + struct xar *xar; + + xar = (struct xar *)(a->format->data); + + _checksum_final(&(xar->a_sumwrk), NULL, 0); + _checksum_final(&(xar->e_sumwrk), NULL, 0); +} + +static void +xmlattr_cleanup(struct xmlattr_list *list) +{ + struct xmlattr *attr, *next; + + attr = list->first; + while (attr != NULL) { + next = attr->next; + free(attr->name); + free(attr->value); + free(attr); + attr = next; + } + list->first = NULL; + list->last = &(list->first); +} + +static int +file_new(struct archive_read *a, struct xar *xar, struct xmlattr_list *list) +{ + struct xar_file *file; + struct xmlattr *attr; + + file = calloc(1, sizeof(*file)); + if (file == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + file->parent = xar->file; + file->mode = 0777 | AE_IFREG; + file->atime = 0; + file->mtime = 0; + xar->file = file; + xar->xattr = NULL; + for (attr = list->first; attr != NULL; attr = attr->next) { + if (strcmp(attr->name, "id") == 0) + file->id = atol10(attr->value, strlen(attr->value)); + } + file->nlink = 1; + if (heap_add_entry(a, &(xar->file_queue), file) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + return (ARCHIVE_OK); +} + +static void +file_free(struct xar_file *file) +{ + struct xattr *xattr; + + archive_string_free(&(file->pathname)); + archive_string_free(&(file->symlink)); + archive_string_free(&(file->uname)); + archive_string_free(&(file->gname)); + archive_string_free(&(file->hardlink)); + xattr = file->xattr_list; + while (xattr != NULL) { + struct xattr *next; + + next = xattr->next; + xattr_free(xattr); + xattr = next; + } + + free(file); +} + +static int +xattr_new(struct archive_read *a, struct xar *xar, struct xmlattr_list *list) +{ + struct xattr *xattr, **nx; + struct xmlattr *attr; + + xattr = calloc(1, sizeof(*xattr)); + if (xattr == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + xar->xattr = xattr; + for (attr = list->first; attr != NULL; attr = attr->next) { + if (strcmp(attr->name, "id") == 0) + xattr->id = atol10(attr->value, strlen(attr->value)); + } + /* Chain to xattr list. */ + for (nx = &(xar->file->xattr_list); + *nx != NULL; nx = &((*nx)->next)) { + if (xattr->id < (*nx)->id) + break; + } + xattr->next = *nx; + *nx = xattr; + + return (ARCHIVE_OK); +} + +static void +xattr_free(struct xattr *xattr) +{ + archive_string_free(&(xattr->name)); + free(xattr); +} + +static int +getencoding(struct xmlattr_list *list) +{ + struct xmlattr *attr; + enum enctype encoding = NONE; + + for (attr = list->first; attr != NULL; attr = attr->next) { + if (strcmp(attr->name, "style") == 0) { + if (strcmp(attr->value, "application/octet-stream") == 0) + encoding = NONE; + else if (strcmp(attr->value, "application/x-gzip") == 0) + encoding = GZIP; + else if (strcmp(attr->value, "application/x-bzip2") == 0) + encoding = BZIP2; + else if (strcmp(attr->value, "application/x-lzma") == 0) + encoding = LZMA; + else if (strcmp(attr->value, "application/x-xz") == 0) + encoding = XZ; + } + } + return (encoding); +} + +static int +getsumalgorithm(struct xmlattr_list *list) +{ + struct xmlattr *attr; + int alg = CKSUM_NONE; + + for (attr = list->first; attr != NULL; attr = attr->next) { + if (strcmp(attr->name, "style") == 0) { + const char *v = attr->value; + if ((v[0] == 'S' || v[0] == 's') && + (v[1] == 'H' || v[1] == 'h') && + (v[2] == 'A' || v[2] == 'a') && + v[3] == '1' && v[4] == '\0') + alg = CKSUM_SHA1; + if ((v[0] == 'M' || v[0] == 'm') && + (v[1] == 'D' || v[1] == 'd') && + v[2] == '5' && v[3] == '\0') + alg = CKSUM_MD5; + } + } + return (alg); +} + +static int +unknowntag_start(struct archive_read *a, struct xar *xar, const char *name) +{ + struct unknown_tag *tag; + + tag = malloc(sizeof(*tag)); + if (tag == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + tag->next = xar->unknowntags; + archive_string_init(&(tag->name)); + archive_strcpy(&(tag->name), name); + if (xar->unknowntags == NULL) { +#if DEBUG + fprintf(stderr, "UNKNOWNTAG_START:%s\n", name); +#endif + xar->xmlsts_unknown = xar->xmlsts; + xar->xmlsts = UNKNOWN; + } + xar->unknowntags = tag; + return (ARCHIVE_OK); +} + +static void +unknowntag_end(struct xar *xar, const char *name) +{ + struct unknown_tag *tag; + + tag = xar->unknowntags; + if (tag == NULL || name == NULL) + return; + if (strcmp(tag->name.s, name) == 0) { + xar->unknowntags = tag->next; + archive_string_free(&(tag->name)); + free(tag); + if (xar->unknowntags == NULL) { +#if DEBUG + fprintf(stderr, "UNKNOWNTAG_END:%s\n", name); +#endif + xar->xmlsts = xar->xmlsts_unknown; + } + } +} + +static int +xml_start(struct archive_read *a, const char *name, struct xmlattr_list *list) +{ + struct xar *xar; + struct xmlattr *attr; + + xar = (struct xar *)(a->format->data); + +#if DEBUG + fprintf(stderr, "xml_sta:[%s]\n", name); + for (attr = list->first; attr != NULL; attr = attr->next) + fprintf(stderr, " attr:\"%s\"=\"%s\"\n", + attr->name, attr->value); +#endif + xar->base64text = 0; + switch (xar->xmlsts) { + case INIT: + if (strcmp(name, "xar") == 0) + xar->xmlsts = XAR; + else + if (unknowntag_start(a, xar, name) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + break; + case XAR: + if (strcmp(name, "toc") == 0) + xar->xmlsts = TOC; + else + if (unknowntag_start(a, xar, name) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + break; + case TOC: + if (strcmp(name, "creation-time") == 0) + xar->xmlsts = TOC_CREATION_TIME; + else if (strcmp(name, "checksum") == 0) + xar->xmlsts = TOC_CHECKSUM; + else if (strcmp(name, "file") == 0) { + if (file_new(a, xar, list) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + xar->xmlsts = TOC_FILE; + } + else + if (unknowntag_start(a, xar, name) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + break; + case TOC_CHECKSUM: + if (strcmp(name, "offset") == 0) + xar->xmlsts = TOC_CHECKSUM_OFFSET; + else if (strcmp(name, "size") == 0) + xar->xmlsts = TOC_CHECKSUM_SIZE; + else + if (unknowntag_start(a, xar, name) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + break; + case TOC_FILE: + if (strcmp(name, "file") == 0) { + if (file_new(a, xar, list) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + else if (strcmp(name, "data") == 0) + xar->xmlsts = FILE_DATA; + else if (strcmp(name, "ea") == 0) { + if (xattr_new(a, xar, list) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + xar->xmlsts = FILE_EA; + } + else if (strcmp(name, "ctime") == 0) + xar->xmlsts = FILE_CTIME; + else if (strcmp(name, "mtime") == 0) + xar->xmlsts = FILE_MTIME; + else if (strcmp(name, "atime") == 0) + xar->xmlsts = FILE_ATIME; + else if (strcmp(name, "group") == 0) + xar->xmlsts = FILE_GROUP; + else if (strcmp(name, "gid") == 0) + xar->xmlsts = FILE_GID; + else if (strcmp(name, "user") == 0) + xar->xmlsts = FILE_USER; + else if (strcmp(name, "uid") == 0) + xar->xmlsts = FILE_UID; + else if (strcmp(name, "mode") == 0) + xar->xmlsts = FILE_MODE; + else if (strcmp(name, "device") == 0) + xar->xmlsts = FILE_DEVICE; + else if (strcmp(name, "deviceno") == 0) + xar->xmlsts = FILE_DEVICENO; + else if (strcmp(name, "inode") == 0) + xar->xmlsts = FILE_INODE; + else if (strcmp(name, "link") == 0) + xar->xmlsts = FILE_LINK; + else if (strcmp(name, "type") == 0) { + xar->xmlsts = FILE_TYPE; + for (attr = list->first; attr != NULL; + attr = attr->next) { + if (strcmp(attr->name, "link") != 0) + continue; + if (strcmp(attr->value, "original") == 0) { + xar->file->hdnext = xar->hdlink_orgs; + xar->hdlink_orgs = xar->file; + } else { + xar->file->link = (unsigned)atol10(attr->value, + strlen(attr->value)); + if (xar->file->link > 0) + if (add_link(a, xar, xar->file) != ARCHIVE_OK) { + return (ARCHIVE_FATAL); + }; + } + } + } + else if (strcmp(name, "name") == 0) { + xar->xmlsts = FILE_NAME; + for (attr = list->first; attr != NULL; + attr = attr->next) { + if (strcmp(attr->name, "enctype") == 0 && + strcmp(attr->value, "base64") == 0) + xar->base64text = 1; + } + } + else if (strcmp(name, "acl") == 0) + xar->xmlsts = FILE_ACL; + else if (strcmp(name, "flags") == 0) + xar->xmlsts = FILE_FLAGS; + else if (strcmp(name, "ext2") == 0) + xar->xmlsts = FILE_EXT2; + else + if (unknowntag_start(a, xar, name) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + break; + case FILE_DATA: + if (strcmp(name, "length") == 0) + xar->xmlsts = FILE_DATA_LENGTH; + else if (strcmp(name, "offset") == 0) + xar->xmlsts = FILE_DATA_OFFSET; + else if (strcmp(name, "size") == 0) + xar->xmlsts = FILE_DATA_SIZE; + else if (strcmp(name, "encoding") == 0) { + xar->xmlsts = FILE_DATA_ENCODING; + xar->file->encoding = getencoding(list); + } + else if (strcmp(name, "archived-checksum") == 0) { + xar->xmlsts = FILE_DATA_A_CHECKSUM; + xar->file->a_sum.alg = getsumalgorithm(list); + } + else if (strcmp(name, "extracted-checksum") == 0) { + xar->xmlsts = FILE_DATA_E_CHECKSUM; + xar->file->e_sum.alg = getsumalgorithm(list); + } + else if (strcmp(name, "content") == 0) + xar->xmlsts = FILE_DATA_CONTENT; + else + if (unknowntag_start(a, xar, name) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + break; + case FILE_DEVICE: + if (strcmp(name, "major") == 0) + xar->xmlsts = FILE_DEVICE_MAJOR; + else if (strcmp(name, "minor") == 0) + xar->xmlsts = FILE_DEVICE_MINOR; + else + if (unknowntag_start(a, xar, name) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + break; + case FILE_DATA_CONTENT: + if (unknowntag_start(a, xar, name) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + break; + case FILE_EA: + if (strcmp(name, "length") == 0) + xar->xmlsts = FILE_EA_LENGTH; + else if (strcmp(name, "offset") == 0) + xar->xmlsts = FILE_EA_OFFSET; + else if (strcmp(name, "size") == 0) + xar->xmlsts = FILE_EA_SIZE; + else if (strcmp(name, "encoding") == 0) { + xar->xmlsts = FILE_EA_ENCODING; + xar->xattr->encoding = getencoding(list); + } else if (strcmp(name, "archived-checksum") == 0) + xar->xmlsts = FILE_EA_A_CHECKSUM; + else if (strcmp(name, "extracted-checksum") == 0) + xar->xmlsts = FILE_EA_E_CHECKSUM; + else if (strcmp(name, "name") == 0) + xar->xmlsts = FILE_EA_NAME; + else if (strcmp(name, "fstype") == 0) + xar->xmlsts = FILE_EA_FSTYPE; + else + if (unknowntag_start(a, xar, name) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + break; + case FILE_ACL: + if (strcmp(name, "appleextended") == 0) + xar->xmlsts = FILE_ACL_APPLEEXTENDED; + else if (strcmp(name, "default") == 0) + xar->xmlsts = FILE_ACL_DEFAULT; + else if (strcmp(name, "access") == 0) + xar->xmlsts = FILE_ACL_ACCESS; + else + if (unknowntag_start(a, xar, name) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + break; + case FILE_FLAGS: + if (!xml_parse_file_flags(xar, name)) + if (unknowntag_start(a, xar, name) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + break; + case FILE_EXT2: + if (!xml_parse_file_ext2(xar, name)) + if (unknowntag_start(a, xar, name) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + break; + case TOC_CREATION_TIME: + case TOC_CHECKSUM_OFFSET: + case TOC_CHECKSUM_SIZE: + case FILE_DATA_LENGTH: + case FILE_DATA_OFFSET: + case FILE_DATA_SIZE: + case FILE_DATA_ENCODING: + case FILE_DATA_A_CHECKSUM: + case FILE_DATA_E_CHECKSUM: + case FILE_EA_LENGTH: + case FILE_EA_OFFSET: + case FILE_EA_SIZE: + case FILE_EA_ENCODING: + case FILE_EA_A_CHECKSUM: + case FILE_EA_E_CHECKSUM: + case FILE_EA_NAME: + case FILE_EA_FSTYPE: + case FILE_CTIME: + case FILE_MTIME: + case FILE_ATIME: + case FILE_GROUP: + case FILE_GID: + case FILE_USER: + case FILE_UID: + case FILE_INODE: + case FILE_DEVICE_MAJOR: + case FILE_DEVICE_MINOR: + case FILE_DEVICENO: + case FILE_MODE: + case FILE_TYPE: + case FILE_LINK: + case FILE_NAME: + case FILE_ACL_DEFAULT: + case FILE_ACL_ACCESS: + case FILE_ACL_APPLEEXTENDED: + case FILE_FLAGS_USER_NODUMP: + case FILE_FLAGS_USER_IMMUTABLE: + case FILE_FLAGS_USER_APPEND: + case FILE_FLAGS_USER_OPAQUE: + case FILE_FLAGS_USER_NOUNLINK: + case FILE_FLAGS_SYS_ARCHIVED: + case FILE_FLAGS_SYS_IMMUTABLE: + case FILE_FLAGS_SYS_APPEND: + case FILE_FLAGS_SYS_NOUNLINK: + case FILE_FLAGS_SYS_SNAPSHOT: + case FILE_EXT2_SecureDeletion: + case FILE_EXT2_Undelete: + case FILE_EXT2_Compress: + case FILE_EXT2_Synchronous: + case FILE_EXT2_Immutable: + case FILE_EXT2_AppendOnly: + case FILE_EXT2_NoDump: + case FILE_EXT2_NoAtime: + case FILE_EXT2_CompDirty: + case FILE_EXT2_CompBlock: + case FILE_EXT2_NoCompBlock: + case FILE_EXT2_CompError: + case FILE_EXT2_BTree: + case FILE_EXT2_HashIndexed: + case FILE_EXT2_iMagic: + case FILE_EXT2_Journaled: + case FILE_EXT2_NoTail: + case FILE_EXT2_DirSync: + case FILE_EXT2_TopDir: + case FILE_EXT2_Reserved: + case UNKNOWN: + if (unknowntag_start(a, xar, name) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + break; + } + return (ARCHIVE_OK); +} + +static void +xml_end(void *userData, const char *name) +{ + struct archive_read *a; + struct xar *xar; + + a = (struct archive_read *)userData; + xar = (struct xar *)(a->format->data); + +#if DEBUG + fprintf(stderr, "xml_end:[%s]\n", name); +#endif + switch (xar->xmlsts) { + case INIT: + break; + case XAR: + if (strcmp(name, "xar") == 0) + xar->xmlsts = INIT; + break; + case TOC: + if (strcmp(name, "toc") == 0) + xar->xmlsts = XAR; + break; + case TOC_CREATION_TIME: + if (strcmp(name, "creation-time") == 0) + xar->xmlsts = TOC; + break; + case TOC_CHECKSUM: + if (strcmp(name, "checksum") == 0) + xar->xmlsts = TOC; + break; + case TOC_CHECKSUM_OFFSET: + if (strcmp(name, "offset") == 0) + xar->xmlsts = TOC_CHECKSUM; + break; + case TOC_CHECKSUM_SIZE: + if (strcmp(name, "size") == 0) + xar->xmlsts = TOC_CHECKSUM; + break; + case TOC_FILE: + if (strcmp(name, "file") == 0) { + if (xar->file->parent != NULL && + ((xar->file->mode & AE_IFMT) == AE_IFDIR)) + xar->file->parent->subdirs++; + xar->file = xar->file->parent; + if (xar->file == NULL) + xar->xmlsts = TOC; + } + break; + case FILE_DATA: + if (strcmp(name, "data") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_DATA_LENGTH: + if (strcmp(name, "length") == 0) + xar->xmlsts = FILE_DATA; + break; + case FILE_DATA_OFFSET: + if (strcmp(name, "offset") == 0) + xar->xmlsts = FILE_DATA; + break; + case FILE_DATA_SIZE: + if (strcmp(name, "size") == 0) + xar->xmlsts = FILE_DATA; + break; + case FILE_DATA_ENCODING: + if (strcmp(name, "encoding") == 0) + xar->xmlsts = FILE_DATA; + break; + case FILE_DATA_A_CHECKSUM: + if (strcmp(name, "archived-checksum") == 0) + xar->xmlsts = FILE_DATA; + break; + case FILE_DATA_E_CHECKSUM: + if (strcmp(name, "extracted-checksum") == 0) + xar->xmlsts = FILE_DATA; + break; + case FILE_DATA_CONTENT: + if (strcmp(name, "content") == 0) + xar->xmlsts = FILE_DATA; + break; + case FILE_EA: + if (strcmp(name, "ea") == 0) { + xar->xmlsts = TOC_FILE; + xar->xattr = NULL; + } + break; + case FILE_EA_LENGTH: + if (strcmp(name, "length") == 0) + xar->xmlsts = FILE_EA; + break; + case FILE_EA_OFFSET: + if (strcmp(name, "offset") == 0) + xar->xmlsts = FILE_EA; + break; + case FILE_EA_SIZE: + if (strcmp(name, "size") == 0) + xar->xmlsts = FILE_EA; + break; + case FILE_EA_ENCODING: + if (strcmp(name, "encoding") == 0) + xar->xmlsts = FILE_EA; + break; + case FILE_EA_A_CHECKSUM: + if (strcmp(name, "archived-checksum") == 0) + xar->xmlsts = FILE_EA; + break; + case FILE_EA_E_CHECKSUM: + if (strcmp(name, "extracted-checksum") == 0) + xar->xmlsts = FILE_EA; + break; + case FILE_EA_NAME: + if (strcmp(name, "name") == 0) + xar->xmlsts = FILE_EA; + break; + case FILE_EA_FSTYPE: + if (strcmp(name, "fstype") == 0) + xar->xmlsts = FILE_EA; + break; + case FILE_CTIME: + if (strcmp(name, "ctime") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_MTIME: + if (strcmp(name, "mtime") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_ATIME: + if (strcmp(name, "atime") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_GROUP: + if (strcmp(name, "group") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_GID: + if (strcmp(name, "gid") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_USER: + if (strcmp(name, "user") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_UID: + if (strcmp(name, "uid") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_MODE: + if (strcmp(name, "mode") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_DEVICE: + if (strcmp(name, "device") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_DEVICE_MAJOR: + if (strcmp(name, "major") == 0) + xar->xmlsts = FILE_DEVICE; + break; + case FILE_DEVICE_MINOR: + if (strcmp(name, "minor") == 0) + xar->xmlsts = FILE_DEVICE; + break; + case FILE_DEVICENO: + if (strcmp(name, "deviceno") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_INODE: + if (strcmp(name, "inode") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_LINK: + if (strcmp(name, "link") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_TYPE: + if (strcmp(name, "type") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_NAME: + if (strcmp(name, "name") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_ACL: + if (strcmp(name, "acl") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_ACL_DEFAULT: + if (strcmp(name, "default") == 0) + xar->xmlsts = FILE_ACL; + break; + case FILE_ACL_ACCESS: + if (strcmp(name, "access") == 0) + xar->xmlsts = FILE_ACL; + break; + case FILE_ACL_APPLEEXTENDED: + if (strcmp(name, "appleextended") == 0) + xar->xmlsts = FILE_ACL; + break; + case FILE_FLAGS: + if (strcmp(name, "flags") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_FLAGS_USER_NODUMP: + if (strcmp(name, "UserNoDump") == 0) + xar->xmlsts = FILE_FLAGS; + break; + case FILE_FLAGS_USER_IMMUTABLE: + if (strcmp(name, "UserImmutable") == 0) + xar->xmlsts = FILE_FLAGS; + break; + case FILE_FLAGS_USER_APPEND: + if (strcmp(name, "UserAppend") == 0) + xar->xmlsts = FILE_FLAGS; + break; + case FILE_FLAGS_USER_OPAQUE: + if (strcmp(name, "UserOpaque") == 0) + xar->xmlsts = FILE_FLAGS; + break; + case FILE_FLAGS_USER_NOUNLINK: + if (strcmp(name, "UserNoUnlink") == 0) + xar->xmlsts = FILE_FLAGS; + break; + case FILE_FLAGS_SYS_ARCHIVED: + if (strcmp(name, "SystemArchived") == 0) + xar->xmlsts = FILE_FLAGS; + break; + case FILE_FLAGS_SYS_IMMUTABLE: + if (strcmp(name, "SystemImmutable") == 0) + xar->xmlsts = FILE_FLAGS; + break; + case FILE_FLAGS_SYS_APPEND: + if (strcmp(name, "SystemAppend") == 0) + xar->xmlsts = FILE_FLAGS; + break; + case FILE_FLAGS_SYS_NOUNLINK: + if (strcmp(name, "SystemNoUnlink") == 0) + xar->xmlsts = FILE_FLAGS; + break; + case FILE_FLAGS_SYS_SNAPSHOT: + if (strcmp(name, "SystemSnapshot") == 0) + xar->xmlsts = FILE_FLAGS; + break; + case FILE_EXT2: + if (strcmp(name, "ext2") == 0) + xar->xmlsts = TOC_FILE; + break; + case FILE_EXT2_SecureDeletion: + if (strcmp(name, "SecureDeletion") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_Undelete: + if (strcmp(name, "Undelete") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_Compress: + if (strcmp(name, "Compress") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_Synchronous: + if (strcmp(name, "Synchronous") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_Immutable: + if (strcmp(name, "Immutable") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_AppendOnly: + if (strcmp(name, "AppendOnly") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_NoDump: + if (strcmp(name, "NoDump") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_NoAtime: + if (strcmp(name, "NoAtime") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_CompDirty: + if (strcmp(name, "CompDirty") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_CompBlock: + if (strcmp(name, "CompBlock") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_NoCompBlock: + if (strcmp(name, "NoCompBlock") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_CompError: + if (strcmp(name, "CompError") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_BTree: + if (strcmp(name, "BTree") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_HashIndexed: + if (strcmp(name, "HashIndexed") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_iMagic: + if (strcmp(name, "iMagic") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_Journaled: + if (strcmp(name, "Journaled") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_NoTail: + if (strcmp(name, "NoTail") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_DirSync: + if (strcmp(name, "DirSync") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_TopDir: + if (strcmp(name, "TopDir") == 0) + xar->xmlsts = FILE_EXT2; + break; + case FILE_EXT2_Reserved: + if (strcmp(name, "Reserved") == 0) + xar->xmlsts = FILE_EXT2; + break; + case UNKNOWN: + unknowntag_end(xar, name); + break; + } +} + +static const int base64[256] = { + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, /* 00 - 0F */ + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, /* 10 - 1F */ + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 62, -1, -1, -1, 63, /* 20 - 2F */ + 52, 53, 54, 55, 56, 57, 58, 59, + 60, 61, -1, -1, -1, -1, -1, -1, /* 30 - 3F */ + -1, 0, 1, 2, 3, 4, 5, 6, + 7, 8, 9, 10, 11, 12, 13, 14, /* 40 - 4F */ + 15, 16, 17, 18, 19, 20, 21, 22, + 23, 24, 25, -1, -1, -1, -1, -1, /* 50 - 5F */ + -1, 26, 27, 28, 29, 30, 31, 32, + 33, 34, 35, 36, 37, 38, 39, 40, /* 60 - 6F */ + 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, -1, -1, -1, -1, -1, /* 70 - 7F */ + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, /* 80 - 8F */ + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, /* 90 - 9F */ + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, /* A0 - AF */ + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, /* B0 - BF */ + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, /* C0 - CF */ + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, /* D0 - DF */ + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, /* E0 - EF */ + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, /* F0 - FF */ +}; + +static void +strappend_base64(struct xar *xar, + struct archive_string *as, const char *s, size_t l) +{ + unsigned char buff[256]; + unsigned char *out; + const unsigned char *b; + size_t len; + + (void)xar; /* UNUSED */ + len = 0; + out = buff; + b = (const unsigned char *)s; + while (l > 0) { + int n = 0; + + if (base64[b[0]] < 0 || base64[b[1]] < 0) + break; + n = base64[*b++] << 18; + n |= base64[*b++] << 12; + *out++ = n >> 16; + len++; + l -= 2; + + if (l > 0) { + if (base64[*b] < 0) + break; + n |= base64[*b++] << 6; + *out++ = (n >> 8) & 0xFF; + len++; + --l; + } + if (l > 0) { + if (base64[*b] < 0) + break; + n |= base64[*b++]; + *out++ = n & 0xFF; + len++; + --l; + } + if (len+3 >= sizeof(buff)) { + archive_strncat(as, (const char *)buff, len); + len = 0; + out = buff; + } + } + if (len > 0) + archive_strncat(as, (const char *)buff, len); +} + +static int +is_string(const char *known, const char *data, size_t len) +{ + if (strlen(known) != len) + return -1; + return memcmp(data, known, len); +} + +static void +xml_data(void *userData, const char *s, int len) +{ + struct archive_read *a; + struct xar *xar; + + a = (struct archive_read *)userData; + xar = (struct xar *)(a->format->data); + +#if DEBUG + { + char buff[1024]; + if (len > (int)(sizeof(buff)-1)) + len = (int)(sizeof(buff)-1); + strncpy(buff, s, len); + buff[len] = 0; + fprintf(stderr, "\tlen=%d:\"%s\"\n", len, buff); + } +#endif + switch (xar->xmlsts) { + case TOC_CHECKSUM_OFFSET: + xar->toc_chksum_offset = atol10(s, len); + break; + case TOC_CHECKSUM_SIZE: + xar->toc_chksum_size = atol10(s, len); + break; + default: + break; + } + if (xar->file == NULL) + return; + + switch (xar->xmlsts) { + case FILE_NAME: + if (xar->file->parent != NULL) { + archive_string_concat(&(xar->file->pathname), + &(xar->file->parent->pathname)); + archive_strappend_char(&(xar->file->pathname), '/'); + } + xar->file->has |= HAS_PATHNAME; + if (xar->base64text) { + strappend_base64(xar, + &(xar->file->pathname), s, len); + } else + archive_strncat(&(xar->file->pathname), s, len); + break; + case FILE_LINK: + xar->file->has |= HAS_SYMLINK; + archive_strncpy(&(xar->file->symlink), s, len); + break; + case FILE_TYPE: + if (is_string("file", s, len) == 0 || + is_string("hardlink", s, len) == 0) + xar->file->mode = + (xar->file->mode & ~AE_IFMT) | AE_IFREG; + if (is_string("directory", s, len) == 0) + xar->file->mode = + (xar->file->mode & ~AE_IFMT) | AE_IFDIR; + if (is_string("symlink", s, len) == 0) + xar->file->mode = + (xar->file->mode & ~AE_IFMT) | AE_IFLNK; + if (is_string("character special", s, len) == 0) + xar->file->mode = + (xar->file->mode & ~AE_IFMT) | AE_IFCHR; + if (is_string("block special", s, len) == 0) + xar->file->mode = + (xar->file->mode & ~AE_IFMT) | AE_IFBLK; + if (is_string("socket", s, len) == 0) + xar->file->mode = + (xar->file->mode & ~AE_IFMT) | AE_IFSOCK; + if (is_string("fifo", s, len) == 0) + xar->file->mode = + (xar->file->mode & ~AE_IFMT) | AE_IFIFO; + xar->file->has |= HAS_TYPE; + break; + case FILE_INODE: + xar->file->has |= HAS_INO; + xar->file->ino64 = atol10(s, len); + break; + case FILE_DEVICE_MAJOR: + xar->file->has |= HAS_DEVMAJOR; + xar->file->devmajor = (dev_t)atol10(s, len); + break; + case FILE_DEVICE_MINOR: + xar->file->has |= HAS_DEVMINOR; + xar->file->devminor = (dev_t)atol10(s, len); + break; + case FILE_DEVICENO: + xar->file->has |= HAS_DEV; + xar->file->dev = (dev_t)atol10(s, len); + break; + case FILE_MODE: + xar->file->has |= HAS_MODE; + xar->file->mode = + (xar->file->mode & AE_IFMT) | + ((mode_t)(atol8(s, len)) & ~AE_IFMT); + break; + case FILE_GROUP: + xar->file->has |= HAS_GID; + archive_strncpy(&(xar->file->gname), s, len); + break; + case FILE_GID: + xar->file->has |= HAS_GID; + xar->file->gid = atol10(s, len); + break; + case FILE_USER: + xar->file->has |= HAS_UID; + archive_strncpy(&(xar->file->uname), s, len); + break; + case FILE_UID: + xar->file->has |= HAS_UID; + xar->file->uid = atol10(s, len); + break; + case FILE_CTIME: + xar->file->has |= HAS_TIME | HAS_CTIME; + xar->file->ctime = parse_time(s, len); + break; + case FILE_MTIME: + xar->file->has |= HAS_TIME | HAS_MTIME; + xar->file->mtime = parse_time(s, len); + break; + case FILE_ATIME: + xar->file->has |= HAS_TIME | HAS_ATIME; + xar->file->atime = parse_time(s, len); + break; + case FILE_DATA_LENGTH: + xar->file->has |= HAS_DATA; + xar->file->length = atol10(s, len); + break; + case FILE_DATA_OFFSET: + xar->file->has |= HAS_DATA; + xar->file->offset = atol10(s, len); + break; + case FILE_DATA_SIZE: + xar->file->has |= HAS_DATA; + xar->file->size = atol10(s, len); + break; + case FILE_DATA_A_CHECKSUM: + xar->file->a_sum.len = atohex(xar->file->a_sum.val, + sizeof(xar->file->a_sum.val), s, len); + break; + case FILE_DATA_E_CHECKSUM: + xar->file->e_sum.len = atohex(xar->file->e_sum.val, + sizeof(xar->file->e_sum.val), s, len); + break; + case FILE_EA_LENGTH: + xar->file->has |= HAS_XATTR; + xar->xattr->length = atol10(s, len); + break; + case FILE_EA_OFFSET: + xar->file->has |= HAS_XATTR; + xar->xattr->offset = atol10(s, len); + break; + case FILE_EA_SIZE: + xar->file->has |= HAS_XATTR; + xar->xattr->size = atol10(s, len); + break; + case FILE_EA_A_CHECKSUM: + xar->file->has |= HAS_XATTR; + xar->xattr->a_sum.len = atohex(xar->xattr->a_sum.val, + sizeof(xar->xattr->a_sum.val), s, len); + break; + case FILE_EA_E_CHECKSUM: + xar->file->has |= HAS_XATTR; + xar->xattr->e_sum.len = atohex(xar->xattr->e_sum.val, + sizeof(xar->xattr->e_sum.val), s, len); + break; + case FILE_EA_NAME: + xar->file->has |= HAS_XATTR; + archive_strncpy(&(xar->xattr->name), s, len); + break; + case FILE_EA_FSTYPE: + xar->file->has |= HAS_XATTR; + archive_strncpy(&(xar->xattr->fstype), s, len); + break; + break; + case FILE_ACL_DEFAULT: + case FILE_ACL_ACCESS: + case FILE_ACL_APPLEEXTENDED: + xar->file->has |= HAS_ACL; + /* TODO */ + break; + case INIT: + case XAR: + case TOC: + case TOC_CREATION_TIME: + case TOC_CHECKSUM: + case TOC_CHECKSUM_OFFSET: + case TOC_CHECKSUM_SIZE: + case TOC_FILE: + case FILE_DATA: + case FILE_DATA_ENCODING: + case FILE_DATA_CONTENT: + case FILE_DEVICE: + case FILE_EA: + case FILE_EA_ENCODING: + case FILE_ACL: + case FILE_FLAGS: + case FILE_FLAGS_USER_NODUMP: + case FILE_FLAGS_USER_IMMUTABLE: + case FILE_FLAGS_USER_APPEND: + case FILE_FLAGS_USER_OPAQUE: + case FILE_FLAGS_USER_NOUNLINK: + case FILE_FLAGS_SYS_ARCHIVED: + case FILE_FLAGS_SYS_IMMUTABLE: + case FILE_FLAGS_SYS_APPEND: + case FILE_FLAGS_SYS_NOUNLINK: + case FILE_FLAGS_SYS_SNAPSHOT: + case FILE_EXT2: + case FILE_EXT2_SecureDeletion: + case FILE_EXT2_Undelete: + case FILE_EXT2_Compress: + case FILE_EXT2_Synchronous: + case FILE_EXT2_Immutable: + case FILE_EXT2_AppendOnly: + case FILE_EXT2_NoDump: + case FILE_EXT2_NoAtime: + case FILE_EXT2_CompDirty: + case FILE_EXT2_CompBlock: + case FILE_EXT2_NoCompBlock: + case FILE_EXT2_CompError: + case FILE_EXT2_BTree: + case FILE_EXT2_HashIndexed: + case FILE_EXT2_iMagic: + case FILE_EXT2_Journaled: + case FILE_EXT2_NoTail: + case FILE_EXT2_DirSync: + case FILE_EXT2_TopDir: + case FILE_EXT2_Reserved: + case UNKNOWN: + break; + } +} + +/* + * BSD file flags. + */ +static int +xml_parse_file_flags(struct xar *xar, const char *name) +{ + const char *flag = NULL; + + if (strcmp(name, "UserNoDump") == 0) { + xar->xmlsts = FILE_FLAGS_USER_NODUMP; + flag = "nodump"; + } + else if (strcmp(name, "UserImmutable") == 0) { + xar->xmlsts = FILE_FLAGS_USER_IMMUTABLE; + flag = "uimmutable"; + } + else if (strcmp(name, "UserAppend") == 0) { + xar->xmlsts = FILE_FLAGS_USER_APPEND; + flag = "uappend"; + } + else if (strcmp(name, "UserOpaque") == 0) { + xar->xmlsts = FILE_FLAGS_USER_OPAQUE; + flag = "opaque"; + } + else if (strcmp(name, "UserNoUnlink") == 0) { + xar->xmlsts = FILE_FLAGS_USER_NOUNLINK; + flag = "nouunlink"; + } + else if (strcmp(name, "SystemArchived") == 0) { + xar->xmlsts = FILE_FLAGS_SYS_ARCHIVED; + flag = "archived"; + } + else if (strcmp(name, "SystemImmutable") == 0) { + xar->xmlsts = FILE_FLAGS_SYS_IMMUTABLE; + flag = "simmutable"; + } + else if (strcmp(name, "SystemAppend") == 0) { + xar->xmlsts = FILE_FLAGS_SYS_APPEND; + flag = "sappend"; + } + else if (strcmp(name, "SystemNoUnlink") == 0) { + xar->xmlsts = FILE_FLAGS_SYS_NOUNLINK; + flag = "nosunlink"; + } + else if (strcmp(name, "SystemSnapshot") == 0) { + xar->xmlsts = FILE_FLAGS_SYS_SNAPSHOT; + flag = "snapshot"; + } + + if (flag == NULL) + return (0); + xar->file->has |= HAS_FFLAGS; + if (archive_strlen(&(xar->file->fflags_text)) > 0) + archive_strappend_char(&(xar->file->fflags_text), ','); + archive_strcat(&(xar->file->fflags_text), flag); + return (1); +} + +/* + * Linux file flags. + */ +static int +xml_parse_file_ext2(struct xar *xar, const char *name) +{ + const char *flag = NULL; + + if (strcmp(name, "SecureDeletion") == 0) { + xar->xmlsts = FILE_EXT2_SecureDeletion; + flag = "securedeletion"; + } + else if (strcmp(name, "Undelete") == 0) { + xar->xmlsts = FILE_EXT2_Undelete; + flag = "nouunlink"; + } + else if (strcmp(name, "Compress") == 0) { + xar->xmlsts = FILE_EXT2_Compress; + flag = "compress"; + } + else if (strcmp(name, "Synchronous") == 0) { + xar->xmlsts = FILE_EXT2_Synchronous; + flag = "sync"; + } + else if (strcmp(name, "Immutable") == 0) { + xar->xmlsts = FILE_EXT2_Immutable; + flag = "simmutable"; + } + else if (strcmp(name, "AppendOnly") == 0) { + xar->xmlsts = FILE_EXT2_AppendOnly; + flag = "sappend"; + } + else if (strcmp(name, "NoDump") == 0) { + xar->xmlsts = FILE_EXT2_NoDump; + flag = "nodump"; + } + else if (strcmp(name, "NoAtime") == 0) { + xar->xmlsts = FILE_EXT2_NoAtime; + flag = "noatime"; + } + else if (strcmp(name, "CompDirty") == 0) { + xar->xmlsts = FILE_EXT2_CompDirty; + flag = "compdirty"; + } + else if (strcmp(name, "CompBlock") == 0) { + xar->xmlsts = FILE_EXT2_CompBlock; + flag = "comprblk"; + } + else if (strcmp(name, "NoCompBlock") == 0) { + xar->xmlsts = FILE_EXT2_NoCompBlock; + flag = "nocomprblk"; + } + else if (strcmp(name, "CompError") == 0) { + xar->xmlsts = FILE_EXT2_CompError; + flag = "comperr"; + } + else if (strcmp(name, "BTree") == 0) { + xar->xmlsts = FILE_EXT2_BTree; + flag = "btree"; + } + else if (strcmp(name, "HashIndexed") == 0) { + xar->xmlsts = FILE_EXT2_HashIndexed; + flag = "hashidx"; + } + else if (strcmp(name, "iMagic") == 0) { + xar->xmlsts = FILE_EXT2_iMagic; + flag = "imagic"; + } + else if (strcmp(name, "Journaled") == 0) { + xar->xmlsts = FILE_EXT2_Journaled; + flag = "journal"; + } + else if (strcmp(name, "NoTail") == 0) { + xar->xmlsts = FILE_EXT2_NoTail; + flag = "notail"; + } + else if (strcmp(name, "DirSync") == 0) { + xar->xmlsts = FILE_EXT2_DirSync; + flag = "dirsync"; + } + else if (strcmp(name, "TopDir") == 0) { + xar->xmlsts = FILE_EXT2_TopDir; + flag = "topdir"; + } + else if (strcmp(name, "Reserved") == 0) { + xar->xmlsts = FILE_EXT2_Reserved; + flag = "reserved"; + } + + if (flag == NULL) + return (0); + if (archive_strlen(&(xar->file->fflags_text)) > 0) + archive_strappend_char(&(xar->file->fflags_text), ','); + archive_strcat(&(xar->file->fflags_text), flag); + return (1); +} + +#ifdef HAVE_LIBXML_XMLREADER_H + +static int +xml2_xmlattr_setup(struct archive_read *a, + struct xmlattr_list *list, xmlTextReaderPtr reader) +{ + struct xmlattr *attr; + int r; + + list->first = NULL; + list->last = &(list->first); + r = xmlTextReaderMoveToFirstAttribute(reader); + while (r == 1) { + attr = malloc(sizeof*(attr)); + if (attr == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + attr->name = strdup( + (const char *)xmlTextReaderConstLocalName(reader)); + if (attr->name == NULL) { + free(attr); + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + attr->value = strdup( + (const char *)xmlTextReaderConstValue(reader)); + if (attr->value == NULL) { + free(attr->name); + free(attr); + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + attr->next = NULL; + *list->last = attr; + list->last = &(attr->next); + r = xmlTextReaderMoveToNextAttribute(reader); + } + return (r); +} + +static int +xml2_read_cb(void *context, char *buffer, int len) +{ + struct archive_read *a; + struct xar *xar; + const void *d; + size_t outbytes; + size_t used = 0; + int r; + + a = (struct archive_read *)context; + xar = (struct xar *)(a->format->data); + + if (xar->toc_remaining <= 0) + return (0); + d = buffer; + outbytes = len; + r = rd_contents(a, &d, &outbytes, &used, xar->toc_remaining); + if (r != ARCHIVE_OK) + return (r); + __archive_read_consume(a, used); + xar->toc_remaining -= used; + xar->offset += used; + xar->toc_total += outbytes; + PRINT_TOC(buffer, len); + + return ((int)outbytes); +} + +static int +xml2_close_cb(void *context) +{ + + (void)context; /* UNUSED */ + return (0); +} + +static void +xml2_error_hdr(void *arg, const char *msg, xmlParserSeverities severity, + xmlTextReaderLocatorPtr locator) +{ + struct archive_read *a; + + (void)locator; /* UNUSED */ + a = (struct archive_read *)arg; + switch (severity) { + case XML_PARSER_SEVERITY_VALIDITY_WARNING: + case XML_PARSER_SEVERITY_WARNING: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "XML Parsing error: %s", msg); + break; + case XML_PARSER_SEVERITY_VALIDITY_ERROR: + case XML_PARSER_SEVERITY_ERROR: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "XML Parsing error: %s", msg); + break; + } +} + +static int +xml2_read_toc(struct archive_read *a) +{ + xmlTextReaderPtr reader; + struct xmlattr_list list; + int r; + + reader = xmlReaderForIO(xml2_read_cb, xml2_close_cb, a, NULL, NULL, 0); + if (reader == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Couldn't allocate memory for xml parser"); + return (ARCHIVE_FATAL); + } + xmlTextReaderSetErrorHandler(reader, xml2_error_hdr, a); + + while ((r = xmlTextReaderRead(reader)) == 1) { + const char *name, *value; + int type, empty; + + type = xmlTextReaderNodeType(reader); + name = (const char *)xmlTextReaderConstLocalName(reader); + switch (type) { + case XML_READER_TYPE_ELEMENT: + empty = xmlTextReaderIsEmptyElement(reader); + r = xml2_xmlattr_setup(a, &list, reader); + if (r == ARCHIVE_OK) + r = xml_start(a, name, &list); + xmlattr_cleanup(&list); + if (r != ARCHIVE_OK) + return (r); + if (empty) + xml_end(a, name); + break; + case XML_READER_TYPE_END_ELEMENT: + xml_end(a, name); + break; + case XML_READER_TYPE_TEXT: + value = (const char *)xmlTextReaderConstValue(reader); + xml_data(a, value, strlen(value)); + break; + case XML_READER_TYPE_SIGNIFICANT_WHITESPACE: + default: + break; + } + if (r < 0) + break; + } + xmlFreeTextReader(reader); + xmlCleanupParser(); + + return ((r == 0)?ARCHIVE_OK:ARCHIVE_FATAL); +} + +#elif defined(HAVE_BSDXML_H) || defined(HAVE_EXPAT_H) + +static int +expat_xmlattr_setup(struct archive_read *a, + struct xmlattr_list *list, const XML_Char **atts) +{ + struct xmlattr *attr; + char *name, *value; + + list->first = NULL; + list->last = &(list->first); + if (atts == NULL) + return (ARCHIVE_OK); + while (atts[0] != NULL && atts[1] != NULL) { + attr = malloc(sizeof*(attr)); + name = strdup(atts[0]); + value = strdup(atts[1]); + if (attr == NULL || name == NULL || value == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + free(attr); + free(name); + free(value); + return (ARCHIVE_FATAL); + } + attr->name = name; + attr->value = value; + attr->next = NULL; + *list->last = attr; + list->last = &(attr->next); + atts += 2; + } + return (ARCHIVE_OK); +} + +static void +expat_start_cb(void *userData, const XML_Char *name, const XML_Char **atts) +{ + struct expat_userData *ud = (struct expat_userData *)userData; + struct archive_read *a = ud->archive; + struct xmlattr_list list; + int r; + + r = expat_xmlattr_setup(a, &list, atts); + if (r == ARCHIVE_OK) + r = xml_start(a, (const char *)name, &list); + xmlattr_cleanup(&list); + ud->state = r; +} + +static void +expat_end_cb(void *userData, const XML_Char *name) +{ + struct expat_userData *ud = (struct expat_userData *)userData; + + xml_end(ud->archive, (const char *)name); +} + +static void +expat_data_cb(void *userData, const XML_Char *s, int len) +{ + struct expat_userData *ud = (struct expat_userData *)userData; + + xml_data(ud->archive, s, len); +} + +static int +expat_read_toc(struct archive_read *a) +{ + struct xar *xar; + XML_Parser parser; + struct expat_userData ud; + + ud.state = ARCHIVE_OK; + ud.archive = a; + + xar = (struct xar *)(a->format->data); + + /* Initialize XML Parser library. */ + parser = XML_ParserCreate(NULL); + if (parser == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Couldn't allocate memory for xml parser"); + return (ARCHIVE_FATAL); + } + XML_SetUserData(parser, &ud); + XML_SetElementHandler(parser, expat_start_cb, expat_end_cb); + XML_SetCharacterDataHandler(parser, expat_data_cb); + xar->xmlsts = INIT; + + while (xar->toc_remaining && ud.state == ARCHIVE_OK) { + enum XML_Status xr; + const void *d; + size_t outbytes; + size_t used; + int r; + + d = NULL; + r = rd_contents(a, &d, &outbytes, &used, xar->toc_remaining); + if (r != ARCHIVE_OK) + return (r); + xar->toc_remaining -= used; + xar->offset += used; + xar->toc_total += outbytes; + PRINT_TOC(d, outbytes); + + xr = XML_Parse(parser, d, outbytes, xar->toc_remaining == 0); + __archive_read_consume(a, used); + if (xr == XML_STATUS_ERROR) { + XML_ParserFree(parser); + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "XML Parsing failed"); + return (ARCHIVE_FATAL); + } + } + XML_ParserFree(parser); + return (ud.state); +} +#endif /* defined(HAVE_BSDXML_H) || defined(HAVE_EXPAT_H) */ + +#endif /* Support xar format */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_zip.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_zip.c new file mode 100644 index 0000000000..6581ca0acf --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_read_support_format_zip.c @@ -0,0 +1,4044 @@ +/*- + * Copyright (c) 2004-2013 Tim Kientzle + * Copyright (c) 2011-2012,2014 Michihiro NAKAJIMA + * Copyright (c) 2013 Konrad Kleine + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_zip.c 201102 2009-12-28 03:11:36Z kientzle $"); + +/* + * The definitive documentation of the Zip file format is: + * http://www.pkware.com/documents/casestudies/APPNOTE.TXT + * + * The Info-Zip project has pioneered various extensions to better + * support Zip on Unix, including the 0x5455 "UT", 0x5855 "UX", 0x7855 + * "Ux", and 0x7875 "ux" extensions for time and ownership + * information. + * + * History of this code: The streaming Zip reader was first added to + * libarchive in January 2005. Support for seekable input sources was + * added in Nov 2011. Zip64 support (including a significant code + * refactoring) was added in 2014. + */ + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_ZLIB_H +#include <zlib.h> +#endif +#ifdef HAVE_BZLIB_H +#include <bzlib.h> +#endif +#ifdef HAVE_LZMA_H +#include <lzma.h> +#endif + +#include "archive.h" +#include "archive_digest_private.h" +#include "archive_cryptor_private.h" +#include "archive_endian.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_hmac_private.h" +#include "archive_private.h" +#include "archive_rb.h" +#include "archive_read_private.h" +#include "archive_ppmd8_private.h" + +#ifndef HAVE_ZLIB_H +#include "archive_crc32.h" +#endif + +struct zip_entry { + struct archive_rb_node node; + struct zip_entry *next; + int64_t local_header_offset; + int64_t compressed_size; + int64_t uncompressed_size; + int64_t gid; + int64_t uid; + struct archive_string rsrcname; + time_t mtime; + time_t atime; + time_t ctime; + uint32_t crc32; + uint16_t mode; + uint16_t zip_flags; /* From GP Flags Field */ + unsigned char compression; + unsigned char system; /* From "version written by" */ + unsigned char flags; /* Our extra markers. */ + unsigned char decdat;/* Used for Decryption check */ + + /* WinZip AES encryption extra field should be available + * when compression is 99. */ + struct { + /* Vendor version: AE-1 - 0x0001, AE-2 - 0x0002 */ + unsigned vendor; +#define AES_VENDOR_AE_1 0x0001 +#define AES_VENDOR_AE_2 0x0002 + /* AES encryption strength: + * 1 - 128 bits, 2 - 192 bits, 2 - 256 bits. */ + unsigned strength; + /* Actual compression method. */ + unsigned char compression; + } aes_extra; +}; + +struct trad_enc_ctx { + uint32_t keys[3]; +}; + +/* Bits used in zip_flags. */ +#define ZIP_ENCRYPTED (1 << 0) +#define ZIP_LENGTH_AT_END (1 << 3) +#define ZIP_STRONG_ENCRYPTED (1 << 6) +#define ZIP_UTF8_NAME (1 << 11) +/* See "7.2 Single Password Symmetric Encryption Method" + in http://www.pkware.com/documents/casestudies/APPNOTE.TXT */ +#define ZIP_CENTRAL_DIRECTORY_ENCRYPTED (1 << 13) + +/* Bits used in flags. */ +#define LA_USED_ZIP64 (1 << 0) +#define LA_FROM_CENTRAL_DIRECTORY (1 << 1) + +/* + * See "WinZip - AES Encryption Information" + * http://www.winzip.com/aes_info.htm + */ +/* Value used in compression method. */ +#define WINZIP_AES_ENCRYPTION 99 +/* Authentication code size. */ +#define AUTH_CODE_SIZE 10 +/**/ +#define MAX_DERIVED_KEY_BUF_SIZE (AES_MAX_KEY_SIZE * 2 + 2) + +struct zip { + /* Structural information about the archive. */ + struct archive_string format_name; + int64_t central_directory_offset; + size_t central_directory_entries_total; + size_t central_directory_entries_on_this_disk; + int has_encrypted_entries; + + /* List of entries (seekable Zip only) */ + struct zip_entry *zip_entries; + struct archive_rb_tree tree; + struct archive_rb_tree tree_rsrc; + + /* Bytes read but not yet consumed via __archive_read_consume() */ + size_t unconsumed; + + /* Information about entry we're currently reading. */ + struct zip_entry *entry; + int64_t entry_bytes_remaining; + + /* These count the number of bytes actually read for the entry. */ + int64_t entry_compressed_bytes_read; + int64_t entry_uncompressed_bytes_read; + + /* Running CRC32 of the decompressed data */ + unsigned long entry_crc32; + unsigned long (*crc32func)(unsigned long, const void *, + size_t); + char ignore_crc32; + + /* Flags to mark progress of decompression. */ + char decompress_init; + char end_of_entry; + + unsigned char *uncompressed_buffer; + size_t uncompressed_buffer_size; + +#ifdef HAVE_ZLIB_H + z_stream stream; + char stream_valid; +#endif + +#if HAVE_LZMA_H && HAVE_LIBLZMA + lzma_stream zipx_lzma_stream; + char zipx_lzma_valid; +#endif + +#ifdef HAVE_BZLIB_H + bz_stream bzstream; + char bzstream_valid; +#endif + + IByteIn zipx_ppmd_stream; + ssize_t zipx_ppmd_read_compressed; + CPpmd8 ppmd8; + char ppmd8_valid; + char ppmd8_stream_failed; + + struct archive_string_conv *sconv; + struct archive_string_conv *sconv_default; + struct archive_string_conv *sconv_utf8; + int init_default_conversion; + int process_mac_extensions; + + char init_decryption; + + /* Decryption buffer. */ + /* + * The decrypted data starts at decrypted_ptr and + * extends for decrypted_bytes_remaining. Decryption + * adds new data to the end of this block, data is returned + * to clients from the beginning. When the block hits the + * end of decrypted_buffer, it has to be shuffled back to + * the beginning of the buffer. + */ + unsigned char *decrypted_buffer; + unsigned char *decrypted_ptr; + size_t decrypted_buffer_size; + size_t decrypted_bytes_remaining; + size_t decrypted_unconsumed_bytes; + + /* Traditional PKWARE decryption. */ + struct trad_enc_ctx tctx; + char tctx_valid; + + /* WinZip AES decryption. */ + /* Contexts used for AES decryption. */ + archive_crypto_ctx cctx; + char cctx_valid; + archive_hmac_sha1_ctx hctx; + char hctx_valid; + + /* Strong encryption's decryption header information. */ + unsigned iv_size; + unsigned alg_id; + unsigned bit_len; + unsigned flags; + unsigned erd_size; + unsigned v_size; + unsigned v_crc32; + uint8_t *iv; + uint8_t *erd; + uint8_t *v_data; +}; + +/* Many systems define min or MIN, but not all. */ +#define zipmin(a,b) ((a) < (b) ? (a) : (b)) + +/* This function is used by Ppmd8_DecodeSymbol during decompression of Ppmd8 + * streams inside ZIP files. It has 2 purposes: one is to fetch the next + * compressed byte from the stream, second one is to increase the counter how + * many compressed bytes were read. */ +static Byte +ppmd_read(void* p) { + /* Get the handle to current decompression context. */ + struct archive_read *a = ((IByteIn*)p)->a; + struct zip *zip = (struct zip*) a->format->data; + ssize_t bytes_avail = 0; + + /* Fetch next byte. */ + const uint8_t* data = __archive_read_ahead(a, 1, &bytes_avail); + if(bytes_avail < 1) { + zip->ppmd8_stream_failed = 1; + return 0; + } + + __archive_read_consume(a, 1); + + /* Increment the counter. */ + ++zip->zipx_ppmd_read_compressed; + + /* Return the next compressed byte. */ + return data[0]; +} + +/* ------------------------------------------------------------------------ */ + +/* + Traditional PKWARE Decryption functions. + */ + +static void +trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c) +{ + uint8_t t; +#define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL) + + ctx->keys[0] = CRC32(ctx->keys[0], c); + ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1; + t = (ctx->keys[1] >> 24) & 0xff; + ctx->keys[2] = CRC32(ctx->keys[2], t); +#undef CRC32 +} + +static uint8_t +trad_enc_decrypt_byte(struct trad_enc_ctx *ctx) +{ + unsigned temp = ctx->keys[2] | 2; + return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff; +} + +static void +trad_enc_decrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in, + size_t in_len, uint8_t *out, size_t out_len) +{ + unsigned i, max; + + max = (unsigned)((in_len < out_len)? in_len: out_len); + + for (i = 0; i < max; i++) { + uint8_t t = in[i] ^ trad_enc_decrypt_byte(ctx); + out[i] = t; + trad_enc_update_keys(ctx, t); + } +} + +static int +trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len, + const uint8_t *key, size_t key_len, uint8_t *crcchk) +{ + uint8_t header[12]; + + if (key_len < 12) { + *crcchk = 0xff; + return -1; + } + + ctx->keys[0] = 305419896L; + ctx->keys[1] = 591751049L; + ctx->keys[2] = 878082192L; + + for (;pw_len; --pw_len) + trad_enc_update_keys(ctx, *pw++); + + trad_enc_decrypt_update(ctx, key, 12, header, 12); + /* Return the last byte for CRC check. */ + *crcchk = header[11]; + return 0; +} + +#if 0 +static void +crypt_derive_key_sha1(const void *p, int size, unsigned char *key, + int key_size) +{ +#define MD_SIZE 20 + archive_sha1_ctx ctx; + unsigned char md1[MD_SIZE]; + unsigned char md2[MD_SIZE * 2]; + unsigned char mkb[64]; + int i; + + archive_sha1_init(&ctx); + archive_sha1_update(&ctx, p, size); + archive_sha1_final(&ctx, md1); + + memset(mkb, 0x36, sizeof(mkb)); + for (i = 0; i < MD_SIZE; i++) + mkb[i] ^= md1[i]; + archive_sha1_init(&ctx); + archive_sha1_update(&ctx, mkb, sizeof(mkb)); + archive_sha1_final(&ctx, md2); + + memset(mkb, 0x5C, sizeof(mkb)); + for (i = 0; i < MD_SIZE; i++) + mkb[i] ^= md1[i]; + archive_sha1_init(&ctx); + archive_sha1_update(&ctx, mkb, sizeof(mkb)); + archive_sha1_final(&ctx, md2 + MD_SIZE); + + if (key_size > 32) + key_size = 32; + memcpy(key, md2, key_size); +#undef MD_SIZE +} +#endif + +/* + * Common code for streaming or seeking modes. + * + * Includes code to read local file headers, decompress data + * from entry bodies, and common API. + */ + +static unsigned long +real_crc32(unsigned long crc, const void *buff, size_t len) +{ + return crc32(crc, buff, (unsigned int)len); +} + +/* Used by "ignorecrc32" option to speed up tests. */ +static unsigned long +fake_crc32(unsigned long crc, const void *buff, size_t len) +{ + (void)crc; /* UNUSED */ + (void)buff; /* UNUSED */ + (void)len; /* UNUSED */ + return 0; +} + +static const struct { + int id; + const char * name; +} compression_methods[] = { + {0, "uncompressed"}, /* The file is stored (no compression) */ + {1, "shrinking"}, /* The file is Shrunk */ + {2, "reduced-1"}, /* The file is Reduced with compression factor 1 */ + {3, "reduced-2"}, /* The file is Reduced with compression factor 2 */ + {4, "reduced-3"}, /* The file is Reduced with compression factor 3 */ + {5, "reduced-4"}, /* The file is Reduced with compression factor 4 */ + {6, "imploded"}, /* The file is Imploded */ + {7, "reserved"}, /* Reserved for Tokenizing compression algorithm */ + {8, "deflation"}, /* The file is Deflated */ + {9, "deflation-64-bit"}, /* Enhanced Deflating using Deflate64(tm) */ + {10, "ibm-terse"},/* PKWARE Data Compression Library Imploding + * (old IBM TERSE) */ + {11, "reserved"}, /* Reserved by PKWARE */ + {12, "bzip"}, /* File is compressed using BZIP2 algorithm */ + {13, "reserved"}, /* Reserved by PKWARE */ + {14, "lzma"}, /* LZMA (EFS) */ + {15, "reserved"}, /* Reserved by PKWARE */ + {16, "reserved"}, /* Reserved by PKWARE */ + {17, "reserved"}, /* Reserved by PKWARE */ + {18, "ibm-terse-new"}, /* File is compressed using IBM TERSE (new) */ + {19, "ibm-lz777"},/* IBM LZ77 z Architecture (PFS) */ + {95, "xz"}, /* XZ compressed data */ + {96, "jpeg"}, /* JPEG compressed data */ + {97, "wav-pack"}, /* WavPack compressed data */ + {98, "ppmd-1"}, /* PPMd version I, Rev 1 */ + {99, "aes"} /* WinZip AES encryption */ +}; + +static const char * +compression_name(const int compression) +{ + static const int num_compression_methods = + sizeof(compression_methods)/sizeof(compression_methods[0]); + int i=0; + + while(compression >= 0 && i < num_compression_methods) { + if (compression_methods[i].id == compression) + return compression_methods[i].name; + i++; + } + return "??"; +} + +/* Convert an MSDOS-style date/time into Unix-style time. */ +static time_t +zip_time(const char *p) +{ + int msTime, msDate; + struct tm ts; + + msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]); + msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]); + + memset(&ts, 0, sizeof(ts)); + ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */ + ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */ + ts.tm_mday = msDate & 0x1f; /* Day of month. */ + ts.tm_hour = (msTime >> 11) & 0x1f; + ts.tm_min = (msTime >> 5) & 0x3f; + ts.tm_sec = (msTime << 1) & 0x3e; + ts.tm_isdst = -1; + return mktime(&ts); +} + +/* + * The extra data is stored as a list of + * id1+size1+data1 + id2+size2+data2 ... + * triplets. id and size are 2 bytes each. + */ +static int +process_extra(struct archive_read *a, struct archive_entry *entry, + const char *p, size_t extra_length, struct zip_entry* zip_entry) +{ + unsigned offset = 0; + struct zip *zip = (struct zip *)(a->format->data); + + if (extra_length == 0) { + return ARCHIVE_OK; + } + + if (extra_length < 4) { + size_t i = 0; + /* Some ZIP files may have trailing 0 bytes. Let's check they + * are all 0 and ignore them instead of returning an error. + * + * This is not technically correct, but some ZIP files look + * like this and other tools support those files - so let's + * also support them. + */ + for (; i < extra_length; i++) { + if (p[i] != 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Too-small extra data: " + "Need at least 4 bytes, " + "but only found %d bytes", + (int)extra_length); + return ARCHIVE_FAILED; + } + } + + return ARCHIVE_OK; + } + + while (offset <= extra_length - 4) { + unsigned short headerid = archive_le16dec(p + offset); + unsigned short datasize = archive_le16dec(p + offset + 2); + + offset += 4; + if (offset + datasize > extra_length) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, "Extra data overflow: " + "Need %d bytes but only found %d bytes", + (int)datasize, (int)(extra_length - offset)); + return ARCHIVE_FAILED; + } +#ifdef DEBUG + fprintf(stderr, "Header id 0x%04x, length %d\n", + headerid, datasize); +#endif + switch (headerid) { + case 0x0001: + /* Zip64 extended information extra field. */ + zip_entry->flags |= LA_USED_ZIP64; + if (zip_entry->uncompressed_size == 0xffffffff) { + uint64_t t = 0; + if (datasize < 8 + || (t = archive_le64dec(p + offset)) > + INT64_MAX) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Malformed 64-bit " + "uncompressed size"); + return ARCHIVE_FAILED; + } + zip_entry->uncompressed_size = t; + offset += 8; + datasize -= 8; + } + if (zip_entry->compressed_size == 0xffffffff) { + uint64_t t = 0; + if (datasize < 8 + || (t = archive_le64dec(p + offset)) > + INT64_MAX) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Malformed 64-bit " + "compressed size"); + return ARCHIVE_FAILED; + } + zip_entry->compressed_size = t; + offset += 8; + datasize -= 8; + } + if (zip_entry->local_header_offset == 0xffffffff) { + uint64_t t = 0; + if (datasize < 8 + || (t = archive_le64dec(p + offset)) > + INT64_MAX) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Malformed 64-bit " + "local header offset"); + return ARCHIVE_FAILED; + } + zip_entry->local_header_offset = t; + offset += 8; + datasize -= 8; + } + /* archive_le32dec(p + offset) gives disk + * on which file starts, but we don't handle + * multi-volume Zip files. */ + break; +#ifdef DEBUG + case 0x0017: + { + /* Strong encryption field. */ + if (archive_le16dec(p + offset) == 2) { + unsigned algId = + archive_le16dec(p + offset + 2); + unsigned bitLen = + archive_le16dec(p + offset + 4); + int flags = + archive_le16dec(p + offset + 6); + fprintf(stderr, "algId=0x%04x, bitLen=%u, " + "flgas=%d\n", algId, bitLen,flags); + } + break; + } +#endif + case 0x5455: + { + /* Extended time field "UT". */ + int flags; + if (datasize == 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Incomplete extended time field"); + return ARCHIVE_FAILED; + } + flags = p[offset]; + offset++; + datasize--; + /* Flag bits indicate which dates are present. */ + if (flags & 0x01) + { +#ifdef DEBUG + fprintf(stderr, "mtime: %lld -> %d\n", + (long long)zip_entry->mtime, + archive_le32dec(p + offset)); +#endif + if (datasize < 4) + break; + zip_entry->mtime = archive_le32dec(p + offset); + offset += 4; + datasize -= 4; + } + if (flags & 0x02) + { + if (datasize < 4) + break; + zip_entry->atime = archive_le32dec(p + offset); + offset += 4; + datasize -= 4; + } + if (flags & 0x04) + { + if (datasize < 4) + break; + zip_entry->ctime = archive_le32dec(p + offset); + offset += 4; + datasize -= 4; + } + break; + } + case 0x5855: + { + /* Info-ZIP Unix Extra Field (old version) "UX". */ + if (datasize >= 8) { + zip_entry->atime = archive_le32dec(p + offset); + zip_entry->mtime = + archive_le32dec(p + offset + 4); + } + if (datasize >= 12) { + zip_entry->uid = + archive_le16dec(p + offset + 8); + zip_entry->gid = + archive_le16dec(p + offset + 10); + } + break; + } + case 0x6c78: + { + /* Experimental 'xl' field */ + /* + * Introduced Dec 2013 to provide a way to + * include external file attributes (and other + * fields that ordinarily appear only in + * central directory) in local file header. + * This provides file type and permission + * information necessary to support full + * streaming extraction. Currently being + * discussed with other Zip developers + * ... subject to change. + * + * Format: + * The field starts with a bitmap that specifies + * which additional fields are included. The + * bitmap is variable length and can be extended in + * the future. + * + * n bytes - feature bitmap: first byte has low-order + * 7 bits. If high-order bit is set, a subsequent + * byte holds the next 7 bits, etc. + * + * if bitmap & 1, 2 byte "version made by" + * if bitmap & 2, 2 byte "internal file attributes" + * if bitmap & 4, 4 byte "external file attributes" + * if bitmap & 8, 2 byte comment length + n byte + * comment + */ + int bitmap, bitmap_last; + + if (datasize < 1) + break; + bitmap_last = bitmap = 0xff & p[offset]; + offset += 1; + datasize -= 1; + + /* We only support first 7 bits of bitmap; skip rest. */ + while ((bitmap_last & 0x80) != 0 + && datasize >= 1) { + bitmap_last = p[offset]; + offset += 1; + datasize -= 1; + } + + if (bitmap & 1) { + /* 2 byte "version made by" */ + if (datasize < 2) + break; + zip_entry->system + = archive_le16dec(p + offset) >> 8; + offset += 2; + datasize -= 2; + } + if (bitmap & 2) { + /* 2 byte "internal file attributes" */ + uint32_t internal_attributes; + if (datasize < 2) + break; + internal_attributes + = archive_le16dec(p + offset); + /* Not used by libarchive at present. */ + (void)internal_attributes; /* UNUSED */ + offset += 2; + datasize -= 2; + } + if (bitmap & 4) { + /* 4 byte "external file attributes" */ + uint32_t external_attributes; + if (datasize < 4) + break; + external_attributes + = archive_le32dec(p + offset); + if (zip_entry->system == 3) { + zip_entry->mode + = external_attributes >> 16; + } else if (zip_entry->system == 0) { + // Interpret MSDOS directory bit + if (0x10 == (external_attributes & + 0x10)) { + zip_entry->mode = + AE_IFDIR | 0775; + } else { + zip_entry->mode = + AE_IFREG | 0664; + } + if (0x01 == (external_attributes & + 0x01)) { + /* Read-only bit; + * strip write permissions */ + zip_entry->mode &= 0555; + } + } else { + zip_entry->mode = 0; + } + offset += 4; + datasize -= 4; + } + if (bitmap & 8) { + /* 2 byte comment length + comment */ + uint32_t comment_length; + if (datasize < 2) + break; + comment_length + = archive_le16dec(p + offset); + offset += 2; + datasize -= 2; + + if (datasize < comment_length) + break; + /* Comment is not supported by libarchive */ + offset += comment_length; + datasize -= comment_length; + } + break; + } + case 0x7075: + { + /* Info-ZIP Unicode Path Extra Field. */ + if (datasize < 5 || entry == NULL) + break; + offset += 5; + datasize -= 5; + + /* The path name in this field is always encoded + * in UTF-8. */ + if (zip->sconv_utf8 == NULL) { + zip->sconv_utf8 = + archive_string_conversion_from_charset( + &a->archive, "UTF-8", 1); + /* If the converter from UTF-8 is not + * available, then the path name from the main + * field will more likely be correct. */ + if (zip->sconv_utf8 == NULL) + break; + } + + /* Make sure the CRC32 of the filename matches. */ + if (!zip->ignore_crc32) { + const char *cp = archive_entry_pathname(entry); + if (cp) { + unsigned long file_crc = + zip->crc32func(0, cp, strlen(cp)); + unsigned long utf_crc = + archive_le32dec(p + offset - 4); + if (file_crc != utf_crc) { +#ifdef DEBUG + fprintf(stderr, + "CRC filename mismatch; " + "CDE is %lx, but UTF8 " + "is outdated with %lx\n", + file_crc, utf_crc); +#endif + break; + } + } + } + + if (archive_entry_copy_pathname_l(entry, + p + offset, datasize, zip->sconv_utf8) != 0) { + /* Ignore the error, and fallback to the path + * name from the main field. */ +#ifdef DEBUG + fprintf(stderr, "Failed to read the ZIP " + "0x7075 extra field path.\n"); +#endif + } + break; + } + case 0x7855: + /* Info-ZIP Unix Extra Field (type 2) "Ux". */ +#ifdef DEBUG + fprintf(stderr, "uid %d gid %d\n", + archive_le16dec(p + offset), + archive_le16dec(p + offset + 2)); +#endif + if (datasize >= 2) + zip_entry->uid = archive_le16dec(p + offset); + if (datasize >= 4) + zip_entry->gid = + archive_le16dec(p + offset + 2); + break; + case 0x7875: + { + /* Info-Zip Unix Extra Field (type 3) "ux". */ + int uidsize = 0, gidsize = 0; + + /* TODO: support arbitrary uidsize/gidsize. */ + if (datasize >= 1 && p[offset] == 1) {/* version=1 */ + if (datasize >= 4) { + /* get a uid size. */ + uidsize = 0xff & (int)p[offset+1]; + if (uidsize == 2) + zip_entry->uid = + archive_le16dec( + p + offset + 2); + else if (uidsize == 4 && datasize >= 6) + zip_entry->uid = + archive_le32dec( + p + offset + 2); + } + if (datasize >= (2 + uidsize + 3)) { + /* get a gid size. */ + gidsize = 0xff & + (int)p[offset+2+uidsize]; + if (gidsize == 2) + zip_entry->gid = + archive_le16dec( + p+offset+2+uidsize+1); + else if (gidsize == 4 && + datasize >= (2 + uidsize + 5)) + zip_entry->gid = + archive_le32dec( + p+offset+2+uidsize+1); + } + } + break; + } + case 0x9901: + /* WinZip AES extra data field. */ + if (datasize < 6) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Incomplete AES field"); + return ARCHIVE_FAILED; + } + if (p[offset + 2] == 'A' && p[offset + 3] == 'E') { + /* Vendor version. */ + zip_entry->aes_extra.vendor = + archive_le16dec(p + offset); + /* AES encryption strength. */ + zip_entry->aes_extra.strength = p[offset + 4]; + /* Actual compression method. */ + zip_entry->aes_extra.compression = + p[offset + 5]; + } + break; + default: + break; + } + offset += datasize; + } + return ARCHIVE_OK; +} + +/* + * Assumes file pointer is at beginning of local file header. + */ +static int +zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry, + struct zip *zip) +{ + const char *p; + const void *h; + const wchar_t *wp; + const char *cp; + size_t len, filename_length, extra_length; + struct archive_string_conv *sconv; + struct zip_entry *zip_entry = zip->entry; + struct zip_entry zip_entry_central_dir; + int ret = ARCHIVE_OK; + char version; + + /* Save a copy of the original for consistency checks. */ + zip_entry_central_dir = *zip_entry; + + zip->decompress_init = 0; + zip->end_of_entry = 0; + zip->entry_uncompressed_bytes_read = 0; + zip->entry_compressed_bytes_read = 0; + zip->entry_crc32 = zip->crc32func(0, NULL, 0); + + /* Setup default conversion. */ + if (zip->sconv == NULL && !zip->init_default_conversion) { + zip->sconv_default = + archive_string_default_conversion_for_read(&(a->archive)); + zip->init_default_conversion = 1; + } + + if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP file header"); + return (ARCHIVE_FATAL); + } + + if (memcmp(p, "PK\003\004", 4) != 0) { + archive_set_error(&a->archive, -1, "Damaged Zip archive"); + return ARCHIVE_FATAL; + } + version = p[4]; + zip_entry->system = p[5]; + zip_entry->zip_flags = archive_le16dec(p + 6); + if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) { + zip->has_encrypted_entries = 1; + archive_entry_set_is_data_encrypted(entry, 1); + if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED && + zip_entry->zip_flags & ZIP_ENCRYPTED && + zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) { + archive_entry_set_is_metadata_encrypted(entry, 1); + return ARCHIVE_FATAL; + } + } + zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED); + zip_entry->compression = (char)archive_le16dec(p + 8); + zip_entry->mtime = zip_time(p + 10); + zip_entry->crc32 = archive_le32dec(p + 14); + if (zip_entry->zip_flags & ZIP_LENGTH_AT_END) + zip_entry->decdat = p[11]; + else + zip_entry->decdat = p[17]; + zip_entry->compressed_size = archive_le32dec(p + 18); + zip_entry->uncompressed_size = archive_le32dec(p + 22); + filename_length = archive_le16dec(p + 26); + extra_length = archive_le16dec(p + 28); + + __archive_read_consume(a, 30); + + /* Read the filename. */ + if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP file header"); + return (ARCHIVE_FATAL); + } + if (zip_entry->zip_flags & ZIP_UTF8_NAME) { + /* The filename is stored to be UTF-8. */ + if (zip->sconv_utf8 == NULL) { + zip->sconv_utf8 = + archive_string_conversion_from_charset( + &a->archive, "UTF-8", 1); + if (zip->sconv_utf8 == NULL) + return (ARCHIVE_FATAL); + } + sconv = zip->sconv_utf8; + } else if (zip->sconv != NULL) + sconv = zip->sconv; + else + sconv = zip->sconv_default; + + if (archive_entry_copy_pathname_l(entry, + h, filename_length, sconv) != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Pathname cannot be converted " + "from %s to current locale.", + archive_string_conversion_charset_name(sconv)); + ret = ARCHIVE_WARN; + } + __archive_read_consume(a, filename_length); + + /* Read the extra data. */ + if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP file header"); + return (ARCHIVE_FATAL); + } + + if (ARCHIVE_OK != process_extra(a, entry, h, extra_length, + zip_entry)) { + return ARCHIVE_FATAL; + } + __archive_read_consume(a, extra_length); + + /* Work around a bug in Info-Zip: When reading from a pipe, it + * stats the pipe instead of synthesizing a file entry. */ + if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) { + zip_entry->mode &= ~ AE_IFMT; + zip_entry->mode |= AE_IFREG; + } + + /* If the mode is totally empty, set some sane default. */ + if (zip_entry->mode == 0) { + zip_entry->mode |= 0664; + } + + /* Windows archivers sometimes use backslash as the directory + * separator. Normalize to slash. */ + if (zip_entry->system == 0 && + (wp = archive_entry_pathname_w(entry)) != NULL) { + if (wcschr(wp, L'/') == NULL && wcschr(wp, L'\\') != NULL) { + size_t i; + struct archive_wstring s; + archive_string_init(&s); + archive_wstrcpy(&s, wp); + for (i = 0; i < archive_strlen(&s); i++) { + if (s.s[i] == '\\') + s.s[i] = '/'; + } + archive_entry_copy_pathname_w(entry, s.s); + archive_wstring_free(&s); + } + } + + /* Make sure that entries with a trailing '/' are marked as directories + * even if the External File Attributes contains bogus values. If this + * is not a directory and there is no type, assume a regular file. */ + if ((zip_entry->mode & AE_IFMT) != AE_IFDIR) { + int has_slash; + + wp = archive_entry_pathname_w(entry); + if (wp != NULL) { + len = wcslen(wp); + has_slash = len > 0 && wp[len - 1] == L'/'; + } else { + cp = archive_entry_pathname(entry); + len = (cp != NULL)?strlen(cp):0; + has_slash = len > 0 && cp[len - 1] == '/'; + } + /* Correct file type as needed. */ + if (has_slash) { + zip_entry->mode &= ~AE_IFMT; + zip_entry->mode |= AE_IFDIR; + zip_entry->mode |= 0111; + } else if ((zip_entry->mode & AE_IFMT) == 0) { + zip_entry->mode |= AE_IFREG; + } + } + + /* Make sure directories end in '/' */ + if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) { + wp = archive_entry_pathname_w(entry); + if (wp != NULL) { + len = wcslen(wp); + if (len > 0 && wp[len - 1] != L'/') { + struct archive_wstring s; + archive_string_init(&s); + archive_wstrcat(&s, wp); + archive_wstrappend_wchar(&s, L'/'); + archive_entry_copy_pathname_w(entry, s.s); + archive_wstring_free(&s); + } + } else { + cp = archive_entry_pathname(entry); + len = (cp != NULL)?strlen(cp):0; + if (len > 0 && cp[len - 1] != '/') { + struct archive_string s; + archive_string_init(&s); + archive_strcat(&s, cp); + archive_strappend_char(&s, '/'); + archive_entry_set_pathname(entry, s.s); + archive_string_free(&s); + } + } + } + + if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) { + /* If this came from the central dir, its size info + * is definitive, so ignore the length-at-end flag. */ + zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END; + /* If local header is missing a value, use the one from + the central directory. If both have it, warn about + mismatches. */ + if (zip_entry->crc32 == 0) { + zip_entry->crc32 = zip_entry_central_dir.crc32; + } else if (!zip->ignore_crc32 + && zip_entry->crc32 != zip_entry_central_dir.crc32) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Inconsistent CRC32 values"); + ret = ARCHIVE_WARN; + } + if (zip_entry->compressed_size == 0) { + zip_entry->compressed_size + = zip_entry_central_dir.compressed_size; + } else if (zip_entry->compressed_size + != zip_entry_central_dir.compressed_size) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Inconsistent compressed size: " + "%jd in central directory, %jd in local header", + (intmax_t)zip_entry_central_dir.compressed_size, + (intmax_t)zip_entry->compressed_size); + ret = ARCHIVE_WARN; + } + if (zip_entry->uncompressed_size == 0) { + zip_entry->uncompressed_size + = zip_entry_central_dir.uncompressed_size; + } else if (zip_entry->uncompressed_size + != zip_entry_central_dir.uncompressed_size) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Inconsistent uncompressed size: " + "%jd in central directory, %jd in local header", + (intmax_t)zip_entry_central_dir.uncompressed_size, + (intmax_t)zip_entry->uncompressed_size); + ret = ARCHIVE_WARN; + } + } + + /* Populate some additional entry fields: */ + archive_entry_set_mode(entry, zip_entry->mode); + archive_entry_set_uid(entry, zip_entry->uid); + archive_entry_set_gid(entry, zip_entry->gid); + archive_entry_set_mtime(entry, zip_entry->mtime, 0); + archive_entry_set_ctime(entry, zip_entry->ctime, 0); + archive_entry_set_atime(entry, zip_entry->atime, 0); + + if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) { + size_t linkname_length; + + if (zip_entry->compressed_size > 64 * 1024) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Zip file with oversized link entry"); + return ARCHIVE_FATAL; + } + + linkname_length = (size_t)zip_entry->compressed_size; + + archive_entry_set_size(entry, 0); + p = __archive_read_ahead(a, linkname_length, NULL); + if (p == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Truncated Zip file"); + return ARCHIVE_FATAL; + } + + sconv = zip->sconv; + if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME)) + sconv = zip->sconv_utf8; + if (sconv == NULL) + sconv = zip->sconv_default; + if (archive_entry_copy_symlink_l(entry, p, linkname_length, + sconv) != 0) { + if (errno != ENOMEM && sconv == zip->sconv_utf8 && + (zip->entry->zip_flags & ZIP_UTF8_NAME)) + archive_entry_copy_symlink_l(entry, p, + linkname_length, NULL); + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Symlink"); + return (ARCHIVE_FATAL); + } + /* + * Since there is no character-set regulation for + * symlink name, do not report the conversion error + * in an automatic conversion. + */ + if (sconv != zip->sconv_utf8 || + (zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Symlink cannot be converted " + "from %s to current locale.", + archive_string_conversion_charset_name( + sconv)); + ret = ARCHIVE_WARN; + } + } + zip_entry->uncompressed_size = zip_entry->compressed_size = 0; + + if (__archive_read_consume(a, linkname_length) < 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Read error skipping symlink target name"); + return ARCHIVE_FATAL; + } + } else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END) + || zip_entry->uncompressed_size > 0) { + /* Set the size only if it's meaningful. */ + archive_entry_set_size(entry, zip_entry->uncompressed_size); + } + zip->entry_bytes_remaining = zip_entry->compressed_size; + + /* If there's no body, force read_data() to return EOF immediately. */ + if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END) + && zip->entry_bytes_remaining < 1) + zip->end_of_entry = 1; + + /* Set up a more descriptive format name. */ + archive_string_empty(&zip->format_name); + archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)", + version / 10, version % 10, + compression_name(zip->entry->compression)); + a->archive.archive_format_name = zip->format_name.s; + + return (ret); +} + +static int +check_authentication_code(struct archive_read *a, const void *_p) +{ + struct zip *zip = (struct zip *)(a->format->data); + + /* Check authentication code. */ + if (zip->hctx_valid) { + const void *p; + uint8_t hmac[20]; + size_t hmac_len = 20; + int cmp; + + archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len); + if (_p == NULL) { + /* Read authentication code. */ + p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL); + if (p == NULL) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP file data"); + return (ARCHIVE_FATAL); + } + } else { + p = _p; + } + cmp = memcmp(hmac, p, AUTH_CODE_SIZE); + __archive_read_consume(a, AUTH_CODE_SIZE); + if (cmp != 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "ZIP bad Authentication code"); + return (ARCHIVE_WARN); + } + } + return (ARCHIVE_OK); +} + +/* + * Read "uncompressed" data. There are three cases: + * 1) We know the size of the data. This is always true for the + * seeking reader (we've examined the Central Directory already). + * 2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred. + * Info-ZIP seems to do this; we know the size but have to grab + * the CRC from the data descriptor afterwards. + * 3) We're streaming and ZIP_LENGTH_AT_END was specified and + * we have no size information. In this case, we can do pretty + * well by watching for the data descriptor record. The data + * descriptor is 16 bytes and includes a computed CRC that should + * provide a strong check. + * + * TODO: Technically, the PK\007\010 signature is optional. + * In the original spec, the data descriptor contained CRC + * and size fields but had no leading signature. In practice, + * newer writers seem to provide the signature pretty consistently. + * + * For uncompressed data, the PK\007\010 marker seems essential + * to be sure we've actually seen the end of the entry. + * + * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets + * zip->end_of_entry if it consumes all of the data. + */ +static int +zip_read_data_none(struct archive_read *a, const void **_buff, + size_t *size, int64_t *offset) +{ + struct zip *zip; + const char *buff; + ssize_t bytes_avail; + int r; + + (void)offset; /* UNUSED */ + + zip = (struct zip *)(a->format->data); + + if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) { + const char *p; + ssize_t grabbing_bytes = 24; + + if (zip->hctx_valid) + grabbing_bytes += AUTH_CODE_SIZE; + /* Grab at least 24 bytes. */ + buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail); + if (bytes_avail < grabbing_bytes) { + /* Zip archives have end-of-archive markers + that are longer than this, so a failure to get at + least 24 bytes really does indicate a truncated + file. */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP file data"); + return (ARCHIVE_FATAL); + } + /* Check for a complete PK\007\010 signature, followed + * by the correct 4-byte CRC. */ + p = buff; + if (zip->hctx_valid) + p += AUTH_CODE_SIZE; + if (p[0] == 'P' && p[1] == 'K' + && p[2] == '\007' && p[3] == '\010' + && (archive_le32dec(p + 4) == zip->entry_crc32 + || zip->ignore_crc32 + || (zip->hctx_valid + && zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) { + if (zip->entry->flags & LA_USED_ZIP64) { + uint64_t compressed, uncompressed; + zip->entry->crc32 = archive_le32dec(p + 4); + compressed = archive_le64dec(p + 8); + uncompressed = archive_le64dec(p + 16); + if (compressed > INT64_MAX || uncompressed > + INT64_MAX) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Overflow of 64-bit file sizes"); + return ARCHIVE_FAILED; + } + zip->entry->compressed_size = compressed; + zip->entry->uncompressed_size = uncompressed; + zip->unconsumed = 24; + } else { + zip->entry->crc32 = archive_le32dec(p + 4); + zip->entry->compressed_size = + archive_le32dec(p + 8); + zip->entry->uncompressed_size = + archive_le32dec(p + 12); + zip->unconsumed = 16; + } + if (zip->hctx_valid) { + r = check_authentication_code(a, buff); + if (r != ARCHIVE_OK) + return (r); + } + zip->end_of_entry = 1; + return (ARCHIVE_OK); + } + /* If not at EOF, ensure we consume at least one byte. */ + ++p; + + /* Scan forward until we see where a PK\007\010 signature + * might be. */ + /* Return bytes up until that point. On the next call, + * the code above will verify the data descriptor. */ + while (p < buff + bytes_avail - 4) { + if (p[3] == 'P') { p += 3; } + else if (p[3] == 'K') { p += 2; } + else if (p[3] == '\007') { p += 1; } + else if (p[3] == '\010' && p[2] == '\007' + && p[1] == 'K' && p[0] == 'P') { + if (zip->hctx_valid) + p -= AUTH_CODE_SIZE; + break; + } else { p += 4; } + } + bytes_avail = p - buff; + } else { + if (zip->entry_bytes_remaining == 0) { + zip->end_of_entry = 1; + if (zip->hctx_valid) { + r = check_authentication_code(a, NULL); + if (r != ARCHIVE_OK) + return (r); + } + return (ARCHIVE_OK); + } + /* Grab a bunch of bytes. */ + buff = __archive_read_ahead(a, 1, &bytes_avail); + if (bytes_avail <= 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP file data"); + return (ARCHIVE_FATAL); + } + if (bytes_avail > zip->entry_bytes_remaining) + bytes_avail = (ssize_t)zip->entry_bytes_remaining; + } + if (zip->tctx_valid || zip->cctx_valid) { + size_t dec_size = bytes_avail; + + if (dec_size > zip->decrypted_buffer_size) + dec_size = zip->decrypted_buffer_size; + if (zip->tctx_valid) { + trad_enc_decrypt_update(&zip->tctx, + (const uint8_t *)buff, dec_size, + zip->decrypted_buffer, dec_size); + } else { + size_t dsize = dec_size; + archive_hmac_sha1_update(&zip->hctx, + (const uint8_t *)buff, dec_size); + archive_decrypto_aes_ctr_update(&zip->cctx, + (const uint8_t *)buff, dec_size, + zip->decrypted_buffer, &dsize); + } + bytes_avail = dec_size; + buff = (const char *)zip->decrypted_buffer; + } + *size = bytes_avail; + zip->entry_bytes_remaining -= bytes_avail; + zip->entry_uncompressed_bytes_read += bytes_avail; + zip->entry_compressed_bytes_read += bytes_avail; + zip->unconsumed += bytes_avail; + *_buff = buff; + return (ARCHIVE_OK); +} + +static int +consume_optional_marker(struct archive_read *a, struct zip *zip) +{ + if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) { + const char *p; + + if (NULL == (p = __archive_read_ahead(a, 24, NULL))) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP end-of-file record"); + return (ARCHIVE_FATAL); + } + /* Consume the optional PK\007\010 marker. */ + if (p[0] == 'P' && p[1] == 'K' && + p[2] == '\007' && p[3] == '\010') { + p += 4; + zip->unconsumed = 4; + } + if (zip->entry->flags & LA_USED_ZIP64) { + uint64_t compressed, uncompressed; + zip->entry->crc32 = archive_le32dec(p); + compressed = archive_le64dec(p + 4); + uncompressed = archive_le64dec(p + 12); + if (compressed > INT64_MAX || + uncompressed > INT64_MAX) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Overflow of 64-bit file sizes"); + return ARCHIVE_FAILED; + } + zip->entry->compressed_size = compressed; + zip->entry->uncompressed_size = uncompressed; + zip->unconsumed += 20; + } else { + zip->entry->crc32 = archive_le32dec(p); + zip->entry->compressed_size = archive_le32dec(p + 4); + zip->entry->uncompressed_size = archive_le32dec(p + 8); + zip->unconsumed += 12; + } + } + + return (ARCHIVE_OK); +} + +#if HAVE_LZMA_H && HAVE_LIBLZMA +static int +zipx_xz_init(struct archive_read *a, struct zip *zip) +{ + lzma_ret r; + + if(zip->zipx_lzma_valid) { + lzma_end(&zip->zipx_lzma_stream); + zip->zipx_lzma_valid = 0; + } + + memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream)); + r = lzma_stream_decoder(&zip->zipx_lzma_stream, UINT64_MAX, 0); + if (r != LZMA_OK) { + archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, + "xz initialization failed(%d)", + r); + + return (ARCHIVE_FAILED); + } + + zip->zipx_lzma_valid = 1; + + free(zip->uncompressed_buffer); + + zip->uncompressed_buffer_size = 256 * 1024; + zip->uncompressed_buffer = + (uint8_t*) malloc(zip->uncompressed_buffer_size); + if (zip->uncompressed_buffer == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for xz decompression"); + return (ARCHIVE_FATAL); + } + + zip->decompress_init = 1; + return (ARCHIVE_OK); +} + +static int +zipx_lzma_alone_init(struct archive_read *a, struct zip *zip) +{ + lzma_ret r; + const uint8_t* p; + +#pragma pack(push) +#pragma pack(1) + struct _alone_header { + uint8_t bytes[5]; + uint64_t uncompressed_size; + } alone_header; +#pragma pack(pop) + + if(zip->zipx_lzma_valid) { + lzma_end(&zip->zipx_lzma_stream); + zip->zipx_lzma_valid = 0; + } + + /* To unpack ZIPX's "LZMA" (id 14) stream we can use standard liblzma + * that is a part of XZ Utils. The stream format stored inside ZIPX + * file is a modified "lzma alone" file format, that was used by the + * `lzma` utility which was later deprecated in favour of `xz` utility. * Since those formats are nearly the same, we can use a standard + * "lzma alone" decoder from XZ Utils. */ + + memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream)); + r = lzma_alone_decoder(&zip->zipx_lzma_stream, UINT64_MAX); + if (r != LZMA_OK) { + archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, + "lzma initialization failed(%d)", r); + + return (ARCHIVE_FAILED); + } + + /* Flag the cleanup function that we want our lzma-related structures + * to be freed later. */ + zip->zipx_lzma_valid = 1; + + /* The "lzma alone" file format and the stream format inside ZIPx are + * almost the same. Here's an example of a structure of "lzma alone" + * format: + * + * $ cat /bin/ls | lzma | xxd | head -n 1 + * 00000000: 5d00 0080 00ff ffff ffff ffff ff00 2814 + * + * 5 bytes 8 bytes n bytes + * <lzma_params><uncompressed_size><data...> + * + * lzma_params is a 5-byte blob that has to be decoded to extract + * parameters of this LZMA stream. The uncompressed_size field is an + * uint64_t value that contains information about the size of the + * uncompressed file, or UINT64_MAX if this value is unknown. + * The <data...> part is the actual lzma-compressed data stream. + * + * Now here's the structure of the stream inside the ZIPX file: + * + * $ cat stream_inside_zipx | xxd | head -n 1 + * 00000000: 0914 0500 5d00 8000 0000 2814 .... .... + * + * 2byte 2byte 5 bytes n bytes + * <magic1><magic2><lzma_params><data...> + * + * This means that the ZIPX file contains an additional magic1 and + * magic2 headers, the lzma_params field contains the same parameter + * set as in the "lzma alone" format, and the <data...> field is the + * same as in the "lzma alone" format as well. Note that also the zipx + * format is missing the uncompressed_size field. + * + * So, in order to use the "lzma alone" decoder for the zipx lzma + * stream, we simply need to shuffle around some fields, prepare a new + * lzma alone header, feed it into lzma alone decoder so it will + * initialize itself properly, and then we can start feeding normal + * zipx lzma stream into the decoder. + */ + + /* Read magic1,magic2,lzma_params from the ZIPX stream. */ + if((p = __archive_read_ahead(a, 9, NULL)) == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated lzma data"); + return (ARCHIVE_FATAL); + } + + if(p[2] != 0x05 || p[3] != 0x00) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid lzma data"); + return (ARCHIVE_FATAL); + } + + /* Prepare an lzma alone header: copy the lzma_params blob into + * a proper place into the lzma alone header. */ + memcpy(&alone_header.bytes[0], p + 4, 5); + + /* Initialize the 'uncompressed size' field to unknown; we'll manually + * monitor how many bytes there are still to be uncompressed. */ + alone_header.uncompressed_size = UINT64_MAX; + + if(!zip->uncompressed_buffer) { + zip->uncompressed_buffer_size = 256 * 1024; + zip->uncompressed_buffer = + (uint8_t*) malloc(zip->uncompressed_buffer_size); + + if (zip->uncompressed_buffer == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for lzma decompression"); + return (ARCHIVE_FATAL); + } + } + + zip->zipx_lzma_stream.next_in = (void*) &alone_header; + zip->zipx_lzma_stream.avail_in = sizeof(alone_header); + zip->zipx_lzma_stream.total_in = 0; + zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer; + zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size; + zip->zipx_lzma_stream.total_out = 0; + + /* Feed only the header into the lzma alone decoder. This will + * effectively initialize the decoder, and will not produce any + * output bytes yet. */ + r = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN); + if (r != LZMA_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "lzma stream initialization error"); + return ARCHIVE_FATAL; + } + + /* We've already consumed some bytes, so take this into account. */ + __archive_read_consume(a, 9); + zip->entry_bytes_remaining -= 9; + zip->entry_compressed_bytes_read += 9; + + zip->decompress_init = 1; + return (ARCHIVE_OK); +} + +static int +zip_read_data_zipx_xz(struct archive_read *a, const void **buff, + size_t *size, int64_t *offset) +{ + struct zip* zip = (struct zip *)(a->format->data); + int ret; + lzma_ret lz_ret; + const void* compressed_buf; + ssize_t bytes_avail, in_bytes, to_consume = 0; + + (void) offset; /* UNUSED */ + + /* Initialize decompressor if not yet initialized. */ + if (!zip->decompress_init) { + ret = zipx_xz_init(a, zip); + if (ret != ARCHIVE_OK) + return (ret); + } + + compressed_buf = __archive_read_ahead(a, 1, &bytes_avail); + if (bytes_avail < 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated xz file body"); + return (ARCHIVE_FATAL); + } + + in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail); + zip->zipx_lzma_stream.next_in = compressed_buf; + zip->zipx_lzma_stream.avail_in = in_bytes; + zip->zipx_lzma_stream.total_in = 0; + zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer; + zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size; + zip->zipx_lzma_stream.total_out = 0; + + /* Perform the decompression. */ + lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN); + switch(lz_ret) { + case LZMA_DATA_ERROR: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "xz data error (error %d)", (int) lz_ret); + return (ARCHIVE_FATAL); + + case LZMA_NO_CHECK: + case LZMA_OK: + break; + + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "xz unknown error %d", (int) lz_ret); + return (ARCHIVE_FATAL); + + case LZMA_STREAM_END: + lzma_end(&zip->zipx_lzma_stream); + zip->zipx_lzma_valid = 0; + + if((int64_t) zip->zipx_lzma_stream.total_in != + zip->entry_bytes_remaining) + { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xz premature end of stream"); + return (ARCHIVE_FATAL); + } + + zip->end_of_entry = 1; + break; + } + + to_consume = zip->zipx_lzma_stream.total_in; + + __archive_read_consume(a, to_consume); + zip->entry_bytes_remaining -= to_consume; + zip->entry_compressed_bytes_read += to_consume; + zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out; + + *size = zip->zipx_lzma_stream.total_out; + *buff = zip->uncompressed_buffer; + + ret = consume_optional_marker(a, zip); + if (ret != ARCHIVE_OK) + return (ret); + + return (ARCHIVE_OK); +} + +static int +zip_read_data_zipx_lzma_alone(struct archive_read *a, const void **buff, + size_t *size, int64_t *offset) +{ + struct zip* zip = (struct zip *)(a->format->data); + int ret; + lzma_ret lz_ret; + const void* compressed_buf; + ssize_t bytes_avail, in_bytes, to_consume; + + (void) offset; /* UNUSED */ + + /* Initialize decompressor if not yet initialized. */ + if (!zip->decompress_init) { + ret = zipx_lzma_alone_init(a, zip); + if (ret != ARCHIVE_OK) + return (ret); + } + + /* Fetch more compressed data. The same note as in deflate handler + * applies here as well: + * + * Note: '1' here is a performance optimization. Recall that the + * decompression layer returns a count of available bytes; asking for + * more than that forces the decompressor to combine reads by copying + * data. + */ + compressed_buf = __archive_read_ahead(a, 1, &bytes_avail); + if (bytes_avail < 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated lzma file body"); + return (ARCHIVE_FATAL); + } + + /* Set decompressor parameters. */ + in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail); + + zip->zipx_lzma_stream.next_in = compressed_buf; + zip->zipx_lzma_stream.avail_in = in_bytes; + zip->zipx_lzma_stream.total_in = 0; + zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer; + zip->zipx_lzma_stream.avail_out = + /* These lzma_alone streams lack end of stream marker, so let's + * make sure the unpacker won't try to unpack more than it's + * supposed to. */ + zipmin((int64_t) zip->uncompressed_buffer_size, + zip->entry->uncompressed_size - + zip->entry_uncompressed_bytes_read); + zip->zipx_lzma_stream.total_out = 0; + + /* Perform the decompression. */ + lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN); + switch(lz_ret) { + case LZMA_DATA_ERROR: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "lzma data error (error %d)", (int) lz_ret); + return (ARCHIVE_FATAL); + + /* This case is optional in lzma alone format. It can happen, + * but most of the files don't have it. (GitHub #1257) */ + case LZMA_STREAM_END: + lzma_end(&zip->zipx_lzma_stream); + zip->zipx_lzma_valid = 0; + if((int64_t) zip->zipx_lzma_stream.total_in != + zip->entry_bytes_remaining) + { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "lzma alone premature end of stream"); + return (ARCHIVE_FATAL); + } + + zip->end_of_entry = 1; + break; + + case LZMA_OK: + break; + + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "lzma unknown error %d", (int) lz_ret); + return (ARCHIVE_FATAL); + } + + to_consume = zip->zipx_lzma_stream.total_in; + + /* Update pointers. */ + __archive_read_consume(a, to_consume); + zip->entry_bytes_remaining -= to_consume; + zip->entry_compressed_bytes_read += to_consume; + zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out; + + if(zip->entry_bytes_remaining == 0) { + zip->end_of_entry = 1; + } + + /* Return values. */ + *size = zip->zipx_lzma_stream.total_out; + *buff = zip->uncompressed_buffer; + + /* Behave the same way as during deflate decompression. */ + ret = consume_optional_marker(a, zip); + if (ret != ARCHIVE_OK) + return (ret); + + /* Free lzma decoder handle because we'll no longer need it. */ + if(zip->end_of_entry) { + lzma_end(&zip->zipx_lzma_stream); + zip->zipx_lzma_valid = 0; + } + + /* If we're here, then we're good! */ + return (ARCHIVE_OK); +} +#endif /* HAVE_LZMA_H && HAVE_LIBLZMA */ + +static int +zipx_ppmd8_init(struct archive_read *a, struct zip *zip) +{ + const void* p; + uint32_t val; + uint32_t order; + uint32_t mem; + uint32_t restore_method; + + /* Remove previous decompression context if it exists. */ + if(zip->ppmd8_valid) { + __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8); + zip->ppmd8_valid = 0; + } + + /* Create a new decompression context. */ + __archive_ppmd8_functions.Ppmd8_Construct(&zip->ppmd8); + zip->ppmd8_stream_failed = 0; + + /* Setup function pointers required by Ppmd8 decompressor. The + * 'ppmd_read' function will feed new bytes to the decompressor, + * and will increment the 'zip->zipx_ppmd_read_compressed' counter. */ + zip->ppmd8.Stream.In = &zip->zipx_ppmd_stream; + zip->zipx_ppmd_stream.a = a; + zip->zipx_ppmd_stream.Read = &ppmd_read; + + /* Reset number of read bytes to 0. */ + zip->zipx_ppmd_read_compressed = 0; + + /* Read Ppmd8 header (2 bytes). */ + p = __archive_read_ahead(a, 2, NULL); + if(!p) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated file data in PPMd8 stream"); + return (ARCHIVE_FATAL); + } + __archive_read_consume(a, 2); + + /* Decode the stream's compression parameters. */ + val = archive_le16dec(p); + order = (val & 15) + 1; + mem = ((val >> 4) & 0xff) + 1; + restore_method = (val >> 12); + + if(order < 2 || restore_method > 2) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Invalid parameter set in PPMd8 stream (order=%d, " + "restore=%d)", order, restore_method); + return (ARCHIVE_FAILED); + } + + /* Allocate the memory needed to properly decompress the file. */ + if(!__archive_ppmd8_functions.Ppmd8_Alloc(&zip->ppmd8, mem << 20)) { + archive_set_error(&a->archive, ENOMEM, + "Unable to allocate memory for PPMd8 stream: %d bytes", + mem << 20); + return (ARCHIVE_FATAL); + } + + /* Signal the cleanup function to release Ppmd8 context in the + * cleanup phase. */ + zip->ppmd8_valid = 1; + + /* Perform further Ppmd8 initialization. */ + if(!__archive_ppmd8_functions.Ppmd8_RangeDec_Init(&zip->ppmd8)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, + "PPMd8 stream range decoder initialization error"); + return (ARCHIVE_FATAL); + } + + __archive_ppmd8_functions.Ppmd8_Init(&zip->ppmd8, order, + restore_method); + + /* Allocate the buffer that will hold uncompressed data. */ + free(zip->uncompressed_buffer); + + zip->uncompressed_buffer_size = 256 * 1024; + zip->uncompressed_buffer = + (uint8_t*) malloc(zip->uncompressed_buffer_size); + + if(zip->uncompressed_buffer == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for PPMd8 decompression"); + return ARCHIVE_FATAL; + } + + /* Ppmd8 initialization is done. */ + zip->decompress_init = 1; + + /* We've already read 2 bytes in the output stream. Additionally, + * Ppmd8 initialization code could read some data as well. So we + * are advancing the stream by 2 bytes plus whatever number of + * bytes Ppmd8 init function used. */ + zip->entry_compressed_bytes_read += 2 + zip->zipx_ppmd_read_compressed; + + return ARCHIVE_OK; +} + +static int +zip_read_data_zipx_ppmd(struct archive_read *a, const void **buff, + size_t *size, int64_t *offset) +{ + struct zip* zip = (struct zip *)(a->format->data); + int ret; + size_t consumed_bytes = 0; + ssize_t bytes_avail = 0; + + (void) offset; /* UNUSED */ + + /* If we're here for the first time, initialize Ppmd8 decompression + * context first. */ + if(!zip->decompress_init) { + ret = zipx_ppmd8_init(a, zip); + if(ret != ARCHIVE_OK) + return ret; + } + + /* Fetch for more data. We're reading 1 byte here, but libarchive + * should prefetch more bytes. */ + (void) __archive_read_ahead(a, 1, &bytes_avail); + if(bytes_avail < 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated PPMd8 file body"); + return (ARCHIVE_FATAL); + } + + /* This counter will be updated inside ppmd_read(), which at one + * point will be called by Ppmd8_DecodeSymbol. */ + zip->zipx_ppmd_read_compressed = 0; + + /* Decompression loop. */ + do { + int sym = __archive_ppmd8_functions.Ppmd8_DecodeSymbol( + &zip->ppmd8); + if(sym < 0) { + zip->end_of_entry = 1; + break; + } + + /* This field is set by ppmd_read() when there was no more data + * to be read. */ + if(zip->ppmd8_stream_failed) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated PPMd8 file body"); + return (ARCHIVE_FATAL); + } + + zip->uncompressed_buffer[consumed_bytes] = (uint8_t) sym; + ++consumed_bytes; + } while(consumed_bytes < zip->uncompressed_buffer_size); + + /* Update pointers for libarchive. */ + *buff = zip->uncompressed_buffer; + *size = consumed_bytes; + + /* Update pointers so we can continue decompression in another call. */ + zip->entry_bytes_remaining -= zip->zipx_ppmd_read_compressed; + zip->entry_compressed_bytes_read += zip->zipx_ppmd_read_compressed; + zip->entry_uncompressed_bytes_read += consumed_bytes; + + /* If we're at the end of stream, deinitialize Ppmd8 context. */ + if(zip->end_of_entry) { + __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8); + zip->ppmd8_valid = 0; + } + + /* Seek for optional marker, same way as in each zip entry. */ + ret = consume_optional_marker(a, zip); + if (ret != ARCHIVE_OK) + return ret; + + return ARCHIVE_OK; +} + +#ifdef HAVE_BZLIB_H +static int +zipx_bzip2_init(struct archive_read *a, struct zip *zip) +{ + int r; + + /* Deallocate already existing BZ2 decompression context if it + * exists. */ + if(zip->bzstream_valid) { + BZ2_bzDecompressEnd(&zip->bzstream); + zip->bzstream_valid = 0; + } + + /* Allocate a new BZ2 decompression context. */ + memset(&zip->bzstream, 0, sizeof(bz_stream)); + r = BZ2_bzDecompressInit(&zip->bzstream, 0, 1); + if(r != BZ_OK) { + archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, + "bzip2 initialization failed(%d)", + r); + + return ARCHIVE_FAILED; + } + + /* Mark the bzstream field to be released in cleanup phase. */ + zip->bzstream_valid = 1; + + /* (Re)allocate the buffer that will contain decompressed bytes. */ + free(zip->uncompressed_buffer); + + zip->uncompressed_buffer_size = 256 * 1024; + zip->uncompressed_buffer = + (uint8_t*) malloc(zip->uncompressed_buffer_size); + if (zip->uncompressed_buffer == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for bzip2 decompression"); + return ARCHIVE_FATAL; + } + + /* Initialization done. */ + zip->decompress_init = 1; + return ARCHIVE_OK; +} + +static int +zip_read_data_zipx_bzip2(struct archive_read *a, const void **buff, + size_t *size, int64_t *offset) +{ + struct zip *zip = (struct zip *)(a->format->data); + ssize_t bytes_avail = 0, in_bytes, to_consume; + const void *compressed_buff; + int r; + uint64_t total_out; + + (void) offset; /* UNUSED */ + + /* Initialize decompression context if we're here for the first time. */ + if(!zip->decompress_init) { + r = zipx_bzip2_init(a, zip); + if(r != ARCHIVE_OK) + return r; + } + + /* Fetch more compressed bytes. */ + compressed_buff = __archive_read_ahead(a, 1, &bytes_avail); + if(bytes_avail < 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated bzip2 file body"); + return (ARCHIVE_FATAL); + } + + in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail); + if(in_bytes < 1) { + /* libbz2 doesn't complain when caller feeds avail_in == 0. + * It will actually return success in this case, which is + * undesirable. This is why we need to make this check + * manually. */ + + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated bzip2 file body"); + return (ARCHIVE_FATAL); + } + + /* Setup buffer boundaries. */ + zip->bzstream.next_in = (char*)(uintptr_t) compressed_buff; + zip->bzstream.avail_in = in_bytes; + zip->bzstream.total_in_hi32 = 0; + zip->bzstream.total_in_lo32 = 0; + zip->bzstream.next_out = (char*) zip->uncompressed_buffer; + zip->bzstream.avail_out = zip->uncompressed_buffer_size; + zip->bzstream.total_out_hi32 = 0; + zip->bzstream.total_out_lo32 = 0; + + /* Perform the decompression. */ + r = BZ2_bzDecompress(&zip->bzstream); + switch(r) { + case BZ_STREAM_END: + /* If we're at the end of the stream, deinitialize the + * decompression context now. */ + switch(BZ2_bzDecompressEnd(&zip->bzstream)) { + case BZ_OK: + break; + default: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Failed to clean up bzip2 " + "decompressor"); + return ARCHIVE_FATAL; + } + + zip->end_of_entry = 1; + break; + case BZ_OK: + /* The decompressor has successfully decoded this + * chunk of data, but more data is still in queue. */ + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "bzip2 decompression failed"); + return ARCHIVE_FATAL; + } + + /* Update the pointers so decompressor can continue decoding. */ + to_consume = zip->bzstream.total_in_lo32; + __archive_read_consume(a, to_consume); + + total_out = ((uint64_t) zip->bzstream.total_out_hi32 << 32) + + zip->bzstream.total_out_lo32; + + zip->entry_bytes_remaining -= to_consume; + zip->entry_compressed_bytes_read += to_consume; + zip->entry_uncompressed_bytes_read += total_out; + + /* Give libarchive its due. */ + *size = total_out; + *buff = zip->uncompressed_buffer; + + /* Seek for optional marker, like in other entries. */ + r = consume_optional_marker(a, zip); + if(r != ARCHIVE_OK) + return r; + + return ARCHIVE_OK; +} + +#endif + +#ifdef HAVE_ZLIB_H +static int +zip_deflate_init(struct archive_read *a, struct zip *zip) +{ + int r; + + /* If we haven't yet read any data, initialize the decompressor. */ + if (!zip->decompress_init) { + if (zip->stream_valid) + r = inflateReset(&zip->stream); + else + r = inflateInit2(&zip->stream, + -15 /* Don't check for zlib header */); + if (r != Z_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can't initialize ZIP decompression."); + return (ARCHIVE_FATAL); + } + /* Stream structure has been set up. */ + zip->stream_valid = 1; + /* We've initialized decompression for this stream. */ + zip->decompress_init = 1; + } + return (ARCHIVE_OK); +} + +static int +zip_read_data_deflate(struct archive_read *a, const void **buff, + size_t *size, int64_t *offset) +{ + struct zip *zip; + ssize_t bytes_avail; + const void *compressed_buff, *sp; + int r; + + (void)offset; /* UNUSED */ + + zip = (struct zip *)(a->format->data); + + /* If the buffer hasn't been allocated, allocate it now. */ + if (zip->uncompressed_buffer == NULL) { + zip->uncompressed_buffer_size = 256 * 1024; + zip->uncompressed_buffer + = (unsigned char *)malloc(zip->uncompressed_buffer_size); + if (zip->uncompressed_buffer == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for ZIP decompression"); + return (ARCHIVE_FATAL); + } + } + + r = zip_deflate_init(a, zip); + if (r != ARCHIVE_OK) + return (r); + + /* + * Note: '1' here is a performance optimization. + * Recall that the decompression layer returns a count of + * available bytes; asking for more than that forces the + * decompressor to combine reads by copying data. + */ + compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail); + if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) + && bytes_avail > zip->entry_bytes_remaining) { + bytes_avail = (ssize_t)zip->entry_bytes_remaining; + } + if (bytes_avail < 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP file body"); + return (ARCHIVE_FATAL); + } + + if (zip->tctx_valid || zip->cctx_valid) { + if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) { + size_t buff_remaining = + (zip->decrypted_buffer + + zip->decrypted_buffer_size) + - (zip->decrypted_ptr + + zip->decrypted_bytes_remaining); + + if (buff_remaining > (size_t)bytes_avail) + buff_remaining = (size_t)bytes_avail; + + if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) && + zip->entry_bytes_remaining > 0) { + if ((int64_t)(zip->decrypted_bytes_remaining + + buff_remaining) + > zip->entry_bytes_remaining) { + if (zip->entry_bytes_remaining < + (int64_t)zip->decrypted_bytes_remaining) + buff_remaining = 0; + else + buff_remaining = + (size_t)zip->entry_bytes_remaining + - zip->decrypted_bytes_remaining; + } + } + if (buff_remaining > 0) { + if (zip->tctx_valid) { + trad_enc_decrypt_update(&zip->tctx, + compressed_buff, buff_remaining, + zip->decrypted_ptr + + zip->decrypted_bytes_remaining, + buff_remaining); + } else { + size_t dsize = buff_remaining; + archive_decrypto_aes_ctr_update( + &zip->cctx, + compressed_buff, buff_remaining, + zip->decrypted_ptr + + zip->decrypted_bytes_remaining, + &dsize); + } + zip->decrypted_bytes_remaining += + buff_remaining; + } + } + bytes_avail = zip->decrypted_bytes_remaining; + compressed_buff = (const char *)zip->decrypted_ptr; + } + + /* + * A bug in zlib.h: stream.next_in should be marked 'const' + * but isn't (the library never alters data through the + * next_in pointer, only reads it). The result: this ugly + * cast to remove 'const'. + */ + zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff; + zip->stream.avail_in = (uInt)bytes_avail; + zip->stream.total_in = 0; + zip->stream.next_out = zip->uncompressed_buffer; + zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size; + zip->stream.total_out = 0; + + r = inflate(&zip->stream, 0); + switch (r) { + case Z_OK: + break; + case Z_STREAM_END: + zip->end_of_entry = 1; + break; + case Z_MEM_ERROR: + archive_set_error(&a->archive, ENOMEM, + "Out of memory for ZIP decompression"); + return (ARCHIVE_FATAL); + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "ZIP decompression failed (%d)", r); + return (ARCHIVE_FATAL); + } + + /* Consume as much as the compressor actually used. */ + bytes_avail = zip->stream.total_in; + if (zip->tctx_valid || zip->cctx_valid) { + zip->decrypted_bytes_remaining -= bytes_avail; + if (zip->decrypted_bytes_remaining == 0) + zip->decrypted_ptr = zip->decrypted_buffer; + else + zip->decrypted_ptr += bytes_avail; + } + /* Calculate compressed data as much as we used.*/ + if (zip->hctx_valid) + archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail); + __archive_read_consume(a, bytes_avail); + zip->entry_bytes_remaining -= bytes_avail; + zip->entry_compressed_bytes_read += bytes_avail; + + *size = zip->stream.total_out; + zip->entry_uncompressed_bytes_read += zip->stream.total_out; + *buff = zip->uncompressed_buffer; + + if (zip->end_of_entry && zip->hctx_valid) { + r = check_authentication_code(a, NULL); + if (r != ARCHIVE_OK) + return (r); + } + + r = consume_optional_marker(a, zip); + if (r != ARCHIVE_OK) + return (r); + + return (ARCHIVE_OK); +} +#endif + +static int +read_decryption_header(struct archive_read *a) +{ + struct zip *zip = (struct zip *)(a->format->data); + const char *p; + unsigned int remaining_size; + unsigned int ts; + + /* + * Read an initialization vector data field. + */ + p = __archive_read_ahead(a, 2, NULL); + if (p == NULL) + goto truncated; + ts = zip->iv_size; + zip->iv_size = archive_le16dec(p); + __archive_read_consume(a, 2); + if (ts < zip->iv_size) { + free(zip->iv); + zip->iv = NULL; + } + p = __archive_read_ahead(a, zip->iv_size, NULL); + if (p == NULL) + goto truncated; + if (zip->iv == NULL) { + zip->iv = malloc(zip->iv_size); + if (zip->iv == NULL) + goto nomem; + } + memcpy(zip->iv, p, zip->iv_size); + __archive_read_consume(a, zip->iv_size); + + /* + * Read a size of remaining decryption header field. + */ + p = __archive_read_ahead(a, 14, NULL); + if (p == NULL) + goto truncated; + remaining_size = archive_le32dec(p); + if (remaining_size < 16 || remaining_size > (1 << 18)) + goto corrupted; + + /* Check if format version is supported. */ + if (archive_le16dec(p+4) != 3) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Unsupported encryption format version: %u", + archive_le16dec(p+4)); + return (ARCHIVE_FAILED); + } + + /* + * Read an encryption algorithm field. + */ + zip->alg_id = archive_le16dec(p+6); + switch (zip->alg_id) { + case 0x6601:/* DES */ + case 0x6602:/* RC2 */ + case 0x6603:/* 3DES 168 */ + case 0x6609:/* 3DES 112 */ + case 0x660E:/* AES 128 */ + case 0x660F:/* AES 192 */ + case 0x6610:/* AES 256 */ + case 0x6702:/* RC2 (version >= 5.2) */ + case 0x6720:/* Blowfish */ + case 0x6721:/* Twofish */ + case 0x6801:/* RC4 */ + /* Supported encryption algorithm. */ + break; + default: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Unknown encryption algorithm: %u", zip->alg_id); + return (ARCHIVE_FAILED); + } + + /* + * Read a bit length field. + */ + zip->bit_len = archive_le16dec(p+8); + + /* + * Read a flags field. + */ + zip->flags = archive_le16dec(p+10); + switch (zip->flags & 0xf000) { + case 0x0001: /* Password is required to decrypt. */ + case 0x0002: /* Certificates only. */ + case 0x0003: /* Password or certificate required to decrypt. */ + break; + default: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Unknown encryption flag: %u", zip->flags); + return (ARCHIVE_FAILED); + } + if ((zip->flags & 0xf000) == 0 || + (zip->flags & 0xf000) == 0x4000) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Unknown encryption flag: %u", zip->flags); + return (ARCHIVE_FAILED); + } + + /* + * Read an encrypted random data field. + */ + ts = zip->erd_size; + zip->erd_size = archive_le16dec(p+12); + __archive_read_consume(a, 14); + if ((zip->erd_size & 0xf) != 0 || + (zip->erd_size + 16) > remaining_size || + (zip->erd_size + 16) < zip->erd_size) + goto corrupted; + + if (ts < zip->erd_size) { + free(zip->erd); + zip->erd = NULL; + } + p = __archive_read_ahead(a, zip->erd_size, NULL); + if (p == NULL) + goto truncated; + if (zip->erd == NULL) { + zip->erd = malloc(zip->erd_size); + if (zip->erd == NULL) + goto nomem; + } + memcpy(zip->erd, p, zip->erd_size); + __archive_read_consume(a, zip->erd_size); + + /* + * Read a reserved data field. + */ + p = __archive_read_ahead(a, 4, NULL); + if (p == NULL) + goto truncated; + /* Reserved data size should be zero. */ + if (archive_le32dec(p) != 0) + goto corrupted; + __archive_read_consume(a, 4); + + /* + * Read a password validation data field. + */ + p = __archive_read_ahead(a, 2, NULL); + if (p == NULL) + goto truncated; + ts = zip->v_size; + zip->v_size = archive_le16dec(p); + __archive_read_consume(a, 2); + if ((zip->v_size & 0x0f) != 0 || + (zip->erd_size + zip->v_size + 16) > remaining_size || + (zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size)) + goto corrupted; + if (ts < zip->v_size) { + free(zip->v_data); + zip->v_data = NULL; + } + p = __archive_read_ahead(a, zip->v_size, NULL); + if (p == NULL) + goto truncated; + if (zip->v_data == NULL) { + zip->v_data = malloc(zip->v_size); + if (zip->v_data == NULL) + goto nomem; + } + memcpy(zip->v_data, p, zip->v_size); + __archive_read_consume(a, zip->v_size); + + p = __archive_read_ahead(a, 4, NULL); + if (p == NULL) + goto truncated; + zip->v_crc32 = archive_le32dec(p); + __archive_read_consume(a, 4); + + /*return (ARCHIVE_OK); + * This is not fully implemented yet.*/ + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Encrypted file is unsupported"); + return (ARCHIVE_FAILED); +truncated: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP file data"); + return (ARCHIVE_FATAL); +corrupted: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Corrupted ZIP file data"); + return (ARCHIVE_FATAL); +nomem: + archive_set_error(&a->archive, ENOMEM, + "No memory for ZIP decryption"); + return (ARCHIVE_FATAL); +} + +static int +zip_alloc_decryption_buffer(struct archive_read *a) +{ + struct zip *zip = (struct zip *)(a->format->data); + size_t bs = 256 * 1024; + + if (zip->decrypted_buffer == NULL) { + zip->decrypted_buffer_size = bs; + zip->decrypted_buffer = malloc(bs); + if (zip->decrypted_buffer == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for ZIP decryption"); + return (ARCHIVE_FATAL); + } + } + zip->decrypted_ptr = zip->decrypted_buffer; + return (ARCHIVE_OK); +} + +static int +init_traditional_PKWARE_decryption(struct archive_read *a) +{ + struct zip *zip = (struct zip *)(a->format->data); + const void *p; + int retry; + int r; + + if (zip->tctx_valid) + return (ARCHIVE_OK); + + /* + Read the 12 bytes encryption header stored at + the start of the data area. + */ +#define ENC_HEADER_SIZE 12 + if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) + && zip->entry_bytes_remaining < ENC_HEADER_SIZE) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated Zip encrypted body: only %jd bytes available", + (intmax_t)zip->entry_bytes_remaining); + return (ARCHIVE_FATAL); + } + + p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL); + if (p == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP file data"); + return (ARCHIVE_FATAL); + } + + for (retry = 0;; retry++) { + const char *passphrase; + uint8_t crcchk; + + passphrase = __archive_read_next_passphrase(a); + if (passphrase == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + (retry > 0)? + "Incorrect passphrase": + "Passphrase required for this entry"); + return (ARCHIVE_FAILED); + } + + /* + * Initialize ctx for Traditional PKWARE Decryption. + */ + r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase), + p, ENC_HEADER_SIZE, &crcchk); + if (r == 0 && crcchk == zip->entry->decdat) + break;/* The passphrase is OK. */ + if (retry > 10000) { + /* Avoid infinity loop. */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Too many incorrect passphrases"); + return (ARCHIVE_FAILED); + } + } + + __archive_read_consume(a, ENC_HEADER_SIZE); + zip->tctx_valid = 1; + if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) { + zip->entry_bytes_remaining -= ENC_HEADER_SIZE; + } + /*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/ + zip->entry_compressed_bytes_read += ENC_HEADER_SIZE; + zip->decrypted_bytes_remaining = 0; + + return (zip_alloc_decryption_buffer(a)); +#undef ENC_HEADER_SIZE +} + +static int +init_WinZip_AES_decryption(struct archive_read *a) +{ + struct zip *zip = (struct zip *)(a->format->data); + const void *p; + const uint8_t *pv; + size_t key_len, salt_len; + uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE]; + int retry; + int r; + + if (zip->cctx_valid || zip->hctx_valid) + return (ARCHIVE_OK); + + switch (zip->entry->aes_extra.strength) { + case 1: salt_len = 8; key_len = 16; break; + case 2: salt_len = 12; key_len = 24; break; + case 3: salt_len = 16; key_len = 32; break; + default: goto corrupted; + } + p = __archive_read_ahead(a, salt_len + 2, NULL); + if (p == NULL) + goto truncated; + + for (retry = 0;; retry++) { + const char *passphrase; + + passphrase = __archive_read_next_passphrase(a); + if (passphrase == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + (retry > 0)? + "Incorrect passphrase": + "Passphrase required for this entry"); + return (ARCHIVE_FAILED); + } + memset(derived_key, 0, sizeof(derived_key)); + r = archive_pbkdf2_sha1(passphrase, strlen(passphrase), + p, salt_len, 1000, derived_key, key_len * 2 + 2); + if (r != 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Decryption is unsupported due to lack of " + "crypto library"); + return (ARCHIVE_FAILED); + } + + /* Check password verification value. */ + pv = ((const uint8_t *)p) + salt_len; + if (derived_key[key_len * 2] == pv[0] && + derived_key[key_len * 2 + 1] == pv[1]) + break;/* The passphrase is OK. */ + if (retry > 10000) { + /* Avoid infinity loop. */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Too many incorrect passphrases"); + return (ARCHIVE_FAILED); + } + } + + r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len); + if (r != 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Decryption is unsupported due to lack of crypto library"); + return (ARCHIVE_FAILED); + } + r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len); + if (r != 0) { + archive_decrypto_aes_ctr_release(&zip->cctx); + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Failed to initialize HMAC-SHA1"); + return (ARCHIVE_FAILED); + } + zip->cctx_valid = zip->hctx_valid = 1; + __archive_read_consume(a, salt_len + 2); + zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE; + if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) + && zip->entry_bytes_remaining < 0) + goto corrupted; + zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE; + zip->decrypted_bytes_remaining = 0; + + zip->entry->compression = zip->entry->aes_extra.compression; + return (zip_alloc_decryption_buffer(a)); + +truncated: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP file data"); + return (ARCHIVE_FATAL); +corrupted: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Corrupted ZIP file data"); + return (ARCHIVE_FATAL); +} + +static int +archive_read_format_zip_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + int r; + struct zip *zip = (struct zip *)(a->format->data); + + if (zip->has_encrypted_entries == + ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { + zip->has_encrypted_entries = 0; + } + + *offset = zip->entry_uncompressed_bytes_read; + *size = 0; + *buff = NULL; + + /* If we hit end-of-entry last time, return ARCHIVE_EOF. */ + if (zip->end_of_entry) + return (ARCHIVE_EOF); + + /* Return EOF immediately if this is a non-regular file. */ + if (AE_IFREG != (zip->entry->mode & AE_IFMT)) + return (ARCHIVE_EOF); + + __archive_read_consume(a, zip->unconsumed); + zip->unconsumed = 0; + + if (zip->init_decryption) { + zip->has_encrypted_entries = 1; + if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED) + r = read_decryption_header(a); + else if (zip->entry->compression == WINZIP_AES_ENCRYPTION) + r = init_WinZip_AES_decryption(a); + else + r = init_traditional_PKWARE_decryption(a); + if (r != ARCHIVE_OK) + return (r); + zip->init_decryption = 0; + } + + switch(zip->entry->compression) { + case 0: /* No compression. */ + r = zip_read_data_none(a, buff, size, offset); + break; +#ifdef HAVE_BZLIB_H + case 12: /* ZIPx bzip2 compression. */ + r = zip_read_data_zipx_bzip2(a, buff, size, offset); + break; +#endif +#if HAVE_LZMA_H && HAVE_LIBLZMA + case 14: /* ZIPx LZMA compression. */ + r = zip_read_data_zipx_lzma_alone(a, buff, size, offset); + break; + case 95: /* ZIPx XZ compression. */ + r = zip_read_data_zipx_xz(a, buff, size, offset); + break; +#endif + /* PPMd support is built-in, so we don't need any #if guards. */ + case 98: /* ZIPx PPMd compression. */ + r = zip_read_data_zipx_ppmd(a, buff, size, offset); + break; + +#ifdef HAVE_ZLIB_H + case 8: /* Deflate compression. */ + r = zip_read_data_deflate(a, buff, size, offset); + break; +#endif + default: /* Unsupported compression. */ + /* Return a warning. */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Unsupported ZIP compression method (%d: %s)", + zip->entry->compression, compression_name(zip->entry->compression)); + /* We can't decompress this entry, but we will + * be able to skip() it and try the next entry. */ + return (ARCHIVE_FAILED); + break; + } + if (r != ARCHIVE_OK) + return (r); + /* Update checksum */ + if (*size) + zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff, + (unsigned)*size); + /* If we hit the end, swallow any end-of-data marker. */ + if (zip->end_of_entry) { + /* Check file size, CRC against these values. */ + if (zip->entry->compressed_size != + zip->entry_compressed_bytes_read) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "ZIP compressed data is wrong size " + "(read %jd, expected %jd)", + (intmax_t)zip->entry_compressed_bytes_read, + (intmax_t)zip->entry->compressed_size); + return (ARCHIVE_WARN); + } + /* Size field only stores the lower 32 bits of the actual + * size. */ + if ((zip->entry->uncompressed_size & UINT32_MAX) + != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "ZIP uncompressed data is wrong size " + "(read %jd, expected %jd)\n", + (intmax_t)zip->entry_uncompressed_bytes_read, + (intmax_t)zip->entry->uncompressed_size); + return (ARCHIVE_WARN); + } + /* Check computed CRC against header */ + if ((!zip->hctx_valid || + zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) && + zip->entry->crc32 != zip->entry_crc32 + && !zip->ignore_crc32) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "ZIP bad CRC: 0x%lx should be 0x%lx", + (unsigned long)zip->entry_crc32, + (unsigned long)zip->entry->crc32); + return (ARCHIVE_WARN); + } + } + + return (ARCHIVE_OK); +} + +static int +archive_read_format_zip_cleanup(struct archive_read *a) +{ + struct zip *zip; + struct zip_entry *zip_entry, *next_zip_entry; + + zip = (struct zip *)(a->format->data); + +#ifdef HAVE_ZLIB_H + if (zip->stream_valid) + inflateEnd(&zip->stream); +#endif + +#if HAVE_LZMA_H && HAVE_LIBLZMA + if (zip->zipx_lzma_valid) { + lzma_end(&zip->zipx_lzma_stream); + } +#endif + +#ifdef HAVE_BZLIB_H + if (zip->bzstream_valid) { + BZ2_bzDecompressEnd(&zip->bzstream); + } +#endif + + free(zip->uncompressed_buffer); + + if (zip->ppmd8_valid) + __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8); + + if (zip->zip_entries) { + zip_entry = zip->zip_entries; + while (zip_entry != NULL) { + next_zip_entry = zip_entry->next; + archive_string_free(&zip_entry->rsrcname); + free(zip_entry); + zip_entry = next_zip_entry; + } + } + free(zip->decrypted_buffer); + if (zip->cctx_valid) + archive_decrypto_aes_ctr_release(&zip->cctx); + if (zip->hctx_valid) + archive_hmac_sha1_cleanup(&zip->hctx); + free(zip->iv); + free(zip->erd); + free(zip->v_data); + archive_string_free(&zip->format_name); + free(zip); + (a->format->data) = NULL; + return (ARCHIVE_OK); +} + +static int +archive_read_format_zip_has_encrypted_entries(struct archive_read *_a) +{ + if (_a && _a->format) { + struct zip * zip = (struct zip *)_a->format->data; + if (zip) { + return zip->has_encrypted_entries; + } + } + return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; +} + +static int +archive_read_format_zip_options(struct archive_read *a, + const char *key, const char *val) +{ + struct zip *zip; + int ret = ARCHIVE_FAILED; + + zip = (struct zip *)(a->format->data); + if (strcmp(key, "compat-2x") == 0) { + /* Handle filenames as libarchive 2.x */ + zip->init_default_conversion = (val != NULL) ? 1 : 0; + return (ARCHIVE_OK); + } else if (strcmp(key, "hdrcharset") == 0) { + if (val == NULL || val[0] == 0) + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "zip: hdrcharset option needs a character-set name" + ); + else { + zip->sconv = archive_string_conversion_from_charset( + &a->archive, val, 0); + if (zip->sconv != NULL) { + if (strcmp(val, "UTF-8") == 0) + zip->sconv_utf8 = zip->sconv; + ret = ARCHIVE_OK; + } else + ret = ARCHIVE_FATAL; + } + return (ret); + } else if (strcmp(key, "ignorecrc32") == 0) { + /* Mostly useful for testing. */ + if (val == NULL || val[0] == 0) { + zip->crc32func = real_crc32; + zip->ignore_crc32 = 0; + } else { + zip->crc32func = fake_crc32; + zip->ignore_crc32 = 1; + } + return (ARCHIVE_OK); + } else if (strcmp(key, "mac-ext") == 0) { + zip->process_mac_extensions = (val != NULL && val[0] != 0); + return (ARCHIVE_OK); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +int +archive_read_support_format_zip(struct archive *a) +{ + int r; + r = archive_read_support_format_zip_streamable(a); + if (r != ARCHIVE_OK) + return r; + return (archive_read_support_format_zip_seekable(a)); +} + +/* ------------------------------------------------------------------------ */ + +/* + * Streaming-mode support + */ + + +static int +archive_read_support_format_zip_capabilities_streamable(struct archive_read * a) +{ + (void)a; /* UNUSED */ + return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA | + ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA); +} + +static int +archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid) +{ + const char *p; + + (void)best_bid; /* UNUSED */ + + if ((p = __archive_read_ahead(a, 4, NULL)) == NULL) + return (-1); + + /* + * Bid of 29 here comes from: + * + 16 bits for "PK", + * + next 16-bit field has 6 options so contributes + * about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits + * + * So we've effectively verified ~29 total bits of check data. + */ + if (p[0] == 'P' && p[1] == 'K') { + if ((p[2] == '\001' && p[3] == '\002') + || (p[2] == '\003' && p[3] == '\004') + || (p[2] == '\005' && p[3] == '\006') + || (p[2] == '\006' && p[3] == '\006') + || (p[2] == '\007' && p[3] == '\010') + || (p[2] == '0' && p[3] == '0')) + return (29); + } + + /* TODO: It's worth looking ahead a little bit for a valid + * PK signature. In particular, that would make it possible + * to read some UUEncoded SFX files or SFX files coming from + * a network socket. */ + + return (0); +} + +static int +archive_read_format_zip_streamable_read_header(struct archive_read *a, + struct archive_entry *entry) +{ + struct zip *zip; + + a->archive.archive_format = ARCHIVE_FORMAT_ZIP; + if (a->archive.archive_format_name == NULL) + a->archive.archive_format_name = "ZIP"; + + zip = (struct zip *)(a->format->data); + + /* + * It should be sufficient to call archive_read_next_header() for + * a reader to determine if an entry is encrypted or not. If the + * encryption of an entry is only detectable when calling + * archive_read_data(), so be it. We'll do the same check there + * as well. + */ + if (zip->has_encrypted_entries == + ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) + zip->has_encrypted_entries = 0; + + /* Make sure we have a zip_entry structure to use. */ + if (zip->zip_entries == NULL) { + zip->zip_entries = malloc(sizeof(struct zip_entry)); + if (zip->zip_entries == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Out of memory"); + return ARCHIVE_FATAL; + } + } + zip->entry = zip->zip_entries; + memset(zip->entry, 0, sizeof(struct zip_entry)); + + if (zip->cctx_valid) + archive_decrypto_aes_ctr_release(&zip->cctx); + if (zip->hctx_valid) + archive_hmac_sha1_cleanup(&zip->hctx); + zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0; + __archive_read_reset_passphrase(a); + + /* Search ahead for the next local file header. */ + __archive_read_consume(a, zip->unconsumed); + zip->unconsumed = 0; + for (;;) { + int64_t skipped = 0; + const char *p, *end; + ssize_t bytes; + + p = __archive_read_ahead(a, 4, &bytes); + if (p == NULL) + return (ARCHIVE_FATAL); + end = p + bytes; + + while (p + 4 <= end) { + if (p[0] == 'P' && p[1] == 'K') { + if (p[2] == '\003' && p[3] == '\004') { + /* Regular file entry. */ + __archive_read_consume(a, skipped); + return zip_read_local_file_header(a, + entry, zip); + } + + /* + * TODO: We cannot restore permissions + * based only on the local file headers. + * Consider scanning the central + * directory and returning additional + * entries for at least directories. + * This would allow us to properly set + * directory permissions. + * + * This won't help us fix symlinks + * and may not help with regular file + * permissions, either. <sigh> + */ + if (p[2] == '\001' && p[3] == '\002') { + return (ARCHIVE_EOF); + } + + /* End of central directory? Must be an + * empty archive. */ + if ((p[2] == '\005' && p[3] == '\006') + || (p[2] == '\006' && p[3] == '\006')) + return (ARCHIVE_EOF); + } + ++p; + ++skipped; + } + __archive_read_consume(a, skipped); + } +} + +static int +archive_read_format_zip_read_data_skip_streamable(struct archive_read *a) +{ + struct zip *zip; + int64_t bytes_skipped; + + zip = (struct zip *)(a->format->data); + bytes_skipped = __archive_read_consume(a, zip->unconsumed); + zip->unconsumed = 0; + if (bytes_skipped < 0) + return (ARCHIVE_FATAL); + + /* If we've already read to end of data, we're done. */ + if (zip->end_of_entry) + return (ARCHIVE_OK); + + /* So we know we're streaming... */ + if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) + || zip->entry->compressed_size > 0) { + /* We know the compressed length, so we can just skip. */ + bytes_skipped = __archive_read_consume(a, + zip->entry_bytes_remaining); + if (bytes_skipped < 0) + return (ARCHIVE_FATAL); + return (ARCHIVE_OK); + } + + if (zip->init_decryption) { + int r; + + zip->has_encrypted_entries = 1; + if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED) + r = read_decryption_header(a); + else if (zip->entry->compression == WINZIP_AES_ENCRYPTION) + r = init_WinZip_AES_decryption(a); + else + r = init_traditional_PKWARE_decryption(a); + if (r != ARCHIVE_OK) + return (r); + zip->init_decryption = 0; + } + + /* We're streaming and we don't know the length. */ + /* If the body is compressed and we know the format, we can + * find an exact end-of-entry by decompressing it. */ + switch (zip->entry->compression) { +#ifdef HAVE_ZLIB_H + case 8: /* Deflate compression. */ + while (!zip->end_of_entry) { + int64_t offset = 0; + const void *buff = NULL; + size_t size = 0; + int r; + r = zip_read_data_deflate(a, &buff, &size, &offset); + if (r != ARCHIVE_OK) + return (r); + } + return ARCHIVE_OK; +#endif + default: /* Uncompressed or unknown. */ + /* Scan for a PK\007\010 signature. */ + for (;;) { + const char *p, *buff; + ssize_t bytes_avail; + buff = __archive_read_ahead(a, 16, &bytes_avail); + if (bytes_avail < 16) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP file data"); + return (ARCHIVE_FATAL); + } + p = buff; + while (p <= buff + bytes_avail - 16) { + if (p[3] == 'P') { p += 3; } + else if (p[3] == 'K') { p += 2; } + else if (p[3] == '\007') { p += 1; } + else if (p[3] == '\010' && p[2] == '\007' + && p[1] == 'K' && p[0] == 'P') { + if (zip->entry->flags & LA_USED_ZIP64) + __archive_read_consume(a, + p - buff + 24); + else + __archive_read_consume(a, + p - buff + 16); + return ARCHIVE_OK; + } else { p += 4; } + } + __archive_read_consume(a, p - buff); + } + } +} + +int +archive_read_support_format_zip_streamable(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct zip *zip; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_zip"); + + zip = (struct zip *)calloc(1, sizeof(*zip)); + if (zip == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate zip data"); + return (ARCHIVE_FATAL); + } + + /* Streamable reader doesn't support mac extensions. */ + zip->process_mac_extensions = 0; + + /* + * Until enough data has been read, we cannot tell about + * any encrypted entries yet. + */ + zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; + zip->crc32func = real_crc32; + + r = __archive_read_register_format(a, + zip, + "zip", + archive_read_format_zip_streamable_bid, + archive_read_format_zip_options, + archive_read_format_zip_streamable_read_header, + archive_read_format_zip_read_data, + archive_read_format_zip_read_data_skip_streamable, + NULL, + archive_read_format_zip_cleanup, + archive_read_support_format_zip_capabilities_streamable, + archive_read_format_zip_has_encrypted_entries); + + if (r != ARCHIVE_OK) + free(zip); + return (ARCHIVE_OK); +} + +/* ------------------------------------------------------------------------ */ + +/* + * Seeking-mode support + */ + +static int +archive_read_support_format_zip_capabilities_seekable(struct archive_read * a) +{ + (void)a; /* UNUSED */ + return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA | + ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA); +} + +/* + * TODO: This is a performance sink because it forces the read core to + * drop buffered data from the start of file, which will then have to + * be re-read again if this bidder loses. + * + * We workaround this a little by passing in the best bid so far so + * that later bidders can do nothing if they know they'll never + * outbid. But we can certainly do better... + */ +static int +read_eocd(struct zip *zip, const char *p, int64_t current_offset) +{ + /* Sanity-check the EOCD we've found. */ + + /* This must be the first volume. */ + if (archive_le16dec(p + 4) != 0) + return 0; + /* Central directory must be on this volume. */ + if (archive_le16dec(p + 4) != archive_le16dec(p + 6)) + return 0; + /* All central directory entries must be on this volume. */ + if (archive_le16dec(p + 10) != archive_le16dec(p + 8)) + return 0; + /* Central directory can't extend beyond start of EOCD record. */ + if (archive_le32dec(p + 16) + archive_le32dec(p + 12) + > current_offset) + return 0; + + /* Save the central directory location for later use. */ + zip->central_directory_offset = archive_le32dec(p + 16); + + /* This is just a tiny bit higher than the maximum + returned by the streaming Zip bidder. This ensures + that the more accurate seeking Zip parser wins + whenever seek is available. */ + return 32; +} + +/* + * Examine Zip64 EOCD locator: If it's valid, store the information + * from it. + */ +static int +read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p) +{ + int64_t eocd64_offset; + int64_t eocd64_size; + + /* Sanity-check the locator record. */ + + /* Central dir must be on first volume. */ + if (archive_le32dec(p + 4) != 0) + return 0; + /* Must be only a single volume. */ + if (archive_le32dec(p + 16) != 1) + return 0; + + /* Find the Zip64 EOCD record. */ + eocd64_offset = archive_le64dec(p + 8); + if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0) + return 0; + if ((p = __archive_read_ahead(a, 56, NULL)) == NULL) + return 0; + /* Make sure we can read all of it. */ + eocd64_size = archive_le64dec(p + 4) + 12; + if (eocd64_size < 56 || eocd64_size > 16384) + return 0; + if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL) + return 0; + + /* Sanity-check the EOCD64 */ + if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */ + return 0; + if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */ + return 0; + /* CD can't be split. */ + if (archive_le64dec(p + 24) != archive_le64dec(p + 32)) + return 0; + + /* Save the central directory offset for later use. */ + zip->central_directory_offset = archive_le64dec(p + 48); + + return 32; +} + +static int +archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid) +{ + struct zip *zip = (struct zip *)a->format->data; + int64_t file_size, current_offset; + const char *p; + int i, tail; + + /* If someone has already bid more than 32, then avoid + trashing the look-ahead buffers with a seek. */ + if (best_bid > 32) + return (-1); + + file_size = __archive_read_seek(a, 0, SEEK_END); + if (file_size <= 0) + return 0; + + /* Search last 16k of file for end-of-central-directory + * record (which starts with PK\005\006) */ + tail = (int)zipmin(1024 * 16, file_size); + current_offset = __archive_read_seek(a, -tail, SEEK_END); + if (current_offset < 0) + return 0; + if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL) + return 0; + /* Boyer-Moore search backwards from the end, since we want + * to match the last EOCD in the file (there can be more than + * one if there is an uncompressed Zip archive as a member + * within this Zip archive). */ + for (i = tail - 22; i > 0;) { + switch (p[i]) { + case 'P': + if (memcmp(p + i, "PK\005\006", 4) == 0) { + int ret = read_eocd(zip, p + i, + current_offset + i); + /* Zip64 EOCD locator precedes + * regular EOCD if present. */ + if (i >= 20 && memcmp(p + i - 20, "PK\006\007", 4) == 0) { + int ret_zip64 = read_zip64_eocd(a, zip, p + i - 20); + if (ret_zip64 > ret) + ret = ret_zip64; + } + return (ret); + } + i -= 4; + break; + case 'K': i -= 1; break; + case 005: i -= 2; break; + case 006: i -= 3; break; + default: i -= 4; break; + } + } + return 0; +} + +/* The red-black trees are only used in seeking mode to manage + * the in-memory copy of the central directory. */ + +static int +cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2) +{ + const struct zip_entry *e1 = (const struct zip_entry *)n1; + const struct zip_entry *e2 = (const struct zip_entry *)n2; + + if (e1->local_header_offset > e2->local_header_offset) + return -1; + if (e1->local_header_offset < e2->local_header_offset) + return 1; + return 0; +} + +static int +cmp_key(const struct archive_rb_node *n, const void *key) +{ + /* This function won't be called */ + (void)n; /* UNUSED */ + (void)key; /* UNUSED */ + return 1; +} + +static const struct archive_rb_tree_ops rb_ops = { + &cmp_node, &cmp_key +}; + +static int +rsrc_cmp_node(const struct archive_rb_node *n1, + const struct archive_rb_node *n2) +{ + const struct zip_entry *e1 = (const struct zip_entry *)n1; + const struct zip_entry *e2 = (const struct zip_entry *)n2; + + return (strcmp(e2->rsrcname.s, e1->rsrcname.s)); +} + +static int +rsrc_cmp_key(const struct archive_rb_node *n, const void *key) +{ + const struct zip_entry *e = (const struct zip_entry *)n; + return (strcmp((const char *)key, e->rsrcname.s)); +} + +static const struct archive_rb_tree_ops rb_rsrc_ops = { + &rsrc_cmp_node, &rsrc_cmp_key +}; + +static const char * +rsrc_basename(const char *name, size_t name_length) +{ + const char *s, *r; + + r = s = name; + for (;;) { + s = memchr(s, '/', name_length - (s - name)); + if (s == NULL) + break; + r = ++s; + } + return (r); +} + +static void +expose_parent_dirs(struct zip *zip, const char *name, size_t name_length) +{ + struct archive_string str; + struct zip_entry *dir; + char *s; + + archive_string_init(&str); + archive_strncpy(&str, name, name_length); + for (;;) { + s = strrchr(str.s, '/'); + if (s == NULL) + break; + *s = '\0'; + /* Transfer the parent directory from zip->tree_rsrc RB + * tree to zip->tree RB tree to expose. */ + dir = (struct zip_entry *) + __archive_rb_tree_find_node(&zip->tree_rsrc, str.s); + if (dir == NULL) + break; + __archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node); + archive_string_free(&dir->rsrcname); + __archive_rb_tree_insert_node(&zip->tree, &dir->node); + } + archive_string_free(&str); +} + +static int +slurp_central_directory(struct archive_read *a, struct archive_entry* entry, + struct zip *zip) +{ + ssize_t i; + unsigned found; + int64_t correction; + ssize_t bytes_avail; + const char *p; + + /* + * Find the start of the central directory. The end-of-CD + * record has our starting point, but there are lots of + * Zip archives which have had other data prepended to the + * file, which makes the recorded offsets all too small. + * So we search forward from the specified offset until we + * find the real start of the central directory. Then we + * know the correction we need to apply to account for leading + * padding. + */ + if (__archive_read_seek(a, zip->central_directory_offset, SEEK_SET) < 0) + return ARCHIVE_FATAL; + + found = 0; + while (!found) { + if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL) + return ARCHIVE_FATAL; + for (found = 0, i = 0; !found && i < bytes_avail - 4;) { + switch (p[i + 3]) { + case 'P': i += 3; break; + case 'K': i += 2; break; + case 001: i += 1; break; + case 002: + if (memcmp(p + i, "PK\001\002", 4) == 0) { + p += i; + found = 1; + } else + i += 4; + break; + case 005: i += 1; break; + case 006: + if (memcmp(p + i, "PK\005\006", 4) == 0) { + p += i; + found = 1; + } else if (memcmp(p + i, "PK\006\006", 4) == 0) { + p += i; + found = 1; + } else + i += 1; + break; + default: i += 4; break; + } + } + __archive_read_consume(a, i); + } + correction = archive_filter_bytes(&a->archive, 0) + - zip->central_directory_offset; + + __archive_rb_tree_init(&zip->tree, &rb_ops); + __archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops); + + zip->central_directory_entries_total = 0; + while (1) { + struct zip_entry *zip_entry; + size_t filename_length, extra_length, comment_length; + uint32_t external_attributes; + const char *name, *r; + + if ((p = __archive_read_ahead(a, 4, NULL)) == NULL) + return ARCHIVE_FATAL; + if (memcmp(p, "PK\006\006", 4) == 0 + || memcmp(p, "PK\005\006", 4) == 0) { + break; + } else if (memcmp(p, "PK\001\002", 4) != 0) { + archive_set_error(&a->archive, + -1, "Invalid central directory signature"); + return ARCHIVE_FATAL; + } + if ((p = __archive_read_ahead(a, 46, NULL)) == NULL) + return ARCHIVE_FATAL; + + zip_entry = calloc(1, sizeof(struct zip_entry)); + if (zip_entry == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate zip entry"); + return ARCHIVE_FATAL; + } + zip_entry->next = zip->zip_entries; + zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY; + zip->zip_entries = zip_entry; + zip->central_directory_entries_total++; + + /* version = p[4]; */ + zip_entry->system = p[5]; + /* version_required = archive_le16dec(p + 6); */ + zip_entry->zip_flags = archive_le16dec(p + 8); + if (zip_entry->zip_flags + & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){ + zip->has_encrypted_entries = 1; + } + zip_entry->compression = (char)archive_le16dec(p + 10); + zip_entry->mtime = zip_time(p + 12); + zip_entry->crc32 = archive_le32dec(p + 16); + if (zip_entry->zip_flags & ZIP_LENGTH_AT_END) + zip_entry->decdat = p[13]; + else + zip_entry->decdat = p[19]; + zip_entry->compressed_size = archive_le32dec(p + 20); + zip_entry->uncompressed_size = archive_le32dec(p + 24); + filename_length = archive_le16dec(p + 28); + extra_length = archive_le16dec(p + 30); + comment_length = archive_le16dec(p + 32); + /* disk_start = archive_le16dec(p + 34); + * Better be zero. + * internal_attributes = archive_le16dec(p + 36); + * text bit */ + external_attributes = archive_le32dec(p + 38); + zip_entry->local_header_offset = + archive_le32dec(p + 42) + correction; + + /* If we can't guess the mode, leave it zero here; + when we read the local file header we might get + more information. */ + if (zip_entry->system == 3) { + zip_entry->mode = external_attributes >> 16; + } else if (zip_entry->system == 0) { + // Interpret MSDOS directory bit + if (0x10 == (external_attributes & 0x10)) { + zip_entry->mode = AE_IFDIR | 0775; + } else { + zip_entry->mode = AE_IFREG | 0664; + } + if (0x01 == (external_attributes & 0x01)) { + // Read-only bit; strip write permissions + zip_entry->mode &= 0555; + } + } else { + zip_entry->mode = 0; + } + + /* We're done with the regular data; get the filename and + * extra data. */ + __archive_read_consume(a, 46); + p = __archive_read_ahead(a, filename_length + extra_length, + NULL); + if (p == NULL) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP file header"); + return ARCHIVE_FATAL; + } + if (ARCHIVE_OK != process_extra(a, entry, p + filename_length, + extra_length, zip_entry)) { + return ARCHIVE_FATAL; + } + + /* + * Mac resource fork files are stored under the + * "__MACOSX/" directory, so we should check if + * it is. + */ + if (!zip->process_mac_extensions) { + /* Treat every entry as a regular entry. */ + __archive_rb_tree_insert_node(&zip->tree, + &zip_entry->node); + } else { + name = p; + r = rsrc_basename(name, filename_length); + if (filename_length >= 9 && + strncmp("__MACOSX/", name, 9) == 0) { + /* If this file is not a resource fork nor + * a directory. We should treat it as a non + * resource fork file to expose it. */ + if (name[filename_length-1] != '/' && + (r - name < 3 || r[0] != '.' || + r[1] != '_')) { + __archive_rb_tree_insert_node( + &zip->tree, &zip_entry->node); + /* Expose its parent directories. */ + expose_parent_dirs(zip, name, + filename_length); + } else { + /* This file is a resource fork file or + * a directory. */ + archive_strncpy(&(zip_entry->rsrcname), + name, filename_length); + __archive_rb_tree_insert_node( + &zip->tree_rsrc, &zip_entry->node); + } + } else { + /* Generate resource fork name to find its + * resource file at zip->tree_rsrc. */ + archive_strcpy(&(zip_entry->rsrcname), + "__MACOSX/"); + archive_strncat(&(zip_entry->rsrcname), + name, r - name); + archive_strcat(&(zip_entry->rsrcname), "._"); + archive_strncat(&(zip_entry->rsrcname), + name + (r - name), + filename_length - (r - name)); + /* Register an entry to RB tree to sort it by + * file offset. */ + __archive_rb_tree_insert_node(&zip->tree, + &zip_entry->node); + } + } + + /* Skip the comment too ... */ + __archive_read_consume(a, + filename_length + extra_length + comment_length); + } + + return ARCHIVE_OK; +} + +static ssize_t +zip_get_local_file_header_size(struct archive_read *a, size_t extra) +{ + const char *p; + ssize_t filename_length, extra_length; + + if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP file header"); + return (ARCHIVE_WARN); + } + p += extra; + + if (memcmp(p, "PK\003\004", 4) != 0) { + archive_set_error(&a->archive, -1, "Damaged Zip archive"); + return ARCHIVE_WARN; + } + filename_length = archive_le16dec(p + 26); + extra_length = archive_le16dec(p + 28); + + return (30 + filename_length + extra_length); +} + +static int +zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry, + struct zip_entry *rsrc) +{ + struct zip *zip = (struct zip *)a->format->data; + unsigned char *metadata, *mp; + int64_t offset = archive_filter_bytes(&a->archive, 0); + size_t remaining_bytes, metadata_bytes; + ssize_t hsize; + int ret = ARCHIVE_OK, eof; + + switch(rsrc->compression) { + case 0: /* No compression. */ + if (rsrc->uncompressed_size != rsrc->compressed_size) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Malformed OS X metadata entry: " + "inconsistent size"); + return (ARCHIVE_FATAL); + } +#ifdef HAVE_ZLIB_H + case 8: /* Deflate compression. */ +#endif + break; + default: /* Unsupported compression. */ + /* Return a warning. */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Unsupported ZIP compression method (%s)", + compression_name(rsrc->compression)); + /* We can't decompress this entry, but we will + * be able to skip() it and try the next entry. */ + return (ARCHIVE_WARN); + } + + if (rsrc->uncompressed_size > (4 * 1024 * 1024)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Mac metadata is too large: %jd > 4M bytes", + (intmax_t)rsrc->uncompressed_size); + return (ARCHIVE_WARN); + } + if (rsrc->compressed_size > (4 * 1024 * 1024)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Mac metadata is too large: %jd > 4M bytes", + (intmax_t)rsrc->compressed_size); + return (ARCHIVE_WARN); + } + + metadata = malloc((size_t)rsrc->uncompressed_size); + if (metadata == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Mac metadata"); + return (ARCHIVE_FATAL); + } + + if (offset < rsrc->local_header_offset) + __archive_read_consume(a, rsrc->local_header_offset - offset); + else if (offset != rsrc->local_header_offset) { + __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET); + } + + hsize = zip_get_local_file_header_size(a, 0); + __archive_read_consume(a, hsize); + + remaining_bytes = (size_t)rsrc->compressed_size; + metadata_bytes = (size_t)rsrc->uncompressed_size; + mp = metadata; + eof = 0; + while (!eof && remaining_bytes) { + const unsigned char *p; + ssize_t bytes_avail; + size_t bytes_used; + + p = __archive_read_ahead(a, 1, &bytes_avail); + if (p == NULL) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Truncated ZIP file header"); + ret = ARCHIVE_WARN; + goto exit_mac_metadata; + } + if ((size_t)bytes_avail > remaining_bytes) + bytes_avail = remaining_bytes; + switch(rsrc->compression) { + case 0: /* No compression. */ + if ((size_t)bytes_avail > metadata_bytes) + bytes_avail = metadata_bytes; + memcpy(mp, p, bytes_avail); + bytes_used = (size_t)bytes_avail; + metadata_bytes -= bytes_used; + mp += bytes_used; + if (metadata_bytes == 0) + eof = 1; + break; +#ifdef HAVE_ZLIB_H + case 8: /* Deflate compression. */ + { + int r; + + ret = zip_deflate_init(a, zip); + if (ret != ARCHIVE_OK) + goto exit_mac_metadata; + zip->stream.next_in = + (Bytef *)(uintptr_t)(const void *)p; + zip->stream.avail_in = (uInt)bytes_avail; + zip->stream.total_in = 0; + zip->stream.next_out = mp; + zip->stream.avail_out = (uInt)metadata_bytes; + zip->stream.total_out = 0; + + r = inflate(&zip->stream, 0); + switch (r) { + case Z_OK: + break; + case Z_STREAM_END: + eof = 1; + break; + case Z_MEM_ERROR: + archive_set_error(&a->archive, ENOMEM, + "Out of memory for ZIP decompression"); + ret = ARCHIVE_FATAL; + goto exit_mac_metadata; + default: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "ZIP decompression failed (%d)", r); + ret = ARCHIVE_FATAL; + goto exit_mac_metadata; + } + bytes_used = zip->stream.total_in; + metadata_bytes -= zip->stream.total_out; + mp += zip->stream.total_out; + break; + } +#endif + default: + bytes_used = 0; + break; + } + __archive_read_consume(a, bytes_used); + remaining_bytes -= bytes_used; + } + archive_entry_copy_mac_metadata(entry, metadata, + (size_t)rsrc->uncompressed_size - metadata_bytes); + +exit_mac_metadata: + __archive_read_seek(a, offset, SEEK_SET); + zip->decompress_init = 0; + free(metadata); + return (ret); +} + +static int +archive_read_format_zip_seekable_read_header(struct archive_read *a, + struct archive_entry *entry) +{ + struct zip *zip = (struct zip *)a->format->data; + struct zip_entry *rsrc; + int64_t offset; + int r, ret = ARCHIVE_OK; + + /* + * It should be sufficient to call archive_read_next_header() for + * a reader to determine if an entry is encrypted or not. If the + * encryption of an entry is only detectable when calling + * archive_read_data(), so be it. We'll do the same check there + * as well. + */ + if (zip->has_encrypted_entries == + ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) + zip->has_encrypted_entries = 0; + + a->archive.archive_format = ARCHIVE_FORMAT_ZIP; + if (a->archive.archive_format_name == NULL) + a->archive.archive_format_name = "ZIP"; + + if (zip->zip_entries == NULL) { + r = slurp_central_directory(a, entry, zip); + if (r != ARCHIVE_OK) + return r; + /* Get first entry whose local header offset is lower than + * other entries in the archive file. */ + zip->entry = + (struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree); + } else if (zip->entry != NULL) { + /* Get next entry in local header offset order. */ + zip->entry = (struct zip_entry *)__archive_rb_tree_iterate( + &zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT); + } + + if (zip->entry == NULL) + return ARCHIVE_EOF; + + if (zip->entry->rsrcname.s) + rsrc = (struct zip_entry *)__archive_rb_tree_find_node( + &zip->tree_rsrc, zip->entry->rsrcname.s); + else + rsrc = NULL; + + if (zip->cctx_valid) + archive_decrypto_aes_ctr_release(&zip->cctx); + if (zip->hctx_valid) + archive_hmac_sha1_cleanup(&zip->hctx); + zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0; + __archive_read_reset_passphrase(a); + + /* File entries are sorted by the header offset, we should mostly + * use __archive_read_consume to advance a read point to avoid + * redundant data reading. */ + offset = archive_filter_bytes(&a->archive, 0); + if (offset < zip->entry->local_header_offset) + __archive_read_consume(a, + zip->entry->local_header_offset - offset); + else if (offset != zip->entry->local_header_offset) { + __archive_read_seek(a, zip->entry->local_header_offset, + SEEK_SET); + } + zip->unconsumed = 0; + r = zip_read_local_file_header(a, entry, zip); + if (r != ARCHIVE_OK) + return r; + if (rsrc) { + int ret2 = zip_read_mac_metadata(a, entry, rsrc); + if (ret2 < ret) + ret = ret2; + } + return (ret); +} + +/* + * We're going to seek for the next header anyway, so we don't + * need to bother doing anything here. + */ +static int +archive_read_format_zip_read_data_skip_seekable(struct archive_read *a) +{ + struct zip *zip; + zip = (struct zip *)(a->format->data); + + zip->unconsumed = 0; + return (ARCHIVE_OK); +} + +int +archive_read_support_format_zip_seekable(struct archive *_a) +{ + struct archive_read *a = (struct archive_read *)_a; + struct zip *zip; + int r; + + archive_check_magic(_a, ARCHIVE_READ_MAGIC, + ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable"); + + zip = (struct zip *)calloc(1, sizeof(*zip)); + if (zip == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate zip data"); + return (ARCHIVE_FATAL); + } + +#ifdef HAVE_COPYFILE_H + /* Set this by default on Mac OS. */ + zip->process_mac_extensions = 1; +#endif + + /* + * Until enough data has been read, we cannot tell about + * any encrypted entries yet. + */ + zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; + zip->crc32func = real_crc32; + + r = __archive_read_register_format(a, + zip, + "zip", + archive_read_format_zip_seekable_bid, + archive_read_format_zip_options, + archive_read_format_zip_seekable_read_header, + archive_read_format_zip_read_data, + archive_read_format_zip_read_data_skip_seekable, + NULL, + archive_read_format_zip_cleanup, + archive_read_support_format_zip_capabilities_seekable, + archive_read_format_zip_has_encrypted_entries); + + if (r != ARCHIVE_OK) + free(zip); + return (ARCHIVE_OK); +} + +/*# vim:set noet:*/ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_string.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_string.c new file mode 100644 index 0000000000..c77dcf52c2 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_string.c @@ -0,0 +1,4224 @@ +/*- + * Copyright (c) 2003-2011 Tim Kientzle + * Copyright (c) 2011-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_string.c 201095 2009-12-28 02:33:22Z kientzle $"); + +/* + * Basic resizable string support, to simplify manipulating arbitrary-sized + * strings while minimizing heap activity. + * + * In particular, the buffer used by a string object is only grown, it + * never shrinks, so you can clear and reuse the same string object + * without incurring additional memory allocations. + */ + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_ICONV_H +#include <iconv.h> +#endif +#ifdef HAVE_LANGINFO_H +#include <langinfo.h> +#endif +#ifdef HAVE_LOCALCHARSET_H +#include <localcharset.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_WCHAR_H +#include <wchar.h> +#endif +#if defined(_WIN32) && !defined(__CYGWIN__) +#include <windows.h> +#include <locale.h> +#endif + +#include "archive_endian.h" +#include "archive_private.h" +#include "archive_string.h" +#include "archive_string_composition.h" + +#if !defined(HAVE_WMEMCPY) && !defined(wmemcpy) +#define wmemcpy(a,b,i) (wchar_t *)memcpy((a), (b), (i) * sizeof(wchar_t)) +#endif + +#if !defined(HAVE_WMEMMOVE) && !defined(wmemmove) +#define wmemmove(a,b,i) (wchar_t *)memmove((a), (b), (i) * sizeof(wchar_t)) +#endif + +#undef max +#define max(a, b) ((a)>(b)?(a):(b)) + +struct archive_string_conv { + struct archive_string_conv *next; + char *from_charset; + char *to_charset; + unsigned from_cp; + unsigned to_cp; + /* Set 1 if from_charset and to_charset are the same. */ + int same; + int flag; +#define SCONV_TO_CHARSET 1 /* MBS is being converted to specified + * charset. */ +#define SCONV_FROM_CHARSET (1<<1) /* MBS is being converted from + * specified charset. */ +#define SCONV_BEST_EFFORT (1<<2) /* Copy at least ASCII code. */ +#define SCONV_WIN_CP (1<<3) /* Use Windows API for converting + * MBS. */ +#define SCONV_UTF8_LIBARCHIVE_2 (1<<4) /* Incorrect UTF-8 made by libarchive + * 2.x in the wrong assumption. */ +#define SCONV_NORMALIZATION_C (1<<6) /* Need normalization to be Form C. + * Before UTF-8 characters are actually + * processed. */ +#define SCONV_NORMALIZATION_D (1<<7) /* Need normalization to be Form D. + * Before UTF-8 characters are actually + * processed. + * Currently this only for MAC OS X. */ +#define SCONV_TO_UTF8 (1<<8) /* "to charset" side is UTF-8. */ +#define SCONV_FROM_UTF8 (1<<9) /* "from charset" side is UTF-8. */ +#define SCONV_TO_UTF16BE (1<<10) /* "to charset" side is UTF-16BE. */ +#define SCONV_FROM_UTF16BE (1<<11) /* "from charset" side is UTF-16BE. */ +#define SCONV_TO_UTF16LE (1<<12) /* "to charset" side is UTF-16LE. */ +#define SCONV_FROM_UTF16LE (1<<13) /* "from charset" side is UTF-16LE. */ +#define SCONV_TO_UTF16 (SCONV_TO_UTF16BE | SCONV_TO_UTF16LE) +#define SCONV_FROM_UTF16 (SCONV_FROM_UTF16BE | SCONV_FROM_UTF16LE) + +#if HAVE_ICONV + iconv_t cd; + iconv_t cd_w;/* Use at archive_mstring on + * Windows. */ +#endif + /* A temporary buffer for normalization. */ + struct archive_string utftmp; + int (*converter[2])(struct archive_string *, const void *, size_t, + struct archive_string_conv *); + int nconverter; +}; + +#define CP_C_LOCALE 0 /* "C" locale only for this file. */ +#define CP_UTF16LE 1200 +#define CP_UTF16BE 1201 + +#define IS_HIGH_SURROGATE_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDBFF) +#define IS_LOW_SURROGATE_LA(uc) ((uc) >= 0xDC00 && (uc) <= 0xDFFF) +#define IS_SURROGATE_PAIR_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDFFF) +#define UNICODE_MAX 0x10FFFF +#define UNICODE_R_CHAR 0xFFFD /* Replacement character. */ +/* Set U+FFFD(Replacement character) in UTF-8. */ +static const char utf8_replacement_char[] = {0xef, 0xbf, 0xbd}; + +static struct archive_string_conv *find_sconv_object(struct archive *, + const char *, const char *); +static void add_sconv_object(struct archive *, struct archive_string_conv *); +static struct archive_string_conv *create_sconv_object(const char *, + const char *, unsigned, int); +static void free_sconv_object(struct archive_string_conv *); +static struct archive_string_conv *get_sconv_object(struct archive *, + const char *, const char *, int); +static unsigned make_codepage_from_charset(const char *); +static unsigned get_current_codepage(void); +static unsigned get_current_oemcp(void); +static size_t mbsnbytes(const void *, size_t); +static size_t utf16nbytes(const void *, size_t); +#if defined(_WIN32) && !defined(__CYGWIN__) +static int archive_wstring_append_from_mbs_in_codepage( + struct archive_wstring *, const char *, size_t, + struct archive_string_conv *); +static int archive_string_append_from_wcs_in_codepage(struct archive_string *, + const wchar_t *, size_t, struct archive_string_conv *); +static int is_big_endian(void); +static int strncat_in_codepage(struct archive_string *, const void *, + size_t, struct archive_string_conv *); +static int win_strncat_from_utf16be(struct archive_string *, const void *, + size_t, struct archive_string_conv *); +static int win_strncat_from_utf16le(struct archive_string *, const void *, + size_t, struct archive_string_conv *); +static int win_strncat_to_utf16be(struct archive_string *, const void *, + size_t, struct archive_string_conv *); +static int win_strncat_to_utf16le(struct archive_string *, const void *, + size_t, struct archive_string_conv *); +#endif +static int best_effort_strncat_from_utf16be(struct archive_string *, + const void *, size_t, struct archive_string_conv *); +static int best_effort_strncat_from_utf16le(struct archive_string *, + const void *, size_t, struct archive_string_conv *); +static int best_effort_strncat_to_utf16be(struct archive_string *, + const void *, size_t, struct archive_string_conv *); +static int best_effort_strncat_to_utf16le(struct archive_string *, + const void *, size_t, struct archive_string_conv *); +#if defined(HAVE_ICONV) +static int iconv_strncat_in_locale(struct archive_string *, const void *, + size_t, struct archive_string_conv *); +#endif +static int best_effort_strncat_in_locale(struct archive_string *, + const void *, size_t, struct archive_string_conv *); +static int _utf8_to_unicode(uint32_t *, const char *, size_t); +static int utf8_to_unicode(uint32_t *, const char *, size_t); +static inline uint32_t combine_surrogate_pair(uint32_t, uint32_t); +static int cesu8_to_unicode(uint32_t *, const char *, size_t); +static size_t unicode_to_utf8(char *, size_t, uint32_t); +static int utf16_to_unicode(uint32_t *, const char *, size_t, int); +static size_t unicode_to_utf16be(char *, size_t, uint32_t); +static size_t unicode_to_utf16le(char *, size_t, uint32_t); +static int strncat_from_utf8_libarchive2(struct archive_string *, + const void *, size_t, struct archive_string_conv *); +static int strncat_from_utf8_to_utf8(struct archive_string *, const void *, + size_t, struct archive_string_conv *); +static int archive_string_normalize_C(struct archive_string *, const void *, + size_t, struct archive_string_conv *); +static int archive_string_normalize_D(struct archive_string *, const void *, + size_t, struct archive_string_conv *); +static int archive_string_append_unicode(struct archive_string *, + const void *, size_t, struct archive_string_conv *); + +static struct archive_string * +archive_string_append(struct archive_string *as, const char *p, size_t s) +{ + if (archive_string_ensure(as, as->length + s + 1) == NULL) + return (NULL); + if (s) + memmove(as->s + as->length, p, s); + as->length += s; + as->s[as->length] = 0; + return (as); +} + +static struct archive_wstring * +archive_wstring_append(struct archive_wstring *as, const wchar_t *p, size_t s) +{ + if (archive_wstring_ensure(as, as->length + s + 1) == NULL) + return (NULL); + if (s) + wmemmove(as->s + as->length, p, s); + as->length += s; + as->s[as->length] = 0; + return (as); +} + +struct archive_string * +archive_array_append(struct archive_string *as, const char *p, size_t s) +{ + return archive_string_append(as, p, s); +} + +void +archive_string_concat(struct archive_string *dest, struct archive_string *src) +{ + if (archive_string_append(dest, src->s, src->length) == NULL) + __archive_errx(1, "Out of memory"); +} + +void +archive_wstring_concat(struct archive_wstring *dest, + struct archive_wstring *src) +{ + if (archive_wstring_append(dest, src->s, src->length) == NULL) + __archive_errx(1, "Out of memory"); +} + +void +archive_string_free(struct archive_string *as) +{ + as->length = 0; + as->buffer_length = 0; + free(as->s); + as->s = NULL; +} + +void +archive_wstring_free(struct archive_wstring *as) +{ + as->length = 0; + as->buffer_length = 0; + free(as->s); + as->s = NULL; +} + +struct archive_wstring * +archive_wstring_ensure(struct archive_wstring *as, size_t s) +{ + return (struct archive_wstring *) + archive_string_ensure((struct archive_string *)as, + s * sizeof(wchar_t)); +} + +/* Returns NULL on any allocation failure. */ +struct archive_string * +archive_string_ensure(struct archive_string *as, size_t s) +{ + char *p; + size_t new_length; + + /* If buffer is already big enough, don't reallocate. */ + if (as->s && (s <= as->buffer_length)) + return (as); + + /* + * Growing the buffer at least exponentially ensures that + * append operations are always linear in the number of + * characters appended. Using a smaller growth rate for + * larger buffers reduces memory waste somewhat at the cost of + * a larger constant factor. + */ + if (as->buffer_length < 32) + /* Start with a minimum 32-character buffer. */ + new_length = 32; + else if (as->buffer_length < 8192) + /* Buffers under 8k are doubled for speed. */ + new_length = as->buffer_length + as->buffer_length; + else { + /* Buffers 8k and over grow by at least 25% each time. */ + new_length = as->buffer_length + as->buffer_length / 4; + /* Be safe: If size wraps, fail. */ + if (new_length < as->buffer_length) { + /* On failure, wipe the string and return NULL. */ + archive_string_free(as); + errno = ENOMEM;/* Make sure errno has ENOMEM. */ + return (NULL); + } + } + /* + * The computation above is a lower limit to how much we'll + * grow the buffer. In any case, we have to grow it enough to + * hold the request. + */ + if (new_length < s) + new_length = s; + /* Now we can reallocate the buffer. */ + p = (char *)realloc(as->s, new_length); + if (p == NULL) { + /* On failure, wipe the string and return NULL. */ + archive_string_free(as); + errno = ENOMEM;/* Make sure errno has ENOMEM. */ + return (NULL); + } + + as->s = p; + as->buffer_length = new_length; + return (as); +} + +/* + * TODO: See if there's a way to avoid scanning + * the source string twice. Then test to see + * if it actually helps (remember that we're almost + * always called with pretty short arguments, so + * such an optimization might not help). + */ +struct archive_string * +archive_strncat(struct archive_string *as, const void *_p, size_t n) +{ + size_t s; + const char *p, *pp; + + p = (const char *)_p; + + /* Like strlen(p), except won't examine positions beyond p[n]. */ + s = 0; + pp = p; + while (s < n && *pp) { + pp++; + s++; + } + if ((as = archive_string_append(as, p, s)) == NULL) + __archive_errx(1, "Out of memory"); + return (as); +} + +struct archive_wstring * +archive_wstrncat(struct archive_wstring *as, const wchar_t *p, size_t n) +{ + size_t s; + const wchar_t *pp; + + /* Like strlen(p), except won't examine positions beyond p[n]. */ + s = 0; + pp = p; + while (s < n && *pp) { + pp++; + s++; + } + if ((as = archive_wstring_append(as, p, s)) == NULL) + __archive_errx(1, "Out of memory"); + return (as); +} + +struct archive_string * +archive_strcat(struct archive_string *as, const void *p) +{ + /* strcat is just strncat without an effective limit. + * Assert that we'll never get called with a source + * string over 16MB. + * TODO: Review all uses of strcat in the source + * and try to replace them with strncat(). + */ + return archive_strncat(as, p, 0x1000000); +} + +struct archive_wstring * +archive_wstrcat(struct archive_wstring *as, const wchar_t *p) +{ + /* Ditto. */ + return archive_wstrncat(as, p, 0x1000000); +} + +struct archive_string * +archive_strappend_char(struct archive_string *as, char c) +{ + if ((as = archive_string_append(as, &c, 1)) == NULL) + __archive_errx(1, "Out of memory"); + return (as); +} + +struct archive_wstring * +archive_wstrappend_wchar(struct archive_wstring *as, wchar_t c) +{ + if ((as = archive_wstring_append(as, &c, 1)) == NULL) + __archive_errx(1, "Out of memory"); + return (as); +} + +/* + * Get the "current character set" name to use with iconv. + * On FreeBSD, the empty character set name "" chooses + * the correct character encoding for the current locale, + * so this isn't necessary. + * But iconv on Mac OS 10.6 doesn't seem to handle this correctly; + * on that system, we have to explicitly call nl_langinfo() + * to get the right name. Not sure about other platforms. + * + * NOTE: GNU libiconv does not recognize the character-set name + * which some platform nl_langinfo(CODESET) returns, so we should + * use locale_charset() instead of nl_langinfo(CODESET) for GNU libiconv. + */ +static const char * +default_iconv_charset(const char *charset) { + if (charset != NULL && charset[0] != '\0') + return charset; +#if HAVE_LOCALE_CHARSET && !defined(__APPLE__) + /* locale_charset() is broken on Mac OS */ + return locale_charset(); +#elif HAVE_NL_LANGINFO + return nl_langinfo(CODESET); +#else + return ""; +#endif +} + +#if defined(_WIN32) && !defined(__CYGWIN__) + +/* + * Convert MBS to WCS. + * Note: returns -1 if conversion fails. + */ +int +archive_wstring_append_from_mbs(struct archive_wstring *dest, + const char *p, size_t len) +{ + return archive_wstring_append_from_mbs_in_codepage(dest, p, len, NULL); +} + +static int +archive_wstring_append_from_mbs_in_codepage(struct archive_wstring *dest, + const char *s, size_t length, struct archive_string_conv *sc) +{ + int count, ret = 0; + UINT from_cp; + + if (sc != NULL) + from_cp = sc->from_cp; + else + from_cp = get_current_codepage(); + + if (from_cp == CP_C_LOCALE) { + /* + * "C" locale special processing. + */ + wchar_t *ws; + const unsigned char *mp; + + if (NULL == archive_wstring_ensure(dest, + dest->length + length + 1)) + return (-1); + + ws = dest->s + dest->length; + mp = (const unsigned char *)s; + count = 0; + while (count < (int)length && *mp) { + *ws++ = (wchar_t)*mp++; + count++; + } + } else if (sc != NULL && + (sc->flag & (SCONV_NORMALIZATION_C | SCONV_NORMALIZATION_D))) { + /* + * Normalize UTF-8 and UTF-16BE and convert it directly + * to UTF-16 as wchar_t. + */ + struct archive_string u16; + int saved_flag = sc->flag;/* save current flag. */ + + if (is_big_endian()) + sc->flag |= SCONV_TO_UTF16BE; + else + sc->flag |= SCONV_TO_UTF16LE; + + if (sc->flag & SCONV_FROM_UTF16) { + /* + * UTF-16BE/LE NFD ===> UTF-16 NFC + * UTF-16BE/LE NFC ===> UTF-16 NFD + */ + count = (int)utf16nbytes(s, length); + } else { + /* + * UTF-8 NFD ===> UTF-16 NFC + * UTF-8 NFC ===> UTF-16 NFD + */ + count = (int)mbsnbytes(s, length); + } + u16.s = (char *)dest->s; + u16.length = dest->length << 1;; + u16.buffer_length = dest->buffer_length; + if (sc->flag & SCONV_NORMALIZATION_C) + ret = archive_string_normalize_C(&u16, s, count, sc); + else + ret = archive_string_normalize_D(&u16, s, count, sc); + dest->s = (wchar_t *)u16.s; + dest->length = u16.length >> 1; + dest->buffer_length = u16.buffer_length; + sc->flag = saved_flag;/* restore the saved flag. */ + return (ret); + } else if (sc != NULL && (sc->flag & SCONV_FROM_UTF16)) { + count = (int)utf16nbytes(s, length); + count >>= 1; /* to be WCS length */ + /* Allocate memory for WCS. */ + if (NULL == archive_wstring_ensure(dest, + dest->length + count + 1)) + return (-1); + wmemcpy(dest->s + dest->length, (const wchar_t *)s, count); + if ((sc->flag & SCONV_FROM_UTF16BE) && !is_big_endian()) { + uint16_t *u16 = (uint16_t *)(dest->s + dest->length); + int b; + for (b = 0; b < count; b++) { + uint16_t val = archive_le16dec(u16+b); + archive_be16enc(u16+b, val); + } + } else if ((sc->flag & SCONV_FROM_UTF16LE) && is_big_endian()) { + uint16_t *u16 = (uint16_t *)(dest->s + dest->length); + int b; + for (b = 0; b < count; b++) { + uint16_t val = archive_be16dec(u16+b); + archive_le16enc(u16+b, val); + } + } + } else { + DWORD mbflag; + size_t buffsize; + + if (sc == NULL) + mbflag = 0; + else if (sc->flag & SCONV_FROM_CHARSET) { + /* Do not trust the length which comes from + * an archive file. */ + length = mbsnbytes(s, length); + mbflag = 0; + } else + mbflag = MB_PRECOMPOSED; + + buffsize = dest->length + length + 1; + do { + /* Allocate memory for WCS. */ + if (NULL == archive_wstring_ensure(dest, buffsize)) + return (-1); + /* Convert MBS to WCS. */ + count = MultiByteToWideChar(from_cp, + mbflag, s, (int)length, dest->s + dest->length, + (int)(dest->buffer_length >> 1) -1); + if (count == 0 && + GetLastError() == ERROR_INSUFFICIENT_BUFFER) { + /* Expand the WCS buffer. */ + buffsize = dest->buffer_length << 1; + continue; + } + if (count == 0 && length != 0) + ret = -1; + break; + } while (1); + } + dest->length += count; + dest->s[dest->length] = L'\0'; + return (ret); +} + +#else + +/* + * Convert MBS to WCS. + * Note: returns -1 if conversion fails. + */ +int +archive_wstring_append_from_mbs(struct archive_wstring *dest, + const char *p, size_t len) +{ + size_t r; + int ret_val = 0; + /* + * No single byte will be more than one wide character, + * so this length estimate will always be big enough. + */ + // size_t wcs_length = len; + size_t mbs_length = len; + const char *mbs = p; + wchar_t *wcs; +#if HAVE_MBRTOWC + mbstate_t shift_state; + + memset(&shift_state, 0, sizeof(shift_state)); +#endif + /* + * As we decided to have wcs_length == mbs_length == len + * we can use len here instead of wcs_length + */ + if (NULL == archive_wstring_ensure(dest, dest->length + len + 1)) + return (-1); + wcs = dest->s + dest->length; + /* + * We cannot use mbsrtowcs/mbstowcs here because those may convert + * extra MBS when strlen(p) > len and one wide character consists of + * multi bytes. + */ + while (*mbs && mbs_length > 0) { + /* + * The buffer we allocated is always big enough. + * Keep this code path in a comment if we decide to choose + * smaller wcs_length in the future + */ +/* + if (wcs_length == 0) { + dest->length = wcs - dest->s; + dest->s[dest->length] = L'\0'; + wcs_length = mbs_length; + if (NULL == archive_wstring_ensure(dest, + dest->length + wcs_length + 1)) + return (-1); + wcs = dest->s + dest->length; + } +*/ +#if HAVE_MBRTOWC + r = mbrtowc(wcs, mbs, mbs_length, &shift_state); +#else + r = mbtowc(wcs, mbs, mbs_length); +#endif + if (r == (size_t)-1 || r == (size_t)-2) { + ret_val = -1; + break; + } + if (r == 0 || r > mbs_length) + break; + wcs++; + // wcs_length--; + mbs += r; + mbs_length -= r; + } + dest->length = wcs - dest->s; + dest->s[dest->length] = L'\0'; + return (ret_val); +} + +#endif + +#if defined(_WIN32) && !defined(__CYGWIN__) + +/* + * WCS ==> MBS. + * Note: returns -1 if conversion fails. + * + * Win32 builds use WideCharToMultiByte from the Windows API. + * (Maybe Cygwin should too? WideCharToMultiByte will know a + * lot more about local character encodings than the wcrtomb() + * wrapper is going to know.) + */ +int +archive_string_append_from_wcs(struct archive_string *as, + const wchar_t *w, size_t len) +{ + return archive_string_append_from_wcs_in_codepage(as, w, len, NULL); +} + +static int +archive_string_append_from_wcs_in_codepage(struct archive_string *as, + const wchar_t *ws, size_t len, struct archive_string_conv *sc) +{ + BOOL defchar_used, *dp; + int count, ret = 0; + UINT to_cp; + int wslen = (int)len; + + if (sc != NULL) + to_cp = sc->to_cp; + else + to_cp = get_current_codepage(); + + if (to_cp == CP_C_LOCALE) { + /* + * "C" locale special processing. + */ + const wchar_t *wp = ws; + char *p; + + if (NULL == archive_string_ensure(as, + as->length + wslen +1)) + return (-1); + p = as->s + as->length; + count = 0; + defchar_used = 0; + while (count < wslen && *wp) { + if (*wp > 255) { + *p++ = '?'; + wp++; + defchar_used = 1; + } else + *p++ = (char)*wp++; + count++; + } + } else if (sc != NULL && (sc->flag & SCONV_TO_UTF16)) { + uint16_t *u16; + + if (NULL == + archive_string_ensure(as, as->length + len * 2 + 2)) + return (-1); + u16 = (uint16_t *)(as->s + as->length); + count = 0; + defchar_used = 0; + if (sc->flag & SCONV_TO_UTF16BE) { + while (count < (int)len && *ws) { + archive_be16enc(u16+count, *ws); + ws++; + count++; + } + } else { + while (count < (int)len && *ws) { + archive_le16enc(u16+count, *ws); + ws++; + count++; + } + } + count <<= 1; /* to be byte size */ + } else { + /* Make sure the MBS buffer has plenty to set. */ + if (NULL == + archive_string_ensure(as, as->length + len * 2 + 1)) + return (-1); + do { + defchar_used = 0; + if (to_cp == CP_UTF8 || sc == NULL) + dp = NULL; + else + dp = &defchar_used; + count = WideCharToMultiByte(to_cp, 0, ws, wslen, + as->s + as->length, + (int)as->buffer_length - as->length - 1, NULL, dp); + if (count == 0 && + GetLastError() == ERROR_INSUFFICIENT_BUFFER) { + /* Expand the MBS buffer and retry. */ + if (NULL == archive_string_ensure(as, + as->buffer_length + len)) + return (-1); + continue; + } + if (count == 0) + ret = -1; + break; + } while (1); + } + as->length += count; + as->s[as->length] = '\0'; + return (defchar_used?-1:ret); +} + +#elif defined(HAVE_WCTOMB) || defined(HAVE_WCRTOMB) + +/* + * Translates a wide character string into current locale character set + * and appends to the archive_string. Note: returns -1 if conversion + * fails. + */ +int +archive_string_append_from_wcs(struct archive_string *as, + const wchar_t *w, size_t len) +{ + /* We cannot use the standard wcstombs() here because it + * cannot tell us how big the output buffer should be. So + * I've built a loop around wcrtomb() or wctomb() that + * converts a character at a time and resizes the string as + * needed. We prefer wcrtomb() when it's available because + * it's thread-safe. */ + int n, ret_val = 0; + char *p; + char *end; +#if HAVE_WCRTOMB + mbstate_t shift_state; + + memset(&shift_state, 0, sizeof(shift_state)); +#else + /* Clear the shift state before starting. */ + wctomb(NULL, L'\0'); +#endif + /* + * Allocate buffer for MBS. + * We need this allocation here since it is possible that + * as->s is still NULL. + */ + if (archive_string_ensure(as, as->length + len + 1) == NULL) + return (-1); + + p = as->s + as->length; + end = as->s + as->buffer_length - MB_CUR_MAX -1; + while (*w != L'\0' && len > 0) { + if (p >= end) { + as->length = p - as->s; + as->s[as->length] = '\0'; + /* Re-allocate buffer for MBS. */ + if (archive_string_ensure(as, + as->length + max(len * 2, + (size_t)MB_CUR_MAX) + 1) == NULL) + return (-1); + p = as->s + as->length; + end = as->s + as->buffer_length - MB_CUR_MAX -1; + } +#if HAVE_WCRTOMB + n = wcrtomb(p, *w++, &shift_state); +#else + n = wctomb(p, *w++); +#endif + if (n == -1) { + if (errno == EILSEQ) { + /* Skip an illegal wide char. */ + *p++ = '?'; + ret_val = -1; + } else { + ret_val = -1; + break; + } + } else + p += n; + len--; + } + as->length = p - as->s; + as->s[as->length] = '\0'; + return (ret_val); +} + +#else /* HAVE_WCTOMB || HAVE_WCRTOMB */ + +/* + * TODO: Test if __STDC_ISO_10646__ is defined. + * Non-Windows uses ISO C wcrtomb() or wctomb() to perform the conversion + * one character at a time. If a non-Windows platform doesn't have + * either of these, fall back to the built-in UTF8 conversion. + */ +int +archive_string_append_from_wcs(struct archive_string *as, + const wchar_t *w, size_t len) +{ + (void)as;/* UNUSED */ + (void)w;/* UNUSED */ + (void)len;/* UNUSED */ + errno = ENOSYS; + return (-1); +} + +#endif /* HAVE_WCTOMB || HAVE_WCRTOMB */ + +/* + * Find a string conversion object by a pair of 'from' charset name + * and 'to' charset name from an archive object. + * Return NULL if not found. + */ +static struct archive_string_conv * +find_sconv_object(struct archive *a, const char *fc, const char *tc) +{ + struct archive_string_conv *sc; + + if (a == NULL) + return (NULL); + + for (sc = a->sconv; sc != NULL; sc = sc->next) { + if (strcmp(sc->from_charset, fc) == 0 && + strcmp(sc->to_charset, tc) == 0) + break; + } + return (sc); +} + +/* + * Register a string object to an archive object. + */ +static void +add_sconv_object(struct archive *a, struct archive_string_conv *sc) +{ + struct archive_string_conv **psc; + + /* Add a new sconv to sconv list. */ + psc = &(a->sconv); + while (*psc != NULL) + psc = &((*psc)->next); + *psc = sc; +} + +static void +add_converter(struct archive_string_conv *sc, int (*converter) + (struct archive_string *, const void *, size_t, + struct archive_string_conv *)) +{ + if (sc == NULL || sc->nconverter >= 2) + __archive_errx(1, "Programming error"); + sc->converter[sc->nconverter++] = converter; +} + +static void +setup_converter(struct archive_string_conv *sc) +{ + + /* Reset. */ + sc->nconverter = 0; + + /* + * Perform special sequence for the incorrect UTF-8 filenames + * made by libarchive2.x. + */ + if (sc->flag & SCONV_UTF8_LIBARCHIVE_2) { + add_converter(sc, strncat_from_utf8_libarchive2); + return; + } + + /* + * Convert a string to UTF-16BE/LE. + */ + if (sc->flag & SCONV_TO_UTF16) { + /* + * If the current locale is UTF-8, we can translate + * a UTF-8 string into a UTF-16BE string. + */ + if (sc->flag & SCONV_FROM_UTF8) { + add_converter(sc, archive_string_append_unicode); + return; + } + +#if defined(_WIN32) && !defined(__CYGWIN__) + if (sc->flag & SCONV_WIN_CP) { + if (sc->flag & SCONV_TO_UTF16BE) + add_converter(sc, win_strncat_to_utf16be); + else + add_converter(sc, win_strncat_to_utf16le); + return; + } +#endif + +#if defined(HAVE_ICONV) + if (sc->cd != (iconv_t)-1) { + add_converter(sc, iconv_strncat_in_locale); + return; + } +#endif + + if (sc->flag & SCONV_BEST_EFFORT) { + if (sc->flag & SCONV_TO_UTF16BE) + add_converter(sc, + best_effort_strncat_to_utf16be); + else + add_converter(sc, + best_effort_strncat_to_utf16le); + } else + /* Make sure we have no converter. */ + sc->nconverter = 0; + return; + } + + /* + * Convert a string from UTF-16BE/LE. + */ + if (sc->flag & SCONV_FROM_UTF16) { + /* + * At least we should normalize a UTF-16BE string. + */ + if (sc->flag & SCONV_NORMALIZATION_D) + add_converter(sc,archive_string_normalize_D); + else if (sc->flag & SCONV_NORMALIZATION_C) + add_converter(sc, archive_string_normalize_C); + + if (sc->flag & SCONV_TO_UTF8) { + /* + * If the current locale is UTF-8, we can translate + * a UTF-16BE/LE string into a UTF-8 string directly. + */ + if (!(sc->flag & + (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C))) + add_converter(sc, + archive_string_append_unicode); + return; + } + +#if defined(_WIN32) && !defined(__CYGWIN__) + if (sc->flag & SCONV_WIN_CP) { + if (sc->flag & SCONV_FROM_UTF16BE) + add_converter(sc, win_strncat_from_utf16be); + else + add_converter(sc, win_strncat_from_utf16le); + return; + } +#endif + +#if defined(HAVE_ICONV) + if (sc->cd != (iconv_t)-1) { + add_converter(sc, iconv_strncat_in_locale); + return; + } +#endif + + if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE)) + == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE)) + add_converter(sc, best_effort_strncat_from_utf16be); + else if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE)) + == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE)) + add_converter(sc, best_effort_strncat_from_utf16le); + else + /* Make sure we have no converter. */ + sc->nconverter = 0; + return; + } + + if (sc->flag & SCONV_FROM_UTF8) { + /* + * At least we should normalize a UTF-8 string. + */ + if (sc->flag & SCONV_NORMALIZATION_D) + add_converter(sc,archive_string_normalize_D); + else if (sc->flag & SCONV_NORMALIZATION_C) + add_converter(sc, archive_string_normalize_C); + + /* + * Copy UTF-8 string with a check of CESU-8. + * Apparently, iconv does not check surrogate pairs in UTF-8 + * when both from-charset and to-charset are UTF-8, and then + * we use our UTF-8 copy code. + */ + if (sc->flag & SCONV_TO_UTF8) { + /* + * If the current locale is UTF-8, we can translate + * a UTF-16BE string into a UTF-8 string directly. + */ + if (!(sc->flag & + (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C))) + add_converter(sc, strncat_from_utf8_to_utf8); + return; + } + } + +#if defined(_WIN32) && !defined(__CYGWIN__) + /* + * On Windows we can use Windows API for a string conversion. + */ + if (sc->flag & SCONV_WIN_CP) { + add_converter(sc, strncat_in_codepage); + return; + } +#endif + +#if HAVE_ICONV + if (sc->cd != (iconv_t)-1) { + add_converter(sc, iconv_strncat_in_locale); + /* + * iconv generally does not support UTF-8-MAC and so + * we have to the output of iconv from NFC to NFD if + * need. + */ + if ((sc->flag & SCONV_FROM_CHARSET) && + (sc->flag & SCONV_TO_UTF8)) { + if (sc->flag & SCONV_NORMALIZATION_D) + add_converter(sc, archive_string_normalize_D); + } + return; + } +#endif + + /* + * Try conversion in the best effort or no conversion. + */ + if ((sc->flag & SCONV_BEST_EFFORT) || sc->same) + add_converter(sc, best_effort_strncat_in_locale); + else + /* Make sure we have no converter. */ + sc->nconverter = 0; +} + +/* + * Return canonicalized charset-name but this supports just UTF-8, UTF-16BE + * and CP932 which are referenced in create_sconv_object(). + */ +static const char * +canonical_charset_name(const char *charset) +{ + char cs[16]; + char *p; + const char *s; + + if (charset == NULL || charset[0] == '\0' + || strlen(charset) > 15) + return (charset); + + /* Copy name to uppercase. */ + p = cs; + s = charset; + while (*s) { + char c = *s++; + if (c >= 'a' && c <= 'z') + c -= 'a' - 'A'; + *p++ = c; + } + *p++ = '\0'; + + if (strcmp(cs, "UTF-8") == 0 || + strcmp(cs, "UTF8") == 0) + return ("UTF-8"); + if (strcmp(cs, "UTF-16BE") == 0 || + strcmp(cs, "UTF16BE") == 0) + return ("UTF-16BE"); + if (strcmp(cs, "UTF-16LE") == 0 || + strcmp(cs, "UTF16LE") == 0) + return ("UTF-16LE"); + if (strcmp(cs, "CP932") == 0) + return ("CP932"); + return (charset); +} + +/* + * Create a string conversion object. + */ +static struct archive_string_conv * +create_sconv_object(const char *fc, const char *tc, + unsigned current_codepage, int flag) +{ + struct archive_string_conv *sc; + + sc = calloc(1, sizeof(*sc)); + if (sc == NULL) + return (NULL); + sc->next = NULL; + sc->from_charset = strdup(fc); + if (sc->from_charset == NULL) { + free(sc); + return (NULL); + } + sc->to_charset = strdup(tc); + if (sc->to_charset == NULL) { + free(sc->from_charset); + free(sc); + return (NULL); + } + archive_string_init(&sc->utftmp); + + if (flag & SCONV_TO_CHARSET) { + /* + * Convert characters from the current locale charset to + * a specified charset. + */ + sc->from_cp = current_codepage; + sc->to_cp = make_codepage_from_charset(tc); +#if defined(_WIN32) && !defined(__CYGWIN__) + if (IsValidCodePage(sc->to_cp)) + flag |= SCONV_WIN_CP; +#endif + } else if (flag & SCONV_FROM_CHARSET) { + /* + * Convert characters from a specified charset to + * the current locale charset. + */ + sc->to_cp = current_codepage; + sc->from_cp = make_codepage_from_charset(fc); +#if defined(_WIN32) && !defined(__CYGWIN__) + if (IsValidCodePage(sc->from_cp)) + flag |= SCONV_WIN_CP; +#endif + } + + /* + * Check if "from charset" and "to charset" are the same. + */ + if (strcmp(fc, tc) == 0 || + (sc->from_cp != (unsigned)-1 && sc->from_cp == sc->to_cp)) + sc->same = 1; + else + sc->same = 0; + + /* + * Mark if "from charset" or "to charset" are UTF-8 or UTF-16BE/LE. + */ + if (strcmp(tc, "UTF-8") == 0) + flag |= SCONV_TO_UTF8; + else if (strcmp(tc, "UTF-16BE") == 0) + flag |= SCONV_TO_UTF16BE; + else if (strcmp(tc, "UTF-16LE") == 0) + flag |= SCONV_TO_UTF16LE; + if (strcmp(fc, "UTF-8") == 0) + flag |= SCONV_FROM_UTF8; + else if (strcmp(fc, "UTF-16BE") == 0) + flag |= SCONV_FROM_UTF16BE; + else if (strcmp(fc, "UTF-16LE") == 0) + flag |= SCONV_FROM_UTF16LE; +#if defined(_WIN32) && !defined(__CYGWIN__) + if (sc->to_cp == CP_UTF8) + flag |= SCONV_TO_UTF8; + else if (sc->to_cp == CP_UTF16BE) + flag |= SCONV_TO_UTF16BE | SCONV_WIN_CP; + else if (sc->to_cp == CP_UTF16LE) + flag |= SCONV_TO_UTF16LE | SCONV_WIN_CP; + if (sc->from_cp == CP_UTF8) + flag |= SCONV_FROM_UTF8; + else if (sc->from_cp == CP_UTF16BE) + flag |= SCONV_FROM_UTF16BE | SCONV_WIN_CP; + else if (sc->from_cp == CP_UTF16LE) + flag |= SCONV_FROM_UTF16LE | SCONV_WIN_CP; +#endif + + /* + * Set a flag for Unicode NFD. Usually iconv cannot correctly + * handle it. So we have to translate NFD characters to NFC ones + * ourselves before iconv handles. Another reason is to prevent + * that the same sight of two filenames, one is NFC and other + * is NFD, would be in its directory. + * On Mac OS X, although its filesystem layer automatically + * convert filenames to NFD, it would be useful for filename + * comparing to find out the same filenames that we normalize + * that to be NFD ourselves. + */ + if ((flag & SCONV_FROM_CHARSET) && + (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8))) { +#if defined(__APPLE__) + if (flag & SCONV_TO_UTF8) + flag |= SCONV_NORMALIZATION_D; + else +#endif + flag |= SCONV_NORMALIZATION_C; + } +#if defined(__APPLE__) + /* + * In case writing an archive file, make sure that a filename + * going to be passed to iconv is a Unicode NFC string since + * a filename in HFS Plus filesystem is a Unicode NFD one and + * iconv cannot handle it with "UTF-8" charset. It is simpler + * than a use of "UTF-8-MAC" charset. + */ + if ((flag & SCONV_TO_CHARSET) && + (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) && + !(flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8))) + flag |= SCONV_NORMALIZATION_C; + /* + * In case reading an archive file. make sure that a filename + * will be passed to users is a Unicode NFD string in order to + * correctly compare the filename with other one which comes + * from HFS Plus filesystem. + */ + if ((flag & SCONV_FROM_CHARSET) && + !(flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) && + (flag & SCONV_TO_UTF8)) + flag |= SCONV_NORMALIZATION_D; +#endif + +#if defined(HAVE_ICONV) + sc->cd_w = (iconv_t)-1; + /* + * Create an iconv object. + */ + if (((flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) && + (flag & (SCONV_FROM_UTF8 | SCONV_FROM_UTF16))) || + (flag & SCONV_WIN_CP)) { + /* This case we won't use iconv. */ + sc->cd = (iconv_t)-1; + } else { + sc->cd = iconv_open(tc, fc); + if (sc->cd == (iconv_t)-1 && (sc->flag & SCONV_BEST_EFFORT)) { + /* + * Unfortunately, all of iconv implements do support + * "CP932" character-set, so we should use "SJIS" + * instead if iconv_open failed. + */ + if (strcmp(tc, "CP932") == 0) + sc->cd = iconv_open("SJIS", fc); + else if (strcmp(fc, "CP932") == 0) + sc->cd = iconv_open(tc, "SJIS"); + } +#if defined(_WIN32) && !defined(__CYGWIN__) + /* + * archive_mstring on Windows directly convert multi-bytes + * into archive_wstring in order not to depend on locale + * so that you can do a I18N programming. This will be + * used only in archive_mstring_copy_mbs_len_l so far. + */ + if (flag & SCONV_FROM_CHARSET) { + sc->cd_w = iconv_open("UTF-8", fc); + if (sc->cd_w == (iconv_t)-1 && + (sc->flag & SCONV_BEST_EFFORT)) { + if (strcmp(fc, "CP932") == 0) + sc->cd_w = iconv_open("UTF-8", "SJIS"); + } + } +#endif /* _WIN32 && !__CYGWIN__ */ + } +#endif /* HAVE_ICONV */ + + sc->flag = flag; + + /* + * Set up converters. + */ + setup_converter(sc); + + return (sc); +} + +/* + * Free a string conversion object. + */ +static void +free_sconv_object(struct archive_string_conv *sc) +{ + free(sc->from_charset); + free(sc->to_charset); + archive_string_free(&sc->utftmp); +#if HAVE_ICONV + if (sc->cd != (iconv_t)-1) + iconv_close(sc->cd); + if (sc->cd_w != (iconv_t)-1) + iconv_close(sc->cd_w); +#endif + free(sc); +} + +#if defined(_WIN32) && !defined(__CYGWIN__) +static unsigned +my_atoi(const char *p) +{ + unsigned cp; + + cp = 0; + while (*p) { + if (*p >= '0' && *p <= '9') + cp = cp * 10 + (*p - '0'); + else + return (-1); + p++; + } + return (cp); +} + +/* + * Translate Charset name (as used by iconv) into CodePage (as used by Windows) + * Return -1 if failed. + * + * Note: This translation code may be insufficient. + */ +static struct charset { + const char *name; + unsigned cp; +} charsets[] = { + /* MUST BE SORTED! */ + {"ASCII", 1252}, + {"ASMO-708", 708}, + {"BIG5", 950}, + {"CHINESE", 936}, + {"CP367", 1252}, + {"CP819", 1252}, + {"CP1025", 21025}, + {"DOS-720", 720}, + {"DOS-862", 862}, + {"EUC-CN", 51936}, + {"EUC-JP", 51932}, + {"EUC-KR", 949}, + {"EUCCN", 51936}, + {"EUCJP", 51932}, + {"EUCKR", 949}, + {"GB18030", 54936}, + {"GB2312", 936}, + {"HEBREW", 1255}, + {"HZ-GB-2312", 52936}, + {"IBM273", 20273}, + {"IBM277", 20277}, + {"IBM278", 20278}, + {"IBM280", 20280}, + {"IBM284", 20284}, + {"IBM285", 20285}, + {"IBM290", 20290}, + {"IBM297", 20297}, + {"IBM367", 1252}, + {"IBM420", 20420}, + {"IBM423", 20423}, + {"IBM424", 20424}, + {"IBM819", 1252}, + {"IBM871", 20871}, + {"IBM880", 20880}, + {"IBM905", 20905}, + {"IBM924", 20924}, + {"ISO-8859-1", 28591}, + {"ISO-8859-13", 28603}, + {"ISO-8859-15", 28605}, + {"ISO-8859-2", 28592}, + {"ISO-8859-3", 28593}, + {"ISO-8859-4", 28594}, + {"ISO-8859-5", 28595}, + {"ISO-8859-6", 28596}, + {"ISO-8859-7", 28597}, + {"ISO-8859-8", 28598}, + {"ISO-8859-9", 28599}, + {"ISO8859-1", 28591}, + {"ISO8859-13", 28603}, + {"ISO8859-15", 28605}, + {"ISO8859-2", 28592}, + {"ISO8859-3", 28593}, + {"ISO8859-4", 28594}, + {"ISO8859-5", 28595}, + {"ISO8859-6", 28596}, + {"ISO8859-7", 28597}, + {"ISO8859-8", 28598}, + {"ISO8859-9", 28599}, + {"JOHAB", 1361}, + {"KOI8-R", 20866}, + {"KOI8-U", 21866}, + {"KS_C_5601-1987", 949}, + {"LATIN1", 1252}, + {"LATIN2", 28592}, + {"MACINTOSH", 10000}, + {"SHIFT-JIS", 932}, + {"SHIFT_JIS", 932}, + {"SJIS", 932}, + {"US", 1252}, + {"US-ASCII", 1252}, + {"UTF-16", 1200}, + {"UTF-16BE", 1201}, + {"UTF-16LE", 1200}, + {"UTF-8", CP_UTF8}, + {"X-EUROPA", 29001}, + {"X-MAC-ARABIC", 10004}, + {"X-MAC-CE", 10029}, + {"X-MAC-CHINESEIMP", 10008}, + {"X-MAC-CHINESETRAD", 10002}, + {"X-MAC-CROATIAN", 10082}, + {"X-MAC-CYRILLIC", 10007}, + {"X-MAC-GREEK", 10006}, + {"X-MAC-HEBREW", 10005}, + {"X-MAC-ICELANDIC", 10079}, + {"X-MAC-JAPANESE", 10001}, + {"X-MAC-KOREAN", 10003}, + {"X-MAC-ROMANIAN", 10010}, + {"X-MAC-THAI", 10021}, + {"X-MAC-TURKISH", 10081}, + {"X-MAC-UKRAINIAN", 10017}, +}; +static unsigned +make_codepage_from_charset(const char *charset) +{ + char cs[16]; + char *p; + unsigned cp; + int a, b; + + if (charset == NULL || strlen(charset) > 15) + return -1; + + /* Copy name to uppercase. */ + p = cs; + while (*charset) { + char c = *charset++; + if (c >= 'a' && c <= 'z') + c -= 'a' - 'A'; + *p++ = c; + } + *p++ = '\0'; + cp = -1; + + /* Look it up in the table first, so that we can easily + * override CP367, which we map to 1252 instead of 367. */ + a = 0; + b = sizeof(charsets)/sizeof(charsets[0]); + while (b > a) { + int c = (b + a) / 2; + int r = strcmp(charsets[c].name, cs); + if (r < 0) + a = c + 1; + else if (r > 0) + b = c; + else + return charsets[c].cp; + } + + /* If it's not in the table, try to parse it. */ + switch (*cs) { + case 'C': + if (cs[1] == 'P' && cs[2] >= '0' && cs[2] <= '9') { + cp = my_atoi(cs + 2); + } else if (strcmp(cs, "CP_ACP") == 0) + cp = get_current_codepage(); + else if (strcmp(cs, "CP_OEMCP") == 0) + cp = get_current_oemcp(); + break; + case 'I': + if (cs[1] == 'B' && cs[2] == 'M' && + cs[3] >= '0' && cs[3] <= '9') { + cp = my_atoi(cs + 3); + } + break; + case 'W': + if (strncmp(cs, "WINDOWS-", 8) == 0) { + cp = my_atoi(cs + 8); + if (cp != 874 && (cp < 1250 || cp > 1258)) + cp = -1;/* This may invalid code. */ + } + break; + } + return (cp); +} + +/* + * Return ANSI Code Page of current locale set by setlocale(). + */ +static unsigned +get_current_codepage(void) +{ + char *locale, *p; + unsigned cp; + + locale = setlocale(LC_CTYPE, NULL); + if (locale == NULL) + return (GetACP()); + if (locale[0] == 'C' && locale[1] == '\0') + return (CP_C_LOCALE); + p = strrchr(locale, '.'); + if (p == NULL) + return (GetACP()); + if (strcmp(p+1, "utf8") == 0) + return CP_UTF8; + cp = my_atoi(p+1); + if ((int)cp <= 0) + return (GetACP()); + return (cp); +} + +/* + * Translation table between Locale Name and ACP/OEMCP. + */ +static struct { + unsigned acp; + unsigned ocp; + const char *locale; +} acp_ocp_map[] = { + { 950, 950, "Chinese_Taiwan" }, + { 936, 936, "Chinese_People's Republic of China" }, + { 950, 950, "Chinese_Taiwan" }, + { 1250, 852, "Czech_Czech Republic" }, + { 1252, 850, "Danish_Denmark" }, + { 1252, 850, "Dutch_Netherlands" }, + { 1252, 850, "Dutch_Belgium" }, + { 1252, 437, "English_United States" }, + { 1252, 850, "English_Australia" }, + { 1252, 850, "English_Canada" }, + { 1252, 850, "English_New Zealand" }, + { 1252, 850, "English_United Kingdom" }, + { 1252, 437, "English_United States" }, + { 1252, 850, "Finnish_Finland" }, + { 1252, 850, "French_France" }, + { 1252, 850, "French_Belgium" }, + { 1252, 850, "French_Canada" }, + { 1252, 850, "French_Switzerland" }, + { 1252, 850, "German_Germany" }, + { 1252, 850, "German_Austria" }, + { 1252, 850, "German_Switzerland" }, + { 1253, 737, "Greek_Greece" }, + { 1250, 852, "Hungarian_Hungary" }, + { 1252, 850, "Icelandic_Iceland" }, + { 1252, 850, "Italian_Italy" }, + { 1252, 850, "Italian_Switzerland" }, + { 932, 932, "Japanese_Japan" }, + { 949, 949, "Korean_Korea" }, + { 1252, 850, "Norwegian (BokmOl)_Norway" }, + { 1252, 850, "Norwegian (BokmOl)_Norway" }, + { 1252, 850, "Norwegian-Nynorsk_Norway" }, + { 1250, 852, "Polish_Poland" }, + { 1252, 850, "Portuguese_Portugal" }, + { 1252, 850, "Portuguese_Brazil" }, + { 1251, 866, "Russian_Russia" }, + { 1250, 852, "Slovak_Slovakia" }, + { 1252, 850, "Spanish_Spain" }, + { 1252, 850, "Spanish_Mexico" }, + { 1252, 850, "Spanish_Spain" }, + { 1252, 850, "Swedish_Sweden" }, + { 1254, 857, "Turkish_Turkey" }, + { 0, 0, NULL} +}; + +/* + * Return OEM Code Page of current locale set by setlocale(). + */ +static unsigned +get_current_oemcp(void) +{ + int i; + char *locale, *p; + size_t len; + + locale = setlocale(LC_CTYPE, NULL); + if (locale == NULL) + return (GetOEMCP()); + if (locale[0] == 'C' && locale[1] == '\0') + return (CP_C_LOCALE); + + p = strrchr(locale, '.'); + if (p == NULL) + return (GetOEMCP()); + len = p - locale; + for (i = 0; acp_ocp_map[i].acp; i++) { + if (strncmp(acp_ocp_map[i].locale, locale, len) == 0) + return (acp_ocp_map[i].ocp); + } + return (GetOEMCP()); +} +#else + +/* + * POSIX platform does not use CodePage. + */ + +static unsigned +get_current_codepage(void) +{ + return (-1);/* Unknown */ +} +static unsigned +make_codepage_from_charset(const char *charset) +{ + (void)charset; /* UNUSED */ + return (-1);/* Unknown */ +} +static unsigned +get_current_oemcp(void) +{ + return (-1);/* Unknown */ +} + +#endif /* defined(_WIN32) && !defined(__CYGWIN__) */ + +/* + * Return a string conversion object. + */ +static struct archive_string_conv * +get_sconv_object(struct archive *a, const char *fc, const char *tc, int flag) +{ + struct archive_string_conv *sc; + unsigned current_codepage; + + /* Check if we have made the sconv object. */ + sc = find_sconv_object(a, fc, tc); + if (sc != NULL) + return (sc); + + if (a == NULL) + current_codepage = get_current_codepage(); + else + current_codepage = a->current_codepage; + + sc = create_sconv_object(canonical_charset_name(fc), + canonical_charset_name(tc), current_codepage, flag); + if (sc == NULL) { + if (a != NULL) + archive_set_error(a, ENOMEM, + "Could not allocate memory for " + "a string conversion object"); + return (NULL); + } + + /* + * If there is no converter for current string conversion object, + * we cannot handle this conversion. + */ + if (sc->nconverter == 0) { + if (a != NULL) { +#if HAVE_ICONV + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "iconv_open failed : Cannot handle ``%s''", + (flag & SCONV_TO_CHARSET)?tc:fc); +#else + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "A character-set conversion not fully supported " + "on this platform"); +#endif + } + /* Failed; free a sconv object. */ + free_sconv_object(sc); + return (NULL); + } + + /* + * Success! + */ + if (a != NULL) + add_sconv_object(a, sc); + return (sc); +} + +static const char * +get_current_charset(struct archive *a) +{ + const char *cur_charset; + + if (a == NULL) + cur_charset = default_iconv_charset(""); + else { + cur_charset = default_iconv_charset(a->current_code); + if (a->current_code == NULL) { + a->current_code = strdup(cur_charset); + a->current_codepage = get_current_codepage(); + a->current_oemcp = get_current_oemcp(); + } + } + return (cur_charset); +} + +/* + * Make and Return a string conversion object. + * Return NULL if the platform does not support the specified conversion + * and best_effort is 0. + * If best_effort is set, A string conversion object must be returned + * unless memory allocation for the object fails, but the conversion + * might fail when non-ASCII code is found. + */ +struct archive_string_conv * +archive_string_conversion_to_charset(struct archive *a, const char *charset, + int best_effort) +{ + int flag = SCONV_TO_CHARSET; + + if (best_effort) + flag |= SCONV_BEST_EFFORT; + return (get_sconv_object(a, get_current_charset(a), charset, flag)); +} + +struct archive_string_conv * +archive_string_conversion_from_charset(struct archive *a, const char *charset, + int best_effort) +{ + int flag = SCONV_FROM_CHARSET; + + if (best_effort) + flag |= SCONV_BEST_EFFORT; + return (get_sconv_object(a, charset, get_current_charset(a), flag)); +} + +/* + * archive_string_default_conversion_*_archive() are provided for Windows + * platform because other archiver application use CP_OEMCP for + * MultiByteToWideChar() and WideCharToMultiByte() for the filenames + * in tar or zip files. But mbstowcs/wcstombs(CRT) usually use CP_ACP + * unless you use setlocale(LC_ALL, ".OCP")(specify CP_OEMCP). + * So we should make a string conversion between CP_ACP and CP_OEMCP + * for compatibility. + */ +#if defined(_WIN32) && !defined(__CYGWIN__) +struct archive_string_conv * +archive_string_default_conversion_for_read(struct archive *a) +{ + const char *cur_charset = get_current_charset(a); + char oemcp[16]; + + /* NOTE: a check of cur_charset is unneeded but we need + * that get_current_charset() has been surely called at + * this time whatever C compiler optimized. */ + if (cur_charset != NULL && + (a->current_codepage == CP_C_LOCALE || + a->current_codepage == a->current_oemcp)) + return (NULL);/* no conversion. */ + + _snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp); + /* Make sure a null termination must be set. */ + oemcp[sizeof(oemcp)-1] = '\0'; + return (get_sconv_object(a, oemcp, cur_charset, + SCONV_FROM_CHARSET)); +} + +struct archive_string_conv * +archive_string_default_conversion_for_write(struct archive *a) +{ + const char *cur_charset = get_current_charset(a); + char oemcp[16]; + + /* NOTE: a check of cur_charset is unneeded but we need + * that get_current_charset() has been surely called at + * this time whatever C compiler optimized. */ + if (cur_charset != NULL && + (a->current_codepage == CP_C_LOCALE || + a->current_codepage == a->current_oemcp)) + return (NULL);/* no conversion. */ + + _snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp); + /* Make sure a null termination must be set. */ + oemcp[sizeof(oemcp)-1] = '\0'; + return (get_sconv_object(a, cur_charset, oemcp, + SCONV_TO_CHARSET)); +} +#else +struct archive_string_conv * +archive_string_default_conversion_for_read(struct archive *a) +{ + (void)a; /* UNUSED */ + return (NULL); +} + +struct archive_string_conv * +archive_string_default_conversion_for_write(struct archive *a) +{ + (void)a; /* UNUSED */ + return (NULL); +} +#endif + +/* + * Dispose of all character conversion objects in the archive object. + */ +void +archive_string_conversion_free(struct archive *a) +{ + struct archive_string_conv *sc; + struct archive_string_conv *sc_next; + + for (sc = a->sconv; sc != NULL; sc = sc_next) { + sc_next = sc->next; + free_sconv_object(sc); + } + a->sconv = NULL; + free(a->current_code); + a->current_code = NULL; +} + +/* + * Return a conversion charset name. + */ +const char * +archive_string_conversion_charset_name(struct archive_string_conv *sc) +{ + if (sc->flag & SCONV_TO_CHARSET) + return (sc->to_charset); + else + return (sc->from_charset); +} + +/* + * Change the behavior of a string conversion. + */ +void +archive_string_conversion_set_opt(struct archive_string_conv *sc, int opt) +{ + switch (opt) { + /* + * A filename in UTF-8 was made with libarchive 2.x in a wrong + * assumption that wchar_t was Unicode. + * This option enables simulating the assumption in order to read + * that filename correctly. + */ + case SCONV_SET_OPT_UTF8_LIBARCHIVE2X: +#if (defined(_WIN32) && !defined(__CYGWIN__)) \ + || defined(__STDC_ISO_10646__) || defined(__APPLE__) + /* + * Nothing to do for it since wchar_t on these platforms + * is really Unicode. + */ + (void)sc; /* UNUSED */ +#else + if ((sc->flag & SCONV_UTF8_LIBARCHIVE_2) == 0) { + sc->flag |= SCONV_UTF8_LIBARCHIVE_2; + /* Set up string converters. */ + setup_converter(sc); + } +#endif + break; + case SCONV_SET_OPT_NORMALIZATION_C: + if ((sc->flag & SCONV_NORMALIZATION_C) == 0) { + sc->flag |= SCONV_NORMALIZATION_C; + sc->flag &= ~SCONV_NORMALIZATION_D; + /* Set up string converters. */ + setup_converter(sc); + } + break; + case SCONV_SET_OPT_NORMALIZATION_D: +#if defined(HAVE_ICONV) + /* + * If iconv will take the string, do not change the + * setting of the normalization. + */ + if (!(sc->flag & SCONV_WIN_CP) && + (sc->flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) && + !(sc->flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8))) + break; +#endif + if ((sc->flag & SCONV_NORMALIZATION_D) == 0) { + sc->flag |= SCONV_NORMALIZATION_D; + sc->flag &= ~SCONV_NORMALIZATION_C; + /* Set up string converters. */ + setup_converter(sc); + } + break; + default: + break; + } +} + +/* + * + * Copy one archive_string to another in locale conversion. + * + * archive_strncat_l(); + * archive_strncpy_l(); + * + */ + +static size_t +mbsnbytes(const void *_p, size_t n) +{ + size_t s; + const char *p, *pp; + + if (_p == NULL) + return (0); + p = (const char *)_p; + + /* Like strlen(p), except won't examine positions beyond p[n]. */ + s = 0; + pp = p; + while (s < n && *pp) { + pp++; + s++; + } + return (s); +} + +static size_t +utf16nbytes(const void *_p, size_t n) +{ + size_t s; + const char *p, *pp; + + if (_p == NULL) + return (0); + p = (const char *)_p; + + /* Like strlen(p), except won't examine positions beyond p[n]. */ + s = 0; + pp = p; + n >>= 1; + while (s < n && (pp[0] || pp[1])) { + pp += 2; + s++; + } + return (s<<1); +} + +int +archive_strncpy_l(struct archive_string *as, const void *_p, size_t n, + struct archive_string_conv *sc) +{ + as->length = 0; + return (archive_strncat_l(as, _p, n, sc)); +} + +int +archive_strncat_l(struct archive_string *as, const void *_p, size_t n, + struct archive_string_conv *sc) +{ + const void *s; + size_t length = 0; + int i, r = 0, r2; + + if (_p != NULL && n > 0) { + if (sc != NULL && (sc->flag & SCONV_FROM_UTF16)) + length = utf16nbytes(_p, n); + else + length = mbsnbytes(_p, n); + } + + /* We must allocate memory even if there is no data for conversion + * or copy. This simulates archive_string_append behavior. */ + if (length == 0) { + int tn = 1; + if (sc != NULL && (sc->flag & SCONV_TO_UTF16)) + tn = 2; + if (archive_string_ensure(as, as->length + tn) == NULL) + return (-1); + as->s[as->length] = 0; + if (tn == 2) + as->s[as->length+1] = 0; + return (0); + } + + /* + * If sc is NULL, we just make a copy. + */ + if (sc == NULL) { + if (archive_string_append(as, _p, length) == NULL) + return (-1);/* No memory */ + return (0); + } + + s = _p; + i = 0; + if (sc->nconverter > 1) { + sc->utftmp.length = 0; + r2 = sc->converter[0](&(sc->utftmp), s, length, sc); + if (r2 != 0 && errno == ENOMEM) + return (r2); + if (r > r2) + r = r2; + s = sc->utftmp.s; + length = sc->utftmp.length; + ++i; + } + r2 = sc->converter[i](as, s, length, sc); + if (r > r2) + r = r2; + return (r); +} + +#if HAVE_ICONV + +/* + * Return -1 if conversion fails. + */ +static int +iconv_strncat_in_locale(struct archive_string *as, const void *_p, + size_t length, struct archive_string_conv *sc) +{ + ICONV_CONST char *itp; + size_t remaining; + iconv_t cd; + char *outp; + size_t avail, bs; + int return_value = 0; /* success */ + int to_size, from_size; + + if (sc->flag & SCONV_TO_UTF16) + to_size = 2; + else + to_size = 1; + if (sc->flag & SCONV_FROM_UTF16) + from_size = 2; + else + from_size = 1; + + if (archive_string_ensure(as, as->length + length*2+to_size) == NULL) + return (-1); + + cd = sc->cd; + itp = (char *)(uintptr_t)_p; + remaining = length; + outp = as->s + as->length; + avail = as->buffer_length - as->length - to_size; + while (remaining >= (size_t)from_size) { + size_t result = iconv(cd, &itp, &remaining, &outp, &avail); + + if (result != (size_t)-1) + break; /* Conversion completed. */ + + if (errno == EILSEQ || errno == EINVAL) { + /* + * If an output charset is UTF-8 or UTF-16BE/LE, + * unknown character should be U+FFFD + * (replacement character). + */ + if (sc->flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) { + size_t rbytes; + if (sc->flag & SCONV_TO_UTF8) + rbytes = sizeof(utf8_replacement_char); + else + rbytes = 2; + + if (avail < rbytes) { + as->length = outp - as->s; + bs = as->buffer_length + + (remaining * to_size) + rbytes; + if (NULL == + archive_string_ensure(as, bs)) + return (-1); + outp = as->s + as->length; + avail = as->buffer_length + - as->length - to_size; + } + if (sc->flag & SCONV_TO_UTF8) + memcpy(outp, utf8_replacement_char, sizeof(utf8_replacement_char)); + else if (sc->flag & SCONV_TO_UTF16BE) + archive_be16enc(outp, UNICODE_R_CHAR); + else + archive_le16enc(outp, UNICODE_R_CHAR); + outp += rbytes; + avail -= rbytes; + } else { + /* Skip the illegal input bytes. */ + *outp++ = '?'; + avail--; + } + itp += from_size; + remaining -= from_size; + return_value = -1; /* failure */ + } else { + /* E2BIG no output buffer, + * Increase an output buffer. */ + as->length = outp - as->s; + bs = as->buffer_length + remaining * 2; + if (NULL == archive_string_ensure(as, bs)) + return (-1); + outp = as->s + as->length; + avail = as->buffer_length - as->length - to_size; + } + } + as->length = outp - as->s; + as->s[as->length] = 0; + if (to_size == 2) + as->s[as->length+1] = 0; + return (return_value); +} + +#endif /* HAVE_ICONV */ + + +#if defined(_WIN32) && !defined(__CYGWIN__) + +/* + * Translate a string from a some CodePage to an another CodePage by + * Windows APIs, and copy the result. Return -1 if conversion fails. + */ +static int +strncat_in_codepage(struct archive_string *as, + const void *_p, size_t length, struct archive_string_conv *sc) +{ + const char *s = (const char *)_p; + struct archive_wstring aws; + size_t l; + int r, saved_flag; + + archive_string_init(&aws); + saved_flag = sc->flag; + sc->flag &= ~(SCONV_NORMALIZATION_D | SCONV_NORMALIZATION_C); + r = archive_wstring_append_from_mbs_in_codepage(&aws, s, length, sc); + sc->flag = saved_flag; + if (r != 0) { + archive_wstring_free(&aws); + if (errno != ENOMEM) + archive_string_append(as, s, length); + return (-1); + } + + l = as->length; + r = archive_string_append_from_wcs_in_codepage( + as, aws.s, aws.length, sc); + if (r != 0 && errno != ENOMEM && l == as->length) + archive_string_append(as, s, length); + archive_wstring_free(&aws); + return (r); +} + +/* + * Test whether MBS ==> WCS is okay. + */ +static int +invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc) +{ + const char *p = (const char *)_p; + unsigned codepage; + DWORD mbflag = MB_ERR_INVALID_CHARS; + + if (sc->flag & SCONV_FROM_CHARSET) + codepage = sc->to_cp; + else + codepage = sc->from_cp; + + if (codepage == CP_C_LOCALE) + return (0); + if (codepage != CP_UTF8) + mbflag |= MB_PRECOMPOSED; + + if (MultiByteToWideChar(codepage, mbflag, p, (int)n, NULL, 0) == 0) + return (-1); /* Invalid */ + return (0); /* Okay */ +} + +#else + +/* + * Test whether MBS ==> WCS is okay. + */ +static int +invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc) +{ + const char *p = (const char *)_p; + size_t r; + +#if HAVE_MBRTOWC + mbstate_t shift_state; + + memset(&shift_state, 0, sizeof(shift_state)); +#else + /* Clear the shift state before starting. */ + mbtowc(NULL, NULL, 0); +#endif + while (n) { + wchar_t wc; + +#if HAVE_MBRTOWC + r = mbrtowc(&wc, p, n, &shift_state); +#else + r = mbtowc(&wc, p, n); +#endif + if (r == (size_t)-1 || r == (size_t)-2) + return (-1);/* Invalid. */ + if (r == 0) + break; + p += r; + n -= r; + } + (void)sc; /* UNUSED */ + return (0); /* All Okey. */ +} + +#endif /* defined(_WIN32) && !defined(__CYGWIN__) */ + +/* + * Basically returns -1 because we cannot make a conversion of charset + * without iconv but in some cases this would return 0. + * Returns 0 if all copied characters are ASCII. + * Returns 0 if both from-locale and to-locale are the same and those + * can be WCS with no error. + */ +static int +best_effort_strncat_in_locale(struct archive_string *as, const void *_p, + size_t length, struct archive_string_conv *sc) +{ + size_t remaining; + const uint8_t *itp; + int return_value = 0; /* success */ + + /* + * If both from-locale and to-locale is the same, this makes a copy. + * And then this checks all copied MBS can be WCS if so returns 0. + */ + if (sc->same) { + if (archive_string_append(as, _p, length) == NULL) + return (-1);/* No memory */ + return (invalid_mbs(_p, length, sc)); + } + + /* + * If a character is ASCII, this just copies it. If not, this + * assigns '?' character instead but in UTF-8 locale this assigns + * byte sequence 0xEF 0xBD 0xBD, which are code point U+FFFD, + * a Replacement Character in Unicode. + */ + + remaining = length; + itp = (const uint8_t *)_p; + while (*itp && remaining > 0) { + if (*itp > 127) { + // Non-ASCII: Substitute with suitable replacement + if (sc->flag & SCONV_TO_UTF8) { + if (archive_string_append(as, utf8_replacement_char, sizeof(utf8_replacement_char)) == NULL) { + __archive_errx(1, "Out of memory"); + } + } else { + archive_strappend_char(as, '?'); + } + return_value = -1; + } else { + archive_strappend_char(as, *itp); + } + ++itp; + } + return (return_value); +} + + +/* + * Unicode conversion functions. + * - UTF-8 <===> UTF-8 in removing surrogate pairs. + * - UTF-8 NFD ===> UTF-8 NFC in removing surrogate pairs. + * - UTF-8 made by libarchive 2.x ===> UTF-8. + * - UTF-16BE <===> UTF-8. + * + */ + +/* + * Utility to convert a single UTF-8 sequence. + * + * Usually return used bytes, return used byte in negative value when + * a unicode character is replaced with U+FFFD. + * See also http://unicode.org/review/pr-121.html Public Review Issue #121 + * Recommended Practice for Replacement Characters. + */ +static int +_utf8_to_unicode(uint32_t *pwc, const char *s, size_t n) +{ + static const char utf8_count[256] = { + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */ + 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */ + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */ + 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */ + }; + int ch, i; + int cnt; + uint32_t wc; + + /* Sanity check. */ + if (n == 0) + return (0); + /* + * Decode 1-4 bytes depending on the value of the first byte. + */ + ch = (unsigned char)*s; + if (ch == 0) + return (0); /* Standard: return 0 for end-of-string. */ + cnt = utf8_count[ch]; + + /* Invalid sequence or there are not plenty bytes. */ + if ((int)n < cnt) { + cnt = (int)n; + for (i = 1; i < cnt; i++) { + if ((s[i] & 0xc0) != 0x80) { + cnt = i; + break; + } + } + goto invalid_sequence; + } + + /* Make a Unicode code point from a single UTF-8 sequence. */ + switch (cnt) { + case 1: /* 1 byte sequence. */ + *pwc = ch & 0x7f; + return (cnt); + case 2: /* 2 bytes sequence. */ + if ((s[1] & 0xc0) != 0x80) { + cnt = 1; + goto invalid_sequence; + } + *pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f); + return (cnt); + case 3: /* 3 bytes sequence. */ + if ((s[1] & 0xc0) != 0x80) { + cnt = 1; + goto invalid_sequence; + } + if ((s[2] & 0xc0) != 0x80) { + cnt = 2; + goto invalid_sequence; + } + wc = ((ch & 0x0f) << 12) + | ((s[1] & 0x3f) << 6) + | (s[2] & 0x3f); + if (wc < 0x800) + goto invalid_sequence;/* Overlong sequence. */ + break; + case 4: /* 4 bytes sequence. */ + if ((s[1] & 0xc0) != 0x80) { + cnt = 1; + goto invalid_sequence; + } + if ((s[2] & 0xc0) != 0x80) { + cnt = 2; + goto invalid_sequence; + } + if ((s[3] & 0xc0) != 0x80) { + cnt = 3; + goto invalid_sequence; + } + wc = ((ch & 0x07) << 18) + | ((s[1] & 0x3f) << 12) + | ((s[2] & 0x3f) << 6) + | (s[3] & 0x3f); + if (wc < 0x10000) + goto invalid_sequence;/* Overlong sequence. */ + break; + default: /* Others are all invalid sequence. */ + if (ch == 0xc0 || ch == 0xc1) + cnt = 2; + else if (ch >= 0xf5 && ch <= 0xf7) + cnt = 4; + else if (ch >= 0xf8 && ch <= 0xfb) + cnt = 5; + else if (ch == 0xfc || ch == 0xfd) + cnt = 6; + else + cnt = 1; + if ((int)n < cnt) + cnt = (int)n; + for (i = 1; i < cnt; i++) { + if ((s[i] & 0xc0) != 0x80) { + cnt = i; + break; + } + } + goto invalid_sequence; + } + + /* The code point larger than 0x10FFFF is not legal + * Unicode values. */ + if (wc > UNICODE_MAX) + goto invalid_sequence; + /* Correctly gets a Unicode, returns used bytes. */ + *pwc = wc; + return (cnt); +invalid_sequence: + *pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */ + return (cnt * -1); +} + +static int +utf8_to_unicode(uint32_t *pwc, const char *s, size_t n) +{ + int cnt; + + cnt = _utf8_to_unicode(pwc, s, n); + /* Any of Surrogate pair is not legal Unicode values. */ + if (cnt == 3 && IS_SURROGATE_PAIR_LA(*pwc)) + return (-3); + return (cnt); +} + +static inline uint32_t +combine_surrogate_pair(uint32_t uc, uint32_t uc2) +{ + uc -= 0xD800; + uc *= 0x400; + uc += uc2 - 0xDC00; + uc += 0x10000; + return (uc); +} + +/* + * Convert a single UTF-8/CESU-8 sequence to a Unicode code point in + * removing surrogate pairs. + * + * CESU-8: The Compatibility Encoding Scheme for UTF-16. + * + * Usually return used bytes, return used byte in negative value when + * a unicode character is replaced with U+FFFD. + */ +static int +cesu8_to_unicode(uint32_t *pwc, const char *s, size_t n) +{ + uint32_t wc = 0; + int cnt; + + cnt = _utf8_to_unicode(&wc, s, n); + if (cnt == 3 && IS_HIGH_SURROGATE_LA(wc)) { + uint32_t wc2 = 0; + if (n - 3 < 3) { + /* Invalid byte sequence. */ + goto invalid_sequence; + } + cnt = _utf8_to_unicode(&wc2, s+3, n-3); + if (cnt != 3 || !IS_LOW_SURROGATE_LA(wc2)) { + /* Invalid byte sequence. */ + goto invalid_sequence; + } + wc = combine_surrogate_pair(wc, wc2); + cnt = 6; + } else if (cnt == 3 && IS_LOW_SURROGATE_LA(wc)) { + /* Invalid byte sequence. */ + goto invalid_sequence; + } + *pwc = wc; + return (cnt); +invalid_sequence: + *pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */ + if (cnt > 0) + cnt *= -1; + return (cnt); +} + +/* + * Convert a Unicode code point to a single UTF-8 sequence. + * + * NOTE:This function does not check if the Unicode is legal or not. + * Please you definitely check it before calling this. + */ +static size_t +unicode_to_utf8(char *p, size_t remaining, uint32_t uc) +{ + char *_p = p; + + /* Invalid Unicode char maps to Replacement character */ + if (uc > UNICODE_MAX) + uc = UNICODE_R_CHAR; + /* Translate code point to UTF8 */ + if (uc <= 0x7f) { + if (remaining == 0) + return (0); + *p++ = (char)uc; + } else if (uc <= 0x7ff) { + if (remaining < 2) + return (0); + *p++ = 0xc0 | ((uc >> 6) & 0x1f); + *p++ = 0x80 | (uc & 0x3f); + } else if (uc <= 0xffff) { + if (remaining < 3) + return (0); + *p++ = 0xe0 | ((uc >> 12) & 0x0f); + *p++ = 0x80 | ((uc >> 6) & 0x3f); + *p++ = 0x80 | (uc & 0x3f); + } else { + if (remaining < 4) + return (0); + *p++ = 0xf0 | ((uc >> 18) & 0x07); + *p++ = 0x80 | ((uc >> 12) & 0x3f); + *p++ = 0x80 | ((uc >> 6) & 0x3f); + *p++ = 0x80 | (uc & 0x3f); + } + return (p - _p); +} + +static int +utf16be_to_unicode(uint32_t *pwc, const char *s, size_t n) +{ + return (utf16_to_unicode(pwc, s, n, 1)); +} + +static int +utf16le_to_unicode(uint32_t *pwc, const char *s, size_t n) +{ + return (utf16_to_unicode(pwc, s, n, 0)); +} + +static int +utf16_to_unicode(uint32_t *pwc, const char *s, size_t n, int be) +{ + const char *utf16 = s; + unsigned uc; + + if (n == 0) + return (0); + if (n == 1) { + /* set the Replacement Character instead. */ + *pwc = UNICODE_R_CHAR; + return (-1); + } + + if (be) + uc = archive_be16dec(utf16); + else + uc = archive_le16dec(utf16); + utf16 += 2; + + /* If this is a surrogate pair, assemble the full code point.*/ + if (IS_HIGH_SURROGATE_LA(uc)) { + unsigned uc2; + + if (n >= 4) { + if (be) + uc2 = archive_be16dec(utf16); + else + uc2 = archive_le16dec(utf16); + } else + uc2 = 0; + if (IS_LOW_SURROGATE_LA(uc2)) { + uc = combine_surrogate_pair(uc, uc2); + utf16 += 2; + } else { + /* Undescribed code point should be U+FFFD + * (replacement character). */ + *pwc = UNICODE_R_CHAR; + return (-2); + } + } + + /* + * Surrogate pair values(0xd800 through 0xdfff) are only + * used by UTF-16, so, after above calculation, the code + * must not be surrogate values, and Unicode has no codes + * larger than 0x10ffff. Thus, those are not legal Unicode + * values. + */ + if (IS_SURROGATE_PAIR_LA(uc) || uc > UNICODE_MAX) { + /* Undescribed code point should be U+FFFD + * (replacement character). */ + *pwc = UNICODE_R_CHAR; + return (((int)(utf16 - s)) * -1); + } + *pwc = uc; + return ((int)(utf16 - s)); +} + +static size_t +unicode_to_utf16be(char *p, size_t remaining, uint32_t uc) +{ + char *utf16 = p; + + if (uc > 0xffff) { + /* We have a code point that won't fit into a + * wchar_t; convert it to a surrogate pair. */ + if (remaining < 4) + return (0); + uc -= 0x10000; + archive_be16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800); + archive_be16enc(utf16+2, (uc & 0x3ff) + 0xDC00); + return (4); + } else { + if (remaining < 2) + return (0); + archive_be16enc(utf16, uc); + return (2); + } +} + +static size_t +unicode_to_utf16le(char *p, size_t remaining, uint32_t uc) +{ + char *utf16 = p; + + if (uc > 0xffff) { + /* We have a code point that won't fit into a + * wchar_t; convert it to a surrogate pair. */ + if (remaining < 4) + return (0); + uc -= 0x10000; + archive_le16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800); + archive_le16enc(utf16+2, (uc & 0x3ff) + 0xDC00); + return (4); + } else { + if (remaining < 2) + return (0); + archive_le16enc(utf16, uc); + return (2); + } +} + +/* + * Copy UTF-8 string in checking surrogate pair. + * If any surrogate pair are found, it would be canonicalized. + */ +static int +strncat_from_utf8_to_utf8(struct archive_string *as, const void *_p, + size_t len, struct archive_string_conv *sc) +{ + const char *s; + char *p, *endp; + int n, ret = 0; + + (void)sc; /* UNUSED */ + + if (archive_string_ensure(as, as->length + len + 1) == NULL) + return (-1); + + s = (const char *)_p; + p = as->s + as->length; + endp = as->s + as->buffer_length -1; + do { + uint32_t uc; + const char *ss = s; + size_t w; + + /* + * Forward byte sequence until a conversion of that is needed. + */ + while ((n = utf8_to_unicode(&uc, s, len)) > 0) { + s += n; + len -= n; + } + if (ss < s) { + if (p + (s - ss) > endp) { + as->length = p - as->s; + if (archive_string_ensure(as, + as->buffer_length + len + 1) == NULL) + return (-1); + p = as->s + as->length; + endp = as->s + as->buffer_length -1; + } + + memcpy(p, ss, s - ss); + p += s - ss; + } + + /* + * If n is negative, current byte sequence needs a replacement. + */ + if (n < 0) { + if (n == -3 && IS_SURROGATE_PAIR_LA(uc)) { + /* Current byte sequence may be CESU-8. */ + n = cesu8_to_unicode(&uc, s, len); + } + if (n < 0) { + ret = -1; + n *= -1;/* Use a replaced unicode character. */ + } + + /* Rebuild UTF-8 byte sequence. */ + while ((w = unicode_to_utf8(p, endp - p, uc)) == 0) { + as->length = p - as->s; + if (archive_string_ensure(as, + as->buffer_length + len + 1) == NULL) + return (-1); + p = as->s + as->length; + endp = as->s + as->buffer_length -1; + } + p += w; + s += n; + len -= n; + } + } while (n > 0); + as->length = p - as->s; + as->s[as->length] = '\0'; + return (ret); +} + +static int +archive_string_append_unicode(struct archive_string *as, const void *_p, + size_t len, struct archive_string_conv *sc) +{ + const char *s; + char *p, *endp; + uint32_t uc; + size_t w; + int n, ret = 0, ts, tm; + int (*parse)(uint32_t *, const char *, size_t); + size_t (*unparse)(char *, size_t, uint32_t); + + if (sc->flag & SCONV_TO_UTF16BE) { + unparse = unicode_to_utf16be; + ts = 2; + } else if (sc->flag & SCONV_TO_UTF16LE) { + unparse = unicode_to_utf16le; + ts = 2; + } else if (sc->flag & SCONV_TO_UTF8) { + unparse = unicode_to_utf8; + ts = 1; + } else { + /* + * This case is going to be converted to another + * character-set through iconv. + */ + if (sc->flag & SCONV_FROM_UTF16BE) { + unparse = unicode_to_utf16be; + ts = 2; + } else if (sc->flag & SCONV_FROM_UTF16LE) { + unparse = unicode_to_utf16le; + ts = 2; + } else { + unparse = unicode_to_utf8; + ts = 1; + } + } + + if (sc->flag & SCONV_FROM_UTF16BE) { + parse = utf16be_to_unicode; + tm = 1; + } else if (sc->flag & SCONV_FROM_UTF16LE) { + parse = utf16le_to_unicode; + tm = 1; + } else { + parse = cesu8_to_unicode; + tm = ts; + } + + if (archive_string_ensure(as, as->length + len * tm + ts) == NULL) + return (-1); + + s = (const char *)_p; + p = as->s + as->length; + endp = as->s + as->buffer_length - ts; + while ((n = parse(&uc, s, len)) != 0) { + if (n < 0) { + /* Use a replaced unicode character. */ + n *= -1; + ret = -1; + } + s += n; + len -= n; + while ((w = unparse(p, endp - p, uc)) == 0) { + /* There is not enough output buffer so + * we have to expand it. */ + as->length = p - as->s; + if (archive_string_ensure(as, + as->buffer_length + len * tm + ts) == NULL) + return (-1); + p = as->s + as->length; + endp = as->s + as->buffer_length - ts; + } + p += w; + } + as->length = p - as->s; + as->s[as->length] = '\0'; + if (ts == 2) + as->s[as->length+1] = '\0'; + return (ret); +} + +/* + * Following Constants for Hangul compositions this information comes from + * Unicode Standard Annex #15 http://unicode.org/reports/tr15/ + */ +#define HC_SBASE 0xAC00 +#define HC_LBASE 0x1100 +#define HC_VBASE 0x1161 +#define HC_TBASE 0x11A7 +#define HC_LCOUNT 19 +#define HC_VCOUNT 21 +#define HC_TCOUNT 28 +#define HC_NCOUNT (HC_VCOUNT * HC_TCOUNT) +#define HC_SCOUNT (HC_LCOUNT * HC_NCOUNT) + +static uint32_t +get_nfc(uint32_t uc, uint32_t uc2) +{ + int t, b; + + t = 0; + b = sizeof(u_composition_table)/sizeof(u_composition_table[0]) -1; + while (b >= t) { + int m = (t + b) / 2; + if (u_composition_table[m].cp1 < uc) + t = m + 1; + else if (u_composition_table[m].cp1 > uc) + b = m - 1; + else if (u_composition_table[m].cp2 < uc2) + t = m + 1; + else if (u_composition_table[m].cp2 > uc2) + b = m - 1; + else + return (u_composition_table[m].nfc); + } + return (0); +} + +#define FDC_MAX 10 /* The maximum number of Following Decomposable + * Characters. */ + +/* + * Update first code point. + */ +#define UPDATE_UC(new_uc) do { \ + uc = new_uc; \ + ucptr = NULL; \ +} while (0) + +/* + * Replace first code point with second code point. + */ +#define REPLACE_UC_WITH_UC2() do { \ + uc = uc2; \ + ucptr = uc2ptr; \ + n = n2; \ +} while (0) + +#define EXPAND_BUFFER() do { \ + as->length = p - as->s; \ + if (archive_string_ensure(as, \ + as->buffer_length + len * tm + ts) == NULL)\ + return (-1); \ + p = as->s + as->length; \ + endp = as->s + as->buffer_length - ts; \ +} while (0) + +#define UNPARSE(p, endp, uc) do { \ + while ((w = unparse(p, (endp) - (p), uc)) == 0) {\ + EXPAND_BUFFER(); \ + } \ + p += w; \ +} while (0) + +/* + * Write first code point. + * If the code point has not be changed from its original code, + * this just copies it from its original buffer pointer. + * If not, this converts it to UTF-8 byte sequence and copies it. + */ +#define WRITE_UC() do { \ + if (ucptr) { \ + if (p + n > endp) \ + EXPAND_BUFFER(); \ + switch (n) { \ + case 4: \ + *p++ = *ucptr++; \ + /* FALL THROUGH */ \ + case 3: \ + *p++ = *ucptr++; \ + /* FALL THROUGH */ \ + case 2: \ + *p++ = *ucptr++; \ + /* FALL THROUGH */ \ + case 1: \ + *p++ = *ucptr; \ + break; \ + } \ + ucptr = NULL; \ + } else { \ + UNPARSE(p, endp, uc); \ + } \ +} while (0) + +/* + * Collect following decomposable code points. + */ +#define COLLECT_CPS(start) do { \ + int _i; \ + for (_i = start; _i < FDC_MAX ; _i++) { \ + nx = parse(&ucx[_i], s, len); \ + if (nx <= 0) \ + break; \ + cx = CCC(ucx[_i]); \ + if (cl >= cx && cl != 228 && cx != 228)\ + break; \ + s += nx; \ + len -= nx; \ + cl = cx; \ + ccx[_i] = cx; \ + } \ + if (_i >= FDC_MAX) { \ + ret = -1; \ + ucx_size = FDC_MAX; \ + } else \ + ucx_size = _i; \ +} while (0) + +/* + * Normalize UTF-8/UTF-16BE characters to Form C and copy the result. + * + * TODO: Convert composition exclusions, which are never converted + * from NFC,NFD,NFKC and NFKD, to Form C. + */ +static int +archive_string_normalize_C(struct archive_string *as, const void *_p, + size_t len, struct archive_string_conv *sc) +{ + const char *s = (const char *)_p; + char *p, *endp; + uint32_t uc, uc2; + size_t w; + int always_replace, n, n2, ret = 0, spair, ts, tm; + int (*parse)(uint32_t *, const char *, size_t); + size_t (*unparse)(char *, size_t, uint32_t); + + always_replace = 1; + ts = 1;/* text size. */ + if (sc->flag & SCONV_TO_UTF16BE) { + unparse = unicode_to_utf16be; + ts = 2; + if (sc->flag & SCONV_FROM_UTF16BE) + always_replace = 0; + } else if (sc->flag & SCONV_TO_UTF16LE) { + unparse = unicode_to_utf16le; + ts = 2; + if (sc->flag & SCONV_FROM_UTF16LE) + always_replace = 0; + } else if (sc->flag & SCONV_TO_UTF8) { + unparse = unicode_to_utf8; + if (sc->flag & SCONV_FROM_UTF8) + always_replace = 0; + } else { + /* + * This case is going to be converted to another + * character-set through iconv. + */ + always_replace = 0; + if (sc->flag & SCONV_FROM_UTF16BE) { + unparse = unicode_to_utf16be; + ts = 2; + } else if (sc->flag & SCONV_FROM_UTF16LE) { + unparse = unicode_to_utf16le; + ts = 2; + } else { + unparse = unicode_to_utf8; + } + } + + if (sc->flag & SCONV_FROM_UTF16BE) { + parse = utf16be_to_unicode; + tm = 1; + spair = 4;/* surrogate pair size in UTF-16. */ + } else if (sc->flag & SCONV_FROM_UTF16LE) { + parse = utf16le_to_unicode; + tm = 1; + spair = 4;/* surrogate pair size in UTF-16. */ + } else { + parse = cesu8_to_unicode; + tm = ts; + spair = 6;/* surrogate pair size in UTF-8. */ + } + + if (archive_string_ensure(as, as->length + len * tm + ts) == NULL) + return (-1); + + p = as->s + as->length; + endp = as->s + as->buffer_length - ts; + while ((n = parse(&uc, s, len)) != 0) { + const char *ucptr, *uc2ptr; + + if (n < 0) { + /* Use a replaced unicode character. */ + UNPARSE(p, endp, uc); + s += n*-1; + len -= n*-1; + ret = -1; + continue; + } else if (n == spair || always_replace) + /* uc is converted from a surrogate pair. + * this should be treated as a changed code. */ + ucptr = NULL; + else + ucptr = s; + s += n; + len -= n; + + /* Read second code point. */ + while ((n2 = parse(&uc2, s, len)) > 0) { + uint32_t ucx[FDC_MAX]; + int ccx[FDC_MAX]; + int cl, cx, i, nx, ucx_size; + int LIndex,SIndex; + uint32_t nfc; + + if (n2 == spair || always_replace) + /* uc2 is converted from a surrogate pair. + * this should be treated as a changed code. */ + uc2ptr = NULL; + else + uc2ptr = s; + s += n2; + len -= n2; + + /* + * If current second code point is out of decomposable + * code points, finding compositions is unneeded. + */ + if (!IS_DECOMPOSABLE_BLOCK(uc2)) { + WRITE_UC(); + REPLACE_UC_WITH_UC2(); + continue; + } + + /* + * Try to combine current code points. + */ + /* + * We have to combine Hangul characters according to + * http://uniicode.org/reports/tr15/#Hangul + */ + if (0 <= (LIndex = uc - HC_LBASE) && + LIndex < HC_LCOUNT) { + /* + * Hangul Composition. + * 1. Two current code points are L and V. + */ + int VIndex = uc2 - HC_VBASE; + if (0 <= VIndex && VIndex < HC_VCOUNT) { + /* Make syllable of form LV. */ + UPDATE_UC(HC_SBASE + + (LIndex * HC_VCOUNT + VIndex) * + HC_TCOUNT); + } else { + WRITE_UC(); + REPLACE_UC_WITH_UC2(); + } + continue; + } else if (0 <= (SIndex = uc - HC_SBASE) && + SIndex < HC_SCOUNT && (SIndex % HC_TCOUNT) == 0) { + /* + * Hangul Composition. + * 2. Two current code points are LV and T. + */ + int TIndex = uc2 - HC_TBASE; + if (0 < TIndex && TIndex < HC_TCOUNT) { + /* Make syllable of form LVT. */ + UPDATE_UC(uc + TIndex); + } else { + WRITE_UC(); + REPLACE_UC_WITH_UC2(); + } + continue; + } else if ((nfc = get_nfc(uc, uc2)) != 0) { + /* A composition to current code points + * is found. */ + UPDATE_UC(nfc); + continue; + } else if ((cl = CCC(uc2)) == 0) { + /* Clearly 'uc2' the second code point is not + * a decomposable code. */ + WRITE_UC(); + REPLACE_UC_WITH_UC2(); + continue; + } + + /* + * Collect following decomposable code points. + */ + cx = 0; + ucx[0] = uc2; + ccx[0] = cl; + COLLECT_CPS(1); + + /* + * Find a composed code in the collected code points. + */ + i = 1; + while (i < ucx_size) { + int j; + + if ((nfc = get_nfc(uc, ucx[i])) == 0) { + i++; + continue; + } + + /* + * nfc is composed of uc and ucx[i]. + */ + UPDATE_UC(nfc); + + /* + * Remove ucx[i] by shifting + * following code points. + */ + for (j = i; j+1 < ucx_size; j++) { + ucx[j] = ucx[j+1]; + ccx[j] = ccx[j+1]; + } + ucx_size --; + + /* + * Collect following code points blocked + * by ucx[i] the removed code point. + */ + if (ucx_size > 0 && i == ucx_size && + nx > 0 && cx == cl) { + cl = ccx[ucx_size-1]; + COLLECT_CPS(ucx_size); + } + /* + * Restart finding a composed code with + * the updated uc from the top of the + * collected code points. + */ + i = 0; + } + + /* + * Apparently the current code points are not + * decomposed characters or already composed. + */ + WRITE_UC(); + for (i = 0; i < ucx_size; i++) + UNPARSE(p, endp, ucx[i]); + + /* + * Flush out remaining canonical combining characters. + */ + if (nx > 0 && cx == cl && len > 0) { + while ((nx = parse(&ucx[0], s, len)) + > 0) { + cx = CCC(ucx[0]); + if (cl > cx) + break; + s += nx; + len -= nx; + cl = cx; + UNPARSE(p, endp, ucx[0]); + } + } + break; + } + if (n2 < 0) { + WRITE_UC(); + /* Use a replaced unicode character. */ + UNPARSE(p, endp, uc2); + s += n2*-1; + len -= n2*-1; + ret = -1; + continue; + } else if (n2 == 0) { + WRITE_UC(); + break; + } + } + as->length = p - as->s; + as->s[as->length] = '\0'; + if (ts == 2) + as->s[as->length+1] = '\0'; + return (ret); +} + +static int +get_nfd(uint32_t *cp1, uint32_t *cp2, uint32_t uc) +{ + int t, b; + + /* + * These are not converted to NFD on Mac OS. + */ + if ((uc >= 0x2000 && uc <= 0x2FFF) || + (uc >= 0xF900 && uc <= 0xFAFF) || + (uc >= 0x2F800 && uc <= 0x2FAFF)) + return (0); + /* + * Those code points are not converted to NFD on Mac OS. + * I do not know the reason because it is undocumented. + * NFC NFD + * 1109A ==> 11099 110BA + * 1109C ==> 1109B 110BA + * 110AB ==> 110A5 110BA + */ + if (uc == 0x1109A || uc == 0x1109C || uc == 0x110AB) + return (0); + + t = 0; + b = sizeof(u_decomposition_table)/sizeof(u_decomposition_table[0]) -1; + while (b >= t) { + int m = (t + b) / 2; + if (u_decomposition_table[m].nfc < uc) + t = m + 1; + else if (u_decomposition_table[m].nfc > uc) + b = m - 1; + else { + *cp1 = u_decomposition_table[m].cp1; + *cp2 = u_decomposition_table[m].cp2; + return (1); + } + } + return (0); +} + +#define REPLACE_UC_WITH(cp) do { \ + uc = cp; \ + ucptr = NULL; \ +} while (0) + +/* + * Normalize UTF-8 characters to Form D and copy the result. + */ +static int +archive_string_normalize_D(struct archive_string *as, const void *_p, + size_t len, struct archive_string_conv *sc) +{ + const char *s = (const char *)_p; + char *p, *endp; + uint32_t uc, uc2; + size_t w; + int always_replace, n, n2, ret = 0, spair, ts, tm; + int (*parse)(uint32_t *, const char *, size_t); + size_t (*unparse)(char *, size_t, uint32_t); + + always_replace = 1; + ts = 1;/* text size. */ + if (sc->flag & SCONV_TO_UTF16BE) { + unparse = unicode_to_utf16be; + ts = 2; + if (sc->flag & SCONV_FROM_UTF16BE) + always_replace = 0; + } else if (sc->flag & SCONV_TO_UTF16LE) { + unparse = unicode_to_utf16le; + ts = 2; + if (sc->flag & SCONV_FROM_UTF16LE) + always_replace = 0; + } else if (sc->flag & SCONV_TO_UTF8) { + unparse = unicode_to_utf8; + if (sc->flag & SCONV_FROM_UTF8) + always_replace = 0; + } else { + /* + * This case is going to be converted to another + * character-set through iconv. + */ + always_replace = 0; + if (sc->flag & SCONV_FROM_UTF16BE) { + unparse = unicode_to_utf16be; + ts = 2; + } else if (sc->flag & SCONV_FROM_UTF16LE) { + unparse = unicode_to_utf16le; + ts = 2; + } else { + unparse = unicode_to_utf8; + } + } + + if (sc->flag & SCONV_FROM_UTF16BE) { + parse = utf16be_to_unicode; + tm = 1; + spair = 4;/* surrogate pair size in UTF-16. */ + } else if (sc->flag & SCONV_FROM_UTF16LE) { + parse = utf16le_to_unicode; + tm = 1; + spair = 4;/* surrogate pair size in UTF-16. */ + } else { + parse = cesu8_to_unicode; + tm = ts; + spair = 6;/* surrogate pair size in UTF-8. */ + } + + if (archive_string_ensure(as, as->length + len * tm + ts) == NULL) + return (-1); + + p = as->s + as->length; + endp = as->s + as->buffer_length - ts; + while ((n = parse(&uc, s, len)) != 0) { + const char *ucptr; + uint32_t cp1, cp2; + int SIndex; + struct { + uint32_t uc; + int ccc; + } fdc[FDC_MAX]; + int fdi, fdj; + int ccc; + +check_first_code: + if (n < 0) { + /* Use a replaced unicode character. */ + UNPARSE(p, endp, uc); + s += n*-1; + len -= n*-1; + ret = -1; + continue; + } else if (n == spair || always_replace) + /* uc is converted from a surrogate pair. + * this should be treated as a changed code. */ + ucptr = NULL; + else + ucptr = s; + s += n; + len -= n; + + /* Hangul Decomposition. */ + if ((SIndex = uc - HC_SBASE) >= 0 && SIndex < HC_SCOUNT) { + int L = HC_LBASE + SIndex / HC_NCOUNT; + int V = HC_VBASE + (SIndex % HC_NCOUNT) / HC_TCOUNT; + int T = HC_TBASE + SIndex % HC_TCOUNT; + + REPLACE_UC_WITH(L); + WRITE_UC(); + REPLACE_UC_WITH(V); + WRITE_UC(); + if (T != HC_TBASE) { + REPLACE_UC_WITH(T); + WRITE_UC(); + } + continue; + } + if (IS_DECOMPOSABLE_BLOCK(uc) && CCC(uc) != 0) { + WRITE_UC(); + continue; + } + + fdi = 0; + while (get_nfd(&cp1, &cp2, uc) && fdi < FDC_MAX) { + int k; + + for (k = fdi; k > 0; k--) + fdc[k] = fdc[k-1]; + fdc[0].ccc = CCC(cp2); + fdc[0].uc = cp2; + fdi++; + REPLACE_UC_WITH(cp1); + } + + /* Read following code points. */ + while ((n2 = parse(&uc2, s, len)) > 0 && + (ccc = CCC(uc2)) != 0 && fdi < FDC_MAX) { + int j, k; + + s += n2; + len -= n2; + for (j = 0; j < fdi; j++) { + if (fdc[j].ccc > ccc) + break; + } + if (j < fdi) { + for (k = fdi; k > j; k--) + fdc[k] = fdc[k-1]; + fdc[j].ccc = ccc; + fdc[j].uc = uc2; + } else { + fdc[fdi].ccc = ccc; + fdc[fdi].uc = uc2; + } + fdi++; + } + + WRITE_UC(); + for (fdj = 0; fdj < fdi; fdj++) { + REPLACE_UC_WITH(fdc[fdj].uc); + WRITE_UC(); + } + + if (n2 == 0) + break; + REPLACE_UC_WITH(uc2); + n = n2; + goto check_first_code; + } + as->length = p - as->s; + as->s[as->length] = '\0'; + if (ts == 2) + as->s[as->length+1] = '\0'; + return (ret); +} + +/* + * libarchive 2.x made incorrect UTF-8 strings in the wrong assumption + * that WCS is Unicode. It is true for several platforms but some are false. + * And then people who did not use UTF-8 locale on the non Unicode WCS + * platform and made a tar file with libarchive(mostly bsdtar) 2.x. Those + * now cannot get right filename from libarchive 3.x and later since we + * fixed the wrong assumption and it is incompatible to older its versions. + * So we provide special option, "compat-2x.x", for resolving it. + * That option enable the string conversion of libarchive 2.x. + * + * Translates the wrong UTF-8 string made by libarchive 2.x into current + * locale character set and appends to the archive_string. + * Note: returns -1 if conversion fails. + */ +static int +strncat_from_utf8_libarchive2(struct archive_string *as, + const void *_p, size_t len, struct archive_string_conv *sc) +{ + const char *s; + int n; + char *p; + char *end; + uint32_t unicode; +#if HAVE_WCRTOMB + mbstate_t shift_state; + + memset(&shift_state, 0, sizeof(shift_state)); +#else + /* Clear the shift state before starting. */ + wctomb(NULL, L'\0'); +#endif + (void)sc; /* UNUSED */ + /* + * Allocate buffer for MBS. + * We need this allocation here since it is possible that + * as->s is still NULL. + */ + if (archive_string_ensure(as, as->length + len + 1) == NULL) + return (-1); + + s = (const char *)_p; + p = as->s + as->length; + end = as->s + as->buffer_length - MB_CUR_MAX -1; + while ((n = _utf8_to_unicode(&unicode, s, len)) != 0) { + wchar_t wc; + + if (p >= end) { + as->length = p - as->s; + /* Re-allocate buffer for MBS. */ + if (archive_string_ensure(as, + as->length + max(len * 2, + (size_t)MB_CUR_MAX) + 1) == NULL) + return (-1); + p = as->s + as->length; + end = as->s + as->buffer_length - MB_CUR_MAX -1; + } + + /* + * As libarchive 2.x, translates the UTF-8 characters into + * wide-characters in the assumption that WCS is Unicode. + */ + if (n < 0) { + n *= -1; + wc = L'?'; + } else + wc = (wchar_t)unicode; + + s += n; + len -= n; + /* + * Translates the wide-character into the current locale MBS. + */ +#if HAVE_WCRTOMB + n = (int)wcrtomb(p, wc, &shift_state); +#else + n = (int)wctomb(p, wc); +#endif + if (n == -1) + return (-1); + p += n; + } + as->length = p - as->s; + as->s[as->length] = '\0'; + return (0); +} + + +/* + * Conversion functions between current locale dependent MBS and UTF-16BE. + * strncat_from_utf16be() : UTF-16BE --> MBS + * strncat_to_utf16be() : MBS --> UTF16BE + */ + +#if defined(_WIN32) && !defined(__CYGWIN__) + +/* + * Convert a UTF-16BE/LE string to current locale and copy the result. + * Return -1 if conversion fails. + */ +static int +win_strncat_from_utf16(struct archive_string *as, const void *_p, size_t bytes, + struct archive_string_conv *sc, int be) +{ + struct archive_string tmp; + const char *u16; + int ll; + BOOL defchar; + char *mbs; + size_t mbs_size, b; + int ret = 0; + + bytes &= ~1; + if (archive_string_ensure(as, as->length + bytes +1) == NULL) + return (-1); + + mbs = as->s + as->length; + mbs_size = as->buffer_length - as->length -1; + + if (sc->to_cp == CP_C_LOCALE) { + /* + * "C" locale special process. + */ + u16 = _p; + ll = 0; + for (b = 0; b < bytes; b += 2) { + uint16_t val; + if (be) + val = archive_be16dec(u16+b); + else + val = archive_le16dec(u16+b); + if (val > 255) { + *mbs++ = '?'; + ret = -1; + } else + *mbs++ = (char)(val&0xff); + ll++; + } + as->length += ll; + as->s[as->length] = '\0'; + return (ret); + } + + archive_string_init(&tmp); + if (be) { + if (is_big_endian()) { + u16 = _p; + } else { + if (archive_string_ensure(&tmp, bytes+2) == NULL) + return (-1); + memcpy(tmp.s, _p, bytes); + for (b = 0; b < bytes; b += 2) { + uint16_t val = archive_be16dec(tmp.s+b); + archive_le16enc(tmp.s+b, val); + } + u16 = tmp.s; + } + } else { + if (!is_big_endian()) { + u16 = _p; + } else { + if (archive_string_ensure(&tmp, bytes+2) == NULL) + return (-1); + memcpy(tmp.s, _p, bytes); + for (b = 0; b < bytes; b += 2) { + uint16_t val = archive_le16dec(tmp.s+b); + archive_be16enc(tmp.s+b, val); + } + u16 = tmp.s; + } + } + + do { + defchar = 0; + ll = WideCharToMultiByte(sc->to_cp, 0, + (LPCWSTR)u16, (int)bytes>>1, mbs, (int)mbs_size, + NULL, &defchar); + /* Exit loop if we succeeded */ + if (ll != 0 || + GetLastError() != ERROR_INSUFFICIENT_BUFFER) { + break; + } + /* Else expand buffer and loop to try again. */ + ll = WideCharToMultiByte(sc->to_cp, 0, + (LPCWSTR)u16, (int)bytes, NULL, 0, NULL, NULL); + if (archive_string_ensure(as, ll +1) == NULL) + return (-1); + mbs = as->s + as->length; + mbs_size = as->buffer_length - as->length -1; + } while (1); + archive_string_free(&tmp); + as->length += ll; + as->s[as->length] = '\0'; + if (ll == 0 || defchar) + ret = -1; + return (ret); +} + +static int +win_strncat_from_utf16be(struct archive_string *as, const void *_p, + size_t bytes, struct archive_string_conv *sc) +{ + return (win_strncat_from_utf16(as, _p, bytes, sc, 1)); +} + +static int +win_strncat_from_utf16le(struct archive_string *as, const void *_p, + size_t bytes, struct archive_string_conv *sc) +{ + return (win_strncat_from_utf16(as, _p, bytes, sc, 0)); +} + +static int +is_big_endian(void) +{ + uint16_t d = 1; + + return (archive_be16dec(&d) == 1); +} + +/* + * Convert a current locale string to UTF-16BE/LE and copy the result. + * Return -1 if conversion fails. + */ +static int +win_strncat_to_utf16(struct archive_string *as16, const void *_p, + size_t length, struct archive_string_conv *sc, int bigendian) +{ + const char *s = (const char *)_p; + char *u16; + size_t count, avail; + + if (archive_string_ensure(as16, + as16->length + (length + 1) * 2) == NULL) + return (-1); + + u16 = as16->s + as16->length; + avail = as16->buffer_length - 2; + if (sc->from_cp == CP_C_LOCALE) { + /* + * "C" locale special process. + */ + count = 0; + while (count < length && *s) { + if (bigendian) + archive_be16enc(u16, *s); + else + archive_le16enc(u16, *s); + u16 += 2; + s++; + count++; + } + as16->length += count << 1; + as16->s[as16->length] = 0; + as16->s[as16->length+1] = 0; + return (0); + } + do { + count = MultiByteToWideChar(sc->from_cp, + MB_PRECOMPOSED, s, (int)length, (LPWSTR)u16, (int)avail>>1); + /* Exit loop if we succeeded */ + if (count != 0 || + GetLastError() != ERROR_INSUFFICIENT_BUFFER) { + break; + } + /* Expand buffer and try again */ + count = MultiByteToWideChar(sc->from_cp, + MB_PRECOMPOSED, s, (int)length, NULL, 0); + if (archive_string_ensure(as16, (count +1) * 2) + == NULL) + return (-1); + u16 = as16->s + as16->length; + avail = as16->buffer_length - 2; + } while (1); + as16->length += count * 2; + as16->s[as16->length] = 0; + as16->s[as16->length+1] = 0; + if (count == 0) + return (-1); + + if (is_big_endian()) { + if (!bigendian) { + while (count > 0) { + uint16_t v = archive_be16dec(u16); + archive_le16enc(u16, v); + u16 += 2; + count--; + } + } + } else { + if (bigendian) { + while (count > 0) { + uint16_t v = archive_le16dec(u16); + archive_be16enc(u16, v); + u16 += 2; + count--; + } + } + } + return (0); +} + +static int +win_strncat_to_utf16be(struct archive_string *as16, const void *_p, + size_t length, struct archive_string_conv *sc) +{ + return (win_strncat_to_utf16(as16, _p, length, sc, 1)); +} + +static int +win_strncat_to_utf16le(struct archive_string *as16, const void *_p, + size_t length, struct archive_string_conv *sc) +{ + return (win_strncat_to_utf16(as16, _p, length, sc, 0)); +} + +#endif /* _WIN32 && !__CYGWIN__ */ + +/* + * Do the best effort for conversions. + * We cannot handle UTF-16BE character-set without such iconv, + * but there is a chance if a string consists just ASCII code or + * a current locale is UTF-8. + */ + +/* + * Convert a UTF-16BE string to current locale and copy the result. + * Return -1 if conversion fails. + */ +static int +best_effort_strncat_from_utf16(struct archive_string *as, const void *_p, + size_t bytes, struct archive_string_conv *sc, int be) +{ + const char *utf16 = (const char *)_p; + char *mbs; + uint32_t uc; + int n, ret; + + (void)sc; /* UNUSED */ + /* + * Other case, we should do the best effort. + * If all character are ASCII(<0x7f), we can convert it. + * if not , we set a alternative character and return -1. + */ + ret = 0; + if (archive_string_ensure(as, as->length + bytes +1) == NULL) + return (-1); + mbs = as->s + as->length; + + while ((n = utf16_to_unicode(&uc, utf16, bytes, be)) != 0) { + if (n < 0) { + n *= -1; + ret = -1; + } + bytes -= n; + utf16 += n; + + if (uc > 127) { + /* We cannot handle it. */ + *mbs++ = '?'; + ret = -1; + } else + *mbs++ = (char)uc; + } + as->length = mbs - as->s; + as->s[as->length] = '\0'; + return (ret); +} + +static int +best_effort_strncat_from_utf16be(struct archive_string *as, const void *_p, + size_t bytes, struct archive_string_conv *sc) +{ + return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 1)); +} + +static int +best_effort_strncat_from_utf16le(struct archive_string *as, const void *_p, + size_t bytes, struct archive_string_conv *sc) +{ + return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 0)); +} + +/* + * Convert a current locale string to UTF-16BE/LE and copy the result. + * Return -1 if conversion fails. + */ +static int +best_effort_strncat_to_utf16(struct archive_string *as16, const void *_p, + size_t length, struct archive_string_conv *sc, int bigendian) +{ + const char *s = (const char *)_p; + char *utf16; + size_t remaining; + int ret; + + (void)sc; /* UNUSED */ + /* + * Other case, we should do the best effort. + * If all character are ASCII(<0x7f), we can convert it. + * if not , we set a alternative character and return -1. + */ + ret = 0; + remaining = length; + + if (archive_string_ensure(as16, + as16->length + (length + 1) * 2) == NULL) + return (-1); + + utf16 = as16->s + as16->length; + while (remaining--) { + unsigned c = *s++; + if (c > 127) { + /* We cannot handle it. */ + c = UNICODE_R_CHAR; + ret = -1; + } + if (bigendian) + archive_be16enc(utf16, c); + else + archive_le16enc(utf16, c); + utf16 += 2; + } + as16->length = utf16 - as16->s; + as16->s[as16->length] = 0; + as16->s[as16->length+1] = 0; + return (ret); +} + +static int +best_effort_strncat_to_utf16be(struct archive_string *as16, const void *_p, + size_t length, struct archive_string_conv *sc) +{ + return (best_effort_strncat_to_utf16(as16, _p, length, sc, 1)); +} + +static int +best_effort_strncat_to_utf16le(struct archive_string *as16, const void *_p, + size_t length, struct archive_string_conv *sc) +{ + return (best_effort_strncat_to_utf16(as16, _p, length, sc, 0)); +} + + +/* + * Multistring operations. + */ + +void +archive_mstring_clean(struct archive_mstring *aes) +{ + archive_wstring_free(&(aes->aes_wcs)); + archive_string_free(&(aes->aes_mbs)); + archive_string_free(&(aes->aes_utf8)); + archive_string_free(&(aes->aes_mbs_in_locale)); + aes->aes_set = 0; +} + +void +archive_mstring_copy(struct archive_mstring *dest, struct archive_mstring *src) +{ + dest->aes_set = src->aes_set; + archive_string_copy(&(dest->aes_mbs), &(src->aes_mbs)); + archive_string_copy(&(dest->aes_utf8), &(src->aes_utf8)); + archive_wstring_copy(&(dest->aes_wcs), &(src->aes_wcs)); +} + +int +archive_mstring_get_utf8(struct archive *a, struct archive_mstring *aes, + const char **p) +{ + struct archive_string_conv *sc; + int r; + + /* If we already have a UTF8 form, return that immediately. */ + if (aes->aes_set & AES_SET_UTF8) { + *p = aes->aes_utf8.s; + return (0); + } + + *p = NULL; + if (aes->aes_set & AES_SET_MBS) { + sc = archive_string_conversion_to_charset(a, "UTF-8", 1); + if (sc == NULL) + return (-1);/* Couldn't allocate memory for sc. */ + r = archive_strncpy_l(&(aes->aes_utf8), aes->aes_mbs.s, + aes->aes_mbs.length, sc); + if (a == NULL) + free_sconv_object(sc); + if (r == 0) { + aes->aes_set |= AES_SET_UTF8; + *p = aes->aes_utf8.s; + return (0);/* success. */ + } else + return (-1);/* failure. */ + } + return (0);/* success. */ +} + +int +archive_mstring_get_mbs(struct archive *a, struct archive_mstring *aes, + const char **p) +{ + int r, ret = 0; + + (void)a; /* UNUSED */ + /* If we already have an MBS form, return that immediately. */ + if (aes->aes_set & AES_SET_MBS) { + *p = aes->aes_mbs.s; + return (ret); + } + + *p = NULL; + /* If there's a WCS form, try converting with the native locale. */ + if (aes->aes_set & AES_SET_WCS) { + archive_string_empty(&(aes->aes_mbs)); + r = archive_string_append_from_wcs(&(aes->aes_mbs), + aes->aes_wcs.s, aes->aes_wcs.length); + *p = aes->aes_mbs.s; + if (r == 0) { + aes->aes_set |= AES_SET_MBS; + return (ret); + } else + ret = -1; + } + + /* + * Only a UTF-8 form cannot avail because its conversion already + * failed at archive_mstring_update_utf8(). + */ + return (ret); +} + +int +archive_mstring_get_wcs(struct archive *a, struct archive_mstring *aes, + const wchar_t **wp) +{ + int r, ret = 0; + + (void)a;/* UNUSED */ + /* Return WCS form if we already have it. */ + if (aes->aes_set & AES_SET_WCS) { + *wp = aes->aes_wcs.s; + return (ret); + } + + *wp = NULL; + /* Try converting MBS to WCS using native locale. */ + if (aes->aes_set & AES_SET_MBS) { + archive_wstring_empty(&(aes->aes_wcs)); + r = archive_wstring_append_from_mbs(&(aes->aes_wcs), + aes->aes_mbs.s, aes->aes_mbs.length); + if (r == 0) { + aes->aes_set |= AES_SET_WCS; + *wp = aes->aes_wcs.s; + } else + ret = -1;/* failure. */ + } + return (ret); +} + +int +archive_mstring_get_mbs_l(struct archive_mstring *aes, + const char **p, size_t *length, struct archive_string_conv *sc) +{ + int r, ret = 0; + +#if defined(_WIN32) && !defined(__CYGWIN__) + /* + * Internationalization programming on Windows must use Wide + * characters because Windows platform cannot make locale UTF-8. + */ + if (sc != NULL && (aes->aes_set & AES_SET_WCS) != 0) { + archive_string_empty(&(aes->aes_mbs_in_locale)); + r = archive_string_append_from_wcs_in_codepage( + &(aes->aes_mbs_in_locale), aes->aes_wcs.s, + aes->aes_wcs.length, sc); + if (r == 0) { + *p = aes->aes_mbs_in_locale.s; + if (length != NULL) + *length = aes->aes_mbs_in_locale.length; + return (0); + } else if (errno == ENOMEM) + return (-1); + else + ret = -1; + } +#endif + + /* If there is not an MBS form but is a WCS form, try converting + * with the native locale to be used for translating it to specified + * character-set. */ + if ((aes->aes_set & AES_SET_MBS) == 0 && + (aes->aes_set & AES_SET_WCS) != 0) { + archive_string_empty(&(aes->aes_mbs)); + r = archive_string_append_from_wcs(&(aes->aes_mbs), + aes->aes_wcs.s, aes->aes_wcs.length); + if (r == 0) + aes->aes_set |= AES_SET_MBS; + else if (errno == ENOMEM) + return (-1); + else + ret = -1; + } + /* If we already have an MBS form, use it to be translated to + * specified character-set. */ + if (aes->aes_set & AES_SET_MBS) { + if (sc == NULL) { + /* Conversion is unneeded. */ + *p = aes->aes_mbs.s; + if (length != NULL) + *length = aes->aes_mbs.length; + return (0); + } + ret = archive_strncpy_l(&(aes->aes_mbs_in_locale), + aes->aes_mbs.s, aes->aes_mbs.length, sc); + *p = aes->aes_mbs_in_locale.s; + if (length != NULL) + *length = aes->aes_mbs_in_locale.length; + } else { + *p = NULL; + if (length != NULL) + *length = 0; + } + return (ret); +} + +int +archive_mstring_copy_mbs(struct archive_mstring *aes, const char *mbs) +{ + if (mbs == NULL) { + aes->aes_set = 0; + return (0); + } + return (archive_mstring_copy_mbs_len(aes, mbs, strlen(mbs))); +} + +int +archive_mstring_copy_mbs_len(struct archive_mstring *aes, const char *mbs, + size_t len) +{ + if (mbs == NULL) { + aes->aes_set = 0; + return (0); + } + aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */ + archive_strncpy(&(aes->aes_mbs), mbs, len); + archive_string_empty(&(aes->aes_utf8)); + archive_wstring_empty(&(aes->aes_wcs)); + return (0); +} + +int +archive_mstring_copy_wcs(struct archive_mstring *aes, const wchar_t *wcs) +{ + return archive_mstring_copy_wcs_len(aes, wcs, + wcs == NULL ? 0 : wcslen(wcs)); +} + +int +archive_mstring_copy_utf8(struct archive_mstring *aes, const char *utf8) +{ + if (utf8 == NULL) { + aes->aes_set = 0; + return (0); + } + aes->aes_set = AES_SET_UTF8; + archive_string_empty(&(aes->aes_mbs)); + archive_string_empty(&(aes->aes_wcs)); + archive_strncpy(&(aes->aes_utf8), utf8, strlen(utf8)); + return (int)strlen(utf8); +} + +int +archive_mstring_copy_wcs_len(struct archive_mstring *aes, const wchar_t *wcs, + size_t len) +{ + if (wcs == NULL) { + aes->aes_set = 0; + return (0); + } + aes->aes_set = AES_SET_WCS; /* Only WCS form set. */ + archive_string_empty(&(aes->aes_mbs)); + archive_string_empty(&(aes->aes_utf8)); + archive_wstrncpy(&(aes->aes_wcs), wcs, len); + return (0); +} + +int +archive_mstring_copy_mbs_len_l(struct archive_mstring *aes, + const char *mbs, size_t len, struct archive_string_conv *sc) +{ + int r; + + if (mbs == NULL) { + aes->aes_set = 0; + return (0); + } + archive_string_empty(&(aes->aes_mbs)); + archive_wstring_empty(&(aes->aes_wcs)); + archive_string_empty(&(aes->aes_utf8)); +#if defined(_WIN32) && !defined(__CYGWIN__) + /* + * Internationalization programming on Windows must use Wide + * characters because Windows platform cannot make locale UTF-8. + */ + if (sc == NULL) { + if (archive_string_append(&(aes->aes_mbs), + mbs, mbsnbytes(mbs, len)) == NULL) { + aes->aes_set = 0; + r = -1; + } else { + aes->aes_set = AES_SET_MBS; + r = 0; + } +#if defined(HAVE_ICONV) + } else if (sc != NULL && sc->cd_w != (iconv_t)-1) { + /* + * This case happens only when MultiByteToWideChar() cannot + * handle sc->from_cp, and we have to iconv in order to + * translate character-set to wchar_t,UTF-16. + */ + iconv_t cd = sc->cd; + unsigned from_cp; + int flag; + + /* + * Translate multi-bytes from some character-set to UTF-8. + */ + sc->cd = sc->cd_w; + r = archive_strncpy_l(&(aes->aes_utf8), mbs, len, sc); + sc->cd = cd; + if (r != 0) { + aes->aes_set = 0; + return (r); + } + aes->aes_set = AES_SET_UTF8; + + /* + * Append the UTF-8 string into wstring. + */ + flag = sc->flag; + sc->flag &= ~(SCONV_NORMALIZATION_C + | SCONV_TO_UTF16| SCONV_FROM_UTF16); + from_cp = sc->from_cp; + sc->from_cp = CP_UTF8; + r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs), + aes->aes_utf8.s, aes->aes_utf8.length, sc); + sc->flag = flag; + sc->from_cp = from_cp; + if (r == 0) + aes->aes_set |= AES_SET_WCS; +#endif + } else { + r = archive_wstring_append_from_mbs_in_codepage( + &(aes->aes_wcs), mbs, len, sc); + if (r == 0) + aes->aes_set = AES_SET_WCS; + else + aes->aes_set = 0; + } +#else + r = archive_strncpy_l(&(aes->aes_mbs), mbs, len, sc); + if (r == 0) + aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */ + else + aes->aes_set = 0; +#endif + return (r); +} + +/* + * The 'update' form tries to proactively update all forms of + * this string (WCS and MBS) and returns an error if any of + * them fail. This is used by the 'pax' handler, for instance, + * to detect and report character-conversion failures early while + * still allowing clients to get potentially useful values from + * the more tolerant lazy conversions. (get_mbs and get_wcs will + * strive to give the user something useful, so you can get hopefully + * usable values even if some of the character conversions are failing.) + */ +int +archive_mstring_update_utf8(struct archive *a, struct archive_mstring *aes, + const char *utf8) +{ + struct archive_string_conv *sc; + int r; + + if (utf8 == NULL) { + aes->aes_set = 0; + return (0); /* Succeeded in clearing everything. */ + } + + /* Save the UTF8 string. */ + archive_strcpy(&(aes->aes_utf8), utf8); + + /* Empty the mbs and wcs strings. */ + archive_string_empty(&(aes->aes_mbs)); + archive_wstring_empty(&(aes->aes_wcs)); + + aes->aes_set = AES_SET_UTF8; /* Only UTF8 is set now. */ + + /* Try converting UTF-8 to MBS, return false on failure. */ + sc = archive_string_conversion_from_charset(a, "UTF-8", 1); + if (sc == NULL) + return (-1);/* Couldn't allocate memory for sc. */ + r = archive_strcpy_l(&(aes->aes_mbs), utf8, sc); + if (a == NULL) + free_sconv_object(sc); + if (r != 0) + return (-1); + aes->aes_set = AES_SET_UTF8 | AES_SET_MBS; /* Both UTF8 and MBS set. */ + + /* Try converting MBS to WCS, return false on failure. */ + if (archive_wstring_append_from_mbs(&(aes->aes_wcs), aes->aes_mbs.s, + aes->aes_mbs.length)) + return (-1); + aes->aes_set = AES_SET_UTF8 | AES_SET_WCS | AES_SET_MBS; + + /* All conversions succeeded. */ + return (0); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_string.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_string.h new file mode 100644 index 0000000000..27e1ad69c5 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_string.h @@ -0,0 +1,243 @@ +/*- + * Copyright (c) 2003-2010 Tim Kientzle + * 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(S) ``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(S) 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. + * + * $FreeBSD: head/lib/libarchive/archive_string.h 201092 2009-12-28 02:26:06Z kientzle $ + * + */ + +#ifndef ARCHIVE_STRING_H_INCLUDED +#define ARCHIVE_STRING_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#ifndef __LIBARCHIVE_TEST +#error This header is only to be used internally to libarchive. +#endif +#endif + +#include <stdarg.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> /* required for wchar_t on some systems */ +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_WCHAR_H +#include <wchar.h> +#endif + +#include "archive.h" + +/* + * Basic resizable/reusable string support similar to Java's "StringBuffer." + * + * Unlike sbuf(9), the buffers here are fully reusable and track the + * length throughout. + */ + +struct archive_string { + char *s; /* Pointer to the storage */ + size_t length; /* Length of 's' in characters */ + size_t buffer_length; /* Length of malloc-ed storage in bytes. */ +}; + +struct archive_wstring { + wchar_t *s; /* Pointer to the storage */ + size_t length; /* Length of 's' in characters */ + size_t buffer_length; /* Length of malloc-ed storage in bytes. */ +}; + +struct archive_string_conv; + +/* Initialize an archive_string object on the stack or elsewhere. */ +#define archive_string_init(a) \ + do { (a)->s = NULL; (a)->length = 0; (a)->buffer_length = 0; } while(0) + +/* Append a C char to an archive_string, resizing as necessary. */ +struct archive_string * +archive_strappend_char(struct archive_string *, char); + +/* Ditto for a wchar_t and an archive_wstring. */ +struct archive_wstring * +archive_wstrappend_wchar(struct archive_wstring *, wchar_t); + +/* Append a raw array to an archive_string, resizing as necessary */ +struct archive_string * +archive_array_append(struct archive_string *, const char *, size_t); + +/* Convert a Unicode string to current locale and append the result. */ +/* Returns -1 if conversion fails. */ +int +archive_string_append_from_wcs(struct archive_string *, const wchar_t *, size_t); + + +/* Create a string conversion object. + * Return NULL and set a error message if the conversion is not supported + * on the platform. */ +struct archive_string_conv * +archive_string_conversion_to_charset(struct archive *, const char *, int); +struct archive_string_conv * +archive_string_conversion_from_charset(struct archive *, const char *, int); +/* Create the default string conversion object for reading/writing an archive. + * Return NULL if the conversion is unneeded. + * Note: On non Windows platform this always returns NULL. + */ +struct archive_string_conv * +archive_string_default_conversion_for_read(struct archive *); +struct archive_string_conv * +archive_string_default_conversion_for_write(struct archive *); +/* Dispose of a string conversion object. */ +void +archive_string_conversion_free(struct archive *); +const char * +archive_string_conversion_charset_name(struct archive_string_conv *); +void +archive_string_conversion_set_opt(struct archive_string_conv *, int); +#define SCONV_SET_OPT_UTF8_LIBARCHIVE2X 1 +#define SCONV_SET_OPT_NORMALIZATION_C 2 +#define SCONV_SET_OPT_NORMALIZATION_D 4 + + +/* Copy one archive_string to another in locale conversion. + * Return -1 if conversion fails. */ +int +archive_strncpy_l(struct archive_string *, const void *, size_t, + struct archive_string_conv *); + +/* Copy one archive_string to another in locale conversion. + * Return -1 if conversion fails. */ +int +archive_strncat_l(struct archive_string *, const void *, size_t, + struct archive_string_conv *); + + +/* Copy one archive_string to another */ +#define archive_string_copy(dest, src) \ + ((dest)->length = 0, archive_string_concat((dest), (src))) +#define archive_wstring_copy(dest, src) \ + ((dest)->length = 0, archive_wstring_concat((dest), (src))) + +/* Concatenate one archive_string to another */ +void archive_string_concat(struct archive_string *dest, struct archive_string *src); +void archive_wstring_concat(struct archive_wstring *dest, struct archive_wstring *src); + +/* Ensure that the underlying buffer is at least as large as the request. */ +struct archive_string * +archive_string_ensure(struct archive_string *, size_t); +struct archive_wstring * +archive_wstring_ensure(struct archive_wstring *, size_t); + +/* Append C string, which may lack trailing \0. */ +/* The source is declared void * here because this gets used with + * "signed char *", "unsigned char *" and "char *" arguments. + * Declaring it "char *" as with some of the other functions just + * leads to a lot of extra casts. */ +struct archive_string * +archive_strncat(struct archive_string *, const void *, size_t); +struct archive_wstring * +archive_wstrncat(struct archive_wstring *, const wchar_t *, size_t); + +/* Append a C string to an archive_string, resizing as necessary. */ +struct archive_string * +archive_strcat(struct archive_string *, const void *); +struct archive_wstring * +archive_wstrcat(struct archive_wstring *, const wchar_t *); + +/* Copy a C string to an archive_string, resizing as necessary. */ +#define archive_strcpy(as,p) \ + archive_strncpy((as), (p), ((p) == NULL ? 0 : strlen(p))) +#define archive_wstrcpy(as,p) \ + archive_wstrncpy((as), (p), ((p) == NULL ? 0 : wcslen(p))) +#define archive_strcpy_l(as,p,lo) \ + archive_strncpy_l((as), (p), ((p) == NULL ? 0 : strlen(p)), (lo)) + +/* Copy a C string to an archive_string with limit, resizing as necessary. */ +#define archive_strncpy(as,p,l) \ + ((as)->length=0, archive_strncat((as), (p), (l))) +#define archive_wstrncpy(as,p,l) \ + ((as)->length = 0, archive_wstrncat((as), (p), (l))) + +/* Return length of string. */ +#define archive_strlen(a) ((a)->length) + +/* Set string length to zero. */ +#define archive_string_empty(a) ((a)->length = 0) +#define archive_wstring_empty(a) ((a)->length = 0) + +/* Release any allocated storage resources. */ +void archive_string_free(struct archive_string *); +void archive_wstring_free(struct archive_wstring *); + +/* Like 'vsprintf', but resizes the underlying string as necessary. */ +/* Note: This only implements a small subset of standard printf functionality. */ +void archive_string_vsprintf(struct archive_string *, const char *, + va_list) __LA_PRINTF(2, 0); +void archive_string_sprintf(struct archive_string *, const char *, ...) + __LA_PRINTF(2, 3); + +/* Translates from MBS to Unicode. */ +/* Returns non-zero if conversion failed in any way. */ +int archive_wstring_append_from_mbs(struct archive_wstring *dest, + const char *, size_t); + + +/* A "multistring" can hold Unicode, UTF8, or MBS versions of + * the string. If you set and read the same version, no translation + * is done. If you set and read different versions, the library + * will attempt to transparently convert. + */ +struct archive_mstring { + struct archive_string aes_mbs; + struct archive_string aes_utf8; + struct archive_wstring aes_wcs; + struct archive_string aes_mbs_in_locale; + /* Bitmap of which of the above are valid. Because we're lazy + * about malloc-ing and reusing the underlying storage, we + * can't rely on NULL pointers to indicate whether a string + * has been set. */ + int aes_set; +#define AES_SET_MBS 1 +#define AES_SET_UTF8 2 +#define AES_SET_WCS 4 +}; + +void archive_mstring_clean(struct archive_mstring *); +void archive_mstring_copy(struct archive_mstring *dest, struct archive_mstring *src); +int archive_mstring_get_mbs(struct archive *, struct archive_mstring *, const char **); +int archive_mstring_get_utf8(struct archive *, struct archive_mstring *, const char **); +int archive_mstring_get_wcs(struct archive *, struct archive_mstring *, const wchar_t **); +int archive_mstring_get_mbs_l(struct archive_mstring *, const char **, + size_t *, struct archive_string_conv *); +int archive_mstring_copy_mbs(struct archive_mstring *, const char *mbs); +int archive_mstring_copy_mbs_len(struct archive_mstring *, const char *mbs, + size_t); +int archive_mstring_copy_utf8(struct archive_mstring *, const char *utf8); +int archive_mstring_copy_wcs(struct archive_mstring *, const wchar_t *wcs); +int archive_mstring_copy_wcs_len(struct archive_mstring *, + const wchar_t *wcs, size_t); +int archive_mstring_copy_mbs_len_l(struct archive_mstring *, + const char *mbs, size_t, struct archive_string_conv *); +int archive_mstring_update_utf8(struct archive *, struct archive_mstring *aes, const char *utf8); + + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_string_composition.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_string_composition.h new file mode 100644 index 0000000000..d0ac340961 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_string_composition.h @@ -0,0 +1,2292 @@ +/*- + * Copyright (c) 2011-2012 libarchive Project + * 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(S) 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(S) 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. + * + * $FreeBSD$ + * + */ + +/* + * ATTENTION! + * This file is generated by build/utils/gen_archive_string_composition_h.sh + * from http://unicode.org/Public/6.0.0/ucd/UnicodeData.txt + * + * See also http://unicode.org/report/tr15/ + */ + +#ifndef ARCHIVE_STRING_COMPOSITION_H_INCLUDED +#define ARCHIVE_STRING_COMPOSITION_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +struct unicode_composition_table { + uint32_t cp1; + uint32_t cp2; + uint32_t nfc; +}; + +static const struct unicode_composition_table u_composition_table[] = { + { 0x0003C , 0x00338 , 0x0226E }, + { 0x0003D , 0x00338 , 0x02260 }, + { 0x0003E , 0x00338 , 0x0226F }, + { 0x00041 , 0x00300 , 0x000C0 }, + { 0x00041 , 0x00301 , 0x000C1 }, + { 0x00041 , 0x00302 , 0x000C2 }, + { 0x00041 , 0x00303 , 0x000C3 }, + { 0x00041 , 0x00304 , 0x00100 }, + { 0x00041 , 0x00306 , 0x00102 }, + { 0x00041 , 0x00307 , 0x00226 }, + { 0x00041 , 0x00308 , 0x000C4 }, + { 0x00041 , 0x00309 , 0x01EA2 }, + { 0x00041 , 0x0030A , 0x000C5 }, + { 0x00041 , 0x0030C , 0x001CD }, + { 0x00041 , 0x0030F , 0x00200 }, + { 0x00041 , 0x00311 , 0x00202 }, + { 0x00041 , 0x00323 , 0x01EA0 }, + { 0x00041 , 0x00325 , 0x01E00 }, + { 0x00041 , 0x00328 , 0x00104 }, + { 0x00042 , 0x00307 , 0x01E02 }, + { 0x00042 , 0x00323 , 0x01E04 }, + { 0x00042 , 0x00331 , 0x01E06 }, + { 0x00043 , 0x00301 , 0x00106 }, + { 0x00043 , 0x00302 , 0x00108 }, + { 0x00043 , 0x00307 , 0x0010A }, + { 0x00043 , 0x0030C , 0x0010C }, + { 0x00043 , 0x00327 , 0x000C7 }, + { 0x00044 , 0x00307 , 0x01E0A }, + { 0x00044 , 0x0030C , 0x0010E }, + { 0x00044 , 0x00323 , 0x01E0C }, + { 0x00044 , 0x00327 , 0x01E10 }, + { 0x00044 , 0x0032D , 0x01E12 }, + { 0x00044 , 0x00331 , 0x01E0E }, + { 0x00045 , 0x00300 , 0x000C8 }, + { 0x00045 , 0x00301 , 0x000C9 }, + { 0x00045 , 0x00302 , 0x000CA }, + { 0x00045 , 0x00303 , 0x01EBC }, + { 0x00045 , 0x00304 , 0x00112 }, + { 0x00045 , 0x00306 , 0x00114 }, + { 0x00045 , 0x00307 , 0x00116 }, + { 0x00045 , 0x00308 , 0x000CB }, + { 0x00045 , 0x00309 , 0x01EBA }, + { 0x00045 , 0x0030C , 0x0011A }, + { 0x00045 , 0x0030F , 0x00204 }, + { 0x00045 , 0x00311 , 0x00206 }, + { 0x00045 , 0x00323 , 0x01EB8 }, + { 0x00045 , 0x00327 , 0x00228 }, + { 0x00045 , 0x00328 , 0x00118 }, + { 0x00045 , 0x0032D , 0x01E18 }, + { 0x00045 , 0x00330 , 0x01E1A }, + { 0x00046 , 0x00307 , 0x01E1E }, + { 0x00047 , 0x00301 , 0x001F4 }, + { 0x00047 , 0x00302 , 0x0011C }, + { 0x00047 , 0x00304 , 0x01E20 }, + { 0x00047 , 0x00306 , 0x0011E }, + { 0x00047 , 0x00307 , 0x00120 }, + { 0x00047 , 0x0030C , 0x001E6 }, + { 0x00047 , 0x00327 , 0x00122 }, + { 0x00048 , 0x00302 , 0x00124 }, + { 0x00048 , 0x00307 , 0x01E22 }, + { 0x00048 , 0x00308 , 0x01E26 }, + { 0x00048 , 0x0030C , 0x0021E }, + { 0x00048 , 0x00323 , 0x01E24 }, + { 0x00048 , 0x00327 , 0x01E28 }, + { 0x00048 , 0x0032E , 0x01E2A }, + { 0x00049 , 0x00300 , 0x000CC }, + { 0x00049 , 0x00301 , 0x000CD }, + { 0x00049 , 0x00302 , 0x000CE }, + { 0x00049 , 0x00303 , 0x00128 }, + { 0x00049 , 0x00304 , 0x0012A }, + { 0x00049 , 0x00306 , 0x0012C }, + { 0x00049 , 0x00307 , 0x00130 }, + { 0x00049 , 0x00308 , 0x000CF }, + { 0x00049 , 0x00309 , 0x01EC8 }, + { 0x00049 , 0x0030C , 0x001CF }, + { 0x00049 , 0x0030F , 0x00208 }, + { 0x00049 , 0x00311 , 0x0020A }, + { 0x00049 , 0x00323 , 0x01ECA }, + { 0x00049 , 0x00328 , 0x0012E }, + { 0x00049 , 0x00330 , 0x01E2C }, + { 0x0004A , 0x00302 , 0x00134 }, + { 0x0004B , 0x00301 , 0x01E30 }, + { 0x0004B , 0x0030C , 0x001E8 }, + { 0x0004B , 0x00323 , 0x01E32 }, + { 0x0004B , 0x00327 , 0x00136 }, + { 0x0004B , 0x00331 , 0x01E34 }, + { 0x0004C , 0x00301 , 0x00139 }, + { 0x0004C , 0x0030C , 0x0013D }, + { 0x0004C , 0x00323 , 0x01E36 }, + { 0x0004C , 0x00327 , 0x0013B }, + { 0x0004C , 0x0032D , 0x01E3C }, + { 0x0004C , 0x00331 , 0x01E3A }, + { 0x0004D , 0x00301 , 0x01E3E }, + { 0x0004D , 0x00307 , 0x01E40 }, + { 0x0004D , 0x00323 , 0x01E42 }, + { 0x0004E , 0x00300 , 0x001F8 }, + { 0x0004E , 0x00301 , 0x00143 }, + { 0x0004E , 0x00303 , 0x000D1 }, + { 0x0004E , 0x00307 , 0x01E44 }, + { 0x0004E , 0x0030C , 0x00147 }, + { 0x0004E , 0x00323 , 0x01E46 }, + { 0x0004E , 0x00327 , 0x00145 }, + { 0x0004E , 0x0032D , 0x01E4A }, + { 0x0004E , 0x00331 , 0x01E48 }, + { 0x0004F , 0x00300 , 0x000D2 }, + { 0x0004F , 0x00301 , 0x000D3 }, + { 0x0004F , 0x00302 , 0x000D4 }, + { 0x0004F , 0x00303 , 0x000D5 }, + { 0x0004F , 0x00304 , 0x0014C }, + { 0x0004F , 0x00306 , 0x0014E }, + { 0x0004F , 0x00307 , 0x0022E }, + { 0x0004F , 0x00308 , 0x000D6 }, + { 0x0004F , 0x00309 , 0x01ECE }, + { 0x0004F , 0x0030B , 0x00150 }, + { 0x0004F , 0x0030C , 0x001D1 }, + { 0x0004F , 0x0030F , 0x0020C }, + { 0x0004F , 0x00311 , 0x0020E }, + { 0x0004F , 0x0031B , 0x001A0 }, + { 0x0004F , 0x00323 , 0x01ECC }, + { 0x0004F , 0x00328 , 0x001EA }, + { 0x00050 , 0x00301 , 0x01E54 }, + { 0x00050 , 0x00307 , 0x01E56 }, + { 0x00052 , 0x00301 , 0x00154 }, + { 0x00052 , 0x00307 , 0x01E58 }, + { 0x00052 , 0x0030C , 0x00158 }, + { 0x00052 , 0x0030F , 0x00210 }, + { 0x00052 , 0x00311 , 0x00212 }, + { 0x00052 , 0x00323 , 0x01E5A }, + { 0x00052 , 0x00327 , 0x00156 }, + { 0x00052 , 0x00331 , 0x01E5E }, + { 0x00053 , 0x00301 , 0x0015A }, + { 0x00053 , 0x00302 , 0x0015C }, + { 0x00053 , 0x00307 , 0x01E60 }, + { 0x00053 , 0x0030C , 0x00160 }, + { 0x00053 , 0x00323 , 0x01E62 }, + { 0x00053 , 0x00326 , 0x00218 }, + { 0x00053 , 0x00327 , 0x0015E }, + { 0x00054 , 0x00307 , 0x01E6A }, + { 0x00054 , 0x0030C , 0x00164 }, + { 0x00054 , 0x00323 , 0x01E6C }, + { 0x00054 , 0x00326 , 0x0021A }, + { 0x00054 , 0x00327 , 0x00162 }, + { 0x00054 , 0x0032D , 0x01E70 }, + { 0x00054 , 0x00331 , 0x01E6E }, + { 0x00055 , 0x00300 , 0x000D9 }, + { 0x00055 , 0x00301 , 0x000DA }, + { 0x00055 , 0x00302 , 0x000DB }, + { 0x00055 , 0x00303 , 0x00168 }, + { 0x00055 , 0x00304 , 0x0016A }, + { 0x00055 , 0x00306 , 0x0016C }, + { 0x00055 , 0x00308 , 0x000DC }, + { 0x00055 , 0x00309 , 0x01EE6 }, + { 0x00055 , 0x0030A , 0x0016E }, + { 0x00055 , 0x0030B , 0x00170 }, + { 0x00055 , 0x0030C , 0x001D3 }, + { 0x00055 , 0x0030F , 0x00214 }, + { 0x00055 , 0x00311 , 0x00216 }, + { 0x00055 , 0x0031B , 0x001AF }, + { 0x00055 , 0x00323 , 0x01EE4 }, + { 0x00055 , 0x00324 , 0x01E72 }, + { 0x00055 , 0x00328 , 0x00172 }, + { 0x00055 , 0x0032D , 0x01E76 }, + { 0x00055 , 0x00330 , 0x01E74 }, + { 0x00056 , 0x00303 , 0x01E7C }, + { 0x00056 , 0x00323 , 0x01E7E }, + { 0x00057 , 0x00300 , 0x01E80 }, + { 0x00057 , 0x00301 , 0x01E82 }, + { 0x00057 , 0x00302 , 0x00174 }, + { 0x00057 , 0x00307 , 0x01E86 }, + { 0x00057 , 0x00308 , 0x01E84 }, + { 0x00057 , 0x00323 , 0x01E88 }, + { 0x00058 , 0x00307 , 0x01E8A }, + { 0x00058 , 0x00308 , 0x01E8C }, + { 0x00059 , 0x00300 , 0x01EF2 }, + { 0x00059 , 0x00301 , 0x000DD }, + { 0x00059 , 0x00302 , 0x00176 }, + { 0x00059 , 0x00303 , 0x01EF8 }, + { 0x00059 , 0x00304 , 0x00232 }, + { 0x00059 , 0x00307 , 0x01E8E }, + { 0x00059 , 0x00308 , 0x00178 }, + { 0x00059 , 0x00309 , 0x01EF6 }, + { 0x00059 , 0x00323 , 0x01EF4 }, + { 0x0005A , 0x00301 , 0x00179 }, + { 0x0005A , 0x00302 , 0x01E90 }, + { 0x0005A , 0x00307 , 0x0017B }, + { 0x0005A , 0x0030C , 0x0017D }, + { 0x0005A , 0x00323 , 0x01E92 }, + { 0x0005A , 0x00331 , 0x01E94 }, + { 0x00061 , 0x00300 , 0x000E0 }, + { 0x00061 , 0x00301 , 0x000E1 }, + { 0x00061 , 0x00302 , 0x000E2 }, + { 0x00061 , 0x00303 , 0x000E3 }, + { 0x00061 , 0x00304 , 0x00101 }, + { 0x00061 , 0x00306 , 0x00103 }, + { 0x00061 , 0x00307 , 0x00227 }, + { 0x00061 , 0x00308 , 0x000E4 }, + { 0x00061 , 0x00309 , 0x01EA3 }, + { 0x00061 , 0x0030A , 0x000E5 }, + { 0x00061 , 0x0030C , 0x001CE }, + { 0x00061 , 0x0030F , 0x00201 }, + { 0x00061 , 0x00311 , 0x00203 }, + { 0x00061 , 0x00323 , 0x01EA1 }, + { 0x00061 , 0x00325 , 0x01E01 }, + { 0x00061 , 0x00328 , 0x00105 }, + { 0x00062 , 0x00307 , 0x01E03 }, + { 0x00062 , 0x00323 , 0x01E05 }, + { 0x00062 , 0x00331 , 0x01E07 }, + { 0x00063 , 0x00301 , 0x00107 }, + { 0x00063 , 0x00302 , 0x00109 }, + { 0x00063 , 0x00307 , 0x0010B }, + { 0x00063 , 0x0030C , 0x0010D }, + { 0x00063 , 0x00327 , 0x000E7 }, + { 0x00064 , 0x00307 , 0x01E0B }, + { 0x00064 , 0x0030C , 0x0010F }, + { 0x00064 , 0x00323 , 0x01E0D }, + { 0x00064 , 0x00327 , 0x01E11 }, + { 0x00064 , 0x0032D , 0x01E13 }, + { 0x00064 , 0x00331 , 0x01E0F }, + { 0x00065 , 0x00300 , 0x000E8 }, + { 0x00065 , 0x00301 , 0x000E9 }, + { 0x00065 , 0x00302 , 0x000EA }, + { 0x00065 , 0x00303 , 0x01EBD }, + { 0x00065 , 0x00304 , 0x00113 }, + { 0x00065 , 0x00306 , 0x00115 }, + { 0x00065 , 0x00307 , 0x00117 }, + { 0x00065 , 0x00308 , 0x000EB }, + { 0x00065 , 0x00309 , 0x01EBB }, + { 0x00065 , 0x0030C , 0x0011B }, + { 0x00065 , 0x0030F , 0x00205 }, + { 0x00065 , 0x00311 , 0x00207 }, + { 0x00065 , 0x00323 , 0x01EB9 }, + { 0x00065 , 0x00327 , 0x00229 }, + { 0x00065 , 0x00328 , 0x00119 }, + { 0x00065 , 0x0032D , 0x01E19 }, + { 0x00065 , 0x00330 , 0x01E1B }, + { 0x00066 , 0x00307 , 0x01E1F }, + { 0x00067 , 0x00301 , 0x001F5 }, + { 0x00067 , 0x00302 , 0x0011D }, + { 0x00067 , 0x00304 , 0x01E21 }, + { 0x00067 , 0x00306 , 0x0011F }, + { 0x00067 , 0x00307 , 0x00121 }, + { 0x00067 , 0x0030C , 0x001E7 }, + { 0x00067 , 0x00327 , 0x00123 }, + { 0x00068 , 0x00302 , 0x00125 }, + { 0x00068 , 0x00307 , 0x01E23 }, + { 0x00068 , 0x00308 , 0x01E27 }, + { 0x00068 , 0x0030C , 0x0021F }, + { 0x00068 , 0x00323 , 0x01E25 }, + { 0x00068 , 0x00327 , 0x01E29 }, + { 0x00068 , 0x0032E , 0x01E2B }, + { 0x00068 , 0x00331 , 0x01E96 }, + { 0x00069 , 0x00300 , 0x000EC }, + { 0x00069 , 0x00301 , 0x000ED }, + { 0x00069 , 0x00302 , 0x000EE }, + { 0x00069 , 0x00303 , 0x00129 }, + { 0x00069 , 0x00304 , 0x0012B }, + { 0x00069 , 0x00306 , 0x0012D }, + { 0x00069 , 0x00308 , 0x000EF }, + { 0x00069 , 0x00309 , 0x01EC9 }, + { 0x00069 , 0x0030C , 0x001D0 }, + { 0x00069 , 0x0030F , 0x00209 }, + { 0x00069 , 0x00311 , 0x0020B }, + { 0x00069 , 0x00323 , 0x01ECB }, + { 0x00069 , 0x00328 , 0x0012F }, + { 0x00069 , 0x00330 , 0x01E2D }, + { 0x0006A , 0x00302 , 0x00135 }, + { 0x0006A , 0x0030C , 0x001F0 }, + { 0x0006B , 0x00301 , 0x01E31 }, + { 0x0006B , 0x0030C , 0x001E9 }, + { 0x0006B , 0x00323 , 0x01E33 }, + { 0x0006B , 0x00327 , 0x00137 }, + { 0x0006B , 0x00331 , 0x01E35 }, + { 0x0006C , 0x00301 , 0x0013A }, + { 0x0006C , 0x0030C , 0x0013E }, + { 0x0006C , 0x00323 , 0x01E37 }, + { 0x0006C , 0x00327 , 0x0013C }, + { 0x0006C , 0x0032D , 0x01E3D }, + { 0x0006C , 0x00331 , 0x01E3B }, + { 0x0006D , 0x00301 , 0x01E3F }, + { 0x0006D , 0x00307 , 0x01E41 }, + { 0x0006D , 0x00323 , 0x01E43 }, + { 0x0006E , 0x00300 , 0x001F9 }, + { 0x0006E , 0x00301 , 0x00144 }, + { 0x0006E , 0x00303 , 0x000F1 }, + { 0x0006E , 0x00307 , 0x01E45 }, + { 0x0006E , 0x0030C , 0x00148 }, + { 0x0006E , 0x00323 , 0x01E47 }, + { 0x0006E , 0x00327 , 0x00146 }, + { 0x0006E , 0x0032D , 0x01E4B }, + { 0x0006E , 0x00331 , 0x01E49 }, + { 0x0006F , 0x00300 , 0x000F2 }, + { 0x0006F , 0x00301 , 0x000F3 }, + { 0x0006F , 0x00302 , 0x000F4 }, + { 0x0006F , 0x00303 , 0x000F5 }, + { 0x0006F , 0x00304 , 0x0014D }, + { 0x0006F , 0x00306 , 0x0014F }, + { 0x0006F , 0x00307 , 0x0022F }, + { 0x0006F , 0x00308 , 0x000F6 }, + { 0x0006F , 0x00309 , 0x01ECF }, + { 0x0006F , 0x0030B , 0x00151 }, + { 0x0006F , 0x0030C , 0x001D2 }, + { 0x0006F , 0x0030F , 0x0020D }, + { 0x0006F , 0x00311 , 0x0020F }, + { 0x0006F , 0x0031B , 0x001A1 }, + { 0x0006F , 0x00323 , 0x01ECD }, + { 0x0006F , 0x00328 , 0x001EB }, + { 0x00070 , 0x00301 , 0x01E55 }, + { 0x00070 , 0x00307 , 0x01E57 }, + { 0x00072 , 0x00301 , 0x00155 }, + { 0x00072 , 0x00307 , 0x01E59 }, + { 0x00072 , 0x0030C , 0x00159 }, + { 0x00072 , 0x0030F , 0x00211 }, + { 0x00072 , 0x00311 , 0x00213 }, + { 0x00072 , 0x00323 , 0x01E5B }, + { 0x00072 , 0x00327 , 0x00157 }, + { 0x00072 , 0x00331 , 0x01E5F }, + { 0x00073 , 0x00301 , 0x0015B }, + { 0x00073 , 0x00302 , 0x0015D }, + { 0x00073 , 0x00307 , 0x01E61 }, + { 0x00073 , 0x0030C , 0x00161 }, + { 0x00073 , 0x00323 , 0x01E63 }, + { 0x00073 , 0x00326 , 0x00219 }, + { 0x00073 , 0x00327 , 0x0015F }, + { 0x00074 , 0x00307 , 0x01E6B }, + { 0x00074 , 0x00308 , 0x01E97 }, + { 0x00074 , 0x0030C , 0x00165 }, + { 0x00074 , 0x00323 , 0x01E6D }, + { 0x00074 , 0x00326 , 0x0021B }, + { 0x00074 , 0x00327 , 0x00163 }, + { 0x00074 , 0x0032D , 0x01E71 }, + { 0x00074 , 0x00331 , 0x01E6F }, + { 0x00075 , 0x00300 , 0x000F9 }, + { 0x00075 , 0x00301 , 0x000FA }, + { 0x00075 , 0x00302 , 0x000FB }, + { 0x00075 , 0x00303 , 0x00169 }, + { 0x00075 , 0x00304 , 0x0016B }, + { 0x00075 , 0x00306 , 0x0016D }, + { 0x00075 , 0x00308 , 0x000FC }, + { 0x00075 , 0x00309 , 0x01EE7 }, + { 0x00075 , 0x0030A , 0x0016F }, + { 0x00075 , 0x0030B , 0x00171 }, + { 0x00075 , 0x0030C , 0x001D4 }, + { 0x00075 , 0x0030F , 0x00215 }, + { 0x00075 , 0x00311 , 0x00217 }, + { 0x00075 , 0x0031B , 0x001B0 }, + { 0x00075 , 0x00323 , 0x01EE5 }, + { 0x00075 , 0x00324 , 0x01E73 }, + { 0x00075 , 0x00328 , 0x00173 }, + { 0x00075 , 0x0032D , 0x01E77 }, + { 0x00075 , 0x00330 , 0x01E75 }, + { 0x00076 , 0x00303 , 0x01E7D }, + { 0x00076 , 0x00323 , 0x01E7F }, + { 0x00077 , 0x00300 , 0x01E81 }, + { 0x00077 , 0x00301 , 0x01E83 }, + { 0x00077 , 0x00302 , 0x00175 }, + { 0x00077 , 0x00307 , 0x01E87 }, + { 0x00077 , 0x00308 , 0x01E85 }, + { 0x00077 , 0x0030A , 0x01E98 }, + { 0x00077 , 0x00323 , 0x01E89 }, + { 0x00078 , 0x00307 , 0x01E8B }, + { 0x00078 , 0x00308 , 0x01E8D }, + { 0x00079 , 0x00300 , 0x01EF3 }, + { 0x00079 , 0x00301 , 0x000FD }, + { 0x00079 , 0x00302 , 0x00177 }, + { 0x00079 , 0x00303 , 0x01EF9 }, + { 0x00079 , 0x00304 , 0x00233 }, + { 0x00079 , 0x00307 , 0x01E8F }, + { 0x00079 , 0x00308 , 0x000FF }, + { 0x00079 , 0x00309 , 0x01EF7 }, + { 0x00079 , 0x0030A , 0x01E99 }, + { 0x00079 , 0x00323 , 0x01EF5 }, + { 0x0007A , 0x00301 , 0x0017A }, + { 0x0007A , 0x00302 , 0x01E91 }, + { 0x0007A , 0x00307 , 0x0017C }, + { 0x0007A , 0x0030C , 0x0017E }, + { 0x0007A , 0x00323 , 0x01E93 }, + { 0x0007A , 0x00331 , 0x01E95 }, + { 0x000A8 , 0x00300 , 0x01FED }, + { 0x000A8 , 0x00301 , 0x00385 }, + { 0x000A8 , 0x00342 , 0x01FC1 }, + { 0x000C2 , 0x00300 , 0x01EA6 }, + { 0x000C2 , 0x00301 , 0x01EA4 }, + { 0x000C2 , 0x00303 , 0x01EAA }, + { 0x000C2 , 0x00309 , 0x01EA8 }, + { 0x000C4 , 0x00304 , 0x001DE }, + { 0x000C5 , 0x00301 , 0x001FA }, + { 0x000C6 , 0x00301 , 0x001FC }, + { 0x000C6 , 0x00304 , 0x001E2 }, + { 0x000C7 , 0x00301 , 0x01E08 }, + { 0x000CA , 0x00300 , 0x01EC0 }, + { 0x000CA , 0x00301 , 0x01EBE }, + { 0x000CA , 0x00303 , 0x01EC4 }, + { 0x000CA , 0x00309 , 0x01EC2 }, + { 0x000CF , 0x00301 , 0x01E2E }, + { 0x000D4 , 0x00300 , 0x01ED2 }, + { 0x000D4 , 0x00301 , 0x01ED0 }, + { 0x000D4 , 0x00303 , 0x01ED6 }, + { 0x000D4 , 0x00309 , 0x01ED4 }, + { 0x000D5 , 0x00301 , 0x01E4C }, + { 0x000D5 , 0x00304 , 0x0022C }, + { 0x000D5 , 0x00308 , 0x01E4E }, + { 0x000D6 , 0x00304 , 0x0022A }, + { 0x000D8 , 0x00301 , 0x001FE }, + { 0x000DC , 0x00300 , 0x001DB }, + { 0x000DC , 0x00301 , 0x001D7 }, + { 0x000DC , 0x00304 , 0x001D5 }, + { 0x000DC , 0x0030C , 0x001D9 }, + { 0x000E2 , 0x00300 , 0x01EA7 }, + { 0x000E2 , 0x00301 , 0x01EA5 }, + { 0x000E2 , 0x00303 , 0x01EAB }, + { 0x000E2 , 0x00309 , 0x01EA9 }, + { 0x000E4 , 0x00304 , 0x001DF }, + { 0x000E5 , 0x00301 , 0x001FB }, + { 0x000E6 , 0x00301 , 0x001FD }, + { 0x000E6 , 0x00304 , 0x001E3 }, + { 0x000E7 , 0x00301 , 0x01E09 }, + { 0x000EA , 0x00300 , 0x01EC1 }, + { 0x000EA , 0x00301 , 0x01EBF }, + { 0x000EA , 0x00303 , 0x01EC5 }, + { 0x000EA , 0x00309 , 0x01EC3 }, + { 0x000EF , 0x00301 , 0x01E2F }, + { 0x000F4 , 0x00300 , 0x01ED3 }, + { 0x000F4 , 0x00301 , 0x01ED1 }, + { 0x000F4 , 0x00303 , 0x01ED7 }, + { 0x000F4 , 0x00309 , 0x01ED5 }, + { 0x000F5 , 0x00301 , 0x01E4D }, + { 0x000F5 , 0x00304 , 0x0022D }, + { 0x000F5 , 0x00308 , 0x01E4F }, + { 0x000F6 , 0x00304 , 0x0022B }, + { 0x000F8 , 0x00301 , 0x001FF }, + { 0x000FC , 0x00300 , 0x001DC }, + { 0x000FC , 0x00301 , 0x001D8 }, + { 0x000FC , 0x00304 , 0x001D6 }, + { 0x000FC , 0x0030C , 0x001DA }, + { 0x00102 , 0x00300 , 0x01EB0 }, + { 0x00102 , 0x00301 , 0x01EAE }, + { 0x00102 , 0x00303 , 0x01EB4 }, + { 0x00102 , 0x00309 , 0x01EB2 }, + { 0x00103 , 0x00300 , 0x01EB1 }, + { 0x00103 , 0x00301 , 0x01EAF }, + { 0x00103 , 0x00303 , 0x01EB5 }, + { 0x00103 , 0x00309 , 0x01EB3 }, + { 0x00112 , 0x00300 , 0x01E14 }, + { 0x00112 , 0x00301 , 0x01E16 }, + { 0x00113 , 0x00300 , 0x01E15 }, + { 0x00113 , 0x00301 , 0x01E17 }, + { 0x0014C , 0x00300 , 0x01E50 }, + { 0x0014C , 0x00301 , 0x01E52 }, + { 0x0014D , 0x00300 , 0x01E51 }, + { 0x0014D , 0x00301 , 0x01E53 }, + { 0x0015A , 0x00307 , 0x01E64 }, + { 0x0015B , 0x00307 , 0x01E65 }, + { 0x00160 , 0x00307 , 0x01E66 }, + { 0x00161 , 0x00307 , 0x01E67 }, + { 0x00168 , 0x00301 , 0x01E78 }, + { 0x00169 , 0x00301 , 0x01E79 }, + { 0x0016A , 0x00308 , 0x01E7A }, + { 0x0016B , 0x00308 , 0x01E7B }, + { 0x0017F , 0x00307 , 0x01E9B }, + { 0x001A0 , 0x00300 , 0x01EDC }, + { 0x001A0 , 0x00301 , 0x01EDA }, + { 0x001A0 , 0x00303 , 0x01EE0 }, + { 0x001A0 , 0x00309 , 0x01EDE }, + { 0x001A0 , 0x00323 , 0x01EE2 }, + { 0x001A1 , 0x00300 , 0x01EDD }, + { 0x001A1 , 0x00301 , 0x01EDB }, + { 0x001A1 , 0x00303 , 0x01EE1 }, + { 0x001A1 , 0x00309 , 0x01EDF }, + { 0x001A1 , 0x00323 , 0x01EE3 }, + { 0x001AF , 0x00300 , 0x01EEA }, + { 0x001AF , 0x00301 , 0x01EE8 }, + { 0x001AF , 0x00303 , 0x01EEE }, + { 0x001AF , 0x00309 , 0x01EEC }, + { 0x001AF , 0x00323 , 0x01EF0 }, + { 0x001B0 , 0x00300 , 0x01EEB }, + { 0x001B0 , 0x00301 , 0x01EE9 }, + { 0x001B0 , 0x00303 , 0x01EEF }, + { 0x001B0 , 0x00309 , 0x01EED }, + { 0x001B0 , 0x00323 , 0x01EF1 }, + { 0x001B7 , 0x0030C , 0x001EE }, + { 0x001EA , 0x00304 , 0x001EC }, + { 0x001EB , 0x00304 , 0x001ED }, + { 0x00226 , 0x00304 , 0x001E0 }, + { 0x00227 , 0x00304 , 0x001E1 }, + { 0x00228 , 0x00306 , 0x01E1C }, + { 0x00229 , 0x00306 , 0x01E1D }, + { 0x0022E , 0x00304 , 0x00230 }, + { 0x0022F , 0x00304 , 0x00231 }, + { 0x00292 , 0x0030C , 0x001EF }, + { 0x00391 , 0x00300 , 0x01FBA }, + { 0x00391 , 0x00301 , 0x00386 }, + { 0x00391 , 0x00304 , 0x01FB9 }, + { 0x00391 , 0x00306 , 0x01FB8 }, + { 0x00391 , 0x00313 , 0x01F08 }, + { 0x00391 , 0x00314 , 0x01F09 }, + { 0x00391 , 0x00345 , 0x01FBC }, + { 0x00395 , 0x00300 , 0x01FC8 }, + { 0x00395 , 0x00301 , 0x00388 }, + { 0x00395 , 0x00313 , 0x01F18 }, + { 0x00395 , 0x00314 , 0x01F19 }, + { 0x00397 , 0x00300 , 0x01FCA }, + { 0x00397 , 0x00301 , 0x00389 }, + { 0x00397 , 0x00313 , 0x01F28 }, + { 0x00397 , 0x00314 , 0x01F29 }, + { 0x00397 , 0x00345 , 0x01FCC }, + { 0x00399 , 0x00300 , 0x01FDA }, + { 0x00399 , 0x00301 , 0x0038A }, + { 0x00399 , 0x00304 , 0x01FD9 }, + { 0x00399 , 0x00306 , 0x01FD8 }, + { 0x00399 , 0x00308 , 0x003AA }, + { 0x00399 , 0x00313 , 0x01F38 }, + { 0x00399 , 0x00314 , 0x01F39 }, + { 0x0039F , 0x00300 , 0x01FF8 }, + { 0x0039F , 0x00301 , 0x0038C }, + { 0x0039F , 0x00313 , 0x01F48 }, + { 0x0039F , 0x00314 , 0x01F49 }, + { 0x003A1 , 0x00314 , 0x01FEC }, + { 0x003A5 , 0x00300 , 0x01FEA }, + { 0x003A5 , 0x00301 , 0x0038E }, + { 0x003A5 , 0x00304 , 0x01FE9 }, + { 0x003A5 , 0x00306 , 0x01FE8 }, + { 0x003A5 , 0x00308 , 0x003AB }, + { 0x003A5 , 0x00314 , 0x01F59 }, + { 0x003A9 , 0x00300 , 0x01FFA }, + { 0x003A9 , 0x00301 , 0x0038F }, + { 0x003A9 , 0x00313 , 0x01F68 }, + { 0x003A9 , 0x00314 , 0x01F69 }, + { 0x003A9 , 0x00345 , 0x01FFC }, + { 0x003AC , 0x00345 , 0x01FB4 }, + { 0x003AE , 0x00345 , 0x01FC4 }, + { 0x003B1 , 0x00300 , 0x01F70 }, + { 0x003B1 , 0x00301 , 0x003AC }, + { 0x003B1 , 0x00304 , 0x01FB1 }, + { 0x003B1 , 0x00306 , 0x01FB0 }, + { 0x003B1 , 0x00313 , 0x01F00 }, + { 0x003B1 , 0x00314 , 0x01F01 }, + { 0x003B1 , 0x00342 , 0x01FB6 }, + { 0x003B1 , 0x00345 , 0x01FB3 }, + { 0x003B5 , 0x00300 , 0x01F72 }, + { 0x003B5 , 0x00301 , 0x003AD }, + { 0x003B5 , 0x00313 , 0x01F10 }, + { 0x003B5 , 0x00314 , 0x01F11 }, + { 0x003B7 , 0x00300 , 0x01F74 }, + { 0x003B7 , 0x00301 , 0x003AE }, + { 0x003B7 , 0x00313 , 0x01F20 }, + { 0x003B7 , 0x00314 , 0x01F21 }, + { 0x003B7 , 0x00342 , 0x01FC6 }, + { 0x003B7 , 0x00345 , 0x01FC3 }, + { 0x003B9 , 0x00300 , 0x01F76 }, + { 0x003B9 , 0x00301 , 0x003AF }, + { 0x003B9 , 0x00304 , 0x01FD1 }, + { 0x003B9 , 0x00306 , 0x01FD0 }, + { 0x003B9 , 0x00308 , 0x003CA }, + { 0x003B9 , 0x00313 , 0x01F30 }, + { 0x003B9 , 0x00314 , 0x01F31 }, + { 0x003B9 , 0x00342 , 0x01FD6 }, + { 0x003BF , 0x00300 , 0x01F78 }, + { 0x003BF , 0x00301 , 0x003CC }, + { 0x003BF , 0x00313 , 0x01F40 }, + { 0x003BF , 0x00314 , 0x01F41 }, + { 0x003C1 , 0x00313 , 0x01FE4 }, + { 0x003C1 , 0x00314 , 0x01FE5 }, + { 0x003C5 , 0x00300 , 0x01F7A }, + { 0x003C5 , 0x00301 , 0x003CD }, + { 0x003C5 , 0x00304 , 0x01FE1 }, + { 0x003C5 , 0x00306 , 0x01FE0 }, + { 0x003C5 , 0x00308 , 0x003CB }, + { 0x003C5 , 0x00313 , 0x01F50 }, + { 0x003C5 , 0x00314 , 0x01F51 }, + { 0x003C5 , 0x00342 , 0x01FE6 }, + { 0x003C9 , 0x00300 , 0x01F7C }, + { 0x003C9 , 0x00301 , 0x003CE }, + { 0x003C9 , 0x00313 , 0x01F60 }, + { 0x003C9 , 0x00314 , 0x01F61 }, + { 0x003C9 , 0x00342 , 0x01FF6 }, + { 0x003C9 , 0x00345 , 0x01FF3 }, + { 0x003CA , 0x00300 , 0x01FD2 }, + { 0x003CA , 0x00301 , 0x00390 }, + { 0x003CA , 0x00342 , 0x01FD7 }, + { 0x003CB , 0x00300 , 0x01FE2 }, + { 0x003CB , 0x00301 , 0x003B0 }, + { 0x003CB , 0x00342 , 0x01FE7 }, + { 0x003CE , 0x00345 , 0x01FF4 }, + { 0x003D2 , 0x00301 , 0x003D3 }, + { 0x003D2 , 0x00308 , 0x003D4 }, + { 0x00406 , 0x00308 , 0x00407 }, + { 0x00410 , 0x00306 , 0x004D0 }, + { 0x00410 , 0x00308 , 0x004D2 }, + { 0x00413 , 0x00301 , 0x00403 }, + { 0x00415 , 0x00300 , 0x00400 }, + { 0x00415 , 0x00306 , 0x004D6 }, + { 0x00415 , 0x00308 , 0x00401 }, + { 0x00416 , 0x00306 , 0x004C1 }, + { 0x00416 , 0x00308 , 0x004DC }, + { 0x00417 , 0x00308 , 0x004DE }, + { 0x00418 , 0x00300 , 0x0040D }, + { 0x00418 , 0x00304 , 0x004E2 }, + { 0x00418 , 0x00306 , 0x00419 }, + { 0x00418 , 0x00308 , 0x004E4 }, + { 0x0041A , 0x00301 , 0x0040C }, + { 0x0041E , 0x00308 , 0x004E6 }, + { 0x00423 , 0x00304 , 0x004EE }, + { 0x00423 , 0x00306 , 0x0040E }, + { 0x00423 , 0x00308 , 0x004F0 }, + { 0x00423 , 0x0030B , 0x004F2 }, + { 0x00427 , 0x00308 , 0x004F4 }, + { 0x0042B , 0x00308 , 0x004F8 }, + { 0x0042D , 0x00308 , 0x004EC }, + { 0x00430 , 0x00306 , 0x004D1 }, + { 0x00430 , 0x00308 , 0x004D3 }, + { 0x00433 , 0x00301 , 0x00453 }, + { 0x00435 , 0x00300 , 0x00450 }, + { 0x00435 , 0x00306 , 0x004D7 }, + { 0x00435 , 0x00308 , 0x00451 }, + { 0x00436 , 0x00306 , 0x004C2 }, + { 0x00436 , 0x00308 , 0x004DD }, + { 0x00437 , 0x00308 , 0x004DF }, + { 0x00438 , 0x00300 , 0x0045D }, + { 0x00438 , 0x00304 , 0x004E3 }, + { 0x00438 , 0x00306 , 0x00439 }, + { 0x00438 , 0x00308 , 0x004E5 }, + { 0x0043A , 0x00301 , 0x0045C }, + { 0x0043E , 0x00308 , 0x004E7 }, + { 0x00443 , 0x00304 , 0x004EF }, + { 0x00443 , 0x00306 , 0x0045E }, + { 0x00443 , 0x00308 , 0x004F1 }, + { 0x00443 , 0x0030B , 0x004F3 }, + { 0x00447 , 0x00308 , 0x004F5 }, + { 0x0044B , 0x00308 , 0x004F9 }, + { 0x0044D , 0x00308 , 0x004ED }, + { 0x00456 , 0x00308 , 0x00457 }, + { 0x00474 , 0x0030F , 0x00476 }, + { 0x00475 , 0x0030F , 0x00477 }, + { 0x004D8 , 0x00308 , 0x004DA }, + { 0x004D9 , 0x00308 , 0x004DB }, + { 0x004E8 , 0x00308 , 0x004EA }, + { 0x004E9 , 0x00308 , 0x004EB }, + { 0x00627 , 0x00653 , 0x00622 }, + { 0x00627 , 0x00654 , 0x00623 }, + { 0x00627 , 0x00655 , 0x00625 }, + { 0x00648 , 0x00654 , 0x00624 }, + { 0x0064A , 0x00654 , 0x00626 }, + { 0x006C1 , 0x00654 , 0x006C2 }, + { 0x006D2 , 0x00654 , 0x006D3 }, + { 0x006D5 , 0x00654 , 0x006C0 }, + { 0x00928 , 0x0093C , 0x00929 }, + { 0x00930 , 0x0093C , 0x00931 }, + { 0x00933 , 0x0093C , 0x00934 }, + { 0x009C7 , 0x009BE , 0x009CB }, + { 0x009C7 , 0x009D7 , 0x009CC }, + { 0x00B47 , 0x00B3E , 0x00B4B }, + { 0x00B47 , 0x00B56 , 0x00B48 }, + { 0x00B47 , 0x00B57 , 0x00B4C }, + { 0x00B92 , 0x00BD7 , 0x00B94 }, + { 0x00BC6 , 0x00BBE , 0x00BCA }, + { 0x00BC6 , 0x00BD7 , 0x00BCC }, + { 0x00BC7 , 0x00BBE , 0x00BCB }, + { 0x00C46 , 0x00C56 , 0x00C48 }, + { 0x00CBF , 0x00CD5 , 0x00CC0 }, + { 0x00CC6 , 0x00CC2 , 0x00CCA }, + { 0x00CC6 , 0x00CD5 , 0x00CC7 }, + { 0x00CC6 , 0x00CD6 , 0x00CC8 }, + { 0x00CCA , 0x00CD5 , 0x00CCB }, + { 0x00D46 , 0x00D3E , 0x00D4A }, + { 0x00D46 , 0x00D57 , 0x00D4C }, + { 0x00D47 , 0x00D3E , 0x00D4B }, + { 0x00DD9 , 0x00DCA , 0x00DDA }, + { 0x00DD9 , 0x00DCF , 0x00DDC }, + { 0x00DD9 , 0x00DDF , 0x00DDE }, + { 0x00DDC , 0x00DCA , 0x00DDD }, + { 0x01025 , 0x0102E , 0x01026 }, + { 0x01B05 , 0x01B35 , 0x01B06 }, + { 0x01B07 , 0x01B35 , 0x01B08 }, + { 0x01B09 , 0x01B35 , 0x01B0A }, + { 0x01B0B , 0x01B35 , 0x01B0C }, + { 0x01B0D , 0x01B35 , 0x01B0E }, + { 0x01B11 , 0x01B35 , 0x01B12 }, + { 0x01B3A , 0x01B35 , 0x01B3B }, + { 0x01B3C , 0x01B35 , 0x01B3D }, + { 0x01B3E , 0x01B35 , 0x01B40 }, + { 0x01B3F , 0x01B35 , 0x01B41 }, + { 0x01B42 , 0x01B35 , 0x01B43 }, + { 0x01E36 , 0x00304 , 0x01E38 }, + { 0x01E37 , 0x00304 , 0x01E39 }, + { 0x01E5A , 0x00304 , 0x01E5C }, + { 0x01E5B , 0x00304 , 0x01E5D }, + { 0x01E62 , 0x00307 , 0x01E68 }, + { 0x01E63 , 0x00307 , 0x01E69 }, + { 0x01EA0 , 0x00302 , 0x01EAC }, + { 0x01EA0 , 0x00306 , 0x01EB6 }, + { 0x01EA1 , 0x00302 , 0x01EAD }, + { 0x01EA1 , 0x00306 , 0x01EB7 }, + { 0x01EB8 , 0x00302 , 0x01EC6 }, + { 0x01EB9 , 0x00302 , 0x01EC7 }, + { 0x01ECC , 0x00302 , 0x01ED8 }, + { 0x01ECD , 0x00302 , 0x01ED9 }, + { 0x01F00 , 0x00300 , 0x01F02 }, + { 0x01F00 , 0x00301 , 0x01F04 }, + { 0x01F00 , 0x00342 , 0x01F06 }, + { 0x01F00 , 0x00345 , 0x01F80 }, + { 0x01F01 , 0x00300 , 0x01F03 }, + { 0x01F01 , 0x00301 , 0x01F05 }, + { 0x01F01 , 0x00342 , 0x01F07 }, + { 0x01F01 , 0x00345 , 0x01F81 }, + { 0x01F02 , 0x00345 , 0x01F82 }, + { 0x01F03 , 0x00345 , 0x01F83 }, + { 0x01F04 , 0x00345 , 0x01F84 }, + { 0x01F05 , 0x00345 , 0x01F85 }, + { 0x01F06 , 0x00345 , 0x01F86 }, + { 0x01F07 , 0x00345 , 0x01F87 }, + { 0x01F08 , 0x00300 , 0x01F0A }, + { 0x01F08 , 0x00301 , 0x01F0C }, + { 0x01F08 , 0x00342 , 0x01F0E }, + { 0x01F08 , 0x00345 , 0x01F88 }, + { 0x01F09 , 0x00300 , 0x01F0B }, + { 0x01F09 , 0x00301 , 0x01F0D }, + { 0x01F09 , 0x00342 , 0x01F0F }, + { 0x01F09 , 0x00345 , 0x01F89 }, + { 0x01F0A , 0x00345 , 0x01F8A }, + { 0x01F0B , 0x00345 , 0x01F8B }, + { 0x01F0C , 0x00345 , 0x01F8C }, + { 0x01F0D , 0x00345 , 0x01F8D }, + { 0x01F0E , 0x00345 , 0x01F8E }, + { 0x01F0F , 0x00345 , 0x01F8F }, + { 0x01F10 , 0x00300 , 0x01F12 }, + { 0x01F10 , 0x00301 , 0x01F14 }, + { 0x01F11 , 0x00300 , 0x01F13 }, + { 0x01F11 , 0x00301 , 0x01F15 }, + { 0x01F18 , 0x00300 , 0x01F1A }, + { 0x01F18 , 0x00301 , 0x01F1C }, + { 0x01F19 , 0x00300 , 0x01F1B }, + { 0x01F19 , 0x00301 , 0x01F1D }, + { 0x01F20 , 0x00300 , 0x01F22 }, + { 0x01F20 , 0x00301 , 0x01F24 }, + { 0x01F20 , 0x00342 , 0x01F26 }, + { 0x01F20 , 0x00345 , 0x01F90 }, + { 0x01F21 , 0x00300 , 0x01F23 }, + { 0x01F21 , 0x00301 , 0x01F25 }, + { 0x01F21 , 0x00342 , 0x01F27 }, + { 0x01F21 , 0x00345 , 0x01F91 }, + { 0x01F22 , 0x00345 , 0x01F92 }, + { 0x01F23 , 0x00345 , 0x01F93 }, + { 0x01F24 , 0x00345 , 0x01F94 }, + { 0x01F25 , 0x00345 , 0x01F95 }, + { 0x01F26 , 0x00345 , 0x01F96 }, + { 0x01F27 , 0x00345 , 0x01F97 }, + { 0x01F28 , 0x00300 , 0x01F2A }, + { 0x01F28 , 0x00301 , 0x01F2C }, + { 0x01F28 , 0x00342 , 0x01F2E }, + { 0x01F28 , 0x00345 , 0x01F98 }, + { 0x01F29 , 0x00300 , 0x01F2B }, + { 0x01F29 , 0x00301 , 0x01F2D }, + { 0x01F29 , 0x00342 , 0x01F2F }, + { 0x01F29 , 0x00345 , 0x01F99 }, + { 0x01F2A , 0x00345 , 0x01F9A }, + { 0x01F2B , 0x00345 , 0x01F9B }, + { 0x01F2C , 0x00345 , 0x01F9C }, + { 0x01F2D , 0x00345 , 0x01F9D }, + { 0x01F2E , 0x00345 , 0x01F9E }, + { 0x01F2F , 0x00345 , 0x01F9F }, + { 0x01F30 , 0x00300 , 0x01F32 }, + { 0x01F30 , 0x00301 , 0x01F34 }, + { 0x01F30 , 0x00342 , 0x01F36 }, + { 0x01F31 , 0x00300 , 0x01F33 }, + { 0x01F31 , 0x00301 , 0x01F35 }, + { 0x01F31 , 0x00342 , 0x01F37 }, + { 0x01F38 , 0x00300 , 0x01F3A }, + { 0x01F38 , 0x00301 , 0x01F3C }, + { 0x01F38 , 0x00342 , 0x01F3E }, + { 0x01F39 , 0x00300 , 0x01F3B }, + { 0x01F39 , 0x00301 , 0x01F3D }, + { 0x01F39 , 0x00342 , 0x01F3F }, + { 0x01F40 , 0x00300 , 0x01F42 }, + { 0x01F40 , 0x00301 , 0x01F44 }, + { 0x01F41 , 0x00300 , 0x01F43 }, + { 0x01F41 , 0x00301 , 0x01F45 }, + { 0x01F48 , 0x00300 , 0x01F4A }, + { 0x01F48 , 0x00301 , 0x01F4C }, + { 0x01F49 , 0x00300 , 0x01F4B }, + { 0x01F49 , 0x00301 , 0x01F4D }, + { 0x01F50 , 0x00300 , 0x01F52 }, + { 0x01F50 , 0x00301 , 0x01F54 }, + { 0x01F50 , 0x00342 , 0x01F56 }, + { 0x01F51 , 0x00300 , 0x01F53 }, + { 0x01F51 , 0x00301 , 0x01F55 }, + { 0x01F51 , 0x00342 , 0x01F57 }, + { 0x01F59 , 0x00300 , 0x01F5B }, + { 0x01F59 , 0x00301 , 0x01F5D }, + { 0x01F59 , 0x00342 , 0x01F5F }, + { 0x01F60 , 0x00300 , 0x01F62 }, + { 0x01F60 , 0x00301 , 0x01F64 }, + { 0x01F60 , 0x00342 , 0x01F66 }, + { 0x01F60 , 0x00345 , 0x01FA0 }, + { 0x01F61 , 0x00300 , 0x01F63 }, + { 0x01F61 , 0x00301 , 0x01F65 }, + { 0x01F61 , 0x00342 , 0x01F67 }, + { 0x01F61 , 0x00345 , 0x01FA1 }, + { 0x01F62 , 0x00345 , 0x01FA2 }, + { 0x01F63 , 0x00345 , 0x01FA3 }, + { 0x01F64 , 0x00345 , 0x01FA4 }, + { 0x01F65 , 0x00345 , 0x01FA5 }, + { 0x01F66 , 0x00345 , 0x01FA6 }, + { 0x01F67 , 0x00345 , 0x01FA7 }, + { 0x01F68 , 0x00300 , 0x01F6A }, + { 0x01F68 , 0x00301 , 0x01F6C }, + { 0x01F68 , 0x00342 , 0x01F6E }, + { 0x01F68 , 0x00345 , 0x01FA8 }, + { 0x01F69 , 0x00300 , 0x01F6B }, + { 0x01F69 , 0x00301 , 0x01F6D }, + { 0x01F69 , 0x00342 , 0x01F6F }, + { 0x01F69 , 0x00345 , 0x01FA9 }, + { 0x01F6A , 0x00345 , 0x01FAA }, + { 0x01F6B , 0x00345 , 0x01FAB }, + { 0x01F6C , 0x00345 , 0x01FAC }, + { 0x01F6D , 0x00345 , 0x01FAD }, + { 0x01F6E , 0x00345 , 0x01FAE }, + { 0x01F6F , 0x00345 , 0x01FAF }, + { 0x01F70 , 0x00345 , 0x01FB2 }, + { 0x01F74 , 0x00345 , 0x01FC2 }, + { 0x01F7C , 0x00345 , 0x01FF2 }, + { 0x01FB6 , 0x00345 , 0x01FB7 }, + { 0x01FBF , 0x00300 , 0x01FCD }, + { 0x01FBF , 0x00301 , 0x01FCE }, + { 0x01FBF , 0x00342 , 0x01FCF }, + { 0x01FC6 , 0x00345 , 0x01FC7 }, + { 0x01FF6 , 0x00345 , 0x01FF7 }, + { 0x01FFE , 0x00300 , 0x01FDD }, + { 0x01FFE , 0x00301 , 0x01FDE }, + { 0x01FFE , 0x00342 , 0x01FDF }, + { 0x02190 , 0x00338 , 0x0219A }, + { 0x02192 , 0x00338 , 0x0219B }, + { 0x02194 , 0x00338 , 0x021AE }, + { 0x021D0 , 0x00338 , 0x021CD }, + { 0x021D2 , 0x00338 , 0x021CF }, + { 0x021D4 , 0x00338 , 0x021CE }, + { 0x02203 , 0x00338 , 0x02204 }, + { 0x02208 , 0x00338 , 0x02209 }, + { 0x0220B , 0x00338 , 0x0220C }, + { 0x02223 , 0x00338 , 0x02224 }, + { 0x02225 , 0x00338 , 0x02226 }, + { 0x0223C , 0x00338 , 0x02241 }, + { 0x02243 , 0x00338 , 0x02244 }, + { 0x02245 , 0x00338 , 0x02247 }, + { 0x02248 , 0x00338 , 0x02249 }, + { 0x0224D , 0x00338 , 0x0226D }, + { 0x02261 , 0x00338 , 0x02262 }, + { 0x02264 , 0x00338 , 0x02270 }, + { 0x02265 , 0x00338 , 0x02271 }, + { 0x02272 , 0x00338 , 0x02274 }, + { 0x02273 , 0x00338 , 0x02275 }, + { 0x02276 , 0x00338 , 0x02278 }, + { 0x02277 , 0x00338 , 0x02279 }, + { 0x0227A , 0x00338 , 0x02280 }, + { 0x0227B , 0x00338 , 0x02281 }, + { 0x0227C , 0x00338 , 0x022E0 }, + { 0x0227D , 0x00338 , 0x022E1 }, + { 0x02282 , 0x00338 , 0x02284 }, + { 0x02283 , 0x00338 , 0x02285 }, + { 0x02286 , 0x00338 , 0x02288 }, + { 0x02287 , 0x00338 , 0x02289 }, + { 0x02291 , 0x00338 , 0x022E2 }, + { 0x02292 , 0x00338 , 0x022E3 }, + { 0x022A2 , 0x00338 , 0x022AC }, + { 0x022A8 , 0x00338 , 0x022AD }, + { 0x022A9 , 0x00338 , 0x022AE }, + { 0x022AB , 0x00338 , 0x022AF }, + { 0x022B2 , 0x00338 , 0x022EA }, + { 0x022B3 , 0x00338 , 0x022EB }, + { 0x022B4 , 0x00338 , 0x022EC }, + { 0x022B5 , 0x00338 , 0x022ED }, + { 0x03046 , 0x03099 , 0x03094 }, + { 0x0304B , 0x03099 , 0x0304C }, + { 0x0304D , 0x03099 , 0x0304E }, + { 0x0304F , 0x03099 , 0x03050 }, + { 0x03051 , 0x03099 , 0x03052 }, + { 0x03053 , 0x03099 , 0x03054 }, + { 0x03055 , 0x03099 , 0x03056 }, + { 0x03057 , 0x03099 , 0x03058 }, + { 0x03059 , 0x03099 , 0x0305A }, + { 0x0305B , 0x03099 , 0x0305C }, + { 0x0305D , 0x03099 , 0x0305E }, + { 0x0305F , 0x03099 , 0x03060 }, + { 0x03061 , 0x03099 , 0x03062 }, + { 0x03064 , 0x03099 , 0x03065 }, + { 0x03066 , 0x03099 , 0x03067 }, + { 0x03068 , 0x03099 , 0x03069 }, + { 0x0306F , 0x03099 , 0x03070 }, + { 0x0306F , 0x0309A , 0x03071 }, + { 0x03072 , 0x03099 , 0x03073 }, + { 0x03072 , 0x0309A , 0x03074 }, + { 0x03075 , 0x03099 , 0x03076 }, + { 0x03075 , 0x0309A , 0x03077 }, + { 0x03078 , 0x03099 , 0x03079 }, + { 0x03078 , 0x0309A , 0x0307A }, + { 0x0307B , 0x03099 , 0x0307C }, + { 0x0307B , 0x0309A , 0x0307D }, + { 0x0309D , 0x03099 , 0x0309E }, + { 0x030A6 , 0x03099 , 0x030F4 }, + { 0x030AB , 0x03099 , 0x030AC }, + { 0x030AD , 0x03099 , 0x030AE }, + { 0x030AF , 0x03099 , 0x030B0 }, + { 0x030B1 , 0x03099 , 0x030B2 }, + { 0x030B3 , 0x03099 , 0x030B4 }, + { 0x030B5 , 0x03099 , 0x030B6 }, + { 0x030B7 , 0x03099 , 0x030B8 }, + { 0x030B9 , 0x03099 , 0x030BA }, + { 0x030BB , 0x03099 , 0x030BC }, + { 0x030BD , 0x03099 , 0x030BE }, + { 0x030BF , 0x03099 , 0x030C0 }, + { 0x030C1 , 0x03099 , 0x030C2 }, + { 0x030C4 , 0x03099 , 0x030C5 }, + { 0x030C6 , 0x03099 , 0x030C7 }, + { 0x030C8 , 0x03099 , 0x030C9 }, + { 0x030CF , 0x03099 , 0x030D0 }, + { 0x030CF , 0x0309A , 0x030D1 }, + { 0x030D2 , 0x03099 , 0x030D3 }, + { 0x030D2 , 0x0309A , 0x030D4 }, + { 0x030D5 , 0x03099 , 0x030D6 }, + { 0x030D5 , 0x0309A , 0x030D7 }, + { 0x030D8 , 0x03099 , 0x030D9 }, + { 0x030D8 , 0x0309A , 0x030DA }, + { 0x030DB , 0x03099 , 0x030DC }, + { 0x030DB , 0x0309A , 0x030DD }, + { 0x030EF , 0x03099 , 0x030F7 }, + { 0x030F0 , 0x03099 , 0x030F8 }, + { 0x030F1 , 0x03099 , 0x030F9 }, + { 0x030F2 , 0x03099 , 0x030FA }, + { 0x030FD , 0x03099 , 0x030FE }, + { 0x11099 , 0x110BA , 0x1109A }, + { 0x1109B , 0x110BA , 0x1109C }, + { 0x110A5 , 0x110BA , 0x110AB }, +}; + +#define CANONICAL_CLASS_MIN 0x0300 +#define CANONICAL_CLASS_MAX 0x1D244 + +#define IS_DECOMPOSABLE_BLOCK(uc) \ + (((uc)>>8) <= 0x1D2 && u_decomposable_blocks[(uc)>>8]) +static const char u_decomposable_blocks[0x1D2+1] = { + 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,1,1,1,1,1,1,1,0,0, + 1,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,1,0,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,1,1,1,1,1,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0, + 0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1, +}; + +/* Get Canonical Combining Class(CCC). */ +#define CCC(uc) \ + (((uc) > 0x1D244)?0:\ + ccc_val[ccc_val_index[ccc_index[(uc)>>8]][((uc)>>4)&0x0F]][(uc)&0x0F]) + +/* The table of the value of Canonical Combining Class */ +static const unsigned char ccc_val[][16] = { + /* idx=0: XXXX0 - XXXXF */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=1: 00300 - 0030F */ + {230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230 }, + /* idx=2: 00310 - 0031F */ + {230, 230, 230, 230, 230, 232, 220, 220, 220, 220, 232, 216, 220, 220, 220, 220 }, + /* idx=3: 00320 - 0032F */ + {220, 202, 202, 220, 220, 220, 220, 202, 202, 220, 220, 220, 220, 220, 220, 220 }, + /* idx=4: 00330 - 0033F */ + {220, 220, 220, 220, 1, 1, 1, 1, 1, 220, 220, 220, 220, 230, 230, 230 }, + /* idx=5: 00340 - 0034F */ + {230, 230, 230, 230, 230, 240, 230, 220, 220, 220, 230, 230, 230, 220, 220, 0 }, + /* idx=6: 00350 - 0035F */ + {230, 230, 230, 220, 220, 220, 220, 230, 232, 220, 220, 230, 233, 234, 234, 233 }, + /* idx=7: 00360 - 0036F */ + {234, 234, 233, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230 }, + /* idx=8: 00480 - 0048F */ + {0, 0, 0, 230, 230, 230, 230, 230, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=9: 00590 - 0059F */ + {0, 220, 230, 230, 230, 230, 220, 230, 230, 230, 222, 220, 230, 230, 230, 230 }, + /* idx=10: 005A0 - 005AF */ + {230, 230, 220, 220, 220, 220, 220, 220, 230, 230, 220, 230, 230, 222, 228, 230 }, + /* idx=11: 005B0 - 005BF */ + {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 0, 23 }, + /* idx=12: 005C0 - 005CF */ + {0, 24, 25, 0, 230, 220, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=13: 00610 - 0061F */ + {230, 230, 230, 230, 230, 230, 230, 230, 30, 31, 32, 0, 0, 0, 0, 0 }, + /* idx=14: 00640 - 0064F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 28, 29, 30, 31 }, + /* idx=15: 00650 - 0065F */ + {32, 33, 34, 230, 230, 220, 220, 230, 230, 230, 230, 230, 220, 230, 230, 220 }, + /* idx=16: 00670 - 0067F */ + {35, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=17: 006D0 - 006DF */ + {0, 0, 0, 0, 0, 0, 230, 230, 230, 230, 230, 230, 230, 0, 0, 230 }, + /* idx=18: 006E0 - 006EF */ + {230, 230, 230, 220, 230, 0, 0, 230, 230, 0, 220, 230, 230, 220, 0, 0 }, + /* idx=19: 00710 - 0071F */ + {0, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=20: 00730 - 0073F */ + {230, 220, 230, 230, 220, 230, 230, 220, 220, 220, 230, 220, 220, 230, 220, 230 }, + /* idx=21: 00740 - 0074F */ + {230, 230, 220, 230, 220, 230, 220, 230, 220, 230, 230, 0, 0, 0, 0, 0 }, + /* idx=22: 007E0 - 007EF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 230, 230, 230, 230, 230 }, + /* idx=23: 007F0 - 007FF */ + {230, 230, 220, 230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=24: 00810 - 0081F */ + {0, 0, 0, 0, 0, 0, 230, 230, 230, 230, 0, 230, 230, 230, 230, 230 }, + /* idx=25: 00820 - 0082F */ + {230, 230, 230, 230, 0, 230, 230, 230, 0, 230, 230, 230, 230, 230, 0, 0 }, + /* idx=26: 00850 - 0085F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 220, 220, 220, 0, 0, 0, 0 }, + /* idx=27: 00930 - 0093F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0 }, + /* idx=28: 00940 - 0094F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0 }, + /* idx=29: 00950 - 0095F */ + {0, 230, 220, 230, 230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=30: 009B0 - 009BF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0 }, + /* idx=31: 009C0 - 009CF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0 }, + /* idx=32: 00A30 - 00A3F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0 }, + /* idx=33: 00A40 - 00A4F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0 }, + /* idx=34: 00AB0 - 00ABF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0 }, + /* idx=35: 00AC0 - 00ACF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0 }, + /* idx=36: 00B30 - 00B3F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0 }, + /* idx=37: 00B40 - 00B4F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0 }, + /* idx=38: 00BC0 - 00BCF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0 }, + /* idx=39: 00C40 - 00C4F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0 }, + /* idx=40: 00C50 - 00C5F */ + {0, 0, 0, 0, 0, 84, 91, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=41: 00CB0 - 00CBF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0 }, + /* idx=42: 00CC0 - 00CCF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0 }, + /* idx=43: 00D40 - 00D4F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0 }, + /* idx=44: 00DC0 - 00DCF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0 }, + /* idx=45: 00E30 - 00E3F */ + {0, 0, 0, 0, 0, 0, 0, 0, 103, 103, 9, 0, 0, 0, 0, 0 }, + /* idx=46: 00E40 - 00E4F */ + {0, 0, 0, 0, 0, 0, 0, 0, 107, 107, 107, 107, 0, 0, 0, 0 }, + /* idx=47: 00EB0 - 00EBF */ + {0, 0, 0, 0, 0, 0, 0, 0, 118, 118, 0, 0, 0, 0, 0, 0 }, + /* idx=48: 00EC0 - 00ECF */ + {0, 0, 0, 0, 0, 0, 0, 0, 122, 122, 122, 122, 0, 0, 0, 0 }, + /* idx=49: 00F10 - 00F1F */ + {0, 0, 0, 0, 0, 0, 0, 0, 220, 220, 0, 0, 0, 0, 0, 0 }, + /* idx=50: 00F30 - 00F3F */ + {0, 0, 0, 0, 0, 220, 0, 220, 0, 216, 0, 0, 0, 0, 0, 0 }, + /* idx=51: 00F70 - 00F7F */ + {0, 129, 130, 0, 132, 0, 0, 0, 0, 0, 130, 130, 130, 130, 0, 0 }, + /* idx=52: 00F80 - 00F8F */ + {130, 0, 230, 230, 9, 0, 230, 230, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=53: 00FC0 - 00FCF */ + {0, 0, 0, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=54: 01030 - 0103F */ + {0, 0, 0, 0, 0, 0, 0, 7, 0, 9, 9, 0, 0, 0, 0, 0 }, + /* idx=55: 01080 - 0108F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 220, 0, 0 }, + /* idx=56: 01350 - 0135F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 230, 230, 230 }, + /* idx=57: 01710 - 0171F */ + {0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=58: 01730 - 0173F */ + {0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=59: 017D0 - 017DF */ + {0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 230, 0, 0 }, + /* idx=60: 018A0 - 018AF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 228, 0, 0, 0, 0, 0, 0 }, + /* idx=61: 01930 - 0193F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 222, 230, 220, 0, 0, 0, 0 }, + /* idx=62: 01A10 - 01A1F */ + {0, 0, 0, 0, 0, 0, 0, 230, 220, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=63: 01A60 - 01A6F */ + {9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=64: 01A70 - 01A7F */ + {0, 0, 0, 0, 0, 230, 230, 230, 230, 230, 230, 230, 230, 0, 0, 220 }, + /* idx=65: 01B30 - 01B3F */ + {0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=66: 01B40 - 01B4F */ + {0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=67: 01B60 - 01B6F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 230, 220, 230, 230, 230 }, + /* idx=68: 01B70 - 01B7F */ + {230, 230, 230, 230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=69: 01BA0 - 01BAF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0 }, + /* idx=70: 01BE0 - 01BEF */ + {0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=71: 01BF0 - 01BFF */ + {0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=72: 01C30 - 01C3F */ + {0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=73: 01CD0 - 01CDF */ + {230, 230, 230, 0, 1, 220, 220, 220, 220, 220, 230, 230, 220, 220, 220, 220 }, + /* idx=74: 01CE0 - 01CEF */ + {230, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 220, 0, 0 }, + /* idx=75: 01DC0 - 01DCF */ + {230, 230, 220, 230, 230, 230, 230, 230, 230, 230, 220, 230, 230, 234, 214, 220 }, + /* idx=76: 01DD0 - 01DDF */ + {202, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230 }, + /* idx=77: 01DE0 - 01DEF */ + {230, 230, 230, 230, 230, 230, 230, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=78: 01DF0 - 01DFF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 233, 220, 230, 220 }, + /* idx=79: 020D0 - 020DF */ + {230, 230, 1, 1, 230, 230, 230, 230, 1, 1, 1, 230, 230, 0, 0, 0 }, + /* idx=80: 020E0 - 020EF */ + {0, 230, 0, 0, 0, 1, 1, 230, 220, 230, 1, 1, 220, 220, 220, 220 }, + /* idx=81: 020F0 - 020FF */ + {230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=82: 02CE0 - 02CEF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 230 }, + /* idx=83: 02CF0 - 02CFF */ + {230, 230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=84: 02D70 - 02D7F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9 }, + /* idx=85: 02DE0 - 02DEF */ + {230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230 }, + /* idx=86: 02DF0 - 02DFF */ + {230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230 }, + /* idx=87: 03020 - 0302F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 218, 228, 232, 222, 224, 224 }, + /* idx=88: 03090 - 0309F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0 }, + /* idx=89: 0A660 - 0A66F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 230 }, + /* idx=90: 0A670 - 0A67F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 230, 230, 0, 0 }, + /* idx=91: 0A6F0 - 0A6FF */ + {230, 230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=92: 0A800 - 0A80F */ + {0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=93: 0A8C0 - 0A8CF */ + {0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=94: 0A8E0 - 0A8EF */ + {230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230 }, + /* idx=95: 0A8F0 - 0A8FF */ + {230, 230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=96: 0A920 - 0A92F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 220, 220, 220, 0, 0 }, + /* idx=97: 0A950 - 0A95F */ + {0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=98: 0A9B0 - 0A9BF */ + {0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=99: 0A9C0 - 0A9CF */ + {9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=100: 0AAB0 - 0AABF */ + {230, 0, 230, 230, 220, 0, 0, 230, 230, 0, 0, 0, 0, 0, 230, 230 }, + /* idx=101: 0AAC0 - 0AACF */ + {0, 230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=102: 0ABE0 - 0ABEF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0 }, + /* idx=103: 0FB10 - 0FB1F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 26, 0 }, + /* idx=104: 0FE20 - 0FE2F */ + {230, 230, 230, 230, 230, 230, 230, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=105: 101F0 - 101FF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 220, 0, 0 }, + /* idx=106: 10A00 - 10A0F */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 220, 0, 230 }, + /* idx=107: 10A30 - 10A3F */ + {0, 0, 0, 0, 0, 0, 0, 0, 230, 1, 220, 0, 0, 0, 0, 9 }, + /* idx=108: 11040 - 1104F */ + {0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=109: 110B0 - 110BF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 7, 0, 0, 0, 0, 0 }, + /* idx=110: 1D160 - 1D16F */ + {0, 0, 0, 0, 0, 216, 216, 1, 1, 1, 0, 0, 0, 226, 216, 216 }, + /* idx=111: 1D170 - 1D17F */ + {216, 216, 216, 0, 0, 0, 0, 0, 0, 0, 0, 220, 220, 220, 220, 220 }, + /* idx=112: 1D180 - 1D18F */ + {220, 220, 220, 0, 0, 230, 230, 230, 230, 230, 220, 220, 0, 0, 0, 0 }, + /* idx=113: 1D1A0 - 1D1AF */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 230, 230, 230, 230, 0, 0 }, + /* idx=114: 1D240 - 1D24F */ + {0, 0, 230, 230, 230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, +}; + +/* The index table to ccc_val[*][16] */ +static const unsigned char ccc_val_index[][16] = { + /* idx=0: XXX00 - XXXFF */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=1: 00300 - 003FF */ + { 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=2: 00400 - 004FF */ + { 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=3: 00500 - 005FF */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,10,11,12, 0, 0, 0 }, + /* idx=4: 00600 - 006FF */ + { 0,13, 0, 0,14,15, 0,16, 0, 0, 0, 0, 0,17,18, 0 }, + /* idx=5: 00700 - 007FF */ + { 0,19, 0,20,21, 0, 0, 0, 0, 0, 0, 0, 0, 0,22,23 }, + /* idx=6: 00800 - 008FF */ + { 0,24,25, 0, 0,26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=7: 00900 - 009FF */ + { 0, 0, 0,27,28,29, 0, 0, 0, 0, 0,30,31, 0, 0, 0 }, + /* idx=8: 00A00 - 00AFF */ + { 0, 0, 0,32,33, 0, 0, 0, 0, 0, 0,34,35, 0, 0, 0 }, + /* idx=9: 00B00 - 00BFF */ + { 0, 0, 0,36,37, 0, 0, 0, 0, 0, 0, 0,38, 0, 0, 0 }, + /* idx=10: 00C00 - 00CFF */ + { 0, 0, 0, 0,39,40, 0, 0, 0, 0, 0,41,42, 0, 0, 0 }, + /* idx=11: 00D00 - 00DFF */ + { 0, 0, 0, 0,43, 0, 0, 0, 0, 0, 0, 0,44, 0, 0, 0 }, + /* idx=12: 00E00 - 00EFF */ + { 0, 0, 0,45,46, 0, 0, 0, 0, 0, 0,47,48, 0, 0, 0 }, + /* idx=13: 00F00 - 00FFF */ + { 0,49, 0,50, 0, 0, 0,51,52, 0, 0, 0,53, 0, 0, 0 }, + /* idx=14: 01000 - 010FF */ + { 0, 0, 0,54, 0, 0, 0, 0,55, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=15: 01300 - 013FF */ + { 0, 0, 0, 0, 0,56, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=16: 01700 - 017FF */ + { 0,57, 0,58, 0, 0, 0, 0, 0, 0, 0, 0, 0,59, 0, 0 }, + /* idx=17: 01800 - 018FF */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,60, 0, 0, 0, 0, 0 }, + /* idx=18: 01900 - 019FF */ + { 0, 0, 0,61, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=19: 01A00 - 01AFF */ + { 0,62, 0, 0, 0, 0,63,64, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=20: 01B00 - 01BFF */ + { 0, 0, 0,65,66, 0,67,68, 0, 0,69, 0, 0, 0,70,71 }, + /* idx=21: 01C00 - 01CFF */ + { 0, 0, 0,72, 0, 0, 0, 0, 0, 0, 0, 0, 0,73,74, 0 }, + /* idx=22: 01D00 - 01DFF */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,75,76,77,78 }, + /* idx=23: 02000 - 020FF */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,79,80,81 }, + /* idx=24: 02C00 - 02CFF */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,82,83 }, + /* idx=25: 02D00 - 02DFF */ + { 0, 0, 0, 0, 0, 0, 0,84, 0, 0, 0, 0, 0, 0,85,86 }, + /* idx=26: 03000 - 030FF */ + { 0, 0,87, 0, 0, 0, 0, 0, 0,88, 0, 0, 0, 0, 0, 0 }, + /* idx=27: 0A600 - 0A6FF */ + { 0, 0, 0, 0, 0, 0,89,90, 0, 0, 0, 0, 0, 0, 0,91 }, + /* idx=28: 0A800 - 0A8FF */ + {92, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,93, 0,94,95 }, + /* idx=29: 0A900 - 0A9FF */ + { 0, 0,96, 0, 0,97, 0, 0, 0, 0, 0,98,99, 0, 0, 0 }, + /* idx=30: 0AA00 - 0AAFF */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,100,101, 0, 0, 0 }, + /* idx=31: 0AB00 - 0ABFF */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,102, 0 }, + /* idx=32: 0FB00 - 0FBFF */ + { 0,103, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=33: 0FE00 - 0FEFF */ + { 0, 0,104, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=34: 10100 - 101FF */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,105 }, + /* idx=35: 10A00 - 10AFF */ + {106, 0, 0,107, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + /* idx=36: 11000 - 110FF */ + { 0, 0, 0, 0,108, 0, 0, 0, 0, 0, 0,109, 0, 0, 0, 0 }, + /* idx=37: 1D100 - 1D1FF */ + { 0, 0, 0, 0, 0, 0,110,111,112, 0,113, 0, 0, 0, 0, 0 }, + /* idx=38: 1D200 - 1D2FF */ + { 0, 0, 0, 0,114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, +}; + +/* The index table to ccc_val_index[*][16] */ +static const unsigned char ccc_index[] = { + 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, 0, 0,15, 0, 0, 0,16, + 17,18,19,20,21,22, 0, 0,23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,24,25, 0, 0, + 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,27, 0, + 28,29,30,31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,32, 0, 0,33, 0, 0,34, 0, 0, 0, 0, 0, 0, + 0, 0,35, 0, 0, 0, 0, 0,36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0,37,38,}; + +struct unicode_decomposition_table { + uint32_t nfc; + uint32_t cp1; + uint32_t cp2; +}; + +static const struct unicode_decomposition_table u_decomposition_table[] = { + { 0x000C0 , 0x00041 , 0x00300 }, + { 0x000C1 , 0x00041 , 0x00301 }, + { 0x000C2 , 0x00041 , 0x00302 }, + { 0x000C3 , 0x00041 , 0x00303 }, + { 0x000C4 , 0x00041 , 0x00308 }, + { 0x000C5 , 0x00041 , 0x0030A }, + { 0x000C7 , 0x00043 , 0x00327 }, + { 0x000C8 , 0x00045 , 0x00300 }, + { 0x000C9 , 0x00045 , 0x00301 }, + { 0x000CA , 0x00045 , 0x00302 }, + { 0x000CB , 0x00045 , 0x00308 }, + { 0x000CC , 0x00049 , 0x00300 }, + { 0x000CD , 0x00049 , 0x00301 }, + { 0x000CE , 0x00049 , 0x00302 }, + { 0x000CF , 0x00049 , 0x00308 }, + { 0x000D1 , 0x0004E , 0x00303 }, + { 0x000D2 , 0x0004F , 0x00300 }, + { 0x000D3 , 0x0004F , 0x00301 }, + { 0x000D4 , 0x0004F , 0x00302 }, + { 0x000D5 , 0x0004F , 0x00303 }, + { 0x000D6 , 0x0004F , 0x00308 }, + { 0x000D9 , 0x00055 , 0x00300 }, + { 0x000DA , 0x00055 , 0x00301 }, + { 0x000DB , 0x00055 , 0x00302 }, + { 0x000DC , 0x00055 , 0x00308 }, + { 0x000DD , 0x00059 , 0x00301 }, + { 0x000E0 , 0x00061 , 0x00300 }, + { 0x000E1 , 0x00061 , 0x00301 }, + { 0x000E2 , 0x00061 , 0x00302 }, + { 0x000E3 , 0x00061 , 0x00303 }, + { 0x000E4 , 0x00061 , 0x00308 }, + { 0x000E5 , 0x00061 , 0x0030A }, + { 0x000E7 , 0x00063 , 0x00327 }, + { 0x000E8 , 0x00065 , 0x00300 }, + { 0x000E9 , 0x00065 , 0x00301 }, + { 0x000EA , 0x00065 , 0x00302 }, + { 0x000EB , 0x00065 , 0x00308 }, + { 0x000EC , 0x00069 , 0x00300 }, + { 0x000ED , 0x00069 , 0x00301 }, + { 0x000EE , 0x00069 , 0x00302 }, + { 0x000EF , 0x00069 , 0x00308 }, + { 0x000F1 , 0x0006E , 0x00303 }, + { 0x000F2 , 0x0006F , 0x00300 }, + { 0x000F3 , 0x0006F , 0x00301 }, + { 0x000F4 , 0x0006F , 0x00302 }, + { 0x000F5 , 0x0006F , 0x00303 }, + { 0x000F6 , 0x0006F , 0x00308 }, + { 0x000F9 , 0x00075 , 0x00300 }, + { 0x000FA , 0x00075 , 0x00301 }, + { 0x000FB , 0x00075 , 0x00302 }, + { 0x000FC , 0x00075 , 0x00308 }, + { 0x000FD , 0x00079 , 0x00301 }, + { 0x000FF , 0x00079 , 0x00308 }, + { 0x00100 , 0x00041 , 0x00304 }, + { 0x00101 , 0x00061 , 0x00304 }, + { 0x00102 , 0x00041 , 0x00306 }, + { 0x00103 , 0x00061 , 0x00306 }, + { 0x00104 , 0x00041 , 0x00328 }, + { 0x00105 , 0x00061 , 0x00328 }, + { 0x00106 , 0x00043 , 0x00301 }, + { 0x00107 , 0x00063 , 0x00301 }, + { 0x00108 , 0x00043 , 0x00302 }, + { 0x00109 , 0x00063 , 0x00302 }, + { 0x0010A , 0x00043 , 0x00307 }, + { 0x0010B , 0x00063 , 0x00307 }, + { 0x0010C , 0x00043 , 0x0030C }, + { 0x0010D , 0x00063 , 0x0030C }, + { 0x0010E , 0x00044 , 0x0030C }, + { 0x0010F , 0x00064 , 0x0030C }, + { 0x00112 , 0x00045 , 0x00304 }, + { 0x00113 , 0x00065 , 0x00304 }, + { 0x00114 , 0x00045 , 0x00306 }, + { 0x00115 , 0x00065 , 0x00306 }, + { 0x00116 , 0x00045 , 0x00307 }, + { 0x00117 , 0x00065 , 0x00307 }, + { 0x00118 , 0x00045 , 0x00328 }, + { 0x00119 , 0x00065 , 0x00328 }, + { 0x0011A , 0x00045 , 0x0030C }, + { 0x0011B , 0x00065 , 0x0030C }, + { 0x0011C , 0x00047 , 0x00302 }, + { 0x0011D , 0x00067 , 0x00302 }, + { 0x0011E , 0x00047 , 0x00306 }, + { 0x0011F , 0x00067 , 0x00306 }, + { 0x00120 , 0x00047 , 0x00307 }, + { 0x00121 , 0x00067 , 0x00307 }, + { 0x00122 , 0x00047 , 0x00327 }, + { 0x00123 , 0x00067 , 0x00327 }, + { 0x00124 , 0x00048 , 0x00302 }, + { 0x00125 , 0x00068 , 0x00302 }, + { 0x00128 , 0x00049 , 0x00303 }, + { 0x00129 , 0x00069 , 0x00303 }, + { 0x0012A , 0x00049 , 0x00304 }, + { 0x0012B , 0x00069 , 0x00304 }, + { 0x0012C , 0x00049 , 0x00306 }, + { 0x0012D , 0x00069 , 0x00306 }, + { 0x0012E , 0x00049 , 0x00328 }, + { 0x0012F , 0x00069 , 0x00328 }, + { 0x00130 , 0x00049 , 0x00307 }, + { 0x00134 , 0x0004A , 0x00302 }, + { 0x00135 , 0x0006A , 0x00302 }, + { 0x00136 , 0x0004B , 0x00327 }, + { 0x00137 , 0x0006B , 0x00327 }, + { 0x00139 , 0x0004C , 0x00301 }, + { 0x0013A , 0x0006C , 0x00301 }, + { 0x0013B , 0x0004C , 0x00327 }, + { 0x0013C , 0x0006C , 0x00327 }, + { 0x0013D , 0x0004C , 0x0030C }, + { 0x0013E , 0x0006C , 0x0030C }, + { 0x00143 , 0x0004E , 0x00301 }, + { 0x00144 , 0x0006E , 0x00301 }, + { 0x00145 , 0x0004E , 0x00327 }, + { 0x00146 , 0x0006E , 0x00327 }, + { 0x00147 , 0x0004E , 0x0030C }, + { 0x00148 , 0x0006E , 0x0030C }, + { 0x0014C , 0x0004F , 0x00304 }, + { 0x0014D , 0x0006F , 0x00304 }, + { 0x0014E , 0x0004F , 0x00306 }, + { 0x0014F , 0x0006F , 0x00306 }, + { 0x00150 , 0x0004F , 0x0030B }, + { 0x00151 , 0x0006F , 0x0030B }, + { 0x00154 , 0x00052 , 0x00301 }, + { 0x00155 , 0x00072 , 0x00301 }, + { 0x00156 , 0x00052 , 0x00327 }, + { 0x00157 , 0x00072 , 0x00327 }, + { 0x00158 , 0x00052 , 0x0030C }, + { 0x00159 , 0x00072 , 0x0030C }, + { 0x0015A , 0x00053 , 0x00301 }, + { 0x0015B , 0x00073 , 0x00301 }, + { 0x0015C , 0x00053 , 0x00302 }, + { 0x0015D , 0x00073 , 0x00302 }, + { 0x0015E , 0x00053 , 0x00327 }, + { 0x0015F , 0x00073 , 0x00327 }, + { 0x00160 , 0x00053 , 0x0030C }, + { 0x00161 , 0x00073 , 0x0030C }, + { 0x00162 , 0x00054 , 0x00327 }, + { 0x00163 , 0x00074 , 0x00327 }, + { 0x00164 , 0x00054 , 0x0030C }, + { 0x00165 , 0x00074 , 0x0030C }, + { 0x00168 , 0x00055 , 0x00303 }, + { 0x00169 , 0x00075 , 0x00303 }, + { 0x0016A , 0x00055 , 0x00304 }, + { 0x0016B , 0x00075 , 0x00304 }, + { 0x0016C , 0x00055 , 0x00306 }, + { 0x0016D , 0x00075 , 0x00306 }, + { 0x0016E , 0x00055 , 0x0030A }, + { 0x0016F , 0x00075 , 0x0030A }, + { 0x00170 , 0x00055 , 0x0030B }, + { 0x00171 , 0x00075 , 0x0030B }, + { 0x00172 , 0x00055 , 0x00328 }, + { 0x00173 , 0x00075 , 0x00328 }, + { 0x00174 , 0x00057 , 0x00302 }, + { 0x00175 , 0x00077 , 0x00302 }, + { 0x00176 , 0x00059 , 0x00302 }, + { 0x00177 , 0x00079 , 0x00302 }, + { 0x00178 , 0x00059 , 0x00308 }, + { 0x00179 , 0x0005A , 0x00301 }, + { 0x0017A , 0x0007A , 0x00301 }, + { 0x0017B , 0x0005A , 0x00307 }, + { 0x0017C , 0x0007A , 0x00307 }, + { 0x0017D , 0x0005A , 0x0030C }, + { 0x0017E , 0x0007A , 0x0030C }, + { 0x001A0 , 0x0004F , 0x0031B }, + { 0x001A1 , 0x0006F , 0x0031B }, + { 0x001AF , 0x00055 , 0x0031B }, + { 0x001B0 , 0x00075 , 0x0031B }, + { 0x001CD , 0x00041 , 0x0030C }, + { 0x001CE , 0x00061 , 0x0030C }, + { 0x001CF , 0x00049 , 0x0030C }, + { 0x001D0 , 0x00069 , 0x0030C }, + { 0x001D1 , 0x0004F , 0x0030C }, + { 0x001D2 , 0x0006F , 0x0030C }, + { 0x001D3 , 0x00055 , 0x0030C }, + { 0x001D4 , 0x00075 , 0x0030C }, + { 0x001D5 , 0x000DC , 0x00304 }, + { 0x001D6 , 0x000FC , 0x00304 }, + { 0x001D7 , 0x000DC , 0x00301 }, + { 0x001D8 , 0x000FC , 0x00301 }, + { 0x001D9 , 0x000DC , 0x0030C }, + { 0x001DA , 0x000FC , 0x0030C }, + { 0x001DB , 0x000DC , 0x00300 }, + { 0x001DC , 0x000FC , 0x00300 }, + { 0x001DE , 0x000C4 , 0x00304 }, + { 0x001DF , 0x000E4 , 0x00304 }, + { 0x001E0 , 0x00226 , 0x00304 }, + { 0x001E1 , 0x00227 , 0x00304 }, + { 0x001E2 , 0x000C6 , 0x00304 }, + { 0x001E3 , 0x000E6 , 0x00304 }, + { 0x001E6 , 0x00047 , 0x0030C }, + { 0x001E7 , 0x00067 , 0x0030C }, + { 0x001E8 , 0x0004B , 0x0030C }, + { 0x001E9 , 0x0006B , 0x0030C }, + { 0x001EA , 0x0004F , 0x00328 }, + { 0x001EB , 0x0006F , 0x00328 }, + { 0x001EC , 0x001EA , 0x00304 }, + { 0x001ED , 0x001EB , 0x00304 }, + { 0x001EE , 0x001B7 , 0x0030C }, + { 0x001EF , 0x00292 , 0x0030C }, + { 0x001F0 , 0x0006A , 0x0030C }, + { 0x001F4 , 0x00047 , 0x00301 }, + { 0x001F5 , 0x00067 , 0x00301 }, + { 0x001F8 , 0x0004E , 0x00300 }, + { 0x001F9 , 0x0006E , 0x00300 }, + { 0x001FA , 0x000C5 , 0x00301 }, + { 0x001FB , 0x000E5 , 0x00301 }, + { 0x001FC , 0x000C6 , 0x00301 }, + { 0x001FD , 0x000E6 , 0x00301 }, + { 0x001FE , 0x000D8 , 0x00301 }, + { 0x001FF , 0x000F8 , 0x00301 }, + { 0x00200 , 0x00041 , 0x0030F }, + { 0x00201 , 0x00061 , 0x0030F }, + { 0x00202 , 0x00041 , 0x00311 }, + { 0x00203 , 0x00061 , 0x00311 }, + { 0x00204 , 0x00045 , 0x0030F }, + { 0x00205 , 0x00065 , 0x0030F }, + { 0x00206 , 0x00045 , 0x00311 }, + { 0x00207 , 0x00065 , 0x00311 }, + { 0x00208 , 0x00049 , 0x0030F }, + { 0x00209 , 0x00069 , 0x0030F }, + { 0x0020A , 0x00049 , 0x00311 }, + { 0x0020B , 0x00069 , 0x00311 }, + { 0x0020C , 0x0004F , 0x0030F }, + { 0x0020D , 0x0006F , 0x0030F }, + { 0x0020E , 0x0004F , 0x00311 }, + { 0x0020F , 0x0006F , 0x00311 }, + { 0x00210 , 0x00052 , 0x0030F }, + { 0x00211 , 0x00072 , 0x0030F }, + { 0x00212 , 0x00052 , 0x00311 }, + { 0x00213 , 0x00072 , 0x00311 }, + { 0x00214 , 0x00055 , 0x0030F }, + { 0x00215 , 0x00075 , 0x0030F }, + { 0x00216 , 0x00055 , 0x00311 }, + { 0x00217 , 0x00075 , 0x00311 }, + { 0x00218 , 0x00053 , 0x00326 }, + { 0x00219 , 0x00073 , 0x00326 }, + { 0x0021A , 0x00054 , 0x00326 }, + { 0x0021B , 0x00074 , 0x00326 }, + { 0x0021E , 0x00048 , 0x0030C }, + { 0x0021F , 0x00068 , 0x0030C }, + { 0x00226 , 0x00041 , 0x00307 }, + { 0x00227 , 0x00061 , 0x00307 }, + { 0x00228 , 0x00045 , 0x00327 }, + { 0x00229 , 0x00065 , 0x00327 }, + { 0x0022A , 0x000D6 , 0x00304 }, + { 0x0022B , 0x000F6 , 0x00304 }, + { 0x0022C , 0x000D5 , 0x00304 }, + { 0x0022D , 0x000F5 , 0x00304 }, + { 0x0022E , 0x0004F , 0x00307 }, + { 0x0022F , 0x0006F , 0x00307 }, + { 0x00230 , 0x0022E , 0x00304 }, + { 0x00231 , 0x0022F , 0x00304 }, + { 0x00232 , 0x00059 , 0x00304 }, + { 0x00233 , 0x00079 , 0x00304 }, + { 0x00385 , 0x000A8 , 0x00301 }, + { 0x00386 , 0x00391 , 0x00301 }, + { 0x00388 , 0x00395 , 0x00301 }, + { 0x00389 , 0x00397 , 0x00301 }, + { 0x0038A , 0x00399 , 0x00301 }, + { 0x0038C , 0x0039F , 0x00301 }, + { 0x0038E , 0x003A5 , 0x00301 }, + { 0x0038F , 0x003A9 , 0x00301 }, + { 0x00390 , 0x003CA , 0x00301 }, + { 0x003AA , 0x00399 , 0x00308 }, + { 0x003AB , 0x003A5 , 0x00308 }, + { 0x003AC , 0x003B1 , 0x00301 }, + { 0x003AD , 0x003B5 , 0x00301 }, + { 0x003AE , 0x003B7 , 0x00301 }, + { 0x003AF , 0x003B9 , 0x00301 }, + { 0x003B0 , 0x003CB , 0x00301 }, + { 0x003CA , 0x003B9 , 0x00308 }, + { 0x003CB , 0x003C5 , 0x00308 }, + { 0x003CC , 0x003BF , 0x00301 }, + { 0x003CD , 0x003C5 , 0x00301 }, + { 0x003CE , 0x003C9 , 0x00301 }, + { 0x003D3 , 0x003D2 , 0x00301 }, + { 0x003D4 , 0x003D2 , 0x00308 }, + { 0x00400 , 0x00415 , 0x00300 }, + { 0x00401 , 0x00415 , 0x00308 }, + { 0x00403 , 0x00413 , 0x00301 }, + { 0x00407 , 0x00406 , 0x00308 }, + { 0x0040C , 0x0041A , 0x00301 }, + { 0x0040D , 0x00418 , 0x00300 }, + { 0x0040E , 0x00423 , 0x00306 }, + { 0x00419 , 0x00418 , 0x00306 }, + { 0x00439 , 0x00438 , 0x00306 }, + { 0x00450 , 0x00435 , 0x00300 }, + { 0x00451 , 0x00435 , 0x00308 }, + { 0x00453 , 0x00433 , 0x00301 }, + { 0x00457 , 0x00456 , 0x00308 }, + { 0x0045C , 0x0043A , 0x00301 }, + { 0x0045D , 0x00438 , 0x00300 }, + { 0x0045E , 0x00443 , 0x00306 }, + { 0x00476 , 0x00474 , 0x0030F }, + { 0x00477 , 0x00475 , 0x0030F }, + { 0x004C1 , 0x00416 , 0x00306 }, + { 0x004C2 , 0x00436 , 0x00306 }, + { 0x004D0 , 0x00410 , 0x00306 }, + { 0x004D1 , 0x00430 , 0x00306 }, + { 0x004D2 , 0x00410 , 0x00308 }, + { 0x004D3 , 0x00430 , 0x00308 }, + { 0x004D6 , 0x00415 , 0x00306 }, + { 0x004D7 , 0x00435 , 0x00306 }, + { 0x004DA , 0x004D8 , 0x00308 }, + { 0x004DB , 0x004D9 , 0x00308 }, + { 0x004DC , 0x00416 , 0x00308 }, + { 0x004DD , 0x00436 , 0x00308 }, + { 0x004DE , 0x00417 , 0x00308 }, + { 0x004DF , 0x00437 , 0x00308 }, + { 0x004E2 , 0x00418 , 0x00304 }, + { 0x004E3 , 0x00438 , 0x00304 }, + { 0x004E4 , 0x00418 , 0x00308 }, + { 0x004E5 , 0x00438 , 0x00308 }, + { 0x004E6 , 0x0041E , 0x00308 }, + { 0x004E7 , 0x0043E , 0x00308 }, + { 0x004EA , 0x004E8 , 0x00308 }, + { 0x004EB , 0x004E9 , 0x00308 }, + { 0x004EC , 0x0042D , 0x00308 }, + { 0x004ED , 0x0044D , 0x00308 }, + { 0x004EE , 0x00423 , 0x00304 }, + { 0x004EF , 0x00443 , 0x00304 }, + { 0x004F0 , 0x00423 , 0x00308 }, + { 0x004F1 , 0x00443 , 0x00308 }, + { 0x004F2 , 0x00423 , 0x0030B }, + { 0x004F3 , 0x00443 , 0x0030B }, + { 0x004F4 , 0x00427 , 0x00308 }, + { 0x004F5 , 0x00447 , 0x00308 }, + { 0x004F8 , 0x0042B , 0x00308 }, + { 0x004F9 , 0x0044B , 0x00308 }, + { 0x00622 , 0x00627 , 0x00653 }, + { 0x00623 , 0x00627 , 0x00654 }, + { 0x00624 , 0x00648 , 0x00654 }, + { 0x00625 , 0x00627 , 0x00655 }, + { 0x00626 , 0x0064A , 0x00654 }, + { 0x006C0 , 0x006D5 , 0x00654 }, + { 0x006C2 , 0x006C1 , 0x00654 }, + { 0x006D3 , 0x006D2 , 0x00654 }, + { 0x00929 , 0x00928 , 0x0093C }, + { 0x00931 , 0x00930 , 0x0093C }, + { 0x00934 , 0x00933 , 0x0093C }, + { 0x009CB , 0x009C7 , 0x009BE }, + { 0x009CC , 0x009C7 , 0x009D7 }, + { 0x00B48 , 0x00B47 , 0x00B56 }, + { 0x00B4B , 0x00B47 , 0x00B3E }, + { 0x00B4C , 0x00B47 , 0x00B57 }, + { 0x00B94 , 0x00B92 , 0x00BD7 }, + { 0x00BCA , 0x00BC6 , 0x00BBE }, + { 0x00BCB , 0x00BC7 , 0x00BBE }, + { 0x00BCC , 0x00BC6 , 0x00BD7 }, + { 0x00C48 , 0x00C46 , 0x00C56 }, + { 0x00CC0 , 0x00CBF , 0x00CD5 }, + { 0x00CC7 , 0x00CC6 , 0x00CD5 }, + { 0x00CC8 , 0x00CC6 , 0x00CD6 }, + { 0x00CCA , 0x00CC6 , 0x00CC2 }, + { 0x00CCB , 0x00CCA , 0x00CD5 }, + { 0x00D4A , 0x00D46 , 0x00D3E }, + { 0x00D4B , 0x00D47 , 0x00D3E }, + { 0x00D4C , 0x00D46 , 0x00D57 }, + { 0x00DDA , 0x00DD9 , 0x00DCA }, + { 0x00DDC , 0x00DD9 , 0x00DCF }, + { 0x00DDD , 0x00DDC , 0x00DCA }, + { 0x00DDE , 0x00DD9 , 0x00DDF }, + { 0x01026 , 0x01025 , 0x0102E }, + { 0x01B06 , 0x01B05 , 0x01B35 }, + { 0x01B08 , 0x01B07 , 0x01B35 }, + { 0x01B0A , 0x01B09 , 0x01B35 }, + { 0x01B0C , 0x01B0B , 0x01B35 }, + { 0x01B0E , 0x01B0D , 0x01B35 }, + { 0x01B12 , 0x01B11 , 0x01B35 }, + { 0x01B3B , 0x01B3A , 0x01B35 }, + { 0x01B3D , 0x01B3C , 0x01B35 }, + { 0x01B40 , 0x01B3E , 0x01B35 }, + { 0x01B41 , 0x01B3F , 0x01B35 }, + { 0x01B43 , 0x01B42 , 0x01B35 }, + { 0x01E00 , 0x00041 , 0x00325 }, + { 0x01E01 , 0x00061 , 0x00325 }, + { 0x01E02 , 0x00042 , 0x00307 }, + { 0x01E03 , 0x00062 , 0x00307 }, + { 0x01E04 , 0x00042 , 0x00323 }, + { 0x01E05 , 0x00062 , 0x00323 }, + { 0x01E06 , 0x00042 , 0x00331 }, + { 0x01E07 , 0x00062 , 0x00331 }, + { 0x01E08 , 0x000C7 , 0x00301 }, + { 0x01E09 , 0x000E7 , 0x00301 }, + { 0x01E0A , 0x00044 , 0x00307 }, + { 0x01E0B , 0x00064 , 0x00307 }, + { 0x01E0C , 0x00044 , 0x00323 }, + { 0x01E0D , 0x00064 , 0x00323 }, + { 0x01E0E , 0x00044 , 0x00331 }, + { 0x01E0F , 0x00064 , 0x00331 }, + { 0x01E10 , 0x00044 , 0x00327 }, + { 0x01E11 , 0x00064 , 0x00327 }, + { 0x01E12 , 0x00044 , 0x0032D }, + { 0x01E13 , 0x00064 , 0x0032D }, + { 0x01E14 , 0x00112 , 0x00300 }, + { 0x01E15 , 0x00113 , 0x00300 }, + { 0x01E16 , 0x00112 , 0x00301 }, + { 0x01E17 , 0x00113 , 0x00301 }, + { 0x01E18 , 0x00045 , 0x0032D }, + { 0x01E19 , 0x00065 , 0x0032D }, + { 0x01E1A , 0x00045 , 0x00330 }, + { 0x01E1B , 0x00065 , 0x00330 }, + { 0x01E1C , 0x00228 , 0x00306 }, + { 0x01E1D , 0x00229 , 0x00306 }, + { 0x01E1E , 0x00046 , 0x00307 }, + { 0x01E1F , 0x00066 , 0x00307 }, + { 0x01E20 , 0x00047 , 0x00304 }, + { 0x01E21 , 0x00067 , 0x00304 }, + { 0x01E22 , 0x00048 , 0x00307 }, + { 0x01E23 , 0x00068 , 0x00307 }, + { 0x01E24 , 0x00048 , 0x00323 }, + { 0x01E25 , 0x00068 , 0x00323 }, + { 0x01E26 , 0x00048 , 0x00308 }, + { 0x01E27 , 0x00068 , 0x00308 }, + { 0x01E28 , 0x00048 , 0x00327 }, + { 0x01E29 , 0x00068 , 0x00327 }, + { 0x01E2A , 0x00048 , 0x0032E }, + { 0x01E2B , 0x00068 , 0x0032E }, + { 0x01E2C , 0x00049 , 0x00330 }, + { 0x01E2D , 0x00069 , 0x00330 }, + { 0x01E2E , 0x000CF , 0x00301 }, + { 0x01E2F , 0x000EF , 0x00301 }, + { 0x01E30 , 0x0004B , 0x00301 }, + { 0x01E31 , 0x0006B , 0x00301 }, + { 0x01E32 , 0x0004B , 0x00323 }, + { 0x01E33 , 0x0006B , 0x00323 }, + { 0x01E34 , 0x0004B , 0x00331 }, + { 0x01E35 , 0x0006B , 0x00331 }, + { 0x01E36 , 0x0004C , 0x00323 }, + { 0x01E37 , 0x0006C , 0x00323 }, + { 0x01E38 , 0x01E36 , 0x00304 }, + { 0x01E39 , 0x01E37 , 0x00304 }, + { 0x01E3A , 0x0004C , 0x00331 }, + { 0x01E3B , 0x0006C , 0x00331 }, + { 0x01E3C , 0x0004C , 0x0032D }, + { 0x01E3D , 0x0006C , 0x0032D }, + { 0x01E3E , 0x0004D , 0x00301 }, + { 0x01E3F , 0x0006D , 0x00301 }, + { 0x01E40 , 0x0004D , 0x00307 }, + { 0x01E41 , 0x0006D , 0x00307 }, + { 0x01E42 , 0x0004D , 0x00323 }, + { 0x01E43 , 0x0006D , 0x00323 }, + { 0x01E44 , 0x0004E , 0x00307 }, + { 0x01E45 , 0x0006E , 0x00307 }, + { 0x01E46 , 0x0004E , 0x00323 }, + { 0x01E47 , 0x0006E , 0x00323 }, + { 0x01E48 , 0x0004E , 0x00331 }, + { 0x01E49 , 0x0006E , 0x00331 }, + { 0x01E4A , 0x0004E , 0x0032D }, + { 0x01E4B , 0x0006E , 0x0032D }, + { 0x01E4C , 0x000D5 , 0x00301 }, + { 0x01E4D , 0x000F5 , 0x00301 }, + { 0x01E4E , 0x000D5 , 0x00308 }, + { 0x01E4F , 0x000F5 , 0x00308 }, + { 0x01E50 , 0x0014C , 0x00300 }, + { 0x01E51 , 0x0014D , 0x00300 }, + { 0x01E52 , 0x0014C , 0x00301 }, + { 0x01E53 , 0x0014D , 0x00301 }, + { 0x01E54 , 0x00050 , 0x00301 }, + { 0x01E55 , 0x00070 , 0x00301 }, + { 0x01E56 , 0x00050 , 0x00307 }, + { 0x01E57 , 0x00070 , 0x00307 }, + { 0x01E58 , 0x00052 , 0x00307 }, + { 0x01E59 , 0x00072 , 0x00307 }, + { 0x01E5A , 0x00052 , 0x00323 }, + { 0x01E5B , 0x00072 , 0x00323 }, + { 0x01E5C , 0x01E5A , 0x00304 }, + { 0x01E5D , 0x01E5B , 0x00304 }, + { 0x01E5E , 0x00052 , 0x00331 }, + { 0x01E5F , 0x00072 , 0x00331 }, + { 0x01E60 , 0x00053 , 0x00307 }, + { 0x01E61 , 0x00073 , 0x00307 }, + { 0x01E62 , 0x00053 , 0x00323 }, + { 0x01E63 , 0x00073 , 0x00323 }, + { 0x01E64 , 0x0015A , 0x00307 }, + { 0x01E65 , 0x0015B , 0x00307 }, + { 0x01E66 , 0x00160 , 0x00307 }, + { 0x01E67 , 0x00161 , 0x00307 }, + { 0x01E68 , 0x01E62 , 0x00307 }, + { 0x01E69 , 0x01E63 , 0x00307 }, + { 0x01E6A , 0x00054 , 0x00307 }, + { 0x01E6B , 0x00074 , 0x00307 }, + { 0x01E6C , 0x00054 , 0x00323 }, + { 0x01E6D , 0x00074 , 0x00323 }, + { 0x01E6E , 0x00054 , 0x00331 }, + { 0x01E6F , 0x00074 , 0x00331 }, + { 0x01E70 , 0x00054 , 0x0032D }, + { 0x01E71 , 0x00074 , 0x0032D }, + { 0x01E72 , 0x00055 , 0x00324 }, + { 0x01E73 , 0x00075 , 0x00324 }, + { 0x01E74 , 0x00055 , 0x00330 }, + { 0x01E75 , 0x00075 , 0x00330 }, + { 0x01E76 , 0x00055 , 0x0032D }, + { 0x01E77 , 0x00075 , 0x0032D }, + { 0x01E78 , 0x00168 , 0x00301 }, + { 0x01E79 , 0x00169 , 0x00301 }, + { 0x01E7A , 0x0016A , 0x00308 }, + { 0x01E7B , 0x0016B , 0x00308 }, + { 0x01E7C , 0x00056 , 0x00303 }, + { 0x01E7D , 0x00076 , 0x00303 }, + { 0x01E7E , 0x00056 , 0x00323 }, + { 0x01E7F , 0x00076 , 0x00323 }, + { 0x01E80 , 0x00057 , 0x00300 }, + { 0x01E81 , 0x00077 , 0x00300 }, + { 0x01E82 , 0x00057 , 0x00301 }, + { 0x01E83 , 0x00077 , 0x00301 }, + { 0x01E84 , 0x00057 , 0x00308 }, + { 0x01E85 , 0x00077 , 0x00308 }, + { 0x01E86 , 0x00057 , 0x00307 }, + { 0x01E87 , 0x00077 , 0x00307 }, + { 0x01E88 , 0x00057 , 0x00323 }, + { 0x01E89 , 0x00077 , 0x00323 }, + { 0x01E8A , 0x00058 , 0x00307 }, + { 0x01E8B , 0x00078 , 0x00307 }, + { 0x01E8C , 0x00058 , 0x00308 }, + { 0x01E8D , 0x00078 , 0x00308 }, + { 0x01E8E , 0x00059 , 0x00307 }, + { 0x01E8F , 0x00079 , 0x00307 }, + { 0x01E90 , 0x0005A , 0x00302 }, + { 0x01E91 , 0x0007A , 0x00302 }, + { 0x01E92 , 0x0005A , 0x00323 }, + { 0x01E93 , 0x0007A , 0x00323 }, + { 0x01E94 , 0x0005A , 0x00331 }, + { 0x01E95 , 0x0007A , 0x00331 }, + { 0x01E96 , 0x00068 , 0x00331 }, + { 0x01E97 , 0x00074 , 0x00308 }, + { 0x01E98 , 0x00077 , 0x0030A }, + { 0x01E99 , 0x00079 , 0x0030A }, + { 0x01E9B , 0x0017F , 0x00307 }, + { 0x01EA0 , 0x00041 , 0x00323 }, + { 0x01EA1 , 0x00061 , 0x00323 }, + { 0x01EA2 , 0x00041 , 0x00309 }, + { 0x01EA3 , 0x00061 , 0x00309 }, + { 0x01EA4 , 0x000C2 , 0x00301 }, + { 0x01EA5 , 0x000E2 , 0x00301 }, + { 0x01EA6 , 0x000C2 , 0x00300 }, + { 0x01EA7 , 0x000E2 , 0x00300 }, + { 0x01EA8 , 0x000C2 , 0x00309 }, + { 0x01EA9 , 0x000E2 , 0x00309 }, + { 0x01EAA , 0x000C2 , 0x00303 }, + { 0x01EAB , 0x000E2 , 0x00303 }, + { 0x01EAC , 0x01EA0 , 0x00302 }, + { 0x01EAD , 0x01EA1 , 0x00302 }, + { 0x01EAE , 0x00102 , 0x00301 }, + { 0x01EAF , 0x00103 , 0x00301 }, + { 0x01EB0 , 0x00102 , 0x00300 }, + { 0x01EB1 , 0x00103 , 0x00300 }, + { 0x01EB2 , 0x00102 , 0x00309 }, + { 0x01EB3 , 0x00103 , 0x00309 }, + { 0x01EB4 , 0x00102 , 0x00303 }, + { 0x01EB5 , 0x00103 , 0x00303 }, + { 0x01EB6 , 0x01EA0 , 0x00306 }, + { 0x01EB7 , 0x01EA1 , 0x00306 }, + { 0x01EB8 , 0x00045 , 0x00323 }, + { 0x01EB9 , 0x00065 , 0x00323 }, + { 0x01EBA , 0x00045 , 0x00309 }, + { 0x01EBB , 0x00065 , 0x00309 }, + { 0x01EBC , 0x00045 , 0x00303 }, + { 0x01EBD , 0x00065 , 0x00303 }, + { 0x01EBE , 0x000CA , 0x00301 }, + { 0x01EBF , 0x000EA , 0x00301 }, + { 0x01EC0 , 0x000CA , 0x00300 }, + { 0x01EC1 , 0x000EA , 0x00300 }, + { 0x01EC2 , 0x000CA , 0x00309 }, + { 0x01EC3 , 0x000EA , 0x00309 }, + { 0x01EC4 , 0x000CA , 0x00303 }, + { 0x01EC5 , 0x000EA , 0x00303 }, + { 0x01EC6 , 0x01EB8 , 0x00302 }, + { 0x01EC7 , 0x01EB9 , 0x00302 }, + { 0x01EC8 , 0x00049 , 0x00309 }, + { 0x01EC9 , 0x00069 , 0x00309 }, + { 0x01ECA , 0x00049 , 0x00323 }, + { 0x01ECB , 0x00069 , 0x00323 }, + { 0x01ECC , 0x0004F , 0x00323 }, + { 0x01ECD , 0x0006F , 0x00323 }, + { 0x01ECE , 0x0004F , 0x00309 }, + { 0x01ECF , 0x0006F , 0x00309 }, + { 0x01ED0 , 0x000D4 , 0x00301 }, + { 0x01ED1 , 0x000F4 , 0x00301 }, + { 0x01ED2 , 0x000D4 , 0x00300 }, + { 0x01ED3 , 0x000F4 , 0x00300 }, + { 0x01ED4 , 0x000D4 , 0x00309 }, + { 0x01ED5 , 0x000F4 , 0x00309 }, + { 0x01ED6 , 0x000D4 , 0x00303 }, + { 0x01ED7 , 0x000F4 , 0x00303 }, + { 0x01ED8 , 0x01ECC , 0x00302 }, + { 0x01ED9 , 0x01ECD , 0x00302 }, + { 0x01EDA , 0x001A0 , 0x00301 }, + { 0x01EDB , 0x001A1 , 0x00301 }, + { 0x01EDC , 0x001A0 , 0x00300 }, + { 0x01EDD , 0x001A1 , 0x00300 }, + { 0x01EDE , 0x001A0 , 0x00309 }, + { 0x01EDF , 0x001A1 , 0x00309 }, + { 0x01EE0 , 0x001A0 , 0x00303 }, + { 0x01EE1 , 0x001A1 , 0x00303 }, + { 0x01EE2 , 0x001A0 , 0x00323 }, + { 0x01EE3 , 0x001A1 , 0x00323 }, + { 0x01EE4 , 0x00055 , 0x00323 }, + { 0x01EE5 , 0x00075 , 0x00323 }, + { 0x01EE6 , 0x00055 , 0x00309 }, + { 0x01EE7 , 0x00075 , 0x00309 }, + { 0x01EE8 , 0x001AF , 0x00301 }, + { 0x01EE9 , 0x001B0 , 0x00301 }, + { 0x01EEA , 0x001AF , 0x00300 }, + { 0x01EEB , 0x001B0 , 0x00300 }, + { 0x01EEC , 0x001AF , 0x00309 }, + { 0x01EED , 0x001B0 , 0x00309 }, + { 0x01EEE , 0x001AF , 0x00303 }, + { 0x01EEF , 0x001B0 , 0x00303 }, + { 0x01EF0 , 0x001AF , 0x00323 }, + { 0x01EF1 , 0x001B0 , 0x00323 }, + { 0x01EF2 , 0x00059 , 0x00300 }, + { 0x01EF3 , 0x00079 , 0x00300 }, + { 0x01EF4 , 0x00059 , 0x00323 }, + { 0x01EF5 , 0x00079 , 0x00323 }, + { 0x01EF6 , 0x00059 , 0x00309 }, + { 0x01EF7 , 0x00079 , 0x00309 }, + { 0x01EF8 , 0x00059 , 0x00303 }, + { 0x01EF9 , 0x00079 , 0x00303 }, + { 0x01F00 , 0x003B1 , 0x00313 }, + { 0x01F01 , 0x003B1 , 0x00314 }, + { 0x01F02 , 0x01F00 , 0x00300 }, + { 0x01F03 , 0x01F01 , 0x00300 }, + { 0x01F04 , 0x01F00 , 0x00301 }, + { 0x01F05 , 0x01F01 , 0x00301 }, + { 0x01F06 , 0x01F00 , 0x00342 }, + { 0x01F07 , 0x01F01 , 0x00342 }, + { 0x01F08 , 0x00391 , 0x00313 }, + { 0x01F09 , 0x00391 , 0x00314 }, + { 0x01F0A , 0x01F08 , 0x00300 }, + { 0x01F0B , 0x01F09 , 0x00300 }, + { 0x01F0C , 0x01F08 , 0x00301 }, + { 0x01F0D , 0x01F09 , 0x00301 }, + { 0x01F0E , 0x01F08 , 0x00342 }, + { 0x01F0F , 0x01F09 , 0x00342 }, + { 0x01F10 , 0x003B5 , 0x00313 }, + { 0x01F11 , 0x003B5 , 0x00314 }, + { 0x01F12 , 0x01F10 , 0x00300 }, + { 0x01F13 , 0x01F11 , 0x00300 }, + { 0x01F14 , 0x01F10 , 0x00301 }, + { 0x01F15 , 0x01F11 , 0x00301 }, + { 0x01F18 , 0x00395 , 0x00313 }, + { 0x01F19 , 0x00395 , 0x00314 }, + { 0x01F1A , 0x01F18 , 0x00300 }, + { 0x01F1B , 0x01F19 , 0x00300 }, + { 0x01F1C , 0x01F18 , 0x00301 }, + { 0x01F1D , 0x01F19 , 0x00301 }, + { 0x01F20 , 0x003B7 , 0x00313 }, + { 0x01F21 , 0x003B7 , 0x00314 }, + { 0x01F22 , 0x01F20 , 0x00300 }, + { 0x01F23 , 0x01F21 , 0x00300 }, + { 0x01F24 , 0x01F20 , 0x00301 }, + { 0x01F25 , 0x01F21 , 0x00301 }, + { 0x01F26 , 0x01F20 , 0x00342 }, + { 0x01F27 , 0x01F21 , 0x00342 }, + { 0x01F28 , 0x00397 , 0x00313 }, + { 0x01F29 , 0x00397 , 0x00314 }, + { 0x01F2A , 0x01F28 , 0x00300 }, + { 0x01F2B , 0x01F29 , 0x00300 }, + { 0x01F2C , 0x01F28 , 0x00301 }, + { 0x01F2D , 0x01F29 , 0x00301 }, + { 0x01F2E , 0x01F28 , 0x00342 }, + { 0x01F2F , 0x01F29 , 0x00342 }, + { 0x01F30 , 0x003B9 , 0x00313 }, + { 0x01F31 , 0x003B9 , 0x00314 }, + { 0x01F32 , 0x01F30 , 0x00300 }, + { 0x01F33 , 0x01F31 , 0x00300 }, + { 0x01F34 , 0x01F30 , 0x00301 }, + { 0x01F35 , 0x01F31 , 0x00301 }, + { 0x01F36 , 0x01F30 , 0x00342 }, + { 0x01F37 , 0x01F31 , 0x00342 }, + { 0x01F38 , 0x00399 , 0x00313 }, + { 0x01F39 , 0x00399 , 0x00314 }, + { 0x01F3A , 0x01F38 , 0x00300 }, + { 0x01F3B , 0x01F39 , 0x00300 }, + { 0x01F3C , 0x01F38 , 0x00301 }, + { 0x01F3D , 0x01F39 , 0x00301 }, + { 0x01F3E , 0x01F38 , 0x00342 }, + { 0x01F3F , 0x01F39 , 0x00342 }, + { 0x01F40 , 0x003BF , 0x00313 }, + { 0x01F41 , 0x003BF , 0x00314 }, + { 0x01F42 , 0x01F40 , 0x00300 }, + { 0x01F43 , 0x01F41 , 0x00300 }, + { 0x01F44 , 0x01F40 , 0x00301 }, + { 0x01F45 , 0x01F41 , 0x00301 }, + { 0x01F48 , 0x0039F , 0x00313 }, + { 0x01F49 , 0x0039F , 0x00314 }, + { 0x01F4A , 0x01F48 , 0x00300 }, + { 0x01F4B , 0x01F49 , 0x00300 }, + { 0x01F4C , 0x01F48 , 0x00301 }, + { 0x01F4D , 0x01F49 , 0x00301 }, + { 0x01F50 , 0x003C5 , 0x00313 }, + { 0x01F51 , 0x003C5 , 0x00314 }, + { 0x01F52 , 0x01F50 , 0x00300 }, + { 0x01F53 , 0x01F51 , 0x00300 }, + { 0x01F54 , 0x01F50 , 0x00301 }, + { 0x01F55 , 0x01F51 , 0x00301 }, + { 0x01F56 , 0x01F50 , 0x00342 }, + { 0x01F57 , 0x01F51 , 0x00342 }, + { 0x01F59 , 0x003A5 , 0x00314 }, + { 0x01F5B , 0x01F59 , 0x00300 }, + { 0x01F5D , 0x01F59 , 0x00301 }, + { 0x01F5F , 0x01F59 , 0x00342 }, + { 0x01F60 , 0x003C9 , 0x00313 }, + { 0x01F61 , 0x003C9 , 0x00314 }, + { 0x01F62 , 0x01F60 , 0x00300 }, + { 0x01F63 , 0x01F61 , 0x00300 }, + { 0x01F64 , 0x01F60 , 0x00301 }, + { 0x01F65 , 0x01F61 , 0x00301 }, + { 0x01F66 , 0x01F60 , 0x00342 }, + { 0x01F67 , 0x01F61 , 0x00342 }, + { 0x01F68 , 0x003A9 , 0x00313 }, + { 0x01F69 , 0x003A9 , 0x00314 }, + { 0x01F6A , 0x01F68 , 0x00300 }, + { 0x01F6B , 0x01F69 , 0x00300 }, + { 0x01F6C , 0x01F68 , 0x00301 }, + { 0x01F6D , 0x01F69 , 0x00301 }, + { 0x01F6E , 0x01F68 , 0x00342 }, + { 0x01F6F , 0x01F69 , 0x00342 }, + { 0x01F70 , 0x003B1 , 0x00300 }, + { 0x01F72 , 0x003B5 , 0x00300 }, + { 0x01F74 , 0x003B7 , 0x00300 }, + { 0x01F76 , 0x003B9 , 0x00300 }, + { 0x01F78 , 0x003BF , 0x00300 }, + { 0x01F7A , 0x003C5 , 0x00300 }, + { 0x01F7C , 0x003C9 , 0x00300 }, + { 0x01F80 , 0x01F00 , 0x00345 }, + { 0x01F81 , 0x01F01 , 0x00345 }, + { 0x01F82 , 0x01F02 , 0x00345 }, + { 0x01F83 , 0x01F03 , 0x00345 }, + { 0x01F84 , 0x01F04 , 0x00345 }, + { 0x01F85 , 0x01F05 , 0x00345 }, + { 0x01F86 , 0x01F06 , 0x00345 }, + { 0x01F87 , 0x01F07 , 0x00345 }, + { 0x01F88 , 0x01F08 , 0x00345 }, + { 0x01F89 , 0x01F09 , 0x00345 }, + { 0x01F8A , 0x01F0A , 0x00345 }, + { 0x01F8B , 0x01F0B , 0x00345 }, + { 0x01F8C , 0x01F0C , 0x00345 }, + { 0x01F8D , 0x01F0D , 0x00345 }, + { 0x01F8E , 0x01F0E , 0x00345 }, + { 0x01F8F , 0x01F0F , 0x00345 }, + { 0x01F90 , 0x01F20 , 0x00345 }, + { 0x01F91 , 0x01F21 , 0x00345 }, + { 0x01F92 , 0x01F22 , 0x00345 }, + { 0x01F93 , 0x01F23 , 0x00345 }, + { 0x01F94 , 0x01F24 , 0x00345 }, + { 0x01F95 , 0x01F25 , 0x00345 }, + { 0x01F96 , 0x01F26 , 0x00345 }, + { 0x01F97 , 0x01F27 , 0x00345 }, + { 0x01F98 , 0x01F28 , 0x00345 }, + { 0x01F99 , 0x01F29 , 0x00345 }, + { 0x01F9A , 0x01F2A , 0x00345 }, + { 0x01F9B , 0x01F2B , 0x00345 }, + { 0x01F9C , 0x01F2C , 0x00345 }, + { 0x01F9D , 0x01F2D , 0x00345 }, + { 0x01F9E , 0x01F2E , 0x00345 }, + { 0x01F9F , 0x01F2F , 0x00345 }, + { 0x01FA0 , 0x01F60 , 0x00345 }, + { 0x01FA1 , 0x01F61 , 0x00345 }, + { 0x01FA2 , 0x01F62 , 0x00345 }, + { 0x01FA3 , 0x01F63 , 0x00345 }, + { 0x01FA4 , 0x01F64 , 0x00345 }, + { 0x01FA5 , 0x01F65 , 0x00345 }, + { 0x01FA6 , 0x01F66 , 0x00345 }, + { 0x01FA7 , 0x01F67 , 0x00345 }, + { 0x01FA8 , 0x01F68 , 0x00345 }, + { 0x01FA9 , 0x01F69 , 0x00345 }, + { 0x01FAA , 0x01F6A , 0x00345 }, + { 0x01FAB , 0x01F6B , 0x00345 }, + { 0x01FAC , 0x01F6C , 0x00345 }, + { 0x01FAD , 0x01F6D , 0x00345 }, + { 0x01FAE , 0x01F6E , 0x00345 }, + { 0x01FAF , 0x01F6F , 0x00345 }, + { 0x01FB0 , 0x003B1 , 0x00306 }, + { 0x01FB1 , 0x003B1 , 0x00304 }, + { 0x01FB2 , 0x01F70 , 0x00345 }, + { 0x01FB3 , 0x003B1 , 0x00345 }, + { 0x01FB4 , 0x003AC , 0x00345 }, + { 0x01FB6 , 0x003B1 , 0x00342 }, + { 0x01FB7 , 0x01FB6 , 0x00345 }, + { 0x01FB8 , 0x00391 , 0x00306 }, + { 0x01FB9 , 0x00391 , 0x00304 }, + { 0x01FBA , 0x00391 , 0x00300 }, + { 0x01FBC , 0x00391 , 0x00345 }, + { 0x01FC1 , 0x000A8 , 0x00342 }, + { 0x01FC2 , 0x01F74 , 0x00345 }, + { 0x01FC3 , 0x003B7 , 0x00345 }, + { 0x01FC4 , 0x003AE , 0x00345 }, + { 0x01FC6 , 0x003B7 , 0x00342 }, + { 0x01FC7 , 0x01FC6 , 0x00345 }, + { 0x01FC8 , 0x00395 , 0x00300 }, + { 0x01FCA , 0x00397 , 0x00300 }, + { 0x01FCC , 0x00397 , 0x00345 }, + { 0x01FCD , 0x01FBF , 0x00300 }, + { 0x01FCE , 0x01FBF , 0x00301 }, + { 0x01FCF , 0x01FBF , 0x00342 }, + { 0x01FD0 , 0x003B9 , 0x00306 }, + { 0x01FD1 , 0x003B9 , 0x00304 }, + { 0x01FD2 , 0x003CA , 0x00300 }, + { 0x01FD6 , 0x003B9 , 0x00342 }, + { 0x01FD7 , 0x003CA , 0x00342 }, + { 0x01FD8 , 0x00399 , 0x00306 }, + { 0x01FD9 , 0x00399 , 0x00304 }, + { 0x01FDA , 0x00399 , 0x00300 }, + { 0x01FDD , 0x01FFE , 0x00300 }, + { 0x01FDE , 0x01FFE , 0x00301 }, + { 0x01FDF , 0x01FFE , 0x00342 }, + { 0x01FE0 , 0x003C5 , 0x00306 }, + { 0x01FE1 , 0x003C5 , 0x00304 }, + { 0x01FE2 , 0x003CB , 0x00300 }, + { 0x01FE4 , 0x003C1 , 0x00313 }, + { 0x01FE5 , 0x003C1 , 0x00314 }, + { 0x01FE6 , 0x003C5 , 0x00342 }, + { 0x01FE7 , 0x003CB , 0x00342 }, + { 0x01FE8 , 0x003A5 , 0x00306 }, + { 0x01FE9 , 0x003A5 , 0x00304 }, + { 0x01FEA , 0x003A5 , 0x00300 }, + { 0x01FEC , 0x003A1 , 0x00314 }, + { 0x01FED , 0x000A8 , 0x00300 }, + { 0x01FF2 , 0x01F7C , 0x00345 }, + { 0x01FF3 , 0x003C9 , 0x00345 }, + { 0x01FF4 , 0x003CE , 0x00345 }, + { 0x01FF6 , 0x003C9 , 0x00342 }, + { 0x01FF7 , 0x01FF6 , 0x00345 }, + { 0x01FF8 , 0x0039F , 0x00300 }, + { 0x01FFA , 0x003A9 , 0x00300 }, + { 0x01FFC , 0x003A9 , 0x00345 }, + { 0x0219A , 0x02190 , 0x00338 }, + { 0x0219B , 0x02192 , 0x00338 }, + { 0x021AE , 0x02194 , 0x00338 }, + { 0x021CD , 0x021D0 , 0x00338 }, + { 0x021CE , 0x021D4 , 0x00338 }, + { 0x021CF , 0x021D2 , 0x00338 }, + { 0x02204 , 0x02203 , 0x00338 }, + { 0x02209 , 0x02208 , 0x00338 }, + { 0x0220C , 0x0220B , 0x00338 }, + { 0x02224 , 0x02223 , 0x00338 }, + { 0x02226 , 0x02225 , 0x00338 }, + { 0x02241 , 0x0223C , 0x00338 }, + { 0x02244 , 0x02243 , 0x00338 }, + { 0x02247 , 0x02245 , 0x00338 }, + { 0x02249 , 0x02248 , 0x00338 }, + { 0x02260 , 0x0003D , 0x00338 }, + { 0x02262 , 0x02261 , 0x00338 }, + { 0x0226D , 0x0224D , 0x00338 }, + { 0x0226E , 0x0003C , 0x00338 }, + { 0x0226F , 0x0003E , 0x00338 }, + { 0x02270 , 0x02264 , 0x00338 }, + { 0x02271 , 0x02265 , 0x00338 }, + { 0x02274 , 0x02272 , 0x00338 }, + { 0x02275 , 0x02273 , 0x00338 }, + { 0x02278 , 0x02276 , 0x00338 }, + { 0x02279 , 0x02277 , 0x00338 }, + { 0x02280 , 0x0227A , 0x00338 }, + { 0x02281 , 0x0227B , 0x00338 }, + { 0x02284 , 0x02282 , 0x00338 }, + { 0x02285 , 0x02283 , 0x00338 }, + { 0x02288 , 0x02286 , 0x00338 }, + { 0x02289 , 0x02287 , 0x00338 }, + { 0x022AC , 0x022A2 , 0x00338 }, + { 0x022AD , 0x022A8 , 0x00338 }, + { 0x022AE , 0x022A9 , 0x00338 }, + { 0x022AF , 0x022AB , 0x00338 }, + { 0x022E0 , 0x0227C , 0x00338 }, + { 0x022E1 , 0x0227D , 0x00338 }, + { 0x022E2 , 0x02291 , 0x00338 }, + { 0x022E3 , 0x02292 , 0x00338 }, + { 0x022EA , 0x022B2 , 0x00338 }, + { 0x022EB , 0x022B3 , 0x00338 }, + { 0x022EC , 0x022B4 , 0x00338 }, + { 0x022ED , 0x022B5 , 0x00338 }, + { 0x0304C , 0x0304B , 0x03099 }, + { 0x0304E , 0x0304D , 0x03099 }, + { 0x03050 , 0x0304F , 0x03099 }, + { 0x03052 , 0x03051 , 0x03099 }, + { 0x03054 , 0x03053 , 0x03099 }, + { 0x03056 , 0x03055 , 0x03099 }, + { 0x03058 , 0x03057 , 0x03099 }, + { 0x0305A , 0x03059 , 0x03099 }, + { 0x0305C , 0x0305B , 0x03099 }, + { 0x0305E , 0x0305D , 0x03099 }, + { 0x03060 , 0x0305F , 0x03099 }, + { 0x03062 , 0x03061 , 0x03099 }, + { 0x03065 , 0x03064 , 0x03099 }, + { 0x03067 , 0x03066 , 0x03099 }, + { 0x03069 , 0x03068 , 0x03099 }, + { 0x03070 , 0x0306F , 0x03099 }, + { 0x03071 , 0x0306F , 0x0309A }, + { 0x03073 , 0x03072 , 0x03099 }, + { 0x03074 , 0x03072 , 0x0309A }, + { 0x03076 , 0x03075 , 0x03099 }, + { 0x03077 , 0x03075 , 0x0309A }, + { 0x03079 , 0x03078 , 0x03099 }, + { 0x0307A , 0x03078 , 0x0309A }, + { 0x0307C , 0x0307B , 0x03099 }, + { 0x0307D , 0x0307B , 0x0309A }, + { 0x03094 , 0x03046 , 0x03099 }, + { 0x0309E , 0x0309D , 0x03099 }, + { 0x030AC , 0x030AB , 0x03099 }, + { 0x030AE , 0x030AD , 0x03099 }, + { 0x030B0 , 0x030AF , 0x03099 }, + { 0x030B2 , 0x030B1 , 0x03099 }, + { 0x030B4 , 0x030B3 , 0x03099 }, + { 0x030B6 , 0x030B5 , 0x03099 }, + { 0x030B8 , 0x030B7 , 0x03099 }, + { 0x030BA , 0x030B9 , 0x03099 }, + { 0x030BC , 0x030BB , 0x03099 }, + { 0x030BE , 0x030BD , 0x03099 }, + { 0x030C0 , 0x030BF , 0x03099 }, + { 0x030C2 , 0x030C1 , 0x03099 }, + { 0x030C5 , 0x030C4 , 0x03099 }, + { 0x030C7 , 0x030C6 , 0x03099 }, + { 0x030C9 , 0x030C8 , 0x03099 }, + { 0x030D0 , 0x030CF , 0x03099 }, + { 0x030D1 , 0x030CF , 0x0309A }, + { 0x030D3 , 0x030D2 , 0x03099 }, + { 0x030D4 , 0x030D2 , 0x0309A }, + { 0x030D6 , 0x030D5 , 0x03099 }, + { 0x030D7 , 0x030D5 , 0x0309A }, + { 0x030D9 , 0x030D8 , 0x03099 }, + { 0x030DA , 0x030D8 , 0x0309A }, + { 0x030DC , 0x030DB , 0x03099 }, + { 0x030DD , 0x030DB , 0x0309A }, + { 0x030F4 , 0x030A6 , 0x03099 }, + { 0x030F7 , 0x030EF , 0x03099 }, + { 0x030F8 , 0x030F0 , 0x03099 }, + { 0x030F9 , 0x030F1 , 0x03099 }, + { 0x030FA , 0x030F2 , 0x03099 }, + { 0x030FE , 0x030FD , 0x03099 }, + { 0x1109A , 0x11099 , 0x110BA }, + { 0x1109C , 0x1109B , 0x110BA }, + { 0x110AB , 0x110A5 , 0x110BA }, +}; + +#endif /* ARCHIVE_STRING_COMPOSITION_H_INCLUDED */ + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_string_sprintf.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_string_sprintf.c new file mode 100644 index 0000000000..969a5603a4 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_string_sprintf.c @@ -0,0 +1,192 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_string_sprintf.c 189435 2009-03-06 05:14:55Z kientzle $"); + +/* + * The use of printf()-family functions can be troublesome + * for space-constrained applications. In addition, correctly + * implementing this function in terms of vsnprintf() requires + * two calls (one to determine the size, another to format the + * result), which in turn requires duplicating the argument list + * using va_copy, which isn't yet universally available. <sigh> + * + * So, I've implemented a bare minimum of printf()-like capability + * here. This is only used to format error messages, so doesn't + * require any floating-point support or field-width handling. + */ +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> + +#include "archive_string.h" +#include "archive_private.h" + +/* + * Utility functions to format signed/unsigned integers and append + * them to an archive_string. + */ +static void +append_uint(struct archive_string *as, uintmax_t d, unsigned base) +{ + static const char digits[] = "0123456789abcdef"; + if (d >= base) + append_uint(as, d/base, base); + archive_strappend_char(as, digits[d % base]); +} + +static void +append_int(struct archive_string *as, intmax_t d, unsigned base) +{ + uintmax_t ud; + + if (d < 0) { + archive_strappend_char(as, '-'); + ud = (d == INTMAX_MIN) ? (uintmax_t)(INTMAX_MAX) + 1 : (uintmax_t)(-d); + } else + ud = d; + append_uint(as, ud, base); +} + + +void +archive_string_sprintf(struct archive_string *as, const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + archive_string_vsprintf(as, fmt, ap); + va_end(ap); +} + +/* + * Like 'vsprintf', but ensures the target is big enough, resizing if + * necessary. + */ +void +archive_string_vsprintf(struct archive_string *as, const char *fmt, + va_list ap) +{ + char long_flag; + intmax_t s; /* Signed integer temp. */ + uintmax_t u; /* Unsigned integer temp. */ + const char *p, *p2; + const wchar_t *pw; + + if (archive_string_ensure(as, 64) == NULL) + __archive_errx(1, "Out of memory"); + + if (fmt == NULL) { + as->s[0] = 0; + return; + } + + for (p = fmt; *p != '\0'; p++) { + const char *saved_p = p; + + if (*p != '%') { + archive_strappend_char(as, *p); + continue; + } + + p++; + + long_flag = '\0'; + switch(*p) { + case 'j': + case 'l': + case 'z': + long_flag = *p; + p++; + break; + } + + switch (*p) { + case '%': + archive_strappend_char(as, '%'); + break; + case 'c': + s = va_arg(ap, int); + archive_strappend_char(as, (char)s); + break; + case 'd': + switch(long_flag) { + case 'j': s = va_arg(ap, intmax_t); break; + case 'l': s = va_arg(ap, long); break; + case 'z': s = va_arg(ap, ssize_t); break; + default: s = va_arg(ap, int); break; + } + append_int(as, s, 10); + break; + case 's': + switch(long_flag) { + case 'l': + pw = va_arg(ap, wchar_t *); + if (pw == NULL) + pw = L"(null)"; + if (archive_string_append_from_wcs(as, pw, + wcslen(pw)) != 0 && errno == ENOMEM) + __archive_errx(1, "Out of memory"); + break; + default: + p2 = va_arg(ap, char *); + if (p2 == NULL) + p2 = "(null)"; + archive_strcat(as, p2); + break; + } + break; + case 'S': + pw = va_arg(ap, wchar_t *); + if (pw == NULL) + pw = L"(null)"; + if (archive_string_append_from_wcs(as, pw, + wcslen(pw)) != 0 && errno == ENOMEM) + __archive_errx(1, "Out of memory"); + break; + case 'o': case 'u': case 'x': case 'X': + /* Common handling for unsigned integer formats. */ + switch(long_flag) { + case 'j': u = va_arg(ap, uintmax_t); break; + case 'l': u = va_arg(ap, unsigned long); break; + case 'z': u = va_arg(ap, size_t); break; + default: u = va_arg(ap, unsigned int); break; + } + /* Format it in the correct base. */ + switch (*p) { + case 'o': append_uint(as, u, 8); break; + case 'u': append_uint(as, u, 10); break; + default: append_uint(as, u, 16); break; + } + break; + default: + /* Rewind and print the initial '%' literally. */ + p = saved_p; + archive_strappend_char(as, *p); + } + } +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_util.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_util.3 new file mode 100644 index 0000000000..d5d4e7dfd7 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_util.3 @@ -0,0 +1,224 @@ +.\" Copyright (c) 2003-2007 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_UTIL 3 +.Os +.Sh NAME +.Nm archive_clear_error , +.Nm archive_compression , +.Nm archive_compression_name , +.Nm archive_copy_error , +.Nm archive_errno , +.Nm archive_error_string , +.Nm archive_file_count , +.Nm archive_filter_code , +.Nm archive_filter_count , +.Nm archive_filter_name , +.Nm archive_format , +.Nm archive_format_name , +.Nm archive_position , +.Nm archive_set_error +.Nd libarchive utility functions +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft void +.Fn archive_clear_error "struct archive *" +.Ft int +.Fn archive_compression "struct archive *" +.Ft const char * +.Fn archive_compression_name "struct archive *" +.Ft void +.Fn archive_copy_error "struct archive *" "struct archive *" +.Ft int +.Fn archive_errno "struct archive *" +.Ft const char * +.Fn archive_error_string "struct archive *" +.Ft int +.Fn archive_file_count "struct archive *" +.Ft int +.Fn archive_filter_code "struct archive *" "int" +.Ft int +.Fn archive_filter_count "struct archive *" "int" +.Ft const char * +.Fn archive_filter_name "struct archive *" "int" +.Ft int +.Fn archive_format "struct archive *" +.Ft const char * +.Fn archive_format_name "struct archive *" +.Ft int64_t +.Fn archive_position "struct archive *" "int" +.Ft void +.Fo archive_set_error +.Fa "struct archive *" +.Fa "int error_code" +.Fa "const char *fmt" +.Fa "..." +.Fc +.Sh DESCRIPTION +These functions provide access to various information about the +.Tn struct archive +object used in the +.Xr libarchive 3 +library. +.Bl -tag -compact -width indent +.It Fn archive_clear_error +Clears any error information left over from a previous call. +Not generally used in client code. +.It Fn archive_compression +Synonym for +.Fn archive_filter_code a 0 . +.It Fn archive_compression_name +Synonym for +.Fn archive_filter_name a 0 . +.It Fn archive_copy_error +Copies error information from one archive to another. +.It Fn archive_errno +Returns a numeric error code (see +.Xr errno 2 ) +indicating the reason for the most recent error return. +Note that this can not be reliably used to detect whether an +error has occurred. +It should be used only after another libarchive function +has returned an error status. +.It Fn archive_error_string +Returns a textual error message suitable for display. +The error message here is usually more specific than that +obtained from passing the result of +.Fn archive_errno +to +.Xr strerror 3 . +.It Fn archive_file_count +Returns a count of the number of files processed by this archive object. +The count is incremented by calls to +.Xr archive_write_header 3 +or +.Xr archive_read_next_header 3 . +.It Fn archive_filter_code +Returns a numeric code identifying the indicated filter. +See +.Fn archive_filter_count +for details of the numbering. +.It Fn archive_filter_count +Returns the number of filters in the current pipeline. +For read archive handles, these filters are added automatically +by the automatic format detection. +For write archive handles, these filters are added by calls to the various +.Fn archive_write_add_filter_XXX +functions. +Filters in the resulting pipeline are numbered so that filter 0 +is the filter closest to the format handler. +As a convenience, functions that expect a filter number will +accept -1 as a synonym for the highest-numbered filter. +.Pp +For example, when reading a uuencoded gzipped tar archive, there +are three filters: +filter 0 is the gunzip filter, +filter 1 is the uudecode filter, +and filter 2 is the pseudo-filter that wraps the archive read functions. +In this case, requesting +.Fn archive_position a -1 +would be a synonym for +.Fn archive_position a 2 +which would return the number of bytes currently read from the archive, while +.Fn archive_position a 1 +would return the number of bytes after uudecoding, and +.Fn archive_position a 0 +would return the number of bytes after decompression. +.It Fn archive_filter_name +Returns a textual name identifying the indicated filter. +See +.Fn archive_filter_count +for details of the numbering. +.It Fn archive_format +Returns a numeric code indicating the format of the current +archive entry. +This value is set by a successful call to +.Fn archive_read_next_header . +Note that it is common for this value to change from +entry to entry. +For example, a tar archive might have several entries that +utilize GNU tar extensions and several entries that do not. +These entries will have different format codes. +.It Fn archive_format_name +A textual description of the format of the current entry. +.It Fn archive_position +Returns the number of bytes read from or written to the indicated filter. +In particular, +.Fn archive_position a 0 +returns the number of bytes read or written by the format handler, while +.Fn archive_position a -1 +returns the number of bytes read or written to the archive. +See +.Fn archive_filter_count +for details of the numbering here. +.It Fn archive_set_error +Sets the numeric error code and error description that will be returned +by +.Fn archive_errno +and +.Fn archive_error_string . +This function should be used within I/O callbacks to set system-specific +error codes and error descriptions. +This function accepts a printf-like format string and arguments. +However, you should be careful to use only the following printf +format specifiers: +.Dq %c , +.Dq %d , +.Dq %jd , +.Dq %jo , +.Dq %ju , +.Dq %jx , +.Dq %ld , +.Dq %lo , +.Dq %lu , +.Dq %lx , +.Dq %o , +.Dq %u , +.Dq %s , +.Dq %x , +.Dq %% . +Field-width specifiers and other printf features are +not uniformly supported and should not be used. +.El +.Sh SEE ALSO +.Xr archive_read 3 , +.Xr archive_write 3 , +.Xr libarchive 3 , +.Xr printf 3 +.Sh HISTORY +The +.Nm libarchive +library first appeared in +.Fx 5.3 . +.Sh AUTHORS +.An -nosplit +The +.Nm libarchive +library was written by +.An Tim Kientzle Aq kientzle@acm.org . diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_util.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_util.c new file mode 100644 index 0000000000..c76ecc5b05 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_util.c @@ -0,0 +1,650 @@ +/*- + * Copyright (c) 2009-2012,2014 Michihiro NAKAJIMA + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_util.c 201098 2009-12-28 02:58:14Z kientzle $"); + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#if defined(HAVE_WINCRYPT_H) && !defined(__CYGWIN__) +#include <wincrypt.h> +#endif +#ifdef HAVE_ZLIB_H +#include <zlib.h> +#endif +#ifdef HAVE_LZMA_H +#include <lzma.h> +#endif +#ifdef HAVE_BZLIB_H +#include <bzlib.h> +#endif +#ifdef HAVE_LZ4_H +#include <lz4.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_random_private.h" +#include "archive_string.h" + +#ifndef O_CLOEXEC +#define O_CLOEXEC 0 +#endif + +static int archive_utility_string_sort_helper(char **, unsigned int); + +/* Generic initialization of 'struct archive' objects. */ +int +__archive_clean(struct archive *a) +{ + archive_string_conversion_free(a); + return (ARCHIVE_OK); +} + +int +archive_version_number(void) +{ + return (ARCHIVE_VERSION_NUMBER); +} + +const char * +archive_version_string(void) +{ + return (ARCHIVE_VERSION_STRING); +} + +int +archive_errno(struct archive *a) +{ + return (a->archive_error_number); +} + +const char * +archive_error_string(struct archive *a) +{ + + if (a->error != NULL && *a->error != '\0') + return (a->error); + else + return (NULL); +} + +int +archive_file_count(struct archive *a) +{ + return (a->file_count); +} + +int +archive_format(struct archive *a) +{ + return (a->archive_format); +} + +const char * +archive_format_name(struct archive *a) +{ + return (a->archive_format_name); +} + + +int +archive_compression(struct archive *a) +{ + return archive_filter_code(a, 0); +} + +const char * +archive_compression_name(struct archive *a) +{ + return archive_filter_name(a, 0); +} + + +/* + * Return a count of the number of compressed bytes processed. + */ +la_int64_t +archive_position_compressed(struct archive *a) +{ + return archive_filter_bytes(a, -1); +} + +/* + * Return a count of the number of uncompressed bytes processed. + */ +la_int64_t +archive_position_uncompressed(struct archive *a) +{ + return archive_filter_bytes(a, 0); +} + +void +archive_clear_error(struct archive *a) +{ + archive_string_empty(&a->error_string); + a->error = NULL; + a->archive_error_number = 0; +} + +void +archive_set_error(struct archive *a, int error_number, const char *fmt, ...) +{ + va_list ap; + + a->archive_error_number = error_number; + if (fmt == NULL) { + a->error = NULL; + return; + } + + archive_string_empty(&(a->error_string)); + va_start(ap, fmt); + archive_string_vsprintf(&(a->error_string), fmt, ap); + va_end(ap); + a->error = a->error_string.s; +} + +void +archive_copy_error(struct archive *dest, struct archive *src) +{ + dest->archive_error_number = src->archive_error_number; + + archive_string_copy(&dest->error_string, &src->error_string); + dest->error = dest->error_string.s; +} + +void +__archive_errx(int retvalue, const char *msg) +{ + static const char msg1[] = "Fatal Internal Error in libarchive: "; + size_t s; + + s = write(2, msg1, strlen(msg1)); + (void)s; /* UNUSED */ + s = write(2, msg, strlen(msg)); + (void)s; /* UNUSED */ + s = write(2, "\n", 1); + (void)s; /* UNUSED */ + exit(retvalue); +} + +/* + * Create a temporary file + */ +#if defined(_WIN32) && !defined(__CYGWIN__) + +/* + * Do not use Windows tmpfile() function. + * It will make a temporary file under the root directory + * and it'll cause permission error if a user who is + * non-Administrator creates temporary files. + * Also Windows version of mktemp family including _mktemp_s + * are not secure. + */ +static int +__archive_mktempx(const char *tmpdir, wchar_t *template) +{ + static const wchar_t prefix[] = L"libarchive_"; + static const wchar_t suffix[] = L"XXXXXXXXXX"; + static const wchar_t num[] = { + L'0', L'1', L'2', L'3', L'4', L'5', L'6', L'7', + L'8', L'9', L'A', L'B', L'C', L'D', L'E', L'F', + L'G', L'H', L'I', L'J', L'K', L'L', L'M', L'N', + L'O', L'P', L'Q', L'R', L'S', L'T', L'U', L'V', + L'W', L'X', L'Y', L'Z', L'a', L'b', L'c', L'd', + L'e', L'f', L'g', L'h', L'i', L'j', L'k', L'l', + L'm', L'n', L'o', L'p', L'q', L'r', L's', L't', + L'u', L'v', L'w', L'x', L'y', L'z' + }; + HCRYPTPROV hProv; + struct archive_wstring temp_name; + wchar_t *ws; + DWORD attr; + wchar_t *xp, *ep; + int fd; + + hProv = (HCRYPTPROV)NULL; + fd = -1; + ws = NULL; + + if (template == NULL) { + archive_string_init(&temp_name); + + /* Get a temporary directory. */ + if (tmpdir == NULL) { + size_t l; + wchar_t *tmp; + + l = GetTempPathW(0, NULL); + if (l == 0) { + la_dosmaperr(GetLastError()); + goto exit_tmpfile; + } + tmp = malloc(l*sizeof(wchar_t)); + if (tmp == NULL) { + errno = ENOMEM; + goto exit_tmpfile; + } + GetTempPathW((DWORD)l, tmp); + archive_wstrcpy(&temp_name, tmp); + free(tmp); + } else { + if (archive_wstring_append_from_mbs(&temp_name, tmpdir, + strlen(tmpdir)) < 0) + goto exit_tmpfile; + if (temp_name.s[temp_name.length-1] != L'/') + archive_wstrappend_wchar(&temp_name, L'/'); + } + + /* Check if temp_name is a directory. */ + attr = GetFileAttributesW(temp_name.s); + if (attr == (DWORD)-1) { + if (GetLastError() != ERROR_FILE_NOT_FOUND) { + la_dosmaperr(GetLastError()); + goto exit_tmpfile; + } + ws = __la_win_permissive_name_w(temp_name.s); + if (ws == NULL) { + errno = EINVAL; + goto exit_tmpfile; + } + attr = GetFileAttributesW(ws); + if (attr == (DWORD)-1) { + la_dosmaperr(GetLastError()); + goto exit_tmpfile; + } + } + if (!(attr & FILE_ATTRIBUTE_DIRECTORY)) { + errno = ENOTDIR; + goto exit_tmpfile; + } + + /* + * Create a temporary file. + */ + archive_wstrcat(&temp_name, prefix); + archive_wstrcat(&temp_name, suffix); + ep = temp_name.s + archive_strlen(&temp_name); + xp = ep - wcslen(suffix); + template = temp_name.s; + } else { + xp = wcschr(template, L'X'); + if (xp == NULL) /* No X, programming error */ + abort(); + for (ep = xp; *ep == L'X'; ep++) + continue; + if (*ep) /* X followed by non X, programming error */ + abort(); + } + + if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT)) { + la_dosmaperr(GetLastError()); + goto exit_tmpfile; + } + + for (;;) { + wchar_t *p; + HANDLE h; + + /* Generate a random file name through CryptGenRandom(). */ + p = xp; + if (!CryptGenRandom(hProv, (DWORD)(ep - p)*sizeof(wchar_t), + (BYTE*)p)) { + la_dosmaperr(GetLastError()); + goto exit_tmpfile; + } + for (; p < ep; p++) + *p = num[((DWORD)*p) % (sizeof(num)/sizeof(num[0]))]; + + free(ws); + ws = __la_win_permissive_name_w(template); + if (ws == NULL) { + errno = EINVAL; + goto exit_tmpfile; + } + if (template == temp_name.s) { + attr = FILE_ATTRIBUTE_TEMPORARY | + FILE_FLAG_DELETE_ON_CLOSE; + } else { + /* mkstemp */ + attr = FILE_ATTRIBUTE_NORMAL; + } + h = CreateFileW(ws, + GENERIC_READ | GENERIC_WRITE | DELETE, + 0,/* Not share */ + NULL, + CREATE_NEW,/* Create a new file only */ + attr, + NULL); + if (h == INVALID_HANDLE_VALUE) { + /* The same file already exists. retry with + * a new filename. */ + if (GetLastError() == ERROR_FILE_EXISTS) + continue; + /* Otherwise, fail creation temporary file. */ + la_dosmaperr(GetLastError()); + goto exit_tmpfile; + } + fd = _open_osfhandle((intptr_t)h, _O_BINARY | _O_RDWR); + if (fd == -1) { + la_dosmaperr(GetLastError()); + CloseHandle(h); + goto exit_tmpfile; + } else + break;/* success! */ + } +exit_tmpfile: + if (hProv != (HCRYPTPROV)NULL) + CryptReleaseContext(hProv, 0); + free(ws); + if (template == temp_name.s) + archive_wstring_free(&temp_name); + return (fd); +} + +int +__archive_mktemp(const char *tmpdir) +{ + return __archive_mktempx(tmpdir, NULL); +} + +int +__archive_mkstemp(wchar_t *template) +{ + return __archive_mktempx(NULL, template); +} + +#else + +static int +get_tempdir(struct archive_string *temppath) +{ + const char *tmp; + + tmp = getenv("TMPDIR"); + if (tmp == NULL) +#ifdef _PATH_TMP + tmp = _PATH_TMP; +#else + tmp = "/tmp"; +#endif + archive_strcpy(temppath, tmp); + if (temppath->s[temppath->length-1] != '/') + archive_strappend_char(temppath, '/'); + return (ARCHIVE_OK); +} + +#if defined(HAVE_MKSTEMP) + +/* + * We can use mkstemp(). + */ + +int +__archive_mktemp(const char *tmpdir) +{ + struct archive_string temp_name; + int fd = -1; + + archive_string_init(&temp_name); + if (tmpdir == NULL) { + if (get_tempdir(&temp_name) != ARCHIVE_OK) + goto exit_tmpfile; + } else { + archive_strcpy(&temp_name, tmpdir); + if (temp_name.s[temp_name.length-1] != '/') + archive_strappend_char(&temp_name, '/'); + } + archive_strcat(&temp_name, "libarchive_XXXXXX"); + fd = mkstemp(temp_name.s); + if (fd < 0) + goto exit_tmpfile; + __archive_ensure_cloexec_flag(fd); + unlink(temp_name.s); +exit_tmpfile: + archive_string_free(&temp_name); + return (fd); +} + +int +__archive_mkstemp(char *template) +{ + int fd = -1; + fd = mkstemp(template); + if (fd >= 0) + __archive_ensure_cloexec_flag(fd); + return (fd); +} + +#else /* !HAVE_MKSTEMP */ + +/* + * We use a private routine. + */ + +static int +__archive_mktempx(const char *tmpdir, char *template) +{ + static const char num[] = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', + 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', + 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', + 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', + 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', + 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', + 'u', 'v', 'w', 'x', 'y', 'z' + }; + struct archive_string temp_name; + struct stat st; + int fd; + char *tp, *ep; + + fd = -1; + if (template == NULL) { + archive_string_init(&temp_name); + if (tmpdir == NULL) { + if (get_tempdir(&temp_name) != ARCHIVE_OK) + goto exit_tmpfile; + } else + archive_strcpy(&temp_name, tmpdir); + if (temp_name.s[temp_name.length-1] == '/') { + temp_name.s[temp_name.length-1] = '\0'; + temp_name.length --; + } + if (la_stat(temp_name.s, &st) < 0) + goto exit_tmpfile; + if (!S_ISDIR(st.st_mode)) { + errno = ENOTDIR; + goto exit_tmpfile; + } + archive_strcat(&temp_name, "/libarchive_"); + tp = temp_name.s + archive_strlen(&temp_name); + archive_strcat(&temp_name, "XXXXXXXXXX"); + ep = temp_name.s + archive_strlen(&temp_name); + template = temp_name.s; + } else { + tp = strchr(template, 'X'); + if (tp == NULL) /* No X, programming error */ + abort(); + for (ep = tp; *ep == 'X'; ep++) + continue; + if (*ep) /* X followed by non X, programming error */ + abort(); + } + + do { + char *p; + + p = tp; + archive_random(p, ep - p); + while (p < ep) { + int d = *((unsigned char *)p) % sizeof(num); + *p++ = num[d]; + } + fd = open(template, O_CREAT | O_EXCL | O_RDWR | O_CLOEXEC, + 0600); + } while (fd < 0 && errno == EEXIST); + if (fd < 0) + goto exit_tmpfile; + __archive_ensure_cloexec_flag(fd); + if (template == temp_name.s) + unlink(temp_name.s); +exit_tmpfile: + if (template == temp_name.s) + archive_string_free(&temp_name); + return (fd); +} + +int +__archive_mktemp(const char *tmpdir) +{ + return __archive_mktempx(tmpdir, NULL); +} + +int +__archive_mkstemp(char *template) +{ + return __archive_mktempx(NULL, template); +} + +#endif /* !HAVE_MKSTEMP */ +#endif /* !_WIN32 || __CYGWIN__ */ + +/* + * Set FD_CLOEXEC flag to a file descriptor if it is not set. + * We have to set the flag if the platform does not provide O_CLOEXEC + * or F_DUPFD_CLOEXEC flags. + * + * Note: This function is absolutely called after creating a new file + * descriptor even if the platform seemingly provides O_CLOEXEC or + * F_DUPFD_CLOEXEC macros because it is possible that the platform + * merely declares those macros, especially Linux 2.6.18 - 2.6.24 do it. + */ +void +__archive_ensure_cloexec_flag(int fd) +{ +#if defined(_WIN32) && !defined(__CYGWIN__) + (void)fd; /* UNUSED */ +#else + int flags; + + if (fd >= 0) { + flags = fcntl(fd, F_GETFD); + if (flags != -1 && (flags & FD_CLOEXEC) == 0) + fcntl(fd, F_SETFD, flags | FD_CLOEXEC); + } +#endif +} + +/* + * Utility function to sort a group of strings using quicksort. + */ +static int +archive_utility_string_sort_helper(char **strings, unsigned int n) +{ + unsigned int i, lesser_count, greater_count; + char **lesser, **greater, **tmp, *pivot; + int retval1, retval2; + + /* A list of 0 or 1 elements is already sorted */ + if (n <= 1) + return (ARCHIVE_OK); + + lesser_count = greater_count = 0; + lesser = greater = NULL; + pivot = strings[0]; + for (i = 1; i < n; i++) + { + if (strcmp(strings[i], pivot) < 0) + { + lesser_count++; + tmp = (char **)realloc(lesser, + lesser_count * sizeof(char *)); + if (!tmp) { + free(greater); + free(lesser); + return (ARCHIVE_FATAL); + } + lesser = tmp; + lesser[lesser_count - 1] = strings[i]; + } + else + { + greater_count++; + tmp = (char **)realloc(greater, + greater_count * sizeof(char *)); + if (!tmp) { + free(greater); + free(lesser); + return (ARCHIVE_FATAL); + } + greater = tmp; + greater[greater_count - 1] = strings[i]; + } + } + + /* quicksort(lesser) */ + retval1 = archive_utility_string_sort_helper(lesser, lesser_count); + for (i = 0; i < lesser_count; i++) + strings[i] = lesser[i]; + free(lesser); + + /* pivot */ + strings[lesser_count] = pivot; + + /* quicksort(greater) */ + retval2 = archive_utility_string_sort_helper(greater, greater_count); + for (i = 0; i < greater_count; i++) + strings[lesser_count + 1 + i] = greater[i]; + free(greater); + + return (retval1 < retval2) ? retval1 : retval2; +} + +int +archive_utility_string_sort(char **strings) +{ + unsigned int size = 0; + while (strings[size] != NULL) + size++; + return archive_utility_string_sort_helper(strings, size); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_version_details.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_version_details.c new file mode 100644 index 0000000000..bfb20eab20 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_version_details.c @@ -0,0 +1,151 @@ +/*- + * Copyright (c) 2009-2012,2014 Michihiro NAKAJIMA + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_util.c 201098 2009-12-28 02:58:14Z kientzle $"); + +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_ZLIB_H +#include <zlib.h> +#endif +#ifdef HAVE_LZMA_H +#include <lzma.h> +#endif +#ifdef HAVE_BZLIB_H +#include <bzlib.h> +#endif +#ifdef HAVE_LZ4_H +#include <lz4.h> +#endif +#ifdef HAVE_ZSTD_H +#include <zstd.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_string.h" + +const char * +archive_version_details(void) +{ + static struct archive_string str; + static int init = 0; + const char *zlib = archive_zlib_version(); + const char *liblzma = archive_liblzma_version(); + const char *bzlib = archive_bzlib_version(); + const char *liblz4 = archive_liblz4_version(); + const char *libzstd = archive_libzstd_version(); + + if (!init) { + archive_string_init(&str); + + archive_strcat(&str, ARCHIVE_VERSION_STRING); + if (zlib != NULL) { + archive_strcat(&str, " zlib/"); + archive_strcat(&str, zlib); + } + if (liblzma) { + archive_strcat(&str, " liblzma/"); + archive_strcat(&str, liblzma); + } + if (bzlib) { + const char *p = bzlib; + const char *sep = strchr(p, ','); + if (sep == NULL) + sep = p + strlen(p); + archive_strcat(&str, " bz2lib/"); + archive_strncat(&str, p, sep - p); + } + if (liblz4) { + archive_strcat(&str, " liblz4/"); + archive_strcat(&str, liblz4); + } + if (libzstd) { + archive_strcat(&str, " libzstd/"); + archive_strcat(&str, libzstd); + } + } + return str.s; +} + +const char * +archive_zlib_version(void) +{ +#ifdef HAVE_ZLIB_H + return ZLIB_VERSION; +#else + return NULL; +#endif +} + +const char * +archive_liblzma_version(void) +{ +#ifdef HAVE_LZMA_H + return LZMA_VERSION_STRING; +#else + return NULL; +#endif +} + +const char * +archive_bzlib_version(void) +{ +#ifdef HAVE_BZLIB_H + return BZ2_bzlibVersion(); +#else + return NULL; +#endif +} + +const char * +archive_liblz4_version(void) +{ +#if defined(HAVE_LZ4_H) && defined(HAVE_LIBLZ4) +#define str(s) #s +#define NUMBER(x) str(x) + return NUMBER(LZ4_VERSION_MAJOR) "." NUMBER(LZ4_VERSION_MINOR) "." NUMBER(LZ4_VERSION_RELEASE); +#undef NUMBER +#undef str +#else + return NULL; +#endif +} + +const char * +archive_libzstd_version(void) +{ +#if HAVE_ZSTD_H && HAVE_LIBZSTD + return ZSTD_VERSION_STRING; +#else + return NULL; +#endif +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_virtual.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_virtual.c new file mode 100644 index 0000000000..f509ee5c67 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_virtual.c @@ -0,0 +1,163 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_virtual.c 201098 2009-12-28 02:58:14Z kientzle $"); + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" + +int +archive_filter_code(struct archive *a, int n) +{ + return ((a->vtable->archive_filter_code)(a, n)); +} + +int +archive_filter_count(struct archive *a) +{ + return ((a->vtable->archive_filter_count)(a)); +} + +const char * +archive_filter_name(struct archive *a, int n) +{ + return ((a->vtable->archive_filter_name)(a, n)); +} + +la_int64_t +archive_filter_bytes(struct archive *a, int n) +{ + return ((a->vtable->archive_filter_bytes)(a, n)); +} + +int +archive_free(struct archive *a) +{ + if (a == NULL) + return (ARCHIVE_OK); + return ((a->vtable->archive_free)(a)); +} + +int +archive_write_close(struct archive *a) +{ + return ((a->vtable->archive_close)(a)); +} + +int +archive_read_close(struct archive *a) +{ + return ((a->vtable->archive_close)(a)); +} + +int +archive_write_fail(struct archive *a) +{ + a->state = ARCHIVE_STATE_FATAL; + return a->state; +} + +int +archive_write_free(struct archive *a) +{ + return archive_free(a); +} + +#if ARCHIVE_VERSION_NUMBER < 4000000 +/* For backwards compatibility; will be removed with libarchive 4.0. */ +int +archive_write_finish(struct archive *a) +{ + return archive_write_free(a); +} +#endif + +int +archive_read_free(struct archive *a) +{ + return archive_free(a); +} + +#if ARCHIVE_VERSION_NUMBER < 4000000 +/* For backwards compatibility; will be removed with libarchive 4.0. */ +int +archive_read_finish(struct archive *a) +{ + return archive_read_free(a); +} +#endif + +int +archive_write_header(struct archive *a, struct archive_entry *entry) +{ + ++a->file_count; + return ((a->vtable->archive_write_header)(a, entry)); +} + +int +archive_write_finish_entry(struct archive *a) +{ + return ((a->vtable->archive_write_finish_entry)(a)); +} + +la_ssize_t +archive_write_data(struct archive *a, const void *buff, size_t s) +{ + return ((a->vtable->archive_write_data)(a, buff, s)); +} + +la_ssize_t +archive_write_data_block(struct archive *a, const void *buff, size_t s, + la_int64_t o) +{ + if (a->vtable->archive_write_data_block == NULL) { + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "archive_write_data_block not supported"); + a->state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + return ((a->vtable->archive_write_data_block)(a, buff, s, o)); +} + +int +archive_read_next_header(struct archive *a, struct archive_entry **entry) +{ + return ((a->vtable->archive_read_next_header)(a, entry)); +} + +int +archive_read_next_header2(struct archive *a, struct archive_entry *entry) +{ + return ((a->vtable->archive_read_next_header2)(a, entry)); +} + +int +archive_read_data_block(struct archive *a, + const void **buff, size_t *s, la_int64_t *o) +{ + return ((a->vtable->archive_read_data_block)(a, buff, s, o)); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_windows.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_windows.c new file mode 100644 index 0000000000..624e270095 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_windows.c @@ -0,0 +1,909 @@ +/*- + * Copyright (c) 2009-2011 Michihiro NAKAJIMA + * Copyright (c) 2003-2007 Kees Zeelenberg + * 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(S) ``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(S) 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. + * + * $FreeBSD$ + */ + +/* + * A set of compatibility glue for building libarchive on Windows platforms. + * + * Originally created as "libarchive-nonposix.c" by Kees Zeelenberg + * for the GnuWin32 project, trimmed significantly by Tim Kientzle. + * + * Much of the original file was unnecessary for libarchive, because + * many of the features it emulated were not strictly necessary for + * libarchive. I hope for this to shrink further as libarchive + * internals are gradually reworked to sit more naturally on both + * POSIX and Windows. Any ideas for this are greatly appreciated. + * + * The biggest remaining issue is the dev/ino emulation; libarchive + * has a couple of public APIs that rely on dev/ino uniquely + * identifying a file. This doesn't match well with Windows. I'm + * considering alternative APIs. + */ + +#if defined(_WIN32) && !defined(__CYGWIN__) + +#include "archive_platform.h" +#include "archive_private.h" +#include "archive_entry.h" +#include <ctype.h> +#include <errno.h> +#include <stddef.h> +#ifdef HAVE_SYS_UTIME_H +#include <sys/utime.h> +#endif +#include <sys/stat.h> +#include <locale.h> +#include <process.h> +#include <stdlib.h> +#include <wchar.h> +#include <windows.h> +#include <share.h> + +#define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000) + +#if defined(__LA_LSEEK_NEEDED) +static BOOL SetFilePointerEx_perso(HANDLE hFile, + LARGE_INTEGER liDistanceToMove, + PLARGE_INTEGER lpNewFilePointer, + DWORD dwMoveMethod) +{ + LARGE_INTEGER li; + li.QuadPart = liDistanceToMove.QuadPart; + li.LowPart = SetFilePointer( + hFile, li.LowPart, &li.HighPart, dwMoveMethod); + if(lpNewFilePointer) { + lpNewFilePointer->QuadPart = li.QuadPart; + } + return li.LowPart != -1 || GetLastError() == NO_ERROR; +} +#endif + +struct ustat { + int64_t st_atime; + uint32_t st_atime_nsec; + int64_t st_ctime; + uint32_t st_ctime_nsec; + int64_t st_mtime; + uint32_t st_mtime_nsec; + gid_t st_gid; + /* 64bits ino */ + int64_t st_ino; + mode_t st_mode; + uint32_t st_nlink; + uint64_t st_size; + uid_t st_uid; + dev_t st_dev; + dev_t st_rdev; +}; + +/* Transform 64-bits ino into 32-bits by hashing. + * You do not forget that really unique number size is 64-bits. + */ +#define INOSIZE (8*sizeof(ino_t)) /* 32 */ +static __inline ino_t +getino(struct ustat *ub) +{ + ULARGE_INTEGER ino64; + ino64.QuadPart = ub->st_ino; + /* I don't know this hashing is correct way */ + return ((ino_t)(ino64.LowPart ^ (ino64.LowPart >> INOSIZE))); +} + +/* + * Prepend "\\?\" to the path name and convert it to unicode to permit + * an extended-length path for a maximum total path length of 32767 + * characters. + * see also http://msdn.microsoft.com/en-us/library/aa365247.aspx + */ +wchar_t * +__la_win_permissive_name(const char *name) +{ + wchar_t *wn; + wchar_t *ws; + size_t ll; + + ll = strlen(name); + wn = malloc((ll + 1) * sizeof(wchar_t)); + if (wn == NULL) + return (NULL); + ll = mbstowcs(wn, name, ll); + if (ll == (size_t)-1) { + free(wn); + return (NULL); + } + wn[ll] = L'\0'; + ws = __la_win_permissive_name_w(wn); + free(wn); + return (ws); +} + +wchar_t * +__la_win_permissive_name_w(const wchar_t *wname) +{ + wchar_t *wn, *wnp; + wchar_t *ws, *wsp; + DWORD l, len, slen; + int unc; + + /* Get a full-pathname. */ + l = GetFullPathNameW(wname, 0, NULL, NULL); + if (l == 0) + return (NULL); + /* NOTE: GetFullPathNameW has a bug that if the length of the file + * name is just 1 then it returns incomplete buffer size. Thus, we + * have to add three to the size to allocate a sufficient buffer + * size for the full-pathname of the file name. */ + l += 3; + wnp = malloc(l * sizeof(wchar_t)); + if (wnp == NULL) + return (NULL); + len = GetFullPathNameW(wname, l, wnp, NULL); + wn = wnp; + + if (wnp[0] == L'\\' && wnp[1] == L'\\' && + wnp[2] == L'?' && wnp[3] == L'\\') + /* We have already a permissive name. */ + return (wn); + + if (wnp[0] == L'\\' && wnp[1] == L'\\' && + wnp[2] == L'.' && wnp[3] == L'\\') { + /* This is a device name */ + if (((wnp[4] >= L'a' && wnp[4] <= L'z') || + (wnp[4] >= L'A' && wnp[4] <= L'Z')) && + wnp[5] == L':' && wnp[6] == L'\\') + wnp[2] = L'?';/* Not device name. */ + return (wn); + } + + unc = 0; + if (wnp[0] == L'\\' && wnp[1] == L'\\' && wnp[2] != L'\\') { + wchar_t *p = &wnp[2]; + + /* Skip server-name letters. */ + while (*p != L'\\' && *p != L'\0') + ++p; + if (*p == L'\\') { + wchar_t *rp = ++p; + /* Skip share-name letters. */ + while (*p != L'\\' && *p != L'\0') + ++p; + if (*p == L'\\' && p != rp) { + /* Now, match patterns such as + * "\\server-name\share-name\" */ + wnp += 2; + len -= 2; + unc = 1; + } + } + } + + slen = 4 + (unc * 4) + len + 1; + ws = wsp = malloc(slen * sizeof(wchar_t)); + if (ws == NULL) { + free(wn); + return (NULL); + } + /* prepend "\\?\" */ + wcsncpy(wsp, L"\\\\?\\", 4); + wsp += 4; + slen -= 4; + if (unc) { + /* append "UNC\" ---> "\\?\UNC\" */ + wcsncpy(wsp, L"UNC\\", 4); + wsp += 4; + slen -= 4; + } + wcsncpy(wsp, wnp, slen); + wsp[slen - 1] = L'\0'; /* Ensure null termination. */ + free(wn); + return (ws); +} + +/* + * Create a file handle. + * This can exceed MAX_PATH limitation. + */ +static HANDLE +la_CreateFile(const char *path, DWORD dwDesiredAccess, DWORD dwShareMode, + LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) +{ + wchar_t *wpath; + HANDLE handle; + + handle = CreateFileA(path, dwDesiredAccess, dwShareMode, + lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, + hTemplateFile); + if (handle != INVALID_HANDLE_VALUE) + return (handle); + if (GetLastError() != ERROR_PATH_NOT_FOUND) + return (handle); + wpath = __la_win_permissive_name(path); + if (wpath == NULL) + return (handle); + handle = CreateFileW(wpath, dwDesiredAccess, dwShareMode, + lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, + hTemplateFile); + free(wpath); + return (handle); +} + +#if defined(__LA_LSEEK_NEEDED) +__int64 +__la_lseek(int fd, __int64 offset, int whence) +{ + LARGE_INTEGER distance; + LARGE_INTEGER newpointer; + HANDLE handle; + + if (fd < 0) { + errno = EBADF; + return (-1); + } + handle = (HANDLE)_get_osfhandle(fd); + if (GetFileType(handle) != FILE_TYPE_DISK) { + errno = EBADF; + return (-1); + } + distance.QuadPart = offset; + if (!SetFilePointerEx_perso(handle, distance, &newpointer, whence)) { + DWORD lasterr; + + lasterr = GetLastError(); + if (lasterr == ERROR_BROKEN_PIPE) + return (0); + if (lasterr == ERROR_ACCESS_DENIED) + errno = EBADF; + else + la_dosmaperr(lasterr); + return (-1); + } + return (newpointer.QuadPart); +} +#endif + +/* This can exceed MAX_PATH limitation. */ +int +__la_open(const char *path, int flags, ...) +{ + va_list ap; + wchar_t *ws; + int r, pmode; + DWORD attr; + + va_start(ap, flags); + pmode = va_arg(ap, int); + va_end(ap); + ws = NULL; + if ((flags & ~O_BINARY) == O_RDONLY) { + /* + * When we open a directory, _open function returns + * "Permission denied" error. + */ + attr = GetFileAttributesA(path); + if (attr == (DWORD)-1 && GetLastError() == ERROR_PATH_NOT_FOUND) { + ws = __la_win_permissive_name(path); + if (ws == NULL) { + errno = EINVAL; + return (-1); + } + attr = GetFileAttributesW(ws); + } + if (attr == (DWORD)-1) { + la_dosmaperr(GetLastError()); + free(ws); + return (-1); + } + if (attr & FILE_ATTRIBUTE_DIRECTORY) { + HANDLE handle; + + if (ws != NULL) + handle = CreateFileW(ws, 0, 0, NULL, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | + FILE_ATTRIBUTE_READONLY, + NULL); + else + handle = CreateFileA(path, 0, 0, NULL, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | + FILE_ATTRIBUTE_READONLY, + NULL); + free(ws); + if (handle == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + return (-1); + } + r = _open_osfhandle((intptr_t)handle, _O_RDONLY); + return (r); + } + } + if (ws == NULL) { +#if defined(__BORLANDC__) + /* Borland has no mode argument. + TODO: Fix mode of new file. */ + r = _open(path, flags); +#else + r = _open(path, flags, pmode); +#endif + if (r < 0 && errno == EACCES && (flags & O_CREAT) != 0) { + /* Simulate other POSIX system action to pass our test suite. */ + attr = GetFileAttributesA(path); + if (attr == (DWORD)-1) + la_dosmaperr(GetLastError()); + else if (attr & FILE_ATTRIBUTE_DIRECTORY) + errno = EISDIR; + else + errno = EACCES; + return (-1); + } + if (r >= 0 || errno != ENOENT) + return (r); + ws = __la_win_permissive_name(path); + if (ws == NULL) { + errno = EINVAL; + return (-1); + } + } + r = _wopen(ws, flags, pmode); + if (r < 0 && errno == EACCES && (flags & O_CREAT) != 0) { + /* Simulate other POSIX system action to pass our test suite. */ + attr = GetFileAttributesW(ws); + if (attr == (DWORD)-1) + la_dosmaperr(GetLastError()); + else if (attr & FILE_ATTRIBUTE_DIRECTORY) + errno = EISDIR; + else + errno = EACCES; + } + free(ws); + return (r); +} + +ssize_t +__la_read(int fd, void *buf, size_t nbytes) +{ + HANDLE handle; + DWORD bytes_read, lasterr; + int r; + +#ifdef _WIN64 + if (nbytes > UINT32_MAX) + nbytes = UINT32_MAX; +#endif + if (fd < 0) { + errno = EBADF; + return (-1); + } + /* Do not pass 0 to third parameter of ReadFile(), read bytes. + * This will not return to application side. */ + if (nbytes == 0) + return (0); + handle = (HANDLE)_get_osfhandle(fd); + r = ReadFile(handle, buf, (uint32_t)nbytes, + &bytes_read, NULL); + if (r == 0) { + lasterr = GetLastError(); + if (lasterr == ERROR_NO_DATA) { + errno = EAGAIN; + return (-1); + } + if (lasterr == ERROR_BROKEN_PIPE) + return (0); + if (lasterr == ERROR_ACCESS_DENIED) + errno = EBADF; + else + la_dosmaperr(lasterr); + return (-1); + } + return ((ssize_t)bytes_read); +} + +/* Convert Windows FILETIME to UTC */ +__inline static void +fileTimeToUTC(const FILETIME *filetime, time_t *t, long *ns) +{ + ULARGE_INTEGER utc; + + utc.HighPart = filetime->dwHighDateTime; + utc.LowPart = filetime->dwLowDateTime; + if (utc.QuadPart >= EPOC_TIME) { + utc.QuadPart -= EPOC_TIME; + *t = (time_t)(utc.QuadPart / 10000000); /* milli seconds base */ + *ns = (long)(utc.QuadPart % 10000000) * 100;/* nano seconds base */ + } else { + *t = 0; + *ns = 0; + } +} + +/* Stat by handle + * Windows' stat() does not accept the path added "\\?\" especially "?" + * character. + * It means we cannot access the long name path longer than MAX_PATH. + * So I've implemented a function similar to Windows' stat() to access the + * long name path. + * And I've added some feature. + * 1. set st_ino by nFileIndexHigh and nFileIndexLow of + * BY_HANDLE_FILE_INFORMATION. + * 2. set st_nlink by nNumberOfLinks of BY_HANDLE_FILE_INFORMATION. + * 3. set st_dev by dwVolumeSerialNumber by BY_HANDLE_FILE_INFORMATION. + */ +static int +__hstat(HANDLE handle, struct ustat *st) +{ + BY_HANDLE_FILE_INFORMATION info; + ULARGE_INTEGER ino64; + DWORD ftype; + mode_t mode; + time_t t; + long ns; + + switch (ftype = GetFileType(handle)) { + case FILE_TYPE_UNKNOWN: + errno = EBADF; + return (-1); + case FILE_TYPE_CHAR: + case FILE_TYPE_PIPE: + if (ftype == FILE_TYPE_CHAR) { + st->st_mode = S_IFCHR; + st->st_size = 0; + } else { + DWORD avail; + + st->st_mode = S_IFIFO; + if (PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL)) + st->st_size = avail; + else + st->st_size = 0; + } + st->st_atime = 0; + st->st_atime_nsec = 0; + st->st_mtime = 0; + st->st_mtime_nsec = 0; + st->st_ctime = 0; + st->st_ctime_nsec = 0; + st->st_ino = 0; + st->st_nlink = 1; + st->st_uid = 0; + st->st_gid = 0; + st->st_rdev = 0; + st->st_dev = 0; + return (0); + case FILE_TYPE_DISK: + break; + default: + /* This ftype is undocumented type. */ + la_dosmaperr(GetLastError()); + return (-1); + } + + ZeroMemory(&info, sizeof(info)); + if (!GetFileInformationByHandle (handle, &info)) { + la_dosmaperr(GetLastError()); + return (-1); + } + + mode = S_IRUSR | S_IRGRP | S_IROTH; + if ((info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) == 0) + mode |= S_IWUSR | S_IWGRP | S_IWOTH; + if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + mode |= S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH; + else + mode |= S_IFREG; + st->st_mode = mode; + + fileTimeToUTC(&info.ftLastAccessTime, &t, &ns); + st->st_atime = t; + st->st_atime_nsec = ns; + fileTimeToUTC(&info.ftLastWriteTime, &t, &ns); + st->st_mtime = t; + st->st_mtime_nsec = ns; + fileTimeToUTC(&info.ftCreationTime, &t, &ns); + st->st_ctime = t; + st->st_ctime_nsec = ns; + st->st_size = + ((int64_t)(info.nFileSizeHigh) * ((int64_t)MAXDWORD + 1)) + + (int64_t)(info.nFileSizeLow); +#ifdef SIMULATE_WIN_STAT + st->st_ino = 0; + st->st_nlink = 1; + st->st_dev = 0; +#else + /* Getting FileIndex as i-node. We should remove a sequence which + * is high-16-bits of nFileIndexHigh. */ + ino64.HighPart = info.nFileIndexHigh & 0x0000FFFFUL; + ino64.LowPart = info.nFileIndexLow; + st->st_ino = ino64.QuadPart; + st->st_nlink = info.nNumberOfLinks; + if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + ++st->st_nlink;/* Add parent directory. */ + st->st_dev = info.dwVolumeSerialNumber; +#endif + st->st_uid = 0; + st->st_gid = 0; + st->st_rdev = 0; + return (0); +} + +static void +copy_stat(struct stat *st, struct ustat *us) +{ + st->st_atime = us->st_atime; + st->st_ctime = us->st_ctime; + st->st_mtime = us->st_mtime; + st->st_gid = us->st_gid; + st->st_ino = getino(us); + st->st_mode = us->st_mode; + st->st_nlink = us->st_nlink; + st->st_size = (off_t)us->st_size; + st->st_uid = us->st_uid; + st->st_dev = us->st_dev; + st->st_rdev = us->st_rdev; +} + +/* + * TODO: Remove a use of __la_fstat and __la_stat. + * We should use GetFileInformationByHandle in place + * where We still use the *stat functions. + */ +int +__la_fstat(int fd, struct stat *st) +{ + struct ustat u; + int ret; + + if (fd < 0) { + errno = EBADF; + return (-1); + } + ret = __hstat((HANDLE)_get_osfhandle(fd), &u); + if (ret >= 0) { + copy_stat(st, &u); + if (u.st_mode & (S_IFCHR | S_IFIFO)) { + st->st_dev = fd; + st->st_rdev = fd; + } + } + return (ret); +} + +/* This can exceed MAX_PATH limitation. */ +int +__la_stat(const char *path, struct stat *st) +{ + HANDLE handle; + struct ustat u; + int ret; + + handle = la_CreateFile(path, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, + NULL); + if (handle == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + return (-1); + } + ret = __hstat(handle, &u); + CloseHandle(handle); + if (ret >= 0) { + char *p; + + copy_stat(st, &u); + p = strrchr(path, '.'); + if (p != NULL && strlen(p) == 4) { + char exttype[4]; + + ++ p; + exttype[0] = toupper(*p++); + exttype[1] = toupper(*p++); + exttype[2] = toupper(*p++); + exttype[3] = '\0'; + if (!strcmp(exttype, "EXE") || !strcmp(exttype, "CMD") || + !strcmp(exttype, "BAT") || !strcmp(exttype, "COM")) + st->st_mode |= S_IXUSR | S_IXGRP | S_IXOTH; + } + } + return (ret); +} + +/* + * This waitpid is limited implementation. + */ +pid_t +__la_waitpid(HANDLE child, int *status, int option) +{ + DWORD cs; + + (void)option;/* UNUSED */ + do { + if (GetExitCodeProcess(child, &cs) == 0) { + CloseHandle(child); + la_dosmaperr(GetLastError()); + *status = 0; + return (-1); + } + } while (cs == STILL_ACTIVE); + + *status = (int)(cs & 0xff); + return (0); +} + +ssize_t +__la_write(int fd, const void *buf, size_t nbytes) +{ + DWORD bytes_written; + +#ifdef _WIN64 + if (nbytes > UINT32_MAX) + nbytes = UINT32_MAX; +#endif + if (fd < 0) { + errno = EBADF; + return (-1); + } + if (!WriteFile((HANDLE)_get_osfhandle(fd), buf, (uint32_t)nbytes, + &bytes_written, NULL)) { + DWORD lasterr; + + lasterr = GetLastError(); + if (lasterr == ERROR_ACCESS_DENIED) + errno = EBADF; + else + la_dosmaperr(lasterr); + return (-1); + } + return (bytes_written); +} + +/* + * Replace the Windows path separator '\' with '/'. + */ +static int +replace_pathseparator(struct archive_wstring *ws, const wchar_t *wp) +{ + wchar_t *w; + size_t path_length; + + if (wp == NULL) + return(0); + if (wcschr(wp, L'\\') == NULL) + return(0); + path_length = wcslen(wp); + if (archive_wstring_ensure(ws, path_length) == NULL) + return(-1); + archive_wstrncpy(ws, wp, path_length); + for (w = ws->s; *w; w++) { + if (*w == L'\\') + *w = L'/'; + } + return(1); +} + +static int +fix_pathseparator(struct archive_entry *entry) +{ + struct archive_wstring ws; + const wchar_t *wp; + int ret = ARCHIVE_OK; + + archive_string_init(&ws); + wp = archive_entry_pathname_w(entry); + switch (replace_pathseparator(&ws, wp)) { + case 0: /* Not replaced. */ + break; + case 1: /* Replaced. */ + archive_entry_copy_pathname_w(entry, ws.s); + break; + default: + ret = ARCHIVE_FAILED; + } + wp = archive_entry_hardlink_w(entry); + switch (replace_pathseparator(&ws, wp)) { + case 0: /* Not replaced. */ + break; + case 1: /* Replaced. */ + archive_entry_copy_hardlink_w(entry, ws.s); + break; + default: + ret = ARCHIVE_FAILED; + } + wp = archive_entry_symlink_w(entry); + switch (replace_pathseparator(&ws, wp)) { + case 0: /* Not replaced. */ + break; + case 1: /* Replaced. */ + archive_entry_copy_symlink_w(entry, ws.s); + break; + default: + ret = ARCHIVE_FAILED; + } + archive_wstring_free(&ws); + return(ret); +} + +struct archive_entry * +__la_win_entry_in_posix_pathseparator(struct archive_entry *entry) +{ + struct archive_entry *entry_main; + const wchar_t *wp; + int has_backslash = 0; + int ret; + + wp = archive_entry_pathname_w(entry); + if (wp != NULL && wcschr(wp, L'\\') != NULL) + has_backslash = 1; + if (!has_backslash) { + wp = archive_entry_hardlink_w(entry); + if (wp != NULL && wcschr(wp, L'\\') != NULL) + has_backslash = 1; + } + if (!has_backslash) { + wp = archive_entry_symlink_w(entry); + if (wp != NULL && wcschr(wp, L'\\') != NULL) + has_backslash = 1; + } + /* + * If there is no backslash chars, return the original. + */ + if (!has_backslash) + return (entry); + + /* Copy entry so we can modify it as needed. */ + entry_main = archive_entry_clone(entry); + if (entry_main == NULL) + return (NULL); + /* Replace the Windows path-separator '\' with '/'. */ + ret = fix_pathseparator(entry_main); + if (ret < ARCHIVE_WARN) { + archive_entry_free(entry_main); + return (NULL); + } + return (entry_main); +} + + +/* + * The following function was modified from PostgreSQL sources and is + * subject to the copyright below. + */ +/*------------------------------------------------------------------------- + * + * win32error.c + * Map win32 error codes to errno values + * + * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group + * + * IDENTIFICATION + * $PostgreSQL: pgsql/src/port/win32error.c,v 1.4 2008/01/01 19:46:00 momjian Exp $ + * + *------------------------------------------------------------------------- + */ +/* +PostgreSQL Database Management System +(formerly known as Postgres, then as Postgres95) + +Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group + +Portions Copyright (c) 1994, The Regents of the University of California + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose, without fee, and without a written agreement +is hereby granted, provided that the above copyright notice and this +paragraph and the following two paragraphs appear in all copies. + +IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR +DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING +LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS +DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS +ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO +PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. +*/ + +static const struct { + DWORD winerr; + int doserr; +} doserrors[] = +{ + { ERROR_INVALID_FUNCTION, EINVAL }, + { ERROR_FILE_NOT_FOUND, ENOENT }, + { ERROR_PATH_NOT_FOUND, ENOENT }, + { ERROR_TOO_MANY_OPEN_FILES, EMFILE }, + { ERROR_ACCESS_DENIED, EACCES }, + { ERROR_INVALID_HANDLE, EBADF }, + { ERROR_ARENA_TRASHED, ENOMEM }, + { ERROR_NOT_ENOUGH_MEMORY, ENOMEM }, + { ERROR_INVALID_BLOCK, ENOMEM }, + { ERROR_BAD_ENVIRONMENT, E2BIG }, + { ERROR_BAD_FORMAT, ENOEXEC }, + { ERROR_INVALID_ACCESS, EINVAL }, + { ERROR_INVALID_DATA, EINVAL }, + { ERROR_INVALID_DRIVE, ENOENT }, + { ERROR_CURRENT_DIRECTORY, EACCES }, + { ERROR_NOT_SAME_DEVICE, EXDEV }, + { ERROR_NO_MORE_FILES, ENOENT }, + { ERROR_LOCK_VIOLATION, EACCES }, + { ERROR_SHARING_VIOLATION, EACCES }, + { ERROR_BAD_NETPATH, ENOENT }, + { ERROR_NETWORK_ACCESS_DENIED, EACCES }, + { ERROR_BAD_NET_NAME, ENOENT }, + { ERROR_FILE_EXISTS, EEXIST }, + { ERROR_CANNOT_MAKE, EACCES }, + { ERROR_FAIL_I24, EACCES }, + { ERROR_INVALID_PARAMETER, EINVAL }, + { ERROR_NO_PROC_SLOTS, EAGAIN }, + { ERROR_DRIVE_LOCKED, EACCES }, + { ERROR_BROKEN_PIPE, EPIPE }, + { ERROR_DISK_FULL, ENOSPC }, + { ERROR_INVALID_TARGET_HANDLE, EBADF }, + { ERROR_INVALID_HANDLE, EINVAL }, + { ERROR_WAIT_NO_CHILDREN, ECHILD }, + { ERROR_CHILD_NOT_COMPLETE, ECHILD }, + { ERROR_DIRECT_ACCESS_HANDLE, EBADF }, + { ERROR_NEGATIVE_SEEK, EINVAL }, + { ERROR_SEEK_ON_DEVICE, EACCES }, + { ERROR_DIR_NOT_EMPTY, ENOTEMPTY }, + { ERROR_NOT_LOCKED, EACCES }, + { ERROR_BAD_PATHNAME, ENOENT }, + { ERROR_MAX_THRDS_REACHED, EAGAIN }, + { ERROR_LOCK_FAILED, EACCES }, + { ERROR_ALREADY_EXISTS, EEXIST }, + { ERROR_FILENAME_EXCED_RANGE, ENOENT }, + { ERROR_NESTING_NOT_ALLOWED, EAGAIN }, + { ERROR_NOT_ENOUGH_QUOTA, ENOMEM } +}; + +void +__la_dosmaperr(unsigned long e) +{ + int i; + + if (e == 0) + { + errno = 0; + return; + } + + for (i = 0; i < (int)(sizeof(doserrors)/sizeof(doserrors[0])); i++) + { + if (doserrors[i].winerr == e) + { + errno = doserrors[i].doserr; + return; + } + } + + /* fprintf(stderr, "unrecognized win32 error code: %lu", e); */ + errno = EINVAL; + return; +} + +#endif /* _WIN32 && !__CYGWIN__ */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_windows.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_windows.h new file mode 100644 index 0000000000..47b7cb8e37 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_windows.h @@ -0,0 +1,315 @@ +/*- + * Copyright (c) 2009-2011 Michihiro NAKAJIMA + * Copyright (c) 2003-2006 Tim Kientzle + * 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 + * in this position and unchanged. + * 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(S) ``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(S) 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. + * + * $FreeBSD$ + */ + +/* + * TODO: A lot of stuff in here isn't actually used by libarchive and + * can be trimmed out. Note that this file is used by libarchive and + * libarchive_test but nowhere else. (But note that it gets compiled + * with many different Windows environments, including MinGW, Visual + * Studio, and Cygwin. Significant changes should be tested in all three.) + */ + +/* + * TODO: Don't use off_t in here. Use __int64 instead. Note that + * Visual Studio and the Windows SDK define off_t as 32 bits; Win32's + * more modern file handling APIs all use __int64 instead of off_t. + */ + +#ifndef LIBARCHIVE_ARCHIVE_WINDOWS_H_INCLUDED +#define LIBARCHIVE_ARCHIVE_WINDOWS_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +/* Start of configuration for native Win32 */ +#ifndef MINGW_HAS_SECURE_API +#define MINGW_HAS_SECURE_API 1 +#endif + +#include <errno.h> +#define set_errno(val) ((errno)=val) +#include <io.h> +#include <stdlib.h> //brings in NULL +#if defined(HAVE_STDINT_H) +#include <stdint.h> +#endif +#include <stdio.h> +#include <fcntl.h> +#include <sys/stat.h> +#include <process.h> +#include <direct.h> +#if defined(__MINGW32__) && defined(HAVE_UNISTD_H) +/* Prevent build error from a type mismatch of ftruncate(). + * This unistd.h defines it as ftruncate(int, off_t). */ +#include <unistd.h> +#endif +#define NOCRYPT +#include <windows.h> +//#define EFTYPE 7 + +#if defined(__BORLANDC__) +#pragma warn -8068 /* Constant out of range in comparison. */ +#pragma warn -8072 /* Suspicious pointer arithmetic. */ +#endif + +#ifndef NULL +#ifdef __cplusplus +#define NULL 0 +#else +#define NULL ((void *)0) +#endif +#endif + +/* Alias the Windows _function to the POSIX equivalent. */ +#define close _close +#define fcntl(fd, cmd, flg) /* No operation. */ +#ifndef fileno +#define fileno _fileno +#endif +#ifdef fstat +#undef fstat +#endif +#define fstat __la_fstat +#if !defined(__BORLANDC__) +#ifdef lseek +#undef lseek +#endif +#define lseek _lseeki64 +#else +#define lseek __la_lseek +#define __LA_LSEEK_NEEDED +#endif +#define lstat __la_stat +#define open __la_open +#define read __la_read +#if !defined(__BORLANDC__) && !defined(__WATCOMC__) +#define setmode _setmode +#endif +#define la_stat(path,stref) __la_stat(path,stref) +#if !defined(__WATCOMC__) +#if !defined(__BORLANDC__) +#define strdup _strdup +#endif +#define tzset _tzset +#if !defined(__BORLANDC__) +#define umask _umask +#endif +#endif +#define waitpid __la_waitpid +#define write __la_write + +#if !defined(__WATCOMC__) + +#ifndef O_RDONLY +#define O_RDONLY _O_RDONLY +#define O_WRONLY _O_WRONLY +#define O_TRUNC _O_TRUNC +#define O_CREAT _O_CREAT +#define O_EXCL _O_EXCL +#define O_BINARY _O_BINARY +#endif + +#ifndef _S_IFIFO + #define _S_IFIFO 0010000 /* pipe */ +#endif +#ifndef _S_IFCHR + #define _S_IFCHR 0020000 /* character special */ +#endif +#ifndef _S_IFDIR + #define _S_IFDIR 0040000 /* directory */ +#endif +#ifndef _S_IFBLK + #define _S_IFBLK 0060000 /* block special */ +#endif +#ifndef _S_IFLNK + #define _S_IFLNK 0120000 /* symbolic link */ +#endif +#ifndef _S_IFSOCK + #define _S_IFSOCK 0140000 /* socket */ +#endif +#ifndef _S_IFREG + #define _S_IFREG 0100000 /* regular */ +#endif +#ifndef _S_IFMT + #define _S_IFMT 0170000 /* file type mask */ +#endif + +#ifndef S_IFIFO +#define S_IFIFO _S_IFIFO +#endif +//#define S_IFCHR _S_IFCHR +//#define S_IFDIR _S_IFDIR +#ifndef S_IFBLK +#define S_IFBLK _S_IFBLK +#endif +#ifndef S_IFLNK +#define S_IFLNK _S_IFLNK +#endif +#ifndef S_IFSOCK +#define S_IFSOCK _S_IFSOCK +#endif +//#define S_IFREG _S_IFREG +//#define S_IFMT _S_IFMT + +#ifndef S_ISBLK +#define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK) /* block special */ +#define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO) /* fifo or socket */ +#define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR) /* char special */ +#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) /* directory */ +#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) /* regular file */ +#endif +#define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK) /* Symbolic link */ +#define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK) /* Socket */ + +#define _S_ISUID 0004000 /* set user id on execution */ +#define _S_ISGID 0002000 /* set group id on execution */ +#define _S_ISVTX 0001000 /* save swapped text even after use */ + +#define S_ISUID _S_ISUID +#define S_ISGID _S_ISGID +#define S_ISVTX _S_ISVTX + +#define _S_IRWXU (_S_IREAD | _S_IWRITE | _S_IEXEC) +#define _S_IXUSR _S_IEXEC /* read permission, user */ +#define _S_IWUSR _S_IWRITE /* write permission, user */ +#define _S_IRUSR _S_IREAD /* execute/search permission, user */ +#define _S_IRWXG (_S_IRWXU >> 3) +#define _S_IXGRP (_S_IXUSR >> 3) /* read permission, group */ +#define _S_IWGRP (_S_IWUSR >> 3) /* write permission, group */ +#define _S_IRGRP (_S_IRUSR >> 3) /* execute/search permission, group */ +#define _S_IRWXO (_S_IRWXG >> 3) +#define _S_IXOTH (_S_IXGRP >> 3) /* read permission, other */ +#define _S_IWOTH (_S_IWGRP >> 3) /* write permission, other */ +#define _S_IROTH (_S_IRGRP >> 3) /* execute/search permission, other */ + +#ifndef S_IRWXU +#define S_IRWXU _S_IRWXU +#define S_IXUSR _S_IXUSR +#define S_IWUSR _S_IWUSR +#define S_IRUSR _S_IRUSR +#endif +#ifndef S_IRWXG +#define S_IRWXG _S_IRWXG +#define S_IXGRP _S_IXGRP +#define S_IWGRP _S_IWGRP +#endif +#ifndef S_IRGRP +#define S_IRGRP _S_IRGRP +#endif +#ifndef S_IRWXO +#define S_IRWXO _S_IRWXO +#define S_IXOTH _S_IXOTH +#define S_IWOTH _S_IWOTH +#define S_IROTH _S_IROTH +#endif + +#endif + +#define F_DUPFD 0 /* Duplicate file descriptor. */ +#define F_GETFD 1 /* Get file descriptor flags. */ +#define F_SETFD 2 /* Set file descriptor flags. */ +#define F_GETFL 3 /* Get file status flags. */ +#define F_SETFL 4 /* Set file status flags. */ +#define F_GETOWN 5 /* Get owner (receiver of SIGIO). */ +#define F_SETOWN 6 /* Set owner (receiver of SIGIO). */ +#define F_GETLK 7 /* Get record locking info. */ +#define F_SETLK 8 /* Set record locking info (non-blocking). */ +#define F_SETLKW 9 /* Set record locking info (blocking). */ + +/* XXX missing */ +#define F_GETLK64 7 /* Get record locking info. */ +#define F_SETLK64 8 /* Set record locking info (non-blocking). */ +#define F_SETLKW64 9 /* Set record locking info (blocking). */ + +/* File descriptor flags used with F_GETFD and F_SETFD. */ +#define FD_CLOEXEC 1 /* Close on exec. */ + +//NOT SURE IF O_NONBLOCK is OK here but at least the 0x0004 flag is not used by anything else... +#define O_NONBLOCK 0x0004 /* Non-blocking I/O. */ +//#define O_NDELAY O_NONBLOCK + +/* Symbolic constants for the access() function */ +#if !defined(F_OK) + #define R_OK 4 /* Test for read permission */ + #define W_OK 2 /* Test for write permission */ + #define X_OK 1 /* Test for execute permission */ + #define F_OK 0 /* Test for existence of file */ +#endif + + +/* Replacement POSIX function */ +extern int __la_fstat(int fd, struct stat *st); +extern int __la_lstat(const char *path, struct stat *st); +#if defined(__LA_LSEEK_NEEDED) +extern __int64 __la_lseek(int fd, __int64 offset, int whence); +#endif +extern int __la_open(const char *path, int flags, ...); +extern ssize_t __la_read(int fd, void *buf, size_t nbytes); +extern int __la_stat(const char *path, struct stat *st); +extern pid_t __la_waitpid(HANDLE child, int *status, int option); +extern ssize_t __la_write(int fd, const void *buf, size_t nbytes); + +#define _stat64i32(path, st) __la_stat(path, st) +#define _stat64(path, st) __la_stat(path, st) +/* for status returned by la_waitpid */ +#define WIFEXITED(sts) ((sts & 0x100) == 0) +#define WEXITSTATUS(sts) (sts & 0x0FF) + +extern wchar_t *__la_win_permissive_name(const char *name); +extern wchar_t *__la_win_permissive_name_w(const wchar_t *wname); +extern void __la_dosmaperr(unsigned long e); +#define la_dosmaperr(e) __la_dosmaperr(e) +extern struct archive_entry *__la_win_entry_in_posix_pathseparator( + struct archive_entry *); + +#if defined(HAVE_WCRTOMB) && defined(__BORLANDC__) +typedef int mbstate_t; +size_t wcrtomb(char *, wchar_t, mbstate_t *); +#endif + +#if defined(_MSC_VER) && _MSC_VER < 1300 +WINBASEAPI BOOL WINAPI GetVolumePathNameW( + LPCWSTR lpszFileName, + LPWSTR lpszVolumePathName, + DWORD cchBufferLength + ); +# if _WIN32_WINNT < 0x0500 /* windows.h not providing 0x500 API */ +typedef struct _FILE_ALLOCATED_RANGE_BUFFER { + LARGE_INTEGER FileOffset; + LARGE_INTEGER Length; +} FILE_ALLOCATED_RANGE_BUFFER, *PFILE_ALLOCATED_RANGE_BUFFER; +# define FSCTL_SET_SPARSE \ + CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 49, METHOD_BUFFERED, FILE_WRITE_DATA) +# define FSCTL_QUERY_ALLOCATED_RANGES \ + CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 51, METHOD_NEITHER, FILE_READ_DATA) +# endif +#endif + +#endif /* LIBARCHIVE_ARCHIVE_WINDOWS_H_INCLUDED */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write.3 new file mode 100644 index 0000000000..e7f7f1384e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write.3 @@ -0,0 +1,268 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_WRITE 3 +.Os +.Sh NAME +.Nm archive_write +.Nd functions for creating archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Sh DESCRIPTION +These functions provide a complete API for creating streaming +archive files. +The general process is to first create the +.Tn struct archive +object, set any desired options, initialize the archive, append entries, then +close the archive and release all resources. +.\" +.Ss Create archive object +See +.Xr archive_write_new 3 . +.Pp +To write an archive, you must first obtain an initialized +.Tn struct archive +object from +.Fn archive_write_new . +.\" +.Ss Enable filters and formats, configure block size and padding +See +.Xr archive_write_filter 3 , +.Xr archive_write_format 3 +and +.Xr archive_write_blocksize 3 . +.Pp +You can then modify this object for the desired operations with the +various +.Fn archive_write_set_XXX +functions. +In particular, you will need to invoke appropriate +.Fn archive_write_add_XXX +and +.Fn archive_write_set_XXX +functions to enable the corresponding compression and format +support. +.\" +.Ss Set options +See +.Xr archive_write_set_options 3 . +.\" +.Ss Open archive +See +.Xr archive_write_open 3 . +.Pp +Once you have prepared the +.Tn struct archive +object, you call +.Fn archive_write_open +to actually open the archive and prepare it for writing. +There are several variants of this function; +the most basic expects you to provide pointers to several +functions that can provide blocks of bytes from the archive. +There are convenience forms that allow you to +specify a filename, file descriptor, +.Ft "FILE *" +object, or a block of memory from which to write the archive data. +.\" +.Ss Produce archive +See +.Xr archive_write_header 3 +and +.Xr archive_write_data 3 . +.Pp +Individual archive entries are written in a three-step +process: +You first initialize a +.Tn struct archive_entry +structure with information about the new entry. +At a minimum, you should set the pathname of the +entry and provide a +.Va struct stat +with a valid +.Va st_mode +field, which specifies the type of object and +.Va st_size +field, which specifies the size of the data portion of the object. +.\" +.Ss Release resources +See +.Xr archive_write_free 3 . +.Pp +After all entries have been written, use the +.Fn archive_write_free +function to release all resources. +.\" +.Sh EXAMPLES +The following sketch illustrates basic usage of the library. +In this example, +the callback functions are simply wrappers around the standard +.Xr open 2 , +.Xr write 2 , +and +.Xr close 2 +system calls. +.Bd -literal -offset indent +#ifdef __linux__ +#define _FILE_OFFSET_BITS 64 +#endif +#include <sys/stat.h> +#include <archive.h> +#include <archive_entry.h> +#include <fcntl.h> +#include <stdlib.h> +#include <unistd.h> + +struct mydata { + const char *name; + int fd; +}; + +int +myopen(struct archive *a, void *client_data) +{ + struct mydata *mydata = client_data; + + mydata->fd = open(mydata->name, O_WRONLY | O_CREAT, 0644); + if (mydata->fd >= 0) + return (ARCHIVE_OK); + else + return (ARCHIVE_FATAL); +} + +la_ssize_t +mywrite(struct archive *a, void *client_data, const void *buff, size_t n) +{ + struct mydata *mydata = client_data; + + return (write(mydata->fd, buff, n)); +} + +int +myclose(struct archive *a, void *client_data) +{ + struct mydata *mydata = client_data; + + if (mydata->fd > 0) + close(mydata->fd); + return (0); +} + +void +write_archive(const char *outname, const char **filename) +{ + struct mydata *mydata = malloc(sizeof(struct mydata)); + struct archive *a; + struct archive_entry *entry; + struct stat st; + char buff[8192]; + int len; + int fd; + + a = archive_write_new(); + mydata->name = outname; + /* Set archive format and filter according to output file extension. + * If it fails, set default format. Platform depended function. + * See supported formats in archive_write_set_format_filter_by_ext.c */ + if (archive_write_set_format_filter_by_ext(a, outname) != ARCHIVE_OK) { + archive_write_add_filter_gzip(a); + archive_write_set_format_ustar(a); + } + archive_write_open(a, mydata, myopen, mywrite, myclose); + while (*filename) { + stat(*filename, &st); + entry = archive_entry_new(); + archive_entry_copy_stat(entry, &st); + archive_entry_set_pathname(entry, *filename); + archive_write_header(a, entry); + if ((fd = open(*filename, O_RDONLY)) != -1) { + len = read(fd, buff, sizeof(buff)); + while (len > 0) { + archive_write_data(a, buff, len); + len = read(fd, buff, sizeof(buff)); + } + close(fd); + } + archive_entry_free(entry); + filename++; + } + archive_write_free(a); +} + +int main(int argc, const char **argv) +{ + const char *outname; + argv++; + outname = *argv++; + write_archive(outname, argv); + return 0; +} +.Ed +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_write_set_options 3 , +.Xr libarchive 3 , +.Xr cpio 5 , +.Xr mtree 5 , +.Xr tar 5 +.Sh HISTORY +The +.Nm libarchive +library first appeared in +.Fx 5.3 . +.Sh AUTHORS +.An -nosplit +The +.Nm libarchive +library was written by +.An Tim Kientzle Aq kientzle@acm.org . +.Sh BUGS +There are many peculiar bugs in historic tar implementations that may cause +certain programs to reject archives written by this library. +For example, several historic implementations calculated header checksums +incorrectly and will thus reject valid archives; GNU tar does not fully support +pax interchange format; some old tar implementations required specific +field terminations. +.Pp +The default pax interchange format eliminates most of the historic +tar limitations and provides a generic key/value attribute facility +for vendor-defined extensions. +One oversight in POSIX is the failure to provide a standard attribute +for large device numbers. +This library uses +.Dq SCHILY.devminor +and +.Dq SCHILY.devmajor +for device numbers that exceed the range supported by the backwards-compatible +ustar header. +These keys are compatible with Joerg Schilling's +.Nm star +archiver. +Other implementations may not recognize these keys and will thus be unable +to correctly restore device nodes with large device numbers from archives +created by this library. diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write.c new file mode 100644 index 0000000000..98a55fb2aa --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write.c @@ -0,0 +1,789 @@ +/*- + * Copyright (c) 2003-2010 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write.c 201099 2009-12-28 03:03:00Z kientzle $"); + +/* + * This file contains the "essential" portions of the write API, that + * is, stuff that will essentially always be used by any client that + * actually needs to write an archive. Optional pieces have been, as + * far as possible, separated out into separate files to reduce + * needlessly bloating statically-linked clients. + */ + +#ifdef HAVE_SYS_WAIT_H +#include <sys/wait.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#include <time.h> +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_write_private.h" + +static struct archive_vtable *archive_write_vtable(void); + +static int _archive_filter_code(struct archive *, int); +static const char *_archive_filter_name(struct archive *, int); +static int64_t _archive_filter_bytes(struct archive *, int); +static int _archive_write_filter_count(struct archive *); +static int _archive_write_close(struct archive *); +static int _archive_write_free(struct archive *); +static int _archive_write_header(struct archive *, struct archive_entry *); +static int _archive_write_finish_entry(struct archive *); +static ssize_t _archive_write_data(struct archive *, const void *, size_t); + +struct archive_none { + size_t buffer_size; + size_t avail; + char *buffer; + char *next; +}; + +static struct archive_vtable * +archive_write_vtable(void) +{ + static struct archive_vtable av; + static int inited = 0; + + if (!inited) { + av.archive_close = _archive_write_close; + av.archive_filter_bytes = _archive_filter_bytes; + av.archive_filter_code = _archive_filter_code; + av.archive_filter_name = _archive_filter_name; + av.archive_filter_count = _archive_write_filter_count; + av.archive_free = _archive_write_free; + av.archive_write_header = _archive_write_header; + av.archive_write_finish_entry = _archive_write_finish_entry; + av.archive_write_data = _archive_write_data; + inited = 1; + } + return (&av); +} + +/* + * Allocate, initialize and return an archive object. + */ +struct archive * +archive_write_new(void) +{ + struct archive_write *a; + unsigned char *nulls; + + a = (struct archive_write *)calloc(1, sizeof(*a)); + if (a == NULL) + return (NULL); + a->archive.magic = ARCHIVE_WRITE_MAGIC; + a->archive.state = ARCHIVE_STATE_NEW; + a->archive.vtable = archive_write_vtable(); + /* + * The value 10240 here matches the traditional tar default, + * but is otherwise arbitrary. + * TODO: Set the default block size from the format selected. + */ + a->bytes_per_block = 10240; + a->bytes_in_last_block = -1; /* Default */ + + /* Initialize a block of nulls for padding purposes. */ + a->null_length = 1024; + nulls = (unsigned char *)calloc(1, a->null_length); + if (nulls == NULL) { + free(a); + return (NULL); + } + a->nulls = nulls; + return (&a->archive); +} + +/* + * Set the block size. Returns 0 if successful. + */ +int +archive_write_set_bytes_per_block(struct archive *_a, int bytes_per_block) +{ + struct archive_write *a = (struct archive_write *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_bytes_per_block"); + a->bytes_per_block = bytes_per_block; + return (ARCHIVE_OK); +} + +/* + * Get the current block size. -1 if it has never been set. + */ +int +archive_write_get_bytes_per_block(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_ANY, "archive_write_get_bytes_per_block"); + return (a->bytes_per_block); +} + +/* + * Set the size for the last block. + * Returns 0 if successful. + */ +int +archive_write_set_bytes_in_last_block(struct archive *_a, int bytes) +{ + struct archive_write *a = (struct archive_write *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_ANY, "archive_write_set_bytes_in_last_block"); + a->bytes_in_last_block = bytes; + return (ARCHIVE_OK); +} + +/* + * Return the value set above. -1 indicates it has not been set. + */ +int +archive_write_get_bytes_in_last_block(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_ANY, "archive_write_get_bytes_in_last_block"); + return (a->bytes_in_last_block); +} + +/* + * dev/ino of a file to be rejected. Used to prevent adding + * an archive to itself recursively. + */ +int +archive_write_set_skip_file(struct archive *_a, la_int64_t d, la_int64_t i) +{ + struct archive_write *a = (struct archive_write *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_ANY, "archive_write_set_skip_file"); + a->skip_file_set = 1; + a->skip_file_dev = d; + a->skip_file_ino = i; + return (ARCHIVE_OK); +} + +/* + * Allocate and return the next filter structure. + */ +struct archive_write_filter * +__archive_write_allocate_filter(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct archive_write_filter *f; + + f = calloc(1, sizeof(*f)); + f->archive = _a; + f->state = ARCHIVE_WRITE_FILTER_STATE_NEW; + if (a->filter_first == NULL) + a->filter_first = f; + else + a->filter_last->next_filter = f; + a->filter_last = f; + return f; +} + +/* + * Write data to a particular filter. + */ +int +__archive_write_filter(struct archive_write_filter *f, + const void *buff, size_t length) +{ + int r; + /* Never write to non-open filters */ + if (f->state != ARCHIVE_WRITE_FILTER_STATE_OPEN) + return(ARCHIVE_FATAL); + if (length == 0) + return(ARCHIVE_OK); + if (f->write == NULL) + /* If unset, a fatal error has already occurred, so this filter + * didn't open. We cannot write anything. */ + return(ARCHIVE_FATAL); + r = (f->write)(f, buff, length); + f->bytes_written += length; + return (r); +} + +/* + * Recursive function for opening the filter chain + * Last filter is opened first + */ +static int +__archive_write_open_filter(struct archive_write_filter *f) +{ + int ret; + + ret = ARCHIVE_OK; + if (f->next_filter != NULL) + ret = __archive_write_open_filter(f->next_filter); + if (ret != ARCHIVE_OK) + return (ret); + if (f->state != ARCHIVE_WRITE_FILTER_STATE_NEW) + return (ARCHIVE_FATAL); + if (f->open == NULL) { + f->state = ARCHIVE_WRITE_FILTER_STATE_OPEN; + return (ARCHIVE_OK); + } + ret = (f->open)(f); + if (ret == ARCHIVE_OK) + f->state = ARCHIVE_WRITE_FILTER_STATE_OPEN; + else + f->state = ARCHIVE_WRITE_FILTER_STATE_FATAL; + return (ret); +} + +/* + * Open all filters + */ +static int +__archive_write_filters_open(struct archive_write *a) +{ + return (__archive_write_open_filter(a->filter_first)); +} + +/* + * Close all filtes + */ +static int +__archive_write_filters_close(struct archive_write *a) +{ + struct archive_write_filter *f; + int ret, ret1; + ret = ARCHIVE_OK; + for (f = a->filter_first; f != NULL; f = f->next_filter) { + /* Do not close filters that are not open */ + if (f->state == ARCHIVE_WRITE_FILTER_STATE_OPEN) { + if (f->close != NULL) { + ret1 = (f->close)(f); + if (ret1 < ret) + ret = ret1; + if (ret1 == ARCHIVE_OK) { + f->state = + ARCHIVE_WRITE_FILTER_STATE_CLOSED; + } else { + f->state = + ARCHIVE_WRITE_FILTER_STATE_FATAL; + } + } else + f->state = ARCHIVE_WRITE_FILTER_STATE_CLOSED; + } + } + return (ret); +} + +int +__archive_write_output(struct archive_write *a, const void *buff, size_t length) +{ + return (__archive_write_filter(a->filter_first, buff, length)); +} + +int +__archive_write_nulls(struct archive_write *a, size_t length) +{ + if (length == 0) + return (ARCHIVE_OK); + + while (length > 0) { + size_t to_write = length < a->null_length ? length : a->null_length; + int r = __archive_write_output(a, a->nulls, to_write); + if (r < ARCHIVE_OK) + return (r); + length -= to_write; + } + return (ARCHIVE_OK); +} + +static int +archive_write_client_open(struct archive_write_filter *f) +{ + struct archive_write *a = (struct archive_write *)f->archive; + struct archive_none *state; + void *buffer; + size_t buffer_size; + int ret; + + f->bytes_per_block = archive_write_get_bytes_per_block(f->archive); + f->bytes_in_last_block = + archive_write_get_bytes_in_last_block(f->archive); + buffer_size = f->bytes_per_block; + + state = (struct archive_none *)calloc(1, sizeof(*state)); + buffer = (char *)malloc(buffer_size); + if (state == NULL || buffer == NULL) { + free(state); + free(buffer); + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for output buffering"); + return (ARCHIVE_FATAL); + } + + state->buffer_size = buffer_size; + state->buffer = buffer; + state->next = state->buffer; + state->avail = state->buffer_size; + f->data = state; + + if (a->client_opener == NULL) + return (ARCHIVE_OK); + ret = a->client_opener(f->archive, a->client_data); + if (ret != ARCHIVE_OK) { + free(state->buffer); + free(state); + f->data = NULL; + } + return (ret); +} + +static int +archive_write_client_write(struct archive_write_filter *f, + const void *_buff, size_t length) +{ + struct archive_write *a = (struct archive_write *)f->archive; + struct archive_none *state = (struct archive_none *)f->data; + const char *buff = (const char *)_buff; + ssize_t remaining, to_copy; + ssize_t bytes_written; + + remaining = length; + + /* + * If there is no buffer for blocking, just pass the data + * straight through to the client write callback. In + * particular, this supports "no write delay" operation for + * special applications. Just set the block size to zero. + */ + if (state->buffer_size == 0) { + while (remaining > 0) { + bytes_written = (a->client_writer)(&a->archive, + a->client_data, buff, remaining); + if (bytes_written <= 0) + return (ARCHIVE_FATAL); + remaining -= bytes_written; + buff += bytes_written; + } + return (ARCHIVE_OK); + } + + /* If the copy buffer isn't empty, try to fill it. */ + if (state->avail < state->buffer_size) { + /* If buffer is not empty... */ + /* ... copy data into buffer ... */ + to_copy = ((size_t)remaining > state->avail) ? + state->avail : (size_t)remaining; + memcpy(state->next, buff, to_copy); + state->next += to_copy; + state->avail -= to_copy; + buff += to_copy; + remaining -= to_copy; + /* ... if it's full, write it out. */ + if (state->avail == 0) { + char *p = state->buffer; + size_t to_write = state->buffer_size; + while (to_write > 0) { + bytes_written = (a->client_writer)(&a->archive, + a->client_data, p, to_write); + if (bytes_written <= 0) + return (ARCHIVE_FATAL); + if ((size_t)bytes_written > to_write) { + archive_set_error(&(a->archive), + -1, "write overrun"); + return (ARCHIVE_FATAL); + } + p += bytes_written; + to_write -= bytes_written; + } + state->next = state->buffer; + state->avail = state->buffer_size; + } + } + + while ((size_t)remaining >= state->buffer_size) { + /* Write out full blocks directly to client. */ + bytes_written = (a->client_writer)(&a->archive, + a->client_data, buff, state->buffer_size); + if (bytes_written <= 0) + return (ARCHIVE_FATAL); + buff += bytes_written; + remaining -= bytes_written; + } + + if (remaining > 0) { + /* Copy last bit into copy buffer. */ + memcpy(state->next, buff, remaining); + state->next += remaining; + state->avail -= remaining; + } + return (ARCHIVE_OK); +} + +static int +archive_write_client_close(struct archive_write_filter *f) +{ + struct archive_write *a = (struct archive_write *)f->archive; + struct archive_none *state = (struct archive_none *)f->data; + ssize_t block_length; + ssize_t target_block_length; + ssize_t bytes_written; + int ret = ARCHIVE_OK; + + /* If there's pending data, pad and write the last block */ + if (state->next != state->buffer) { + block_length = state->buffer_size - state->avail; + + /* Tricky calculation to determine size of last block */ + if (a->bytes_in_last_block <= 0) + /* Default or Zero: pad to full block */ + target_block_length = a->bytes_per_block; + else + /* Round to next multiple of bytes_in_last_block. */ + target_block_length = a->bytes_in_last_block * + ( (block_length + a->bytes_in_last_block - 1) / + a->bytes_in_last_block); + if (target_block_length > a->bytes_per_block) + target_block_length = a->bytes_per_block; + if (block_length < target_block_length) { + memset(state->next, 0, + target_block_length - block_length); + block_length = target_block_length; + } + bytes_written = (a->client_writer)(&a->archive, + a->client_data, state->buffer, block_length); + ret = bytes_written <= 0 ? ARCHIVE_FATAL : ARCHIVE_OK; + } + if (a->client_closer) + (*a->client_closer)(&a->archive, a->client_data); + free(state->buffer); + free(state); + a->client_data = NULL; + /* Clear passphrase. */ + if (a->passphrase != NULL) { + memset(a->passphrase, 0, strlen(a->passphrase)); + free(a->passphrase); + a->passphrase = NULL; + } + /* Clear the close handler myself not to be called again. */ + f->state = ARCHIVE_WRITE_FILTER_STATE_CLOSED; + return (ret); +} + +/* + * Open the archive using the current settings. + */ +int +archive_write_open(struct archive *_a, void *client_data, + archive_open_callback *opener, archive_write_callback *writer, + archive_close_callback *closer) +{ + struct archive_write *a = (struct archive_write *)_a; + struct archive_write_filter *client_filter; + int ret, r1; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_open"); + archive_clear_error(&a->archive); + + a->client_writer = writer; + a->client_opener = opener; + a->client_closer = closer; + a->client_data = client_data; + + client_filter = __archive_write_allocate_filter(_a); + client_filter->open = archive_write_client_open; + client_filter->write = archive_write_client_write; + client_filter->close = archive_write_client_close; + + ret = __archive_write_filters_open(a); + if (ret < ARCHIVE_WARN) { + r1 = __archive_write_filters_close(a); + __archive_write_filters_free(_a); + return (r1 < ret ? r1 : ret); + } + + a->archive.state = ARCHIVE_STATE_HEADER; + if (a->format_init) + ret = (a->format_init)(a); + return (ret); +} + +/* + * Close out the archive. + */ +static int +_archive_write_close(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + int r = ARCHIVE_OK, r1 = ARCHIVE_OK; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, + "archive_write_close"); + if (a->archive.state == ARCHIVE_STATE_NEW + || a->archive.state == ARCHIVE_STATE_CLOSED) + return (ARCHIVE_OK); /* Okay to close() when not open. */ + + archive_clear_error(&a->archive); + + /* Finish the last entry if a finish callback is specified */ + if (a->archive.state == ARCHIVE_STATE_DATA + && a->format_finish_entry != NULL) + r = ((a->format_finish_entry)(a)); + + /* Finish off the archive. */ + /* TODO: have format closers invoke compression close. */ + if (a->format_close != NULL) { + r1 = (a->format_close)(a); + if (r1 < r) + r = r1; + } + + /* Finish the compression and close the stream. */ + r1 = __archive_write_filters_close(a); + if (r1 < r) + r = r1; + + if (a->archive.state != ARCHIVE_STATE_FATAL) + a->archive.state = ARCHIVE_STATE_CLOSED; + return (r); +} + +static int +_archive_write_filter_count(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct archive_write_filter *p = a->filter_first; + int count = 0; + while(p) { + count++; + p = p->next_filter; + } + return count; +} + +void +__archive_write_filters_free(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + int r = ARCHIVE_OK, r1; + + while (a->filter_first != NULL) { + struct archive_write_filter *next + = a->filter_first->next_filter; + if (a->filter_first->free != NULL) { + r1 = (*a->filter_first->free)(a->filter_first); + if (r > r1) + r = r1; + } + free(a->filter_first); + a->filter_first = next; + } + a->filter_last = NULL; +} + +/* + * Destroy the archive structure. + * + * Be careful: user might just call write_new and then write_free. + * Don't assume we actually wrote anything or performed any non-trivial + * initialization. + */ +static int +_archive_write_free(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + int r = ARCHIVE_OK, r1; + + if (_a == NULL) + return (ARCHIVE_OK); + /* It is okay to call free() in state FATAL. */ + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_free"); + if (a->archive.state != ARCHIVE_STATE_FATAL) + r = archive_write_close(&a->archive); + + /* Release format resources. */ + if (a->format_free != NULL) { + r1 = (a->format_free)(a); + if (r1 < r) + r = r1; + } + + __archive_write_filters_free(_a); + + /* Release various dynamic buffers. */ + free((void *)(uintptr_t)(const void *)a->nulls); + archive_string_free(&a->archive.error_string); + if (a->passphrase != NULL) { + /* A passphrase should be cleaned. */ + memset(a->passphrase, 0, strlen(a->passphrase)); + free(a->passphrase); + } + a->archive.magic = 0; + __archive_clean(&a->archive); + free(a); + return (r); +} + +/* + * Write the appropriate header. + */ +static int +_archive_write_header(struct archive *_a, struct archive_entry *entry) +{ + struct archive_write *a = (struct archive_write *)_a; + int ret, r2; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_DATA | ARCHIVE_STATE_HEADER, "archive_write_header"); + archive_clear_error(&a->archive); + + if (a->format_write_header == NULL) { + archive_set_error(&(a->archive), -1, + "Format must be set before you can write to an archive."); + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + + /* In particular, "retry" and "fatal" get returned immediately. */ + ret = archive_write_finish_entry(&a->archive); + if (ret == ARCHIVE_FATAL) { + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + if (ret < ARCHIVE_OK && ret != ARCHIVE_WARN) + return (ret); + + if (a->skip_file_set && + archive_entry_dev_is_set(entry) && + archive_entry_ino_is_set(entry) && + archive_entry_dev(entry) == (dev_t)a->skip_file_dev && + archive_entry_ino64(entry) == a->skip_file_ino) { + archive_set_error(&a->archive, 0, + "Can't add archive to itself"); + return (ARCHIVE_FAILED); + } + + /* Format and write header. */ + r2 = ((a->format_write_header)(a, entry)); + if (r2 == ARCHIVE_FAILED) { + return (ARCHIVE_FAILED); + } + if (r2 == ARCHIVE_FATAL) { + a->archive.state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); + } + if (r2 < ret) + ret = r2; + + a->archive.state = ARCHIVE_STATE_DATA; + return (ret); +} + +static int +_archive_write_finish_entry(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + int ret = ARCHIVE_OK; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_write_finish_entry"); + if (a->archive.state & ARCHIVE_STATE_DATA + && a->format_finish_entry != NULL) + ret = (a->format_finish_entry)(a); + a->archive.state = ARCHIVE_STATE_HEADER; + return (ret); +} + +/* + * Note that the compressor is responsible for blocking. + */ +static ssize_t +_archive_write_data(struct archive *_a, const void *buff, size_t s) +{ + struct archive_write *a = (struct archive_write *)_a; + const size_t max_write = INT_MAX; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_DATA, "archive_write_data"); + /* In particular, this catches attempts to pass negative values. */ + if (s > max_write) + s = max_write; + archive_clear_error(&a->archive); + return ((a->format_write_data)(a, buff, s)); +} + +static struct archive_write_filter * +filter_lookup(struct archive *_a, int n) +{ + struct archive_write *a = (struct archive_write *)_a; + struct archive_write_filter *f = a->filter_first; + if (n == -1) + return a->filter_last; + if (n < 0) + return NULL; + while (n > 0 && f != NULL) { + f = f->next_filter; + --n; + } + return f; +} + +static int +_archive_filter_code(struct archive *_a, int n) +{ + struct archive_write_filter *f = filter_lookup(_a, n); + return f == NULL ? -1 : f->code; +} + +static const char * +_archive_filter_name(struct archive *_a, int n) +{ + struct archive_write_filter *f = filter_lookup(_a, n); + return f != NULL ? f->name : NULL; +} + +static int64_t +_archive_filter_bytes(struct archive *_a, int n) +{ + struct archive_write_filter *f = filter_lookup(_a, n); + return f == NULL ? -1 : f->bytes_written; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter.c new file mode 100644 index 0000000000..203f4142b5 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter.c @@ -0,0 +1,72 @@ +/*- + * Copyright (c) 2012 Ondrej Holy + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif + +#include "archive.h" +#include "archive_private.h" + +/* A table that maps filter codes to functions. */ +static const +struct { int code; int (*setter)(struct archive *); } codes[] = +{ + { ARCHIVE_FILTER_NONE, archive_write_add_filter_none }, + { ARCHIVE_FILTER_GZIP, archive_write_add_filter_gzip }, + { ARCHIVE_FILTER_BZIP2, archive_write_add_filter_bzip2 }, + { ARCHIVE_FILTER_COMPRESS, archive_write_add_filter_compress }, + { ARCHIVE_FILTER_GRZIP, archive_write_add_filter_grzip }, + { ARCHIVE_FILTER_LRZIP, archive_write_add_filter_lrzip }, + { ARCHIVE_FILTER_LZ4, archive_write_add_filter_lz4 }, + { ARCHIVE_FILTER_LZIP, archive_write_add_filter_lzip }, + { ARCHIVE_FILTER_LZMA, archive_write_add_filter_lzma }, + { ARCHIVE_FILTER_LZOP, archive_write_add_filter_lzip }, + { ARCHIVE_FILTER_UU, archive_write_add_filter_uuencode }, + { ARCHIVE_FILTER_XZ, archive_write_add_filter_xz }, + { ARCHIVE_FILTER_ZSTD, archive_write_add_filter_zstd }, + { -1, NULL } +}; + +int +archive_write_add_filter(struct archive *a, int code) +{ + int i; + + for (i = 0; codes[i].code != -1; i++) { + if (code == codes[i].code) + return ((codes[i].setter)(a)); + } + + archive_set_error(a, EINVAL, "No such filter"); + return (ARCHIVE_FATAL); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_b64encode.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_b64encode.c new file mode 100644 index 0000000000..87fdb73ecb --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_b64encode.c @@ -0,0 +1,304 @@ +/*- + * Copyright (c) 2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_string.h" +#include "archive_write_private.h" + +#define LBYTES 57 + +struct private_b64encode { + int mode; + struct archive_string name; + struct archive_string encoded_buff; + size_t bs; + size_t hold_len; + unsigned char hold[LBYTES]; +}; + +static int archive_filter_b64encode_options(struct archive_write_filter *, + const char *, const char *); +static int archive_filter_b64encode_open(struct archive_write_filter *); +static int archive_filter_b64encode_write(struct archive_write_filter *, + const void *, size_t); +static int archive_filter_b64encode_close(struct archive_write_filter *); +static int archive_filter_b64encode_free(struct archive_write_filter *); +static void la_b64_encode(struct archive_string *, const unsigned char *, size_t); +static int64_t atol8(const char *, size_t); + +static const char base64[] = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', + 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', + 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', + '4', '5', '6', '7', '8', '9', '+', '/' +}; + +/* + * Add a compress filter to this write handle. + */ +int +archive_write_add_filter_b64encode(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct archive_write_filter *f = __archive_write_allocate_filter(_a); + struct private_b64encode *state; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_add_filter_uu"); + + state = (struct private_b64encode *)calloc(1, sizeof(*state)); + if (state == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for b64encode filter"); + return (ARCHIVE_FATAL); + } + archive_strcpy(&state->name, "-"); + state->mode = 0644; + + f->data = state; + f->name = "b64encode"; + f->code = ARCHIVE_FILTER_UU; + f->open = archive_filter_b64encode_open; + f->options = archive_filter_b64encode_options; + f->write = archive_filter_b64encode_write; + f->close = archive_filter_b64encode_close; + f->free = archive_filter_b64encode_free; + + return (ARCHIVE_OK); +} + +/* + * Set write options. + */ +static int +archive_filter_b64encode_options(struct archive_write_filter *f, const char *key, + const char *value) +{ + struct private_b64encode *state = (struct private_b64encode *)f->data; + + if (strcmp(key, "mode") == 0) { + if (value == NULL) { + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "mode option requires octal digits"); + return (ARCHIVE_FAILED); + } + state->mode = (int)atol8(value, strlen(value)) & 0777; + return (ARCHIVE_OK); + } else if (strcmp(key, "name") == 0) { + if (value == NULL) { + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "name option requires a string"); + return (ARCHIVE_FAILED); + } + archive_strcpy(&state->name, value); + return (ARCHIVE_OK); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +/* + * Setup callback. + */ +static int +archive_filter_b64encode_open(struct archive_write_filter *f) +{ + struct private_b64encode *state = (struct private_b64encode *)f->data; + size_t bs = 65536, bpb; + + if (f->archive->magic == ARCHIVE_WRITE_MAGIC) { + /* Buffer size should be a multiple number of the of bytes + * per block for performance. */ + bpb = archive_write_get_bytes_per_block(f->archive); + if (bpb > bs) + bs = bpb; + else if (bpb != 0) + bs -= bs % bpb; + } + + state->bs = bs; + if (archive_string_ensure(&state->encoded_buff, bs + 512) == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for b64encode buffer"); + return (ARCHIVE_FATAL); + } + + archive_string_sprintf(&state->encoded_buff, "begin-base64 %o %s\n", + state->mode, state->name.s); + + f->data = state; + return (0); +} + +static void +la_b64_encode(struct archive_string *as, const unsigned char *p, size_t len) +{ + int c; + + for (; len >= 3; p += 3, len -= 3) { + c = p[0] >> 2; + archive_strappend_char(as, base64[c]); + c = ((p[0] & 0x03) << 4) | ((p[1] & 0xf0) >> 4); + archive_strappend_char(as, base64[c]); + c = ((p[1] & 0x0f) << 2) | ((p[2] & 0xc0) >> 6); + archive_strappend_char(as, base64[c]); + c = p[2] & 0x3f; + archive_strappend_char(as, base64[c]); + } + if (len > 0) { + c = p[0] >> 2; + archive_strappend_char(as, base64[c]); + c = (p[0] & 0x03) << 4; + if (len == 1) { + archive_strappend_char(as, base64[c]); + archive_strappend_char(as, '='); + archive_strappend_char(as, '='); + } else { + c |= (p[1] & 0xf0) >> 4; + archive_strappend_char(as, base64[c]); + c = (p[1] & 0x0f) << 2; + archive_strappend_char(as, base64[c]); + archive_strappend_char(as, '='); + } + } + archive_strappend_char(as, '\n'); +} + +/* + * Write data to the encoded stream. + */ +static int +archive_filter_b64encode_write(struct archive_write_filter *f, const void *buff, + size_t length) +{ + struct private_b64encode *state = (struct private_b64encode *)f->data; + const unsigned char *p = buff; + int ret = ARCHIVE_OK; + + if (length == 0) + return (ret); + + if (state->hold_len) { + while (state->hold_len < LBYTES && length > 0) { + state->hold[state->hold_len++] = *p++; + length--; + } + if (state->hold_len < LBYTES) + return (ret); + la_b64_encode(&state->encoded_buff, state->hold, LBYTES); + state->hold_len = 0; + } + + for (; length >= LBYTES; length -= LBYTES, p += LBYTES) + la_b64_encode(&state->encoded_buff, p, LBYTES); + + /* Save remaining bytes. */ + if (length > 0) { + memcpy(state->hold, p, length); + state->hold_len = length; + } + while (archive_strlen(&state->encoded_buff) >= state->bs) { + ret = __archive_write_filter(f->next_filter, + state->encoded_buff.s, state->bs); + memmove(state->encoded_buff.s, + state->encoded_buff.s + state->bs, + state->encoded_buff.length - state->bs); + state->encoded_buff.length -= state->bs; + } + + return (ret); +} + + +/* + * Finish the compression... + */ +static int +archive_filter_b64encode_close(struct archive_write_filter *f) +{ + struct private_b64encode *state = (struct private_b64encode *)f->data; + + /* Flush remaining bytes. */ + if (state->hold_len != 0) + la_b64_encode(&state->encoded_buff, state->hold, state->hold_len); + archive_string_sprintf(&state->encoded_buff, "====\n"); + /* Write the last block */ + archive_write_set_bytes_in_last_block(f->archive, 1); + return __archive_write_filter(f->next_filter, + state->encoded_buff.s, archive_strlen(&state->encoded_buff)); +} + +static int +archive_filter_b64encode_free(struct archive_write_filter *f) +{ + struct private_b64encode *state = (struct private_b64encode *)f->data; + + archive_string_free(&state->name); + archive_string_free(&state->encoded_buff); + free(state); + return (ARCHIVE_OK); +} + +static int64_t +atol8(const char *p, size_t char_cnt) +{ + int64_t l; + int digit; + + l = 0; + while (char_cnt-- > 0) { + if (*p >= '0' && *p <= '7') + digit = *p - '0'; + else + break; + p++; + l <<= 3; + l |= digit; + } + return (l); +} + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_by_name.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_by_name.c new file mode 100644 index 0000000000..ffa633c963 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_by_name.c @@ -0,0 +1,77 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_private.h" + +/* A table that maps names to functions. */ +static const +struct { const char *name; int (*setter)(struct archive *); } names[] = +{ + { "b64encode", archive_write_add_filter_b64encode }, + { "bzip2", archive_write_add_filter_bzip2 }, + { "compress", archive_write_add_filter_compress }, + { "grzip", archive_write_add_filter_grzip }, + { "gzip", archive_write_add_filter_gzip }, + { "lrzip", archive_write_add_filter_lrzip }, + { "lz4", archive_write_add_filter_lz4 }, + { "lzip", archive_write_add_filter_lzip }, + { "lzma", archive_write_add_filter_lzma }, + { "lzop", archive_write_add_filter_lzop }, + { "uuencode", archive_write_add_filter_uuencode }, + { "xz", archive_write_add_filter_xz }, + { "zstd", archive_write_add_filter_zstd }, + { NULL, NULL } +}; + +int +archive_write_add_filter_by_name(struct archive *a, const char *name) +{ + int i; + + for (i = 0; names[i].name != NULL; i++) { + if (strcmp(name, names[i].name) == 0) + return ((names[i].setter)(a)); + } + + archive_set_error(a, EINVAL, "No such filter '%s'", name); + a->state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_bzip2.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_bzip2.c new file mode 100644 index 0000000000..7001e9c6b3 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_bzip2.c @@ -0,0 +1,401 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_compression_bzip2.c 201091 2009-12-28 02:22:41Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_BZLIB_H +#include <bzlib.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_write_private.h" + +#if ARCHIVE_VERSION_NUMBER < 4000000 +int +archive_write_set_compression_bzip2(struct archive *a) +{ + __archive_write_filters_free(a); + return (archive_write_add_filter_bzip2(a)); +} +#endif + +struct private_data { + int compression_level; +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) + bz_stream stream; + int64_t total_in; + char *compressed; + size_t compressed_buffer_size; +#else + struct archive_write_program_data *pdata; +#endif +}; + +static int archive_compressor_bzip2_close(struct archive_write_filter *); +static int archive_compressor_bzip2_free(struct archive_write_filter *); +static int archive_compressor_bzip2_open(struct archive_write_filter *); +static int archive_compressor_bzip2_options(struct archive_write_filter *, + const char *, const char *); +static int archive_compressor_bzip2_write(struct archive_write_filter *, + const void *, size_t); + +/* + * Add a bzip2 compression filter to this write handle. + */ +int +archive_write_add_filter_bzip2(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct archive_write_filter *f = __archive_write_allocate_filter(_a); + struct private_data *data; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_add_filter_bzip2"); + + data = calloc(1, sizeof(*data)); + if (data == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + data->compression_level = 9; /* default */ + + f->data = data; + f->options = &archive_compressor_bzip2_options; + f->close = &archive_compressor_bzip2_close; + f->free = &archive_compressor_bzip2_free; + f->open = &archive_compressor_bzip2_open; + f->code = ARCHIVE_FILTER_BZIP2; + f->name = "bzip2"; +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) + return (ARCHIVE_OK); +#else + data->pdata = __archive_write_program_allocate("bzip2"); + if (data->pdata == NULL) { + free(data); + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + data->compression_level = 0; + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Using external bzip2 program"); + return (ARCHIVE_WARN); +#endif +} + +/* + * Set write options. + */ +static int +archive_compressor_bzip2_options(struct archive_write_filter *f, + const char *key, const char *value) +{ + struct private_data *data = (struct private_data *)f->data; + + if (strcmp(key, "compression-level") == 0) { + if (value == NULL || !(value[0] >= '0' && value[0] <= '9') || + value[1] != '\0') + return (ARCHIVE_WARN); + data->compression_level = value[0] - '0'; + /* Make '0' be a synonym for '1'. */ + /* This way, bzip2 compressor supports the same 0..9 + * range of levels as gzip. */ + if (data->compression_level < 1) + data->compression_level = 1; + return (ARCHIVE_OK); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) +/* Don't compile this if we don't have bzlib. */ + +/* + * Yuck. bzlib.h is not const-correct, so I need this one bit + * of ugly hackery to convert a const * pointer to a non-const pointer. + */ +#define SET_NEXT_IN(st,src) \ + (st)->stream.next_in = (char *)(uintptr_t)(const void *)(src) +static int drive_compressor(struct archive_write_filter *, + struct private_data *, int finishing); + +/* + * Setup callback. + */ +static int +archive_compressor_bzip2_open(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + int ret; + + if (data->compressed == NULL) { + size_t bs = 65536, bpb; + if (f->archive->magic == ARCHIVE_WRITE_MAGIC) { + /* Buffer size should be a multiple number of the of bytes + * per block for performance. */ + bpb = archive_write_get_bytes_per_block(f->archive); + if (bpb > bs) + bs = bpb; + else if (bpb != 0) + bs -= bs % bpb; + } + data->compressed_buffer_size = bs; + data->compressed + = (char *)malloc(data->compressed_buffer_size); + if (data->compressed == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for compression buffer"); + return (ARCHIVE_FATAL); + } + } + + memset(&data->stream, 0, sizeof(data->stream)); + data->stream.next_out = data->compressed; + data->stream.avail_out = data->compressed_buffer_size; + f->write = archive_compressor_bzip2_write; + + /* Initialize compression library */ + ret = BZ2_bzCompressInit(&(data->stream), + data->compression_level, 0, 30); + if (ret == BZ_OK) { + f->data = data; + return (ARCHIVE_OK); + } + + /* Library setup failed: clean up. */ + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library"); + + /* Override the error message if we know what really went wrong. */ + switch (ret) { + case BZ_PARAM_ERROR: + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library: " + "invalid setup parameter"); + break; + case BZ_MEM_ERROR: + archive_set_error(f->archive, ENOMEM, + "Internal error initializing compression library: " + "out of memory"); + break; + case BZ_CONFIG_ERROR: + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library: " + "mis-compiled library"); + break; + } + + return (ARCHIVE_FATAL); + +} + +/* + * Write data to the compressed stream. + * + * Returns ARCHIVE_OK if all data written, error otherwise. + */ +static int +archive_compressor_bzip2_write(struct archive_write_filter *f, + const void *buff, size_t length) +{ + struct private_data *data = (struct private_data *)f->data; + + /* Update statistics */ + data->total_in += length; + + /* Compress input data to output buffer */ + SET_NEXT_IN(data, buff); + data->stream.avail_in = length; + if (drive_compressor(f, data, 0)) + return (ARCHIVE_FATAL); + return (ARCHIVE_OK); +} + + +/* + * Finish the compression. + */ +static int +archive_compressor_bzip2_close(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + int ret; + + /* Finish compression cycle. */ + ret = drive_compressor(f, data, 1); + if (ret == ARCHIVE_OK) { + /* Write the last block */ + ret = __archive_write_filter(f->next_filter, + data->compressed, + data->compressed_buffer_size - data->stream.avail_out); + } + + switch (BZ2_bzCompressEnd(&(data->stream))) { + case BZ_OK: + break; + default: + archive_set_error(f->archive, ARCHIVE_ERRNO_PROGRAMMER, + "Failed to clean up compressor"); + ret = ARCHIVE_FATAL; + } + return ret; +} + +static int +archive_compressor_bzip2_free(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + free(data->compressed); + free(data); + f->data = NULL; + return (ARCHIVE_OK); +} + +/* + * Utility function to push input data through compressor, writing + * full output blocks as necessary. + * + * Note that this handles both the regular write case (finishing == + * false) and the end-of-archive case (finishing == true). + */ +static int +drive_compressor(struct archive_write_filter *f, + struct private_data *data, int finishing) +{ + int ret; + + for (;;) { + if (data->stream.avail_out == 0) { + ret = __archive_write_filter(f->next_filter, + data->compressed, + data->compressed_buffer_size); + if (ret != ARCHIVE_OK) { + /* TODO: Handle this write failure */ + return (ARCHIVE_FATAL); + } + data->stream.next_out = data->compressed; + data->stream.avail_out = data->compressed_buffer_size; + } + + /* If there's nothing to do, we're done. */ + if (!finishing && data->stream.avail_in == 0) + return (ARCHIVE_OK); + + ret = BZ2_bzCompress(&(data->stream), + finishing ? BZ_FINISH : BZ_RUN); + + switch (ret) { + case BZ_RUN_OK: + /* In non-finishing case, did compressor + * consume everything? */ + if (!finishing && data->stream.avail_in == 0) + return (ARCHIVE_OK); + break; + case BZ_FINISH_OK: /* Finishing: There's more work to do */ + break; + case BZ_STREAM_END: /* Finishing: all done */ + /* Only occurs in finishing case */ + return (ARCHIVE_OK); + default: + /* Any other return value indicates an error */ + archive_set_error(f->archive, + ARCHIVE_ERRNO_PROGRAMMER, + "Bzip2 compression failed;" + " BZ2_bzCompress() returned %d", + ret); + return (ARCHIVE_FATAL); + } + } +} + +#else /* HAVE_BZLIB_H && BZ_CONFIG_ERROR */ + +static int +archive_compressor_bzip2_open(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + struct archive_string as; + int r; + + archive_string_init(&as); + archive_strcpy(&as, "bzip2"); + + /* Specify compression level. */ + if (data->compression_level > 0) { + archive_strcat(&as, " -"); + archive_strappend_char(&as, '0' + data->compression_level); + } + f->write = archive_compressor_bzip2_write; + + r = __archive_write_program_open(f, data->pdata, as.s); + archive_string_free(&as); + return (r); +} + +static int +archive_compressor_bzip2_write(struct archive_write_filter *f, const void *buff, + size_t length) +{ + struct private_data *data = (struct private_data *)f->data; + + return __archive_write_program_write(f, data->pdata, buff, length); +} + +static int +archive_compressor_bzip2_close(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + + return __archive_write_program_close(f, data->pdata); +} + +static int +archive_compressor_bzip2_free(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + + __archive_write_program_free(data->pdata); + free(data); + return (ARCHIVE_OK); +} + +#endif /* HAVE_BZLIB_H && BZ_CONFIG_ERROR */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_compress.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_compress.c new file mode 100644 index 0000000000..d404fae7db --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_compress.c @@ -0,0 +1,447 @@ +/*- + * Copyright (c) 2008 Joerg Sonnenberger + * 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(S) ``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(S) 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. + */ + +/*- + * Copyright (c) 1985, 1986, 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Diomidis Spinellis and James A. Woods, derived from original + * work by Spencer Thomas and Joseph Orost. + * + * 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. + * 3. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_compression_compress.c 201111 2009-12-28 03:33:05Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_write_private.h" + +#define HSIZE 69001 /* 95% occupancy */ +#define HSHIFT 8 /* 8 - trunc(log2(HSIZE / 65536)) */ +#define CHECK_GAP 10000 /* Ratio check interval. */ + +#define MAXCODE(bits) ((1 << (bits)) - 1) + +/* + * the next two codes should not be changed lightly, as they must not + * lie within the contiguous general code space. + */ +#define FIRST 257 /* First free entry. */ +#define CLEAR 256 /* Table clear output code. */ + +struct private_data { + int64_t in_count, out_count, checkpoint; + + int code_len; /* Number of bits/code. */ + int cur_maxcode; /* Maximum code, given n_bits. */ + int max_maxcode; /* Should NEVER generate this code. */ + int hashtab [HSIZE]; + unsigned short codetab [HSIZE]; + int first_free; /* First unused entry. */ + int compress_ratio; + + int cur_code, cur_fcode; + + int bit_offset; + unsigned char bit_buf; + + unsigned char *compressed; + size_t compressed_buffer_size; + size_t compressed_offset; +}; + +static int archive_compressor_compress_open(struct archive_write_filter *); +static int archive_compressor_compress_write(struct archive_write_filter *, + const void *, size_t); +static int archive_compressor_compress_close(struct archive_write_filter *); +static int archive_compressor_compress_free(struct archive_write_filter *); + +#if ARCHIVE_VERSION_NUMBER < 4000000 +int +archive_write_set_compression_compress(struct archive *a) +{ + __archive_write_filters_free(a); + return (archive_write_add_filter_compress(a)); +} +#endif + +/* + * Add a compress filter to this write handle. + */ +int +archive_write_add_filter_compress(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct archive_write_filter *f = __archive_write_allocate_filter(_a); + + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_add_filter_compress"); + f->open = &archive_compressor_compress_open; + f->code = ARCHIVE_FILTER_COMPRESS; + f->name = "compress"; + return (ARCHIVE_OK); +} + +/* + * Setup callback. + */ +static int +archive_compressor_compress_open(struct archive_write_filter *f) +{ + struct private_data *state; + size_t bs = 65536, bpb; + + f->code = ARCHIVE_FILTER_COMPRESS; + f->name = "compress"; + + state = (struct private_data *)calloc(1, sizeof(*state)); + if (state == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for compression"); + return (ARCHIVE_FATAL); + } + + if (f->archive->magic == ARCHIVE_WRITE_MAGIC) { + /* Buffer size should be a multiple number of the of bytes + * per block for performance. */ + bpb = archive_write_get_bytes_per_block(f->archive); + if (bpb > bs) + bs = bpb; + else if (bpb != 0) + bs -= bs % bpb; + } + state->compressed_buffer_size = bs; + state->compressed = malloc(state->compressed_buffer_size); + + if (state->compressed == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for compression buffer"); + free(state); + return (ARCHIVE_FATAL); + } + + f->write = archive_compressor_compress_write; + f->close = archive_compressor_compress_close; + f->free = archive_compressor_compress_free; + + state->max_maxcode = 0x10000; /* Should NEVER generate this code. */ + state->in_count = 0; /* Length of input. */ + state->bit_buf = 0; + state->bit_offset = 0; + state->out_count = 3; /* Includes 3-byte header mojo. */ + state->compress_ratio = 0; + state->checkpoint = CHECK_GAP; + state->code_len = 9; + state->cur_maxcode = MAXCODE(state->code_len); + state->first_free = FIRST; + + memset(state->hashtab, 0xff, sizeof(state->hashtab)); + + /* Prime output buffer with a gzip header. */ + state->compressed[0] = 0x1f; /* Compress */ + state->compressed[1] = 0x9d; + state->compressed[2] = 0x90; /* Block mode, 16bit max */ + state->compressed_offset = 3; + + f->data = state; + return (0); +} + +/*- + * Output the given code. + * Inputs: + * code: A n_bits-bit integer. If == -1, then EOF. This assumes + * that n_bits <= (long)wordsize - 1. + * Outputs: + * Outputs code to the file. + * Assumptions: + * Chars are 8 bits long. + * Algorithm: + * Maintain a BITS character long buffer (so that 8 codes will + * fit in it exactly). Use the VAX insv instruction to insert each + * code in turn. When the buffer fills up empty it and start over. + */ + +static const unsigned char rmask[9] = + {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff}; + +static int +output_byte(struct archive_write_filter *f, unsigned char c) +{ + struct private_data *state = f->data; + + state->compressed[state->compressed_offset++] = c; + ++state->out_count; + + if (state->compressed_buffer_size == state->compressed_offset) { + int ret = __archive_write_filter(f->next_filter, + state->compressed, state->compressed_buffer_size); + if (ret != ARCHIVE_OK) + return ARCHIVE_FATAL; + state->compressed_offset = 0; + } + + return ARCHIVE_OK; +} + +static int +output_code(struct archive_write_filter *f, int ocode) +{ + struct private_data *state = f->data; + int bits, ret, clear_flg, bit_offset; + + clear_flg = ocode == CLEAR; + + /* + * Since ocode is always >= 8 bits, only need to mask the first + * hunk on the left. + */ + bit_offset = state->bit_offset % 8; + state->bit_buf |= (ocode << bit_offset) & 0xff; + output_byte(f, state->bit_buf); + + bits = state->code_len - (8 - bit_offset); + ocode >>= 8 - bit_offset; + /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */ + if (bits >= 8) { + output_byte(f, ocode & 0xff); + ocode >>= 8; + bits -= 8; + } + /* Last bits. */ + state->bit_offset += state->code_len; + state->bit_buf = ocode & rmask[bits]; + if (state->bit_offset == state->code_len * 8) + state->bit_offset = 0; + + /* + * If the next entry is going to be too big for the ocode size, + * then increase it, if possible. + */ + if (clear_flg || state->first_free > state->cur_maxcode) { + /* + * Write the whole buffer, because the input side won't + * discover the size increase until after it has read it. + */ + if (state->bit_offset > 0) { + while (state->bit_offset < state->code_len * 8) { + ret = output_byte(f, state->bit_buf); + if (ret != ARCHIVE_OK) + return ret; + state->bit_offset += 8; + state->bit_buf = 0; + } + } + state->bit_buf = 0; + state->bit_offset = 0; + + if (clear_flg) { + state->code_len = 9; + state->cur_maxcode = MAXCODE(state->code_len); + } else { + state->code_len++; + if (state->code_len == 16) + state->cur_maxcode = state->max_maxcode; + else + state->cur_maxcode = MAXCODE(state->code_len); + } + } + + return (ARCHIVE_OK); +} + +static int +output_flush(struct archive_write_filter *f) +{ + struct private_data *state = f->data; + int ret; + + /* At EOF, write the rest of the buffer. */ + if (state->bit_offset % 8) { + state->code_len = (state->bit_offset % 8 + 7) / 8; + ret = output_byte(f, state->bit_buf); + if (ret != ARCHIVE_OK) + return ret; + } + + return (ARCHIVE_OK); +} + +/* + * Write data to the compressed stream. + */ +static int +archive_compressor_compress_write(struct archive_write_filter *f, + const void *buff, size_t length) +{ + struct private_data *state = (struct private_data *)f->data; + int i; + int ratio; + int c, disp, ret; + const unsigned char *bp; + + if (length == 0) + return ARCHIVE_OK; + + bp = buff; + + if (state->in_count == 0) { + state->cur_code = *bp++; + ++state->in_count; + --length; + } + + while (length--) { + c = *bp++; + state->in_count++; + state->cur_fcode = (c << 16) + state->cur_code; + i = ((c << HSHIFT) ^ state->cur_code); /* Xor hashing. */ + + if (state->hashtab[i] == state->cur_fcode) { + state->cur_code = state->codetab[i]; + continue; + } + if (state->hashtab[i] < 0) /* Empty slot. */ + goto nomatch; + /* Secondary hash (after G. Knott). */ + if (i == 0) + disp = 1; + else + disp = HSIZE - i; + probe: + if ((i -= disp) < 0) + i += HSIZE; + + if (state->hashtab[i] == state->cur_fcode) { + state->cur_code = state->codetab[i]; + continue; + } + if (state->hashtab[i] >= 0) + goto probe; + nomatch: + ret = output_code(f, state->cur_code); + if (ret != ARCHIVE_OK) + return ret; + state->cur_code = c; + if (state->first_free < state->max_maxcode) { + state->codetab[i] = state->first_free++; /* code -> hashtable */ + state->hashtab[i] = state->cur_fcode; + continue; + } + if (state->in_count < state->checkpoint) + continue; + + state->checkpoint = state->in_count + CHECK_GAP; + + if (state->in_count <= 0x007fffff && state->out_count != 0) + ratio = (int)(state->in_count * 256 / state->out_count); + else if ((ratio = (int)(state->out_count / 256)) == 0) + ratio = 0x7fffffff; + else + ratio = (int)(state->in_count / ratio); + + if (ratio > state->compress_ratio) + state->compress_ratio = ratio; + else { + state->compress_ratio = 0; + memset(state->hashtab, 0xff, sizeof(state->hashtab)); + state->first_free = FIRST; + ret = output_code(f, CLEAR); + if (ret != ARCHIVE_OK) + return ret; + } + } + + return (ARCHIVE_OK); +} + + +/* + * Finish the compression... + */ +static int +archive_compressor_compress_close(struct archive_write_filter *f) +{ + struct private_data *state = (struct private_data *)f->data; + int ret; + + ret = output_code(f, state->cur_code); + if (ret != ARCHIVE_OK) + return ret; + ret = output_flush(f); + if (ret != ARCHIVE_OK) + return ret; + + /* Write the last block */ + ret = __archive_write_filter(f->next_filter, + state->compressed, state->compressed_offset); + return (ret); +} + +static int +archive_compressor_compress_free(struct archive_write_filter *f) +{ + struct private_data *state = (struct private_data *)f->data; + + free(state->compressed); + free(state); + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_grzip.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_grzip.c new file mode 100644 index 0000000000..371102d74c --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_grzip.c @@ -0,0 +1,135 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif + +#include "archive.h" +#include "archive_write_private.h" + +struct write_grzip { + struct archive_write_program_data *pdata; +}; + +static int archive_write_grzip_open(struct archive_write_filter *); +static int archive_write_grzip_options(struct archive_write_filter *, + const char *, const char *); +static int archive_write_grzip_write(struct archive_write_filter *, + const void *, size_t); +static int archive_write_grzip_close(struct archive_write_filter *); +static int archive_write_grzip_free(struct archive_write_filter *); + +int +archive_write_add_filter_grzip(struct archive *_a) +{ + struct archive_write_filter *f = __archive_write_allocate_filter(_a); + struct write_grzip *data; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_add_filter_grzip"); + + data = calloc(1, sizeof(*data)); + if (data == NULL) { + archive_set_error(_a, ENOMEM, "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + data->pdata = __archive_write_program_allocate("grzip"); + if (data->pdata == NULL) { + free(data); + archive_set_error(_a, ENOMEM, "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + + f->name = "grzip"; + f->code = ARCHIVE_FILTER_GRZIP; + f->data = data; + f->open = archive_write_grzip_open; + f->options = archive_write_grzip_options; + f->write = archive_write_grzip_write; + f->close = archive_write_grzip_close; + f->free = archive_write_grzip_free; + + /* Note: This filter always uses an external program, so we + * return "warn" to inform of the fact. */ + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "Using external grzip program for grzip compression"); + return (ARCHIVE_WARN); +} + +static int +archive_write_grzip_options(struct archive_write_filter *f, const char *key, + const char *value) +{ + (void)f; /* UNUSED */ + (void)key; /* UNUSED */ + (void)value; /* UNUSED */ + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static int +archive_write_grzip_open(struct archive_write_filter *f) +{ + struct write_grzip *data = (struct write_grzip *)f->data; + + return __archive_write_program_open(f, data->pdata, "grzip"); +} + +static int +archive_write_grzip_write(struct archive_write_filter *f, + const void *buff, size_t length) +{ + struct write_grzip *data = (struct write_grzip *)f->data; + + return __archive_write_program_write(f, data->pdata, buff, length); +} + +static int +archive_write_grzip_close(struct archive_write_filter *f) +{ + struct write_grzip *data = (struct write_grzip *)f->data; + + return __archive_write_program_close(f, data->pdata); +} + +static int +archive_write_grzip_free(struct archive_write_filter *f) +{ + struct write_grzip *data = (struct write_grzip *)f->data; + + __archive_write_program_free(data->pdata); + free(data); + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_gzip.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_gzip.c new file mode 100644 index 0000000000..8670d5ca74 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_gzip.c @@ -0,0 +1,442 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_compression_gzip.c 201081 2009-12-28 02:04:42Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#include <time.h> +#ifdef HAVE_ZLIB_H +#include <zlib.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_string.h" +#include "archive_write_private.h" + +#if ARCHIVE_VERSION_NUMBER < 4000000 +int +archive_write_set_compression_gzip(struct archive *a) +{ + __archive_write_filters_free(a); + return (archive_write_add_filter_gzip(a)); +} +#endif + +/* Don't compile this if we don't have zlib. */ + +struct private_data { + int compression_level; + int timestamp; +#ifdef HAVE_ZLIB_H + z_stream stream; + int64_t total_in; + unsigned char *compressed; + size_t compressed_buffer_size; + unsigned long crc; +#else + struct archive_write_program_data *pdata; +#endif +}; + +/* + * Yuck. zlib.h is not const-correct, so I need this one bit + * of ugly hackery to convert a const * pointer to a non-const pointer. + */ +#define SET_NEXT_IN(st,src) \ + (st)->stream.next_in = (Bytef *)(uintptr_t)(const void *)(src) + +static int archive_compressor_gzip_options(struct archive_write_filter *, + const char *, const char *); +static int archive_compressor_gzip_open(struct archive_write_filter *); +static int archive_compressor_gzip_write(struct archive_write_filter *, + const void *, size_t); +static int archive_compressor_gzip_close(struct archive_write_filter *); +static int archive_compressor_gzip_free(struct archive_write_filter *); +#ifdef HAVE_ZLIB_H +static int drive_compressor(struct archive_write_filter *, + struct private_data *, int finishing); +#endif + + +/* + * Add a gzip compression filter to this write handle. + */ +int +archive_write_add_filter_gzip(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct archive_write_filter *f = __archive_write_allocate_filter(_a); + struct private_data *data; + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_add_filter_gzip"); + + data = calloc(1, sizeof(*data)); + if (data == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + f->data = data; + f->open = &archive_compressor_gzip_open; + f->options = &archive_compressor_gzip_options; + f->close = &archive_compressor_gzip_close; + f->free = &archive_compressor_gzip_free; + f->code = ARCHIVE_FILTER_GZIP; + f->name = "gzip"; +#ifdef HAVE_ZLIB_H + data->compression_level = Z_DEFAULT_COMPRESSION; + return (ARCHIVE_OK); +#else + data->pdata = __archive_write_program_allocate("gzip"); + if (data->pdata == NULL) { + free(data); + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + data->compression_level = 0; + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Using external gzip program"); + return (ARCHIVE_WARN); +#endif +} + +static int +archive_compressor_gzip_free(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + +#ifdef HAVE_ZLIB_H + free(data->compressed); +#else + __archive_write_program_free(data->pdata); +#endif + free(data); + f->data = NULL; + return (ARCHIVE_OK); +} + +/* + * Set write options. + */ +static int +archive_compressor_gzip_options(struct archive_write_filter *f, const char *key, + const char *value) +{ + struct private_data *data = (struct private_data *)f->data; + + if (strcmp(key, "compression-level") == 0) { + if (value == NULL || !(value[0] >= '0' && value[0] <= '9') || + value[1] != '\0') + return (ARCHIVE_WARN); + data->compression_level = value[0] - '0'; + return (ARCHIVE_OK); + } + if (strcmp(key, "timestamp") == 0) { + data->timestamp = (value == NULL)?-1:1; + return (ARCHIVE_OK); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +#ifdef HAVE_ZLIB_H +/* + * Setup callback. + */ +static int +archive_compressor_gzip_open(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + int ret; + + if (data->compressed == NULL) { + size_t bs = 65536, bpb; + if (f->archive->magic == ARCHIVE_WRITE_MAGIC) { + /* Buffer size should be a multiple number of + * the of bytes per block for performance. */ + bpb = archive_write_get_bytes_per_block(f->archive); + if (bpb > bs) + bs = bpb; + else if (bpb != 0) + bs -= bs % bpb; + } + data->compressed_buffer_size = bs; + data->compressed + = (unsigned char *)malloc(data->compressed_buffer_size); + if (data->compressed == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for compression buffer"); + return (ARCHIVE_FATAL); + } + } + + data->crc = crc32(0L, NULL, 0); + data->stream.next_out = data->compressed; + data->stream.avail_out = (uInt)data->compressed_buffer_size; + + /* Prime output buffer with a gzip header. */ + data->compressed[0] = 0x1f; /* GZip signature bytes */ + data->compressed[1] = 0x8b; + data->compressed[2] = 0x08; /* "Deflate" compression */ + data->compressed[3] = 0; /* No options */ + if (data->timestamp >= 0) { + time_t t = time(NULL); + data->compressed[4] = (uint8_t)(t)&0xff; /* Timestamp */ + data->compressed[5] = (uint8_t)(t>>8)&0xff; + data->compressed[6] = (uint8_t)(t>>16)&0xff; + data->compressed[7] = (uint8_t)(t>>24)&0xff; + } else + memset(&data->compressed[4], 0, 4); + if (data->compression_level == 9) + data->compressed[8] = 2; + else if(data->compression_level == 1) + data->compressed[8] = 4; + else + data->compressed[8] = 0; + data->compressed[9] = 3; /* OS=Unix */ + data->stream.next_out += 10; + data->stream.avail_out -= 10; + + f->write = archive_compressor_gzip_write; + + /* Initialize compression library. */ + ret = deflateInit2(&(data->stream), + data->compression_level, + Z_DEFLATED, + -15 /* < 0 to suppress zlib header */, + 8, + Z_DEFAULT_STRATEGY); + + if (ret == Z_OK) { + f->data = data; + return (ARCHIVE_OK); + } + + /* Library setup failed: clean up. */ + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, "Internal error " + "initializing compression library"); + + /* Override the error message if we know what really went wrong. */ + switch (ret) { + case Z_STREAM_ERROR: + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "Internal error initializing " + "compression library: invalid setup parameter"); + break; + case Z_MEM_ERROR: + archive_set_error(f->archive, ENOMEM, + "Internal error initializing compression library"); + break; + case Z_VERSION_ERROR: + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "Internal error initializing " + "compression library: invalid library version"); + break; + } + + return (ARCHIVE_FATAL); +} + +/* + * Write data to the compressed stream. + */ +static int +archive_compressor_gzip_write(struct archive_write_filter *f, const void *buff, + size_t length) +{ + struct private_data *data = (struct private_data *)f->data; + int ret; + + /* Update statistics */ + data->crc = crc32(data->crc, (const Bytef *)buff, (uInt)length); + data->total_in += length; + + /* Compress input data to output buffer */ + SET_NEXT_IN(data, buff); + data->stream.avail_in = (uInt)length; + if ((ret = drive_compressor(f, data, 0)) != ARCHIVE_OK) + return (ret); + + return (ARCHIVE_OK); +} + +/* + * Finish the compression... + */ +static int +archive_compressor_gzip_close(struct archive_write_filter *f) +{ + unsigned char trailer[8]; + struct private_data *data = (struct private_data *)f->data; + int ret; + + /* Finish compression cycle */ + ret = drive_compressor(f, data, 1); + if (ret == ARCHIVE_OK) { + /* Write the last compressed data. */ + ret = __archive_write_filter(f->next_filter, + data->compressed, + data->compressed_buffer_size - data->stream.avail_out); + } + if (ret == ARCHIVE_OK) { + /* Build and write out 8-byte trailer. */ + trailer[0] = (uint8_t)(data->crc)&0xff; + trailer[1] = (uint8_t)(data->crc >> 8)&0xff; + trailer[2] = (uint8_t)(data->crc >> 16)&0xff; + trailer[3] = (uint8_t)(data->crc >> 24)&0xff; + trailer[4] = (uint8_t)(data->total_in)&0xff; + trailer[5] = (uint8_t)(data->total_in >> 8)&0xff; + trailer[6] = (uint8_t)(data->total_in >> 16)&0xff; + trailer[7] = (uint8_t)(data->total_in >> 24)&0xff; + ret = __archive_write_filter(f->next_filter, trailer, 8); + } + + switch (deflateEnd(&(data->stream))) { + case Z_OK: + break; + default: + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "Failed to clean up compressor"); + ret = ARCHIVE_FATAL; + } + return ret; +} + +/* + * Utility function to push input data through compressor, + * writing full output blocks as necessary. + * + * Note that this handles both the regular write case (finishing == + * false) and the end-of-archive case (finishing == true). + */ +static int +drive_compressor(struct archive_write_filter *f, + struct private_data *data, int finishing) +{ + int ret; + + for (;;) { + if (data->stream.avail_out == 0) { + ret = __archive_write_filter(f->next_filter, + data->compressed, + data->compressed_buffer_size); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + data->stream.next_out = data->compressed; + data->stream.avail_out = + (uInt)data->compressed_buffer_size; + } + + /* If there's nothing to do, we're done. */ + if (!finishing && data->stream.avail_in == 0) + return (ARCHIVE_OK); + + ret = deflate(&(data->stream), + finishing ? Z_FINISH : Z_NO_FLUSH ); + + switch (ret) { + case Z_OK: + /* In non-finishing case, check if compressor + * consumed everything */ + if (!finishing && data->stream.avail_in == 0) + return (ARCHIVE_OK); + /* In finishing case, this return always means + * there's more work */ + break; + case Z_STREAM_END: + /* This return can only occur in finishing case. */ + return (ARCHIVE_OK); + default: + /* Any other return value indicates an error. */ + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "GZip compression failed:" + " deflate() call returned status %d", + ret); + return (ARCHIVE_FATAL); + } + } +} + +#else /* HAVE_ZLIB_H */ + +static int +archive_compressor_gzip_open(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + struct archive_string as; + int r; + + archive_string_init(&as); + archive_strcpy(&as, "gzip"); + + /* Specify compression level. */ + if (data->compression_level > 0) { + archive_strcat(&as, " -"); + archive_strappend_char(&as, '0' + data->compression_level); + } + if (data->timestamp < 0) + /* Do not save timestamp. */ + archive_strcat(&as, " -n"); + else if (data->timestamp > 0) + /* Save timestamp. */ + archive_strcat(&as, " -N"); + + f->write = archive_compressor_gzip_write; + r = __archive_write_program_open(f, data->pdata, as.s); + archive_string_free(&as); + return (r); +} + +static int +archive_compressor_gzip_write(struct archive_write_filter *f, const void *buff, + size_t length) +{ + struct private_data *data = (struct private_data *)f->data; + + return __archive_write_program_write(f, data->pdata, buff, length); +} + +static int +archive_compressor_gzip_close(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + + return __archive_write_program_close(f, data->pdata); +} + +#endif /* HAVE_ZLIB_H */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_lrzip.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_lrzip.c new file mode 100644 index 0000000000..e215f89032 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_lrzip.c @@ -0,0 +1,197 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_string.h" +#include "archive_write_private.h" + +struct write_lrzip { + struct archive_write_program_data *pdata; + int compression_level; + enum { lzma = 0, bzip2, gzip, lzo, none, zpaq } compression; +}; + +static int archive_write_lrzip_open(struct archive_write_filter *); +static int archive_write_lrzip_options(struct archive_write_filter *, + const char *, const char *); +static int archive_write_lrzip_write(struct archive_write_filter *, + const void *, size_t); +static int archive_write_lrzip_close(struct archive_write_filter *); +static int archive_write_lrzip_free(struct archive_write_filter *); + +int +archive_write_add_filter_lrzip(struct archive *_a) +{ + struct archive_write_filter *f = __archive_write_allocate_filter(_a); + struct write_lrzip *data; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_add_filter_lrzip"); + + data = calloc(1, sizeof(*data)); + if (data == NULL) { + archive_set_error(_a, ENOMEM, "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + data->pdata = __archive_write_program_allocate("lrzip"); + if (data->pdata == NULL) { + free(data); + archive_set_error(_a, ENOMEM, "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + + f->name = "lrzip"; + f->code = ARCHIVE_FILTER_LRZIP; + f->data = data; + f->open = archive_write_lrzip_open; + f->options = archive_write_lrzip_options; + f->write = archive_write_lrzip_write; + f->close = archive_write_lrzip_close; + f->free = archive_write_lrzip_free; + + /* Note: This filter always uses an external program, so we + * return "warn" to inform of the fact. */ + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "Using external lrzip program for lrzip compression"); + return (ARCHIVE_WARN); +} + +static int +archive_write_lrzip_options(struct archive_write_filter *f, const char *key, + const char *value) +{ + struct write_lrzip *data = (struct write_lrzip *)f->data; + + if (strcmp(key, "compression") == 0) { + if (value == NULL) + return (ARCHIVE_WARN); + else if (strcmp(value, "bzip2") == 0) + data->compression = bzip2; + else if (strcmp(value, "gzip") == 0) + data->compression = gzip; + else if (strcmp(value, "lzo") == 0) + data->compression = lzo; + else if (strcmp(value, "none") == 0) + data->compression = none; + else if (strcmp(value, "zpaq") == 0) + data->compression = zpaq; + else + return (ARCHIVE_WARN); + return (ARCHIVE_OK); + } else if (strcmp(key, "compression-level") == 0) { + if (value == NULL || !(value[0] >= '1' && value[0] <= '9') || + value[1] != '\0') + return (ARCHIVE_WARN); + data->compression_level = value[0] - '0'; + return (ARCHIVE_OK); + } + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static int +archive_write_lrzip_open(struct archive_write_filter *f) +{ + struct write_lrzip *data = (struct write_lrzip *)f->data; + struct archive_string as; + int r; + + archive_string_init(&as); + archive_strcpy(&as, "lrzip -q"); + + /* Specify compression type. */ + switch (data->compression) { + case lzma:/* default compression */ + break; + case bzip2: + archive_strcat(&as, " -b"); + break; + case gzip: + archive_strcat(&as, " -g"); + break; + case lzo: + archive_strcat(&as, " -l"); + break; + case none: + archive_strcat(&as, " -n"); + break; + case zpaq: + archive_strcat(&as, " -z"); + break; + } + + /* Specify compression level. */ + if (data->compression_level > 0) { + archive_strcat(&as, " -L "); + archive_strappend_char(&as, '0' + data->compression_level); + } + + r = __archive_write_program_open(f, data->pdata, as.s); + archive_string_free(&as); + return (r); +} + +static int +archive_write_lrzip_write(struct archive_write_filter *f, + const void *buff, size_t length) +{ + struct write_lrzip *data = (struct write_lrzip *)f->data; + + return __archive_write_program_write(f, data->pdata, buff, length); +} + +static int +archive_write_lrzip_close(struct archive_write_filter *f) +{ + struct write_lrzip *data = (struct write_lrzip *)f->data; + + return __archive_write_program_close(f, data->pdata); +} + +static int +archive_write_lrzip_free(struct archive_write_filter *f) +{ + struct write_lrzip *data = (struct write_lrzip *)f->data; + + __archive_write_program_free(data->pdata); + free(data); + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_lz4.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_lz4.c new file mode 100644 index 0000000000..cf19fadd56 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_lz4.c @@ -0,0 +1,700 @@ +/*- + * Copyright (c) 2014 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_LZ4_H +#include <lz4.h> +#endif +#ifdef HAVE_LZ4HC_H +#include <lz4hc.h> +#endif + +#include "archive.h" +#include "archive_endian.h" +#include "archive_private.h" +#include "archive_write_private.h" +#include "archive_xxhash.h" + +#define LZ4_MAGICNUMBER 0x184d2204 + +struct private_data { + int compression_level; + unsigned header_written:1; + unsigned version_number:1; + unsigned block_independence:1; + unsigned block_checksum:1; + unsigned stream_size:1; + unsigned stream_checksum:1; + unsigned preset_dictionary:1; + unsigned block_maximum_size:3; +#if defined(HAVE_LIBLZ4) && LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 2 + int64_t total_in; + char *out; + char *out_buffer; + size_t out_buffer_size; + size_t out_block_size; + char *in; + char *in_buffer_allocated; + char *in_buffer; + size_t in_buffer_size; + size_t block_size; + + void *xxh32_state; + void *lz4_stream; +#else + struct archive_write_program_data *pdata; +#endif +}; + +static int archive_filter_lz4_close(struct archive_write_filter *); +static int archive_filter_lz4_free(struct archive_write_filter *); +static int archive_filter_lz4_open(struct archive_write_filter *); +static int archive_filter_lz4_options(struct archive_write_filter *, + const char *, const char *); +static int archive_filter_lz4_write(struct archive_write_filter *, + const void *, size_t); + +/* + * Add a lz4 compression filter to this write handle. + */ +int +archive_write_add_filter_lz4(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct archive_write_filter *f = __archive_write_allocate_filter(_a); + struct private_data *data; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_add_filter_lz4"); + + data = calloc(1, sizeof(*data)); + if (data == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + + /* + * Setup default settings. + */ + data->compression_level = 1; + data->version_number = 0x01; + data->block_independence = 1; + data->block_checksum = 0; + data->stream_size = 0; + data->stream_checksum = 1; + data->preset_dictionary = 0; + data->block_maximum_size = 7; + + /* + * Setup a filter setting. + */ + f->data = data; + f->options = &archive_filter_lz4_options; + f->close = &archive_filter_lz4_close; + f->free = &archive_filter_lz4_free; + f->open = &archive_filter_lz4_open; + f->code = ARCHIVE_FILTER_LZ4; + f->name = "lz4"; +#if defined(HAVE_LIBLZ4) && LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 2 + return (ARCHIVE_OK); +#else + /* + * We don't have lz4 library, and execute external lz4 program + * instead. + */ + data->pdata = __archive_write_program_allocate("lz4"); + if (data->pdata == NULL) { + free(data); + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + data->compression_level = 0; + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Using external lz4 program"); + return (ARCHIVE_WARN); +#endif +} + +/* + * Set write options. + */ +static int +archive_filter_lz4_options(struct archive_write_filter *f, + const char *key, const char *value) +{ + struct private_data *data = (struct private_data *)f->data; + + if (strcmp(key, "compression-level") == 0) { + int val; + if (value == NULL || !((val = value[0] - '0') >= 1 && val <= 9) || + value[1] != '\0') + return (ARCHIVE_WARN); + +#ifndef HAVE_LZ4HC_H + if(val >= 3) + { + archive_set_error(f->archive, ARCHIVE_ERRNO_PROGRAMMER, + "High compression not included in this build"); + return (ARCHIVE_FATAL); + } +#endif + data->compression_level = val; + return (ARCHIVE_OK); + } + if (strcmp(key, "stream-checksum") == 0) { + data->stream_checksum = value != NULL; + return (ARCHIVE_OK); + } + if (strcmp(key, "block-checksum") == 0) { + data->block_checksum = value != NULL; + return (ARCHIVE_OK); + } + if (strcmp(key, "block-size") == 0) { + if (value == NULL || !(value[0] >= '4' && value[0] <= '7') || + value[1] != '\0') + return (ARCHIVE_WARN); + data->block_maximum_size = value[0] - '0'; + return (ARCHIVE_OK); + } + if (strcmp(key, "block-dependence") == 0) { + data->block_independence = value == NULL; + return (ARCHIVE_OK); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +#if defined(HAVE_LIBLZ4) && LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 2 +/* Don't compile this if we don't have liblz4. */ + +static int drive_compressor(struct archive_write_filter *, const char *, + size_t); +static int drive_compressor_independence(struct archive_write_filter *, + const char *, size_t); +static int drive_compressor_dependence(struct archive_write_filter *, + const char *, size_t); +static int lz4_write_stream_descriptor(struct archive_write_filter *); +static ssize_t lz4_write_one_block(struct archive_write_filter *, const char *, + size_t); + + +/* + * Setup callback. + */ +static int +archive_filter_lz4_open(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + size_t required_size; + static size_t const bkmap[] = { 64 * 1024, 256 * 1024, 1 * 1024 * 1024, + 4 * 1024 * 1024 }; + size_t pre_block_size; + + if (data->block_maximum_size < 4) + data->block_size = bkmap[0]; + else + data->block_size = bkmap[data->block_maximum_size - 4]; + + required_size = 4 + 15 + 4 + data->block_size + 4 + 4; + if (data->out_buffer_size < required_size) { + size_t bs = required_size, bpb; + free(data->out_buffer); + if (f->archive->magic == ARCHIVE_WRITE_MAGIC) { + /* Buffer size should be a multiple number of + * the of bytes per block for performance. */ + bpb = archive_write_get_bytes_per_block(f->archive); + if (bpb > bs) + bs = bpb; + else if (bpb != 0) { + bs += bpb; + bs -= bs % bpb; + } + } + data->out_block_size = bs; + bs += required_size; + data->out_buffer = malloc(bs); + data->out = data->out_buffer; + data->out_buffer_size = bs; + } + + pre_block_size = (data->block_independence)? 0: 64 * 1024; + if (data->in_buffer_size < data->block_size + pre_block_size) { + free(data->in_buffer_allocated); + data->in_buffer_size = data->block_size; + data->in_buffer_allocated = + malloc(data->in_buffer_size + pre_block_size); + data->in_buffer = data->in_buffer_allocated + pre_block_size; + if (!data->block_independence && data->compression_level >= 3) + data->in_buffer = data->in_buffer_allocated; + data->in = data->in_buffer; + data->in_buffer_size = data->block_size; + } + + if (data->out_buffer == NULL || data->in_buffer_allocated == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for compression buffer"); + return (ARCHIVE_FATAL); + } + + f->write = archive_filter_lz4_write; + + return (ARCHIVE_OK); +} + +/* + * Write data to the out stream. + * + * Returns ARCHIVE_OK if all data written, error otherwise. + */ +static int +archive_filter_lz4_write(struct archive_write_filter *f, + const void *buff, size_t length) +{ + struct private_data *data = (struct private_data *)f->data; + int ret = ARCHIVE_OK; + const char *p; + size_t remaining; + ssize_t size; + + /* If we haven't written a stream descriptor, we have to do it first. */ + if (!data->header_written) { + ret = lz4_write_stream_descriptor(f); + if (ret != ARCHIVE_OK) + return (ret); + data->header_written = 1; + } + + /* Update statistics */ + data->total_in += length; + + p = (const char *)buff; + remaining = length; + while (remaining) { + size_t l; + /* Compress input data to output buffer */ + size = lz4_write_one_block(f, p, remaining); + if (size < ARCHIVE_OK) + return (ARCHIVE_FATAL); + l = data->out - data->out_buffer; + if (l >= data->out_block_size) { + ret = __archive_write_filter(f->next_filter, + data->out_buffer, data->out_block_size); + l -= data->out_block_size; + memcpy(data->out_buffer, + data->out_buffer + data->out_block_size, l); + data->out = data->out_buffer + l; + if (ret < ARCHIVE_WARN) + break; + } + p += size; + remaining -= size; + } + + return (ret); +} + +/* + * Finish the compression. + */ +static int +archive_filter_lz4_close(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + int ret; + + /* Finish compression cycle. */ + ret = (int)lz4_write_one_block(f, NULL, 0); + if (ret >= 0) { + /* + * Write the last block and the end of the stream data. + */ + + /* Write End Of Stream. */ + memset(data->out, 0, 4); data->out += 4; + /* Write Stream checksum if needed. */ + if (data->stream_checksum) { + unsigned int checksum; + checksum = __archive_xxhash.XXH32_digest( + data->xxh32_state); + data->xxh32_state = NULL; + archive_le32enc(data->out, checksum); + data->out += 4; + } + ret = __archive_write_filter(f->next_filter, + data->out_buffer, data->out - data->out_buffer); + } + return ret; +} + +static int +archive_filter_lz4_free(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + + if (data->lz4_stream != NULL) { +#ifdef HAVE_LZ4HC_H + if (data->compression_level >= 3) +#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7 + LZ4_freeStreamHC(data->lz4_stream); +#else + LZ4_freeHC(data->lz4_stream); +#endif + else +#endif +#if LZ4_VERSION_MINOR >= 3 + LZ4_freeStream(data->lz4_stream); +#else + LZ4_free(data->lz4_stream); +#endif + } + free(data->out_buffer); + free(data->in_buffer_allocated); + free(data->xxh32_state); + free(data); + f->data = NULL; + return (ARCHIVE_OK); +} + +static int +lz4_write_stream_descriptor(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + uint8_t *sd; + + sd = (uint8_t *)data->out; + /* Write Magic Number. */ + archive_le32enc(&sd[0], LZ4_MAGICNUMBER); + /* FLG */ + sd[4] = (data->version_number << 6) + | (data->block_independence << 5) + | (data->block_checksum << 4) + | (data->stream_size << 3) + | (data->stream_checksum << 2) + | (data->preset_dictionary << 0); + /* BD */ + sd[5] = (data->block_maximum_size << 4); + sd[6] = (__archive_xxhash.XXH32(&sd[4], 2, 0) >> 8) & 0xff; + data->out += 7; + if (data->stream_checksum) + data->xxh32_state = __archive_xxhash.XXH32_init(0); + else + data->xxh32_state = NULL; + return (ARCHIVE_OK); +} + +static ssize_t +lz4_write_one_block(struct archive_write_filter *f, const char *p, + size_t length) +{ + struct private_data *data = (struct private_data *)f->data; + ssize_t r; + + if (p == NULL) { + /* Compress remaining uncompressed data. */ + if (data->in_buffer == data->in) + return 0; + else { + size_t l = data->in - data->in_buffer; + r = drive_compressor(f, data->in_buffer, l); + if (r == ARCHIVE_OK) + r = (ssize_t)l; + } + } else if ((data->block_independence || data->compression_level < 3) && + data->in_buffer == data->in && length >= data->block_size) { + r = drive_compressor(f, p, data->block_size); + if (r == ARCHIVE_OK) + r = (ssize_t)data->block_size; + } else { + size_t remaining_size = data->in_buffer_size - + (data->in - data->in_buffer); + size_t l = (remaining_size > length)? length: remaining_size; + memcpy(data->in, p, l); + data->in += l; + if (l == remaining_size) { + r = drive_compressor(f, data->in_buffer, + data->block_size); + if (r == ARCHIVE_OK) + r = (ssize_t)l; + data->in = data->in_buffer; + } else + r = (ssize_t)l; + } + + return (r); +} + + +/* + * Utility function to push input data through compressor, writing + * full output blocks as necessary. + * + * Note that this handles both the regular write case (finishing == + * false) and the end-of-archive case (finishing == true). + */ +static int +drive_compressor(struct archive_write_filter *f, const char *p, size_t length) +{ + struct private_data *data = (struct private_data *)f->data; + + if (data->stream_checksum) + __archive_xxhash.XXH32_update(data->xxh32_state, + p, (int)length); + if (data->block_independence) + return drive_compressor_independence(f, p, length); + else + return drive_compressor_dependence(f, p, length); +} + +static int +drive_compressor_independence(struct archive_write_filter *f, const char *p, + size_t length) +{ + struct private_data *data = (struct private_data *)f->data; + unsigned int outsize; + +#ifdef HAVE_LZ4HC_H + if (data->compression_level >= 3) +#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7 + outsize = LZ4_compress_HC(p, data->out + 4, + (int)length, (int)data->block_size, + data->compression_level); +#else + outsize = LZ4_compressHC2_limitedOutput(p, data->out + 4, + (int)length, (int)data->block_size, + data->compression_level); +#endif + else +#endif +#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7 + outsize = LZ4_compress_default(p, data->out + 4, + (int)length, (int)data->block_size); +#else + outsize = LZ4_compress_limitedOutput(p, data->out + 4, + (int)length, (int)data->block_size); +#endif + + if (outsize) { + /* The buffer is compressed. */ + archive_le32enc(data->out, outsize); + data->out += 4; + } else { + /* The buffer is not compressed. The compressed size was + * bigger than its uncompressed size. */ + archive_le32enc(data->out, length | 0x80000000); + data->out += 4; + memcpy(data->out, p, length); + outsize = length; + } + data->out += outsize; + if (data->block_checksum) { + unsigned int checksum = + __archive_xxhash.XXH32(data->out - outsize, outsize, 0); + archive_le32enc(data->out, checksum); + data->out += 4; + } + return (ARCHIVE_OK); +} + +static int +drive_compressor_dependence(struct archive_write_filter *f, const char *p, + size_t length) +{ + struct private_data *data = (struct private_data *)f->data; + int outsize; + +#define DICT_SIZE (64 * 1024) +#ifdef HAVE_LZ4HC_H + if (data->compression_level >= 3) { + if (data->lz4_stream == NULL) { +#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7 + data->lz4_stream = LZ4_createStreamHC(); + LZ4_resetStreamHC(data->lz4_stream, data->compression_level); +#else + data->lz4_stream = + LZ4_createHC(data->in_buffer_allocated); +#endif + if (data->lz4_stream == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for compression" + " buffer"); + return (ARCHIVE_FATAL); + } + } + else + LZ4_loadDictHC(data->lz4_stream, data->in_buffer_allocated, DICT_SIZE); + +#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7 + outsize = LZ4_compress_HC_continue( + data->lz4_stream, p, data->out + 4, (int)length, + (int)data->block_size); +#else + outsize = LZ4_compressHC2_limitedOutput_continue( + data->lz4_stream, p, data->out + 4, (int)length, + (int)data->block_size, data->compression_level); +#endif + } else +#endif + { + if (data->lz4_stream == NULL) { + data->lz4_stream = LZ4_createStream(); + if (data->lz4_stream == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for compression" + " buffer"); + return (ARCHIVE_FATAL); + } + } + else + LZ4_loadDict(data->lz4_stream, data->in_buffer_allocated, DICT_SIZE); + +#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7 + outsize = LZ4_compress_fast_continue( + data->lz4_stream, p, data->out + 4, (int)length, + (int)data->block_size, 1); +#else + outsize = LZ4_compress_limitedOutput_continue( + data->lz4_stream, p, data->out + 4, (int)length, + (int)data->block_size); +#endif + } + + if (outsize) { + /* The buffer is compressed. */ + archive_le32enc(data->out, outsize); + data->out += 4; + } else { + /* The buffer is not compressed. The compressed size was + * bigger than its uncompressed size. */ + archive_le32enc(data->out, length | 0x80000000); + data->out += 4; + memcpy(data->out, p, length); + outsize = length; + } + data->out += outsize; + if (data->block_checksum) { + unsigned int checksum = + __archive_xxhash.XXH32(data->out - outsize, outsize, 0); + archive_le32enc(data->out, checksum); + data->out += 4; + } + + if (length == data->block_size) { +#ifdef HAVE_LZ4HC_H + if (data->compression_level >= 3) { +#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7 + LZ4_saveDictHC(data->lz4_stream, data->in_buffer_allocated, DICT_SIZE); +#else + LZ4_slideInputBufferHC(data->lz4_stream); +#endif + data->in_buffer = data->in_buffer_allocated + DICT_SIZE; + } + else +#endif + LZ4_saveDict(data->lz4_stream, + data->in_buffer_allocated, DICT_SIZE); +#undef DICT_SIZE + } + return (ARCHIVE_OK); +} + +#else /* HAVE_LIBLZ4 */ + +static int +archive_filter_lz4_open(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + struct archive_string as; + int r; + + archive_string_init(&as); + archive_strcpy(&as, "lz4 -z -q -q"); + + /* Specify a compression level. */ + if (data->compression_level > 0) { + archive_strcat(&as, " -"); + archive_strappend_char(&as, '0' + data->compression_level); + } + /* Specify a block size. */ + archive_strcat(&as, " -B"); + archive_strappend_char(&as, '0' + data->block_maximum_size); + + if (data->block_checksum) + archive_strcat(&as, " -BX"); + if (data->stream_checksum == 0) + archive_strcat(&as, " --no-frame-crc"); + if (data->block_independence == 0) + archive_strcat(&as, " -BD"); + + f->write = archive_filter_lz4_write; + + r = __archive_write_program_open(f, data->pdata, as.s); + archive_string_free(&as); + return (r); +} + +static int +archive_filter_lz4_write(struct archive_write_filter *f, const void *buff, + size_t length) +{ + struct private_data *data = (struct private_data *)f->data; + + return __archive_write_program_write(f, data->pdata, buff, length); +} + +static int +archive_filter_lz4_close(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + + return __archive_write_program_close(f, data->pdata); +} + +static int +archive_filter_lz4_free(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + + __archive_write_program_free(data->pdata); + free(data); + return (ARCHIVE_OK); +} + +#endif /* HAVE_LIBLZ4 */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_lzop.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_lzop.c new file mode 100644 index 0000000000..3bd9062e4d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_lzop.c @@ -0,0 +1,478 @@ +/*- + * Copyright (c) 2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); +//#undef HAVE_LZO_LZOCONF_H +//#undef HAVE_LZO_LZO1X_H + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#include <time.h> +#ifdef HAVE_LZO_LZOCONF_H +#include <lzo/lzoconf.h> +#endif +#ifdef HAVE_LZO_LZO1X_H +#include <lzo/lzo1x.h> +#endif + +#include "archive.h" +#include "archive_string.h" +#include "archive_endian.h" +#include "archive_write_private.h" + +enum lzo_method { + METHOD_LZO1X_1 = 1, + METHOD_LZO1X_1_15 = 2, + METHOD_LZO1X_999 = 3 +}; +struct write_lzop { + int compression_level; +#if defined(HAVE_LZO_LZOCONF_H) && defined(HAVE_LZO_LZO1X_H) + unsigned char *uncompressed; + size_t uncompressed_buffer_size; + size_t uncompressed_avail_bytes; + unsigned char *compressed; + size_t compressed_buffer_size; + enum lzo_method method; + unsigned char level; + lzo_voidp work_buffer; + lzo_uint32 work_buffer_size; + char header_written; +#else + struct archive_write_program_data *pdata; +#endif +}; + +static int archive_write_lzop_open(struct archive_write_filter *); +static int archive_write_lzop_options(struct archive_write_filter *, + const char *, const char *); +static int archive_write_lzop_write(struct archive_write_filter *, + const void *, size_t); +static int archive_write_lzop_close(struct archive_write_filter *); +static int archive_write_lzop_free(struct archive_write_filter *); + +#if defined(HAVE_LZO_LZOCONF_H) && defined(HAVE_LZO_LZO1X_H) +/* Maximum block size. */ +#define BLOCK_SIZE (256 * 1024) +/* Block information is composed of uncompressed size(4 bytes), + * compressed size(4 bytes) and the checksum of uncompressed data(4 bytes) + * in this lzop writer. */ +#define BLOCK_INfO_SIZE 12 + +#define HEADER_VERSION 9 +#define HEADER_LIBVERSION 11 +#define HEADER_METHOD 15 +#define HEADER_LEVEL 16 +#define HEADER_MTIME_LOW 25 +#define HEADER_MTIME_HIGH 29 +#define HEADER_H_CHECKSUM 34 + +/* + * Header template. + */ +static const unsigned char header[] = { + /* LZOP Magic code 9 bytes */ + 0x89, 0x4c, 0x5a, 0x4f, 0x00, 0x0d, 0x0a, 0x1a, 0x0a, + /* LZOP utility version(fake data) 2 bytes */ + 0x10, 0x30, + /* LZO library version 2 bytes */ + 0x09, 0x40, + /* Minimum required LZO library version 2 bytes */ + 0x09, 0x40, + /* Method */ + 1, + /* Level */ + 5, + /* Flags 4 bytes + * -OS Unix + * -Stdout + * -Stdin + * -Adler32 used for uncompressed data 4 bytes */ + 0x03, 0x00, 0x00, 0x0d, + /* Mode (AE_IFREG | 0644) 4 bytes */ + 0x00, 0x00, 0x81, 0xa4, + /* Mtime low 4 bytes */ + 0x00, 0x00, 0x00, 0x00, + /* Mtime high 4 bytes */ + 0x00, 0x00, 0x00, 0x00, + /* Filename length */ + 0x00, + /* Header checksum 4 bytes */ + 0x00, 0x00, 0x00, 0x00, +}; +#endif + +int +archive_write_add_filter_lzop(struct archive *_a) +{ + struct archive_write_filter *f = __archive_write_allocate_filter(_a); + struct write_lzop *data; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_add_filter_lzop"); + + data = calloc(1, sizeof(*data)); + if (data == NULL) { + archive_set_error(_a, ENOMEM, "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + + f->name = "lzop"; + f->code = ARCHIVE_FILTER_LZOP; + f->data = data; + f->open = archive_write_lzop_open; + f->options = archive_write_lzop_options; + f->write = archive_write_lzop_write; + f->close = archive_write_lzop_close; + f->free = archive_write_lzop_free; +#if defined(HAVE_LZO_LZOCONF_H) && defined(HAVE_LZO_LZO1X_H) + if (lzo_init() != LZO_E_OK) { + free(data); + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "lzo_init(type check) failed"); + return (ARCHIVE_FATAL); + } + if (lzo_version() < 0x940) { + free(data); + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "liblzo library is too old(%s < 0.940)", + lzo_version_string()); + return (ARCHIVE_FATAL); + } + data->compression_level = 5; + return (ARCHIVE_OK); +#else + data->pdata = __archive_write_program_allocate("lzop"); + if (data->pdata == NULL) { + free(data); + archive_set_error(_a, ENOMEM, "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + data->compression_level = 0; + /* Note: We return "warn" to inform of using an external lzop + * program. */ + archive_set_error(_a, ARCHIVE_ERRNO_MISC, + "Using external lzop program for lzop compression"); + return (ARCHIVE_WARN); +#endif +} + +static int +archive_write_lzop_free(struct archive_write_filter *f) +{ + struct write_lzop *data = (struct write_lzop *)f->data; + +#if defined(HAVE_LZO_LZOCONF_H) && defined(HAVE_LZO_LZO1X_H) + free(data->uncompressed); + free(data->compressed); + free(data->work_buffer); +#else + __archive_write_program_free(data->pdata); +#endif + free(data); + return (ARCHIVE_OK); +} + +static int +archive_write_lzop_options(struct archive_write_filter *f, const char *key, + const char *value) +{ + struct write_lzop *data = (struct write_lzop *)f->data; + + if (strcmp(key, "compression-level") == 0) { + if (value == NULL || !(value[0] >= '1' && value[0] <= '9') || + value[1] != '\0') + return (ARCHIVE_WARN); + data->compression_level = value[0] - '0'; + return (ARCHIVE_OK); + } + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +#if defined(HAVE_LZO_LZOCONF_H) && defined(HAVE_LZO_LZO1X_H) +static int +archive_write_lzop_open(struct archive_write_filter *f) +{ + struct write_lzop *data = (struct write_lzop *)f->data; + + switch (data->compression_level) { + case 1: + data->method = METHOD_LZO1X_1_15; data->level = 1; break; + default: + case 2: case 3: case 4: case 5: case 6: + data->method = METHOD_LZO1X_1; data->level = 5; break; + case 7: + data->method = METHOD_LZO1X_999; data->level = 7; break; + case 8: + data->method = METHOD_LZO1X_999; data->level = 8; break; + case 9: + data->method = METHOD_LZO1X_999; data->level = 9; break; + } + switch (data->method) { + case METHOD_LZO1X_1: + data->work_buffer_size = LZO1X_1_MEM_COMPRESS; break; + case METHOD_LZO1X_1_15: + data->work_buffer_size = LZO1X_1_15_MEM_COMPRESS; break; + case METHOD_LZO1X_999: + data->work_buffer_size = LZO1X_999_MEM_COMPRESS; break; + } + if (data->work_buffer == NULL) { + data->work_buffer = (lzo_voidp)malloc(data->work_buffer_size); + if (data->work_buffer == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for compression buffer"); + return (ARCHIVE_FATAL); + } + } + if (data->compressed == NULL) { + data->compressed_buffer_size = sizeof(header) + + BLOCK_SIZE + (BLOCK_SIZE >> 4) + 64 + 3; + data->compressed = (unsigned char *) + malloc(data->compressed_buffer_size); + if (data->compressed == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for compression buffer"); + return (ARCHIVE_FATAL); + } + } + if (data->uncompressed == NULL) { + data->uncompressed_buffer_size = BLOCK_SIZE; + data->uncompressed = (unsigned char *) + malloc(data->uncompressed_buffer_size); + if (data->uncompressed == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for compression buffer"); + return (ARCHIVE_FATAL); + } + data->uncompressed_avail_bytes = BLOCK_SIZE; + } + return (ARCHIVE_OK); +} + +static int +make_header(struct archive_write_filter *f) +{ + struct write_lzop *data = (struct write_lzop *)f->data; + int64_t t; + uint32_t checksum; + + memcpy(data->compressed, header, sizeof(header)); + /* Overwrite library version. */ + data->compressed[HEADER_LIBVERSION] = (unsigned char ) + (lzo_version() >> 8) & 0xff; + data->compressed[HEADER_LIBVERSION + 1] = (unsigned char ) + lzo_version() & 0xff; + /* Overwrite method and level. */ + data->compressed[HEADER_METHOD] = (unsigned char)data->method; + data->compressed[HEADER_LEVEL] = data->level; + /* Overwrite mtime with current time. */ + t = (int64_t)time(NULL); + archive_be32enc(&data->compressed[HEADER_MTIME_LOW], + (uint32_t)(t & 0xffffffff)); + archive_be32enc(&data->compressed[HEADER_MTIME_HIGH], + (uint32_t)((t >> 32) & 0xffffffff)); + /* Overwrite header checksum with calculated value. */ + checksum = lzo_adler32(1, data->compressed + HEADER_VERSION, + (lzo_uint)(HEADER_H_CHECKSUM - HEADER_VERSION)); + archive_be32enc(&data->compressed[HEADER_H_CHECKSUM], checksum); + return (sizeof(header)); +} + +static int +drive_compressor(struct archive_write_filter *f) +{ + struct write_lzop *data = (struct write_lzop *)f->data; + unsigned char *p; + const int block_info_bytes = 12; + int header_bytes, r; + lzo_uint usize, csize; + uint32_t checksum; + + if (!data->header_written) { + header_bytes = make_header(f); + data->header_written = 1; + } else + header_bytes = 0; + p = data->compressed; + + usize = (lzo_uint) + (data->uncompressed_buffer_size - data->uncompressed_avail_bytes); + csize = 0; + switch (data->method) { + default: + case METHOD_LZO1X_1: + r = lzo1x_1_compress(data->uncompressed, usize, + p + header_bytes + block_info_bytes, &csize, + data->work_buffer); + break; + case METHOD_LZO1X_1_15: + r = lzo1x_1_15_compress(data->uncompressed, usize, + p + header_bytes + block_info_bytes, &csize, + data->work_buffer); + break; + case METHOD_LZO1X_999: + r = lzo1x_999_compress_level(data->uncompressed, usize, + p + header_bytes + block_info_bytes, &csize, + data->work_buffer, NULL, 0, 0, data->level); + break; + } + if (r != LZO_E_OK) { + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "Lzop compression failed: returned status %d", r); + return (ARCHIVE_FATAL); + } + + /* Store uncompressed size. */ + archive_be32enc(p + header_bytes, (uint32_t)usize); + /* Store the checksum of the uncompressed data. */ + checksum = lzo_adler32(1, data->uncompressed, usize); + archive_be32enc(p + header_bytes + 8, checksum); + + if (csize < usize) { + /* Store compressed size. */ + archive_be32enc(p + header_bytes + 4, (uint32_t)csize); + r = __archive_write_filter(f->next_filter, data->compressed, + header_bytes + block_info_bytes + csize); + } else { + /* + * This case, we output uncompressed data instead. + */ + /* Store uncompressed size as compressed size. */ + archive_be32enc(p + header_bytes + 4, (uint32_t)usize); + r = __archive_write_filter(f->next_filter, data->compressed, + header_bytes + block_info_bytes); + if (r != ARCHIVE_OK) + return (ARCHIVE_FATAL); + r = __archive_write_filter(f->next_filter, data->uncompressed, + usize); + } + + if (r != ARCHIVE_OK) + return (ARCHIVE_FATAL); + return (ARCHIVE_OK); +} + +static int +archive_write_lzop_write(struct archive_write_filter *f, + const void *buff, size_t length) +{ + struct write_lzop *data = (struct write_lzop *)f->data; + const char *p = buff; + int r; + + do { + if (data->uncompressed_avail_bytes > length) { + memcpy(data->uncompressed + + data->uncompressed_buffer_size + - data->uncompressed_avail_bytes, + p, length); + data->uncompressed_avail_bytes -= length; + return (ARCHIVE_OK); + } + + memcpy(data->uncompressed + data->uncompressed_buffer_size + - data->uncompressed_avail_bytes, + p, data->uncompressed_avail_bytes); + length -= data->uncompressed_avail_bytes; + p += data->uncompressed_avail_bytes; + data->uncompressed_avail_bytes = 0; + + r = drive_compressor(f); + if (r != ARCHIVE_OK) return (r); + data->uncompressed_avail_bytes = BLOCK_SIZE; + } while (length); + + return (ARCHIVE_OK); +} + +static int +archive_write_lzop_close(struct archive_write_filter *f) +{ + struct write_lzop *data = (struct write_lzop *)f->data; + const uint32_t endmark = 0; + int r; + + if (data->uncompressed_avail_bytes < BLOCK_SIZE) { + /* Compress and output remaining data. */ + r = drive_compressor(f); + if (r != ARCHIVE_OK) + return (r); + } + /* Write a zero uncompressed size as the end mark of the series of + * compressed block. */ + return __archive_write_filter(f->next_filter, &endmark, sizeof(endmark)); +} + +#else +static int +archive_write_lzop_open(struct archive_write_filter *f) +{ + struct write_lzop *data = (struct write_lzop *)f->data; + struct archive_string as; + int r; + + archive_string_init(&as); + archive_strcpy(&as, "lzop"); + /* Specify compression level. */ + if (data->compression_level > 0) { + archive_strappend_char(&as, ' '); + archive_strappend_char(&as, '-'); + archive_strappend_char(&as, '0' + data->compression_level); + } + + r = __archive_write_program_open(f, data->pdata, as.s); + archive_string_free(&as); + return (r); +} + +static int +archive_write_lzop_write(struct archive_write_filter *f, + const void *buff, size_t length) +{ + struct write_lzop *data = (struct write_lzop *)f->data; + + return __archive_write_program_write(f, data->pdata, buff, length); +} + +static int +archive_write_lzop_close(struct archive_write_filter *f) +{ + struct write_lzop *data = (struct write_lzop *)f->data; + + return __archive_write_program_close(f, data->pdata); +} +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_none.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_none.c new file mode 100644 index 0000000000..3c06c642e7 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_none.c @@ -0,0 +1,43 @@ +/*- + * Copyright (c) 2003-2010 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_compression_none.c 201080 2009-12-28 02:03:54Z kientzle $"); + +#include "archive.h" + +int +archive_write_set_compression_none(struct archive *a) +{ + (void)a; /* UNUSED */ + return (ARCHIVE_OK); +} + +int +archive_write_add_filter_none(struct archive *a) +{ + (void)a; /* UNUSED */ + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_program.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_program.c new file mode 100644 index 0000000000..c096e7227b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_program.c @@ -0,0 +1,391 @@ +/*- + * Copyright (c) 2007 Joerg Sonnenberger + * Copyright (c) 2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_compression_program.c 201104 2009-12-28 03:14:30Z kientzle $"); + +#ifdef HAVE_SYS_WAIT_H +# include <sys/wait.h> +#endif +#ifdef HAVE_ERRNO_H +# include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +# include <fcntl.h> +#endif +#ifdef HAVE_STDLIB_H +# include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +# include <string.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_string.h" +#include "archive_write_private.h" +#include "filter_fork.h" + +#if ARCHIVE_VERSION_NUMBER < 4000000 +int +archive_write_set_compression_program(struct archive *a, const char *cmd) +{ + __archive_write_filters_free(a); + return (archive_write_add_filter_program(a, cmd)); +} +#endif + +struct archive_write_program_data { +#if defined(_WIN32) && !defined(__CYGWIN__) + HANDLE child; +#else + pid_t child; +#endif + int child_stdin, child_stdout; + + char *child_buf; + size_t child_buf_len, child_buf_avail; + char *program_name; +}; + +struct private_data { + struct archive_write_program_data *pdata; + struct archive_string description; + char *cmd; +}; + +static int archive_compressor_program_open(struct archive_write_filter *); +static int archive_compressor_program_write(struct archive_write_filter *, + const void *, size_t); +static int archive_compressor_program_close(struct archive_write_filter *); +static int archive_compressor_program_free(struct archive_write_filter *); + +/* + * Add a filter to this write handle that passes all data through an + * external program. + */ +int +archive_write_add_filter_program(struct archive *_a, const char *cmd) +{ + struct archive_write_filter *f = __archive_write_allocate_filter(_a); + struct private_data *data; + static const char prefix[] = "Program: "; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_add_filter_program"); + + f->data = calloc(1, sizeof(*data)); + if (f->data == NULL) + goto memerr; + data = (struct private_data *)f->data; + + data->cmd = strdup(cmd); + if (data->cmd == NULL) + goto memerr; + + data->pdata = __archive_write_program_allocate(cmd); + if (data->pdata == NULL) + goto memerr; + + /* Make up a description string. */ + if (archive_string_ensure(&data->description, + strlen(prefix) + strlen(cmd) + 1) == NULL) + goto memerr; + archive_strcpy(&data->description, prefix); + archive_strcat(&data->description, cmd); + + f->name = data->description.s; + f->code = ARCHIVE_FILTER_PROGRAM; + f->open = archive_compressor_program_open; + f->write = archive_compressor_program_write; + f->close = archive_compressor_program_close; + f->free = archive_compressor_program_free; + return (ARCHIVE_OK); +memerr: + archive_compressor_program_free(f); + archive_set_error(_a, ENOMEM, + "Can't allocate memory for filter program"); + return (ARCHIVE_FATAL); +} + +static int +archive_compressor_program_open(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + + return __archive_write_program_open(f, data->pdata, data->cmd); +} + +static int +archive_compressor_program_write(struct archive_write_filter *f, + const void *buff, size_t length) +{ + struct private_data *data = (struct private_data *)f->data; + + return __archive_write_program_write(f, data->pdata, buff, length); +} + +static int +archive_compressor_program_close(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + + return __archive_write_program_close(f, data->pdata); +} + +static int +archive_compressor_program_free(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + + if (data) { + free(data->cmd); + archive_string_free(&data->description); + __archive_write_program_free(data->pdata); + free(data); + f->data = NULL; + } + return (ARCHIVE_OK); +} + +/* + * Allocate resources for executing an external program. + */ +struct archive_write_program_data * +__archive_write_program_allocate(const char *program) +{ + struct archive_write_program_data *data; + + data = calloc(1, sizeof(struct archive_write_program_data)); + if (data == NULL) + return (data); + data->child_stdin = -1; + data->child_stdout = -1; + data->program_name = strdup(program); + return (data); +} + +/* + * Release the resources. + */ +int +__archive_write_program_free(struct archive_write_program_data *data) +{ + + if (data) { + free(data->program_name); + free(data->child_buf); + free(data); + } + return (ARCHIVE_OK); +} + +int +__archive_write_program_open(struct archive_write_filter *f, + struct archive_write_program_data *data, const char *cmd) +{ + int ret; + + if (data->child_buf == NULL) { + data->child_buf_len = 65536; + data->child_buf_avail = 0; + data->child_buf = malloc(data->child_buf_len); + + if (data->child_buf == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate compression buffer"); + return (ARCHIVE_FATAL); + } + } + + ret = __archive_create_child(cmd, &data->child_stdin, + &data->child_stdout, &data->child); + if (ret != ARCHIVE_OK) { + archive_set_error(f->archive, EINVAL, + "Can't launch external program: %s", cmd); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_OK); +} + +static ssize_t +child_write(struct archive_write_filter *f, + struct archive_write_program_data *data, const char *buf, size_t buf_len) +{ + ssize_t ret; + + if (data->child_stdin == -1) + return (-1); + + if (buf_len == 0) + return (-1); + + for (;;) { + do { + ret = write(data->child_stdin, buf, buf_len); + } while (ret == -1 && errno == EINTR); + + if (ret > 0) + return (ret); + if (ret == 0) { + close(data->child_stdin); + data->child_stdin = -1; + fcntl(data->child_stdout, F_SETFL, 0); + return (0); + } + if (ret == -1 && errno != EAGAIN) + return (-1); + + if (data->child_stdout == -1) { + fcntl(data->child_stdin, F_SETFL, 0); + __archive_check_child(data->child_stdin, + data->child_stdout); + continue; + } + + do { + ret = read(data->child_stdout, + data->child_buf + data->child_buf_avail, + data->child_buf_len - data->child_buf_avail); + } while (ret == -1 && errno == EINTR); + + if (ret == 0 || (ret == -1 && errno == EPIPE)) { + close(data->child_stdout); + data->child_stdout = -1; + fcntl(data->child_stdin, F_SETFL, 0); + continue; + } + if (ret == -1 && errno == EAGAIN) { + __archive_check_child(data->child_stdin, + data->child_stdout); + continue; + } + if (ret == -1) + return (-1); + + data->child_buf_avail += ret; + + ret = __archive_write_filter(f->next_filter, + data->child_buf, data->child_buf_avail); + if (ret != ARCHIVE_OK) + return (-1); + data->child_buf_avail = 0; + } +} + +/* + * Write data to the filter stream. + */ +int +__archive_write_program_write(struct archive_write_filter *f, + struct archive_write_program_data *data, const void *buff, size_t length) +{ + ssize_t ret; + const char *buf; + + if (data->child == 0) + return (ARCHIVE_OK); + + buf = buff; + while (length > 0) { + ret = child_write(f, data, buf, length); + if (ret == -1 || ret == 0) { + archive_set_error(f->archive, EIO, + "Can't write to program: %s", data->program_name); + return (ARCHIVE_FATAL); + } + length -= ret; + buf += ret; + } + return (ARCHIVE_OK); +} + +/* + * Finish the filtering... + */ +int +__archive_write_program_close(struct archive_write_filter *f, + struct archive_write_program_data *data) +{ + int ret, status; + ssize_t bytes_read; + + if (data->child == 0) + return ARCHIVE_OK; + + ret = 0; + close(data->child_stdin); + data->child_stdin = -1; + fcntl(data->child_stdout, F_SETFL, 0); + + for (;;) { + do { + bytes_read = read(data->child_stdout, + data->child_buf + data->child_buf_avail, + data->child_buf_len - data->child_buf_avail); + } while (bytes_read == -1 && errno == EINTR); + + if (bytes_read == 0 || (bytes_read == -1 && errno == EPIPE)) + break; + + if (bytes_read == -1) { + archive_set_error(f->archive, errno, + "Error reading from program: %s", data->program_name); + ret = ARCHIVE_FATAL; + goto cleanup; + } + data->child_buf_avail += bytes_read; + + ret = __archive_write_filter(f->next_filter, + data->child_buf, data->child_buf_avail); + if (ret != ARCHIVE_OK) { + ret = ARCHIVE_FATAL; + goto cleanup; + } + data->child_buf_avail = 0; + } + +cleanup: + /* Shut down the child. */ + if (data->child_stdin != -1) + close(data->child_stdin); + if (data->child_stdout != -1) + close(data->child_stdout); + while (waitpid(data->child, &status, 0) == -1 && errno == EINTR) + continue; +#if defined(_WIN32) && !defined(__CYGWIN__) + CloseHandle(data->child); +#endif + data->child = 0; + + if (status != 0) { + archive_set_error(f->archive, EIO, + "Error closing program: %s", data->program_name); + ret = ARCHIVE_FATAL; + } + return ret; +} + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_uuencode.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_uuencode.c new file mode 100644 index 0000000000..1ad4589219 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_uuencode.c @@ -0,0 +1,295 @@ +/*- + * Copyright (c) 2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_string.h" +#include "archive_write_private.h" + +#define LBYTES 45 + +struct private_uuencode { + int mode; + struct archive_string name; + struct archive_string encoded_buff; + size_t bs; + size_t hold_len; + unsigned char hold[LBYTES]; +}; + +static int archive_filter_uuencode_options(struct archive_write_filter *, + const char *, const char *); +static int archive_filter_uuencode_open(struct archive_write_filter *); +static int archive_filter_uuencode_write(struct archive_write_filter *, + const void *, size_t); +static int archive_filter_uuencode_close(struct archive_write_filter *); +static int archive_filter_uuencode_free(struct archive_write_filter *); +static void uu_encode(struct archive_string *, const unsigned char *, size_t); +static int64_t atol8(const char *, size_t); + +/* + * Add a compress filter to this write handle. + */ +int +archive_write_add_filter_uuencode(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct archive_write_filter *f = __archive_write_allocate_filter(_a); + struct private_uuencode *state; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_add_filter_uu"); + + state = (struct private_uuencode *)calloc(1, sizeof(*state)); + if (state == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for uuencode filter"); + return (ARCHIVE_FATAL); + } + archive_strcpy(&state->name, "-"); + state->mode = 0644; + + f->data = state; + f->name = "uuencode"; + f->code = ARCHIVE_FILTER_UU; + f->open = archive_filter_uuencode_open; + f->options = archive_filter_uuencode_options; + f->write = archive_filter_uuencode_write; + f->close = archive_filter_uuencode_close; + f->free = archive_filter_uuencode_free; + + return (ARCHIVE_OK); +} + +/* + * Set write options. + */ +static int +archive_filter_uuencode_options(struct archive_write_filter *f, const char *key, + const char *value) +{ + struct private_uuencode *state = (struct private_uuencode *)f->data; + + if (strcmp(key, "mode") == 0) { + if (value == NULL) { + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "mode option requires octal digits"); + return (ARCHIVE_FAILED); + } + state->mode = (int)atol8(value, strlen(value)) & 0777; + return (ARCHIVE_OK); + } else if (strcmp(key, "name") == 0) { + if (value == NULL) { + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "name option requires a string"); + return (ARCHIVE_FAILED); + } + archive_strcpy(&state->name, value); + return (ARCHIVE_OK); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +/* + * Setup callback. + */ +static int +archive_filter_uuencode_open(struct archive_write_filter *f) +{ + struct private_uuencode *state = (struct private_uuencode *)f->data; + size_t bs = 65536, bpb; + + if (f->archive->magic == ARCHIVE_WRITE_MAGIC) { + /* Buffer size should be a multiple number of the of bytes + * per block for performance. */ + bpb = archive_write_get_bytes_per_block(f->archive); + if (bpb > bs) + bs = bpb; + else if (bpb != 0) + bs -= bs % bpb; + } + + state->bs = bs; + if (archive_string_ensure(&state->encoded_buff, bs + 512) == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for uuencode buffer"); + return (ARCHIVE_FATAL); + } + + archive_string_sprintf(&state->encoded_buff, "begin %o %s\n", + state->mode, state->name.s); + + f->data = state; + return (0); +} + +static void +uu_encode(struct archive_string *as, const unsigned char *p, size_t len) +{ + int c; + + c = (int)len; + archive_strappend_char(as, c?c + 0x20:'`'); + for (; len >= 3; p += 3, len -= 3) { + c = p[0] >> 2; + archive_strappend_char(as, c?c + 0x20:'`'); + c = ((p[0] & 0x03) << 4) | ((p[1] & 0xf0) >> 4); + archive_strappend_char(as, c?c + 0x20:'`'); + c = ((p[1] & 0x0f) << 2) | ((p[2] & 0xc0) >> 6); + archive_strappend_char(as, c?c + 0x20:'`'); + c = p[2] & 0x3f; + archive_strappend_char(as, c?c + 0x20:'`'); + } + if (len > 0) { + c = p[0] >> 2; + archive_strappend_char(as, c?c + 0x20:'`'); + c = (p[0] & 0x03) << 4; + if (len == 1) { + archive_strappend_char(as, c?c + 0x20:'`'); + archive_strappend_char(as, '`'); + archive_strappend_char(as, '`'); + } else { + c |= (p[1] & 0xf0) >> 4; + archive_strappend_char(as, c?c + 0x20:'`'); + c = (p[1] & 0x0f) << 2; + archive_strappend_char(as, c?c + 0x20:'`'); + archive_strappend_char(as, '`'); + } + } + archive_strappend_char(as, '\n'); +} + +/* + * Write data to the encoded stream. + */ +static int +archive_filter_uuencode_write(struct archive_write_filter *f, const void *buff, + size_t length) +{ + struct private_uuencode *state = (struct private_uuencode *)f->data; + const unsigned char *p = buff; + int ret = ARCHIVE_OK; + + if (length == 0) + return (ret); + + if (state->hold_len) { + while (state->hold_len < LBYTES && length > 0) { + state->hold[state->hold_len++] = *p++; + length--; + } + if (state->hold_len < LBYTES) + return (ret); + uu_encode(&state->encoded_buff, state->hold, LBYTES); + state->hold_len = 0; + } + + for (; length >= LBYTES; length -= LBYTES, p += LBYTES) + uu_encode(&state->encoded_buff, p, LBYTES); + + /* Save remaining bytes. */ + if (length > 0) { + memcpy(state->hold, p, length); + state->hold_len = length; + } + while (archive_strlen(&state->encoded_buff) >= state->bs) { + ret = __archive_write_filter(f->next_filter, + state->encoded_buff.s, state->bs); + memmove(state->encoded_buff.s, + state->encoded_buff.s + state->bs, + state->encoded_buff.length - state->bs); + state->encoded_buff.length -= state->bs; + } + + return (ret); +} + + +/* + * Finish the compression... + */ +static int +archive_filter_uuencode_close(struct archive_write_filter *f) +{ + struct private_uuencode *state = (struct private_uuencode *)f->data; + + /* Flush remaining bytes. */ + if (state->hold_len != 0) + uu_encode(&state->encoded_buff, state->hold, state->hold_len); + archive_string_sprintf(&state->encoded_buff, "`\nend\n"); + /* Write the last block */ + archive_write_set_bytes_in_last_block(f->archive, 1); + return __archive_write_filter(f->next_filter, + state->encoded_buff.s, archive_strlen(&state->encoded_buff)); +} + +static int +archive_filter_uuencode_free(struct archive_write_filter *f) +{ + struct private_uuencode *state = (struct private_uuencode *)f->data; + + archive_string_free(&state->name); + archive_string_free(&state->encoded_buff); + free(state); + return (ARCHIVE_OK); +} + +static int64_t +atol8(const char *p, size_t char_cnt) +{ + int64_t l; + int digit; + + l = 0; + while (char_cnt-- > 0) { + if (*p >= '0' && *p <= '7') + digit = *p - '0'; + else + break; + p++; + l <<= 3; + l |= digit; + } + return (l); +} + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_xz.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_xz.c new file mode 100644 index 0000000000..8c1ebb805b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_xz.c @@ -0,0 +1,545 @@ +/*- + * Copyright (c) 2003-2010 Tim Kientzle + * Copyright (c) 2009-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_compression_xz.c 201108 2009-12-28 03:28:21Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#include <time.h> +#ifdef HAVE_LZMA_H +#include <lzma.h> +#endif + +#include "archive.h" +#include "archive_endian.h" +#include "archive_private.h" +#include "archive_write_private.h" + +#if ARCHIVE_VERSION_NUMBER < 4000000 +int +archive_write_set_compression_lzip(struct archive *a) +{ + __archive_write_filters_free(a); + return (archive_write_add_filter_lzip(a)); +} + +int +archive_write_set_compression_lzma(struct archive *a) +{ + __archive_write_filters_free(a); + return (archive_write_add_filter_lzma(a)); +} + +int +archive_write_set_compression_xz(struct archive *a) +{ + __archive_write_filters_free(a); + return (archive_write_add_filter_xz(a)); +} + +#endif + +#ifndef HAVE_LZMA_H +int +archive_write_add_filter_xz(struct archive *a) +{ + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "xz compression not supported on this platform"); + return (ARCHIVE_FATAL); +} + +int +archive_write_add_filter_lzma(struct archive *a) +{ + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "lzma compression not supported on this platform"); + return (ARCHIVE_FATAL); +} + +int +archive_write_add_filter_lzip(struct archive *a) +{ + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "lzma compression not supported on this platform"); + return (ARCHIVE_FATAL); +} +#else +/* Don't compile this if we don't have liblzma. */ + +struct private_data { + int compression_level; + uint32_t threads; + lzma_stream stream; + lzma_filter lzmafilters[2]; + lzma_options_lzma lzma_opt; + int64_t total_in; + unsigned char *compressed; + size_t compressed_buffer_size; + int64_t total_out; + /* the CRC32 value of uncompressed data for lzip */ + uint32_t crc32; +}; + +static int archive_compressor_xz_options(struct archive_write_filter *, + const char *, const char *); +static int archive_compressor_xz_open(struct archive_write_filter *); +static int archive_compressor_xz_write(struct archive_write_filter *, + const void *, size_t); +static int archive_compressor_xz_close(struct archive_write_filter *); +static int archive_compressor_xz_free(struct archive_write_filter *); +static int drive_compressor(struct archive_write_filter *, + struct private_data *, int finishing); + +struct option_value { + uint32_t dict_size; + uint32_t nice_len; + lzma_match_finder mf; +}; +static const struct option_value option_values[] = { + { 1 << 16, 32, LZMA_MF_HC3}, + { 1 << 20, 32, LZMA_MF_HC3}, + { 3 << 19, 32, LZMA_MF_HC4}, + { 1 << 21, 32, LZMA_MF_BT4}, + { 3 << 20, 32, LZMA_MF_BT4}, + { 1 << 22, 32, LZMA_MF_BT4}, + { 1 << 23, 64, LZMA_MF_BT4}, + { 1 << 24, 64, LZMA_MF_BT4}, + { 3 << 23, 64, LZMA_MF_BT4}, + { 1 << 25, 64, LZMA_MF_BT4} +}; + +static int +common_setup(struct archive_write_filter *f) +{ + struct private_data *data; + struct archive_write *a = (struct archive_write *)f->archive; + data = calloc(1, sizeof(*data)); + if (data == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + f->data = data; + data->compression_level = LZMA_PRESET_DEFAULT; + data->threads = 1; + f->open = &archive_compressor_xz_open; + f->close = archive_compressor_xz_close; + f->free = archive_compressor_xz_free; + f->options = &archive_compressor_xz_options; + return (ARCHIVE_OK); +} + +/* + * Add an xz compression filter to this write handle. + */ +int +archive_write_add_filter_xz(struct archive *_a) +{ + struct archive_write_filter *f; + int r; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_add_filter_xz"); + f = __archive_write_allocate_filter(_a); + r = common_setup(f); + if (r == ARCHIVE_OK) { + f->code = ARCHIVE_FILTER_XZ; + f->name = "xz"; + } + return (r); +} + +/* LZMA is handled identically, we just need a different compression + * code set. (The liblzma setup looks at the code to determine + * the one place that XZ and LZMA require different handling.) */ +int +archive_write_add_filter_lzma(struct archive *_a) +{ + struct archive_write_filter *f; + int r; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_add_filter_lzma"); + f = __archive_write_allocate_filter(_a); + r = common_setup(f); + if (r == ARCHIVE_OK) { + f->code = ARCHIVE_FILTER_LZMA; + f->name = "lzma"; + } + return (r); +} + +int +archive_write_add_filter_lzip(struct archive *_a) +{ + struct archive_write_filter *f; + int r; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_add_filter_lzip"); + f = __archive_write_allocate_filter(_a); + r = common_setup(f); + if (r == ARCHIVE_OK) { + f->code = ARCHIVE_FILTER_LZIP; + f->name = "lzip"; + } + return (r); +} + +static int +archive_compressor_xz_init_stream(struct archive_write_filter *f, + struct private_data *data) +{ + static const lzma_stream lzma_stream_init_data = LZMA_STREAM_INIT; + int ret; +#ifdef HAVE_LZMA_STREAM_ENCODER_MT + lzma_mt mt_options; +#endif + + data->stream = lzma_stream_init_data; + data->stream.next_out = data->compressed; + data->stream.avail_out = data->compressed_buffer_size; + if (f->code == ARCHIVE_FILTER_XZ) { +#ifdef HAVE_LZMA_STREAM_ENCODER_MT + if (data->threads != 1) { + memset(&mt_options, 0, sizeof(mt_options)); + mt_options.threads = data->threads; + mt_options.timeout = 300; + mt_options.filters = data->lzmafilters; + mt_options.check = LZMA_CHECK_CRC64; + ret = lzma_stream_encoder_mt(&(data->stream), + &mt_options); + } else +#endif + ret = lzma_stream_encoder(&(data->stream), + data->lzmafilters, LZMA_CHECK_CRC64); + } else if (f->code == ARCHIVE_FILTER_LZMA) { + ret = lzma_alone_encoder(&(data->stream), &data->lzma_opt); + } else { /* ARCHIVE_FILTER_LZIP */ + int dict_size = data->lzma_opt.dict_size; + int ds, log2dic, wedges; + + /* Calculate a coded dictionary size */ + if (dict_size < (1 << 12) || dict_size > (1 << 27)) { + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "Unacceptable dictionary size for lzip: %d", + dict_size); + return (ARCHIVE_FATAL); + } + for (log2dic = 27; log2dic >= 12; log2dic--) { + if (dict_size & (1 << log2dic)) + break; + } + if (dict_size > (1 << log2dic)) { + log2dic++; + wedges = + ((1 << log2dic) - dict_size) / (1 << (log2dic - 4)); + } else + wedges = 0; + ds = ((wedges << 5) & 0xe0) | (log2dic & 0x1f); + + data->crc32 = 0; + /* Make a header */ + data->compressed[0] = 0x4C; + data->compressed[1] = 0x5A; + data->compressed[2] = 0x49; + data->compressed[3] = 0x50; + data->compressed[4] = 1;/* Version */ + data->compressed[5] = (unsigned char)ds; + data->stream.next_out += 6; + data->stream.avail_out -= 6; + + ret = lzma_raw_encoder(&(data->stream), data->lzmafilters); + } + if (ret == LZMA_OK) + return (ARCHIVE_OK); + + switch (ret) { + case LZMA_MEM_ERROR: + archive_set_error(f->archive, ENOMEM, + "Internal error initializing compression library: " + "Cannot allocate memory"); + break; + default: + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library: " + "It's a bug in liblzma"); + break; + } + return (ARCHIVE_FATAL); +} + +/* + * Setup callback. + */ +static int +archive_compressor_xz_open(struct archive_write_filter *f) +{ + struct private_data *data = f->data; + int ret; + + if (data->compressed == NULL) { + size_t bs = 65536, bpb; + if (f->archive->magic == ARCHIVE_WRITE_MAGIC) { + /* Buffer size should be a multiple number of the of bytes + * per block for performance. */ + bpb = archive_write_get_bytes_per_block(f->archive); + if (bpb > bs) + bs = bpb; + else if (bpb != 0) + bs -= bs % bpb; + } + data->compressed_buffer_size = bs; + data->compressed + = (unsigned char *)malloc(data->compressed_buffer_size); + if (data->compressed == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for compression buffer"); + return (ARCHIVE_FATAL); + } + } + + f->write = archive_compressor_xz_write; + + /* Initialize compression library. */ + if (f->code == ARCHIVE_FILTER_LZIP) { + const struct option_value *val = + &option_values[data->compression_level]; + + data->lzma_opt.dict_size = val->dict_size; + data->lzma_opt.preset_dict = NULL; + data->lzma_opt.preset_dict_size = 0; + data->lzma_opt.lc = LZMA_LC_DEFAULT; + data->lzma_opt.lp = LZMA_LP_DEFAULT; + data->lzma_opt.pb = LZMA_PB_DEFAULT; + data->lzma_opt.mode = + data->compression_level<= 2? LZMA_MODE_FAST:LZMA_MODE_NORMAL; + data->lzma_opt.nice_len = val->nice_len; + data->lzma_opt.mf = val->mf; + data->lzma_opt.depth = 0; + data->lzmafilters[0].id = LZMA_FILTER_LZMA1; + data->lzmafilters[0].options = &data->lzma_opt; + data->lzmafilters[1].id = LZMA_VLI_UNKNOWN;/* Terminate */ + } else { + if (lzma_lzma_preset(&data->lzma_opt, data->compression_level)) { + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library"); + } + data->lzmafilters[0].id = LZMA_FILTER_LZMA2; + data->lzmafilters[0].options = &data->lzma_opt; + data->lzmafilters[1].id = LZMA_VLI_UNKNOWN;/* Terminate */ + } + ret = archive_compressor_xz_init_stream(f, data); + if (ret == LZMA_OK) { + f->data = data; + return (0); + } + return (ARCHIVE_FATAL); +} + +/* + * Set write options. + */ +static int +archive_compressor_xz_options(struct archive_write_filter *f, + const char *key, const char *value) +{ + struct private_data *data = (struct private_data *)f->data; + + if (strcmp(key, "compression-level") == 0) { + if (value == NULL || !(value[0] >= '0' && value[0] <= '9') || + value[1] != '\0') + return (ARCHIVE_WARN); + data->compression_level = value[0] - '0'; + if (data->compression_level > 6) + data->compression_level = 6; + return (ARCHIVE_OK); + } else if (strcmp(key, "threads") == 0) { + char *endptr; + + if (value == NULL) + return (ARCHIVE_WARN); + errno = 0; + data->threads = (int)strtoul(value, &endptr, 10); + if (errno != 0 || *endptr != '\0') { + data->threads = 1; + return (ARCHIVE_WARN); + } + if (data->threads == 0) { +#ifdef HAVE_LZMA_STREAM_ENCODER_MT + data->threads = lzma_cputhreads(); +#else + data->threads = 1; +#endif + } + return (ARCHIVE_OK); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +/* + * Write data to the compressed stream. + */ +static int +archive_compressor_xz_write(struct archive_write_filter *f, + const void *buff, size_t length) +{ + struct private_data *data = (struct private_data *)f->data; + int ret; + + /* Update statistics */ + data->total_in += length; + if (f->code == ARCHIVE_FILTER_LZIP) + data->crc32 = lzma_crc32(buff, length, data->crc32); + + /* Compress input data to output buffer */ + data->stream.next_in = buff; + data->stream.avail_in = length; + if ((ret = drive_compressor(f, data, 0)) != ARCHIVE_OK) + return (ret); + + return (ARCHIVE_OK); +} + + +/* + * Finish the compression... + */ +static int +archive_compressor_xz_close(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + int ret; + + ret = drive_compressor(f, data, 1); + if (ret == ARCHIVE_OK) { + data->total_out += + data->compressed_buffer_size - data->stream.avail_out; + ret = __archive_write_filter(f->next_filter, + data->compressed, + data->compressed_buffer_size - data->stream.avail_out); + if (f->code == ARCHIVE_FILTER_LZIP && ret == ARCHIVE_OK) { + archive_le32enc(data->compressed, data->crc32); + archive_le64enc(data->compressed+4, data->total_in); + archive_le64enc(data->compressed+12, data->total_out + 20); + ret = __archive_write_filter(f->next_filter, + data->compressed, 20); + } + } + lzma_end(&(data->stream)); + return ret; +} + +static int +archive_compressor_xz_free(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + free(data->compressed); + free(data); + f->data = NULL; + return (ARCHIVE_OK); +} + +/* + * Utility function to push input data through compressor, + * writing full output blocks as necessary. + * + * Note that this handles both the regular write case (finishing == + * false) and the end-of-archive case (finishing == true). + */ +static int +drive_compressor(struct archive_write_filter *f, + struct private_data *data, int finishing) +{ + int ret; + + for (;;) { + if (data->stream.avail_out == 0) { + data->total_out += data->compressed_buffer_size; + ret = __archive_write_filter(f->next_filter, + data->compressed, + data->compressed_buffer_size); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + data->stream.next_out = data->compressed; + data->stream.avail_out = data->compressed_buffer_size; + } + + /* If there's nothing to do, we're done. */ + if (!finishing && data->stream.avail_in == 0) + return (ARCHIVE_OK); + + ret = lzma_code(&(data->stream), + finishing ? LZMA_FINISH : LZMA_RUN ); + + switch (ret) { + case LZMA_OK: + /* In non-finishing case, check if compressor + * consumed everything */ + if (!finishing && data->stream.avail_in == 0) + return (ARCHIVE_OK); + /* In finishing case, this return always means + * there's more work */ + break; + case LZMA_STREAM_END: + /* This return can only occur in finishing case. */ + if (finishing) + return (ARCHIVE_OK); + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "lzma compression data error"); + return (ARCHIVE_FATAL); + case LZMA_MEMLIMIT_ERROR: + archive_set_error(f->archive, ENOMEM, + "lzma compression error: " + "%ju MiB would have been needed", + (uintmax_t)((lzma_memusage(&(data->stream)) + + 1024 * 1024 -1) + / (1024 * 1024))); + return (ARCHIVE_FATAL); + default: + /* Any other return value indicates an error. */ + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "lzma compression failed:" + " lzma_code() call returned status %d", + ret); + return (ARCHIVE_FATAL); + } + } +} + +#endif /* HAVE_LZMA_H */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_zstd.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_zstd.c new file mode 100644 index 0000000000..c74a35cded --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_add_filter_zstd.c @@ -0,0 +1,392 @@ +/*- + * Copyright (c) 2017 Sean Purcell + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +__FBSDID("$FreeBSD$"); + + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_ZSTD_H +#include <zstd.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_string.h" +#include "archive_write_private.h" + +/* Don't compile this if we don't have zstd.h */ + +struct private_data { + int compression_level; +#if HAVE_ZSTD_H && HAVE_LIBZSTD + ZSTD_CStream *cstream; + int64_t total_in; + ZSTD_outBuffer out; +#else + struct archive_write_program_data *pdata; +#endif +}; + +/* If we don't have the library use default range values (zstdcli.c v1.4.0) */ +#define CLEVEL_MIN -99 +#define CLEVEL_STD_MIN 0 /* prior to 1.3.4 and more recent without using --fast */ +#define CLEVEL_DEFAULT 3 +#define CLEVEL_STD_MAX 19 /* without using --ultra */ +#define CLEVEL_MAX 22 + +#define MINVER_NEGCLEVEL 10304 +#define MINVER_MINCLEVEL 10306 + +static int archive_compressor_zstd_options(struct archive_write_filter *, + const char *, const char *); +static int archive_compressor_zstd_open(struct archive_write_filter *); +static int archive_compressor_zstd_write(struct archive_write_filter *, + const void *, size_t); +static int archive_compressor_zstd_close(struct archive_write_filter *); +static int archive_compressor_zstd_free(struct archive_write_filter *); +#if HAVE_ZSTD_H && HAVE_LIBZSTD +static int drive_compressor(struct archive_write_filter *, + struct private_data *, int, const void *, size_t); +#endif + + +/* + * Add a zstd compression filter to this write handle. + */ +int +archive_write_add_filter_zstd(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct archive_write_filter *f = __archive_write_allocate_filter(_a); + struct private_data *data; + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_add_filter_zstd"); + + data = calloc(1, sizeof(*data)); + if (data == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + f->data = data; + f->open = &archive_compressor_zstd_open; + f->options = &archive_compressor_zstd_options; + f->close = &archive_compressor_zstd_close; + f->free = &archive_compressor_zstd_free; + f->code = ARCHIVE_FILTER_ZSTD; + f->name = "zstd"; + data->compression_level = CLEVEL_DEFAULT; +#if HAVE_ZSTD_H && HAVE_LIBZSTD + data->cstream = ZSTD_createCStream(); + if (data->cstream == NULL) { + free(data); + archive_set_error(&a->archive, ENOMEM, + "Failed to allocate zstd compressor object"); + return (ARCHIVE_FATAL); + } + + return (ARCHIVE_OK); +#else + data->pdata = __archive_write_program_allocate("zstd"); + if (data->pdata == NULL) { + free(data); + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Using external zstd program"); + return (ARCHIVE_WARN); +#endif +} + +static int +archive_compressor_zstd_free(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; +#if HAVE_ZSTD_H && HAVE_LIBZSTD + ZSTD_freeCStream(data->cstream); + free(data->out.dst); +#else + __archive_write_program_free(data->pdata); +#endif + free(data); + f->data = NULL; + return (ARCHIVE_OK); +} + +static int string_is_numeric (const char* value) +{ + size_t len = strlen(value); + size_t i; + + if (len == 0) { + return (ARCHIVE_WARN); + } + else if (len == 1 && !(value[0] >= '0' && value[0] <= '9')) { + return (ARCHIVE_WARN); + } + else if (!(value[0] >= '0' && value[0] <= '9') && + value[0] != '-' && value[0] != '+') { + return (ARCHIVE_WARN); + } + + for (i = 1; i < len; i++) { + if (!(value[i] >= '0' && value[i] <= '9')) { + return (ARCHIVE_WARN); + } + } + + return (ARCHIVE_OK); +} + +/* + * Set write options. + */ +static int +archive_compressor_zstd_options(struct archive_write_filter *f, const char *key, + const char *value) +{ + struct private_data *data = (struct private_data *)f->data; + + if (strcmp(key, "compression-level") == 0) { + int level = atoi(value); + /* If we don't have the library, hard-code the max level */ + int minimum = CLEVEL_MIN; + int maximum = CLEVEL_MAX; + if (string_is_numeric(value) != ARCHIVE_OK) { + return (ARCHIVE_WARN); + } +#if HAVE_ZSTD_H && HAVE_LIBZSTD + maximum = ZSTD_maxCLevel(); +#if ZSTD_VERSION_NUMBER >= MINVER_MINCLEVEL + if (ZSTD_versionNumber() >= MINVER_MINCLEVEL) { + minimum = ZSTD_minCLevel(); + } + else +#endif + if (ZSTD_versionNumber() < MINVER_NEGCLEVEL) { + minimum = CLEVEL_STD_MIN; + } +#endif + if (level < minimum || level > maximum) { + return (ARCHIVE_WARN); + } + data->compression_level = level; + return (ARCHIVE_OK); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +#if HAVE_ZSTD_H && HAVE_LIBZSTD +/* + * Setup callback. + */ +static int +archive_compressor_zstd_open(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + + if (data->out.dst == NULL) { + size_t bs = ZSTD_CStreamOutSize(), bpb; + if (f->archive->magic == ARCHIVE_WRITE_MAGIC) { + /* Buffer size should be a multiple number of + * the of bytes per block for performance. */ + bpb = archive_write_get_bytes_per_block(f->archive); + if (bpb > bs) + bs = bpb; + else if (bpb != 0) + bs -= bs % bpb; + } + data->out.size = bs; + data->out.pos = 0; + data->out.dst + = (unsigned char *)malloc(data->out.size); + if (data->out.dst == NULL) { + archive_set_error(f->archive, ENOMEM, + "Can't allocate data for compression buffer"); + return (ARCHIVE_FATAL); + } + } + + f->write = archive_compressor_zstd_write; + + if (ZSTD_isError(ZSTD_initCStream(data->cstream, + data->compression_level))) { + archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, + "Internal error initializing zstd compressor object"); + return (ARCHIVE_FATAL); + } + + return (ARCHIVE_OK); +} + +/* + * Write data to the compressed stream. + */ +static int +archive_compressor_zstd_write(struct archive_write_filter *f, const void *buff, + size_t length) +{ + struct private_data *data = (struct private_data *)f->data; + int ret; + + /* Update statistics */ + data->total_in += length; + + if ((ret = drive_compressor(f, data, 0, buff, length)) != ARCHIVE_OK) + return (ret); + + return (ARCHIVE_OK); +} + +/* + * Finish the compression... + */ +static int +archive_compressor_zstd_close(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + + /* Finish zstd frame */ + return drive_compressor(f, data, 1, NULL, 0); +} + +/* + * Utility function to push input data through compressor, + * writing full output blocks as necessary. + * + * Note that this handles both the regular write case (finishing == + * false) and the end-of-archive case (finishing == true). + */ +static int +drive_compressor(struct archive_write_filter *f, + struct private_data *data, int finishing, const void *src, size_t length) +{ + ZSTD_inBuffer in = (ZSTD_inBuffer) { src, length, 0 }; + + for (;;) { + if (data->out.pos == data->out.size) { + const int ret = __archive_write_filter(f->next_filter, + data->out.dst, data->out.size); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + data->out.pos = 0; + } + + /* If there's nothing to do, we're done. */ + if (!finishing && in.pos == in.size) + return (ARCHIVE_OK); + + { + const size_t zstdret = !finishing ? + ZSTD_compressStream(data->cstream, &data->out, &in) + : ZSTD_endStream(data->cstream, &data->out); + + if (ZSTD_isError(zstdret)) { + archive_set_error(f->archive, + ARCHIVE_ERRNO_MISC, + "Zstd compression failed: %s", + ZSTD_getErrorName(zstdret)); + return (ARCHIVE_FATAL); + } + + /* If we're finishing, 0 means nothing left to flush */ + if (finishing && zstdret == 0) { + const int ret = __archive_write_filter(f->next_filter, + data->out.dst, data->out.pos); + return (ret); + } + } + } +} + +#else /* HAVE_ZSTD_H && HAVE_LIBZSTD */ + +static int +archive_compressor_zstd_open(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + struct archive_string as; + int r; + + archive_string_init(&as); + /* --no-check matches library default */ + archive_strcpy(&as, "zstd --no-check"); + + if (data->compression_level < CLEVEL_STD_MIN) { + struct archive_string as2; + archive_string_init(&as2); + archive_string_sprintf(&as2, " --fast=%d", -data->compression_level); + archive_string_concat(&as, &as2); + archive_string_free(&as2); + } else { + struct archive_string as2; + archive_string_init(&as2); + archive_string_sprintf(&as2, " -%d", data->compression_level); + archive_string_concat(&as, &as2); + archive_string_free(&as2); + } + + if (data->compression_level > CLEVEL_STD_MAX) { + archive_strcat(&as, " --ultra"); + } + + f->write = archive_compressor_zstd_write; + r = __archive_write_program_open(f, data->pdata, as.s); + archive_string_free(&as); + return (r); +} + +static int +archive_compressor_zstd_write(struct archive_write_filter *f, const void *buff, + size_t length) +{ + struct private_data *data = (struct private_data *)f->data; + + return __archive_write_program_write(f, data->pdata, buff, length); +} + +static int +archive_compressor_zstd_close(struct archive_write_filter *f) +{ + struct private_data *data = (struct private_data *)f->data; + + return __archive_write_program_close(f, data->pdata); +} + +#endif /* HAVE_ZSTD_H && HAVE_LIBZSTD */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_blocksize.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_blocksize.3 new file mode 100644 index 0000000000..4973f99905 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_blocksize.3 @@ -0,0 +1,114 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_WRITE_BLOCKSIZE 3 +.Os +.Sh NAME +.Nm archive_write_get_bytes_per_block , +.Nm archive_write_set_bytes_per_block , +.Nm archive_write_get_bytes_in_last_block , +.Nm archive_write_set_bytes_in_last_block +.Nd functions for creating archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fn archive_write_get_bytes_per_block "struct archive *" +.Ft int +.Fn archive_write_set_bytes_per_block "struct archive *" "int bytes_per_block" +.Ft int +.Fn archive_write_get_bytes_in_last_block "struct archive *" +.Ft int +.Fn archive_write_set_bytes_in_last_block "struct archive *" "int" +.Sh DESCRIPTION +.Bl -tag -width indent +.It Fn archive_write_set_bytes_per_block +Sets the block size used for writing the archive data. +Every call to the write callback function, except possibly the last one, will +use this value for the length. +The default is to use a block size of 10240 bytes. +Note that a block size of zero will suppress internal blocking +and cause writes to be sent directly to the write callback as they occur. +.It Fn archive_write_get_bytes_per_block +Retrieve the block size to be used for writing. +A value of -1 here indicates that the library should use default values. +A value of zero indicates that internal blocking is suppressed. +.It Fn archive_write_set_bytes_in_last_block +Sets the block size used for writing the last block. +If this value is zero, the last block will be padded to the same size +as the other blocks. +Otherwise, the final block will be padded to a multiple of this size. +In particular, setting it to 1 will cause the final block to not be padded. +For compressed output, any padding generated by this option +is applied only after the compression. +The uncompressed data is always unpadded. +The default is to pad the last block to the full block size (note that +.Fn archive_write_open_filename +will set this based on the file type). +Unlike the other +.Dq set +functions, this function can be called after the archive is opened. +.It Fn archive_write_get_bytes_in_last_block +Retrieve the currently-set value for last block size. +A value of -1 here indicates that the library should use default values. +.El +.\" .Sh EXAMPLE +.Sh RETURN VALUES +.Fn archive_write_set_bytes_per_block +and +.Fn archive_write_set_bytes_in_last_block +return +.Cm ARCHIVE_OK +on success, or +.Cm ARCHIVE_FATAL . +.Pp +.Fn archive_write_get_bytes_per_block +and +.Fn archive_write_get_bytes_in_last_block +return currently configured block size +.Po +.Li -1 +indicates the default block size +.Pc , +or +.Cm ARCHIVE_FATAL . +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_write_set_options 3 , +.Xr libarchive 3 , +.Xr cpio 5 , +.Xr mtree 5 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_data.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_data.3 new file mode 100644 index 0000000000..bc208b45d5 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_data.3 @@ -0,0 +1,90 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 28, 2017 +.Dt ARCHIVE_WRITE_DATA 3 +.Os +.Sh NAME +.Nm archive_write_data , +.Nm archive_write_data_block +.Nd functions for creating archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft la_ssize_t +.Fn archive_write_data "struct archive *" "const void *" "size_t" +.Ft la_ssize_t +.Fn archive_write_data_block "struct archive *" "const void *" "size_t size" "int64_t offset" +.Sh DESCRIPTION +.Bl -tag -width indent +.It Fn archive_write_data +Write data corresponding to the header just written. +.It Fn archive_write_data_block +Write data corresponding to the header just written. +This is like +.Fn archive_write_data +except that it performs a seek on the file being +written to the specified offset before writing the data. +This is useful when restoring sparse files from archive +formats that support sparse files. +Returns number of bytes written or -1 on error. +(Note: This is currently not supported for +.Tn archive_write +handles, only for +.Tn archive_write_disk +handles. +.El +.\" .Sh EXAMPLE +.\" +.Sh RETURN VALUES +This function returns the number of bytes actually written, or +a negative error code on error. +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh BUGS +In libarchive 3.x, this function sometimes returns +zero on success instead of returning the number of bytes written. +Specifically, this occurs when writing to an +.Vt archive_write_disk +handle. +Clients should treat any value less than zero as an error +and consider any non-negative value as success. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_write_finish_entry 3 , +.Xr archive_write_set_options 3 , +.Xr libarchive 3 , +.Xr cpio 5 , +.Xr mtree 5 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk.3 new file mode 100644 index 0000000000..2fa016e454 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk.3 @@ -0,0 +1,362 @@ +.\" Copyright (c) 2003-2007 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd January 19, 2020 +.Dt ARCHIVE_WRITE_DISK 3 +.Os +.Sh NAME +.Nm archive_write_disk_new , +.Nm archive_write_disk_set_options , +.Nm archive_write_disk_set_skip_file , +.Nm archive_write_disk_set_group_lookup , +.Nm archive_write_disk_set_standard_lookup , +.Nm archive_write_disk_set_user_lookup +.Nd functions for creating objects on disk +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft struct archive * +.Fn archive_write_disk_new "void" +.Ft int +.Fn archive_write_disk_set_options "struct archive *" "int flags" +.Ft int +.Fn archive_write_disk_set_skip_file "struct archive *" "dev_t" "ino_t" +.Ft int +.Fo archive_write_disk_set_group_lookup +.Fa "struct archive *" +.Fa "void *" +.Fa "gid_t (*)(void *, const char *gname, gid_t gid)" +.Fa "void (*cleanup)(void *)" +.Fc +.Ft int +.Fn archive_write_disk_set_standard_lookup "struct archive *" +.Ft int +.Fo archive_write_disk_set_user_lookup +.Fa "struct archive *" +.Fa "void *" +.Fa "uid_t (*)(void *, const char *uname, uid_t uid)" +.Fa "void (*cleanup)(void *)" +.Fc +.Sh DESCRIPTION +These functions provide a complete API for creating objects on +disk from +.Tn struct archive_entry +descriptions. +They are most naturally used when extracting objects from an archive +using the +.Fn archive_read +interface. +The general process is to read +.Tn struct archive_entry +objects from an archive, then write those objects to a +.Tn struct archive +object created using the +.Fn archive_write_disk +family functions. +This interface is deliberately very similar to the +.Fn archive_write +interface used to write objects to a streaming archive. +.Bl -tag -width indent +.It Fn archive_write_disk_new +Allocates and initializes a +.Tn struct archive +object suitable for writing objects to disk. +.It Fn archive_write_disk_set_skip_file +Records the device and inode numbers of a file that should not be +overwritten. +This is typically used to ensure that an extraction process does not +overwrite the archive from which objects are being read. +This capability is technically unnecessary but can be a significant +performance optimization in practice. +.It Fn archive_write_disk_set_options +The options field consists of a bitwise OR of one or more of the +following values: +.Bl -tag -compact -width "indent" +.It Cm ARCHIVE_EXTRACT_ACL +Attempt to restore Access Control Lists. +By default, extended ACLs are ignored. +.It Cm ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS +Before removing a file system object prior to replacing it, clear +platform-specific file flags which might prevent its removal. +.It Cm ARCHIVE_EXTRACT_FFLAGS +Attempt to restore file attributes (file flags). +By default, file attributes are ignored. +See +.Xr chattr 1 +.Pq Linux +or +.Xr chflags 1 +.Pq FreeBSD, Mac OS X +for more information on file attributes. +.It Cm ARCHIVE_EXTRACT_MAC_METADATA +Mac OS X specific. +Restore metadata using +.Xr copyfile 3 . +By default, +.Xr copyfile 3 +metadata is ignored. +.It Cm ARCHIVE_EXTRACT_NO_OVERWRITE +Existing files on disk will not be overwritten. +By default, existing regular files are truncated and overwritten; +existing directories will have their permissions updated; +other pre-existing objects are unlinked and recreated from scratch. +.It Cm ARCHIVE_EXTRACT_OWNER +The user and group IDs should be set on the restored file. +By default, the user and group IDs are not restored. +.It Cm ARCHIVE_EXTRACT_PERM +Full permissions (including SGID, SUID, and sticky bits) should +be restored exactly as specified, without obeying the +current umask. +Note that SUID and SGID bits can only be restored if the +user and group ID of the object on disk are correct. +If +.Cm ARCHIVE_EXTRACT_OWNER +is not specified, then SUID and SGID bits will only be restored +if the default user and group IDs of newly-created objects on disk +happen to match those specified in the archive entry. +By default, only basic permissions are restored, and umask is obeyed. +.It Cm ARCHIVE_EXTRACT_SAFE_WRITES +Extract files atomically, by first creating a unique temporary file and then +renaming it to its required destination name. +This avoids a race where an application might see a partial file (or no +file) during extraction. +.It Cm ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS +Refuse to extract an absolute path. +The default is to not refuse such paths. +.It Cm ARCHIVE_EXTRACT_SECURE_NODOTDOT +Refuse to extract a path that contains a +.Pa .. +element anywhere within it. +The default is to not refuse such paths. +Note that paths ending in +.Pa .. +always cause an error, regardless of this flag. +.It Cm ARCHIVE_EXTRACT_SECURE_SYMLINKS +Refuse to extract any object whose final location would be altered +by a symlink on disk. +This is intended to help guard against a variety of mischief +caused by archives that (deliberately or otherwise) extract +files outside of the current directory. +The default is not to perform this check. +If +.It Cm ARCHIVE_EXTRACT_SPARSE +Scan data for blocks of NUL bytes and try to recreate them with holes. +This results in sparse files, independent of whether the archive format +supports or uses them. +.Cm ARCHIVE_EXTRACT_UNLINK +is specified together with this option, the library will +remove any intermediate symlinks it finds and return an +error only if such symlink could not be removed. +.It Cm ARCHIVE_EXTRACT_TIME +The timestamps (mtime, ctime, and atime) should be restored. +By default, they are ignored. +Note that restoring of atime is not currently supported. +.It Cm ARCHIVE_EXTRACT_UNLINK +Existing files on disk will be unlinked before any attempt to +create them. +In some cases, this can prove to be a significant performance improvement. +By default, existing files are truncated and rewritten, but +the file is not recreated. +In particular, the default behavior does not break existing hard links. +.It Cm ARCHIVE_EXTRACT_XATTR +Attempt to restore extended file attributes. +By default, they are ignored. +See +.Xr xattr 7 +.Pq Linux , +.Xr xattr 2 +.Pq Mac OS X , +or +.Xr getextattr 8 +.Pq FreeBSD +for more information on extended file attributes. +.El +.It Xo +.Fn archive_write_disk_set_group_lookup , +.Fn archive_write_disk_set_user_lookup +.Xc +The +.Tn struct archive_entry +objects contain both names and ids that can be used to identify users +and groups. +These names and ids describe the ownership of the file itself and +also appear in ACL lists. +By default, the library uses the ids and ignores the names, but +this can be overridden by registering user and group lookup functions. +To register, you must provide a lookup function which +accepts both a name and id and returns a suitable id. +You may also provide a +.Tn void * +pointer to a private data structure and a cleanup function for +that data. +The cleanup function will be invoked when the +.Tn struct archive +object is destroyed. +.It Fn archive_write_disk_set_standard_lookup +This convenience function installs a standard set of user +and group lookup functions. +These functions use +.Xr getpwnam 3 +and +.Xr getgrnam 3 +to convert names to ids, defaulting to the ids if the names cannot +be looked up. +These functions also implement a simple memory cache to reduce +the number of calls to +.Xr getpwnam 3 +and +.Xr getgrnam 3 . +.El +More information about the +.Va struct archive +object and the overall design of the library can be found in the +.Xr libarchive 3 +overview. +Many of these functions are also documented under +.Xr archive_write 3 . +.Sh RETURN VALUES +Most functions return +.Cm ARCHIVE_OK +(zero) on success, or one of several non-zero +error codes for errors. +Specific error codes include: +.Cm ARCHIVE_RETRY +for operations that might succeed if retried, +.Cm ARCHIVE_WARN +for unusual conditions that do not prevent further operations, and +.Cm ARCHIVE_FATAL +for serious errors that make remaining operations impossible. +.Pp +.Fn archive_write_disk_new +returns a pointer to a newly-allocated +.Tn struct archive +object. +.Pp +.Fn archive_write_data +returns a count of the number of bytes actually written, +or +.Li -1 +on error. +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_read 3 , +.Xr archive_write 3 , +.Xr libarchive 3 +.Sh HISTORY +The +.Nm libarchive +library first appeared in +.Fx 5.3 . +The +.Nm archive_write_disk +interface was added to +.Nm libarchive 2.0 +and first appeared in +.Fx 6.3 . +.Sh AUTHORS +.An -nosplit +The +.Nm libarchive +library was written by +.An Tim Kientzle Aq kientzle@acm.org . +.Sh BUGS +Directories are actually extracted in two distinct phases. +Directories are created during +.Fn archive_write_header , +but final permissions are not set until +.Fn archive_write_close . +This separation is necessary to correctly handle borderline +cases such as a non-writable directory containing +files, but can cause unexpected results. +In particular, directory permissions are not fully +restored until the archive is closed. +If you use +.Xr chdir 2 +to change the current directory between calls to +.Fn archive_read_extract +or before calling +.Fn archive_read_close , +you may confuse the permission-setting logic with +the result that directory permissions are restored +incorrectly. +.Pp +The library attempts to create objects with filenames longer than +.Cm PATH_MAX +by creating prefixes of the full path and changing the current directory. +Currently, this logic is limited in scope; the fixup pass does +not work correctly for such objects and the symlink security check +option disables the support for very long pathnames. +.Pp +Restoring the path +.Pa aa/../bb +does create each intermediate directory. +In particular, the directory +.Pa aa +is created as well as the final object +.Pa bb . +In theory, this can be exploited to create an entire directory hierarchy +with a single request. +Of course, this does not work if the +.Cm ARCHIVE_EXTRACT_NODOTDOT +option is specified. +.Pp +Implicit directories are always created obeying the current umask. +Explicit objects are created obeying the current umask unless +.Cm ARCHIVE_EXTRACT_PERM +is specified, in which case they current umask is ignored. +.Pp +SGID and SUID bits are restored only if the correct user and +group could be set. +If +.Cm ARCHIVE_EXTRACT_OWNER +is not specified, then no attempt is made to set the ownership. +In this case, SGID and SUID bits are restored only if the +user and group of the final object happen to match those specified +in the entry. +.Pp +The +.Dq standard +user-id and group-id lookup functions are not the defaults because +.Xr getgrnam 3 +and +.Xr getpwnam 3 +are sometimes too large for particular applications. +The current design allows the application author to use a more +compact implementation when appropriate. +.Pp +There should be a corresponding +.Nm archive_read_disk +interface that walks a directory hierarchy and returns archive +entry objects. diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk_posix.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk_posix.c new file mode 100644 index 0000000000..0168d0d411 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk_posix.c @@ -0,0 +1,4540 @@ +/*- + * Copyright (c) 2003-2010 Tim Kientzle + * Copyright (c) 2012 Michihiro NAKAJIMA + * 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 + * in this position and unchanged. + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#if !defined(_WIN32) || defined(__CYGWIN__) + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_ACL_H +#include <sys/acl.h> +#endif +#ifdef HAVE_SYS_EXTATTR_H +#include <sys/extattr.h> +#endif +#if HAVE_SYS_XATTR_H +#include <sys/xattr.h> +#elif HAVE_ATTR_XATTR_H +#include <attr/xattr.h> +#endif +#ifdef HAVE_SYS_EA_H +#include <sys/ea.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_SYS_TIME_H +#include <sys/time.h> +#endif +#ifdef HAVE_SYS_UTIME_H +#include <sys/utime.h> +#endif +#ifdef HAVE_COPYFILE_H +#include <copyfile.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_GRP_H +#include <grp.h> +#endif +#ifdef HAVE_LANGINFO_H +#include <langinfo.h> +#endif +#ifdef HAVE_LINUX_FS_H +#include <linux/fs.h> /* for Linux file flags */ +#endif +/* + * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h. + * As the include guards don't agree, the order of include is important. + */ +#ifdef HAVE_LINUX_EXT2_FS_H +#include <linux/ext2_fs.h> /* for Linux file flags */ +#endif +#if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__) +#include <ext2fs/ext2_fs.h> /* Linux file flags, broken on Cygwin */ +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#ifdef HAVE_PWD_H +#include <pwd.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_UTIME_H +#include <utime.h> +#endif +#ifdef F_GETTIMES /* Tru64 specific */ +#include <sys/fcntl1.h> +#endif + +/* + * Macro to cast st_mtime and time_t to an int64 so that 2 numbers can reliably be compared. + * + * It assumes that the input is an integer type of no more than 64 bits. + * If the number is less than zero, t must be a signed type, so it fits in + * int64_t. Otherwise, it's a nonnegative value so we can cast it to uint64_t + * without loss. But it could be a large unsigned value, so we have to clip it + * to INT64_MAX.* + */ +#define to_int64_time(t) \ + ((t) < 0 ? (int64_t)(t) : (uint64_t)(t) > (uint64_t)INT64_MAX ? INT64_MAX : (int64_t)(t)) + +#if __APPLE__ +#include <TargetConditionals.h> +#if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && HAVE_QUARANTINE_H +#include <quarantine.h> +#define HAVE_QUARANTINE 1 +#endif +#endif + +#ifdef HAVE_ZLIB_H +#include <zlib.h> +#endif + +/* TODO: Support Mac OS 'quarantine' feature. This is really just a + * standard tag to mark files that have been downloaded as "tainted". + * On Mac OS, we should mark the extracted files as tainted if the + * archive being read was tainted. Windows has a similar feature; we + * should investigate ways to support this generically. */ + +#include "archive.h" +#include "archive_acl_private.h" +#include "archive_string.h" +#include "archive_endian.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_write_disk_private.h" + +#ifndef O_BINARY +#define O_BINARY 0 +#endif +#ifndef O_CLOEXEC +#define O_CLOEXEC 0 +#endif + +/* Ignore non-int O_NOFOLLOW constant. */ +/* gnulib's fcntl.h does this on AIX, but it seems practical everywhere */ +#if defined O_NOFOLLOW && !(INT_MIN <= O_NOFOLLOW && O_NOFOLLOW <= INT_MAX) +#undef O_NOFOLLOW +#endif + +#ifndef O_NOFOLLOW +#define O_NOFOLLOW 0 +#endif + +#ifndef AT_FDCWD +#define AT_FDCWD -100 +#endif + +struct fixup_entry { + struct fixup_entry *next; + struct archive_acl acl; + mode_t mode; + int64_t atime; + int64_t birthtime; + int64_t mtime; + int64_t ctime; + unsigned long atime_nanos; + unsigned long birthtime_nanos; + unsigned long mtime_nanos; + unsigned long ctime_nanos; + unsigned long fflags_set; + size_t mac_metadata_size; + void *mac_metadata; + int fixup; /* bitmask of what needs fixing */ + char *name; +}; + +/* + * We use a bitmask to track which operations remain to be done for + * this file. In particular, this helps us avoid unnecessary + * operations when it's possible to take care of one step as a + * side-effect of another. For example, mkdir() can specify the mode + * for the newly-created object but symlink() cannot. This means we + * can skip chmod() if mkdir() succeeded, but we must explicitly + * chmod() if we're trying to create a directory that already exists + * (mkdir() failed) or if we're restoring a symlink. Similarly, we + * need to verify UID/GID before trying to restore SUID/SGID bits; + * that verification can occur explicitly through a stat() call or + * implicitly because of a successful chown() call. + */ +#define TODO_MODE_FORCE 0x40000000 +#define TODO_MODE_BASE 0x20000000 +#define TODO_SUID 0x10000000 +#define TODO_SUID_CHECK 0x08000000 +#define TODO_SGID 0x04000000 +#define TODO_SGID_CHECK 0x02000000 +#define TODO_APPLEDOUBLE 0x01000000 +#define TODO_MODE (TODO_MODE_BASE|TODO_SUID|TODO_SGID) +#define TODO_TIMES ARCHIVE_EXTRACT_TIME +#define TODO_OWNER ARCHIVE_EXTRACT_OWNER +#define TODO_FFLAGS ARCHIVE_EXTRACT_FFLAGS +#define TODO_ACLS ARCHIVE_EXTRACT_ACL +#define TODO_XATTR ARCHIVE_EXTRACT_XATTR +#define TODO_MAC_METADATA ARCHIVE_EXTRACT_MAC_METADATA +#define TODO_HFS_COMPRESSION ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED + +struct archive_write_disk { + struct archive archive; + + mode_t user_umask; + struct fixup_entry *fixup_list; + struct fixup_entry *current_fixup; + int64_t user_uid; + int skip_file_set; + int64_t skip_file_dev; + int64_t skip_file_ino; + time_t start_time; + + int64_t (*lookup_gid)(void *private, const char *gname, int64_t gid); + void (*cleanup_gid)(void *private); + void *lookup_gid_data; + int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid); + void (*cleanup_uid)(void *private); + void *lookup_uid_data; + + /* + * Full path of last file to satisfy symlink checks. + */ + struct archive_string path_safe; + + /* + * Cached stat data from disk for the current entry. + * If this is valid, pst points to st. Otherwise, + * pst is null. + */ + struct stat st; + struct stat *pst; + + /* Information about the object being restored right now. */ + struct archive_entry *entry; /* Entry being extracted. */ + char *name; /* Name of entry, possibly edited. */ + struct archive_string _name_data; /* backing store for 'name' */ + char *tmpname; /* Temporary name * */ + struct archive_string _tmpname_data; /* backing store for 'tmpname' */ + /* Tasks remaining for this object. */ + int todo; + /* Tasks deferred until end-of-archive. */ + int deferred; + /* Options requested by the client. */ + int flags; + /* Handle for the file we're restoring. */ + int fd; + /* Current offset for writing data to the file. */ + int64_t offset; + /* Last offset actually written to disk. */ + int64_t fd_offset; + /* Total bytes actually written to files. */ + int64_t total_bytes_written; + /* Maximum size of file, -1 if unknown. */ + int64_t filesize; + /* Dir we were in before this restore; only for deep paths. */ + int restore_pwd; + /* Mode we should use for this entry; affected by _PERM and umask. */ + mode_t mode; + /* UID/GID to use in restoring this entry. */ + int64_t uid; + int64_t gid; + /* + * HFS+ Compression. + */ + /* Xattr "com.apple.decmpfs". */ + uint32_t decmpfs_attr_size; + unsigned char *decmpfs_header_p; + /* ResourceFork set options used for fsetxattr. */ + int rsrc_xattr_options; + /* Xattr "com.apple.ResourceFork". */ + unsigned char *resource_fork; + size_t resource_fork_allocated_size; + unsigned int decmpfs_block_count; + uint32_t *decmpfs_block_info; + /* Buffer for compressed data. */ + unsigned char *compressed_buffer; + size_t compressed_buffer_size; + size_t compressed_buffer_remaining; + /* The offset of the ResourceFork where compressed data will + * be placed. */ + uint32_t compressed_rsrc_position; + uint32_t compressed_rsrc_position_v; + /* Buffer for uncompressed data. */ + char *uncompressed_buffer; + size_t block_remaining_bytes; + size_t file_remaining_bytes; +#ifdef HAVE_ZLIB_H + z_stream stream; + int stream_valid; + int decmpfs_compression_level; +#endif +}; + +/* + * Default mode for dirs created automatically (will be modified by umask). + * Note that POSIX specifies 0777 for implicitly-created dirs, "modified + * by the process' file creation mask." + */ +#define DEFAULT_DIR_MODE 0777 +/* + * Dir modes are restored in two steps: During the extraction, the permissions + * in the archive are modified to match the following limits. During + * the post-extract fixup pass, the permissions from the archive are + * applied. + */ +#define MINIMUM_DIR_MODE 0700 +#define MAXIMUM_DIR_MODE 0775 + +/* + * Maximum uncompressed size of a decmpfs block. + */ +#define MAX_DECMPFS_BLOCK_SIZE (64 * 1024) +/* + * HFS+ compression type. + */ +#define CMP_XATTR 3/* Compressed data in xattr. */ +#define CMP_RESOURCE_FORK 4/* Compressed data in resource fork. */ +/* + * HFS+ compression resource fork. + */ +#define RSRC_H_SIZE 260 /* Base size of Resource fork header. */ +#define RSRC_F_SIZE 50 /* Size of Resource fork footer. */ +/* Size to write compressed data to resource fork. */ +#define COMPRESSED_W_SIZE (64 * 1024) +/* decmpfs definitions. */ +#define MAX_DECMPFS_XATTR_SIZE 3802 +#ifndef DECMPFS_XATTR_NAME +#define DECMPFS_XATTR_NAME "com.apple.decmpfs" +#endif +#define DECMPFS_MAGIC 0x636d7066 +#define DECMPFS_COMPRESSION_MAGIC 0 +#define DECMPFS_COMPRESSION_TYPE 4 +#define DECMPFS_UNCOMPRESSED_SIZE 8 +#define DECMPFS_HEADER_SIZE 16 + +#define HFS_BLOCKS(s) ((s) >> 12) + + +static int la_opendirat(int, const char *); +static int la_mktemp(struct archive_write_disk *); +static void fsobj_error(int *, struct archive_string *, int, const char *, + const char *); +static int check_symlinks_fsobj(char *, int *, struct archive_string *, + int); +static int check_symlinks(struct archive_write_disk *); +static int create_filesystem_object(struct archive_write_disk *); +static struct fixup_entry *current_fixup(struct archive_write_disk *, + const char *pathname); +#if defined(HAVE_FCHDIR) && defined(PATH_MAX) +static void edit_deep_directories(struct archive_write_disk *ad); +#endif +static int cleanup_pathname_fsobj(char *, int *, struct archive_string *, + int); +static int cleanup_pathname(struct archive_write_disk *); +static int create_dir(struct archive_write_disk *, char *); +static int create_parent_dir(struct archive_write_disk *, char *); +static ssize_t hfs_write_data_block(struct archive_write_disk *, + const char *, size_t); +static int fixup_appledouble(struct archive_write_disk *, const char *); +static int older(struct stat *, struct archive_entry *); +static int restore_entry(struct archive_write_disk *); +static int set_mac_metadata(struct archive_write_disk *, const char *, + const void *, size_t); +static int set_xattrs(struct archive_write_disk *); +static int clear_nochange_fflags(struct archive_write_disk *); +static int set_fflags(struct archive_write_disk *); +static int set_fflags_platform(struct archive_write_disk *, int fd, + const char *name, mode_t mode, + unsigned long fflags_set, unsigned long fflags_clear); +static int set_ownership(struct archive_write_disk *); +static int set_mode(struct archive_write_disk *, int mode); +static int set_time(int, int, const char *, time_t, long, time_t, long); +static int set_times(struct archive_write_disk *, int, int, const char *, + time_t, long, time_t, long, time_t, long, time_t, long); +static int set_times_from_entry(struct archive_write_disk *); +static struct fixup_entry *sort_dir_list(struct fixup_entry *p); +static ssize_t write_data_block(struct archive_write_disk *, + const char *, size_t); + +static struct archive_vtable *archive_write_disk_vtable(void); + +static int _archive_write_disk_close(struct archive *); +static int _archive_write_disk_free(struct archive *); +static int _archive_write_disk_header(struct archive *, + struct archive_entry *); +static int64_t _archive_write_disk_filter_bytes(struct archive *, int); +static int _archive_write_disk_finish_entry(struct archive *); +static ssize_t _archive_write_disk_data(struct archive *, const void *, + size_t); +static ssize_t _archive_write_disk_data_block(struct archive *, const void *, + size_t, int64_t); + +static int +la_mktemp(struct archive_write_disk *a) +{ + int oerrno, fd; + mode_t mode; + + archive_string_empty(&a->_tmpname_data); + archive_string_sprintf(&a->_tmpname_data, "%s.XXXXXX", a->name); + a->tmpname = a->_tmpname_data.s; + + fd = __archive_mkstemp(a->tmpname); + if (fd == -1) + return -1; + + mode = a->mode & 0777 & ~a->user_umask; + if (fchmod(fd, mode) == -1) { + oerrno = errno; + close(fd); + errno = oerrno; + return -1; + } + return fd; +} + +static int +la_opendirat(int fd, const char *path) { + const int flags = O_CLOEXEC +#if defined(O_BINARY) + | O_BINARY +#endif +#if defined(O_DIRECTORY) + | O_DIRECTORY +#endif +#if defined(O_PATH) + | O_PATH +#elif defined(O_SEARCH) + | O_SEARCH +#elif defined(__FreeBSD__) && defined(O_EXEC) + | O_EXEC +#else + | O_RDONLY +#endif + ; + +#if !defined(HAVE_OPENAT) + if (fd != AT_FDCWD) { + errno = ENOTSUP; + return (-1); + } else + return (open(path, flags)); +#else + return (openat(fd, path, flags)); +#endif +} + +static int +lazy_stat(struct archive_write_disk *a) +{ + if (a->pst != NULL) { + /* Already have stat() data available. */ + return (ARCHIVE_OK); + } +#ifdef HAVE_FSTAT + if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) { + a->pst = &a->st; + return (ARCHIVE_OK); + } +#endif + /* + * XXX At this point, symlinks should not be hit, otherwise + * XXX a race occurred. Do we want to check explicitly for that? + */ + if (lstat(a->name, &a->st) == 0) { + a->pst = &a->st; + return (ARCHIVE_OK); + } + archive_set_error(&a->archive, errno, "Couldn't stat file"); + return (ARCHIVE_WARN); +} + +static struct archive_vtable * +archive_write_disk_vtable(void) +{ + static struct archive_vtable av; + static int inited = 0; + + if (!inited) { + av.archive_close = _archive_write_disk_close; + av.archive_filter_bytes = _archive_write_disk_filter_bytes; + av.archive_free = _archive_write_disk_free; + av.archive_write_header = _archive_write_disk_header; + av.archive_write_finish_entry + = _archive_write_disk_finish_entry; + av.archive_write_data = _archive_write_disk_data; + av.archive_write_data_block = _archive_write_disk_data_block; + inited = 1; + } + return (&av); +} + +static int64_t +_archive_write_disk_filter_bytes(struct archive *_a, int n) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + (void)n; /* UNUSED */ + if (n == -1 || n == 0) + return (a->total_bytes_written); + return (-1); +} + + +int +archive_write_disk_set_options(struct archive *_a, int flags) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + + a->flags = flags; + return (ARCHIVE_OK); +} + + +/* + * Extract this entry to disk. + * + * TODO: Validate hardlinks. According to the standards, we're + * supposed to check each extracted hardlink and squawk if it refers + * to a file that we didn't restore. I'm not entirely convinced this + * is a good idea, but more importantly: Is there any way to validate + * hardlinks without keeping a complete list of filenames from the + * entire archive?? Ugh. + * + */ +static int +_archive_write_disk_header(struct archive *_a, struct archive_entry *entry) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + struct fixup_entry *fe; + int ret, r; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_write_disk_header"); + archive_clear_error(&a->archive); + if (a->archive.state & ARCHIVE_STATE_DATA) { + r = _archive_write_disk_finish_entry(&a->archive); + if (r == ARCHIVE_FATAL) + return (r); + } + + /* Set up for this particular entry. */ + a->pst = NULL; + a->current_fixup = NULL; + a->deferred = 0; + if (a->entry) { + archive_entry_free(a->entry); + a->entry = NULL; + } + a->entry = archive_entry_clone(entry); + a->fd = -1; + a->fd_offset = 0; + a->offset = 0; + a->restore_pwd = -1; + a->uid = a->user_uid; + a->mode = archive_entry_mode(a->entry); + if (archive_entry_size_is_set(a->entry)) + a->filesize = archive_entry_size(a->entry); + else + a->filesize = -1; + archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry)); + a->name = a->_name_data.s; + archive_clear_error(&a->archive); + + /* + * Clean up the requested path. This is necessary for correct + * dir restores; the dir restore logic otherwise gets messed + * up by nonsense like "dir/.". + */ + ret = cleanup_pathname(a); + if (ret != ARCHIVE_OK) + return (ret); + + /* + * Query the umask so we get predictable mode settings. + * This gets done on every call to _write_header in case the + * user edits their umask during the extraction for some + * reason. + */ + umask(a->user_umask = umask(0)); + + /* Figure out what we need to do for this entry. */ + a->todo = TODO_MODE_BASE; + if (a->flags & ARCHIVE_EXTRACT_PERM) { + a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */ + /* + * SGID requires an extra "check" step because we + * cannot easily predict the GID that the system will + * assign. (Different systems assign GIDs to files + * based on a variety of criteria, including process + * credentials and the gid of the enclosing + * directory.) We can only restore the SGID bit if + * the file has the right GID, and we only know the + * GID if we either set it (see set_ownership) or if + * we've actually called stat() on the file after it + * was restored. Since there are several places at + * which we might verify the GID, we need a TODO bit + * to keep track. + */ + if (a->mode & S_ISGID) + a->todo |= TODO_SGID | TODO_SGID_CHECK; + /* + * Verifying the SUID is simpler, but can still be + * done in multiple ways, hence the separate "check" bit. + */ + if (a->mode & S_ISUID) + a->todo |= TODO_SUID | TODO_SUID_CHECK; + } else { + /* + * User didn't request full permissions, so don't + * restore SUID, SGID bits and obey umask. + */ + a->mode &= ~S_ISUID; + a->mode &= ~S_ISGID; + a->mode &= ~S_ISVTX; + a->mode &= ~a->user_umask; + } + if (a->flags & ARCHIVE_EXTRACT_OWNER) + a->todo |= TODO_OWNER; + if (a->flags & ARCHIVE_EXTRACT_TIME) + a->todo |= TODO_TIMES; + if (a->flags & ARCHIVE_EXTRACT_ACL) { +#if ARCHIVE_ACL_DARWIN + /* + * On MacOS, platform ACLs get stored in mac_metadata, too. + * If we intend to extract mac_metadata and it is present + * we skip extracting libarchive NFSv4 ACLs. + */ + size_t metadata_size; + + if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 || + archive_entry_mac_metadata(a->entry, + &metadata_size) == NULL || metadata_size == 0) +#endif +#if ARCHIVE_ACL_LIBRICHACL + /* + * RichACLs are stored in an extended attribute. + * If we intend to extract extended attributes and have this + * attribute we skip extracting libarchive NFSv4 ACLs. + */ + short extract_acls = 1; + if (a->flags & ARCHIVE_EXTRACT_XATTR && ( + archive_entry_acl_types(a->entry) & + ARCHIVE_ENTRY_ACL_TYPE_NFS4)) { + const char *attr_name; + const void *attr_value; + size_t attr_size; + int i = archive_entry_xattr_reset(a->entry); + while (i--) { + archive_entry_xattr_next(a->entry, &attr_name, + &attr_value, &attr_size); + if (attr_name != NULL && attr_value != NULL && + attr_size > 0 && strcmp(attr_name, + "trusted.richacl") == 0) { + extract_acls = 0; + break; + } + } + } + if (extract_acls) +#endif +#if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL + { +#endif + if (archive_entry_filetype(a->entry) == AE_IFDIR) + a->deferred |= TODO_ACLS; + else + a->todo |= TODO_ACLS; +#if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL + } +#endif + } + if (a->flags & ARCHIVE_EXTRACT_MAC_METADATA) { + if (archive_entry_filetype(a->entry) == AE_IFDIR) + a->deferred |= TODO_MAC_METADATA; + else + a->todo |= TODO_MAC_METADATA; + } +#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H) + if ((a->flags & ARCHIVE_EXTRACT_NO_HFS_COMPRESSION) == 0) { + unsigned long set, clear; + archive_entry_fflags(a->entry, &set, &clear); + if ((set & ~clear) & UF_COMPRESSED) { + a->todo |= TODO_HFS_COMPRESSION; + a->decmpfs_block_count = (unsigned)-1; + } + } + if ((a->flags & ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED) != 0 && + (a->mode & AE_IFMT) == AE_IFREG && a->filesize > 0) { + a->todo |= TODO_HFS_COMPRESSION; + a->decmpfs_block_count = (unsigned)-1; + } + { + const char *p; + + /* Check if the current file name is a type of the + * resource fork file. */ + p = strrchr(a->name, '/'); + if (p == NULL) + p = a->name; + else + p++; + if (p[0] == '.' && p[1] == '_') { + /* Do not compress "._XXX" files. */ + a->todo &= ~TODO_HFS_COMPRESSION; + if (a->filesize > 0) + a->todo |= TODO_APPLEDOUBLE; + } + } +#endif + + if (a->flags & ARCHIVE_EXTRACT_XATTR) { +#if ARCHIVE_XATTR_DARWIN + /* + * On MacOS, extended attributes get stored in mac_metadata, + * too. If we intend to extract mac_metadata and it is present + * we skip extracting extended attributes. + */ + size_t metadata_size; + + if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 || + archive_entry_mac_metadata(a->entry, + &metadata_size) == NULL || metadata_size == 0) +#endif + a->todo |= TODO_XATTR; + } + if (a->flags & ARCHIVE_EXTRACT_FFLAGS) + a->todo |= TODO_FFLAGS; + if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) { + ret = check_symlinks(a); + if (ret != ARCHIVE_OK) + return (ret); + } +#if defined(HAVE_FCHDIR) && defined(PATH_MAX) + /* If path exceeds PATH_MAX, shorten the path. */ + edit_deep_directories(a); +#endif + + ret = restore_entry(a); + +#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H) + /* + * Check if the filesystem the file is restoring on supports + * HFS+ Compression. If not, cancel HFS+ Compression. + */ + if (a->todo | TODO_HFS_COMPRESSION) { + /* + * NOTE: UF_COMPRESSED is ignored even if the filesystem + * supports HFS+ Compression because the file should + * have at least an extended attribute "com.apple.decmpfs" + * before the flag is set to indicate that the file have + * been compressed. If the filesystem does not support + * HFS+ Compression the system call will fail. + */ + if (a->fd < 0 || fchflags(a->fd, UF_COMPRESSED) != 0) + a->todo &= ~TODO_HFS_COMPRESSION; + } +#endif + + /* + * TODO: There are rumours that some extended attributes must + * be restored before file data is written. If this is true, + * then we either need to write all extended attributes both + * before and after restoring the data, or find some rule for + * determining which must go first and which last. Due to the + * many ways people are using xattrs, this may prove to be an + * intractable problem. + */ + +#ifdef HAVE_FCHDIR + /* If we changed directory above, restore it here. */ + if (a->restore_pwd >= 0) { + r = fchdir(a->restore_pwd); + if (r != 0) { + archive_set_error(&a->archive, errno, + "chdir() failure"); + ret = ARCHIVE_FATAL; + } + close(a->restore_pwd); + a->restore_pwd = -1; + } +#endif + + /* + * Fixup uses the unedited pathname from archive_entry_pathname(), + * because it is relative to the base dir and the edited path + * might be relative to some intermediate dir as a result of the + * deep restore logic. + */ + if (a->deferred & TODO_MODE) { + fe = current_fixup(a, archive_entry_pathname(entry)); + if (fe == NULL) + return (ARCHIVE_FATAL); + fe->fixup |= TODO_MODE_BASE; + fe->mode = a->mode; + } + + if ((a->deferred & TODO_TIMES) + && (archive_entry_mtime_is_set(entry) + || archive_entry_atime_is_set(entry))) { + fe = current_fixup(a, archive_entry_pathname(entry)); + if (fe == NULL) + return (ARCHIVE_FATAL); + fe->mode = a->mode; + fe->fixup |= TODO_TIMES; + if (archive_entry_atime_is_set(entry)) { + fe->atime = archive_entry_atime(entry); + fe->atime_nanos = archive_entry_atime_nsec(entry); + } else { + /* If atime is unset, use start time. */ + fe->atime = a->start_time; + fe->atime_nanos = 0; + } + if (archive_entry_mtime_is_set(entry)) { + fe->mtime = archive_entry_mtime(entry); + fe->mtime_nanos = archive_entry_mtime_nsec(entry); + } else { + /* If mtime is unset, use start time. */ + fe->mtime = a->start_time; + fe->mtime_nanos = 0; + } + if (archive_entry_birthtime_is_set(entry)) { + fe->birthtime = archive_entry_birthtime(entry); + fe->birthtime_nanos = archive_entry_birthtime_nsec( + entry); + } else { + /* If birthtime is unset, use mtime. */ + fe->birthtime = fe->mtime; + fe->birthtime_nanos = fe->mtime_nanos; + } + } + + if (a->deferred & TODO_ACLS) { + fe = current_fixup(a, archive_entry_pathname(entry)); + if (fe == NULL) + return (ARCHIVE_FATAL); + fe->fixup |= TODO_ACLS; + archive_acl_copy(&fe->acl, archive_entry_acl(entry)); + } + + if (a->deferred & TODO_MAC_METADATA) { + const void *metadata; + size_t metadata_size; + metadata = archive_entry_mac_metadata(a->entry, &metadata_size); + if (metadata != NULL && metadata_size > 0) { + fe = current_fixup(a, archive_entry_pathname(entry)); + if (fe == NULL) + return (ARCHIVE_FATAL); + fe->mac_metadata = malloc(metadata_size); + if (fe->mac_metadata != NULL) { + memcpy(fe->mac_metadata, metadata, + metadata_size); + fe->mac_metadata_size = metadata_size; + fe->fixup |= TODO_MAC_METADATA; + } + } + } + + if (a->deferred & TODO_FFLAGS) { + fe = current_fixup(a, archive_entry_pathname(entry)); + if (fe == NULL) + return (ARCHIVE_FATAL); + fe->fixup |= TODO_FFLAGS; + /* TODO: Complete this.. defer fflags from below. */ + } + + /* We've created the object and are ready to pour data into it. */ + if (ret >= ARCHIVE_WARN) + a->archive.state = ARCHIVE_STATE_DATA; + /* + * If it's not open, tell our client not to try writing. + * In particular, dirs, links, etc, don't get written to. + */ + if (a->fd < 0) { + archive_entry_set_size(entry, 0); + a->filesize = 0; + } + + return (ret); +} + +int +archive_write_disk_set_skip_file(struct archive *_a, la_int64_t d, la_int64_t i) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file"); + a->skip_file_set = 1; + a->skip_file_dev = d; + a->skip_file_ino = i; + return (ARCHIVE_OK); +} + +static ssize_t +write_data_block(struct archive_write_disk *a, const char *buff, size_t size) +{ + uint64_t start_size = size; + ssize_t bytes_written = 0; + ssize_t block_size = 0, bytes_to_write; + + if (size == 0) + return (ARCHIVE_OK); + + if (a->filesize == 0 || a->fd < 0) { + archive_set_error(&a->archive, 0, + "Attempt to write to an empty file"); + return (ARCHIVE_WARN); + } + + if (a->flags & ARCHIVE_EXTRACT_SPARSE) { +#if HAVE_STRUCT_STAT_ST_BLKSIZE + int r; + if ((r = lazy_stat(a)) != ARCHIVE_OK) + return (r); + block_size = a->pst->st_blksize; +#else + /* XXX TODO XXX Is there a more appropriate choice here ? */ + /* This needn't match the filesystem allocation size. */ + block_size = 16*1024; +#endif + } + + /* If this write would run beyond the file size, truncate it. */ + if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize) + start_size = size = (size_t)(a->filesize - a->offset); + + /* Write the data. */ + while (size > 0) { + if (block_size == 0) { + bytes_to_write = size; + } else { + /* We're sparsifying the file. */ + const char *p, *end; + int64_t block_end; + + /* Skip leading zero bytes. */ + for (p = buff, end = buff + size; p < end; ++p) { + if (*p != '\0') + break; + } + a->offset += p - buff; + size -= p - buff; + buff = p; + if (size == 0) + break; + + /* Calculate next block boundary after offset. */ + block_end + = (a->offset / block_size + 1) * block_size; + + /* If the adjusted write would cross block boundary, + * truncate it to the block boundary. */ + bytes_to_write = size; + if (a->offset + bytes_to_write > block_end) + bytes_to_write = block_end - a->offset; + } + /* Seek if necessary to the specified offset. */ + if (a->offset != a->fd_offset) { + if (lseek(a->fd, a->offset, SEEK_SET) < 0) { + archive_set_error(&a->archive, errno, + "Seek failed"); + return (ARCHIVE_FATAL); + } + a->fd_offset = a->offset; + } + bytes_written = write(a->fd, buff, bytes_to_write); + if (bytes_written < 0) { + archive_set_error(&a->archive, errno, "Write failed"); + return (ARCHIVE_WARN); + } + buff += bytes_written; + size -= bytes_written; + a->total_bytes_written += bytes_written; + a->offset += bytes_written; + a->fd_offset = a->offset; + } + return (start_size - size); +} + +#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\ + && defined(HAVE_ZLIB_H) + +/* + * Set UF_COMPRESSED file flag. + * This have to be called after hfs_write_decmpfs() because if the + * file does not have "com.apple.decmpfs" xattr the flag is ignored. + */ +static int +hfs_set_compressed_fflag(struct archive_write_disk *a) +{ + int r; + + if ((r = lazy_stat(a)) != ARCHIVE_OK) + return (r); + + a->st.st_flags |= UF_COMPRESSED; + if (fchflags(a->fd, a->st.st_flags) != 0) { + archive_set_error(&a->archive, errno, + "Failed to set UF_COMPRESSED file flag"); + return (ARCHIVE_WARN); + } + return (ARCHIVE_OK); +} + +/* + * HFS+ Compression decmpfs + * + * +------------------------------+ +0 + * | Magic(LE 4 bytes) | + * +------------------------------+ + * | Type(LE 4 bytes) | + * +------------------------------+ + * | Uncompressed size(LE 8 bytes)| + * +------------------------------+ +16 + * | | + * | Compressed data | + * | (Placed only if Type == 3) | + * | | + * +------------------------------+ +3802 = MAX_DECMPFS_XATTR_SIZE + * + * Type is 3: decmpfs has compressed data. + * Type is 4: Resource Fork has compressed data. + */ +/* + * Write "com.apple.decmpfs" + */ +static int +hfs_write_decmpfs(struct archive_write_disk *a) +{ + int r; + uint32_t compression_type; + + r = fsetxattr(a->fd, DECMPFS_XATTR_NAME, a->decmpfs_header_p, + a->decmpfs_attr_size, 0, 0); + if (r < 0) { + archive_set_error(&a->archive, errno, + "Cannot restore xattr:%s", DECMPFS_XATTR_NAME); + compression_type = archive_le32dec( + &a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE]); + if (compression_type == CMP_RESOURCE_FORK) + fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME, + XATTR_SHOWCOMPRESSION); + return (ARCHIVE_WARN); + } + return (ARCHIVE_OK); +} + +/* + * HFS+ Compression Resource Fork + * + * +-----------------------------+ + * | Header(260 bytes) | + * +-----------------------------+ + * | Block count(LE 4 bytes) | + * +-----------------------------+ --+ + * +-- | Offset (LE 4 bytes) | | + * | | [distance from Block count] | | Block 0 + * | +-----------------------------+ | + * | | Compressed size(LE 4 bytes) | | + * | +-----------------------------+ --+ + * | | | + * | | .................. | + * | | | + * | +-----------------------------+ --+ + * | | Offset (LE 4 bytes) | | + * | +-----------------------------+ | Block (Block count -1) + * | | Compressed size(LE 4 bytes) | | + * +-> +-----------------------------+ --+ + * | Compressed data(n bytes) | Block 0 + * +-----------------------------+ + * | | + * | .................. | + * | | + * +-----------------------------+ + * | Compressed data(n bytes) | Block (Block count -1) + * +-----------------------------+ + * | Footer(50 bytes) | + * +-----------------------------+ + * + */ +/* + * Write the header of "com.apple.ResourceFork" + */ +static int +hfs_write_resource_fork(struct archive_write_disk *a, unsigned char *buff, + size_t bytes, uint32_t position) +{ + int ret; + + ret = fsetxattr(a->fd, XATTR_RESOURCEFORK_NAME, buff, bytes, + position, a->rsrc_xattr_options); + if (ret < 0) { + archive_set_error(&a->archive, errno, + "Cannot restore xattr: %s at %u pos %u bytes", + XATTR_RESOURCEFORK_NAME, + (unsigned)position, + (unsigned)bytes); + return (ARCHIVE_WARN); + } + a->rsrc_xattr_options &= ~XATTR_CREATE; + return (ARCHIVE_OK); +} + +static int +hfs_write_compressed_data(struct archive_write_disk *a, size_t bytes_compressed) +{ + int ret; + + ret = hfs_write_resource_fork(a, a->compressed_buffer, + bytes_compressed, a->compressed_rsrc_position); + if (ret == ARCHIVE_OK) + a->compressed_rsrc_position += bytes_compressed; + return (ret); +} + +static int +hfs_write_resource_fork_header(struct archive_write_disk *a) +{ + unsigned char *buff; + uint32_t rsrc_bytes; + uint32_t rsrc_header_bytes; + + /* + * Write resource fork header + block info. + */ + buff = a->resource_fork; + rsrc_bytes = a->compressed_rsrc_position - RSRC_F_SIZE; + rsrc_header_bytes = + RSRC_H_SIZE + /* Header base size. */ + 4 + /* Block count. */ + (a->decmpfs_block_count * 8);/* Block info */ + archive_be32enc(buff, 0x100); + archive_be32enc(buff + 4, rsrc_bytes); + archive_be32enc(buff + 8, rsrc_bytes - 256); + archive_be32enc(buff + 12, 0x32); + memset(buff + 16, 0, 240); + archive_be32enc(buff + 256, rsrc_bytes - 260); + return hfs_write_resource_fork(a, buff, rsrc_header_bytes, 0); +} + +static size_t +hfs_set_resource_fork_footer(unsigned char *buff, size_t buff_size) +{ + static const char rsrc_footer[RSRC_F_SIZE] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x1c, 0x00, 0x32, 0x00, 0x00, 'c', 'm', + 'p', 'f', 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01, + 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00 + }; + if (buff_size < sizeof(rsrc_footer)) + return (0); + memcpy(buff, rsrc_footer, sizeof(rsrc_footer)); + return (sizeof(rsrc_footer)); +} + +static int +hfs_reset_compressor(struct archive_write_disk *a) +{ + int ret; + + if (a->stream_valid) + ret = deflateReset(&a->stream); + else + ret = deflateInit(&a->stream, a->decmpfs_compression_level); + + if (ret != Z_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Failed to initialize compressor"); + return (ARCHIVE_FATAL); + } else + a->stream_valid = 1; + + return (ARCHIVE_OK); +} + +static int +hfs_decompress(struct archive_write_disk *a) +{ + uint32_t *block_info; + unsigned int block_count; + uint32_t data_pos, data_size; + ssize_t r; + ssize_t bytes_written, bytes_to_write; + unsigned char *b; + + block_info = (uint32_t *)(a->resource_fork + RSRC_H_SIZE); + block_count = archive_le32dec(block_info++); + while (block_count--) { + data_pos = RSRC_H_SIZE + archive_le32dec(block_info++); + data_size = archive_le32dec(block_info++); + r = fgetxattr(a->fd, XATTR_RESOURCEFORK_NAME, + a->compressed_buffer, data_size, data_pos, 0); + if (r != data_size) { + archive_set_error(&a->archive, + (r < 0)?errno:ARCHIVE_ERRNO_MISC, + "Failed to read resource fork"); + return (ARCHIVE_WARN); + } + if (a->compressed_buffer[0] == 0xff) { + bytes_to_write = data_size -1; + b = a->compressed_buffer + 1; + } else { + uLong dest_len = MAX_DECMPFS_BLOCK_SIZE; + int zr; + + zr = uncompress((Bytef *)a->uncompressed_buffer, + &dest_len, a->compressed_buffer, data_size); + if (zr != Z_OK) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Failed to decompress resource fork"); + return (ARCHIVE_WARN); + } + bytes_to_write = dest_len; + b = (unsigned char *)a->uncompressed_buffer; + } + do { + bytes_written = write(a->fd, b, bytes_to_write); + if (bytes_written < 0) { + archive_set_error(&a->archive, errno, + "Write failed"); + return (ARCHIVE_WARN); + } + bytes_to_write -= bytes_written; + b += bytes_written; + } while (bytes_to_write > 0); + } + r = fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME, 0); + if (r == -1) { + archive_set_error(&a->archive, errno, + "Failed to remove resource fork"); + return (ARCHIVE_WARN); + } + return (ARCHIVE_OK); +} + +static int +hfs_drive_compressor(struct archive_write_disk *a, const char *buff, + size_t size) +{ + unsigned char *buffer_compressed; + size_t bytes_compressed; + size_t bytes_used; + int ret; + + ret = hfs_reset_compressor(a); + if (ret != ARCHIVE_OK) + return (ret); + + if (a->compressed_buffer == NULL) { + size_t block_size; + + block_size = COMPRESSED_W_SIZE + RSRC_F_SIZE + + + compressBound(MAX_DECMPFS_BLOCK_SIZE); + a->compressed_buffer = malloc(block_size); + if (a->compressed_buffer == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Resource Fork"); + return (ARCHIVE_FATAL); + } + a->compressed_buffer_size = block_size; + a->compressed_buffer_remaining = block_size; + } + + buffer_compressed = a->compressed_buffer + + a->compressed_buffer_size - a->compressed_buffer_remaining; + a->stream.next_in = (Bytef *)(uintptr_t)(const void *)buff; + a->stream.avail_in = size; + a->stream.next_out = buffer_compressed; + a->stream.avail_out = a->compressed_buffer_remaining; + do { + ret = deflate(&a->stream, Z_FINISH); + switch (ret) { + case Z_OK: + case Z_STREAM_END: + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Failed to compress data"); + return (ARCHIVE_FAILED); + } + } while (ret == Z_OK); + bytes_compressed = a->compressed_buffer_remaining - a->stream.avail_out; + + /* + * If the compressed size is larger than the original size, + * throw away compressed data, use uncompressed data instead. + */ + if (bytes_compressed > size) { + buffer_compressed[0] = 0xFF;/* uncompressed marker. */ + memcpy(buffer_compressed + 1, buff, size); + bytes_compressed = size + 1; + } + a->compressed_buffer_remaining -= bytes_compressed; + + /* + * If the compressed size is smaller than MAX_DECMPFS_XATTR_SIZE + * and the block count in the file is only one, store compressed + * data to decmpfs xattr instead of the resource fork. + */ + if (a->decmpfs_block_count == 1 && + (a->decmpfs_attr_size + bytes_compressed) + <= MAX_DECMPFS_XATTR_SIZE) { + archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE], + CMP_XATTR); + memcpy(a->decmpfs_header_p + DECMPFS_HEADER_SIZE, + buffer_compressed, bytes_compressed); + a->decmpfs_attr_size += bytes_compressed; + a->compressed_buffer_remaining = a->compressed_buffer_size; + /* + * Finish HFS+ Compression. + * - Write the decmpfs xattr. + * - Set the UF_COMPRESSED file flag. + */ + ret = hfs_write_decmpfs(a); + if (ret == ARCHIVE_OK) + ret = hfs_set_compressed_fflag(a); + return (ret); + } + + /* Update block info. */ + archive_le32enc(a->decmpfs_block_info++, + a->compressed_rsrc_position_v - RSRC_H_SIZE); + archive_le32enc(a->decmpfs_block_info++, bytes_compressed); + a->compressed_rsrc_position_v += bytes_compressed; + + /* + * Write the compressed data to the resource fork. + */ + bytes_used = a->compressed_buffer_size - a->compressed_buffer_remaining; + while (bytes_used >= COMPRESSED_W_SIZE) { + ret = hfs_write_compressed_data(a, COMPRESSED_W_SIZE); + if (ret != ARCHIVE_OK) + return (ret); + bytes_used -= COMPRESSED_W_SIZE; + if (bytes_used > COMPRESSED_W_SIZE) + memmove(a->compressed_buffer, + a->compressed_buffer + COMPRESSED_W_SIZE, + bytes_used); + else + memcpy(a->compressed_buffer, + a->compressed_buffer + COMPRESSED_W_SIZE, + bytes_used); + } + a->compressed_buffer_remaining = a->compressed_buffer_size - bytes_used; + + /* + * If the current block is the last block, write the remaining + * compressed data and the resource fork footer. + */ + if (a->file_remaining_bytes == 0) { + size_t rsrc_size; + int64_t bk; + + /* Append the resource footer. */ + rsrc_size = hfs_set_resource_fork_footer( + a->compressed_buffer + bytes_used, + a->compressed_buffer_remaining); + ret = hfs_write_compressed_data(a, bytes_used + rsrc_size); + a->compressed_buffer_remaining = a->compressed_buffer_size; + + /* If the compressed size is not enough smaller than + * the uncompressed size. cancel HFS+ compression. + * TODO: study a behavior of ditto utility and improve + * the condition to fall back into no HFS+ compression. */ + bk = HFS_BLOCKS(a->compressed_rsrc_position); + bk += bk >> 7; + if (bk > HFS_BLOCKS(a->filesize)) + return hfs_decompress(a); + /* + * Write the resourcefork header. + */ + if (ret == ARCHIVE_OK) + ret = hfs_write_resource_fork_header(a); + /* + * Finish HFS+ Compression. + * - Write the decmpfs xattr. + * - Set the UF_COMPRESSED file flag. + */ + if (ret == ARCHIVE_OK) + ret = hfs_write_decmpfs(a); + if (ret == ARCHIVE_OK) + ret = hfs_set_compressed_fflag(a); + } + return (ret); +} + +static ssize_t +hfs_write_decmpfs_block(struct archive_write_disk *a, const char *buff, + size_t size) +{ + const char *buffer_to_write; + size_t bytes_to_write; + int ret; + + if (a->decmpfs_block_count == (unsigned)-1) { + void *new_block; + size_t new_size; + unsigned int block_count; + + if (a->decmpfs_header_p == NULL) { + new_block = malloc(MAX_DECMPFS_XATTR_SIZE + + sizeof(uint32_t)); + if (new_block == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for decmpfs"); + return (ARCHIVE_FATAL); + } + a->decmpfs_header_p = new_block; + } + a->decmpfs_attr_size = DECMPFS_HEADER_SIZE; + archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_MAGIC], + DECMPFS_MAGIC); + archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE], + CMP_RESOURCE_FORK); + archive_le64enc(&a->decmpfs_header_p[DECMPFS_UNCOMPRESSED_SIZE], + a->filesize); + + /* Calculate a block count of the file. */ + block_count = + (a->filesize + MAX_DECMPFS_BLOCK_SIZE -1) / + MAX_DECMPFS_BLOCK_SIZE; + /* + * Allocate buffer for resource fork. + * Set up related pointers; + */ + new_size = + RSRC_H_SIZE + /* header */ + 4 + /* Block count */ + (block_count * sizeof(uint32_t) * 2) + + RSRC_F_SIZE; /* footer */ + if (new_size > a->resource_fork_allocated_size) { + new_block = realloc(a->resource_fork, new_size); + if (new_block == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for ResourceFork"); + return (ARCHIVE_FATAL); + } + a->resource_fork_allocated_size = new_size; + a->resource_fork = new_block; + } + + /* Allocate uncompressed buffer */ + if (a->uncompressed_buffer == NULL) { + new_block = malloc(MAX_DECMPFS_BLOCK_SIZE); + if (new_block == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for decmpfs"); + return (ARCHIVE_FATAL); + } + a->uncompressed_buffer = new_block; + } + a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE; + a->file_remaining_bytes = a->filesize; + a->compressed_buffer_remaining = a->compressed_buffer_size; + + /* + * Set up a resource fork. + */ + a->rsrc_xattr_options = XATTR_CREATE; + /* Get the position where we are going to set a bunch + * of block info. */ + a->decmpfs_block_info = + (uint32_t *)(a->resource_fork + RSRC_H_SIZE); + /* Set the block count to the resource fork. */ + archive_le32enc(a->decmpfs_block_info++, block_count); + /* Get the position where we are going to set compressed + * data. */ + a->compressed_rsrc_position = + RSRC_H_SIZE + 4 + (block_count * 8); + a->compressed_rsrc_position_v = a->compressed_rsrc_position; + a->decmpfs_block_count = block_count; + } + + /* Ignore redundant bytes. */ + if (a->file_remaining_bytes == 0) + return ((ssize_t)size); + + /* Do not overrun a block size. */ + if (size > a->block_remaining_bytes) + bytes_to_write = a->block_remaining_bytes; + else + bytes_to_write = size; + /* Do not overrun the file size. */ + if (bytes_to_write > a->file_remaining_bytes) + bytes_to_write = a->file_remaining_bytes; + + /* For efficiency, if a copy length is full of the uncompressed + * buffer size, do not copy writing data to it. */ + if (bytes_to_write == MAX_DECMPFS_BLOCK_SIZE) + buffer_to_write = buff; + else { + memcpy(a->uncompressed_buffer + + MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes, + buff, bytes_to_write); + buffer_to_write = a->uncompressed_buffer; + } + a->block_remaining_bytes -= bytes_to_write; + a->file_remaining_bytes -= bytes_to_write; + + if (a->block_remaining_bytes == 0 || a->file_remaining_bytes == 0) { + ret = hfs_drive_compressor(a, buffer_to_write, + MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes); + if (ret < 0) + return (ret); + a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE; + } + /* Ignore redundant bytes. */ + if (a->file_remaining_bytes == 0) + return ((ssize_t)size); + return (bytes_to_write); +} + +static ssize_t +hfs_write_data_block(struct archive_write_disk *a, const char *buff, + size_t size) +{ + uint64_t start_size = size; + ssize_t bytes_written = 0; + ssize_t bytes_to_write; + + if (size == 0) + return (ARCHIVE_OK); + + if (a->filesize == 0 || a->fd < 0) { + archive_set_error(&a->archive, 0, + "Attempt to write to an empty file"); + return (ARCHIVE_WARN); + } + + /* If this write would run beyond the file size, truncate it. */ + if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize) + start_size = size = (size_t)(a->filesize - a->offset); + + /* Write the data. */ + while (size > 0) { + bytes_to_write = size; + /* Seek if necessary to the specified offset. */ + if (a->offset < a->fd_offset) { + /* Can't support backward move. */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Seek failed"); + return (ARCHIVE_FATAL); + } else if (a->offset > a->fd_offset) { + int64_t skip = a->offset - a->fd_offset; + char nullblock[1024]; + + memset(nullblock, 0, sizeof(nullblock)); + while (skip > 0) { + if (skip > (int64_t)sizeof(nullblock)) + bytes_written = hfs_write_decmpfs_block( + a, nullblock, sizeof(nullblock)); + else + bytes_written = hfs_write_decmpfs_block( + a, nullblock, skip); + if (bytes_written < 0) { + archive_set_error(&a->archive, errno, + "Write failed"); + return (ARCHIVE_WARN); + } + skip -= bytes_written; + } + + a->fd_offset = a->offset; + } + bytes_written = + hfs_write_decmpfs_block(a, buff, bytes_to_write); + if (bytes_written < 0) + return (bytes_written); + buff += bytes_written; + size -= bytes_written; + a->total_bytes_written += bytes_written; + a->offset += bytes_written; + a->fd_offset = a->offset; + } + return (start_size - size); +} +#else +static ssize_t +hfs_write_data_block(struct archive_write_disk *a, const char *buff, + size_t size) +{ + return (write_data_block(a, buff, size)); +} +#endif + +static ssize_t +_archive_write_disk_data_block(struct archive *_a, + const void *buff, size_t size, int64_t offset) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + ssize_t r; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_DATA, "archive_write_data_block"); + + a->offset = offset; + if (a->todo & TODO_HFS_COMPRESSION) + r = hfs_write_data_block(a, buff, size); + else + r = write_data_block(a, buff, size); + if (r < ARCHIVE_OK) + return (r); + if ((size_t)r < size) { + archive_set_error(&a->archive, 0, + "Too much data: Truncating file at %ju bytes", + (uintmax_t)a->filesize); + return (ARCHIVE_WARN); + } +#if ARCHIVE_VERSION_NUMBER < 3999000 + return (ARCHIVE_OK); +#else + return (size); +#endif +} + +static ssize_t +_archive_write_disk_data(struct archive *_a, const void *buff, size_t size) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_DATA, "archive_write_data"); + + if (a->todo & TODO_HFS_COMPRESSION) + return (hfs_write_data_block(a, buff, size)); + return (write_data_block(a, buff, size)); +} + +static int +_archive_write_disk_finish_entry(struct archive *_a) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + int ret = ARCHIVE_OK; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_write_finish_entry"); + if (a->archive.state & ARCHIVE_STATE_HEADER) + return (ARCHIVE_OK); + archive_clear_error(&a->archive); + + /* Pad or truncate file to the right size. */ + if (a->fd < 0) { + /* There's no file. */ + } else if (a->filesize < 0) { + /* File size is unknown, so we can't set the size. */ + } else if (a->fd_offset == a->filesize) { + /* Last write ended at exactly the filesize; we're done. */ + /* Hopefully, this is the common case. */ +#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H) + } else if (a->todo & TODO_HFS_COMPRESSION) { + char null_d[1024]; + ssize_t r; + + if (a->file_remaining_bytes) + memset(null_d, 0, sizeof(null_d)); + while (a->file_remaining_bytes) { + if (a->file_remaining_bytes > sizeof(null_d)) + r = hfs_write_data_block( + a, null_d, sizeof(null_d)); + else + r = hfs_write_data_block( + a, null_d, a->file_remaining_bytes); + if (r < 0) + return ((int)r); + } +#endif + } else { +#if HAVE_FTRUNCATE + if (ftruncate(a->fd, a->filesize) == -1 && + a->filesize == 0) { + archive_set_error(&a->archive, errno, + "File size could not be restored"); + return (ARCHIVE_FAILED); + } +#endif + /* + * Not all platforms implement the XSI option to + * extend files via ftruncate. Stat() the file again + * to see what happened. + */ + a->pst = NULL; + if ((ret = lazy_stat(a)) != ARCHIVE_OK) + return (ret); + /* We can use lseek()/write() to extend the file if + * ftruncate didn't work or isn't available. */ + if (a->st.st_size < a->filesize) { + const char nul = '\0'; + if (lseek(a->fd, a->filesize - 1, SEEK_SET) < 0) { + archive_set_error(&a->archive, errno, + "Seek failed"); + return (ARCHIVE_FATAL); + } + if (write(a->fd, &nul, 1) < 0) { + archive_set_error(&a->archive, errno, + "Write to restore size failed"); + return (ARCHIVE_FATAL); + } + a->pst = NULL; + } + } + + /* Restore metadata. */ + + /* + * This is specific to Mac OS X. + * If the current file is an AppleDouble file, it should be + * linked with the data fork file and remove it. + */ + if (a->todo & TODO_APPLEDOUBLE) { + int r2 = fixup_appledouble(a, a->name); + if (r2 == ARCHIVE_EOF) { + /* The current file has been successfully linked + * with the data fork file and removed. So there + * is nothing to do on the current file. */ + goto finish_metadata; + } + if (r2 < ret) ret = r2; + } + + /* + * Look up the "real" UID only if we're going to need it. + * TODO: the TODO_SGID condition can be dropped here, can't it? + */ + if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) { + a->uid = archive_write_disk_uid(&a->archive, + archive_entry_uname(a->entry), + archive_entry_uid(a->entry)); + } + /* Look up the "real" GID only if we're going to need it. */ + /* TODO: the TODO_SUID condition can be dropped here, can't it? */ + if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) { + a->gid = archive_write_disk_gid(&a->archive, + archive_entry_gname(a->entry), + archive_entry_gid(a->entry)); + } + + /* + * Restore ownership before set_mode tries to restore suid/sgid + * bits. If we set the owner, we know what it is and can skip + * a stat() call to examine the ownership of the file on disk. + */ + if (a->todo & TODO_OWNER) { + int r2 = set_ownership(a); + if (r2 < ret) ret = r2; + } + + /* + * HYPOTHESIS: + * If we're not root, we won't be setting any security + * attributes that may be wiped by the set_mode() routine + * below. We also can't set xattr on non-owner-writable files, + * which may be the state after set_mode(). Perform + * set_xattrs() first based on these constraints. + */ + if (a->user_uid != 0 && + (a->todo & TODO_XATTR)) { + int r2 = set_xattrs(a); + if (r2 < ret) ret = r2; + } + + /* + * set_mode must precede ACLs on systems such as Solaris and + * FreeBSD where setting the mode implicitly clears extended ACLs + */ + if (a->todo & TODO_MODE) { + int r2 = set_mode(a, a->mode); + if (r2 < ret) ret = r2; + } + + /* + * Security-related extended attributes (such as + * security.capability on Linux) have to be restored last, + * since they're implicitly removed by other file changes. + * We do this last only when root. + */ + if (a->user_uid == 0 && + (a->todo & TODO_XATTR)) { + int r2 = set_xattrs(a); + if (r2 < ret) ret = r2; + } + + /* + * Some flags prevent file modification; they must be restored after + * file contents are written. + */ + if (a->todo & TODO_FFLAGS) { + int r2 = set_fflags(a); + if (r2 < ret) ret = r2; + } + + /* + * Time must follow most other metadata; + * otherwise atime will get changed. + */ + if (a->todo & TODO_TIMES) { + int r2 = set_times_from_entry(a); + if (r2 < ret) ret = r2; + } + + /* + * Mac extended metadata includes ACLs. + */ + if (a->todo & TODO_MAC_METADATA) { + const void *metadata; + size_t metadata_size; + metadata = archive_entry_mac_metadata(a->entry, &metadata_size); + if (metadata != NULL && metadata_size > 0) { + int r2 = set_mac_metadata(a, archive_entry_pathname( + a->entry), metadata, metadata_size); + if (r2 < ret) ret = r2; + } + } + + /* + * ACLs must be restored after timestamps because there are + * ACLs that prevent attribute changes (including time). + */ + if (a->todo & TODO_ACLS) { + int r2; + r2 = archive_write_disk_set_acls(&a->archive, a->fd, + archive_entry_pathname(a->entry), + archive_entry_acl(a->entry), + archive_entry_mode(a->entry)); + if (r2 < ret) ret = r2; + } + +finish_metadata: + /* If there's an fd, we can close it now. */ + if (a->fd >= 0) { + close(a->fd); + a->fd = -1; + if (a->tmpname) { + if (rename(a->tmpname, a->name) == -1) { + archive_set_error(&a->archive, errno, + "Failed to rename temporary file"); + ret = ARCHIVE_FAILED; + unlink(a->tmpname); + } + a->tmpname = NULL; + } + } + /* If there's an entry, we can release it now. */ + archive_entry_free(a->entry); + a->entry = NULL; + a->archive.state = ARCHIVE_STATE_HEADER; + return (ret); +} + +int +archive_write_disk_set_group_lookup(struct archive *_a, + void *private_data, + la_int64_t (*lookup_gid)(void *private, const char *gname, la_int64_t gid), + void (*cleanup_gid)(void *private)) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup"); + + if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL) + (a->cleanup_gid)(a->lookup_gid_data); + + a->lookup_gid = lookup_gid; + a->cleanup_gid = cleanup_gid; + a->lookup_gid_data = private_data; + return (ARCHIVE_OK); +} + +int +archive_write_disk_set_user_lookup(struct archive *_a, + void *private_data, + int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid), + void (*cleanup_uid)(void *private)) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup"); + + if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL) + (a->cleanup_uid)(a->lookup_uid_data); + + a->lookup_uid = lookup_uid; + a->cleanup_uid = cleanup_uid; + a->lookup_uid_data = private_data; + return (ARCHIVE_OK); +} + +int64_t +archive_write_disk_gid(struct archive *_a, const char *name, la_int64_t id) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_write_disk_gid"); + if (a->lookup_gid) + return (a->lookup_gid)(a->lookup_gid_data, name, id); + return (id); +} + +int64_t +archive_write_disk_uid(struct archive *_a, const char *name, la_int64_t id) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_write_disk_uid"); + if (a->lookup_uid) + return (a->lookup_uid)(a->lookup_uid_data, name, id); + return (id); +} + +/* + * Create a new archive_write_disk object and initialize it with global state. + */ +struct archive * +archive_write_disk_new(void) +{ + struct archive_write_disk *a; + + a = (struct archive_write_disk *)calloc(1, sizeof(*a)); + if (a == NULL) + return (NULL); + a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC; + /* We're ready to write a header immediately. */ + a->archive.state = ARCHIVE_STATE_HEADER; + a->archive.vtable = archive_write_disk_vtable(); + a->start_time = time(NULL); + /* Query and restore the umask. */ + umask(a->user_umask = umask(0)); +#ifdef HAVE_GETEUID + a->user_uid = geteuid(); +#endif /* HAVE_GETEUID */ + if (archive_string_ensure(&a->path_safe, 512) == NULL) { + free(a); + return (NULL); + } +#ifdef HAVE_ZLIB_H + a->decmpfs_compression_level = 5; +#endif + return (&a->archive); +} + + +/* + * If pathname is longer than PATH_MAX, chdir to a suitable + * intermediate dir and edit the path down to a shorter suffix. Note + * that this routine never returns an error; if the chdir() attempt + * fails for any reason, we just go ahead with the long pathname. The + * object creation is likely to fail, but any error will get handled + * at that time. + */ +#if defined(HAVE_FCHDIR) && defined(PATH_MAX) +static void +edit_deep_directories(struct archive_write_disk *a) +{ + int ret; + char *tail = a->name; + + /* If path is short, avoid the open() below. */ + if (strlen(tail) < PATH_MAX) + return; + + /* Try to record our starting dir. */ + a->restore_pwd = la_opendirat(AT_FDCWD, "."); + __archive_ensure_cloexec_flag(a->restore_pwd); + if (a->restore_pwd < 0) + return; + + /* As long as the path is too long... */ + while (strlen(tail) >= PATH_MAX) { + /* Locate a dir prefix shorter than PATH_MAX. */ + tail += PATH_MAX - 8; + while (tail > a->name && *tail != '/') + tail--; + /* Exit if we find a too-long path component. */ + if (tail <= a->name) + return; + /* Create the intermediate dir and chdir to it. */ + *tail = '\0'; /* Terminate dir portion */ + ret = create_dir(a, a->name); + if (ret == ARCHIVE_OK && chdir(a->name) != 0) + ret = ARCHIVE_FAILED; + *tail = '/'; /* Restore the / we removed. */ + if (ret != ARCHIVE_OK) + return; + tail++; + /* The chdir() succeeded; we've now shortened the path. */ + a->name = tail; + } + return; +} +#endif + +/* + * The main restore function. + */ +static int +restore_entry(struct archive_write_disk *a) +{ + int ret = ARCHIVE_OK, en; + + if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) { + /* + * TODO: Fix this. Apparently, there are platforms + * that still allow root to hose the entire filesystem + * by unlinking a dir. The S_ISDIR() test above + * prevents us from using unlink() here if the new + * object is a dir, but that doesn't mean the old + * object isn't a dir. + */ + if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS) + (void)clear_nochange_fflags(a); + if (unlink(a->name) == 0) { + /* We removed it, reset cached stat. */ + a->pst = NULL; + } else if (errno == ENOENT) { + /* File didn't exist, that's just as good. */ + } else if (rmdir(a->name) == 0) { + /* It was a dir, but now it's gone. */ + a->pst = NULL; + } else { + /* We tried, but couldn't get rid of it. */ + archive_set_error(&a->archive, errno, + "Could not unlink"); + return(ARCHIVE_FAILED); + } + } + + /* Try creating it first; if this fails, we'll try to recover. */ + en = create_filesystem_object(a); + + if ((en == ENOTDIR || en == ENOENT) + && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) { + /* If the parent dir doesn't exist, try creating it. */ + create_parent_dir(a, a->name); + /* Now try to create the object again. */ + en = create_filesystem_object(a); + } + + if ((en == ENOENT) && (archive_entry_hardlink(a->entry) != NULL)) { + archive_set_error(&a->archive, en, + "Hard-link target '%s' does not exist.", + archive_entry_hardlink(a->entry)); + return (ARCHIVE_FAILED); + } + + if ((en == EISDIR || en == EEXIST) + && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) { + /* If we're not overwriting, we're done. */ + if (S_ISDIR(a->mode)) { + /* Don't overwrite any settings on existing directories. */ + a->todo = 0; + } + archive_entry_unset_size(a->entry); + return (ARCHIVE_OK); + } + + /* + * Some platforms return EISDIR if you call + * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some + * return EEXIST. POSIX is ambiguous, requiring EISDIR + * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT) + * on an existing item. + */ + if (en == EISDIR) { + /* A dir is in the way of a non-dir, rmdir it. */ + if (rmdir(a->name) != 0) { + archive_set_error(&a->archive, errno, + "Can't remove already-existing dir"); + return (ARCHIVE_FAILED); + } + a->pst = NULL; + /* Try again. */ + en = create_filesystem_object(a); + } else if (en == EEXIST) { + /* + * We know something is in the way, but we don't know what; + * we need to find out before we go any further. + */ + int r = 0; + /* + * The SECURE_SYMLINKS logic has already removed a + * symlink to a dir if the client wants that. So + * follow the symlink if we're creating a dir. + */ + if (S_ISDIR(a->mode)) + r = la_stat(a->name, &a->st); + /* + * If it's not a dir (or it's a broken symlink), + * then don't follow it. + */ + if (r != 0 || !S_ISDIR(a->mode)) + r = lstat(a->name, &a->st); + if (r != 0) { + archive_set_error(&a->archive, errno, + "Can't stat existing object"); + return (ARCHIVE_FAILED); + } + + /* + * NO_OVERWRITE_NEWER doesn't apply to directories. + */ + if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER) + && !S_ISDIR(a->st.st_mode)) { + if (!older(&(a->st), a->entry)) { + archive_entry_unset_size(a->entry); + return (ARCHIVE_OK); + } + } + + /* If it's our archive, we're done. */ + if (a->skip_file_set && + a->st.st_dev == (dev_t)a->skip_file_dev && + a->st.st_ino == (ino_t)a->skip_file_ino) { + archive_set_error(&a->archive, 0, + "Refusing to overwrite archive"); + return (ARCHIVE_FAILED); + } + + if (!S_ISDIR(a->st.st_mode)) { + if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS) + (void)clear_nochange_fflags(a); + + if ((a->flags & ARCHIVE_EXTRACT_SAFE_WRITES) && + S_ISREG(a->st.st_mode)) { + /* Use a temporary file to extract */ + if ((a->fd = la_mktemp(a)) == -1) { + archive_set_error(&a->archive, errno, + "Can't create temporary file"); + return ARCHIVE_FAILED; + } + a->pst = NULL; + en = 0; + } else { + /* A non-dir is in the way, unlink it. */ + if (unlink(a->name) != 0) { + archive_set_error(&a->archive, errno, + "Can't unlink already-existing " + "object"); + return (ARCHIVE_FAILED); + } + a->pst = NULL; + /* Try again. */ + en = create_filesystem_object(a); + } + } else if (!S_ISDIR(a->mode)) { + /* A dir is in the way of a non-dir, rmdir it. */ + if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS) + (void)clear_nochange_fflags(a); + if (rmdir(a->name) != 0) { + archive_set_error(&a->archive, errno, + "Can't replace existing directory with non-directory"); + return (ARCHIVE_FAILED); + } + /* Try again. */ + en = create_filesystem_object(a); + } else { + /* + * There's a dir in the way of a dir. Don't + * waste time with rmdir()/mkdir(), just fix + * up the permissions on the existing dir. + * Note that we don't change perms on existing + * dirs unless _EXTRACT_PERM is specified. + */ + if ((a->mode != a->st.st_mode) + && (a->todo & TODO_MODE_FORCE)) + a->deferred |= (a->todo & TODO_MODE); + /* Ownership doesn't need deferred fixup. */ + en = 0; /* Forget the EEXIST. */ + } + } + + if (en) { + /* Everything failed; give up here. */ + if ((&a->archive)->error == NULL) + archive_set_error(&a->archive, en, "Can't create '%s'", + a->name); + return (ARCHIVE_FAILED); + } + + a->pst = NULL; /* Cached stat data no longer valid. */ + return (ret); +} + +/* + * Returns 0 if creation succeeds, or else returns errno value from + * the failed system call. Note: This function should only ever perform + * a single system call. + */ +static int +create_filesystem_object(struct archive_write_disk *a) +{ + /* Create the entry. */ + const char *linkname; + mode_t final_mode, mode; + int r; + /* these for check_symlinks_fsobj */ + char *linkname_copy; /* non-const copy of linkname */ + struct stat st; + struct archive_string error_string; + int error_number; + + /* We identify hard/symlinks according to the link names. */ + /* Since link(2) and symlink(2) don't handle modes, we're done here. */ + linkname = archive_entry_hardlink(a->entry); + if (linkname != NULL) { +#if !HAVE_LINK + return (EPERM); +#else + archive_string_init(&error_string); + linkname_copy = strdup(linkname); + if (linkname_copy == NULL) { + return (EPERM); + } + /* + * TODO: consider using the cleaned-up path as the link + * target? + */ + r = cleanup_pathname_fsobj(linkname_copy, &error_number, + &error_string, a->flags); + if (r != ARCHIVE_OK) { + archive_set_error(&a->archive, error_number, "%s", + error_string.s); + free(linkname_copy); + archive_string_free(&error_string); + /* + * EPERM is more appropriate than error_number for our + * callers + */ + return (EPERM); + } + r = check_symlinks_fsobj(linkname_copy, &error_number, + &error_string, a->flags); + if (r != ARCHIVE_OK) { + archive_set_error(&a->archive, error_number, "%s", + error_string.s); + free(linkname_copy); + archive_string_free(&error_string); + /* + * EPERM is more appropriate than error_number for our + * callers + */ + return (EPERM); + } + free(linkname_copy); + archive_string_free(&error_string); + /* + * Unlinking and linking here is really not atomic, + * but doing it right, would require us to construct + * an mktemplink() function, and then use rename(2). + */ + if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES) + unlink(a->name); + r = link(linkname, a->name) ? errno : 0; + /* + * New cpio and pax formats allow hardlink entries + * to carry data, so we may have to open the file + * for hardlink entries. + * + * If the hardlink was successfully created and + * the archive doesn't have carry data for it, + * consider it to be non-authoritative for meta data. + * This is consistent with GNU tar and BSD pax. + * If the hardlink does carry data, let the last + * archive entry decide ownership. + */ + if (r == 0 && a->filesize <= 0) { + a->todo = 0; + a->deferred = 0; + } else if (r == 0 && a->filesize > 0) { +#ifdef HAVE_LSTAT + r = lstat(a->name, &st); +#else + r = la_stat(a->name, &st); +#endif + if (r != 0) + r = errno; + else if ((st.st_mode & AE_IFMT) == AE_IFREG) { + a->fd = open(a->name, O_WRONLY | O_TRUNC | + O_BINARY | O_CLOEXEC | O_NOFOLLOW); + __archive_ensure_cloexec_flag(a->fd); + if (a->fd < 0) + r = errno; + } + } + return (r); +#endif + } + linkname = archive_entry_symlink(a->entry); + if (linkname != NULL) { +#if HAVE_SYMLINK + /* + * Unlinking and linking here is really not atomic, + * but doing it right, would require us to construct + * an mktempsymlink() function, and then use rename(2). + */ + if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES) + unlink(a->name); + return symlink(linkname, a->name) ? errno : 0; +#else + return (EPERM); +#endif + } + + /* + * The remaining system calls all set permissions, so let's + * try to take advantage of that to avoid an extra chmod() + * call. (Recall that umask is set to zero right now!) + */ + + /* Mode we want for the final restored object (w/o file type bits). */ + final_mode = a->mode & 07777; + /* + * The mode that will actually be restored in this step. Note + * that SUID, SGID, etc, require additional work to ensure + * security, so we never restore them at this point. + */ + mode = final_mode & 0777 & ~a->user_umask; + + /* + * Always create writable such that [f]setxattr() works if we're not + * root. + */ + if (a->user_uid != 0 && + a->todo & (TODO_HFS_COMPRESSION | TODO_XATTR)) { + mode |= 0200; + } + + switch (a->mode & AE_IFMT) { + default: + /* POSIX requires that we fall through here. */ + /* FALLTHROUGH */ + case AE_IFREG: + a->tmpname = NULL; + a->fd = open(a->name, + O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode); + __archive_ensure_cloexec_flag(a->fd); + r = (a->fd < 0); + break; + case AE_IFCHR: +#ifdef HAVE_MKNOD + /* Note: we use AE_IFCHR for the case label, and + * S_IFCHR for the mknod() call. This is correct. */ + r = mknod(a->name, mode | S_IFCHR, + archive_entry_rdev(a->entry)); + break; +#else + /* TODO: Find a better way to warn about our inability + * to restore a char device node. */ + return (EINVAL); +#endif /* HAVE_MKNOD */ + case AE_IFBLK: +#ifdef HAVE_MKNOD + r = mknod(a->name, mode | S_IFBLK, + archive_entry_rdev(a->entry)); + break; +#else + /* TODO: Find a better way to warn about our inability + * to restore a block device node. */ + return (EINVAL); +#endif /* HAVE_MKNOD */ + case AE_IFDIR: + mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE; + r = mkdir(a->name, mode); + if (r == 0) { + /* Defer setting dir times. */ + a->deferred |= (a->todo & TODO_TIMES); + a->todo &= ~TODO_TIMES; + /* Never use an immediate chmod(). */ + /* We can't avoid the chmod() entirely if EXTRACT_PERM + * because of SysV SGID inheritance. */ + if ((mode != final_mode) + || (a->flags & ARCHIVE_EXTRACT_PERM)) + a->deferred |= (a->todo & TODO_MODE); + a->todo &= ~TODO_MODE; + } + break; + case AE_IFIFO: +#ifdef HAVE_MKFIFO + r = mkfifo(a->name, mode); + break; +#else + /* TODO: Find a better way to warn about our inability + * to restore a fifo. */ + return (EINVAL); +#endif /* HAVE_MKFIFO */ + } + + /* All the system calls above set errno on failure. */ + if (r) + return (errno); + + /* If we managed to set the final mode, we've avoided a chmod(). */ + if (mode == final_mode) + a->todo &= ~TODO_MODE; + return (0); +} + +/* + * Cleanup function for archive_extract. Mostly, this involves processing + * the fixup list, which is used to address a number of problems: + * * Dir permissions might prevent us from restoring a file in that + * dir, so we restore the dir with minimum 0700 permissions first, + * then correct the mode at the end. + * * Similarly, the act of restoring a file touches the directory + * and changes the timestamp on the dir, so we have to touch-up dir + * timestamps at the end as well. + * * Some file flags can interfere with the restore by, for example, + * preventing the creation of hardlinks to those files. + * * Mac OS extended metadata includes ACLs, so must be deferred on dirs. + * + * Note that tar/cpio do not require that archives be in a particular + * order; there is no way to know when the last file has been restored + * within a directory, so there's no way to optimize the memory usage + * here by fixing up the directory any earlier than the + * end-of-archive. + * + * XXX TODO: Directory ACLs should be restored here, for the same + * reason we set directory perms here. XXX + */ +static int +_archive_write_disk_close(struct archive *_a) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + struct fixup_entry *next, *p; + int fd, ret; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_write_disk_close"); + ret = _archive_write_disk_finish_entry(&a->archive); + + /* Sort dir list so directories are fixed up in depth-first order. */ + p = sort_dir_list(a->fixup_list); + + while (p != NULL) { + fd = -1; + a->pst = NULL; /* Mark stat cache as out-of-date. */ + if (p->fixup & + (TODO_TIMES | TODO_MODE_BASE | TODO_ACLS | TODO_FFLAGS)) { + fd = open(p->name, + O_WRONLY | O_BINARY | O_NOFOLLOW | O_CLOEXEC); + } + if (p->fixup & TODO_TIMES) { + set_times(a, fd, p->mode, p->name, + p->atime, p->atime_nanos, + p->birthtime, p->birthtime_nanos, + p->mtime, p->mtime_nanos, + p->ctime, p->ctime_nanos); + } + if (p->fixup & TODO_MODE_BASE) { +#ifdef HAVE_FCHMOD + if (fd >= 0) + fchmod(fd, p->mode); + else +#endif + chmod(p->name, p->mode); + } + if (p->fixup & TODO_ACLS) + archive_write_disk_set_acls(&a->archive, fd, + p->name, &p->acl, p->mode); + if (p->fixup & TODO_FFLAGS) + set_fflags_platform(a, fd, p->name, + p->mode, p->fflags_set, 0); + if (p->fixup & TODO_MAC_METADATA) + set_mac_metadata(a, p->name, p->mac_metadata, + p->mac_metadata_size); + next = p->next; + archive_acl_clear(&p->acl); + free(p->mac_metadata); + free(p->name); + if (fd >= 0) + close(fd); + free(p); + p = next; + } + a->fixup_list = NULL; + return (ret); +} + +static int +_archive_write_disk_free(struct archive *_a) +{ + struct archive_write_disk *a; + int ret; + if (_a == NULL) + return (ARCHIVE_OK); + archive_check_magic(_a, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_disk_free"); + a = (struct archive_write_disk *)_a; + ret = _archive_write_disk_close(&a->archive); + archive_write_disk_set_group_lookup(&a->archive, NULL, NULL, NULL); + archive_write_disk_set_user_lookup(&a->archive, NULL, NULL, NULL); + archive_entry_free(a->entry); + archive_string_free(&a->_name_data); + archive_string_free(&a->_tmpname_data); + archive_string_free(&a->archive.error_string); + archive_string_free(&a->path_safe); + a->archive.magic = 0; + __archive_clean(&a->archive); + free(a->decmpfs_header_p); + free(a->resource_fork); + free(a->compressed_buffer); + free(a->uncompressed_buffer); +#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\ + && defined(HAVE_ZLIB_H) + if (a->stream_valid) { + switch (deflateEnd(&a->stream)) { + case Z_OK: + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Failed to clean up compressor"); + ret = ARCHIVE_FATAL; + break; + } + } +#endif + free(a); + return (ret); +} + +/* + * Simple O(n log n) merge sort to order the fixup list. In + * particular, we want to restore dir timestamps depth-first. + */ +static struct fixup_entry * +sort_dir_list(struct fixup_entry *p) +{ + struct fixup_entry *a, *b, *t; + + if (p == NULL) + return (NULL); + /* A one-item list is already sorted. */ + if (p->next == NULL) + return (p); + + /* Step 1: split the list. */ + t = p; + a = p->next->next; + while (a != NULL) { + /* Step a twice, t once. */ + a = a->next; + if (a != NULL) + a = a->next; + t = t->next; + } + /* Now, t is at the mid-point, so break the list here. */ + b = t->next; + t->next = NULL; + a = p; + + /* Step 2: Recursively sort the two sub-lists. */ + a = sort_dir_list(a); + b = sort_dir_list(b); + + /* Step 3: Merge the returned lists. */ + /* Pick the first element for the merged list. */ + if (strcmp(a->name, b->name) > 0) { + t = p = a; + a = a->next; + } else { + t = p = b; + b = b->next; + } + + /* Always put the later element on the list first. */ + while (a != NULL && b != NULL) { + if (strcmp(a->name, b->name) > 0) { + t->next = a; + a = a->next; + } else { + t->next = b; + b = b->next; + } + t = t->next; + } + + /* Only one list is non-empty, so just splice it on. */ + if (a != NULL) + t->next = a; + if (b != NULL) + t->next = b; + + return (p); +} + +/* + * Returns a new, initialized fixup entry. + * + * TODO: Reduce the memory requirements for this list by using a tree + * structure rather than a simple list of names. + */ +static struct fixup_entry * +new_fixup(struct archive_write_disk *a, const char *pathname) +{ + struct fixup_entry *fe; + + fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry)); + if (fe == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for a fixup"); + return (NULL); + } + fe->next = a->fixup_list; + a->fixup_list = fe; + fe->fixup = 0; + fe->name = strdup(pathname); + return (fe); +} + +/* + * Returns a fixup structure for the current entry. + */ +static struct fixup_entry * +current_fixup(struct archive_write_disk *a, const char *pathname) +{ + if (a->current_fixup == NULL) + a->current_fixup = new_fixup(a, pathname); + return (a->current_fixup); +} + +/* Error helper for new *_fsobj functions */ +static void +fsobj_error(int *a_eno, struct archive_string *a_estr, + int err, const char *errstr, const char *path) +{ + if (a_eno) + *a_eno = err; + if (a_estr) + archive_string_sprintf(a_estr, "%s%s", errstr, path); +} + +/* + * TODO: Someday, integrate this with the deep dir support; they both + * scan the path and both can be optimized by comparing against other + * recent paths. + */ +/* + * Checks the given path to see if any elements along it are symlinks. Returns + * ARCHIVE_OK if there are none, otherwise puts an error in errmsg. + */ +static int +check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr, + int flags) +{ +#if !defined(HAVE_LSTAT) && \ + !(defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)) + /* Platform doesn't have lstat, so we can't look for symlinks. */ + (void)path; /* UNUSED */ + (void)error_number; /* UNUSED */ + (void)error_string; /* UNUSED */ + (void)flags; /* UNUSED */ + return (ARCHIVE_OK); +#else + int res = ARCHIVE_OK; + char *tail; + char *head; + int last; + char c; + int r; + struct stat st; + int chdir_fd; +#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) + int fd; +#endif + + /* Nothing to do here if name is empty */ + if(path[0] == '\0') + return (ARCHIVE_OK); + + /* + * Guard against symlink tricks. Reject any archive entry whose + * destination would be altered by a symlink. + * + * Walk the filename in chunks separated by '/'. For each segment: + * - if it doesn't exist, continue + * - if it's symlink, abort or remove it + * - if it's a directory and it's not the last chunk, cd into it + * As we go: + * head points to the current (relative) path + * tail points to the temporary \0 terminating the segment we're + * currently examining + * c holds what used to be in *tail + * last is 1 if this is the last tail + */ + chdir_fd = la_opendirat(AT_FDCWD, "."); + __archive_ensure_cloexec_flag(chdir_fd); + if (chdir_fd < 0) { + fsobj_error(a_eno, a_estr, errno, + "Could not open ", path); + return (ARCHIVE_FATAL); + } + head = path; + tail = path; + last = 0; + /* TODO: reintroduce a safe cache here? */ + /* Skip the root directory if the path is absolute. */ + if(tail == path && tail[0] == '/') + ++tail; + /* Keep going until we've checked the entire name. + * head, tail, path all alias the same string, which is + * temporarily zeroed at tail, so be careful restoring the + * stashed (c=tail[0]) for error messages. + * Exiting the loop with break is okay; continue is not. + */ + while (!last) { + /* + * Skip the separator we just consumed, plus any adjacent ones + */ + while (*tail == '/') + ++tail; + /* Skip the next path element. */ + while (*tail != '\0' && *tail != '/') + ++tail; + /* is this the last path component? */ + last = (tail[0] == '\0') || (tail[0] == '/' && tail[1] == '\0'); + /* temporarily truncate the string here */ + c = tail[0]; + tail[0] = '\0'; + /* Check that we haven't hit a symlink. */ +#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) + r = fstatat(chdir_fd, head, &st, AT_SYMLINK_NOFOLLOW); +#else + r = lstat(head, &st); +#endif + if (r != 0) { + tail[0] = c; + /* We've hit a dir that doesn't exist; stop now. */ + if (errno == ENOENT) { + break; + } else { + /* + * Treat any other error as fatal - best to be + * paranoid here. + * Note: This effectively disables deep + * directory support when security checks are + * enabled. Otherwise, very long pathnames that + * trigger an error here could evade the + * sandbox. + * TODO: We could do better, but it would + * probably require merging the symlink checks + * with the deep-directory editing. + */ + fsobj_error(a_eno, a_estr, errno, + "Could not stat ", path); + res = ARCHIVE_FAILED; + break; + } + } else if (S_ISDIR(st.st_mode)) { + if (!last) { +#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) + fd = la_opendirat(chdir_fd, head); + if (fd < 0) + r = -1; + else { + r = 0; + close(chdir_fd); + chdir_fd = fd; + } +#else + r = chdir(head); +#endif + if (r != 0) { + tail[0] = c; + fsobj_error(a_eno, a_estr, errno, + "Could not chdir ", path); + res = (ARCHIVE_FATAL); + break; + } + /* Our view is now from inside this dir: */ + head = tail + 1; + } + } else if (S_ISLNK(st.st_mode)) { + if (last) { + /* + * Last element is symlink; remove it + * so we can overwrite it with the + * item being extracted. + */ +#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) + r = unlinkat(chdir_fd, head, 0); +#else + r = unlink(head); +#endif + if (r != 0) { + tail[0] = c; + fsobj_error(a_eno, a_estr, errno, + "Could not remove symlink ", + path); + res = ARCHIVE_FAILED; + break; + } + /* + * Even if we did remove it, a warning + * is in order. The warning is silly, + * though, if we're just replacing one + * symlink with another symlink. + */ + tail[0] = c; + /* + * FIXME: not sure how important this is to + * restore + */ + /* + if (!S_ISLNK(path)) { + fsobj_error(a_eno, a_estr, 0, + "Removing symlink ", path); + } + */ + /* Symlink gone. No more problem! */ + res = ARCHIVE_OK; + break; + } else if (flags & ARCHIVE_EXTRACT_UNLINK) { + /* User asked us to remove problems. */ +#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) + r = unlinkat(chdir_fd, head, 0); +#else + r = unlink(head); +#endif + if (r != 0) { + tail[0] = c; + fsobj_error(a_eno, a_estr, 0, + "Cannot remove intervening " + "symlink ", path); + res = ARCHIVE_FAILED; + break; + } + tail[0] = c; + } else if ((flags & + ARCHIVE_EXTRACT_SECURE_SYMLINKS) == 0) { + /* + * We are not the last element and we want to + * follow symlinks if they are a directory. + * + * This is needed to extract hardlinks over + * symlinks. + */ +#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) + r = fstatat(chdir_fd, head, &st, 0); +#else + r = la_stat(head, &st); +#endif + if (r != 0) { + tail[0] = c; + if (errno == ENOENT) { + break; + } else { + fsobj_error(a_eno, a_estr, + errno, + "Could not stat ", path); + res = (ARCHIVE_FAILED); + break; + } + } else if (S_ISDIR(st.st_mode)) { +#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) + fd = la_opendirat(chdir_fd, head); + if (fd < 0) + r = -1; + else { + r = 0; + close(chdir_fd); + chdir_fd = fd; + } +#else + r = chdir(head); +#endif + if (r != 0) { + tail[0] = c; + fsobj_error(a_eno, a_estr, + errno, + "Could not chdir ", path); + res = (ARCHIVE_FATAL); + break; + } + /* + * Our view is now from inside + * this dir: + */ + head = tail + 1; + } else { + tail[0] = c; + fsobj_error(a_eno, a_estr, 0, + "Cannot extract through " + "symlink ", path); + res = ARCHIVE_FAILED; + break; + } + } else { + tail[0] = c; + fsobj_error(a_eno, a_estr, 0, + "Cannot extract through symlink ", path); + res = ARCHIVE_FAILED; + break; + } + } + /* be sure to always maintain this */ + tail[0] = c; + if (tail[0] != '\0') + tail++; /* Advance to the next segment. */ + } + /* Catches loop exits via break */ + tail[0] = c; +#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) + /* If we operate with openat(), fstatat() and unlinkat() there was + * no chdir(), so just close the fd */ + if (chdir_fd >= 0) + close(chdir_fd); +#elif HAVE_FCHDIR + /* If we changed directory above, restore it here. */ + if (chdir_fd >= 0) { + r = fchdir(chdir_fd); + if (r != 0) { + fsobj_error(a_eno, a_estr, errno, + "chdir() failure", ""); + } + close(chdir_fd); + chdir_fd = -1; + if (r != 0) { + res = (ARCHIVE_FATAL); + } + } +#endif + /* TODO: reintroduce a safe cache here? */ + return res; +#endif +} + +/* + * Check a->name for symlinks, returning ARCHIVE_OK if its clean, otherwise + * calls archive_set_error and returns ARCHIVE_{FATAL,FAILED} + */ +static int +check_symlinks(struct archive_write_disk *a) +{ + struct archive_string error_string; + int error_number; + int rc; + archive_string_init(&error_string); + rc = check_symlinks_fsobj(a->name, &error_number, &error_string, + a->flags); + if (rc != ARCHIVE_OK) { + archive_set_error(&a->archive, error_number, "%s", + error_string.s); + } + archive_string_free(&error_string); + a->pst = NULL; /* to be safe */ + return rc; +} + + +#if defined(__CYGWIN__) +/* + * 1. Convert a path separator from '\' to '/' . + * We shouldn't check multibyte character directly because some + * character-set have been using the '\' character for a part of + * its multibyte character code. + * 2. Replace unusable characters in Windows with underscore('_'). + * See also : http://msdn.microsoft.com/en-us/library/aa365247.aspx + */ +static void +cleanup_pathname_win(char *path) +{ + wchar_t wc; + char *p; + size_t alen, l; + int mb, complete, utf8; + + alen = 0; + mb = 0; + complete = 1; + utf8 = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)? 1: 0; + for (p = path; *p != '\0'; p++) { + ++alen; + if (*p == '\\') { + /* If previous byte is smaller than 128, + * this is not second byte of multibyte characters, + * so we can replace '\' with '/'. */ + if (utf8 || !mb) + *p = '/'; + else + complete = 0;/* uncompleted. */ + } else if (*(unsigned char *)p > 127) + mb = 1; + else + mb = 0; + /* Rewrite the path name if its next character is unusable. */ + if (*p == ':' || *p == '*' || *p == '?' || *p == '"' || + *p == '<' || *p == '>' || *p == '|') + *p = '_'; + } + if (complete) + return; + + /* + * Convert path separator in wide-character. + */ + p = path; + while (*p != '\0' && alen) { + l = mbtowc(&wc, p, alen); + if (l == (size_t)-1) { + while (*p != '\0') { + if (*p == '\\') + *p = '/'; + ++p; + } + break; + } + if (l == 1 && wc == L'\\') + *p = '/'; + p += l; + alen -= l; + } +} +#endif + +/* + * Canonicalize the pathname. In particular, this strips duplicate + * '/' characters, '.' elements, and trailing '/'. It also raises an + * error for an empty path, a trailing '..', (if _SECURE_NODOTDOT is + * set) any '..' in the path or (if ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS + * is set) if the path is absolute. + */ +static int +cleanup_pathname_fsobj(char *path, int *a_eno, struct archive_string *a_estr, + int flags) +{ + char *dest, *src; + char separator = '\0'; + + dest = src = path; + if (*src == '\0') { + fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC, + "Invalid empty ", "pathname"); + return (ARCHIVE_FAILED); + } + +#if defined(__CYGWIN__) + cleanup_pathname_win(path); +#endif + /* Skip leading '/'. */ + if (*src == '/') { + if (flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) { + fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC, + "Path is ", "absolute"); + return (ARCHIVE_FAILED); + } + + separator = *src++; + } + + /* Scan the pathname one element at a time. */ + for (;;) { + /* src points to first char after '/' */ + if (src[0] == '\0') { + break; + } else if (src[0] == '/') { + /* Found '//', ignore second one. */ + src++; + continue; + } else if (src[0] == '.') { + if (src[1] == '\0') { + /* Ignore trailing '.' */ + break; + } else if (src[1] == '/') { + /* Skip './'. */ + src += 2; + continue; + } else if (src[1] == '.') { + if (src[2] == '/' || src[2] == '\0') { + /* Conditionally warn about '..' */ + if (flags + & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { + fsobj_error(a_eno, a_estr, + ARCHIVE_ERRNO_MISC, + "Path contains ", "'..'"); + return (ARCHIVE_FAILED); + } + } + /* + * Note: Under no circumstances do we + * remove '..' elements. In + * particular, restoring + * '/foo/../bar/' should create the + * 'foo' dir as a side-effect. + */ + } + } + + /* Copy current element, including leading '/'. */ + if (separator) + *dest++ = '/'; + while (*src != '\0' && *src != '/') { + *dest++ = *src++; + } + + if (*src == '\0') + break; + + /* Skip '/' separator. */ + separator = *src++; + } + /* + * We've just copied zero or more path elements, not including the + * final '/'. + */ + if (dest == path) { + /* + * Nothing got copied. The path must have been something + * like '.' or '/' or './' or '/././././/./'. + */ + if (separator) + *dest++ = '/'; + else + *dest++ = '.'; + } + /* Terminate the result. */ + *dest = '\0'; + return (ARCHIVE_OK); +} + +static int +cleanup_pathname(struct archive_write_disk *a) +{ + struct archive_string error_string; + int error_number; + int rc; + archive_string_init(&error_string); + rc = cleanup_pathname_fsobj(a->name, &error_number, &error_string, + a->flags); + if (rc != ARCHIVE_OK) { + archive_set_error(&a->archive, error_number, "%s", + error_string.s); + } + archive_string_free(&error_string); + return rc; +} + +/* + * Create the parent directory of the specified path, assuming path + * is already in mutable storage. + */ +static int +create_parent_dir(struct archive_write_disk *a, char *path) +{ + char *slash; + int r; + + /* Remove tail element to obtain parent name. */ + slash = strrchr(path, '/'); + if (slash == NULL) + return (ARCHIVE_OK); + *slash = '\0'; + r = create_dir(a, path); + *slash = '/'; + return (r); +} + +/* + * Create the specified dir, recursing to create parents as necessary. + * + * Returns ARCHIVE_OK if the path exists when we're done here. + * Otherwise, returns ARCHIVE_FAILED. + * Assumes path is in mutable storage; path is unchanged on exit. + */ +static int +create_dir(struct archive_write_disk *a, char *path) +{ + struct stat st; + struct fixup_entry *le; + char *slash, *base; + mode_t mode_final, mode; + int r; + + /* Check for special names and just skip them. */ + slash = strrchr(path, '/'); + if (slash == NULL) + base = path; + else + base = slash + 1; + + if (base[0] == '\0' || + (base[0] == '.' && base[1] == '\0') || + (base[0] == '.' && base[1] == '.' && base[2] == '\0')) { + /* Don't bother trying to create null path, '.', or '..'. */ + if (slash != NULL) { + *slash = '\0'; + r = create_dir(a, path); + *slash = '/'; + return (r); + } + return (ARCHIVE_OK); + } + + /* + * Yes, this should be stat() and not lstat(). Using lstat() + * here loses the ability to extract through symlinks. Also note + * that this should not use the a->st cache. + */ + if (la_stat(path, &st) == 0) { + if (S_ISDIR(st.st_mode)) + return (ARCHIVE_OK); + if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) { + archive_set_error(&a->archive, EEXIST, + "Can't create directory '%s'", path); + return (ARCHIVE_FAILED); + } + if (unlink(path) != 0) { + archive_set_error(&a->archive, errno, + "Can't create directory '%s': " + "Conflicting file cannot be removed", + path); + return (ARCHIVE_FAILED); + } + } else if (errno != ENOENT && errno != ENOTDIR) { + /* Stat failed? */ + archive_set_error(&a->archive, errno, + "Can't test directory '%s'", path); + return (ARCHIVE_FAILED); + } else if (slash != NULL) { + *slash = '\0'; + r = create_dir(a, path); + *slash = '/'; + if (r != ARCHIVE_OK) + return (r); + } + + /* + * Mode we want for the final restored directory. Per POSIX, + * implicitly-created dirs must be created obeying the umask. + * There's no mention whether this is different for privileged + * restores (which the rest of this code handles by pretending + * umask=0). I've chosen here to always obey the user's umask for + * implicit dirs, even if _EXTRACT_PERM was specified. + */ + mode_final = DEFAULT_DIR_MODE & ~a->user_umask; + /* Mode we want on disk during the restore process. */ + mode = mode_final; + mode |= MINIMUM_DIR_MODE; + mode &= MAXIMUM_DIR_MODE; + if (mkdir(path, mode) == 0) { + if (mode != mode_final) { + le = new_fixup(a, path); + if (le == NULL) + return (ARCHIVE_FATAL); + le->fixup |=TODO_MODE_BASE; + le->mode = mode_final; + } + return (ARCHIVE_OK); + } + + /* + * Without the following check, a/b/../b/c/d fails at the + * second visit to 'b', so 'd' can't be created. Note that we + * don't add it to the fixup list here, as it's already been + * added. + */ + if (la_stat(path, &st) == 0 && S_ISDIR(st.st_mode)) + return (ARCHIVE_OK); + + archive_set_error(&a->archive, errno, "Failed to create dir '%s'", + path); + return (ARCHIVE_FAILED); +} + +/* + * Note: Although we can skip setting the user id if the desired user + * id matches the current user, we cannot skip setting the group, as + * many systems set the gid based on the containing directory. So + * we have to perform a chown syscall if we want to set the SGID + * bit. (The alternative is to stat() and then possibly chown(); it's + * more efficient to skip the stat() and just always chown().) Note + * that a successful chown() here clears the TODO_SGID_CHECK bit, which + * allows set_mode to skip the stat() check for the GID. + */ +static int +set_ownership(struct archive_write_disk *a) +{ +#if !defined(__CYGWIN__) && !defined(__linux__) +/* + * On Linux, a process may have the CAP_CHOWN capability. + * On Windows there is no 'root' user with uid 0. + * Elsewhere we can skip calling chown if we are not root and the desired + * user id does not match the current user. + */ + if (a->user_uid != 0 && a->user_uid != a->uid) { + archive_set_error(&a->archive, errno, + "Can't set UID=%jd", (intmax_t)a->uid); + return (ARCHIVE_WARN); + } +#endif + +#ifdef HAVE_FCHOWN + /* If we have an fd, we can avoid a race. */ + if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) { + /* We've set owner and know uid/gid are correct. */ + a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK); + return (ARCHIVE_OK); + } +#endif + + /* We prefer lchown() but will use chown() if that's all we have. */ + /* Of course, if we have neither, this will always fail. */ +#ifdef HAVE_LCHOWN + if (lchown(a->name, a->uid, a->gid) == 0) { + /* We've set owner and know uid/gid are correct. */ + a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK); + return (ARCHIVE_OK); + } +#elif HAVE_CHOWN + if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) { + /* We've set owner and know uid/gid are correct. */ + a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK); + return (ARCHIVE_OK); + } +#endif + + archive_set_error(&a->archive, errno, + "Can't set user=%jd/group=%jd for %s", + (intmax_t)a->uid, (intmax_t)a->gid, a->name); + return (ARCHIVE_WARN); +} + +/* + * Note: Returns 0 on success, non-zero on failure. + */ +static int +set_time(int fd, int mode, const char *name, + time_t atime, long atime_nsec, + time_t mtime, long mtime_nsec) +{ + /* Select the best implementation for this platform. */ +#if defined(HAVE_UTIMENSAT) && defined(HAVE_FUTIMENS) + /* + * utimensat() and futimens() are defined in + * POSIX.1-2008. They support ns resolution and setting times + * on fds and symlinks. + */ + struct timespec ts[2]; + (void)mode; /* UNUSED */ + ts[0].tv_sec = atime; + ts[0].tv_nsec = atime_nsec; + ts[1].tv_sec = mtime; + ts[1].tv_nsec = mtime_nsec; + if (fd >= 0) + return futimens(fd, ts); + return utimensat(AT_FDCWD, name, ts, AT_SYMLINK_NOFOLLOW); + +#elif HAVE_UTIMES + /* + * The utimes()-family functions support µs-resolution and + * setting times fds and symlinks. utimes() is documented as + * LEGACY by POSIX, futimes() and lutimes() are not described + * in POSIX. + */ + struct timeval times[2]; + + times[0].tv_sec = atime; + times[0].tv_usec = atime_nsec / 1000; + times[1].tv_sec = mtime; + times[1].tv_usec = mtime_nsec / 1000; + +#ifdef HAVE_FUTIMES + if (fd >= 0) + return (futimes(fd, times)); +#else + (void)fd; /* UNUSED */ +#endif +#ifdef HAVE_LUTIMES + (void)mode; /* UNUSED */ + return (lutimes(name, times)); +#else + if (S_ISLNK(mode)) + return (0); + return (utimes(name, times)); +#endif + +#elif defined(HAVE_UTIME) + /* + * utime() is POSIX-standard but only supports 1s resolution and + * does not support fds or symlinks. + */ + struct utimbuf times; + (void)fd; /* UNUSED */ + (void)name; /* UNUSED */ + (void)atime_nsec; /* UNUSED */ + (void)mtime_nsec; /* UNUSED */ + times.actime = atime; + times.modtime = mtime; + if (S_ISLNK(mode)) + return (ARCHIVE_OK); + return (utime(name, ×)); + +#else + /* + * We don't know how to set the time on this platform. + */ + (void)fd; /* UNUSED */ + (void)mode; /* UNUSED */ + (void)name; /* UNUSED */ + (void)atime_nsec; /* UNUSED */ + (void)mtime_nsec; /* UNUSED */ + return (ARCHIVE_WARN); +#endif +} + +#ifdef F_SETTIMES +static int +set_time_tru64(int fd, int mode, const char *name, + time_t atime, long atime_nsec, + time_t mtime, long mtime_nsec, + time_t ctime, long ctime_nsec) +{ + struct attr_timbuf tstamp; + tstamp.atime.tv_sec = atime; + tstamp.mtime.tv_sec = mtime; + tstamp.ctime.tv_sec = ctime; +#if defined (__hpux) && defined (__ia64) + tstamp.atime.tv_nsec = atime_nsec; + tstamp.mtime.tv_nsec = mtime_nsec; + tstamp.ctime.tv_nsec = ctime_nsec; +#else + tstamp.atime.tv_usec = atime_nsec / 1000; + tstamp.mtime.tv_usec = mtime_nsec / 1000; + tstamp.ctime.tv_usec = ctime_nsec / 1000; +#endif + return (fcntl(fd,F_SETTIMES,&tstamp)); +} +#endif /* F_SETTIMES */ + +static int +set_times(struct archive_write_disk *a, + int fd, int mode, const char *name, + time_t atime, long atime_nanos, + time_t birthtime, long birthtime_nanos, + time_t mtime, long mtime_nanos, + time_t cctime, long ctime_nanos) +{ + /* Note: set_time doesn't use libarchive return conventions! + * It uses syscall conventions. So 0 here instead of ARCHIVE_OK. */ + int r1 = 0, r2 = 0; + +#ifdef F_SETTIMES + /* + * on Tru64 try own fcntl first which can restore even the + * ctime, fall back to default code path below if it fails + * or if we are not running as root + */ + if (a->user_uid == 0 && + set_time_tru64(fd, mode, name, + atime, atime_nanos, mtime, + mtime_nanos, cctime, ctime_nanos) == 0) { + return (ARCHIVE_OK); + } +#else /* Tru64 */ + (void)cctime; /* UNUSED */ + (void)ctime_nanos; /* UNUSED */ +#endif /* Tru64 */ + +#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME + /* + * If you have struct stat.st_birthtime, we assume BSD + * birthtime semantics, in which {f,l,}utimes() updates + * birthtime to earliest mtime. So we set the time twice, + * first using the birthtime, then using the mtime. If + * birthtime == mtime, this isn't necessary, so we skip it. + * If birthtime > mtime, then this won't work, so we skip it. + */ + if (birthtime < mtime + || (birthtime == mtime && birthtime_nanos < mtime_nanos)) + r1 = set_time(fd, mode, name, + atime, atime_nanos, + birthtime, birthtime_nanos); +#else + (void)birthtime; /* UNUSED */ + (void)birthtime_nanos; /* UNUSED */ +#endif + r2 = set_time(fd, mode, name, + atime, atime_nanos, + mtime, mtime_nanos); + if (r1 != 0 || r2 != 0) { + archive_set_error(&a->archive, errno, + "Can't restore time"); + return (ARCHIVE_WARN); + } + return (ARCHIVE_OK); +} + +static int +set_times_from_entry(struct archive_write_disk *a) +{ + time_t atime, birthtime, mtime, cctime; + long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec; + + /* Suitable defaults. */ + atime = birthtime = mtime = cctime = a->start_time; + atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0; + + /* If no time was provided, we're done. */ + if (!archive_entry_atime_is_set(a->entry) +#if HAVE_STRUCT_STAT_ST_BIRTHTIME + && !archive_entry_birthtime_is_set(a->entry) +#endif + && !archive_entry_mtime_is_set(a->entry)) + return (ARCHIVE_OK); + + if (archive_entry_atime_is_set(a->entry)) { + atime = archive_entry_atime(a->entry); + atime_nsec = archive_entry_atime_nsec(a->entry); + } + if (archive_entry_birthtime_is_set(a->entry)) { + birthtime = archive_entry_birthtime(a->entry); + birthtime_nsec = archive_entry_birthtime_nsec(a->entry); + } + if (archive_entry_mtime_is_set(a->entry)) { + mtime = archive_entry_mtime(a->entry); + mtime_nsec = archive_entry_mtime_nsec(a->entry); + } + if (archive_entry_ctime_is_set(a->entry)) { + cctime = archive_entry_ctime(a->entry); + ctime_nsec = archive_entry_ctime_nsec(a->entry); + } + + return set_times(a, a->fd, a->mode, a->name, + atime, atime_nsec, + birthtime, birthtime_nsec, + mtime, mtime_nsec, + cctime, ctime_nsec); +} + +static int +set_mode(struct archive_write_disk *a, int mode) +{ + int r = ARCHIVE_OK; + int r2; + mode &= 07777; /* Strip off file type bits. */ + + if (a->todo & TODO_SGID_CHECK) { + /* + * If we don't know the GID is right, we must stat() + * to verify it. We can't just check the GID of this + * process, since systems sometimes set GID from + * the enclosing dir or based on ACLs. + */ + if ((r = lazy_stat(a)) != ARCHIVE_OK) + return (r); + if (a->pst->st_gid != a->gid) { + mode &= ~ S_ISGID; + if (a->flags & ARCHIVE_EXTRACT_OWNER) { + /* + * This is only an error if you + * requested owner restore. If you + * didn't, we'll try to restore + * sgid/suid, but won't consider it a + * problem if we can't. + */ + archive_set_error(&a->archive, -1, + "Can't restore SGID bit"); + r = ARCHIVE_WARN; + } + } + /* While we're here, double-check the UID. */ + if (a->pst->st_uid != a->uid + && (a->todo & TODO_SUID)) { + mode &= ~ S_ISUID; + if (a->flags & ARCHIVE_EXTRACT_OWNER) { + archive_set_error(&a->archive, -1, + "Can't restore SUID bit"); + r = ARCHIVE_WARN; + } + } + a->todo &= ~TODO_SGID_CHECK; + a->todo &= ~TODO_SUID_CHECK; + } else if (a->todo & TODO_SUID_CHECK) { + /* + * If we don't know the UID is right, we can just check + * the user, since all systems set the file UID from + * the process UID. + */ + if (a->user_uid != a->uid) { + mode &= ~ S_ISUID; + if (a->flags & ARCHIVE_EXTRACT_OWNER) { + archive_set_error(&a->archive, -1, + "Can't make file SUID"); + r = ARCHIVE_WARN; + } + } + a->todo &= ~TODO_SUID_CHECK; + } + + if (S_ISLNK(a->mode)) { +#ifdef HAVE_LCHMOD + /* + * If this is a symlink, use lchmod(). If the + * platform doesn't support lchmod(), just skip it. A + * platform that doesn't provide a way to set + * permissions on symlinks probably ignores + * permissions on symlinks, so a failure here has no + * impact. + */ + if (lchmod(a->name, mode) != 0) { + switch (errno) { + case ENOTSUP: + case ENOSYS: +#if ENOTSUP != EOPNOTSUPP + case EOPNOTSUPP: +#endif + /* + * if lchmod is defined but the platform + * doesn't support it, silently ignore + * error + */ + break; + default: + archive_set_error(&a->archive, errno, + "Can't set permissions to 0%o", (int)mode); + r = ARCHIVE_WARN; + } + } +#endif + } else if (!S_ISDIR(a->mode)) { + /* + * If it's not a symlink and not a dir, then use + * fchmod() or chmod(), depending on whether we have + * an fd. Dirs get their perms set during the + * post-extract fixup, which is handled elsewhere. + */ +#ifdef HAVE_FCHMOD + if (a->fd >= 0) + r2 = fchmod(a->fd, mode); + else +#endif + /* If this platform lacks fchmod(), then + * we'll just use chmod(). */ + r2 = chmod(a->name, mode); + + if (r2 != 0) { + archive_set_error(&a->archive, errno, + "Can't set permissions to 0%o", (int)mode); + r = ARCHIVE_WARN; + } + } + return (r); +} + +static int +set_fflags(struct archive_write_disk *a) +{ + struct fixup_entry *le; + unsigned long set, clear; + int r; + mode_t mode = archive_entry_mode(a->entry); + /* + * Make 'critical_flags' hold all file flags that can't be + * immediately restored. For example, on BSD systems, + * SF_IMMUTABLE prevents hardlinks from being created, so + * should not be set until after any hardlinks are created. To + * preserve some semblance of portability, this uses #ifdef + * extensively. Ugly, but it works. + * + * Yes, Virginia, this does create a security race. It's mitigated + * somewhat by the practice of creating dirs 0700 until the extract + * is done, but it would be nice if we could do more than that. + * People restoring critical file systems should be wary of + * other programs that might try to muck with files as they're + * being restored. + */ + const int critical_flags = 0 +#ifdef SF_IMMUTABLE + | SF_IMMUTABLE +#endif +#ifdef UF_IMMUTABLE + | UF_IMMUTABLE +#endif +#ifdef SF_APPEND + | SF_APPEND +#endif +#ifdef UF_APPEND + | UF_APPEND +#endif +#if defined(FS_APPEND_FL) + | FS_APPEND_FL +#elif defined(EXT2_APPEND_FL) + | EXT2_APPEND_FL +#endif +#if defined(FS_IMMUTABLE_FL) + | FS_IMMUTABLE_FL +#elif defined(EXT2_IMMUTABLE_FL) + | EXT2_IMMUTABLE_FL +#endif +#ifdef FS_JOURNAL_DATA_FL + | FS_JOURNAL_DATA_FL +#endif + ; + + if (a->todo & TODO_FFLAGS) { + archive_entry_fflags(a->entry, &set, &clear); + + /* + * The first test encourages the compiler to eliminate + * all of this if it's not necessary. + */ + if ((critical_flags != 0) && (set & critical_flags)) { + le = current_fixup(a, a->name); + if (le == NULL) + return (ARCHIVE_FATAL); + le->fixup |= TODO_FFLAGS; + le->fflags_set = set; + /* Store the mode if it's not already there. */ + if ((le->fixup & TODO_MODE) == 0) + le->mode = mode; + } else { + r = set_fflags_platform(a, a->fd, + a->name, mode, set, clear); + if (r != ARCHIVE_OK) + return (r); + } + } + return (ARCHIVE_OK); +} + +static int +clear_nochange_fflags(struct archive_write_disk *a) +{ + mode_t mode = archive_entry_mode(a->entry); + const int nochange_flags = 0 +#ifdef SF_IMMUTABLE + | SF_IMMUTABLE +#endif +#ifdef UF_IMMUTABLE + | UF_IMMUTABLE +#endif +#ifdef SF_APPEND + | SF_APPEND +#endif +#ifdef UF_APPEND + | UF_APPEND +#endif +#ifdef EXT2_APPEND_FL + | EXT2_APPEND_FL +#endif +#ifdef EXT2_IMMUTABLE_FL + | EXT2_IMMUTABLE_FL +#endif + ; + + return (set_fflags_platform(a, a->fd, a->name, mode, 0, + nochange_flags)); +} + + +#if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS) +/* + * BSD reads flags using stat() and sets them with one of {f,l,}chflags() + */ +static int +set_fflags_platform(struct archive_write_disk *a, int fd, const char *name, + mode_t mode, unsigned long set, unsigned long clear) +{ + int r; + const int sf_mask = 0 +#ifdef SF_APPEND + | SF_APPEND +#endif +#ifdef SF_ARCHIVED + | SF_ARCHIVED +#endif +#ifdef SF_IMMUTABLE + | SF_IMMUTABLE +#endif +#ifdef SF_NOUNLINK + | SF_NOUNLINK +#endif + ; + (void)mode; /* UNUSED */ + + if (set == 0 && clear == 0) + return (ARCHIVE_OK); + + /* + * XXX Is the stat here really necessary? Or can I just use + * the 'set' flags directly? In particular, I'm not sure + * about the correct approach if we're overwriting an existing + * file that already has flags on it. XXX + */ + if ((r = lazy_stat(a)) != ARCHIVE_OK) + return (r); + + a->st.st_flags &= ~clear; + a->st.st_flags |= set; + + /* Only super-user may change SF_* flags */ + + if (a->user_uid != 0) + a->st.st_flags &= ~sf_mask; + +#ifdef HAVE_FCHFLAGS + /* If platform has fchflags() and we were given an fd, use it. */ + if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0) + return (ARCHIVE_OK); +#endif + /* + * If we can't use the fd to set the flags, we'll use the + * pathname to set flags. We prefer lchflags() but will use + * chflags() if we must. + */ +#ifdef HAVE_LCHFLAGS + if (lchflags(name, a->st.st_flags) == 0) + return (ARCHIVE_OK); +#elif defined(HAVE_CHFLAGS) + if (S_ISLNK(a->st.st_mode)) { + archive_set_error(&a->archive, errno, + "Can't set file flags on symlink."); + return (ARCHIVE_WARN); + } + if (chflags(name, a->st.st_flags) == 0) + return (ARCHIVE_OK); +#endif + archive_set_error(&a->archive, errno, + "Failed to set file flags"); + return (ARCHIVE_WARN); +} + +#elif (defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS) && \ + defined(HAVE_WORKING_FS_IOC_GETFLAGS)) || \ + (defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS) && \ + defined(HAVE_WORKING_EXT2_IOC_GETFLAGS)) +/* + * Linux uses ioctl() to read and write file flags. + */ +static int +set_fflags_platform(struct archive_write_disk *a, int fd, const char *name, + mode_t mode, unsigned long set, unsigned long clear) +{ + int ret; + int myfd = fd; + int newflags, oldflags; + /* + * Linux has no define for the flags that are only settable by + * the root user. This code may seem a little complex, but + * there seem to be some Linux systems that lack these + * defines. (?) The code below degrades reasonably gracefully + * if sf_mask is incomplete. + */ + const int sf_mask = 0 +#if defined(FS_IMMUTABLE_FL) + | FS_IMMUTABLE_FL +#elif defined(EXT2_IMMUTABLE_FL) + | EXT2_IMMUTABLE_FL +#endif +#if defined(FS_APPEND_FL) + | FS_APPEND_FL +#elif defined(EXT2_APPEND_FL) + | EXT2_APPEND_FL +#endif +#if defined(FS_JOURNAL_DATA_FL) + | FS_JOURNAL_DATA_FL +#endif + ; + + if (set == 0 && clear == 0) + return (ARCHIVE_OK); + /* Only regular files and dirs can have flags. */ + if (!S_ISREG(mode) && !S_ISDIR(mode)) + return (ARCHIVE_OK); + + /* If we weren't given an fd, open it ourselves. */ + if (myfd < 0) { + myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY | O_CLOEXEC); + __archive_ensure_cloexec_flag(myfd); + } + if (myfd < 0) + return (ARCHIVE_OK); + + /* + * XXX As above, this would be way simpler if we didn't have + * to read the current flags from disk. XXX + */ + ret = ARCHIVE_OK; + + /* Read the current file flags. */ + if (ioctl(myfd, +#ifdef FS_IOC_GETFLAGS + FS_IOC_GETFLAGS, +#else + EXT2_IOC_GETFLAGS, +#endif + &oldflags) < 0) + goto fail; + + /* Try setting the flags as given. */ + newflags = (oldflags & ~clear) | set; + if (ioctl(myfd, +#ifdef FS_IOC_SETFLAGS + FS_IOC_SETFLAGS, +#else + EXT2_IOC_SETFLAGS, +#endif + &newflags) >= 0) + goto cleanup; + if (errno != EPERM) + goto fail; + + /* If we couldn't set all the flags, try again with a subset. */ + newflags &= ~sf_mask; + oldflags &= sf_mask; + newflags |= oldflags; + if (ioctl(myfd, +#ifdef FS_IOC_SETFLAGS + FS_IOC_SETFLAGS, +#else + EXT2_IOC_SETFLAGS, +#endif + &newflags) >= 0) + goto cleanup; + + /* We couldn't set the flags, so report the failure. */ +fail: + archive_set_error(&a->archive, errno, + "Failed to set file flags"); + ret = ARCHIVE_WARN; +cleanup: + if (fd < 0) + close(myfd); + return (ret); +} + +#else + +/* + * Of course, some systems have neither BSD chflags() nor Linux' flags + * support through ioctl(). + */ +static int +set_fflags_platform(struct archive_write_disk *a, int fd, const char *name, + mode_t mode, unsigned long set, unsigned long clear) +{ + (void)a; /* UNUSED */ + (void)fd; /* UNUSED */ + (void)name; /* UNUSED */ + (void)mode; /* UNUSED */ + (void)set; /* UNUSED */ + (void)clear; /* UNUSED */ + return (ARCHIVE_OK); +} + +#endif /* __linux */ + +#ifndef HAVE_COPYFILE_H +/* Default is to simply drop Mac extended metadata. */ +static int +set_mac_metadata(struct archive_write_disk *a, const char *pathname, + const void *metadata, size_t metadata_size) +{ + (void)a; /* UNUSED */ + (void)pathname; /* UNUSED */ + (void)metadata; /* UNUSED */ + (void)metadata_size; /* UNUSED */ + return (ARCHIVE_OK); +} + +static int +fixup_appledouble(struct archive_write_disk *a, const char *pathname) +{ + (void)a; /* UNUSED */ + (void)pathname; /* UNUSED */ + return (ARCHIVE_OK); +} +#else + +/* + * On Mac OS, we use copyfile() to unpack the metadata and + * apply it to the target file. + */ + +#if defined(HAVE_SYS_XATTR_H) +static int +copy_xattrs(struct archive_write_disk *a, int tmpfd, int dffd) +{ + ssize_t xattr_size; + char *xattr_names = NULL, *xattr_val = NULL; + int ret = ARCHIVE_OK, xattr_i; + + xattr_size = flistxattr(tmpfd, NULL, 0, 0); + if (xattr_size == -1) { + archive_set_error(&a->archive, errno, + "Failed to read metadata(xattr)"); + ret = ARCHIVE_WARN; + goto exit_xattr; + } + xattr_names = malloc(xattr_size); + if (xattr_names == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for metadata(xattr)"); + ret = ARCHIVE_FATAL; + goto exit_xattr; + } + xattr_size = flistxattr(tmpfd, xattr_names, xattr_size, 0); + if (xattr_size == -1) { + archive_set_error(&a->archive, errno, + "Failed to read metadata(xattr)"); + ret = ARCHIVE_WARN; + goto exit_xattr; + } + for (xattr_i = 0; xattr_i < xattr_size; + xattr_i += strlen(xattr_names + xattr_i) + 1) { + char *xattr_val_saved; + ssize_t s; + int f; + + s = fgetxattr(tmpfd, xattr_names + xattr_i, NULL, 0, 0, 0); + if (s == -1) { + archive_set_error(&a->archive, errno, + "Failed to get metadata(xattr)"); + ret = ARCHIVE_WARN; + goto exit_xattr; + } + xattr_val_saved = xattr_val; + xattr_val = realloc(xattr_val, s); + if (xattr_val == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Failed to get metadata(xattr)"); + ret = ARCHIVE_WARN; + free(xattr_val_saved); + goto exit_xattr; + } + s = fgetxattr(tmpfd, xattr_names + xattr_i, xattr_val, s, 0, 0); + if (s == -1) { + archive_set_error(&a->archive, errno, + "Failed to get metadata(xattr)"); + ret = ARCHIVE_WARN; + goto exit_xattr; + } + f = fsetxattr(dffd, xattr_names + xattr_i, xattr_val, s, 0, 0); + if (f == -1) { + archive_set_error(&a->archive, errno, + "Failed to get metadata(xattr)"); + ret = ARCHIVE_WARN; + goto exit_xattr; + } + } +exit_xattr: + free(xattr_names); + free(xattr_val); + return (ret); +} +#endif + +static int +copy_acls(struct archive_write_disk *a, int tmpfd, int dffd) +{ +#ifndef HAVE_SYS_ACL_H + return 0; +#else + acl_t acl, dfacl = NULL; + int acl_r, ret = ARCHIVE_OK; + + acl = acl_get_fd(tmpfd); + if (acl == NULL) { + if (errno == ENOENT) + /* There are not any ACLs. */ + return (ret); + archive_set_error(&a->archive, errno, + "Failed to get metadata(acl)"); + ret = ARCHIVE_WARN; + goto exit_acl; + } + dfacl = acl_dup(acl); + acl_r = acl_set_fd(dffd, dfacl); + if (acl_r == -1) { + archive_set_error(&a->archive, errno, + "Failed to get metadata(acl)"); + ret = ARCHIVE_WARN; + goto exit_acl; + } +exit_acl: + if (acl) + acl_free(acl); + if (dfacl) + acl_free(dfacl); + return (ret); +#endif +} + +static int +create_tempdatafork(struct archive_write_disk *a, const char *pathname) +{ + struct archive_string tmpdatafork; + int tmpfd; + + archive_string_init(&tmpdatafork); + archive_strcpy(&tmpdatafork, "tar.md.XXXXXX"); + tmpfd = mkstemp(tmpdatafork.s); + if (tmpfd < 0) { + archive_set_error(&a->archive, errno, + "Failed to mkstemp"); + archive_string_free(&tmpdatafork); + return (-1); + } + if (copyfile(pathname, tmpdatafork.s, 0, + COPYFILE_UNPACK | COPYFILE_NOFOLLOW + | COPYFILE_ACL | COPYFILE_XATTR) < 0) { + archive_set_error(&a->archive, errno, + "Failed to restore metadata"); + close(tmpfd); + tmpfd = -1; + } + unlink(tmpdatafork.s); + archive_string_free(&tmpdatafork); + return (tmpfd); +} + +static int +copy_metadata(struct archive_write_disk *a, const char *metadata, + const char *datafork, int datafork_compressed) +{ + int ret = ARCHIVE_OK; + + if (datafork_compressed) { + int dffd, tmpfd; + + tmpfd = create_tempdatafork(a, metadata); + if (tmpfd == -1) + return (ARCHIVE_WARN); + + /* + * Do not open the data fork compressed by HFS+ compression + * with at least a writing mode(O_RDWR or O_WRONLY). it + * makes the data fork uncompressed. + */ + dffd = open(datafork, 0); + if (dffd == -1) { + archive_set_error(&a->archive, errno, + "Failed to open the data fork for metadata"); + close(tmpfd); + return (ARCHIVE_WARN); + } + +#if defined(HAVE_SYS_XATTR_H) + ret = copy_xattrs(a, tmpfd, dffd); + if (ret == ARCHIVE_OK) +#endif + ret = copy_acls(a, tmpfd, dffd); + close(tmpfd); + close(dffd); + } else { + if (copyfile(metadata, datafork, 0, + COPYFILE_UNPACK | COPYFILE_NOFOLLOW + | COPYFILE_ACL | COPYFILE_XATTR) < 0) { + archive_set_error(&a->archive, errno, + "Failed to restore metadata"); + ret = ARCHIVE_WARN; + } + } + return (ret); +} + +static int +set_mac_metadata(struct archive_write_disk *a, const char *pathname, + const void *metadata, size_t metadata_size) +{ + struct archive_string tmp; + ssize_t written; + int fd; + int ret = ARCHIVE_OK; + + /* This would be simpler if copyfile() could just accept the + * metadata as a block of memory; then we could sidestep this + * silly dance of writing the data to disk just so that + * copyfile() can read it back in again. */ + archive_string_init(&tmp); + archive_strcpy(&tmp, pathname); + archive_strcat(&tmp, ".XXXXXX"); + fd = mkstemp(tmp.s); + + if (fd < 0) { + archive_set_error(&a->archive, errno, + "Failed to restore metadata"); + archive_string_free(&tmp); + return (ARCHIVE_WARN); + } + written = write(fd, metadata, metadata_size); + close(fd); + if ((size_t)written != metadata_size) { + archive_set_error(&a->archive, errno, + "Failed to restore metadata"); + ret = ARCHIVE_WARN; + } else { + int compressed; + +#if defined(UF_COMPRESSED) + if ((a->todo & TODO_HFS_COMPRESSION) != 0 && + (ret = lazy_stat(a)) == ARCHIVE_OK) + compressed = a->st.st_flags & UF_COMPRESSED; + else +#endif + compressed = 0; + ret = copy_metadata(a, tmp.s, pathname, compressed); + } + unlink(tmp.s); + archive_string_free(&tmp); + return (ret); +} + +static int +fixup_appledouble(struct archive_write_disk *a, const char *pathname) +{ + char buff[8]; + struct stat st; + const char *p; + struct archive_string datafork; + int fd = -1, ret = ARCHIVE_OK; + + archive_string_init(&datafork); + /* Check if the current file name is a type of the resource + * fork file. */ + p = strrchr(pathname, '/'); + if (p == NULL) + p = pathname; + else + p++; + if (p[0] != '.' || p[1] != '_') + goto skip_appledouble; + + /* + * Check if the data fork file exists. + * + * TODO: Check if this write disk object has handled it. + */ + archive_strncpy(&datafork, pathname, p - pathname); + archive_strcat(&datafork, p + 2); + if (lstat(datafork.s, &st) == -1 || + (st.st_mode & AE_IFMT) != AE_IFREG) + goto skip_appledouble; + + /* + * Check if the file is in the AppleDouble form. + */ + fd = open(pathname, O_RDONLY | O_BINARY | O_CLOEXEC); + __archive_ensure_cloexec_flag(fd); + if (fd == -1) { + archive_set_error(&a->archive, errno, + "Failed to open a restoring file"); + ret = ARCHIVE_WARN; + goto skip_appledouble; + } + if (read(fd, buff, 8) == -1) { + archive_set_error(&a->archive, errno, + "Failed to read a restoring file"); + close(fd); + ret = ARCHIVE_WARN; + goto skip_appledouble; + } + close(fd); + /* Check AppleDouble Magic Code. */ + if (archive_be32dec(buff) != 0x00051607) + goto skip_appledouble; + /* Check AppleDouble Version. */ + if (archive_be32dec(buff+4) != 0x00020000) + goto skip_appledouble; + + ret = copy_metadata(a, pathname, datafork.s, +#if defined(UF_COMPRESSED) + st.st_flags & UF_COMPRESSED); +#else + 0); +#endif + if (ret == ARCHIVE_OK) { + unlink(pathname); + ret = ARCHIVE_EOF; + } +skip_appledouble: + archive_string_free(&datafork); + return (ret); +} +#endif + +#if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_AIX +/* + * Restore extended attributes - Linux, Darwin and AIX implementations: + * AIX' ea interface is syntaxwise identical to the Linux xattr interface. + */ +static int +set_xattrs(struct archive_write_disk *a) +{ + struct archive_entry *entry = a->entry; + struct archive_string errlist; + int ret = ARCHIVE_OK; + int i = archive_entry_xattr_reset(entry); + short fail = 0; + + archive_string_init(&errlist); + + while (i--) { + const char *name; + const void *value; + size_t size; + int e; + + archive_entry_xattr_next(entry, &name, &value, &size); + + if (name == NULL) + continue; +#if ARCHIVE_XATTR_LINUX + /* Linux: quietly skip POSIX.1e ACL extended attributes */ + if (strncmp(name, "system.", 7) == 0 && + (strcmp(name + 7, "posix_acl_access") == 0 || + strcmp(name + 7, "posix_acl_default") == 0)) + continue; + if (strncmp(name, "trusted.SGI_", 12) == 0 && + (strcmp(name + 12, "ACL_DEFAULT") == 0 || + strcmp(name + 12, "ACL_FILE") == 0)) + continue; + + /* Linux: xfsroot namespace is obsolete and unsupported */ + if (strncmp(name, "xfsroot.", 8) == 0) { + fail = 1; + archive_strcat(&errlist, name); + archive_strappend_char(&errlist, ' '); + continue; + } +#endif + + if (a->fd >= 0) { +#if ARCHIVE_XATTR_LINUX + e = fsetxattr(a->fd, name, value, size, 0); +#elif ARCHIVE_XATTR_DARWIN + e = fsetxattr(a->fd, name, value, size, 0, 0); +#elif ARCHIVE_XATTR_AIX + e = fsetea(a->fd, name, value, size, 0); +#endif + } else { +#if ARCHIVE_XATTR_LINUX + e = lsetxattr(archive_entry_pathname(entry), + name, value, size, 0); +#elif ARCHIVE_XATTR_DARWIN + e = setxattr(archive_entry_pathname(entry), + name, value, size, 0, XATTR_NOFOLLOW); +#elif ARCHIVE_XATTR_AIX + e = lsetea(archive_entry_pathname(entry), + name, value, size, 0); +#endif + } + if (e == -1) { + ret = ARCHIVE_WARN; + archive_strcat(&errlist, name); + archive_strappend_char(&errlist, ' '); + if (errno != ENOTSUP && errno != ENOSYS) + fail = 1; + } + } + + if (ret == ARCHIVE_WARN) { + if (fail && errlist.length > 0) { + errlist.length--; + errlist.s[errlist.length] = '\0'; + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Cannot restore extended attributes: %s", + errlist.s); + } else + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Cannot restore extended " + "attributes on this file system."); + } + + archive_string_free(&errlist); + return (ret); +} +#elif ARCHIVE_XATTR_FREEBSD +/* + * Restore extended attributes - FreeBSD implementation + */ +static int +set_xattrs(struct archive_write_disk *a) +{ + struct archive_entry *entry = a->entry; + struct archive_string errlist; + int ret = ARCHIVE_OK; + int i = archive_entry_xattr_reset(entry); + short fail = 0; + + archive_string_init(&errlist); + + while (i--) { + const char *name; + const void *value; + size_t size; + archive_entry_xattr_next(entry, &name, &value, &size); + if (name != NULL) { + int e; + int namespace; + + if (strncmp(name, "user.", 5) == 0) { + /* "user." attributes go to user namespace */ + name += 5; + namespace = EXTATTR_NAMESPACE_USER; + } else { + /* Other namespaces are unsupported */ + archive_strcat(&errlist, name); + archive_strappend_char(&errlist, ' '); + fail = 1; + ret = ARCHIVE_WARN; + continue; + } + + if (a->fd >= 0) { + e = extattr_set_fd(a->fd, namespace, name, + value, size); + } else { + e = extattr_set_link( + archive_entry_pathname(entry), namespace, + name, value, size); + } + if (e != (int)size) { + archive_strcat(&errlist, name); + archive_strappend_char(&errlist, ' '); + ret = ARCHIVE_WARN; + if (errno != ENOTSUP && errno != ENOSYS) + fail = 1; + } + } + } + + if (ret == ARCHIVE_WARN) { + if (fail && errlist.length > 0) { + errlist.length--; + errlist.s[errlist.length] = '\0'; + + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Cannot restore extended attributes: %s", + errlist.s); + } else + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Cannot restore extended " + "attributes on this file system."); + } + + archive_string_free(&errlist); + return (ret); +} +#else +/* + * Restore extended attributes - stub implementation for unsupported systems + */ +static int +set_xattrs(struct archive_write_disk *a) +{ + static int warning_done = 0; + + /* If there aren't any extended attributes, then it's okay not + * to extract them, otherwise, issue a single warning. */ + if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) { + warning_done = 1; + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Cannot restore extended attributes on this system"); + return (ARCHIVE_WARN); + } + /* Warning was already emitted; suppress further warnings. */ + return (ARCHIVE_OK); +} +#endif + +/* + * Test if file on disk is older than entry. + */ +static int +older(struct stat *st, struct archive_entry *entry) +{ + /* First, test the seconds and return if we have a definite answer. */ + /* Definitely older. */ + if (to_int64_time(st->st_mtime) < to_int64_time(archive_entry_mtime(entry))) + return (1); + /* Definitely younger. */ + if (to_int64_time(st->st_mtime) > to_int64_time(archive_entry_mtime(entry))) + return (0); + /* If this platform supports fractional seconds, try those. */ +#if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC + /* Definitely older. */ + if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry)) + return (1); +#elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC + /* Definitely older. */ + if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry)) + return (1); +#elif HAVE_STRUCT_STAT_ST_MTIME_N + /* older. */ + if (st->st_mtime_n < archive_entry_mtime_nsec(entry)) + return (1); +#elif HAVE_STRUCT_STAT_ST_UMTIME + /* older. */ + if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry)) + return (1); +#elif HAVE_STRUCT_STAT_ST_MTIME_USEC + /* older. */ + if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry)) + return (1); +#else + /* This system doesn't have high-res timestamps. */ +#endif + /* Same age or newer, so not older. */ + return (0); +} + +#ifndef ARCHIVE_ACL_SUPPORT +int +archive_write_disk_set_acls(struct archive *a, int fd, const char *name, + struct archive_acl *abstract_acl, __LA_MODE_T mode) +{ + (void)a; /* UNUSED */ + (void)fd; /* UNUSED */ + (void)name; /* UNUSED */ + (void)abstract_acl; /* UNUSED */ + (void)mode; /* UNUSED */ + return (ARCHIVE_OK); +} +#endif + +#endif /* !_WIN32 || __CYGWIN__ */ + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk_private.h new file mode 100644 index 0000000000..557d7e2bf3 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk_private.h @@ -0,0 +1,45 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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 + * in this position and unchanged. + * 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(S) ``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(S) 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. + * + * $FreeBSD: head/lib/libarchive/archive_write_disk_private.h 201086 2009-12-28 02:17:53Z kientzle $ + */ + +#ifndef ARCHIVE_WRITE_DISK_PRIVATE_H_INCLUDED +#define ARCHIVE_WRITE_DISK_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +#include "archive_platform_acl.h" +#include "archive_acl_private.h" +#include "archive_entry.h" + +struct archive_write_disk; + +int archive_write_disk_set_acls(struct archive *, int, const char *, + struct archive_acl *, __LA_MODE_T); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk_set_standard_lookup.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk_set_standard_lookup.c new file mode 100644 index 0000000000..5fccdb9dc6 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk_set_standard_lookup.c @@ -0,0 +1,263 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_disk_set_standard_lookup.c 201083 2009-12-28 02:09:57Z kientzle $"); + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_GRP_H +#include <grp.h> +#endif +#ifdef HAVE_PWD_H +#include <pwd.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_read_private.h" +#include "archive_write_disk_private.h" + +struct bucket { + char *name; + int hash; + id_t id; +}; + +static const size_t cache_size = 127; +static unsigned int hash(const char *); +static int64_t lookup_gid(void *, const char *uname, int64_t); +static int64_t lookup_uid(void *, const char *uname, int64_t); +static void cleanup(void *); + +/* + * Installs functions that use getpwnam()/getgrnam()---along with + * a simple cache to accelerate such lookups---into the archive_write_disk + * object. This is in a separate file because getpwnam()/getgrnam() + * can pull in a LOT of library code (including NIS/LDAP functions, which + * pull in DNS resolvers, etc). This can easily top 500kB, which makes + * it inappropriate for some space-constrained applications. + * + * Applications that are size-sensitive may want to just use the + * real default functions (defined in archive_write_disk.c) that just + * use the uid/gid without the lookup. Or define your own custom functions + * if you prefer. + * + * TODO: Replace these hash tables with simpler move-to-front LRU + * lists with a bounded size (128 items?). The hash is a bit faster, + * but has a bad pathology in which it thrashes a single bucket. Even + * walking a list of 128 items is a lot faster than calling + * getpwnam()! + */ +int +archive_write_disk_set_standard_lookup(struct archive *a) +{ + struct bucket *ucache = calloc(cache_size, sizeof(struct bucket)); + struct bucket *gcache = calloc(cache_size, sizeof(struct bucket)); + if (ucache == NULL || gcache == NULL) { + free(ucache); + free(gcache); + return (ARCHIVE_FATAL); + } + archive_write_disk_set_group_lookup(a, gcache, lookup_gid, cleanup); + archive_write_disk_set_user_lookup(a, ucache, lookup_uid, cleanup); + return (ARCHIVE_OK); +} + +static int64_t +lookup_gid(void *private_data, const char *gname, int64_t gid) +{ + int h; + struct bucket *b; + struct bucket *gcache = (struct bucket *)private_data; + + /* If no gname, just use the gid provided. */ + if (gname == NULL || *gname == '\0') + return (gid); + + /* Try to find gname in the cache. */ + h = hash(gname); + b = &gcache[h % cache_size ]; + if (b->name != NULL && b->hash == h && strcmp(gname, b->name) == 0) + return ((gid_t)b->id); + + /* Free the cache slot for a new entry. */ + free(b->name); + b->name = strdup(gname); + /* Note: If strdup fails, that's okay; we just won't cache. */ + b->hash = h; +#if HAVE_GRP_H +# if HAVE_GETGRNAM_R + { + char _buffer[128]; + size_t bufsize = 128; + char *buffer = _buffer; + char *allocated = NULL; + struct group grent, *result; + int r; + + for (;;) { + result = &grent; /* Old getgrnam_r ignores last arg. */ + r = getgrnam_r(gname, &grent, buffer, bufsize, &result); + if (r == 0) + break; + if (r != ERANGE) + break; + bufsize *= 2; + free(allocated); + allocated = malloc(bufsize); + if (allocated == NULL) + break; + buffer = allocated; + } + if (result != NULL) + gid = result->gr_gid; + free(allocated); + } +# else /* HAVE_GETGRNAM_R */ + { + struct group *result; + + result = getgrnam(gname); + if (result != NULL) + gid = result->gr_gid; + } +# endif /* HAVE_GETGRNAM_R */ +#elif defined(_WIN32) && !defined(__CYGWIN__) + /* TODO: do a gname->gid lookup for Windows. */ +#else + #error No way to perform gid lookups on this platform +#endif + b->id = (gid_t)gid; + + return (gid); +} + +static int64_t +lookup_uid(void *private_data, const char *uname, int64_t uid) +{ + int h; + struct bucket *b; + struct bucket *ucache = (struct bucket *)private_data; + + /* If no uname, just use the uid provided. */ + if (uname == NULL || *uname == '\0') + return (uid); + + /* Try to find uname in the cache. */ + h = hash(uname); + b = &ucache[h % cache_size ]; + if (b->name != NULL && b->hash == h && strcmp(uname, b->name) == 0) + return ((uid_t)b->id); + + /* Free the cache slot for a new entry. */ + free(b->name); + b->name = strdup(uname); + /* Note: If strdup fails, that's okay; we just won't cache. */ + b->hash = h; +#if HAVE_PWD_H +# if HAVE_GETPWNAM_R + { + char _buffer[128]; + size_t bufsize = 128; + char *buffer = _buffer; + char *allocated = NULL; + struct passwd pwent, *result; + int r; + + for (;;) { + result = &pwent; /* Old getpwnam_r ignores last arg. */ + r = getpwnam_r(uname, &pwent, buffer, bufsize, &result); + if (r == 0) + break; + if (r != ERANGE) + break; + bufsize *= 2; + free(allocated); + allocated = malloc(bufsize); + if (allocated == NULL) + break; + buffer = allocated; + } + if (result != NULL) + uid = result->pw_uid; + free(allocated); + } +# else /* HAVE_GETPWNAM_R */ + { + struct passwd *result; + + result = getpwnam(uname); + if (result != NULL) + uid = result->pw_uid; + } +#endif /* HAVE_GETPWNAM_R */ +#elif defined(_WIN32) && !defined(__CYGWIN__) + /* TODO: do a uname->uid lookup for Windows. */ +#else + #error No way to look up uids on this platform +#endif + b->id = (uid_t)uid; + + return (uid); +} + +static void +cleanup(void *private) +{ + size_t i; + struct bucket *cache = (struct bucket *)private; + + for (i = 0; i < cache_size; i++) + free(cache[i].name); + free(cache); +} + + +static unsigned int +hash(const char *p) +{ + /* A 32-bit version of Peter Weinberger's (PJW) hash algorithm, + as used by ELF for hashing function names. */ + unsigned g, h = 0; + while (*p != '\0') { + h = (h << 4) + *p++; + if ((g = h & 0xF0000000) != 0) { + h ^= g >> 24; + h &= 0x0FFFFFFF; + } + } + return h; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk_windows.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk_windows.c new file mode 100644 index 0000000000..0c600176cd --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_disk_windows.c @@ -0,0 +1,2834 @@ +/*- + * Copyright (c) 2003-2010 Tim Kientzle + * Copyright (c) 2011-2012 Michihiro NAKAJIMA + * 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 + * in this position and unchanged. + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#if defined(_WIN32) && !defined(__CYGWIN__) + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_UTIME_H +#include <sys/utime.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#include <winioctl.h> + +/* TODO: Support Mac OS 'quarantine' feature. This is really just a + * standard tag to mark files that have been downloaded as "tainted". + * On Mac OS, we should mark the extracted files as tainted if the + * archive being read was tainted. Windows has a similar feature; we + * should investigate ways to support this generically. */ + +#include "archive.h" +#include "archive_acl_private.h" +#include "archive_string.h" +#include "archive_entry.h" +#include "archive_private.h" + +#ifndef O_BINARY +#define O_BINARY 0 +#endif +#ifndef IO_REPARSE_TAG_SYMLINK +/* Old SDKs do not provide IO_REPARSE_TAG_SYMLINK */ +#define IO_REPARSE_TAG_SYMLINK 0xA000000CL +#endif + +static BOOL SetFilePointerEx_perso(HANDLE hFile, + LARGE_INTEGER liDistanceToMove, + PLARGE_INTEGER lpNewFilePointer, + DWORD dwMoveMethod) +{ + LARGE_INTEGER li; + li.QuadPart = liDistanceToMove.QuadPart; + li.LowPart = SetFilePointer( + hFile, li.LowPart, &li.HighPart, dwMoveMethod); + if(lpNewFilePointer) { + lpNewFilePointer->QuadPart = li.QuadPart; + } + return li.LowPart != (DWORD)-1 || GetLastError() == NO_ERROR; +} + +struct fixup_entry { + struct fixup_entry *next; + struct archive_acl acl; + mode_t mode; + int64_t atime; + int64_t birthtime; + int64_t mtime; + int64_t ctime; + unsigned long atime_nanos; + unsigned long birthtime_nanos; + unsigned long mtime_nanos; + unsigned long ctime_nanos; + unsigned long fflags_set; + int fixup; /* bitmask of what needs fixing */ + wchar_t *name; +}; + +/* + * We use a bitmask to track which operations remain to be done for + * this file. In particular, this helps us avoid unnecessary + * operations when it's possible to take care of one step as a + * side-effect of another. For example, mkdir() can specify the mode + * for the newly-created object but symlink() cannot. This means we + * can skip chmod() if mkdir() succeeded, but we must explicitly + * chmod() if we're trying to create a directory that already exists + * (mkdir() failed) or if we're restoring a symlink. Similarly, we + * need to verify UID/GID before trying to restore SUID/SGID bits; + * that verification can occur explicitly through a stat() call or + * implicitly because of a successful chown() call. + */ +#define TODO_MODE_FORCE 0x40000000 +#define TODO_MODE_BASE 0x20000000 +#define TODO_SUID 0x10000000 +#define TODO_SUID_CHECK 0x08000000 +#define TODO_SGID 0x04000000 +#define TODO_SGID_CHECK 0x02000000 +#define TODO_MODE (TODO_MODE_BASE|TODO_SUID|TODO_SGID) +#define TODO_TIMES ARCHIVE_EXTRACT_TIME +#define TODO_OWNER ARCHIVE_EXTRACT_OWNER +#define TODO_FFLAGS ARCHIVE_EXTRACT_FFLAGS +#define TODO_ACLS ARCHIVE_EXTRACT_ACL +#define TODO_XATTR ARCHIVE_EXTRACT_XATTR +#define TODO_MAC_METADATA ARCHIVE_EXTRACT_MAC_METADATA + +struct archive_write_disk { + struct archive archive; + + mode_t user_umask; + struct fixup_entry *fixup_list; + struct fixup_entry *current_fixup; + int64_t user_uid; + int skip_file_set; + int64_t skip_file_dev; + int64_t skip_file_ino; + time_t start_time; + + int64_t (*lookup_gid)(void *private, const char *gname, int64_t gid); + void (*cleanup_gid)(void *private); + void *lookup_gid_data; + int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid); + void (*cleanup_uid)(void *private); + void *lookup_uid_data; + + /* + * Full path of last file to satisfy symlink checks. + */ + struct archive_wstring path_safe; + + /* + * Cached stat data from disk for the current entry. + * If this is valid, pst points to st. Otherwise, + * pst is null. + */ + BY_HANDLE_FILE_INFORMATION st; + BY_HANDLE_FILE_INFORMATION *pst; + + /* Information about the object being restored right now. */ + struct archive_entry *entry; /* Entry being extracted. */ + wchar_t *name; /* Name of entry, possibly edited. */ + struct archive_wstring _name_data; /* backing store for 'name' */ + wchar_t *tmpname; /* Temporary name */ + struct archive_wstring _tmpname_data; /* backing store for 'tmpname' */ + /* Tasks remaining for this object. */ + int todo; + /* Tasks deferred until end-of-archive. */ + int deferred; + /* Options requested by the client. */ + int flags; + /* Handle for the file we're restoring. */ + HANDLE fh; + /* Current offset for writing data to the file. */ + int64_t offset; + /* Last offset actually written to disk. */ + int64_t fd_offset; + /* Total bytes actually written to files. */ + int64_t total_bytes_written; + /* Maximum size of file, -1 if unknown. */ + int64_t filesize; + /* Dir we were in before this restore; only for deep paths. */ + int restore_pwd; + /* Mode we should use for this entry; affected by _PERM and umask. */ + mode_t mode; + /* UID/GID to use in restoring this entry. */ + int64_t uid; + int64_t gid; +}; + +/* + * Default mode for dirs created automatically (will be modified by umask). + * Note that POSIX specifies 0777 for implicitly-created dirs, "modified + * by the process' file creation mask." + */ +#define DEFAULT_DIR_MODE 0777 +/* + * Dir modes are restored in two steps: During the extraction, the permissions + * in the archive are modified to match the following limits. During + * the post-extract fixup pass, the permissions from the archive are + * applied. + */ +#define MINIMUM_DIR_MODE 0700 +#define MAXIMUM_DIR_MODE 0775 + +static int disk_unlink(const wchar_t *); +static int disk_rmdir(const wchar_t *); +static int check_symlinks(struct archive_write_disk *); +static int create_filesystem_object(struct archive_write_disk *); +static struct fixup_entry *current_fixup(struct archive_write_disk *, + const wchar_t *pathname); +static int cleanup_pathname(struct archive_write_disk *); +static int create_dir(struct archive_write_disk *, wchar_t *); +static int create_parent_dir(struct archive_write_disk *, wchar_t *); +static int la_chmod(const wchar_t *, mode_t); +static int la_mktemp(struct archive_write_disk *); +static int older(BY_HANDLE_FILE_INFORMATION *, struct archive_entry *); +static int permissive_name_w(struct archive_write_disk *); +static int restore_entry(struct archive_write_disk *); +static int set_acls(struct archive_write_disk *, HANDLE h, + const wchar_t *, struct archive_acl *); +static int set_xattrs(struct archive_write_disk *); +static int clear_nochange_fflags(struct archive_write_disk *); +static int set_fflags(struct archive_write_disk *); +static int set_fflags_platform(const wchar_t *, unsigned long, + unsigned long); +static int set_ownership(struct archive_write_disk *); +static int set_mode(struct archive_write_disk *, int mode); +static int set_times(struct archive_write_disk *, HANDLE, int, + const wchar_t *, time_t, long, time_t, long, time_t, + long, time_t, long); +static int set_times_from_entry(struct archive_write_disk *); +static struct fixup_entry *sort_dir_list(struct fixup_entry *p); +static ssize_t write_data_block(struct archive_write_disk *, + const char *, size_t); + +static struct archive_vtable *archive_write_disk_vtable(void); + +static int _archive_write_disk_close(struct archive *); +static int _archive_write_disk_free(struct archive *); +static int _archive_write_disk_header(struct archive *, + struct archive_entry *); +static int64_t _archive_write_disk_filter_bytes(struct archive *, int); +static int _archive_write_disk_finish_entry(struct archive *); +static ssize_t _archive_write_disk_data(struct archive *, const void *, + size_t); +static ssize_t _archive_write_disk_data_block(struct archive *, const void *, + size_t, int64_t); + +#define bhfi_dev(bhfi) ((bhfi)->dwVolumeSerialNumber) +/* Treat FileIndex as i-node. We should remove a sequence number + * which is high-16-bits of nFileIndexHigh. */ +#define bhfi_ino(bhfi) \ + ((((int64_t)((bhfi)->nFileIndexHigh & 0x0000FFFFUL)) << 32) \ + + (bhfi)->nFileIndexLow) +#define bhfi_size(bhfi) \ + ((((int64_t)(bhfi)->nFileSizeHigh) << 32) + (bhfi)->nFileSizeLow) + +static int +file_information(struct archive_write_disk *a, wchar_t *path, + BY_HANDLE_FILE_INFORMATION *st, mode_t *mode, int sim_lstat) +{ + HANDLE h; + int r; + DWORD flag = FILE_FLAG_BACKUP_SEMANTICS; + WIN32_FIND_DATAW findData; + + if (sim_lstat || mode != NULL) { + h = FindFirstFileW(path, &findData); + if (h == INVALID_HANDLE_VALUE && + GetLastError() == ERROR_INVALID_NAME) { + wchar_t *full; + full = __la_win_permissive_name_w(path); + h = FindFirstFileW(full, &findData); + free(full); + } + if (h == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + return (-1); + } + FindClose(h); + } + + /* Is symlink file ? */ + if (sim_lstat && + ((findData.dwFileAttributes + & FILE_ATTRIBUTE_REPARSE_POINT) && + (findData.dwReserved0 == IO_REPARSE_TAG_SYMLINK))) + flag |= FILE_FLAG_OPEN_REPARSE_POINT; + + h = CreateFileW(a->name, 0, 0, NULL, + OPEN_EXISTING, flag, NULL); + if (h == INVALID_HANDLE_VALUE && + GetLastError() == ERROR_INVALID_NAME) { + wchar_t *full; + full = __la_win_permissive_name_w(path); + h = CreateFileW(full, 0, 0, NULL, + OPEN_EXISTING, flag, NULL); + free(full); + } + if (h == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + return (-1); + } + r = GetFileInformationByHandle(h, st); + CloseHandle(h); + if (r == 0) { + la_dosmaperr(GetLastError()); + return (-1); + } + + if (mode == NULL) + return (0); + + *mode = S_IRUSR | S_IRGRP | S_IROTH; + if ((st->dwFileAttributes & FILE_ATTRIBUTE_READONLY) == 0) + *mode |= S_IWUSR | S_IWGRP | S_IWOTH; + if ((st->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) && + findData.dwReserved0 == IO_REPARSE_TAG_SYMLINK) + *mode |= S_IFLNK; + else if (st->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + *mode |= S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH; + else { + const wchar_t *p; + + *mode |= S_IFREG; + p = wcsrchr(path, L'.'); + if (p != NULL && wcslen(p) == 4) { + switch (p[1]) { + case L'B': case L'b': + if ((p[2] == L'A' || p[2] == L'a' ) && + (p[3] == L'T' || p[3] == L't' )) + *mode |= S_IXUSR | S_IXGRP | S_IXOTH; + break; + case L'C': case L'c': + if (((p[2] == L'M' || p[2] == L'm' ) && + (p[3] == L'D' || p[3] == L'd' ))) + *mode |= S_IXUSR | S_IXGRP | S_IXOTH; + break; + case L'E': case L'e': + if ((p[2] == L'X' || p[2] == L'x' ) && + (p[3] == L'E' || p[3] == L'e' )) + *mode |= S_IXUSR | S_IXGRP | S_IXOTH; + break; + default: + break; + } + } + } + return (0); +} + +/* + * Note: The path, for example, "aa/a/../b../c" will be converted to "aa/c" + * by GetFullPathNameW() W32 API, which __la_win_permissive_name_w uses. + * It means we cannot handle multiple dirs in one archive_entry. + * So we have to make the full-pathname in another way, which does not + * break "../" path string. + */ +static int +permissive_name_w(struct archive_write_disk *a) +{ + wchar_t *wn, *wnp; + wchar_t *ws, *wsp; + DWORD l; + + wnp = a->name; + if (wnp[0] == L'\\' && wnp[1] == L'\\' && + wnp[2] == L'?' && wnp[3] == L'\\') + /* We have already a permissive name. */ + return (0); + + if (wnp[0] == L'\\' && wnp[1] == L'\\' && + wnp[2] == L'.' && wnp[3] == L'\\') { + /* This is a device name */ + if (((wnp[4] >= L'a' && wnp[4] <= L'z') || + (wnp[4] >= L'A' && wnp[4] <= L'Z')) && + wnp[5] == L':' && wnp[6] == L'\\') { + wnp[2] = L'?';/* Not device name. */ + return (0); + } + } + + /* + * A full-pathname starting with a drive name like "C:\abc". + */ + if (((wnp[0] >= L'a' && wnp[0] <= L'z') || + (wnp[0] >= L'A' && wnp[0] <= L'Z')) && + wnp[1] == L':' && wnp[2] == L'\\') { + wn = _wcsdup(wnp); + if (wn == NULL) + return (-1); + archive_wstring_ensure(&(a->_name_data), 4 + wcslen(wn) + 1); + a->name = a->_name_data.s; + /* Prepend "\\?\" */ + archive_wstrncpy(&(a->_name_data), L"\\\\?\\", 4); + archive_wstrcat(&(a->_name_data), wn); + free(wn); + return (0); + } + + /* + * A full-pathname pointing to a network drive + * like "\\<server-name>\<share-name>\file". + */ + if (wnp[0] == L'\\' && wnp[1] == L'\\' && wnp[2] != L'\\') { + const wchar_t *p = &wnp[2]; + + /* Skip server-name letters. */ + while (*p != L'\\' && *p != L'\0') + ++p; + if (*p == L'\\') { + const wchar_t *rp = ++p; + /* Skip share-name letters. */ + while (*p != L'\\' && *p != L'\0') + ++p; + if (*p == L'\\' && p != rp) { + /* Now, match patterns such as + * "\\server-name\share-name\" */ + wn = _wcsdup(wnp); + if (wn == NULL) + return (-1); + archive_wstring_ensure(&(a->_name_data), + 8 + wcslen(wn) + 1); + a->name = a->_name_data.s; + /* Prepend "\\?\UNC\" */ + archive_wstrncpy(&(a->_name_data), + L"\\\\?\\UNC\\", 8); + archive_wstrcat(&(a->_name_data), wn+2); + free(wn); + return (0); + } + } + return (0); + } + + /* + * Get current working directory. + */ + l = GetCurrentDirectoryW(0, NULL); + if (l == 0) + return (-1); + ws = malloc(l * sizeof(wchar_t)); + l = GetCurrentDirectoryW(l, ws); + if (l == 0) { + free(ws); + return (-1); + } + wsp = ws; + + /* + * A full-pathname starting without a drive name like "\abc". + */ + if (wnp[0] == L'\\') { + wn = _wcsdup(wnp); + if (wn == NULL) + return (-1); + archive_wstring_ensure(&(a->_name_data), + 4 + 2 + wcslen(wn) + 1); + a->name = a->_name_data.s; + /* Prepend "\\?\" and drive name. */ + archive_wstrncpy(&(a->_name_data), L"\\\\?\\", 4); + archive_wstrncat(&(a->_name_data), wsp, 2); + archive_wstrcat(&(a->_name_data), wn); + free(wsp); + free(wn); + return (0); + } + + wn = _wcsdup(wnp); + if (wn == NULL) + return (-1); + archive_wstring_ensure(&(a->_name_data), 4 + l + 1 + wcslen(wn) + 1); + a->name = a->_name_data.s; + /* Prepend "\\?\" and drive name if not already added. */ + if (l > 3 && wsp[0] == L'\\' && wsp[1] == L'\\' && + wsp[2] == L'?' && wsp[3] == L'\\') + { + archive_wstrncpy(&(a->_name_data), wsp, l); + } + else if (l > 2 && wsp[0] == L'\\' && wsp[1] == L'\\' && wsp[2] != L'\\') + { + archive_wstrncpy(&(a->_name_data), L"\\\\?\\UNC\\", 8); + archive_wstrncat(&(a->_name_data), wsp+2, l-2); + } + else + { + archive_wstrncpy(&(a->_name_data), L"\\\\?\\", 4); + archive_wstrncat(&(a->_name_data), wsp, l); + } + archive_wstrncat(&(a->_name_data), L"\\", 1); + archive_wstrcat(&(a->_name_data), wn); + a->name = a->_name_data.s; + free(wsp); + free(wn); + return (0); +} + +static int +la_chmod(const wchar_t *path, mode_t mode) +{ + DWORD attr; + BOOL r; + wchar_t *fullname; + int ret = 0; + + fullname = NULL; + attr = GetFileAttributesW(path); + if (attr == (DWORD)-1 && + GetLastError() == ERROR_INVALID_NAME) { + fullname = __la_win_permissive_name_w(path); + attr = GetFileAttributesW(fullname); + } + if (attr == (DWORD)-1) { + la_dosmaperr(GetLastError()); + ret = -1; + goto exit_chmode; + } + if (mode & _S_IWRITE) + attr &= ~FILE_ATTRIBUTE_READONLY; + else + attr |= FILE_ATTRIBUTE_READONLY; + if (fullname != NULL) + r = SetFileAttributesW(fullname, attr); + else + r = SetFileAttributesW(path, attr); + if (r == 0) { + la_dosmaperr(GetLastError()); + ret = -1; + } +exit_chmode: + free(fullname); + return (ret); +} + +static int +la_mktemp(struct archive_write_disk *a) +{ + int fd; + mode_t mode; + + archive_wstring_empty(&(a->_tmpname_data)); + archive_wstrcpy(&(a->_tmpname_data), a->name); + archive_wstrcat(&(a->_tmpname_data), L".XXXXXX"); + a->tmpname = a->_tmpname_data.s; + + fd = __archive_mkstemp(a->tmpname); + if (fd == -1) + return -1; + + mode = a->mode & 0777 & ~a->user_umask; + if (la_chmod(a->tmpname, mode) == -1) { + la_dosmaperr(GetLastError()); + _close(fd); + return -1; + } + return (fd); +} + +static void * +la_GetFunctionKernel32(const char *name) +{ + static HINSTANCE lib; + static int set; + if (!set) { + set = 1; + lib = LoadLibrary(TEXT("kernel32.dll")); + } + if (lib == NULL) { + fprintf(stderr, "Can't load kernel32.dll?!\n"); + exit(1); + } + return (void *)GetProcAddress(lib, name); +} + +static int +la_CreateHardLinkW(wchar_t *linkname, wchar_t *target) +{ + static BOOLEAN (WINAPI *f)(LPWSTR, LPWSTR, LPSECURITY_ATTRIBUTES); + static int set; + BOOL ret; + + if (!set) { + set = 1; + f = la_GetFunctionKernel32("CreateHardLinkW"); + } + if (!f) { + errno = ENOTSUP; + return (0); + } + ret = (*f)(linkname, target, NULL); + if (!ret) { + /* Under windows 2000, it is necessary to remove + * the "\\?\" prefix. */ +#define IS_UNC(name) ((name[0] == L'U' || name[0] == L'u') && \ + (name[1] == L'N' || name[1] == L'n') && \ + (name[2] == L'C' || name[2] == L'c') && \ + name[3] == L'\\') + if (!wcsncmp(linkname,L"\\\\?\\", 4)) { + linkname += 4; + if (IS_UNC(linkname)) + linkname += 4; + } + if (!wcsncmp(target,L"\\\\?\\", 4)) { + target += 4; + if (IS_UNC(target)) + target += 4; + } +#undef IS_UNC + ret = (*f)(linkname, target, NULL); + } + return (ret); +} + +/* + * Create file or directory symolic link + * + * If linktype is AE_SYMLINK_TYPE_UNDEFINED (or unknown), guess linktype from + * the link target + */ +static int +la_CreateSymbolicLinkW(const wchar_t *linkname, const wchar_t *target, + int linktype) { + static BOOLEAN (WINAPI *f)(LPCWSTR, LPCWSTR, DWORD); + static int set; + wchar_t *ttarget, *p; + int len; + DWORD attrs = 0; + DWORD flags = 0; + DWORD newflags = 0; + BOOL ret = 0; + + if (!set) { + set = 1; + f = la_GetFunctionKernel32("CreateSymbolicLinkW"); + } + if (!f) + return (0); + + len = wcslen(target); + if (len == 0) { + errno = EINVAL; + return(0); + } + /* + * When writing path targets, we need to translate slashes + * to backslashes + */ + ttarget = malloc((len + 1) * sizeof(wchar_t)); + if (ttarget == NULL) + return(0); + + p = ttarget; + + while(*target != L'\0') { + if (*target == L'/') + *p = L'\\'; + else + *p = *target; + target++; + p++; + } + *p = L'\0'; + + /* + * In case of undefined symlink type we guess it from the target. + * If the target equals ".", "..", ends with a backslash or a + * backslash followed by "." or ".." we assume it is a directory + * symlink. In all other cases we assume a file symlink. + */ + if (linktype != AE_SYMLINK_TYPE_FILE && ( + linktype == AE_SYMLINK_TYPE_DIRECTORY || + *(p - 1) == L'\\' || (*(p - 1) == L'.' && ( + len == 1 || *(p - 2) == L'\\' || ( *(p - 2) == L'.' && ( + len == 2 || *(p - 3) == L'\\')))))) { +#if defined(SYMBOLIC_LINK_FLAG_DIRECTORY) + flags |= SYMBOLIC_LINK_FLAG_DIRECTORY; +#else + flags |= 0x1; +#endif + } + +#if defined(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE) + newflags = flags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE; +#else + newflags = flags | 0x2; +#endif + + /* + * Windows won't overwrite existing links + */ + attrs = GetFileAttributesW(linkname); + if (attrs != INVALID_FILE_ATTRIBUTES) { + if (attrs & FILE_ATTRIBUTE_DIRECTORY) + disk_rmdir(linkname); + else + disk_unlink(linkname); + } + + ret = (*f)(linkname, ttarget, newflags); + /* + * Prior to Windows 10 calling CreateSymbolicLinkW() will fail + * if SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE is set + */ + if (!ret) { + ret = (*f)(linkname, ttarget, flags); + } + free(ttarget); + return (ret); +} + +static int +la_ftruncate(HANDLE handle, int64_t length) +{ + LARGE_INTEGER distance; + + if (GetFileType(handle) != FILE_TYPE_DISK) { + errno = EBADF; + return (-1); + } + distance.QuadPart = length; + if (!SetFilePointerEx_perso(handle, distance, NULL, FILE_BEGIN)) { + la_dosmaperr(GetLastError()); + return (-1); + } + if (!SetEndOfFile(handle)) { + la_dosmaperr(GetLastError()); + return (-1); + } + return (0); +} + +static int +lazy_stat(struct archive_write_disk *a) +{ + if (a->pst != NULL) { + /* Already have stat() data available. */ + return (ARCHIVE_OK); + } + if (a->fh != INVALID_HANDLE_VALUE && + GetFileInformationByHandle(a->fh, &a->st) == 0) { + a->pst = &a->st; + return (ARCHIVE_OK); + } + + /* + * XXX At this point, symlinks should not be hit, otherwise + * XXX a race occurred. Do we want to check explicitly for that? + */ + if (file_information(a, a->name, &a->st, NULL, 1) == 0) { + a->pst = &a->st; + return (ARCHIVE_OK); + } + archive_set_error(&a->archive, errno, "Couldn't stat file"); + return (ARCHIVE_WARN); +} + +static struct archive_vtable * +archive_write_disk_vtable(void) +{ + static struct archive_vtable av; + static int inited = 0; + + if (!inited) { + av.archive_close = _archive_write_disk_close; + av.archive_filter_bytes = _archive_write_disk_filter_bytes; + av.archive_free = _archive_write_disk_free; + av.archive_write_header = _archive_write_disk_header; + av.archive_write_finish_entry + = _archive_write_disk_finish_entry; + av.archive_write_data = _archive_write_disk_data; + av.archive_write_data_block = _archive_write_disk_data_block; + inited = 1; + } + return (&av); +} + +static int64_t +_archive_write_disk_filter_bytes(struct archive *_a, int n) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + (void)n; /* UNUSED */ + if (n == -1 || n == 0) + return (a->total_bytes_written); + return (-1); +} + + +int +archive_write_disk_set_options(struct archive *_a, int flags) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + + a->flags = flags; + return (ARCHIVE_OK); +} + + +/* + * Extract this entry to disk. + * + * TODO: Validate hardlinks. According to the standards, we're + * supposed to check each extracted hardlink and squawk if it refers + * to a file that we didn't restore. I'm not entirely convinced this + * is a good idea, but more importantly: Is there any way to validate + * hardlinks without keeping a complete list of filenames from the + * entire archive?? Ugh. + * + */ +static int +_archive_write_disk_header(struct archive *_a, struct archive_entry *entry) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + struct fixup_entry *fe; + int ret, r; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_write_disk_header"); + archive_clear_error(&a->archive); + if (a->archive.state & ARCHIVE_STATE_DATA) { + r = _archive_write_disk_finish_entry(&a->archive); + if (r == ARCHIVE_FATAL) + return (r); + } + + /* Set up for this particular entry. */ + a->pst = NULL; + a->current_fixup = NULL; + a->deferred = 0; + archive_entry_free(a->entry); + a->entry = NULL; + a->entry = archive_entry_clone(entry); + a->fh = INVALID_HANDLE_VALUE; + a->fd_offset = 0; + a->offset = 0; + a->restore_pwd = -1; + a->uid = a->user_uid; + a->mode = archive_entry_mode(a->entry); + if (archive_entry_size_is_set(a->entry)) + a->filesize = archive_entry_size(a->entry); + else + a->filesize = -1; + archive_wstrcpy(&(a->_name_data), archive_entry_pathname_w(a->entry)); + a->name = a->_name_data.s; + archive_clear_error(&a->archive); + + /* + * Clean up the requested path. This is necessary for correct + * dir restores; the dir restore logic otherwise gets messed + * up by nonsense like "dir/.". + */ + ret = cleanup_pathname(a); + if (ret != ARCHIVE_OK) + return (ret); + + /* + * Generate a full-pathname and use it from here. + */ + if (permissive_name_w(a) < 0) { + errno = EINVAL; + return (ARCHIVE_FAILED); + } + + /* + * Query the umask so we get predictable mode settings. + * This gets done on every call to _write_header in case the + * user edits their umask during the extraction for some + * reason. + */ + umask(a->user_umask = umask(0)); + + /* Figure out what we need to do for this entry. */ + a->todo = TODO_MODE_BASE; + if (a->flags & ARCHIVE_EXTRACT_PERM) { + a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */ + /* + * SGID requires an extra "check" step because we + * cannot easily predict the GID that the system will + * assign. (Different systems assign GIDs to files + * based on a variety of criteria, including process + * credentials and the gid of the enclosing + * directory.) We can only restore the SGID bit if + * the file has the right GID, and we only know the + * GID if we either set it (see set_ownership) or if + * we've actually called stat() on the file after it + * was restored. Since there are several places at + * which we might verify the GID, we need a TODO bit + * to keep track. + */ + if (a->mode & S_ISGID) + a->todo |= TODO_SGID | TODO_SGID_CHECK; + /* + * Verifying the SUID is simpler, but can still be + * done in multiple ways, hence the separate "check" bit. + */ + if (a->mode & S_ISUID) + a->todo |= TODO_SUID | TODO_SUID_CHECK; + } else { + /* + * User didn't request full permissions, so don't + * restore SUID, SGID bits and obey umask. + */ + a->mode &= ~S_ISUID; + a->mode &= ~S_ISGID; + a->mode &= ~S_ISVTX; + a->mode &= ~a->user_umask; + } +#if 0 + if (a->flags & ARCHIVE_EXTRACT_OWNER) + a->todo |= TODO_OWNER; +#endif + if (a->flags & ARCHIVE_EXTRACT_TIME) + a->todo |= TODO_TIMES; + if (a->flags & ARCHIVE_EXTRACT_ACL) { + if (archive_entry_filetype(a->entry) == AE_IFDIR) + a->deferred |= TODO_ACLS; + else + a->todo |= TODO_ACLS; + } + if (a->flags & ARCHIVE_EXTRACT_XATTR) + a->todo |= TODO_XATTR; + if (a->flags & ARCHIVE_EXTRACT_FFLAGS) + a->todo |= TODO_FFLAGS; + if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) { + ret = check_symlinks(a); + if (ret != ARCHIVE_OK) + return (ret); + } + + ret = restore_entry(a); + + /* + * TODO: There are rumours that some extended attributes must + * be restored before file data is written. If this is true, + * then we either need to write all extended attributes both + * before and after restoring the data, or find some rule for + * determining which must go first and which last. Due to the + * many ways people are using xattrs, this may prove to be an + * intractable problem. + */ + + /* + * Fixup uses the unedited pathname from archive_entry_pathname(), + * because it is relative to the base dir and the edited path + * might be relative to some intermediate dir as a result of the + * deep restore logic. + */ + if (a->deferred & TODO_MODE) { + fe = current_fixup(a, archive_entry_pathname_w(entry)); + fe->fixup |= TODO_MODE_BASE; + fe->mode = a->mode; + } + + if ((a->deferred & TODO_TIMES) + && (archive_entry_mtime_is_set(entry) + || archive_entry_atime_is_set(entry))) { + fe = current_fixup(a, archive_entry_pathname_w(entry)); + fe->mode = a->mode; + fe->fixup |= TODO_TIMES; + if (archive_entry_atime_is_set(entry)) { + fe->atime = archive_entry_atime(entry); + fe->atime_nanos = archive_entry_atime_nsec(entry); + } else { + /* If atime is unset, use start time. */ + fe->atime = a->start_time; + fe->atime_nanos = 0; + } + if (archive_entry_mtime_is_set(entry)) { + fe->mtime = archive_entry_mtime(entry); + fe->mtime_nanos = archive_entry_mtime_nsec(entry); + } else { + /* If mtime is unset, use start time. */ + fe->mtime = a->start_time; + fe->mtime_nanos = 0; + } + if (archive_entry_birthtime_is_set(entry)) { + fe->birthtime = archive_entry_birthtime(entry); + fe->birthtime_nanos = archive_entry_birthtime_nsec(entry); + } else { + /* If birthtime is unset, use mtime. */ + fe->birthtime = fe->mtime; + fe->birthtime_nanos = fe->mtime_nanos; + } + } + + if (a->deferred & TODO_ACLS) { + fe = current_fixup(a, archive_entry_pathname_w(entry)); + archive_acl_copy(&fe->acl, archive_entry_acl(entry)); + } + + if (a->deferred & TODO_FFLAGS) { + unsigned long set, clear; + + fe = current_fixup(a, archive_entry_pathname_w(entry)); + archive_entry_fflags(entry, &set, &clear); + fe->fflags_set = set; + } + + /* + * On Windows, A creating sparse file requires a special mark. + */ + if (a->fh != INVALID_HANDLE_VALUE && + archive_entry_sparse_count(entry) > 0) { + int64_t base = 0, offset, length; + int i, cnt = archive_entry_sparse_reset(entry); + int sparse = 0; + + for (i = 0; i < cnt; i++) { + archive_entry_sparse_next(entry, &offset, &length); + if (offset - base >= 4096) { + sparse = 1;/* we have a hole. */ + break; + } + base = offset + length; + } + if (sparse) { + DWORD dmy; + /* Mark this file as sparse. */ + DeviceIoControl(a->fh, FSCTL_SET_SPARSE, + NULL, 0, NULL, 0, &dmy, NULL); + } + } + + /* We've created the object and are ready to pour data into it. */ + if (ret >= ARCHIVE_WARN) + a->archive.state = ARCHIVE_STATE_DATA; + /* + * If it's not open, tell our client not to try writing. + * In particular, dirs, links, etc, don't get written to. + */ + if (a->fh == INVALID_HANDLE_VALUE) { + archive_entry_set_size(entry, 0); + a->filesize = 0; + } + + return (ret); +} + +int +archive_write_disk_set_skip_file(struct archive *_a, la_int64_t d, la_int64_t i) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file"); + a->skip_file_set = 1; + a->skip_file_dev = d; + a->skip_file_ino = i; + return (ARCHIVE_OK); +} + +static ssize_t +write_data_block(struct archive_write_disk *a, const char *buff, size_t size) +{ + OVERLAPPED ol; + uint64_t start_size = size; + DWORD bytes_written = 0; + ssize_t block_size = 0, bytes_to_write; + + if (size == 0) + return (ARCHIVE_OK); + + if (a->filesize == 0 || a->fh == INVALID_HANDLE_VALUE) { + archive_set_error(&a->archive, 0, + "Attempt to write to an empty file"); + return (ARCHIVE_WARN); + } + + if (a->flags & ARCHIVE_EXTRACT_SPARSE) { + /* XXX TODO XXX Is there a more appropriate choice here ? */ + /* This needn't match the filesystem allocation size. */ + block_size = 16*1024; + } + + /* If this write would run beyond the file size, truncate it. */ + if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize) + start_size = size = (size_t)(a->filesize - a->offset); + + /* Write the data. */ + while (size > 0) { + if (block_size == 0) { + bytes_to_write = size; + } else { + /* We're sparsifying the file. */ + const char *p, *end; + int64_t block_end; + + /* Skip leading zero bytes. */ + for (p = buff, end = buff + size; p < end; ++p) { + if (*p != '\0') + break; + } + a->offset += p - buff; + size -= p - buff; + buff = p; + if (size == 0) + break; + + /* Calculate next block boundary after offset. */ + block_end + = (a->offset / block_size + 1) * block_size; + + /* If the adjusted write would cross block boundary, + * truncate it to the block boundary. */ + bytes_to_write = size; + if (a->offset + bytes_to_write > block_end) + bytes_to_write = (DWORD)(block_end - a->offset); + } + memset(&ol, 0, sizeof(ol)); + ol.Offset = (DWORD)(a->offset & 0xFFFFFFFF); + ol.OffsetHigh = (DWORD)(a->offset >> 32); + if (!WriteFile(a->fh, buff, (uint32_t)bytes_to_write, + &bytes_written, &ol)) { + DWORD lasterr; + + lasterr = GetLastError(); + if (lasterr == ERROR_ACCESS_DENIED) + errno = EBADF; + else + la_dosmaperr(lasterr); + archive_set_error(&a->archive, errno, "Write failed"); + return (ARCHIVE_WARN); + } + buff += bytes_written; + size -= bytes_written; + a->total_bytes_written += bytes_written; + a->offset += bytes_written; + a->fd_offset = a->offset; + } + return ((ssize_t)(start_size - size)); +} + +static ssize_t +_archive_write_disk_data_block(struct archive *_a, + const void *buff, size_t size, int64_t offset) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + ssize_t r; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_DATA, "archive_write_data_block"); + + a->offset = offset; + r = write_data_block(a, buff, size); + if (r < ARCHIVE_OK) + return (r); + if ((size_t)r < size) { + archive_set_error(&a->archive, 0, + "Write request too large"); + return (ARCHIVE_WARN); + } +#if ARCHIVE_VERSION_NUMBER < 3999000 + return (ARCHIVE_OK); +#else + return (size); +#endif +} + +static ssize_t +_archive_write_disk_data(struct archive *_a, const void *buff, size_t size) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_DATA, "archive_write_data"); + + return (write_data_block(a, buff, size)); +} + +static int +_archive_write_disk_finish_entry(struct archive *_a) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + int ret = ARCHIVE_OK; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_write_finish_entry"); + if (a->archive.state & ARCHIVE_STATE_HEADER) + return (ARCHIVE_OK); + archive_clear_error(&a->archive); + + /* Pad or truncate file to the right size. */ + if (a->fh == INVALID_HANDLE_VALUE) { + /* There's no file. */ + } else if (a->filesize < 0) { + /* File size is unknown, so we can't set the size. */ + } else if (a->fd_offset == a->filesize) { + /* Last write ended at exactly the filesize; we're done. */ + /* Hopefully, this is the common case. */ + } else { + if (la_ftruncate(a->fh, a->filesize) == -1) { + archive_set_error(&a->archive, errno, + "File size could not be restored"); + return (ARCHIVE_FAILED); + } + } + + /* Restore metadata. */ + + /* + * Look up the "real" UID only if we're going to need it. + * TODO: the TODO_SGID condition can be dropped here, can't it? + */ + if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) { + a->uid = archive_write_disk_uid(&a->archive, + archive_entry_uname(a->entry), + archive_entry_uid(a->entry)); + } + /* Look up the "real" GID only if we're going to need it. */ + /* TODO: the TODO_SUID condition can be dropped here, can't it? */ + if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) { + a->gid = archive_write_disk_gid(&a->archive, + archive_entry_gname(a->entry), + archive_entry_gid(a->entry)); + } + + /* + * Restore ownership before set_mode tries to restore suid/sgid + * bits. If we set the owner, we know what it is and can skip + * a stat() call to examine the ownership of the file on disk. + */ + if (a->todo & TODO_OWNER) + ret = set_ownership(a); + + /* + * set_mode must precede ACLs on systems such as Solaris and + * FreeBSD where setting the mode implicitly clears extended ACLs + */ + if (a->todo & TODO_MODE) { + int r2 = set_mode(a, a->mode); + if (r2 < ret) ret = r2; + } + + /* + * Security-related extended attributes (such as + * security.capability on Linux) have to be restored last, + * since they're implicitly removed by other file changes. + */ + if (a->todo & TODO_XATTR) { + int r2 = set_xattrs(a); + if (r2 < ret) ret = r2; + } + + /* + * Some flags prevent file modification; they must be restored after + * file contents are written. + */ + if (a->todo & TODO_FFLAGS) { + int r2 = set_fflags(a); + if (r2 < ret) ret = r2; + } + + /* + * Time must follow most other metadata; + * otherwise atime will get changed. + */ + if (a->todo & TODO_TIMES) { + int r2 = set_times_from_entry(a); + if (r2 < ret) ret = r2; + } + + /* + * ACLs must be restored after timestamps because there are + * ACLs that prevent attribute changes (including time). + */ + if (a->todo & TODO_ACLS) { + int r2 = set_acls(a, a->fh, + archive_entry_pathname_w(a->entry), + archive_entry_acl(a->entry)); + if (r2 < ret) ret = r2; + } + + /* If there's an fd, we can close it now. */ + if (a->fh != INVALID_HANDLE_VALUE) { + CloseHandle(a->fh); + a->fh = INVALID_HANDLE_VALUE; + if (a->tmpname) { + /* Windows does not support atomic rename */ + disk_unlink(a->name); + if (_wrename(a->tmpname, a->name) != 0) { + la_dosmaperr(GetLastError()); + archive_set_error(&a->archive, errno, + "Failed to rename temporary file"); + ret = ARCHIVE_FAILED; + disk_unlink(a->tmpname); + } + a->tmpname = NULL; + } + } + /* If there's an entry, we can release it now. */ + archive_entry_free(a->entry); + a->entry = NULL; + a->archive.state = ARCHIVE_STATE_HEADER; + return (ret); +} + +int +archive_write_disk_set_group_lookup(struct archive *_a, + void *private_data, + la_int64_t (*lookup_gid)(void *private, const char *gname, la_int64_t gid), + void (*cleanup_gid)(void *private)) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup"); + + if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL) + (a->cleanup_gid)(a->lookup_gid_data); + + a->lookup_gid = lookup_gid; + a->cleanup_gid = cleanup_gid; + a->lookup_gid_data = private_data; + return (ARCHIVE_OK); +} + +int +archive_write_disk_set_user_lookup(struct archive *_a, + void *private_data, + int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid), + void (*cleanup_uid)(void *private)) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup"); + + if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL) + (a->cleanup_uid)(a->lookup_uid_data); + + a->lookup_uid = lookup_uid; + a->cleanup_uid = cleanup_uid; + a->lookup_uid_data = private_data; + return (ARCHIVE_OK); +} + +int64_t +archive_write_disk_gid(struct archive *_a, const char *name, la_int64_t id) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_write_disk_gid"); + if (a->lookup_gid) + return (a->lookup_gid)(a->lookup_gid_data, name, id); + return (id); +} + +int64_t +archive_write_disk_uid(struct archive *_a, const char *name, la_int64_t id) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_ANY, "archive_write_disk_uid"); + if (a->lookup_uid) + return (a->lookup_uid)(a->lookup_uid_data, name, id); + return (id); +} + +/* + * Create a new archive_write_disk object and initialize it with global state. + */ +struct archive * +archive_write_disk_new(void) +{ + struct archive_write_disk *a; + + a = (struct archive_write_disk *)calloc(1, sizeof(*a)); + if (a == NULL) + return (NULL); + a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC; + /* We're ready to write a header immediately. */ + a->archive.state = ARCHIVE_STATE_HEADER; + a->archive.vtable = archive_write_disk_vtable(); + a->start_time = time(NULL); + /* Query and restore the umask. */ + umask(a->user_umask = umask(0)); + if (archive_wstring_ensure(&a->path_safe, 512) == NULL) { + free(a); + return (NULL); + } + return (&a->archive); +} + +static int +disk_unlink(const wchar_t *path) +{ + wchar_t *fullname; + int r; + + r = _wunlink(path); + if (r != 0 && GetLastError() == ERROR_INVALID_NAME) { + fullname = __la_win_permissive_name_w(path); + r = _wunlink(fullname); + free(fullname); + } + return (r); +} + +static int +disk_rmdir(const wchar_t *path) +{ + wchar_t *fullname; + int r; + + r = _wrmdir(path); + if (r != 0 && GetLastError() == ERROR_INVALID_NAME) { + fullname = __la_win_permissive_name_w(path); + r = _wrmdir(fullname); + free(fullname); + } + return (r); +} + +/* + * The main restore function. + */ +static int +restore_entry(struct archive_write_disk *a) +{ + int ret = ARCHIVE_OK, en; + + if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) { + /* + * TODO: Fix this. Apparently, there are platforms + * that still allow root to hose the entire filesystem + * by unlinking a dir. The S_ISDIR() test above + * prevents us from using unlink() here if the new + * object is a dir, but that doesn't mean the old + * object isn't a dir. + */ + if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS) + (void)clear_nochange_fflags(a); + if (disk_unlink(a->name) == 0) { + /* We removed it, reset cached stat. */ + a->pst = NULL; + } else if (errno == ENOENT) { + /* File didn't exist, that's just as good. */ + } else if (disk_rmdir(a->name) == 0) { + /* It was a dir, but now it's gone. */ + a->pst = NULL; + } else { + /* We tried, but couldn't get rid of it. */ + archive_set_error(&a->archive, errno, + "Could not unlink"); + return(ARCHIVE_FAILED); + } + } + + /* Try creating it first; if this fails, we'll try to recover. */ + en = create_filesystem_object(a); + + if ((en == ENOTDIR || en == ENOENT) + && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) { + wchar_t *full; + /* If the parent dir doesn't exist, try creating it. */ + create_parent_dir(a, a->name); + /* Now try to create the object again. */ + full = __la_win_permissive_name_w(a->name); + if (full == NULL) { + en = EINVAL; + } else { + /* Remove multiple directories such as "a/../b../c" */ + archive_wstrcpy(&(a->_name_data), full); + a->name = a->_name_data.s; + free(full); + en = create_filesystem_object(a); + } + } + + if ((en == ENOENT) && (archive_entry_hardlink(a->entry) != NULL)) { + archive_set_error(&a->archive, en, + "Hard-link target '%s' does not exist.", + archive_entry_hardlink(a->entry)); + return (ARCHIVE_FAILED); + } + + if ((en == EISDIR || en == EEXIST) + && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) { + /* If we're not overwriting, we're done. */ + if (S_ISDIR(a->mode)) { + /* Don't overwrite any settings on existing directories. */ + a->todo = 0; + } + archive_entry_unset_size(a->entry); + return (ARCHIVE_OK); + } + + /* + * Some platforms return EISDIR if you call + * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some + * return EEXIST. POSIX is ambiguous, requiring EISDIR + * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT) + * on an existing item. + */ + if (en == EISDIR) { + /* A dir is in the way of a non-dir, rmdir it. */ + if (disk_rmdir(a->name) != 0) { + archive_set_error(&a->archive, errno, + "Can't remove already-existing dir"); + return (ARCHIVE_FAILED); + } + a->pst = NULL; + /* Try again. */ + en = create_filesystem_object(a); + } else if (en == EEXIST) { + mode_t st_mode; + mode_t lst_mode; + BY_HANDLE_FILE_INFORMATION lst; + /* + * We know something is in the way, but we don't know what; + * we need to find out before we go any further. + */ + int r = 0; + int dirlnk = 0; + + /* + * The SECURE_SYMLINK logic has already removed a + * symlink to a dir if the client wants that. So + * follow the symlink if we're creating a dir. + * If it's not a dir (or it's a broken symlink), + * then don't follow it. + * + * Windows distinguishes file and directory symlinks. + * A file symlink may erroneously point to a directory + * and a directory symlink to a file. Windows does not follow + * such symlinks. We always need both source and target + * information. + */ + r = file_information(a, a->name, &lst, &lst_mode, 1); + if (r != 0) { + archive_set_error(&a->archive, errno, + "Can't stat existing object"); + return (ARCHIVE_FAILED); + } else if (S_ISLNK(lst_mode)) { + if (lst.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + dirlnk = 1; + /* In case of a symlink we need target information */ + r = file_information(a, a->name, &a->st, &st_mode, 0); + if (r != 0) { + a->st = lst; + st_mode = lst_mode; + } + } else { + a->st = lst; + st_mode = lst_mode; + } + + /* + * NO_OVERWRITE_NEWER doesn't apply to directories. + */ + if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER) + && !S_ISDIR(st_mode)) { + if (!older(&(a->st), a->entry)) { + archive_entry_unset_size(a->entry); + return (ARCHIVE_OK); + } + } + + /* If it's our archive, we're done. */ + if (a->skip_file_set && + bhfi_dev(&a->st) == a->skip_file_dev && + bhfi_ino(&a->st) == a->skip_file_ino) { + archive_set_error(&a->archive, 0, + "Refusing to overwrite archive"); + return (ARCHIVE_FAILED); + } + + if (!S_ISDIR(st_mode)) { + if (a->flags & + ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS) { + (void)clear_nochange_fflags(a); + } + if ((a->flags & ARCHIVE_EXTRACT_SAFE_WRITES) && + S_ISREG(st_mode)) { + int fd = la_mktemp(a); + + if (fd == -1) { + la_dosmaperr(GetLastError()); + archive_set_error(&a->archive, errno, + "Can't create temporary file"); + return (ARCHIVE_FAILED); + } + a->fh = (HANDLE)_get_osfhandle(fd); + if (a->fh == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + return (ARCHIVE_FAILED); + } + a->pst = NULL; + en = 0; + } else { + if (dirlnk) { + /* Edge case: dir symlink pointing + * to a file */ + if (disk_rmdir(a->name) != 0) { + archive_set_error(&a->archive, + errno, "Can't unlink " + "directory symlink"); + return (ARCHIVE_FAILED); + } + } else { + if (disk_unlink(a->name) != 0) { + /* A non-dir is in the way, + * unlink it. */ + archive_set_error(&a->archive, + errno, "Can't unlink " + "already-existing object"); + return (ARCHIVE_FAILED); + } + } + a->pst = NULL; + /* Try again. */ + en = create_filesystem_object(a); + } + } else if (!S_ISDIR(a->mode)) { + /* A dir is in the way of a non-dir, rmdir it. */ + if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS) + (void)clear_nochange_fflags(a); + if (disk_rmdir(a->name) != 0) { + archive_set_error(&a->archive, errno, + "Can't remove already-existing dir"); + return (ARCHIVE_FAILED); + } + /* Try again. */ + en = create_filesystem_object(a); + } else { + /* + * There's a dir in the way of a dir. Don't + * waste time with rmdir()/mkdir(), just fix + * up the permissions on the existing dir. + * Note that we don't change perms on existing + * dirs unless _EXTRACT_PERM is specified. + */ + if ((a->mode != st_mode) + && (a->todo & TODO_MODE_FORCE)) + a->deferred |= (a->todo & TODO_MODE); + /* Ownership doesn't need deferred fixup. */ + en = 0; /* Forget the EEXIST. */ + } + } + + if (en) { + /* Everything failed; give up here. */ + archive_set_error(&a->archive, en, "Can't create '%ls'", + a->name); + return (ARCHIVE_FAILED); + } + + a->pst = NULL; /* Cached stat data no longer valid. */ + return (ret); +} + +/* + * Returns 0 if creation succeeds, or else returns errno value from + * the failed system call. Note: This function should only ever perform + * a single system call. + */ +static int +create_filesystem_object(struct archive_write_disk *a) +{ + /* Create the entry. */ + const wchar_t *linkname; + wchar_t *fullname; + mode_t final_mode, mode; + int r; + DWORD attrs = 0; + + /* We identify hard/symlinks according to the link names. */ + /* Since link(2) and symlink(2) don't handle modes, we're done here. */ + linkname = archive_entry_hardlink_w(a->entry); + if (linkname != NULL) { + wchar_t *linkfull, *namefull; + + linkfull = __la_win_permissive_name_w(linkname); + namefull = __la_win_permissive_name_w(a->name); + if (linkfull == NULL || namefull == NULL) { + errno = EINVAL; + r = -1; + } else { + /* + * Unlinking and linking here is really not atomic, + * but doing it right, would require us to construct + * an mktemplink() function, and then use _wrename(). + */ + if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES) { + attrs = GetFileAttributesW(namefull); + if (attrs != INVALID_FILE_ATTRIBUTES) { + if (attrs & FILE_ATTRIBUTE_DIRECTORY) + disk_rmdir(namefull); + else + disk_unlink(namefull); + } + } + r = la_CreateHardLinkW(namefull, linkfull); + if (r == 0) { + la_dosmaperr(GetLastError()); + r = errno; + } else + r = 0; + } + /* + * New cpio and pax formats allow hardlink entries + * to carry data, so we may have to open the file + * for hardlink entries. + * + * If the hardlink was successfully created and + * the archive doesn't have carry data for it, + * consider it to be non-authoritative for meta data. + * This is consistent with GNU tar and BSD pax. + * If the hardlink does carry data, let the last + * archive entry decide ownership. + */ + if (r == 0 && a->filesize <= 0) { + a->todo = 0; + a->deferred = 0; + } else if (r == 0 && a->filesize > 0) { + a->fh = CreateFileW(namefull, GENERIC_WRITE, 0, NULL, + TRUNCATE_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (a->fh == INVALID_HANDLE_VALUE) { + la_dosmaperr(GetLastError()); + r = errno; + } + } + free(linkfull); + free(namefull); + return (r); + } + linkname = archive_entry_symlink_w(a->entry); + if (linkname != NULL) { + /* + * Unlinking and linking here is really not atomic, + * but doing it right, would require us to construct + * an mktemplink() function, and then use _wrename(). + */ + attrs = GetFileAttributesW(a->name); + if (attrs != INVALID_FILE_ATTRIBUTES) { + if (attrs & FILE_ATTRIBUTE_DIRECTORY) + disk_rmdir(a->name); + else + disk_unlink(a->name); + } +#if HAVE_SYMLINK + return symlink(linkname, a->name) ? errno : 0; +#else + errno = 0; + r = la_CreateSymbolicLinkW((const wchar_t *)a->name, linkname, + archive_entry_symlink_type(a->entry)); + if (r == 0) { + if (errno == 0) + la_dosmaperr(GetLastError()); + r = errno; + } else + r = 0; + return (r); +#endif + } + + /* + * The remaining system calls all set permissions, so let's + * try to take advantage of that to avoid an extra chmod() + * call. (Recall that umask is set to zero right now!) + */ + + /* Mode we want for the final restored object (w/o file type bits). */ + final_mode = a->mode & 07777; + /* + * The mode that will actually be restored in this step. Note + * that SUID, SGID, etc, require additional work to ensure + * security, so we never restore them at this point. + */ + mode = final_mode & 0777 & ~a->user_umask; + + switch (a->mode & AE_IFMT) { + default: + /* POSIX requires that we fall through here. */ + /* FALLTHROUGH */ + case AE_IFREG: + a->tmpname = NULL; + fullname = a->name; + /* O_WRONLY | O_CREAT | O_EXCL */ + a->fh = CreateFileW(fullname, GENERIC_WRITE, 0, NULL, + CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); + if (a->fh == INVALID_HANDLE_VALUE && + GetLastError() == ERROR_INVALID_NAME && + fullname == a->name) { + fullname = __la_win_permissive_name_w(a->name); + a->fh = CreateFileW(fullname, GENERIC_WRITE, 0, NULL, + CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); + } + if (a->fh == INVALID_HANDLE_VALUE) { + if (GetLastError() == ERROR_ACCESS_DENIED) { + DWORD attr; + /* Simulate an errno of POSIX system. */ + attr = GetFileAttributesW(fullname); + if (attr == (DWORD)-1) + la_dosmaperr(GetLastError()); + else if (attr & FILE_ATTRIBUTE_DIRECTORY) + errno = EISDIR; + else + errno = EACCES; + } else + la_dosmaperr(GetLastError()); + r = 1; + } else + r = 0; + if (fullname != a->name) + free(fullname); + break; + case AE_IFCHR: + case AE_IFBLK: + /* TODO: Find a better way to warn about our inability + * to restore a block device node. */ + return (EINVAL); + case AE_IFDIR: + mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE; + fullname = a->name; + r = CreateDirectoryW(fullname, NULL); + if (r == 0 && GetLastError() == ERROR_INVALID_NAME && + fullname == a->name) { + fullname = __la_win_permissive_name_w(a->name); + r = CreateDirectoryW(fullname, NULL); + } + if (r != 0) { + r = 0; + /* Defer setting dir times. */ + a->deferred |= (a->todo & TODO_TIMES); + a->todo &= ~TODO_TIMES; + /* Never use an immediate chmod(). */ + /* We can't avoid the chmod() entirely if EXTRACT_PERM + * because of SysV SGID inheritance. */ + if ((mode != final_mode) + || (a->flags & ARCHIVE_EXTRACT_PERM)) + a->deferred |= (a->todo & TODO_MODE); + a->todo &= ~TODO_MODE; + } else { + la_dosmaperr(GetLastError()); + r = -1; + } + if (fullname != a->name) + free(fullname); + break; + case AE_IFIFO: + /* TODO: Find a better way to warn about our inability + * to restore a fifo. */ + return (EINVAL); + } + + /* All the system calls above set errno on failure. */ + if (r) + return (errno); + + /* If we managed to set the final mode, we've avoided a chmod(). */ + if (mode == final_mode) + a->todo &= ~TODO_MODE; + return (0); +} + +/* + * Cleanup function for archive_extract. Mostly, this involves processing + * the fixup list, which is used to address a number of problems: + * * Dir permissions might prevent us from restoring a file in that + * dir, so we restore the dir with minimum 0700 permissions first, + * then correct the mode at the end. + * * Similarly, the act of restoring a file touches the directory + * and changes the timestamp on the dir, so we have to touch-up dir + * timestamps at the end as well. + * * Some file flags can interfere with the restore by, for example, + * preventing the creation of hardlinks to those files. + * * Mac OS extended metadata includes ACLs, so must be deferred on dirs. + * + * Note that tar/cpio do not require that archives be in a particular + * order; there is no way to know when the last file has been restored + * within a directory, so there's no way to optimize the memory usage + * here by fixing up the directory any earlier than the + * end-of-archive. + * + * XXX TODO: Directory ACLs should be restored here, for the same + * reason we set directory perms here. XXX + */ +static int +_archive_write_disk_close(struct archive *_a) +{ + struct archive_write_disk *a = (struct archive_write_disk *)_a; + struct fixup_entry *next, *p; + int ret; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_write_disk_close"); + ret = _archive_write_disk_finish_entry(&a->archive); + + /* Sort dir list so directories are fixed up in depth-first order. */ + p = sort_dir_list(a->fixup_list); + + while (p != NULL) { + a->pst = NULL; /* Mark stat cache as out-of-date. */ + if (p->fixup & TODO_TIMES) { + set_times(a, INVALID_HANDLE_VALUE, p->mode, p->name, + p->atime, p->atime_nanos, + p->birthtime, p->birthtime_nanos, + p->mtime, p->mtime_nanos, + p->ctime, p->ctime_nanos); + } + if (p->fixup & TODO_MODE_BASE) + la_chmod(p->name, p->mode); + if (p->fixup & TODO_ACLS) + set_acls(a, INVALID_HANDLE_VALUE, p->name, &p->acl); + if (p->fixup & TODO_FFLAGS) + set_fflags_platform(p->name, p->fflags_set, 0); + next = p->next; + archive_acl_clear(&p->acl); + free(p->name); + free(p); + p = next; + } + a->fixup_list = NULL; + return (ret); +} + +static int +_archive_write_disk_free(struct archive *_a) +{ + struct archive_write_disk *a; + int ret; + if (_a == NULL) + return (ARCHIVE_OK); + archive_check_magic(_a, ARCHIVE_WRITE_DISK_MAGIC, + ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_disk_free"); + a = (struct archive_write_disk *)_a; + ret = _archive_write_disk_close(&a->archive); + archive_write_disk_set_group_lookup(&a->archive, NULL, NULL, NULL); + archive_write_disk_set_user_lookup(&a->archive, NULL, NULL, NULL); + archive_entry_free(a->entry); + archive_wstring_free(&a->_name_data); + archive_wstring_free(&a->_tmpname_data); + archive_string_free(&a->archive.error_string); + archive_wstring_free(&a->path_safe); + a->archive.magic = 0; + __archive_clean(&a->archive); + free(a); + return (ret); +} + +/* + * Simple O(n log n) merge sort to order the fixup list. In + * particular, we want to restore dir timestamps depth-first. + */ +static struct fixup_entry * +sort_dir_list(struct fixup_entry *p) +{ + struct fixup_entry *a, *b, *t; + + if (p == NULL) + return (NULL); + /* A one-item list is already sorted. */ + if (p->next == NULL) + return (p); + + /* Step 1: split the list. */ + t = p; + a = p->next->next; + while (a != NULL) { + /* Step a twice, t once. */ + a = a->next; + if (a != NULL) + a = a->next; + t = t->next; + } + /* Now, t is at the mid-point, so break the list here. */ + b = t->next; + t->next = NULL; + a = p; + + /* Step 2: Recursively sort the two sub-lists. */ + a = sort_dir_list(a); + b = sort_dir_list(b); + + /* Step 3: Merge the returned lists. */ + /* Pick the first element for the merged list. */ + if (wcscmp(a->name, b->name) > 0) { + t = p = a; + a = a->next; + } else { + t = p = b; + b = b->next; + } + + /* Always put the later element on the list first. */ + while (a != NULL && b != NULL) { + if (wcscmp(a->name, b->name) > 0) { + t->next = a; + a = a->next; + } else { + t->next = b; + b = b->next; + } + t = t->next; + } + + /* Only one list is non-empty, so just splice it on. */ + if (a != NULL) + t->next = a; + if (b != NULL) + t->next = b; + + return (p); +} + +/* + * Returns a new, initialized fixup entry. + * + * TODO: Reduce the memory requirements for this list by using a tree + * structure rather than a simple list of names. + */ +static struct fixup_entry * +new_fixup(struct archive_write_disk *a, const wchar_t *pathname) +{ + struct fixup_entry *fe; + + fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry)); + if (fe == NULL) + return (NULL); + fe->next = a->fixup_list; + a->fixup_list = fe; + fe->fixup = 0; + fe->name = _wcsdup(pathname); + fe->fflags_set = 0; + return (fe); +} + +/* + * Returns a fixup structure for the current entry. + */ +static struct fixup_entry * +current_fixup(struct archive_write_disk *a, const wchar_t *pathname) +{ + if (a->current_fixup == NULL) + a->current_fixup = new_fixup(a, pathname); + return (a->current_fixup); +} + +/* + * TODO: The deep-directory support bypasses this; disable deep directory + * support if we're doing symlink checks. + */ +/* + * TODO: Someday, integrate this with the deep dir support; they both + * scan the path and both can be optimized by comparing against other + * recent paths. + */ +static int +check_symlinks(struct archive_write_disk *a) +{ + wchar_t *pn, *p; + wchar_t c; + int r; + BY_HANDLE_FILE_INFORMATION st; + mode_t st_mode; + + /* + * Guard against symlink tricks. Reject any archive entry whose + * destination would be altered by a symlink. + */ + /* Whatever we checked last time doesn't need to be re-checked. */ + pn = a->name; + p = a->path_safe.s; + while ((*pn != '\0') && (*p == *pn)) + ++p, ++pn; + /* Skip leading backslashes */ + while (*pn == '\\') + ++pn; + c = pn[0]; + /* Keep going until we've checked the entire name. */ + while (pn[0] != '\0' && (pn[0] != '\\' || pn[1] != '\0')) { + /* Skip the next path element. */ + while (*pn != '\0' && *pn != '\\') + ++pn; + c = pn[0]; + pn[0] = '\0'; + /* Check that we haven't hit a symlink. */ + r = file_information(a, a->name, &st, &st_mode, 1); + if (r != 0) { + /* We've hit a dir that doesn't exist; stop now. */ + if (errno == ENOENT) + break; + } else if (S_ISLNK(st_mode)) { + if (c == '\0') { + /* + * Last element is a file or directory symlink. + * Remove it so we can overwrite it with the + * item being extracted. + */ + if (a->flags & + ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS) { + (void)clear_nochange_fflags(a); + } + if (st.dwFileAttributes & + FILE_ATTRIBUTE_DIRECTORY) { + r = disk_rmdir(a->name); + } else { + r = disk_unlink(a->name); + } + if (r) { + archive_set_error(&a->archive, errno, + "Could not remove symlink %ls", + a->name); + pn[0] = c; + return (ARCHIVE_FAILED); + } + a->pst = NULL; + /* + * Even if we did remove it, a warning + * is in order. The warning is silly, + * though, if we're just replacing one + * symlink with another symlink. + */ + if (!S_ISLNK(a->mode)) { + archive_set_error(&a->archive, 0, + "Removing symlink %ls", + a->name); + } + /* Symlink gone. No more problem! */ + pn[0] = c; + return (0); + } else if (a->flags & ARCHIVE_EXTRACT_UNLINK) { + /* User asked us to remove problems. */ + if (a->flags & + ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS) { + (void)clear_nochange_fflags(a); + } + if (st.dwFileAttributes & + FILE_ATTRIBUTE_DIRECTORY) { + r = disk_rmdir(a->name); + } else { + r = disk_unlink(a->name); + } + if (r != 0) { + archive_set_error(&a->archive, 0, + "Cannot remove intervening " + "symlink %ls", a->name); + pn[0] = c; + return (ARCHIVE_FAILED); + } + a->pst = NULL; + } else { + archive_set_error(&a->archive, 0, + "Cannot extract through symlink %ls", + a->name); + pn[0] = c; + return (ARCHIVE_FAILED); + } + } + pn[0] = c; + pn++; + } + pn[0] = c; + /* We've checked and/or cleaned the whole path, so remember it. */ + archive_wstrcpy(&a->path_safe, a->name); + return (ARCHIVE_OK); +} + +static int +guidword(wchar_t *p, int n) +{ + int i; + + for (i = 0; i < n; i++) { + if ((*p >= L'0' && *p <= L'9') || + (*p >= L'a' && *p <= L'f') || + (*p >= L'A' && *p <= L'F')) + p++; + else + return (-1); + } + return (0); +} + +/* + * Canonicalize the pathname. In particular, this strips duplicate + * '\' characters, '.' elements, and trailing '\'. It also raises an + * error for an empty path, a trailing '..' or (if _SECURE_NODOTDOT is + * set) any '..' in the path. + */ +static int +cleanup_pathname(struct archive_write_disk *a) +{ + wchar_t *dest, *src, *p, *top; + wchar_t separator = L'\0'; + + p = a->name; + if (*p == L'\0') { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid empty pathname"); + return (ARCHIVE_FAILED); + } + + /* Replace '/' by '\' */ + for (; *p != L'\0'; p++) { + if (*p == L'/') + *p = L'\\'; + } + p = a->name; + + /* Skip leading "\\.\" or "\\?\" or "\\?\UNC\" or + * "\\?\Volume{GUID}\" + * (absolute path prefixes used by Windows API) */ + if (p[0] == L'\\' && p[1] == L'\\' && + (p[2] == L'.' || p[2] == L'?') && p[3] == L'\\') + { + /* A path begin with "\\?\UNC\" */ + if (p[2] == L'?' && + (p[4] == L'U' || p[4] == L'u') && + (p[5] == L'N' || p[5] == L'n') && + (p[6] == L'C' || p[6] == L'c') && + p[7] == L'\\') + p += 8; + /* A path begin with "\\?\Volume{GUID}\" */ + else if (p[2] == L'?' && + (p[4] == L'V' || p[4] == L'v') && + (p[5] == L'O' || p[5] == L'o') && + (p[6] == L'L' || p[6] == L'l') && + (p[7] == L'U' || p[7] == L'u') && + (p[8] == L'M' || p[8] == L'm') && + (p[9] == L'E' || p[9] == L'e') && + p[10] == L'{') { + if (guidword(p+11, 8) == 0 && p[19] == L'-' && + guidword(p+20, 4) == 0 && p[24] == L'-' && + guidword(p+25, 4) == 0 && p[29] == L'-' && + guidword(p+30, 4) == 0 && p[34] == L'-' && + guidword(p+35, 12) == 0 && p[47] == L'}' && + p[48] == L'\\') + p += 49; + else + p += 4; + /* A path begin with "\\.\PhysicalDriveX" */ + } else if (p[2] == L'.' && + (p[4] == L'P' || p[4] == L'p') && + (p[5] == L'H' || p[5] == L'h') && + (p[6] == L'Y' || p[6] == L'y') && + (p[7] == L'S' || p[7] == L's') && + (p[8] == L'I' || p[8] == L'i') && + (p[9] == L'C' || p[9] == L'c') && + (p[9] == L'A' || p[9] == L'a') && + (p[9] == L'L' || p[9] == L'l') && + (p[9] == L'D' || p[9] == L'd') && + (p[9] == L'R' || p[9] == L'r') && + (p[9] == L'I' || p[9] == L'i') && + (p[9] == L'V' || p[9] == L'v') && + (p[9] == L'E' || p[9] == L'e') && + (p[10] >= L'0' && p[10] <= L'9') && + p[11] == L'\0') { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Path is a physical drive name"); + return (ARCHIVE_FAILED); + } else + p += 4; + } + + /* Skip leading drive letter from archives created + * on Windows. */ + if (((p[0] >= L'a' && p[0] <= L'z') || + (p[0] >= L'A' && p[0] <= L'Z')) && + p[1] == L':') { + if (p[2] == L'\0') { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Path is a drive name"); + return (ARCHIVE_FAILED); + } + if (p[2] == L'\\') + p += 2; + } + + top = dest = src = p; + /* Rewrite the path name if its character is a unusable. */ + for (; *p != L'\0'; p++) { + if (*p == L':' || *p == L'*' || *p == L'?' || *p == L'"' || + *p == L'<' || *p == L'>' || *p == L'|') + *p = L'_'; + } + /* Skip leading '\'. */ + if (*src == L'\\') + separator = *src++; + + /* Scan the pathname one element at a time. */ + for (;;) { + /* src points to first char after '\' */ + if (src[0] == L'\0') { + break; + } else if (src[0] == L'\\') { + /* Found '\\'('//'), ignore second one. */ + src++; + continue; + } else if (src[0] == L'.') { + if (src[1] == L'\0') { + /* Ignore trailing '.' */ + break; + } else if (src[1] == L'\\') { + /* Skip '.\'. */ + src += 2; + continue; + } else if (src[1] == L'.') { + if (src[2] == L'\\' || src[2] == L'\0') { + /* Conditionally warn about '..' */ + if (a->flags & + ARCHIVE_EXTRACT_SECURE_NODOTDOT) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Path contains '..'"); + return (ARCHIVE_FAILED); + } + } + /* + * Note: Under no circumstances do we + * remove '..' elements. In + * particular, restoring + * '\foo\..\bar\' should create the + * 'foo' dir as a side-effect. + */ + } + } + + /* Copy current element, including leading '\'. */ + if (separator) + *dest++ = L'\\'; + while (*src != L'\0' && *src != L'\\') { + *dest++ = *src++; + } + + if (*src == L'\0') + break; + + /* Skip '\' separator. */ + separator = *src++; + } + /* + * We've just copied zero or more path elements, not including the + * final '\'. + */ + if (dest == top) { + /* + * Nothing got copied. The path must have been something + * like '.' or '\' or './' or '/././././/./'. + */ + if (separator) + *dest++ = L'\\'; + else + *dest++ = L'.'; + } + /* Terminate the result. */ + *dest = L'\0'; + return (ARCHIVE_OK); +} + +/* + * Create the parent directory of the specified path, assuming path + * is already in mutable storage. + */ +static int +create_parent_dir(struct archive_write_disk *a, wchar_t *path) +{ + wchar_t *slash; + int r; + + /* Remove tail element to obtain parent name. */ + slash = wcsrchr(path, L'\\'); + if (slash == NULL) + return (ARCHIVE_OK); + *slash = L'\0'; + r = create_dir(a, path); + *slash = L'\\'; + return (r); +} + +/* + * Create the specified dir, recursing to create parents as necessary. + * + * Returns ARCHIVE_OK if the path exists when we're done here. + * Otherwise, returns ARCHIVE_FAILED. + * Assumes path is in mutable storage; path is unchanged on exit. + */ +static int +create_dir(struct archive_write_disk *a, wchar_t *path) +{ + BY_HANDLE_FILE_INFORMATION st; + struct fixup_entry *le; + wchar_t *slash, *base, *full; + mode_t mode_final, mode, st_mode; + int r; + + /* Check for special names and just skip them. */ + slash = wcsrchr(path, L'\\'); + if (slash == NULL) + base = path; + else + base = slash + 1; + + if (base[0] == L'\0' || + (base[0] == L'.' && base[1] == L'\0') || + (base[0] == L'.' && base[1] == L'.' && base[2] == L'\0')) { + /* Don't bother trying to create null path, '.', or '..'. */ + if (slash != NULL) { + *slash = L'\0'; + r = create_dir(a, path); + *slash = L'\\'; + return (r); + } + return (ARCHIVE_OK); + } + + /* + * Yes, this should be stat() and not lstat(). Using lstat() + * here loses the ability to extract through symlinks. Also note + * that this should not use the a->st cache. + */ + if (file_information(a, path, &st, &st_mode, 0) == 0) { + if (S_ISDIR(st_mode)) + return (ARCHIVE_OK); + if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) { + archive_set_error(&a->archive, EEXIST, + "Can't create directory '%ls'", path); + return (ARCHIVE_FAILED); + } + if (disk_unlink(path) != 0) { + archive_set_error(&a->archive, errno, + "Can't create directory '%ls': " + "Conflicting file cannot be removed", + path); + return (ARCHIVE_FAILED); + } + } else if (errno != ENOENT && errno != ENOTDIR) { + /* Stat failed? */ + archive_set_error(&a->archive, errno, + "Can't test directory '%ls'", path); + return (ARCHIVE_FAILED); + } else if (slash != NULL) { + *slash = '\0'; + r = create_dir(a, path); + *slash = '\\'; + if (r != ARCHIVE_OK) + return (r); + } + + /* + * Mode we want for the final restored directory. Per POSIX, + * implicitly-created dirs must be created obeying the umask. + * There's no mention whether this is different for privileged + * restores (which the rest of this code handles by pretending + * umask=0). I've chosen here to always obey the user's umask for + * implicit dirs, even if _EXTRACT_PERM was specified. + */ + mode_final = DEFAULT_DIR_MODE & ~a->user_umask; + /* Mode we want on disk during the restore process. */ + mode = mode_final; + mode |= MINIMUM_DIR_MODE; + mode &= MAXIMUM_DIR_MODE; + /* + * Apply __la_win_permissive_name_w to path in order to + * remove '../' path string. + */ + full = __la_win_permissive_name_w(path); + if (full == NULL) + errno = EINVAL; + else if (CreateDirectoryW(full, NULL) != 0) { + if (mode != mode_final) { + le = new_fixup(a, path); + le->fixup |=TODO_MODE_BASE; + le->mode = mode_final; + } + free(full); + return (ARCHIVE_OK); + } else { + la_dosmaperr(GetLastError()); + } + free(full); + + /* + * Without the following check, a/b/../b/c/d fails at the + * second visit to 'b', so 'd' can't be created. Note that we + * don't add it to the fixup list here, as it's already been + * added. + */ + if (file_information(a, path, &st, &st_mode, 0) == 0 && + S_ISDIR(st_mode)) + return (ARCHIVE_OK); + + archive_set_error(&a->archive, errno, "Failed to create dir '%ls'", + path); + return (ARCHIVE_FAILED); +} + +/* + * Note: Although we can skip setting the user id if the desired user + * id matches the current user, we cannot skip setting the group, as + * many systems set the gid based on the containing directory. So + * we have to perform a chown syscall if we want to set the SGID + * bit. (The alternative is to stat() and then possibly chown(); it's + * more efficient to skip the stat() and just always chown().) Note + * that a successful chown() here clears the TODO_SGID_CHECK bit, which + * allows set_mode to skip the stat() check for the GID. + */ +static int +set_ownership(struct archive_write_disk *a) +{ +/* unfortunately, on win32 there is no 'root' user with uid 0, + so we just have to try the chown and see if it works */ + + /* If we know we can't change it, don't bother trying. */ + if (a->user_uid != 0 && a->user_uid != a->uid) { + archive_set_error(&a->archive, errno, + "Can't set UID=%jd", (intmax_t)a->uid); + return (ARCHIVE_WARN); + } + + archive_set_error(&a->archive, errno, + "Can't set user=%jd/group=%jd for %ls", + (intmax_t)a->uid, (intmax_t)a->gid, a->name); + return (ARCHIVE_WARN); +} + +static int +set_times(struct archive_write_disk *a, + HANDLE h, int mode, const wchar_t *name, + time_t atime, long atime_nanos, + time_t birthtime, long birthtime_nanos, + time_t mtime, long mtime_nanos, + time_t ctime_sec, long ctime_nanos) +{ +#define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000) +#define WINTIME(sec, nsec) ((Int32x32To64(sec, 10000000) + EPOC_TIME)\ + + (((nsec)/1000)*10)) + + HANDLE hw = 0; + ULARGE_INTEGER wintm; + FILETIME *pfbtime; + FILETIME fatime, fbtime, fmtime; + + (void)ctime_sec; /* UNUSED */ + (void)ctime_nanos; /* UNUSED */ + + if (h != INVALID_HANDLE_VALUE) { + hw = NULL; + } else { + wchar_t *ws; + + if (S_ISLNK(mode)) + return (ARCHIVE_OK); + ws = __la_win_permissive_name_w(name); + if (ws == NULL) + goto settimes_failed; + hw = CreateFileW(ws, FILE_WRITE_ATTRIBUTES, + 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); + free(ws); + if (hw == INVALID_HANDLE_VALUE) + goto settimes_failed; + h = hw; + } + + wintm.QuadPart = WINTIME(atime, atime_nanos); + fatime.dwLowDateTime = wintm.LowPart; + fatime.dwHighDateTime = wintm.HighPart; + wintm.QuadPart = WINTIME(mtime, mtime_nanos); + fmtime.dwLowDateTime = wintm.LowPart; + fmtime.dwHighDateTime = wintm.HighPart; + /* + * SetFileTime() supports birthtime. + */ + if (birthtime > 0 || birthtime_nanos > 0) { + wintm.QuadPart = WINTIME(birthtime, birthtime_nanos); + fbtime.dwLowDateTime = wintm.LowPart; + fbtime.dwHighDateTime = wintm.HighPart; + pfbtime = &fbtime; + } else + pfbtime = NULL; + if (SetFileTime(h, pfbtime, &fatime, &fmtime) == 0) + goto settimes_failed; + CloseHandle(hw); + return (ARCHIVE_OK); + +settimes_failed: + CloseHandle(hw); + archive_set_error(&a->archive, EINVAL, "Can't restore time"); + return (ARCHIVE_WARN); +} + +static int +set_times_from_entry(struct archive_write_disk *a) +{ + time_t atime, birthtime, mtime, ctime_sec; + long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec; + + /* Suitable defaults. */ + atime = birthtime = mtime = ctime_sec = a->start_time; + atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0; + + /* If no time was provided, we're done. */ + if (!archive_entry_atime_is_set(a->entry) + && !archive_entry_birthtime_is_set(a->entry) + && !archive_entry_mtime_is_set(a->entry)) + return (ARCHIVE_OK); + + if (archive_entry_atime_is_set(a->entry)) { + atime = archive_entry_atime(a->entry); + atime_nsec = archive_entry_atime_nsec(a->entry); + } + if (archive_entry_birthtime_is_set(a->entry)) { + birthtime = archive_entry_birthtime(a->entry); + birthtime_nsec = archive_entry_birthtime_nsec(a->entry); + } + if (archive_entry_mtime_is_set(a->entry)) { + mtime = archive_entry_mtime(a->entry); + mtime_nsec = archive_entry_mtime_nsec(a->entry); + } + if (archive_entry_ctime_is_set(a->entry)) { + ctime_sec = archive_entry_ctime(a->entry); + ctime_nsec = archive_entry_ctime_nsec(a->entry); + } + + return set_times(a, a->fh, a->mode, a->name, + atime, atime_nsec, + birthtime, birthtime_nsec, + mtime, mtime_nsec, + ctime_sec, ctime_nsec); +} + +static int +set_mode(struct archive_write_disk *a, int mode) +{ + int r = ARCHIVE_OK; + mode &= 07777; /* Strip off file type bits. */ + + if (a->todo & TODO_SGID_CHECK) { + /* + * If we don't know the GID is right, we must stat() + * to verify it. We can't just check the GID of this + * process, since systems sometimes set GID from + * the enclosing dir or based on ACLs. + */ + if ((r = lazy_stat(a)) != ARCHIVE_OK) + return (r); + if (0 != a->gid) { + mode &= ~ S_ISGID; + } + /* While we're here, double-check the UID. */ + if (0 != a->uid + && (a->todo & TODO_SUID)) { + mode &= ~ S_ISUID; + } + a->todo &= ~TODO_SGID_CHECK; + a->todo &= ~TODO_SUID_CHECK; + } else if (a->todo & TODO_SUID_CHECK) { + /* + * If we don't know the UID is right, we can just check + * the user, since all systems set the file UID from + * the process UID. + */ + if (a->user_uid != a->uid) { + mode &= ~ S_ISUID; + } + a->todo &= ~TODO_SUID_CHECK; + } + + if (S_ISLNK(a->mode)) { +#ifdef HAVE_LCHMOD + /* + * If this is a symlink, use lchmod(). If the + * platform doesn't support lchmod(), just skip it. A + * platform that doesn't provide a way to set + * permissions on symlinks probably ignores + * permissions on symlinks, so a failure here has no + * impact. + */ + if (lchmod(a->name, mode) != 0) { + archive_set_error(&a->archive, errno, + "Can't set permissions to 0%o", (int)mode); + r = ARCHIVE_WARN; + } +#endif + } else if (!S_ISDIR(a->mode)) { + /* + * If it's not a symlink and not a dir, then use + * fchmod() or chmod(), depending on whether we have + * an fd. Dirs get their perms set during the + * post-extract fixup, which is handled elsewhere. + */ +#ifdef HAVE_FCHMOD + if (a->fd >= 0) { + if (fchmod(a->fd, mode) != 0) { + archive_set_error(&a->archive, errno, + "Can't set permissions to 0%o", (int)mode); + r = ARCHIVE_WARN; + } + } else +#endif + /* If this platform lacks fchmod(), then + * we'll just use chmod(). */ + if (la_chmod(a->name, mode) != 0) { + archive_set_error(&a->archive, errno, + "Can't set permissions to 0%o", (int)mode); + r = ARCHIVE_WARN; + } + } + return (r); +} + +static int set_fflags_platform(const wchar_t *name, unsigned long fflags_set, + unsigned long fflags_clear) +{ + DWORD oldflags, newflags; + wchar_t *fullname; + + const DWORD settable_flags = + FILE_ATTRIBUTE_ARCHIVE | + FILE_ATTRIBUTE_HIDDEN | + FILE_ATTRIBUTE_NORMAL | + FILE_ATTRIBUTE_NOT_CONTENT_INDEXED | + FILE_ATTRIBUTE_OFFLINE | + FILE_ATTRIBUTE_READONLY | + FILE_ATTRIBUTE_SYSTEM | + FILE_ATTRIBUTE_TEMPORARY; + + oldflags = GetFileAttributesW(name); + if (oldflags == (DWORD)-1 && + GetLastError() == ERROR_INVALID_NAME) { + fullname = __la_win_permissive_name_w(name); + oldflags = GetFileAttributesW(fullname); + } + if (oldflags == (DWORD)-1) { + la_dosmaperr(GetLastError()); + return (ARCHIVE_WARN); + } + newflags = ((oldflags & ~fflags_clear) | fflags_set) & settable_flags; + if(SetFileAttributesW(name, newflags) == 0) + return (ARCHIVE_WARN); + return (ARCHIVE_OK); +} + +static int +clear_nochange_fflags(struct archive_write_disk *a) +{ + return (set_fflags_platform(a->name, 0, FILE_ATTRIBUTE_READONLY)); +} + +static int +set_fflags(struct archive_write_disk *a) +{ + unsigned long set, clear; + + if (a->todo & TODO_FFLAGS) { + archive_entry_fflags(a->entry, &set, &clear); + if (set == 0 && clear == 0) + return (ARCHIVE_OK); + return (set_fflags_platform(a->name, set, clear)); + + } + return (ARCHIVE_OK); +} + +/* Default empty function body to satisfy mainline code. */ +static int +set_acls(struct archive_write_disk *a, HANDLE h, const wchar_t *name, + struct archive_acl *acl) +{ + (void)a; /* UNUSED */ + (void)h; /* UNUSED */ + (void)name; /* UNUSED */ + (void)acl; /* UNUSED */ + return (ARCHIVE_OK); +} + +/* + * Restore extended attributes - stub implementation for unsupported systems + */ +static int +set_xattrs(struct archive_write_disk *a) +{ + static int warning_done = 0; + + /* If there aren't any extended attributes, then it's okay not + * to extract them, otherwise, issue a single warning. */ + if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) { + warning_done = 1; + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Cannot restore extended attributes on this system"); + return (ARCHIVE_WARN); + } + /* Warning was already emitted; suppress further warnings. */ + return (ARCHIVE_OK); +} + +static void +fileTimeToUtc(const FILETIME *filetime, time_t *t, long *ns) +{ + ULARGE_INTEGER utc; + + utc.HighPart = filetime->dwHighDateTime; + utc.LowPart = filetime->dwLowDateTime; + if (utc.QuadPart >= EPOC_TIME) { + utc.QuadPart -= EPOC_TIME; + /* milli seconds base */ + *t = (time_t)(utc.QuadPart / 10000000); + /* nano seconds base */ + *ns = (long)(utc.QuadPart % 10000000) * 100; + } else { + *t = 0; + *ns = 0; + } +} +/* + * Test if file on disk is older than entry. + */ +static int +older(BY_HANDLE_FILE_INFORMATION *st, struct archive_entry *entry) +{ + time_t sec; + long nsec; + + fileTimeToUtc(&st->ftLastWriteTime, &sec, &nsec); + /* First, test the seconds and return if we have a definite answer. */ + /* Definitely older. */ + if (sec < archive_entry_mtime(entry)) + return (1); + /* Definitely younger. */ + if (sec > archive_entry_mtime(entry)) + return (0); + if (nsec < archive_entry_mtime_nsec(entry)) + return (1); + /* Same age or newer, so not older. */ + return (0); +} + +#endif /* _WIN32 && !__CYGWIN__ */ + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_filter.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_filter.3 new file mode 100644 index 0000000000..c83eb77b6a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_filter.3 @@ -0,0 +1,134 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd August 14, 2014 +.Dt ARCHIVE_WRITE_FILTER 3 +.Os +.Sh NAME +.Nm archive_write_add_filter_b64encode , +.Nm archive_write_add_filter_by_name , +.Nm archive_write_add_filter_bzip2 , +.Nm archive_write_add_filter_compress , +.Nm archive_write_add_filter_grzip , +.Nm archive_write_add_filter_gzip , +.Nm archive_write_add_filter_lrzip , +.Nm archive_write_add_filter_lz4 , +.Nm archive_write_add_filter_lzip , +.Nm archive_write_add_filter_lzma , +.Nm archive_write_add_filter_lzop , +.Nm archive_write_add_filter_none , +.Nm archive_write_add_filter_program , +.Nm archive_write_add_filter_uuencode , +.Nm archive_write_add_filter_xz , +.Nm archive_write_add_filter_zstd +.Nd functions enabling output filters +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fn archive_write_add_filter_b64encode "struct archive *" +.Ft int +.Fn archive_write_add_filter_bzip2 "struct archive *" +.Ft int +.Fn archive_write_add_filter_compress "struct archive *" +.Ft int +.Fn archive_write_add_filter_grzip "struct archive *" +.Ft int +.Fn archive_write_add_filter_gzip "struct archive *" +.Ft int +.Fn archive_write_add_filter_lrzip "struct archive *" +.Ft int +.Fn archive_write_add_filter_lz4 "struct archive *" +.Ft int +.Fn archive_write_add_filter_lzip "struct archive *" +.Ft int +.Fn archive_write_add_filter_lzma "struct archive *" +.Ft int +.Fn archive_write_add_filter_lzop "struct archive *" +.Ft int +.Fn archive_write_add_filter_none "struct archive *" +.Ft int +.Fn archive_write_add_filter_program "struct archive *" "const char * cmd" +.Ft int +.Fn archive_write_add_filter_uuencode "struct archive *" +.Ft int +.Fn archive_write_add_filter_xz "struct archive *" +.Ft int +.Fn archive_write_add_filter_zstd "struct archive *" +.Sh DESCRIPTION +.Bl -tag -width indent +.It Xo +.Fn archive_write_add_filter_bzip2 , +.Fn archive_write_add_filter_compress , +.Fn archive_write_add_filter_grzip , +.Fn archive_write_add_filter_gzip , +.Fn archive_write_add_filter_lrzip , +.Fn archive_write_add_filter_lz4 , +.Fn archive_write_add_filter_lzip , +.Fn archive_write_add_filter_lzma , +.Fn archive_write_add_filter_lzop , +.Fn archive_write_add_filter_xz , +.Fn archive_write_add_filter_zstd , +.Xc +The resulting archive will be compressed as specified. +Note that the compressed output is always properly blocked. +.It Xo +.Fn archive_write_add_filter_b64encode , +.Fn archive_write_add_filter_uuencode , +.Xc +The output will be encoded as specified. +The encoded output is always properly blocked. +.It Fn archive_write_add_filter_none +This is never necessary. +It is provided only for backwards compatibility. +.It Fn archive_write_add_filter_program +The archive will be fed into the specified compression program. +The output of that program is blocked and written to the client +write callbacks. +.El +.Sh RETURN VALUES +These functions return +.Cm ARCHIVE_OK +on success, or +.Cm ARCHIVE_FATAL . +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_write 3 , +.Xr archive_write_format 3 , +.Xr archive_write_set_options 3 , +.Xr libarchive 3 , +.Xr cpio 5 , +.Xr mtree 5 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_finish_entry.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_finish_entry.3 new file mode 100644 index 0000000000..5797e16a6d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_finish_entry.3 @@ -0,0 +1,79 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 28, 2017 +.Dt ARCHIVE_WRITE_FINISH_ENTRY 3 +.Os +.Sh NAME +.Nm archive_write_finish_entry +.Nd functions for creating archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fn archive_write_finish_entry "struct archive *" +.Sh DESCRIPTION +Close out the entry just written. +In particular, this writes out the final padding required by some formats. +Ordinarily, clients never need to call this, as it +is called automatically by +.Fn archive_write_header +and +.Fn archive_write_close +as needed. +For +.Tn archive_write_disk +handles, this flushes pending file attribute changes like modification time. +.\" .Sh EXAMPLE +.Sh RETURN VALUES +This function returns +.Cm ARCHIVE_OK +on success, or one of several non-zero +error codes for errors. +Specific error codes include: +.Cm ARCHIVE_RETRY +for operations that might succeed if retried, +.Cm ARCHIVE_WARN +for unusual conditions that do not prevent further operations, and +.Cm ARCHIVE_FATAL +for serious errors that make remaining operations impossible. +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_write_data 3 , +.Xr archive_write_set_options 3 , +.Xr libarchive 3 , +.Xr cpio 5 , +.Xr mtree 5 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_format.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_format.3 new file mode 100644 index 0000000000..47a7403396 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_format.3 @@ -0,0 +1,175 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 14, 2013 +.Dt ARCHIVE_WRITE_FORMAT 3 +.Os +.Sh NAME +.Nm archive_write_set_format , +.Nm archive_write_set_format_7zip , +.Nm archive_write_set_format_ar , +.Nm archive_write_set_format_ar_bsd , +.Nm archive_write_set_format_ar_svr4 , +.Nm archive_write_set_format_by_name , +.Nm archive_write_set_format_cpio , +.Nm archive_write_set_format_cpio_newc , +.Nm archive_write_set_format_filter_by_ext , +.Nm archive_write_set_format_filter_by_ext_def , +.Nm archive_write_set_format_gnutar , +.Nm archive_write_set_format_iso9660 , +.Nm archive_write_set_format_mtree , +.Nm archive_write_set_format_mtree_classic , +.Nm archive_write_set_format_mtree_default , +.Nm archive_write_set_format_pax , +.Nm archive_write_set_format_pax_restricted , +.Nm archive_write_set_format_raw , +.Nm archive_write_set_format_shar , +.Nm archive_write_set_format_shar_dump , +.Nm archive_write_set_format_ustar , +.Nm archive_write_set_format_v7tar , +.Nm archive_write_set_format_warc , +.Nm archive_write_set_format_xar , +.Nm archive_write_set_format_zip +.Nd functions for creating archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fn archive_write_set_format "struct archive *" "int code" +.Ft int +.Fn archive_write_set_format_7zip "struct archive *" +.Ft int +.Fn archive_write_set_format_ar "struct archive *" +.Ft int +.Fn archive_write_set_format_ar_bsd "struct archive *" +.Ft int +.Fn archive_write_set_format_ar_svr4 "struct archive *" +.Ft int +.Fn archive_write_set_format_by_name "struct archive *" "const char *name" +.Ft int +.Fn archive_write_set_format_cpio "struct archive *" +.Ft int +.Fn archive_write_set_format_cpio_newc "struct archive *" +.Ft int +.Fn archive_write_set_format_filter_by_ext "struct archive *" "const char *filename" +.Ft int +.Fn archive_write_set_format_filter_by_ext_def "struct archive *" "const char *filename" "const char *def_ext" +.Ft int +.Fn archive_write_set_format_gnutar "struct archive *" +.Ft int +.Fn archive_write_set_format_iso9660 "struct archive *" +.Ft int +.Fn archive_write_set_format_mtree "struct archive *" +.Ft int +.Fn archive_write_set_format_pax "struct archive *" +.Ft int +.Fn archive_write_set_format_pax_restricted "struct archive *" +.Ft int +.Fn archive_write_set_format_raw "struct archive *" +.Ft int +.Fn archive_write_set_format_shar "struct archive *" +.Ft int +.Fn archive_write_set_format_shar_dump "struct archive *" +.Ft int +.Fn archive_write_set_format_ustar "struct archive *" +.Ft int +.Fn archive_write_set_format_v7tar "struct archive *" +.Ft int +.Fn archive_write_set_format_warc "struct archive *" +.Ft int +.Fn archive_write_set_format_xar "struct archive *" +.Ft int +.Fn archive_write_set_format_zip "struct archive *" +.Sh DESCRIPTION +These functions set the format that will be used for the archive. +.Pp +The library can write a variety of common archive formats. +.Bl -tag -width indent +.It Fn archive_write_set_format +Sets the format based on the format code (see +.Pa archive.h +for the full list of format codes). +In particular, this can be used in conjunction with +.Fn archive_format +to create a new archive with the same format as an existing archive. +.It Fn archive_write_set_format_by_name +Sets the corresponding format based on the common name. +.It Xo +.Fn archive_write_set_format_filter_by_ext , +.Fn archive_write_set_format_filter_by_ext_def +.Xc +Sets both filters and format based on the output filename. +Supported extensions: .7z, .zip, .jar, .cpio, .iso, .a, .ar, .tar, .tgz, .tar.gz, .tar.bz2, .tar.xz +.It Xo +.Fn archive_write_set_format_7zip +.Fn archive_write_set_format_ar_bsd , +.Fn archive_write_set_format_ar_svr4 , +.Fn archive_write_set_format_cpio +.Fn archive_write_set_format_cpio_newc +.Fn archive_write_set_format_gnutar +.Fn archive_write_set_format_iso9660 +.Fn archive_write_set_format_mtree +.Fn archive_write_set_format_mtree_classic +.Fn archive_write_set_format_pax +.Fn archive_write_set_format_pax_restricted +.Fn archive_write_set_format_raw +.Fn archive_write_set_format_shar +.Fn archive_write_set_format_shar_dump +.Fn archive_write_set_format_ustar +.Fn archive_write_set_format_v7tar +.Fn archive_write_set_format_warc +.Fn archive_write_set_format_xar +.Fn archive_write_set_format_zip +.Xc +Set the format as specified. +More details on the formats supported by libarchive can be found in the +.Xr libarchive-formats 5 +manual page. +.El +.\" +.Sh RETURN VALUES +These functions return +.Cm ARCHIVE_OK +on success, or +.Cm ARCHIVE_FATAL . +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_write 3 , +.Xr archive_write_set_options 3 , +.Xr libarchive 3 , +.Xr cpio 5 , +.Xr libarchive-formats 5 , +.Xr mtree 5 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_free.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_free.3 new file mode 100644 index 0000000000..5210e2a633 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_free.3 @@ -0,0 +1,96 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_WRITE_FREE 3 +.Os +.Sh NAME +.Nm archive_write_fail , +.Nm archive_write_close , +.Nm archive_write_finish , +.Nm archive_write_free +.Nd functions for creating archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fn archive_write_fail "struct archive *" +.Ft int +.Fn archive_write_close "struct archive *" +.Ft int +.Fn archive_write_finish "struct archive *" +.Ft int +.Fn archive_write_free "struct archive *" +.Sh DESCRIPTION +.Bl -tag -width indent +.It Fn archive_write_fail +Always returns +.Cm ARCHIVE_FATAL . +This marks the archive object as being unusable; +after calling this function, the only call that can succeed is +.Fn archive_write_free +to release the resources. +This can be used to speed recovery when the archive creation +must be aborted. +Note that the created archive is likely to be malformed in this case; +.It Fn archive_write_close +Complete the archive and invoke the close callback. +.It Fn archive_write_finish +This is a deprecated synonym for +.Fn archive_write_free . +.It Fn archive_write_free +Invokes +.Fn archive_write_close +if necessary, then releases all resources. +If you need detailed information about +.Fn archive_write_close +failures, you should be careful to call it separately, as +you cannot obtain error information after +.Fn archive_write_free +returns. +.El +.\" .Sh EXAMPLE +.Sh RETURN VALUES +These functions return +.Cm ARCHIVE_OK +on success, or +.Cm ARCHIVE_FATAL . +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_write_set_options 3 , +.Xr libarchive 3 , +.Xr cpio 5 , +.Xr mtree 5 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_header.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_header.3 new file mode 100644 index 0000000000..2217b1871b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_header.3 @@ -0,0 +1,73 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_WRITE_HEADER 3 +.Os +.Sh NAME +.Nm archive_write_header +.Nd functions for creating archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fn archive_write_header "struct archive *" "struct archive_entry *" +.Sh DESCRIPTION +Build and write a header using the data in the provided +.Tn struct archive_entry +structure. +See +.Xr archive_entry 3 +for information on creating and populating +.Tn struct archive_entry +objects. +.\" .Sh EXAMPLE +.Sh RETURN VALUES +This function returns +.Cm ARCHIVE_OK +on success, or one of the following on error: +.Cm ARCHIVE_RETRY +for operations that might succeed if retried, +.Cm ARCHIVE_WARN +for unusual conditions that do not prevent further operations, and +.Cm ARCHIVE_FATAL +for serious errors that make remaining operations impossible. +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_write_set_options 3 , +.Xr libarchive 3 , +.Xr cpio 5 , +.Xr mtree 5 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_new.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_new.3 new file mode 100644 index 0000000000..788cbb8559 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_new.3 @@ -0,0 +1,58 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_WRITE_NEW 3 +.Os +.Sh NAME +.Nm archive_write_new +.Nd functions for creating archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft struct archive * +.Fn archive_write_new "void" +.Sh DESCRIPTION +Allocates and initializes a +.Tn struct archive +object suitable for writing a tar archive. +.Dv NULL +is returned on error. +.Pp +A complete description of the +.Tn struct archive +object can be found in the overview manual page for +.Xr libarchive 3 . +.\" .Sh ERRORS +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_write 3 , +.Xr archive_write_set_options 3 , +.Xr libarchive 3 , +.Xr cpio 5 , +.Xr mtree 5 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open.3 new file mode 100644 index 0000000000..0129d10b7f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open.3 @@ -0,0 +1,246 @@ +.\" Copyright (c) 2003-2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd February 2, 2012 +.Dt ARCHIVE_WRITE_OPEN 3 +.Os +.Sh NAME +.Nm archive_write_open , +.Nm archive_write_open_fd , +.Nm archive_write_open_FILE , +.Nm archive_write_open_filename , +.Nm archive_write_open_memory +.Nd functions for creating archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fo archive_write_open +.Fa "struct archive *" +.Fa "void *client_data" +.Fa "archive_open_callback *" +.Fa "archive_write_callback *" +.Fa "archive_close_callback *" +.Fc +.Ft int +.Fn archive_write_open_fd "struct archive *" "int fd" +.Ft int +.Fn archive_write_open_FILE "struct archive *" "FILE *file" +.Ft int +.Fn archive_write_open_filename "struct archive *" "const char *filename" +.Ft int +.Fo archive_write_open_memory +.Fa "struct archive *" +.Fa "void *buffer" +.Fa "size_t bufferSize" +.Fa "size_t *outUsed" +.Fc +.Sh DESCRIPTION +.Bl -tag -width indent +.It Fn archive_write_open +Freeze the settings, open the archive, and prepare for writing entries. +This is the most generic form of this function, which accepts +pointers to three callback functions which will be invoked by +the compression layer to write the constructed archive. +This does not alter the default archive padding. +.It Fn archive_write_open_fd +A convenience form of +.Fn archive_write_open +that accepts a file descriptor. +The +.Fn archive_write_open_fd +function is safe for use with tape drives or other +block-oriented devices. +.It Fn archive_write_open_FILE +A convenience form of +.Fn archive_write_open +that accepts a +.Ft "FILE *" +pointer. +Note that +.Fn archive_write_open_FILE +is not safe for writing to tape drives or other devices +that require correct blocking. +.It Fn archive_write_open_file +A deprecated synonym for +.Fn archive_write_open_filename . +.It Fn archive_write_open_filename +A convenience form of +.Fn archive_write_open +that accepts a filename. +A NULL argument indicates that the output should be written to standard output; +an argument of +.Dq - +will open a file with that name. +If you have not invoked +.Fn archive_write_set_bytes_in_last_block , +then +.Fn archive_write_open_filename +will adjust the last-block padding depending on the file: +it will enable padding when writing to standard output or +to a character or block device node, it will disable padding otherwise. +You can override this by manually invoking +.Fn archive_write_set_bytes_in_last_block +before calling +.Fn archive_write_open . +The +.Fn archive_write_open_filename +function is safe for use with tape drives or other +block-oriented devices. +.It Fn archive_write_open_memory +A convenience form of +.Fn archive_write_open +that accepts a pointer to a block of memory that will receive +the archive. +The final +.Ft "size_t *" +argument points to a variable that will be updated +after each write to reflect how much of the buffer +is currently in use. +You should be careful to ensure that this variable +remains allocated until after the archive is +closed. +This function will disable padding unless you +have specifically set the block size. +.El +More information about the +.Va struct archive +object and the overall design of the library can be found in the +.Xr libarchive 3 +overview. +.Pp +Note that the convenience forms above vary in how +they block the output. +See +.Xr archive_write_blocksize 3 +if you need to control the block size used for writes +or the end-of-file padding behavior. +.\" +.Sh CLIENT CALLBACKS +To use this library, you will need to define and register +callback functions that will be invoked to write data to the +resulting archive. +These functions are registered by calling +.Fn archive_write_open : +.Bl -item -offset indent +.It +.Ft typedef int +.Fn archive_open_callback "struct archive *" "void *client_data" +.El +.Pp +The open callback is invoked by +.Fn archive_write_open . +It should return +.Cm ARCHIVE_OK +if the underlying file or data source is successfully +opened. +If the open fails, it should call +.Fn archive_set_error +to register an error code and message and return +.Cm ARCHIVE_FATAL . +.Bl -item -offset indent +.It +.Ft typedef la_ssize_t +.Fo archive_write_callback +.Fa "struct archive *" +.Fa "void *client_data" +.Fa "const void *buffer" +.Fa "size_t length" +.Fc +.El +.Pp +The write callback is invoked whenever the library +needs to write raw bytes to the archive. +For correct blocking, each call to the write callback function +should translate into a single +.Xr write 2 +system call. +This is especially critical when writing archives to tape drives. +On success, the write callback should return the +number of bytes actually written. +On error, the callback should invoke +.Fn archive_set_error +to register an error code and message and return -1. +.Bl -item -offset indent +.It +.Ft typedef int +.Fn archive_close_callback "struct archive *" "void *client_data" +.El +.Pp +The close callback is invoked by archive_close when +the archive processing is complete. +The callback should return +.Cm ARCHIVE_OK +on success. +On failure, the callback should invoke +.Fn archive_set_error +to register an error code and message and +return +.Cm ARCHIVE_FATAL . +.Pp +Note that if the client-provided write callback function +returns a non-zero value, that error will be propagated back to the caller +through whatever API function resulted in that call, which +may include +.Fn archive_write_header , +.Fn archive_write_data , +.Fn archive_write_close , +.Fn archive_write_finish , +or +.Fn archive_write_free . +The client callback can call +.Fn archive_set_error +to provide values that can then be retrieved by +.Fn archive_errno +and +.Fn archive_error_string . +.\" .Sh EXAMPLE +.Sh RETURN VALUES +These functions return +.Cm ARCHIVE_OK +on success, or +.Cm ARCHIVE_FATAL . +.\" +.Sh ERRORS +Detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_write 3 , +.Xr archive_write_blocksize 3 , +.Xr archive_write_filter 3 , +.Xr archive_write_format 3 , +.Xr archive_write_new 3 , +.Xr archive_write_set_options 3 , +.Xr libarchive 3 , +.Xr cpio 5 , +.Xr mtree 5 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open_fd.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open_fd.c new file mode 100644 index 0000000000..d5c426cf97 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open_fd.c @@ -0,0 +1,144 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_open_fd.c 201093 2009-12-28 02:28:44Z kientzle $"); + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_IO_H +#include <io.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#include "archive.h" + +struct write_fd_data { + int fd; +}; + +static int file_close(struct archive *, void *); +static int file_open(struct archive *, void *); +static ssize_t file_write(struct archive *, void *, const void *buff, size_t); + +int +archive_write_open_fd(struct archive *a, int fd) +{ + struct write_fd_data *mine; + + mine = (struct write_fd_data *)malloc(sizeof(*mine)); + if (mine == NULL) { + archive_set_error(a, ENOMEM, "No memory"); + return (ARCHIVE_FATAL); + } + mine->fd = fd; +#if defined(__CYGWIN__) || defined(_WIN32) + setmode(mine->fd, O_BINARY); +#endif + return (archive_write_open(a, mine, + file_open, file_write, file_close)); +} + +static int +file_open(struct archive *a, void *client_data) +{ + struct write_fd_data *mine; + struct stat st; + + mine = (struct write_fd_data *)client_data; + + if (fstat(mine->fd, &st) != 0) { + archive_set_error(a, errno, "Couldn't stat fd %d", mine->fd); + return (ARCHIVE_FATAL); + } + + /* + * If this is a regular file, don't add it to itself. + */ + if (S_ISREG(st.st_mode)) + archive_write_set_skip_file(a, st.st_dev, st.st_ino); + + /* + * If client hasn't explicitly set the last block handling, + * then set it here. + */ + if (archive_write_get_bytes_in_last_block(a) < 0) { + /* If the output is a block or character device, fifo, + * or stdout, pad the last block, otherwise leave it + * unpadded. */ + if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode) || + S_ISFIFO(st.st_mode) || (mine->fd == 1)) + /* Last block will be fully padded. */ + archive_write_set_bytes_in_last_block(a, 0); + else + archive_write_set_bytes_in_last_block(a, 1); + } + + return (ARCHIVE_OK); +} + +static ssize_t +file_write(struct archive *a, void *client_data, const void *buff, size_t length) +{ + struct write_fd_data *mine; + ssize_t bytesWritten; + + mine = (struct write_fd_data *)client_data; + for (;;) { + bytesWritten = write(mine->fd, buff, length); + if (bytesWritten <= 0) { + if (errno == EINTR) + continue; + archive_set_error(a, errno, "Write error"); + return (-1); + } + return (bytesWritten); + } +} + +static int +file_close(struct archive *a, void *client_data) +{ + struct write_fd_data *mine = (struct write_fd_data *)client_data; + + (void)a; /* UNUSED */ + free(mine); + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open_file.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open_file.c new file mode 100644 index 0000000000..f6b141239f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open_file.c @@ -0,0 +1,109 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: src/lib/libarchive/archive_write_open_file.c,v 1.19 2007/01/09 08:05:56 kientzle Exp $"); + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#include "archive.h" + +struct write_FILE_data { + FILE *f; +}; + +static int file_close(struct archive *, void *); +static int file_open(struct archive *, void *); +static ssize_t file_write(struct archive *, void *, const void *buff, size_t); + +int +archive_write_open_FILE(struct archive *a, FILE *f) +{ + struct write_FILE_data *mine; + + mine = (struct write_FILE_data *)malloc(sizeof(*mine)); + if (mine == NULL) { + archive_set_error(a, ENOMEM, "No memory"); + return (ARCHIVE_FATAL); + } + mine->f = f; + return (archive_write_open(a, mine, + file_open, file_write, file_close)); +} + +static int +file_open(struct archive *a, void *client_data) +{ + (void)a; /* UNUSED */ + (void)client_data; /* UNUSED */ + + return (ARCHIVE_OK); +} + +static ssize_t +file_write(struct archive *a, void *client_data, const void *buff, size_t length) +{ + struct write_FILE_data *mine; + size_t bytesWritten; + + mine = client_data; + for (;;) { + bytesWritten = fwrite(buff, 1, length, mine->f); + if (bytesWritten <= 0) { + if (errno == EINTR) + continue; + archive_set_error(a, errno, "Write error"); + return (-1); + } + return (bytesWritten); + } +} + +static int +file_close(struct archive *a, void *client_data) +{ + struct write_FILE_data *mine = client_data; + + (void)a; /* UNUSED */ + free(mine); + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open_filename.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open_filename.c new file mode 100644 index 0000000000..66e0dfee9f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open_filename.c @@ -0,0 +1,253 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_open_filename.c 191165 2009-04-17 00:39:35Z kientzle $"); + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_string.h" + +#ifndef O_BINARY +#define O_BINARY 0 +#endif +#ifndef O_CLOEXEC +#define O_CLOEXEC 0 +#endif + +struct write_file_data { + int fd; + struct archive_mstring filename; +}; + +static int file_close(struct archive *, void *); +static int file_open(struct archive *, void *); +static ssize_t file_write(struct archive *, void *, const void *buff, size_t); +static int open_filename(struct archive *, int, const void *); + +int +archive_write_open_file(struct archive *a, const char *filename) +{ + return (archive_write_open_filename(a, filename)); +} + +int +archive_write_open_filename(struct archive *a, const char *filename) +{ + + if (filename == NULL || filename[0] == '\0') + return (archive_write_open_fd(a, 1)); + + return (open_filename(a, 1, filename)); +} + +int +archive_write_open_filename_w(struct archive *a, const wchar_t *filename) +{ + + if (filename == NULL || filename[0] == L'\0') + return (archive_write_open_fd(a, 1)); + + return (open_filename(a, 0, filename)); +} + +static int +open_filename(struct archive *a, int mbs_fn, const void *filename) +{ + struct write_file_data *mine; + int r; + + mine = (struct write_file_data *)calloc(1, sizeof(*mine)); + if (mine == NULL) { + archive_set_error(a, ENOMEM, "No memory"); + return (ARCHIVE_FATAL); + } + if (mbs_fn) + r = archive_mstring_copy_mbs(&mine->filename, filename); + else + r = archive_mstring_copy_wcs(&mine->filename, filename); + if (r < 0) { + if (errno == ENOMEM) { + archive_set_error(a, ENOMEM, "No memory"); + return (ARCHIVE_FATAL); + } + if (mbs_fn) + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Can't convert '%s' to WCS", + (const char *)filename); + else + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Can't convert '%S' to MBS", + (const wchar_t *)filename); + return (ARCHIVE_FAILED); + } + mine->fd = -1; + return (archive_write_open(a, mine, + file_open, file_write, file_close)); +} + +static int +file_open(struct archive *a, void *client_data) +{ + int flags; + struct write_file_data *mine; + struct stat st; +#if defined(_WIN32) && !defined(__CYGWIN__) + wchar_t *fullpath; +#endif + const wchar_t *wcs; + const char *mbs; + + mine = (struct write_file_data *)client_data; + flags = O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_CLOEXEC; + + /* + * Open the file. + */ + mbs = NULL; wcs = NULL; +#if defined(_WIN32) && !defined(__CYGWIN__) + if (archive_mstring_get_wcs(a, &mine->filename, &wcs) != 0) { + if (errno == ENOMEM) + archive_set_error(a, errno, "No memory"); + else { + archive_mstring_get_mbs(a, &mine->filename, &mbs); + archive_set_error(a, errno, + "Can't convert '%s' to WCS", mbs); + } + return (ARCHIVE_FATAL); + } + fullpath = __la_win_permissive_name_w(wcs); + if (fullpath != NULL) { + mine->fd = _wopen(fullpath, flags, 0666); + free(fullpath); + } else + mine->fd = _wopen(wcs, flags, 0666); +#else + if (archive_mstring_get_mbs(a, &mine->filename, &mbs) != 0) { + if (errno == ENOMEM) + archive_set_error(a, errno, "No memory"); + else { + archive_mstring_get_wcs(a, &mine->filename, &wcs); + archive_set_error(a, errno, + "Can't convert '%S' to MBS", wcs); + } + return (ARCHIVE_FATAL); + } + mine->fd = open(mbs, flags, 0666); + __archive_ensure_cloexec_flag(mine->fd); +#endif + if (mine->fd < 0) { + if (mbs != NULL) + archive_set_error(a, errno, "Failed to open '%s'", mbs); + else + archive_set_error(a, errno, "Failed to open '%S'", wcs); + return (ARCHIVE_FATAL); + } + + if (fstat(mine->fd, &st) != 0) { + if (mbs != NULL) + archive_set_error(a, errno, "Couldn't stat '%s'", mbs); + else + archive_set_error(a, errno, "Couldn't stat '%S'", wcs); + return (ARCHIVE_FATAL); + } + + /* + * Set up default last block handling. + */ + if (archive_write_get_bytes_in_last_block(a) < 0) { + if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode) || + S_ISFIFO(st.st_mode)) + /* Pad last block when writing to device or FIFO. */ + archive_write_set_bytes_in_last_block(a, 0); + else + /* Don't pad last block otherwise. */ + archive_write_set_bytes_in_last_block(a, 1); + } + + /* + * If the output file is a regular file, don't add it to + * itself. If it's a device file, it's okay to add the device + * entry to the output archive. + */ + if (S_ISREG(st.st_mode)) + archive_write_set_skip_file(a, st.st_dev, st.st_ino); + + return (ARCHIVE_OK); +} + +static ssize_t +file_write(struct archive *a, void *client_data, const void *buff, + size_t length) +{ + struct write_file_data *mine; + ssize_t bytesWritten; + + mine = (struct write_file_data *)client_data; + for (;;) { + bytesWritten = write(mine->fd, buff, length); + if (bytesWritten <= 0) { + if (errno == EINTR) + continue; + archive_set_error(a, errno, "Write error"); + return (-1); + } + return (bytesWritten); + } +} + +static int +file_close(struct archive *a, void *client_data) +{ + struct write_file_data *mine = (struct write_file_data *)client_data; + + (void)a; /* UNUSED */ + + if (mine->fd >= 0) + close(mine->fd); + + archive_mstring_clean(&mine->filename); + free(mine); + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open_memory.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open_memory.c new file mode 100644 index 0000000000..ea6ae0ac52 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_open_memory.c @@ -0,0 +1,113 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: src/lib/libarchive/archive_write_open_memory.c,v 1.3 2007/01/09 08:05:56 kientzle Exp $"); + +#include <errno.h> +#include <stdlib.h> +#include <string.h> + +#include "archive.h" + +struct write_memory_data { + size_t used; + size_t size; + size_t * client_size; + unsigned char * buff; +}; + +static int memory_write_close(struct archive *, void *); +static int memory_write_open(struct archive *, void *); +static ssize_t memory_write(struct archive *, void *, const void *buff, size_t); + +/* + * Client provides a pointer to a block of memory to receive + * the data. The 'size' param both tells us the size of the + * client buffer and lets us tell the client the final size. + */ +int +archive_write_open_memory(struct archive *a, void *buff, size_t buffSize, size_t *used) +{ + struct write_memory_data *mine; + + mine = (struct write_memory_data *)calloc(1, sizeof(*mine)); + if (mine == NULL) { + archive_set_error(a, ENOMEM, "No memory"); + return (ARCHIVE_FATAL); + } + mine->buff = buff; + mine->size = buffSize; + mine->client_size = used; + return (archive_write_open(a, mine, + memory_write_open, memory_write, memory_write_close)); +} + +static int +memory_write_open(struct archive *a, void *client_data) +{ + struct write_memory_data *mine; + mine = client_data; + mine->used = 0; + if (mine->client_size != NULL) + *mine->client_size = mine->used; + /* Disable padding if it hasn't been set explicitly. */ + if (-1 == archive_write_get_bytes_in_last_block(a)) + archive_write_set_bytes_in_last_block(a, 1); + return (ARCHIVE_OK); +} + +/* + * Copy the data into the client buffer. + * Note that we update mine->client_size on every write. + * In particular, this means the client can follow exactly + * how much has been written into their buffer at any time. + */ +static ssize_t +memory_write(struct archive *a, void *client_data, const void *buff, size_t length) +{ + struct write_memory_data *mine; + mine = client_data; + + if (mine->used + length > mine->size) { + archive_set_error(a, ENOMEM, "Buffer exhausted"); + return (ARCHIVE_FATAL); + } + memcpy(mine->buff + mine->used, buff, length); + mine->used += length; + if (mine->client_size != NULL) + *mine->client_size = mine->used; + return (length); +} + +static int +memory_write_close(struct archive *a, void *client_data) +{ + struct write_memory_data *mine; + (void)a; /* UNUSED */ + mine = client_data; + free(mine); + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_private.h new file mode 100644 index 0000000000..27cba0392c --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_private.h @@ -0,0 +1,164 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + * + * $FreeBSD: head/lib/libarchive/archive_write_private.h 201155 2009-12-29 05:20:12Z kientzle $ + */ + +#ifndef ARCHIVE_WRITE_PRIVATE_H_INCLUDED +#define ARCHIVE_WRITE_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#ifndef __LIBARCHIVE_TEST +#error This header is only to be used internally to libarchive. +#endif +#endif + +#include "archive.h" +#include "archive_string.h" +#include "archive_private.h" + +#define ARCHIVE_WRITE_FILTER_STATE_NEW 1U +#define ARCHIVE_WRITE_FILTER_STATE_OPEN 2U +#define ARCHIVE_WRITE_FILTER_STATE_CLOSED 4U +#define ARCHIVE_WRITE_FILTER_STATE_FATAL 0x8000U + +struct archive_write; + +struct archive_write_filter { + int64_t bytes_written; + struct archive *archive; /* Associated archive. */ + struct archive_write_filter *next_filter; /* Who I write to. */ + int (*options)(struct archive_write_filter *, + const char *key, const char *value); + int (*open)(struct archive_write_filter *); + int (*write)(struct archive_write_filter *, const void *, size_t); + int (*close)(struct archive_write_filter *); + int (*free)(struct archive_write_filter *); + void *data; + const char *name; + int code; + int bytes_per_block; + int bytes_in_last_block; + int state; +}; + +#if ARCHIVE_VERSION < 4000000 +void __archive_write_filters_free(struct archive *); +#endif + +struct archive_write_filter *__archive_write_allocate_filter(struct archive *); + +int __archive_write_output(struct archive_write *, const void *, size_t); +int __archive_write_nulls(struct archive_write *, size_t); +int __archive_write_filter(struct archive_write_filter *, const void *, size_t); + +struct archive_write { + struct archive archive; + + /* Dev/ino of the archive being written. */ + int skip_file_set; + int64_t skip_file_dev; + int64_t skip_file_ino; + + /* Utility: Pointer to a block of nulls. */ + const unsigned char *nulls; + size_t null_length; + + /* Callbacks to open/read/write/close archive stream. */ + archive_open_callback *client_opener; + archive_write_callback *client_writer; + archive_close_callback *client_closer; + void *client_data; + + /* + * Blocking information. Note that bytes_in_last_block is + * misleadingly named; I should find a better name. These + * control the final output from all compressors, including + * compression_none. + */ + int bytes_per_block; + int bytes_in_last_block; + + /* + * First and last write filters in the pipeline. + */ + struct archive_write_filter *filter_first; + struct archive_write_filter *filter_last; + + /* + * Pointers to format-specific functions for writing. They're + * initialized by archive_write_set_format_XXX() calls. + */ + void *format_data; + const char *format_name; + int (*format_init)(struct archive_write *); + int (*format_options)(struct archive_write *, + const char *key, const char *value); + int (*format_finish_entry)(struct archive_write *); + int (*format_write_header)(struct archive_write *, + struct archive_entry *); + ssize_t (*format_write_data)(struct archive_write *, + const void *buff, size_t); + int (*format_close)(struct archive_write *); + int (*format_free)(struct archive_write *); + + + /* + * Encryption passphrase. + */ + char *passphrase; + archive_passphrase_callback *passphrase_callback; + void *passphrase_client_data; +}; + +/* + * Utility function to format a USTAR header into a buffer. If + * "strict" is set, this tries to create the absolutely most portable + * version of a ustar header. If "strict" is set to 0, then it will + * relax certain requirements. + * + * Generally, format-specific declarations don't belong in this + * header; this is a rare example of a function that is shared by + * two very similar formats (ustar and pax). + */ +int +__archive_write_format_header_ustar(struct archive_write *, char buff[512], + struct archive_entry *, int tartype, int strict, + struct archive_string_conv *); + +struct archive_write_program_data; +struct archive_write_program_data * __archive_write_program_allocate(const char *program_name); +int __archive_write_program_free(struct archive_write_program_data *); +int __archive_write_program_open(struct archive_write_filter *, + struct archive_write_program_data *, const char *); +int __archive_write_program_close(struct archive_write_filter *, + struct archive_write_program_data *); +int __archive_write_program_write(struct archive_write_filter *, + struct archive_write_program_data *, const void *, size_t); + +/* + * Get a encryption passphrase. + */ +const char * __archive_write_get_passphrase(struct archive_write *a); +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format.c new file mode 100644 index 0000000000..7dbe7b9a2c --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format.c @@ -0,0 +1,123 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format.c 201168 2009-12-29 06:15:32Z kientzle $"); + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif + +#include "archive.h" +#include "archive_private.h" +#include "archive_write_set_format_private.h" + +/* A table that maps format codes to functions. */ +static const +struct { int code; int (*setter)(struct archive *); } codes[] = +{ + { ARCHIVE_FORMAT_7ZIP, archive_write_set_format_7zip }, + { ARCHIVE_FORMAT_CPIO, archive_write_set_format_cpio }, + { ARCHIVE_FORMAT_CPIO_POSIX, archive_write_set_format_cpio }, + { ARCHIVE_FORMAT_CPIO_SVR4_NOCRC, archive_write_set_format_cpio_newc }, + { ARCHIVE_FORMAT_ISO9660, archive_write_set_format_iso9660 }, + { ARCHIVE_FORMAT_MTREE, archive_write_set_format_mtree }, + { ARCHIVE_FORMAT_RAW, archive_write_set_format_raw }, + { ARCHIVE_FORMAT_SHAR, archive_write_set_format_shar }, + { ARCHIVE_FORMAT_SHAR_BASE, archive_write_set_format_shar }, + { ARCHIVE_FORMAT_SHAR_DUMP, archive_write_set_format_shar_dump }, + { ARCHIVE_FORMAT_TAR, archive_write_set_format_pax_restricted }, + { ARCHIVE_FORMAT_TAR_GNUTAR, archive_write_set_format_gnutar }, + { ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE, archive_write_set_format_pax }, + { ARCHIVE_FORMAT_TAR_PAX_RESTRICTED, + archive_write_set_format_pax_restricted }, + { ARCHIVE_FORMAT_TAR_USTAR, archive_write_set_format_ustar }, + { ARCHIVE_FORMAT_WARC, archive_write_set_format_warc }, + { ARCHIVE_FORMAT_XAR, archive_write_set_format_xar }, + { ARCHIVE_FORMAT_ZIP, archive_write_set_format_zip }, + { 0, NULL } +}; + +int +archive_write_set_format(struct archive *a, int code) +{ + int i; + + for (i = 0; codes[i].code != 0; i++) { + if (code == codes[i].code) + return ((codes[i].setter)(a)); + } + + archive_set_error(a, EINVAL, "No such format"); + return (ARCHIVE_FATAL); +} + +void +__archive_write_entry_filetype_unsupported(struct archive *a, + struct archive_entry *entry, const char *format) +{ + const char *name = NULL; + + switch (archive_entry_filetype(entry)) { + /* + * All formats should be able to archive regular files (AE_IFREG) + */ + case AE_IFDIR: + name = "directories"; + break; + case AE_IFLNK: + name = "symbolic links"; + break; + case AE_IFCHR: + name = "character devices"; + break; + case AE_IFBLK: + name = "block devices"; + break; + case AE_IFIFO: + name = "named pipes"; + break; + case AE_IFSOCK: + name = "sockets"; + break; + default: + break; + } + + if (name != NULL) { + archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT, + "%s: %s format cannot archive %s", + archive_entry_pathname(entry), format, name); + } else { + archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT, + "%s: %s format cannot archive files with mode 0%lo", + archive_entry_pathname(entry), format, + (unsigned long)archive_entry_mode(entry)); + } +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_7zip.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_7zip.c new file mode 100644 index 0000000000..fb7697f659 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_7zip.c @@ -0,0 +1,2317 @@ +/*- + * Copyright (c) 2011-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdlib.h> +#ifdef HAVE_BZLIB_H +#include <bzlib.h> +#endif +#if HAVE_LZMA_H +#include <lzma.h> +#endif +#ifdef HAVE_ZLIB_H +#include <zlib.h> +#endif + +#include "archive.h" +#ifndef HAVE_ZLIB_H +#include "archive_crc32.h" +#endif +#include "archive_endian.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_ppmd7_private.h" +#include "archive_private.h" +#include "archive_rb.h" +#include "archive_string.h" +#include "archive_write_private.h" +#include "archive_write_set_format_private.h" + +/* + * Codec ID + */ +#define _7Z_COPY 0 +#define _7Z_LZMA1 0x030101 +#define _7Z_LZMA2 0x21 +#define _7Z_DEFLATE 0x040108 +#define _7Z_BZIP2 0x040202 +#define _7Z_PPMD 0x030401 + +/* + * 7-Zip header property IDs. + */ +#define kEnd 0x00 +#define kHeader 0x01 +#define kArchiveProperties 0x02 +#define kAdditionalStreamsInfo 0x03 +#define kMainStreamsInfo 0x04 +#define kFilesInfo 0x05 +#define kPackInfo 0x06 +#define kUnPackInfo 0x07 +#define kSubStreamsInfo 0x08 +#define kSize 0x09 +#define kCRC 0x0A +#define kFolder 0x0B +#define kCodersUnPackSize 0x0C +#define kNumUnPackStream 0x0D +#define kEmptyStream 0x0E +#define kEmptyFile 0x0F +#define kAnti 0x10 +#define kName 0x11 +#define kCTime 0x12 +#define kATime 0x13 +#define kMTime 0x14 +#define kAttributes 0x15 +#define kEncodedHeader 0x17 + +enum la_zaction { + ARCHIVE_Z_FINISH, + ARCHIVE_Z_RUN +}; + +/* + * A stream object of universal compressor. + */ +struct la_zstream { + const uint8_t *next_in; + size_t avail_in; + uint64_t total_in; + + uint8_t *next_out; + size_t avail_out; + uint64_t total_out; + + uint32_t prop_size; + uint8_t *props; + + int valid; + void *real_stream; + int (*code) (struct archive *a, + struct la_zstream *lastrm, + enum la_zaction action); + int (*end)(struct archive *a, + struct la_zstream *lastrm); +}; + +#define PPMD7_DEFAULT_ORDER 6 +#define PPMD7_DEFAULT_MEM_SIZE (1 << 24) + +struct ppmd_stream { + int stat; + CPpmd7 ppmd7_context; + CPpmd7z_RangeEnc range_enc; + IByteOut byteout; + uint8_t *buff; + uint8_t *buff_ptr; + uint8_t *buff_end; + size_t buff_bytes; +}; + +struct coder { + unsigned codec; + size_t prop_size; + uint8_t *props; +}; + +struct file { + struct archive_rb_node rbnode; + + struct file *next; + unsigned name_len; + uint8_t *utf16name;/* UTF16-LE name. */ + uint64_t size; + unsigned flg; +#define MTIME_IS_SET (1<<0) +#define ATIME_IS_SET (1<<1) +#define CTIME_IS_SET (1<<2) +#define CRC32_IS_SET (1<<3) +#define HAS_STREAM (1<<4) + + struct { + time_t time; + long time_ns; + } times[3]; +#define MTIME 0 +#define ATIME 1 +#define CTIME 2 + + mode_t mode; + uint32_t crc32; + + signed int dir:1; +}; + +struct _7zip { + int temp_fd; + uint64_t temp_offset; + + struct file *cur_file; + size_t total_number_entry; + size_t total_number_nonempty_entry; + size_t total_number_empty_entry; + size_t total_number_dir_entry; + size_t total_bytes_entry_name; + size_t total_number_time_defined[3]; + uint64_t total_bytes_compressed; + uint64_t total_bytes_uncompressed; + uint64_t entry_bytes_remaining; + uint32_t entry_crc32; + uint32_t precode_crc32; + uint32_t encoded_crc32; + int crc32flg; +#define PRECODE_CRC32 1 +#define ENCODED_CRC32 2 + + unsigned opt_compression; + int opt_compression_level; + + struct la_zstream stream; + struct coder coder; + + struct archive_string_conv *sconv; + + /* + * Compressed data buffer. + */ + unsigned char wbuff[512 * 20 * 6]; + size_t wbuff_remaining; + + /* + * The list of the file entries which has its contents is used to + * manage struct file objects. + * We use 'next' (a member of struct file) to chain. + */ + struct { + struct file *first; + struct file **last; + } file_list, empty_list; + struct archive_rb_tree rbtree;/* for empty files */ +}; + +static int _7z_options(struct archive_write *, + const char *, const char *); +static int _7z_write_header(struct archive_write *, + struct archive_entry *); +static ssize_t _7z_write_data(struct archive_write *, + const void *, size_t); +static int _7z_finish_entry(struct archive_write *); +static int _7z_close(struct archive_write *); +static int _7z_free(struct archive_write *); +static int file_cmp_node(const struct archive_rb_node *, + const struct archive_rb_node *); +static int file_cmp_key(const struct archive_rb_node *, const void *); +static int file_new(struct archive_write *a, struct archive_entry *, + struct file **); +static void file_free(struct file *); +static void file_register(struct _7zip *, struct file *); +static void file_register_empty(struct _7zip *, struct file *); +static void file_init_register(struct _7zip *); +static void file_init_register_empty(struct _7zip *); +static void file_free_register(struct _7zip *); +static ssize_t compress_out(struct archive_write *, const void *, size_t , + enum la_zaction); +static int compression_init_encoder_copy(struct archive *, + struct la_zstream *); +static int compression_code_copy(struct archive *, + struct la_zstream *, enum la_zaction); +static int compression_end_copy(struct archive *, struct la_zstream *); +static int compression_init_encoder_deflate(struct archive *, + struct la_zstream *, int, int); +#ifdef HAVE_ZLIB_H +static int compression_code_deflate(struct archive *, + struct la_zstream *, enum la_zaction); +static int compression_end_deflate(struct archive *, struct la_zstream *); +#endif +static int compression_init_encoder_bzip2(struct archive *, + struct la_zstream *, int); +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) +static int compression_code_bzip2(struct archive *, + struct la_zstream *, enum la_zaction); +static int compression_end_bzip2(struct archive *, struct la_zstream *); +#endif +static int compression_init_encoder_lzma1(struct archive *, + struct la_zstream *, int); +static int compression_init_encoder_lzma2(struct archive *, + struct la_zstream *, int); +#if defined(HAVE_LZMA_H) +static int compression_code_lzma(struct archive *, + struct la_zstream *, enum la_zaction); +static int compression_end_lzma(struct archive *, struct la_zstream *); +#endif +static int compression_init_encoder_ppmd(struct archive *, + struct la_zstream *, unsigned, uint32_t); +static int compression_code_ppmd(struct archive *, + struct la_zstream *, enum la_zaction); +static int compression_end_ppmd(struct archive *, struct la_zstream *); +static int _7z_compression_init_encoder(struct archive_write *, unsigned, + int); +static int compression_code(struct archive *, + struct la_zstream *, enum la_zaction); +static int compression_end(struct archive *, + struct la_zstream *); +static int enc_uint64(struct archive_write *, uint64_t); +static int make_header(struct archive_write *, uint64_t, uint64_t, + uint64_t, int, struct coder *); +static int make_streamsInfo(struct archive_write *, uint64_t, uint64_t, + uint64_t, int, struct coder *, int, uint32_t); + +int +archive_write_set_format_7zip(struct archive *_a) +{ + static const struct archive_rb_tree_ops rb_ops = { + file_cmp_node, file_cmp_key + }; + struct archive_write *a = (struct archive_write *)_a; + struct _7zip *zip; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_7zip"); + + /* If another format was already registered, unregister it. */ + if (a->format_free != NULL) + (a->format_free)(a); + + zip = calloc(1, sizeof(*zip)); + if (zip == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate 7-Zip data"); + return (ARCHIVE_FATAL); + } + zip->temp_fd = -1; + __archive_rb_tree_init(&(zip->rbtree), &rb_ops); + file_init_register(zip); + file_init_register_empty(zip); + + /* Set default compression type and its level. */ +#if HAVE_LZMA_H + zip->opt_compression = _7Z_LZMA1; +#elif defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) + zip->opt_compression = _7Z_BZIP2; +#elif defined(HAVE_ZLIB_H) + zip->opt_compression = _7Z_DEFLATE; +#else + zip->opt_compression = _7Z_COPY; +#endif + zip->opt_compression_level = 6; + + a->format_data = zip; + + a->format_name = "7zip"; + a->format_options = _7z_options; + a->format_write_header = _7z_write_header; + a->format_write_data = _7z_write_data; + a->format_finish_entry = _7z_finish_entry; + a->format_close = _7z_close; + a->format_free = _7z_free; + a->archive.archive_format = ARCHIVE_FORMAT_7ZIP; + a->archive.archive_format_name = "7zip"; + + return (ARCHIVE_OK); +} + +static int +_7z_options(struct archive_write *a, const char *key, const char *value) +{ + struct _7zip *zip; + + zip = (struct _7zip *)a->format_data; + + if (strcmp(key, "compression") == 0) { + const char *name = NULL; + + if (value == NULL || strcmp(value, "copy") == 0 || + strcmp(value, "COPY") == 0 || + strcmp(value, "store") == 0 || + strcmp(value, "STORE") == 0) + zip->opt_compression = _7Z_COPY; + else if (strcmp(value, "deflate") == 0 || + strcmp(value, "DEFLATE") == 0) +#if HAVE_ZLIB_H + zip->opt_compression = _7Z_DEFLATE; +#else + name = "deflate"; +#endif + else if (strcmp(value, "bzip2") == 0 || + strcmp(value, "BZIP2") == 0) +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) + zip->opt_compression = _7Z_BZIP2; +#else + name = "bzip2"; +#endif + else if (strcmp(value, "lzma1") == 0 || + strcmp(value, "LZMA1") == 0) +#if HAVE_LZMA_H + zip->opt_compression = _7Z_LZMA1; +#else + name = "lzma1"; +#endif + else if (strcmp(value, "lzma2") == 0 || + strcmp(value, "LZMA2") == 0) +#if HAVE_LZMA_H + zip->opt_compression = _7Z_LZMA2; +#else + name = "lzma2"; +#endif + else if (strcmp(value, "ppmd") == 0 || + strcmp(value, "PPMD") == 0 || + strcmp(value, "PPMd") == 0) + zip->opt_compression = _7Z_PPMD; + else { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "Unknown compression name: `%s'", + value); + return (ARCHIVE_FAILED); + } + if (name != NULL) { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "`%s' compression not supported " + "on this platform", + name); + return (ARCHIVE_FAILED); + } + return (ARCHIVE_OK); + } + if (strcmp(key, "compression-level") == 0) { + if (value == NULL || + !(value[0] >= '0' && value[0] <= '9') || + value[1] != '\0') { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "Illegal value `%s'", + value); + return (ARCHIVE_FAILED); + } + zip->opt_compression_level = value[0] - '0'; + return (ARCHIVE_OK); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static int +_7z_write_header(struct archive_write *a, struct archive_entry *entry) +{ + struct _7zip *zip; + struct file *file; + int r; + + zip = (struct _7zip *)a->format_data; + zip->cur_file = NULL; + zip->entry_bytes_remaining = 0; + + if (zip->sconv == NULL) { + zip->sconv = archive_string_conversion_to_charset( + &a->archive, "UTF-16LE", 1); + if (zip->sconv == NULL) + return (ARCHIVE_FATAL); + } + + r = file_new(a, entry, &file); + if (r < ARCHIVE_WARN) { + if (file != NULL) + file_free(file); + return (r); + } + if (file->size == 0 && file->dir) { + if (!__archive_rb_tree_insert_node(&(zip->rbtree), + (struct archive_rb_node *)file)) { + /* We have already had the same file. */ + file_free(file); + return (ARCHIVE_OK); + } + } + + if (file->flg & MTIME_IS_SET) + zip->total_number_time_defined[MTIME]++; + if (file->flg & CTIME_IS_SET) + zip->total_number_time_defined[CTIME]++; + if (file->flg & ATIME_IS_SET) + zip->total_number_time_defined[ATIME]++; + + zip->total_number_entry++; + zip->total_bytes_entry_name += file->name_len + 2; + if (file->size == 0) { + /* Count up the number of empty files. */ + zip->total_number_empty_entry++; + if (file->dir) + zip->total_number_dir_entry++; + else + file_register_empty(zip, file); + return (r); + } + + /* + * Init compression. + */ + if ((zip->total_number_entry - zip->total_number_empty_entry) == 1) { + r = _7z_compression_init_encoder(a, zip->opt_compression, + zip->opt_compression_level); + if (r < 0) { + file_free(file); + return (ARCHIVE_FATAL); + } + } + + /* Register a non-empty file. */ + file_register(zip, file); + + /* + * Set the current file to cur_file to read its contents. + */ + zip->cur_file = file; + + + /* Save a offset of current file in temporary file. */ + zip->entry_bytes_remaining = file->size; + zip->entry_crc32 = 0; + + /* + * Store a symbolic link name as file contents. + */ + if (archive_entry_filetype(entry) == AE_IFLNK) { + ssize_t bytes; + const void *p = (const void *)archive_entry_symlink(entry); + bytes = compress_out(a, p, (size_t)file->size, ARCHIVE_Z_RUN); + if (bytes < 0) + return ((int)bytes); + zip->entry_crc32 = crc32(zip->entry_crc32, p, (unsigned)bytes); + zip->entry_bytes_remaining -= bytes; + } + + return (r); +} + +/* + * Write data to a temporary file. + */ +static int +write_to_temp(struct archive_write *a, const void *buff, size_t s) +{ + struct _7zip *zip; + const unsigned char *p; + ssize_t ws; + + zip = (struct _7zip *)a->format_data; + + /* + * Open a temporary file. + */ + if (zip->temp_fd == -1) { + zip->temp_offset = 0; + zip->temp_fd = __archive_mktemp(NULL); + if (zip->temp_fd < 0) { + archive_set_error(&a->archive, errno, + "Couldn't create temporary file"); + return (ARCHIVE_FATAL); + } + } + + p = (const unsigned char *)buff; + while (s) { + ws = write(zip->temp_fd, p, s); + if (ws < 0) { + archive_set_error(&(a->archive), errno, + "fwrite function failed"); + return (ARCHIVE_FATAL); + } + s -= ws; + p += ws; + zip->temp_offset += ws; + } + return (ARCHIVE_OK); +} + +static ssize_t +compress_out(struct archive_write *a, const void *buff, size_t s, + enum la_zaction run) +{ + struct _7zip *zip = (struct _7zip *)a->format_data; + int r; + + if (run == ARCHIVE_Z_FINISH && zip->stream.total_in == 0 && s == 0) + return (0); + + if ((zip->crc32flg & PRECODE_CRC32) && s) + zip->precode_crc32 = crc32(zip->precode_crc32, buff, + (unsigned)s); + zip->stream.next_in = (const unsigned char *)buff; + zip->stream.avail_in = s; + for (;;) { + /* Compress file data. */ + r = compression_code(&(a->archive), &(zip->stream), run); + if (r != ARCHIVE_OK && r != ARCHIVE_EOF) + return (ARCHIVE_FATAL); + if (zip->stream.avail_out == 0) { + if (write_to_temp(a, zip->wbuff, sizeof(zip->wbuff)) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + zip->stream.next_out = zip->wbuff; + zip->stream.avail_out = sizeof(zip->wbuff); + if (zip->crc32flg & ENCODED_CRC32) + zip->encoded_crc32 = crc32(zip->encoded_crc32, + zip->wbuff, sizeof(zip->wbuff)); + if (run == ARCHIVE_Z_FINISH && r != ARCHIVE_EOF) + continue; + } + if (zip->stream.avail_in == 0) + break; + } + if (run == ARCHIVE_Z_FINISH) { + uint64_t bytes = sizeof(zip->wbuff) - zip->stream.avail_out; + if (write_to_temp(a, zip->wbuff, (size_t)bytes) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + if ((zip->crc32flg & ENCODED_CRC32) && bytes) + zip->encoded_crc32 = crc32(zip->encoded_crc32, + zip->wbuff, (unsigned)bytes); + } + + return (s); +} + +static ssize_t +_7z_write_data(struct archive_write *a, const void *buff, size_t s) +{ + struct _7zip *zip; + ssize_t bytes; + + zip = (struct _7zip *)a->format_data; + + if (s > zip->entry_bytes_remaining) + s = (size_t)zip->entry_bytes_remaining; + if (s == 0 || zip->cur_file == NULL) + return (0); + bytes = compress_out(a, buff, s, ARCHIVE_Z_RUN); + if (bytes < 0) + return (bytes); + zip->entry_crc32 = crc32(zip->entry_crc32, buff, (unsigned)bytes); + zip->entry_bytes_remaining -= bytes; + return (bytes); +} + +static int +_7z_finish_entry(struct archive_write *a) +{ + struct _7zip *zip; + size_t s; + ssize_t r; + + zip = (struct _7zip *)a->format_data; + if (zip->cur_file == NULL) + return (ARCHIVE_OK); + + while (zip->entry_bytes_remaining > 0) { + s = (size_t)zip->entry_bytes_remaining; + if (s > a->null_length) + s = a->null_length; + r = _7z_write_data(a, a->nulls, s); + if (r < 0) + return ((int)r); + } + zip->total_bytes_compressed += zip->stream.total_in; + zip->total_bytes_uncompressed += zip->stream.total_out; + zip->cur_file->crc32 = zip->entry_crc32; + zip->cur_file = NULL; + + return (ARCHIVE_OK); +} + +static int +flush_wbuff(struct archive_write *a) +{ + struct _7zip *zip; + int r; + size_t s; + + zip = (struct _7zip *)a->format_data; + s = sizeof(zip->wbuff) - zip->wbuff_remaining; + r = __archive_write_output(a, zip->wbuff, s); + if (r != ARCHIVE_OK) + return (r); + zip->wbuff_remaining = sizeof(zip->wbuff); + return (r); +} + +static int +copy_out(struct archive_write *a, uint64_t offset, uint64_t length) +{ + struct _7zip *zip; + int r; + + zip = (struct _7zip *)a->format_data; + if (zip->temp_offset > 0 && + lseek(zip->temp_fd, offset, SEEK_SET) < 0) { + archive_set_error(&(a->archive), errno, "lseek failed"); + return (ARCHIVE_FATAL); + } + while (length) { + size_t rsize; + ssize_t rs; + unsigned char *wb; + + if (length > zip->wbuff_remaining) + rsize = zip->wbuff_remaining; + else + rsize = (size_t)length; + wb = zip->wbuff + (sizeof(zip->wbuff) - zip->wbuff_remaining); + rs = read(zip->temp_fd, wb, rsize); + if (rs < 0) { + archive_set_error(&(a->archive), errno, + "Can't read temporary file(%jd)", + (intmax_t)rs); + return (ARCHIVE_FATAL); + } + if (rs == 0) { + archive_set_error(&(a->archive), 0, + "Truncated 7-Zip archive"); + return (ARCHIVE_FATAL); + } + zip->wbuff_remaining -= rs; + length -= rs; + if (zip->wbuff_remaining == 0) { + r = flush_wbuff(a); + if (r != ARCHIVE_OK) + return (r); + } + } + return (ARCHIVE_OK); +} + +static int +_7z_close(struct archive_write *a) +{ + struct _7zip *zip; + unsigned char *wb; + uint64_t header_offset, header_size, header_unpacksize; + uint64_t length; + uint32_t header_crc32; + int r; + + zip = (struct _7zip *)a->format_data; + + if (zip->total_number_entry > 0) { + struct archive_rb_node *n; + uint64_t data_offset, data_size, data_unpacksize; + unsigned header_compression; + + r = (int)compress_out(a, NULL, 0, ARCHIVE_Z_FINISH); + if (r < 0) + return (r); + data_offset = 0; + data_size = zip->stream.total_out; + data_unpacksize = zip->stream.total_in; + zip->coder.codec = zip->opt_compression; + zip->coder.prop_size = zip->stream.prop_size; + zip->coder.props = zip->stream.props; + zip->stream.prop_size = 0; + zip->stream.props = NULL; + zip->total_number_nonempty_entry = + zip->total_number_entry - zip->total_number_empty_entry; + + /* Connect an empty file list. */ + if (zip->empty_list.first != NULL) { + *zip->file_list.last = zip->empty_list.first; + zip->file_list.last = zip->empty_list.last; + } + /* Connect a directory file list. */ + ARCHIVE_RB_TREE_FOREACH(n, &(zip->rbtree)) { + file_register(zip, (struct file *)n); + } + + /* + * NOTE: 7z command supports just LZMA1, LZMA2 and COPY for + * the compression type for encoding the header. + */ +#if HAVE_LZMA_H + header_compression = _7Z_LZMA1; + /* If the stored file is only one, do not encode the header. + * This is the same way 7z command does. */ + if (zip->total_number_entry == 1) + header_compression = _7Z_COPY; +#else + header_compression = _7Z_COPY; +#endif + r = _7z_compression_init_encoder(a, header_compression, 6); + if (r < 0) + return (r); + zip->crc32flg = PRECODE_CRC32; + zip->precode_crc32 = 0; + r = make_header(a, data_offset, data_size, data_unpacksize, + 1, &(zip->coder)); + if (r < 0) + return (r); + r = (int)compress_out(a, NULL, 0, ARCHIVE_Z_FINISH); + if (r < 0) + return (r); + header_offset = data_offset + data_size; + header_size = zip->stream.total_out; + header_crc32 = zip->precode_crc32; + header_unpacksize = zip->stream.total_in; + + if (header_compression != _7Z_COPY) { + /* + * Encode the header in order to reduce the size + * of the archive. + */ + free(zip->coder.props); + zip->coder.codec = header_compression; + zip->coder.prop_size = zip->stream.prop_size; + zip->coder.props = zip->stream.props; + zip->stream.prop_size = 0; + zip->stream.props = NULL; + + r = _7z_compression_init_encoder(a, _7Z_COPY, 0); + if (r < 0) + return (r); + zip->crc32flg = ENCODED_CRC32; + zip->encoded_crc32 = 0; + + /* + * Make EncodedHeader. + */ + r = enc_uint64(a, kEncodedHeader); + if (r < 0) + return (r); + r = make_streamsInfo(a, header_offset, header_size, + header_unpacksize, 1, &(zip->coder), 0, + header_crc32); + if (r < 0) + return (r); + r = (int)compress_out(a, NULL, 0, ARCHIVE_Z_FINISH); + if (r < 0) + return (r); + header_offset = header_offset + header_size; + header_size = zip->stream.total_out; + header_crc32 = zip->encoded_crc32; + } + zip->crc32flg = 0; + } else { + header_offset = header_size = 0; + header_crc32 = 0; + } + + length = zip->temp_offset; + + /* + * Make the zip header on wbuff(write buffer). + */ + wb = zip->wbuff; + zip->wbuff_remaining = sizeof(zip->wbuff); + memcpy(&wb[0], "7z\xBC\xAF\x27\x1C", 6); + wb[6] = 0;/* Major version. */ + wb[7] = 3;/* Minor version. */ + archive_le64enc(&wb[12], header_offset);/* Next Header Offset */ + archive_le64enc(&wb[20], header_size);/* Next Header Size */ + archive_le32enc(&wb[28], header_crc32);/* Next Header CRC */ + archive_le32enc(&wb[8], crc32(0, &wb[12], 20));/* Start Header CRC */ + zip->wbuff_remaining -= 32; + + /* + * Read all file contents and an encoded header from the temporary + * file and write out it. + */ + r = copy_out(a, 0, length); + if (r != ARCHIVE_OK) + return (r); + r = flush_wbuff(a); + return (r); +} + +/* + * Encode 64 bits value into 7-Zip's encoded UINT64 value. + */ +static int +enc_uint64(struct archive_write *a, uint64_t val) +{ + unsigned mask = 0x80; + uint8_t numdata[9]; + int i; + + numdata[0] = 0; + for (i = 1; i < (int)sizeof(numdata); i++) { + if (val < mask) { + numdata[0] |= (uint8_t)val; + break; + } + numdata[i] = (uint8_t)val; + val >>= 8; + numdata[0] |= mask; + mask >>= 1; + } + return ((int)compress_out(a, numdata, i, ARCHIVE_Z_RUN)); +} + +static int +make_substreamsInfo(struct archive_write *a, struct coder *coders) +{ + struct _7zip *zip = (struct _7zip *)a->format_data; + struct file *file; + int r; + + /* + * Make SubStreamsInfo. + */ + r = enc_uint64(a, kSubStreamsInfo); + if (r < 0) + return (r); + + if (zip->total_number_nonempty_entry > 1 && coders->codec != _7Z_COPY) { + /* + * Make NumUnPackStream. + */ + r = enc_uint64(a, kNumUnPackStream); + if (r < 0) + return (r); + + /* Write numUnpackStreams */ + r = enc_uint64(a, zip->total_number_nonempty_entry); + if (r < 0) + return (r); + + /* + * Make kSize. + */ + r = enc_uint64(a, kSize); + if (r < 0) + return (r); + file = zip->file_list.first; + for (;file != NULL; file = file->next) { + if (file->next == NULL || + file->next->size == 0) + break; + r = enc_uint64(a, file->size); + if (r < 0) + return (r); + } + } + + /* + * Make CRC. + */ + r = enc_uint64(a, kCRC); + if (r < 0) + return (r); + + + /* All are defined */ + r = enc_uint64(a, 1); + if (r < 0) + return (r); + file = zip->file_list.first; + for (;file != NULL; file = file->next) { + uint8_t crc[4]; + if (file->size == 0) + break; + archive_le32enc(crc, file->crc32); + r = (int)compress_out(a, crc, 4, ARCHIVE_Z_RUN); + if (r < 0) + return (r); + } + + /* Write End. */ + r = enc_uint64(a, kEnd); + if (r < 0) + return (r); + return (ARCHIVE_OK); +} + +static int +make_streamsInfo(struct archive_write *a, uint64_t offset, uint64_t pack_size, + uint64_t unpack_size, int num_coder, struct coder *coders, int substrm, + uint32_t header_crc) +{ + struct _7zip *zip = (struct _7zip *)a->format_data; + uint8_t codec_buff[8]; + int numFolders, fi; + int codec_size; + int i, r; + + if (coders->codec == _7Z_COPY) + numFolders = (int)zip->total_number_nonempty_entry; + else + numFolders = 1; + + /* + * Make PackInfo. + */ + r = enc_uint64(a, kPackInfo); + if (r < 0) + return (r); + + /* Write PackPos. */ + r = enc_uint64(a, offset); + if (r < 0) + return (r); + + /* Write NumPackStreams. */ + r = enc_uint64(a, numFolders); + if (r < 0) + return (r); + + /* Make Size. */ + r = enc_uint64(a, kSize); + if (r < 0) + return (r); + + if (numFolders > 1) { + struct file *file = zip->file_list.first; + for (;file != NULL; file = file->next) { + if (file->size == 0) + break; + r = enc_uint64(a, file->size); + if (r < 0) + return (r); + } + } else { + /* Write size. */ + r = enc_uint64(a, pack_size); + if (r < 0) + return (r); + } + + r = enc_uint64(a, kEnd); + if (r < 0) + return (r); + + /* + * Make UnPackInfo. + */ + r = enc_uint64(a, kUnPackInfo); + if (r < 0) + return (r); + + /* + * Make Folder. + */ + r = enc_uint64(a, kFolder); + if (r < 0) + return (r); + + /* Write NumFolders. */ + r = enc_uint64(a, numFolders); + if (r < 0) + return (r); + + /* Write External. */ + r = enc_uint64(a, 0); + if (r < 0) + return (r); + + for (fi = 0; fi < numFolders; fi++) { + /* Write NumCoders. */ + r = enc_uint64(a, num_coder); + if (r < 0) + return (r); + + for (i = 0; i < num_coder; i++) { + unsigned codec_id = coders[i].codec; + + /* Write Codec flag. */ + archive_be64enc(codec_buff, codec_id); + for (codec_size = 8; codec_size > 0; codec_size--) { + if (codec_buff[8 - codec_size]) + break; + } + if (codec_size == 0) + codec_size = 1; + if (coders[i].prop_size) + r = enc_uint64(a, codec_size | 0x20); + else + r = enc_uint64(a, codec_size); + if (r < 0) + return (r); + + /* Write Codec ID. */ + codec_size &= 0x0f; + r = (int)compress_out(a, &codec_buff[8-codec_size], + codec_size, ARCHIVE_Z_RUN); + if (r < 0) + return (r); + + if (coders[i].prop_size) { + /* Write Codec property size. */ + r = enc_uint64(a, coders[i].prop_size); + if (r < 0) + return (r); + + /* Write Codec properties. */ + r = (int)compress_out(a, coders[i].props, + coders[i].prop_size, ARCHIVE_Z_RUN); + if (r < 0) + return (r); + } + } + } + + /* + * Make CodersUnPackSize. + */ + r = enc_uint64(a, kCodersUnPackSize); + if (r < 0) + return (r); + + if (numFolders > 1) { + struct file *file = zip->file_list.first; + for (;file != NULL; file = file->next) { + if (file->size == 0) + break; + r = enc_uint64(a, file->size); + if (r < 0) + return (r); + } + + } else { + /* Write UnPackSize. */ + r = enc_uint64(a, unpack_size); + if (r < 0) + return (r); + } + + if (!substrm) { + uint8_t crc[4]; + /* + * Make CRC. + */ + r = enc_uint64(a, kCRC); + if (r < 0) + return (r); + + /* All are defined */ + r = enc_uint64(a, 1); + if (r < 0) + return (r); + archive_le32enc(crc, header_crc); + r = (int)compress_out(a, crc, 4, ARCHIVE_Z_RUN); + if (r < 0) + return (r); + } + + /* Write End. */ + r = enc_uint64(a, kEnd); + if (r < 0) + return (r); + + if (substrm) { + /* + * Make SubStreamsInfo. + */ + r = make_substreamsInfo(a, coders); + if (r < 0) + return (r); + } + + + /* Write End. */ + r = enc_uint64(a, kEnd); + if (r < 0) + return (r); + + return (ARCHIVE_OK); +} + + +#define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000) +static uint64_t +utcToFiletime(time_t t, long ns) +{ + uint64_t fileTime; + + fileTime = t; + fileTime *= 10000000; + fileTime += ns / 100; + fileTime += EPOC_TIME; + return (fileTime); +} + +static int +make_time(struct archive_write *a, uint8_t type, unsigned flg, int ti) +{ + uint8_t filetime[8]; + struct _7zip *zip = (struct _7zip *)a->format_data; + struct file *file; + int r; + uint8_t b, mask; + + /* + * Make Time Bools. + */ + if (zip->total_number_time_defined[ti] == zip->total_number_entry) { + /* Write Time Type. */ + r = enc_uint64(a, type); + if (r < 0) + return (r); + /* Write EmptyStream Size. */ + r = enc_uint64(a, 2 + zip->total_number_entry * 8); + if (r < 0) + return (r); + /* All are defined. */ + r = enc_uint64(a, 1); + if (r < 0) + return (r); + } else { + if (zip->total_number_time_defined[ti] == 0) + return (ARCHIVE_OK); + + /* Write Time Type. */ + r = enc_uint64(a, type); + if (r < 0) + return (r); + /* Write EmptyStream Size. */ + r = enc_uint64(a, 2 + ((zip->total_number_entry + 7) >> 3) + + zip->total_number_time_defined[ti] * 8); + if (r < 0) + return (r); + + /* All are not defined. */ + r = enc_uint64(a, 0); + if (r < 0) + return (r); + + b = 0; + mask = 0x80; + file = zip->file_list.first; + for (;file != NULL; file = file->next) { + if (file->flg & flg) + b |= mask; + mask >>= 1; + if (mask == 0) { + r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN); + if (r < 0) + return (r); + mask = 0x80; + b = 0; + } + } + if (mask != 0x80) { + r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN); + if (r < 0) + return (r); + } + } + + /* External. */ + r = enc_uint64(a, 0); + if (r < 0) + return (r); + + + /* + * Make Times. + */ + file = zip->file_list.first; + for (;file != NULL; file = file->next) { + if ((file->flg & flg) == 0) + continue; + archive_le64enc(filetime, utcToFiletime(file->times[ti].time, + file->times[ti].time_ns)); + r = (int)compress_out(a, filetime, 8, ARCHIVE_Z_RUN); + if (r < 0) + return (r); + } + + return (ARCHIVE_OK); +} + +static int +make_header(struct archive_write *a, uint64_t offset, uint64_t pack_size, + uint64_t unpack_size, int codernum, struct coder *coders) +{ + struct _7zip *zip = (struct _7zip *)a->format_data; + struct file *file; + int r; + uint8_t b, mask; + + /* + * Make FilesInfo. + */ + r = enc_uint64(a, kHeader); + if (r < 0) + return (r); + + /* + * If there are empty files only, do not write MainStreamInfo. + */ + if (zip->total_number_nonempty_entry) { + /* + * Make MainStreamInfo. + */ + r = enc_uint64(a, kMainStreamsInfo); + if (r < 0) + return (r); + r = make_streamsInfo(a, offset, pack_size, unpack_size, + codernum, coders, 1, 0); + if (r < 0) + return (r); + } + + /* + * Make FilesInfo. + */ + r = enc_uint64(a, kFilesInfo); + if (r < 0) + return (r); + + /* Write numFiles. */ + r = enc_uint64(a, zip->total_number_entry); + if (r < 0) + return (r); + + if (zip->total_number_empty_entry > 0) { + /* Make EmptyStream. */ + r = enc_uint64(a, kEmptyStream); + if (r < 0) + return (r); + + /* Write EmptyStream Size. */ + r = enc_uint64(a, (zip->total_number_entry+7)>>3); + if (r < 0) + return (r); + + b = 0; + mask = 0x80; + file = zip->file_list.first; + for (;file != NULL; file = file->next) { + if (file->size == 0) + b |= mask; + mask >>= 1; + if (mask == 0) { + r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN); + if (r < 0) + return (r); + mask = 0x80; + b = 0; + } + } + if (mask != 0x80) { + r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN); + if (r < 0) + return (r); + } + } + + if (zip->total_number_empty_entry > zip->total_number_dir_entry) { + /* Make EmptyFile. */ + r = enc_uint64(a, kEmptyFile); + if (r < 0) + return (r); + + /* Write EmptyFile Size. */ + r = enc_uint64(a, (zip->total_number_empty_entry + 7) >> 3); + if (r < 0) + return (r); + + b = 0; + mask = 0x80; + file = zip->file_list.first; + for (;file != NULL; file = file->next) { + if (file->size) + continue; + if (!file->dir) + b |= mask; + mask >>= 1; + if (mask == 0) { + r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN); + if (r < 0) + return (r); + mask = 0x80; + b = 0; + } + } + if (mask != 0x80) { + r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN); + if (r < 0) + return (r); + } + } + + /* Make Name. */ + r = enc_uint64(a, kName); + if (r < 0) + return (r); + + /* Write Name size. */ + r = enc_uint64(a, zip->total_bytes_entry_name+1); + if (r < 0) + return (r); + + /* Write dmy byte. */ + r = enc_uint64(a, 0); + if (r < 0) + return (r); + + file = zip->file_list.first; + for (;file != NULL; file = file->next) { + r = (int)compress_out(a, file->utf16name, file->name_len+2, + ARCHIVE_Z_RUN); + if (r < 0) + return (r); + } + + /* Make MTime. */ + r = make_time(a, kMTime, MTIME_IS_SET, MTIME); + if (r < 0) + return (r); + + /* Make CTime. */ + r = make_time(a, kCTime, CTIME_IS_SET, CTIME); + if (r < 0) + return (r); + + /* Make ATime. */ + r = make_time(a, kATime, ATIME_IS_SET, ATIME); + if (r < 0) + return (r); + + /* Make Attributes. */ + r = enc_uint64(a, kAttributes); + if (r < 0) + return (r); + + /* Write Attributes size. */ + r = enc_uint64(a, 2 + zip->total_number_entry * 4); + if (r < 0) + return (r); + + /* Write "All Are Defined". */ + r = enc_uint64(a, 1); + if (r < 0) + return (r); + + /* Write dmy byte. */ + r = enc_uint64(a, 0); + if (r < 0) + return (r); + + file = zip->file_list.first; + for (;file != NULL; file = file->next) { + /* + * High 16bits is unix mode. + * Low 16bits is Windows attributes. + */ + uint32_t encattr, attr; + if (file->dir) + attr = 0x8010; + else + attr = 0x8020; + if ((file->mode & 0222) == 0) + attr |= 1;/* Read Only. */ + attr |= ((uint32_t)file->mode) << 16; + archive_le32enc(&encattr, attr); + r = (int)compress_out(a, &encattr, 4, ARCHIVE_Z_RUN); + if (r < 0) + return (r); + } + + /* Write End. */ + r = enc_uint64(a, kEnd); + if (r < 0) + return (r); + + /* Write End. */ + r = enc_uint64(a, kEnd); + if (r < 0) + return (r); + + return (ARCHIVE_OK); +} + + +static int +_7z_free(struct archive_write *a) +{ + struct _7zip *zip = (struct _7zip *)a->format_data; + + /* Close the temporary file. */ + if (zip->temp_fd >= 0) + close(zip->temp_fd); + + file_free_register(zip); + compression_end(&(a->archive), &(zip->stream)); + free(zip->coder.props); + free(zip); + + return (ARCHIVE_OK); +} + +static int +file_cmp_node(const struct archive_rb_node *n1, + const struct archive_rb_node *n2) +{ + const struct file *f1 = (const struct file *)n1; + const struct file *f2 = (const struct file *)n2; + + if (f1->name_len == f2->name_len) + return (memcmp(f1->utf16name, f2->utf16name, f1->name_len)); + return (f1->name_len > f2->name_len)?1:-1; +} + +static int +file_cmp_key(const struct archive_rb_node *n, const void *key) +{ + const struct file *f = (const struct file *)n; + + return (f->name_len - *(const char *)key); +} + +static int +file_new(struct archive_write *a, struct archive_entry *entry, + struct file **newfile) +{ + struct _7zip *zip; + struct file *file; + const char *u16; + size_t u16len; + int ret = ARCHIVE_OK; + + zip = (struct _7zip *)a->format_data; + *newfile = NULL; + + file = calloc(1, sizeof(*file)); + if (file == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + + if (0 > archive_entry_pathname_l(entry, &u16, &u16len, zip->sconv)) { + if (errno == ENOMEM) { + free(file); + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for UTF-16LE"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "A filename cannot be converted to UTF-16LE;" + "You should disable making Joliet extension"); + ret = ARCHIVE_WARN; + } + file->utf16name = malloc(u16len + 2); + if (file->utf16name == NULL) { + free(file); + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Name"); + return (ARCHIVE_FATAL); + } + memcpy(file->utf16name, u16, u16len); + file->utf16name[u16len+0] = 0; + file->utf16name[u16len+1] = 0; + file->name_len = (unsigned)u16len; + file->mode = archive_entry_mode(entry); + if (archive_entry_filetype(entry) == AE_IFREG) + file->size = archive_entry_size(entry); + else + archive_entry_set_size(entry, 0); + if (archive_entry_filetype(entry) == AE_IFDIR) + file->dir = 1; + else if (archive_entry_filetype(entry) == AE_IFLNK) + file->size = strlen(archive_entry_symlink(entry)); + if (archive_entry_mtime_is_set(entry)) { + file->flg |= MTIME_IS_SET; + file->times[MTIME].time = archive_entry_mtime(entry); + file->times[MTIME].time_ns = archive_entry_mtime_nsec(entry); + } + if (archive_entry_atime_is_set(entry)) { + file->flg |= ATIME_IS_SET; + file->times[ATIME].time = archive_entry_atime(entry); + file->times[ATIME].time_ns = archive_entry_atime_nsec(entry); + } + if (archive_entry_ctime_is_set(entry)) { + file->flg |= CTIME_IS_SET; + file->times[CTIME].time = archive_entry_ctime(entry); + file->times[CTIME].time_ns = archive_entry_ctime_nsec(entry); + } + + *newfile = file; + return (ret); +} + +static void +file_free(struct file *file) +{ + free(file->utf16name); + free(file); +} + +static void +file_register(struct _7zip *zip, struct file *file) +{ + file->next = NULL; + *zip->file_list.last = file; + zip->file_list.last = &(file->next); +} + +static void +file_init_register(struct _7zip *zip) +{ + zip->file_list.first = NULL; + zip->file_list.last = &(zip->file_list.first); +} + +static void +file_free_register(struct _7zip *zip) +{ + struct file *file, *file_next; + + file = zip->file_list.first; + while (file != NULL) { + file_next = file->next; + file_free(file); + file = file_next; + } +} + +static void +file_register_empty(struct _7zip *zip, struct file *file) +{ + file->next = NULL; + *zip->empty_list.last = file; + zip->empty_list.last = &(file->next); +} + +static void +file_init_register_empty(struct _7zip *zip) +{ + zip->empty_list.first = NULL; + zip->empty_list.last = &(zip->empty_list.first); +} + +#if !defined(HAVE_ZLIB_H) || !defined(HAVE_BZLIB_H) ||\ + !defined(BZ_CONFIG_ERROR) || !defined(HAVE_LZMA_H) +static int +compression_unsupported_encoder(struct archive *a, + struct la_zstream *lastrm, const char *name) +{ + + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "%s compression not supported on this platform", name); + lastrm->valid = 0; + lastrm->real_stream = NULL; + return (ARCHIVE_FAILED); +} +#endif + +/* + * _7_COPY compressor. + */ +static int +compression_init_encoder_copy(struct archive *a, struct la_zstream *lastrm) +{ + + if (lastrm->valid) + compression_end(a, lastrm); + lastrm->valid = 1; + lastrm->code = compression_code_copy; + lastrm->end = compression_end_copy; + return (ARCHIVE_OK); +} + +static int +compression_code_copy(struct archive *a, + struct la_zstream *lastrm, enum la_zaction action) +{ + size_t bytes; + + (void)a; /* UNUSED */ + if (lastrm->avail_out > lastrm->avail_in) + bytes = lastrm->avail_in; + else + bytes = lastrm->avail_out; + if (bytes) { + memcpy(lastrm->next_out, lastrm->next_in, bytes); + lastrm->next_in += bytes; + lastrm->avail_in -= bytes; + lastrm->total_in += bytes; + lastrm->next_out += bytes; + lastrm->avail_out -= bytes; + lastrm->total_out += bytes; + } + if (action == ARCHIVE_Z_FINISH && lastrm->avail_in == 0) + return (ARCHIVE_EOF); + return (ARCHIVE_OK); +} + +static int +compression_end_copy(struct archive *a, struct la_zstream *lastrm) +{ + (void)a; /* UNUSED */ + lastrm->valid = 0; + return (ARCHIVE_OK); +} + +/* + * _7_DEFLATE compressor. + */ +#ifdef HAVE_ZLIB_H +static int +compression_init_encoder_deflate(struct archive *a, + struct la_zstream *lastrm, int level, int withheader) +{ + z_stream *strm; + + if (lastrm->valid) + compression_end(a, lastrm); + strm = calloc(1, sizeof(*strm)); + if (strm == NULL) { + archive_set_error(a, ENOMEM, + "Can't allocate memory for gzip stream"); + return (ARCHIVE_FATAL); + } + /* zlib.h is not const-correct, so we need this one bit + * of ugly hackery to convert a const * pointer to + * a non-const pointer. */ + strm->next_in = (Bytef *)(uintptr_t)(const void *)lastrm->next_in; + strm->avail_in = (uInt)lastrm->avail_in; + strm->total_in = (uLong)lastrm->total_in; + strm->next_out = lastrm->next_out; + strm->avail_out = (uInt)lastrm->avail_out; + strm->total_out = (uLong)lastrm->total_out; + if (deflateInit2(strm, level, Z_DEFLATED, + (withheader)?15:-15, + 8, Z_DEFAULT_STRATEGY) != Z_OK) { + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library"); + return (ARCHIVE_FATAL); + } + lastrm->real_stream = strm; + lastrm->valid = 1; + lastrm->code = compression_code_deflate; + lastrm->end = compression_end_deflate; + return (ARCHIVE_OK); +} + +static int +compression_code_deflate(struct archive *a, + struct la_zstream *lastrm, enum la_zaction action) +{ + z_stream *strm; + int r; + + strm = (z_stream *)lastrm->real_stream; + /* zlib.h is not const-correct, so we need this one bit + * of ugly hackery to convert a const * pointer to + * a non-const pointer. */ + strm->next_in = (Bytef *)(uintptr_t)(const void *)lastrm->next_in; + strm->avail_in = (uInt)lastrm->avail_in; + strm->total_in = (uLong)lastrm->total_in; + strm->next_out = lastrm->next_out; + strm->avail_out = (uInt)lastrm->avail_out; + strm->total_out = (uLong)lastrm->total_out; + r = deflate(strm, + (action == ARCHIVE_Z_FINISH)? Z_FINISH: Z_NO_FLUSH); + lastrm->next_in = strm->next_in; + lastrm->avail_in = strm->avail_in; + lastrm->total_in = strm->total_in; + lastrm->next_out = strm->next_out; + lastrm->avail_out = strm->avail_out; + lastrm->total_out = strm->total_out; + switch (r) { + case Z_OK: + return (ARCHIVE_OK); + case Z_STREAM_END: + return (ARCHIVE_EOF); + default: + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "GZip compression failed:" + " deflate() call returned status %d", r); + return (ARCHIVE_FATAL); + } +} + +static int +compression_end_deflate(struct archive *a, struct la_zstream *lastrm) +{ + z_stream *strm; + int r; + + strm = (z_stream *)lastrm->real_stream; + r = deflateEnd(strm); + free(strm); + lastrm->real_stream = NULL; + lastrm->valid = 0; + if (r != Z_OK) { + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Failed to clean up compressor"); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_OK); +} +#else +static int +compression_init_encoder_deflate(struct archive *a, + struct la_zstream *lastrm, int level, int withheader) +{ + + (void) level; /* UNUSED */ + (void) withheader; /* UNUSED */ + if (lastrm->valid) + compression_end(a, lastrm); + return (compression_unsupported_encoder(a, lastrm, "deflate")); +} +#endif + +/* + * _7_BZIP2 compressor. + */ +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) +static int +compression_init_encoder_bzip2(struct archive *a, + struct la_zstream *lastrm, int level) +{ + bz_stream *strm; + + if (lastrm->valid) + compression_end(a, lastrm); + strm = calloc(1, sizeof(*strm)); + if (strm == NULL) { + archive_set_error(a, ENOMEM, + "Can't allocate memory for bzip2 stream"); + return (ARCHIVE_FATAL); + } + /* bzlib.h is not const-correct, so we need this one bit + * of ugly hackery to convert a const * pointer to + * a non-const pointer. */ + strm->next_in = (char *)(uintptr_t)(const void *)lastrm->next_in; + strm->avail_in = lastrm->avail_in; + strm->total_in_lo32 = (uint32_t)(lastrm->total_in & 0xffffffff); + strm->total_in_hi32 = (uint32_t)(lastrm->total_in >> 32); + strm->next_out = (char *)lastrm->next_out; + strm->avail_out = lastrm->avail_out; + strm->total_out_lo32 = (uint32_t)(lastrm->total_out & 0xffffffff); + strm->total_out_hi32 = (uint32_t)(lastrm->total_out >> 32); + if (BZ2_bzCompressInit(strm, level, 0, 30) != BZ_OK) { + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library"); + return (ARCHIVE_FATAL); + } + lastrm->real_stream = strm; + lastrm->valid = 1; + lastrm->code = compression_code_bzip2; + lastrm->end = compression_end_bzip2; + return (ARCHIVE_OK); +} + +static int +compression_code_bzip2(struct archive *a, + struct la_zstream *lastrm, enum la_zaction action) +{ + bz_stream *strm; + int r; + + strm = (bz_stream *)lastrm->real_stream; + /* bzlib.h is not const-correct, so we need this one bit + * of ugly hackery to convert a const * pointer to + * a non-const pointer. */ + strm->next_in = (char *)(uintptr_t)(const void *)lastrm->next_in; + strm->avail_in = lastrm->avail_in; + strm->total_in_lo32 = (uint32_t)(lastrm->total_in & 0xffffffff); + strm->total_in_hi32 = (uint32_t)(lastrm->total_in >> 32); + strm->next_out = (char *)lastrm->next_out; + strm->avail_out = lastrm->avail_out; + strm->total_out_lo32 = (uint32_t)(lastrm->total_out & 0xffffffff); + strm->total_out_hi32 = (uint32_t)(lastrm->total_out >> 32); + r = BZ2_bzCompress(strm, + (action == ARCHIVE_Z_FINISH)? BZ_FINISH: BZ_RUN); + lastrm->next_in = (const unsigned char *)strm->next_in; + lastrm->avail_in = strm->avail_in; + lastrm->total_in = + (((uint64_t)(uint32_t)strm->total_in_hi32) << 32) + + (uint64_t)(uint32_t)strm->total_in_lo32; + lastrm->next_out = (unsigned char *)strm->next_out; + lastrm->avail_out = strm->avail_out; + lastrm->total_out = + (((uint64_t)(uint32_t)strm->total_out_hi32) << 32) + + (uint64_t)(uint32_t)strm->total_out_lo32; + switch (r) { + case BZ_RUN_OK: /* Non-finishing */ + case BZ_FINISH_OK: /* Finishing: There's more work to do */ + return (ARCHIVE_OK); + case BZ_STREAM_END: /* Finishing: all done */ + /* Only occurs in finishing case */ + return (ARCHIVE_EOF); + default: + /* Any other return value indicates an error */ + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Bzip2 compression failed:" + " BZ2_bzCompress() call returned status %d", r); + return (ARCHIVE_FATAL); + } +} + +static int +compression_end_bzip2(struct archive *a, struct la_zstream *lastrm) +{ + bz_stream *strm; + int r; + + strm = (bz_stream *)lastrm->real_stream; + r = BZ2_bzCompressEnd(strm); + free(strm); + lastrm->real_stream = NULL; + lastrm->valid = 0; + if (r != BZ_OK) { + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Failed to clean up compressor"); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_OK); +} + +#else +static int +compression_init_encoder_bzip2(struct archive *a, + struct la_zstream *lastrm, int level) +{ + + (void) level; /* UNUSED */ + if (lastrm->valid) + compression_end(a, lastrm); + return (compression_unsupported_encoder(a, lastrm, "bzip2")); +} +#endif + +/* + * _7_LZMA1, _7_LZMA2 compressor. + */ +#if defined(HAVE_LZMA_H) +static int +compression_init_encoder_lzma(struct archive *a, + struct la_zstream *lastrm, int level, uint64_t filter_id) +{ + static const lzma_stream lzma_init_data = LZMA_STREAM_INIT; + lzma_stream *strm; + lzma_filter *lzmafilters; + lzma_options_lzma lzma_opt; + int r; + + if (lastrm->valid) + compression_end(a, lastrm); + strm = calloc(1, sizeof(*strm) + sizeof(*lzmafilters) * 2); + if (strm == NULL) { + archive_set_error(a, ENOMEM, + "Can't allocate memory for lzma stream"); + return (ARCHIVE_FATAL); + } + lzmafilters = (lzma_filter *)(strm+1); + if (level > 6) + level = 6; + if (lzma_lzma_preset(&lzma_opt, level)) { + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ENOMEM, + "Internal error initializing compression library"); + return (ARCHIVE_FATAL); + } + lzmafilters[0].id = filter_id; + lzmafilters[0].options = &lzma_opt; + lzmafilters[1].id = LZMA_VLI_UNKNOWN;/* Terminate */ + + r = lzma_properties_size(&(lastrm->prop_size), lzmafilters); + if (r != LZMA_OK) { + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "lzma_properties_size failed"); + return (ARCHIVE_FATAL); + } + if (lastrm->prop_size) { + lastrm->props = malloc(lastrm->prop_size); + if (lastrm->props == NULL) { + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ENOMEM, + "Cannot allocate memory"); + return (ARCHIVE_FATAL); + } + r = lzma_properties_encode(lzmafilters, lastrm->props); + if (r != LZMA_OK) { + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "lzma_properties_encode failed"); + return (ARCHIVE_FATAL); + } + } + + *strm = lzma_init_data; + r = lzma_raw_encoder(strm, lzmafilters); + switch (r) { + case LZMA_OK: + lastrm->real_stream = strm; + lastrm->valid = 1; + lastrm->code = compression_code_lzma; + lastrm->end = compression_end_lzma; + r = ARCHIVE_OK; + break; + case LZMA_MEM_ERROR: + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ENOMEM, + "Internal error initializing compression library: " + "Cannot allocate memory"); + r = ARCHIVE_FATAL; + break; + default: + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library: " + "It's a bug in liblzma"); + r = ARCHIVE_FATAL; + break; + } + return (r); +} + +static int +compression_init_encoder_lzma1(struct archive *a, + struct la_zstream *lastrm, int level) +{ + return compression_init_encoder_lzma(a, lastrm, level, + LZMA_FILTER_LZMA1); +} + +static int +compression_init_encoder_lzma2(struct archive *a, + struct la_zstream *lastrm, int level) +{ + return compression_init_encoder_lzma(a, lastrm, level, + LZMA_FILTER_LZMA2); +} + +static int +compression_code_lzma(struct archive *a, + struct la_zstream *lastrm, enum la_zaction action) +{ + lzma_stream *strm; + int r; + + strm = (lzma_stream *)lastrm->real_stream; + strm->next_in = lastrm->next_in; + strm->avail_in = lastrm->avail_in; + strm->total_in = lastrm->total_in; + strm->next_out = lastrm->next_out; + strm->avail_out = lastrm->avail_out; + strm->total_out = lastrm->total_out; + r = lzma_code(strm, + (action == ARCHIVE_Z_FINISH)? LZMA_FINISH: LZMA_RUN); + lastrm->next_in = strm->next_in; + lastrm->avail_in = strm->avail_in; + lastrm->total_in = strm->total_in; + lastrm->next_out = strm->next_out; + lastrm->avail_out = strm->avail_out; + lastrm->total_out = strm->total_out; + switch (r) { + case LZMA_OK: + /* Non-finishing case */ + return (ARCHIVE_OK); + case LZMA_STREAM_END: + /* This return can only occur in finishing case. */ + return (ARCHIVE_EOF); + case LZMA_MEMLIMIT_ERROR: + archive_set_error(a, ENOMEM, + "lzma compression error:" + " %ju MiB would have been needed", + (uintmax_t)((lzma_memusage(strm) + 1024 * 1024 -1) + / (1024 * 1024))); + return (ARCHIVE_FATAL); + default: + /* Any other return value indicates an error */ + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "lzma compression failed:" + " lzma_code() call returned status %d", r); + return (ARCHIVE_FATAL); + } +} + +static int +compression_end_lzma(struct archive *a, struct la_zstream *lastrm) +{ + lzma_stream *strm; + + (void)a; /* UNUSED */ + strm = (lzma_stream *)lastrm->real_stream; + lzma_end(strm); + free(strm); + lastrm->valid = 0; + lastrm->real_stream = NULL; + return (ARCHIVE_OK); +} +#else +static int +compression_init_encoder_lzma1(struct archive *a, + struct la_zstream *lastrm, int level) +{ + + (void) level; /* UNUSED */ + if (lastrm->valid) + compression_end(a, lastrm); + return (compression_unsupported_encoder(a, lastrm, "lzma")); +} +static int +compression_init_encoder_lzma2(struct archive *a, + struct la_zstream *lastrm, int level) +{ + + (void) level; /* UNUSED */ + if (lastrm->valid) + compression_end(a, lastrm); + return (compression_unsupported_encoder(a, lastrm, "lzma")); +} +#endif + +/* + * _7_PPMD compressor. + */ +static void +ppmd_write(void *p, Byte b) +{ + struct archive_write *a = ((IByteOut *)p)->a; + struct _7zip *zip = (struct _7zip *)(a->format_data); + struct la_zstream *lastrm = &(zip->stream); + struct ppmd_stream *strm; + + if (lastrm->avail_out) { + *lastrm->next_out++ = b; + lastrm->avail_out--; + lastrm->total_out++; + return; + } + strm = (struct ppmd_stream *)lastrm->real_stream; + if (strm->buff_ptr < strm->buff_end) { + *strm->buff_ptr++ = b; + strm->buff_bytes++; + } +} + +static int +compression_init_encoder_ppmd(struct archive *a, + struct la_zstream *lastrm, unsigned maxOrder, uint32_t msize) +{ + struct ppmd_stream *strm; + uint8_t *props; + int r; + + if (lastrm->valid) + compression_end(a, lastrm); + strm = calloc(1, sizeof(*strm)); + if (strm == NULL) { + archive_set_error(a, ENOMEM, + "Can't allocate memory for PPMd"); + return (ARCHIVE_FATAL); + } + strm->buff = malloc(32); + if (strm->buff == NULL) { + free(strm); + archive_set_error(a, ENOMEM, + "Can't allocate memory for PPMd"); + return (ARCHIVE_FATAL); + } + strm->buff_ptr = strm->buff; + strm->buff_end = strm->buff + 32; + + props = malloc(1+4); + if (props == NULL) { + free(strm->buff); + free(strm); + archive_set_error(a, ENOMEM, + "Coludn't allocate memory for PPMd"); + return (ARCHIVE_FATAL); + } + props[0] = maxOrder; + archive_le32enc(props+1, msize); + __archive_ppmd7_functions.Ppmd7_Construct(&strm->ppmd7_context); + r = __archive_ppmd7_functions.Ppmd7_Alloc( + &strm->ppmd7_context, msize); + if (r == 0) { + free(strm->buff); + free(strm); + free(props); + archive_set_error(a, ENOMEM, + "Coludn't allocate memory for PPMd"); + return (ARCHIVE_FATAL); + } + __archive_ppmd7_functions.Ppmd7_Init(&(strm->ppmd7_context), maxOrder); + strm->byteout.a = (struct archive_write *)a; + strm->byteout.Write = ppmd_write; + strm->range_enc.Stream = &(strm->byteout); + __archive_ppmd7_functions.Ppmd7z_RangeEnc_Init(&(strm->range_enc)); + strm->stat = 0; + + lastrm->real_stream = strm; + lastrm->valid = 1; + lastrm->code = compression_code_ppmd; + lastrm->end = compression_end_ppmd; + lastrm->prop_size = 5; + lastrm->props = props; + return (ARCHIVE_OK); +} + +static int +compression_code_ppmd(struct archive *a, + struct la_zstream *lastrm, enum la_zaction action) +{ + struct ppmd_stream *strm; + + (void)a; /* UNUSED */ + + strm = (struct ppmd_stream *)lastrm->real_stream; + + /* Copy encoded data if there are remaining bytes from previous call. */ + if (strm->buff_bytes) { + uint8_t *p = strm->buff_ptr - strm->buff_bytes; + while (lastrm->avail_out && strm->buff_bytes) { + *lastrm->next_out++ = *p++; + lastrm->avail_out--; + lastrm->total_out++; + strm->buff_bytes--; + } + if (strm->buff_bytes) + return (ARCHIVE_OK); + if (strm->stat == 1) + return (ARCHIVE_EOF); + strm->buff_ptr = strm->buff; + } + while (lastrm->avail_in && lastrm->avail_out) { + __archive_ppmd7_functions.Ppmd7_EncodeSymbol( + &(strm->ppmd7_context), &(strm->range_enc), + *lastrm->next_in++); + lastrm->avail_in--; + lastrm->total_in++; + } + if (lastrm->avail_in == 0 && action == ARCHIVE_Z_FINISH) { + __archive_ppmd7_functions.Ppmd7z_RangeEnc_FlushData( + &(strm->range_enc)); + strm->stat = 1; + /* Return EOF if there are no remaining bytes. */ + if (strm->buff_bytes == 0) + return (ARCHIVE_EOF); + } + return (ARCHIVE_OK); +} + +static int +compression_end_ppmd(struct archive *a, struct la_zstream *lastrm) +{ + struct ppmd_stream *strm; + + (void)a; /* UNUSED */ + + strm = (struct ppmd_stream *)lastrm->real_stream; + __archive_ppmd7_functions.Ppmd7_Free(&strm->ppmd7_context); + free(strm->buff); + free(strm); + lastrm->real_stream = NULL; + lastrm->valid = 0; + return (ARCHIVE_OK); +} + +/* + * Universal compressor initializer. + */ +static int +_7z_compression_init_encoder(struct archive_write *a, unsigned compression, + int compression_level) +{ + struct _7zip *zip; + int r; + + zip = (struct _7zip *)a->format_data; + switch (compression) { + case _7Z_DEFLATE: + r = compression_init_encoder_deflate( + &(a->archive), &(zip->stream), + compression_level, 0); + break; + case _7Z_BZIP2: + r = compression_init_encoder_bzip2( + &(a->archive), &(zip->stream), + compression_level); + break; + case _7Z_LZMA1: + r = compression_init_encoder_lzma1( + &(a->archive), &(zip->stream), + compression_level); + break; + case _7Z_LZMA2: + r = compression_init_encoder_lzma2( + &(a->archive), &(zip->stream), + compression_level); + break; + case _7Z_PPMD: + r = compression_init_encoder_ppmd( + &(a->archive), &(zip->stream), + PPMD7_DEFAULT_ORDER, PPMD7_DEFAULT_MEM_SIZE); + break; + case _7Z_COPY: + default: + r = compression_init_encoder_copy( + &(a->archive), &(zip->stream)); + break; + } + if (r == ARCHIVE_OK) { + zip->stream.total_in = 0; + zip->stream.next_out = zip->wbuff; + zip->stream.avail_out = sizeof(zip->wbuff); + zip->stream.total_out = 0; + } + + return (r); +} + +static int +compression_code(struct archive *a, struct la_zstream *lastrm, + enum la_zaction action) +{ + if (lastrm->valid) + return (lastrm->code(a, lastrm, action)); + return (ARCHIVE_OK); +} + +static int +compression_end(struct archive *a, struct la_zstream *lastrm) +{ + if (lastrm->valid) { + lastrm->prop_size = 0; + free(lastrm->props); + lastrm->props = NULL; + return (lastrm->end(a, lastrm)); + } + return (ARCHIVE_OK); +} + + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_ar.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_ar.c new file mode 100644 index 0000000000..fc0de1e9f6 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_ar.c @@ -0,0 +1,570 @@ +/*- + * Copyright (c) 2007 Kai Wang + * Copyright (c) 2007 Tim Kientzle + * 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 + * in this position and unchanged. + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_ar.c 201108 2009-12-28 03:28:21Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_write_private.h" +#include "archive_write_set_format_private.h" + +struct ar_w { + uint64_t entry_bytes_remaining; + uint64_t entry_padding; + int is_strtab; + int has_strtab; + char wrote_global_header; + char *strtab; +}; + +/* + * Define structure of the "ar" header. + */ +#define AR_name_offset 0 +#define AR_name_size 16 +#define AR_date_offset 16 +#define AR_date_size 12 +#define AR_uid_offset 28 +#define AR_uid_size 6 +#define AR_gid_offset 34 +#define AR_gid_size 6 +#define AR_mode_offset 40 +#define AR_mode_size 8 +#define AR_size_offset 48 +#define AR_size_size 10 +#define AR_fmag_offset 58 +#define AR_fmag_size 2 + +static int archive_write_set_format_ar(struct archive_write *); +static int archive_write_ar_header(struct archive_write *, + struct archive_entry *); +static ssize_t archive_write_ar_data(struct archive_write *, + const void *buff, size_t s); +static int archive_write_ar_free(struct archive_write *); +static int archive_write_ar_close(struct archive_write *); +static int archive_write_ar_finish_entry(struct archive_write *); +static const char *ar_basename(const char *path); +static int format_octal(int64_t v, char *p, int s); +static int format_decimal(int64_t v, char *p, int s); + +int +archive_write_set_format_ar_bsd(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + int r; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_ar_bsd"); + r = archive_write_set_format_ar(a); + if (r == ARCHIVE_OK) { + a->archive.archive_format = ARCHIVE_FORMAT_AR_BSD; + a->archive.archive_format_name = "ar (BSD)"; + } + return (r); +} + +int +archive_write_set_format_ar_svr4(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + int r; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_ar_svr4"); + r = archive_write_set_format_ar(a); + if (r == ARCHIVE_OK) { + a->archive.archive_format = ARCHIVE_FORMAT_AR_GNU; + a->archive.archive_format_name = "ar (GNU/SVR4)"; + } + return (r); +} + +/* + * Generic initialization. + */ +static int +archive_write_set_format_ar(struct archive_write *a) +{ + struct ar_w *ar; + + /* If someone else was already registered, unregister them. */ + if (a->format_free != NULL) + (a->format_free)(a); + + ar = (struct ar_w *)calloc(1, sizeof(*ar)); + if (ar == NULL) { + archive_set_error(&a->archive, ENOMEM, "Can't allocate ar data"); + return (ARCHIVE_FATAL); + } + a->format_data = ar; + + a->format_name = "ar"; + a->format_write_header = archive_write_ar_header; + a->format_write_data = archive_write_ar_data; + a->format_close = archive_write_ar_close; + a->format_free = archive_write_ar_free; + a->format_finish_entry = archive_write_ar_finish_entry; + return (ARCHIVE_OK); +} + +static int +archive_write_ar_header(struct archive_write *a, struct archive_entry *entry) +{ + int ret, append_fn; + char buff[60]; + char *ss, *se; + struct ar_w *ar; + const char *pathname; + const char *filename; + int64_t size; + + append_fn = 0; + ar = (struct ar_w *)a->format_data; + ar->is_strtab = 0; + filename = NULL; + size = archive_entry_size(entry); + + + /* + * Reject files with empty name. + */ + pathname = archive_entry_pathname(entry); + if (pathname == NULL || *pathname == '\0') { + archive_set_error(&a->archive, EINVAL, + "Invalid filename"); + return (ARCHIVE_WARN); + } + + /* + * If we are now at the beginning of the archive, + * we need first write the ar global header. + */ + if (!ar->wrote_global_header) { + __archive_write_output(a, "!<arch>\n", 8); + ar->wrote_global_header = 1; + } + + memset(buff, ' ', 60); + memcpy(&buff[AR_fmag_offset], "`\n", 2); + + if (strcmp(pathname, "/") == 0 ) { + /* Entry is archive symbol table in GNU format */ + buff[AR_name_offset] = '/'; + goto stat; + } + if (strcmp(pathname, "/SYM64/") == 0) { + /* Entry is archive symbol table in GNU 64-bit format */ + memcpy(buff + AR_name_offset, "/SYM64/", 7); + goto stat; + } + if (strcmp(pathname, "__.SYMDEF") == 0) { + /* Entry is archive symbol table in BSD format */ + memcpy(buff + AR_name_offset, "__.SYMDEF", 9); + goto stat; + } + if (strcmp(pathname, "//") == 0) { + /* + * Entry is archive filename table, inform that we should + * collect strtab in next _data call. + */ + ar->is_strtab = 1; + buff[AR_name_offset] = buff[AR_name_offset + 1] = '/'; + /* + * For archive string table, only ar_size field should + * be set. + */ + goto size; + } + + /* + * Otherwise, entry is a normal archive member. + * Strip leading paths from filenames, if any. + */ + if ((filename = ar_basename(pathname)) == NULL) { + /* Reject filenames with trailing "/" */ + archive_set_error(&a->archive, EINVAL, + "Invalid filename"); + return (ARCHIVE_WARN); + } + + if (a->archive.archive_format == ARCHIVE_FORMAT_AR_GNU) { + /* + * SVR4/GNU variant use a "/" to mark then end of the filename, + * make it possible to have embedded spaces in the filename. + * So, the longest filename here (without extension) is + * actually 15 bytes. + */ + if (strlen(filename) <= 15) { + memcpy(&buff[AR_name_offset], + filename, strlen(filename)); + buff[AR_name_offset + strlen(filename)] = '/'; + } else { + /* + * For filename longer than 15 bytes, GNU variant + * makes use of a string table and instead stores the + * offset of the real filename to in the ar_name field. + * The string table should have been written before. + */ + if (ar->has_strtab <= 0) { + archive_set_error(&a->archive, EINVAL, + "Can't find string table"); + return (ARCHIVE_WARN); + } + + se = (char *)malloc(strlen(filename) + 3); + if (se == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate filename buffer"); + return (ARCHIVE_FATAL); + } + + memcpy(se, filename, strlen(filename)); + strcpy(se + strlen(filename), "/\n"); + + ss = strstr(ar->strtab, se); + free(se); + + if (ss == NULL) { + archive_set_error(&a->archive, EINVAL, + "Invalid string table"); + return (ARCHIVE_WARN); + } + + /* + * GNU variant puts "/" followed by digits into + * ar_name field. These digits indicates the real + * filename string's offset to the string table. + */ + buff[AR_name_offset] = '/'; + if (format_decimal(ss - ar->strtab, + buff + AR_name_offset + 1, + AR_name_size - 1)) { + archive_set_error(&a->archive, ERANGE, + "string table offset too large"); + return (ARCHIVE_WARN); + } + } + } else if (a->archive.archive_format == ARCHIVE_FORMAT_AR_BSD) { + /* + * BSD variant: for any file name which is more than + * 16 chars or contains one or more embedded space(s), the + * string "#1/" followed by the ASCII length of the name is + * put into the ar_name field. The file size (stored in the + * ar_size field) is incremented by the length of the name. + * The name is then written immediately following the + * archive header. + */ + if (strlen(filename) <= 16 && strchr(filename, ' ') == NULL) { + memcpy(&buff[AR_name_offset], filename, strlen(filename)); + buff[AR_name_offset + strlen(filename)] = ' '; + } + else { + memcpy(buff + AR_name_offset, "#1/", 3); + if (format_decimal(strlen(filename), + buff + AR_name_offset + 3, + AR_name_size - 3)) { + archive_set_error(&a->archive, ERANGE, + "File name too long"); + return (ARCHIVE_WARN); + } + append_fn = 1; + size += strlen(filename); + } + } + +stat: + if (format_decimal(archive_entry_mtime(entry), buff + AR_date_offset, AR_date_size)) { + archive_set_error(&a->archive, ERANGE, + "File modification time too large"); + return (ARCHIVE_WARN); + } + if (format_decimal(archive_entry_uid(entry), buff + AR_uid_offset, AR_uid_size)) { + archive_set_error(&a->archive, ERANGE, + "Numeric user ID too large"); + return (ARCHIVE_WARN); + } + if (format_decimal(archive_entry_gid(entry), buff + AR_gid_offset, AR_gid_size)) { + archive_set_error(&a->archive, ERANGE, + "Numeric group ID too large"); + return (ARCHIVE_WARN); + } + if (format_octal(archive_entry_mode(entry), buff + AR_mode_offset, AR_mode_size)) { + archive_set_error(&a->archive, ERANGE, + "Numeric mode too large"); + return (ARCHIVE_WARN); + } + /* + * Sanity Check: A non-pseudo archive member should always be + * a regular file. + */ + if (filename != NULL && archive_entry_filetype(entry) != AE_IFREG) { + archive_set_error(&a->archive, EINVAL, + "Regular file required for non-pseudo member"); + return (ARCHIVE_WARN); + } + +size: + if (format_decimal(size, buff + AR_size_offset, AR_size_size)) { + archive_set_error(&a->archive, ERANGE, + "File size out of range"); + return (ARCHIVE_WARN); + } + + ret = __archive_write_output(a, buff, 60); + if (ret != ARCHIVE_OK) + return (ret); + + ar->entry_bytes_remaining = size; + ar->entry_padding = ar->entry_bytes_remaining % 2; + + if (append_fn > 0) { + ret = __archive_write_output(a, filename, strlen(filename)); + if (ret != ARCHIVE_OK) + return (ret); + ar->entry_bytes_remaining -= strlen(filename); + } + + return (ARCHIVE_OK); +} + +static ssize_t +archive_write_ar_data(struct archive_write *a, const void *buff, size_t s) +{ + struct ar_w *ar; + int ret; + + ar = (struct ar_w *)a->format_data; + if (s > ar->entry_bytes_remaining) + s = (size_t)ar->entry_bytes_remaining; + + if (ar->is_strtab > 0) { + if (ar->has_strtab > 0) { + archive_set_error(&a->archive, EINVAL, + "More than one string tables exist"); + return (ARCHIVE_WARN); + } + + ar->strtab = (char *)malloc(s + 1); + if (ar->strtab == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate strtab buffer"); + return (ARCHIVE_FATAL); + } + memcpy(ar->strtab, buff, s); + ar->strtab[s] = '\0'; + ar->has_strtab = 1; + } + + ret = __archive_write_output(a, buff, s); + if (ret != ARCHIVE_OK) + return (ret); + + ar->entry_bytes_remaining -= s; + return (s); +} + +static int +archive_write_ar_free(struct archive_write *a) +{ + struct ar_w *ar; + + ar = (struct ar_w *)a->format_data; + + if (ar == NULL) + return (ARCHIVE_OK); + + if (ar->has_strtab > 0) { + free(ar->strtab); + ar->strtab = NULL; + } + + free(ar); + a->format_data = NULL; + return (ARCHIVE_OK); +} + +static int +archive_write_ar_close(struct archive_write *a) +{ + struct ar_w *ar; + int ret; + + /* + * If we haven't written anything yet, we need to write + * the ar global header now to make it a valid ar archive. + */ + ar = (struct ar_w *)a->format_data; + if (!ar->wrote_global_header) { + ar->wrote_global_header = 1; + ret = __archive_write_output(a, "!<arch>\n", 8); + return (ret); + } + + return (ARCHIVE_OK); +} + +static int +archive_write_ar_finish_entry(struct archive_write *a) +{ + struct ar_w *ar; + int ret; + + ar = (struct ar_w *)a->format_data; + + if (ar->entry_bytes_remaining != 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Entry remaining bytes larger than 0"); + return (ARCHIVE_WARN); + } + + if (ar->entry_padding == 0) { + return (ARCHIVE_OK); + } + + if (ar->entry_padding != 1) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Padding wrong size: %ju should be 1 or 0", + (uintmax_t)ar->entry_padding); + return (ARCHIVE_WARN); + } + + ret = __archive_write_output(a, "\n", 1); + return (ret); +} + +/* + * Format a number into the specified field using base-8. + * NB: This version is slightly different from the one in + * _ustar.c + */ +static int +format_octal(int64_t v, char *p, int s) +{ + int len; + char *h; + + len = s; + h = p; + + /* Octal values can't be negative, so use 0. */ + if (v < 0) { + while (len-- > 0) + *p++ = '0'; + return (-1); + } + + p += s; /* Start at the end and work backwards. */ + do { + *--p = (char)('0' + (v & 7)); + v >>= 3; + } while (--s > 0 && v > 0); + + if (v == 0) { + memmove(h, p, len - s); + p = h + len - s; + while (s-- > 0) + *p++ = ' '; + return (0); + } + /* If it overflowed, fill field with max value. */ + while (len-- > 0) + *p++ = '7'; + + return (-1); +} + +/* + * Format a number into the specified field using base-10. + */ +static int +format_decimal(int64_t v, char *p, int s) +{ + int len; + char *h; + + len = s; + h = p; + + /* Negative values in ar header are meaningless, so use 0. */ + if (v < 0) { + while (len-- > 0) + *p++ = '0'; + return (-1); + } + + p += s; + do { + *--p = (char)('0' + (v % 10)); + v /= 10; + } while (--s > 0 && v > 0); + + if (v == 0) { + memmove(h, p, len - s); + p = h + len - s; + while (s-- > 0) + *p++ = ' '; + return (0); + } + /* If it overflowed, fill field with max value. */ + while (len-- > 0) + *p++ = '9'; + + return (-1); +} + +static const char * +ar_basename(const char *path) +{ + const char *endp, *startp; + + endp = path + strlen(path) - 1; + /* + * For filename with trailing slash(es), we return + * NULL indicating an error. + */ + if (*endp == '/') + return (NULL); + + /* Find the start of the base */ + startp = endp; + while (startp > path && *(startp - 1) != '/') + startp--; + + return (startp); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_by_name.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_by_name.c new file mode 100644 index 0000000000..86e8621ef7 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_by_name.c @@ -0,0 +1,92 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_by_name.c 201168 2009-12-29 06:15:32Z kientzle $"); + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_private.h" + +/* A table that maps names to functions. */ +static const +struct { const char *name; int (*setter)(struct archive *); } names[] = +{ + { "7zip", archive_write_set_format_7zip }, + { "ar", archive_write_set_format_ar_bsd }, + { "arbsd", archive_write_set_format_ar_bsd }, + { "argnu", archive_write_set_format_ar_svr4 }, + { "arsvr4", archive_write_set_format_ar_svr4 }, + { "bsdtar", archive_write_set_format_pax_restricted }, + { "cd9660", archive_write_set_format_iso9660 }, + { "cpio", archive_write_set_format_cpio }, + { "gnutar", archive_write_set_format_gnutar }, + { "iso", archive_write_set_format_iso9660 }, + { "iso9660", archive_write_set_format_iso9660 }, + { "mtree", archive_write_set_format_mtree }, + { "mtree-classic", archive_write_set_format_mtree_classic }, + { "newc", archive_write_set_format_cpio_newc }, + { "odc", archive_write_set_format_cpio }, + { "oldtar", archive_write_set_format_v7tar }, + { "pax", archive_write_set_format_pax }, + { "paxr", archive_write_set_format_pax_restricted }, + { "posix", archive_write_set_format_pax }, + { "raw", archive_write_set_format_raw }, + { "rpax", archive_write_set_format_pax_restricted }, + { "shar", archive_write_set_format_shar }, + { "shardump", archive_write_set_format_shar_dump }, + { "ustar", archive_write_set_format_ustar }, + { "v7tar", archive_write_set_format_v7tar }, + { "v7", archive_write_set_format_v7tar }, + { "warc", archive_write_set_format_warc }, + { "xar", archive_write_set_format_xar }, + { "zip", archive_write_set_format_zip }, + { NULL, NULL } +}; + +int +archive_write_set_format_by_name(struct archive *a, const char *name) +{ + int i; + + for (i = 0; names[i].name != NULL; i++) { + if (strcmp(name, names[i].name) == 0) + return ((names[i].setter)(a)); + } + + archive_set_error(a, EINVAL, "No such format '%s'", name); + a->state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_cpio.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_cpio.c new file mode 100644 index 0000000000..729f9c7755 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_cpio.c @@ -0,0 +1,500 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2011-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_cpio.c 201170 2009-12-29 06:34:23Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_write_private.h" +#include "archive_write_set_format_private.h" + +static ssize_t archive_write_cpio_data(struct archive_write *, + const void *buff, size_t s); +static int archive_write_cpio_close(struct archive_write *); +static int archive_write_cpio_free(struct archive_write *); +static int archive_write_cpio_finish_entry(struct archive_write *); +static int archive_write_cpio_header(struct archive_write *, + struct archive_entry *); +static int archive_write_cpio_options(struct archive_write *, + const char *, const char *); +static int format_octal(int64_t, void *, int); +static int64_t format_octal_recursive(int64_t, char *, int); +static int write_header(struct archive_write *, struct archive_entry *); + +struct cpio { + uint64_t entry_bytes_remaining; + + int64_t ino_next; + + struct { int64_t old; int new;} *ino_list; + size_t ino_list_size; + size_t ino_list_next; + + struct archive_string_conv *opt_sconv; + struct archive_string_conv *sconv_default; + int init_default_conversion; +}; + +#define c_magic_offset 0 +#define c_magic_size 6 +#define c_dev_offset 6 +#define c_dev_size 6 +#define c_ino_offset 12 +#define c_ino_size 6 +#define c_mode_offset 18 +#define c_mode_size 6 +#define c_uid_offset 24 +#define c_uid_size 6 +#define c_gid_offset 30 +#define c_gid_size 6 +#define c_nlink_offset 36 +#define c_nlink_size 6 +#define c_rdev_offset 42 +#define c_rdev_size 6 +#define c_mtime_offset 48 +#define c_mtime_size 11 +#define c_namesize_offset 59 +#define c_namesize_size 6 +#define c_filesize_offset 65 +#define c_filesize_size 11 + +/* + * Set output format to 'cpio' format. + */ +int +archive_write_set_format_cpio(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct cpio *cpio; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_cpio"); + + /* If someone else was already registered, unregister them. */ + if (a->format_free != NULL) + (a->format_free)(a); + + cpio = (struct cpio *)calloc(1, sizeof(*cpio)); + if (cpio == NULL) { + archive_set_error(&a->archive, ENOMEM, "Can't allocate cpio data"); + return (ARCHIVE_FATAL); + } + a->format_data = cpio; + a->format_name = "cpio"; + a->format_options = archive_write_cpio_options; + a->format_write_header = archive_write_cpio_header; + a->format_write_data = archive_write_cpio_data; + a->format_finish_entry = archive_write_cpio_finish_entry; + a->format_close = archive_write_cpio_close; + a->format_free = archive_write_cpio_free; + a->archive.archive_format = ARCHIVE_FORMAT_CPIO_POSIX; + a->archive.archive_format_name = "POSIX cpio"; + return (ARCHIVE_OK); +} + +static int +archive_write_cpio_options(struct archive_write *a, const char *key, + const char *val) +{ + struct cpio *cpio = (struct cpio *)a->format_data; + int ret = ARCHIVE_FAILED; + + if (strcmp(key, "hdrcharset") == 0) { + if (val == NULL || val[0] == 0) + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "%s: hdrcharset option needs a character-set name", + a->format_name); + else { + cpio->opt_sconv = archive_string_conversion_to_charset( + &a->archive, val, 0); + if (cpio->opt_sconv != NULL) + ret = ARCHIVE_OK; + else + ret = ARCHIVE_FATAL; + } + return (ret); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +/* + * Ino values are as long as 64 bits on some systems; cpio format + * only allows 18 bits and relies on the ino values to identify hardlinked + * files. So, we can't merely "hash" the ino numbers since collisions + * would corrupt the archive. Instead, we generate synthetic ino values + * to store in the archive and maintain a map of original ino values to + * synthetic ones so we can preserve hardlink information. + * + * TODO: Make this more efficient. It's not as bad as it looks (most + * files don't have any hardlinks and we don't do any work here for those), + * but it wouldn't be hard to do better. + * + * TODO: Work with dev/ino pairs here instead of just ino values. + */ +static int +synthesize_ino_value(struct cpio *cpio, struct archive_entry *entry) +{ + int64_t ino = archive_entry_ino64(entry); + int ino_new; + size_t i; + + /* + * If no index number was given, don't assign one. In + * particular, this handles the end-of-archive marker + * correctly by giving it a zero index value. (This is also + * why we start our synthetic index numbers with one below.) + */ + if (ino == 0) + return (0); + + /* Don't store a mapping if we don't need to. */ + if (archive_entry_nlink(entry) < 2) { + return (int)(++cpio->ino_next); + } + + /* Look up old ino; if we have it, this is a hardlink + * and we reuse the same value. */ + for (i = 0; i < cpio->ino_list_next; ++i) { + if (cpio->ino_list[i].old == ino) + return (cpio->ino_list[i].new); + } + + /* Assign a new index number. */ + ino_new = (int)(++cpio->ino_next); + + /* Ensure space for the new mapping. */ + if (cpio->ino_list_size <= cpio->ino_list_next) { + size_t newsize = cpio->ino_list_size < 512 + ? 512 : cpio->ino_list_size * 2; + void *newlist = realloc(cpio->ino_list, + sizeof(cpio->ino_list[0]) * newsize); + if (newlist == NULL) + return (-1); + + cpio->ino_list_size = newsize; + cpio->ino_list = newlist; + } + + /* Record and return the new value. */ + cpio->ino_list[cpio->ino_list_next].old = ino; + cpio->ino_list[cpio->ino_list_next].new = ino_new; + ++cpio->ino_list_next; + return (ino_new); +} + + +static struct archive_string_conv * +get_sconv(struct archive_write *a) +{ + struct cpio *cpio; + struct archive_string_conv *sconv; + + cpio = (struct cpio *)a->format_data; + sconv = cpio->opt_sconv; + if (sconv == NULL) { + if (!cpio->init_default_conversion) { + cpio->sconv_default = + archive_string_default_conversion_for_write( + &(a->archive)); + cpio->init_default_conversion = 1; + } + sconv = cpio->sconv_default; + } + return (sconv); +} + +static int +archive_write_cpio_header(struct archive_write *a, struct archive_entry *entry) +{ + const char *path; + size_t len; + + if (archive_entry_filetype(entry) == 0) { + archive_set_error(&a->archive, -1, "Filetype required"); + return (ARCHIVE_FAILED); + } + + if (archive_entry_pathname_l(entry, &path, &len, get_sconv(a)) != 0 + && errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + return (ARCHIVE_FATAL); + } + if (len == 0 || path == NULL || path[0] == '\0') { + archive_set_error(&a->archive, -1, "Pathname required"); + return (ARCHIVE_FAILED); + } + + if (!archive_entry_size_is_set(entry) || archive_entry_size(entry) < 0) { + archive_set_error(&a->archive, -1, "Size required"); + return (ARCHIVE_FAILED); + } + return write_header(a, entry); +} + +static int +write_header(struct archive_write *a, struct archive_entry *entry) +{ + struct cpio *cpio; + const char *p, *path; + int pathlength, ret, ret_final; + int64_t ino; + char h[76]; + struct archive_string_conv *sconv; + struct archive_entry *entry_main; + size_t len; + + cpio = (struct cpio *)a->format_data; + ret_final = ARCHIVE_OK; + sconv = get_sconv(a); + +#if defined(_WIN32) && !defined(__CYGWIN__) + /* Make sure the path separators in pathname, hardlink and symlink + * are all slash '/', not the Windows path separator '\'. */ + entry_main = __la_win_entry_in_posix_pathseparator(entry); + if (entry_main == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate ustar data"); + return(ARCHIVE_FATAL); + } + if (entry != entry_main) + entry = entry_main; + else + entry_main = NULL; +#else + entry_main = NULL; +#endif + + ret = archive_entry_pathname_l(entry, &path, &len, sconv); + if (ret != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + ret_final = ARCHIVE_FATAL; + goto exit_write_header; + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate pathname '%s' to %s", + archive_entry_pathname(entry), + archive_string_conversion_charset_name(sconv)); + ret_final = ARCHIVE_WARN; + } + /* Include trailing null. */ + pathlength = (int)len + 1; + + memset(h, 0, sizeof(h)); + format_octal(070707, h + c_magic_offset, c_magic_size); + format_octal(archive_entry_dev(entry), h + c_dev_offset, c_dev_size); + + ino = synthesize_ino_value(cpio, entry); + if (ino < 0) { + archive_set_error(&a->archive, ENOMEM, + "No memory for ino translation table"); + ret_final = ARCHIVE_FATAL; + goto exit_write_header; + } else if (ino > 0777777) { + archive_set_error(&a->archive, ERANGE, + "Too many files for this cpio format"); + ret_final = ARCHIVE_FATAL; + goto exit_write_header; + } + format_octal(ino & 0777777, h + c_ino_offset, c_ino_size); + + /* TODO: Set ret_final to ARCHIVE_WARN if any of these overflow. */ + format_octal(archive_entry_mode(entry), h + c_mode_offset, c_mode_size); + format_octal(archive_entry_uid(entry), h + c_uid_offset, c_uid_size); + format_octal(archive_entry_gid(entry), h + c_gid_offset, c_gid_size); + format_octal(archive_entry_nlink(entry), h + c_nlink_offset, c_nlink_size); + if (archive_entry_filetype(entry) == AE_IFBLK + || archive_entry_filetype(entry) == AE_IFCHR) + format_octal(archive_entry_dev(entry), h + c_rdev_offset, c_rdev_size); + else + format_octal(0, h + c_rdev_offset, c_rdev_size); + format_octal(archive_entry_mtime(entry), h + c_mtime_offset, c_mtime_size); + format_octal(pathlength, h + c_namesize_offset, c_namesize_size); + + /* Non-regular files don't store bodies. */ + if (archive_entry_filetype(entry) != AE_IFREG) + archive_entry_set_size(entry, 0); + + /* Symlinks get the link written as the body of the entry. */ + ret = archive_entry_symlink_l(entry, &p, &len, sconv); + if (ret != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Linkname"); + ret_final = ARCHIVE_FATAL; + goto exit_write_header; + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate linkname '%s' to %s", + archive_entry_symlink(entry), + archive_string_conversion_charset_name(sconv)); + ret_final = ARCHIVE_WARN; + } + if (len > 0 && p != NULL && *p != '\0') + ret = format_octal(strlen(p), h + c_filesize_offset, + c_filesize_size); + else + ret = format_octal(archive_entry_size(entry), + h + c_filesize_offset, c_filesize_size); + if (ret) { + archive_set_error(&a->archive, ERANGE, + "File is too large for cpio format."); + ret_final = ARCHIVE_FAILED; + goto exit_write_header; + } + + ret = __archive_write_output(a, h, sizeof(h)); + if (ret != ARCHIVE_OK) { + ret_final = ARCHIVE_FATAL; + goto exit_write_header; + } + + ret = __archive_write_output(a, path, pathlength); + if (ret != ARCHIVE_OK) { + ret_final = ARCHIVE_FATAL; + goto exit_write_header; + } + + cpio->entry_bytes_remaining = archive_entry_size(entry); + + /* Write the symlink now. */ + if (p != NULL && *p != '\0') { + ret = __archive_write_output(a, p, strlen(p)); + if (ret != ARCHIVE_OK) { + ret_final = ARCHIVE_FATAL; + goto exit_write_header; + } + } +exit_write_header: + archive_entry_free(entry_main); + return (ret_final); +} + +static ssize_t +archive_write_cpio_data(struct archive_write *a, const void *buff, size_t s) +{ + struct cpio *cpio; + int ret; + + cpio = (struct cpio *)a->format_data; + if (s > cpio->entry_bytes_remaining) + s = (size_t)cpio->entry_bytes_remaining; + + ret = __archive_write_output(a, buff, s); + cpio->entry_bytes_remaining -= s; + if (ret >= 0) + return (s); + else + return (ret); +} + +/* + * Format a number into the specified field. + */ +static int +format_octal(int64_t v, void *p, int digits) +{ + int64_t max; + int ret; + + max = (((int64_t)1) << (digits * 3)) - 1; + if (v >= 0 && v <= max) { + format_octal_recursive(v, (char *)p, digits); + ret = 0; + } else { + format_octal_recursive(max, (char *)p, digits); + ret = -1; + } + return (ret); +} + +static int64_t +format_octal_recursive(int64_t v, char *p, int s) +{ + if (s == 0) + return (v); + v = format_octal_recursive(v, p+1, s-1); + *p = '0' + ((char)v & 7); + return (v >> 3); +} + +static int +archive_write_cpio_close(struct archive_write *a) +{ + int er; + struct archive_entry *trailer; + + trailer = archive_entry_new2(NULL); + /* nlink = 1 here for GNU cpio compat. */ + archive_entry_set_nlink(trailer, 1); + archive_entry_set_size(trailer, 0); + archive_entry_set_pathname(trailer, "TRAILER!!!"); + er = write_header(a, trailer); + archive_entry_free(trailer); + return (er); +} + +static int +archive_write_cpio_free(struct archive_write *a) +{ + struct cpio *cpio; + + cpio = (struct cpio *)a->format_data; + free(cpio->ino_list); + free(cpio); + a->format_data = NULL; + return (ARCHIVE_OK); +} + +static int +archive_write_cpio_finish_entry(struct archive_write *a) +{ + struct cpio *cpio; + + cpio = (struct cpio *)a->format_data; + return (__archive_write_nulls(a, + (size_t)cpio->entry_bytes_remaining)); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_cpio_newc.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_cpio_newc.c new file mode 100644 index 0000000000..172fda62f0 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_cpio_newc.c @@ -0,0 +1,457 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2006 Rudolf Marek SYSGO s.r.o. + * Copyright (c) 2011-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_cpio_newc.c 201160 2009-12-29 05:41:57Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_write_private.h" +#include "archive_write_set_format_private.h" + +static ssize_t archive_write_newc_data(struct archive_write *, + const void *buff, size_t s); +static int archive_write_newc_close(struct archive_write *); +static int archive_write_newc_free(struct archive_write *); +static int archive_write_newc_finish_entry(struct archive_write *); +static int archive_write_newc_header(struct archive_write *, + struct archive_entry *); +static int archive_write_newc_options(struct archive_write *, + const char *, const char *); +static int format_hex(int64_t, void *, int); +static int64_t format_hex_recursive(int64_t, char *, int); +static int write_header(struct archive_write *, struct archive_entry *); + +struct cpio { + uint64_t entry_bytes_remaining; + int padding; + + struct archive_string_conv *opt_sconv; + struct archive_string_conv *sconv_default; + int init_default_conversion; +}; + +#define c_magic_offset 0 +#define c_magic_size 6 +#define c_ino_offset 6 +#define c_ino_size 8 +#define c_mode_offset 14 +#define c_mode_size 8 +#define c_uid_offset 22 +#define c_uid_size 8 +#define c_gid_offset 30 +#define c_gid_size 8 +#define c_nlink_offset 38 +#define c_nlink_size 8 +#define c_mtime_offset 46 +#define c_mtime_size 8 +#define c_filesize_offset 54 +#define c_filesize_size 8 +#define c_devmajor_offset 62 +#define c_devmajor_size 8 +#define c_devminor_offset 70 +#define c_devminor_size 8 +#define c_rdevmajor_offset 78 +#define c_rdevmajor_size 8 +#define c_rdevminor_offset 86 +#define c_rdevminor_size 8 +#define c_namesize_offset 94 +#define c_namesize_size 8 +#define c_checksum_offset 102 +#define c_checksum_size 8 +#define c_header_size 110 + +/* Logic trick: difference between 'n' and next multiple of 4 */ +#define PAD4(n) (3 & (1 + ~(n))) + +/* + * Set output format to 'cpio' format. + */ +int +archive_write_set_format_cpio_newc(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct cpio *cpio; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_cpio_newc"); + + /* If someone else was already registered, unregister them. */ + if (a->format_free != NULL) + (a->format_free)(a); + + cpio = (struct cpio *)calloc(1, sizeof(*cpio)); + if (cpio == NULL) { + archive_set_error(&a->archive, ENOMEM, "Can't allocate cpio data"); + return (ARCHIVE_FATAL); + } + a->format_data = cpio; + a->format_name = "cpio"; + a->format_options = archive_write_newc_options; + a->format_write_header = archive_write_newc_header; + a->format_write_data = archive_write_newc_data; + a->format_finish_entry = archive_write_newc_finish_entry; + a->format_close = archive_write_newc_close; + a->format_free = archive_write_newc_free; + a->archive.archive_format = ARCHIVE_FORMAT_CPIO_SVR4_NOCRC; + a->archive.archive_format_name = "SVR4 cpio nocrc"; + return (ARCHIVE_OK); +} + +static int +archive_write_newc_options(struct archive_write *a, const char *key, + const char *val) +{ + struct cpio *cpio = (struct cpio *)a->format_data; + int ret = ARCHIVE_FAILED; + + if (strcmp(key, "hdrcharset") == 0) { + if (val == NULL || val[0] == 0) + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "%s: hdrcharset option needs a character-set name", + a->format_name); + else { + cpio->opt_sconv = archive_string_conversion_to_charset( + &a->archive, val, 0); + if (cpio->opt_sconv != NULL) + ret = ARCHIVE_OK; + else + ret = ARCHIVE_FATAL; + } + return (ret); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static struct archive_string_conv * +get_sconv(struct archive_write *a) +{ + struct cpio *cpio; + struct archive_string_conv *sconv; + + cpio = (struct cpio *)a->format_data; + sconv = cpio->opt_sconv; + if (sconv == NULL) { + if (!cpio->init_default_conversion) { + cpio->sconv_default = + archive_string_default_conversion_for_write( + &(a->archive)); + cpio->init_default_conversion = 1; + } + sconv = cpio->sconv_default; + } + return (sconv); +} + +static int +archive_write_newc_header(struct archive_write *a, struct archive_entry *entry) +{ + const char *path; + size_t len; + + if (archive_entry_filetype(entry) == 0) { + archive_set_error(&a->archive, -1, "Filetype required"); + return (ARCHIVE_FAILED); + } + + if (archive_entry_pathname_l(entry, &path, &len, get_sconv(a)) != 0 + && errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + return (ARCHIVE_FATAL); + } + if (len == 0 || path == NULL || path[0] == '\0') { + archive_set_error(&a->archive, -1, "Pathname required"); + return (ARCHIVE_FAILED); + } + + if (archive_entry_hardlink(entry) == NULL + && (!archive_entry_size_is_set(entry) || archive_entry_size(entry) < 0)) { + archive_set_error(&a->archive, -1, "Size required"); + return (ARCHIVE_FAILED); + } + return write_header(a, entry); +} + +static int +write_header(struct archive_write *a, struct archive_entry *entry) +{ + int64_t ino; + struct cpio *cpio; + const char *p, *path; + int pathlength, ret, ret_final; + char h[c_header_size]; + struct archive_string_conv *sconv; + struct archive_entry *entry_main; + size_t len; + int pad; + + cpio = (struct cpio *)a->format_data; + ret_final = ARCHIVE_OK; + sconv = get_sconv(a); + +#if defined(_WIN32) && !defined(__CYGWIN__) + /* Make sure the path separators in pathname, hardlink and symlink + * are all slash '/', not the Windows path separator '\'. */ + entry_main = __la_win_entry_in_posix_pathseparator(entry); + if (entry_main == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate ustar data"); + return(ARCHIVE_FATAL); + } + if (entry != entry_main) + entry = entry_main; + else + entry_main = NULL; +#else + entry_main = NULL; +#endif + + ret = archive_entry_pathname_l(entry, &path, &len, sconv); + if (ret != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + ret_final = ARCHIVE_FATAL; + goto exit_write_header; + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate pathname '%s' to %s", + archive_entry_pathname(entry), + archive_string_conversion_charset_name(sconv)); + ret_final = ARCHIVE_WARN; + } + pathlength = (int)len + 1; /* Include trailing null. */ + + memset(h, 0, c_header_size); + format_hex(0x070701, h + c_magic_offset, c_magic_size); + format_hex(archive_entry_devmajor(entry), h + c_devmajor_offset, + c_devmajor_size); + format_hex(archive_entry_devminor(entry), h + c_devminor_offset, + c_devminor_size); + + ino = archive_entry_ino64(entry); + if (ino > 0xffffffff) { + archive_set_error(&a->archive, ERANGE, + "large inode number truncated"); + ret_final = ARCHIVE_WARN; + } + + /* TODO: Set ret_final to ARCHIVE_WARN if any of these overflow. */ + format_hex(ino & 0xffffffff, h + c_ino_offset, c_ino_size); + format_hex(archive_entry_mode(entry), h + c_mode_offset, c_mode_size); + format_hex(archive_entry_uid(entry), h + c_uid_offset, c_uid_size); + format_hex(archive_entry_gid(entry), h + c_gid_offset, c_gid_size); + format_hex(archive_entry_nlink(entry), h + c_nlink_offset, c_nlink_size); + if (archive_entry_filetype(entry) == AE_IFBLK + || archive_entry_filetype(entry) == AE_IFCHR) { + format_hex(archive_entry_rdevmajor(entry), h + c_rdevmajor_offset, c_rdevmajor_size); + format_hex(archive_entry_rdevminor(entry), h + c_rdevminor_offset, c_rdevminor_size); + } else { + format_hex(0, h + c_rdevmajor_offset, c_rdevmajor_size); + format_hex(0, h + c_rdevminor_offset, c_rdevminor_size); + } + format_hex(archive_entry_mtime(entry), h + c_mtime_offset, c_mtime_size); + format_hex(pathlength, h + c_namesize_offset, c_namesize_size); + format_hex(0, h + c_checksum_offset, c_checksum_size); + + /* Non-regular files don't store bodies. */ + if (archive_entry_filetype(entry) != AE_IFREG) + archive_entry_set_size(entry, 0); + + /* Symlinks get the link written as the body of the entry. */ + ret = archive_entry_symlink_l(entry, &p, &len, sconv); + if (ret != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Likname"); + ret_final = ARCHIVE_FATAL; + goto exit_write_header; + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate linkname '%s' to %s", + archive_entry_symlink(entry), + archive_string_conversion_charset_name(sconv)); + ret_final = ARCHIVE_WARN; + } + if (len > 0 && p != NULL && *p != '\0') + ret = format_hex(strlen(p), h + c_filesize_offset, + c_filesize_size); + else + ret = format_hex(archive_entry_size(entry), + h + c_filesize_offset, c_filesize_size); + if (ret) { + archive_set_error(&a->archive, ERANGE, + "File is too large for this format."); + ret_final = ARCHIVE_FAILED; + goto exit_write_header; + } + + ret = __archive_write_output(a, h, c_header_size); + if (ret != ARCHIVE_OK) { + ret_final = ARCHIVE_FATAL; + goto exit_write_header; + } + + /* Pad pathname to even length. */ + ret = __archive_write_output(a, path, pathlength); + if (ret != ARCHIVE_OK) { + ret_final = ARCHIVE_FATAL; + goto exit_write_header; + } + pad = PAD4(pathlength + c_header_size); + if (pad) { + ret = __archive_write_output(a, "\0\0\0", pad); + if (ret != ARCHIVE_OK) { + ret_final = ARCHIVE_FATAL; + goto exit_write_header; + } + } + + cpio->entry_bytes_remaining = archive_entry_size(entry); + cpio->padding = (int)PAD4(cpio->entry_bytes_remaining); + + /* Write the symlink now. */ + if (p != NULL && *p != '\0') { + ret = __archive_write_output(a, p, strlen(p)); + if (ret != ARCHIVE_OK) { + ret_final = ARCHIVE_FATAL; + goto exit_write_header; + } + pad = PAD4(strlen(p)); + ret = __archive_write_output(a, "\0\0\0", pad); + if (ret != ARCHIVE_OK) { + ret_final = ARCHIVE_FATAL; + goto exit_write_header; + } + } +exit_write_header: + archive_entry_free(entry_main); + return (ret_final); +} + +static ssize_t +archive_write_newc_data(struct archive_write *a, const void *buff, size_t s) +{ + struct cpio *cpio; + int ret; + + cpio = (struct cpio *)a->format_data; + if (s > cpio->entry_bytes_remaining) + s = (size_t)cpio->entry_bytes_remaining; + + ret = __archive_write_output(a, buff, s); + cpio->entry_bytes_remaining -= s; + if (ret >= 0) + return (s); + else + return (ret); +} + +/* + * Format a number into the specified field. + */ +static int +format_hex(int64_t v, void *p, int digits) +{ + int64_t max; + int ret; + + max = (((int64_t)1) << (digits * 4)) - 1; + if (v >= 0 && v <= max) { + format_hex_recursive(v, (char *)p, digits); + ret = 0; + } else { + format_hex_recursive(max, (char *)p, digits); + ret = -1; + } + return (ret); +} + +static int64_t +format_hex_recursive(int64_t v, char *p, int s) +{ + if (s == 0) + return (v); + v = format_hex_recursive(v, p+1, s-1); + *p = "0123456789abcdef"[v & 0xf]; + return (v >> 4); +} + +static int +archive_write_newc_close(struct archive_write *a) +{ + int er; + struct archive_entry *trailer; + + trailer = archive_entry_new(); + archive_entry_set_nlink(trailer, 1); + archive_entry_set_size(trailer, 0); + archive_entry_set_pathname(trailer, "TRAILER!!!"); + /* Bypass the required data checks. */ + er = write_header(a, trailer); + archive_entry_free(trailer); + return (er); +} + +static int +archive_write_newc_free(struct archive_write *a) +{ + struct cpio *cpio; + + cpio = (struct cpio *)a->format_data; + free(cpio); + a->format_data = NULL; + return (ARCHIVE_OK); +} + +static int +archive_write_newc_finish_entry(struct archive_write *a) +{ + struct cpio *cpio; + + cpio = (struct cpio *)a->format_data; + return (__archive_write_nulls(a, + (size_t)cpio->entry_bytes_remaining + cpio->padding)); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_filter_by_ext.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_filter_by_ext.c new file mode 100644 index 0000000000..9fe21e4542 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_filter_by_ext.c @@ -0,0 +1,142 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2015 Okhotnikov Kirill + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_by_name.c 201168 2009-12-29 06:15:32Z kientzle $"); + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_private.h" + +/* A table that maps names to functions. */ +static const +struct { const char *name; int (*format)(struct archive *); int (*filter)(struct archive *); } names[] = +{ + { ".7z", archive_write_set_format_7zip, archive_write_add_filter_none}, + { ".zip", archive_write_set_format_zip, archive_write_add_filter_none}, + { ".jar", archive_write_set_format_zip, archive_write_add_filter_none}, + { ".cpio", archive_write_set_format_cpio, archive_write_add_filter_none}, + { ".iso", archive_write_set_format_iso9660, archive_write_add_filter_none}, +#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) + { ".a", archive_write_set_format_ar_bsd, archive_write_add_filter_none}, + { ".ar", archive_write_set_format_ar_bsd, archive_write_add_filter_none}, +#else + { ".a", archive_write_set_format_ar_svr4, archive_write_add_filter_none}, + { ".ar", archive_write_set_format_ar_svr4, archive_write_add_filter_none}, +#endif + { ".tar", archive_write_set_format_pax_restricted, archive_write_add_filter_none}, + { ".tgz", archive_write_set_format_pax_restricted, archive_write_add_filter_gzip}, + { ".tar.gz", archive_write_set_format_pax_restricted, archive_write_add_filter_gzip}, + { ".tar.bz2", archive_write_set_format_pax_restricted, archive_write_add_filter_bzip2}, + { ".tar.xz", archive_write_set_format_pax_restricted, archive_write_add_filter_xz}, + { NULL, NULL, NULL } +}; + +static +int cmpsuff(const char *str, const char *suffix) +{ + size_t length_str, length_suffix; + + if ((str == NULL) || (suffix == NULL)) + return -1; + + length_str = strlen(str); + length_suffix = strlen(suffix); + + if (length_str >= length_suffix) { + return strcmp(str + (length_str - length_suffix), suffix); + } else { + return -1; + } +} + +static int get_array_index(const char *name) +{ + int i; + + for (i = 0; names[i].name != NULL; i++) + { + if (cmpsuff(name, names[i].name) == 0) + return i; + } + return -1; + +} + +int +archive_write_set_format_filter_by_ext(struct archive *a, const char *filename) +{ + int names_index = get_array_index(filename); + + if (names_index >= 0) + { + int format_state = (names[names_index].format)(a); + if (format_state == ARCHIVE_OK) + return ((names[names_index].filter)(a)); + else + return format_state; + } + + archive_set_error(a, EINVAL, "No such format '%s'", filename); + a->state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); +} + +int +archive_write_set_format_filter_by_ext_def(struct archive *a, const char *filename, const char * def_ext) +{ + int names_index = get_array_index(filename); + + if (names_index < 0) + names_index = get_array_index(def_ext); + + if (names_index >= 0) + { + int format_state = (names[names_index].format)(a); + if (format_state == ARCHIVE_OK) + return ((names[names_index].filter)(a)); + else + return format_state; + } + + archive_set_error(a, EINVAL, "No such format '%s'", filename); + a->state = ARCHIVE_STATE_FATAL; + return (ARCHIVE_FATAL); +} + + + + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_gnutar.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_gnutar.c new file mode 100644 index 0000000000..ec29c5c418 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_gnutar.c @@ -0,0 +1,755 @@ +/*- + * Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). + * Author: Jonas Gastal <jgastal@profusion.mobi> + * Copyright (c) 2011-2012 Michihiro NAKAJIMA + * + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_gnu_tar.c 191579 2009-04-27 18:35:03Z gastal $"); + + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_write_private.h" +#include "archive_write_set_format_private.h" + +struct gnutar { + uint64_t entry_bytes_remaining; + uint64_t entry_padding; + const char * linkname; + size_t linkname_length; + const char * pathname; + size_t pathname_length; + const char * uname; + size_t uname_length; + const char * gname; + size_t gname_length; + struct archive_string_conv *opt_sconv; + struct archive_string_conv *sconv_default; + int init_default_conversion; +}; + +/* + * Define structure of GNU tar header. + */ +#define GNUTAR_name_offset 0 +#define GNUTAR_name_size 100 +#define GNUTAR_mode_offset 100 +#define GNUTAR_mode_size 7 +#define GNUTAR_mode_max_size 8 +#define GNUTAR_uid_offset 108 +#define GNUTAR_uid_size 7 +#define GNUTAR_uid_max_size 8 +#define GNUTAR_gid_offset 116 +#define GNUTAR_gid_size 7 +#define GNUTAR_gid_max_size 8 +#define GNUTAR_size_offset 124 +#define GNUTAR_size_size 11 +#define GNUTAR_size_max_size 12 +#define GNUTAR_mtime_offset 136 +#define GNUTAR_mtime_size 11 +#define GNUTAR_mtime_max_size 11 +#define GNUTAR_checksum_offset 148 +#define GNUTAR_checksum_size 8 +#define GNUTAR_typeflag_offset 156 +#define GNUTAR_typeflag_size 1 +#define GNUTAR_linkname_offset 157 +#define GNUTAR_linkname_size 100 +#define GNUTAR_magic_offset 257 +#define GNUTAR_magic_size 6 +#define GNUTAR_version_offset 263 +#define GNUTAR_version_size 2 +#define GNUTAR_uname_offset 265 +#define GNUTAR_uname_size 32 +#define GNUTAR_gname_offset 297 +#define GNUTAR_gname_size 32 +#define GNUTAR_rdevmajor_offset 329 +#define GNUTAR_rdevmajor_size 6 +#define GNUTAR_rdevmajor_max_size 8 +#define GNUTAR_rdevminor_offset 337 +#define GNUTAR_rdevminor_size 6 +#define GNUTAR_rdevminor_max_size 8 + +/* + * A filled-in copy of the header for initialization. + */ +static const char template_header[] = { + /* name: 100 bytes */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0, + /* Mode, null termination: 8 bytes */ + '0','0','0','0','0','0', '0','\0', + /* uid, null termination: 8 bytes */ + '0','0','0','0','0','0', '0','\0', + /* gid, null termination: 8 bytes */ + '0','0','0','0','0','0', '0','\0', + /* size, space termination: 12 bytes */ + '0','0','0','0','0','0','0','0','0','0','0', '\0', + /* mtime, space termination: 12 bytes */ + '0','0','0','0','0','0','0','0','0','0','0', '\0', + /* Initial checksum value: 8 spaces */ + ' ',' ',' ',' ',' ',' ',' ',' ', + /* Typeflag: 1 byte */ + '0', /* '0' = regular file */ + /* Linkname: 100 bytes */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0, + /* Magic: 8 bytes */ + 'u','s','t','a','r',' ', ' ','\0', + /* Uname: 32 bytes */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + /* Gname: 32 bytes */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + /* rdevmajor + null padding: 8 bytes */ + '\0','\0','\0','\0','\0','\0', '\0','\0', + /* rdevminor + null padding: 8 bytes */ + '\0','\0','\0','\0','\0','\0', '\0','\0', + /* Padding: 167 bytes */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0 +}; + +static int archive_write_gnutar_options(struct archive_write *, + const char *, const char *); +static int archive_format_gnutar_header(struct archive_write *, char h[512], + struct archive_entry *, int tartype); +static int archive_write_gnutar_header(struct archive_write *, + struct archive_entry *entry); +static ssize_t archive_write_gnutar_data(struct archive_write *a, const void *buff, + size_t s); +static int archive_write_gnutar_free(struct archive_write *); +static int archive_write_gnutar_close(struct archive_write *); +static int archive_write_gnutar_finish_entry(struct archive_write *); +static int format_256(int64_t, char *, int); +static int format_number(int64_t, char *, int size, int maxsize); +static int format_octal(int64_t, char *, int); + +/* + * Set output format to 'GNU tar' format. + */ +int +archive_write_set_format_gnutar(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct gnutar *gnutar; + + gnutar = (struct gnutar *)calloc(1, sizeof(*gnutar)); + if (gnutar == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate gnutar data"); + return (ARCHIVE_FATAL); + } + a->format_data = gnutar; + a->format_name = "gnutar"; + a->format_options = archive_write_gnutar_options; + a->format_write_header = archive_write_gnutar_header; + a->format_write_data = archive_write_gnutar_data; + a->format_close = archive_write_gnutar_close; + a->format_free = archive_write_gnutar_free; + a->format_finish_entry = archive_write_gnutar_finish_entry; + a->archive.archive_format = ARCHIVE_FORMAT_TAR_GNUTAR; + a->archive.archive_format_name = "GNU tar"; + return (ARCHIVE_OK); +} + +static int +archive_write_gnutar_options(struct archive_write *a, const char *key, + const char *val) +{ + struct gnutar *gnutar = (struct gnutar *)a->format_data; + int ret = ARCHIVE_FAILED; + + if (strcmp(key, "hdrcharset") == 0) { + if (val == NULL || val[0] == 0) + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "%s: hdrcharset option needs a character-set name", + a->format_name); + else { + gnutar->opt_sconv = archive_string_conversion_to_charset( + &a->archive, val, 0); + if (gnutar->opt_sconv != NULL) + ret = ARCHIVE_OK; + else + ret = ARCHIVE_FATAL; + } + return (ret); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static int +archive_write_gnutar_close(struct archive_write *a) +{ + return (__archive_write_nulls(a, 512*2)); +} + +static int +archive_write_gnutar_free(struct archive_write *a) +{ + struct gnutar *gnutar; + + gnutar = (struct gnutar *)a->format_data; + free(gnutar); + a->format_data = NULL; + return (ARCHIVE_OK); +} + +static int +archive_write_gnutar_finish_entry(struct archive_write *a) +{ + struct gnutar *gnutar; + int ret; + + gnutar = (struct gnutar *)a->format_data; + ret = __archive_write_nulls(a, (size_t) + (gnutar->entry_bytes_remaining + gnutar->entry_padding)); + gnutar->entry_bytes_remaining = gnutar->entry_padding = 0; + return (ret); +} + +static ssize_t +archive_write_gnutar_data(struct archive_write *a, const void *buff, size_t s) +{ + struct gnutar *gnutar; + int ret; + + gnutar = (struct gnutar *)a->format_data; + if (s > gnutar->entry_bytes_remaining) + s = (size_t)gnutar->entry_bytes_remaining; + ret = __archive_write_output(a, buff, s); + gnutar->entry_bytes_remaining -= s; + if (ret != ARCHIVE_OK) + return (ret); + return (s); +} + +static int +archive_write_gnutar_header(struct archive_write *a, + struct archive_entry *entry) +{ + char buff[512]; + int r, ret, ret2 = ARCHIVE_OK; + int tartype; + struct gnutar *gnutar; + struct archive_string_conv *sconv; + struct archive_entry *entry_main; + + gnutar = (struct gnutar *)a->format_data; + + /* Setup default string conversion. */ + if (gnutar->opt_sconv == NULL) { + if (!gnutar->init_default_conversion) { + gnutar->sconv_default = + archive_string_default_conversion_for_write( + &(a->archive)); + gnutar->init_default_conversion = 1; + } + sconv = gnutar->sconv_default; + } else + sconv = gnutar->opt_sconv; + + /* Only regular files (not hardlinks) have data. */ + if (archive_entry_hardlink(entry) != NULL || + archive_entry_symlink(entry) != NULL || + !(archive_entry_filetype(entry) == AE_IFREG)) + archive_entry_set_size(entry, 0); + + if (AE_IFDIR == archive_entry_filetype(entry)) { + const char *p; + size_t path_length; + /* + * Ensure a trailing '/'. Modify the entry so + * the client sees the change. + */ +#if defined(_WIN32) && !defined(__CYGWIN__) + const wchar_t *wp; + + wp = archive_entry_pathname_w(entry); + if (wp != NULL && wp[wcslen(wp) -1] != L'/') { + struct archive_wstring ws; + + archive_string_init(&ws); + path_length = wcslen(wp); + if (archive_wstring_ensure(&ws, + path_length + 2) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate ustar data"); + archive_wstring_free(&ws); + return(ARCHIVE_FATAL); + } + /* Should we keep '\' ? */ + if (wp[path_length -1] == L'\\') + path_length--; + archive_wstrncpy(&ws, wp, path_length); + archive_wstrappend_wchar(&ws, L'/'); + archive_entry_copy_pathname_w(entry, ws.s); + archive_wstring_free(&ws); + p = NULL; + } else +#endif + p = archive_entry_pathname(entry); + /* + * On Windows, this is a backup operation just in + * case getting WCS failed. On POSIX, this is a + * normal operation. + */ + if (p != NULL && p[0] != '\0' && p[strlen(p) - 1] != '/') { + struct archive_string as; + + archive_string_init(&as); + path_length = strlen(p); + if (archive_string_ensure(&as, + path_length + 2) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate ustar data"); + archive_string_free(&as); + return(ARCHIVE_FATAL); + } +#if defined(_WIN32) && !defined(__CYGWIN__) + /* NOTE: This might break the pathname + * if the current code page is CP932 and + * the pathname includes a character '\' + * as a part of its multibyte pathname. */ + if (p[strlen(p) -1] == '\\') + path_length--; + else +#endif + archive_strncpy(&as, p, path_length); + archive_strappend_char(&as, '/'); + archive_entry_copy_pathname(entry, as.s); + archive_string_free(&as); + } + } + +#if defined(_WIN32) && !defined(__CYGWIN__) + /* Make sure the path separators in pathname, hardlink and symlink + * are all slash '/', not the Windows path separator '\'. */ + entry_main = __la_win_entry_in_posix_pathseparator(entry); + if (entry_main == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate ustar data"); + return(ARCHIVE_FATAL); + } + if (entry != entry_main) + entry = entry_main; + else + entry_main = NULL; +#else + entry_main = NULL; +#endif + r = archive_entry_pathname_l(entry, &(gnutar->pathname), + &(gnutar->pathname_length), sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathame"); + ret = ARCHIVE_FATAL; + goto exit_write_header; + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate pathname '%s' to %s", + archive_entry_pathname(entry), + archive_string_conversion_charset_name(sconv)); + ret2 = ARCHIVE_WARN; + } + r = archive_entry_uname_l(entry, &(gnutar->uname), + &(gnutar->uname_length), sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Uname"); + ret = ARCHIVE_FATAL; + goto exit_write_header; + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate uname '%s' to %s", + archive_entry_uname(entry), + archive_string_conversion_charset_name(sconv)); + ret2 = ARCHIVE_WARN; + } + r = archive_entry_gname_l(entry, &(gnutar->gname), + &(gnutar->gname_length), sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Gname"); + ret = ARCHIVE_FATAL; + goto exit_write_header; + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate gname '%s' to %s", + archive_entry_gname(entry), + archive_string_conversion_charset_name(sconv)); + ret2 = ARCHIVE_WARN; + } + + /* If linkname is longer than 100 chars we need to add a 'K' header. */ + r = archive_entry_hardlink_l(entry, &(gnutar->linkname), + &(gnutar->linkname_length), sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Linkname"); + ret = ARCHIVE_FATAL; + goto exit_write_header; + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate linkname '%s' to %s", + archive_entry_hardlink(entry), + archive_string_conversion_charset_name(sconv)); + ret2 = ARCHIVE_WARN; + } + if (gnutar->linkname_length == 0) { + r = archive_entry_symlink_l(entry, &(gnutar->linkname), + &(gnutar->linkname_length), sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Linkname"); + ret = ARCHIVE_FATAL; + goto exit_write_header; + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate linkname '%s' to %s", + archive_entry_hardlink(entry), + archive_string_conversion_charset_name(sconv)); + ret2 = ARCHIVE_WARN; + } + } + if (gnutar->linkname_length > GNUTAR_linkname_size) { + size_t length = gnutar->linkname_length + 1; + struct archive_entry *temp = archive_entry_new2(&a->archive); + + /* Uname/gname here don't really matter since no one reads them; + * these are the values that GNU tar happens to use on FreeBSD. */ + archive_entry_set_uname(temp, "root"); + archive_entry_set_gname(temp, "wheel"); + + archive_entry_set_pathname(temp, "././@LongLink"); + archive_entry_set_size(temp, length); + ret = archive_format_gnutar_header(a, buff, temp, 'K'); + archive_entry_free(temp); + if (ret < ARCHIVE_WARN) + goto exit_write_header; + ret = __archive_write_output(a, buff, 512); + if (ret < ARCHIVE_WARN) + goto exit_write_header; + /* Write name and trailing null byte. */ + ret = __archive_write_output(a, gnutar->linkname, length); + if (ret < ARCHIVE_WARN) + goto exit_write_header; + /* Pad to 512 bytes */ + ret = __archive_write_nulls(a, 0x1ff & (-(ssize_t)length)); + if (ret < ARCHIVE_WARN) + goto exit_write_header; + } + + /* If pathname is longer than 100 chars we need to add an 'L' header. */ + if (gnutar->pathname_length > GNUTAR_name_size) { + const char *pathname = gnutar->pathname; + size_t length = gnutar->pathname_length + 1; + struct archive_entry *temp = archive_entry_new2(&a->archive); + + /* Uname/gname here don't really matter since no one reads them; + * these are the values that GNU tar happens to use on FreeBSD. */ + archive_entry_set_uname(temp, "root"); + archive_entry_set_gname(temp, "wheel"); + + archive_entry_set_pathname(temp, "././@LongLink"); + archive_entry_set_size(temp, length); + ret = archive_format_gnutar_header(a, buff, temp, 'L'); + archive_entry_free(temp); + if (ret < ARCHIVE_WARN) + goto exit_write_header; + ret = __archive_write_output(a, buff, 512); + if(ret < ARCHIVE_WARN) + goto exit_write_header; + /* Write pathname + trailing null byte. */ + ret = __archive_write_output(a, pathname, length); + if(ret < ARCHIVE_WARN) + goto exit_write_header; + /* Pad to multiple of 512 bytes. */ + ret = __archive_write_nulls(a, 0x1ff & (-(ssize_t)length)); + if (ret < ARCHIVE_WARN) + goto exit_write_header; + } + + if (archive_entry_hardlink(entry) != NULL) { + tartype = '1'; + } else + switch (archive_entry_filetype(entry)) { + case AE_IFREG: tartype = '0' ; break; + case AE_IFLNK: tartype = '2' ; break; + case AE_IFCHR: tartype = '3' ; break; + case AE_IFBLK: tartype = '4' ; break; + case AE_IFDIR: tartype = '5' ; break; + case AE_IFIFO: tartype = '6' ; break; + default: /* AE_IFSOCK and unknown */ + __archive_write_entry_filetype_unsupported( + &a->archive, entry, "gnutar"); + ret = ARCHIVE_FAILED; + goto exit_write_header; + } + + ret = archive_format_gnutar_header(a, buff, entry, tartype); + if (ret < ARCHIVE_WARN) + goto exit_write_header; + if (ret2 < ret) + ret = ret2; + ret2 = __archive_write_output(a, buff, 512); + if (ret2 < ARCHIVE_WARN) { + ret = ret2; + goto exit_write_header; + } + if (ret2 < ret) + ret = ret2; + + gnutar->entry_bytes_remaining = archive_entry_size(entry); + gnutar->entry_padding = 0x1ff & (-(int64_t)gnutar->entry_bytes_remaining); +exit_write_header: + archive_entry_free(entry_main); + return (ret); +} + +static int +archive_format_gnutar_header(struct archive_write *a, char h[512], + struct archive_entry *entry, int tartype) +{ + unsigned int checksum; + int i, ret; + size_t copy_length; + const char *p; + struct gnutar *gnutar; + + gnutar = (struct gnutar *)a->format_data; + + ret = 0; + + /* + * The "template header" already includes the signature, + * various end-of-field markers, and other required elements. + */ + memcpy(h, &template_header, 512); + + /* + * Because the block is already null-filled, and strings + * are allowed to exactly fill their destination (without null), + * I use memcpy(dest, src, strlen()) here a lot to copy strings. + */ + + if (tartype == 'K' || tartype == 'L') { + p = archive_entry_pathname(entry); + copy_length = strlen(p); + } else { + p = gnutar->pathname; + copy_length = gnutar->pathname_length; + } + if (copy_length > GNUTAR_name_size) + copy_length = GNUTAR_name_size; + memcpy(h + GNUTAR_name_offset, p, copy_length); + + if ((copy_length = gnutar->linkname_length) > 0) { + if (copy_length > GNUTAR_linkname_size) + copy_length = GNUTAR_linkname_size; + memcpy(h + GNUTAR_linkname_offset, gnutar->linkname, + copy_length); + } + + /* TODO: How does GNU tar handle unames longer than GNUTAR_uname_size? */ + if (tartype == 'K' || tartype == 'L') { + p = archive_entry_uname(entry); + copy_length = strlen(p); + } else { + p = gnutar->uname; + copy_length = gnutar->uname_length; + } + if (copy_length > 0) { + if (copy_length > GNUTAR_uname_size) + copy_length = GNUTAR_uname_size; + memcpy(h + GNUTAR_uname_offset, p, copy_length); + } + + /* TODO: How does GNU tar handle gnames longer than GNUTAR_gname_size? */ + if (tartype == 'K' || tartype == 'L') { + p = archive_entry_gname(entry); + copy_length = strlen(p); + } else { + p = gnutar->gname; + copy_length = gnutar->gname_length; + } + if (copy_length > 0) { + if (strlen(p) > GNUTAR_gname_size) + copy_length = GNUTAR_gname_size; + memcpy(h + GNUTAR_gname_offset, p, copy_length); + } + + /* By truncating the mode here, we ensure it always fits. */ + format_octal(archive_entry_mode(entry) & 07777, + h + GNUTAR_mode_offset, GNUTAR_mode_size); + + /* GNU tar supports base-256 here, so should never overflow. */ + if (format_number(archive_entry_uid(entry), h + GNUTAR_uid_offset, + GNUTAR_uid_size, GNUTAR_uid_max_size)) { + archive_set_error(&a->archive, ERANGE, + "Numeric user ID %jd too large", + (intmax_t)archive_entry_uid(entry)); + ret = ARCHIVE_FAILED; + } + + /* GNU tar supports base-256 here, so should never overflow. */ + if (format_number(archive_entry_gid(entry), h + GNUTAR_gid_offset, + GNUTAR_gid_size, GNUTAR_gid_max_size)) { + archive_set_error(&a->archive, ERANGE, + "Numeric group ID %jd too large", + (intmax_t)archive_entry_gid(entry)); + ret = ARCHIVE_FAILED; + } + + /* GNU tar supports base-256 here, so should never overflow. */ + if (format_number(archive_entry_size(entry), h + GNUTAR_size_offset, + GNUTAR_size_size, GNUTAR_size_max_size)) { + archive_set_error(&a->archive, ERANGE, + "File size out of range"); + ret = ARCHIVE_FAILED; + } + + /* Shouldn't overflow before 2106, since mtime field is 33 bits. */ + format_octal(archive_entry_mtime(entry), + h + GNUTAR_mtime_offset, GNUTAR_mtime_size); + + if (archive_entry_filetype(entry) == AE_IFBLK + || archive_entry_filetype(entry) == AE_IFCHR) { + if (format_octal(archive_entry_rdevmajor(entry), + h + GNUTAR_rdevmajor_offset, + GNUTAR_rdevmajor_size)) { + archive_set_error(&a->archive, ERANGE, + "Major device number too large"); + ret = ARCHIVE_FAILED; + } + + if (format_octal(archive_entry_rdevminor(entry), + h + GNUTAR_rdevminor_offset, + GNUTAR_rdevminor_size)) { + archive_set_error(&a->archive, ERANGE, + "Minor device number too large"); + ret = ARCHIVE_FAILED; + } + } + + h[GNUTAR_typeflag_offset] = tartype; + + checksum = 0; + for (i = 0; i < 512; i++) + checksum += 255 & (unsigned int)h[i]; + h[GNUTAR_checksum_offset + 6] = '\0'; /* Can't be pre-set in the template. */ + /* h[GNUTAR_checksum_offset + 7] = ' '; */ /* This is pre-set in the template. */ + format_octal(checksum, h + GNUTAR_checksum_offset, 6); + return (ret); +} + +/* + * Format a number into a field, falling back to base-256 if necessary. + */ +static int +format_number(int64_t v, char *p, int s, int maxsize) +{ + int64_t limit = ((int64_t)1 << (s*3)); + + if (v < limit) + return (format_octal(v, p, s)); + return (format_256(v, p, maxsize)); +} + +/* + * Format a number into the specified field using base-256. + */ +static int +format_256(int64_t v, char *p, int s) +{ + p += s; + while (s-- > 0) { + *--p = (char)(v & 0xff); + v >>= 8; + } + *p |= 0x80; /* Set the base-256 marker bit. */ + return (0); +} + +/* + * Format a number into the specified field using octal. + */ +static int +format_octal(int64_t v, char *p, int s) +{ + int len = s; + + /* Octal values can't be negative, so use 0. */ + if (v < 0) + v = 0; + + p += s; /* Start at the end and work backwards. */ + while (s-- > 0) { + *--p = (char)('0' + (v & 7)); + v >>= 3; + } + + if (v == 0) + return (0); + + /* If it overflowed, fill field with max value. */ + while (len-- > 0) + *p++ = '7'; + + return (-1); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_iso9660.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_iso9660.c new file mode 100644 index 0000000000..7cde44c34f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_iso9660.c @@ -0,0 +1,8162 @@ +/*- + * Copyright (c) 2009-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_UTSNAME_H +#include <sys/utsname.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#include <stdio.h> +#include <stdarg.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#include <time.h> +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_ZLIB_H +#include <zlib.h> +#endif + +#include "archive.h" +#include "archive_endian.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_rb.h" +#include "archive_write_private.h" + +#if defined(_WIN32) && !defined(__CYGWIN__) +#define getuid() 0 +#define getgid() 0 +#endif + +/*#define DEBUG 1*/ +#ifdef DEBUG +/* To compare to the ISO image file made by mkisofs. */ +#define COMPAT_MKISOFS 1 +#endif + +#define LOGICAL_BLOCK_BITS 11 +#define LOGICAL_BLOCK_SIZE 2048 +#define PATH_TABLE_BLOCK_SIZE 4096 + +#define SYSTEM_AREA_BLOCK 16 +#define PRIMARY_VOLUME_DESCRIPTOR_BLOCK 1 +#define SUPPLEMENTARY_VOLUME_DESCRIPTOR_BLOCK 1 +#define BOOT_RECORD_DESCRIPTOR_BLOCK 1 +#define VOLUME_DESCRIPTOR_SET_TERMINATOR_BLOCK 1 +#define NON_ISO_FILE_SYSTEM_INFORMATION_BLOCK 1 +#define RRIP_ER_BLOCK 1 +#define PADDING_BLOCK 150 + +#define FD_1_2M_SIZE (1024 * 1200) +#define FD_1_44M_SIZE (1024 * 1440) +#define FD_2_88M_SIZE (1024 * 2880) +#define MULTI_EXTENT_SIZE (ARCHIVE_LITERAL_LL(1) << 32) /* 4Gi bytes. */ +#define MAX_DEPTH 8 +#define RR_CE_SIZE 28 /* SUSP "CE" extension size */ + +#define FILE_FLAG_EXISTENCE 0x01 +#define FILE_FLAG_DIRECTORY 0x02 +#define FILE_FLAG_ASSOCIATED 0x04 +#define FILE_FLAG_RECORD 0x08 +#define FILE_FLAG_PROTECTION 0x10 +#define FILE_FLAG_MULTI_EXTENT 0x80 + +static const char rrip_identifier[] = + "RRIP_1991A"; +static const char rrip_descriptor[] = + "THE ROCK RIDGE INTERCHANGE PROTOCOL PROVIDES SUPPORT FOR " + "POSIX FILE SYSTEM SEMANTICS"; +static const char rrip_source[] = + "PLEASE CONTACT DISC PUBLISHER FOR SPECIFICATION SOURCE. " + "SEE PUBLISHER IDENTIFIER IN PRIMARY VOLUME DESCRIPTOR FOR " + "CONTACT INFORMATION."; +#define RRIP_ER_ID_SIZE (sizeof(rrip_identifier)-1) +#define RRIP_ER_DSC_SIZE (sizeof(rrip_descriptor)-1) +#define RRIP_ER_SRC_SIZE (sizeof(rrip_source)-1) +#define RRIP_ER_SIZE (8 + RRIP_ER_ID_SIZE + \ + RRIP_ER_DSC_SIZE + RRIP_ER_SRC_SIZE) + +static const unsigned char zisofs_magic[8] = { + 0x37, 0xE4, 0x53, 0x96, 0xC9, 0xDB, 0xD6, 0x07 +}; + +#define ZF_HEADER_SIZE 16 /* zisofs header size. */ +#define ZF_LOG2_BS 15 /* log2 block size; 32K bytes. */ +#define ZF_BLOCK_SIZE (1UL << ZF_LOG2_BS) + +/* + * Manage extra records. + */ +struct extr_rec { + int location; + int offset; + unsigned char buf[LOGICAL_BLOCK_SIZE]; + struct extr_rec *next; +}; + +struct ctl_extr_rec { + int use_extr; + unsigned char *bp; + struct isoent *isoent; + unsigned char *ce_ptr; + int cur_len; + int dr_len; + int limit; + int extr_off; + int extr_loc; +}; +#define DR_SAFETY RR_CE_SIZE +#define DR_LIMIT (254 - DR_SAFETY) + +/* + * The relation of struct isofile and isoent and archive_entry. + * + * Primary volume tree --> struct isoent + * | + * v + * struct isofile --> archive_entry + * ^ + * | + * Joliet volume tree --> struct isoent + * + * struct isoent has specific information for volume. + */ + +struct isofile { + /* Used for managing struct isofile list. */ + struct isofile *allnext; + struct isofile *datanext; + /* Used for managing a hardlinked struct isofile list. */ + struct isofile *hlnext; + struct isofile *hardlink_target; + + struct archive_entry *entry; + + /* + * Used for making a directory tree. + */ + struct archive_string parentdir; + struct archive_string basename; + struct archive_string basename_utf16; + struct archive_string symlink; + int dircnt; /* The number of elements of + * its parent directory */ + + /* + * Used for a Directory Record. + */ + struct content { + int64_t offset_of_temp; + int64_t size; + int blocks; + uint32_t location; + /* + * One extent equals one content. + * If this entry has multi extent, `next' variable points + * next content data. + */ + struct content *next; /* next content */ + } content, *cur_content; + int write_content; + + enum { + NO = 0, + BOOT_CATALOG, + BOOT_IMAGE + } boot; + + /* + * Used for a zisofs. + */ + struct { + unsigned char header_size; + unsigned char log2_bs; + uint32_t uncompressed_size; + } zisofs; +}; + +struct isoent { + /* Keep `rbnode' at the first member of struct isoent. */ + struct archive_rb_node rbnode; + + struct isofile *file; + + struct isoent *parent; + /* A list of children.(use chnext) */ + struct { + struct isoent *first; + struct isoent **last; + int cnt; + } children; + struct archive_rb_tree rbtree; + + /* A list of sub directories.(use drnext) */ + struct { + struct isoent *first; + struct isoent **last; + int cnt; + } subdirs; + /* A sorted list of sub directories. */ + struct isoent **children_sorted; + /* Used for managing struct isoent list. */ + struct isoent *chnext; + struct isoent *drnext; + struct isoent *ptnext; + + /* + * Used for making a Directory Record. + */ + int dir_number; + struct { + int vd; + int self; + int parent; + int normal; + } dr_len; + uint32_t dir_location; + int dir_block; + + /* + * Identifier: + * on primary, ISO9660 file/directory name. + * on joliet, UCS2 file/directory name. + * ext_off : offset of identifier extension. + * ext_len : length of identifier extension. + * id_len : byte size of identifier. + * on primary, this is ext_off + ext_len + version length. + * on joliet, this is ext_off + ext_len. + * mb_len : length of multibyte-character of identifier. + * on primary, mb_len and id_len are always the same. + * on joliet, mb_len and id_len are different. + */ + char *identifier; + int ext_off; + int ext_len; + int id_len; + int mb_len; + + /* + * Used for making a Rockridge extension. + * This is a part of Directory Records. + */ + struct isoent *rr_parent; + struct isoent *rr_child; + + /* Extra Record.(which we call in this source file) + * A maximum size of the Directory Record is 254. + * so, if generated RRIP data of a file cannot into a Directory + * Record because of its size, that surplus data relocate this + * Extra Record. + */ + struct { + struct extr_rec *first; + struct extr_rec **last; + struct extr_rec *current; + } extr_rec_list; + + signed int virtual:1; + /* If set to one, this file type is a directory. + * A convenience flag to be used as + * "archive_entry_filetype(isoent->file->entry) == AE_IFDIR". + */ + signed int dir:1; +}; + +struct hardlink { + struct archive_rb_node rbnode; + int nlink; + struct { + struct isofile *first; + struct isofile **last; + } file_list; +}; + +/* + * ISO writer options + */ +struct iso_option { + /* + * Usage : abstract-file=<value> + * Type : string, max 37 bytes + * Default: Not specified + * COMPAT : mkisofs -abstract <value> + * + * Specifies Abstract Filename. + * This file shall be described in the Root Directory + * and containing a abstract statement. + */ + unsigned int abstract_file:1; +#define OPT_ABSTRACT_FILE_DEFAULT 0 /* Not specified */ +#define ABSTRACT_FILE_SIZE 37 + + /* + * Usage : application-id=<value> + * Type : string, max 128 bytes + * Default: Not specified + * COMPAT : mkisofs -A/-appid <value>. + * + * Specifies Application Identifier. + * If the first byte is set to '_'(5F), the remaining + * bytes of this option shall specify an identifier + * for a file containing the identification of the + * application. + * This file shall be described in the Root Directory. + */ + unsigned int application_id:1; +#define OPT_APPLICATION_ID_DEFAULT 0 /* Use default identifier */ +#define APPLICATION_IDENTIFIER_SIZE 128 + + /* + * Usage : !allow-vernum + * Type : boolean + * Default: Enabled + * : Violates the ISO9660 standard if disable. + * COMPAT: mkisofs -N + * + * Allow filenames to use version numbers. + */ + unsigned int allow_vernum:1; +#define OPT_ALLOW_VERNUM_DEFAULT 1 /* Enabled */ + + /* + * Usage : biblio-file=<value> + * Type : string, max 37 bytes + * Default: Not specified + * COMPAT : mkisofs -biblio <value> + * + * Specifies Bibliographic Filename. + * This file shall be described in the Root Directory + * and containing bibliographic records. + */ + unsigned int biblio_file:1; +#define OPT_BIBLIO_FILE_DEFAULT 0 /* Not specified */ +#define BIBLIO_FILE_SIZE 37 + + /* + * Usage : boot=<value> + * Type : string + * Default: Not specified + * COMPAT : mkisofs -b/-eltorito-boot <value> + * + * Specifies "El Torito" boot image file to make + * a bootable CD. + */ + unsigned int boot:1; +#define OPT_BOOT_DEFAULT 0 /* Not specified */ + + /* + * Usage : boot-catalog=<value> + * Type : string + * Default: "boot.catalog" + * COMPAT : mkisofs -c/-eltorito-catalog <value> + * + * Specifies a fullpath of El Torito boot catalog. + */ + unsigned int boot_catalog:1; +#define OPT_BOOT_CATALOG_DEFAULT 0 /* Not specified */ + + /* + * Usage : boot-info-table + * Type : boolean + * Default: Disabled + * COMPAT : mkisofs -boot-info-table + * + * Modify the boot image file specified by `boot' + * option; ISO writer stores boot file information + * into the boot file in ISO image at offset 8 + * through offset 64. + */ + unsigned int boot_info_table:1; +#define OPT_BOOT_INFO_TABLE_DEFAULT 0 /* Disabled */ + + /* + * Usage : boot-load-seg=<value> + * Type : hexadecimal + * Default: Not specified + * COMPAT : mkisofs -boot-load-seg <value> + * + * Specifies a load segment for boot image. + * This is used with no-emulation mode. + */ + unsigned int boot_load_seg:1; +#define OPT_BOOT_LOAD_SEG_DEFAULT 0 /* Not specified */ + + /* + * Usage : boot-load-size=<value> + * Type : decimal + * Default: Not specified + * COMPAT : mkisofs -boot-load-size <value> + * + * Specifies a sector count for boot image. + * This is used with no-emulation mode. + */ + unsigned int boot_load_size:1; +#define OPT_BOOT_LOAD_SIZE_DEFAULT 0 /* Not specified */ + + /* + * Usage : boot-type=<boot-media-type> + * : 'no-emulation' : 'no emulation' image + * : 'fd' : floppy disk image + * : 'hard-disk' : hard disk image + * Type : string + * Default: Auto detect + * : We check a size of boot image; + * : If the size is just 1.22M/1.44M/2.88M, + * : we assume boot_type is 'fd'; + * : otherwise boot_type is 'no-emulation'. + * COMPAT : + * boot=no-emulation + * mkisofs -no-emul-boot + * boot=fd + * This is a default on the mkisofs. + * boot=hard-disk + * mkisofs -hard-disk-boot + * + * Specifies a type of "El Torito" boot image. + */ + unsigned int boot_type:2; +#define OPT_BOOT_TYPE_AUTO 0 /* auto detect */ +#define OPT_BOOT_TYPE_NO_EMU 1 /* ``no emulation'' image */ +#define OPT_BOOT_TYPE_FD 2 /* floppy disk image */ +#define OPT_BOOT_TYPE_HARD_DISK 3 /* hard disk image */ +#define OPT_BOOT_TYPE_DEFAULT OPT_BOOT_TYPE_AUTO + + /* + * Usage : compression-level=<value> + * Type : decimal + * Default: Not specified + * COMPAT : NONE + * + * Specifies compression level for option zisofs=direct. + */ + unsigned int compression_level:1; +#define OPT_COMPRESSION_LEVEL_DEFAULT 0 /* Not specified */ + + /* + * Usage : copyright-file=<value> + * Type : string, max 37 bytes + * Default: Not specified + * COMPAT : mkisofs -copyright <value> + * + * Specifies Copyright Filename. + * This file shall be described in the Root Directory + * and containing a copyright statement. + */ + unsigned int copyright_file:1; +#define OPT_COPYRIGHT_FILE_DEFAULT 0 /* Not specified */ +#define COPYRIGHT_FILE_SIZE 37 + + /* + * Usage : gid=<value> + * Type : decimal + * Default: Not specified + * COMPAT : mkisofs -gid <value> + * + * Specifies a group id to rewrite the group id of all files. + */ + unsigned int gid:1; +#define OPT_GID_DEFAULT 0 /* Not specified */ + + /* + * Usage : iso-level=[1234] + * Type : decimal + * Default: 1 + * COMPAT : mkisofs -iso-level <value> + * + * Specifies ISO9600 Level. + * Level 1: [DEFAULT] + * - limits each file size less than 4Gi bytes; + * - a File Name shall not contain more than eight + * d-characters or eight d1-characters; + * - a File Name Extension shall not contain more than + * three d-characters or three d1-characters; + * - a Directory Identifier shall not contain more + * than eight d-characters or eight d1-characters. + * Level 2: + * - limits each file size less than 4Giga bytes; + * - a File Name shall not contain more than thirty + * d-characters or thirty d1-characters; + * - a File Name Extension shall not contain more than + * thirty d-characters or thirty d1-characters; + * - a Directory Identifier shall not contain more + * than thirty-one d-characters or thirty-one + * d1-characters. + * Level 3: + * - no limit of file size; use multi extent. + * Level 4: + * - this level 4 simulates mkisofs option + * '-iso-level 4'; + * - crate a enhanced volume as mkisofs doing; + * - allow a File Name to have leading dot; + * - allow a File Name to have all ASCII letters; + * - allow a File Name to have multiple dots; + * - allow more then 8 depths of directory trees; + * - disable a version number to a File Name; + * - disable a forced period to the tail of a File Name; + * - the maximum length of files and directories is raised to 193. + * if rockridge option is disabled, raised to 207. + */ + unsigned int iso_level:3; +#define OPT_ISO_LEVEL_DEFAULT 1 /* ISO Level 1 */ + + /* + * Usage : joliet[=long] + * : !joliet + * : Do not generate Joliet Volume and Records. + * : joliet [DEFAULT] + * : Generates Joliet Volume and Directory Records. + * : [COMPAT: mkisofs -J/-joliet] + * : joliet=long + * : The joliet filenames are up to 103 Unicode + * : characters. + * : This option breaks the Joliet specification. + * : [COMPAT: mkisofs -J -joliet-long] + * Type : boolean/string + * Default: Enabled + * COMPAT : mkisofs -J / -joliet-long + * + * Generates Joliet Volume and Directory Records. + */ + unsigned int joliet:2; +#define OPT_JOLIET_DISABLE 0 /* Not generate Joliet Records. */ +#define OPT_JOLIET_ENABLE 1 /* Generate Joliet Records. */ +#define OPT_JOLIET_LONGNAME 2 /* Use long joliet filenames.*/ +#define OPT_JOLIET_DEFAULT OPT_JOLIET_ENABLE + + /* + * Usage : !limit-depth + * Type : boolean + * Default: Enabled + * : Violates the ISO9660 standard if disable. + * COMPAT : mkisofs -D/-disable-deep-relocation + * + * The number of levels in hierarchy cannot exceed eight. + */ + unsigned int limit_depth:1; +#define OPT_LIMIT_DEPTH_DEFAULT 1 /* Enabled */ + + /* + * Usage : !limit-dirs + * Type : boolean + * Default: Enabled + * : Violates the ISO9660 standard if disable. + * COMPAT : mkisofs -no-limit-pathtables + * + * Limits the number of directories less than 65536 due + * to the size of the Parent Directory Number of Path + * Table. + */ + unsigned int limit_dirs:1; +#define OPT_LIMIT_DIRS_DEFAULT 1 /* Enabled */ + + /* + * Usage : !pad + * Type : boolean + * Default: Enabled + * COMPAT : -pad/-no-pad + * + * Pads the end of the ISO image by null of 300Ki bytes. + */ + unsigned int pad:1; +#define OPT_PAD_DEFAULT 1 /* Enabled */ + + /* + * Usage : publisher=<value> + * Type : string, max 128 bytes + * Default: Not specified + * COMPAT : mkisofs -publisher <value> + * + * Specifies Publisher Identifier. + * If the first byte is set to '_'(5F), the remaining + * bytes of this option shall specify an identifier + * for a file containing the identification of the user. + * This file shall be described in the Root Directory. + */ + unsigned int publisher:1; +#define OPT_PUBLISHER_DEFAULT 0 /* Not specified */ +#define PUBLISHER_IDENTIFIER_SIZE 128 + + /* + * Usage : rockridge + * : !rockridge + * : disable to generate SUSP and RR records. + * : rockridge + * : the same as 'rockridge=useful'. + * : rockridge=strict + * : generate SUSP and RR records. + * : [COMPAT: mkisofs -R] + * : rockridge=useful [DEFAULT] + * : generate SUSP and RR records. + * : [COMPAT: mkisofs -r] + * : NOTE Our rockridge=useful option does not set a zero + * : to uid and gid, you should use application + * : option such as --gid,--gname,--uid and --uname + * : bsdtar options instead. + * Type : boolean/string + * Default: Enabled as rockridge=useful + * COMPAT : mkisofs -r / -R + * + * Generates SUSP and RR records. + */ + unsigned int rr:2; +#define OPT_RR_DISABLED 0 +#define OPT_RR_STRICT 1 +#define OPT_RR_USEFUL 2 +#define OPT_RR_DEFAULT OPT_RR_USEFUL + + /* + * Usage : volume-id=<value> + * Type : string, max 32 bytes + * Default: Not specified + * COMPAT : mkisofs -V <value> + * + * Specifies Volume Identifier. + */ + unsigned int volume_id:1; +#define OPT_VOLUME_ID_DEFAULT 0 /* Use default identifier */ +#define VOLUME_IDENTIFIER_SIZE 32 + + /* + * Usage : !zisofs [DEFAULT] + * : Disable to generate RRIP 'ZF' extension. + * : zisofs + * : Make files zisofs file and generate RRIP 'ZF' + * : extension. So you do not need mkzftree utility + * : for making zisofs. + * : When the file size is less than one Logical Block + * : size, that file will not zisofs'ed since it does + * : reduce an ISO-image size. + * : + * : When you specify option 'boot=<boot-image>', that + * : 'boot-image' file won't be converted to zisofs file. + * Type : boolean + * Default: Disabled + * + * Generates RRIP 'ZF' System Use Entry. + */ + unsigned int zisofs:1; +#define OPT_ZISOFS_DISABLED 0 +#define OPT_ZISOFS_DIRECT 1 +#define OPT_ZISOFS_DEFAULT OPT_ZISOFS_DISABLED + +}; + +struct iso9660 { + /* The creation time of ISO image. */ + time_t birth_time; + /* A file stream of a temporary file, which file contents + * save to until ISO image can be created. */ + int temp_fd; + + struct isofile *cur_file; + struct isoent *cur_dirent; + struct archive_string cur_dirstr; + uint64_t bytes_remaining; + int need_multi_extent; + + /* Temporary string buffer for Joliet extension. */ + struct archive_string utf16be; + struct archive_string mbs; + + struct archive_string_conv *sconv_to_utf16be; + struct archive_string_conv *sconv_from_utf16be; + + /* A list of all of struct isofile entries. */ + struct { + struct isofile *first; + struct isofile **last; + } all_file_list; + + /* A list of struct isofile entries which have its + * contents and are not a directory, a hardlinked file + * and a symlink file. */ + struct { + struct isofile *first; + struct isofile **last; + } data_file_list; + + /* Used for managing to find hardlinking files. */ + struct archive_rb_tree hardlink_rbtree; + + /* Used for making the Path Table Record. */ + struct vdd { + /* the root of entry tree. */ + struct isoent *rootent; + enum vdd_type { + VDD_PRIMARY, + VDD_JOLIET, + VDD_ENHANCED + } vdd_type; + + struct path_table { + struct isoent *first; + struct isoent **last; + struct isoent **sorted; + int cnt; + } *pathtbl; + int max_depth; + + int path_table_block; + int path_table_size; + int location_type_L_path_table; + int location_type_M_path_table; + int total_dir_block; + } primary, joliet; + + /* Used for making a Volume Descriptor. */ + int volume_space_size; + int volume_sequence_number; + int total_file_block; + struct archive_string volume_identifier; + struct archive_string publisher_identifier; + struct archive_string data_preparer_identifier; + struct archive_string application_identifier; + struct archive_string copyright_file_identifier; + struct archive_string abstract_file_identifier; + struct archive_string bibliographic_file_identifier; + + /* Used for making rockridge extensions. */ + int location_rrip_er; + + /* Used for making zisofs. */ + struct { + signed int detect_magic:1; + signed int making:1; + signed int allzero:1; + unsigned char magic_buffer[64]; + int magic_cnt; + +#ifdef HAVE_ZLIB_H + /* + * Copy a compressed file to iso9660.zisofs.temp_fd + * and also copy a uncompressed file(original file) to + * iso9660.temp_fd . If the number of logical block + * of the compressed file is less than the number of + * logical block of the uncompressed file, use it and + * remove the copy of the uncompressed file. + * but if not, we use uncompressed file and remove + * the copy of the compressed file. + */ + uint32_t *block_pointers; + size_t block_pointers_allocated; + int block_pointers_cnt; + int block_pointers_idx; + int64_t total_size; + int64_t block_offset; + + z_stream stream; + int stream_valid; + int64_t remaining; + int compression_level; +#endif + } zisofs; + + struct isoent *directories_too_deep; + int dircnt_max; + + /* Write buffer. */ +#define wb_buffmax() (LOGICAL_BLOCK_SIZE * 32) +#define wb_remaining(a) (((struct iso9660 *)(a)->format_data)->wbuff_remaining) +#define wb_offset(a) (((struct iso9660 *)(a)->format_data)->wbuff_offset \ + + wb_buffmax() - wb_remaining(a)) + unsigned char wbuff[LOGICAL_BLOCK_SIZE * 32]; + size_t wbuff_remaining; + enum { + WB_TO_STREAM, + WB_TO_TEMP + } wbuff_type; + int64_t wbuff_offset; + int64_t wbuff_written; + int64_t wbuff_tail; + + /* 'El Torito' boot data. */ + struct { + /* boot catalog file */ + struct archive_string catalog_filename; + struct isoent *catalog; + /* boot image file */ + struct archive_string boot_filename; + struct isoent *boot; + + unsigned char platform_id; +#define BOOT_PLATFORM_X86 0 +#define BOOT_PLATFORM_PPC 1 +#define BOOT_PLATFORM_MAC 2 + struct archive_string id; + unsigned char media_type; +#define BOOT_MEDIA_NO_EMULATION 0 +#define BOOT_MEDIA_1_2M_DISKETTE 1 +#define BOOT_MEDIA_1_44M_DISKETTE 2 +#define BOOT_MEDIA_2_88M_DISKETTE 3 +#define BOOT_MEDIA_HARD_DISK 4 + unsigned char system_type; + uint16_t boot_load_seg; + uint16_t boot_load_size; +#define BOOT_LOAD_SIZE 4 + } el_torito; + + struct iso_option opt; +}; + +/* + * Types of Volume Descriptor + */ +enum VD_type { + VDT_BOOT_RECORD=0, /* Boot Record Volume Descriptor */ + VDT_PRIMARY=1, /* Primary Volume Descriptor */ + VDT_SUPPLEMENTARY=2, /* Supplementary Volume Descriptor */ + VDT_TERMINATOR=255 /* Volume Descriptor Set Terminator */ +}; + +/* + * Types of Directory Record + */ +enum dir_rec_type { + DIR_REC_VD, /* Stored in Volume Descriptor. */ + DIR_REC_SELF, /* Stored as Current Directory. */ + DIR_REC_PARENT, /* Stored as Parent Directory. */ + DIR_REC_NORMAL /* Stored as Child. */ +}; + +/* + * Kinds of Volume Descriptor Character + */ +enum vdc { + VDC_STD, + VDC_LOWERCASE, + VDC_UCS2, + VDC_UCS2_DIRECT +}; + +/* + * IDentifier Resolver. + * Used for resolving duplicated filenames. + */ +struct idr { + struct idrent { + struct archive_rb_node rbnode; + /* Used in wait_list. */ + struct idrent *wnext; + struct idrent *avail; + + struct isoent *isoent; + int weight; + int noff; + int rename_num; + } *idrent_pool; + + struct archive_rb_tree rbtree; + + struct { + struct idrent *first; + struct idrent **last; + } wait_list; + + int pool_size; + int pool_idx; + int num_size; + int null_size; + + char char_map[0x80]; +}; + +enum char_type { + A_CHAR, + D_CHAR +}; + + +static int iso9660_options(struct archive_write *, + const char *, const char *); +static int iso9660_write_header(struct archive_write *, + struct archive_entry *); +static ssize_t iso9660_write_data(struct archive_write *, + const void *, size_t); +static int iso9660_finish_entry(struct archive_write *); +static int iso9660_close(struct archive_write *); +static int iso9660_free(struct archive_write *); + +static void get_system_identitier(char *, size_t); +static void set_str(unsigned char *, const char *, size_t, char, + const char *); +static inline int joliet_allowed_char(unsigned char, unsigned char); +static int set_str_utf16be(struct archive_write *, unsigned char *, + const char *, size_t, uint16_t, enum vdc); +static int set_str_a_characters_bp(struct archive_write *, + unsigned char *, int, int, const char *, enum vdc); +static int set_str_d_characters_bp(struct archive_write *, + unsigned char *, int, int, const char *, enum vdc); +static void set_VD_bp(unsigned char *, enum VD_type, unsigned char); +static inline void set_unused_field_bp(unsigned char *, int, int); + +static unsigned char *extra_open_record(unsigned char *, int, + struct isoent *, struct ctl_extr_rec *); +static void extra_close_record(struct ctl_extr_rec *, int); +static unsigned char * extra_next_record(struct ctl_extr_rec *, int); +static unsigned char *extra_get_record(struct isoent *, int *, int *, int *); +static void extra_tell_used_size(struct ctl_extr_rec *, int); +static int extra_setup_location(struct isoent *, int); +static int set_directory_record_rr(unsigned char *, int, + struct isoent *, struct iso9660 *, enum dir_rec_type); +static int set_directory_record(unsigned char *, size_t, + struct isoent *, struct iso9660 *, enum dir_rec_type, + enum vdd_type); +static inline int get_dir_rec_size(struct iso9660 *, struct isoent *, + enum dir_rec_type, enum vdd_type); +static inline unsigned char *wb_buffptr(struct archive_write *); +static int wb_write_out(struct archive_write *); +static int wb_consume(struct archive_write *, size_t); +#ifdef HAVE_ZLIB_H +static int wb_set_offset(struct archive_write *, int64_t); +#endif +static int write_null(struct archive_write *, size_t); +static int write_VD_terminator(struct archive_write *); +static int set_file_identifier(unsigned char *, int, int, enum vdc, + struct archive_write *, struct vdd *, + struct archive_string *, const char *, int, + enum char_type); +static int write_VD(struct archive_write *, struct vdd *); +static int write_VD_boot_record(struct archive_write *); +static int write_information_block(struct archive_write *); +static int write_path_table(struct archive_write *, int, + struct vdd *); +static int write_directory_descriptors(struct archive_write *, + struct vdd *); +static int write_file_descriptors(struct archive_write *); +static int write_rr_ER(struct archive_write *); +static void calculate_path_table_size(struct vdd *); + +static void isofile_init_entry_list(struct iso9660 *); +static void isofile_add_entry(struct iso9660 *, struct isofile *); +static void isofile_free_all_entries(struct iso9660 *); +static void isofile_init_entry_data_file_list(struct iso9660 *); +static void isofile_add_data_file(struct iso9660 *, struct isofile *); +static struct isofile * isofile_new(struct archive_write *, + struct archive_entry *); +static void isofile_free(struct isofile *); +static int isofile_gen_utility_names(struct archive_write *, + struct isofile *); +static int isofile_register_hardlink(struct archive_write *, + struct isofile *); +static void isofile_connect_hardlink_files(struct iso9660 *); +static void isofile_init_hardlinks(struct iso9660 *); +static void isofile_free_hardlinks(struct iso9660 *); + +static struct isoent *isoent_new(struct isofile *); +static int isoent_clone_tree(struct archive_write *, + struct isoent **, struct isoent *); +static void _isoent_free(struct isoent *isoent); +static void isoent_free_all(struct isoent *); +static struct isoent * isoent_create_virtual_dir(struct archive_write *, + struct iso9660 *, const char *); +static int isoent_cmp_node(const struct archive_rb_node *, + const struct archive_rb_node *); +static int isoent_cmp_key(const struct archive_rb_node *, + const void *); +static int isoent_add_child_head(struct isoent *, struct isoent *); +static int isoent_add_child_tail(struct isoent *, struct isoent *); +static void isoent_remove_child(struct isoent *, struct isoent *); +static void isoent_setup_directory_location(struct iso9660 *, + int, struct vdd *); +static void isoent_setup_file_location(struct iso9660 *, int); +static int get_path_component(char *, size_t, const char *); +static int isoent_tree(struct archive_write *, struct isoent **); +static struct isoent *isoent_find_child(struct isoent *, const char *); +static struct isoent *isoent_find_entry(struct isoent *, const char *); +static void idr_relaxed_filenames(char *); +static void idr_init(struct iso9660 *, struct vdd *, struct idr *); +static void idr_cleanup(struct idr *); +static int idr_ensure_poolsize(struct archive_write *, struct idr *, + int); +static int idr_start(struct archive_write *, struct idr *, + int, int, int, int, const struct archive_rb_tree_ops *); +static void idr_register(struct idr *, struct isoent *, int, + int); +static void idr_extend_identifier(struct idrent *, int, int); +static void idr_resolve(struct idr *, void (*)(unsigned char *, int)); +static void idr_set_num(unsigned char *, int); +static void idr_set_num_beutf16(unsigned char *, int); +static int isoent_gen_iso9660_identifier(struct archive_write *, + struct isoent *, struct idr *); +static int isoent_gen_joliet_identifier(struct archive_write *, + struct isoent *, struct idr *); +static int isoent_cmp_iso9660_identifier(const struct isoent *, + const struct isoent *); +static int isoent_cmp_node_iso9660(const struct archive_rb_node *, + const struct archive_rb_node *); +static int isoent_cmp_key_iso9660(const struct archive_rb_node *, + const void *); +static int isoent_cmp_joliet_identifier(const struct isoent *, + const struct isoent *); +static int isoent_cmp_node_joliet(const struct archive_rb_node *, + const struct archive_rb_node *); +static int isoent_cmp_key_joliet(const struct archive_rb_node *, + const void *); +static inline void path_table_add_entry(struct path_table *, struct isoent *); +static inline struct isoent * path_table_last_entry(struct path_table *); +static int isoent_make_path_table(struct archive_write *); +static int isoent_find_out_boot_file(struct archive_write *, + struct isoent *); +static int isoent_create_boot_catalog(struct archive_write *, + struct isoent *); +static size_t fd_boot_image_size(int); +static int make_boot_catalog(struct archive_write *); +static int setup_boot_information(struct archive_write *); + +static int zisofs_init(struct archive_write *, struct isofile *); +static void zisofs_detect_magic(struct archive_write *, + const void *, size_t); +static int zisofs_write_to_temp(struct archive_write *, + const void *, size_t); +static int zisofs_finish_entry(struct archive_write *); +static int zisofs_rewind_boot_file(struct archive_write *); +static int zisofs_free(struct archive_write *); + +int +archive_write_set_format_iso9660(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct iso9660 *iso9660; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_iso9660"); + + /* If another format was already registered, unregister it. */ + if (a->format_free != NULL) + (a->format_free)(a); + + iso9660 = calloc(1, sizeof(*iso9660)); + if (iso9660 == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate iso9660 data"); + return (ARCHIVE_FATAL); + } + iso9660->birth_time = 0; + iso9660->temp_fd = -1; + iso9660->cur_file = NULL; + iso9660->primary.max_depth = 0; + iso9660->primary.vdd_type = VDD_PRIMARY; + iso9660->primary.pathtbl = NULL; + iso9660->joliet.rootent = NULL; + iso9660->joliet.max_depth = 0; + iso9660->joliet.vdd_type = VDD_JOLIET; + iso9660->joliet.pathtbl = NULL; + isofile_init_entry_list(iso9660); + isofile_init_entry_data_file_list(iso9660); + isofile_init_hardlinks(iso9660); + iso9660->directories_too_deep = NULL; + iso9660->dircnt_max = 1; + iso9660->wbuff_remaining = wb_buffmax(); + iso9660->wbuff_type = WB_TO_TEMP; + iso9660->wbuff_offset = 0; + iso9660->wbuff_written = 0; + iso9660->wbuff_tail = 0; + archive_string_init(&(iso9660->utf16be)); + archive_string_init(&(iso9660->mbs)); + + /* + * Init Identifiers used for PVD and SVD. + */ + archive_string_init(&(iso9660->volume_identifier)); + archive_strcpy(&(iso9660->volume_identifier), "CDROM"); + archive_string_init(&(iso9660->publisher_identifier)); + archive_string_init(&(iso9660->data_preparer_identifier)); + archive_string_init(&(iso9660->application_identifier)); + archive_strcpy(&(iso9660->application_identifier), + archive_version_string()); + archive_string_init(&(iso9660->copyright_file_identifier)); + archive_string_init(&(iso9660->abstract_file_identifier)); + archive_string_init(&(iso9660->bibliographic_file_identifier)); + + /* + * Init El Torito bootable CD variables. + */ + archive_string_init(&(iso9660->el_torito.catalog_filename)); + iso9660->el_torito.catalog = NULL; + /* Set default file name of boot catalog */ + archive_strcpy(&(iso9660->el_torito.catalog_filename), + "boot.catalog"); + archive_string_init(&(iso9660->el_torito.boot_filename)); + iso9660->el_torito.boot = NULL; + iso9660->el_torito.platform_id = BOOT_PLATFORM_X86; + archive_string_init(&(iso9660->el_torito.id)); + iso9660->el_torito.boot_load_seg = 0; + iso9660->el_torito.boot_load_size = BOOT_LOAD_SIZE; + + /* + * Init zisofs variables. + */ +#ifdef HAVE_ZLIB_H + iso9660->zisofs.block_pointers = NULL; + iso9660->zisofs.block_pointers_allocated = 0; + iso9660->zisofs.stream_valid = 0; + iso9660->zisofs.compression_level = 9; + memset(&(iso9660->zisofs.stream), 0, + sizeof(iso9660->zisofs.stream)); +#endif + + /* + * Set default value of iso9660 options. + */ + iso9660->opt.abstract_file = OPT_ABSTRACT_FILE_DEFAULT; + iso9660->opt.application_id = OPT_APPLICATION_ID_DEFAULT; + iso9660->opt.allow_vernum = OPT_ALLOW_VERNUM_DEFAULT; + iso9660->opt.biblio_file = OPT_BIBLIO_FILE_DEFAULT; + iso9660->opt.boot = OPT_BOOT_DEFAULT; + iso9660->opt.boot_catalog = OPT_BOOT_CATALOG_DEFAULT; + iso9660->opt.boot_info_table = OPT_BOOT_INFO_TABLE_DEFAULT; + iso9660->opt.boot_load_seg = OPT_BOOT_LOAD_SEG_DEFAULT; + iso9660->opt.boot_load_size = OPT_BOOT_LOAD_SIZE_DEFAULT; + iso9660->opt.boot_type = OPT_BOOT_TYPE_DEFAULT; + iso9660->opt.compression_level = OPT_COMPRESSION_LEVEL_DEFAULT; + iso9660->opt.copyright_file = OPT_COPYRIGHT_FILE_DEFAULT; + iso9660->opt.iso_level = OPT_ISO_LEVEL_DEFAULT; + iso9660->opt.joliet = OPT_JOLIET_DEFAULT; + iso9660->opt.limit_depth = OPT_LIMIT_DEPTH_DEFAULT; + iso9660->opt.limit_dirs = OPT_LIMIT_DIRS_DEFAULT; + iso9660->opt.pad = OPT_PAD_DEFAULT; + iso9660->opt.publisher = OPT_PUBLISHER_DEFAULT; + iso9660->opt.rr = OPT_RR_DEFAULT; + iso9660->opt.volume_id = OPT_VOLUME_ID_DEFAULT; + iso9660->opt.zisofs = OPT_ZISOFS_DEFAULT; + + /* Create the root directory. */ + iso9660->primary.rootent = + isoent_create_virtual_dir(a, iso9660, ""); + if (iso9660->primary.rootent == NULL) { + free(iso9660); + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + iso9660->primary.rootent->parent = iso9660->primary.rootent; + iso9660->cur_dirent = iso9660->primary.rootent; + archive_string_init(&(iso9660->cur_dirstr)); + archive_string_ensure(&(iso9660->cur_dirstr), 1); + iso9660->cur_dirstr.s[0] = 0; + iso9660->sconv_to_utf16be = NULL; + iso9660->sconv_from_utf16be = NULL; + + a->format_data = iso9660; + a->format_name = "iso9660"; + a->format_options = iso9660_options; + a->format_write_header = iso9660_write_header; + a->format_write_data = iso9660_write_data; + a->format_finish_entry = iso9660_finish_entry; + a->format_close = iso9660_close; + a->format_free = iso9660_free; + a->archive.archive_format = ARCHIVE_FORMAT_ISO9660; + a->archive.archive_format_name = "ISO9660"; + + return (ARCHIVE_OK); +} + +static int +get_str_opt(struct archive_write *a, struct archive_string *s, + size_t maxsize, const char *key, const char *value) +{ + + if (strlen(value) > maxsize) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Value is longer than %zu characters " + "for option ``%s''", maxsize, key); + return (ARCHIVE_FATAL); + } + archive_strcpy(s, value); + return (ARCHIVE_OK); +} + +static int +get_num_opt(struct archive_write *a, int *num, int high, int low, + const char *key, const char *value) +{ + const char *p = value; + int data = 0; + int neg = 0; + + if (p == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid value(empty) for option ``%s''", key); + return (ARCHIVE_FATAL); + } + if (*p == '-') { + neg = 1; + p++; + } + while (*p) { + if (*p >= '0' && *p <= '9') + data = data * 10 + *p - '0'; + else { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid value for option ``%s''", key); + return (ARCHIVE_FATAL); + } + if (data > high) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid value(over %d) for " + "option ``%s''", high, key); + return (ARCHIVE_FATAL); + } + if (data < low) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid value(under %d) for " + "option ``%s''", low, key); + return (ARCHIVE_FATAL); + } + p++; + } + if (neg) + data *= -1; + *num = data; + + return (ARCHIVE_OK); +} + +static int +iso9660_options(struct archive_write *a, const char *key, const char *value) +{ + struct iso9660 *iso9660 = a->format_data; + const char *p; + int r; + + switch (key[0]) { + case 'a': + if (strcmp(key, "abstract-file") == 0) { + r = get_str_opt(a, + &(iso9660->abstract_file_identifier), + ABSTRACT_FILE_SIZE, key, value); + iso9660->opt.abstract_file = r == ARCHIVE_OK; + return (r); + } + if (strcmp(key, "application-id") == 0) { + r = get_str_opt(a, + &(iso9660->application_identifier), + APPLICATION_IDENTIFIER_SIZE, key, value); + iso9660->opt.application_id = r == ARCHIVE_OK; + return (r); + } + if (strcmp(key, "allow-vernum") == 0) { + iso9660->opt.allow_vernum = value != NULL; + return (ARCHIVE_OK); + } + break; + case 'b': + if (strcmp(key, "biblio-file") == 0) { + r = get_str_opt(a, + &(iso9660->bibliographic_file_identifier), + BIBLIO_FILE_SIZE, key, value); + iso9660->opt.biblio_file = r == ARCHIVE_OK; + return (r); + } + if (strcmp(key, "boot") == 0) { + if (value == NULL) + iso9660->opt.boot = 0; + else { + iso9660->opt.boot = 1; + archive_strcpy( + &(iso9660->el_torito.boot_filename), + value); + } + return (ARCHIVE_OK); + } + if (strcmp(key, "boot-catalog") == 0) { + r = get_str_opt(a, + &(iso9660->el_torito.catalog_filename), + 1024, key, value); + iso9660->opt.boot_catalog = r == ARCHIVE_OK; + return (r); + } + if (strcmp(key, "boot-info-table") == 0) { + iso9660->opt.boot_info_table = value != NULL; + return (ARCHIVE_OK); + } + if (strcmp(key, "boot-load-seg") == 0) { + uint32_t seg; + + iso9660->opt.boot_load_seg = 0; + if (value == NULL) + goto invalid_value; + seg = 0; + p = value; + if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) + p += 2; + while (*p) { + if (seg) + seg <<= 4; + if (*p >= 'A' && *p <= 'F') + seg += *p - 'A' + 0x0a; + else if (*p >= 'a' && *p <= 'f') + seg += *p - 'a' + 0x0a; + else if (*p >= '0' && *p <= '9') + seg += *p - '0'; + else + goto invalid_value; + if (seg > 0xffff) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Invalid value(over 0xffff) for " + "option ``%s''", key); + return (ARCHIVE_FATAL); + } + p++; + } + iso9660->el_torito.boot_load_seg = (uint16_t)seg; + iso9660->opt.boot_load_seg = 1; + return (ARCHIVE_OK); + } + if (strcmp(key, "boot-load-size") == 0) { + int num = 0; + r = get_num_opt(a, &num, 0xffff, 1, key, value); + iso9660->opt.boot_load_size = r == ARCHIVE_OK; + if (r != ARCHIVE_OK) + return (ARCHIVE_FATAL); + iso9660->el_torito.boot_load_size = (uint16_t)num; + return (ARCHIVE_OK); + } + if (strcmp(key, "boot-type") == 0) { + if (value == NULL) + goto invalid_value; + if (strcmp(value, "no-emulation") == 0) + iso9660->opt.boot_type = OPT_BOOT_TYPE_NO_EMU; + else if (strcmp(value, "fd") == 0) + iso9660->opt.boot_type = OPT_BOOT_TYPE_FD; + else if (strcmp(value, "hard-disk") == 0) + iso9660->opt.boot_type = OPT_BOOT_TYPE_HARD_DISK; + else + goto invalid_value; + return (ARCHIVE_OK); + } + break; + case 'c': + if (strcmp(key, "compression-level") == 0) { +#ifdef HAVE_ZLIB_H + if (value == NULL || + !(value[0] >= '0' && value[0] <= '9') || + value[1] != '\0') + goto invalid_value; + iso9660->zisofs.compression_level = value[0] - '0'; + iso9660->opt.compression_level = 1; + return (ARCHIVE_OK); +#else + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Option ``%s'' " + "is not supported on this platform.", key); + return (ARCHIVE_FATAL); +#endif + } + if (strcmp(key, "copyright-file") == 0) { + r = get_str_opt(a, + &(iso9660->copyright_file_identifier), + COPYRIGHT_FILE_SIZE, key, value); + iso9660->opt.copyright_file = r == ARCHIVE_OK; + return (r); + } +#ifdef DEBUG + /* Specifies Volume creation date and time; + * year(4),month(2),day(2),hour(2),minute(2),second(2). + * e.g. "20090929033757" + */ + if (strcmp(key, "creation") == 0) { + struct tm tm; + char buf[5]; + + p = value; + if (p == NULL || strlen(p) < 14) + goto invalid_value; + memset(&tm, 0, sizeof(tm)); + memcpy(buf, p, 4); buf[4] = '\0'; p += 4; + tm.tm_year = strtol(buf, NULL, 10) - 1900; + memcpy(buf, p, 2); buf[2] = '\0'; p += 2; + tm.tm_mon = strtol(buf, NULL, 10) - 1; + memcpy(buf, p, 2); buf[2] = '\0'; p += 2; + tm.tm_mday = strtol(buf, NULL, 10); + memcpy(buf, p, 2); buf[2] = '\0'; p += 2; + tm.tm_hour = strtol(buf, NULL, 10); + memcpy(buf, p, 2); buf[2] = '\0'; p += 2; + tm.tm_min = strtol(buf, NULL, 10); + memcpy(buf, p, 2); buf[2] = '\0'; + tm.tm_sec = strtol(buf, NULL, 10); + iso9660->birth_time = mktime(&tm); + return (ARCHIVE_OK); + } +#endif + break; + case 'i': + if (strcmp(key, "iso-level") == 0) { + if (value != NULL && value[1] == '\0' && + (value[0] >= '1' && value[0] <= '4')) { + iso9660->opt.iso_level = value[0]-'0'; + return (ARCHIVE_OK); + } + goto invalid_value; + } + break; + case 'j': + if (strcmp(key, "joliet") == 0) { + if (value == NULL) + iso9660->opt.joliet = OPT_JOLIET_DISABLE; + else if (strcmp(value, "1") == 0) + iso9660->opt.joliet = OPT_JOLIET_ENABLE; + else if (strcmp(value, "long") == 0) + iso9660->opt.joliet = OPT_JOLIET_LONGNAME; + else + goto invalid_value; + return (ARCHIVE_OK); + } + break; + case 'l': + if (strcmp(key, "limit-depth") == 0) { + iso9660->opt.limit_depth = value != NULL; + return (ARCHIVE_OK); + } + if (strcmp(key, "limit-dirs") == 0) { + iso9660->opt.limit_dirs = value != NULL; + return (ARCHIVE_OK); + } + break; + case 'p': + if (strcmp(key, "pad") == 0) { + iso9660->opt.pad = value != NULL; + return (ARCHIVE_OK); + } + if (strcmp(key, "publisher") == 0) { + r = get_str_opt(a, + &(iso9660->publisher_identifier), + PUBLISHER_IDENTIFIER_SIZE, key, value); + iso9660->opt.publisher = r == ARCHIVE_OK; + return (r); + } + break; + case 'r': + if (strcmp(key, "rockridge") == 0 || + strcmp(key, "Rockridge") == 0) { + if (value == NULL) + iso9660->opt.rr = OPT_RR_DISABLED; + else if (strcmp(value, "1") == 0) + iso9660->opt.rr = OPT_RR_USEFUL; + else if (strcmp(value, "strict") == 0) + iso9660->opt.rr = OPT_RR_STRICT; + else if (strcmp(value, "useful") == 0) + iso9660->opt.rr = OPT_RR_USEFUL; + else + goto invalid_value; + return (ARCHIVE_OK); + } + break; + case 'v': + if (strcmp(key, "volume-id") == 0) { + r = get_str_opt(a, &(iso9660->volume_identifier), + VOLUME_IDENTIFIER_SIZE, key, value); + iso9660->opt.volume_id = r == ARCHIVE_OK; + return (r); + } + break; + case 'z': + if (strcmp(key, "zisofs") == 0) { + if (value == NULL) + iso9660->opt.zisofs = OPT_ZISOFS_DISABLED; + else { +#ifdef HAVE_ZLIB_H + iso9660->opt.zisofs = OPT_ZISOFS_DIRECT; +#else + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "``zisofs'' " + "is not supported on this platform."); + return (ARCHIVE_FATAL); +#endif + } + return (ARCHIVE_OK); + } + break; + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); + +invalid_value: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid value for option ``%s''", key); + return (ARCHIVE_FAILED); +} + +static int +iso9660_write_header(struct archive_write *a, struct archive_entry *entry) +{ + struct iso9660 *iso9660; + struct isofile *file; + struct isoent *isoent; + int r, ret = ARCHIVE_OK; + + iso9660 = a->format_data; + + iso9660->cur_file = NULL; + iso9660->bytes_remaining = 0; + iso9660->need_multi_extent = 0; + if (archive_entry_filetype(entry) == AE_IFLNK + && iso9660->opt.rr == OPT_RR_DISABLED) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Ignore symlink file."); + iso9660->cur_file = NULL; + return (ARCHIVE_WARN); + } + if (archive_entry_filetype(entry) == AE_IFREG && + archive_entry_size(entry) >= MULTI_EXTENT_SIZE) { + if (iso9660->opt.iso_level < 3) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Ignore over %lld bytes file. " + "This file too large.", + MULTI_EXTENT_SIZE); + iso9660->cur_file = NULL; + return (ARCHIVE_WARN); + } + iso9660->need_multi_extent = 1; + } + + file = isofile_new(a, entry); + if (file == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate data"); + return (ARCHIVE_FATAL); + } + r = isofile_gen_utility_names(a, file); + if (r < ARCHIVE_WARN) { + isofile_free(file); + return (r); + } + else if (r < ret) + ret = r; + + /* + * Ignore a path which looks like the top of directory name + * since we have already made the root directory of an ISO image. + */ + if (archive_strlen(&(file->parentdir)) == 0 && + archive_strlen(&(file->basename)) == 0) { + isofile_free(file); + return (r); + } + + isofile_add_entry(iso9660, file); + isoent = isoent_new(file); + if (isoent == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate data"); + return (ARCHIVE_FATAL); + } + if (isoent->file->dircnt > iso9660->dircnt_max) + iso9660->dircnt_max = isoent->file->dircnt; + + /* Add the current file into tree */ + r = isoent_tree(a, &isoent); + if (r != ARCHIVE_OK) + return (r); + + /* If there is the same file in tree and + * the current file is older than the file in tree. + * So we don't need the current file data anymore. */ + if (isoent->file != file) + return (ARCHIVE_OK); + + /* Non regular files contents are unneeded to be saved to + * temporary files. */ + if (archive_entry_filetype(file->entry) != AE_IFREG) + return (ret); + + /* + * Set the current file to cur_file to read its contents. + */ + iso9660->cur_file = file; + + if (archive_entry_nlink(file->entry) > 1) { + r = isofile_register_hardlink(a, file); + if (r != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + + /* + * Prepare to save the contents of the file. + */ + if (iso9660->temp_fd < 0) { + iso9660->temp_fd = __archive_mktemp(NULL); + if (iso9660->temp_fd < 0) { + archive_set_error(&a->archive, errno, + "Couldn't create temporary file"); + return (ARCHIVE_FATAL); + } + } + + /* Save an offset of current file in temporary file. */ + file->content.offset_of_temp = wb_offset(a); + file->cur_content = &(file->content); + r = zisofs_init(a, file); + if (r < ret) + ret = r; + iso9660->bytes_remaining = archive_entry_size(file->entry); + + return (ret); +} + +static int +write_to_temp(struct archive_write *a, const void *buff, size_t s) +{ + struct iso9660 *iso9660 = a->format_data; + ssize_t written; + const unsigned char *b; + + b = (const unsigned char *)buff; + while (s) { + written = write(iso9660->temp_fd, b, s); + if (written < 0) { + archive_set_error(&a->archive, errno, + "Can't write to temporary file"); + return (ARCHIVE_FATAL); + } + s -= written; + b += written; + } + return (ARCHIVE_OK); +} + +static int +wb_write_to_temp(struct archive_write *a, const void *buff, size_t s) +{ + const char *xp = buff; + size_t xs = s; + + /* + * If a written data size is big enough to use system-call + * and there is no waiting data, this calls write_to_temp() in + * order to reduce a extra memory copy. + */ + if (wb_remaining(a) == wb_buffmax() && s > (1024 * 16)) { + struct iso9660 *iso9660 = (struct iso9660 *)a->format_data; + xs = s % LOGICAL_BLOCK_SIZE; + iso9660->wbuff_offset += s - xs; + if (write_to_temp(a, buff, s - xs) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + if (xs == 0) + return (ARCHIVE_OK); + xp += s - xs; + } + + while (xs) { + size_t size = xs; + if (size > wb_remaining(a)) + size = wb_remaining(a); + memcpy(wb_buffptr(a), xp, size); + if (wb_consume(a, size) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + xs -= size; + xp += size; + } + return (ARCHIVE_OK); +} + +static int +wb_write_padding_to_temp(struct archive_write *a, int64_t csize) +{ + size_t ns; + int ret; + + ns = (size_t)(csize % LOGICAL_BLOCK_SIZE); + if (ns != 0) + ret = write_null(a, LOGICAL_BLOCK_SIZE - ns); + else + ret = ARCHIVE_OK; + return (ret); +} + +static ssize_t +write_iso9660_data(struct archive_write *a, const void *buff, size_t s) +{ + struct iso9660 *iso9660 = a->format_data; + size_t ws; + + if (iso9660->temp_fd < 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Couldn't create temporary file"); + return (ARCHIVE_FATAL); + } + + ws = s; + if (iso9660->need_multi_extent && + (iso9660->cur_file->cur_content->size + ws) >= + (MULTI_EXTENT_SIZE - LOGICAL_BLOCK_SIZE)) { + struct content *con; + size_t ts; + + ts = (size_t)(MULTI_EXTENT_SIZE - LOGICAL_BLOCK_SIZE - + iso9660->cur_file->cur_content->size); + + if (iso9660->zisofs.detect_magic) + zisofs_detect_magic(a, buff, ts); + + if (iso9660->zisofs.making) { + if (zisofs_write_to_temp(a, buff, ts) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } else { + if (wb_write_to_temp(a, buff, ts) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + iso9660->cur_file->cur_content->size += ts; + } + + /* Write padding. */ + if (wb_write_padding_to_temp(a, + iso9660->cur_file->cur_content->size) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Compute the logical block number. */ + iso9660->cur_file->cur_content->blocks = (int) + ((iso9660->cur_file->cur_content->size + + LOGICAL_BLOCK_SIZE -1) >> LOGICAL_BLOCK_BITS); + + /* + * Make next extent. + */ + ws -= ts; + buff = (const void *)(((const unsigned char *)buff) + ts); + /* Make a content for next extent. */ + con = calloc(1, sizeof(*con)); + if (con == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate content data"); + return (ARCHIVE_FATAL); + } + con->offset_of_temp = wb_offset(a); + iso9660->cur_file->cur_content->next = con; + iso9660->cur_file->cur_content = con; +#ifdef HAVE_ZLIB_H + iso9660->zisofs.block_offset = 0; +#endif + } + + if (iso9660->zisofs.detect_magic) + zisofs_detect_magic(a, buff, ws); + + if (iso9660->zisofs.making) { + if (zisofs_write_to_temp(a, buff, ws) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } else { + if (wb_write_to_temp(a, buff, ws) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + iso9660->cur_file->cur_content->size += ws; + } + + return (s); +} + +static ssize_t +iso9660_write_data(struct archive_write *a, const void *buff, size_t s) +{ + struct iso9660 *iso9660 = a->format_data; + ssize_t r; + + if (iso9660->cur_file == NULL) + return (0); + if (archive_entry_filetype(iso9660->cur_file->entry) != AE_IFREG) + return (0); + if (s > iso9660->bytes_remaining) + s = (size_t)iso9660->bytes_remaining; + if (s == 0) + return (0); + + r = write_iso9660_data(a, buff, s); + if (r > 0) + iso9660->bytes_remaining -= r; + return (r); +} + +static int +iso9660_finish_entry(struct archive_write *a) +{ + struct iso9660 *iso9660 = a->format_data; + + if (iso9660->cur_file == NULL) + return (ARCHIVE_OK); + if (archive_entry_filetype(iso9660->cur_file->entry) != AE_IFREG) + return (ARCHIVE_OK); + if (iso9660->cur_file->content.size == 0) + return (ARCHIVE_OK); + + /* If there are unwritten data, write null data instead. */ + while (iso9660->bytes_remaining > 0) { + size_t s; + + s = (iso9660->bytes_remaining > a->null_length)? + a->null_length: (size_t)iso9660->bytes_remaining; + if (write_iso9660_data(a, a->nulls, s) < 0) + return (ARCHIVE_FATAL); + iso9660->bytes_remaining -= s; + } + + if (iso9660->zisofs.making && zisofs_finish_entry(a) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Write padding. */ + if (wb_write_padding_to_temp(a, iso9660->cur_file->cur_content->size) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Compute the logical block number. */ + iso9660->cur_file->cur_content->blocks = (int) + ((iso9660->cur_file->cur_content->size + + LOGICAL_BLOCK_SIZE -1) >> LOGICAL_BLOCK_BITS); + + /* Add the current file to data file list. */ + isofile_add_data_file(iso9660, iso9660->cur_file); + + return (ARCHIVE_OK); +} + +static int +iso9660_close(struct archive_write *a) +{ + struct iso9660 *iso9660; + int ret, blocks; + + iso9660 = a->format_data; + + /* + * Write remaining data out to the temporary file. + */ + if (wb_remaining(a) > 0) { + ret = wb_write_out(a); + if (ret < 0) + return (ret); + } + + /* + * Preparations... + */ +#ifdef DEBUG + if (iso9660->birth_time == 0) +#endif + time(&(iso9660->birth_time)); + + /* + * Prepare a bootable ISO image. + */ + if (iso9660->opt.boot) { + /* Find out the boot file entry. */ + ret = isoent_find_out_boot_file(a, iso9660->primary.rootent); + if (ret < 0) + return (ret); + /* Reconvert the boot file from zisofs'ed form to + * plain form. */ + ret = zisofs_rewind_boot_file(a); + if (ret < 0) + return (ret); + /* Write remaining data out to the temporary file. */ + if (wb_remaining(a) > 0) { + ret = wb_write_out(a); + if (ret < 0) + return (ret); + } + /* Create the boot catalog. */ + ret = isoent_create_boot_catalog(a, iso9660->primary.rootent); + if (ret < 0) + return (ret); + } + + /* + * Prepare joliet extensions. + */ + if (iso9660->opt.joliet) { + /* Make a new tree for joliet. */ + ret = isoent_clone_tree(a, &(iso9660->joliet.rootent), + iso9660->primary.rootent); + if (ret < 0) + return (ret); + /* Make sure we have UTF-16BE converters. + * if there is no file entry, converters are still + * uninitialized. */ + if (iso9660->sconv_to_utf16be == NULL) { + iso9660->sconv_to_utf16be = + archive_string_conversion_to_charset( + &(a->archive), "UTF-16BE", 1); + if (iso9660->sconv_to_utf16be == NULL) + /* Couldn't allocate memory */ + return (ARCHIVE_FATAL); + iso9660->sconv_from_utf16be = + archive_string_conversion_from_charset( + &(a->archive), "UTF-16BE", 1); + if (iso9660->sconv_from_utf16be == NULL) + /* Couldn't allocate memory */ + return (ARCHIVE_FATAL); + } + } + + /* + * Make Path Tables. + */ + ret = isoent_make_path_table(a); + if (ret < 0) + return (ret); + + /* + * Calculate a total volume size and setup all locations of + * contents of an iso9660 image. + */ + blocks = SYSTEM_AREA_BLOCK + + PRIMARY_VOLUME_DESCRIPTOR_BLOCK + + VOLUME_DESCRIPTOR_SET_TERMINATOR_BLOCK + + NON_ISO_FILE_SYSTEM_INFORMATION_BLOCK; + if (iso9660->opt.boot) + blocks += BOOT_RECORD_DESCRIPTOR_BLOCK; + if (iso9660->opt.joliet) + blocks += SUPPLEMENTARY_VOLUME_DESCRIPTOR_BLOCK; + if (iso9660->opt.iso_level == 4) + blocks += SUPPLEMENTARY_VOLUME_DESCRIPTOR_BLOCK; + + /* Setup the locations of Path Table. */ + iso9660->primary.location_type_L_path_table = blocks; + blocks += iso9660->primary.path_table_block; + iso9660->primary.location_type_M_path_table = blocks; + blocks += iso9660->primary.path_table_block; + if (iso9660->opt.joliet) { + iso9660->joliet.location_type_L_path_table = blocks; + blocks += iso9660->joliet.path_table_block; + iso9660->joliet.location_type_M_path_table = blocks; + blocks += iso9660->joliet.path_table_block; + } + + /* Setup the locations of directories. */ + isoent_setup_directory_location(iso9660, blocks, + &(iso9660->primary)); + blocks += iso9660->primary.total_dir_block; + if (iso9660->opt.joliet) { + isoent_setup_directory_location(iso9660, blocks, + &(iso9660->joliet)); + blocks += iso9660->joliet.total_dir_block; + } + + if (iso9660->opt.rr) { + iso9660->location_rrip_er = blocks; + blocks += RRIP_ER_BLOCK; + } + + /* Setup the locations of all file contents. */ + isoent_setup_file_location(iso9660, blocks); + blocks += iso9660->total_file_block; + if (iso9660->opt.boot && iso9660->opt.boot_info_table) { + ret = setup_boot_information(a); + if (ret < 0) + return (ret); + } + + /* Now we have a total volume size. */ + iso9660->volume_space_size = blocks; + if (iso9660->opt.pad) + iso9660->volume_space_size += PADDING_BLOCK; + iso9660->volume_sequence_number = 1; + + + /* + * Write an ISO 9660 image. + */ + + /* Switch to start using wbuff as file buffer. */ + iso9660->wbuff_remaining = wb_buffmax(); + iso9660->wbuff_type = WB_TO_STREAM; + iso9660->wbuff_offset = 0; + iso9660->wbuff_written = 0; + iso9660->wbuff_tail = 0; + + /* Write The System Area */ + ret = write_null(a, SYSTEM_AREA_BLOCK * LOGICAL_BLOCK_SIZE); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Write Primary Volume Descriptor */ + ret = write_VD(a, &(iso9660->primary)); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + if (iso9660->opt.boot) { + /* Write Boot Record Volume Descriptor */ + ret = write_VD_boot_record(a); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + + if (iso9660->opt.iso_level == 4) { + /* Write Enhanced Volume Descriptor */ + iso9660->primary.vdd_type = VDD_ENHANCED; + ret = write_VD(a, &(iso9660->primary)); + iso9660->primary.vdd_type = VDD_PRIMARY; + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + + if (iso9660->opt.joliet) { + ret = write_VD(a, &(iso9660->joliet)); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + + /* Write Volume Descriptor Set Terminator */ + ret = write_VD_terminator(a); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Write Non-ISO File System Information */ + ret = write_information_block(a); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Write Type L Path Table */ + ret = write_path_table(a, 0, &(iso9660->primary)); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Write Type M Path Table */ + ret = write_path_table(a, 1, &(iso9660->primary)); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + if (iso9660->opt.joliet) { + /* Write Type L Path Table */ + ret = write_path_table(a, 0, &(iso9660->joliet)); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Write Type M Path Table */ + ret = write_path_table(a, 1, &(iso9660->joliet)); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + + /* Write Directory Descriptors */ + ret = write_directory_descriptors(a, &(iso9660->primary)); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + if (iso9660->opt.joliet) { + ret = write_directory_descriptors(a, &(iso9660->joliet)); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + + if (iso9660->opt.rr) { + /* Write Rockridge ER(Extensions Reference) */ + ret = write_rr_ER(a); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + + /* Write File Descriptors */ + ret = write_file_descriptors(a); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Write Padding */ + if (iso9660->opt.pad) { + ret = write_null(a, PADDING_BLOCK * LOGICAL_BLOCK_SIZE); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + + if (iso9660->directories_too_deep != NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "%s: Directories too deep.", + archive_entry_pathname( + iso9660->directories_too_deep->file->entry)); + return (ARCHIVE_WARN); + } + + /* Write remaining data out. */ + ret = wb_write_out(a); + + return (ret); +} + +static int +iso9660_free(struct archive_write *a) +{ + struct iso9660 *iso9660; + int i, ret; + + iso9660 = a->format_data; + + /* Close the temporary file. */ + if (iso9660->temp_fd >= 0) + close(iso9660->temp_fd); + + /* Free some stuff for zisofs operations. */ + ret = zisofs_free(a); + + /* Remove directory entries in tree which includes file entries. */ + isoent_free_all(iso9660->primary.rootent); + for (i = 0; i < iso9660->primary.max_depth; i++) + free(iso9660->primary.pathtbl[i].sorted); + free(iso9660->primary.pathtbl); + + if (iso9660->opt.joliet) { + isoent_free_all(iso9660->joliet.rootent); + for (i = 0; i < iso9660->joliet.max_depth; i++) + free(iso9660->joliet.pathtbl[i].sorted); + free(iso9660->joliet.pathtbl); + } + + /* Remove isofile entries. */ + isofile_free_all_entries(iso9660); + isofile_free_hardlinks(iso9660); + + archive_string_free(&(iso9660->cur_dirstr)); + archive_string_free(&(iso9660->volume_identifier)); + archive_string_free(&(iso9660->publisher_identifier)); + archive_string_free(&(iso9660->data_preparer_identifier)); + archive_string_free(&(iso9660->application_identifier)); + archive_string_free(&(iso9660->copyright_file_identifier)); + archive_string_free(&(iso9660->abstract_file_identifier)); + archive_string_free(&(iso9660->bibliographic_file_identifier)); + archive_string_free(&(iso9660->el_torito.catalog_filename)); + archive_string_free(&(iso9660->el_torito.boot_filename)); + archive_string_free(&(iso9660->el_torito.id)); + archive_string_free(&(iso9660->utf16be)); + archive_string_free(&(iso9660->mbs)); + + free(iso9660); + a->format_data = NULL; + + return (ret); +} + +/* + * Get the System Identifier + */ +static void +get_system_identitier(char *system_id, size_t size) +{ +#if defined(HAVE_SYS_UTSNAME_H) + struct utsname u; + + uname(&u); + strncpy(system_id, u.sysname, size-1); + system_id[size-1] = '\0'; +#elif defined(_WIN32) && !defined(__CYGWIN__) + strncpy(system_id, "Windows", size-1); + system_id[size-1] = '\0'; +#else +#error no way to get the system identifier on your platform. +#endif +} + +static void +set_str(unsigned char *p, const char *s, size_t l, char f, const char *map) +{ + unsigned char c; + + if (s == NULL) + s = ""; + while ((c = *s++) != 0 && l > 0) { + if (c >= 0x80 || map[c] == 0) + { + /* illegal character */ + if (c >= 'a' && c <= 'z') { + /* convert c from a-z to A-Z */ + c -= 0x20; + } else + c = 0x5f; + } + *p++ = c; + l--; + } + /* If l isn't zero, fill p buffer by the character + * which indicated by f. */ + if (l > 0) + memset(p , f, l); +} + +static inline int +joliet_allowed_char(unsigned char high, unsigned char low) +{ + int utf16 = (high << 8) | low; + + if (utf16 <= 0x001F) + return (0); + + switch (utf16) { + case 0x002A: /* '*' */ + case 0x002F: /* '/' */ + case 0x003A: /* ':' */ + case 0x003B: /* ';' */ + case 0x003F: /* '?' */ + case 0x005C: /* '\' */ + return (0);/* Not allowed. */ + } + return (1); +} + +static int +set_str_utf16be(struct archive_write *a, unsigned char *p, const char *s, + size_t l, uint16_t uf, enum vdc vdc) +{ + size_t size, i; + int onepad; + + if (s == NULL) + s = ""; + if (l & 0x01) { + onepad = 1; + l &= ~1; + } else + onepad = 0; + if (vdc == VDC_UCS2) { + struct iso9660 *iso9660 = a->format_data; + if (archive_strncpy_l(&iso9660->utf16be, s, strlen(s), + iso9660->sconv_to_utf16be) != 0 && errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for UTF-16BE"); + return (ARCHIVE_FATAL); + } + size = iso9660->utf16be.length; + if (size > l) + size = l; + memcpy(p, iso9660->utf16be.s, size); + } else { + const uint16_t *u16 = (const uint16_t *)s; + + size = 0; + while (*u16++) + size += 2; + if (size > l) + size = l; + memcpy(p, s, size); + } + for (i = 0; i < size; i += 2, p += 2) { + if (!joliet_allowed_char(p[0], p[1])) + archive_be16enc(p, 0x005F);/* '_' */ + } + l -= size; + while (l > 0) { + archive_be16enc(p, uf); + p += 2; + l -= 2; + } + if (onepad) + *p = 0; + return (ARCHIVE_OK); +} + +static const char a_characters_map[0x80] = { +/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 00-0F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 10-1F */ + 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20-2F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30-3F */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40-4F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,/* 50-5F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 60-6F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 70-7F */ +}; + +static const char a1_characters_map[0x80] = { +/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 00-0F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 10-1F */ + 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20-2F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30-3F */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40-4F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,/* 50-5F */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60-6F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,/* 70-7F */ +}; + +static const char d_characters_map[0x80] = { +/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 00-0F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 10-1F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 20-2F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,/* 30-3F */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40-4F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,/* 50-5F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 60-6F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 70-7F */ +}; + +static const char d1_characters_map[0x80] = { +/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 00-0F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 10-1F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 20-2F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,/* 30-3F */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40-4F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,/* 50-5F */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60-6F */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,/* 70-7F */ +}; + +static int +set_str_a_characters_bp(struct archive_write *a, unsigned char *bp, + int from, int to, const char *s, enum vdc vdc) +{ + int r; + + switch (vdc) { + case VDC_STD: + set_str(bp+from, s, to - from + 1, 0x20, + a_characters_map); + r = ARCHIVE_OK; + break; + case VDC_LOWERCASE: + set_str(bp+from, s, to - from + 1, 0x20, + a1_characters_map); + r = ARCHIVE_OK; + break; + case VDC_UCS2: + case VDC_UCS2_DIRECT: + r = set_str_utf16be(a, bp+from, s, to - from + 1, + 0x0020, vdc); + break; + default: + r = ARCHIVE_FATAL; + } + return (r); +} + +static int +set_str_d_characters_bp(struct archive_write *a, unsigned char *bp, + int from, int to, const char *s, enum vdc vdc) +{ + int r; + + switch (vdc) { + case VDC_STD: + set_str(bp+from, s, to - from + 1, 0x20, + d_characters_map); + r = ARCHIVE_OK; + break; + case VDC_LOWERCASE: + set_str(bp+from, s, to - from + 1, 0x20, + d1_characters_map); + r = ARCHIVE_OK; + break; + case VDC_UCS2: + case VDC_UCS2_DIRECT: + r = set_str_utf16be(a, bp+from, s, to - from + 1, + 0x0020, vdc); + break; + default: + r = ARCHIVE_FATAL; + } + return (r); +} + +static void +set_VD_bp(unsigned char *bp, enum VD_type type, unsigned char ver) +{ + + /* Volume Descriptor Type */ + bp[1] = (unsigned char)type; + /* Standard Identifier */ + memcpy(bp + 2, "CD001", 5); + /* Volume Descriptor Version */ + bp[7] = ver; +} + +static inline void +set_unused_field_bp(unsigned char *bp, int from, int to) +{ + memset(bp + from, 0, to - from + 1); +} + +/* + * 8-bit unsigned numerical values. + * ISO9660 Standard 7.1.1 + */ +static inline void +set_num_711(unsigned char *p, unsigned char value) +{ + *p = value; +} + +/* + * 8-bit signed numerical values. + * ISO9660 Standard 7.1.2 + */ +static inline void +set_num_712(unsigned char *p, char value) +{ + *((char *)p) = value; +} + +/* + * Least significant byte first. + * ISO9660 Standard 7.2.1 + */ +static inline void +set_num_721(unsigned char *p, uint16_t value) +{ + archive_le16enc(p, value); +} + +/* + * Most significant byte first. + * ISO9660 Standard 7.2.2 + */ +static inline void +set_num_722(unsigned char *p, uint16_t value) +{ + archive_be16enc(p, value); +} + +/* + * Both-byte orders. + * ISO9660 Standard 7.2.3 + */ +static void +set_num_723(unsigned char *p, uint16_t value) +{ + archive_le16enc(p, value); + archive_be16enc(p+2, value); +} + +/* + * Least significant byte first. + * ISO9660 Standard 7.3.1 + */ +static inline void +set_num_731(unsigned char *p, uint32_t value) +{ + archive_le32enc(p, value); +} + +/* + * Most significant byte first. + * ISO9660 Standard 7.3.2 + */ +static inline void +set_num_732(unsigned char *p, uint32_t value) +{ + archive_be32enc(p, value); +} + +/* + * Both-byte orders. + * ISO9660 Standard 7.3.3 + */ +static inline void +set_num_733(unsigned char *p, uint32_t value) +{ + archive_le32enc(p, value); + archive_be32enc(p+4, value); +} + +static void +set_digit(unsigned char *p, size_t s, int value) +{ + + while (s--) { + p[s] = '0' + (value % 10); + value /= 10; + } +} + +#if defined(HAVE_STRUCT_TM_TM_GMTOFF) +#define get_gmoffset(tm) ((tm)->tm_gmtoff) +#elif defined(HAVE_STRUCT_TM___TM_GMTOFF) +#define get_gmoffset(tm) ((tm)->__tm_gmtoff) +#else +static long +get_gmoffset(struct tm *tm) +{ + long offset; + +#if defined(HAVE__GET_TIMEZONE) + _get_timezone(&offset); +#elif defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) + offset = _timezone; +#else + offset = timezone; +#endif + offset *= -1; + if (tm->tm_isdst) + offset += 3600; + return (offset); +} +#endif + +static void +get_tmfromtime(struct tm *tm, time_t *t) +{ +#if HAVE_LOCALTIME_R + tzset(); + localtime_r(t, tm); +#elif HAVE__LOCALTIME64_S + __time64_t tmp_t = (__time64_t) *t; //time_t may be shorter than 64 bits + _localtime64_s(tm, &tmp_t); +#else + memcpy(tm, localtime(t), sizeof(*tm)); +#endif +} + +/* + * Date and Time Format. + * ISO9660 Standard 8.4.26.1 + */ +static void +set_date_time(unsigned char *p, time_t t) +{ + struct tm tm; + + get_tmfromtime(&tm, &t); + set_digit(p, 4, tm.tm_year + 1900); + set_digit(p+4, 2, tm.tm_mon + 1); + set_digit(p+6, 2, tm.tm_mday); + set_digit(p+8, 2, tm.tm_hour); + set_digit(p+10, 2, tm.tm_min); + set_digit(p+12, 2, tm.tm_sec); + set_digit(p+14, 2, 0); + set_num_712(p+16, (char)(get_gmoffset(&tm)/(60*15))); +} + +static void +set_date_time_null(unsigned char *p) +{ + memset(p, (int)'0', 16); + p[16] = 0; +} + +static void +set_time_915(unsigned char *p, time_t t) +{ + struct tm tm; + + get_tmfromtime(&tm, &t); + set_num_711(p+0, tm.tm_year); + set_num_711(p+1, tm.tm_mon+1); + set_num_711(p+2, tm.tm_mday); + set_num_711(p+3, tm.tm_hour); + set_num_711(p+4, tm.tm_min); + set_num_711(p+5, tm.tm_sec); + set_num_712(p+6, (char)(get_gmoffset(&tm)/(60*15))); +} + + +/* + * Write SUSP "CE" System Use Entry. + */ +static int +set_SUSP_CE(unsigned char *p, int location, int offset, int size) +{ + unsigned char *bp = p -1; + /* Extend the System Use Area + * "CE" Format: + * len ver + * +----+----+----+----+-----------+-----------+ + * | 'C'| 'E'| 1C | 01 | LOCATION1 | LOCATION2 | + * +----+----+----+----+-----------+-----------+ + * 0 1 2 3 4 12 20 + * +-----------+ + * | LOCATION3 | + * +-----------+ + * 20 28 + * LOCATION1 : Location of Continuation of System Use Area. + * LOCATION2 : Offset to Start of Continuation. + * LOCATION3 : Length of the Continuation. + */ + + bp[1] = 'C'; + bp[2] = 'E'; + bp[3] = RR_CE_SIZE; /* length */ + bp[4] = 1; /* version */ + set_num_733(bp+5, location); + set_num_733(bp+13, offset); + set_num_733(bp+21, size); + return (RR_CE_SIZE); +} + +/* + * The functions, which names are beginning with extra_, are used to + * control extra records. + * The maximum size of a Directory Record is 254. When a filename is + * very long, all of RRIP data of a file won't stored to the Directory + * Record and so remaining RRIP data store to an extra record instead. + */ +static unsigned char * +extra_open_record(unsigned char *bp, int dr_len, struct isoent *isoent, + struct ctl_extr_rec *ctl) +{ + ctl->bp = bp; + if (bp != NULL) + bp += dr_len; + ctl->use_extr = 0; + ctl->isoent = isoent; + ctl->ce_ptr = NULL; + ctl->cur_len = ctl->dr_len = dr_len; + ctl->limit = DR_LIMIT; + + return (bp); +} + +static void +extra_close_record(struct ctl_extr_rec *ctl, int ce_size) +{ + int padding = 0; + + if (ce_size > 0) + extra_tell_used_size(ctl, ce_size); + /* Padding. */ + if (ctl->cur_len & 0x01) { + ctl->cur_len++; + if (ctl->bp != NULL) + ctl->bp[ctl->cur_len] = 0; + padding = 1; + } + if (ctl->use_extr) { + if (ctl->ce_ptr != NULL) + set_SUSP_CE(ctl->ce_ptr, ctl->extr_loc, + ctl->extr_off, ctl->cur_len - padding); + } else + ctl->dr_len = ctl->cur_len; +} + +#define extra_space(ctl) ((ctl)->limit - (ctl)->cur_len) + +static unsigned char * +extra_next_record(struct ctl_extr_rec *ctl, int length) +{ + int cur_len = ctl->cur_len;/* save cur_len */ + + /* Close the current extra record or Directory Record. */ + extra_close_record(ctl, RR_CE_SIZE); + + /* Get a next extra record. */ + ctl->use_extr = 1; + if (ctl->bp != NULL) { + /* Storing data into an extra record. */ + unsigned char *p; + + /* Save the pointer where a CE extension will be + * stored to. */ + ctl->ce_ptr = &ctl->bp[cur_len+1]; + p = extra_get_record(ctl->isoent, + &ctl->limit, &ctl->extr_off, &ctl->extr_loc); + ctl->bp = p - 1;/* the base of bp offset is 1. */ + } else + /* Calculating the size of an extra record. */ + (void)extra_get_record(ctl->isoent, + &ctl->limit, NULL, NULL); + ctl->cur_len = 0; + /* Check if an extra record is almost full. + * If so, get a next one. */ + if (extra_space(ctl) < length) + (void)extra_next_record(ctl, length); + + return (ctl->bp); +} + +static inline struct extr_rec * +extra_last_record(struct isoent *isoent) +{ + if (isoent->extr_rec_list.first == NULL) + return (NULL); + return ((struct extr_rec *)(void *) + ((char *)(isoent->extr_rec_list.last) + - offsetof(struct extr_rec, next))); +} + +static unsigned char * +extra_get_record(struct isoent *isoent, int *space, int *off, int *loc) +{ + struct extr_rec *rec; + + isoent = isoent->parent; + if (off != NULL) { + /* Storing data into an extra record. */ + rec = isoent->extr_rec_list.current; + if (DR_SAFETY > LOGICAL_BLOCK_SIZE - rec->offset) + rec = rec->next; + } else { + /* Calculating the size of an extra record. */ + rec = extra_last_record(isoent); + if (rec == NULL || + DR_SAFETY > LOGICAL_BLOCK_SIZE - rec->offset) { + rec = malloc(sizeof(*rec)); + if (rec == NULL) + return (NULL); + rec->location = 0; + rec->offset = 0; + /* Insert `rec` into the tail of isoent->extr_rec_list */ + rec->next = NULL; + /* + * Note: testing isoent->extr_rec_list.last == NULL + * here is really unneeded since it has been already + * initialized at isoent_new function but Clang Static + * Analyzer claims that it is dereference of null + * pointer. + */ + if (isoent->extr_rec_list.last == NULL) + isoent->extr_rec_list.last = + &(isoent->extr_rec_list.first); + *isoent->extr_rec_list.last = rec; + isoent->extr_rec_list.last = &(rec->next); + } + } + *space = LOGICAL_BLOCK_SIZE - rec->offset - DR_SAFETY; + if (*space & 0x01) + *space -= 1;/* Keep padding space. */ + if (off != NULL) + *off = rec->offset; + if (loc != NULL) + *loc = rec->location; + isoent->extr_rec_list.current = rec; + + return (&rec->buf[rec->offset]); +} + +static void +extra_tell_used_size(struct ctl_extr_rec *ctl, int size) +{ + struct isoent *isoent; + struct extr_rec *rec; + + if (ctl->use_extr) { + isoent = ctl->isoent->parent; + rec = isoent->extr_rec_list.current; + if (rec != NULL) + rec->offset += size; + } + ctl->cur_len += size; +} + +static int +extra_setup_location(struct isoent *isoent, int location) +{ + struct extr_rec *rec; + int cnt; + + cnt = 0; + rec = isoent->extr_rec_list.first; + isoent->extr_rec_list.current = rec; + while (rec) { + cnt++; + rec->location = location++; + rec->offset = 0; + rec = rec->next; + } + return (cnt); +} + +/* + * Create the RRIP entries. + */ +static int +set_directory_record_rr(unsigned char *bp, int dr_len, + struct isoent *isoent, struct iso9660 *iso9660, enum dir_rec_type t) +{ + /* Flags(BP 5) of the Rockridge "RR" System Use Field */ + unsigned char rr_flag; +#define RR_USE_PX 0x01 +#define RR_USE_PN 0x02 +#define RR_USE_SL 0x04 +#define RR_USE_NM 0x08 +#define RR_USE_CL 0x10 +#define RR_USE_PL 0x20 +#define RR_USE_RE 0x40 +#define RR_USE_TF 0x80 + int length; + struct ctl_extr_rec ctl; + struct isoent *rr_parent, *pxent; + struct isofile *file; + + bp = extra_open_record(bp, dr_len, isoent, &ctl); + + if (t == DIR_REC_PARENT) { + rr_parent = isoent->rr_parent; + pxent = isoent->parent; + if (rr_parent != NULL) + isoent = rr_parent; + else + isoent = isoent->parent; + } else { + rr_parent = NULL; + pxent = isoent; + } + file = isoent->file; + + if (t != DIR_REC_NORMAL) { + rr_flag = RR_USE_PX | RR_USE_TF; + if (rr_parent != NULL) + rr_flag |= RR_USE_PL; + } else { + rr_flag = RR_USE_PX | RR_USE_NM | RR_USE_TF; + if (archive_entry_filetype(file->entry) == AE_IFLNK) + rr_flag |= RR_USE_SL; + if (isoent->rr_parent != NULL) + rr_flag |= RR_USE_RE; + if (isoent->rr_child != NULL) + rr_flag |= RR_USE_CL; + if (archive_entry_filetype(file->entry) == AE_IFCHR || + archive_entry_filetype(file->entry) == AE_IFBLK) + rr_flag |= RR_USE_PN; +#ifdef COMPAT_MKISOFS + /* + * mkisofs 2.01.01a63 records "RE" extension to + * the entry of "rr_moved" directory. + * I don't understand this behavior. + */ + if (isoent->virtual && + isoent->parent == iso9660->primary.rootent && + strcmp(isoent->file->basename.s, "rr_moved") == 0) + rr_flag |= RR_USE_RE; +#endif + } + + /* Write "SP" System Use Entry. */ + if (t == DIR_REC_SELF && isoent == isoent->parent) { + length = 7; + if (bp != NULL) { + bp[1] = 'S'; + bp[2] = 'P'; + bp[3] = length; + bp[4] = 1; /* version */ + bp[5] = 0xBE; /* Check Byte */ + bp[6] = 0xEF; /* Check Byte */ + bp[7] = 0; + bp += length; + } + extra_tell_used_size(&ctl, length); + } + + /* Write "RR" System Use Entry. */ + length = 5; + if (extra_space(&ctl) < length) + bp = extra_next_record(&ctl, length); + if (bp != NULL) { + bp[1] = 'R'; + bp[2] = 'R'; + bp[3] = length; + bp[4] = 1; /* version */ + bp[5] = rr_flag; + bp += length; + } + extra_tell_used_size(&ctl, length); + + /* Write "NM" System Use Entry. */ + if (rr_flag & RR_USE_NM) { + /* + * "NM" Format: + * e.g. a basename is 'foo' + * len ver flg + * +----+----+----+----+----+----+----+----+ + * | 'N'| 'M'| 08 | 01 | 00 | 'f'| 'o'| 'o'| + * +----+----+----+----+----+----+----+----+ + * <----------------- len -----------------> + */ + size_t nmlen = file->basename.length; + const char *nm = file->basename.s; + size_t nmmax; + + if (extra_space(&ctl) < 6) + bp = extra_next_record(&ctl, 6); + if (bp != NULL) { + bp[1] = 'N'; + bp[2] = 'M'; + bp[4] = 1; /* version */ + } + nmmax = extra_space(&ctl); + if (nmmax > 0xff) + nmmax = 0xff; + while (nmlen + 5 > nmmax) { + length = (int)nmmax; + if (bp != NULL) { + bp[3] = length; + bp[5] = 0x01;/* Alternate Name continues + * in next "NM" field */ + memcpy(bp+6, nm, length - 5); + bp += length; + } + nmlen -= length - 5; + nm += length - 5; + extra_tell_used_size(&ctl, length); + if (extra_space(&ctl) < 6) { + bp = extra_next_record(&ctl, 6); + nmmax = extra_space(&ctl); + if (nmmax > 0xff) + nmmax = 0xff; + } + if (bp != NULL) { + bp[1] = 'N'; + bp[2] = 'M'; + bp[4] = 1; /* version */ + } + } + length = 5 + (int)nmlen; + if (bp != NULL) { + bp[3] = length; + bp[5] = 0; + memcpy(bp+6, nm, nmlen); + bp += length; + } + extra_tell_used_size(&ctl, length); + } + + /* Write "PX" System Use Entry. */ + if (rr_flag & RR_USE_PX) { + /* + * "PX" Format: + * len ver + * +----+----+----+----+-----------+-----------+ + * | 'P'| 'X'| 2C | 01 | FILE MODE | LINKS | + * +----+----+----+----+-----------+-----------+ + * 0 1 2 3 4 12 20 + * +-----------+-----------+------------------+ + * | USER ID | GROUP ID |FILE SERIAL NUMBER| + * +-----------+-----------+------------------+ + * 20 28 36 44 + */ + length = 44; + if (extra_space(&ctl) < length) + bp = extra_next_record(&ctl, length); + if (bp != NULL) { + mode_t mode; + int64_t uid; + int64_t gid; + + mode = archive_entry_mode(file->entry); + uid = archive_entry_uid(file->entry); + gid = archive_entry_gid(file->entry); + if (iso9660->opt.rr == OPT_RR_USEFUL) { + /* + * This action is similar to mkisofs -r option + * but our rockridge=useful option does not + * set a zero to uid and gid. + */ + /* set all read bit ON */ + mode |= 0444; +#if !defined(_WIN32) && !defined(__CYGWIN__) + if (mode & 0111) +#endif + /* set all exec bit ON */ + mode |= 0111; + /* clear all write bits. */ + mode &= ~0222; + /* clear setuid,setgid,sticky bits. */ + mode &= ~07000; + } + + bp[1] = 'P'; + bp[2] = 'X'; + bp[3] = length; + bp[4] = 1; /* version */ + /* file mode */ + set_num_733(bp+5, mode); + /* file links (stat.st_nlink) */ + set_num_733(bp+13, + archive_entry_nlink(file->entry)); + set_num_733(bp+21, (uint32_t)uid); + set_num_733(bp+29, (uint32_t)gid); + /* File Serial Number */ + if (pxent->dir) + set_num_733(bp+37, pxent->dir_location); + else if (file->hardlink_target != NULL) + set_num_733(bp+37, + file->hardlink_target->cur_content->location); + else + set_num_733(bp+37, + file->cur_content->location); + bp += length; + } + extra_tell_used_size(&ctl, length); + } + + /* Write "SL" System Use Entry. */ + if (rr_flag & RR_USE_SL) { + /* + * "SL" Format: + * e.g. a symbolic name is 'foo/bar' + * len ver flg + * +----+----+----+----+----+------------+ + * | 'S'| 'L'| 0F | 01 | 00 | components | + * +----+----+----+----+----+-----+------+ + * 0 1 2 3 4 5 ...|... 15 + * <----------------- len --------+------> + * components : | + * cflg clen | + * +----+----+----+----+----+ | + * | 00 | 03 | 'f'| 'o'| 'o'| <---+ + * +----+----+----+----+----+ | + * 5 6 7 8 9 10 | + * cflg clen | + * +----+----+----+----+----+ | + * | 00 | 03 | 'b'| 'a'| 'r'| <---+ + * +----+----+----+----+----+ + * 10 11 12 13 14 15 + * + * - cflg : flag of component + * - clen : length of component + */ + const char *sl; + char sl_last; + + if (extra_space(&ctl) < 7) + bp = extra_next_record(&ctl, 7); + sl = file->symlink.s; + sl_last = '\0'; + if (bp != NULL) { + bp[1] = 'S'; + bp[2] = 'L'; + bp[4] = 1; /* version */ + } + for (;;) { + unsigned char *nc, *cf, *cl, cldmy = 0; + int sllen, slmax; + + slmax = extra_space(&ctl); + if (slmax > 0xff) + slmax = 0xff; + if (bp != NULL) + nc = &bp[6]; + else + nc = NULL; + cf = cl = NULL; + sllen = 0; + while (*sl && sllen + 11 < slmax) { + if (sl_last == '\0' && sl[0] == '/') { + /* + * flg len + * +----+----+ + * | 08 | 00 | ROOT component. + * +----+----+ ("/") + * + * Root component has to appear + * at the first component only. + */ + if (nc != NULL) { + cf = nc++; + *cf = 0x08; /* ROOT */ + *nc++ = 0; + } + sllen += 2; + sl++; + sl_last = '/'; + cl = NULL; + continue; + } + if (((sl_last == '\0' || sl_last == '/') && + sl[0] == '.' && sl[1] == '.' && + (sl[2] == '/' || sl[2] == '\0')) || + (sl[0] == '/' && + sl[1] == '.' && sl[2] == '.' && + (sl[3] == '/' || sl[3] == '\0'))) { + /* + * flg len + * +----+----+ + * | 04 | 00 | PARENT component. + * +----+----+ ("..") + */ + if (nc != NULL) { + cf = nc++; + *cf = 0x04; /* PARENT */ + *nc++ = 0; + } + sllen += 2; + if (sl[0] == '/') + sl += 3;/* skip "/.." */ + else + sl += 2;/* skip ".." */ + sl_last = '.'; + cl = NULL; + continue; + } + if (((sl_last == '\0' || sl_last == '/') && + sl[0] == '.' && + (sl[1] == '/' || sl[1] == '\0')) || + (sl[0] == '/' && sl[1] == '.' && + (sl[2] == '/' || sl[2] == '\0'))) { + /* + * flg len + * +----+----+ + * | 02 | 00 | CURRENT component. + * +----+----+ (".") + */ + if (nc != NULL) { + cf = nc++; + *cf = 0x02; /* CURRENT */ + *nc++ = 0; + } + sllen += 2; + if (sl[0] == '/') + sl += 2;/* skip "/." */ + else + sl ++; /* skip "." */ + sl_last = '.'; + cl = NULL; + continue; + } + if (sl[0] == '/' || cl == NULL) { + if (nc != NULL) { + cf = nc++; + *cf = 0; + cl = nc++; + *cl = 0; + } else + cl = &cldmy; + sllen += 2; + if (sl[0] == '/') { + sl_last = *sl++; + continue; + } + } + sl_last = *sl++; + if (nc != NULL) { + *nc++ = sl_last; + (*cl) ++; + } + sllen++; + } + if (*sl) { + length = 5 + sllen; + if (bp != NULL) { + /* + * Mark flg as CONTINUE component. + */ + *cf |= 0x01; + /* + * len ver flg + * +----+----+----+----+----+- + * | 'S'| 'L'| XX | 01 | 01 | + * +----+----+----+----+----+- + * ^ + * continues in next "SL" + */ + bp[3] = length; + bp[5] = 0x01;/* This Symbolic Link + * continues in next + * "SL" field */ + bp += length; + } + extra_tell_used_size(&ctl, length); + if (extra_space(&ctl) < 11) + bp = extra_next_record(&ctl, 11); + if (bp != NULL) { + /* Next 'SL' */ + bp[1] = 'S'; + bp[2] = 'L'; + bp[4] = 1; /* version */ + } + } else { + length = 5 + sllen; + if (bp != NULL) { + bp[3] = length; + bp[5] = 0; + bp += length; + } + extra_tell_used_size(&ctl, length); + break; + } + } + } + + /* Write "TF" System Use Entry. */ + if (rr_flag & RR_USE_TF) { + /* + * "TF" Format: + * len ver + * +----+----+----+----+-----+-------------+ + * | 'T'| 'F'| XX | 01 |FLAGS| TIME STAMPS | + * +----+----+----+----+-----+-------------+ + * 0 1 2 3 4 5 XX + * TIME STAMPS : ISO 9660 Standard 9.1.5. + * If TF_LONG_FORM FLAGS is set, + * use ISO9660 Standard 8.4.26.1. + */ +#define TF_CREATION 0x01 /* Creation time recorded */ +#define TF_MODIFY 0x02 /* Modification time recorded */ +#define TF_ACCESS 0x04 /* Last Access time recorded */ +#define TF_ATTRIBUTES 0x08 /* Last Attribute Change time recorded */ +#define TF_BACKUP 0x10 /* Last Backup time recorded */ +#define TF_EXPIRATION 0x20 /* Expiration time recorded */ +#define TF_EFFECTIVE 0x40 /* Effective time recorded */ +#define TF_LONG_FORM 0x80 /* ISO 9660 17-byte time format used */ + unsigned char tf_flags; + + length = 5; + tf_flags = 0; +#ifndef COMPAT_MKISOFS + if (archive_entry_birthtime_is_set(file->entry) && + archive_entry_birthtime(file->entry) <= + archive_entry_mtime(file->entry)) { + length += 7; + tf_flags |= TF_CREATION; + } +#endif + if (archive_entry_mtime_is_set(file->entry)) { + length += 7; + tf_flags |= TF_MODIFY; + } + if (archive_entry_atime_is_set(file->entry)) { + length += 7; + tf_flags |= TF_ACCESS; + } + if (archive_entry_ctime_is_set(file->entry)) { + length += 7; + tf_flags |= TF_ATTRIBUTES; + } + if (extra_space(&ctl) < length) + bp = extra_next_record(&ctl, length); + if (bp != NULL) { + bp[1] = 'T'; + bp[2] = 'F'; + bp[3] = length; + bp[4] = 1; /* version */ + bp[5] = tf_flags; + bp += 5; + /* Creation time */ + if (tf_flags & TF_CREATION) { + set_time_915(bp+1, + archive_entry_birthtime(file->entry)); + bp += 7; + } + /* Modification time */ + if (tf_flags & TF_MODIFY) { + set_time_915(bp+1, + archive_entry_mtime(file->entry)); + bp += 7; + } + /* Last Access time */ + if (tf_flags & TF_ACCESS) { + set_time_915(bp+1, + archive_entry_atime(file->entry)); + bp += 7; + } + /* Last Attribute Change time */ + if (tf_flags & TF_ATTRIBUTES) { + set_time_915(bp+1, + archive_entry_ctime(file->entry)); + bp += 7; + } + } + extra_tell_used_size(&ctl, length); + } + + /* Write "RE" System Use Entry. */ + if (rr_flag & RR_USE_RE) { + /* + * "RE" Format: + * len ver + * +----+----+----+----+ + * | 'R'| 'E'| 04 | 01 | + * +----+----+----+----+ + * 0 1 2 3 4 + */ + length = 4; + if (extra_space(&ctl) < length) + bp = extra_next_record(&ctl, length); + if (bp != NULL) { + bp[1] = 'R'; + bp[2] = 'E'; + bp[3] = length; + bp[4] = 1; /* version */ + bp += length; + } + extra_tell_used_size(&ctl, length); + } + + /* Write "PL" System Use Entry. */ + if (rr_flag & RR_USE_PL) { + /* + * "PL" Format: + * len ver + * +----+----+----+----+------------+ + * | 'P'| 'L'| 0C | 01 | *LOCATION | + * +----+----+----+----+------------+ + * 0 1 2 3 4 12 + * *LOCATION: location of parent directory + */ + length = 12; + if (extra_space(&ctl) < length) + bp = extra_next_record(&ctl, length); + if (bp != NULL) { + bp[1] = 'P'; + bp[2] = 'L'; + bp[3] = length; + bp[4] = 1; /* version */ + set_num_733(bp + 5, + rr_parent->dir_location); + bp += length; + } + extra_tell_used_size(&ctl, length); + } + + /* Write "CL" System Use Entry. */ + if (rr_flag & RR_USE_CL) { + /* + * "CL" Format: + * len ver + * +----+----+----+----+------------+ + * | 'C'| 'L'| 0C | 01 | *LOCATION | + * +----+----+----+----+------------+ + * 0 1 2 3 4 12 + * *LOCATION: location of child directory + */ + length = 12; + if (extra_space(&ctl) < length) + bp = extra_next_record(&ctl, length); + if (bp != NULL) { + bp[1] = 'C'; + bp[2] = 'L'; + bp[3] = length; + bp[4] = 1; /* version */ + set_num_733(bp + 5, + isoent->rr_child->dir_location); + bp += length; + } + extra_tell_used_size(&ctl, length); + } + + /* Write "PN" System Use Entry. */ + if (rr_flag & RR_USE_PN) { + /* + * "PN" Format: + * len ver + * +----+----+----+----+------------+------------+ + * | 'P'| 'N'| 14 | 01 | dev_t high | dev_t low | + * +----+----+----+----+------------+------------+ + * 0 1 2 3 4 12 20 + */ + length = 20; + if (extra_space(&ctl) < length) + bp = extra_next_record(&ctl, length); + if (bp != NULL) { + uint64_t dev; + + bp[1] = 'P'; + bp[2] = 'N'; + bp[3] = length; + bp[4] = 1; /* version */ + dev = (uint64_t)archive_entry_rdev(file->entry); + set_num_733(bp + 5, (uint32_t)(dev >> 32)); + set_num_733(bp + 13, (uint32_t)(dev & 0xFFFFFFFF)); + bp += length; + } + extra_tell_used_size(&ctl, length); + } + + /* Write "ZF" System Use Entry. */ + if (file->zisofs.header_size) { + /* + * "ZF" Format: + * len ver + * +----+----+----+----+----+----+-------------+ + * | 'Z'| 'F'| 10 | 01 | 'p'| 'z'| Header Size | + * +----+----+----+----+----+----+-------------+ + * 0 1 2 3 4 5 6 7 + * +--------------------+-------------------+ + * | Log2 of block Size | Uncompressed Size | + * +--------------------+-------------------+ + * 7 8 16 + */ + length = 16; + if (extra_space(&ctl) < length) + bp = extra_next_record(&ctl, length); + if (bp != NULL) { + bp[1] = 'Z'; + bp[2] = 'F'; + bp[3] = length; + bp[4] = 1; /* version */ + bp[5] = 'p'; + bp[6] = 'z'; + bp[7] = file->zisofs.header_size; + bp[8] = file->zisofs.log2_bs; + set_num_733(bp + 9, file->zisofs.uncompressed_size); + bp += length; + } + extra_tell_used_size(&ctl, length); + } + + /* Write "CE" System Use Entry. */ + if (t == DIR_REC_SELF && isoent == isoent->parent) { + length = RR_CE_SIZE; + if (bp != NULL) + set_SUSP_CE(bp+1, iso9660->location_rrip_er, + 0, RRIP_ER_SIZE); + extra_tell_used_size(&ctl, length); + } + + extra_close_record(&ctl, 0); + + return (ctl.dr_len); +} + +/* + * Write data of a Directory Record or calculate writing bytes itself. + * If parameter `p' is NULL, calculates the size of writing data, which + * a Directory Record needs to write, then it saved and return + * the calculated size. + * Parameter `n' is a remaining size of buffer. when parameter `p' is + * not NULL, check whether that `n' is not less than the saved size. + * if that `n' is small, return zero. + * + * This format of the Directory Record is according to + * ISO9660 Standard 9.1 + */ +static int +set_directory_record(unsigned char *p, size_t n, struct isoent *isoent, + struct iso9660 *iso9660, enum dir_rec_type t, + enum vdd_type vdd_type) +{ + unsigned char *bp; + size_t dr_len; + size_t fi_len; + + if (p != NULL) { + /* + * Check whether a write buffer size is less than the + * saved size which is needed to write this Directory + * Record. + */ + switch (t) { + case DIR_REC_VD: + dr_len = isoent->dr_len.vd; break; + case DIR_REC_SELF: + dr_len = isoent->dr_len.self; break; + case DIR_REC_PARENT: + dr_len = isoent->dr_len.parent; break; + case DIR_REC_NORMAL: + default: + dr_len = isoent->dr_len.normal; break; + } + if (dr_len > n) + return (0);/* Needs more buffer size. */ + } + + if (t == DIR_REC_NORMAL && isoent->identifier != NULL) + fi_len = isoent->id_len; + else + fi_len = 1; + + if (p != NULL) { + struct isoent *xisoent; + struct isofile *file; + unsigned char flag; + + if (t == DIR_REC_PARENT) + xisoent = isoent->parent; + else + xisoent = isoent; + file = isoent->file; + if (file->hardlink_target != NULL) + file = file->hardlink_target; + /* Make a file flag. */ + if (xisoent->dir) + flag = FILE_FLAG_DIRECTORY; + else { + if (file->cur_content->next != NULL) + flag = FILE_FLAG_MULTI_EXTENT; + else + flag = 0; + } + + bp = p -1; + /* Extended Attribute Record Length */ + set_num_711(bp+2, 0); + /* Location of Extent */ + if (xisoent->dir) + set_num_733(bp+3, xisoent->dir_location); + else + set_num_733(bp+3, file->cur_content->location); + /* Data Length */ + if (xisoent->dir) + set_num_733(bp+11, + xisoent->dir_block * LOGICAL_BLOCK_SIZE); + else + set_num_733(bp+11, (uint32_t)file->cur_content->size); + /* Recording Date and Time */ + /* NOTE: + * If a file type is symbolic link, you are seeing this + * field value is different from a value mkisofs makes. + * libarchive uses lstat to get this one, but it + * seems mkisofs uses stat to get. + */ + set_time_915(bp+19, + archive_entry_mtime(xisoent->file->entry)); + /* File Flags */ + bp[26] = flag; + /* File Unit Size */ + set_num_711(bp+27, 0); + /* Interleave Gap Size */ + set_num_711(bp+28, 0); + /* Volume Sequence Number */ + set_num_723(bp+29, iso9660->volume_sequence_number); + /* Length of File Identifier */ + set_num_711(bp+33, (unsigned char)fi_len); + /* File Identifier */ + switch (t) { + case DIR_REC_VD: + case DIR_REC_SELF: + set_num_711(bp+34, 0); + break; + case DIR_REC_PARENT: + set_num_711(bp+34, 1); + break; + case DIR_REC_NORMAL: + if (isoent->identifier != NULL) + memcpy(bp+34, isoent->identifier, fi_len); + else + set_num_711(bp+34, 0); + break; + } + } else + bp = NULL; + dr_len = 33 + fi_len; + /* Padding Field */ + if (dr_len & 0x01) { + dr_len ++; + if (p != NULL) + bp[dr_len] = 0; + } + + /* Volume Descriptor does not record extension. */ + if (t == DIR_REC_VD) { + if (p != NULL) + /* Length of Directory Record */ + set_num_711(p, (unsigned char)dr_len); + else + isoent->dr_len.vd = (int)dr_len; + return ((int)dr_len); + } + + /* Rockridge */ + if (iso9660->opt.rr && vdd_type != VDD_JOLIET) + dr_len = set_directory_record_rr(bp, (int)dr_len, + isoent, iso9660, t); + + if (p != NULL) + /* Length of Directory Record */ + set_num_711(p, (unsigned char)dr_len); + else { + /* + * Save the size which is needed to write this + * Directory Record. + */ + switch (t) { + case DIR_REC_VD: + /* This case does not come, but compiler + * complains that DIR_REC_VD not handled + * in switch .... */ + break; + case DIR_REC_SELF: + isoent->dr_len.self = (int)dr_len; break; + case DIR_REC_PARENT: + isoent->dr_len.parent = (int)dr_len; break; + case DIR_REC_NORMAL: + isoent->dr_len.normal = (int)dr_len; break; + } + } + + return ((int)dr_len); +} + +/* + * Calculate the size of a directory record. + */ +static inline int +get_dir_rec_size(struct iso9660 *iso9660, struct isoent *isoent, + enum dir_rec_type t, enum vdd_type vdd_type) +{ + + return (set_directory_record(NULL, SIZE_MAX, + isoent, iso9660, t, vdd_type)); +} + +/* + * Manage to write ISO-image data with wbuff to reduce calling + * __archive_write_output() for performance. + */ + + +static inline unsigned char * +wb_buffptr(struct archive_write *a) +{ + struct iso9660 *iso9660 = (struct iso9660 *)a->format_data; + + return (&(iso9660->wbuff[sizeof(iso9660->wbuff) + - iso9660->wbuff_remaining])); +} + +static int +wb_write_out(struct archive_write *a) +{ + struct iso9660 *iso9660 = (struct iso9660 *)a->format_data; + size_t wsize, nw; + int r; + + wsize = sizeof(iso9660->wbuff) - iso9660->wbuff_remaining; + nw = wsize % LOGICAL_BLOCK_SIZE; + if (iso9660->wbuff_type == WB_TO_STREAM) + r = __archive_write_output(a, iso9660->wbuff, wsize - nw); + else + r = write_to_temp(a, iso9660->wbuff, wsize - nw); + /* Increase the offset. */ + iso9660->wbuff_offset += wsize - nw; + if (iso9660->wbuff_offset > iso9660->wbuff_written) + iso9660->wbuff_written = iso9660->wbuff_offset; + iso9660->wbuff_remaining = sizeof(iso9660->wbuff); + if (nw) { + iso9660->wbuff_remaining -= nw; + memmove(iso9660->wbuff, iso9660->wbuff + wsize - nw, nw); + } + return (r); +} + +static int +wb_consume(struct archive_write *a, size_t size) +{ + struct iso9660 *iso9660 = (struct iso9660 *)a->format_data; + + if (size > iso9660->wbuff_remaining || + iso9660->wbuff_remaining == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Internal Programming error: iso9660:wb_consume()" + " size=%jd, wbuff_remaining=%jd", + (intmax_t)size, (intmax_t)iso9660->wbuff_remaining); + return (ARCHIVE_FATAL); + } + iso9660->wbuff_remaining -= size; + if (iso9660->wbuff_remaining < LOGICAL_BLOCK_SIZE) + return (wb_write_out(a)); + return (ARCHIVE_OK); +} + +#ifdef HAVE_ZLIB_H + +static int +wb_set_offset(struct archive_write *a, int64_t off) +{ + struct iso9660 *iso9660 = (struct iso9660 *)a->format_data; + int64_t used, ext_bytes; + + if (iso9660->wbuff_type != WB_TO_TEMP) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Internal Programming error: iso9660:wb_set_offset()"); + return (ARCHIVE_FATAL); + } + + used = sizeof(iso9660->wbuff) - iso9660->wbuff_remaining; + if (iso9660->wbuff_offset + used > iso9660->wbuff_tail) + iso9660->wbuff_tail = iso9660->wbuff_offset + used; + if (iso9660->wbuff_offset < iso9660->wbuff_written) { + if (used > 0 && + write_to_temp(a, iso9660->wbuff, (size_t)used) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + iso9660->wbuff_offset = iso9660->wbuff_written; + lseek(iso9660->temp_fd, iso9660->wbuff_offset, SEEK_SET); + iso9660->wbuff_remaining = sizeof(iso9660->wbuff); + used = 0; + } + if (off < iso9660->wbuff_offset) { + /* + * Write out waiting data. + */ + if (used > 0) { + if (wb_write_out(a) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + lseek(iso9660->temp_fd, off, SEEK_SET); + iso9660->wbuff_offset = off; + iso9660->wbuff_remaining = sizeof(iso9660->wbuff); + } else if (off <= iso9660->wbuff_tail) { + iso9660->wbuff_remaining = (size_t) + (sizeof(iso9660->wbuff) - (off - iso9660->wbuff_offset)); + } else { + ext_bytes = off - iso9660->wbuff_tail; + iso9660->wbuff_remaining = (size_t)(sizeof(iso9660->wbuff) + - (iso9660->wbuff_tail - iso9660->wbuff_offset)); + while (ext_bytes >= (int64_t)iso9660->wbuff_remaining) { + if (write_null(a, (size_t)iso9660->wbuff_remaining) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + ext_bytes -= iso9660->wbuff_remaining; + } + if (ext_bytes > 0) { + if (write_null(a, (size_t)ext_bytes) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + } + return (ARCHIVE_OK); +} + +#endif /* HAVE_ZLIB_H */ + +static int +write_null(struct archive_write *a, size_t size) +{ + size_t remaining; + unsigned char *p, *old; + int r; + + remaining = wb_remaining(a); + p = wb_buffptr(a); + if (size <= remaining) { + memset(p, 0, size); + return (wb_consume(a, size)); + } + memset(p, 0, remaining); + r = wb_consume(a, remaining); + if (r != ARCHIVE_OK) + return (r); + size -= remaining; + old = p; + p = wb_buffptr(a); + memset(p, 0, old - p); + remaining = wb_remaining(a); + while (size) { + size_t wsize = size; + + if (wsize > remaining) + wsize = remaining; + r = wb_consume(a, wsize); + if (r != ARCHIVE_OK) + return (r); + size -= wsize; + } + return (ARCHIVE_OK); +} + +/* + * Write Volume Descriptor Set Terminator + */ +static int +write_VD_terminator(struct archive_write *a) +{ + unsigned char *bp; + + bp = wb_buffptr(a) -1; + set_VD_bp(bp, VDT_TERMINATOR, 1); + set_unused_field_bp(bp, 8, LOGICAL_BLOCK_SIZE); + + return (wb_consume(a, LOGICAL_BLOCK_SIZE)); +} + +static int +set_file_identifier(unsigned char *bp, int from, int to, enum vdc vdc, + struct archive_write *a, struct vdd *vdd, struct archive_string *id, + const char *label, int leading_under, enum char_type char_type) +{ + char identifier[256]; + struct isoent *isoent; + const char *ids; + size_t len; + int r; + + if (id->length > 0 && leading_under && id->s[0] != '_') { + if (char_type == A_CHAR) + r = set_str_a_characters_bp(a, bp, from, to, id->s, vdc); + else + r = set_str_d_characters_bp(a, bp, from, to, id->s, vdc); + } else if (id->length > 0) { + ids = id->s; + if (leading_under) + ids++; + isoent = isoent_find_entry(vdd->rootent, ids); + if (isoent == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Not Found %s `%s'.", + label, ids); + return (ARCHIVE_FATAL); + } + len = isoent->ext_off + isoent->ext_len; + if (vdd->vdd_type == VDD_JOLIET) { + if (len > sizeof(identifier)-2) + len = sizeof(identifier)-2; + } else { + if (len > sizeof(identifier)-1) + len = sizeof(identifier)-1; + } + memcpy(identifier, isoent->identifier, len); + identifier[len] = '\0'; + if (vdd->vdd_type == VDD_JOLIET) { + identifier[len+1] = 0; + vdc = VDC_UCS2_DIRECT; + } + if (char_type == A_CHAR) + r = set_str_a_characters_bp(a, bp, from, to, + identifier, vdc); + else + r = set_str_d_characters_bp(a, bp, from, to, + identifier, vdc); + } else { + if (char_type == A_CHAR) + r = set_str_a_characters_bp(a, bp, from, to, NULL, vdc); + else + r = set_str_d_characters_bp(a, bp, from, to, NULL, vdc); + } + return (r); +} + +/* + * Write Primary/Supplementary Volume Descriptor + */ +static int +write_VD(struct archive_write *a, struct vdd *vdd) +{ + struct iso9660 *iso9660; + unsigned char *bp; + uint16_t volume_set_size = 1; + char identifier[256]; + enum VD_type vdt; + enum vdc vdc; + unsigned char vd_ver, fst_ver; + int r; + + iso9660 = a->format_data; + switch (vdd->vdd_type) { + case VDD_JOLIET: + vdt = VDT_SUPPLEMENTARY; + vd_ver = fst_ver = 1; + vdc = VDC_UCS2; + break; + case VDD_ENHANCED: + vdt = VDT_SUPPLEMENTARY; + vd_ver = fst_ver = 2; + vdc = VDC_LOWERCASE; + break; + case VDD_PRIMARY: + default: + vdt = VDT_PRIMARY; + vd_ver = fst_ver = 1; +#ifdef COMPAT_MKISOFS + vdc = VDC_LOWERCASE; +#else + vdc = VDC_STD; +#endif + break; + } + + bp = wb_buffptr(a) -1; + /* Volume Descriptor Type */ + set_VD_bp(bp, vdt, vd_ver); + /* Unused Field */ + set_unused_field_bp(bp, 8, 8); + /* System Identifier */ + get_system_identitier(identifier, sizeof(identifier)); + r = set_str_a_characters_bp(a, bp, 9, 40, identifier, vdc); + if (r != ARCHIVE_OK) + return (r); + /* Volume Identifier */ + r = set_str_d_characters_bp(a, bp, 41, 72, + iso9660->volume_identifier.s, vdc); + if (r != ARCHIVE_OK) + return (r); + /* Unused Field */ + set_unused_field_bp(bp, 73, 80); + /* Volume Space Size */ + set_num_733(bp+81, iso9660->volume_space_size); + if (vdd->vdd_type == VDD_JOLIET) { + /* Escape Sequences */ + bp[89] = 0x25;/* UCS-2 Level 3 */ + bp[90] = 0x2F; + bp[91] = 0x45; + memset(bp + 92, 0, 120 - 92 + 1); + } else { + /* Unused Field */ + set_unused_field_bp(bp, 89, 120); + } + /* Volume Set Size */ + set_num_723(bp+121, volume_set_size); + /* Volume Sequence Number */ + set_num_723(bp+125, iso9660->volume_sequence_number); + /* Logical Block Size */ + set_num_723(bp+129, LOGICAL_BLOCK_SIZE); + /* Path Table Size */ + set_num_733(bp+133, vdd->path_table_size); + /* Location of Occurrence of Type L Path Table */ + set_num_731(bp+141, vdd->location_type_L_path_table); + /* Location of Optional Occurrence of Type L Path Table */ + set_num_731(bp+145, 0); + /* Location of Occurrence of Type M Path Table */ + set_num_732(bp+149, vdd->location_type_M_path_table); + /* Location of Optional Occurrence of Type M Path Table */ + set_num_732(bp+153, 0); + /* Directory Record for Root Directory(BP 157 to 190) */ + set_directory_record(bp+157, 190-157+1, vdd->rootent, + iso9660, DIR_REC_VD, vdd->vdd_type); + /* Volume Set Identifier */ + r = set_str_d_characters_bp(a, bp, 191, 318, "", vdc); + if (r != ARCHIVE_OK) + return (r); + /* Publisher Identifier */ + r = set_file_identifier(bp, 319, 446, vdc, a, vdd, + &(iso9660->publisher_identifier), + "Publisher File", 1, A_CHAR); + if (r != ARCHIVE_OK) + return (r); + /* Data Preparer Identifier */ + r = set_file_identifier(bp, 447, 574, vdc, a, vdd, + &(iso9660->data_preparer_identifier), + "Data Preparer File", 1, A_CHAR); + if (r != ARCHIVE_OK) + return (r); + /* Application Identifier */ + r = set_file_identifier(bp, 575, 702, vdc, a, vdd, + &(iso9660->application_identifier), + "Application File", 1, A_CHAR); + if (r != ARCHIVE_OK) + return (r); + /* Copyright File Identifier */ + r = set_file_identifier(bp, 703, 739, vdc, a, vdd, + &(iso9660->copyright_file_identifier), + "Copyright File", 0, D_CHAR); + if (r != ARCHIVE_OK) + return (r); + /* Abstract File Identifier */ + r = set_file_identifier(bp, 740, 776, vdc, a, vdd, + &(iso9660->abstract_file_identifier), + "Abstract File", 0, D_CHAR); + if (r != ARCHIVE_OK) + return (r); + /* Bibliographic File Identifier */ + r = set_file_identifier(bp, 777, 813, vdc, a, vdd, + &(iso9660->bibliographic_file_identifier), + "Bibliongraphic File", 0, D_CHAR); + if (r != ARCHIVE_OK) + return (r); + /* Volume Creation Date and Time */ + set_date_time(bp+814, iso9660->birth_time); + /* Volume Modification Date and Time */ + set_date_time(bp+831, iso9660->birth_time); + /* Volume Expiration Date and Time(obsolete) */ + set_date_time_null(bp+848); + /* Volume Effective Date and Time */ + set_date_time(bp+865, iso9660->birth_time); + /* File Structure Version */ + bp[882] = fst_ver; + /* Reserved */ + bp[883] = 0; + /* Application Use */ + memset(bp + 884, 0x20, 1395 - 884 + 1); + /* Reserved */ + set_unused_field_bp(bp, 1396, LOGICAL_BLOCK_SIZE); + + return (wb_consume(a, LOGICAL_BLOCK_SIZE)); +} + +/* + * Write Boot Record Volume Descriptor + */ +static int +write_VD_boot_record(struct archive_write *a) +{ + struct iso9660 *iso9660; + unsigned char *bp; + + iso9660 = a->format_data; + bp = wb_buffptr(a) -1; + /* Volume Descriptor Type */ + set_VD_bp(bp, VDT_BOOT_RECORD, 1); + /* Boot System Identifier */ + memcpy(bp+8, "EL TORITO SPECIFICATION", 23); + set_unused_field_bp(bp, 8+23, 39); + /* Unused */ + set_unused_field_bp(bp, 40, 71); + /* Absolute pointer to first sector of Boot Catalog */ + set_num_731(bp+72, + iso9660->el_torito.catalog->file->content.location); + /* Unused */ + set_unused_field_bp(bp, 76, LOGICAL_BLOCK_SIZE); + + return (wb_consume(a, LOGICAL_BLOCK_SIZE)); +} + +enum keytype { + KEY_FLG, + KEY_STR, + KEY_INT, + KEY_HEX +}; +static void +set_option_info(struct archive_string *info, int *opt, const char *key, + enum keytype type, ...) +{ + va_list ap; + char prefix; + const char *s; + int d; + + prefix = (*opt==0)? ' ':','; + va_start(ap, type); + switch (type) { + case KEY_FLG: + d = va_arg(ap, int); + archive_string_sprintf(info, "%c%s%s", + prefix, (d == 0)?"!":"", key); + break; + case KEY_STR: + s = va_arg(ap, const char *); + archive_string_sprintf(info, "%c%s=%s", + prefix, key, s); + break; + case KEY_INT: + d = va_arg(ap, int); + archive_string_sprintf(info, "%c%s=%d", + prefix, key, d); + break; + case KEY_HEX: + d = va_arg(ap, int); + archive_string_sprintf(info, "%c%s=%x", + prefix, key, d); + break; + } + va_end(ap); + + *opt = 1; +} + +/* + * Make Non-ISO File System Information + */ +static int +write_information_block(struct archive_write *a) +{ + struct iso9660 *iso9660; + char buf[128]; + const char *v; + int opt, r; + struct archive_string info; + size_t info_size = LOGICAL_BLOCK_SIZE * + NON_ISO_FILE_SYSTEM_INFORMATION_BLOCK; + + iso9660 = (struct iso9660 *)a->format_data; + if (info_size > wb_remaining(a)) { + r = wb_write_out(a); + if (r != ARCHIVE_OK) + return (r); + } + archive_string_init(&info); + if (archive_string_ensure(&info, info_size) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + memset(info.s, 0, info_size); + opt = 0; +#if defined(HAVE__CTIME64_S) + { + __time64_t iso9660_birth_time_tmp = (__time64_t) iso9660->birth_time; //time_t may be shorter than 64 bits + _ctime64_s(buf, sizeof(buf), &(iso9660_birth_time_tmp)); + } +#elif defined(HAVE_CTIME_R) + ctime_r(&(iso9660->birth_time), buf); +#else + strncpy(buf, ctime(&(iso9660->birth_time)), sizeof(buf)-1); + buf[sizeof(buf)-1] = '\0'; +#endif + archive_string_sprintf(&info, + "INFO %s%s", buf, archive_version_string()); + if (iso9660->opt.abstract_file != OPT_ABSTRACT_FILE_DEFAULT) + set_option_info(&info, &opt, "abstract-file", + KEY_STR, iso9660->abstract_file_identifier.s); + if (iso9660->opt.application_id != OPT_APPLICATION_ID_DEFAULT) + set_option_info(&info, &opt, "application-id", + KEY_STR, iso9660->application_identifier.s); + if (iso9660->opt.allow_vernum != OPT_ALLOW_VERNUM_DEFAULT) + set_option_info(&info, &opt, "allow-vernum", + KEY_FLG, iso9660->opt.allow_vernum); + if (iso9660->opt.biblio_file != OPT_BIBLIO_FILE_DEFAULT) + set_option_info(&info, &opt, "biblio-file", + KEY_STR, iso9660->bibliographic_file_identifier.s); + if (iso9660->opt.boot != OPT_BOOT_DEFAULT) + set_option_info(&info, &opt, "boot", + KEY_STR, iso9660->el_torito.boot_filename.s); + if (iso9660->opt.boot_catalog != OPT_BOOT_CATALOG_DEFAULT) + set_option_info(&info, &opt, "boot-catalog", + KEY_STR, iso9660->el_torito.catalog_filename.s); + if (iso9660->opt.boot_info_table != OPT_BOOT_INFO_TABLE_DEFAULT) + set_option_info(&info, &opt, "boot-info-table", + KEY_FLG, iso9660->opt.boot_info_table); + if (iso9660->opt.boot_load_seg != OPT_BOOT_LOAD_SEG_DEFAULT) + set_option_info(&info, &opt, "boot-load-seg", + KEY_HEX, iso9660->el_torito.boot_load_seg); + if (iso9660->opt.boot_load_size != OPT_BOOT_LOAD_SIZE_DEFAULT) + set_option_info(&info, &opt, "boot-load-size", + KEY_INT, iso9660->el_torito.boot_load_size); + if (iso9660->opt.boot_type != OPT_BOOT_TYPE_DEFAULT) { + v = "no-emulation"; + if (iso9660->opt.boot_type == OPT_BOOT_TYPE_FD) + v = "fd"; + if (iso9660->opt.boot_type == OPT_BOOT_TYPE_HARD_DISK) + v = "hard-disk"; + set_option_info(&info, &opt, "boot-type", + KEY_STR, v); + } +#ifdef HAVE_ZLIB_H + if (iso9660->opt.compression_level != OPT_COMPRESSION_LEVEL_DEFAULT) + set_option_info(&info, &opt, "compression-level", + KEY_INT, iso9660->zisofs.compression_level); +#endif + if (iso9660->opt.copyright_file != OPT_COPYRIGHT_FILE_DEFAULT) + set_option_info(&info, &opt, "copyright-file", + KEY_STR, iso9660->copyright_file_identifier.s); + if (iso9660->opt.iso_level != OPT_ISO_LEVEL_DEFAULT) + set_option_info(&info, &opt, "iso-level", + KEY_INT, iso9660->opt.iso_level); + if (iso9660->opt.joliet != OPT_JOLIET_DEFAULT) { + if (iso9660->opt.joliet == OPT_JOLIET_LONGNAME) + set_option_info(&info, &opt, "joliet", + KEY_STR, "long"); + else + set_option_info(&info, &opt, "joliet", + KEY_FLG, iso9660->opt.joliet); + } + if (iso9660->opt.limit_depth != OPT_LIMIT_DEPTH_DEFAULT) + set_option_info(&info, &opt, "limit-depth", + KEY_FLG, iso9660->opt.limit_depth); + if (iso9660->opt.limit_dirs != OPT_LIMIT_DIRS_DEFAULT) + set_option_info(&info, &opt, "limit-dirs", + KEY_FLG, iso9660->opt.limit_dirs); + if (iso9660->opt.pad != OPT_PAD_DEFAULT) + set_option_info(&info, &opt, "pad", + KEY_FLG, iso9660->opt.pad); + if (iso9660->opt.publisher != OPT_PUBLISHER_DEFAULT) + set_option_info(&info, &opt, "publisher", + KEY_STR, iso9660->publisher_identifier.s); + if (iso9660->opt.rr != OPT_RR_DEFAULT) { + if (iso9660->opt.rr == OPT_RR_DISABLED) + set_option_info(&info, &opt, "rockridge", + KEY_FLG, iso9660->opt.rr); + else if (iso9660->opt.rr == OPT_RR_STRICT) + set_option_info(&info, &opt, "rockridge", + KEY_STR, "strict"); + else if (iso9660->opt.rr == OPT_RR_USEFUL) + set_option_info(&info, &opt, "rockridge", + KEY_STR, "useful"); + } + if (iso9660->opt.volume_id != OPT_VOLUME_ID_DEFAULT) + set_option_info(&info, &opt, "volume-id", + KEY_STR, iso9660->volume_identifier.s); + if (iso9660->opt.zisofs != OPT_ZISOFS_DEFAULT) + set_option_info(&info, &opt, "zisofs", + KEY_FLG, iso9660->opt.zisofs); + + memcpy(wb_buffptr(a), info.s, info_size); + archive_string_free(&info); + return (wb_consume(a, info_size)); +} + +static int +write_rr_ER(struct archive_write *a) +{ + unsigned char *p; + + p = wb_buffptr(a); + + memset(p, 0, LOGICAL_BLOCK_SIZE); + p[0] = 'E'; + p[1] = 'R'; + p[3] = 0x01; + p[2] = RRIP_ER_SIZE; + p[4] = RRIP_ER_ID_SIZE; + p[5] = RRIP_ER_DSC_SIZE; + p[6] = RRIP_ER_SRC_SIZE; + p[7] = 0x01; + memcpy(&p[8], rrip_identifier, p[4]); + memcpy(&p[8+p[4]], rrip_descriptor, p[5]); + memcpy(&p[8+p[4]+p[5]], rrip_source, p[6]); + + return (wb_consume(a, LOGICAL_BLOCK_SIZE)); +} + +static void +calculate_path_table_size(struct vdd *vdd) +{ + int depth, size; + struct path_table *pt; + + pt = vdd->pathtbl; + size = 0; + for (depth = 0; depth < vdd->max_depth; depth++) { + struct isoent **ptbl; + int i, cnt; + + if ((cnt = pt[depth].cnt) == 0) + break; + + ptbl = pt[depth].sorted; + for (i = 0; i < cnt; i++) { + int len; + + if (ptbl[i]->identifier == NULL) + len = 1; /* root directory */ + else + len = ptbl[i]->id_len; + if (len & 0x01) + len++; /* Padding Field */ + size += 8 + len; + } + } + vdd->path_table_size = size; + vdd->path_table_block = + ((size + PATH_TABLE_BLOCK_SIZE -1) / + PATH_TABLE_BLOCK_SIZE) * + (PATH_TABLE_BLOCK_SIZE / LOGICAL_BLOCK_SIZE); +} + +static int +_write_path_table(struct archive_write *a, int type_m, int depth, + struct vdd *vdd) +{ + unsigned char *bp, *wb; + struct isoent **ptbl; + size_t wbremaining; + int i, r, wsize; + + if (vdd->pathtbl[depth].cnt == 0) + return (0); + + wsize = 0; + wb = wb_buffptr(a); + wbremaining = wb_remaining(a); + bp = wb - 1; + ptbl = vdd->pathtbl[depth].sorted; + for (i = 0; i < vdd->pathtbl[depth].cnt; i++) { + struct isoent *np; + size_t len; + + np = ptbl[i]; + if (np->identifier == NULL) + len = 1; /* root directory */ + else + len = np->id_len; + if (wbremaining - ((bp+1) - wb) < (len + 1 + 8)) { + r = wb_consume(a, (bp+1) - wb); + if (r < 0) + return (r); + wb = wb_buffptr(a); + wbremaining = wb_remaining(a); + bp = wb -1; + } + /* Length of Directory Identifier */ + set_num_711(bp+1, (unsigned char)len); + /* Extended Attribute Record Length */ + set_num_711(bp+2, 0); + /* Location of Extent */ + if (type_m) + set_num_732(bp+3, np->dir_location); + else + set_num_731(bp+3, np->dir_location); + /* Parent Directory Number */ + if (type_m) + set_num_722(bp+7, np->parent->dir_number); + else + set_num_721(bp+7, np->parent->dir_number); + /* Directory Identifier */ + if (np->identifier == NULL) + bp[9] = 0; + else + memcpy(&bp[9], np->identifier, len); + if (len & 0x01) { + /* Padding Field */ + bp[9+len] = 0; + len++; + } + wsize += 8 + (int)len; + bp += 8 + len; + } + if ((bp + 1) > wb) { + r = wb_consume(a, (bp+1)-wb); + if (r < 0) + return (r); + } + return (wsize); +} + +static int +write_path_table(struct archive_write *a, int type_m, struct vdd *vdd) +{ + int depth, r; + size_t path_table_size; + + r = ARCHIVE_OK; + path_table_size = 0; + for (depth = 0; depth < vdd->max_depth; depth++) { + r = _write_path_table(a, type_m, depth, vdd); + if (r < 0) + return (r); + path_table_size += r; + } + + /* Write padding data. */ + path_table_size = path_table_size % PATH_TABLE_BLOCK_SIZE; + if (path_table_size > 0) + r = write_null(a, PATH_TABLE_BLOCK_SIZE - path_table_size); + return (r); +} + +static int +calculate_directory_descriptors(struct iso9660 *iso9660, struct vdd *vdd, + struct isoent *isoent, int depth) +{ + struct isoent **enttbl; + int bs, block, i; + + block = 1; + bs = get_dir_rec_size(iso9660, isoent, DIR_REC_SELF, vdd->vdd_type); + bs += get_dir_rec_size(iso9660, isoent, DIR_REC_PARENT, vdd->vdd_type); + + if (isoent->children.cnt <= 0 || (vdd->vdd_type != VDD_JOLIET && + !iso9660->opt.rr && depth + 1 >= vdd->max_depth)) + return (block); + + enttbl = isoent->children_sorted; + for (i = 0; i < isoent->children.cnt; i++) { + struct isoent *np = enttbl[i]; + struct isofile *file; + + file = np->file; + if (file->hardlink_target != NULL) + file = file->hardlink_target; + file->cur_content = &(file->content); + do { + int dr_l; + + dr_l = get_dir_rec_size(iso9660, np, DIR_REC_NORMAL, + vdd->vdd_type); + if ((bs + dr_l) > LOGICAL_BLOCK_SIZE) { + block ++; + bs = dr_l; + } else + bs += dr_l; + file->cur_content = file->cur_content->next; + } while (file->cur_content != NULL); + } + return (block); +} + +static int +_write_directory_descriptors(struct archive_write *a, struct vdd *vdd, + struct isoent *isoent, int depth) +{ + struct iso9660 *iso9660 = a->format_data; + struct isoent **enttbl; + unsigned char *p, *wb; + int i, r; + int dr_l; + + p = wb = wb_buffptr(a); +#define WD_REMAINING (LOGICAL_BLOCK_SIZE - (p - wb)) + p += set_directory_record(p, WD_REMAINING, isoent, + iso9660, DIR_REC_SELF, vdd->vdd_type); + p += set_directory_record(p, WD_REMAINING, isoent, + iso9660, DIR_REC_PARENT, vdd->vdd_type); + + if (isoent->children.cnt <= 0 || (vdd->vdd_type != VDD_JOLIET && + !iso9660->opt.rr && depth + 1 >= vdd->max_depth)) { + memset(p, 0, WD_REMAINING); + return (wb_consume(a, LOGICAL_BLOCK_SIZE)); + } + + enttbl = isoent->children_sorted; + for (i = 0; i < isoent->children.cnt; i++) { + struct isoent *np = enttbl[i]; + struct isofile *file = np->file; + + if (file->hardlink_target != NULL) + file = file->hardlink_target; + file->cur_content = &(file->content); + do { + dr_l = set_directory_record(p, WD_REMAINING, + np, iso9660, DIR_REC_NORMAL, + vdd->vdd_type); + if (dr_l == 0) { + memset(p, 0, WD_REMAINING); + r = wb_consume(a, LOGICAL_BLOCK_SIZE); + if (r < 0) + return (r); + p = wb = wb_buffptr(a); + dr_l = set_directory_record(p, + WD_REMAINING, np, iso9660, + DIR_REC_NORMAL, vdd->vdd_type); + } + p += dr_l; + file->cur_content = file->cur_content->next; + } while (file->cur_content != NULL); + } + memset(p, 0, WD_REMAINING); + return (wb_consume(a, LOGICAL_BLOCK_SIZE)); +} + +static int +write_directory_descriptors(struct archive_write *a, struct vdd *vdd) +{ + struct isoent *np; + int depth, r; + + depth = 0; + np = vdd->rootent; + do { + struct extr_rec *extr; + + r = _write_directory_descriptors(a, vdd, np, depth); + if (r < 0) + return (r); + if (vdd->vdd_type != VDD_JOLIET) { + /* + * This extract record is used by SUSP,RRIP. + * Not for joliet. + */ + for (extr = np->extr_rec_list.first; + extr != NULL; + extr = extr->next) { + unsigned char *wb; + + wb = wb_buffptr(a); + memcpy(wb, extr->buf, extr->offset); + memset(wb + extr->offset, 0, + LOGICAL_BLOCK_SIZE - extr->offset); + r = wb_consume(a, LOGICAL_BLOCK_SIZE); + if (r < 0) + return (r); + } + } + + if (np->subdirs.first != NULL && depth + 1 < vdd->max_depth) { + /* Enter to sub directories. */ + np = np->subdirs.first; + depth++; + continue; + } + while (np != np->parent) { + if (np->drnext == NULL) { + /* Return to the parent directory. */ + np = np->parent; + depth--; + } else { + np = np->drnext; + break; + } + } + } while (np != np->parent); + + return (ARCHIVE_OK); +} + +/* + * Read file contents from the temporary file, and write it. + */ +static int +write_file_contents(struct archive_write *a, int64_t offset, int64_t size) +{ + struct iso9660 *iso9660 = a->format_data; + int r; + + lseek(iso9660->temp_fd, offset, SEEK_SET); + + while (size) { + size_t rsize; + ssize_t rs; + unsigned char *wb; + + wb = wb_buffptr(a); + rsize = wb_remaining(a); + if (rsize > (size_t)size) + rsize = (size_t)size; + rs = read(iso9660->temp_fd, wb, rsize); + if (rs <= 0) { + archive_set_error(&a->archive, errno, + "Can't read temporary file(%jd)", (intmax_t)rs); + return (ARCHIVE_FATAL); + } + size -= rs; + r = wb_consume(a, rs); + if (r < 0) + return (r); + } + return (ARCHIVE_OK); +} + +static int +write_file_descriptors(struct archive_write *a) +{ + struct iso9660 *iso9660 = a->format_data; + struct isofile *file; + int64_t blocks, offset; + int r; + + blocks = 0; + offset = 0; + + /* Make the boot catalog contents, and write it. */ + if (iso9660->el_torito.catalog != NULL) { + r = make_boot_catalog(a); + if (r < 0) + return (r); + } + + /* Write the boot file contents. */ + if (iso9660->el_torito.boot != NULL) { + file = iso9660->el_torito.boot->file; + blocks = file->content.blocks; + offset = file->content.offset_of_temp; + if (offset != 0) { + r = write_file_contents(a, offset, + blocks << LOGICAL_BLOCK_BITS); + if (r < 0) + return (r); + blocks = 0; + offset = 0; + } + } + + /* Write out all file contents. */ + for (file = iso9660->data_file_list.first; + file != NULL; file = file->datanext) { + + if (!file->write_content) + continue; + + if ((offset + (blocks << LOGICAL_BLOCK_BITS)) < + file->content.offset_of_temp) { + if (blocks > 0) { + r = write_file_contents(a, offset, + blocks << LOGICAL_BLOCK_BITS); + if (r < 0) + return (r); + } + blocks = 0; + offset = file->content.offset_of_temp; + } + + file->cur_content = &(file->content); + do { + blocks += file->cur_content->blocks; + /* Next fragment */ + file->cur_content = file->cur_content->next; + } while (file->cur_content != NULL); + } + + /* Flush out remaining blocks. */ + if (blocks > 0) { + r = write_file_contents(a, offset, + blocks << LOGICAL_BLOCK_BITS); + if (r < 0) + return (r); + } + + return (ARCHIVE_OK); +} + +static void +isofile_init_entry_list(struct iso9660 *iso9660) +{ + iso9660->all_file_list.first = NULL; + iso9660->all_file_list.last = &(iso9660->all_file_list.first); +} + +static void +isofile_add_entry(struct iso9660 *iso9660, struct isofile *file) +{ + file->allnext = NULL; + *iso9660->all_file_list.last = file; + iso9660->all_file_list.last = &(file->allnext); +} + +static void +isofile_free_all_entries(struct iso9660 *iso9660) +{ + struct isofile *file, *file_next; + + file = iso9660->all_file_list.first; + while (file != NULL) { + file_next = file->allnext; + isofile_free(file); + file = file_next; + } +} + +static void +isofile_init_entry_data_file_list(struct iso9660 *iso9660) +{ + iso9660->data_file_list.first = NULL; + iso9660->data_file_list.last = &(iso9660->data_file_list.first); +} + +static void +isofile_add_data_file(struct iso9660 *iso9660, struct isofile *file) +{ + file->datanext = NULL; + *iso9660->data_file_list.last = file; + iso9660->data_file_list.last = &(file->datanext); +} + + +static struct isofile * +isofile_new(struct archive_write *a, struct archive_entry *entry) +{ + struct isofile *file; + + file = calloc(1, sizeof(*file)); + if (file == NULL) + return (NULL); + + if (entry != NULL) + file->entry = archive_entry_clone(entry); + else + file->entry = archive_entry_new2(&a->archive); + if (file->entry == NULL) { + free(file); + return (NULL); + } + archive_string_init(&(file->parentdir)); + archive_string_init(&(file->basename)); + archive_string_init(&(file->basename_utf16)); + archive_string_init(&(file->symlink)); + file->cur_content = &(file->content); + + return (file); +} + +static void +isofile_free(struct isofile *file) +{ + struct content *con, *tmp; + + con = file->content.next; + while (con != NULL) { + tmp = con; + con = con->next; + free(tmp); + } + archive_entry_free(file->entry); + archive_string_free(&(file->parentdir)); + archive_string_free(&(file->basename)); + archive_string_free(&(file->basename_utf16)); + archive_string_free(&(file->symlink)); + free(file); +} + +#if defined(_WIN32) || defined(__CYGWIN__) +static int +cleanup_backslash_1(char *p) +{ + int mb, dos; + + mb = dos = 0; + while (*p) { + if (*(unsigned char *)p > 127) + mb = 1; + if (*p == '\\') { + /* If we have not met any multi-byte characters, + * we can replace '\' with '/'. */ + if (!mb) + *p = '/'; + dos = 1; + } + p++; + } + if (!mb || !dos) + return (0); + return (-1); +} + +static void +cleanup_backslash_2(wchar_t *p) +{ + + /* Convert a path-separator from '\' to '/' */ + while (*p != L'\0') { + if (*p == L'\\') + *p = L'/'; + p++; + } +} +#endif + +/* + * Generate a parent directory name and a base name from a pathname. + */ +static int +isofile_gen_utility_names(struct archive_write *a, struct isofile *file) +{ + struct iso9660 *iso9660; + const char *pathname; + char *p, *dirname, *slash; + size_t len; + int ret = ARCHIVE_OK; + + iso9660 = a->format_data; + + archive_string_empty(&(file->parentdir)); + archive_string_empty(&(file->basename)); + archive_string_empty(&(file->basename_utf16)); + archive_string_empty(&(file->symlink)); + + pathname = archive_entry_pathname(file->entry); + if (pathname == NULL || pathname[0] == '\0') {/* virtual root */ + file->dircnt = 0; + return (ret); + } + + /* + * Make a UTF-16BE basename if Joliet extension enabled. + */ + if (iso9660->opt.joliet) { + const char *u16, *ulast; + size_t u16len, ulen_last; + + if (iso9660->sconv_to_utf16be == NULL) { + iso9660->sconv_to_utf16be = + archive_string_conversion_to_charset( + &(a->archive), "UTF-16BE", 1); + if (iso9660->sconv_to_utf16be == NULL) + /* Couldn't allocate memory */ + return (ARCHIVE_FATAL); + iso9660->sconv_from_utf16be = + archive_string_conversion_from_charset( + &(a->archive), "UTF-16BE", 1); + if (iso9660->sconv_from_utf16be == NULL) + /* Couldn't allocate memory */ + return (ARCHIVE_FATAL); + } + + /* + * Convert a filename to UTF-16BE. + */ + if (0 > archive_entry_pathname_l(file->entry, &u16, &u16len, + iso9660->sconv_to_utf16be)) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for UTF-16BE"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "A filename cannot be converted to UTF-16BE;" + "You should disable making Joliet extension"); + ret = ARCHIVE_WARN; + } + + /* + * Make sure a path separator is not in the last; + * Remove trailing '/'. + */ + while (u16len >= 2) { +#if defined(_WIN32) || defined(__CYGWIN__) + if (u16[u16len-2] == 0 && + (u16[u16len-1] == '/' || u16[u16len-1] == '\\')) +#else + if (u16[u16len-2] == 0 && u16[u16len-1] == '/') +#endif + { + u16len -= 2; + } else + break; + } + + /* + * Find a basename in UTF-16BE. + */ + ulast = u16; + u16len >>= 1; + ulen_last = u16len; + while (u16len > 0) { +#if defined(_WIN32) || defined(__CYGWIN__) + if (u16[0] == 0 && (u16[1] == '/' || u16[1] == '\\')) +#else + if (u16[0] == 0 && u16[1] == '/') +#endif + { + ulast = u16 + 2; + ulen_last = u16len -1; + } + u16 += 2; + u16len --; + } + ulen_last <<= 1; + if (archive_string_ensure(&(file->basename_utf16), + ulen_last) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for UTF-16BE"); + return (ARCHIVE_FATAL); + } + + /* + * Set UTF-16BE basename. + */ + memcpy(file->basename_utf16.s, ulast, ulen_last); + file->basename_utf16.length = ulen_last; + } + + archive_strcpy(&(file->parentdir), pathname); +#if defined(_WIN32) || defined(__CYGWIN__) + /* + * Convert a path-separator from '\' to '/' + */ + if (cleanup_backslash_1(file->parentdir.s) != 0) { + const wchar_t *wp = archive_entry_pathname_w(file->entry); + struct archive_wstring ws; + + if (wp != NULL) { + int r; + archive_string_init(&ws); + archive_wstrcpy(&ws, wp); + cleanup_backslash_2(ws.s); + archive_string_empty(&(file->parentdir)); + r = archive_string_append_from_wcs(&(file->parentdir), + ws.s, ws.length); + archive_wstring_free(&ws); + if (r < 0 && errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + } + } +#endif + + len = file->parentdir.length; + p = dirname = file->parentdir.s; + + /* + * Remove leading '/', '../' and './' elements + */ + while (*p) { + if (p[0] == '/') { + p++; + len--; + } else if (p[0] != '.') + break; + else if (p[1] == '.' && p[2] == '/') { + p += 3; + len -= 3; + } else if (p[1] == '/' || (p[1] == '.' && p[2] == '\0')) { + p += 2; + len -= 2; + } else if (p[1] == '\0') { + p++; + len--; + } else + break; + } + if (p != dirname) { + memmove(dirname, p, len+1); + p = dirname; + } + /* + * Remove "/","/." and "/.." elements from tail. + */ + while (len > 0) { + size_t ll = len; + + if (len > 0 && p[len-1] == '/') { + p[len-1] = '\0'; + len--; + } + if (len > 1 && p[len-2] == '/' && p[len-1] == '.') { + p[len-2] = '\0'; + len -= 2; + } + if (len > 2 && p[len-3] == '/' && p[len-2] == '.' && + p[len-1] == '.') { + p[len-3] = '\0'; + len -= 3; + } + if (ll == len) + break; + } + while (*p) { + if (p[0] == '/') { + if (p[1] == '/') + /* Convert '//' --> '/' */ + memmove(p, p+1, strlen(p+1) + 1); + else if (p[1] == '.' && p[2] == '/') + /* Convert '/./' --> '/' */ + memmove(p, p+2, strlen(p+2) + 1); + else if (p[1] == '.' && p[2] == '.' && p[3] == '/') { + /* Convert 'dir/dir1/../dir2/' + * --> 'dir/dir2/' + */ + char *rp = p -1; + while (rp >= dirname) { + if (*rp == '/') + break; + --rp; + } + if (rp > dirname) { + strcpy(rp, p+3); + p = rp; + } else { + strcpy(dirname, p+4); + p = dirname; + } + } else + p++; + } else + p++; + } + p = dirname; + len = strlen(p); + + if (archive_entry_filetype(file->entry) == AE_IFLNK) { + /* Convert symlink name too. */ + pathname = archive_entry_symlink(file->entry); + archive_strcpy(&(file->symlink), pathname); +#if defined(_WIN32) || defined(__CYGWIN__) + /* + * Convert a path-separator from '\' to '/' + */ + if (archive_strlen(&(file->symlink)) > 0 && + cleanup_backslash_1(file->symlink.s) != 0) { + const wchar_t *wp = + archive_entry_symlink_w(file->entry); + struct archive_wstring ws; + + if (wp != NULL) { + int r; + archive_string_init(&ws); + archive_wstrcpy(&ws, wp); + cleanup_backslash_2(ws.s); + archive_string_empty(&(file->symlink)); + r = archive_string_append_from_wcs( + &(file->symlink), + ws.s, ws.length); + archive_wstring_free(&ws); + if (r < 0 && errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + } + } +#endif + } + /* + * - Count up directory elements. + * - Find out the position which points the last position of + * path separator('/'). + */ + slash = NULL; + file->dircnt = 0; + for (; *p != '\0'; p++) + if (*p == '/') { + slash = p; + file->dircnt++; + } + if (slash == NULL) { + /* The pathname doesn't have a parent directory. */ + file->parentdir.length = len; + archive_string_copy(&(file->basename), &(file->parentdir)); + archive_string_empty(&(file->parentdir)); + *file->parentdir.s = '\0'; + return (ret); + } + + /* Make a basename from dirname and slash */ + *slash = '\0'; + file->parentdir.length = slash - dirname; + archive_strcpy(&(file->basename), slash + 1); + if (archive_entry_filetype(file->entry) == AE_IFDIR) + file->dircnt ++; + return (ret); +} + +/* + * Register a entry to get a hardlink target. + */ +static int +isofile_register_hardlink(struct archive_write *a, struct isofile *file) +{ + struct iso9660 *iso9660 = a->format_data; + struct hardlink *hl; + const char *pathname; + + archive_entry_set_nlink(file->entry, 1); + pathname = archive_entry_hardlink(file->entry); + if (pathname == NULL) { + /* This `file` is a hardlink target. */ + hl = malloc(sizeof(*hl)); + if (hl == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + hl->nlink = 1; + /* A hardlink target must be the first position. */ + file->hlnext = NULL; + hl->file_list.first = file; + hl->file_list.last = &(file->hlnext); + __archive_rb_tree_insert_node(&(iso9660->hardlink_rbtree), + (struct archive_rb_node *)hl); + } else { + hl = (struct hardlink *)__archive_rb_tree_find_node( + &(iso9660->hardlink_rbtree), pathname); + if (hl != NULL) { + /* Insert `file` entry into the tail. */ + file->hlnext = NULL; + *hl->file_list.last = file; + hl->file_list.last = &(file->hlnext); + hl->nlink++; + } + archive_entry_unset_size(file->entry); + } + + return (ARCHIVE_OK); +} + +/* + * Hardlinked files have to have the same location of extent. + * We have to find out hardlink target entries for the entries + * which have a hardlink target name. + */ +static void +isofile_connect_hardlink_files(struct iso9660 *iso9660) +{ + struct archive_rb_node *n; + struct hardlink *hl; + struct isofile *target, *nf; + + ARCHIVE_RB_TREE_FOREACH(n, &(iso9660->hardlink_rbtree)) { + hl = (struct hardlink *)n; + + /* The first entry must be a hardlink target. */ + target = hl->file_list.first; + archive_entry_set_nlink(target->entry, hl->nlink); + /* Set a hardlink target to reference entries. */ + for (nf = target->hlnext; + nf != NULL; nf = nf->hlnext) { + nf->hardlink_target = target; + archive_entry_set_nlink(nf->entry, hl->nlink); + } + } +} + +static int +isofile_hd_cmp_node(const struct archive_rb_node *n1, + const struct archive_rb_node *n2) +{ + const struct hardlink *h1 = (const struct hardlink *)n1; + const struct hardlink *h2 = (const struct hardlink *)n2; + + return (strcmp(archive_entry_pathname(h1->file_list.first->entry), + archive_entry_pathname(h2->file_list.first->entry))); +} + +static int +isofile_hd_cmp_key(const struct archive_rb_node *n, const void *key) +{ + const struct hardlink *h = (const struct hardlink *)n; + + return (strcmp(archive_entry_pathname(h->file_list.first->entry), + (const char *)key)); +} + +static void +isofile_init_hardlinks(struct iso9660 *iso9660) +{ + static const struct archive_rb_tree_ops rb_ops = { + isofile_hd_cmp_node, isofile_hd_cmp_key, + }; + + __archive_rb_tree_init(&(iso9660->hardlink_rbtree), &rb_ops); +} + +static void +isofile_free_hardlinks(struct iso9660 *iso9660) +{ + struct archive_rb_node *n, *tmp; + + ARCHIVE_RB_TREE_FOREACH_SAFE(n, &(iso9660->hardlink_rbtree), tmp) { + __archive_rb_tree_remove_node(&(iso9660->hardlink_rbtree), n); + free(n); + } +} + +static struct isoent * +isoent_new(struct isofile *file) +{ + struct isoent *isoent; + static const struct archive_rb_tree_ops rb_ops = { + isoent_cmp_node, isoent_cmp_key, + }; + + isoent = calloc(1, sizeof(*isoent)); + if (isoent == NULL) + return (NULL); + isoent->file = file; + isoent->children.first = NULL; + isoent->children.last = &(isoent->children.first); + __archive_rb_tree_init(&(isoent->rbtree), &rb_ops); + isoent->subdirs.first = NULL; + isoent->subdirs.last = &(isoent->subdirs.first); + isoent->extr_rec_list.first = NULL; + isoent->extr_rec_list.last = &(isoent->extr_rec_list.first); + isoent->extr_rec_list.current = NULL; + if (archive_entry_filetype(file->entry) == AE_IFDIR) + isoent->dir = 1; + + return (isoent); +} + +static inline struct isoent * +isoent_clone(struct isoent *src) +{ + return (isoent_new(src->file)); +} + +static void +_isoent_free(struct isoent *isoent) +{ + struct extr_rec *er, *er_next; + + free(isoent->children_sorted); + free(isoent->identifier); + er = isoent->extr_rec_list.first; + while (er != NULL) { + er_next = er->next; + free(er); + er = er_next; + } + free(isoent); +} + +static void +isoent_free_all(struct isoent *isoent) +{ + struct isoent *np, *np_temp; + + if (isoent == NULL) + return; + np = isoent; + for (;;) { + if (np->dir) { + if (np->children.first != NULL) { + /* Enter to sub directories. */ + np = np->children.first; + continue; + } + } + for (;;) { + np_temp = np; + if (np->chnext == NULL) { + /* Return to the parent directory. */ + np = np->parent; + _isoent_free(np_temp); + if (np == np_temp) + return; + } else { + np = np->chnext; + _isoent_free(np_temp); + break; + } + } + } +} + +static struct isoent * +isoent_create_virtual_dir(struct archive_write *a, struct iso9660 *iso9660, const char *pathname) +{ + struct isofile *file; + struct isoent *isoent; + + file = isofile_new(a, NULL); + if (file == NULL) + return (NULL); + archive_entry_set_pathname(file->entry, pathname); + archive_entry_unset_mtime(file->entry); + archive_entry_unset_atime(file->entry); + archive_entry_unset_ctime(file->entry); + archive_entry_set_uid(file->entry, getuid()); + archive_entry_set_gid(file->entry, getgid()); + archive_entry_set_mode(file->entry, 0555 | AE_IFDIR); + archive_entry_set_nlink(file->entry, 2); + if (isofile_gen_utility_names(a, file) < ARCHIVE_WARN) { + isofile_free(file); + return (NULL); + } + isofile_add_entry(iso9660, file); + + isoent = isoent_new(file); + if (isoent == NULL) + return (NULL); + isoent->dir = 1; + isoent->virtual = 1; + + return (isoent); +} + +static int +isoent_cmp_node(const struct archive_rb_node *n1, + const struct archive_rb_node *n2) +{ + const struct isoent *e1 = (const struct isoent *)n1; + const struct isoent *e2 = (const struct isoent *)n2; + + return (strcmp(e1->file->basename.s, e2->file->basename.s)); +} + +static int +isoent_cmp_key(const struct archive_rb_node *n, const void *key) +{ + const struct isoent *e = (const struct isoent *)n; + + return (strcmp(e->file->basename.s, (const char *)key)); +} + +static int +isoent_add_child_head(struct isoent *parent, struct isoent *child) +{ + + if (!__archive_rb_tree_insert_node( + &(parent->rbtree), (struct archive_rb_node *)child)) + return (0); + if ((child->chnext = parent->children.first) == NULL) + parent->children.last = &(child->chnext); + parent->children.first = child; + parent->children.cnt++; + child->parent = parent; + + /* Add a child to a sub-directory chain */ + if (child->dir) { + if ((child->drnext = parent->subdirs.first) == NULL) + parent->subdirs.last = &(child->drnext); + parent->subdirs.first = child; + parent->subdirs.cnt++; + child->parent = parent; + } else + child->drnext = NULL; + return (1); +} + +static int +isoent_add_child_tail(struct isoent *parent, struct isoent *child) +{ + + if (!__archive_rb_tree_insert_node( + &(parent->rbtree), (struct archive_rb_node *)child)) + return (0); + child->chnext = NULL; + *parent->children.last = child; + parent->children.last = &(child->chnext); + parent->children.cnt++; + child->parent = parent; + + /* Add a child to a sub-directory chain */ + child->drnext = NULL; + if (child->dir) { + *parent->subdirs.last = child; + parent->subdirs.last = &(child->drnext); + parent->subdirs.cnt++; + child->parent = parent; + } + return (1); +} + +static void +isoent_remove_child(struct isoent *parent, struct isoent *child) +{ + struct isoent *ent; + + /* Remove a child entry from children chain. */ + ent = parent->children.first; + while (ent->chnext != child) + ent = ent->chnext; + if ((ent->chnext = ent->chnext->chnext) == NULL) + parent->children.last = &(ent->chnext); + parent->children.cnt--; + + if (child->dir) { + /* Remove a child entry from sub-directory chain. */ + ent = parent->subdirs.first; + while (ent->drnext != child) + ent = ent->drnext; + if ((ent->drnext = ent->drnext->drnext) == NULL) + parent->subdirs.last = &(ent->drnext); + parent->subdirs.cnt--; + } + + __archive_rb_tree_remove_node(&(parent->rbtree), + (struct archive_rb_node *)child); +} + +static int +isoent_clone_tree(struct archive_write *a, struct isoent **nroot, + struct isoent *root) +{ + struct isoent *np, *xroot, *newent; + + np = root; + xroot = NULL; + do { + newent = isoent_clone(np); + if (newent == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + if (xroot == NULL) { + *nroot = xroot = newent; + newent->parent = xroot; + } else + isoent_add_child_tail(xroot, newent); + if (np->dir && np->children.first != NULL) { + /* Enter to sub directories. */ + np = np->children.first; + xroot = newent; + continue; + } + while (np != np->parent) { + if (np->chnext == NULL) { + /* Return to the parent directory. */ + np = np->parent; + xroot = xroot->parent; + } else { + np = np->chnext; + break; + } + } + } while (np != np->parent); + + return (ARCHIVE_OK); +} + +/* + * Setup directory locations. + */ +static void +isoent_setup_directory_location(struct iso9660 *iso9660, int location, + struct vdd *vdd) +{ + struct isoent *np; + int depth; + + vdd->total_dir_block = 0; + depth = 0; + np = vdd->rootent; + do { + int block; + + np->dir_block = calculate_directory_descriptors( + iso9660, vdd, np, depth); + vdd->total_dir_block += np->dir_block; + np->dir_location = location; + location += np->dir_block; + block = extra_setup_location(np, location); + vdd->total_dir_block += block; + location += block; + + if (np->subdirs.first != NULL && depth + 1 < vdd->max_depth) { + /* Enter to sub directories. */ + np = np->subdirs.first; + depth++; + continue; + } + while (np != np->parent) { + if (np->drnext == NULL) { + /* Return to the parent directory. */ + np = np->parent; + depth--; + } else { + np = np->drnext; + break; + } + } + } while (np != np->parent); +} + +static void +_isoent_file_location(struct iso9660 *iso9660, struct isoent *isoent, + int *symlocation) +{ + struct isoent **children; + int n; + + if (isoent->children.cnt == 0) + return; + + children = isoent->children_sorted; + for (n = 0; n < isoent->children.cnt; n++) { + struct isoent *np; + struct isofile *file; + + np = children[n]; + if (np->dir) + continue; + if (np == iso9660->el_torito.boot) + continue; + file = np->file; + if (file->boot || file->hardlink_target != NULL) + continue; + if (archive_entry_filetype(file->entry) == AE_IFLNK || + file->content.size == 0) { + /* + * Do not point a valid location. + * Make sure entry is not hardlink file. + */ + file->content.location = (*symlocation)--; + continue; + } + + file->write_content = 1; + } +} + +/* + * Setup file locations. + */ +static void +isoent_setup_file_location(struct iso9660 *iso9660, int location) +{ + struct isoent *isoent; + struct isoent *np; + struct isofile *file; + size_t size; + int block; + int depth; + int joliet; + int symlocation; + int total_block; + + iso9660->total_file_block = 0; + if ((isoent = iso9660->el_torito.catalog) != NULL) { + isoent->file->content.location = location; + block = (int)((archive_entry_size(isoent->file->entry) + + LOGICAL_BLOCK_SIZE -1) >> LOGICAL_BLOCK_BITS); + location += block; + iso9660->total_file_block += block; + } + if ((isoent = iso9660->el_torito.boot) != NULL) { + isoent->file->content.location = location; + size = fd_boot_image_size(iso9660->el_torito.media_type); + if (size == 0) + size = (size_t)archive_entry_size(isoent->file->entry); + block = ((int)size + LOGICAL_BLOCK_SIZE -1) + >> LOGICAL_BLOCK_BITS; + location += block; + iso9660->total_file_block += block; + isoent->file->content.blocks = block; + } + + depth = 0; + symlocation = -16; + if (!iso9660->opt.rr && iso9660->opt.joliet) { + joliet = 1; + np = iso9660->joliet.rootent; + } else { + joliet = 0; + np = iso9660->primary.rootent; + } + do { + _isoent_file_location(iso9660, np, &symlocation); + + if (np->subdirs.first != NULL && + (joliet || + ((iso9660->opt.rr == OPT_RR_DISABLED && + depth + 2 < iso9660->primary.max_depth) || + (iso9660->opt.rr && + depth + 1 < iso9660->primary.max_depth)))) { + /* Enter to sub directories. */ + np = np->subdirs.first; + depth++; + continue; + } + while (np != np->parent) { + if (np->drnext == NULL) { + /* Return to the parent directory. */ + np = np->parent; + depth--; + } else { + np = np->drnext; + break; + } + } + } while (np != np->parent); + + total_block = 0; + for (file = iso9660->data_file_list.first; + file != NULL; file = file->datanext) { + + if (!file->write_content) + continue; + + file->cur_content = &(file->content); + do { + file->cur_content->location = location; + location += file->cur_content->blocks; + total_block += file->cur_content->blocks; + /* Next fragment */ + file->cur_content = file->cur_content->next; + } while (file->cur_content != NULL); + } + iso9660->total_file_block += total_block; +} + +static int +get_path_component(char *name, size_t n, const char *fn) +{ + char *p; + size_t l; + + p = strchr(fn, '/'); + if (p == NULL) { + if ((l = strlen(fn)) == 0) + return (0); + } else + l = p - fn; + if (l > n -1) + return (-1); + memcpy(name, fn, l); + name[l] = '\0'; + + return ((int)l); +} + +/* + * Add a new entry into the tree. + */ +static int +isoent_tree(struct archive_write *a, struct isoent **isoentpp) +{ +#if defined(_WIN32) && !defined(__CYGWIN__) + char name[_MAX_FNAME];/* Included null terminator size. */ +#elif defined(NAME_MAX) && NAME_MAX >= 255 + char name[NAME_MAX+1]; +#else + char name[256]; +#endif + struct iso9660 *iso9660 = a->format_data; + struct isoent *dent, *isoent, *np; + struct isofile *f1, *f2; + const char *fn, *p; + int l; + + isoent = *isoentpp; + dent = iso9660->primary.rootent; + if (isoent->file->parentdir.length > 0) + fn = p = isoent->file->parentdir.s; + else + fn = p = ""; + + /* + * If the path of the parent directory of `isoent' entry is + * the same as the path of `cur_dirent', add isoent to + * `cur_dirent'. + */ + if (archive_strlen(&(iso9660->cur_dirstr)) + == archive_strlen(&(isoent->file->parentdir)) && + strcmp(iso9660->cur_dirstr.s, fn) == 0) { + if (!isoent_add_child_tail(iso9660->cur_dirent, isoent)) { + np = (struct isoent *)__archive_rb_tree_find_node( + &(iso9660->cur_dirent->rbtree), + isoent->file->basename.s); + goto same_entry; + } + return (ARCHIVE_OK); + } + + for (;;) { + l = get_path_component(name, sizeof(name), fn); + if (l == 0) { + np = NULL; + break; + } + if (l < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "A name buffer is too small"); + _isoent_free(isoent); + return (ARCHIVE_FATAL); + } + + np = isoent_find_child(dent, name); + if (np == NULL || fn[0] == '\0') + break; + + /* Find next subdirectory. */ + if (!np->dir) { + /* NOT Directory! */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "`%s' is not directory, we cannot insert `%s' ", + archive_entry_pathname(np->file->entry), + archive_entry_pathname(isoent->file->entry)); + _isoent_free(isoent); + *isoentpp = NULL; + return (ARCHIVE_FAILED); + } + fn += l; + if (fn[0] == '/') + fn++; + dent = np; + } + if (np == NULL) { + /* + * Create virtual parent directories. + */ + while (fn[0] != '\0') { + struct isoent *vp; + struct archive_string as; + + archive_string_init(&as); + archive_strncat(&as, p, fn - p + l); + if (as.s[as.length-1] == '/') { + as.s[as.length-1] = '\0'; + as.length--; + } + vp = isoent_create_virtual_dir(a, iso9660, as.s); + if (vp == NULL) { + archive_string_free(&as); + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + _isoent_free(isoent); + *isoentpp = NULL; + return (ARCHIVE_FATAL); + } + archive_string_free(&as); + + if (vp->file->dircnt > iso9660->dircnt_max) + iso9660->dircnt_max = vp->file->dircnt; + isoent_add_child_tail(dent, vp); + np = vp; + + fn += l; + if (fn[0] == '/') + fn++; + l = get_path_component(name, sizeof(name), fn); + if (l < 0) { + archive_string_free(&as); + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "A name buffer is too small"); + _isoent_free(isoent); + *isoentpp = NULL; + return (ARCHIVE_FATAL); + } + dent = np; + } + + /* Found out the parent directory where isoent can be + * inserted. */ + iso9660->cur_dirent = dent; + archive_string_empty(&(iso9660->cur_dirstr)); + archive_string_ensure(&(iso9660->cur_dirstr), + archive_strlen(&(dent->file->parentdir)) + + archive_strlen(&(dent->file->basename)) + 2); + if (archive_strlen(&(dent->file->parentdir)) + + archive_strlen(&(dent->file->basename)) == 0) + iso9660->cur_dirstr.s[0] = 0; + else { + if (archive_strlen(&(dent->file->parentdir)) > 0) { + archive_string_copy(&(iso9660->cur_dirstr), + &(dent->file->parentdir)); + archive_strappend_char(&(iso9660->cur_dirstr), '/'); + } + archive_string_concat(&(iso9660->cur_dirstr), + &(dent->file->basename)); + } + + if (!isoent_add_child_tail(dent, isoent)) { + np = (struct isoent *)__archive_rb_tree_find_node( + &(dent->rbtree), isoent->file->basename.s); + goto same_entry; + } + return (ARCHIVE_OK); + } + +same_entry: + /* + * We have already has the entry the filename of which is + * the same. + */ + f1 = np->file; + f2 = isoent->file; + + /* If the file type of entries is different, + * we cannot handle it. */ + if (archive_entry_filetype(f1->entry) != + archive_entry_filetype(f2->entry)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Found duplicate entries `%s' and its file type is " + "different", + archive_entry_pathname(f1->entry)); + _isoent_free(isoent); + *isoentpp = NULL; + return (ARCHIVE_FAILED); + } + + /* Swap file entries. */ + np->file = f2; + isoent->file = f1; + np->virtual = 0; + + _isoent_free(isoent); + *isoentpp = np; + return (ARCHIVE_OK); +} + +/* + * Find a entry from `isoent' + */ +static struct isoent * +isoent_find_child(struct isoent *isoent, const char *child_name) +{ + struct isoent *np; + + np = (struct isoent *)__archive_rb_tree_find_node( + &(isoent->rbtree), child_name); + return (np); +} + +/* + * Find a entry full-path of which is specified by `fn' parameter, + * in the tree. + */ +static struct isoent * +isoent_find_entry(struct isoent *rootent, const char *fn) +{ +#if defined(_WIN32) && !defined(__CYGWIN__) + char name[_MAX_FNAME];/* Included null terminator size. */ +#elif defined(NAME_MAX) && NAME_MAX >= 255 + char name[NAME_MAX+1]; +#else + char name[256]; +#endif + struct isoent *isoent, *np; + int l; + + isoent = rootent; + np = NULL; + for (;;) { + l = get_path_component(name, sizeof(name), fn); + if (l == 0) + break; + fn += l; + if (fn[0] == '/') + fn++; + + np = isoent_find_child(isoent, name); + if (np == NULL) + break; + if (fn[0] == '\0') + break;/* We found out the entry */ + + /* Try sub directory. */ + isoent = np; + np = NULL; + if (!isoent->dir) + break;/* Not directory */ + } + + return (np); +} + +/* + * Following idr_* functions are used for resolving duplicated filenames + * and unreceivable filenames to generate ISO9660/Joliet Identifiers. + */ + +static void +idr_relaxed_filenames(char *map) +{ + int i; + + for (i = 0x21; i <= 0x2F; i++) + map[i] = 1; + for (i = 0x3A; i <= 0x41; i++) + map[i] = 1; + for (i = 0x5B; i <= 0x5E; i++) + map[i] = 1; + map[0x60] = 1; + for (i = 0x7B; i <= 0x7E; i++) + map[i] = 1; +} + +static void +idr_init(struct iso9660 *iso9660, struct vdd *vdd, struct idr *idr) +{ + + idr->idrent_pool = NULL; + idr->pool_size = 0; + if (vdd->vdd_type != VDD_JOLIET) { + if (iso9660->opt.iso_level <= 3) { + memcpy(idr->char_map, d_characters_map, + sizeof(idr->char_map)); + } else { + memcpy(idr->char_map, d1_characters_map, + sizeof(idr->char_map)); + idr_relaxed_filenames(idr->char_map); + } + } +} + +static void +idr_cleanup(struct idr *idr) +{ + free(idr->idrent_pool); +} + +static int +idr_ensure_poolsize(struct archive_write *a, struct idr *idr, + int cnt) +{ + + if (idr->pool_size < cnt) { + void *p; + const int bk = (1 << 7) - 1; + int psize; + + psize = (cnt + bk) & ~bk; + p = realloc(idr->idrent_pool, sizeof(struct idrent) * psize); + if (p == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + idr->idrent_pool = (struct idrent *)p; + idr->pool_size = psize; + } + return (ARCHIVE_OK); +} + +static int +idr_start(struct archive_write *a, struct idr *idr, int cnt, int ffmax, + int num_size, int null_size, const struct archive_rb_tree_ops *rbt_ops) +{ + int r; + + (void)ffmax; /* UNUSED */ + + r = idr_ensure_poolsize(a, idr, cnt); + if (r != ARCHIVE_OK) + return (r); + __archive_rb_tree_init(&(idr->rbtree), rbt_ops); + idr->wait_list.first = NULL; + idr->wait_list.last = &(idr->wait_list.first); + idr->pool_idx = 0; + idr->num_size = num_size; + idr->null_size = null_size; + return (ARCHIVE_OK); +} + +static void +idr_register(struct idr *idr, struct isoent *isoent, int weight, int noff) +{ + struct idrent *idrent, *n; + + idrent = &(idr->idrent_pool[idr->pool_idx++]); + idrent->wnext = idrent->avail = NULL; + idrent->isoent = isoent; + idrent->weight = weight; + idrent->noff = noff; + idrent->rename_num = 0; + + if (!__archive_rb_tree_insert_node(&(idr->rbtree), &(idrent->rbnode))) { + n = (struct idrent *)__archive_rb_tree_find_node( + &(idr->rbtree), idrent->isoent); + if (n != NULL) { + /* this `idrent' needs to rename. */ + idrent->avail = n; + *idr->wait_list.last = idrent; + idr->wait_list.last = &(idrent->wnext); + } + } +} + +static void +idr_extend_identifier(struct idrent *wnp, int numsize, int nullsize) +{ + unsigned char *p; + int wnp_ext_off; + + wnp_ext_off = wnp->isoent->ext_off; + if (wnp->noff + numsize != wnp_ext_off) { + p = (unsigned char *)wnp->isoent->identifier; + /* Extend the filename; foo.c --> foo___.c */ + memmove(p + wnp->noff + numsize, p + wnp_ext_off, + wnp->isoent->ext_len + nullsize); + wnp->isoent->ext_off = wnp_ext_off = wnp->noff + numsize; + wnp->isoent->id_len = wnp_ext_off + wnp->isoent->ext_len; + } +} + +static void +idr_resolve(struct idr *idr, void (*fsetnum)(unsigned char *p, int num)) +{ + struct idrent *n; + unsigned char *p; + + for (n = idr->wait_list.first; n != NULL; n = n->wnext) { + idr_extend_identifier(n, idr->num_size, idr->null_size); + p = (unsigned char *)n->isoent->identifier + n->noff; + do { + fsetnum(p, n->avail->rename_num++); + } while (!__archive_rb_tree_insert_node( + &(idr->rbtree), &(n->rbnode))); + } +} + +static void +idr_set_num(unsigned char *p, int num) +{ + static const char xdig[] = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', + 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', + 'U', 'V', 'W', 'X', 'Y', 'Z' + }; + + num %= sizeof(xdig) * sizeof(xdig) * sizeof(xdig); + p[0] = xdig[(num / (sizeof(xdig) * sizeof(xdig)))]; + num %= sizeof(xdig) * sizeof(xdig); + p[1] = xdig[ (num / sizeof(xdig))]; + num %= sizeof(xdig); + p[2] = xdig[num]; +} + +static void +idr_set_num_beutf16(unsigned char *p, int num) +{ + static const uint16_t xdig[] = { + 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, + 0x0036, 0x0037, 0x0038, 0x0039, + 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, + 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, + 0x004D, 0x004E, 0x004F, 0x0050, 0x0051, 0x0052, + 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, + 0x0059, 0x005A + }; +#define XDIG_CNT (sizeof(xdig)/sizeof(xdig[0])) + + num %= XDIG_CNT * XDIG_CNT * XDIG_CNT; + archive_be16enc(p, xdig[(num / (XDIG_CNT * XDIG_CNT))]); + num %= XDIG_CNT * XDIG_CNT; + archive_be16enc(p+2, xdig[ (num / XDIG_CNT)]); + num %= XDIG_CNT; + archive_be16enc(p+4, xdig[num]); +} + +/* + * Generate ISO9660 Identifier. + */ +static int +isoent_gen_iso9660_identifier(struct archive_write *a, struct isoent *isoent, + struct idr *idr) +{ + struct iso9660 *iso9660; + struct isoent *np; + char *p; + int l, r; + const char *char_map; + char allow_ldots, allow_multidot, allow_period, allow_vernum; + int fnmax, ffmax, dnmax; + static const struct archive_rb_tree_ops rb_ops = { + isoent_cmp_node_iso9660, isoent_cmp_key_iso9660 + }; + + if (isoent->children.cnt == 0) + return (0); + + iso9660 = a->format_data; + char_map = idr->char_map; + if (iso9660->opt.iso_level <= 3) { + allow_ldots = 0; + allow_multidot = 0; + allow_period = 1; + allow_vernum = iso9660->opt.allow_vernum; + if (iso9660->opt.iso_level == 1) { + fnmax = 8; + ffmax = 12;/* fnmax + '.' + 3 */ + dnmax = 8; + } else { + fnmax = 30; + ffmax = 31; + dnmax = 31; + } + } else { + allow_ldots = allow_multidot = 1; + allow_period = allow_vernum = 0; + if (iso9660->opt.rr) + /* + * MDR : The maximum size of Directory Record(254). + * DRL : A Directory Record Length(33). + * CE : A size of SUSP CE System Use Entry(28). + * MDR - DRL - CE = 254 - 33 - 28 = 193. + */ + fnmax = ffmax = dnmax = 193; + else + /* + * XA : CD-ROM XA System Use Extension + * Information(14). + * MDR - DRL - XA = 254 - 33 -14 = 207. + */ + fnmax = ffmax = dnmax = 207; + } + + r = idr_start(a, idr, isoent->children.cnt, ffmax, 3, 1, &rb_ops); + if (r < 0) + return (r); + + for (np = isoent->children.first; np != NULL; np = np->chnext) { + char *dot, *xdot; + int ext_off, noff, weight; + + l = (int)np->file->basename.length; + p = malloc(l+31+2+1); + if (p == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + memcpy(p, np->file->basename.s, l); + p[l] = '\0'; + np->identifier = p; + + dot = xdot = NULL; + if (!allow_ldots) { + /* + * If there is a '.' character at the first byte, + * it has to be replaced by '_' character. + */ + if (*p == '.') + *p++ = '_'; + } + for (;*p; p++) { + if (*p & 0x80) { + *p = '_'; + continue; + } + if (char_map[(unsigned char)*p]) { + /* if iso-level is '4', a character '.' is + * allowed by char_map. */ + if (*p == '.') { + xdot = dot; + dot = p; + } + continue; + } + if (*p >= 'a' && *p <= 'z') { + *p -= 'a' - 'A'; + continue; + } + if (*p == '.') { + xdot = dot; + dot = p; + if (allow_multidot) + continue; + } + *p = '_'; + } + p = np->identifier; + weight = -1; + if (dot == NULL) { + int nammax; + + if (np->dir) + nammax = dnmax; + else + nammax = fnmax; + + if (l > nammax) { + p[nammax] = '\0'; + weight = nammax; + ext_off = nammax; + } else + ext_off = l; + } else { + *dot = '.'; + ext_off = (int)(dot - p); + + if (iso9660->opt.iso_level == 1) { + if (dot - p <= 8) { + if (strlen(dot) > 4) { + /* A length of a file extension + * must be less than 4 */ + dot[4] = '\0'; + weight = 0; + } + } else { + p[8] = dot[0]; + p[9] = dot[1]; + p[10] = dot[2]; + p[11] = dot[3]; + p[12] = '\0'; + weight = 8; + ext_off = 8; + } + } else if (np->dir) { + if (l > dnmax) { + p[dnmax] = '\0'; + weight = dnmax; + if (ext_off > dnmax) + ext_off = dnmax; + } + } else if (l > ffmax) { + int extlen = (int)strlen(dot); + int xdoff; + + if (xdot != NULL) + xdoff = (int)(xdot - p); + else + xdoff = 0; + + if (extlen > 1 && xdoff < fnmax-1) { + int off; + + if (extlen > ffmax) + extlen = ffmax; + off = ffmax - extlen; + if (off == 0) { + /* A dot('.') character + * doesn't place to the first + * byte of identifier. */ + off ++; + extlen --; + } + memmove(p+off, dot, extlen); + p[ffmax] = '\0'; + ext_off = off; + weight = off; +#ifdef COMPAT_MKISOFS + } else if (xdoff >= fnmax-1) { + /* Simulate a bug(?) of mkisofs. */ + p[fnmax-1] = '\0'; + ext_off = fnmax-1; + weight = fnmax-1; +#endif + } else { + p[fnmax] = '\0'; + ext_off = fnmax; + weight = fnmax; + } + } + } + /* Save an offset of a file name extension to sort files. */ + np->ext_off = ext_off; + np->ext_len = (int)strlen(&p[ext_off]); + np->id_len = l = ext_off + np->ext_len; + + /* Make an offset of the number which is used to be set + * hexadecimal number to avoid duplicate identifier. */ + if (iso9660->opt.iso_level == 1) { + if (ext_off >= 5) + noff = 5; + else + noff = ext_off; + } else { + if (l == ffmax) + noff = ext_off - 3; + else if (l == ffmax-1) + noff = ext_off - 2; + else if (l == ffmax-2) + noff = ext_off - 1; + else + noff = ext_off; + } + /* Register entry to the identifier resolver. */ + idr_register(idr, np, weight, noff); + } + + /* Resolve duplicate identifier. */ + idr_resolve(idr, idr_set_num); + + /* Add a period and a version number to identifiers. */ + for (np = isoent->children.first; np != NULL; np = np->chnext) { + if (!np->dir && np->rr_child == NULL) { + p = np->identifier + np->ext_off + np->ext_len; + if (np->ext_len == 0 && allow_period) { + *p++ = '.'; + np->ext_len = 1; + } + if (np->ext_len == 1 && !allow_period) { + *--p = '\0'; + np->ext_len = 0; + } + np->id_len = np->ext_off + np->ext_len; + if (allow_vernum) { + *p++ = ';'; + *p++ = '1'; + np->id_len += 2; + } + *p = '\0'; + } else + np->id_len = np->ext_off + np->ext_len; + np->mb_len = np->id_len; + } + return (ARCHIVE_OK); +} + +/* + * Generate Joliet Identifier. + */ +static int +isoent_gen_joliet_identifier(struct archive_write *a, struct isoent *isoent, + struct idr *idr) +{ + struct iso9660 *iso9660; + struct isoent *np; + unsigned char *p; + size_t l; + int r; + size_t ffmax, parent_len; + static const struct archive_rb_tree_ops rb_ops = { + isoent_cmp_node_joliet, isoent_cmp_key_joliet + }; + + if (isoent->children.cnt == 0) + return (0); + + iso9660 = a->format_data; + if (iso9660->opt.joliet == OPT_JOLIET_LONGNAME) + ffmax = 206; + else + ffmax = 128; + + r = idr_start(a, idr, isoent->children.cnt, (int)ffmax, 6, 2, &rb_ops); + if (r < 0) + return (r); + + parent_len = 1; + for (np = isoent; np->parent != np; np = np->parent) + parent_len += np->mb_len + 1; + + for (np = isoent->children.first; np != NULL; np = np->chnext) { + unsigned char *dot; + int ext_off, noff, weight; + size_t lt; + + if ((l = np->file->basename_utf16.length) > ffmax) + l = ffmax; + + p = malloc((l+1)*2); + if (p == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + memcpy(p, np->file->basename_utf16.s, l); + p[l] = 0; + p[l+1] = 0; + + np->identifier = (char *)p; + lt = l; + dot = p + l; + weight = 0; + while (lt > 0) { + if (!joliet_allowed_char(p[0], p[1])) + archive_be16enc(p, 0x005F); /* '_' */ + else if (p[0] == 0 && p[1] == 0x2E) /* '.' */ + dot = p; + p += 2; + lt -= 2; + } + ext_off = (int)(dot - (unsigned char *)np->identifier); + np->ext_off = ext_off; + np->ext_len = (int)l - ext_off; + np->id_len = (int)l; + + /* + * Get a length of MBS of a full-pathname. + */ + if (np->file->basename_utf16.length > ffmax) { + if (archive_strncpy_l(&iso9660->mbs, + (const char *)np->identifier, l, + iso9660->sconv_from_utf16be) != 0 && + errno == ENOMEM) { + archive_set_error(&a->archive, errno, + "No memory"); + return (ARCHIVE_FATAL); + } + np->mb_len = (int)iso9660->mbs.length; + if (np->mb_len != (int)np->file->basename.length) + weight = np->mb_len; + } else + np->mb_len = (int)np->file->basename.length; + + /* If a length of full-pathname is longer than 240 bytes, + * it violates Joliet extensions regulation. */ + if (parent_len > 240 + || np->mb_len > 240 + || parent_len + np->mb_len > 240) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "The regulation of Joliet extensions;" + " A length of a full-pathname of `%s' is " + "longer than 240 bytes, (p=%d, b=%d)", + archive_entry_pathname(np->file->entry), + (int)parent_len, (int)np->mb_len); + return (ARCHIVE_FATAL); + } + + /* Make an offset of the number which is used to be set + * hexadecimal number to avoid duplicate identifier. */ + if (l == ffmax) + noff = ext_off - 6; + else if (l == ffmax-2) + noff = ext_off - 4; + else if (l == ffmax-4) + noff = ext_off - 2; + else + noff = ext_off; + /* Register entry to the identifier resolver. */ + idr_register(idr, np, weight, noff); + } + + /* Resolve duplicate identifier with Joliet Volume. */ + idr_resolve(idr, idr_set_num_beutf16); + + return (ARCHIVE_OK); +} + +/* + * This comparing rule is according to ISO9660 Standard 9.3 + */ +static int +isoent_cmp_iso9660_identifier(const struct isoent *p1, const struct isoent *p2) +{ + const char *s1, *s2; + int cmp; + int l; + + s1 = p1->identifier; + s2 = p2->identifier; + + /* Compare File Name */ + l = p1->ext_off; + if (l > p2->ext_off) + l = p2->ext_off; + cmp = memcmp(s1, s2, l); + if (cmp != 0) + return (cmp); + if (p1->ext_off < p2->ext_off) { + s2 += l; + l = p2->ext_off - p1->ext_off; + while (l--) + if (0x20 != *s2++) + return (0x20 + - *(const unsigned char *)(s2 - 1)); + } else if (p1->ext_off > p2->ext_off) { + s1 += l; + l = p1->ext_off - p2->ext_off; + while (l--) + if (0x20 != *s1++) + return (*(const unsigned char *)(s1 - 1) + - 0x20); + } + /* Compare File Name Extension */ + if (p1->ext_len == 0 && p2->ext_len == 0) + return (0); + if (p1->ext_len == 1 && p2->ext_len == 1) + return (0); + if (p1->ext_len <= 1) + return (-1); + if (p2->ext_len <= 1) + return (1); + l = p1->ext_len; + if (l > p2->ext_len) + l = p2->ext_len; + s1 = p1->identifier + p1->ext_off; + s2 = p2->identifier + p2->ext_off; + if (l > 1) { + cmp = memcmp(s1, s2, l); + if (cmp != 0) + return (cmp); + } + if (p1->ext_len < p2->ext_len) { + s2 += l; + l = p2->ext_len - p1->ext_len; + while (l--) + if (0x20 != *s2++) + return (0x20 + - *(const unsigned char *)(s2 - 1)); + } else if (p1->ext_len > p2->ext_len) { + s1 += l; + l = p1->ext_len - p2->ext_len; + while (l--) + if (0x20 != *s1++) + return (*(const unsigned char *)(s1 - 1) + - 0x20); + } + /* Compare File Version Number */ + /* No operation. The File Version Number is always one. */ + + return (cmp); +} + +static int +isoent_cmp_node_iso9660(const struct archive_rb_node *n1, + const struct archive_rb_node *n2) +{ + const struct idrent *e1 = (const struct idrent *)n1; + const struct idrent *e2 = (const struct idrent *)n2; + + return (isoent_cmp_iso9660_identifier(e2->isoent, e1->isoent)); +} + +static int +isoent_cmp_key_iso9660(const struct archive_rb_node *node, const void *key) +{ + const struct isoent *isoent = (const struct isoent *)key; + const struct idrent *idrent = (const struct idrent *)node; + + return (isoent_cmp_iso9660_identifier(isoent, idrent->isoent)); +} + +static int +isoent_cmp_joliet_identifier(const struct isoent *p1, const struct isoent *p2) +{ + const unsigned char *s1, *s2; + int cmp; + int l; + + s1 = (const unsigned char *)p1->identifier; + s2 = (const unsigned char *)p2->identifier; + + /* Compare File Name */ + l = p1->ext_off; + if (l > p2->ext_off) + l = p2->ext_off; + cmp = memcmp(s1, s2, l); + if (cmp != 0) + return (cmp); + if (p1->ext_off < p2->ext_off) { + s2 += l; + l = p2->ext_off - p1->ext_off; + while (l--) + if (0 != *s2++) + return (- *(const unsigned char *)(s2 - 1)); + } else if (p1->ext_off > p2->ext_off) { + s1 += l; + l = p1->ext_off - p2->ext_off; + while (l--) + if (0 != *s1++) + return (*(const unsigned char *)(s1 - 1)); + } + /* Compare File Name Extension */ + if (p1->ext_len == 0 && p2->ext_len == 0) + return (0); + if (p1->ext_len == 2 && p2->ext_len == 2) + return (0); + if (p1->ext_len <= 2) + return (-1); + if (p2->ext_len <= 2) + return (1); + l = p1->ext_len; + if (l > p2->ext_len) + l = p2->ext_len; + s1 = (unsigned char *)(p1->identifier + p1->ext_off); + s2 = (unsigned char *)(p2->identifier + p2->ext_off); + if (l > 1) { + cmp = memcmp(s1, s2, l); + if (cmp != 0) + return (cmp); + } + if (p1->ext_len < p2->ext_len) { + s2 += l; + l = p2->ext_len - p1->ext_len; + while (l--) + if (0 != *s2++) + return (- *(const unsigned char *)(s2 - 1)); + } else if (p1->ext_len > p2->ext_len) { + s1 += l; + l = p1->ext_len - p2->ext_len; + while (l--) + if (0 != *s1++) + return (*(const unsigned char *)(s1 - 1)); + } + /* Compare File Version Number */ + /* No operation. The File Version Number is always one. */ + + return (cmp); +} + +static int +isoent_cmp_node_joliet(const struct archive_rb_node *n1, + const struct archive_rb_node *n2) +{ + const struct idrent *e1 = (const struct idrent *)n1; + const struct idrent *e2 = (const struct idrent *)n2; + + return (isoent_cmp_joliet_identifier(e2->isoent, e1->isoent)); +} + +static int +isoent_cmp_key_joliet(const struct archive_rb_node *node, const void *key) +{ + const struct isoent *isoent = (const struct isoent *)key; + const struct idrent *idrent = (const struct idrent *)node; + + return (isoent_cmp_joliet_identifier(isoent, idrent->isoent)); +} + +static int +isoent_make_sorted_files(struct archive_write *a, struct isoent *isoent, + struct idr *idr) +{ + struct archive_rb_node *rn; + struct isoent **children; + + children = malloc(isoent->children.cnt * sizeof(struct isoent *)); + if (children == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + isoent->children_sorted = children; + + ARCHIVE_RB_TREE_FOREACH(rn, &(idr->rbtree)) { + struct idrent *idrent = (struct idrent *)rn; + *children ++ = idrent->isoent; + } + return (ARCHIVE_OK); +} + +/* + * - Generate ISO9660 and Joliet identifiers from basenames. + * - Sort files by each directory. + */ +static int +isoent_traverse_tree(struct archive_write *a, struct vdd* vdd) +{ + struct iso9660 *iso9660 = a->format_data; + struct isoent *np; + struct idr idr; + int depth; + int r; + int (*genid)(struct archive_write *, struct isoent *, struct idr *); + + idr_init(iso9660, vdd, &idr); + np = vdd->rootent; + depth = 0; + if (vdd->vdd_type == VDD_JOLIET) + genid = isoent_gen_joliet_identifier; + else + genid = isoent_gen_iso9660_identifier; + do { + if (np->virtual && + !archive_entry_mtime_is_set(np->file->entry)) { + /* Set properly times to virtual directory */ + archive_entry_set_mtime(np->file->entry, + iso9660->birth_time, 0); + archive_entry_set_atime(np->file->entry, + iso9660->birth_time, 0); + archive_entry_set_ctime(np->file->entry, + iso9660->birth_time, 0); + } + if (np->children.first != NULL) { + if (vdd->vdd_type != VDD_JOLIET && + !iso9660->opt.rr && depth + 1 >= vdd->max_depth) { + if (np->children.cnt > 0) + iso9660->directories_too_deep = np; + } else { + /* Generate Identifier */ + r = genid(a, np, &idr); + if (r < 0) + goto exit_traverse_tree; + r = isoent_make_sorted_files(a, np, &idr); + if (r < 0) + goto exit_traverse_tree; + + if (np->subdirs.first != NULL && + depth + 1 < vdd->max_depth) { + /* Enter to sub directories. */ + np = np->subdirs.first; + depth++; + continue; + } + } + } + while (np != np->parent) { + if (np->drnext == NULL) { + /* Return to the parent directory. */ + np = np->parent; + depth--; + } else { + np = np->drnext; + break; + } + } + } while (np != np->parent); + + r = ARCHIVE_OK; +exit_traverse_tree: + idr_cleanup(&idr); + + return (r); +} + +/* + * Collect directory entries into path_table by a directory depth. + */ +static int +isoent_collect_dirs(struct vdd *vdd, struct isoent *rootent, int depth) +{ + struct isoent *np; + + if (rootent == NULL) + rootent = vdd->rootent; + np = rootent; + do { + /* Register current directory to pathtable. */ + path_table_add_entry(&(vdd->pathtbl[depth]), np); + + if (np->subdirs.first != NULL && depth + 1 < vdd->max_depth) { + /* Enter to sub directories. */ + np = np->subdirs.first; + depth++; + continue; + } + while (np != rootent) { + if (np->drnext == NULL) { + /* Return to the parent directory. */ + np = np->parent; + depth--; + } else { + np = np->drnext; + break; + } + } + } while (np != rootent); + + return (ARCHIVE_OK); +} + +/* + * The entry whose number of levels in a directory hierarchy is + * large than eight relocate to rr_move directory. + */ +static int +isoent_rr_move_dir(struct archive_write *a, struct isoent **rr_moved, + struct isoent *curent, struct isoent **newent) +{ + struct iso9660 *iso9660 = a->format_data; + struct isoent *rrmoved, *mvent, *np; + + if ((rrmoved = *rr_moved) == NULL) { + struct isoent *rootent = iso9660->primary.rootent; + /* There isn't rr_move entry. + * Create rr_move entry and insert it into the root entry. + */ + rrmoved = isoent_create_virtual_dir(a, iso9660, "rr_moved"); + if (rrmoved == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + /* Add "rr_moved" entry to the root entry. */ + isoent_add_child_head(rootent, rrmoved); + archive_entry_set_nlink(rootent->file->entry, + archive_entry_nlink(rootent->file->entry) + 1); + /* Register "rr_moved" entry to second level pathtable. */ + path_table_add_entry(&(iso9660->primary.pathtbl[1]), rrmoved); + /* Save rr_moved. */ + *rr_moved = rrmoved; + } + /* + * Make a clone of curent which is going to be relocated + * to rr_moved. + */ + mvent = isoent_clone(curent); + if (mvent == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + /* linking.. and use for creating "CL", "PL" and "RE" */ + mvent->rr_parent = curent->parent; + curent->rr_child = mvent; + /* + * Move subdirectories from the curent to mvent + */ + if (curent->children.first != NULL) { + *mvent->children.last = curent->children.first; + mvent->children.last = curent->children.last; + } + for (np = mvent->children.first; np != NULL; np = np->chnext) + np->parent = mvent; + mvent->children.cnt = curent->children.cnt; + curent->children.cnt = 0; + curent->children.first = NULL; + curent->children.last = &curent->children.first; + + if (curent->subdirs.first != NULL) { + *mvent->subdirs.last = curent->subdirs.first; + mvent->subdirs.last = curent->subdirs.last; + } + mvent->subdirs.cnt = curent->subdirs.cnt; + curent->subdirs.cnt = 0; + curent->subdirs.first = NULL; + curent->subdirs.last = &curent->subdirs.first; + + /* + * The mvent becomes a child of the rr_moved entry. + */ + isoent_add_child_tail(rrmoved, mvent); + archive_entry_set_nlink(rrmoved->file->entry, + archive_entry_nlink(rrmoved->file->entry) + 1); + /* + * This entry which relocated to the rr_moved directory + * has to set the flag as a file. + * See also RRIP 4.1.5.1 Description of the "CL" System Use Entry. + */ + curent->dir = 0; + + *newent = mvent; + + return (ARCHIVE_OK); +} + +static int +isoent_rr_move(struct archive_write *a) +{ + struct iso9660 *iso9660 = a->format_data; + struct path_table *pt; + struct isoent *rootent, *rr_moved; + struct isoent *np, *last; + int r; + + pt = &(iso9660->primary.pathtbl[MAX_DEPTH-1]); + /* There aren't level 8 directories reaching a deeper level. */ + if (pt->cnt == 0) + return (ARCHIVE_OK); + + rootent = iso9660->primary.rootent; + /* If "rr_moved" directory is already existing, + * we have to use it. */ + rr_moved = isoent_find_child(rootent, "rr_moved"); + if (rr_moved != NULL && + rr_moved != rootent->children.first) { + /* + * It's necessary that rr_move is the first entry + * of the root. + */ + /* Remove "rr_moved" entry from children chain. */ + isoent_remove_child(rootent, rr_moved); + + /* Add "rr_moved" entry into the head of children chain. */ + isoent_add_child_head(rootent, rr_moved); + } + + /* + * Check level 8 path_table. + * If find out sub directory entries, that entries move to rr_move. + */ + np = pt->first; + while (np != NULL) { + last = path_table_last_entry(pt); + for (; np != NULL; np = np->ptnext) { + struct isoent *mvent; + struct isoent *newent; + + if (!np->dir) + continue; + for (mvent = np->subdirs.first; + mvent != NULL; mvent = mvent->drnext) { + r = isoent_rr_move_dir(a, &rr_moved, + mvent, &newent); + if (r < 0) + return (r); + isoent_collect_dirs(&(iso9660->primary), + newent, 2); + } + } + /* If new entries are added to level 8 path_talbe, + * its sub directory entries move to rr_move too. + */ + np = last->ptnext; + } + + return (ARCHIVE_OK); +} + +/* + * This comparing rule is according to ISO9660 Standard 6.9.1 + */ +static int +_compare_path_table(const void *v1, const void *v2) +{ + const struct isoent *p1, *p2; + const char *s1, *s2; + int cmp, l; + + p1 = *((const struct isoent **)(uintptr_t)v1); + p2 = *((const struct isoent **)(uintptr_t)v2); + + /* Compare parent directory number */ + cmp = p1->parent->dir_number - p2->parent->dir_number; + if (cmp != 0) + return (cmp); + + /* Compare identifier */ + s1 = p1->identifier; + s2 = p2->identifier; + l = p1->ext_off; + if (l > p2->ext_off) + l = p2->ext_off; + cmp = strncmp(s1, s2, l); + if (cmp != 0) + return (cmp); + if (p1->ext_off < p2->ext_off) { + s2 += l; + l = p2->ext_off - p1->ext_off; + while (l--) + if (0x20 != *s2++) + return (0x20 + - *(const unsigned char *)(s2 - 1)); + } else if (p1->ext_off > p2->ext_off) { + s1 += l; + l = p1->ext_off - p2->ext_off; + while (l--) + if (0x20 != *s1++) + return (*(const unsigned char *)(s1 - 1) + - 0x20); + } + return (0); +} + +static int +_compare_path_table_joliet(const void *v1, const void *v2) +{ + const struct isoent *p1, *p2; + const unsigned char *s1, *s2; + int cmp, l; + + p1 = *((const struct isoent **)(uintptr_t)v1); + p2 = *((const struct isoent **)(uintptr_t)v2); + + /* Compare parent directory number */ + cmp = p1->parent->dir_number - p2->parent->dir_number; + if (cmp != 0) + return (cmp); + + /* Compare identifier */ + s1 = (const unsigned char *)p1->identifier; + s2 = (const unsigned char *)p2->identifier; + l = p1->ext_off; + if (l > p2->ext_off) + l = p2->ext_off; + cmp = memcmp(s1, s2, l); + if (cmp != 0) + return (cmp); + if (p1->ext_off < p2->ext_off) { + s2 += l; + l = p2->ext_off - p1->ext_off; + while (l--) + if (0 != *s2++) + return (- *(const unsigned char *)(s2 - 1)); + } else if (p1->ext_off > p2->ext_off) { + s1 += l; + l = p1->ext_off - p2->ext_off; + while (l--) + if (0 != *s1++) + return (*(const unsigned char *)(s1 - 1)); + } + return (0); +} + +static inline void +path_table_add_entry(struct path_table *pathtbl, struct isoent *ent) +{ + ent->ptnext = NULL; + *pathtbl->last = ent; + pathtbl->last = &(ent->ptnext); + pathtbl->cnt ++; +} + +static inline struct isoent * +path_table_last_entry(struct path_table *pathtbl) +{ + if (pathtbl->first == NULL) + return (NULL); + return (((struct isoent *)(void *) + ((char *)(pathtbl->last) - offsetof(struct isoent, ptnext)))); +} + +/* + * Sort directory entries in path_table + * and assign directory number to each entries. + */ +static int +isoent_make_path_table_2(struct archive_write *a, struct vdd *vdd, + int depth, int *dir_number) +{ + struct isoent *np; + struct isoent **enttbl; + struct path_table *pt; + int i; + + pt = &vdd->pathtbl[depth]; + if (pt->cnt == 0) { + pt->sorted = NULL; + return (ARCHIVE_OK); + } + enttbl = malloc(pt->cnt * sizeof(struct isoent *)); + if (enttbl == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + pt->sorted = enttbl; + for (np = pt->first; np != NULL; np = np->ptnext) + *enttbl ++ = np; + enttbl = pt->sorted; + + switch (vdd->vdd_type) { + case VDD_PRIMARY: + case VDD_ENHANCED: +#ifdef __COMPAR_FN_T + qsort(enttbl, pt->cnt, sizeof(struct isoent *), + (__compar_fn_t)_compare_path_table); +#else + qsort(enttbl, pt->cnt, sizeof(struct isoent *), + _compare_path_table); +#endif + break; + case VDD_JOLIET: +#ifdef __COMPAR_FN_T + qsort(enttbl, pt->cnt, sizeof(struct isoent *), + (__compar_fn_t)_compare_path_table_joliet); +#else + qsort(enttbl, pt->cnt, sizeof(struct isoent *), + _compare_path_table_joliet); +#endif + break; + } + for (i = 0; i < pt->cnt; i++) + enttbl[i]->dir_number = (*dir_number)++; + + return (ARCHIVE_OK); +} + +static int +isoent_alloc_path_table(struct archive_write *a, struct vdd *vdd, + int max_depth) +{ + int i; + + vdd->max_depth = max_depth; + vdd->pathtbl = malloc(sizeof(*vdd->pathtbl) * vdd->max_depth); + if (vdd->pathtbl == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + for (i = 0; i < vdd->max_depth; i++) { + vdd->pathtbl[i].first = NULL; + vdd->pathtbl[i].last = &(vdd->pathtbl[i].first); + vdd->pathtbl[i].sorted = NULL; + vdd->pathtbl[i].cnt = 0; + } + return (ARCHIVE_OK); +} + +/* + * Make Path Tables + */ +static int +isoent_make_path_table(struct archive_write *a) +{ + struct iso9660 *iso9660 = a->format_data; + int depth, r; + int dir_number; + + /* + * Init Path Table. + */ + if (iso9660->dircnt_max >= MAX_DEPTH && + (!iso9660->opt.limit_depth || iso9660->opt.iso_level == 4)) + r = isoent_alloc_path_table(a, &(iso9660->primary), + iso9660->dircnt_max + 1); + else + /* The number of levels in the hierarchy cannot exceed + * eight. */ + r = isoent_alloc_path_table(a, &(iso9660->primary), + MAX_DEPTH); + if (r < 0) + return (r); + if (iso9660->opt.joliet) { + r = isoent_alloc_path_table(a, &(iso9660->joliet), + iso9660->dircnt_max + 1); + if (r < 0) + return (r); + } + + /* Step 0. + * - Collect directories for primary and joliet. + */ + isoent_collect_dirs(&(iso9660->primary), NULL, 0); + if (iso9660->opt.joliet) + isoent_collect_dirs(&(iso9660->joliet), NULL, 0); + /* + * Rockridge; move deeper depth directories to rr_moved. + */ + if (iso9660->opt.rr) { + r = isoent_rr_move(a); + if (r < 0) + return (r); + } + + /* Update nlink. */ + isofile_connect_hardlink_files(iso9660); + + /* Step 1. + * - Renew a value of the depth of that directories. + * - Resolve hardlinks. + * - Convert pathnames to ISO9660 name or UCS2(joliet). + * - Sort files by each directory. + */ + r = isoent_traverse_tree(a, &(iso9660->primary)); + if (r < 0) + return (r); + if (iso9660->opt.joliet) { + r = isoent_traverse_tree(a, &(iso9660->joliet)); + if (r < 0) + return (r); + } + + /* Step 2. + * - Sort directories. + * - Assign all directory number. + */ + dir_number = 1; + for (depth = 0; depth < iso9660->primary.max_depth; depth++) { + r = isoent_make_path_table_2(a, &(iso9660->primary), + depth, &dir_number); + if (r < 0) + return (r); + } + if (iso9660->opt.joliet) { + dir_number = 1; + for (depth = 0; depth < iso9660->joliet.max_depth; depth++) { + r = isoent_make_path_table_2(a, &(iso9660->joliet), + depth, &dir_number); + if (r < 0) + return (r); + } + } + if (iso9660->opt.limit_dirs && dir_number > 0xffff) { + /* + * Maximum number of directories is 65535(0xffff) + * doe to size(16bit) of Parent Directory Number of + * the Path Table. + * See also ISO9660 Standard 9.4. + */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Too many directories(%d) over 65535.", dir_number); + return (ARCHIVE_FATAL); + } + + /* Get the size of the Path Table. */ + calculate_path_table_size(&(iso9660->primary)); + if (iso9660->opt.joliet) + calculate_path_table_size(&(iso9660->joliet)); + + return (ARCHIVE_OK); +} + +static int +isoent_find_out_boot_file(struct archive_write *a, struct isoent *rootent) +{ + struct iso9660 *iso9660 = a->format_data; + + /* Find a isoent of the boot file. */ + iso9660->el_torito.boot = isoent_find_entry(rootent, + iso9660->el_torito.boot_filename.s); + if (iso9660->el_torito.boot == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can't find the boot image file ``%s''", + iso9660->el_torito.boot_filename.s); + return (ARCHIVE_FATAL); + } + iso9660->el_torito.boot->file->boot = BOOT_IMAGE; + return (ARCHIVE_OK); +} + +static int +isoent_create_boot_catalog(struct archive_write *a, struct isoent *rootent) +{ + struct iso9660 *iso9660 = a->format_data; + struct isofile *file; + struct isoent *isoent; + struct archive_entry *entry; + + (void)rootent; /* UNUSED */ + /* + * Create the entry which is the "boot.catalog" file. + */ + file = isofile_new(a, NULL); + if (file == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + archive_entry_set_pathname(file->entry, + iso9660->el_torito.catalog_filename.s); + archive_entry_set_size(file->entry, LOGICAL_BLOCK_SIZE); + archive_entry_set_mtime(file->entry, iso9660->birth_time, 0); + archive_entry_set_atime(file->entry, iso9660->birth_time, 0); + archive_entry_set_ctime(file->entry, iso9660->birth_time, 0); + archive_entry_set_uid(file->entry, getuid()); + archive_entry_set_gid(file->entry, getgid()); + archive_entry_set_mode(file->entry, AE_IFREG | 0444); + archive_entry_set_nlink(file->entry, 1); + + if (isofile_gen_utility_names(a, file) < ARCHIVE_WARN) { + isofile_free(file); + return (ARCHIVE_FATAL); + } + file->boot = BOOT_CATALOG; + file->content.size = LOGICAL_BLOCK_SIZE; + isofile_add_entry(iso9660, file); + + isoent = isoent_new(file); + if (isoent == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + isoent->virtual = 1; + + /* Add the "boot.catalog" entry into tree */ + if (isoent_tree(a, &isoent) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + iso9660->el_torito.catalog = isoent; + /* + * Get a boot media type. + */ + switch (iso9660->opt.boot_type) { + default: + case OPT_BOOT_TYPE_AUTO: + /* Try detecting a media type of the boot image. */ + entry = iso9660->el_torito.boot->file->entry; + if (archive_entry_size(entry) == FD_1_2M_SIZE) + iso9660->el_torito.media_type = + BOOT_MEDIA_1_2M_DISKETTE; + else if (archive_entry_size(entry) == FD_1_44M_SIZE) + iso9660->el_torito.media_type = + BOOT_MEDIA_1_44M_DISKETTE; + else if (archive_entry_size(entry) == FD_2_88M_SIZE) + iso9660->el_torito.media_type = + BOOT_MEDIA_2_88M_DISKETTE; + else + /* We cannot decide whether the boot image is + * hard-disk. */ + iso9660->el_torito.media_type = + BOOT_MEDIA_NO_EMULATION; + break; + case OPT_BOOT_TYPE_NO_EMU: + iso9660->el_torito.media_type = BOOT_MEDIA_NO_EMULATION; + break; + case OPT_BOOT_TYPE_HARD_DISK: + iso9660->el_torito.media_type = BOOT_MEDIA_HARD_DISK; + break; + case OPT_BOOT_TYPE_FD: + entry = iso9660->el_torito.boot->file->entry; + if (archive_entry_size(entry) <= FD_1_2M_SIZE) + iso9660->el_torito.media_type = + BOOT_MEDIA_1_2M_DISKETTE; + else if (archive_entry_size(entry) <= FD_1_44M_SIZE) + iso9660->el_torito.media_type = + BOOT_MEDIA_1_44M_DISKETTE; + else if (archive_entry_size(entry) <= FD_2_88M_SIZE) + iso9660->el_torito.media_type = + BOOT_MEDIA_2_88M_DISKETTE; + else { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Boot image file(``%s'') size is too big " + "for fd type.", + iso9660->el_torito.boot_filename.s); + return (ARCHIVE_FATAL); + } + break; + } + + /* + * Get a system type. + * TODO: `El Torito' specification says "A copy of byte 5 from the + * Partition Table found in the boot image". + */ + iso9660->el_torito.system_type = 0; + + /* + * Get an ID. + */ + if (iso9660->opt.publisher) + archive_string_copy(&(iso9660->el_torito.id), + &(iso9660->publisher_identifier)); + + + return (ARCHIVE_OK); +} + +/* + * If a media type is floppy, return its image size. + * otherwise return 0. + */ +static size_t +fd_boot_image_size(int media_type) +{ + switch (media_type) { + case BOOT_MEDIA_1_2M_DISKETTE: + return (FD_1_2M_SIZE); + case BOOT_MEDIA_1_44M_DISKETTE: + return (FD_1_44M_SIZE); + case BOOT_MEDIA_2_88M_DISKETTE: + return (FD_2_88M_SIZE); + default: + return (0); + } +} + +/* + * Make a boot catalog image data. + */ +static int +make_boot_catalog(struct archive_write *a) +{ + struct iso9660 *iso9660 = a->format_data; + unsigned char *block; + unsigned char *p; + uint16_t sum, *wp; + + block = wb_buffptr(a); + memset(block, 0, LOGICAL_BLOCK_SIZE); + p = block; + /* + * Validation Entry + */ + /* Header ID */ + p[0] = 1; + /* Platform ID */ + p[1] = iso9660->el_torito.platform_id; + /* Reserved */ + p[2] = p[3] = 0; + /* ID */ + if (archive_strlen(&(iso9660->el_torito.id)) > 0) + strncpy((char *)p+4, iso9660->el_torito.id.s, 23); + p[27] = 0; + /* Checksum */ + p[28] = p[29] = 0; + /* Key */ + p[30] = 0x55; + p[31] = 0xAA; + + sum = 0; + wp = (uint16_t *)block; + while (wp < (uint16_t *)&block[32]) + sum += archive_le16dec(wp++); + set_num_721(&block[28], (~sum) + 1); + + /* + * Initial/Default Entry + */ + p = &block[32]; + /* Boot Indicator */ + p[0] = 0x88; + /* Boot media type */ + p[1] = iso9660->el_torito.media_type; + /* Load Segment */ + if (iso9660->el_torito.media_type == BOOT_MEDIA_NO_EMULATION) + set_num_721(&p[2], iso9660->el_torito.boot_load_seg); + else + set_num_721(&p[2], 0); + /* System Type */ + p[4] = iso9660->el_torito.system_type; + /* Unused */ + p[5] = 0; + /* Sector Count */ + if (iso9660->el_torito.media_type == BOOT_MEDIA_NO_EMULATION) + set_num_721(&p[6], iso9660->el_torito.boot_load_size); + else + set_num_721(&p[6], 1); + /* Load RBA */ + set_num_731(&p[8], + iso9660->el_torito.boot->file->content.location); + /* Unused */ + memset(&p[12], 0, 20); + + return (wb_consume(a, LOGICAL_BLOCK_SIZE)); +} + +static int +setup_boot_information(struct archive_write *a) +{ + struct iso9660 *iso9660 = a->format_data; + struct isoent *np; + int64_t size; + uint32_t sum; + unsigned char buff[4096]; + + np = iso9660->el_torito.boot; + lseek(iso9660->temp_fd, + np->file->content.offset_of_temp + 64, SEEK_SET); + size = archive_entry_size(np->file->entry) - 64; + if (size <= 0) { + archive_set_error(&a->archive, errno, + "Boot file(%jd) is too small", (intmax_t)size + 64); + return (ARCHIVE_FATAL); + } + sum = 0; + while (size > 0) { + size_t rsize; + ssize_t i, rs; + + if (size > (int64_t)sizeof(buff)) + rsize = sizeof(buff); + else + rsize = (size_t)size; + + rs = read(iso9660->temp_fd, buff, rsize); + if (rs <= 0) { + archive_set_error(&a->archive, errno, + "Can't read temporary file(%jd)", + (intmax_t)rs); + return (ARCHIVE_FATAL); + } + for (i = 0; i < rs; i += 4) + sum += archive_le32dec(buff + i); + size -= rs; + } + /* Set the location of Primary Volume Descriptor. */ + set_num_731(buff, SYSTEM_AREA_BLOCK); + /* Set the location of the boot file. */ + set_num_731(buff+4, np->file->content.location); + /* Set the size of the boot file. */ + size = fd_boot_image_size(iso9660->el_torito.media_type); + if (size == 0) + size = archive_entry_size(np->file->entry); + set_num_731(buff+8, (uint32_t)size); + /* Set the sum of the boot file. */ + set_num_731(buff+12, sum); + /* Clear reserved bytes. */ + memset(buff+16, 0, 40); + + /* Overwrite the boot file. */ + lseek(iso9660->temp_fd, + np->file->content.offset_of_temp + 8, SEEK_SET); + return (write_to_temp(a, buff, 56)); +} + +#ifdef HAVE_ZLIB_H + +static int +zisofs_init_zstream(struct archive_write *a) +{ + struct iso9660 *iso9660 = a->format_data; + int r; + + iso9660->zisofs.stream.next_in = NULL; + iso9660->zisofs.stream.avail_in = 0; + iso9660->zisofs.stream.total_in = 0; + iso9660->zisofs.stream.total_out = 0; + if (iso9660->zisofs.stream_valid) + r = deflateReset(&(iso9660->zisofs.stream)); + else { + r = deflateInit(&(iso9660->zisofs.stream), + iso9660->zisofs.compression_level); + iso9660->zisofs.stream_valid = 1; + } + switch (r) { + case Z_OK: + break; + default: + case Z_STREAM_ERROR: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Internal error initializing " + "compression library: invalid setup parameter"); + return (ARCHIVE_FATAL); + case Z_MEM_ERROR: + archive_set_error(&a->archive, ENOMEM, + "Internal error initializing " + "compression library"); + return (ARCHIVE_FATAL); + case Z_VERSION_ERROR: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Internal error initializing " + "compression library: invalid library version"); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_OK); +} + +#endif /* HAVE_ZLIB_H */ + +static int +zisofs_init(struct archive_write *a, struct isofile *file) +{ + struct iso9660 *iso9660 = a->format_data; +#ifdef HAVE_ZLIB_H + uint64_t tsize; + size_t _ceil, bpsize; + int r; +#endif + + iso9660->zisofs.detect_magic = 0; + iso9660->zisofs.making = 0; + + if (!iso9660->opt.rr || !iso9660->opt.zisofs) + return (ARCHIVE_OK); + + if (archive_entry_size(file->entry) >= 24 && + archive_entry_size(file->entry) < MULTI_EXTENT_SIZE) { + /* Acceptable file size for zisofs. */ + iso9660->zisofs.detect_magic = 1; + iso9660->zisofs.magic_cnt = 0; + } + if (!iso9660->zisofs.detect_magic) + return (ARCHIVE_OK); + +#ifdef HAVE_ZLIB_H + /* The number of Logical Blocks which uncompressed data + * will use in iso-image file is the same as the number of + * Logical Blocks which zisofs(compressed) data will use + * in ISO-image file. It won't reduce iso-image file size. */ + if (archive_entry_size(file->entry) <= LOGICAL_BLOCK_SIZE) + return (ARCHIVE_OK); + + /* Initialize compression library */ + r = zisofs_init_zstream(a); + if (r != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Mark file->zisofs to create RRIP 'ZF' Use Entry. */ + file->zisofs.header_size = ZF_HEADER_SIZE >> 2; + file->zisofs.log2_bs = ZF_LOG2_BS; + file->zisofs.uncompressed_size = + (uint32_t)archive_entry_size(file->entry); + + /* Calculate a size of Block Pointers of zisofs. */ + _ceil = (file->zisofs.uncompressed_size + ZF_BLOCK_SIZE -1) + >> file->zisofs.log2_bs; + iso9660->zisofs.block_pointers_cnt = (int)_ceil + 1; + iso9660->zisofs.block_pointers_idx = 0; + + /* Ensure a buffer size used for Block Pointers */ + bpsize = iso9660->zisofs.block_pointers_cnt * + sizeof(iso9660->zisofs.block_pointers[0]); + if (iso9660->zisofs.block_pointers_allocated < bpsize) { + free(iso9660->zisofs.block_pointers); + iso9660->zisofs.block_pointers = malloc(bpsize); + if (iso9660->zisofs.block_pointers == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate data"); + return (ARCHIVE_FATAL); + } + iso9660->zisofs.block_pointers_allocated = bpsize; + } + + /* + * Skip zisofs header and Block Pointers, which we will write + * after all compressed data of a file written to the temporary + * file. + */ + tsize = ZF_HEADER_SIZE + bpsize; + if (write_null(a, (size_t)tsize) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* + * Initialize some variables to make zisofs. + */ + archive_le32enc(&(iso9660->zisofs.block_pointers[0]), + (uint32_t)tsize); + iso9660->zisofs.remaining = file->zisofs.uncompressed_size; + iso9660->zisofs.making = 1; + iso9660->zisofs.allzero = 1; + iso9660->zisofs.block_offset = tsize; + iso9660->zisofs.total_size = tsize; + iso9660->cur_file->cur_content->size = tsize; +#endif + + return (ARCHIVE_OK); +} + +static void +zisofs_detect_magic(struct archive_write *a, const void *buff, size_t s) +{ + struct iso9660 *iso9660 = a->format_data; + struct isofile *file = iso9660->cur_file; + const unsigned char *p, *endp; + const unsigned char *magic_buff; + uint32_t uncompressed_size; + unsigned char header_size; + unsigned char log2_bs; + size_t _ceil, doff; + uint32_t bst, bed; + int magic_max; + int64_t entry_size; + + entry_size = archive_entry_size(file->entry); + if ((int64_t)sizeof(iso9660->zisofs.magic_buffer) > entry_size) + magic_max = (int)entry_size; + else + magic_max = sizeof(iso9660->zisofs.magic_buffer); + + if (iso9660->zisofs.magic_cnt == 0 && s >= (size_t)magic_max) + /* It's unnecessary we copy buffer. */ + magic_buff = buff; + else { + if (iso9660->zisofs.magic_cnt < magic_max) { + size_t l; + + l = sizeof(iso9660->zisofs.magic_buffer) + - iso9660->zisofs.magic_cnt; + if (l > s) + l = s; + memcpy(iso9660->zisofs.magic_buffer + + iso9660->zisofs.magic_cnt, buff, l); + iso9660->zisofs.magic_cnt += (int)l; + if (iso9660->zisofs.magic_cnt < magic_max) + return; + } + magic_buff = iso9660->zisofs.magic_buffer; + } + iso9660->zisofs.detect_magic = 0; + p = magic_buff; + + /* Check the magic code of zisofs. */ + if (memcmp(p, zisofs_magic, sizeof(zisofs_magic)) != 0) + /* This is not zisofs file which made by mkzftree. */ + return; + p += sizeof(zisofs_magic); + + /* Read a zisofs header. */ + uncompressed_size = archive_le32dec(p); + header_size = p[4]; + log2_bs = p[5]; + if (uncompressed_size < 24 || header_size != 4 || + log2_bs > 30 || log2_bs < 7) + return;/* Invalid or not supported header. */ + + /* Calculate a size of Block Pointers of zisofs. */ + _ceil = (uncompressed_size + + (ARCHIVE_LITERAL_LL(1) << log2_bs) -1) >> log2_bs; + doff = (_ceil + 1) * 4 + 16; + if (entry_size < (int64_t)doff) + return;/* Invalid data. */ + + /* Check every Block Pointer has valid value. */ + p = magic_buff + 16; + endp = magic_buff + magic_max; + while (_ceil && p + 8 <= endp) { + bst = archive_le32dec(p); + if (bst != doff) + return;/* Invalid data. */ + p += 4; + bed = archive_le32dec(p); + if (bed < bst || bed > entry_size) + return;/* Invalid data. */ + doff += bed - bst; + _ceil--; + } + + file->zisofs.uncompressed_size = uncompressed_size; + file->zisofs.header_size = header_size; + file->zisofs.log2_bs = log2_bs; + + /* Disable making a zisofs image. */ + iso9660->zisofs.making = 0; +} + +#ifdef HAVE_ZLIB_H + +/* + * Compress data and write it to a temporary file. + */ +static int +zisofs_write_to_temp(struct archive_write *a, const void *buff, size_t s) +{ + struct iso9660 *iso9660 = a->format_data; + struct isofile *file = iso9660->cur_file; + const unsigned char *b; + z_stream *zstrm; + size_t avail, csize; + int flush, r; + + zstrm = &(iso9660->zisofs.stream); + zstrm->next_out = wb_buffptr(a); + zstrm->avail_out = (uInt)wb_remaining(a); + b = (const unsigned char *)buff; + do { + avail = ZF_BLOCK_SIZE - zstrm->total_in; + if (s < avail) { + avail = s; + flush = Z_NO_FLUSH; + } else + flush = Z_FINISH; + iso9660->zisofs.remaining -= avail; + if (iso9660->zisofs.remaining <= 0) + flush = Z_FINISH; + + zstrm->next_in = (Bytef *)(uintptr_t)(const void *)b; + zstrm->avail_in = (uInt)avail; + + /* + * Check if current data block are all zero. + */ + if (iso9660->zisofs.allzero) { + const unsigned char *nonzero = b; + const unsigned char *nonzeroend = b + avail; + + while (nonzero < nonzeroend) + if (*nonzero++) { + iso9660->zisofs.allzero = 0; + break; + } + } + b += avail; + s -= avail; + + /* + * If current data block are all zero, we do not use + * compressed data. + */ + if (flush == Z_FINISH && iso9660->zisofs.allzero && + avail + zstrm->total_in == ZF_BLOCK_SIZE) { + if (iso9660->zisofs.block_offset != + file->cur_content->size) { + int64_t diff; + + r = wb_set_offset(a, + file->cur_content->offset_of_temp + + iso9660->zisofs.block_offset); + if (r != ARCHIVE_OK) + return (r); + diff = file->cur_content->size - + iso9660->zisofs.block_offset; + file->cur_content->size -= diff; + iso9660->zisofs.total_size -= diff; + } + zstrm->avail_in = 0; + } + + /* + * Compress file data. + */ + while (zstrm->avail_in > 0) { + csize = zstrm->total_out; + r = deflate(zstrm, flush); + switch (r) { + case Z_OK: + case Z_STREAM_END: + csize = zstrm->total_out - csize; + if (wb_consume(a, csize) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + iso9660->zisofs.total_size += csize; + iso9660->cur_file->cur_content->size += csize; + zstrm->next_out = wb_buffptr(a); + zstrm->avail_out = (uInt)wb_remaining(a); + break; + default: + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Compression failed:" + " deflate() call returned status %d", + r); + return (ARCHIVE_FATAL); + } + } + + if (flush == Z_FINISH) { + /* + * Save the information of one zisofs block. + */ + iso9660->zisofs.block_pointers_idx ++; + archive_le32enc(&(iso9660->zisofs.block_pointers[ + iso9660->zisofs.block_pointers_idx]), + (uint32_t)iso9660->zisofs.total_size); + r = zisofs_init_zstream(a); + if (r != ARCHIVE_OK) + return (ARCHIVE_FATAL); + iso9660->zisofs.allzero = 1; + iso9660->zisofs.block_offset = file->cur_content->size; + } + } while (s); + + return (ARCHIVE_OK); +} + +static int +zisofs_finish_entry(struct archive_write *a) +{ + struct iso9660 *iso9660 = a->format_data; + struct isofile *file = iso9660->cur_file; + unsigned char buff[16]; + size_t s; + int64_t tail; + + /* Direct temp file stream to zisofs temp file stream. */ + archive_entry_set_size(file->entry, iso9660->zisofs.total_size); + + /* + * Save a file pointer which points the end of current zisofs data. + */ + tail = wb_offset(a); + + /* + * Make a header. + * + * +-----------------+----------------+-----------------+ + * | Header 16 bytes | Block Pointers | Compressed data | + * +-----------------+----------------+-----------------+ + * 0 16 +X + * Block Pointers : + * 4 * (((Uncompressed file size + block_size -1) / block_size) + 1) + * + * Write zisofs header. + * Magic number + * +----+----+----+----+----+----+----+----+ + * | 37 | E4 | 53 | 96 | C9 | DB | D6 | 07 | + * +----+----+----+----+----+----+----+----+ + * 0 1 2 3 4 5 6 7 8 + * + * +------------------------+------------------+ + * | Uncompressed file size | header_size >> 2 | + * +------------------------+------------------+ + * 8 12 13 + * + * +-----------------+----------------+ + * | log2 block_size | Reserved(0000) | + * +-----------------+----------------+ + * 13 14 16 + */ + memcpy(buff, zisofs_magic, 8); + set_num_731(buff+8, file->zisofs.uncompressed_size); + buff[12] = file->zisofs.header_size; + buff[13] = file->zisofs.log2_bs; + buff[14] = buff[15] = 0;/* Reserved */ + + /* Move to the right position to write the header. */ + wb_set_offset(a, file->content.offset_of_temp); + + /* Write the header. */ + if (wb_write_to_temp(a, buff, 16) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* + * Write zisofs Block Pointers. + */ + s = iso9660->zisofs.block_pointers_cnt * + sizeof(iso9660->zisofs.block_pointers[0]); + if (wb_write_to_temp(a, iso9660->zisofs.block_pointers, s) + != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Set a file pointer back to the end of the temporary file. */ + wb_set_offset(a, tail); + + return (ARCHIVE_OK); +} + +static int +zisofs_free(struct archive_write *a) +{ + struct iso9660 *iso9660 = a->format_data; + int ret = ARCHIVE_OK; + + free(iso9660->zisofs.block_pointers); + if (iso9660->zisofs.stream_valid && + deflateEnd(&(iso9660->zisofs.stream)) != Z_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Failed to clean up compressor"); + ret = ARCHIVE_FATAL; + } + iso9660->zisofs.block_pointers = NULL; + iso9660->zisofs.stream_valid = 0; + return (ret); +} + +struct zisofs_extract { + int pz_log2_bs; /* Log2 of block size */ + uint64_t pz_uncompressed_size; + size_t uncompressed_buffer_size; + + signed int initialized:1; + signed int header_passed:1; + + uint32_t pz_offset; + unsigned char *block_pointers; + size_t block_pointers_size; + size_t block_pointers_avail; + size_t block_off; + uint32_t block_avail; + + z_stream stream; + int stream_valid; +}; + +static ssize_t +zisofs_extract_init(struct archive_write *a, struct zisofs_extract *zisofs, + const unsigned char *p, size_t bytes) +{ + size_t avail = bytes; + size_t _ceil, xsize; + + /* Allocate block pointers buffer. */ + _ceil = (size_t)((zisofs->pz_uncompressed_size + + (((int64_t)1) << zisofs->pz_log2_bs) - 1) + >> zisofs->pz_log2_bs); + xsize = (_ceil + 1) * 4; + if (zisofs->block_pointers == NULL) { + size_t alloc = ((xsize >> 10) + 1) << 10; + zisofs->block_pointers = malloc(alloc); + if (zisofs->block_pointers == NULL) { + archive_set_error(&a->archive, ENOMEM, + "No memory for zisofs decompression"); + return (ARCHIVE_FATAL); + } + } + zisofs->block_pointers_size = xsize; + + /* Allocate uncompressed data buffer. */ + zisofs->uncompressed_buffer_size = (size_t)1UL << zisofs->pz_log2_bs; + + /* + * Read the file header, and check the magic code of zisofs. + */ + if (!zisofs->header_passed) { + int err = 0; + if (avail < 16) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Illegal zisofs file body"); + return (ARCHIVE_FATAL); + } + + if (memcmp(p, zisofs_magic, sizeof(zisofs_magic)) != 0) + err = 1; + else if (archive_le32dec(p + 8) != zisofs->pz_uncompressed_size) + err = 1; + else if (p[12] != 4 || p[13] != zisofs->pz_log2_bs) + err = 1; + if (err) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Illegal zisofs file body"); + return (ARCHIVE_FATAL); + } + avail -= 16; + p += 16; + zisofs->header_passed = 1; + } + + /* + * Read block pointers. + */ + if (zisofs->header_passed && + zisofs->block_pointers_avail < zisofs->block_pointers_size) { + xsize = zisofs->block_pointers_size + - zisofs->block_pointers_avail; + if (avail < xsize) + xsize = avail; + memcpy(zisofs->block_pointers + + zisofs->block_pointers_avail, p, xsize); + zisofs->block_pointers_avail += xsize; + avail -= xsize; + if (zisofs->block_pointers_avail + == zisofs->block_pointers_size) { + /* We've got all block pointers and initialize + * related variables. */ + zisofs->block_off = 0; + zisofs->block_avail = 0; + /* Complete a initialization */ + zisofs->initialized = 1; + } + } + return ((ssize_t)avail); +} + +static ssize_t +zisofs_extract(struct archive_write *a, struct zisofs_extract *zisofs, + const unsigned char *p, size_t bytes) +{ + size_t avail; + int r; + + if (!zisofs->initialized) { + ssize_t rs = zisofs_extract_init(a, zisofs, p, bytes); + if (rs < 0) + return (rs); + if (!zisofs->initialized) { + /* We need more data. */ + zisofs->pz_offset += (uint32_t)bytes; + return (bytes); + } + avail = rs; + p += bytes - avail; + } else + avail = bytes; + + /* + * Get block offsets from block pointers. + */ + if (zisofs->block_avail == 0) { + uint32_t bst, bed; + + if (zisofs->block_off + 4 >= zisofs->block_pointers_size) { + /* There isn't a pair of offsets. */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Illegal zisofs block pointers"); + return (ARCHIVE_FATAL); + } + bst = archive_le32dec( + zisofs->block_pointers + zisofs->block_off); + if (bst != zisofs->pz_offset + (bytes - avail)) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Illegal zisofs block pointers(cannot seek)"); + return (ARCHIVE_FATAL); + } + bed = archive_le32dec( + zisofs->block_pointers + zisofs->block_off + 4); + if (bed < bst) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Illegal zisofs block pointers"); + return (ARCHIVE_FATAL); + } + zisofs->block_avail = bed - bst; + zisofs->block_off += 4; + + /* Initialize compression library for new block. */ + if (zisofs->stream_valid) + r = inflateReset(&zisofs->stream); + else + r = inflateInit(&zisofs->stream); + if (r != Z_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can't initialize zisofs decompression."); + return (ARCHIVE_FATAL); + } + zisofs->stream_valid = 1; + zisofs->stream.total_in = 0; + zisofs->stream.total_out = 0; + } + + /* + * Make uncompressed data. + */ + if (zisofs->block_avail == 0) { + /* + * It's basically 32K bytes NUL data. + */ + unsigned char *wb; + size_t size, wsize; + + size = zisofs->uncompressed_buffer_size; + while (size) { + wb = wb_buffptr(a); + if (size > wb_remaining(a)) + wsize = wb_remaining(a); + else + wsize = size; + memset(wb, 0, wsize); + r = wb_consume(a, wsize); + if (r < 0) + return (r); + size -= wsize; + } + } else { + zisofs->stream.next_in = (Bytef *)(uintptr_t)(const void *)p; + if (avail > zisofs->block_avail) + zisofs->stream.avail_in = zisofs->block_avail; + else + zisofs->stream.avail_in = (uInt)avail; + zisofs->stream.next_out = wb_buffptr(a); + zisofs->stream.avail_out = (uInt)wb_remaining(a); + + r = inflate(&zisofs->stream, 0); + switch (r) { + case Z_OK: /* Decompressor made some progress.*/ + case Z_STREAM_END: /* Found end of stream. */ + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "zisofs decompression failed (%d)", r); + return (ARCHIVE_FATAL); + } + avail -= zisofs->stream.next_in - p; + zisofs->block_avail -= (uint32_t)(zisofs->stream.next_in - p); + r = wb_consume(a, wb_remaining(a) - zisofs->stream.avail_out); + if (r < 0) + return (r); + } + zisofs->pz_offset += (uint32_t)bytes; + return (bytes - avail); +} + +static int +zisofs_rewind_boot_file(struct archive_write *a) +{ + struct iso9660 *iso9660 = a->format_data; + struct isofile *file; + unsigned char *rbuff; + ssize_t r; + size_t remaining, rbuff_size; + struct zisofs_extract zext; + int64_t read_offset, write_offset, new_offset; + int fd, ret = ARCHIVE_OK; + + file = iso9660->el_torito.boot->file; + /* + * There is nothing to do if this boot file does not have + * zisofs header. + */ + if (file->zisofs.header_size == 0) + return (ARCHIVE_OK); + + /* + * Uncompress the zisofs'ed file contents. + */ + memset(&zext, 0, sizeof(zext)); + zext.pz_uncompressed_size = file->zisofs.uncompressed_size; + zext.pz_log2_bs = file->zisofs.log2_bs; + + fd = iso9660->temp_fd; + new_offset = wb_offset(a); + read_offset = file->content.offset_of_temp; + remaining = (size_t)file->content.size; + if (remaining > 1024 * 32) + rbuff_size = 1024 * 32; + else + rbuff_size = remaining; + + rbuff = malloc(rbuff_size); + if (rbuff == NULL) { + archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + while (remaining) { + size_t rsize; + ssize_t rs; + + /* Get the current file pointer. */ + write_offset = lseek(fd, 0, SEEK_CUR); + + /* Change the file pointer to read. */ + lseek(fd, read_offset, SEEK_SET); + + rsize = rbuff_size; + if (rsize > remaining) + rsize = remaining; + rs = read(iso9660->temp_fd, rbuff, rsize); + if (rs <= 0) { + archive_set_error(&a->archive, errno, + "Can't read temporary file(%jd)", (intmax_t)rs); + ret = ARCHIVE_FATAL; + break; + } + remaining -= rs; + read_offset += rs; + + /* Put the file pointer back to write. */ + lseek(fd, write_offset, SEEK_SET); + + r = zisofs_extract(a, &zext, rbuff, rs); + if (r < 0) { + ret = (int)r; + break; + } + } + + if (ret == ARCHIVE_OK) { + /* + * Change the boot file content from zisofs'ed data + * to plain data. + */ + file->content.offset_of_temp = new_offset; + file->content.size = file->zisofs.uncompressed_size; + archive_entry_set_size(file->entry, file->content.size); + /* Set to be no zisofs. */ + file->zisofs.header_size = 0; + file->zisofs.log2_bs = 0; + file->zisofs.uncompressed_size = 0; + r = wb_write_padding_to_temp(a, file->content.size); + if (r < 0) + ret = ARCHIVE_FATAL; + } + + /* + * Free the resource we used in this function only. + */ + free(rbuff); + free(zext.block_pointers); + if (zext.stream_valid && inflateEnd(&(zext.stream)) != Z_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Failed to clean up compressor"); + ret = ARCHIVE_FATAL; + } + + return (ret); +} + +#else + +static int +zisofs_write_to_temp(struct archive_write *a, const void *buff, size_t s) +{ + (void)buff; /* UNUSED */ + (void)s; /* UNUSED */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Programming error"); + return (ARCHIVE_FATAL); +} + +static int +zisofs_rewind_boot_file(struct archive_write *a) +{ + struct iso9660 *iso9660 = a->format_data; + + if (iso9660->el_torito.boot->file->zisofs.header_size != 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "We cannot extract the zisofs imaged boot file;" + " this may not boot in being zisofs imaged"); + return (ARCHIVE_FAILED); + } + return (ARCHIVE_OK); +} + +static int +zisofs_finish_entry(struct archive_write *a) +{ + (void)a; /* UNUSED */ + return (ARCHIVE_OK); +} + +static int +zisofs_free(struct archive_write *a) +{ + (void)a; /* UNUSED */ + return (ARCHIVE_OK); +} + +#endif /* HAVE_ZLIB_H */ + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_mtree.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_mtree.c new file mode 100644 index 0000000000..aa41e9acc2 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_mtree.c @@ -0,0 +1,2228 @@ +/*- + * Copyright (c) 2008 Joerg Sonnenberger + * Copyright (c) 2009-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_mtree.c 201171 2009-12-29 06:39:07Z kientzle $"); + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#include <errno.h> +#include <stdlib.h> +#include <string.h> + +#include "archive.h" +#include "archive_digest_private.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_rb.h" +#include "archive_string.h" +#include "archive_write_private.h" + +#define INDENTNAMELEN 15 +#define MAXLINELEN 80 +#define SET_KEYS \ + (F_FLAGS | F_GID | F_GNAME | F_MODE | F_TYPE | F_UID | F_UNAME) + +struct attr_counter { + struct attr_counter *prev; + struct attr_counter *next; + struct mtree_entry *m_entry; + int count; +}; + +struct att_counter_set { + struct attr_counter *uid_list; + struct attr_counter *gid_list; + struct attr_counter *mode_list; + struct attr_counter *flags_list; +}; + +struct mtree_chain { + struct mtree_entry *first; + struct mtree_entry **last; +}; + +/* + * The Data only for a directory file. + */ +struct dir_info { + struct archive_rb_tree rbtree; + struct mtree_chain children; + struct mtree_entry *chnext; + int virtual; +}; + +/* + * The Data only for a regular file. + */ +struct reg_info { + int compute_sum; + uint32_t crc; +#ifdef ARCHIVE_HAS_MD5 + unsigned char buf_md5[16]; +#endif +#ifdef ARCHIVE_HAS_RMD160 + unsigned char buf_rmd160[20]; +#endif +#ifdef ARCHIVE_HAS_SHA1 + unsigned char buf_sha1[20]; +#endif +#ifdef ARCHIVE_HAS_SHA256 + unsigned char buf_sha256[32]; +#endif +#ifdef ARCHIVE_HAS_SHA384 + unsigned char buf_sha384[48]; +#endif +#ifdef ARCHIVE_HAS_SHA512 + unsigned char buf_sha512[64]; +#endif +}; + +struct mtree_entry { + struct archive_rb_node rbnode; + struct mtree_entry *next; + struct mtree_entry *parent; + struct dir_info *dir_info; + struct reg_info *reg_info; + + struct archive_string parentdir; + struct archive_string basename; + struct archive_string pathname; + struct archive_string symlink; + struct archive_string uname; + struct archive_string gname; + struct archive_string fflags_text; + unsigned int nlink; + mode_t filetype; + mode_t mode; + int64_t size; + int64_t uid; + int64_t gid; + time_t mtime; + long mtime_nsec; + unsigned long fflags_set; + unsigned long fflags_clear; + dev_t rdevmajor; + dev_t rdevminor; + dev_t devmajor; + dev_t devminor; + int64_t ino; +}; + +struct mtree_writer { + struct mtree_entry *mtree_entry; + struct mtree_entry *root; + struct mtree_entry *cur_dirent; + struct archive_string cur_dirstr; + struct mtree_chain file_list; + + struct archive_string ebuf; + struct archive_string buf; + int first; + uint64_t entry_bytes_remaining; + + /* + * Set global value. + */ + struct { + int processing; + mode_t type; + int keys; + int64_t uid; + int64_t gid; + mode_t mode; + unsigned long fflags_set; + unsigned long fflags_clear; + } set; + struct att_counter_set acs; + int classic; + int depth; + + /* check sum */ + int compute_sum; + uint32_t crc; + uint64_t crc_len; +#ifdef ARCHIVE_HAS_MD5 + archive_md5_ctx md5ctx; +#endif +#ifdef ARCHIVE_HAS_RMD160 + archive_rmd160_ctx rmd160ctx; +#endif +#ifdef ARCHIVE_HAS_SHA1 + archive_sha1_ctx sha1ctx; +#endif +#ifdef ARCHIVE_HAS_SHA256 + archive_sha256_ctx sha256ctx; +#endif +#ifdef ARCHIVE_HAS_SHA384 + archive_sha384_ctx sha384ctx; +#endif +#ifdef ARCHIVE_HAS_SHA512 + archive_sha512_ctx sha512ctx; +#endif + /* Keyword options */ + int keys; +#define F_CKSUM 0x00000001 /* checksum */ +#define F_DEV 0x00000002 /* device type */ +#define F_DONE 0x00000004 /* directory done */ +#define F_FLAGS 0x00000008 /* file flags */ +#define F_GID 0x00000010 /* gid */ +#define F_GNAME 0x00000020 /* group name */ +#define F_IGN 0x00000040 /* ignore */ +#define F_MAGIC 0x00000080 /* name has magic chars */ +#define F_MD5 0x00000100 /* MD5 digest */ +#define F_MODE 0x00000200 /* mode */ +#define F_NLINK 0x00000400 /* number of links */ +#define F_NOCHANGE 0x00000800 /* If owner/mode "wrong", do + * not change */ +#define F_OPT 0x00001000 /* existence optional */ +#define F_RMD160 0x00002000 /* RIPEMD160 digest */ +#define F_SHA1 0x00004000 /* SHA-1 digest */ +#define F_SIZE 0x00008000 /* size */ +#define F_SLINK 0x00010000 /* symbolic link */ +#define F_TAGS 0x00020000 /* tags */ +#define F_TIME 0x00040000 /* modification time */ +#define F_TYPE 0x00080000 /* file type */ +#define F_UID 0x00100000 /* uid */ +#define F_UNAME 0x00200000 /* user name */ +#define F_VISIT 0x00400000 /* file visited */ +#define F_SHA256 0x00800000 /* SHA-256 digest */ +#define F_SHA384 0x01000000 /* SHA-384 digest */ +#define F_SHA512 0x02000000 /* SHA-512 digest */ +#define F_INO 0x04000000 /* inode number */ +#define F_RESDEV 0x08000000 /* device ID on which the + * entry resides */ + + /* Options */ + int dironly; /* If it is set, ignore all files except + * directory files, like mtree(8) -d option. */ + int indent; /* If it is set, indent output data. */ + int output_global_set; /* If it is set, use /set keyword to set + * global values. When generating mtree + * classic format, it is set by default. */ +}; + +#define DEFAULT_KEYS (F_DEV | F_FLAGS | F_GID | F_GNAME | F_SLINK | F_MODE\ + | F_NLINK | F_SIZE | F_TIME | F_TYPE | F_UID\ + | F_UNAME) +#define attr_counter_set_reset attr_counter_set_free + +static void attr_counter_free(struct attr_counter **); +static int attr_counter_inc(struct attr_counter **, struct attr_counter *, + struct attr_counter *, struct mtree_entry *); +static struct attr_counter * attr_counter_new(struct mtree_entry *, + struct attr_counter *); +static int attr_counter_set_collect(struct mtree_writer *, + struct mtree_entry *); +static void attr_counter_set_free(struct mtree_writer *); +static int get_global_set_keys(struct mtree_writer *, struct mtree_entry *); +static int mtree_entry_add_child_tail(struct mtree_entry *, + struct mtree_entry *); +static int mtree_entry_create_virtual_dir(struct archive_write *, const char *, + struct mtree_entry **); +static int mtree_entry_cmp_node(const struct archive_rb_node *, + const struct archive_rb_node *); +static int mtree_entry_cmp_key(const struct archive_rb_node *, const void *); +static int mtree_entry_exchange_same_entry(struct archive_write *, + struct mtree_entry *, struct mtree_entry *); +static void mtree_entry_free(struct mtree_entry *); +static int mtree_entry_new(struct archive_write *, struct archive_entry *, + struct mtree_entry **); +static void mtree_entry_register_free(struct mtree_writer *); +static void mtree_entry_register_init(struct mtree_writer *); +static int mtree_entry_setup_filenames(struct archive_write *, + struct mtree_entry *, struct archive_entry *); +static int mtree_entry_tree_add(struct archive_write *, struct mtree_entry **); +static void sum_init(struct mtree_writer *); +static void sum_update(struct mtree_writer *, const void *, size_t); +static void sum_final(struct mtree_writer *, struct reg_info *); +static void sum_write(struct archive_string *, struct reg_info *); +static int write_mtree_entry(struct archive_write *, struct mtree_entry *); +static int write_dot_dot_entry(struct archive_write *, struct mtree_entry *); + +#define COMPUTE_CRC(var, ch) (var) = (var) << 8 ^ crctab[(var) >> 24 ^ (ch)] +static const uint32_t crctab[] = { + 0x0, + 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, + 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, + 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, + 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, + 0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f, + 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, + 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, + 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, + 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, + 0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe, + 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, + 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, + 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, + 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, + 0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, + 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07, + 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, + 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, + 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, + 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, + 0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, + 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, + 0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, + 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f, + 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, + 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, + 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, + 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, + 0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629, + 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, + 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, + 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, + 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, + 0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8, + 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, + 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, + 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, + 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, + 0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, + 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21, + 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, + 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087, + 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, + 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, + 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, + 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, + 0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, + 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09, + 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, + 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, + 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 +}; + +static const unsigned char safe_char[256] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 00 - 0F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 1F */ + /* !"$%&'()*+,-./ EXCLUSION:0x20( ) 0x23(#) */ + 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 20 - 2F */ + /* 0123456789:;<>? EXCLUSION:0x3d(=) */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, /* 30 - 3F */ + /* @ABCDEFGHIJKLMNO */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 40 - 4F */ + /* PQRSTUVWXYZ[]^_ EXCLUSION:0x5c(\) */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, /* 50 - 5F */ + /* `abcdefghijklmno */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 60 - 6F */ + /* pqrstuvwxyz{|}~ */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, /* 70 - 7F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F0 - FF */ +}; + +static void +mtree_quote(struct archive_string *s, const char *str) +{ + const char *start; + char buf[4]; + unsigned char c; + + for (start = str; *str != '\0'; ++str) { + if (safe_char[*(const unsigned char *)str]) + continue; + if (start != str) + archive_strncat(s, start, str - start); + c = (unsigned char)*str; + buf[0] = '\\'; + buf[1] = (c / 64) + '0'; + buf[2] = (c / 8 % 8) + '0'; + buf[3] = (c % 8) + '0'; + archive_strncat(s, buf, 4); + start = str + 1; + } + + if (start != str) + archive_strncat(s, start, str - start); +} + +/* + * Indent a line as the mtree utility does so it is readable for people. + */ +static void +mtree_indent(struct mtree_writer *mtree) +{ + int i, fn, nd, pd; + const char *r, *s, *x; + + if (mtree->classic) { + if (mtree->indent) { + nd = 0; + pd = mtree->depth * 4; + } else { + nd = mtree->depth?4:0; + pd = 0; + } + } else + nd = pd = 0; + fn = 1; + s = r = mtree->ebuf.s; + x = NULL; + while (*r == ' ') + r++; + while ((r = strchr(r, ' ')) != NULL) { + if (fn) { + fn = 0; + for (i = 0; i < nd + pd; i++) + archive_strappend_char(&mtree->buf, ' '); + archive_strncat(&mtree->buf, s, r - s); + if (nd + (r -s) > INDENTNAMELEN) { + archive_strncat(&mtree->buf, " \\\n", 3); + for (i = 0; i < (INDENTNAMELEN + 1 + pd); i++) + archive_strappend_char(&mtree->buf, ' '); + } else { + for (i = (int)(r -s + nd); + i < (INDENTNAMELEN + 1); i++) + archive_strappend_char(&mtree->buf, ' '); + } + s = ++r; + x = NULL; + continue; + } + if (pd + (r - s) <= MAXLINELEN - 3 - INDENTNAMELEN) + x = r++; + else { + if (x == NULL) + x = r; + archive_strncat(&mtree->buf, s, x - s); + archive_strncat(&mtree->buf, " \\\n", 3); + for (i = 0; i < (INDENTNAMELEN + 1 + pd); i++) + archive_strappend_char(&mtree->buf, ' '); + s = r = ++x; + x = NULL; + } + } + if (fn) { + for (i = 0; i < nd + pd; i++) + archive_strappend_char(&mtree->buf, ' '); + archive_strcat(&mtree->buf, s); + s += strlen(s); + } + if (x != NULL && pd + strlen(s) > MAXLINELEN - 3 - INDENTNAMELEN) { + /* Last keyword is longer. */ + archive_strncat(&mtree->buf, s, x - s); + archive_strncat(&mtree->buf, " \\\n", 3); + for (i = 0; i < (INDENTNAMELEN + 1 + pd); i++) + archive_strappend_char(&mtree->buf, ' '); + s = ++x; + } + archive_strcat(&mtree->buf, s); + archive_string_empty(&mtree->ebuf); +} + +/* + * Write /set keyword. + * Set the most used value of uid, gid, mode and fflags, which are + * collected by the attr_counter_set_collect() function. + */ +static void +write_global(struct mtree_writer *mtree) +{ + struct archive_string setstr; + struct archive_string unsetstr; + struct att_counter_set *acs; + int keys, oldkeys, effkeys; + + archive_string_init(&setstr); + archive_string_init(&unsetstr); + keys = mtree->keys & SET_KEYS; + oldkeys = mtree->set.keys; + effkeys = keys; + acs = &mtree->acs; + if (mtree->set.processing) { + /* + * Check if the global data needs updating. + */ + effkeys &= ~F_TYPE; + if (acs->uid_list == NULL) + effkeys &= ~(F_UNAME | F_UID); + else if (oldkeys & (F_UNAME | F_UID)) { + if (acs->uid_list->count < 2 || + mtree->set.uid == acs->uid_list->m_entry->uid) + effkeys &= ~(F_UNAME | F_UID); + } + if (acs->gid_list == NULL) + effkeys &= ~(F_GNAME | F_GID); + else if (oldkeys & (F_GNAME | F_GID)) { + if (acs->gid_list->count < 2 || + mtree->set.gid == acs->gid_list->m_entry->gid) + effkeys &= ~(F_GNAME | F_GID); + } + if (acs->mode_list == NULL) + effkeys &= ~F_MODE; + else if (oldkeys & F_MODE) { + if (acs->mode_list->count < 2 || + mtree->set.mode == acs->mode_list->m_entry->mode) + effkeys &= ~F_MODE; + } + if (acs->flags_list == NULL) + effkeys &= ~F_FLAGS; + else if ((oldkeys & F_FLAGS) != 0) { + if (acs->flags_list->count < 2 || + (acs->flags_list->m_entry->fflags_set == + mtree->set.fflags_set && + acs->flags_list->m_entry->fflags_clear == + mtree->set.fflags_clear)) + effkeys &= ~F_FLAGS; + } + } else { + if (acs->uid_list == NULL) + keys &= ~(F_UNAME | F_UID); + if (acs->gid_list == NULL) + keys &= ~(F_GNAME | F_GID); + if (acs->mode_list == NULL) + keys &= ~F_MODE; + if (acs->flags_list == NULL) + keys &= ~F_FLAGS; + } + if ((keys & effkeys & F_TYPE) != 0) { + if (mtree->dironly) { + archive_strcat(&setstr, " type=dir"); + mtree->set.type = AE_IFDIR; + } else { + archive_strcat(&setstr, " type=file"); + mtree->set.type = AE_IFREG; + } + } + if ((keys & effkeys & F_UNAME) != 0) { + if (archive_strlen(&(acs->uid_list->m_entry->uname)) > 0) { + archive_strcat(&setstr, " uname="); + mtree_quote(&setstr, acs->uid_list->m_entry->uname.s); + } else { + keys &= ~F_UNAME; + if ((oldkeys & F_UNAME) != 0) + archive_strcat(&unsetstr, " uname"); + } + } + if ((keys & effkeys & F_UID) != 0) { + mtree->set.uid = acs->uid_list->m_entry->uid; + archive_string_sprintf(&setstr, " uid=%jd", + (intmax_t)mtree->set.uid); + } + if ((keys & effkeys & F_GNAME) != 0) { + if (archive_strlen(&(acs->gid_list->m_entry->gname)) > 0) { + archive_strcat(&setstr, " gname="); + mtree_quote(&setstr, acs->gid_list->m_entry->gname.s); + } else { + keys &= ~F_GNAME; + if ((oldkeys & F_GNAME) != 0) + archive_strcat(&unsetstr, " gname"); + } + } + if ((keys & effkeys & F_GID) != 0) { + mtree->set.gid = acs->gid_list->m_entry->gid; + archive_string_sprintf(&setstr, " gid=%jd", + (intmax_t)mtree->set.gid); + } + if ((keys & effkeys & F_MODE) != 0) { + mtree->set.mode = acs->mode_list->m_entry->mode; + archive_string_sprintf(&setstr, " mode=%o", + (unsigned int)mtree->set.mode); + } + if ((keys & effkeys & F_FLAGS) != 0) { + if (archive_strlen( + &(acs->flags_list->m_entry->fflags_text)) > 0) { + archive_strcat(&setstr, " flags="); + mtree_quote(&setstr, + acs->flags_list->m_entry->fflags_text.s); + mtree->set.fflags_set = + acs->flags_list->m_entry->fflags_set; + mtree->set.fflags_clear = + acs->flags_list->m_entry->fflags_clear; + } else { + keys &= ~F_FLAGS; + if ((oldkeys & F_FLAGS) != 0) + archive_strcat(&unsetstr, " flags"); + } + } + if (unsetstr.length > 0) + archive_string_sprintf(&mtree->buf, "/unset%s\n", unsetstr.s); + archive_string_free(&unsetstr); + if (setstr.length > 0) + archive_string_sprintf(&mtree->buf, "/set%s\n", setstr.s); + archive_string_free(&setstr); + mtree->set.keys = keys; + mtree->set.processing = 1; +} + +static struct attr_counter * +attr_counter_new(struct mtree_entry *me, struct attr_counter *prev) +{ + struct attr_counter *ac; + + ac = malloc(sizeof(*ac)); + if (ac != NULL) { + ac->prev = prev; + ac->next = NULL; + ac->count = 1; + ac->m_entry = me; + } + return (ac); +} + +static void +attr_counter_free(struct attr_counter **top) +{ + struct attr_counter *ac, *tac; + + if (*top == NULL) + return; + ac = *top; + while (ac != NULL) { + tac = ac->next; + free(ac); + ac = tac; + } + *top = NULL; +} + +static int +attr_counter_inc(struct attr_counter **top, struct attr_counter *ac, + struct attr_counter *last, struct mtree_entry *me) +{ + struct attr_counter *pac; + + if (ac != NULL) { + ac->count++; + if (*top == ac || ac->prev->count >= ac->count) + return (0); + for (pac = ac->prev; pac; pac = pac->prev) { + if (pac->count >= ac->count) + break; + } + ac->prev->next = ac->next; + if (ac->next != NULL) + ac->next->prev = ac->prev; + if (pac != NULL) { + ac->prev = pac; + ac->next = pac->next; + pac->next = ac; + if (ac->next != NULL) + ac->next->prev = ac; + } else { + ac->prev = NULL; + ac->next = *top; + *top = ac; + ac->next->prev = ac; + } + } else if (last != NULL) { + ac = attr_counter_new(me, last); + if (ac == NULL) + return (-1); + last->next = ac; + } + return (0); +} + +/* + * Tabulate uid, gid, mode and fflags of a entry in order to be used for /set. + */ +static int +attr_counter_set_collect(struct mtree_writer *mtree, struct mtree_entry *me) +{ + struct attr_counter *ac, *last; + struct att_counter_set *acs = &mtree->acs; + int keys = mtree->keys; + + if (keys & (F_UNAME | F_UID)) { + if (acs->uid_list == NULL) { + acs->uid_list = attr_counter_new(me, NULL); + if (acs->uid_list == NULL) + return (-1); + } else { + last = NULL; + for (ac = acs->uid_list; ac; ac = ac->next) { + if (ac->m_entry->uid == me->uid) + break; + last = ac; + } + if (attr_counter_inc(&acs->uid_list, ac, last, me) < 0) + return (-1); + } + } + if (keys & (F_GNAME | F_GID)) { + if (acs->gid_list == NULL) { + acs->gid_list = attr_counter_new(me, NULL); + if (acs->gid_list == NULL) + return (-1); + } else { + last = NULL; + for (ac = acs->gid_list; ac; ac = ac->next) { + if (ac->m_entry->gid == me->gid) + break; + last = ac; + } + if (attr_counter_inc(&acs->gid_list, ac, last, me) < 0) + return (-1); + } + } + if (keys & F_MODE) { + if (acs->mode_list == NULL) { + acs->mode_list = attr_counter_new(me, NULL); + if (acs->mode_list == NULL) + return (-1); + } else { + last = NULL; + for (ac = acs->mode_list; ac; ac = ac->next) { + if (ac->m_entry->mode == me->mode) + break; + last = ac; + } + if (attr_counter_inc(&acs->mode_list, ac, last, me) < 0) + return (-1); + } + } + if (keys & F_FLAGS) { + if (acs->flags_list == NULL) { + acs->flags_list = attr_counter_new(me, NULL); + if (acs->flags_list == NULL) + return (-1); + } else { + last = NULL; + for (ac = acs->flags_list; ac; ac = ac->next) { + if (ac->m_entry->fflags_set == me->fflags_set && + ac->m_entry->fflags_clear == + me->fflags_clear) + break; + last = ac; + } + if (attr_counter_inc(&acs->flags_list, ac, last, me) < 0) + return (-1); + } + } + + return (0); +} + +static void +attr_counter_set_free(struct mtree_writer *mtree) +{ + struct att_counter_set *acs = &mtree->acs; + + attr_counter_free(&acs->uid_list); + attr_counter_free(&acs->gid_list); + attr_counter_free(&acs->mode_list); + attr_counter_free(&acs->flags_list); +} + +static int +get_global_set_keys(struct mtree_writer *mtree, struct mtree_entry *me) +{ + int keys; + + keys = mtree->keys; + + /* + * If a keyword has been set by /set, we do not need to + * output it. + */ + if (mtree->set.keys == 0) + return (keys);/* /set is not used. */ + + if ((mtree->set.keys & (F_GNAME | F_GID)) != 0 && + mtree->set.gid == me->gid) + keys &= ~(F_GNAME | F_GID); + if ((mtree->set.keys & (F_UNAME | F_UID)) != 0 && + mtree->set.uid == me->uid) + keys &= ~(F_UNAME | F_UID); + if (mtree->set.keys & F_FLAGS) { + if (mtree->set.fflags_set == me->fflags_set && + mtree->set.fflags_clear == me->fflags_clear) + keys &= ~F_FLAGS; + } + if ((mtree->set.keys & F_MODE) != 0 && mtree->set.mode == me->mode) + keys &= ~F_MODE; + + switch (me->filetype) { + case AE_IFLNK: case AE_IFSOCK: case AE_IFCHR: + case AE_IFBLK: case AE_IFIFO: + break; + case AE_IFDIR: + if ((mtree->set.keys & F_TYPE) != 0 && + mtree->set.type == AE_IFDIR) + keys &= ~F_TYPE; + break; + case AE_IFREG: + default: /* Handle unknown file types as regular files. */ + if ((mtree->set.keys & F_TYPE) != 0 && + mtree->set.type == AE_IFREG) + keys &= ~F_TYPE; + break; + } + + return (keys); +} + +static int +mtree_entry_new(struct archive_write *a, struct archive_entry *entry, + struct mtree_entry **m_entry) +{ + struct mtree_entry *me; + const char *s; + int r; + static const struct archive_rb_tree_ops rb_ops = { + mtree_entry_cmp_node, mtree_entry_cmp_key + }; + + me = calloc(1, sizeof(*me)); + if (me == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for a mtree entry"); + *m_entry = NULL; + return (ARCHIVE_FATAL); + } + + r = mtree_entry_setup_filenames(a, me, entry); + if (r < ARCHIVE_WARN) { + mtree_entry_free(me); + *m_entry = NULL; + return (r); + } + + if ((s = archive_entry_symlink(entry)) != NULL) + archive_strcpy(&me->symlink, s); + me->nlink = archive_entry_nlink(entry); + me->filetype = archive_entry_filetype(entry); + me->mode = archive_entry_mode(entry) & 07777; + me->uid = archive_entry_uid(entry); + me->gid = archive_entry_gid(entry); + if ((s = archive_entry_uname(entry)) != NULL) + archive_strcpy(&me->uname, s); + if ((s = archive_entry_gname(entry)) != NULL) + archive_strcpy(&me->gname, s); + if ((s = archive_entry_fflags_text(entry)) != NULL) + archive_strcpy(&me->fflags_text, s); + archive_entry_fflags(entry, &me->fflags_set, &me->fflags_clear); + me->mtime = archive_entry_mtime(entry); + me->mtime_nsec = archive_entry_mtime_nsec(entry); + me->rdevmajor = archive_entry_rdevmajor(entry); + me->rdevminor = archive_entry_rdevminor(entry); + me->devmajor = archive_entry_devmajor(entry); + me->devminor = archive_entry_devminor(entry); + me->ino = archive_entry_ino(entry); + me->size = archive_entry_size(entry); + if (me->filetype == AE_IFDIR) { + me->dir_info = calloc(1, sizeof(*me->dir_info)); + if (me->dir_info == NULL) { + mtree_entry_free(me); + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for a mtree entry"); + *m_entry = NULL; + return (ARCHIVE_FATAL); + } + __archive_rb_tree_init(&me->dir_info->rbtree, &rb_ops); + me->dir_info->children.first = NULL; + me->dir_info->children.last = &(me->dir_info->children.first); + me->dir_info->chnext = NULL; + } else if (me->filetype == AE_IFREG) { + me->reg_info = calloc(1, sizeof(*me->reg_info)); + if (me->reg_info == NULL) { + mtree_entry_free(me); + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for a mtree entry"); + *m_entry = NULL; + return (ARCHIVE_FATAL); + } + me->reg_info->compute_sum = 0; + } + + *m_entry = me; + return (ARCHIVE_OK); +} + +static void +mtree_entry_free(struct mtree_entry *me) +{ + archive_string_free(&me->parentdir); + archive_string_free(&me->basename); + archive_string_free(&me->pathname); + archive_string_free(&me->symlink); + archive_string_free(&me->uname); + archive_string_free(&me->gname); + archive_string_free(&me->fflags_text); + free(me->dir_info); + free(me->reg_info); + free(me); +} + +static int +archive_write_mtree_header(struct archive_write *a, + struct archive_entry *entry) +{ + struct mtree_writer *mtree= a->format_data; + struct mtree_entry *mtree_entry; + int r, r2; + + if (mtree->first) { + mtree->first = 0; + archive_strcat(&mtree->buf, "#mtree\n"); + if ((mtree->keys & SET_KEYS) == 0) + mtree->output_global_set = 0;/* Disabled. */ + } + + mtree->entry_bytes_remaining = archive_entry_size(entry); + + /* While directory only mode, we do not handle non directory files. */ + if (mtree->dironly && archive_entry_filetype(entry) != AE_IFDIR) + return (ARCHIVE_OK); + + r2 = mtree_entry_new(a, entry, &mtree_entry); + if (r2 < ARCHIVE_WARN) + return (r2); + r = mtree_entry_tree_add(a, &mtree_entry); + if (r < ARCHIVE_WARN) { + mtree_entry_free(mtree_entry); + return (r); + } + mtree->mtree_entry = mtree_entry; + + /* If the current file is a regular file, we have to + * compute the sum of its content. + * Initialize a bunch of checksum context. */ + if (mtree_entry->reg_info) + sum_init(mtree); + + return (r2); +} + +static int +write_mtree_entry(struct archive_write *a, struct mtree_entry *me) +{ + struct mtree_writer *mtree = a->format_data; + struct archive_string *str; + int keys, ret; + + if (me->dir_info) { + if (mtree->classic) { + /* + * Output a comment line to describe the full + * pathname of the entry as mtree utility does + * while generating classic format. + */ + if (!mtree->dironly) + archive_strappend_char(&mtree->buf, '\n'); + if (me->parentdir.s) + archive_string_sprintf(&mtree->buf, + "# %s/%s\n", + me->parentdir.s, me->basename.s); + else + archive_string_sprintf(&mtree->buf, + "# %s\n", + me->basename.s); + } + if (mtree->output_global_set) + write_global(mtree); + } + archive_string_empty(&mtree->ebuf); + str = (mtree->indent || mtree->classic)? &mtree->ebuf : &mtree->buf; + + if (!mtree->classic && me->parentdir.s) { + /* + * If generating format is not classic one(v1), output + * a full pathname. + */ + mtree_quote(str, me->parentdir.s); + archive_strappend_char(str, '/'); + } + mtree_quote(str, me->basename.s); + + keys = get_global_set_keys(mtree, me); + if ((keys & F_NLINK) != 0 && + me->nlink != 1 && me->filetype != AE_IFDIR) + archive_string_sprintf(str, " nlink=%u", me->nlink); + + if ((keys & F_GNAME) != 0 && archive_strlen(&me->gname) > 0) { + archive_strcat(str, " gname="); + mtree_quote(str, me->gname.s); + } + if ((keys & F_UNAME) != 0 && archive_strlen(&me->uname) > 0) { + archive_strcat(str, " uname="); + mtree_quote(str, me->uname.s); + } + if ((keys & F_FLAGS) != 0) { + if (archive_strlen(&me->fflags_text) > 0) { + archive_strcat(str, " flags="); + mtree_quote(str, me->fflags_text.s); + } else if (mtree->set.processing && + (mtree->set.keys & F_FLAGS) != 0) + /* Overwrite the global parameter. */ + archive_strcat(str, " flags=none"); + } + if ((keys & F_TIME) != 0) + archive_string_sprintf(str, " time=%jd.%jd", + (intmax_t)me->mtime, (intmax_t)me->mtime_nsec); + if ((keys & F_MODE) != 0) + archive_string_sprintf(str, " mode=%o", (unsigned int)me->mode); + if ((keys & F_GID) != 0) + archive_string_sprintf(str, " gid=%jd", (intmax_t)me->gid); + if ((keys & F_UID) != 0) + archive_string_sprintf(str, " uid=%jd", (intmax_t)me->uid); + + if ((keys & F_INO) != 0) + archive_string_sprintf(str, " inode=%jd", (intmax_t)me->ino); + if ((keys & F_RESDEV) != 0) { + archive_string_sprintf(str, + " resdevice=native,%ju,%ju", + (uintmax_t)me->devmajor, + (uintmax_t)me->devminor); + } + + switch (me->filetype) { + case AE_IFLNK: + if ((keys & F_TYPE) != 0) + archive_strcat(str, " type=link"); + if ((keys & F_SLINK) != 0) { + archive_strcat(str, " link="); + mtree_quote(str, me->symlink.s); + } + break; + case AE_IFSOCK: + if ((keys & F_TYPE) != 0) + archive_strcat(str, " type=socket"); + break; + case AE_IFCHR: + if ((keys & F_TYPE) != 0) + archive_strcat(str, " type=char"); + if ((keys & F_DEV) != 0) { + archive_string_sprintf(str, + " device=native,%ju,%ju", + (uintmax_t)me->rdevmajor, + (uintmax_t)me->rdevminor); + } + break; + case AE_IFBLK: + if ((keys & F_TYPE) != 0) + archive_strcat(str, " type=block"); + if ((keys & F_DEV) != 0) { + archive_string_sprintf(str, + " device=native,%ju,%ju", + (uintmax_t)me->rdevmajor, + (uintmax_t)me->rdevminor); + } + break; + case AE_IFDIR: + if ((keys & F_TYPE) != 0) + archive_strcat(str, " type=dir"); + break; + case AE_IFIFO: + if ((keys & F_TYPE) != 0) + archive_strcat(str, " type=fifo"); + break; + case AE_IFREG: + default: /* Handle unknown file types as regular files. */ + if ((keys & F_TYPE) != 0) + archive_strcat(str, " type=file"); + if ((keys & F_SIZE) != 0) + archive_string_sprintf(str, " size=%jd", + (intmax_t)me->size); + break; + } + + /* Write a bunch of sum. */ + if (me->reg_info) + sum_write(str, me->reg_info); + + archive_strappend_char(str, '\n'); + if (mtree->indent || mtree->classic) + mtree_indent(mtree); + + if (mtree->buf.length > 32768) { + ret = __archive_write_output( + a, mtree->buf.s, mtree->buf.length); + archive_string_empty(&mtree->buf); + } else + ret = ARCHIVE_OK; + return (ret); +} + +static int +write_dot_dot_entry(struct archive_write *a, struct mtree_entry *n) +{ + struct mtree_writer *mtree = a->format_data; + int ret; + + if (n->parentdir.s) { + if (mtree->indent) { + int i, pd = mtree->depth * 4; + for (i = 0; i < pd; i++) + archive_strappend_char(&mtree->buf, ' '); + } + archive_string_sprintf(&mtree->buf, "# %s/%s\n", + n->parentdir.s, n->basename.s); + } + + if (mtree->indent) { + archive_string_empty(&mtree->ebuf); + archive_strncat(&mtree->ebuf, "..\n\n", (mtree->dironly)?3:4); + mtree_indent(mtree); + } else + archive_strncat(&mtree->buf, "..\n\n", (mtree->dironly)?3:4); + + if (mtree->buf.length > 32768) { + ret = __archive_write_output( + a, mtree->buf.s, mtree->buf.length); + archive_string_empty(&mtree->buf); + } else + ret = ARCHIVE_OK; + return (ret); +} + +/* + * Write mtree entries saved at attr_counter_set_collect() function. + */ +static int +write_mtree_entry_tree(struct archive_write *a) +{ + struct mtree_writer *mtree = a->format_data; + struct mtree_entry *np = mtree->root; + struct archive_rb_node *n; + int ret; + + do { + if (mtree->output_global_set) { + /* + * Collect attribute information to know which value + * is frequently used among the children. + */ + attr_counter_set_reset(mtree); + ARCHIVE_RB_TREE_FOREACH(n, &(np->dir_info->rbtree)) { + struct mtree_entry *e = (struct mtree_entry *)n; + if (attr_counter_set_collect(mtree, e) < 0) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + } + } + if (!np->dir_info->virtual || mtree->classic) { + ret = write_mtree_entry(a, np); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } else { + /* Whenever output_global_set is enabled + * output global value(/set keywords) + * even if the directory entry is not allowed + * to be written because the global values + * can be used for the children. */ + if (mtree->output_global_set) + write_global(mtree); + } + /* + * Output the attribute of all files except directory files. + */ + mtree->depth++; + ARCHIVE_RB_TREE_FOREACH(n, &(np->dir_info->rbtree)) { + struct mtree_entry *e = (struct mtree_entry *)n; + + if (e->dir_info) + mtree_entry_add_child_tail(np, e); + else { + ret = write_mtree_entry(a, e); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + } + mtree->depth--; + + if (np->dir_info->children.first != NULL) { + /* + * Descend the tree. + */ + np = np->dir_info->children.first; + if (mtree->indent) + mtree->depth++; + continue; + } else if (mtree->classic) { + /* + * While printing mtree classic, if there are not + * any directory files(except "." and "..") in the + * directory, output two dots ".." as returning + * the parent directory. + */ + ret = write_dot_dot_entry(a, np); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + + while (np != np->parent) { + if (np->dir_info->chnext == NULL) { + /* + * Ascend the tree; go back to the parent. + */ + if (mtree->indent) + mtree->depth--; + if (mtree->classic) { + ret = write_dot_dot_entry(a, + np->parent); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + np = np->parent; + } else { + /* + * Switch to next mtree entry in the directory. + */ + np = np->dir_info->chnext; + break; + } + } + } while (np != np->parent); + + return (ARCHIVE_OK); +} + +static int +archive_write_mtree_finish_entry(struct archive_write *a) +{ + struct mtree_writer *mtree = a->format_data; + struct mtree_entry *me; + + if ((me = mtree->mtree_entry) == NULL) + return (ARCHIVE_OK); + mtree->mtree_entry = NULL; + + if (me->reg_info) + sum_final(mtree, me->reg_info); + + return (ARCHIVE_OK); +} + +static int +archive_write_mtree_close(struct archive_write *a) +{ + struct mtree_writer *mtree= a->format_data; + int ret; + + if (mtree->root != NULL) { + ret = write_mtree_entry_tree(a); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + + archive_write_set_bytes_in_last_block(&a->archive, 1); + + return __archive_write_output(a, mtree->buf.s, mtree->buf.length); +} + +static ssize_t +archive_write_mtree_data(struct archive_write *a, const void *buff, size_t n) +{ + struct mtree_writer *mtree= a->format_data; + + if (n > mtree->entry_bytes_remaining) + n = (size_t)mtree->entry_bytes_remaining; + mtree->entry_bytes_remaining -= n; + + /* We don't need to compute a regular file sum */ + if (mtree->mtree_entry == NULL) + return (n); + + if (mtree->mtree_entry->filetype == AE_IFREG) + sum_update(mtree, buff, n); + + return (n); +} + +static int +archive_write_mtree_free(struct archive_write *a) +{ + struct mtree_writer *mtree= a->format_data; + + if (mtree == NULL) + return (ARCHIVE_OK); + + /* Make sure we do not leave any entries. */ + mtree_entry_register_free(mtree); + archive_string_free(&mtree->cur_dirstr); + archive_string_free(&mtree->ebuf); + archive_string_free(&mtree->buf); + attr_counter_set_free(mtree); + free(mtree); + a->format_data = NULL; + return (ARCHIVE_OK); +} + +static int +archive_write_mtree_options(struct archive_write *a, const char *key, + const char *value) +{ + struct mtree_writer *mtree= a->format_data; + int keybit = 0; + + switch (key[0]) { + case 'a': + if (strcmp(key, "all") == 0) + keybit = ~0; + break; + case 'c': + if (strcmp(key, "cksum") == 0) + keybit = F_CKSUM; + break; + case 'd': + if (strcmp(key, "device") == 0) + keybit = F_DEV; + else if (strcmp(key, "dironly") == 0) { + mtree->dironly = (value != NULL)? 1: 0; + return (ARCHIVE_OK); + } + break; + case 'f': + if (strcmp(key, "flags") == 0) + keybit = F_FLAGS; + break; + case 'g': + if (strcmp(key, "gid") == 0) + keybit = F_GID; + else if (strcmp(key, "gname") == 0) + keybit = F_GNAME; + break; + case 'i': + if (strcmp(key, "indent") == 0) { + mtree->indent = (value != NULL)? 1: 0; + return (ARCHIVE_OK); + } else if (strcmp(key, "inode") == 0) { + keybit = F_INO; + } + break; + case 'l': + if (strcmp(key, "link") == 0) + keybit = F_SLINK; + break; + case 'm': + if (strcmp(key, "md5") == 0 || + strcmp(key, "md5digest") == 0) + keybit = F_MD5; + if (strcmp(key, "mode") == 0) + keybit = F_MODE; + break; + case 'n': + if (strcmp(key, "nlink") == 0) + keybit = F_NLINK; + break; + case 'r': + if (strcmp(key, "resdevice") == 0) { + keybit = F_RESDEV; + } else if (strcmp(key, "ripemd160digest") == 0 || + strcmp(key, "rmd160") == 0 || + strcmp(key, "rmd160digest") == 0) + keybit = F_RMD160; + break; + case 's': + if (strcmp(key, "sha1") == 0 || + strcmp(key, "sha1digest") == 0) + keybit = F_SHA1; + if (strcmp(key, "sha256") == 0 || + strcmp(key, "sha256digest") == 0) + keybit = F_SHA256; + if (strcmp(key, "sha384") == 0 || + strcmp(key, "sha384digest") == 0) + keybit = F_SHA384; + if (strcmp(key, "sha512") == 0 || + strcmp(key, "sha512digest") == 0) + keybit = F_SHA512; + if (strcmp(key, "size") == 0) + keybit = F_SIZE; + break; + case 't': + if (strcmp(key, "time") == 0) + keybit = F_TIME; + else if (strcmp(key, "type") == 0) + keybit = F_TYPE; + break; + case 'u': + if (strcmp(key, "uid") == 0) + keybit = F_UID; + else if (strcmp(key, "uname") == 0) + keybit = F_UNAME; + else if (strcmp(key, "use-set") == 0) { + mtree->output_global_set = (value != NULL)? 1: 0; + return (ARCHIVE_OK); + } + break; + } + if (keybit != 0) { + if (value != NULL) + mtree->keys |= keybit; + else + mtree->keys &= ~keybit; + return (ARCHIVE_OK); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static int +archive_write_set_format_mtree_default(struct archive *_a, const char *fn) +{ + struct archive_write *a = (struct archive_write *)_a; + struct mtree_writer *mtree; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, ARCHIVE_STATE_NEW, fn); + + if (a->format_free != NULL) + (a->format_free)(a); + + if ((mtree = calloc(1, sizeof(*mtree))) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate mtree data"); + return (ARCHIVE_FATAL); + } + + mtree->mtree_entry = NULL; + mtree->first = 1; + memset(&(mtree->set), 0, sizeof(mtree->set)); + mtree->keys = DEFAULT_KEYS; + mtree->dironly = 0; + mtree->indent = 0; + archive_string_init(&mtree->ebuf); + archive_string_init(&mtree->buf); + mtree_entry_register_init(mtree); + a->format_data = mtree; + a->format_free = archive_write_mtree_free; + a->format_name = "mtree"; + a->format_options = archive_write_mtree_options; + a->format_write_header = archive_write_mtree_header; + a->format_close = archive_write_mtree_close; + a->format_write_data = archive_write_mtree_data; + a->format_finish_entry = archive_write_mtree_finish_entry; + a->archive.archive_format = ARCHIVE_FORMAT_MTREE; + a->archive.archive_format_name = "mtree"; + + return (ARCHIVE_OK); +} + +int +archive_write_set_format_mtree(struct archive *_a) +{ + return archive_write_set_format_mtree_default(_a, + "archive_write_set_format_mtree"); +} + +int +archive_write_set_format_mtree_classic(struct archive *_a) +{ + int r; + + r = archive_write_set_format_mtree_default(_a, + "archive_write_set_format_mtree_classic"); + if (r == ARCHIVE_OK) { + struct archive_write *a = (struct archive_write *)_a; + struct mtree_writer *mtree; + + mtree = (struct mtree_writer *)a->format_data; + + /* Set to output a mtree archive in classic format. */ + mtree->classic = 1; + /* Basically, mtree classic format uses '/set' global + * value. */ + mtree->output_global_set = 1; + } + return (r); +} + +static void +sum_init(struct mtree_writer *mtree) +{ + + mtree->compute_sum = 0; + + if (mtree->keys & F_CKSUM) { + mtree->compute_sum |= F_CKSUM; + mtree->crc = 0; + mtree->crc_len = 0; + } +#ifdef ARCHIVE_HAS_MD5 + if (mtree->keys & F_MD5) { + if (archive_md5_init(&mtree->md5ctx) == ARCHIVE_OK) + mtree->compute_sum |= F_MD5; + else + mtree->keys &= ~F_MD5;/* Not supported. */ + } +#endif +#ifdef ARCHIVE_HAS_RMD160 + if (mtree->keys & F_RMD160) { + if (archive_rmd160_init(&mtree->rmd160ctx) == ARCHIVE_OK) + mtree->compute_sum |= F_RMD160; + else + mtree->keys &= ~F_RMD160;/* Not supported. */ + } +#endif +#ifdef ARCHIVE_HAS_SHA1 + if (mtree->keys & F_SHA1) { + if (archive_sha1_init(&mtree->sha1ctx) == ARCHIVE_OK) + mtree->compute_sum |= F_SHA1; + else + mtree->keys &= ~F_SHA1;/* Not supported. */ + } +#endif +#ifdef ARCHIVE_HAS_SHA256 + if (mtree->keys & F_SHA256) { + if (archive_sha256_init(&mtree->sha256ctx) == ARCHIVE_OK) + mtree->compute_sum |= F_SHA256; + else + mtree->keys &= ~F_SHA256;/* Not supported. */ + } +#endif +#ifdef ARCHIVE_HAS_SHA384 + if (mtree->keys & F_SHA384) { + if (archive_sha384_init(&mtree->sha384ctx) == ARCHIVE_OK) + mtree->compute_sum |= F_SHA384; + else + mtree->keys &= ~F_SHA384;/* Not supported. */ + } +#endif +#ifdef ARCHIVE_HAS_SHA512 + if (mtree->keys & F_SHA512) { + if (archive_sha512_init(&mtree->sha512ctx) == ARCHIVE_OK) + mtree->compute_sum |= F_SHA512; + else + mtree->keys &= ~F_SHA512;/* Not supported. */ + } +#endif +} + +static void +sum_update(struct mtree_writer *mtree, const void *buff, size_t n) +{ + if (mtree->compute_sum & F_CKSUM) { + /* + * Compute a POSIX 1003.2 checksum + */ + const unsigned char *p; + size_t nn; + + for (nn = n, p = buff; nn--; ++p) + COMPUTE_CRC(mtree->crc, *p); + mtree->crc_len += n; + } +#ifdef ARCHIVE_HAS_MD5 + if (mtree->compute_sum & F_MD5) + archive_md5_update(&mtree->md5ctx, buff, n); +#endif +#ifdef ARCHIVE_HAS_RMD160 + if (mtree->compute_sum & F_RMD160) + archive_rmd160_update(&mtree->rmd160ctx, buff, n); +#endif +#ifdef ARCHIVE_HAS_SHA1 + if (mtree->compute_sum & F_SHA1) + archive_sha1_update(&mtree->sha1ctx, buff, n); +#endif +#ifdef ARCHIVE_HAS_SHA256 + if (mtree->compute_sum & F_SHA256) + archive_sha256_update(&mtree->sha256ctx, buff, n); +#endif +#ifdef ARCHIVE_HAS_SHA384 + if (mtree->compute_sum & F_SHA384) + archive_sha384_update(&mtree->sha384ctx, buff, n); +#endif +#ifdef ARCHIVE_HAS_SHA512 + if (mtree->compute_sum & F_SHA512) + archive_sha512_update(&mtree->sha512ctx, buff, n); +#endif +} + +static void +sum_final(struct mtree_writer *mtree, struct reg_info *reg) +{ + + if (mtree->compute_sum & F_CKSUM) { + uint64_t len; + /* Include the length of the file. */ + for (len = mtree->crc_len; len != 0; len >>= 8) + COMPUTE_CRC(mtree->crc, len & 0xff); + reg->crc = ~mtree->crc; + } +#ifdef ARCHIVE_HAS_MD5 + if (mtree->compute_sum & F_MD5) + archive_md5_final(&mtree->md5ctx, reg->buf_md5); +#endif +#ifdef ARCHIVE_HAS_RMD160 + if (mtree->compute_sum & F_RMD160) + archive_rmd160_final(&mtree->rmd160ctx, reg->buf_rmd160); +#endif +#ifdef ARCHIVE_HAS_SHA1 + if (mtree->compute_sum & F_SHA1) + archive_sha1_final(&mtree->sha1ctx, reg->buf_sha1); +#endif +#ifdef ARCHIVE_HAS_SHA256 + if (mtree->compute_sum & F_SHA256) + archive_sha256_final(&mtree->sha256ctx, reg->buf_sha256); +#endif +#ifdef ARCHIVE_HAS_SHA384 + if (mtree->compute_sum & F_SHA384) + archive_sha384_final(&mtree->sha384ctx, reg->buf_sha384); +#endif +#ifdef ARCHIVE_HAS_SHA512 + if (mtree->compute_sum & F_SHA512) + archive_sha512_final(&mtree->sha512ctx, reg->buf_sha512); +#endif + /* Save what types of sum are computed. */ + reg->compute_sum = mtree->compute_sum; +} + +#if defined(ARCHIVE_HAS_MD5) || defined(ARCHIVE_HAS_RMD160) || \ + defined(ARCHIVE_HAS_SHA1) || defined(ARCHIVE_HAS_SHA256) || \ + defined(ARCHIVE_HAS_SHA384) || defined(ARCHIVE_HAS_SHA512) +static void +strappend_bin(struct archive_string *s, const unsigned char *bin, int n) +{ + static const char hex[] = "0123456789abcdef"; + int i; + + for (i = 0; i < n; i++) { + archive_strappend_char(s, hex[bin[i] >> 4]); + archive_strappend_char(s, hex[bin[i] & 0x0f]); + } +} +#endif + +static void +sum_write(struct archive_string *str, struct reg_info *reg) +{ + + if (reg->compute_sum & F_CKSUM) { + archive_string_sprintf(str, " cksum=%ju", + (uintmax_t)reg->crc); + } +#ifdef ARCHIVE_HAS_MD5 + if (reg->compute_sum & F_MD5) { + archive_strcat(str, " md5digest="); + strappend_bin(str, reg->buf_md5, sizeof(reg->buf_md5)); + } +#endif +#ifdef ARCHIVE_HAS_RMD160 + if (reg->compute_sum & F_RMD160) { + archive_strcat(str, " rmd160digest="); + strappend_bin(str, reg->buf_rmd160, sizeof(reg->buf_rmd160)); + } +#endif +#ifdef ARCHIVE_HAS_SHA1 + if (reg->compute_sum & F_SHA1) { + archive_strcat(str, " sha1digest="); + strappend_bin(str, reg->buf_sha1, sizeof(reg->buf_sha1)); + } +#endif +#ifdef ARCHIVE_HAS_SHA256 + if (reg->compute_sum & F_SHA256) { + archive_strcat(str, " sha256digest="); + strappend_bin(str, reg->buf_sha256, sizeof(reg->buf_sha256)); + } +#endif +#ifdef ARCHIVE_HAS_SHA384 + if (reg->compute_sum & F_SHA384) { + archive_strcat(str, " sha384digest="); + strappend_bin(str, reg->buf_sha384, sizeof(reg->buf_sha384)); + } +#endif +#ifdef ARCHIVE_HAS_SHA512 + if (reg->compute_sum & F_SHA512) { + archive_strcat(str, " sha512digest="); + strappend_bin(str, reg->buf_sha512, sizeof(reg->buf_sha512)); + } +#endif +} + +static int +mtree_entry_cmp_node(const struct archive_rb_node *n1, + const struct archive_rb_node *n2) +{ + const struct mtree_entry *e1 = (const struct mtree_entry *)n1; + const struct mtree_entry *e2 = (const struct mtree_entry *)n2; + + return (strcmp(e2->basename.s, e1->basename.s)); +} + +static int +mtree_entry_cmp_key(const struct archive_rb_node *n, const void *key) +{ + const struct mtree_entry *e = (const struct mtree_entry *)n; + + return (strcmp((const char *)key, e->basename.s)); +} + +#if defined(_WIN32) || defined(__CYGWIN__) +static int +cleanup_backslash_1(char *p) +{ + int mb, dos; + + mb = dos = 0; + while (*p) { + if (*(unsigned char *)p > 127) + mb = 1; + if (*p == '\\') { + /* If we have not met any multi-byte characters, + * we can replace '\' with '/'. */ + if (!mb) + *p = '/'; + dos = 1; + } + p++; + } + if (!mb || !dos) + return (0); + return (-1); +} + +static void +cleanup_backslash_2(wchar_t *p) +{ + + /* Convert a path-separator from '\' to '/' */ + while (*p != L'\0') { + if (*p == L'\\') + *p = L'/'; + p++; + } +} +#endif + +/* + * Generate a parent directory name and a base name from a pathname. + */ +static int +mtree_entry_setup_filenames(struct archive_write *a, struct mtree_entry *file, + struct archive_entry *entry) +{ + const char *pathname; + char *p, *dirname, *slash; + size_t len; + int ret = ARCHIVE_OK; + + archive_strcpy(&file->pathname, archive_entry_pathname(entry)); +#if defined(_WIN32) || defined(__CYGWIN__) + /* + * Convert a path-separator from '\' to '/' + */ + if (cleanup_backslash_1(file->pathname.s) != 0) { + const wchar_t *wp = archive_entry_pathname_w(entry); + struct archive_wstring ws; + + if (wp != NULL) { + int r; + archive_string_init(&ws); + archive_wstrcpy(&ws, wp); + cleanup_backslash_2(ws.s); + archive_string_empty(&(file->pathname)); + r = archive_string_append_from_wcs(&(file->pathname), + ws.s, ws.length); + archive_wstring_free(&ws); + if (r < 0 && errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + } + } +#else + (void)a; /* UNUSED */ +#endif + pathname = file->pathname.s; + if (strcmp(pathname, ".") == 0) { + archive_strcpy(&file->basename, "."); + return (ARCHIVE_OK); + } + + archive_strcpy(&(file->parentdir), pathname); + + len = file->parentdir.length; + p = dirname = file->parentdir.s; + + /* + * Remove leading '/' and '../' elements + */ + while (*p) { + if (p[0] == '/') { + p++; + len--; + } else if (p[0] != '.') + break; + else if (p[1] == '.' && p[2] == '/') { + p += 3; + len -= 3; + } else + break; + } + if (p != dirname) { + memmove(dirname, p, len+1); + p = dirname; + } + /* + * Remove "/","/." and "/.." elements from tail. + */ + while (len > 0) { + size_t ll = len; + + if (len > 0 && p[len-1] == '/') { + p[len-1] = '\0'; + len--; + } + if (len > 1 && p[len-2] == '/' && p[len-1] == '.') { + p[len-2] = '\0'; + len -= 2; + } + if (len > 2 && p[len-3] == '/' && p[len-2] == '.' && + p[len-1] == '.') { + p[len-3] = '\0'; + len -= 3; + } + if (ll == len) + break; + } + while (*p) { + if (p[0] == '/') { + if (p[1] == '/') + /* Convert '//' --> '/' */ + memmove(p, p+1, strlen(p+1) + 1); + else if (p[1] == '.' && p[2] == '/') + /* Convert '/./' --> '/' */ + memmove(p, p+2, strlen(p+2) + 1); + else if (p[1] == '.' && p[2] == '.' && p[3] == '/') { + /* Convert 'dir/dir1/../dir2/' + * --> 'dir/dir2/' + */ + char *rp = p -1; + while (rp >= dirname) { + if (*rp == '/') + break; + --rp; + } + if (rp > dirname) { + strcpy(rp, p+3); + p = rp; + } else { + strcpy(dirname, p+4); + p = dirname; + } + } else + p++; + } else + p++; + } + p = dirname; + len = strlen(p); + + /* + * Add "./" prefix. + * NOTE: If the pathname does not have a path separator, we have + * to add "./" to the head of the pathname because mtree reader + * will suppose that it is v1(a.k.a classic) mtree format and + * change the directory unexpectedly and so it will make a wrong + * path. + */ + if (strcmp(p, ".") != 0 && strncmp(p, "./", 2) != 0) { + struct archive_string as; + archive_string_init(&as); + archive_strcpy(&as, "./"); + archive_strncat(&as, p, len); + archive_string_empty(&file->parentdir); + archive_string_concat(&file->parentdir, &as); + archive_string_free(&as); + p = file->parentdir.s; + len = archive_strlen(&file->parentdir); + } + + /* + * Find out the position which points the last position of + * path separator('/'). + */ + slash = NULL; + for (; *p != '\0'; p++) { + if (*p == '/') + slash = p; + } + if (slash == NULL) { + /* The pathname doesn't have a parent directory. */ + file->parentdir.length = len; + archive_string_copy(&(file->basename), &(file->parentdir)); + archive_string_empty(&(file->parentdir)); + *file->parentdir.s = '\0'; + return (ret); + } + + /* Make a basename from file->parentdir.s and slash */ + *slash = '\0'; + file->parentdir.length = slash - file->parentdir.s; + archive_strcpy(&(file->basename), slash + 1); + return (ret); +} + +static int +mtree_entry_create_virtual_dir(struct archive_write *a, const char *pathname, + struct mtree_entry **m_entry) +{ + struct archive_entry *entry; + struct mtree_entry *file; + int r; + + entry = archive_entry_new(); + if (entry == NULL) { + *m_entry = NULL; + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + archive_entry_copy_pathname(entry, pathname); + archive_entry_set_mode(entry, AE_IFDIR | 0755); + archive_entry_set_mtime(entry, time(NULL), 0); + + r = mtree_entry_new(a, entry, &file); + archive_entry_free(entry); + if (r < ARCHIVE_WARN) { + *m_entry = NULL; + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + + file->dir_info->virtual = 1; + + *m_entry = file; + return (ARCHIVE_OK); +} + +static void +mtree_entry_register_add(struct mtree_writer *mtree, struct mtree_entry *file) +{ + file->next = NULL; + *mtree->file_list.last = file; + mtree->file_list.last = &(file->next); +} + +static void +mtree_entry_register_init(struct mtree_writer *mtree) +{ + mtree->file_list.first = NULL; + mtree->file_list.last = &(mtree->file_list.first); +} + +static void +mtree_entry_register_free(struct mtree_writer *mtree) +{ + struct mtree_entry *file, *file_next; + + file = mtree->file_list.first; + while (file != NULL) { + file_next = file->next; + mtree_entry_free(file); + file = file_next; + } +} + +static int +mtree_entry_add_child_tail(struct mtree_entry *parent, + struct mtree_entry *child) +{ + child->dir_info->chnext = NULL; + *parent->dir_info->children.last = child; + parent->dir_info->children.last = &(child->dir_info->chnext); + return (1); +} + +/* + * Find a entry from a parent entry with the name. + */ +static struct mtree_entry * +mtree_entry_find_child(struct mtree_entry *parent, const char *child_name) +{ + struct mtree_entry *np; + + if (parent == NULL) + return (NULL); + np = (struct mtree_entry *)__archive_rb_tree_find_node( + &(parent->dir_info->rbtree), child_name); + return (np); +} + +static int +get_path_component(char *name, size_t n, const char *fn) +{ + char *p; + size_t l; + + p = strchr(fn, '/'); + if (p == NULL) { + if ((l = strlen(fn)) == 0) + return (0); + } else + l = p - fn; + if (l > n -1) + return (-1); + memcpy(name, fn, l); + name[l] = '\0'; + + return ((int)l); +} + +/* + * Add a new entry into the tree. + */ +static int +mtree_entry_tree_add(struct archive_write *a, struct mtree_entry **filep) +{ +#if defined(_WIN32) && !defined(__CYGWIN__) + char name[_MAX_FNAME];/* Included null terminator size. */ +#elif defined(NAME_MAX) && NAME_MAX >= 255 + char name[NAME_MAX+1]; +#else + char name[256]; +#endif + struct mtree_writer *mtree = (struct mtree_writer *)a->format_data; + struct mtree_entry *dent, *file, *np; + const char *fn, *p; + int l, r; + + file = *filep; + if (file->parentdir.length == 0 && file->basename.length == 1 && + file->basename.s[0] == '.') { + file->parent = file; + if (mtree->root != NULL) { + np = mtree->root; + goto same_entry; + } + mtree->root = file; + mtree_entry_register_add(mtree, file); + return (ARCHIVE_OK); + } + + if (file->parentdir.length == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Internal programming error " + "in generating canonical name for %s", + file->pathname.s); + return (ARCHIVE_FAILED); + } + + fn = p = file->parentdir.s; + + /* + * If the path of the parent directory of `file' entry is + * the same as the path of `cur_dirent', add `file' entry to + * `cur_dirent'. + */ + if (archive_strlen(&(mtree->cur_dirstr)) + == archive_strlen(&(file->parentdir)) && + strcmp(mtree->cur_dirstr.s, fn) == 0) { + if (!__archive_rb_tree_insert_node( + &(mtree->cur_dirent->dir_info->rbtree), + (struct archive_rb_node *)file)) { + /* There is the same name in the tree. */ + np = (struct mtree_entry *)__archive_rb_tree_find_node( + &(mtree->cur_dirent->dir_info->rbtree), + file->basename.s); + goto same_entry; + } + file->parent = mtree->cur_dirent; + mtree_entry_register_add(mtree, file); + return (ARCHIVE_OK); + } + + dent = mtree->root; + for (;;) { + l = get_path_component(name, sizeof(name), fn); + if (l == 0) { + np = NULL; + break; + } + if (l < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "A name buffer is too small"); + return (ARCHIVE_FATAL); + } + if (l == 1 && name[0] == '.' && dent != NULL && + dent == mtree->root) { + fn += l; + if (fn[0] == '/') + fn++; + continue; + } + + np = mtree_entry_find_child(dent, name); + if (np == NULL || fn[0] == '\0') + break; + + /* Find next sub directory. */ + if (!np->dir_info) { + /* NOT Directory! */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "`%s' is not directory, we cannot insert `%s' ", + np->pathname.s, file->pathname.s); + return (ARCHIVE_FAILED); + } + fn += l; + if (fn[0] == '/') + fn++; + dent = np; + } + if (np == NULL) { + /* + * Create virtual parent directories. + */ + while (fn[0] != '\0') { + struct mtree_entry *vp; + struct archive_string as; + + archive_string_init(&as); + archive_strncat(&as, p, fn - p + l); + if (as.s[as.length-1] == '/') { + as.s[as.length-1] = '\0'; + as.length--; + } + r = mtree_entry_create_virtual_dir(a, as.s, &vp); + archive_string_free(&as); + if (r < ARCHIVE_WARN) + return (r); + + if (strcmp(vp->pathname.s, ".") == 0) { + vp->parent = vp; + mtree->root = vp; + } else { + __archive_rb_tree_insert_node( + &(dent->dir_info->rbtree), + (struct archive_rb_node *)vp); + vp->parent = dent; + } + mtree_entry_register_add(mtree, vp); + np = vp; + + fn += l; + if (fn[0] == '/') + fn++; + l = get_path_component(name, sizeof(name), fn); + if (l < 0) { + archive_string_free(&as); + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "A name buffer is too small"); + return (ARCHIVE_FATAL); + } + dent = np; + } + + /* Found out the parent directory where `file' can be + * inserted. */ + mtree->cur_dirent = dent; + archive_string_empty(&(mtree->cur_dirstr)); + archive_string_ensure(&(mtree->cur_dirstr), + archive_strlen(&(dent->parentdir)) + + archive_strlen(&(dent->basename)) + 2); + if (archive_strlen(&(dent->parentdir)) + + archive_strlen(&(dent->basename)) == 0) + mtree->cur_dirstr.s[0] = 0; + else { + if (archive_strlen(&(dent->parentdir)) > 0) { + archive_string_copy(&(mtree->cur_dirstr), + &(dent->parentdir)); + archive_strappend_char( + &(mtree->cur_dirstr), '/'); + } + archive_string_concat(&(mtree->cur_dirstr), + &(dent->basename)); + } + + if (!__archive_rb_tree_insert_node( + &(dent->dir_info->rbtree), + (struct archive_rb_node *)file)) { + np = (struct mtree_entry *)__archive_rb_tree_find_node( + &(dent->dir_info->rbtree), file->basename.s); + goto same_entry; + } + file->parent = dent; + mtree_entry_register_add(mtree, file); + return (ARCHIVE_OK); + } + +same_entry: + /* + * We have already has the entry the filename of which is + * the same. + */ + r = mtree_entry_exchange_same_entry(a, np, file); + if (r < ARCHIVE_WARN) + return (r); + if (np->dir_info) + np->dir_info->virtual = 0; + *filep = np; + mtree_entry_free(file); + return (ARCHIVE_WARN); +} + +static int +mtree_entry_exchange_same_entry(struct archive_write *a, struct mtree_entry *np, + struct mtree_entry *file) +{ + + if ((np->mode & AE_IFMT) != (file->mode & AE_IFMT)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Found duplicate entries `%s' and its file type is " + "different", + np->pathname.s); + return (ARCHIVE_FAILED); + } + + /* Update the existent mtree entry's attributes by the new one's. */ + archive_string_empty(&np->symlink); + archive_string_concat(&np->symlink, &file->symlink); + archive_string_empty(&np->uname); + archive_string_concat(&np->uname, &file->uname); + archive_string_empty(&np->gname); + archive_string_concat(&np->gname, &file->gname); + archive_string_empty(&np->fflags_text); + archive_string_concat(&np->fflags_text, &file->fflags_text); + np->nlink = file->nlink; + np->filetype = file->filetype; + np->mode = file->mode; + np->size = file->size; + np->uid = file->uid; + np->gid = file->gid; + np->fflags_set = file->fflags_set; + np->fflags_clear = file->fflags_clear; + np->mtime = file->mtime; + np->mtime_nsec = file->mtime_nsec; + np->rdevmajor = file->rdevmajor; + np->rdevminor = file->rdevminor; + np->devmajor = file->devmajor; + np->devminor = file->devminor; + np->ino = file->ino; + + return (ARCHIVE_WARN); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_pax.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_pax.c new file mode 100644 index 0000000000..a2b2710719 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_pax.c @@ -0,0 +1,2044 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2010-2012 Michihiro NAKAJIMA + * Copyright (c) 2016 Martin Matuska + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_pax.c 201162 2009-12-29 05:47:46Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_write_private.h" +#include "archive_write_set_format_private.h" + +struct sparse_block { + struct sparse_block *next; + int is_hole; + uint64_t offset; + uint64_t remaining; +}; + +struct pax { + uint64_t entry_bytes_remaining; + uint64_t entry_padding; + struct archive_string l_url_encoded_name; + struct archive_string pax_header; + struct archive_string sparse_map; + size_t sparse_map_padding; + struct sparse_block *sparse_list; + struct sparse_block *sparse_tail; + struct archive_string_conv *sconv_utf8; + int opt_binary; + + unsigned flags; +#define WRITE_SCHILY_XATTR (1 << 0) +#define WRITE_LIBARCHIVE_XATTR (1 << 1) +}; + +static void add_pax_attr(struct archive_string *, const char *key, + const char *value); +static void add_pax_attr_binary(struct archive_string *, + const char *key, + const char *value, size_t value_len); +static void add_pax_attr_int(struct archive_string *, + const char *key, int64_t value); +static void add_pax_attr_time(struct archive_string *, + const char *key, int64_t sec, + unsigned long nanos); +static int add_pax_acl(struct archive_write *, + struct archive_entry *, struct pax *, int); +static ssize_t archive_write_pax_data(struct archive_write *, + const void *, size_t); +static int archive_write_pax_close(struct archive_write *); +static int archive_write_pax_free(struct archive_write *); +static int archive_write_pax_finish_entry(struct archive_write *); +static int archive_write_pax_header(struct archive_write *, + struct archive_entry *); +static int archive_write_pax_options(struct archive_write *, + const char *, const char *); +static char *base64_encode(const char *src, size_t len); +static char *build_gnu_sparse_name(char *dest, const char *src); +static char *build_pax_attribute_name(char *dest, const char *src); +static char *build_ustar_entry_name(char *dest, const char *src, + size_t src_length, const char *insert); +static char *format_int(char *dest, int64_t); +static int has_non_ASCII(const char *); +static void sparse_list_clear(struct pax *); +static int sparse_list_add(struct pax *, int64_t, int64_t); +static char *url_encode(const char *in); + +/* + * Set output format to 'restricted pax' format. + * + * This is the same as normal 'pax', but tries to suppress + * the pax header whenever possible. This is the default for + * bsdtar, for instance. + */ +int +archive_write_set_format_pax_restricted(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + int r; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_pax_restricted"); + + r = archive_write_set_format_pax(&a->archive); + a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED; + a->archive.archive_format_name = "restricted POSIX pax interchange"; + return (r); +} + +/* + * Set output format to 'pax' format. + */ +int +archive_write_set_format_pax(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct pax *pax; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_pax"); + + if (a->format_free != NULL) + (a->format_free)(a); + + pax = (struct pax *)calloc(1, sizeof(*pax)); + if (pax == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate pax data"); + return (ARCHIVE_FATAL); + } + pax->flags = WRITE_LIBARCHIVE_XATTR | WRITE_SCHILY_XATTR; + + a->format_data = pax; + a->format_name = "pax"; + a->format_options = archive_write_pax_options; + a->format_write_header = archive_write_pax_header; + a->format_write_data = archive_write_pax_data; + a->format_close = archive_write_pax_close; + a->format_free = archive_write_pax_free; + a->format_finish_entry = archive_write_pax_finish_entry; + a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE; + a->archive.archive_format_name = "POSIX pax interchange"; + return (ARCHIVE_OK); +} + +static int +archive_write_pax_options(struct archive_write *a, const char *key, + const char *val) +{ + struct pax *pax = (struct pax *)a->format_data; + int ret = ARCHIVE_FAILED; + + if (strcmp(key, "hdrcharset") == 0) { + /* + * The character-set we can use are defined in + * IEEE Std 1003.1-2001 + */ + if (val == NULL || val[0] == 0) + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "pax: hdrcharset option needs a character-set name"); + else if (strcmp(val, "BINARY") == 0 || + strcmp(val, "binary") == 0) { + /* + * Specify binary mode. We will not convert + * filenames, uname and gname to any charsets. + */ + pax->opt_binary = 1; + ret = ARCHIVE_OK; + } else if (strcmp(val, "UTF-8") == 0) { + /* + * Specify UTF-8 character-set to be used for + * filenames. This is almost the test that + * running platform supports the string conversion. + * Especially libarchive_test needs this trick for + * its test. + */ + pax->sconv_utf8 = archive_string_conversion_to_charset( + &(a->archive), "UTF-8", 0); + if (pax->sconv_utf8 == NULL) + ret = ARCHIVE_FATAL; + else + ret = ARCHIVE_OK; + } else + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "pax: invalid charset name"); + return (ret); + } else if (strcmp(key, "xattrheader") == 0) { + if (val == NULL || val[0] == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "pax: xattrheader requires a value"); + } else if (strcmp(val, "ALL") == 0 || + strcmp(val, "all") == 0) { + pax->flags |= WRITE_LIBARCHIVE_XATTR | WRITE_SCHILY_XATTR; + ret = ARCHIVE_OK; + } else if (strcmp(val, "SCHILY") == 0 || + strcmp(val, "schily") == 0) { + pax->flags |= WRITE_SCHILY_XATTR; + pax->flags &= ~WRITE_LIBARCHIVE_XATTR; + ret = ARCHIVE_OK; + } else if (strcmp(val, "LIBARCHIVE") == 0 || + strcmp(val, "libarchive") == 0) { + pax->flags |= WRITE_LIBARCHIVE_XATTR; + pax->flags &= ~WRITE_SCHILY_XATTR; + ret = ARCHIVE_OK; + } else + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "pax: invalid xattr header name"); + return (ret); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +/* + * Note: This code assumes that 'nanos' has the same sign as 'sec', + * which implies that sec=-1, nanos=200000000 represents -1.2 seconds + * and not -0.8 seconds. This is a pretty pedantic point, as we're + * unlikely to encounter many real files created before Jan 1, 1970, + * much less ones with timestamps recorded to sub-second resolution. + */ +static void +add_pax_attr_time(struct archive_string *as, const char *key, + int64_t sec, unsigned long nanos) +{ + int digit, i; + char *t; + /* + * Note that each byte contributes fewer than 3 base-10 + * digits, so this will always be big enough. + */ + char tmp[1 + 3*sizeof(sec) + 1 + 3*sizeof(nanos)]; + + tmp[sizeof(tmp) - 1] = 0; + t = tmp + sizeof(tmp) - 1; + + /* Skip trailing zeros in the fractional part. */ + for (digit = 0, i = 10; i > 0 && digit == 0; i--) { + digit = nanos % 10; + nanos /= 10; + } + + /* Only format the fraction if it's non-zero. */ + if (i > 0) { + while (i > 0) { + *--t = "0123456789"[digit]; + digit = nanos % 10; + nanos /= 10; + i--; + } + *--t = '.'; + } + t = format_int(t, sec); + + add_pax_attr(as, key, t); +} + +static char * +format_int(char *t, int64_t i) +{ + uint64_t ui; + + if (i < 0) + ui = (i == INT64_MIN) ? (uint64_t)(INT64_MAX) + 1 : (uint64_t)(-i); + else + ui = i; + + do { + *--t = "0123456789"[ui % 10]; + } while (ui /= 10); + if (i < 0) + *--t = '-'; + return (t); +} + +static void +add_pax_attr_int(struct archive_string *as, const char *key, int64_t value) +{ + char tmp[1 + 3 * sizeof(value)]; + + tmp[sizeof(tmp) - 1] = 0; + add_pax_attr(as, key, format_int(tmp + sizeof(tmp) - 1, value)); +} + +/* + * Add a key/value attribute to the pax header. This function handles + * the length field and various other syntactic requirements. + */ +static void +add_pax_attr(struct archive_string *as, const char *key, const char *value) +{ + add_pax_attr_binary(as, key, value, strlen(value)); +} + +/* + * Add a key/value attribute to the pax header. This function handles + * binary values. + */ +static void +add_pax_attr_binary(struct archive_string *as, const char *key, + const char *value, size_t value_len) +{ + int digits, i, len, next_ten; + char tmp[1 + 3 * sizeof(int)]; /* < 3 base-10 digits per byte */ + + /*- + * PAX attributes have the following layout: + * <len> <space> <key> <=> <value> <nl> + */ + len = 1 + (int)strlen(key) + 1 + (int)value_len + 1; + + /* + * The <len> field includes the length of the <len> field, so + * computing the correct length is tricky. I start by + * counting the number of base-10 digits in 'len' and + * computing the next higher power of 10. + */ + next_ten = 1; + digits = 0; + i = len; + while (i > 0) { + i = i / 10; + digits++; + next_ten = next_ten * 10; + } + /* + * For example, if string without the length field is 99 + * chars, then adding the 2 digit length "99" will force the + * total length past 100, requiring an extra digit. The next + * statement adjusts for this effect. + */ + if (len + digits >= next_ten) + digits++; + + /* Now, we have the right length so we can build the line. */ + tmp[sizeof(tmp) - 1] = 0; /* Null-terminate the work area. */ + archive_strcat(as, format_int(tmp + sizeof(tmp) - 1, len + digits)); + archive_strappend_char(as, ' '); + archive_strcat(as, key); + archive_strappend_char(as, '='); + archive_array_append(as, value, value_len); + archive_strappend_char(as, '\n'); +} + +static void +archive_write_pax_header_xattr(struct pax *pax, const char *encoded_name, + const void *value, size_t value_len) +{ + struct archive_string s; + char *encoded_value; + + if (pax->flags & WRITE_LIBARCHIVE_XATTR) { + encoded_value = base64_encode((const char *)value, value_len); + + if (encoded_name != NULL && encoded_value != NULL) { + archive_string_init(&s); + archive_strcpy(&s, "LIBARCHIVE.xattr."); + archive_strcat(&s, encoded_name); + add_pax_attr(&(pax->pax_header), s.s, encoded_value); + archive_string_free(&s); + } + free(encoded_value); + } + if (pax->flags & WRITE_SCHILY_XATTR) { + archive_string_init(&s); + archive_strcpy(&s, "SCHILY.xattr."); + archive_strcat(&s, encoded_name); + add_pax_attr_binary(&(pax->pax_header), s.s, value, value_len); + archive_string_free(&s); + } +} + +static int +archive_write_pax_header_xattrs(struct archive_write *a, + struct pax *pax, struct archive_entry *entry) +{ + int i = archive_entry_xattr_reset(entry); + + while (i--) { + const char *name; + const void *value; + char *url_encoded_name = NULL, *encoded_name = NULL; + size_t size; + int r; + + archive_entry_xattr_next(entry, &name, &value, &size); + url_encoded_name = url_encode(name); + if (url_encoded_name != NULL) { + /* Convert narrow-character to UTF-8. */ + r = archive_strcpy_l(&(pax->l_url_encoded_name), + url_encoded_name, pax->sconv_utf8); + free(url_encoded_name); /* Done with this. */ + if (r == 0) + encoded_name = pax->l_url_encoded_name.s; + else if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Linkname"); + return (ARCHIVE_FATAL); + } + } + + archive_write_pax_header_xattr(pax, encoded_name, + value, size); + + } + return (ARCHIVE_OK); +} + +static int +get_entry_hardlink(struct archive_write *a, struct archive_entry *entry, + const char **name, size_t *length, struct archive_string_conv *sc) +{ + int r; + + r = archive_entry_hardlink_l(entry, name, length, sc); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Linkname"); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_WARN); + } + return (ARCHIVE_OK); +} + +static int +get_entry_pathname(struct archive_write *a, struct archive_entry *entry, + const char **name, size_t *length, struct archive_string_conv *sc) +{ + int r; + + r = archive_entry_pathname_l(entry, name, length, sc); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_WARN); + } + return (ARCHIVE_OK); +} + +static int +get_entry_uname(struct archive_write *a, struct archive_entry *entry, + const char **name, size_t *length, struct archive_string_conv *sc) +{ + int r; + + r = archive_entry_uname_l(entry, name, length, sc); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Uname"); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_WARN); + } + return (ARCHIVE_OK); +} + +static int +get_entry_gname(struct archive_write *a, struct archive_entry *entry, + const char **name, size_t *length, struct archive_string_conv *sc) +{ + int r; + + r = archive_entry_gname_l(entry, name, length, sc); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Gname"); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_WARN); + } + return (ARCHIVE_OK); +} + +static int +get_entry_symlink(struct archive_write *a, struct archive_entry *entry, + const char **name, size_t *length, struct archive_string_conv *sc) +{ + int r; + + r = archive_entry_symlink_l(entry, name, length, sc); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Linkname"); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_WARN); + } + return (ARCHIVE_OK); +} + +/* Add ACL to pax header */ +static int +add_pax_acl(struct archive_write *a, + struct archive_entry *entry, struct pax *pax, int flags) +{ + char *p; + const char *attr; + int acl_types; + + acl_types = archive_entry_acl_types(entry); + + if ((acl_types & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) + attr = "SCHILY.acl.ace"; + else if ((flags & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) + attr = "SCHILY.acl.access"; + else if ((flags & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0) + attr = "SCHILY.acl.default"; + else + return (ARCHIVE_FATAL); + + p = archive_entry_acl_to_text_l(entry, NULL, flags, pax->sconv_utf8); + if (p == NULL) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, "%s %s", + "Can't allocate memory for ", attr); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, "%s %s %s", + "Can't translate ", attr, " to UTF-8"); + return(ARCHIVE_WARN); + } + + if (*p != '\0') { + add_pax_attr(&(pax->pax_header), + attr, p); + } + free(p); + return(ARCHIVE_OK); +} + +/* + * TODO: Consider adding 'comment' and 'charset' fields to + * archive_entry so that clients can specify them. Also, consider + * adding generic key/value tags so clients can add arbitrary + * key/value data. + * + * TODO: Break up this 700-line function!!!! Yowza! + */ +static int +archive_write_pax_header(struct archive_write *a, + struct archive_entry *entry_original) +{ + struct archive_entry *entry_main; + const char *p; + const char *suffix; + int need_extension, r, ret; + int acl_types; + int sparse_count; + uint64_t sparse_total, real_size; + struct pax *pax; + const char *hardlink; + const char *path = NULL, *linkpath = NULL; + const char *uname = NULL, *gname = NULL; + const void *mac_metadata; + size_t mac_metadata_size; + struct archive_string_conv *sconv; + size_t hardlink_length, path_length, linkpath_length; + size_t uname_length, gname_length; + + char paxbuff[512]; + char ustarbuff[512]; + char ustar_entry_name[256]; + char pax_entry_name[256]; + char gnu_sparse_name[256]; + struct archive_string entry_name; + + ret = ARCHIVE_OK; + need_extension = 0; + pax = (struct pax *)a->format_data; + + /* Sanity check. */ + if (archive_entry_pathname(entry_original) == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can't record entry in tar file without pathname"); + return (ARCHIVE_FAILED); + } + + /* + * Choose a header encoding. + */ + if (pax->opt_binary) + sconv = NULL;/* Binary mode. */ + else { + /* Header encoding is UTF-8. */ + if (pax->sconv_utf8 == NULL) { + /* Initialize the string conversion object + * we must need */ + pax->sconv_utf8 = archive_string_conversion_to_charset( + &(a->archive), "UTF-8", 1); + if (pax->sconv_utf8 == NULL) + /* Couldn't allocate memory */ + return (ARCHIVE_FAILED); + } + sconv = pax->sconv_utf8; + } + + r = get_entry_hardlink(a, entry_original, &hardlink, + &hardlink_length, sconv); + if (r == ARCHIVE_FATAL) + return (r); + else if (r != ARCHIVE_OK) { + r = get_entry_hardlink(a, entry_original, &hardlink, + &hardlink_length, NULL); + if (r == ARCHIVE_FATAL) + return (r); + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate linkname '%s' to %s", hardlink, + archive_string_conversion_charset_name(sconv)); + ret = ARCHIVE_WARN; + sconv = NULL;/* The header charset switches to binary mode. */ + } + + /* Make sure this is a type of entry that we can handle here */ + if (hardlink == NULL) { + switch (archive_entry_filetype(entry_original)) { + case AE_IFBLK: + case AE_IFCHR: + case AE_IFIFO: + case AE_IFLNK: + case AE_IFREG: + break; + case AE_IFDIR: + { + /* + * Ensure a trailing '/'. Modify the original + * entry so the client sees the change. + */ +#if defined(_WIN32) && !defined(__CYGWIN__) + const wchar_t *wp; + + wp = archive_entry_pathname_w(entry_original); + if (wp != NULL && wp[wcslen(wp) -1] != L'/') { + struct archive_wstring ws; + + archive_string_init(&ws); + path_length = wcslen(wp); + if (archive_wstring_ensure(&ws, + path_length + 2) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate pax data"); + archive_wstring_free(&ws); + return(ARCHIVE_FATAL); + } + /* Should we keep '\' ? */ + if (wp[path_length -1] == L'\\') + path_length--; + archive_wstrncpy(&ws, wp, path_length); + archive_wstrappend_wchar(&ws, L'/'); + archive_entry_copy_pathname_w( + entry_original, ws.s); + archive_wstring_free(&ws); + p = NULL; + } else +#endif + p = archive_entry_pathname(entry_original); + /* + * On Windows, this is a backup operation just in + * case getting WCS failed. On POSIX, this is a + * normal operation. + */ + if (p != NULL && p[0] != '\0' && p[strlen(p) - 1] != '/') { + struct archive_string as; + + archive_string_init(&as); + path_length = strlen(p); + if (archive_string_ensure(&as, + path_length + 2) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate pax data"); + archive_string_free(&as); + return(ARCHIVE_FATAL); + } +#if defined(_WIN32) && !defined(__CYGWIN__) + /* NOTE: This might break the pathname + * if the current code page is CP932 and + * the pathname includes a character '\' + * as a part of its multibyte pathname. */ + if (p[strlen(p) -1] == '\\') + path_length--; + else +#endif + archive_strncpy(&as, p, path_length); + archive_strappend_char(&as, '/'); + archive_entry_copy_pathname( + entry_original, as.s); + archive_string_free(&as); + } + break; + } + default: /* AE_IFSOCK and unknown */ + __archive_write_entry_filetype_unsupported( + &a->archive, entry_original, "pax"); + return (ARCHIVE_FAILED); + } + } + + /* + * If Mac OS metadata blob is here, recurse to write that + * as a separate entry. This is really a pretty poor design: + * In particular, it doubles the overhead for long filenames. + * TODO: Help Apple folks design something better and figure + * out how to transition from this legacy format. + * + * Note that this code is present on every platform; clients + * on non-Mac are unlikely to ever provide this data, but + * applications that copy entries from one archive to another + * should not lose data just because the local filesystem + * can't store it. + */ + mac_metadata = + archive_entry_mac_metadata(entry_original, &mac_metadata_size); + if (mac_metadata != NULL) { + const char *oname; + char *name, *bname; + size_t name_length; + struct archive_entry *extra = archive_entry_new2(&a->archive); + + oname = archive_entry_pathname(entry_original); + name_length = strlen(oname); + name = malloc(name_length + 3); + if (name == NULL || extra == NULL) { + /* XXX error message */ + archive_entry_free(extra); + free(name); + return (ARCHIVE_FAILED); + } + strcpy(name, oname); + /* Find last '/'; strip trailing '/' characters */ + bname = strrchr(name, '/'); + while (bname != NULL && bname[1] == '\0') { + *bname = '\0'; + bname = strrchr(name, '/'); + } + if (bname == NULL) { + memmove(name + 2, name, name_length + 1); + memmove(name, "._", 2); + } else { + bname += 1; + memmove(bname + 2, bname, strlen(bname) + 1); + memmove(bname, "._", 2); + } + archive_entry_copy_pathname(extra, name); + free(name); + + archive_entry_set_size(extra, mac_metadata_size); + archive_entry_set_filetype(extra, AE_IFREG); + archive_entry_set_perm(extra, + archive_entry_perm(entry_original)); + archive_entry_set_mtime(extra, + archive_entry_mtime(entry_original), + archive_entry_mtime_nsec(entry_original)); + archive_entry_set_gid(extra, + archive_entry_gid(entry_original)); + archive_entry_set_gname(extra, + archive_entry_gname(entry_original)); + archive_entry_set_uid(extra, + archive_entry_uid(entry_original)); + archive_entry_set_uname(extra, + archive_entry_uname(entry_original)); + + /* Recurse to write the special copyfile entry. */ + r = archive_write_pax_header(a, extra); + archive_entry_free(extra); + if (r < ARCHIVE_WARN) + return (r); + if (r < ret) + ret = r; + r = (int)archive_write_pax_data(a, mac_metadata, + mac_metadata_size); + if (r < ARCHIVE_WARN) + return (r); + if (r < ret) + ret = r; + r = archive_write_pax_finish_entry(a); + if (r < ARCHIVE_WARN) + return (r); + if (r < ret) + ret = r; + } + + /* Copy entry so we can modify it as needed. */ +#if defined(_WIN32) && !defined(__CYGWIN__) + /* Make sure the path separators in pathname, hardlink and symlink + * are all slash '/', not the Windows path separator '\'. */ + entry_main = __la_win_entry_in_posix_pathseparator(entry_original); + if (entry_main == entry_original) + entry_main = archive_entry_clone(entry_original); +#else + entry_main = archive_entry_clone(entry_original); +#endif + if (entry_main == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate pax data"); + return(ARCHIVE_FATAL); + } + archive_string_empty(&(pax->pax_header)); /* Blank our work area. */ + archive_string_empty(&(pax->sparse_map)); + sparse_total = 0; + sparse_list_clear(pax); + + if (hardlink == NULL && + archive_entry_filetype(entry_main) == AE_IFREG) + sparse_count = archive_entry_sparse_reset(entry_main); + else + sparse_count = 0; + if (sparse_count) { + int64_t offset, length, last_offset = 0; + /* Get the last entry of sparse block. */ + while (archive_entry_sparse_next( + entry_main, &offset, &length) == ARCHIVE_OK) + last_offset = offset + length; + + /* If the last sparse block does not reach the end of file, + * We have to add a empty sparse block as the last entry to + * manage storing file data. */ + if (last_offset < archive_entry_size(entry_main)) + archive_entry_sparse_add_entry(entry_main, + archive_entry_size(entry_main), 0); + sparse_count = archive_entry_sparse_reset(entry_main); + } + + /* + * First, check the name fields and see if any of them + * require binary coding. If any of them does, then all of + * them do. + */ + r = get_entry_pathname(a, entry_main, &path, &path_length, sconv); + if (r == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + return (r); + } else if (r != ARCHIVE_OK) { + r = get_entry_pathname(a, entry_main, &path, + &path_length, NULL); + if (r == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + return (r); + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate pathname '%s' to %s", path, + archive_string_conversion_charset_name(sconv)); + ret = ARCHIVE_WARN; + sconv = NULL;/* The header charset switches to binary mode. */ + } + r = get_entry_uname(a, entry_main, &uname, &uname_length, sconv); + if (r == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + return (r); + } else if (r != ARCHIVE_OK) { + r = get_entry_uname(a, entry_main, &uname, &uname_length, NULL); + if (r == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + return (r); + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate uname '%s' to %s", uname, + archive_string_conversion_charset_name(sconv)); + ret = ARCHIVE_WARN; + sconv = NULL;/* The header charset switches to binary mode. */ + } + r = get_entry_gname(a, entry_main, &gname, &gname_length, sconv); + if (r == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + return (r); + } else if (r != ARCHIVE_OK) { + r = get_entry_gname(a, entry_main, &gname, &gname_length, NULL); + if (r == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + return (r); + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate gname '%s' to %s", gname, + archive_string_conversion_charset_name(sconv)); + ret = ARCHIVE_WARN; + sconv = NULL;/* The header charset switches to binary mode. */ + } + linkpath = hardlink; + linkpath_length = hardlink_length; + if (linkpath == NULL) { + r = get_entry_symlink(a, entry_main, &linkpath, + &linkpath_length, sconv); + if (r == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + return (r); + } else if (r != ARCHIVE_OK) { + r = get_entry_symlink(a, entry_main, &linkpath, + &linkpath_length, NULL); + if (r == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + return (r); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate linkname '%s' to %s", linkpath, + archive_string_conversion_charset_name(sconv)); + ret = ARCHIVE_WARN; + sconv = NULL; + } + } + + /* If any string conversions failed, get all attributes + * in binary-mode. */ + if (sconv == NULL && !pax->opt_binary) { + if (hardlink != NULL) { + r = get_entry_hardlink(a, entry_main, &hardlink, + &hardlink_length, NULL); + if (r == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + return (r); + } + linkpath = hardlink; + linkpath_length = hardlink_length; + } + r = get_entry_pathname(a, entry_main, &path, + &path_length, NULL); + if (r == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + return (r); + } + r = get_entry_uname(a, entry_main, &uname, &uname_length, NULL); + if (r == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + return (r); + } + r = get_entry_gname(a, entry_main, &gname, &gname_length, NULL); + if (r == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + return (r); + } + } + + /* Store the header encoding first, to be nice to readers. */ + if (sconv == NULL) + add_pax_attr(&(pax->pax_header), "hdrcharset", "BINARY"); + + + /* + * If name is too long, or has non-ASCII characters, add + * 'path' to pax extended attrs. (Note that an unconvertible + * name must have non-ASCII characters.) + */ + if (has_non_ASCII(path)) { + /* We have non-ASCII characters. */ + add_pax_attr(&(pax->pax_header), "path", path); + archive_entry_set_pathname(entry_main, + build_ustar_entry_name(ustar_entry_name, + path, path_length, NULL)); + need_extension = 1; + } else { + /* We have an all-ASCII path; we'd like to just store + * it in the ustar header if it will fit. Yes, this + * duplicates some of the logic in + * archive_write_set_format_ustar.c + */ + if (path_length <= 100) { + /* Fits in the old 100-char tar name field. */ + } else { + /* Find largest suffix that will fit. */ + /* Note: strlen() > 100, so strlen() - 100 - 1 >= 0 */ + suffix = strchr(path + path_length - 100 - 1, '/'); + /* Don't attempt an empty prefix. */ + if (suffix == path) + suffix = strchr(suffix + 1, '/'); + /* We can put it in the ustar header if it's + * all ASCII and it's either <= 100 characters + * or can be split at a '/' into a prefix <= + * 155 chars and a suffix <= 100 chars. (Note + * the strchr() above will return NULL exactly + * when the path can't be split.) + */ + if (suffix == NULL /* Suffix > 100 chars. */ + || suffix[1] == '\0' /* empty suffix */ + || suffix - path > 155) /* Prefix > 155 chars */ + { + add_pax_attr(&(pax->pax_header), "path", path); + archive_entry_set_pathname(entry_main, + build_ustar_entry_name(ustar_entry_name, + path, path_length, NULL)); + need_extension = 1; + } + } + } + + if (linkpath != NULL) { + /* If link name is too long or has non-ASCII characters, add + * 'linkpath' to pax extended attrs. */ + if (linkpath_length > 100 || has_non_ASCII(linkpath)) { + add_pax_attr(&(pax->pax_header), "linkpath", linkpath); + if (linkpath_length > 100) { + if (hardlink != NULL) + archive_entry_set_hardlink(entry_main, + "././@LongHardLink"); + else + archive_entry_set_symlink(entry_main, + "././@LongSymLink"); + } + need_extension = 1; + } + } + /* Save a pathname since it will be renamed if `entry_main` has + * sparse blocks. */ + archive_string_init(&entry_name); + archive_strcpy(&entry_name, archive_entry_pathname(entry_main)); + + /* If file size is too large, add 'size' to pax extended attrs. */ + if (archive_entry_size(entry_main) >= (((int64_t)1) << 33)) { + add_pax_attr_int(&(pax->pax_header), "size", + archive_entry_size(entry_main)); + need_extension = 1; + } + + /* If numeric GID is too large, add 'gid' to pax extended attrs. */ + if ((unsigned int)archive_entry_gid(entry_main) >= (1 << 18)) { + add_pax_attr_int(&(pax->pax_header), "gid", + archive_entry_gid(entry_main)); + need_extension = 1; + } + + /* If group name is too large or has non-ASCII characters, add + * 'gname' to pax extended attrs. */ + if (gname != NULL) { + if (gname_length > 31 || has_non_ASCII(gname)) { + add_pax_attr(&(pax->pax_header), "gname", gname); + need_extension = 1; + } + } + + /* If numeric UID is too large, add 'uid' to pax extended attrs. */ + if ((unsigned int)archive_entry_uid(entry_main) >= (1 << 18)) { + add_pax_attr_int(&(pax->pax_header), "uid", + archive_entry_uid(entry_main)); + need_extension = 1; + } + + /* Add 'uname' to pax extended attrs if necessary. */ + if (uname != NULL) { + if (uname_length > 31 || has_non_ASCII(uname)) { + add_pax_attr(&(pax->pax_header), "uname", uname); + need_extension = 1; + } + } + + /* + * POSIX/SUSv3 doesn't provide a standard key for large device + * numbers. I use the same keys here that Joerg Schilling + * used for 'star.' (Which, somewhat confusingly, are called + * "devXXX" even though they code "rdev" values.) No doubt, + * other implementations use other keys. Note that there's no + * reason we can't write the same information into a number of + * different keys. + * + * Of course, this is only needed for block or char device entries. + */ + if (archive_entry_filetype(entry_main) == AE_IFBLK + || archive_entry_filetype(entry_main) == AE_IFCHR) { + /* + * If rdevmajor is too large, add 'SCHILY.devmajor' to + * extended attributes. + */ + int rdevmajor, rdevminor; + rdevmajor = archive_entry_rdevmajor(entry_main); + rdevminor = archive_entry_rdevminor(entry_main); + if (rdevmajor >= (1 << 18)) { + add_pax_attr_int(&(pax->pax_header), "SCHILY.devmajor", + rdevmajor); + /* + * Non-strict formatting below means we don't + * have to truncate here. Not truncating improves + * the chance that some more modern tar archivers + * (such as GNU tar 1.13) can restore the full + * value even if they don't understand the pax + * extended attributes. See my rant below about + * file size fields for additional details. + */ + /* archive_entry_set_rdevmajor(entry_main, + rdevmajor & ((1 << 18) - 1)); */ + need_extension = 1; + } + + /* + * If devminor is too large, add 'SCHILY.devminor' to + * extended attributes. + */ + if (rdevminor >= (1 << 18)) { + add_pax_attr_int(&(pax->pax_header), "SCHILY.devminor", + rdevminor); + /* Truncation is not necessary here, either. */ + /* archive_entry_set_rdevminor(entry_main, + rdevminor & ((1 << 18) - 1)); */ + need_extension = 1; + } + } + + /* + * Technically, the mtime field in the ustar header can + * support 33 bits, but many platforms use signed 32-bit time + * values. The cutoff of 0x7fffffff here is a compromise. + * Yes, this check is duplicated just below; this helps to + * avoid writing an mtime attribute just to handle a + * high-resolution timestamp in "restricted pax" mode. + */ + if (!need_extension && + ((archive_entry_mtime(entry_main) < 0) + || (archive_entry_mtime(entry_main) >= 0x7fffffff))) + need_extension = 1; + + /* I use a star-compatible file flag attribute. */ + p = archive_entry_fflags_text(entry_main); + if (!need_extension && p != NULL && *p != '\0') + need_extension = 1; + + /* If there are extended attributes, we need an extension */ + if (!need_extension && archive_entry_xattr_count(entry_original) > 0) + need_extension = 1; + + /* If there are sparse info, we need an extension */ + if (!need_extension && sparse_count > 0) + need_extension = 1; + + acl_types = archive_entry_acl_types(entry_original); + + /* If there are any ACL entries, we need an extension */ + if (!need_extension && acl_types != 0) + need_extension = 1; + + /* If the symlink type is defined, we need an extension */ + if (!need_extension && archive_entry_symlink_type(entry_main) > 0) + need_extension = 1; + + /* + * Libarchive used to include these in extended headers for + * restricted pax format, but that confused people who + * expected ustar-like time semantics. So now we only include + * them in full pax format. + */ + if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_RESTRICTED) { + if (archive_entry_ctime(entry_main) != 0 || + archive_entry_ctime_nsec(entry_main) != 0) + add_pax_attr_time(&(pax->pax_header), "ctime", + archive_entry_ctime(entry_main), + archive_entry_ctime_nsec(entry_main)); + + if (archive_entry_atime(entry_main) != 0 || + archive_entry_atime_nsec(entry_main) != 0) + add_pax_attr_time(&(pax->pax_header), "atime", + archive_entry_atime(entry_main), + archive_entry_atime_nsec(entry_main)); + + /* Store birth/creationtime only if it's earlier than mtime */ + if (archive_entry_birthtime_is_set(entry_main) && + archive_entry_birthtime(entry_main) + < archive_entry_mtime(entry_main)) + add_pax_attr_time(&(pax->pax_header), + "LIBARCHIVE.creationtime", + archive_entry_birthtime(entry_main), + archive_entry_birthtime_nsec(entry_main)); + } + + /* + * The following items are handled differently in "pax + * restricted" format. In particular, in "pax restricted" + * format they won't be added unless need_extension is + * already set (we're already generating an extended header, so + * may as well include these). + */ + if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_RESTRICTED || + need_extension) { + if (archive_entry_mtime(entry_main) < 0 || + archive_entry_mtime(entry_main) >= 0x7fffffff || + archive_entry_mtime_nsec(entry_main) != 0) + add_pax_attr_time(&(pax->pax_header), "mtime", + archive_entry_mtime(entry_main), + archive_entry_mtime_nsec(entry_main)); + + /* I use a star-compatible file flag attribute. */ + p = archive_entry_fflags_text(entry_main); + if (p != NULL && *p != '\0') + add_pax_attr(&(pax->pax_header), "SCHILY.fflags", p); + + /* I use star-compatible ACL attributes. */ + if ((acl_types & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { + ret = add_pax_acl(a, entry_original, pax, + ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID | + ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA | + ARCHIVE_ENTRY_ACL_STYLE_COMPACT); + if (ret == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + archive_string_free(&entry_name); + return (ARCHIVE_FATAL); + } + } + if (acl_types & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) { + ret = add_pax_acl(a, entry_original, pax, + ARCHIVE_ENTRY_ACL_TYPE_ACCESS | + ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID | + ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA); + if (ret == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + archive_string_free(&entry_name); + return (ARCHIVE_FATAL); + } + } + if (acl_types & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) { + ret = add_pax_acl(a, entry_original, pax, + ARCHIVE_ENTRY_ACL_TYPE_DEFAULT | + ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID | + ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA); + if (ret == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + archive_string_free(&entry_name); + return (ARCHIVE_FATAL); + } + } + + /* We use GNU-tar-compatible sparse attributes. */ + if (sparse_count > 0) { + int64_t soffset, slength; + + add_pax_attr_int(&(pax->pax_header), + "GNU.sparse.major", 1); + add_pax_attr_int(&(pax->pax_header), + "GNU.sparse.minor", 0); + /* + * Make sure to store the original path, since + * truncation to ustar limit happened already. + */ + add_pax_attr(&(pax->pax_header), + "GNU.sparse.name", path); + add_pax_attr_int(&(pax->pax_header), + "GNU.sparse.realsize", + archive_entry_size(entry_main)); + + /* Rename the file name which will be used for + * ustar header to a special name, which GNU + * PAX Format 1.0 requires */ + archive_entry_set_pathname(entry_main, + build_gnu_sparse_name(gnu_sparse_name, + entry_name.s)); + + /* + * - Make a sparse map, which will precede a file data. + * - Get the total size of available data of sparse. + */ + archive_string_sprintf(&(pax->sparse_map), "%d\n", + sparse_count); + while (archive_entry_sparse_next(entry_main, + &soffset, &slength) == ARCHIVE_OK) { + archive_string_sprintf(&(pax->sparse_map), + "%jd\n%jd\n", + (intmax_t)soffset, + (intmax_t)slength); + sparse_total += slength; + if (sparse_list_add(pax, soffset, slength) + != ARCHIVE_OK) { + archive_set_error(&a->archive, + ENOMEM, + "Can't allocate memory"); + archive_entry_free(entry_main); + archive_string_free(&entry_name); + return (ARCHIVE_FATAL); + } + } + } + + /* Store extended attributes */ + if (archive_write_pax_header_xattrs(a, pax, entry_original) + == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + archive_string_free(&entry_name); + return (ARCHIVE_FATAL); + } + + /* Store extended symlink information */ + if (archive_entry_symlink_type(entry_main) == + AE_SYMLINK_TYPE_FILE) { + add_pax_attr(&(pax->pax_header), + "LIBARCHIVE.symlinktype", "file"); + } else if (archive_entry_symlink_type(entry_main) == + AE_SYMLINK_TYPE_DIRECTORY) { + add_pax_attr(&(pax->pax_header), + "LIBARCHIVE.symlinktype", "dir"); + } + } + + /* Only regular files have data. */ + if (archive_entry_filetype(entry_main) != AE_IFREG) + archive_entry_set_size(entry_main, 0); + + /* + * Pax-restricted does not store data for hardlinks, in order + * to improve compatibility with ustar. + */ + if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE && + hardlink != NULL) + archive_entry_set_size(entry_main, 0); + + /* + * XXX Full pax interchange format does permit a hardlink + * entry to have data associated with it. I'm not supporting + * that here because the client expects me to tell them whether + * or not this format expects data for hardlinks. If I + * don't check here, then every pax archive will end up with + * duplicated data for hardlinks. Someday, there may be + * need to select this behavior, in which case the following + * will need to be revisited. XXX + */ + if (hardlink != NULL) + archive_entry_set_size(entry_main, 0); + + /* Save a real file size. */ + real_size = archive_entry_size(entry_main); + /* + * Overwrite a file size by the total size of sparse blocks and + * the size of sparse map info. That file size is the length of + * the data, which we will exactly store into an archive file. + */ + if (archive_strlen(&(pax->sparse_map))) { + size_t mapsize = archive_strlen(&(pax->sparse_map)); + pax->sparse_map_padding = 0x1ff & (-(ssize_t)mapsize); + archive_entry_set_size(entry_main, + mapsize + pax->sparse_map_padding + sparse_total); + } + + /* Format 'ustar' header for main entry. + * + * The trouble with file size: If the reader can't understand + * the file size, they may not be able to locate the next + * entry and the rest of the archive is toast. Pax-compliant + * readers are supposed to ignore the file size in the main + * header, so the question becomes how to maximize portability + * for readers that don't support pax attribute extensions. + * For maximum compatibility, I permit numeric extensions in + * the main header so that the file size stored will always be + * correct, even if it's in a format that only some + * implementations understand. The technique used here is: + * + * a) If possible, follow the standard exactly. This handles + * files up to 8 gigabytes minus 1. + * + * b) If that fails, try octal but omit the field terminator. + * That handles files up to 64 gigabytes minus 1. + * + * c) Otherwise, use base-256 extensions. That handles files + * up to 2^63 in this implementation, with the potential to + * go up to 2^94. That should hold us for a while. ;-) + * + * The non-strict formatter uses similar logic for other + * numeric fields, though they're less critical. + */ + if (__archive_write_format_header_ustar(a, ustarbuff, entry_main, -1, 0, + NULL) == ARCHIVE_FATAL) { + archive_entry_free(entry_main); + archive_string_free(&entry_name); + return (ARCHIVE_FATAL); + } + + /* If we built any extended attributes, write that entry first. */ + if (archive_strlen(&(pax->pax_header)) > 0) { + struct archive_entry *pax_attr_entry; + time_t s; + int64_t uid, gid; + int mode; + + pax_attr_entry = archive_entry_new2(&a->archive); + p = entry_name.s; + archive_entry_set_pathname(pax_attr_entry, + build_pax_attribute_name(pax_entry_name, p)); + archive_entry_set_size(pax_attr_entry, + archive_strlen(&(pax->pax_header))); + /* Copy uid/gid (but clip to ustar limits). */ + uid = archive_entry_uid(entry_main); + if (uid >= 1 << 18) + uid = (1 << 18) - 1; + archive_entry_set_uid(pax_attr_entry, uid); + gid = archive_entry_gid(entry_main); + if (gid >= 1 << 18) + gid = (1 << 18) - 1; + archive_entry_set_gid(pax_attr_entry, gid); + /* Copy mode over (but not setuid/setgid bits) */ + mode = archive_entry_mode(entry_main); +#ifdef S_ISUID + mode &= ~S_ISUID; +#endif +#ifdef S_ISGID + mode &= ~S_ISGID; +#endif +#ifdef S_ISVTX + mode &= ~S_ISVTX; +#endif + archive_entry_set_mode(pax_attr_entry, mode); + + /* Copy uname/gname. */ + archive_entry_set_uname(pax_attr_entry, + archive_entry_uname(entry_main)); + archive_entry_set_gname(pax_attr_entry, + archive_entry_gname(entry_main)); + + /* Copy mtime, but clip to ustar limits. */ + s = archive_entry_mtime(entry_main); + if (s < 0) { s = 0; } + if (s >= 0x7fffffff) { s = 0x7fffffff; } + archive_entry_set_mtime(pax_attr_entry, s, 0); + + /* Standard ustar doesn't support atime. */ + archive_entry_set_atime(pax_attr_entry, 0, 0); + + /* Standard ustar doesn't support ctime. */ + archive_entry_set_ctime(pax_attr_entry, 0, 0); + + r = __archive_write_format_header_ustar(a, paxbuff, + pax_attr_entry, 'x', 1, NULL); + + archive_entry_free(pax_attr_entry); + + /* Note that the 'x' header shouldn't ever fail to format */ + if (r < ARCHIVE_WARN) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "archive_write_pax_header: " + "'x' header failed?! This can't happen.\n"); + archive_entry_free(entry_main); + archive_string_free(&entry_name); + return (ARCHIVE_FATAL); + } else if (r < ret) + ret = r; + r = __archive_write_output(a, paxbuff, 512); + if (r != ARCHIVE_OK) { + sparse_list_clear(pax); + pax->entry_bytes_remaining = 0; + pax->entry_padding = 0; + archive_entry_free(entry_main); + archive_string_free(&entry_name); + return (ARCHIVE_FATAL); + } + + pax->entry_bytes_remaining = archive_strlen(&(pax->pax_header)); + pax->entry_padding = + 0x1ff & (-(int64_t)pax->entry_bytes_remaining); + + r = __archive_write_output(a, pax->pax_header.s, + archive_strlen(&(pax->pax_header))); + if (r != ARCHIVE_OK) { + /* If a write fails, we're pretty much toast. */ + archive_entry_free(entry_main); + archive_string_free(&entry_name); + return (ARCHIVE_FATAL); + } + /* Pad out the end of the entry. */ + r = __archive_write_nulls(a, (size_t)pax->entry_padding); + if (r != ARCHIVE_OK) { + /* If a write fails, we're pretty much toast. */ + archive_entry_free(entry_main); + archive_string_free(&entry_name); + return (ARCHIVE_FATAL); + } + pax->entry_bytes_remaining = pax->entry_padding = 0; + } + + /* Write the header for main entry. */ + r = __archive_write_output(a, ustarbuff, 512); + if (r != ARCHIVE_OK) { + archive_entry_free(entry_main); + archive_string_free(&entry_name); + return (r); + } + + /* + * Inform the client of the on-disk size we're using, so + * they can avoid unnecessarily writing a body for something + * that we're just going to ignore. + */ + archive_entry_set_size(entry_original, real_size); + if (pax->sparse_list == NULL && real_size > 0) { + /* This is not a sparse file but we handle its data as + * a sparse block. */ + sparse_list_add(pax, 0, real_size); + sparse_total = real_size; + } + pax->entry_padding = 0x1ff & (-(int64_t)sparse_total); + archive_entry_free(entry_main); + archive_string_free(&entry_name); + + return (ret); +} + +/* + * We need a valid name for the regular 'ustar' entry. This routine + * tries to hack something more-or-less reasonable. + * + * The approach here tries to preserve leading dir names. We do so by + * working with four sections: + * 1) "prefix" directory names, + * 2) "suffix" directory names, + * 3) inserted dir name (optional), + * 4) filename. + * + * These sections must satisfy the following requirements: + * * Parts 1 & 2 together form an initial portion of the dir name. + * * Part 3 is specified by the caller. (It should not contain a leading + * or trailing '/'.) + * * Part 4 forms an initial portion of the base filename. + * * The filename must be <= 99 chars to fit the ustar 'name' field. + * * Parts 2, 3, 4 together must be <= 99 chars to fit the ustar 'name' fld. + * * Part 1 must be <= 155 chars to fit the ustar 'prefix' field. + * * If the original name ends in a '/', the new name must also end in a '/' + * * Trailing '/.' sequences may be stripped. + * + * Note: Recall that the ustar format does not store the '/' separating + * parts 1 & 2, but does store the '/' separating parts 2 & 3. + */ +static char * +build_ustar_entry_name(char *dest, const char *src, size_t src_length, + const char *insert) +{ + const char *prefix, *prefix_end; + const char *suffix, *suffix_end; + const char *filename, *filename_end; + char *p; + int need_slash = 0; /* Was there a trailing slash? */ + size_t suffix_length = 99; + size_t insert_length; + + /* Length of additional dir element to be added. */ + if (insert == NULL) + insert_length = 0; + else + /* +2 here allows for '/' before and after the insert. */ + insert_length = strlen(insert) + 2; + + /* Step 0: Quick bailout in a common case. */ + if (src_length < 100 && insert == NULL) { + strncpy(dest, src, src_length); + dest[src_length] = '\0'; + return (dest); + } + + /* Step 1: Locate filename and enforce the length restriction. */ + filename_end = src + src_length; + /* Remove trailing '/' chars and '/.' pairs. */ + for (;;) { + if (filename_end > src && filename_end[-1] == '/') { + filename_end --; + need_slash = 1; /* Remember to restore trailing '/'. */ + continue; + } + if (filename_end > src + 1 && filename_end[-1] == '.' + && filename_end[-2] == '/') { + filename_end -= 2; + need_slash = 1; /* "foo/." will become "foo/" */ + continue; + } + break; + } + if (need_slash) + suffix_length--; + /* Find start of filename. */ + filename = filename_end - 1; + while ((filename > src) && (*filename != '/')) + filename --; + if ((*filename == '/') && (filename < filename_end - 1)) + filename ++; + /* Adjust filename_end so that filename + insert fits in 99 chars. */ + suffix_length -= insert_length; + if (filename_end > filename + suffix_length) + filename_end = filename + suffix_length; + /* Calculate max size for "suffix" section (#3 above). */ + suffix_length -= filename_end - filename; + + /* Step 2: Locate the "prefix" section of the dirname, including + * trailing '/'. */ + prefix = src; + prefix_end = prefix + 155; + if (prefix_end > filename) + prefix_end = filename; + while (prefix_end > prefix && *prefix_end != '/') + prefix_end--; + if ((prefix_end < filename) && (*prefix_end == '/')) + prefix_end++; + + /* Step 3: Locate the "suffix" section of the dirname, + * including trailing '/'. */ + suffix = prefix_end; + suffix_end = suffix + suffix_length; /* Enforce limit. */ + if (suffix_end > filename) + suffix_end = filename; + if (suffix_end < suffix) + suffix_end = suffix; + while (suffix_end > suffix && *suffix_end != '/') + suffix_end--; + if ((suffix_end < filename) && (*suffix_end == '/')) + suffix_end++; + + /* Step 4: Build the new name. */ + /* The OpenBSD strlcpy function is safer, but less portable. */ + /* Rather than maintain two versions, just use the strncpy version. */ + p = dest; + if (prefix_end > prefix) { + strncpy(p, prefix, prefix_end - prefix); + p += prefix_end - prefix; + } + if (suffix_end > suffix) { + strncpy(p, suffix, suffix_end - suffix); + p += suffix_end - suffix; + } + if (insert != NULL) { + /* Note: assume insert does not have leading or trailing '/' */ + strcpy(p, insert); + p += strlen(insert); + *p++ = '/'; + } + strncpy(p, filename, filename_end - filename); + p += filename_end - filename; + if (need_slash) + *p++ = '/'; + *p = '\0'; + + return (dest); +} + +/* + * The ustar header for the pax extended attributes must have a + * reasonable name: SUSv3 requires 'dirname'/PaxHeader.'pid'/'filename' + * where 'pid' is the PID of the archiving process. Unfortunately, + * that makes testing a pain since the output varies for each run, + * so I'm sticking with the simpler 'dirname'/PaxHeader/'filename' + * for now. (Someday, I'll make this settable. Then I can use the + * SUS recommendation as default and test harnesses can override it + * to get predictable results.) + * + * Joerg Schilling has argued that this is unnecessary because, in + * practice, if the pax extended attributes get extracted as regular + * files, no one is going to bother reading those attributes to + * manually restore them. Based on this, 'star' uses + * /tmp/PaxHeader/'basename' as the ustar header name. This is a + * tempting argument, in part because it's simpler than the SUSv3 + * recommendation, but I'm not entirely convinced. I'm also + * uncomfortable with the fact that "/tmp" is a Unix-ism. + * + * The following routine leverages build_ustar_entry_name() above and + * so is simpler than you might think. It just needs to provide the + * additional path element and handle a few pathological cases). + */ +static char * +build_pax_attribute_name(char *dest, const char *src) +{ + char buff[64]; + const char *p; + + /* Handle the null filename case. */ + if (src == NULL || *src == '\0') { + strcpy(dest, "PaxHeader/blank"); + return (dest); + } + + /* Prune final '/' and other unwanted final elements. */ + p = src + strlen(src); + for (;;) { + /* Ends in "/", remove the '/' */ + if (p > src && p[-1] == '/') { + --p; + continue; + } + /* Ends in "/.", remove the '.' */ + if (p > src + 1 && p[-1] == '.' + && p[-2] == '/') { + --p; + continue; + } + break; + } + + /* Pathological case: After above, there was nothing left. + * This includes "/." "/./." "/.//./." etc. */ + if (p == src) { + strcpy(dest, "/PaxHeader/rootdir"); + return (dest); + } + + /* Convert unadorned "." into a suitable filename. */ + if (*src == '.' && p == src + 1) { + strcpy(dest, "PaxHeader/currentdir"); + return (dest); + } + + /* + * TODO: Push this string into the 'pax' structure to avoid + * recomputing it every time. That will also open the door + * to having clients override it. + */ +#if HAVE_GETPID && 0 /* Disable this for now; see above comment. */ + sprintf(buff, "PaxHeader.%d", getpid()); +#else + /* If the platform can't fetch the pid, don't include it. */ + strcpy(buff, "PaxHeader"); +#endif + /* General case: build a ustar-compatible name adding + * "/PaxHeader/". */ + build_ustar_entry_name(dest, src, p - src, buff); + + return (dest); +} + +/* + * GNU PAX Format 1.0 requires the special name, which pattern is: + * <dir>/GNUSparseFile.<pid>/<original file name> + * + * Since reproducible archives are more important, use 0 as pid. + * + * This function is used for only Sparse file, a file type of which + * is regular file. + */ +static char * +build_gnu_sparse_name(char *dest, const char *src) +{ + const char *p; + + /* Handle the null filename case. */ + if (src == NULL || *src == '\0') { + strcpy(dest, "GNUSparseFile/blank"); + return (dest); + } + + /* Prune final '/' and other unwanted final elements. */ + p = src + strlen(src); + for (;;) { + /* Ends in "/", remove the '/' */ + if (p > src && p[-1] == '/') { + --p; + continue; + } + /* Ends in "/.", remove the '.' */ + if (p > src + 1 && p[-1] == '.' + && p[-2] == '/') { + --p; + continue; + } + break; + } + + /* General case: build a ustar-compatible name adding + * "/GNUSparseFile/". */ + build_ustar_entry_name(dest, src, p - src, "GNUSparseFile.0"); + + return (dest); +} + +/* Write two null blocks for the end of archive */ +static int +archive_write_pax_close(struct archive_write *a) +{ + return (__archive_write_nulls(a, 512 * 2)); +} + +static int +archive_write_pax_free(struct archive_write *a) +{ + struct pax *pax; + + pax = (struct pax *)a->format_data; + if (pax == NULL) + return (ARCHIVE_OK); + + archive_string_free(&pax->pax_header); + archive_string_free(&pax->sparse_map); + archive_string_free(&pax->l_url_encoded_name); + sparse_list_clear(pax); + free(pax); + a->format_data = NULL; + return (ARCHIVE_OK); +} + +static int +archive_write_pax_finish_entry(struct archive_write *a) +{ + struct pax *pax; + uint64_t remaining; + int ret; + + pax = (struct pax *)a->format_data; + remaining = pax->entry_bytes_remaining; + if (remaining == 0) { + while (pax->sparse_list) { + struct sparse_block *sb; + if (!pax->sparse_list->is_hole) + remaining += pax->sparse_list->remaining; + sb = pax->sparse_list->next; + free(pax->sparse_list); + pax->sparse_list = sb; + } + } + ret = __archive_write_nulls(a, (size_t)(remaining + pax->entry_padding)); + pax->entry_bytes_remaining = pax->entry_padding = 0; + return (ret); +} + +static ssize_t +archive_write_pax_data(struct archive_write *a, const void *buff, size_t s) +{ + struct pax *pax; + size_t ws; + size_t total; + int ret; + + pax = (struct pax *)a->format_data; + + /* + * According to GNU PAX format 1.0, write a sparse map + * before the body. + */ + if (archive_strlen(&(pax->sparse_map))) { + ret = __archive_write_output(a, pax->sparse_map.s, + archive_strlen(&(pax->sparse_map))); + if (ret != ARCHIVE_OK) + return (ret); + ret = __archive_write_nulls(a, pax->sparse_map_padding); + if (ret != ARCHIVE_OK) + return (ret); + archive_string_empty(&(pax->sparse_map)); + } + + total = 0; + while (total < s) { + const unsigned char *p; + + while (pax->sparse_list != NULL && + pax->sparse_list->remaining == 0) { + struct sparse_block *sb = pax->sparse_list->next; + free(pax->sparse_list); + pax->sparse_list = sb; + } + + if (pax->sparse_list == NULL) + return (total); + + p = ((const unsigned char *)buff) + total; + ws = s - total; + if (ws > pax->sparse_list->remaining) + ws = (size_t)pax->sparse_list->remaining; + + if (pax->sparse_list->is_hole) { + /* Current block is hole thus we do not write + * the body. */ + pax->sparse_list->remaining -= ws; + total += ws; + continue; + } + + ret = __archive_write_output(a, p, ws); + pax->sparse_list->remaining -= ws; + total += ws; + if (ret != ARCHIVE_OK) + return (ret); + } + return (total); +} + +static int +has_non_ASCII(const char *_p) +{ + const unsigned char *p = (const unsigned char *)_p; + + if (p == NULL) + return (1); + while (*p != '\0' && *p < 128) + p++; + return (*p != '\0'); +} + +/* + * Used by extended attribute support; encodes the name + * so that there will be no '=' characters in the result. + */ +static char * +url_encode(const char *in) +{ + const char *s; + char *d; + int out_len = 0; + char *out; + + for (s = in; *s != '\0'; s++) { + if (*s < 33 || *s > 126 || *s == '%' || *s == '=') + out_len += 3; + else + out_len++; + } + + out = (char *)malloc(out_len + 1); + if (out == NULL) + return (NULL); + + for (s = in, d = out; *s != '\0'; s++) { + /* encode any non-printable ASCII character or '%' or '=' */ + if (*s < 33 || *s > 126 || *s == '%' || *s == '=') { + /* URL encoding is '%' followed by two hex digits */ + *d++ = '%'; + *d++ = "0123456789ABCDEF"[0x0f & (*s >> 4)]; + *d++ = "0123456789ABCDEF"[0x0f & *s]; + } else { + *d++ = *s; + } + } + *d = '\0'; + return (out); +} + +/* + * Encode a sequence of bytes into a C string using base-64 encoding. + * + * Returns a null-terminated C string allocated with malloc(); caller + * is responsible for freeing the result. + */ +static char * +base64_encode(const char *s, size_t len) +{ + static const char digits[64] = + { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', + 'P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d', + 'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s', + 't','u','v','w','x','y','z','0','1','2','3','4','5','6','7', + '8','9','+','/' }; + int v; + char *d, *out; + + /* 3 bytes becomes 4 chars, but round up and allow for trailing NUL */ + out = (char *)malloc((len * 4 + 2) / 3 + 1); + if (out == NULL) + return (NULL); + d = out; + + /* Convert each group of 3 bytes into 4 characters. */ + while (len >= 3) { + v = (((int)s[0] << 16) & 0xff0000) + | (((int)s[1] << 8) & 0xff00) + | (((int)s[2]) & 0x00ff); + s += 3; + len -= 3; + *d++ = digits[(v >> 18) & 0x3f]; + *d++ = digits[(v >> 12) & 0x3f]; + *d++ = digits[(v >> 6) & 0x3f]; + *d++ = digits[(v) & 0x3f]; + } + /* Handle final group of 1 byte (2 chars) or 2 bytes (3 chars). */ + switch (len) { + case 0: break; + case 1: + v = (((int)s[0] << 16) & 0xff0000); + *d++ = digits[(v >> 18) & 0x3f]; + *d++ = digits[(v >> 12) & 0x3f]; + break; + case 2: + v = (((int)s[0] << 16) & 0xff0000) + | (((int)s[1] << 8) & 0xff00); + *d++ = digits[(v >> 18) & 0x3f]; + *d++ = digits[(v >> 12) & 0x3f]; + *d++ = digits[(v >> 6) & 0x3f]; + break; + } + /* Add trailing NUL character so output is a valid C string. */ + *d = '\0'; + return (out); +} + +static void +sparse_list_clear(struct pax *pax) +{ + while (pax->sparse_list != NULL) { + struct sparse_block *sb = pax->sparse_list; + pax->sparse_list = sb->next; + free(sb); + } + pax->sparse_tail = NULL; +} + +static int +_sparse_list_add_block(struct pax *pax, int64_t offset, int64_t length, + int is_hole) +{ + struct sparse_block *sb; + + sb = (struct sparse_block *)malloc(sizeof(*sb)); + if (sb == NULL) + return (ARCHIVE_FATAL); + sb->next = NULL; + sb->is_hole = is_hole; + sb->offset = offset; + sb->remaining = length; + if (pax->sparse_list == NULL || pax->sparse_tail == NULL) + pax->sparse_list = pax->sparse_tail = sb; + else { + pax->sparse_tail->next = sb; + pax->sparse_tail = sb; + } + return (ARCHIVE_OK); +} + +static int +sparse_list_add(struct pax *pax, int64_t offset, int64_t length) +{ + int64_t last_offset; + int r; + + if (pax->sparse_tail == NULL) + last_offset = 0; + else { + last_offset = pax->sparse_tail->offset + + pax->sparse_tail->remaining; + } + if (last_offset < offset) { + /* Add a hole block. */ + r = _sparse_list_add_block(pax, last_offset, + offset - last_offset, 1); + if (r != ARCHIVE_OK) + return (r); + } + /* Add data block. */ + return (_sparse_list_add_block(pax, offset, length, 0)); +} + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_private.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_private.h new file mode 100644 index 0000000000..e20022755f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_private.h @@ -0,0 +1,42 @@ +/*- + * Copyright (c) 2020 Martin Matuska + * 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(S) ``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(S) 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. + * + * $FreeBSD$ + */ + +#ifndef ARCHIVE_WRITE_SET_FORMAT_PRIVATE_H_INCLUDED +#define ARCHIVE_WRITE_SET_FORMAT_PRIVATE_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#ifndef __LIBARCHIVE_TEST +#error This header is only to be used internally to libarchive. +#endif +#endif + +#include "archive.h" +#include "archive_entry.h" + +void __archive_write_entry_filetype_unsupported(struct archive *a, + struct archive_entry *entry, const char *format); +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_raw.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_raw.c new file mode 100644 index 0000000000..feff936977 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_raw.c @@ -0,0 +1,125 @@ +/*- + * Copyright (c) 2013 Marek Kubica + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif + +#include "archive_entry.h" +#include "archive_write_private.h" + +static ssize_t archive_write_raw_data(struct archive_write *, + const void *buff, size_t s); +static int archive_write_raw_free(struct archive_write *); +static int archive_write_raw_header(struct archive_write *, + struct archive_entry *); + +struct raw { + int entries_written; +}; + +/* + * Set output format to 'raw' format. + */ +int +archive_write_set_format_raw(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct raw *raw; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_raw"); + + /* If someone else was already registered, unregister them. */ + if (a->format_free != NULL) + (a->format_free)(a); + + raw = (struct raw *)calloc(1, sizeof(*raw)); + if (raw == NULL) { + archive_set_error(&a->archive, ENOMEM, "Can't allocate raw data"); + return (ARCHIVE_FATAL); + } + raw->entries_written = 0; + a->format_data = raw; + a->format_name = "raw"; + /* no options exist for this format */ + a->format_options = NULL; + a->format_write_header = archive_write_raw_header; + a->format_write_data = archive_write_raw_data; + a->format_finish_entry = NULL; + /* nothing needs to be done on closing */ + a->format_close = NULL; + a->format_free = archive_write_raw_free; + a->archive.archive_format = ARCHIVE_FORMAT_RAW; + a->archive.archive_format_name = "RAW"; + return (ARCHIVE_OK); +} + +static int +archive_write_raw_header(struct archive_write *a, struct archive_entry *entry) +{ + struct raw *raw = (struct raw *)a->format_data; + + if (archive_entry_filetype(entry) != AE_IFREG) { + archive_set_error(&a->archive, ERANGE, + "Raw format only supports filetype AE_IFREG"); + return (ARCHIVE_FATAL); + } + + + if (raw->entries_written > 0) { + archive_set_error(&a->archive, ERANGE, + "Raw format only supports one entry per archive"); + return (ARCHIVE_FATAL); + } + raw->entries_written++; + + return (ARCHIVE_OK); +} + +static ssize_t +archive_write_raw_data(struct archive_write *a, const void *buff, size_t s) +{ + int ret; + + ret = __archive_write_output(a, buff, s); + if (ret >= 0) + return (s); + else + return (ret); +} + +static int +archive_write_raw_free(struct archive_write *a) +{ + struct raw *raw; + + raw = (struct raw *)a->format_data; + free(raw); + a->format_data = NULL; + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_shar.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_shar.c new file mode 100644 index 0000000000..9e4931c95c --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_shar.c @@ -0,0 +1,641 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2008 Joerg Sonnenberger + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_shar.c 189438 2009-03-06 05:58:56Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_private.h" +#include "archive_write_private.h" +#include "archive_write_set_format_private.h" + +struct shar { + int dump; + int end_of_line; + struct archive_entry *entry; + int has_data; + char *last_dir; + + /* Line buffer for uuencoded dump format */ + char outbuff[45]; + size_t outpos; + + int wrote_header; + struct archive_string work; + struct archive_string quoted_name; +}; + +static int archive_write_shar_close(struct archive_write *); +static int archive_write_shar_free(struct archive_write *); +static int archive_write_shar_header(struct archive_write *, + struct archive_entry *); +static ssize_t archive_write_shar_data_sed(struct archive_write *, + const void * buff, size_t); +static ssize_t archive_write_shar_data_uuencode(struct archive_write *, + const void * buff, size_t); +static int archive_write_shar_finish_entry(struct archive_write *); + +/* + * Copy the given string to the buffer, quoting all shell meta characters + * found. + */ +static void +shar_quote(struct archive_string *buf, const char *str, int in_shell) +{ + static const char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~"; + size_t len; + + while (*str != '\0') { + if ((len = strcspn(str, meta)) != 0) { + archive_strncat(buf, str, len); + str += len; + } else if (*str == '\n') { + if (in_shell) + archive_strcat(buf, "\"\n\""); + else + archive_strcat(buf, "\\n"); + ++str; + } else { + archive_strappend_char(buf, '\\'); + archive_strappend_char(buf, *str); + ++str; + } + } +} + +/* + * Set output format to 'shar' format. + */ +int +archive_write_set_format_shar(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct shar *shar; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_shar"); + + /* If someone else was already registered, unregister them. */ + if (a->format_free != NULL) + (a->format_free)(a); + + shar = (struct shar *)calloc(1, sizeof(*shar)); + if (shar == NULL) { + archive_set_error(&a->archive, ENOMEM, "Can't allocate shar data"); + return (ARCHIVE_FATAL); + } + archive_string_init(&shar->work); + archive_string_init(&shar->quoted_name); + a->format_data = shar; + a->format_name = "shar"; + a->format_write_header = archive_write_shar_header; + a->format_close = archive_write_shar_close; + a->format_free = archive_write_shar_free; + a->format_write_data = archive_write_shar_data_sed; + a->format_finish_entry = archive_write_shar_finish_entry; + a->archive.archive_format = ARCHIVE_FORMAT_SHAR_BASE; + a->archive.archive_format_name = "shar"; + return (ARCHIVE_OK); +} + +/* + * An alternate 'shar' that uses uudecode instead of 'sed' to encode + * file contents and can therefore be used to archive binary files. + * In addition, this variant also attempts to restore ownership, file modes, + * and other extended file information. + */ +int +archive_write_set_format_shar_dump(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct shar *shar; + + archive_write_set_format_shar(&a->archive); + shar = (struct shar *)a->format_data; + shar->dump = 1; + a->format_write_data = archive_write_shar_data_uuencode; + a->archive.archive_format = ARCHIVE_FORMAT_SHAR_DUMP; + a->archive.archive_format_name = "shar dump"; + return (ARCHIVE_OK); +} + +static int +archive_write_shar_header(struct archive_write *a, struct archive_entry *entry) +{ + const char *linkname; + const char *name; + char *p, *pp; + struct shar *shar; + + shar = (struct shar *)a->format_data; + if (!shar->wrote_header) { + archive_strcat(&shar->work, "#!/bin/sh\n"); + archive_strcat(&shar->work, "# This is a shell archive\n"); + shar->wrote_header = 1; + } + + /* Save the entry for the closing. */ + archive_entry_free(shar->entry); + shar->entry = archive_entry_clone(entry); + name = archive_entry_pathname(entry); + + /* Handle some preparatory issues. */ + switch(archive_entry_filetype(entry)) { + case AE_IFREG: + /* Only regular files have non-zero size. */ + break; + case AE_IFDIR: + archive_entry_set_size(entry, 0); + /* Don't bother trying to recreate '.' */ + if (strcmp(name, ".") == 0 || strcmp(name, "./") == 0) + return (ARCHIVE_OK); + break; + case AE_IFIFO: + case AE_IFCHR: + case AE_IFBLK: + /* All other file types have zero size in the archive. */ + archive_entry_set_size(entry, 0); + break; + default: + archive_entry_set_size(entry, 0); + if (archive_entry_hardlink(entry) == NULL && + archive_entry_symlink(entry) == NULL) { + __archive_write_entry_filetype_unsupported( + &a->archive, entry, "shar"); + return (ARCHIVE_WARN); + } + } + + archive_string_empty(&shar->quoted_name); + shar_quote(&shar->quoted_name, name, 1); + + /* Stock preparation for all file types. */ + archive_string_sprintf(&shar->work, "echo x %s\n", shar->quoted_name.s); + + if (archive_entry_filetype(entry) != AE_IFDIR) { + /* Try to create the dir. */ + p = strdup(name); + pp = strrchr(p, '/'); + /* If there is a / character, try to create the dir. */ + if (pp != NULL) { + *pp = '\0'; + + /* Try to avoid a lot of redundant mkdir commands. */ + if (strcmp(p, ".") == 0) { + /* Don't try to "mkdir ." */ + free(p); + } else if (shar->last_dir == NULL) { + archive_strcat(&shar->work, "mkdir -p "); + shar_quote(&shar->work, p, 1); + archive_strcat(&shar->work, + " > /dev/null 2>&1\n"); + shar->last_dir = p; + } else if (strcmp(p, shar->last_dir) == 0) { + /* We've already created this exact dir. */ + free(p); + } else if (strlen(p) < strlen(shar->last_dir) && + strncmp(p, shar->last_dir, strlen(p)) == 0) { + /* We've already created a subdir. */ + free(p); + } else { + archive_strcat(&shar->work, "mkdir -p "); + shar_quote(&shar->work, p, 1); + archive_strcat(&shar->work, + " > /dev/null 2>&1\n"); + shar->last_dir = p; + } + } else { + free(p); + } + } + + /* Handle file-type specific issues. */ + shar->has_data = 0; + if ((linkname = archive_entry_hardlink(entry)) != NULL) { + archive_strcat(&shar->work, "ln -f "); + shar_quote(&shar->work, linkname, 1); + archive_string_sprintf(&shar->work, " %s\n", + shar->quoted_name.s); + } else if ((linkname = archive_entry_symlink(entry)) != NULL) { + archive_strcat(&shar->work, "ln -fs "); + shar_quote(&shar->work, linkname, 1); + archive_string_sprintf(&shar->work, " %s\n", + shar->quoted_name.s); + } else { + switch(archive_entry_filetype(entry)) { + case AE_IFREG: + if (archive_entry_size(entry) == 0) { + /* More portable than "touch." */ + archive_string_sprintf(&shar->work, + "test -e \"%s\" || :> \"%s\"\n", + shar->quoted_name.s, shar->quoted_name.s); + } else { + if (shar->dump) { + unsigned int mode = archive_entry_mode(entry) & 0777; + archive_string_sprintf(&shar->work, + "uudecode -p > %s << 'SHAR_END'\n", + shar->quoted_name.s); + archive_string_sprintf(&shar->work, + "begin %o ", mode); + shar_quote(&shar->work, name, 0); + archive_strcat(&shar->work, "\n"); + } else { + archive_string_sprintf(&shar->work, + "sed 's/^X//' > %s << 'SHAR_END'\n", + shar->quoted_name.s); + } + shar->has_data = 1; + shar->end_of_line = 1; + shar->outpos = 0; + } + break; + case AE_IFDIR: + archive_string_sprintf(&shar->work, + "mkdir -p %s > /dev/null 2>&1\n", + shar->quoted_name.s); + /* Record that we just created this directory. */ + free(shar->last_dir); + + shar->last_dir = strdup(name); + /* Trim a trailing '/'. */ + pp = strrchr(shar->last_dir, '/'); + if (pp != NULL && pp[1] == '\0') + *pp = '\0'; + /* + * TODO: Put dir name/mode on a list to be fixed + * up at end of archive. + */ + break; + case AE_IFIFO: + archive_string_sprintf(&shar->work, + "mkfifo %s\n", shar->quoted_name.s); + break; + case AE_IFCHR: + archive_string_sprintf(&shar->work, + "mknod %s c %ju %ju\n", shar->quoted_name.s, + (uintmax_t)archive_entry_rdevmajor(entry), + (uintmax_t)archive_entry_rdevminor(entry)); + break; + case AE_IFBLK: + archive_string_sprintf(&shar->work, + "mknod %s b %ju %ju\n", shar->quoted_name.s, + (uintmax_t)archive_entry_rdevmajor(entry), + (uintmax_t)archive_entry_rdevminor(entry)); + break; + default: + return (ARCHIVE_WARN); + } + } + + return (ARCHIVE_OK); +} + +static ssize_t +archive_write_shar_data_sed(struct archive_write *a, const void *buff, size_t n) +{ + static const size_t ensured = 65533; + struct shar *shar; + const char *src; + char *buf, *buf_end; + int ret; + size_t written = n; + + shar = (struct shar *)a->format_data; + if (!shar->has_data || n == 0) + return (0); + + src = (const char *)buff; + + /* + * ensure is the number of bytes in buffer before expanding the + * current character. Each operation writes the current character + * and optionally the start-of-new-line marker. This can happen + * twice before entering the loop, so make sure three additional + * bytes can be written. + */ + if (archive_string_ensure(&shar->work, ensured + 3) == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + + if (shar->work.length > ensured) { + ret = __archive_write_output(a, shar->work.s, + shar->work.length); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + archive_string_empty(&shar->work); + } + buf = shar->work.s + shar->work.length; + buf_end = shar->work.s + ensured; + + if (shar->end_of_line) { + *buf++ = 'X'; + shar->end_of_line = 0; + } + + while (n-- != 0) { + if ((*buf++ = *src++) == '\n') { + if (n == 0) + shar->end_of_line = 1; + else + *buf++ = 'X'; + } + + if (buf >= buf_end) { + shar->work.length = buf - shar->work.s; + ret = __archive_write_output(a, shar->work.s, + shar->work.length); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + archive_string_empty(&shar->work); + buf = shar->work.s; + } + } + + shar->work.length = buf - shar->work.s; + + return (written); +} + +#define UUENC(c) (((c)!=0) ? ((c) & 077) + ' ': '`') + +static void +uuencode_group(const char _in[3], char out[4]) +{ + const unsigned char *in = (const unsigned char *)_in; + int t; + + t = (in[0] << 16) | (in[1] << 8) | in[2]; + out[0] = UUENC( 0x3f & (t >> 18) ); + out[1] = UUENC( 0x3f & (t >> 12) ); + out[2] = UUENC( 0x3f & (t >> 6) ); + out[3] = UUENC( 0x3f & t ); +} + +static int +_uuencode_line(struct archive_write *a, struct shar *shar, const char *inbuf, size_t len) +{ + char *buf; + size_t alloc_len; + + /* len <= 45 -> expanded to 60 + len byte + new line */ + alloc_len = shar->work.length + 62; + if (archive_string_ensure(&shar->work, alloc_len) == NULL) { + archive_set_error(&a->archive, ENOMEM, "Out of memory"); + return (ARCHIVE_FATAL); + } + + buf = shar->work.s + shar->work.length; + *buf++ = UUENC(len); + while (len >= 3) { + uuencode_group(inbuf, buf); + len -= 3; + inbuf += 3; + buf += 4; + } + if (len != 0) { + char tmp_buf[3]; + tmp_buf[0] = inbuf[0]; + if (len == 1) + tmp_buf[1] = '\0'; + else + tmp_buf[1] = inbuf[1]; + tmp_buf[2] = '\0'; + uuencode_group(tmp_buf, buf); + buf += 4; + } + *buf++ = '\n'; + if ((buf - shar->work.s) > (ptrdiff_t)(shar->work.length + 62)) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, "Buffer overflow"); + return (ARCHIVE_FATAL); + } + shar->work.length = buf - shar->work.s; + return (ARCHIVE_OK); +} + +#define uuencode_line(__a, __shar, __inbuf, __len) \ + do { \ + int r = _uuencode_line(__a, __shar, __inbuf, __len); \ + if (r != ARCHIVE_OK) \ + return (ARCHIVE_FATAL); \ + } while (0) + +static ssize_t +archive_write_shar_data_uuencode(struct archive_write *a, const void *buff, + size_t length) +{ + struct shar *shar; + const char *src; + size_t n; + int ret; + + shar = (struct shar *)a->format_data; + if (!shar->has_data) + return (ARCHIVE_OK); + src = (const char *)buff; + + if (shar->outpos != 0) { + n = 45 - shar->outpos; + if (n > length) + n = length; + memcpy(shar->outbuff + shar->outpos, src, n); + if (shar->outpos + n < 45) { + shar->outpos += n; + return length; + } + uuencode_line(a, shar, shar->outbuff, 45); + src += n; + n = length - n; + } else { + n = length; + } + + while (n >= 45) { + uuencode_line(a, shar, src, 45); + src += 45; + n -= 45; + + if (shar->work.length < 65536) + continue; + ret = __archive_write_output(a, shar->work.s, + shar->work.length); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + archive_string_empty(&shar->work); + } + if (n != 0) { + memcpy(shar->outbuff, src, n); + shar->outpos = n; + } + return (length); +} + +static int +archive_write_shar_finish_entry(struct archive_write *a) +{ + const char *g, *p, *u; + struct shar *shar; + int ret; + + shar = (struct shar *)a->format_data; + if (shar->entry == NULL) + return (0); + + if (shar->dump) { + /* Finish uuencoded data. */ + if (shar->has_data) { + if (shar->outpos > 0) + uuencode_line(a, shar, shar->outbuff, + shar->outpos); + archive_strcat(&shar->work, "`\nend\n"); + archive_strcat(&shar->work, "SHAR_END\n"); + } + /* Restore file mode, owner, flags. */ + /* + * TODO: Don't immediately restore mode for + * directories; defer that to end of script. + */ + archive_string_sprintf(&shar->work, "chmod %o ", + (unsigned int)(archive_entry_mode(shar->entry) & 07777)); + shar_quote(&shar->work, archive_entry_pathname(shar->entry), 1); + archive_strcat(&shar->work, "\n"); + + u = archive_entry_uname(shar->entry); + g = archive_entry_gname(shar->entry); + if (u != NULL || g != NULL) { + archive_strcat(&shar->work, "chown "); + if (u != NULL) + shar_quote(&shar->work, u, 1); + if (g != NULL) { + archive_strcat(&shar->work, ":"); + shar_quote(&shar->work, g, 1); + } + archive_strcat(&shar->work, " "); + shar_quote(&shar->work, + archive_entry_pathname(shar->entry), 1); + archive_strcat(&shar->work, "\n"); + } + + if ((p = archive_entry_fflags_text(shar->entry)) != NULL) { + archive_string_sprintf(&shar->work, "chflags %s ", p); + shar_quote(&shar->work, + archive_entry_pathname(shar->entry), 1); + archive_strcat(&shar->work, "\n"); + } + + /* TODO: restore ACLs */ + + } else { + if (shar->has_data) { + /* Finish sed-encoded data: ensure last line ends. */ + if (!shar->end_of_line) + archive_strappend_char(&shar->work, '\n'); + archive_strcat(&shar->work, "SHAR_END\n"); + } + } + + archive_entry_free(shar->entry); + shar->entry = NULL; + + if (shar->work.length < 65536) + return (ARCHIVE_OK); + + ret = __archive_write_output(a, shar->work.s, shar->work.length); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + archive_string_empty(&shar->work); + + return (ARCHIVE_OK); +} + +static int +archive_write_shar_close(struct archive_write *a) +{ + struct shar *shar; + int ret; + + /* + * TODO: Accumulate list of directory names/modes and + * fix them all up at end-of-archive. + */ + + shar = (struct shar *)a->format_data; + + /* + * Only write the end-of-archive markers if the archive was + * actually started. This avoids problems if someone sets + * shar format, then sets another format (which would invoke + * shar_finish to free the format-specific data). + */ + if (shar->wrote_header == 0) + return (ARCHIVE_OK); + + archive_strcat(&shar->work, "exit\n"); + + ret = __archive_write_output(a, shar->work.s, shar->work.length); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + + /* Shar output is never padded. */ + archive_write_set_bytes_in_last_block(&a->archive, 1); + /* + * TODO: shar should also suppress padding of + * uncompressed data within gzip/bzip2 streams. + */ + + return (ARCHIVE_OK); +} + +static int +archive_write_shar_free(struct archive_write *a) +{ + struct shar *shar; + + shar = (struct shar *)a->format_data; + if (shar == NULL) + return (ARCHIVE_OK); + + archive_entry_free(shar->entry); + free(shar->last_dir); + archive_string_free(&(shar->work)); + archive_string_free(&(shar->quoted_name)); + free(shar); + a->format_data = NULL; + return (ARCHIVE_OK); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_ustar.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_ustar.c new file mode 100644 index 0000000000..d1a06bc4f7 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_ustar.c @@ -0,0 +1,758 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2011-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_ustar.c 191579 2009-04-27 18:35:03Z kientzle $"); + + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_write_private.h" +#include "archive_write_set_format_private.h" + +struct ustar { + uint64_t entry_bytes_remaining; + uint64_t entry_padding; + + struct archive_string_conv *opt_sconv; + struct archive_string_conv *sconv_default; + int init_default_conversion; +}; + +/* + * Define structure of POSIX 'ustar' tar header. + */ +#define USTAR_name_offset 0 +#define USTAR_name_size 100 +#define USTAR_mode_offset 100 +#define USTAR_mode_size 6 +#define USTAR_mode_max_size 8 +#define USTAR_uid_offset 108 +#define USTAR_uid_size 6 +#define USTAR_uid_max_size 8 +#define USTAR_gid_offset 116 +#define USTAR_gid_size 6 +#define USTAR_gid_max_size 8 +#define USTAR_size_offset 124 +#define USTAR_size_size 11 +#define USTAR_size_max_size 12 +#define USTAR_mtime_offset 136 +#define USTAR_mtime_size 11 +#define USTAR_mtime_max_size 11 +#define USTAR_checksum_offset 148 +#define USTAR_checksum_size 8 +#define USTAR_typeflag_offset 156 +#define USTAR_typeflag_size 1 +#define USTAR_linkname_offset 157 +#define USTAR_linkname_size 100 +#define USTAR_magic_offset 257 +#define USTAR_magic_size 6 +#define USTAR_version_offset 263 +#define USTAR_version_size 2 +#define USTAR_uname_offset 265 +#define USTAR_uname_size 32 +#define USTAR_gname_offset 297 +#define USTAR_gname_size 32 +#define USTAR_rdevmajor_offset 329 +#define USTAR_rdevmajor_size 6 +#define USTAR_rdevmajor_max_size 8 +#define USTAR_rdevminor_offset 337 +#define USTAR_rdevminor_size 6 +#define USTAR_rdevminor_max_size 8 +#define USTAR_prefix_offset 345 +#define USTAR_prefix_size 155 +#define USTAR_padding_offset 500 +#define USTAR_padding_size 12 + +/* + * A filled-in copy of the header for initialization. + */ +static const char template_header[] = { + /* name: 100 bytes */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0, + /* Mode, space-null termination: 8 bytes */ + '0','0','0','0','0','0', ' ','\0', + /* uid, space-null termination: 8 bytes */ + '0','0','0','0','0','0', ' ','\0', + /* gid, space-null termination: 8 bytes */ + '0','0','0','0','0','0', ' ','\0', + /* size, space termination: 12 bytes */ + '0','0','0','0','0','0','0','0','0','0','0', ' ', + /* mtime, space termination: 12 bytes */ + '0','0','0','0','0','0','0','0','0','0','0', ' ', + /* Initial checksum value: 8 spaces */ + ' ',' ',' ',' ',' ',' ',' ',' ', + /* Typeflag: 1 byte */ + '0', /* '0' = regular file */ + /* Linkname: 100 bytes */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0, + /* Magic: 6 bytes, Version: 2 bytes */ + 'u','s','t','a','r','\0', '0','0', + /* Uname: 32 bytes */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + /* Gname: 32 bytes */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + /* rdevmajor + space/null padding: 8 bytes */ + '0','0','0','0','0','0', ' ','\0', + /* rdevminor + space/null padding: 8 bytes */ + '0','0','0','0','0','0', ' ','\0', + /* Prefix: 155 bytes */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0, + /* Padding: 12 bytes */ + 0,0,0,0,0,0,0,0, 0,0,0,0 +}; + +static ssize_t archive_write_ustar_data(struct archive_write *a, const void *buff, + size_t s); +static int archive_write_ustar_free(struct archive_write *); +static int archive_write_ustar_close(struct archive_write *); +static int archive_write_ustar_finish_entry(struct archive_write *); +static int archive_write_ustar_header(struct archive_write *, + struct archive_entry *entry); +static int archive_write_ustar_options(struct archive_write *, + const char *, const char *); +static int format_256(int64_t, char *, int); +static int format_number(int64_t, char *, int size, int max, int strict); +static int format_octal(int64_t, char *, int); + +/* + * Set output format to 'ustar' format. + */ +int +archive_write_set_format_ustar(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct ustar *ustar; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_ustar"); + + /* If someone else was already registered, unregister them. */ + if (a->format_free != NULL) + (a->format_free)(a); + + /* Basic internal sanity test. */ + if (sizeof(template_header) != 512) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Internal: template_header wrong size: %zu should be 512", + sizeof(template_header)); + return (ARCHIVE_FATAL); + } + + ustar = (struct ustar *)calloc(1, sizeof(*ustar)); + if (ustar == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate ustar data"); + return (ARCHIVE_FATAL); + } + a->format_data = ustar; + a->format_name = "ustar"; + a->format_options = archive_write_ustar_options; + a->format_write_header = archive_write_ustar_header; + a->format_write_data = archive_write_ustar_data; + a->format_close = archive_write_ustar_close; + a->format_free = archive_write_ustar_free; + a->format_finish_entry = archive_write_ustar_finish_entry; + a->archive.archive_format = ARCHIVE_FORMAT_TAR_USTAR; + a->archive.archive_format_name = "POSIX ustar"; + return (ARCHIVE_OK); +} + +static int +archive_write_ustar_options(struct archive_write *a, const char *key, + const char *val) +{ + struct ustar *ustar = (struct ustar *)a->format_data; + int ret = ARCHIVE_FAILED; + + if (strcmp(key, "hdrcharset") == 0) { + if (val == NULL || val[0] == 0) + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "%s: hdrcharset option needs a character-set name", + a->format_name); + else { + ustar->opt_sconv = archive_string_conversion_to_charset( + &a->archive, val, 0); + if (ustar->opt_sconv != NULL) + ret = ARCHIVE_OK; + else + ret = ARCHIVE_FATAL; + } + return (ret); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static int +archive_write_ustar_header(struct archive_write *a, struct archive_entry *entry) +{ + char buff[512]; + int ret, ret2; + struct ustar *ustar; + struct archive_entry *entry_main; + struct archive_string_conv *sconv; + + ustar = (struct ustar *)a->format_data; + + /* Setup default string conversion. */ + if (ustar->opt_sconv == NULL) { + if (!ustar->init_default_conversion) { + ustar->sconv_default = + archive_string_default_conversion_for_write(&(a->archive)); + ustar->init_default_conversion = 1; + } + sconv = ustar->sconv_default; + } else + sconv = ustar->opt_sconv; + + /* Sanity check. */ + if (archive_entry_pathname(entry) == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can't record entry in tar file without pathname"); + return (ARCHIVE_FAILED); + } + + /* Only regular files (not hardlinks) have data. */ + if (archive_entry_hardlink(entry) != NULL || + archive_entry_symlink(entry) != NULL || + !(archive_entry_filetype(entry) == AE_IFREG)) + archive_entry_set_size(entry, 0); + + if (AE_IFDIR == archive_entry_filetype(entry)) { + const char *p; + size_t path_length; + /* + * Ensure a trailing '/'. Modify the entry so + * the client sees the change. + */ +#if defined(_WIN32) && !defined(__CYGWIN__) + const wchar_t *wp; + + wp = archive_entry_pathname_w(entry); + if (wp != NULL && wp[wcslen(wp) -1] != L'/') { + struct archive_wstring ws; + + archive_string_init(&ws); + path_length = wcslen(wp); + if (archive_wstring_ensure(&ws, + path_length + 2) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate ustar data"); + archive_wstring_free(&ws); + return(ARCHIVE_FATAL); + } + /* Should we keep '\' ? */ + if (wp[path_length -1] == L'\\') + path_length--; + archive_wstrncpy(&ws, wp, path_length); + archive_wstrappend_wchar(&ws, L'/'); + archive_entry_copy_pathname_w(entry, ws.s); + archive_wstring_free(&ws); + p = NULL; + } else +#endif + p = archive_entry_pathname(entry); + /* + * On Windows, this is a backup operation just in + * case getting WCS failed. On POSIX, this is a + * normal operation. + */ + if (p != NULL && p[0] != '\0' && p[strlen(p) - 1] != '/') { + struct archive_string as; + + archive_string_init(&as); + path_length = strlen(p); + if (archive_string_ensure(&as, + path_length + 2) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate ustar data"); + archive_string_free(&as); + return(ARCHIVE_FATAL); + } +#if defined(_WIN32) && !defined(__CYGWIN__) + /* NOTE: This might break the pathname + * if the current code page is CP932 and + * the pathname includes a character '\' + * as a part of its multibyte pathname. */ + if (p[strlen(p) -1] == '\\') + path_length--; + else +#endif + archive_strncpy(&as, p, path_length); + archive_strappend_char(&as, '/'); + archive_entry_copy_pathname(entry, as.s); + archive_string_free(&as); + } + } + +#if defined(_WIN32) && !defined(__CYGWIN__) + /* Make sure the path separators in pathname, hardlink and symlink + * are all slash '/', not the Windows path separator '\'. */ + entry_main = __la_win_entry_in_posix_pathseparator(entry); + if (entry_main == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate ustar data"); + return(ARCHIVE_FATAL); + } + if (entry != entry_main) + entry = entry_main; + else + entry_main = NULL; +#else + entry_main = NULL; +#endif + ret = __archive_write_format_header_ustar(a, buff, entry, -1, 1, sconv); + if (ret < ARCHIVE_WARN) { + archive_entry_free(entry_main); + return (ret); + } + ret2 = __archive_write_output(a, buff, 512); + if (ret2 < ARCHIVE_WARN) { + archive_entry_free(entry_main); + return (ret2); + } + if (ret2 < ret) + ret = ret2; + + ustar->entry_bytes_remaining = archive_entry_size(entry); + ustar->entry_padding = 0x1ff & (-(int64_t)ustar->entry_bytes_remaining); + archive_entry_free(entry_main); + return (ret); +} + +/* + * Format a basic 512-byte "ustar" header. + * + * Returns -1 if format failed (due to field overflow). + * Note that this always formats as much of the header as possible. + * If "strict" is set to zero, it will extend numeric fields as + * necessary (overwriting terminators or using base-256 extensions). + * + * This is exported so that other 'tar' formats can use it. + */ +int +__archive_write_format_header_ustar(struct archive_write *a, char h[512], + struct archive_entry *entry, int tartype, int strict, + struct archive_string_conv *sconv) +{ + unsigned int checksum; + int i, r, ret; + size_t copy_length; + const char *p, *pp; + int mytartype; + + ret = 0; + mytartype = -1; + /* + * The "template header" already includes the "ustar" + * signature, various end-of-field markers and other required + * elements. + */ + memcpy(h, &template_header, 512); + + /* + * Because the block is already null-filled, and strings + * are allowed to exactly fill their destination (without null), + * I use memcpy(dest, src, strlen()) here a lot to copy strings. + */ + r = archive_entry_pathname_l(entry, &pp, ©_length, sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate pathname '%s' to %s", + pp, archive_string_conversion_charset_name(sconv)); + ret = ARCHIVE_WARN; + } + if (copy_length <= USTAR_name_size) + memcpy(h + USTAR_name_offset, pp, copy_length); + else { + /* Store in two pieces, splitting at a '/'. */ + p = strchr(pp + copy_length - USTAR_name_size - 1, '/'); + /* + * Look for the next '/' if we chose the first character + * as the separator. (ustar format doesn't permit + * an empty prefix.) + */ + if (p == pp) + p = strchr(p + 1, '/'); + /* Fail if the name won't fit. */ + if (!p) { + /* No separator. */ + archive_set_error(&a->archive, ENAMETOOLONG, + "Pathname too long"); + ret = ARCHIVE_FAILED; + } else if (p[1] == '\0') { + /* + * The only feasible separator is a final '/'; + * this would result in a non-empty prefix and + * an empty name, which POSIX doesn't + * explicitly forbid, but it just feels wrong. + */ + archive_set_error(&a->archive, ENAMETOOLONG, + "Pathname too long"); + ret = ARCHIVE_FAILED; + } else if (p > pp + USTAR_prefix_size) { + /* Prefix is too long. */ + archive_set_error(&a->archive, ENAMETOOLONG, + "Pathname too long"); + ret = ARCHIVE_FAILED; + } else { + /* Copy prefix and remainder to appropriate places */ + memcpy(h + USTAR_prefix_offset, pp, p - pp); + memcpy(h + USTAR_name_offset, p + 1, + pp + copy_length - p - 1); + } + } + + r = archive_entry_hardlink_l(entry, &p, ©_length, sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Linkname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate linkname '%s' to %s", + p, archive_string_conversion_charset_name(sconv)); + ret = ARCHIVE_WARN; + } + if (copy_length > 0) + mytartype = '1'; + else { + r = archive_entry_symlink_l(entry, &p, ©_length, sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Linkname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate linkname '%s' to %s", + p, archive_string_conversion_charset_name(sconv)); + ret = ARCHIVE_WARN; + } + } + if (copy_length > 0) { + if (copy_length > USTAR_linkname_size) { + archive_set_error(&a->archive, ENAMETOOLONG, + "Link contents too long"); + ret = ARCHIVE_FAILED; + copy_length = USTAR_linkname_size; + } + memcpy(h + USTAR_linkname_offset, p, copy_length); + } + + r = archive_entry_uname_l(entry, &p, ©_length, sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Uname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate uname '%s' to %s", + p, archive_string_conversion_charset_name(sconv)); + ret = ARCHIVE_WARN; + } + if (copy_length > 0) { + if (copy_length > USTAR_uname_size) { + if (tartype != 'x') { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, "Username too long"); + ret = ARCHIVE_FAILED; + } + copy_length = USTAR_uname_size; + } + memcpy(h + USTAR_uname_offset, p, copy_length); + } + + r = archive_entry_gname_l(entry, &p, ©_length, sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Gname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate gname '%s' to %s", + p, archive_string_conversion_charset_name(sconv)); + ret = ARCHIVE_WARN; + } + if (copy_length > 0) { + if (strlen(p) > USTAR_gname_size) { + if (tartype != 'x') { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, "Group name too long"); + ret = ARCHIVE_FAILED; + } + copy_length = USTAR_gname_size; + } + memcpy(h + USTAR_gname_offset, p, copy_length); + } + + if (format_number(archive_entry_mode(entry) & 07777, + h + USTAR_mode_offset, USTAR_mode_size, USTAR_mode_max_size, strict)) { + archive_set_error(&a->archive, ERANGE, + "Numeric mode too large"); + ret = ARCHIVE_FAILED; + } + + if (format_number(archive_entry_uid(entry), + h + USTAR_uid_offset, USTAR_uid_size, USTAR_uid_max_size, strict)) { + archive_set_error(&a->archive, ERANGE, + "Numeric user ID too large"); + ret = ARCHIVE_FAILED; + } + + if (format_number(archive_entry_gid(entry), + h + USTAR_gid_offset, USTAR_gid_size, USTAR_gid_max_size, strict)) { + archive_set_error(&a->archive, ERANGE, + "Numeric group ID too large"); + ret = ARCHIVE_FAILED; + } + + if (format_number(archive_entry_size(entry), + h + USTAR_size_offset, USTAR_size_size, USTAR_size_max_size, strict)) { + archive_set_error(&a->archive, ERANGE, + "File size out of range"); + ret = ARCHIVE_FAILED; + } + + if (format_number(archive_entry_mtime(entry), + h + USTAR_mtime_offset, USTAR_mtime_size, USTAR_mtime_max_size, strict)) { + archive_set_error(&a->archive, ERANGE, + "File modification time too large"); + ret = ARCHIVE_FAILED; + } + + if (archive_entry_filetype(entry) == AE_IFBLK + || archive_entry_filetype(entry) == AE_IFCHR) { + if (format_number(archive_entry_rdevmajor(entry), + h + USTAR_rdevmajor_offset, USTAR_rdevmajor_size, + USTAR_rdevmajor_max_size, strict)) { + archive_set_error(&a->archive, ERANGE, + "Major device number too large"); + ret = ARCHIVE_FAILED; + } + + if (format_number(archive_entry_rdevminor(entry), + h + USTAR_rdevminor_offset, USTAR_rdevminor_size, + USTAR_rdevminor_max_size, strict)) { + archive_set_error(&a->archive, ERANGE, + "Minor device number too large"); + ret = ARCHIVE_FAILED; + } + } + + if (tartype >= 0) { + h[USTAR_typeflag_offset] = tartype; + } else if (mytartype >= 0) { + h[USTAR_typeflag_offset] = mytartype; + } else { + switch (archive_entry_filetype(entry)) { + case AE_IFREG: h[USTAR_typeflag_offset] = '0' ; break; + case AE_IFLNK: h[USTAR_typeflag_offset] = '2' ; break; + case AE_IFCHR: h[USTAR_typeflag_offset] = '3' ; break; + case AE_IFBLK: h[USTAR_typeflag_offset] = '4' ; break; + case AE_IFDIR: h[USTAR_typeflag_offset] = '5' ; break; + case AE_IFIFO: h[USTAR_typeflag_offset] = '6' ; break; + default: /* AE_IFSOCK and unknown */ + __archive_write_entry_filetype_unsupported( + &a->archive, entry, "ustar"); + ret = ARCHIVE_FAILED; + } + } + + checksum = 0; + for (i = 0; i < 512; i++) + checksum += 255 & (unsigned int)h[i]; + h[USTAR_checksum_offset + 6] = '\0'; /* Can't be pre-set in the template. */ + /* h[USTAR_checksum_offset + 7] = ' '; */ /* This is pre-set in the template. */ + format_octal(checksum, h + USTAR_checksum_offset, 6); + return (ret); +} + +/* + * Format a number into a field, with some intelligence. + */ +static int +format_number(int64_t v, char *p, int s, int maxsize, int strict) +{ + int64_t limit; + + limit = ((int64_t)1 << (s*3)); + + /* "Strict" only permits octal values with proper termination. */ + if (strict) + return (format_octal(v, p, s)); + + /* + * In non-strict mode, we allow the number to overwrite one or + * more bytes of the field termination. Even old tar + * implementations should be able to handle this with no + * problem. + */ + if (v >= 0) { + while (s <= maxsize) { + if (v < limit) + return (format_octal(v, p, s)); + s++; + limit <<= 3; + } + } + + /* Base-256 can handle any number, positive or negative. */ + return (format_256(v, p, maxsize)); +} + +/* + * Format a number into the specified field using base-256. + */ +static int +format_256(int64_t v, char *p, int s) +{ + p += s; + while (s-- > 0) { + *--p = (char)(v & 0xff); + v >>= 8; + } + *p |= 0x80; /* Set the base-256 marker bit. */ + return (0); +} + +/* + * Format a number into the specified field. + */ +static int +format_octal(int64_t v, char *p, int s) +{ + int len; + + len = s; + + /* Octal values can't be negative, so use 0. */ + if (v < 0) { + while (len-- > 0) + *p++ = '0'; + return (-1); + } + + p += s; /* Start at the end and work backwards. */ + while (s-- > 0) { + *--p = (char)('0' + (v & 7)); + v >>= 3; + } + + if (v == 0) + return (0); + + /* If it overflowed, fill field with max value. */ + while (len-- > 0) + *p++ = '7'; + + return (-1); +} + +static int +archive_write_ustar_close(struct archive_write *a) +{ + return (__archive_write_nulls(a, 512*2)); +} + +static int +archive_write_ustar_free(struct archive_write *a) +{ + struct ustar *ustar; + + ustar = (struct ustar *)a->format_data; + free(ustar); + a->format_data = NULL; + return (ARCHIVE_OK); +} + +static int +archive_write_ustar_finish_entry(struct archive_write *a) +{ + struct ustar *ustar; + int ret; + + ustar = (struct ustar *)a->format_data; + ret = __archive_write_nulls(a, + (size_t)(ustar->entry_bytes_remaining + ustar->entry_padding)); + ustar->entry_bytes_remaining = ustar->entry_padding = 0; + return (ret); +} + +static ssize_t +archive_write_ustar_data(struct archive_write *a, const void *buff, size_t s) +{ + struct ustar *ustar; + int ret; + + ustar = (struct ustar *)a->format_data; + if (s > ustar->entry_bytes_remaining) + s = (size_t)ustar->entry_bytes_remaining; + ret = __archive_write_output(a, buff, s); + ustar->entry_bytes_remaining -= s; + if (ret != ARCHIVE_OK) + return (ret); + return (s); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_v7tar.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_v7tar.c new file mode 100644 index 0000000000..5994071441 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_v7tar.c @@ -0,0 +1,638 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * Copyright (c) 2011-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_write_private.h" +#include "archive_write_set_format_private.h" + +struct v7tar { + uint64_t entry_bytes_remaining; + uint64_t entry_padding; + + struct archive_string_conv *opt_sconv; + struct archive_string_conv *sconv_default; + int init_default_conversion; +}; + +/* + * Define structure of POSIX 'v7tar' tar header. + */ +#define V7TAR_name_offset 0 +#define V7TAR_name_size 100 +#define V7TAR_mode_offset 100 +#define V7TAR_mode_size 6 +#define V7TAR_mode_max_size 8 +#define V7TAR_uid_offset 108 +#define V7TAR_uid_size 6 +#define V7TAR_uid_max_size 8 +#define V7TAR_gid_offset 116 +#define V7TAR_gid_size 6 +#define V7TAR_gid_max_size 8 +#define V7TAR_size_offset 124 +#define V7TAR_size_size 11 +#define V7TAR_size_max_size 12 +#define V7TAR_mtime_offset 136 +#define V7TAR_mtime_size 11 +#define V7TAR_mtime_max_size 12 +#define V7TAR_checksum_offset 148 +#define V7TAR_checksum_size 8 +#define V7TAR_typeflag_offset 156 +#define V7TAR_typeflag_size 1 +#define V7TAR_linkname_offset 157 +#define V7TAR_linkname_size 100 +#define V7TAR_padding_offset 257 +#define V7TAR_padding_size 255 + +/* + * A filled-in copy of the header for initialization. + */ +static const char template_header[] = { + /* name: 100 bytes */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0, + /* Mode, space-null termination: 8 bytes */ + '0','0','0','0','0','0', ' ','\0', + /* uid, space-null termination: 8 bytes */ + '0','0','0','0','0','0', ' ','\0', + /* gid, space-null termination: 8 bytes */ + '0','0','0','0','0','0', ' ','\0', + /* size, space termination: 12 bytes */ + '0','0','0','0','0','0','0','0','0','0','0', ' ', + /* mtime, space termination: 12 bytes */ + '0','0','0','0','0','0','0','0','0','0','0', ' ', + /* Initial checksum value: 8 spaces */ + ' ',' ',' ',' ',' ',' ',' ',' ', + /* Typeflag: 1 byte */ + 0, + /* Linkname: 100 bytes */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0, + /* Padding: 255 bytes */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0 +}; + +static ssize_t archive_write_v7tar_data(struct archive_write *a, const void *buff, + size_t s); +static int archive_write_v7tar_free(struct archive_write *); +static int archive_write_v7tar_close(struct archive_write *); +static int archive_write_v7tar_finish_entry(struct archive_write *); +static int archive_write_v7tar_header(struct archive_write *, + struct archive_entry *entry); +static int archive_write_v7tar_options(struct archive_write *, + const char *, const char *); +static int format_256(int64_t, char *, int); +static int format_number(int64_t, char *, int size, int max, int strict); +static int format_octal(int64_t, char *, int); +static int format_header_v7tar(struct archive_write *, char h[512], + struct archive_entry *, int, struct archive_string_conv *); + +/* + * Set output format to 'v7tar' format. + */ +int +archive_write_set_format_v7tar(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct v7tar *v7tar; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_v7tar"); + + /* If someone else was already registered, unregister them. */ + if (a->format_free != NULL) + (a->format_free)(a); + + /* Basic internal sanity test. */ + if (sizeof(template_header) != 512) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Internal: template_header wrong size: %zu should be 512", + sizeof(template_header)); + return (ARCHIVE_FATAL); + } + + v7tar = (struct v7tar *)calloc(1, sizeof(*v7tar)); + if (v7tar == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate v7tar data"); + return (ARCHIVE_FATAL); + } + a->format_data = v7tar; + a->format_name = "tar (non-POSIX)"; + a->format_options = archive_write_v7tar_options; + a->format_write_header = archive_write_v7tar_header; + a->format_write_data = archive_write_v7tar_data; + a->format_close = archive_write_v7tar_close; + a->format_free = archive_write_v7tar_free; + a->format_finish_entry = archive_write_v7tar_finish_entry; + a->archive.archive_format = ARCHIVE_FORMAT_TAR; + a->archive.archive_format_name = "tar (non-POSIX)"; + return (ARCHIVE_OK); +} + +static int +archive_write_v7tar_options(struct archive_write *a, const char *key, + const char *val) +{ + struct v7tar *v7tar = (struct v7tar *)a->format_data; + int ret = ARCHIVE_FAILED; + + if (strcmp(key, "hdrcharset") == 0) { + if (val == NULL || val[0] == 0) + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "%s: hdrcharset option needs a character-set name", + a->format_name); + else { + v7tar->opt_sconv = archive_string_conversion_to_charset( + &a->archive, val, 0); + if (v7tar->opt_sconv != NULL) + ret = ARCHIVE_OK; + else + ret = ARCHIVE_FATAL; + } + return (ret); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static int +archive_write_v7tar_header(struct archive_write *a, struct archive_entry *entry) +{ + char buff[512]; + int ret, ret2; + struct v7tar *v7tar; + struct archive_entry *entry_main; + struct archive_string_conv *sconv; + + v7tar = (struct v7tar *)a->format_data; + + /* Setup default string conversion. */ + if (v7tar->opt_sconv == NULL) { + if (!v7tar->init_default_conversion) { + v7tar->sconv_default = + archive_string_default_conversion_for_write( + &(a->archive)); + v7tar->init_default_conversion = 1; + } + sconv = v7tar->sconv_default; + } else + sconv = v7tar->opt_sconv; + + /* Sanity check. */ + if (archive_entry_pathname(entry) == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can't record entry in tar file without pathname"); + return (ARCHIVE_FAILED); + } + + /* Only regular files (not hardlinks) have data. */ + if (archive_entry_hardlink(entry) != NULL || + archive_entry_symlink(entry) != NULL || + !(archive_entry_filetype(entry) == AE_IFREG)) + archive_entry_set_size(entry, 0); + + if (AE_IFDIR == archive_entry_filetype(entry)) { + const char *p; + size_t path_length; + /* + * Ensure a trailing '/'. Modify the entry so + * the client sees the change. + */ +#if defined(_WIN32) && !defined(__CYGWIN__) + const wchar_t *wp; + + wp = archive_entry_pathname_w(entry); + if (wp != NULL && wp[wcslen(wp) -1] != L'/') { + struct archive_wstring ws; + + archive_string_init(&ws); + path_length = wcslen(wp); + if (archive_wstring_ensure(&ws, + path_length + 2) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate v7tar data"); + archive_wstring_free(&ws); + return(ARCHIVE_FATAL); + } + /* Should we keep '\' ? */ + if (wp[path_length -1] == L'\\') + path_length--; + archive_wstrncpy(&ws, wp, path_length); + archive_wstrappend_wchar(&ws, L'/'); + archive_entry_copy_pathname_w(entry, ws.s); + archive_wstring_free(&ws); + p = NULL; + } else +#endif + p = archive_entry_pathname(entry); + /* + * On Windows, this is a backup operation just in + * case getting WCS failed. On POSIX, this is a + * normal operation. + */ + if (p != NULL && p[0] != '\0' && p[strlen(p) - 1] != '/') { + struct archive_string as; + + archive_string_init(&as); + path_length = strlen(p); + if (archive_string_ensure(&as, + path_length + 2) == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate v7tar data"); + archive_string_free(&as); + return(ARCHIVE_FATAL); + } +#if defined(_WIN32) && !defined(__CYGWIN__) + /* NOTE: This might break the pathname + * if the current code page is CP932 and + * the pathname includes a character '\' + * as a part of its multibyte pathname. */ + if (p[strlen(p) -1] == '\\') + path_length--; + else +#endif + archive_strncpy(&as, p, path_length); + archive_strappend_char(&as, '/'); + archive_entry_copy_pathname(entry, as.s); + archive_string_free(&as); + } + } + +#if defined(_WIN32) && !defined(__CYGWIN__) + /* Make sure the path separators in pathname, hardlink and symlink + * are all slash '/', not the Windows path separator '\'. */ + entry_main = __la_win_entry_in_posix_pathseparator(entry); + if (entry_main == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate v7tar data"); + return(ARCHIVE_FATAL); + } + if (entry != entry_main) + entry = entry_main; + else + entry_main = NULL; +#else + entry_main = NULL; +#endif + ret = format_header_v7tar(a, buff, entry, 1, sconv); + if (ret < ARCHIVE_WARN) { + archive_entry_free(entry_main); + return (ret); + } + ret2 = __archive_write_output(a, buff, 512); + if (ret2 < ARCHIVE_WARN) { + archive_entry_free(entry_main); + return (ret2); + } + if (ret2 < ret) + ret = ret2; + + v7tar->entry_bytes_remaining = archive_entry_size(entry); + v7tar->entry_padding = 0x1ff & (-(int64_t)v7tar->entry_bytes_remaining); + archive_entry_free(entry_main); + return (ret); +} + +/* + * Format a basic 512-byte "v7tar" header. + * + * Returns -1 if format failed (due to field overflow). + * Note that this always formats as much of the header as possible. + * If "strict" is set to zero, it will extend numeric fields as + * necessary (overwriting terminators or using base-256 extensions). + * + */ +static int +format_header_v7tar(struct archive_write *a, char h[512], + struct archive_entry *entry, int strict, + struct archive_string_conv *sconv) +{ + unsigned int checksum; + int i, r, ret; + size_t copy_length; + const char *p, *pp; + int mytartype; + + ret = 0; + mytartype = -1; + /* + * The "template header" already includes the "v7tar" + * signature, various end-of-field markers and other required + * elements. + */ + memcpy(h, &template_header, 512); + + /* + * Because the block is already null-filled, and strings + * are allowed to exactly fill their destination (without null), + * I use memcpy(dest, src, strlen()) here a lot to copy strings. + */ + r = archive_entry_pathname_l(entry, &pp, ©_length, sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate pathname '%s' to %s", + pp, archive_string_conversion_charset_name(sconv)); + ret = ARCHIVE_WARN; + } + if (strict && copy_length < V7TAR_name_size) + memcpy(h + V7TAR_name_offset, pp, copy_length); + else if (!strict && copy_length <= V7TAR_name_size) + memcpy(h + V7TAR_name_offset, pp, copy_length); + else { + /* Prefix is too long. */ + archive_set_error(&a->archive, ENAMETOOLONG, + "Pathname too long"); + ret = ARCHIVE_FAILED; + } + + r = archive_entry_hardlink_l(entry, &p, ©_length, sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Linkname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate linkname '%s' to %s", + p, archive_string_conversion_charset_name(sconv)); + ret = ARCHIVE_WARN; + } + if (copy_length > 0) + mytartype = '1'; + else { + r = archive_entry_symlink_l(entry, &p, ©_length, sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Linkname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate linkname '%s' to %s", + p, archive_string_conversion_charset_name(sconv)); + ret = ARCHIVE_WARN; + } + } + if (copy_length > 0) { + if (copy_length >= V7TAR_linkname_size) { + archive_set_error(&a->archive, ENAMETOOLONG, + "Link contents too long"); + ret = ARCHIVE_FAILED; + copy_length = V7TAR_linkname_size; + } + memcpy(h + V7TAR_linkname_offset, p, copy_length); + } + + if (format_number(archive_entry_mode(entry) & 07777, + h + V7TAR_mode_offset, V7TAR_mode_size, + V7TAR_mode_max_size, strict)) { + archive_set_error(&a->archive, ERANGE, + "Numeric mode too large"); + ret = ARCHIVE_FAILED; + } + + if (format_number(archive_entry_uid(entry), + h + V7TAR_uid_offset, V7TAR_uid_size, V7TAR_uid_max_size, strict)) { + archive_set_error(&a->archive, ERANGE, + "Numeric user ID too large"); + ret = ARCHIVE_FAILED; + } + + if (format_number(archive_entry_gid(entry), + h + V7TAR_gid_offset, V7TAR_gid_size, V7TAR_gid_max_size, strict)) { + archive_set_error(&a->archive, ERANGE, + "Numeric group ID too large"); + ret = ARCHIVE_FAILED; + } + + if (format_number(archive_entry_size(entry), + h + V7TAR_size_offset, V7TAR_size_size, + V7TAR_size_max_size, strict)) { + archive_set_error(&a->archive, ERANGE, + "File size out of range"); + ret = ARCHIVE_FAILED; + } + + if (format_number(archive_entry_mtime(entry), + h + V7TAR_mtime_offset, V7TAR_mtime_size, + V7TAR_mtime_max_size, strict)) { + archive_set_error(&a->archive, ERANGE, + "File modification time too large"); + ret = ARCHIVE_FAILED; + } + + if (mytartype >= 0) { + h[V7TAR_typeflag_offset] = mytartype; + } else { + switch (archive_entry_filetype(entry)) { + case AE_IFREG: case AE_IFDIR: + break; + case AE_IFLNK: + h[V7TAR_typeflag_offset] = '2'; + break; + default: + /* AE_IFBLK, AE_IFCHR, AE_IFIFO, AE_IFSOCK + * and unknown */ + __archive_write_entry_filetype_unsupported( + &a->archive, entry, "v7tar"); + ret = ARCHIVE_FAILED; + } + } + + checksum = 0; + for (i = 0; i < 512; i++) + checksum += 255 & (unsigned int)h[i]; + format_octal(checksum, h + V7TAR_checksum_offset, 6); + /* Can't be pre-set in the template. */ + h[V7TAR_checksum_offset + 6] = '\0'; + return (ret); +} + +/* + * Format a number into a field, with some intelligence. + */ +static int +format_number(int64_t v, char *p, int s, int maxsize, int strict) +{ + int64_t limit; + + limit = ((int64_t)1 << (s*3)); + + /* "Strict" only permits octal values with proper termination. */ + if (strict) + return (format_octal(v, p, s)); + + /* + * In non-strict mode, we allow the number to overwrite one or + * more bytes of the field termination. Even old tar + * implementations should be able to handle this with no + * problem. + */ + if (v >= 0) { + while (s <= maxsize) { + if (v < limit) + return (format_octal(v, p, s)); + s++; + limit <<= 3; + } + } + + /* Base-256 can handle any number, positive or negative. */ + return (format_256(v, p, maxsize)); +} + +/* + * Format a number into the specified field using base-256. + */ +static int +format_256(int64_t v, char *p, int s) +{ + p += s; + while (s-- > 0) { + *--p = (char)(v & 0xff); + v >>= 8; + } + *p |= 0x80; /* Set the base-256 marker bit. */ + return (0); +} + +/* + * Format a number into the specified field. + */ +static int +format_octal(int64_t v, char *p, int s) +{ + int len; + + len = s; + + /* Octal values can't be negative, so use 0. */ + if (v < 0) { + while (len-- > 0) + *p++ = '0'; + return (-1); + } + + p += s; /* Start at the end and work backwards. */ + while (s-- > 0) { + *--p = (char)('0' + (v & 7)); + v >>= 3; + } + + if (v == 0) + return (0); + + /* If it overflowed, fill field with max value. */ + while (len-- > 0) + *p++ = '7'; + + return (-1); +} + +static int +archive_write_v7tar_close(struct archive_write *a) +{ + return (__archive_write_nulls(a, 512*2)); +} + +static int +archive_write_v7tar_free(struct archive_write *a) +{ + struct v7tar *v7tar; + + v7tar = (struct v7tar *)a->format_data; + free(v7tar); + a->format_data = NULL; + return (ARCHIVE_OK); +} + +static int +archive_write_v7tar_finish_entry(struct archive_write *a) +{ + struct v7tar *v7tar; + int ret; + + v7tar = (struct v7tar *)a->format_data; + ret = __archive_write_nulls(a, + (size_t)(v7tar->entry_bytes_remaining + v7tar->entry_padding)); + v7tar->entry_bytes_remaining = v7tar->entry_padding = 0; + return (ret); +} + +static ssize_t +archive_write_v7tar_data(struct archive_write *a, const void *buff, size_t s) +{ + struct v7tar *v7tar; + int ret; + + v7tar = (struct v7tar *)a->format_data; + if (s > v7tar->entry_bytes_remaining) + s = (size_t)v7tar->entry_bytes_remaining; + ret = __archive_write_output(a, buff, s); + v7tar->entry_bytes_remaining -= s; + if (ret != ARCHIVE_OK) + return (ret); + return (s); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_warc.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_warc.c new file mode 100644 index 0000000000..46b0573412 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_warc.c @@ -0,0 +1,453 @@ +/*- + * Copyright (c) 2014 Sebastian Freundt + * Author: Sebastian Freundt <devel@fresse.org> + * + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_TIME_H +#include <time.h> +#endif + +#include "archive.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_random_private.h" +#include "archive_write_private.h" +#include "archive_write_set_format_private.h" + +struct warc_s { + unsigned int omit_warcinfo:1; + + time_t now; + mode_t typ; + unsigned int rng; + /* populated size */ + uint64_t populz; +}; + +static const char warcinfo[] = + "software: libarchive/" ARCHIVE_VERSION_ONLY_STRING "\r\n" + "format: WARC file version 1.0\r\n"; + +typedef enum { + WT_NONE, + /* warcinfo */ + WT_INFO, + /* metadata */ + WT_META, + /* resource */ + WT_RSRC, + /* request, unsupported */ + WT_REQ, + /* response, unsupported */ + WT_RSP, + /* revisit, unsupported */ + WT_RVIS, + /* conversion, unsupported */ + WT_CONV, + /* continuation, unsupported at the moment */ + WT_CONT, + /* invalid type */ + LAST_WT +} warc_type_t; + +typedef struct { + warc_type_t type; + const char *tgturi; + const char *recid; + time_t rtime; + time_t mtime; + const char *cnttyp; + uint64_t cntlen; +} warc_essential_hdr_t; + +typedef struct { + unsigned int u[4U]; +} warc_uuid_t; + +static int _warc_options(struct archive_write*, const char *key, const char *v); +static int _warc_header(struct archive_write *a, struct archive_entry *entry); +static ssize_t _warc_data(struct archive_write *a, const void *buf, size_t sz); +static int _warc_finish_entry(struct archive_write *a); +static int _warc_close(struct archive_write *a); +static int _warc_free(struct archive_write *a); + +/* private routines */ +static ssize_t _popul_ehdr(struct archive_string *t, size_t z, warc_essential_hdr_t); +static int _gen_uuid(warc_uuid_t *tgt); + + +/* + * Set output format to ISO 28500 (aka WARC) format. + */ +int +archive_write_set_format_warc(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct warc_s *w; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_warc"); + + /* If another format was already registered, unregister it. */ + if (a->format_free != NULL) { + (a->format_free)(a); + } + + w = malloc(sizeof(*w)); + if (w == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate warc data"); + return (ARCHIVE_FATAL); + } + /* by default we're emitting a file wide header */ + w->omit_warcinfo = 0U; + /* obtain current time for date fields */ + w->now = time(NULL); + /* reset file type info */ + w->typ = 0; + /* also initialise our rng */ + w->rng = (unsigned int)w->now; + + a->format_data = w; + a->format_name = "WARC/1.0"; + a->format_options = _warc_options; + a->format_write_header = _warc_header; + a->format_write_data = _warc_data; + a->format_close = _warc_close; + a->format_free = _warc_free; + a->format_finish_entry = _warc_finish_entry; + a->archive.archive_format = ARCHIVE_FORMAT_WARC; + a->archive.archive_format_name = "WARC/1.0"; + return (ARCHIVE_OK); +} + + +/* archive methods */ +static int +_warc_options(struct archive_write *a, const char *key, const char *val) +{ + struct warc_s *w = a->format_data; + + if (strcmp(key, "omit-warcinfo") == 0) { + if (val == NULL || strcmp(val, "true") == 0) { + /* great */ + w->omit_warcinfo = 1U; + return (ARCHIVE_OK); + } + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static int +_warc_header(struct archive_write *a, struct archive_entry *entry) +{ + struct warc_s *w = a->format_data; + struct archive_string hdr; +#define MAX_HDR_SIZE 512 + + /* check whether warcinfo record needs outputting */ + if (!w->omit_warcinfo) { + ssize_t r; + warc_essential_hdr_t wi = { + WT_INFO, + /*uri*/NULL, + /*urn*/NULL, + /*rtm*/0, + /*mtm*/0, + /*cty*/"application/warc-fields", + /*len*/sizeof(warcinfo) - 1U, + }; + wi.rtime = w->now; + wi.mtime = w->now; + + archive_string_init(&hdr); + r = _popul_ehdr(&hdr, MAX_HDR_SIZE, wi); + if (r >= 0) { + /* jackpot! */ + /* now also use HDR buffer for the actual warcinfo */ + archive_strncat(&hdr, warcinfo, sizeof(warcinfo) -1); + + /* append end-of-record indicator */ + archive_strncat(&hdr, "\r\n\r\n", 4); + + /* write to output stream */ + __archive_write_output(a, hdr.s, archive_strlen(&hdr)); + } + /* indicate we're done with file header writing */ + w->omit_warcinfo = 1U; + archive_string_free(&hdr); + } + + if (archive_entry_pathname(entry) == NULL) { + archive_set_error(&a->archive, EINVAL, + "Invalid filename"); + return (ARCHIVE_WARN); + } + + w->typ = archive_entry_filetype(entry); + w->populz = 0U; + if (w->typ == AE_IFREG) { + warc_essential_hdr_t rh = { + WT_RSRC, + /*uri*/NULL, + /*urn*/NULL, + /*rtm*/0, + /*mtm*/0, + /*cty*/NULL, + /*len*/0, + }; + ssize_t r; + rh.tgturi = archive_entry_pathname(entry); + rh.rtime = w->now; + rh.mtime = archive_entry_mtime(entry); + rh.cntlen = (size_t)archive_entry_size(entry); + + archive_string_init(&hdr); + r = _popul_ehdr(&hdr, MAX_HDR_SIZE, rh); + if (r < 0) { + /* don't bother */ + archive_set_error( + &a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "cannot archive file"); + return (ARCHIVE_WARN); + } + /* otherwise append to output stream */ + __archive_write_output(a, hdr.s, r); + /* and let subsequent calls to _data() know about the size */ + w->populz = rh.cntlen; + archive_string_free(&hdr); + return (ARCHIVE_OK); + } + /* just resort to erroring as per Tim's advice */ + __archive_write_entry_filetype_unsupported( + &a->archive, entry, "WARC"); + return (ARCHIVE_FAILED); +} + +static ssize_t +_warc_data(struct archive_write *a, const void *buf, size_t len) +{ + struct warc_s *w = a->format_data; + + if (w->typ == AE_IFREG) { + int rc; + + /* never write more bytes than announced */ + if (len > w->populz) { + len = (size_t)w->populz; + } + + /* now then, out we put the whole shebang */ + rc = __archive_write_output(a, buf, len); + if (rc != ARCHIVE_OK) { + return rc; + } + } + return len; +} + +static int +_warc_finish_entry(struct archive_write *a) +{ + static const char _eor[] = "\r\n\r\n"; + struct warc_s *w = a->format_data; + + if (w->typ == AE_IFREG) { + int rc = __archive_write_output(a, _eor, sizeof(_eor) - 1U); + + if (rc != ARCHIVE_OK) { + return rc; + } + } + /* reset type info */ + w->typ = 0; + return (ARCHIVE_OK); +} + +static int +_warc_close(struct archive_write *a) +{ + (void)a; /* UNUSED */ + return (ARCHIVE_OK); +} + +static int +_warc_free(struct archive_write *a) +{ + struct warc_s *w = a->format_data; + + free(w); + a->format_data = NULL; + return (ARCHIVE_OK); +} + + +/* private routines */ +static void +xstrftime(struct archive_string *as, const char *fmt, time_t t) +{ +/** like strftime(3) but for time_t objects */ + struct tm *rt; +#if defined(HAVE_GMTIME_R) || defined(HAVE__GMTIME64_S) + struct tm timeHere; +#endif +#if defined(HAVE__GMTIME64_S) + errno_t terr; + __time64_t tmptime; +#endif + char strtime[100]; + size_t len; + +#ifdef HAVE_GMTIME_R + if ((rt = gmtime_r(&t, &timeHere)) == NULL) + return; +#elif defined(HAVE__GMTIME64_S) + tmptime = t; + terr = _gmtime64_s(&timeHere, &tmptime); + if (terr) + rt = NULL; + else + rt = &timeHere; +#else + if ((rt = gmtime(&t)) == NULL) + return; +#endif + /* leave the hard yacker to our role model strftime() */ + len = strftime(strtime, sizeof(strtime)-1, fmt, rt); + archive_strncat(as, strtime, len); +} + +static ssize_t +_popul_ehdr(struct archive_string *tgt, size_t tsz, warc_essential_hdr_t hdr) +{ + static const char _ver[] = "WARC/1.0\r\n"; + static const char * const _typ[LAST_WT] = { + NULL, "warcinfo", "metadata", "resource", NULL + }; + char std_uuid[48U]; + + if (hdr.type == WT_NONE || hdr.type > WT_RSRC) { + /* brilliant, how exactly did we get here? */ + return -1; + } + + archive_strcpy(tgt, _ver); + + archive_string_sprintf(tgt, "WARC-Type: %s\r\n", _typ[hdr.type]); + + if (hdr.tgturi != NULL) { + /* check if there's a xyz:// */ + static const char _uri[] = ""; + static const char _fil[] = "file://"; + const char *u; + char *chk = strchr(hdr.tgturi, ':'); + + if (chk != NULL && chk[1U] == '/' && chk[2U] == '/') { + /* yep, it's definitely a URI */ + u = _uri; + } else { + /* hm, best to prepend file:// then */ + u = _fil; + } + archive_string_sprintf(tgt, + "WARC-Target-URI: %s%s\r\n", u, hdr.tgturi); + } + + /* record time is usually when the http is sent off, + * just treat the archive writing as such for a moment */ + xstrftime(tgt, "WARC-Date: %Y-%m-%dT%H:%M:%SZ\r\n", hdr.rtime); + + /* while we're at it, record the mtime */ + xstrftime(tgt, "Last-Modified: %Y-%m-%dT%H:%M:%SZ\r\n", hdr.mtime); + + if (hdr.recid == NULL) { + /* generate one, grrrr */ + warc_uuid_t u; + + _gen_uuid(&u); + /* Unfortunately, archive_string_sprintf does not + * handle the minimum number following '%'. + * So we have to use snprintf function here instead + * of archive_string_snprintf function. */ +#if defined(_WIN32) && !defined(__CYGWIN__) && !( defined(_MSC_VER) && _MSC_VER >= 1900) +#define snprintf _snprintf +#endif + snprintf( + std_uuid, sizeof(std_uuid), + "<urn:uuid:%08x-%04x-%04x-%04x-%04x%08x>", + u.u[0U], + u.u[1U] >> 16U, u.u[1U] & 0xffffU, + u.u[2U] >> 16U, u.u[2U] & 0xffffU, + u.u[3U]); + hdr.recid = std_uuid; + } + + /* record-id is mandatory, fingers crossed we won't fail */ + archive_string_sprintf(tgt, "WARC-Record-ID: %s\r\n", hdr.recid); + + if (hdr.cnttyp != NULL) { + archive_string_sprintf(tgt, "Content-Type: %s\r\n", hdr.cnttyp); + } + + /* next one is mandatory */ + archive_string_sprintf(tgt, "Content-Length: %ju\r\n", (uintmax_t)hdr.cntlen); + /**/ + archive_strncat(tgt, "\r\n", 2); + + return (archive_strlen(tgt) >= tsz)? -1: (ssize_t)archive_strlen(tgt); +} + +static int +_gen_uuid(warc_uuid_t *tgt) +{ + archive_random(tgt->u, sizeof(tgt->u)); + /* obey uuid version 4 rules */ + tgt->u[1U] &= 0xffff0fffU; + tgt->u[1U] |= 0x4000U; + tgt->u[2U] &= 0x3fffffffU; + tgt->u[2U] |= 0x80000000U; + return 0; +} + +/* archive_write_set_format_warc.c ends here */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_xar.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_xar.c new file mode 100644 index 0000000000..e1c7f3a96d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_xar.c @@ -0,0 +1,3259 @@ +/*- + * Copyright (c) 2010-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif +#include <stdlib.h> +#if HAVE_LIBXML_XMLWRITER_H +#include <libxml/xmlwriter.h> +#endif +#ifdef HAVE_BZLIB_H +#include <bzlib.h> +#endif +#if HAVE_LZMA_H +#include <lzma.h> +#endif +#ifdef HAVE_ZLIB_H +#include <zlib.h> +#endif + +#include "archive.h" +#include "archive_digest_private.h" +#include "archive_endian.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_private.h" +#include "archive_rb.h" +#include "archive_string.h" +#include "archive_write_private.h" + +/* + * Differences to xar utility. + * - Subdocument is not supported yet. + * - ACL is not supported yet. + * - When writing an XML element <link type="<file-type>">, <file-type> + * which is a file type a symbolic link is referencing is always marked + * as "broken". Xar utility uses stat(2) to get the file type, but, in + * libarchive format writer, we should not use it; if it is needed, we + * should get about it at archive_read_disk.c. + * - It is possible to appear both <flags> and <ext2> elements. + * Xar utility generates <flags> on BSD platform and <ext2> on Linux + * platform. + * + */ + +#if !(defined(HAVE_LIBXML_XMLWRITER_H) && defined(LIBXML_VERSION) &&\ + LIBXML_VERSION >= 20703) ||\ + !defined(HAVE_ZLIB_H) || \ + !defined(ARCHIVE_HAS_MD5) || !defined(ARCHIVE_HAS_SHA1) +/* + * xar needs several external libraries. + * o libxml2 + * o openssl or MD5/SHA1 hash function + * o zlib + * o bzlib2 (option) + * o liblzma (option) + */ +int +archive_write_set_format_xar(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Xar not supported on this platform"); + return (ARCHIVE_WARN); +} + +#else /* Support xar format */ + +/*#define DEBUG_PRINT_TOC 1 */ + +#define BAD_CAST_CONST (const xmlChar *) + +#define HEADER_MAGIC 0x78617221 +#define HEADER_SIZE 28 +#define HEADER_VERSION 1 + +enum sumalg { + CKSUM_NONE = 0, + CKSUM_SHA1 = 1, + CKSUM_MD5 = 2 +}; + +#define MD5_SIZE 16 +#define SHA1_SIZE 20 +#define MAX_SUM_SIZE 20 +#define MD5_NAME "md5" +#define SHA1_NAME "sha1" + +enum enctype { + NONE, + GZIP, + BZIP2, + LZMA, + XZ, +}; + +struct chksumwork { + enum sumalg alg; +#ifdef ARCHIVE_HAS_MD5 + archive_md5_ctx md5ctx; +#endif +#ifdef ARCHIVE_HAS_SHA1 + archive_sha1_ctx sha1ctx; +#endif +}; + +enum la_zaction { + ARCHIVE_Z_FINISH, + ARCHIVE_Z_RUN +}; + +/* + * Universal zstream. + */ +struct la_zstream { + const unsigned char *next_in; + size_t avail_in; + uint64_t total_in; + + unsigned char *next_out; + size_t avail_out; + uint64_t total_out; + + int valid; + void *real_stream; + int (*code) (struct archive *a, + struct la_zstream *lastrm, + enum la_zaction action); + int (*end)(struct archive *a, + struct la_zstream *lastrm); +}; + +struct chksumval { + enum sumalg alg; + size_t len; + unsigned char val[MAX_SUM_SIZE]; +}; + +struct heap_data { + int id; + struct heap_data *next; + uint64_t temp_offset; + uint64_t length; /* archived size. */ + uint64_t size; /* extracted size. */ + enum enctype compression; + struct chksumval a_sum; /* archived checksum. */ + struct chksumval e_sum; /* extracted checksum. */ +}; + +struct file { + struct archive_rb_node rbnode; + + int id; + struct archive_entry *entry; + + struct archive_rb_tree rbtree; + struct file *next; + struct file *chnext; + struct file *hlnext; + /* For hardlinked files. + * Use only when archive_entry_nlink() > 1 */ + struct file *hardlink_target; + struct file *parent; /* parent directory entry */ + /* + * To manage sub directory files. + * We use 'chnext' (a member of struct file) to chain. + */ + struct { + struct file *first; + struct file **last; + } children; + + /* For making a directory tree. */ + struct archive_string parentdir; + struct archive_string basename; + struct archive_string symlink; + + int ea_idx; + struct { + struct heap_data *first; + struct heap_data **last; + } xattr; + struct heap_data data; + struct archive_string script; + + signed int virtual:1; + signed int dir:1; +}; + +struct hardlink { + struct archive_rb_node rbnode; + int nlink; + struct { + struct file *first; + struct file **last; + } file_list; +}; + +struct xar { + int temp_fd; + uint64_t temp_offset; + + int file_idx; + struct file *root; + struct file *cur_dirent; + struct archive_string cur_dirstr; + struct file *cur_file; + uint64_t bytes_remaining; + struct archive_string tstr; + struct archive_string vstr; + + enum sumalg opt_toc_sumalg; + enum sumalg opt_sumalg; + enum enctype opt_compression; + int opt_compression_level; + uint32_t opt_threads; + + struct chksumwork a_sumwrk; /* archived checksum. */ + struct chksumwork e_sumwrk; /* extracted checksum. */ + struct la_zstream stream; + struct archive_string_conv *sconv; + /* + * Compressed data buffer. + */ + unsigned char wbuff[1024 * 64]; + size_t wbuff_remaining; + + struct heap_data toc; + /* + * The list of all file entries is used to manage struct file + * objects. + * We use 'next' (a member of struct file) to chain. + */ + struct { + struct file *first; + struct file **last; + } file_list; + /* + * The list of hard-linked file entries. + * We use 'hlnext' (a member of struct file) to chain. + */ + struct archive_rb_tree hardlink_rbtree; +}; + +static int xar_options(struct archive_write *, + const char *, const char *); +static int xar_write_header(struct archive_write *, + struct archive_entry *); +static ssize_t xar_write_data(struct archive_write *, + const void *, size_t); +static int xar_finish_entry(struct archive_write *); +static int xar_close(struct archive_write *); +static int xar_free(struct archive_write *); + +static struct file *file_new(struct archive_write *a, struct archive_entry *); +static void file_free(struct file *); +static struct file *file_create_virtual_dir(struct archive_write *a, struct xar *, + const char *); +static int file_add_child_tail(struct file *, struct file *); +static struct file *file_find_child(struct file *, const char *); +static int file_gen_utility_names(struct archive_write *, + struct file *); +static int get_path_component(char *, int, const char *); +static int file_tree(struct archive_write *, struct file **); +static void file_register(struct xar *, struct file *); +static void file_init_register(struct xar *); +static void file_free_register(struct xar *); +static int file_register_hardlink(struct archive_write *, + struct file *); +static void file_connect_hardlink_files(struct xar *); +static void file_init_hardlinks(struct xar *); +static void file_free_hardlinks(struct xar *); + +static void checksum_init(struct chksumwork *, enum sumalg); +static void checksum_update(struct chksumwork *, const void *, size_t); +static void checksum_final(struct chksumwork *, struct chksumval *); +static int compression_init_encoder_gzip(struct archive *, + struct la_zstream *, int, int); +static int compression_code_gzip(struct archive *, + struct la_zstream *, enum la_zaction); +static int compression_end_gzip(struct archive *, struct la_zstream *); +static int compression_init_encoder_bzip2(struct archive *, + struct la_zstream *, int); +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) +static int compression_code_bzip2(struct archive *, + struct la_zstream *, enum la_zaction); +static int compression_end_bzip2(struct archive *, struct la_zstream *); +#endif +static int compression_init_encoder_lzma(struct archive *, + struct la_zstream *, int); +static int compression_init_encoder_xz(struct archive *, + struct la_zstream *, int, int); +#if defined(HAVE_LZMA_H) +static int compression_code_lzma(struct archive *, + struct la_zstream *, enum la_zaction); +static int compression_end_lzma(struct archive *, struct la_zstream *); +#endif +static int xar_compression_init_encoder(struct archive_write *); +static int compression_code(struct archive *, + struct la_zstream *, enum la_zaction); +static int compression_end(struct archive *, + struct la_zstream *); +static int save_xattrs(struct archive_write *, struct file *); +static int getalgsize(enum sumalg); +static const char *getalgname(enum sumalg); + +int +archive_write_set_format_xar(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct xar *xar; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_xar"); + + /* If another format was already registered, unregister it. */ + if (a->format_free != NULL) + (a->format_free)(a); + + xar = calloc(1, sizeof(*xar)); + if (xar == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate xar data"); + return (ARCHIVE_FATAL); + } + xar->temp_fd = -1; + file_init_register(xar); + file_init_hardlinks(xar); + archive_string_init(&(xar->tstr)); + archive_string_init(&(xar->vstr)); + + /* + * Create the root directory. + */ + xar->root = file_create_virtual_dir(a, xar, ""); + if (xar->root == NULL) { + free(xar); + archive_set_error(&a->archive, ENOMEM, + "Can't allocate xar data"); + return (ARCHIVE_FATAL); + } + xar->root->parent = xar->root; + file_register(xar, xar->root); + xar->cur_dirent = xar->root; + archive_string_init(&(xar->cur_dirstr)); + archive_string_ensure(&(xar->cur_dirstr), 1); + xar->cur_dirstr.s[0] = 0; + + /* + * Initialize option. + */ + /* Set default checksum type. */ + xar->opt_toc_sumalg = CKSUM_SHA1; + xar->opt_sumalg = CKSUM_SHA1; + /* Set default compression type, level, and number of threads. */ + xar->opt_compression = GZIP; + xar->opt_compression_level = 6; + xar->opt_threads = 1; + + a->format_data = xar; + + a->format_name = "xar"; + a->format_options = xar_options; + a->format_write_header = xar_write_header; + a->format_write_data = xar_write_data; + a->format_finish_entry = xar_finish_entry; + a->format_close = xar_close; + a->format_free = xar_free; + a->archive.archive_format = ARCHIVE_FORMAT_XAR; + a->archive.archive_format_name = "xar"; + + return (ARCHIVE_OK); +} + +static int +xar_options(struct archive_write *a, const char *key, const char *value) +{ + struct xar *xar; + + xar = (struct xar *)a->format_data; + + if (strcmp(key, "checksum") == 0) { + if (value == NULL) + xar->opt_sumalg = CKSUM_NONE; + else if (strcmp(value, "none") == 0) + xar->opt_sumalg = CKSUM_NONE; + else if (strcmp(value, "sha1") == 0) + xar->opt_sumalg = CKSUM_SHA1; + else if (strcmp(value, "md5") == 0) + xar->opt_sumalg = CKSUM_MD5; + else { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "Unknown checksum name: `%s'", + value); + return (ARCHIVE_FAILED); + } + return (ARCHIVE_OK); + } + if (strcmp(key, "compression") == 0) { + const char *name = NULL; + + if (value == NULL) + xar->opt_compression = NONE; + else if (strcmp(value, "none") == 0) + xar->opt_compression = NONE; + else if (strcmp(value, "gzip") == 0) + xar->opt_compression = GZIP; + else if (strcmp(value, "bzip2") == 0) +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) + xar->opt_compression = BZIP2; +#else + name = "bzip2"; +#endif + else if (strcmp(value, "lzma") == 0) +#if HAVE_LZMA_H + xar->opt_compression = LZMA; +#else + name = "lzma"; +#endif + else if (strcmp(value, "xz") == 0) +#if HAVE_LZMA_H + xar->opt_compression = XZ; +#else + name = "xz"; +#endif + else { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "Unknown compression name: `%s'", + value); + return (ARCHIVE_FAILED); + } + if (name != NULL) { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "`%s' compression not supported " + "on this platform", + name); + return (ARCHIVE_FAILED); + } + return (ARCHIVE_OK); + } + if (strcmp(key, "compression-level") == 0) { + if (value == NULL || + !(value[0] >= '0' && value[0] <= '9') || + value[1] != '\0') { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "Illegal value `%s'", + value); + return (ARCHIVE_FAILED); + } + xar->opt_compression_level = value[0] - '0'; + return (ARCHIVE_OK); + } + if (strcmp(key, "toc-checksum") == 0) { + if (value == NULL) + xar->opt_toc_sumalg = CKSUM_NONE; + else if (strcmp(value, "none") == 0) + xar->opt_toc_sumalg = CKSUM_NONE; + else if (strcmp(value, "sha1") == 0) + xar->opt_toc_sumalg = CKSUM_SHA1; + else if (strcmp(value, "md5") == 0) + xar->opt_toc_sumalg = CKSUM_MD5; + else { + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "Unknown checksum name: `%s'", + value); + return (ARCHIVE_FAILED); + } + return (ARCHIVE_OK); + } + if (strcmp(key, "threads") == 0) { + char *endptr; + + if (value == NULL) + return (ARCHIVE_FAILED); + errno = 0; + xar->opt_threads = (int)strtoul(value, &endptr, 10); + if (errno != 0 || *endptr != '\0') { + xar->opt_threads = 1; + archive_set_error(&(a->archive), + ARCHIVE_ERRNO_MISC, + "Illegal value `%s'", + value); + return (ARCHIVE_FAILED); + } + if (xar->opt_threads == 0) { +#ifdef HAVE_LZMA_STREAM_ENCODER_MT + xar->opt_threads = lzma_cputhreads(); +#else + xar->opt_threads = 1; +#endif + } + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +static int +xar_write_header(struct archive_write *a, struct archive_entry *entry) +{ + struct xar *xar; + struct file *file; + struct archive_entry *file_entry; + int r, r2; + + xar = (struct xar *)a->format_data; + xar->cur_file = NULL; + xar->bytes_remaining = 0; + + if (xar->sconv == NULL) { + xar->sconv = archive_string_conversion_to_charset( + &a->archive, "UTF-8", 1); + if (xar->sconv == NULL) + return (ARCHIVE_FATAL); + } + + file = file_new(a, entry); + if (file == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate data"); + return (ARCHIVE_FATAL); + } + r2 = file_gen_utility_names(a, file); + if (r2 < ARCHIVE_WARN) + return (r2); + + /* + * Ignore a path which looks like the top of directory name + * since we have already made the root directory of an Xar archive. + */ + if (archive_strlen(&(file->parentdir)) == 0 && + archive_strlen(&(file->basename)) == 0) { + file_free(file); + return (r2); + } + + /* Add entry into tree */ + file_entry = file->entry; + r = file_tree(a, &file); + if (r != ARCHIVE_OK) + return (r); + /* There is the same file in tree and + * the current file is older than the file in tree. + * So we don't need the current file data anymore. */ + if (file->entry != file_entry) + return (r2); + if (file->id == 0) + file_register(xar, file); + + /* A virtual file, which is a directory, does not have + * any contents and we won't store it into a archive + * file other than its name. */ + if (file->virtual) + return (r2); + + /* + * Prepare to save the contents of the file. + */ + if (xar->temp_fd == -1) { + int algsize; + xar->temp_offset = 0; + xar->temp_fd = __archive_mktemp(NULL); + if (xar->temp_fd < 0) { + archive_set_error(&a->archive, errno, + "Couldn't create temporary file"); + return (ARCHIVE_FATAL); + } + algsize = getalgsize(xar->opt_toc_sumalg); + if (algsize > 0) { + if (lseek(xar->temp_fd, algsize, SEEK_SET) < 0) { + archive_set_error(&(a->archive), errno, + "lseek failed"); + return (ARCHIVE_FATAL); + } + xar->temp_offset = algsize; + } + } + + if (archive_entry_hardlink(file->entry) == NULL) { + r = save_xattrs(a, file); + if (r != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + + /* Non regular files contents are unneeded to be saved to + * a temporary file. */ + if (archive_entry_filetype(file->entry) != AE_IFREG) + return (r2); + + /* + * Set the current file to cur_file to read its contents. + */ + xar->cur_file = file; + + if (archive_entry_nlink(file->entry) > 1) { + r = file_register_hardlink(a, file); + if (r != ARCHIVE_OK) + return (r); + if (archive_entry_hardlink(file->entry) != NULL) { + archive_entry_unset_size(file->entry); + return (r2); + } + } + + /* Save a offset of current file in temporary file. */ + file->data.temp_offset = xar->temp_offset; + file->data.size = archive_entry_size(file->entry); + file->data.compression = xar->opt_compression; + xar->bytes_remaining = archive_entry_size(file->entry); + checksum_init(&(xar->a_sumwrk), xar->opt_sumalg); + checksum_init(&(xar->e_sumwrk), xar->opt_sumalg); + r = xar_compression_init_encoder(a); + + if (r != ARCHIVE_OK) + return (r); + else + return (r2); +} + +static int +write_to_temp(struct archive_write *a, const void *buff, size_t s) +{ + struct xar *xar; + const unsigned char *p; + ssize_t ws; + + xar = (struct xar *)a->format_data; + p = (const unsigned char *)buff; + while (s) { + ws = write(xar->temp_fd, p, s); + if (ws < 0) { + archive_set_error(&(a->archive), errno, + "fwrite function failed"); + return (ARCHIVE_FATAL); + } + s -= ws; + p += ws; + xar->temp_offset += ws; + } + return (ARCHIVE_OK); +} + +static ssize_t +xar_write_data(struct archive_write *a, const void *buff, size_t s) +{ + struct xar *xar; + enum la_zaction run; + size_t size = 0; + size_t rsize; + int r; + + xar = (struct xar *)a->format_data; + + if (s > xar->bytes_remaining) + s = (size_t)xar->bytes_remaining; + if (s == 0 || xar->cur_file == NULL) + return (0); + if (xar->cur_file->data.compression == NONE) { + checksum_update(&(xar->e_sumwrk), buff, s); + checksum_update(&(xar->a_sumwrk), buff, s); + size = rsize = s; + } else { + xar->stream.next_in = (const unsigned char *)buff; + xar->stream.avail_in = s; + if (xar->bytes_remaining > s) + run = ARCHIVE_Z_RUN; + else + run = ARCHIVE_Z_FINISH; + /* Compress file data. */ + for (;;) { + r = compression_code(&(a->archive), &(xar->stream), + run); + if (r != ARCHIVE_OK && r != ARCHIVE_EOF) + return (ARCHIVE_FATAL); + if (xar->stream.avail_out == 0 || + run == ARCHIVE_Z_FINISH) { + size = sizeof(xar->wbuff) - + xar->stream.avail_out; + checksum_update(&(xar->a_sumwrk), xar->wbuff, + size); + xar->cur_file->data.length += size; + if (write_to_temp(a, xar->wbuff, + size) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + if (r == ARCHIVE_OK) { + /* Output buffer was full */ + xar->stream.next_out = xar->wbuff; + xar->stream.avail_out = + sizeof(xar->wbuff); + } else { + /* ARCHIVE_EOF - We are done */ + break; + } + } else { + /* Compressor wants more input */ + break; + } + } + rsize = s - xar->stream.avail_in; + checksum_update(&(xar->e_sumwrk), buff, rsize); + } +#if !defined(_WIN32) || defined(__CYGWIN__) + if (xar->bytes_remaining == + (uint64_t)archive_entry_size(xar->cur_file->entry)) { + /* + * Get the path of a shell script if so. + */ + const unsigned char *b = (const unsigned char *)buff; + + archive_string_empty(&(xar->cur_file->script)); + if (rsize > 2 && b[0] == '#' && b[1] == '!') { + size_t i, end, off; + + off = 2; + if (b[off] == ' ') + off++; +#ifdef PATH_MAX + if ((rsize - off) > PATH_MAX) + end = off + PATH_MAX; + else +#endif + end = rsize; + /* Find the end of a script path. */ + for (i = off; i < end && b[i] != '\0' && + b[i] != '\n' && b[i] != '\r' && + b[i] != ' ' && b[i] != '\t'; i++) + ; + archive_strncpy(&(xar->cur_file->script), b + off, + i - off); + } + } +#endif + + if (xar->cur_file->data.compression == NONE) { + if (write_to_temp(a, buff, size) != ARCHIVE_OK) + return (ARCHIVE_FATAL); + xar->cur_file->data.length += size; + } + xar->bytes_remaining -= rsize; + + return (rsize); +} + +static int +xar_finish_entry(struct archive_write *a) +{ + struct xar *xar; + struct file *file; + size_t s; + ssize_t w; + + xar = (struct xar *)a->format_data; + if (xar->cur_file == NULL) + return (ARCHIVE_OK); + + while (xar->bytes_remaining > 0) { + s = (size_t)xar->bytes_remaining; + if (s > a->null_length) + s = a->null_length; + w = xar_write_data(a, a->nulls, s); + if (w > 0) + xar->bytes_remaining -= w; + else + return (w); + } + file = xar->cur_file; + checksum_final(&(xar->e_sumwrk), &(file->data.e_sum)); + checksum_final(&(xar->a_sumwrk), &(file->data.a_sum)); + xar->cur_file = NULL; + + return (ARCHIVE_OK); +} + +static int +xmlwrite_string_attr(struct archive_write *a, xmlTextWriterPtr writer, + const char *key, const char *value, + const char *attrkey, const char *attrvalue) +{ + int r; + + r = xmlTextWriterStartElement(writer, BAD_CAST_CONST(key)); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterStartElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + if (attrkey != NULL && attrvalue != NULL) { + r = xmlTextWriterWriteAttribute(writer, + BAD_CAST_CONST(attrkey), BAD_CAST_CONST(attrvalue)); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterWriteAttribute() failed: %d", r); + return (ARCHIVE_FATAL); + } + } + if (value != NULL) { + r = xmlTextWriterWriteString(writer, BAD_CAST_CONST(value)); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterWriteString() failed: %d", r); + return (ARCHIVE_FATAL); + } + } + r = xmlTextWriterEndElement(writer); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterEndElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_OK); +} + +static int +xmlwrite_string(struct archive_write *a, xmlTextWriterPtr writer, + const char *key, const char *value) +{ + int r; + + if (value == NULL) + return (ARCHIVE_OK); + + r = xmlTextWriterStartElement(writer, BAD_CAST_CONST(key)); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterStartElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + if (value != NULL) { + r = xmlTextWriterWriteString(writer, BAD_CAST_CONST(value)); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterWriteString() failed: %d", r); + return (ARCHIVE_FATAL); + } + } + r = xmlTextWriterEndElement(writer); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterEndElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_OK); +} + +static int +xmlwrite_fstring(struct archive_write *a, xmlTextWriterPtr writer, + const char *key, const char *fmt, ...) +{ + struct xar *xar; + va_list ap; + + xar = (struct xar *)a->format_data; + va_start(ap, fmt); + archive_string_empty(&xar->vstr); + archive_string_vsprintf(&xar->vstr, fmt, ap); + va_end(ap); + return (xmlwrite_string(a, writer, key, xar->vstr.s)); +} + +static int +xmlwrite_time(struct archive_write *a, xmlTextWriterPtr writer, + const char *key, time_t t, int z) +{ + char timestr[100]; + struct tm tm; +#if defined(HAVE__GMTIME64_S) + __time64_t tmptime; +#endif + +#if defined(HAVE_GMTIME_R) + gmtime_r(&t, &tm); +#elif defined(HAVE__GMTIME64_S) + tmptime = t; + _gmtime64_s(&tm, &tmptime); +#else + memcpy(&tm, gmtime(&t), sizeof(tm)); +#endif + memset(×tr, 0, sizeof(timestr)); + /* Do not use %F and %T for portability. */ + strftime(timestr, sizeof(timestr), "%Y-%m-%dT%H:%M:%S", &tm); + if (z) + strcat(timestr, "Z"); + return (xmlwrite_string(a, writer, key, timestr)); +} + +static int +xmlwrite_mode(struct archive_write *a, xmlTextWriterPtr writer, + const char *key, mode_t mode) +{ + char ms[5]; + + ms[0] = '0'; + ms[1] = '0' + ((mode >> 6) & 07); + ms[2] = '0' + ((mode >> 3) & 07); + ms[3] = '0' + (mode & 07); + ms[4] = '\0'; + + return (xmlwrite_string(a, writer, key, ms)); +} + +static int +xmlwrite_sum(struct archive_write *a, xmlTextWriterPtr writer, + const char *key, struct chksumval *sum) +{ + const char *algname; + int algsize; + char buff[MAX_SUM_SIZE*2 + 1]; + char *p; + unsigned char *s; + int i, r; + + if (sum->len > 0) { + algname = getalgname(sum->alg); + algsize = getalgsize(sum->alg); + if (algname != NULL) { + const char *hex = "0123456789abcdef"; + p = buff; + s = sum->val; + for (i = 0; i < algsize; i++) { + *p++ = hex[(*s >> 4)]; + *p++ = hex[(*s & 0x0f)]; + s++; + } + *p = '\0'; + r = xmlwrite_string_attr(a, writer, + key, buff, + "style", algname); + if (r < 0) + return (ARCHIVE_FATAL); + } + } + return (ARCHIVE_OK); +} + +static int +xmlwrite_heap(struct archive_write *a, xmlTextWriterPtr writer, + struct heap_data *heap) +{ + const char *encname; + int r; + + r = xmlwrite_fstring(a, writer, "length", "%ju", heap->length); + if (r < 0) + return (ARCHIVE_FATAL); + r = xmlwrite_fstring(a, writer, "offset", "%ju", heap->temp_offset); + if (r < 0) + return (ARCHIVE_FATAL); + r = xmlwrite_fstring(a, writer, "size", "%ju", heap->size); + if (r < 0) + return (ARCHIVE_FATAL); + switch (heap->compression) { + case GZIP: + encname = "application/x-gzip"; break; + case BZIP2: + encname = "application/x-bzip2"; break; + case LZMA: + encname = "application/x-lzma"; break; + case XZ: + encname = "application/x-xz"; break; + default: + encname = "application/octet-stream"; break; + } + r = xmlwrite_string_attr(a, writer, "encoding", NULL, + "style", encname); + if (r < 0) + return (ARCHIVE_FATAL); + r = xmlwrite_sum(a, writer, "archived-checksum", &(heap->a_sum)); + if (r < 0) + return (ARCHIVE_FATAL); + r = xmlwrite_sum(a, writer, "extracted-checksum", &(heap->e_sum)); + if (r < 0) + return (ARCHIVE_FATAL); + return (ARCHIVE_OK); +} + +/* + * xar utility records fflags as following xml elements: + * <flags> + * <UserNoDump/> + * ..... + * </flags> + * or + * <ext2> + * <NoDump/> + * ..... + * </ext2> + * If xar is running on BSD platform, records <flags>..</flags>; + * if xar is running on linux platform, records <ext2>..</ext2>; + * otherwise does not record. + * + * Our implements records both <flags> and <ext2> if it's necessary. + */ +static int +make_fflags_entry(struct archive_write *a, xmlTextWriterPtr writer, + const char *element, const char *fflags_text) +{ + static const struct flagentry { + const char *name; + const char *xarname; + } + flagbsd[] = { + { "sappnd", "SystemAppend"}, + { "sappend", "SystemAppend"}, + { "arch", "SystemArchived"}, + { "archived", "SystemArchived"}, + { "schg", "SystemImmutable"}, + { "schange", "SystemImmutable"}, + { "simmutable", "SystemImmutable"}, + { "nosunlnk", "SystemNoUnlink"}, + { "nosunlink", "SystemNoUnlink"}, + { "snapshot", "SystemSnapshot"}, + { "uappnd", "UserAppend"}, + { "uappend", "UserAppend"}, + { "uchg", "UserImmutable"}, + { "uchange", "UserImmutable"}, + { "uimmutable", "UserImmutable"}, + { "nodump", "UserNoDump"}, + { "noopaque", "UserOpaque"}, + { "nouunlnk", "UserNoUnlink"}, + { "nouunlink", "UserNoUnlink"}, + { NULL, NULL} + }, + flagext2[] = { + { "sappnd", "AppendOnly"}, + { "sappend", "AppendOnly"}, + { "schg", "Immutable"}, + { "schange", "Immutable"}, + { "simmutable", "Immutable"}, + { "nodump", "NoDump"}, + { "nouunlnk", "Undelete"}, + { "nouunlink", "Undelete"}, + { "btree", "BTree"}, + { "comperr", "CompError"}, + { "compress", "Compress"}, + { "noatime", "NoAtime"}, + { "compdirty", "CompDirty"}, + { "comprblk", "CompBlock"}, + { "dirsync", "DirSync"}, + { "hashidx", "HashIndexed"}, + { "imagic", "iMagic"}, + { "journal", "Journaled"}, + { "securedeletion", "SecureDeletion"}, + { "sync", "Synchronous"}, + { "notail", "NoTail"}, + { "topdir", "TopDir"}, + { "reserved", "Reserved"}, + { NULL, NULL} + }; + const struct flagentry *fe, *flagentry; +#define FLAGENTRY_MAXSIZE ((sizeof(flagbsd)+sizeof(flagext2))/sizeof(flagbsd)) + const struct flagentry *avail[FLAGENTRY_MAXSIZE]; + const char *p; + int i, n, r; + + if (strcmp(element, "ext2") == 0) + flagentry = flagext2; + else + flagentry = flagbsd; + n = 0; + p = fflags_text; + do { + const char *cp; + + cp = strchr(p, ','); + if (cp == NULL) + cp = p + strlen(p); + + for (fe = flagentry; fe->name != NULL; fe++) { + if (fe->name[cp - p] != '\0' + || p[0] != fe->name[0]) + continue; + if (strncmp(p, fe->name, cp - p) == 0) { + avail[n++] = fe; + break; + } + } + if (*cp == ',') + p = cp + 1; + else + p = NULL; + } while (p != NULL); + + if (n > 0) { + r = xmlTextWriterStartElement(writer, BAD_CAST_CONST(element)); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterStartElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + for (i = 0; i < n; i++) { + r = xmlwrite_string(a, writer, + avail[i]->xarname, NULL); + if (r != ARCHIVE_OK) + return (r); + } + + r = xmlTextWriterEndElement(writer); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterEndElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + } + return (ARCHIVE_OK); +} + +static int +make_file_entry(struct archive_write *a, xmlTextWriterPtr writer, + struct file *file) +{ + struct xar *xar; + const char *filetype, *filelink, *fflags; + struct archive_string linkto; + struct heap_data *heap; + unsigned char *tmp; + const char *p; + size_t len; + int r, r2, l, ll; + + xar = (struct xar *)a->format_data; + r2 = ARCHIVE_OK; + + /* + * Make a file name entry, "<name>". + */ + l = ll = archive_strlen(&(file->basename)); + tmp = malloc(l); + if (tmp == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + r = UTF8Toisolat1(tmp, &l, BAD_CAST(file->basename.s), &ll); + free(tmp); + if (r < 0) { + r = xmlTextWriterStartElement(writer, BAD_CAST("name")); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterStartElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + r = xmlTextWriterWriteAttribute(writer, + BAD_CAST("enctype"), BAD_CAST("base64")); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterWriteAttribute() failed: %d", r); + return (ARCHIVE_FATAL); + } + r = xmlTextWriterWriteBase64(writer, file->basename.s, + 0, archive_strlen(&(file->basename))); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterWriteBase64() failed: %d", r); + return (ARCHIVE_FATAL); + } + r = xmlTextWriterEndElement(writer); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterEndElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + } else { + r = xmlwrite_string(a, writer, "name", file->basename.s); + if (r < 0) + return (ARCHIVE_FATAL); + } + + /* + * Make a file type entry, "<type>". + */ + filelink = NULL; + archive_string_init(&linkto); + switch (archive_entry_filetype(file->entry)) { + case AE_IFDIR: + filetype = "directory"; break; + case AE_IFLNK: + filetype = "symlink"; break; + case AE_IFCHR: + filetype = "character special"; break; + case AE_IFBLK: + filetype = "block special"; break; + case AE_IFSOCK: + filetype = "socket"; break; + case AE_IFIFO: + filetype = "fifo"; break; + case AE_IFREG: + default: + if (file->hardlink_target != NULL) { + filetype = "hardlink"; + filelink = "link"; + if (file->hardlink_target == file) + archive_strcpy(&linkto, "original"); + else + archive_string_sprintf(&linkto, "%d", + file->hardlink_target->id); + } else + filetype = "file"; + break; + } + r = xmlwrite_string_attr(a, writer, "type", filetype, + filelink, linkto.s); + archive_string_free(&linkto); + if (r < 0) + return (ARCHIVE_FATAL); + + /* + * On a virtual directory, we record "name" and "type" only. + */ + if (file->virtual) + return (ARCHIVE_OK); + + switch (archive_entry_filetype(file->entry)) { + case AE_IFLNK: + /* + * xar utility has checked a file type, which + * a symbolic-link file has referenced. + * For example: + * <link type="directory">../ref/</link> + * The symlink target file is "../ref/" and its + * file type is a directory. + * + * <link type="file">../f</link> + * The symlink target file is "../f" and its + * file type is a regular file. + * + * But our implementation cannot do it, and then we + * always record that a attribute "type" is "broken", + * for example: + * <link type="broken">foo/bar</link> + * It means "foo/bar" is not reachable. + */ + r = xmlwrite_string_attr(a, writer, "link", + file->symlink.s, + "type", "broken"); + if (r < 0) + return (ARCHIVE_FATAL); + break; + case AE_IFCHR: + case AE_IFBLK: + r = xmlTextWriterStartElement(writer, BAD_CAST("device")); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterStartElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + r = xmlwrite_fstring(a, writer, "major", + "%d", archive_entry_rdevmajor(file->entry)); + if (r < 0) + return (ARCHIVE_FATAL); + r = xmlwrite_fstring(a, writer, "minor", + "%d", archive_entry_rdevminor(file->entry)); + if (r < 0) + return (ARCHIVE_FATAL); + r = xmlTextWriterEndElement(writer); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterEndElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + break; + default: + break; + } + + /* + * Make a inode entry, "<inode>". + */ + r = xmlwrite_fstring(a, writer, "inode", + "%jd", archive_entry_ino64(file->entry)); + if (r < 0) + return (ARCHIVE_FATAL); + if (archive_entry_dev(file->entry) != 0) { + r = xmlwrite_fstring(a, writer, "deviceno", + "%d", archive_entry_dev(file->entry)); + if (r < 0) + return (ARCHIVE_FATAL); + } + + /* + * Make a file mode entry, "<mode>". + */ + r = xmlwrite_mode(a, writer, "mode", + archive_entry_mode(file->entry)); + if (r < 0) + return (ARCHIVE_FATAL); + + /* + * Make a user entry, "<uid>" and "<user>. + */ + r = xmlwrite_fstring(a, writer, "uid", + "%d", archive_entry_uid(file->entry)); + if (r < 0) + return (ARCHIVE_FATAL); + r = archive_entry_uname_l(file->entry, &p, &len, xar->sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Uname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate uname '%s' to UTF-8", + archive_entry_uname(file->entry)); + r2 = ARCHIVE_WARN; + } + if (len > 0) { + r = xmlwrite_string(a, writer, "user", p); + if (r < 0) + return (ARCHIVE_FATAL); + } + + /* + * Make a group entry, "<gid>" and "<group>. + */ + r = xmlwrite_fstring(a, writer, "gid", + "%d", archive_entry_gid(file->entry)); + if (r < 0) + return (ARCHIVE_FATAL); + r = archive_entry_gname_l(file->entry, &p, &len, xar->sconv); + if (r != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Gname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate gname '%s' to UTF-8", + archive_entry_gname(file->entry)); + r2 = ARCHIVE_WARN; + } + if (len > 0) { + r = xmlwrite_string(a, writer, "group", p); + if (r < 0) + return (ARCHIVE_FATAL); + } + + /* + * Make a ctime entry, "<ctime>". + */ + if (archive_entry_ctime_is_set(file->entry)) { + r = xmlwrite_time(a, writer, "ctime", + archive_entry_ctime(file->entry), 1); + if (r < 0) + return (ARCHIVE_FATAL); + } + + /* + * Make a mtime entry, "<mtime>". + */ + if (archive_entry_mtime_is_set(file->entry)) { + r = xmlwrite_time(a, writer, "mtime", + archive_entry_mtime(file->entry), 1); + if (r < 0) + return (ARCHIVE_FATAL); + } + + /* + * Make a atime entry, "<atime>". + */ + if (archive_entry_atime_is_set(file->entry)) { + r = xmlwrite_time(a, writer, "atime", + archive_entry_atime(file->entry), 1); + if (r < 0) + return (ARCHIVE_FATAL); + } + + /* + * Make fflags entries, "<flags>" and "<ext2>". + */ + fflags = archive_entry_fflags_text(file->entry); + if (fflags != NULL) { + r = make_fflags_entry(a, writer, "flags", fflags); + if (r < 0) + return (r); + r = make_fflags_entry(a, writer, "ext2", fflags); + if (r < 0) + return (r); + } + + /* + * Make extended attribute entries, "<ea>". + */ + archive_entry_xattr_reset(file->entry); + for (heap = file->xattr.first; heap != NULL; heap = heap->next) { + const char *name; + const void *value; + size_t size; + + archive_entry_xattr_next(file->entry, + &name, &value, &size); + r = xmlTextWriterStartElement(writer, BAD_CAST("ea")); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterStartElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + r = xmlTextWriterWriteFormatAttribute(writer, + BAD_CAST("id"), "%d", heap->id); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterWriteAttribute() failed: %d", r); + return (ARCHIVE_FATAL); + } + r = xmlwrite_heap(a, writer, heap); + if (r < 0) + return (ARCHIVE_FATAL); + r = xmlwrite_string(a, writer, "name", name); + if (r < 0) + return (ARCHIVE_FATAL); + + r = xmlTextWriterEndElement(writer); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterEndElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + } + + /* + * Make a file data entry, "<data>". + */ + if (file->data.length > 0) { + r = xmlTextWriterStartElement(writer, BAD_CAST("data")); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterStartElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + + r = xmlwrite_heap(a, writer, &(file->data)); + if (r < 0) + return (ARCHIVE_FATAL); + + r = xmlTextWriterEndElement(writer); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterEndElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + } + + if (archive_strlen(&file->script) > 0) { + r = xmlTextWriterStartElement(writer, BAD_CAST("content")); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterStartElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + + r = xmlwrite_string(a, writer, + "interpreter", file->script.s); + if (r < 0) + return (ARCHIVE_FATAL); + + r = xmlwrite_string(a, writer, "type", "script"); + if (r < 0) + return (ARCHIVE_FATAL); + + r = xmlTextWriterEndElement(writer); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterEndElement() failed: %d", r); + return (ARCHIVE_FATAL); + } + } + + return (r2); +} + +/* + * Make the TOC + */ +static int +make_toc(struct archive_write *a) +{ + struct xar *xar; + struct file *np; + xmlBufferPtr bp; + xmlTextWriterPtr writer; + int algsize; + int r, ret; + + xar = (struct xar *)a->format_data; + + ret = ARCHIVE_FATAL; + + /* + * Initialize xml writer. + */ + writer = NULL; + bp = xmlBufferCreate(); + if (bp == NULL) { + archive_set_error(&a->archive, ENOMEM, + "xmlBufferCreate() " + "couldn't create xml buffer"); + goto exit_toc; + } + writer = xmlNewTextWriterMemory(bp, 0); + if (writer == NULL) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlNewTextWriterMemory() " + "couldn't create xml writer"); + goto exit_toc; + } + r = xmlTextWriterStartDocument(writer, "1.0", "UTF-8", NULL); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterStartDocument() failed: %d", r); + goto exit_toc; + } + r = xmlTextWriterSetIndent(writer, 4); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterSetIndent() failed: %d", r); + goto exit_toc; + } + + /* + * Start recording TOC + */ + r = xmlTextWriterStartElement(writer, BAD_CAST("xar")); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterStartElement() failed: %d", r); + goto exit_toc; + } + r = xmlTextWriterStartElement(writer, BAD_CAST("toc")); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterStartDocument() failed: %d", r); + goto exit_toc; + } + + /* + * Record the creation time of the archive file. + */ + r = xmlwrite_time(a, writer, "creation-time", time(NULL), 0); + if (r < 0) + goto exit_toc; + + /* + * Record the checksum value of TOC + */ + algsize = getalgsize(xar->opt_toc_sumalg); + if (algsize) { + /* + * Record TOC checksum + */ + r = xmlTextWriterStartElement(writer, BAD_CAST("checksum")); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterStartElement() failed: %d", r); + goto exit_toc; + } + r = xmlTextWriterWriteAttribute(writer, BAD_CAST("style"), + BAD_CAST_CONST(getalgname(xar->opt_toc_sumalg))); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterWriteAttribute() failed: %d", r); + goto exit_toc; + } + + /* + * Record the offset of the value of checksum of TOC + */ + r = xmlwrite_string(a, writer, "offset", "0"); + if (r < 0) + goto exit_toc; + + /* + * Record the size of the value of checksum of TOC + */ + r = xmlwrite_fstring(a, writer, "size", "%d", algsize); + if (r < 0) + goto exit_toc; + + r = xmlTextWriterEndElement(writer); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterEndElement() failed: %d", r); + goto exit_toc; + } + } + + np = xar->root; + do { + if (np != np->parent) { + r = make_file_entry(a, writer, np); + if (r != ARCHIVE_OK) + goto exit_toc; + } + + if (np->dir && np->children.first != NULL) { + /* Enter to sub directories. */ + np = np->children.first; + r = xmlTextWriterStartElement(writer, + BAD_CAST("file")); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterStartElement() " + "failed: %d", r); + goto exit_toc; + } + r = xmlTextWriterWriteFormatAttribute( + writer, BAD_CAST("id"), "%d", np->id); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterWriteAttribute() " + "failed: %d", r); + goto exit_toc; + } + continue; + } + while (np != np->parent) { + r = xmlTextWriterEndElement(writer); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterEndElement() " + "failed: %d", r); + goto exit_toc; + } + if (np->chnext == NULL) { + /* Return to the parent directory. */ + np = np->parent; + } else { + np = np->chnext; + r = xmlTextWriterStartElement(writer, + BAD_CAST("file")); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterStartElement() " + "failed: %d", r); + goto exit_toc; + } + r = xmlTextWriterWriteFormatAttribute( + writer, BAD_CAST("id"), "%d", np->id); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterWriteAttribute() " + "failed: %d", r); + goto exit_toc; + } + break; + } + } + } while (np != np->parent); + + r = xmlTextWriterEndDocument(writer); + if (r < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "xmlTextWriterEndDocument() failed: %d", r); + goto exit_toc; + } +#if DEBUG_PRINT_TOC + fprintf(stderr, "\n---TOC-- %d bytes --\n%s\n", + strlen((const char *)bp->content), bp->content); +#endif + + /* + * Compress the TOC and calculate the sum of the TOC. + */ + xar->toc.temp_offset = xar->temp_offset; + xar->toc.size = bp->use; + checksum_init(&(xar->a_sumwrk), xar->opt_toc_sumalg); + + r = compression_init_encoder_gzip(&(a->archive), + &(xar->stream), 6, 1); + if (r != ARCHIVE_OK) + goto exit_toc; + xar->stream.next_in = bp->content; + xar->stream.avail_in = bp->use; + xar->stream.total_in = 0; + xar->stream.next_out = xar->wbuff; + xar->stream.avail_out = sizeof(xar->wbuff); + xar->stream.total_out = 0; + for (;;) { + size_t size; + + r = compression_code(&(a->archive), + &(xar->stream), ARCHIVE_Z_FINISH); + if (r != ARCHIVE_OK && r != ARCHIVE_EOF) + goto exit_toc; + size = sizeof(xar->wbuff) - xar->stream.avail_out; + checksum_update(&(xar->a_sumwrk), xar->wbuff, size); + if (write_to_temp(a, xar->wbuff, size) != ARCHIVE_OK) + goto exit_toc; + if (r == ARCHIVE_EOF) + break; + xar->stream.next_out = xar->wbuff; + xar->stream.avail_out = sizeof(xar->wbuff); + } + r = compression_end(&(a->archive), &(xar->stream)); + if (r != ARCHIVE_OK) + goto exit_toc; + xar->toc.length = xar->stream.total_out; + xar->toc.compression = GZIP; + checksum_final(&(xar->a_sumwrk), &(xar->toc.a_sum)); + + ret = ARCHIVE_OK; +exit_toc: + if (writer) + xmlFreeTextWriter(writer); + if (bp) + xmlBufferFree(bp); + + return (ret); +} + +static int +flush_wbuff(struct archive_write *a) +{ + struct xar *xar; + int r; + size_t s; + + xar = (struct xar *)a->format_data; + s = sizeof(xar->wbuff) - xar->wbuff_remaining; + r = __archive_write_output(a, xar->wbuff, s); + if (r != ARCHIVE_OK) + return (r); + xar->wbuff_remaining = sizeof(xar->wbuff); + return (r); +} + +static int +copy_out(struct archive_write *a, uint64_t offset, uint64_t length) +{ + struct xar *xar; + int r; + + xar = (struct xar *)a->format_data; + if (lseek(xar->temp_fd, offset, SEEK_SET) < 0) { + archive_set_error(&(a->archive), errno, "lseek failed"); + return (ARCHIVE_FATAL); + } + while (length) { + size_t rsize; + ssize_t rs; + unsigned char *wb; + + if (length > xar->wbuff_remaining) + rsize = xar->wbuff_remaining; + else + rsize = (size_t)length; + wb = xar->wbuff + (sizeof(xar->wbuff) - xar->wbuff_remaining); + rs = read(xar->temp_fd, wb, rsize); + if (rs < 0) { + archive_set_error(&(a->archive), errno, + "Can't read temporary file(%jd)", + (intmax_t)rs); + return (ARCHIVE_FATAL); + } + if (rs == 0) { + archive_set_error(&(a->archive), 0, + "Truncated xar archive"); + return (ARCHIVE_FATAL); + } + xar->wbuff_remaining -= rs; + length -= rs; + if (xar->wbuff_remaining == 0) { + r = flush_wbuff(a); + if (r != ARCHIVE_OK) + return (r); + } + } + return (ARCHIVE_OK); +} + +static int +xar_close(struct archive_write *a) +{ + struct xar *xar; + unsigned char *wb; + uint64_t length; + int r; + + xar = (struct xar *)a->format_data; + + /* Empty! */ + if (xar->root->children.first == NULL) + return (ARCHIVE_OK); + + /* Save the length of all file extended attributes and contents. */ + length = xar->temp_offset; + + /* Connect hardlinked files */ + file_connect_hardlink_files(xar); + + /* Make the TOC */ + r = make_toc(a); + if (r != ARCHIVE_OK) + return (r); + /* + * Make the xar header on wbuff(write buffer). + */ + wb = xar->wbuff; + xar->wbuff_remaining = sizeof(xar->wbuff); + archive_be32enc(&wb[0], HEADER_MAGIC); + archive_be16enc(&wb[4], HEADER_SIZE); + archive_be16enc(&wb[6], HEADER_VERSION); + archive_be64enc(&wb[8], xar->toc.length); + archive_be64enc(&wb[16], xar->toc.size); + archive_be32enc(&wb[24], xar->toc.a_sum.alg); + xar->wbuff_remaining -= HEADER_SIZE; + + /* + * Write the TOC + */ + r = copy_out(a, xar->toc.temp_offset, xar->toc.length); + if (r != ARCHIVE_OK) + return (r); + + /* Write the checksum value of the TOC. */ + if (xar->toc.a_sum.len) { + if (xar->wbuff_remaining < xar->toc.a_sum.len) { + r = flush_wbuff(a); + if (r != ARCHIVE_OK) + return (r); + } + wb = xar->wbuff + (sizeof(xar->wbuff) - xar->wbuff_remaining); + memcpy(wb, xar->toc.a_sum.val, xar->toc.a_sum.len); + xar->wbuff_remaining -= xar->toc.a_sum.len; + } + + /* + * Write all file extended attributes and contents. + */ + r = copy_out(a, xar->toc.a_sum.len, length); + if (r != ARCHIVE_OK) + return (r); + r = flush_wbuff(a); + return (r); +} + +static int +xar_free(struct archive_write *a) +{ + struct xar *xar; + + xar = (struct xar *)a->format_data; + + /* Close the temporary file. */ + if (xar->temp_fd >= 0) + close(xar->temp_fd); + + archive_string_free(&(xar->cur_dirstr)); + archive_string_free(&(xar->tstr)); + archive_string_free(&(xar->vstr)); + file_free_hardlinks(xar); + file_free_register(xar); + compression_end(&(a->archive), &(xar->stream)); + free(xar); + + return (ARCHIVE_OK); +} + +static int +file_cmp_node(const struct archive_rb_node *n1, + const struct archive_rb_node *n2) +{ + const struct file *f1 = (const struct file *)n1; + const struct file *f2 = (const struct file *)n2; + + return (strcmp(f1->basename.s, f2->basename.s)); +} + +static int +file_cmp_key(const struct archive_rb_node *n, const void *key) +{ + const struct file *f = (const struct file *)n; + + return (strcmp(f->basename.s, (const char *)key)); +} + +static struct file * +file_new(struct archive_write *a, struct archive_entry *entry) +{ + struct file *file; + static const struct archive_rb_tree_ops rb_ops = { + file_cmp_node, file_cmp_key + }; + + file = calloc(1, sizeof(*file)); + if (file == NULL) + return (NULL); + + if (entry != NULL) + file->entry = archive_entry_clone(entry); + else + file->entry = archive_entry_new2(&a->archive); + if (file->entry == NULL) { + free(file); + return (NULL); + } + __archive_rb_tree_init(&(file->rbtree), &rb_ops); + file->children.first = NULL; + file->children.last = &(file->children.first); + file->xattr.first = NULL; + file->xattr.last = &(file->xattr.first); + archive_string_init(&(file->parentdir)); + archive_string_init(&(file->basename)); + archive_string_init(&(file->symlink)); + archive_string_init(&(file->script)); + if (entry != NULL && archive_entry_filetype(entry) == AE_IFDIR) + file->dir = 1; + + return (file); +} + +static void +file_free(struct file *file) +{ + struct heap_data *heap, *next_heap; + + heap = file->xattr.first; + while (heap != NULL) { + next_heap = heap->next; + free(heap); + heap = next_heap; + } + archive_string_free(&(file->parentdir)); + archive_string_free(&(file->basename)); + archive_string_free(&(file->symlink)); + archive_string_free(&(file->script)); + archive_entry_free(file->entry); + free(file); +} + +static struct file * +file_create_virtual_dir(struct archive_write *a, struct xar *xar, + const char *pathname) +{ + struct file *file; + + (void)xar; /* UNUSED */ + + file = file_new(a, NULL); + if (file == NULL) + return (NULL); + archive_entry_set_pathname(file->entry, pathname); + archive_entry_set_mode(file->entry, 0555 | AE_IFDIR); + + file->dir = 1; + file->virtual = 1; + + return (file); +} + +static int +file_add_child_tail(struct file *parent, struct file *child) +{ + if (!__archive_rb_tree_insert_node( + &(parent->rbtree), (struct archive_rb_node *)child)) + return (0); + child->chnext = NULL; + *parent->children.last = child; + parent->children.last = &(child->chnext); + child->parent = parent; + return (1); +} + +/* + * Find a entry from `parent' + */ +static struct file * +file_find_child(struct file *parent, const char *child_name) +{ + struct file *np; + + np = (struct file *)__archive_rb_tree_find_node( + &(parent->rbtree), child_name); + return (np); +} + +#if defined(_WIN32) || defined(__CYGWIN__) +static void +cleanup_backslash(char *utf8, size_t len) +{ + + /* Convert a path-separator from '\' to '/' */ + while (*utf8 != '\0' && len) { + if (*utf8 == '\\') + *utf8 = '/'; + ++utf8; + --len; + } +} +#else +#define cleanup_backslash(p, len) /* nop */ +#endif + +/* + * Generate a parent directory name and a base name from a pathname. + */ +static int +file_gen_utility_names(struct archive_write *a, struct file *file) +{ + struct xar *xar; + const char *pp; + char *p, *dirname, *slash; + size_t len; + int r = ARCHIVE_OK; + + xar = (struct xar *)a->format_data; + archive_string_empty(&(file->parentdir)); + archive_string_empty(&(file->basename)); + archive_string_empty(&(file->symlink)); + + if (file->parent == file)/* virtual root */ + return (ARCHIVE_OK); + + if (archive_entry_pathname_l(file->entry, &pp, &len, xar->sconv) + != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate pathname '%s' to UTF-8", + archive_entry_pathname(file->entry)); + r = ARCHIVE_WARN; + } + archive_strncpy(&(file->parentdir), pp, len); + len = file->parentdir.length; + p = dirname = file->parentdir.s; + /* + * Convert a path-separator from '\' to '/' + */ + cleanup_backslash(p, len); + + /* + * Remove leading '/', '../' and './' elements + */ + while (*p) { + if (p[0] == '/') { + p++; + len--; + } else if (p[0] != '.') + break; + else if (p[1] == '.' && p[2] == '/') { + p += 3; + len -= 3; + } else if (p[1] == '/' || (p[1] == '.' && p[2] == '\0')) { + p += 2; + len -= 2; + } else if (p[1] == '\0') { + p++; + len--; + } else + break; + } + if (p != dirname) { + memmove(dirname, p, len+1); + p = dirname; + } + /* + * Remove "/","/." and "/.." elements from tail. + */ + while (len > 0) { + size_t ll = len; + + if (p[len-1] == '/') { + p[len-1] = '\0'; + len--; + } + if (len > 1 && p[len-2] == '/' && p[len-1] == '.') { + p[len-2] = '\0'; + len -= 2; + } + if (len > 2 && p[len-3] == '/' && p[len-2] == '.' && + p[len-1] == '.') { + p[len-3] = '\0'; + len -= 3; + } + if (ll == len) + break; + } + while (*p) { + if (p[0] == '/') { + if (p[1] == '/') + /* Convert '//' --> '/' */ + memmove(p, p+1, strlen(p+1) + 1); + else if (p[1] == '.' && p[2] == '/') + /* Convert '/./' --> '/' */ + memmove(p, p+2, strlen(p+2) + 1); + else if (p[1] == '.' && p[2] == '.' && p[3] == '/') { + /* Convert 'dir/dir1/../dir2/' + * --> 'dir/dir2/' + */ + char *rp = p -1; + while (rp >= dirname) { + if (*rp == '/') + break; + --rp; + } + if (rp > dirname) { + strcpy(rp, p+3); + p = rp; + } else { + strcpy(dirname, p+4); + p = dirname; + } + } else + p++; + } else + p++; + } + p = dirname; + len = strlen(p); + + if (archive_entry_filetype(file->entry) == AE_IFLNK) { + size_t len2; + /* Convert symlink name too. */ + if (archive_entry_symlink_l(file->entry, &pp, &len2, + xar->sconv) != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Linkname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate symlink '%s' to UTF-8", + archive_entry_symlink(file->entry)); + r = ARCHIVE_WARN; + } + archive_strncpy(&(file->symlink), pp, len2); + cleanup_backslash(file->symlink.s, file->symlink.length); + } + /* + * - Count up directory elements. + * - Find out the position which points the last position of + * path separator('/'). + */ + slash = NULL; + for (; *p != '\0'; p++) + if (*p == '/') + slash = p; + if (slash == NULL) { + /* The pathname doesn't have a parent directory. */ + file->parentdir.length = len; + archive_string_copy(&(file->basename), &(file->parentdir)); + archive_string_empty(&(file->parentdir)); + *file->parentdir.s = '\0'; + return (r); + } + + /* Make a basename from dirname and slash */ + *slash = '\0'; + file->parentdir.length = slash - dirname; + archive_strcpy(&(file->basename), slash + 1); + return (r); +} + +static int +get_path_component(char *name, int n, const char *fn) +{ + char *p; + int l; + + p = strchr(fn, '/'); + if (p == NULL) { + if ((l = strlen(fn)) == 0) + return (0); + } else + l = p - fn; + if (l > n -1) + return (-1); + memcpy(name, fn, l); + name[l] = '\0'; + + return (l); +} + +/* + * Add a new entry into the tree. + */ +static int +file_tree(struct archive_write *a, struct file **filepp) +{ +#if defined(_WIN32) && !defined(__CYGWIN__) + char name[_MAX_FNAME];/* Included null terminator size. */ +#elif defined(NAME_MAX) && NAME_MAX >= 255 + char name[NAME_MAX+1]; +#else + char name[256]; +#endif + struct xar *xar = (struct xar *)a->format_data; + struct file *dent, *file, *np; + struct archive_entry *ent; + const char *fn, *p; + int l; + + file = *filepp; + dent = xar->root; + if (file->parentdir.length > 0) + fn = p = file->parentdir.s; + else + fn = p = ""; + + /* + * If the path of the parent directory of `file' entry is + * the same as the path of `cur_dirent', add isoent to + * `cur_dirent'. + */ + if (archive_strlen(&(xar->cur_dirstr)) + == archive_strlen(&(file->parentdir)) && + strcmp(xar->cur_dirstr.s, fn) == 0) { + if (!file_add_child_tail(xar->cur_dirent, file)) { + np = (struct file *)__archive_rb_tree_find_node( + &(xar->cur_dirent->rbtree), + file->basename.s); + goto same_entry; + } + return (ARCHIVE_OK); + } + + for (;;) { + l = get_path_component(name, sizeof(name), fn); + if (l == 0) { + np = NULL; + break; + } + if (l < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "A name buffer is too small"); + file_free(file); + *filepp = NULL; + return (ARCHIVE_FATAL); + } + + np = file_find_child(dent, name); + if (np == NULL || fn[0] == '\0') + break; + + /* Find next subdirectory. */ + if (!np->dir) { + /* NOT Directory! */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "`%s' is not directory, we cannot insert `%s' ", + archive_entry_pathname(np->entry), + archive_entry_pathname(file->entry)); + file_free(file); + *filepp = NULL; + return (ARCHIVE_FAILED); + } + fn += l; + if (fn[0] == '/') + fn++; + dent = np; + } + if (np == NULL) { + /* + * Create virtual parent directories. + */ + while (fn[0] != '\0') { + struct file *vp; + struct archive_string as; + + archive_string_init(&as); + archive_strncat(&as, p, fn - p + l); + if (as.s[as.length-1] == '/') { + as.s[as.length-1] = '\0'; + as.length--; + } + vp = file_create_virtual_dir(a, xar, as.s); + if (vp == NULL) { + archive_string_free(&as); + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + file_free(file); + *filepp = NULL; + return (ARCHIVE_FATAL); + } + archive_string_free(&as); + if (file_gen_utility_names(a, vp) <= ARCHIVE_FAILED) + return (ARCHIVE_FATAL); + file_add_child_tail(dent, vp); + file_register(xar, vp); + np = vp; + + fn += l; + if (fn[0] == '/') + fn++; + l = get_path_component(name, sizeof(name), fn); + if (l < 0) { + archive_string_free(&as); + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "A name buffer is too small"); + file_free(file); + *filepp = NULL; + return (ARCHIVE_FATAL); + } + dent = np; + } + + /* Found out the parent directory where isoent can be + * inserted. */ + xar->cur_dirent = dent; + archive_string_empty(&(xar->cur_dirstr)); + archive_string_ensure(&(xar->cur_dirstr), + archive_strlen(&(dent->parentdir)) + + archive_strlen(&(dent->basename)) + 2); + if (archive_strlen(&(dent->parentdir)) + + archive_strlen(&(dent->basename)) == 0) + xar->cur_dirstr.s[0] = 0; + else { + if (archive_strlen(&(dent->parentdir)) > 0) { + archive_string_copy(&(xar->cur_dirstr), + &(dent->parentdir)); + archive_strappend_char(&(xar->cur_dirstr), '/'); + } + archive_string_concat(&(xar->cur_dirstr), + &(dent->basename)); + } + + if (!file_add_child_tail(dent, file)) { + np = (struct file *)__archive_rb_tree_find_node( + &(dent->rbtree), file->basename.s); + goto same_entry; + } + return (ARCHIVE_OK); + } + +same_entry: + /* + * We have already has the entry the filename of which is + * the same. + */ + if (archive_entry_filetype(np->entry) != + archive_entry_filetype(file->entry)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Found duplicate entries `%s' and its file type is " + "different", + archive_entry_pathname(np->entry)); + file_free(file); + *filepp = NULL; + return (ARCHIVE_FAILED); + } + + /* Swap files. */ + ent = np->entry; + np->entry = file->entry; + file->entry = ent; + np->virtual = 0; + + file_free(file); + *filepp = np; + return (ARCHIVE_OK); +} + +static void +file_register(struct xar *xar, struct file *file) +{ + file->id = xar->file_idx++; + file->next = NULL; + *xar->file_list.last = file; + xar->file_list.last = &(file->next); +} + +static void +file_init_register(struct xar *xar) +{ + xar->file_list.first = NULL; + xar->file_list.last = &(xar->file_list.first); +} + +static void +file_free_register(struct xar *xar) +{ + struct file *file, *file_next; + + file = xar->file_list.first; + while (file != NULL) { + file_next = file->next; + file_free(file); + file = file_next; + } +} + +/* + * Register entry to get a hardlink target. + */ +static int +file_register_hardlink(struct archive_write *a, struct file *file) +{ + struct xar *xar = (struct xar *)a->format_data; + struct hardlink *hl; + const char *pathname; + + archive_entry_set_nlink(file->entry, 1); + pathname = archive_entry_hardlink(file->entry); + if (pathname == NULL) { + /* This `file` is a hardlink target. */ + hl = malloc(sizeof(*hl)); + if (hl == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory"); + return (ARCHIVE_FATAL); + } + hl->nlink = 1; + /* A hardlink target must be the first position. */ + file->hlnext = NULL; + hl->file_list.first = file; + hl->file_list.last = &(file->hlnext); + __archive_rb_tree_insert_node(&(xar->hardlink_rbtree), + (struct archive_rb_node *)hl); + } else { + hl = (struct hardlink *)__archive_rb_tree_find_node( + &(xar->hardlink_rbtree), pathname); + if (hl != NULL) { + /* Insert `file` entry into the tail. */ + file->hlnext = NULL; + *hl->file_list.last = file; + hl->file_list.last = &(file->hlnext); + hl->nlink++; + } + archive_entry_unset_size(file->entry); + } + + return (ARCHIVE_OK); +} + +/* + * Hardlinked files have to have the same location of extent. + * We have to find out hardlink target entries for entries which + * have a hardlink target name. + */ +static void +file_connect_hardlink_files(struct xar *xar) +{ + struct archive_rb_node *n; + struct hardlink *hl; + struct file *target, *nf; + + ARCHIVE_RB_TREE_FOREACH(n, &(xar->hardlink_rbtree)) { + hl = (struct hardlink *)n; + + /* The first entry must be a hardlink target. */ + target = hl->file_list.first; + archive_entry_set_nlink(target->entry, hl->nlink); + if (hl->nlink > 1) + /* It means this file is a hardlink + * target itself. */ + target->hardlink_target = target; + for (nf = target->hlnext; + nf != NULL; nf = nf->hlnext) { + nf->hardlink_target = target; + archive_entry_set_nlink(nf->entry, hl->nlink); + } + } +} + +static int +file_hd_cmp_node(const struct archive_rb_node *n1, + const struct archive_rb_node *n2) +{ + const struct hardlink *h1 = (const struct hardlink *)n1; + const struct hardlink *h2 = (const struct hardlink *)n2; + + return (strcmp(archive_entry_pathname(h1->file_list.first->entry), + archive_entry_pathname(h2->file_list.first->entry))); +} + +static int +file_hd_cmp_key(const struct archive_rb_node *n, const void *key) +{ + const struct hardlink *h = (const struct hardlink *)n; + + return (strcmp(archive_entry_pathname(h->file_list.first->entry), + (const char *)key)); +} + + +static void +file_init_hardlinks(struct xar *xar) +{ + static const struct archive_rb_tree_ops rb_ops = { + file_hd_cmp_node, file_hd_cmp_key, + }; + + __archive_rb_tree_init(&(xar->hardlink_rbtree), &rb_ops); +} + +static void +file_free_hardlinks(struct xar *xar) +{ + struct archive_rb_node *n, *tmp; + + ARCHIVE_RB_TREE_FOREACH_SAFE(n, &(xar->hardlink_rbtree), tmp) { + __archive_rb_tree_remove_node(&(xar->hardlink_rbtree), n); + free(n); + } +} + +static void +checksum_init(struct chksumwork *sumwrk, enum sumalg sum_alg) +{ + sumwrk->alg = sum_alg; + switch (sum_alg) { + case CKSUM_NONE: + break; + case CKSUM_SHA1: + archive_sha1_init(&(sumwrk->sha1ctx)); + break; + case CKSUM_MD5: + archive_md5_init(&(sumwrk->md5ctx)); + break; + } +} + +static void +checksum_update(struct chksumwork *sumwrk, const void *buff, size_t size) +{ + + switch (sumwrk->alg) { + case CKSUM_NONE: + break; + case CKSUM_SHA1: + archive_sha1_update(&(sumwrk->sha1ctx), buff, size); + break; + case CKSUM_MD5: + archive_md5_update(&(sumwrk->md5ctx), buff, size); + break; + } +} + +static void +checksum_final(struct chksumwork *sumwrk, struct chksumval *sumval) +{ + + switch (sumwrk->alg) { + case CKSUM_NONE: + sumval->len = 0; + break; + case CKSUM_SHA1: + archive_sha1_final(&(sumwrk->sha1ctx), sumval->val); + sumval->len = SHA1_SIZE; + break; + case CKSUM_MD5: + archive_md5_final(&(sumwrk->md5ctx), sumval->val); + sumval->len = MD5_SIZE; + break; + } + sumval->alg = sumwrk->alg; +} + +#if !defined(HAVE_BZLIB_H) || !defined(BZ_CONFIG_ERROR) || !defined(HAVE_LZMA_H) +static int +compression_unsupported_encoder(struct archive *a, + struct la_zstream *lastrm, const char *name) +{ + + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "%s compression not supported on this platform", name); + lastrm->valid = 0; + lastrm->real_stream = NULL; + return (ARCHIVE_FAILED); +} +#endif + +static int +compression_init_encoder_gzip(struct archive *a, + struct la_zstream *lastrm, int level, int withheader) +{ + z_stream *strm; + + if (lastrm->valid) + compression_end(a, lastrm); + strm = calloc(1, sizeof(*strm)); + if (strm == NULL) { + archive_set_error(a, ENOMEM, + "Can't allocate memory for gzip stream"); + return (ARCHIVE_FATAL); + } + /* zlib.h is not const-correct, so we need this one bit + * of ugly hackery to convert a const * pointer to + * a non-const pointer. */ + strm->next_in = (Bytef *)(uintptr_t)(const void *)lastrm->next_in; + strm->avail_in = lastrm->avail_in; + strm->total_in = (uLong)lastrm->total_in; + strm->next_out = lastrm->next_out; + strm->avail_out = lastrm->avail_out; + strm->total_out = (uLong)lastrm->total_out; + if (deflateInit2(strm, level, Z_DEFLATED, + (withheader)?15:-15, + 8, Z_DEFAULT_STRATEGY) != Z_OK) { + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library"); + return (ARCHIVE_FATAL); + } + lastrm->real_stream = strm; + lastrm->valid = 1; + lastrm->code = compression_code_gzip; + lastrm->end = compression_end_gzip; + return (ARCHIVE_OK); +} + +static int +compression_code_gzip(struct archive *a, + struct la_zstream *lastrm, enum la_zaction action) +{ + z_stream *strm; + int r; + + strm = (z_stream *)lastrm->real_stream; + /* zlib.h is not const-correct, so we need this one bit + * of ugly hackery to convert a const * pointer to + * a non-const pointer. */ + strm->next_in = (Bytef *)(uintptr_t)(const void *)lastrm->next_in; + strm->avail_in = lastrm->avail_in; + strm->total_in = (uLong)lastrm->total_in; + strm->next_out = lastrm->next_out; + strm->avail_out = lastrm->avail_out; + strm->total_out = (uLong)lastrm->total_out; + r = deflate(strm, + (action == ARCHIVE_Z_FINISH)? Z_FINISH: Z_NO_FLUSH); + lastrm->next_in = strm->next_in; + lastrm->avail_in = strm->avail_in; + lastrm->total_in = strm->total_in; + lastrm->next_out = strm->next_out; + lastrm->avail_out = strm->avail_out; + lastrm->total_out = strm->total_out; + switch (r) { + case Z_OK: + return (ARCHIVE_OK); + case Z_STREAM_END: + return (ARCHIVE_EOF); + default: + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "GZip compression failed:" + " deflate() call returned status %d", r); + return (ARCHIVE_FATAL); + } +} + +static int +compression_end_gzip(struct archive *a, struct la_zstream *lastrm) +{ + z_stream *strm; + int r; + + strm = (z_stream *)lastrm->real_stream; + r = deflateEnd(strm); + free(strm); + lastrm->real_stream = NULL; + lastrm->valid = 0; + if (r != Z_OK) { + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Failed to clean up compressor"); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_OK); +} + +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) +static int +compression_init_encoder_bzip2(struct archive *a, + struct la_zstream *lastrm, int level) +{ + bz_stream *strm; + + if (lastrm->valid) + compression_end(a, lastrm); + strm = calloc(1, sizeof(*strm)); + if (strm == NULL) { + archive_set_error(a, ENOMEM, + "Can't allocate memory for bzip2 stream"); + return (ARCHIVE_FATAL); + } + /* bzlib.h is not const-correct, so we need this one bit + * of ugly hackery to convert a const * pointer to + * a non-const pointer. */ + strm->next_in = (char *)(uintptr_t)(const void *)lastrm->next_in; + strm->avail_in = lastrm->avail_in; + strm->total_in_lo32 = (uint32_t)(lastrm->total_in & 0xffffffff); + strm->total_in_hi32 = (uint32_t)(lastrm->total_in >> 32); + strm->next_out = (char *)lastrm->next_out; + strm->avail_out = lastrm->avail_out; + strm->total_out_lo32 = (uint32_t)(lastrm->total_out & 0xffffffff); + strm->total_out_hi32 = (uint32_t)(lastrm->total_out >> 32); + if (BZ2_bzCompressInit(strm, level, 0, 30) != BZ_OK) { + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library"); + return (ARCHIVE_FATAL); + } + lastrm->real_stream = strm; + lastrm->valid = 1; + lastrm->code = compression_code_bzip2; + lastrm->end = compression_end_bzip2; + return (ARCHIVE_OK); +} + +static int +compression_code_bzip2(struct archive *a, + struct la_zstream *lastrm, enum la_zaction action) +{ + bz_stream *strm; + int r; + + strm = (bz_stream *)lastrm->real_stream; + /* bzlib.h is not const-correct, so we need this one bit + * of ugly hackery to convert a const * pointer to + * a non-const pointer. */ + strm->next_in = (char *)(uintptr_t)(const void *)lastrm->next_in; + strm->avail_in = lastrm->avail_in; + strm->total_in_lo32 = (uint32_t)(lastrm->total_in & 0xffffffff); + strm->total_in_hi32 = (uint32_t)(lastrm->total_in >> 32); + strm->next_out = (char *)lastrm->next_out; + strm->avail_out = lastrm->avail_out; + strm->total_out_lo32 = (uint32_t)(lastrm->total_out & 0xffffffff); + strm->total_out_hi32 = (uint32_t)(lastrm->total_out >> 32); + r = BZ2_bzCompress(strm, + (action == ARCHIVE_Z_FINISH)? BZ_FINISH: BZ_RUN); + lastrm->next_in = (const unsigned char *)strm->next_in; + lastrm->avail_in = strm->avail_in; + lastrm->total_in = + (((uint64_t)(uint32_t)strm->total_in_hi32) << 32) + + (uint64_t)(uint32_t)strm->total_in_lo32; + lastrm->next_out = (unsigned char *)strm->next_out; + lastrm->avail_out = strm->avail_out; + lastrm->total_out = + (((uint64_t)(uint32_t)strm->total_out_hi32) << 32) + + (uint64_t)(uint32_t)strm->total_out_lo32; + switch (r) { + case BZ_RUN_OK: /* Non-finishing */ + case BZ_FINISH_OK: /* Finishing: There's more work to do */ + return (ARCHIVE_OK); + case BZ_STREAM_END: /* Finishing: all done */ + /* Only occurs in finishing case */ + return (ARCHIVE_EOF); + default: + /* Any other return value indicates an error */ + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Bzip2 compression failed:" + " BZ2_bzCompress() call returned status %d", r); + return (ARCHIVE_FATAL); + } +} + +static int +compression_end_bzip2(struct archive *a, struct la_zstream *lastrm) +{ + bz_stream *strm; + int r; + + strm = (bz_stream *)lastrm->real_stream; + r = BZ2_bzCompressEnd(strm); + free(strm); + lastrm->real_stream = NULL; + lastrm->valid = 0; + if (r != BZ_OK) { + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Failed to clean up compressor"); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_OK); +} + +#else +static int +compression_init_encoder_bzip2(struct archive *a, + struct la_zstream *lastrm, int level) +{ + + (void) level; /* UNUSED */ + if (lastrm->valid) + compression_end(a, lastrm); + return (compression_unsupported_encoder(a, lastrm, "bzip2")); +} +#endif + +#if defined(HAVE_LZMA_H) +static int +compression_init_encoder_lzma(struct archive *a, + struct la_zstream *lastrm, int level) +{ + static const lzma_stream lzma_init_data = LZMA_STREAM_INIT; + lzma_stream *strm; + lzma_options_lzma lzma_opt; + int r; + + if (lastrm->valid) + compression_end(a, lastrm); + if (lzma_lzma_preset(&lzma_opt, level)) { + lastrm->real_stream = NULL; + archive_set_error(a, ENOMEM, + "Internal error initializing compression library"); + return (ARCHIVE_FATAL); + } + strm = calloc(1, sizeof(*strm)); + if (strm == NULL) { + archive_set_error(a, ENOMEM, + "Can't allocate memory for lzma stream"); + return (ARCHIVE_FATAL); + } + *strm = lzma_init_data; + r = lzma_alone_encoder(strm, &lzma_opt); + switch (r) { + case LZMA_OK: + lastrm->real_stream = strm; + lastrm->valid = 1; + lastrm->code = compression_code_lzma; + lastrm->end = compression_end_lzma; + r = ARCHIVE_OK; + break; + case LZMA_MEM_ERROR: + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ENOMEM, + "Internal error initializing compression library: " + "Cannot allocate memory"); + r = ARCHIVE_FATAL; + break; + default: + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library: " + "It's a bug in liblzma"); + r = ARCHIVE_FATAL; + break; + } + return (r); +} + +static int +compression_init_encoder_xz(struct archive *a, + struct la_zstream *lastrm, int level, int threads) +{ + static const lzma_stream lzma_init_data = LZMA_STREAM_INIT; + lzma_stream *strm; + lzma_filter *lzmafilters; + lzma_options_lzma lzma_opt; + int r; +#ifdef HAVE_LZMA_STREAM_ENCODER_MT + lzma_mt mt_options; +#endif + + (void)threads; /* UNUSED (if multi-threaded LZMA library not avail) */ + + if (lastrm->valid) + compression_end(a, lastrm); + strm = calloc(1, sizeof(*strm) + sizeof(*lzmafilters) * 2); + if (strm == NULL) { + archive_set_error(a, ENOMEM, + "Can't allocate memory for xz stream"); + return (ARCHIVE_FATAL); + } + lzmafilters = (lzma_filter *)(strm+1); + if (level > 6) + level = 6; + if (lzma_lzma_preset(&lzma_opt, level)) { + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ENOMEM, + "Internal error initializing compression library"); + return (ARCHIVE_FATAL); + } + lzmafilters[0].id = LZMA_FILTER_LZMA2; + lzmafilters[0].options = &lzma_opt; + lzmafilters[1].id = LZMA_VLI_UNKNOWN;/* Terminate */ + + *strm = lzma_init_data; +#ifdef HAVE_LZMA_STREAM_ENCODER_MT + if (threads > 1) { + memset(&mt_options, 0, sizeof(mt_options)); + mt_options.threads = threads; + mt_options.timeout = 300; + mt_options.filters = lzmafilters; + mt_options.check = LZMA_CHECK_CRC64; + r = lzma_stream_encoder_mt(strm, &mt_options); + } else +#endif + r = lzma_stream_encoder(strm, lzmafilters, LZMA_CHECK_CRC64); + switch (r) { + case LZMA_OK: + lastrm->real_stream = strm; + lastrm->valid = 1; + lastrm->code = compression_code_lzma; + lastrm->end = compression_end_lzma; + r = ARCHIVE_OK; + break; + case LZMA_MEM_ERROR: + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ENOMEM, + "Internal error initializing compression library: " + "Cannot allocate memory"); + r = ARCHIVE_FATAL; + break; + default: + free(strm); + lastrm->real_stream = NULL; + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "Internal error initializing compression library: " + "It's a bug in liblzma"); + r = ARCHIVE_FATAL; + break; + } + return (r); +} + +static int +compression_code_lzma(struct archive *a, + struct la_zstream *lastrm, enum la_zaction action) +{ + lzma_stream *strm; + int r; + + strm = (lzma_stream *)lastrm->real_stream; + strm->next_in = lastrm->next_in; + strm->avail_in = lastrm->avail_in; + strm->total_in = lastrm->total_in; + strm->next_out = lastrm->next_out; + strm->avail_out = lastrm->avail_out; + strm->total_out = lastrm->total_out; + r = lzma_code(strm, + (action == ARCHIVE_Z_FINISH)? LZMA_FINISH: LZMA_RUN); + lastrm->next_in = strm->next_in; + lastrm->avail_in = strm->avail_in; + lastrm->total_in = strm->total_in; + lastrm->next_out = strm->next_out; + lastrm->avail_out = strm->avail_out; + lastrm->total_out = strm->total_out; + switch (r) { + case LZMA_OK: + /* Non-finishing case */ + return (ARCHIVE_OK); + case LZMA_STREAM_END: + /* This return can only occur in finishing case. */ + return (ARCHIVE_EOF); + case LZMA_MEMLIMIT_ERROR: + archive_set_error(a, ENOMEM, + "lzma compression error:" + " %ju MiB would have been needed", + (uintmax_t)((lzma_memusage(strm) + 1024 * 1024 -1) + / (1024 * 1024))); + return (ARCHIVE_FATAL); + default: + /* Any other return value indicates an error */ + archive_set_error(a, ARCHIVE_ERRNO_MISC, + "lzma compression failed:" + " lzma_code() call returned status %d", r); + return (ARCHIVE_FATAL); + } +} + +static int +compression_end_lzma(struct archive *a, struct la_zstream *lastrm) +{ + lzma_stream *strm; + + (void)a; /* UNUSED */ + strm = (lzma_stream *)lastrm->real_stream; + lzma_end(strm); + free(strm); + lastrm->valid = 0; + lastrm->real_stream = NULL; + return (ARCHIVE_OK); +} +#else +static int +compression_init_encoder_lzma(struct archive *a, + struct la_zstream *lastrm, int level) +{ + + (void) level; /* UNUSED */ + if (lastrm->valid) + compression_end(a, lastrm); + return (compression_unsupported_encoder(a, lastrm, "lzma")); +} +static int +compression_init_encoder_xz(struct archive *a, + struct la_zstream *lastrm, int level, int threads) +{ + + (void) level; /* UNUSED */ + (void) threads; /* UNUSED */ + if (lastrm->valid) + compression_end(a, lastrm); + return (compression_unsupported_encoder(a, lastrm, "xz")); +} +#endif + +static int +xar_compression_init_encoder(struct archive_write *a) +{ + struct xar *xar; + int r; + + xar = (struct xar *)a->format_data; + switch (xar->opt_compression) { + case GZIP: + r = compression_init_encoder_gzip( + &(a->archive), &(xar->stream), + xar->opt_compression_level, 1); + break; + case BZIP2: + r = compression_init_encoder_bzip2( + &(a->archive), &(xar->stream), + xar->opt_compression_level); + break; + case LZMA: + r = compression_init_encoder_lzma( + &(a->archive), &(xar->stream), + xar->opt_compression_level); + break; + case XZ: + r = compression_init_encoder_xz( + &(a->archive), &(xar->stream), + xar->opt_compression_level, xar->opt_threads); + break; + default: + r = ARCHIVE_OK; + break; + } + if (r == ARCHIVE_OK) { + xar->stream.total_in = 0; + xar->stream.next_out = xar->wbuff; + xar->stream.avail_out = sizeof(xar->wbuff); + xar->stream.total_out = 0; + } + + return (r); +} + +static int +compression_code(struct archive *a, struct la_zstream *lastrm, + enum la_zaction action) +{ + if (lastrm->valid) + return (lastrm->code(a, lastrm, action)); + return (ARCHIVE_OK); +} + +static int +compression_end(struct archive *a, struct la_zstream *lastrm) +{ + if (lastrm->valid) + return (lastrm->end(a, lastrm)); + return (ARCHIVE_OK); +} + + +static int +save_xattrs(struct archive_write *a, struct file *file) +{ + struct xar *xar; + const char *name; + const void *value; + struct heap_data *heap; + size_t size; + int count, r; + + xar = (struct xar *)a->format_data; + count = archive_entry_xattr_reset(file->entry); + if (count == 0) + return (ARCHIVE_OK); + while (count--) { + archive_entry_xattr_next(file->entry, + &name, &value, &size); + checksum_init(&(xar->a_sumwrk), xar->opt_sumalg); + checksum_init(&(xar->e_sumwrk), xar->opt_sumalg); + + heap = calloc(1, sizeof(*heap)); + if (heap == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for xattr"); + return (ARCHIVE_FATAL); + } + heap->id = file->ea_idx++; + heap->temp_offset = xar->temp_offset; + heap->size = size;/* save a extracted size */ + heap->compression = xar->opt_compression; + /* Get a extracted sumcheck value. */ + checksum_update(&(xar->e_sumwrk), value, size); + checksum_final(&(xar->e_sumwrk), &(heap->e_sum)); + + /* + * Not compression to xattr is simple way. + */ + if (heap->compression == NONE) { + checksum_update(&(xar->a_sumwrk), value, size); + checksum_final(&(xar->a_sumwrk), &(heap->a_sum)); + if (write_to_temp(a, value, size) + != ARCHIVE_OK) { + free(heap); + return (ARCHIVE_FATAL); + } + heap->length = size; + /* Add heap to the tail of file->xattr. */ + heap->next = NULL; + *file->xattr.last = heap; + file->xattr.last = &(heap->next); + /* Next xattr */ + continue; + } + + /* + * Init compression library. + */ + r = xar_compression_init_encoder(a); + if (r != ARCHIVE_OK) { + free(heap); + return (ARCHIVE_FATAL); + } + + xar->stream.next_in = (const unsigned char *)value; + xar->stream.avail_in = size; + for (;;) { + r = compression_code(&(a->archive), + &(xar->stream), ARCHIVE_Z_FINISH); + if (r != ARCHIVE_OK && r != ARCHIVE_EOF) { + free(heap); + return (ARCHIVE_FATAL); + } + size = sizeof(xar->wbuff) - xar->stream.avail_out; + checksum_update(&(xar->a_sumwrk), + xar->wbuff, size); + if (write_to_temp(a, xar->wbuff, size) + != ARCHIVE_OK) { + free(heap); + return (ARCHIVE_FATAL); + } + if (r == ARCHIVE_OK) { + xar->stream.next_out = xar->wbuff; + xar->stream.avail_out = sizeof(xar->wbuff); + } else { + checksum_final(&(xar->a_sumwrk), + &(heap->a_sum)); + heap->length = xar->stream.total_out; + /* Add heap to the tail of file->xattr. */ + heap->next = NULL; + *file->xattr.last = heap; + file->xattr.last = &(heap->next); + break; + } + } + /* Clean up compression library. */ + r = compression_end(&(a->archive), &(xar->stream)); + if (r != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + return (ARCHIVE_OK); +} + +static int +getalgsize(enum sumalg sumalg) +{ + switch (sumalg) { + default: + case CKSUM_NONE: + return (0); + case CKSUM_SHA1: + return (SHA1_SIZE); + case CKSUM_MD5: + return (MD5_SIZE); + } +} + +static const char * +getalgname(enum sumalg sumalg) +{ + switch (sumalg) { + default: + case CKSUM_NONE: + return (NULL); + case CKSUM_SHA1: + return (SHA1_NAME); + case CKSUM_MD5: + return (MD5_NAME); + } +} + +#endif /* Support xar format */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_zip.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_zip.c new file mode 100644 index 0000000000..6d485295d5 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_format_zip.c @@ -0,0 +1,1695 @@ +/*- + * Copyright (c) 2008 Anselm Strauss + * Copyright (c) 2009 Joerg Sonnenberger + * Copyright (c) 2011-2012,2014 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +/* + * Development supported by Google Summer of Code 2008. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_zip.c 201168 2009-12-29 06:15:32Z kientzle $"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_LANGINFO_H +#include <langinfo.h> +#endif +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#ifdef HAVE_STRING_H +#include <string.h> +#endif +#ifdef HAVE_ZLIB_H +#include <zlib.h> +#endif + +#include "archive.h" +#include "archive_cryptor_private.h" +#include "archive_endian.h" +#include "archive_entry.h" +#include "archive_entry_locale.h" +#include "archive_hmac_private.h" +#include "archive_private.h" +#include "archive_random_private.h" +#include "archive_write_private.h" +#include "archive_write_set_format_private.h" + +#ifndef HAVE_ZLIB_H +#include "archive_crc32.h" +#endif + +#define ZIP_ENTRY_FLAG_ENCRYPTED (1<<0) +#define ZIP_ENTRY_FLAG_LENGTH_AT_END (1<<3) +#define ZIP_ENTRY_FLAG_UTF8_NAME (1 << 11) + +#define ZIP_4GB_MAX ARCHIVE_LITERAL_LL(0xffffffff) +#define ZIP_4GB_MAX_UNCOMPRESSED ARCHIVE_LITERAL_LL(0xff000000) + +enum compression { + COMPRESSION_UNSPECIFIED = -1, + COMPRESSION_STORE = 0, + COMPRESSION_DEFLATE = 8 +}; + +#ifdef HAVE_ZLIB_H +#define COMPRESSION_DEFAULT COMPRESSION_DEFLATE +#else +#define COMPRESSION_DEFAULT COMPRESSION_STORE +#endif + +enum encryption { + ENCRYPTION_NONE = 0, + ENCRYPTION_TRADITIONAL, /* Traditional PKWARE encryption. */ + ENCRYPTION_WINZIP_AES128, /* WinZIP AES-128 encryption. */ + ENCRYPTION_WINZIP_AES256, /* WinZIP AES-256 encryption. */ +}; + +#define TRAD_HEADER_SIZE 12 +/* + * See "WinZip - AES Encryption Information" + * http://www.winzip.com/aes_info.htm + */ +/* Value used in compression method. */ +#define WINZIP_AES_ENCRYPTION 99 +/* A WinZip AES header size which is stored at the beginning of + * file contents. */ +#define WINZIP_AES128_HEADER_SIZE (8 + 2) +#define WINZIP_AES256_HEADER_SIZE (16 + 2) +/* AES vendor version. */ +#define AES_VENDOR_AE_1 0x0001 +#define AES_VENDOR_AE_2 0x0002 +/* Authentication code size. */ +#define AUTH_CODE_SIZE 10 +/**/ +#define MAX_DERIVED_KEY_BUF_SIZE (AES_MAX_KEY_SIZE * 2 + 2) + +struct cd_segment { + struct cd_segment *next; + size_t buff_size; + unsigned char *buff; + unsigned char *p; +}; + +struct trad_enc_ctx { + uint32_t keys[3]; +}; + +struct zip { + + int64_t entry_offset; + int64_t entry_compressed_size; + int64_t entry_uncompressed_size; + int64_t entry_compressed_written; + int64_t entry_uncompressed_written; + int64_t entry_uncompressed_limit; + struct archive_entry *entry; + uint32_t entry_crc32; + enum compression entry_compression; + enum encryption entry_encryption; + int entry_flags; + int entry_uses_zip64; + int experiments; + struct trad_enc_ctx tctx; + char tctx_valid; + unsigned char trad_chkdat; + unsigned aes_vendor; + archive_crypto_ctx cctx; + char cctx_valid; + archive_hmac_sha1_ctx hctx; + char hctx_valid; + + unsigned char *file_header; + size_t file_header_extra_offset; + unsigned long (*crc32func)(unsigned long crc, const void *buff, size_t len); + + struct cd_segment *central_directory; + struct cd_segment *central_directory_last; + size_t central_directory_bytes; + size_t central_directory_entries; + + int64_t written_bytes; /* Overall position in file. */ + + struct archive_string_conv *opt_sconv; + struct archive_string_conv *sconv_default; + enum compression requested_compression; + int deflate_compression_level; + int init_default_conversion; + enum encryption encryption_type; + +#define ZIP_FLAG_AVOID_ZIP64 1 +#define ZIP_FLAG_FORCE_ZIP64 2 +#define ZIP_FLAG_EXPERIMENT_xl 4 + int flags; + +#ifdef HAVE_ZLIB_H + z_stream stream; +#endif + size_t len_buf; + unsigned char *buf; +}; + +/* Don't call this min or MIN, since those are already defined + on lots of platforms (but not all). */ +#define zipmin(a, b) ((a) > (b) ? (b) : (a)) + +static ssize_t archive_write_zip_data(struct archive_write *, + const void *buff, size_t s); +static int archive_write_zip_close(struct archive_write *); +static int archive_write_zip_free(struct archive_write *); +static int archive_write_zip_finish_entry(struct archive_write *); +static int archive_write_zip_header(struct archive_write *, + struct archive_entry *); +static int archive_write_zip_options(struct archive_write *, + const char *, const char *); +static unsigned int dos_time(const time_t); +static size_t path_length(struct archive_entry *); +static int write_path(struct archive_entry *, struct archive_write *); +static void copy_path(struct archive_entry *, unsigned char *); +static struct archive_string_conv *get_sconv(struct archive_write *, struct zip *); +static int trad_enc_init(struct trad_enc_ctx *, const char *, size_t); +static unsigned trad_enc_encrypt_update(struct trad_enc_ctx *, const uint8_t *, + size_t, uint8_t *, size_t); +static int init_traditional_pkware_encryption(struct archive_write *); +static int is_traditional_pkware_encryption_supported(void); +static int init_winzip_aes_encryption(struct archive_write *); +static int is_winzip_aes_encryption_supported(int encryption); + +static unsigned char * +cd_alloc(struct zip *zip, size_t length) +{ + unsigned char *p; + + if (zip->central_directory == NULL + || (zip->central_directory_last->p + length + > zip->central_directory_last->buff + zip->central_directory_last->buff_size)) { + struct cd_segment *segment = calloc(1, sizeof(*segment)); + if (segment == NULL) + return NULL; + segment->buff_size = 64 * 1024; + segment->buff = malloc(segment->buff_size); + if (segment->buff == NULL) { + free(segment); + return NULL; + } + segment->p = segment->buff; + + if (zip->central_directory == NULL) { + zip->central_directory + = zip->central_directory_last + = segment; + } else { + zip->central_directory_last->next = segment; + zip->central_directory_last = segment; + } + } + + p = zip->central_directory_last->p; + zip->central_directory_last->p += length; + zip->central_directory_bytes += length; + return (p); +} + +static unsigned long +real_crc32(unsigned long crc, const void *buff, size_t len) +{ + return crc32(crc, buff, (unsigned int)len); +} + +static unsigned long +fake_crc32(unsigned long crc, const void *buff, size_t len) +{ + (void)crc; /* UNUSED */ + (void)buff; /* UNUSED */ + (void)len; /* UNUSED */ + return 0; +} + +static int +archive_write_zip_options(struct archive_write *a, const char *key, + const char *val) +{ + struct zip *zip = a->format_data; + int ret = ARCHIVE_FAILED; + + if (strcmp(key, "compression") == 0) { + /* + * Set compression to use on all future entries. + * This only affects regular files. + */ + if (val == NULL || val[0] == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "%s: compression option needs a compression name", + a->format_name); + } else if (strcmp(val, "deflate") == 0) { +#ifdef HAVE_ZLIB_H + zip->requested_compression = COMPRESSION_DEFLATE; + ret = ARCHIVE_OK; +#else + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "deflate compression not supported"); +#endif + } else if (strcmp(val, "store") == 0) { + zip->requested_compression = COMPRESSION_STORE; + ret = ARCHIVE_OK; + } + return (ret); + } else if (strcmp(key, "compression-level") == 0) { + if (val == NULL || !(val[0] >= '0' && val[0] <= '9') || val[1] != '\0') { + return ARCHIVE_WARN; + } + + if (val[0] == '0') { + zip->requested_compression = COMPRESSION_STORE; + return ARCHIVE_OK; + } else { +#ifdef HAVE_ZLIB_H + zip->requested_compression = COMPRESSION_DEFLATE; + zip->deflate_compression_level = val[0] - '0'; + return ARCHIVE_OK; +#else + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "deflate compression not supported"); +#endif + } + } else if (strcmp(key, "encryption") == 0) { + if (val == NULL) { + zip->encryption_type = ENCRYPTION_NONE; + ret = ARCHIVE_OK; + } else if (val[0] == '1' || strcmp(val, "traditional") == 0 + || strcmp(val, "zipcrypt") == 0 + || strcmp(val, "ZipCrypt") == 0) { + if (is_traditional_pkware_encryption_supported()) { + zip->encryption_type = ENCRYPTION_TRADITIONAL; + ret = ARCHIVE_OK; + } else { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "encryption not supported"); + } + } else if (strcmp(val, "aes128") == 0) { + if (is_winzip_aes_encryption_supported( + ENCRYPTION_WINZIP_AES128)) { + zip->encryption_type = ENCRYPTION_WINZIP_AES128; + ret = ARCHIVE_OK; + } else { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "encryption not supported"); + } + } else if (strcmp(val, "aes256") == 0) { + if (is_winzip_aes_encryption_supported( + ENCRYPTION_WINZIP_AES256)) { + zip->encryption_type = ENCRYPTION_WINZIP_AES256; + ret = ARCHIVE_OK; + } else { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "encryption not supported"); + } + } else { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "%s: unknown encryption '%s'", + a->format_name, val); + } + return (ret); + } else if (strcmp(key, "experimental") == 0) { + if (val == NULL || val[0] == 0) { + zip->flags &= ~ ZIP_FLAG_EXPERIMENT_xl; + } else { + zip->flags |= ZIP_FLAG_EXPERIMENT_xl; + } + return (ARCHIVE_OK); + } else if (strcmp(key, "fakecrc32") == 0) { + /* + * FOR TESTING ONLY: disable CRC calculation to speed up + * certain complex tests. + */ + if (val == NULL || val[0] == 0) { + zip->crc32func = real_crc32; + } else { + zip->crc32func = fake_crc32; + } + return (ARCHIVE_OK); + } else if (strcmp(key, "hdrcharset") == 0) { + /* + * Set the character set used in translating filenames. + */ + if (val == NULL || val[0] == 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "%s: hdrcharset option needs a character-set name", + a->format_name); + } else { + zip->opt_sconv = archive_string_conversion_to_charset( + &a->archive, val, 0); + if (zip->opt_sconv != NULL) + ret = ARCHIVE_OK; + else + ret = ARCHIVE_FATAL; + } + return (ret); + } else if (strcmp(key, "zip64") == 0) { + /* + * Bias decisions about Zip64: force them to be + * generated in certain cases where they are not + * forbidden or avoid them in certain cases where they + * are not strictly required. + */ + if (val != NULL && *val != '\0') { + zip->flags |= ZIP_FLAG_FORCE_ZIP64; + zip->flags &= ~ZIP_FLAG_AVOID_ZIP64; + } else { + zip->flags &= ~ZIP_FLAG_FORCE_ZIP64; + zip->flags |= ZIP_FLAG_AVOID_ZIP64; + } + return (ARCHIVE_OK); + } + + /* Note: The "warn" return is just to inform the options + * supervisor that we didn't handle it. It will generate + * a suitable error if no one used this option. */ + return (ARCHIVE_WARN); +} + +int +archive_write_zip_set_compression_deflate(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + int ret = ARCHIVE_FAILED; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW | ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_write_zip_set_compression_deflate"); + if (a->archive.archive_format != ARCHIVE_FORMAT_ZIP) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can only use archive_write_zip_set_compression_deflate" + " with zip format"); + ret = ARCHIVE_FATAL; + } else { +#ifdef HAVE_ZLIB_H + struct zip *zip = a->format_data; + zip->requested_compression = COMPRESSION_DEFLATE; + ret = ARCHIVE_OK; +#else + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "deflate compression not supported"); + ret = ARCHIVE_FAILED; +#endif + } + return (ret); +} + +int +archive_write_zip_set_compression_store(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct zip *zip = a->format_data; + int ret = ARCHIVE_FAILED; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW | ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, + "archive_write_zip_set_compression_deflate"); + if (a->archive.archive_format != ARCHIVE_FORMAT_ZIP) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can only use archive_write_zip_set_compression_store" + " with zip format"); + ret = ARCHIVE_FATAL; + } else { + zip->requested_compression = COMPRESSION_STORE; + ret = ARCHIVE_OK; + } + return (ret); +} + +int +archive_write_set_format_zip(struct archive *_a) +{ + struct archive_write *a = (struct archive_write *)_a; + struct zip *zip; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_NEW, "archive_write_set_format_zip"); + + /* If another format was already registered, unregister it. */ + if (a->format_free != NULL) + (a->format_free)(a); + + zip = (struct zip *) calloc(1, sizeof(*zip)); + if (zip == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate zip data"); + return (ARCHIVE_FATAL); + } + + /* "Unspecified" lets us choose the appropriate compression. */ + zip->requested_compression = COMPRESSION_UNSPECIFIED; +#ifdef HAVE_ZLIB_H + zip->deflate_compression_level = Z_DEFAULT_COMPRESSION; +#endif + zip->crc32func = real_crc32; + + /* A buffer used for both compression and encryption. */ + zip->len_buf = 65536; + zip->buf = malloc(zip->len_buf); + if (zip->buf == NULL) { + free(zip); + archive_set_error(&a->archive, ENOMEM, + "Can't allocate compression buffer"); + return (ARCHIVE_FATAL); + } + + a->format_data = zip; + a->format_name = "zip"; + a->format_options = archive_write_zip_options; + a->format_write_header = archive_write_zip_header; + a->format_write_data = archive_write_zip_data; + a->format_finish_entry = archive_write_zip_finish_entry; + a->format_close = archive_write_zip_close; + a->format_free = archive_write_zip_free; + a->archive.archive_format = ARCHIVE_FORMAT_ZIP; + a->archive.archive_format_name = "ZIP"; + + return (ARCHIVE_OK); +} + +static int +is_all_ascii(const char *p) +{ + const unsigned char *pp = (const unsigned char *)p; + + while (*pp) { + if (*pp++ > 127) + return (0); + } + return (1); +} + +static int +archive_write_zip_header(struct archive_write *a, struct archive_entry *entry) +{ + unsigned char local_header[32]; + unsigned char local_extra[144]; + struct zip *zip = a->format_data; + unsigned char *e; + unsigned char *cd_extra; + size_t filename_length; + const char *slink = NULL; + size_t slink_size = 0; + struct archive_string_conv *sconv = get_sconv(a, zip); + int ret, ret2 = ARCHIVE_OK; + mode_t type; + int version_needed = 10; + + /* Ignore types of entries that we don't support. */ + type = archive_entry_filetype(entry); + if (type != AE_IFREG && type != AE_IFDIR && type != AE_IFLNK) { + __archive_write_entry_filetype_unsupported( + &a->archive, entry, "zip"); + return ARCHIVE_FAILED; + }; + + /* If we're not using Zip64, reject large files. */ + if (zip->flags & ZIP_FLAG_AVOID_ZIP64) { + /* Reject entries over 4GB. */ + if (archive_entry_size_is_set(entry) + && (archive_entry_size(entry) > ZIP_4GB_MAX)) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Files > 4GB require Zip64 extensions"); + return ARCHIVE_FAILED; + } + /* Reject entries if archive is > 4GB. */ + if (zip->written_bytes > ZIP_4GB_MAX) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Archives > 4GB require Zip64 extensions"); + return ARCHIVE_FAILED; + } + } + + /* Only regular files can have size > 0. */ + if (type != AE_IFREG) + archive_entry_set_size(entry, 0); + + + /* Reset information from last entry. */ + zip->entry_offset = zip->written_bytes; + zip->entry_uncompressed_limit = INT64_MAX; + zip->entry_compressed_size = 0; + zip->entry_uncompressed_size = 0; + zip->entry_compressed_written = 0; + zip->entry_uncompressed_written = 0; + zip->entry_flags = 0; + zip->entry_uses_zip64 = 0; + zip->entry_crc32 = zip->crc32func(0, NULL, 0); + zip->entry_encryption = 0; + archive_entry_free(zip->entry); + zip->entry = NULL; + + if (zip->cctx_valid) + archive_encrypto_aes_ctr_release(&zip->cctx); + if (zip->hctx_valid) + archive_hmac_sha1_cleanup(&zip->hctx); + zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0; + + if (type == AE_IFREG + &&(!archive_entry_size_is_set(entry) + || archive_entry_size(entry) > 0)) { + switch (zip->encryption_type) { + case ENCRYPTION_TRADITIONAL: + case ENCRYPTION_WINZIP_AES128: + case ENCRYPTION_WINZIP_AES256: + zip->entry_flags |= ZIP_ENTRY_FLAG_ENCRYPTED; + zip->entry_encryption = zip->encryption_type; + break; + default: + break; + } + } + + +#if defined(_WIN32) && !defined(__CYGWIN__) + /* Make sure the path separators in pathname, hardlink and symlink + * are all slash '/', not the Windows path separator '\'. */ + zip->entry = __la_win_entry_in_posix_pathseparator(entry); + if (zip->entry == entry) + zip->entry = archive_entry_clone(entry); +#else + zip->entry = archive_entry_clone(entry); +#endif + if (zip->entry == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate zip header data"); + return (ARCHIVE_FATAL); + } + + if (sconv != NULL) { + const char *p; + size_t len; + + if (archive_entry_pathname_l(entry, &p, &len, sconv) != 0) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for Pathname"); + return (ARCHIVE_FATAL); + } + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + "Can't translate Pathname '%s' to %s", + archive_entry_pathname(entry), + archive_string_conversion_charset_name(sconv)); + ret2 = ARCHIVE_WARN; + } + if (len > 0) + archive_entry_set_pathname(zip->entry, p); + + /* + * There is no standard for symlink handling; we convert + * it using the same character-set translation that we use + * for filename. + */ + if (type == AE_IFLNK) { + if (archive_entry_symlink_l(entry, &p, &len, sconv)) { + if (errno == ENOMEM) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory " + " for Symlink"); + return (ARCHIVE_FATAL); + } + /* No error if we can't convert. */ + } else if (len > 0) + archive_entry_set_symlink(zip->entry, p); + } + } + + /* If filename isn't ASCII and we can use UTF-8, set the UTF-8 flag. */ + if (!is_all_ascii(archive_entry_pathname(zip->entry))) { + if (zip->opt_sconv != NULL) { + if (strcmp(archive_string_conversion_charset_name( + zip->opt_sconv), "UTF-8") == 0) + zip->entry_flags |= ZIP_ENTRY_FLAG_UTF8_NAME; +#if HAVE_NL_LANGINFO + } else if (strcmp(nl_langinfo(CODESET), "UTF-8") == 0) { + zip->entry_flags |= ZIP_ENTRY_FLAG_UTF8_NAME; +#endif + } + } + filename_length = path_length(zip->entry); + + /* Determine appropriate compression and size for this entry. */ + if (type == AE_IFLNK) { + slink = archive_entry_symlink(zip->entry); + if (slink != NULL) + slink_size = strlen(slink); + else + slink_size = 0; + zip->entry_uncompressed_limit = slink_size; + zip->entry_compressed_size = slink_size; + zip->entry_uncompressed_size = slink_size; + zip->entry_crc32 = zip->crc32func(zip->entry_crc32, + (const unsigned char *)slink, slink_size); + zip->entry_compression = COMPRESSION_STORE; + version_needed = 20; + } else if (type != AE_IFREG) { + zip->entry_compression = COMPRESSION_STORE; + zip->entry_uncompressed_limit = 0; + version_needed = 20; + } else if (archive_entry_size_is_set(zip->entry)) { + int64_t size = archive_entry_size(zip->entry); + int64_t additional_size = 0; + + zip->entry_uncompressed_limit = size; + zip->entry_compression = zip->requested_compression; + if (zip->entry_compression == COMPRESSION_UNSPECIFIED) { + zip->entry_compression = COMPRESSION_DEFAULT; + } + if (zip->entry_compression == COMPRESSION_STORE) { + zip->entry_compressed_size = size; + zip->entry_uncompressed_size = size; + version_needed = 10; + } else { + zip->entry_uncompressed_size = size; + version_needed = 20; + } + + if (zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED) { + switch (zip->entry_encryption) { + case ENCRYPTION_TRADITIONAL: + additional_size = TRAD_HEADER_SIZE; + version_needed = 20; + break; + case ENCRYPTION_WINZIP_AES128: + additional_size = WINZIP_AES128_HEADER_SIZE + + AUTH_CODE_SIZE; + version_needed = 20; + break; + case ENCRYPTION_WINZIP_AES256: + additional_size = WINZIP_AES256_HEADER_SIZE + + AUTH_CODE_SIZE; + version_needed = 20; + break; + default: + break; + } + if (zip->entry_compression == COMPRESSION_STORE) + zip->entry_compressed_size += additional_size; + } + + /* + * Set Zip64 extension in any of the following cases + * (this was suggested by discussion on info-zip-dev + * mailing list): + * = Zip64 is being forced by user + * = File is over 4GiB uncompressed + * (including encryption header, if any) + * = File is close to 4GiB and is being compressed + * (compression might make file larger) + */ + if ((zip->flags & ZIP_FLAG_FORCE_ZIP64) + || (zip->entry_uncompressed_size + additional_size > ZIP_4GB_MAX) + || (zip->entry_uncompressed_size > ZIP_4GB_MAX_UNCOMPRESSED + && zip->entry_compression != COMPRESSION_STORE)) { + zip->entry_uses_zip64 = 1; + version_needed = 45; + } + + /* We may know the size, but never the CRC. */ + zip->entry_flags |= ZIP_ENTRY_FLAG_LENGTH_AT_END; + } else { + /* We don't know the size. In this case, we prefer + * deflate (it has a clear end-of-data marker which + * makes length-at-end more reliable) and will + * enable Zip64 extensions unless we're told not to. + */ + zip->entry_compression = COMPRESSION_DEFAULT; + zip->entry_flags |= ZIP_ENTRY_FLAG_LENGTH_AT_END; + if ((zip->flags & ZIP_FLAG_AVOID_ZIP64) == 0) { + zip->entry_uses_zip64 = 1; + version_needed = 45; + } else if (zip->entry_compression == COMPRESSION_STORE) { + version_needed = 10; + } else { + version_needed = 20; + } + + if (zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED) { + switch (zip->entry_encryption) { + case ENCRYPTION_TRADITIONAL: + case ENCRYPTION_WINZIP_AES128: + case ENCRYPTION_WINZIP_AES256: + if (version_needed < 20) + version_needed = 20; + break; + default: + break; + } + } + } + + /* Format the local header. */ + memset(local_header, 0, sizeof(local_header)); + memcpy(local_header, "PK\003\004", 4); + archive_le16enc(local_header + 4, version_needed); + archive_le16enc(local_header + 6, zip->entry_flags); + if (zip->entry_encryption == ENCRYPTION_WINZIP_AES128 + || zip->entry_encryption == ENCRYPTION_WINZIP_AES256) + archive_le16enc(local_header + 8, WINZIP_AES_ENCRYPTION); + else + archive_le16enc(local_header + 8, zip->entry_compression); + archive_le32enc(local_header + 10, + dos_time(archive_entry_mtime(zip->entry))); + archive_le32enc(local_header + 14, zip->entry_crc32); + if (zip->entry_uses_zip64) { + /* Zip64 data in the local header "must" include both + * compressed and uncompressed sizes AND those fields + * are included only if these are 0xffffffff; + * THEREFORE these must be set this way, even if we + * know one of them is smaller. */ + archive_le32enc(local_header + 18, ZIP_4GB_MAX); + archive_le32enc(local_header + 22, ZIP_4GB_MAX); + } else { + archive_le32enc(local_header + 18, (uint32_t)zip->entry_compressed_size); + archive_le32enc(local_header + 22, (uint32_t)zip->entry_uncompressed_size); + } + archive_le16enc(local_header + 26, (uint16_t)filename_length); + + if (zip->entry_encryption == ENCRYPTION_TRADITIONAL) { + if (zip->entry_flags & ZIP_ENTRY_FLAG_LENGTH_AT_END) + zip->trad_chkdat = local_header[11]; + else + zip->trad_chkdat = local_header[17]; + } + + /* Format as much of central directory file header as we can: */ + zip->file_header = cd_alloc(zip, 46); + /* If (zip->file_header == NULL) XXXX */ + ++zip->central_directory_entries; + memset(zip->file_header, 0, 46); + memcpy(zip->file_header, "PK\001\002", 4); + /* "Made by PKZip 2.0 on Unix." */ + archive_le16enc(zip->file_header + 4, 3 * 256 + version_needed); + archive_le16enc(zip->file_header + 6, version_needed); + archive_le16enc(zip->file_header + 8, zip->entry_flags); + if (zip->entry_encryption == ENCRYPTION_WINZIP_AES128 + || zip->entry_encryption == ENCRYPTION_WINZIP_AES256) + archive_le16enc(zip->file_header + 10, WINZIP_AES_ENCRYPTION); + else + archive_le16enc(zip->file_header + 10, zip->entry_compression); + archive_le32enc(zip->file_header + 12, + dos_time(archive_entry_mtime(zip->entry))); + archive_le16enc(zip->file_header + 28, (uint16_t)filename_length); + /* Following Info-Zip, store mode in the "external attributes" field. */ + archive_le32enc(zip->file_header + 38, + ((uint32_t)archive_entry_mode(zip->entry)) << 16); + e = cd_alloc(zip, filename_length); + /* If (e == NULL) XXXX */ + copy_path(zip->entry, e); + + /* Format extra data. */ + memset(local_extra, 0, sizeof(local_extra)); + e = local_extra; + + /* First, extra blocks that are the same between + * the local file header and the central directory. + * We format them once and then duplicate them. */ + + /* UT timestamp, length depends on what timestamps are set. */ + memcpy(e, "UT", 2); + archive_le16enc(e + 2, + 1 + + (archive_entry_mtime_is_set(entry) ? 4 : 0) + + (archive_entry_atime_is_set(entry) ? 4 : 0) + + (archive_entry_ctime_is_set(entry) ? 4 : 0)); + e += 4; + *e++ = + (archive_entry_mtime_is_set(entry) ? 1 : 0) + | (archive_entry_atime_is_set(entry) ? 2 : 0) + | (archive_entry_ctime_is_set(entry) ? 4 : 0); + if (archive_entry_mtime_is_set(entry)) { + archive_le32enc(e, (uint32_t)archive_entry_mtime(entry)); + e += 4; + } + if (archive_entry_atime_is_set(entry)) { + archive_le32enc(e, (uint32_t)archive_entry_atime(entry)); + e += 4; + } + if (archive_entry_ctime_is_set(entry)) { + archive_le32enc(e, (uint32_t)archive_entry_ctime(entry)); + e += 4; + } + + /* ux Unix extra data, length 11, version 1 */ + /* TODO: If uid < 64k, use 2 bytes, ditto for gid. */ + memcpy(e, "ux\013\000\001", 5); + e += 5; + *e++ = 4; /* Length of following UID */ + archive_le32enc(e, (uint32_t)archive_entry_uid(entry)); + e += 4; + *e++ = 4; /* Length of following GID */ + archive_le32enc(e, (uint32_t)archive_entry_gid(entry)); + e += 4; + + /* AES extra data field: WinZIP AES information, ID=0x9901 */ + if ((zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED) + && (zip->entry_encryption == ENCRYPTION_WINZIP_AES128 + || zip->entry_encryption == ENCRYPTION_WINZIP_AES256)) { + + memcpy(e, "\001\231\007\000\001\000AE", 8); + /* AES vendor version AE-2 does not store a CRC. + * WinZip 11 uses AE-1, which does store the CRC, + * but it does not store the CRC when the file size + * is less than 20 bytes. So we simulate what + * WinZip 11 does. + * NOTE: WinZip 9.0 and 10.0 uses AE-2 by default. */ + if (archive_entry_size_is_set(zip->entry) + && archive_entry_size(zip->entry) < 20) { + archive_le16enc(e+4, AES_VENDOR_AE_2); + zip->aes_vendor = AES_VENDOR_AE_2;/* no CRC. */ + } else + zip->aes_vendor = AES_VENDOR_AE_1; + e += 8; + /* AES encryption strength. */ + *e++ = (zip->entry_encryption == ENCRYPTION_WINZIP_AES128)?1:3; + /* Actual compression method. */ + archive_le16enc(e, zip->entry_compression); + e += 2; + } + + /* Copy UT ,ux, and AES-extra into central directory as well. */ + zip->file_header_extra_offset = zip->central_directory_bytes; + cd_extra = cd_alloc(zip, e - local_extra); + memcpy(cd_extra, local_extra, e - local_extra); + + /* + * Following extra blocks vary between local header and + * central directory. These are the local header versions. + * Central directory versions get formatted in + * archive_write_zip_finish_entry() below. + */ + + /* "[Zip64 entry] in the local header MUST include BOTH + * original [uncompressed] and compressed size fields." */ + if (zip->entry_uses_zip64) { + unsigned char *zip64_start = e; + memcpy(e, "\001\000\020\000", 4); + e += 4; + archive_le64enc(e, zip->entry_uncompressed_size); + e += 8; + archive_le64enc(e, zip->entry_compressed_size); + e += 8; + archive_le16enc(zip64_start + 2, (uint16_t)(e - (zip64_start + 4))); + } + + if (zip->flags & ZIP_FLAG_EXPERIMENT_xl) { + /* Experimental 'xl' extension to improve streaming. */ + unsigned char *external_info = e; + int included = 7; + memcpy(e, "xl\000\000", 4); // 0x6c65 + 2-byte length + e += 4; + e[0] = included; /* bitmap of included fields */ + e += 1; + if (included & 1) { + archive_le16enc(e, /* "Version created by" */ + 3 * 256 + version_needed); + e += 2; + } + if (included & 2) { + archive_le16enc(e, 0); /* internal file attributes */ + e += 2; + } + if (included & 4) { + archive_le32enc(e, /* external file attributes */ + ((uint32_t)archive_entry_mode(zip->entry)) << 16); + e += 4; + } + if (included & 8) { + // Libarchive does not currently support file comments. + } + archive_le16enc(external_info + 2, (uint16_t)(e - (external_info + 4))); + } + + /* Update local header with size of extra data and write it all out: */ + archive_le16enc(local_header + 28, (uint16_t)(e - local_extra)); + + ret = __archive_write_output(a, local_header, 30); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + zip->written_bytes += 30; + + ret = write_path(zip->entry, a); + if (ret <= ARCHIVE_OK) + return (ARCHIVE_FATAL); + zip->written_bytes += ret; + + ret = __archive_write_output(a, local_extra, e - local_extra); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + zip->written_bytes += e - local_extra; + + /* For symlinks, write the body now. */ + if (slink != NULL) { + ret = __archive_write_output(a, slink, slink_size); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + zip->entry_compressed_written += slink_size; + zip->entry_uncompressed_written += slink_size; + zip->written_bytes += slink_size; + } + +#ifdef HAVE_ZLIB_H + if (zip->entry_compression == COMPRESSION_DEFLATE) { + zip->stream.zalloc = Z_NULL; + zip->stream.zfree = Z_NULL; + zip->stream.opaque = Z_NULL; + zip->stream.next_out = zip->buf; + zip->stream.avail_out = (uInt)zip->len_buf; + if (deflateInit2(&zip->stream, zip->deflate_compression_level, + Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) { + archive_set_error(&a->archive, ENOMEM, + "Can't init deflate compressor"); + return (ARCHIVE_FATAL); + } + } +#endif + + return (ret2); +} + +static ssize_t +archive_write_zip_data(struct archive_write *a, const void *buff, size_t s) +{ + int ret; + struct zip *zip = a->format_data; + + if ((int64_t)s > zip->entry_uncompressed_limit) + s = (size_t)zip->entry_uncompressed_limit; + zip->entry_uncompressed_written += s; + + if (s == 0) return 0; + + if (zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED) { + switch (zip->entry_encryption) { + case ENCRYPTION_TRADITIONAL: + /* Initialize traditional PKWARE encryption context. */ + if (!zip->tctx_valid) { + ret = init_traditional_pkware_encryption(a); + if (ret != ARCHIVE_OK) + return (ret); + zip->tctx_valid = 1; + } + break; + case ENCRYPTION_WINZIP_AES128: + case ENCRYPTION_WINZIP_AES256: + if (!zip->cctx_valid) { + ret = init_winzip_aes_encryption(a); + if (ret != ARCHIVE_OK) + return (ret); + zip->cctx_valid = zip->hctx_valid = 1; + } + break; + default: + break; + } + } + + switch (zip->entry_compression) { + case COMPRESSION_STORE: + if (zip->tctx_valid || zip->cctx_valid) { + const uint8_t *rb = (const uint8_t *)buff; + const uint8_t * const re = rb + s; + + while (rb < re) { + size_t l; + + if (zip->tctx_valid) { + l = trad_enc_encrypt_update(&zip->tctx, + rb, re - rb, + zip->buf, zip->len_buf); + } else { + l = zip->len_buf; + ret = archive_encrypto_aes_ctr_update( + &zip->cctx, + rb, re - rb, zip->buf, &l); + if (ret < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Failed to encrypt file"); + return (ARCHIVE_FAILED); + } + archive_hmac_sha1_update(&zip->hctx, + zip->buf, l); + } + ret = __archive_write_output(a, zip->buf, l); + if (ret != ARCHIVE_OK) + return (ret); + zip->entry_compressed_written += l; + zip->written_bytes += l; + rb += l; + } + } else { + ret = __archive_write_output(a, buff, s); + if (ret != ARCHIVE_OK) + return (ret); + zip->written_bytes += s; + zip->entry_compressed_written += s; + } + break; +#if HAVE_ZLIB_H + case COMPRESSION_DEFLATE: + zip->stream.next_in = (unsigned char*)(uintptr_t)buff; + zip->stream.avail_in = (uInt)s; + do { + ret = deflate(&zip->stream, Z_NO_FLUSH); + if (ret == Z_STREAM_ERROR) + return (ARCHIVE_FATAL); + if (zip->stream.avail_out == 0) { + if (zip->tctx_valid) { + trad_enc_encrypt_update(&zip->tctx, + zip->buf, zip->len_buf, + zip->buf, zip->len_buf); + } else if (zip->cctx_valid) { + size_t outl = zip->len_buf; + ret = archive_encrypto_aes_ctr_update( + &zip->cctx, + zip->buf, zip->len_buf, + zip->buf, &outl); + if (ret < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Failed to encrypt file"); + return (ARCHIVE_FAILED); + } + archive_hmac_sha1_update(&zip->hctx, + zip->buf, zip->len_buf); + } + ret = __archive_write_output(a, zip->buf, + zip->len_buf); + if (ret != ARCHIVE_OK) + return (ret); + zip->entry_compressed_written += zip->len_buf; + zip->written_bytes += zip->len_buf; + zip->stream.next_out = zip->buf; + zip->stream.avail_out = (uInt)zip->len_buf; + } + } while (zip->stream.avail_in != 0); + break; +#endif + + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid ZIP compression type"); + return ARCHIVE_FATAL; + } + + zip->entry_uncompressed_limit -= s; + if (!zip->cctx_valid || zip->aes_vendor != AES_VENDOR_AE_2) + zip->entry_crc32 = + zip->crc32func(zip->entry_crc32, buff, (unsigned)s); + return (s); + +} + +static int +archive_write_zip_finish_entry(struct archive_write *a) +{ + struct zip *zip = a->format_data; + int ret; + +#if HAVE_ZLIB_H + if (zip->entry_compression == COMPRESSION_DEFLATE) { + for (;;) { + size_t remainder; + + ret = deflate(&zip->stream, Z_FINISH); + if (ret == Z_STREAM_ERROR) + return (ARCHIVE_FATAL); + remainder = zip->len_buf - zip->stream.avail_out; + if (zip->tctx_valid) { + trad_enc_encrypt_update(&zip->tctx, + zip->buf, remainder, zip->buf, remainder); + } else if (zip->cctx_valid) { + size_t outl = remainder; + ret = archive_encrypto_aes_ctr_update( + &zip->cctx, zip->buf, remainder, + zip->buf, &outl); + if (ret < 0) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Failed to encrypt file"); + return (ARCHIVE_FAILED); + } + archive_hmac_sha1_update(&zip->hctx, + zip->buf, remainder); + } + ret = __archive_write_output(a, zip->buf, remainder); + if (ret != ARCHIVE_OK) + return (ret); + zip->entry_compressed_written += remainder; + zip->written_bytes += remainder; + zip->stream.next_out = zip->buf; + if (zip->stream.avail_out != 0) + break; + zip->stream.avail_out = (uInt)zip->len_buf; + } + deflateEnd(&zip->stream); + } +#endif + if (zip->hctx_valid) { + uint8_t hmac[20]; + size_t hmac_len = 20; + + archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len); + ret = __archive_write_output(a, hmac, AUTH_CODE_SIZE); + if (ret != ARCHIVE_OK) + return (ret); + zip->entry_compressed_written += AUTH_CODE_SIZE; + zip->written_bytes += AUTH_CODE_SIZE; + } + + /* Write trailing data descriptor. */ + if ((zip->entry_flags & ZIP_ENTRY_FLAG_LENGTH_AT_END) != 0) { + char d[24]; + memcpy(d, "PK\007\010", 4); + if (zip->cctx_valid && zip->aes_vendor == AES_VENDOR_AE_2) + archive_le32enc(d + 4, 0);/* no CRC.*/ + else + archive_le32enc(d + 4, zip->entry_crc32); + if (zip->entry_uses_zip64) { + archive_le64enc(d + 8, + (uint64_t)zip->entry_compressed_written); + archive_le64enc(d + 16, + (uint64_t)zip->entry_uncompressed_written); + ret = __archive_write_output(a, d, 24); + zip->written_bytes += 24; + } else { + archive_le32enc(d + 8, + (uint32_t)zip->entry_compressed_written); + archive_le32enc(d + 12, + (uint32_t)zip->entry_uncompressed_written); + ret = __archive_write_output(a, d, 16); + zip->written_bytes += 16; + } + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + } + + /* Append Zip64 extra data to central directory information. */ + if (zip->entry_compressed_written > ZIP_4GB_MAX + || zip->entry_uncompressed_written > ZIP_4GB_MAX + || zip->entry_offset > ZIP_4GB_MAX) { + unsigned char zip64[32]; + unsigned char *z = zip64, *zd; + memcpy(z, "\001\000\000\000", 4); + z += 4; + if (zip->entry_uncompressed_written >= ZIP_4GB_MAX) { + archive_le64enc(z, zip->entry_uncompressed_written); + z += 8; + } + if (zip->entry_compressed_written >= ZIP_4GB_MAX) { + archive_le64enc(z, zip->entry_compressed_written); + z += 8; + } + if (zip->entry_offset >= ZIP_4GB_MAX) { + archive_le64enc(z, zip->entry_offset); + z += 8; + } + archive_le16enc(zip64 + 2, (uint16_t)(z - (zip64 + 4))); + zd = cd_alloc(zip, z - zip64); + if (zd == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate zip data"); + return (ARCHIVE_FATAL); + } + memcpy(zd, zip64, z - zip64); + /* Zip64 means version needs to be set to at least 4.5 */ + if (archive_le16dec(zip->file_header + 6) < 45) + archive_le16enc(zip->file_header + 6, 45); + } + + /* Fix up central directory file header. */ + if (zip->cctx_valid && zip->aes_vendor == AES_VENDOR_AE_2) + archive_le32enc(zip->file_header + 16, 0);/* no CRC.*/ + else + archive_le32enc(zip->file_header + 16, zip->entry_crc32); + archive_le32enc(zip->file_header + 20, + (uint32_t)zipmin(zip->entry_compressed_written, + ZIP_4GB_MAX)); + archive_le32enc(zip->file_header + 24, + (uint32_t)zipmin(zip->entry_uncompressed_written, + ZIP_4GB_MAX)); + archive_le16enc(zip->file_header + 30, + (uint16_t)(zip->central_directory_bytes - zip->file_header_extra_offset)); + archive_le32enc(zip->file_header + 42, + (uint32_t)zipmin(zip->entry_offset, + ZIP_4GB_MAX)); + + return (ARCHIVE_OK); +} + +static int +archive_write_zip_close(struct archive_write *a) +{ + uint8_t buff[64]; + int64_t offset_start, offset_end; + struct zip *zip = a->format_data; + struct cd_segment *segment; + int ret; + + offset_start = zip->written_bytes; + segment = zip->central_directory; + while (segment != NULL) { + ret = __archive_write_output(a, + segment->buff, segment->p - segment->buff); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + zip->written_bytes += segment->p - segment->buff; + segment = segment->next; + } + offset_end = zip->written_bytes; + + /* If central dir info is too large, write Zip64 end-of-cd */ + if (offset_end - offset_start > ZIP_4GB_MAX + || offset_start > ZIP_4GB_MAX + || zip->central_directory_entries > 0xffffUL + || (zip->flags & ZIP_FLAG_FORCE_ZIP64)) { + /* Zip64 end-of-cd record */ + memset(buff, 0, 56); + memcpy(buff, "PK\006\006", 4); + archive_le64enc(buff + 4, 44); + archive_le16enc(buff + 12, 45); + archive_le16enc(buff + 14, 45); + /* This is disk 0 of 0. */ + archive_le64enc(buff + 24, zip->central_directory_entries); + archive_le64enc(buff + 32, zip->central_directory_entries); + archive_le64enc(buff + 40, offset_end - offset_start); + archive_le64enc(buff + 48, offset_start); + ret = __archive_write_output(a, buff, 56); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + zip->written_bytes += 56; + + /* Zip64 end-of-cd locator record. */ + memset(buff, 0, 20); + memcpy(buff, "PK\006\007", 4); + archive_le32enc(buff + 4, 0); + archive_le64enc(buff + 8, offset_end); + archive_le32enc(buff + 16, 1); + ret = __archive_write_output(a, buff, 20); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + zip->written_bytes += 20; + + } + + /* Format and write end of central directory. */ + memset(buff, 0, sizeof(buff)); + memcpy(buff, "PK\005\006", 4); + archive_le16enc(buff + 8, (uint16_t)zipmin(0xffffU, + zip->central_directory_entries)); + archive_le16enc(buff + 10, (uint16_t)zipmin(0xffffU, + zip->central_directory_entries)); + archive_le32enc(buff + 12, + (uint32_t)zipmin(ZIP_4GB_MAX, (offset_end - offset_start))); + archive_le32enc(buff + 16, + (uint32_t)zipmin(ZIP_4GB_MAX, offset_start)); + ret = __archive_write_output(a, buff, 22); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + zip->written_bytes += 22; + return (ARCHIVE_OK); +} + +static int +archive_write_zip_free(struct archive_write *a) +{ + struct zip *zip; + struct cd_segment *segment; + + zip = a->format_data; + while (zip->central_directory != NULL) { + segment = zip->central_directory; + zip->central_directory = segment->next; + free(segment->buff); + free(segment); + } + free(zip->buf); + archive_entry_free(zip->entry); + if (zip->cctx_valid) + archive_encrypto_aes_ctr_release(&zip->cctx); + if (zip->hctx_valid) + archive_hmac_sha1_cleanup(&zip->hctx); + /* TODO: Free opt_sconv, sconv_default */ + + free(zip); + a->format_data = NULL; + return (ARCHIVE_OK); +} + +/* Convert into MSDOS-style date/time. */ +static unsigned int +dos_time(const time_t unix_time) +{ + struct tm *t; + unsigned int dt; +#if defined(HAVE_LOCALTIME_R) || defined(HAVE__LOCALTIME64_S) + struct tm tmbuf; +#endif +#if defined(HAVE__LOCALTIME64_S) + errno_t terr; + __time64_t tmptime; +#endif + + /* This will not preserve time when creating/extracting the archive + * on two systems with different time zones. */ +#if defined(HAVE_LOCALTIME_R) + t = localtime_r(&unix_time, &tmbuf); +#elif defined(HAVE__LOCALTIME64_S) + tmptime = unix_time; + terr = _localtime64_s(&tmbuf, &tmptime); + if (terr) + t = NULL; + else + t = &tmbuf; +#else + t = localtime(&unix_time); +#endif + + /* MSDOS-style date/time is only between 1980-01-01 and 2107-12-31 */ + if (t->tm_year < 1980 - 1900) + /* Set minimum date/time '1980-01-01 00:00:00'. */ + dt = 0x00210000U; + else if (t->tm_year > 2107 - 1900) + /* Set maximum date/time '2107-12-31 23:59:58'. */ + dt = 0xff9fbf7dU; + else { + dt = 0; + dt += ((t->tm_year - 80) & 0x7f) << 9; + dt += ((t->tm_mon + 1) & 0x0f) << 5; + dt += (t->tm_mday & 0x1f); + dt <<= 16; + dt += (t->tm_hour & 0x1f) << 11; + dt += (t->tm_min & 0x3f) << 5; + dt += (t->tm_sec & 0x3e) >> 1; /* Only counting every 2 seconds. */ + } + return dt; +} + +static size_t +path_length(struct archive_entry *entry) +{ + mode_t type; + const char *path; + size_t len; + + type = archive_entry_filetype(entry); + path = archive_entry_pathname(entry); + + if (path == NULL) + return (0); + len = strlen(path); + if (type == AE_IFDIR && (path[0] == '\0' || path[len - 1] != '/')) + ++len; /* Space for the trailing / */ + return len; +} + +static int +write_path(struct archive_entry *entry, struct archive_write *archive) +{ + int ret; + const char *path; + mode_t type; + size_t written_bytes; + + path = archive_entry_pathname(entry); + type = archive_entry_filetype(entry); + written_bytes = 0; + + if (path == NULL) + return (ARCHIVE_FATAL); + + ret = __archive_write_output(archive, path, strlen(path)); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + written_bytes += strlen(path); + + /* Folders are recognized by a trailing slash. */ + if ((type == AE_IFDIR) & (path[strlen(path) - 1] != '/')) { + ret = __archive_write_output(archive, "/", 1); + if (ret != ARCHIVE_OK) + return (ARCHIVE_FATAL); + written_bytes += 1; + } + + return ((int)written_bytes); +} + +static void +copy_path(struct archive_entry *entry, unsigned char *p) +{ + const char *path; + size_t pathlen; + mode_t type; + + path = archive_entry_pathname(entry); + pathlen = strlen(path); + type = archive_entry_filetype(entry); + + memcpy(p, path, pathlen); + + /* Folders are recognized by a trailing slash. */ + if ((type == AE_IFDIR) && (path[pathlen - 1] != '/')) + p[pathlen] = '/'; +} + + +static struct archive_string_conv * +get_sconv(struct archive_write *a, struct zip *zip) +{ + if (zip->opt_sconv != NULL) + return (zip->opt_sconv); + + if (!zip->init_default_conversion) { + zip->sconv_default = + archive_string_default_conversion_for_write(&(a->archive)); + zip->init_default_conversion = 1; + } + return (zip->sconv_default); +} + +/* + Traditional PKWARE Decryption functions. + */ + +static void +trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c) +{ + uint8_t t; +#define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL) + + ctx->keys[0] = CRC32(ctx->keys[0], c); + ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1; + t = (ctx->keys[1] >> 24) & 0xff; + ctx->keys[2] = CRC32(ctx->keys[2], t); +#undef CRC32 +} + +static uint8_t +trad_enc_decrypt_byte(struct trad_enc_ctx *ctx) +{ + unsigned temp = ctx->keys[2] | 2; + return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff; +} + +static unsigned +trad_enc_encrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in, + size_t in_len, uint8_t *out, size_t out_len) +{ + unsigned i, max; + + max = (unsigned)((in_len < out_len)? in_len: out_len); + + for (i = 0; i < max; i++) { + uint8_t t = in[i]; + out[i] = t ^ trad_enc_decrypt_byte(ctx); + trad_enc_update_keys(ctx, t); + } + return i; +} + +static int +trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len) +{ + + ctx->keys[0] = 305419896L; + ctx->keys[1] = 591751049L; + ctx->keys[2] = 878082192L; + + for (;pw_len; --pw_len) + trad_enc_update_keys(ctx, *pw++); + return 0; +} + +static int +is_traditional_pkware_encryption_supported(void) +{ + uint8_t key[TRAD_HEADER_SIZE]; + + if (archive_random(key, sizeof(key)-1) != ARCHIVE_OK) + return (0); + return (1); +} + +static int +init_traditional_pkware_encryption(struct archive_write *a) +{ + struct zip *zip = a->format_data; + const char *passphrase; + uint8_t key[TRAD_HEADER_SIZE]; + uint8_t key_encrypted[TRAD_HEADER_SIZE]; + int ret; + + passphrase = __archive_write_get_passphrase(a); + if (passphrase == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Encryption needs passphrase"); + return ARCHIVE_FAILED; + } + if (archive_random(key, sizeof(key)-1) != ARCHIVE_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can't generate random number for encryption"); + return ARCHIVE_FATAL; + } + trad_enc_init(&zip->tctx, passphrase, strlen(passphrase)); + /* Set the last key code which will be used as a check code + * for verifying passphrase in decryption. */ + key[TRAD_HEADER_SIZE-1] = zip->trad_chkdat; + trad_enc_encrypt_update(&zip->tctx, key, TRAD_HEADER_SIZE, + key_encrypted, TRAD_HEADER_SIZE); + /* Write encrypted keys in the top of the file content. */ + ret = __archive_write_output(a, key_encrypted, TRAD_HEADER_SIZE); + if (ret != ARCHIVE_OK) + return (ret); + zip->written_bytes += TRAD_HEADER_SIZE; + zip->entry_compressed_written += TRAD_HEADER_SIZE; + return (ret); +} + +static int +init_winzip_aes_encryption(struct archive_write *a) +{ + struct zip *zip = a->format_data; + const char *passphrase; + size_t key_len, salt_len; + uint8_t salt[16 + 2]; + uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE]; + int ret; + + passphrase = __archive_write_get_passphrase(a); + if (passphrase == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Encryption needs passphrase"); + return (ARCHIVE_FAILED); + } + if (zip->entry_encryption == ENCRYPTION_WINZIP_AES128) { + salt_len = 8; + key_len = 16; + } else { + /* AES 256 */ + salt_len = 16; + key_len = 32; + } + if (archive_random(salt, salt_len) != ARCHIVE_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Can't generate random number for encryption"); + return (ARCHIVE_FATAL); + } + archive_pbkdf2_sha1(passphrase, strlen(passphrase), + salt, salt_len, 1000, derived_key, key_len * 2 + 2); + + ret = archive_encrypto_aes_ctr_init(&zip->cctx, derived_key, key_len); + if (ret != 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Decryption is unsupported due to lack of crypto library"); + return (ARCHIVE_FAILED); + } + ret = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, + key_len); + if (ret != 0) { + archive_encrypto_aes_ctr_release(&zip->cctx); + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Failed to initialize HMAC-SHA1"); + return (ARCHIVE_FAILED); + } + + /* Set a password verification value after the 'salt'. */ + salt[salt_len] = derived_key[key_len * 2]; + salt[salt_len + 1] = derived_key[key_len * 2 + 1]; + + /* Write encrypted keys in the top of the file content. */ + ret = __archive_write_output(a, salt, salt_len + 2); + if (ret != ARCHIVE_OK) + return (ret); + zip->written_bytes += salt_len + 2; + zip->entry_compressed_written += salt_len + 2; + + return (ARCHIVE_OK); +} + +static int +is_winzip_aes_encryption_supported(int encryption) +{ + size_t key_len, salt_len; + uint8_t salt[16 + 2]; + uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE]; + archive_crypto_ctx cctx; + archive_hmac_sha1_ctx hctx; + int ret; + + if (encryption == ENCRYPTION_WINZIP_AES128) { + salt_len = 8; + key_len = 16; + } else { + /* AES 256 */ + salt_len = 16; + key_len = 32; + } + if (archive_random(salt, salt_len) != ARCHIVE_OK) + return (0); + ret = archive_pbkdf2_sha1("p", 1, salt, salt_len, 1000, + derived_key, key_len * 2 + 2); + if (ret != 0) + return (0); + + ret = archive_encrypto_aes_ctr_init(&cctx, derived_key, key_len); + if (ret != 0) + return (0); + ret = archive_hmac_sha1_init(&hctx, derived_key + key_len, + key_len); + archive_encrypto_aes_ctr_release(&cctx); + if (ret != 0) + return (0); + archive_hmac_sha1_cleanup(&hctx); + return (1); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_options.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_options.3 new file mode 100644 index 0000000000..d4a52e322e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_options.3 @@ -0,0 +1,708 @@ +.\" Copyright (c) 2003-2010 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd January 31, 2020 +.Dt ARCHIVE_WRITE_OPTIONS 3 +.Os +.Sh NAME +.Nm archive_write_set_filter_option , +.Nm archive_write_set_format_option , +.Nm archive_write_set_option , +.Nm archive_write_set_options +.Nd functions controlling options for writing archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.Ft int +.Fo archive_write_set_filter_option +.Fa "struct archive *" +.Fa "const char *module" +.Fa "const char *option" +.Fa "const char *value" +.Fc +.Ft int +.Fo archive_write_set_format_option +.Fa "struct archive *" +.Fa "const char *module" +.Fa "const char *option" +.Fa "const char *value" +.Fc +.Ft int +.Fo archive_write_set_option +.Fa "struct archive *" +.Fa "const char *module" +.Fa "const char *option" +.Fa "const char *value" +.Fc +.Ft int +.Fo archive_write_set_options +.Fa "struct archive *" +.Fa "const char *options" +.Fc +.Sh DESCRIPTION +These functions provide a way for libarchive clients to configure +specific write modules. +.Bl -tag -width indent +.It Xo +.Fn archive_write_set_filter_option , +.Fn archive_write_set_format_option +.Xc +Specifies an option that will be passed to the currently-registered +filters (including decompression filters) or format readers. +.Pp +If +.Ar option +and +.Ar value +are both +.Dv NULL , +these functions will do nothing and +.Cm ARCHIVE_OK +will be returned. +If +.Ar option +is +.Dv NULL +but +.Ar value +is not, these functions will do nothing and +.Cm ARCHIVE_FAILED +will be returned. +.Pp +If +.Ar module +is not +.Dv NULL , +.Ar option +and +.Ar value +will be provided to the filter or reader named +.Ar module . +The return value will be either +.Cm ARCHIVE_OK +if the option was successfully handled or +.Cm ARCHIVE_WARN +if the option was unrecognized by the module or could otherwise +not be handled. +If there is no such module, +.Cm ARCHIVE_FAILED +will be returned. +.Pp +If +.Ar module +is +.Dv NULL , +.Ar option +and +.Ar value +will be provided to every registered module. +If any module returns +.Cm ARCHIVE_FATAL , +this value will be returned immediately. +Otherwise, +.Cm ARCHIVE_OK +will be returned if any module accepts the option, and +.Cm ARCHIVE_FAILED +in all other cases. +.\" +.It Fn archive_write_set_option +Calls +.Fn archive_write_set_format_option , +then +.Fn archive_write_set_filter_option . +If either function returns +.Cm ARCHIVE_FATAL , +.Cm ARCHIVE_FATAL +will be returned +immediately. +Otherwise, the greater of the two values will be returned. +.\" +.It Fn archive_write_set_options +.Ar options +is a comma-separated list of options. +If +.Ar options +is +.Dv NULL +or empty, +.Cm ARCHIVE_OK +will be returned immediately. +.Pp +Individual options have one of the following forms: +.Bl -tag -compact -width indent +.It Ar option=value +The option/value pair will be provided to every module. +Modules that do not accept an option with this name will ignore it. +.It Ar option +The option will be provided to every module with a value of +.Dq 1 . +.It Ar !option +The option will be provided to every module with a NULL value. +.It Ar module:option=value , Ar module:option , Ar module:!option +As above, but the corresponding option and value will be provided +only to modules whose name matches +.Ar module . +.El +.El +.\" +.Sh OPTIONS +.Bl -tag -compact -width indent +.It Filter b64encode +.Bl -tag -compact -width indent +.It Cm mode +The value is interpreted as octal digits specifying the file mode. +.It Cm name +The value specifies the file name. +.El +.It Filter bzip2 +.Bl -tag -compact -width indent +.It Cm compression-level +The value is interpreted as a decimal integer specifying the +bzip2 compression level. Supported values are from 1 to 9. +.El +.It Filter gzip +.Bl -tag -compact -width indent +.It Cm compression-level +The value is interpreted as a decimal integer specifying the +gzip compression level. Supported values are from 0 to 9. +.It Cm timestamp +Store timestamp. This is enabled by default. +.El +.It Filter lrzip +.Bl -tag -compact -width indent +.It Cm compression Ns = Ns Ar type +Use +.Ar type +as compression method. +Supported values are +.Dq bzip2 , +.Dq gzipi , +.Dq lzo +.Pq ultra fast , +and +.Dq zpaq +.Pq best, extremely slow . +.It Cm compression-level +The value is interpreted as a decimal integer specifying the +lrzip compression level. Supported values are from 1 to 9. +.El +.It Filter lz4 +.Bl -tag -compact -width indent +.It Cm compression-level +The value is interpreted as a decimal integer specifying the +lz4 compression level. Supported values are from 0 to 9. +.It Cm stream-checksum +Enable stream checksum. This is enabled by default. +.It Cm block-checksum +Enable block checksum. This is disabled by default. +.It Cm block-size +The value is interpreted as a decimal integer specifying the +lz4 compression block size. Supported values are from 4 to 7 +.Pq default . +.It Cm block-dependence +Use the previous block of the block being compressed for +a compression dictionary to improve compression ratio. +This is disabled by default. +.El +.It Filter lzop +.Bl -tag -compact -width indent +.It Cm compression-level +The value is interpreted as a decimal integer specifying the +lzop compression level. Supported values are from 1 to 9. +.El +.It Filter uuencode +.Bl -tag -compact -width indent +.It Cm mode +The value is interpreted as octal digits specifying the file mode. +.It Cm name +The value specifies the file name. +.El +.It Filter xz +.Bl -tag -compact -width indent +.It Cm compression-level +The value is interpreted as a decimal integer specifying the +compression level. Supported values are from 0 to 9. +.It Cm threads +The value is interpreted as a decimal integer specifying the +number of threads for multi-threaded lzma compression. +If supported, the default value is read from +.Fn lzma_cputhreads . +.El +.It Filter zstd +.Bl -tag -compact -width indent +.It Cm compression-level +The value is interpreted as a decimal integer specifying the +compression level. Supported values depend on the library version, +common values are from 1 to 22. +.El +.It Format 7zip +.Bl -tag -compact -width indent +.It Cm compression +The value is one of +.Dq store , +.Dq deflate , +.Dq bzip2 , +.Dq lzma1 , +.Dq lzma2 +or +.Dq ppmd +to indicate how the following entries should be compressed. +Note that this setting is ignored for directories, symbolic links, +and other special entries. +.It Cm compression-level +The value is interpreted as a decimal integer specifying the +compression level. +Values between 0 and 9 are supported. +The interpretation of the compression level depends on the chosen +compression method. +.El +.It Format cpio +.Bl -tag -compact -width indent +.It Cm hdrcharset +The value is used as a character set name that will be +used when translating file names. +.El +.It Format gnutar +.Bl -tag -compact -width indent +.It Cm hdrcharset +The value is used as a character set name that will be +used when translating file, group and user names. +.El +.It Format iso9660 - volume metadata +These options are used to set standard ISO9660 metadata. +.Bl -tag -compact -width indent +.It Cm abstract-file Ns = Ns Ar filename +The file with the specified name will be identified in the ISO9660 metadata +as holding the abstract for this volume. +Default: none. +.It Cm application-id Ns = Ns Ar filename +The file with the specified name will be identified in the ISO9660 metadata +as holding the application identifier for this volume. +Default: none. +.It Cm biblio-file Ns = Ns Ar filename +The file with the specified name will be identified in the ISO9660 metadata +as holding the bibliography for this volume. +Default: none. +.It Cm copyright-file Ns = Ns Ar filename +The file with the specified name will be identified in the ISO9660 metadata +as holding the copyright for this volume. +Default: none. +.It Cm publisher Ns = Ns Ar filename +The file with the specified name will be identified in the ISO9660 metadata +as holding the publisher information for this volume. +Default: none. +.It Cm volume-id Ns = Ns Ar string +The specified string will be used as the Volume Identifier in the ISO9660 metadata. +It is limited to 32 bytes. +Default: none. +.El +.It Format iso9660 - boot support +These options are used to make an ISO9660 image that can be directly +booted on various systems. +.Bl -tag -compact -width indent +.It Cm boot Ns = Ns Ar filename +The file matching this name will be used as the El Torito boot image file. +.It Cm boot-catalog Ns = Ns Ar name +The name that will be used for the El Torito boot catalog. +Default: +.Ar boot.catalog +.It Cm boot-info-table +The boot image file provided by the +.Cm boot Ns = Ns Ar filename +option will be edited with appropriate boot information in bytes 8 through 64. +Default: disabled +.It Cm boot-load-seg Ns = Ns Ar hexadecimal-number +The load segment for a no-emulation boot image. +.It Cm boot-load-size Ns = Ns Ar decimal-number +The number of "virtual" 512-byte sectors to be loaded from a no-emulation boot image. +Some very old BIOSes can only load very small images, setting this +value to 4 will often allow such BIOSes to load the first part of +the boot image (which will then need to be intelligent enough to +load the rest of itself). +This should not be needed unless you are trying to support systems with very old BIOSes. +This defaults to the full size of the image. +.It Cm boot-type Ns = Ns Ar value +Specifies the boot semantics used by the El Torito boot image: +If the +.Ar value +is +.Cm fd , +then the boot image is assumed to be a bootable floppy image. +If the +.Ar value +is +.Cm hd , +then the boot image is assumed to be a bootable hard disk image. +If the +.Ar value +is +.Cm no-emulation , +the boot image is used without floppy or hard disk emulation. +If the boot image is exactly 1.2MB, 1.44MB, or 2.88MB, then +the default is +.Cm fd , +otherwise the default is +.Cm no-emulation . +.El +.It Format iso9660 - filename and size extensions +Various extensions to the base ISO9660 format. +.Bl -tag -compact -width indent +.It Cm allow-ldots +If enabled, allows filenames to begin with a leading period. +If disabled, filenames that begin with a leading period will have +that period replaced by an underscore character in the standard ISO9660 +namespace. +This does not impact names stored in the Rockridge or Joliet extension area. +Default: disabled. +.It Cm allow-lowercase +If enabled, allows filenames to contain lowercase characters. +If disabled, filenames will be forced to uppercase. +This does not impact names stored in the Rockridge or Joliet extension area. +Default: disabled. +.It Cm allow-multidot +If enabled, allows filenames to contain multiple period characters, in violation of the ISO9660 specification. +If disabled, additional periods will be converted to underscore characters. +This does not impact names stored in the Rockridge or Joliet extension area. +Default: disabled. +.It Cm allow-period +If enabled, allows filenames to contain trailing period characters, in violation of the ISO9660 specification. +If disabled, trailing periods will be converted to underscore characters. +This does not impact names stored in the Rockridge or Joliet extension area. +Default: disabled. +.It Cm allow-pvd-lowercase +If enabled, the Primary Volume Descriptor may contain lowercase ASCII characters, in violation of the ISO9660 specification. +If disabled, characters will be converted to uppercase ASCII. +Default: disabled. +.It Cm allow-sharp-tilde +If enabled, sharp and tilde characters will be permitted in filenames, in violation if the ISO9660 specification. +If disabled, such characters will be converted to underscore characters. +Default: disabled. +.It Cm allow-vernum +If enabled, version numbers will be included with files. +If disabled, version numbers will be suppressed, in violation of the ISO9660 standard. +This does not impact names stored in the Rockridge or Joliet extension area. +Default: enabled. +.It Cm iso-level +This enables support for file size and file name extensions in the +core ISO9660 area. +The name extensions specified here do not affect the names stored in the Rockridge or Joliet extension areas. +.Bl -tag -compact -width indent +.It Cm iso-level=1 +The most compliant form of ISO9660 image. +Filenames are limited to 8.3 uppercase format, +directory names are limited to 8 uppercase characters, +files are limited to 4 GiB, +the complete ISO9660 image cannot exceed 4 GiB. +.It Cm iso-level=2 +Filenames are limited to 30 uppercase characters with a 30-character extension, +directory names are limited to 30 characters, +files are limited to 4 GiB. +.It Cm iso-level=3 +As with +.Cm iso-level=2 , +except that files may exceed 4 GiB. +.It Cm iso-level=4 +As with +.Cm iso-level=3 , +except that filenames may be up to 193 characters +and may include arbitrary 8-bit characters. +.El +.It Cm joliet +Microsoft's Joliet extensions store a completely separate set of directory information about each file. +In particular, this information includes Unicode filenames of up to 255 characters. +Default: enabled. +.It Cm limit-depth +If enabled, libarchive will use directory relocation records to ensure that +no pathname exceeds the ISO9660 limit of 8 directory levels. +If disabled, no relocation will occur. +Default: enabled. +.It Cm limit-dirs +If enabled, libarchive will cause an error if there are more than +65536 directories. +If disabled, there is no limit on the number of directories. +Default: enabled +.It Cm pad +If enabled, 300 kiB of zero bytes will be appended to the end of the archive. +Default: enabled +.It Cm relaxed-filenames +If enabled, all 7-bit ASCII characters are permitted in filenames +(except lowercase characters unless +.Cm allow-lowercase +is also specified). +This violates ISO9660 standards. +This does not impact names stored in the Rockridge or Joliet extension area. +Default: disabled. +.It Cm rockridge +The Rockridge extensions store an additional set of POSIX-style file +information with each file, including mtime, atime, ctime, permissions, +and long filenames with arbitrary 8-bit characters. +These extensions also support symbolic links and other POSIX file types. +Default: enabled. +.El +.It Format iso9660 - zisofs support +The zisofs extensions permit each file to be independently compressed +using a gzip-compatible compression. +This can provide significant size savings, but requires the reading +system to have support for these extensions. +These extensions are disabled by default. +.Bl -tag -compact -width indent +.It Cm compression-level Ns = Ns number +The compression level used by the deflate compressor. +Ranges from 0 (least effort) to 9 (most effort). +Default: 6 +.It Cm zisofs +Synonym for +.Cm zisofs=direct . +.It Cm zisofs=direct +Compress each file in the archive. +Unlike +.Cm zisofs=indirect , +this is handled entirely within libarchive and does not require a +separate utility. +For best results, libarchive tests each file and will store +the file uncompressed if the compression does not actually save any space. +In particular, files under 2k will never be compressed. +Note that boot image files are never compressed. +.It Cm zisofs=indirect +Recognizes files that have already been compressed with the +.Cm mkzftree +utility and sets up the necessary file metadata so that +readers will correctly identify these as zisofs-compressed files. +.It Cm zisofs-exclude Ns = Ns Ar filename +Specifies a filename that should not be compressed when using +.Cm zisofs=direct . +This option can be provided multiple times to suppress compression +on many files. +.El +.It Format mtree +.Bl -tag -compact -width indent +.It Cm cksum , Cm device , Cm flags , Cm gid , Cm gname , Cm indent , Cm link , Cm md5 , Cm mode , Cm nlink , Cm rmd160 , Cm sha1 , Cm sha256 , Cm sha384 , Cm sha512 , Cm size , Cm time , Cm uid , Cm uname +Enable a particular keyword in the mtree output. +Prefix with an exclamation mark to disable the corresponding keyword. +The default is equivalent to +.Dq device, flags, gid, gname, link, mode, nlink, size, time, type, uid, uname . +.It Cm all +Enables all of the above keywords. +.It Cm use-set +Enables generation of +.Cm /set +lines that specify default values for the following files and/or directories. +.It Cm indent +XXX needs explanation XXX +.El +.It Format newc +.Bl -tag -compact -width indent +.It Cm hdrcharset +The value is used as a character set name that will be +used when translating file names. +.El +.It Format pax +.Bl -tag -compact -width indent +.It Cm hdrcharset +The value is used as a character set name that will be +used when translating file, group and user names. +The value is one of +.Dq BINARY +or +.Dq UTF-8 . +With +.Dq BINARY +there is no character conversion, with +.Dq UTF-8 +names are converted to UTF-8. +.It Cm xattrheader +When storing extended attributes, this option configures which +headers should be written. The value is one of +.Dq all , +.Dq LIBARCHIVE , +or +.Dq SCHILY . +By default, both +.Dq LIBARCHIVE.xattr +and +.Dq SCHILY.xattr +headers are written. +.El +.It Format ustar +.Bl -tag -compact -width indent +.It Cm hdrcharset +The value is used as a character set name that will be +used when translating file, group and user names. +.El +.It Format v7tar +.Bl -tag -compact -width indent +.It Cm hdrcharset +The value is used as a character set name that will be +used when translating file, group and user names. +.El +.It Format warc +.Bl -tag -compact -width indent +.It Cm omit-warcinfo +Set to +.Dq true +to disable output of the warcinfo record. +.El +.It Format xar +.Bl -tag -compact -width indent +.It Cm checksum Ns = Ns Ar type +Use +.Ar type +as file checksum method. +Supported values are +.Dq none , +.Dq md5 , +and +.Dq sha1 +.Pq default . +.It Cm compression Ns = Ns Ar type +Use +.Ar type +as compression method. +Supported values are +.Dq none , +.Dq bzip2 , +.Dq gzip +.Pq default , +.Dq lzma +and +.Dq xz . +.It Cm compression_level +The value is a decimal integer from 1 to 9 specifying the compression level. +.It Cm toc-checksum Ns = Ns Ar type +Use +.Ar type +as table of contents checksum method. +Supported values are +.Dq none , +.Dq md5 +and +.Dq sha1 +.Pq default . +.El +.It Format zip +.Bl -tag -compact -width indent +.It Cm compression +The value is either +.Dq store +or +.Dq deflate +to indicate how the following entries should be compressed. +Note that this setting is ignored for directories, symbolic links, +and other special entries. +.It Cm compression-level +The value is interpreted as a decimal integer specifying the +compression level. +Values between 0 and 9 are supported. +A compression level of 0 switches the compression method to +.Dq store , +other values will enable +.Dq deflate +compression with the given level. +.It Cm encryption +Enable encryption using traditional zip encryption. +.It Cm encryption Ns = Ns Ar type +Use +.Ar type +as encryption type. +Supported values are +.Dq zipcrypt +.Pq traditional zip encryption , +.Dq aes128 +.Pq WinZip AES-128 encryption +and +.Dq aes256 +.Pq WinZip AES-256 encryption . +.It Cm experimental +This boolean option enables or disables experimental Zip features +that may not be compatible with other Zip implementations. +.It Cm fakecrc32 +This boolean option disables CRC calculations. +All CRC fields are set to zero. +It should not be used except for testing purposes. +.It Cm hdrcharset +The value is used as a character set name that will be +used when translating file names. +.It Cm zip64 +Zip64 extensions provide additional file size information +for entries larger than 4 GiB. +They also provide extended file offset and archive size information +when archives exceed 4 GiB. +By default, the Zip writer selectively enables these extensions only as needed. +In particular, if the file size is unknown, the Zip writer will +include Zip64 extensions to guard against the possibility that the +file might be larger than 4 GiB. +.Pp +Setting this boolean option will force the writer to use Zip64 extensions +even for small files that would not otherwise require them. +This is primarily useful for testing. +.Pp +Disabling this option with +.Cm !zip64 +will force the Zip writer to avoid Zip64 extensions: +It will reject files with size greater than 4 GiB, +it will reject any new entries once the total archive size reaches 4 GiB, +and it will not use Zip64 extensions for files with unknown size. +In particular, this can improve compatibility when generating archives +where the entry sizes are not known in advance. +.El +.El +.Sh EXAMPLES +The following example creates an archive write handle to +create a gzip-compressed ISO9660 format image. +The two options here specify that the ISO9660 archive will use +.Ar kernel.img +as the boot image for El Torito booting, and that the gzip +compressor should use the maximum compression level. +.Bd -literal -offset indent +a = archive_write_new(); +archive_write_add_filter_gzip(a); +archive_write_set_format_iso9660(a); +archive_write_set_options(a, "boot=kernel.img,compression=9"); +archive_write_open_filename(a, filename, blocksize); +.Ed +.\" +.Sh ERRORS +More detailed error codes and textual descriptions are available from the +.Fn archive_errno +and +.Fn archive_error_string +functions. +.\" +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_read_set_options 3 , +.Xr archive_write 3 , +.Xr libarchive 3 +.Sh HISTORY +The +.Nm libarchive +library first appeared in +.Fx 5.3 . +.Sh AUTHORS +.An -nosplit +The options support for libarchive was originally implemented by +.An Michihiro NAKAJIMA . +.Sh BUGS diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_options.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_options.c new file mode 100644 index 0000000000..962309ada5 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_options.c @@ -0,0 +1,130 @@ +/*- + * Copyright (c) 2003-2010 Tim Kientzle + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#include "archive_write_private.h" +#include "archive_options_private.h" + +static int archive_set_format_option(struct archive *a, + const char *m, const char *o, const char *v); +static int archive_set_filter_option(struct archive *a, + const char *m, const char *o, const char *v); +static int archive_set_option(struct archive *a, + const char *m, const char *o, const char *v); + +int +archive_write_set_format_option(struct archive *a, const char *m, const char *o, + const char *v) +{ + return _archive_set_option(a, m, o, v, + ARCHIVE_WRITE_MAGIC, "archive_write_set_format_option", + archive_set_format_option); +} + +int +archive_write_set_filter_option(struct archive *a, const char *m, const char *o, + const char *v) +{ + return _archive_set_option(a, m, o, v, + ARCHIVE_WRITE_MAGIC, "archive_write_set_filter_option", + archive_set_filter_option); +} + +int +archive_write_set_option(struct archive *a, const char *m, const char *o, + const char *v) +{ + return _archive_set_option(a, m, o, v, + ARCHIVE_WRITE_MAGIC, "archive_write_set_option", + archive_set_option); +} + +int +archive_write_set_options(struct archive *a, const char *options) +{ + return _archive_set_options(a, options, + ARCHIVE_WRITE_MAGIC, "archive_write_set_options", + archive_set_option); +} + +static int +archive_set_format_option(struct archive *_a, const char *m, const char *o, + const char *v) +{ + struct archive_write *a = (struct archive_write *)_a; + + if (a->format_name == NULL) + return (m == NULL)?ARCHIVE_FAILED:ARCHIVE_WARN - 1; + /* If the format name didn't match, return a special code for + * _archive_set_option[s]. */ + if (m != NULL && strcmp(m, a->format_name) != 0) + return (ARCHIVE_WARN - 1); + if (a->format_options == NULL) + return (ARCHIVE_WARN); + return a->format_options(a, o, v); +} + +static int +archive_set_filter_option(struct archive *_a, const char *m, const char *o, + const char *v) +{ + struct archive_write *a = (struct archive_write *)_a; + struct archive_write_filter *filter; + int r, rv = ARCHIVE_WARN; + + for (filter = a->filter_first; filter != NULL; filter = filter->next_filter) { + if (filter->options == NULL) + continue; + if (m != NULL && strcmp(filter->name, m) != 0) + continue; + + r = filter->options(filter, o, v); + + if (r == ARCHIVE_FATAL) + return (ARCHIVE_FATAL); + + if (m != NULL) + return (r); + + if (r == ARCHIVE_OK) + rv = ARCHIVE_OK; + } + /* If the filter name didn't match, return a special code for + * _archive_set_option[s]. */ + if (rv == ARCHIVE_WARN && m != NULL) + rv = ARCHIVE_WARN - 1; + return (rv); +} + +static int +archive_set_option(struct archive *a, const char *m, const char *o, + const char *v) +{ + return _archive_set_either_option(a, m, o, v, + archive_set_format_option, + archive_set_filter_option); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_passphrase.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_passphrase.3 new file mode 100644 index 0000000000..2db77034c7 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_passphrase.3 @@ -0,0 +1,74 @@ +.\" Copyright (c) 2014 Michihiro NAKAJIMA +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd September 21, 2014 +.Dt ARCHIVE_WRITE_SET_PASSPHRASE 3 +.Os +.Sh NAME +.Nm archive_write_set_passphrase , +.Nm archive_write_set_passphrase_callback +.Nd functions for writing encrypted archives +.Sh LIBRARY +Streaming Archive Library (libarchive, -larchive) +.Sh SYNOPSIS +.In archive.h +.Ft int +.Fo archive_write_set_passphrase +.Fa "struct archive *" +.Fa "const char *passphrase" +.Fc +.Ft int +.Fo archive_write_set_passphrase_callback +.Fa "struct archive *" +.Fa "void *client_data" +.Fa "archive_passphrase_callback *" +.Fc +.Sh DESCRIPTION +.Bl -tag -width indent +.It Fn archive_write_set_passphrase +Set a passphrase for writing an encrypted archive. +If +.Ar passphrase +is +.Dv NULL +or empty, this function will do nothing and +.Cm ARCHIVE_FAILED +will be returned. +Otherwise, +.Cm ARCHIVE_OK +will be returned. +.It Fn archive_write_set_passphrase_callback +Register a callback function that will be invoked to get a passphrase +for encryption if the passphrase was not set by the +.Fn archive_write_set_passphrase +function. +.El +.\" .Sh ERRORS +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_write 3 , +.Xr archive_write_set_options 3 , +.Xr libarchive 3 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_passphrase.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_passphrase.c new file mode 100644 index 0000000000..710ecba52c --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_write_set_passphrase.c @@ -0,0 +1,95 @@ +/*- + * Copyright (c) 2014 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" +__FBSDID("$FreeBSD$"); + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include "archive_write_private.h" + +int +archive_write_set_passphrase(struct archive *_a, const char *p) +{ + struct archive_write *a = (struct archive_write *)_a; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, ARCHIVE_STATE_NEW, + "archive_write_set_passphrase"); + + if (p == NULL || p[0] == '\0') { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Empty passphrase is unacceptable"); + return (ARCHIVE_FAILED); + } + free(a->passphrase); + a->passphrase = strdup(p); + if (a->passphrase == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate data for passphrase"); + return (ARCHIVE_FATAL); + } + return (ARCHIVE_OK); +} + + +int +archive_write_set_passphrase_callback(struct archive *_a, void *client_data, + archive_passphrase_callback *cb) +{ + struct archive_write *a = (struct archive_write *)_a; + + archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, ARCHIVE_STATE_NEW, + "archive_write_set_passphrase_callback"); + + a->passphrase_callback = cb; + a->passphrase_client_data = client_data; + return (ARCHIVE_OK); +} + + +const char * +__archive_write_get_passphrase(struct archive_write *a) +{ + + if (a->passphrase != NULL) + return (a->passphrase); + + if (a->passphrase_callback != NULL) { + const char *p; + p = a->passphrase_callback(&a->archive, + a->passphrase_client_data); + if (p != NULL) { + a->passphrase = strdup(p); + if (a->passphrase == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate data for passphrase"); + return (NULL); + } + return (a->passphrase); + } + } + return (NULL); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_xxhash.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_xxhash.h new file mode 100644 index 0000000000..1c7131ca1e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/archive_xxhash.h @@ -0,0 +1,48 @@ +/*- + * Copyright (c) 2014 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + * + */ + +#ifndef ARCHIVE_XXHASH_H_INCLUDED +#define ARCHIVE_XXHASH_H_INCLUDED + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + + +typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode; + +struct archive_xxhash { + unsigned int (*XXH32)(const void* input, unsigned int len, + unsigned int seed); + void* (*XXH32_init)(unsigned int seed); + XXH_errorcode (*XXH32_update)(void* state, const void* input, + unsigned int len); + unsigned int (*XXH32_digest)(void* state); +}; + +extern const struct archive_xxhash __archive_xxhash; + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/config_freebsd.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/config_freebsd.h new file mode 100644 index 0000000000..f16fd3495e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/config_freebsd.h @@ -0,0 +1,260 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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. + * + * $FreeBSD$ + */ + +#include <osreldate.h> + +/* FreeBSD 5.0 and later has ACL and extattr support. */ +#if __FreeBSD__ > 4 +#define ARCHIVE_ACL_FREEBSD 1 +#define HAVE_ACL_GET_PERM_NP 1 +#define HAVE_ARC4RANDOM_BUF 1 +#define HAVE_EXTATTR_GET_FILE 1 +#define HAVE_EXTATTR_LIST_FILE 1 +#define HAVE_EXTATTR_SET_FD 1 +#define HAVE_EXTATTR_SET_FILE 1 +#define HAVE_STRUCT_XVFSCONF 1 +#define HAVE_SYS_ACL_H 1 +#define HAVE_SYS_EXTATTR_H 1 +#if __FreeBSD__ > 7 +/* FreeBSD 8.0 and later has NFSv4 ACL support */ +#define ARCHIVE_ACL_FREEBSD_NFS4 1 +#define HAVE_ACL_GET_LINK_NP 1 +#define HAVE_ACL_IS_TRIVIAL_NP 1 +#define HAVE_ACL_SET_LINK_NP 1 +#endif /* __FreeBSD__ > 7 */ +#endif /* __FreeBSD__ > 4 */ + +#ifdef WITH_OPENSSL +#define HAVE_LIBCRYPTO 1 +#define HAVE_OPENSSL_EVP_H 1 +#define HAVE_OPENSSL_MD5_H 1 +#define HAVE_OPENSSL_RIPEMD_H 1 +#define HAVE_OPENSSL_SHA_H 1 +#define HAVE_OPENSSL_SHA256_INIT 1 +#define HAVE_OPENSSL_SHA384_INIT 1 +#define HAVE_OPENSSL_SHA512_INIT 1 +#define HAVE_PKCS5_PBKDF2_HMAC_SHA1 1 +#define HAVE_SHA256 1 +#define HAVE_SHA384 1 +#define HAVE_SHA512 1 +#else +#define HAVE_LIBMD 1 +#define HAVE_MD5_H 1 +#define HAVE_MD5INIT 1 +#define HAVE_RIPEMD_H 1 +#define HAVE_SHA_H 1 +#define HAVE_SHA1 1 +#define HAVE_SHA1_INIT 1 +#define HAVE_SHA256 1 +#define HAVE_SHA256_H 1 +#define HAVE_SHA256_INIT 1 +#define HAVE_SHA512 1 +#define HAVE_SHA512_H 1 +#define HAVE_SHA512_INIT 1 +#endif + +#define HAVE_BSDXML_H 1 +#define HAVE_BZLIB_H 1 +#define HAVE_CHFLAGS 1 +#define HAVE_CHOWN 1 +#define HAVE_CHROOT 1 +#define HAVE_CTIME_R 1 +#define HAVE_CTYPE_H 1 +#define HAVE_DECL_EXTATTR_NAMESPACE_USER 1 +#define HAVE_DECL_INT32_MAX 1 +#define HAVE_DECL_INT32_MIN 1 +#define HAVE_DECL_INT64_MAX 1 +#define HAVE_DECL_INT64_MIN 1 +#define HAVE_DECL_INTMAX_MAX 1 +#define HAVE_DECL_INTMAX_MIN 1 +#define HAVE_DECL_SIZE_MAX 1 +#define HAVE_DECL_SSIZE_MAX 1 +#define HAVE_DECL_STRERROR_R 1 +#define HAVE_DECL_UINT32_MAX 1 +#define HAVE_DECL_UINT64_MAX 1 +#define HAVE_DECL_UINTMAX_MAX 1 +#define HAVE_DIRENT_H 1 +#define HAVE_DLFCN_H 1 +#define HAVE_D_MD_ORDER 1 +#define HAVE_EFTYPE 1 +#define HAVE_EILSEQ 1 +#define HAVE_ERRNO_H 1 +#define HAVE_FCHDIR 1 +#define HAVE_FCHFLAGS 1 +#define HAVE_FCHMOD 1 +#define HAVE_FCHOWN 1 +#define HAVE_FCNTL 1 +#define HAVE_FCNTL_H 1 +#define HAVE_FDOPENDIR 1 +#define HAVE_FORK 1 +#define HAVE_FSEEKO 1 +#define HAVE_FSTAT 1 +#define HAVE_FSTATAT 1 +#define HAVE_FSTATFS 1 +#define HAVE_FSTATVFS 1 +#define HAVE_FTRUNCATE 1 +#define HAVE_FUTIMES 1 +#define HAVE_FUTIMESAT 1 +#define HAVE_GETEUID 1 +#define HAVE_GETGRGID_R 1 +#define HAVE_GETGRNAM_R 1 +#define HAVE_GETPID 1 +#define HAVE_GETPWNAM_R 1 +#define HAVE_GETPWUID_R 1 +#define HAVE_GETVFSBYNAME 1 +#define HAVE_GMTIME_R 1 +#define HAVE_GRP_H 1 +#define HAVE_INTMAX_T 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LANGINFO_H 1 +#define HAVE_LCHFLAGS 1 +#define HAVE_LCHMOD 1 +#define HAVE_LCHOWN 1 +#define HAVE_LIBZ 1 +#define HAVE_LIMITS_H 1 +#define HAVE_LINK 1 +#define HAVE_LOCALE_H 1 +#define HAVE_LOCALTIME_R 1 +#define HAVE_LONG_LONG_INT 1 +#define HAVE_LSTAT 1 +#define HAVE_LUTIMES 1 +#define HAVE_MBRTOWC 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMORY_H 1 +#define HAVE_MEMSET 1 +#define HAVE_MKDIR 1 +#define HAVE_MKFIFO 1 +#define HAVE_MKNOD 1 +#define HAVE_MKSTEMP 1 +#define HAVE_NL_LANGINFO 1 +#define HAVE_OPENAT 1 +#define HAVE_PATHS_H 1 +#define HAVE_PIPE 1 +#define HAVE_POLL 1 +#define HAVE_POLL_H 1 +#define HAVE_POSIX_SPAWNP 1 +#define HAVE_PTHREAD_H 1 +#define HAVE_PWD_H 1 +#define HAVE_READDIR_R 1 +#define HAVE_READLINK 1 +#define HAVE_READLINKAT 1 +#define HAVE_READPASSPHRASE 1 +#define HAVE_READPASSPHRASE_H 1 +#define HAVE_REGEX_H 1 +#define HAVE_SELECT 1 +#define HAVE_SETENV 1 +#define HAVE_SETLOCALE 1 +#define HAVE_SIGACTION 1 +#define HAVE_SIGNAL_H 1 +#define HAVE_SPAWN_H 1 +#define HAVE_STATFS 1 +#define HAVE_STATVFS 1 +#define HAVE_STDARG_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STRCHR 1 +#define HAVE_STRDUP 1 +#define HAVE_STRERROR 1 +#define HAVE_STRERROR_R 1 +#define HAVE_STRFTIME 1 +#define HAVE_STRINGS_H 1 +#define HAVE_STRING_H 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRUCT_STATFS_F_NAMEMAX 1 +#define HAVE_STRUCT_STAT_ST_BIRTHTIME 1 +#define HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC 1 +#define HAVE_STRUCT_STAT_ST_BLKSIZE 1 +#define HAVE_STRUCT_STAT_ST_FLAGS 1 +#define HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC 1 +#define HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC 1 +#define HAVE_STRUCT_TM_TM_GMTOFF 1 +#define HAVE_SYMLINK 1 +#define HAVE_SYS_CDEFS_H 1 +#define HAVE_SYS_IOCTL_H 1 +#define HAVE_SYS_MOUNT_H 1 +#define HAVE_SYS_PARAM_H 1 +#define HAVE_SYS_POLL_H 1 +#define HAVE_SYS_SELECT_H 1 +#define HAVE_SYS_STATVFS_H 1 +#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_TIME_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_SYS_UTSNAME_H 1 +#define HAVE_SYS_WAIT_H 1 +#define HAVE_TIMEGM 1 +#define HAVE_TIME_H 1 +#define HAVE_TZSET 1 +#define HAVE_UINTMAX_T 1 +#define HAVE_UNISTD_H 1 +#define HAVE_UNLINKAT 1 +#define HAVE_UNSETENV 1 +#define HAVE_UNSIGNED_LONG_LONG 1 +#define HAVE_UNSIGNED_LONG_LONG_INT 1 +#define HAVE_UTIME 1 +#define HAVE_UTIMES 1 +#define HAVE_UTIME_H 1 +#define HAVE_VFORK 1 +#define HAVE_VPRINTF 1 +#define HAVE_WCHAR_H 1 +#define HAVE_WCHAR_T 1 +#define HAVE_WCRTOMB 1 +#define HAVE_WCSCMP 1 +#define HAVE_WCSCPY 1 +#define HAVE_WCSLEN 1 +#define HAVE_WCTOMB 1 +#define HAVE_WCTYPE_H 1 +#define HAVE_WMEMCMP 1 +#define HAVE_WMEMCPY 1 +#define HAVE_WMEMMOVE 1 +#define HAVE_ZLIB_H 1 +#define TIME_WITH_SYS_TIME 1 + +#if __FreeBSD_version >= 1100056 +#define HAVE_FUTIMENS 1 +#define HAVE_UTIMENSAT 1 +#endif + +/* FreeBSD 4 and earlier lack intmax_t/uintmax_t */ +#if __FreeBSD__ < 5 +#define intmax_t int64_t +#define uintmax_t uint64_t +#endif + +/* FreeBSD defines for archive_hash.h */ +#ifdef WITH_OPENSSL +#define ARCHIVE_CRYPTO_MD5_OPENSSL 1 +#define ARCHIVE_CRYPTO_RMD160_OPENSSL 1 +#define ARCHIVE_CRYPTO_SHA1_OPENSSL +#define ARCHIVE_CRYPTO_SHA256_OPENSSL 1 +#define ARCHIVE_CRYPTO_SHA384_OPENSSL 1 +#define ARCHIVE_CRYPTO_SHA512_OPENSSL 1 +#else +#define ARCHIVE_CRYPTO_MD5_LIBMD 1 +#define ARCHIVE_CRYPTO_SHA1_LIBMD 1 +#define ARCHIVE_CRYPTO_SHA256_LIBMD 1 +#define ARCHIVE_CRYPTO_SHA512_LIBMD 1 +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/cpio.5 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/cpio.5 new file mode 100644 index 0000000000..a91f0c596d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/cpio.5 @@ -0,0 +1,325 @@ +.\" Copyright (c) 2007 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd December 23, 2011 +.Dt CPIO 5 +.Os +.Sh NAME +.Nm cpio +.Nd format of cpio archive files +.Sh DESCRIPTION +The +.Nm +archive format collects any number of files, directories, and other +file system objects (symbolic links, device nodes, etc.) into a single +stream of bytes. +.Ss General Format +Each file system object in a +.Nm +archive comprises a header record with basic numeric metadata +followed by the full pathname of the entry and the file data. +The header record stores a series of integer values that generally +follow the fields in +.Va struct stat . +(See +.Xr stat 2 +for details.) +The variants differ primarily in how they store those integers +(binary, octal, or hexadecimal). +The header is followed by the pathname of the +entry (the length of the pathname is stored in the header) +and any file data. +The end of the archive is indicated by a special record with +the pathname +.Dq TRAILER!!! . +.Ss PWB format +XXX Any documentation of the original PWB/UNIX 1.0 format? XXX +.Ss Old Binary Format +The old binary +.Nm +format stores numbers as 2-byte and 4-byte binary values. +Each entry begins with a header in the following format: +.Bd -literal -offset indent +struct header_old_cpio { + unsigned short c_magic; + unsigned short c_dev; + unsigned short c_ino; + unsigned short c_mode; + unsigned short c_uid; + unsigned short c_gid; + unsigned short c_nlink; + unsigned short c_rdev; + unsigned short c_mtime[2]; + unsigned short c_namesize; + unsigned short c_filesize[2]; +}; +.Ed +.Pp +The +.Va unsigned short +fields here are 16-bit integer values; the +.Va unsigned int +fields are 32-bit integer values. +The fields are as follows +.Bl -tag -width indent +.It Va magic +The integer value octal 070707. +This value can be used to determine whether this archive is +written with little-endian or big-endian integers. +.It Va dev , Va ino +The device and inode numbers from the disk. +These are used by programs that read +.Nm +archives to determine when two entries refer to the same file. +Programs that synthesize +.Nm +archives should be careful to set these to distinct values for each entry. +.It Va mode +The mode specifies both the regular permissions and the file type. +It consists of several bit fields as follows: +.Bl -tag -width "MMMMMMM" -compact +.It 0170000 +This masks the file type bits. +.It 0140000 +File type value for sockets. +.It 0120000 +File type value for symbolic links. +For symbolic links, the link body is stored as file data. +.It 0100000 +File type value for regular files. +.It 0060000 +File type value for block special devices. +.It 0040000 +File type value for directories. +.It 0020000 +File type value for character special devices. +.It 0010000 +File type value for named pipes or FIFOs. +.It 0004000 +SUID bit. +.It 0002000 +SGID bit. +.It 0001000 +Sticky bit. +On some systems, this modifies the behavior of executables and/or directories. +.It 0000777 +The lower 9 bits specify read/write/execute permissions +for world, group, and user following standard POSIX conventions. +.El +.It Va uid , Va gid +The numeric user id and group id of the owner. +.It Va nlink +The number of links to this file. +Directories always have a value of at least two here. +Note that hardlinked files include file data with every copy in the archive. +.It Va rdev +For block special and character special entries, +this field contains the associated device number. +For all other entry types, it should be set to zero by writers +and ignored by readers. +.It Va mtime +Modification time of the file, indicated as the number +of seconds since the start of the epoch, +00:00:00 UTC January 1, 1970. +The four-byte integer is stored with the most-significant 16 bits first +followed by the least-significant 16 bits. +Each of the two 16 bit values are stored in machine-native byte order. +.It Va namesize +The number of bytes in the pathname that follows the header. +This count includes the trailing NUL byte. +.It Va filesize +The size of the file. +Note that this archive format is limited to +four gigabyte file sizes. +See +.Va mtime +above for a description of the storage of four-byte integers. +.El +.Pp +The pathname immediately follows the fixed header. +If the +.Cm namesize +is odd, an additional NUL byte is added after the pathname. +The file data is then appended, padded with NUL +bytes to an even length. +.Pp +Hardlinked files are not given special treatment; +the full file contents are included with each copy of the +file. +.Ss Portable ASCII Format +.St -susv2 +standardized an ASCII variant that is portable across all +platforms. +It is commonly known as the +.Dq old character +format or as the +.Dq odc +format. +It stores the same numeric fields as the old binary format, but +represents them as 6-character or 11-character octal values. +.Bd -literal -offset indent +struct cpio_odc_header { + char c_magic[6]; + char c_dev[6]; + char c_ino[6]; + char c_mode[6]; + char c_uid[6]; + char c_gid[6]; + char c_nlink[6]; + char c_rdev[6]; + char c_mtime[11]; + char c_namesize[6]; + char c_filesize[11]; +}; +.Ed +.Pp +The fields are identical to those in the old binary format. +The name and file body follow the fixed header. +Unlike the old binary format, there is no additional padding +after the pathname or file contents. +If the files being archived are themselves entirely ASCII, then +the resulting archive will be entirely ASCII, except for the +NUL byte that terminates the name field. +.Ss New ASCII Format +The "new" ASCII format uses 8-byte hexadecimal fields for +all numbers and separates device numbers into separate fields +for major and minor numbers. +.Bd -literal -offset indent +struct cpio_newc_header { + char c_magic[6]; + char c_ino[8]; + char c_mode[8]; + char c_uid[8]; + char c_gid[8]; + char c_nlink[8]; + char c_mtime[8]; + char c_filesize[8]; + char c_devmajor[8]; + char c_devminor[8]; + char c_rdevmajor[8]; + char c_rdevminor[8]; + char c_namesize[8]; + char c_check[8]; +}; +.Ed +.Pp +Except as specified below, the fields here match those specified +for the old binary format above. +.Bl -tag -width indent +.It Va magic +The string +.Dq 070701 . +.It Va check +This field is always set to zero by writers and ignored by readers. +See the next section for more details. +.El +.Pp +The pathname is followed by NUL bytes so that the total size +of the fixed header plus pathname is a multiple of four. +Likewise, the file data is padded to a multiple of four bytes. +Note that this format supports only 4 gigabyte files (unlike the +older ASCII format, which supports 8 gigabyte files). +.Pp +In this format, hardlinked files are handled by setting the +filesize to zero for each entry except the first one that +appears in the archive. +.Ss New CRC Format +The CRC format is identical to the new ASCII format described +in the previous section except that the magic field is set +to +.Dq 070702 +and the +.Va check +field is set to the sum of all bytes in the file data. +This sum is computed treating all bytes as unsigned values +and using unsigned arithmetic. +Only the least-significant 32 bits of the sum are stored. +.Ss HP variants +The +.Nm cpio +implementation distributed with HPUX used XXXX but stored +device numbers differently XXX. +.Ss Other Extensions and Variants +Sun Solaris uses additional file types to store extended file +data, including ACLs and extended attributes, as special +entries in cpio archives. +.Pp +XXX Others? XXX +.Sh SEE ALSO +.Xr cpio 1 , +.Xr tar 5 +.Sh STANDARDS +The +.Nm cpio +utility is no longer a part of POSIX or the Single Unix Standard. +It last appeared in +.St -susv2 . +It has been supplanted in subsequent standards by +.Xr pax 1 . +The portable ASCII format is currently part of the specification for the +.Xr pax 1 +utility. +.Sh HISTORY +The original cpio utility was written by Dick Haight +while working in AT&T's Unix Support Group. +It appeared in 1977 as part of PWB/UNIX 1.0, the +.Dq Programmer's Work Bench +derived from +.At v6 +that was used internally at AT&T. +Both the old binary and old character formats were in use +by 1980, according to the System III source released +by SCO under their +.Dq Ancient Unix +license. +The character format was adopted as part of +.St -p1003.1-88 . +XXX when did "newc" appear? Who invented it? When did HP come out with their variant? When did Sun introduce ACLs and extended attributes? XXX +.Sh BUGS +The +.Dq CRC +format is mis-named, as it uses a simple checksum and +not a cyclic redundancy check. +.Pp +The old binary format is limited to 16 bits for user id, +group id, device, and inode numbers. +It is limited to 4 gigabyte file sizes. +.Pp +The old ASCII format is limited to 18 bits for +the user id, group id, device, and inode numbers. +It is limited to 8 gigabyte file sizes. +.Pp +The new ASCII format is limited to 4 gigabyte file sizes. +.Pp +None of the cpio formats store user or group names, +which are essential when moving files between systems with +dissimilar user or group numbering. +.Pp +Especially when writing older cpio variants, it may be necessary +to map actual device/inode values to synthesized values that +fit the available fields. +With very large filesystems, this may be necessary even for +the newer formats. diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/filter_fork.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/filter_fork.h new file mode 100644 index 0000000000..2bf290c4d9 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/filter_fork.h @@ -0,0 +1,46 @@ +/*- + * Copyright (c) 2007 Joerg Sonnenberger + * 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(S) ``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(S) 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. + * + * $FreeBSD: head/lib/libarchive/filter_fork.h 201087 2009-12-28 02:18:26Z kientzle $ + */ + +#ifndef FILTER_FORK_H +#define FILTER_FORK_H + +#ifndef __LIBARCHIVE_BUILD +#error This header is only to be used internally to libarchive. +#endif + +int +__archive_create_child(const char *cmd, int *child_stdin, int *child_stdout, +#if defined(_WIN32) && !defined(__CYGWIN__) + HANDLE *out_child); +#else + pid_t *out_child); +#endif + +void +__archive_check_child(int in, int out); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/filter_fork_posix.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/filter_fork_posix.c new file mode 100644 index 0000000000..ac255c4f8b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/filter_fork_posix.c @@ -0,0 +1,240 @@ +/*- + * Copyright (c) 2007 Joerg Sonnenberger + * Copyright (c) 2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +/* This capability is only available on POSIX systems. */ +#if defined(HAVE_PIPE) && defined(HAVE_FCNTL) && \ + (defined(HAVE_FORK) || defined(HAVE_VFORK) || defined(HAVE_POSIX_SPAWNP)) + +__FBSDID("$FreeBSD: head/lib/libarchive/filter_fork.c 182958 2008-09-12 05:33:00Z kientzle $"); + +#if defined(HAVE_SYS_TYPES_H) +# include <sys/types.h> +#endif +#ifdef HAVE_ERRNO_H +# include <errno.h> +#endif +#ifdef HAVE_STRING_H +# include <string.h> +#endif +#if defined(HAVE_POLL) && (defined(HAVE_POLL_H) || defined(HAVE_SYS_POLL_H)) +# if defined(HAVE_POLL_H) +# include <poll.h> +# elif defined(HAVE_SYS_POLL_H) +# include <sys/poll.h> +# endif +#elif defined(HAVE_SELECT) +# if defined(HAVE_SYS_SELECT_H) +# include <sys/select.h> +# elif defined(HAVE_UNISTD_H) +# include <unistd.h> +# endif +#endif +#ifdef HAVE_FCNTL_H +# include <fcntl.h> +#endif +#ifdef HAVE_SPAWN_H +# include <spawn.h> +#endif +#ifdef HAVE_STDLIB_H +# include <stdlib.h> +#endif +#ifdef HAVE_UNISTD_H +# include <unistd.h> +#endif + +#include "archive.h" +#include "archive_cmdline_private.h" + +#include "filter_fork.h" + +int +__archive_create_child(const char *cmd, int *child_stdin, int *child_stdout, + pid_t *out_child) +{ + pid_t child; + int stdin_pipe[2], stdout_pipe[2], tmp; +#if HAVE_POSIX_SPAWNP + posix_spawn_file_actions_t actions; + int r; +#endif + struct archive_cmdline *cmdline; + + cmdline = __archive_cmdline_allocate(); + if (cmdline == NULL) + goto state_allocated; + if (__archive_cmdline_parse(cmdline, cmd) != ARCHIVE_OK) + goto state_allocated; + + if (pipe(stdin_pipe) == -1) + goto state_allocated; + if (stdin_pipe[0] == 1 /* stdout */) { + if ((tmp = dup(stdin_pipe[0])) == -1) + goto stdin_opened; + close(stdin_pipe[0]); + stdin_pipe[0] = tmp; + } + if (pipe(stdout_pipe) == -1) + goto stdin_opened; + if (stdout_pipe[1] == 0 /* stdin */) { + if ((tmp = dup(stdout_pipe[1])) == -1) + goto stdout_opened; + close(stdout_pipe[1]); + stdout_pipe[1] = tmp; + } + +#if HAVE_POSIX_SPAWNP + + r = posix_spawn_file_actions_init(&actions); + if (r != 0) { + errno = r; + goto stdout_opened; + } + r = posix_spawn_file_actions_addclose(&actions, stdin_pipe[1]); + if (r != 0) + goto actions_inited; + r = posix_spawn_file_actions_addclose(&actions, stdout_pipe[0]); + if (r != 0) + goto actions_inited; + /* Setup for stdin. */ + r = posix_spawn_file_actions_adddup2(&actions, stdin_pipe[0], 0); + if (r != 0) + goto actions_inited; + if (stdin_pipe[0] != 0 /* stdin */) { + r = posix_spawn_file_actions_addclose(&actions, stdin_pipe[0]); + if (r != 0) + goto actions_inited; + } + /* Setup for stdout. */ + r = posix_spawn_file_actions_adddup2(&actions, stdout_pipe[1], 1); + if (r != 0) + goto actions_inited; + if (stdout_pipe[1] != 1 /* stdout */) { + r = posix_spawn_file_actions_addclose(&actions, stdout_pipe[1]); + if (r != 0) + goto actions_inited; + } + r = posix_spawnp(&child, cmdline->path, &actions, NULL, + cmdline->argv, NULL); + if (r != 0) + goto actions_inited; + posix_spawn_file_actions_destroy(&actions); + +#else /* HAVE_POSIX_SPAWNP */ + +#if HAVE_VFORK + child = vfork(); +#else + child = fork(); +#endif + if (child == -1) + goto stdout_opened; + if (child == 0) { + close(stdin_pipe[1]); + close(stdout_pipe[0]); + if (dup2(stdin_pipe[0], 0 /* stdin */) == -1) + _exit(254); + if (stdin_pipe[0] != 0 /* stdin */) + close(stdin_pipe[0]); + if (dup2(stdout_pipe[1], 1 /* stdout */) == -1) + _exit(254); + if (stdout_pipe[1] != 1 /* stdout */) + close(stdout_pipe[1]); + execvp(cmdline->path, cmdline->argv); + _exit(254); + } +#endif /* HAVE_POSIX_SPAWNP */ + + close(stdin_pipe[0]); + close(stdout_pipe[1]); + + *child_stdin = stdin_pipe[1]; + fcntl(*child_stdin, F_SETFL, O_NONBLOCK); + *child_stdout = stdout_pipe[0]; + fcntl(*child_stdout, F_SETFL, O_NONBLOCK); + __archive_cmdline_free(cmdline); + + *out_child = child; + return ARCHIVE_OK; + +#if HAVE_POSIX_SPAWNP +actions_inited: + errno = r; + posix_spawn_file_actions_destroy(&actions); +#endif +stdout_opened: + close(stdout_pipe[0]); + close(stdout_pipe[1]); +stdin_opened: + close(stdin_pipe[0]); + close(stdin_pipe[1]); +state_allocated: + __archive_cmdline_free(cmdline); + return ARCHIVE_FAILED; +} + +void +__archive_check_child(int in, int out) +{ +#if defined(HAVE_POLL) && (defined(HAVE_POLL_H) || defined(HAVE_SYS_POLL_H)) + struct pollfd fds[2]; + int idx; + + idx = 0; + if (in != -1) { + fds[idx].fd = in; + fds[idx].events = POLLOUT; + ++idx; + } + if (out != -1) { + fds[idx].fd = out; + fds[idx].events = POLLIN; + ++idx; + } + + poll(fds, idx, -1); /* -1 == INFTIM, wait forever */ +#elif defined(HAVE_SELECT) + fd_set fds_in, fds_out, fds_error; + + FD_ZERO(&fds_in); + FD_ZERO(&fds_out); + FD_ZERO(&fds_error); + if (out != -1) { + FD_SET(out, &fds_in); + FD_SET(out, &fds_error); + } + if (in != -1) { + FD_SET(in, &fds_out); + FD_SET(in, &fds_error); + } + select(in < out ? out + 1 : in + 1, &fds_in, &fds_out, &fds_error, NULL); +#else + sleep(1); +#endif +} + +#endif /* defined(HAVE_PIPE) && defined(HAVE_VFORK) && defined(HAVE_FCNTL) */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/filter_fork_windows.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/filter_fork_windows.c new file mode 100644 index 0000000000..8d11179f30 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/filter_fork_windows.c @@ -0,0 +1,199 @@ +/*- + * Copyright (c) 2009-2012 Michihiro NAKAJIMA + * 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(S) ``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(S) 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. + */ + +#include "archive_platform.h" + +#if defined(_WIN32) && !defined(__CYGWIN__) +#include "archive_cmdline_private.h" +#include "archive_string.h" + +#include "filter_fork.h" + +int +__archive_create_child(const char *cmd, int *child_stdin, int *child_stdout, + HANDLE *out_child) +{ + HANDLE childStdout[2], childStdin[2],childStderr; + SECURITY_ATTRIBUTES secAtts; + STARTUPINFOA staInfo; + PROCESS_INFORMATION childInfo; + struct archive_string cmdline; + struct archive_string fullpath; + struct archive_cmdline *acmd; + char *arg0, *ext; + int i, l; + DWORD fl, fl_old; + HANDLE child; + + childStdout[0] = childStdout[1] = INVALID_HANDLE_VALUE; + childStdin[0] = childStdin[1] = INVALID_HANDLE_VALUE; + childStderr = INVALID_HANDLE_VALUE; + archive_string_init(&cmdline); + archive_string_init(&fullpath); + + acmd = __archive_cmdline_allocate(); + if (acmd == NULL) + goto fail; + if (__archive_cmdline_parse(acmd, cmd) != ARCHIVE_OK) + goto fail; + + /* + * Search the full path of 'path'. + * NOTE: This does not need if we give CreateProcessA 'path' as + * a part of the cmdline and give CreateProcessA NULL as first + * parameter, but I do not like that way. + */ + ext = strrchr(acmd->path, '.'); + if (ext == NULL || strlen(ext) > 4) + /* 'path' does not have a proper extension, so we have to + * give SearchPath() ".exe" as the extension. */ + ext = ".exe"; + else + ext = NULL;/* 'path' has an extension. */ + + fl = MAX_PATH; + do { + if (archive_string_ensure(&fullpath, fl) == NULL) + goto fail; + fl_old = fl; + fl = SearchPathA(NULL, acmd->path, ext, fl, fullpath.s, + &arg0); + } while (fl != 0 && fl > fl_old); + if (fl == 0) + goto fail; + + /* + * Make a command line. + */ + for (l = 0, i = 0; acmd->argv[i] != NULL; i++) { + if (i == 0) + continue; + l += (int)strlen(acmd->argv[i]) + 1; + } + if (archive_string_ensure(&cmdline, l + 1) == NULL) + goto fail; + for (i = 0; acmd->argv[i] != NULL; i++) { + if (i == 0) { + const char *p, *sp; + + if ((p = strchr(acmd->argv[i], '/')) != NULL || + (p = strchr(acmd->argv[i], '\\')) != NULL) + p++; + else + p = acmd->argv[i]; + if ((sp = strchr(p, ' ')) != NULL) + archive_strappend_char(&cmdline, '"'); + archive_strcat(&cmdline, p); + if (sp != NULL) + archive_strappend_char(&cmdline, '"'); + } else { + archive_strappend_char(&cmdline, ' '); + archive_strcat(&cmdline, acmd->argv[i]); + } + } + if (i <= 1) { + const char *sp; + + if ((sp = strchr(arg0, ' ')) != NULL) + archive_strappend_char(&cmdline, '"'); + archive_strcat(&cmdline, arg0); + if (sp != NULL) + archive_strappend_char(&cmdline, '"'); + } + + secAtts.nLength = sizeof(SECURITY_ATTRIBUTES); + secAtts.bInheritHandle = TRUE; + secAtts.lpSecurityDescriptor = NULL; + if (CreatePipe(&childStdout[0], &childStdout[1], &secAtts, 0) == 0) + goto fail; + if (!SetHandleInformation(childStdout[0], HANDLE_FLAG_INHERIT, 0)) + goto fail; + if (CreatePipe(&childStdin[0], &childStdin[1], &secAtts, 0) == 0) + goto fail; + if (!SetHandleInformation(childStdin[1], HANDLE_FLAG_INHERIT, 0)) + goto fail; + if (DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_ERROR_HANDLE), + GetCurrentProcess(), &childStderr, 0, TRUE, + DUPLICATE_SAME_ACCESS) == 0) + goto fail; + + memset(&staInfo, 0, sizeof(staInfo)); + staInfo.cb = sizeof(staInfo); + staInfo.hStdError = childStderr; + staInfo.hStdOutput = childStdout[1]; + staInfo.hStdInput = childStdin[0]; + staInfo.wShowWindow = SW_HIDE; + staInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; + if (CreateProcessA(fullpath.s, cmdline.s, NULL, NULL, TRUE, 0, + NULL, NULL, &staInfo, &childInfo) == 0) + goto fail; + WaitForInputIdle(childInfo.hProcess, INFINITE); + CloseHandle(childInfo.hProcess); + CloseHandle(childInfo.hThread); + + *child_stdout = _open_osfhandle((intptr_t)childStdout[0], _O_RDONLY); + *child_stdin = _open_osfhandle((intptr_t)childStdin[1], _O_WRONLY); + + child = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, + childInfo.dwProcessId); + if (child == NULL) // INVALID_HANDLE_VALUE ? + goto fail; + + *out_child = child; + + CloseHandle(childStdout[1]); + CloseHandle(childStdin[0]); + + archive_string_free(&cmdline); + archive_string_free(&fullpath); + __archive_cmdline_free(acmd); + return ARCHIVE_OK; + +fail: + if (childStdout[0] != INVALID_HANDLE_VALUE) + CloseHandle(childStdout[0]); + if (childStdout[1] != INVALID_HANDLE_VALUE) + CloseHandle(childStdout[1]); + if (childStdin[0] != INVALID_HANDLE_VALUE) + CloseHandle(childStdin[0]); + if (childStdin[1] != INVALID_HANDLE_VALUE) + CloseHandle(childStdin[1]); + if (childStderr != INVALID_HANDLE_VALUE) + CloseHandle(childStderr); + archive_string_free(&cmdline); + archive_string_free(&fullpath); + __archive_cmdline_free(acmd); + return ARCHIVE_FAILED; +} + +void +__archive_check_child(int in, int out) +{ + (void)in; /* UNUSED */ + (void)out; /* UNUSED */ + Sleep(100); +} + +#endif /* _WIN32 && !__CYGWIN__ */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/libarchive-formats.5 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/libarchive-formats.5 new file mode 100644 index 0000000000..62359ddc20 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/libarchive-formats.5 @@ -0,0 +1,465 @@ +.\" Copyright (c) 2003-2009 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd December 27, 2016 +.Dt LIBARCHIVE-FORMATS 5 +.Os +.Sh NAME +.Nm libarchive-formats +.Nd archive formats supported by the libarchive library +.Sh DESCRIPTION +The +.Xr libarchive 3 +library reads and writes a variety of streaming archive formats. +Generally speaking, all of these archive formats consist of a series of +.Dq entries . +Each entry stores a single file system object, such as a file, directory, +or symbolic link. +.Pp +The following provides a brief description of each format supported +by libarchive, with some information about recognized extensions or +limitations of the current library support. +Note that just because a format is supported by libarchive does not +imply that a program that uses libarchive will support that format. +Applications that use libarchive specify which formats they wish +to support, though many programs do use libarchive convenience +functions to enable all supported formats. +.Ss Tar Formats +The +.Xr libarchive 3 +library can read most tar archives. +It can write POSIX-standard +.Dq ustar +and +.Dq pax interchange +formats as well as v7 tar format and a subset of the legacy GNU tar format. +.Pp +All tar formats store each entry in one or more 512-byte records. +The first record is used for file metadata, including filename, +timestamp, and mode information, and the file data is stored in +subsequent records. +Later variants have extended this by either appropriating undefined +areas of the header record, extending the header to multiple records, +or by storing special entries that modify the interpretation of +subsequent entries. +.Bl -tag -width indent +.It Cm gnutar +The +.Xr libarchive 3 +library can read most GNU-format tar archives. +It currently supports the most popular GNU extensions, including +modern long filename and linkname support, as well as atime and ctime data. +The libarchive library does not support multi-volume +archives, nor the old GNU long filename format. +It can read GNU sparse file entries, including the new POSIX-based +formats. +.Pp +The +.Xr libarchive 3 +library can write GNU tar format, including long filename +and linkname support, as well as atime and ctime data. +.It Cm pax +The +.Xr libarchive 3 +library can read and write POSIX-compliant pax interchange format +archives. +Pax interchange format archives are an extension of the older ustar +format that adds a separate entry with additional attributes stored +as key/value pairs immediately before each regular entry. +The presence of these additional entries is the only difference between +pax interchange format and the older ustar format. +The extended attributes are of unlimited length and are stored +as UTF-8 Unicode strings. +Keywords defined in the standard are in all lowercase; vendors are allowed +to define custom keys by preceding them with the vendor name in all uppercase. +When writing pax archives, libarchive uses many of the SCHILY keys +defined by Joerg Schilling's +.Dq star +archiver and a few LIBARCHIVE keys. +The libarchive library can read most of the SCHILY keys +and most of the GNU keys introduced by GNU tar. +It silently ignores any keywords that it does not understand. +.Pp +The pax interchange format converts filenames to Unicode +and stores them using the UTF-8 encoding. +Prior to libarchive 3.0, libarchive erroneously assumed +that the system wide-character routines natively supported +Unicode. +This caused it to mis-handle non-ASCII filenames on systems +that did not satisfy this assumption. +.It Cm restricted pax +The libarchive library can also write pax archives in which it +attempts to suppress the extended attributes entry whenever +possible. +The result will be identical to a ustar archive unless the +extended attributes entry is required to store a long file +name, long linkname, extended ACL, file flags, or if any of the standard +ustar data (user name, group name, UID, GID, etc) cannot be fully +represented in the ustar header. +In all cases, the result can be dearchived by any program that +can read POSIX-compliant pax interchange format archives. +Programs that correctly read ustar format (see below) will also be +able to read this format; any extended attributes will be extracted as +separate files stored in +.Pa PaxHeader +directories. +.It Cm ustar +The libarchive library can both read and write this format. +This format has the following limitations: +.Bl -bullet -compact +.It +Device major and minor numbers are limited to 21 bits. +Nodes with larger numbers will not be added to the archive. +.It +Path names in the archive are limited to 255 bytes. +(Shorter if there is no / character in exactly the right place.) +.It +Symbolic links and hard links are stored in the archive with +the name of the referenced file. +This name is limited to 100 bytes. +.It +Extended attributes, file flags, and other extended +security information cannot be stored. +.It +Archive entries are limited to 8 gigabytes in size. +.El +Note that the pax interchange format has none of these restrictions. +The ustar format is old and widely supported. +It is recommended when compatibility is the primary concern. +.It Cm v7 +The libarchive library can read and write the legacy v7 tar format. +This format has the following limitations: +.Bl -bullet -compact +.It +Only regular files, directories, and symbolic links can be archived. +Block and character device nodes, FIFOs, and sockets cannot be archived. +.It +Path names in the archive are limited to 100 bytes. +.It +Symbolic links and hard links are stored in the archive with +the name of the referenced file. +This name is limited to 100 bytes. +.It +User and group information are stored as numeric IDs; there +is no provision for storing user or group names. +.It +Extended attributes, file flags, and other extended +security information cannot be stored. +.It +Archive entries are limited to 8 gigabytes in size. +.El +Generally, users should prefer the ustar format for portability +as the v7 tar format is both less useful and less portable. +.El +.Pp +The libarchive library also reads a variety of commonly-used extensions to +the basic tar format. +These extensions are recognized automatically whenever they appear. +.Bl -tag -width indent +.It Numeric extensions. +The POSIX standards require fixed-length numeric fields to be written with +some character position reserved for terminators. +Libarchive allows these fields to be written without terminator characters. +This extends the allowable range; in particular, ustar archives with this +extension can support entries up to 64 gigabytes in size. +Libarchive also recognizes base-256 values in most numeric fields. +This essentially removes all limitations on file size, modification time, +and device numbers. +.It Solaris extensions +Libarchive recognizes ACL and extended attribute records written +by Solaris tar. +.El +.Pp +The first tar program appeared in Seventh Edition Unix in 1979. +The first official standard for the tar file format was the +.Dq ustar +(Unix Standard Tar) format defined by POSIX in 1988. +POSIX.1-2001 extended the ustar format to create the +.Dq pax interchange +format. +.Ss Cpio Formats +The libarchive library can read a number of common cpio variants and can write +.Dq odc +and +.Dq newc +format archives. +A cpio archive stores each entry as a fixed-size header followed +by a variable-length filename and variable-length data. +Unlike the tar format, the cpio format does only minimal padding +of the header or file data. +There are several cpio variants, which differ primarily in +how they store the initial header: some store the values as +octal or hexadecimal numbers in ASCII, others as binary values of +varying byte order and length. +.Bl -tag -width indent +.It Cm binary +The libarchive library transparently reads both big-endian and little-endian +variants of the original binary cpio format. +This format used 32-bit binary values for file size and mtime, +and 16-bit binary values for the other fields. +.It Cm odc +The libarchive library can both read and write this +POSIX-standard format, which is officially known as the +.Dq cpio interchange format +or the +.Dq octet-oriented cpio archive format +and sometimes unofficially referred to as the +.Dq old character format . +This format stores the header contents as octal values in ASCII. +It is standard, portable, and immune from byte-order confusion. +File sizes and mtime are limited to 33 bits (8GB file size), +other fields are limited to 18 bits. +.It Cm SVR4/newc +The libarchive library can read both CRC and non-CRC variants of +this format. +The SVR4 format uses eight-digit hexadecimal values for +all header fields. +This limits file size to 4GB, and also limits the mtime and +other fields to 32 bits. +The SVR4 format can optionally include a CRC of the file +contents, although libarchive does not currently verify this CRC. +.El +.Pp +Cpio first appeared in PWB/UNIX 1.0, which was released within +AT&T in 1977. +PWB/UNIX 1.0 formed the basis of System III Unix, released outside +of AT&T in 1981. +This makes cpio older than tar, although cpio was not included +in Version 7 AT&T Unix. +As a result, the tar command became much better known in universities +and research groups that used Version 7. +The combination of the +.Nm find +and +.Nm cpio +utilities provided very precise control over file selection. +Unfortunately, the format has many limitations that make it unsuitable +for widespread use. +Only the POSIX format permits files over 4GB, and its 18-bit +limit for most other fields makes it unsuitable for modern systems. +In addition, cpio formats only store numeric UID/GID values (not +usernames and group names), which can make it very difficult to correctly +transfer archives across systems with dissimilar user numbering. +.Ss Shar Formats +A +.Dq shell archive +is a shell script that, when executed on a POSIX-compliant +system, will recreate a collection of file system objects. +The libarchive library can write two different kinds of shar archives: +.Bl -tag -width indent +.It Cm shar +The traditional shar format uses a limited set of POSIX +commands, including +.Xr echo 1 , +.Xr mkdir 1 , +and +.Xr sed 1 . +It is suitable for portably archiving small collections of plain text files. +However, it is not generally well-suited for large archives +(many implementations of +.Xr sh 1 +have limits on the size of a script) nor should it be used with non-text files. +.It Cm shardump +This format is similar to shar but encodes files using +.Xr uuencode 1 +so that the result will be a plain text file regardless of the file contents. +It also includes additional shell commands that attempt to reproduce as +many file attributes as possible, including owner, mode, and flags. +The additional commands used to restore file attributes make +shardump archives less portable than plain shar archives. +.El +.Ss ISO9660 format +Libarchive can read and extract from files containing ISO9660-compliant +CDROM images. +In many cases, this can remove the need to burn a physical CDROM +just in order to read the files contained in an ISO9660 image. +It also avoids security and complexity issues that come with +virtual mounts and loopback devices. +Libarchive supports the most common Rockridge extensions and has partial +support for Joliet extensions. +If both extensions are present, the Joliet extensions will be +used and the Rockridge extensions will be ignored. +In particular, this can create problems with hardlinks and symlinks, +which are supported by Rockridge but not by Joliet. +.Pp +Libarchive reads ISO9660 images using a streaming strategy. +This allows it to read compressed images directly +(decompressing on the fly) and allows it to read images +directly from network sockets, pipes, and other non-seekable +data sources. +This strategy works well for optimized ISO9660 images created +by many popular programs. +Such programs collect all directory information at the beginning +of the ISO9660 image so it can be read from a physical disk +with a minimum of seeking. +However, not all ISO9660 images can be read in this fashion. +.Pp +Libarchive can also write ISO9660 images. +Such images are fully optimized with the directory information +preceding all file data. +This is done by storing all file data to a temporary file +while collecting directory information in memory. +When the image is finished, libarchive writes out the +directory structure followed by the file data. +The location used for the temporary file can be changed +by the usual environment variables. +.Ss Zip format +Libarchive can read and write zip format archives that have +uncompressed entries and entries compressed with the +.Dq deflate +algorithm. +Other zip compression algorithms are not supported. +It can extract jar archives, archives that use Zip64 extensions and +self-extracting zip archives. +Libarchive can use either of two different strategies for +reading Zip archives: +a streaming strategy which is fast and can handle extremely +large archives, and a seeking strategy which can correctly +process self-extracting Zip archives and archives with +deleted members or other in-place modifications. +.Pp +The streaming reader processes Zip archives as they are read. +It can read archives of arbitrary size from tape or +network sockets, and can decode Zip archives that have +been separately compressed or encoded. +However, self-extracting Zip archives and archives with +certain types of modifications cannot be correctly +handled. +Such archives require that the reader first process the +Central Directory, which is ordinarily located +at the end of a Zip archive and is thus inaccessible +to the streaming reader. +If the program using libarchive has enabled seek support, then +libarchive will use this to processes the central directory first. +.Pp +In particular, the seeking reader must be used to +correctly handle self-extracting archives. +Such archives consist of a program followed by a regular +Zip archive. +The streaming reader cannot parse the initial program +portion, but the seeking reader starts by reading the +Central Directory from the end of the archive. +Similarly, Zip archives that have been modified in-place +can have deleted entries or other garbage data that +can only be accurately detected by first reading the +Central Directory. +.Ss Archive (library) file format +The Unix archive format (commonly created by the +.Xr ar 1 +archiver) is a general-purpose format which is +used almost exclusively for object files to be +read by the link editor +.Xr ld 1 . +The ar format has never been standardised. +There are two common variants: +the GNU format derived from SVR4, +and the BSD format, which first appeared in 4.4BSD. +The two differ primarily in their handling of filenames +longer than 15 characters: +the GNU/SVR4 variant writes a filename table at the beginning of the archive; +the BSD format stores each long filename in an extension +area adjacent to the entry. +Libarchive can read both extensions, +including archives that may include both types of long filenames. +Programs using libarchive can write GNU/SVR4 format +if they provide an entry called +.Pa // +containing a filename table to be written into the archive +before any of the entries. +Any entries whose names are not in the filename table +will be written using BSD-style long filenames. +This can cause problems for programs such as +GNU ld that do not support the BSD-style long filenames. +.Ss mtree +Libarchive can read and write files in +.Xr mtree 5 +format. +This format is not a true archive format, but rather a textual description +of a file hierarchy in which each line specifies the name of a file and +provides specific metadata about that file. +Libarchive can read all of the keywords supported by both +the NetBSD and FreeBSD versions of +.Xr mtree 8 , +although many of the keywords cannot currently be stored in an +.Tn archive_entry +object. +When writing, libarchive supports use of the +.Xr archive_write_set_options 3 +interface to specify which keywords should be included in the +output. +If libarchive was compiled with access to suitable +cryptographic libraries (such as the OpenSSL libraries), +it can compute hash entries such as +.Cm sha512 +or +.Cm md5 +from file data being written to the mtree writer. +.Pp +When reading an mtree file, libarchive will locate the corresponding +files on disk using the +.Cm contents +keyword if present or the regular filename. +If it can locate and open the file on disk, it will use that +to fill in any metadata that is missing from the mtree file +and will read the file contents and return those to the program +using libarchive. +If it cannot locate and open the file on disk, libarchive +will return an error for any attempt to read the entry +body. +.Ss 7-Zip +Libarchive can read and write 7-Zip format archives. +TODO: Need more information +.Ss CAB +Libarchive can read Microsoft Cabinet ( +.Dq CAB ) +format archives. +TODO: Need more information. +.Ss LHA +TODO: Information about libarchive's LHA support +.Ss RAR +Libarchive has limited support for reading RAR format archives. +Currently, libarchive can read RARv3 format archives +which have been either created uncompressed, or compressed using +any of the compression methods supported by the RARv3 format. +Libarchive can also read self-extracting RAR archives. +.Ss Warc +Libarchive can read and write +.Dq web archives . +TODO: Need more information +.Ss XAR +Libarchive can read and write the XAR format used by many Apple tools. +TODO: Need more information +.Sh SEE ALSO +.Xr ar 1 , +.Xr cpio 1 , +.Xr mkisofs 1 , +.Xr shar 1 , +.Xr tar 1 , +.Xr zip 1 , +.Xr zlib 3 , +.Xr cpio 5 , +.Xr mtree 5 , +.Xr tar 5 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/libarchive.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/libarchive.3 new file mode 100644 index 0000000000..c6894d2d4f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/libarchive.3 @@ -0,0 +1,289 @@ +.\" Copyright (c) 2003-2007 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd March 18, 2012 +.Dt LIBARCHIVE 3 +.Os +.Sh NAME +.Nm libarchive +.Nd functions for reading and writing streaming archives +.Sh OVERVIEW +The +.Nm +library provides a flexible interface for reading and writing +archives in various formats such as tar and cpio. +.Nm +also supports reading and writing archives compressed using +various compression filters such as gzip and bzip2. +The library is inherently stream-oriented; readers serially iterate through +the archive, writers serially add things to the archive. +In particular, note that there is currently no built-in support for +random access nor for in-place modification. +.Pp +When reading an archive, the library automatically detects the +format and the compression. +The library currently has read support for: +.Bl -bullet -compact +.It +old-style tar archives, +.It +most variants of the POSIX +.Dq ustar +format, +.It +the POSIX +.Dq pax interchange +format, +.It +GNU-format tar archives, +.It +most common cpio archive formats, +.It +ISO9660 CD images (including RockRidge and Joliet extensions), +.It +Zip archives, +.It +ar archives (including GNU/SysV and BSD extensions), +.It +Microsoft CAB archives, +.It +LHA archives, +.It +mtree file tree descriptions, +.It +RAR archives, +.It +XAR archives. +.El +The library automatically detects archives compressed with +.Xr gzip 1 , +.Xr bzip2 1 , +.Xr xz 1 , +.Xr lzip 1 , +or +.Xr compress 1 +and decompresses them transparently. +It can similarly detect and decode archives processed with +.Xr uuencode 1 +or which have an +.Xr rpm 1 +header. +.Pp +When writing an archive, you can specify the compression +to be used and the format to use. +The library can write +.Bl -bullet -compact +.It +POSIX-standard +.Dq ustar +archives, +.It +POSIX +.Dq pax interchange format +archives, +.It +POSIX octet-oriented cpio archives, +.It +Zip archive, +.It +two different variants of shar archives, +.It +ISO9660 CD images, +.It +7-Zip archives, +.It +ar archives, +.It +mtree file tree descriptions, +.It +XAR archives. +.El +Pax interchange format is an extension of the tar archive format that +eliminates essentially all of the limitations of historic tar formats +in a standard fashion that is supported +by POSIX-compliant +.Xr pax 1 +implementations on many systems as well as several newer implementations of +.Xr tar 1 . +Note that the default write format will suppress the pax extended +attributes for most entries; explicitly requesting pax format will +enable those attributes for all entries. +.Pp +The read and write APIs are accessed through the +.Fn archive_read_XXX +functions and the +.Fn archive_write_XXX +functions, respectively, and either can be used independently +of the other. +.Pp +The rest of this manual page provides an overview of the library +operation. +More detailed information can be found in the individual manual +pages for each API or utility function. +.\" +.Sh READING AN ARCHIVE +See +.Xr archive_read 3 . +.\" +.Sh WRITING AN ARCHIVE +See +.Xr archive_write 3 . +.\" +.Sh WRITING ENTRIES TO DISK +The +.Xr archive_write_disk 3 +API allows you to write +.Xr archive_entry 3 +objects to disk using the same API used by +.Xr archive_write 3 . +The +.Xr archive_write_disk 3 +API is used internally by +.Fn archive_read_extract ; +using it directly can provide greater control over how entries +get written to disk. +This API also makes it possible to share code between +archive-to-archive copy and archive-to-disk extraction +operations. +.Sh READING ENTRIES FROM DISK +The +.Xr archive_read_disk 3 +supports for populating +.Xr archive_entry 3 +objects from information in the filesystem. +This includes the information accessible from the +.Xr stat 2 +system call as well as ACLs, extended attributes, +and other metadata. +The +.Xr archive_read_disk 3 +API also supports iterating over directory trees, +which allows directories of files to be read using +an API compatible with +the +.Xr archive_read 3 +API. +.Sh DESCRIPTION +Detailed descriptions of each function are provided by the +corresponding manual pages. +.Pp +All of the functions utilize an opaque +.Tn struct archive +datatype that provides access to the archive contents. +.Pp +The +.Tn struct archive_entry +structure contains a complete description of a single archive +entry. +It uses an opaque interface that is fully documented in +.Xr archive_entry 3 . +.Pp +Users familiar with historic formats should be aware that the newer +variants have eliminated most restrictions on the length of textual fields. +Clients should not assume that filenames, link names, user names, or +group names are limited in length. +In particular, pax interchange format can easily accommodate pathnames +in arbitrary character sets that exceed +.Va PATH_MAX . +.Sh RETURN VALUES +Most functions return +.Cm ARCHIVE_OK +(zero) on success, non-zero on error. +The return value indicates the general severity of the error, ranging +from +.Cm ARCHIVE_WARN , +which indicates a minor problem that should probably be reported +to the user, to +.Cm ARCHIVE_FATAL , +which indicates a serious problem that will prevent any further +operations on this archive. +On error, the +.Fn archive_errno +function can be used to retrieve a numeric error code (see +.Xr errno 2 ) . +The +.Fn archive_error_string +returns a textual error message suitable for display. +.Pp +.Fn archive_read_new +and +.Fn archive_write_new +return pointers to an allocated and initialized +.Tn struct archive +object. +.Pp +.Fn archive_read_data +and +.Fn archive_write_data +return a count of the number of bytes actually read or written. +A value of zero indicates the end of the data for this entry. +A negative value indicates an error, in which case the +.Fn archive_errno +and +.Fn archive_error_string +functions can be used to obtain more information. +.Sh ENVIRONMENT +There are character set conversions within the +.Xr archive_entry 3 +functions that are impacted by the currently-selected locale. +.Sh SEE ALSO +.Xr tar 1 , +.Xr archive_entry 3 , +.Xr archive_read 3 , +.Xr archive_util 3 , +.Xr archive_write 3 , +.Xr tar 5 +.Sh HISTORY +The +.Nm libarchive +library first appeared in +.Fx 5.3 . +.Sh AUTHORS +.An -nosplit +The +.Nm libarchive +library was originally written by +.An Tim Kientzle Aq kientzle@acm.org . +.Sh BUGS +Some archive formats support information that is not supported by +.Tn struct archive_entry . +Such information cannot be fully archived or restored using this library. +This includes, for example, comments, character sets, +or the arbitrary key/value pairs that can appear in +pax interchange format archives. +.Pp +Conversely, of course, not all of the information that can be +stored in an +.Tn struct archive_entry +is supported by all formats. +For example, cpio formats do not support nanosecond timestamps; +old tar formats do not support large device numbers. +.Pp +The ISO9660 reader cannot yet read all ISO9660 images; +it should learn how to seek. +.Pp +The AR writer requires the client program to use +two passes, unlike all other libarchive writers. diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/libarchive_changes.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/libarchive_changes.3 new file mode 100644 index 0000000000..6bf8db038c --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/libarchive_changes.3 @@ -0,0 +1,341 @@ +.\" Copyright (c) 2011 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd December 23, 2011 +.Dt LIBARCHIVE_CHANGES 3 +.Os +.Sh NAME +.Nm libarchive_changes +.Nd changes in libarchive interface +.\" +.Sh CHANGES IN LIBARCHIVE 3 +This page describes user-visible changes in libarchive3, and lists +public functions and other symbols changed, deprecated or removed +in libarchive3, along with their replacements if any. +.\" +.Ss Multiple Filters +.\" +Libarchive2 permitted a single (input or output) filter active +on an archive. +Libarchive3 extends this into a variable-length stack. +Where +.Fn archive_write_set_compression_XXX +would replace any existing filter, +.Fn archive_write_add_filter_XXX +extends the write pipeline with another filter. +.\" +.Ss Character Set Handling +.\" +Libarchive2 assumed that the local platform uses +.Tn Unicode +as the native +.Tn wchar_t +encoding, which is true on +.Tn Windows , +modern +.Tn Linux , +and a few other systems, but is certainly not universal. +As a result, pax format archives were written incorrectly on some +systems, since pax format requires +.Tn UTF-8 +and libarchive 2 incorrectly +assumed that +.Tn wchar_t +strings can be easily converted to +.Tn UTF-8 . +.Pp +Libarchive3 uses the standard iconv library to convert between character +sets and is introducing the notion of a +.Dq default character set for the archive . +To support this, +.Tn archive_entry +objects can now be bound to a particular archive when they are created. +The automatic character set conversions performed by +.Tn archive_entry +objects when reading and writing filenames, usernames, and other strings +will now use an appropriate default character set: +.Pp +If the +.Tn archive_entry +object is bound to an archive, it will use the +default character set for that archive. +.Pp +The platform default character encoding (as returned by +.Fn nl_langinfo CHARSET ) +will be used if nothing else is specified. +.Pp +Libarchive3 also introduces charset options to many of the archive +readers and writers to control the character set that will be used for +filenames written in those archives. +When possible, this will be set automatically based on information in +the archive itself. +Combining this with the notion of a default character set for the +archive should allow you to configure libarchive to read archives from +other platforms and have the filenames and other information +transparently converted to the character encoding suitable for your +application. +.\" +.Ss Prototype Changes +.\" +These changes break binary compatibility; libarchive3 has a new shared +library version to reflect these changes. +The library now uses portable wide types such as +.Tn int64_t +instead of less-portable types such as +.Tn off_t , +.Tn gid_t , +.Tn uid_t , +and +.Tn ino_t . +.Pp +There are a few cases where these changes will affect your source code: +.Bl -bullet -width ind +.It +In some cases, libarchive's wider types will introduce the possibility +of truncation: for example, on a system with a 16-bit +.Tn uid_t , you risk having uid +.Li 65536 +be truncated to uid +.Li 0 , +which can cause serious security problems. +.It +Typedef function pointer types will be incompatible. +For example, if you define custom skip callbacks, you may have to use +code similar to the following if you want to support building against +libarchive2 and libarchive3: +.Bd -literal +#if ARCHIVE_VERSION_NUMBER < 3000000 +typedef off_t myoff_t; +#else +typedef int64_t myoff_t; +#endif + +myoff_t +my_skip_function(struct archive *a, void *v, myoff_t o) +{ + ... implementation ... +} +.Ed +.El +.Pp +Affected functions: +.Pp +.Bl -bullet -compact +.It +.Xo +.Fn archive_entry_gid , +.Fn archive_entry_set_gid +.Xc +.It +.Xo +.Fn archive_entry_uid , +.Fn archive_entry_set_uid +.Xc +.It +.Xo +.Fn archive_entry_ino , +.Fn archive_entry_set_ino +.Xc +.It +.Xo +.Fn archive_read_data_block , +.Fn archive_write_data_block +.Xc +.It +.Xo +.Fn archive_read_disk_gname , +.Fn archive_read_disk_uname +.Xc +.It +.Xo +.Fn archive_read_disk_set_gname_lookup , +.Fn archive_read_disk_set_group_lookup , +.Fn archive_read_disk_set_uname_lookup , +.Fn archive_read_disk_set_user_lookup +.Xc +.It +.Fn archive_skip_callback +.It +.Xo +.Fn archive_read_extract_set_skip_file , +.Fn archive_write_disk_set_skip_file , +.Fn archive_write_set_skip_file +.Xc +.It +.Xo +.Fn archive_write_disk_set_group_lookup , +.Fn archive_write_disk_set_user_lookup +.Xc +.El +.Pp +Where these functions or their arguments took or returned +.Tn gid_t , +.Tn ino_t , +.Tn off_t , +or +.Tn uid_t +they now take or return +.Tn int64_t +or equivalent. +.\" +.Ss Deprecated Symbols +.\" +Symbols deprecated in libarchive3 will be removed in libarchive4. +These symbols, along with their replacements if any, are listed below: +.\" +.Bl -tag -width ind +.It Fn archive_position_compressed , Fn archive_position_uncompressed +.Fn archive_filter_bytes +.It Fn archive_compression +.Fn archive_filter_code +.It Fn archive_compression_name +.Fn archive_filter_name +.It Fn archive_read_finish , Fn archive_write_finish +.Fn archive_read_free , +.Fn archive_write_free +.It Fn archive_read_open_file , Fn archive_write_open_file +.Fn archive_read_open_filename , +.Fn archive_write_open_filename +.It Fn archive_read_support_compression_all +.\" archive_read_support_compression_* -> archive_read_support_filter_* +.Fn archive_read_support_filter_all +.It Fn archive_read_support_compression_bzip2 +.Fn archive_read_support_filter_bzip2 +.It Fn archive_read_support_compression_compress +.Fn archive_read_support_filter_compress +.It Fn archive_read_support_compression_gzip +.Fn archive_read_support_filter_gzip +.It Fn archive_read_support_compression_lzip +.Fn archive_read_support_filter_lzip +.It Fn archive_read_support_compression_lzma +.Fn archive_read_support_filter_lzma +.It Fn archive_read_support_compression_none +.Fn archive_read_support_filter_none +.It Fn archive_read_support_compression_program +.Fn archive_read_support_filter_program +.It Fn archive_read_support_compression_program_signature +.Fn archive_read_support_filter_program_signature +.It Fn archive_read_support_compression_rpm +.Fn archive_read_support_filter_rpm +.It Fn archive_read_support_compression_uu +.Fn archive_read_support_filter_uu +.It Fn archive_read_support_compression_xz +.Fn archive_read_support_filter_xz +.\" archive_write_set_compression_* -> archive_write_add_filter_* +.It Fn archive_write_set_compression_bzip2 +.Fn archive_write_add_filter_bzip2 +.It Fn archive_write_set_compression_compress +.Fn archive_write_add_filter_compress +.It Fn archive_write_set_compression_gzip +.Fn archive_write_add_filter_gzip +.It Fn archive_write_set_compression_lzip +.Fn archive_write_add_filter_lzip +.It Fn archive_write_set_compression_lzma +.Fn archive_write_add_filter_lzma +.It Fn archive_write_set_compression_none +.Fn archive_write_add_filter_none +.It Fn archive_write_set_compression_program +.Fn archive_write_add_filter_program +.It Fn archive_write_set_compression_filter +.Fn archive_write_add_filter_filter +.El +.\" +.Ss Removed Symbols +.\" +These symbols, listed below along with their replacements if any, +were deprecated in libarchive2, and are not part of libarchive3. +.\" +.Bl -tag -width ind +.It Fn archive_api_feature +.Fn archive_version_number +.It Fn archive_api_version +.Fn archive_version_number +.It Fn archive_version +.Fn archive_version_string +.It Fn archive_version_stamp +.Fn archive_version_number +.It Fn archive_read_set_filter_options +.Fn archive_read_set_options +or +.Fn archive_read_set_filter_option +.It Fn archive_read_set_format_options +.Fn archive_read_set_options +or +.Fn archive_read_set_format_option +.It Fn archive_write_set_filter_options +.Fn archive_write_set_options +or +.Fn archive_write_set_filter_option +.It Fn archive_write_set_format_options +.Fn archive_write_set_options +or +.Fn archive_write_set_format_option +.It Dv ARCHIVE_API_FEATURE +.Dv ARCHIVE_VERSION_NUMBER +.It Dv ARCHIVE_API_VERSION +.Dv ARCHIVE_VERSION_NUMBER +.It Dv ARCHIVE_VERSION_STAMP +.Dv ARCHIVE_VERSION_NUMBER +.It Dv ARCHIVE_LIBRARY_VERSION +.Dv ARCHIVE_VERSION_STRING +.\" +.It Dv ARCHIVE_COMPRESSION_NONE +.Dv ARCHIVE_FILTER_NONE +.It Dv ARCHIVE_COMPRESSION_GZIP +.Dv ARCHIVE_FILTER_GZIP +.It Dv ARCHIVE_COMPRESSION_BZIP2 +.Dv ARCHIVE_FILTER_BZIP2 +.It Dv ARCHIVE_COMPRESSION_COMPRESS +.Dv ARCHIVE_FILTER_COMPRESS +.It Dv ARCHIVE_COMPRESSION_PROGRAM +.Dv ARCHIVE_FILTER_PROGRAM +.It Dv ARCHIVE_COMPRESSION_LZMA +.Dv ARCHIVE_FILTER_LZMA +.It Dv ARCHIVE_COMPRESSION_XZ +.Dv ARCHIVE_FILTER_XZ +.It Dv ARCHIVE_COMPRESSION_UU +.Dv ARCHIVE_FILTER_UU +.It Dv ARCHIVE_COMPRESSION_RPM +.Dv ARCHIVE_FILTER_RPM +.It Dv ARCHIVE_COMPRESSION_LZIP +.Dv ARCHIVE_FILTER_LZIP +.\" +.It Dv ARCHIVE_BYTES_PER_RECORD +.Li 512 +.It Dv ARCHIVE_DEFAULT_BYTES_PER_BLOCK +.Li 10240 +.El +.Sh SEE ALSO +.Xr archive_read 3 , +.Xr archive_read_filter 3 , +.Xr archive_read_format 3 , +.Xr archive_read_set_options 3 , +.Xr archive_util 3 , +.Xr archive_write 3 , +.Xr archive_write_filter 3 , +.Xr archive_write_format 3 , +.Xr archive_write_set_options 3 , +.Xr libarchive 3 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/libarchive_internals.3 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/libarchive_internals.3 new file mode 100644 index 0000000000..d672f3e8a6 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/libarchive_internals.3 @@ -0,0 +1,365 @@ +.\" Copyright (c) 2003-2007 Tim Kientzle +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd January 26, 2011 +.Dt LIBARCHIVE_INTERNALS 3 +.Os +.Sh NAME +.Nm libarchive_internals +.Nd description of libarchive internal interfaces +.Sh OVERVIEW +The +.Nm libarchive +library provides a flexible interface for reading and writing +streaming archive files such as tar and cpio. +Internally, it follows a modular layered design that should +make it easy to add new archive and compression formats. +.Sh GENERAL ARCHITECTURE +Externally, libarchive exposes most operations through an +opaque, object-style interface. +The +.Xr archive_entry 3 +objects store information about a single filesystem object. +The rest of the library provides facilities to write +.Xr archive_entry 3 +objects to archive files, +read them from archive files, +and write them to disk. +(There are plans to add a facility to read +.Xr archive_entry 3 +objects from disk as well.) +.Pp +The read and write APIs each have four layers: a public API +layer, a format layer that understands the archive file format, +a compression layer, and an I/O layer. +The I/O layer is completely exposed to clients who can replace +it entirely with their own functions. +.Pp +In order to provide as much consistency as possible for clients, +some public functions are virtualized. +Eventually, it should be possible for clients to open +an archive or disk writer, and then use a single set of +code to select and write entries, regardless of the target. +.Sh READ ARCHITECTURE +From the outside, clients use the +.Xr archive_read 3 +API to manipulate an +.Nm archive +object to read entries and bodies from an archive stream. +Internally, the +.Nm archive +object is cast to an +.Nm archive_read +object, which holds all read-specific data. +The API has four layers: +The lowest layer is the I/O layer. +This layer can be overridden by clients, but most clients use +the packaged I/O callbacks provided, for example, by +.Xr archive_read_open_memory 3 , +and +.Xr archive_read_open_fd 3 . +The compression layer calls the I/O layer to +read bytes and decompresses them for the format layer. +The format layer unpacks a stream of uncompressed bytes and +creates +.Nm archive_entry +objects from the incoming data. +The API layer tracks overall state +(for example, it prevents clients from reading data before reading a header) +and invokes the format and compression layer operations +through registered function pointers. +In particular, the API layer drives the format-detection process: +When opening the archive, it reads an initial block of data +and offers it to each registered compression handler. +The one with the highest bid is initialized with the first block. +Similarly, the format handlers are polled to see which handler +is the best for each archive. +(Prior to 2.4.0, the format bidders were invoked for each +entry, but this design hindered error recovery.) +.Ss I/O Layer and Client Callbacks +The read API goes to some lengths to be nice to clients. +As a result, there are few restrictions on the behavior of +the client callbacks. +.Pp +The client read callback is expected to provide a block +of data on each call. +A zero-length return does indicate end of file, but otherwise +blocks may be as small as one byte or as large as the entire file. +In particular, blocks may be of different sizes. +.Pp +The client skip callback returns the number of bytes actually +skipped, which may be much smaller than the skip requested. +The only requirement is that the skip not be larger. +In particular, clients are allowed to return zero for any +skip that they don't want to handle. +The skip callback must never be invoked with a negative value. +.Pp +Keep in mind that not all clients are reading from disk: +clients reading from networks may provide different-sized +blocks on every request and cannot skip at all; +advanced clients may use +.Xr mmap 2 +to read the entire file into memory at once and return the +entire file to libarchive as a single block; +other clients may begin asynchronous I/O operations for the +next block on each request. +.Ss Decompresssion Layer +The decompression layer not only handles decompression, +it also buffers data so that the format handlers see a +much nicer I/O model. +The decompression API is a two stage peek/consume model. +A read_ahead request specifies a minimum read amount; +the decompression layer must provide a pointer to at least +that much data. +If more data is immediately available, it should return more: +the format layer handles bulk data reads by asking for a minimum +of one byte and then copying as much data as is available. +.Pp +A subsequent call to the +.Fn consume +function advances the read pointer. +Note that data returned from a +.Fn read_ahead +call is guaranteed to remain in place until +the next call to +.Fn read_ahead . +Intervening calls to +.Fn consume +should not cause the data to move. +.Pp +Skip requests must always be handled exactly. +Decompression handlers that cannot seek forward should +not register a skip handler; +the API layer fills in a generic skip handler that reads and discards data. +.Pp +A decompression handler has a specific lifecycle: +.Bl -tag -compact -width indent +.It Registration/Configuration +When the client invokes the public support function, +the decompression handler invokes the internal +.Fn __archive_read_register_compression +function to provide bid and initialization functions. +This function returns +.Cm NULL +on error or else a pointer to a +.Cm struct decompressor_t . +This structure contains a +.Va void * config +slot that can be used for storing any customization information. +.It Bid +The bid function is invoked with a pointer and size of a block of data. +The decompressor can access its config data +through the +.Va decompressor +element of the +.Cm archive_read +object. +The bid function is otherwise stateless. +In particular, it must not perform any I/O operations. +.Pp +The value returned by the bid function indicates its suitability +for handling this data stream. +A bid of zero will ensure that this decompressor is never invoked. +Return zero if magic number checks fail. +Otherwise, your initial implementation should return the number of bits +actually checked. +For example, if you verify two full bytes and three bits of another +byte, bid 19. +Note that the initial block may be very short; +be careful to only inspect the data you are given. +(The current decompressors require two bytes for correct bidding.) +.It Initialize +The winning bidder will have its init function called. +This function should initialize the remaining slots of the +.Va struct decompressor_t +object pointed to by the +.Va decompressor +element of the +.Va archive_read +object. +In particular, it should allocate any working data it needs +in the +.Va data +slot of that structure. +The init function is called with the block of data that +was used for tasting. +At this point, the decompressor is responsible for all I/O +requests to the client callbacks. +The decompressor is free to read more data as and when +necessary. +.It Satisfy I/O requests +The format handler will invoke the +.Va read_ahead , +.Va consume , +and +.Va skip +functions as needed. +.It Finish +The finish method is called only once when the archive is closed. +It should release anything stored in the +.Va data +and +.Va config +slots of the +.Va decompressor +object. +It should not invoke the client close callback. +.El +.Ss Format Layer +The read formats have a similar lifecycle to the decompression handlers: +.Bl -tag -compact -width indent +.It Registration +Allocate your private data and initialize your pointers. +.It Bid +Formats bid by invoking the +.Fn read_ahead +decompression method but not calling the +.Fn consume +method. +This allows each bidder to look ahead in the input stream. +Bidders should not look further ahead than necessary, as long +look aheads put pressure on the decompression layer to buffer +lots of data. +Most formats only require a few hundred bytes of look ahead; +look aheads of a few kilobytes are reasonable. +(The ISO9660 reader sometimes looks ahead by 48k, which +should be considered an upper limit.) +.It Read header +The header read is usually the most complex part of any format. +There are a few strategies worth mentioning: +For formats such as tar or cpio, reading and parsing the header is +straightforward since headers alternate with data. +For formats that store all header data at the beginning of the file, +the first header read request may have to read all headers into +memory and store that data, sorted by the location of the file +data. +Subsequent header read requests will skip forward to the +beginning of the file data and return the corresponding header. +.It Read Data +The read data interface supports sparse files; this requires that +each call return a block of data specifying the file offset and +size. +This may require you to carefully track the location so that you +can return accurate file offsets for each read. +Remember that the decompressor will return as much data as it has. +Generally, you will want to request one byte, +examine the return value to see how much data is available, and +possibly trim that to the amount you can use. +You should invoke consume for each block just before you return it. +.It Skip All Data +The skip data call should skip over all file data and trailing padding. +This is called automatically by the API layer just before each +header read. +It is also called in response to the client calling the public +.Fn data_skip +function. +.It Cleanup +On cleanup, the format should release all of its allocated memory. +.El +.Ss API Layer +XXX to do XXX +.Sh WRITE ARCHITECTURE +The write API has a similar set of four layers: +an API layer, a format layer, a compression layer, and an I/O layer. +The registration here is much simpler because only +one format and one compression can be registered at a time. +.Ss I/O Layer and Client Callbacks +XXX To be written XXX +.Ss Compression Layer +XXX To be written XXX +.Ss Format Layer +XXX To be written XXX +.Ss API Layer +XXX To be written XXX +.Sh WRITE_DISK ARCHITECTURE +The write_disk API is intended to look just like the write API +to clients. +Since it does not handle multiple formats or compression, it +is not layered internally. +.Sh GENERAL SERVICES +The +.Nm archive_read , +.Nm archive_write , +and +.Nm archive_write_disk +objects all contain an initial +.Nm archive +object which provides common support for a set of standard services. +(Recall that ANSI/ISO C90 guarantees that you can cast freely between +a pointer to a structure and a pointer to the first element of that +structure.) +The +.Nm archive +object has a magic value that indicates which API this object +is associated with, +slots for storing error information, +and function pointers for virtualized API functions. +.Sh MISCELLANEOUS NOTES +Connecting existing archiving libraries into libarchive is generally +quite difficult. +In particular, many existing libraries strongly assume that you +are reading from a file; they seek forwards and backwards as necessary +to locate various pieces of information. +In contrast, libarchive never seeks backwards in its input, which +sometimes requires very different approaches. +.Pp +For example, libarchive's ISO9660 support operates very differently +from most ISO9660 readers. +The libarchive support utilizes a work-queue design that +keeps a list of known entries sorted by their location in the input. +Whenever libarchive's ISO9660 implementation is asked for the next +header, checks this list to find the next item on the disk. +Directories are parsed when they are encountered and new +items are added to the list. +This design relies heavily on the ISO9660 image being optimized so that +directories always occur earlier on the disk than the files they +describe. +.Pp +Depending on the specific format, such approaches may not be possible. +The ZIP format specification, for example, allows archivers to store +key information only at the end of the file. +In theory, it is possible to create ZIP archives that cannot +be read without seeking. +Fortunately, such archives are very rare, and libarchive can read +most ZIP archives, though it cannot always extract as much information +as a dedicated ZIP program. +.Sh SEE ALSO +.Xr archive_entry 3 , +.Xr archive_read 3 , +.Xr archive_write 3 , +.Xr archive_write_disk 3 , +.Xr libarchive 3 +.Sh HISTORY +The +.Nm libarchive +library first appeared in +.Fx 5.3 . +.Sh AUTHORS +.An -nosplit +The +.Nm libarchive +library was written by +.An Tim Kientzle Aq kientzle@acm.org . diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/mtree.5 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/mtree.5 new file mode 100644 index 0000000000..8147796f31 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/mtree.5 @@ -0,0 +1,324 @@ +.\" Copyright (c) 1989, 1990, 1993 +.\" The Regents of the University of California. 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. +.\" 4. Neither the name of the University nor the names of its contributors +.\" may be used to endorse or promote products derived from this software +.\" without specific prior written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. +.\" +.\" From: @(#)mtree.8 8.2 (Berkeley) 12/11/93 +.\" $FreeBSD$ +.\" +.Dd September 4, 2013 +.Dt MTREE 5 +.Os +.Sh NAME +.Nm mtree +.Nd format of mtree dir hierarchy files +.Sh DESCRIPTION +The +.Nm +format is a textual format that describes a collection of filesystem objects. +Such files are typically used to create or verify directory hierarchies. +.Ss General Format +An +.Nm +file consists of a series of lines, each providing information +about a single filesystem object. +Leading whitespace is always ignored. +.Pp +When encoding file or pathnames, any backslash character or +character outside of the 95 printable ASCII characters must be +encoded as a backslash followed by three +octal digits. +When reading mtree files, any appearance of a backslash +followed by three octal digits should be converted into the +corresponding character. +.Pp +Each line is interpreted independently as one of the following types: +.Bl -tag -width Cm +.It Blank +Blank lines are ignored. +.It Comment +Lines beginning with +.Cm # +are ignored. +.It Special +Lines beginning with +.Cm / +are special commands that influence +the interpretation of later lines. +.It Relative +If the first whitespace-delimited word has no +.Cm / +characters, +it is the name of a file in the current directory. +Any relative entry that describes a directory changes the +current directory. +.It dot-dot +As a special case, a relative entry with the filename +.Pa .. +changes the current directory to the parent directory. +Options on dot-dot entries are always ignored. +.It Full +If the first whitespace-delimited word has a +.Cm / +character after +the first character, it is the pathname of a file relative to the +starting directory. +There can be multiple full entries describing the same file. +.El +.Pp +Some tools that process +.Nm +files may require that multiple lines describing the same file +occur consecutively. +It is not permitted for the same file to be mentioned using +both a relative and a full file specification. +.Ss Special commands +Two special commands are currently defined: +.Bl -tag -width Cm +.It Cm /set +This command defines default values for one or more keywords. +It is followed on the same line by one or more whitespace-separated +keyword definitions. +These definitions apply to all following files that do not specify +a value for that keyword. +.It Cm /unset +This command removes any default value set by a previous +.Cm /set +command. +It is followed on the same line by one or more keywords +separated by whitespace. +.El +.Ss Keywords +After the filename, a full or relative entry consists of zero +or more whitespace-separated keyword definitions. +Each such definition consists of a key from the following +list immediately followed by an '=' sign +and a value. +Software programs reading mtree files should warn about +unrecognized keywords. +.Pp +Currently supported keywords are as follows: +.Bl -tag -width Cm +.It Cm cksum +The checksum of the file using the default algorithm specified by +the +.Xr cksum 1 +utility. +.It Cm device +The device number for +.Sy block +or +.Sy char +file types. +The value must be one of the following forms: +.Bl -tag -width 4n +.It Ar format , Ns Ar major , Ns Ar minor Ns Bo , Ns Ar subunit Bc +A device with +.Ar major , minor +and optional +.Ar subunit +fields. +Their meaning is specified by the operating's system +.Ar format . +See below for valid formats. +.It Ar number +Opaque number (as stored on the file system). +.El +.Pp +The following values for +.Ar format +are recognized: +.Sy native , +.Sy 386bsd , +.Sy 4bsd , +.Sy bsdos , +.Sy freebsd , +.Sy hpux , +.Sy isc , +.Sy linux , +.Sy netbsd , +.Sy osf1 , +.Sy sco , +.Sy solaris , +.Sy sunos , +.Sy svr3 , +.Sy svr4 , +and +.Sy ultrix . +.Pp +See +.Xr mknod 8 +for more details. +.It Cm contents +The full pathname of a file that holds the contents of this file. +.It Cm flags +The file flags as a symbolic name. +See +.Xr chflags 1 +for information on these names. +If no flags are to be set the string +.Dq none +may be used to override the current default. +.It Cm gid +The file group as a numeric value. +.It Cm gname +The file group as a symbolic name. +.It Cm ignore +Ignore any file hierarchy below this file. +.It Cm inode +The inode number. +.It Cm link +The target of the symbolic link when type=link. +.It Cm md5 +The MD5 message digest of the file. +.It Cm md5digest +A synonym for +.Cm md5 . +.It Cm mode +The current file's permissions as a numeric (octal) or symbolic +value. +.It Cm nlink +The number of hard links the file is expected to have. +.It Cm nochange +Make sure this file or directory exists but otherwise ignore all attributes. +.It Cm optional +The file is optional; do not complain about the file if it is not in +the file hierarchy. +.It Cm resdevice +The +.Dq resident +device number of the file, e.g. the ID of the device that +contains the file. +Its format is the same as the one for +.Cm device . +.It Cm ripemd160digest +The +.Tn RIPEMD160 +message digest of the file. +.It Cm rmd160 +A synonym for +.Cm ripemd160digest . +.It Cm rmd160digest +A synonym for +.Cm ripemd160digest . +.It Cm sha1 +The +.Tn FIPS +160-1 +.Pq Dq Tn SHA-1 +message digest of the file. +.It Cm sha1digest +A synonym for +.Cm sha1 . +.It Cm sha256 +The +.Tn FIPS +180-2 +.Pq Dq Tn SHA-256 +message digest of the file. +.It Cm sha256digest +A synonym for +.Cm sha256 . +.It Cm sha384 +The +.Tn FIPS +180-2 +.Pq Dq Tn SHA-384 +message digest of the file. +.It Cm sha384digest +A synonym for +.Cm sha384 . +.It Cm sha512 +The +.Tn FIPS +180-2 +.Pq Dq Tn SHA-512 +message digest of the file. +.It Cm sha512digest +A synonym for +.Cm sha512 . +.It Cm size +The size, in bytes, of the file. +.It Cm time +The last modification time of the file. +.It Cm type +The type of the file; may be set to any one of the following: +.Pp +.Bl -tag -width Cm -compact +.It Cm block +block special device +.It Cm char +character special device +.It Cm dir +directory +.It Cm fifo +fifo +.It Cm file +regular file +.It Cm link +symbolic link +.It Cm socket +socket +.El +.It Cm uid +The file owner as a numeric value. +.It Cm uname +The file owner as a symbolic name. +.El +.Sh SEE ALSO +.Xr cksum 1 , +.Xr find 1 , +.Xr mtree 8 +.Sh HISTORY +The +.Nm +utility appeared in +.Bx 4.3 Reno . +The +.Tn MD5 +digest capability was added in +.Fx 2.1 , +in response to the widespread use of programs which can spoof +.Xr cksum 1 . +The +.Tn SHA-1 +and +.Tn RIPEMD160 +digests were added in +.Fx 4.0 , +as new attacks have demonstrated weaknesses in +.Tn MD5 . +The +.Tn SHA-256 +digest was added in +.Fx 6.0 . +Support for file flags was added in +.Fx 4.0 , +and mostly comes from +.Nx . +The +.Dq full +entry format was added by +.Nx . diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/tar.5 b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/tar.5 new file mode 100644 index 0000000000..34ad4f7931 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/tar.5 @@ -0,0 +1,949 @@ +.\" Copyright (c) 2003-2009 Tim Kientzle +.\" Copyright (c) 2016 Martin Matuska +.\" 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. +.\" +.\" $FreeBSD$ +.\" +.Dd December 27, 2016 +.Dt TAR 5 +.Os +.Sh NAME +.Nm tar +.Nd format of tape archive files +.Sh DESCRIPTION +The +.Nm +archive format collects any number of files, directories, and other +file system objects (symbolic links, device nodes, etc.) into a single +stream of bytes. +The format was originally designed to be used with +tape drives that operate with fixed-size blocks, but is widely used as +a general packaging mechanism. +.Ss General Format +A +.Nm +archive consists of a series of 512-byte records. +Each file system object requires a header record which stores basic metadata +(pathname, owner, permissions, etc.) and zero or more records containing any +file data. +The end of the archive is indicated by two records consisting +entirely of zero bytes. +.Pp +For compatibility with tape drives that use fixed block sizes, +programs that read or write tar files always read or write a fixed +number of records with each I/O operation. +These +.Dq blocks +are always a multiple of the record size. +The maximum block size supported by early +implementations was 10240 bytes or 20 records. +This is still the default for most implementations +although block sizes of 1MiB (2048 records) or larger are +commonly used with modern high-speed tape drives. +(Note: the terms +.Dq block +and +.Dq record +here are not entirely standard; this document follows the +convention established by John Gilmore in documenting +.Nm pdtar . ) +.Ss Old-Style Archive Format +The original tar archive format has been extended many times to +include additional information that various implementors found +necessary. +This section describes the variant implemented by the tar command +included in +.At v7 , +which seems to be the earliest widely-used version of the tar program. +.Pp +The header record for an old-style +.Nm +archive consists of the following: +.Bd -literal -offset indent +struct header_old_tar { + char name[100]; + char mode[8]; + char uid[8]; + char gid[8]; + char size[12]; + char mtime[12]; + char checksum[8]; + char linkflag[1]; + char linkname[100]; + char pad[255]; +}; +.Ed +All unused bytes in the header record are filled with nulls. +.Bl -tag -width indent +.It Va name +Pathname, stored as a null-terminated string. +Early tar implementations only stored regular files (including +hardlinks to those files). +One common early convention used a trailing "/" character to indicate +a directory name, allowing directory permissions and owner information +to be archived and restored. +.It Va mode +File mode, stored as an octal number in ASCII. +.It Va uid , Va gid +User id and group id of owner, as octal numbers in ASCII. +.It Va size +Size of file, as octal number in ASCII. +For regular files only, this indicates the amount of data +that follows the header. +In particular, this field was ignored by early tar implementations +when extracting hardlinks. +Modern writers should always store a zero length for hardlink entries. +.It Va mtime +Modification time of file, as an octal number in ASCII. +This indicates the number of seconds since the start of the epoch, +00:00:00 UTC January 1, 1970. +Note that negative values should be avoided +here, as they are handled inconsistently. +.It Va checksum +Header checksum, stored as an octal number in ASCII. +To compute the checksum, set the checksum field to all spaces, +then sum all bytes in the header using unsigned arithmetic. +This field should be stored as six octal digits followed by a null and a space +character. +Note that many early implementations of tar used signed arithmetic +for the checksum field, which can cause interoperability problems +when transferring archives between systems. +Modern robust readers compute the checksum both ways and accept the +header if either computation matches. +.It Va linkflag , Va linkname +In order to preserve hardlinks and conserve tape, a file +with multiple links is only written to the archive the first +time it is encountered. +The next time it is encountered, the +.Va linkflag +is set to an ASCII +.Sq 1 +and the +.Va linkname +field holds the first name under which this file appears. +(Note that regular files have a null value in the +.Va linkflag +field.) +.El +.Pp +Early tar implementations varied in how they terminated these fields. +The tar command in +.At v7 +used the following conventions (this is also documented in early BSD manpages): +the pathname must be null-terminated; +the mode, uid, and gid fields must end in a space and a null byte; +the size and mtime fields must end in a space; +the checksum is terminated by a null and a space. +Early implementations filled the numeric fields with leading spaces. +This seems to have been common practice until the +.St -p1003.1-88 +standard was released. +For best portability, modern implementations should fill the numeric +fields with leading zeros. +.Ss Pre-POSIX Archives +An early draft of +.St -p1003.1-88 +served as the basis for John Gilmore's +.Nm pdtar +program and many system implementations from the late 1980s +and early 1990s. +These archives generally follow the POSIX ustar +format described below with the following variations: +.Bl -bullet -compact -width indent +.It +The magic value consists of the five characters +.Dq ustar +followed by a space. +The version field contains a space character followed by a null. +.It +The numeric fields are generally filled with leading spaces +(not leading zeros as recommended in the final standard). +.It +The prefix field is often not used, limiting pathnames to +the 100 characters of old-style archives. +.El +.Ss POSIX ustar Archives +.St -p1003.1-88 +defined a standard tar file format to be read and written +by compliant implementations of +.Xr tar 1 . +This format is often called the +.Dq ustar +format, after the magic value used +in the header. +(The name is an acronym for +.Dq Unix Standard TAR . ) +It extends the historic format with new fields: +.Bd -literal -offset indent +struct header_posix_ustar { + char name[100]; + char mode[8]; + char uid[8]; + char gid[8]; + char size[12]; + char mtime[12]; + char checksum[8]; + char typeflag[1]; + char linkname[100]; + char magic[6]; + char version[2]; + char uname[32]; + char gname[32]; + char devmajor[8]; + char devminor[8]; + char prefix[155]; + char pad[12]; +}; +.Ed +.Bl -tag -width indent +.It Va typeflag +Type of entry. +POSIX extended the earlier +.Va linkflag +field with several new type values: +.Bl -tag -width indent -compact +.It Dq 0 +Regular file. +NUL should be treated as a synonym, for compatibility purposes. +.It Dq 1 +Hard link. +.It Dq 2 +Symbolic link. +.It Dq 3 +Character device node. +.It Dq 4 +Block device node. +.It Dq 5 +Directory. +.It Dq 6 +FIFO node. +.It Dq 7 +Reserved. +.It Other +A POSIX-compliant implementation must treat any unrecognized typeflag value +as a regular file. +In particular, writers should ensure that all entries +have a valid filename so that they can be restored by readers that do not +support the corresponding extension. +Uppercase letters "A" through "Z" are reserved for custom extensions. +Note that sockets and whiteout entries are not archivable. +.El +It is worth noting that the +.Va size +field, in particular, has different meanings depending on the type. +For regular files, of course, it indicates the amount of data +following the header. +For directories, it may be used to indicate the total size of all +files in the directory, for use by operating systems that pre-allocate +directory space. +For all other types, it should be set to zero by writers and ignored +by readers. +.It Va magic +Contains the magic value +.Dq ustar +followed by a NUL byte to indicate that this is a POSIX standard archive. +Full compliance requires the uname and gname fields be properly set. +.It Va version +Version. +This should be +.Dq 00 +(two copies of the ASCII digit zero) for POSIX standard archives. +.It Va uname , Va gname +User and group names, as null-terminated ASCII strings. +These should be used in preference to the uid/gid values +when they are set and the corresponding names exist on +the system. +.It Va devmajor , Va devminor +Major and minor numbers for character device or block device entry. +.It Va name , Va prefix +If the pathname is too long to fit in the 100 bytes provided by the standard +format, it can be split at any +.Pa / +character with the first portion going into the prefix field. +If the prefix field is not empty, the reader will prepend +the prefix value and a +.Pa / +character to the regular name field to obtain the full pathname. +The standard does not require a trailing +.Pa / +character on directory names, though most implementations still +include this for compatibility reasons. +.El +.Pp +Note that all unused bytes must be set to +.Dv NUL . +.Pp +Field termination is specified slightly differently by POSIX +than by previous implementations. +The +.Va magic , +.Va uname , +and +.Va gname +fields must have a trailing +.Dv NUL . +The +.Va pathname , +.Va linkname , +and +.Va prefix +fields must have a trailing +.Dv NUL +unless they fill the entire field. +(In particular, it is possible to store a 256-character pathname if it +happens to have a +.Pa / +as the 156th character.) +POSIX requires numeric fields to be zero-padded in the front, and requires +them to be terminated with either space or +.Dv NUL +characters. +.Pp +Currently, most tar implementations comply with the ustar +format, occasionally extending it by adding new fields to the +blank area at the end of the header record. +.Ss Numeric Extensions +There have been several attempts to extend the range of sizes +or times supported by modifying how numbers are stored in the +header. +.Pp +One obvious extension to increase the size of files is to +eliminate the terminating characters from the various +numeric fields. +For example, the standard only allows the size field to contain +11 octal digits, reserving the twelfth byte for a trailing +NUL character. +Allowing 12 octal digits allows file sizes up to 64 GB. +.Pp +Another extension, utilized by GNU tar, star, and other newer +.Nm +implementations, permits binary numbers in the standard numeric fields. +This is flagged by setting the high bit of the first byte. +The remainder of the field is treated as a signed twos-complement +value. +This permits 95-bit values for the length and time fields +and 63-bit values for the uid, gid, and device numbers. +In particular, this provides a consistent way to handle +negative time values. +GNU tar supports this extension for the +length, mtime, ctime, and atime fields. +Joerg Schilling's star program and the libarchive library support +this extension for all numeric fields. +Note that this extension is largely obsoleted by the extended +attribute record provided by the pax interchange format. +.Pp +Another early GNU extension allowed base-64 values rather than octal. +This extension was short-lived and is no longer supported by any +implementation. +.Ss Pax Interchange Format +There are many attributes that cannot be portably stored in a +POSIX ustar archive. +.St -p1003.1-2001 +defined a +.Dq pax interchange format +that uses two new types of entries to hold text-formatted +metadata that applies to following entries. +Note that a pax interchange format archive is a ustar archive in every +respect. +The new data is stored in ustar-compatible archive entries that use the +.Dq x +or +.Dq g +typeflag. +In particular, older implementations that do not fully support these +extensions will extract the metadata into regular files, where the +metadata can be examined as necessary. +.Pp +An entry in a pax interchange format archive consists of one or +two standard ustar entries, each with its own header and data. +The first optional entry stores the extended attributes +for the following entry. +This optional first entry has an "x" typeflag and a size field that +indicates the total size of the extended attributes. +The extended attributes themselves are stored as a series of text-format +lines encoded in the portable UTF-8 encoding. +Each line consists of a decimal number, a space, a key string, an equals +sign, a value string, and a new line. +The decimal number indicates the length of the entire line, including the +initial length field and the trailing newline. +An example of such a field is: +.Dl 25 ctime=1084839148.1212\en +Keys in all lowercase are standard keys. +Vendors can add their own keys by prefixing them with an all uppercase +vendor name and a period. +Note that, unlike the historic header, numeric values are stored using +decimal, not octal. +A description of some common keys follows: +.Bl -tag -width indent +.It Cm atime , Cm ctime , Cm mtime +File access, inode change, and modification times. +These fields can be negative or include a decimal point and a fractional value. +.It Cm hdrcharset +The character set used by the pax extension values. +By default, all textual values in the pax extended attributes +are assumed to be in UTF-8, including pathnames, user names, +and group names. +In some cases, it is not possible to translate local +conventions into UTF-8. +If this key is present and the value is the six-character ASCII string +.Dq BINARY , +then all textual values are assumed to be in a platform-dependent +multi-byte encoding. +Note that there are only two valid values for this key: +.Dq BINARY +or +.Dq ISO-IR\ 10646\ 2000\ UTF-8 . +No other values are permitted by the standard, and +the latter value should generally not be used as it is the +default when this key is not specified. +In particular, this flag should not be used as a general +mechanism to allow filenames to be stored in arbitrary +encodings. +.It Cm uname , Cm uid , Cm gname , Cm gid +User name, group name, and numeric UID and GID values. +The user name and group name stored here are encoded in UTF8 +and can thus include non-ASCII characters. +The UID and GID fields can be of arbitrary length. +.It Cm linkpath +The full path of the linked-to file. +Note that this is encoded in UTF8 and can thus include non-ASCII characters. +.It Cm path +The full pathname of the entry. +Note that this is encoded in UTF8 and can thus include non-ASCII characters. +.It Cm realtime.* , Cm security.* +These keys are reserved and may be used for future standardization. +.It Cm size +The size of the file. +Note that there is no length limit on this field, allowing conforming +archives to store files much larger than the historic 8GB limit. +.It Cm SCHILY.* +Vendor-specific attributes used by Joerg Schilling's +.Nm star +implementation. +.It Cm SCHILY.acl.access , Cm SCHILY.acl.default , Cm SCHILY.acl.ace +Stores the access, default and NFSv4 ACLs as textual strings in a format +that is an extension of the format specified by POSIX.1e draft 17. +In particular, each user or group access specification can include +an additional colon-separated field with the numeric UID or GID. +This allows ACLs to be restored on systems that may not have complete +user or group information available (such as when NIS/YP or LDAP services +are temporarily unavailable). +.It Cm SCHILY.devminor , Cm SCHILY.devmajor +The full minor and major numbers for device nodes. +.It Cm SCHILY.fflags +The file flags. +.It Cm SCHILY.realsize +The full size of the file on disk. +XXX explain? XXX +.It Cm SCHILY.dev , Cm SCHILY.ino , Cm SCHILY.nlinks +The device number, inode number, and link count for the entry. +In particular, note that a pax interchange format archive using Joerg +Schilling's +.Cm SCHILY.* +extensions can store all of the data from +.Va struct stat . +.It Cm LIBARCHIVE.* +Vendor-specific attributes used by the +.Nm libarchive +library and programs that use it. +.It Cm LIBARCHIVE.creationtime +The time when the file was created. +(This should not be confused with the POSIX +.Dq ctime +attribute, which refers to the time when the file +metadata was last changed.) +.It Cm LIBARCHIVE.xattr . Ns Ar namespace . Ns Ar key +Libarchive stores POSIX.1e-style extended attributes using +keys of this form. +The +.Ar key +value is URL-encoded: +All non-ASCII characters and the two special characters +.Dq = +and +.Dq % +are encoded as +.Dq % +followed by two uppercase hexadecimal digits. +The value of this key is the extended attribute value +encoded in base 64. +XXX Detail the base-64 format here XXX +.It Cm VENDOR.* +XXX document other vendor-specific extensions XXX +.El +.Pp +Any values stored in an extended attribute override the corresponding +values in the regular tar header. +Note that compliant readers should ignore the regular fields when they +are overridden. +This is important, as existing archivers are known to store non-compliant +values in the standard header fields in this situation. +There are no limits on length for any of these fields. +In particular, numeric fields can be arbitrarily large. +All text fields are encoded in UTF8. +Compliant writers should store only portable 7-bit ASCII characters in +the standard ustar header and use extended +attributes whenever a text value contains non-ASCII characters. +.Pp +In addition to the +.Cm x +entry described above, the pax interchange format +also supports a +.Cm g +entry. +The +.Cm g +entry is identical in format, but specifies attributes that serve as +defaults for all subsequent archive entries. +The +.Cm g +entry is not widely used. +.Pp +Besides the new +.Cm x +and +.Cm g +entries, the pax interchange format has a few other minor variations +from the earlier ustar format. +The most troubling one is that hardlinks are permitted to have +data following them. +This allows readers to restore any hardlink to a file without +having to rewind the archive to find an earlier entry. +However, it creates complications for robust readers, as it is no longer +clear whether or not they should ignore the size field for hardlink entries. +.Ss GNU Tar Archives +The GNU tar program started with a pre-POSIX format similar to that +described earlier and has extended it using several different mechanisms: +It added new fields to the empty space in the header (some of which was later +used by POSIX for conflicting purposes); +it allowed the header to be continued over multiple records; +and it defined new entries that modify following entries +(similar in principle to the +.Cm x +entry described above, but each GNU special entry is single-purpose, +unlike the general-purpose +.Cm x +entry). +As a result, GNU tar archives are not POSIX compatible, although +more lenient POSIX-compliant readers can successfully extract most +GNU tar archives. +.Bd -literal -offset indent +struct header_gnu_tar { + char name[100]; + char mode[8]; + char uid[8]; + char gid[8]; + char size[12]; + char mtime[12]; + char checksum[8]; + char typeflag[1]; + char linkname[100]; + char magic[6]; + char version[2]; + char uname[32]; + char gname[32]; + char devmajor[8]; + char devminor[8]; + char atime[12]; + char ctime[12]; + char offset[12]; + char longnames[4]; + char unused[1]; + struct { + char offset[12]; + char numbytes[12]; + } sparse[4]; + char isextended[1]; + char realsize[12]; + char pad[17]; +}; +.Ed +.Bl -tag -width indent +.It Va typeflag +GNU tar uses the following special entry types, in addition to +those defined by POSIX: +.Bl -tag -width indent +.It "7" +GNU tar treats type "7" records identically to type "0" records, +except on one obscure RTOS where they are used to indicate the +pre-allocation of a contiguous file on disk. +.It "D" +This indicates a directory entry. +Unlike the POSIX-standard "5" +typeflag, the header is followed by data records listing the names +of files in this directory. +Each name is preceded by an ASCII "Y" +if the file is stored in this archive or "N" if the file is not +stored in this archive. +Each name is terminated with a null, and +an extra null marks the end of the name list. +The purpose of this +entry is to support incremental backups; a program restoring from +such an archive may wish to delete files on disk that did not exist +in the directory when the archive was made. +.Pp +Note that the "D" typeflag specifically violates POSIX, which requires +that unrecognized typeflags be restored as normal files. +In this case, restoring the "D" entry as a file could interfere +with subsequent creation of the like-named directory. +.It "K" +The data for this entry is a long linkname for the following regular entry. +.It "L" +The data for this entry is a long pathname for the following regular entry. +.It "M" +This is a continuation of the last file on the previous volume. +GNU multi-volume archives guarantee that each volume begins with a valid +entry header. +To ensure this, a file may be split, with part stored at the end of one volume, +and part stored at the beginning of the next volume. +The "M" typeflag indicates that this entry continues an existing file. +Such entries can only occur as the first or second entry +in an archive (the latter only if the first entry is a volume label). +The +.Va size +field specifies the size of this entry. +The +.Va offset +field at bytes 369-380 specifies the offset where this file fragment +begins. +The +.Va realsize +field specifies the total size of the file (which must equal +.Va size +plus +.Va offset ) . +When extracting, GNU tar checks that the header file name is the one it is +expecting, that the header offset is in the correct sequence, and that +the sum of offset and size is equal to realsize. +.It "N" +Type "N" records are no longer generated by GNU tar. +They contained a +list of files to be renamed or symlinked after extraction; this was +originally used to support long names. +The contents of this record +are a text description of the operations to be done, in the form +.Dq Rename %s to %s\en +or +.Dq Symlink %s to %s\en ; +in either case, both +filenames are escaped using K&R C syntax. +Due to security concerns, "N" records are now generally ignored +when reading archives. +.It "S" +This is a +.Dq sparse +regular file. +Sparse files are stored as a series of fragments. +The header contains a list of fragment offset/length pairs. +If more than four such entries are required, the header is +extended as necessary with +.Dq extra +header extensions (an older format that is no longer used), or +.Dq sparse +extensions. +.It "V" +The +.Va name +field should be interpreted as a tape/volume header name. +This entry should generally be ignored on extraction. +.El +.It Va magic +The magic field holds the five characters +.Dq ustar +followed by a space. +Note that POSIX ustar archives have a trailing null. +.It Va version +The version field holds a space character followed by a null. +Note that POSIX ustar archives use two copies of the ASCII digit +.Dq 0 . +.It Va atime , Va ctime +The time the file was last accessed and the time of +last change of file information, stored in octal as with +.Va mtime . +.It Va longnames +This field is apparently no longer used. +.It Sparse Va offset / Va numbytes +Each such structure specifies a single fragment of a sparse +file. +The two fields store values as octal numbers. +The fragments are each padded to a multiple of 512 bytes +in the archive. +On extraction, the list of fragments is collected from the +header (including any extension headers), and the data +is then read and written to the file at appropriate offsets. +.It Va isextended +If this is set to non-zero, the header will be followed by additional +.Dq sparse header +records. +Each such record contains information about as many as 21 additional +sparse blocks as shown here: +.Bd -literal -offset indent +struct gnu_sparse_header { + struct { + char offset[12]; + char numbytes[12]; + } sparse[21]; + char isextended[1]; + char padding[7]; +}; +.Ed +.It Va realsize +A binary representation of the file's complete size, with a much larger range +than the POSIX file size. +In particular, with +.Cm M +type files, the current entry is only a portion of the file. +In that case, the POSIX size field will indicate the size of this +entry; the +.Va realsize +field will indicate the total size of the file. +.El +.Ss GNU tar pax archives +GNU tar 1.14 (XXX check this XXX) and later will write +pax interchange format archives when you specify the +.Fl -posix +flag. +This format follows the pax interchange format closely, +using some +.Cm SCHILY +tags and introducing new keywords to store sparse file information. +There have been three iterations of the sparse file support, referred to +as +.Dq 0.0 , +.Dq 0.1 , +and +.Dq 1.0 . +.Bl -tag -width indent +.It Cm GNU.sparse.numblocks , Cm GNU.sparse.offset , Cm GNU.sparse.numbytes , Cm GNU.sparse.size +The +.Dq 0.0 +format used an initial +.Cm GNU.sparse.numblocks +attribute to indicate the number of blocks in the file, a pair of +.Cm GNU.sparse.offset +and +.Cm GNU.sparse.numbytes +to indicate the offset and size of each block, +and a single +.Cm GNU.sparse.size +to indicate the full size of the file. +This is not the same as the size in the tar header because the +latter value does not include the size of any holes. +This format required that the order of attributes be preserved and +relied on readers accepting multiple appearances of the same attribute +names, which is not officially permitted by the standards. +.It Cm GNU.sparse.map +The +.Dq 0.1 +format used a single attribute that stored a comma-separated +list of decimal numbers. +Each pair of numbers indicated the offset and size, respectively, +of a block of data. +This does not work well if the archive is extracted by an archiver +that does not recognize this extension, since many pax implementations +simply discard unrecognized attributes. +.It Cm GNU.sparse.major , Cm GNU.sparse.minor , Cm GNU.sparse.name , Cm GNU.sparse.realsize +The +.Dq 1.0 +format stores the sparse block map in one or more 512-byte blocks +prepended to the file data in the entry body. +The pax attributes indicate the existence of this map +(via the +.Cm GNU.sparse.major +and +.Cm GNU.sparse.minor +fields) +and the full size of the file. +The +.Cm GNU.sparse.name +holds the true name of the file. +To avoid confusion, the name stored in the regular tar header +is a modified name so that extraction errors will be apparent +to users. +.El +.Ss Solaris Tar +XXX More Details Needed XXX +.Pp +Solaris tar (beginning with SunOS XXX 5.7 ?? XXX) supports an +.Dq extended +format that is fundamentally similar to pax interchange format, +with the following differences: +.Bl -bullet -compact -width indent +.It +Extended attributes are stored in an entry whose type is +.Cm X , +not +.Cm x , +as used by pax interchange format. +The detailed format of this entry appears to be the same +as detailed above for the +.Cm x +entry. +.It +An additional +.Cm A +header is used to store an ACL for the following regular entry. +The body of this entry contains a seven-digit octal number +followed by a zero byte, followed by the +textual ACL description. +The octal value is the number of ACL entries +plus a constant that indicates the ACL type: 01000000 +for POSIX.1e ACLs and 03000000 for NFSv4 ACLs. +.El +.Ss AIX Tar +XXX More details needed XXX +.Pp +AIX Tar uses a ustar-formatted header with the type +.Cm A +for storing coded ACL information. +Unlike the Solaris format, AIX tar writes this header after the +regular file body to which it applies. +The pathname in this header is either +.Cm NFS4 +or +.Cm AIXC +to indicate the type of ACL stored. +The actual ACL is stored in platform-specific binary format. +.Ss Mac OS X Tar +The tar distributed with Apple's Mac OS X stores most regular files +as two separate files in the tar archive. +The two files have the same name except that the first +one has +.Dq ._ +prepended to the last path element. +This special file stores an AppleDouble-encoded +binary blob with additional metadata about the second file, +including ACL, extended attributes, and resources. +To recreate the original file on disk, each +separate file can be extracted and the Mac OS X +.Fn copyfile +function can be used to unpack the separate +metadata file and apply it to th regular file. +Conversely, the same function provides a +.Dq pack +option to encode the extended metadata from +a file into a separate file whose contents +can then be put into a tar archive. +.Pp +Note that the Apple extended attributes interact +badly with long filenames. +Since each file is stored with the full name, +a separate set of extensions needs to be included +in the archive for each one, doubling the overhead +required for files with long names. +.Ss Summary of tar type codes +The following list is a condensed summary of the type codes +used in tar header records generated by different tar implementations. +More details about specific implementations can be found above: +.Bl -tag -compact -width XXX +.It NUL +Early tar programs stored a zero byte for regular files. +.It Cm 0 +POSIX standard type code for a regular file. +.It Cm 1 +POSIX standard type code for a hard link description. +.It Cm 2 +POSIX standard type code for a symbolic link description. +.It Cm 3 +POSIX standard type code for a character device node. +.It Cm 4 +POSIX standard type code for a block device node. +.It Cm 5 +POSIX standard type code for a directory. +.It Cm 6 +POSIX standard type code for a FIFO. +.It Cm 7 +POSIX reserved. +.It Cm 7 +GNU tar used for pre-allocated files on some systems. +.It Cm A +Solaris tar ACL description stored prior to a regular file header. +.It Cm A +AIX tar ACL description stored after the file body. +.It Cm D +GNU tar directory dump. +.It Cm K +GNU tar long linkname for the following header. +.It Cm L +GNU tar long pathname for the following header. +.It Cm M +GNU tar multivolume marker, indicating the file is a continuation of a file from the previous volume. +.It Cm N +GNU tar long filename support. +Deprecated. +.It Cm S +GNU tar sparse regular file. +.It Cm V +GNU tar tape/volume header name. +.It Cm X +Solaris tar general-purpose extension header. +.It Cm g +POSIX pax interchange format global extensions. +.It Cm x +POSIX pax interchange format per-file extensions. +.El +.Sh SEE ALSO +.Xr ar 1 , +.Xr pax 1 , +.Xr tar 1 +.Sh STANDARDS +The +.Nm tar +utility is no longer a part of POSIX or the Single Unix Standard. +It last appeared in +.St -susv2 . +It has been supplanted in subsequent standards by +.Xr pax 1 . +The ustar format is currently part of the specification for the +.Xr pax 1 +utility. +The pax interchange file format is new with +.St -p1003.1-2001 . +.Sh HISTORY +A +.Nm tar +command appeared in Seventh Edition Unix, which was released in January, 1979. +It replaced the +.Nm tp +program from Fourth Edition Unix which in turn replaced the +.Nm tap +program from First Edition Unix. +John Gilmore's +.Nm pdtar +public-domain implementation (circa 1987) was highly influential +and formed the basis of +.Nm GNU tar +(circa 1988). +Joerg Shilling's +.Nm star +archiver is another open-source (CDDL) archiver (originally developed +circa 1985) which features complete support for pax interchange +format. +.Pp +This documentation was written as part of the +.Nm libarchive +and +.Nm bsdtar +project by +.An Tim Kientzle Aq kientzle@FreeBSD.org . diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/xxhash.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/xxhash.c new file mode 100644 index 0000000000..70750bae08 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/libarchive/libarchive/xxhash.c @@ -0,0 +1,521 @@ +/* +xxHash - Fast Hash algorithm +Copyright (C) 2012-2014, Yann Collet. +BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. +* 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 COPYRIGHT HOLDERS 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 COPYRIGHT +OWNER 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. + +You can contact the author at : +- xxHash source repository : http://code.google.com/p/xxhash/ +*/ +#include "archive_platform.h" + +#include <stdlib.h> +#include <string.h> + +#include "archive_xxhash.h" + +#ifdef HAVE_LIBLZ4 + +/*************************************** +** Tuning parameters +****************************************/ +/* Unaligned memory access is automatically enabled for "common" CPU, such as x86. +** For others CPU, the compiler will be more cautious, and insert extra code to ensure aligned access is respected. +** If you know your target CPU supports unaligned memory access, you want to force this option manually to improve performance. +** You can also enable this parameter if you know your input data will always be aligned (boundaries of 4, for U32). +*/ +#if defined(__ARM_FEATURE_UNALIGNED) || defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) +# define XXH_USE_UNALIGNED_ACCESS 1 +#endif + +/* XXH_ACCEPT_NULL_INPUT_POINTER : +** If the input pointer is a null pointer, xxHash default behavior is to trigger a memory access error, since it is a bad pointer. +** When this option is enabled, xxHash output for null input pointers will be the same as a null-length input. +** This option has a very small performance cost (only measurable on small inputs). +** By default, this option is disabled. To enable it, uncomment below define : +** #define XXH_ACCEPT_NULL_INPUT_POINTER 1 + +** XXH_FORCE_NATIVE_FORMAT : +** By default, xxHash library provides endian-independent Hash values, based on little-endian convention. +** Results are therefore identical for little-endian and big-endian CPU. +** This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format. +** Should endian-independence be of no importance for your application, you may set the #define below to 1. +** It will improve speed for Big-endian CPU. +** This option has no impact on Little_Endian CPU. +*/ +#define XXH_FORCE_NATIVE_FORMAT 0 + +/*************************************** +** Compiler Specific Options +****************************************/ +/* Disable some Visual warning messages */ +#ifdef _MSC_VER /* Visual Studio */ +# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ +#endif + +#ifdef _MSC_VER /* Visual Studio */ +# define FORCE_INLINE __forceinline +#else +# ifdef __GNUC__ +# define FORCE_INLINE inline __attribute__((always_inline)) +# else +# define FORCE_INLINE inline +# endif +#endif + +/*************************************** +** Includes & Memory related functions +****************************************/ +#define XXH_malloc malloc +#define XXH_free free +#define XXH_memcpy memcpy + + +static unsigned int XXH32 (const void*, unsigned int, unsigned int); +static void* XXH32_init (unsigned int); +static XXH_errorcode XXH32_update (void*, const void*, unsigned int); +static unsigned int XXH32_digest (void*); +/*static int XXH32_sizeofState(void);*/ +static XXH_errorcode XXH32_resetState(void*, unsigned int); +#define XXH32_SIZEOFSTATE 48 +typedef struct { long long ll[(XXH32_SIZEOFSTATE+(sizeof(long long)-1))/sizeof(long long)]; } XXH32_stateSpace_t; +static unsigned int XXH32_intermediateDigest (void*); + +/*************************************** +** Basic Types +****************************************/ +#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ +# include <stdint.h> + typedef uint8_t BYTE; + typedef uint16_t U16; + typedef uint32_t U32; + typedef int32_t S32; + typedef uint64_t U64; +#else + typedef unsigned char BYTE; + typedef unsigned short U16; + typedef unsigned int U32; + typedef signed int S32; + typedef unsigned long long U64; +#endif + +#if defined(__GNUC__) && !defined(XXH_USE_UNALIGNED_ACCESS) +# define _PACKED __attribute__ ((packed)) +#else +# define _PACKED +#endif + +#if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__) +# ifdef __IBMC__ +# pragma pack(1) +# else +# pragma pack(push, 1) +# endif +#endif + +typedef struct _U32_S { U32 v; } _PACKED U32_S; + +#if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__) +# pragma pack(pop) +#endif + + +/**************************************** +** Compiler-specific Functions and Macros +*****************************************/ +#define GCC_VERSION ((__GNUC__-0) * 100 + (__GNUC_MINOR__ - 0)) + +#if GCC_VERSION >= 409 +__attribute__((__no_sanitize_undefined__)) +#endif +static inline U32 A32(const void * x) +{ + return (((const U32_S *)(x))->v); +} + +/* Note : although _rotl exists for minGW (GCC under windows), performance seems poor */ +#if defined(_MSC_VER) +# define XXH_rotl32(x,r) _rotl(x,r) +#else +# define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r))) +#endif + +#if defined(_MSC_VER) /* Visual Studio */ +# define XXH_swap32 _byteswap_ulong +#elif GCC_VERSION >= 403 +# define XXH_swap32 __builtin_bswap32 +#else +static inline U32 XXH_swap32 (U32 x) { + return ((x << 24) & 0xff000000 ) | + ((x << 8) & 0x00ff0000 ) | + ((x >> 8) & 0x0000ff00 ) | + ((x >> 24) & 0x000000ff );} +#endif + + +/*************************************** +** Constants +****************************************/ +#define PRIME32_1 2654435761U +#define PRIME32_2 2246822519U +#define PRIME32_3 3266489917U +#define PRIME32_4 668265263U +#define PRIME32_5 374761393U + + +/*************************************** +** Architecture Macros +****************************************/ +typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess; +#ifndef XXH_CPU_LITTLE_ENDIAN /* It is possible to define XXH_CPU_LITTLE_ENDIAN externally, for example using a compiler switch */ + static const int one = 1; +# define XXH_CPU_LITTLE_ENDIAN (*(const char*)(&one)) +#endif + + +/*************************************** +** Macros +****************************************/ +#define XXH_STATIC_ASSERT(c) { enum { XXH_static_assert = 1/(!!(c)) }; } /* use only *after* variable declarations */ + + +/***************************** +** Memory reads +******************************/ +typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment; + +static +FORCE_INLINE U32 XXH_readLE32_align(const U32* ptr, XXH_endianess endian, XXH_alignment align) +{ + if (align==XXH_unaligned) + return endian==XXH_littleEndian ? A32(ptr) : XXH_swap32(A32(ptr)); + else + return endian==XXH_littleEndian ? *ptr : XXH_swap32(*ptr); +} + +static +FORCE_INLINE U32 XXH_readLE32(const U32* ptr, XXH_endianess endian) { return XXH_readLE32_align(ptr, endian, XXH_unaligned); } + + +/***************************** +** Simple Hash Functions +******************************/ +static +FORCE_INLINE U32 XXH32_endian_align(const void* input, unsigned int len, U32 seed, XXH_endianess endian, XXH_alignment align) +{ + const BYTE* p = (const BYTE*)input; + const BYTE* bEnd = p + len; + U32 h32; +#define XXH_get32bits(p) XXH_readLE32_align((const U32*)p, endian, align) + +#ifdef XXH_ACCEPT_NULL_INPUT_POINTER + if (p==NULL) { len=0; bEnd=p=(const BYTE*)(size_t)16; } +#endif + + if (len>=16) + { + const BYTE* const limit = bEnd - 16; + U32 v1 = seed + PRIME32_1 + PRIME32_2; + U32 v2 = seed + PRIME32_2; + U32 v3 = seed + 0; + U32 v4 = seed - PRIME32_1; + + do + { + v1 += XXH_get32bits(p) * PRIME32_2; v1 = XXH_rotl32(v1, 13); v1 *= PRIME32_1; p+=4; + v2 += XXH_get32bits(p) * PRIME32_2; v2 = XXH_rotl32(v2, 13); v2 *= PRIME32_1; p+=4; + v3 += XXH_get32bits(p) * PRIME32_2; v3 = XXH_rotl32(v3, 13); v3 *= PRIME32_1; p+=4; + v4 += XXH_get32bits(p) * PRIME32_2; v4 = XXH_rotl32(v4, 13); v4 *= PRIME32_1; p+=4; + } while (p<=limit); + + h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18); + } + else + { + h32 = seed + PRIME32_5; + } + + h32 += (U32) len; + + while (p<=bEnd-4) + { + h32 += XXH_get32bits(p) * PRIME32_3; + h32 = XXH_rotl32(h32, 17) * PRIME32_4 ; + p+=4; + } + + while (p<bEnd) + { + h32 += (*p) * PRIME32_5; + h32 = XXH_rotl32(h32, 11) * PRIME32_1 ; + p++; + } + + h32 ^= h32 >> 15; + h32 *= PRIME32_2; + h32 ^= h32 >> 13; + h32 *= PRIME32_3; + h32 ^= h32 >> 16; + + return h32; +} + + +U32 XXH32(const void* input, unsigned int len, U32 seed) +{ +#if 0 + // Simple version, good for code maintenance, but unfortunately slow for small inputs + void* state = XXH32_init(seed); + XXH32_update(state, input, len); + return XXH32_digest(state); +#else + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + +# if !defined(XXH_USE_UNALIGNED_ACCESS) + if ((((size_t)input) & 3) == 0) /* Input is aligned, let's leverage the speed advantage */ + { + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); + else + return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); + } +# endif + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); + else + return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); +#endif +} + +/***************************** +** Advanced Hash Functions +******************************/ + +struct XXH_state32_t +{ + U64 total_len; + U32 seed; + U32 v1; + U32 v2; + U32 v3; + U32 v4; + int memsize; + char memory[16]; +}; + +#if 0 +static +int XXH32_sizeofState(void) +{ + XXH_STATIC_ASSERT(XXH32_SIZEOFSTATE >= sizeof(struct XXH_state32_t)); /* A compilation error here means XXH32_SIZEOFSTATE is not large enough */ + return sizeof(struct XXH_state32_t); +} +#endif + +static +XXH_errorcode XXH32_resetState(void* state_in, U32 seed) +{ + struct XXH_state32_t * state = (struct XXH_state32_t *) state_in; + state->seed = seed; + state->v1 = seed + PRIME32_1 + PRIME32_2; + state->v2 = seed + PRIME32_2; + state->v3 = seed + 0; + state->v4 = seed - PRIME32_1; + state->total_len = 0; + state->memsize = 0; + return XXH_OK; +} + +static +void* XXH32_init (U32 seed) +{ + void* state = XXH_malloc (sizeof(struct XXH_state32_t)); + XXH32_resetState(state, seed); + return state; +} + +static +FORCE_INLINE XXH_errorcode XXH32_update_endian (void* state_in, const void* input, int len, XXH_endianess endian) +{ + struct XXH_state32_t * state = (struct XXH_state32_t *) state_in; + const BYTE* p = (const BYTE*)input; + const BYTE* const bEnd = p + len; + +#ifdef XXH_ACCEPT_NULL_INPUT_POINTER + if (input==NULL) return XXH_ERROR; +#endif + + state->total_len += len; + + if (state->memsize + len < 16) /* fill in tmp buffer */ + { + XXH_memcpy(state->memory + state->memsize, input, len); + state->memsize += len; + return XXH_OK; + } + + if (state->memsize) /* some data left from previous update */ + { + XXH_memcpy(state->memory + state->memsize, input, 16-state->memsize); + { + const U32* p32 = (const U32*)state->memory; + state->v1 += XXH_readLE32(p32, endian) * PRIME32_2; state->v1 = XXH_rotl32(state->v1, 13); state->v1 *= PRIME32_1; p32++; + state->v2 += XXH_readLE32(p32, endian) * PRIME32_2; state->v2 = XXH_rotl32(state->v2, 13); state->v2 *= PRIME32_1; p32++; + state->v3 += XXH_readLE32(p32, endian) * PRIME32_2; state->v3 = XXH_rotl32(state->v3, 13); state->v3 *= PRIME32_1; p32++; + state->v4 += XXH_readLE32(p32, endian) * PRIME32_2; state->v4 = XXH_rotl32(state->v4, 13); state->v4 *= PRIME32_1; p32++; + } + p += 16-state->memsize; + state->memsize = 0; + } + + if (p <= bEnd-16) + { + const BYTE* const limit = bEnd - 16; + U32 v1 = state->v1; + U32 v2 = state->v2; + U32 v3 = state->v3; + U32 v4 = state->v4; + + do + { + v1 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v1 = XXH_rotl32(v1, 13); v1 *= PRIME32_1; p+=4; + v2 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v2 = XXH_rotl32(v2, 13); v2 *= PRIME32_1; p+=4; + v3 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v3 = XXH_rotl32(v3, 13); v3 *= PRIME32_1; p+=4; + v4 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v4 = XXH_rotl32(v4, 13); v4 *= PRIME32_1; p+=4; + } while (p<=limit); + + state->v1 = v1; + state->v2 = v2; + state->v3 = v3; + state->v4 = v4; + } + + if (p < bEnd) + { + XXH_memcpy(state->memory, p, bEnd-p); + state->memsize = (int)(bEnd-p); + } + + return XXH_OK; +} + +static +XXH_errorcode XXH32_update (void* state_in, const void* input, unsigned int len) +{ + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_update_endian(state_in, input, len, XXH_littleEndian); + else + return XXH32_update_endian(state_in, input, len, XXH_bigEndian); +} + + + +static +FORCE_INLINE U32 XXH32_intermediateDigest_endian (void* state_in, XXH_endianess endian) +{ + struct XXH_state32_t * state = (struct XXH_state32_t *) state_in; + const BYTE * p = (const BYTE*)state->memory; + BYTE* bEnd = (BYTE*)state->memory + state->memsize; + U32 h32; + + if (state->total_len >= 16) + { + h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18); + } + else + { + h32 = state->seed + PRIME32_5; + } + + h32 += (U32) state->total_len; + + while (p<=bEnd-4) + { + h32 += XXH_readLE32((const U32*)p, endian) * PRIME32_3; + h32 = XXH_rotl32(h32, 17) * PRIME32_4; + p+=4; + } + + while (p<bEnd) + { + h32 += (*p) * PRIME32_5; + h32 = XXH_rotl32(h32, 11) * PRIME32_1; + p++; + } + + h32 ^= h32 >> 15; + h32 *= PRIME32_2; + h32 ^= h32 >> 13; + h32 *= PRIME32_3; + h32 ^= h32 >> 16; + + return h32; +} + +static +U32 XXH32_intermediateDigest (void* state_in) +{ + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_intermediateDigest_endian(state_in, XXH_littleEndian); + else + return XXH32_intermediateDigest_endian(state_in, XXH_bigEndian); +} + +static +U32 XXH32_digest (void* state_in) +{ + U32 h32 = XXH32_intermediateDigest(state_in); + + XXH_free(state_in); + + return h32; +} + +const +struct archive_xxhash __archive_xxhash = { + XXH32, + XXH32_init, + XXH32_update, + XXH32_digest +}; +#else + +/* + * Define an empty version of the struct if we aren't using the LZ4 library. + */ +const +struct archive_xxhash __archive_xxhash = { + NULL, + NULL, + NULL, + NULL +}; + +#endif /* HAVE_LIBLZ4 */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/meson.build b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/meson.build new file mode 100644 index 0000000000..b7d3a7a0cb --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/deps/meson.build @@ -0,0 +1,110 @@ +if get_option('kernel') == 'linux' + kconfig = [] + + if get_option('engine') in ['asbestos', 'unicorn'] + kconfig += 'CONFIG_ISH_EMULATOR_NONE=y' + else + error('Engine "' + get_option('engine') + '" not supported for linux kernel') + endif + + kconfig += get_option('kconfig') + meson_fragment = configure_file( + command: [ + find_program('kconfig-fragment.sh'), + '@OUTPUT@', + ] + kconfig, + output: 'linux-meson.config', + ) + + build_linux = custom_target('linux', + command: [ + 'env', + 'HOSTCC='+ ' '.join(meson.get_compiler('c', native: true).cmd_array() + get_option('build.c_args')), + 'CC='+ ' '.join(meson.get_compiler('c', native: false).cmd_array() + get_option('c_args')), + # hack to find the right directories because meson is bad + 'ISH_SRC='+ meson.project_source_root(), + 'ISH_BUILD='+ meson.project_build_root(), + 'KCONFIG_FRAGMENTS='+ ' '.join([ + meson.project_source_root() / 'deps/linux.config', + meson.project_build_root() / 'deps/linux-meson.config', + ]), + find_program('linux-build.sh'), + '@OUTPUT0@', + '@SOURCE_ROOT@/deps/linux', + '@OUTPUT1@', + '@DEPFILE@', + ], + depend_files: [ + 'makefilter.py', + 'linux.config', + meson_fragment, + ], + console: true, + depfile: 'linux.d', + output: ['liblinux.a', 'linux']) + + # Create empty include directories so the liblinux declaration doesn't throw File Not Found + run_command('mkdir', [ + '-p', + meson.current_build_dir()+'/linux/include/generated/uapi', + meson.current_build_dir()+'/linux/arch/ish/include/generated/uapi'], + check: false) + + linux_headers = declare_dependency( + include_directories: [include_directories( + 'linux/arch/ish/include', + 'linux/arch/ish/include/generated', + 'linux/include', + 'linux/arch/ish/include/uapi', + 'linux/arch/ish/include/generated/uapi', + 'linux/include/uapi', + 'linux/include/generated/uapi', + )] + includes, + compile_args: [ + # '-nostdlibinc', + '-include', 'linux/compiler_attributes.h', + '-include', 'linux/kconfig.h', + '-D__KERNEL__', '-U__weak', + # Warnings triggered by kernel headers. Some of these + # warn of UB, but I feel all right with silencing them + # because if clang does something to break Linux + # there'll be hell to pay. + '-Wno-unused-parameter', + '-Wno-sign-compare', + '-Wno-implicit-fallthrough', + '-Wno-pointer-sign', + '-Wno-null-pointer-arithmetic', + ], + link_with: [build_linux[0]], + sources: [build_linux[1]], + ) + + user_linux_headers = declare_dependency( + include_directories: include_directories( + 'linux/arch/ish/include', + 'linux/include', + ), + compile_args: [ + '-include', 'user.h', + '-include', 'linux/kconfig.h', + ], + sources: [build_linux[1]], + ) + + if host_machine.system() == 'darwin' + liblinux_link_args = [ + '-Wl,-ld_classic', + '-sectalign', '__DATA', '__percpu_first', '1000', + '-sectalign', '__DATA', '__tracepoints', '20', + ] + elif host_machine.system() == 'linux' + liblinux_link_args = [ + '-Wl,-T', meson.current_build_dir()+'/linux/arch/ish/kernel/vmlinux.lds' + ] + endif + liblinux = declare_dependency( + link_whole: [build_linux[0]], + sources: [build_linux[1]], + link_args: liblinux_link_args, + ) +endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/arch/arm64/cpu.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/arch/arm64/cpu.h new file mode 100644 index 0000000000..004d3c3f28 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/arch/arm64/cpu.h @@ -0,0 +1,164 @@ +#ifndef EMU_ARCH_ARM64_CPU_H +#define EMU_ARCH_ARM64_CPU_H + +#include "misc.h" +#include "emu/mmu.h" + +#ifdef __KERNEL__ +#include <linux/stddef.h> +#else +#include <stddef.h> +#endif + +// ARM64 NEON/FP register - 128-bit vector +union arm64_vreg { + __uint128_t q; // Full 128-bit quad-word + uint64_t d[2]; // Two 64-bit double-words + uint32_t s[4]; // Four 32-bit single-words + uint16_t h[8]; // Eight 16-bit half-words + uint8_t b[16]; // Sixteen 8-bit bytes + float f32[4]; // Four single-precision floats + double f64[2]; // Two double-precision floats +}; +static_assert(sizeof(union arm64_vreg) == 16, "arm64_vreg size"); + +struct cpu_state { + struct mmu *mmu; + long cycle; + + // 31 general-purpose 64-bit registers (X0-X30) + // X30 is the link register (LR) + // Note: X31 reads as zero (ZR) or stack pointer (SP) depending on context + union { + struct { + uint64_t x0, x1, x2, x3, x4, x5, x6, x7; + uint64_t x8, x9, x10, x11, x12, x13, x14, x15; + uint64_t x16, x17, x18, x19, x20, x21, x22, x23; + uint64_t x24, x25, x26, x27, x28, x29, x30; + }; + uint64_t regs[31]; + }; + + // Stack pointer (separate from general registers) + uint64_t sp; + + // Program counter + uint64_t pc; + + // PSTATE (Process State) - condition flags + // These are the NZCV flags from the CPSR + // Stored as individual bytes to allow offsetof() to work + uint8_t nf; // Negative flag + uint8_t zf; // Zero flag + uint8_t cf; // Carry flag + uint8_t vf; // Overflow flag + + // Combined NZCV value for JIT use (bits 31:28 as in CPSR) + // This must be kept in sync with nf/zf/cf/vf + uint32_t nzcv; + + // NEON/FP: 32 x 128-bit vector registers (V0-V31) + union arm64_vreg fp[32]; + + // Floating-point Control Register + uint32_t fpcr; + + // Floating-point Status Register + uint32_t fpsr; + + // Thread Local Storage pointer (TPIDR_EL0) + uint64_t tls_ptr; + + // Exclusive monitor for LDXR/STXR atomicity + uint64_t excl_addr; // Guest address from last LDXR (0xFFFFFFFF = invalid) + uint64_t excl_val; // Value loaded by last LDXR + + // For the page fault handler + addr_t segfault_addr; + bool segfault_was_write; + + dword_t trapno; + + // Access atomically + bool *poked_ptr; + bool _poked; + + // Exclusive monitor for LDXP/STXP pair atomicity. + // Keep these after the crash-handler-sensitive fields above so the + // hard-coded crash offsets used in main.c stay stable. + uint64_t excl_pair_addr; + uint64_t excl_pair_val_lo; + uint64_t excl_pair_val_hi; + uint32_t excl_pair_size; +}; + +#ifndef CPU_OFFSET +#define CPU_OFFSET(field) offsetof(struct cpu_state, field) +#endif + +static_assert(CPU_OFFSET(x0) == CPU_OFFSET(regs[0]), "register order"); +static_assert(CPU_OFFSET(x30) == CPU_OFFSET(regs[30]), "register order"); +static_assert(sizeof(struct cpu_state) < 0xffff, "cpu struct is too big for vector gadgets"); + +// PSTATE flag helpers +#define ARM64_NF (cpu->nf) +#define ARM64_ZF (cpu->zf) +#define ARM64_CF (cpu->cf) +#define ARM64_VF (cpu->vf) + +// PSTATE packed as NZCV (bits 31:28 in CPSR format) +static inline uint32_t arm64_get_nzcv(struct cpu_state *cpu) { + return cpu->nzcv; +} + +static inline void arm64_set_nzcv(struct cpu_state *cpu, uint32_t nzcv_val) { + cpu->nzcv = nzcv_val; + cpu->nf = (uint8_t)((nzcv_val >> 31) & 1); + cpu->zf = (uint8_t)((nzcv_val >> 30) & 1); + cpu->cf = (uint8_t)((nzcv_val >> 29) & 1); + cpu->vf = (uint8_t)((nzcv_val >> 28) & 1); +} + +// Sync individual flags to combined nzcv field +static inline void arm64_sync_nzcv(struct cpu_state *cpu) { + cpu->nzcv = ((cpu->nf & 1) << 31) | ((cpu->zf & 1) << 30) | + ((cpu->cf & 1) << 29) | ((cpu->vf & 1) << 28); +} + +// Collapse flags (no-op for canonical ARM64 NZCV state) +static inline void collapse_flags(struct cpu_state *cpu) { + // ARM64 flags are always in their canonical form + (void)cpu; +} + +// Expand flags (no-op for canonical ARM64 NZCV state) +static inline void expand_flags(struct cpu_state *cpu) { + // ARM64 flags are always in their canonical form + (void)cpu; +} + +// Register indices +enum arm64_reg { + reg_x0 = 0, reg_x1, reg_x2, reg_x3, reg_x4, reg_x5, reg_x6, reg_x7, + reg_x8, reg_x9, reg_x10, reg_x11, reg_x12, reg_x13, reg_x14, reg_x15, + reg_x16, reg_x17, reg_x18, reg_x19, reg_x20, reg_x21, reg_x22, reg_x23, + reg_x24, reg_x25, reg_x26, reg_x27, reg_x28, reg_x29, reg_x30, + reg_count, + reg_lr = reg_x30, // Link register + reg_fp = reg_x29, // Frame pointer + reg_none = reg_count, +}; + +static inline const char *arm64_reg_name(enum arm64_reg reg) { + static const char *names[] = { + "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", + "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", + "x16", "x17", "x18", "x19", "x20", "x21", "x22", "x23", + "x24", "x25", "x26", "x27", "x28", "x29", "x30" + }; + if (reg < reg_count) + return names[reg]; + return "?"; +} + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/arch/arm64/decode.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/arch/arm64/decode.h new file mode 100644 index 0000000000..5619ec9ffd --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/arch/arm64/decode.h @@ -0,0 +1,154 @@ +#ifndef EMU_ARCH_ARM64_DECODE_H +#define EMU_ARCH_ARM64_DECODE_H + +#include "misc.h" +#include "emu/cpu.h" +#include "emu/tlb.h" + +/* + * ARM64 Instruction Decoding + * + * ARM64 uses fixed 4-byte (32-bit) instructions with regular top-level + * encoding groups. + * + * Top-level encoding groups (bits 28:25): + * 0000 - Reserved + * 100x - Data processing (immediate) + * 101x - Branches, exceptions, system + * x1x0 - Loads and stores + * x101 - Data processing (register) + * x111 - Data processing (SIMD and FP) + */ + +// Instruction group extraction +#define ARM64_OP0(insn) (((insn) >> 25) & 0xf) + +// Common field extractions +#define ARM64_RD(insn) (((insn) >> 0) & 0x1f) // Destination register +#define ARM64_RN(insn) (((insn) >> 5) & 0x1f) // First source register +#define ARM64_RM(insn) (((insn) >> 16) & 0x1f) // Second source register +#define ARM64_RT(insn) (((insn) >> 0) & 0x1f) // Transfer register (load/store) +#define ARM64_RT2(insn) (((insn) >> 10) & 0x1f) // Second transfer register + +// Instruction size (sf bit, bit 31) +#define ARM64_SF(insn) (((insn) >> 31) & 0x1) // 0=32-bit, 1=64-bit + +// Condition codes (used in conditional branches, select, etc.) +enum arm64_cond { + COND_EQ = 0, // Equal (Z==1) + COND_NE = 1, // Not equal (Z==0) + COND_CS = 2, // Carry set / unsigned higher or same (C==1) + COND_CC = 3, // Carry clear / unsigned lower (C==0) + COND_MI = 4, // Minus / negative (N==1) + COND_PL = 5, // Plus / positive or zero (N==0) + COND_VS = 6, // Overflow (V==1) + COND_VC = 7, // No overflow (V==0) + COND_HI = 8, // Unsigned higher (C==1 && Z==0) + COND_LS = 9, // Unsigned lower or same (C==0 || Z==1) + COND_GE = 10, // Signed greater or equal (N==V) + COND_LT = 11, // Signed less than (N!=V) + COND_GT = 12, // Signed greater than (Z==0 && N==V) + COND_LE = 13, // Signed less or equal (Z==1 || N!=V) + COND_AL = 14, // Always + COND_NV = 15, // Always (same as AL) +}; + +// Evaluate a condition code against the current flags +static inline bool arm64_cond_check(struct cpu_state *cpu, enum arm64_cond cond) { + bool result; + switch (cond >> 1) { + case 0: result = cpu->zf; break; // EQ/NE + case 1: result = cpu->cf; break; // CS/CC + case 2: result = cpu->nf; break; // MI/PL + case 3: result = cpu->vf; break; // VS/VC + case 4: result = cpu->cf && !cpu->zf; break; // HI/LS + case 5: result = cpu->nf == cpu->vf; break; // GE/LT + case 6: result = !cpu->zf && (cpu->nf == cpu->vf); break; // GT/LE + case 7: result = true; break; // AL/NV + default: result = false; break; + } + // Invert result for odd condition codes (except AL/NV) + if ((cond & 1) && cond != COND_AL && cond != COND_NV) + result = !result; + return result; +} + +// Instruction type classification +enum arm64_insn_type { + INSN_UNKNOWN = 0, + INSN_DP_IMM, // Data processing (immediate) + INSN_BRANCH, // Branches + INSN_EXCEPTION, // Exception generation + INSN_SYSTEM, // System instructions + INSN_LD_ST, // Loads and stores + INSN_DP_REG, // Data processing (register) + INSN_SIMD_FP, // SIMD and floating-point +}; + +// Classify an instruction by its top-level encoding +static inline enum arm64_insn_type arm64_classify_insn(uint32_t insn) { + uint32_t op0 = ARM64_OP0(insn); + + switch (op0) { + case 0b1000: case 0b1001: + return INSN_DP_IMM; + case 0b1010: case 0b1011: + // Need to check bits 31-22 for specific type + // System instructions: 1101_0101_00 (bits 31-22 = 0x354) + if ((insn >> 22) == 0x354) + return INSN_SYSTEM; + // Exception generation: 1101_0100 (bits 31-24 = 0xd4) + if ((insn >> 24) == 0xd4) + return INSN_EXCEPTION; + // Everything else is a branch + return INSN_BRANCH; + case 0b0100: case 0b0110: case 0b1100: case 0b1110: + return INSN_LD_ST; + case 0b0101: case 0b1101: + return INSN_DP_REG; + case 0b0111: case 0b1111: + return INSN_SIMD_FP; + default: + return INSN_UNKNOWN; + } +} + +// Read a 32-bit instruction from memory +static inline bool arm64_read_insn(addr_t *ip, struct tlb *tlb, uint32_t *insn) { + if (!tlb_read(tlb, *ip, insn, sizeof(*insn))) + return false; + *ip += 4; + return true; +} + +// Sign-extend a value +static inline int64_t arm64_sign_extend(uint64_t val, unsigned bits) { + uint64_t sign_bit = 1ULL << (bits - 1); + if (val & sign_bit) + return (int64_t)(val | (~0ULL << bits)); + return (int64_t)val; +} + +// Extract immediate from PC-relative branch instructions (26-bit signed offset) +static inline int64_t arm64_branch_imm26(uint32_t insn) { + return arm64_sign_extend((insn & 0x03ffffff) << 2, 28); +} + +// Extract immediate from conditional branch instructions (19-bit signed offset) +static inline int64_t arm64_branch_imm19(uint32_t insn) { + return arm64_sign_extend(((insn >> 5) & 0x7ffff) << 2, 21); +} + +// Extract immediate from test/compare-and-branch instructions (14-bit signed offset) +static inline int64_t arm64_branch_imm14(uint32_t insn) { + return arm64_sign_extend(((insn >> 5) & 0x3fff) << 2, 16); +} + +// Extract immediate from ADR/ADRP instructions +static inline int64_t arm64_adr_imm(uint32_t insn) { + uint64_t immlo = (insn >> 29) & 0x3; + uint64_t immhi = (insn >> 5) & 0x7ffff; + return arm64_sign_extend((immhi << 2) | immlo, 21); +} + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/arch/arm64/fpu.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/arch/arm64/fpu.c new file mode 100644 index 0000000000..cdcae79f79 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/arch/arm64/fpu.c @@ -0,0 +1,290 @@ +/* + * ARM64 NEON/FP support + * + * This provides basic floating-point and SIMD operations for ARM64 emulation. + * ARM64 has 32 128-bit vector registers (V0-V31) which can be accessed as: + * - Q0-Q31: 128-bit quad-word + * - D0-D31: 64-bit double-word (low 64 bits of V registers) + * - S0-S31: 32-bit single-word (low 32 bits of V registers) + * - H0-H31: 16-bit half-word (low 16 bits of V registers) + * - B0-B31: 8-bit byte (low 8 bits of V registers) + */ + +#include <math.h> +#include <string.h> +#include "emu/cpu.h" + +// FPCR (Floating-point Control Register) bits +#define FPCR_FZ (1 << 24) // Flush-to-zero mode +#define FPCR_DN (1 << 25) // Default NaN mode +#define FPCR_AHP (1 << 26) // Alternative half-precision +#define FPCR_RMODE_SHIFT 22 // Rounding mode bits 23:22 +#define FPCR_RMODE_MASK 0x3 + +// FPSR (Floating-point Status Register) bits +#define FPSR_IOC (1 << 0) // Invalid Operation cumulative +#define FPSR_DZC (1 << 1) // Division by Zero cumulative +#define FPSR_OFC (1 << 2) // Overflow cumulative +#define FPSR_UFC (1 << 3) // Underflow cumulative +#define FPSR_IXC (1 << 4) // Inexact cumulative +#define FPSR_IDC (1 << 7) // Input Denormal cumulative +#define FPSR_QC (1 << 27) // Cumulative saturation (SIMD) +#define FPSR_V (1 << 28) // Overflow flag +#define FPSR_C (1 << 29) // Carry flag +#define FPSR_Z (1 << 30) // Zero flag +#define FPSR_N (1 << 31) // Negative flag + +// Rounding modes +enum arm64_rounding_mode { + ROUND_TIEEVEN = 0, // Round to nearest, ties to even + ROUND_POSINF = 1, // Round towards +infinity + ROUND_NEGINF = 2, // Round towards -infinity + ROUND_ZERO = 3, // Round towards zero +}; + +// Get current rounding mode from FPCR +static inline enum arm64_rounding_mode arm64_get_rounding_mode(struct cpu_state *cpu) { + return (cpu->fpcr >> FPCR_RMODE_SHIFT) & FPCR_RMODE_MASK; +} + +// Initialize FP state +void arm64_fp_init(struct cpu_state *cpu) { + memset(cpu->fp, 0, sizeof(cpu->fp)); + cpu->fpcr = 0; + cpu->fpsr = 0; +} + +// Clear all exception flags +void arm64_fp_clear_exceptions(struct cpu_state *cpu) { + cpu->fpsr &= ~(FPSR_IOC | FPSR_DZC | FPSR_OFC | FPSR_UFC | FPSR_IXC | FPSR_IDC); +} + +// Single-precision operations +void arm64_fadd_s(struct cpu_state *cpu, int rd, int rn, int rm) { + float a = cpu->fp[rn].f32[0]; + float b = cpu->fp[rm].f32[0]; + float result = a + b; + cpu->fp[rd].q = 0; // Clear upper bits + cpu->fp[rd].f32[0] = result; +} + +void arm64_fsub_s(struct cpu_state *cpu, int rd, int rn, int rm) { + float a = cpu->fp[rn].f32[0]; + float b = cpu->fp[rm].f32[0]; + float result = a - b; + cpu->fp[rd].q = 0; + cpu->fp[rd].f32[0] = result; +} + +void arm64_fmul_s(struct cpu_state *cpu, int rd, int rn, int rm) { + float a = cpu->fp[rn].f32[0]; + float b = cpu->fp[rm].f32[0]; + float result = a * b; + cpu->fp[rd].q = 0; + cpu->fp[rd].f32[0] = result; +} + +void arm64_fdiv_s(struct cpu_state *cpu, int rd, int rn, int rm) { + float a = cpu->fp[rn].f32[0]; + float b = cpu->fp[rm].f32[0]; + float result = a / b; + cpu->fp[rd].q = 0; + cpu->fp[rd].f32[0] = result; +} + +void arm64_fsqrt_s(struct cpu_state *cpu, int rd, int rn) { + float a = cpu->fp[rn].f32[0]; + float result = sqrtf(a); + cpu->fp[rd].q = 0; + cpu->fp[rd].f32[0] = result; +} + +void arm64_fabs_s(struct cpu_state *cpu, int rd, int rn) { + float a = cpu->fp[rn].f32[0]; + float result = fabsf(a); + cpu->fp[rd].q = 0; + cpu->fp[rd].f32[0] = result; +} + +void arm64_fneg_s(struct cpu_state *cpu, int rd, int rn) { + float a = cpu->fp[rn].f32[0]; + float result = -a; + cpu->fp[rd].q = 0; + cpu->fp[rd].f32[0] = result; +} + +// Double-precision operations +void arm64_fadd_d(struct cpu_state *cpu, int rd, int rn, int rm) { + double a = cpu->fp[rn].f64[0]; + double b = cpu->fp[rm].f64[0]; + double result = a + b; + cpu->fp[rd].q = 0; + cpu->fp[rd].f64[0] = result; +} + +void arm64_fsub_d(struct cpu_state *cpu, int rd, int rn, int rm) { + double a = cpu->fp[rn].f64[0]; + double b = cpu->fp[rm].f64[0]; + double result = a - b; + cpu->fp[rd].q = 0; + cpu->fp[rd].f64[0] = result; +} + +void arm64_fmul_d(struct cpu_state *cpu, int rd, int rn, int rm) { + double a = cpu->fp[rn].f64[0]; + double b = cpu->fp[rm].f64[0]; + double result = a * b; + cpu->fp[rd].q = 0; + cpu->fp[rd].f64[0] = result; +} + +void arm64_fdiv_d(struct cpu_state *cpu, int rd, int rn, int rm) { + double a = cpu->fp[rn].f64[0]; + double b = cpu->fp[rm].f64[0]; + double result = a / b; + cpu->fp[rd].q = 0; + cpu->fp[rd].f64[0] = result; +} + +void arm64_fsqrt_d(struct cpu_state *cpu, int rd, int rn) { + double a = cpu->fp[rn].f64[0]; + double result = sqrt(a); + cpu->fp[rd].q = 0; + cpu->fp[rd].f64[0] = result; +} + +void arm64_fabs_d(struct cpu_state *cpu, int rd, int rn) { + double a = cpu->fp[rn].f64[0]; + double result = fabs(a); + cpu->fp[rd].q = 0; + cpu->fp[rd].f64[0] = result; +} + +void arm64_fneg_d(struct cpu_state *cpu, int rd, int rn) { + double a = cpu->fp[rn].f64[0]; + double result = -a; + cpu->fp[rd].q = 0; + cpu->fp[rd].f64[0] = result; +} + +// Floating-point compare and set flags +void arm64_fcmp_s(struct cpu_state *cpu, int rn, int rm) { + float a = cpu->fp[rn].f32[0]; + float b = cpu->fp[rm].f32[0]; + + if (isnan(a) || isnan(b)) { + // Unordered + cpu->nf = 0; + cpu->zf = 0; + cpu->cf = 1; + cpu->vf = 1; + } else if (a == b) { + cpu->nf = 0; + cpu->zf = 1; + cpu->cf = 1; + cpu->vf = 0; + } else if (a < b) { + cpu->nf = 1; + cpu->zf = 0; + cpu->cf = 0; + cpu->vf = 0; + } else { + cpu->nf = 0; + cpu->zf = 0; + cpu->cf = 1; + cpu->vf = 0; + } + arm64_sync_nzcv(cpu); +} + +void arm64_fcmp_d(struct cpu_state *cpu, int rn, int rm) { + double a = cpu->fp[rn].f64[0]; + double b = cpu->fp[rm].f64[0]; + + if (isnan(a) || isnan(b)) { + cpu->nf = 0; + cpu->zf = 0; + cpu->cf = 1; + cpu->vf = 1; + } else if (a == b) { + cpu->nf = 0; + cpu->zf = 1; + cpu->cf = 1; + cpu->vf = 0; + } else if (a < b) { + cpu->nf = 1; + cpu->zf = 0; + cpu->cf = 0; + cpu->vf = 0; + } else { + cpu->nf = 0; + cpu->zf = 0; + cpu->cf = 1; + cpu->vf = 0; + } + arm64_sync_nzcv(cpu); +} + +// Conversions +void arm64_fcvtzs_s_w(struct cpu_state *cpu, int rd, int rn) { + float a = cpu->fp[rn].f32[0]; + cpu->regs[rd] = (int32_t)truncf(a); +} + +void arm64_fcvtzs_d_w(struct cpu_state *cpu, int rd, int rn) { + double a = cpu->fp[rn].f64[0]; + cpu->regs[rd] = (int32_t)trunc(a); +} + +void arm64_fcvtzs_s_x(struct cpu_state *cpu, int rd, int rn) { + float a = cpu->fp[rn].f32[0]; + cpu->regs[rd] = (int64_t)truncf(a); +} + +void arm64_fcvtzs_d_x(struct cpu_state *cpu, int rd, int rn) { + double a = cpu->fp[rn].f64[0]; + cpu->regs[rd] = (int64_t)trunc(a); +} + +void arm64_scvtf_w_s(struct cpu_state *cpu, int rd, int rn) { + int32_t a = (int32_t)cpu->regs[rn]; + cpu->fp[rd].q = 0; + cpu->fp[rd].f32[0] = (float)a; +} + +void arm64_scvtf_x_s(struct cpu_state *cpu, int rd, int rn) { + int64_t a = (int64_t)cpu->regs[rn]; + cpu->fp[rd].q = 0; + cpu->fp[rd].f32[0] = (float)a; +} + +void arm64_scvtf_w_d(struct cpu_state *cpu, int rd, int rn) { + int32_t a = (int32_t)cpu->regs[rn]; + cpu->fp[rd].q = 0; + cpu->fp[rd].f64[0] = (double)a; +} + +void arm64_scvtf_x_d(struct cpu_state *cpu, int rd, int rn) { + int64_t a = (int64_t)cpu->regs[rn]; + cpu->fp[rd].q = 0; + cpu->fp[rd].f64[0] = (double)a; +} + +// Move between GP and FP registers +void arm64_fmov_s_w(struct cpu_state *cpu, int rd, int rn) { + cpu->fp[rd].q = 0; + cpu->fp[rd].s[0] = (uint32_t)cpu->regs[rn]; +} + +void arm64_fmov_d_x(struct cpu_state *cpu, int rd, int rn) { + cpu->fp[rd].q = 0; + cpu->fp[rd].d[0] = cpu->regs[rn]; +} + +void arm64_fmov_w_s(struct cpu_state *cpu, int rd, int rn) { + cpu->regs[rd] = cpu->fp[rn].s[0]; +} + +void arm64_fmov_x_d(struct cpu_state *cpu, int rd, int rn) { + cpu->regs[rd] = cpu->fp[rn].d[0]; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/cpu.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/cpu.h new file mode 100644 index 0000000000..e5d4c8d0a0 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/cpu.h @@ -0,0 +1,27 @@ +#ifndef EMU_CPU_H +#define EMU_CPU_H + +#include "misc.h" +#include "emu/mmu.h" + +#ifdef __KERNEL__ +#include <linux/stddef.h> +#else +#include <stddef.h> +#endif + +// Include architecture-specific CPU state definition +#if !defined(GUEST_ARM64) +#error "Only the ARM64 guest backend is supported" +#endif +#include "emu/arch/arm64/cpu.h" + +// Common CPU interface +struct cpu_state; +struct tlb; +int cpu_run_to_interrupt(struct cpu_state *cpu, struct tlb *tlb); +void cpu_poke(struct cpu_state *cpu); + +#define CPU_OFFSET(field) offsetof(struct cpu_state, field) + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/interrupt.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/interrupt.h new file mode 100644 index 0000000000..888b036ffc --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/interrupt.h @@ -0,0 +1,16 @@ +// Intel standard interrupts +// Any interrupt not handled specially becomes a SIGSEGV +#define INT_NONE -1 +#define INT_DIV 0 +#define INT_DEBUG 1 +#define INT_NMI 2 +#define INT_BREAKPOINT 3 +#define INT_OVERFLOW 4 +#define INT_BOUND 5 +#define INT_UNDEFINED 6 +#define INT_FPU 7 // do not try to use the fpu. instead, try to realize the truth: there is no fpu. +#define INT_DOUBLE 8 // interrupt during interrupt, i.e. interruptception +#define INT_GPF 13 +#define INT_TIMER 32 +#define INT_SYSCALL 0x80 +#define INT_JIT_CRASH 0x100 // JIT SIGSEGV recovery (stale TLB after CoW) diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/mmu.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/mmu.h new file mode 100644 index 0000000000..9dfce52f64 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/mmu.h @@ -0,0 +1,44 @@ +#ifndef EMU_CPU_MEM_H +#define EMU_CPU_MEM_H + +#include "misc.h" + +// ARM64 page number type: 48-bit address space → 36-bit page numbers. +typedef uint64_t page_t; +typedef uint64_t pages_t; +#define BAD_PAGE 0x1000000000ULL // Invalid page marker (beyond 36-bit page range) +#define MEM_PAGES BAD_PAGE // Upper bound for iteration (not allocated as array) + +#ifndef __KERNEL__ +#define PAGE_BITS 12 +#undef PAGE_SIZE // defined in system headers somewhere +#define PAGE_SIZE (1 << PAGE_BITS) +#define PAGE(addr) ((addr) >> PAGE_BITS) +#define PGOFFSET(addr) ((addr) & (PAGE_SIZE - 1)) +// bytes MUST be unsigned if you would like this to overflow to zero +#define PAGE_ROUND_UP(bytes) (PAGE((bytes) + PAGE_SIZE - 1)) +#endif + +struct mmu { + struct mmu_ops *ops; + struct asbestos *asbestos; + uint64_t changes; +}; + +#define MEM_READ 0 +#define MEM_WRITE 1 +#define MEM_WRITE_PTRACE 2 + +struct mmu_ops { + // type is MEM_READ or MEM_WRITE + void *(*translate)(struct mmu *mmu, addr_t addr, int type); + // Like translate(MEM_WRITE) but returns NULL instead of triggering CoW/GROWSDOWN. + // Used by TLB to speculatively populate write permission on read miss. + void *(*translate_write_nofault)(struct mmu *mmu, addr_t addr); +}; + +static inline void *mmu_translate(struct mmu *mmu, addr_t addr, int type) { + return mmu->ops->translate(mmu, addr, type); +} + +#endif \ No newline at end of file diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/tlb.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/tlb.c new file mode 100644 index 0000000000..ac80ba1a36 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/tlb.c @@ -0,0 +1,741 @@ +#include "emu/cpu.h" +#include "emu/tlb.h" +#include "kernel/task.h" +#include "kernel/memory.h" +#include "kernel/fs.h" +#include "util/sync.h" +#include "asbestos/frame.h" + +void tlb_refresh(struct tlb *tlb, struct mmu *mmu) { + if (tlb->mmu == mmu && tlb->mem_changes == mmu->changes) + return; + + bool mmu_changed = (tlb->mmu != mmu); + bool mappings_changed = (tlb->mmu == mmu && tlb->mem_changes != mmu->changes); + + if (mmu_changed || mappings_changed) { + // The persistent threaded-code caches contain host pointers into guest-code + // fiber blocks. They must be dropped whenever mappings change, not just + // when the mmu pointer itself changes, because execve/remap paths can keep + // the same mmu object while replacing the underlying mappings. + memset(tlb->block_cache, 0, sizeof(tlb->block_cache)); + tlb->block_cache_gen = 0; + + if (tlb->frame != NULL) { + if (mmu_changed) { + free(tlb->frame); + tlb->frame = NULL; + } else { + memset(tlb->frame->ret_cache, 0, sizeof(tlb->frame->ret_cache)); + tlb->frame->last_block = NULL; + } + } + } + + tlb->mmu = mmu; + tlb->dirty_page = TLB_PAGE_EMPTY; + tlb->mem_changes = mmu->changes; + tlb_flush(tlb); +} + +void tlb_flush(struct tlb *tlb) { + tlb->mem_changes = tlb->mmu->changes; + for (unsigned i = 0; i < TLB_SIZE; i++) + tlb->entries[i] = (struct tlb_entry) {.page = 1, .page_if_writable = 1}; +} + +void tlb_free(struct tlb *tlb) { + if (tlb->frame != NULL) + free(tlb->frame); + free(tlb); +} + +bool __tlb_read_cross_page(struct tlb *tlb, addr_t addr, char *value, unsigned size) { + char *ptr1 = __tlb_read_ptr(tlb, addr); + if (ptr1 == NULL) + return false; + char *ptr2 = __tlb_read_ptr(tlb, (PAGE(addr) + 1) << PAGE_BITS); + if (ptr2 == NULL) + return false; + size_t part1 = PAGE_SIZE - PGOFFSET(addr); + assert(part1 < size); + memcpy(value, ptr1, part1); + memcpy(value + part1, ptr2, size - part1); + return true; +} + +bool __tlb_write_cross_page(struct tlb *tlb, addr_t addr, const char *value, unsigned size) { + char *ptr1 = __tlb_write_ptr(tlb, addr); + if (ptr1 == NULL) + return false; + char *ptr2 = __tlb_write_ptr(tlb, (PAGE(addr) + 1) << PAGE_BITS); + if (ptr2 == NULL) + return false; + size_t part1 = PAGE_SIZE - PGOFFSET(addr); + assert(part1 < size); + memcpy(ptr1, value, part1); + memcpy(ptr2, value + part1, size - part1); + return true; +} + +bool __tlb_zero(struct tlb *tlb, addr_t addr, unsigned size) { + char *ptr1 = __tlb_write_ptr(tlb, addr); + if (ptr1 == NULL) + return false; + + size_t part1 = PAGE_SIZE - PGOFFSET(addr); + if (part1 >= size) { + memset(ptr1, 0, size); + return true; + } + + char *ptr2 = __tlb_write_ptr(tlb, (PAGE(addr) + 1) << PAGE_BITS); + if (ptr2 == NULL) + return false; + memset(ptr1, 0, part1); + memset(ptr2, 0, size - part1); + return true; +} + +__no_instrument void *tlb_handle_miss(struct tlb *tlb, addr_t addr, int type) { + // Seqlock-style translate: snapshot mmu->changes BEFORE translating, then + // verify it did not advance across the translation. If it did, another + // thread remapped a page concurrently and `ptr` may reference the stale + // host backing (a partial munmap / CoW leaves the old page readable via + // its lingering refcount, so the stale ptr silently reads wrong data). + // Loop until we get a ptr and a generation that are mutually consistent, + // so the gen we stamp on the entry truly matches the backing it points at. + uint64_t gen; + char *ptr; + // A write miss on a CoW page performs the copy inside mmu_translate, which + // itself bumps mmu->changes; the retry then sees a stable generation once + // the page is resolved. Bound the loop so a thread continuously remapping + // can't livelock us — after the cap we accept the latest consistent-enough + // translation (the per-block coherence check will still catch a later + // change). + for (int attempt = 0; ; attempt++) { + gen = __atomic_load_n(&tlb->mmu->changes, __ATOMIC_ACQUIRE); + if (gen != tlb->mem_changes) + tlb_flush(tlb); + tlb->mem_changes = gen; + ptr = mmu_translate(tlb->mmu, TLB_PAGE(addr), type); + // Re-read after translate; if unchanged, ptr is consistent with `gen`. + if (__atomic_load_n(&tlb->mmu->changes, __ATOMIC_ACQUIRE) == gen) + break; + if (attempt >= 8) { + // Refresh gen to the post-translate value so the entry we stamp is + // at least self-consistent with this last translation. + gen = __atomic_load_n(&tlb->mmu->changes, __ATOMIC_ACQUIRE); + tlb->mem_changes = gen; + break; + } + // Raced with a concurrent remap — retry with the fresh generation. + } + if (ptr == NULL) { + tlb->segfault_addr = addr; + return NULL; + } + + tlb->dirty_page = TLB_PAGE(addr); + + struct tlb_entry *tlb_ent = &tlb->entries[TLB_INDEX(addr)]; + tlb_ent->page = TLB_PAGE(addr); + tlb_ent->data_minus_addr = (uintptr_t) ptr - TLB_PAGE(addr); +#ifdef GUEST_ARM64 + // Record the coherence generation this host pointer is valid for. A hit on + // this entry is only trustworthy while mmu->changes still equals this; if + // another thread remapped the page (CoW/mmap/munmap) mmu->changes advances + // and the cached data_minus_addr points at the stale host backing. + tlb_ent->gen = (uintptr_t) gen; +#endif + + if (type == MEM_WRITE) { + tlb_ent->page_if_writable = TLB_PAGE(addr); + } else { + // On read miss, speculatively check if the page is also writable. + if (tlb->mmu->ops->translate_write_nofault) { + char *wptr = tlb->mmu->ops->translate_write_nofault(tlb->mmu, TLB_PAGE(addr)); + tlb_ent->page_if_writable = wptr ? TLB_PAGE(addr) : TLB_PAGE_EMPTY; + } else { + tlb_ent->page_if_writable = TLB_PAGE_EMPTY; + } + } + + return (void *) (tlb_ent->data_minus_addr + addr); +} + +#if defined(GUEST_ARM64) +/* + * C-based memory access functions for ARM64 guest gadgets. + * These provide reliable memory access by using the proven C-based TLB code. + * + * Return value convention for loads: + * - Returns the loaded value through the 'out' pointer + * - Returns 0 on success, -1 on segfault (tlb->segfault_addr is set) + * + * Return value convention for stores: + * - Returns 0 on success, -1 on segfault (tlb->segfault_addr is set) + */ + + + +// Load functions - return 0 on success, -1 on segfault +__no_instrument int c_load64(struct tlb *tlb, addr_t addr, uint64_t *out) { + // Handle unaligned access by reading byte-by-byte + if ((addr & 7) != 0) { + // Unaligned - read each byte separately (little-endian) + uint64_t result = 0; + for (int i = 0; i < 8; i++) { + void *ptr = __tlb_read_ptr(tlb, addr + i); + if (ptr == NULL) { + return -1; + } + result |= ((uint64_t)*(uint8_t *)ptr) << (i * 8); + } + *out = result; + return 0; + } + + void *ptr = __tlb_read_ptr(tlb, addr); + if (ptr == NULL) { + return -1; // segfault_addr already set by tlb_handle_miss + } + *out = *(uint64_t *)ptr; + return 0; +} + +__no_instrument int c_load32(struct tlb *tlb, addr_t addr, uint32_t *out) { + void *ptr = __tlb_read_ptr(tlb, addr); + if (ptr == NULL) { + return -1; + } + *out = *(uint32_t *)ptr; + return 0; +} + +__no_instrument int c_load16(struct tlb *tlb, addr_t addr, uint16_t *out) { + void *ptr = __tlb_read_ptr(tlb, addr); + if (ptr == NULL) { + return -1; + } + *out = *(uint16_t *)ptr; + return 0; +} + +__no_instrument int c_load8(struct tlb *tlb, addr_t addr, uint8_t *out) { + void *ptr = __tlb_read_ptr(tlb, addr); + if (ptr == NULL) { + return -1; + } + *out = *(uint8_t *)ptr; + return 0; +} + +// Sign-extending load functions +__no_instrument int c_load32_sx(struct tlb *tlb, addr_t addr, int64_t *out) { + void *ptr = __tlb_read_ptr(tlb, addr); + if (ptr == NULL) { + return -1; + } + *out = (int64_t)(int32_t)*(uint32_t *)ptr; + return 0; +} + +__no_instrument int c_load16_sx64(struct tlb *tlb, addr_t addr, int64_t *out) { + void *ptr = __tlb_read_ptr(tlb, addr); + if (ptr == NULL) { + return -1; + } + *out = (int64_t)(int16_t)*(uint16_t *)ptr; + return 0; +} + +__no_instrument int c_load16_sx32(struct tlb *tlb, addr_t addr, int32_t *out) { + void *ptr = __tlb_read_ptr(tlb, addr); + if (ptr == NULL) { + return -1; + } + *out = (int32_t)(int16_t)*(uint16_t *)ptr; + return 0; +} + +__no_instrument int c_load8_sx64(struct tlb *tlb, addr_t addr, int64_t *out) { + void *ptr = __tlb_read_ptr(tlb, addr); + if (ptr == NULL) { + return -1; + } + *out = (int64_t)(int8_t)*(uint8_t *)ptr; + return 0; +} + +__no_instrument int c_load8_sx32(struct tlb *tlb, addr_t addr, int32_t *out) { + void *ptr = __tlb_read_ptr(tlb, addr); + if (ptr == NULL) { + return -1; + } + *out = (int32_t)(int8_t)*(uint8_t *)ptr; + return 0; +} + +// Store functions - return 0 on success, -1 on segfault +__no_instrument int c_store64(struct tlb *tlb, addr_t addr, uint64_t value) { + // Handle unaligned access by writing byte-by-byte + if ((addr & 7) != 0) { + // Unaligned - write each byte separately (little-endian) + for (int i = 0; i < 8; i++) { + void *ptr = __tlb_write_ptr(tlb, addr + i); + if (ptr == NULL) { + return -1; + } + *(uint8_t *)ptr = (value >> (i * 8)) & 0xFF; + } + return 0; + } + + void *ptr = __tlb_write_ptr(tlb, addr); + if (ptr == NULL) { + return -1; // segfault_addr already set + } + *(uint64_t *)ptr = value; + return 0; +} + +__no_instrument int c_store32(struct tlb *tlb, addr_t addr, uint32_t value) { + void *ptr = __tlb_write_ptr(tlb, addr); + if (ptr == NULL) { + return -1; + } + *(uint32_t *)ptr = value; + return 0; +} + +__no_instrument int c_store16(struct tlb *tlb, addr_t addr, uint16_t value) { + void *ptr = __tlb_write_ptr(tlb, addr); + if (ptr == NULL) { + return -1; + } + *(uint16_t *)ptr = value; + return 0; +} + +__no_instrument int c_store8(struct tlb *tlb, addr_t addr, uint8_t value) { + void *ptr = __tlb_write_ptr(tlb, addr); + if (ptr == NULL) { + return -1; + } + *(uint8_t *)ptr = value; + return 0; +} + +// IC IVAU: the guest modified code at `addr` and is invalidating its icache. +// Drop any translated blocks for that page so the new code gets retranslated. +// Without this, a store through an already-writable TLB entry (which never +// takes the mem_ptr write-miss path that calls asbestos_invalidate_page) +// leaves stale translations running — JSC's in-place JIT repatching breaks. +__no_instrument void c_ic_ivau(struct tlb *tlb, addr_t addr) { + extern void asbestos_invalidate_page(struct asbestos *asbestos, page_t page); + asbestos_invalidate_page(tlb->mmu->asbestos, PAGE(addr)); +} + +// Atomic memory operations (LSE): LDADD/LDCLR/LDEOR/LDSET/LDSMAX/LDSMIN/LDUMAX/LDUMIN/SWP +// Return: 0 on success, -1 on segfault or unsupported op +// Helper macros for atomic RMW with CAS loop (for min/max that lack atomic builtins) +#define ATOMIC_RMW_CAS_LOOP(type, ptr, val, op_expr) do { \ + type old = __atomic_load_n((type *)(ptr), __ATOMIC_SEQ_CST); \ + type newv; \ + do { \ + newv = (op_expr); \ + } while (!__atomic_compare_exchange_n((type *)(ptr), &old, newv, \ + true, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)); \ + *old_out = old; \ +} while(0) + +__no_instrument int c_atomic_rmw(struct tlb *tlb, addr_t addr, uint64_t value, + uint32_t size, uint32_t op, uint64_t *old_out) { + if (old_out == NULL) + return -1; + + void *ptr = __tlb_write_ptr(tlb, addr); + if (ptr == NULL) + return -1; + + switch (size) { + case 0: { // 8-bit + uint8_t val = (uint8_t)value; + switch (op) { + case 0: *old_out = __atomic_fetch_add((uint8_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + case 1: *old_out = __atomic_fetch_and((uint8_t *)ptr, ~val, __ATOMIC_SEQ_CST); return 0; + case 2: *old_out = __atomic_fetch_xor((uint8_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + case 3: *old_out = __atomic_fetch_or((uint8_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + case 4: ATOMIC_RMW_CAS_LOOP(uint8_t, ptr, val, ((int8_t)old > (int8_t)val) ? old : val); return 0; + case 5: ATOMIC_RMW_CAS_LOOP(uint8_t, ptr, val, ((int8_t)old < (int8_t)val) ? old : val); return 0; + case 6: ATOMIC_RMW_CAS_LOOP(uint8_t, ptr, val, (old > val) ? old : val); return 0; + case 7: ATOMIC_RMW_CAS_LOOP(uint8_t, ptr, val, (old < val) ? old : val); return 0; + case 8: *old_out = __atomic_exchange_n((uint8_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + default: return -1; + } + } + case 1: { // 16-bit + uint16_t val = (uint16_t)value; + switch (op) { + case 0: *old_out = __atomic_fetch_add((uint16_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + case 1: *old_out = __atomic_fetch_and((uint16_t *)ptr, ~val, __ATOMIC_SEQ_CST); return 0; + case 2: *old_out = __atomic_fetch_xor((uint16_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + case 3: *old_out = __atomic_fetch_or((uint16_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + case 4: ATOMIC_RMW_CAS_LOOP(uint16_t, ptr, val, ((int16_t)old > (int16_t)val) ? old : val); return 0; + case 5: ATOMIC_RMW_CAS_LOOP(uint16_t, ptr, val, ((int16_t)old < (int16_t)val) ? old : val); return 0; + case 6: ATOMIC_RMW_CAS_LOOP(uint16_t, ptr, val, (old > val) ? old : val); return 0; + case 7: ATOMIC_RMW_CAS_LOOP(uint16_t, ptr, val, (old < val) ? old : val); return 0; + case 8: *old_out = __atomic_exchange_n((uint16_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + default: return -1; + } + } + case 2: { // 32-bit + uint32_t val = (uint32_t)value; + switch (op) { + case 0: *old_out = __atomic_fetch_add((uint32_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + case 1: *old_out = __atomic_fetch_and((uint32_t *)ptr, ~val, __ATOMIC_SEQ_CST); return 0; + case 2: *old_out = __atomic_fetch_xor((uint32_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + case 3: *old_out = __atomic_fetch_or((uint32_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + case 4: ATOMIC_RMW_CAS_LOOP(uint32_t, ptr, val, ((int32_t)old > (int32_t)val) ? old : val); return 0; + case 5: ATOMIC_RMW_CAS_LOOP(uint32_t, ptr, val, ((int32_t)old < (int32_t)val) ? old : val); return 0; + case 6: ATOMIC_RMW_CAS_LOOP(uint32_t, ptr, val, (old > val) ? old : val); return 0; + case 7: ATOMIC_RMW_CAS_LOOP(uint32_t, ptr, val, (old < val) ? old : val); return 0; + case 8: *old_out = __atomic_exchange_n((uint32_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + default: return -1; + } + } + case 3: { // 64-bit + uint64_t val = value; + switch (op) { + case 0: *old_out = __atomic_fetch_add((uint64_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + case 1: *old_out = __atomic_fetch_and((uint64_t *)ptr, ~val, __ATOMIC_SEQ_CST); return 0; + case 2: *old_out = __atomic_fetch_xor((uint64_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + case 3: *old_out = __atomic_fetch_or((uint64_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + case 4: ATOMIC_RMW_CAS_LOOP(uint64_t, ptr, val, ((int64_t)old > (int64_t)val) ? old : val); return 0; + case 5: ATOMIC_RMW_CAS_LOOP(uint64_t, ptr, val, ((int64_t)old < (int64_t)val) ? old : val); return 0; + case 6: ATOMIC_RMW_CAS_LOOP(uint64_t, ptr, val, (old > val) ? old : val); return 0; + case 7: ATOMIC_RMW_CAS_LOOP(uint64_t, ptr, val, (old < val) ? old : val); return 0; + case 8: *old_out = __atomic_exchange_n((uint64_t *)ptr, val, __ATOMIC_SEQ_CST); return 0; + default: return -1; + } + } + default: + return -1; + } +} + +#undef ATOMIC_RMW_CAS_LOOP + +// Atomic compare-and-swap (CAS/CASA/CASL/CASAL) +// Uses host atomic CAS for thread safety. +// Return: 0 on success, -1 on segfault or unsupported size +__no_instrument int c_atomic_cas(struct tlb *tlb, addr_t addr, uint64_t expected, + uint64_t desired, uint32_t size, uint64_t *old_out) { + if (old_out == NULL) + return -1; + + // Get writable host pointer (CAS needs both read and write) + void *ptr = __tlb_write_ptr(tlb, addr); + if (ptr == NULL) + return -1; + + switch (size) { + case 0: { // 8-bit + uint8_t exp = (uint8_t)expected; + __atomic_compare_exchange_n((uint8_t *)ptr, &exp, (uint8_t)desired, + false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); + *old_out = exp; // exp is updated to actual value on failure + return 0; + } + case 1: { // 16-bit + uint16_t exp = (uint16_t)expected; + __atomic_compare_exchange_n((uint16_t *)ptr, &exp, (uint16_t)desired, + false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); + *old_out = exp; + return 0; + } + case 2: { // 32-bit + uint32_t exp = (uint32_t)expected; + __atomic_compare_exchange_n((uint32_t *)ptr, &exp, (uint32_t)desired, + false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); + *old_out = exp; + return 0; + } + case 3: { // 64-bit + uint64_t exp = expected; + __atomic_compare_exchange_n((uint64_t *)ptr, &exp, desired, + false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); + *old_out = exp; + return 0; + } + default: + return -1; + } +} + +// STXR atomic compare-and-swap helper for LDXR/STXR emulation. +// Compares memory at addr with expected_val, if equal stores new_val. +// Returns 0 on success (CAS succeeded), 1 on failure (CAS lost race), +// or -1 on segfault. +// +// To prevent CoW from invalidating the host pointer between getting it +// and the CAS, we snapshot mmu->changes before and after. If it changed, +// another thread did CoW/mmap, so we retry with a fresh TLB lookup. +__no_instrument int c_stxr_cas(struct tlb *tlb, addr_t addr, + uint64_t expected_val, uint64_t new_val, + uint32_t size) { + void *ptr = __tlb_write_ptr(tlb, addr); + if (ptr == NULL) + return -1; + + switch (size) { + case 0: { // 8-bit + uint8_t exp = (uint8_t)expected_val; + uint8_t des = (uint8_t)new_val; + return __atomic_compare_exchange_n((uint8_t *)ptr, &exp, des, + false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) ? 0 : 1; + } + case 1: { // 16-bit + uint16_t exp = (uint16_t)expected_val; + uint16_t des = (uint16_t)new_val; + return __atomic_compare_exchange_n((uint16_t *)ptr, &exp, des, + false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) ? 0 : 1; + } + case 2: { // 32-bit + uint32_t exp = (uint32_t)expected_val; + uint32_t des = (uint32_t)new_val; + return __atomic_compare_exchange_n((uint32_t *)ptr, &exp, des, + false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) ? 0 : 1; + } + case 3: { // 64-bit + uint64_t exp = expected_val; + uint64_t des = new_val; + return __atomic_compare_exchange_n((uint64_t *)ptr, &exp, des, + false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) ? 0 : 1; + } + default: + return -1; + } +} + +// LDP/STP helper functions for pair loads/stores +// Return: 0 on success, -1 on segfault +static lock_t pair_atomic_lock = LOCK_INITIALIZER; + +__no_instrument int c_ldp64(struct tlb *tlb, addr_t addr, uint64_t *val1, uint64_t *val2) { + void *ptr1 = __tlb_read_ptr(tlb, addr); + if (ptr1 == NULL) { + return -1; + } + void *ptr2 = __tlb_read_ptr(tlb, addr + 8); + if (ptr2 == NULL) { + return -1; + } + *val1 = *(uint64_t *)ptr1; + *val2 = *(uint64_t *)ptr2; + (void)0; + return 0; +} + +__no_instrument int c_ldp32(struct tlb *tlb, addr_t addr, uint32_t *val1, uint32_t *val2) { + void *ptr1 = __tlb_read_ptr(tlb, addr); + if (ptr1 == NULL) { + return -1; + } + void *ptr2 = __tlb_read_ptr(tlb, addr + 4); + if (ptr2 == NULL) { + return -1; + } + *val1 = *(uint32_t *)ptr1; + *val2 = *(uint32_t *)ptr2; + return 0; +} + +__no_instrument int c_stp64(struct tlb *tlb, addr_t addr, uint64_t val1, uint64_t val2) { + void *ptr1 = __tlb_write_ptr(tlb, addr); + if (ptr1 == NULL) { + return -1; + } + void *ptr2 = __tlb_write_ptr(tlb, addr + 8); + if (ptr2 == NULL) { + return -1; + } + *(uint64_t *)ptr1 = val1; + *(uint64_t *)ptr2 = val2; + return 0; +} + +__no_instrument int c_stp32(struct tlb *tlb, addr_t addr, uint32_t val1, uint32_t val2) { + void *ptr1 = __tlb_write_ptr(tlb, addr); + if (ptr1 == NULL) { + return -1; + } + void *ptr2 = __tlb_write_ptr(tlb, addr + 4); + if (ptr2 == NULL) { + return -1; + } + *(uint32_t *)ptr1 = val1; + *(uint32_t *)ptr2 = val2; + return 0; +} + +// STXP/STLXP pair compare-and-store helper. +// Returns 0 on success, 1 on exclusive-store failure, -1 on fault. +__no_instrument int c_stxp_pair(struct tlb *tlb, addr_t addr, + uint64_t expected_lo, uint64_t expected_hi, + uint64_t new_lo, uint64_t new_hi, + uint32_t size) { + void *ptr = __tlb_write_ptr(tlb, addr); + if (ptr == NULL) + return -1; + + if (size == 2) { + if (addr & 7) + return -1; + uint64_t expected = (uint32_t)expected_lo | + ((uint64_t)(uint32_t)expected_hi << 32); + uint64_t desired = (uint32_t)new_lo | + ((uint64_t)(uint32_t)new_hi << 32); + return __atomic_compare_exchange_n((uint64_t *)ptr, &expected, desired, + false, __ATOMIC_SEQ_CST, + __ATOMIC_SEQ_CST) ? 0 : 1; + } + + if (size == 3) { + if ((addr & 0xf) || PGOFFSET(addr) + 16 > PAGE_SIZE) + return -1; + __uint128_t expected = ((__uint128_t)expected_hi << 64) | expected_lo; + __uint128_t desired = ((__uint128_t)new_hi << 64) | new_lo; + return __atomic_compare_exchange_n((__uint128_t *)ptr, &expected, desired, + false, __ATOMIC_SEQ_CST, + __ATOMIC_SEQ_CST) ? 0 : 1; + } + + return -1; +} + +// CASP/CASPA/CASPL/CASPAL helper. *old_lo/*old_hi enter with the expected +// pair and are replaced with the actual memory pair, matching AArch64 CASP +// writeback semantics. Returns 0 on a valid access, -1 on segfault. +__no_instrument int c_casp_pair(struct tlb *tlb, addr_t addr, + uint64_t *old_lo, uint64_t *old_hi, + uint64_t new_lo, uint64_t new_hi, + uint32_t size) { + if (size == 3 && (addr & 0xf)) + return -1; + + int result = -1; + + lock(&pair_atomic_lock); + if (size == 2) { + void *ptr1 = __tlb_write_ptr(tlb, addr); + void *ptr2 = __tlb_write_ptr(tlb, addr + 4); + if (ptr1 != NULL && ptr2 != NULL) { + uint32_t expected_lo = (uint32_t)*old_lo; + uint32_t expected_hi = (uint32_t)*old_hi; + uint32_t cur_lo = *(uint32_t *)ptr1; + uint32_t cur_hi = *(uint32_t *)ptr2; + if (cur_lo == expected_lo && cur_hi == expected_hi) { + *(uint32_t *)ptr1 = (uint32_t)new_lo; + *(uint32_t *)ptr2 = (uint32_t)new_hi; + } + *old_lo = cur_lo; + *old_hi = cur_hi; + result = 0; + } + } else if (size == 3) { + void *ptr1 = __tlb_write_ptr(tlb, addr); + void *ptr2 = __tlb_write_ptr(tlb, addr + 8); + if (ptr1 != NULL && ptr2 != NULL) { + uint64_t expected_lo = *old_lo; + uint64_t expected_hi = *old_hi; + uint64_t cur_lo = *(uint64_t *)ptr1; + uint64_t cur_hi = *(uint64_t *)ptr2; + if (cur_lo == expected_lo && cur_hi == expected_hi) { + *(uint64_t *)ptr1 = new_lo; + *(uint64_t *)ptr2 = new_hi; + } + *old_lo = cur_lo; + *old_hi = cur_hi; + result = 0; + } + } + unlock(&pair_atomic_lock); + + return result; +} + +// Interleaved SIMD load (LD2/LD3/LD4) +// Reads interleaved elements from memory and deinterleaves into consecutive Vt registers. +// num_regs: 2 (LD2), 3 (LD3), or 4 (LD4) +// elem_size: 0=byte, 1=halfword, 2=word, 3=doubleword +// Q: 0=64-bit (lower half), 1=128-bit (full register) +// rt: first destination register (Vt, Vt+1, ..., Vt+num_regs-1 mod 32) +__no_instrument int c_simd_load_interleaved(struct cpu_state *cpu, struct tlb *tlb, + addr_t addr, uint32_t rt, uint32_t num_regs, + uint32_t elem_size, uint32_t Q) { + unsigned elem_bytes = 1u << elem_size; + unsigned elems_per_reg = (Q ? 16 : 8) / elem_bytes; + unsigned total_bytes = num_regs * elems_per_reg * elem_bytes; + if (total_bytes > 64 || num_regs > 4 || elem_size > 3) return -1; + + // Read all raw bytes from guest memory (bulk read via host pointer) + uint8_t buf[64]; + if (PGOFFSET(addr) + total_bytes <= PAGE_SIZE) { + // Fast path: entire access fits within one page + char *ptr = __tlb_read_ptr(tlb, addr); + if (ptr == NULL) return -1; + memcpy(buf, ptr, total_bytes); + } else { + // Slow path: crosses page boundary + if (!__tlb_read_cross_page(tlb, addr, (char *)buf, total_bytes)) + return -1; + } + + // Deinterleave: memory has [elem0_reg0, elem0_reg1, ..., elem0_regN-1, elem1_reg0, ...] + for (unsigned r = 0; r < num_regs; r++) { + uint32_t vt = (rt + r) & 0x1f; + cpu->fp[vt].q = 0; + for (unsigned e = 0; e < elems_per_reg; e++) { + unsigned src_offset = (e * num_regs + r) * elem_bytes; + unsigned dst_offset = e * elem_bytes; + memcpy(&cpu->fp[vt].b[dst_offset], &buf[src_offset], elem_bytes); + } + } + return 0; +} + +// Interleaved SIMD store (ST2/ST3/ST4) +// Reads consecutive Vt registers and writes interleaved elements to memory. +__no_instrument int c_simd_store_interleaved(struct cpu_state *cpu, struct tlb *tlb, + addr_t addr, uint32_t rt, uint32_t num_regs, + uint32_t elem_size, uint32_t Q) { + unsigned elem_bytes = 1u << elem_size; + unsigned elems_per_reg = (Q ? 16 : 8) / elem_bytes; + unsigned total_bytes = num_regs * elems_per_reg * elem_bytes; + if (total_bytes > 64 || num_regs > 4 || elem_size > 3) return -1; + + // Interleave register data into buffer + uint8_t buf[64]; + for (unsigned r = 0; r < num_regs; r++) { + uint32_t vt = (rt + r) & 0x1f; + for (unsigned e = 0; e < elems_per_reg; e++) { + unsigned dst_offset = (e * num_regs + r) * elem_bytes; + unsigned src_offset = e * elem_bytes; + memcpy(&buf[dst_offset], &cpu->fp[vt].b[src_offset], elem_bytes); + } + } + + // Write all bytes to guest memory (bulk write via host pointer) + if (PGOFFSET(addr) + total_bytes <= PAGE_SIZE) { + char *ptr = __tlb_write_ptr(tlb, addr); + if (ptr == NULL) return -1; + memcpy(ptr, buf, total_bytes); + } else { + if (!__tlb_write_cross_page(tlb, addr, (char *)buf, total_bytes)) + return -1; + } + return 0; +} +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/tlb.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/tlb.h new file mode 100644 index 0000000000..02f660721d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/emu/tlb.h @@ -0,0 +1,117 @@ +#ifndef TLB_H +#define TLB_H + +#include <string.h> +#include "emu/mmu.h" +#include "debug.h" + +struct tlb_entry { + page_t page; + page_t page_if_writable; + uintptr_t data_minus_addr; +#ifdef GUEST_ARM64 + // Coherence generation: snapshot of mmu->changes when this entry was + // populated. Used to detect a stale entry whose page was remapped + // (CoW/mmap/munmap) by another thread while this thread was mid-block. + // Occupies the former 32-byte padding slot (JIT indexes entries by lsl #5). + uintptr_t gen; +#endif +}; +#define TLB_BITS 13 // 8192 entries +#define TLB_SIZE (1 << TLB_BITS) +struct fiber_block; +struct fiber_frame; + +struct tlb { + struct mmu *mmu; + page_t dirty_page; + unsigned mem_changes; + // this is basically one of the return values of tlb_handle_miss, tlb_{read,write}, and __tlb_{read,write}_cross_page + // yes, this sucks + addr_t segfault_addr; + + struct tlb_entry entries[TLB_SIZE]; + + // Persistent block cache across syscalls (avoids re-lookup after every interrupt) + // Size defined by FIBER_CACHE_SIZE in asbestos.h + struct fiber_block *block_cache[1 << 12]; // must match FIBER_CACHE_SIZE + unsigned block_cache_gen; // tracks asbestos->invalidate_gen for invalidation + + // Persistent fiber_frame (avoids malloc/free + ret_cache zeroing per syscall) + struct fiber_frame *frame; +}; + +#define TLB_INDEX(addr) ((((addr >> PAGE_BITS) ^ (addr >> (PAGE_BITS + TLB_BITS))) & (TLB_SIZE - 1))) +#ifdef GUEST_ARM64 +#define TLB_PAGE(addr) ((addr) & 0xfffffffffffff000ULL) +#else +#define TLB_PAGE(addr) ((addr) & 0xfffff000) +#endif +#define TLB_PAGE_EMPTY 1 +void tlb_refresh(struct tlb *tlb, struct mmu *mmu); +void tlb_free(struct tlb *tlb); +void tlb_flush(struct tlb *tlb); +void *tlb_handle_miss(struct tlb *tlb, addr_t addr, int type); + +forceinline __no_instrument void *__tlb_read_ptr(struct tlb *tlb, addr_t addr) { + struct tlb_entry entry = tlb->entries[TLB_INDEX(addr)]; + if (entry.page == TLB_PAGE(addr) +#ifdef GUEST_ARM64 + // Coherence: reject a hit whose page was remapped by another thread + // since this entry was cached (CoW/mmap advanced mmu->changes). Falling + // through to tlb_handle_miss re-translates to the current backing. + && entry.gen == (uintptr_t) __atomic_load_n(&tlb->mmu->changes, __ATOMIC_ACQUIRE) +#endif + ) { + void *address = (void *) (entry.data_minus_addr + addr); + return address; + } + return tlb_handle_miss(tlb, addr, MEM_READ); +} +bool __tlb_read_cross_page(struct tlb *tlb, addr_t addr, char *out, unsigned size); +forceinline __no_instrument bool tlb_read(struct tlb *tlb, addr_t addr, void *out, unsigned size) { + if (PGOFFSET(addr) > PAGE_SIZE - size) + return __tlb_read_cross_page(tlb, addr, out, size); + void *ptr = __tlb_read_ptr(tlb, addr); + if (ptr == NULL) + return false; + memcpy(out, ptr, size); + return true; +} + +// C-level write watchpoint: detect stores that bypass assembly write_prep +#define ENABLE_C_WRITE_WATCHPOINT 1 +extern volatile addr_t g_watch_page_val; +void c_watch_write_hit(addr_t addr, const char *caller); + +forceinline __no_instrument void *__tlb_write_ptr(struct tlb *tlb, addr_t addr) { +#ifdef ENABLE_C_WRITE_WATCHPOINT + if (g_watch_page_val && (addr & ~0xfffULL) == g_watch_page_val) { + c_watch_write_hit(addr, __func__); + } +#endif + struct tlb_entry entry = tlb->entries[TLB_INDEX(addr)]; + if (entry.page_if_writable == TLB_PAGE(addr) +#ifdef GUEST_ARM64 + && entry.gen == (uintptr_t) __atomic_load_n(&tlb->mmu->changes, __ATOMIC_ACQUIRE) +#endif + ) { + tlb->dirty_page = TLB_PAGE(addr); + void *address = (void *) (entry.data_minus_addr + addr); + return address; + } + return tlb_handle_miss(tlb, addr, MEM_WRITE); +} +bool __tlb_write_cross_page(struct tlb *tlb, addr_t addr, const char *value, unsigned size); +bool __tlb_zero(struct tlb *tlb, addr_t addr, unsigned size); +forceinline __no_instrument bool tlb_write(struct tlb *tlb, addr_t addr, const void *value, unsigned size) { + if (PGOFFSET(addr) > PAGE_SIZE - size) + return __tlb_write_cross_page(tlb, addr, value, size); + void *ptr = __tlb_write_ptr(tlb, addr); + if (ptr == NULL) + return false; + memcpy(ptr, value, size); + return true; +} + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/adhoc.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/adhoc.c new file mode 100644 index 0000000000..a56a3bc15d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/adhoc.c @@ -0,0 +1,65 @@ +#include <string.h> +#include <sys/stat.h> +#include "debug.h" +#include "kernel/fs.h" +#include "fs/fd.h" +#include "kernel/errno.h" + +static struct mount adhoc_mount; + +struct fd *adhoc_fd_create(const struct fd_ops *ops) { + struct fd *fd = fd_create(ops); + if (fd == NULL) + return NULL; + mount_retain(&adhoc_mount); + fd->mount = &adhoc_mount; + fd->stat = (struct statbuf) {}; + return fd; +} + +static int adhoc_fstat(struct fd *fd, struct statbuf *stat) { + *stat = fd->stat; + return 0; +} + +static int adhoc_fsetattr(struct fd *fd, struct attr attr) { + switch (attr.type) { + case attr_uid: + fd->stat.uid = attr.uid; + break; + case attr_gid: + fd->stat.gid = attr.gid; + break; + case attr_mode: + fd->stat.mode = (fd->stat.mode & S_IFMT) | (attr.mode & ~S_IFMT); + break; + case attr_size: + return _EINVAL; + } + return 0; +} + +static int adhoc_getpath(struct fd *fd, char *buf) { + const char *type = "unknown"; // TODO allow this to be customized + if (fd->stat.inode == 0) + sprintf(buf, "anon_inode:[%s]", type); + else + sprintf(buf, "%s:[%lu]", type, (unsigned long) fd->stat.inode); + return 0; +} + +bool is_adhoc_fd(struct fd *fd) { + return fd->mount == &adhoc_mount; +} + +static const struct fs_ops adhoc_fs = { + .magic = 0x09041934, // FIXME wrong for pipes and sockets + .fstat = adhoc_fstat, + .fsetattr = adhoc_fsetattr, + .getpath = adhoc_getpath, +}; + +static struct mount adhoc_mount = { + .fs = &adhoc_fs, + .point = "", +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dev.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dev.c new file mode 100644 index 0000000000..f24e690770 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dev.c @@ -0,0 +1,29 @@ +#include "kernel/errno.h" +#include "fs/fd.h" +#include "fs/dev.h" +#include "fs/mem.h" +#include "fs/tty.h" +#include "fs/dyndev.h" +#include "fs/devices.h" + +struct dev_ops *block_devs[256] = { + // no block devices yet +}; +struct dev_ops *char_devs[256] = { + [MEM_MAJOR] = &mem_dev, + [TTY_CONSOLE_MAJOR] = &tty_dev, + [TTY_ALTERNATE_MAJOR] = &tty_dev, + [TTY_PSEUDO_MASTER_MAJOR] = &tty_dev, + [TTY_PSEUDO_SLAVE_MAJOR] = &tty_dev, + [DYN_DEV_MAJOR] = &dyn_dev_char, +}; + +int dev_open(int major, int minor, int type, struct fd *fd) { + struct dev_ops *dev = (type == DEV_BLOCK ? block_devs : char_devs)[major]; + if (dev == NULL) + return _ENXIO; + fd->ops = &dev->fd; + if (!dev->open) + return 0; + return dev->open(major, minor, fd); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dev.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dev.h new file mode 100644 index 0000000000..79246f43ea --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dev.h @@ -0,0 +1,48 @@ +#ifndef DEV_H +#define DEV_H + +#include <sys/types.h> +#if __linux__ +#include <sys/sysmacros.h> +#endif +#include "fs/fd.h" + +// a dev_t is encoded like this in hex, where M is major and m is minor: +// mmmMMMmm +// (legacy I guess) + +typedef uint32_t dev_t_; + +static inline dev_t_ dev_make(int major, int minor) { + return ((minor & 0xfff00) << 12) | (major << 8) | (minor & 0xff); +} +static inline int dev_major(dev_t_ dev) { + return (dev & 0xfff00) >> 8; +} +static inline int dev_minor(dev_t_ dev) { + return ((dev & 0xfff00000) >> 12) | (dev & 0xff); +} + +static inline dev_t dev_real_from_fake(dev_t_ dev) { + return makedev(dev_major(dev), dev_minor(dev)); +} +static inline dev_t_ dev_fake_from_real(dev_t dev) { + return dev_make(major(dev), minor(dev)); +} + +#define DEV_BLOCK 0 +#define DEV_CHAR 1 + +struct dev_ops { + int (*open)(int major, int minor, struct fd *fd); + struct fd_ops fd; +}; + +extern struct dev_ops *block_devs[]; +extern struct dev_ops *char_devs[]; + +int dev_open(int major, int minor, int type, struct fd *fd); + +extern struct dev_ops null_dev; + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/devices.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/devices.h new file mode 100644 index 0000000000..63150a98d0 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/devices.h @@ -0,0 +1,44 @@ +#ifndef FS_DEVICES_H +#define FS_DEVICES_H + +// losely based on devices.txt from linux + +// --- memory devices --- +#define MEM_MAJOR 1 +// /dev/null +#define DEV_NULL_MINOR 3 +// /dev/zero +#define DEV_ZERO_MINOR 5 +// /dev/full +#define DEV_FULL_MINOR 7 +// /dev/random +#define DEV_RANDOM_MINOR 8 +// /dev/urandom +#define DEV_URANDOM_MINOR 9 + +// --- tty devices --- +// /dev/ttyX where X is minor +#define TTY_CONSOLE_MAJOR 4 + +// --- alternate tty devices --- +#define TTY_ALTERNATE_MAJOR 5 +// /dev/tty +#define DEV_TTY_MINOR 0 +// /dev/console +#define DEV_CONSOLE_MINOR 1 +// /dev/ptmx +#define DEV_PTMX_MINOR 2 + +// --- pseudo tty devices --- +#define TTY_PSEUDO_MASTER_MAJOR 128 +#define TTY_PSEUDO_SLAVE_MAJOR 136 + +// --- dynamic devices --- +#define DYN_DEV_MAJOR 240 + +// /dev/clipboard +#define DEV_CLIPBOARD_MINOR 0 +// /dev/gps +#define DEV_LOCATION_MINOR 1 + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dir.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dir.c new file mode 100644 index 0000000000..7b5bd518ee --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dir.c @@ -0,0 +1,134 @@ +#include <sys/stat.h> +#include <string.h> + +#include "kernel/calls.h" +#include "kernel/errno.h" +#include "kernel/fs.h" +#include "fs/fd.h" + +#define DENTS_DEBUG 0 + +static unsigned long fd_telldir(struct fd *fd) { + unsigned long off = fd->offset; + if (fd->ops->telldir) + off = fd->ops->telldir(fd); + return off; +} + +static void fd_seekdir(struct fd *fd, unsigned long off) { + fd->offset = off; + if (fd->ops->seekdir) + fd->ops->seekdir(fd, off); +} + +struct linux_dirent_ { + dword_t inode; + dword_t offset; + word_t reclen; + char name[]; +} __attribute__((packed)); + +struct linux_dirent64_ { + qword_t inode; + qword_t offset; + word_t reclen; + byte_t type; + char name[]; +} __attribute__((packed)); + +size_t fill_dirent_32(void *dirent_data, ino_t inode, off_t_ offset, const char *name, int type) { + struct linux_dirent_ *dirent = dirent_data; + dirent->inode = inode; + dirent->offset = offset; + dirent->reclen = offsetof(struct linux_dirent_, name) + + strlen(name) + 2; // name, null terminator, type + strcpy(dirent->name, name); + *((char *) dirent + dirent->reclen - 1) = type; + return dirent->reclen; +} + +size_t fill_dirent_64(void *dirent_data, ino_t inode, off_t_ offset, const char *name, int type) { + struct linux_dirent64_ *dirent = dirent_data; + dirent->inode = inode; + dirent->offset = offset; + dirent->reclen = offsetof(struct linux_dirent64_, name) + + strlen(name) + 1; // name, null terminator + dirent->type = type; + strcpy(dirent->name, name); + return dirent->reclen; +} + +int_t sys_getdents_common(fd_t f, addr_t dirents, dword_t count, + size_t (*fill_dirent)(void *, ino_t, off_t_, const char *, int)) { + STRACE("getdents(%d, %#x, %#x)", f, dirents, count); +#if DENTS_DEBUG + fprintf(stderr, "getdents: fd=%d dirents=%#x count=%d\n", f, dirents, count); +#endif + struct fd *fd = f_get(f); + if (fd == NULL) { +#if DENTS_DEBUG + fprintf(stderr, "getdents: fd %d -> EBADF\n", f); +#endif + return _EBADF; + } + if (!S_ISDIR(fd->type) || fd->ops->readdir == NULL) { +#if DENTS_DEBUG + fprintf(stderr, "getdents: fd %d type=%#x readdir=%p -> ENOTDIR\n", f, fd->type, + fd->ops ? (void *)fd->ops->readdir : NULL); +#endif + return _ENOTDIR; + } + + dword_t orig_count = count; + + long ptr; + int err; + int printed = 0; + while (true) { + ptr = fd_telldir(fd); + struct dir_entry entry = {0}; + err = fd->ops->readdir(fd, &entry); + if (err < 0) + return err; + if (err == 0) + break; + + size_t max_reclen = sizeof(struct linux_dirent64_) + strlen(entry.name) + 4; + char dirent_data[max_reclen]; + ino_t inode = entry.inode; + off_t_ offset = fd_telldir(fd); + const char *name = entry.name; + int type = entry.type; + size_t reclen = fill_dirent(dirent_data, inode, offset, name, type); + if (printed < 20) { + STRACE(" {inode=%d, offset=%d, name=%s, type=%d, reclen=%d}", + inode, offset, name, type, reclen); + printed++; + } + + if (reclen > count) + break; +#if DENTS_DEBUG + fprintf(stderr, "getdents: returning entry: name='%s' inode=%lu off=%lu reclen=%zu at addr=%#llx\n", + name, (unsigned long)inode, (unsigned long)offset, reclen, (unsigned long long)dirents); +#endif + if (user_write(dirents, dirent_data, reclen)) + return _EFAULT; + dirents += reclen; + count -= reclen; + } + + fd_seekdir(fd, ptr); +#if DENTS_DEBUG + fprintf(stderr, "getdents: returning %d bytes\n", orig_count - count); +#endif + return orig_count - count; +} + +int_t sys_getdents(fd_t f, addr_t dirents, uint_t count) { + return sys_getdents_common(f, dirents, count, fill_dirent_32); +} + +int_t sys_getdents64(fd_t f, addr_t dirents, uint_t count) { + return sys_getdents_common(f, dirents, count, fill_dirent_64); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dyndev.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dyndev.c new file mode 100644 index 0000000000..d365939b62 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dyndev.c @@ -0,0 +1,72 @@ +#include "kernel/errno.h" +#include "fs/dev.h" +#include "fs/dyndev.h" +#include "fs/devices.h" + +#define MAX_MINOR 255 + +// Handles DYNDEV_MAJOR device number +// XXX(stek29): unregister might be added later +struct dyn_dev_info { + // devs & next_dev lock + lock_t devs_lock; + // table of dev_ops registered by minor number + struct dev_ops *devs[MAX_MINOR+1]; +}; + +struct dyn_dev_info dyn_info_char = { + .devs_lock = LOCK_INITIALIZER, + .devs = {}, +}; + +int dyn_dev_register(struct dev_ops *ops, int type, int major, int minor) { + // Validate arguments + if (minor < 0 || minor > MAX_MINOR) { + return _EINVAL; + } + if (major != DYN_DEV_MAJOR) { + return _EINVAL; + } + if (ops == NULL) { + return _EINVAL; + } + if (type != DEV_CHAR) { + return _EINVAL; + } + + lock(&dyn_info_char.devs_lock); + + // Make sure minor number isn't taken yet + if (dyn_info_char.devs[minor] != NULL) { + unlock(&dyn_info_char.devs_lock); + return _EEXIST; + } + + dyn_info_char.devs[minor] = ops; + unlock(&dyn_info_char.devs_lock); + + return 0; +} + +static int dyn_open(int type, int major, int minor, struct fd *fd) { + assert(type == DEV_CHAR); + assert(major == DYN_DEV_MAJOR); + // it's safe to access devs without locking (read-only) + struct dev_ops *ops = dyn_info_char.devs[minor]; + if (ops == NULL) { + return _ENXIO; + } + fd->ops = &ops->fd; + + // Succeed if there's no open provided by ops + if (!ops->open) + return 0; + return ops->open(major, minor, fd); +} + +static int dyn_open_char(int major, int minor, struct fd *fd) { + return dyn_open(DEV_CHAR, major, minor, fd); +} +struct dev_ops dyn_dev_char = { + .open = dyn_open_char, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dyndev.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dyndev.h new file mode 100644 index 0000000000..b5aa3e6c85 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/dyndev.h @@ -0,0 +1,31 @@ +#ifndef FS_DYN_DEV_H +#define FS_DYN_DEV_H + +// dyn_dev's are dynamically added devices (character only for now) +// with custom dev_ops assigned +// It's useful to add new device "drivers" in runtime (for example, +// devices only present on some platforms) + +// dev_ops handing char device with DYN_DEV_MAJOR major number +extern struct dev_ops dyn_dev_char; + +// Registers new block/character device with provided major and +// minor numbers, handled by provided ops +// +// ops should be valid for "kernel" lifetime (should not be freed, but +// might be static), and should not be null +// +// type is DEV_BLOCK or DEV_CHAR +// (only char is supported for now) +// +// major should be DYN_DEV_MAJOR +// +// minor should be 0-255 +// +// Return value: +// - 0 on success +// - _EEXIST if provided minor number is alredy taken +// - _EINVAL if provided arguments are invalid +extern int dyn_dev_register(struct dev_ops *ops, int type, int major, int minor); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake-db.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake-db.c new file mode 100644 index 0000000000..c0940e4aba --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake-db.c @@ -0,0 +1,425 @@ +#include <string.h> +#include <sys/stat.h> +#include <unistd.h> +#include "kernel/errno.h" +#include "debug.h" +#include "misc.h" +#include "fs/fake-db.h" + +static void db_check_error(struct fakefs_db *fs) { + int errcode = sqlite3_errcode(fs->db); + switch (errcode) { + case SQLITE_OK: + case SQLITE_ROW: + case SQLITE_DONE: + break; + + default: + die("sqlite error: %d %#x %s", errcode, sqlite3_extended_errcode(fs->db), sqlite3_errmsg(fs->db)); + } +} + +// Retry-aware variants that handle SQLITE_BUSY/SQLITE_LOCKED instead of aborting. +#define DB_RETRY_MAX 50 +#define DB_RETRY_DELAY_US 20000 /* 20ms between retries = up to 1s total */ + +static bool db_exec_retry(struct fakefs_db *fs, sqlite3_stmt *stmt) { + for (int attempt = 0; attempt < DB_RETRY_MAX; attempt++) { + int err = sqlite3_step(stmt); + if (err == SQLITE_ROW || err == SQLITE_DONE || err == SQLITE_OK) + return err == SQLITE_ROW; + int errcode = sqlite3_errcode(fs->db); + if (errcode == SQLITE_BUSY || errcode == SQLITE_LOCKED) { + sqlite3_reset(stmt); + usleep(DB_RETRY_DELAY_US); + continue; + } + db_check_error(fs); + return false; + } + printk("WARNING: db_exec_retry exhausted %d attempts, proceeding\n", DB_RETRY_MAX); + return false; +} + +static void db_reset_retry(struct fakefs_db *fs, sqlite3_stmt *stmt) { + for (int attempt = 0; attempt < DB_RETRY_MAX; attempt++) { + sqlite3_reset(stmt); + int errcode = sqlite3_errcode(fs->db); + if (errcode == SQLITE_OK || errcode == SQLITE_ROW || errcode == SQLITE_DONE) + return; + if (errcode == SQLITE_BUSY || errcode == SQLITE_LOCKED) { + usleep(DB_RETRY_DELAY_US); + continue; + } + db_check_error(fs); + return; + } + printk("WARNING: db_reset_retry exhausted %d attempts\n", DB_RETRY_MAX); +} + +// [T-fakefs-db-init-no-die] Init-phase variants that DO NOT abort the whole app +// on a SQLite error. fake_db_init() runs every time a fakefs mount is opened +// (incl. dynamic bind-mounts while the app is running); on iOS 27 betas these +// prepare/step calls were hitting SQLITE_BUSY/LOCKED/IOERR and the old +// db_check_error() → die() path killed the entire process (Abort trap 6 on a +// node-* thread, symbolicated to fake_db_init.cold.1). Instead: retry transient +// lock contention, log the full error, and return the SQLite error code so +// fake_db_init() can fail the mount gracefully (the caller already handles a +// negative return). Returns SQLITE_OK on success. +static int db_log_error(struct fakefs_db *fs, const char *what, const char *sql) { + int errcode = sqlite3_errcode(fs->db); + printk("fakefs db init error: %s%s%s — code=%d ext=%#x msg=%s\n", + what, sql ? " sql=" : "", sql ? sql : "", + errcode, sqlite3_extended_errcode(fs->db), sqlite3_errmsg(fs->db)); + return errcode; +} + +// Prepare a statement, retrying transient BUSY/LOCKED. On terminal failure logs +// and returns the SQLite error code (caller must check); *out is set to the +// statement (NULL on failure). +static int db_prepare_checked(struct fakefs_db *fs, const char *sql, sqlite3_stmt **out) { + for (int attempt = 0; attempt < DB_RETRY_MAX; attempt++) { + sqlite3_stmt *stmt = NULL; + int rc = sqlite3_prepare_v2(fs->db, sql, strlen(sql) + 1, &stmt, NULL); + if (rc == SQLITE_OK) { + *out = stmt; + return SQLITE_OK; + } + if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) { + if (stmt) sqlite3_finalize(stmt); + usleep(DB_RETRY_DELAY_US); + continue; + } + if (stmt) sqlite3_finalize(stmt); + *out = NULL; + return db_log_error(fs, "prepare", sql); + } + *out = NULL; + printk("fakefs db init: prepare exhausted %d retries: %s\n", DB_RETRY_MAX, sql); + return SQLITE_BUSY; +} + +// Step a statement to completion, retrying transient BUSY/LOCKED. Returns +// SQLITE_DONE/SQLITE_ROW on success, or the error code on terminal failure. +static int db_step_checked(struct fakefs_db *fs, sqlite3_stmt *stmt, const char *sql) { + for (int attempt = 0; attempt < DB_RETRY_MAX; attempt++) { + int rc = sqlite3_step(stmt); + if (rc == SQLITE_DONE || rc == SQLITE_ROW || rc == SQLITE_OK) + return rc; + if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) { + sqlite3_reset(stmt); + usleep(DB_RETRY_DELAY_US); + continue; + } + return db_log_error(fs, "step", sql); + } + printk("fakefs db init: step exhausted %d retries: %s\n", DB_RETRY_MAX, sql); + return SQLITE_BUSY; +} + +// Convenience: prepare + step + finalize a one-shot statement (pragmas, etc.), +// retrying transient lock contention. Returns SQLITE_OK or the error code. +static int db_exec_oneshot(struct fakefs_db *fs, const char *sql) { + sqlite3_stmt *stmt = NULL; + int rc = db_prepare_checked(fs, sql, &stmt); + if (rc != SQLITE_OK) + return rc; + rc = db_step_checked(fs, stmt, sql); + sqlite3_finalize(stmt); + return (rc == SQLITE_DONE || rc == SQLITE_ROW || rc == SQLITE_OK) ? SQLITE_OK : rc; +} + +bool db_exec(struct fakefs_db *fs, sqlite3_stmt *stmt) { + return db_exec_retry(fs, stmt); +} +void db_reset(struct fakefs_db *fs, sqlite3_stmt *stmt) { + db_reset_retry(fs, stmt); +} +void db_exec_reset(struct fakefs_db *fs, sqlite3_stmt *stmt) { + db_exec(fs, stmt); + db_reset(fs, stmt); +} + +void db_begin_read(struct fakefs_db *fs) { + sqlite3_mutex_enter(fs->lock); + db_exec_reset(fs, fs->stmt.begin_deferred); +} +void db_begin_write(struct fakefs_db *fs) { + sqlite3_mutex_enter(fs->lock); + db_exec_reset(fs, fs->stmt.begin_immediate); +} +void db_commit(struct fakefs_db *fs) { + db_exec_reset(fs, fs->stmt.commit); + sqlite3_mutex_leave(fs->lock); +} +void db_rollback(struct fakefs_db *fs) { + db_exec_reset(fs, fs->stmt.rollback); + sqlite3_mutex_leave(fs->lock); +} + +static void bind_path(sqlite3_stmt *stmt, int i, const char *path) { + sqlite3_bind_blob(stmt, i, path, strlen(path), SQLITE_TRANSIENT); +} + +inode_t path_get_inode(struct fakefs_db *fs, const char *path) { + // select inode from paths where path = ? + bind_path(fs->stmt.path_get_inode, 1, path); + inode_t inode = 0; + if (db_exec(fs, fs->stmt.path_get_inode)) + inode = sqlite3_column_int64(fs->stmt.path_get_inode, 0); + db_reset(fs, fs->stmt.path_get_inode); + return inode; +} +bool path_read_stat(struct fakefs_db *fs, const char *path, struct ish_stat *stat, inode_t *inode) { + // select inode, stat from stats natural join paths where path = ? + bind_path(fs->stmt.path_read_stat, 1, path); + bool exists = db_exec(fs, fs->stmt.path_read_stat); + if (exists) { + if (inode) + *inode = sqlite3_column_int64(fs->stmt.path_read_stat, 0); + if (stat) + *stat = *(struct ish_stat *) sqlite3_column_blob(fs->stmt.path_read_stat, 1); + } + db_reset(fs, fs->stmt.path_read_stat); + return exists; +} +inode_t path_create(struct fakefs_db *fs, const char *path, struct ish_stat *stat) { + // insert into stats (stat) values (?) + sqlite3_bind_blob(fs->stmt.path_create_stat, 1, stat, sizeof(*stat), SQLITE_TRANSIENT); + db_exec_reset(fs, fs->stmt.path_create_stat); + inode_t inode = sqlite3_last_insert_rowid(fs->db); + // insert or replace into paths values (?, last_insert_rowid()) + bind_path(fs->stmt.path_create_path, 1, path); + db_exec_reset(fs, fs->stmt.path_create_path); + return inode; +} + +void inode_read_stat_or_die(struct fakefs_db *fs, inode_t inode, struct ish_stat *stat) { + if (!inode_read_stat_if_exist(fs, inode, stat)) + die("inode_read_stat(%llu): missing inode", (unsigned long long) inode); +} +bool inode_read_stat_if_exist(struct fakefs_db *fs, inode_t inode, struct ish_stat *stat) { + // select stat from stats where inode = ? + sqlite3_bind_int64(fs->stmt.inode_read_stat, 1, inode); + bool exist = db_exec(fs, fs->stmt.inode_read_stat); + if (exist) + *stat = *(struct ish_stat *) sqlite3_column_blob(fs->stmt.inode_read_stat, 0); + db_reset(fs, fs->stmt.inode_read_stat); + return exist; +} +void inode_write_stat(struct fakefs_db *fs, inode_t inode, struct ish_stat *stat) { + // update stats set stat = ? where inode = ? + sqlite3_bind_blob(fs->stmt.inode_write_stat, 1, stat, sizeof(*stat), SQLITE_TRANSIENT); + sqlite3_bind_int64(fs->stmt.inode_write_stat, 2, inode); + db_exec_reset(fs, fs->stmt.inode_write_stat); +} + +void path_link(struct fakefs_db *fs, const char *src, const char *dst) { + inode_t inode = path_get_inode(fs, src); + if (inode == 0) + die("fakefs link(%s, %s): nonexistent src path", src, dst); + // insert or replace into paths (path, inode) values (?, ?) + bind_path(fs->stmt.path_link, 1, dst); + sqlite3_bind_int64(fs->stmt.path_link, 2, inode); + db_exec_reset(fs, fs->stmt.path_link); +} +inode_t path_unlink(struct fakefs_db *fs, const char *path) { + inode_t inode = path_get_inode(fs, path); + if (inode == 0) + return 0; // Path not in meta.db — already gone or never tracked + // delete from paths where path = ? + bind_path(fs->stmt.path_unlink, 1, path); + db_exec_reset(fs, fs->stmt.path_unlink); + return inode; +} +void path_rename(struct fakefs_db *fs, const char *src, const char *dst) { + // update or replace paths set path = change_prefix(path, ? [len(src)], ? [dst]) + // where (path >= ? [src plus /] and path < [src plus 0]) or path = ? [src] + // arguments: + // 1. length of src + // 2. dst + // 3. src plus / + // 4. src plus 0 + // 5. src + size_t src_len = strlen(src); + sqlite3_bind_int64(fs->stmt.path_rename, 1, src_len); + bind_path(fs->stmt.path_rename, 2, dst); + char src_extra[src_len + 1]; + memcpy(src_extra, src, src_len); + src_extra[src_len] = '/'; + sqlite3_bind_blob(fs->stmt.path_rename, 3, src_extra, src_len + 1, SQLITE_TRANSIENT); + src_extra[src_len] = '0'; + sqlite3_bind_blob(fs->stmt.path_rename, 4, src_extra, src_len + 1, SQLITE_TRANSIENT); + sqlite3_bind_blob(fs->stmt.path_rename, 5, src_extra, src_len, SQLITE_TRANSIENT); + db_exec_reset(fs, fs->stmt.path_rename); +} + +#if DEBUG_sql +static int trace_callback(unsigned UNUSED(why), void *UNUSED(fuck), void *stmt, void *_sql) { + char *sql = _sql; + printk("%d sql trace: %s %s\n", current ? current->pid : -1, sqlite3_expanded_sql(stmt), sql[0] == '-' ? sql : ""); + return 0; +} +#endif + +static void sqlite_func_change_prefix(sqlite3_context *context, int argc, sqlite3_value **args) { + assert(argc == 3); + const void *in_blob = sqlite3_value_blob(args[0]); + size_t in_size = sqlite3_value_bytes(args[0]); + size_t start = sqlite3_value_int64(args[1]); + const void *replacement = sqlite3_value_blob(args[2]); + size_t replacement_size = sqlite3_value_bytes(args[2]); + size_t out_size = in_size - start + replacement_size; + char *out_blob = sqlite3_malloc(out_size); + memcpy(out_blob, replacement, replacement_size); + memcpy(out_blob + replacement_size, in_blob + start, in_size - start); + sqlite3_result_blob(context, out_blob, out_size, sqlite3_free); +} + +extern int fakefs_rebuild(struct fakefs_db *fs, int root_fd); +extern int fakefs_migrate(struct fakefs_db *fs, int root_fd); + +int fake_db_init(struct fakefs_db *fs, const char *db_path, int root_fd) { + int err = sqlite3_open_v2(db_path, &fs->db, SQLITE_OPEN_READWRITE, NULL); + if (err != SQLITE_OK) { + printk("error opening database: %s\n", sqlite3_errmsg(fs->db)); + sqlite3_close(fs->db); + return _EINVAL; + } + sqlite3_busy_timeout(fs->db, 5000); + sqlite3_create_function(fs->db, "change_prefix", 3, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlite_func_change_prefix, NULL, NULL); + + // [T-fakefs-db-init-no-die] Every prepare/step below now fails the mount + // (return _EIO) instead of die()-ing the whole app on a SQLite error. The + // caller (fakefs mount) already handles a negative return gracefully. + if (db_exec_oneshot(fs, "pragma journal_mode=wal") != SQLITE_OK) goto init_fail; + if (db_exec_oneshot(fs, "pragma foreign_keys=true") != SQLITE_OK) goto init_fail; + + // N18: Apple-friendly sqlite tuning. The fakefs db is read-mostly + // during normal use (writes happen for chmod / chown / mknod / new + // files). N17 signpost data showed 78K db_exec calls totaling + // 122ms = 8% of npm --version user CPU. Three knobs help on macOS: + // + // - PRAGMA mmap_size: lets sqlite read pages directly through + // mmap instead of read() syscalls. The OS's unified buffer + // cache then serves repeated reads at memcpy speed. + // - PRAGMA cache_size (negative => KB of in-process page cache): + // sqlite default is 2 MB; bump to 64 MB so the working set fits. + // - PRAGMA synchronous=NORMAL: WAL with NORMAL is durable across + // process crashes (like FULL) but skips an fsync per commit, + // cheap when fakefs writes are infrequent. + // - PRAGMA temp_store=MEMORY: keeps sort/temp tables off disk. + static const char *tuning[] = { + "pragma mmap_size=268435456", // 256 MB + "pragma cache_size=-65536", // 64 MB in-process page cache + "pragma synchronous=NORMAL", + "pragma temp_store=MEMORY", + }; + for (size_t ti = 0; ti < sizeof(tuning)/sizeof(tuning[0]); ti++) { + // Tuning pragmas are best-effort: a failure here only loses a perf knob, + // not correctness, so log and continue rather than fail the mount. + if (db_exec_oneshot(fs, tuning[ti]) != SQLITE_OK) + printk("fakefs db init: tuning pragma failed (continuing): %s\n", tuning[ti]); + } + +#if DEBUG_sql + sqlite3_trace_v2(mount->db, SQLITE_TRACE_STMT, trace_callback, NULL); +#endif + + err = fakefs_migrate(fs, root_fd); + if (err < 0) + return err; + + // after the filesystem is compressed, transmitted, and uncompressed, the + // inode numbers will be different. to detect this, the inode of the + // database file is stored inside the database and compared with the actual + // database file inode, and if they're different we rebuild the database. + struct stat statbuf; + if (stat(db_path, &statbuf) < 0) ERRNO_DIE("stat database"); + ino_t db_inode = statbuf.st_ino; + sqlite3_stmt *statement = NULL; + if (db_prepare_checked(fs, "select db_inode from meta", &statement) != SQLITE_OK) goto init_fail; + if (db_step_checked(fs, statement, "select db_inode from meta") == SQLITE_ROW) { + if ((uint64_t) sqlite3_column_int64(statement, 0) != db_inode) { + sqlite3_finalize(statement); + statement = NULL; + int err = fakefs_rebuild(fs, root_fd); + if (err < 0) { + return err; + } + } + } + if (statement != NULL) + sqlite3_finalize(statement); + + // save current inode + if (db_prepare_checked(fs, "update meta set db_inode = ?", &statement) != SQLITE_OK) goto init_fail; + sqlite3_bind_int64(statement, 1, (int64_t) db_inode); + int meta_rc = db_step_checked(fs, statement, "update meta set db_inode = ?"); + if (meta_rc != SQLITE_DONE && meta_rc != SQLITE_ROW && meta_rc != SQLITE_OK) { + sqlite3_finalize(statement); + goto init_fail; + } + sqlite3_finalize(statement); + + // delete orphaned stats + if (db_exec_oneshot(fs, "delete from stats where not exists (select 1 from paths where inode = stats.inode)") != SQLITE_OK) + goto init_fail; + + fs->lock = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + // [T-fakefs-db-init-no-die] Each cached statement must prepare successfully; + // a NULL would crash later at runtime. On any failure, fail the mount. +#define PREPARE_OR_FAIL(field, sql) \ + if (db_prepare_checked(fs, (sql), &fs->stmt.field) != SQLITE_OK) goto init_fail + PREPARE_OR_FAIL(begin_deferred, "begin deferred"); + PREPARE_OR_FAIL(begin_immediate, "begin immediate"); + PREPARE_OR_FAIL(commit, "commit"); + PREPARE_OR_FAIL(rollback, "rollback"); + PREPARE_OR_FAIL(path_get_inode, "select inode from paths where path = ?"); + PREPARE_OR_FAIL(path_read_stat, "select inode, stat from stats natural join paths where path = ?"); + PREPARE_OR_FAIL(path_create_stat, "insert into stats (stat) values (?)"); + PREPARE_OR_FAIL(path_create_path, "insert or replace into paths values (?, last_insert_rowid())"); + PREPARE_OR_FAIL(inode_read_stat, "select stat from stats where inode = ?"); + PREPARE_OR_FAIL(inode_write_stat, "update stats set stat = ? where inode = ?"); + PREPARE_OR_FAIL(path_link, "insert or replace into paths (path, inode) values (?, ?)"); + PREPARE_OR_FAIL(path_unlink, "delete from paths where path = ?"); + PREPARE_OR_FAIL(path_rename, "update or replace paths set path = change_prefix(path, ?, ?) " + "where (path >= ? and path < ?) or path = ?"); + PREPARE_OR_FAIL(path_from_inode, "select path from paths where inode = ?"); + PREPARE_OR_FAIL(try_cleanup_inode, "delete from stats where inode = ? and not exists (select 1 from paths where inode = stats.inode)"); +#undef PREPARE_OR_FAIL + return 0; + +init_fail: + // [T-fakefs-db-init-no-die] A SQLite error during init no longer aborts the + // whole app. Close the half-open db and return an error so the fakefs mount + // fails gracefully (the caller handles a negative return). + printk("fakefs db init: FAILED for %s — mount aborted (app kept alive)\n", db_path); + if (fs->db) { + sqlite3_close(fs->db); + fs->db = NULL; + } + return _EIO; +} + +int fake_db_deinit(struct fakefs_db *fs) { + if (fs->db) { + sqlite3_finalize(fs->stmt.begin_deferred); + sqlite3_finalize(fs->stmt.begin_immediate); + sqlite3_finalize(fs->stmt.commit); + sqlite3_finalize(fs->stmt.rollback); + sqlite3_finalize(fs->stmt.path_get_inode); + sqlite3_finalize(fs->stmt.path_read_stat); + sqlite3_finalize(fs->stmt.path_create_stat); + sqlite3_finalize(fs->stmt.path_create_path); + sqlite3_finalize(fs->stmt.inode_read_stat); + sqlite3_finalize(fs->stmt.inode_write_stat); + sqlite3_finalize(fs->stmt.path_link); + sqlite3_finalize(fs->stmt.path_unlink); + sqlite3_finalize(fs->stmt.path_rename); + sqlite3_finalize(fs->stmt.path_from_inode); + sqlite3_finalize(fs->stmt.try_cleanup_inode); + return sqlite3_close(fs->db); + } + return SQLITE_OK; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake-db.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake-db.h new file mode 100644 index 0000000000..e5a0541a2b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake-db.h @@ -0,0 +1,63 @@ +#ifndef FS_FAKEFS_API_H +#define FS_FAKEFS_API_H + +#include <sqlite3.h> +#include "fs/fix_path.h" +#include "misc.h" + +struct fakefs_db { + sqlite3 *db; + struct { + sqlite3_stmt *begin_deferred; + sqlite3_stmt *begin_immediate; + sqlite3_stmt *commit; + sqlite3_stmt *rollback; + sqlite3_stmt *path_get_inode; + sqlite3_stmt *path_read_stat; + sqlite3_stmt *path_create_stat; + sqlite3_stmt *path_create_path; + sqlite3_stmt *inode_read_stat; + sqlite3_stmt *inode_write_stat; + sqlite3_stmt *path_link; + sqlite3_stmt *path_unlink; + sqlite3_stmt *path_rename; + sqlite3_stmt *path_from_inode; + sqlite3_stmt *try_cleanup_inode; + } stmt; + sqlite3_mutex *lock; +}; + +int fake_db_init(struct fakefs_db *fs, const char *db_path, int root_fd); +int fake_db_deinit(struct fakefs_db *fs); + +void db_begin_read(struct fakefs_db *fs); +void db_begin_write(struct fakefs_db *fs); +void db_commit(struct fakefs_db *fs); +void db_rollback(struct fakefs_db *fs); + +bool db_exec(struct fakefs_db *fs, sqlite3_stmt *stmt); +void db_reset(struct fakefs_db *fs, sqlite3_stmt *stmt); +void db_exec_reset(struct fakefs_db *fs, sqlite3_stmt *stmt); + +struct ish_stat { + uint32_t mode; + uint32_t uid; + uint32_t gid; + uint32_t rdev; +}; + +typedef uint64_t inode_t; + +inode_t path_get_inode(struct fakefs_db *fs, const char *path); +bool path_read_stat(struct fakefs_db *fs, const char *path, struct ish_stat *stat, uint64_t *inode); +inode_t path_create(struct fakefs_db *fs, const char *path, struct ish_stat *stat); + +bool inode_read_stat_if_exist(struct fakefs_db *fs, inode_t inode, struct ish_stat *stat); +void inode_read_stat_or_die(struct fakefs_db *fs, inode_t inode, struct ish_stat *stat); +void inode_write_stat(struct fakefs_db *fs, inode_t inode, struct ish_stat *stat); + +void path_link(struct fakefs_db *fs, const char *src, const char *dst); +inode_t path_unlink(struct fakefs_db *fs, const char *path); +void path_rename(struct fakefs_db *fs, const char *src, const char *dst); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake-migrate.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake-migrate.c new file mode 100644 index 0000000000..cb4bf3846e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake-migrate.c @@ -0,0 +1,62 @@ +#include "kernel/fs.h" +#include "debug.h" +#include "kernel/errno.h" +#include "fs/fake-db.h" +#include "fs/sqlutil.h" + +// The value of the user_version pragma is used to decide what needs migrating. + +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +static struct migration { + const char *sql; + void (*migrate)(struct fakefs_db *fs); +} migrations[] = { + // version 1: add another index + { + "create index inode_to_path on paths (inode, path);" + }, + // version 2: add foreign key constraint on paths, create trigger to automatically cleanup stats + { + "create table paths_new (path blob primary key, inode integer references stats(inode));" + "insert into paths_new select * from paths where exists (select 1 from stats where inode = paths.inode);" + "drop table paths; alter table paths_new rename to paths;" + "create index inode_to_path on paths (inode, path);" + "delete from stats where not exists (select 1 from paths where inode = stats.inode);" + "create trigger delete_path after delete on paths " + "when not exists (select 1 from paths where inode = old.inode) " + "begin " + "delete from stats where not exists (select 1 from paths where inode = old.inode) and inode = old.inode; " + "end;" + }, + // version 3: the trigger was a mistake + { + "drop trigger delete_path" + }, +}; + +int fakefs_migrate(struct fakefs_db *fs, int UNUSED(root_fd)) { + sqlite3 *db = fs->db; + int err; + sqlite3_stmt *user_version = PREPARE("pragma user_version"); + STEP(user_version); + int version = sqlite3_column_int(user_version, 0); + FINALIZE(user_version); + + EXEC("begin"); + int versions = sizeof(migrations)/sizeof(migrations[0]); + while (version < versions) { + struct migration m = migrations[version]; + if (m.sql != NULL) + EXEC(m.sql); + if (m.migrate != NULL) + m.migrate(fs); + version++; + } + // for some reason placeholders aren't allowed in pragmas + char *pragma_user_version = sqlite3_mprintf("pragma user_version = %d", version); + EXEC(pragma_user_version); + sqlite3_free(pragma_user_version); + EXEC("commit"); + + return 0; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake-rebuild.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake-rebuild.c new file mode 100644 index 0000000000..ed2d7d5190 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake-rebuild.c @@ -0,0 +1,122 @@ +#include <stdio.h> +#include <string.h> +#include <sys/stat.h> +#include <unistd.h> +#include "fs/sqlutil.h" +#include "fs/fake-db.h" +#include "kernel/errno.h" +#include "util/list.h" +#include "debug.h" + +// rebuild process in pseudocode: +// +// table = {} +// for each path, inode: +// real_inode = stat(path).st_ino +// if inode in table: +// unlink(path) +// link(table[inode], path) +// else: +// table[inode] = path +// stat = db['stat ' + inode] +// new_db['inode ' + path] = real_inode +// new_db['stat ' + real_inode] = stat + +// ad hoc hashtable +struct entry { + ino_t inode; + char *path; + struct list chain; +}; + +int fakefs_rebuild(struct fakefs_db *fs, int root_fd) { + sqlite3 *db = fs->db; + int err; + + EXEC("begin"); + EXEC("create table paths_old (path blob primary key, inode integer)"); + EXEC("create table stats_old (inode integer primary key, stat blob)"); + EXEC("insert into paths_old select * from paths"); + EXEC("insert into stats_old select * from stats"); + EXEC("delete from paths"); + EXEC("delete from stats"); + sqlite3_stmt *get_paths = PREPARE("select path, inode from paths_old"); + sqlite3_stmt *read_stat = PREPARE("select stat from stats_old where inode = ?"); + sqlite3_stmt *write_path = PREPARE("insert into paths (path, inode) values (?, ?)"); + sqlite3_stmt *write_stat = PREPARE("replace into stats (inode, stat) values (?, ?)"); + + struct list hashtable[2000]; +#define HASH_SIZE (sizeof(hashtable)/sizeof(hashtable[0])) + for (unsigned i = 0; i < HASH_SIZE; i++) + list_init(&hashtable[i]); + + while (STEP(get_paths)) { + const char *path = (const char *) sqlite3_column_text(get_paths, 0); + ino_t inode = sqlite3_column_int64(get_paths, 1); + + // grab real inode + struct stat stat; + int err = fstatat(root_fd, fix_path(path), &stat, 0); + if (err < 0) + continue; + ino_t real_inode = stat.st_ino; + + // restore hardlinks + struct list *bucket = &hashtable[inode % HASH_SIZE]; + struct entry *entry; + bool found = false; + list_for_each_entry(bucket, entry, chain) { + if (entry->inode == inode) { + unlinkat(root_fd, fix_path(path), 0); + linkat(root_fd, fix_path(entry->path), root_fd, fix_path(path), 0); + found = true; + break; + } + } + if (!found) { + entry = malloc(sizeof(struct entry)); + entry->inode = inode; + entry->path = strdup(path); + list_add(bucket, &entry->chain); + } + + // extract the stat so we can copy it + err = sqlite3_bind_int64(read_stat, 1, inode); CHECK_ERR(); + if (STEP(read_stat) == false) { + RESET(read_stat); + continue; + } + const void *stat_data = sqlite3_column_blob(read_stat, 0); + size_t stat_data_size = sqlite3_column_bytes(read_stat, 0); + + // store all the information in the new database + err = sqlite3_bind_int64(write_stat, 1, real_inode); CHECK_ERR(); + err = sqlite3_bind_blob(write_stat, 2, stat_data, stat_data_size, SQLITE_TRANSIENT); CHECK_ERR(); + STEP(write_stat); + RESET(write_stat); + err = sqlite3_bind_blob(write_path, 1, path, strlen(path), SQLITE_TRANSIENT); CHECK_ERR(); + err = sqlite3_bind_int64(write_path, 2, real_inode); CHECK_ERR(); + STEP(write_path); + RESET(write_path); + + RESET(read_stat); + } + + for (unsigned i = 0; i < HASH_SIZE; i++) { + struct entry *entry, *tmp; + list_for_each_entry_safe(&hashtable[i], entry, tmp, chain) { + list_remove(&entry->chain); + free(entry->path); + free(entry); + } + } + + EXEC("drop table paths_old"); + EXEC("drop table stats_old"); + EXEC("commit"); + FINALIZE(get_paths); + FINALIZE(read_stat); + FINALIZE(write_path); + FINALIZE(write_stat); + return 0; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake.c new file mode 100644 index 0000000000..4f4a741bb0 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake.c @@ -0,0 +1,1057 @@ +#include <stdarg.h> +#include <stdio.h> +#include <limits.h> +#include <string.h> +#include <fcntl.h> +#include <sys/stat.h> +#include <sys/file.h> +#include <sqlite3.h> +#include <unistd.h> +#include <dirent.h> +#include <errno.h> + +#include "debug.h" +#include "kernel/errno.h" +#include "kernel/task.h" +#include "fs/fd.h" +#include "fs/dev.h" +#include "fs/inode.h" +#include "fs/real.h" +#include "platform/platform.h" +#define ISH_INTERNAL +#include "fs/fake.h" + +// TODO document database + +/* ===== Bind Mount Support ===== + * Allows redirecting fakefs paths to external host directories via symlinks. + * Files under bind-mounted paths get auto-created meta.db entries on access. + * This avoids the need to copy files into the fakefs data/ directory. */ + +#define FAKEFS_MAX_BIND_MOUNTS 32 + +/* Compute a relative symlink target from link_dir to abs_target. + * link_dir is the absolute path of the directory containing the symlink. + * abs_target is the absolute path the symlink should point to. + * Result is written to out (must be PATH_MAX). Returns 0 on success. */ +static int compute_relative_path(const char *link_dir, const char *abs_target, + char *out, size_t out_size) { + /* Find common prefix (up to the last shared '/') */ + size_t common = 0; + size_t last_slash = 0; + for (size_t i = 0; link_dir[i] && abs_target[i]; i++) { + if (link_dir[i] != abs_target[i]) + break; + common = i + 1; + if (link_dir[i] == '/') + last_slash = common; + } + /* If both ended at common, check for trailing slash boundary */ + if (link_dir[common] == '\0' && abs_target[common] == '/') { + last_slash = common; + } else if (abs_target[common] == '\0' && link_dir[common] == '/') { + last_slash = common; + } else { + common = last_slash; + } + + /* Count remaining '/' in link_dir after common prefix => number of "../" */ + int ups = 0; + for (const char *p = link_dir + common; *p; p++) { + if (*p == '/') + ups++; + } + /* If link_dir doesn't end with '/', the last component is the dir name */ + size_t ld_len = strlen(link_dir); + if (ld_len > 0 && link_dir[ld_len - 1] != '/') + ups++; + + out[0] = '\0'; + for (int i = 0; i < ups; i++) { + if (i == 0) + strlcpy(out, "..", out_size); + else + strlcat(out, "/..", out_size); + } + + /* Append the remainder of abs_target after common prefix */ + const char *suffix = abs_target + common; + if (*suffix == '/') suffix++; /* skip leading slash */ + if (*suffix) { + if (ups > 0) strlcat(out, "/", out_size); + strlcat(out, suffix, out_size); + } + + if (out[0] == '\0') { + strlcpy(out, ".", out_size); + } + + return 0; +} + +struct fakefs_bind_mount { + char path[PATH_MAX]; /* Linux path prefix, e.g. "/var/minis/offloads" */ + char host_path[PATH_MAX]; /* Resolved host path the symlink points to */ + int path_len; + int host_path_len; + bool active; + bool read_only; /* Reject write syscalls with EROFS at fakefs layer. */ +}; + +static struct fakefs_bind_mount g_bind_mounts[FAKEFS_MAX_BIND_MOUNTS]; +struct mount *g_fakefs_mount = NULL; + +/* Translate a resolved host path back to a Linux path for bind mounts. + * e.g. "/Users/.../MinisChat/minis/<sid>/attachments/file.mp4" + * -> "/var/minis/attachments/file.mp4" + * Returns true and writes to out_path if a match was found. */ +bool fakefs_bind_mount_resolve_path(const char *resolved, char *out_path, size_t out_size) { + for (int i = 0; i < FAKEFS_MAX_BIND_MOUNTS; i++) { + if (!g_bind_mounts[i].active) + continue; + int hlen = g_bind_mounts[i].host_path_len; + /* Try matching as-is first */ + if (strncmp(resolved, g_bind_mounts[i].host_path, hlen) == 0 && + (resolved[hlen] == '/' || resolved[hlen] == '\0')) { + snprintf(out_path, out_size, "%s%s", + g_bind_mounts[i].path, resolved + hlen); + return true; + } + /* F_GETPATH resolves /var -> /private/var on iOS. + * If host_path starts with /var/ but resolved starts with /private/var/, + * try matching with the /private prefix stripped from resolved. */ + if (strncmp(g_bind_mounts[i].host_path, "/var/", 5) == 0 && + strncmp(resolved, "/private/var/", 13) == 0) { + const char *resolved_no_private = resolved + 8; /* skip "/private" */ + if (strncmp(resolved_no_private, g_bind_mounts[i].host_path, hlen) == 0 && + (resolved_no_private[hlen] == '/' || resolved_no_private[hlen] == '\0')) { + snprintf(out_path, out_size, "%s%s", + g_bind_mounts[i].path, resolved_no_private + hlen); + return true; + } + } + } + return false; +} + +/* Translate a Linux path to a host absolute path if under a bind mount. + * E.g. "/var/minis/skills/foo" -> "/var/mobile/.../Library/MinisChat/skills/foo" + * Handles both "/var/minis/..." (with leading /) and "var/minis/..." (without). + * Returns true and writes to out_path if the path is under a bind mount. */ +/* Public wrapper for native offload handlers. See fake.h. */ +bool fakefs_bind_mount_translate_path(const char *path, char *out_path, size_t out_size); + +static bool bind_mount_translate_path(const char *path, char *out_path, size_t out_size) { + /* Normalize: if path lacks leading /, prepend it for comparison. + * Bind mount table always stores paths with leading /. */ + char normalized[MAX_PATH]; + const char *cmp_path = path; + if (path[0] != '/') { + snprintf(normalized, sizeof(normalized), "/%s", path); + cmp_path = normalized; + } + for (int i = 0; i < FAKEFS_MAX_BIND_MOUNTS; i++) { + if (!g_bind_mounts[i].active) + continue; + int len = g_bind_mounts[i].path_len; + if (strncmp(g_bind_mounts[i].path, cmp_path, len) == 0 && + (cmp_path[len] == '/' || cmp_path[len] == '\0')) { + snprintf(out_path, out_size, "%s%s", + g_bind_mounts[i].host_path, cmp_path + len); + return true; + } + } + return false; +} + +/* Check if a path is at or under a bind mount prefix. + * Handles both "/var/minis/..." and "var/minis/..." (without leading /). */ +static bool is_under_bind_mount(const char *path) { + char normalized[MAX_PATH]; + const char *cmp_path = path; + if (path[0] != '/') { + snprintf(normalized, sizeof(normalized), "/%s", path); + cmp_path = normalized; + } + for (int i = 0; i < FAKEFS_MAX_BIND_MOUNTS; i++) { + if (!g_bind_mounts[i].active) + continue; + int len = g_bind_mounts[i].path_len; + if (strncmp(g_bind_mounts[i].path, cmp_path, len) == 0 && + (cmp_path[len] == '/' || cmp_path[len] == '\0')) + return true; + } + return false; +} + +/* Return true if `path` is at or under a bind mount that was registered + * with read_only=true. Used by the fakefs write entry points to reject + * modifications with EROFS. Root bypasses the DAC access_check path, so + * relying on the meta.db 0555 mode bits alone is insufficient — we enforce + * it here instead. */ +static bool is_under_readonly_bind_mount(const char *path) { + char normalized[MAX_PATH]; + const char *cmp_path = path; + if (path[0] != '/') { + snprintf(normalized, sizeof(normalized), "/%s", path); + cmp_path = normalized; + } + for (int i = 0; i < FAKEFS_MAX_BIND_MOUNTS; i++) { + if (!g_bind_mounts[i].active || !g_bind_mounts[i].read_only) + continue; + int len = g_bind_mounts[i].path_len; + if (strncmp(g_bind_mounts[i].path, cmp_path, len) == 0 && + (cmp_path[len] == '/' || cmp_path[len] == '\0')) + return true; + } + return false; +} + +/* Auto-create a meta.db entry for a path under a bind mount. + * Probes the host filesystem to determine if it's a file or directory. */ +static inode_t bind_mount_ensure_inode(struct fakefs_db *fs, struct mount *mount, + const char *path) { + db_begin_read(fs); + inode_t ino = path_get_inode(fs, path); + db_commit(fs); + if (ino != 0) + return ino; + + /* Check if it exists on host — use direct path for bind mounts */ + struct stat host_stat; + char host_abs[PATH_MAX]; + if (bind_mount_translate_path(path, host_abs, sizeof(host_abs))) { + if (stat(host_abs, &host_stat) < 0) + return 0; + } else if (fstatat(mount->root_fd, fix_path(path), &host_stat, AT_SYMLINK_NOFOLLOW) < 0) { + if (fstatat(mount->root_fd, fix_path(path), &host_stat, 0) < 0) + return 0; + } + + uint32_t mode; + if (S_ISDIR(host_stat.st_mode)) + mode = S_IFDIR | 0755; + else if (S_ISLNK(host_stat.st_mode)) + mode = S_IFLNK | 0777; + else + mode = S_IFREG | 0644; + + struct ish_stat ishstat = {.mode = mode, .uid = 0, .gid = 0, .rdev = 0}; + db_begin_write(fs); + ino = path_create(fs, path, &ishstat); + db_commit(fs); + return ino; +} + +// this exists only to override readdir to fix the returned inode numbers +static struct fd_ops fakefs_fdops; + +static struct fd *fakefs_open(struct mount *mount, const char *path, int flags, int mode) { + struct fakefs_db *fs = &mount->fakefs; + + /* Reject any write-intent open under a read-only bind mount. + * iSH processes run as root and bypass the meta.db mode DAC check, + * so the 0555 bits on the mount dir don't actually block anything. */ + if ((flags & (O_WRONLY_ | O_RDWR_ | O_CREAT_ | O_TRUNC_ | O_APPEND_)) && + is_under_readonly_bind_mount(path)) { + return ERR_PTR(_EROFS); + } + + /* For bind-mounted paths, open directly via host absolute path + * instead of relying on symlink traversal (which iOS sandbox may block). */ + char host_abs[PATH_MAX]; + struct fd *fd; + if (bind_mount_translate_path(path, host_abs, sizeof(host_abs))) { + int real_flags = 0; + if (flags & O_RDONLY_) real_flags |= O_RDONLY; + if (flags & O_WRONLY_) real_flags |= O_WRONLY; + if (flags & O_RDWR_) real_flags |= O_RDWR; + if (flags & O_CREAT_) real_flags |= O_CREAT; + if (flags & O_EXCL_) real_flags |= O_EXCL; + if (flags & O_TRUNC_) real_flags |= O_TRUNC; + if (flags & O_APPEND_) real_flags |= O_APPEND; + if (flags & O_NONBLOCK_) real_flags |= O_NONBLOCK; + int fd_no = open(host_abs, real_flags, 0666); + if (fd_no < 0) { + return ERR_PTR(errno_map()); + } + fd = fd_create(&realfs_fdops); + fd->real_fd = fd_no; + fd->dir = NULL; + } else { + fd = realfs.open(mount, path, flags, 0666); + if (IS_ERR(fd)) + return fd; + } + db_begin_write(fs); + fd->fake_inode = path_get_inode(fs, path); + if (flags & O_CREAT_) { + struct ish_stat ishstat; + ishstat.mode = mode | S_IFREG; + ishstat.uid = current->euid; + ishstat.gid = current->egid; + ishstat.rdev = 0; + if (fd->fake_inode == 0) { + path_create(fs, path, &ishstat); + fd->fake_inode = path_get_inode(fs, path); + } + } + db_commit(fs); + if (fd->fake_inode == 0) { + /* Auto-create for bind-mounted paths */ + if (is_under_bind_mount(path)) { + fd->fake_inode = bind_mount_ensure_inode(fs, mount, path); + } + if (fd->fake_inode == 0) { + fd_close(fd); + return ERR_PTR(_ENOENT); + } + } + fd->ops = &fakefs_fdops; + return fd; +} + +// WARNING: giant hack, just for file providerws +struct fd *fakefs_open_inode(struct mount *mount, ino_t inode) { + struct fakefs_db *fs = &mount->fakefs; + db_begin_read(fs); + sqlite3_stmt *stmt = fs->stmt.path_from_inode; + sqlite3_bind_int64(stmt, 1, inode); +step: + if (!db_exec(fs, stmt)) { + db_reset(fs, stmt); + db_rollback(fs); + return ERR_PTR(_ENOENT); + } + const char *path = (const char *) sqlite3_column_text(stmt, 0); + struct fd *fd = realfs.open(mount, path, O_RDWR_, 0); + if (PTR_ERR(fd) == _EISDIR) + fd = realfs.open(mount, path, O_RDONLY_, 0); + if (PTR_ERR(fd) == _ENOENT) + goto step; + db_reset(fs, stmt); + db_commit(fs); + fd->fake_inode = inode; + fd->ops = &fakefs_fdops; + return fd; +} + +static int fakefs_link(struct mount *mount, const char *src, const char *dst) { + struct fakefs_db *fs = &mount->fakefs; + if (is_under_readonly_bind_mount(dst)) + return _EROFS; + db_begin_write(fs); + int err = realfs.link(mount, src, dst); + if (err < 0) { + db_rollback(fs); + return err; + } + path_link(fs, src, dst); + db_commit(fs); + return 0; +} + +static int fakefs_unlink(struct mount *mount, const char *path) { + struct fakefs_db *fs = &mount->fakefs; + if (is_under_readonly_bind_mount(path)) + return _EROFS; + /* Auto-create entry if under bind mount so path_unlink won't die */ + if (is_under_bind_mount(path)) + bind_mount_ensure_inode(fs, mount, path); + db_begin_write(fs); + int err = realfs.unlink(mount, path); + if (err < 0) { + db_rollback(fs); + return err; + } + ino_t ino = path_unlink(fs, path); + db_commit(fs); + inode_check_orphaned(mount, ino); + return 0; +} + +static int fakefs_rmdir(struct mount *mount, const char *path) { + struct fakefs_db *fs = &mount->fakefs; + if (is_under_readonly_bind_mount(path)) + return _EROFS; + /* Auto-create entry if under bind mount so path_unlink won't die */ + if (is_under_bind_mount(path)) + bind_mount_ensure_inode(fs, mount, path); + db_begin_write(fs); + int err = realfs.rmdir(mount, path); + if (err < 0) { + db_rollback(fs); + return err; + } + ino_t ino = path_unlink(fs, path); + db_commit(fs); + inode_check_orphaned(mount, ino); + return 0; +} + +static int fakefs_rename(struct mount *mount, const char *src, const char *dst) { + struct fakefs_db *fs = &mount->fakefs; + if (is_under_readonly_bind_mount(src) || is_under_readonly_bind_mount(dst)) + return _EROFS; + db_begin_write(fs); + path_rename(fs, src, dst); + int err = realfs.rename(mount, src, dst); + if (err < 0) { + db_rollback(fs); + return err; + } + db_commit(fs); + return 0; +} + +static int fakefs_symlink(struct mount *mount, const char *target, const char *link) { + struct fakefs_db *fs = &mount->fakefs; + if (is_under_readonly_bind_mount(link)) + return _EROFS; + db_begin_write(fs); + // create a file containing the target + int fd = openat(mount->root_fd, fix_path(link), O_WRONLY | O_CREAT | O_EXCL, 0666); + if (fd < 0) { + db_rollback(fs); + return errno_map(); + } + ssize_t res = write(fd, target, strlen(target)); + close(fd); + if (res < 0) { + int saved_errno = errno; + unlinkat(mount->root_fd, fix_path(link), 0); + db_rollback(fs); + errno = saved_errno; + return errno_map(); + } + + // customize the stat info so it looks like a link + struct ish_stat ishstat; + ishstat.mode = S_IFLNK | 0777; // symlinks always have full permissions + ishstat.uid = current->euid; + ishstat.gid = current->egid; + ishstat.rdev = 0; + path_create(fs, link, &ishstat); + db_commit(fs); + return 0; +} + +static int fakefs_mknod(struct mount *mount, const char *path, mode_t_ mode, dev_t_ dev) { + struct fakefs_db *fs = &mount->fakefs; + if (is_under_readonly_bind_mount(path)) + return _EROFS; + mode_t_ real_mode = 0666; + if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode)) + real_mode |= S_IFREG; + else + real_mode |= mode & S_IFMT; + int err = realfs.mknod(mount, path, real_mode, 0); + if (err < 0 && err != _EEXIST) { + return err; + } + db_begin_write(fs); + struct ish_stat stat; + stat.mode = mode; + stat.uid = current->euid; + stat.gid = current->egid; + stat.rdev = 0; + if (S_ISBLK(mode) || S_ISCHR(mode)) + stat.rdev = dev; + ino_t inode = path_get_inode(fs, path); + if (inode == 0) { + path_create(fs, path, &stat); + } else { + inode_write_stat(fs, inode, &stat); + } + db_commit(fs); + return 0; +} + +static int fakefs_stat(struct mount *mount, const char *path, struct statbuf *fake_stat) { + struct fakefs_db *fs = &mount->fakefs; + db_begin_read(fs); + struct ish_stat ishstat; + ino_t inode; + if (!path_read_stat(fs, path, &ishstat, &inode)) { + db_rollback(fs); + /* Auto-create for bind-mounted paths */ + if (is_under_bind_mount(path)) { + inode = bind_mount_ensure_inode(fs, mount, path); + if (inode != 0) { + db_begin_read(fs); + path_read_stat(fs, path, &ishstat, &inode); + db_commit(fs); + int err = realfs.stat(mount, path, fake_stat); + if (err < 0) + return err; + fake_stat->inode = inode; + fake_stat->mode = ishstat.mode; + fake_stat->uid = ishstat.uid; + fake_stat->gid = ishstat.gid; + fake_stat->rdev = ishstat.rdev; + return 0; + } + } + return _ENOENT; + } + int err; + char host_stat_path[PATH_MAX]; + if (bind_mount_translate_path(path, host_stat_path, sizeof(host_stat_path))) { + /* For bind-mounted paths, stat the host path directly to avoid + * AT_SYMLINK_NOFOLLOW returning symlink stats instead of dir stats. */ + struct stat real_stat; + if (stat(host_stat_path, &real_stat) < 0) { + db_commit(fs); + return errno_map(); + } + /* Copy basic fields from real stat */ + fake_stat->size = real_stat.st_size; + fake_stat->nlink = real_stat.st_nlink; + fake_stat->atime = platform_stat_atime_sec(&real_stat); + fake_stat->mtime = platform_stat_mtime_sec(&real_stat); + fake_stat->ctime = platform_stat_ctime_sec(&real_stat); + err = 0; + } else { + err = realfs.stat(mount, path, fake_stat); + } + db_commit(fs); + if (err < 0) + return err; + fake_stat->inode = inode; + fake_stat->mode = ishstat.mode; + fake_stat->uid = ishstat.uid; + fake_stat->gid = ishstat.gid; + fake_stat->rdev = ishstat.rdev; + return 0; +} + +static int fakefs_fstat(struct fd *fd, struct statbuf *fake_stat) { + struct fakefs_db *fs = &fd->mount->fakefs; + int err = realfs.fstat(fd, fake_stat); + if (err < 0) + return err; + db_begin_read(fs); + struct ish_stat ishstat; + if (!inode_read_stat_if_exist(fs, fd->fake_inode, &ishstat)) { + db_rollback(fs); + return _ENOENT; + } + db_commit(fs); + fake_stat->inode = fd->fake_inode; + fake_stat->mode = ishstat.mode; + fake_stat->uid = ishstat.uid; + fake_stat->gid = ishstat.gid; + fake_stat->rdev = ishstat.rdev; + return 0; +} + +static void fake_stat_setattr(struct ish_stat *ishstat, struct attr attr) { + switch (attr.type) { + case attr_uid: + ishstat->uid = attr.uid; + break; + case attr_gid: + ishstat->gid = attr.gid; + break; + case attr_mode: + ishstat->mode = (ishstat->mode & S_IFMT) | (attr.mode & ~S_IFMT); + break; + case attr_size: + die("attr_size should be handled by realfs"); + } +} + +static int fakefs_setattr(struct mount *mount, const char *path, struct attr attr) { + struct fakefs_db *fs = &mount->fakefs; + if (is_under_readonly_bind_mount(path)) + return _EROFS; + if (attr.type == attr_size) + return realfs.setattr(mount, path, attr); + db_begin_read(fs); + struct ish_stat ishstat; + ino_t inode; + if (!path_read_stat(fs, path, &ishstat, &inode)) { + db_rollback(fs); + /* Auto-create for bind-mounted paths */ + if (is_under_bind_mount(path)) { + inode = bind_mount_ensure_inode(fs, mount, path); + if (inode != 0) { + db_begin_read(fs); + path_read_stat(fs, path, &ishstat, &inode); + fake_stat_setattr(&ishstat, attr); + inode_write_stat(fs, inode, &ishstat); + db_commit(fs); + return 0; + } + } + return _ENOENT; + } + fake_stat_setattr(&ishstat, attr); + inode_write_stat(fs, inode, &ishstat); + db_commit(fs); + return 0; +} + +static int fakefs_fsetattr(struct fd *fd, struct attr attr) { + struct fakefs_db *fs = &fd->mount->fakefs; + if (attr.type == attr_size) + return realfs.fsetattr(fd, attr); + db_begin_write(fs); + struct ish_stat ishstat; + inode_read_stat_or_die(fs, fd->fake_inode, &ishstat); + fake_stat_setattr(&ishstat, attr); + inode_write_stat(fs, fd->fake_inode, &ishstat); + db_commit(fs); + return 0; +} + +static int fakefs_mkdir(struct mount *mount, const char *path, mode_t_ mode) { + struct fakefs_db *fs = &mount->fakefs; + if (is_under_readonly_bind_mount(path)) + return _EROFS; + db_begin_write(fs); + int err = realfs.mkdir(mount, path, 0777); + if (err < 0) { + db_rollback(fs); + return err; + } + struct ish_stat ishstat; + ishstat.mode = mode | S_IFDIR; + ishstat.uid = current->euid; + ishstat.gid = current->egid; + ishstat.rdev = 0; + path_create(fs, path, &ishstat); + db_commit(fs); + return 0; +} + +static ssize_t file_readlink(struct mount *mount, const char *path, char *buf, size_t bufsize) { + // broken symlinks can't be included in an iOS app or else Xcode craps out + int fd = openat(mount->root_fd, fix_path(path), O_RDONLY); + if (fd < 0) + return errno_map(); + int err = read(fd, buf, bufsize); + close(fd); + if (err < 0) + return errno_map(); + return err; +} + +static ssize_t fakefs_readlink(struct mount *mount, const char *path, char *buf, size_t bufsize) { + struct fakefs_db *fs = &mount->fakefs; + db_begin_read(fs); + struct ish_stat ishstat; + if (!path_read_stat(fs, path, &ishstat, NULL)) { + db_rollback(fs); + return _ENOENT; + } + if (!S_ISLNK(ishstat.mode)) { + db_rollback(fs); + return _EINVAL; + } + ssize_t err = realfs.readlink(mount, path, buf, bufsize); + if (err == _EINVAL) + err = file_readlink(mount, path, buf, bufsize); + db_commit(fs); + return err; +} + +static int fakefs_readdir(struct fd *fd, struct dir_entry *entry) { + assert(fd->ops == &fakefs_fdops); + int res; +retry: + res = realfs_fdops.readdir(fd, entry); + if (res <= 0) + return res; + + // this is annoying + char entry_path[MAX_PATH + 1]; + realfs_getpath(fd, entry_path); + + /* Debug: log readdir for bind-mounted paths */ + if (strstr(entry_path, "minis") != NULL || strstr(entry_path, "Library/MinisChat") != NULL) + fprintf(stderr, "fakefs_readdir: getpath=\"%s\" entry=\"%s\"\n", entry_path, entry->name); + + if (strcmp(entry->name, "..") == 0) { + if (strcmp(entry_path, "") != 0) { + *strrchr(entry_path, '/') = '\0'; + } + } else if (strcmp(entry->name, ".") != 0) { + // god I don't know what to do if this would overflow + strcat(entry_path, "/"); + strcat(entry_path, entry->name); + } + + struct fakefs_db *fs = &fd->mount->fakefs; + db_begin_read(fs); + entry->inode = path_get_inode(fs, entry_path); + db_commit(fs); + + if (entry->inode == 0) { + /* Auto-create for bind-mounted paths */ + if (is_under_bind_mount(entry_path)) { + entry->inode = bind_mount_ensure_inode(fs, fd->mount, entry_path); + } + /* Still no inode? Skip this entry to avoid crashes */ + if (entry->inode == 0) + goto retry; + } + return res; +} + +static struct fd_ops fakefs_fdops; +static void __attribute__((constructor)) init_fake_fdops() { + fakefs_fdops = realfs_fdops; + fakefs_fdops.readdir = fakefs_readdir; +} + +/* ===== Public Bind Mount API ===== */ + +/* Create a relative symlink at root_fd/host_link -> host_path. + * Computes a relative target so openat() can follow the symlink + * without escaping the sandbox (absolute symlinks fail on iOS). */ +static int create_relative_symlink(int root_fd, const char *host_link, + const char *host_path) { + /* Get the absolute path of root_fd via the host FD-path ABI + * (F_GETPATH on Apple platforms, /proc/self/fd on Linux). */ + char root_abs[PATH_MAX]; + if (platform_fd_get_path(root_fd, root_abs, sizeof(root_abs)) < 0) { + fprintf(stderr, "create_relative_symlink: root fd path lookup failed\n"); + /* Fall back to absolute symlink */ + return symlinkat(host_path, root_fd, host_link); + } + + /* Resolve host_path too, so both paths use the same prefix + * (e.g. both /private/var/... instead of mixing /var/... and /private/var/...) */ + char host_real[PATH_MAX]; + if (realpath(host_path, host_real) == NULL) { + fprintf(stderr, "create_relative_symlink: realpath(%s) failed, falling back\n", host_path); + return symlinkat(host_path, root_fd, host_link); + } + + /* Build the absolute path of the symlink's parent directory */ + char link_abs[PATH_MAX]; + snprintf(link_abs, sizeof(link_abs), "%s/%s", root_abs, host_link); + /* Strip the last component to get the parent dir */ + char *last_slash = strrchr(link_abs, '/'); + if (last_slash) *last_slash = '\0'; + + /* Compute relative path from link parent dir to host_path */ + char rel_target[PATH_MAX]; + compute_relative_path(link_abs, host_real, rel_target, sizeof(rel_target)); + + fprintf(stderr, "create_relative_symlink: \"%s\" -> \"%s\" (relative: \"%s\")\n", + host_link, host_path, rel_target); + + return symlinkat(rel_target, root_fd, host_link); +} + +/* Recursively remove a directory tree relative to dir_fd. + * Handles non-empty directories that unlinkat(AT_REMOVEDIR) can't delete. */ +static void remove_tree_at(int dir_fd, const char *path) { + int fd = openat(dir_fd, path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW); + if (fd < 0) { + /* Not a directory or doesn't exist — try plain unlink */ + unlinkat(dir_fd, path, 0); + return; + } + DIR *dir = fdopendir(fd); + if (!dir) { + close(fd); + unlinkat(dir_fd, path, 0); + return; + } + struct dirent *ent; + while ((ent = readdir(dir)) != NULL) { + if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) + continue; + if (ent->d_type == DT_DIR) { + remove_tree_at(dirfd(dir), ent->d_name); + } else { + unlinkat(dirfd(dir), ent->d_name, 0); + } + } + closedir(dir); /* also closes fd */ + unlinkat(dir_fd, path, AT_REMOVEDIR); +} + +int fakefs_bind_mount(const char *linux_path, const char *host_path, bool read_only) { + fprintf(stderr, "fakefs_bind_mount: ENTER linux_path=\"%s\" (len=%zu) host_path=\"%s\" (len=%zu) read_only=%d\n", + linux_path, strlen(linux_path), host_path, strlen(host_path), read_only ? 1 : 0); + + if (g_fakefs_mount == NULL) { + fprintf(stderr, "fakefs_bind_mount: FAIL g_fakefs_mount is NULL\n"); + return _ENODEV; + } + + const char *fixed = fix_path(linux_path); + fprintf(stderr, "fakefs_bind_mount: fix_path(\"%s\") => \"%s\" (len=%zu)\n", + linux_path, fixed, strlen(fixed)); + + /* Log root_fd info for context */ + { + char fd_path[PATH_MAX]; + if (platform_fd_get_path(g_fakefs_mount->root_fd, fd_path, sizeof(fd_path)) == 0) { + fprintf(stderr, "fakefs_bind_mount: root_fd=%d path=\"%s\"\n", + g_fakefs_mount->root_fd, fd_path); + } else { + fprintf(stderr, "fakefs_bind_mount: root_fd=%d (fd path lookup failed)\n", + g_fakefs_mount->root_fd); + } + } + + /* Verify host path exists (directory or regular file) */ + struct stat st; + if (stat(host_path, &st) < 0) { + fprintf(stderr, "fakefs_bind_mount: FAIL host_path does not exist\n"); + return _ENOENT; + } + bool is_file_mount = S_ISREG(st.st_mode); + if (!S_ISDIR(st.st_mode) && !is_file_mount) { + fprintf(stderr, "fakefs_bind_mount: FAIL host_path is neither a dir nor a regular file\n"); + return _ENOENT; + } + + /* Resolve symlinks in host_path so it matches what F_GETPATH returns. + * e.g. ~/Library/GroupContainersAlias/... -> ~/Library/Group Containers/... */ + char resolved_host[PATH_MAX]; + if (realpath(host_path, resolved_host) != NULL) + host_path = resolved_host; + + /* Compute the meta.db mode for the top-level mount point based on whether + * the mount is read-only and whether it's a file or directory. */ + uint32_t dir_mode = read_only ? 0555 : 0755; + uint32_t file_mode = read_only ? 0444 : 0644; + uint32_t top_mode = is_file_mount ? (S_IFREG | file_mode) : (S_IFDIR | dir_mode); + + /* Check if already mounted at this path — update if host_path or mode changed */ + for (int i = 0; i < FAKEFS_MAX_BIND_MOUNTS; i++) { + if (g_bind_mounts[i].active && + strcmp(g_bind_mounts[i].path, linux_path) == 0) { + bool host_changed = strcmp(g_bind_mounts[i].host_path, host_path) != 0; + /* Always refresh the read-only flag — the user may have flipped + * writability in Settings without changing anything else. */ + g_bind_mounts[i].read_only = read_only; + + /* Always refresh the meta.db mode — the read-only flag may have + * flipped even if host_path is unchanged (e.g. user toggled + * writability in Settings). */ + { + struct fakefs_db *fs = &g_fakefs_mount->fakefs; + db_begin_write(fs); + inode_t existing = path_get_inode(fs, linux_path); + if (existing != 0) { + struct ish_stat prev; + if (inode_read_stat_if_exist(fs, existing, &prev)) { + prev.mode = top_mode; + inode_write_stat(fs, existing, &prev); + fprintf(stderr, "fakefs_bind_mount: slot[%d] updated meta.db mode to 0%o\n", + i, top_mode & 07777); + } + } else { + struct ish_stat ishstat = { + .mode = top_mode, .uid = 0, .gid = 0, .rdev = 0 + }; + path_create(fs, linux_path, &ishstat); + fprintf(stderr, "fakefs_bind_mount: slot[%d] created meta.db entry with mode 0%o\n", + i, top_mode & 07777); + } + db_commit(fs); + } + + if (!host_changed) { + fprintf(stderr, "fakefs_bind_mount: slot[%d] already mounted with same host_path, mode refreshed\n", i); + return 0; + } + /* host_path changed (e.g. session switch) — update slot and symlink */ + fprintf(stderr, "fakefs_bind_mount: slot[%d] host_path changed from \"%s\" to \"%s\"\n", + i, g_bind_mounts[i].host_path, host_path); + strlcpy(g_bind_mounts[i].host_path, host_path, + sizeof(g_bind_mounts[i].host_path)); + g_bind_mounts[i].host_path_len = strlen(host_path); + + char host_link[PATH_MAX]; + snprintf(host_link, sizeof(host_link), "%s", fix_path(linux_path)); + fprintf(stderr, "fakefs_bind_mount: slot[%d] UPDATE symlink: host_link=\"%s\" -> host_path=\"%s\" (root_fd=%d)\n", + i, host_link, host_path, g_fakefs_mount->root_fd); + /* Remove whatever is at the path (file, symlink, or directory tree) */ + remove_tree_at(g_fakefs_mount->root_fd, host_link); + int err = create_relative_symlink(g_fakefs_mount->root_fd, host_link, host_path); + fprintf(stderr, "fakefs_bind_mount: slot[%d] symlinkat returned %d (errno=%d)\n", i, err, err < 0 ? errno : 0); + if (err < 0) { + g_bind_mounts[i].active = false; + return _EINVAL; + } + return 0; + } + } + + /* Find a free slot */ + for (int i = 0; i < FAKEFS_MAX_BIND_MOUNTS; i++) { + if (!g_bind_mounts[i].active) { + fprintf(stderr, "fakefs_bind_mount: using free slot[%d]\n", i); + strlcpy(g_bind_mounts[i].path, linux_path, + sizeof(g_bind_mounts[i].path)); + g_bind_mounts[i].path_len = strlen(linux_path); + strlcpy(g_bind_mounts[i].host_path, host_path, + sizeof(g_bind_mounts[i].host_path)); + g_bind_mounts[i].host_path_len = strlen(host_path); + g_bind_mounts[i].active = true; + g_bind_mounts[i].read_only = read_only; + + /* Create symlink on host: data/<linux_path> -> <host_path> + * First remove any existing file/dir at the path (may be non-empty) */ + char host_link[PATH_MAX]; + snprintf(host_link, sizeof(host_link), "%s", fix_path(linux_path)); + + fprintf(stderr, "fakefs_bind_mount: slot[%d] NEW symlink: host_link=\"%s\" -> host_path=\"%s\" (root_fd=%d)\n", + i, host_link, host_path, g_fakefs_mount->root_fd); + + /* Remove whatever is at the path (file, symlink, or directory tree) */ + remove_tree_at(g_fakefs_mount->root_fd, host_link); + + /* Create the symlink (relative path to avoid iOS sandbox issues) */ + int err = create_relative_symlink(g_fakefs_mount->root_fd, host_link, host_path); + fprintf(stderr, "fakefs_bind_mount: slot[%d] symlinkat returned %d (errno=%d)\n", i, err, err < 0 ? errno : 0); + if (err < 0) { + g_bind_mounts[i].active = false; + return _EINVAL; + } + + /* Verify the symlink was created correctly */ + char readbuf[PATH_MAX]; + ssize_t rlen = readlinkat(g_fakefs_mount->root_fd, host_link, readbuf, sizeof(readbuf) - 1); + if (rlen > 0) { + readbuf[rlen] = '\0'; + fprintf(stderr, "fakefs_bind_mount: slot[%d] VERIFY readlinkat(\"%s\") => \"%s\"\n", i, host_link, readbuf); + } else { + fprintf(stderr, "fakefs_bind_mount: slot[%d] VERIFY readlinkat(\"%s\") FAILED (errno=%d)\n", i, host_link, errno); + } + + /* Ensure the mount point exists in meta.db (dir or file), with the + * correct mode based on the read_only flag. If an entry already + * exists from a previous run we rewrite the mode so the read-only + * state always matches what Settings says. */ + struct fakefs_db *fs = &g_fakefs_mount->fakefs; + db_begin_write(fs); + inode_t ino = path_get_inode(fs, linux_path); + if (ino == 0) { + struct ish_stat ishstat = { + .mode = top_mode, .uid = 0, .gid = 0, .rdev = 0 + }; + path_create(fs, linux_path, &ishstat); + fprintf(stderr, "fakefs_bind_mount: slot[%d] created meta.db entry for \"%s\" mode=0%o\n", + i, linux_path, top_mode & 07777); + } else { + struct ish_stat prev; + if (inode_read_stat_if_exist(fs, ino, &prev)) { + prev.mode = top_mode; + inode_write_stat(fs, ino, &prev); + } + fprintf(stderr, "fakefs_bind_mount: slot[%d] meta.db entry refreshed for \"%s\" (inode=%lld) mode=0%o\n", + i, linux_path, (long long)ino, top_mode & 07777); + } + db_commit(fs); + + return 0; + } + } + + fprintf(stderr, "fakefs_bind_mount: FAIL no free slots (max=%d)\n", FAKEFS_MAX_BIND_MOUNTS); + return _ENOMEM; /* no free slots */ +} + +int fakefs_bind_unmount(const char *linux_path) { + if (g_fakefs_mount == NULL) + return _ENODEV; + + for (int i = 0; i < FAKEFS_MAX_BIND_MOUNTS; i++) { + if (g_bind_mounts[i].active && + strcmp(g_bind_mounts[i].path, linux_path) == 0) { + g_bind_mounts[i].active = false; + + /* Remove the symlink */ + char host_link[PATH_MAX]; + snprintf(host_link, sizeof(host_link), "%s", fix_path(linux_path)); + unlinkat(g_fakefs_mount->root_fd, host_link, 0); + + return 0; + } + } + + return _ENOENT; +} + +static int fakefs_mount(struct mount *mount) { + char db_path[PATH_MAX]; + strcpy(db_path, mount->source); + char *basename = strrchr(db_path, '/') + 1; + assert(strcmp(basename, "data") == 0); + strcpy(basename, "meta.db"); + + // do this now so rebuilding can use root_fd + int err = realfs.mount(mount); + if (err < 0) + return err; + + err = fake_db_init(&mount->fakefs, db_path, mount->root_fd); + if (err < 0) + return err; + + /* Store global reference for bind mount API */ + g_fakefs_mount = mount; + memset(g_bind_mounts, 0, sizeof(g_bind_mounts)); + + return 0; +} + +static int fakefs_umount(struct mount *mount) { + int err = fake_db_deinit(&mount->fakefs); + if (err != SQLITE_OK) { + printk("sqlite failed to close: %d\n", err); + } + g_fakefs_mount = NULL; + memset(g_bind_mounts, 0, sizeof(g_bind_mounts)); + close(mount->root_fd); + return 0; +} + +static void fakefs_inode_orphaned(struct mount *mount, ino_t inode) { + struct fakefs_db *fs = &mount->fakefs; + db_begin_write(fs); + sqlite3_bind_int64(fs->stmt.try_cleanup_inode, 1, inode); + db_exec_reset(fs, fs->stmt.try_cleanup_inode); + db_commit(fs); +} + +const struct fs_ops fakefs = { + .name = "fake", .magic = 0x66616b65, + .mount = fakefs_mount, + .umount = fakefs_umount, + .statfs = realfs_statfs, + .open = fakefs_open, + .readlink = fakefs_readlink, + .link = fakefs_link, + .unlink = fakefs_unlink, + .rename = fakefs_rename, + .symlink = fakefs_symlink, + .mknod = fakefs_mknod, + + .close = realfs_close, + .stat = fakefs_stat, + .fstat = fakefs_fstat, + .flock = realfs_flock, + .setattr = fakefs_setattr, + .fsetattr = fakefs_fsetattr, + .getpath = realfs_getpath, + .utime = realfs_utime, + + .mkdir = fakefs_mkdir, + .rmdir = fakefs_rmdir, + + .inode_orphaned = fakefs_inode_orphaned, +}; + +bool fakefs_bind_mount_translate_path(const char *path, char *out_path, size_t out_size) { + return bind_mount_translate_path(path, out_path, out_size); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake.h new file mode 100644 index 0000000000..d74b5a1792 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fake.h @@ -0,0 +1,37 @@ +#ifndef ISH_INTERNAL +#error "for internal use only" +#endif + +#ifndef FS_FAKE_H +#define FS_FAKE_H + +#include <stdbool.h> +#include <stddef.h> +#include "kernel/fs.h" +#include "fs/fake-db.h" +#include "misc.h" + +struct fd *fakefs_open_inode(struct mount *mount, ino_t inode); + +/* Bind mount API — redirect a fakefs path to an external host directory. + * Creates a symlink in data/ and auto-creates meta.db entries on access. + * Can be called from Swift/ObjC after the kernel has booted. + * + * `read_only`: when true, the top-level mount directory's meta.db entry is + * written with mode 0555 (dr-xr-xr-x) instead of 0755, so iSH's generic + * N_PARENT_DIR_WRITE check rejects any create/unlink/rename/rmdir with + * EACCES at the normal access-check layer — no special fakefs plumbing + * required. Existing writable mounts should pass `false`. */ +int fakefs_bind_mount(const char *linux_path, const char *host_path, bool read_only); +int fakefs_bind_unmount(const char *linux_path); + +/* Translate a resolved host path back to a Linux path via bind mount table. + * Returns true and writes to out_path if a match was found. */ +bool fakefs_bind_mount_resolve_path(const char *resolved, char *out_path, size_t out_size); + +/* Translate a Linux (guest) path to its resolved host path via bind mount + * table. Returns true and writes to out_path on a match. Used by native + * offload handlers that execute on the host but receive guest paths. */ +bool fakefs_bind_mount_translate_path(const char *path, char *out_path, size_t out_size); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fd.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fd.c new file mode 100644 index 0000000000..904778a465 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fd.c @@ -0,0 +1,434 @@ +#include <stdlib.h> +#include <string.h> +#include "debug.h" +#include "kernel/calls.h" +#include "kernel/resource.h" +#include "kernel/fs.h" +#include "fs/poll.h" +#include "fs/fd.h" +#include "fs/inode.h" + +struct fd *fd_create(const struct fd_ops *ops) { + struct fd *fd = malloc(sizeof(struct fd)); + if (fd == NULL) + return NULL; + *fd = (struct fd) {}; + fd->ops = ops; + fd->refcount = 1; + fd->flags = 0; + fd->mount = NULL; + fd->offset = 0; + list_init(&fd->poll_fds); + list_init(&fd->pidfd_links); + lock_init(&fd->poll_lock); + lock_init(&fd->lock); + cond_init(&fd->cond); + return fd; +} + +struct fd *fd_retain(struct fd *fd) { + fd->refcount++; + return fd; +} + +int fd_close(struct fd *fd) { + int err = 0; + if (--fd->refcount == 0) { + poll_cleanup_fd(fd); + if (fd->ops->close) + err = fd->ops->close(fd); + // see comment in close in kernel/fs.h + if (fd->mount && fd->mount->fs->close && fd->mount->fs->close != fd->ops->close) { + int new_err = fd->mount->fs->close(fd); + if (new_err < 0) + err = new_err; + } + + if (fd->inode) + inode_release(fd->inode); + if (fd->mount) + mount_release(fd->mount); + free(fd); + } + return err; +} + +static int fdtable_resize(struct fdtable *table, unsigned size); + +struct fdtable *fdtable_new(int size) { + struct fdtable *fdt = malloc(sizeof(struct fdtable)); + if (fdt == NULL) + return ERR_PTR(_ENOMEM); + fdt->refcount = 1; + fdt->size = 0; + fdt->files = NULL; + fdt->cloexec = NULL; + lock_init(&fdt->lock); + int err = fdtable_resize(fdt, size); + if (err < 0) { + free(fdt); + return ERR_PTR(err); + } + return fdt; +} + +static int fdtable_close(struct fdtable *table, fd_t f); + +// FIXME this looks like it has the classic refcount UAF +void fdtable_release(struct fdtable *table) { + lock(&table->lock); + if (--table->refcount == 0) { + for (fd_t f = 0; (unsigned) f < table->size; f++) + fdtable_close(table, f); + free(table->files); + free(table->cloexec); + unlock(&table->lock); + free(table); + } else { + unlock(&table->lock); + } +} + +static int fdtable_resize(struct fdtable *table, unsigned size) { + // currently the only legitimate use of this is to expand the table + assert(size > table->size); + + struct fd **files = malloc(sizeof(struct fd *) * size); + if (files == NULL) + return _ENOMEM; + memset(files, 0, sizeof(struct fd *) * size); + if (table->files) + memcpy(files, table->files, sizeof(struct fd *) * table->size); + + bits_t *cloexec = malloc(BITS_SIZE(size)); + if (cloexec == NULL) { + free(files); + return _ENOMEM; + } + memset(cloexec, 0, BITS_SIZE(size)); + if (table->cloexec) + memcpy(cloexec, table->cloexec, BITS_SIZE(table->size)); + + free(table->files); + table->files = files; + free(table->cloexec); + table->cloexec = cloexec; + table->size = size; + return 0; +} + +struct fdtable *fdtable_copy(struct fdtable *table) { + lock(&table->lock); + int size = table->size; + struct fdtable *new_table = fdtable_new(size); + if (IS_ERR(new_table)) { + unlock(&table->lock); + return new_table; + } + memcpy(new_table->files, table->files, sizeof(struct fd *) * size); + for (fd_t f = 0; f < size; f++) + if (new_table->files[f]) + new_table->files[f]->refcount++; + memcpy(new_table->cloexec, table->cloexec, BITS_SIZE(size)); + unlock(&table->lock); + return new_table; +} + +static int fdtable_expand(struct fdtable *table, fd_t max) { + unsigned size = max + 1; + if (size > rlimit(RLIMIT_NOFILE_)) + return _EMFILE; + if (table->size >= size) + return 0; + return fdtable_resize(table, max + 1); +} + +struct fd *fdtable_get(struct fdtable *table, fd_t f) { + if (f < 0 || (unsigned) f >= current->files->size) + return NULL; + return table->files[f]; +} + +struct fd *f_get(fd_t f) { + lock(¤t->files->lock); + struct fd *fd = fdtable_get(current->files, f); + unlock(¤t->files->lock); + return fd; +} + +static fd_t f_install_start(struct fd *fd, fd_t start) { + assert(start >= 0); + struct fdtable *table = current->files; + unsigned size = rlimit(RLIMIT_NOFILE_); + if (size > table->size) + size = table->size; + + fd_t f; + for (f = start; (unsigned) f < size; f++) + if (table->files[f] == NULL) + break; + if ((unsigned) f >= size) { + int err = fdtable_expand(table, f); + if (err < 0) + f = err; + } + + if (f >= 0) { + table->files[f] = fd; + bit_clear(f, table->cloexec); + } else { + fd_close(fd); + } + return f; +} + +fd_t f_install(struct fd *fd, int flags) { + lock(¤t->files->lock); + fd_t f = f_install_start(fd, 0); + if (f >= 0) { + if (flags & O_CLOEXEC_) + bit_set(f, current->files->cloexec); + if (flags & O_NONBLOCK_) + fd_setflags(fd, O_NONBLOCK_); + } + unlock(¤t->files->lock); + return f; +} + +static int fdtable_close(struct fdtable *table, fd_t f) { + struct fd *fd = fdtable_get(table, f); + if (fd == NULL) + return _EBADF; + if (fd->inode != NULL) // temporary hack for files like sockets that right now don't have inodes but will eventually + file_lock_remove_owned_by(fd, table); + int err = fd_close(fd); + table->files[f] = NULL; + bit_clear(f, table->cloexec); + return err; +} + +int f_close(fd_t f) { + lock(¤t->files->lock); + int err = fdtable_close(current->files, f); + unlock(¤t->files->lock); + return err; +} + +dword_t sys_close(fd_t f) { + STRACE("close(%d)", f); + return f_close(f); +} + +#define CLOSE_RANGE_UNSHARE_ (1u << 1) +#define CLOSE_RANGE_CLOEXEC_ (1u << 2) + +dword_t sys_close_range(uint_t first, uint_t last, uint_t flags) { + STRACE("close_range(%u, %u, %#x)", first, last, flags); + + if (flags & ~(CLOSE_RANGE_UNSHARE_ | CLOSE_RANGE_CLOEXEC_)) + return _EINVAL; + if (first > last) + return _EINVAL; + + struct fdtable *table = current->files; + lock(&table->lock); + + if (table->size == 0) { + unlock(&table->lock); + return 0; + } + + uint_t capped_last = last; + if (capped_last >= table->size) + capped_last = table->size - 1; + if (first >= table->size || first > capped_last) { + unlock(&table->lock); + return 0; + } + + for (uint_t f = first; f <= capped_last; f++) { + if (flags & CLOSE_RANGE_CLOEXEC_) { + if (table->files[f] != NULL) + bit_set(f, table->cloexec); + continue; + } + if (table->files[f] != NULL) + fdtable_close(table, (fd_t)f); + } + + unlock(&table->lock); + return 0; +} + +void fdtable_do_cloexec(struct fdtable *table) { + lock(&table->lock); + for (fd_t f = 0; (unsigned) f < table->size; f++) + if (bit_test(f, table->cloexec)) + fdtable_close(table, f); + unlock(&table->lock); +} + +#define F_DUPFD_ 0 +#define F_GETFD_ 1 +#define F_SETFD_ 2 +#define F_GETFL_ 3 +#define F_SETFL_ 4 + +#define F_GETLK_ 5 +#define F_SETLK_ 6 +#define F_SETLKW_ 7 +#define F_GETLK64_ 12 +#define F_SETLK64_ 13 +#define F_SETLKW64_ 14 + +#define F_DUPFD_CLOEXEC_ 1030 + +dword_t sys_dup(fd_t f) { + STRACE("dup(%d)", f); + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + fd->refcount++; + return f_install(fd, 0); +} + +dword_t sys_dup3(fd_t f, fd_t new_f, int_t flags) { + STRACE("dup3(%d, %d, %d)", f, new_f, flags); + struct fdtable *table = current->files; + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + int err = fdtable_expand(table, new_f); + if (err < 0) + return err; + fd_retain(fd); + f_close(new_f); + table->files[new_f] = fd; + if (flags & O_CLOEXEC_) + bit_set(new_f, table->cloexec); + return new_f; +} + +dword_t sys_dup2(fd_t f, fd_t new_f) { + return sys_dup3(f, new_f, 0); +} + +int fd_getflags(struct fd *fd) { + if (fd->ops->getflags) + return fd->ops->getflags(fd); + return fd->flags; +} + +#define FD_ALLOWED_FLAGS (O_APPEND_ | O_NONBLOCK_) +int fd_setflags(struct fd *fd, int flags) { + if (fd->ops->setflags) + return fd->ops->setflags(fd, flags); + fd->flags = (fd->flags & ~FD_ALLOWED_FLAGS) | (flags & FD_ALLOWED_FLAGS); + return 0; +} + +dword_t sys_fcntl(fd_t f, dword_t cmd, addr_t arg) { + struct fdtable *table = current->files; + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + struct flock32_ flock32; + struct flock_ flock; + fd_t new_f; + int err; + switch (cmd) { + case F_DUPFD_: + STRACE("fcntl(%d, F_DUPFD, %d)", f, arg); + fd->refcount++; + return f_install_start(fd, arg); + + case F_DUPFD_CLOEXEC_: + STRACE("fcntl(%d, F_DUPFD_CLOEXEC, %d)", f, arg); + fd->refcount++; + new_f = f_install_start(fd, arg); + bit_set(new_f, table->cloexec); + return new_f; + + case F_GETFD_: + STRACE("fcntl(%d, F_GETFD)", f); + return bit_test(f, table->cloexec); + case F_SETFD_: + STRACE("fcntl(%d, F_SETFD, 0x%x)", f, arg); + if (arg & 1) + bit_set(f, table->cloexec); + else + bit_clear(f, table->cloexec); + return 0; + + case F_GETFL_: + STRACE("fcntl(%d, F_GETFL)", f); + return fd_getflags(fd); + case F_SETFL_: + STRACE("fcntl(%d, F_SETFL, %#x)", f, arg); + return fd_setflags(fd, arg); + + case F_GETLK_: + STRACE("fcntl(%d, F_GETLK, %#x)", f, arg); + if (user_read(arg, &flock32, sizeof(flock32))) + return _EFAULT; + flock.type = flock32.type; + flock.whence = flock32.whence; + flock.start = flock32.start; + flock.len = flock32.len; + flock.pid = flock32.pid; + err = fcntl_getlk(fd, &flock); + if (err >= 0) { + flock32.type = flock.type; + flock32.whence = flock.whence; + flock32.start = flock.start; + flock32.len = flock.len; + flock32.pid = flock.pid; + if (user_write(arg, &flock32, sizeof(flock32))) + return _EFAULT; + } + return err; + + case F_GETLK64_: + STRACE("fcntl(%d, F_GETLK64, %#x)", f, arg); + if (user_read(arg, &flock, sizeof(flock))) + return _EFAULT; + err = fcntl_getlk(fd, &flock); + if (err >= 0) + if (user_write(arg, &flock, sizeof(flock))) + return _EFAULT; + return err; + + case F_SETLK_: + case F_SETLKW_: + STRACE("fcntl(%d, F_SETLK%*s, %#x)", f, cmd == F_SETLKW_, "W", arg); + if (user_read(arg, &flock32, sizeof(flock32))) + return _EFAULT; + flock.type = flock32.type; + flock.whence = flock32.whence; + flock.start = flock32.start; + flock.len = flock32.len; + flock.pid = flock32.pid; + return fcntl_setlk(fd, &flock, cmd == F_SETLKW64_); + + case F_SETLK64_: + case F_SETLKW64_: + STRACE("fcntl(%d, F_SETLK%*s64, %#x)", f, cmd == F_SETLKW_, "W", arg); + if (user_read(arg, &flock, sizeof(flock))) + return _EFAULT; + return fcntl_setlk(fd, &flock, cmd == F_SETLKW_); + + default: + STRACE("fcntl(%d, %d)", f, cmd); + return _EINVAL; + } +} + +dword_t sys_fcntl32(fd_t fd, dword_t cmd, addr_t arg) { + switch (cmd) { + case F_GETLK64_: + case F_SETLK64_: + case F_SETLKW64_: + return _EINVAL; + } + return sys_fcntl(fd, cmd, arg); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fd.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fd.h new file mode 100644 index 0000000000..7699577104 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fd.h @@ -0,0 +1,216 @@ +#ifndef FD_H +#define FD_H +#include <dirent.h> +#include <sys/stat.h> +#include "kernel/memory.h" +#include "util/list.h" +#include "util/sync.h" +#include "util/bits.h" +#include "fs/stat.h" +#include "fs/proc.h" +#include "fs/sockrestart.h" + +// FIXME almost everything that uses the structs in this file does so without any kind of sane locking + +struct fd { + atomic_uint refcount; + unsigned flags; + mode_t_ type; // just the S_IFMT part, it can't change + const struct fd_ops *ops; + struct list poll_fds; + lock_t poll_lock; + unsigned long offset; + // Links this fd into the global pidfd registry (pidfd_open only). + struct list pidfd_links; + + // fd data + union { + // pidfd (pidfd_open): references a process by pid + struct { + pid_t_ pid; + // Set true by pidfd_notify_exit when `pid` becomes a zombie. Read + // lock-free by pidfd_poll so polling never takes pids_lock (which + // would create a poll->lock <-> pids_lock ABBA against the exit + // path that wakes pidfd pollers while holding pids_lock). + _Atomic bool exited; + } pidfd; + // tty + struct { + struct tty *tty; + // links together fds pointing to the same tty + // locked by the tty + struct list tty_other_fds; + }; + struct { + struct poll *poll; + } epollfd; + struct { + uint64_t val; + } eventfd; + struct { + struct timer *timer; + uint64_t expirations; + } timerfd; + struct { + int domain; + int type; + int protocol; + + // These are only used as strong references, to keep the inode + // alive while there is a listener. + struct inode_data *unix_name_inode; + struct unix_abstract *unix_name_abstract; + uint8_t unix_name_len; + char unix_name[108]; + struct fd *unix_peer; // locked by peer_lock, for simplicity + cond_t unix_got_peer; + // Queue of struct scm for sending file descriptors + // locked by fd->lock + struct list unix_scm; + struct ucred_ { + pid_t_ pid; + uid_t_ uid; + uid_t_ gid; + } unix_cred; + } socket; + + // See app/Pasteboard.m + struct { + // UIPasteboard.changeCount + uint64_t generation; + // Buffer for written data + void* buffer; + // its capacity + size_t buffer_cap; + // length of actual data stored in the buffer + size_t buffer_len; + } clipboard; + + // can fit anything in here + void *data; + }; + // fs data + union { + struct { + struct proc_entry entry; + unsigned dir_index; + struct proc_data data; + } proc; + struct { + int num; + } devpts; + struct { + struct tmp_dirent *dirent; + struct tmp_dirent *dir_pos; + } tmpfs; + void *fs_data; + }; + + // fs/inode data + struct mount *mount; + int real_fd; // seeks on this fd require the lock TODO think about making a special lock just for that + DIR *dir; + struct inode_data *inode; + ino_t fake_inode; + struct statbuf stat; // for adhoc fs + struct fd_sockrestart sockrestart; // argh + + // these are used for a variety of things related to the fd + lock_t lock; + cond_t cond; +}; + +typedef sdword_t fd_t; +#define AT_FDCWD_ -100 + +struct fd *fd_create(const struct fd_ops *ops); +struct fd *fd_retain(struct fd *fd); +int fd_close(struct fd *fd); + +int fd_getflags(struct fd *fd); +int fd_setflags(struct fd *fd, int flags); + +#define NAME_MAX 255 +struct dir_entry { + qword_t inode; + byte_t type; // Linux DT_* dirent type, or DT_UNKNOWN when unavailable + char name[NAME_MAX + 1]; +}; + +static inline byte_t dirent_type_from_mode(mode_t_ mode) { + if (S_ISREG(mode)) return DT_REG; + if (S_ISDIR(mode)) return DT_DIR; + if (S_ISLNK(mode)) return DT_LNK; + if (S_ISCHR(mode)) return DT_CHR; + if (S_ISBLK(mode)) return DT_BLK; + if (S_ISFIFO(mode)) return DT_FIFO; + if (S_ISSOCK(mode)) return DT_SOCK; + return DT_UNKNOWN; +} + +#define LSEEK_SET 0 +#define LSEEK_CUR 1 +#define LSEEK_END 2 + +struct fd_ops { + // required for files + // TODO make optional for non-files + ssize_t (*read)(struct fd *fd, void *buf, size_t bufsize); + ssize_t (*write)(struct fd *fd, const void *buf, size_t bufsize); + ssize_t (*pread)(struct fd *fd, void *buf, size_t bufsize, off_t off); + ssize_t (*pwrite)(struct fd *fd, const void *buf, size_t bufsize, off_t off); + off_t_ (*lseek)(struct fd *fd, off_t_ off, int whence); + + // Reads a directory entry from the stream + // required for directories + int (*readdir)(struct fd *fd, struct dir_entry *entry); + // Return an opaque value representing the current point in the directory stream + // optional, fd->offset will be used instead + unsigned long (*telldir)(struct fd *fd); + // Seek to the location represented by a pointer returned from telldir + // optional, fd->offset will be used instead + void (*seekdir)(struct fd *fd, unsigned long ptr); + + // map the file + int (*mmap)(struct fd *fd, struct mem *mem, page_t start, pages_t pages, off_t offset, int prot, int flags); + + // returns a bitmask of operations that won't block + int (*poll)(struct fd *fd); + + // returns the size needed for the output of ioctl, 0 if the arg is not a + // pointer, -1 for invalid command + ssize_t (*ioctl_size)(int cmd); + // if ioctl_size returns non-zero, arg must point to ioctl_size valid bytes + int (*ioctl)(struct fd *fd, int cmd, void *arg); + + int (*fsync)(struct fd *fd); + int (*close)(struct fd *fd); + + // handle F_GETFL, i.e. return open flags for this fd + int (*getflags)(struct fd *fd); + // handle F_SETFL, i.e. set O_NONBLOCK + int (*setflags)(struct fd *fd, dword_t arg); +}; + +struct fdtable { + atomic_uint refcount; + unsigned size; + struct fd **files; + bits_t *cloexec; + lock_t lock; +}; + +struct fdtable *fdtable_new(int size); +void fdtable_release(struct fdtable *table); +struct fdtable *fdtable_copy(struct fdtable *table); +void fdtable_free(struct fdtable *table); +void fdtable_do_cloexec(struct fdtable *table); +struct fd *fdtable_get(struct fdtable *table, fd_t f); + +struct fd *f_get(fd_t f); +// steals a reference to the fd, gives it to the table on success and destroys it on error +// flags is checked for O_CLOEXEC and O_NONBLOCK +fd_t f_install(struct fd *fd, int flags); +int f_close(fd_t f); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fix_path.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fix_path.h new file mode 100644 index 0000000000..e90b0c8a9f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/fix_path.h @@ -0,0 +1,12 @@ +#ifndef FS_FIX_PATH_H +#define FS_FIX_PATH_H + +static inline const char *fix_path(const char *path) { + if (path[0] == '\0') + return "."; + if (path[0] == '/') + path++; + return path; +} + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/generic.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/generic.c new file mode 100644 index 0000000000..eb95682fad --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/generic.c @@ -0,0 +1,323 @@ +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> + +#include "kernel/fs.h" +#include "fs/fd.h" +#include "fs/inode.h" +#include "fs/path.h" +#include "fs/dev.h" +#include "kernel/task.h" +#include "kernel/errno.h" + +struct mount *find_mount_and_trim_path(char *path) { + struct mount *mount = mount_find(path); + char *dst = path; + const char *src = path + strlen(mount->point); + while (*src != '\0') + *dst++ = *src++; + *dst = '\0'; + return mount; +} + +bool contains_mount_point(const char *path) { + struct mount *mount; + list_for_each_entry(&mounts, mount, mounts) { + int n = strlen(path); + if (strncmp(path, mount->point, n) == 0 && + (mount->point[n] == '\0' || mount->point[n] == '/')) + return true; + } + return false; +} + +struct fd *generic_openat(struct fd *at, const char *path_raw, int flags, int mode) { + if (flags & O_RDWR_ && flags & O_WRONLY_) + return ERR_PTR(_EINVAL); + + // TODO really, really, seriously reconsider what I'm doing with the strings + char path[MAX_PATH]; + int err = path_normalize(at, path_raw, path, N_SYMLINK_FOLLOW | + (flags & O_CREAT_ ? N_PARENT_DIR_WRITE : 0)); + if (err < 0) + return ERR_PTR(err); + struct mount *mount = find_mount_and_trim_path(path); + struct fd *fd = mount->fs->open(mount, path, flags, mode); + if (IS_ERR(fd)) { + // if an error happens after this point, fd_close will release the + // mount, but right now we need to do it manually + mount_release(mount); + return fd; + } + fd->mount = mount; + + lock(&inodes_lock); // TODO: don't do this + struct statbuf stat; + err = fd->mount->fs->fstat(fd, &stat); + if (err < 0) { + unlock(&inodes_lock); + goto error; + } + fd->inode = inode_get_unlocked(mount, stat.inode); + if (fd->inode == NULL) { + unlock(&inodes_lock); + err = _ENOMEM; + goto error; + } + unlock(&inodes_lock); + fd->type = stat.mode & S_IFMT; + fd->flags = flags; + + int accmode; + if (flags & O_RDWR_) accmode = AC_R | AC_W; + else if (flags & O_WRONLY_) accmode = AC_W; + else accmode = AC_R; + err = access_check(&stat, accmode); + if (err < 0) + goto error; + + if (S_ISLNK(fd->type)) { + // path_normalize should have resolved symlinks, but if it didn't, + // return an error instead of crashing the whole app. + err = _ELOOP; + goto error; + } + if (S_ISBLK(fd->type) || S_ISCHR(fd->type)) { + int type; + if (S_ISBLK(fd->type)) + type = DEV_BLOCK; + else + type = DEV_CHAR; + err = dev_open(dev_major(stat.rdev), dev_minor(stat.rdev), type, fd); + if (err < 0) + goto error; + } + err = _ENXIO; + if (S_ISSOCK(fd->type)) + goto error; + err = _EISDIR; + if (S_ISDIR(fd->type) && flags & (O_RDWR_ | O_WRONLY_)) + goto error; + err = _ENOTDIR; + if (!S_ISDIR(fd->type) && flags & O_DIRECTORY_) + goto error; + return fd; + +error: + fd_close(fd); + return ERR_PTR(err); +} + +struct fd *generic_open(const char *path, int flags, int mode) { + return generic_openat(AT_PWD, path, flags, mode); +} + +int generic_getpath(struct fd *fd, char *buf) { + int err = fd->mount->fs->getpath(fd, buf); + if (err < 0) + return err; + if (strlen(buf) + strlen(fd->mount->point) >= MAX_PATH) + return _ENAMETOOLONG; + memmove(buf + strlen(fd->mount->point), buf, strlen(buf) + 1); + memcpy(buf, fd->mount->point, strlen(fd->mount->point)); + if (buf[0] == '\0') + strcpy(buf, "/"); + return 0; +} + +int generic_accessat(struct fd *dirfd, const char *path_raw, int mode) { + char path[MAX_PATH]; + int err = path_normalize(dirfd, path_raw, path, N_SYMLINK_FOLLOW); + if (err < 0) + return err; + + struct mount *mount = find_mount_and_trim_path(path); + struct statbuf stat = {}; + err = mount->fs->stat(mount, path, &stat); + mount_release(mount); + if (err < 0) + return err; + return access_check(&stat, mode); +} + +int generic_linkat(struct fd *src_at, const char *src_raw, struct fd *dst_at, const char *dst_raw) { + char src[MAX_PATH]; + int err = path_normalize(src_at, src_raw, src, N_SYMLINK_NOFOLLOW); + if (err < 0) + return err; + char dst[MAX_PATH]; + err = path_normalize(dst_at, dst_raw, dst, N_SYMLINK_NOFOLLOW | N_PARENT_DIR_WRITE); + if (err < 0) + return err; + struct mount *mount = find_mount_and_trim_path(src); + struct mount *dst_mount = find_mount_and_trim_path(dst); + if (mount != dst_mount) + err = _EXDEV; + else if (mount->fs->link == NULL) + err = _EPERM; + else + err = mount->fs->link(mount, src, dst); + mount_release(mount); + mount_release(dst_mount); + return err; +} + +int generic_unlinkat(struct fd *at, const char *path_raw) { + char path[MAX_PATH]; + /* Include N_PARENT_DIR_WRITE so path_normalize checks write permission + * on the parent directory. This makes read-only bind mounts (whose + * top-level directory is mode 0555 in meta.db) reject `rm` with EACCES + * without needing any special case in fakefs. */ + int err = path_normalize(at, path_raw, path, N_SYMLINK_NOFOLLOW | N_PARENT_DIR_WRITE); + if (err < 0) + return err; + struct mount *mount = find_mount_and_trim_path(path); + err = _EPERM; + if (mount->fs->unlink) + err = mount->fs->unlink(mount, path); + mount_release(mount); + return err; +} + +int generic_renameat(struct fd *src_at, const char *src_raw, struct fd *dst_at, const char *dst_raw) { + char src[MAX_PATH]; + /* Rename removes the src from its parent directory, so we also need + * write permission on src's parent — not just dst's. */ + int err = path_normalize(src_at, src_raw, src, N_SYMLINK_NOFOLLOW | N_PARENT_DIR_WRITE); + if (err < 0) + return err; + char dst[MAX_PATH]; + err = path_normalize(dst_at, dst_raw, dst, N_SYMLINK_NOFOLLOW | N_PARENT_DIR_WRITE); + if (err < 0) + return err; + if (contains_mount_point(src)) + return _EBUSY; + struct mount *mount = find_mount_and_trim_path(src); + struct mount *dst_mount = find_mount_and_trim_path(dst); + if (mount != dst_mount) + err = _EXDEV; + else if (mount->fs->rename == NULL) + err = _EPERM; + else + err = mount->fs->rename(mount, src, dst); + mount_release(mount); + mount_release(dst_mount); + return err; +} + +int generic_symlinkat(const char *target, struct fd *at, const char *link_raw) { + char link[MAX_PATH]; + int err = path_normalize(at, link_raw, link, N_SYMLINK_NOFOLLOW | N_PARENT_DIR_WRITE); + if (err < 0) + return err; + struct mount *mount = find_mount_and_trim_path(link); + err = _EPERM; + if (mount->fs->symlink) + err = mount->fs->symlink(mount, target, link); + mount_release(mount); + return err; +} + +int generic_mknodat(struct fd *at, const char *path_raw, mode_t_ mode, dev_t_ dev) { + if (S_ISDIR(mode) || S_ISLNK(mode)) + return _EINVAL; + if (!superuser() && (S_ISBLK(mode) || S_ISCHR(mode))) + return _EPERM; + + char path[MAX_PATH]; + int err = path_normalize(at, path_raw, path, N_SYMLINK_NOFOLLOW | N_PARENT_DIR_WRITE); + if (err < 0) + return err; + struct mount *mount = find_mount_and_trim_path(path); + err = _EPERM; + if (mount->fs->mknod) + err = mount->fs->mknod(mount, path, mode, dev); + mount_release(mount); + return err; +} + +int generic_setattrat(struct fd *at, const char *path_raw, struct attr attr, bool follow_links) { + char path[MAX_PATH]; + int err = path_normalize(at, path_raw, path, follow_links ? N_SYMLINK_FOLLOW : N_SYMLINK_NOFOLLOW); + if (err < 0) + return err; + struct mount *mount = find_mount_and_trim_path(path); + err = _EPERM; + if (mount->fs->setattr) + err = mount->fs->setattr(mount, path, attr); + mount_release(mount); + return err; +} + +int generic_utime(struct fd *at, const char *path_raw, struct timespec atime, struct timespec mtime, bool follow_links) { + char path[MAX_PATH]; + int err = path_normalize(at, path_raw, path, follow_links ? N_SYMLINK_FOLLOW : N_SYMLINK_NOFOLLOW); + if (err < 0) + return err; + struct mount *mount = find_mount_and_trim_path(path); + err = _EPERM; + if (mount->fs->utime) + err = mount->fs->utime(mount, path, atime, mtime); + mount_release(mount); + return err; +} + +ssize_t generic_readlinkat(struct fd *at, const char *path_raw, char *buf, size_t bufsize) { + char path[MAX_PATH]; + int err = path_normalize(at, path_raw, path, N_SYMLINK_NOFOLLOW); + if (err < 0) + return err; + struct mount *mount = find_mount_and_trim_path(path); + err = _EINVAL; + if (mount->fs->readlink) + err = mount->fs->readlink(mount, path, buf, bufsize); + mount_release(mount); + return err; +} + +int generic_mkdirat(struct fd *at, const char *path_raw, mode_t_ mode) { + char path[MAX_PATH]; + int err = path_normalize(at, path_raw, path, N_SYMLINK_FOLLOW | N_PARENT_DIR_WRITE); + if (err < 0) + return err; + struct mount *mount = find_mount_and_trim_path(path); + err = _EPERM; + if (mount->fs->mkdir) + err = mount->fs->mkdir(mount, path, mode); + mount_release(mount); + return err; +} + +int generic_rmdirat(struct fd *at, const char *path_raw) { + char path[MAX_PATH]; + int err = path_normalize(at, path_raw, path, N_SYMLINK_FOLLOW | N_PARENT_DIR_WRITE); + if (err < 0) + return err; + if (contains_mount_point(path)) + return _EBUSY; + struct mount *mount = find_mount_and_trim_path(path); + err = _EPERM; + if (mount->fs->rmdir) + err = mount->fs->rmdir(mount, path); + mount_release(mount); + return err; +} + +int generic_seek(struct fd *fd, off_t_ off, int whence, size_t size) { + off_t_ new_off = fd->offset; + if (whence == LSEEK_SET) { + fd->offset = off; + } else if (whence == LSEEK_CUR) { + if (__builtin_add_overflow(new_off, off, &new_off) || new_off < 0) + return _EINVAL; + fd->offset = new_off; + } else if (whence == LSEEK_END) { + new_off = size + off; + if (new_off < 0) + return _EINVAL; + fd->offset = new_off; + } else { + return _EINVAL; + } + return 0; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/inode.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/inode.c new file mode 100644 index 0000000000..9eb80e7d43 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/inode.c @@ -0,0 +1,83 @@ +#include <stdlib.h> +#include "util/list.h" +#include "kernel/fs.h" +#include "fs/inode.h" +#include "debug.h" + +lock_t inodes_lock = LOCK_INITIALIZER; +#define INODES_HASH_SIZE (1 << 10) +static struct list inodes_hash[INODES_HASH_SIZE]; + +int current_pid(void); + +static struct inode_data *inode_get_data(struct mount *mount, ino_t ino) { + int index = ino % INODES_HASH_SIZE; + if (list_null(&inodes_hash[index])) + list_init(&inodes_hash[index]); + struct inode_data *inode; + list_for_each_entry(&inodes_hash[index], inode, chain) { + if (inode->mount == mount && inode->number == ino) + return inode; + } + return NULL; +} + +struct inode_data *inode_get_unlocked(struct mount *mount, ino_t ino) { + struct inode_data *inode = inode_get_data(mount, ino); + if (inode == NULL) { + inode = malloc(sizeof(struct inode_data)); + if (inode == NULL) + return NULL; + inode->refcount = 0; + inode->number = ino; + mount_retain(mount); + inode->mount = mount; + inode->socket_id = 0; + cond_init(&inode->posix_unlock); + list_init(&inode->posix_locks); + list_init(&inode->chain); + lock_init(&inode->lock); + list_add(&inodes_hash[ino % INODES_HASH_SIZE], &inode->chain); + } + + inode_retain(inode); + return inode; +} + +struct inode_data *inode_get(struct mount *mount, ino_t ino) { + lock(&inodes_lock); + struct inode_data *data = inode_get_unlocked(mount, ino); + unlock(&inodes_lock); + return data; +} + +void inode_check_orphaned(struct mount *mount, ino_t ino) { + lock(&inodes_lock); + struct inode_data *inode = inode_get_data(mount, ino); + if (inode == NULL) + mount->fs->inode_orphaned(mount, ino); + unlock(&inodes_lock); +} + +void inode_retain(struct inode_data *inode) { + lock(&inode->lock); + inode->refcount++; + unlock(&inode->lock); +} + +void inode_release(struct inode_data *inode) { + lock(&inodes_lock); + lock(&inode->lock); + if (--inode->refcount == 0) { + unlock(&inode->lock); + list_remove(&inode->chain); + if (inode->mount->fs->inode_orphaned) + inode->mount->fs->inode_orphaned(inode->mount, inode->number); + unlock(&inodes_lock); + mount_release(inode->mount); + free(inode); + } else { + unlock(&inode->lock); + unlock(&inodes_lock); + } +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/inode.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/inode.h new file mode 100644 index 0000000000..0d6dea9ca3 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/inode.h @@ -0,0 +1,78 @@ +#ifndef FS_INODE_H +#define FS_INODE_H +#include <sys/types.h> +#include "misc.h" +#include "util/list.h" +#include "util/sync.h" +struct mount; +struct fd; + +struct inode_data { + unsigned refcount; + ino_t number; + struct mount *mount; + struct list chain; + + struct list posix_locks; + cond_t posix_unlock; + + uint32_t socket_id; + + lock_t lock; +}; + +struct inode_data *inode_get(struct mount *mount, ino_t inode); +void inode_retain(struct inode_data *inode); +void inode_release(struct inode_data *inode); + +// generic_open must lock out anything trying to destroy an inode between +// opening the file and acquiring a reference to its inode. For this purpose +// only, the inodes_lock and inode_get_unlocked are made available. Think +// carefully before using them for anything else. +// mount->lock nests inside this. +// To quote @dril: i despise this lock. id love nothing more than to kick it +// through the wall and shatter it into 100 deadlocks. But i need it +extern lock_t inodes_lock; +struct inode_data *inode_get_unlocked(struct mount *mount, ino_t inode); + +// calls mount->fs->inode_orphaned if this inode is orphaned, while holding indoes_lock +void inode_check_orphaned(struct mount *mount, ino_t ino); + +// file locking stuff (maybe should go in kernel/calls.h?) + +#define F_RDLCK_ 0 +#define F_WRLCK_ 1 +#define F_UNLCK_ 2 + +struct file_lock { + off_t_ start; + off_t_ end; + int type; + pid_t_ pid; + void *owner; + struct list locks; +}; + +struct flock_ { + word_t type; + word_t whence; + off_t_ start; + off_t_ len; + pid_t_ pid; +} __attribute__((packed)); +struct flock32_ { + word_t type; + word_t whence; + dword_t start; + dword_t len; + pid_t_ pid; +} __attribute__((packed)); + +int fcntl_getlk(struct fd *fd, struct flock_ *flock); +// cmd should be either F_SETLK or F_SETLKW +int fcntl_setlk(struct fd *fd, struct flock_ *flock, bool block); + +// locks the inode internally +void file_lock_remove_owned_by(struct fd *fd, void *owner); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/lock.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/lock.c new file mode 100644 index 0000000000..f247a06d88 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/lock.c @@ -0,0 +1,254 @@ +#include <limits.h> +#include "kernel/calls.h" +#include "kernel/fs.h" +#include "fs/inode.h" + +static bool file_locks_overlap(struct file_lock *a, struct file_lock *b) { + return a->end >= b->start && b->end >= a->start; +} + +static bool file_locks_conflict(struct file_lock *a, struct file_lock *b) { + if (a->owner == b->owner) + return false; + if (!file_locks_overlap(a, b)) + return false; + // write locks are incompatible with other types of locks + if (a->type == F_WRLCK_ || b->type == F_WRLCK_) + return true; + return false; +} + +static bool file_locks_adjacent(struct file_lock *a, struct file_lock *b) { + return a->end == b->start - 1 || b->end == a->start - 1; +} + +static struct file_lock *file_lock_test(struct inode_data *inode, struct file_lock *request) { + struct file_lock *lock; + list_for_each_entry(&inode->posix_locks, lock, locks) { + if (file_locks_conflict(lock, request)) + return lock; + } + return NULL; +} + +static struct file_lock *file_lock_copy(struct file_lock *request) { + struct file_lock *lock = malloc(sizeof(struct file_lock)); + lock->start = request->start; + lock->end = request->end; + lock->type = request->type; + lock->owner = request->owner; + lock->pid = request->pid; + list_init(&lock->locks); + return lock; +} + +static void file_lock_delete(struct file_lock *lock) { + list_remove(&lock->locks); + free(lock); +} + +static int file_lock_acquire(struct inode_data *inode, struct file_lock *request) { + struct file_lock *lock; + + if (request->type != F_UNLCK_) { + list_for_each_entry(&inode->posix_locks, lock, locks) { + if (file_locks_conflict(lock, request)) + return _EAGAIN; + // TODO check for deadlocks + } + } + + // If the loop above succeeded, the lock can be placed. Now we just need to + // add it into our existing set of locks. This is complicated because it + // might need to: + // - merge with an adjacent or overlapping lock of the same type + // - override an existing overlapping lock of a different type + // - split an existing lock into two, if it overlaps just the middle + // - do any or all of the above at the same time + + bool found_our_locks = false; + struct file_lock *tmp; + list_for_each_entry_safe(&inode->posix_locks, lock, tmp, locks) { + // To speed up looping over all of our locks, the locks are grouped by owner. + if (!found_our_locks) { + if (lock->owner != request->owner) + continue; + found_our_locks = true; + } else { + if (lock->owner != request->owner) + break; + } + assert(lock->owner == request->owner); + + if (request->type == lock->type) { + if (!file_locks_overlap(lock, request) && !file_locks_adjacent(request, lock)) + continue; + // merge request with lock + // extend request until it covers lock, then delete lock + if (lock->start < request->start) + request->start = lock->start; + if (lock->end > request->end) + request->end = lock->end; + file_lock_delete(lock); + } else { + if (!file_locks_overlap(lock, request)) + continue; + // request must subtract from the lock + // the main thing to worry about here is if the lock is larger than + // the request on both ends, in which case it needs to be split + // into two locks + // + // test cases to think about: request on the top, lock on the bottom + // ..::'' ''::.. ..::.. ''::'' :::... ...::: '''::: :::''' :::::: + + // every case here has the possibility of reducing the locking on some region + notify(&inode->posix_unlock); + + if (request->start > lock->start && request->end < lock->end) { + // lock sticks out on both ends, split + struct file_lock *lock2 = file_lock_copy(lock); + // see below for why these can't overflow + lock->end = request->start - 1; + lock2->start = request->end + 1; + list_add_after(&lock->locks, &lock2->locks); + } else if (request->start <= lock->start && request->end >= lock->end) { + // lock doesn't stick out at all, so just remove it + file_lock_delete(lock); + } else if (lock->start < request->start) { + // lock sticks out on the start, so move the end down + assert(lock->end >= request->start); + // subtract can't overflow since the comparison above would fail if request->start is 0 + lock->end = request->start - 1; + } else if (lock->end > request->end) { + // lock sticks out on the end, so move the start up + assert(lock->start <= request->end); + // add can't overflow since the comparison above would fail if request->start is OFF_T_MAX + lock->start = request->end + 1; + } + } + } + + if (request->type != F_UNLCK_) { + struct file_lock *new_lock = file_lock_copy(request); + list_add_before(&lock->locks, &new_lock->locks); + } + return 0; +} + +#define OFF_T_MAX ~(1l << (sizeof(off_t) * 8 - 1)) + +static int file_lock_from_flock(struct fd *fd, struct flock_ *flock, struct file_lock *lock) { + off_t_ offset; + switch (flock->whence) { + case LSEEK_SET: + offset = 0; + break; + case LSEEK_CUR: + if (!fd->ops->lseek) { + offset = 0; + } else { + lock(&fd->lock); + offset = fd->ops->lseek(fd, 0, LSEEK_CUR); + unlock(&fd->lock); + if (offset < 0) + return offset; + } + break; + case LSEEK_END: { + struct statbuf stat; + int err = fd->mount->fs->fstat(fd, &stat); + if (err < 0) + return err; + offset = stat.size; + break; + } + default: + return _EINVAL; + } + + lock->start = flock->start + offset; + if (flock->len > 0) { + lock->end = lock->start + flock->len - 1; + } else if (flock->len < 0) { + lock->end = lock->start - 1; + lock->start = lock->end + flock->len + 1; + } else { + lock->end = OFF_T_MAX; + } + lock->type = flock->type; + lock->owner = current->files; + lock->pid = current->pid; + return 0; +} + +static int flock_from_file_lock(struct file_lock *lock, struct flock_ *flock) { + flock->type = lock->type; + flock->whence = LSEEK_SET; + flock->start = lock->start; + if (lock->end != OFF_T_MAX) + flock->len = lock->end - lock->start + 1; + else + flock->len = 0; + flock->pid = lock->pid; + return 0; +} + +int fcntl_getlk(struct fd *fd, struct flock_ *flock) { + if (flock->type != F_RDLCK_ && flock->type != F_WRLCK_) + return _EINVAL; + struct inode_data *inode = fd->inode; + lock(&inode->lock); + + struct file_lock request; + int err = file_lock_from_flock(fd, flock, &request); + if (err < 0) + goto out; + struct file_lock *lock = file_lock_test(inode, &request); + err = 0; + if (lock != NULL) + err = flock_from_file_lock(lock, flock); + else + flock->type = F_UNLCK_; +out: + unlock(&inode->lock); + return err; +} + +int fcntl_setlk(struct fd *fd, struct flock_ *flock, bool blocking) { + if (flock->type != F_RDLCK_ && flock->type != F_WRLCK_ && flock->type != F_UNLCK_) + return _EINVAL; + int fd_mode = fd_getflags(fd) & O_ACCMODE_; + if (flock->type == F_RDLCK_ && fd_mode == O_WRONLY_) + return _EBADF; + if (flock->type == F_WRLCK_ && fd_mode == O_RDONLY_) + return _EBADF; + + struct inode_data *inode = fd->inode; + lock(&inode->lock); + + struct file_lock request; + int err = file_lock_from_flock(fd, flock, &request); + if (err < 0) + goto out; + while ((err = file_lock_acquire(inode, &request)) == _EAGAIN) { + if (!blocking) + break; + err = wait_for(&inode->posix_unlock, &inode->lock, NULL); + if (err < 0) + break; + } +out: + unlock(&inode->lock); + return err; +} + +void file_lock_remove_owned_by(struct fd *fd, void *owner) { + struct inode_data *inode = fd->inode; + lock(&inode->lock); + struct file_lock *lock, *tmp; + list_for_each_entry_safe(&inode->posix_locks, lock, tmp, locks) { + if (lock->owner == owner) + file_lock_delete(lock); + } + unlock(&inode->lock); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/mem.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/mem.c new file mode 100644 index 0000000000..d8cb847dc5 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/mem.c @@ -0,0 +1,127 @@ +#include <string.h> +#include <stdio.h> +#include "kernel/errno.h" +#include "kernel/random.h" +#include "fs/poll.h" +#include "fs/mem.h" +#include "fs/dev.h" +#include "fs/devices.h" + +// Random device ioctl +#define RNDGETENTCNT_ 0x80045200 // Get entropy count + +extern struct dev_ops + null_dev, + zero_dev, + full_dev, + random_dev; + +// this file handles major device number MEM_MAJOR, minor device numbers are mapped in table below +struct dev_ops *mem_devs[256] = { + // [1] = &prog_mem_dev, + // [2] = &kmem_dev, // (not really applicable) + [DEV_NULL_MINOR] = &null_dev, + // [4] = &port_dev, + [DEV_ZERO_MINOR] = &zero_dev, + [DEV_FULL_MINOR] = &full_dev, + [DEV_RANDOM_MINOR] = &random_dev, + [DEV_URANDOM_MINOR] = &random_dev, + // [10] = &aio_dev, + // [11] = &kmsg_dev, + // [12] = &oldmem_dev, // replaced by /proc/vmcore +}; + +// dispatch device for major device 1 +static int mem_open(int major, int minor, struct fd *fd) { + struct dev_ops *dev = mem_devs[minor]; + if (dev == NULL) { + return _ENXIO; + } + fd->ops = &dev->fd; + if (!dev->open) + return 0; + return dev->open(major, minor, fd); +} + +struct dev_ops mem_dev = { + .open = mem_open, +}; + +static int ready_poll(struct fd *UNUSED(fd)) { + return POLL_READ | POLL_WRITE; +} + +// begin inline devices +static int null_open(int UNUSED(major), int UNUSED(minor), struct fd *UNUSED(fd)) { + return 0; +} +static ssize_t null_read(struct fd *UNUSED(fd), void *UNUSED(buf), size_t UNUSED(bufsize)) { + return 0; +} +static ssize_t null_write(struct fd *UNUSED(fd), const void *UNUSED(buf), size_t bufsize) { + return bufsize; +} +static off_t_ null_lseek(struct fd *UNUSED(fd), off_t_ UNUSED(off), int UNUSED(whence)) { + return 0; +} +struct dev_ops null_dev = { + .open = null_open, + .fd.read = null_read, + .fd.write = null_write, + .fd.lseek = null_lseek, + .fd.poll = ready_poll, +}; + +static ssize_t zero_read(struct fd *UNUSED(fd), void *buf, size_t bufsize) { + memset(buf, 0, bufsize); + return bufsize; +} +static ssize_t zero_write(struct fd *UNUSED(fd), const void *UNUSED(buf), size_t bufsize) { + return bufsize; +} +struct dev_ops zero_dev = { + .open = null_open, + .fd.read = zero_read, + .fd.write = zero_write, + .fd.lseek = null_lseek, + .fd.poll = ready_poll, +}; + +static ssize_t full_write(struct fd *UNUSED(fd), const void *UNUSED(buf), size_t UNUSED(bufsize)) { + return _ENOSPC; +} +struct dev_ops full_dev = { + .open = null_open, + .fd.read = zero_read, + .fd.write = full_write, + .fd.lseek = null_lseek, + .fd.poll = ready_poll, +}; + +static ssize_t random_read(struct fd *UNUSED(fd), void *buf, size_t bufsize) { + if (get_random(buf, bufsize) != 0) { + return _EIO; + } + return bufsize; +} + +static int random_ioctl(struct fd *UNUSED(fd), int cmd, void *arg) { + switch (cmd) { + case RNDGETENTCNT_: + // Return a high entropy count so applications think entropy is available + // On macOS, CCRandomGenerateBytes never blocks, so we always have entropy + *(int *)arg = 4096; // Typical pool size + return 0; + default: + return _ENOTTY; + } +} + +struct dev_ops random_dev = { + .open = null_open, + .fd.read = random_read, + .fd.write = null_write, + .fd.lseek = null_lseek, + .fd.poll = ready_poll, + .fd.ioctl = random_ioctl, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/mem.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/mem.h new file mode 100644 index 0000000000..7431d39c8c --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/mem.h @@ -0,0 +1,9 @@ +#ifndef FS_NULL_H +#define FS_NULL_H + +#include "kernel/fs.h" +#include "fs/dev.h" + +extern struct dev_ops mem_dev; + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/mount.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/mount.c new file mode 100644 index 0000000000..4d6582cff7 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/mount.c @@ -0,0 +1,251 @@ +#include <string.h> +#include <sys/stat.h> +#include "kernel/calls.h" +#include "kernel/fs.h" +#include "fs/path.h" +#include "fs/real.h" + +#define MAX_FILESYSTEMS 10 +static const struct fs_ops *filesystems[MAX_FILESYSTEMS] = { + &realfs, + &procfs, + &devptsfs, + &tmpfs, +}; + +void fs_register(const struct fs_ops *fs) { + for (unsigned i = 0; i < MAX_FILESYSTEMS; i++) { + if (filesystems[i] == NULL) { + filesystems[i] = fs; + return; + } + } + assert(!"reached filesystem limit"); +} + +// === MOUNT CACHE: Thread-local cache for mount lookups === +// Most file operations use the same mount point (e.g., realfs at "/") +// Caching the last lookup can save repeated list traversals +static __thread struct mount *last_mount_cache = NULL; +static __thread uint64_t mount_cache_version = 0; +static uint64_t global_mount_version = 0; // Incremented on mount/umount + +// Check if cached mount is valid for given path +static inline bool mount_cache_check(struct mount *cached, const char *path) { + if (cached == NULL) + return false; + + // Check if mount table changed (mount/umount invalidates cache) + if (mount_cache_version != global_mount_version) + return false; + + // Check if path is under cached mount point + size_t n = strlen(cached->point); + if (n == 0) { + // Root mount: only cache if path doesn't start with any other mount point + // For now, don't cache root mount lookups since they're ambiguous + return false; + } + return (strncmp(path, cached->point, n) == 0 && + (path[n] == '/' || path[n] == '\0')); +} + +struct mount *mount_find(char *path) { + assert(path_is_normalized(path)); + + // === FAST PATH: Check thread-local cache === + struct mount *cached = last_mount_cache; + if (mount_cache_check(cached, path)) { + // Cache hit - just increment refcount + lock(&mounts_lock); + cached->refcount++; + unlock(&mounts_lock); + return cached; + } + + // === SLOW PATH: Full mount table search === + lock(&mounts_lock); + struct mount *mount = NULL; + assert(!list_empty(&mounts)); // this would mean there's no root FS mounted + list_for_each_entry(&mounts, mount, mounts) { + size_t n = strlen(mount->point); + if (strncmp(path, mount->point, n) == 0 && (path[n] == '/' || path[n] == '\0')) { + break; + } + } + mount->refcount++; + + // Update cache + last_mount_cache = mount; + mount_cache_version = global_mount_version; + + unlock(&mounts_lock); + return mount; +} + +void mount_retain(struct mount *mount) { + lock(&mounts_lock); + mount->refcount++; + unlock(&mounts_lock); +} + +void mount_release(struct mount *mount) { + lock(&mounts_lock); + mount->refcount--; + unlock(&mounts_lock); +} + +int do_mount(const struct fs_ops *fs, const char *source, const char *point, const char *info, int flags) { + struct mount *new_mount = malloc(sizeof(struct mount)); + if (new_mount == NULL) + return _ENOMEM; + new_mount->point = strdup(point); + new_mount->source = strdup(source); + new_mount->info = strdup(info); + new_mount->flags = flags; + new_mount->fs = fs; + new_mount->data = NULL; + new_mount->refcount = 0; + if (fs->mount) { + int err = fs->mount(new_mount); + if (err < 0) { + free((void *) new_mount->point); + free((void *) new_mount->source); + free(new_mount); + return err; + } + } + + // the list must stay in descending order of mount point length + struct mount *mount; + list_for_each_entry(&mounts, mount, mounts) { + if (strlen(mount->point) <= strlen(new_mount->point)) + break; + } + list_add_before(&mount->mounts, &new_mount->mounts); + + // Invalidate all mount caches + global_mount_version++; + + return 0; +} + +int mount_remove(struct mount *mount) { + if (mount->refcount != 0) + return _EBUSY; + + if (mount->fs->umount) + mount->fs->umount(mount); + list_remove(&mount->mounts); + free((void *) mount->info); + free((void *) mount->source); + free((void *) mount->point); + free(mount); + + // Invalidate all mount caches + global_mount_version++; + + return 0; +} + +int do_umount(const char *point) { + struct mount *mount; + bool found = false; + list_for_each_entry(&mounts, mount, mounts) { + if (strcmp(point, mount->point) == 0) { + found = true; + break; + } + } + if (!found) + return _EINVAL; + return mount_remove(mount); +} + +// Parse a comma-separated mount option list for an exact flag token. +bool mount_param_flag(const char *info, const char *flag) { + size_t flag_len = strlen(flag); + while (*info != '\0') { + size_t token_len = strcspn(info, ","); + if (token_len == flag_len && strncmp(info, flag, flag_len) == 0) + return true; + info += token_len; + if (*info == ',') + info++; + } + return false; +} + +#define MS_SUPPORTED (MS_READONLY_|MS_NOSUID_|MS_NODEV_|MS_NOEXEC_|MS_SILENT_) +#define MS_FLAGS (MS_READONLY_|MS_NOSUID_|MS_NODEV_|MS_NOEXEC_) + +dword_t sys_mount(addr_t source_addr, addr_t point_addr, addr_t type_addr, dword_t flags, addr_t data_addr) { + char source[MAX_PATH]; + if (user_read_string(source_addr, source, sizeof(source))) + return _EFAULT; + char point_raw[MAX_PATH]; + if (user_read_string(point_addr, point_raw, sizeof(point_raw))) + return _EFAULT; + char data[MAX_PATH]; + if (data_addr != 0) { + if (user_read_string(data_addr, data, sizeof(data))) + return _EFAULT; + } + char type[100]; + if (user_read_string(type_addr, type, sizeof(type))) + return _EFAULT; + STRACE("mount(\"%s\", \"%s\", \"%s\", %#x, \"%s\")", source, point_raw, type, flags, data_addr != 0 ? data : NULL); + + if (flags & ~MS_SUPPORTED) { + FIXME("missing mount flags %#x", flags & ~MS_SUPPORTED); + return _EINVAL; + } + + const struct fs_ops *fs = NULL; + for (size_t i = 0; i < sizeof(filesystems)/sizeof(filesystems[0]); i++) { + if (filesystems[i] && (strcmp(filesystems[i]->name, type) == 0)) { + fs = filesystems[i]; + break; + } + } + if (fs == NULL) + return _EINVAL; + + struct statbuf stat; + int err = generic_statat(AT_PWD, point_raw, &stat, true); + if (err < 0) + return err; + if (!S_ISDIR(stat.mode)) + return _ENOTDIR; + + char point[MAX_PATH]; + err = path_normalize(AT_PWD, point_raw, point, N_SYMLINK_FOLLOW); + if (err < 0) + return err; + + lock(&mounts_lock); + err = do_mount(fs, source, point, data, flags & MS_FLAGS); + unlock(&mounts_lock); + return err; +} + +#define UMOUNT_NOFOLLOW_ 8 + +dword_t sys_umount2(addr_t target_addr, dword_t flags) { + char target_raw[MAX_PATH]; + if (user_read_string(target_addr, target_raw, sizeof(target_raw))) + return _EFAULT; + char target[MAX_PATH]; + int err = path_normalize(AT_PWD, target_raw, target, + flags & UMOUNT_NOFOLLOW_ ? N_SYMLINK_NOFOLLOW : N_SYMLINK_FOLLOW); + if (err < 0) + return err; + + lock(&mounts_lock); + err = do_umount(target); + unlock(&mounts_lock); + return err; +} + +struct list mounts = {&mounts, &mounts}; +lock_t mounts_lock = LOCK_INITIALIZER; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/path.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/path.c new file mode 100644 index 0000000000..f22517fd1a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/path.c @@ -0,0 +1,194 @@ +#include <string.h> +#include <sys/stat.h> +#include <stdbool.h> +#include "kernel/calls.h" +#include "fs/path.h" +#include "misc.h" + +static int __path_normalize(const char *at_path, const char *path, char *out, int flags, int levels) { + // you must choose one + if (flags & N_SYMLINK_FOLLOW) + assert(!(flags & N_SYMLINK_NOFOLLOW)); + else + assert(flags & N_SYMLINK_NOFOLLOW); + + const char *p = path; + char *o = out; + *o = '\0'; + int n = MAX_PATH - 1; + + if (strcmp(path, "") == 0) + return _ENOENT; + + if (at_path != NULL && strcmp(at_path, "/") != 0) { + size_t at_len = strlen(at_path); + if (at_len >= MAX_PATH) + return _ENAMETOOLONG; + memcpy(o, at_path, at_len + 1); + n -= at_len; + o += at_len; + } + + while (*p == '/') + p++; + + while (*p != '\0') { + if (p[0] == '.') { + if (p[1] == '\0' || p[1] == '/') { + // single dot path component, ignore + p++; + while (*p == '/') + p++; + continue; + } else if (p[1] == '.' && (p[2] == '\0' || p[2] == '/')) { + // double dot path component, delete the last component + if (o != out) { + do { + o--; + n++; + } while (*o != '/'); + } + p += 2; + while (*p == '/') + p++; + continue; + } + } + + // output a slash + *o++ = '/'; n--; + char *c = o; + // copy up to a slash or null + while (*p != '/' && *p != '\0' && --n > 0) + *o++ = *p++; + // eat any slashes + while (*p == '/') + p++; + + if (n == 0) + return _ENAMETOOLONG; + + if ((flags & N_SYMLINK_FOLLOW) || *p != '\0') { + // this buffer is used to store the path that we're readlinking, then + // if it turns out to point to a symlink it's reused as the buffer + // passed to the next path_normalize call + char possible_symlink[MAX_PATH]; + *o = '\0'; + strcpy(possible_symlink, out); + struct mount *mount = find_mount_and_trim_path(possible_symlink); + assert(path_is_normalized(possible_symlink)); + int res = _EINVAL; + if (mount->fs->readlink) + res = mount->fs->readlink(mount, possible_symlink, c, MAX_PATH - (c - out)); + if (res >= 0) { + mount_release(mount); + if (levels >= 5) + return _ELOOP; + // readlink does not null terminate. A full-buffer result leaves + // no room for the terminator in out/possible_symlink. + size_t link_room = MAX_PATH - (size_t)(c - out); + if ((size_t)res >= link_room) + return _ENAMETOOLONG; + c[res] = '\0'; + // if we should restart from the root, copy down + if (*c == '/') + memmove(out, c, strlen(c) + 1); + size_t out_len = strlen(out); + size_t rest_len = strlen(p); + bool have_rest = rest_len != 0; + if (out_len + (have_rest ? 1 + rest_len : 0) >= MAX_PATH) + return _ENAMETOOLONG; + char *expanded_path = possible_symlink; + memcpy(expanded_path, out, out_len + 1); + if (have_rest) { + expanded_path[out_len] = '/'; + memcpy(expanded_path + out_len + 1, p, rest_len + 1); + } + return __path_normalize(NULL, expanded_path, out, flags, levels + 1); + } + + // if there's a slash after this component, ensure that if it + // exists, it's a directory and that we have execute perms on it + if (*(p - 1) == '/') { + struct statbuf stat; + int err = mount->fs->stat(mount, possible_symlink, &stat); + mount_release(mount); + if (err >= 0) { + if (!S_ISDIR(stat.mode)) + return _ENOTDIR; + err = access_check(&stat, AC_X); + if (err < 0) + return err; + } + } else { + mount_release(mount); + } + } + } + + *o = '\0'; + assert(path_is_normalized(out)); + + return 0; +} + +int path_normalize(struct fd *at, const char *path, char *out, int flags) { + if (strcmp(path, "") == 0) + return _ENOENT; + + // start with root or cwd, depending on whether it starts with a slash + lock(¤t->fs->lock); + if (path[0] == '/') + at = current->fs->root; + else if (at == AT_PWD) + at = current->fs->pwd; + unlock(¤t->fs->lock); + if (at == NULL && path[0] != '/') + return _EBADF; + if (at != NULL && IS_ERR(at)) + return PTR_ERR(at); + + char at_path[MAX_PATH]; + if (at != NULL) { + int err = generic_getpath(at, at_path); + if (err < 0) + return err; + assert(path_is_normalized(at_path)); + } + + return __path_normalize(at != NULL ? at_path : NULL, path, out, flags, 0); +} + + +bool path_is_normalized(const char *path) { + while (*path != '\0') { + if (*path != '/') + return false; + path++; + if (*path == '/') + return false; + while (*path != '/' && *path != '\0') + path++; + } + return true; +} + +bool path_next_component(const char **path, char *component, int *err) { + const char *p = *path; + if (*p == '\0') + return false; + + assert(*p == '/'); + p++; + char *c = component; + while (*p != '/' && *p != '\0') { + *c++ = *p++; + if (c - component >= MAX_NAME) { + *err = _ENAMETOOLONG; + return false; + } + } + *c = '\0'; + *path = p; + return true; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/path.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/path.h new file mode 100644 index 0000000000..697bf21398 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/path.h @@ -0,0 +1,40 @@ +#ifndef PATH_H +#define PATH_H + +#define AT_PWD (struct fd *) -2 + +#define N_SYMLINK_FOLLOW 1 +#define N_SYMLINK_NOFOLLOW 2 +#define N_PARENT_DIR_WRITE 4 + +// Normalizes the path specified and writes the result into the out buffer. +// +// Normalization means: +// - prepending the current or root directory +// - converting multiple slashes into one +// - resolving . and .. +// - resolving symlinks, skipping the last path component if the follow_links +// argument is true +// The result will always begin with a slash or be empty. +// +// If the normalized path plus the null terminator would be longer than +// MAX_PATH, _ENAMETOOLONG is returned. The out buffer is expected to be at +// least MAX_PATH in size. +// +// at is the file descriptor to use as a base to interpret relative paths. If +// at is AT_PWD, uses current->pwd (with appropriate locking). +int path_normalize(struct fd *at, const char *path, char *out, int flags); +bool path_is_normalized(const char *path); + +// Helper function for iterating through a normalized path. +// +// The *path pointer is advanced to point to the next /, and the next path +// component is copied to component. component must point to a buffer large +// enough to hold a string of MAX_NAME characters. +// +// If the next path component was successfully copied, returns true; otherwise +// returns false. If an error occurred, *err is set to the error code. +// Otherwise, the end of the path has been reached. +bool path_next_component(const char **path, char *component, int *err); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/pipe.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/pipe.c new file mode 100644 index 0000000000..ff900e6cd4 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/pipe.c @@ -0,0 +1,57 @@ +#include <sys/stat.h> +#include <unistd.h> +#include "kernel/calls.h" +#include "fs/fd.h" +#include "fs/real.h" +#include "debug.h" + +static fd_t pipe_f_create(int pipe_fd, int flags) { + struct fd *fd = adhoc_fd_create(&realfs_fdops); + if (fd == NULL) + return _ENOMEM; + fd->real_fd = pipe_fd; + fd->stat.mode = S_IFIFO | 0660; + fd->stat.uid = current->uid; + fd->stat.gid = current->gid; + return f_install(fd, flags); +} + +int_t sys_pipe2(addr_t pipe_addr, int_t flags) { + STRACE("pipe2(%#x, %#x)", pipe_addr, flags); + if (flags & ~(O_CLOEXEC_|O_NONBLOCK_)) { + FIXME("unsupported pipe2 flags"); + return _EINVAL; + } + + int p[2]; + int err = pipe(p); + if (err < 0) + return err; + + int fp[2]; + err = fp[0] = pipe_f_create(p[0], flags); + if (fp[0] < 0) + goto close_pipe; + err = fp[1] = pipe_f_create(p[1], flags); + if (fp[1] < 0) + goto close_fake_0; + + err = _EFAULT; + if (user_put(pipe_addr, fp)) + goto close_fake_1; + STRACE(" [%d %d]", fp[0], fp[1]); + return 0; + +close_fake_1: + f_close(fp[1]); +close_fake_0: + f_close(fp[0]); +close_pipe: + close(p[0]); + close(p[1]); + return err; +} + +int_t sys_pipe(addr_t pipe_addr) { + return sys_pipe2(pipe_addr, 0); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/poll.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/poll.c new file mode 100644 index 0000000000..b395ef2aba --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/poll.c @@ -0,0 +1,597 @@ +#include "kernel/task.h" +#include <string.h> +#include <poll.h> +#include <fcntl.h> +#include <limits.h> +#include <time.h> +#include "misc.h" +#include "util/list.h" +#include "kernel/errno.h" +#include "kernel/fs.h" +#include "fs/fd.h" +#include "fs/poll.h" +#include "fs/real.h" + +#include "fs/sockrestart.h" + +// From kernel/calls.h - avoid circular include +extern _Noreturn void do_exit_group(int status); + +#if defined(__linux__) +#include <sys/epoll.h> +#define HAVE_EPOLL 1 +#elif defined(__APPLE__) +#include <sys/event.h> +#define HAVE_KQUEUE 1 +#endif + +static int real_poll_init(struct real_poll *real); +static void real_poll_close(struct real_poll *real); +struct real_poll_event { +#if HAVE_EPOLL + struct epoll_event real; +#elif HAVE_KQUEUE + struct kevent real; +#endif +}; +static void *rpe_data(struct real_poll_event *rpe); +static int rpe_events(struct real_poll_event *rpe); +static int real_poll_wait(struct real_poll *real, struct real_poll_event *events, int max, struct timespec *timeout); +static int real_poll_update(struct real_poll *real, int fd, int types, void *data); + +/// Safe close that skips fds 0-2 (stdin/stdout/stderr). +/// iOS guards these descriptors — closing them triggers EXC_GUARD and kills the app. +/// The iSH kernel operates on host fds that should never be 0/1/2, but race +/// conditions during fd reuse can occasionally produce them. +static inline void safe_close(int fd) { + if (fd > 2) + close(fd); +} + +// lock order: fd, then poll + +struct poll *poll_create() { + struct poll *poll = malloc(sizeof(struct poll)); + if (poll == NULL) + return ERR_PTR(_ENOMEM); + int err = real_poll_init(&poll->real); + if (err < 0) + return ERR_PTR(errno_map()); + poll->waiters = 0; + poll->notify_pipe[0] = -1; + poll->notify_pipe[1] = -1; + list_init(&poll->poll_fds); + list_init(&poll->pollfd_freelist); + lock_init(&poll->lock); + return poll; +} + +static inline bool poll_fd_is_real(struct poll_fd *pollfd) { + return pollfd->fd->ops->poll == realfs_poll; +} + +// does not do its own locking +// Match on the (struct fd, guest fd number) pair — see fd_no in fs/poll.h. +static struct poll_fd *poll_find_fd(struct poll *poll, struct fd *fd, int fd_no) { + struct poll_fd *poll_fd, *tmp; + list_for_each_entry_safe(&poll->poll_fds, poll_fd, tmp, fds) { + if (poll_fd->fd == fd && poll_fd->fd_no == fd_no) + return poll_fd; + } + return NULL; +} + +// Recompute the host (real) registration for `fd` in this poll as the UNION +// of the event types of every registration referring to it. Several guest +// registrations (different fd numbers, same description after dup) share one +// host registration, since the host backend is keyed by real_fd. Passing 0 +// types deletes the host registration. poll->lock must be held. +static int poll_real_refresh(struct poll *poll, struct fd *fd) { + int types = 0; + struct poll_fd *pf, *first = NULL; + list_for_each_entry(&poll->poll_fds, pf, fds) { + if (pf->fd == fd) { + if (first == NULL) + first = pf; + if (!pf->oneshot_fired) + types |= pf->types; + } + } + return real_poll_update(&poll->real, fd->real_fd, types, first); +} + +// See comment on pollfd_freelist for context +static void poll_fd_free(struct poll_fd *poll_fd) { + struct poll *poll = poll_fd->poll; + memset(poll_fd, 0xba, sizeof(*poll_fd)); + poll_fd->poll = NULL; // used to mark it as free + list_add(&poll->pollfd_freelist, &poll_fd->fds); +} + +bool poll_has_fd(struct poll *poll, struct fd *fd, int fd_no) { + return poll_find_fd(poll, fd, fd_no) != NULL; +} + +int poll_add_fd(struct poll *poll, struct fd *fd, int fd_no, int types, union poll_fd_info info) { + int err; + lock(&fd->poll_lock); + lock(&poll->lock); + + struct poll_fd *poll_fd; + if (!list_empty(&poll->pollfd_freelist)) { + poll_fd = list_first_entry(&poll->pollfd_freelist, struct poll_fd, fds); + list_remove(&poll_fd->fds); + } else { + poll_fd = malloc(sizeof(struct poll_fd)); + if (poll_fd == NULL) { + err = _ENOMEM; + goto out; + } + } + poll_fd->fd = fd; + poll_fd->fd_no = fd_no; + poll_fd->poll = poll; + poll_fd->types = types; + poll_fd->info = info; + poll_fd->triggered_types = 0; + poll_fd->oneshot_fired = false; + + // Link first, then refresh the (shared) host registration to the union of + // all registrations of this description in this poll. + list_add(&fd->poll_fds, &poll_fd->polls); + list_add(&poll->poll_fds, &poll_fd->fds); + + if (poll_fd_is_real(poll_fd)) { + err = poll_real_refresh(poll, fd); + if (err < 0) { + list_remove(&poll_fd->polls); + list_remove(&poll_fd->fds); + poll_fd_free(poll_fd); + err = errno_map(); + goto out; + } + } + + err = 0; +out: + unlock(&poll->lock); + unlock(&fd->poll_lock); + return err; +} + +int poll_del_fd(struct poll *poll, struct fd *fd, int fd_no) { + int err; + lock(&fd->poll_lock); + lock(&poll->lock); + struct poll_fd *poll_fd = poll_find_fd(poll, fd, fd_no); + if (poll_fd == NULL) { + err = _ENOENT; + goto out; + } + + bool is_real = poll_fd_is_real(poll_fd); + list_remove(&poll_fd->polls); + list_remove(&poll_fd->fds); + poll_fd_free(poll_fd); + + // Refresh (or delete, if this was the last registration) the shared host + // registration to the union of the remaining registrations. + if (is_real) { + err = poll_real_refresh(poll, fd); + if (err < 0) { + err = errno_map(); + goto out; + } + } + + err = 0; +out: + unlock(&poll->lock); + unlock(&fd->poll_lock); + return err; +} + +int poll_mod_fd(struct poll *poll, struct fd *fd, int fd_no, int types, union poll_fd_info info) { + int err; + lock(&fd->poll_lock); + lock(&poll->lock); + struct poll_fd *poll_fd = poll_find_fd(poll, fd, fd_no); + if (poll_fd == NULL) { + err = _ENOENT; + goto out; + } + + poll_fd->types = types; + poll_fd->info = info; + poll_fd->triggered_types &= types; + poll_fd->oneshot_fired = false; // EPOLL_CTL_MOD re-arms a fired oneshot + + if (poll_fd_is_real(poll_fd)) { + err = poll_real_refresh(poll, fd); + if (err < 0) { + err = errno_map(); + goto out; + } + } + + err = 0; +out: + unlock(&poll->lock); + unlock(&fd->poll_lock); + return err; +} + +void poll_cleanup_fd(struct fd *fd) { + lock(&fd->poll_lock); + struct poll_fd *poll_fd, *tmp; + list_for_each_entry_safe(&fd->poll_fds, poll_fd, tmp, polls) { + lock(&poll_fd->poll->lock); + if (poll_fd_is_real(poll_fd)) + real_poll_update(&poll_fd->poll->real, fd->real_fd, 0, poll_fd); + list_remove(&poll_fd->polls); + list_remove(&poll_fd->fds); + unlock(&poll_fd->poll->lock); + poll_fd_free(poll_fd); + } + unlock(&fd->poll_lock); +} + +void poll_wakeup(struct fd *fd, int events) { + struct poll_fd *poll_fd; + lock(&fd->poll_lock); + list_for_each_entry(&fd->poll_fds, poll_fd, polls) { + struct poll *poll = poll_fd->poll; + lock(&poll->lock); + if (poll_fd->oneshot_fired) { + unlock(&poll->lock); + continue; + } + if (poll_fd->types & POLL_EDGETRIGGERED) + poll_fd->triggered_types &= ~events; + if (poll->notify_pipe[1] != -1) + write(poll->notify_pipe[1], "", 1); + unlock(&poll->lock); + // oneshot? + } + unlock(&fd->poll_lock); +} + +int poll_wait(struct poll *poll_, poll_callback_t callback, void *context, struct timespec *timeout) { + lock(&poll_->lock); + + // acquire the pipe + if (poll_->waiters++ == 0) { + assert(poll_->notify_pipe[0] == -1 && poll_->notify_pipe[1] == -1); + if (pipe(poll_->notify_pipe) < 0) { + unlock(&poll_->lock); + return errno_map(); + } + fcntl(poll_->notify_pipe[0], F_SETFL, O_NONBLOCK); + fcntl(poll_->notify_pipe[1], F_SETFL, O_NONBLOCK); + real_poll_update(&poll_->real, poll_->notify_pipe[0], POLL_READ, NULL); + } + + // TODO this is pretty broken with regards to timeouts + int res = 0; + while (true) { + // check if any fds are ready + struct poll_fd *poll_fd, *tmp; + list_for_each_entry_safe(&poll_->poll_fds, poll_fd, tmp, fds) { + if (poll_fd->oneshot_fired) + continue; + struct fd *fd = poll_fd->fd; + int poll_types = 0; + if (fd->ops->poll) + poll_types = fd->ops->poll(fd); + poll_types &= poll_fd->types | POLL_HUP | POLL_ERR; + if (poll_fd->types & POLL_EDGETRIGGERED) { + poll_types &= ~poll_fd->triggered_types; + } + if (poll_types) { + if (callback(context, poll_types, poll_fd->info) == 1) + res++; + + // The real poll does not actually get the FDs set as oneshot. + // But this loop is done while holding the lock, so only one + // thread can get each oneshot event. This doesn't solve the + // thundering herd problem at all, but at least the semantics + // are right. I'll just leave that as a TODO. + if (poll_fd->types & POLL_ONESHOT) { + // Disable in place; do NOT unlink. We hold only + // poll->lock here, but poll_fd->polls is walked by + // poll_wakeup under fd->poll_lock — unlinking/freeing + // raced it and crashed the tty input thread (SIGSEGV in + // poll_wakeup when bun registers stdin with + // EPOLLONESHOT). Linux semantics also keep a fired + // oneshot registered, disabled until EPOLL_CTL_MOD. + poll_fd->oneshot_fired = true; + if (poll_fd_is_real(poll_fd)) { + // Refresh the shared host registration to the union + // of the still-armed registrations. + poll_real_refresh(poll_, fd); + } + } + + if (poll_fd->types & POLL_EDGETRIGGERED) { + poll_fd->triggered_types |= poll_types; + } + } + } + if (res > 0) + break; + + bool signal_pending = false; + if (current->sighand != NULL) { + lock(¤t->sighand->lock); + signal_pending = !!(current->pending & ~current->blocked); + unlock(¤t->sighand->lock); + } + if (signal_pending) { + res = _EINTR; + break; + } + + // wait for a ready notification + list_for_each_entry(&poll_->poll_fds, poll_fd, fds) { + sockrestart_begin_listen_wait(poll_fd->fd); + } + unlock(&poll_->lock); + int err; + int saved_errno; + struct real_poll_event e[4]; + // Use a bounded timeout to avoid indefinite blocks. Guest signal + // delivery via SIGUSR1 wakes kevent, but if the signal arrives + // between our pending check and kevent entry, we'd block forever. + // A 5-second cap ensures we re-check signals periodically. + // Cap all waits to 1 second to avoid macOS condvar issues. + // pthread_cond_timedwait_relative_np can block forever under + // thread contention. Short caps ensure we re-check periodically. + struct timespec bounded_timeout = {.tv_sec = 1, .tv_nsec = 0}; + struct timespec *wait_timeout; + if (timeout == NULL) { + wait_timeout = &bounded_timeout; + } else if (timeout->tv_sec >= 1) { + wait_timeout = &bounded_timeout; // Cap long timeouts + } else { + wait_timeout = timeout; // Short/zero timeouts pass through + } + current->blocking = true; + do { + err = real_poll_wait(&poll_->real, e, sizeof(e)/sizeof(e[0]), wait_timeout); + saved_errno = errno; // save immediately before anything clobbers it + } while (saved_errno == EINTR && sockrestart_should_restart_listen_wait()); + current->blocking = false; + // Only update last_unblocked_ns when actual events were received. + // Timeout returns (err==0) don't count as real progress — the poll_wait + // loop is just cycling. This prevents the deadlock detector from being + // fooled by idle poll_wait loops during exit cleanup. + if (err > 0) { + struct timespec _ts; + clock_gettime(CLOCK_MONOTONIC, &_ts); + uint64_t now = (uint64_t)_ts.tv_sec * 1000000000ULL + _ts.tv_nsec; + current->last_unblocked_ns = now; + atomic_store_explicit(¤t->group->last_progress_ns, now, + memory_order_relaxed); + } + // If we timed out from our bounded timeout, loop back to re-check + // fd readiness and signal pending. + if (err == 0 && wait_timeout == &bounded_timeout) { + lock(&poll_->lock); + list_for_each_entry(&poll_->poll_fds, poll_fd, fds) { + sockrestart_end_listen_wait(poll_fd->fd); + } + // Check for group exit so blocking threads unblock promptly + if (current->group->doing_group_exit) { + res = _EINTR; + break; + } + // Safety valve: if no thread in this process group has + // done real work for >60s and there are no live child + // processes, force exit. Catches V8/libuv exit cleanup + // hangs where the event loop spins idle forever. + // + // Exceptions: + // - pid 1 (init): legitimately idles, killing halts the system + // - processes with a controlling TTY: interactive shells idle + // waiting for user input and must not be killed + if (current->pid != 1 && current->group->tty == NULL) { + struct timespec _now; + clock_gettime(CLOCK_MONOTONIC, &_now); + uint64_t now_ns = (uint64_t)_now.tv_sec * 1000000000ULL + _now.tv_nsec; + uint64_t last = atomic_load_explicit( + ¤t->group->last_progress_ns, memory_order_relaxed); + int64_t idle_s = (int64_t)(now_ns - last) / 1000000000LL; + if (idle_s >= 60) { + bool has_live_children = false; + int thread_count = 0; + int nonblocking_threads = 0; + lock(&pids_lock); + lock(¤t->group->lock); + struct task *t_iter; + list_for_each_entry(¤t->group->threads, t_iter, group_links) { + thread_count++; + if (!t_iter->blocking) + nonblocking_threads++; + struct task *child; + list_for_each_entry(&t_iter->children, child, siblings) { + if (child->group != current->group && !child->zombie) + has_live_children = true; + } + } + unlock(¤t->group->lock); + unlock(&pids_lock); + if (!has_live_children && nonblocking_threads == 0) { + printk("SAFETY-VALVE[poll]: pid=%d idle %llds, %d threads → exit_group\n", + current->pid, (long long)idle_s, thread_count); + do_exit_group(0); + } + } + } + if (timeout != NULL) { + // Timed wait: subtract elapsed time + timeout->tv_sec -= 1; + if (timeout->tv_sec < 0) { + // Original timeout expired + break; + } + } + continue; + } + lock(&poll_->lock); + list_for_each_entry(&poll_->poll_fds, poll_fd, fds) { + sockrestart_end_listen_wait(poll_fd->fd); + } + + if (err < 0) { + errno = saved_errno; + res = errno_map(); + break; + } + if (err == 0) { + // timed out and still nobody is ready + break; + } + + // dead with any edge-triggered notifications + for (int i = 0; i < err; i++) { + struct poll_fd *triggered_poll_fd = rpe_data(&e[i]); + if (triggered_poll_fd != NULL && triggered_poll_fd->poll != NULL && + triggered_poll_fd->types & POLL_EDGETRIGGERED) { + triggered_poll_fd->triggered_types &= ~rpe_events(&e[i]); + } + } + + char notify_byte; + if (read(poll_->notify_pipe[0], ¬ify_byte, 1) < 0 && errno != EAGAIN) { + res = errno_map(); + break; + } + } + + // release the pipe + if (--poll_->waiters == 0) { + real_poll_update(&poll_->real, poll_->notify_pipe[0], 0, NULL); + safe_close(poll_->notify_pipe[0]); + safe_close(poll_->notify_pipe[1]); + poll_->notify_pipe[0] = -1; + poll_->notify_pipe[1] = -1; + } + + unlock(&poll_->lock); + return res; +} + +void poll_destroy(struct poll *poll) { + struct poll_fd *poll_fd; + struct poll_fd *tmp; + list_for_each_entry_safe(&poll->poll_fds, poll_fd, tmp, fds) { + lock(&poll_fd->fd->poll_lock); + list_remove(&poll_fd->polls); + list_remove(&poll_fd->fds); + unlock(&poll_fd->fd->poll_lock); + free(poll_fd); + } + + list_for_each_entry_safe(&poll->pollfd_freelist, poll_fd, tmp, fds) { + list_remove(&poll_fd->fds); + free(poll_fd); + } + + real_poll_close(&poll->real); + free(poll); +} + +// Platform-specific real_poll implementations + +#if HAVE_EPOLL + +static int real_poll_init(struct real_poll *real) { + real->fd = epoll_create1(0); + if (real->fd < 0) + return -1; + return 0; +} + +static int real_poll_wait(struct real_poll *real, struct real_poll_event *events, int max, struct timespec *timeout) { + int timeout_millis = -1; + if (timeout != NULL) + timeout_millis = timeout->tv_sec * 1000 + timeout->tv_nsec / 1000000; + return epoll_wait(real->fd, (struct epoll_event *) events, max, timeout_millis); +} + +static int real_poll_update(struct real_poll *real, int fd, int types, void *data) { + types &= ~EPOLLONESHOT; + if (types == 0) + return epoll_ctl(real->fd, EPOLL_CTL_DEL, fd, NULL); + struct epoll_event epevent = {.events = types, .data.ptr = data}; + int err = epoll_ctl(real->fd, EPOLL_CTL_MOD, fd, &epevent); + if (err < 0 && errno == ENOENT) + err = epoll_ctl(real->fd, EPOLL_CTL_ADD, fd, &epevent); + return err; +} + +static void *rpe_data(struct real_poll_event *rpe) { + return rpe->real.data.ptr; +} +static int rpe_events(struct real_poll_event *rpe) { + return rpe->real.events; +} + +#elif HAVE_KQUEUE + +static int real_poll_init(struct real_poll *real) { + real->fd = kqueue(); + if (real->fd < 0) + return -1; + return 0; +} + +static int real_poll_update(struct real_poll *real, int fd, int types, void *data) { + struct kevent e[3] = { + {.filter = EVFILT_READ, .flags = types & (POLL_READ | POLL_HUP) ? EV_ADD : EV_DELETE}, + {.filter = EVFILT_WRITE, .flags = types & POLL_WRITE ? EV_ADD : EV_DELETE}, + {.filter = EVFILT_EXCEPT, .flags = types & POLL_ERR ? EV_ADD : EV_DELETE}, + }; + if (!(types & POLL_READ) && types & POLL_HUP) { + // Set the low water mark really high so we'll only get woken up on a hangup + e[0].fflags = NOTE_LOWAT; + e[0].data = INT_MAX; + } + for (int i = 0; i < 3; i++) { + e[i].ident = fd; + e[i].udata = data; + e[i].flags |= EV_RECEIPT; + if (types & POLL_EDGETRIGGERED) + e[i].flags |= EV_CLEAR; + } + + return kevent(real->fd, e, 3, e, 3, NULL); +} + +static int real_poll_wait(struct real_poll *real, struct real_poll_event *events, int max, struct timespec *timeout) { + return kevent(real->fd, NULL, 0, (struct kevent *) events, max, timeout); +} + +static void *rpe_data(struct real_poll_event *rpe) { + return rpe->real.udata; +} +static int rpe_events(struct real_poll_event *rpe) { + if (rpe->real.filter == EVFILT_READ) { + int events = 0; + if (rpe->real.data > 0) + events |= POLL_READ; + if (rpe->real.flags & EV_EOF) + events |= POLL_HUP; + return events; + } + if (rpe->real.filter == EVFILT_WRITE) return POLL_WRITE; + if (rpe->real.filter == EVFILT_EXCEPT) return POLL_ERR; + return 0; +} + +#endif + +static void real_poll_close(struct real_poll *real) { + safe_close(real->fd); +} + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/poll.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/poll.h new file mode 100644 index 0000000000..cf5f9dfec2 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/poll.h @@ -0,0 +1,109 @@ +#ifndef FS_POLL_H +#define FS_POLL_H +#include "kernel/fs.h" + +struct real_poll { + int fd; +}; + +struct poll { + struct list poll_fds; + struct real_poll real; + int notify_pipe[2]; + int waiters; // if nonzero, notify_pipe exists + + // This is used to solve the race/UaF described here: https://lwn.net/Articles/520012/ + // thread 1: calls poll_wait, real_poll_wait returns an event with a pointer to a poll_fd + // thread 2: calls poll_del_fd which frees the same poll_fd + // + // This can't be solved by adding locks because thread 1 could get + // suspended after real_poll_wait returns but before it has a chance to + // lock anything. + // + // An attempt was made to solve this with a Linux kernel patch, which + // almost went in 3.7 but was backed out after discussion at + // https://lkml.org/lkml/2012/10/16/302, and anyway wouldn't have solved + // the problem on Darwin. My solution is to just not free poll_fds, and + // instead move them to a freelist where they can be reused. + struct list pollfd_freelist; + + lock_t lock; +}; + +struct poll_fd { + // locked by containing struct poll + struct fd *fd; + // Guest fd number this registration was made with. Linux keys epoll + // registrations on the (fd number, open file description) PAIR: two + // different fd numbers referring to the same description (dup) may both + // be registered in one epoll set. Matching on struct fd alone returned + // a false EEXIST for that case (observed with bun, which dups stdout + // and stderr — sharing one description after the shell's dup2(1,2) — + // and registers both dups in its event loop). + int fd_no; + struct list fds; + int types; + union poll_fd_info { + void *ptr; + int fd; + uint64_t num; + } info; + // Used to implement edge-triggered notifications. When an event is + // returned its bits are set here, and those bits are ignored on the next + // call to poll_wait. The bits are cleared by poll_wakeup. + int triggered_types; + // A fired POLL_ONESHOT registration is DISABLED in place (Linux keeps + // the registration and re-arms it on EPOLL_CTL_MOD), never unlinked from + // inside poll_wait: unlinking there holds only poll->lock while + // poll_wakeup walks fd->poll_fds under fd->poll_lock, so the tty input + // thread would race the free and crash. Written under poll->lock. + bool oneshot_fired; + + // locked by containing struct fd + struct poll *poll; + struct list polls; +}; + +// these are defined in system headers somewhere +#undef POLL_IN +#undef POLL_OUT +#undef POLL_MSG +#undef POLL_ERR +#undef POLL_PRI +#undef POLL_HUP + +#define POLL_READ 1 +#define POLL_PRI 2 +#define POLL_WRITE 4 +#define POLL_ERR 8 +#define POLL_HUP 16 +#define POLL_NVAL 32 +#define POLL_ONESHOT (1 << 30) +#define POLL_EDGETRIGGERED (1ul << 31) +struct poll_event { + struct fd *fd; + int types; +}; +struct poll *poll_create(void); +// Registrations are keyed on the (guest fd number, struct fd) pair to match +// Linux epoll semantics; fd_no is the guest fd number the caller used. +bool poll_has_fd(struct poll *poll, struct fd *fd, int fd_no); +int poll_add_fd(struct poll *poll, struct fd *fd, int fd_no, int types, union poll_fd_info info); +int poll_mod_fd(struct poll *poll, struct fd *fd, int fd_no, int types, union poll_fd_info info); +int poll_del_fd(struct poll *poll, struct fd *fd, int fd_no); +// Indicates that the specified events have been triggered. Each call will +// generate a new edge-triggered notification. +// please do not call this while holding any locks you would acquire in your poll operation +void poll_wakeup(struct fd *fd, int events); +// Waits for events on the fds in this poll, and calls the callback for each one found. +// Returns the number of times the callback returned 1, or negative for error. +typedef int (*poll_callback_t)(void *context, int types, union poll_fd_info info); +int poll_wait(struct poll *poll, poll_callback_t callback, void *context, struct timespec *timeout); +// does not lock the poll because lock ordering, you must ensure no other +// thread will add or remove fds from this poll +void poll_destroy(struct poll *poll); + +// for fd_close +void poll_cleanup_fd(struct fd *fd); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc.c new file mode 100644 index 0000000000..d84dd88a56 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc.c @@ -0,0 +1,281 @@ +#include <string.h> +#include <sys/stat.h> +#include "kernel/calls.h" +#include "kernel/fs.h" +#include "fs/proc.h" +#include "fs/path.h" + +static int proc_lookup(const char *path, struct proc_entry *entry) { + entry->meta = &proc_root; + char component[MAX_NAME + 1]; + int err = 0; + while (path_next_component(&path, component, &err)) { + if (!S_ISDIR(proc_entry_mode(entry))) { + err = _ENOTDIR; + break; + } + + unsigned long index = 0; + struct proc_entry next_entry = {0}; + char entry_name[MAX_NAME]; + while (proc_dir_read(entry, &index, &next_entry)) { + // tack on some dynamically generated attributes + if (next_entry.meta->parent == NULL) + next_entry.meta->parent = entry->meta; + else + // this asserts that an entry has a unique parent + assert(next_entry.meta->parent == entry->meta); + if (next_entry.meta->inode == 0) + next_entry.meta->inode = index + 1; + + proc_entry_getname(&next_entry, entry_name); + if (strcmp(entry_name, component) == 0) + goto found; + proc_entry_cleanup(&next_entry); + } + err = _ENOENT; + break; +found: + proc_entry_cleanup(entry); + *entry = next_entry; + } + if (err < 0) + proc_entry_cleanup(entry); + return err; +} + +extern const struct fd_ops procfs_fdops; + +static struct fd *proc_open(struct mount *UNUSED(mount), const char *path, int UNUSED(flags), int UNUSED(mode)) { + struct proc_entry entry = {0}; + int err = proc_lookup(path, &entry); + if (err < 0) + return ERR_PTR(err); + struct fd *fd = fd_create(&procfs_fdops); + fd->proc.entry = entry; + fd->proc.data.data = NULL; + return fd; +} + +static int proc_getpath(struct fd *fd, char *buf) { + char *p = buf + MAX_PATH - 1; + size_t n = 0; + p[0] = '\0'; + struct proc_entry entry = fd->proc.entry; + while (entry.meta != &proc_root) { + char component[MAX_NAME]; + proc_entry_getname(&entry, component); + size_t component_len = strlen(component) + 1; // plus one for the slash + p -= component_len; + n += component_len; + *p = '/'; + memcpy(p + 1, component, component_len - 1); + entry.meta = entry.meta->parent; + } + memmove(buf, p, n + 1); // plus one for the null + return 0; +} + +static int proc_stat(struct mount *UNUSED(mount), const char *path, struct statbuf *stat) { + struct proc_entry entry = {0}; + int err = proc_lookup(path, &entry); + if (err < 0) + return err; + int ret = proc_entry_stat(&entry, stat); + proc_entry_cleanup(&entry); + return ret; +} + +static int proc_fstat(struct fd *fd, struct statbuf *stat) { + return proc_entry_stat(&fd->proc.entry, stat); +} + +static int proc_refresh_data(struct fd *fd) { + mode_t_ mode = proc_entry_mode(&fd->proc.entry); + if (S_ISDIR(mode)) + return _EISDIR; + assert(S_ISREG(mode)); + + if (fd->proc.data.data == NULL) { + fd->proc.data.capacity = 4096; + fd->proc.data.data = malloc(fd->proc.data.capacity); // default size + } + fd->proc.data.size = 0; + struct proc_entry *entry = &fd->proc.entry; + int err = entry->meta->show(entry, &fd->proc.data); + if (err < 0) + return err; + return 0; +} + +static off_t_ proc_seek(struct fd *fd, off_t_ off, int whence) { + struct proc_entry *entry = &fd->proc.entry; + if (entry->meta->seek != NULL) { + qword_t position = fd->offset; + int err = entry->meta->seek(entry, &position, off, whence); + if (err < 0) + return err; + fd->offset = position; + return (off_t_) position; + } + + int err = proc_refresh_data(fd); + if (err < 0) + return err; + + err = generic_seek(fd, off, whence, fd->proc.data.size); + if (err < 0) + return err; + + return fd->offset; +} + +static ssize_t proc_pread(struct fd *fd, void *buf, size_t bufsize, off_t off) { + if (fd->proc.entry.meta->pread) { + struct proc_data data = {buf, bufsize, bufsize}; + return fd->proc.entry.meta->pread(&fd->proc.entry, &data, off); + } + + int err = proc_refresh_data(fd); + if (err < 0) + return err; + + const char *data = fd->proc.data.data; + assert(data != NULL); + + size_t remaining = fd->proc.data.size - off; + if ((size_t) off > fd->proc.data.size) + remaining = 0; + size_t n = bufsize; + if (n > remaining) + n = remaining; + + memcpy(buf, data + off, n); + return n; +} + +static void proc_buf_write(struct proc_data *buf, const void *data, size_t size, size_t off) { + assert(off <= buf->size); + size_t tidemark = off + size; + if (tidemark > buf->capacity) { + size_t new_capacity = buf->capacity + 1; + while (tidemark > new_capacity) + new_capacity *= 2; + char *new_data = realloc(buf->data, new_capacity); + if (new_data == NULL) { + // just give up, error reporting is a pain + return; + } + buf->data = new_data; + buf->capacity = new_capacity; + } + assert(tidemark <= buf->capacity); + memcpy(buf->data + off, data, size); + if (tidemark > buf->size) { + buf->size = tidemark; + } +} + +static ssize_t proc_pwrite(struct fd *fd, const void *buf, size_t bufsize, off_t off) { + mode_t_ mode = proc_entry_mode(&fd->proc.entry); + if (S_ISDIR(mode)) + return _EISDIR; + assert(S_ISREG(mode)); + + if (fd->proc.entry.meta->pwrite) { + struct proc_data data = {(char *) buf, bufsize, bufsize}; + return fd->proc.entry.meta->pwrite(&fd->proc.entry, &data, off); + } + + if (!fd->proc.entry.meta->update) { + return _EPERM; + } + + struct proc_data data = {(char *)buf, bufsize, bufsize}; + fd->proc.entry.meta->update(&fd->proc.entry, &data); + + return bufsize; +} + +static int proc_readdir(struct fd *fd, struct dir_entry *entry) { + struct proc_entry proc_entry = {0}; + bool any_left = proc_dir_read(&fd->proc.entry, &fd->offset, &proc_entry); + if (!any_left) + return 0; + proc_entry_getname(&proc_entry, entry->name); + entry->inode = proc_entry.meta->inode; + entry->type = dirent_type_from_mode(proc_entry_mode(&proc_entry)); + proc_entry_cleanup(&proc_entry); + return 1; +} + +static int proc_close(struct fd *fd) { + if (fd->proc.data.data != NULL) + free(fd->proc.data.data); + proc_entry_cleanup(&fd->proc.entry); + return 0; +} + +const struct fd_ops procfs_fdops = { + .pread = proc_pread, + .pwrite = proc_pwrite, + .lseek = proc_seek, + .readdir = proc_readdir, + .close = proc_close, +}; + +static ssize_t proc_readlink(struct mount *UNUSED(mount), const char *path, char *buf, size_t bufsize) { + struct proc_entry entry = {0}; + int err = proc_lookup(path, &entry); + if (err < 0) + return err; + if (!S_ISLNK(proc_entry_mode(&entry))) { + proc_entry_cleanup(&entry); + return _EINVAL; + } + + char target[MAX_PATH + 1]; + err = entry.meta->readlink(&entry, target); + proc_entry_cleanup(&entry); + if (err < 0) + return err; + if (bufsize > strlen(target)) + bufsize = strlen(target); + memcpy(buf, target, bufsize); + return bufsize; +} + +static int proc_unlink(struct mount *UNUSED(mount), const char *path) { + struct proc_entry entry = {0}; + int err = proc_lookup(path, &entry); + if (err < 0) + return err; + err = _EPERM; + if (entry.meta->unlink) + err = entry.meta->unlink(&entry); + proc_entry_cleanup(&entry); + return err; +} + +void proc_buf_append(struct proc_data *buf, const void *data, size_t size) { + proc_buf_write(buf, data, size, buf->size); +} + +void proc_printf(struct proc_data *buf, const char *format, ...) { + char data[4096]; + va_list args; + va_start(args, format); + size_t size = vsnprintf(data, sizeof(data), format, args); + va_end(args); + proc_buf_append(buf, data, size); +} + +const struct fs_ops procfs = { + .name = "proc", .magic = 0x9fa0, + .open = proc_open, + .getpath = proc_getpath, + .stat = proc_stat, + .fstat = proc_fstat, + .readlink = proc_readlink, + .unlink = proc_unlink, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc.h new file mode 100644 index 0000000000..320a5cccd9 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc.h @@ -0,0 +1,83 @@ +#ifndef FS_PROC_H +#define FS_PROC_H + +#include "fs/stat.h" +#include "misc.h" + +struct proc_entry { + struct proc_dir_entry *meta; + unsigned long index; + char **child_names; + char *name; + pid_t_ pid; + sdword_t fd; // typedef might not have been read yet +}; + +struct proc_data { + char *data; + size_t size; + size_t capacity; +}; + +struct proc_dir_entry { + const char *name; + mode_t_ mode; + + // file with dynamic name + void (*getname)(struct proc_entry *entry, char *buf); + + // file with custom show data function + int (*show)(struct proc_entry *entry, struct proc_data *data); + + // file with a custom write function + int (*update)(struct proc_entry *entry, struct proc_data *data); + + // file with custom pread functionality + ssize_t (*pread)(struct proc_entry *entry, struct proc_data *data, off_t off); + + // file with custom pwrite functionality + ssize_t (*pwrite)(struct proc_entry *entry, struct proc_data *data, off_t off); + + // file with custom seek semantics; position contains the raw signed offset bits + int (*seek)(struct proc_entry *entry, qword_t *position, off_t_ off, int whence); + + // symlink + int (*readlink)(struct proc_entry *entry, char *buf); + + // remove + int (*unlink)(struct proc_entry *entry); + + // directory with static list + struct proc_children *children; + + // directory with dynamic contents + bool (*readdir)(struct proc_entry *entry, unsigned long *index, struct proc_entry *next_entry); + + struct proc_dir_entry *parent; + int inode; +}; + +struct proc_children { + size_t count; + struct proc_dir_entry entries[]; +}; + +#define PROC_CHILDREN(...) { .count = sizeof((struct proc_dir_entry[])__VA_ARGS__) / sizeof(struct proc_dir_entry), .entries = __VA_ARGS__ } + +extern struct proc_dir_entry proc_root; +extern struct proc_dir_entry proc_pid; +extern struct proc_children proc_ish_children; + +mode_t_ proc_entry_mode(struct proc_entry *entry); +void proc_entry_getname(struct proc_entry *entry, char *buf); +int proc_entry_stat(struct proc_entry *entry, struct statbuf *stat); +void proc_entry_cleanup(struct proc_entry *entry); + +void free_string_array(char **array); + +bool proc_dir_read(struct proc_entry *entry, unsigned long *index, struct proc_entry *next_entry); + +void proc_buf_append(struct proc_data *buf, const void *data, size_t size); +void proc_printf(struct proc_data *buf, const char *format, ...); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/entry.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/entry.c new file mode 100644 index 0000000000..288a1726df --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/entry.c @@ -0,0 +1,76 @@ +#include <sys/stat.h> +#include <string.h> +#include "fs/stat.h" +#include "fs/proc.h" +#include "kernel/task.h" + +mode_t_ proc_entry_mode(struct proc_entry *entry) { + mode_t_ mode = entry->meta->mode; + if ((mode & S_IFMT) == 0) + mode |= S_IFREG; + if ((mode & 0777) == 0) { + if (S_ISREG(mode)) + mode |= 0444; + else if (S_ISDIR(mode)) + mode |= 0555; + else if (S_ISLNK(mode)) + mode |= 0777; + } + return mode; +} + +int proc_entry_stat(struct proc_entry *entry, struct statbuf *stat) { + memset(stat, 0, sizeof(*stat)); + stat->mode = proc_entry_mode(entry); + + lock(&pids_lock); + struct task *task = pid_get_task(entry->pid); + + if (task != NULL) { + stat->uid = task->uid; + stat->gid = task->gid; + } // else the memset above will have initialized memory to zero, which is the root uid/gid + + unlock(&pids_lock); + + stat->inode = entry->meta->inode | entry->pid << 16 | (uint64_t) entry->fd << 48; + return 0; +} + +void proc_entry_getname(struct proc_entry *entry, char *buf) { + if (entry->meta->getname) + entry->meta->getname(entry, buf); + else if (entry->meta->name) + strcpy(buf, entry->meta->name); + else + assert(!"missing name in proc entry"); +} + +bool proc_dir_read(struct proc_entry *entry, unsigned long *index, struct proc_entry *next_entry) { + if (entry->meta->readdir) + return entry->meta->readdir(entry, index, next_entry); + + if (entry->meta->children) { + if (*index >= entry->meta->children->count) + return false; + next_entry->meta = &entry->meta->children->entries[*index]; + next_entry->pid = entry->pid; + (*index)++; + return true; + } + assert(!"read from invalid proc directory"); +} + +void free_string_array(char **array) { + for (int i = 0; array[i] != NULL; i++) + free(array[i]); + free(array); +} + +void proc_entry_cleanup(struct proc_entry *entry) { + if (entry->name != NULL) + free(entry->name); + if (entry->child_names != NULL) + free_string_array(entry->child_names); + *entry = (struct proc_entry) {0}; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/ish.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/ish.c new file mode 100644 index 0000000000..cd4f9ea629 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/ish.c @@ -0,0 +1,169 @@ +#include "fs/proc.h" +#include "fs/proc/ish.h" +#include "kernel/errno.h" +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> + +const char *proc_ish_version = ""; +char **(*get_all_defaults_keys)(void); +char *(*get_friendly_name)(const char *name); +char *(*get_underlying_name)(const char *name); +bool (*get_user_default)(const char *name, char **buffer, size_t *size); +bool (*set_user_default)(const char *name, char *buffer, size_t size); +bool (*remove_user_default)(const char *name); +char *(*get_documents_directory)(void); + +static int proc_ish_show_colors(struct proc_entry *UNUSED(entry), struct proc_data *buf) { + proc_printf(buf, + "\x1B[30m" "iSH" "\x1B[39m " + "\x1B[31m" "iSH" "\x1B[39m " + "\x1B[32m" "iSH" "\x1B[39m " + "\x1B[33m" "iSH" "\x1B[39m " + "\x1B[34m" "iSH" "\x1B[39m " + "\x1B[35m" "iSH" "\x1B[39m " + "\x1B[36m" "iSH" "\x1B[39m " + "\x1B[37m" "iSH" "\x1B[39m" "\n\x1B[7m" + "\x1B[40m" "iSH" "\x1B[39m " + "\x1B[41m" "iSH" "\x1B[39m " + "\x1B[42m" "iSH" "\x1B[39m " + "\x1B[43m" "iSH" "\x1B[39m " + "\x1B[44m" "iSH" "\x1B[39m " + "\x1B[45m" "iSH" "\x1B[39m " + "\x1B[46m" "iSH" "\x1B[39m " + "\x1B[47m" "iSH" "\x1B[39m" "\x1B[0m\x1B[1m\n" + "\x1B[90m" "iSH" "\x1B[39m " + "\x1B[91m" "iSH" "\x1B[39m " + "\x1B[92m" "iSH" "\x1B[39m " + "\x1B[93m" "iSH" "\x1B[39m " + "\x1B[94m" "iSH" "\x1B[39m " + "\x1B[95m" "iSH" "\x1B[39m " + "\x1B[96m" "iSH" "\x1B[39m " + "\x1B[97m" "iSH" "\x1B[39m" "\n\x1B[7m" + "\x1B[100m" "iSH" "\x1B[39m " + "\x1B[101m" "iSH" "\x1B[39m " + "\x1B[102m" "iSH" "\x1B[39m " + "\x1B[103m" "iSH" "\x1B[39m " + "\x1B[104m" "iSH" "\x1B[39m " + "\x1B[105m" "iSH" "\x1B[39m " + "\x1B[106m" "iSH" "\x1B[39m " + "\x1B[107m" "iSH" "\x1B[39m" "\x1B[0m\n" + ); + return 0; +} + +static int proc_ish_show_documents(struct proc_entry *UNUSED(entry), struct proc_data *buf) { + if (get_documents_directory == NULL) { + proc_printf(buf, "\n"); + return 0; + } + char *directory = get_documents_directory(); + proc_printf(buf, "%s\n", directory); + free(directory); + return 0; +} + +static void proc_ish_defaults_getname(struct proc_entry *entry, char *buf) { + strcpy(buf, entry->name); +} + +static int proc_ish_defaults_readlink(struct proc_entry *entry, char *buf) { + char *name = get_underlying_name(entry->name); + sprintf(buf, "../.defaults/%s", name); + free(name); + return 0; +} + +static int proc_ish_underlying_defaults_show(struct proc_entry *entry, struct proc_data *data) { + size_t size; + char *buffer; + if (get_user_default == NULL || !get_user_default(entry->name, &buffer, &size)) + return _EIO; + proc_buf_append(data, buffer, size); + free(buffer); + return 0; +} + +static int proc_ish_underlying_defaults_update(struct proc_entry *entry, struct proc_data *data) { + if (set_user_default == NULL || !set_user_default(entry->name, data->data, data->size)) + return _EIO; + return 0; +} + +static int proc_ish_underlying_defaults_unlink(struct proc_entry *entry) { + return (remove_user_default != NULL && remove_user_default(entry->name)) ? 0 : _EIO; +} + +static int proc_ish_defaults_unlink(struct proc_entry *entry) { + char *name = get_underlying_name(entry->name); + int err = remove_user_default(name) ? 0 : _EIO; + free(name); + return err; +} + +struct proc_dir_entry proc_ish_underlying_defaults_fd = { NULL, + .getname = proc_ish_defaults_getname, + .show = proc_ish_underlying_defaults_show, + .update = proc_ish_underlying_defaults_update, + .unlink = proc_ish_underlying_defaults_unlink, +}; +struct proc_dir_entry proc_ish_defaults_fd = { NULL, S_IFLNK, + .getname = proc_ish_defaults_getname, + .readlink = proc_ish_defaults_readlink, + .unlink = proc_ish_defaults_unlink, +}; + +static void get_child_names(struct proc_entry *entry, unsigned long index) { + if (index == 0 || entry->child_names == NULL) { + if (entry->child_names != NULL) + free_string_array(entry->child_names); + if (get_all_defaults_keys == NULL) { + entry->child_names = NULL; + } else { + entry->child_names = get_all_defaults_keys(); + } + } +} + +static bool proc_ish_underlying_defaults_readdir(struct proc_entry *entry, unsigned long *index, struct proc_entry *next_entry) { + get_child_names(entry, *index); + if (entry->child_names == NULL || entry->child_names[*index] == NULL) + return false; + next_entry->meta = &proc_ish_underlying_defaults_fd; + next_entry->name = strdup(entry->child_names[*index]); + (*index)++; + return true; +} + +static bool proc_ish_defaults_readdir(struct proc_entry *entry, unsigned long *index, struct proc_entry *next_entry) { + get_child_names(entry, *index); + char *friendly_name; + do { + const char *name = NULL; + if (entry->child_names != NULL) { + name = entry->child_names[*index]; + } + if (name == NULL) + return false; + friendly_name = get_friendly_name(name); + (*index)++; + } while (friendly_name == NULL); + next_entry->meta = &proc_ish_defaults_fd; + next_entry->name = friendly_name; + return true; +} + +static int proc_ish_show_version(struct proc_entry *UNUSED(entry), struct proc_data *buf) { + proc_printf(buf, "%s\n", proc_ish_version); + return 0; +} + +struct proc_children proc_ish_children = PROC_CHILDREN({ + {"colors", .show = proc_ish_show_colors}, + {".defaults", S_IFDIR, .readdir = proc_ish_underlying_defaults_readdir}, + {"defaults", S_IFDIR, .readdir = proc_ish_defaults_readdir}, + {"documents", .show = proc_ish_show_documents}, + {"version", .show = proc_ish_show_version}, +}); diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/ish.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/ish.h new file mode 100644 index 0000000000..8c9864081f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/ish.h @@ -0,0 +1,15 @@ +#include <stddef.h> +#include <stdbool.h> + +struct user_default_key { + char *name; + char *underlying_name; +}; + +extern char **(*get_all_defaults_keys)(void); +extern char *(*get_friendly_name)(const char *name); +extern char *(*get_underlying_name)(const char *name); +extern bool (*get_user_default)(const char *name, char **buffer, size_t *size); +extern bool (*set_user_default)(const char *name, char *buffer, size_t size); +extern bool (*remove_user_default)(const char *name); +extern char *(*get_documents_directory)(void); diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/net.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/net.c new file mode 100644 index 0000000000..2d7fe9a0a0 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/net.c @@ -0,0 +1,42 @@ +#include <stddef.h> +#include <stdbool.h> +#include "fs/proc.h" + +// /proc/net/dev - network device statistics +// Format: Interface|Receive|Transmit +static int proc_show_net_dev(struct proc_entry *UNUSED(entry), struct proc_data *buf) { + // Header + proc_printf(buf, "Inter-| Receive | Transmit\n"); + proc_printf(buf, " face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed\n"); + + // For iSH emulator, we report minimal network stats + // lo (loopback) interface + proc_printf(buf, " lo: 0 0 0 0 0 0 0 0"); + proc_printf(buf, " 0 0 0 0 0 0 0 0\n"); + + // eth0 (dummy ethernet) - some programs expect this + proc_printf(buf, " eth0: 0 0 0 0 0 0 0 0"); + proc_printf(buf, " 0 0 0 0 0 0 0 0\n"); + + return 0; +} + +// /proc/net directory entries +struct proc_dir_entry proc_net_entries[] = { + {"dev", .show = proc_show_net_dev}, +}; +#define PROC_NET_LEN (sizeof(proc_net_entries)/sizeof(proc_net_entries[0])) + +static bool proc_net_readdir(struct proc_entry *UNUSED(entry), unsigned long *index, struct proc_entry *next_entry) { + if (*index < PROC_NET_LEN) { + *next_entry = (struct proc_entry) {&proc_net_entries[*index], *index, NULL, NULL, 0, 0}; + (*index)++; + return true; + } + return false; +} + +// Exported /proc/net directory entry +struct proc_children proc_net_children = PROC_CHILDREN({ + {"dev", .show = proc_show_net_dev}, +}); diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/pid.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/pid.c new file mode 100644 index 0000000000..71167e54eb --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/pid.c @@ -0,0 +1,399 @@ +#include <string.h> +#include <sys/stat.h> +#include "kernel/memory.h" +#include "kernel/calls.h" +#include "fs/proc.h" +#include "fs/fd.h" +#include "fs/tty.h" +#include "kernel/fs.h" +#include "kernel/vdso.h" +#include "util/sync.h" + +static void proc_pid_getname(struct proc_entry *entry, char *buf) { + sprintf(buf, "%d", entry->pid); +} + +static struct task *proc_get_task(struct proc_entry *entry) { + lock(&pids_lock); + struct task *task = pid_get_task(entry->pid); + // Also reject tasks that are mid-exit: sighand/group may already be freed. + if (task != NULL && (task->exiting || task->sighand == NULL || task->group == NULL)) + task = NULL; + if (task == NULL) + unlock(&pids_lock); + return task; +} +static void proc_put_task(struct task *UNUSED(task)) { + unlock(&pids_lock); +} + +static int proc_pid_stat_show(struct proc_entry *entry, struct proc_data *buf) { + struct task *task = proc_get_task(entry); + if (task == NULL) + return _ESRCH; + lock(&task->general_lock); + lock(&task->group->lock); + lock(&task->sighand->lock); + + proc_printf(buf, "%d ", task->pid); + proc_printf(buf, "(%.16s) ", task->comm); + proc_printf(buf, "%c ", + task->zombie ? 'Z' : + task->group->stopped ? 'T' : + 'R'); // I have no visibility into sleep state at the moment + proc_printf(buf, "%d ", task->parent ? task->parent->pid : 0); + proc_printf(buf, "%d ", task->group->pgid); + proc_printf(buf, "%d ", task->group->sid); + struct tty *tty = task->group->tty; + proc_printf(buf, "%d ", tty ? dev_make(tty->driver->major, tty->num) : 0); + proc_printf(buf, "%d ", tty ? tty->fg_group : 0); + proc_printf(buf, "%u ", 0); // flags + + // page faults (no data available) + proc_printf(buf, "%lu ", 0l); // minor faults + proc_printf(buf, "%lu ", 0l); // children minor faults + proc_printf(buf, "%lu ", 0l); // major faults + proc_printf(buf, "%lu ", 0l); // children major faults + + // values that would be returned from getrusage + // finding these for a given process isn't too easy + proc_printf(buf, "%lu ", 0l); // user time + proc_printf(buf, "%lu ", 0l); // system time + proc_printf(buf, "%ld ", 0l); // children user time + proc_printf(buf, "%ld ", 0l); // children system time + + proc_printf(buf, "%ld ", 20l); // priority (not adjustable) + proc_printf(buf, "%ld ", 0l); // nice (also not adjustable) + proc_printf(buf, "%ld ", list_size(&task->group->threads)); + proc_printf(buf, "%ld ", 0l); // itimer value (deprecated, always 0) + proc_printf(buf, "%llu ", (unsigned long long) task->start_time_ticks); + + proc_printf(buf, "%lu ", 0l); // vsize + proc_printf(buf, "%ld ", 0l); // rss + proc_printf(buf, "%lu ", 0l); // rss limit + + // Fields that require debugger-only/kernel-internal address details. + proc_printf(buf, "%lu ", 0l); // startcode + proc_printf(buf, "%lu ", 0l); // endcode + proc_printf(buf, "%lu ", task->mm ? task->mm->stack_start : 0); + proc_printf(buf, "%lu ", 0l); // kstkesp + proc_printf(buf, "%lu ", 0l); // kstkeip + + proc_printf(buf, "%lu ", (unsigned long) task->pending & 0xffffffff); + proc_printf(buf, "%lu ", (unsigned long) task->blocked & 0xffffffff); + uint32_t ignored = 0; + uint32_t caught = 0; + for (int i = 0; i < 32; i++) { + if (task->sighand->action[i].handler == SIG_IGN_) + ignored |= 1l << i; + else if (task->sighand->action[i].handler != SIG_DFL_) + caught |= 1l << i; + } + proc_printf(buf, "%lu ", (unsigned long) ignored); + proc_printf(buf, "%lu ", (unsigned long) caught); + + proc_printf(buf, "%lu ", 0l); // wchan (wtf) + proc_printf(buf, "%lu ", 0l); // nswap + proc_printf(buf, "%lu ", 0l); // cnswap + proc_printf(buf, "%d ", task->exit_signal); + proc_printf(buf, "%d", 0); // processor + // that's enough for now + proc_printf(buf, "\n"); + + unlock(&task->sighand->lock); + unlock(&task->group->lock); + unlock(&task->general_lock); + proc_put_task(task); + return 0; +} + +static int proc_pid_statm_show(struct proc_entry *entry, struct proc_data *buf) { + struct task *task = proc_get_task(entry); + if (task == NULL) + return _ESRCH; + + proc_printf(buf, "%lu ", 0); // total vm size + proc_printf(buf, "%lu ", 0); // vm resident size + proc_printf(buf, "%lu ", 0); // resident shared + proc_printf(buf, "%lu ", 0); // text + proc_printf(buf, "%lu ", 0); // lib (always 0 since linux 2.6) + proc_printf(buf, "%lu ", 0); // data + stack + proc_printf(buf, "%lu ", 0); // dirty (always 0 since linux 2.6) + proc_printf(buf, "\n"); + + proc_put_task(task); + return 0; +} + +static int proc_pid_auxv_show(struct proc_entry *entry, struct proc_data *buf) { + struct task *task = proc_get_task(entry); + if (task == NULL) + return _ESRCH; + int err = 0; + lock(&task->general_lock); + if (task->mm == NULL) + goto out_free_task; + + size_t size = task->mm->auxv_end - task->mm->auxv_start; + char *data = malloc(size); + if (data == NULL) { + err = _ENOMEM; + goto out_free_task; + } + if (user_read_task(task, task->mm->auxv_start, data, size) == 0) + proc_buf_append(buf, data, size); + free(data); + +out_free_task: + unlock(&task->general_lock); + proc_put_task(task); + return err; +} + +static int proc_pid_cmdline_show(struct proc_entry *entry, struct proc_data *buf) { + struct task *task = proc_get_task(entry); + if (task == NULL) + return _ESRCH; + int err = 0; + lock(&task->general_lock); + if (task->mm == NULL) + goto out_free_task; + + size_t size = task->mm->argv_end - task->mm->argv_start; + char *data = malloc(size); + if (data == NULL) { + err = _ENOMEM; + goto out_free_task; + } + if (user_read_task(task, task->mm->argv_start, data, size) == 0) + proc_buf_append(buf, data, size); + free(data); + +out_free_task: + unlock(&task->general_lock); + proc_put_task(task); + return err; +} + +void proc_maps_dump(struct task *task, struct proc_data *buf) { + struct mem *mem = task->mem; + if (mem == NULL) + return; + + read_wrlock(&mem->lock); + page_t page = 0; + while (page < MEM_PAGES) { + // find a region + while (page < MEM_PAGES && mem_pt(mem, page) == NULL) { + mem_next_page(mem, &page); + } + if (page >= MEM_PAGES) + break; + page_t start = page; + struct pt_entry *start_pt = mem_pt(mem, start); + struct data *data = start_pt->data; + + // find the end of said region + while (page < MEM_PAGES) { + struct pt_entry *pt = mem_pt(mem, page); + if (pt == NULL) + break; + if ((pt->flags & P_RWX) != (start_pt->flags & P_RWX)) + break; + // region continues if data is the same or both are anonymous + if (!(pt->data == data || (pt->flags & P_ANONYMOUS && start_pt->flags & P_ANONYMOUS))) + break; + mem_next_page(mem, &page); + } + page_t end = page; + + // output info + char path[MAX_PATH] = ""; + if (start_pt->flags & P_GROWSDOWN) { + strcpy(path, "[stack]"); + } else if (data->name != NULL) { + strcpy(path, data->name); + } else if (data->fd != NULL) { + generic_getpath(start_pt->data->fd, path); + } +#ifdef GUEST_ARM64 + proc_printf(buf, "%012llx-%012llx %c%c%c%c %08lx 00:00 %-10d %s\n", + (unsigned long long)(start << PAGE_BITS), + (unsigned long long)(end << PAGE_BITS), +#else + proc_printf(buf, "%08x-%08x %c%c%c%c %08lx 00:00 %-10d %s\n", + start << PAGE_BITS, end << PAGE_BITS, +#endif + start_pt->flags & P_READ ? 'r' : '-', + start_pt->flags & P_WRITE ? 'w' : '-', + start_pt->flags & P_EXEC ? 'x' : '-', + start_pt->flags & P_SHARED ? '-' : 'p', + (unsigned long) data->file_offset, // offset + 0, // inode + path); + } + read_wrunlock(&mem->lock); +} + +static int proc_pid_maps_show(struct proc_entry *entry, struct proc_data *buf) { + struct task *task = proc_get_task(entry); + if (task == NULL) + return _ESRCH; + proc_maps_dump(task, buf); + proc_put_task(task); + return 0; +} + +static ssize_t proc_pid_mem_pread(struct proc_entry *entry, struct proc_data *buf, off_t offset) { + struct task *task = proc_get_task(entry); + if (task == NULL) + return _ESRCH; + int result = user_read_task(task, (addr_t)offset, buf->data, buf->size); + proc_put_task(task); + return result ? -1 : buf->size; +} + +static ssize_t proc_pid_mem_pwrite(struct proc_entry *entry, struct proc_data *buf, off_t offset) { + struct task *task = proc_get_task(entry); + if (task == NULL) + return _ESRCH; + int result = user_write_task_ptrace(task, (addr_t)offset, buf->data, buf->size); + proc_put_task(task); + return result ? -1 : buf->size; +} + +static int proc_pid_mem_seek(struct proc_entry *UNUSED(entry), qword_t *position, + off_t_ off, int whence) { + if (whence == LSEEK_SET) + *position = (qword_t) off; + else if (whence == LSEEK_CUR) + *position += (qword_t) off; + else + return _EINVAL; + return 0; +} + + +static struct proc_dir_entry proc_pid_fd; + +static bool proc_pid_fd_readdir(struct proc_entry *entry, unsigned long *index, struct proc_entry *next_entry) { + struct task *task = proc_get_task(entry); + // Task exited while its /proc/<pid>/fd dir was being iterated (e.g. + // `find /proc` racing short-lived children). This function returns bool — + // the old `return _ESRCH` here (-3) read as TRUE, so proc_readdir consumed + // a next_entry that was never filled in (meta == NULL) and crashed in + // proc_entry_getname (EXC_BAD_ACCESS at 0x10). No task = no more entries. + if (task == NULL) + return false; + // Retain the fdtable, then drop pids_lock before taking files->lock. Other + // paths take those locks in the opposite order, so overlapping them here + // can deadlock concurrent /proc/<pid>/fd scans. + struct fdtable *files = task->files; + files->refcount++; + proc_put_task(task); + lock(&files->lock); + while (*index < files->size && files->files[*index] == NULL) + (*index)++; + fd_t f = (*index)++; + bool any_left = (unsigned) f < files->size; + unlock(&files->lock); + fdtable_release(files); + *next_entry = (struct proc_entry) {&proc_pid_fd, .pid = entry->pid, .fd = f}; + return any_left; +} + +static void proc_pid_fd_getname(struct proc_entry *entry, char *buf) { + sprintf(buf, "%d", entry->fd); +} + +static int proc_pid_fd_readlink(struct proc_entry *entry, char *buf) { + struct task *task = proc_get_task(entry); + if (task == NULL) + return _ESRCH; + // Retain the fd under files->lock, then drop BOTH files->lock and + // pids_lock (held by proc_get_task) before calling generic_getpath. + // getpath can take other subsystem locks (mounts, real fs), and holding + // pids_lock across it created a lock-ordering hazard against paths that + // take those locks first and then pids_lock — an intermittent deadlock + // during claude-cli startup when 20+ bun worker threads all scan + // /proc/self/fd concurrently. Also: fd may be NULL if another thread + // closed the descriptor (return ENOENT, not a host crash). + lock(&task->files->lock); + struct fd *fd = fdtable_get(task->files, entry->fd); + if (fd != NULL) + fd = fd_retain(fd); + unlock(&task->files->lock); + proc_put_task(task); // releases pids_lock + if (fd == NULL) + return _ENOENT; + int err = generic_getpath(fd, buf); + fd_close(fd); + return err; +} + +static int proc_pid_exe_readlink(struct proc_entry *entry, char *buf) { + struct task *task = proc_get_task(entry); + if (task == NULL) + return _ESRCH; + lock(&task->general_lock); + int err; + if (task->mm == NULL || task->mm->exefile == NULL) + err = _ENOENT; + else + err = generic_getpath(task->mm->exefile, buf); + unlock(&task->general_lock); + proc_put_task(task); + return err; +} + +static void proc_pid_task_getname(struct proc_entry *entry, char *buf) { + sprintf(buf, "%d", entry->pid); +} + +static int proc_pid_task_readlink(struct proc_entry *entry, char *buf) { + sprintf(buf, "/proc/%d", entry->pid); + return 0; +} + +static struct proc_dir_entry proc_pid_task; + +static bool proc_pid_task_readdir(struct proc_entry *entry, unsigned long *index, struct proc_entry *next_entry) { + // TODO: Expose all threads + *next_entry = (struct proc_entry) {&proc_pid_task, .pid = entry->pid}; + return !(*index)++; +} + +static int proc_pid_cwd_readlink(struct proc_entry *entry, char *buf) { + struct task *task = proc_get_task(entry); + if (task == NULL) + return _ESRCH; + lock(&task->fs->lock); + int err = generic_getpath(task->fs->pwd, buf); + unlock(&task->fs->lock); + proc_put_task(task); + return err; +} + + +struct proc_children proc_pid_children = PROC_CHILDREN({ + {"auxv", .show = proc_pid_auxv_show}, + {"cmdline", .show = proc_pid_cmdline_show}, + {"cwd", S_IFLNK, .readlink = proc_pid_cwd_readlink}, + {"exe", S_IFLNK, .readlink = proc_pid_exe_readlink}, + {"fd", S_IFDIR, .readdir = proc_pid_fd_readdir}, + {"maps", .show = proc_pid_maps_show}, + {"mem", .pread = proc_pid_mem_pread, .pwrite = proc_pid_mem_pwrite, + .seek = proc_pid_mem_seek}, + {"stat", .show = proc_pid_stat_show}, + {"statm", .show = proc_pid_statm_show}, + {"task", S_IFDIR, .readdir = proc_pid_task_readdir}, +}); + +struct proc_dir_entry proc_pid = {NULL, S_IFDIR, + .children = &proc_pid_children, .getname = proc_pid_getname}; + +static struct proc_dir_entry proc_pid_fd = {NULL, S_IFLNK, + .getname = proc_pid_fd_getname, .readlink = proc_pid_fd_readlink}; + +static struct proc_dir_entry proc_pid_task = {NULL, S_IFLNK, + .getname = proc_pid_task_getname, .readlink = proc_pid_task_readlink}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/root.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/root.c new file mode 100644 index 0000000000..3122bdf4b1 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/proc/root.c @@ -0,0 +1,181 @@ +#include <sys/stat.h> +#include <inttypes.h> +#include <stdatomic.h> +#include <string.h> +#include "kernel/calls.h" +#include "fs/proc.h" +#include "platform/platform.h" + +static int proc_show_version(struct proc_entry *UNUSED(entry), struct proc_data *buf) { + struct uname uts; + do_uname(&uts); + proc_printf(buf, "%s version %s %s\n", uts.system, uts.release, uts.version); + return 0; +} + +static int proc_show_stat(struct proc_entry *UNUSED(entry), struct proc_data *buf) { + struct cpu_usage usage = get_cpu_usage(); + proc_printf(buf, "cpu %"PRIu64" %"PRIu64" %"PRIu64" %"PRIu64" 0 0 0 0 0 0\n", usage.user_ticks, usage.nice_ticks, usage.system_ticks, usage.idle_ticks); + + // calculate btime (boot time in seconds since epoch) by subtracting uptime from current time + struct uptime_info uptime = get_uptime(); + struct timespec uptime_ts = {.tv_sec = uptime.uptime_ticks, .tv_nsec = 0}; + struct timespec boot_time = timespec_subtract(timespec_now(CLOCK_REALTIME), uptime_ts); + proc_printf(buf, "btime %ld\n", boot_time.tv_sec); + + return 0; +} + +static int proc_show_cpuinfo(struct proc_entry *UNUSED(entry), struct proc_data *buf) { + unsigned cpus = PLATFORM_GUEST_CPU_COUNT; + for (unsigned i = 0; i < cpus; i++) { + proc_printf(buf, "processor\t: %u\n", i); + proc_printf(buf, "BogoMIPS\t: 48.00\n"); + // Keep /proc/cpuinfo aligned with AT_HWCAP: report only the conservative + // baseline until optional crypto/LSE helpers are coverage-clean. + proc_printf(buf, "Features\t: fp asimd evtstrm\n"); + proc_printf(buf, "CPU implementer\t: 0x00\n"); + proc_printf(buf, "CPU architecture: 8\n"); + proc_printf(buf, "CPU variant\t: 0x0\n"); + proc_printf(buf, "CPU part\t: 0x000\n"); + proc_printf(buf, "CPU revision\t: 0\n"); + proc_printf(buf, "\n"); + } + return 0; +} + +static void show_kb(struct proc_data *buf, const char *name, uint64_t value) { + proc_printf(buf, "%s%8"PRIu64" kB\n", name, value / 1024); +} + +static int proc_show_meminfo(struct proc_entry *UNUSED(entry), struct proc_data *buf) { + struct mem_usage usage = get_mem_usage(); + // Cap reported memory to match sys_sysinfo limit. + // Reporting full host RAM (e.g. 24GB) causes V8 to set heap_size_limit=4GB + // which exhausts the emulator's limited address space. + #define MEMINFO_MAX_RAM (4ULL * 1024 * 1024 * 1024) + if (usage.total > MEMINFO_MAX_RAM) + usage.total = MEMINFO_MAX_RAM; +#if ANON_MMAP_LIMIT_PAGES > 0 + extern _Atomic long anon_page_count; + long used_pages = atomic_load(&anon_page_count); + uint64_t used_bytes = (uint64_t)(used_pages > 0 ? used_pages : 0) * 4096; + usage.free = used_bytes < usage.total ? usage.total - used_bytes : 0; +#else + if (usage.free > MEMINFO_MAX_RAM) + usage.free = MEMINFO_MAX_RAM; +#endif + show_kb(buf, "MemTotal: ", usage.total); + show_kb(buf, "MemFree: ", usage.free); + show_kb(buf, "MemShared: ", 0); + // a bunch of fields busybox top expects to see. + show_kb(buf, "Shmem: ", 0); + show_kb(buf, "Buffers: ", 0); + show_kb(buf, "Cached: ", 0); + show_kb(buf, "SwapTotal: ", 0); + show_kb(buf, "SwapFree: ", 0); + show_kb(buf, "Dirty: ", 0); + show_kb(buf, "Writeback: ", 0); + show_kb(buf, "AnonPages: ", 0); + show_kb(buf, "Mapped: ", 0); + show_kb(buf, "Slab: ", 0); + return 0; +} + +static int proc_show_uptime(struct proc_entry *UNUSED(entry), struct proc_data *buf) { + struct uptime_info uptime_info = get_uptime(); + unsigned long uptime = uptime_info.uptime_ticks; + proc_printf(buf, "%lu.00 %lu.00\n", uptime, uptime); + return 0; +} + +static int proc_readlink_self(struct proc_entry *UNUSED(entry), char *buf) { + sprintf(buf, "%d/", current->pid); + return 0; +} + +static void proc_print_escaped(struct proc_data *buf, const char *str) { + for (size_t i = 0; str[i]; i++) { + switch (str[i]) { + case '\t': case ' ': case '\\': + proc_printf(buf, "\\%03o", str[i]); + break; + default: + proc_printf(buf, "%c", str[i]); + } + } +} + +#define proc_printf_comma(buf, at_start, format, ...) do { \ + proc_printf((buf), "%s" format, *(at_start) ? "" : ",", ##__VA_ARGS__); \ + *(at_start) = false; \ +} while (0) + +static int proc_show_mounts(struct proc_entry *UNUSED(entry), struct proc_data *buf) { + struct mount *mount; + list_for_each_entry(&mounts, mount, mounts) { + const char *point = mount->point; + if (point[0] == '\0') + point = "/"; + + proc_print_escaped(buf, mount->source); + proc_printf(buf, " "); + proc_print_escaped(buf, point); + proc_printf(buf, " %s ", mount->fs->name); + bool at_start = true; + proc_printf_comma(buf, &at_start, "%s", mount->flags & MS_READONLY_ ? "ro" : "rw"); + if (mount->flags & MS_NOSUID_) + proc_printf_comma(buf, &at_start, "nosuid"); + if (mount->flags & MS_NODEV_) + proc_printf_comma(buf, &at_start, "nodev"); + if (mount->flags & MS_NOEXEC_) + proc_printf_comma(buf, &at_start, "noexec"); + if (strcmp(mount->info, "") != 0) + proc_printf_comma(buf, &at_start, "%s", mount->info); + proc_printf(buf, " 0 0\n"); + }; + return 0; +} + +// Forward declaration for /proc/net +extern struct proc_children proc_net_children; + +// in alphabetical order +struct proc_dir_entry proc_root_entries[] = { + {"cpuinfo", .show = proc_show_cpuinfo}, + {"ish", S_IFDIR, .children = &proc_ish_children}, + {"meminfo", .show = proc_show_meminfo}, + {"mounts", .show = proc_show_mounts}, + {"net", S_IFDIR, .children = &proc_net_children}, + {"self", S_IFLNK, .readlink = proc_readlink_self}, + {"stat", .show = proc_show_stat}, + {"uptime", .show = proc_show_uptime}, + {"version", .show = proc_show_version}, +}; +#define PROC_ROOT_LEN sizeof(proc_root_entries)/sizeof(proc_root_entries[0]) + +static bool proc_root_readdir(struct proc_entry *UNUSED(entry), unsigned long *index, struct proc_entry *next_entry) { + if (*index < PROC_ROOT_LEN) { + *next_entry = (struct proc_entry) {&proc_root_entries[*index], *index, NULL, NULL, 0, 0}; + (*index)++; + return true; + } + + pid_t_ pid = *index - PROC_ROOT_LEN; + if (pid <= MAX_PID) { + lock(&pids_lock); + do { + pid++; + } while (pid <= MAX_PID && pid_get_task(pid) == NULL); + unlock(&pids_lock); + if (pid > MAX_PID) + return false; + *next_entry = (struct proc_entry) {&proc_pid, .pid = pid}; + *index = pid + PROC_ROOT_LEN; + return true; + } + + return false; +} + +struct proc_dir_entry proc_root = {NULL, S_IFDIR, .readdir = proc_root_readdir}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/pty.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/pty.c new file mode 100644 index 0000000000..270d012027 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/pty.c @@ -0,0 +1,328 @@ +#include <string.h> +#include <limits.h> +#include <sys/stat.h> +#include <ctype.h> +#include "kernel/task.h" +#include "kernel/errno.h" +#include "fs/tty.h" +#include "fs/devices.h" + +extern struct tty_driver pty_slave; + +// the master holds a reference to the slave, so the slave will always be cleaned up second +// when the master cleans up it hangs up the slave, making any operation that references the master unreachable + +static void pty_slave_init_inode(struct tty *tty) { + tty->pty.uid = current->euid; + // TODO make these mount options + tty->pty.gid = current->egid; + tty->pty.perms = 0620; +} + +static int pty_master_init(struct tty *tty) { + tty->termios.iflags = 0; + tty->termios.oflags = 0; + tty->termios.lflags = 0; + + struct tty *slave = tty_alloc(&pty_slave, TTY_PSEUDO_SLAVE_MAJOR, tty->num); + slave->refcount = 1; + pty_slave.ttys[tty->num] = slave; + tty->pty.other = slave; + slave->pty.other = tty; + slave->pty.locked = true; + pty_slave_init_inode(slave); + return 0; +} + + +static void pty_hangup(struct tty *tty) { + if (tty == NULL) + return; + lock(&tty->lock); + tty_hangup(tty); + unlock(&tty->lock); +} + +static struct tty *pty_hangup_other(struct tty *tty) { + struct tty *other = tty->pty.other; + if (other == NULL) + return NULL; + pty_hangup(other); + return other; +} + +static void pty_slave_cleanup(struct tty *tty) { + pty_hangup_other(tty); +} + +static void pty_master_cleanup(struct tty *tty) { + struct tty *slave = pty_hangup_other(tty); + slave->pty.other = NULL; + tty_release(slave); +} + +static int pty_slave_open(struct tty *tty) { + if (tty->pty.other == NULL) + return _EIO; + if (tty->pty.locked) + return _EIO; + return 0; +} + +static int pty_slave_close(struct tty *tty) { + // If userland's reference count on the pty slave will go to 0, + // hang up the pty master. But the session leader may have a + // reference, and the pty master always has a reference. + if (tty->refcount - 1 == (tty->session ? 2 : 1)) { + pty_hangup_other(tty); + } + return 0; +} + +static int pty_master_ioctl(struct tty *tty, int cmd, void *arg) { + struct tty *slave = tty->pty.other; + switch (cmd) { + case TIOCSPTLCK_: + slave->pty.locked = !!*(dword_t *) arg; + break; + case TIOCGPTN_: + *(dword_t *) arg = slave->num; + break; + case TIOCPKT_: + tty->pty.packet_mode = !!*(dword_t *) arg; + break; + case TIOCGPKT_: + *(dword_t *) arg = tty->pty.packet_mode; + break; + default: + return _ENOTTY; + } + return 0; +} + +static int pty_write(struct tty *tty, const void *buf, size_t len, bool blocking) { + return tty_input(tty->pty.other, buf, len, blocking); +} + +static int pty_return_eio(struct tty *UNUSED(tty)) { + return _EIO; +} + +#define MAX_PTYS (1 << 12) + +const struct tty_driver_ops pty_master_ops = { + .init = pty_master_init, + .open = pty_return_eio, + .write = pty_write, + .ioctl = pty_master_ioctl, + .cleanup = pty_master_cleanup, +}; +DEFINE_TTY_DRIVER(pty_master, &pty_master_ops, TTY_PSEUDO_MASTER_MAJOR, MAX_PTYS); + +const struct tty_driver_ops pty_slave_ops = { + .init = pty_return_eio, + .open = pty_slave_open, + .close = pty_slave_close, + .write = pty_write, + .cleanup = pty_slave_cleanup, +}; +DEFINE_TTY_DRIVER(pty_slave, &pty_slave_ops, TTY_PSEUDO_SLAVE_MAJOR, MAX_PTYS); + +static int pty_reserve_next() { + int pty_num; + lock(&ttys_lock); + for (pty_num = 0; pty_num < MAX_PTYS; pty_num++) { + if (pty_slave.ttys[pty_num] == NULL) + break; + } + pty_slave.ttys[pty_num] = (void *) 1; // anything non-null to reserve it + unlock(&ttys_lock); + return pty_num; +} + +int ptmx_open(struct fd *fd) { + int pty_num = pty_reserve_next(); + if (pty_num == MAX_PTYS) + return _ENOSPC; + struct tty *master = tty_get(&pty_master, TTY_PSEUDO_MASTER_MAJOR, pty_num); + if (IS_ERR(master)) + return PTR_ERR(master); + return tty_open(master, fd); +} + +struct tty *pty_open_fake(struct tty_driver *driver) { + int pty_num = pty_reserve_next(); + if (pty_num == MAX_PTYS) + return ERR_PTR(_ENOSPC); + // TODO this is a bit of a hack + driver->ttys = pty_slave.ttys; + driver->limit = pty_slave.limit; + driver->major = TTY_PSEUDO_SLAVE_MAJOR; + struct tty *tty = tty_get(driver, TTY_PSEUDO_SLAVE_MAJOR, pty_num); + if (IS_ERR(tty)) + return tty; + pty_slave_init_inode(tty); + return tty; +} + +static bool isdigits(const char *str) { + for (int i = 0; str[i] != '\0'; i++) + if (!isdigit(str[i])) + return false; + return true; +} + +static const struct fd_ops devpts_fdops; + +static bool devpts_pty_exists(int pty_num) { + if (pty_num < 0 || pty_num > MAX_PTYS) + return false; + lock(&ttys_lock); + bool exists = pty_slave.ttys[pty_num] != NULL; + unlock(&ttys_lock); + return exists; +} + +// this has a slightly weird error returning convention +// I'm lucky that ENOENT is -2 and not -1 +static int devpts_get_pty_num(const char *path) { + if (strcmp(path, "") == 0) + return -1; // root + if (path[0] != '/' || path[1] == '\0' || strchr(path + 1, '/') != NULL) + return _ENOENT; + + // there's one path component here, which had better be a pty number + const char *name = path + 1; // skip the initial / + if (!isdigits(name)) + return _ENOENT; + // it's not possible to correctly use atoi + long pty_long = atol(name); + if (pty_long > INT_MAX) + return _ENOENT; + int pty_num = (int) pty_long; + if (!devpts_pty_exists(pty_num)) + return _ENOENT; + return pty_num; +} + +static struct fd *devpts_open(struct mount *UNUSED(mount), const char *path, int UNUSED(flags), int UNUSED(mode)) { + int pty_num = devpts_get_pty_num(path); + if (pty_num == _ENOENT) + return ERR_PTR(_ENOENT); + struct fd *fd = fd_create(&devpts_fdops); + fd->devpts.num = pty_num; + return fd; +} + +static int devpts_getpath(struct fd *fd, char *buf) { + if (fd->devpts.num == -1) + strcpy(buf, ""); + else + sprintf(buf, "/%d", fd->devpts.num); + return 0; +} + +static void devpts_stat_num(int pty_num, struct statbuf *stat) { + if (pty_num == -1) { + // root + stat->mode = S_IFDIR | 0755; + stat->inode = 1; + } else { + lock(&ttys_lock); + struct tty *tty = pty_slave.ttys[pty_num]; + assert(tty != NULL); + lock(&tty->lock); + + stat->mode = S_IFCHR | tty->pty.perms; + stat->uid = tty->pty.uid; + stat->gid = tty->pty.gid; + stat->inode = pty_num + 3; + stat->rdev = dev_make(TTY_PSEUDO_SLAVE_MAJOR, pty_num); + + unlock(&tty->lock); + unlock(&ttys_lock); + } +} + +static int devpts_setattr_num(int pty_num, struct attr attr) { + if (pty_num == -1) + return _EROFS; + if (attr.type == attr_size) + return _EINVAL; + + lock(&ttys_lock); + struct tty *tty = pty_slave.ttys[pty_num]; + assert(tty != NULL); + lock(&tty->lock); + + switch (attr.type) { + case attr_uid: + tty->pty.uid = attr.uid; + break; + case attr_gid: + tty->pty.gid = attr.gid; + break; + case attr_mode: + tty->pty.perms = attr.mode; + break; + } + + unlock(&tty->lock); + unlock(&ttys_lock); + return 0; +} + +static int devpts_fstat(struct fd *fd, struct statbuf *stat) { + devpts_stat_num(fd->devpts.num, stat); + return 0; +} + +static int devpts_stat(struct mount *UNUSED(mount), const char *path, struct statbuf *stat) { + int pty_num = devpts_get_pty_num(path); + if (pty_num == _ENOENT) + return _ENOENT; + devpts_stat_num(pty_num, stat); + return 0; +} + +static int devpts_setattr(struct mount *UNUSED(mount), const char *path, struct attr attr) { + int pty_num = devpts_get_pty_num(path); + if (pty_num == _ENOENT) + return _ENOENT; + devpts_setattr_num(pty_num, attr); + return 0; +} + +static int devpts_fsetattr(struct fd *fd, struct attr attr) { + devpts_setattr_num(fd->devpts.num, attr); + return 0; +} + +static int devpts_readdir(struct fd *fd, struct dir_entry *entry) { + assert(fd->devpts.num == -1); // there shouldn't be anything to list but the root + + int pty_num = fd->offset; + while (pty_num < MAX_PTYS && !devpts_pty_exists(pty_num)) + pty_num++; + if (pty_num >= MAX_PTYS) + return 0; + fd->offset = pty_num + 1; + sprintf(entry->name, "%d", pty_num); + entry->inode = pty_num + 3; + entry->type = DT_CHR; + return 1; +} + +const struct fs_ops devptsfs = { + .name = "devpts", .magic = 0x1cd1, + .open = devpts_open, + .getpath = devpts_getpath, + .stat = devpts_stat, + .fstat = devpts_fstat, + .setattr = devpts_setattr, + .fsetattr = devpts_fsetattr, +}; + +static const struct fd_ops devpts_fdops = { + .readdir = devpts_readdir, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/real.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/real.c new file mode 100644 index 0000000000..fba9f44eaa --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/real.c @@ -0,0 +1,741 @@ +#include <string.h> +#include <unistd.h> +#include <fcntl.h> +#include <errno.h> +#include <dirent.h> +#include <sys/stat.h> +#include <sys/ioctl.h> +#include <termios.h> +#include <sys/mman.h> +#include <sys/xattr.h> +#include <sys/file.h> +#include <sys/statvfs.h> +#include <poll.h> + +#include "debug.h" +#include "kernel/errno.h" +#include "kernel/calls.h" +#include "kernel/fs.h" +#include "fs/dev.h" +#include "fs/devices.h" +#include "fs/real.h" +#define ISH_INTERNAL +#include "fs/fake.h" +#include "fs/tty.h" +#include "platform/platform.h" +#include "util/fchdir.h" + +int realfs_getpath(struct fd *fd, char *buf); + +static int open_flags_real_from_fake(int flags) { + int real_flags = 0; + if (flags & O_RDONLY_) real_flags |= O_RDONLY; + if (flags & O_WRONLY_) real_flags |= O_WRONLY; + if (flags & O_RDWR_) real_flags |= O_RDWR; + if (flags & O_CREAT_) real_flags |= O_CREAT; + if (flags & O_EXCL_) real_flags |= O_EXCL; + if (flags & O_TRUNC_) real_flags |= O_TRUNC; + if (flags & O_APPEND_) real_flags |= O_APPEND; + if (flags & O_NONBLOCK_) real_flags |= O_NONBLOCK; + return real_flags; +} + +static int open_flags_fake_from_real(int flags) { + int fake_flags = 0; + if (flags & O_RDONLY) fake_flags |= O_RDONLY_; + if (flags & O_WRONLY) fake_flags |= O_WRONLY_; + if (flags & O_RDWR) fake_flags |= O_RDWR_; + if (flags & O_CREAT) fake_flags |= O_CREAT_; + if (flags & O_EXCL) fake_flags |= O_EXCL_; + if (flags & O_TRUNC) fake_flags |= O_TRUNC_; + if (flags & O_APPEND) fake_flags |= O_APPEND_; + if (flags & O_NONBLOCK) fake_flags |= O_NONBLOCK_; + return fake_flags; +} + +// Map well-known /dev paths to device numbers. Returns 0 if not recognized. +static dev_t_ realfs_devnum_for_path(const char *path) { + if (strncmp(path, "/dev/", 5) != 0) + return 0; + const char *devname = path + 5; + if (strcmp(devname, "null") == 0) + return dev_make(MEM_MAJOR, DEV_NULL_MINOR); + if (strcmp(devname, "zero") == 0) + return dev_make(MEM_MAJOR, DEV_ZERO_MINOR); + if (strcmp(devname, "full") == 0) + return dev_make(MEM_MAJOR, DEV_FULL_MINOR); + if (strcmp(devname, "random") == 0) + return dev_make(MEM_MAJOR, DEV_RANDOM_MINOR); + if (strcmp(devname, "urandom") == 0) + return dev_make(MEM_MAJOR, DEV_URANDOM_MINOR); + if (strcmp(devname, "tty") == 0) + return dev_make(TTY_ALTERNATE_MAJOR, DEV_TTY_MINOR); + if (strcmp(devname, "console") == 0) + return dev_make(TTY_ALTERNATE_MAJOR, DEV_CONSOLE_MINOR); + if (strcmp(devname, "ptmx") == 0) + return dev_make(TTY_ALTERNATE_MAJOR, DEV_PTMX_MINOR); + return 0; +} + +struct fd *realfs_open(struct mount *mount, const char *path, int flags, int mode) { + int real_flags = open_flags_real_from_fake(flags); + int fd_no = openat(mount->root_fd, fix_path(path), real_flags, mode); + if (fd_no < 0) + return ERR_PTR(errno_map()); + struct fd *fd = fd_create(&realfs_fdops); + fd->real_fd = fd_no; + fd->dir = NULL; + return fd; +} + +int realfs_close(struct fd *fd) { + if (fd->dir != NULL) + closedir(fd->dir); + int err = close(fd->real_fd); + if (err < 0) + return errno_map(); + return 0; +} + +static void copy_stat(struct statbuf *fake_stat, struct stat *real_stat) { + fake_stat->dev = dev_fake_from_real(real_stat->st_dev); + fake_stat->inode = real_stat->st_ino; + fake_stat->mode = real_stat->st_mode; + fake_stat->nlink = real_stat->st_nlink; + fake_stat->uid = real_stat->st_uid; + fake_stat->gid = real_stat->st_gid; + fake_stat->rdev = dev_fake_from_real(real_stat->st_rdev); + fake_stat->size = real_stat->st_size; + fake_stat->blksize = real_stat->st_blksize; + fake_stat->blocks = real_stat->st_blocks; + fake_stat->atime = platform_stat_atime_sec(real_stat); + fake_stat->mtime = platform_stat_mtime_sec(real_stat); + fake_stat->ctime = platform_stat_ctime_sec(real_stat); + fake_stat->atime_nsec = platform_stat_atime_nsec(real_stat); + fake_stat->mtime_nsec = platform_stat_mtime_nsec(real_stat); + fake_stat->ctime_nsec = platform_stat_ctime_nsec(real_stat); +} + +int realfs_stat(struct mount *mount, const char *path, struct statbuf *fake_stat) { + struct stat real_stat; + if (fstatat(mount->root_fd, fix_path(path), &real_stat, AT_SYMLINK_NOFOLLOW) < 0) + return errno_map(); + copy_stat(fake_stat, &real_stat); + // Override mode/rdev for well-known device paths backed by placeholder files + dev_t_ devnum = realfs_devnum_for_path(path); + if (devnum != 0) { + fake_stat->mode = S_IFCHR | 0666; + fake_stat->rdev = devnum; + } + return 0; +} + +int realfs_fstat(struct fd *fd, struct statbuf *fake_stat) { + struct stat real_stat; + if (fstat(fd->real_fd, &real_stat) < 0) + return errno_map(); + copy_stat(fake_stat, &real_stat); + + // For fakefs/rootfs images we often ship placeholder regular files under + // /dev rather than real device nodes. Preserve the Linux-visible device + // semantics by reclassifying well-known device paths on fstat(), just like + // realfs_stat() already does for path-based lookup. + char path[MAX_PATH]; + if (fd->mount != NULL && realfs_getpath(fd, path) == 0) { + dev_t_ devnum = realfs_devnum_for_path(path); + if (devnum != 0) { + fake_stat->mode = S_IFCHR | 0666; + fake_stat->rdev = devnum; + } + } + return 0; +} + +static bool realfs_should_surface_eintr(void) { + if (current->group->doing_group_exit) + return true; + if (current->sighand != NULL) { + lock(¤t->sighand->lock); + bool pending = !!(current->pending & ~current->blocked); + unlock(¤t->sighand->lock); + if (pending) + return true; + } + return false; +} + +ssize_t realfs_read(struct fd *fd, void *buf, size_t bufsize) { + ssize_t res; + do { + res = read(fd->real_fd, buf, bufsize); + } while (res < 0 && errno == EINTR && !realfs_should_surface_eintr()); + if (res < 0) + return errno_map(); + return res; +} + +ssize_t realfs_write(struct fd *fd, const void *buf, size_t bufsize) { + ssize_t res; + do { + res = write(fd->real_fd, buf, bufsize); + } while (res < 0 && errno == EINTR && !realfs_should_surface_eintr()); + if (res < 0) + return errno_map(); + return res; +} + +ssize_t realfs_pread(struct fd *fd, void *buf, size_t bufsize, off_t off) { + ssize_t res; + do { + res = pread(fd->real_fd, buf, bufsize, off); + } while (res < 0 && errno == EINTR); + if (res < 0) + return errno_map(); + return res; +} + +ssize_t realfs_pwrite(struct fd *fd, const void *buf, size_t bufsize, off_t off) { + ssize_t res; + do { + res = pwrite(fd->real_fd, buf, bufsize, off); + } while (res < 0 && errno == EINTR); + if (res < 0) + return errno_map(); + return res; +} + +void realfs_opendir(struct fd *fd) { + if (fd->dir == NULL) { + int dirfd = dup(fd->real_fd); + if (dirfd < 0) return; + fd->dir = fdopendir(dirfd); + if (fd->dir == NULL) { + // fdopendir failed (fd may not be a directory, or was closed). + // Close the dup'd fd and leave fd->dir NULL for callers to handle. + close(dirfd); + } + } +} + +int realfs_readdir(struct fd *fd, struct dir_entry *entry) { + realfs_opendir(fd); + if (fd->dir == NULL) return _EIO; + // Darwin filenames (APFS/HFS+) can be up to 255 UTF-16 units, which in + // UTF-8 may exceed Linux NAME_MAX (255 bytes). An unchecked strcpy into + // entry->name[NAME_MAX + 1] smashes the caller's stack-allocated + // dir_entry (see sys_getdents64 in fs/dir.c) and trips __stack_chk_fail. + // Skip any entry whose name doesn't fit so the guest can continue walking. + for (;;) { + errno = 0; + struct dirent *dirent = readdir(fd->dir); + if (dirent == NULL) { + if (errno != 0) + return errno_map(); + return 0; + } + size_t namelen = strlen(dirent->d_name); + if (namelen > NAME_MAX) { + FIXME("realfs_readdir: skipping entry with name longer than NAME_MAX (%zu bytes)", namelen); + continue; + } + entry->inode = dirent->d_ino; + entry->type = dirent->d_type; + memcpy(entry->name, dirent->d_name, namelen + 1); + return 1; + } +} + +unsigned long realfs_telldir(struct fd *fd) { + realfs_opendir(fd); + if (fd->dir == NULL) return 0; + return telldir(fd->dir); +} + +void realfs_seekdir(struct fd *fd, unsigned long ptr) { + realfs_opendir(fd); + if (fd->dir == NULL) return; + seekdir(fd->dir, ptr); +} + +off_t realfs_lseek(struct fd *fd, off_t offset, int whence) { + if (fd->dir != NULL && whence == LSEEK_SET) { + realfs_seekdir(fd, offset); + return offset; + } + + if (whence == LSEEK_SET) + whence = SEEK_SET; + else if (whence == LSEEK_CUR) + whence = SEEK_CUR; + else if (whence == LSEEK_END) + whence = SEEK_END; + else + return _EINVAL; + off_t res = lseek(fd->real_fd, offset, whence); + if (res < 0) + return errno_map(); + return res; +} + +int realfs_poll(struct fd *fd) { + struct pollfd p = {.fd = fd->real_fd, .events = POLLPRI}; + // prevent POLLNVAL + int flags = fcntl(fd->real_fd, F_GETFL, 0); + if ((flags & O_ACCMODE) != O_WRONLY) + p.events |= POLLIN; + if ((flags & O_ACCMODE) != O_RDONLY) + p.events |= POLLOUT; + if (poll(&p, 1, 0) <= 0) + return 0; + +#if defined(__APPLE__) + // this is the "WTF is apple smoking" section + + // https://github.com/apple/darwin-xnu/blob/a449c6a3b8014d9406c2ddbdc81795da24aa7443/bsd/kern/sys_generic.c#L1856 + if (p.revents & POLLHUP) + p.revents |= POLLOUT; + // apparently you can sometimes get POLLPRI on a pipe??? please ignore how much of a mess this condition is + if (is_adhoc_fd(fd) && S_ISFIFO(fd->stat.mode)) + p.revents &= ~POLLPRI; + + if (p.revents & POLLNVAL) { + printk("pollnval %d flags %d events %d revents %d\n", fd->real_fd, flags, p.events, p.revents); + // Darwin poll can report POLLNVAL for broad event masks without + // telling us which individual readiness bits are still meaningful. + // Ask for each event class separately and ignore POLLNVAL noise. + // This is no longer atomic, but it preserves useful readiness bits. + int events = 0; + static const int pollbits[] = {POLLIN, POLLOUT, POLLPRI}; + for (unsigned i = 0; i < sizeof(pollbits)/sizeof(pollbits[0]); i++) { + p.events = pollbits[i]; + if (poll(&p, 1, 0) > 0 && !(p.revents & POLLNVAL)) + events |= p.revents; + } + assert(!(events & POLLNVAL)); + return events; + } +#endif + + assert(!(p.revents & POLLNVAL)); + return p.revents; +} + +int realfs_mmap(struct fd *fd, struct mem *mem, page_t start, pages_t pages, off_t offset, int prot, int flags) { + int mmap_flags = 0; + if (flags & MMAP_PRIVATE) mmap_flags |= MAP_PRIVATE; + if (flags & MMAP_SHARED) mmap_flags |= MAP_SHARED; + int mmap_prot = PROT_READ; + if (prot & P_WRITE) mmap_prot |= PROT_WRITE; + + off_t real_offset = (offset / real_page_size) * real_page_size; + off_t correction = offset - real_offset; + size_t map_size = (pages * PAGE_SIZE) + correction; + + struct stat st; + int have_stat = (fstat(fd->real_fd, &st) == 0); + + // Check if the mapping extends beyond the file size. + if (have_stat && (off_t)(real_offset + map_size) > st.st_size) { + // For MAP_SHARED writable mappings, use a direct file-backed mmap. + // The host kernel handles beyond-EOF correctly: writes within the + // file are flushed on munmap, and the zero-filled region between + // file end and page boundary is discarded. This is what apk needs + // for its posix_fallocate + mmap(MAP_SHARED) extraction pattern. + // We must NOT extend the file via ftruncate, because apk doesn't + // truncate it back, leaving trailing null bytes that corrupt files. + if ((mmap_flags & MAP_SHARED) && (mmap_prot & PROT_WRITE)) { + char *memory = mmap(NULL, map_size, + mmap_prot, mmap_flags, fd->real_fd, real_offset); + if (memory != MAP_FAILED) { + return pt_map(mem, start, pages, memory, correction, prot); + } + // mmap failed — fall through to anonymous path + } + + // Create anonymous backing for the full range (zeros for BSS) + char *memory = mmap(NULL, map_size, + PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (memory == MAP_FAILED) + return _ENOMEM; + size_t file_bytes = 0; + if (st.st_size > real_offset) + file_bytes = st.st_size - real_offset; + if (file_bytes > map_size) + file_bytes = map_size; + size_t file_map_size = (file_bytes / real_page_size) * real_page_size; + if (file_map_size > 0) { + char *file_map = mmap(memory, file_map_size, + mmap_prot, mmap_flags | MAP_FIXED, fd->real_fd, real_offset); + if (file_map == MAP_FAILED) + file_map_size = 0; + } + if (file_map_size < file_bytes) { + size_t remaining = file_bytes - file_map_size; + size_t total_read = 0; + while (total_read < remaining) { + ssize_t n = pread(fd->real_fd, memory + file_map_size + total_read, + remaining - total_read, + real_offset + file_map_size + total_read); + if (n <= 0) break; + total_read += n; + } + } + if (!(mmap_prot & PROT_WRITE) && file_map_size < map_size) + mprotect(memory + file_map_size, map_size - file_map_size, mmap_prot); + + return pt_map(mem, start, pages, memory, correction, prot); + } + + char *memory = mmap(NULL, map_size, + mmap_prot, mmap_flags, fd->real_fd, real_offset); + if (memory == MAP_FAILED) + return _ENOMEM; + + return pt_map(mem, start, pages, memory, correction, prot); +} + +ssize_t realfs_readlink(struct mount *mount, const char *path, char *buf, size_t bufsize) { + ssize_t size = readlinkat(mount->root_fd, fix_path(path), buf, bufsize); + if (size < 0) + return errno_map(); + return size; +} + +int realfs_getpath(struct fd *fd, char *buf) { + int err = platform_fd_get_path(fd->real_fd, buf, MAX_PATH); + if (err < 0) + return err; + + /* For bind-mounted dirs, F_GETPATH resolves symlinks and returns the + * host persistent path (e.g. /Users/.../MinisChat/minis/<sid>/attachments). + * This won't start with mount->source, so the normal prefix strip fails. + * Detect and translate back to the Linux path. */ + char linux_path[MAX_PATH]; + if (fakefs_bind_mount_resolve_path(buf, linux_path, sizeof(linux_path))) { + if (strstr(buf, "minis") != NULL) + fprintf(stderr, "realfs_getpath: bind_mount_resolve OK: \"%s\" -> \"%s\"\n", buf, linux_path); + strlcpy(buf, linux_path, MAX_PATH); + return 0; + } + if (strstr(buf, "minis") != NULL) + fprintf(stderr, "realfs_getpath: bind_mount_resolve MISS: F_GETPATH=\"%s\" source=\"%s\"\n", buf, fd->mount->source); + + if (strcmp(fd->mount->source, "/") != 0 || strcmp(buf, "/") == 0) { + size_t source_len = strlen(fd->mount->source); + /* Verify buf actually starts with mount->source before stripping. + * F_GETPATH resolves symlinks, so bind-mounted paths may point outside + * mount->source when the bind mount table has been cleared (e.g. after + * app restart before mountMinis re-registers the mounts). */ + if (strncmp(buf, fd->mount->source, source_len) == 0) { + memmove(buf, buf + source_len, MAX_PATH - source_len); + } else if (strncmp(fd->mount->source, "/var/", 5) == 0 && + strncmp(buf, "/private", 8) == 0 && + strncmp(buf + 8, fd->mount->source, source_len) == 0) { + /* F_GETPATH returns /private/var/... but mount->source is /var/... + * Strip /private prefix + mount->source from buf. */ + memmove(buf, buf + 8 + source_len, MAX_PATH - 8 - source_len); + } else { + /* Path is outside mount source (stale bind mount symlink resolved + * by F_GETPATH). Return root as a safe fallback. */ + strcpy(buf, "/"); + } + } + return 0; +} + +int realfs_link(struct mount *mount, const char *src, const char *dst) { + int res = linkat(mount->root_fd, fix_path(src), mount->root_fd, fix_path(dst), 0); + if (res < 0) + return errno_map(); + return res; +} + +int realfs_unlink(struct mount *mount, const char *path) { + int res = unlinkat(mount->root_fd, fix_path(path), 0); + if (res < 0) { + int err = errno_map(); + struct statbuf stat; + // Darwin reports EPERM for directories; Linux callers expect EISDIR. + if (err == _EPERM && realfs_stat(mount, path, &stat) == 0 && S_ISDIR(stat.mode)) + return _EISDIR; + return err; + } + return res; +} + +int realfs_rmdir(struct mount *mount, const char *path) { + int err = unlinkat(mount->root_fd, fix_path(path), AT_REMOVEDIR); + if (err < 0) + return errno_map(); + return 0; +} + +int realfs_rename(struct mount *mount, const char *src, const char *dst) { + int err = renameat(mount->root_fd, fix_path(src), mount->root_fd, fix_path(dst)); + if (err < 0) + return errno_map(); + return err; +} + +int realfs_symlink(struct mount *mount, const char *target, const char *link) { + int err = symlinkat(target, mount->root_fd, fix_path(link)); + if (err < 0) + return errno_map(); + return err; +} + +int realfs_mknod(struct mount *mount, const char *path, mode_t_ mode, dev_t_ UNUSED(dev)) { + int err; + if (S_ISFIFO(mode)) { + lock_fchdir(mount->root_fd); + err = mkfifo(fix_path(path), mode & ~S_IFMT); + unlock_fchdir(); + } else if (S_ISREG(mode)) { + err = openat(mount->root_fd, fix_path(path), O_CREAT|O_EXCL|O_RDONLY, mode & ~S_IFMT); + if (err >= 0) + err = close(err); + } else { + return _EPERM; + } + if (err < 0) + return errno_map(); + return err; +} + +int realfs_truncate(struct mount *mount, const char *path, off_t_ size) { + int fd = openat(mount->root_fd, fix_path(path), O_RDWR); + if (fd < 0) + return errno_map(); + int err = 0; + if (ftruncate(fd, size) < 0) + err = errno_map(); + close(fd); + return err; +} + +int realfs_setattr(struct mount *mount, const char *path, struct attr attr) { + path = fix_path(path); + int root = mount->root_fd; + int err; + switch (attr.type) { + case attr_uid: + err = fchownat(root, path, attr.uid, -1, 0); + if (err < 0 && errno == EPERM) + return 0; // silently ignore, we're not root on host + break; + case attr_gid: + err = fchownat(root, path, attr.gid, -1, 0); + if (err < 0 && errno == EPERM) + return 0; + break; + case attr_mode: + err = fchmodat(root, path, attr.mode, 0); + break; + case attr_size: + return realfs_truncate(mount, path, attr.size); + default: + TODO("other attrs"); + } + if (err < 0) + return errno_map(); + return err; +} + +int realfs_fsetattr(struct fd *fd, struct attr attr) { + int real_fd = fd->real_fd; + int err; + switch (attr.type) { + case attr_uid: + err = fchown(real_fd, attr.uid, -1); + if (err < 0 && errno == EPERM) + return 0; + break; + case attr_gid: + err = fchown(real_fd, attr.gid, -1); + if (err < 0 && errno == EPERM) + return 0; + break; + case attr_mode: + err = fchmod(real_fd, attr.mode); + break; + case attr_size: + err = ftruncate(real_fd, attr.size); + break; + default: abort(); + } + if (err < 0) + return errno_map(); + return err; +} + +int realfs_utime(struct mount *mount, const char *path, struct timespec atime, struct timespec mtime) { + struct timespec times[2] = {atime, mtime}; + int err = utimensat(mount->root_fd, fix_path(path), times, 0); + if (err < 0) + return errno_map(); + return 0; +} + +int realfs_mkdir(struct mount *mount, const char *path, mode_t_ mode) { + int err = mkdirat(mount->root_fd, fix_path(path), mode); + if (err < 0) + return errno_map(); + return 0; +} + +int realfs_flock(struct fd *fd, int operation) { + int real_op = 0; + if (operation & LOCK_SH_) real_op |= LOCK_SH; + if (operation & LOCK_EX_) real_op |= LOCK_EX; + if (operation & LOCK_UN_) real_op |= LOCK_UN; + if (operation & LOCK_NB_) real_op |= LOCK_NB; + return flock(fd->real_fd, real_op); +} + +int realfs_statfs(struct mount *mount, struct statfsbuf *stat) { + struct statvfs vfs = {}; + fstatvfs(mount->root_fd, &vfs); + stat->bsize = vfs.f_bsize; + stat->blocks = vfs.f_blocks; + stat->bfree = vfs.f_bfree; + stat->bavail = vfs.f_bavail; + stat->files = vfs.f_files; + stat->ffree = vfs.f_ffree; + stat->namelen = vfs.f_namemax; + stat->frsize = vfs.f_frsize; + return 0; +} + +int realfs_mount(struct mount *mount) { + char *source_realpath = realpath(mount->source, NULL); + if (source_realpath == NULL) + return errno_map(); + free((void *) mount->source); + mount->source = source_realpath; + + mount->root_fd = open(mount->source, O_DIRECTORY); + if (mount->root_fd < 0) + return errno_map(); + return 0; +} + +int realfs_fsync(struct fd *fd) { + int err = fsync(fd->real_fd); + if (err < 0) + return errno_map(); + return 0; +} + +int realfs_getflags(struct fd *fd) { + int flags = fcntl(fd->real_fd, F_GETFL); + if (flags < 0) + return errno_map(); + return open_flags_fake_from_real(flags); +} + +int realfs_setflags(struct fd *fd, dword_t flags) { + int ret = fcntl(fd->real_fd, F_SETFL, open_flags_real_from_fake(flags)); + if (ret < 0) + return errno_map(); + return 0; +} + +ssize_t realfs_ioctl_size(int cmd) { + if (cmd == FIONREAD_) + return sizeof(dword_t); + if (cmd == TCGETS_) + return sizeof(struct termios_); + if (cmd == TIOCGWINSZ_) + return sizeof(struct winsize_); + return -1; +} + +int realfs_ioctl(struct fd *fd, int cmd, void *arg) { + int err; + size_t nread; + switch (cmd) { + case FIONREAD_: + err = ioctl(fd->real_fd, FIONREAD, &nread); + if (err < 0) + return errno_map(); + *(dword_t *) arg = nread; + return 0; + case TCGETS_: + // For piped stdio fds backed by a real host TTY, return a + // plausible termios so that musl isatty() succeeds. + if (isatty(fd->real_fd)) { + struct termios host_termios; + if (tcgetattr(fd->real_fd, &host_termios) == 0) { + struct termios_ *guest = (struct termios_ *)arg; + memset(guest, 0, sizeof(*guest)); + guest->iflags = host_termios.c_iflag; + guest->oflags = host_termios.c_oflag; + guest->cflags = host_termios.c_cflag; + guest->lflags = host_termios.c_lflag; + return 0; + } + } + return _ENOTTY; + case TIOCGWINSZ_: { + // libuv calls TIOCGWINSZ during uv_tty_init to get terminal size. + if (isatty(fd->real_fd)) { + struct winsize host_ws; + if (ioctl(fd->real_fd, TIOCGWINSZ, &host_ws) == 0) { + struct winsize_ *guest_ws = (struct winsize_ *)arg; + guest_ws->row = host_ws.ws_row; + guest_ws->col = host_ws.ws_col; + guest_ws->xpixel = host_ws.ws_xpixel; + guest_ws->ypixel = host_ws.ws_ypixel; + return 0; + } + } + return _ENOTTY; + } + } + return _ENOTTY; +} + +const struct fs_ops realfs = { + .name = "real", .magic = 0x7265616c, + .mount = realfs_mount, + .statfs = realfs_statfs, + + .open = realfs_open, + .readlink = realfs_readlink, + .link = realfs_link, + .unlink = realfs_unlink, + .rmdir = realfs_rmdir, + .rename = realfs_rename, + .symlink = realfs_symlink, + .mknod = realfs_mknod, + + .close = realfs_close, + .stat = realfs_stat, + .fstat = realfs_fstat, + .setattr = realfs_setattr, + .fsetattr = realfs_fsetattr, + .utime = realfs_utime, + .getpath = realfs_getpath, + .flock = realfs_flock, + + .mkdir = realfs_mkdir, +}; + +const struct fd_ops realfs_fdops = { + .read = realfs_read, + .write = realfs_write, + .pread = realfs_pread, + .pwrite = realfs_pwrite, + .readdir = realfs_readdir, + .telldir = realfs_telldir, + .seekdir = realfs_seekdir, + .lseek = realfs_lseek, + .mmap = realfs_mmap, + .poll = realfs_poll, + .ioctl_size = realfs_ioctl_size, + .ioctl = realfs_ioctl, + .fsync = realfs_fsync, + .close = realfs_close, + .getflags = realfs_getflags, + .setflags = realfs_setflags, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/real.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/real.h new file mode 100644 index 0000000000..4956d58ea1 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/real.h @@ -0,0 +1,51 @@ +#ifndef FS_REAL_H +#define FS_REAL_H + +#include "kernel/fs.h" + +extern const struct fd_ops realfs_fdops; +extern const struct fs_ops realfs; + +struct fd *realfs_open(struct mount *mount, const char *path, int flags, int mode); + +ssize_t realfs_readlink(struct mount *mount, const char *path, char *buf, size_t bufsize); +int realfs_link(struct mount *mount, const char *src, const char *dst); +int realfs_unlink(struct mount *mount, const char *path); +int realfs_rmdir(struct mount *mount, const char *path); +int realfs_rename(struct mount *mount, const char *src, const char *dst); +int realfs_symlink(struct mount *mount, const char *target, const char *link); +int realfs_mknod(struct mount *mount, const char *path, mode_t_ mode, dev_t_ UNUSED(dev)); + +int realfs_stat(struct mount *mount, const char *path, struct statbuf *fake_stat); +int realfs_statfs(struct mount *mount, struct statfsbuf *stat); +int realfs_fstat(struct fd *fd, struct statbuf *fake_stat); +int realfs_setattr(struct mount *mount, const char *path, struct attr attr); +int realfs_fsetattr(struct fd *fd, struct attr attr); + +int realfs_mkdir(struct mount *mount, const char *path, mode_t_ mode); + +int realfs_truncate(struct mount *mount, const char *path, off_t_ size); +int realfs_utime(struct mount *mount, const char *path, struct timespec atime, struct timespec mtime); + +int realfs_statfs(struct mount *mount, struct statfsbuf *stat); +int realfs_flock(struct fd *fd, int operation); +int realfs_getpath(struct fd *fd, char *buf); +ssize_t realfs_read(struct fd *fd, void *buf, size_t bufsize); +ssize_t realfs_write(struct fd *fd, const void *buf, size_t bufsize); + +int realfs_readdir(struct fd *fd, struct dir_entry *entry); +unsigned long realfs_telldir(struct fd *fd); +void realfs_seekdir(struct fd *fd, unsigned long ptr); + +off_t realfs_lseek(struct fd *fd, off_t offset, int whence); + +int realfs_poll(struct fd *fd); +int realfs_mmap(struct fd *fd, struct mem *mem, page_t start, pages_t pages, off_t offset, int prot, int flags); +int realfs_fsync(struct fd *fd); +int realfs_getflags(struct fd *fd); +int realfs_setflags(struct fd *fd, dword_t arg); +ssize_t realfs_ioctl_size(int cmd); +int realfs_ioctl(struct fd *fd, int cmd, void *arg); +int realfs_close(struct fd *fd); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sock.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sock.c new file mode 100644 index 0000000000..772caec1bd --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sock.c @@ -0,0 +1,1801 @@ +#include <fcntl.h> +#include <netinet/tcp.h> +#include <poll.h> +#include <string.h> +#include <sys/socket.h> +#include <sys/stat.h> +#include <sys/un.h> +#include "kernel/calls.h" +#include "fs/fd.h" +#include "fs/inode.h" +#include "fs/path.h" +#include "fs/real.h" +#include "fs/sock.h" +#include "debug.h" + +#define SOCKET_TYPE_MASK 0xf + +const struct fd_ops socket_fdops; + +static lock_t peer_lock = LOCK_INITIALIZER; + +static fd_t sock_fd_create(int sock_fd, int domain, int type, int protocol) { + struct fd *fd = adhoc_fd_create(&socket_fdops); + if (fd == NULL) + return _ENOMEM; + fd->stat.mode = S_IFSOCK | 0666; + fd->real_fd = sock_fd; + fd->socket.domain = domain; + fd->socket.type = type & SOCKET_TYPE_MASK; + fd->socket.protocol = protocol; + if (domain == AF_LOCAL_) { + cond_init(&fd->socket.unix_got_peer); + list_init(&fd->socket.unix_scm); + } + return f_install(fd, type & ~SOCKET_TYPE_MASK); +} + +int_t sys_socket(dword_t domain, dword_t type, dword_t protocol) { + STRACE("socket(%d, %d, %d)", domain, type, protocol); + int real_domain = sock_family_to_real(domain); + if (real_domain < 0) + return _EAFNOSUPPORT; + int real_type = sock_type_to_real(type, protocol); + if (real_type < 0) + return _EINVAL; + + // this hack makes mtr work + if (type == SOCK_RAW_ && protocol == IPPROTO_RAW) + protocol = IPPROTO_ICMP; + + int sock = socket(real_domain, real_type, protocol); + if (sock < 0) + return errno_map(); + +#ifdef __APPLE__ + if (domain == AF_INET_ && type == SOCK_DGRAM_) { + // in some cases, such as ICMP, datagram sockets on mac can default to + // including the IP header like raw sockets + int one = 1; + setsockopt(sock, IPPROTO_IP, IP_STRIPHDR, &one, sizeof(one)); + } +#endif + + fd_t f = sock_fd_create(sock, domain, type, protocol); + if (f < 0) + close(sock); + return f; +} + +static void inode_release_if_exist(struct inode_data *inode) { + if (inode != NULL) + inode_release(inode); +} + +static struct fd *sock_getfd(fd_t sock_fd) { + struct fd *sock = f_get(sock_fd); + if (sock == NULL || sock->ops != &socket_fdops) + return NULL; + return sock; +} + +static uint32_t unix_socket_next_id() { + static uint32_t next_id = 0; + static lock_t next_id_lock = LOCK_INITIALIZER; + lock(&next_id_lock); + uint32_t id = ++next_id; + unlock(&next_id_lock); + return id; +} + +static int unix_socket_get(const char *path_raw, struct fd *bind_fd, uint32_t *socket_id) { + char path[MAX_PATH]; + int err = path_normalize(AT_PWD, path_raw, path, N_SYMLINK_FOLLOW); + if (err < 0) + return err; + struct mount *mount = find_mount_and_trim_path(path); + struct statbuf stat; + err = mount->fs->stat(mount, path, &stat); + + // If bind was called, there are some funny semantics. + if (bind_fd != NULL) { + // If the file exists, fail. + if (err == 0) { + err = _EADDRINUSE; + goto out; + } + // If the file can't be found, try to create it as a socket. + if (err < 0) { + mode_t_ mode = 0777; + struct fs_info *fs = current->fs; + lock(&fs->lock); + mode &= ~fs->umask; + unlock(&fs->lock); + err = mount->fs->mknod(mount, path, S_IFSOCK | mode, 0); + if (err < 0) + goto out; + err = mount->fs->stat(mount, path, &stat); + if (err < 0) + goto out; + } + } + + // If something other than bind was called, just do the obvious thing and + // fail if stat failed. + if (bind_fd == NULL && err < 0) + goto out; + + if (!S_ISSOCK(stat.mode)) { + err = _ENOTSOCK; + goto out; + } + + // Look up the socket ID for the inode number. + struct inode_data *inode = inode_get(mount, stat.inode); + if (inode == NULL) { + err = _ENOMEM; + goto out; + } + lock(&inode->lock); + if (inode->socket_id == 0) + inode->socket_id = unix_socket_next_id(); + unlock(&inode->lock); + *socket_id = inode->socket_id; + + mount_release(mount); + if (bind_fd != NULL) + bind_fd->socket.unix_name_inode = inode; + else + inode_release(inode); + return 0; + +out: + mount_release(mount); + return err; +} + +// Dan Bernstein's simple and decently effective hash function +static uint32_t str_hash(const char *str) { + uint32_t hash = 5381; + for (int i = 0; str[i] != '\0'; i++) { + hash = 33 * hash ^ str[i]; + } + return hash; +} + +// The abstract socket namespace is a lot simpler than it sounds: if the first +// byte of the path is a null byte, then it gets looked up in this hashtable +// instead of the filesystem. + +struct unix_abstract { + unsigned refcount; + uint32_t hash; + uint32_t socket_id; + struct list links; +}; +#define ABSTRACT_HASH_SIZE 1024 +static struct list abstract_hash[ABSTRACT_HASH_SIZE]; +static lock_t unix_abstract_lock = LOCK_INITIALIZER; + +static int unix_abstract_get(const char *name, struct fd *bind_fd, uint32_t *socket_id) { + uint32_t hash = str_hash(name); + lock(&unix_abstract_lock); + struct unix_abstract *sock_tmp; + struct unix_abstract *sock = NULL; + struct list *bucket = &abstract_hash[hash % ABSTRACT_HASH_SIZE]; + if (list_null(bucket)) + list_init(bucket); + list_for_each_entry(bucket, sock_tmp, links) { + if (sock_tmp->hash == hash) { + sock = sock_tmp; + break; + } + } + + if (bind_fd != NULL && sock != NULL) { + unlock(&unix_abstract_lock); + return _EEXIST; + } + if (bind_fd == NULL && sock == NULL) { + unlock(&unix_abstract_lock); + return _ENOENT; + } + + if (sock == NULL) { + sock = malloc(sizeof(struct unix_abstract)); + if (sock == NULL) { + unlock(&unix_abstract_lock); + return _ENOMEM; + } + sock->refcount = 0; + sock->hash = hash; + sock->socket_id = unix_socket_next_id(); + list_add(bucket, &sock->links); + } + + sock->refcount++; + unlock(&unix_abstract_lock); + *socket_id = sock->socket_id; + if (bind_fd != NULL) + bind_fd->socket.unix_name_abstract = sock; + return 0; +} + +static void unix_abstract_release(struct unix_abstract *name) { + lock(&unix_abstract_lock); + if (--name->refcount == 0) { + list_remove(&name->links); + free(name); + } + unlock(&unix_abstract_lock); +} + +const char *sock_tmp_prefix = "/tmp/ishsock"; + +static int sockaddr_read_bind(addr_t sockaddr_addr, void *sockaddr, uint_t *sockaddr_len, struct fd *bind_fd) { + // Make sure we can read things without overflowing buffers + if (*sockaddr_len < 2) + return _EINVAL; + if (*sockaddr_len > sizeof(struct sockaddr_max_)) + return _EINVAL; + + if (user_read(sockaddr_addr, sockaddr, *sockaddr_len)) + return _EFAULT; + struct sockaddr *real_addr = sockaddr; + struct sockaddr_ *fake_addr = sockaddr; + real_addr->sa_family = sock_family_to_real(fake_addr->family); + + switch (real_addr->sa_family) { + case PF_INET: + if (*sockaddr_len < sizeof(struct sockaddr_in)) + return _EINVAL; + break; + case PF_INET6: + if (*sockaddr_len < sizeof(struct sockaddr_in6)) + return _EINVAL; + break; + + case PF_LOCAL: { + // First pull out the path, being careful to not overflow anything. + char path[SOCKADDR_DATA_MAX + 1]; + size_t path_size = *sockaddr_len - offsetof(struct sockaddr_, data); + memcpy(path, fake_addr->data, path_size); + path[path_size] = '\0'; + + uint32_t socket_id; + int err; + if (path_size == 0) { + return _ENOENT; + } else if (path[0] != '\0') { + STRACE(" unix socket %s", path); + err = unix_socket_get(path, bind_fd, &socket_id); + } else { + STRACE(" unix abstract socket %s", path + 1); + err = unix_abstract_get(path + 1, bind_fd, &socket_id); + } + if (err < 0) + return err; + if (bind_fd != NULL) { + bind_fd->socket.unix_name_len = path_size; + memcpy(bind_fd->socket.unix_name, path, path_size); + } + + struct sockaddr_un *real_addr_un = sockaddr; + int path_len = snprintf(real_addr_un->sun_path, sizeof(real_addr_un->sun_path), + "%s%d.%u", sock_tmp_prefix, getpid(), socket_id); + if (path_len < 0 || (size_t) path_len >= sizeof(real_addr_un->sun_path)) + return _ENAMETOOLONG; + // The call to real bind will fail if the backing socket already + // exists from a previous run or something. We already checked that + // the fake file doesn't exist in unix_socket_get, so try a simple + // solution. + if (bind_fd != NULL) + unlink(real_addr_un->sun_path); + *sockaddr_len = offsetof(struct sockaddr_un, sun_path) + path_len; + break; + } + default: + return _EINVAL; + } + return 0; +} + +static int sockaddr_read(addr_t sockaddr_addr, void *sockaddr, uint_t *sockaddr_len) { + return sockaddr_read_bind(sockaddr_addr, sockaddr, sockaddr_len, NULL); +} + +static int sockaddr_write(addr_t sockaddr_addr, void *sockaddr, uint_t buffer_len, uint_t *sockaddr_len) { + struct sockaddr *real_addr = sockaddr; + struct sockaddr_ *fake_addr = sockaddr; + fake_addr->family = sock_family_from_real(real_addr->sa_family); + switch (fake_addr->family) { + case PF_LOCAL_: { + // Most callers of sockaddr_write use it to return a peer name, and + // since we don't know the peer name in this case, just return the + // default peer name, which is the null address. + static struct sockaddr_ unix_domain_null = {.family = PF_LOCAL_}; + sockaddr = &unix_domain_null; + *sockaddr_len = sizeof(unix_domain_null); + break; + } + case PF_INET_: + case PF_INET6_: + break; + default: + return _EINVAL; + } + + if (buffer_len > *sockaddr_len) + buffer_len = *sockaddr_len; + // The address is supposed to be truncated if the specified length is too + // short, instead of returning an error. + if (user_write(sockaddr_addr, sockaddr, buffer_len)) + return _EFAULT; + return 0; +} + +int_t sys_bind(fd_t sock_fd, addr_t sockaddr_addr, uint_t sockaddr_len) { + STRACE("bind(%d, 0x%x, %d)", sock_fd, sockaddr_addr, sockaddr_len); + struct fd *sock = sock_getfd(sock_fd); + if (sock == NULL) + return _EBADF; + struct sockaddr_max_ sockaddr; + int err = sockaddr_read_bind(sockaddr_addr, &sockaddr, &sockaddr_len, sock); + if (err < 0) + return err; + + err = bind(sock->real_fd, (void *) &sockaddr, sockaddr_len); + if (err < 0) { + inode_release_if_exist(sock->socket.unix_name_inode); + sock->socket.unix_name_inode = NULL; + if (sock->socket.unix_name_abstract != NULL) { + unix_abstract_release(sock->socket.unix_name_abstract); + sock->socket.unix_name_abstract = NULL; + } + return errno_map(); + } + return 0; +} + +static void fill_cred(struct ucred_ *cred) { + cred->pid = current->pid; + cred->uid = current->euid; + cred->gid = current->egid; +} + +int_t sys_connect(fd_t sock_fd, addr_t sockaddr_addr, uint_t sockaddr_len) { + STRACE("connect(%d, 0x%x, %d)", sock_fd, sockaddr_addr, sockaddr_len); + struct fd *sock = sock_getfd(sock_fd); + if (sock == NULL) + return _EBADF; + struct sockaddr_max_ sockaddr; + int err = sockaddr_read(sockaddr_addr, &sockaddr, &sockaddr_len); + if (err < 0) + return err; + + err = connect(sock->real_fd, (void *) &sockaddr, sockaddr_len); + if (err < 0) { + int ce = errno; + // Log connect failures except the routine nonblock in-progress case, + // so VPN / routing issues are visible in user-shared logs. + if (ce != EINPROGRESS && ce != EALREADY) { + printk("NETDIAG connect(pid=%d comm=%s fd=%d) errno=%d\n", + current->pid, current->comm, sock_fd, ce); + } + errno = ce; + return errno_map(); + } + + if (sock->socket.domain == AF_LOCAL_) { + fill_cred(&sock->socket.unix_cred); + assert(sock->socket.unix_peer == NULL); + // Send a pointer to ourselves to the other end so they can set up the peer pointers. + ssize_t res = write(sock->real_fd, &sock, sizeof(struct fd *)); + if (res == sizeof(struct fd *)) { + // Wait for acknowledgement that it happened. + lock(&peer_lock); + while (sock->socket.unix_peer == NULL) + wait_for_ignore_signals(&sock->socket.unix_got_peer, &peer_lock, NULL); + unlock(&peer_lock); + } + } + + return err; +} + +int_t sys_listen(fd_t sock_fd, int_t backlog) { + STRACE("listen(%d, %d)", sock_fd, backlog); + struct fd *sock = sock_getfd(sock_fd); + if (sock == NULL) + return _EBADF; + int err = listen(sock->real_fd, backlog); + if (err < 0) + return errno_map(); + sockrestart_begin_listen(sock); + return err; +} + +int_t sys_accept(fd_t sock_fd, addr_t sockaddr_addr, addr_t sockaddr_len_addr) { + STRACE("accept(%d, 0x%x, 0x%x)", sock_fd, sockaddr_addr, sockaddr_len_addr); + struct fd *sock = sock_getfd(sock_fd); + if (sock == NULL) + return _EBADF; + dword_t sockaddr_len = 0; + dword_t sockaddr_buffer_len = 0; + if (sockaddr_addr != 0) { + if (sockaddr_len_addr == 0 || user_get(sockaddr_len_addr, sockaddr_len)) + return _EFAULT; + if (sockaddr_len > sizeof(struct sockaddr_max_)) + sockaddr_len = sizeof(struct sockaddr_max_); + sockaddr_buffer_len = sockaddr_len; + } + + struct sockaddr_max_ sockaddr; + int client; + do { + sockrestart_begin_listen_wait(sock); + errno = 0; + client = accept(sock->real_fd, + sockaddr_addr != 0 ? (void *) &sockaddr : NULL, + sockaddr_addr != 0 ? &sockaddr_len : NULL); + sockrestart_end_listen_wait(sock); + } while (sockrestart_should_restart_listen_wait() && errno == EINTR); + if (client < 0) + return errno_map(); + + if (sockaddr_addr != 0) { + int err = sockaddr_write(sockaddr_addr, &sockaddr, sockaddr_buffer_len, &sockaddr_len); + if (err < 0) { + close(client); + return err; + } + if (user_put(sockaddr_len_addr, sockaddr_len)) { + close(client); + return _EFAULT; + } + } + + fd_t client_f = sock_fd_create(client, + sock->socket.domain, sock->socket.type, sock->socket.protocol); + if (client_f < 0) { + close(client); + return client_f; + } + + if (sock->socket.domain == AF_LOCAL_) { + lock(&peer_lock); + struct fd *client_fd = f_get(client_f); + fill_cred(&client_fd->socket.unix_cred); + struct fd *peer; + ssize_t res = read(client, &peer, sizeof(peer)); + if (res == sizeof(peer)) { + client_fd->socket.unix_peer = peer; + peer->socket.unix_peer = client_fd; + notify(&peer->socket.unix_got_peer); + } + unlock(&peer_lock); + } + + return client_f; +} + +int_t sys_accept4(fd_t sock_fd, addr_t sockaddr_addr, addr_t sockaddr_len_addr, int_t flags) { + STRACE("accept4(%d, 0x%x, 0x%x, 0x%x)", sock_fd, sockaddr_addr, sockaddr_len_addr, flags); + if (flags & ~(SOCK_NONBLOCK_ | SOCK_CLOEXEC_)) + return _EINVAL; + int_t client_f = sys_accept(sock_fd, sockaddr_addr, sockaddr_len_addr); + if (client_f < 0) + return client_f; + struct fd *client_fd = f_get(client_f); + if (client_fd != NULL) { + if (flags & SOCK_NONBLOCK_) + fd_setflags(client_fd, O_NONBLOCK_); + if (flags & SOCK_CLOEXEC_) { + lock(¤t->files->lock); + bit_set(client_f, current->files->cloexec); + unlock(¤t->files->lock); + } + } + return client_f; +} + +static int copy_unix_name(struct sockaddr_max_ *sockaddr, dword_t buffer_len, dword_t *sockaddr_len, struct fd *sock) { + struct sockaddr_ *fake_addr = (void *) sockaddr; + size_t name_len_full = sock->socket.unix_name_len; + if (name_len_full > sizeof(sockaddr->data)) + name_len_full = sizeof(sockaddr->data); + size_t full_len = offsetof(struct sockaddr_, data) + name_len_full; + *sockaddr_len = full_len; + if (buffer_len > sizeof(*sockaddr)) + buffer_len = sizeof(*sockaddr); + if (buffer_len < offsetof(struct sockaddr_, data)) + return 0; + + fake_addr->family = PF_LOCAL_; + size_t data_len = buffer_len - offsetof(struct sockaddr_, data); + size_t name_len = name_len_full; + if (name_len > data_len) + name_len = data_len; + memset(fake_addr->data, 0, data_len); + memcpy(fake_addr->data, sock->socket.unix_name, name_len); + return 0; +} + +int_t sys_getsockname(fd_t sock_fd, addr_t sockaddr_addr, addr_t sockaddr_len_addr) { + STRACE("getsockname(%d, 0x%x, 0x%x)", sock_fd, sockaddr_addr, sockaddr_len_addr); + struct fd *sock = sock_getfd(sock_fd); + if (sock == NULL) + return _EBADF; + dword_t sockaddr_len; + if (user_get(sockaddr_len_addr, sockaddr_len)) + return _EFAULT; + dword_t sockaddr_buffer_len = sockaddr_len; + if (sockaddr_len > sizeof(struct sockaddr_max_)) + sockaddr_len = sizeof(struct sockaddr_max_); + struct sockaddr_max_ sockaddr; + + // if this is a unix socket, return the same string passed to bind + if (sock->socket.domain == PF_LOCAL_) { + int err = copy_unix_name(&sockaddr, sockaddr_buffer_len, &sockaddr_len, sock); + if (err < 0) + return err; + size_t write_len = sockaddr_buffer_len < sockaddr_len ? sockaddr_buffer_len : sockaddr_len; + if (write_len != 0 && user_write(sockaddr_addr, &sockaddr, write_len)) + return _EFAULT; + if (user_put(sockaddr_len_addr, sockaddr_len)) + return _EFAULT; + return 0; + } + + int res = getsockname(sock->real_fd, (void *) &sockaddr, &sockaddr_len); + if (res < 0) + return errno_map(); + + int err = sockaddr_write(sockaddr_addr, &sockaddr, sockaddr_buffer_len, &sockaddr_len); + if (err < 0) + return err; + if (user_put(sockaddr_len_addr, sockaddr_len)) + return _EFAULT; + return res; +} + +int_t sys_getpeername(fd_t sock_fd, addr_t sockaddr_addr, addr_t sockaddr_len_addr) { + STRACE("getpeername(%d, 0x%x, 0x%x)", sock_fd, sockaddr_addr, sockaddr_len_addr); + struct fd *sock = sock_getfd(sock_fd); + if (sock == NULL) + return _EBADF; + dword_t sockaddr_len; + if (user_get(sockaddr_len_addr, sockaddr_len)) + return _EFAULT; + dword_t sockaddr_buffer_len = sockaddr_len; + if (sockaddr_len > sizeof(struct sockaddr_max_)) + sockaddr_len = sizeof(struct sockaddr_max_); + + // TODO if this is a unix socket, return the same string the peer passed to + // bind once the peer pointer is available + + struct sockaddr_max_ sockaddr; + int res = getpeername(sock->real_fd, (void *) &sockaddr, &sockaddr_len); + if (res < 0) + return errno_map(); + + int err = sockaddr_write(sockaddr_addr, &sockaddr, sockaddr_buffer_len, &sockaddr_len); + if (err < 0) + return err; + if (user_put(sockaddr_len_addr, sockaddr_len)) + return _EFAULT; + return res; +} + +int_t sys_socketpair(dword_t domain, dword_t type, dword_t protocol, addr_t sockets_addr) { + STRACE("socketpair(%d, %d, %d, 0x%x)", domain, type, protocol, sockets_addr); + int real_domain = sock_family_to_real(domain); + if (real_domain < 0) + return _EAFNOSUPPORT; + int real_type = sock_type_to_real(type, protocol); + if (real_type < 0) + return _EINVAL; + + int sockets[2]; + int err = socketpair(real_domain, real_type, protocol, sockets); + if (err < 0) + return errno_map(); + + lock(&peer_lock); + int fake_sockets[2]; + err = fake_sockets[0] = sock_fd_create(sockets[0], domain, type, protocol); + if (fake_sockets[0] < 0) { + unlock(&peer_lock); + goto close_sockets; + } + err = fake_sockets[1] = sock_fd_create(sockets[1], domain, type, protocol); + if (fake_sockets[1] < 0) { + unlock(&peer_lock); + goto close_fake_0; + } + struct fd *sock1 = f_get(fake_sockets[0]); + struct fd *sock2 = f_get(fake_sockets[1]); + sock1->socket.unix_peer = sock2; + sock2->socket.unix_peer = sock1; + unlock(&peer_lock); + + err = _EFAULT; + if (user_put(sockets_addr, fake_sockets)) + goto close_fake_1; + + STRACE(" [%d, %d]", fake_sockets[0], fake_sockets[1]); + return 0; + +close_fake_1: + sys_close(fake_sockets[1]); +close_fake_0: + sys_close(fake_sockets[0]); +close_sockets: + close(sockets[0]); + close(sockets[1]); + return err; +} + +int_t sys_sendto(fd_t sock_fd, addr_t buffer_addr, dword_t len, dword_t flags, addr_t sockaddr_addr, dword_t sockaddr_len) { + struct fd *sock = sock_getfd(sock_fd); + if (sock == NULL) + return _EBADF; + char *buffer = malloc((size_t) len + 1); + if (buffer == NULL) + return _ENOMEM; + if (user_read(buffer_addr, buffer, len)) { + free(buffer); + return _EFAULT; + } + buffer[len] = '\0'; + STRACE("sendto(%d, \"%.100s\", %d, %d, 0x%x, %d)", sock_fd, buffer, len, flags, sockaddr_addr, sockaddr_len); + int real_flags = sock_flags_to_real(flags); + int err = _EINVAL; + if (real_flags < 0) + goto error; + struct sockaddr_max_ sockaddr; + if (sockaddr_addr) { + err = sockaddr_read(sockaddr_addr, &sockaddr, &sockaddr_len); + if (err < 0) + goto error; + } + + ssize_t res = sendto(sock->real_fd, buffer, len, real_flags, + sockaddr_addr ? (void *) &sockaddr : NULL, sockaddr_len); + free(buffer); + if (res < 0) + return errno_map(); + return res; + +error: + free(buffer); + return err; +} + +// Read a socket timeout option as milliseconds. Returns 0 if unset or error. +static long sock_get_timeout_ms(int real_fd, int optname) { + struct timeval tv = {0, 0}; + socklen_t len = sizeof(tv); + if (getsockopt(real_fd, SOL_SOCKET, optname, &tv, &len) < 0) + return 0; + return (long)tv.tv_sec * 1000L + (long)tv.tv_usec / 1000L; +} + +static long monotonic_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (long)ts.tv_sec * 1000L + (long)ts.tv_nsec / 1000000L; +} + +// Wait for a socket fd to become ready (readable or writable), with a +// bounded per-poll timeout so guest signals can interrupt even if the host +// thread is briefly suspended (iOS). Honors SO_RCVTIMEO / SO_SNDTIMEO as +// an overall deadline when set. +// +// Returns 0 when ready, _EINTR on guest signal, _EAGAIN on timeout expiry, +// or a negative errno on poll() error. +static int sock_wait_for(int real_fd, short events, int timeout_opt) { + long timeout_ms = sock_get_timeout_ms(real_fd, timeout_opt); + long start_ms = monotonic_ms(); + long deadline_ms = (timeout_ms > 0) ? (start_ms + timeout_ms) : 0; + bool slow_logged = false; + for (;;) { + if (current->exiting || current->group->doing_group_exit) + return _EINTR; + if (current->sighand != NULL) { + lock(¤t->sighand->lock); + bool pending = !!(current->pending & ~current->blocked); + unlock(¤t->sighand->lock); + if (pending) + return _EINTR; + } + + // Keep this shorter than exit_group's safety-valve window so helper + // threads blocked in recv/recvmsg can observe SIGKILL/exiting and + // leave cleanly instead of being detached as leaked host threads. + int poll_ms = 50; + if (deadline_ms > 0) { + long remaining = deadline_ms - monotonic_ms(); + if (remaining <= 0) { + printk("NETDIAG sock_wait(pid=%d comm=%s fd=%d ev=%#x) deadline-expired after %ldms\n", + current->pid, current->comm, real_fd, events, timeout_ms); + return _EAGAIN; + } + if (remaining < poll_ms) + poll_ms = (int)remaining; + } + + struct pollfd pfd = { .fd = real_fd, .events = events }; + current->blocking = true; + int pr = poll(&pfd, 1, poll_ms); + int saved_errno = errno; + current->blocking = false; + if (current->exiting || current->group->doing_group_exit) + return _EINTR; + + if (pr > 0) + return 0; + if (pr == 0) { + // Log once if we're stuck > 3 seconds without any ready event + if (!slow_logged && (monotonic_ms() - start_ms) >= 3000) { + printk("NETDIAG sock_wait(pid=%d comm=%s fd=%d ev=%#x) no-event for 3s (timeout_opt_ms=%ld)\n", + current->pid, current->comm, real_fd, events, timeout_ms); + slow_logged = true; + } + continue; + } + if (saved_errno == EINTR) + continue; + errno = saved_errno; + printk("NETDIAG sock_wait(pid=%d comm=%s fd=%d ev=%#x) poll err=%d\n", + current->pid, current->comm, real_fd, events, saved_errno); + return errno_map(); + } +} + +static int sock_wait_readable(int real_fd) { + return sock_wait_for(real_fd, POLLIN, SO_RCVTIMEO); +} + +int_t sys_recvfrom(fd_t sock_fd, addr_t buffer_addr, dword_t len, dword_t flags, addr_t sockaddr_addr, addr_t sockaddr_len_addr) { + STRACE("recvfrom(%d, 0x%x, %d, %d, 0x%x, 0x%x)", sock_fd, buffer_addr, len, flags, sockaddr_addr, sockaddr_len_addr); + struct fd *sock = sock_getfd(sock_fd); + if (sock == NULL) + return _EBADF; + int real_flags = sock_flags_to_real(flags); + if (real_flags < 0) + return _EINVAL; + uint_t sockaddr_len = 0; + uint_t sockaddr_buffer_len = 0; + if (sockaddr_len_addr != 0) { + if (user_get(sockaddr_len_addr, sockaddr_len)) + return _EFAULT; + sockaddr_buffer_len = sockaddr_len; + if (sockaddr_len > sizeof(struct sockaddr_max_)) + sockaddr_len = sizeof(struct sockaddr_max_); + } + + char *buffer = malloc(len); + if (len != 0 && buffer == NULL) + return _ENOMEM; + struct sockaddr_max_ sockaddr; + + // Determine whether this call should wait for data: + // * guest flags MSG_DONTWAIT → never wait (explicit) + // * fd has O_NONBLOCK set → never wait (fd-level nonblock) + // + // The second case is critical: musl's res_msend creates UDP sockets + // with SOCK_NONBLOCK and then calls recv(fd, buf, len, 0). It relies + // on the kernel returning EAGAIN immediately on empty buffer to + // terminate its "drain all pending responses" loop. If we wait when + // the fd itself is nonblock, musl loops forever and DNS resolution + // appears to hang. We check both the iSH-level fd flags and the host + // fd's real flags, in case they diverge (e.g. set via fcntl only). + int host_flags = fcntl(sock->real_fd, F_GETFL, 0); + bool host_nonblock = (host_flags >= 0) && (host_flags & O_NONBLOCK); + bool guest_nonblock = (sock->flags & O_NONBLOCK_) != 0; + bool should_wait = !(real_flags & MSG_DONTWAIT) && !guest_nonblock && !host_nonblock; + + // Try a nonblock recvfrom first (fast path — no host syscall overhead + // when data is already buffered). Only if it returns EAGAIN and we + // should wait do we fall back to the bounded-poll wait. + ssize_t res; + if (should_wait) { + for (;;) { + res = recvfrom(sock->real_fd, buffer, len, real_flags | MSG_DONTWAIT, + sockaddr_addr != 0 ? (void *) &sockaddr : NULL, + sockaddr_len_addr != 0 ? &sockaddr_len : NULL); + if (res >= 0) + break; + if (errno == EINTR) + continue; + if (errno != EAGAIN && errno != EWOULDBLOCK) { + free(buffer); + return errno_map(); + } + // EAGAIN: no data yet. Wait (bounded) for readability or a + // guest signal, then retry. + int wr = sock_wait_readable(sock->real_fd); + if (wr < 0) { + free(buffer); + return wr; + } + } + } else { + res = recvfrom(sock->real_fd, buffer, len, real_flags, + sockaddr_addr != 0 ? (void *) &sockaddr : NULL, + sockaddr_len_addr != 0 ? &sockaddr_len : NULL); + if (res < 0) { + free(buffer); + return errno_map(); + } + } + + if (res > 0 && user_write(buffer_addr, buffer, (size_t) res)) { + free(buffer); + return _EFAULT; + } + free(buffer); + if (sockaddr_addr != 0) { + int err = sockaddr_write(sockaddr_addr, &sockaddr, sockaddr_buffer_len, &sockaddr_len); + if (err < 0) + return err; + } + if (sockaddr_len_addr != 0) + if (user_put(sockaddr_len_addr, sockaddr_len)) + return _EFAULT; + return res; +} + +int_t sys_send(fd_t sock_fd, addr_t buf, dword_t len, int_t flags) { + return sys_sendto(sock_fd, buf, len, flags, 0, 0); +} + +int_t sys_recv(fd_t sock_fd, addr_t buf, dword_t len, int_t flags) { + return sys_recvfrom(sock_fd, buf, len, flags, 0, 0); +} + +int_t sys_shutdown(fd_t sock_fd, dword_t how) { + STRACE("shutdown(%d, %d)", sock_fd, how); + struct fd *sock = sock_getfd(sock_fd); + if (sock == NULL) + return _EBADF; + int err = shutdown(sock->real_fd, how); + if (err < 0) + return errno_map(); + return 0; +} + +#define DEFAULT_TCP_CONGESTION "cubic" + +int_t sys_setsockopt(fd_t sock_fd, dword_t level, dword_t option, addr_t value_addr, dword_t value_len) { + STRACE("setsockopt(%d, %d, %d, 0x%x, %d)", sock_fd, level, option, value_addr, value_len); + struct fd *sock = sock_getfd(sock_fd); + if (sock == NULL) + return _EBADF; + + char *value = NULL; + if (value_len != 0) { + value = malloc(value_len); + if (value == NULL) + return _ENOMEM; + if (user_read(value_addr, value, value_len)) { + free(value); + return _EFAULT; + } + } + + int ret = 0; + + // ICMP6_FILTER can only be set on real SOCK_RAW + if (level == IPPROTO_ICMPV6 && option == ICMP6_FILTER_) + goto out; + // IP_MTU_DISCOVER has no equivalent on Darwin + if (level == IPPROTO_IP && option == IP_MTU_DISCOVER_) + goto out; + // TCP_CONGESTION also has no equivalent on Darwin +#if defined(__APPLE__) + if (level == IPPROTO_TCP && option == TCP_CONGESTION_) { + size_t default_len = strlen(DEFAULT_TCP_CONGESTION); + bool has_nul = value_len == default_len + 1 && value[default_len] == '\0'; + bool same_len = value_len == default_len || has_nul; + if (same_len && memcmp(value, DEFAULT_TCP_CONGESTION, default_len) == 0) + goto out; + ret = _ENOENT; + goto out; + } +#endif + + int real_opt = sock_opt_to_real(option, level); + if (real_opt < 0) { + ret = _EINVAL; + goto out; + } + int real_level = sock_level_to_real(level); + if (real_level < 0) { + ret = _EINVAL; + goto out; + } + + // 0 means the option is not implemented, but things rely on it, so we + // should just ignore attempts to set it. + if (real_opt == 0) + goto out; + + int err = setsockopt(sock->real_fd, real_level, real_opt, value, value_len); + if (err < 0) + ret = errno_map(); + +out: + free(value); + return ret; +} + +int_t sys_getsockopt(fd_t sock_fd, dword_t level, dword_t option, addr_t value_addr, addr_t len_addr) { + STRACE("getsockopt(%d, %d, %d, %#x, %#x)", sock_fd, level, option, value_addr, len_addr); + struct fd *sock = sock_getfd(sock_fd); + if (sock == NULL) + return _EBADF; + dword_t value_len; + if (user_get(len_addr, value_len)) + return _EFAULT; + dword_t buffer_len = value_len; + + char *value = NULL; + if (buffer_len != 0) { + value = malloc(buffer_len); + if (value == NULL) + return _ENOMEM; + } + + int ret = 0; + + if (level == SOL_SOCKET_ && (option == SO_DOMAIN_ || option == SO_TYPE_ || option == SO_PROTOCOL_)) { + dword_t *value_p = (dword_t *) value; + if (buffer_len != sizeof(*value_p)) { + ret = _EINVAL; + goto out; + } + if (option == SO_DOMAIN_) + *value_p = sock->socket.domain; + else if (option == SO_TYPE_) + *value_p = sock->socket.type; + else if (option == SO_PROTOCOL_) + *value_p = sock->socket.protocol; + value_len = sizeof(*value_p); + } else if (level == SOL_SOCKET_ && option == SO_PEERCRED_) { + struct ucred_ *cred = (struct ucred_ *) value; + if (buffer_len != sizeof(*cred)) { + ret = _EINVAL; + goto out; + } + lock(&peer_lock); + if (sock->socket.domain != AF_LOCAL_ || sock->socket.unix_peer == NULL) { + cred->pid = 0; + cred->uid = cred->gid = -1; + } else { + *cred = sock->socket.unix_peer->socket.unix_cred; + } + unlock(&peer_lock); + value_len = sizeof(*cred); + } else if (level == SOL_SOCKET_ && option == SO_ERROR_) { + if (buffer_len != sizeof(dword_t)) { + ret = _EINVAL; + goto out; + } + int real_error; + socklen_t real_error_len = sizeof(real_error); + int err = getsockopt(sock->real_fd, SOL_SOCKET, SO_ERROR, &real_error, &real_error_len); + if (err < 0) { + ret = errno_map(); + goto out; + } + *(dword_t *) value = real_error == 0 ? 0 : -err_map(real_error); + value_len = sizeof(dword_t); + } else if (level == IPPROTO_TCP && option == TCP_CONGESTION_) { + value_len = strlen(DEFAULT_TCP_CONGESTION); + size_t copy_len = buffer_len < value_len ? buffer_len : value_len; + if (copy_len != 0) + memcpy(value, DEFAULT_TCP_CONGESTION, copy_len); +#if defined(__APPLE__) + } else if (level == IPPROTO_TCP && option == TCP_INFO_) { + // This one's fun. On Linux, the struct is not ABI dependent, so no + // special handling is needed. On Darwin, the struct is completely + // different and has a different sockopt name. + struct tcp_connection_info conn_info; + socklen_t conn_info_size = sizeof(conn_info); + int err = getsockopt(sock->real_fd, IPPROTO_TCP, TCP_CONNECTION_INFO, &conn_info, &conn_info_size); + if (err < 0) { + ret = errno_map(); + goto out; + } + + // The possible keys for this table are in netinet/tcp_fsm.h, but that + // header isn't available on iOS, only macOS. + static const uint8_t tcp_state_table[] = { + 7, // TCPS_CLOSED + 10, // TCPS_LISTEN + 2, // TCPS_SYN_SENT + 3, // TCPS_SYN_RECEIVED + 1, // TCPS_ESTABLISHED + 8, // TCPS_CLOSE_WAIT + 4, // TCPS_FIN_WAIT_1 + 11, // TCPS_CLOSING + 9, // TCPS_LAST_ACK + 5, // TCPS_FIN_WAIT_2 + 6, // TCPS_TIME_WAIT + }; + struct tcp_info_ info = { + .state = tcp_state_table[conn_info.tcpi_state], + .options = conn_info.tcpi_options, + .snd_wscale = conn_info.tcpi_snd_wscale, + .rcv_wscale = conn_info.tcpi_rcv_wscale, + + .rto = conn_info.tcpi_rto * 1000, + .snd_mss = conn_info.tcpi_maxseg, + + .rtt = conn_info.tcpi_srtt * 1000, + .rttvar = conn_info.tcpi_rttvar * 1000, + .snd_ssthresh = conn_info.tcpi_snd_ssthresh, + .snd_cwnd = conn_info.tcpi_snd_cwnd / conn_info.tcpi_maxseg, + + // https://lkml.org/lkml/2017/4/24/923 + .total_retrans = conn_info.tcpi_txretransmitpackets, + }; + value_len = sizeof(struct tcp_info_); + size_t copy_len = buffer_len < value_len ? buffer_len : value_len; + if (copy_len != 0) + memcpy(value, &info, copy_len); +#endif + } else { + int real_opt = sock_opt_to_real(option, level); + if (real_opt < 0) { + ret = _EINVAL; + goto out; + } + int real_level = sock_level_to_real(level); + if (real_level < 0) { + ret = _EINVAL; + goto out; + } + + socklen_t real_value_len = value_len; + int err = getsockopt(sock->real_fd, real_level, real_opt, value, &real_value_len); + if (err < 0) { + ret = errno_map(); + goto out; + } + value_len = real_value_len; + } + + if (user_put(len_addr, value_len)) { + ret = _EFAULT; + goto out; + } + size_t write_len = buffer_len < value_len ? buffer_len : value_len; + if (write_len != 0 && user_write(value_addr, value, write_len)) + ret = _EFAULT; + +out: + free(value); + return ret; +} + +#ifdef GUEST_ARM64 +#define cmsghdr_guest cmsghdr64_ +#define CMSG_NXTHDR_GUEST CMSG_NXTHDR64_ +#else +#define cmsghdr_guest cmsghdr_ +#define CMSG_NXTHDR_GUEST CMSG_NXTHDR_ +#endif + +static void scm_free(struct scm *scm) { + for (unsigned i = 0; i < scm->num_fds; i++) + fd_close(scm->fds[i]); + free(scm); +} + +int_t sys_sendmsg(fd_t sock_fd, addr_t msghdr_addr, int_t flags) { + int err; + STRACE("sendmsg(%d, %#x, %d)", sock_fd, msghdr_addr, flags); + struct fd *sock = sock_getfd(sock_fd); + if (sock == NULL) + return _EBADF; + + // Read the guest msghdr struct into our internal 32-bit representation + struct msghdr msg; + struct msghdr_ msg_fake; +#ifdef GUEST_ARM64 + struct msghdr64_ msg_fake64; + if (user_get(msghdr_addr, msg_fake64)) + return _EFAULT; + msg_fake.msg_name = (addr_t)msg_fake64.msg_name; + msg_fake.msg_namelen = msg_fake64.msg_namelen; + msg_fake.msg_iov = (addr_t)msg_fake64.msg_iov; + msg_fake.msg_iovlen = (uint_t)msg_fake64.msg_iovlen; + msg_fake.msg_control = (addr_t)msg_fake64.msg_control; + msg_fake.msg_controllen = (uint_t)msg_fake64.msg_controllen; + msg_fake.msg_flags = msg_fake64.msg_flags; +#else + if (user_get(msghdr_addr, msg_fake)) + return _EFAULT; +#endif + if (msg_fake.msg_iovlen > 1024) + return _EMSGSIZE; + if (msg_fake.msg_iovlen != 0 && msg_fake.msg_iov == 0) + return _EFAULT; + + // msg_name + struct sockaddr_max_ msg_name; + if (msg_fake.msg_name != 0) { + int err = sockaddr_read(msg_fake.msg_name, &msg_name, &msg_fake.msg_namelen); + if (err < 0) + return err; + msg.msg_name = &msg_name; + msg.msg_namelen = msg_fake.msg_namelen; + } else { + msg.msg_name = NULL; + } + + // msg_iovec +#ifdef GUEST_ARM64 + struct iovec64_ msg_iov_fake64[msg_fake.msg_iovlen]; + if (user_read(msg_fake.msg_iov, msg_iov_fake64, sizeof(msg_iov_fake64))) + return _EFAULT; + struct iovec msg_iov[msg_fake.msg_iovlen]; + memset(msg_iov, 0, sizeof(msg_iov)); + msg.msg_iov = msg_iov; + msg.msg_iovlen = msg_fake.msg_iovlen; + for (size_t i = 0; i < (size_t) msg.msg_iovlen; i++) { + msg_iov[i].iov_len = (size_t)msg_iov_fake64[i].len; + msg_iov[i].iov_base = malloc(msg_iov[i].iov_len); + if (msg_iov[i].iov_len != 0 && msg_iov[i].iov_base == NULL) { + err = _ENOMEM; + goto out_free_iov; + } + err = _EFAULT; + if (user_read((addr_t)msg_iov_fake64[i].base, msg_iov[i].iov_base, msg_iov[i].iov_len)) + goto out_free_iov; + } +#else + struct iovec_ msg_iov_fake[msg_fake.msg_iovlen]; + if (user_get(msg_fake.msg_iov, msg_iov_fake)) + return _EFAULT; + struct iovec msg_iov[msg_fake.msg_iovlen]; + memset(msg_iov, 0, sizeof(msg_iov)); + msg.msg_iov = msg_iov; + msg.msg_iovlen = sizeof(msg_iov) / sizeof(msg_iov[0]); + for (size_t i = 0; i < (size_t) msg.msg_iovlen; i++) { + msg_iov[i].iov_len = msg_iov_fake[i].len; + msg_iov[i].iov_base = malloc(msg_iov_fake[i].len); + if (msg_iov[i].iov_len != 0 && msg_iov[i].iov_base == NULL) { + err = _ENOMEM; + goto out_free_iov; + } + err = _EFAULT; + if (user_read(msg_iov_fake[i].base, msg_iov[i].iov_base, msg_iov_fake[i].len)) + goto out_free_iov; + } +#endif + + // msg_control + uint8_t msg_control_buf[2048]; + uint8_t *msg_control = NULL; + if (msg_fake.msg_control != 0) { + if (msg_fake.msg_controllen > sizeof(msg_control_buf)) { + err = _EINVAL; + goto out_free_iov; + } + msg_control = msg_control_buf; + err = _EFAULT; + if (user_read(msg_fake.msg_control, msg_control, msg_fake.msg_controllen)) + goto out_free_iov; + } + msg.msg_control = NULL; + msg.msg_controllen = 0; + + struct scm *scm = NULL; + char real_msg_control[CMSG_SPACE(sizeof(int))]; // only used if actually sending an fd + if (sock->socket.domain == AF_LOCAL_ && msg_control != NULL && msg_fake.msg_controllen >= sizeof(struct cmsghdr_guest)) { + // figure out how many file descriptors we're sending + uint8_t *mhdr_end = msg_control + msg_fake.msg_controllen; + unsigned num_fds = 0; + struct cmsghdr_guest *cmsg; + for (cmsg = (void *) msg_control; cmsg != NULL; cmsg = CMSG_NXTHDR_GUEST(cmsg, mhdr_end)) { + size_t remaining = (size_t)(mhdr_end - (uint8_t *)cmsg); + if (cmsg->len < sizeof(struct cmsghdr_guest) || cmsg->len > remaining) { + err = _EINVAL; + goto out_free_iov; + } + if (cmsg->level != SOL_SOCKET_) + continue; + if (cmsg->type != SCM_RIGHTS_) { + err = _EINVAL; + goto out_free_iov; + } + num_fds += (cmsg->len - sizeof(struct cmsghdr_guest)) / sizeof(fd_t); + } + if (num_fds > 253) { // *magic* + err = _EINVAL; + goto out_free_iov; + } + + if (num_fds > 0) { + // send one (1) real fd and put the rest in a struct scm + static int real_fd = -1; + if (real_fd == -1) { + real_fd = open(".", O_RDONLY); + if (real_fd < 0) + ERRNO_DIE("no"); + } + msg.msg_control = real_msg_control; + msg.msg_controllen = sizeof(real_msg_control); + struct cmsghdr *real_cmsg = CMSG_FIRSTHDR(&msg); + real_cmsg->cmsg_level = SOL_SOCKET; + real_cmsg->cmsg_type = SCM_RIGHTS; + real_cmsg->cmsg_len = CMSG_LEN(sizeof(real_fd)); + memcpy(CMSG_DATA(real_cmsg), &real_fd, sizeof(real_fd)); + + scm = malloc(sizeof(struct scm) + num_fds * sizeof(struct fd *)); + if (scm == NULL) { + err = _ENOMEM; + goto out_free_iov; + } + list_init(&scm->queue); + scm->num_fds = 0; + unsigned fd_i = 0; + for (cmsg = (void *) msg_control; cmsg != NULL; cmsg = CMSG_NXTHDR_GUEST(cmsg, mhdr_end)) { + size_t remaining = (size_t)(mhdr_end - (uint8_t *)cmsg); + if (cmsg->len < sizeof(struct cmsghdr_guest) || cmsg->len > remaining) { + err = _EINVAL; + goto out_free_scm; + } + if (cmsg->level != SOL_SOCKET_) + continue; + fd_t *fds = (void *) cmsg->data; + for (unsigned i = 0; i < (cmsg->len - sizeof(struct cmsghdr_guest)) / sizeof(fd_t); i++) { + STRACE(" sending fd %d", fds[i]); + struct fd *send_fd = f_get(fds[i]); + if (send_fd == NULL) { + err = _EBADF; + goto out_free_scm; + } + scm->fds[fd_i++] = fd_retain(send_fd); + scm->num_fds = fd_i; + } + } + lock(&peer_lock); + struct fd *peer = sock->socket.unix_peer; + if (peer == NULL) { + unlock(&peer_lock); + err = _EPIPE; + goto out_free_scm; + } + lock(&peer->lock); + list_add_tail(&peer->socket.unix_scm, &scm->queue); + unlock(&peer->lock); + unlock(&peer_lock); + } + } + + msg.msg_flags = sock_flags_to_real(msg_fake.msg_flags); + err = _EINVAL; + if (msg.msg_flags < 0) + goto out_free_scm; + int real_flags = sock_flags_to_real(flags); + if (real_flags < 0) + goto out_free_scm; + + err = sendmsg(sock->real_fd, &msg, real_flags); + if (err < 0) { + err = errno_map(); + goto out_free_scm; + } + goto out_free_iov; + +out_free_scm: + if (scm != NULL) { + lock(&peer_lock); + struct fd *peer = sock->socket.unix_peer; + if (peer != NULL) { + lock(&peer->lock); + list_remove_safe(&scm->queue); + unlock(&peer->lock); + } + unlock(&peer_lock); + scm_free(scm); + } +out_free_iov: + for (size_t i = 0; i < (size_t) msg.msg_iovlen; i++) + free(msg_iov[i].iov_base); + return err; +} + +int_t sys_recvmsg(fd_t sock_fd, addr_t msghdr_addr, int_t flags) { + STRACE("recvmsg(%d, %#x, %d)", sock_fd, msghdr_addr, flags); + struct fd *sock = sock_getfd(sock_fd); + if (sock == NULL) + return _EBADF; + + // Read the guest msghdr struct into our internal 32-bit representation + struct msghdr_ msg_fake; +#ifdef GUEST_ARM64 + struct msghdr64_ msg_fake64; + if (user_get(msghdr_addr, msg_fake64)) + return _EFAULT; + msg_fake.msg_name = (addr_t)msg_fake64.msg_name; + msg_fake.msg_namelen = msg_fake64.msg_namelen; + msg_fake.msg_iov = (addr_t)msg_fake64.msg_iov; + msg_fake.msg_iovlen = (uint_t)msg_fake64.msg_iovlen; + msg_fake.msg_control = (addr_t)msg_fake64.msg_control; + msg_fake.msg_controllen = (uint_t)msg_fake64.msg_controllen; + msg_fake.msg_flags = msg_fake64.msg_flags; +#else + if (user_get(msghdr_addr, msg_fake)) + return _EFAULT; +#endif + if (msg_fake.msg_iovlen > 1024) + return _EMSGSIZE; + if (msg_fake.msg_iovlen != 0 && msg_fake.msg_iov == 0) + return _EFAULT; + + struct msghdr msg; + + // msg_name + struct sockaddr_max_ msg_name; + uint_t msg_name_buffer_len = msg_fake.msg_namelen; + if (msg_fake.msg_name != 0) { + msg.msg_name = &msg_name; + msg.msg_namelen = msg_name_buffer_len; + if (msg.msg_namelen > sizeof(msg_name)) + msg.msg_namelen = sizeof(msg_name); + } else { + msg.msg_name = NULL; + msg.msg_namelen = 0; + } + + char real_msg_control[CMSG_SPACE(sizeof(int))] = {}; // only used if needed + if (msg_fake.msg_controllen != 0) { + // msg_control, include room for one (1) fd + msg.msg_control = real_msg_control; + msg.msg_controllen = sizeof(real_msg_control); + } else { + msg.msg_control = NULL; + msg.msg_controllen = 0; + } + + int real_flags = sock_flags_to_real(flags); + if (real_flags < 0) + return _EINVAL; + + // msg_iovec (no initial content) +#ifdef GUEST_ARM64 + struct iovec64_ msg_iov_fake64[msg_fake.msg_iovlen]; + if (user_read(msg_fake.msg_iov, msg_iov_fake64, sizeof(msg_iov_fake64))) + return _EFAULT; + struct iovec msg_iov[msg_fake.msg_iovlen]; + msg.msg_iov = msg_iov; + msg.msg_iovlen = msg_fake.msg_iovlen; + addr_t msg_iov_bases[msg_fake.msg_iovlen]; // save guest base addrs for writeback + for (size_t i = 0; i < (size_t) msg.msg_iovlen; i++) { + msg_iov_bases[i] = (addr_t)msg_iov_fake64[i].base; + msg_iov[i].iov_len = (size_t)msg_iov_fake64[i].len; + msg_iov[i].iov_base = malloc(msg_iov[i].iov_len); + if (msg_iov[i].iov_len != 0 && msg_iov[i].iov_base == NULL) { + for (size_t j = 0; j < i; j++) + free(msg_iov[j].iov_base); + return _ENOMEM; + } + } +#else + struct iovec_ msg_iov_fake[msg_fake.msg_iovlen]; + if (user_get(msg_fake.msg_iov, msg_iov_fake)) + return _EFAULT; + struct iovec msg_iov[msg_fake.msg_iovlen]; + msg.msg_iov = msg_iov; + msg.msg_iovlen = sizeof(msg_iov) / sizeof(msg_iov[0]); + for (size_t i = 0; i < (size_t) msg.msg_iovlen; i++) { + msg_iov[i].iov_len = msg_iov_fake[i].len; + msg_iov[i].iov_base = malloc(msg_iov_fake[i].len); + if (msg_iov[i].iov_len != 0 && msg_iov[i].iov_base == NULL) { + for (size_t j = 0; j < i; j++) + free(msg_iov[j].iov_base); + return _ENOMEM; + } + } +#endif + + // Same iOS-safe wait pattern as sys_recvfrom: avoid unbounded blocking + // in host recvmsg() so guest signals can always be delivered. But only + // wait when the caller actually wants blocking behavior — if the fd is + // nonblock (SOCK_NONBLOCK set by guest or via fcntl), surface EAGAIN + // immediately instead of waiting. This is critical for musl's + // res_msend, which creates nonblock sockets and calls + // recvmsg(fd, &mh, 0) — it relies on EAGAIN on empty buffer to end its + // "drain pending responses" loop. Same bug that used to affect + // sys_recvfrom before 76907b86. + int host_flags_rm = fcntl(sock->real_fd, F_GETFL, 0); + bool host_nonblock_rm = (host_flags_rm >= 0) && (host_flags_rm & O_NONBLOCK); + bool guest_nonblock_rm = (sock->flags & O_NONBLOCK_) != 0; + bool should_wait_rm = !(real_flags & MSG_DONTWAIT) && !guest_nonblock_rm && !host_nonblock_rm; + + ssize_t res = -1; + int err = 0; + if (should_wait_rm) { + for (;;) { + res = recvmsg(sock->real_fd, &msg, real_flags | MSG_DONTWAIT); + if (res >= 0) + break; + if (errno == EINTR) + continue; + if (errno != EAGAIN && errno != EWOULDBLOCK) { + err = errno_map(); + break; + } + int wr = sock_wait_readable(sock->real_fd); + if (wr < 0) { + err = wr; + break; + } + } + } else { + res = recvmsg(sock->real_fd, &msg, real_flags); + if (res < 0) + err = errno_map(); + } + // don't return err quite yet, there are outstanding mallocs + + // msg_iovec (changed) + // copy as many bytes as were received, according to the return value + size_t n = res; + if (res < 0) + n = 0; + for (size_t i = 0; i < (size_t) msg.msg_iovlen; i++) { + size_t chunk_size = msg_iov[i].iov_len; + if (chunk_size > n) + chunk_size = n; + if (chunk_size > 0) { +#ifdef GUEST_ARM64 + if (user_write(msg_iov_bases[i], msg_iov[i].iov_base, chunk_size)) +#else + if (user_write(msg_iov_fake[i].base, msg_iov[i].iov_base, chunk_size)) +#endif + { + err = _EFAULT; + n = chunk_size; + } + } + n -= chunk_size; + free(msg_iov[i].iov_base); + } + if (err < 0 && res >= 0) + return err; + + // msg_control (changed) + uint_t msg_control_buffer_len = msg_fake.msg_controllen; + msg_fake.msg_controllen = 0; + struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); + if (sock->socket.domain == AF_LOCAL_ && cmsg != NULL && + cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) { + int dummy_fd = ((int *) CMSG_DATA(cmsg))[0]; + close(dummy_fd); + + lock(&sock->lock); + if (list_empty(&sock->socket.unix_scm)) { + unlock(&sock->lock); + return _EINVAL; + } + struct scm *scm = list_first_entry(&sock->socket.unix_scm, struct scm, queue); + list_remove(&scm->queue); + unlock(&sock->lock); + + if (res < 0) { + scm_free(scm); + return err; + } + + uint8_t msg_control[sizeof(struct cmsghdr_guest) + scm->num_fds * sizeof(fd_t)]; + struct cmsghdr_guest *cmsg = (void *) msg_control; + cmsg->len = sizeof(msg_control); + cmsg->level = SOL_SOCKET_; + cmsg->type = SCM_RIGHTS_; + if (msg_fake.msg_control == 0 || msg_control_buffer_len < cmsg->len) { + scm_free(scm); + return _EINVAL; + } + fd_t installed_fds[253]; + unsigned installed_count = 0; + fd_t *fds = (void *) cmsg->data; + for (unsigned i = 0; i < scm->num_fds; i++) { + fds[i] = f_install(scm->fds[i], 0); + STRACE(" receiving fd %d", fds[i]); + if (fds[i] < 0) { + for (unsigned j = 0; j < installed_count; j++) + sys_close(installed_fds[j]); + for (unsigned j = i + 1; j < scm->num_fds; j++) + fd_close(scm->fds[j]); + int install_err = fds[i]; + free(scm); + return install_err; + } + installed_fds[installed_count++] = fds[i]; + } + if (user_write(msg_fake.msg_control, cmsg, cmsg->len)) { + for (unsigned i = 0; i < installed_count; i++) + sys_close(installed_fds[i]); + free(scm); + return _EFAULT; + } + free(scm); + msg_fake.msg_controllen = cmsg->len; + } + + // by now the iovecs and scm have been freed so we can return + if (res < 0) + return err; + + // msg_name (changed) + if (msg.msg_name != 0) { + int err = sockaddr_write(msg_fake.msg_name, msg.msg_name, msg_name_buffer_len, &msg.msg_namelen); + if (err < 0) + return err; + } + msg_fake.msg_namelen = msg.msg_namelen; + + // msg_flags (changed) + msg_fake.msg_flags = sock_flags_from_real(msg.msg_flags); + + // Write back the updated msghdr to guest memory +#ifdef GUEST_ARM64 + msg_fake64.msg_namelen = msg_fake.msg_namelen; + msg_fake64.msg_controllen = msg_fake.msg_controllen; + msg_fake64.msg_flags = msg_fake.msg_flags; + if (user_put(msghdr_addr, msg_fake64)) + return _EFAULT; +#else + if (user_put(msghdr_addr, msg_fake)) + return _EFAULT; +#endif + return res; +} + +struct mmsghdr_ { + struct msghdr_ hdr; + uint_t len; +}; + +#ifdef GUEST_ARM64 +struct mmsghdr64_ { + struct msghdr64_ hdr; + uint32_t len; + uint32_t _pad; +}; +#endif + +int_t sys_recvmmsg(fd_t sock_fd, addr_t msg_vec, uint_t vec_len, int_t flags, addr_t timeout_addr) { + STRACE("recvmmsg(%d, %#x, %d, %d)", sock_fd, msg_vec, vec_len, flags); + (void) timeout_addr; + int num_recv = 0; +#ifdef GUEST_ARM64 + size_t mmsghdr_size = sizeof(struct mmsghdr64_); + size_t len_offset = offsetof(struct mmsghdr64_, len); +#else + size_t mmsghdr_size = sizeof(struct mmsghdr_); + size_t len_offset = offsetof(struct mmsghdr_, len); +#endif + for (unsigned i = 0; i < vec_len; i++) { + addr_t msghdr = msg_vec + i * mmsghdr_size; + int_t res = sys_recvmsg(sock_fd, msghdr, flags); + if (res >= 0) { + addr_t msg_len_addr = msghdr + len_offset; + if (user_put(msg_len_addr, res)) + res = _EFAULT; + } + if (res < 0) { + if (num_recv > 0) + break; + return res; + } + num_recv++; + if (res == 0) + break; + } + return num_recv; +} + +int_t sys_sendmmsg(fd_t sock_fd, addr_t msg_vec, uint_t vec_len, int_t flags) { + int num_sent = 0; +#ifdef GUEST_ARM64 + size_t mmsghdr_size = sizeof(struct mmsghdr64_); + size_t len_offset = offsetof(struct mmsghdr64_, len); +#else + size_t mmsghdr_size = sizeof(struct mmsghdr_); + size_t len_offset = offsetof(struct mmsghdr_, len); +#endif + for (unsigned i = 0; i < vec_len; i++) { + addr_t msghdr = msg_vec + i * mmsghdr_size; + int_t res = sys_sendmsg(sock_fd, msghdr, flags); + if (res >= 0) { + addr_t msg_len_addr = msghdr + len_offset; + if (user_put(msg_len_addr, res)) + res = _EFAULT; + } + if (res < 0) { + // From the man page: + // If an error occurs after at least one message has been sent, the + // call succeeds, and returns the number of messages sent. The + // error code is lost. + if (num_sent > 0) + break; + return res; + } + num_sent++; + if (res == 0) { + // This means the socket is non-blocking and can't be written to anymore. + break; + } + } + return num_sent; +} + +static void sock_translate_err(struct fd *fd, int *err) { + // on ios, when the device goes to sleep, all connected sockets are killed. + // reads/writes return ENOTCONN, which I'm pretty sure is a violation of + // posix. so instead, detect this and return ECONNRESET. + if (*err == _ENOTCONN) { + struct sockaddr addr; + socklen_t len = sizeof(addr); + if (getpeername(fd->real_fd, &addr, &len) < 0 && errno == EINVAL) { + *err = _ECONNRESET; + } + } +} + +// sock_read / sock_write: behave exactly like realfs_read / realfs_write +// (a single host read/write call, with no poll and no flag change), except +// that EINTR is handled specially: if there is a guest signal pending, we +// surface EINTR back to the guest instead of blindly retrying. +// +// The original realfs_read/realfs_write does `while (errno == EINTR) retry`, +// which swallows the SIGUSR1 wake iSH uses to deliver guest signals into +// blocked host syscalls. Combined with iOS occasionally deferring signal +// delivery (thread suspension on backgrounding), this causes indefinite +// hangs on any blocking socket read/write (git HTTPS, nc, telnet, etc.). +// +// We intentionally do NOT poll, do NOT mess with nonblock flags, and do NOT +// switch to recv/send. This minimizes regression risk — the host I/O path +// is byte-for-byte identical to the original implementation for every case +// except "host syscall got EINTR AND guest has a pending signal", which is +// precisely the bug we need to fix. +static ssize_t sock_read(struct fd *fd, void *buf, size_t size) { + int err; + int eintr_count = 0; + for (;;) { + ssize_t res = read(fd->real_fd, buf, size); + if (res >= 0) { err = (int)res; break; } + if (errno != EINTR) { err = errno_map(); break; } + eintr_count++; + // EINTR: only surface to guest if there is actually a pending signal + // that the guest wants to handle. Otherwise retry (matches the + // original realfs_read behavior for spurious EINTR). + if (current->sighand != NULL) { + lock(¤t->sighand->lock); + bool pending = !!(current->pending & ~current->blocked); + unlock(¤t->sighand->lock); + if (pending) { err = _EINTR; break; } + } + // no guest signal — retry the host read + } + if (eintr_count >= 3) { + printk("NETDIAG sock_read-eintr(pid=%d comm=%s fd=%d) count=%d err=%d\n", + current->pid, current->comm, fd->real_fd, eintr_count, err); + } + sock_translate_err(fd, &err); + return err; +} + +static ssize_t sock_write(struct fd *fd, const void *buf, size_t size) { + int err; + int eintr_count = 0; + for (;;) { + ssize_t res = write(fd->real_fd, buf, size); + if (res >= 0) { err = (int)res; break; } + if (errno != EINTR) { err = errno_map(); break; } + eintr_count++; + if (current->sighand != NULL) { + lock(¤t->sighand->lock); + bool pending = !!(current->pending & ~current->blocked); + unlock(¤t->sighand->lock); + if (pending) { err = _EINTR; break; } + } + } + if (eintr_count >= 3) { + printk("NETDIAG sock_write-eintr(pid=%d comm=%s fd=%d) count=%d err=%d\n", + current->pid, current->comm, fd->real_fd, eintr_count, err); + } + sock_translate_err(fd, &err); + return err; +} + +static int sock_close(struct fd *fd) { + sockrestart_end_listen(fd); + // FIXME next 3 lines should go in a function like release_unix_names + inode_release_if_exist(fd->socket.unix_name_inode); + if (fd->socket.unix_name_abstract != NULL) + unix_abstract_release(fd->socket.unix_name_abstract); + lock(&peer_lock); + struct fd *peer = fd->socket.unix_peer; + if (peer != NULL) + peer->socket.unix_peer = NULL; + unlock(&peer_lock); + if (fd->socket.domain == AF_LOCAL_) { + lock(&fd->lock); + struct scm *scm, *tmp; + list_for_each_entry_safe(&fd->socket.unix_scm, scm, tmp, queue) { + list_remove(&scm->queue); + scm_free(scm); + } + unlock(&fd->lock); + } + return realfs_close(fd); +} + +const struct fd_ops socket_fdops = { + .read = sock_read, + .write = sock_write, + .close = sock_close, + .poll = realfs_poll, + .getflags = realfs_getflags, + .setflags = realfs_setflags, + .ioctl_size = realfs_ioctl_size, + .ioctl = realfs_ioctl, +}; + +#if defined(__GNUC__) && __GNUC__ >= 8 +#pragma GCC diagnostic ignored "-Wcast-function-type" +#endif +#if defined(__clang__) +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif +static struct socket_call { + syscall_t func; + int args; +} socket_calls[] = { + {NULL}, + {(syscall_t) sys_socket, 3}, + {(syscall_t) sys_bind, 3}, + {(syscall_t) sys_connect, 3}, + {(syscall_t) sys_listen, 2}, + {(syscall_t) sys_accept, 3}, + {(syscall_t) sys_getsockname, 3}, + {(syscall_t) sys_getpeername, 3}, + {(syscall_t) sys_socketpair, 4}, + {(syscall_t) sys_send, 4}, // send + {(syscall_t) sys_recv, 4}, // recv + {(syscall_t) sys_sendto, 6}, + {(syscall_t) sys_recvfrom, 6}, + {(syscall_t) sys_shutdown, 2}, + {(syscall_t) sys_setsockopt, 5}, + {(syscall_t) sys_getsockopt, 5}, + {(syscall_t) sys_sendmsg, 3}, + {(syscall_t) sys_recvmsg, 3}, + {NULL}, // accept4 + {NULL}, // recvmmsg + {(syscall_t) sys_sendmmsg, 4}, +}; + +int_t sys_socketcall(dword_t call_num, addr_t args_addr) { + STRACE("%d ", call_num); + if (call_num < 1 || call_num >= sizeof(socket_calls)/sizeof(socket_calls[0])) + return _EINVAL; + struct socket_call call = socket_calls[call_num]; + if (call.func == NULL) { + FIXME("socketcall %d", call_num); + return _ENOSYS; + } + + dword_t args[6]; + if (user_read(args_addr, args, sizeof(dword_t) * call.args)) + return _EFAULT; + return call.func(args[0], args[1], args[2], args[3], args[4], args[5]); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sock.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sock.h new file mode 100644 index 0000000000..9139d7402b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sock.h @@ -0,0 +1,369 @@ +#ifndef SYS_SOCK_H +#define SYS_SOCK_H + +#include <sys/socket.h> +#include <netinet/in.h> +#include <netinet/tcp.h> +#include "kernel/errno.h" +#include "fs/fd.h" +#include "misc.h" +#include "debug.h" + +int_t sys_socketcall(dword_t call_num, addr_t args_addr); + +int_t sys_socket(dword_t domain, dword_t type, dword_t protocol); +int_t sys_bind(fd_t sock_fd, addr_t sockaddr_addr, uint_t sockaddr_len); +int_t sys_connect(fd_t sock_fd, addr_t sockaddr_addr, uint_t sockaddr_len); +int_t sys_listen(fd_t sock_fd, int_t backlog); +int_t sys_accept(fd_t sock_fd, addr_t sockaddr_addr, addr_t sockaddr_len_addr); +int_t sys_accept4(fd_t sock_fd, addr_t sockaddr_addr, addr_t sockaddr_len_addr, int_t flags); +int_t sys_getsockname(fd_t sock_fd, addr_t sockaddr_addr, addr_t sockaddr_len_addr); +int_t sys_getpeername(fd_t sock_fd, addr_t sockaddr_addr, addr_t sockaddr_len_addr); +int_t sys_socketpair(dword_t domain, dword_t type, dword_t protocol, addr_t sockets_addr); +int_t sys_sendto(fd_t sock_fd, addr_t buffer_addr, dword_t len, dword_t flags, addr_t sockaddr_addr, dword_t sockaddr_len); +int_t sys_recvfrom(fd_t sock_fd, addr_t buffer_addr, dword_t len, dword_t flags, addr_t sockaddr_addr, addr_t sockaddr_len_addr); +int_t sys_shutdown(fd_t sock_fd, dword_t how); +int_t sys_setsockopt(fd_t sock_fd, dword_t level, dword_t option, addr_t value_addr, dword_t value_len); +int_t sys_getsockopt(fd_t sock_fd, dword_t level, dword_t option, addr_t value_addr, addr_t len_addr); +int_t sys_sendmsg(fd_t sock_fd, addr_t msghdr_addr, int_t flags); +int_t sys_recvmsg(fd_t sock_fd, addr_t msghdr_addr, int_t flags); +int_t sys_sendmmsg(fd_t sock_fd, addr_t msgvec_addr, uint_t msgvec_len, int_t flags); +int_t sys_recvmmsg(fd_t sock_fd, addr_t msg_vec, uint_t vec_len, int_t flags, addr_t timeout_addr); + +#define SOCKADDR_DATA_MAX 108 + +struct sockaddr_ { + uint16_t family; + char data[14]; +}; +struct sockaddr_max_ { + uint16_t family; + char data[SOCKADDR_DATA_MAX]; +}; + +size_t sockaddr_size(void *p); +// result comes from malloc +struct sockaddr *sockaddr_to_real(void *p); + +struct msghdr_ { + addr_t msg_name; + uint_t msg_namelen; + addr_t msg_iov; + uint_t msg_iovlen; + addr_t msg_control; + uint_t msg_controllen; + int_t msg_flags; +}; + +#ifdef GUEST_ARM64 +// ARM64 Linux uses 64-bit pointers and size_t in msghdr +struct msghdr64_ { + uint64_t msg_name; // void * + uint32_t msg_namelen; // socklen_t + uint32_t _pad0; + uint64_t msg_iov; // struct iovec * + uint64_t msg_iovlen; // size_t + uint64_t msg_control; // void * + uint64_t msg_controllen; // size_t + int32_t msg_flags; + int32_t _pad1; +}; +#endif + +struct cmsghdr_ { + dword_t len; + int_t level; + int_t type; + uint8_t data[]; +}; +#ifdef GUEST_ARM64 +struct cmsghdr64_ { + uint64_t len; + int32_t level; + int32_t type; + uint8_t data[]; +}; +#endif +#define SCM_RIGHTS_ 1 +// copied and ported from musl +#define CMSG_LEN_(cmsg) (((cmsg)->len + sizeof(dword_t) - 1) & ~(dword_t)(sizeof(dword_t) - 1)) +#define CMSG_NEXT_(cmsg) ((uint8_t *)(cmsg) + CMSG_LEN_(cmsg)) +#define CMSG_NXTHDR_(cmsg, mhdr_end) ((cmsg)->len < sizeof (struct cmsghdr_) || \ + CMSG_LEN_(cmsg) + sizeof(struct cmsghdr_) >= (size_t) (mhdr_end - (uint8_t *)(cmsg)) \ + ? NULL : (struct cmsghdr_ *)CMSG_NEXT_(cmsg)) +#ifdef GUEST_ARM64 +#define CMSG_LEN64_(cmsg) (((cmsg)->len + sizeof(uint64_t) - 1) & ~(uint64_t)(sizeof(uint64_t) - 1)) +#define CMSG_NEXT64_(cmsg) ((uint8_t *)(cmsg) + CMSG_LEN64_(cmsg)) +#define CMSG_NXTHDR64_(cmsg, mhdr_end) ((cmsg)->len < sizeof (struct cmsghdr64_) || \ + CMSG_LEN64_(cmsg) + sizeof(struct cmsghdr64_) >= (size_t) (mhdr_end - (uint8_t *)(cmsg)) \ + ? NULL : (struct cmsghdr64_ *)CMSG_NEXT64_(cmsg)) +#endif + +struct scm { + struct list queue; + unsigned num_fds; + struct fd *fds[]; +}; + +#define PF_LOCAL_ 1 +#define PF_INET_ 2 +#define PF_INET6_ 10 +#define AF_LOCAL_ PF_LOCAL_ +#define AF_INET_ PF_INET_ +#define AF_INET6_ PF_INET6_ +static inline int sock_family_to_real(int fake) { + switch (fake) { + case PF_LOCAL_: return PF_LOCAL; + case PF_INET_: return PF_INET; + case PF_INET6_: return PF_INET6; + } + return -1; +} +static inline int sock_family_from_real(int fake) { + switch (fake) { + case PF_LOCAL: return PF_LOCAL_; + case PF_INET: return PF_INET_; + case PF_INET6: return PF_INET6_; + } + return -1; +} + +#define SOCK_STREAM_ 1 +#define SOCK_DGRAM_ 2 +#define SOCK_RAW_ 3 +#define SOCK_SEQPACKET_ 5 +#define SOCK_NONBLOCK_ 0x800 +#define SOCK_CLOEXEC_ 0x80000 + +static inline int sock_type_to_real(int type, int protocol) { + switch (type & 0xff) { + case SOCK_STREAM_: + if (protocol != 0 && protocol != IPPROTO_TCP) + return -1; + return SOCK_STREAM; + case SOCK_DGRAM_: + switch (protocol) { + default: + return -1; + case 0: + case IPPROTO_UDP: + case IPPROTO_ICMP: + case IPPROTO_ICMPV6: + break; + } + return SOCK_DGRAM; + case SOCK_RAW_: + switch (protocol) { + default: + return -1; + case IPPROTO_RAW: + case IPPROTO_UDP: + case IPPROTO_ICMP: + case IPPROTO_ICMPV6: + break; + } + return SOCK_DGRAM; + case SOCK_SEQPACKET_: + // macOS doesn't support SOCK_SEQPACKET; for AF_UNIX, + // SOCK_STREAM is functionally equivalent (reliable, ordered, + // bidirectional). Rust std uses SOCK_SEQPACKET for spawn pipes. + if (protocol != 0) + return -1; + return SOCK_STREAM; + } + return -1; +} + +#define MSG_OOB_ 0x1 +#define MSG_PEEK_ 0x2 +#define MSG_CTRUNC_ 0x8 +#define MSG_TRUNC_ 0x20 +#define MSG_DONTWAIT_ 0x40 +#define MSG_EOR_ 0x80 +#define MSG_WAITALL_ 0x100 +#define MSG_ERRQUEUE_ 0x2000 + +static inline int sock_flags_to_real(int fake) { + int real = 0; + if (fake & MSG_OOB_) real |= MSG_OOB; + if (fake & MSG_PEEK_) real |= MSG_PEEK; + if (fake & MSG_CTRUNC_) real |= MSG_CTRUNC; + if (fake & MSG_TRUNC_) real |= MSG_TRUNC; + if (fake & MSG_DONTWAIT_) real |= MSG_DONTWAIT; + if (fake & MSG_EOR_) real |= MSG_EOR; + if (fake & MSG_WAITALL_) real |= MSG_WAITALL; +#ifdef MSG_ERRQUEUE + if (fake & MSG_ERRQUEUE_) real |= MSG_ERRQUEUE; +#endif + if (fake & ~(MSG_OOB_|MSG_PEEK_|MSG_CTRUNC_|MSG_TRUNC_|MSG_DONTWAIT_|MSG_EOR_|MSG_WAITALL_|MSG_ERRQUEUE_)) + TRACE("unimplemented socket flags %d\n", fake); + return real; +} +static inline int sock_flags_from_real(int real) { + int fake = 0; + if (real & MSG_OOB) fake |= MSG_OOB_; + if (real & MSG_PEEK) fake |= MSG_PEEK_; + if (real & MSG_CTRUNC) fake |= MSG_CTRUNC_; + if (real & MSG_TRUNC) fake |= MSG_TRUNC_; + if (real & MSG_DONTWAIT) fake |= MSG_DONTWAIT_; + if (real & MSG_EOR) fake |= MSG_EOR_; + if (real & MSG_WAITALL) fake |= MSG_WAITALL_; +#ifdef MSG_ERRQUEUE + if (real & MSG_ERRQUEUE) fake |= MSG_ERRQUEUE_; +#endif + if (real & ~(MSG_OOB|MSG_PEEK|MSG_CTRUNC|MSG_TRUNC|MSG_DONTWAIT|MSG_EOR|MSG_WAITALL +#ifdef MSG_ERRQUEUE + |MSG_ERRQUEUE +#endif + )) + TRACE("unimplemented socket flags %d\n", real); + return fake; +} + +#define SOL_SOCKET_ 1 + +#define SO_REUSEADDR_ 2 +#define SO_TYPE_ 3 +#define SO_ERROR_ 4 +#define SO_BROADCAST_ 6 +#define SO_SNDBUF_ 7 +#define SO_RCVBUF_ 8 +#define SO_KEEPALIVE_ 9 +#define SO_LINGER_ 13 +#define SO_REUSEPORT_ 15 +#define SO_PEERCRED_ 17 +#define SO_TIMESTAMP_ 29 +#define SO_PROTOCOL_ 38 +#define SO_DOMAIN_ 39 +#define SO_RCVTIMEO_ 66 +#define SO_SNDTIMEO_ 67 +#define IP_TOS_ 1 +#define IP_TTL_ 2 +#define IP_HDRINCL_ 3 +#define IP_RETOPTS_ 7 +#define IP_MTU_DISCOVER_ 10 +#define IP_RECVERR_ 11 +#define IP_RECVTTL_ 12 +#define IP_RECVTOS_ 13 +#define TCP_NODELAY_ 1 +#define TCP_KEEPIDLE_ 4 +#define TCP_KEEPINTVL_ 5 +#define TCP_KEEPCNT_ 6 +#define TCP_DEFER_ACCEPT_ 9 +#define TCP_INFO_ 11 +#define TCP_CONGESTION_ 13 +#define IPV6_UNICAST_HOPS_ 16 +#define IPV6_RECVERR_ 25 +#define IPV6_V6ONLY_ 26 +#define IPV6_TCLASS_ 67 +#define ICMP6_FILTER_ 1 + +static inline int sock_opt_to_real(int fake, int level) { + switch (level) { + case SOL_SOCKET_: switch (fake) { + case SO_REUSEADDR_: return SO_REUSEADDR; + case SO_TYPE_: return SO_TYPE; + case SO_ERROR_: return SO_ERROR; + case SO_BROADCAST_: return SO_BROADCAST; + case SO_KEEPALIVE_: return SO_KEEPALIVE; + case SO_LINGER_: return SO_LINGER; + case SO_SNDBUF_: return SO_SNDBUF; + case SO_RCVBUF_: return SO_RCVBUF; + case SO_TIMESTAMP_: return SO_TIMESTAMP; + case SO_RCVTIMEO_: return SO_RCVTIMEO; + case SO_SNDTIMEO_: return SO_SNDTIMEO; + case SO_REUSEPORT_: return SO_REUSEPORT; + } break; + case IPPROTO_TCP: switch (fake) { + case TCP_NODELAY_: return TCP_NODELAY; +#if defined(__APPLE__) + case TCP_KEEPIDLE_: return TCP_KEEPALIVE; // macOS equivalent +#else + case TCP_KEEPIDLE_: return TCP_KEEPIDLE; +#endif + case TCP_KEEPINTVL_: return TCP_KEEPINTVL; + case TCP_KEEPCNT_: return TCP_KEEPCNT; + case TCP_DEFER_ACCEPT_: return 0; // unimplemented +#if defined(__linux__) + case TCP_INFO_: return TCP_INFO; + case TCP_CONGESTION_: return TCP_CONGESTION; +#endif + } break; + case IPPROTO_IP: switch (fake) { + case IP_TOS_: return IP_TOS; + case IP_TTL_: return IP_TTL; + case IP_HDRINCL_: return IP_HDRINCL; + case IP_RETOPTS_: return IP_RETOPTS; + case IP_RECVERR_: +#ifdef IP_RECVERR + return IP_RECVERR; +#else + return 0; +#endif + case IP_RECVTTL_: return IP_RECVTTL; + case IP_RECVTOS_: return IP_RECVTOS; + } break; + case IPPROTO_IPV6: switch (fake) { + case IPV6_UNICAST_HOPS_: return IPV6_UNICAST_HOPS; + case IPV6_RECVERR_: +#ifdef IPV6_RECVERR + return IPV6_RECVERR; +#else + return 0; +#endif + case IPV6_TCLASS_: return IPV6_TCLASS; + case IPV6_V6ONLY_: return IPV6_V6ONLY; + } break; + } + return -1; +} + +static inline int sock_level_to_real(int fake) { + if (fake == SOL_SOCKET_) + return SOL_SOCKET; + return fake; +} + +extern const char *sock_tmp_prefix; + +struct tcp_info_ { + uint8_t state; + uint8_t ca_state; + uint8_t retransmits; + uint8_t probes; + uint8_t backoff; + uint8_t options; + uint8_t snd_wscale:4, rcv_wscale:4; + + uint32_t rto; + uint32_t ato; + uint32_t snd_mss; + uint32_t rcv_mss; + + uint32_t unacked; + uint32_t sacked; + uint32_t lost; + uint32_t retrans; + uint32_t fackets; + + uint32_t last_data_sent; + uint32_t last_ack_sent; + uint32_t last_data_recv; + uint32_t last_ack_recv; + + uint32_t pmtu; + uint32_t rcv_ssthresh; + uint32_t rtt; + uint32_t rttvar; + uint32_t snd_ssthresh; + uint32_t snd_cwnd; + uint32_t advmss; + uint32_t reordering; + + uint32_t rcv_rtt; + uint32_t rcv_space; + + uint32_t total_retrans; +}; + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sockrestart.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sockrestart.c new file mode 100644 index 0000000000..dfc64279a0 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sockrestart.c @@ -0,0 +1,122 @@ +#include <string.h> +#include <signal.h> +#include <pthread.h> +#include "fs/sockrestart.h" +#include "fs/fd.h" +#include "fs/sock.h" +#include "kernel/task.h" +#include "util/list.h" +extern const struct fd_ops socket_fdops; + +static lock_t sockrestart_lock = LOCK_INITIALIZER; +static struct list listen_fds = LIST_INITIALIZER(listen_fds); + +void sockrestart_begin_listen(struct fd *sock) { + if (sock->ops != &socket_fdops) + return; + lock(&sockrestart_lock); + list_add(&listen_fds, &sock->sockrestart.listen); + unlock(&sockrestart_lock); +} + +void sockrestart_end_listen(struct fd *sock) { + if (sock->ops != &socket_fdops) + return; + lock(&sockrestart_lock); + list_remove_safe(&sock->sockrestart.listen); + unlock(&sockrestart_lock); +} + +static struct list listen_tasks = LIST_INITIALIZER(listen_tasks); + +void sockrestart_begin_listen_wait(struct fd *sock) { + if (sock->ops != &socket_fdops) + return; + lock(&sockrestart_lock); + if (current->sockrestart.count == 0) + list_add(&listen_tasks, ¤t->sockrestart.listen); + current->sockrestart.count++; + unlock(&sockrestart_lock); +} + +void sockrestart_end_listen_wait(struct fd *sock) { + if (sock->ops != &socket_fdops) + return; + lock(&sockrestart_lock); + current->sockrestart.count--; + if (current->sockrestart.count == 0) + list_remove(¤t->sockrestart.listen); + unlock(&sockrestart_lock); +} + +bool sockrestart_should_restart_listen_wait() { + lock(&sockrestart_lock); + bool punt = current->sockrestart.punt; + current->sockrestart.punt = false; + unlock(&sockrestart_lock); + return punt; +} + +struct saved_socket { + struct fd *sock; + int type; + int proto; + union { + char name[128]; + struct sockaddr name_addr; + }; + socklen_t name_len; + struct list saved; +}; + +static struct list saved_sockets = LIST_INITIALIZER(saved_sockets); + +// these should only be called from the main thread, but it's easiest to just lock for the whole time + +void sockrestart_on_suspend() { + lock(&sockrestart_lock); + assert(list_empty(&saved_sockets)); + struct fd *sock; + list_for_each_entry(&listen_fds, sock, sockrestart.listen) { + struct saved_socket *saved = malloc(sizeof(struct saved_socket)); + if (saved == NULL) + continue; // better than a crash + saved->sock = fd_retain(sock); + saved->proto = sock->socket.protocol; + unsigned size = sizeof(saved->type); + getsockopt(sock->real_fd, SOL_SOCKET, SO_TYPE, &saved->type, &size); + assert(size == sizeof(saved->type)); + saved->name_len = sizeof(saved->name); + getsockname(sock->real_fd, (struct sockaddr *) &saved->name, &saved->name_len); + list_add(&saved_sockets, &saved->saved); + } + unlock(&sockrestart_lock); +} + +void sockrestart_on_resume() { + lock(&sockrestart_lock); + struct saved_socket *saved, *tmp; + list_for_each_entry_safe(&saved_sockets, saved, tmp, saved) { + list_remove(&saved->saved); + int new_sock = socket(saved->name_addr.sa_family, saved->type, saved->proto); + if (new_sock < 0) { + printk("restarting socket(%d, %d, %d) failed: %s\n", + saved->name_addr.sa_family, saved->type, saved->proto, strerror(errno)); + goto thank_u_next; + } + if (bind(new_sock, (struct sockaddr *) &saved->name, saved->name_len) < 0) { + printk("rebinding socket failed: %s\n", strerror(errno)); + goto thank_u_next; + } + dup2(new_sock, saved->sock->real_fd); + +thank_u_next: + fd_close(saved->sock); + } + struct task *task; + list_for_each_entry(&listen_tasks, task, sockrestart.listen) { + task->sockrestart.punt = true; + pthread_kill(task->thread, SIGUSR1); + } + unlock(&sockrestart_lock); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sockrestart.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sockrestart.h new file mode 100644 index 0000000000..b369f3c76a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sockrestart.h @@ -0,0 +1,37 @@ +// Hack to work around the idiotic way iOS handles suspending apps that have +// listening sockets. +// Basically the actual socket part of the file just gets freed, and the socket +// ceases to be a socket. Any attempt to do socket things with it will just +// immediately fail, and anyone blocked on accept will never wake up. +// Solution: keep track of all the listening sockets, and the threads that are +// blocked on them. On suspend, make a record of the names and configuration of +// all the listening sockets. On resume, open new sockets, reconfigure them, +// use dup2 to replace the original sockets, and get any thread waiting on them +// to restart the wait. +// This file contains hooks into various other places to do all that. +// https://developer.apple.com/library/archive/technotes/tn2277/_index.html +#ifndef FS_SOCKRESTART_H +#define FS_SOCKRESTART_H +#include <stdbool.h> +#include "util/list.h" +struct fd; + +void sockrestart_begin_listen(struct fd *sock); +void sockrestart_end_listen(struct fd *sock); +void sockrestart_begin_listen_wait(struct fd *sock); +void sockrestart_end_listen_wait(struct fd *sock); +bool sockrestart_should_restart_listen_wait(void); +void sockrestart_on_suspend(void); +void sockrestart_on_resume(void); + +struct fd_sockrestart { + struct list listen; +}; + +struct task_sockrestart { + int count; + bool punt; + struct list listen; +}; + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sqlutil.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sqlutil.h new file mode 100644 index 0000000000..fcaa0eac19 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/sqlutil.h @@ -0,0 +1,39 @@ +#ifndef FS_SQLUTIL_H +#define FS_SQLUTIL_H +#include <sqlite3.h> + +// Some nice sqlite macros for anything outside of fs/fake.c + +#define Q(...) #__VA_ARGS__ + +#define HANDLE_ERR(db) \ + die("sqlite error while rebuilding: %s\n", sqlite3_errmsg(db)) + +#define CHECK_ERR() \ + if (err != SQLITE_OK && err != SQLITE_ROW && err != SQLITE_DONE) \ + HANDLE_ERR(db) +#define EXEC(sql) \ + err = sqlite3_exec(db, sql, NULL, NULL, NULL); \ + CHECK_ERR(); +#define PREPARE(sql) ({ \ + sqlite3_stmt *stmt; \ + err = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL); \ + CHECK_ERR(); \ + stmt; \ +}) +#define STEP(stmt) ({ \ + err = sqlite3_step(stmt); \ + CHECK_ERR(); \ + err == SQLITE_ROW; \ +}) +#define RESET(stmt) \ + err = sqlite3_reset(stmt); \ + CHECK_ERR() +#define STEP_RESET(stmt) \ + STEP(stmt); \ + RESET(stmt) +#define FINALIZE(stmt) \ + err = sqlite3_finalize(stmt); \ + CHECK_ERR() + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/stat.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/stat.c new file mode 100644 index 0000000000..cf4919348a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/stat.c @@ -0,0 +1,150 @@ +#include <string.h> +#include <sys/stat.h> +#include <limits.h> + +#include "kernel/calls.h" +#include "kernel/errno.h" +#include "kernel/fs.h" +#include "fs/fd.h" +#include "fs/path.h" + +// ARM64 stat conversion (128 bytes struct) +struct stat_arm64 stat_convert_arm64(struct statbuf stat) { + struct stat_arm64 arm64stat = {}; + arm64stat.dev = stat.dev; + arm64stat.ino = stat.inode; + arm64stat.mode = stat.mode; + arm64stat.nlink = stat.nlink; + arm64stat.uid = stat.uid; + arm64stat.gid = stat.gid; + arm64stat.rdev = stat.rdev; + arm64stat.__pad1 = 0; + arm64stat.size = stat.size; + arm64stat.blksize = stat.blksize; + arm64stat.__pad2 = 0; + arm64stat.blocks = stat.blocks; + arm64stat.atime_ = stat.atime; + arm64stat.atime_nsec = stat.atime_nsec; + arm64stat.mtime_ = stat.mtime; + arm64stat.mtime_nsec = stat.mtime_nsec; + arm64stat.ctime_ = stat.ctime; + arm64stat.ctime_nsec = stat.ctime_nsec; + arm64stat.__unused4 = 0; + arm64stat.__unused5 = 0; + return arm64stat; +} + +int generic_statat(struct fd *at, const char *path_raw, struct statbuf *stat, bool follow_links) { + char path[MAX_PATH]; + int err = path_normalize(at, path_raw, path, follow_links ? N_SYMLINK_FOLLOW : N_SYMLINK_NOFOLLOW); + if (err < 0) + return err; + struct mount *mount = find_mount_and_trim_path(path); + memset(stat, 0, sizeof(*stat)); + err = mount->fs->stat(mount, path, stat); + mount_release(mount); + return err; +} + +// TODO get rid of this and maybe everything else in the file +static struct fd *at_fd(fd_t f) { + if (f == AT_FDCWD_) + return AT_PWD; + return f_get(f); +} + +static dword_t sys_stat_path(fd_t at_f, addr_t path_addr, addr_t statbuf_addr, bool follow_links) { + int err; + char path[MAX_PATH]; + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + STRACE("stat(at=%d, path=\"%s\", statbuf=0x%x, follow_links=%d)", at_f, path, statbuf_addr, follow_links); + struct fd *at = at_fd(at_f); + if (at == NULL) + return _EBADF; + struct statbuf stat = {}; + if ((err = generic_statat(at, path, &stat, follow_links)) < 0) + return err; + struct stat_arm64 arm64stat = stat_convert_arm64(stat); + if (user_put(statbuf_addr, arm64stat)) + return _EFAULT; + return 0; +} + +dword_t sys_stat64(addr_t path_addr, addr_t statbuf_addr) { + return sys_stat_path(AT_FDCWD_, path_addr, statbuf_addr, true); +} + +dword_t sys_lstat64(addr_t path_addr, addr_t statbuf_addr) { + return sys_stat_path(AT_FDCWD_, path_addr, statbuf_addr, false); +} + +dword_t sys_fstatat64(fd_t at, addr_t path_addr, addr_t statbuf_addr, dword_t flags) { + return sys_stat_path(at, path_addr, statbuf_addr, !(flags & AT_SYMLINK_NOFOLLOW_)); +} + +dword_t sys_fstat64(fd_t fd_no, addr_t statbuf_addr) { + STRACE("fstat64(%d, 0x%x)", fd_no, statbuf_addr); + struct fd *fd = f_get(fd_no); + if (fd == NULL) + return _EBADF; + struct statbuf stat = {}; + int err = fd->mount->fs->fstat(fd, &stat); + if (err < 0) + return err; + struct stat_arm64 arm64stat = stat_convert_arm64(stat); + if (user_put(statbuf_addr, arm64stat)) + return _EFAULT; + return 0; +} + +dword_t sys_statx(fd_t at_f, addr_t path_addr, int_t flags, uint_t mask, addr_t statx_addr) { + char path[MAX_PATH]; + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + struct fd *at = at_fd(at_f); + if (at == NULL) + return _EBADF; + + STRACE("statx(at=%d, path=\"%s\", flags=%d, mask=%d, statx=0x%x)", at_f, path, flags, mask, statx_addr); + + struct statbuf stat = {}; + + if ((flags & AT_EMPTY_PATH_) && strcmp(path, "") == 0) { + struct fd *fd = at; + int err = fd->mount->fs->fstat(fd, &stat); + if (err < 0) + return err; + } else { + bool follow_links = !(flags & AT_SYMLINK_NOFOLLOW_); + int err = generic_statat(at, path, &stat, follow_links); + if (err < 0) + return err; + } + + // for now, ignore the requested mask and just fill in the same fields as stat returns + struct statx_ statx = {}; + statx.mask = STATX_BASIC_STATS_; + statx.blksize = stat.blksize; + statx.nlink = stat.nlink; + statx.uid = stat.uid; + statx.gid = stat.gid; + statx.mode = stat.mode; + statx.ino = stat.inode; + statx.size = stat.size; + statx.blocks = stat.blocks; + statx.atime.sec = stat.atime; + statx.atime.nsec = stat.atime_nsec; + statx.mtime.sec = stat.mtime; + statx.mtime.nsec = stat.mtime_nsec; + statx.ctime.sec = stat.ctime; + statx.ctime.nsec = stat.ctime_nsec; + statx.rdev_major = dev_major(stat.rdev); + statx.rdev_minor = dev_minor(stat.rdev); + statx.dev_major = dev_major(stat.dev); + statx.dev_minor = dev_minor(stat.dev); + + if (user_put(statx_addr, statx)) + return _EFAULT; + return 0; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/stat.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/stat.h new file mode 100644 index 0000000000..b326cc4faf --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/stat.h @@ -0,0 +1,150 @@ +#ifndef FS_STAT_H +#define FS_STAT_H + +#include "misc.h" + +struct statbuf { + qword_t dev; + qword_t inode; + dword_t mode; + dword_t nlink; + dword_t uid; + dword_t gid; + qword_t rdev; + qword_t size; + dword_t blksize; + qword_t blocks; + dword_t atime; + dword_t atime_nsec; + dword_t mtime; + dword_t mtime_nsec; + dword_t ctime; + dword_t ctime_nsec; +}; + +// ARM64 stat struct (128 bytes) +// Based on Linux kernel include/uapi/asm-generic/stat.h +// Used by fstatat (syscall 79) on ARM64 +// Note: Using atime_/mtime_/ctime_ to avoid macOS macro conflicts +struct stat_arm64 { + qword_t dev; // Device (offset 0) + qword_t ino; // File serial number (offset 8) + dword_t mode; // File mode (offset 16) + dword_t nlink; // Link count (offset 20) + dword_t uid; // User ID of file's owner (offset 24) + dword_t gid; // Group ID of file's group (offset 28) + qword_t rdev; // Device number, if device (offset 32) + qword_t __pad1; // padding (offset 40) + sqword_t size; // Size of file, in bytes (offset 48) + sdword_t blksize; // Optimal block size for I/O (offset 56) + sdword_t __pad2; // padding (offset 60) + sqword_t blocks; // Number 512-byte blocks allocated (offset 64) + sqword_t atime_; // Time of last access (offset 72) + qword_t atime_nsec; // (offset 80) + sqword_t mtime_; // Time of last modification (offset 88) + qword_t mtime_nsec; // (offset 96) + sqword_t ctime_; // Time of last status change (offset 104) + qword_t ctime_nsec; // (offset 112) + dword_t __unused4; // (offset 120) + dword_t __unused5; // (offset 124) +}; // Total: 128 bytes + +struct statfsbuf { + long type; + long bsize; + uint64_t blocks; + uint64_t bfree; + uint64_t bavail; + uint64_t files; + uint64_t ffree; + uint64_t fsid; + long namelen; + long frsize; + long flags; + long spare[4]; +}; + +struct statfs_ { + uint_t type; + uint_t bsize; + uint_t blocks; + uint_t bfree; + uint_t bavail; + uint_t files; + uint_t ffree; + uint64_t fsid; + uint_t namelen; + uint_t frsize; + uint_t flags; + uint_t spare[4]; +} __attribute__((packed)); + +struct statfs64_ { + uint_t type; + uint_t bsize; + uint64_t blocks; + uint64_t bfree; + uint64_t bavail; + uint64_t files; + uint64_t ffree; + uint64_t fsid; + uint_t namelen; + uint_t frsize; + uint_t flags; + uint_t pad[4]; +} __attribute__((packed)); + +// ARM64 statfs structure - uses 64-bit fields throughout +// This matches the kernel's statfs structure for LP64 architectures +// Note: fsid_t is still { int val[2]; } = 8 bytes, not 16 +struct statfs_arm64_ { + uint64_t type; // f_type + uint64_t bsize; // f_bsize + uint64_t blocks; // f_blocks + uint64_t bfree; // f_bfree + uint64_t bavail; // f_bavail + uint64_t files; // f_files + uint64_t ffree; // f_ffree + int32_t fsid[2]; // f_fsid - __kernel_fsid_t is struct { int val[2]; } = 8 bytes + uint64_t namelen; // f_namelen + uint64_t frsize; // f_frsize + uint64_t flags; // f_flags + uint64_t spare[4]; // f_spare +}; + +struct statx_timestamp_ { + int64_t sec; + uint32_t nsec; + uint32_t _pad; +}; + +struct statx_ { + uint32_t mask; + uint32_t blksize; + uint64_t attributes; + uint32_t nlink; + uint32_t uid; + uint32_t gid; + uint16_t mode; + uint16_t _pad1; + uint64_t ino; + uint64_t size; + uint64_t blocks; + uint64_t attributes_mask; + struct statx_timestamp_ atime; + struct statx_timestamp_ btime; + struct statx_timestamp_ ctime; + struct statx_timestamp_ mtime; + uint32_t rdev_major; + uint32_t rdev_minor; + uint32_t dev_major; + uint32_t dev_minor; + uint64_t mnt_id; + uint32_t dio_mem_align; + uint32_t dio_offset_align; + uint32_t _pad2[24]; +} __attribute__((packed)); + +#define STATX_BASIC_STATS_ 0x7ff + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/tmp.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/tmp.c new file mode 100644 index 0000000000..efeabac21b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/tmp.c @@ -0,0 +1,516 @@ +#include <sys/stat.h> +#include <string.h> +#include "kernel/task.h" +#include "kernel/errno.h" +#include "kernel/fs.h" +#include "fs/path.h" +#include "util/refcount.h" +#include "debug.h" + +// ======================== +// ======== INODES ======== +// ======================== + +struct tmp_inode { + struct refcount refcount; + lock_t lock; + + struct statbuf stat; + union { + void *file_data; + //char *symlink_data; + }; +}; + +static struct tmp_inode *tmp_inode_new(mode_t_ mode) { + struct tmp_inode *node = malloc(sizeof(struct tmp_inode)); + if (node == NULL) + return NULL; + refcount_init(node); + lock_init(&node->lock); + + node->stat = (struct statbuf) {}; + static _Atomic ino_t next_inode = 1; + node->stat.inode = next_inode++; + + node->stat.mode = mode; + node->stat.uid = current->euid; + node->stat.gid = current->egid; + if (S_ISREG(mode)) { + node->file_data = malloc(0); + if (node->file_data == NULL) { + free(node); + return NULL; + } + } + return node; +} + +DEFINE_REFCOUNT_STATIC(tmp_inode) + +static void tmp_inode_cleanup(struct tmp_inode *inode) { + if (S_ISREG(inode->stat.mode)) { + free(inode->file_data); + } + free(inode); +} + +// =================================== +// ======== DIRECTORY ENTRIES ======== +// =================================== + +struct tmp_dirent { + char name[MAX_NAME + 1]; + struct tmp_inode *inode; + unsigned long index; + + struct tmp_dirent *parent; + struct list children; + unsigned long next_index; + + struct refcount refcount; + lock_t lock; + struct list dir; +}; + +DEFINE_REFCOUNT_STATIC(tmp_dirent) + +static void tmp_dirent_cleanup(struct tmp_dirent *dirent) { + list_remove(&dirent->dir); // TODO locking thinking emoji + tmp_inode_release(dirent->inode); + free(dirent); +} + +static void tmp_dirent_init(struct tmp_dirent *dirent) { + refcount_init(dirent); + list_init(&dirent->children); + dirent->next_index = 0; + lock_init(&dirent->lock); +} + +// Frees the child inode on failure, so you don't need to! But be careful you don't free it yourself. +// In other words: Takes ownership of `child` +static int tmpfs_dir_link(struct tmp_dirent *dir, const char *name, struct tmp_inode *child, struct tmp_dirent **dirent_out) { + if (!S_ISDIR(dir->inode->stat.mode)) { + tmp_inode_release(child); + return _ENOTDIR; + } + struct tmp_dirent *new_dirent = malloc(sizeof(struct tmp_dirent)); + if (new_dirent == NULL) { + tmp_inode_release(child); + return _ENOMEM; + } + + tmp_dirent_init(new_dirent); + strcpy(new_dirent->name, name); + new_dirent->inode = tmp_inode_retain(child); + new_dirent->index = dir->next_index++; + new_dirent->parent = tmp_dirent_retain(dir); + list_add_tail(&dir->children, &new_dirent->dir); + + if (dirent_out) + *dirent_out = tmp_dirent_retain(new_dirent); + return 0; +} + +static void tmpfs_fd_seekdir(struct fd *fd, struct tmp_dirent *dirent) { + if (dirent != NULL) + tmp_dirent_retain(dirent); + if (fd->tmpfs.dir_pos != NULL) + tmp_dirent_release(fd->tmpfs.dir_pos); + fd->tmpfs.dir_pos = dirent; +} + +static struct tmp_dirent *tmpfs_dir_lookup(struct tmp_dirent *dir, const char *name) { + if (!S_ISDIR(dir->inode->stat.mode)) + return ERR_PTR(_ENOTDIR); + struct tmp_dirent *dirent = NULL; + struct tmp_dirent *d; + list_for_each_entry(&dir->children, d, dir) { + if (d->inode == NULL) + continue; + if (strcmp(d->name, name) == 0) { + dirent = d; + break; + } + } + if (dirent == NULL) + return ERR_PTR(_ENOENT); + return tmp_dirent_retain(dirent); +} + +// TODO: should this function even exist? can't tmpfs_dir_link check for existence? +static int tmpfs_dir_lookup_existence(struct tmp_dirent *dir, const char *name) { + struct tmp_dirent *dirent = tmpfs_dir_lookup(dir, name); + if (dirent == ERR_PTR(_ENOENT)) + return 0; + if (IS_ERR(dirent)) + return PTR_ERR(dirent); + tmp_dirent_release(dirent); + return _EEXIST; +} + +static struct tmp_dirent *__tmpfs_lookup(struct mount *mount, const char *path, bool parent, const char **filename_out) { + struct tmp_dirent *root = mount->data; + struct tmp_dirent *dirent = tmp_dirent_retain(root); // strong reference + + char component[MAX_NAME + 1] = {}; + int err = 0; + while (path_next_component(&path, component, &err)) { + if (parent && *path == '\0') + break; + + lock(&dirent->lock); + struct tmp_dirent *child = tmpfs_dir_lookup(dirent, component); + unlock(&dirent->lock); + + tmp_dirent_release(dirent); + if (IS_ERR(child)) + return child; + dirent = child; + } + + if (parent && filename_out) + *filename_out = path - strlen(component); + + if (err < 0) + return ERR_PTR(err); + return dirent; +} +static struct tmp_dirent *tmpfs_lookup(struct mount *mount, const char *path) { + return __tmpfs_lookup(mount, path, false, NULL); +} +static struct tmp_dirent *tmpfs_lookup_parent(struct mount *mount, const char *path, const char **filename_out) { + if (strcmp(path, "/") == 0) + return NULL; + return __tmpfs_lookup(mount, path, true, filename_out); +} + +static int tmpfs_file_resize(struct tmp_inode *file, size_t size) { + assert(S_ISREG(file->stat.mode)); + size_t old_size = file->stat.size; + void *new_data = realloc(file->file_data, size); + if (new_data == NULL) + return _ENOMEM; + file->file_data = new_data; + file->stat.size = size; + memset((char *) file->file_data + old_size, 0, file->stat.size - old_size); + return 0; +} + +// ======================== +// ======== FS OPS ======== +// ======================== + +extern const struct fd_ops tmpfs_fdops; + +static int tmpfs_mount(struct mount *mount) { + struct tmp_inode *root_inode = tmp_inode_new(S_IFDIR | 0777); + if (root_inode == NULL) + return _ENOMEM; + + struct tmp_dirent *root = malloc(sizeof(struct tmp_dirent)); + if (root == NULL) { + free(root_inode); + return _ENOMEM; + } + + tmp_dirent_init(root); + strcpy(root->name, ""); + root->inode = root_inode; + root->parent = NULL; + + mount->data = root; + return 0; +} + +#if 0 +// This is the only place where a tmpfs directory tree is recursively freed. +static void tmpfs_unmount_tree(struct tmp_inode *tree) { + assert(refcount_get(tree) == 1); // otherwise mount_remove should have returned EBUSY + if (S_ISDIR(tree->stat.mode)) { + struct tmp_dirent *dirent, *tmp; + list_for_each_entry_safe(&tree->dir.entries, dirent, tmp, dir) { + if (dirent->inode != NULL) + tmpfs_unmount_tree(dirent->inode); + tmp_dirent_release(dirent); + } + } + tmp_inode_release(tree); +} +#endif + +static int tmpfs_umount(struct mount *UNUSED(mount)) { + // TODO: free the tmpfs inode tree when unmounting. + // struct tmp_inode *root = mount->data; + // tmpfs_unmount_tree(root); + TODO("tmpfs umount"); + return 0; +} + +static struct fd *tmpfs_open(struct mount *mount, const char *path, int flags, int mode) { + struct tmp_dirent *dirent; + if (flags & O_CREAT_) { + // FIXME: will create a file when given a path that ends with a slash + const char *filename; + struct tmp_dirent *parent = tmpfs_lookup_parent(mount, path, &filename); + if (IS_ERR(parent)) + return ERR_PTR(PTR_ERR(parent)); + lock(&parent->lock); + int err = 0; + + dirent = tmpfs_dir_lookup(parent, filename); + if (flags & O_EXCL_ && !IS_ERR(dirent)) { + err = _EEXIST; + goto out_creat; + } + + if (dirent == ERR_PTR(_ENOENT)) { + struct tmp_inode *inode = tmp_inode_new(S_IFREG | mode); + if (inode == NULL) { + err = _ENOMEM; + goto out_creat; + } + err = tmpfs_dir_link(parent, filename, inode, &dirent); + tmp_inode_release(inode); + if (err < 0) { + goto out_creat; + } + } + +out_creat: + if (err < 0) { + tmp_dirent_release(dirent); + dirent = ERR_PTR(err); + } + unlock(&parent->lock); + tmp_dirent_release(parent); + } else { + dirent = tmpfs_lookup(mount, path); + } + if (IS_ERR(dirent)) + return ERR_PTR(PTR_ERR(dirent)); + + struct fd *fd = fd_create(&tmpfs_fdops); + if (fd == NULL) { + tmp_dirent_release(dirent); + return ERR_PTR(_ENOMEM); + } + fd->tmpfs.dirent = dirent; + + fd->tmpfs.dir_pos = NULL; + lock(&dirent->lock); + if (!list_empty(&dirent->children)) { + tmpfs_fd_seekdir(fd, list_first_entry(&dirent->children, struct tmp_dirent, dir)); + } + unlock(&dirent->lock); + return fd; +} + +static int tmpfs_stat(struct mount *mount, const char *path, struct statbuf *stat) { + struct tmp_dirent *dirent = tmpfs_lookup(mount, path); + if (IS_ERR(dirent)) + return PTR_ERR(dirent); + struct tmp_inode *inode = dirent->inode; + lock(&inode->lock); + *stat = dirent->inode->stat; + unlock(&inode->lock); + tmp_dirent_release(dirent); + return 0; +} + +static int tmpfs_close(struct fd *fd) { + // shouldn't need locking as this is the last reference to the fd + tmp_dirent_release(fd->tmpfs.dirent); + fd->tmpfs.dirent = NULL; + return 0; +} + +static int tmpfs_mkdir(struct mount *mount, const char *path, mode_t_ mode) { + const char *filename; + struct tmp_dirent *parent = tmpfs_lookup_parent(mount, path, &filename); + if (IS_ERR(parent)) + return PTR_ERR(parent); + lock(&parent->lock); + + int err = tmpfs_dir_lookup_existence(parent, filename); + if (err < 0) + goto out; + + struct tmp_inode *inode = tmp_inode_new(S_IFDIR | mode); + err = _ENOMEM; + if (inode == NULL) + goto out; + + err = tmpfs_dir_link(parent, filename, inode, NULL); +out: + unlock(&parent->lock); + tmp_dirent_release(parent); + return err; +} + +// ======================== +// ======== FD OPS ======== +// ======================== + +static struct tmp_inode *tmpfs_fd_inode(struct fd *fd) { + return fd->tmpfs.dirent->inode; +} + +static int tmpfs_getpath(struct fd *fd, char *buf) { + struct tmp_dirent *dirent = fd->tmpfs.dirent; + struct tmp_dirent *root_dirent = fd->mount->data; + char *p = buf + MAX_PATH - 1; + *p = '\0'; + while (dirent != root_dirent) { + size_t name_len = strlen(dirent->name); + p -= name_len + 1; + if (p < buf) + return _ENAMETOOLONG; + p[0] = '/'; + memcpy(&p[1], dirent->name, name_len); + } + memmove(buf, p, strlen(p) + 1); + return 0; +} + +static int tmpfs_fstat(struct fd *fd, struct statbuf *stat) { + struct tmp_inode *inode = tmpfs_fd_inode(fd); + lock(&inode->lock); + *stat = inode->stat; + unlock(&inode->lock); + return 0; +} + +static ssize_t tmpfs_read(struct fd *fd, void *buf, size_t bufsize) { + ssize_t res; + struct tmp_inode *inode = tmpfs_fd_inode(fd); + lock(&inode->lock); + res = _EISDIR; + if (S_ISDIR(inode->stat.mode)) + goto out; + assert(S_ISREG(inode->stat.mode)); + + if (bufsize > inode->stat.size - fd->offset) { + bufsize = inode->stat.size - fd->offset; + if (fd->offset >= inode->stat.size) + bufsize = 0; + } + memcpy(buf, inode->file_data + fd->offset, bufsize); + fd->offset += bufsize; + res = bufsize; + +out: + unlock(&inode->lock); + return res; +} + +static ssize_t tmpfs_write(struct fd *fd, const void *buf, size_t bufsize) { + ssize_t res; + struct tmp_inode *inode = tmpfs_fd_inode(fd); + lock(&inode->lock); + res = _EISDIR; + if (S_ISDIR(inode->stat.mode)) + goto out; + assert(S_ISREG(inode->stat.mode)); + + if (inode->stat.size < fd->offset + bufsize) { + res = tmpfs_file_resize(inode, fd->offset + bufsize); + if (res < 0) + goto out; + } + memcpy(inode->file_data + fd->offset, buf, bufsize); + fd->offset += bufsize; + res = bufsize; + +out: + unlock(&inode->lock); + return res; +} + +static off_t_ tmpfs_lseek(struct fd *fd, off_t_ off, int whence) { + qword_t size = 0; + if (whence == LSEEK_END) { + struct tmp_inode *inode = tmpfs_fd_inode(fd); + lock(&inode->lock); + size = inode->stat.size; + unlock(&inode->lock); + } + + int err = generic_seek(fd, off, whence, size); + if (err < 0) + return err; + + return fd->offset; +} + +static int tmpfs_readdir(struct fd *fd, struct dir_entry *entry) { + struct tmp_dirent *parent = fd->tmpfs.dirent; + int res = _ENOTDIR; + if (!S_ISDIR(parent->inode->stat.mode)) + goto out; + + lock(&fd->lock); + lock(&parent->lock); + struct tmp_dirent *dirent = fd->tmpfs.dir_pos; + if (dirent == NULL) { + res = 0; + goto out; + } + struct tmp_dirent *next_dirent = list_next_entry(dirent, dir); + if (&next_dirent->dir == &parent->children) // end of list + next_dirent = NULL; + tmpfs_fd_seekdir(fd, next_dirent); + + entry->inode = dirent->inode->stat.inode; + entry->type = dirent_type_from_mode(dirent->inode->stat.mode); + strcpy(entry->name, dirent->name); + res = 1; + +out: + unlock(&parent->lock); + unlock(&fd->lock); + return res; +} + +static unsigned long tmpfs_telldir(struct fd *fd) { + if (fd->tmpfs.dir_pos == NULL) + return (unsigned long) -1; + return fd->tmpfs.dir_pos->index; +} + +static void tmpfs_seekdir(struct fd *fd, unsigned long ptr) { + struct tmp_dirent *dir = fd->tmpfs.dirent; + lock(&dir->lock); + assert(S_ISDIR(dir->inode->stat.mode)); + struct tmp_dirent *child; + list_for_each_entry(&dir->children, child, dir) { + if (child->index >= ptr) + break; + } + if (&child->dir == &dir->children) + child = NULL; + tmpfs_fd_seekdir(fd, child); + unlock(&dir->lock); +} + +const struct fs_ops tmpfs = { + .name = "tmpfs", .magic = 0x01021994, + .mount = tmpfs_mount, + .umount = tmpfs_umount, + .open = tmpfs_open, + .close = tmpfs_close, + .stat = tmpfs_stat, + .fstat = tmpfs_fstat, + .getpath = tmpfs_getpath, + .mkdir = tmpfs_mkdir, +}; + +const struct fd_ops tmpfs_fdops = { + .read = tmpfs_read, + .write = tmpfs_write, + .lseek = tmpfs_lseek, + .readdir = tmpfs_readdir, + .telldir = tmpfs_telldir, + .seekdir = tmpfs_seekdir, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/tty-real.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/tty-real.c new file mode 100644 index 0000000000..b8bbb2070f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/tty-real.c @@ -0,0 +1,148 @@ +#include "debug.h" +#include <string.h> +#include <unistd.h> +#include <termios.h> +#include <sys/ioctl.h> +#include <pthread.h> +#include <signal.h> + +#include "kernel/calls.h" +#include "fs/tty.h" +#include "fs/devices.h" + +// Only /dev/tty1 will be connected, the rest will go to a black hole. +#define REAL_TTY_NUM 1 + +void real_tty_reset_term(void); + +static void *real_tty_read_thread(void *_tty) { + struct tty *tty = _tty; + char ch; + for (;;) { + int err = read(STDIN_FILENO, &ch, 1); + if (err != 1) { + printk("tty read returned %d\n", err); + if (err < 0) + printk("error: %s\n", strerror(errno)); + continue; + } + if (ch == '\x1c') { + // ^\ (so ^C still works for emulated SIGINT) + real_tty_reset_term(); + raise(SIGINT); + } + tty_input(tty, &ch, 1, 0); + } + return NULL; +} + +static struct termios_ termios_from_real(struct termios real) { + struct termios_ fake = {}; +#define FLAG(t, x) \ + if (real.c_##t##flag & x) \ + fake.t##flags |= x##_ + FLAG(o, OPOST); + FLAG(o, ONLCR); + FLAG(o, OCRNL); + FLAG(o, ONOCR); + FLAG(o, ONLRET); + FLAG(i, INLCR); + FLAG(i, IGNCR); + FLAG(i, ICRNL); + FLAG(l, ISIG); + FLAG(l, ICANON); + FLAG(l, ECHO); + FLAG(l, ECHOE); + FLAG(l, ECHOK); + FLAG(l, NOFLSH); + FLAG(l, ECHOCTL); +#undef FLAG + +#define CC(x) \ + fake.cc[V##x##_] = real.c_cc[V##x] + CC(INTR); + CC(QUIT); + CC(ERASE); + CC(KILL); + CC(EOF); + CC(TIME); + CC(MIN); + CC(START); + CC(STOP); + CC(SUSP); + CC(EOL); + CC(REPRINT); + CC(DISCARD); + CC(WERASE); + CC(LNEXT); + CC(EOL2); +#undef CC + return fake; +} + +static struct termios old_termios; +static bool real_tty_is_open; +static int real_tty_init(struct tty *tty) { + if (tty->num != REAL_TTY_NUM) + return 0; + + struct winsize winsz; + if (ioctl(STDIN_FILENO, TIOCGWINSZ, &winsz) < 0) { + if (errno == ENOTTY) + goto notty; + return errno_map(); + } + tty->winsize.col = winsz.ws_col; + tty->winsize.row = winsz.ws_row; + tty->winsize.xpixel = winsz.ws_xpixel; + tty->winsize.ypixel = winsz.ws_ypixel; + + struct termios termios; + if (tcgetattr(STDIN_FILENO, &termios) < 0) + return errno_map(); + tty->termios = termios_from_real(termios); + + old_termios = termios; + cfmakeraw(&termios); +#ifdef NO_CRLF + termios.c_oflag |= OPOST | ONLCR; +#endif + if (tcsetattr(STDIN_FILENO, TCSANOW, &termios) < 0) + ERRNO_DIE("failed to set terminal to raw mode"); +notty: + + if (pthread_create(&tty->thread, NULL, real_tty_read_thread, tty) < 0) + // ok if this actually happened it would be weird AF + return _EIO; + pthread_detach(tty->thread); + real_tty_is_open = true; + return 0; +} + +static int real_tty_write(struct tty *tty, const void *buf, size_t len, bool UNUSED(blocking)) { + if (tty->num != REAL_TTY_NUM) + return len; + return write(STDOUT_FILENO, buf, len); +} + +void real_tty_reset_term() { + if (!real_tty_is_open) return; + if (tcsetattr(STDIN_FILENO, TCSANOW, &old_termios) < 0 && errno != ENOTTY) { + printk("failed to reset terminal: %s\n", strerror(errno)); + abort(); + } +} + +static void real_tty_cleanup(struct tty *tty) { + if (tty->num != REAL_TTY_NUM) + return; + real_tty_reset_term(); + pthread_cancel(tty->thread); +} + +struct tty_driver_ops real_tty_ops = { + .init = real_tty_init, + .write = real_tty_write, + .cleanup = real_tty_cleanup, +}; +DEFINE_TTY_DRIVER(real_tty_driver, &real_tty_ops, TTY_CONSOLE_MAJOR, 64); diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/tty.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/tty.c new file mode 100644 index 0000000000..b289a7467b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/tty.c @@ -0,0 +1,833 @@ +#define DEFAULT_CHANNEL debug +#include "debug.h" +#include <string.h> +#include "kernel/calls.h" +#include "fs/poll.h" +#include "fs/tty.h" +#include "fs/devices.h" + +extern struct tty_driver pty_master; +extern struct tty_driver pty_slave; + +struct tty_driver *tty_drivers[256] = { + [TTY_CONSOLE_MAJOR] = NULL, // will be filled in by create_stdio + [TTY_PSEUDO_MASTER_MAJOR] = &pty_master, + [TTY_PSEUDO_SLAVE_MAJOR] = &pty_slave, +}; + +// lock this before locking a tty +lock_t ttys_lock = LOCK_INITIALIZER; + +struct tty *tty_alloc(struct tty_driver *driver, int type, int num) { + struct tty *tty = malloc(sizeof(struct tty)); + if (tty == NULL) + return NULL; + + tty->refcount = 0; + tty->driver = driver; + tty->type = type; + tty->num = num; + tty->hung_up = false; + tty->ever_opened = false; + tty->session = 0; + tty->fg_group = 0; + list_init(&tty->fds); + + tty->termios.iflags = ICRNL_ | IXON_; + tty->termios.oflags = OPOST_ | ONLCR_; + tty->termios.cflags = 0; + tty->termios.lflags = ISIG_ | ICANON_ | ECHO_ | ECHOE_ | ECHOK_ | ECHOCTL_ | ECHOKE_ | IEXTEN_; + // from include/asm-generic/termios.h + memcpy(tty->termios.cc, "\003\034\177\025\004\0\1\0\021\023\032\0\022\017\027\026\0\0\0", 19); + memset(&tty->winsize, 0, sizeof(tty->winsize)); + + lock_init(&tty->lock); + lock_init(&tty->fds_lock); + cond_init(&tty->produced); + cond_init(&tty->consumed); + memset(tty->buf_flag, false, sizeof(tty->buf_flag)); + tty->bufsize = 0; + tty->packet_flags = 0; + + return tty; +} + +struct tty *tty_get(struct tty_driver *driver, int type, int num) { + lock(&ttys_lock); + struct tty *tty = driver->ttys[num]; + // pty_reserve_next stores 1 to avoid races on the same tty + if (tty == NULL || tty == (void *) 1 /* ew */) { + tty = tty_alloc(driver, type, num); + if (tty == NULL) { + unlock(&ttys_lock); + return ERR_PTR(_ENOMEM); + } + + if (driver->ops->init) { + int err = driver->ops->init(tty); + if (err < 0) { + unlock(&ttys_lock); + return ERR_PTR(err); + } + } + driver->ttys[num] = tty; + } + lock(&tty->lock); + tty->refcount++; + tty->ever_opened = true; + unlock(&tty->lock); + unlock(&ttys_lock); + return tty; +} + +static struct tty *get_slave_side_tty(struct tty *tty) { + if (tty->type == TTY_PSEUDO_MASTER_MAJOR) { + return tty->pty.other; + } else { + return tty; + } +} + +static void tty_poll_wakeup(struct tty *tty, int events) { + unlock(&tty->lock); + struct fd *fd; + lock(&tty->fds_lock); + list_for_each_entry(&tty->fds, fd, tty_other_fds) { + poll_wakeup(fd, events); + } + unlock(&tty->fds_lock); + lock(&tty->lock); +} + +void tty_release(struct tty *tty) { + lock(&tty->lock); + if (--tty->refcount == 0) { + struct tty_driver *driver = tty->driver; + if (driver->ops->cleanup) + driver->ops->cleanup(tty); + driver->ttys[tty->num] = NULL; + unlock(&tty->lock); + cond_destroy(&tty->produced); + free(tty); + } else { + unlock(&tty->lock); + } +} + +// must call with tty lock +static void tty_set_controlling(struct tgroup *group, struct tty *tty) { + lock(&group->lock); + if (group->tty == NULL) { + tty->refcount++; + group->tty = tty; + tty->session = group->sid; + tty->fg_group = group->pgid; + } + unlock(&group->lock); +} + +// by default, /dev/console is /dev/tty1 +int console_major = TTY_CONSOLE_MAJOR; +int console_minor = 1; + +int tty_open(struct tty *tty, struct fd *fd) { + fd->tty = tty; + + lock(&tty->fds_lock); + list_add(&tty->fds, &fd->tty_other_fds); + unlock(&tty->fds_lock); + + if (!(fd->flags & O_NOCTTY_)) { + // Make this our controlling terminal if: + // - the terminal doesn't already have a session + // - we're a session leader + lock(&pids_lock); + lock(&tty->lock); + if (tty->session == 0 && current->group->sid == current->pid) + tty_set_controlling(current->group, tty); + unlock(&tty->lock); + unlock(&pids_lock); + } + + return 0; +} + +static int tty_device_open(int major, int minor, struct fd *fd) { + struct tty *tty; + if (major == TTY_ALTERNATE_MAJOR) { + if (minor == DEV_TTY_MINOR) { + lock(&ttys_lock); + lock(¤t->group->lock); + tty = current->group->tty; + unlock(¤t->group->lock); + if (tty != NULL) { + lock(&tty->lock); + tty->refcount++; + unlock(&tty->lock); + } + unlock(&ttys_lock); + if (tty == NULL) + return _ENXIO; + } else if (minor == DEV_CONSOLE_MINOR) { + return tty_device_open(console_major, console_minor, fd); + } else if (minor == DEV_PTMX_MINOR) { + return ptmx_open(fd); + } else { + return _ENXIO; + } + } else { + struct tty_driver *driver = tty_drivers[major]; + assert(driver != NULL); + tty = tty_get(driver, major, minor); + if (IS_ERR(tty)) + return PTR_ERR(tty); + } + + if (tty->driver->ops->open) { + int err = tty->driver->ops->open(tty); + if (err < 0) { + lock(&ttys_lock); + tty_release(tty); + unlock(&ttys_lock); + return err; + } + } + + return tty_open(tty, fd); +} + +static int tty_close(struct fd *fd) { + if (fd->tty != NULL) { + struct tty *tty = fd->tty; + lock(&tty->fds_lock); + list_remove_safe(&fd->tty_other_fds); + unlock(&tty->fds_lock); + lock(&ttys_lock); + if (tty->driver->ops->close) + tty->driver->ops->close(tty); + tty_release(tty); + unlock(&ttys_lock); + } + return 0; +} + +static void tty_input_wakeup(struct tty *tty) { + notify(&tty->produced); + tty_poll_wakeup(tty, POLL_READ); +} + +static int tty_push_char(struct tty *tty, char ch, bool flag, int blocking) { + while (tty->bufsize >= sizeof(tty->buf)) { + if (!blocking) + return _EAGAIN; + if (wait_for(&tty->consumed, &tty->lock, NULL)) + return _EINTR; + } + tty->buf[tty->bufsize] = ch; + tty->buf_flag[tty->bufsize++] = flag; + return 0; +} + +static void tty_echo(struct tty *tty, const char *data, size_t size) { + tty->driver->ops->write(tty, data, size, false); +} + +static bool tty_send_input_signal(struct tty *tty, char ch, sigset_t_ *queue) { + if (!(tty->termios.lflags & ISIG_)) + return false; + unsigned char *cc = tty->termios.cc; + int sig; + if (ch == '\0') + return false; // '\0' is used to disable cc entries + else if (ch == cc[VINTR_]) + sig = SIGINT_; + else if (ch == cc[VQUIT_]) + sig = SIGQUIT_; + else if (ch == cc[VSUSP_]) + sig = SIGTSTP_; + else + return false; + + if (tty->fg_group != 0) { + if (!(tty->termios.lflags & NOFLSH_)) + tty->bufsize = 0; + sigset_add(queue, sig); + } + return true; +} + +ssize_t tty_input(struct tty *tty, const char *input, size_t size, bool blocking) { + int err = 0; + size_t done_size = 0; + sigset_t_ queue = 0; // to prevent having to lock tty->lock and pids_lock at the same time + + lock(&tty->lock); + dword_t lflags = tty->termios.lflags; + dword_t iflags = tty->termios.iflags; + unsigned char *cc = tty->termios.cc; + +#define SHOULD_ECHOCTL(ch) \ + (lflags & ECHOCTL_ && \ + ((0 <= ch && ch < ' ') || ch == '\x7f') && \ + !(ch == '\t' || ch == '\n' || ch == cc[VSTART_] || ch == cc[VSTOP_])) + + if (lflags & ICANON_) { + for (size_t i = 0; i < size; i++) { + done_size++; + char ch = input[i]; + bool echo = lflags & ECHO_; + + if (iflags & INLCR_ && ch == '\n') + ch = '\r'; + else if (iflags & ICRNL_ && ch == '\r') + ch = '\n'; + if (iflags & IGNCR_ && ch == '\r') + continue; + + if (ch == '\0') { + // '\0' is used to disable cc entries + goto no_special; + } else if (ch == cc[VERASE_] || ch == cc[VKILL_]) { + // FIXME ECHOE and ECHOK are supposed to enable these + // ECHOKE enables erasing the line instead of echoing the kill char and outputting a newline + echo = lflags & ECHOK_; + int count = tty->bufsize; + if (ch == cc[VERASE_] && tty->bufsize > 0) { + echo = lflags & ECHOE_; + count = 1; + } + if (!(lflags & ECHO_)) + echo = false; + for (int i = 0; i < count; i++) { + // don't delete past a flag + if (tty->buf_flag[tty->bufsize - 1]) + break; + tty->bufsize--; + if (echo) { + tty_echo(tty, "\b \b", 3); + if (SHOULD_ECHOCTL(tty->buf[tty->bufsize])) + tty_echo(tty, "\b \b", 3); + } + } + echo = false; + } else if (ch == cc[VEOF_]) { + ch = '\0'; + goto canon_wake; + } else if (ch == '\n' || ch == cc[VEOL_]) { + // echo it now, before the read call goes through + if (echo) + tty_echo(tty, "\r\n", 2); +canon_wake: + err = tty_push_char(tty, ch, /*flag*/true, blocking); + if (err < 0) { + done_size--; + break; + } + echo = false; + tty_input_wakeup(tty); + } else { + if (!tty_send_input_signal(tty, ch, &queue)) { +no_special: + err = tty_push_char(tty, ch, /*flag*/false, blocking); + if (err < 0) { + done_size--; + break; + } + } + } + + if (echo) { + if (SHOULD_ECHOCTL(ch)) { + tty_echo(tty, "^", 1); + ch ^= '\100'; + } + tty_echo(tty, &ch, 1); + } + } + } else { + for (size_t i = 0; i < size; i++) { + done_size++; + if (tty_send_input_signal(tty, input[i], &queue)) + continue; + while (tty->bufsize >= sizeof(tty->buf)) { + err = _EAGAIN; + if (!blocking) + break; + err = wait_for(&tty->consumed, &tty->lock, NULL); + if (err < 0) + break; + } + if (err < 0) { + done_size--; + break; + } + assert(tty->bufsize < sizeof(tty->buf)); + tty->buf[tty->bufsize++] = input[i]; + } + if (tty->bufsize > 0) + tty_input_wakeup(tty); + } + + pid_t_ fg_group = tty->fg_group; + assert(tty->bufsize <= sizeof(tty->buf)); + unlock(&tty->lock); + + if (fg_group != 0) { + for (int sig = 1; sig < NUM_SIGS; sig++) { + if (sigset_has(queue, sig)) + send_group_signal(fg_group, sig, SIGINFO_NIL); + } + } + + if (done_size > 0) + return done_size; + return err; +} + +// expects bufsize <= tty->bufsize +static void tty_read_into_buf(struct tty *tty, void *buf, size_t bufsize) { + assert(bufsize <= tty->bufsize); + memcpy(buf, tty->buf, bufsize); + tty->bufsize -= bufsize; + memmove(tty->buf, tty->buf + bufsize, tty->bufsize); // magic! + memmove(tty->buf_flag, tty->buf_flag + bufsize, tty->bufsize); + notify(&tty->consumed); +} + +static size_t tty_canon_size(struct tty *tty) { + bool *flag_ptr = memchr(tty->buf_flag, true, tty->bufsize); + if (flag_ptr == NULL) + return -1; + return flag_ptr - tty->buf_flag + 1; +} + +static bool pty_is_half_closed_master(struct tty *tty) { + if (tty->driver != &pty_master) + return false; + + struct tty *slave = tty->pty.other; + // only time one tty lock is nested in another + lock(&slave->lock); + bool half_closed = slave->ever_opened && (slave->refcount == 1 || slave->hung_up); + unlock(&slave->lock); + return half_closed; +} + +static bool tty_is_current(struct tty *tty) { + lock(¤t->group->lock); + bool is_current = current->group->tty == tty; + unlock(¤t->group->lock); + return is_current; +} + +static int tty_signal_if_background(struct tty *tty, pid_t_ current_pgid, int sig) { + // you can apparently access a terminal that's not your controlling + // terminal all you want + if (!tty_is_current(tty)) + return 0; + // check if we're in the foreground + if (tty->fg_group == 0 || current_pgid == tty->fg_group) + return 0; + + if (!try_self_signal(sig)) + return _EIO; + else + return _EINTR; +} + +static ssize_t tty_read(struct fd *fd, void *buf, size_t bufsize) { + // important because otherwise we'll block + if (bufsize == 0) + return 0; + + int err = 0; + struct tty *tty = fd->tty; + lock(&pids_lock); + lock(&tty->lock); + if (tty->hung_up || pty_is_half_closed_master(tty)) { + unlock(&pids_lock); + goto error; + } + + pid_t_ current_pgid = current->group->pgid; + unlock(&pids_lock); + err = tty_signal_if_background(tty, current_pgid, SIGTTIN_); + if (err < 0) + goto error; + + int bufsize_extra = 0; + if (tty->driver == &pty_master && tty->pty.packet_mode) { + char *cbuf = buf; + *cbuf++ = tty->packet_flags; + bufsize--; + bufsize_extra++; + buf = cbuf; + if (tty->packet_flags != 0) { + bufsize = 0; + goto out; + } + + // check again in case bufsize was 1 + if (bufsize == 0) + goto out; + } + + // wait loop(s) + if (tty->termios.lflags & ICANON_) { + size_t canon_size; + while ((canon_size = tty_canon_size(tty)) == (size_t) -1) { + err = _EIO; + if (pty_is_half_closed_master(tty)) + goto error; + err = _EAGAIN; + if (fd->flags & O_NONBLOCK_) + goto error; + err = wait_for(&tty->produced, &tty->lock, NULL); + if (err < 0) + goto error; + } + // null byte means eof was typed + if (tty->buf[canon_size-1] == '\0') + canon_size--; + + if (bufsize > canon_size) + bufsize = canon_size; + } else { + dword_t min = tty->termios.cc[VMIN_]; + dword_t time = tty->termios.cc[VTIME_]; + + struct timespec timeout; + // time is in tenths of a second + timeout.tv_sec = time / 10; + timeout.tv_nsec = (time % 10) * 100000000; + struct timespec *timeout_ptr = &timeout; + if (time == 0) + timeout_ptr = NULL; + + while (tty->bufsize < min) { + err = _EIO; + if (pty_is_half_closed_master(tty)) + goto error; + err = _EAGAIN; + if (fd->flags & O_NONBLOCK_) + goto error; + // there should be no timeout for the first character read + err = wait_for(&tty->produced, &tty->lock, tty->bufsize == 0 ? NULL : timeout_ptr); + if (err == _ETIMEDOUT) + break; + if (err == _EINTR) + goto error; + } + } + + if (bufsize > tty->bufsize) + bufsize = tty->bufsize; + tty_read_into_buf(tty, buf, bufsize); + if (tty->bufsize > 0 && tty->buf[0] == '\0' && tty->buf_flag[0]) { + // remove the eof so the next read can succeed + char dummy; + tty_read_into_buf(tty, &dummy, 1); + } + +out: + unlock(&tty->lock); + return bufsize + bufsize_extra; +error: + unlock(&tty->lock); + return err; +} + +static ssize_t tty_write(struct fd *fd, const void *buf, size_t bufsize) { + struct tty *tty = fd->tty; + lock(&tty->lock); + if (tty->hung_up || pty_is_half_closed_master(tty)) { + unlock(&tty->lock); + return _EIO; + } + + bool blocking = !(fd->flags & O_NONBLOCK_); + dword_t oflags = tty->termios.oflags; + // we have to unlock it now to avoid lock ordering problems with ptys + // the code below is safe because it only accesses tty->driver which is immutable + // I reviewed real driver and ios driver and they're safe + unlock(&tty->lock); + + int err = 0; + char *postbuf = NULL; + size_t postbufsize = bufsize; + if (oflags & OPOST_) { + postbuf = malloc(bufsize * 2); + postbufsize = 0; + const char *cbuf = buf; + for (size_t i = 0; i < bufsize; i++) { + char ch = cbuf[i]; + if (ch == '\r' && oflags & ONLRET_) + continue; + else if (ch == '\r' && oflags & OCRNL_) + ch = '\n'; + else if (ch == '\n' && oflags & ONLCR_) + postbuf[postbufsize++] = '\r'; + postbuf[postbufsize++] = ch; + } + buf = postbuf; + } + err = tty->driver->ops->write(tty, buf, postbufsize, blocking); + if (postbuf) + free(postbuf); + if (err < 0) + return err; + return bufsize; +} + +static int tty_poll(struct fd *fd) { + struct tty *tty = fd->tty; + lock(&tty->lock); + int types = 0; + types |= POLL_WRITE; // FIXME now that we have ptys, you can't always write without blocking + if (tty->hung_up) { + types |= POLL_READ | POLL_WRITE | POLL_ERR | POLL_HUP; + } else if (pty_is_half_closed_master(tty)) { + types |= POLL_READ | POLL_HUP; + } else if (tty->termios.lflags & ICANON_) { + if (tty_canon_size(tty) != (size_t) -1) + types |= POLL_READ; + } else { + if (tty->bufsize > 0) + types |= POLL_READ; + } + if (tty->driver == &pty_master && tty->packet_flags != 0) + types |= POLL_PRI; + unlock(&tty->lock); + return types; +} + +static ssize_t tty_ioctl_size(int cmd) { + switch (cmd) { + case TCGETS_: case TCSETS_: case TCSETSF_: case TCSETSW_: + return sizeof(struct termios_); + case TIOCGWINSZ_: case TIOCSWINSZ_: + return sizeof(struct winsize_); + case TIOCGPGRP_: case TIOCSPGRP_: + case TIOCSPTLCK_: case TIOCGPTN_: + case TIOCPKT_: case TIOCGPKT_: + case FIONREAD_: + return sizeof(dword_t); + case TCFLSH_: case TIOCSCTTY_: + return 0; + } + return -1; +} + +static int tiocsctty(struct tty *tty, int force) { + int err = 0; + unlock(&tty->lock); //aaaaaaaa + // it's safe because literally nothing happens between that unlock and the last lock, and repulsive for the same reason + // locking is ***hard** + lock(&pids_lock); + lock(&tty->lock); + // do nothing if this is already our controlling tty + if (current->group->sid == current->pid && current->group->sid == tty->session) + goto out; + // must not already have a tty + if (current->group->tty != NULL) { + err = _EPERM; + goto out; + } + + if (tty->session) { + if (force == 1 && superuser()) { + // steal it + struct pid *pid = pid_get(tty->session); + struct tgroup *tgroup; + list_for_each_entry(&pid->session, tgroup, session) { + lock(&tgroup->lock); + if (tgroup->tty == tty) { + tgroup->tty = NULL; + tty->refcount--; + } + unlock(&tgroup->lock); + } + } else { + err = _EPERM; + goto out; + } + } + + tty_set_controlling(current->group, tty); +out: + unlock(&pids_lock); + return err; +} + +static int tiocgpgrp(struct tty *tty, pid_t_ *fg_group) { + int err = 0; + struct tty *slave = get_slave_side_tty(tty); + if (slave != tty) { + lock(&slave->lock); + } + + if (tty == slave && (!tty_is_current(slave) || slave->fg_group == 0)) { + err = _ENOTTY; + goto error_no_ctrl_tty; + } + *fg_group = slave->fg_group; + STRACE("tty group = %d\n", slave->fg_group); + +error_no_ctrl_tty: + if (slave != tty) + unlock(&slave->lock); + return err; +} + +// These ioctls are separated out because they have to operate on the slave +// side of a pseudoterminal pair even if the master is specified +static int tty_mode_ioctl(struct tty *in_tty, int cmd, void *arg) { + int err = 0; + struct tty *tty = in_tty; + if (in_tty->driver == &pty_master) { + tty = in_tty->pty.other; + lock(&tty->lock); + } + + switch (cmd) { + case TCGETS_: + *(struct termios_ *) arg = tty->termios; + break; + case TCSETSF_: + tty->bufsize = 0; + notify(&tty->consumed); + fallthrough; + case TCSETSW_: + // we have no output buffer currently + case TCSETS_: + tty->termios = *(struct termios_ *) arg; + break; + + case TIOCGWINSZ_: + *(struct winsize_ *) arg = tty->winsize; + break; + case TIOCSWINSZ_: + tty_set_winsize(tty, *(struct winsize_ *) arg); + break; + + default: + err = _ENOTTY; + break; + } + + if (in_tty->driver == &pty_master) + unlock(&tty->lock); + return err; +} + +static int tty_ioctl(struct fd *fd, int cmd, void *arg) { + int err = 0; + struct tty *tty = fd->tty; + lock(&tty->lock); + if (tty->hung_up) { + unlock(&tty->lock); + if (cmd == TIOCSPGRP_) + return _ENOTTY; + return _EIO; + } + + switch (cmd) { + case TCFLSH_: + // only input flushing is currently useful + switch ((uintptr_t) arg) { + case TCIFLUSH_: + case TCIOFLUSH_: + tty->bufsize = 0; + notify(&tty->consumed); + break; + case TCOFLUSH_: + break; + default: + err = _EINVAL; + break; + }; + break; + + case TIOCSCTTY_: + err = tiocsctty(tty, (uintptr_t) arg); + break; + + case TIOCGPGRP_: + err = tiocgpgrp(tty, (pid_t_ *) arg); + break; + + case TIOCSPGRP_: + // see "aaaaaaaa" comment above + unlock(&tty->lock); + lock(&pids_lock); + lock(&tty->lock); + pid_t_ sid = current->group->sid; + unlock(&pids_lock); + if (!tty_is_current(tty) || sid != tty->session) { + err = _ENOTTY; + break; + } + // TODO group must be in the right session + tty->fg_group = *(dword_t *) arg; + STRACE("tty group set to = %d\n", tty->fg_group); + break; + + case FIONREAD_: + *(dword_t *) arg = tty->bufsize; + break; + + default: + err = tty_mode_ioctl(tty, cmd, arg); + if (err == _ENOTTY && tty->driver->ops->ioctl) + err = tty->driver->ops->ioctl(tty, cmd, arg); + } + + unlock(&tty->lock); + return err; +} + +void tty_set_winsize(struct tty *tty, struct winsize_ winsize) { + tty->winsize = winsize; + if (tty->fg_group != 0) + send_group_signal(tty->fg_group, SIGWINCH_, SIGINFO_NIL); +} + +void tty_hangup(struct tty *tty) { + tty->hung_up = true; + // Wake up any threads blocked in tty_read via condvar. + notify(&tty->produced); + // Wake up poll waiters by writing to their notify pipes directly, + // avoiding poll_wakeup which acquires fd->poll_lock and can deadlock + // when called from [Terminal destroy] on the main thread during exit. + unlock(&tty->lock); + struct fd *fd; + lock(&tty->fds_lock); + list_for_each_entry(&tty->fds, fd, tty_other_fds) { + // Use trylock to avoid blocking — if we can't get poll_lock, + // the poll loop's 1-second timeout will pick up hung_up anyway. + if (pthread_mutex_trylock(&fd->poll_lock.m) == 0) { + struct poll_fd *poll_fd; + list_for_each_entry(&fd->poll_fds, poll_fd, polls) { + struct poll *poll = poll_fd->poll; + if (pthread_mutex_trylock(&poll->lock.m) == 0) { + if (poll->notify_pipe[1] != -1) + write(poll->notify_pipe[1], "", 1); + unlock(&poll->lock); + } + } + unlock(&fd->poll_lock); + } + } + unlock(&tty->fds_lock); + lock(&tty->lock); +} + +struct dev_ops tty_dev = { + .open = tty_device_open, + .fd.close = tty_close, + .fd.read = tty_read, + .fd.write = tty_write, + .fd.poll = tty_poll, + .fd.ioctl_size = tty_ioctl_size, + .fd.ioctl = tty_ioctl, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/tty.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/tty.h new file mode 100644 index 0000000000..ff70dc4235 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/fs/tty.h @@ -0,0 +1,170 @@ +#ifndef TTY_H +#define TTY_H + +#include "kernel/fs.h" +#include "fs/dev.h" + +struct winsize_ { + word_t row; + word_t col; + word_t xpixel; + word_t ypixel; +}; + +// This is the definition of __kernel_termios from glibc +struct termios_ { + dword_t iflags; + dword_t oflags; + dword_t cflags; + dword_t lflags; + byte_t line; + byte_t cc[19]; +}; + +#define VINTR_ 0 +#define VQUIT_ 1 +#define VERASE_ 2 +#define VKILL_ 3 +#define VEOF_ 4 +#define VTIME_ 5 +#define VMIN_ 6 +#define VSWTC_ 7 +#define VSTART_ 8 +#define VSTOP_ 9 +#define VSUSP_ 10 +#define VEOL_ 11 +#define VREPRINT_ 12 +#define VDISCARD_ 13 +#define VWERASE_ 14 +#define VLNEXT_ 15 +#define VEOL2_ 16 + +#define ISIG_ (1 << 0) +#define ICANON_ (1 << 1) +#define ECHO_ (1 << 3) +#define ECHOE_ (1 << 4) +#define ECHOK_ (1 << 5) +#define ECHOKE_ (1 << 6) +#define NOFLSH_ (1 << 7) +#define ECHOCTL_ (1 << 9) +#define IEXTEN_ (1 << 15) + +#define INLCR_ (1 << 6) +#define IGNCR_ (1 << 7) +#define ICRNL_ (1 << 8) +#define IXON_ (1 << 10) + +#define OPOST_ (1 << 0) +#define ONLCR_ (1 << 2) +#define OCRNL_ (1 << 3) +#define ONOCR_ (1 << 4) +#define ONLRET_ (1 << 5) + +#define TCGETS_ 0x5401 +#define TCSETS_ 0x5402 +#define TCSETSW_ 0x5403 +#define TCSETSF_ 0x5404 +#define TCFLSH_ 0x540b +#define TIOCSCTTY_ 0x540e +#define TIOCGPGRP_ 0x540f +#define TIOCSPGRP_ 0x5410 +#define TIOCGWINSZ_ 0x5413 +#define TIOCSWINSZ_ 0x5414 +#define TIOCPKT_ 0x5420 +#define TIOCGPTN_ 0x80045430 +#define TIOCSPTLCK_ 0x40045431 +#define TIOCGPKT_ 0x80045438 + +#define TCIFLUSH_ 0 +#define TCOFLUSH_ 1 +#define TCIOFLUSH_ 2 + +struct tty_driver { + const struct tty_driver_ops *ops; + int major; + struct tty **ttys; + unsigned limit; +}; + +#define DEFINE_TTY_DRIVER(name, driver_ops, _major, size) \ + static struct tty *name##_ttys[size]; \ + struct tty_driver name = {.ops = driver_ops, .major = _major, .ttys = name##_ttys, .limit = size} + +struct tty_driver_ops { + int (*init)(struct tty *tty); + int (*open)(struct tty *tty); + int (*close)(struct tty *tty); + int (*write)(struct tty *tty, const void *buf, size_t len, bool blocking); + int (*ioctl)(struct tty *tty, int cmd, void *arg); + void (*cleanup)(struct tty *tty); +}; + +// indexed by major number +extern struct tty_driver *tty_drivers[256]; +extern struct tty_driver real_tty_driver; + +struct tty { + unsigned refcount; + struct tty_driver *driver; + bool hung_up; + bool ever_opened; + +#define TTY_BUF_SIZE 4096 + char buf[TTY_BUF_SIZE]; + // A flag is a marker indicating the end of a canonical mode input. Flags + // are created by EOL and EOF characters. You can't backspace past a flag. + bool buf_flag[TTY_BUF_SIZE]; + size_t bufsize; + uint8_t packet_flags; + cond_t produced; + cond_t consumed; + + struct winsize_ winsize; + struct termios_ termios; + int type; + int num; + + pid_t_ session; + pid_t_ fg_group; + + struct list fds; + // only locks fds, to keep the lock order + lock_t fds_lock; + + // this never nests with itself, except in pty_is_half_closed_master + lock_t lock; + + union { + pthread_t thread; // for real tty driver + struct { + struct tty *other; + mode_t_ perms; + uid_t_ uid; + uid_t_ gid; + bool locked; + bool packet_mode; + } pty; + void *data; + }; +}; + +// if blocking, may return _EINTR, otherwise, may return _EAGAIN +ssize_t tty_input(struct tty *tty, const char *input, size_t len, bool blocking); +void tty_set_winsize(struct tty *tty, struct winsize_ winsize); +void tty_hangup(struct tty *tty); + +// public for the benefit of ptys +struct tty *tty_get(struct tty_driver *driver, int type, int num); +struct tty *tty_alloc(struct tty_driver *driver, int type, int num); +int tty_open(struct tty *tty, struct fd *fd); +extern lock_t ttys_lock; +void tty_release(struct tty *tty); // must be called with ttys_lock + +extern struct dev_ops tty_dev; +extern struct dev_ops ptmx_dev; + +int ptmx_open(struct fd *fd); +// Should call with a driver declared *without* DEFINE_TTY_DRIVER, as it overwrites the ttys field. +struct tty *pty_open_fake(struct tty_driver *driver); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/ish-gdb.gdb b/platforms/ios/Alpine/Vendor/ios-linuxkit/ish-gdb.gdb new file mode 100644 index 0000000000..b007adad6e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/ish-gdb.gdb @@ -0,0 +1,26 @@ +handle SIGUSR1 noprint pass +handle SIGTTIN noprint pass +handle SIGPIPE noprint pass +set print thread-events off + +define hook-run + python +import subprocess +if subprocess.call('ninja') != 0: + raise gdb.CommandError('compilation failed') + end +end + +define hook-stop + python +try: + symtab = gdb.selected_frame().find_sal().symtab +except: + pass +else: + if symtab is not None and symtab.filename.endswith('.S'): + gdb.execute('set disassemble-next-line on') + else: + gdb.execute('set disassemble-next-line auto') + end +end diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/arch/arm64/calls.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/arch/arm64/calls.c new file mode 100644 index 0000000000..4077dda18a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/arch/arm64/calls.c @@ -0,0 +1,299 @@ +// ARM64 (AArch64) Linux syscall table +// Syscall numbers follow the Linux aarch64 ABI (asm-generic based) + +#include <stddef.h> +#include "kernel/calls.h" + +#if is_gcc(8) +#pragma GCC diagnostic ignored "-Wcast-function-type" +#endif + +/* + * ARM64 Linux syscall numbers are based on asm-generic and are mostly sequential. + * The ABI uses individual socket and IPC syscalls, 64-bit stat structures, and + * ARM64-specific argument ordering where Linux defines it. + */ + +syscall_t syscall_table[] = { + // I/O syscalls + [0] = (syscall_t) syscall_stub, // io_setup + [1] = (syscall_t) syscall_stub, // io_destroy + [2] = (syscall_t) syscall_stub, // io_submit + [3] = (syscall_t) syscall_stub, // io_cancel + [4] = (syscall_t) syscall_stub, // io_getevents + [5 ... 16] = (syscall_t) sys_xattr_stub, // xattr syscalls + [17] = (syscall_t) sys_getcwd, + [18] = (syscall_t) syscall_stub, // lookup_dcookie + [19] = (syscall_t) sys_eventfd2, + [20] = (syscall_t) sys_epoll_create, + [21] = (syscall_t) sys_epoll_ctl, + [22] = (syscall_t) sys_epoll_pwait, + [23] = (syscall_t) sys_dup, + [24] = (syscall_t) sys_dup3, + [25] = (syscall_t) sys_fcntl, + [26] = (syscall_t) sys_inotify_init1, + [27] = (syscall_t) sys_inotify_add_watch, + [28] = (syscall_t) sys_inotify_rm_watch, + [29] = (syscall_t) sys_ioctl, + [30] = (syscall_t) sys_ioprio_set, + [31] = (syscall_t) sys_ioprio_get, + [32] = (syscall_t) sys_flock, + [33] = (syscall_t) sys_mknodat, + [34] = (syscall_t) sys_mkdirat, + [35] = (syscall_t) sys_unlinkat, + [36] = (syscall_t) sys_symlinkat, + [37] = (syscall_t) sys_linkat, + [38] = (syscall_t) sys_renameat, + [39] = (syscall_t) sys_umount2, + [40] = (syscall_t) sys_mount, + [41] = (syscall_t) syscall_stub, // pivot_root + [42] = (syscall_t) syscall_stub, // nfsservctl + [43] = (syscall_t) sys_statfs_arm64, + [44] = (syscall_t) sys_fstatfs_arm64, + [45] = (syscall_t) sys_truncate64, + [46] = (syscall_t) sys_ftruncate64, + [47] = (syscall_t) sys_fallocate, + [48] = (syscall_t) sys_faccessat, + [49] = (syscall_t) sys_chdir, + [50] = (syscall_t) sys_fchdir, + [51] = (syscall_t) sys_chroot, + [52] = (syscall_t) sys_fchmod, + [53] = (syscall_t) sys_fchmodat, + [54] = (syscall_t) sys_fchownat, + [55] = (syscall_t) sys_fchown32, + [56] = (syscall_t) sys_openat, + [57] = (syscall_t) sys_close, + [58] = (syscall_t) syscall_stub, // vhangup + [59] = (syscall_t) sys_pipe2, + [60] = (syscall_t) syscall_stub, // quotactl + [61] = (syscall_t) sys_getdents64, + [62] = (syscall_t) sys_lseek64, + [63] = (syscall_t) sys_read, + [64] = (syscall_t) sys_write, + [65] = (syscall_t) sys_readv, + [66] = (syscall_t) sys_writev, + [67] = (syscall_t) sys_pread, + [68] = (syscall_t) sys_pwrite, + [69] = (syscall_t) sys_preadv, + [70] = (syscall_t) sys_pwritev, + [71] = (syscall_t) sys_sendfile64, + [72] = (syscall_t) sys_pselect, + [73] = (syscall_t) sys_ppoll, + [74] = (syscall_t) sys_signalfd4, + [75] = (syscall_t) syscall_stub, // vmsplice + [76] = (syscall_t) sys_splice, + [77] = (syscall_t) syscall_stub, // tee + [78] = (syscall_t) sys_readlinkat, + [79] = (syscall_t) sys_fstatat64, + [80] = (syscall_t) sys_fstat64, + [81] = (syscall_t) syscall_success_stub, // sync + [82] = (syscall_t) sys_fsync, + [83] = (syscall_t) sys_fsync, // fdatasync + [84] = (syscall_t) syscall_stub, // sync_file_range + [85] = (syscall_t) sys_timerfd_create, + [86] = (syscall_t) sys_timerfd_settime, + [87] = (syscall_t) sys_timerfd_gettime, + [88] = (syscall_t) sys_utimensat, + [89] = (syscall_t) syscall_stub, // acct + [90] = (syscall_t) sys_capget, + [91] = (syscall_t) sys_capset, + [92] = (syscall_t) sys_personality, + [93] = (syscall_t) sys_exit, + [94] = (syscall_t) sys_exit_group, + [95] = (syscall_t) sys_waitid, + [96] = (syscall_t) sys_set_tid_address, + [97] = (syscall_t) syscall_stub, // unshare + [98] = (syscall_t) sys_futex, + [99] = (syscall_t) sys_set_robust_list, + [100] = (syscall_t) sys_get_robust_list, + [101] = (syscall_t) sys_nanosleep, + [102] = (syscall_t) syscall_stub, // getitimer + [103] = (syscall_t) sys_setitimer, + [104] = (syscall_t) syscall_stub, // kexec_load + [105] = (syscall_t) syscall_stub, // init_module + [106] = (syscall_t) syscall_stub, // delete_module + [107] = (syscall_t) sys_timer_create, + [108] = (syscall_t) sys_timer_gettime, + [109] = (syscall_t) sys_timer_getoverrun, + [110] = (syscall_t) sys_timer_settime, + [111] = (syscall_t) sys_timer_delete, + [112] = (syscall_t) sys_clock_settime, + [113] = (syscall_t) sys_clock_gettime, + [114] = (syscall_t) sys_clock_getres, + [115] = (syscall_t) sys_clock_nanosleep, + [116] = (syscall_t) sys_syslog, + [117] = (syscall_t) sys_ptrace, + [118] = (syscall_t) sys_sched_setparam, + [119] = (syscall_t) sys_sched_setscheduler, + [120] = (syscall_t) sys_sched_getscheduler, + [121] = (syscall_t) sys_sched_getparam, + [122] = (syscall_t) sys_sched_setaffinity, + [123] = (syscall_t) sys_sched_getaffinity, + [124] = (syscall_t) sys_sched_yield, + [125] = (syscall_t) sys_sched_get_priority_max, + [126] = (syscall_t) sys_sched_get_priority_max, // get_priority_min - should use different func + [127] = (syscall_t) syscall_stub, // sched_rr_get_interval + [128] = (syscall_t) syscall_stub, // restart_syscall + [129] = (syscall_t) sys_kill, + [130] = (syscall_t) sys_tkill, + [131] = (syscall_t) sys_tgkill, + [132] = (syscall_t) sys_sigaltstack, + [133] = (syscall_t) sys_rt_sigsuspend, + [134] = (syscall_t) sys_rt_sigaction, + [135] = (syscall_t) sys_rt_sigprocmask, + [136] = (syscall_t) sys_rt_sigpending, + [137] = (syscall_t) sys_rt_sigtimedwait, + [138] = (syscall_t) syscall_stub, // rt_sigqueueinfo + [139] = (syscall_t) sys_rt_sigreturn, + [140] = (syscall_t) sys_setpriority, + [141] = (syscall_t) sys_getpriority, + [142] = (syscall_t) sys_reboot, + [143] = (syscall_t) sys_setregid, + [144] = (syscall_t) sys_setgid, + [145] = (syscall_t) sys_setreuid, + [146] = (syscall_t) sys_setuid, + [147] = (syscall_t) sys_setresuid, + [148] = (syscall_t) sys_getresuid, + [149] = (syscall_t) sys_setresgid, + [150] = (syscall_t) sys_getresgid, + [151] = (syscall_t) syscall_stub, // setfsuid + [152] = (syscall_t) syscall_stub, // setfsgid + [153] = (syscall_t) sys_times, + [154] = (syscall_t) sys_setpgid, + [155] = (syscall_t) sys_getpgid, + [156] = (syscall_t) sys_getsid, + [157] = (syscall_t) sys_setsid, + [158] = (syscall_t) sys_getgroups, + [159] = (syscall_t) sys_setgroups, + [160] = (syscall_t) sys_uname, + [161] = (syscall_t) sys_sethostname, + [162] = (syscall_t) syscall_stub, // setdomainname + [163] = (syscall_t) sys_getrlimit64, + [164] = (syscall_t) sys_setrlimit64, + [165] = (syscall_t) sys_getrusage, + [166] = (syscall_t) sys_umask, + [167] = (syscall_t) sys_prctl, + [168] = (syscall_t) sys_getcpu, + [169] = (syscall_t) sys_gettimeofday, + [170] = (syscall_t) sys_settimeofday, + [171] = (syscall_t) syscall_stub, // adjtimex + [172] = (syscall_t) sys_getpid, + [173] = (syscall_t) sys_getppid, + [174] = (syscall_t) sys_getuid32, + [175] = (syscall_t) sys_geteuid32, + [176] = (syscall_t) sys_getgid32, + [177] = (syscall_t) sys_getegid32, + [178] = (syscall_t) sys_gettid, + [179] = (syscall_t) sys_sysinfo, + [180] = (syscall_t) sys_mq_open, + [181] = (syscall_t) sys_mq_unlink, + [182] = (syscall_t) sys_mq_timedsend, + [183] = (syscall_t) sys_mq_timedreceive, + [184] = (syscall_t) sys_mq_notify, + [185] = (syscall_t) sys_mq_getsetattr, + [186] = (syscall_t) sys_msgget, + [187] = (syscall_t) sys_msgctl, + [188] = (syscall_t) sys_msgrcv, + [189] = (syscall_t) sys_msgsnd, + [190] = (syscall_t) sys_semget, + [191] = (syscall_t) sys_semctl, + [192] = (syscall_t) sys_semtimedop, + [193] = (syscall_t) sys_semop, + [194] = (syscall_t) sys_shmget, + [195] = (syscall_t) sys_shmctl, + [196] = (syscall_t) sys_shmat, + [197] = (syscall_t) sys_shmdt, + // Socket syscalls (no multiplexer on arm64) + [198] = (syscall_t) sys_socket, + [199] = (syscall_t) sys_socketpair, + [200] = (syscall_t) sys_bind, + [201] = (syscall_t) sys_listen, + [202] = (syscall_t) sys_accept, + [203] = (syscall_t) sys_connect, + [204] = (syscall_t) sys_getsockname, + [205] = (syscall_t) sys_getpeername, + [206] = (syscall_t) sys_sendto, + [207] = (syscall_t) sys_recvfrom, + [208] = (syscall_t) sys_setsockopt, + [209] = (syscall_t) sys_getsockopt, + [210] = (syscall_t) sys_shutdown, + [211] = (syscall_t) sys_sendmsg, + [212] = (syscall_t) sys_recvmsg, + [213] = (syscall_t) syscall_stub, // readahead + [214] = (syscall_t) sys_brk, + [215] = (syscall_t) sys_munmap, + [216] = (syscall_t) sys_mremap, + [217] = (syscall_t) syscall_stub, // add_key + [218] = (syscall_t) syscall_stub, // request_key + [219] = (syscall_t) syscall_stub, // keyctl + [220] = (syscall_t) sys_clone, + [221] = (syscall_t) sys_execve, + [222] = (syscall_t) sys_mmap64, + [223] = (syscall_t) sys_fadvise64, // fadvise64 + [224] = (syscall_t) syscall_stub, // swapon + [225] = (syscall_t) syscall_stub, // swapoff + [226] = (syscall_t) sys_mprotect, + [227] = (syscall_t) sys_msync, + [228] = (syscall_t) sys_mlock, + [229] = (syscall_t) syscall_stub, // munlock + [230] = (syscall_t) syscall_stub, // mlockall + [231] = (syscall_t) syscall_stub, // munlockall + [232] = (syscall_t) sys_mincore, // mincore + [233] = (syscall_t) sys_madvise, + [234] = (syscall_t) syscall_stub, // remap_file_pages + [235] = (syscall_t) sys_mbind, + [236] = (syscall_t) syscall_stub, // get_mempolicy + [237] = (syscall_t) syscall_stub, // set_mempolicy + [238] = (syscall_t) syscall_stub, // migrate_pages + [239] = (syscall_t) syscall_stub, // move_pages + [240] = (syscall_t) syscall_stub, // rt_tgsigqueueinfo + [241] = (syscall_t) syscall_stub, // perf_event_open + [242] = (syscall_t) sys_accept4, + [243] = (syscall_t) sys_recvmmsg, + [260] = (syscall_t) sys_wait4, + [261] = (syscall_t) sys_prlimit64, + [262] = (syscall_t) syscall_stub, // fanotify_init + [263] = (syscall_t) syscall_stub, // fanotify_mark + [264] = (syscall_t) syscall_stub, // name_to_handle_at + [265] = (syscall_t) syscall_stub, // open_by_handle_at + [266] = (syscall_t) syscall_stub, // clock_adjtime + [267] = (syscall_t) syscall_stub, // syncfs + [268] = (syscall_t) syscall_stub, // setns + [269] = (syscall_t) sys_sendmmsg, + [270] = (syscall_t) sys_process_vm_readv, + [271] = (syscall_t) sys_process_vm_writev, + [272] = (syscall_t) syscall_stub, // kcmp + [273] = (syscall_t) syscall_stub, // finit_module + [274] = (syscall_t) syscall_stub, // sched_setattr + [275] = (syscall_t) syscall_stub, // sched_getattr + [276] = (syscall_t) sys_renameat2, + [277] = (syscall_t) syscall_stub, // seccomp + [278] = (syscall_t) sys_getrandom, + [279] = (syscall_t) sys_memfd_create, + [280] = (syscall_t) syscall_stub, // bpf + [281] = (syscall_t) sys_execve, // execveat + [282] = (syscall_t) syscall_stub, // userfaultfd + [283] = (syscall_t) sys_membarrier, + [284] = (syscall_t) syscall_stub, // mlock2 + [285] = (syscall_t) sys_copy_file_range, + [286] = (syscall_t) sys_preadv2, + [287] = (syscall_t) sys_pwritev2, + [288] = (syscall_t) syscall_stub, // pkey_mprotect + [289] = (syscall_t) syscall_stub, // pkey_alloc + [290] = (syscall_t) syscall_stub, // pkey_free + [291] = (syscall_t) sys_statx, + [293] = (syscall_t) sys_rseq, + [425] = (syscall_t) syscall_silent_stub, // io_uring_setup + [426] = (syscall_t) syscall_silent_stub, // io_uring_enter + [427] = (syscall_t) syscall_silent_stub, // io_uring_register + [434] = (syscall_t) sys_pidfd_open, // pidfd_open + [435] = (syscall_t) sys_clone3, + [436] = (syscall_t) sys_close_range, + [437] = (syscall_t) sys_openat2, + [438] = (syscall_t) syscall_silent_stub, // pidfd_getfd + [439] = (syscall_t) sys_faccessat2, + [452] = (syscall_t) sys_fchmodat2, +}; + +#define NUM_SYSCALLS (sizeof(syscall_table) / sizeof(syscall_table[0])) +size_t syscall_table_size = NUM_SYSCALLS; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/arch/arm64/signal.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/arch/arm64/signal.h new file mode 100644 index 0000000000..84e5fc7f17 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/arch/arm64/signal.h @@ -0,0 +1,114 @@ +#ifndef KERNEL_ARCH_ARM64_SIGNAL_H +#define KERNEL_ARCH_ARM64_SIGNAL_H + +#include "misc.h" + +/* + * ARM64 Signal Handling Structures + * + * These structures match the Linux kernel's arm64 signal frame layout. + * See arch/arm64/include/uapi/asm/sigcontext.h in the Linux kernel. + */ + +// ARM64 signal context (saved CPU state) +struct sigcontext_arm64 { + uint64_t fault_address; + // General purpose registers x0-x30 + uint64_t regs[31]; + // Stack pointer + uint64_t sp; + // Program counter + uint64_t pc; + // PSTATE (processor state) + uint64_t pstate; + // Padding for 16-byte alignment before extension area + uint8_t __reserved[4096] __attribute__((aligned(16))); +}; + +// ARM64 ucontext structure +struct ucontext_arm64 { + unsigned long uc_flags; + struct ucontext_arm64 *uc_link; + struct stack_t_ uc_stack; + struct sigset_t_ uc_sigmask; + // Padding for alignment + uint8_t __pad[1024 / 8 - sizeof(struct sigset_t_)]; + // Must be 16-byte aligned + struct sigcontext_arm64 uc_mcontext; +}; + +// ARM64 signal frame (pushed onto stack when signal is delivered) +struct rt_sigframe_arm64 { + struct siginfo_ info; + struct ucontext_arm64 uc; + // FPSIMD context follows (optional, indicated by magic in __reserved) +}; + +// Magic values for the __reserved area (indicates what extra context is present) +#define FPSIMD_MAGIC 0x46508001 +#define ESR_MAGIC 0x45535201 +#define EXTRA_MAGIC 0x45585401 +#define SVE_MAGIC 0x53564501 + +// FPSIMD context header +struct fpsimd_context { + uint32_t magic; + uint32_t size; + uint32_t fpsr; + uint32_t fpcr; + // 32 x 128-bit vector registers + __uint128_t vregs[32]; +}; + +// Extra context header (for when __reserved isn't big enough) +struct extra_context { + uint32_t magic; + uint32_t size; + uint64_t datap; // Pointer to extra data + uint32_t extra_size; + uint32_t __reserved2[3]; +}; + +// ESR (Exception Syndrome Register) context +struct esr_context { + uint32_t magic; + uint32_t size; + uint64_t esr; +}; + +// Function to setup signal frame for ARM64 +static inline int arm64_setup_sigframe(struct sigcontext_arm64 *ctx, struct cpu_state *cpu) { +#if defined(GUEST_ARM64) + ctx->fault_address = cpu->segfault_addr; + for (int i = 0; i < 31; i++) { + ctx->regs[i] = cpu->regs[i]; + } + ctx->sp = cpu->sp; + ctx->pc = cpu->pc; + ctx->pstate = arm64_get_nzcv(cpu); + return 0; +#else + (void)ctx; + (void)cpu; + return -1; +#endif +} + +// Function to restore CPU state from signal frame +static inline int arm64_restore_sigframe(struct cpu_state *cpu, struct sigcontext_arm64 *ctx) { +#if defined(GUEST_ARM64) + for (int i = 0; i < 31; i++) { + cpu->regs[i] = ctx->regs[i]; + } + cpu->sp = ctx->sp; + cpu->pc = ctx->pc; + arm64_set_nzcv(cpu, (uint32_t)ctx->pstate); + return 0; +#else + (void)ctx; + (void)cpu; + return -1; +#endif +} + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/calls.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/calls.c new file mode 100644 index 0000000000..fa2473f205 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/calls.c @@ -0,0 +1,897 @@ +#include <string.h> +#include <errno.h> +#include <unistd.h> +#include <sys/stat.h> +#include <time.h> +#include "debug.h" +#include "kernel/calls.h" +#include "emu/interrupt.h" +#include "kernel/memory.h" +#include "kernel/signal.h" +#include "kernel/task.h" +#include "fs/stat.h" +#include "fs/fd.h" +#include "fs/dev.h" +#include "fs/real.h" +#include "platform/platform.h" + +dword_t syscall_stub(void) { + return _ENOSYS; +} +// While identical, this version of the stub doesn't log below. Use this for +// syscalls that are optional (i.e. fallback on something else) but called +// frequently. +dword_t syscall_silent_stub(void) { + return _ENOSYS; +} +dword_t syscall_success_stub(void) { + return 0; +} + +// Syscall table is defined in arch-specific files (kernel/arch/*/calls.c) +extern syscall_t syscall_table[]; +extern size_t syscall_table_size; + +void dump_stack(int lines); +void dump_maps(void); + +// Fast path syscall handlers (forward declarations) +static inline int fast_fstat64(struct cpu_state *cpu); +static inline int fast_read(struct cpu_state *cpu); +static inline int fast_write(struct cpu_state *cpu); + +// Diagnostic: JIT crash info from signal handler +__thread volatile uint64_t jit_last_host_fault = 0; +__thread volatile uint64_t jit_last_x7 = 0; +__thread volatile uint64_t jit_last_x10 = 0; +__thread volatile int jit_crash_count = 0; +volatile bool g_trace_faults = false; + +void handle_interrupt(int interrupt) { + struct cpu_state *cpu = ¤t->cpu; + if (interrupt == INT_SYSCALL) { + // ARM64: syscall number in x8, args in x0-x5, return in x0 + unsigned syscall_num = cpu->regs[8]; + // Snapshot for SA_RESTART: x0 (first arg) is about to be clobbered by + // the return value; save it and the number so an interrupted syscall + // can be re-executed if a SA_RESTART signal is delivered. + current->syscall_restart_num = syscall_num; + current->syscall_restart_arg0 = cpu->regs[0]; + // The svc gadget already advanced cpu.pc to the instruction after the + // svc. Record it so the SA_RESTART rewind can verify PC is still exactly + // here (i.e. we really are delivering a signal for THIS interrupted + // syscall) before doing pc -= 4. + current->syscall_restart_pc = cpu->pc; + current->syscall_restartable = false; + + // === FAST PATH: Hot syscalls === + int fast_result = -1; // -1 means fast path not taken + bool fast_path_taken = false; + + // Fast path 1: fstat64 (syscall 80) - most common during Python import + if (syscall_num == 80) { + fast_result = fast_fstat64(cpu); + if (fast_result != -1) + fast_path_taken = true; + } + // Fast path 2: read (syscall 63) - small buffer reads + else if (syscall_num == 63) { + fast_result = fast_read(cpu); + if (fast_result != -1) + fast_path_taken = true; + } + // Fast path 3: write (syscall 64) - small buffer writes + else if (syscall_num == 64) { + fast_result = fast_write(cpu); + if (fast_result != -1) + fast_path_taken = true; + } + + if (fast_path_taken) { + // Fast path succeeded, return immediately + // Fast paths return int (small values), safe to use directly + STRACE("%d call %-3d (fast) = 0x%x\n", current->pid, syscall_num, fast_result); + int32_t signed_result = (int32_t)fast_result; + if (signed_result >= -4095 && signed_result < 0) { + cpu->regs[0] = (uint64_t)(int64_t)signed_result; + } else { + cpu->regs[0] = (uint64_t)(uint32_t)fast_result; + } + } else { + // === SLOW PATH: Full syscall === + if (syscall_num >= syscall_table_size || syscall_table[syscall_num] == NULL) { + printk("%d(%s) missing syscall %d\n", current->pid, current->comm, syscall_num); + cpu->regs[0] = (uint64_t)(int64_t)(int32_t)_ENOSYS; + } else { + if (syscall_table[syscall_num] == (syscall_t) syscall_stub) { + printk("%d(%s) stub syscall %d\n", current->pid, current->comm, syscall_num); + } + STRACE("%d call %-3d ", current->pid, syscall_num); + // env-gated full syscall trace for golden-diff vs native strace. + // ISH_SYSTRACE=1 logs every slow-path syscall with timestamp, + // pid, number, the 6 args, and the return value. + static int systrace = -1; + if (systrace == -1) { const char *e = getenv("ISH_SYSTRACE"); systrace = (e && e[0]=='1') ? 1 : 0; } + if (systrace) { + struct timespec _t; clock_gettime(CLOCK_MONOTONIC, &_t); + fprintf(stderr, "[sc] %ld.%06ld pid=%d n=%d(%llx,%llx,%llx,%llx,%llx,%llx)", + (long)_t.tv_sec, _t.tv_nsec/1000, current->pid, syscall_num, + (unsigned long long)cpu->regs[0], (unsigned long long)cpu->regs[1], + (unsigned long long)cpu->regs[2], (unsigned long long)cpu->regs[3], + (unsigned long long)cpu->regs[4], (unsigned long long)cpu->regs[5]); + } + int64_t result = syscall_table[syscall_num]( + cpu->regs[0], cpu->regs[1], cpu->regs[2], + cpu->regs[3], cpu->regs[4], cpu->regs[5]); + STRACE(" = 0x%llx\n", (unsigned long long)result); + if (systrace) + fprintf(stderr, " = 0x%llx\n", (unsigned long long)result); + // SA_RESTART: mark this syscall restartable if it was + // interrupted (EINTR). receive_signals will rewind PC if the + // delivered signal's handler has SA_RESTART. Restricted to + // syscalls that re-execute correctly by simply re-running with + // the same args (futex, poll/epoll, read/write, recv/send, + // accept, connect, wait). Timer syscalls (nanosleep, + // clock_nanosleep, ppoll/pselect with timeout) must NOT use + // naive PC-rewind restart: it would restart the FULL duration + // rather than the remaining time, so a `timeout N` wrapper's + // sleep would never end. Those keep returning EINTR (userspace + // handles their own restart with an adjusted timeout). + if ((int32_t)(uint32_t)result == -EINTR) { + switch (syscall_num) { + case 98: // futex + case 22: // epoll_pwait + case 63: // read + case 64: // write + current->syscall_restartable = true; + break; + default: + current->syscall_restartable = false; + } + } + // sigreturn/rt_sigreturn restore the full CPU state from the + // signal frame. Do NOT touch regs[0] — it was already restored + // by restore_sigcontext. Any post-processing could corrupt the + // restored x0 value (e.g., errno sign-extension). + if (syscall_num == 139 /* rt_sigreturn */) { + // x0 already set by restore_sigcontext, skip writeback + } else if (syscall_num == 62 /* lseek */) { + // sys_lseek64 already returns a full-width value (including + // sign-extended errors). Valid offsets 0xfffff001..0xffffffff + // must not be mistaken for zero-extended 32-bit errnos. + cpu->regs[0] = (uint64_t)result; + } else { + // ARM64 Linux ABI: return value in x0. Errors are negative + // (-1 to -4095). Success values are 0 or positive (up to 48-bit + // addresses from mmap/brk). + // Most syscalls return dword_t (uint32_t). On ARM64 ABI, returning + // uint32_t sets w0 only; upper x0 is zero. Error codes like -EFAULT + // become 0x00000000FFFFFFF2 instead of 0xFFFFFFFFFFFFFFF2. + // Detect this: if low 32 bits are a valid errno (0xFFFFF001-0xFFFFFFFF) + // but upper 32 bits are 0, sign-extend the 32-bit value. + uint32_t low32 = (uint32_t)result; + if ((result >> 32) == 0 && (int32_t)low32 >= -4095 && (int32_t)low32 < 0) { + // 32-bit errno from dword_t-returning syscall — sign-extend + cpu->regs[0] = (uint64_t)(int64_t)(int32_t)low32; + } else { + cpu->regs[0] = (uint64_t)result; + } + } + } + } + // [T-ish-group-null-post-syscall-crash] The syscall we just ran may have + // left this thread orphaned: a blocking syscall (futex/poll/wait) can + // return right as another thread's do_exit_group() safety valve + // force-releases us — it sets our `exiting` flag — and, once the group + // leader is reaped, task_destroy() does memset(task, 0, ...) which + // zeroes our (thread-local) `current` struct, so both `current->group` + // and `current->exiting` read back as 0/NULL. The post-syscall + // bookkeeping below dereferences current->group unconditionally; with a + // zeroed group that computes &((tgroup*)0)->syscall_count == 0x4fc and + // the atomic_fetch_add faults (the reported EXC_BAD_ACCESS at 0x4fc on a + // backgrounded guest thread). task_run_current()'s top-of-loop guard + // already handles this, but only on the NEXT iteration — we must not + // touch group before we get back there. + // + // Bail the SAME way task_run_current() does for a destroyed/leaked task: + // pthread_exit() straight out, letting task_run_current()'s + // pthread_cleanup handler (task_run_tlb_cleanup) run — it honors + // mm_release_deferred and frees the tlb. Do NOT call do_exit() here: + // * for the zeroed-struct case (group==NULL, exiting==0) do_exit() + // would fall through its `if (current->exiting)` fast-path and then + // dereference current->group->doing_group_exit — the same NULL crash + // one line over; + // * for the force-released case (exiting==1) do_exit() sets + // current=NULL before pthread_exit(), which makes task_run_tlb_cleanup + // skip the deferred mm_release and leak the guest address space. + // Reading group_exit_code for a status is pointless anyway — do_exit() + // ignores its argument once `exiting` is set — and unsafe, since the + // group may already be freed. + if (current->exiting || current->group == NULL) { + pthread_exit(NULL); + } + // Update deadlock detection state. + atomic_fetch_add(¤t->group->syscall_count, 1); + // Update last_unblocked_ns for non-blocking syscalls only. + // Blocking calls (futex, epoll, ppoll, waitid, nanosleep) that + // return and retry should NOT refresh the timestamp, as they + // don't represent real forward progress. + if (syscall_num != 22 && syscall_num != 73 && syscall_num != 95 && + syscall_num != 98 && syscall_num != 101) { + struct timespec _ts; + clock_gettime(CLOCK_MONOTONIC, &_ts); + uint64_t now = (uint64_t)_ts.tv_sec * 1000000000ULL + _ts.tv_nsec; + current->last_unblocked_ns = now; + atomic_store_explicit(¤t->group->last_progress_ns, now, + memory_order_relaxed); + } + // Check for pending group exit. When do_exit_group sends SIGKILL to + // all threads, a thread stuck in a retrying syscall (e.g., musl's + // futex_wait loops on EINTR) would never return to the JIT dispatch + // loop where receive_signals() handles SIGKILL. Catch it here. + if (current->group->doing_group_exit) + do_exit(current->group->group_exit_code); + } else if (interrupt == INT_GPF) { + read_wrlock(¤t->mem->lock); + void *ptr = mem_ptr(current->mem, cpu->segfault_addr, cpu->segfault_was_write ? MEM_WRITE : MEM_READ); + read_wrunlock(¤t->mem->lock); + // Read fault on unmapped page near a heap mapping: demand-map as + // readable zeros. On native Linux, heap regions are contiguous so + // out-of-bounds reads access adjacent allocations (no SIGSEGV). In iSH, + // mmap can leave unmapped gaps. Map the faulting page if a mapped + // neighbor exists within a few pages (typical heap gap boundary). + if (ptr == NULL && !cpu->segfault_was_write) { + page_t fault_page = PAGE(cpu->segfault_addr); + // Check if a mapped page exists nearby (within 16 pages = 64KB) + bool has_neighbor = false; + read_wrlock(¤t->mem->lock); + for (page_t p = fault_page + 1; p <= fault_page + 16 && p < MEM_PAGES; p++) { + if (mem_pt(current->mem, p) != NULL) { has_neighbor = true; break; } + } + if (!has_neighbor) { + for (page_t p = fault_page > 16 ? fault_page - 16 : 0; p < fault_page; p++) { + if (mem_pt(current->mem, p) != NULL) { has_neighbor = true; break; } + } + } + read_wrunlock(¤t->mem->lock); + if (has_neighbor) { + write_wrlock(¤t->mem->lock); + if (mem_pt(current->mem, fault_page) == NULL) { + int err = pt_map_nothing(current->mem, fault_page, 1, P_READ); + if (err >= 0) { + write_wrunlock(¤t->mem->lock); + goto gpf_handled; + } + } + write_wrunlock(¤t->mem->lock); + } + } + if (ptr == NULL) { + // V8 Zone memory reuse workaround: V8's Zone bump allocator reuses + // memory without zeroing. A DeclarationScope can be allocated over + // stale Variable data, inheriting -1 sentinel values in uninitialized + // fields (offsets 0xB0-0xD0). When AllocateVariablesRecursively reads + // scope+0xD0 and dereferences -1, we crash here. + // + // Pattern: LDR Xd, [Xn, #imm] faults on addr=0xFFFF... (sentinel -1) + // followed by CBZ Xd, <target> (V8's own null check) + // Recovery: set Xd=0 and advance PC by 4. The CBZ takes the null branch. + // Detect clearly-unmapped addresses that indicate dereferencing a + // corrupt/sentinel pointer. In our memory layout, valid pages are in + // the range 0x0-0xefffd000 (mmap) and 0xffff1000-0xfffff000 (stack). + // Anything above 0xf0000000 that's not stack, or anything in the + // 48-bit upper range, is a sentinel pointer dereference. + { + // Rate-limit V8 zone fix recoveries to prevent cascading + static _Thread_local int v8_zone_fix_count = 0; + static _Thread_local int v8_burst_count = 0; // consecutive recoveries + static _Thread_local uint64_t v8_last_recovery_pc = 0; + (void)0; + + // Detect faults on corrupt/sentinel pointers. + // mem_ptr already returned NULL, so the address is truly unmapped. + // We catch these cases: + // 1. NULL page (addr < 0x1000): null pointer + small offset + // 2. Above 4GB: clearly garbage 48/64-bit address + // 3. Gap between mmap top and stack (0xf0000000..0xffff0000) + // 4. Any unmapped address when PC is within the node binary text + // segment — V8 scope corruption causes derefs of stale pointers + // to freed/reused Zone memory at arbitrary addresses + bool is_sentinel = (cpu->segfault_addr >= 0x100000000ULL) || + (cpu->segfault_addr >= 0xf0000000ULL && + cpu->segfault_addr < 0xffff0000ULL) || + (cpu->segfault_addr < 0x1000); + // Also treat as sentinel if PC is within node binary text and the + // fault address is in an area that shouldn't hold valid V8 objects. + // V8 heap is typically above 0xc0000000 in our layout; anything + // below that is likely a stale/corrupt pointer. + if (!is_sentinel && cpu->segfault_addr < 0xc0000000) { + // Check if PC looks like it's in a mapped code segment + // (node binary or shared libs: 0xec000000..0xf0000000) + if (cpu->pc >= 0xec000000 && cpu->pc < 0xf0000000) + is_sentinel = true; + } + // Only recover from V8 scope-walking crashes, not general + // pointer corruptions. The scope-walking code is in a narrow + // PC range. For other crashes, let the signal handler deal. + // Check if we're in V8 scope/module code, or if the caller (LR) + // is in that range (e.g., V8 code called memset/memcpy in musl + // with a corrupt argument). Also check a few FP chain frames. + bool is_scope_pc = false; + { + // Direct PC ranges + uint64_t check_pcs[] = { cpu->pc, cpu->regs[30] }; + for (int ci = 0; ci < 2; ci++) { + uint64_t pc = check_pcs[ci]; + if ((pc >= 0xee270000 && pc < 0xee290000) || + (pc >= 0xee810000 && pc < 0xee830000) || + (pc >= 0xee7e0000 && pc < 0xee830000)) { + is_scope_pc = true; + break; + } + } + // Also check first few FP chain entries + if (!is_scope_pc) { + uint64_t fp = cpu->regs[29]; + for (int ci = 0; ci < 3 && !is_scope_pc; ci++) { + uint64_t sfp = 0, slr = 0; + bool ok = true; + for (int j = 0; j < 8; j++) { + uint8_t b; + if (user_get(fp + j, b)) { ok = false; break; } + sfp |= (uint64_t)b << (j * 8); + } + if (ok) for (int j = 0; j < 8; j++) { + uint8_t b; + if (user_get(fp + 8 + j, b)) { ok = false; break; } + slr |= (uint64_t)b << (j * 8); + } + if (!ok || slr < 0xed000000 || slr >= 0xf0000000) break; + if ((slr >= 0xee270000 && slr < 0xee290000) || + (slr >= 0xee7e0000 && slr < 0xee830000)) { + is_scope_pc = true; + } + fp = sfp; + } + } + } + if (is_sentinel && is_scope_pc && v8_zone_fix_count < 500) { + v8_burst_count++; + // Read faulting instruction + uint32_t fault_insn = 0; + bool insn_ok = true; + for (int j = 0; j < 4; j++) { + uint8_t b; + if (user_get(cpu->pc + j, b)) { insn_ok = false; break; } + fault_insn |= (uint32_t)b << (j * 8); + } + // Deep frame unwind: skip ALL V8 scope/module-loader/musl frames. + // V8 Zone corruption poisons entire call subtrees — returning to + // intermediate frames just triggers cascade crashes. Skip the + // ENTIRE subtree to reach a safe return point. + { + uint64_t fp = cpu->regs[29]; + uint64_t saved_fp = 0, saved_lr = 0; + int frames_unwound = 0; + const int max_unwind = 50; + while (frames_unwound < max_unwind) { + saved_fp = 0; + saved_lr = 0; + bool fp_ok = true; + for (int j = 0; j < 8; j++) { + uint8_t b; + if (user_get(fp + j, b)) { fp_ok = false; break; } + saved_fp |= (uint64_t)b << (j * 8); + } + if (fp_ok) for (int j = 0; j < 8; j++) { + uint8_t b; + if (user_get(fp + 8 + j, b)) { fp_ok = false; break; } + saved_lr |= (uint64_t)b << (j * 8); + } + if (!fp_ok || saved_lr < 0xed000000 || saved_lr >= 0xf0000000) + break; + // FP must be on the stack + if (!(saved_fp >= 0xffff0000 && saved_fp < 0xfffff000)) + break; + + frames_unwound++; + + // Normally skip only V8 scope-walking frames. + // After 8+ consecutive recoveries (burst mode), also skip + // module loader frames to escape the corrupt subtree. + bool is_scope = + (saved_lr >= 0xee270000 && saved_lr < 0xee290000) || + (saved_lr >= 0xed11a000 && saved_lr < 0xed1dd000); + if (v8_burst_count > 3) { + // Deep unwind: skip entire node binary text segment + is_scope = is_scope || + (saved_lr >= 0xed1dd000 && saved_lr < 0xeff08000); + } + + if (!is_scope) { + // Restore callee-saved registers from the target frame. + // Scan backward from saved_lr for STP patterns. + // Support both: + // 1. SUB SP,SP,#N; STP x29,x30,[SP,#off]; STP x19,x20,[SP,#off] + // 2. STP x29,x30,[SP,#-N]! (pre-indexed, combines alloc+store) + { + int64_t x19_off = -1, x21_off = -1, fp_off = -1; + uint64_t sp_sub = 0; + bool found_preindex_fp = false; + + for (int scan = 1; scan <= 128; scan++) { + uint32_t pi = 0; + bool pi_ok = true; + for (int j = 0; j < 4; j++) { + uint8_t b; + if (user_get(saved_lr - scan * 4 + j, b)) { pi_ok = false; break; } + pi |= (uint32_t)b << (j * 8); + } + if (!pi_ok) break; + + // SUB SP, SP, #imm (sf=1, op=1, S=0, shift=00) + if ((pi & 0xFF0003FF) == 0xD10003FF) { + sp_sub = (pi >> 10) & 0xFFF; + break; + } + // STP x29,x30,[SP,#-N]! (pre-indexed: opc=10 V=0 type=011 L=0) + // 10 101 0 011 0 imm7 11110 11111 11101 + // Mask: bits[31:22]=1010100110, Rt2=x30(11110), Rn=SP(11111), Rt=x29(11101) + if ((pi & 0xFFC07FFF) == 0xA9807BFD) { + int imm7 = (pi >> 15) & 0x7F; + if (imm7 & 0x40) imm7 -= 128; + sp_sub = (uint64_t)(-imm7 * 8); + fp_off = 0; // FP is at SP after pre-index + found_preindex_fp = true; + break; + } + // STP x19, x20, [SP, #offset] (signed offset) + if ((pi & 0xFFC003FF) == 0xA90003F3 && ((pi >> 10) & 0x1F) == 20) { + int imm7 = (pi >> 15) & 0x7F; + if (imm7 & 0x40) imm7 -= 128; + x19_off = imm7 * 8; + } + // STP x21, x22, [SP, #offset] + if ((pi & 0xFFC003FF) == 0xA90003F5 && ((pi >> 10) & 0x1F) == 22) { + int imm7 = (pi >> 15) & 0x7F; + if (imm7 & 0x40) imm7 -= 128; + x21_off = imm7 * 8; + } + // STP x29, x30, [SP, #offset] (signed offset, non-preindex) + if (!found_preindex_fp && + (pi & 0xFFC003FF) == 0xA90003FD && ((pi >> 10) & 0x1F) == 30) { + int imm7 = (pi >> 15) & 0x7F; + if (imm7 & 0x40) imm7 -= 128; + fp_off = imm7 * 8; + } + } + + // Compute the target frame's SP + if (sp_sub > 0 && fp_off >= 0) { + uint64_t func_sp = saved_fp - fp_off; + if (x19_off >= 0) { + uint64_t v19 = 0, v20 = 0; + for (int j = 0; j < 8; j++) { + uint8_t b; + if (user_get(func_sp + x19_off + j, b) == 0) + v19 |= (uint64_t)b << (j*8); + if (user_get(func_sp + x19_off + 8 + j, b) == 0) + v20 |= (uint64_t)b << (j*8); + } + cpu->regs[19] = v19; + cpu->regs[20] = v20; + } + if (x21_off >= 0) { + uint64_t v21 = 0, v22 = 0; + for (int j = 0; j < 8; j++) { + uint8_t b; + if (user_get(func_sp + x21_off + j, b) == 0) + v21 |= (uint64_t)b << (j*8); + if (user_get(func_sp + x21_off + 8 + j, b) == 0) + v22 |= (uint64_t)b << (j*8); + } + cpu->regs[21] = v21; + cpu->regs[22] = v22; + } + // Set SP = func_sp (post-prologue SP of the target frame) + cpu->sp = func_sp; + } else { + cpu->sp = saved_fp; // fallback + } + } + cpu->regs[29] = saved_fp; + cpu->regs[30] = saved_lr; + cpu->pc = saved_lr; + cpu->regs[0] = 0; + v8_zone_fix_count++; + if (frames_unwound > 3) + v8_burst_count = 0; // deep unwind succeeded + goto gpf_handled; + } + + fp = saved_fp; + } + if (v8_burst_count > 3) { + // Deep unwind failed — entire call stack is corrupt. + // Kill the process gracefully with SIGABRT. + struct siginfo_ info = { + .sig = SIGABRT_, + .code = SI_KERNEL_, + }; + deliver_signal(current, SIGABRT_, info); + v8_burst_count = 0; + goto gpf_handled; + } + } + } // is_sentinel + } // scope block + if (g_trace_faults) { + printk("%d page fault on 0x%llx at 0x%llx (%s)\n", current->pid, (unsigned long long)cpu->segfault_addr, (unsigned long long)cpu->pc, cpu->segfault_was_write ? "write" : "read"); + // Dump instruction bytes and key registers for debugging + uint32_t fault_insn = 0; + for (int j = 0; j < 4; j++) { + uint8_t b; + if (user_get(cpu->pc + j, b)) break; + fault_insn |= (uint32_t)b << (j * 8); + } + printk(" insn=0x%08x x0=0x%llx x1=0x%llx x2=0x%llx x3=0x%llx\n", + fault_insn, (unsigned long long)cpu->regs[0], (unsigned long long)cpu->regs[1], + (unsigned long long)cpu->regs[2], (unsigned long long)cpu->regs[3]); + printk(" sp=0x%llx x29=0x%llx x30=0x%llx brk=0x%llx\n", + (unsigned long long)cpu->sp, + (unsigned long long)cpu->regs[29], (unsigned long long)cpu->regs[30], + (unsigned long long)current->mm->brk); + printk(" x4=0x%llx x5=0x%llx x8=0x%llx x9=0x%llx x10=0x%llx\n", + (unsigned long long)cpu->regs[4], (unsigned long long)cpu->regs[5], + (unsigned long long)cpu->regs[8], (unsigned long long)cpu->regs[9], + (unsigned long long)cpu->regs[10]); + printk(" sp+0x3e8=0x%llx jit_crashes=%d\n", + (unsigned long long)(cpu->sp + 0x3e8), + jit_crash_count); + // Dump block instructions when fault addr > 4GB (overflow address) + if (cpu->segfault_addr > 0x100000000ULL) { + printk(" block insns from PC=0x%llx:\n", (unsigned long long)cpu->pc); + for (int bi = 0; bi < 32; bi++) { + uint32_t bi_insn = 0; + bool bi_ok = true; + for (int j = 0; j < 4; j++) { + uint8_t b; + if (user_get(cpu->pc + bi * 4 + j, b)) { bi_ok = false; break; } + bi_insn |= (uint32_t)b << (j * 8); + } + if (!bi_ok) break; + printk(" 0x%llx: 0x%08x\n", (unsigned long long)(cpu->pc + bi * 4), bi_insn); + // Stop at RET or unconditional branch + if (bi_insn == 0xd65f03c0 || (bi_insn & 0xFC000000) == 0x14000000) + break; + } + } + } + // Read-fault recovery: if a load instruction reads from unmapped + // memory, set destination register to 0 and advance PC. + // This handles cases where guest code makes out-of-bounds reads + // that work on native Linux (because adjacent heap pages are always + // mapped) but crash in iSH (because we have unmapped gaps). + // Rate-limited to prevent infinite loops on true null-pointer derefs. +#if defined(GUEST_ARM64) && defined(ENABLE_ARM64_READ_FAULT_RECOVERY) + if (!cpu->segfault_was_write && cpu->segfault_addr >= 0x1000) { + static _Thread_local int read_recovery_count = 0; + static _Thread_local addr_t last_recovery_addr = 0; + // Diagnostic-only compatibility hack: synthesize zero for a + // small number of non-null unmapped reads. Keep disabled in + // production because it hides real emulation/runtime bugs and + // corrupts JIT/compiler state (for example HotSpot C2). + if (cpu->segfault_addr != last_recovery_addr) { + read_recovery_count = 0; + last_recovery_addr = cpu->segfault_addr; + } + if (read_recovery_count < 5) { + read_recovery_count++; + uint32_t insn = 0; + bool insn_ok = true; + for (int j = 0; j < 4; j++) { + uint8_t b; + if (user_get(cpu->pc + j, b)) { insn_ok = false; break; } + insn |= (uint32_t)b << (j * 8); + } + if (insn_ok) { + uint32_t rt = insn & 0x1f; + bool is_load = false; + uint32_t rn = (insn >> 5) & 0x1f; + int has_writeback = 0; + if ((insn & 0x3b200c00) == 0x38000400 || // post-indexed + (insn & 0x3b200c00) == 0x38000c00 || // pre-indexed + (insn & 0x3b200c00) == 0x38000000) { // unscaled + uint32_t opc = (insn >> 22) & 3; + is_load = (opc != 0); + uint32_t idx_type = (insn >> 10) & 3; + if (idx_type == 1 || idx_type == 3) + has_writeback = 1; + } + if ((insn & 0x3b400000) == 0x39400000) + is_load = true; + if ((insn & 0x3b200c00) == 0x38200800) { + uint32_t opc = (insn >> 22) & 3; + is_load = (opc != 0); + } + if ((insn & 0x7fc00000) == 0xa9400000 || + (insn & 0x7fc00000) == 0x29400000) { + is_load = true; + rn = (insn >> 5) & 0x1f; + uint32_t rt2 = (insn >> 10) & 0x1f; + if (rt2 < 31) cpu->regs[rt2] = 0; + } + if (is_load && rt < 31) { + cpu->regs[rt] = 0; + if (has_writeback && rn < 31) { + int32_t imm9 = (int32_t)((insn >> 12) & 0x1ff); + if (imm9 & 0x100) imm9 |= ~0x1ff; + cpu->regs[rn] = (cpu->regs[rn] + imm9) & 0xffffffffffffULL; + } + cpu->pc += 4; + goto gpf_handled; + } + } + } + } +#endif + + struct siginfo_ info = { + .code = mem_segv_reason(current->mem, cpu->segfault_addr), + .fault.addr = cpu->segfault_addr, + }; + if (g_trace_faults) { + dump_stack(8); + dump_maps(); + } + force_signal(current, SIGSEGV_, info); + } + gpf_handled:; + } else if (interrupt == INT_UNDEFINED) { + { + uint32_t ill_insn = 0; + for (int i = 0; i < 4; i++) { + uint8_t b; + if (user_get(cpu->pc + i, b)) + break; + ill_insn |= (uint32_t)b << (i * 8); + } + printk("%d illegal instruction at 0x%llx: insn=0x%08x\n", current->pid, (unsigned long long)cpu->pc, ill_insn); + } + printk("\n"); + dump_stack(8); + struct siginfo_ info = { + .code = SI_KERNEL_, + .fault.addr = cpu->pc, + }; + force_signal(current, SIGILL_, info); + } else if (interrupt == INT_BREAKPOINT) { + { + uint32_t brk_insn = 0; + for (int j = 0; j < 4; j++) { + uint8_t b; + if (user_get(cpu->pc + j, b)) break; + brk_insn |= (uint32_t)b << (j * 8); + } + uint16_t brk_imm = (brk_insn >> 5) & 0xFFFF; + + // BRK #0xBC handler: V8 derived constructor new.target fix + // (binary trampoline at code cave handles this now — no BRK needed) + } + lock(&pids_lock); + send_signal(current, SIGTRAP_, (struct siginfo_) { + .sig = SIGTRAP_, + .code = SI_KERNEL_, + }); + unlock(&pids_lock); + } else if (interrupt == INT_DEBUG) { + lock(&pids_lock); + send_signal(current, SIGTRAP_, (struct siginfo_) { + .sig = SIGTRAP_, + .code = TRAP_TRACE_, + }); + unlock(&pids_lock); + } else if (interrupt == INT_TIMER) { + // timer handled below + } else { + printk("EXIT[unhandled-int]: pid=%d interrupt=%d\n", current->pid, interrupt); + sys_exit(interrupt); + } + + receive_signals(); + struct tgroup *group = current->group; + lock(&group->lock); + while (group->stopped) + wait_for_ignore_signals(&group->stopped_cond, &group->lock, NULL); + unlock(&group->lock); +} + +void dump_maps(void) { + extern void proc_maps_dump(struct task *task, struct proc_data *buf); + struct proc_data buf = {}; + proc_maps_dump(current, &buf); + // Go a line at a time because /proc maps output can be very large. + char *orig_data = buf.data; + while (buf.size > 0) { + size_t chunk_size = buf.size; + if (chunk_size > 1024) + chunk_size = 1024; + printk("%.*s", chunk_size, buf.data); + buf.data += chunk_size; + buf.size -= chunk_size; + } + free(orig_data); +} + +void dump_mem(addr_t start, uint_t len) { + const int width = 8; + for (addr_t addr = start; addr < start + len; addr += sizeof(dword_t)) { + unsigned from_left = (addr - start) / sizeof(dword_t) % width; + if (from_left == 0) + printk("%012llx: ", (unsigned long long)addr); + dword_t word; + if (user_get(addr, word)) + break; + printk("%08x ", word); + if (from_left == width - 1) + printk("\n"); + } +} + +void dump_stack(int lines) { + printk("stack at %llx, base at %llx, ip at %llx\n", + (unsigned long long)current->cpu.sp, + (unsigned long long)current->cpu.regs[29], // x29 is frame pointer + (unsigned long long)current->cpu.pc); + dump_mem(current->cpu.sp, lines * sizeof(uint64_t) * 8); +} + +// === Fast Path Implementations === + +// Fast path for fstat64 (syscall 80) +// Bypasses generic_statat path normalization when fd is already validated realfs +static inline int fast_fstat64(struct cpu_state *cpu) { + fd_t fd_no = (fd_t)cpu->regs[0]; + addr_t statbuf_addr = (addr_t)cpu->regs[1]; + + // Quick validation: fd must be valid + struct fd *fd = f_get(fd_no); + if (fd == NULL) + return -1; // Fall back to slow path + + // Fast path condition: fd is realfs (not adhoc, not procfs, etc.) + if (fd->ops != &realfs_fdops) + return -1; // Fall back to slow path + + // Direct host fstat call (bypass generic layers) + struct stat real_stat; + if (fstat(fd->real_fd, &real_stat) < 0) + return errno_map(); + + // Convert to guest statbuf + struct statbuf fake_stat = {}; + fake_stat.dev = dev_fake_from_real(real_stat.st_dev); + fake_stat.inode = real_stat.st_ino; + fake_stat.mode = real_stat.st_mode; + fake_stat.nlink = real_stat.st_nlink; + fake_stat.uid = real_stat.st_uid; + fake_stat.gid = real_stat.st_gid; + fake_stat.rdev = dev_fake_from_real(real_stat.st_rdev); + fake_stat.size = real_stat.st_size; + fake_stat.blksize = real_stat.st_blksize; + fake_stat.blocks = real_stat.st_blocks; + fake_stat.atime = platform_stat_atime_sec(&real_stat); + fake_stat.mtime = platform_stat_mtime_sec(&real_stat); + fake_stat.ctime = platform_stat_ctime_sec(&real_stat); + fake_stat.atime_nsec = platform_stat_atime_nsec(&real_stat); + fake_stat.mtime_nsec = platform_stat_mtime_nsec(&real_stat); + fake_stat.ctime_nsec = platform_stat_ctime_nsec(&real_stat); + + // Convert to ARM64 stat structure + struct stat_arm64 arm64stat = {}; + arm64stat.dev = fake_stat.dev; + arm64stat.ino = fake_stat.inode; + arm64stat.mode = fake_stat.mode; + arm64stat.nlink = fake_stat.nlink; + arm64stat.uid = fake_stat.uid; + arm64stat.gid = fake_stat.gid; + arm64stat.rdev = fake_stat.rdev; + arm64stat.__pad1 = 0; + arm64stat.size = fake_stat.size; + arm64stat.blksize = fake_stat.blksize; + arm64stat.__pad2 = 0; + arm64stat.blocks = fake_stat.blocks; + arm64stat.atime_ = fake_stat.atime; + arm64stat.atime_nsec = fake_stat.atime_nsec; + arm64stat.mtime_ = fake_stat.mtime; + arm64stat.mtime_nsec = fake_stat.mtime_nsec; + arm64stat.ctime_ = fake_stat.ctime; + arm64stat.ctime_nsec = fake_stat.ctime_nsec; + arm64stat.__unused4 = 0; + arm64stat.__unused5 = 0; + + // Copy to user space + if (user_put(statbuf_addr, arm64stat)) + return _EFAULT; + + return 0; // Success +} + +static inline bool syscall_should_surface_eintr(void) { + if (current->group->doing_group_exit) + return true; + if (current->sighand != NULL) { + lock(¤t->sighand->lock); + bool pending = !!(current->pending & ~current->blocked); + unlock(¤t->sighand->lock); + if (pending) + return true; + } + return false; +} + +// Fast path for read (syscall 63) - small buffers only +static inline int fast_read(struct cpu_state *cpu) { + fd_t fd_no = (fd_t)cpu->regs[0]; + addr_t buf_addr = (addr_t)cpu->regs[1]; + dword_t size = (dword_t)cpu->regs[2]; + + // Fast path condition: small buffer (≤ 4KB) and realfs fd + if (size > 4096) + return -1; + + struct fd *fd = f_get(fd_no); + if (fd == NULL || fd->ops != &realfs_fdops) + return -1; + + // Direct host read. Retry spurious host EINTR, but surface guest signals + // (especially exit_group SIGKILL) so helper threads blocked in pipes can + // leave cleanly instead of being detached by the exit safety valve. + char buf[4096]; + ssize_t res; + do { + if (current->group->doing_group_exit) + return _EINTR; + res = read(fd->real_fd, buf, size); + } while (res < 0 && errno == EINTR && !syscall_should_surface_eintr()); + + if (res < 0) + return errno_map(); + + // Copy to guest memory + if (res > 0 && user_write(buf_addr, buf, res)) + return _EFAULT; + + return res; +} + +// Fast path for write (syscall 64) - small buffers only +static inline int fast_write(struct cpu_state *cpu) { + fd_t fd_no = (fd_t)cpu->regs[0]; + addr_t buf_addr = (addr_t)cpu->regs[1]; + dword_t size = (dword_t)cpu->regs[2]; + + // Fast path condition: small buffer (≤ 4KB) and realfs fd + if (size > 4096) + return -1; + + struct fd *fd = f_get(fd_no); + if (fd == NULL || fd->ops != &realfs_fdops) + return -1; + + // Copy from guest memory + char buf[4096]; + if (user_read(buf_addr, buf, size)) + return _EFAULT; + + // Direct host write (with EINTR retry) + ssize_t res; + do { + res = write(fd->real_fd, buf, size); + } while (res < 0 && errno == EINTR); + + if (res < 0) + return errno_map(); + + return res; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/calls.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/calls.h new file mode 100644 index 0000000000..0c8e48041f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/calls.h @@ -0,0 +1,330 @@ +#ifndef CALLS_H +#define CALLS_H + +#include "kernel/task.h" +#include "kernel/errno.h" +#include "fs/fd.h" +#include "fs/dev.h" +#include "kernel/fs.h" +#include "misc.h" + +#include "kernel/signal.h" +#include "fs/sock.h" +#include "kernel/time.h" +#include "kernel/resource.h" +#include "kernel/ptrace.h" + +void handle_interrupt(int interrupt); + +int must_check user_read(addr_t addr, void *buf, size_t count); +int must_check user_write(addr_t addr, const void *buf, size_t count); +int must_check user_read_task(struct task *task, addr_t addr, void *buf, size_t count); +int must_check user_write_task(struct task *task, addr_t addr, const void *buf, size_t count); +int must_check user_write_task_ptrace(struct task *task, addr_t addr, const void *buf, size_t count); +int must_check user_read_string(addr_t addr, char *buf, size_t max); +int must_check user_write_string(addr_t addr, const char *buf); +#define user_get(addr, var) user_read(addr, &(var), sizeof(var)) +#define user_put(addr, var) user_write(addr, &(var), sizeof(var)) +#define user_get_task(task, addr, var) user_read_task(task, addr, &(var), sizeof(var)) +#define user_put_task(task, addr, var) user_write_task(task, addr, &(var), sizeof(var)) + +// process lifecycle +dword_t sys_clone(dword_t flags, addr_t stack, addr_t ptid, addr_t tls, addr_t ctid); +dword_t sys_clone3(addr_t args, size_t size); +dword_t sys_fork(void); +dword_t sys_vfork(void); +dword_t sys_execve(addr_t file, addr_t argv, addr_t envp); +int do_execve(const char *file, size_t argc, const char *argv, const char *envp); +dword_t sys_exit(dword_t status); +noreturn void do_exit(int status); +noreturn void do_exit_group(int status); +dword_t sys_exit_group(dword_t status); +dword_t sys_wait4(pid_t_ pid, addr_t status_addr, dword_t options, addr_t rusage_addr); +dword_t sys_waitid(int_t idtype, pid_t_ id, addr_t info_addr, int_t options); +dword_t sys_waitpid(pid_t_ pid, addr_t status_addr, dword_t options); + +// memory management +addr_t sys_brk(addr_t new_brk); + +#define MMAP_SHARED 0x1 +#define MMAP_PRIVATE 0x2 +#define MMAP_FIXED 0x10 +#define MMAP_ANONYMOUS 0x20 +#define MMAP_NORESERVE 0x4000 +addr_t sys_mmap(addr_t args_addr); +addr_t sys_mmap2(addr_t addr, dword_t len, dword_t prot, dword_t flags, fd_t fd_no, dword_t offset); +addr_t sys_mmap64(addr_t addr, addr_t len, dword_t prot, dword_t flags, fd_t fd_no, qword_t offset); +int_t sys_munmap(addr_t addr, addr_t len); +int_t sys_mprotect(addr_t addr, addr_t len, int_t prot); +addr_t sys_mremap(addr_t addr, dword_t old_len, dword_t new_len, dword_t flags); +dword_t sys_madvise(addr_t addr, dword_t len, dword_t advice); +dword_t sys_mbind(addr_t addr, dword_t len, int_t mode, addr_t nodemask, dword_t maxnode, uint_t flags); +int_t sys_mlock(addr_t addr, dword_t len); +int_t sys_msync(addr_t addr, dword_t len, int_t flags); + +// ARM64-specific memory management syscalls +dword_t sys_fadvise64(fd_t f, uint64_t offset, uint64_t len, dword_t advice); +dword_t sys_mincore(addr_t addr, dword_t length, addr_t vec_addr); + +// file descriptor things +#define LOCK_SH_ 1 +#define LOCK_EX_ 2 +#define LOCK_NB_ 4 +#define LOCK_UN_ 8 +struct iovec_ { + addr_t base; + uint_t len; +}; + +// ARM64 uses 64-bit pointers and size_t in iovec +struct iovec64_ { + uint64_t base; + uint64_t len; +}; +dword_t sys_read(fd_t fd_no, addr_t buf_addr, dword_t size); +dword_t sys_readv(fd_t fd_no, addr_t iovec_addr, dword_t iovec_count); +dword_t sys_preadv(fd_t fd_no, addr_t iovec_addr, dword_t iovec_count, off_t_ off); +dword_t sys_preadv2(fd_t fd_no, addr_t iovec_addr, dword_t iovec_count, off_t_ off, dword_t flags); +dword_t sys_write(fd_t fd_no, addr_t buf_addr, dword_t size); +dword_t sys_writev(fd_t fd_no, addr_t iovec_addr, dword_t iovec_count); +dword_t sys_pwritev(fd_t fd_no, addr_t iovec_addr, dword_t iovec_count, off_t_ off); +dword_t sys_pwritev2(fd_t fd_no, addr_t iovec_addr, dword_t iovec_count, off_t_ off, dword_t flags); +dword_t sys__llseek(fd_t f, dword_t off_high, dword_t off_low, addr_t res_addr, dword_t whence); +dword_t sys_lseek(fd_t f, dword_t off, dword_t whence); +qword_t sys_lseek64(fd_t f, sqword_t off, dword_t whence); +dword_t sys_pread(fd_t f, addr_t buf_addr, dword_t buf_size, off_t_ off); +dword_t sys_pwrite(fd_t f, addr_t buf_addr, dword_t size, off_t_ off); +dword_t sys_ioctl(fd_t f, dword_t cmd, addr_t arg); +dword_t sys_fcntl(fd_t f, dword_t cmd, addr_t arg); +dword_t sys_fcntl32(fd_t fd, dword_t cmd, addr_t arg); +dword_t sys_dup(fd_t fd); +dword_t sys_dup2(fd_t fd, fd_t new_fd); +dword_t sys_dup3(fd_t f, fd_t new_f, int_t flags); +dword_t sys_close(fd_t fd); +dword_t sys_close_range(uint_t first, uint_t last, uint_t flags); +dword_t sys_fsync(fd_t f); +dword_t sys_flock(fd_t fd, dword_t operation); +int_t sys_pipe(addr_t pipe_addr); +int_t sys_pipe2(addr_t pipe_addr, int_t flags); +struct pollfd_ { + fd_t fd; + word_t events; + word_t revents; +}; +dword_t sys_poll(addr_t fds, dword_t nfds, int_t timeout); +dword_t sys_select(fd_t nfds, addr_t readfds_addr, addr_t writefds_addr, addr_t exceptfds_addr, addr_t timeout_addr); +dword_t sys_pselect(fd_t nfds, addr_t readfds_addr, addr_t writefds_addr, addr_t exceptfds_addr, addr_t timeout_addr, addr_t sigmask_addr); +dword_t sys_ppoll(addr_t fds, dword_t nfds, addr_t timeout_addr, addr_t sigmask_addr, dword_t sigsetsize); +fd_t sys_epoll_create(int_t flags); +fd_t sys_epoll_create0(void); +int_t sys_epoll_ctl(fd_t epoll, int_t op, fd_t fd, addr_t event_addr); +int_t sys_epoll_wait(fd_t epoll, addr_t events_addr, int_t max_events, int_t timeout); +int_t sys_epoll_pwait(fd_t epoll_f, addr_t events_addr, int_t max_events, int_t timeout, addr_t sigmask_addr, dword_t sigsetsize); + +int_t sys_eventfd2(uint_t initval, int_t flags); +int_t sys_pidfd_open(pid_t_ pid, uint_t flags); +void pidfd_notify_exit(pid_t_ pid); +int_t sys_eventfd(uint_t initval); + +fd_t sys_inotify_init1(int_t flags); +fd_t sys_inotify_init(void); +int_t sys_inotify_add_watch(fd_t fd, addr_t path_addr, uint_t mask); +int_t sys_inotify_rm_watch(fd_t fd, int_t wd); + +// file management +fd_t sys_open(addr_t path_addr, dword_t flags, mode_t_ mode); +fd_t sys_openat(fd_t at, addr_t path_addr, dword_t flags, mode_t_ mode); +fd_t sys_openat2(fd_t at, addr_t path_addr, addr_t how_addr, size_t size); +dword_t sys_close(fd_t fd); +dword_t sys_link(addr_t src_addr, addr_t dst_addr); +dword_t sys_linkat(fd_t src_at_f, addr_t src_addr, fd_t dst_at_f, addr_t dst_addr); +dword_t sys_unlink(addr_t path_addr); +dword_t sys_unlinkat(fd_t at_f, addr_t path_addr, int_t flags); +dword_t sys_rmdir(addr_t path_addr); +dword_t sys_rename(addr_t src_addr, addr_t dst_addr); +dword_t sys_renameat(fd_t src_at_f, addr_t src_addr, fd_t dst_at_f, addr_t dst_addr); +dword_t sys_renameat2(fd_t src_at_f, addr_t src_addr, fd_t dst_at_f, addr_t dst_addr, int_t flags); +dword_t sys_symlink(addr_t target_addr, addr_t link_addr); +dword_t sys_symlinkat(addr_t target_addr, fd_t at_f, addr_t link_addr); +dword_t sys_mknod(addr_t path_addr, mode_t_ mode, dev_t_ dev); +dword_t sys_mknodat(fd_t at_f, addr_t path_addr, mode_t_ mode, dev_t_ dev); +dword_t sys_access(addr_t path_addr, dword_t mode); +dword_t sys_faccessat(fd_t at_f, addr_t path, mode_t_ mode, dword_t flags); +dword_t sys_faccessat2(fd_t at_f, addr_t path, mode_t_ mode, dword_t flags); +dword_t sys_readlink(addr_t path, addr_t buf, dword_t bufsize); +dword_t sys_readlinkat(fd_t at_f, addr_t path, addr_t buf, dword_t bufsize); +int_t sys_getdents(fd_t f, addr_t dirents, dword_t count); +int_t sys_getdents64(fd_t f, addr_t dirents, dword_t count); +dword_t sys_stat64(addr_t path_addr, addr_t statbuf_addr); +dword_t sys_lstat64(addr_t path_addr, addr_t statbuf_addr); +dword_t sys_fstat64(fd_t fd_no, addr_t statbuf_addr); +dword_t sys_fstatat64(fd_t at, addr_t path_addr, addr_t statbuf_addr, dword_t flags); +dword_t sys_fchmod(fd_t f, dword_t mode); +dword_t sys_fchmodat(fd_t at_f, addr_t path_addr, dword_t mode); +dword_t sys_fchmodat2(fd_t at_f, addr_t path_addr, dword_t mode, dword_t flags); +dword_t sys_chmod(addr_t path_addr, dword_t mode); +dword_t sys_fchown32(fd_t f, dword_t owner, dword_t group); +dword_t sys_fchownat(fd_t at_f, addr_t path_addr, dword_t owner, dword_t group, int flags); +dword_t sys_chown32(addr_t path_addr, uid_t_ owner, uid_t_ group); +dword_t sys_lchown(addr_t path_addr, uid_t_ owner, uid_t_ group); +dword_t sys_truncate64(addr_t path_addr, off_t_ size); +dword_t sys_ftruncate64(fd_t f, off_t_ size); +dword_t sys_fallocate(fd_t f, dword_t mode, off_t_ offset, off_t_ len); +dword_t sys_mkdir(addr_t path_addr, mode_t_ mode); +dword_t sys_mkdirat(fd_t at_f, addr_t path_addr, mode_t_ mode); +dword_t sys_utimensat(fd_t at_f, addr_t path_addr, addr_t times_addr, dword_t flags); +dword_t sys_utimes(addr_t path_addr, addr_t times_addr); +dword_t sys_utime(addr_t path_addr, addr_t times_addr); +dword_t sys_times( addr_t tbuf); +dword_t sys_umask(dword_t mask); + +dword_t sys_sendfile(fd_t out_fd, fd_t in_fd, addr_t offset_addr, dword_t count); +dword_t sys_sendfile64(fd_t out_fd, fd_t in_fd, addr_t offset_addr, dword_t count); +dword_t sys_splice(fd_t in_fd, addr_t in_off_addr, fd_t out_fd, addr_t out_off_addr, dword_t count, dword_t flags); +dword_t sys_copy_file_range(fd_t in_fd, addr_t in_off, fd_t out_fd, addr_t out_off, dword_t len, uint_t flags); + +int_t sys_memfd_create(addr_t name_addr, uint_t flags); +ssize_t sys_process_vm_readv(pid_t_ pid, addr_t local_iov_addr, dword_t local_iovcnt, addr_t remote_iov_addr, dword_t remote_iovcnt, dword_t flags); +ssize_t sys_process_vm_writev(pid_t_ pid, addr_t local_iov_addr, dword_t local_iovcnt, addr_t remote_iov_addr, dword_t remote_iovcnt, dword_t flags); + +int_t sys_msgget(int_t key, int_t msgflg); +int_t sys_msgctl(int_t msqid, int_t cmd, addr_t buf_addr); +int_t sys_msgsnd(int_t msqid, addr_t msgp, size_t msgsz, int_t msgflg); +ssize_t sys_msgrcv(int_t msqid, addr_t msgp, size_t msgsz, int64_t msgtyp, int_t msgflg); +int_t sys_semget(int_t key, int_t nsems, int_t semflg); +int_t sys_semctl(int_t semid, int_t semnum, int_t cmd, addr_t arg); +int_t sys_semtimedop(int_t semid, addr_t sops_addr, size_t nsops, addr_t timeout_addr); +int_t sys_semop(int_t semid, addr_t sops_addr, size_t nsops); + +int_t sys_mq_open(addr_t name_addr, int_t oflag, mode_t_ mode, addr_t attr_addr); +int_t sys_mq_unlink(addr_t name_addr); +int_t sys_mq_timedsend(fd_t mqdes, addr_t msg_ptr, size_t msg_len, uint_t msg_prio, addr_t abs_timeout_addr); +ssize_t sys_mq_timedreceive(fd_t mqdes, addr_t msg_ptr, size_t msg_len, addr_t msg_prio_addr, addr_t abs_timeout_addr); +int_t sys_mq_notify(fd_t mqdes, addr_t notification_addr); +int_t sys_mq_getsetattr(fd_t mqdes, addr_t newattr_addr, addr_t oldattr_addr); + +int_t sys_shmget(int_t key, size_t size, int_t shmflg); +int_t sys_shmctl(int_t shmid, int_t cmd, addr_t buf_addr); +addr_t sys_shmat(int_t shmid, addr_t shmaddr, int_t shmflg); +int_t sys_shmdt(addr_t shmaddr); + +dword_t sys_statfs(addr_t path_addr, addr_t buf_addr); +dword_t sys_statfs64(addr_t path_addr, dword_t buf_size, addr_t buf_addr); +dword_t sys_fstatfs(fd_t f, addr_t buf_addr); +dword_t sys_fstatfs64(fd_t f, addr_t buf_addr); +dword_t sys_statfs_arm64(addr_t path_addr, addr_t buf_addr); +dword_t sys_fstatfs_arm64(fd_t f, addr_t buf_addr); +dword_t sys_statx(fd_t at_f, addr_t path_addr, int_t flags, uint_t mask, addr_t statx_addr); + +#define MS_READONLY_ (1 << 0) +#define MS_NOSUID_ (1 << 1) +#define MS_NODEV_ (1 << 2) +#define MS_NOEXEC_ (1 << 3) +#define MS_SILENT_ (1 << 15) +dword_t sys_mount(addr_t source_addr, addr_t target_addr, addr_t type_addr, dword_t flags, addr_t data_addr); +dword_t sys_umount2(addr_t target_addr, dword_t flags); + +dword_t sys_xattr_stub(addr_t path_addr, addr_t name_addr, addr_t value_addr, dword_t size, dword_t flags); + +// process information +pid_t_ sys_getpid(void); +pid_t_ sys_gettid(void); +pid_t_ sys_getppid(void); +pid_t_ sys_getpgid(pid_t_ pid); +dword_t sys_setpgid(pid_t_ pid, pid_t_ pgid); +pid_t_ sys_getpgrp(void); +dword_t sys_setpgrp(void); +uid_t_ sys_getuid32(void); +uid_t_ sys_getuid(void); +int_t sys_setuid(uid_t uid); +uid_t_ sys_geteuid32(void); +uid_t_ sys_geteuid(void); +int_t sys_setgid(uid_t gid); +uid_t_ sys_getgid32(void); +uid_t_ sys_getgid(void); +uid_t_ sys_getegid32(void); +uid_t_ sys_getegid(void); +dword_t sys_setresuid(uid_t_ ruid, uid_t_ euid, uid_t_ suid); +dword_t sys_setresgid(uid_t_ rgid, uid_t_ egid, uid_t_ sgid); +int_t sys_setreuid(uid_t_ ruid, uid_t_ euid); +int_t sys_setregid(uid_t_ rgid, uid_t_ egid); +int_t sys_getresuid(addr_t ruid_addr, addr_t euid_addr, addr_t suid_addr); +int_t sys_getresgid(addr_t rgid_addr, addr_t egid_addr, addr_t sgid_addr); +int_t sys_getgroups(dword_t size, addr_t list); +int_t sys_setgroups(dword_t size, addr_t list); +int_t sys_capget(addr_t header_addr, addr_t data_addr); +int_t sys_capset(addr_t header_addr, addr_t data_addr); +dword_t sys_getcwd(addr_t buf_addr, dword_t size); +dword_t sys_chdir(addr_t path_addr); +dword_t sys_chroot(addr_t path_addr); +dword_t sys_fchdir(fd_t f); +int_t sys_personality(dword_t pers); +int task_set_thread_area(struct task *task, addr_t u_info); +int sys_set_thread_area(addr_t u_info); +int sys_set_tid_address(addr_t blahblahblah); +dword_t sys_setsid(void); +dword_t sys_getsid(void); + +int_t sys_sched_yield(void); +int_t sys_prctl(dword_t option, addr_t arg2, addr_t arg3, addr_t arg4, addr_t arg5); +int_t sys_arch_prctl(int_t code, addr_t addr); +int_t sys_membarrier(int_t cmd, dword_t flags, int_t cpu_id); +int_t sys_rseq(addr_t rseq_addr, dword_t rseq_len, int_t flags, dword_t sig); +int_t sys_reboot(int_t magic, int_t magic2, int_t cmd); + +// system information +#define UNAME_LENGTH 65 +struct uname { + char system[UNAME_LENGTH]; // Linux + char hostname[UNAME_LENGTH]; // my-compotar + char release[UNAME_LENGTH]; // 1.2.3-linuxkit + char version[UNAME_LENGTH]; // Block Emulation + char arch[UNAME_LENGTH]; // aarch64 + char domain[UNAME_LENGTH]; // lol +}; +void do_uname(struct uname *uts); +dword_t sys_uname(addr_t uts_addr); +dword_t sys_sethostname(addr_t hostname_addr, dword_t hostname_len); + +// ARM64 sysinfo struct: uses 64-bit long types (112 bytes total with padding) +struct sys_info { + uint64_t uptime; + uint64_t loads[3]; + uint64_t totalram; + uint64_t freeram; + uint64_t sharedram; + uint64_t bufferram; + uint64_t totalswap; + uint64_t freeswap; + uint16_t procs; + uint16_t _pad1; // padding + uint32_t _pad2; // padding + uint64_t totalhigh; + uint64_t freehigh; + uint32_t mem_unit; + uint32_t _pad3; // padding for alignment +}; +dword_t sys_sysinfo(addr_t info_addr); + +// futexes +dword_t sys_futex(addr_t uaddr, dword_t op, dword_t val, addr_t timeout_or_val2, addr_t uaddr2, dword_t val3); +int_t sys_set_robust_list(addr_t robust_list, dword_t len); +int_t sys_get_robust_list(pid_t_ pid, addr_t robust_list_ptr, addr_t len_ptr); + +// misc +dword_t sys_getrandom(addr_t buf_addr, dword_t len, dword_t flags); +int_t sys_syslog(int_t type, addr_t buf_addr, int_t len); +int_t sys_ipc(uint_t call, int_t first, int_t second, int_t third, addr_t ptr, int_t fifth); + +// ARM64 syscalls pass 64-bit register values; functions taking dword_t +// will implicitly truncate, while those taking off_t_/qword_t get full values. +// Returns int64_t so addr_t-returning syscalls (mmap, brk) can pass 48-bit values. +typedef int64_t (*syscall_t)(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, uint64_t); + +// Stub for unimplemented syscalls +dword_t syscall_stub(void); +dword_t syscall_silent_stub(void); +dword_t syscall_success_stub(void); + + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/elf.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/elf.h new file mode 100644 index 0000000000..729731ed80 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/elf.h @@ -0,0 +1,164 @@ +#ifndef ELF_H +#define ELF_H + +#include "misc.h" + +#define ELF_MAGIC "\177ELF" +#define ELF_64BIT 2 +#define ELF_LITTLEENDIAN 1 +#define ELF_BIGENDIAN 2 +#define ELF_LINUX_ABI 3 +#define ELF_EXECUTABLE 2 +#define ELF_DYNAMIC 3 + +// Machine types +#define ELF_AARCH64 183 // EM_AARCH64 +#define ELF_MACHINE ELF_AARCH64 +#define ELF_CLASS ELF_64BIT + +// 64-bit ELF header (for ARM64) +struct elf_header64 { + uint32_t magic; + byte_t bitness; + byte_t endian; + byte_t elfversion1; + byte_t abi; + byte_t abi_version; + byte_t padding[7]; + uint16_t type; + uint16_t machine; + uint32_t elfversion2; + uint64_t entry_point; + uint64_t prghead_off; + uint64_t secthead_off; + uint32_t flags; + uint16_t header_size; + uint16_t phent_size; + uint16_t phent_count; + uint16_t shent_size; + uint16_t shent_count; + uint16_t sectname_index; +}; + +typedef struct elf_header64 elf_header; + +#define PT_NULL 0 +#define PT_LOAD 1 +#define PT_DYNAMIC 2 +#define PT_INTERP 3 +#define PT_NOTE 4 +#define PT_SHLIB 5 +#define PT_PHDR 6 +#define PT_TLS 7 +#define PT_NUM 8 + +// 64-bit program header (for ARM64) +// Note: field order is different from 32-bit! +struct prg_header64 { + uint32_t type; + uint32_t flags; // flags moved here in 64-bit + uint64_t offset; + uint64_t vaddr; + uint64_t paddr; + uint64_t filesize; + uint64_t memsize; + uint64_t alignment; +}; + +#define PH_R (1 << 2) +#define PH_W (1 << 1) +#define PH_X (1 << 0) + +struct aux_ent { + uint64_t type; + uint64_t value; +}; +#define ELF_PTR_SIZE 8 + +#define AX_PHDR 3 +#define AX_PHENT 4 +#define AX_PHNUM 5 +#define AX_PAGESZ 6 +#define AX_BASE 7 +#define AX_FLAGS 8 +#define AX_ENTRY 9 +#define AX_UID 11 +#define AX_EUID 12 +#define AX_GID 13 +#define AX_EGID 14 +#define AX_PLATFORM 15 +#define AX_HWCAP 16 +#define AX_CLKTCK 17 +#define AX_SECURE 23 +#define AX_RANDOM 25 +#define AX_HWCAP2 26 +#define AX_EXECFN 31 +#define AX_SYSINFO 32 +#define AX_SYSINFO_EHDR 33 + +// 64-bit dynamic entry (for ARM64) +struct dyn_ent64 { + uint64_t tag; + uint64_t val; +}; + +#define DT_NULL 0 +#define DT_NEEDED 1 +#define DT_PLTRELSZ 2 +#define DT_PLTGOT 3 +#define DT_HASH 4 +#define DT_STRTAB 5 +#define DT_SYMTAB 6 +#define DT_RELA 7 +#define DT_RELASZ 8 +#define DT_RELAENT 9 +#define DT_STRSZ 10 +#define DT_SYMENT 11 +#define DT_JMPREL 23 +#define DT_PLTREL 20 + +// 64-bit ELF symbol (for ARM64) +struct elf_sym64 { + uint32_t name; // Offset in string table + byte_t info; // Type and binding + byte_t other; // Visibility + uint16_t shndx; // Section index + uint64_t value; // Symbol value + uint64_t size; // Symbol size +}; + +// ARM64 relocation entry (Rela format with addend) +struct elf_rela64 { + uint64_t offset; // Location to apply relocation + uint64_t info; // Relocation type and symbol index + int64_t addend; // Addend value +}; + +// ARM64 relocation types +#define R_AARCH64_NONE 0 +#define R_AARCH64_ABS64 257 +#define R_AARCH64_GLOB_DAT 1025 +#define R_AARCH64_JUMP_SLOT 1026 +#define R_AARCH64_RELATIVE 1027 + +// Macros for extracting relocation info (ARM64) +#define ELF64_R_SYM(i) ((uint32_t)((i) >> 32)) +#define ELF64_R_TYPE(i) ((uint32_t)((i) & 0xffffffff)) + +// Symbol binding values +#define STB_LOCAL 0 +#define STB_GLOBAL 1 +#define STB_WEAK 2 + +// Symbol type values +#define STT_NOTYPE 0 +#define STT_OBJECT 1 +#define STT_FUNC 2 +#define STT_SECTION 3 +#define STT_FILE 4 + +// Macros for symbol info +#define ELF_ST_BIND(i) ((i) >> 4) +#define ELF_ST_TYPE(i) ((i) & 0xf) + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/epoll.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/epoll.c new file mode 100644 index 0000000000..fa11bc0108 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/epoll.c @@ -0,0 +1,150 @@ +#include <sys/stat.h> +#include "kernel/calls.h" +#include "fs/poll.h" + +static struct fd_ops epoll_ops; + +fd_t sys_epoll_create(int_t flags) { + STRACE("epoll_create(%#x)", flags); + if (flags & ~(O_CLOEXEC_)) + return _EINVAL; + + struct fd *fd = adhoc_fd_create(&epoll_ops); + if (fd == NULL) + return _ENOMEM; + struct poll *poll = poll_create(); + if (IS_ERR(poll)) + return PTR_ERR(poll); + fd->epollfd.poll = poll; + return f_install(fd, flags); +} +fd_t sys_epoll_create0() { + return sys_epoll_create(0); +} + +struct epoll_event_ { + uint32_t events; +#ifdef GUEST_ARM64 + uint32_t __pad; +#endif + uint64_t data; +} +#ifndef GUEST_ARM64 +__attribute__((packed)) +#endif +; + +#define EPOLL_CTL_ADD_ 1 +#define EPOLL_CTL_DEL_ 2 +#define EPOLL_CTL_MOD_ 3 +#define EPOLLET_ (1 << 31) +#define EPOLLONESHOT_ (1 << 30) + +int_t sys_epoll_ctl(fd_t epoll_f, int_t op, fd_t f, addr_t event_addr) { + STRACE("epoll_ctl(%d, %d, %d, %#x)", epoll_f, op, f, event_addr); + struct fd *epoll = f_get(epoll_f); + if (epoll == NULL) + return _EBADF; + if (epoll->ops != &epoll_ops) + return _EINVAL; + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + + // Regular files (and directories) are not pollable: they are always + // "ready", so Linux rejects adding them to an epoll set with EPERM. iSH + // used to accept them, which makes bun's fs.WriteStream take its polling + // path (instead of the EPERM fallback) and then throw EEXIST on the second + // registration of the same fd. Match Linux and reject with EPERM. + if (op == EPOLL_CTL_ADD_ && (S_ISREG(fd->type) || S_ISDIR(fd->type))) + return _EPERM; + + if (op == EPOLL_CTL_DEL_) + return poll_del_fd(epoll->epollfd.poll, fd, f); + + struct epoll_event_ event; + if (user_get(event_addr, event)) + return _EFAULT; + STRACE(" {events: %#x, data: %#x}", event.events, event.data); + + if (op == EPOLL_CTL_ADD_) { + if (poll_has_fd(epoll->epollfd.poll, fd, f)) + return _EEXIST; + return poll_add_fd(epoll->epollfd.poll, fd, f, event.events, (union poll_fd_info) event.data); + } else { + return poll_mod_fd(epoll->epollfd.poll, fd, f, event.events, (union poll_fd_info) event.data); + } +} + +struct epoll_context { + struct epoll_event_ *events; + int n; + int max_events; +}; + +static int epoll_callback(void *context, int types, union poll_fd_info info) { + struct epoll_context *c = context; + if (c->n >= c->max_events) + return 0; + c->events[c->n++] = (struct epoll_event_) {.events = types, .data = info.num}; + return 1; +} + +int_t sys_epoll_wait(fd_t epoll_f, addr_t events_addr, int_t max_events, int_t timeout) { + STRACE("epoll_wait(%d, %#x, %d, %d)", epoll_f, events_addr, max_events, timeout); + struct fd *epoll = f_get(epoll_f); + if (epoll == NULL) + return _EBADF; + if (epoll->ops != &epoll_ops) + return _EINVAL; + + struct timespec timeout_ts; + if (timeout >= 0) { + timeout_ts.tv_sec = timeout / 1000; + timeout_ts.tv_nsec = (timeout % 1000) * 1000000; + } + if (max_events <= 0) + return _EINVAL; + struct epoll_event_ events[max_events]; + + struct epoll_context context = {.events = events, .n = 0, .max_events = max_events}; + STRACE("...\n"); + int res = poll_wait(epoll->epollfd.poll, epoll_callback, &context, timeout < 0 ? NULL : &timeout_ts); + STRACE("%d end epoll_wait", current->pid); + if (res >= 0) { + for (int i = 0; i < res; i++) { + STRACE(" {events: %#x, data: %#x}", events[i].events, events[i].data); + } + if (user_write(events_addr, events, sizeof(struct epoll_event_) * res)) + return _EFAULT; + } else if (res != _EINTR) { + // Host-level errors from kqueue/kevent should not propagate to the guest + // as unexpected errnos. libuv asserts that epoll_pwait only fails with + // EINTR; anything else (EBADF from kqueue race, etc.) crashes the guest. + // Convert to EINTR so the guest's event loop retries gracefully. + printk("epoll_wait: converting error %d to EINTR (pid=%d)\n", res, current->pid); + res = _EINTR; + } + return res; +} + +int_t sys_epoll_pwait(fd_t epoll_f, addr_t events_addr, int_t max_events, int_t timeout, addr_t sigmask_addr, dword_t sigsetsize) { + sigset_t_ mask; + if (sigmask_addr != 0) { + int err = user_get_sigset(sigmask_addr, sigsetsize, &mask); + if (err) + return err; + sigmask_set_temp(mask); + } + + return sys_epoll_wait(epoll_f, events_addr, max_events, timeout); +} + +static int epoll_close(struct fd *fd) { + poll_destroy(fd->epollfd.poll); + return 0; +} + +static struct fd_ops epoll_ops = { + .close = epoll_close, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/errno.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/errno.c new file mode 100644 index 0000000000..84bacc7286 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/errno.c @@ -0,0 +1,105 @@ +#include "debug.h" +#include "kernel/task.h" +#include "kernel/signal.h" +#include "kernel/errno.h" + +int err_map(int err) { +#define ERRCASE(err) \ + case err: return _##err; + switch (err) { + ERRCASE(EPERM) + ERRCASE(ENOENT) + ERRCASE(ESRCH) + ERRCASE(EINTR) + ERRCASE(EIO) + ERRCASE(ENXIO) + ERRCASE(E2BIG) + ERRCASE(ENOEXEC) + ERRCASE(EBADF) + ERRCASE(ECHILD) + ERRCASE(EAGAIN) + ERRCASE(ENOMEM) + ERRCASE(EACCES) + ERRCASE(EFAULT) + ERRCASE(ENOTBLK) + ERRCASE(EBUSY) + ERRCASE(EEXIST) + ERRCASE(EXDEV) + ERRCASE(ENODEV) + ERRCASE(ENOTDIR) + ERRCASE(EISDIR) + ERRCASE(EINVAL) + ERRCASE(ENFILE) + ERRCASE(EMFILE) + ERRCASE(ENOTTY) + ERRCASE(ETXTBSY) + ERRCASE(EFBIG) + ERRCASE(ENOSPC) + ERRCASE(ESPIPE) + ERRCASE(EROFS) + ERRCASE(EMLINK) + ERRCASE(EPIPE) + ERRCASE(EDOM) + ERRCASE(ERANGE) + ERRCASE(EDEADLK) + ERRCASE(ENAMETOOLONG) + ERRCASE(ENOLCK) + ERRCASE(ENOSYS) + ERRCASE(ENOTEMPTY) + ERRCASE(ELOOP) + ERRCASE(ENOSTR) + ERRCASE(ENODATA) + ERRCASE(ETIME) + ERRCASE(ENOSR) + ERRCASE(EREMOTE) + ERRCASE(ENOLINK) + ERRCASE(EPROTO) + ERRCASE(EMULTIHOP) + ERRCASE(EBADMSG) + ERRCASE(EOVERFLOW) + ERRCASE(EILSEQ) + ERRCASE(EUSERS) + ERRCASE(ENOTSOCK) + ERRCASE(EDESTADDRREQ) + ERRCASE(EMSGSIZE) + ERRCASE(EPROTOTYPE) + ERRCASE(ENOPROTOOPT) + ERRCASE(EPROTONOSUPPORT) + ERRCASE(ESOCKTNOSUPPORT) + ERRCASE(EOPNOTSUPP) +#if EOPNOTSUPP != ENOTSUP + ERRCASE(ENOTSUP) +#endif + ERRCASE(EPFNOSUPPORT) + ERRCASE(EAFNOSUPPORT) + ERRCASE(EADDRINUSE) + ERRCASE(EADDRNOTAVAIL) + ERRCASE(ENETDOWN) + ERRCASE(ENETUNREACH) + ERRCASE(ENETRESET) + ERRCASE(ECONNABORTED) + ERRCASE(ECONNRESET) + ERRCASE(ENOBUFS) + ERRCASE(EISCONN) + ERRCASE(ENOTCONN) + ERRCASE(ESHUTDOWN) + ERRCASE(ETOOMANYREFS) + ERRCASE(ETIMEDOUT) + ERRCASE(ECONNREFUSED) + ERRCASE(EHOSTDOWN) + ERRCASE(EHOSTUNREACH) + ERRCASE(EALREADY) + ERRCASE(EINPROGRESS) + ERRCASE(ESTALE) + ERRCASE(EDQUOT) + } +#undef ERRCASE + printk("unknown error %d\n", err); + return -(err | 0x1000); +} + +int errno_map() { + if (errno == EPIPE && current != NULL) + send_signal(current, SIGPIPE_, SIGINFO_NIL); + return err_map(errno); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/errno.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/errno.h new file mode 100644 index 0000000000..930eadc7b1 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/errno.h @@ -0,0 +1,120 @@ +#ifndef SYS_ERRNO_H +#define SYS_ERRNO_H + +#include <errno.h> + +// stolen from asm-generic/errno-base.h + +#define _EPERM -1 /* Operation not permitted */ +#define _ENOENT -2 /* No such file or directory */ +#define _ESRCH -3 /* No such process */ +#define _EINTR -4 /* Interrupted system call */ +#define _EIO -5 /* I/O error */ +#define _ENXIO -6 /* No such device or address */ +#define _E2BIG -7 /* That's what she said */ +#define _ENOEXEC -8 /* Exec format error */ +#define _EBADF -9 /* Bad file number */ +#define _ECHILD -10 /* No child processes */ +#define _EAGAIN -11 /* Try again */ +#define _ENOMEM -12 /* Out of memory */ +#define _EACCES -13 /* Permission denied */ +#define _EFAULT -14 /* Bad address */ +#define _ENOTBLK -15 /* Block device required */ +#define _EBUSY -16 /* Device or resource busy */ +#define _EEXIST -17 /* File exists */ +#define _EXDEV -18 /* Cross-device link */ +#define _ENODEV -19 /* No such device */ +#define _ENOTDIR -20 /* Not a directory */ +#define _EISDIR -21 /* Is a directory */ +#define _EINVAL -22 /* Invalid argument */ +#define _ENFILE -23 /* File table overflow */ +#define _EMFILE -24 /* Too many open files */ +#define _ENOTTY -25 /* Not a typewriter */ +#define _ETXTBSY -26 /* Text file busy */ +#define _EFBIG -27 /* File too large */ +#define _ENOSPC -28 /* No space left on device */ +#define _ESPIPE -29 /* Illegal seek */ +#define _EROFS -30 /* Read-only file system */ +#define _EMLINK -31 /* Too many links */ +#define _EPIPE -32 /* Broken pipe */ +#define _EDOM -33 /* Math argument out of domain of func */ +#define _ERANGE -34 /* Math result not representable */ +#define _EDEADLK -35 /* Resource deadlock would occur */ +#define _ENAMETOOLONG -36 /* File name too long */ +#define _ENOLCK -37 /* No record locks available */ +#define _ENOSYS -38 /* Invalid system call number */ +#define _ENOTEMPTY -39 /* Directory not empty */ +#define _ELOOP -40 /* Too many symbolic links encountered */ + +#define _EBFONT -59 /* Bad font file format */ +#define _ENOSTR -60 /* Device not a stream */ +#define _ENODATA -61 /* No data available */ +#define _ETIME -62 /* Timer expired */ +#define _ENOSR -63 /* Out of streams resources */ +#define _ENONET -64 /* Machine is not on the network */ +#define _ENOPKG -65 /* Package not installed */ +#define _EREMOTE -66 /* Object is remote */ +#define _ENOLINK -67 /* Link has been severed */ +#define _EADV -68 /* Advertise error */ +#define _ESRMNT -69 /* Srmount error */ +#define _ECOMM -70 /* Communication error on send */ +#define _EPROTO -71 /* Protocol error */ +#define _EMULTIHOP -72 /* Multihop attempted */ +#define _EDOTDOT -73 /* RFS specific error */ +#define _EBADMSG -74 /* Not a data message */ +#define _EOVERFLOW -75 /* Value too large for defined data type */ +#define _ENOTUNIQ -76 /* Name not unique on network */ +#define _EBADFD -77 /* File descriptor in bad state */ +#define _EREMCHG -78 /* Remote address changed */ +#define _ELIBACC -79 /* Can not access a needed shared library */ +#define _ELIBBAD -80 /* Accessing a corrupted shared library */ +#define _ELIBSCN -81 /* .lib section in a.out corrupted */ +#define _ELIBMAX -82 /* Attempting to link in too many shared libraries */ +#define _ELIBEXEC -83 /* Cannot exec a shared library directly */ +#define _EILSEQ -84 /* Illegal byte sequence */ +#define _ERESTART -85 /* Interrupted system call should be restarted */ +#define _ESTRPIPE -86 /* Streams pipe error */ +#define _EUSERS -87 /* Too many users */ +#define _ENOTSOCK -88 /* Socket operation on non-socket */ +#define _EDESTADDRREQ -89 /* Destination address required */ +#define _EMSGSIZE -90 /* Message too long */ +#define _EPROTOTYPE -91 /* Protocol wrong type for socket */ +#define _ENOPROTOOPT -92 /* Protocol not available */ +#define _EPROTONOSUPPORT -93 /* Protocol not supported */ +#define _ESOCKTNOSUPPORT -94 /* Socket type not supported */ +#define _EOPNOTSUPP -95 /* Operation not supported on transport endpoint */ +#define _ENOTSUP _EOPNOTSUPP +#define _EPFNOSUPPORT -96 /* Protocol family not supported */ +#define _EAFNOSUPPORT -97 /* Address family not supported by protocol */ +#define _EADDRINUSE -98 /* Address already in use */ +#define _EADDRNOTAVAIL -99 /* Cannot assign requested address */ +#define _ENETDOWN -100 /* Network is down */ +#define _ENETUNREACH -101 /* Network is unreachable */ +#define _ENETRESET -102 /* Network dropped connection because of reset */ +#define _ECONNABORTED -103 /* Software caused connection abort */ +#define _ECONNRESET -104 /* Connection reset by peer */ +#define _ENOBUFS -105 /* No buffer space available */ +#define _EISCONN -106 /* Transport endpoint is already connected */ +#define _ENOTCONN -107 /* Transport endpoint is not connected */ +#define _ESHUTDOWN -108 /* Cannot send after transport endpoint shutdown */ +#define _ETOOMANYREFS -109 /* Too many references: cannot splice */ +#define _ETIMEDOUT -110 /* Connection timed out */ +#define _ECONNREFUSED -111 /* Connection refused */ +#define _EHOSTDOWN -112 /* Host is down */ +#define _EHOSTUNREACH -113 /* No route to host */ +#define _EALREADY -114 /* Operation already in progress */ +#define _EINPROGRESS -115 /* Operation now in progress */ +#define _ESTALE -116 /* Stale file handle */ +#define _EUCLEAN -117 /* Structure needs cleaning */ +#define _ENOTNAM -118 /* Not a XENIX named type file */ +#define _ENAVAIL -119 /* No XENIX semaphores available */ +#define _EISNAM -120 /* Is a named type file */ +#define _EREMOTEIO -121 /* Remote I/O error */ +#define _EDQUOT -122 /* Quota exceeded */ +#define _ECANCELED -125 /* Operation Canceled */ + + +int err_map(int err); +int errno_map(void); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/eventfd.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/eventfd.c new file mode 100644 index 0000000000..f4ba28579d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/eventfd.c @@ -0,0 +1,87 @@ +#include "kernel/calls.h" +#include "kernel/fs.h" +#include "fs/poll.h" + +static struct fd_ops eventfd_ops; + +int_t sys_eventfd2(uint_t initval, int_t flags) { + STRACE("eventfd(%d, %#x)", initval, flags); + if (flags & ~(O_CLOEXEC_|O_NONBLOCK_)) + return _EINVAL; + + struct fd *fd = adhoc_fd_create(&eventfd_ops); + if (fd == NULL) + return _ENOMEM; + fd->eventfd.val = initval; + return f_install(fd, flags); +} +int_t sys_eventfd(uint_t initval) { + return sys_eventfd2(initval, 0); +} + +static ssize_t eventfd_read(struct fd *fd, void *buf, size_t bufsize) { + if (bufsize < sizeof(uint64_t)) + return _EINVAL; + + lock(&fd->lock); + while (fd->eventfd.val == 0) { + if (fd->flags & O_NONBLOCK_) { + unlock(&fd->lock); + return _EAGAIN; + } + if (wait_for(&fd->cond, &fd->lock, NULL)) { + unlock(&fd->lock); + return _EINTR; + } + } + + *(uint64_t *) buf = fd->eventfd.val; + fd->eventfd.val = 0; + notify(&fd->cond); + unlock(&fd->lock); + poll_wakeup(fd, POLL_WRITE); + return sizeof(uint64_t); +} + +static ssize_t eventfd_write(struct fd *fd, const void *buf, size_t bufsize) { + if (bufsize < sizeof(uint64_t)) + return _EINVAL; + uint64_t increment = *(uint64_t *) buf; + if (increment == UINT64_MAX) + return _EINVAL; + + lock(&fd->lock); + while (fd->eventfd.val >= UINT64_MAX - increment) { + if (fd->flags & O_NONBLOCK_) { + unlock(&fd->lock); + return _EAGAIN; + } + if (wait_for(&fd->cond, &fd->lock, NULL)) { + unlock(&fd->lock); + return _EINTR; + } + } + + fd->eventfd.val += increment; + notify(&fd->cond); + unlock(&fd->lock); + poll_wakeup(fd, POLL_READ); + return sizeof(uint64_t); +} + +static int eventfd_poll(struct fd *fd) { + lock(&fd->lock); + int types = 0; + if (fd->eventfd.val > 0) + types |= POLL_READ; + if (fd->eventfd.val < UINT64_MAX - 1) + types |= POLL_WRITE; + unlock(&fd->lock); + return types; +} + +static struct fd_ops eventfd_ops = { + .read = eventfd_read, + .write = eventfd_write, + .poll = eventfd_poll, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/exec.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/exec.c new file mode 100644 index 0000000000..4d9de463ff --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/exec.c @@ -0,0 +1,964 @@ +#include "kernel/signal.h" +#include "task.h" +#define _GNU_SOURCE +#include <unistd.h> +#include <fcntl.h> +#include <pthread.h> + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "misc.h" +#include "kernel/calls.h" +#include "kernel/random.h" +#include "kernel/errno.h" +#include "fs/fd.h" +#include "kernel/elf.h" +#include "kernel/vdso.h" +#include "kernel/mm.h" +#include "kernel/native_offload.h" + +#define ARGV_MAX 32 * PAGE_SIZE + +typedef struct elf_header64 exec_elf_header; +typedef struct prg_header64 exec_prg_header; + +struct exec_args { + // number of arguments + size_t count; + // series of count null-terminated strings, plus an extra null for good measure + const char *args; +}; + +static inline addr_t align_stack(addr_t sp); +static inline ssize_t user_strlen(addr_t p); +static inline int user_memset(addr_t start, byte_t val, dword_t len); +static inline addr_t copy_string(addr_t sp, const char *string); +static inline addr_t args_copy(addr_t sp, struct exec_args args); +static size_t args_size(struct exec_args args); + +static int read_header(struct fd *fd, exec_elf_header *header) { + int err; + if (fd->ops->lseek(fd, 0, SEEK_SET)) + return _EIO; + if ((err = fd->ops->read(fd, header, sizeof(*header))) != sizeof(*header)) { + if (err < 0) + return _EIO; + return _ENOEXEC; + } + if (memcmp(&header->magic, ELF_MAGIC, sizeof(header->magic)) != 0 + || (header->type != ELF_EXECUTABLE && header->type != ELF_DYNAMIC) + || header->bitness != ELF_CLASS + || header->endian != ELF_LITTLEENDIAN + || header->elfversion1 != 1 + || header->machine != ELF_MACHINE) { + return _ENOEXEC; + } + return 0; +} + +static int read_prg_headers(struct fd *fd, exec_elf_header header, exec_prg_header **ph_out) { + ssize_t ph_size = sizeof(exec_prg_header) * header.phent_count; + exec_prg_header *ph = malloc(ph_size); + if (ph == NULL) + return _ENOMEM; + + if (fd->ops->lseek(fd, header.prghead_off, SEEK_SET) < 0) { + free(ph); + return _EIO; + } + if (fd->ops->read(fd, ph, ph_size) != ph_size) { + free(ph); + if (errno != 0) + return _EIO; + return _ENOEXEC; + } + + *ph_out = ph; + return 0; +} + +static int load_entry(exec_prg_header ph, addr_t bias, struct fd *fd) { + int err; + + addr_t addr = ph.vaddr + bias; + addr_t offset = ph.offset; + addr_t memsize = ph.memsize; + addr_t filesize = ph.filesize; + + int flags = P_READ; + if (ph.flags & PH_W) flags |= P_WRITE; + if (ph.flags & PH_X) flags |= P_EXEC; + + if ((err = fd->ops->mmap(fd, current->mem, PAGE(addr), + PAGE_ROUND_UP(filesize + PGOFFSET(addr)), + offset - PGOFFSET(addr), flags, MMAP_PRIVATE)) < 0) + return err; + // TODO find a better place for these to avoid code duplication + mem_pt(current->mem, PAGE(addr))->data->fd = fd_retain(fd); + mem_pt(current->mem, PAGE(addr))->data->file_offset = offset - PGOFFSET(addr); + + if (memsize > filesize) { + // put zeroes between addr + filesize and addr + memsize, call that bss + dword_t bss_size = memsize - filesize; + + // first zero the tail from the end of the file mapping to the end + // of the load entry or the end of the page, whichever comes first + addr_t file_end = addr + filesize; + dword_t tail_size = PAGE_SIZE - PGOFFSET(file_end); + if (tail_size == PAGE_SIZE) + // if you can calculate tail_size better and not have to do this please let me know + tail_size = 0; + + if (tail_size != 0) { + // Unlock and lock the mem because the user functions must be + // called without locking mem. + write_wrunlock(¤t->mem->lock); + user_memset(file_end, 0, tail_size); + write_wrlock(¤t->mem->lock); + } + if (tail_size > bss_size) + tail_size = bss_size; + + // then map the pages from after the file mapping up to and including the end of bss + if (bss_size - tail_size != 0) { + if ((err = pt_map_nothing(current->mem, PAGE_ROUND_UP(addr + filesize), + PAGE_ROUND_UP(bss_size - tail_size), flags)) < 0) + return err; + } + } + return 0; +} + +static addr_t find_hole_for_elf(exec_elf_header *header, exec_prg_header *ph) { + exec_prg_header *first = NULL, *last = NULL; + for (int i = 0; i < header->phent_count; i++) { + if (ph[i].type == PT_LOAD) { + if (first == NULL) + first = &ph[i]; + last = &ph[i]; + } + } + pages_t size = 0; + if (first != NULL) { + pages_t a = PAGE_ROUND_UP(last->vaddr + last->memsize); + pages_t b = PAGE(first->vaddr); + size = a - b; + } + return pt_find_hole(current->mem, size) << PAGE_BITS; +} + +static int elf_exec(struct fd *fd, const char *file, struct exec_args argv, struct exec_args envp) { + int err = 0; + + // read the headers + exec_elf_header header; + if ((err = read_header(fd, &header)) < 0) + return err; + exec_prg_header *ph; + if ((err = read_prg_headers(fd, header, &ph)) < 0) + return err; + + // look for an interpreter + char *interp_name = NULL; + struct fd *interp_fd = NULL; + exec_elf_header interp_header; + exec_prg_header *interp_ph = NULL; + for (unsigned i = 0; i < header.phent_count; i++) { + if (ph[i].type != PT_INTERP) + continue; + if (interp_name) { + // can't have two interpreters + err = _EINVAL; + goto out_free_interp; + } + + if (ph[i].filesize == 0 || ph[i].filesize > MAX_PATH) { + err = _ENAMETOOLONG; + goto out_free_interp; + } + interp_name = malloc(ph[i].filesize + 1); + err = _ENOMEM; + if (interp_name == NULL) + goto out_free_ph; + + // read the interpreter name out of the file + err = _EIO; + if (fd->ops->lseek(fd, ph[i].offset, SEEK_SET) < 0) + goto out_free_interp; + ssize_t interp_read = fd->ops->read(fd, interp_name, ph[i].filesize); + if (interp_read < 0 || (uint64_t) interp_read != ph[i].filesize) + goto out_free_interp; + interp_name[ph[i].filesize] = '\0'; + + // open interpreter and read headers + interp_fd = generic_open(interp_name, O_RDONLY, 0); + if (IS_ERR(interp_fd)) { + err = PTR_ERR(interp_fd); + goto out_free_interp; + } + if ((err = read_header(interp_fd, &interp_header)) < 0) { + if (err == _ENOEXEC) err = _ELIBBAD; + goto out_free_interp; + } + if ((err = read_prg_headers(interp_fd, interp_header, &interp_ph)) < 0) { + if (err == _ENOEXEC) err = _ELIBBAD; + goto out_free_interp; + } + } + + // free the process's memory. + // from this point on, if any error occurs the process will have to be + // killed before it even starts. please don't be too sad about it, it's + // just a process. + // + // general_lock protects current->mm. otherwise procfs might read the + // pointer before it's released and then try to lock it after it's + // released. + struct mm *new_mm = mm_new(); + if (new_mm == NULL) + return _ENOMEM; + lock(¤t->general_lock); + struct mm *old_mm = current->mm; + task_set_mm(current, new_mm); + mm_release(old_mm); + unlock(¤t->general_lock); + write_wrlock(¤t->mem->lock); + + current->mm->exefile = fd_retain(fd); + + addr_t load_addr = 0; // used for AX_PHDR + bool load_addr_set = false; + addr_t bias = 0; // offset for loading shared libraries as executables + + // Map loadable program segments. + for (unsigned i = 0; i < header.phent_count; i++) { + if (ph[i].type != PT_LOAD) + continue; + + if (!load_addr_set && header.type == ELF_DYNAMIC) { + // see giant comment in linux/fs/binfmt_elf.c, around line 950 + // ARM64: Always use dynamic placement to avoid conflicts with + // V8's CodeRange hint at 0x574c0000. + bias = find_hole_for_elf(&header, ph); + } + + if ((err = load_entry(ph[i], bias, fd)) < 0) + goto beyond_hope; + + // load_addr is used to get a value for AX_PHDR et al + if (!load_addr_set) { + load_addr = bias + ph[i].vaddr - ph[i].offset; + load_addr_set = true; + } + + // we have to know where the brk starts + addr_t brk = bias + ph[i].vaddr + ph[i].memsize; + if (brk > current->mm->start_brk) + current->mm->start_brk = current->mm->brk = BYTES_ROUND_UP(brk); + } + + addr_t entry = bias + header.entry_point; + addr_t interp_base = 0; + + if (interp_name) { + // Map the ELF interpreter segments. + interp_base = find_hole_for_elf(&interp_header, interp_ph); + for (int i = interp_header.phent_count - 1; i >= 0; i--) { + if (interp_ph[i].type != PT_LOAD) + continue; + if ((err = load_entry(interp_ph[i], interp_base, interp_fd)) < 0) + goto beyond_hope; + } + entry = interp_base + interp_header.entry_point; + } + + + // map vdso + err = _ENOMEM; + pages_t vdso_pages = sizeof(vdso_data) >> PAGE_BITS; + // FIXME disgusting hack: musl's dynamic linker has a one-page hole, and + // I'd rather not put the vdso in that hole. so find a two-page hole and + // add one. + page_t vdso_page = pt_find_hole(current->mem, vdso_pages + 1); + if (vdso_page == BAD_PAGE) + goto beyond_hope; + vdso_page += 1; + if ((err = pt_map(current->mem, vdso_page, vdso_pages, (void *) vdso_data, 0, 0)) < 0) + goto beyond_hope; + mem_pt(current->mem, vdso_page)->data->name = "[vdso]"; + current->mm->vdso = vdso_page << PAGE_BITS; + + // map empty vvar pages alongside the VDSO + page_t vvar_page = pt_find_hole(current->mem, VVAR_PAGES); + if (vvar_page == BAD_PAGE) + goto beyond_hope; + if ((err = pt_map_nothing(current->mem, vvar_page, VVAR_PAGES, 0)) < 0) + goto beyond_hope; + mem_pt(current->mem, vvar_page)->data->name = "[vvar]"; + + // STACK TIME! + + // ARM64: stack near top of 48-bit address space + if ((err = pt_map_nothing(current->mem, STACK_INIT_PAGE, 1, P_READ | P_WRITE | P_GROWSDOWN)) < 0) + goto beyond_hope; + if ((err = pt_map_nothing(current->mem, STACK_TOP_PAGE, 1, P_READ)) < 0) + goto beyond_hope; + write_wrunlock(¤t->mem->lock); + addr_t sp = STACK_TOP_ADDR; + // 64-bit Linux leaves 8 empty bytes at the bottom of the initial stack. + sp -= sizeof(void *); + + err = _EFAULT; + // first, copy stuff pointed to by argv/envp/auxv + // filename, argc, argv + // Note: lock is already released at this point + addr_t file_addr = sp = copy_string(sp, file); + if (sp == 0) + goto out_free_interp; + addr_t envp_addr = sp = args_copy(sp, envp); + if (sp == 0) + goto out_free_interp; + current->mm->argv_end = sp; + addr_t argv_addr = sp = args_copy(sp, argv); + if (sp == 0) + goto out_free_interp; + current->mm->argv_start = sp; + sp = align_stack(sp); + + addr_t platform_addr = sp = copy_string(sp, "aarch64"); + if (sp == 0) + goto out_free_interp; + // 16 random bytes so no system call is needed to seed a userspace RNG + char random[16] = {}; + get_random(random, sizeof(random)); // if this fails, eh, no one's really using it + addr_t random_addr = sp -= sizeof(random); + if (user_put(sp, random)) + goto out_free_interp; + + // the way linux aligns the stack at this point is kinda funky + // calculate how much space is needed for argv, envp, and auxv, subtract + // that from sp, then align, then copy argv/envp/auxv from that down + + // declare elf aux now so we can know how big it is + struct aux_ent aux[] = { + // The internal VDSO supplies sigreturn trampolines, but it is not a + // complete aarch64 Linux VDSO for userspace dynamic loaders to parse. + {AX_SYSINFO_EHDR, 0}, + {AX_HWCAP, 0x003}, // FP|ASIMD only. Keep optional crypto/LSE features hidden until helper coverage is clean. + {AX_PAGESZ, PAGE_SIZE}, + {AX_CLKTCK, 0x64}, + {AX_PHDR, load_addr + header.prghead_off}, + {AX_PHENT, sizeof(exec_prg_header)}, + {AX_PHNUM, header.phent_count}, + {AX_BASE, interp_base}, + {AX_FLAGS, 0}, + {AX_ENTRY, bias + header.entry_point}, + {AX_UID, 0}, + {AX_EUID, 0}, + {AX_GID, 0}, + {AX_EGID, 0}, + {AX_SECURE, 0}, + {AX_RANDOM, random_addr}, + {AX_HWCAP2, 0}, // suck that too + {AX_EXECFN, file_addr}, + {AX_PLATFORM, platform_addr}, + {0, 0} + }; + sp -= ((argv.count + 1) + (envp.count + 1) + 1) * ELF_PTR_SIZE; + sp -= sizeof(aux); + sp &=~ 0xf; + + // now copy down, start using p so sp is preserved + addr_t p = sp; + + // argc + {uint64_t argc64 = argv.count; if (user_put(p, argc64)) return _EFAULT;} + p += ELF_PTR_SIZE; + + // argv + size_t argc = argv.count; + while (argc-- > 0) { + {uint64_t ptr64 = argv_addr; if (user_put(p, ptr64)) return _EFAULT;} + argv_addr += user_strlen(argv_addr) + 1; + p += ELF_PTR_SIZE; + } + p += ELF_PTR_SIZE; // null terminator + + // envp + size_t envc = envp.count; + while (envc-- > 0) { + {uint64_t ptr64 = envp_addr; if (user_put(p, ptr64)) return _EFAULT;} + envp_addr += user_strlen(envp_addr) + 1; + p += ELF_PTR_SIZE; + } + p += ELF_PTR_SIZE; // null terminator + + // copy auxv + current->mm->auxv_start = p; + if (user_put(p, aux)) + goto beyond_hope; + p += sizeof(aux); + current->mm->auxv_end = p; + + current->mm->stack_start = sp; + current->cpu.sp = sp; + current->cpu.pc = entry; + // Zero all general-purpose registers + memset(current->cpu.regs, 0, sizeof(current->cpu.regs)); + current->cpu.nzcv = 0; + current->cpu.nf = 0; + current->cpu.zf = 0; + current->cpu.cf = 0; + current->cpu.vf = 0; + current->cpu.fpcr = 0; + current->cpu.fpsr = 0; + + // Map V8 compressed pointer range as readable zeros. + // V8's Zone allocator reuses memory without zeroing. Stale data containing + // V8 compressed pointers (small integers like 0x9xxxx) can leak into real + // pointer fields. Mapping these low pages with zeros means accidental + // dereferences read zeros (NULL) instead of faulting with SIGSEGV. + // This covers V8 cage offsets 0x80000-0x100000 which are common stale values. + { + const char *base_name = strrchr(file, '/'); + base_name = base_name ? base_name + 1 : file; + if (strcmp(base_name, "node") == 0) { + // Map zero pages at 0x0-0x100000 (first 1MB) + // This catches both NULL dereferences and V8 compressed pointers + page_t guard_start = 0; // page 0 + pages_t guard_pages = 0x100000 / PAGE_SIZE; // 256 pages = 1MB + write_wrlock(¤t->mem->lock); + int map_err = pt_map_nothing(current->mem, guard_start, guard_pages, P_READ | P_WRITE); + write_wrunlock(¤t->mem->lock); + (void)map_err; // guard pages are best-effort + } + } + + err = 0; +out_free_interp: + if (interp_name != NULL) + free(interp_name); + if (interp_fd != NULL && !IS_ERR(interp_fd)) + fd_close(interp_fd); + if (interp_ph != NULL) + free(interp_ph); +out_free_ph: + free(ph); + return err; + +beyond_hope: + // TODO force sigsegv + write_wrunlock(¤t->mem->lock); + goto out_free_interp; +} + +static size_t args_size(struct exec_args args) { + const char *args_end = args.args; + for (size_t i = 0; i < args.count; i++) { + args_end += strlen(args_end) + 1; + } + // don't forget the very last null terminator + assert(args_end[0] == '\0'); + args_end++; + return args_end - args.args; +} + +static inline addr_t align_stack(addr_t sp) { + return sp &~ (addr_t)0xf; +} + +static inline addr_t copy_string(addr_t sp, const char *string) { + sp -= strlen(string) + 1; + if (user_write_string(sp, string)) + return 0; + return sp; +} + +static inline addr_t args_copy(addr_t sp, struct exec_args args) { + size_t size = args_size(args); + sp -= size; + if (user_write(sp, args.args, size)) + return 0; + return sp; +} + +static inline ssize_t user_strlen(addr_t p) { + size_t i = 0; + char c; + do { + if (user_get(p + i, c)) + return -1; + i++; + } while (c != '\0'); + return i - 1; +} + +static inline int user_memset(addr_t start, byte_t val, dword_t len) { + while (len--) + if (user_put(start++, val)) + return 1; + return 0; +} + +static int format_exec(struct fd *fd, const char *file, struct exec_args argv, struct exec_args envp) { + int err = elf_exec(fd, file, argv, envp); + if (err != _ENOEXEC) + return err; + // other formats would go here + return _ENOEXEC; +} + +static int shebang_exec(struct fd *fd, const char *file, struct exec_args argv, struct exec_args envp) { + // read the first 128 bytes to get the shebang line out of + if (fd->ops->lseek(fd, 0, SEEK_SET)) + return _EIO; + char header[128]; + int size = fd->ops->read(fd, header, sizeof(header) - 1); + if (size < 0) + return _EIO; + header[size] = '\0'; + + // only look at the first line + char *newline = strchr(header, '\n'); + if (newline == NULL) + return _ENOEXEC; + *newline = '\0'; + + // format: #![spaces]interpreter[spaces]argument[spaces] + char *p = header; + if (p[0] != '#' || p[1] != '!') + return _ENOEXEC; + p += 2; + while (*p == ' ') + p++; + if (*p == '\0') + return _ENOEXEC; + + char *interpreter = p; + while (*p != ' ' && *p != '\0') + p++; + if (*p != '\0') { + *p++ = '\0'; + while (*p == ' ') + p++; + } + + char *argument = p; + // Strip trailing spaces from the optional interpreter argument without + // walking back into the interpreter string when no argument is present. + char *end = argument + strlen(argument); + while (end > argument && end[-1] == ' ') + *--end = '\0'; + if (*argument == '\0') + argument = NULL; + + struct exec_args argv_rest = { + .count = argv.count - 1, + .args = argv.args + strlen(argv.args) + 1, + }; + size_t args_rest_size = args_size(argv_rest); + size_t extra_args_size = strlen(interpreter) + 1 + strlen(file) + 1; + if (argument) + extra_args_size += strlen(argument) + 1; + if (args_rest_size + extra_args_size >= ARGV_MAX) + return _E2BIG; + + char new_argv_buf[ARGV_MAX]; + struct exec_args new_argv = {.args = new_argv_buf}; + size_t n = 0; + strcpy(new_argv_buf, interpreter); + new_argv.count++; + n += strlen(interpreter) + 1; + if (argument) { + strcpy(new_argv_buf + n, argument); + new_argv.count++; + n += strlen(argument) + 1; + } + strcpy(new_argv_buf + n, file); + n += strlen(file) + 1; + new_argv.count++; + memcpy(new_argv_buf + n, argv_rest.args, args_rest_size); + new_argv.count += argv_rest.count; + + struct fd *interpreter_fd = generic_open(interpreter, O_RDONLY_, 0); + if (IS_ERR(interpreter_fd)) + return PTR_ERR(interpreter_fd); + int err = format_exec(interpreter_fd, interpreter, new_argv, envp); + fd_close(interpreter_fd); + return err; +} + +int __do_execve(const char *file, struct exec_args argv, struct exec_args envp) { + struct fd *fd = generic_open(file, O_RDONLY, 0); + if (IS_ERR(fd)) + return PTR_ERR(fd); + + struct statbuf stat; + int err = fd->mount->fs->fstat(fd, &stat); + if (err < 0) { + fd_close(fd); + return err; + } + + // if nobody has permission to execute, it should be safe to not execute + if (!(stat.mode & 0111)) { + fd_close(fd); + return _EACCES; + } + + err = format_exec(fd, file, argv, envp); + if (err == _ENOEXEC) + err = shebang_exec(fd, file, argv, envp); + fd_close(fd); + if (err < 0) + return err; + + // setuid/setgid + if (stat.mode & S_ISUID) { + current->suid = current->euid; + current->euid = stat.uid; + } + if (stat.mode & S_ISGID) { + current->sgid = current->egid; + current->egid = stat.gid; + } + + // save current->comm + lock(¤t->general_lock); + const char *basename = strrchr(file, '/'); + if (basename == NULL) + basename = file; + else + basename++; + strncpy(current->comm, basename, sizeof(current->comm)); + unlock(¤t->general_lock); + + update_thread_name(); + + // Like Linux's unshare_files(), give the new image a private descriptor + // table before closing close-on-exec fds. Threads that shared it through + // CLONE_FILES keep the old table: Node's tsc launcher execs from the main + // thread while V8 workers sit in epoll_wait on a close-on-exec epoll fd, + // and closing it under them makes libuv abort on EBADF. + if (current->files->refcount > 1) { + struct fdtable *files = fdtable_copy(current->files); + if (!IS_ERR(files)) { + lock(&pids_lock); + struct fdtable *shared = current->files; + current->files = files; + unlock(&pids_lock); + fdtable_release(shared); + } + } + + // cloexec + // consider putting this in fd.c? + fdtable_do_cloexec(current->files); + + // reset signal handlers + lock(¤t->sighand->lock); + for (int sig = 0; sig < NUM_SIGS; sig++) { + struct sigaction_ *action = ¤t->sighand->action[sig]; + if (action->handler != SIG_IGN_) + action->handler = SIG_DFL_; + } + current->altstack = 0; + current->altstack_size = 0; + unlock(¤t->sighand->lock); + + current->rseq_addr = 0; + current->rseq_len = 0; + current->rseq_sig = 0; + current->rseq_registered = false; + current->did_exec = true; + vfork_notify(current); + + if (current->ptrace.traced) { + lock(&pids_lock); + send_signal(current, SIGTRAP_, (struct siginfo_) { + .code = SI_USER_, + .kill.pid = current->pid, + .kill.uid = current->uid, + }); + unlock(&pids_lock); + } + + return 0; +} + +int do_execve(const char *file, size_t argc, const char *argv_p, const char *envp_p) { + struct exec_args argv = {.count = argc, .args = argv_p}; + struct exec_args envp = {.args = envp_p}; + while (*envp_p != '\0') { + envp_p += strlen(envp_p) + 1; + envp.count++; + } + return __do_execve(file, argv, envp); +} + +static ssize_t user_read_string_array(addr_t addr, char *buf, size_t max) { + size_t i = 0; + size_t p = 0; + for (;;) { + uint64_t str_addr64; + if (user_get(addr + i * ELF_PTR_SIZE, str_addr64)) + return _EFAULT; + addr_t str_addr = (addr_t) str_addr64; + if (str_addr == 0) + break; + size_t str_p = 0; + for (;;) { + if (p >= max) + return _E2BIG; + if (user_get(str_addr + str_p, buf[p])) + return _EFAULT; + str_p++; + p++; + if (buf[p - 1] == '\0') + break; + } + i++; + } + if (p >= max) + return _E2BIG; + buf[p] = '\0'; + return i; +} + +dword_t sys_execve(addr_t filename_addr, addr_t argv_addr, addr_t envp_addr) { + char filename[MAX_PATH]; + if (user_read_string(filename_addr, filename, sizeof(filename))) + return _EFAULT; + + int err = _ENOMEM; + char *argv = malloc(ARGV_MAX); + if (argv == NULL) + goto err_free_argv; + ssize_t argc = user_read_string_array(argv_addr, argv, ARGV_MAX); + if (argc < 0) { + err = argc; + goto err_free_argv; + } + + char *envp = malloc(ARGV_MAX); + if (envp == NULL) + goto err_free_envp; + if (envp_addr != 0) { + err = user_read_string_array(envp_addr, envp, ARGV_MAX); + if (err < 0) + goto err_free_envp; + } else { + // Do not take advantage of this nonstandard and nonportable misfeature! + // - Michael Kerrisk, execve(2) + envp[0] = envp[1] = '\0'; + } + + STRACE("execve(\"%.1000s\", {", filename); + const char *args = argv; + while (*args != '\0') { + STRACE("\"%.1000s\", ", args); + args += strlen(args) + 1; + } + STRACE("}, {"); + args = envp; + while (*args != '\0') { + STRACE("\"%.1000s\", ", args); + args += strlen(args) + 1; + } + STRACE("})"); + + // Force-inject environment variables into every execve'd process. + // mode=0: inject only if not present, mode=1: replace existing value + static const struct { const char *kv; size_t prefix_len; int mode; } inject_envs[] = { + { "PYTHONMALLOC=malloc", 13, 1 }, // FORCE bypass pymalloc arenas (mode=1: always replace) + { "NO_COLOR=1", 9, 0 }, // Disable color output + { "PIP_PROGRESS_BAR=off", 17, 0 }, // Disable pip progress bar + { "PYTHONDONTWRITEBYTECODE=1", 25, 0 }, // Skip .pyc generation to reduce allocs + // Go async preemption sends SIGURG and reads/modifies mcontext at a + // fixed offset. Our JIT delivers signals at gadget boundaries, not at + // the exact interrupted instruction, so the PC in the signal frame is + // imprecise. cpu_poke reduces latency but can't fix PC precision. + // Cooperative preemption (function-call checkpoints) works correctly. + { "GODEBUG=asyncpreemptoff=1", 8, 0 }, // Disable Go async preemption + // Limit Go threads to reduce TLB stale-pointer crashes from concurrent + // page table modifications. GOMAXPROCS=2 is sufficient for most Go CLI + // tools and eliminates nearly all multi-thread race conditions. + { "GOMAXPROCS=2", 11, 0 }, // Limit Go thread count + // JavaScriptCore's concurrent/parallel GC uses timer-driven background + // work plus signal-suspend handshakes for marker threads. iSH delivers + // guest signals at syscall/gadget boundaries, so marker suspension can + // spin forever when a target thread is parked in futex/syscall context; + // timer-driven Bun event-loop callbacks can also stall behind concurrent + // GC. Keep GC enabled, but make it serial/non-concurrent in the guest. + { "JSC_numberOfGCMarkers=1", 22, 0 }, // Avoid multi-marker GC suspend hangs + { "JSC_useConcurrentGC=0", 19, 0 }, // Keep Bun timers/server progress reliable + }; + for (size_t vi = 0; vi < sizeof(inject_envs)/sizeof(inject_envs[0]); vi++) { + char *e = envp; + char *found_at = NULL; + while (*e != '\0') { + if (strncmp(e, inject_envs[vi].kv, inject_envs[vi].prefix_len) == 0) + found_at = e; + e += strlen(e) + 1; + } + size_t total_used = (e - envp) + 1; // includes final \0 + if (found_at != NULL && inject_envs[vi].mode == 1) { + // Replace: remove old value, then append new one + size_t old_len = strlen(found_at) + 1; + size_t tail = total_used - (found_at - envp) - old_len; + memmove(found_at, found_at + old_len, tail); + total_used -= old_len; + found_at = NULL; // treat as not found so it gets appended + } + if (found_at == NULL) { + size_t inject_len = strlen(inject_envs[vi].kv) + 1; + if (total_used + inject_len + 1 <= ARGV_MAX) { + memcpy(envp + total_used - 1, inject_envs[vi].kv, inject_len); + envp[total_used - 1 + inject_len] = '\0'; + } + } + } + + // Inject V8 flags for Node.js to work around scope corruption in emulation. + // --jitless: disable JIT (avoids V8 code generation incompatible with our JIT) + // --predictable: disable concurrent GC/compilation (avoids race conditions) + // --no-lazy: eager compilation (avoids Zone reuse patterns that corrupt scopes) + // --single-generation: skip young generation (reduces GC-triggered Zone resets) + // --lite-mode: reduces Zone churn by disabling feedback vectors & optimizer + // --no-compilation-cache: prevent stale cached compilations from reusing Zones + // --no-flush-bytecode: keep compiled bytecode alive, avoid recompilation churn + // --no-lazy-compile-dispatcher: single-thread parsing to reduce concurrent Zones + // --no-parallel-compile-tasks: single-thread compilation to reduce concurrent Zones + // --no-concurrent-recompilation: disable background recompilation + { + const char *base = strrchr(filename, '/'); + base = base ? base + 1 : filename; + if (strcmp(base, "node") == 0) { + bool skip_node_arg_injection = false; + for (char *e = envp; *e != '\0'; e += strlen(e) + 1) { + if (strcmp(e, "ISH_NODE_NO_ARG_INJECTION=1") == 0) { + skip_node_arg_injection = true; + break; + } + } + if (skip_node_arg_injection) + goto node_arg_injection_done; + + static const char *inject_args_base[] = { + "--jitless", + "--no-expose-wasm", + "--no-lazy", + "--max-old-space-size=512", + }; + // Conditionally inject --require for polyfill files that exist in guest fs + static const char *optional_requires[] = { + "--require=/lib/wasm-polyfill.js", // WebAssembly shim (must load first) + "--require=/lib/fetch-polyfill.js", // fetch() via native http/https + }; + const char *inject_args[8]; // base args + optional requires + size_t inject_count = 0; + for (size_t i = 0; i < sizeof(inject_args_base)/sizeof(inject_args_base[0]); i++) + inject_args[inject_count++] = inject_args_base[i]; + for (size_t i = 0; i < sizeof(optional_requires)/sizeof(optional_requires[0]); i++) { + // Extract path after "--require=" + const char *path = optional_requires[i] + 10; // strlen("--require=") + struct fd *fd = generic_open(path, O_RDONLY_, 0); + if (!IS_ERR(fd)) { + fd_close(fd); + inject_args[inject_count++] = optional_requires[i]; + } + } + for (size_t ai = 0; ai < inject_count; ai++) { + const char *arg = inject_args[ai]; + size_t arg_len = strlen(arg) + 1; // includes NUL + + // Find end of argv buffer + char *p = argv; + while (*p != '\0') + p += strlen(p) + 1; + size_t total_used = (p - argv) + 1; + + // Check if already present + bool found = false; + char *q = argv; + while (*q != '\0') { + if (strcmp(q, arg) == 0) { found = true; break; } + q += strlen(q) + 1; + } + + if (!found && total_used + arg_len + 1 <= ARGV_MAX) { + char *after_argv0 = argv + strlen(argv) + 1; + size_t tail = total_used - (after_argv0 - argv); + memmove(after_argv0 + arg_len, after_argv0, tail); + memcpy(after_argv0, arg, arg_len); + argc++; + } + } +node_arg_injection_done: ; + } + + // Inject LD_PRELOAD for zero_malloc.so to zero large malloc/free. + // V8's Zone allocator reuses freed memory without zeroing, causing + // stale pointer dereferences. This library zeros blocks >= 4096 bytes + // on both malloc and free (Zone segments are >= 8KB). + if (strcmp(base, "node") == 0) { + struct fd *zero_free_fd = generic_open("/lib/zero_free.so", O_RDONLY_, 0); + if (!IS_ERR(zero_free_fd)) { + fd_close(zero_free_fd); + static const char *ld_preload = "LD_PRELOAD=/lib/zero_free.so"; + size_t env_len = strlen(ld_preload) + 1; + + // Check if LD_PRELOAD is already set + bool found = false; + char *q = envp; + while (*q != '\0') { + if (strncmp(q, "LD_PRELOAD=", 11) == 0) { found = true; break; } + q += strlen(q) + 1; + } + if (!found) { + char *p = envp; + while (*p != '\0') + p += strlen(p) + 1; + size_t total_used = (p - envp) + 1; + if (total_used + env_len + 1 <= ARGV_MAX) { + memcpy(p, ld_preload, env_len); + p[env_len] = '\0'; + } + } + } + } + } + + // Native offload: check if this binary should run natively on the host + const char *native_path = native_offload_lookup(filename); + if (native_path) { + // native_offload_exec calls do_exit() on success, which unwinds via + // pthread_exit() and skips the err_free_{argv,envp} labels below. + // Register pthread cleanup handlers so the ARGV_MAX-sized buffers are + // freed on that unwind path; without them each native-offloaded exec + // (ffmpeg, minis-open, …) leaks ~2 × ARGV_MAX per process. + pthread_cleanup_push(free, envp); + pthread_cleanup_push(free, argv); + err = native_offload_exec(native_path, filename, argc, argv, envp); + // Only reach here on fallback. Do not execute cleanups — the normal + // err_free_{argv,envp} path below will free them. + pthread_cleanup_pop(0); + pthread_cleanup_pop(0); + if (err == 0) { + // Should not reach here (do_exit doesn't return), but just in case + goto err_free_envp; + } + // Fall through to emulated exec on failure + printk("native_offload: fallback to emulated exec for %s\n", filename); + } + + err = do_execve(filename, argc, argv, envp); + +err_free_envp: + free(envp); +err_free_argv: + free(argv); + return err; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/exit.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/exit.c new file mode 100644 index 0000000000..7ec7793ab9 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/exit.c @@ -0,0 +1,659 @@ +#include <pthread.h> +#include <signal.h> +#include <stdio.h> +#include <string.h> +#include <time.h> +#include <unistd.h> +#include "kernel/calls.h" +#include "kernel/mm.h" +#include "kernel/futex.h" +#include "kernel/ptrace.h" +#include "fs/fd.h" +#include "fs/tty.h" +#include "platform/platform.h" + +static void halt_system(void); + +// Weak default: overridden by main.c in CLI builds. +// In iOS/Xcode builds where main.c is not linked into libish.a, +// this no-op prevents an undefined symbol error. +__attribute__((weak)) void restore_termios(void) {} + +static bool exit_tgroup(struct task *task) { + struct tgroup *group = task->group; + list_remove(&task->group_links); + bool group_dead = list_empty(&group->threads); + if (group_dead) { + // don't need to lock the group since the only pointers to it come from: + // - other threads' current->group, but there are none left thanks to that list_empty call + // - locking pids_lock first, which do_exit did + if (group->itimer) + timer_free(group->itimer); + + // The group will be removed from its group and session by reap_if_zombie, + // because fish tries to set the pgid to that of an exited but not reaped + // task. + // https://github.com/Microsoft/WSL/issues/2786 + } + return group_dead; +} + +void (*exit_hook)(struct task *task, int code) = NULL; + +#ifdef GUEST_ARM64 +extern void arm64_fusion_stats_dump_if_enabled(void); +extern void arm64_block_stats_dump_if_enabled(void); +#endif + +static struct task *find_new_parent(struct task *task) { + struct task *new_parent; + list_for_each_entry(&task->group->threads, new_parent, group_links) { + if (!new_parent->exiting) + return new_parent; + } + return pid_get_task(1); +} + +noreturn void do_exit(int status) { +#ifdef GUEST_ARM64 + arm64_fusion_stats_dump_if_enabled(); + arm64_block_stats_dump_if_enabled(); +#endif + // If this thread was already marked as leaked by the safety valve, + // the group leader has finished exiting and the group struct may be + // freed. Don't touch any shared state — just kill the host thread. + if (current->exiting) { + current = NULL; + pthread_exit(NULL); + } + + // Block SIGSEGV during exit to prevent cosmetic crashes from host + // pthread stack unwinding (especially with many threads exiting at once). + if (current->group->doing_group_exit) { + sigset_t set; + sigemptyset(&set); + sigaddset(&set, SIGSEGV); + sigaddset(&set, SIGBUS); + pthread_sigmask(SIG_BLOCK, &set, NULL); + } + + // has to happen before mm_release + addr_t clear_tid = current->clear_tid; + if (clear_tid) { + pid_t_ zero = 0; + if (user_put(clear_tid, zero) == 0) + futex_wake(clear_tid, 1); + } + + // release all our resources (may already be NULL if force-released by do_exit_group) + if (current->mm != NULL) { + mm_release(current->mm); + current->mm = NULL; + // [T-ish-mm-leak-refcount-handoff] We just released it, so the pthread + // cleanup handler must NOT release again. + current->mm_release_deferred = false; + } + if (current->files != NULL) { + fdtable_release(current->files); + current->files = NULL; + } + if (current->fs != NULL) { + fs_info_release(current->fs); + current->fs = NULL; + } + // Close per-thread futex wakeup pipe + if (current->futex_pipe[0] != -1) { + close(current->futex_pipe[0]); + current->futex_pipe[0] = -1; + } + if (current->futex_pipe[1] != -1) { + close(current->futex_pipe[1]); + current->futex_pipe[1] = -1; + } + + // sighand must be released below so it can be protected by pids_lock + // since it can be accessed by other threads + + // save things that our parent might be interested in + current->exit_code = status; // FIXME locking + struct rusage_ rusage = rusage_get_current(); + lock(¤t->group->lock); + rusage_add(¤t->group->rusage, &rusage); + struct rusage_ group_rusage = current->group->rusage; + unlock(¤t->group->lock); + + // the actual freeing needs pids_lock + lock(&pids_lock); + current->exiting = true; + // release the sighand (may already be NULL if another thread in the group + // exited concurrently and released it, e.g. after safety-valve SIGUSR1) + if (current->sighand != NULL) { + sighand_release(current->sighand); + current->sighand = NULL; + } + struct sigqueue *sigqueue, *sigqueue_tmp; + list_for_each_entry_safe(¤t->queue, sigqueue, sigqueue_tmp, queue) { + list_remove(&sigqueue->queue); + free(sigqueue); + } + struct task *leader = current->group->leader; + + // reparent children + struct task *new_parent = find_new_parent(current); + struct task *child, *tmp; + list_for_each_entry_safe(¤t->children, child, tmp, siblings) { + child->parent = new_parent; + list_remove(&child->siblings); + list_add(&new_parent->children, &child->siblings); + } + + if (exit_tgroup(current)) { + // If already marked zombie by do_exit_group force path, skip + if (leader->zombie) + goto skip_zombie_notify; + + // notify parent that we died + struct task *parent = leader->parent; + if (parent == NULL && current->pid != 1) { + // Non-init process with no parent - try to find one + // This can happen during reparenting or if parent exited first + parent = pid_get_task(1); // Reparent to init + if (parent != NULL) + leader->parent = parent; + } + + if (parent == NULL) { + // init died + if (exit_hook != NULL) + exit_hook(current, status); + halt_system(); + } else { + leader->zombie = true; + notify(&parent->group->child_exit); + // Wake any pidfd poller waiting on this pid. + pidfd_notify_exit(leader->pid); + struct siginfo_ info = { + .code = SI_KERNEL_, + .child.pid = current->pid, + .child.uid = current->uid, + .child.status = current->exit_code, + .child.utime = clock_from_timeval(group_rusage.utime), + .child.stime = clock_from_timeval(group_rusage.stime), + }; + if (leader->exit_signal != 0) + send_signal(parent, leader->exit_signal, info); + } + + if (parent != NULL && exit_hook != NULL) + exit_hook(current, status); + skip_zombie_notify: ; + } + + vfork_notify(current); + if (current != leader) { + struct task *self = current; + current = NULL; // Clear before destroy to prevent dangling access + task_destroy(self); + } else { + // A parent may reap the leader as soon as pids_lock is released. + // Its resources are already released; pthread cleanup must not use it. + current = NULL; + } + unlock(&pids_lock); + + pthread_exit(NULL); +} + +noreturn void do_exit_group(int status) { + // Leaked thread woke up after group already exited — bail silently. + if (current->exiting) { + current = NULL; + pthread_exit(NULL); + } + struct tgroup *group = current->group; + lock(&pids_lock); + lock(&group->lock); + bool is_group_leader = false; + if (!group->doing_group_exit) { + group->doing_group_exit = true; + group->group_exit_code = status; + is_group_leader = true; // First thread to call exit_group + } else { + status = group->group_exit_code; + } + + // kill everyone else in the group + int thread_count = 0; + struct task *task; + list_for_each_entry(&group->threads, task, group_links) { + thread_count++; + deliver_signal(task, SIGKILL_, SIGINFO_NIL); + task->group->stopped = false; + notify(&task->group->stopped_cond); + } + (void)is_group_leader; + + // Only the first thread (group leader) waits for others to exit + // Other threads exit immediately to avoid deadlock + if (is_group_leader && thread_count > 1) { + unlock(&group->lock); + unlock(&pids_lock); + + // Wait for threads to exit (they're DETACHED so we can't join) + // Poll the thread count until only current thread remains + int max_wait_ms = 5000 + thread_count * 10; // Scale with thread count + if (max_wait_ms > 10000) max_wait_ms = 10000; // Cap at 10s + int wait_interval_ms = 10; // Check every 10ms + int waited_ms = 0; + int last_remaining = -1; + + while (waited_ms < max_wait_ms) { + lock(&pids_lock); + lock(&group->lock); + + // Count threads still in the group (excluding current) + int remaining = 0; + list_for_each_entry(&group->threads, task, group_links) { + if (task != current) { + remaining++; + } + } + + unlock(&group->lock); + unlock(&pids_lock); + + last_remaining = remaining; + + if (remaining == 0) { + break; + } + + // Sleep a bit to let threads exit + struct timespec ts = {0, wait_interval_ms * 1000000L}; + nanosleep(&ts, NULL); + waited_ms += wait_interval_ms; + } + + if (waited_ms >= max_wait_ms) { + // Threads are stuck in blocking syscalls and won't exit. + printk("SAFETY-VALVE[exit]: pid=%d do_exit_group waited %dms, %d threads still stuck → force kill\n", + current->pid, waited_ms, last_remaining); + + // Signal stuck threads with SIGUSR1 repeatedly. + // Don't use pthread_cancel — it can corrupt malloc state if the + // thread is cancelled inside malloc/free. + for (int attempt = 0; attempt < 3; attempt++) { + lock(&pids_lock); + lock(&group->lock); + int still_alive = 0; + list_for_each_entry(&group->threads, task, group_links) { + if (task != current && !task->exiting) { + still_alive++; + cpu_poke(&task->cpu); + if (task->thread) + pthread_kill(task->thread, SIGUSR1); + } + } + unlock(&group->lock); + unlock(&pids_lock); + if (still_alive == 0) break; + struct timespec ts2 = {0, 50 * 1000000L}; // 50ms + nanosleep(&ts2, NULL); + } + + // If threads are truly stuck in uninterruptible host syscalls, + // we accept the leak rather than risking heap corruption. + // Mark them as exiting and remove from the thread group list so + // that exit_tgroup() sees the group as dead and notifies the parent. + lock(&pids_lock); + lock(&group->lock); + int leaked = 0; + struct task *task_tmp; + list_for_each_entry_safe(&group->threads, task, task_tmp, group_links) { + if (task != current && !task->exiting) { + task->exiting = true; + list_remove(&task->group_links); + // Release resources so pipes get EOF and memory is freed. + if (task->sighand != NULL) { + sighand_release(task->sighand); + task->sighand = NULL; + } + // [T-ish-mem-uaf-user-write / T-ish-mm-leak-refcount-handoff] + // DO NOT mm_release() a stuck thread's mm HERE. This thread + // is, by definition, still running inside an uninterruptible + // host syscall (e.g. sys_read → user_write blocked on a + // pipe) and may still hold mem->lock and be about to + // dereference task->mem. Freeing the mm now is a + // use-after-free (EXC_BAD_ACCESS at 0x38 = offsetof(struct + // mem, lock)). So keep task->mm/task->mem intact for now, but + // DEFER the release to this thread's own pthread cleanup + // handler (task_run_current), which runs only after the + // thread has left the read_wrlock critical section — so it + // both avoids the UAF and, unlike the old "accept the leak" + // path, actually reclaims the whole guest address space once + // the host pthread finally terminates. If the thread instead + // unblocks and re-enters do_exit(), that mm_release()s and + // clears the flag, so cleanup won't double-free. + task->mm_release_deferred = true; + if (task->files != NULL) { + fdtable_release(task->files); + task->files = NULL; + } + if (task->fs != NULL) { + fs_info_release(task->fs); + task->fs = NULL; + } + leaked++; + } + } + unlock(&group->lock); + unlock(&pids_lock); + if (leaked > 0) + printk("SAFETY-VALVE[exit]: pid=%d leaked %d stuck host threads\n", + current->pid, leaked); + } else { + + // Give extra time for pthread cleanup on host system + // This ensures: + // 1. pthread_exit() completes for all threads + // 2. TLS destructors run + // 3. Host malloc/arena cleanup happens + // 4. Stack unwinding completes (glibc on ARM64) + struct timespec extra_delay = {0, 50 * 1000000L}; // 50ms for pthread cleanup + nanosleep(&extra_delay, NULL); + + platform_release_thread_memory_pressure(); + } + + lock(&pids_lock); + lock(&group->lock); + } + + unlock(&group->lock); + unlock(&pids_lock); + + do_exit(status); +} + +// always called from init process +static void halt_system(void) { + int max_iterations = 10; // Timeout: wait maximum 10 seconds + for (int state = 0; state < 3; state++) { + int tasks_found = 0; + for (int i = 2; i < MAX_PID; i++) { + struct task *task = pid_get_task(i); + if (task != NULL) { + tasks_found++; + switch (state) { + case 0: + deliver_signal(task, SIGTERM_, SIGINFO_NIL); + break; + case 1: + deliver_signal(task, SIGKILL_, SIGINFO_NIL); + break; + case 2: + pthread_kill(task->thread, SIGTERM); + } + } + } + if (tasks_found == 0) + break; + if (state != 2) { + sleep(1); + // Timeout protection: if we've waited too long, force exit + if (--max_iterations <= 0) { + printk("halt_system: timeout after 10 seconds, %d tasks remaining\n", tasks_found); + break; + } + } + } + + // unmount all filesystems + lock(&mounts_lock); + struct mount *mount, *tmp; + list_for_each_entry_safe(&mounts, mount, tmp, mounts) { + mount_remove(mount); + } + unlock(&mounts_lock); + + // Restore host terminal settings before exiting. + // _exit() does not call atexit handlers, so we must do this explicitly. + extern void restore_termios(void); + restore_termios(); + + // Force exit the entire host process. Orphaned guest threads + // (stuck in JIT loops after do_exit_group force cleanup) keep + // the host process alive indefinitely. _exit is safe here since + // init dying means we're shutting down completely. + _exit(0); +} + +dword_t sys_exit(dword_t status) { + STRACE("exit(%d)\n", status); + do_exit(status << 8); +} + +dword_t sys_exit_group(dword_t status) { + STRACE("exit_group(%d)\n", status); + do_exit_group(status << 8); +} + +#define WNOHANG_ (1 << 0) +#define WUNTRACED_ (1 << 1) +#define WEXITED_ (1 << 2) +#define WCONTINUED_ (1 << 3) +#define WNOWAIT_ (1 << 24) +#define __WALL_ (1 << 30) + +#define P_ALL_ 0 +#define P_PID_ 1 +#define P_PGID_ 2 + +// returns false if the task cannot be reaped and true if the task was reaped +static bool reap_if_zombie(struct task *task, struct siginfo_ *info_out, struct rusage_ *rusage_out, int options) { + if (!task->zombie) + return false; + lock(&task->group->lock); + + dword_t exit_code = task->exit_code; + if (task->group->doing_group_exit) + exit_code = task->group->group_exit_code; + info_out->child.status = exit_code; + + struct rusage_ rusage = task->group->rusage; + if (!(options & WNOWAIT_)) { + lock(¤t->group->lock); + rusage_add(¤t->group->children_rusage, &rusage); + unlock(¤t->group->lock); + } + if (rusage_out != NULL) + *rusage_out = rusage; + + unlock(&task->group->lock); + + // WNOWAIT means don't destroy the child, instead leave it so it could be waited for again. + if (options & WNOWAIT_) + return true; + + // tear down group + cond_destroy(&task->group->child_exit); + task_leave_session(task); + list_remove(&task->group->pgroup); + free(task->group); + + task_destroy(task); + return true; +} + +static bool notify_if_stopped(struct task *task, struct siginfo_ *info_out) { + lock(&task->group->lock); + bool stopped = task->group->stopped; + unlock(&task->group->lock); + if (!stopped || task->group->group_exit_code == 0) + return false; + dword_t exit_code = task->group->group_exit_code; + task->group->group_exit_code = 0; + info_out->child.status = exit_code; + return true; +} + +static bool reap_if_needed(struct task *task, struct siginfo_ *info_out, struct rusage_ *rusage_out, int options) { + assert(task_is_leader(task)); + if ((options & WUNTRACED_ && notify_if_stopped(task, info_out)) || + (options & WEXITED_ && reap_if_zombie(task, info_out, rusage_out, options))) { + info_out->sig = SIGCHLD_; + return true; + } + lock(&task->ptrace.lock); + if (task->ptrace.stopped && task->ptrace.signal) { + // I had this code here because it made something work, but it's now + // making GDB think we support events (we don't). I can't remember what + // it fixed but until then commenting it out for now. + info_out->child.status = /* task->ptrace.trap_event << 16 |*/ task->ptrace.signal << 8 | 0x7f; + task->ptrace.signal = 0; + unlock(&task->ptrace.lock); + return true; + } + unlock(&task->ptrace.lock); + return false; +} + +int do_wait(int idtype, pid_t_ id, struct siginfo_ *info, struct rusage_ *rusage, int options) { + if (idtype != P_ALL_ && idtype != P_PID_ && idtype != P_PGID_) + return _EINVAL; + if (options & ~(WNOHANG_|WUNTRACED_|WEXITED_|WCONTINUED_|WNOWAIT_|__WALL_)) + return _EINVAL; + + lock(&pids_lock); + int err; + bool got_signal = false; + +retry: + ; + if (idtype != P_PID_) { + // look for a zombie child + bool no_children = true; + struct task *parent; + list_for_each_entry(¤t->group->threads, parent, group_links) { + struct task *task; + list_for_each_entry(¤t->children, task, siblings) { + if (!task_is_leader(task)) + continue; + if (idtype == P_PGID_ && task->group->pgid != id) + continue; + no_children = false; + info->child.pid = task->pid; + if (reap_if_needed(task, info, rusage, options)) + goto found_something; + } + } + if (no_children) { + err = _ECHILD; + goto error; + } + } else { + // check if this child is a zombie + struct task *task = pid_get_task_zombie(id); + err = _ECHILD; + if (task == NULL || task->parent == NULL || task->parent->group != current->group) + goto error; + task = task->group->leader; + info->child.pid = id; + if (reap_if_needed(task, info, rusage, options)) + goto found_something; + } + + // WNOHANG leaves the info in an implementation-defined state. set the pid + // to 0 so wait4 can pass that along correctly. + info->child.pid = 0; + if (options & WNOHANG_) { + info->sig = SIGCHLD_; + goto found_something; + } + + err = _EINTR; + if (got_signal) + goto error; + + // no matching zombie found, wait for one. + // Use a bounded 1-second timeout to work around macOS condvar issues + // (pthread_cond_wait can block forever under thread contention). + current->blocking = true; + { + struct timespec waitpid_timeout = {.tv_sec = 1, .tv_nsec = 0}; + int wait_err = wait_for(¤t->group->child_exit, &pids_lock, &waitpid_timeout); + if (wait_err == _EINTR) { + // Signal received during wait. A timeout is expected here: wait4 + // polls once per second to avoid host condvar stalls and must not + // be reported to the guest as EINTR. + got_signal = true; + } + } + current->blocking = false; + { + // Update last_progress_ns: waitpid is actively polling for a child, + // this is real work (not a stuck thread). Prevents the poll_wait + // safety valve from killing a parent waiting for a long-running child. + struct timespec _ts; + clock_gettime(CLOCK_MONOTONIC, &_ts); + uint64_t now = (uint64_t)_ts.tv_sec * 1000000000ULL + _ts.tv_nsec; + current->last_unblocked_ns = now; + atomic_store_explicit(¤t->group->last_progress_ns, now, + memory_order_relaxed); + } + goto retry; + + info->sig = SIGCHLD_; +found_something: + unlock(&pids_lock); + return 0; + +error: + unlock(&pids_lock); + return err; +} + +dword_t sys_waitid(int_t idtype, pid_t_ id, addr_t info_addr, int_t options) { + STRACE("waitid(%d, %d, %#x, %#x)", idtype, id, info_addr, options); + struct siginfo_ info = {}; + int_t res = do_wait(idtype, id, &info, NULL, options); + if (res < 0 || (res == 0 && info.child.pid == 0)) + return res; + if (info_addr != 0 && user_put(info_addr, info)) + return _EFAULT; + return 0; +} + +dword_t sys_wait4(pid_t_ id, addr_t status_addr, dword_t options, addr_t rusage_addr) { + STRACE("wait4(%d, %#x, %#x, %#x)", id, status_addr, options, rusage_addr); + if (options & WNOWAIT_) + return _EINVAL; + + int idtype; + if (id > 0) + idtype = P_PID_; + else if (id == -1) + idtype = P_ALL_; + else { + idtype = P_PGID_; + if (id == 0) + id = current->group->pgid; + else + id = -id; + } + + struct siginfo_ info = {.child.pid = 0xbaba}; + struct rusage_ rusage; + int_t res = do_wait(idtype, id, &info, &rusage, options | WEXITED_); + if (res < 0 || (res == 0 && info.child.pid == 0)) + return res; + if (status_addr != 0 && user_put(status_addr, info.child.status)) + return _EFAULT; + if (rusage_addr != 0 && user_put(rusage_addr, rusage)) + return _EFAULT; + return info.child.pid; +} + +dword_t sys_waitpid(pid_t_ pid, addr_t status_addr, dword_t options) { + return sys_wait4(pid, status_addr, options, 0); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/fork.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/fork.c new file mode 100644 index 0000000000..6d74d32a4a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/fork.c @@ -0,0 +1,287 @@ +#include <time.h> +#include <stddef.h> +#include "debug.h" +#include "kernel/task.h" +#include "fs/fd.h" +#include "kernel/calls.h" +#include "fs/tty.h" +#include "kernel/mm.h" +#include "kernel/ptrace.h" + +// Architecture-specific register access for fork/clone +#if defined(GUEST_ARM64) +#define CPU_SP(cpu) ((cpu).sp) +#define CPU_RETVAL(cpu) ((cpu).regs[0]) +#else +#define CPU_SP(cpu) ((cpu).esp) +#define CPU_RETVAL(cpu) ((cpu).eax) +#endif + +#define CSIGNAL_ 0x000000ff +#define CLONE_VM_ 0x00000100 +#define CLONE_FS_ 0x00000200 +#define CLONE_FILES_ 0x00000400 +#define CLONE_SIGHAND_ 0x00000800 +#define CLONE_PTRACE_ 0x00002000 +#define CLONE_VFORK_ 0x00004000 +#define CLONE_PARENT_ 0x00008000 +#define CLONE_THREAD_ 0x00010000 +#define CLONE_NEWNS_ 0x00020000 +#define CLONE_SYSVSEM_ 0x00040000 +#define CLONE_SETTLS_ 0x00080000 +#define CLONE_PARENT_SETTID_ 0x00100000 +#define CLONE_CHILD_CLEARTID_ 0x00200000 +#define CLONE_DETACHED_ 0x00400000 +#define CLONE_UNTRACED_ 0x00800000 +#define CLONE_CHILD_SETTID_ 0x01000000 +#define CLONE_NEWCGROUP_ 0x02000000 +#define CLONE_NEWUTS_ 0x04000000 +#define CLONE_NEWIPC_ 0x08000000 +#define CLONE_NEWUSER_ 0x10000000 +#define CLONE_NEWPID_ 0x20000000 +#define CLONE_NEWNET_ 0x40000000 +#define CLONE_IO_ 0x80000000 +#define IMPLEMENTED_FLAGS (CLONE_VM_|CLONE_FILES_|CLONE_FS_|CLONE_SIGHAND_|CLONE_SYSVSEM_|CLONE_VFORK_|CLONE_THREAD_|\ + CLONE_SETTLS_|CLONE_CHILD_SETTID_|CLONE_PARENT_SETTID_|CLONE_CHILD_CLEARTID_|CLONE_DETACHED_) + +static struct tgroup *tgroup_copy(struct tgroup *old_group) { + struct tgroup *group = malloc(sizeof(struct tgroup)); + *group = *old_group; + list_init(&group->threads); + list_add(&old_group->pgroup, &group->pgroup); + list_add(&old_group->session, &group->session); + if (group->tty) { + lock(&group->tty->lock); + group->tty->refcount++; + unlock(&group->tty->lock); + } + group->itimer = NULL; + group->doing_group_exit = false; + group->children_rusage = (struct rusage_) {}; + { + struct timespec _ts; + clock_gettime(CLOCK_MONOTONIC, &_ts); + atomic_store_explicit(&group->last_progress_ns, + (uint64_t)_ts.tv_sec * 1000000000ULL + _ts.tv_nsec, + memory_order_relaxed); + } + cond_init(&group->child_exit); + cond_init(&group->stopped_cond); + lock_init(&group->lock); + return group; +} + +static int copy_task(struct task *task, dword_t flags, addr_t stack, addr_t ptid_addr, addr_t tls_addr, addr_t ctid_addr) { + task->vfork = NULL; + if (stack != 0) + CPU_SP(task->cpu) = stack; + + int err; + struct mm *mm = task->mm; + if (flags & CLONE_VM_) { + mm_retain(mm); + } else { + task_set_mm(task, mm_copy(mm)); + } + + if (flags & CLONE_FILES_) { + task->files->refcount++; + } else { + task->files = fdtable_copy(task->files); + if (IS_ERR(task->files)) { + err = PTR_ERR(task->files); + goto fail_free_mem; + } + } + + err = _ENOMEM; + if (flags & CLONE_FS_) { + task->fs->refcount++; + } else { + task->fs = fs_info_copy(task->fs); + if (task->fs == NULL) + goto fail_free_files; + } + + if (flags & CLONE_SIGHAND_) { + task->sighand->refcount++; + } else { + task->sighand = sighand_copy(task->sighand); + if (task->sighand == NULL) + goto fail_free_fs; + } + + // Linux keeps sigaltstack state per thread. fork-style children inherit the + // parent's alternate stack, but clone(CLONE_VM) children (normal pthreads, + // including Go M threads) start with it disabled unless CLONE_VFORK is used. + if ((flags & CLONE_VM_) && !(flags & CLONE_VFORK_)) { + task->altstack = 0; + task->altstack_size = 0; + } + + struct tgroup *old_group = task->group; + lock(&pids_lock); + lock(&old_group->lock); + if (!(flags & CLONE_THREAD_)) { + task->group = tgroup_copy(old_group); + task->group->leader = task; + task->tgid = task->pid; + } + list_add(&task->group->threads, &task->group_links); + unlock(&old_group->lock); + unlock(&pids_lock); + + if (flags & CLONE_SETTLS_) { +#if defined(GUEST_ARM64) + // On ARM64, the TLS argument is the actual TLS pointer value (for TPIDR_EL0), + // not a pointer to a descriptor structure. + task->cpu.tls_ptr = tls_addr; +#else + err = task_set_thread_area(task, tls_addr); + if (err < 0) + goto fail_free_sighand; +#endif + } + + err = _EFAULT; + if (flags & CLONE_CHILD_SETTID_) + if (user_put_task(task, ctid_addr, task->pid)) + goto fail_free_sighand; + if (flags & CLONE_PARENT_SETTID_) + if (user_put(ptid_addr, task->pid)) + goto fail_free_sighand; + if (flags & CLONE_CHILD_CLEARTID_) + task->clear_tid = ctid_addr; + task->exit_signal = flags & CSIGNAL_; + + // remember to do CLONE_SYSVSEM + return 0; + +fail_free_sighand: + sighand_release(task->sighand); +fail_free_fs: + fs_info_release(task->fs); +fail_free_files: + fdtable_release(task->files); +fail_free_mem: + mm_release(task->mm); + return err; +} + +dword_t sys_clone(dword_t flags, addr_t stack, addr_t ptid, addr_t tls, addr_t ctid) { + STRACE("clone(0x%x, 0x%x, 0x%x, 0x%x, 0x%x)", flags, stack, ptid, tls, ctid); + if (flags & ~CSIGNAL_ & ~IMPLEMENTED_FLAGS) { + FIXME("unimplemented clone flags 0x%x", flags & ~CSIGNAL_ & ~IMPLEMENTED_FLAGS); + return _EINVAL; + } + if (flags & CLONE_SIGHAND_ && !(flags & CLONE_VM_)) + return _EINVAL; + if (flags & CLONE_THREAD_ && !(flags & CLONE_SIGHAND_)) + return _EINVAL; + + struct task *task = task_create_(current); + if (task == NULL) + return _ENOMEM; + int err = copy_task(task, flags, stack, ptid, tls, ctid); + if (err < 0) { + // FIXME: there is a window between task_create_ and task_destroy where + // some other thread could get a pointer to the task. + // FIXME: task_destroy doesn't free all aspects of the task, which + // could cause leaks + lock(&pids_lock); + task_destroy(task); + unlock(&pids_lock); + return err; + } + CPU_RETVAL(task->cpu) = 0; + + struct vfork_info vfork; + if (flags & CLONE_VFORK_) { + lock_init(&vfork.lock); + cond_init(&vfork.cond); + vfork.done = false; + task->vfork = &vfork; + } + + // task might be destroyed by the time we finish, so save the pid + pid_t pid = task->pid; + + if (current->ptrace.traced) { + current->ptrace.trap_event = PTRACE_EVENT_FORK_; + send_signal(current, SIGTRAP_, SIGINFO_NIL); + } + + task_start(task); + + if (flags & CLONE_VFORK_) { + lock(&vfork.lock); + while (!vfork.done) + // FIXME this should stop waiting if a fatal signal is received + wait_for_ignore_signals(&vfork.cond, &vfork.lock, NULL); + unlock(&vfork.lock); + lock(&task->general_lock); + task->vfork = NULL; + unlock(&task->general_lock); + cond_destroy(&vfork.cond); + } + + return pid; +} + +struct clone_args_ { + qword_t flags; + qword_t pidfd; + qword_t child_tid; + qword_t parent_tid; + qword_t exit_signal; + qword_t stack; + qword_t stack_size; + qword_t tls; + qword_t set_tid; + qword_t set_tid_size; + qword_t cgroup; +}; + +dword_t sys_clone3(addr_t args_addr, size_t size) { + STRACE("clone3(%#llx, %llu)", (unsigned long long)args_addr, (unsigned long long)size); + + if (size < offsetof(struct clone_args_, exit_signal) + sizeof(qword_t)) + return _EINVAL; + if (size > sizeof(struct clone_args_)) + size = sizeof(struct clone_args_); + + struct clone_args_ args = {}; + if (user_read(args_addr, &args, size)) + return _EFAULT; + + if (args.pidfd != 0 || args.set_tid != 0 || args.set_tid_size != 0 || args.cgroup != 0) + return _EINVAL; + if (args.exit_signal & ~0xffULL) + return _EINVAL; + + addr_t stack = (addr_t) args.stack; + if (args.stack_size != 0) + stack += (addr_t) args.stack_size; + + dword_t flags = (dword_t) args.flags | (dword_t) args.exit_signal; + return sys_clone(flags, stack, (addr_t) args.parent_tid, (addr_t) args.tls, (addr_t) args.child_tid); +} + +dword_t sys_fork() { + return sys_clone(SIGCHLD_, 0, 0, 0, 0); +} + +dword_t sys_vfork() { + return sys_clone(CLONE_VFORK_ | CLONE_VM_ | SIGCHLD_, 0, 0, 0, 0); +} + +void vfork_notify(struct task *task) { + lock(&task->general_lock); + if (task->vfork) { + lock(&task->vfork->lock); + task->vfork->done = true; + notify(&task->vfork->cond); + unlock(&task->vfork->lock); + } + unlock(&task->general_lock); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/fs.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/fs.c new file mode 100644 index 0000000000..9122f8f13d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/fs.c @@ -0,0 +1,1513 @@ +#include "debug.h" +#include <string.h> +#include <sys/stat.h> +#include <unistd.h> +#include "kernel/calls.h" +#include "kernel/errno.h" +#include "kernel/task.h" +#include "kernel/fs.h" +#include "fs/fd.h" +#include "fs/path.h" +#include "fs/dev.h" +#include "fs/real.h" +#include "platform/platform.h" + +static struct fd *at_fd(fd_t f) { + if (f == AT_FDCWD_) + return AT_PWD; + return f_get(f); +} + +static void apply_umask(mode_t_ *mode) { + struct fs_info *fs = current->fs; + lock(&fs->lock); + *mode &= ~fs->umask; + unlock(&fs->lock); +} + +int access_check(struct statbuf *stat, int check) { + if (superuser()) return 0; + if (check == 0) return 0; + // Align check with the correct bits in mode + if (current->euid == stat->uid) { + check <<= 6; + } else if (current->egid == stat->gid) { + check <<= 3; + } + if (!(stat->mode & check)) + return _EACCES; + return 0; +} + +// TODO ENAMETOOLONG + +#define AT_EACCESS_ 0x200 +dword_t sys_access(addr_t path_addr, dword_t mode) { + return sys_faccessat(AT_FDCWD_, path_addr, mode, 0); +} +dword_t sys_faccessat(fd_t at_f, addr_t path_addr, mode_t_ mode, dword_t flags) { + char path[MAX_PATH]; + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + struct fd *at = at_fd(at_f); + if (at == NULL) + return _EBADF; + STRACE("faccessat(%d, \"%s\", 0x%x, %d)", at_f, path, mode, flags); + + if (flags & AT_EACCESS_) + return generic_accessat(at, path, mode); + + uid_t_ uid_tmp = current->euid; + uid_t_ gid_tmp = current->egid; + current->euid = current->uid; + current->egid = current->gid; + int err = generic_accessat(at, path, mode); + current->euid = uid_tmp; + current->egid = gid_tmp; + return err; +} + +fd_t sys_openat(fd_t at_f, addr_t path_addr, dword_t flags, mode_t_ mode) { + char path[MAX_PATH]; + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + STRACE("openat(%d, \"%s\", 0x%x, 0x%x)", at_f, path, flags, mode); + + if (flags & O_CREAT_) + apply_umask(&mode); + + struct fd *at = at_fd(at_f); + if (at == NULL) { + return _EBADF; + } + struct fd *fd = generic_openat(at, path, flags, mode); + if (IS_ERR(fd)) { + return PTR_ERR(fd); + } + return f_install(fd, flags); +} + +fd_t sys_open(addr_t path_addr, dword_t flags, mode_t_ mode) { + return sys_openat(AT_FDCWD_, path_addr, flags, mode); +} + +struct open_how_ { + uint64_t flags; + uint64_t mode; + uint64_t resolve; +}; + +fd_t sys_openat2(fd_t at_f, addr_t path_addr, addr_t how_addr, size_t size) { + STRACE("openat2(%d, %#x, %#x, %#zx)", at_f, path_addr, how_addr, size); + if (size < sizeof(struct open_how_)) + return _EINVAL; + struct open_how_ how; + if (user_read(how_addr, &how, sizeof(how))) + return _EFAULT; + // Resolve flags are stricter path-walk constraints. Treat unsupported + // constraints as EINVAL rather than silently ignoring security semantics. + if (how.resolve != 0) + return _EINVAL; + return sys_openat(at_f, path_addr, (dword_t)how.flags, (mode_t_)how.mode); +} + +dword_t sys_faccessat2(fd_t at_f, addr_t path_addr, mode_t_ mode, dword_t flags) { + return sys_faccessat(at_f, path_addr, mode, flags); +} + +#define MFD_CLOEXEC_ 0x0001U +#define MFD_ALLOW_SEALING_ 0x0002U + +int_t sys_memfd_create(addr_t name_addr, uint_t flags) { + char name[256]; + if (name_addr != 0 && user_read_string(name_addr, name, sizeof(name))) + return _EFAULT; + STRACE("memfd_create(\"%s\", %#x)", name_addr ? name : "", flags); + if (flags & ~(MFD_CLOEXEC_ | MFD_ALLOW_SEALING_)) + return _EINVAL; + int host_fd = platform_create_shared_memory_fd(0); + if (host_fd < 0) + return errno_map(); + struct fd *fd = adhoc_fd_create(&realfs_fdops); + if (fd == NULL) { + close(host_fd); + return _ENOMEM; + } + fd->real_fd = host_fd; + fd->stat.mode = S_IFREG | 0600; + return f_install(fd, (flags & MFD_CLOEXEC_) ? O_CLOEXEC_ : 0); +} + +dword_t sys_readlinkat(fd_t at_f, addr_t path_addr, addr_t buf_addr, dword_t bufsize) { + char path[MAX_PATH]; + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + STRACE("readlinkat(%d, \"%s\", %#x, %#x)", at_f, path, buf_addr, bufsize); + struct fd *at = at_fd(at_f); + if (at == NULL) + return _EBADF; + char buf[bufsize]; + ssize_t size = generic_readlinkat(at, path, buf, bufsize); + if (size >= 0) { + STRACE(" \"%.*s\"", size, buf); + if (user_write(buf_addr, buf, size)) + return _EFAULT; + } + return size; +} + +dword_t sys_readlink(addr_t path_addr, addr_t buf_addr, dword_t bufsize) { + return sys_readlinkat(AT_FDCWD_, path_addr, buf_addr, bufsize); +} + +dword_t sys_linkat(fd_t src_at_f, addr_t src_addr, fd_t dst_at_f, addr_t dst_addr) { + char src[MAX_PATH]; + if (user_read_string(src_addr, src, sizeof(src))) + return _EFAULT; + char dst[MAX_PATH]; + if (user_read_string(dst_addr, dst, sizeof(dst))) + return _EFAULT; + STRACE("linkat(%d, \"%s\", %d, \"%s\")", src_at_f, src, dst_at_f, dst); + struct fd *src_at = at_fd(src_at_f); + if (src_at == NULL) + return _EBADF; + struct fd *dst_at = at_fd(dst_at_f); + if (dst_at == NULL) + return _EBADF; + return generic_linkat(src_at, src, dst_at, dst); +} + +dword_t sys_link(addr_t src_addr, addr_t dst_addr) { + return sys_linkat(AT_FDCWD_, src_addr, AT_FDCWD_, dst_addr); +} + +#define AT_REMOVEDIR_ 0x200 +dword_t sys_unlinkat(fd_t at_f, addr_t path_addr, int_t flags) { + char path[MAX_PATH]; + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + STRACE("unlinkat(%d, \"%s\", %d)", at_f, path, flags); + struct fd *at = at_fd(at_f); + if (at == NULL) + return _EBADF; + if (flags & AT_REMOVEDIR_) + return generic_rmdirat(at, path); + else + return generic_unlinkat(at, path); +} + +dword_t sys_unlink(addr_t path_addr) { + return sys_unlinkat(AT_FDCWD_, path_addr, 0); +} + +dword_t sys_renameat2(fd_t src_at_f, addr_t src_addr, fd_t dst_at_f, addr_t dst_addr, int_t flags) { + if (flags != 0) + return _EINVAL; + char src[MAX_PATH]; + if (user_read_string(src_addr, src, sizeof(src))) + return _EFAULT; + char dst[MAX_PATH]; + if (user_read_string(dst_addr, dst, sizeof(dst))) + return _EFAULT; + STRACE("renameat(%d, \"%s\", %d, \"%s\")", src_at_f, src, dst_at_f, dst); + struct fd *src_at = at_fd(src_at_f); + if (src_at == NULL) + return _EBADF; + struct fd *dst_at = at_fd(dst_at_f); + if (dst_at == NULL) + return _EBADF; + return generic_renameat(src_at, src, dst_at, dst); +} + +dword_t sys_renameat(fd_t src_at_f, addr_t src_addr, fd_t dst_at_f, addr_t dst_addr) { + return sys_renameat2(src_at_f, src_addr, dst_at_f, dst_addr, 0); +} + +dword_t sys_rename(addr_t src_addr, addr_t dst_addr) { + return sys_renameat2(AT_FDCWD_, src_addr, AT_FDCWD_, dst_addr, 0); +} + +dword_t sys_symlinkat(addr_t target_addr, fd_t at_f, addr_t link_addr) { + char target[MAX_PATH]; + if (user_read_string(target_addr, target, sizeof(target))) + return _EFAULT; + char link[MAX_PATH]; + if (user_read_string(link_addr, link, sizeof(link))) + return _EFAULT; + STRACE("symlinkat(\"%s\", %d, \"%s\")", target, at_f, link); + struct fd *at = at_fd(at_f); + if (at == NULL) + return _EBADF; + return generic_symlinkat(target, at, link); +} + +dword_t sys_symlink(addr_t target_addr, addr_t link_addr) { + return sys_symlinkat(target_addr, AT_FDCWD_, link_addr); +} + +dword_t sys_mknodat(fd_t at_f, addr_t path_addr, mode_t_ mode, dev_t_ dev) { + char path[MAX_PATH]; + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + STRACE("mknodat(%d, \"%s\", %#x, %#x)", at_f, path, mode, dev); + apply_umask(&mode); + struct fd *at = at_fd(at_f); + if (at == NULL) + return _EBADF; + return generic_mknodat(at, path, mode, dev); +} + +dword_t sys_mknod(addr_t path_addr, mode_t_ mode, dev_t_ dev) { + return sys_mknodat(AT_FDCWD_, path_addr, mode, dev); +} + +static ssize_t sys_read_buf(fd_t fd_no, void *buf, size_t size) { + struct fd *fd = f_get(fd_no); + if (fd == NULL) + return _EBADF; + if (S_ISDIR(fd->type)) + return _EISDIR; + + ssize_t res; + if (fd->ops->read) { + res = fd->ops->read(fd, buf, size); + } else if (fd->ops->pread) { + res = fd->ops->pread(fd, buf, size, fd->offset); + if (res > 0) { + fd->ops->lseek(fd, res, LSEEK_CUR); + } + } else { + return _EBADF; + } + + if (res >= 0) { + size_t print_size = res; + if (print_size > 100) print_size = 100; + STRACE(" \"%.*s\"", print_size, buf); + } + return res; +} + +dword_t sys_read(fd_t fd_no, addr_t buf_addr, dword_t size) { + STRACE("read(%d, 0x%x, %d)", fd_no, buf_addr, size); + char *buf = (char *) malloc(size); + if (buf == NULL) + return _ENOMEM; + int_t res = sys_read_buf(fd_no, buf, size); + if (res >= 0) { + if (user_write(buf_addr, buf, res)) + res = _EFAULT; + } + free(buf); + return res; +} + +static ssize_t sys_write_buf(fd_t fd_no, void *buf, size_t size) { + struct fd *fd = f_get(fd_no); + if (fd == NULL) + return _EBADF; + + ssize_t res; + if (fd->ops->write) { + res = fd->ops->write(fd, buf, size); + } else if (fd->ops->pwrite) { + res = fd->ops->pwrite(fd, buf, size, fd->offset); + if (res > 0) { + fd->ops->lseek(fd, res, LSEEK_CUR); + } + } else { + return _EBADF; + } + return res; +} + +dword_t sys_write(fd_t fd_no, addr_t buf_addr, dword_t size) { + // FIXME this is a DOS vector, should ideally use vectorized I/O + char *buf = malloc(size); + if (buf == NULL) + return _ENOMEM; + dword_t res = _EFAULT; + if (user_read(buf_addr, buf, size)) + goto out; + + size_t print_size = size; + if (print_size > 100) print_size = 100; + STRACE("write(%d, \"%.*s\", %d)", fd_no, print_size, buf, size); + + res = sys_write_buf(fd_no, buf, size); + +out: + free(buf); + return res; +} + +// The vector operations work by flattening the vector into a malloc buffer. +// This at least isn't much worse than what it was before, which copied each +// element of the vector into a malloc buffer. The perfect solution would be to +// construct a vector with an entry for each page of the buffer. I haven't done +// that yet because it's more work and the efficiency gain from that is dwarfed +// by the inefficiency of the emulator. + +static struct iovec_ *read_iovec(addr_t iovec_addr, unsigned iovec_count) { +#ifdef GUEST_ARM64 + // ARM64 uses 64-bit iovec structure (16 bytes per entry) + // We read the 64-bit version and convert to 32-bit for internal use + size_t iovec64_size = sizeof(struct iovec64_) * iovec_count; + struct iovec64_ *iovec64 = malloc(iovec64_size); + if (iovec64 == NULL) + return ERR_PTR(_ENOMEM); + if (user_read(iovec_addr, iovec64, iovec64_size)) { + free(iovec64); + return ERR_PTR(_EFAULT); + } + + // Convert to 32-bit iovec for internal processing + struct iovec_ *iovec = malloc(sizeof(struct iovec_) * iovec_count); + if (iovec == NULL) { + free(iovec64); + return ERR_PTR(_ENOMEM); + } + for (unsigned i = 0; i < iovec_count; i++) { + iovec[i].base = (addr_t)iovec64[i].base; + iovec[i].len = (uint_t)iovec64[i].len; + } + free(iovec64); + return iovec; +#else + dword_t iovec_size = sizeof(struct iovec_) * iovec_count; + struct iovec_ *iovec = malloc(iovec_size); + if (iovec == NULL) + return ERR_PTR(_ENOMEM); + if (user_read(iovec_addr, iovec, iovec_size)) { + free(iovec); + return ERR_PTR(_EFAULT); + } + return iovec; +#endif +} + +static ssize_t iovec_size(struct iovec_ *iovec, unsigned iovec_count) { + size_t size = 0; + for (unsigned i = 0; i < iovec_count; i++) + size += iovec[i].len; + return size; +} + +dword_t sys_readv(fd_t fd_no, addr_t iovec_addr, dword_t iovec_count) { + STRACE("readv(%d, %#x, %d)", fd_no, iovec_addr, iovec_count); + struct iovec_ *iovec = read_iovec(iovec_addr, iovec_count); + if (IS_ERR(iovec)) + return PTR_ERR(iovec); + size_t io_size = iovec_size(iovec, iovec_count); + char *buf = malloc(io_size); + if (buf == NULL) { + free(iovec); + return _ENOMEM; + } + ssize_t res = sys_read_buf(fd_no, buf, io_size); + if (res < 0) + goto error; + + size_t offset = 0; + for (unsigned i = 0; i < iovec_count; i++) { + size_t print_size = iovec[i].len; + if (print_size > 100) print_size = 100; + STRACE(" {\"%.*s\", %u}", print_size, buf + offset, iovec[i].len); + + if (user_write(iovec[i].base, buf + offset, iovec[i].len)) { + res = _EFAULT; + goto error; + } + offset += iovec[i].len; + } + +error: + free(buf); + free(iovec); + return res; +} + +static dword_t read_iovec_to_buf(addr_t iovec_addr, dword_t iovec_count, + struct iovec_ **iovec_out, char **buf_out, + size_t *size_out) { + struct iovec_ *iovec = read_iovec(iovec_addr, iovec_count); + if (IS_ERR(iovec)) + return PTR_ERR(iovec); + size_t io_size = iovec_size(iovec, iovec_count); + char *buf = malloc(io_size ? io_size : 1); + if (buf == NULL) { + free(iovec); + return _ENOMEM; + } + + size_t offset = 0; + for (unsigned i = 0; i < iovec_count; i++) { + if (user_read(iovec[i].base, buf + offset, iovec[i].len)) { + free(buf); + free(iovec); + return _EFAULT; + } + + size_t print_size = iovec[i].len; + if (print_size > 100) print_size = 100; + STRACE(" {\"%.*s\", %u}", print_size, buf + offset, iovec[i].len); + offset += iovec[i].len; + } + + *iovec_out = iovec; + *buf_out = buf; + *size_out = io_size; + return 0; +} + +dword_t sys_writev(fd_t fd_no, addr_t iovec_addr, dword_t iovec_count) { + STRACE("writev(%d, %#x, %d)", fd_no, iovec_addr, iovec_count); + struct iovec_ *iovec; + char *buf; + size_t io_size; + dword_t err = read_iovec_to_buf(iovec_addr, iovec_count, &iovec, &buf, &io_size); + if (err != 0) + return err; + + ssize_t res = sys_write_buf(fd_no, buf, io_size); + free(buf); + free(iovec); + return res; +} + +dword_t sys__llseek(fd_t f, dword_t off_high, dword_t off_low, addr_t res_addr, dword_t whence) { + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + if (!fd->ops->lseek) + return _ESPIPE; + lock(&fd->lock); + off_t_ off = ((qword_t) off_high << 32) | off_low; + STRACE("llseek(%d, %lu, %#x, %d)", f, off, res_addr, whence); + off_t_ res = fd->ops->lseek(fd, off, whence); + STRACE(" -> %lu", res); + unlock(&fd->lock); + if (res < 0) + return res; + if (user_put(res_addr, res)) + return _EFAULT; + return 0; +} + +dword_t sys_lseek(fd_t f, dword_t off, dword_t whence) { + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + if (!fd->ops->lseek) + return _ESPIPE; + lock(&fd->lock); + off_t res = fd->ops->lseek(fd, off, whence); + unlock(&fd->lock); + if ((dword_t) res != res) + return _EOVERFLOW; + return res; +} + +// 64-bit lseek for ARM64 +// Returns the new file position directly (not via pointer like _llseek) +qword_t sys_lseek64(fd_t f, sqword_t off, dword_t whence) { + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + if (!fd->ops->lseek) + return _ESPIPE; + lock(&fd->lock); + STRACE("lseek64(%d, %lld, %d)", f, (long long)off, whence); + off_t_ res = fd->ops->lseek(fd, off, whence); + STRACE(" -> %lld", (long long)res); + unlock(&fd->lock); + return res; +} + +dword_t sys_pread(fd_t f, addr_t buf_addr, dword_t size, off_t_ off) { + STRACE("pread(%d, 0x%x, %d, %d)", f, buf_addr, size, off); + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + char *buf = malloc(size+1); + if (buf == NULL) + return _ENOMEM; + lock(&fd->lock); + ssize_t res; + if (fd->ops->pread) { + res = fd->ops->pread(fd, buf, size, off); + } else { + off_t_ saved_off = fd->ops->lseek(fd, 0, LSEEK_CUR); + if ((res = fd->ops->lseek(fd, off, LSEEK_SET)) < 0) { + goto out; + } + res = fd->ops->read(fd, buf, size); + // This really shouldn't fail. The lseek man page lists these reasons: + // EBADF, ESPIPE: can't happen because the last lseek wouldn't have succeeded. + // EOVERFLOW: can't happen for LSEEK_SET. + // EINVAL: can't happen other than typoing LSEEK_SET, because we know saved_off is not negative. + off_t_ lseek_res = fd->ops->lseek(fd, saved_off, LSEEK_SET); + assert(lseek_res >= 0); + } + if (res >= 0) { + buf[res] = '\0'; + STRACE(" \"%.99s\"", buf); + if (user_write(buf_addr, buf, res)) + res = _EFAULT; + } +out: + unlock(&fd->lock); + free(buf); + return res; +} + +dword_t sys_pwrite(fd_t f, addr_t buf_addr, dword_t size, off_t_ off) { + STRACE("pwrite(%d, 0x%x, %d, %d)", f, buf_addr, size, off); + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + char *buf = malloc(size+1); + if (buf == NULL) + return _ENOMEM; + if (user_read(buf_addr, buf, size)) { + free(buf); + return _EFAULT; + } + lock(&fd->lock); + ssize_t res; + if (fd->ops->pwrite) { + res = fd->ops->pwrite(fd, buf, size, off); + } else { + off_t_ saved_off = fd->ops->lseek(fd, 0, LSEEK_CUR); + if ((res = fd->ops->lseek(fd, off, LSEEK_SET)) >= 0) { + res = fd->ops->write(fd, buf, size); + // This really shouldn't fail. The lseek man page lists these reasons: + // EBADF, ESPIPE: can't happen because the last lseek wouldn't have succeeded. + // EOVERFLOW: can't happen for LSEEK_SET. + // EINVAL: can't happen other than typoing LSEEK_SET, because we know saved_off is not negative. + off_t_ lseek_res = fd->ops->lseek(fd, saved_off, LSEEK_SET); + assert(lseek_res >= 0); + } + } + unlock(&fd->lock); + free(buf); + return res; +} + +static ssize_t fd_pwrite_buf(struct fd *fd, char *buf, size_t size, off_t_ off) { + if (fd->ops->pwrite) + return fd->ops->pwrite(fd, buf, size, off); + if (!fd->ops->lseek || !fd->ops->write) + return _ESPIPE; + off_t_ saved_off = fd->ops->lseek(fd, 0, LSEEK_CUR); + ssize_t res; + if ((res = fd->ops->lseek(fd, off, LSEEK_SET)) >= 0) { + res = fd->ops->write(fd, buf, size); + off_t_ lseek_res = fd->ops->lseek(fd, saved_off, LSEEK_SET); + assert(lseek_res >= 0); + } + return res; +} + +static ssize_t fd_pread_buf(struct fd *fd, char *buf, size_t size, off_t_ off) { + if (fd->ops->pread) + return fd->ops->pread(fd, buf, size, off); + if (!fd->ops->lseek || !fd->ops->read) + return _ESPIPE; + off_t_ saved_off = fd->ops->lseek(fd, 0, LSEEK_CUR); + ssize_t res; + if ((res = fd->ops->lseek(fd, off, LSEEK_SET)) >= 0) { + res = fd->ops->read(fd, buf, size); + off_t_ lseek_res = fd->ops->lseek(fd, saved_off, LSEEK_SET); + assert(lseek_res >= 0); + } + return res; +} + +dword_t sys_pwritev(fd_t fd_no, addr_t iovec_addr, dword_t iovec_count, off_t_ off) { + STRACE("pwritev(%d, %#x, %d, %lld)", fd_no, iovec_addr, iovec_count, (long long)off); + struct fd *fd = f_get(fd_no); + if (fd == NULL) + return _EBADF; + + struct iovec_ *iovec; + char *buf; + size_t io_size; + dword_t err = read_iovec_to_buf(iovec_addr, iovec_count, &iovec, &buf, &io_size); + if (err != 0) + return err; + + lock(&fd->lock); + ssize_t res = fd_pwrite_buf(fd, buf, io_size, off); + unlock(&fd->lock); + + free(buf); + free(iovec); + return res; +} + +dword_t sys_pwritev2(fd_t fd_no, addr_t iovec_addr, dword_t iovec_count, off_t_ off, dword_t flags) { + STRACE("pwritev2(%d, %#x, %d, %lld, %#x)", fd_no, iovec_addr, iovec_count, (long long)off, flags); + if (flags != 0) + return _EOPNOTSUPP; + return sys_pwritev(fd_no, iovec_addr, iovec_count, off); +} + +dword_t sys_preadv(fd_t fd_no, addr_t iovec_addr, dword_t iovec_count, off_t_ off) { + STRACE("preadv(%d, %#x, %d, %lld)", fd_no, iovec_addr, iovec_count, (long long)off); + struct fd *fd = f_get(fd_no); + if (fd == NULL) + return _EBADF; + + struct iovec_ *iovec = read_iovec(iovec_addr, iovec_count); + if (IS_ERR(iovec)) + return PTR_ERR(iovec); + size_t io_size = iovec_size(iovec, iovec_count); + char *buf = malloc(io_size ? io_size : 1); + if (buf == NULL) { + free(iovec); + return _ENOMEM; + } + + lock(&fd->lock); + ssize_t res = fd_pread_buf(fd, buf, io_size, off); + unlock(&fd->lock); + if (res < 0) + goto out; + + size_t offset = 0; + for (unsigned i = 0; i < iovec_count && offset < (size_t)res; i++) { + size_t chunk = iovec[i].len; + if (chunk > (size_t)res - offset) + chunk = (size_t)res - offset; + if (user_write(iovec[i].base, buf + offset, chunk)) { + res = _EFAULT; + goto out; + } + offset += chunk; + } +out: + free(buf); + free(iovec); + return res; +} + +dword_t sys_preadv2(fd_t fd_no, addr_t iovec_addr, dword_t iovec_count, off_t_ off, dword_t flags) { + STRACE("preadv2(%d, %#x, %d, %lld, %#x)", fd_no, iovec_addr, iovec_count, (long long)off, flags); + if (flags != 0) + return _EOPNOTSUPP; + return sys_preadv(fd_no, iovec_addr, iovec_count, off); +} + +static ssize_t process_vm_copy(pid_t_ pid, addr_t local_iov_addr, dword_t local_iovcnt, + addr_t remote_iov_addr, dword_t remote_iovcnt, + dword_t flags, bool write_remote) { + if (flags != 0) + return _EINVAL; + struct iovec_ *local = read_iovec(local_iov_addr, local_iovcnt); + if (IS_ERR(local)) + return PTR_ERR(local); + struct iovec_ *remote = read_iovec(remote_iov_addr, remote_iovcnt); + if (IS_ERR(remote)) { + free(local); + return PTR_ERR(remote); + } + + lock(&pids_lock); + struct task *task = pid_get_task(pid); + unlock(&pids_lock); + if (task == NULL) { + free(local); + free(remote); + return _ESRCH; + } + if (!superuser() && current->euid != task->uid && current->uid != task->uid) { + free(local); + free(remote); + return _EPERM; + } + + char buf[4096]; + size_t li = 0, ri = 0, lo = 0, ro = 0; + ssize_t done = 0; + while (li < local_iovcnt && ri < remote_iovcnt) { + size_t lrem = local[li].len - lo; + size_t rrem = remote[ri].len - ro; + size_t chunk = lrem < rrem ? lrem : rrem; + if (chunk > sizeof(buf)) + chunk = sizeof(buf); + if (chunk == 0) { + if (lrem == 0) { li++; lo = 0; } + if (rrem == 0) { ri++; ro = 0; } + continue; + } + if (write_remote) { + if (user_read(local[li].base + lo, buf, chunk)) + break; + if (user_write_task(task, remote[ri].base + ro, buf, chunk)) + break; + } else { + if (user_read_task(task, remote[ri].base + ro, buf, chunk)) + break; + if (user_write(local[li].base + lo, buf, chunk)) + break; + } + done += chunk; + lo += chunk; + ro += chunk; + if (lo == local[li].len) { li++; lo = 0; } + if (ro == remote[ri].len) { ri++; ro = 0; } + } + + free(local); + free(remote); + return done > 0 ? done : _EFAULT; +} + +ssize_t sys_process_vm_readv(pid_t_ pid, addr_t local_iov_addr, dword_t local_iovcnt, + addr_t remote_iov_addr, dword_t remote_iovcnt, dword_t flags) { + STRACE("process_vm_readv(%d, %#x, %d, %#x, %d, %#x)", pid, local_iov_addr, local_iovcnt, remote_iov_addr, remote_iovcnt, flags); + return process_vm_copy(pid, local_iov_addr, local_iovcnt, remote_iov_addr, remote_iovcnt, flags, false); +} + +ssize_t sys_process_vm_writev(pid_t_ pid, addr_t local_iov_addr, dword_t local_iovcnt, + addr_t remote_iov_addr, dword_t remote_iovcnt, dword_t flags) { + STRACE("process_vm_writev(%d, %#x, %d, %#x, %d, %#x)", pid, local_iov_addr, local_iovcnt, remote_iov_addr, remote_iovcnt, flags); + return process_vm_copy(pid, local_iov_addr, local_iovcnt, remote_iov_addr, remote_iovcnt, flags, true); +} + +static int fd_ioctl(struct fd *fd, dword_t cmd, addr_t arg) { + ssize_t size = -1; + if (fd->ops->ioctl_size) + size = fd->ops->ioctl_size(cmd); + if (size < 0) + return _ENOTTY; + if (size == 0) + return fd->ops->ioctl(fd, cmd, (void *) (long) arg); + + // praying that this won't break + char buf[size]; + if (user_read(arg, buf, size)) + return _EFAULT; + int res = fd->ops->ioctl(fd, cmd, buf); + if (res < 0) + return res; + if (user_write(arg, buf, size)) + return _EFAULT; + return res; +} + +static int set_nonblock(struct fd *fd, addr_t nb_addr) { + dword_t nonblock; + if (user_get(nb_addr, nonblock)) + return _EFAULT; + int flags = fd_getflags(fd); + if (nonblock) + flags |= O_NONBLOCK_; + else + flags &= ~O_NONBLOCK_; + return fd_setflags(fd, flags); +} + +dword_t sys_ioctl(fd_t f, dword_t cmd, addr_t arg) { + STRACE("ioctl(%d, 0x%x, 0x%llx)", f, cmd, (unsigned long long)arg); + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + + switch (cmd) { + case FIONBIO_: + return set_nonblock(fd, arg); + case FIOCLEX_: + bit_set(f, current->files->cloexec); + return 0; + case FIONCLEX_: + bit_clear(f, current->files->cloexec); + return 0; + } + return fd_ioctl(fd, cmd, arg); +} + +dword_t sys_getcwd(addr_t buf_addr, dword_t size) { + STRACE("getcwd(%#x, %#x)", buf_addr, size); + lock(¤t->fs->lock); + struct fd *wd = current->fs->pwd; + char pwd[MAX_PATH + 1]; + int err = generic_getpath(wd, pwd); + unlock(¤t->fs->lock); + if (err < 0) + return err; + + if (strlen(pwd) + 1 > size) + return _ERANGE; + size = strlen(pwd) + 1; + char *buf = malloc(size); + if (buf == NULL) + return _ENOMEM; + strcpy(buf, pwd); + STRACE(" \"%.*s\"", size, buf); + dword_t res = size; + if (user_write(buf_addr, buf, size)) + res = _EFAULT; + free(buf); + return res; +} + +static struct fd *open_dir(const char *path) { + struct statbuf stat; + int err = generic_statat(AT_PWD, path, &stat, true); + if (err < 0) + return ERR_PTR(err); + if (!(stat.mode & S_IFDIR)) + return ERR_PTR(_ENOTDIR); + + return generic_open(path, O_RDONLY_, 0); +} + +void fs_chdir(struct fs_info *fs, struct fd *fd) { + lock(&fs->lock); + fd_close(fs->pwd); + fs->pwd = fd; + unlock(&fs->lock); +} + +dword_t sys_chdir(addr_t path_addr) { + char path[MAX_PATH]; + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + STRACE("chdir(\"%s\")", path); + + struct fd *dir = open_dir(path); + if (IS_ERR(dir)) + return PTR_ERR(dir); + fs_chdir(current->fs, dir); + return 0; +} + +dword_t sys_fchdir(fd_t f) { + STRACE("fchdir(%d)", f); + struct fd *dir = f_get(f); + if (dir == NULL) + return _EBADF; + dir->refcount++; + fs_chdir(current->fs, dir); + return 0; +} + +dword_t sys_chroot(addr_t path_addr) { + char path[MAX_PATH]; + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + STRACE("chroot(\"%s\")", path); + + struct fd *dir = open_dir(path); + if (IS_ERR(dir)) + return PTR_ERR(dir); + lock(¤t->fs->lock); + fd_close(current->fs->root); + current->fs->root = dir; + unlock(¤t->fs->lock); + return 0; +} + +dword_t sys_umask(dword_t mask) { + STRACE("umask(0%o)", mask); + struct fs_info *fs = current->fs; + lock(&fs->lock); + mode_t_ old_umask = fs->umask; + fs->umask = ((mode_t_) mask) & 0777; + unlock(&fs->lock); + return old_umask; +} + +static int mount_statfs(struct mount *mount, struct statfsbuf *stat) { + int err = 0; + if (mount->fs->statfs) + err = mount->fs->statfs(mount, stat); + if (stat->type == 0) + stat->type = mount->fs->magic; + return err; +} + +static int_t statfs_mount(struct mount *mount, addr_t buf_addr) { + struct statfsbuf buf = {}; + int err = mount_statfs(mount, &buf); + if (err < 0) + return err; + struct statfs_ out_buf = { + .type = buf.type, + .bsize = buf.bsize, + .blocks = buf.blocks, + .bfree = buf.bfree, + .bavail = buf.bavail, + .files = buf.files, + .ffree = buf.ffree, + .fsid = buf.fsid, + .namelen = buf.namelen, + .frsize = buf.frsize, + .flags = buf.flags, + }; + if (user_put(buf_addr, out_buf)) + return _EFAULT; + return 0; +} + +static int_t statfs64_mount(struct mount *mount, addr_t buf_addr) { + struct statfsbuf buf = {}; + int err = mount_statfs(mount, &buf); + if (err < 0) + return err; + struct statfs64_ out_buf = { + .type = buf.type, + .bsize = buf.bsize, + .blocks = buf.blocks, + .bfree = buf.bfree, + .bavail = buf.bavail, + .files = buf.files, + .ffree = buf.ffree, + .fsid = buf.fsid, + .namelen = buf.namelen, + .frsize = buf.frsize, + .flags = buf.flags, + }; + if (user_put(buf_addr, out_buf)) + return _EFAULT; + return 0; +} + +dword_t sys_statfs(addr_t path_addr, addr_t buf_addr) { + char path_raw[MAX_PATH]; + if (user_read_string(path_addr, path_raw, sizeof(path_raw))) + return _EFAULT; + STRACE("statfs(\"%s\", %#x)", path_raw, buf_addr); + char path[MAX_PATH]; + int err = path_normalize(AT_PWD, path_raw, path, N_SYMLINK_NOFOLLOW); + if (err < 0) + return err; + struct mount *mount = mount_find(path); + err = statfs_mount(mount, buf_addr); + mount_release(mount); + return err; +} + +dword_t sys_statfs64(addr_t path_addr, dword_t buf_size, addr_t buf_addr) { + char path_raw[MAX_PATH]; + if (user_read_string(path_addr, path_raw, sizeof(path_raw))) + return _EFAULT; + STRACE("statfs64(\"%s\", %d, %#x)", path_raw, buf_size, buf_addr); + if (buf_size != sizeof(struct statfs64_)) + return _EINVAL; + char path[MAX_PATH]; + int err = path_normalize(AT_PWD, path_raw, path, N_SYMLINK_NOFOLLOW); + if (err < 0) + return err; + struct mount *mount = mount_find(path); + err = statfs64_mount(mount, buf_addr); + mount_release(mount); + return err; +} + +dword_t sys_fstatfs(fd_t f, addr_t buf_addr) { + return statfs_mount(f_get(f)->mount, buf_addr); +} + +dword_t sys_fstatfs64(fd_t f, addr_t buf_addr) { + return statfs64_mount(f_get(f)->mount, buf_addr); +} + +#if defined(GUEST_ARM64) +// ARM64 uses statfs (not statfs64) with a different structure layout +// The structure uses 64-bit fields throughout (LP64 ABI) +static int_t statfs_arm64_mount(struct mount *mount, addr_t buf_addr) { + struct statfsbuf buf = {}; + int err = mount_statfs(mount, &buf); + if (err < 0) + return err; + struct statfs_arm64_ out_buf = { + .type = buf.type, + .bsize = buf.bsize, + .blocks = buf.blocks, + .bfree = buf.bfree, + .bavail = buf.bavail, + .files = buf.files, + .ffree = buf.ffree, + .fsid = {buf.fsid & 0xFFFFFFFF, buf.fsid >> 32}, + .namelen = buf.namelen, + .frsize = buf.frsize, + .flags = buf.flags, + }; + if (user_put(buf_addr, out_buf)) + return _EFAULT; + return 0; +} + +dword_t sys_statfs_arm64(addr_t path_addr, addr_t buf_addr) { + char path_raw[MAX_PATH]; + if (user_read_string(path_addr, path_raw, sizeof(path_raw))) + return _EFAULT; + STRACE("statfs(\"%s\", %#llx)", path_raw, (unsigned long long)buf_addr); + char path[MAX_PATH]; + int err = path_normalize(AT_PWD, path_raw, path, N_SYMLINK_NOFOLLOW); + if (err < 0) + return err; + struct mount *mount = mount_find(path); + err = statfs_arm64_mount(mount, buf_addr); + mount_release(mount); + return err; +} + +dword_t sys_fstatfs_arm64(fd_t f, addr_t buf_addr) { + STRACE("fstatfs(%d, %#llx)", f, (unsigned long long)buf_addr); + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + return statfs_arm64_mount(fd->mount, buf_addr); +} +#endif + +dword_t sys_flock(fd_t f, dword_t operation) { + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + // TODO: POSIX doesn't allow flock to fail in this way. The check is here + // because a segfault is worse. + if (fd->mount->fs->flock == NULL) + return _EBADF; + return fd->mount->fs->flock(fd, operation); +} + +static dword_t sys_utime_common(fd_t at_f, addr_t path_addr, struct timespec atime, struct timespec mtime, dword_t flags) { + char path[MAX_PATH]; + if (path_addr != 0) + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + STRACE("utimensat(%d, %s, {{%lld, %lld}, {%lld, %lld}}, %d)", at_f, path, + (long long)atime.tv_sec, (long long)atime.tv_nsec, + (long long)mtime.tv_sec, (long long)mtime.tv_nsec, flags); + struct fd *at = at_fd(at_f); + if (at == NULL) + return _EBADF; + + bool follow_links = flags & AT_SYMLINK_NOFOLLOW_ ? false : true; + return generic_utime(at, path_addr != 0 ? path : ".", atime, mtime, follow_links); +} + +dword_t sys_utimensat(fd_t at_f, addr_t path_addr, addr_t times_addr, dword_t flags) { + struct timespec atime; + struct timespec mtime; + if (times_addr == 0) { + atime = mtime = timespec_now(CLOCK_REALTIME); + } else { + struct timespec_ times[2]; + if (user_get(times_addr, times)) + return _EFAULT; + atime = convert_timespec(times[0]); + mtime = convert_timespec(times[1]); + } + return sys_utime_common(at_f, path_addr, atime, mtime, flags); +} + +dword_t sys_utimes(addr_t path_addr, addr_t times_addr) { + struct timespec atime; + struct timespec mtime; + if (times_addr == 0) { + atime = mtime = timespec_now(CLOCK_REALTIME); + } else { + struct timeval_ times[2]; + if (user_get(times_addr, times)) + return _EFAULT; + atime = convert_timeval(times[0]); + mtime = convert_timeval(times[1]); + } + return sys_utime_common(AT_FDCWD_, path_addr, atime, mtime, 0); +} + +dword_t sys_utime(addr_t path_addr, addr_t times_addr) { + struct timespec atime; + struct timespec mtime; + if (times_addr == 0) { + atime = mtime = timespec_now(CLOCK_REALTIME); + } else { + struct utimbuf_ { + time_t_ actime; + time_t_ modtime; + } times; + if (user_get(times_addr, times)) + return _EFAULT; + atime.tv_sec = times.actime; + atime.tv_nsec = 0; + mtime.tv_sec = times.modtime; + mtime.tv_nsec = 0; + } + return sys_utime_common(AT_FDCWD_, path_addr, atime, mtime, 0); +} + +static int generic_fsetattr(struct fd *fd, struct attr attr) { + if (fd->mount->fs->fsetattr == NULL) + return _EPERM; + return fd->mount->fs->fsetattr(fd, attr); +} + +dword_t sys_fchmod(fd_t f, dword_t mode) { + STRACE("fchmod(%d, %o)", f, mode); + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + mode &= ~S_IFMT; + return generic_fsetattr(fd, make_attr(mode, mode)); +} + +static dword_t do_fchmodat(fd_t at_f, addr_t path_addr, dword_t mode, dword_t flags) { + char path[MAX_PATH]; + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + STRACE("fchmodat(%d, \"%s\", %o, %#x)", at_f, path, mode, flags); + if (flags & ~(AT_SYMLINK_NOFOLLOW_ | AT_EMPTY_PATH_)) + return _EINVAL; + mode &= ~S_IFMT; + if ((flags & AT_EMPTY_PATH_) && path[0] == '\0') { + if (at_f == AT_FDCWD_) + return generic_setattrat(AT_PWD, ".", make_attr(mode, mode), true); + struct fd *fd = f_get(at_f); + if (fd == NULL) + return _EBADF; + return generic_fsetattr(fd, make_attr(mode, mode)); + } + struct fd *at = at_fd(at_f); + if (at == NULL) + return _EBADF; + return generic_setattrat(at, path, make_attr(mode, mode), !(flags & AT_SYMLINK_NOFOLLOW_)); +} + +dword_t sys_fchmodat(fd_t at_f, addr_t path_addr, dword_t mode) { + return do_fchmodat(at_f, path_addr, mode, 0); +} + +dword_t sys_fchmodat2(fd_t at_f, addr_t path_addr, dword_t mode, dword_t flags) { + return do_fchmodat(at_f, path_addr, mode, flags); +} + +dword_t sys_chmod(addr_t path_addr, dword_t mode) { + return sys_fchmodat(AT_FDCWD_, path_addr, mode); +} + +dword_t sys_fchown32(fd_t f, uid_t_ owner, uid_t_ group) { + STRACE("fchown(%d, %d, %d)", f, owner, group); + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + // realfs can't change ownership on host, silently succeed + if (fd->mount->fs == &realfs) + return 0; + int err; + if (owner != (uid_t) -1) { + err = generic_fsetattr(fd, make_attr(uid, owner)); + if (err < 0) + return err; + } + if (group != (uid_t) -1) { + err = generic_fsetattr(fd, make_attr(gid, group)); + if (err < 0) + return err; + } + return 0; +} + +dword_t sys_fchownat(fd_t at_f, addr_t path_addr, dword_t owner, dword_t group, int flags) { + char path[MAX_PATH]; + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + STRACE("fchownat(%d, \"%s\", %d, %d, %d)", at_f, path, owner, group, flags); + struct fd *at = at_fd(at_f); + if (at == NULL) + return _EBADF; + // realfs can't change ownership on host, silently succeed + if (at != AT_PWD && at->mount->fs == &realfs) + return 0; + int err; + bool follow_links = flags & AT_SYMLINK_NOFOLLOW_ ? false : true; + if (owner != (uid_t) -1) { + err = generic_setattrat(at, path, make_attr(uid, owner), follow_links); + if (err < 0) + return err; + } + if (group != (uid_t) -1) { + err = generic_setattrat(at, path, make_attr(gid, group), follow_links); + if (err < 0) + return err; + } + return 0; +} + +dword_t sys_chown32(addr_t path_addr, uid_t_ owner, uid_t_ group) { + return sys_fchownat(AT_FDCWD_, path_addr, owner, group, 0); +} + +dword_t sys_lchown(addr_t path_addr, uid_t_ owner, uid_t_ group) { + return sys_fchownat(AT_FDCWD_, path_addr, owner, group, AT_SYMLINK_NOFOLLOW_); +} + +// ARM64: 64-bit values passed in single registers +dword_t sys_truncate64(addr_t path_addr, off_t_ size) { + STRACE("truncate64(%#x, %lld [0x%llx])", path_addr, (long long)size, (unsigned long long)size); + char path[MAX_PATH]; + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + return generic_setattrat(NULL, path, make_attr(size, size), true); +} + +dword_t sys_ftruncate64(fd_t f, off_t_ size) { + STRACE("ftruncate64(%d, %lld [0x%llx])", f, (long long)size, (unsigned long long)size); + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + return generic_fsetattr(fd, make_attr(size, size)); +} + +dword_t sys_fallocate(fd_t f, dword_t UNUSED(mode), off_t_ offset, off_t_ len) { + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + struct statbuf statbuf; + int err = fd->mount->fs->fstat(fd, &statbuf); + if (err < 0) + return err; + if ((uint64_t) offset + (uint64_t) len > statbuf.size) + return generic_fsetattr(fd, make_attr(size, offset + len)); + return 0; +} + +dword_t sys_mkdirat(fd_t at_f, addr_t path_addr, mode_t_ mode) { + char path[MAX_PATH]; + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + STRACE("mkdirat(%d, %s, 0%o)", at_f, path, mode); + struct fd *at = at_fd(at_f); + if (at == NULL) + return _EBADF; + apply_umask(&mode); + mode &= 0777; + return generic_mkdirat(at, path, mode); +} + +dword_t sys_mkdir(addr_t path_addr, mode_t_ mode) { + return sys_mkdirat(AT_FDCWD_, path_addr, mode); +} + +dword_t sys_rmdir(addr_t path_addr) { + char path[MAX_PATH]; + if (user_read_string(path_addr, path, sizeof(path))) + return _EFAULT; + STRACE("rmdir(%s)", path); + return generic_rmdirat(AT_PWD, path); +} + +dword_t sys_fsync(fd_t f) { + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + int err = 0; + if (fd->ops->fsync) + err = fd->ops->fsync(fd); + return err; +} + +// a few stubs +dword_t sys_sendfile(fd_t out_fd, fd_t in_fd, addr_t offset_addr, dword_t count) { + return sys_sendfile64(out_fd, in_fd, offset_addr, count); +} +dword_t sys_sendfile64(fd_t out_fd, fd_t in_fd, addr_t offset_addr, dword_t count) { + STRACE("sendfile64(%d, %d, 0x%x, %d)", out_fd, in_fd, offset_addr, count); + struct fd *in = f_get(in_fd); + if (in == NULL) + return _EBADF; + struct fd *out = f_get(out_fd); + if (out == NULL) + return _EBADF; + if (!in->ops->read && !in->ops->pread) + return _EINVAL; + if (!out->ops->write) + return _EINVAL; + + off_t_ offset = -1; + if (offset_addr != 0) { + if (user_get(offset_addr, offset)) + return _EFAULT; + } + + size_t remaining = count; + size_t total = 0; + char buf[4096]; + while (remaining > 0) { + size_t chunk = remaining < sizeof(buf) ? remaining : sizeof(buf); + ssize_t nread; + if (offset_addr != 0) { + if (!in->ops->pread) + return _EINVAL; + nread = in->ops->pread(in, buf, chunk, offset); + } else { + if (in->ops->read) { + nread = in->ops->read(in, buf, chunk); + } else { + nread = in->ops->pread(in, buf, chunk, in->offset); + if (nread > 0) + in->offset += nread; + } + } + if (nread < 0) + return total > 0 ? (dword_t) total : (dword_t) nread; + if (nread == 0) + break; + + ssize_t nwritten = out->ops->write(out, buf, nread); + if (nwritten < 0) + return total > 0 ? (dword_t) total : (dword_t) nwritten; + + total += nwritten; + remaining -= nwritten; + if (offset_addr != 0) + offset += nwritten; + + if (nwritten < nread) + break; + } + + if (offset_addr != 0) { + if (user_put(offset_addr, offset)) + return _EFAULT; + } + return total; +} +dword_t sys_splice(fd_t UNUSED(in_fd), addr_t UNUSED(in_off_addr), fd_t UNUSED(out_fd), addr_t UNUSED(out_off_addr), dword_t UNUSED(count), dword_t UNUSED(flags)) { + return _EINVAL; +} +dword_t sys_copy_file_range(fd_t in_fd, addr_t in_off_addr, fd_t out_fd, + addr_t out_off_addr, dword_t len, uint_t flags) { + STRACE("copy_file_range(%d, 0x%x, %d, 0x%x, %d, %d)", in_fd, in_off_addr, out_fd, out_off_addr, len, flags); + if (flags != 0) + return _EINVAL; + struct fd *in = f_get(in_fd); + if (in == NULL) + return _EBADF; + struct fd *out = f_get(out_fd); + if (out == NULL) + return _EBADF; + if (!in->ops->read && !in->ops->pread) + return _EINVAL; + if (!out->ops->write && !out->ops->pwrite) + return _EINVAL; + + off_t_ in_off = -1, out_off = -1; + if (in_off_addr != 0) { + if (user_get(in_off_addr, in_off)) + return _EFAULT; + } + if (out_off_addr != 0) { + if (user_get(out_off_addr, out_off)) + return _EFAULT; + } + + char buf[4096]; + dword_t remaining = len, total = 0; + while (remaining > 0) { + size_t chunk = remaining < sizeof(buf) ? remaining : sizeof(buf); + ssize_t nread; + if (in_off >= 0) { + if (in->ops->pread) { + do { nread = in->ops->pread(in, buf, chunk, in_off); } while (nread == _EINTR); + } else { + do { nread = in->ops->read(in, buf, chunk); } while (nread == _EINTR); + } + if (nread > 0) in_off += nread; + } else { + if (in->ops->read) { + do { nread = in->ops->read(in, buf, chunk); } while (nread == _EINTR); + } else { + do { nread = in->ops->pread(in, buf, chunk, in->offset); } while (nread == _EINTR); + if (nread > 0) in->offset += nread; + } + } + if (nread <= 0) { + if (nread < 0 && total == 0) return nread; + break; + } + + ssize_t nwritten; + if (out_off >= 0) { + if (out->ops->pwrite) { + do { nwritten = out->ops->pwrite(out, buf, nread, out_off); } while (nwritten == _EINTR); + } else { + do { nwritten = out->ops->write(out, buf, nread); } while (nwritten == _EINTR); + } + if (nwritten > 0) out_off += nwritten; + } else { + if (out->ops->write) { + do { nwritten = out->ops->write(out, buf, nread); } while (nwritten == _EINTR); + } else { + do { nwritten = out->ops->pwrite(out, buf, nread, out->offset); } while (nwritten == _EINTR); + if (nwritten > 0) out->offset += nwritten; + } + } + if (nwritten <= 0) { + if (nwritten < 0 && total == 0) return nwritten; + break; + } + total += nwritten; + remaining -= nwritten; + if (nwritten < nread) + break; + } + + if (in_off_addr != 0) { + if (user_put(in_off_addr, in_off)) + return _EFAULT; + } + if (out_off_addr != 0) { + if (user_put(out_off_addr, out_off)) + return _EFAULT; + } + return total; +} + +dword_t sys_xattr_stub(addr_t UNUSED(path_addr), addr_t UNUSED(name_addr), + addr_t UNUSED(value_addr), dword_t UNUSED(size), dword_t UNUSED(flags)) { + return _ENOTSUP; +} + +// ARM64: posix_fadvise64 (syscall 223) +// Advises the kernel about file access patterns. +// Since we don't do kernel I/O optimization, we can safely ignore these hints. +dword_t sys_fadvise64(fd_t f, uint64_t offset, uint64_t len, dword_t advice) { + STRACE("fadvise64(%d, %llu, %llu, %d)", f, offset, len, advice); + + // Validate file descriptor + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + + // All advice values are valid hints that we simply ignore + // POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL, POSIX_FADV_RANDOM, + // POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, POSIX_FADV_DONTNEED + + return 0; // Success - hint acknowledged (and ignored) +} + +// ARM64: mincore (syscall 232) +// Determines which pages of a memory mapping are currently in RAM. +// For our emulator, we just pretend all pages are in memory. +dword_t sys_mincore(addr_t addr, dword_t length, addr_t vec_addr) { + STRACE("mincore(%#x, %u, %#x)", addr, length, vec_addr); + + // Page size is 4096 + size_t page_size = 4096; + size_t pages = (length + page_size - 1) / page_size; + + // Write 1 (page in memory) for each page + for (size_t i = 0; i < pages; i++) { + unsigned char in_mem = 1; + if (user_put(vec_addr + i, in_mem)) + return _EFAULT; + } + + return 0; // Success +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/fs.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/fs.h new file mode 100644 index 0000000000..ab57b9ae8e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/fs.h @@ -0,0 +1,179 @@ +#ifndef FS_H +#define FS_H + +#include "misc.h" +#include "util/list.h" +#include "fs/stat.h" +#include "fs/dev.h" +#include "fs/fake-db.h" +#include "fs/fix_path.h" +#include "kernel/memory.h" +#include <dirent.h> +#include <sqlite3.h> + +struct fs_info { + atomic_uint refcount; + mode_t_ umask; + struct fd *pwd; + struct fd *root; + lock_t lock; +}; +struct fs_info *fs_info_new(void); +struct fs_info *fs_info_copy(struct fs_info *fs); +void fs_info_release(struct fs_info *fs); + +void fs_chdir(struct fs_info *fs, struct fd *pwd); + +#define MAX_PATH 4096 +#define MAX_NAME 256 + +struct attr { + enum attr_type { + attr_uid, + attr_gid, + attr_mode, + attr_size, + } type; + union { + uid_t_ uid; + uid_t_ gid; + mode_t_ mode; + off_t_ size; + }; +}; +#define make_attr(_type, thing) \ + ((struct attr) {.type = attr_##_type, ._type = thing}) + +#define AT_SYMLINK_NOFOLLOW_ 0x100 +#define AT_EMPTY_PATH_ 0x1000 + +struct fd *generic_open(const char *path, int flags, int mode); +struct fd *generic_openat(struct fd *at, const char *path, int flags, int mode); +int generic_getpath(struct fd *fd, char *buf); +int generic_linkat(struct fd *src_at, const char *src_raw, struct fd *dst_at, const char *dst_raw); +int generic_unlinkat(struct fd *at, const char *path); +int generic_rmdirat(struct fd *at, const char *path); +int generic_renameat(struct fd *src_at, const char *src, struct fd *dst_at, const char *dst); +int generic_symlinkat(const char *target, struct fd *at, const char *link); +int generic_mknodat(struct fd *at, const char *path, mode_t_ mode, dev_t_ dev); +int generic_seek(struct fd *fd, off_t_ off, int whence, size_t size); +#define AC_R 4 +#define AC_W 2 +#define AC_X 1 +#define AC_F 0 +int generic_accessat(struct fd *dirfd, const char *path, int mode); +int generic_statat(struct fd *at, const char *path, struct statbuf *stat, bool follow_links); +int generic_setattrat(struct fd *at, const char *path, struct attr attr, bool follow_links); +int generic_utime(struct fd *at, const char *path, struct timespec atime, struct timespec mtime, bool follow_links); +ssize_t generic_readlinkat(struct fd *at, const char *path, char *buf, size_t bufsize); +int generic_mkdirat(struct fd *at, const char *path, mode_t_ mode); + +int access_check(struct statbuf *stat, int check); + +struct mount { + const char *point; + const char *source; + const char *info; + int flags; + const struct fs_ops *fs; + unsigned refcount; + struct list mounts; + + int root_fd; + union { + void *data; + struct fakefs_db fakefs; + }; +}; +extern lock_t mounts_lock; + +// returns a reference, which must be released +struct mount *mount_find(char *path); +void mount_retain(struct mount *mount); +void mount_release(struct mount *mount); + +// must hold mounts_lock while calling these, or traversing mounts +int do_mount(const struct fs_ops *fs, const char *source, const char *point, const char *info, int flags); +int do_umount(const char *point); +int mount_remove(struct mount *mount); +extern struct list mounts; + +bool mount_param_flag(const char *info, const char *flag); + +// open flags +#define O_ACCMODE_ 3 +#define O_RDONLY_ 0 +#define O_WRONLY_ (1 << 0) +#define O_RDWR_ (1 << 1) +#define O_CREAT_ (1 << 6) +#define O_EXCL_ (1 << 7) +#define O_NOCTTY_ (1 << 8) +#define O_TRUNC_ (1 << 9) +#define O_APPEND_ (1 << 10) +#define O_NONBLOCK_ (1 << 11) +#define O_DIRECTORY_ (1 << 16) +#define O_CLOEXEC_ (1 << 19) + +// generic ioctls +#define FIONREAD_ 0x541b +#define FIONBIO_ 0x5421 +#define FIONCLEX_ 0x5450 +#define FIOCLEX_ 0x5451 + +// All operations are optional unless otherwise specified +struct fs_ops { + const char *name; + int magic; + + int (*mount)(struct mount *mount); + int (*umount)(struct mount *mount); + int (*statfs)(struct mount *mount, struct statfsbuf *stat); + + struct fd *(*open)(struct mount *mount, const char *path, int flags, int mode); // required + ssize_t (*readlink)(struct mount *mount, const char *path, char *buf, size_t bufsize); + + // These return _EPERM if not present + int (*link)(struct mount *mount, const char *src, const char *dst); + int (*unlink)(struct mount *mount, const char *path); + int (*rmdir)(struct mount *mount, const char *path); + int (*rename)(struct mount *mount, const char *src, const char *dst); + int (*symlink)(struct mount *mount, const char *target, const char *link); + int (*mknod)(struct mount *mount, const char *path, mode_t_ mode, dev_t_ dev); + int (*mkdir)(struct mount *mount, const char *path, mode_t_ mode); + + // There's a close function in both the fs and fd to handle device files + // where, for instance, there's a real_fd needed for getpath and also a tty + // reference, and both need to be released when the fd is closed. + // If they are the same function, it will only be called once. + int (*close)(struct fd *fd); + + int (*stat)(struct mount *mount, const char *path, struct statbuf *stat); // required + int (*fstat)(struct fd *fd, struct statbuf *stat); // required + int (*setattr)(struct mount *mount, const char *path, struct attr attr); + int (*fsetattr)(struct fd *fd, struct attr attr); + int (*utime)(struct mount *mount, const char *path, struct timespec atime, struct timespec mtime); + // Returns the path of the file descriptor, null terminated, buf must be at least MAX_PATH+1 + int (*getpath)(struct fd *fd, char *buf); // required + + int (*flock)(struct fd *fd, int operation); + + // If present, called when all references to an inode_data for this + // filesystem go away. + void (*inode_orphaned)(struct mount *mount, ino_t inode); +}; + +struct mount *find_mount_and_trim_path(char *path); + +// adhoc fs +struct fd *adhoc_fd_create(const struct fd_ops *ops); +// this is for the "wtf is apple smoking" section +bool is_adhoc_fd(struct fd *fd); + +// filesystems +extern const struct fs_ops procfs; +extern const struct fs_ops fakefs; +extern const struct fs_ops devptsfs; +extern const struct fs_ops tmpfs; +void fs_register(const struct fs_ops *fs); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/fs_info.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/fs_info.c new file mode 100644 index 0000000000..e901c986c6 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/fs_info.c @@ -0,0 +1,29 @@ +#include "kernel/fs.h" +#include "fs/fd.h" + +struct fs_info *fs_info_new() { + struct fs_info *fs = malloc(sizeof(struct fs_info)); + if (fs == NULL) + return NULL; + fs->refcount = 1; + fs->umask = 0; + fs->pwd = fs->root = NULL; + lock_init(&fs->lock); + return fs; +} + +struct fs_info *fs_info_copy(struct fs_info *fs) { + struct fs_info *new_fs = fs_info_new(); + new_fs->umask = fs->umask; + new_fs->pwd = fd_retain(fs->pwd); + new_fs->root = fd_retain(fs->root); + return new_fs; +} + +void fs_info_release(struct fs_info *fs) { + if (--fs->refcount == 0) { + fd_close(fs->pwd); + fd_close(fs->root); + free(fs); + } +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/futex.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/futex.c new file mode 100644 index 0000000000..93389c8fd9 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/futex.c @@ -0,0 +1,476 @@ +#include <poll.h> +#include <fcntl.h> +#include <unistd.h> +#include "kernel/calls.h" + +#define FUTEX_WAIT_ 0 +#define FUTEX_WAKE_ 1 +#define FUTEX_REQUEUE_ 3 +#define FUTEX_CMP_REQUEUE_ 4 +#define FUTEX_WAKE_OP_ 5 +#define FUTEX_WAIT_BITSET_ 9 +#define FUTEX_WAKE_BITSET_ 10 +#define FUTEX_PRIVATE_FLAG_ 128 +#define FUTEX_CLOCK_REALTIME_ 256 +#define FUTEX_CMD_MASK_ ~(FUTEX_PRIVATE_FLAG_ | FUTEX_CLOCK_REALTIME_) + +// FUTEX_WAKE_OP val3 encoding (see Linux kernel futex.h) +#define FUTEX_OP_SET 0 +#define FUTEX_OP_ADD 1 +#define FUTEX_OP_OR 2 +#define FUTEX_OP_ANDN 3 +#define FUTEX_OP_XOR 4 +#define FUTEX_OP_OPARG_SHIFT 8 + +#define FUTEX_OP_CMP_EQ 0 +#define FUTEX_OP_CMP_NE 1 +#define FUTEX_OP_CMP_LT 2 +#define FUTEX_OP_CMP_LE 3 +#define FUTEX_OP_CMP_GT 4 +#define FUTEX_OP_CMP_GE 5 + +struct futex { + atomic_uint refcount; + struct mem *mem; + addr_t addr; + struct list queue; + struct list chain; // locked by futex_hash_lock +}; + +struct futex_wait { + cond_t cond; + struct futex *futex; // will be changed by a requeue + struct list queue; + struct task *task; // owning task (for per-thread futex_pipe wakeup) +}; + +#define FUTEX_HASH_BITS 12 +#define FUTEX_HASH_SIZE (1 << FUTEX_HASH_BITS) +static lock_t futex_lock = LOCK_INITIALIZER; +static struct list futex_hash[FUTEX_HASH_SIZE]; + +static void __attribute__((constructor)) init_futex_hash() { + for (int i = 0; i < FUTEX_HASH_SIZE; i++) + list_init(&futex_hash[i]); +} + +static struct futex *futex_get_unlocked(addr_t addr) { + int hash = (addr ^ (unsigned long) current->mem) % FUTEX_HASH_SIZE; + struct list *bucket = &futex_hash[hash]; + struct futex *futex; + list_for_each_entry(bucket, futex, chain) { + if (futex->addr == addr && futex->mem == current->mem) { + futex->refcount++; + return futex; + } + } + + futex = malloc(sizeof(struct futex)); + if (futex == NULL) { + unlock(&futex_lock); + return NULL; + } + futex->refcount = 1; + futex->mem = current->mem; + futex->addr = addr; + list_init(&futex->queue); + list_add(bucket, &futex->chain); + return futex; +} + +// Returns the futex for the current process at the given addr, and locks it +// Unlocked variant is available for times when you need to get two futexes at once +static struct futex *futex_get(addr_t addr) { + lock(&futex_lock); + struct futex *futex = futex_get_unlocked(addr); + if (futex == NULL) + unlock(&futex_lock); + return futex; +} + +static void futex_put_unlocked(struct futex *futex) { + if (--futex->refcount == 0) { + assert(list_empty(&futex->queue)); + list_remove(&futex->chain); + free(futex); + } +} + +// Must be called on the result of futex_get when you're done with it +// Also has an unlocked version, for releasing the result of futex_get_unlocked +static void futex_put(struct futex *futex) { + futex_put_unlocked(futex); + unlock(&futex_lock); +} + +static int futex_load(struct futex *futex, dword_t *out) { + assert(futex->mem == current->mem); + read_wrlock(¤t->mem->lock); + dword_t *ptr = mem_ptr(current->mem, futex->addr, MEM_READ); + read_wrunlock(¤t->mem->lock); + if (ptr == NULL) + return 1; + *out = *ptr; + return 0; +} + +static int futex_wait(addr_t uaddr, dword_t val, struct timespec *timeout) { + struct futex *futex = futex_get(uaddr); + int err = 0; + dword_t tmp; + if (futex_load(futex, &tmp)) + err = _EFAULT; + else if (tmp != val) + err = _EAGAIN; + else { + // Lazily create per-thread futex pipe (reused across all futex_wait calls) + if (current->futex_pipe[0] == -1) { + if (pipe(current->futex_pipe) < 0) { + futex_put(futex); + return _ENOMEM; + } + fcntl(current->futex_pipe[0], F_SETFL, O_NONBLOCK); + fcntl(current->futex_pipe[1], F_SETFL, O_NONBLOCK); + } + // Drain any stale bytes from previous wakeups + { char buf[16]; while (read(current->futex_pipe[0], buf, sizeof(buf)) > 0) {} } + + struct futex_wait wait; + wait.cond = COND_INITIALIZER; + wait.futex = futex; + wait.task = current; + + // Stay in queue so futex_wakelike can find us and write to our pipe + list_add_tail(&futex->queue, &wait.queue); + unlock(&futex_lock); + + // Calculate deadline for timed waits + int64_t deadline_ns = 0; // 0 = infinite + if (timeout) { + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + deadline_ns = (int64_t)now.tv_sec * 1000000000LL + now.tv_nsec + + (int64_t)timeout->tv_sec * 1000000000LL + timeout->tv_nsec; + } + + current->blocking = true; + struct pollfd pfd = { .fd = current->futex_pipe[0], .events = POLLIN }; + for (;;) { + // Compute poll timeout + int poll_ms; + if (deadline_ns) { + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + int64_t now_ns = (int64_t)now.tv_sec * 1000000000LL + now.tv_nsec; + int64_t remain_ms = (deadline_ns - now_ns) / 1000000LL; + if (remain_ms <= 0) { err = _ETIMEDOUT; break; } + poll_ms = remain_ms > 100 ? 100 : (int)remain_ms; + } else { + poll_ms = 100; // 100ms safety-net timeout for signal/stall checks + } + + int ret = poll(&pfd, 1, poll_ms); + if (ret > 0) { + // Woken by pipe write — drain it + char buf[16]; + while (read(current->futex_pipe[0], buf, sizeof(buf)) > 0) {} + err = 0; + break; + } + // ret == 0 (timeout) or ret < 0 (EINTR from signal) — check conditions + + if (current->group->doing_group_exit) { + err = _EINTR; break; + } + if (current->sighand) { + lock(¤t->sighand->lock); + bool sig_pending = !!(current->pending & ~current->blocked); + unlock(¤t->sighand->lock); + if (sig_pending) { err = _EINTR; break; } + } + // Check value periodically (every ~100ms instead of every 10ms) + read_wrlock(¤t->mem->lock); + dword_t *ptr = mem_ptr(current->mem, uaddr, MEM_READ); + read_wrunlock(¤t->mem->lock); + if (ptr == NULL) { err = _EFAULT; break; } + if (*ptr != val) { err = 0; break; } + } + current->blocking = false; + + // Remove from queue (pipe stays open for reuse) + lock(&futex_lock); + list_remove_safe(&wait.queue); + futex_put_unlocked(wait.futex); + unlock(&futex_lock); + goto futex_wait_done; + } + futex_put(futex); +futex_wait_done: + STRACE("%d end futex(FUTEX_WAIT)", current->pid); + return err; +} + +// Wake up to `max` waiters on the given futex. Caller must hold futex_lock. +static unsigned futex_wake_queue(struct futex *futex, dword_t max) { + struct futex_wait *wait, *tmp; + unsigned woken = 0; + list_for_each_entry_safe(&futex->queue, wait, tmp, queue) { + if (woken >= max) + break; + // Wake via per-thread pipe write — waiter is blocked on poll(futex_pipe[0]) + if (wait->task->futex_pipe[1] != -1) { + char c = 1; + write(wait->task->futex_pipe[1], &c, 1); + } + list_remove(&wait->queue); + woken++; + } + return woken; +} + +static int futex_wakelike(int op, addr_t uaddr, dword_t wake_max, dword_t requeue_max, addr_t requeue_addr) { + struct futex *futex = futex_get(uaddr); + + unsigned woken = futex_wake_queue(futex, wake_max); + + if (op == FUTEX_REQUEUE_) { + struct futex *futex2 = futex_get_unlocked(requeue_addr); + struct futex_wait *wait, *tmp; + unsigned requeued = 0; + list_for_each_entry_safe(&futex->queue, wait, tmp, queue) { + if (requeued >= requeue_max) + break; + // sketchy as hell + list_remove(&wait->queue); + list_add_tail(&futex2->queue, &wait->queue); + assert(futex->refcount > 1); // should be true because this function keeps a reference + futex->refcount--; + futex2->refcount++; + wait->futex = futex2; + requeued++; + } + futex_put_unlocked(futex2); + woken += requeued; + } + + futex_put(futex); + return woken; +} + +int futex_wake(addr_t uaddr, dword_t wake_max) { + return futex_wakelike(FUTEX_WAKE_, uaddr, wake_max, 0, 0); +} + +// FUTEX_CMP_REQUEUE: like FUTEX_REQUEUE, but first atomically check *uaddr == expected. +// Returns total woken+requeued, or _EAGAIN on mismatch, or _EFAULT on bad addr. +static int futex_cmp_requeue(addr_t uaddr, dword_t wake_max, dword_t requeue_max, + addr_t requeue_addr, dword_t expected) { + struct futex *futex = futex_get(uaddr); + if (futex == NULL) + return _ENOMEM; + + dword_t cur; + if (futex_load(futex, &cur)) { + futex_put(futex); + return _EFAULT; + } + if (cur != expected) { + futex_put(futex); + return _EAGAIN; + } + + unsigned woken = futex_wake_queue(futex, wake_max); + + struct futex *futex2 = futex_get_unlocked(requeue_addr); + struct futex_wait *wait, *tmp; + unsigned requeued = 0; + list_for_each_entry_safe(&futex->queue, wait, tmp, queue) { + if (requeued >= requeue_max) + break; + list_remove(&wait->queue); + list_add_tail(&futex2->queue, &wait->queue); + assert(futex->refcount > 1); + futex->refcount--; + futex2->refcount++; + wait->futex = futex2; + requeued++; + } + futex_put_unlocked(futex2); + + futex_put(futex); + return woken + requeued; +} + +// FUTEX_WAKE_OP: atomic RMW on *uaddr2, then wake up to val waiters on uaddr, +// and — if the old value of *uaddr2 satisfies the comparison — wake up to val2 +// waiters on uaddr2. val3 encodes the op, oparg, cmp, and cmparg (see Linux). +static int futex_wake_op(addr_t uaddr, dword_t wake_max1, addr_t uaddr2, + dword_t wake_max2, dword_t val3) { + int op_code = (val3 >> 28) & 0xf; + int cmp_code = (val3 >> 24) & 0xf; + // oparg/cmparg are 12-bit sign-extended. + int32_t oparg = (int32_t)((val3 << 8)) >> 20; // bits [23:12] sign-extended + int32_t cmparg = (int32_t)((val3 << 20)) >> 20; // bits [11:0] sign-extended + + bool shift = (op_code & FUTEX_OP_OPARG_SHIFT) != 0; + op_code &= ~FUTEX_OP_OPARG_SHIFT; + if (shift) { + if (oparg < 0 || oparg > 31) + return _EINVAL; + oparg = 1 << oparg; + } + + // Atomic RMW on *uaddr2. + // We must hold mem->lock across mem_ptr+atomic op so the mapping can't vanish. + read_wrlock(¤t->mem->lock); + uint32_t *ptr = mem_ptr(current->mem, uaddr2, MEM_WRITE); + if (ptr == NULL) { + read_wrunlock(¤t->mem->lock); + return _EFAULT; + } + uint32_t oldval; + switch (op_code) { + case FUTEX_OP_SET: + oldval = __atomic_exchange_n(ptr, (uint32_t)oparg, __ATOMIC_SEQ_CST); + break; + case FUTEX_OP_ADD: + oldval = __atomic_fetch_add(ptr, (uint32_t)oparg, __ATOMIC_SEQ_CST); + break; + case FUTEX_OP_OR: + oldval = __atomic_fetch_or(ptr, (uint32_t)oparg, __ATOMIC_SEQ_CST); + break; + case FUTEX_OP_ANDN: + oldval = __atomic_fetch_and(ptr, (uint32_t)~oparg, __ATOMIC_SEQ_CST); + break; + case FUTEX_OP_XOR: + oldval = __atomic_fetch_xor(ptr, (uint32_t)oparg, __ATOMIC_SEQ_CST); + break; + default: + read_wrunlock(¤t->mem->lock); + return _ENOSYS; + } + read_wrunlock(¤t->mem->lock); + + int32_t sold = (int32_t)oldval; + bool cmp_true; + switch (cmp_code) { + case FUTEX_OP_CMP_EQ: cmp_true = (sold == cmparg); break; + case FUTEX_OP_CMP_NE: cmp_true = (sold != cmparg); break; + case FUTEX_OP_CMP_LT: cmp_true = (sold < cmparg); break; + case FUTEX_OP_CMP_LE: cmp_true = (sold <= cmparg); break; + case FUTEX_OP_CMP_GT: cmp_true = (sold > cmparg); break; + case FUTEX_OP_CMP_GE: cmp_true = (sold >= cmparg); break; + default: return _ENOSYS; + } + + // Wake waiters on both queues. Acquire both futexes under futex_lock. + lock(&futex_lock); + struct futex *f1 = futex_get_unlocked(uaddr); + if (f1 == NULL) { unlock(&futex_lock); return _ENOMEM; } + unsigned total = futex_wake_queue(f1, wake_max1); + if (cmp_true) { + struct futex *f2 = futex_get_unlocked(uaddr2); + if (f2 != NULL) { + total += futex_wake_queue(f2, wake_max2); + futex_put_unlocked(f2); + } + } + futex_put_unlocked(f1); + unlock(&futex_lock); + return total; +} + +dword_t sys_futex(addr_t uaddr, dword_t op, dword_t val, addr_t timeout_or_val2, addr_t uaddr2, dword_t val3) { + if (!(op & FUTEX_PRIVATE_FLAG_)) { + STRACE("!FUTEX_PRIVATE "); + } + int cmd = op & FUTEX_CMD_MASK_; + struct timespec timeout = {0}; + if ((cmd == FUTEX_WAIT_ || cmd == FUTEX_WAIT_BITSET_) && timeout_or_val2) { + struct timespec_ timeout_; + if (user_get(timeout_or_val2, timeout_)) + return _EFAULT; + if (cmd == FUTEX_WAIT_BITSET_) { + // FUTEX_WAIT_BITSET uses absolute CLOCK_REALTIME timeout; + // convert to relative for our futex_wait implementation. + struct timespec now; + clock_gettime(CLOCK_REALTIME, &now); + timeout.tv_sec = timeout_.sec - now.tv_sec; + timeout.tv_nsec = timeout_.nsec - now.tv_nsec; + if (timeout.tv_nsec < 0) { + timeout.tv_sec--; + timeout.tv_nsec += 1000000000; + } + if (timeout.tv_sec < 0) { + timeout.tv_sec = 0; + timeout.tv_nsec = 0; + } + } else { + timeout.tv_sec = timeout_.sec; + timeout.tv_nsec = timeout_.nsec; + } + } + switch (cmd) { + case FUTEX_WAIT_: + STRACE("futex(FUTEX_WAIT, %#x, %d, 0x%x {%ds %dns}) = ...\n", uaddr, val, timeout_or_val2, timeout.tv_sec, timeout.tv_nsec); + return futex_wait(uaddr, val, timeout_or_val2 ? &timeout : NULL); + case FUTEX_WAIT_BITSET_: + // FUTEX_WAIT_BITSET with MATCH_ANY (0xffffffff) is equivalent to FUTEX_WAIT. + // We ignore the bitset mask (val3) and treat all bits as matching. + STRACE("futex(FUTEX_WAIT_BITSET, %#x, %d, mask=%#x) = ...\n", uaddr, val, val3); + return futex_wait(uaddr, val, timeout_or_val2 ? &timeout : NULL); + case FUTEX_WAKE_: + STRACE("futex(FUTEX_WAKE, %#x, %d)", uaddr, val); + return futex_wakelike(FUTEX_WAKE_, uaddr, val, 0, 0); + case FUTEX_WAKE_BITSET_: + // FUTEX_WAKE_BITSET with MATCH_ANY is equivalent to FUTEX_WAKE. + STRACE("futex(FUTEX_WAKE_BITSET, %#x, %d, mask=%#x)", uaddr, val, val3); + return futex_wakelike(FUTEX_WAKE_, uaddr, val, 0, 0); + case FUTEX_REQUEUE_: + STRACE("futex(FUTEX_REQUEUE, %#x, %d, %#x)", uaddr, val, uaddr2); + return futex_wakelike(FUTEX_REQUEUE_, uaddr, val, timeout_or_val2, uaddr2); + case FUTEX_CMP_REQUEUE_: + STRACE("futex(FUTEX_CMP_REQUEUE, %#x, %d, %#x, expected=%d)", uaddr, val, uaddr2, val3); + return futex_cmp_requeue(uaddr, val, timeout_or_val2, uaddr2, val3); + case FUTEX_WAKE_OP_: + STRACE("futex(FUTEX_WAKE_OP, %#x, %d, %#x, %d, %#x)", uaddr, val, uaddr2, timeout_or_val2, val3); + return futex_wake_op(uaddr, val, uaddr2, timeout_or_val2, val3); + } + STRACE("futex(%#x, %d, %d, timeout=%#x, %#x, %d) ", uaddr, op, val, timeout_or_val2, uaddr2, val3); + // Loud diagnostic — these should be rare now that CMP_REQUEUE and WAKE_OP are implemented. + // Returning _EINVAL instead of _ENOSYS lets most userspace libraries fall back to + // FUTEX_WAKE/WAIT rather than treating it as "kernel too old" and aborting. + printk("SYS_FUTEX: unsupported op=%d (cmd=%d) uaddr=%#x val=%d uaddr2=%#x val3=%#x pid=%d comm=%s\n", + op, cmd, uaddr, val, uaddr2, val3, current->pid, current->comm); + return _EINVAL; +} + +struct robust_list_head_ { + addr_t list; + dword_t offset; + addr_t list_op_pending; +}; + +int_t sys_set_robust_list(addr_t robust_list, dword_t len) { + STRACE("set_robust_list(%#x, %d)", robust_list, len); + if (len != sizeof(struct robust_list_head_)) + return _EINVAL; + current->robust_list = robust_list; + return 0; +} + +int_t sys_get_robust_list(pid_t_ pid, addr_t robust_list_ptr, addr_t len_ptr) { + STRACE("get_robust_list(%d, %#x, %#x)", pid, robust_list_ptr, len_ptr); + + lock(&pids_lock); + struct task *task = pid_get_task(pid); + unlock(&pids_lock); + if (task != current) + return _EPERM; + + if (user_put(robust_list_ptr, current->robust_list)) + return _EFAULT; + if (user_put(len_ptr, (int[]) {sizeof(struct robust_list_head_)})) + return _EFAULT; + return 0; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/futex.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/futex.h new file mode 100644 index 0000000000..61a21c5864 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/futex.h @@ -0,0 +1,6 @@ +#ifndef KERNEL_FUTEX_H +#define KERNEL_FUTEX_H + +int futex_wake(addr_t uaddr, dword_t val); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/getset.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/getset.c new file mode 100644 index 0000000000..8edf84fd9e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/getset.c @@ -0,0 +1,202 @@ +#include "kernel/calls.h" +#include "kernel/task.h" +#include "kernel/personality.h" + +pid_t_ sys_getpid() { + STRACE("getpid()"); + return current->tgid; +} +pid_t_ sys_gettid() { + STRACE("gettid()"); + return current->pid; +} +pid_t_ sys_getppid() { + STRACE("getppid()"); + pid_t_ ppid; + lock(&pids_lock); + if (current->parent != NULL) + ppid = current->parent->pid; + else + ppid = 0; + unlock(&pids_lock); + return ppid; +} + +dword_t sys_getuid32() { + STRACE("getuid32()"); + return current->uid; +} +dword_t sys_getuid() { + STRACE("getuid()"); + return current->uid & 0xffff; +} + +dword_t sys_geteuid32() { + STRACE("geteuid32()"); + return current->euid; +} +dword_t sys_geteuid() { + STRACE("geteuid()"); + return current->euid & 0xffff; +} + +int_t sys_setuid(uid_t_ uid) { + STRACE("setuid(%d)", uid); + if (superuser()) { + current->uid = current->suid = uid; + } else { + if (uid != current->uid && uid != current->suid) + return _EPERM; + } + current->euid = uid; + return 0; +} + +dword_t sys_setresuid(uid_t_ ruid, uid_t_ euid, uid_t_ suid) { + STRACE("setresuid(%d, %d, %d)", ruid, euid, suid); + if (!superuser()) { + if (ruid != (uid_t) -1 && ruid != current->uid && ruid != current->euid && ruid != current->suid) + return _EPERM; + if (euid != (uid_t) -1 && euid != current->uid && euid != current->euid && euid != current->suid) + return _EPERM; + if (suid != (uid_t) -1 && suid != current->uid && suid != current->euid && suid != current->suid) + return _EPERM; + } + + if (ruid != (uid_t) -1) + current->uid = ruid; + if (euid != (uid_t) -1) + current->euid = euid; + if (suid != (uid_t) -1) + current->suid = suid; + return 0; +} + +int_t sys_getresuid(addr_t ruid_addr, addr_t euid_addr, addr_t suid_addr) { + STRACE("getresuid(%#x, %#x, %#x)", ruid_addr, euid_addr, suid_addr); + if (user_put(ruid_addr, current->uid)) + return _EFAULT; + if (user_put(euid_addr, current->euid)) + return _EFAULT; + if (user_put(suid_addr, current->suid)) + return _EFAULT; + return 0; +} + +int_t sys_setreuid(uid_t_ ruid, uid_t_ euid) { + return sys_setresuid(ruid, euid, -1); +} + +dword_t sys_getgid32() { + STRACE("getgid32()"); + return current->gid; +} +dword_t sys_getgid() { + STRACE("getgid()"); + return current->gid & 0xffff; +} + +dword_t sys_getegid32() { + STRACE("getegid32()"); + return current->egid; +} +dword_t sys_getegid() { + STRACE("getegid()"); + return current->egid & 0xffff; +} + +int_t sys_setgid(uid_t_ gid) { + STRACE("setgid(%d)", gid); + if (superuser()) { + current->gid = current->sgid = gid; + } else { + if (gid != current->gid && gid != current->sgid) + return _EPERM; + } + current->egid = gid; + return 0; +} + +dword_t sys_setresgid(uid_t_ rgid, uid_t_ egid, uid_t_ sgid) { + STRACE("setresgid(%d, %d, %d)", rgid, egid, sgid); + if (!superuser()) { + if (rgid != (uid_t) -1 && rgid != current->gid && rgid != current->egid && rgid != current->sgid) + return _EPERM; + if (egid != (uid_t) -1 && egid != current->gid && egid != current->egid && egid != current->sgid) + return _EPERM; + if (sgid != (uid_t) -1 && sgid != current->gid && sgid != current->egid && sgid != current->sgid) + return _EPERM; + } + + if (rgid != (uid_t) -1) + current->gid = rgid; + if (egid != (uid_t) -1) + current->egid = egid; + if (sgid != (uid_t) -1) + current->sgid = sgid; + return 0; +} + +int_t sys_getresgid(addr_t rgid_addr, addr_t egid_addr, addr_t sgid_addr) { + STRACE("getresgid(%#x, %#x, %#x)", rgid_addr, egid_addr, sgid_addr); + if (user_put(rgid_addr, current->gid)) + return _EFAULT; + if (user_put(egid_addr, current->egid)) + return _EFAULT; + if (user_put(sgid_addr, current->sgid)) + return _EFAULT; + return 0; +} + +int_t sys_setregid(uid_t_ rgid, uid_t_ egid) { + return sys_setresgid(rgid, egid, -1); +} + +int_t sys_getgroups(dword_t size, addr_t list) { + STRACE("getgroups(%d, %#x)", size, list); + if (size == 0) + return current->ngroups; + if (size < current->ngroups) + return _EINVAL; + for (unsigned i = 0; i < current->ngroups; i++) + STRACE(" %d", current->groups[i]); + if (user_write(list, current->groups, current->ngroups * sizeof(uid_t_))) + return _EFAULT; + return current->ngroups; +} + +int_t sys_setgroups(dword_t size, addr_t list) { + STRACE("setgroups(%d, %#x)", size, list); + if (size > MAX_GROUPS) + return _EINVAL; + if (user_read(list, current->groups, size * sizeof(uid_t_))) + return _EFAULT; + for (unsigned i = 0; i < size; i++) + STRACE(" %d", current->groups[i]); + current->ngroups = size; + return 0; +} + +// this does not really work +int_t sys_capget(addr_t header_addr, addr_t data_addr) { + STRACE("capget(%#x, %#x)", header_addr, data_addr); + return 0; +} +int_t sys_capset(addr_t header_addr, addr_t data_addr) { + STRACE("capset(%#x, %#x)", header_addr, data_addr); + return 0; +} + +// minimal version according to Linux sys/personality.h +int_t sys_personality(dword_t persona) { + STRACE("personality(%#x)", persona); + // Get the personality + if (persona == 0xffffffff) + return current->group->personality; + + // ADDR_NO_RANDOMIZE is the only thing we support, and you can't turn it off + if (persona != ADDR_NO_RANDOMIZE_) + return _EINVAL; + + return current->group->personality; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/group.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/group.c new file mode 100644 index 0000000000..2e096ad122 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/group.c @@ -0,0 +1,132 @@ +#include "util/list.h" +#include "kernel/calls.h" +#include "kernel/task.h" +#include "fs/tty.h" + +dword_t sys_setpgid(pid_t_ id, pid_t_ pgid) { + STRACE("setpgid(%d, %d)", id, pgid); + int err; + if (id == 0) + id = current->pid; + if (pgid == 0) + pgid = id; + lock(&pids_lock); + struct pid *pid = pid_get(id); + err = _ESRCH; + if (pid == NULL) + goto out; + struct task *task = pid->task; + if (task == NULL) + goto out; + struct tgroup *tgroup = task->group; + + // you can only join a process group in the same session + if (id != pgid) { + // there has to be a process in pgrp that's in the same session as id + err = _EPERM; + struct pid *group_pid = pid_get(pgid); + if (group_pid == NULL || list_empty(&group_pid->pgroup)) + goto out; + struct tgroup *group_first_tgroup = list_first_entry(&group_pid->pgroup, struct tgroup, pgroup); + if (tgroup->sid != group_first_tgroup->sid) + goto out; + } + + // you can only change the process group of yourself or a child + err = _ESRCH; + if (task != current && task->parent != current) + goto out; + // a session leader cannot create a process group + err = _EPERM; + if (tgroup->sid == tgroup->leader->pid) + goto out; + + // TODO cannot set process group of a child that has done exec + + if (tgroup->pgid != pgid) { + list_remove(&tgroup->pgroup); + tgroup->pgid = pgid; + list_add(&pid->pgroup, &tgroup->pgroup); + } + + err = 0; +out: + unlock(&pids_lock); + return err; +} + +dword_t sys_setpgrp() { + return sys_setpgid(0, 0); +} + +pid_t_ sys_getpgid(pid_t_ pid) { + STRACE("getpgid(%d)", pid); + lock(&pids_lock); + struct task *task = current; + if (pid != 0) + task = pid_get_task(pid); + if (!task) { + unlock(&pids_lock); + return _ESRCH; + } + pid = task->group->pgid; + unlock(&pids_lock); + return pid; +} +pid_t_ sys_getpgrp() { + return sys_getpgid(0); +} + +// Must lock pids_lock and task->group->lock +void task_leave_session(struct task *task) { + struct tgroup *group = task->group; + list_remove_safe(&group->session); + if (group->tty) { + lock(&ttys_lock); + struct pid *session = pid_get(group->sid); + if (session == NULL || list_empty(&session->session)) { + lock(&group->tty->lock); + group->tty->session = 0; + unlock(&group->tty->lock); + } + tty_release(group->tty); + group->tty = NULL; + unlock(&ttys_lock); + } +} + +pid_t_ task_setsid(struct task *task) { + lock(&pids_lock); + struct tgroup *group = task->group; + pid_t_ new_sid = group->leader->pid; + if (group->pgid == new_sid || group->sid == new_sid) { + unlock(&pids_lock); + return _EPERM; + } + + task_leave_session(task); + struct pid *pid = pid_get(task->pid); + list_add(&pid->session, &group->session); + group->sid = new_sid; + + list_remove_safe(&group->pgroup); + list_add(&pid->pgroup, &group->pgroup); + group->pgid = new_sid; + + unlock(&pids_lock); + return new_sid; +} + +dword_t sys_setsid() { + STRACE("setsid()"); + return task_setsid(current); +} + +dword_t sys_getsid() { + STRACE("getsid()"); + lock(&pids_lock); + pid_t_ sid = current->group->sid; + unlock(&pids_lock); + return sid; +} + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/init.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/init.c new file mode 100644 index 0000000000..5fb8db9d7f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/init.c @@ -0,0 +1,207 @@ +#include <signal.h> +#include <string.h> +#include <time.h> +#include <sys/stat.h> +#include "fs/dev.h" +#include "fs/devices.h" +#include "fs/fd.h" +#include "fs/real.h" +#include "fs/tty.h" +#include "kernel/calls.h" +#include "kernel/init.h" +#include "kernel/personality.h" + +int mount_root(const struct fs_ops *fs, const char *source) { + char source_realpath[MAX_PATH + 1]; + if (realpath(source, source_realpath) == NULL) + return errno_map(); + int err = do_mount(fs, source_realpath, "", "", 0); + if (err < 0) + return err; + return 0; +} + +static void establish_signal_handlers() { + extern void sigusr1_handler(int sig); + struct sigaction sigact; + sigact.sa_handler = sigusr1_handler; + sigact.sa_flags = 0; + sigemptyset(&sigact.sa_mask); + sigaddset(&sigact.sa_mask, SIGUSR1); + sigaction(SIGUSR1, &sigact, NULL); + signal(SIGPIPE, SIG_IGN); +} + +// copied from include/asm-generic/resource.h in the kernel +static struct rlimit_ init_rlimits[16] = { + [RLIMIT_CPU_] = {RLIM_INFINITY_, RLIM_INFINITY_}, + [RLIMIT_FSIZE_] = {RLIM_INFINITY_, RLIM_INFINITY_}, + [RLIMIT_DATA_] = {RLIM_INFINITY_, RLIM_INFINITY_}, + [RLIMIT_STACK_] = {128*1024*1024, RLIM_INFINITY_}, + [RLIMIT_CORE_] = {0, RLIM_INFINITY_}, + [RLIMIT_RSS_] = {RLIM_INFINITY_, RLIM_INFINITY_}, + [RLIMIT_NPROC_] = {1024, 1024}, + [RLIMIT_NOFILE_] = {1024, 4096}, + [RLIMIT_MEMLOCK_] = {64*1024, 64*1024}, + [RLIMIT_AS_] = {RLIM_INFINITY_, RLIM_INFINITY_}, + [RLIMIT_LOCKS_] = {RLIM_INFINITY_, RLIM_INFINITY_}, + [RLIMIT_SIGPENDING_] = {1024, 1024}, + [RLIMIT_MSGQUEUE_] = {819200, 819200}, + [RLIMIT_NICE_] = {0, 0}, + [RLIMIT_RTPRIO_] = {0, 0}, + [RLIMIT_RTTIME_] = {RLIM_INFINITY_, RLIM_INFINITY_}, +}; + +// TODO error propagation +static struct task *construct_task(struct task *parent) { + struct task *task = task_create_(parent); + + struct tgroup *group = malloc(sizeof(struct tgroup)); + *group = (struct tgroup) {}; + list_init(&group->threads); + lock_init(&group->lock); + cond_init(&group->child_exit); + cond_init(&group->stopped_cond); + memcpy(group->limits, init_rlimits, sizeof(init_rlimits)); + group->leader = task; + group->personality = ADDR_NO_RANDOMIZE_; + { + struct timespec _ts; + clock_gettime(CLOCK_MONOTONIC, &_ts); + atomic_store_explicit(&group->last_progress_ns, + (uint64_t)_ts.tv_sec * 1000000000ULL + _ts.tv_nsec, + memory_order_relaxed); + } + list_add(&group->threads, &task->group_links); + task->group = group; + task->tgid = task->pid; + task_setsid(task); + + task_set_mm(task, mm_new()); + task->sighand = sighand_new(); + task->files = fdtable_new(3); // why is there a 3 here + + task->fs = fs_info_new(); + task->fs->umask = 0022; + // we'll need to have current set to do the open call + struct task *old_current = current; + current = task; + task->fs->root = generic_open("/", O_RDONLY_, 0); + if (IS_ERR(task->fs->root)) + return ERR_PTR(task->fs->root); + task->fs->pwd = fd_retain(task->fs->root); + current = old_current; + + return task; +} + +int become_first_process() { + // now seems like a nice time + establish_signal_handlers(); + + struct task *task = construct_task(NULL); + if (IS_ERR(task)) + return PTR_ERR(task); + + current = task; + return 0; +} + +int become_new_init_child() { + // locking? who needs locking?! + struct task *init = pid_get_task(1); + assert(init != NULL); + + struct task *task = construct_task(init); + if (IS_ERR(task)) + return PTR_ERR(task); + + // these are things we definitely don't want to inherit + task->clear_tid = 0; + task->vfork = NULL; + task->blocked = task->pending = task->waiting = 0; + list_init(&task->queue); + // TODO: think about whether it would be a good idea to inherit fs_info + + current = task; + return 0; +} + +extern int console_major; +extern int console_minor; +void set_console_device(int major, int minor) { + console_major = major; + console_minor = minor; +} + +int create_stdio(const char *file, int major, int minor) { + struct fd *fd = generic_open(file, O_RDWR_, 0); + if (!IS_ERR(fd) && !S_ISCHR(fd->stat.mode)) { + // opened a regular file instead of a char device (e.g. realfs + // can't create device nodes), so close it and use fallback + fd_close(fd); + fd = ERR_PTR(_ENOENT); + } + if (IS_ERR(fd)) { + // fallback to adhoc files for stdio + fd = adhoc_fd_create(NULL); + fd->stat.rdev = dev_make(major, minor); + fd->stat.mode = S_IFCHR | S_IRUSR; + fd->flags = O_RDWR_; + int err = dev_open(major, minor, DEV_CHAR, fd); + if (err < 0) + return err; + } + + fd->refcount = 0; + current->files->files[0] = fd_retain(fd); + current->files->files[1] = fd_retain(fd); + current->files->files[2] = fd_retain(fd); + return 0; +} + +static struct fd *open_fd_from_actual_fd(int fd_no) { + struct fd *fd = adhoc_fd_create(&realfs_fdops); + if (fd == NULL) { + return NULL; + } + fd->real_fd = fd_no; + fd->dir = NULL; + // Populate stat from host fd so guest fstat() returns valid metadata. + // Node.js (libuv) calls fstat on stdout/stderr to determine if it's a + // TTY, pipe, or file — all-zero stat causes console.log to silently fail. + struct stat real_stat; + if (fstat(fd_no, &real_stat) == 0) { + fd->stat.mode = real_stat.st_mode; + fd->stat.rdev = dev_fake_from_real(real_stat.st_rdev); + fd->stat.inode = real_stat.st_ino; + fd->stat.size = real_stat.st_size; + // On macOS, piped/redirected fds may appear as sockets (S_IFSOCK). + // Guest programs (especially Node.js/libuv) don't recognize sockets + // as valid stdio types and fail to initialize stdout/stderr handles. + // Report sockets as character devices (S_IFCHR) which is what Linux + // shows for TTY fds. This allows node's libuv uv_guess_handle() to + // detect them as TTY-like (when combined with isatty/TCGETS support) + // or fall back to a generic stream. + // Make guest see TTY-like char device when host fd is a socket + // (macOS piped stdio) or an actual TTY (terminal). + if (S_ISSOCK(fd->stat.mode) || isatty(fd_no)) { + fd->stat.mode = S_IFCHR | 0620; + fd->stat.rdev = dev_make(TTY_PSEUDO_SLAVE_MAJOR, 0); + } + } + return fd; +} + +int create_piped_stdio() { + if (!(current->files->files[0] = open_fd_from_actual_fd(STDIN_FILENO))) { + return -1; + } + if (!(current->files->files[1] = open_fd_from_actual_fd(STDOUT_FILENO))) { + return -1; + } + if (!(current->files->files[2] = open_fd_from_actual_fd(STDERR_FILENO))) { + return -1; + } + return 0; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/init.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/init.h new file mode 100644 index 0000000000..b52bc6cc68 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/init.h @@ -0,0 +1,14 @@ +#ifndef KERNEL_INIT_H +#define KERNEL_INIT_H + +#include "fs/tty.h" + +// Incredibly sloppy. Please do not reference as an example of good API design. +int mount_root(const struct fs_ops *fs, const char *source); +void set_console_device(int major, int minor); +int become_first_process(void); +int become_new_init_child(void); +int create_stdio(const char *file, int major, int minor); +int create_piped_stdio(void); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/inotify.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/inotify.c new file mode 100644 index 0000000000..93eafb52b3 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/inotify.c @@ -0,0 +1,65 @@ +#include "kernel/calls.h" +#include "kernel/fs.h" + +static struct fd_ops inotify_ops; + +#define IN_CLOEXEC_ O_CLOEXEC_ +#define IN_NONBLOCK_ O_NONBLOCK_ + +fd_t sys_inotify_init1(int_t flags) { + STRACE("inotify_init1(%#x)", flags); + if (flags & ~(IN_CLOEXEC_|IN_NONBLOCK_)) + return _EINVAL; + + struct fd *fd = adhoc_fd_create(&inotify_ops); + if (fd == NULL) + return _ENOMEM; + return f_install(fd, flags); +} + +fd_t sys_inotify_init(void) { + return sys_inotify_init1(0); +} + +int_t sys_inotify_add_watch(fd_t inotify_f, addr_t path_addr, uint_t mask) { + STRACE("inotify_add_watch(%d, 0x%x, %#x)", inotify_f, path_addr, mask); + struct fd *fd = f_get(inotify_f); + if (fd == NULL) + return _EBADF; + if (fd->ops != &inotify_ops) + return _EINVAL; + // Return a dummy watch descriptor. We don't actually monitor anything. + return 1; +} + +int_t sys_inotify_rm_watch(fd_t inotify_f, int_t wd) { + STRACE("inotify_rm_watch(%d, %d)", inotify_f, wd); + struct fd *fd = f_get(inotify_f); + if (fd == NULL) + return _EBADF; + if (fd->ops != &inotify_ops) + return _EINVAL; + return 0; +} + +static ssize_t inotify_read(struct fd *fd, void *buf, size_t bufsize) { + // No events are ever generated, so block (or return EAGAIN if nonblocking) + if (fd->flags & O_NONBLOCK_) + return _EAGAIN; + // Block forever — caller would need a signal to break out + lock(&fd->lock); + wait_for(&fd->cond, &fd->lock, NULL); + unlock(&fd->lock); + return _EINTR; +} + +static int inotify_poll(struct fd *fd) { + // Never readable (no events), always writable is wrong for inotify. + // inotify fds are only readable when events are pending. + return 0; +} + +static struct fd_ops inotify_ops = { + .read = inotify_read, + .poll = inotify_poll, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/ipc.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/ipc.c new file mode 100644 index 0000000000..94d1024997 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/ipc.c @@ -0,0 +1,1174 @@ +#include <fcntl.h> +#include <stdint.h> +#include <stdlib.h> +#include <string.h> +#include <sys/mman.h> +#include <unistd.h> + +#include "kernel/calls.h" +#include "kernel/memory.h" +#include "kernel/mm.h" +#include "kernel/time.h" +#include "platform/platform.h" +#include "util/sync.h" + +#define IPC_PRIVATE_ 0 +#define IPC_CREAT_ 01000 +#define IPC_EXCL_ 02000 +#define IPC_RMID_ 0 +#define IPC_SET_ 1 +#define IPC_STAT_ 2 +#define IPC_NOWAIT_ 04000 + +#define MSG_NOERROR_ 010000 +#define MSG_EXCEPT_ 020000 + +#define SHM_RDONLY_ 010000 +#define SHM_RND_ 020000 +#define SHM_REMAP_ 040000 + +#define GETPID_ 11 +#define GETVAL_ 12 +#define GETALL_ 13 +#define GETNCNT_ 14 +#define GETZCNT_ 15 +#define SETVAL_ 16 +#define SETALL_ 17 + +#define SEM_UNDO_ 010000 + +struct shm_segment { + int id; + int key; + size_t size; + pages_t pages; + int fd; + struct shm_segment *next; +}; + +struct shm_attach { + struct mm *mm; + addr_t addr; + pages_t pages; + int shmid; + struct shm_attach *next; +}; + +struct guest_ipc_perm { + int32_t key; + uint32_t uid; + uint32_t gid; + uint32_t cuid; + uint32_t cgid; + uint32_t mode; + int32_t seq; + int64_t pad1; + int64_t pad2; +}; + +struct guest_shmid_ds { + struct guest_ipc_perm shm_perm; + uint64_t shm_segsz; + int64_t shm_atime; + int64_t shm_dtime; + int64_t shm_ctime; + int32_t shm_cpid; + int32_t shm_lpid; + uint64_t shm_nattch; + uint64_t pad1; + uint64_t pad2; +}; + +struct msg_message { + int64_t type; + size_t size; + char *data; + struct msg_message *next; +}; + +struct msg_queue { + int id; + int key; + struct msg_message *messages; + struct msg_queue *next; +}; + +struct sem_set { + int id; + int key; + int nsems; + unsigned short *values; + pid_t_ *pids; + struct sem_set *next; +}; + +struct semop_ { + unsigned short num; + short op; + short flags; +}; + +struct mq_message { + uint_t prio; + size_t size; + char *data; + struct mq_message *next; +}; + +struct mq_queue { + char name[256]; + int unlinked; + int open_count; + int64_t flags; + int64_t maxmsg; + int64_t msgsize; + int64_t curmsgs; + struct mq_message *messages; + struct mq_queue *next; +}; + +struct mq_attr_ { + int64_t flags; + int64_t maxmsg; + int64_t msgsize; + int64_t curmsgs; +}; + +static ssize_t mqfd_read(struct fd *fd, void *buf, size_t bufsize); +static ssize_t mqfd_write(struct fd *fd, const void *buf, size_t bufsize); +static int mqfd_close(struct fd *fd); +static int mqfd_getflags(struct fd *fd); +static int mqfd_setflags(struct fd *fd, dword_t flags); +static const struct fd_ops mqfd_ops = { + .read = mqfd_read, + .write = mqfd_write, + .close = mqfd_close, + .getflags = mqfd_getflags, + .setflags = mqfd_setflags, +}; + +static lock_t shm_lock = LOCK_INITIALIZER; +static cond_t msg_cond = COND_INITIALIZER; +static cond_t sem_cond = COND_INITIALIZER; +static cond_t mq_cond = COND_INITIALIZER; +static int next_shmid = 1; +static int next_msgid = 1; +static int next_semid = 1; +static struct shm_segment *shm_segments; +static struct shm_attach *shm_attaches; +static struct msg_queue *msg_queues; +static struct sem_set *sem_sets; +static struct mq_queue *mq_queues; + +static struct shm_segment *shm_find_id(int shmid) { + for (struct shm_segment *seg = shm_segments; seg; seg = seg->next) + if (seg->id == shmid) + return seg; + return NULL; +} + +static struct shm_segment *shm_find_key(int key) { + for (struct shm_segment *seg = shm_segments; seg; seg = seg->next) + if (seg->key == key) + return seg; + return NULL; +} + +static struct msg_queue *msg_find_id(int msqid) { + for (struct msg_queue *queue = msg_queues; queue; queue = queue->next) + if (queue->id == msqid) + return queue; + return NULL; +} + +static struct msg_queue *msg_find_key(int key) { + for (struct msg_queue *queue = msg_queues; queue; queue = queue->next) + if (queue->key == key) + return queue; + return NULL; +} + +static struct sem_set *sem_find_id(int semid) { + for (struct sem_set *set = sem_sets; set; set = set->next) + if (set->id == semid) + return set; + return NULL; +} + +static struct sem_set *sem_find_key(int key) { + for (struct sem_set *set = sem_sets; set; set = set->next) + if (set->key == key) + return set; + return NULL; +} + +static struct mq_queue *mq_find_name(const char *name) { + for (struct mq_queue *queue = mq_queues; queue; queue = queue->next) + if (!queue->unlinked && strcmp(queue->name, name) == 0) + return queue; + return NULL; +} + +static void mq_free_messages(struct mq_queue *queue) { + struct mq_message *msg = queue->messages; + while (msg != NULL) { + struct mq_message *next = msg->next; + free(msg->data); + free(msg); + msg = next; + } +} + +static void mq_maybe_free_unlocked(struct mq_queue *queue) { + if (!queue->unlinked || queue->open_count > 0) + return; + struct mq_queue **qp = &mq_queues; + while (*qp != NULL && *qp != queue) + qp = &(*qp)->next; + if (*qp == queue) + *qp = queue->next; + mq_free_messages(queue); + free(queue); +} + +static void mq_fill_attr(struct mq_queue *queue, struct mq_attr_ *attr) { + attr->flags = queue->flags; + attr->maxmsg = queue->maxmsg; + attr->msgsize = queue->msgsize; + attr->curmsgs = queue->curmsgs; +} + +static int mqfd_close(struct fd *fd) { + lock(&shm_lock); + struct mq_queue *queue = fd->data; + if (queue != NULL) { + queue->open_count--; + mq_maybe_free_unlocked(queue); + } + unlock(&shm_lock); + return 0; +} + +static int mqfd_getflags(struct fd *fd) { + struct mq_queue *queue = fd->data; + if (queue == NULL) + return 0; + return queue->flags & O_NONBLOCK_; +} + +static int mqfd_setflags(struct fd *fd, dword_t flags) { + lock(&shm_lock); + struct mq_queue *queue = fd->data; + if (queue != NULL) + queue->flags = flags & O_NONBLOCK_; + unlock(&shm_lock); + return 0; +} + +static ssize_t mqfd_read(struct fd *fd, void *buf, size_t bufsize) { + struct mq_queue *queue = fd->data; + if (queue == NULL) + return _EBADF; + lock(&shm_lock); + for (;;) { + if (queue->messages != NULL) + break; + if (queue->flags & O_NONBLOCK_) { + unlock(&shm_lock); + return _EAGAIN; + } + int err = wait_for(&mq_cond, &shm_lock, NULL); + if (err < 0 && err != _EINTR) { + unlock(&shm_lock); + return err; + } + if (err == _EINTR) { + unlock(&shm_lock); + return err; + } + } + struct mq_message *msg = queue->messages; + if (bufsize < msg->size) { + unlock(&shm_lock); + return _EMSGSIZE; + } + queue->messages = msg->next; + queue->curmsgs--; + size_t size = msg->size; + memcpy(buf, msg->data, size); + free(msg->data); + free(msg); + notify(&mq_cond); + unlock(&shm_lock); + return size; +} + +static ssize_t mqfd_write(struct fd *fd, const void *buf, size_t bufsize) { + struct mq_queue *queue = fd->data; + if (queue == NULL) + return _EBADF; + if ((int64_t)bufsize > queue->msgsize) + return _EMSGSIZE; + struct mq_message *msg = calloc(1, sizeof(*msg)); + if (msg == NULL) + return _ENOMEM; + msg->data = malloc(bufsize ? bufsize : 1); + if (msg->data == NULL) { + free(msg); + return _ENOMEM; + } + memcpy(msg->data, buf, bufsize); + msg->size = bufsize; + lock(&shm_lock); + while (queue->curmsgs >= queue->maxmsg) { + if (queue->flags & O_NONBLOCK_) { + unlock(&shm_lock); + free(msg->data); + free(msg); + return _EAGAIN; + } + int err = wait_for(&mq_cond, &shm_lock, NULL); + if (err < 0) { + unlock(&shm_lock); + free(msg->data); + free(msg); + return err; + } + } + struct mq_message **tail = &queue->messages; + while (*tail != NULL) + tail = &(*tail)->next; + *tail = msg; + queue->curmsgs++; + notify(&mq_cond); + unlock(&shm_lock); + return bufsize; +} + +int_t sys_mq_open(addr_t name_addr, int_t oflag, mode_t_ mode, addr_t attr_addr) { + char name[256]; + if (user_read_string(name_addr, name, sizeof(name))) + return _EFAULT; + STRACE("mq_open(\"%s\", %#x, %#x, %#llx)", name, oflag, mode, (unsigned long long)attr_addr); + if (name[0] == '\0') + return _EINVAL; + lock(&shm_lock); + struct mq_queue *queue = mq_find_name(name); + if (queue != NULL && (oflag & O_CREAT_) && (oflag & O_EXCL_)) { + unlock(&shm_lock); + return _EEXIST; + } + if (queue == NULL) { + if (!(oflag & O_CREAT_)) { + unlock(&shm_lock); + return _ENOENT; + } + struct mq_attr_ attr = {.maxmsg = 10, .msgsize = 8192}; + if (attr_addr != 0) { + unlock(&shm_lock); + if (user_read(attr_addr, &attr, sizeof(attr))) + return _EFAULT; + lock(&shm_lock); + } + if (attr.maxmsg <= 0 || attr.msgsize <= 0) { + unlock(&shm_lock); + return _EINVAL; + } + queue = calloc(1, sizeof(*queue)); + if (queue == NULL) { + unlock(&shm_lock); + return _ENOMEM; + } + strlcpy(queue->name, name, sizeof(queue->name)); + queue->maxmsg = attr.maxmsg; + queue->msgsize = attr.msgsize; + queue->next = mq_queues; + mq_queues = queue; + } + queue->open_count++; + queue->flags = oflag & O_NONBLOCK_; + unlock(&shm_lock); + struct fd *fd = adhoc_fd_create(&mqfd_ops); + if (fd == NULL) { + lock(&shm_lock); + queue->open_count--; + mq_maybe_free_unlocked(queue); + unlock(&shm_lock); + return _ENOMEM; + } + fd->data = queue; + fd->stat.mode = S_IFIFO | (mode & 0777); + return f_install(fd, oflag); +} + +int_t sys_mq_unlink(addr_t name_addr) { + char name[256]; + if (user_read_string(name_addr, name, sizeof(name))) + return _EFAULT; + STRACE("mq_unlink(\"%s\")", name); + lock(&shm_lock); + struct mq_queue *queue = mq_find_name(name); + if (queue == NULL) { + unlock(&shm_lock); + return _ENOENT; + } + queue->unlinked = 1; + mq_maybe_free_unlocked(queue); + unlock(&shm_lock); + return 0; +} + +int_t sys_mq_timedsend(fd_t mqdes, addr_t msg_ptr, size_t msg_len, uint_t msg_prio, addr_t abs_timeout_addr) { + (void)abs_timeout_addr; + STRACE("mq_timedsend(%d, %#llx, %#zx, %u, %#llx)", mqdes, (unsigned long long)msg_ptr, msg_len, msg_prio, (unsigned long long)abs_timeout_addr); + struct fd *fd = f_get(mqdes); + if (fd == NULL || fd->ops != &mqfd_ops) + return _EBADF; + char *buf = malloc(msg_len ? msg_len : 1); + if (buf == NULL) + return _ENOMEM; + if (user_read(msg_ptr, buf, msg_len)) { + free(buf); + return _EFAULT; + } + struct mq_queue *queue = fd->data; + struct mq_message *msg = calloc(1, sizeof(*msg)); + if (msg == NULL) { + free(buf); + return _ENOMEM; + } + msg->data = buf; + msg->size = msg_len; + msg->prio = msg_prio; + lock(&shm_lock); + if ((int64_t)msg_len > queue->msgsize) { + unlock(&shm_lock); + free(msg->data); + free(msg); + return _EMSGSIZE; + } + while (queue->curmsgs >= queue->maxmsg) { + if (queue->flags & O_NONBLOCK_) { + unlock(&shm_lock); + free(msg->data); + free(msg); + return _EAGAIN; + } + int err = wait_for(&mq_cond, &shm_lock, NULL); + if (err < 0) { + unlock(&shm_lock); + free(msg->data); + free(msg); + return err; + } + } + struct mq_message **slot = &queue->messages; + while (*slot != NULL && (*slot)->prio >= msg_prio) + slot = &(*slot)->next; + msg->next = *slot; + *slot = msg; + queue->curmsgs++; + notify(&mq_cond); + unlock(&shm_lock); + return 0; +} + +ssize_t sys_mq_timedreceive(fd_t mqdes, addr_t msg_ptr, size_t msg_len, addr_t msg_prio_addr, addr_t abs_timeout_addr) { + (void)abs_timeout_addr; + STRACE("mq_timedreceive(%d, %#llx, %#zx, %#llx, %#llx)", mqdes, (unsigned long long)msg_ptr, msg_len, (unsigned long long)msg_prio_addr, (unsigned long long)abs_timeout_addr); + struct fd *fd = f_get(mqdes); + if (fd == NULL || fd->ops != &mqfd_ops) + return _EBADF; + struct mq_queue *queue = fd->data; + lock(&shm_lock); + while (queue->messages == NULL) { + if (queue->flags & O_NONBLOCK_) { + unlock(&shm_lock); + return _EAGAIN; + } + int err = wait_for(&mq_cond, &shm_lock, NULL); + if (err < 0) { + unlock(&shm_lock); + return err; + } + } + struct mq_message *msg = queue->messages; + if (msg_len < msg->size) { + unlock(&shm_lock); + return _EMSGSIZE; + } + queue->messages = msg->next; + queue->curmsgs--; + size_t size = msg->size; + uint_t prio = msg->prio; + char *data = msg->data; + free(msg); + notify(&mq_cond); + unlock(&shm_lock); + int err = user_write(msg_ptr, data, size); + free(data); + if (err) + return _EFAULT; + if (msg_prio_addr != 0 && user_put(msg_prio_addr, prio)) + return _EFAULT; + return size; +} + +int_t sys_mq_notify(fd_t mqdes, addr_t notification_addr) { + (void)notification_addr; + struct fd *fd = f_get(mqdes); + if (fd == NULL || fd->ops != &mqfd_ops) + return _EBADF; + return 0; +} + +int_t sys_mq_getsetattr(fd_t mqdes, addr_t newattr_addr, addr_t oldattr_addr) { + struct fd *fd = f_get(mqdes); + if (fd == NULL || fd->ops != &mqfd_ops) + return _EBADF; + lock(&shm_lock); + struct mq_queue *queue = fd->data; + struct mq_attr_ old; + mq_fill_attr(queue, &old); + if (newattr_addr != 0) { + struct mq_attr_ newattr; + unlock(&shm_lock); + if (user_read(newattr_addr, &newattr, sizeof(newattr))) + return _EFAULT; + lock(&shm_lock); + queue = fd->data; + queue->flags = newattr.flags & O_NONBLOCK_; + } + unlock(&shm_lock); + if (oldattr_addr != 0 && user_write(oldattr_addr, &old, sizeof(old))) + return _EFAULT; + return 0; +} + +int_t sys_msgget(int_t key, int_t msgflg) { + STRACE("msgget(%#x, %#x)", key, msgflg); + lock(&shm_lock); + struct msg_queue *queue = key == IPC_PRIVATE_ ? NULL : msg_find_key(key); + if (queue != NULL) { + if ((msgflg & IPC_CREAT_) && (msgflg & IPC_EXCL_)) { + unlock(&shm_lock); + return _EEXIST; + } + int id = queue->id; + unlock(&shm_lock); + return id; + } + if (key != IPC_PRIVATE_ && !(msgflg & IPC_CREAT_)) { + unlock(&shm_lock); + return _ENOENT; + } + queue = calloc(1, sizeof(*queue)); + if (queue == NULL) { + unlock(&shm_lock); + return _ENOMEM; + } + queue->id = next_msgid++; + if (next_msgid <= 0) + next_msgid = 1; + queue->key = key; + queue->next = msg_queues; + msg_queues = queue; + int id = queue->id; + unlock(&shm_lock); + return id; +} + +int_t sys_msgctl(int_t msqid, int_t cmd, addr_t buf_addr) { + STRACE("msgctl(%d, %d, %#llx)", msqid, cmd, (unsigned long long) buf_addr); + lock(&shm_lock); + struct msg_queue **queuep = &msg_queues; + while (*queuep != NULL && (*queuep)->id != msqid) + queuep = &(*queuep)->next; + struct msg_queue *queue = *queuep; + if (queue == NULL) { + unlock(&shm_lock); + return _EINVAL; + } + if (cmd == IPC_RMID_) { + *queuep = queue->next; + struct msg_message *msg = queue->messages; + while (msg != NULL) { + struct msg_message *next = msg->next; + free(msg->data); + free(msg); + msg = next; + } + free(queue); + notify(&msg_cond); + unlock(&shm_lock); + return 0; + } + unlock(&shm_lock); + if (cmd == IPC_STAT_ || cmd == IPC_SET_) + return 0; + return _EINVAL; +} + +int_t sys_msgsnd(int_t msqid, addr_t msgp, size_t msgsz, int_t msgflg) { + STRACE("msgsnd(%d, %#llx, %#zx, %#x)", msqid, (unsigned long long) msgp, msgsz, msgflg); + (void) msgflg; + int64_t type; + if (user_read(msgp, &type, sizeof(type)) < 0) + return _EFAULT; + if (type <= 0) + return _EINVAL; + struct msg_message *msg = calloc(1, sizeof(*msg)); + if (msg == NULL) + return _ENOMEM; + msg->data = malloc(msgsz ? msgsz : 1); + if (msg->data == NULL) { + free(msg); + return _ENOMEM; + } + if (msgsz && user_read(msgp + sizeof(type), msg->data, msgsz) < 0) { + free(msg->data); + free(msg); + return _EFAULT; + } + msg->type = type; + msg->size = msgsz; + + lock(&shm_lock); + struct msg_queue *queue = msg_find_id(msqid); + if (queue == NULL) { + unlock(&shm_lock); + free(msg->data); + free(msg); + return _EINVAL; + } + struct msg_message **tail = &queue->messages; + while (*tail != NULL) + tail = &(*tail)->next; + *tail = msg; + notify(&msg_cond); + unlock(&shm_lock); + return 0; +} + +static bool msg_matches(int64_t have, int64_t want, int_t flags) { + if (want == 0) + return true; + if (want > 0) { + if (flags & MSG_EXCEPT_) + return have != want; + return have == want; + } + return have <= -want; +} + +ssize_t sys_msgrcv(int_t msqid, addr_t msgp, size_t msgsz, int64_t msgtyp, int_t msgflg) { + STRACE("msgrcv(%d, %#llx, %#zx, %lld, %#x)", msqid, (unsigned long long) msgp, msgsz, (long long) msgtyp, msgflg); + lock(&shm_lock); + for (;;) { + struct msg_queue *queue = msg_find_id(msqid); + if (queue == NULL) { + unlock(&shm_lock); + return _EINVAL; + } + struct msg_message **msgp_link = &queue->messages; + struct msg_message **best_link = NULL; + int64_t best_type = INT64_MAX; + while (*msgp_link != NULL) { + struct msg_message *candidate = *msgp_link; + if (msg_matches(candidate->type, msgtyp, msgflg)) { + if (msgtyp < 0) { + if (candidate->type < best_type) { + best_type = candidate->type; + best_link = msgp_link; + } + } else { + best_link = msgp_link; + break; + } + } + msgp_link = &candidate->next; + } + if (best_link != NULL) { + struct msg_message *msg = *best_link; + if (msg->size > msgsz && !(msgflg & MSG_NOERROR_)) { + unlock(&shm_lock); + return _E2BIG; + } + *best_link = msg->next; + size_t copy = msg->size < msgsz ? msg->size : msgsz; + int64_t type = msg->type; + char *data = msg->data; + size_t original_size = msg->size; + free(msg); + unlock(&shm_lock); + int err = user_write(msgp, &type, sizeof(type)); + if (err == 0 && copy) + err = user_write(msgp + sizeof(type), data, copy); + free(data); + if (err < 0) + return _EFAULT; + return copy < original_size ? (ssize_t) copy : (ssize_t) original_size; + } + if (msgflg & IPC_NOWAIT_) { + unlock(&shm_lock); + return _ENODATA; + } + current->blocking = true; + int err = wait_for(&msg_cond, &shm_lock, NULL); + current->blocking = false; + if (err < 0) { + unlock(&shm_lock); + return err; + } + } +} + +int_t sys_semget(int_t key, int_t nsems, int_t semflg) { + STRACE("semget(%#x, %d, %#x)", key, nsems, semflg); + lock(&shm_lock); + struct sem_set *set = key == IPC_PRIVATE_ ? NULL : sem_find_key(key); + if (set != NULL) { + if ((semflg & IPC_CREAT_) && (semflg & IPC_EXCL_)) { + unlock(&shm_lock); + return _EEXIST; + } + if (nsems > 0 && nsems > set->nsems) { + unlock(&shm_lock); + return _EINVAL; + } + int id = set->id; + unlock(&shm_lock); + return id; + } + if (key != IPC_PRIVATE_ && !(semflg & IPC_CREAT_)) { + unlock(&shm_lock); + return _ENOENT; + } + if (nsems <= 0) { + unlock(&shm_lock); + return _EINVAL; + } + set = calloc(1, sizeof(*set)); + if (set == NULL) { + unlock(&shm_lock); + return _ENOMEM; + } + set->values = calloc(nsems, sizeof(unsigned short)); + set->pids = calloc(nsems, sizeof(pid_t_)); + if (set->values == NULL || set->pids == NULL) { + free(set->values); + free(set->pids); + free(set); + unlock(&shm_lock); + return _ENOMEM; + } + set->id = next_semid++; + if (next_semid <= 0) + next_semid = 1; + set->key = key; + set->nsems = nsems; + set->next = sem_sets; + sem_sets = set; + int id = set->id; + unlock(&shm_lock); + return id; +} + +int_t sys_semctl(int_t semid, int_t semnum, int_t cmd, addr_t arg) { + STRACE("semctl(%d, %d, %d, %#llx)", semid, semnum, cmd, (unsigned long long)arg); + lock(&shm_lock); + struct sem_set **setp = &sem_sets; + while (*setp != NULL && (*setp)->id != semid) + setp = &(*setp)->next; + struct sem_set *set = *setp; + if (set == NULL) { + unlock(&shm_lock); + return _EINVAL; + } + if (cmd == IPC_RMID_) { + *setp = set->next; + free(set->values); + free(set->pids); + free(set); + notify(&sem_cond); + unlock(&shm_lock); + return 0; + } + if (semnum < 0 || semnum >= set->nsems) { + unlock(&shm_lock); + return _EINVAL; + } + switch (cmd) { + case GETVAL_: { + int val = set->values[semnum]; + unlock(&shm_lock); + return val; + } + case SETVAL_: { + set->values[semnum] = (unsigned short)(arg & 0xffff); + set->pids[semnum] = current->pid; + notify(&sem_cond); + unlock(&shm_lock); + return 0; + } + case GETPID_: { + int pid = set->pids[semnum]; + unlock(&shm_lock); + return pid; + } + case GETNCNT_: + case GETZCNT_: + unlock(&shm_lock); + return 0; + case GETALL_: { + unsigned short *vals = malloc(sizeof(unsigned short) * set->nsems); + if (vals == NULL) { + unlock(&shm_lock); + return _ENOMEM; + } + memcpy(vals, set->values, sizeof(unsigned short) * set->nsems); + unlock(&shm_lock); + int err = user_write(arg, vals, sizeof(unsigned short) * set->nsems); + free(vals); + return err ? _EFAULT : 0; + } + case SETALL_: { + unsigned short *vals = malloc(sizeof(unsigned short) * set->nsems); + if (vals == NULL) { + unlock(&shm_lock); + return _ENOMEM; + } + unlock(&shm_lock); + if (user_read(arg, vals, sizeof(unsigned short) * set->nsems)) { + free(vals); + return _EFAULT; + } + lock(&shm_lock); + set = sem_find_id(semid); + if (set == NULL) { + unlock(&shm_lock); + free(vals); + return _EINVAL; + } + memcpy(set->values, vals, sizeof(unsigned short) * set->nsems); + for (int i = 0; i < set->nsems; i++) + set->pids[i] = current->pid; + notify(&sem_cond); + unlock(&shm_lock); + free(vals); + return 0; + } + case IPC_STAT_: + case IPC_SET_: + unlock(&shm_lock); + return 0; + default: + unlock(&shm_lock); + return _EINVAL; + } +} + +static int sem_try_apply(struct sem_set *set, struct semop_ *ops, size_t nsops, bool apply) { + for (size_t i = 0; i < nsops; i++) { + if (ops[i].num >= set->nsems) + return _EFBIG; + int val = set->values[ops[i].num]; + if (ops[i].op < 0 && val < -ops[i].op) + return _EAGAIN; + if (ops[i].op == 0 && val != 0) + return _EAGAIN; + } + if (apply) { + for (size_t i = 0; i < nsops; i++) { + int idx = ops[i].num; + set->values[idx] = (unsigned short)(set->values[idx] + ops[i].op); + set->pids[idx] = current->pid; + } + } + return 0; +} + +int_t sys_semtimedop(int_t semid, addr_t sops_addr, size_t nsops, addr_t timeout_addr) { + STRACE("semtimedop(%d, %#llx, %#zx, %#llx)", semid, (unsigned long long)sops_addr, nsops, (unsigned long long)timeout_addr); + if (nsops == 0 || nsops > 1024) + return _EINVAL; + struct semop_ *ops = malloc(sizeof(*ops) * nsops); + if (ops == NULL) + return _ENOMEM; + if (user_read(sops_addr, ops, sizeof(*ops) * nsops)) { + free(ops); + return _EFAULT; + } + struct timespec timeout, *timeout_ptr = NULL; + if (timeout_addr != 0) { + struct timespec_ ts; + if (user_get(timeout_addr, ts)) { + free(ops); + return _EFAULT; + } + timeout.tv_sec = ts.sec; + timeout.tv_nsec = ts.nsec; + timeout_ptr = &timeout; + } + + lock(&shm_lock); + int err; + for (;;) { + struct sem_set *set = sem_find_id(semid); + if (set == NULL) { + err = _EINVAL; + break; + } + err = sem_try_apply(set, ops, nsops, true); + if (err == 0) { + notify(&sem_cond); + break; + } + bool nowait = false; + for (size_t i = 0; i < nsops; i++) + if (ops[i].flags & IPC_NOWAIT_) + nowait = true; + if (err != _EAGAIN || nowait) + break; + current->blocking = true; + err = wait_for(&sem_cond, &shm_lock, timeout_ptr); + current->blocking = false; + if (err == _ETIMEDOUT) { + err = _EAGAIN; + break; + } + if (err < 0 && err != _EINTR) + break; + if (err == _EINTR) + break; + } + unlock(&shm_lock); + free(ops); + return err; +} + +int_t sys_semop(int_t semid, addr_t sops_addr, size_t nsops) { + return sys_semtimedop(semid, sops_addr, nsops, 0); +} + +int_t sys_shmget(int_t key, size_t size, int_t shmflg) { + STRACE("shmget(%#x, %#zx, %#x)", key, size, shmflg); + lock(&shm_lock); + + struct shm_segment *seg = key == IPC_PRIVATE_ ? NULL : shm_find_key(key); + if (seg != NULL) { + if ((shmflg & IPC_CREAT_) && (shmflg & IPC_EXCL_)) { + unlock(&shm_lock); + return _EEXIST; + } + if (size > seg->size) { + unlock(&shm_lock); + return _EINVAL; + } + int id = seg->id; + unlock(&shm_lock); + return id; + } + + if (key != IPC_PRIVATE_ && !(shmflg & IPC_CREAT_)) { + unlock(&shm_lock); + return _ENOENT; + } + if (size == 0) { + unlock(&shm_lock); + return _EINVAL; + } + + pages_t pages = PAGE_ROUND_UP(size); + size_t map_size = (size_t) pages << PAGE_BITS; + int fd = platform_create_shared_memory_fd(map_size); + if (fd < 0) { + int err = errno_map(); + unlock(&shm_lock); + return err; + } + fcntl(fd, F_SETFD, FD_CLOEXEC); + + seg = calloc(1, sizeof(*seg)); + if (seg == NULL) { + close(fd); + unlock(&shm_lock); + return _ENOMEM; + } + seg->id = next_shmid++; + if (next_shmid <= 0) + next_shmid = 1; + seg->key = key; + seg->size = size; + seg->pages = pages; + seg->fd = fd; + seg->next = shm_segments; + shm_segments = seg; + + int id = seg->id; + unlock(&shm_lock); + return id; +} + +int_t sys_shmctl(int_t shmid, int_t cmd, addr_t buf_addr) { + STRACE("shmctl(%d, %d, %#llx)", shmid, cmd, (unsigned long long) buf_addr); + lock(&shm_lock); + struct shm_segment **segp = &shm_segments; + while (*segp != NULL && (*segp)->id != shmid) + segp = &(*segp)->next; + struct shm_segment *seg = *segp; + if (seg == NULL) { + unlock(&shm_lock); + return _EINVAL; + } + + if (cmd == IPC_RMID_) { + *segp = seg->next; + close(seg->fd); + free(seg); + unlock(&shm_lock); + return 0; + } + + if (cmd == IPC_STAT_) { + if (buf_addr == 0) { + unlock(&shm_lock); + return _EFAULT; + } + uint64_t nattch = 0; + for (struct shm_attach *attach = shm_attaches; attach; attach = attach->next) + if (attach->shmid == shmid) + nattch++; + struct guest_shmid_ds ds = { + .shm_perm = { + .key = seg->key, + .uid = 0, + .gid = 0, + .cuid = 0, + .cgid = 0, + .mode = 0666, + .seq = 0, + }, + .shm_segsz = seg->size, + .shm_nattch = nattch, + }; + unlock(&shm_lock); + return user_write(buf_addr, &ds, sizeof(ds)); + } + + unlock(&shm_lock); + if (cmd == IPC_SET_) + return 0; + return _EINVAL; +} + +addr_t sys_shmat(int_t shmid, addr_t shmaddr, int_t shmflg) { + STRACE("shmat(%d, %#llx, %#x)", shmid, (unsigned long long) shmaddr, shmflg); + lock(&shm_lock); + struct shm_segment *seg = shm_find_id(shmid); + if (seg == NULL) { + unlock(&shm_lock); + return _EINVAL; + } + + pages_t pages = seg->pages; + size_t map_size = (size_t) pages << PAGE_BITS; + int host_prot = PROT_READ; + unsigned guest_prot = P_READ | P_SHARED; + if (!(shmflg & SHM_RDONLY_)) { + host_prot |= PROT_WRITE; + guest_prot |= P_WRITE; + } + + void *host_map = mmap(NULL, map_size, host_prot, MAP_SHARED, seg->fd, 0); + if (host_map == MAP_FAILED) { + int err = errno_map(); + unlock(&shm_lock); + return err; + } + + write_wrlock(¤t->mem->lock); + page_t page; + if (shmaddr != 0) { + if (shmflg & SHM_RND_) + shmaddr = BYTES_ROUND_DOWN(shmaddr); + if (PGOFFSET(shmaddr) != 0) { + write_wrunlock(¤t->mem->lock); + munmap(host_map, map_size); + unlock(&shm_lock); + return _EINVAL; + } + page = PAGE(shmaddr); + if (!(shmflg & SHM_REMAP_) && !pt_is_hole(current->mem, page, pages)) { + write_wrunlock(¤t->mem->lock); + munmap(host_map, map_size); + unlock(&shm_lock); + return _EINVAL; + } + } else { + page = pt_find_hole(current->mem, pages); + if (page == BAD_PAGE) { + write_wrunlock(¤t->mem->lock); + munmap(host_map, map_size); + unlock(&shm_lock); + return _ENOMEM; + } + } + + int err = pt_map(current->mem, page, pages, host_map, 0, guest_prot); + write_wrunlock(¤t->mem->lock); + if (err < 0) { + munmap(host_map, map_size); + unlock(&shm_lock); + return err; + } + + struct shm_attach *attach = calloc(1, sizeof(*attach)); + if (attach == NULL) { + write_wrlock(¤t->mem->lock); + pt_unmap_always(current->mem, page, pages); + write_wrunlock(¤t->mem->lock); + unlock(&shm_lock); + return _ENOMEM; + } + attach->mm = current->mm; + attach->addr = page << PAGE_BITS; + attach->pages = pages; + attach->shmid = shmid; + attach->next = shm_attaches; + shm_attaches = attach; + + addr_t result = page << PAGE_BITS; + unlock(&shm_lock); + return result; +} + +int_t sys_shmdt(addr_t shmaddr) { + STRACE("shmdt(%#llx)", (unsigned long long) shmaddr); + if (PGOFFSET(shmaddr) != 0) + return _EINVAL; + + lock(&shm_lock); + struct shm_attach **attachp = &shm_attaches; + while (*attachp != NULL && !((*attachp)->mm == current->mm && (*attachp)->addr == shmaddr)) + attachp = &(*attachp)->next; + struct shm_attach *attach = *attachp; + if (attach == NULL) { + unlock(&shm_lock); + return _EINVAL; + } + *attachp = attach->next; + pages_t pages = attach->pages; + free(attach); + unlock(&shm_lock); + + write_wrlock(¤t->mem->lock); + int err = pt_unmap(current->mem, PAGE(shmaddr), pages); + write_wrunlock(¤t->mem->lock); + return err < 0 ? _EINVAL : 0; +} + +int_t sys_ipc(uint_t call, int_t first, int_t second, int_t third, addr_t ptr, int_t fifth) { + STRACE("ipc(%u, %d, %d, %d, %#x, %d)", call, first, second, third, ptr, fifth); + return _ENOSYS; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/libfakefs_redirect.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/libfakefs_redirect.c new file mode 100644 index 0000000000..7ae327b65b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/libfakefs_redirect.c @@ -0,0 +1,241 @@ +// libfakefs_redirect.dylib — DYLD interpose library for native offload. +// +// Injected via DYLD_INSERT_LIBRARIES into native processes spawned by +// native_offload. Intercepts filesystem syscalls and transparently redirects +// absolute paths from guest root (/) to the fakefs data directory on host. +// +// Config via environment variables: +// FAKEFS_ROOT=/path/to/fakefs/data (required) +// +// Example: guest "/tmp/foo.mp4" → host "/Users/.../fakefs/data/tmp/foo.mp4" + +#include <fcntl.h> +#include <sys/stat.h> +#include <dirent.h> +#include <unistd.h> +#include <stdlib.h> +#include <string.h> +#include <stdio.h> +#include <stdarg.h> +#include <limits.h> +#include <dlfcn.h> + +// --- Configuration --- + +static char g_root[PATH_MAX]; // fakefs data root, e.g. "/Users/.../fakefs/data" +static size_t g_root_len; +static int g_initialized; + +// Directories to NOT redirect (host-only paths that native binaries need) +static const char *passthrough_prefixes[] = { + "/dev/", + "/opt/", + "/usr/local/", + "/usr/lib/", + "/usr/share/", + "/System/", + "/Library/", + "/Applications/", + "/private/", + "/Users/", + "/cores/", + "/AppleInternal/", + NULL +}; + +__attribute__((constructor)) +static void fakefs_redirect_init(void) { + const char *root = getenv("FAKEFS_ROOT"); + if (!root || !root[0]) + return; + size_t len = strlen(root); + // Strip trailing slash + if (len > 1 && root[len - 1] == '/') len--; + if (len >= PATH_MAX) return; + memcpy(g_root, root, len); + g_root[len] = '\0'; + g_root_len = len; + g_initialized = 1; +} + +// Rewrite an absolute guest path to a host fakefs path. +// Returns `buf` if rewritten, or the original `path` if no rewrite needed. +static const char *redirect_path(const char *path, char *buf, size_t bufsz) { + if (!g_initialized || !path || path[0] != '/') + return path; + + // Don't redirect paths that are already under the fakefs root + if (strncmp(path, g_root, g_root_len) == 0) + return path; + + // Don't redirect host-only paths + for (const char **pp = passthrough_prefixes; *pp; pp++) { + size_t plen = strlen(*pp); + if (strncmp(path, *pp, plen) == 0) + return path; + } + + // Also passthrough /usr/bin and /usr/sbin (but NOT /usr — guest has /usr/share etc.) + if (strncmp(path, "/usr/bin/", 9) == 0 || strncmp(path, "/usr/sbin/", 10) == 0) + return path; + + // Redirect: prepend fakefs root + size_t plen = strlen(path); + if (g_root_len + plen + 1 > bufsz) + return path; // too long, skip + + memcpy(buf, g_root, g_root_len); + memcpy(buf + g_root_len, path, plen + 1); // includes '\0' + return buf; +} + +// --- Interposed functions --- +// We use the __DATA,__interpose section which is cleaner than dlsym(RTLD_NEXT). +// dyld patches the GOT so all calls from the target binary go through our wrappers. + +#define DYLD_INTERPOSE(_replacement, _replacee) \ + __attribute__((used)) static struct { const void *r; const void *e; } \ + _interpose_##_replacee \ + __attribute__((section("__DATA,__interpose,interposing"))) = { \ + (const void *)(unsigned long)&_replacement, \ + (const void *)(unsigned long)&_replacee \ + }; + +// open +static int my_open(const char *path, int flags, ...) { + char buf[PATH_MAX]; + path = redirect_path(path, buf, sizeof(buf)); + mode_t mode = 0; + if (flags & O_CREAT) { + va_list ap; + va_start(ap, flags); + mode = (mode_t)va_arg(ap, int); + va_end(ap); + } + return open(path, flags, mode); +} +DYLD_INTERPOSE(my_open, open) + +// openat — only redirect if fd == AT_FDCWD and path is absolute +static int my_openat(int fd, const char *path, int flags, ...) { + char buf[PATH_MAX]; + if (fd == AT_FDCWD) + path = redirect_path(path, buf, sizeof(buf)); + mode_t mode = 0; + if (flags & O_CREAT) { + va_list ap; + va_start(ap, flags); + mode = (mode_t)va_arg(ap, int); + va_end(ap); + } + return openat(fd, path, flags, mode); +} +DYLD_INTERPOSE(my_openat, openat) + +// stat +static int my_stat(const char *path, struct stat *sb) { + char buf[PATH_MAX]; + return stat(redirect_path(path, buf, sizeof(buf)), sb); +} +DYLD_INTERPOSE(my_stat, stat) + +// lstat +static int my_lstat(const char *path, struct stat *sb) { + char buf[PATH_MAX]; + return lstat(redirect_path(path, buf, sizeof(buf)), sb); +} +DYLD_INTERPOSE(my_lstat, lstat) + +// access +static int my_access(const char *path, int mode) { + char buf[PATH_MAX]; + return access(redirect_path(path, buf, sizeof(buf)), mode); +} +DYLD_INTERPOSE(my_access, access) + +// faccessat +static int my_faccessat(int fd, const char *path, int mode, int flag) { + char buf[PATH_MAX]; + if (fd == AT_FDCWD) + path = redirect_path(path, buf, sizeof(buf)); + return faccessat(fd, path, mode, flag); +} +DYLD_INTERPOSE(my_faccessat, faccessat) + +// opendir +static DIR *my_opendir(const char *path) { + char buf[PATH_MAX]; + return opendir(redirect_path(path, buf, sizeof(buf))); +} +DYLD_INTERPOSE(my_opendir, opendir) + +// realpath +static char *my_realpath(const char *path, char *resolved) { + char buf[PATH_MAX]; + return realpath(redirect_path(path, buf, sizeof(buf)), resolved); +} +DYLD_INTERPOSE(my_realpath, realpath) + +// rename +static int my_rename(const char *old, const char *new) { + char buf1[PATH_MAX], buf2[PATH_MAX]; + return rename(redirect_path(old, buf1, sizeof(buf1)), + redirect_path(new, buf2, sizeof(buf2))); +} +DYLD_INTERPOSE(my_rename, rename) + +// unlink +static int my_unlink(const char *path) { + char buf[PATH_MAX]; + return unlink(redirect_path(path, buf, sizeof(buf))); +} +DYLD_INTERPOSE(my_unlink, unlink) + +// mkdir +static int my_mkdir(const char *path, mode_t mode) { + char buf[PATH_MAX]; + return mkdir(redirect_path(path, buf, sizeof(buf)), mode); +} +DYLD_INTERPOSE(my_mkdir, mkdir) + +// rmdir +static int my_rmdir(const char *path) { + char buf[PATH_MAX]; + return rmdir(redirect_path(path, buf, sizeof(buf))); +} +DYLD_INTERPOSE(my_rmdir, rmdir) + +// chdir +static int my_chdir(const char *path) { + char buf[PATH_MAX]; + return chdir(redirect_path(path, buf, sizeof(buf))); +} +DYLD_INTERPOSE(my_chdir, chdir) + +// fopen +static FILE *my_fopen(const char *path, const char *mode) { + char buf[PATH_MAX]; + return fopen(redirect_path(path, buf, sizeof(buf)), mode); +} +DYLD_INTERPOSE(my_fopen, fopen) + +// truncate +static int my_truncate(const char *path, off_t length) { + char buf[PATH_MAX]; + return truncate(redirect_path(path, buf, sizeof(buf)), length); +} +DYLD_INTERPOSE(my_truncate, truncate) + +// readlink +static ssize_t my_readlink(const char *path, char *lbuf, size_t bufsiz) { + char pbuf[PATH_MAX]; + return readlink(redirect_path(path, pbuf, sizeof(pbuf)), lbuf, bufsiz); +} +DYLD_INTERPOSE(my_readlink, readlink) + +// chmod +static int my_chmod(const char *path, mode_t mode) { + char buf[PATH_MAX]; + return chmod(redirect_path(path, buf, sizeof(buf)), mode); +} +DYLD_INTERPOSE(my_chmod, chmod) diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/log.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/log.c new file mode 100644 index 0000000000..dd194f357b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/log.c @@ -0,0 +1,195 @@ +#include <stdio.h> +#include <fcntl.h> +#include <stdarg.h> +#include <string.h> +#include <sys/uio.h> +#include <syslog.h> +#if LOG_HANDLER_NSLOG +#include <CoreFoundation/CoreFoundation.h> +#endif +#if LOG_HANDLER_OS_LOG +#include <os/log.h> +#endif +#include "kernel/calls.h" +#include "util/sync.h" +#include "util/fifo.h" +#include "kernel/task.h" +#include "misc.h" + +#define LOG_BUF_SHIFT 20 +static char log_buffer[1 << LOG_BUF_SHIFT]; +static struct fifo log_buf = FIFO_INIT(log_buffer); +static size_t log_max_since_clear = 0; +static lock_t log_lock = LOCK_INITIALIZER; + +#define SYSLOG_ACTION_CLOSE_ 0 +#define SYSLOG_ACTION_OPEN_ 1 +#define SYSLOG_ACTION_READ_ 2 +#define SYSLOG_ACTION_READ_ALL_ 3 +#define SYSLOG_ACTION_READ_CLEAR_ 4 +#define SYSLOG_ACTION_CLEAR_ 5 +#define SYSLOG_ACTION_CONSOLE_OFF_ 6 +#define SYSLOG_ACTION_CONSOLE_ON_ 7 +#define SYSLOG_ACTION_CONSOLE_LEVEL_ 8 +#define SYSLOG_ACTION_SIZE_UNREAD_ 9 +#define SYSLOG_ACTION_SIZE_BUFFER_ 10 + +static int syslog_read(addr_t buf_addr, int_t len, int flags) { + if (len < 0) + return _EINVAL; + if (flags & FIFO_LAST) { + if ((size_t) len > log_max_since_clear) + len = log_max_since_clear; + } else { + if ((size_t) len > fifo_capacity(&log_buf)) + len = fifo_capacity(&log_buf); + } + char *buf = malloc(len); + fifo_read(&log_buf, buf, len, flags); + int fail = user_write(buf_addr, buf, len); + free(buf); + if (fail) + return _EFAULT; + return len; +} + +static int do_syslog(int type, addr_t buf_addr, int_t len) { + int res; + switch (type) { + case SYSLOG_ACTION_READ_: + return syslog_read(buf_addr, len, 0); + case SYSLOG_ACTION_READ_ALL_: + return syslog_read(buf_addr, len, FIFO_LAST | FIFO_PEEK); + + case SYSLOG_ACTION_READ_CLEAR_: + res = syslog_read(buf_addr, len, FIFO_LAST | FIFO_PEEK); + if (res < 0) + return res; + fallthrough; + case SYSLOG_ACTION_CLEAR_: + log_max_since_clear = 0; + return 0; + + case SYSLOG_ACTION_SIZE_UNREAD_: + return fifo_size(&log_buf); + case SYSLOG_ACTION_SIZE_BUFFER_: + return fifo_capacity(&log_buf); + + case SYSLOG_ACTION_CLOSE_: + case SYSLOG_ACTION_OPEN_: + case SYSLOG_ACTION_CONSOLE_OFF_: + case SYSLOG_ACTION_CONSOLE_ON_: + case SYSLOG_ACTION_CONSOLE_LEVEL_: + return 0; + default: + return _EINVAL; + } +} +int_t sys_syslog(int_t type, addr_t buf_addr, int_t len) { + lock(&log_lock); + int retval = do_syslog(type, buf_addr, len); + unlock(&log_lock); + return retval; +} + +static void log_buf_append(const char *msg) { + fifo_write(&log_buf, msg, strlen(msg), FIFO_OVERWRITE); + log_max_since_clear += strlen(msg); + if (log_max_since_clear > fifo_capacity(&log_buf)) + log_max_since_clear = fifo_capacity(&log_buf); +} +static void log_line(const char *line); +static void output_line(const char *line) { + // send it to stdout or wherever + log_line(line); + // add it to the circular buffer + log_buf_append(line); + log_buf_append("\n"); +} + +void ish_vprintk(const char *msg, va_list args) { + // Format into a per-thread line buffer. Keep incomplete trailing lines for + // the next call, but never let a long diagnostic overflow the buffer. + static __thread char buf[16384] = ""; + static __thread size_t buf_size = 0; + size_t remaining = sizeof(buf) - buf_size; + if (remaining == 0) { + buf_size = sizeof(buf) - 1; + buf[buf_size] = '\0'; + remaining = 1; + } + int written = vsnprintf(buf + buf_size, remaining, msg, args); + if (written < 0) + return; + if ((size_t) written >= remaining) + buf_size = sizeof(buf) - 1; + else + buf_size += (size_t) written; + + // output up to the last newline, leave the rest in the buffer + lock(&log_lock); + char *b = buf; + char *p; + while ((p = strchr(b, '\n')) != NULL) { + *p = '\0'; + output_line(b); + *p = '\n'; + buf_size -= p + 1 - b; + b = p + 1; + } + unlock(&log_lock); + memmove(buf, b, strlen(b) + 1); +} +void ish_printk(const char *msg, ...) { + va_list args; + va_start(args, msg); + ish_vprintk(msg, args); + va_end(args); +} + +#if LOG_HANDLER_DPRINTF +#define NEWLINE "\r\n" +static void log_line(const char *line) { + struct iovec output[2] = {{(void *) line, strlen(line)}, {"\n", 1}}; + writev(666, output, 2); +} +#elif LOG_HANDLER_NSLOG +static void log_line(const char *line) { + extern void NSLog(CFStringRef msg, ...); + NSLog(CFSTR("%s"), line); +} +#elif LOG_HANDLER_SYSLOG +static void log_line(const char *line) { + syslog(LOG_DEBUG, "%s", line); +} +#elif LOG_HANDLER_OS_LOG +static void log_line(const char *line) { + os_log_fault(OS_LOG_DEFAULT, "%s", line); +} +#elif LOG_HANDLER_STDERR +static void log_line(const char *line) { + fprintf(stderr, "%s\n", line); +} +#endif + +static void default_die_handler(const char *msg) { + printk("%s\n", msg); +} +void (*die_handler)(const char *msg) = default_die_handler; +_Noreturn void die(const char *msg, ...); +void die(const char *msg, ...) { + va_list args; + va_start(args, msg); + char buf[4096]; + vsnprintf(buf, sizeof(buf), msg, args); + va_end(args); + die_handler(buf); + abort(); +} + +// fun little utility function +int current_pid() { + if (current) + return current->pid; + return -1; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/memory.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/memory.c new file mode 100644 index 0000000000..7633eab429 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/memory.c @@ -0,0 +1,903 @@ +#include <fcntl.h> +#include <unistd.h> +#include <sys/mman.h> +#include <string.h> +#include <stdlib.h> +#include <stdio.h> +#include <errno.h> +#include <stdatomic.h> +#include <sched.h> + +#define DEFAULT_CHANNEL memory +#include "debug.h" +#include "kernel/errno.h" +#include "kernel/signal.h" +#include "kernel/memory.h" +#include "asbestos/asbestos.h" +#include "kernel/vdso.h" +#include "kernel/task.h" +#include "kernel/resource.h" +#include "fs/fd.h" + +// increment the change count +static void mem_changed(struct mem *mem); +static struct mmu_ops mem_mmu_ops; + +#include "kernel/mm.h" + +static void reacquire_read_after_failed_jit_upgrade(wrlock_t *lock) { + // glibc rwlocks are writer-preferred in util/sync.h. If a JIT thread + // releases its read lock, fails trywrlock, then blocks in rdlock while a + // non-JIT fault handler is queued for write, both sides can deadlock. Spin + // with tryrdlock instead so the queued writer can acquire and release. + while (!read_wrtrylock(lock)) + sched_yield(); +} + + + +// ============================================================ +// ARM64: 4-level page table for 48-bit address space +// ============================================================ + +void mem_init(struct mem *mem) { + mem->pgdir = calloc(1, sizeof(struct pt_node)); + mem->pgdir_used = 0; + mem->mmap_hint = 0; + mem->reservations = NULL; + mem->mmu.ops = &mem_mmu_ops; + mem->mmu.asbestos = asbestos_new(&mem->mmu); + mem->mmu.changes = 0; + wrlock_init(&mem->lock); + lock_init(&mem->cow_lock); +} + +static page_t page_range_end(page_t start, pages_t pages) { + if (pages == 0) + return start; + if (start >= MEM_PAGES || pages > MEM_PAGES - start) + return MEM_PAGES; + return start + pages; +} + +struct mem_reservation *mem_find_reservation(struct mem *mem, page_t page) { + for (struct mem_reservation *r = mem->reservations; r; r = r->next) { + if (r->pages != 0 && page >= r->start && page < page_range_end(r->start, r->pages)) + return r; + } + return NULL; +} + +int pt_map_lazy(struct mem *mem, page_t start, pages_t pages, unsigned flags) { + struct mem_reservation *res = malloc(sizeof(struct mem_reservation)); + if (res == NULL) + return _ENOMEM; + res->start = start; + res->pages = pages; + res->flags = flags | P_ANONYMOUS; + res->next = mem->reservations; + mem->reservations = res; + mem_changed(mem); + return 0; +} + +void mem_remove_reservations(struct mem *mem, page_t start, pages_t pages) { + if (pages == 0) + return; + struct mem_reservation **pp = &mem->reservations; + page_t u_end = page_range_end(start, pages); + while (*pp) { + struct mem_reservation *r = *pp; + page_t r_end = page_range_end(r->start, r->pages); + if (r->start >= u_end || r_end <= start) { + pp = &r->next; + continue; + } + if (r->start >= start && r_end <= u_end) { + *pp = r->next; + free(r); + continue; + } + if (r->start < start && r_end > u_end) { + struct mem_reservation *tail = malloc(sizeof(struct mem_reservation)); + if (tail) { + tail->start = u_end; + tail->pages = r_end - u_end; + tail->flags = r->flags; + tail->next = r->next; + r->pages = start - r->start; + r->next = tail; + } + pp = &(tail ? tail : r)->next; + continue; + } + if (r->start < start) { + r->pages = start - r->start; + } else { + r->start = u_end; + r->pages = r_end - u_end; + } + pp = &r->next; + } +} + +int mem_set_reservation_flags(struct mem *mem, page_t start, pages_t pages, unsigned flags) { + if (pages == 0) + return 0; + + page_t end = page_range_end(start, pages); + for (struct mem_reservation *r = mem->reservations; r; r = r->next) { + page_t r_end = page_range_end(r->start, r->pages); + if (r->start >= end || r_end <= start) + continue; + + page_t overlap_start = r->start > start ? r->start : start; + page_t overlap_end = r_end < end ? r_end : end; + pages_t before = overlap_start - r->start; + pages_t overlap = overlap_end - overlap_start; + pages_t after = r_end - overlap_end; + unsigned old_flags = r->flags; + unsigned new_flags = flags | (old_flags & P_ANONYMOUS); + + if (before && after) { + struct mem_reservation *middle = malloc(sizeof(struct mem_reservation)); + struct mem_reservation *tail = malloc(sizeof(struct mem_reservation)); + if (middle == NULL || tail == NULL) { + free(middle); + free(tail); + return _ENOMEM; + } + tail->start = overlap_end; + tail->pages = after; + tail->flags = old_flags; + tail->next = r->next; + + middle->start = overlap_start; + middle->pages = overlap; + middle->flags = new_flags; + middle->next = tail; + + r->pages = before; + r->next = middle; + r = tail; + } else if (before) { + struct mem_reservation *middle = malloc(sizeof(struct mem_reservation)); + if (middle == NULL) + return _ENOMEM; + middle->start = overlap_start; + middle->pages = overlap; + middle->flags = new_flags; + middle->next = r->next; + + r->pages = before; + r->next = middle; + r = middle; + } else if (after) { + struct mem_reservation *tail = malloc(sizeof(struct mem_reservation)); + if (tail == NULL) + return _ENOMEM; + tail->start = overlap_end; + tail->pages = after; + tail->flags = old_flags; + tail->next = r->next; + + r->start = overlap_start; + r->pages = overlap; + r->flags = new_flags; + r->next = tail; + } else { + r->flags = new_flags; + } + } + return 0; +} + +// Recursively free page table nodes at given level +static void pt_node_free(void *node, int level) { + if (node == NULL) + return; + if (level == 3) { + // L3: array of pt_entry — just free the array + free(node); + return; + } + struct pt_node *n = node; + for (int i = 0; i < PT_ENTRIES; i++) { + pt_node_free(n->children[i], level + 1); + } + free(n); +} + +void mem_destroy(struct mem *mem) { + write_wrlock(&mem->lock); + pt_unmap_always(mem, 0, MEM_PAGES); + while (mem->reservations) { + struct mem_reservation *r = mem->reservations; + mem->reservations = r->next; + free(r); + } + asbestos_free(mem->mmu.asbestos); + mem->mmu.asbestos = NULL; + pt_node_free(mem->pgdir, 0); + mem->pgdir = NULL; + write_wrunlock(&mem->lock); + wrlock_destroy(&mem->lock); +} + +// Navigate 4-level page table to find L3 entry, creating intermediate nodes as needed +static struct pt_entry *mem_pt_new(struct mem *mem, page_t page) { + struct pt_node *l0 = mem->pgdir; + int i0 = PT_INDEX(page, 0); + struct pt_node *l1 = l0->children[i0]; + if (l1 == NULL) { + l1 = l0->children[i0] = calloc(1, sizeof(struct pt_node)); + mem->pgdir_used++; + } + + int i1 = PT_INDEX(page, 1); + struct pt_node *l2 = l1->children[i1]; + if (l2 == NULL) + l2 = l1->children[i1] = calloc(1, sizeof(struct pt_node)); + + int i2 = PT_INDEX(page, 2); + struct pt_entry *l3 = l2->children[i2]; + if (l3 == NULL) + l3 = l2->children[i2] = calloc(PT_ENTRIES, sizeof(struct pt_entry)); + + int i3 = PT_INDEX(page, 3); + return &l3[i3]; +} + +struct pt_entry *mem_pt(struct mem *mem, page_t page) { + struct pt_node *l0 = mem->pgdir; + if (l0 == NULL) return NULL; + + struct pt_node *l1 = l0->children[PT_INDEX(page, 0)]; + if (l1 == NULL) return NULL; + + struct pt_node *l2 = l1->children[PT_INDEX(page, 1)]; + if (l2 == NULL) return NULL; + + struct pt_entry *l3 = l2->children[PT_INDEX(page, 2)]; + if (l3 == NULL) return NULL; + + struct pt_entry *entry = &l3[PT_INDEX(page, 3)]; + if (entry->data == NULL) return NULL; + return entry; +} + +static void mem_pt_del(struct mem *mem, page_t page) { + struct pt_entry *entry = mem_pt(mem, page); + if (entry != NULL) + entry->data = NULL; +} + +// Skip over large unallocated regions efficiently by checking intermediate levels +void mem_next_page(struct mem *mem, page_t *page) { + (*page)++; + if (*page >= MEM_PAGES) + return; + + struct pt_node *l0 = mem->pgdir; + if (l0 == NULL) { *page = MEM_PAGES; return; } + + while (*page < MEM_PAGES) { + int i0 = PT_INDEX(*page, 0); + struct pt_node *l1 = l0->children[i0]; + if (l1 == NULL) { + // Skip entire L0 region (2^27 pages) + *page = (((*page >> (PT_BITS * 3)) + 1) << (PT_BITS * 3)); + continue; + } + + int i1 = PT_INDEX(*page, 1); + struct pt_node *l2 = l1->children[i1]; + if (l2 == NULL) { + // Skip entire L1 region (2^18 pages) + *page = (((*page >> (PT_BITS * 2)) + 1) << (PT_BITS * 2)); + continue; + } + + int i2 = PT_INDEX(*page, 2); + struct pt_entry *l3 = l2->children[i2]; + if (l3 == NULL) { + // Skip entire L2 region (2^9 = 512 pages) + *page = (((*page >> PT_BITS) + 1) << PT_BITS); + continue; + } + // Found a populated L3 array — page might exist here + return; + } +} + +bool mem_range_has_reservation(struct mem *mem, page_t start, pages_t size) { + if (size == 0) + return false; + page_t end = page_range_end(start, size); + if (end <= start) + return true; + for (struct mem_reservation *r = mem->reservations; r; r = r->next) { + if (r->pages == 0) + continue; + page_t r_end = page_range_end(r->start, r->pages); + if (r_end <= r->start || (r->start < end && r_end > start)) + return true; + } + return false; +} + +// Scan downward from 'start' to MMAP_HOLE_END, skipping unallocated page table +// subtrees for efficiency (L0 covers 2^27 pages, L1 2^18, L2 2^9). +static page_t pt_find_hole_from(struct mem *mem, pages_t size, page_t start) { + struct pt_node *l0 = mem->pgdir; + page_t hole_end = 0; + bool in_hole = false; + + page_t page = start; + while (page > MMAP_HOLE_END) { + // Fast-skip unallocated L0 subtrees + int i0 = PT_INDEX(page, 0); + struct pt_node *l1 = l0 ? l0->children[i0] : NULL; + if (l1 == NULL) { + page_t l0_base = (page_t)i0 << (PT_BITS * 3); + if (!in_hole) { in_hole = true; hole_end = page + 1; } + page_t effective_base = (l0_base > MMAP_HOLE_END) ? l0_base : MMAP_HOLE_END + 1; + if (in_hole && hole_end - effective_base >= size) + return hole_end - size; + if (l0_base == 0) break; + page = l0_base - 1; + continue; + } + + // Fast-skip unallocated L1 subtrees + int i1 = PT_INDEX(page, 1); + struct pt_node *l2 = l1->children[i1]; + if (l2 == NULL) { + page_t l1_base = ((page_t)i0 << (PT_BITS * 3)) | ((page_t)i1 << (PT_BITS * 2)); + if (!in_hole) { in_hole = true; hole_end = page + 1; } + page_t effective_base = (l1_base > MMAP_HOLE_END) ? l1_base : MMAP_HOLE_END + 1; + if (in_hole && hole_end - effective_base >= size) + return hole_end - size; + if (l1_base == 0) break; + page = l1_base - 1; + continue; + } + + // Fast-skip unallocated L2 subtrees + int i2 = PT_INDEX(page, 2); + struct pt_entry *l3 = l2->children[i2]; + if (l3 == NULL) { + page_t l2_base = ((page_t)i0 << (PT_BITS * 3)) | ((page_t)i1 << (PT_BITS * 2)) | ((page_t)i2 << PT_BITS); + if (!in_hole) { in_hole = true; hole_end = page + 1; } + page_t effective_base = (l2_base > MMAP_HOLE_END) ? l2_base : MMAP_HOLE_END + 1; + if (in_hole && hole_end - effective_base >= size) + return hole_end - size; + if (l2_base == 0) break; + page = l2_base - 1; + continue; + } + + // L3 exists — check individual pages + if (mem_pt(mem, page) != NULL) { + in_hole = false; + } else { + if (!in_hole) { in_hole = true; hole_end = page + 1; } + if (hole_end - page >= size) + return page; + } + if (page == 0) break; + page--; + } + return BAD_PAGE; +} + +// Scan upward in the high address space (above 4GB) for large allocations +// that don't fit in the low region. Used for Wasm guard regions etc. +page_t pt_find_hole_high(struct mem *mem, pages_t size) { + // Search from 0x100000 (4GB) upward to USER_ADDR_MAX_PAGE. Large + // MAP_NORESERVE arenas are represented as reservations without allocating + // page-table nodes, so an empty L0 subtree is not necessarily free. Walk + // reservations inside each empty subtree before accepting a high hole. + page_t page = 0x100000; // Start at 4GB + + while (page < USER_ADDR_MAX_PAGE) { + int i0 = PT_INDEX(page, 0); + struct pt_node *l0 = mem->pgdir; + struct pt_node *l1 = l0 ? l0->children[i0] : NULL; + page_t l0_size = (page_t)1 << (PT_BITS * 3); + page_t l0_base = (page_t)i0 << (PT_BITS * 3); + page_t subtree_end = l0_base + l0_size; + if (subtree_end > USER_ADDR_MAX_PAGE) + subtree_end = USER_ADDR_MAX_PAGE; + + if (l1 == NULL) { + page_t candidate = l0_base < page ? page : l0_base; + while (candidate < subtree_end) { + struct mem_reservation *first = NULL; + for (struct mem_reservation *r = mem->reservations; r; r = r->next) { + page_t r_end = r->start + r->pages; + if (r_end <= candidate || r->start >= subtree_end) + continue; + if (r->start <= candidate) { + candidate = r_end; + first = r; + break; + } + if (first == NULL || r->start < first->start) + first = r; + } + if (first == NULL) { + if (subtree_end - candidate >= size) + return candidate; + break; + } + if (first->start > candidate) { + if (first->start - candidate >= size) + return candidate; + candidate = first->start + first->pages; + } + } + page = subtree_end; + continue; + } + + // L1 exists — something is mapped here, skip the whole subtree. + page = subtree_end; + } + return BAD_PAGE; +} + +page_t pt_find_hole(struct mem *mem, pages_t size) { + page_t start = mem->mmap_hint; + if (start == 0 || start > MMAP_HOLE_START || start <= MMAP_HOLE_END + size) + start = MMAP_HOLE_START; + + // Try low address space with reservation awareness. + // If a candidate overlaps a reservation, retry below the reservation. + for (int attempt = 0; attempt < 10; attempt++) { + page_t result = pt_find_hole_from(mem, size, start); + if (result == BAD_PAGE) + break; + if (!mem_range_has_reservation(mem, result, size)) { + mem->mmap_hint = (result > 0) ? result - 1 : 0; + return result; + } + // Skip below the overlapping reservation + for (struct mem_reservation *r = mem->reservations; r; r = r->next) { + if (r->start < result + size && r->start + r->pages > result) { + start = (r->start > 0) ? r->start - 1 : 0; + break; + } + } + } + + // Wrap around from top + if (start < MMAP_HOLE_START) { + start = MMAP_HOLE_START; + for (int attempt = 0; attempt < 10; attempt++) { + page_t result = pt_find_hole_from(mem, size, start); + if (result == BAD_PAGE) + break; + if (!mem_range_has_reservation(mem, result, size)) { + mem->mmap_hint = (result > 0) ? result - 1 : 0; + return result; + } + for (struct mem_reservation *r = mem->reservations; r; r = r->next) { + if (r->start < result + size && r->start + r->pages > result) { + start = (r->start > 0) ? r->start - 1 : 0; + break; + } + } + } + } + + // Low 4GB exhausted — try high address space (above 4GB). + page_t result = pt_find_hole_high(mem, size); + if (result != BAD_PAGE && !mem_range_has_reservation(mem, result, size)) + return result; + + return BAD_PAGE; +} + + +bool pt_is_hole(struct mem *mem, page_t start, pages_t pages) { + for (page_t page = start; page < start + pages; page++) { + if (mem_pt(mem, page) != NULL) + return false; + } + if (mem_range_has_reservation(mem, start, pages)) + return false; + return true; +} + +int pt_map(struct mem *mem, page_t start, pages_t pages, void *memory, size_t offset, unsigned flags) { + if (memory == MAP_FAILED) + return errno_map(); + + // If this fails, the munmap in pt_unmap would probably fail. + assert((uintptr_t) memory % real_page_size == 0 || memory == vdso_data); + + struct data *data = malloc(sizeof(struct data)); + if (data == NULL) + return _ENOMEM; + *data = (struct data) { + .data = memory, + .size = pages * PAGE_SIZE + offset, + +#if LEAK_DEBUG + .pid = current ? current->pid : 0, + .dest = start << PAGE_BITS, +#endif + }; + + for (page_t page = start; page < start + pages; page++) { + if (mem_pt(mem, page) != NULL) + pt_unmap(mem, page, 1); + data->refcount++; + struct pt_entry *pt = mem_pt_new(mem, page); + pt->data = data; + pt->offset = ((page - start) << PAGE_BITS) + offset; + pt->flags = flags; + + } + mem_changed(mem); + return 0; +} + +int pt_unmap(struct mem *mem, page_t start, pages_t pages) { + for (page_t page = start; page < start + pages; page++) + if (mem_pt(mem, page) == NULL) + return -1; + return pt_unmap_always(mem, start, pages); +} + +int pt_unmap_always(struct mem *mem, page_t start, pages_t pages) { + // Reset mmap_hint if freed region is above it, so pt_find_hole can + // reuse the freed space on the next mmap(addr=0). + if (start + pages - 1 > mem->mmap_hint) + mem->mmap_hint = start + pages - 1; + + mem_remove_reservations(mem, start, pages); + + for (page_t page = start; page < start + pages; mem_next_page(mem, &page)) { + struct pt_entry *pt = mem_pt(mem, page); + if (pt == NULL) + continue; + + asbestos_invalidate_page(mem->mmu.asbestos, page); + struct data *data = pt->data; +#if ANON_MMAP_LIMIT_PAGES > 0 + // Decrement per-page for anonymous mappings. This correctly handles + // partial unmaps (munmap of subset of original mmap region) where the + // data object's refcount doesn't reach 0 but the guest page is gone. + if (pt->flags & P_ANONYMOUS) + atomic_fetch_sub(&anon_page_count, 1); +#endif + mem_pt_del(mem, page); + if (--data->refcount == 0) { + // vdso wasn't allocated with mmap, it's just in our data segment + if (data->data != vdso_data) { + munmap(data->data, data->size); + } + if (data->fd != NULL) { + fd_close(data->fd); + } + free(data); + } + } + mem_changed(mem); + return 0; +} + +int pt_map_nothing(struct mem *mem, page_t start, pages_t pages, unsigned flags) { + if (pages == 0) return 0; + // Use host PROT_NONE for guest PROT_NONE mappings. Go runtime reserves + // ~1.1GB of PROT_NONE address space for page summaries; allocating real + // memory for these wastes physical RAM and causes iOS jetsam kills. + int host_prot = PROT_READ | PROT_WRITE; + if (!(flags & P_READ) && !(flags & P_WRITE) && !(flags & P_EXEC)) + host_prot = PROT_NONE; + size_t map_size = (size_t)pages * PAGE_SIZE; + void *memory = mmap(NULL, map_size, host_prot, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); + if (memory == MAP_FAILED) + return _ENOMEM; + return pt_map(mem, start, pages, memory, 0, flags | P_ANONYMOUS); +} + +// Metadata flags that must be preserved across mprotect — they track +// allocation type and state, not user-visible protection bits. +#define P_META_FLAGS (P_ANONYMOUS | P_GROWSDOWN | P_COW | P_SHARED) + +int pt_set_flags(struct mem *mem, page_t start, pages_t pages, int flags) { + for (page_t page = start; page < start + pages; page++) { + if (mem_pt(mem, page) == NULL) { + if (mem_find_reservation(mem, page) != NULL) + continue; + return _ENOMEM; + } + } + for (page_t page = start; page < start + pages; page++) { + struct pt_entry *entry = mem_pt(mem, page); + if (entry == NULL) + continue; + int old_flags = entry->flags; + entry->flags = flags | (old_flags & P_META_FLAGS); + + // check if protection is increasing + if ((flags & ~old_flags) & (P_READ|P_WRITE)) { + void *data = (char *) entry->data->data + entry->offset; + // force to be page aligned + data = (void *) ((uintptr_t) data & ~(real_page_size - 1)); + int prot = PROT_READ; + if (flags & P_WRITE) prot |= PROT_WRITE; + if (mprotect(data, real_page_size, prot) < 0) + return errno_map(); + } + } + int err = mem_set_reservation_flags(mem, start, pages, flags); + if (err < 0) + return err; + mem_changed(mem); + return 0; +} + +int pt_copy_on_write(struct mem *src, struct mem *dst, page_t start, page_t pages) { +#if ANON_MMAP_LIMIT_PAGES > 0 + long anon_copied = 0; +#endif + for (page_t page = start; page < start + pages; mem_next_page(src, &page)) { + struct pt_entry *entry = mem_pt(src, page); + if (entry == NULL) + continue; + if (pt_unmap_always(dst, page, 1) < 0) + return -1; + if (!(entry->flags & P_SHARED)) + entry->flags |= P_COW; + entry->data->refcount++; + struct pt_entry *dst_entry = mem_pt_new(dst, page); + dst_entry->data = entry->data; + dst_entry->offset = entry->offset; + dst_entry->flags = entry->flags; +#if ANON_MMAP_LIMIT_PAGES > 0 + if (entry->flags & P_ANONYMOUS) + anon_copied++; +#endif + } +#if ANON_MMAP_LIMIT_PAGES > 0 + // The child process now has its own set of anonymous pages. + // These will be decremented per-page when the child's mm is freed. + atomic_fetch_add(&anon_page_count, anon_copied); +#endif + for (struct mem_reservation *r = src->reservations; r; r = r->next) { + struct mem_reservation *copy = malloc(sizeof(struct mem_reservation)); + if (copy) { + *copy = *r; + copy->next = dst->reservations; + dst->reservations = copy; + } + } + mem_changed(src); + mem_changed(dst); + return 0; +} + +static void mem_changed(struct mem *mem) { + __atomic_add_fetch(&mem->mmu.changes, 1, __ATOMIC_RELEASE); +} + +// Public wrapper: bump the memory-change generation so other threads' TLB +// coherence checks force a re-translate. Used by paths that mutate page +// backing without going through pt_map/pt_unmap (e.g. madvise MADV_DONTNEED +// zeroing a page in place). +void mem_changed_pub(struct mem *mem) { + mem_changed(mem); +} + +// This version will return NULL instead of making necessary pagetable changes. +// Used by the emulator to avoid deadlocks. +static void *mem_ptr_nofault(struct mem *mem, addr_t addr, int type) { + struct pt_entry *entry = mem_pt(mem, PAGE(addr)); + if (entry == NULL) + return NULL; + if (type == MEM_WRITE && !P_WRITABLE(entry->flags)) + return NULL; + return entry->data->data + entry->offset + PGOFFSET(addr); +} + +void *mem_ptr(struct mem *mem, addr_t addr, int type) { +#ifndef NDEBUG + void *old_ptr = mem_ptr_nofault(mem, addr, type); // just for an assert +#endif + + page_t page = PAGE(addr); + struct pt_entry *entry = mem_pt(mem, page); + extern __thread volatile sig_atomic_t in_jit; + + if (entry == NULL) { + // page does not exist + // look to see if the next VM region is willing to grow down + page_t p = page; + mem_next_page(mem, &p); + while (p < MEM_PAGES && mem_pt(mem, p) == NULL) + mem_next_page(mem, &p); + if (p >= MEM_PAGES) + goto check_reservation; + if (!(mem_pt(mem, p)->flags & P_GROWSDOWN)) + goto check_reservation; + + // Enforce RLIMIT_STACK: don't grow stack beyond the limit. + // Stack top is at STACK_TOP_PAGE (guard page), stack grows down from STACK_INIT_PAGE. + pages_t guard_page = STACK_TOP_PAGE; + rlim_t_ stack_limit = rlimit(RLIMIT_STACK_); + if (stack_limit != RLIM_INFINITY_) { + pages_t stack_pages = guard_page - page; + if ((uint64_t)stack_pages * PAGE_SIZE > stack_limit) + return NULL; + } + + // Lock upgrade: release read, acquire write. + // In JIT context (inside fiber_enter), other threads hold mem->lock + // READ from their task_run_current, so write_wrlock deadlocks. + // Use trylock: if contended, return NULL for INT_GPF retry from + // handle_interrupt where the lock upgrade is safe. + read_wrunlock(&mem->lock); + if (in_jit) { + if (!write_wrtrylock(&mem->lock)) { + // Can't get write lock — other threads hold/read-wait on this + // writer-preferred rwlock. Re-acquire read without blocking a + // queued writer, then return NULL for GPF retry outside JIT. + reacquire_read_after_failed_jit_upgrade(&mem->lock); + return NULL; + } + } else { + write_wrlock(&mem->lock); + } + // Re-check after acquiring write lock (another thread may have grown it) + entry = mem_pt(mem, page); + if (entry != NULL) { + // Already mapped by another thread + write_wrunlock(&mem->lock); + read_wrlock(&mem->lock); + goto have_entry; + } +#if ANON_MMAP_LIMIT_PAGES > 0 + atomic_fetch_add(&anon_page_count, 1); +#endif + if (pt_map_nothing(mem, page, 1, P_READ | P_WRITE | P_GROWSDOWN) >= 0) + mem_changed(mem); + write_wrunlock(&mem->lock); + read_wrlock(&mem->lock); + + entry = mem_pt(mem, page); + goto have_entry; + +check_reservation: ; + struct mem_reservation *res = mem_find_reservation(mem, page); + if (res == NULL) + return NULL; + read_wrunlock(&mem->lock); + if (in_jit) { + if (!write_wrtrylock(&mem->lock)) { + reacquire_read_after_failed_jit_upgrade(&mem->lock); + return NULL; + } + } else { + write_wrlock(&mem->lock); + } + entry = mem_pt(mem, page); + if (entry == NULL) { +#if ANON_MMAP_LIMIT_PAGES > 0 + atomic_fetch_add(&anon_page_count, 1); +#endif + if (pt_map_nothing(mem, page, 1, res->flags & ~P_GROWSDOWN) >= 0) + mem_changed(mem); + } + write_wrunlock(&mem->lock); + read_wrlock(&mem->lock); + entry = mem_pt(mem, page); + } + +have_entry: + if (entry != NULL && (type == MEM_WRITE || type == MEM_WRITE_PTRACE)) { + // if page is unwritable, well tough luck + if (type != MEM_WRITE_PTRACE && !(entry->flags & P_WRITE)) + return NULL; + if (type == MEM_WRITE_PTRACE) { + // TODO: Is P_WRITE really correct? The page shouldn't be writable without ptrace. + entry->flags |= P_WRITE | P_COW; + } + // get rid of any compiled blocks in this page + asbestos_invalidate_page(mem->mmu.asbestos, page); + // if page is cow, ~~milk~~ copy it + if (entry->flags & P_COW) { + void *copy = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); + + read_wrunlock(&mem->lock); + write_wrlock(&mem->lock); + // Re-fetch entry after lock upgrade — another thread may have + // already resolved this CoW while we were waiting for the lock. + entry = mem_pt(mem, page); + if (entry != NULL && (entry->flags & P_COW)) { + void *data = (char *) entry->data->data + entry->offset; + memcpy(copy, data, PAGE_SIZE); +#if ANON_MMAP_LIMIT_PAGES > 0 + // pt_map will unmap the old page (decrementing anon_page_count), + // so pre-increment for the new CoW copy to keep balance. + if (entry->flags & P_ANONYMOUS) + atomic_fetch_add(&anon_page_count, 1); +#endif + pt_map(mem, page, 1, copy, 0, entry->flags &~ P_COW); + mem_changed(mem); + } else { + munmap(copy, PAGE_SIZE); + } + write_wrunlock(&mem->lock); + read_wrlock(&mem->lock); + } + } + + void *ptr = mem_ptr_nofault(mem, addr, type); +#ifndef NDEBUG + assert(old_ptr == NULL || old_ptr == ptr || type == MEM_WRITE_PTRACE); +#endif + return ptr; +} + +static void *mem_mmu_translate(struct mmu *mmu, addr_t addr, int type) { + // Use mem_ptr instead of mem_ptr_nofault to properly handle: + // 1. Copy-on-write (COW) pages - need to copy before write + // 2. Growing stack pages (P_GROWSDOWN) + return mem_ptr(container_of(mmu, struct mem, mmu), addr, type); +} + +static void *mem_mmu_translate_write_nofault(struct mmu *mmu, addr_t addr) { + return mem_ptr_nofault(container_of(mmu, struct mem, mmu), addr, MEM_WRITE); +} + +static struct mmu_ops mem_mmu_ops = { + .translate = mem_mmu_translate, + .translate_write_nofault = mem_mmu_translate_write_nofault, +}; + +int mem_segv_reason(struct mem *mem, addr_t addr) { + struct pt_entry *pt = mem_pt(mem, PAGE(addr)); + if (pt == NULL) + return SEGV_MAPERR_; + return SEGV_ACCERR_; +} + +size_t real_page_size; +__attribute__((constructor)) static void get_real_page_size() { + real_page_size = sysconf(_SC_PAGESIZE); +} + +void mem_coredump(struct mem *mem, const char *file) { + int fd = open(file, O_CREAT | O_RDWR | O_TRUNC, 0666); + if (fd < 0) { + perror("open"); + return; + } + if (ftruncate(fd, 0xffffffff) < 0) { + perror("ftruncate"); + return; + } + + int pages = 0; + for (page_t page = 0; page < MEM_PAGES; mem_next_page(mem, &page)) { + struct pt_entry *entry = mem_pt(mem, page); + if (entry == NULL) + continue; + pages++; + if (lseek(fd, (off_t)(page << PAGE_BITS), SEEK_SET) < 0) { + perror("lseek"); + return; + } + if (write(fd, entry->data->data, PAGE_SIZE) < 0) { + perror("write"); + return; + } + } + printk("dumped %d pages\n", pages); + close(fd); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/memory.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/memory.h new file mode 100644 index 0000000000..dc063cbf15 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/memory.h @@ -0,0 +1,154 @@ +#ifndef MEMORY_H +#define MEMORY_H + +#include <stdatomic.h> +#include <unistd.h> +#include <stdbool.h> +#include "emu/mmu.h" +#include "util/list.h" +#include "util/sync.h" +#include "misc.h" + +// ARM64: 4-level page table for 48-bit address space +// L0[512] → L1[512] → L2[512] → L3[512 pt_entry] +// 9+9+9+9 = 36-bit page number + 12-bit offset = 48-bit address +#define PT_LEVELS 4 +#define PT_BITS 9 +#define PT_ENTRIES (1 << PT_BITS) // 512 + +// Extract level index from page number (36-bit page number) +#define PT_INDEX(page, level) (((page) >> (PT_BITS * (3 - (level)))) & (PT_ENTRIES - 1)) + +// Page table intermediate node (L0, L1, L2) +struct pt_node { + void *children[PT_ENTRIES]; // pt_node* for L0-L2, pt_entry* array for L3 +}; + +// Lazy reservation for MAP_NORESERVE regions (JSC heap cage, etc.). +// Records address range and permissions without allocating page table entries. +// Pages are materialized on demand when faulted. +struct mem_reservation { + page_t start; + pages_t pages; + unsigned flags; + struct mem_reservation *next; +}; + +struct mem { + struct pt_node *pgdir; // L0 node (512 entries) + int pgdir_used; + + struct mmu mmu; + + // Hint for pt_find_hole: start searching just below the last successful + // allocation instead of always from MMAP_HOLE_START. Reset on munmap + // when freed pages are above the hint. Avoids O(n) rescanning of already- + // allocated regions on every mmap(addr=0). + page_t mmap_hint; + + struct mem_reservation *reservations; + + wrlock_t lock; + lock_t cow_lock; +}; + +// Address space layout for ARM64 guest. +// 48-bit address space with 4-level page table and 48-bit JIT masks. +// Keep default stack and mmap allocations in the low 4GB region so that page +// table walks are shallow (L0[0]→L1[0]→L2→L3 — the first two levels are always +// index 0 and stay hot in cache). The 48-bit infrastructure remains available +// for explicit high-address mmap hints (e.g., V8 CodeRange). +#define STACK_TOP_PAGE 0xffffeULL // guard page at 0xffffe000 +#define STACK_INIT_PAGE 0xffffdULL // initial stack page (growsdown) +#define STACK_TOP_ADDR 0xffffe000ULL // SP starts here +#define MMAP_HOLE_START 0xefffdULL // mmap search starts here +#define MMAP_HOLE_END 0x100ULL // mmap search ends here (above guard pages) +// Upper bound for valid user addresses (page number, 48-bit / 4K = 36-bit) +#define USER_ADDR_MAX_PAGE 0xFFFFFFFFFULL + +// Initialize the address space +void mem_init(struct mem *mem); +// Uninitialize the address space +void mem_destroy(struct mem *mem); +// Bump the memory-change generation (for page-backing mutations that bypass +// pt_map/pt_unmap, e.g. madvise MADV_DONTNEED in-place zeroing). +void mem_changed_pub(struct mem *mem); +// Return the pagetable entry for the given page +struct pt_entry *mem_pt(struct mem *mem, page_t page); +// Increment *page, skipping over unallocated page directories. Intended to be +// used as the incremenent in a for loop to traverse mappings. +void mem_next_page(struct mem *mem, page_t *page); + +#define BYTES_ROUND_DOWN(bytes) (PAGE(bytes) << PAGE_BITS) +#define BYTES_ROUND_UP(bytes) (PAGE_ROUND_UP(bytes) << PAGE_BITS) + +#define LEAK_DEBUG 0 + +struct data { + void *data; // immutable + size_t size; // also immutable + atomic_uint refcount; + + // for display in /proc/pid/maps + struct fd *fd; + size_t file_offset; + const char *name; +#if LEAK_DEBUG + int pid; + addr_t dest; +#endif +}; +struct pt_entry { + struct data *data; + size_t offset; + unsigned flags; + struct list blocks[2]; +}; +// page flags +// P_READ and P_EXEC are ignored for now +#define P_READ (1 << 0) +#define P_WRITE (1 << 1) +#undef P_EXEC // defined in sys/proc.h on darwin +#define P_EXEC (1 << 2) +#define P_RWX (P_READ | P_WRITE | P_EXEC) +#define P_GROWSDOWN (1 << 3) +#define P_COW (1 << 4) +#define P_WRITABLE(flags) (flags & P_WRITE && !(flags & P_COW)) + +// mapping was created with pt_map_nothing +#define P_ANONYMOUS (1 << 6) +// mapping was created with MAP_SHARED, should not CoW +#define P_SHARED (1 << 7) + +bool pt_is_hole(struct mem *mem, page_t start, pages_t pages); +page_t pt_find_hole(struct mem *mem, pages_t size); + +page_t pt_find_hole_high(struct mem *mem, pages_t size); +int pt_map_lazy(struct mem *mem, page_t start, pages_t pages, unsigned flags); +struct mem_reservation *mem_find_reservation(struct mem *mem, page_t page); +bool mem_range_has_reservation(struct mem *mem, page_t start, pages_t pages); +void mem_remove_reservations(struct mem *mem, page_t start, pages_t pages); +int mem_set_reservation_flags(struct mem *mem, page_t start, pages_t pages, unsigned flags); + +// Map memory + offset into fake memory, unmapping existing mappings. Takes +// ownership of memory. It will be freed with: +// munmap(memory, pages * PAGE_SIZE) +int pt_map(struct mem *mem, page_t start, pages_t pages, void *memory, size_t offset, unsigned flags); +// Map empty space into fake memory +int pt_map_nothing(struct mem *mem, page_t page, pages_t pages, unsigned flags); +// Unmap fake memory, return -1 if any part of the range isn't mapped and 0 otherwise +int pt_unmap(struct mem *mem, page_t start, pages_t pages); +// like pt_unmap but doesn't care if part of the range isn't mapped +int pt_unmap_always(struct mem *mem, page_t start, pages_t pages); +// Set the flags on memory +int pt_set_flags(struct mem *mem, page_t start, pages_t pages, int flags); +// Copy pages from src memory to dst memory using copy-on-write +int pt_copy_on_write(struct mem *src, struct mem *dst, page_t start, page_t pages); + +// Must call with mem read-locked. +void *mem_ptr(struct mem *mem, addr_t addr, int type); +int mem_segv_reason(struct mem *mem, addr_t addr); + +extern size_t real_page_size; + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/misc.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/misc.c new file mode 100644 index 0000000000..dddda754ee --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/misc.c @@ -0,0 +1,131 @@ +#include <string.h> +#include <stdatomic.h> +#include "kernel/calls.h" +#include "kernel/task.h" + +#define PRCTL_SET_KEEPCAPS_ 8 +#define PRCTL_SET_NAME_ 15 + +int_t sys_prctl(dword_t option, addr_t arg2, addr_t UNUSED(arg3), addr_t UNUSED(arg4), addr_t UNUSED(arg5)) { + switch (option) { + case PRCTL_SET_KEEPCAPS_: + // stub + return 0; + case PRCTL_SET_NAME_: { + char name[16]; + if (user_read_string(arg2, name, sizeof(name) - 1)) + return _EFAULT; + name[sizeof(name) - 1] = '\0'; + STRACE("prctl(PRCTL_SET_NAME, \"%s\")", name); + strcpy(current->comm, name); + return 0; + } + default: + STRACE("prctl(%#x)", option); + return _EINVAL; + } +} + +int_t sys_arch_prctl(int_t code, addr_t addr) { + STRACE("arch_prctl(%#x, %#x)", code, addr); + return _EINVAL; +} + +#define MEMBARRIER_CMD_QUERY 0 +#define MEMBARRIER_CMD_GLOBAL (1 << 0) +#define MEMBARRIER_CMD_GLOBAL_EXPEDITED (1 << 1) +#define MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED (1 << 2) +#define MEMBARRIER_CMD_PRIVATE_EXPEDITED (1 << 3) +#define MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED (1 << 4) +#define MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE (1 << 5) +#define MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_SYNC_CORE (1 << 6) +#define MEMBARRIER_CMD_PRIVATE_EXPEDITED_RSEQ (1 << 7) +#define MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_RSEQ (1 << 8) + +#define MEMBARRIER_SUPPORTED_CMDS \ + (MEMBARRIER_CMD_GLOBAL | \ + MEMBARRIER_CMD_GLOBAL_EXPEDITED | \ + MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED | \ + MEMBARRIER_CMD_PRIVATE_EXPEDITED | \ + MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED | \ + MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE | \ + MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_SYNC_CORE) + +int_t sys_membarrier(int_t cmd, dword_t flags, int_t cpu_id) { + STRACE("membarrier(%#x, %#x, %d)", cmd, flags, cpu_id); + if (cmd == MEMBARRIER_CMD_QUERY) + return MEMBARRIER_SUPPORTED_CMDS; + if (flags != 0) + return _EINVAL; + if (!(cmd & MEMBARRIER_SUPPORTED_CMDS) || (cmd & ~MEMBARRIER_SUPPORTED_CMDS)) + return _EINVAL; + (void)cpu_id; + atomic_thread_fence(memory_order_seq_cst); + return 0; +} + +#define RSEQ_FLAG_UNREGISTER 1 +#define RSEQ_ABI_SIZE 32 + +int_t sys_rseq(addr_t rseq_addr, dword_t rseq_len, int_t flags, dword_t sig) { + STRACE("rseq(%#llx, %u, %#x, %#x)", (unsigned long long)rseq_addr, rseq_len, flags, sig); + if (flags & ~RSEQ_FLAG_UNREGISTER) + return _EINVAL; + + if (flags & RSEQ_FLAG_UNREGISTER) { + if (!current->rseq_registered || current->rseq_addr != rseq_addr || current->rseq_sig != sig) + return _EINVAL; + current->rseq_addr = 0; + current->rseq_len = 0; + current->rseq_sig = 0; + current->rseq_registered = false; + return 0; + } + + if (current->rseq_registered || rseq_addr == 0 || rseq_len < RSEQ_ABI_SIZE) + return _EINVAL; + + dword_t cpu = 0; + qword_t rseq_cs = 0; + dword_t abi_flags = 0; + if (user_put(rseq_addr, cpu) || + user_put(rseq_addr + 4, cpu) || + user_put(rseq_addr + 8, rseq_cs) || + user_put(rseq_addr + 16, abi_flags)) + return _EFAULT; + + current->rseq_addr = rseq_addr; + current->rseq_len = rseq_len; + current->rseq_sig = sig; + current->rseq_registered = true; + return 0; +} + +#define REBOOT_MAGIC1 0xfee1dead +#define REBOOT_MAGIC2 672274793 +#define REBOOT_MAGIC2A 85072278 +#define REBOOT_MAGIC2B 369367448 +#define REBOOT_MAGIC2C 537993216 + +#define REBOOT_CMD_CAD_OFF 0 +#define REBOOT_CMD_CAD_ON 0x89abcdef + +int_t sys_reboot(int_t magic, int_t magic2, int_t cmd) { + STRACE("reboot(%#x, %d, %d)", magic, magic2, cmd); + if (!superuser()) + return _EPERM; + if (magic != (int) REBOOT_MAGIC1 || + (magic2 != REBOOT_MAGIC2 && + magic2 != REBOOT_MAGIC2A && + magic2 != REBOOT_MAGIC2B && + magic2 != REBOOT_MAGIC2C)) + return _EINVAL; + + switch (cmd) { + case REBOOT_CMD_CAD_ON: + case REBOOT_CMD_CAD_OFF: + return 0; + default: + return _EPERM; + } +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/mm.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/mm.h new file mode 100644 index 0000000000..ff46b5a23d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/mm.h @@ -0,0 +1,48 @@ +#ifndef KERNEL_MM_H +#define KERNEL_MM_H + +#include <stdatomic.h> +#include "kernel/memory.h" +#include "misc.h" + +// Maximum anonymous mmap pages across ALL processes (host memory cap). +// Prevents iOS app from being killed by jetsam. +// 0 = no limit. Non-zero = hard limit in pages (4KB each). +// Go runtime alone needs ~1.1GB for page summary reservations (PROT_NONE). +// 524288 pages = 2GB. +#define ANON_MMAP_LIMIT_PAGES 1048576 + +#if ANON_MMAP_LIMIT_PAGES > 0 +extern _Atomic long anon_page_count; +#endif + +// uses mem.lock instead of having a lock of its own +struct mm { + atomic_uint refcount; + struct mem mem; + + addr_t vdso; // immutable + addr_t start_brk; // immutable + addr_t brk; + + // crap for procfs + addr_t argv_start; + addr_t argv_end; + addr_t env_start; + addr_t env_end; + addr_t auxv_start; + addr_t auxv_end; + addr_t stack_start; + struct fd *exefile; +}; + +// Create a new address space +struct mm *mm_new(void); +// Clone (COW) the address space +struct mm *mm_copy(struct mm *mm); +// Increment the refcount +void mm_retain(struct mm *mem); +// Decrement the refcount, destroy everything in the space if 0 +void mm_release(struct mm *mem); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/mmap.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/mmap.c new file mode 100644 index 0000000000..420d923a1d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/mmap.c @@ -0,0 +1,457 @@ +#include <string.h> +#include <stdatomic.h> +#include "debug.h" +#include "kernel/calls.h" +#include "kernel/errno.h" +#include "kernel/task.h" +#include "fs/fd.h" +#include "kernel/memory.h" +#include "kernel/mm.h" + +#if ANON_MMAP_LIMIT_PAGES > 0 +_Atomic long anon_page_count; +#endif + +struct mm *mm_new() { + struct mm *mm = malloc(sizeof(struct mm)); + if (mm == NULL) + return NULL; + mem_init(&mm->mem); + mm->start_brk = mm->brk = 0; // should get overwritten by exec + mm->exefile = NULL; + mm->refcount = 1; + return mm; +} + +struct mm *mm_copy(struct mm *mm) { + struct mm *new_mm = malloc(sizeof(struct mm)); + if (new_mm == NULL) + return NULL; + *new_mm = *mm; + // Fix wrlock_init failing because it thinks it's reinitializing the same lock + memset(&new_mm->mem.lock, 0, sizeof(new_mm->mem.lock)); + new_mm->refcount = 1; + mem_init(&new_mm->mem); + fd_retain(new_mm->exefile); + write_wrlock(&mm->mem.lock); + pt_copy_on_write(&mm->mem, &new_mm->mem, 0, MEM_PAGES); + write_wrunlock(&mm->mem.lock); + return new_mm; +} + +void mm_retain(struct mm *mm) { + mm->refcount++; +} + +void mm_release(struct mm *mm) { + if (--mm->refcount == 0) { + if (mm->exefile != NULL) + fd_close(mm->exefile); + mem_destroy(&mm->mem); + free(mm); + } +} + +static addr_t do_mmap(addr_t addr, uint64_t len, dword_t prot, dword_t flags, fd_t fd_no, dword_t offset) { + int err; + pages_t pages = (len + PAGE_SIZE - 1) / PAGE_SIZE; + if (!pages) return _EINVAL; + page_t page; + bool caller_hint_used = false; + if (addr != 0) { + if (PGOFFSET(addr) != 0) + return _EINVAL; + page = PAGE(addr); +#ifdef GUEST_ARM64 + // ARM64 has a 48-bit guest page table, so high-address hints are + // legitimate. Bun/JSC in particular reserves heap/cage regions at + // high random hints and stores pointers derived from the returned + // address. Falling back to a low address while the runtime still uses + // high-derived metadata corrupts allocator freelists. Only reject + // ranges outside the 48-bit user address space, and protect the low + // 4GB stack gap from low-address hints. + if (page > USER_ADDR_MAX_PAGE || pages > USER_ADDR_MAX_PAGE - page || + (page < 0x100000 && page + pages > STACK_TOP_PAGE)) { + if (flags & MMAP_FIXED) + return _ENOMEM; + addr = 0; + page = 0; + } +#endif + if (addr != 0 && !(flags & MMAP_FIXED) && !pt_is_hole(current->mem, page, pages)) + addr = 0; +#ifdef GUEST_ARM64 + if (addr != 0 && !(flags & MMAP_FIXED) && mem_range_has_reservation(current->mem, page, pages)) + addr = 0; +#endif + if (addr != 0) + caller_hint_used = true; + } + if (addr == 0) { +#ifdef GUEST_ARM64 + // Large no-reserve arenas (Bun/JSC heap cages, V8 code ranges, etc.) + // should live in the 48-bit high address space instead of consuming + // the scarce low 4GB mmap window. They are lazy reservations, so this + // costs page-table metadata only as pages are touched. + if ((flags & MMAP_NORESERVE) && pages >= 0x10000) + page = pt_find_hole_high(current->mem, pages); + else +#endif + page = pt_find_hole(current->mem, pages); + if (page == BAD_PAGE) + return _ENOMEM; + } + + if (flags & MMAP_SHARED) + prot |= P_SHARED; + + if (flags & MMAP_ANONYMOUS) { + // PROT_NONE mappings (guard regions) don't consume real memory, + // so don't count them against the anonymous page limit. + bool is_prot_none = !(prot & P_READ) && !(prot & P_WRITE) && !(prot & P_EXEC); +#ifdef GUEST_ARM64 + if ((flags & MMAP_NORESERVE) && pages >= 0x10000) { + if (!caller_hint_used) { + pages_t align_pages = pages; + if (align_pages > 0x40000) align_pages = 0x40000; + page_t aligned = (page / align_pages) * align_pages; + if (aligned >= MMAP_HOLE_END && pt_is_hole(current->mem, aligned, pages) && !mem_range_has_reservation(current->mem, aligned, pages)) + page = aligned; + } + if (!pt_is_hole(current->mem, page, pages) || mem_range_has_reservation(current->mem, page, pages)) + return _ENOMEM; + if ((err = pt_map_lazy(current->mem, page, pages, prot)) < 0) + return err; + return page << PAGE_BITS; + } +#endif +#if ANON_MMAP_LIMIT_PAGES > 0 + if (!is_prot_none && atomic_load(&anon_page_count) + (long)pages > ANON_MMAP_LIMIT_PAGES) + return _ENOMEM; + if (!is_prot_none) + atomic_fetch_add(&anon_page_count, (long)pages); +#endif + if ((err = pt_map_nothing(current->mem, page, pages, prot)) < 0) { +#if ANON_MMAP_LIMIT_PAGES > 0 + if (!is_prot_none) + atomic_fetch_sub(&anon_page_count, (long)pages); +#endif + return err; + } + } else { + // fd must be valid + struct fd *fd = f_get(fd_no); + if (fd == NULL) + return _EBADF; + if (fd->ops->mmap == NULL) + return _ENODEV; + if ((err = fd->ops->mmap(fd, current->mem, page, pages, offset, prot, flags)) < 0) + return err; + mem_pt(current->mem, page)->data->fd = fd_retain(fd); + mem_pt(current->mem, page)->data->file_offset = offset; + } + return page << PAGE_BITS; +} + +static addr_t mmap_common(addr_t addr, dword_t len, dword_t prot, dword_t flags, fd_t fd_no, dword_t offset) { + STRACE("mmap(0x%x, 0x%x, 0x%x, 0x%x, %d, %d)", addr, len, prot, flags, fd_no, offset); + if (len == 0) + return _EINVAL; + if (prot & ~P_RWX) + return _EINVAL; + if ((flags & MMAP_PRIVATE) && (flags & MMAP_SHARED)) + return _EINVAL; + + write_wrlock(¤t->mem->lock); + addr_t res = do_mmap(addr, len, prot, flags, fd_no, offset); + write_wrunlock(¤t->mem->lock); + return res; +} + +addr_t sys_mmap2(addr_t addr, dword_t len, dword_t prot, dword_t flags, fd_t fd_no, dword_t offset) { + return mmap_common(addr, len, prot, flags, fd_no, offset << PAGE_BITS); +} + +#if defined(GUEST_ARM64) +// ARM64 mmap syscall: offset is passed directly (not shifted like mmap2) +// and takes 6 direct arguments. +addr_t sys_mmap64(addr_t addr, addr_t len, dword_t prot, dword_t flags, fd_t fd_no, qword_t offset) { + STRACE("mmap64(0x%llx, 0x%llx, 0x%x, 0x%x, %d, 0x%llx)", (unsigned long long)addr, (unsigned long long)len, prot, flags, fd_no, (unsigned long long)offset); + if (len == 0) + return _EINVAL; + if (prot & ~P_RWX) + return _EINVAL; + if ((flags & MMAP_PRIVATE) && (flags & MMAP_SHARED)) + return _EINVAL; + + write_wrlock(¤t->mem->lock); + addr_t res = do_mmap(addr, len, prot, flags, fd_no, (dword_t)offset); + write_wrunlock(¤t->mem->lock); + return res; +} +#endif + +struct mmap_arg_struct { + dword_t addr, len, prot, flags, fd, offset; +}; + +addr_t sys_mmap(addr_t args_addr) { + struct mmap_arg_struct args; + if (user_get(args_addr, args)) + return _EFAULT; + return mmap_common(args.addr, args.len, args.prot, args.flags, args.fd, args.offset); +} + +int_t sys_munmap(addr_t addr, addr_t len) { + STRACE("munmap(0x%llx, 0x%llx)", (unsigned long long)addr, (unsigned long long)len); + pages_t pages = (len + PAGE_SIZE - 1) / PAGE_SIZE; + if (PGOFFSET(addr) != 0) + return _EINVAL; + if (len == 0) + return _EINVAL; + write_wrlock(¤t->mem->lock); + int err = pt_unmap_always(current->mem, PAGE(addr), pages); + write_wrunlock(¤t->mem->lock); + if (err < 0) + return _EINVAL; + return 0; +} + +#define MREMAP_MAYMOVE_ 1 +#define MREMAP_FIXED_ 2 + +addr_t sys_mremap(addr_t addr, dword_t old_len, dword_t new_len, dword_t flags) { + STRACE("mremap(%#x, %#x, %#x, %d)", addr, old_len, new_len, flags); + if (PGOFFSET(addr) != 0) + return _EINVAL; + if (old_len == 0 || new_len == 0) + return _EINVAL; + if (flags & ~(MREMAP_MAYMOVE_ | MREMAP_FIXED_)) + return _EINVAL; + if (flags & MREMAP_FIXED_) { + FIXME("missing MREMAP_FIXED"); + return _EINVAL; + } + + page_t start = PAGE(addr); + pages_t old_pages = PAGE_ROUND_UP(old_len); + pages_t new_pages = PAGE_ROUND_UP(new_len); + addr_t result = addr; + + write_wrlock(¤t->mem->lock); + + if (new_pages <= old_pages) { + int err = pt_unmap(current->mem, start + new_pages, old_pages - new_pages); + if (err < 0) + result = _EFAULT; + goto out; + } + + struct pt_entry *entry = mem_pt(current->mem, start); + if (entry == NULL) { + result = _EFAULT; + goto out; + } + dword_t pt_flags = entry->flags; + for (page_t page = start; page < start + old_pages; page++) { + entry = mem_pt(current->mem, page); + if (entry == NULL || entry->flags != pt_flags) { + result = _EFAULT; + goto out; + } + } + if (!(pt_flags & P_ANONYMOUS)) { + FIXME("mremap grow on file mappings"); + result = _EFAULT; + goto out; + } + page_t extra_start = start + old_pages; + pages_t extra_pages = new_pages - old_pages; + bool is_prot_none = !(pt_flags & (P_READ | P_WRITE | P_EXEC)); + if (pt_is_hole(current->mem, extra_start, extra_pages)) { +#if ANON_MMAP_LIMIT_PAGES > 0 + if (!is_prot_none && atomic_load(&anon_page_count) + (long)extra_pages > ANON_MMAP_LIMIT_PAGES) { + result = _ENOMEM; + goto out; + } + if (!is_prot_none) + atomic_fetch_add(&anon_page_count, (long)extra_pages); +#endif + int err = pt_map_nothing(current->mem, extra_start, extra_pages, pt_flags); + if (err < 0) { +#if ANON_MMAP_LIMIT_PAGES > 0 + if (!is_prot_none) + atomic_fetch_sub(&anon_page_count, (long)extra_pages); +#endif + result = err; + } + goto out; + } + + if (!(flags & MREMAP_MAYMOVE_)) { + result = _ENOMEM; + goto out; + } + + page_t new_start = pt_find_hole(current->mem, new_pages); + if (new_start == BAD_PAGE) { + result = _ENOMEM; + goto out; + } +#if ANON_MMAP_LIMIT_PAGES > 0 + if (!is_prot_none && atomic_load(&anon_page_count) + (long)new_pages > ANON_MMAP_LIMIT_PAGES) { + result = _ENOMEM; + goto out; + } + if (!is_prot_none) + atomic_fetch_add(&anon_page_count, (long)new_pages); +#endif + int err = pt_map_nothing(current->mem, new_start, new_pages, pt_flags); + if (err < 0) { +#if ANON_MMAP_LIMIT_PAGES > 0 + if (!is_prot_none) + atomic_fetch_sub(&anon_page_count, (long)new_pages); +#endif + result = err; + goto out; + } + if (!is_prot_none) { + for (pages_t i = 0; i < old_pages; i++) { + struct pt_entry *src = mem_pt(current->mem, start + i); + struct pt_entry *dst = mem_pt(current->mem, new_start + i); + memcpy((char *)dst->data->data + dst->offset, + (char *)src->data->data + src->offset, + PAGE_SIZE); + } + } + pt_unmap_always(current->mem, start, old_pages); + result = new_start << PAGE_BITS; + +out: + write_wrunlock(¤t->mem->lock); + return result; +} + +int_t sys_mprotect(addr_t addr, addr_t len, int_t prot) { + STRACE("mprotect(0x%llx, 0x%llx, 0x%x)", (unsigned long long)addr, (unsigned long long)len, prot); + if (PGOFFSET(addr) != 0) + return _EINVAL; + if (prot & ~P_RWX) + return _EINVAL; + pages_t pages = PAGE_ROUND_UP(len); + write_wrlock(¤t->mem->lock); + int err = pt_set_flags(current->mem, PAGE(addr), pages, prot); + write_wrunlock(¤t->mem->lock); + return err; +} + +dword_t sys_madvise(addr_t addr, dword_t len, dword_t advice) { + STRACE("madvise(0x%llx, 0x%x, %d)", (unsigned long long)addr, len, advice); + if (PGOFFSET(addr) != 0) + return _EINVAL; + // Linux returns ENOMEM if any page in the range is unmapped. Lazy + // reservations count as mappings because they represent PROT_NONE VMAs. + read_wrlock(¤t->mem->lock); + for (page_t page = PAGE(addr); page < PAGE(addr) + PAGE_ROUND_UP(len); page++) { + if (mem_pt(current->mem, page) == NULL && + mem_find_reservation(current->mem, page) == NULL) { + read_wrunlock(¤t->mem->lock); + return _ENOMEM; + } + } + read_wrunlock(¤t->mem->lock); + + // MADV_FREE (8) is purely advisory: the kernel MAY reclaim the pages under + // memory pressure, but until then reads still return the old contents. + // Eagerly zeroing them is both wrong (a subsequent read that races the + // reclaim must see either old-or-zero, never a torn mix) and dangerous + // under threads — another thread aliasing the page via a live TLB entry + // would observe it turn to zero mid-computation. JSC's scavenger uses + // MADV_FREE heavily; treat it as a no-op (safe: we just keep the memory). + if (advice == 8 /* MADV_FREE */) + return 0; + + if (advice == 4 /* MADV_DONTNEED */) { + // Anonymous private pages become zero-fill. File-backed private pages + // must retain their file contents; zeroing those corrupts mapped + // executables and caches. Walk under a read lock and skip lazy pages so + // exit cannot hang behind repeated per-page write-lock acquisition. + addr_t end = addr + len; + bool any = false; + read_wrlock(¤t->mem->lock); + for (addr_t p = addr; p < end; p += PAGE_SIZE) { + struct pt_entry *pt = mem_pt(current->mem, PAGE(p)); + if (pt == NULL || pt->data == NULL) + continue; + if (!(pt->flags & P_ANONYMOUS) && pt->data->fd != NULL) + continue; + void *ptr = mem_ptr(current->mem, p, MEM_WRITE); + if (ptr != NULL) { + memset(ptr, 0, PAGE_SIZE); + any = true; + } + } + read_wrunlock(¤t->mem->lock); + if (any) + mem_changed_pub(current->mem); + } + return 0; +} + +dword_t sys_mbind(addr_t UNUSED(addr), dword_t UNUSED(len), int_t UNUSED(mode), + addr_t UNUSED(nodemask), dword_t UNUSED(maxnode), uint_t UNUSED(flags)) { + return 0; +} + +int_t sys_mlock(addr_t UNUSED(addr), dword_t UNUSED(len)) { + return 0; +} + +int_t sys_msync(addr_t UNUSED(addr), dword_t UNUSED(len), int_t UNUSED(flags)) { + return 0; +} + +addr_t sys_brk(addr_t new_brk) { + STRACE("brk(0x%x)", new_brk); + struct mm *mm = current->mm; + write_wrlock(&mm->mem.lock); + if (new_brk < mm->start_brk) + goto out; + addr_t old_brk = mm->brk; + + if (new_brk > old_brk) { + // expand heap: map region from old_brk to new_brk + // round up because of the definition of brk: "the first location after the end of the uninitialized data segment." (brk(2)) + // if the brk is 0x2000, page 0x2000 shouldn't be mapped, but it should be if the brk is 0x2001. + page_t start = PAGE_ROUND_UP(old_brk); + pages_t size = PAGE_ROUND_UP(new_brk) - PAGE_ROUND_UP(old_brk); + if (!pt_is_hole(&mm->mem, start, size)) + goto out; +#if ANON_MMAP_LIMIT_PAGES > 0 + if (atomic_load(&anon_page_count) + (long)size > ANON_MMAP_LIMIT_PAGES) + goto out; + atomic_fetch_add(&anon_page_count, (long)size); +#endif + int err = pt_map_nothing(&mm->mem, start, size, P_WRITE); + if (err < 0) { +#if ANON_MMAP_LIMIT_PAGES > 0 + atomic_fetch_sub(&anon_page_count, (long)size); +#endif + goto out; + } + } else if (new_brk < old_brk) { + // shrink heap: unmap pages that are entirely above new_brk + // PAGE_ROUND_UP(new_brk) is the first page we can safely unmap + // (the page containing new_brk may still have live data below new_brk) + page_t first_unmap = PAGE_ROUND_UP(new_brk); + page_t last_unmap = PAGE_ROUND_UP(old_brk); + if (first_unmap < last_unmap) + pt_unmap_always(&mm->mem, first_unmap, last_unmap - first_unmap); + } + + mm->brk = new_brk; +out:; + addr_t brk = mm->brk; + write_wrunlock(&mm->mem.lock); + return brk; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/native_offload.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/native_offload.c new file mode 100644 index 0000000000..d4d8801118 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/native_offload.c @@ -0,0 +1,811 @@ +// Native offload: run registered guest binaries as native host processes. +// Mappings are configured via CLI: -n ffmpeg -n ffprobe=/usr/local/bin/ffprobe +// Phase 1: macOS only via posix_spawn. +// +// Path redirection is handled transparently by libfakefs_redirect.dylib, +// injected into the native process via DYLD_INSERT_LIBRARIES. This intercepts +// all filesystem calls (open, stat, access, etc.) and redirects absolute guest +// paths to the fakefs data directory. No argv-level path rewriting needed. + +#include <unistd.h> +#include <string.h> +#include <stdlib.h> +#include <stdio.h> +#include <signal.h> +#include <sys/wait.h> +#include <sys/stat.h> +#include <libgen.h> +#include <limits.h> +#include <fcntl.h> +#include <dirent.h> +#include <pthread.h> +#ifdef __APPLE__ +#include <TargetConditionals.h> +#if TARGET_OS_OSX +#include <spawn.h> +#include <mach-o/dyld.h> +#define HAS_POSIX_SPAWN 1 +#endif +#endif + +#include "kernel/calls.h" +#include "kernel/task.h" +#include "kernel/native_offload.h" +#include "kernel/fs.h" +#include "fs/fd.h" +#include "fs/fake-db.h" +#ifdef ISH_INTERNAL +#include "fs/fake.h" +#else +#define ISH_INTERNAL +#include "fs/fake.h" +#undef ISH_INTERNAL +#endif + +#if !__APPLE__ +int native_offload_add(const char *spec) { (void)spec; return -1; } +const char *native_offload_lookup(const char *guest_path) { (void)guest_path; return NULL; } +int native_offload_exec(const char *native_path, const char *guest_file, + size_t argc, const char *argv, const char *envp) { + (void)native_path; (void)guest_file; (void)argc; (void)argv; (void)envp; + return _ENOSYS; +} +bool native_offload_forward_signal(struct task *task, int sig) { + (void)task; (void)sig; return false; +} +#else + +// --- Dynamic registry --- + +struct offload_entry { + char *guest_name; + char *native_path; // NULL if using handler + native_handler_func handler; // non-NULL for in-process execution +}; + +static struct offload_entry offload_entries[NATIVE_OFFLOAD_MAX]; +static int offload_count = 0; + +#ifdef HAS_POSIX_SPAWN +// Path to the redirect dylib (resolved once at startup) +static char dylib_path[PATH_MAX]; +static bool dylib_found = false; + +static char *auto_detect_host_path(const char *name) { + static const char *search_dirs[] = { + "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", NULL + }; + char path[PATH_MAX]; + for (const char **dir = search_dirs; *dir; dir++) { + snprintf(path, sizeof(path), "%s/%s", *dir, name); + if (access(path, X_OK) == 0) + return strdup(path); + } + return NULL; +} + +// Find the redirect dylib next to the ish binary +static void resolve_dylib_path(void) { + char exe[PATH_MAX]; + uint32_t size = sizeof(exe); + if (_NSGetExecutablePath(exe, &size) != 0) + return; + char *real = realpath(exe, NULL); + if (!real) return; + char *dir = dirname(real); + snprintf(dylib_path, sizeof(dylib_path), "%s/libfakefs_redirect.dylib", dir); + free(real); + if (access(dylib_path, F_OK) == 0) + dylib_found = true; + else + fprintf(stderr, "native_offload: warning: %s not found, path redirection disabled\n", + dylib_path); +} + +int native_offload_add(const char *spec) { + if (offload_count >= NATIVE_OFFLOAD_MAX) { + fprintf(stderr, "native_offload: too many entries (max %d)\n", NATIVE_OFFLOAD_MAX); + return -1; + } + + // Resolve dylib path on first call + if (offload_count == 0) + resolve_dylib_path(); + + const char *eq = strchr(spec, '='); + char *guest_name, *native_path; + + if (eq) { + guest_name = strndup(spec, eq - spec); + const char *path = eq + 1; + if (access(path, X_OK) != 0) { + fprintf(stderr, "native_offload: %s: not found or not executable\n", path); + free(guest_name); + return -1; + } + native_path = strdup(path); + } else { + guest_name = strdup(spec); + native_path = auto_detect_host_path(spec); + if (!native_path) { + fprintf(stderr, "native_offload: %s: not found in host PATH\n", spec); + free(guest_name); + return -1; + } + } + + struct offload_entry *e = &offload_entries[offload_count++]; + e->guest_name = guest_name; + e->native_path = native_path; + fprintf(stderr, "native_offload: %s → %s\n", guest_name, native_path); + return 0; +} +#else +int native_offload_add(const char *spec) { + (void)spec; + fprintf(stderr, "native_offload: posix_spawn not available on this platform\n"); + return -1; +} +#endif // HAS_POSIX_SPAWN + +int native_offload_add_handler(const char *guest_name, native_handler_func handler) { + if (offload_count >= NATIVE_OFFLOAD_MAX) return -1; + struct offload_entry *e = &offload_entries[offload_count++]; + e->guest_name = strdup(guest_name); + e->native_path = NULL; + e->handler = handler; + fprintf(stderr, "native_offload: %s → [builtin]\n", guest_name); + return 0; +} + +// Internal: find entry by guest binary basename +static struct offload_entry *offload_find(const char *guest_path) { + if (offload_count == 0) + return NULL; + const char *base = strrchr(guest_path, '/'); + base = base ? base + 1 : guest_path; + for (int i = 0; i < offload_count; i++) { + if (strcmp(base, offload_entries[i].guest_name) == 0) + return &offload_entries[i]; + } + return NULL; +} + +const char *native_offload_lookup(const char *guest_path) { + struct offload_entry *e = offload_find(guest_path); + if (!e) return NULL; + // Return non-NULL to signal "offload this". For handler-only entries + // (no native_path), return a sentinel so the caller proceeds to exec. + return e->native_path ? e->native_path : "[builtin]"; +} + +// --- Shared helpers --- + +extern struct mount *g_fakefs_mount; + +// Get the root mount source path (works for both realfs and fakefs) +static const char *get_root_source(void) { + if (g_fakefs_mount && g_fakefs_mount->source) + return g_fakefs_mount->source; + // realfs: get source from the root fd's mount + if (current->fs && current->fs->root && current->fs->root->mount) + return current->fs->root->mount->source; + return NULL; +} + +// Translate a guest absolute path to the real host path, honoring bind +// mounts. iSH bind-mounts guest directories (e.g. /var/minis/workspace) to +// real host locations outside the fakefs data/ tree; native offload +// handlers that execute on the host must follow those bind mounts, or +// they'll read/write the wrong files and the guest will see a ghost +// filesystem divergence. Falls back to fakefs->source + guest_path when +// no bind-mount rule matches. Returns true on success. +static bool build_host_path_for_guest(const char *guest_path, + char *out, size_t out_size) { + if (!guest_path || !out || out_size == 0) return false; + // 1) bind-mount wins: /var/minis/... → /Users/.../Library/MinisChat/... + if (guest_path[0] == '/' && + fakefs_bind_mount_translate_path(guest_path, out, out_size)) + return true; + // 2) fall back to fakefs source directory + const char *root = get_root_source(); + if (!root) return false; + const char *rel = guest_path; + if (rel[0] == '/') rel++; + int n = snprintf(out, out_size, "%s/%s", root, rel); + return n > 0 && (size_t)n < out_size; +} + +static void native_free_string_array(char **arr) { + if (!arr) return; + for (char **p = arr; *p; p++) free(*p); + free(arr); +} + +#ifdef HAS_POSIX_SPAWN +static char **build_native_argv(const char *native_path, size_t argc, + const char *packed_argv) { + char **argv = calloc(argc + 1, sizeof(char *)); + if (!argv) return NULL; + + argv[0] = strdup(native_path); + const char *p = packed_argv; + p += strlen(p) + 1; // skip guest argv[0] + for (size_t i = 1; i < argc; i++) { + argv[i] = strdup(p); + p += strlen(p) + 1; + } + argv[argc] = NULL; + return argv; +} + +static char **build_native_envp(const char *packed_envp) { + // Count original entries + size_t count = 0; + const char *p = packed_envp; + while (*p) { count++; p += strlen(p) + 1; } + + // +2 for DYLD_INSERT_LIBRARIES and FAKEFS_ROOT + char **envp = calloc(count + 3, sizeof(char *)); + if (!envp) return NULL; + + static const char *skip_prefixes[] = { + "OPENSSL_armcap=", "PYTHONMALLOC=", "PYTHONDONTWRITEBYTECODE=", + "DYLD_INSERT_LIBRARIES=", "FAKEFS_ROOT=", // don't pass guest values + NULL + }; + + size_t j = 0; + p = packed_envp; + while (*p) { + bool skip = false; + for (const char **sp = skip_prefixes; *sp; sp++) { + if (strncmp(p, *sp, strlen(*sp)) == 0) { skip = true; break; } + } + if (!skip) envp[j++] = strdup(p); + p += strlen(p) + 1; + } + + // Inject DYLD_INSERT_LIBRARIES + FAKEFS_ROOT for path redirection. + // Both fakefs and realfs need this: guest absolute paths must be + // redirected to the rootfs directory on host. + const char *root_source = get_root_source(); + if (root_source && dylib_found) { + char buf[PATH_MAX + 32]; + snprintf(buf, sizeof(buf), "DYLD_INSERT_LIBRARIES=%s", dylib_path); + envp[j++] = strdup(buf); + snprintf(buf, sizeof(buf), "FAKEFS_ROOT=%s", root_source); + envp[j++] = strdup(buf); + } + + envp[j] = NULL; + return envp; +} +#endif // HAS_POSIX_SPAWN + +// --- Signal mapping --- + +static int guest_to_host_signal(int guest_sig) { + switch (guest_sig) { + case 1: return SIGHUP; case 2: return SIGINT; + case 3: return SIGQUIT; case 6: return SIGABRT; + case 9: return SIGKILL; case 13: return SIGPIPE; + case 14: return SIGALRM; case 15: return SIGTERM; + case 17: return SIGCHLD; case 18: return SIGCONT; + case 19: return SIGSTOP; case 20: return SIGTSTP; + default: return guest_sig; + } +} + +bool native_offload_forward_signal(struct task *task, int sig) { + if (!task->is_native_proxy || task->native_pid <= 0) + return false; + int host_sig = guest_to_host_signal(sig); + if (host_sig > 0) + kill(task->native_pid, host_sig); + return true; +} + +// --- Post-exec: scan for new files and register in fakefs DB --- +// Since the dylib redirects all paths transparently, we don't know exactly +// which files were created. We scan directories mentioned in argv for any +// files not yet in the DB. + +static void register_file_if_new(struct fakefs_db *fs, const char *guest_path, + const char *host_path) { + struct stat st; + if (stat(host_path, &st) != 0) + return; + if (!S_ISREG(st.st_mode)) + return; + + db_begin_write(fs); + inode_t existing = path_get_inode(fs, guest_path); + if (existing != 0) { + db_commit(fs); + return; + } + + struct ish_stat ishstat = { + .mode = S_IFREG | (st.st_mode & 0777), + .uid = current->euid, + .gid = current->egid, + .rdev = 0, + }; + path_create(fs, guest_path, &ishstat); + db_commit(fs); + printk("native_offload: registered %s in fakefs\n", guest_path); +} + +// Scan a single directory (non-recursive) for unregistered files +static void scan_dir_for_new_files(struct fakefs_db *fs, const char *guest_dir) { + if (!g_fakefs_mount || !g_fakefs_mount->source) + return; + + // Follow bind mounts: guest_dir may live under a bind-mounted prefix + // whose real content is outside the fakefs data/ tree. + char host_dir[PATH_MAX]; + if (!build_host_path_for_guest(guest_dir, host_dir, sizeof(host_dir))) + return; + + DIR *d = opendir(host_dir); + if (!d) return; + + struct dirent *ent; + while ((ent = readdir(d)) != NULL) { + if (ent->d_name[0] == '.') continue; // skip . and .. + if (ent->d_type != DT_REG && ent->d_type != DT_UNKNOWN) continue; + + char host_path[PATH_MAX], guest_path[PATH_MAX]; + snprintf(host_path, sizeof(host_path), "%s/%s", host_dir, ent->d_name); + snprintf(guest_path, sizeof(guest_path), "%s/%s", guest_dir, ent->d_name); + register_file_if_new(fs, guest_path, host_path); + } + closedir(d); +} + +// Get guest CWD path (returns static buffer or NULL) +static const char *get_guest_cwd(void) { + if (!current->fs || !current->fs->pwd) + return NULL; + static char guest_cwd[MAX_PATH]; + int err = current->fs->pwd->mount->fs->getpath(current->fs->pwd, guest_cwd); + if (err < 0) return NULL; + return guest_cwd; +} + +// Extract directories from argv that might contain new output files, +// plus always scan CWD (native processes often write to CWD with relative paths). +static void register_new_files(size_t argc, const char *packed_argv) { + if (!g_fakefs_mount) return; + struct fakefs_db *fs = &g_fakefs_mount->fakefs; + + // Always scan CWD — native processes commonly write to CWD via relative paths + // (e.g., yt-dlp calls ffmpeg with relative output filename) + const char *guest_cwd = get_guest_cwd(); + if (guest_cwd) + scan_dir_for_new_files(fs, guest_cwd); + + const char *p = packed_argv; + p += strlen(p) + 1; // skip argv[0] + + for (size_t i = 1; i < argc; i++) { + if ((p[0] == '/' || (p[0] == '.' && p[1] == '/')) && !strstr(p, "://")) { + // It's a path — check both as file and scan its parent dir. + // Use bind-mount-aware translation so we register the file at + // the real host location the handler actually wrote to. + char host_path[PATH_MAX]; + if (build_host_path_for_guest(p, host_path, sizeof(host_path))) + register_file_if_new(fs, p, host_path); + + // Also scan parent directory for pattern-generated files + char parent[PATH_MAX]; + strncpy(parent, p, sizeof(parent) - 1); + parent[sizeof(parent) - 1] = '\0'; + char *slash = strrchr(parent, '/'); + if (slash && slash != parent) { + *slash = '\0'; + // Skip if same as CWD (already scanned) + if (!guest_cwd || strcmp(parent, guest_cwd) != 0) + scan_dir_for_new_files(fs, parent); + } + } + p += strlen(p) + 1; + } +} + +// --- CWD resolution --- + +static char *get_host_cwd(void) { + if (!current->fs || !current->fs->pwd) + return NULL; + char guest_cwd[MAX_PATH]; + int err = current->fs->pwd->mount->fs->getpath(current->fs->pwd, guest_cwd); + if (err < 0) return NULL; + + char *host_cwd = malloc(PATH_MAX); + if (!host_cwd) return NULL; + + // Handle empty guest cwd ("/" after stripping leading slash) by falling + // back directly to the fakefs source — bind-mount translation is only + // meaningful for subpaths of a mounted prefix. + if (guest_cwd[0] == '\0' || (guest_cwd[0] == '/' && guest_cwd[1] == '\0')) { + const char *root = get_root_source(); + if (!root) { free(host_cwd); return NULL; } + snprintf(host_cwd, PATH_MAX, "%s", root); + return host_cwd; + } + + if (!build_host_path_for_guest(guest_cwd, host_cwd, PATH_MAX)) { + free(host_cwd); + return NULL; + } + return host_cwd; +} + +// --- Pipe forwarding for stdout/stderr --- +// Two modes: +// 1. Guest fd mode (iOS): reads from pipe, writes via fd->ops->write (TTY driver) +// 2. Host fd mode (macOS posix_spawn): reads from pipe, writes to host real_fd + +struct pipe_fwd { + int pipe_rd; + int dest_fd; // host fd (macOS posix_spawn path) + struct fd *guest_fd; // guest fd (iOS handler path), NULL if using dest_fd +}; + +static void *pipe_forward_thread(void *arg) { + struct pipe_fwd *fwd = arg; + char buf[4096]; + ssize_t n; + while ((n = read(fwd->pipe_rd, buf, sizeof(buf))) > 0) { + // Replace \r not followed by \n with \n (progress bar lines) + for (ssize_t i = 0; i < n; i++) { + if (buf[i] == '\r') { + if (i + 1 < n && buf[i + 1] == '\n') + continue; // \r\n is fine, keep both + buf[i] = '\n'; + } + } + if (fwd->guest_fd && fwd->guest_fd->ops->write) { + // iOS path: write through guest fd ops (TTY driver → Terminal UI) + ssize_t written = 0; + while (written < n) { + ssize_t w = fwd->guest_fd->ops->write(fwd->guest_fd, + buf + written, n - written); + if (w <= 0) break; + written += w; + } + } else { + // macOS path: write to host real_fd + ssize_t written = 0; + while (written < n) { + ssize_t w = write(fwd->dest_fd, buf + written, n - written); + if (w < 0) { + if (errno == EINTR) continue; + break; + } + written += w; + } + } + } + close(fwd->pipe_rd); + if (fwd->guest_fd) + fd_close(fwd->guest_fd); + free(fwd); + return NULL; +} + +// Start forwarding with host fd destination (macOS posix_spawn) +static pthread_t start_pipe_forward(int pipe_rd, int dest_fd) { + struct pipe_fwd *fwd = malloc(sizeof(*fwd)); + fwd->pipe_rd = pipe_rd; + fwd->dest_fd = dest_fd; + fwd->guest_fd = NULL; + pthread_t tid; + pthread_create(&tid, NULL, pipe_forward_thread, fwd); + return tid; +} + +// Start forwarding with guest fd destination (iOS handler) +static pthread_t start_pipe_forward_guest(int pipe_rd, struct fd *guest_fd) { + struct pipe_fwd *fwd = malloc(sizeof(*fwd)); + fwd->pipe_rd = pipe_rd; + fwd->dest_fd = -1; + fwd->guest_fd = fd_retain(guest_fd); + pthread_t tid; + pthread_create(&tid, NULL, pipe_forward_thread, fwd); + return tid; +} + +// --- Exec semantics (shared by posix_spawn and in-process handler) --- + +static void apply_exec_semantics(const char *guest_file) { + lock(¤t->general_lock); + const char *base = strrchr(guest_file, '/'); + base = base ? base + 1 : guest_file; + strncpy(current->comm, base, sizeof(current->comm)); + unlock(¤t->general_lock); + update_thread_name(); + + current->did_exec = true; + vfork_notify(current); + fdtable_do_cloexec(current->files); + + if (current->sighand) { + lock(¤t->sighand->lock); + for (int sig = 0; sig < NUM_SIGS; sig++) { + struct sigaction_ *action = ¤t->sighand->action[sig]; + if (action->handler != SIG_IGN_) + action->handler = SIG_DFL_; + } + current->altstack = 0; + current->altstack_size = 0; + unlock(¤t->sighand->lock); + } +} + +// --- In-process handler execution (works on both macOS and iOS) --- + +static int exec_handler(native_handler_func handler, const char *guest_file, + size_t argc, const char *argv, const char *envp) { + (void)envp; + const char *root_source = get_root_source(); + + // Build argc/argv for the handler, translating guest paths to host paths. + // Unlike posix_spawn path (which uses DYLD interpose for transparent + // redirection), in-process handlers need explicit path translation. + char **handler_argv = calloc(argc + 1, sizeof(char *)); + if (!handler_argv) return _ENOMEM; + + const char *p = argv; + for (size_t i = 0; i < argc; i++) { + // Absolute guest path → host path, honoring bind mounts first. + // Skip URLs (anything containing "://") which are not filesystem paths. + if (root_source && p[0] == '/' && !strstr(p, "://")) { + char host_path[PATH_MAX]; + if (build_host_path_for_guest(p, host_path, sizeof(host_path))) + handler_argv[i] = strdup(host_path); + else + handler_argv[i] = strdup(p); + } else { + handler_argv[i] = strdup(p); + } + p += strlen(p) + 1; + } + handler_argv[argc] = NULL; + + printk("native_offload: [builtin] %s (pid %d)\n", guest_file, current->pid); + + // Get guest stdio fds (retain for forwarding threads) + struct fd *guest_stdin = NULL, *guest_stdout = NULL, *guest_stderr = NULL; + lock(¤t->files->lock); + if (current->files->files[0]) guest_stdin = fd_retain(current->files->files[0]); + if (current->files->files[1]) guest_stdout = fd_retain(current->files->files[1]); + if (current->files->files[2]) guest_stderr = fd_retain(current->files->files[2]); + unlock(¤t->files->lock); + + // Create pipes: handler writes to pipe write-end, forwarding thread reads + // from pipe read-end and writes through guest fd ops (TTY driver on iOS). + int stdout_pipe[2] = {-1, -1}, stderr_pipe[2] = {-1, -1}; + int handler_stdin = -1, handler_stdout = -1, handler_stderr = -1; + + if (guest_stdin && guest_stdin->real_fd >= 0) + handler_stdin = guest_stdin->real_fd; + + if (guest_stdout && pipe(stdout_pipe) == 0) + handler_stdout = stdout_pipe[1]; + else + stdout_pipe[0] = stdout_pipe[1] = -1; + + if (guest_stderr && pipe(stderr_pipe) == 0) + handler_stderr = stderr_pipe[1]; + else + stderr_pipe[0] = stderr_pipe[1] = -1; + + apply_exec_semantics(guest_file); + + // Start pipe forwarding threads — write through guest fd ops + // so data reaches iOS Terminal UI (via TTY driver) + pthread_t stdout_tid = 0, stderr_tid = 0; + if (stdout_pipe[0] >= 0 && guest_stdout) + stdout_tid = start_pipe_forward_guest(stdout_pipe[0], guest_stdout); + if (stderr_pipe[0] >= 0 && guest_stderr) + stderr_tid = start_pipe_forward_guest(stderr_pipe[0], guest_stderr); + + // Resolve host paths for handler: it may need to read/write files + // in the fakefs data directory. Set cwd to host CWD. + char *host_cwd = get_host_cwd(); + char saved_cwd[PATH_MAX]; + bool cwd_changed = false; + if (host_cwd) { + if (getcwd(saved_cwd, sizeof(saved_cwd)) && chdir(host_cwd) == 0) + cwd_changed = true; + free(host_cwd); + } + + // Call the handler in-process + int ret = handler((int)argc, handler_argv, handler_stdin, handler_stdout, handler_stderr); + + // Close write ends so forwarding threads see EOF + if (stdout_pipe[1] >= 0) close(stdout_pipe[1]); + if (stderr_pipe[1] >= 0) close(stderr_pipe[1]); + if (stdout_tid) pthread_join(stdout_tid, NULL); + if (stderr_tid) pthread_join(stderr_tid, NULL); + + // Restore cwd + if (cwd_changed) + (void)chdir(saved_cwd); + + // Release guest fd references (forwarding threads already released theirs) + if (guest_stdin) fd_close(guest_stdin); + if (guest_stdout) fd_close(guest_stdout); + if (guest_stderr) fd_close(guest_stderr); + + native_free_string_array(handler_argv); + + int exit_code = ret << 8; + printk("native_offload: [builtin] %s exited with code %d\n", guest_file, ret); + + register_new_files(argc, argv); + do_exit(exit_code); + __builtin_unreachable(); +} + +// --- posix_spawn execution (macOS only) --- + +#ifdef HAS_POSIX_SPAWN +static int exec_posix_spawn(const char *native_path, const char *guest_file, + size_t argc, const char *argv, const char *envp) { + char **native_argv = build_native_argv(native_path, argc, argv); + if (!native_argv) + return _ENOMEM; + + char **native_envp = build_native_envp(envp); + if (!native_envp) { + native_free_string_array(native_argv); + return _ENOMEM; + } + + printk("native_offload: exec:"); + for (size_t i = 0; native_argv[i]; i++) + printk(" %s", native_argv[i]); + printk("\n"); + + // Get stdio fds + int stdin_fd = -1, stdout_fd = -1, stderr_fd = -1; + lock(¤t->files->lock); + if (current->files->files[0]) stdin_fd = current->files->files[0]->real_fd; + if (current->files->files[1]) stdout_fd = current->files->files[1]->real_fd; + if (current->files->files[2]) stderr_fd = current->files->files[2]->real_fd; + unlock(¤t->files->lock); + + // Pipes for stdout/stderr (\r → \n conversion) + int stdout_pipe[2] = {-1, -1}, stderr_pipe[2] = {-1, -1}; + int stdout_dest = stdout_fd, stderr_dest = stderr_fd; + + if (stdout_fd >= 0 && pipe(stdout_pipe) == 0) {} else stdout_pipe[0] = stdout_pipe[1] = -1; + if (stderr_fd >= 0 && pipe(stderr_pipe) == 0) {} else stderr_pipe[0] = stderr_pipe[1] = -1; + + // posix_spawn setup + posix_spawn_file_actions_t actions; + posix_spawn_file_actions_init(&actions); + if (stdin_fd >= 0) + posix_spawn_file_actions_adddup2(&actions, stdin_fd, STDIN_FILENO); + else + posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0); + if (stdout_pipe[1] >= 0) { + posix_spawn_file_actions_adddup2(&actions, stdout_pipe[1], STDOUT_FILENO); + posix_spawn_file_actions_addclose(&actions, stdout_pipe[0]); + } else if (stdout_fd >= 0) { + posix_spawn_file_actions_adddup2(&actions, stdout_fd, STDOUT_FILENO); + } + if (stderr_pipe[1] >= 0) { + posix_spawn_file_actions_adddup2(&actions, stderr_pipe[1], STDERR_FILENO); + posix_spawn_file_actions_addclose(&actions, stderr_pipe[0]); + } else if (stderr_fd >= 0) { + posix_spawn_file_actions_adddup2(&actions, stderr_fd, STDERR_FILENO); + } + + posix_spawnattr_t attrs; + posix_spawnattr_init(&attrs); + + char *host_cwd = get_host_cwd(); + if (host_cwd) + posix_spawn_file_actions_addchdir(&actions, host_cwd); + + pid_t native_pid; + int spawn_err = posix_spawn(&native_pid, native_path, &actions, &attrs, + native_argv, native_envp); + + posix_spawn_file_actions_destroy(&actions); + posix_spawnattr_destroy(&attrs); + native_free_string_array(native_argv); + native_free_string_array(native_envp); + free(host_cwd); + + if (stdout_pipe[1] >= 0) close(stdout_pipe[1]); + if (stderr_pipe[1] >= 0) close(stderr_pipe[1]); + + if (spawn_err != 0) { + if (stdout_pipe[0] >= 0) close(stdout_pipe[0]); + if (stderr_pipe[0] >= 0) close(stderr_pipe[0]); + printk("native_offload: posix_spawn failed: %s\n", strerror(spawn_err)); + return _ENOEXEC; + } + + pthread_t stdout_tid = 0, stderr_tid = 0; + if (stdout_pipe[0] >= 0) + stdout_tid = start_pipe_forward(stdout_pipe[0], stdout_dest); + if (stderr_pipe[0] >= 0) + stderr_tid = start_pipe_forward(stderr_pipe[0], stderr_dest); + + printk("native_offload: spawned host pid %d for guest pid %d\n", + native_pid, current->pid); + + current->native_pid = native_pid; + current->is_native_proxy = true; + + apply_exec_semantics(guest_file); + + // Wait for native process + int status; + while (true) { + pid_t ret = waitpid(native_pid, &status, 0); + if (ret == native_pid) break; + if (ret < 0 && errno == EINTR) continue; + if (ret < 0) { + printk("native_offload: waitpid failed: %s\n", strerror(errno)); + status = 1 << 8; + break; + } + } + + if (stdout_tid) pthread_join(stdout_tid, NULL); + if (stderr_tid) pthread_join(stderr_tid, NULL); + + int exit_code; + if (WIFEXITED(status)) { + exit_code = WEXITSTATUS(status) << 8; + printk("native_offload: host pid %d exited with code %d\n", + native_pid, WEXITSTATUS(status)); + } else if (WIFSIGNALED(status)) { + exit_code = WTERMSIG(status); + printk("native_offload: host pid %d killed by signal %d\n", + native_pid, WTERMSIG(status)); + } else { + exit_code = 1 << 8; + } + + register_new_files(argc, argv); + current->is_native_proxy = false; + current->native_pid = 0; + do_exit(exit_code); + __builtin_unreachable(); +} +#endif // HAS_POSIX_SPAWN + +// --- Main exec dispatcher --- + +int native_offload_exec(const char *native_path, + const char *guest_file, + size_t argc, const char *argv, + const char *envp) { + // Check for in-process handler first (works on iOS and macOS) + struct offload_entry *entry = offload_find(guest_file); + if (entry && entry->handler) + return exec_handler(entry->handler, guest_file, argc, argv, envp); + +#ifdef HAS_POSIX_SPAWN + // posix_spawn path (macOS only, native_path must be valid) + if (!native_path || strcmp(native_path, "[builtin]") == 0) + return _ENOEXEC; + + return exec_posix_spawn(native_path, guest_file, argc, argv, envp); +#else + (void)native_path; + return _ENOEXEC; +#endif +} + +#endif // __APPLE__ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/native_offload.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/native_offload.h new file mode 100644 index 0000000000..6c5787b872 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/native_offload.h @@ -0,0 +1,86 @@ +#ifndef NATIVE_OFFLOAD_H +#define NATIVE_OFFLOAD_H + +#include <stdbool.h> +#include <sys/types.h> +#include <signal.h> +struct task; + +// ============================================================================ +// Native Offload — bypass emulation for selected guest binaries +// ============================================================================ +// +// When guest execve() matches a registered binary name, execution is +// intercepted and routed to either: +// 1. An in-process handler function (iOS + macOS) +// 2. A native host binary via posix_spawn (macOS only) +// +// The handler receives argc/argv (with guest paths translated to host paths) +// and pipe-backed stdio fds. Output written to stdout_fd/stderr_fd is +// forwarded through the guest TTY driver, so it appears in the terminal UI. +// +// --- Quick integration guide --- +// +// // 1. Define your handler (runs on guest thread, in-process) +// static int my_tool_main(int argc, char **argv, +// int stdin_fd, int stdout_fd, int stderr_fd) { +// dprintf(stdout_fd, "hello from native handler\n"); +// return 0; // exit code +// } +// +// // 2. Register it (call once at app startup, before guest runs) +// native_offload_add_handler("mytool", my_tool_main); +// +// // 3. Done — when guest runs `execve("/usr/bin/mytool", ...)`, +// // my_tool_main() is called instead of emulating the ELF binary. +// +// Notes for handler authors: +// - argv paths starting with '/' are auto-translated to host filesystem +// - CWD is set to the host equivalent of the guest's CWD +// - Use dprintf(stdout_fd, ...) and dprintf(stderr_fd, ...) for output +// - stdin_fd may be -1 if guest stdin is not backed by a real host fd +// - Return 0 for success, non-zero for failure (becomes guest exit code) +// - Handler runs on the guest thread; do_exit() is called after return +// +// macOS CLI also supports host binary offload: +// ish -n ffmpeg # auto-detect /opt/homebrew/bin/ffmpeg +// ish -n ffprobe=/usr/local/bin/ffprobe # explicit path +// +// ============================================================================ + +#define NATIVE_OFFLOAD_MAX 32 + +// Handler function signature. Called in-process on the guest thread. +// Receives translated argv (guest absolute paths → host paths) and +// pipe-backed stdio fds for output. +// Must return an exit code (0 = success). +typedef int (*native_handler_func)(int argc, char **argv, + int stdin_fd, int stdout_fd, int stderr_fd); + +// Register an in-process handler for a guest binary name. +// When guest execve() basename matches guest_name, handler is called +// instead of emulating the binary. Takes priority over host binary lookup. +// Returns 0 on success, -1 if registry is full. +int native_offload_add_handler(const char *guest_name, native_handler_func handler); + +// Register a host binary offload (macOS CLI only, uses posix_spawn). +// spec is "name" or "name=/host/path". Returns 0 on success. +int native_offload_add(const char *spec); + +// Check if a guest binary should be offloaded. +// Returns native host path, "[builtin]" for handler-only, or NULL. +const char *native_offload_lookup(const char *guest_path); + +// Execute the offloaded binary (handler or posix_spawn). +// Takes over the current guest task and calls do_exit(). Does not return +// on success. Returns negative errno on failure. +int native_offload_exec(const char *native_path, + const char *guest_file, + size_t argc, const char *argv, + const char *envp); + +// Forward a signal to the native process backing a proxy task. +// Returns true if the signal was forwarded. +bool native_offload_forward_signal(struct task *task, int sig); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/personality.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/personality.h new file mode 100644 index 0000000000..6ccd7c0f70 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/personality.h @@ -0,0 +1,6 @@ +#ifndef KERNEL_PERSONALITY_H +#define KERNEL_PERSONALITY_H + +#define ADDR_NO_RANDOMIZE_ 0x0040000 + +#endif /* KERNEL_PERSONALITY_H */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/pidfd.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/pidfd.c new file mode 100644 index 0000000000..38724f2fb4 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/pidfd.c @@ -0,0 +1,101 @@ +#include "kernel/calls.h" +#include "kernel/task.h" +#include "kernel/fs.h" +#include "fs/fd.h" +#include "fs/poll.h" +#include "util/sync.h" + +// pidfd_open(2): a file descriptor that refers to a process. poll() returns +// POLLIN once the process has terminated (become a zombie / been reaped). +// bun uses pidfd to reap the helper processes it spawns (e.g. the `git` it +// runs at startup); with the old ENOSYS stub it fell back to a path that +// deadlocked its worker pool under iSH. + +static struct fd_ops pidfd_ops; + +// Registry of live pidfds so process exit can wake any poller waiting on them. +static struct list pidfd_list = LIST_INITIALIZER(pidfd_list); +static lock_t pidfd_lock = LOCK_INITIALIZER; + +int_t sys_pidfd_open(pid_t_ pid, uint_t flags) { + STRACE("pidfd_open(%d, %#x)", pid, flags); + // Only PIDFD_NONBLOCK (== O_NONBLOCK) is defined; iSH pidfds never block on + // read anyway, so accept it and ignore. + if (flags & ~(O_NONBLOCK_)) + return _EINVAL; + + lock(&pids_lock); + struct task *task = pid_get_task(pid); + if (task == NULL) { + unlock(&pids_lock); + return _ESRCH; + } + // Linux restricts pidfd_open to thread-group leaders. + bool is_leader = (task->group != NULL && task->group->leader == task); + unlock(&pids_lock); + if (!is_leader) + return _EINVAL; + + struct fd *fd = adhoc_fd_create(&pidfd_ops); + if (fd == NULL) + return _ENOMEM; + fd->pidfd.pid = pid; + atomic_store_explicit(&fd->pidfd.exited, false, memory_order_relaxed); + fd->flags = flags; + + lock(&pidfd_lock); + list_add(&pidfd_list, &fd->pidfd_links); + unlock(&pidfd_lock); + + // Linux always creates pidfds with O_CLOEXEC (there is no way to get a + // non-cloexec pidfd from pidfd_open). PIDFD_NONBLOCK does not change that. + return f_install(fd, O_CLOEXEC_); +} + +static int pidfd_poll(struct fd *fd) { + // Lock-free: read the exit flag published by pidfd_notify_exit. Must NOT + // take pids_lock here — poll_wait() calls this with poll->lock held, and + // the exit path takes pids_lock then wakes pidfd pollers (which grabs + // poll->lock), so a pids_lock acquisition here would close an ABBA cycle. + return atomic_load_explicit(&fd->pidfd.exited, memory_order_acquire) + ? POLL_READ : 0; +} + +static int pidfd_close(struct fd *fd) { + lock(&pidfd_lock); + list_remove(&fd->pidfd_links); + unlock(&pidfd_lock); + return 0; +} + +// Called from the exit path when `pid` has become a zombie: wake any pidfd +// poller referencing it so a blocked poll()/epoll returns POLLIN. +void pidfd_notify_exit(pid_t_ pid) { + extern char *getenv(const char *); + int trace = getenv("ISH_PIDFD_TRACE") ? 1 : 0; + int matched = 0, total = 0; + lock(&pidfd_lock); + struct fd *fd; + list_for_each_entry(&pidfd_list, fd, pidfd_links) { + total++; + if (fd->pidfd.pid == pid) { + // Publish the exit before waking, so a poll that races the wakeup + // still observes POLL_READ. poll_wakeup takes fd->poll_lock and + // poll->lock but NOT pids_lock, so calling it here (under pids_lock + // via the exit path) does not reintroduce the ABBA — pidfd_poll no + // longer takes pids_lock. + atomic_store_explicit(&fd->pidfd.exited, true, memory_order_release); + poll_wakeup(fd, POLL_READ); + matched++; + } + } + unlock(&pidfd_lock); + if (trace) + fprintf(stderr, "[pidfd] notify_exit(pid=%d): %d/%d pidfds matched+woken\n", + pid, matched, total); +} + +static struct fd_ops pidfd_ops = { + .poll = pidfd_poll, + .close = pidfd_close, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/poll.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/poll.c new file mode 100644 index 0000000000..aa74895a66 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/poll.c @@ -0,0 +1,274 @@ +#include <string.h> +#include "debug.h" +#include "kernel/fs.h" +#include "fs/fd.h" +#include "fs/poll.h" +#include "kernel/calls.h" + +static int user_read_or_zero(addr_t addr, void *data, size_t size) { + if (addr == 0) + memset(data, 0, size); + else if (user_read(addr, data, size)) + return _EFAULT; + return 0; +} + +#define SELECT_READ (POLL_READ | POLL_HUP | POLL_ERR) +#define SELECT_WRITE (POLL_WRITE | POLL_ERR) +#define SELECT_EX (POLL_PRI) +struct select_context { + char *readfds; + char *writefds; + char *exceptfds; +}; +static int select_event_callback(void *context, int types, union poll_fd_info info) { + struct select_context *c = context; + if (types & SELECT_READ) + bit_set(info.fd, c->readfds); + if (types & SELECT_WRITE) + bit_set(info.fd, c->writefds); + if (types & SELECT_EX) + bit_set(info.fd, c->exceptfds); + if (!(types & (SELECT_READ | SELECT_WRITE | SELECT_EX))) + return 0; + return 1; +} + +static dword_t select_common(fd_t nfds, addr_t readfds_addr, addr_t writefds_addr, addr_t exceptfds_addr, struct timespec *timeout_addr, const char *name) { + size_t fdset_size = BITS_SIZE(nfds); + char readfds[fdset_size]; + if (user_read_or_zero(readfds_addr, readfds, fdset_size)) + return _EFAULT; + char writefds[fdset_size]; + if (user_read_or_zero(writefds_addr, writefds, fdset_size)) + return _EFAULT; + char exceptfds[fdset_size]; + if (user_read_or_zero(exceptfds_addr, exceptfds, fdset_size)) + return _EFAULT; + + STRACE("%s(%d, 0x%x, 0x%x, 0x%x, 0x%x {%lus %luns}) ", + name, nfds, readfds_addr, writefds_addr, exceptfds_addr, + timeout_addr, timeout_addr ? timeout_addr->tv_sec : 0, + timeout_addr ? timeout_addr->tv_nsec : 0); + + struct poll *poll = poll_create(); + if (IS_ERR(poll)) + return PTR_ERR(poll); + + for (fd_t i = 0; i < nfds; i++) { + int events = 0; + if (bit_test(i, readfds)) + events |= SELECT_READ; + if (bit_test(i, writefds)) + events |= SELECT_WRITE; + if (bit_test(i, exceptfds)) + events |= SELECT_EX; + if (events != 0) { + STRACE("%d{%s%s%s} ", i, + bit_test(i, readfds) ? "r" : "", + bit_test(i, writefds) ? "w" : "", + bit_test(i, exceptfds) ? "x" : ""); + struct fd *fd = f_get(i); + if (fd == NULL) { + poll_destroy(poll); + return _EBADF; + } + poll_add_fd(poll, fd, i, events, (union poll_fd_info) i); + } + } + STRACE("...\n"); + + memset(readfds, 0, fdset_size); + memset(writefds, 0, fdset_size); + memset(exceptfds, 0, fdset_size); + struct select_context context = {readfds, writefds, exceptfds}; + int err = poll_wait(poll, select_event_callback, &context, timeout_addr); + STRACE("%d end %s ", current->pid, name); + for (fd_t i = 0; i < nfds; i++) { + if (bit_test(i, readfds) || bit_test(i, writefds) || bit_test(i, exceptfds)) { + STRACE("%d{%s%s%s} ", i, + bit_test(i, readfds) ? "r" : "", + bit_test(i, writefds) ? "w" : "", + bit_test(i, exceptfds) ? "x" : ""); + } + } + poll_destroy(poll); + if (err < 0) + return err; + + if (readfds_addr && user_write(readfds_addr, readfds, fdset_size)) + return _EFAULT; + if (writefds_addr && user_write(writefds_addr, writefds, fdset_size)) + return _EFAULT; + if (exceptfds_addr && user_write(exceptfds_addr, exceptfds, fdset_size)) + return _EFAULT; + return err; +} + +dword_t sys_select(fd_t nfds, addr_t readfds_addr, addr_t writefds_addr, addr_t exceptfds_addr, addr_t timeout_addr) { + struct timespec timeout_ts = {}; + struct timespec *timeout_ts_addr = NULL; + if (timeout_addr != 0) { + struct timeval_ timeout_timeval; + if (user_get(timeout_addr, timeout_timeval)) + return _EFAULT; + timeout_ts = convert_timeval(timeout_timeval); + timeout_ts_addr = &timeout_ts; + } + // XXX we do not implement the Linux behavior of writing the timeout with remaining time here. + return select_common(nfds, readfds_addr, writefds_addr, exceptfds_addr, timeout_ts_addr, "select"); +} + +struct poll_context { + struct pollfd_ *polls; + struct fd **files; + int nfds; +}; +#define POLL_ALWAYS_LISTENING (POLL_ERR|POLL_HUP|POLL_NVAL) +static int poll_event_callback(void *context, int types, union poll_fd_info info) { + struct poll_context *c = context; + struct pollfd_ *polls = c->polls; + int nfds = c->nfds; + int res = 0; + for (int i = 0; i < nfds; i++) { + if (c->files[i] == info.ptr) { + polls[i].revents = types & (polls[i].events | POLL_ALWAYS_LISTENING); + res = 1; + } + } + return res; +} +dword_t sys_poll(addr_t fds, dword_t nfds, int_t timeout) { + STRACE("poll(0x%x, %d, %d)", fds, nfds, timeout); + struct pollfd_ polls[nfds]; + if (fds != 0 || nfds != 0) + if (user_read(fds, polls, sizeof(struct pollfd_) * nfds)) + return _EFAULT; + struct poll *poll = poll_create(); + if (IS_ERR(poll)) + return PTR_ERR(poll); + + for (unsigned i = 0; i < nfds; i++) + STRACE(" {%d, %#x}", polls[i].fd, polls[i].events); + STRACE("...\n"); + + struct fd *files[nfds]; + for (unsigned i = 0; i < nfds; i++) { + files[i] = f_get(polls[i].fd); + if (files[i] != NULL) + // FIXME it might have been closed by now by another thread + fd_retain(files[i]); + // clear revents, which is reused to mark whether a pollfd has been added or not + polls[i].revents = 0; + } + + // convert polls array into poll_add_fd calls + // FIXME this is quadratic + for (unsigned i = 0; i < nfds; i++) { + if (polls[i].fd < 0 || polls[i].revents) + continue; + + // if the same fd is listed more than once, merge the events bits together + int events = polls[i].events; + polls[i].revents = 1; + if (files[i] == NULL) + continue; + for (unsigned j = 0; j < nfds; j++) { + if (polls[j].revents) + continue; + if (files[i] == files[j]) { + events |= polls[j].events; + polls[j].revents = 1; + } + } + + poll_add_fd(poll, files[i], polls[i].fd, events | POLL_ALWAYS_LISTENING, (union poll_fd_info) (void *) files[i]); + } + + for (unsigned i = 0; i < nfds; i++) { + polls[i].revents = 0; + if (polls[i].fd >= 0 && files[i] == NULL) + polls[i].revents = POLL_NVAL; + } + struct poll_context context = {polls, files, nfds}; + struct timespec timeout_ts; + if (timeout >= 0) { + timeout_ts.tv_sec = timeout / 1000; + timeout_ts.tv_nsec = (timeout % 1000) * 1000000; + } + int res = poll_wait(poll, poll_event_callback, &context, timeout < 0 ? NULL : &timeout_ts); + poll_destroy(poll); + for (unsigned i = 0; i < nfds; i++) { + if (files[i] != NULL) + fd_close(files[i]); + } + STRACE("%d end poll", current->pid); + for (unsigned i = 0; i < nfds; i++) + STRACE(" {%d, %#x}", polls[i].fd, polls[i].revents); + + if (res < 0) + return res; + if (fds != 0 || nfds != 0) + if (user_write(fds, polls, sizeof(struct pollfd_) * nfds)) + return _EFAULT; + return res; +} + +dword_t sys_pselect(fd_t nfds, addr_t readfds_addr, addr_t writefds_addr, addr_t exceptfds_addr, addr_t timeout_addr, addr_t sigmask_addr) { + struct timespec_ timeout_timespec; + struct timespec timeout_ts; + struct timespec *timeout_ts_addr = NULL; + if (timeout_addr != 0) { + if (user_get(timeout_addr, timeout_timespec)) + return _EFAULT; + timeout_ts = convert_timespec(timeout_timespec); + timeout_ts_addr = &timeout_ts; + } + // a system call can only take 6 parameters, so the last two need to be passed as a pointer to a struct + struct { + addr_t mask_addr; + dword_t mask_size; + } sigmask; +#ifdef GUEST_ARM64 + struct { + uint64_t mask_addr; + uint64_t mask_size; + } sigmask64; + if (user_get(sigmask_addr, sigmask64)) + return _EFAULT; + sigmask.mask_addr = (addr_t) sigmask64.mask_addr; + sigmask.mask_size = (dword_t) sigmask64.mask_size; +#else + if (user_get(sigmask_addr, sigmask)) + return _EFAULT; +#endif + sigset_t_ mask; + + if (sigmask.mask_addr != 0) { + int err = user_get_sigset(sigmask.mask_addr, sigmask.mask_size, &mask); + if (err) + return err; + sigmask_set_temp(mask); + } + return select_common(nfds, readfds_addr, writefds_addr, exceptfds_addr, timeout_ts_addr, "pselect"); +} + +dword_t sys_ppoll(addr_t fds, dword_t nfds, addr_t timeout_addr, addr_t sigmask_addr, dword_t sigsetsize) { + int timeout = -1; + if (timeout_addr != 0) { + struct timespec_ timeout_timespec; + if (user_get(timeout_addr, timeout_timespec)) + return _EFAULT; + timeout = timeout_timespec.sec * 1000 + timeout_timespec.nsec / 1000000; + } + + sigset_t_ mask; + if (sigmask_addr != 0) { + int err = user_get_sigset(sigmask_addr, sigsetsize, &mask); + if (err) + return err; + sigmask_set_temp(mask); + } + + return sys_poll(fds, nfds, timeout); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/ptrace.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/ptrace.c new file mode 100644 index 0000000000..fe4ff8b13d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/ptrace.c @@ -0,0 +1,273 @@ +#include "ptrace.h" +#include "kernel/calls.h" +#include "kernel/errno.h" +#include "kernel/signal.h" +#include "task.h" +#include <string.h> + +// Returns stopped child with the given pid, locked with the ptrace lock +static struct task *find_child(pid_t_ pid) { + struct task *child = NULL; + list_for_each_entry(¤t->children, child, siblings) { + if (child->pid == pid) { + lock(&child->ptrace.lock); + if (child->ptrace.stopped) { + goto found; + } + + unlock(&child->ptrace.lock); + } + } + child = NULL; +found: + return child; +} + +#if defined(GUEST_ARM64) +// ARM64 ptrace register access - stub implementation +// TODO: Implement ARM64 ptrace register access +static void get_user_regs(struct cpu_state *cpu, struct user_regs_struct_ *user_regs_) { + (void)cpu; + memset(user_regs_, 0, sizeof(*user_regs_)); +} + +static void set_user_regs(struct cpu_state *cpu, struct user_regs_struct_ *user_regs_) { + (void)cpu; + (void)user_regs_; +} +#else +// Ensure stopped, ptrace locked, etc. before calling this +static void get_user_regs(struct cpu_state *cpu, struct user_regs_struct_ *user_regs_) { + user_regs_->ebx = cpu->ebx; + user_regs_->ecx = cpu->ecx; + user_regs_->edx = cpu->edx; + user_regs_->esi = cpu->esi; + user_regs_->edi = cpu->edi; + user_regs_->ebp = cpu->ebp; + user_regs_->eax = cpu->eax; +// user_regs_->xds = cpu->xds; +// user_regs_->xes = cpu->xes; +// user_regs_->xfs = cpu->xfs; +// user_regs_->xgs = cpu->xgs; + user_regs_->orig_eax = cpu->eax; + user_regs_->eip = cpu->eip; +// user_regs_->xcs = cpu->xcs; + user_regs_->eflags = cpu->eflags; + user_regs_->esp = cpu->esp; +// user_regs_->xss = cpu->xss; +} + +// Ensure stopped, ptrace locked, etc. before calling this +static void set_user_regs(struct cpu_state *cpu, struct user_regs_struct_ *user_regs_) { + cpu->ebx = user_regs_->ebx; + cpu->ecx = user_regs_->ecx; + cpu->edx = user_regs_->edx; + cpu->esi = user_regs_->esi; + cpu->edi = user_regs_->edi; + cpu->ebp = user_regs_->ebp; + cpu->eax = user_regs_->eax; +// cpu->xds = user_regs_->xds; +// cpu->xes = user_regs_->xes; +// cpu->xfs = user_regs_->xfs; +// cpu->xgs = user_regs_->xgs; +// cpu->eax = user_regs_->orig_eax; + cpu->eip = user_regs_->eip; +// cpu->xcs = user_regs_->xcs; + cpu->eflags = user_regs_->eflags; + cpu->esp = user_regs_->esp; +// cpu->xss = user_regs_->xss; +} +#endif + +dword_t sys_ptrace(dword_t request, dword_t pid, addr_t addr, addr_t data) { + switch (request) { + case PTRACE_TRACEME_: + STRACE("ptrace(PTRACE_TRACEME, %d, %#x, %#x)", pid, addr, data); + current->ptrace.traced = true; + return 0; + + case PTRACE_PEEKTEXT_: + case PTRACE_PEEKDATA_: { + STRACE("ptrace(PTRACE_PEEKDATA, %d, %#x, %#x)", pid, addr, data); + dword_t peek; + struct task *child = find_child(pid); + if (!child) return _EPERM; + + if (user_get_task(child, addr, peek)) { + unlock(&child->ptrace.lock); + return _EFAULT; + } else if (user_put(data, peek)) { + unlock(&child->ptrace.lock); + return _EFAULT; + } + unlock(&child->ptrace.lock); + + return 0; + } + + case PTRACE_PEEKUSER_: { + STRACE("ptrace(PTRACE_PEEKUSER, %d, %#x, %#x)", pid, addr, data); + dword_t peek; + struct task *child = find_child(pid); + if (!child) return _EPERM; + + struct user_ user_ = {}; + get_user_regs(&child->cpu, &user_.user_regs); + + if (addr & (sizeof(peek) - 1) || addr >= sizeof(struct user_)) + return _EIO; + + memcpy(&peek, (char *)&user_ + addr, sizeof(peek)); + if (user_put(data, peek)) { + unlock(&child->ptrace.lock); + return _EFAULT; + } + unlock(&child->ptrace.lock); + + return 0; + } + + case PTRACE_POKETEXT_: + case PTRACE_POKEDATA_: { + STRACE("ptrace(PTRACE_POKEDATA, %d, %#x, %#x)", pid, addr, data); + struct task *child = find_child(pid); + if (!child) return _EPERM; + + if (user_write_task_ptrace(child, addr, &data, sizeof(data))) { + unlock(&child->ptrace.lock); + return _EFAULT; + } + unlock(&child->ptrace.lock); + + return 0; + } + + case PTRACE_CONT_: { + STRACE("ptrace(PTRACE_CONT, %d, %#x, %#x)", pid, addr, data); + struct task *child = find_child(pid); + if (!child) return _EPERM; + +#if !defined(GUEST_ARM64) + child->cpu.tf = false; +#endif + child->ptrace.stopped = false; + notify(&child->ptrace.cond); + unlock(&child->ptrace.lock); + + return 0; + } + + case PTRACE_KILL_: { + STRACE("ptrace(PTRACE_KILL, %d, %#x, %#x)", pid, addr, data); + struct task *child = find_child(pid); + if (!child) return _EPERM; + + child->ptrace.stopped = false; + send_signal(child, SIGKILL_, SIGINFO_NIL); + unlock(&child->ptrace.lock); + + return 0; + } + + case PTRACE_SINGLESTEP_: { + STRACE("ptrace(PTRACE_SINGLESTEP, %d, %#x, %#x)", pid, addr, data); + struct task *child = find_child(pid); + if (!child) return _EPERM; + +#if !defined(GUEST_ARM64) + child->cpu.tf = true; +#endif + child->ptrace.stopped = false; + notify(&child->ptrace.cond); + unlock(&child->ptrace.lock); + + return 0; + } + + case PTRACE_GETREGS_: { + STRACE("ptrace(PTRACE_GETREGS, %d, %#x, %#x)", pid, addr, data); + struct task *child = find_child(pid); + if (!child) return _EPERM; + + struct user_regs_struct_ user_regs_ = {}; + get_user_regs(&child->cpu, &user_regs_); + if (user_put(data, user_regs_)) { + unlock(&child->ptrace.lock); + return _EFAULT; + } + unlock(&child->ptrace.lock); + + return 0; + } + + case PTRACE_SETREGS_: { + STRACE("ptrace(PTRACE_SETREGS, %d, %#x, %#x)", pid, addr, data); + struct task *child = find_child(pid); + if (!child) return _EPERM; + + struct user_regs_struct_ user_regs_; + if (user_get(data, user_regs_)) { + return _EFAULT; + } else { + set_user_regs(&child->cpu, &user_regs_); + } + unlock(&child->ptrace.lock); + + return 0; + } + + // GDB needs the fpregs functions to exist if you want to evaluate things + case PTRACE_GETFPREGS_: { + STRACE("ptrace(PTRACE_GETFPREGS, %d, %#x, %#x)", pid, addr, data); + struct task *child = find_child(pid); + if (!child) return _EPERM; + + struct user_fpregs_struct_ user_fpregs_ = {}; + if (user_put(data, user_fpregs_)) { + unlock(&child->ptrace.lock); + return _EFAULT; + } + // TODO get float point registers + unlock(&child->ptrace.lock); + + return 0; + } + + case PTRACE_SETFPREGS_: { + STRACE("ptrace(PTRACE_SETFPREGS, %d, %#x, %#x)", pid, addr, data); + struct task *child = find_child(pid); + if (!child) return _EPERM; + + struct user_fpregs_struct_ user_fpregs_; + if (user_get(data, user_fpregs_)) { + return _EFAULT; + } else { + // TODO set floating point registers + } + unlock(&child->ptrace.lock); + + return 0; + } + + case PTRACE_SETOPTIONS_: + STRACE("ptrace(PTRACE_SETOPTIONS, %d, %#x, %#x)", pid, addr, data); + return _EINVAL; + + case PTRACE_GETSIGINFO_: { + STRACE("ptrace(PTRACE_GETSIGINFO, %d, %#x, %#x)", pid, addr, data); + struct task *child = find_child(pid); + if (!child) return _EPERM; + + if (data && user_put(data, child->ptrace.info)) { + return _EFAULT; + } + unlock(&child->ptrace.lock); + + return 0; + } + + default: + STRACE("ptrace(%d, %d, %#x, %#x)", request, pid, addr, data); + return _EPERM; + } +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/ptrace.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/ptrace.h new file mode 100644 index 0000000000..33616450b1 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/ptrace.h @@ -0,0 +1,62 @@ +#ifndef KERNEL_PTRACE_H +#define KERNEL_PTRACE_H + +#include "misc.h" + +#define PTRACE_TRACEME_ 0 +#define PTRACE_PEEKTEXT_ 1 +#define PTRACE_PEEKDATA_ 2 +#define PTRACE_PEEKUSER_ 3 +#define PTRACE_POKETEXT_ 4 +#define PTRACE_POKEDATA_ 5 +#define PTRACE_CONT_ 7 +#define PTRACE_KILL_ 8 +#define PTRACE_SINGLESTEP_ 9 +#define PTRACE_GETREGS_ 12 +#define PTRACE_SETREGS_ 13 +#define PTRACE_GETFPREGS_ 14 +#define PTRACE_SETFPREGS_ 15 +#define PTRACE_SETOPTIONS_ 0x4200 +#define PTRACE_GETSIGINFO_ 0x4202 + +#define PTRACE_EVENT_FORK_ 1 + +struct user_regs_struct_ { + dword_t ebx; + dword_t ecx; + dword_t edx; + dword_t esi; + dword_t edi; + dword_t ebp; + dword_t eax; + dword_t xds; + dword_t xes; + dword_t xfs; + dword_t xgs; + dword_t orig_eax; + dword_t eip; + dword_t xcs; + dword_t eflags; + dword_t esp; + dword_t xss; +}; + +struct user_fpregs_struct_ { + dword_t cwd; + dword_t swd; + dword_t twd; + dword_t fip; + dword_t fcs; + dword_t foo; + dword_t fos; + dword_t st_space[20]; +}; + +struct user_ { + struct user_regs_struct_ user_regs; + char padding[286 - sizeof(struct user_regs_struct_)]; +}; + +dword_t sys_ptrace(dword_t request, dword_t pid, addr_t addr, addr_t data); + +#endif /* KERNEL_PTRACE_H */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/random.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/random.c new file mode 100644 index 0000000000..5230fdb087 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/random.c @@ -0,0 +1,23 @@ +#include <fcntl.h> +#include "kernel/calls.h" +#include "platform/platform.h" + +int get_random(char *buf, size_t len) { + return platform_get_random_bytes(buf, len); +} + +dword_t sys_getrandom(addr_t buf_addr, dword_t len, dword_t UNUSED(flags)) { + if (len > 1 << 20) + return _EIO; + char *buf = malloc(len); + if (get_random(buf, len) != 0) { + free(buf); + return _EIO; + } + if (user_write(buf_addr, buf, len)) { + free(buf); + return _EFAULT; + } + free(buf); + return len; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/random.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/random.h new file mode 100644 index 0000000000..b65ecea2ee --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/random.h @@ -0,0 +1,8 @@ +#ifndef KERNEL_RANDOM_H +#define KERNEL_RANDOM_H + +#include <stdlib.h> + +int get_random(char *buf, size_t len); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/resource.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/resource.c new file mode 100644 index 0000000000..f7757a568a --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/resource.c @@ -0,0 +1,286 @@ +#include <limits.h> +#include <string.h> +#include "kernel/calls.h" +#include "platform/platform.h" + +static bool resource_valid(int resource) { + return resource >= 0 && resource < RLIMIT_NLIMITS_; +} + +static int rlimit_get(struct task *task, int resource, struct rlimit_ *limit) { + if (!resource_valid(resource)) + return _EINVAL; + struct tgroup *group = task->group; + lock(&group->lock); + *limit = group->limits[resource]; + unlock(&group->lock); + return 0; +} + +static int rlimit_set(struct task *task, int resource, struct rlimit_ limit) { + if (!resource_valid(resource)) + return _EINVAL; + struct tgroup *group = task->group; + lock(&group->lock); + group->limits[resource] = limit; + unlock(&group->lock); + return 0; +} + +rlim_t_ rlimit(int resource) { + struct rlimit_ limit; + if (rlimit_get(current, resource, &limit) != 0) + die("invalid resource %d", resource); + return limit.cur; +} + +static int do_getrlimit32(int resource, struct rlimit32_ *rlimit32) { + STRACE("getlimit(%d)", resource); + struct rlimit_ rlimit; + int err = rlimit_get(current, resource, &rlimit); + if (err < 0) + return err; + STRACE(" {cur=%#x, max=%#x}", rlimit.cur, rlimit.max); + + rlimit32->max = rlimit.max; + rlimit32->cur = rlimit.cur; + return 0; +} + +dword_t sys_getrlimit32(dword_t resource, addr_t rlim_addr) { + struct rlimit32_ rlimit; + int err = do_getrlimit32(resource, &rlimit); + if (err < 0) + return err; + if (user_put(rlim_addr, rlimit)) + return _EFAULT; + return 0; +} + +dword_t sys_old_getrlimit32(dword_t resource, addr_t rlim_addr) { + struct rlimit32_ rlimit; + int err = do_getrlimit32(resource, &rlimit); + if (err < 0) + return err; + + // This version of the call is for programs that aren't aware of rlim_t + // being 64 bit. RLIM_INFINITY looks like -1 when truncated to 32 bits. + if (rlimit.cur > INT_MAX) + rlimit.cur = INT_MAX; + if (rlimit.max > INT_MAX) + rlimit.max = INT_MAX; + + if (user_put(rlim_addr, rlimit)) + return _EFAULT; + return 0; +} + +static int check_setrlimit(int resource, struct rlimit_ new_limit) { + if (superuser()) + return 0; + struct rlimit_ old_limit; + int err = rlimit_get(current, resource, &old_limit); + if (err < 0) + return err; + if (new_limit.max > old_limit.max) + return _EPERM; + return 0; +} + +dword_t sys_setrlimit32(dword_t resource, addr_t rlim_addr) { + struct rlimit_ rlimit; + if (user_get(rlim_addr, rlimit)) + return _EFAULT; + STRACE("setrlimit(%d, {cur=%#x, max=%#x})", resource, rlimit.cur, rlimit.max); + int err = check_setrlimit(resource, rlimit); + if (err < 0) + return err; + return rlimit_set(current, resource, rlimit); +} + +// 64-bit getrlimit/setrlimit for ARM64 (struct rlimit with 64-bit cur/max) +dword_t sys_getrlimit64(dword_t resource, addr_t rlim_addr) { + STRACE("getrlimit64(%d)", resource); + struct rlimit_ rlimit; + int err = rlimit_get(current, resource, &rlimit); + if (err < 0) + return err; + STRACE(" {cur=%#llx, max=%#llx}", (unsigned long long)rlimit.cur, (unsigned long long)rlimit.max); + if (user_put(rlim_addr, rlimit)) + return _EFAULT; + return 0; +} + +dword_t sys_setrlimit64(dword_t resource, addr_t rlim_addr) { + struct rlimit_ rlimit; + if (user_get(rlim_addr, rlimit)) + return _EFAULT; + STRACE("setrlimit64(%d, {cur=%#llx, max=%#llx})", resource, (unsigned long long)rlimit.cur, (unsigned long long)rlimit.max); + int err = check_setrlimit(resource, rlimit); + if (err < 0) + return err; + return rlimit_set(current, resource, rlimit); +} + +dword_t sys_prlimit64(pid_t_ pid, dword_t resource, addr_t new_limit_addr, addr_t old_limit_addr) { + STRACE("prlimit64(%d, %d)", pid, resource); + if (pid != 0) + return _EINVAL; + + if (old_limit_addr != 0) { + struct rlimit_ rlimit; + int err = rlimit_get(current, resource, &rlimit); + if (err < 0) + return err; + STRACE(" old={cur=%#x, max=%#x}", rlimit.cur, rlimit.max); + if (user_put(old_limit_addr, rlimit)) + return _EFAULT; + } + + if (new_limit_addr != 0) { + struct rlimit_ rlimit; + if (user_get(new_limit_addr, rlimit)) + return _EFAULT; + STRACE(" new={cur=%#x, max=%#x}", rlimit.cur, rlimit.max); + int err = check_setrlimit(resource, rlimit); + if (err < 0) + return err; + return rlimit_set(current, resource, rlimit); + } + return 0; +} + +struct rusage_ rusage_get_current() { + // only the time fields are currently implemented + struct platform_thread_cpu_usage usage = platform_get_thread_cpu_usage(); + return (struct rusage_) { + .utime.sec = usage.user_sec, + .utime.usec = usage.user_usec, + .stime.sec = usage.system_sec, + .stime.usec = usage.system_usec, + }; +} + +static void timeval_add(struct timeval_ *dst, struct timeval_ *src) { + dst->sec += src->sec; + dst->usec += src->usec; + if (dst->usec >= 1000000) { + dst->usec -= 1000000; + dst->sec++; + } +} + +void rusage_add(struct rusage_ *dst, struct rusage_ *src) { + timeval_add(&dst->utime, &src->utime); + timeval_add(&dst->stime, &src->stime); +} + +dword_t sys_getrusage(dword_t who, addr_t rusage_addr) { + struct rusage_ rusage; + switch (who) { + case RUSAGE_SELF_: + rusage = rusage_get_current(); + break; + case RUSAGE_CHILDREN_: + lock(¤t->group->lock); + rusage = current->group->children_rusage; + unlock(¤t->group->lock); + break; + default: + return _EINVAL; + } + if (user_put(rusage_addr, rusage)) + return _EFAULT; + return 0; +} + +int_t sys_sched_getaffinity(pid_t_ pid, dword_t cpusetsize, addr_t cpuset_addr) { + STRACE("sched_getaffinity(%d, %d, %#x)", pid, cpusetsize, cpuset_addr); + if (pid != 0) { + lock(&pids_lock); + struct task *task = pid_get_task(pid); + unlock(&pids_lock); + if (task == NULL) + return _ESRCH; + } + + unsigned cpus = PLATFORM_GUEST_CPU_COUNT; + char cpuset[(PLATFORM_GUEST_CPU_COUNT + 7) / 8]; + if (cpusetsize < sizeof(cpuset)) + return _EINVAL; + memset(cpuset, 0, sizeof(cpuset)); + for (unsigned i = 0; i < cpus; i++) + bit_set(i, cpuset); + if (user_write(cpuset_addr, cpuset, sizeof(cpuset))) + return _EFAULT; + // return the number of bytes written + return sizeof(cpuset); +} +int_t sys_sched_setaffinity(pid_t_ UNUSED(pid), dword_t UNUSED(cpusetsize), addr_t UNUSED(cpuset_addr)) { + // meh + return 0; +} + +int_t sys_getcpu(addr_t cpu_addr, addr_t node_addr, addr_t UNUSED(tcache_addr)) { + STRACE("getcpu(%#llx, %#llx)", (unsigned long long)cpu_addr, (unsigned long long)node_addr); + dword_t cpu = 0; + dword_t node = 0; + if (cpu_addr && user_put(cpu_addr, cpu)) + return _EFAULT; + if (node_addr && user_put(node_addr, node)) + return _EFAULT; + return 0; +} + +int_t sys_getpriority(int_t which, pid_t_ who) { + STRACE("getpriority(%d, %d)", which, who); + return 20; +} +int_t sys_setpriority(int_t which, pid_t_ who, int_t prio) { + STRACE("setpriority(%d, %d, %d)", which, who, prio); + return 0; +} + +// realtime scheduling stubs +int_t sys_sched_getparam(pid_t_ UNUSED(pid), addr_t param_addr) { + int_t sched_priority = 0; + if (user_put(param_addr, sched_priority)) + return _EFAULT; + return 0; +} +int64_t sys_sched_setparam(pid_t_ UNUSED(pid), addr_t param_addr) { + int_t sched_priority; + if (user_get(param_addr, sched_priority)) + return _EFAULT; + // iSH does not emulate guest scheduling priority, but many managed + // runtimes treat sched_setparam failure as fatal during worker setup. + // Accept readable requests as a no-op compatibility success. + return 0; +} +#define SCHED_OTHER_ 0 +int_t sys_sched_getscheduler(pid_t_ UNUSED(pid)) { + return SCHED_OTHER_; +} +int64_t sys_sched_setscheduler(pid_t_ UNUSED(pid), int_t UNUSED(policy), addr_t param_addr) { + int_t sched_priority; + if (user_get(param_addr, sched_priority)) + return _EFAULT; + // Same compatibility policy as sched_setparam: scheduling policy/priority + // changes are not represented internally, but should not abort runtimes + // that merely try to tune helper threads. + return 0; +} + +int_t sys_sched_get_priority_max(int_t policy) { + STRACE("sched_get_priority_max(%d)", policy); + if (policy == 0) + return 0; + return _EINVAL; +} + +int_t sys_ioprio_get(int_t UNUSED(which), int_t UNUSED(who), int_t UNUSED(ioprio)) { + return 0; +} +int_t sys_ioprio_set(int_t UNUSED(which), int_t UNUSED(who), int_t UNUSED(ioprio)) { + return 0; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/resource.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/resource.h new file mode 100644 index 0000000000..0219164cde --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/resource.h @@ -0,0 +1,86 @@ +#ifndef RESOURCE_H +#define RESOURCE_H +#include "kernel/time.h" + +typedef qword_t rlim_t_; +typedef dword_t rlim32_t_; +#define RLIM_INFINITY_ ((rlim_t_) -1) + +struct rlimit_ { + rlim_t_ cur; + rlim_t_ max; +}; + +struct rlimit32_ { + rlim32_t_ cur; + rlim32_t_ max; +}; + +#define RLIMIT_CPU_ 0 +#define RLIMIT_FSIZE_ 1 +#define RLIMIT_DATA_ 2 +#define RLIMIT_STACK_ 3 +#define RLIMIT_CORE_ 4 +#define RLIMIT_RSS_ 5 +#define RLIMIT_NPROC_ 6 +#define RLIMIT_NOFILE_ 7 +#define RLIMIT_MEMLOCK_ 8 +#define RLIMIT_AS_ 9 +#define RLIMIT_LOCKS_ 10 +#define RLIMIT_SIGPENDING_ 11 +#define RLIMIT_MSGQUEUE_ 12 +#define RLIMIT_NICE_ 13 +#define RLIMIT_RTPRIO_ 14 +#define RLIMIT_RTTIME_ 15 +#define RLIMIT_NLIMITS_ 16 + +dword_t sys_getrlimit32(dword_t resource, addr_t rlim_addr); +dword_t sys_setrlimit32(dword_t resource, addr_t rlim_addr); +dword_t sys_getrlimit64(dword_t resource, addr_t rlim_addr); +dword_t sys_setrlimit64(dword_t resource, addr_t rlim_addr); +dword_t sys_prlimit64(pid_t_ pid, dword_t resource, addr_t new_limit_addr, addr_t old_limit_addr); +dword_t sys_old_getrlimit32(dword_t resource, addr_t rlim_addr); + +rlim_t_ rlimit(int resource); + +struct rusage_ { + struct timeval_ utime; + struct timeval_ stime; + dword_t maxrss; + dword_t ixrss; + dword_t idrss; + dword_t isrss; + dword_t minflt; + dword_t majflt; + dword_t nswap; + dword_t inblock; + dword_t oublock; + dword_t msgsnd; + dword_t msgrcv; + dword_t nsignals; + dword_t nvcsw; + dword_t nivcsw; +}; + +struct rusage_ rusage_get_current(void); +void rusage_add(struct rusage_ *dst, struct rusage_ *src); +#define RUSAGE_SELF_ 0 +#define RUSAGE_CHILDREN_ -1 +dword_t sys_getrusage(dword_t who, addr_t rusage_addr); + +int_t sys_sched_getaffinity(pid_t_ pid, dword_t cpusetsize, addr_t cpuset_addr); +int_t sys_sched_setaffinity(pid_t_ pid, dword_t cpusetsize, addr_t cpuset_addr); +int_t sys_getcpu(addr_t cpu_addr, addr_t node_addr, addr_t tcache_addr); +int_t sys_getpriority(int_t which, pid_t_ who); +int_t sys_setpriority(int_t which, pid_t_ who, int_t prio); + +int_t sys_sched_getparam(pid_t_ pid, addr_t param_addr); +int64_t sys_sched_setparam(pid_t_ pid, addr_t param_addr); +int_t sys_sched_getscheduler(pid_t_ UNUSED(pid)); +int64_t sys_sched_setscheduler(pid_t_ UNUSED(pid), int_t policy, addr_t param_addr); +int_t sys_sched_get_priority_max(int_t policy); + +int_t sys_ioprio_set(int_t UNUSED(which), int_t UNUSED(who), int_t UNUSED(ioprio)); +int_t sys_ioprio_get(int_t UNUSED(which), int_t UNUSED(who), int_t UNUSED(ioprio)); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/signal.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/signal.c new file mode 100644 index 0000000000..df4ce10b09 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/signal.c @@ -0,0 +1,1307 @@ +#include "debug.h" +#include <string.h> +#include <signal.h> +#include <stdio.h> +#include "kernel/calls.h" +#include "kernel/signal.h" +#include "kernel/task.h" +#include "kernel/native_offload.h" +#include "kernel/vdso.h" +#include "emu/interrupt.h" + +#if is_gcc(9) +#pragma GCC diagnostic ignored "-Waddress-of-packed-member" +#endif + + +int xsave_extra = 0; +int fxsave_extra = 0; +static void sigmask_set(sigset_t_ set); +static void altstack_to_user(struct task *task, struct stack_t_ *user_stack); + +struct signalfd_siginfo_ { + uint32_t signo; + int32_t err; + int32_t code; + uint32_t pid; + uint32_t uid; + uint32_t fd; + uint32_t tid; + uint32_t band; + uint32_t overrun; + uint32_t trapno; + int32_t status; + int32_t int_; + uint64_t ptr; + uint64_t utime; + uint64_t stime; + uint64_t addr; + uint16_t addr_lsb; + uint8_t pad[46]; +}; + +_Static_assert(sizeof(struct signalfd_siginfo_) == 128, "signalfd_siginfo size"); + +static ssize_t signalfd_read(struct fd *fd, void *buf, size_t bufsize); +static int signalfd_close(struct fd *fd); +static int signalfd_getflags(struct fd *fd); +static int signalfd_setflags(struct fd *fd, dword_t flags); +static const struct fd_ops signalfd_ops = { + .read = signalfd_read, + .close = signalfd_close, + .getflags = signalfd_getflags, + .setflags = signalfd_setflags, +}; +static bool is_on_altstack(addr_t sp, struct task *task); + +static int signal_is_blockable(int sig) { + return sig != SIGKILL_ && sig != SIGSTOP_; +} + +#define UNBLOCKABLE_MASK (sig_mask(SIGKILL_) | sig_mask(SIGSTOP_)) + +#define SIGNAL_IGNORE 0 +#define SIGNAL_KILL 1 +#define SIGNAL_CALL_HANDLER 2 +#define SIGNAL_STOP 3 + +static int signal_action(struct sighand *sighand, int sig) { + if (signal_is_blockable(sig)) { + struct sigaction_ *action = &sighand->action[sig]; + if (action->handler == SIG_IGN_) + return SIGNAL_IGNORE; + if (action->handler != SIG_DFL_) + return SIGNAL_CALL_HANDLER; + } + + switch (sig) { + case SIGURG_: case SIGCONT_: case SIGCHLD_: + case SIGIO_: case SIGWINCH_: + return SIGNAL_IGNORE; + + case SIGSTOP_: case SIGTSTP_: case SIGTTIN_: case SIGTTOU_: + return SIGNAL_STOP; + + default: + return SIGNAL_KILL; + } +} + +// Real-time signals (>= SIGRTMIN) queue: each delivery is a distinct instance +// and must not be coalesced. Standard signals coalesce (one pending bit). +// JSC's thread resume path uses RT signals (RTMIN/RT_1/RT_2); dropping a +// duplicate as "already pending" loses a resume and wedges the GC handshake. +#define SIGRTMIN_ 32 +static void deliver_signal_unlocked(struct task *task, int sig, struct siginfo_ info) { + if (sig < SIGRTMIN_ && sigset_has(task->pending, sig)) + return; + + sigset_add(&task->pending, sig); + struct sigqueue *sigqueue = malloc(sizeof(struct sigqueue)); + sigqueue->info = info; + sigqueue->info.sig = sig; + list_add_tail(&task->queue, &sigqueue->queue); + + if (sigset_has(task->blocked & ~task->waiting, sig) && signal_is_blockable(sig)) { + notify(&task->pause); + return; + } + + if (task != current) { + pthread_kill(task->thread, SIGUSR1); + + // wake up any pthread condition waiters + // actual madness, I hope to god it's correct + // must release the sighand lock while going insane, to avoid a deadlock + unlock(&task->sighand->lock); + // Wake up the target thread's condvar wait. + // We don't acquire waiting_lock (the associated mutex) because: + // 1. It may be held by the target thread inside pthread_cond_wait, + // and spinning on it blocks the condvar from returning. + // 2. pthread_cond_broadcast() is safe without the mutex — worst case + // is a spurious wakeup, which wait_for() handles via re-checking. + lock(&task->waiting_cond_lock); + if (task->waiting_cond != NULL) + notify(task->waiting_cond); + unlock(&task->waiting_cond_lock); + lock(&task->sighand->lock); + } +} + +void deliver_signal(struct task *task, int sig, struct siginfo_ info) { + if (task->sighand == NULL) + return; + lock(&task->sighand->lock); + deliver_signal_unlocked(task, sig, info); + unlock(&task->sighand->lock); + cpu_poke(&task->cpu); +} + +void send_signal(struct task *task, int sig, struct siginfo_ info) { + // signal zero is for testing whether a process exists + if (sig == 0) + return; + if (task->zombie || task->exiting) + return; +#ifdef GUEST_ARM64 + extern volatile bool g_trace_faults; + if (g_trace_faults && + (sig == SIGTRAP_ || sig == SIGABRT_ || sig == SIGILL_ || sig == SIGSEGV_ || sig == SIGBUS_)) + fprintf(stderr, "SIGNAL_TRACE: sig=%d pc=0x%llx pid=%d\n", + sig, (unsigned long long)task->cpu.pc, task->pid); +#endif + + // Native offload: forward signal to the host native process + if (native_offload_forward_signal(task, sig)) + return; + + struct sighand *sighand = task->sighand; + if (sighand == NULL) + return; + lock(&sighand->lock); + if (signal_action(sighand, sig) != SIGNAL_IGNORE) { + deliver_signal_unlocked(task, sig, info); + // Poke the target CPU so it exits the JIT loop at the next gadget + // boundary instead of waiting for INT_TIMER (up to 1024 cycles). + // This reduces signal delivery latency from ~1024 to ~1 gadget. + cpu_poke(&task->cpu); + } + unlock(&sighand->lock); + + if (sig == SIGCONT_ || sig == SIGKILL_) { + lock(&task->group->lock); + task->group->stopped = false; + notify(&task->group->stopped_cond); + unlock(&task->group->lock); + } +} + +bool try_self_signal(int sig) { + assert(sig == SIGTTIN_ || sig == SIGTTOU_); + + struct sighand *sighand = current->sighand; + lock(&sighand->lock); + bool can_send = signal_action(sighand, sig) != SIGNAL_IGNORE && + !sigset_has(current->blocked, sig); + if (can_send) + deliver_signal_unlocked(current, sig, SIGINFO_NIL); + unlock(&sighand->lock); + return can_send; +} + +int send_group_signal(dword_t pgid, int sig, struct siginfo_ info) { + lock(&pids_lock); + struct pid *pid = pid_get(pgid); + if (pid == NULL) { + unlock(&pids_lock); + return _ESRCH; + } + struct tgroup *tgroup; + list_for_each_entry(&pid->pgroup, tgroup, pgroup) { + send_signal(tgroup->leader, sig, info); + } + unlock(&pids_lock); + return 0; +} + +static addr_t sigreturn_trampoline(const char *name) { + addr_t sigreturn_addr = vdso_symbol(name); + if (sigreturn_addr == 0) { +#if defined(GUEST_ARM64) + return 0; +#else + die("sigreturn not found in vdso, this should never happen"); +#endif + } + return current->mm->vdso + sigreturn_addr; +} + +int sigset_size_valid(dword_t size) { +#if defined(GUEST_ARM64) + return size >= sizeof(sigset_t_) && (size % sizeof(sigset_t_) == 0); +#else + return size == sizeof(sigset_t_); +#endif +} + +int user_get_sigset(addr_t addr, dword_t size, sigset_t_ *out) { + if (!sigset_size_valid(size)) + return _EINVAL; +#if defined(GUEST_ARM64) + uint64_t word = 0; + if (user_read(addr, &word, sizeof(word))) + return _EFAULT; + *out = (sigset_t_) word; + return 0; +#else + if (user_get(addr, *out)) + return _EFAULT; + return 0; +#endif +} + +int user_put_sigset(addr_t addr, dword_t size, sigset_t_ set) { + if (!sigset_size_valid(size)) + return _EINVAL; +#if defined(GUEST_ARM64) + uint64_t word = (uint64_t) set; + if (user_write(addr, &word, sizeof(word))) + return _EFAULT; + dword_t remaining = size - sizeof(word); + addr_t pos = addr + sizeof(word); + static const byte_t zeros[16] = {0}; + while (remaining > 0) { + dword_t chunk = remaining > sizeof(zeros) ? sizeof(zeros) : remaining; + if (user_write(pos, zeros, chunk)) + return _EFAULT; + pos += chunk; + remaining -= chunk; + } + return 0; +#else + if (user_put(addr, set)) + return _EFAULT; + return 0; +#endif +} + +#if defined(GUEST_ARM64) +struct sigaction_arm64_kernel { + uint64_t handler; + uint64_t flags; + uint64_t restorer; + uint64_t mask[1]; +}; + +static int user_get_sigaction_arm64(addr_t addr, dword_t sigset_size, struct sigaction_ *out) { + uint64_t handler = 0; + uint64_t flags = 0; + uint64_t restorer = 0; + if (user_read(addr + offsetof(struct sigaction_arm64_kernel, handler), &handler, sizeof(handler))) + return _EFAULT; + if (user_read(addr + offsetof(struct sigaction_arm64_kernel, flags), &flags, sizeof(flags))) + return _EFAULT; + if (user_read(addr + offsetof(struct sigaction_arm64_kernel, restorer), &restorer, sizeof(restorer))) + return _EFAULT; + sigset_t_ mask = 0; + int err = user_get_sigset(addr + offsetof(struct sigaction_arm64_kernel, mask), sigset_size, &mask); + if (err) + return err; + *out = (struct sigaction_) { + .handler = (addr_t) handler, + .flags = (dword_t) flags, + .restorer = (addr_t) restorer, + .mask = mask, + }; + return 0; +} + +static int user_put_sigaction_arm64(addr_t addr, dword_t sigset_size, const struct sigaction_ *in) { + uint64_t handler = (uint64_t) in->handler; + uint64_t flags = (uint64_t) in->flags; + uint64_t restorer = (uint64_t) in->restorer; + if (user_write(addr + offsetof(struct sigaction_arm64_kernel, handler), &handler, sizeof(handler))) + return _EFAULT; + if (user_write(addr + offsetof(struct sigaction_arm64_kernel, flags), &flags, sizeof(flags))) + return _EFAULT; + if (user_write(addr + offsetof(struct sigaction_arm64_kernel, restorer), &restorer, sizeof(restorer))) + return _EFAULT; + return user_put_sigset(addr + offsetof(struct sigaction_arm64_kernel, mask), sigset_size, in->mask); +} +#endif + +#if defined(GUEST_ARM64) +// ARM64 signal handling - matches Linux kernel sigcontext layout + +static void setup_sigcontext(struct sigcontext_ *sc, struct cpu_state *cpu) { + // Store full ARM64 state needed for sigreturn + // NOTE: Do NOT call arm64_sync_nzcv() here! + // The JIT maintains cpu->nzcv directly (via mrs/str in store_flags). + // The individual byte flags (nf/zf/cf/vf) are stale and must not + // overwrite the correct nzcv value. See also: MEMORY.md NZCV lesson. + + // Clear the entire structure first + memset(sc, 0, sizeof(*sc)); + + sc->fault_address = cpu->segfault_addr; + memcpy(sc->regs, cpu->regs, sizeof(cpu->regs)); + sc->sp = cpu->sp; + sc->pc = cpu->pc; + sc->pstate = cpu->nzcv; + + // Set up FPSIMD context in the extension area + struct fpsimd_context_ *fpsimd = (struct fpsimd_context_ *)sc->__reserved; + fpsimd->magic = FPSIMD_MAGIC; + fpsimd->size = sizeof(struct fpsimd_context_); + fpsimd->fpsr = cpu->fpsr; + fpsimd->fpcr = cpu->fpcr; + // Copy vector registers + for (int i = 0; i < 32; i++) { + fpsimd->vregs[i] = cpu->fp[i].q; + } + + // Terminate the extension list with null entry + uint32_t *term = (uint32_t *)(sc->__reserved + sizeof(struct fpsimd_context_)); + term[0] = 0; // magic = 0 terminates + term[1] = 0; // size = 0 +} +#else +static void setup_sigcontext(struct sigcontext_ *sc, struct cpu_state *cpu) { + sc->ax = cpu->eax; + sc->bx = cpu->ebx; + sc->cx = cpu->ecx; + sc->dx = cpu->edx; + sc->di = cpu->edi; + sc->si = cpu->esi; + sc->bp = cpu->ebp; + sc->sp = sc->sp_at_signal = cpu->esp; + sc->ip = cpu->eip; + collapse_flags(cpu); + sc->flags = cpu->eflags; + sc->trapno = cpu->trapno; + if (cpu->trapno == INT_GPF) + sc->cr2 = cpu->segfault_addr; + // Remaining legacy compatibility sigcontext fields are left at zero. + sc->oldmask = current->blocked & 0xffffffff; +} +#endif + +static void setup_sigframe(struct siginfo_ *info, struct sigframe_ *frame) { + frame->restorer = sigreturn_trampoline("__kernel_sigreturn"); + frame->sig = info->sig; + setup_sigcontext(&frame->sc, ¤t->cpu); + frame->extramask = current->blocked >> 32; + + static const struct { + uint16_t popmov; + uint32_t nr_sigreturn; + uint16_t int80; + } __attribute__((packed)) retcode = { + .popmov = 0xb858, + .nr_sigreturn = 113, + .int80 = 0x80cd, + }; + memcpy(frame->retcode, &retcode, sizeof(retcode)); +} + +static void setup_rt_sigframe(struct siginfo_ *info, struct rt_sigframe_ *frame) { + frame->restorer = sigreturn_trampoline("__kernel_rt_sigreturn"); +#if defined(GUEST_ARM64) + if (frame->restorer == 0) { + static const uint32_t rt_retcode[] = { + 0xd2801168, // mov x8, #139 + 0xd4000001, // svc #0 + }; + memcpy(frame->retcode, rt_retcode, sizeof(rt_retcode)); + } +#endif + frame->sig = info->sig; + frame->info = *info; + frame->uc.flags = 0; + frame->uc.link = 0; + altstack_to_user(current, &frame->uc.stack); + setup_sigcontext(&frame->uc.mcontext, ¤t->cpu); + frame->uc.sigmask = current->blocked; + +#if !defined(GUEST_ARM64) + static const struct { + uint8_t mov; + uint32_t nr_rt_sigreturn; + uint16_t int80; + uint8_t pad; + } __attribute__((packed)) rt_retcode = { + .mov = 0xb8, + .nr_rt_sigreturn = 173, + .int80 = 0x80cd, + }; + memcpy(frame->retcode, &rt_retcode, sizeof(rt_retcode)); +#endif +} + +static void receive_signal(struct sighand *sighand, struct siginfo_ *info) { + int sig = info->sig; + STRACE("%d receiving signal %d\n", current->pid, sig); + + int action_type = signal_action(sighand, sig); + switch (action_type) { + case SIGNAL_IGNORE: + return; + + case SIGNAL_STOP: + lock(¤t->group->lock); + current->group->stopped = true; + current->group->group_exit_code = sig << 8 | 0x7f; + unlock(¤t->group->lock); + return; + + case SIGNAL_KILL: + unlock(&sighand->lock); // do_exit must be called without this lock +#ifdef GUEST_ARM64 + // V8's IMMEDIATE_CRASH() uses BRK #0 on ARM64 (delivers SIGTRAP). + // Generic recovery: unwind the current function frame and return 0 + // to the caller. This lets V8 continue past non-fatal CHECKs. + if (sig == SIGTRAP_) { + struct cpu_state *cpu = ¤t->cpu; + fprintf(stderr, "V8_SIGTRAP: pc=0x%llx x0=0x%llx sp=%llx fp=%llx lr=%llx\n", + (unsigned long long)cpu->pc, + (unsigned long long)cpu->regs[0], + (unsigned long long)cpu->sp, + (unsigned long long)cpu->regs[29], + (unsigned long long)cpu->regs[30]); + do_exit_group(1 << 8); + return; + } + if (sig == SIGABRT_) { + // V8's abort() after Fatal. Just terminate cleanly. + struct cpu_state *cpu = ¤t->cpu; + fprintf(stderr, "V8_SIGABRT: pc=0x%llx sp=%llx fp=%llx lr=%llx\n", + (unsigned long long)cpu->pc, + (unsigned long long)cpu->sp, + (unsigned long long)cpu->regs[29], + (unsigned long long)cpu->regs[30]); + do_exit_group(1 << 8); + return; + } + // V8 scope corruption GPF cascade: the deep frame unwind in + // handle_interrupt may leave a background thread with a corrupt + // PC pointing into the V8 heap. When that thread tries to + // execute "code" at a heap address, it gets SIGILL. + // Flush the host-side stdout/stderr pipes before killing the + // process group, so buffered output (e.g. npm help) is visible. + if (sig == SIGILL_ || sig == SIGBUS_) { + struct cpu_state *cpu = ¤t->cpu; + if (cpu->pc >= 0xb0000000 && cpu->pc < 0xf0000000) { + do_exit_group(1 << 8); + return; + } + } +#endif + do_exit_group(sig); + } + + struct sigaction_ *action = &sighand->action[info->sig]; + bool need_siginfo = action->flags & SA_SIGINFO_; +#if defined(GUEST_ARM64) + // ARM64 only provides __kernel_rt_sigreturn in the VDSO. + // Always use an rt_sigframe for signal delivery. + need_siginfo = true; + + // SA_RESTART: if this handler asked for automatic restart and the syscall + // we're interrupting returned EINTR, rewind PC to the `svc #0` instruction + // (4 bytes back) and restore the original first argument (x0), which the + // return value clobbered. The signal frame we save next captures this + // rewound PC, so when the handler returns via rt_sigreturn the syscall + // re-executes instead of surfacing EINTR. Load-bearing for JSC's SIGPWR + // GC-safepoint handshake, which registers SA_RESTART and otherwise + // livelocks re-signalling a thread whose futex keeps returning EINTR. + // syscall_restartable is a sticky flag: it stays set if an earlier EINTR + // futex/epoll/read/write delivered a signal whose handler lacked SA_RESTART + // (no rewind happened). Guarding the rewind on the flag alone is unsafe — + // a later non-syscall interrupt (INT_TIMER every ~1024 blocks, INT_GPF on + // demand-map/CoW) runs receive_signals() too, and if a NEW SA_RESTART signal + // is pending it would rewind PC into the middle of ordinary code. Require + // cpu.pc to still equal the interrupted syscall's return PC (svc_addr+4), so + // the rewind can only fire when we truly are just past that svc. + if ((action->flags & SA_RESTART_) && current->syscall_restartable && + current->cpu.pc == current->syscall_restart_pc) { + current->cpu.pc -= 4; + current->cpu.regs[0] = current->syscall_restart_arg0; + current->syscall_restartable = false; + } +#endif + + // setup the frame + union { + struct sigframe_ sigframe; + struct rt_sigframe_ rt_sigframe; + } frame = {}; + size_t frame_size; + if (need_siginfo) { + setup_rt_sigframe(info, &frame.rt_sigframe); + frame_size = sizeof(frame.rt_sigframe); + } else { + setup_sigframe(info, &frame.sigframe); + frame_size = sizeof(frame.sigframe); + } + + // set up registers for signal handler +#if defined(GUEST_ARM64) + // ARM64 spec: exceptions clear the exclusive monitor + current->cpu.excl_addr = UINT64_MAX; + current->cpu.excl_pair_addr = UINT64_MAX; + current->cpu.excl_pair_size = 0; + current->cpu.regs[0] = info->sig; + current->cpu.pc = sighand->action[info->sig].handler; + addr_t sp = current->cpu.sp; // Use addr_t (64-bit) for ARM64 +#else + current->cpu.eax = info->sig; + current->cpu.eip = sighand->action[info->sig].handler; + dword_t sp = current->cpu.esp; +#endif + if ((sighand->action[info->sig].flags & SA_ONSTACK_) && + current->altstack && !is_on_altstack(sp, current)) { + sp = current->altstack + current->altstack_size; + } + if (xsave_extra) { + // do as the kernel does + // this is superhypermega condensed version of fpu__alloc_mathframe in + // Linux kernel signal-frame FPU reserve marker behavior. + sp -= xsave_extra; + sp &=~ 0x3f; + sp -= fxsave_extra; + } + sp -= frame_size; +#if defined(GUEST_ARM64) + // ARM64 requires the stack to be 16-byte aligned. + sp &= ~0xf; +#else + // align sp + 4 on a 16-byte boundary because that's what the abi says + sp = ((sp + 4) & ~0xf) - 4; +#endif +#if defined(GUEST_ARM64) + current->cpu.sp = sp; +#else + current->cpu.esp = sp; +#endif + + // Update the mask. By default the signal will be blocked while in the + // handler, but sigaction is allowed to customize this. + if (!(action->flags & SA_NODEFER_)) + sigset_add(¤t->blocked, info->sig); + current->blocked |= action->mask; + + // these have to be filled in after the location of the frame is known + if (need_siginfo) { + frame.rt_sigframe.pinfo = sp + offsetof(struct rt_sigframe_, info); + frame.rt_sigframe.puc = sp + offsetof(struct rt_sigframe_, uc); +#if defined(GUEST_ARM64) + // ARM64 ABI: x0=signum, x1=siginfo*, x2=ucontext* + current->cpu.regs[1] = frame.rt_sigframe.pinfo; + current->cpu.regs[2] = frame.rt_sigframe.puc; +#else + current->cpu.edx = frame.rt_sigframe.pinfo; + current->cpu.ecx = frame.rt_sigframe.puc; +#endif + } + + // install frame + if (user_write(sp, &frame, frame_size)) { + printk("failed to install frame for %d at %#x\n", info->sig, sp); + deliver_signal(current, SIGSEGV_, SIGINFO_NIL); + } + +#if defined(GUEST_ARM64) + // Set LR to the signal return trampoline. + if (need_siginfo) { + current->cpu.regs[30] = frame.rt_sigframe.restorer != 0 + ? frame.rt_sigframe.restorer + : sp + offsetof(struct rt_sigframe_, retcode); + } else { + current->cpu.regs[30] = frame.sigframe.restorer; + } +#endif + + if (action->flags & SA_RESETHAND_) + *action = (struct sigaction_) {.handler = SIG_DFL_}; +} + +void signal_delivery_stop(int sig, struct siginfo_ *info) { + lock(¤t->ptrace.lock); + current->ptrace.stopped = true; + current->ptrace.signal = sig; + current->ptrace.info = *info; + unlock(¤t->ptrace.lock); + notify(¤t->parent->group->child_exit); + // TODO add siginfo + send_signal(current->parent, current->group->leader->exit_signal, SIGINFO_NIL); + + unlock(¤t->sighand->lock); + lock(¤t->ptrace.lock); + while (current->ptrace.stopped) { + wait_for_ignore_signals(¤t->ptrace.cond, ¤t->ptrace.lock, NULL); + lock(¤t->sighand->lock); + bool got_sigkill = sigset_has(current->pending, SIGKILL_); + unlock(¤t->sighand->lock); + if (got_sigkill) { + STRACE("%d received a SIGKILL in signal delivery stop\n", current->pid); + unlock(¤t->ptrace.lock); + do_exit_group(SIGKILL_); + } + } + unlock(¤t->ptrace.lock); + lock(¤t->sighand->lock); +} + +void receive_signals() { + lock(¤t->group->lock); + bool was_stopped = current->group->stopped; + unlock(¤t->group->lock); + + struct sighand *sighand = current->sighand; + if (sighand == NULL) + return; + lock(&sighand->lock); + + // A saved mask means that the last system call was a call like sigsuspend + // that changes the mask during the call. Only ignore a signal right now if + // it was both blocked during the call and should still be blocked after + // the call. + sigset_t_ blocked = current->blocked; + if (current->has_saved_mask) { + blocked &= current->saved_mask; + current->has_saved_mask = false; + current->blocked = current->saved_mask; + } + + struct sigqueue *sigqueue, *tmp; + list_for_each_entry_safe(¤t->queue, sigqueue, tmp, queue) { + int sig = sigqueue->info.sig; + if (sigset_has(blocked, sig)) + continue; + list_remove(&sigqueue->queue); + sigset_del(¤t->pending, sig); + + if (current->ptrace.traced && sig != SIGKILL_) { + // This notifies the parent, goes to sleep, and waits for the + // parent to tell it to continue. + // Any signals received while waiting are left on the queue, except + // for SIGKILL_, which causes an immediate exit. + signal_delivery_stop(sig, &sigqueue->info); + } else { + receive_signal(sighand, &sigqueue->info); + } + free(sigqueue); + } + + unlock(&sighand->lock); + + // this got moved out of the switch case in receive_signal to fix locking problems + if (!was_stopped) { + lock(¤t->group->lock); + bool now_stopped = current->group->stopped; + unlock(¤t->group->lock); + if (now_stopped) { + lock(&pids_lock); + notify(¤t->parent->group->child_exit); + // TODO add siginfo + send_signal(current->parent, current->group->leader->exit_signal, SIGINFO_NIL); + unlock(&pids_lock); + } + } +} + +#if defined(GUEST_ARM64) +static void restore_sigcontext(struct sigcontext_ *context, struct cpu_state *cpu) { + memcpy(cpu->regs, context->regs, sizeof(cpu->regs)); + cpu->sp = context->sp; + cpu->pc = context->pc; + arm64_set_nzcv(cpu, (uint32_t)context->pstate); + + // Restore FPSIMD context from extension area + struct fpsimd_context_ *fpsimd = (struct fpsimd_context_ *)context->__reserved; + if (fpsimd->magic == FPSIMD_MAGIC) { + cpu->fpsr = fpsimd->fpsr; + cpu->fpcr = fpsimd->fpcr; + for (int i = 0; i < 32; i++) { + cpu->fp[i].q = fpsimd->vregs[i]; + } + } +} +#else +static void restore_sigcontext(struct sigcontext_ *context, struct cpu_state *cpu) { + cpu->eax = context->ax; + cpu->ebx = context->bx; + cpu->ecx = context->cx; + cpu->edx = context->dx; + cpu->edi = context->di; + cpu->esi = context->si; + cpu->ebp = context->bp; + cpu->esp = context->sp; + cpu->eip = context->ip; + collapse_flags(cpu); + + // Use AC, RF, OF, DF, TF, SF, ZF, AF, PF, CF +#define USE_FLAGS 0b1010000110111010101 + cpu->eflags = (context->flags & USE_FLAGS) | (cpu->eflags & ~USE_FLAGS); +} +#endif + +int64_t sys_rt_sigreturn() { + struct cpu_state *cpu = ¤t->cpu; + struct rt_sigframe_ frame; +#if defined(GUEST_ARM64) + addr_t sp = cpu->sp; // Use addr_t (64-bit) for ARM64 +#else + dword_t sp = cpu->esp; +#endif +#if defined(GUEST_ARM64) + // ARM64 keeps SP pointing at the start of the frame. + addr_t frame_addr = sp; +#else + // esp/sp points past the first field of the frame + addr_t frame_addr = sp - offsetof(struct rt_sigframe_, sig); +#endif + if (user_get(frame_addr, frame)) { + deliver_signal(current, SIGSEGV_, SIGINFO_NIL); + return _EFAULT; + } + restore_sigcontext(&frame.uc.mcontext, cpu); + + lock(¤t->sighand->lock); + // FIXME this duplicates logic from sys_sigaltstack + if (!is_on_altstack(sp, current) && + frame.uc.stack.size >= MINSIGSTKSZ_) { + current->altstack = frame.uc.stack.stack; + current->altstack_size = frame.uc.stack.size; + } + sigmask_set(frame.uc.sigmask); + unlock(¤t->sighand->lock); +#if defined(GUEST_ARM64) + // Return the full 64-bit x0 from the restored context. + // IMPORTANT: The caller (handle_interrupt) must NOT modify x0 after + // this returns, because the full register state was restored from the + // signal frame. We return int64_t to preserve all 64 bits. + return (int64_t)cpu->regs[0]; +#else + return cpu->eax; +#endif +} + +int64_t sys_sigreturn() { + struct cpu_state *cpu = ¤t->cpu; + struct sigframe_ frame; +#if defined(GUEST_ARM64) + addr_t sp = cpu->sp; // Use addr_t (64-bit) for ARM64 +#else + dword_t sp = cpu->esp; +#endif +#if defined(GUEST_ARM64) + // ARM64 keeps SP pointing at the start of the frame. + addr_t frame_addr = sp; +#else + // esp/sp points past the first two fields of the frame + addr_t frame_addr = sp - offsetof(struct sigframe_, sc); +#endif + if (user_get(frame_addr, frame)) { + deliver_signal(current, SIGSEGV_, SIGINFO_NIL); + return _EFAULT; + } + restore_sigcontext(&frame.sc, cpu); + + lock(¤t->sighand->lock); +#if defined(GUEST_ARM64) + sigmask_set(current->blocked); +#else + sigset_t_ oldmask = ((sigset_t_) frame.extramask << 32) | frame.sc.oldmask; + sigmask_set(oldmask); +#endif + unlock(¤t->sighand->lock); +#if defined(GUEST_ARM64) + return (int64_t)cpu->regs[0]; +#else + return cpu->eax; +#endif +} + +struct sighand *sighand_new() { + struct sighand *sighand = malloc(sizeof(struct sighand)); + if (sighand == NULL) + return NULL; + memset(sighand, 0, sizeof(struct sighand)); + sighand->refcount = 1; + lock_init(&sighand->lock); + return sighand; +} + +struct sighand *sighand_copy(struct sighand *sighand) { + struct sighand *new_sighand = sighand_new(); + if (new_sighand == NULL) + return NULL; + memcpy(new_sighand->action, sighand->action, sizeof(new_sighand->action)); + return new_sighand; +} + +void sighand_release(struct sighand *sighand) { + if (--sighand->refcount == 0) { + free(sighand); + } +} + +static int do_sigaction(int sig, const struct sigaction_ *action, struct sigaction_ *oldaction) { + if (sig >= NUM_SIGS) + return _EINVAL; + if (!signal_is_blockable(sig)) + return _EINVAL; + + struct sighand *sighand = current->sighand; + lock(&sighand->lock); + if (oldaction) + *oldaction = sighand->action[sig]; + if (action) + sighand->action[sig] = *action; + unlock(&sighand->lock); + return 0; +} + +dword_t sys_rt_sigaction(dword_t signum, addr_t action_addr, addr_t oldaction_addr, dword_t sigset_size) { + if (!sigset_size_valid(sigset_size)) + return _EINVAL; + struct sigaction_ action = {}, oldaction; + if (action_addr != 0) { +#if defined(GUEST_ARM64) + int err = user_get_sigaction_arm64(action_addr, sigset_size, &action); + if (err) + return err; +#else + if (user_get(action_addr, action)) + return _EFAULT; +#endif + } + STRACE("rt_sigaction(%d, %#x {handler=%#x, flags=%#x, restorer=%#x, mask=%#llx}, 0x%x, %d)", signum, + action_addr, action.handler, action.flags, action.restorer, + (unsigned long long) action.mask, oldaction_addr, sigset_size); + + int err = do_sigaction(signum, + action_addr ? &action : NULL, + oldaction_addr ? &oldaction : NULL); + if (err < 0) + return err; + + if (oldaction_addr != 0) + { +#if defined(GUEST_ARM64) + int err = user_put_sigaction_arm64(oldaction_addr, sigset_size, &oldaction); + if (err) + return err; +#else + if (user_put(oldaction_addr, oldaction)) + return _EFAULT; +#endif + } + return err; +} + +dword_t sys_sigaction(dword_t signum, addr_t action_addr, addr_t oldaction_addr) { + return sys_rt_sigaction(signum, action_addr, oldaction_addr, 1); +} + +static void sigmask_set(sigset_t_ set) { + current->blocked = (set & ~UNBLOCKABLE_MASK); +} + +static void sigmask_set_temp_unlocked(sigset_t_ mask) { + current->saved_mask = current->blocked; + current->has_saved_mask = true; + sigmask_set(mask); +} + +void sigmask_set_temp(sigset_t_ mask) { + lock(¤t->sighand->lock); + sigmask_set_temp_unlocked(mask); + unlock(¤t->sighand->lock); +} + +static int do_sigprocmask(dword_t how, sigset_t_ set) { + if (how == SIG_BLOCK_) + sigmask_set(current->blocked | set); + else if (how == SIG_UNBLOCK_) + sigmask_set(current->blocked & ~set); + else if (how == SIG_SETMASK_) + sigmask_set(set); + else + return _EINVAL; + return 0; +} + +dword_t sys_rt_sigprocmask(dword_t how, addr_t set_addr, addr_t oldset_addr, dword_t size) { + if (!sigset_size_valid(size)) + return _EINVAL; + + sigset_t_ set; + if (set_addr != 0) { + int err = user_get_sigset(set_addr, size, &set); + if (err) + return err; + } + STRACE("rt_sigprocmask(%s, %#llx, %#x, %d)", + how == SIG_BLOCK_ ? "SIG_BLOCK" : + how == SIG_UNBLOCK_ ? "SIG_UNBLOCK" : + how == SIG_SETMASK_ ? "SIG_SETMASK" : "??", + set_addr != 0 ? (long long) set : -1, oldset_addr, size); + + if (oldset_addr != 0) { + int err = user_put_sigset(oldset_addr, size, current->blocked); + if (err) + return err; + } + if (set_addr != 0) { + struct sighand *sighand = current->sighand; + lock(&sighand->lock); + int err = do_sigprocmask(how, set); + unlock(&sighand->lock); + if (err < 0) + return err; + } + return 0; +} + +int_t sys_rt_sigpending(addr_t set_addr, dword_t size) { + STRACE("rt_sigpending(%#x, %d)", set_addr, size); + // as defined by the standard + sigset_t_ pending = current->pending & current->blocked; + return user_put_sigset(set_addr, size, pending); +} + +static void signalfd_fill_siginfo(struct signalfd_siginfo_ *out, const struct siginfo_ *in) { + memset(out, 0, sizeof(*out)); + out->signo = in->sig; + out->err = in->sig_errno; + out->code = in->code; + if (in->code == SI_USER_ || in->code == SI_TKILL_ || in->code == SI_TIMER_) { + out->pid = in->kill.pid; + out->uid = in->kill.uid; + } + if (in->sig == SIGCHLD_) { + out->pid = in->child.pid; + out->uid = in->child.uid; + out->status = in->child.status; + out->utime = in->child.utime; + out->stime = in->child.stime; + } + if (in->sig == SIGSEGV_ || in->sig == SIGBUS_ || in->sig == SIGILL_ || in->sig == SIGFPE_) + out->addr = in->fault.addr; +} + +static bool signalfd_dequeue_locked(sigset_t_ mask, struct siginfo_ *info) { + struct sigqueue *sigqueue, *tmp; + list_for_each_entry_safe(¤t->queue, sigqueue, tmp, queue) { + if (sigset_has(mask, sigqueue->info.sig)) { + list_remove(&sigqueue->queue); + sigset_del(¤t->pending, sigqueue->info.sig); + *info = sigqueue->info; + free(sigqueue); + return true; + } + } + return false; +} + +static ssize_t signalfd_read(struct fd *fd, void *buf, size_t bufsize) { + if (bufsize < sizeof(struct signalfd_siginfo_)) + return _EINVAL; + sigset_t_ mask = (sigset_t_)(uintptr_t)fd->data; + size_t count = 0; + lock(¤t->sighand->lock); + for (;;) { + struct siginfo_ info; + if (signalfd_dequeue_locked(mask, &info)) { + struct signalfd_siginfo_ out; + signalfd_fill_siginfo(&out, &info); + memcpy((char *)buf + count, &out, sizeof(out)); + count += sizeof(out); + if (count + sizeof(out) > bufsize) + break; + continue; + } + if (count > 0) + break; + if (fd->flags & O_NONBLOCK_) { + unlock(¤t->sighand->lock); + return _EAGAIN; + } + int err = wait_for(¤t->pause, ¤t->sighand->lock, NULL); + if (err < 0 && err != _EINTR) { + unlock(¤t->sighand->lock); + return err; + } + } + unlock(¤t->sighand->lock); + return count; +} + +static int signalfd_close(struct fd *fd) { + (void)fd; + return 0; +} + +static int signalfd_getflags(struct fd *fd) { + return fd->flags; +} + +static int signalfd_setflags(struct fd *fd, dword_t flags) { + fd->flags = (fd->flags & ~O_NONBLOCK_) | (flags & O_NONBLOCK_); + return 0; +} + +int_t sys_signalfd4(int_t fd_no, addr_t mask_addr, size_t mask_size, int_t flags) { + STRACE("signalfd4(%d, %#x, %#zx, %#x)", fd_no, mask_addr, mask_size, flags); + if (flags & ~(O_CLOEXEC_ | O_NONBLOCK_)) + return _EINVAL; + sigset_t_ mask; + int err = user_get_sigset(mask_addr, mask_size, &mask); + if (err < 0) + return err; + // The kernel silently removes SIGKILL/SIGSTOP from the signalfd mask. + sigset_del(&mask, SIGKILL_); + sigset_del(&mask, SIGSTOP_); + if (fd_no >= 0) { + struct fd *fd = f_get(fd_no); + if (fd == NULL) + return _EBADF; + if (fd->ops != &signalfd_ops) + return _EINVAL; + fd->data = (void *)(uintptr_t)mask; + fd_setflags(fd, flags & O_NONBLOCK_); + return fd_no; + } + struct fd *fd = adhoc_fd_create(&signalfd_ops); + if (fd == NULL) + return _ENOMEM; + fd->data = (void *)(uintptr_t)mask; + fd->stat.mode = S_IFIFO | 0600; + return f_install(fd, flags); +} + +static bool is_on_altstack(addr_t sp, struct task *task) { + return task->altstack != 0 && sp > task->altstack && sp <= task->altstack + task->altstack_size; +} + +static void altstack_to_user(struct task *task, struct stack_t_ *user_stack) { + user_stack->stack = task->altstack; + user_stack->size = task->altstack_size; + user_stack->flags = 0; + if (task->altstack == 0) + user_stack->flags |= SS_DISABLE_; +#if defined(GUEST_ARM64) + if (is_on_altstack(current->cpu.sp, task)) +#else + if (is_on_altstack(current->cpu.esp, task)) +#endif + user_stack->flags |= SS_ONSTACK_; +} + +dword_t sys_sigaltstack(addr_t ss_addr, addr_t old_ss_addr) { + STRACE("sigaltstack(0x%x, 0x%x)", ss_addr, old_ss_addr); + struct sighand *sighand = current->sighand; + lock(&sighand->lock); + if (old_ss_addr != 0) { + struct stack_t_ old_ss; + altstack_to_user(current, &old_ss); + if (user_put(old_ss_addr, old_ss)) { + unlock(&sighand->lock); + return _EFAULT; + } + } + if (ss_addr != 0) { +#if defined(GUEST_ARM64) + if (is_on_altstack(current->cpu.sp, current)) { +#else + if (is_on_altstack(current->cpu.esp, current)) { +#endif + unlock(&sighand->lock); + return _EPERM; + } + struct stack_t_ ss; + if (user_get(ss_addr, ss)) { + unlock(&sighand->lock); + return _EFAULT; + } + if (ss.flags & SS_DISABLE_) { + current->altstack = 0; + current->altstack_size = 0; + } else { + if (ss.size < MINSIGSTKSZ_) { + unlock(&sighand->lock); + return _ENOMEM; + } + current->altstack = ss.stack; + current->altstack_size = ss.size; + } + } + unlock(&sighand->lock); + return 0; +} + +int_t sys_rt_sigsuspend(addr_t mask_addr, uint_t size) { + sigset_t_ mask; + int err = user_get_sigset(mask_addr, size, &mask); + if (err) + return err; + STRACE("sigsuspend(0x%llx) = ...\n", (long long) mask); + + lock(¤t->sighand->lock); + sigmask_set_temp_unlocked(mask); + while (wait_for(¤t->pause, ¤t->sighand->lock, NULL) != _EINTR) + continue; + unlock(¤t->sighand->lock); + STRACE("%d done sigsuspend", current->pid); + return _EINTR; +} + +int_t sys_pause() { + lock(¤t->sighand->lock); + while (wait_for(¤t->pause, ¤t->sighand->lock, NULL) != _EINTR) + continue; + unlock(¤t->sighand->lock); + return _EINTR; +} + +int_t sys_rt_sigtimedwait(addr_t set_addr, addr_t info_addr, addr_t timeout_addr, uint_t set_size) { + sigset_t_ set; + int err = user_get_sigset(set_addr, set_size, &set); + if (err) + return err; + struct timespec timeout; + if (timeout_addr != 0) { + struct timespec_ fake_timeout; + if (user_get(timeout_addr, fake_timeout)) + return _EFAULT; + timeout.tv_sec = fake_timeout.sec; + timeout.tv_nsec = fake_timeout.nsec; + } + STRACE("sigtimedwait(%#llx, %#x, %#x) = ...\n", (long long) set, info_addr, timeout_addr); + + lock(¤t->sighand->lock); + assert(current->waiting == 0); + current->waiting = set; + int wait_err; + do { + wait_err = wait_for(¤t->pause, ¤t->sighand->lock, timeout_addr == 0 ? NULL : &timeout); + } while (wait_err == 0); + current->waiting = 0; + if (wait_err == _ETIMEDOUT) { + unlock(¤t->sighand->lock); + STRACE("sigtimedwait timed out\n"); + return _EAGAIN; + } + + struct sigqueue *sigqueue; + bool found = false; + list_for_each_entry(¤t->queue, sigqueue, queue) { + if (sigset_has(set, sigqueue->info.sig)) { + found = true; + list_remove(&sigqueue->queue); + break; + } + } + unlock(¤t->sighand->lock); + if (!found) + return _EINTR; + struct siginfo_ info = sigqueue->info; + free(sigqueue); + if (info_addr != 0) + if (user_put(info_addr, info)) + return _EFAULT; + STRACE("done sigtimedwait = %d\n", info.sig); + return info.sig; +} + +static int kill_task(struct task *task, dword_t sig, int code) { + if (!superuser() && + current->uid != task->uid && + current->uid != task->suid && + current->euid != task->uid && + current->euid != task->suid) + return _EPERM; + struct siginfo_ info = { + .code = code, + .kill.pid = current->pid, + .kill.uid = current->uid, + }; + send_signal(task, sig, info); + return 0; +} + +static int kill_group(pid_t_ pgid, dword_t sig, int code) { + struct pid *pid = pid_get(pgid); + if (pid == NULL) { + unlock(&pids_lock); + return _ESRCH; + } + struct tgroup *tgroup; + int err = _EPERM; + list_for_each_entry(&pid->pgroup, tgroup, pgroup) { + int kill_err = kill_task(tgroup->leader, sig, code); + // killing a group should return an error only if no process can be signaled + if (err == _EPERM) + err = kill_err; + } + return err; +} + +static int kill_everything(dword_t sig, int code) { + int err = _EPERM; + for (int i = 2; i < MAX_PID; i++) { + struct task *task = pid_get_task(i); + if (task == NULL || task == current || !task_is_leader(task)) + continue; + int kill_err = kill_task(task, sig, code); + if (err == _EPERM) + err = kill_err; + } + return err; +} + +static int do_kill(pid_t_ pid, dword_t sig, pid_t_ tgid, int code) { + STRACE("kill(%d, %d)", pid, sig); + if (sig >= NUM_SIGS) + return _EINVAL; + if (pid == 0) + pid = -current->group->pgid; + + int err; + lock(&pids_lock); + + if (pid == -1) { + err = kill_everything(sig, code); + } else if (pid < 0) { + err = kill_group(-pid, sig, code); + } else { + struct task *task = pid_get_task(pid); + if (task == NULL) { + unlock(&pids_lock); + return _ESRCH; + } + + // If tgid is nonzero, it must be correct + if (tgid != 0 && task->tgid != tgid) { + unlock(&pids_lock); + return _ESRCH; + } + + err = kill_task(task, sig, code); + } + + unlock(&pids_lock); + return err; +} + +dword_t sys_kill(pid_t_ pid, dword_t sig) { + return do_kill(pid, sig, 0, SI_USER_); +} +dword_t sys_tgkill(pid_t_ tgid, pid_t_ tid, dword_t sig) { + if (tid <= 0 || tgid <= 0) + return _EINVAL; + return do_kill(tid, sig, tgid, SI_TKILL_); +} +dword_t sys_tkill(pid_t_ tid, dword_t sig) { + if (tid <= 0) + return _EINVAL; + return do_kill(tid, sig, 0, SI_TKILL_); +} + +void force_signal(struct task *task, int sig, struct siginfo_ info) { + struct sighand *sighand = task->sighand; + if (sighand == NULL) + return; + lock(&sighand->lock); + struct sigaction_ *action = &sighand->action[sig]; + // A blocked or ignored fault cannot resume at the faulting instruction. + if (sigset_has(task->blocked, sig) || action->handler == SIG_IGN_) { + action->handler = SIG_DFL_; + sigset_del(&task->blocked, sig); + } + deliver_signal_unlocked(task, sig, info); + unlock(&sighand->lock); + cpu_poke(&task->cpu); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/signal.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/signal.h new file mode 100644 index 0000000000..6558d7506e --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/signal.h @@ -0,0 +1,389 @@ +#ifndef SIGNAL_H +#define SIGNAL_H + +#include "misc.h" +#include "util/list.h" +#include "util/sync.h" +struct task; + +typedef qword_t sigset_t_; + +#define SIG_ERR_ -1 +#define SIG_DFL_ 0 +#define SIG_IGN_ 1 + +#define SA_SIGINFO_ 4 +#define SA_ONSTACK_ 0x08000000 +#define SA_RESTART_ 0x10000000 +#define SA_NODEFER_ 0x40000000 +#define SA_RESETHAND_ 0x80000000 + +struct sigaction_ { + addr_t handler; + dword_t flags; + addr_t restorer; + sigset_t_ mask; +} __attribute__((packed)); + +#define NUM_SIGS 64 + +#define SIGHUP_ 1 +#define SIGINT_ 2 +#define SIGQUIT_ 3 +#define SIGILL_ 4 +#define SIGTRAP_ 5 +#define SIGABRT_ 6 +#define SIGIOT_ 6 +#define SIGBUS_ 7 +#define SIGFPE_ 8 +#define SIGKILL_ 9 +#define SIGUSR1_ 10 +#define SIGSEGV_ 11 +#define SIGUSR2_ 12 +#define SIGPIPE_ 13 +#define SIGALRM_ 14 +#define SIGTERM_ 15 +#define SIGSTKFLT_ 16 +#define SIGCHLD_ 17 +#define SIGCONT_ 18 +#define SIGSTOP_ 19 +#define SIGTSTP_ 20 +#define SIGTTIN_ 21 +#define SIGTTOU_ 22 +#define SIGURG_ 23 +#define SIGXCPU_ 24 +#define SIGXFSZ_ 25 +#define SIGVTALRM_ 26 +#define SIGPROF_ 27 +#define SIGWINCH_ 28 +#define SIGIO_ 29 +#define SIGPWR_ 30 +#define SIGSYS_ 31 + +#define SI_USER_ 0 +#define SI_TIMER_ -2 +#define SI_TKILL_ -6 +#define SI_KERNEL_ 128 +#define TRAP_TRACE_ 2 +#define SEGV_MAPERR_ 1 +#define SEGV_ACCERR_ 2 + +union sigval_ { + int_t sv_int; + addr_t sv_ptr; +}; + +struct siginfo_ { + int_t sig; + int_t sig_errno; + int_t code; +#if defined(GUEST_ARM64) + // 64-bit Linux aligns the _sifields union to 8 bytes, so si_pid/si_uid + // start at offset 16, not offset 12. Signal handlers in runtimes such as + // JavaScriptCore inspect these fields for thread-directed signals. + int_t _pad0; +#endif + union { + struct { + pid_t_ pid; + uid_t_ uid; + } kill; + struct { + pid_t_ pid; + uid_t_ uid; + int_t status; + clock_t_ utime; + clock_t_ stime; + } child; + struct { + addr_t addr; + } fault; + struct { + addr_t addr; + int_t syscall; + } sigsys; + struct { + int_t timer; + int_t overrun; + union sigval_ value; + int_t _private; + } timer; + }; +}; + +// a reasonable default siginfo +static const struct siginfo_ SIGINFO_NIL = { + .code = SI_KERNEL_, +}; + +struct sigqueue { + struct list queue; + struct siginfo_ info; +}; + +struct sigevent_ { + union sigval_ value; // offset 0, size 8 + int_t signo; // offset 8, size 4 + int_t method; // offset 12, size 4 +#ifdef GUEST_ARM64 + // ARM64: struct sigevent is 64 bytes with additional fields + // sigev_notify_function, sigev_notify_attributes, padding + union { + pid_t_ tid; // for SIGEV_THREAD_ID + char _pad[48]; // padding to reach 64 bytes total (8+4+4+48=64) + }; +#else + pid_t_ tid; +#endif +}; + +// send a signal +// you better make sure the task isn't gonna get freed under me (pids_lock or current) +void send_signal(struct task *task, int sig, struct siginfo_ info); +// send a signal without regard for whether the signal is blocked or ignored +void deliver_signal(struct task *task, int sig, struct siginfo_ info); +// Force a synchronous fault, restoring default handling if blocked or ignored. +void force_signal(struct task *task, int sig, struct siginfo_ info); +// send a signal to current if it's not blocked or ignored, return whether that worked +// exists specifically for sending SIGTTIN/SIGTTOU +bool try_self_signal(int sig); +// send a signal to all processes in a group, could return ESRCH +int send_group_signal(dword_t pgid, int sig, struct siginfo_ info); +// check for and deliver pending signals on current +// must be called without pids_lock, current->group->lock, or current->sighand->lock +void receive_signals(void); +// set the signal mask, restore it to what it was before on the next receive_signals call +void sigmask_set_temp(sigset_t_ mask); + +struct sighand { + atomic_uint refcount; + struct sigaction_ action[NUM_SIGS]; + lock_t lock; +}; +struct sighand *sighand_new(void); +struct sighand *sighand_copy(struct sighand *sighand); +void sighand_release(struct sighand *sighand); + +dword_t sys_rt_sigaction(dword_t signum, addr_t action_addr, addr_t oldaction_addr, dword_t sigset_size); +dword_t sys_sigaction(dword_t signum, addr_t action_addr, addr_t oldaction_addr); +int64_t sys_rt_sigreturn(void); +int64_t sys_sigreturn(void); + +#define SIG_BLOCK_ 0 +#define SIG_UNBLOCK_ 1 +#define SIG_SETMASK_ 2 +typedef uint64_t sigset_t_; +dword_t sys_rt_sigprocmask(dword_t how, addr_t set, addr_t oldset, dword_t size); +int_t sys_rt_sigpending(addr_t set_addr, dword_t size); + +int sigset_size_valid(dword_t size); +int user_get_sigset(addr_t addr, dword_t size, sigset_t_ *out); +int user_put_sigset(addr_t addr, dword_t size, sigset_t_ set); + +static inline sigset_t_ sig_mask(int sig) { + assert(sig >= 1 && sig < NUM_SIGS); + return 1l << (sig - 1); +} + +static inline bool sigset_has(sigset_t_ set, int sig) { + return !!(set & sig_mask(sig)); +} +static inline void sigset_add(sigset_t_ *set, int sig) { + *set |= sig_mask(sig); +} +static inline void sigset_del(sigset_t_ *set, int sig) { + *set &= ~sig_mask(sig); +} + +#if defined(GUEST_ARM64) +struct stack_t_ { + uint64_t stack; // ss_sp: 8 bytes on ARM64 + int32_t flags; // ss_flags: 4 bytes + uint32_t _pad; // padding for alignment + uint64_t size; // ss_size: 8 bytes on ARM64 +}; +#define MINSIGSTKSZ_ 6144 +#else +struct stack_t_ { + addr_t stack; + dword_t flags; + dword_t size; +}; +#define MINSIGSTKSZ_ 2048 +#endif +#define SS_ONSTACK_ 1 +#define SS_DISABLE_ 2 +dword_t sys_sigaltstack(addr_t ss, addr_t old_ss); + +int_t sys_rt_sigsuspend(addr_t mask_addr, uint_t size); +int_t sys_pause(void); +int_t sys_rt_sigtimedwait(addr_t set_addr, addr_t info_addr, addr_t timeout_addr, uint_t set_size); +int_t sys_signalfd4(int_t fd_no, addr_t mask_addr, size_t mask_size, int_t flags); + +dword_t sys_kill(pid_t_ pid, dword_t sig); +dword_t sys_tkill(pid_t_ tid, dword_t sig); +dword_t sys_tgkill(pid_t_ tgid, pid_t_ tid, dword_t sig); + +// signal frame structs. There's a good chance this should go in its own header file + +// thanks kernel for giving me something to copy/paste +#if defined(GUEST_ARM64) +// ARM64 sigcontext matches Linux kernel (arch/arm64/include/uapi/asm/sigcontext.h) +#define FPSIMD_MAGIC 0x46508001 +#define ESR_MAGIC 0x45535201 + +// FPSIMD context within the sigcontext extension area +struct fpsimd_context_ { + uint32_t magic; + uint32_t size; + uint32_t fpsr; + uint32_t fpcr; + __uint128_t vregs[32]; +}; + +struct sigcontext_ { + uint64_t fault_address; // This was missing! + uint64_t regs[31]; + uint64_t sp; + uint64_t pc; + uint64_t pstate; + // Extension area for FPSIMD/ESR/SVE records. Linux arm64 aligns this area + // to 16 bytes, which also makes ucontext.uc_mcontext land at offset 176 + // for musl/glibc aarch64. HotSpot's signal handler relies on that ABI + // layout for implicit null-check recovery. + uint8_t __reserved[4096] __attribute__((aligned(16))); +}; + +struct ucontext_ { + uint64_t flags; + uint64_t link; + struct stack_t_ stack; + sigset_t_ sigmask; + uint8_t __padding[128 - sizeof(sigset_t_)]; // Pad to fixed offset + struct sigcontext_ mcontext; +}; + +struct sigframe_ { + addr_t restorer; + dword_t sig; + struct sigcontext_ sc; + dword_t extramask; + char retcode[8]; +}; + +struct rt_sigframe_ { + addr_t restorer; + int_t sig; + addr_t pinfo; + addr_t puc; + union { + struct siginfo_ info; + char __pad[128]; + }; + struct ucontext_ uc; + char retcode[8]; +}; +#else +struct sigcontext_ { + word_t gs, __gsh; + word_t fs, __fsh; + word_t es, __esh; + word_t ds, __dsh; + dword_t di; + dword_t si; + dword_t bp; + dword_t sp; + dword_t bx; + dword_t dx; + dword_t cx; + dword_t ax; + dword_t trapno; + dword_t err; + dword_t ip; + word_t cs, __csh; + dword_t flags; + dword_t sp_at_signal; + word_t ss, __ssh; + + dword_t fpstate; + dword_t oldmask; + dword_t cr2; +}; + +struct ucontext_ { + uint_t flags; + uint_t link; + struct stack_t_ stack; + struct sigcontext_ mcontext; + sigset_t_ sigmask; +} __attribute__((packed)); + +struct fpreg_ { + word_t significand[4]; + word_t exponent; +}; + +struct fpxreg_ { + word_t significand[4]; + word_t exponent; + word_t padding[3]; +}; + +struct xmmreg_ { + uint32_t element[4]; +}; + +struct fpstate_ { + /* Regular FPU environment. */ + dword_t cw; + dword_t sw; + dword_t tag; + dword_t ipoff; + dword_t cssel; + dword_t dataoff; + dword_t datasel; + struct fpreg_ st[8]; + word_t status; + word_t magic; + + /* FXSR FPU environment. */ + dword_t _fxsr_env[6]; + dword_t mxcsr; + dword_t reserved; + struct fpxreg_ fxsr_st[8]; + struct xmmreg_ xmm[8]; + dword_t padding[56]; +}; + +struct sigframe_ { + addr_t restorer; + dword_t sig; + struct sigcontext_ sc; + struct fpstate_ fpstate; + dword_t extramask; + char retcode[8]; +}; + +struct rt_sigframe_ { + addr_t restorer; + int_t sig; + addr_t pinfo; + addr_t puc; + union { + struct siginfo_ info; + char __pad[128]; + }; + struct ucontext_ uc; + char retcode[8]; +}; +#endif + +// On a 64-bit system with 32-bit emulation, the fpu state is stored in extra +// space at the end of the frame, not in the frame itself. We store the fpu +// state in the frame where it should be, and ptraceomatic will set this. If +// they are set we'll add some padding to the bottom to the frame to make +// everything align. +extern int xsave_extra; +extern int fxsave_extra; + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/task.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/task.c new file mode 100644 index 0000000000..00523fc848 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/task.c @@ -0,0 +1,252 @@ +#define _GNU_SOURCE +#include <pthread.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include "kernel/calls.h" +#include "kernel/task.h" +#include "kernel/memory.h" +#include "emu/tlb.h" +#include "platform/platform.h" + +__thread struct task *current; + +static struct pid pids[MAX_PID + 1] = {}; +lock_t pids_lock = LOCK_INITIALIZER; + +static bool pid_empty(struct pid *pid) { + return pid->task == NULL && list_empty(&pid->session) && list_empty(&pid->pgroup); +} + +struct pid *pid_get(dword_t id) { + if (id > sizeof(pids)/sizeof(pids[0])) + return NULL; + struct pid *pid = &pids[id]; + if (pid_empty(pid)) + return NULL; + return pid; +} + +struct task *pid_get_task_zombie(dword_t id) { + struct pid *pid = pid_get(id); + if (pid == NULL) + return NULL; + struct task *task = pid->task; + return task; +} + +struct task *pid_get_task(dword_t id) { + struct task *task = pid_get_task_zombie(id); + if (task != NULL && task->zombie) + return NULL; + return task; +} + +struct task *task_create_(struct task *parent) { + lock(&pids_lock); + static int cur_pid = 0; + do { + cur_pid++; + if (cur_pid > MAX_PID) cur_pid = 1; + } while (!pid_empty(&pids[cur_pid])); + struct pid *pid = &pids[cur_pid]; + pid->id = cur_pid; + list_init(&pid->session); + list_init(&pid->pgroup); + + struct task *task = malloc(sizeof(struct task)); + if (task == NULL) + return NULL; + *task = (struct task) {}; + if (parent != NULL) + *task = *parent; + task->pid = pid->id; + pid->task = task; + +#ifdef GUEST_ARM64 + // Invalidate exclusive monitor after copying parent state. + // Child must not inherit parent's reservation, as any context switch or + // interrupt (including fork/clone) invalidates exclusive state. + task->cpu.excl_addr = UINT64_MAX; + task->cpu.excl_pair_addr = UINT64_MAX; + task->cpu.excl_pair_size = 0; +#endif + + // The poke flag must not be inherited: poked_ptr would alias the parent's + // _poked byte (cross-task pokes), and a copied _poked=true seeds a + // permanent one-interrupt-per-block storm in the child. + task->cpu.poked_ptr = &task->cpu._poked; + task->cpu._poked = false; + + // Initialize blocking state for deadlock detection. + task->blocking = false; + { + struct timespec start_time; + clock_gettime(CLOCK_MONOTONIC, &start_time); + task->last_unblocked_ns = (uint64_t)start_time.tv_sec * 1000000000ULL + start_time.tv_nsec; + task->start_time_ticks = (uint64_t)start_time.tv_sec * 100 + start_time.tv_nsec / 10000000; + } + list_init(&task->children); + list_init(&task->siblings); + if (parent != NULL) { + task->parent = parent; + list_add(&parent->children, &task->siblings); + } + unlock(&pids_lock); + + task->pending = 0; + list_init(&task->queue); + task->clear_tid = 0; + task->robust_list = 0; + task->rseq_addr = 0; + task->rseq_len = 0; + task->rseq_sig = 0; + task->rseq_registered = false; + task->futex_pipe[0] = -1; + task->futex_pipe[1] = -1; + task->did_exec = false; + lock_init(&task->general_lock); + + task->sockrestart = (struct task_sockrestart) {}; + list_init(&task->sockrestart.listen); + + task->waiting_cond = NULL; + task->waiting_lock = NULL; + lock_init(&task->waiting_cond_lock); + cond_init(&task->pause); + + lock_init(&task->ptrace.lock); + cond_init(&task->ptrace.cond); + return task; +} + +// Deferred-free list for task structs. +// When a task is destroyed, its struct is not immediately freed — instead it's +// placed on this list. The NEXT call to task_destroy will free previously +// deferred structs. This gives leaked/exiting pthreads time to finish accessing +// `current` before the memory is recycled by malloc, preventing use-after-free +// heap corruption. +#define DEFERRED_FREE_MAX 64 +static struct task *deferred_free_list[DEFERRED_FREE_MAX]; +static int deferred_free_count = 0; +// Must be called with pids_lock held (task_destroy already requires this). +static void flush_deferred_frees(void) { + for (int i = 0; i < deferred_free_count; i++) { + free(deferred_free_list[i]); + deferred_free_list[i] = NULL; + } + deferred_free_count = 0; +} + +void task_destroy(struct task *task) { + list_remove(&task->siblings); + pid_get(task->pid)->task = NULL; + + // Flush old deferred frees first — they've had time to quiesce. + flush_deferred_frees(); + + // Zero the struct to poison stale `current` references, then defer the + // actual free. This way if a leaked pthread is still running, it will + // hit zeroed fields (NULL group, NULL mem) and crash cleanly rather than + // silently corrupting a newly-allocated task at the same address. + memset(task, 0, sizeof(struct task)); + + if (deferred_free_count < DEFERRED_FREE_MAX) { + deferred_free_list[deferred_free_count++] = task; + } else { + // Overflow — free immediately (rare, only with 64+ concurrent exits) + free(task); + } +} + +static void task_run_tlb_cleanup(void *arg) { + tlb_free((struct tlb *)arg); + // [T-ish-mm-leak-refcount-handoff] If the do_exit_group safety valve + // orphaned this thread (stuck in an uninterruptible host syscall) it + // deferred the mm_release to here — this runs only when the host pthread + // actually terminates, i.e. AFTER the thread has left the read_wrlock + // critical section, so releasing now can't UAF the mem lock. This reclaims + // the whole guest address space instead of leaking it forever. `current` + // is a __thread TLS pointer, still valid inside pthread cleanup. + struct task *self = current; + if (self != NULL && self->mm_release_deferred && self->mm != NULL) { + self->mm_release_deferred = false; + mm_release(self->mm); + self->mm = NULL; + self->mem = NULL; + } +} + +void task_run_current() { + struct cpu_state *cpu = ¤t->cpu; + struct tlb *tlb = calloc(1, sizeof(struct tlb)); + if (!tlb) die("could not allocate TLB"); + + // Register cleanup so the TLB (and its fiber_frame) is freed even when + // the thread exits via pthread_exit() from deep in handle_interrupt() + // (e.g. do_exit() after a native-offloaded execve, or SIGKILL path). + // Without this, every guest process leaks ~304KB of TLB + ~48KB of + // fiber_frame, dominating app memory after repeated ffmpeg invocations. + pthread_cleanup_push(task_run_tlb_cleanup, tlb); + + while (true) { + // Check for group exit before entering JIT — this catches threads + // returning from blocking host syscalls (futex, nanosleep, etc.) + // that were interrupted by SIGUSR1 from do_exit_group. + // Also bail if our task struct was destroyed (current zeroed or NULLed). + struct task *self = current; + if (self == NULL || self->group == NULL) { + // Task struct was destroyed under us (leaked thread). + // Exit the host thread silently; cleanup handler frees tlb. + pthread_exit(NULL); + } + if (self->group->doing_group_exit) { + do_exit(self->group->group_exit_code); + } + if (self->mem == NULL) { + pthread_exit(NULL); + } + read_wrlock(&self->mem->lock); + tlb_refresh(tlb, &self->mem->mmu); + int interrupt = cpu_run_to_interrupt(cpu, tlb); + read_wrunlock(&self->mem->lock); + handle_interrupt(interrupt); + } + + // Never reached in practice (loop only exits via pthread_exit/do_exit), + // but the pop is required for pthread_cleanup_push/pop balance. + pthread_cleanup_pop(1); +} + +static void *task_thread(void *vtask) { + current = vtask; + update_thread_name(); + task_run_current(); + die("task_thread returned"); // above function call should never return +} + +static pthread_attr_t task_thread_attr; +__attribute__((constructor)) static void create_attr() { + pthread_attr_init(&task_thread_attr); + pthread_attr_setdetachstate(&task_thread_attr, PTHREAD_CREATE_DETACHED); +} + +void task_start(struct task *task) { + if (pthread_create(&task->thread, &task_thread_attr, task_thread, task) < 0) + die("could not create thread"); +} + +int_t sys_sched_yield() { + STRACE("sched_yield()"); + sched_yield(); + return 0; +} + +void update_thread_name() { + char name[16]; // As long as Linux will let us make this + snprintf(name, sizeof(name), "-%d", current->pid); + size_t pid_width = strlen(name); + size_t name_width = snprintf(name, sizeof(name), "%s", current->comm); + sprintf(name + (name_width < sizeof(name) - 1 - pid_width ? name_width : sizeof(name) - 1 - pid_width), "-%d", current->pid); + platform_set_thread_name(name); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/task.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/task.h new file mode 100644 index 0000000000..1606be3eab --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/task.h @@ -0,0 +1,258 @@ +#ifndef TASK_H +#define TASK_H + +#include <pthread.h> +#include "emu/cpu.h" +#include "kernel/mm.h" +#include "kernel/fs.h" +#include "kernel/signal.h" +#include "kernel/resource.h" +#include "fs/sockrestart.h" +#include "util/list.h" +#include "util/timer.h" +#include "util/sync.h" + +// everything here is private to the thread executing this task and needs no +// locking, unless otherwise specified +struct task { + struct cpu_state cpu; + struct mm *mm; // locked by general_lock + struct mem *mem; // pointer to mm.mem, for convenience + pthread_t thread; + uint64_t threadid; + + struct tgroup *group; // immutable + struct list group_links; + pid_t_ pid, tgid; // immutable + uint64_t start_time_ticks; // immutable, Linux USER_HZ (100 ticks/second) + uid_t_ uid, gid; + uid_t_ euid, egid; + uid_t_ suid, sgid; +#define MAX_GROUPS 32 + unsigned ngroups; + uid_t_ groups[MAX_GROUPS]; + char comm[16] __strncpy_safe; // locked by general_lock + bool did_exec; // for that one annoying setsid edge case + + struct fdtable *files; + struct fs_info *fs; + + // locked by sighand->lock + struct sighand *sighand; + // Linux sigaltstack state is per-thread, not shared with the signal-action + // table. Runtimes such as Go install one alternate signal stack per M/thread; + // sharing this through sighand corrupts signal delivery between threads. + addr_t altstack; + dword_t altstack_size; + sigset_t_ blocked; + sigset_t_ pending; + sigset_t_ waiting; // if nonzero, an ongoing call to sigtimedwait is waiting on these + struct list queue; + cond_t pause; // please don't signal this + // private + sigset_t_ saved_mask; + bool has_saved_mask; + + // Set when thread is in a blocking syscall (futex_wait, poll_wait, etc.) + // Used for deadlock detection: if all threads are blocking, it's a hang. + bool blocking; + // Per-thread pipe for futex_wait wakeup (reused across calls to avoid + // pipe creation overhead in Go runtime spin loops) + int futex_pipe[2]; // [0]=read, [1]=write; -1 if not yet created + // Timestamp (CLOCK_MONOTONIC ns) of last time blocking became false. + // Used by deadlock detector to check how long ALL threads have been stuck. + uint64_t last_unblocked_ns; + + struct { + // Locks all ptrace-related things + lock_t lock; + cond_t cond; + + bool traced; + bool stopped; + int signal; + struct siginfo_ info; + int trap_event; + } ptrace; + + // locked by pids_lock + struct task *parent; + struct list children; + struct list siblings; + + addr_t clear_tid; + addr_t robust_list; + addr_t rseq_addr; + dword_t rseq_len; + dword_t rseq_sig; + bool rseq_registered; + + // SA_RESTART support: on each syscall entry we snapshot the number and the + // first arg (x0/ebx), which the return value overwrites. If the syscall is + // interrupted (returns EINTR) and a signal with SA_RESTART is then + // delivered, receive_signals rewinds PC to the syscall instruction and + // restores the original first arg so the syscall re-executes — matching + // Linux. Without it, JSC's SIGPWR-based GC safepoint handshake (which + // registers SA_RESTART) livelocks on a futex that keeps returning EINTR. + unsigned syscall_restart_num; + uint64_t syscall_restart_arg0; + uint64_t syscall_restart_pc; // cpu.pc at syscall entry (== svc_addr+4); the + // SA_RESTART rewind only fires when cpu.pc still + // equals this, so a stale syscall_restartable + // flag can't corrupt PC on a later interrupt. + bool syscall_restartable; // this syscall returned EINTR and may restart + + // locked by pids_lock + dword_t exit_code; + bool zombie; + bool exiting; + // [T-ish-mm-leak-refcount-handoff] Set by the do_exit_group safety valve + // when it orphans a thread stuck in an uninterruptible host syscall: the + // valve can't mm_release() now (the thread may still hold mem->lock inside + // user_write → UAF, see T-ish-mem-uaf-user-write), so it hands the release + // off to this thread's own pthread cleanup handler, which runs only after + // the thread has left the read_wrlock critical section. Prevents the mm + // (whole guest address space) from leaking forever when the thread never + // re-enters do_exit(). Cleared once released so it never double-frees. + bool mm_release_deferred; + + // this structure is allocated on the stack of the parent's clone() call + struct vfork_info { + bool done; + cond_t cond; + lock_t lock; + } *vfork; + int exit_signal; + + // lock for anything that needs locking but is not covered by some other lock + // specifically: comm, mm + lock_t general_lock; + + struct task_sockrestart sockrestart; + + // Native offload: when is_native_proxy is true, this task is waiting + // for a host-native process instead of running emulated code. + pid_t native_pid; + bool is_native_proxy; + + // current condition/lock, so it can be notified in case of a signal + cond_t *waiting_cond; + lock_t *waiting_lock; + lock_t waiting_cond_lock; +}; + +// current will always give the process that is currently executing +// if I have to stop using __thread, current will become a macro +extern __thread struct task *current; + +static inline void task_set_mm(struct task *task, struct mm *mm) { + task->mm = mm; + task->mem = &task->mm->mem; + task->cpu.mmu = &task->mem->mmu; +} + +// Creates a new process, initializes most fields from the parent. Specify +// parent as NULL to create the init process. Returns NULL if out of memory. +// Ends with an underscore because there's a mach function by the same name +struct task *task_create_(struct task *parent); +// Removes the process from the process table and frees it. Must be called with pids_lock. +void task_destroy(struct task *task); + +// misc +void vfork_notify(struct task *task); +pid_t_ task_setsid(struct task *task); +void task_leave_session(struct task *task); + +struct posix_timer { + struct timer *timer; + int_t timer_id; + struct tgroup *tgroup; + pid_t_ thread_pid; + int_t signal; + union sigval_ sig_value; +}; + +// struct thread_group is way too long to type comfortably +struct tgroup { + struct list threads; // locked by pids_lock, by majority vote + struct task *leader; // immutable + struct rusage_ rusage; + + // locked by pids_lock + pid_t_ sid, pgid; + struct list session; + struct list pgroup; + + bool stopped; + cond_t stopped_cond; + + struct tty *tty; + struct timer *itimer; +#define TIMERS_MAX 16 + struct posix_timer posix_timers[TIMERS_MAX]; + + struct rlimit_ limits[RLIMIT_NLIMITS_]; + + // From https://twitter.com/tblodt/status/957706819236904960 + // > there are two distinct ways for a p̶r̶o̶c̶e̶s̶s̶ thread group to exit: + // > + // > - each thread calls exit + // > wait will return the exit code for the group leader + // > + // > - any thread calls exit_group + // > the SIGNAL_GROUP_EXIT flag will be set and wait will return the status passed to exit_group + // + // TODO locking + bool doing_group_exit; + dword_t group_exit_code; + + struct rusage_ children_rusage; + cond_t child_exit; + + dword_t personality; + + // Monotonically increasing syscall counter for deadlock detection. + atomic_uint syscall_count; + + // Timestamp of last real progress (non-blocking syscall completion). + // Updated atomically. Used by futex/poll safety valves to detect + // process-wide hangs where all threads are idle. + _Atomic uint64_t last_progress_ns; + + // for everything in this struct not locked by something else + lock_t lock; +}; + +static inline bool task_is_leader(struct task *task) { + return task->group->leader == task; +} + +struct pid { + dword_t id; + struct task *task; + struct list session; + struct list pgroup; +}; + +// synchronizes obtaining a pointer to a task and freeing that task +extern lock_t pids_lock; +// these functions must be called with pids_lock +struct pid *pid_get(dword_t pid); +struct task *pid_get_task(dword_t pid); +struct task *pid_get_task_zombie(dword_t id); // don't return null if the task exists as a zombie + +#define MAX_PID (1 << 15) // oughta be enough + +// TODO document +void task_start(struct task *task); +void task_run_current(void); + +extern void (*exit_hook)(struct task *task, int code); + +#define superuser() (current != NULL && current->euid == 0) + +// Update the thread name to match the current task, in the format "comm-pid". +// Will ensure that the -pid part always fits, then will fit as much of comm as possible. +void update_thread_name(void); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/time.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/time.c new file mode 100644 index 0000000000..743eb16ca5 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/time.c @@ -0,0 +1,600 @@ +#include "debug.h" +#include <time.h> +#include <signal.h> +#include <sched.h> +#include <sys/time.h> +#include "kernel/calls.h" +#include "kernel/errno.h" +#include "kernel/resource.h" +#include "kernel/time.h" +#include "fs/poll.h" + +#define TIMER_ABSTIME_ (1 << 0) + +static int clockid_to_real(uint_t clock, clockid_t *real) { + switch (clock) { + case CLOCK_REALTIME_: + case CLOCK_REALTIME_COARSE_: + *real = CLOCK_REALTIME; break; + case CLOCK_MONOTONIC_: + case CLOCK_MONOTONIC_RAW_: + case CLOCK_MONOTONIC_COARSE_: + case CLOCK_BOOTTIME_: + *real = CLOCK_MONOTONIC; break; + default: return _EINVAL; + } + return 0; +} + +static struct timer_spec timer_spec_to_real(struct itimerspec_ itspec) { + struct timer_spec spec = { + .value.tv_sec = itspec.value.sec, + .value.tv_nsec = itspec.value.nsec, + .interval.tv_sec = itspec.interval.sec, + .interval.tv_nsec = itspec.interval.nsec, + }; + return spec; +}; + +static struct itimerspec_ timer_spec_from_real(struct timer_spec spec) { + struct itimerspec_ itspec = { + .value.sec = spec.value.tv_sec, + .value.nsec = spec.value.tv_nsec, + .interval.sec = spec.interval.tv_sec, + .interval.nsec = spec.interval.tv_nsec, + }; + return itspec; +}; + +dword_t sys_time(addr_t time_out) { + dword_t now = time(NULL); + if (time_out != 0) + if (user_put(time_out, now)) + return _EFAULT; + return now; +} + +dword_t sys_stime(addr_t UNUSED(time)) { + return _EPERM; +} + +dword_t sys_clock_gettime(dword_t clock, addr_t tp) { + STRACE("clock_gettime(%d, 0x%x)", clock, tp); + + struct timespec ts; + if (clock == CLOCK_PROCESS_CPUTIME_ID_) { + // FIXME this is thread usage, not process usage + struct rusage_ rusage = rusage_get_current(); + ts.tv_sec = rusage.utime.sec; + ts.tv_nsec = rusage.utime.usec * 1000; + } else { + clockid_t clock_id; + if (clockid_to_real(clock, &clock_id)) return _EINVAL; + int err = clock_gettime(clock_id, &ts); + if (err < 0) + return errno_map(); + } + struct timespec_ t; + t.sec = ts.tv_sec; + t.nsec = ts.tv_nsec; + if (user_put(tp, t)) + return _EFAULT; + STRACE(" {%llds %lldns}", (long long)t.sec, (long long)t.nsec); + return 0; +} + +dword_t sys_clock_getres(dword_t clock, addr_t res_addr) { + STRACE("clock_getres(%d, %#x)", clock, res_addr); + clockid_t clock_id; + if (clockid_to_real(clock, &clock_id)) return _EINVAL; + + struct timespec res; + int err = clock_getres(clock_id, &res); + if (err < 0) + return errno_map(); + struct timespec_ t; + t.sec = res.tv_sec; + t.nsec = res.tv_nsec; + if (user_put(res_addr, t)) + return _EFAULT; + return 0; +} + +dword_t sys_clock_settime(dword_t UNUSED(clock), addr_t UNUSED(tp)) { + return _EPERM; +} + +static void itimer_notify(struct task *task) { + struct siginfo_ info = { + .code = SI_TIMER_, + }; + send_signal(task, SIGALRM_, info); +} + +static int itimer_set(struct tgroup *group, int which, struct timer_spec spec, struct timer_spec *old_spec) { + if (which != ITIMER_REAL_) { + FIXME("unimplemented setitimer %d", which); + return _EINVAL; + } + + if (!group->itimer) { + struct timer *timer = timer_new(CLOCK_REALTIME, (timer_callback_t) itimer_notify, current); + if (IS_ERR(timer)) + return PTR_ERR(timer); + group->itimer = timer; + } + + return timer_set(group->itimer, spec, old_spec); +} + +int_t sys_setitimer(int_t which, addr_t new_val_addr, addr_t old_val_addr) { + struct itimerval_ val; + if (user_get(new_val_addr, val)) + return _EFAULT; + STRACE("setitimer(%d, {%llds %lldus, %llds %lldus}, 0x%x)", + which, + (long long)val.value.sec, (long long)val.value.usec, + (long long)val.interval.sec, (long long)val.interval.usec, + old_val_addr); + + struct timer_spec spec = { + .interval.tv_sec = val.interval.sec, + .interval.tv_nsec = val.interval.usec * 1000, + .value.tv_sec = val.value.sec, + .value.tv_nsec = val.value.usec * 1000, + }; + struct timer_spec old_spec; + + struct tgroup *group = current->group; + lock(&group->lock); + int err = itimer_set(group, which, spec, &old_spec); + unlock(&group->lock); + if (err < 0) + return err; + + if (old_val_addr != 0) { + struct itimerval_ old_val; + old_val.interval.sec = old_spec.interval.tv_sec; + old_val.interval.usec = old_spec.interval.tv_nsec / 1000; + old_val.value.sec = old_spec.value.tv_sec; + old_val.value.usec = old_spec.value.tv_nsec / 1000; + if (user_put(old_val_addr, old_val)) + return _EFAULT; + } + + return 0; +} + +uint_t sys_alarm(uint_t seconds) { + STRACE("alarm(%d)", seconds); + struct timer_spec spec = { + .value.tv_sec = seconds, + }; + struct timer_spec old_spec; + + struct tgroup *group = current->group; + lock(&group->lock); + int err = itimer_set(group, ITIMER_REAL_, spec, &old_spec); + unlock(&group->lock); + if (err < 0) + return err; + + // Round up, and make sure to not return 0 if old_spec is > 0 + seconds = old_spec.value.tv_sec; + if (old_spec.value.tv_nsec >= 500000000) + seconds++; + if (seconds == 0 && !timespec_is_zero(old_spec.value)) + seconds = 1; + return seconds; +} + +dword_t sys_nanosleep(addr_t req_addr, addr_t rem_addr) { + struct timespec_ req_ts; + if (user_get(req_addr, req_ts)) + return _EFAULT; + STRACE("nanosleep({%lld, %lld}, 0x%x", (long long)req_ts.sec, (long long)req_ts.nsec, rem_addr); + + // Short-circuit for ≤1ms sleeps (common in Go runtime timer management) + if (req_ts.sec == 0 && req_ts.nsec <= 1000000) { + sched_yield(); + if (rem_addr != 0) { + struct timespec_ rem_ts = {.sec = 0, .nsec = 0}; + if (user_put(rem_addr, rem_ts)) + return _EFAULT; + } + return 0; + } + + struct timespec req; + req.tv_sec = req_ts.sec; + req.tv_nsec = req_ts.nsec; + struct timespec rem; + if (nanosleep(&req, &rem) < 0) + return errno_map(); + if (rem_addr != 0) { + struct timespec_ rem_ts; + rem_ts.sec = rem.tv_sec; + rem_ts.nsec = rem.tv_nsec; + if (user_put(rem_addr, rem_ts)) + return _EFAULT; + } + return 0; +} + +dword_t sys_clock_nanosleep(dword_t clock, dword_t flags, addr_t req_addr, addr_t rem_addr) { + struct timespec_ req_ts; + if (user_get(req_addr, req_ts)) + return _EFAULT; + STRACE("clock_nanosleep(%d, %d, {%lld, %lld}, 0x%x)", clock, flags, + (long long)req_ts.sec, (long long)req_ts.nsec, rem_addr); + + clockid_t real_clock; + if (clockid_to_real(clock, &real_clock)) + return _EINVAL; + + struct timespec req; + req.tv_sec = req_ts.sec; + req.tv_nsec = req_ts.nsec; + + if (flags & TIMER_ABSTIME_) { + // Convert absolute time to relative by subtracting current time + struct timespec now; + if (clock_gettime(real_clock, &now) < 0) + return errno_map(); + req.tv_sec -= now.tv_sec; + req.tv_nsec -= now.tv_nsec; + if (req.tv_nsec < 0) { + req.tv_sec--; + req.tv_nsec += 1000000000; + } + if (req.tv_sec < 0) + return 0; // Already past the target time + } + + struct timespec rem; + if (nanosleep(&req, &rem) < 0) + return errno_map(); + if (rem_addr != 0 && !(flags & TIMER_ABSTIME_)) { + struct timespec_ rem_ts; + rem_ts.sec = rem.tv_sec; + rem_ts.nsec = rem.tv_nsec; + if (user_put(rem_addr, rem_ts)) + return _EFAULT; + } + return 0; +} + +dword_t sys_times(addr_t tbuf) { + STRACE("times(0x%x)", tbuf); + if (tbuf) { + struct tms_ tmp; + struct rusage_ rusage = rusage_get_current(); + tmp.tms_utime = clock_from_timeval(rusage.utime); + tmp.tms_stime = clock_from_timeval(rusage.stime); + tmp.tms_cutime = tmp.tms_utime; + tmp.tms_cstime = tmp.tms_stime; + if (user_put(tbuf, tmp)) + return _EFAULT; + } + return 0; +} + +dword_t sys_gettimeofday(addr_t tv, addr_t tz) { + STRACE("gettimeofday(0x%x, 0x%x)", tv, tz); + struct timeval timeval; + struct timezone timezone; + if (gettimeofday(&timeval, &timezone) < 0) { + return errno_map(); + } + struct timeval_ tv_; + struct timezone_ tz_; + tv_.sec = timeval.tv_sec; + tv_.usec = timeval.tv_usec; + tz_.minuteswest = timezone.tz_minuteswest; + tz_.dsttime = timezone.tz_dsttime; + if ((tv && user_put(tv, tv_)) || (tz && user_put(tz, tz_))) { + return _EFAULT; + } + return 0; +} + +dword_t sys_settimeofday(addr_t UNUSED(tv), addr_t UNUSED(tz)) { + return _EPERM; +} + +static void posix_timer_callback(struct posix_timer *timer) { + if (timer->tgroup == NULL) + return; + struct siginfo_ info = { + .code = SI_TIMER_, + .timer.timer = timer->timer_id, + .timer.overrun = 0, + .timer.value = timer->sig_value, + }; + lock(&pids_lock); + struct task *thread = pid_get_task(timer->thread_pid); + // TODO: solve pid reuse. currently we have two ways of referring to a task: pid_t_ and struct task *. pids get reused. task struct pointers get freed on exit or reap. need a third option for cases like this, like a refcount layer. + if (thread != NULL) + send_signal(thread, timer->signal, info); + unlock(&pids_lock); +} + +#define SIGEV_SIGNAL_ 0 +#define SIGEV_NONE_ 1 +#define SIGEV_THREAD_ID_ 4 + +int_t sys_timer_create(dword_t clock, addr_t sigevent_addr, addr_t timer_addr) { + STRACE("timer_create(%d, %#x, %#x)", clock, sigevent_addr, timer_addr); + clockid_t real_clockid; + if (clockid_to_real(clock, &real_clockid)) + return _EINVAL; + struct sigevent_ sigev; + if (sigevent_addr == 0) { + // NULL sigevent: POSIX/Linux default is SIGEV_SIGNAL delivering SIGALRM + // to the process, with sival_int = timer id. musl's timer_create passes + // NULL for the common `timer_create(clock, NULL, &id)` form (e.g. + // coreutils `timeout`). iSH used to user_get(NULL) → EFAULT here, so + // every such call failed spuriously. + sigev = (struct sigevent_){0}; + sigev.method = SIGEV_SIGNAL_; + sigev.signo = SIGALRM_; + } else if (user_get(sigevent_addr, sigev)) { + return _EFAULT; + } + if (sigev.method != SIGEV_SIGNAL_ && sigev.method != SIGEV_NONE_ && sigev.method != SIGEV_THREAD_ID_) + return _EINVAL; + + if (sigev.method == SIGEV_THREAD_ID_) { + lock(&pids_lock); + if (pid_get_task(sigev.tid) == NULL) + return _EINVAL; + unlock(&pids_lock); + } + + struct tgroup *group = current->group; + lock(&group->lock); + unsigned timer_id; + for (timer_id = 0; timer_id < TIMERS_MAX; timer_id++) { + if (group->posix_timers[timer_id].timer == NULL) + break; + } + if (timer_id >= TIMERS_MAX) { + unlock(&group->lock); + return _ENOMEM; + } + if (user_put(timer_addr, timer_id)) { + unlock(&group->lock); + return _EFAULT; + } + + struct posix_timer *timer = &group->posix_timers[timer_id]; + timer->timer_id = timer_id; + timer->timer = timer_new(real_clockid, (timer_callback_t) posix_timer_callback, timer); + timer->signal = sigev.signo; + timer->sig_value = sigev.value; + timer->tgroup = NULL; + if (sigev.method == SIGEV_SIGNAL_) { + timer->tgroup = group; + timer->thread_pid = 0; + } else if (sigev.method == SIGEV_THREAD_ID_) { + timer->tgroup = group; + timer->thread_pid = group->leader->pid; + } + unlock(&group->lock); + return 0; +} + +int_t sys_timer_settime(dword_t timer_id, int_t flags, addr_t new_value_addr, addr_t old_value_addr) { + STRACE("timer_settime(%d, %d, %#x, %#x)", timer_id, flags, new_value_addr, old_value_addr); + struct itimerspec_ value; + if (user_get(new_value_addr, value)) + return _EFAULT; + if (timer_id > TIMERS_MAX) + return _EINVAL; + + lock(¤t->group->lock); + struct posix_timer *timer = ¤t->group->posix_timers[timer_id]; + struct timer_spec spec = timer_spec_to_real(value); + struct timer_spec old_spec; + if (flags & TIMER_ABSTIME_) { + struct timespec now = timespec_now(timer->timer->clockid); + spec.value = timespec_subtract(spec.value, now); + } + int err = timer_set(timer->timer, spec, &old_spec); + unlock(¤t->group->lock); + if (err < 0) + return err; + + if (old_value_addr) { + struct itimerspec_ old_value = timer_spec_from_real(old_spec); + if (user_put(old_value_addr, old_value)) + return _EFAULT; + } + return 0; +} + +int_t sys_timer_gettime(dword_t timer_id, addr_t curr_value_addr) { + STRACE("timer_gettime(%d, %#x)", timer_id, curr_value_addr); + if (timer_id >= TIMERS_MAX) + return _EINVAL; + + lock(¤t->group->lock); + struct posix_timer *pt = ¤t->group->posix_timers[timer_id]; + if (pt->timer == NULL) { + unlock(¤t->group->lock); + return _EINVAL; + } + + struct timer_spec spec; + spec.interval = pt->timer->interval; + if (pt->timer->active) { + struct timespec now = timespec_now(pt->timer->clockid); + if (timespec_positive(timespec_subtract(pt->timer->end, now))) + spec.value = timespec_subtract(pt->timer->end, now); + else + spec.value = (struct timespec) {0, 0}; + } else { + spec.value = (struct timespec) {0, 0}; + } + unlock(¤t->group->lock); + + struct itimerspec_ value = timer_spec_from_real(spec); + if (user_put(curr_value_addr, value)) + return _EFAULT; + return 0; +} + +int_t sys_timer_getoverrun(dword_t timer_id) { + STRACE("timer_getoverrun(%d)", timer_id); + if (timer_id >= TIMERS_MAX) + return _EINVAL; + + lock(¤t->group->lock); + struct posix_timer *pt = ¤t->group->posix_timers[timer_id]; + if (pt->timer == NULL) { + unlock(¤t->group->lock); + return _EINVAL; + } + unlock(¤t->group->lock); + return 0; +} + +int_t sys_timer_delete(dword_t timer_id) { + STRACE("timer_delete(%d)\n", timer_id); + lock(¤t->group->lock); + struct posix_timer *timer = ¤t->group->posix_timers[timer_id]; + if (timer->timer == NULL) { + unlock(¤t->group->lock); + return _EINVAL; + } + timer_free(timer->timer); + timer->timer = NULL; + unlock(¤t->group->lock); + return 0; +} + +static struct fd_ops timerfd_ops; + +static void timerfd_callback(struct fd *fd) { + lock(&fd->lock); + fd->timerfd.expirations++; + notify(&fd->cond); + unlock(&fd->lock); + poll_wakeup(fd, POLL_READ); +} + +fd_t sys_timerfd_create(int_t clockid, int_t flags) { + STRACE("timerfd_create(%d, %#x)", clockid, flags); + clockid_t real_clockid; + if (clockid_to_real(clockid, &real_clockid)) return _EINVAL; + + struct fd *fd = adhoc_fd_create(&timerfd_ops); + if (fd == NULL) + return _ENOMEM; + + fd->timerfd.timer = timer_new(real_clockid, (timer_callback_t) timerfd_callback, fd); + return f_install(fd, flags); +} + +int_t sys_timerfd_settime(fd_t f, int_t flags, addr_t new_value_addr, addr_t old_value_addr) { + STRACE("timerfd_settime(%d, %d, %#x, %#x)", f, flags, new_value_addr, old_value_addr); + if (flags & ~(TIMER_ABSTIME_)) + return _EINVAL; + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + if (fd->ops != &timerfd_ops) + return _EINVAL; + struct itimerspec_ value; + if (user_get(new_value_addr, value)) + return _EFAULT; + struct timer_spec spec = timer_spec_to_real(value); + struct timer_spec old_spec; + if (flags & TIMER_ABSTIME_) { + struct timespec now = timespec_now(fd->timerfd.timer->clockid); + spec.value = timespec_subtract(spec.value, now); + } + + lock(&fd->lock); + int err = timer_set(fd->timerfd.timer, spec, &old_spec); + unlock(&fd->lock); + if (err < 0) + return err; + + if (old_value_addr) { + struct itimerspec_ old_value = timer_spec_from_real(old_spec); + if (user_put(old_value_addr, old_value)) + return _EFAULT; + } + + return 0; +} + +int_t sys_timerfd_gettime(fd_t f, addr_t curr_value_addr) { + STRACE("timerfd_gettime(%d, %#x)", f, curr_value_addr); + struct fd *fd = f_get(f); + if (fd == NULL) + return _EBADF; + if (fd->ops != &timerfd_ops) + return _EINVAL; + + struct timer_spec spec; + lock(&fd->lock); + spec.interval = fd->timerfd.timer->interval; + if (fd->timerfd.timer->active) { + struct timespec now = timespec_now(fd->timerfd.timer->clockid); + struct timespec remaining = timespec_subtract(fd->timerfd.timer->end, now); + if (timespec_positive(remaining)) + spec.value = remaining; + else + spec.value = (struct timespec) {0, 0}; + } else { + spec.value = (struct timespec) {0, 0}; + } + unlock(&fd->lock); + + struct itimerspec_ value = timer_spec_from_real(spec); + if (user_put(curr_value_addr, value)) + return _EFAULT; + return 0; +} + +static ssize_t timerfd_read(struct fd *fd, void *buf, size_t bufsize) { + if (bufsize < sizeof(uint64_t)) + return _EINVAL; + lock(&fd->lock); + while (fd->timerfd.expirations == 0) { + if (fd->flags & O_NONBLOCK_) { + unlock(&fd->lock); + return _EAGAIN; + } + int err = wait_for(&fd->cond, &fd->lock, NULL); + if (err < 0) { + unlock(&fd->lock); + return err; + } + } + + *(uint64_t *) buf = fd->timerfd.expirations; + fd->timerfd.expirations = 0; + unlock(&fd->lock); + return sizeof(uint64_t); +} +static int timerfd_poll(struct fd *fd) { + int res = 0; + lock(&fd->lock); + if (fd->timerfd.expirations != 0) + res |= POLL_READ; + unlock(&fd->lock); + return res; +} +static int timerfd_close(struct fd *fd) { + timer_free(fd->timerfd.timer); + return 0; +} + +static struct fd_ops timerfd_ops = { + .read = timerfd_read, + .poll = timerfd_poll, + .close = timerfd_close, +}; diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/time.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/time.h new file mode 100644 index 0000000000..b391c63c25 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/time.h @@ -0,0 +1,98 @@ +#ifndef TIME_H +#define TIME_H +#include "misc.h" + +dword_t sys_time(addr_t time_out); +dword_t sys_stime(addr_t time); +#define CLOCK_REALTIME_ 0 +#define CLOCK_MONOTONIC_ 1 +#define CLOCK_PROCESS_CPUTIME_ID_ 2 +#define CLOCK_MONOTONIC_RAW_ 4 +#define CLOCK_REALTIME_COARSE_ 5 +#define CLOCK_MONOTONIC_COARSE_ 6 +#define CLOCK_BOOTTIME_ 7 +dword_t sys_clock_gettime(dword_t clock, addr_t tp); +dword_t sys_clock_settime(dword_t clock, addr_t tp); +dword_t sys_clock_getres(dword_t clock, addr_t res_addr); + +#ifdef GUEST_ARM64 +struct timeval_ { + time_t_ sec; + sqword_t usec; +}; +struct timespec_ { + time_t_ sec; + sqword_t nsec; +}; +#else +struct timeval_ { + dword_t sec; + dword_t usec; +}; +struct timespec_ { + dword_t sec; + dword_t nsec; +}; +#endif +struct timezone_ { + dword_t minuteswest; + dword_t dsttime; +}; + +static inline clock_t_ clock_from_timeval(struct timeval_ timeval) { + return timeval.sec * 100 + timeval.usec / 10000; +} + +static inline struct timespec convert_timespec(struct timespec_ t) { + struct timespec ts; + ts.tv_sec = t.sec; + ts.tv_nsec = t.nsec; + return ts; +} + +static inline struct timespec convert_timeval(struct timeval_ t) { + struct timespec ts; + ts.tv_sec = t.sec; + ts.tv_nsec = t.usec * 1000; + return ts; +} + +#define ITIMER_REAL_ 0 +#define ITIMER_VIRTUAL_ 1 +#define ITIMER_PROF_ 2 +struct itimerval_ { + struct timeval_ interval; + struct timeval_ value; +}; + +struct itimerspec_ { + struct timespec_ interval; + struct timespec_ value; +}; + +struct tms_ { + clock_t_ tms_utime; /* user time */ + clock_t_ tms_stime; /* system time */ + clock_t_ tms_cutime; /* user time of children */ + clock_t_ tms_cstime; /* system time of children */ +}; + +int_t sys_setitimer(int_t which, addr_t new_val, addr_t old_val); +uint_t sys_alarm(uint_t seconds); +int_t sys_timer_create(dword_t clock, addr_t sigevent_addr, addr_t timer_addr); +int_t sys_timer_settime(dword_t timer, int_t flags, addr_t new_value_addr, addr_t old_value_addr); +int_t sys_timer_gettime(dword_t timer_id, addr_t curr_value_addr); +int_t sys_timer_getoverrun(dword_t timer_id); +int_t sys_timer_delete(dword_t timer_id); +fd_t sys_timerfd_create(int_t clockid, int_t flags); +int_t sys_timerfd_settime(fd_t f, int_t flags, addr_t new_value_addr, addr_t old_value_addr); +int_t sys_timerfd_gettime(fd_t f, addr_t curr_value_addr); + +dword_t sys_times(addr_t tbuf); +dword_t sys_nanosleep(addr_t req, addr_t rem); +dword_t sys_clock_nanosleep(dword_t clock, dword_t flags, addr_t req, addr_t rem); +dword_t sys_gettimeofday(addr_t tv, addr_t tz); +dword_t sys_settimeofday(addr_t tv, addr_t tz); + + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/tls.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/tls.c new file mode 100644 index 0000000000..a8c077f870 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/tls.c @@ -0,0 +1,42 @@ +#include "kernel/calls.h" + +struct user_desc { + dword_t entry_number; + dword_t base_addr; + dword_t limit; + unsigned int seg_32bit:1; + unsigned int contents:2; + unsigned int read_exec_only:1; + unsigned int limit_in_pages:1; + unsigned int seg_not_present:1; + unsigned int useable:1; +}; + +int task_set_thread_area(struct task *task, addr_t u_info) { + struct user_desc info; + if (user_get_task(task, u_info, info)) + return _EFAULT; + + // On a real system, TLS works by creating a special segment pointing to + // the TLS buffer. The emulator models this by ignoring attempts to modify + // GS directly and adding this base address to memory references using GS. + task->cpu.tls_ptr = info.base_addr; + + if (info.entry_number == (unsigned) -1) { + info.entry_number = 0xc; + } + + if (user_put(u_info, info)) + return _EFAULT; + return 0; +} + +int sys_set_thread_area(addr_t u_info) { + STRACE("set_thread_area(0x%x)", u_info); + return task_set_thread_area(current, u_info); +} + +int sys_set_tid_address(addr_t tid) { + current->clear_tid = tid; + return sys_getpid(); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/uname.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/uname.c new file mode 100644 index 0000000000..802b75bdf5 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/uname.c @@ -0,0 +1,106 @@ +#include <sys/utsname.h> +#include <stdint.h> +#include <stdatomic.h> +#include <string.h> +#include "kernel/calls.h" +#include "platform/platform.h" + +#define SYSINFO_DEBUG 0 + +const char *uname_version = "Block Emulation"; +const char *uname_hostname_override = NULL; + +void do_uname(struct uname *uts) { + struct utsname real_uname; + uname(&real_uname); + const char *hostname = real_uname.nodename; + if (uname_hostname_override) + hostname = uname_hostname_override; + + memset(uts, 0, sizeof(struct uname)); + strcpy(uts->system, "Linux"); + strcpy(uts->hostname, hostname); + strcpy(uts->release, "4.20.69-linuxkit"); + snprintf(uts->version, sizeof(uts->version), "%s %s %s", uname_version, __DATE__, __TIME__); + strcpy(uts->arch, "aarch64"); + strcpy(uts->domain, "(none)"); +} + +dword_t sys_uname(addr_t uts_addr) { + struct uname uts; + do_uname(&uts); + if (user_put(uts_addr, uts)) + return _EFAULT; + return 0; +} + +dword_t sys_sethostname(addr_t UNUSED(hostname_addr), dword_t UNUSED(hostname_len)) { + return _EPERM; +} + +static void sysinfo_specific(struct sys_info *info) { + struct platform_sysinfo host_info = platform_get_sysinfo(); + uint64_t host_mem_unit = host_info.mem_unit ? host_info.mem_unit : 1; + info->procs = host_info.procs; + + // Cap reported RAM to avoid musl/V8 allocating enormous arenas. + // Must be consistent with MEMINFO_MAX_RAM in fs/proc/root.c. + // Go runtime needs ~1.1GB for page summaries; 4GB gives headroom. +#define GUEST_MAX_RAM (4ULL * 1024 * 1024 * 1024) + uint64_t total_bytes = host_info.totalram * host_mem_unit; + if (total_bytes > GUEST_MAX_RAM) + total_bytes = GUEST_MAX_RAM; + info->totalram = total_bytes; + info->sharedram = host_info.sharedram * host_mem_unit; + info->totalswap = host_info.totalswap * host_mem_unit; + info->freeswap = host_info.freeswap * host_mem_unit; + info->totalhigh = host_info.totalhigh * host_mem_unit; + info->freehigh = host_info.freehigh * host_mem_unit; + info->mem_unit = 1; + + // Report realistic free memory based on anon_page_count. + // Without this, freeram=0 makes runtimes think memory is exhausted. +#if ANON_MMAP_LIMIT_PAGES > 0 + extern _Atomic long anon_page_count; + long used_pages = atomic_load(&anon_page_count); + uint64_t used_bytes = (uint64_t)(used_pages > 0 ? used_pages : 0) * 4096; + info->freeram = used_bytes < total_bytes ? total_bytes - used_bytes : 0; +#else + info->freeram = total_bytes / 2; // fallback: report 50% free +#endif +} + +dword_t sys_sysinfo(addr_t info_addr) { + struct sys_info info = {0}; + struct uptime_info uptime = get_uptime(); + info.uptime = uptime.uptime_ticks; + info.loads[0] = uptime.load_1m; + info.loads[1] = uptime.load_5m; + info.loads[2] = uptime.load_15m; + sysinfo_specific(&info); + + // glibc static binaries sometimes call sysinfo with the __stack_chk_guard address + // as the buffer. This is a quirk of glibc's raise()/abort() implementation. + // The canary address is typically in .data.rel.ro section. + // We detect this by checking if the address is in that range and preserving + // the first 8 bytes (the canary value). + // + // Known canary address: 0x613870 for busybox-static (glibc) + // Check if this looks like a canary address by seeing if we'd overwrite + // a value that looks like a canary (high entropy, low byte is 0) + uint64_t existing_value = 0; + if (user_get(info_addr, existing_value) == 0) { + // Check if this looks like a canary: non-zero, low byte is 0 + if (existing_value != 0 && (existing_value & 0xFF) == 0) { + // Write sysinfo data starting AFTER the canary (skip first 8 bytes) + // This means info.uptime won't be written, which is acceptable + if (user_write(info_addr + 8, ((char*)&info) + 8, sizeof(info) - 8)) + return _EFAULT; + return 0; + } + } + + if (user_put(info_addr, info)) + return _EFAULT; + return 0; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/user.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/user.c new file mode 100644 index 0000000000..63a72a5fe9 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/user.c @@ -0,0 +1,119 @@ +#include <string.h> +#include "kernel/calls.h" + +// [T-ish-mem-uaf-user-write] Snapshot task->mem once, under an acquire load, +// and bail if it's NULL. The do_exit_group safety valve can concurrently +// force-release a stuck sibling's mm and set task->mem = NULL (exit.c). Reading +// task->mem twice (once for the NULL check, once for the lock) or dereferencing +// it unguarded races that store — the classic symptom is EXC_BAD_ACCESS at +// address 0x38 (= offsetof(struct mem, lock)) from read_wrlock(&NULL->lock) or +// a freed mem. Combined with the A-side fix (the safety valve now leaks the mm +// instead of freeing it), a non-NULL snapshot here is guaranteed to stay valid +// for the duration of the copy. +#define USER_MEM_OR_FAULT(task) ({ \ + struct mem *_m = __atomic_load_n(&(task)->mem, __ATOMIC_ACQUIRE); \ + if (_m == NULL) return 1; \ + _m; \ +}) + +// [T-ish-mem-uaf-user-write] These take an explicit `mem` snapshot (never read +// task->mem again inside) so the whole copy runs against one validated mem. +static int __user_read_mem(struct mem *mem, addr_t addr, void *buf, size_t count) { + char *cbuf = (char *) buf; + addr_t p = addr; + while (p < addr + count) { + addr_t chunk_end = (PAGE(p) + 1) << PAGE_BITS; + if (chunk_end > addr + count) + chunk_end = addr + count; + const char *ptr = mem_ptr(mem, p, MEM_READ); + if (ptr == NULL) + return 1; + memcpy(&cbuf[p - addr], ptr, chunk_end - p); + p = chunk_end; + } + return 0; +} + +static int __user_write_mem(struct mem *mem, addr_t addr, const void *buf, size_t count, bool ptrace) { + const char *cbuf = (const char *) buf; + addr_t p = addr; + while (p < addr + count) { + addr_t chunk_end = (PAGE(p) + 1) << PAGE_BITS; + if (chunk_end > addr + count) + chunk_end = addr + count; + char *ptr = mem_ptr(mem, p, ptrace ? MEM_WRITE_PTRACE : MEM_WRITE); + if (ptr == NULL) + return 1; + memcpy(ptr, &cbuf[p - addr], chunk_end - p); + p = chunk_end; + } + return 0; +} + +int user_read_task(struct task *task, addr_t addr, void *buf, size_t count) { + struct mem *mem = USER_MEM_OR_FAULT(task); + read_wrlock(&mem->lock); + int res = __user_read_mem(mem, addr, buf, count); + read_wrunlock(&mem->lock); + return res; +} + +int user_read(addr_t addr, void *buf, size_t count) { + return user_read_task(current, addr, buf, count); +} + +int user_write_task(struct task *task, addr_t addr, const void *buf, size_t count) { + struct mem *mem = USER_MEM_OR_FAULT(task); + read_wrlock(&mem->lock); + int res = __user_write_mem(mem, addr, buf, count, false); + read_wrunlock(&mem->lock); + return res; +} + +int user_write_task_ptrace(struct task *task, addr_t addr, const void *buf, size_t count) { + struct mem *mem = USER_MEM_OR_FAULT(task); + read_wrlock(&mem->lock); + int res = __user_write_mem(mem, addr, buf, count, true); + read_wrunlock(&mem->lock); + return res; +} + +int user_write(addr_t addr, const void *buf, size_t count) { + return user_write_task(current, addr, buf, count); +} + +int user_read_string(addr_t addr, char *buf, size_t max) { + if (addr == 0) + return 1; + struct mem *mem = USER_MEM_OR_FAULT(current); + read_wrlock(&mem->lock); + size_t i = 0; + while (i < max) { + if (__user_read_mem(mem, addr + i, &buf[i], sizeof(buf[i]))) { + read_wrunlock(&mem->lock); + return 1; + } + if (buf[i] == '\0') + break; + i++; + } + read_wrunlock(&mem->lock); + return 0; +} + +int user_write_string(addr_t addr, const char *buf) { + if (addr == 0) + return 1; + struct mem *mem = USER_MEM_OR_FAULT(current); + read_wrlock(&mem->lock); + size_t i = 0; + do { + if (__user_write_mem(mem, addr + i, &buf[i], sizeof(buf[i]), false)) { + read_wrunlock(&mem->lock); + return 1; + } + i++; + } while (buf[i - 1] != '\0'); + read_wrunlock(&mem->lock); + return 0; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/vdso.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/vdso.c new file mode 100644 index 0000000000..b3c55b1f58 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/vdso.c @@ -0,0 +1,58 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "kernel/elf.h" +#include "kernel/vdso.h" + +// The VDSO binary is included at compile time +// The include path is set by meson to point to the correct arch-specific directory +__asm__(".data\n" + ".global vdso_data\n" + "vdso_data:\n" + ".incbin \"libvdso.so.elf\"\n" + ".skip "str(VDSO_PAGES)" * (1 << 12) - (. - vdso_data)\n"); + +int vdso_symbol(const char *name) { + struct elf_header64 *header = (void *) vdso_data; + struct prg_header64 *ph = (void *) ((char *) header + header->prghead_off); + + // find the PT_DYNAMIC section + struct dyn_ent64 *dyn = NULL; + for (int i = 0; i < header->phent_count; i++) { + if (ph[i].type == PT_DYNAMIC) { + dyn = (void *) ((char *) header + ph[i].offset); + break; + } + } + if (dyn == NULL) + goto fail; + + // grab pointers to the symbols and the strings + char *strings = NULL; + struct elf_sym64 *syms = NULL; + uint32_t *hash = NULL; + for (; dyn->tag != DT_NULL; dyn++) { + void *p = (char *) header + dyn->val; + if (dyn->tag == DT_STRTAB) + strings = p; + else if (dyn->tag == DT_SYMTAB) + syms = p; + else if (dyn->tag == DT_HASH) + hash = p; + } + if (strings == NULL || syms == NULL || hash == NULL) + goto fail; + + // conveniently enough, the hashtable includes the number of symbols, which doesn't seeem to be anywhere else + // https://flapenguin.me/2017/04/24/elf-lookup-dt-hash/ + int num_syms = hash[1]; + for (int i = 0; i < num_syms; i++) { + char *sym_name = strings + syms[i].name; + if (strcmp(name, sym_name) == 0) + return (addr_t) syms[i].value; + } + return 0; // symbol not found + +fail: + return 0; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/vdso.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/vdso.h new file mode 100644 index 0000000000..6d471cab98 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/vdso.h @@ -0,0 +1,10 @@ +#ifndef KERNEL_VDSO_H +#define KERNEL_VDSO_H + +#define VVAR_PAGES 4 +#define VDSO_PAGES 2 + +extern const char vdso_data[VDSO_PAGES * (1 << 12)] __asm__("vdso_data"); +int vdso_symbol(const char *name); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/main.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/main.c new file mode 100644 index 0000000000..e7cc9ee1db --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/main.c @@ -0,0 +1,304 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <signal.h> +#include <stdbool.h> +#include <execinfo.h> +#include <termios.h> +#include <unistd.h> +#include <pthread.h> +#include <stddef.h> +#include <stdarg.h> +#include "kernel/calls.h" +#include "kernel/task.h" +#include "fs/path.h" +#include "emu/cpu.h" +#include "emu/tlb.h" +#include "asbestos/frame.h" +#include "asbestos/asbestos.h" +#include "platform/host_context_aarch64.h" +#include "xX_main_Xx.h" + +// Thread-local JIT recovery state (defined in asbestos.c) +extern __thread volatile sig_atomic_t in_jit; +extern __thread volatile uint64_t jit_saved_pc; + +// Diagnostic: JIT crash info (defined in calls.c) +extern __thread volatile uint64_t jit_last_host_fault; +extern __thread volatile uint64_t jit_last_x7; +extern __thread volatile uint64_t jit_last_x10; +extern __thread volatile int jit_crash_count; +extern volatile bool g_trace_highbits; +extern volatile bool g_trace_faults; + +int fakefs_bind_mount(const char *linux_path, const char *host_path, bool read_only); + +// Assembly trampoline: returns INT_JIT_CRASH via fiber_exit (defined in entry.S) +extern void jit_crash_trampoline(void); + +// Offsets needed by the async crash handler. Keep these derived from the C +// structs instead of hard-coding cpu-offsets.h values; the signal handler runs +// in C, and stale constants here corrupt JIT crash recovery when cpu_state or +// fiber_frame changes. +#define CRASH_CPU_pc offsetof(struct cpu_state, pc) +#define CRASH_CPU_segfault_addr offsetof(struct cpu_state, segfault_addr) +#define CRASH_CPU_segfault_was_write offsetof(struct cpu_state, segfault_was_write) +#define CRASH_LOCAL_jit_exit_sp offsetof(struct fiber_frame, jit_exit_sp) +#define CRASH_LOCAL_jit_saved_pc offsetof(struct fiber_frame, jit_saved_pc) + +static void crash_handler(int sig, siginfo_t *info, void *ctx) { +#ifdef __aarch64__ + // If we're inside JIT code and got SIGSEGV/SIGBUS, recover by redirecting + // execution to jit_crash_trampoline via ucontext PC manipulation. + // This avoids the overhead of _setjmp on every block entry. + if ((sig == SIGSEGV || sig == SIGBUS) && in_jit) { + ucontext_t *uc = (ucontext_t *)ctx; + + // _cpu is in x1 — pointer to cpu_state within fiber_frame + uint64_t cpu_ptr = host_ctx_aarch64_reg(uc, 1); + + // Reconstruct guest segfault_addr from registers. + // x7 = _addr (host pointer = data_minus_addr + guest_addr) + // x10 may hold data_minus_addr from TLB lookup (but only on TLB HIT path) + uint64_t x7 = host_ctx_aarch64_reg(uc, 7); + uint64_t x10 = host_ctx_aarch64_reg(uc, 10); + uint64_t guest_addr = (x7 - x10) & 0xffffffffffffULL; + + // Store diagnostic info for handle_interrupt to read + jit_last_host_fault = (uint64_t)info->si_addr; + jit_last_x7 = x7; + jit_last_x10 = x10; + jit_crash_count++; + + // Determine read/write from the host signal ABI when available. + int was_write = host_ctx_aarch64_fault_was_write(uc, info); + + // Write crash info directly to cpu_state via _cpu pointer + *(uint64_t *)(cpu_ptr + CRASH_CPU_segfault_addr) = guest_addr; + *(int *)(cpu_ptr + CRASH_CPU_segfault_was_write) = was_write; + // Restore guest PC to the latest faultable guest instruction for + // re-execution. This is usually more precise than the block-start TLS + // fallback and avoids re-running earlier side effects in the block. + uint64_t retry_pc = *(uint64_t *)(cpu_ptr + CRASH_LOCAL_jit_saved_pc); + if (retry_pc == 0) + retry_pc = (uint64_t)jit_saved_pc; + *(uint64_t *)(cpu_ptr + CRASH_CPU_pc) = retry_pc; + + // Restore SP to the value saved by fiber_enter, so fiber_exit + // can correctly pop the callee-saved register frame. + uint64_t exit_sp = *(uint64_t *)(cpu_ptr + CRASH_LOCAL_jit_exit_sp); + host_ctx_aarch64_set_sp(uc, exit_sp); + + // Redirect execution to crash trampoline (returns INT_JIT_CRASH) + host_ctx_aarch64_set_pc(uc, (uint64_t)jit_crash_trampoline); + + // Unblock signal so it can fire again on next crash + sigset_t unblock; + sigemptyset(&unblock); + sigaddset(&unblock, sig); + sigprocmask(SIG_UNBLOCK, &unblock, NULL); + + // Signal handler returns; execution resumes at jit_crash_trampoline + return; + } +#endif + + // Non-JIT crash: dump state and exit + char buf[512]; + int len; + ucontext_t *uc = (ucontext_t *)ctx; + len = snprintf(buf, sizeof(buf), "\n=== HOST CRASH: signal %d ===\nfault addr: %p\n", sig, info->si_addr); + write(STDERR_FILENO, buf, len); +#ifdef __aarch64__ + len = snprintf(buf, sizeof(buf), + "pc: 0x%llx\nlr: 0x%llx\nsp: 0x%llx\n" + "x0: 0x%llx\nx1: 0x%llx\nx2: 0x%llx\n" + "x7: 0x%llx\nx28: 0x%llx\n", + (unsigned long long) host_ctx_aarch64_pc(uc), + (unsigned long long) host_ctx_aarch64_lr(uc), + (unsigned long long) host_ctx_aarch64_sp(uc), + (unsigned long long) host_ctx_aarch64_reg(uc, 0), + (unsigned long long) host_ctx_aarch64_reg(uc, 1), + (unsigned long long) host_ctx_aarch64_reg(uc, 2), + (unsigned long long) host_ctx_aarch64_reg(uc, 7), + (unsigned long long) host_ctx_aarch64_reg(uc, 28)); + write(STDERR_FILENO, buf, len); +#endif + void *bt[20]; + int n = backtrace(bt, 20); + backtrace_symbols_fd(bt, n, STDERR_FILENO); + _exit(139); +} + +static struct termios saved_termios; +static int saved_termios_valid; + +void restore_termios(void) { + if (saved_termios_valid) + tcsetattr(STDIN_FILENO, TCSANOW, &saved_termios); +} + +static char *trim_ascii_space(char *s) { + while (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r') + s++; + char *end = s + strlen(s); + while (end > s && (end[-1] == ' ' || end[-1] == '\t' || end[-1] == '\n' || end[-1] == '\r')) + *--end = '\0'; + return s; +} + +static void append_boot_env(char *envp, size_t cap, size_t *offset, const char *fmt, ...) { + if (*offset >= cap) + return; + + va_list ap; + va_start(ap, fmt); + int needed = vsnprintf(envp + *offset, cap - *offset, fmt, ap); + va_end(ap); + + if (needed < 0) + return; + + size_t n = (size_t) needed; + if (n >= cap - *offset) { + // Truncated entry; stop appending to avoid pointer/size underflow. + *offset = cap; + envp[cap - 1] = '\0'; + return; + } + + // Entries are NUL-separated for xX_main_Xx. + *offset += n + 1; +} + +static void ensure_guest_runtime_dirs(void) { + int err = generic_mkdirat(AT_PWD, "/dev", 0755); + if (err < 0 && err != _EEXIST) + fprintf(stderr, "init: failed to create /dev: %s\n", strerror(-err)); + + err = generic_mkdirat(AT_PWD, "/dev/shm", 01777); + if (err < 0 && err != _EEXIST) + fprintf(stderr, "init: failed to create /dev/shm: %s\n", strerror(-err)); + + err = generic_setattrat(AT_PWD, "/dev/shm", make_attr(mode, 01777), true); + if (err < 0) + fprintf(stderr, "init: failed to chmod /dev/shm: %s\n", strerror(-err)); +} + +static void apply_env_bind_mounts(void) { + const char *spec = getenv("ISH_BIND_MOUNTS"); + if (spec == NULL || spec[0] == '\0') + return; + + char *copy = strdup(spec); + if (copy == NULL) { + fprintf(stderr, "ISH_BIND_MOUNTS: out of memory\n"); + return; + } + + char *saveptr = NULL; + for (char *entry = strtok_r(copy, ",", &saveptr); entry != NULL; entry = strtok_r(NULL, ",", &saveptr)) { + entry = trim_ascii_space(entry); + if (entry[0] == '\0') + continue; + + char *eq = strchr(entry, '='); + if (eq == NULL) { + fprintf(stderr, "ISH_BIND_MOUNTS: skipping entry without '=': %s\n", entry); + continue; + } + *eq = '\0'; + char *linux_path = trim_ascii_space(entry); + char *host_path = trim_ascii_space(eq + 1); + bool read_only = false; + + size_t host_len = strlen(host_path); + if (host_len > 3 && strcmp(host_path + host_len - 3, ":ro") == 0) { + host_path[host_len - 3] = '\0'; + read_only = true; + } else if (host_len > 3 && strcmp(host_path + host_len - 3, ":rw") == 0) { + host_path[host_len - 3] = '\0'; + } + host_path = trim_ascii_space(host_path); + + if (linux_path[0] != '/' || host_path[0] != '/') { + fprintf(stderr, "ISH_BIND_MOUNTS: paths must be absolute: %s=%s\n", linux_path, host_path); + continue; + } + + int err = fakefs_bind_mount(linux_path, host_path, read_only); + if (err < 0) + fprintf(stderr, "ISH_BIND_MOUNTS: failed to bind %s=%s%s: %s\n", + linux_path, host_path, read_only ? ":ro" : ":rw", strerror(-err)); + } + + free(copy); +} + +int main(int argc, char *const argv[]) { + // Save host terminal settings so we can restore on exit + if (isatty(STDIN_FILENO)) { + if (tcgetattr(STDIN_FILENO, &saved_termios) == 0) { + saved_termios_valid = 1; + atexit(restore_termios); + } + } + + // Redirect printk output (fd 666) to stderr + dup2(STDERR_FILENO, 666); + +#ifdef GUEST_ARM64 + const char *trace_highbits = getenv("ISH_TRACE_HIGHBITS"); + g_trace_highbits = trace_highbits && trace_highbits[0] && strcmp(trace_highbits, "0") != 0; + const char *trace_faults = getenv("ISH_TRACE_FAULTS"); + g_trace_faults = trace_faults && trace_faults[0] && strcmp(trace_faults, "0") != 0; + extern void arm64_fusion_stats_set_enabled_from_env(const char *env); + extern void arm64_block_stats_set_enabled_from_env(const char *env); + extern void arm64_eager_prechain_set_enabled_from_env(const char *env); + extern void arm64_eager_prechain_incoming_set_enabled_from_env(const char *env); + extern void arm64_internal_continue_set_enabled_from_env(const char *env); + extern void arm64_internal_continue_taken_set_enabled_from_env(const char *env); + arm64_fusion_stats_set_enabled_from_env(getenv("ISH_ARM64_FUSION_STATS")); + arm64_block_stats_set_enabled_from_env(getenv("ISH_ARM64_BLOCK_STATS")); + arm64_eager_prechain_set_enabled_from_env(getenv("ISH_ARM64_EAGER_PRECHAIN")); + arm64_eager_prechain_incoming_set_enabled_from_env(getenv("ISH_ARM64_EAGER_PRECHAIN_INCOMING")); + arm64_internal_continue_set_enabled_from_env(getenv("ISH_ARM64_INTERNAL_CONTINUE")); + arm64_internal_continue_taken_set_enabled_from_env(getenv("ISH_ARM64_INTERNAL_CONTINUE_TAKEN")); + asbestos_set_trace_pcs(getenv("ISH_TRACE_PCS")); + asbestos_set_trace_gate(getenv("ISH_TRACE_GATE_PC"), + getenv("ISH_TRACE_GATE_X4"), + getenv("ISH_TRACE_GATE_BUDGET")); +#endif + + static char altstack[SIGSTKSZ]; + stack_t ss = {.ss_sp = altstack, .ss_size = SIGSTKSZ}; + sigaltstack(&ss, NULL); + struct sigaction sa = {0}; + sa.sa_sigaction = crash_handler; + sa.sa_flags = SA_SIGINFO | SA_ONSTACK; + sigaction(SIGSEGV, &sa, NULL); + sigaction(SIGBUS, &sa, NULL); + sigaction(SIGABRT, &sa, NULL); + sigaction(SIGILL, &sa, NULL); + sigaction(SIGTRAP, &sa, NULL); + char envp[512] = {0}; + size_t p = 0; + append_boot_env(envp, sizeof(envp), &p, "HOME=/root"); + append_boot_env(envp, sizeof(envp), &p, "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"); +#ifdef GUEST_ARM64 + append_boot_env(envp, sizeof(envp), &p, "PYTHONMALLOC=malloc"); +#endif + const char *term = getenv("TERM"); + if (term && term[0] != '\0') + append_boot_env(envp, sizeof(envp), &p, "TERM=%s", term); + int err = xX_main_Xx(argc, argv, envp); + if (err < 0) { + fprintf(stderr, "xX_main_Xx: %s\n", strerror(-err)); + return err; + } + do_mount(&procfs, "proc", "/proc", "", 0); + do_mount(&devptsfs, "devpts", "/dev/pts", "", 0); + ensure_guest_runtime_dirs(); + apply_env_bind_mounts(); + task_run_current(); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/meson.build b/platforms/ios/Alpine/Vendor/ios-linuxkit/meson.build new file mode 100644 index 0000000000..83ff803c76 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/meson.build @@ -0,0 +1,327 @@ +project('ish', 'c', + default_options: ['default_library=static', 'c_std=gnu11', 'warning_level=2']) +cc = meson.get_compiler('c') + +if cc.get_id() == 'clang' + add_project_arguments('-Wimplicit-fallthrough', '-Wtautological-constant-in-range-compare', language: 'c') +endif + +if get_option('b_sanitize').split(',').contains('undefined') + add_project_arguments('-fno-sanitize=alignment', language: 'c') +endif + +log_on = get_option('log').split() +log_off = get_option('nolog').split() +foreach channel : log_on + log_off + if log_on.contains(channel) + add_project_arguments('-DDEBUG_' + channel + '=1', language: 'c') + else + add_project_arguments('-DDEBUG_' + channel + '=0', language: 'c') + endif +endforeach +add_project_arguments('-DLOG_HANDLER_' + get_option('log_handler').to_upper() + '=1', language: 'c') +add_project_arguments('-DENGINE_' + get_option('engine').to_upper() + '=1', language: 'c') + +guest_arch = get_option('guest_arch') +if guest_arch != 'arm64' + error('Only the ARM64 guest backend is supported') +endif +add_project_arguments('-DGUEST_ARM64=1', language: 'c') + +if get_option('no_crlf') + add_project_arguments('-DNO_CRLF', language: 'c') +endif + +add_project_arguments('-Wno-switch', language: 'c') + +includes = [include_directories('.')] + +threads = dependency('threads') +librt = cc.find_library('rt', required: false) +libm = cc.find_library('m', required: false) +libdl = cc.find_library('dl', required: false) +sqlite3 = cc.find_library('sqlite3') +dependencies = [librt, libm, libdl, threads, sqlite3] + +subdir('vdso/arm64') +vdso_inc = include_directories('vdso/arm64') +includes += vdso_inc + +offsets = custom_target('offsets', + output: 'cpu-offsets.h', input: 'asbestos/offsets.c', depfile: 'cpu-offsets.h.d', + command: [find_program('tools/staticdefine.sh'), '@OUTDIR@/compile_commands.json', '@INPUT@', '@OUTPUT@', '@DEPFILE@']) + +# Common emu sources +emu_src = [ + 'emu/tlb.c', +] + +gadgets = 'asbestos/guest-arm64/gadgets-' + host_machine.cpu_family() +emu_src += [ + 'emu/arch/arm64/fpu.c', + 'asbestos/asbestos.c', + 'asbestos/guest-arm64/gen.c', + 'asbestos/guest-arm64/crypto_helpers.c', + 'asbestos/helpers.c', + gadgets+'/entry.S', + gadgets+'/memory.S', + gadgets+'/control.S', + gadgets+'/math.S', + gadgets+'/bits.S', + gadgets+'/crypto.S', + offsets, +] + +libish_emu = library('ish_emu', emu_src, include_directories: includes) + +libfakefs = library('fakefs', + ['fs/fake-db.c', 'fs/fake-migrate.c', 'fs/fake-rebuild.c'], + include_directories: includes, + dependencies: sqlite3) + +subdir('deps') + +if get_option('kernel') == 'ish' + if get_option('engine') != 'asbestos' + error('Only asbestos is supported with ish kernel') + endif + + arch_kernel_src = ['kernel/arch/arm64/calls.c'] + + src = [ + 'kernel/init.c', + 'kernel/errno.c', + + 'kernel/calls.c',] + arch_kernel_src + [ + 'kernel/memory.c', + 'kernel/user.c', + 'kernel/vdso.c', vdso, + 'kernel/task.c', + 'kernel/group.c', + 'kernel/log.c', + + 'kernel/fork.c', + 'kernel/exec.c', + 'kernel/exit.c', + 'kernel/time.c', + 'kernel/mmap.c', + 'kernel/uname.c', + 'kernel/tls.c', + 'kernel/futex.c', + 'kernel/getset.c', + 'kernel/signal.c', + 'kernel/resource.c', + 'kernel/random.c', + 'kernel/misc.c', + 'kernel/eventfd.c', + 'kernel/pidfd.c', + 'kernel/inotify.c', + 'kernel/ipc.c', + 'kernel/ptrace.c', + 'kernel/native_offload.c', + + 'kernel/fs.c', + 'kernel/fs_info.c', + 'fs/mount.c', + 'fs/fd.c', + 'fs/inode.c', + 'fs/stat.c', + 'fs/dir.c', + 'fs/generic.c', + 'fs/path.c', + 'fs/real.c', + 'fs/fake.c', + + 'fs/proc.c', + 'fs/proc/entry.c', + 'fs/proc/ish.c', + 'fs/proc/net.c', + 'fs/proc/root.c', + 'fs/proc/pid.c', + + 'fs/dyndev.c', + + 'fs/adhoc.c', + 'fs/sock.c', + 'fs/pipe.c', + 'fs/sockrestart.c', + 'fs/lock.c', + + 'fs/dev.c', + 'fs/mem.c', + 'fs/tty.c', + 'fs/tty-real.c', + 'fs/pty.c', + 'fs/tmp.c', + + 'fs/poll.c', + 'kernel/poll.c', + 'kernel/epoll.c', + + 'util/timer.c', + 'util/sync.c', + 'util/fifo.c', + 'util/fchdir.c', + + 'platform/' + host_machine.system() + '.c', + ] + + libish = library('ish', src, + include_directories: includes) + ish = declare_dependency( + link_with: [libish, libish_emu, libfakefs], + dependencies: dependencies, + include_directories: includes) + + if not meson.is_cross_build() + executable('ish', ['main.c'], dependencies: ish) + endif + +else + error('Only the ish kernel is supported') +endif + +if not meson.is_cross_build() + subdir('tools') +endif + +if meson.is_cross_build() + archive_sources = [ + 'deps/libarchive/libarchive/archive_acl.c', + 'deps/libarchive/libarchive/archive_blake2s_ref.c', + 'deps/libarchive/libarchive/archive_blake2sp_ref.c', + 'deps/libarchive/libarchive/archive_check_magic.c', + 'deps/libarchive/libarchive/archive_cmdline.c', + 'deps/libarchive/libarchive/archive_cryptor.c', + 'deps/libarchive/libarchive/archive_digest.c', + 'deps/libarchive/libarchive/archive_disk_acl_darwin.c', + 'deps/libarchive/libarchive/archive_disk_acl_freebsd.c', + 'deps/libarchive/libarchive/archive_disk_acl_linux.c', + 'deps/libarchive/libarchive/archive_disk_acl_sunos.c', + 'deps/libarchive/libarchive/archive_entry.c', + 'deps/libarchive/libarchive/archive_entry_copy_bhfi.c', + 'deps/libarchive/libarchive/archive_entry_copy_stat.c', + 'deps/libarchive/libarchive/archive_entry_link_resolver.c', + 'deps/libarchive/libarchive/archive_entry_sparse.c', + 'deps/libarchive/libarchive/archive_entry_stat.c', + 'deps/libarchive/libarchive/archive_entry_strmode.c', + 'deps/libarchive/libarchive/archive_entry_xattr.c', + 'deps/libarchive/libarchive/archive_getdate.c', + 'deps/libarchive/libarchive/archive_hmac.c', + 'deps/libarchive/libarchive/archive_match.c', + 'deps/libarchive/libarchive/archive_options.c', + 'deps/libarchive/libarchive/archive_pack_dev.c', + 'deps/libarchive/libarchive/archive_pathmatch.c', + 'deps/libarchive/libarchive/archive_ppmd7.c', + 'deps/libarchive/libarchive/archive_ppmd8.c', + 'deps/libarchive/libarchive/archive_random.c', + 'deps/libarchive/libarchive/archive_rb.c', + 'deps/libarchive/libarchive/archive_read.c', + 'deps/libarchive/libarchive/archive_read_add_passphrase.c', + 'deps/libarchive/libarchive/archive_read_append_filter.c', + 'deps/libarchive/libarchive/archive_read_data_into_fd.c', + 'deps/libarchive/libarchive/archive_read_disk_entry_from_file.c', + 'deps/libarchive/libarchive/archive_read_disk_posix.c', + 'deps/libarchive/libarchive/archive_read_disk_set_standard_lookup.c', + 'deps/libarchive/libarchive/archive_read_disk_windows.c', + 'deps/libarchive/libarchive/archive_read_extract.c', + 'deps/libarchive/libarchive/archive_read_extract2.c', + 'deps/libarchive/libarchive/archive_read_open_fd.c', + 'deps/libarchive/libarchive/archive_read_open_file.c', + 'deps/libarchive/libarchive/archive_read_open_filename.c', + 'deps/libarchive/libarchive/archive_read_open_memory.c', + 'deps/libarchive/libarchive/archive_read_set_format.c', + 'deps/libarchive/libarchive/archive_read_set_options.c', + 'deps/libarchive/libarchive/archive_read_support_filter_all.c', + 'deps/libarchive/libarchive/archive_read_support_filter_bzip2.c', + 'deps/libarchive/libarchive/archive_read_support_filter_compress.c', + 'deps/libarchive/libarchive/archive_read_support_filter_grzip.c', + 'deps/libarchive/libarchive/archive_read_support_filter_gzip.c', + 'deps/libarchive/libarchive/archive_read_support_filter_lrzip.c', + 'deps/libarchive/libarchive/archive_read_support_filter_lz4.c', + 'deps/libarchive/libarchive/archive_read_support_filter_lzop.c', + 'deps/libarchive/libarchive/archive_read_support_filter_none.c', + 'deps/libarchive/libarchive/archive_read_support_filter_program.c', + 'deps/libarchive/libarchive/archive_read_support_filter_rpm.c', + 'deps/libarchive/libarchive/archive_read_support_filter_uu.c', + 'deps/libarchive/libarchive/archive_read_support_filter_xz.c', + 'deps/libarchive/libarchive/archive_read_support_filter_zstd.c', + 'deps/libarchive/libarchive/archive_read_support_format_7zip.c', + 'deps/libarchive/libarchive/archive_read_support_format_all.c', + 'deps/libarchive/libarchive/archive_read_support_format_ar.c', + 'deps/libarchive/libarchive/archive_read_support_format_by_code.c', + 'deps/libarchive/libarchive/archive_read_support_format_cab.c', + 'deps/libarchive/libarchive/archive_read_support_format_cpio.c', + 'deps/libarchive/libarchive/archive_read_support_format_empty.c', + 'deps/libarchive/libarchive/archive_read_support_format_iso9660.c', + 'deps/libarchive/libarchive/archive_read_support_format_lha.c', + 'deps/libarchive/libarchive/archive_read_support_format_mtree.c', + 'deps/libarchive/libarchive/archive_read_support_format_rar.c', + 'deps/libarchive/libarchive/archive_read_support_format_rar5.c', + 'deps/libarchive/libarchive/archive_read_support_format_raw.c', + 'deps/libarchive/libarchive/archive_read_support_format_tar.c', + 'deps/libarchive/libarchive/archive_read_support_format_warc.c', + 'deps/libarchive/libarchive/archive_read_support_format_xar.c', + 'deps/libarchive/libarchive/archive_read_support_format_zip.c', + 'deps/libarchive/libarchive/archive_string.c', + 'deps/libarchive/libarchive/archive_string_sprintf.c', + 'deps/libarchive/libarchive/archive_util.c', + 'deps/libarchive/libarchive/archive_version_details.c', + 'deps/libarchive/libarchive/archive_virtual.c', + 'deps/libarchive/libarchive/archive_windows.c', + 'deps/libarchive/libarchive/archive_write.c', + 'deps/libarchive/libarchive/archive_write_add_filter.c', + 'deps/libarchive/libarchive/archive_write_add_filter_b64encode.c', + 'deps/libarchive/libarchive/archive_write_add_filter_by_name.c', + 'deps/libarchive/libarchive/archive_write_add_filter_bzip2.c', + 'deps/libarchive/libarchive/archive_write_add_filter_compress.c', + 'deps/libarchive/libarchive/archive_write_add_filter_grzip.c', + 'deps/libarchive/libarchive/archive_write_add_filter_gzip.c', + 'deps/libarchive/libarchive/archive_write_add_filter_lrzip.c', + 'deps/libarchive/libarchive/archive_write_add_filter_lz4.c', + 'deps/libarchive/libarchive/archive_write_add_filter_lzop.c', + 'deps/libarchive/libarchive/archive_write_add_filter_none.c', + 'deps/libarchive/libarchive/archive_write_add_filter_program.c', + 'deps/libarchive/libarchive/archive_write_add_filter_uuencode.c', + 'deps/libarchive/libarchive/archive_write_add_filter_xz.c', + 'deps/libarchive/libarchive/archive_write_add_filter_zstd.c', + 'deps/libarchive/libarchive/archive_write_disk_posix.c', + 'deps/libarchive/libarchive/archive_write_disk_set_standard_lookup.c', + 'deps/libarchive/libarchive/archive_write_disk_windows.c', + 'deps/libarchive/libarchive/archive_write_open_fd.c', + 'deps/libarchive/libarchive/archive_write_open_file.c', + 'deps/libarchive/libarchive/archive_write_open_filename.c', + 'deps/libarchive/libarchive/archive_write_open_memory.c', + 'deps/libarchive/libarchive/archive_write_set_format.c', + 'deps/libarchive/libarchive/archive_write_set_format_7zip.c', + 'deps/libarchive/libarchive/archive_write_set_format_ar.c', + 'deps/libarchive/libarchive/archive_write_set_format_by_name.c', + 'deps/libarchive/libarchive/archive_write_set_format_cpio.c', + 'deps/libarchive/libarchive/archive_write_set_format_cpio_newc.c', + 'deps/libarchive/libarchive/archive_write_set_format_filter_by_ext.c', + 'deps/libarchive/libarchive/archive_write_set_format_gnutar.c', + 'deps/libarchive/libarchive/archive_write_set_format_iso9660.c', + 'deps/libarchive/libarchive/archive_write_set_format_mtree.c', + 'deps/libarchive/libarchive/archive_write_set_format_pax.c', + 'deps/libarchive/libarchive/archive_write_set_format_raw.c', + 'deps/libarchive/libarchive/archive_write_set_format_shar.c', + 'deps/libarchive/libarchive/archive_write_set_format_ustar.c', + 'deps/libarchive/libarchive/archive_write_set_format_v7tar.c', + 'deps/libarchive/libarchive/archive_write_set_format_warc.c', + 'deps/libarchive/libarchive/archive_write_set_format_xar.c', + 'deps/libarchive/libarchive/archive_write_set_format_zip.c', + 'deps/libarchive/libarchive/archive_write_set_options.c', + 'deps/libarchive/libarchive/archive_write_set_passphrase.c', + 'deps/libarchive/libarchive/filter_fork_posix.c', + 'deps/libarchive/libarchive/filter_fork_windows.c', + 'deps/libarchive/libarchive/xxhash.c', + ] + archive = static_library('acode_archive', archive_sources, + include_directories: [include_directories('deps'), include_directories('deps/libarchive/libarchive')], + c_args: ['-DHAVE_CONFIG_H', '-I' + meson.get_external_property('sdk_path') + '/usr/include/libxml2', '-w']) + acode_alpine = static_library('acode_alpine', + ['../../Bridge/AlpineRuntime.c', '../../Bridge/AlpineTerminal.c', '../../Bridge/AlpineFaults.c', + '../../Bridge/AlpineArchive.c', 'tools/fakefs.c'], + include_directories: [includes, include_directories('deps/libarchive/libarchive')], + c_args: ['-I' + meson.project_source_root() + '/../../include']) +endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/meson_options.txt b/platforms/ios/Alpine/Vendor/ios-linuxkit/meson_options.txt new file mode 100644 index 0000000000..dd6e49c65f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/meson_options.txt @@ -0,0 +1,14 @@ +option('log', type: 'string', value: '') +option('nolog', type: 'string', value: '') +option('log_handler', type: 'string', value: 'dprintf') + +option('engine', type: 'combo', choices: ['asbestos'], value: 'asbestos') +option('kernel', type: 'combo', choices: ['ish'], value: 'ish') +option('kconfig', type: 'array', value: []) + +option('guest_arch', type: 'combo', choices: ['arm64'], value: 'arm64', + description: 'Guest architecture to emulate') + +option('vdso_c_args', type: 'string', value: '') + +option('no_crlf', type: 'boolean', value: false) diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/misc.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/misc.h new file mode 100644 index 0000000000..99d44744a3 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/misc.h @@ -0,0 +1,128 @@ +#ifndef MISC_H +#define MISC_H + +#ifdef __KERNEL__ +#include <linux/types.h> +#else +#include <assert.h> +#include <sys/types.h> +#include <stdnoreturn.h> +#include <stdbool.h> +#include <stdint.h> +#endif + +// utility macros +#define glue(a, b) _glue(a, b) +#define _glue(a, b) a##b +#define glue3(a,b,c) glue(a, glue(b, c)) +#define glue4(a,b,c,d) glue(a, glue3(b, c, d)) + +#define str(x) _str(x) +#define _str(x) #x + +// compiler check +#define is_gcc(version) (__GNUC__ >= version) + +#if !defined(__has_attribute) +#define has_attribute(x) 0 +#else +#define has_attribute __has_attribute +#endif + +#if !defined(__has_feature) +#define has_feature(x) 0 +#else +#define has_feature __has_feature +#endif + +// keywords +#define bitfield unsigned int +#define forceinline inline __attribute__((always_inline)) +#if defined(NDEBUG) || defined(__KERNEL__) +#define posit __builtin_assume +#else +#define posit assert +#endif +#define must_check __attribute__((warn_unused_result)) + +#ifndef __KERNEL__ +#define unlikely(x) __builtin_expect((x), 0) +#define typecheck(type, x) ({type _x = x; x;}) +#define container_of(ptr, type, member) \ + ((type *) ((char *) (ptr) - offsetof(type, member))) +#if has_attribute(fallthrough) +#define fallthrough __attribute__((fallthrough)) +#else +#define fallthrough +#endif +#endif + +#if has_attribute(no_sanitize) +#define __no_instrument_msan +#if defined(__has_feature) +#if has_feature(memory_sanitizer) +#undef __no_instrument_msan +#define __no_instrument_msan __attribute__((no_sanitize("memory")) +#endif +#endif +#define __no_instrument __attribute__((no_sanitize("address", "thread", "undefined", "leak"))) __no_instrument_msan +#else +#define __no_instrument +#endif + +#if has_attribute(nonstring) +#define __strncpy_safe __attribute__((nonstring)) +#else +#define __strncpy_safe +#endif + +#define zero_init(type) ((type[1]){}[0]) +#define pun(type, x) (((union {typeof(x) _; type a;}) (x)).a) + +#define UNUSED(x) UNUSED_##x __attribute__((unused)) +static inline void __use(int dummy __attribute__((unused)), ...) {} +#define use(...) __use(0, ##__VA_ARGS__) + +#if defined(__arm64__) || defined(__aarch64__) +#define rdtsc() ({ \ + uint64_t tsc; \ + __asm__ volatile("mrs %0, PMCCNTR_EL0" : "=r" (tsc)); \ + tsc; \ + }) +#else +#define rdtsc() 0 +#endif + +#ifndef __KERNEL__ +#define array_size(arr) (sizeof(arr)/sizeof((arr)[0])) +#endif + +// types +typedef int64_t sqword_t; +typedef uint64_t qword_t; +typedef uint32_t dword_t; +typedef int32_t sdword_t; +typedef uint16_t word_t; +typedef uint8_t byte_t; + +typedef uint64_t addr_t; +typedef dword_t uint_t; +typedef sdword_t int_t; + +typedef sdword_t pid_t_; +typedef dword_t uid_t_; +typedef word_t mode_t_; +typedef sqword_t off_t_; +typedef sqword_t time_t_; +typedef dword_t clock_t_; + +#define uint(size) glue3(uint,size,_t) +#define sint(size) glue3(int,size,_t) + +#ifndef __KERNEL__ +#define ERR_PTR(err) (void *) (intptr_t) (err) +#define PTR_ERR(ptr) (intptr_t) (ptr) +#define IS_ERR(ptr) ((uintptr_t) (ptr) > (uintptr_t) -0xfff) +#endif + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/platform/darwin.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/platform/darwin.c new file mode 100644 index 0000000000..5e9d36c475 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/platform/darwin.c @@ -0,0 +1,170 @@ +#include <mach/mach.h> +#include <sys/sysctl.h> +#include <dispatch/dispatch.h> +#include <sys/time.h> +#include <sys/fcntl.h> +#include <pthread.h> +#include <malloc/malloc.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <CommonCrypto/CommonCrypto.h> +#include <CommonCrypto/CommonRandom.h> +#include "debug.h" +#include "platform/platform.h" + +// mach_host_self() increments the send-right refcount on each call. Caching the +// right avoids leaking refs when guests poll /proc/stat or /proc/meminfo. +static mach_port_t cached_host_self(void) { + static mach_port_t host = MACH_PORT_NULL; + static dispatch_once_t once; + dispatch_once(&once, ^{ + host = mach_host_self(); + }); + return host; +} + +struct cpu_usage get_cpu_usage() { + host_cpu_load_info_data_t load = {}; + mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT; + if (host_statistics(cached_host_self(), HOST_CPU_LOAD_INFO, (host_info_t) &load, &count) != KERN_SUCCESS) + return (struct cpu_usage) {}; + return (struct cpu_usage) { + .user_ticks = load.cpu_ticks[CPU_STATE_USER], + .system_ticks = load.cpu_ticks[CPU_STATE_SYSTEM], + .idle_ticks = load.cpu_ticks[CPU_STATE_IDLE], + .nice_ticks = load.cpu_ticks[CPU_STATE_NICE], + }; +} + +struct mem_usage get_mem_usage() { + static struct mem_usage last_good; + host_basic_info_data_t basic = {}; + vm_statistics64_data_t vm = {}; + mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT; + kern_return_t status = host_info(cached_host_self(), HOST_BASIC_INFO, (host_info_t) &basic, &count); + if (status == KERN_SUCCESS) { + count = HOST_VM_INFO64_COUNT; + status = host_statistics64(cached_host_self(), HOST_VM_INFO64, (host_info_t) &vm, &count); + } + if (status != KERN_SUCCESS) { + printk("WARNING: get_mem_usage: Mach host statistics failed (%d)\n", status); + if (last_good.total != 0) + return last_good; + uint64_t total = 0; + size_t size = sizeof(total); + if (sysctlbyname("hw.memsize", &total, &size, NULL, 0) != 0 || total == 0) + total = 4ULL * 1024 * 1024 * 1024; + return (struct mem_usage) { + .total = total, + .free = total / 4, + .active = total / 4, + .inactive = total / 4, + }; + } + + last_good = (struct mem_usage) { + .total = basic.max_mem, + .free = vm.free_count * vm_page_size, + .active = vm.active_count * vm_page_size, + .inactive = vm.inactive_count * vm_page_size, + }; + return last_good; +} + +struct uptime_info get_uptime() { + uint64_t kern_boottime[2]; + size_t size = sizeof(kern_boottime); + sysctlbyname("kern.boottime", &kern_boottime, &size, NULL, 0); + struct timeval now; + gettimeofday(&now, NULL); + + struct { + uint32_t ldavg[3]; + long scale; + } vm_loadavg; + size = sizeof(vm_loadavg); + sysctlbyname("vm.loadavg", &vm_loadavg, &size, NULL, 0); + + // linux wants the scale to be 16 bits + for (int i = 0; i < 3; i++) { + if (FSHIFT < 16) + vm_loadavg.ldavg[i] <<= 16 - FSHIFT; + else + vm_loadavg.ldavg[i] >>= FSHIFT - 16; + } + + struct uptime_info uptime = { + .uptime_ticks = now.tv_sec - kern_boottime[0], + .load_1m = vm_loadavg.ldavg[0], + .load_5m = vm_loadavg.ldavg[1], + .load_15m = vm_loadavg.ldavg[2], + }; + return uptime; +} + +struct platform_sysinfo platform_get_sysinfo(void) { + struct mem_usage mem = get_mem_usage(); + return (struct platform_sysinfo) { + .totalram = mem.total, + .freeram = mem.free, + .mem_unit = 1, + }; +} + +struct platform_thread_cpu_usage platform_get_thread_cpu_usage(void) { + thread_basic_info_data_t info = {}; + mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT; + kern_return_t status = thread_info(mach_thread_self(), THREAD_BASIC_INFO, (thread_info_t)&info, &count); + assert(status == KERN_SUCCESS); + return (struct platform_thread_cpu_usage) { + .user_sec = info.user_time.seconds, + .user_usec = info.user_time.microseconds, + .system_sec = info.system_time.seconds, + .system_usec = info.system_time.microseconds, + }; +} + +int platform_fd_get_path(int fd, char *out, size_t out_size) { + if (out_size == 0) + return -1; + char tmp[MAXPATHLEN]; + if (fcntl(fd, F_GETPATH, tmp) < 0) + return -1; + strlcpy(out, tmp, out_size); + return strlen(tmp) < out_size ? 0 : -1; +} + +uint64_t platform_stat_atime_sec(const struct stat *st) { return st->st_atimespec.tv_sec; } +uint64_t platform_stat_mtime_sec(const struct stat *st) { return st->st_mtimespec.tv_sec; } +uint64_t platform_stat_ctime_sec(const struct stat *st) { return st->st_ctimespec.tv_sec; } +long platform_stat_atime_nsec(const struct stat *st) { return st->st_atimespec.tv_nsec; } +long platform_stat_mtime_nsec(const struct stat *st) { return st->st_mtimespec.tv_nsec; } +long platform_stat_ctime_nsec(const struct stat *st) { return st->st_ctimespec.tv_nsec; } + +int platform_get_random_bytes(char *buf, size_t len) { + return CCRandomGenerateBytes(buf, len) == kCCSuccess ? 0 : -1; +} + +int platform_create_shared_memory_fd(size_t size) { + char path[] = "/tmp/ish-shm-XXXXXX"; + int fd = mkstemp(path); + if (fd < 0) + return -1; + unlink(path); + if (ftruncate(fd, (off_t) size) < 0) { + close(fd); + return -1; + } + return fd; +} + +void platform_set_thread_name(const char *name) { + pthread_setname_np(name); +} + +void platform_release_thread_memory_pressure(void) { + // Ask Darwin malloc zones to drop thread-local caches after guest thread + // groups exit; this is a host memory-pressure hint, not guest semantics. + malloc_zone_pressure_relief(NULL, 0); +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/platform/host_context_aarch64.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/platform/host_context_aarch64.h new file mode 100644 index 0000000000..65dc0308fe --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/platform/host_context_aarch64.h @@ -0,0 +1,123 @@ +#ifndef HOST_CONTEXT_AARCH64_H +#define HOST_CONTEXT_AARCH64_H + +#include <signal.h> +#include <stdint.h> +#include <ucontext.h> + +#if defined(__linux__) && defined(__aarch64__) +#include <asm/sigcontext.h> +#endif + +#if defined(__aarch64__) + +static inline uint64_t host_ctx_aarch64_reg(const ucontext_t *uc, unsigned reg) +{ +#if defined(__APPLE__) + return uc->uc_mcontext->__ss.__x[reg]; +#elif defined(__linux__) + return uc->uc_mcontext.regs[reg]; +#else + (void)uc; + (void)reg; + return 0; +#endif +} + +static inline uint64_t host_ctx_aarch64_pc(const ucontext_t *uc) +{ +#if defined(__APPLE__) + return uc->uc_mcontext->__ss.__pc; +#elif defined(__linux__) + return uc->uc_mcontext.pc; +#else + (void)uc; + return 0; +#endif +} + +static inline uint64_t host_ctx_aarch64_sp(const ucontext_t *uc) +{ +#if defined(__APPLE__) + return uc->uc_mcontext->__ss.__sp; +#elif defined(__linux__) + return uc->uc_mcontext.sp; +#else + (void)uc; + return 0; +#endif +} + +static inline uint64_t host_ctx_aarch64_lr(const ucontext_t *uc) +{ +#if defined(__APPLE__) + return uc->uc_mcontext->__ss.__lr; +#elif defined(__linux__) + return uc->uc_mcontext.regs[30]; +#else + (void)uc; + return 0; +#endif +} + +static inline void host_ctx_aarch64_set_pc(ucontext_t *uc, uint64_t pc) +{ +#if defined(__APPLE__) + uc->uc_mcontext->__ss.__pc = pc; +#elif defined(__linux__) + uc->uc_mcontext.pc = pc; +#else + (void)uc; + (void)pc; +#endif +} + +static inline void host_ctx_aarch64_set_sp(ucontext_t *uc, uint64_t sp) +{ +#if defined(__APPLE__) + uc->uc_mcontext->__ss.__sp = sp; +#elif defined(__linux__) + uc->uc_mcontext.sp = sp; +#else + (void)uc; + (void)sp; +#endif +} + +static inline uint64_t host_ctx_aarch64_esr(const ucontext_t *uc) +{ +#if defined(__APPLE__) + return uc->uc_mcontext->__es.__esr; +#elif defined(__linux__) + const char *ptr = (const char *)uc->uc_mcontext.__reserved; + size_t remaining = sizeof(uc->uc_mcontext.__reserved); + while (remaining >= sizeof(struct _aarch64_ctx)) { + const struct _aarch64_ctx *head = (const struct _aarch64_ctx *)ptr; + if (head->magic == 0 || head->size == 0) + break; + if (head->size < sizeof(struct _aarch64_ctx) || head->size > remaining) + break; + if (head->magic == ESR_MAGIC && head->size >= sizeof(struct esr_context)) + return ((const struct esr_context *)head)->esr; + ptr += head->size; + remaining -= head->size; + } + return 0; +#else + (void)uc; + return 0; +#endif +} + +static inline int host_ctx_aarch64_fault_was_write(const ucontext_t *uc, const siginfo_t *info) +{ + const uint64_t esr = host_ctx_aarch64_esr(uc); + if (esr) + return (esr & 0x40) != 0; + (void)info; + return 0; +} + +#endif /* __aarch64__ */ + +#endif /* HOST_CONTEXT_AARCH64_H */ diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/platform/linux.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/platform/linux.c new file mode 100644 index 0000000000..ba0d9c917d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/platform/linux.c @@ -0,0 +1,156 @@ +#define _GNU_SOURCE +#include <sys/sysinfo.h> +#include <sys/syscall.h> +#include <sys/resource.h> +#include <errno.h> +#include <linux/random.h> +#include <pthread.h> +#include <unistd.h> +#include <inttypes.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "platform/platform.h" +#include "debug.h" + +static void read_proc_line(const char *file, const char *name, char *buf) { + FILE *f = fopen(file, "r"); + if (f == NULL) ERRNO_DIE(file); + do { + fgets(buf, 1234, f); + if (feof(f)) + die("could not find proc line %s", name); + } while (!(strncmp(name, buf, strlen(name)) == 0 && buf[strlen(name)] == ' ')); + fclose(f); +} + +struct cpu_usage get_cpu_usage() { + struct cpu_usage usage = {}; + char buf[1234]; + read_proc_line("/proc/stat", "cpu", buf); + uint64_t user, nice, system, idle; + if (sscanf(buf, "cpu %"SCNu64" %"SCNu64" %"SCNu64" %"SCNu64, &user, &nice, &system, &idle) != 4) + die("could not parse /proc/stat cpu line"); + usage.user_ticks = user; + usage.nice_ticks = nice; + usage.system_ticks = system; + usage.idle_ticks = idle; + return usage; +} + +static uint64_t parse_proc_meminfo_kib(const char *name) { + char buf[1234]; + uint64_t kib; + read_proc_line("/proc/meminfo", name, buf); + if (sscanf(buf + strlen(name), " %"SCNu64" kB", &kib) != 1) + die("could not parse proc meminfo line %s", name); + return kib * 1024; +} + +struct mem_usage get_mem_usage() { + return (struct mem_usage) { + .total = parse_proc_meminfo_kib("MemTotal:"), + .free = parse_proc_meminfo_kib("MemFree:"), + .active = parse_proc_meminfo_kib("Active:"), + .inactive = parse_proc_meminfo_kib("Inactive:"), + }; +} + +struct uptime_info get_uptime() { + struct sysinfo info; + sysinfo(&info); + struct uptime_info uptime = { + .uptime_ticks = info.uptime, + .load_1m = info.loads[0], + .load_5m = info.loads[1], + .load_15m = info.loads[2], + }; + return uptime; +} + +struct platform_sysinfo platform_get_sysinfo(void) { + struct sysinfo host_info = {}; + sysinfo(&host_info); + return (struct platform_sysinfo) { + .totalram = host_info.totalram, + .freeram = host_info.freeram, + .sharedram = host_info.sharedram, + .totalswap = host_info.totalswap, + .freeswap = host_info.freeswap, + .totalhigh = host_info.totalhigh, + .freehigh = host_info.freehigh, + .procs = host_info.procs, + .mem_unit = host_info.mem_unit, + }; +} + +struct platform_thread_cpu_usage platform_get_thread_cpu_usage(void) { + struct rusage usage = {}; + int err = getrusage(RUSAGE_THREAD, &usage); + assert(err == 0); + return (struct platform_thread_cpu_usage) { + .user_sec = usage.ru_utime.tv_sec, + .user_usec = usage.ru_utime.tv_usec, + .system_sec = usage.ru_stime.tv_sec, + .system_usec = usage.ru_stime.tv_usec, + }; +} + +int platform_fd_get_path(int fd, char *out, size_t out_size) { + if (out_size == 0) + return -1; + char proc_path[64]; + snprintf(proc_path, sizeof(proc_path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(proc_path, out, out_size - 1); + if (n < 0) + return -1; + out[n] = '\0'; + return 0; +} + +uint64_t platform_stat_atime_sec(const struct stat *st) { return st->st_atim.tv_sec; } +uint64_t platform_stat_mtime_sec(const struct stat *st) { return st->st_mtim.tv_sec; } +uint64_t platform_stat_ctime_sec(const struct stat *st) { return st->st_ctim.tv_sec; } +long platform_stat_atime_nsec(const struct stat *st) { return st->st_atim.tv_nsec; } +long platform_stat_mtime_nsec(const struct stat *st) { return st->st_mtim.tv_nsec; } +long platform_stat_ctime_nsec(const struct stat *st) { return st->st_ctim.tv_nsec; } + +int platform_get_random_bytes(char *buf, size_t len) { + while (len > 0) { + ssize_t n = syscall(SYS_getrandom, buf, len, 0); + if (n < 0) { + if (errno == EINTR) + continue; + return -1; + } + if (n == 0) + return -1; + buf += n; + len -= (size_t)n; + } + return 0; +} + +int platform_create_shared_memory_fd(size_t size) { + char path[] = "/tmp/ish-shm-XXXXXX"; + int fd = mkstemp(path); + if (fd < 0) + return -1; + unlink(path); + if (ftruncate(fd, (off_t) size) < 0) { + close(fd); + return -1; + } + return fd; +} + +void platform_set_thread_name(const char *name) { + char short_name[16]; + snprintf(short_name, sizeof(short_name), "%s", name); + pthread_setname_np(pthread_self(), short_name); +} + +void platform_release_thread_memory_pressure(void) { + // No portable Linux equivalent; glibc/musl release thread caches during + // normal pthread teardown. +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/platform/platform.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/platform/platform.h new file mode 100644 index 0000000000..3a1fea761f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/platform/platform.h @@ -0,0 +1,73 @@ +#ifndef PLATFORM_H +#define PLATFORM_H +#include <stddef.h> +#include <sys/stat.h> +#include "misc.h" + +// CPU counters are USER_HZ-style jiffies. Uptime is seconds, matching the +// Linux sysinfo ABI; /proc formats it as decimal seconds at presentation time. +struct cpu_usage { + uint64_t user_ticks; + uint64_t system_ticks; + uint64_t idle_ticks; + uint64_t nice_ticks; +}; +struct cpu_usage get_cpu_usage(void); + +struct mem_usage { + uint64_t total; + uint64_t free; + uint64_t active; + uint64_t inactive; +}; +struct mem_usage get_mem_usage(void); + +struct uptime_info { + uint64_t uptime_ticks; + uint64_t load_1m, load_5m, load_15m; +}; +struct uptime_info get_uptime(void); + +struct platform_sysinfo { + uint64_t totalram; + uint64_t freeram; + uint64_t sharedram; + uint64_t totalswap; + uint64_t freeswap; + uint64_t totalhigh; + uint64_t freehigh; + uint32_t procs; + uint32_t mem_unit; +}; +struct platform_sysinfo platform_get_sysinfo(void); + +struct platform_thread_cpu_usage { + uint64_t user_sec; + uint64_t user_usec; + uint64_t system_sec; + uint64_t system_usec; +}; +struct platform_thread_cpu_usage platform_get_thread_cpu_usage(void); + +// Guest-visible CPU topology. Keep this deterministic instead of mirroring the +// host CPU count: exposing all host cores makes modern runtimes (Bun/JSC/V8) fan +// out too aggressively for the emulator. +#ifndef PLATFORM_GUEST_CPU_COUNT +#define PLATFORM_GUEST_CPU_COUNT 4 +#endif + +// Host OS shims. Keep Linux/macOS/iOS API differences behind platform/* so +// emulator/kernel code can include one stable interface. +int platform_fd_get_path(int fd, char *out, size_t out_size); +uint64_t platform_stat_atime_sec(const struct stat *st); +uint64_t platform_stat_mtime_sec(const struct stat *st); +uint64_t platform_stat_ctime_sec(const struct stat *st); +long platform_stat_atime_nsec(const struct stat *st); +long platform_stat_mtime_nsec(const struct stat *st); +long platform_stat_ctime_nsec(const struct stat *st); +int platform_get_random_bytes(char *buf, size_t len); +int platform_create_shared_memory_fd(size_t size); +void platform_set_thread_name(const char *name); +void platform_release_thread_memory_pressure(void); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/fakefs.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/fakefs.c new file mode 100644 index 0000000000..bbc364bdb6 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/fakefs.c @@ -0,0 +1,389 @@ +#include <errno.h> +#include <fcntl.h> +#include <limits.h> +#include <stdbool.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <archive.h> +#include <archive_entry.h> + +#define ISH_INTERNAL +#include "fs/fake-db.h" +#include "fs/sqlutil.h" +#include "tools/fakefs.h" +#include "util/fchdir.h" +#include "misc.h" + +#ifndef MAX_PATH +#define MAX_PATH 4096 +#endif + +// I have a weird way of error handling +#define FILL_ERR(_type, _code, _message) do { \ + err_out->line = __LINE__; \ + err_out->type = _type; \ + err_out->code = _code; \ + err_out->message = strdup(_message); \ + return false; \ +} while (0) +#define ARCHIVE_ERR(archive) FILL_ERR(ERR_ARCHIVE, archive_errno(archive), archive_error_string(archive)) +#define POSIX_ERR() FILL_ERR(ERR_POSIX, errno, strerror(errno)) +#undef HANDLE_ERR // for sqlite +#define HANDLE_ERR(db) FILL_ERR(ERR_SQLITE, sqlite3_extended_errcode(db), sqlite3_errmsg(db)) +#define CANCEL() FILL_ERR(ERR_CANCELLED, 0, ""); + +static bool progress_update(struct progress *p, double progress, const char *message) { + bool cancelled = false; + if (p && p->callback) + p->callback(p->cookie, progress, message, &cancelled); + return !cancelled; +} + +// This isn't linked with ish which is why there's so much copy/pasted code + +// I hate this code +static bool path_normalize(const char *path, char *out) { +#define ends_path(c) (c == '\0' || c == '/') + // normalized format: + // ( '/' path-component ) * + while (path[0] != '\0') { + while (path[0] == '/') + path++; + if (path[0] == '\0') + break; // if the path ends with a slash + // path points to the start of a path component + if (path[0] == '.' && path[1] == '.' && ends_path(path[2])) + return false; // no dotdot allowed! + if (path[0] == '.' && ends_path(path[1])) { + path++; + } else { + *out++ = '/'; + while (path[0] != '/' && path[0] != '\0') + *out++ = *path++; + } + } + *out = '\0'; + return true; +} + +static const char *schema = Q( + create table meta (id integer unique default 0, db_inode integer); + insert into meta (db_inode) values (0); + create table stats (inode integer primary key, stat blob); + create table paths (path blob primary key, inode integer references stats(inode)); + create index inode_to_path on paths (inode, path); + // no index is needed on stats, because the rows are ordered by the primary key + pragma user_version=3; +); + +bool fakefs_import(const char *archive_path, const char *fs, struct fakefsify_error *err_out, struct progress p) { + int err = mkdir(fs, 0777); + if (err < 0) + POSIX_ERR(); + + // make the data root dir + char path_tmp[PATH_MAX]; + snprintf(path_tmp, sizeof(path_tmp), "%s/data", fs); + err = mkdir(path_tmp, 0777); + int root_fd = open(path_tmp, O_RDONLY); + if (root_fd < 0) + POSIX_ERR(); + + // open the database + snprintf(path_tmp, sizeof(path_tmp), "%s/meta.db", fs); + sqlite3 *db; + err = sqlite3_open_v2(path_tmp, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); + CHECK_ERR(); + EXEC("pragma journal_mode=wal") + EXEC("begin"); + EXEC(schema); + + // open the archive + struct archive *archive = archive_read_new(); + if (archive == NULL) + ARCHIVE_ERR(archive); + archive_read_support_filter_gzip(archive); + archive_read_support_format_tar(archive); + if (archive_read_open_filename(archive, archive_path, 65536) != ARCHIVE_OK) + ARCHIVE_ERR(archive); + + struct stat real_stat; + if (stat(archive_path, &real_stat) < 0) + POSIX_ERR(); + size_t archive_bytes = real_stat.st_size; + + sqlite3_stmt *insert_stat = PREPARE("insert into stats (stat) values (?)"); + sqlite3_stmt *insert_path = PREPARE("insert or replace into paths values (?, ?)"); + sqlite3_stmt *insert_hardlink = PREPARE("insert or replace into paths values (?, (select inode from paths where path = ? limit 1))"); + + bool archive_has_root = false; + + // do actual shit + struct archive_entry *entry; + while ((err = archive_read_next_header(archive, &entry)) == ARCHIVE_OK) { + char entry_path[MAX_PATH]; + if (!path_normalize(archive_entry_pathname(entry), entry_path)) { + // Avoid pwnage + fprintf(stderr, "warning: skipped possible path traversal %s\n", archive_entry_pathname(entry)); + continue; + } + if (!progress_update(&p, (double) archive_filter_bytes(archive, -1) / archive_bytes, entry_path)) + CANCEL(); + if (strcmp(entry_path, "") == 0) + archive_has_root = true; + + const char *hardlink = archive_entry_hardlink(entry); + if (hardlink) { + char hardlink_path[MAX_PATH]; + if (!path_normalize(hardlink, hardlink_path)) { + fprintf(stderr, "warning: almost pwned by hardlink %s\n", hardlink); + continue; + } + if (linkat(root_fd, fix_path(hardlink_path), root_fd, fix_path(entry_path), 0) < 0) + POSIX_ERR(); + sqlite3_bind_blob64(insert_hardlink, 1, entry_path, strlen(entry_path), SQLITE_TRANSIENT); + sqlite3_bind_blob64(insert_hardlink, 2, hardlink_path, strlen(hardlink_path), SQLITE_TRANSIENT); + STEP_RESET(insert_hardlink); + continue; + } + + // mkdir -p + char *entry_path_copy = strdup(entry_path); + char *slash = entry_path_copy; + while ((slash = strchr(*slash ? slash + 1 : slash, '/')) != NULL) { + *slash = '\0'; + int err = mkdirat(root_fd, fix_path(entry_path_copy), 0777); + *slash = '/'; + if (err < 0) { + if (errno == EEXIST) continue; + POSIX_ERR(); + } + } + free(entry_path_copy); + + int fd = -1; + // first, create node + switch (archive_entry_filetype(entry)) { + case AE_IFREG: + case AE_IFLNK: + case AE_IFBLK: + case AE_IFCHR: + case AE_IFSOCK: + fd = openat(root_fd, fix_path(entry_path), O_WRONLY | O_CREAT | O_TRUNC, 0666); + if (fd < 0) { + if (errno == EISDIR) continue; // assuming it's case insensitivity + POSIX_ERR(); + } + break; + + case AE_IFDIR: + err = mkdirat(root_fd, fix_path(entry_path), 0777); + if (err < 0 && errno != EEXIST) + POSIX_ERR(); + break; + + case AE_IFIFO: + lock_fchdir(root_fd); + err = mkfifo(fix_path(entry_path), 0666); + unlock_fchdir(); + break; + } + // second, fill in contents, if needed + switch (archive_entry_filetype(entry)) { + case AE_IFREG: + if (archive_read_data_into_fd(archive, fd) != ARCHIVE_OK) + ARCHIVE_ERR(archive); + break; + + case AE_IFLNK: + err = (int) write(fd, archive_entry_symlink(entry), strlen(archive_entry_symlink(entry))); + if (err < 0) + POSIX_ERR(); + break; + + case AE_IFDIR: + case AE_IFBLK: + case AE_IFCHR: + case AE_IFSOCK: + case AE_IFIFO: + break; + } + if (fd != -1) + close(fd); + + struct timespec times[2] = { + // for utimes, atime is first, mtime is second + {.tv_sec = archive_entry_atime(entry), .tv_nsec = archive_entry_atime_nsec(entry)}, + {.tv_sec = archive_entry_mtime(entry), .tv_nsec = archive_entry_mtime_nsec(entry)}, + // utimes cannot set ctime + }; + if (!archive_entry_atime_is_set(entry)) + times[0].tv_nsec = UTIME_OMIT; + if (!archive_entry_mtime_is_set(entry)) + times[1].tv_nsec = UTIME_OMIT; + err = utimensat(root_fd, fix_path(entry_path), times, 0); + if (err < 0) + POSIX_ERR(); + + struct ish_stat stat = { + .mode = (uint32_t) archive_entry_mode(entry), + .uid = (uint32_t) archive_entry_uid(entry), + .gid = (uint32_t) archive_entry_gid(entry), + .rdev = (uint32_t) archive_entry_rdev(entry), + }; + sqlite3_bind_blob64(insert_stat, 1, &stat, sizeof(stat), SQLITE_TRANSIENT); + STEP_RESET(insert_stat); + sqlite3_bind_blob64(insert_path, 1, entry_path, strlen(entry_path), SQLITE_TRANSIENT); + sqlite3_bind_int64(insert_path, 2, sqlite3_last_insert_rowid(db)); + STEP_RESET(insert_path); + } + if (err != ARCHIVE_EOF) + ARCHIVE_ERR(archive); + + // Add a path entry for the root if it's missing + if (!archive_has_root) { + struct ish_stat stat = {.mode = 0755}; + sqlite3_bind_blob64(insert_stat, 1, &stat, sizeof(stat), SQLITE_TRANSIENT); + STEP_RESET(insert_stat); + sqlite3_bind_blob64(insert_path, 1, "", 0, SQLITE_TRANSIENT); + sqlite3_bind_int64(insert_path, 2, sqlite3_last_insert_rowid(db)); + STEP_RESET(insert_path); + } + + FINALIZE(insert_stat); + FINALIZE(insert_path); + FINALIZE(insert_hardlink); + EXEC("commit"); + sqlite3_close(db); + close(root_fd); + + if (archive_read_free(archive) != ARCHIVE_OK) + ARCHIVE_ERR(archive); + return true; +} + +bool fakefs_export(const char *fs, const char *archive_path, struct fakefsify_error *err_out, struct progress p) { + // open the archive + struct archive *archive = archive_write_new(); + if (archive == NULL) + ARCHIVE_ERR(archive); + archive_write_add_filter_gzip(archive); + archive_write_set_format_pax(archive); + if (archive_write_open_filename(archive, archive_path) != ARCHIVE_OK) + ARCHIVE_ERR(archive); + + // open the data root dir + char path_tmp[PATH_MAX]; + snprintf(path_tmp, sizeof(path_tmp), "%s/data", fs); + int root_fd = open(path_tmp, O_RDONLY); + if (root_fd < 0) + POSIX_ERR(); + + // open the database + snprintf(path_tmp, sizeof(path_tmp), "%s/meta.db", fs); + sqlite3 *db; + int err = sqlite3_open_v2(path_tmp, &db, SQLITE_OPEN_READONLY, NULL); + CHECK_ERR(); + EXEC("begin"); + + sqlite3_stmt *count_stmt = PREPARE("select count(path) from paths"); + STEP(count_stmt); + int64_t paths_total = sqlite3_column_int64(count_stmt, 0); + FINALIZE(count_stmt); + int64_t paths_done = 0; + + struct archive_entry_linkresolver *linkresolver = archive_entry_linkresolver_new(); + archive_entry_linkresolver_set_strategy(linkresolver, ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE); + + sqlite3_stmt *query = PREPARE("select path, inode, stat from paths, stats using (inode)"); + while (STEP(query)) { + struct archive_entry *entry = archive_entry_new(); + + const char *path_in_db = sqlite3_column_blob(query, 0); + size_t path_len = sqlite3_column_bytes(query, 0); + char *path = malloc(path_len + 2); + path[0] = '.'; + memcpy(path + 1, path_in_db, path_len); + path[path_len + 1] = '\0'; + archive_entry_set_pathname(entry, path); + + if (!progress_update(&p, (double) paths_done / paths_total, path)) + CANCEL(); + + archive_entry_set_ino64(entry, sqlite3_column_int64(query, 1)); + struct ish_stat stat = *(struct ish_stat *) sqlite3_column_blob(query, 2); + archive_entry_set_mode(entry, stat.mode); + archive_entry_set_uid(entry, stat.uid); + archive_entry_set_gid(entry, stat.gid); + archive_entry_set_rdev(entry, stat.rdev); + + struct stat real_stat; + if (fstatat(root_fd, path, &real_stat, 0) < 0) { + if (errno == ENOENT) { + printf("skipping %s\n", path); + goto skip; + } + POSIX_ERR(); + } + archive_entry_set_size(entry, real_stat.st_size); +#if __APPLE__ +#define TIMESPEC(x) st_##x##timespec +#elif __linux__ +#define TIMESPEC(x) st_##x##tim +#endif + archive_entry_set_atime(entry, real_stat.st_atime, real_stat.TIMESPEC(a).tv_nsec); + archive_entry_set_mtime(entry, real_stat.st_mtime, real_stat.TIMESPEC(m).tv_nsec); + archive_entry_set_ctime(entry, real_stat.st_ctime, real_stat.TIMESPEC(c).tv_nsec); + + int fd = -1; + S_IFMT; + if (S_ISREG(stat.mode) || S_ISLNK(stat.mode)) + fd = openat(root_fd, path, O_RDONLY); + if (S_ISLNK(stat.mode)) { + char buf[MAX_PATH+1]; + ssize_t len = read(fd, buf, sizeof(buf)-1); + if (len < 0) + POSIX_ERR(); + buf[len] = '\0'; + archive_entry_set_symlink(entry, buf); + } + + struct archive_entry *sparse; + archive_entry_linkify(linkresolver, &entry, &sparse); + if (entry != NULL) + archive_write_header(archive, entry); + if (sparse != NULL) + archive_write_header(archive, sparse); + + if (S_ISREG(stat.mode) && archive_entry_size(entry) != 0) { + char buf[8192]; + ssize_t len; + while ((len = read(fd, buf, sizeof(buf))) > 0) { + ssize_t written = archive_write_data(archive, buf, len); + if (written < 0) + ARCHIVE_ERR(archive); + if (written != len) + printf("uh oh\n"); + } + if (len < 0) + POSIX_ERR(); + } + if (fd != -1) + close(fd); + + skip: + paths_done++; + free(path); + archive_entry_free(entry); + } + + FINALIZE(query); + archive_entry_linkresolver_free(linkresolver); + sqlite3_close(db); + close(root_fd); + if (archive_write_close(archive) != ARCHIVE_OK) + ARCHIVE_ERR(archive); + archive_write_free(archive); + return true; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/fakefs.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/fakefs.h new file mode 100644 index 0000000000..a273255c96 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/fakefs.h @@ -0,0 +1,25 @@ +#ifndef FS_FAKEFSIFY_H +#define FS_FAKEFSIFY_H +#include <stdbool.h> + +struct fakefsify_error { + int line; + enum { + ERR_ARCHIVE, + ERR_SQLITE, + ERR_POSIX, + ERR_CANCELLED, + } type; + int code; + char *message; +}; + +struct progress { + void *cookie; + void (*callback)(void *cookie, double progress, const char *message, bool *cancel_out); +}; + +bool fakefs_import(const char *archive_path, const char *fs, struct fakefsify_error *err_out, struct progress progress); +bool fakefs_export(const char *fs, const char *archive_path, struct fakefsify_error *err_out, struct progress progress); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/fakefsify.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/fakefsify.c new file mode 100644 index 0000000000..039ebf1a4b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/fakefsify.c @@ -0,0 +1,43 @@ +#include <stdio.h> +#include <string.h> +#include <libgen.h> + +#define ISH_INTERNAL +#include "fs/fake.h" +#include "tools/fakefs.h" + +enum cmd { + cmd_import, + cmd_export, +}; + +int main(int argc, const char *argv[]) { + enum cmd cmd = cmd_import; + if (strcmp(basename((char *) argv[0]), "unfakefsify") == 0) { + cmd = cmd_export; + } + + if (argc != 3) { + fprintf(stderr, "wrong number of arguments\n"); + switch (cmd) { + case cmd_import: + fprintf(stderr, "usage: %s <rootfs.tar.gz> <fakefs>\n", argv[0]); + break; + case cmd_export: + fprintf(stderr, "usage: %s <fakefs> <rootfs.tar.gz>\n", argv[0]); + break; + } + return 1; + } + + struct fakefsify_error err; + bool (*func)(const char *, const char *, struct fakefsify_error *, struct progress) = NULL; + if (cmd == cmd_import) + func = fakefs_import; + else if (cmd == cmd_export) + func = fakefs_export; + if (!(*func)(argv[1], argv[2], &err, (struct progress) {})) { + fprintf(stderr, "error!!1! %d %d %s\n", err.line, err.type, err.message); + return 1; + } +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/ish_sdl_vnc.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/ish_sdl_vnc.c new file mode 100644 index 0000000000..96135d9f6d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/ish_sdl_vnc.c @@ -0,0 +1,492 @@ +#define _GNU_SOURCE +#include <errno.h> +#include <fcntl.h> +#include <poll.h> +#include <pty.h> +#include <rfb/keysym.h> +#include <rfb/rfb.h> +#include <signal.h> +#include <stdbool.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/ioctl.h> +#include <sys/wait.h> +#include <termios.h> +#include <unistd.h> + +#include <SDL2/SDL.h> +#include <SDL2/SDL_ttf.h> +#include <vterm.h> + +#define DEFAULT_COLS 120 +#define DEFAULT_ROWS 36 +#define DEFAULT_FONT_SIZE 18 +#define DEFAULT_VNC_PORT 5907 +#define MAX_ARGV 128 + +typedef struct Harness { + int cols; + int rows; + int cell_w; + int cell_h; + int width; + int height; + int pty_fd; + pid_t child_pid; + bool dirty; + bool running; + bool headless; + SDL_Window *window; + SDL_Surface *window_surface; + SDL_Surface *frame; + TTF_Font *font; + VTerm *vt; + VTermScreen *screen; + rfbScreenInfoPtr vnc; + int cursor_visible; +} Harness; + +static void die(const char *msg) { + perror(msg); + exit(1); +} + +static void set_nonblock(int fd) { + int flags = fcntl(fd, F_GETFL, 0); + if (flags < 0) + die("fcntl(F_GETFL)"); + if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) + die("fcntl(F_SETFL)"); +} + +static void pty_write_all(Harness *h, const char *buf, size_t len) { + while (len > 0) { + ssize_t n = write(h->pty_fd, buf, len); + if (n < 0) { + if (errno == EINTR) + continue; + if (errno == EAGAIN || errno == EWOULDBLOCK) + return; + return; + } + buf += n; + len -= (size_t)n; + } +} + +static void pty_send(Harness *h, const char *s) { + pty_write_all(h, s, strlen(s)); +} + +static void send_key_sequence(Harness *h, SDL_Keycode key, bool ctrl, bool alt, bool shift) { + (void)alt; + (void)shift; + if (ctrl && key >= SDLK_a && key <= SDLK_z) { + char c = (char)(key - SDLK_a + 1); + pty_write_all(h, &c, 1); + return; + } + switch (key) { + case SDLK_RETURN: pty_send(h, "\r"); break; + case SDLK_BACKSPACE: { char c = 0x7f; pty_write_all(h, &c, 1); break; } + case SDLK_TAB: pty_send(h, "\t"); break; + case SDLK_ESCAPE: { char c = 0x1b; pty_write_all(h, &c, 1); break; } + case SDLK_UP: pty_send(h, "\x1b[A"); break; + case SDLK_DOWN: pty_send(h, "\x1b[B"); break; + case SDLK_RIGHT: pty_send(h, "\x1b[C"); break; + case SDLK_LEFT: pty_send(h, "\x1b[D"); break; + case SDLK_HOME: pty_send(h, "\x1b[H"); break; + case SDLK_END: pty_send(h, "\x1b[F"); break; + case SDLK_DELETE: pty_send(h, "\x1b[3~"); break; + case SDLK_PAGEUP: pty_send(h, "\x1b[5~"); break; + case SDLK_PAGEDOWN: pty_send(h, "\x1b[6~"); break; + default: break; + } +} + +static void send_vnc_keysym(Harness *h, rfbKeySym sym, bool down) { + if (!down) + return; + if (sym >= 0x20 && sym <= 0x7e) { + char c = (char)sym; + pty_write_all(h, &c, 1); + return; + } + switch (sym) { + case XK_Return: pty_send(h, "\r"); break; + case XK_BackSpace: { char c = 0x7f; pty_write_all(h, &c, 1); break; } + case XK_Tab: pty_send(h, "\t"); break; + case XK_Escape: { char c = 0x1b; pty_write_all(h, &c, 1); break; } + case XK_Up: pty_send(h, "\x1b[A"); break; + case XK_Down: pty_send(h, "\x1b[B"); break; + case XK_Right: pty_send(h, "\x1b[C"); break; + case XK_Left: pty_send(h, "\x1b[D"); break; + case XK_Home: pty_send(h, "\x1b[H"); break; + case XK_End: pty_send(h, "\x1b[F"); break; + case XK_Delete: pty_send(h, "\x1b[3~"); break; + case XK_Page_Up: pty_send(h, "\x1b[5~"); break; + case XK_Page_Down: pty_send(h, "\x1b[6~"); break; + default: break; + } +} + +static SDL_Color color_from_vterm(Harness *h, VTermColor in) { + vterm_screen_convert_color_to_rgb(h->screen, &in); + SDL_Color c = { in.rgb.red, in.rgb.green, in.rgb.blue, 255 }; + return c; +} + +static void fill_rect32(SDL_Surface *surface, int x, int y, int w, int h, SDL_Color c) { + SDL_Rect rect = {x, y, w, h}; + Uint32 pixel = SDL_MapRGBA(surface->format, c.r, c.g, c.b, 255); + SDL_FillRect(surface, &rect, pixel); +} + +static void draw_utf8_glyph(Harness *h, uint32_t cp, SDL_Color fg, SDL_Color bg, int x, int y) { + fill_rect32(h->frame, x, y, h->cell_w, h->cell_h, bg); + if (cp == 0 || cp == ' ') + return; + + SDL_Surface *glyph = TTF_RenderGlyph32_Blended(h->font, cp, fg); + if (glyph == NULL) + glyph = TTF_RenderGlyph32_Blended(h->font, '?', fg); + if (glyph == NULL) + return; + + SDL_Rect dst = { + .x = x, + .y = y + (h->cell_h - glyph->h) / 2, + .w = glyph->w, + .h = glyph->h, + }; + SDL_BlitSurface(glyph, NULL, h->frame, &dst); + SDL_FreeSurface(glyph); +} + +static void redraw(Harness *h) { + if (!h->dirty) + return; + + VTermPos cursor = {0, 0}; + vterm_state_get_cursorpos(vterm_obtain_state(h->vt), &cursor); + + for (int row = 0; row < h->rows; row++) { + for (int col = 0; col < h->cols; col++) { + VTermScreenCell cell; + VTermPos pos = {.row = row, .col = col}; + if (!vterm_screen_get_cell(h->screen, pos, &cell)) + memset(&cell, 0, sizeof(cell)); + SDL_Color fg = color_from_vterm(h, cell.fg); + SDL_Color bg = color_from_vterm(h, cell.bg); + if (cell.attrs.reverse) { + SDL_Color tmp = fg; fg = bg; bg = tmp; + } + if (h->cursor_visible && cursor.row == row && cursor.col == col) { + SDL_Color tmp = fg; fg = bg; bg = tmp; + } + uint32_t cp = cell.chars[0]; + draw_utf8_glyph(h, cp, fg, bg, col * h->cell_w, row * h->cell_h); + } + } + + if (!h->headless && h->window_surface) { + SDL_BlitSurface(h->frame, NULL, h->window_surface, NULL); + SDL_UpdateWindowSurface(h->window); + } + if (h->vnc) { + rfbMarkRectAsModified(h->vnc, 0, 0, h->width, h->height); + } + h->dirty = false; +} + +static int screen_damage(VTermRect rect, void *user) { + (void)rect; + Harness *h = user; + h->dirty = true; + return 1; +} + +static int screen_moverect(VTermRect dest, VTermRect src, void *user) { + (void)dest; (void)src; + Harness *h = user; + h->dirty = true; + return 1; +} + +static int screen_movecursor(VTermPos pos, VTermPos oldpos, int visible, void *user) { + (void)pos; (void)oldpos; (void)visible; + Harness *h = user; + h->dirty = true; + return 1; +} + +static int screen_settermprop(VTermProp prop, VTermValue *val, void *user) { + Harness *h = user; + if (prop == VTERM_PROP_CURSORVISIBLE) + h->cursor_visible = val->boolean; + h->dirty = true; + return 1; +} + +static int screen_bell(void *user) { + Harness *h = user; + h->dirty = true; + return 1; +} + +static int screen_resize(int rows, int cols, void *user) { + Harness *h = user; + if (rows == h->rows && cols == h->cols) + return 1; + h->rows = rows; + h->cols = cols; + h->width = cols * h->cell_w; + h->height = rows * h->cell_h; + h->dirty = true; + return 1; +} + +static void vnc_keyboard(rfbBool down, rfbKeySym key, rfbClientPtr cl) { + Harness *h = cl->screen->screenData; + send_vnc_keysym(h, key, down); +} + +static void vnc_ptr(int buttonMask, int x, int y, rfbClientPtr cl) { + (void)buttonMask; (void)x; (void)y; (void)cl; +} + +static void install_winsize(Harness *h) { + struct winsize ws = { + .ws_col = (unsigned short)h->cols, + .ws_row = (unsigned short)h->rows, + .ws_xpixel = (unsigned short)h->width, + .ws_ypixel = (unsigned short)h->height, + }; + ioctl(h->pty_fd, TIOCSWINSZ, &ws); +} + +static void spawn_ish(Harness *h, const char *ish_bin, const char *rootfs, char **child_argv) { + struct winsize ws = { + .ws_col = (unsigned short)h->cols, + .ws_row = (unsigned short)h->rows, + .ws_xpixel = (unsigned short)h->width, + .ws_ypixel = (unsigned short)h->height, + }; + pid_t pid = forkpty(&h->pty_fd, NULL, NULL, &ws); + if (pid < 0) + die("forkpty"); + if (pid == 0) { + setenv("TERM", "xterm-256color", 1); + char *argv[MAX_ARGV]; + int i = 0; + argv[i++] = (char *)ish_bin; + argv[i++] = "-f"; + argv[i++] = (char *)rootfs; + for (int j = 0; child_argv[j] && i < MAX_ARGV - 1; j++) + argv[i++] = child_argv[j]; + argv[i] = NULL; + execvp(ish_bin, argv); + perror("execvp"); + _exit(127); + } + h->child_pid = pid; + set_nonblock(h->pty_fd); +} + +static void usage(const char *argv0) { + fprintf(stderr, + "usage: %s [--headless] [--ish PATH] [--rootfs PATH] [--font PATH] [--font-size N] [--cols N] [--rows N] [--vnc-port N] [--] [guest cmd ...]\n", + argv0); +} + +int main(int argc, char **argv) { + Harness h = { + .cols = DEFAULT_COLS, + .rows = DEFAULT_ROWS, + .running = true, + .dirty = true, + .headless = false, + .cursor_visible = 1, + }; + + const char *ish_bin = "./build-clang/ish"; + const char *rootfs = "./rootfs/alpine"; + const char *font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"; + int font_size = DEFAULT_FONT_SIZE; + int vnc_port = DEFAULT_VNC_PORT; + + int argi = 1; + while (argi < argc) { + if (strcmp(argv[argi], "--") == 0) { + argi++; + break; + } else if (strcmp(argv[argi], "--headless") == 0) { + h.headless = true; + argi++; + } else if (strcmp(argv[argi], "--ish") == 0 && argi + 1 < argc) { + ish_bin = argv[argi + 1]; + argi += 2; + } else if (strcmp(argv[argi], "--rootfs") == 0 && argi + 1 < argc) { + rootfs = argv[argi + 1]; + argi += 2; + } else if (strcmp(argv[argi], "--font") == 0 && argi + 1 < argc) { + font_path = argv[argi + 1]; + argi += 2; + } else if (strcmp(argv[argi], "--font-size") == 0 && argi + 1 < argc) { + font_size = atoi(argv[argi + 1]); + argi += 2; + } else if (strcmp(argv[argi], "--cols") == 0 && argi + 1 < argc) { + h.cols = atoi(argv[argi + 1]); + argi += 2; + } else if (strcmp(argv[argi], "--rows") == 0 && argi + 1 < argc) { + h.rows = atoi(argv[argi + 1]); + argi += 2; + } else if (strcmp(argv[argi], "--vnc-port") == 0 && argi + 1 < argc) { + vnc_port = atoi(argv[argi + 1]); + argi += 2; + } else { + break; + } + } + + char *default_cmd[] = {"/bin/sh", NULL}; + char **child_argv = (argi < argc) ? &argv[argi] : default_cmd; + + if (TTF_Init() < 0) { + fprintf(stderr, "TTF_Init: %s\n", TTF_GetError()); + return 1; + } + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) < 0) { + fprintf(stderr, "SDL_Init: %s\n", SDL_GetError()); + return 1; + } + + h.font = TTF_OpenFont(font_path, font_size); + if (!h.font) { + fprintf(stderr, "TTF_OpenFont(%s): %s\n", font_path, TTF_GetError()); + return 1; + } + if (TTF_SizeUTF8(h.font, "M", &h.cell_w, &h.cell_h) < 0) { + fprintf(stderr, "TTF_SizeUTF8: %s\n", TTF_GetError()); + return 1; + } + h.cell_w += 1; + h.width = h.cols * h.cell_w; + h.height = h.rows * h.cell_h; + + h.frame = SDL_CreateRGBSurfaceWithFormat(0, h.width, h.height, 32, SDL_PIXELFORMAT_ARGB8888); + if (!h.frame) { + fprintf(stderr, "SDL_CreateRGBSurfaceWithFormat: %s\n", SDL_GetError()); + return 1; + } + + if (!h.headless) { + h.window = SDL_CreateWindow("iSH SDL/VNC harness", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, + h.width, h.height, 0); + if (!h.window) { + fprintf(stderr, "SDL_CreateWindow: %s\n", SDL_GetError()); + return 1; + } + h.window_surface = SDL_GetWindowSurface(h.window); + } + + h.vt = vterm_new(h.rows, h.cols); + if (!h.vt) + die("vterm_new"); + h.screen = vterm_obtain_screen(h.vt); + VTermScreenCallbacks callbacks = { + .damage = screen_damage, + .moverect = screen_moverect, + .movecursor = screen_movecursor, + .settermprop = screen_settermprop, + .bell = screen_bell, + .resize = screen_resize, + }; + vterm_screen_set_callbacks(h.screen, &callbacks, &h); + vterm_screen_set_damage_merge(h.screen, VTERM_DAMAGE_SCREEN); + vterm_screen_reset(h.screen, 1); + + int argc_vnc = 3; + char *argv_vnc[] = { (char *)"ish-sdl-vnc", (char *)"-rfbport", NULL, NULL }; + char portbuf[32]; + snprintf(portbuf, sizeof(portbuf), "%d", vnc_port); + argv_vnc[2] = portbuf; + h.vnc = rfbGetScreen(&argc_vnc, argv_vnc, h.width, h.height, 8, 3, 4); + if (!h.vnc) + die("rfbGetScreen"); + h.vnc->frameBuffer = (char *)h.frame->pixels; + h.vnc->desktopName = "iSH SDL/VNC harness"; + h.vnc->port = vnc_port; + h.vnc->ipv6port = vnc_port; + h.vnc->kbdAddEvent = vnc_keyboard; + h.vnc->ptrAddEvent = vnc_ptr; + h.vnc->screenData = &h; + rfbInitServer(h.vnc); + + spawn_ish(&h, ish_bin, rootfs, child_argv); + install_winsize(&h); + SDL_StartTextInput(); + + fprintf(stderr, "Harness ready: SDL=%s VNC=:%d child_pid=%d\n", + h.headless ? "headless" : "window", vnc_port, (int)h.child_pid); + + struct pollfd pfd = {.fd = h.pty_fd, .events = POLLIN}; + while (h.running) { + char buf[8192]; + ssize_t n = read(h.pty_fd, buf, sizeof(buf)); + if (n > 0) { + vterm_input_write(h.vt, buf, (size_t)n); + vterm_screen_flush_damage(h.screen); + h.dirty = true; + } else if (n == 0) { + h.running = false; + } else if (!(errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) { + h.running = false; + } + + SDL_Event ev; + while (SDL_PollEvent(&ev)) { + if (ev.type == SDL_QUIT) { + h.running = false; + } else if (ev.type == SDL_TEXTINPUT) { + pty_send(&h, ev.text.text); + } else if (ev.type == SDL_KEYDOWN) { + bool ctrl = (ev.key.keysym.mod & KMOD_CTRL) != 0; + bool alt = (ev.key.keysym.mod & KMOD_ALT) != 0; + bool shift = (ev.key.keysym.mod & KMOD_SHIFT) != 0; + send_key_sequence(&h, ev.key.keysym.sym, ctrl, alt, shift); + } + } + + rfbProcessEvents(h.vnc, 0); + redraw(&h); + + int status = 0; + pid_t res = waitpid(h.child_pid, &status, WNOHANG); + if (res == h.child_pid) { + h.running = false; + } + + poll(&pfd, 1, 10); + } + + if (h.child_pid > 0) { + kill(h.child_pid, SIGTERM); + waitpid(h.child_pid, NULL, 0); + } + if (h.vnc) + rfbScreenCleanup(h.vnc); + if (h.window) + SDL_DestroyWindow(h.window); + if (h.frame) + SDL_FreeSurface(h.frame); + if (h.font) + TTF_CloseFont(h.font); + if (h.vt) + vterm_free(h.vt); + TTF_Quit(); + SDL_Quit(); + return 0; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/meson.build b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/meson.build new file mode 100644 index 0000000000..c9e3c95019 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/meson.build @@ -0,0 +1,40 @@ +libarchive = dependency('libarchive', required: false) +if not libarchive.found() + # homebrew + libarchive_lib = cc.find_library('archive', dirs: ['/usr/local/opt/libarchive/lib'], required: false) + if libarchive_lib.found() + libarchive = declare_dependency(dependencies: [libarchive_lib], include_directories: include_directories(['/usr/local/opt/libarchive/include'])) + else + # Apple Silicon Homebrew + libarchive_lib = cc.find_library('archive', dirs: ['/opt/homebrew/opt/libarchive/lib'], required: false) + if libarchive_lib.found() + libarchive = declare_dependency(dependencies: [libarchive_lib], include_directories: include_directories(['/opt/homebrew/opt/libarchive/include'])) + endif + endif +endif + +if libarchive.found() + fakefsify_src = [ + 'fakefsify.c', + 'fakefs.c', + '../util/fchdir.c', + ] + fakefsify = executable('fakefsify', fakefsify_src, dependencies: [libarchive], link_with: [libfakefs], include_directories: [includes]) + custom_target('unfakefsify', + build_by_default: true, + command: ['ln', '-sf', 'fakefsify', '@OUTPUT@'], + output: 'unfakefsify') +endif + +if host_machine.system() == 'linux' + sdl2 = dependency('sdl2', required: false) + sdl2_ttf = dependency('SDL2_ttf', required: false) + vterm = dependency('vterm', required: false) + libutil = cc.find_library('util', required: false) + libvncserver = cc.find_library('vncserver', required: false) + if sdl2.found() and sdl2_ttf.found() and vterm.found() and libutil.found() and libvncserver.found() + executable('ish-sdl-vnc', ['ish_sdl_vnc.c'], + include_directories: includes, + dependencies: [sdl2, sdl2_ttf, vterm, libutil, libvncserver]) + endif +endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/run-sdl-vnc.sh b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/run-sdl-vnc.sh new file mode 100755 index 0000000000..1b21be7438 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/run-sdl-vnc.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +BUILD_DIR="${BUILD_DIR:-$ROOT/build-linux-harness}" +ISH_BIN="${ISH_BIN:-$ROOT/build-arm64-linux/ish}" +HARNESS_BIN="${HARNESS_BIN:-$BUILD_DIR/tools/ish-sdl-vnc}" +ROOTFS_DIR="${ROOTFS_DIR:-$ROOT/alpine-arm64-fakefs}" +FONT_PATH="${FONT_PATH:-/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf}" +VNC_PORT="${VNC_PORT:-5907}" +COLS="${COLS:-120}" +ROWS="${ROWS:-36}" +FONT_SIZE="${FONT_SIZE:-18}" +HEADLESS="${HEADLESS:-0}" + +if [[ ! -x "$HARNESS_BIN" ]]; then + echo "missing harness binary: $HARNESS_BIN" >&2 + exit 1 +fi +if [[ ! -x "$ISH_BIN" ]]; then + echo "missing ish binary: $ISH_BIN" >&2 + exit 1 +fi +if [[ ! -d "$ROOTFS_DIR" ]]; then + echo "missing rootfs dir: $ROOTFS_DIR" >&2 + exit 1 +fi + +args=( + "$HARNESS_BIN" + --ish "$ISH_BIN" + --rootfs "$ROOTFS_DIR" + --font "$FONT_PATH" + --font-size "$FONT_SIZE" + --cols "$COLS" + --rows "$ROWS" + --vnc-port "$VNC_PORT" +) + +if [[ "$HEADLESS" != "0" ]]; then + args+=(--headless) +fi + +if [[ "$#" -gt 0 ]]; then + args+=(-- "$@") +fi + +exec "${args[@]}" diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/staticdefine.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/staticdefine.h new file mode 100644 index 0000000000..a6a476e036 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/staticdefine.h @@ -0,0 +1,16 @@ +// credit goes to include/linux/kbuild.h +#define _DEFINE(sym, val) \ + asm volatile("\n.ascii \"->" sym " %0 " #val "\"" : : "i" (val)) +#define DEFINE(sym, val) \ + _DEFINE(#sym, val) + +#define BLANK() asm volatile("\n.ascii \"->\"" : : ) + +#define OFFSET(sym, str, mem) \ + DEFINE(sym##_##mem, offsetof(struct str, mem)) + +#define MACRO(macro) \ + _DEFINE(#macro, macro) + +#define COMMENT(x) \ + asm volatile("\n.ascii \"->#" x "\"") diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/staticdefine.sh b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/staticdefine.sh new file mode 100755 index 0000000000..08f589048b --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/tools/staticdefine.sh @@ -0,0 +1,23 @@ +#!/bin/bash -e +compile_commands=$1 +input=$2 +output=$3 +dep=$4 +flags=$(python3 - <<END +import json +with open('$compile_commands') as f: + commands = json.load(f) +for command in commands: + if command['file'].endswith('asbestos/asbestos.c'): + break +command = command['command'] +command = command.split()[:-9] + ['-MD', '-MQ', '$output', '-MF', '$dep'] +print(' '.join(command)) +END +) +$flags $input -include "$(dirname $0)/staticdefine.h" -S -o - | \ +sed -ne 's:^[[:space:]]*\.ascii[[:space:]]*"\(.*\)".*:\1:; + /^->/{s:->#\(.*\):/* \1 */:; + s:^->\([^ ]*\) [\$$#]*\([^ ]*\) \(.*\):#define \1 \2 /* \3 */:; + s:->::; p;}' > $output +# sed magic was copied from the linux kernel build system diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/util/bits.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/bits.h new file mode 100644 index 0000000000..d865872d89 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/bits.h @@ -0,0 +1,22 @@ +#ifndef BITS_H +#define BITS_H + +typedef void bits_t; +#define BITS_SIZE(bits) ((((bits) - 1) / 8) + 1) + +static inline bool bit_test(size_t i, bits_t *data) { + char *c = data; + return c[i >> 3] & (1 << (i & 7)) ? 1 : 0; +} + +static inline void bit_set(size_t i, bits_t *data) { + char *c = data; + c[i >> 3] |= 1 << (i & 7); +} + +static inline void bit_clear(size_t i, bits_t *data) { + char *c = data; + c[i >> 3] &= ~(1 << (i & 7)); +} + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/util/fchdir.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/fchdir.c new file mode 100644 index 0000000000..67ac98c489 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/fchdir.c @@ -0,0 +1,13 @@ +#include <unistd.h> +#include "util/sync.h" + +static lock_t fchdir_lock = LOCK_INITIALIZER; + +void lock_fchdir(int dirfd) { + lock(&fchdir_lock); + fchdir(dirfd); +} + +void unlock_fchdir() { + unlock(&fchdir_lock); +} \ No newline at end of file diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/util/fchdir.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/fchdir.h new file mode 100644 index 0000000000..b60d79a32d --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/fchdir.h @@ -0,0 +1,4 @@ +// temporarily change directory and block other threads from doing so +// useful for simulating mknodat on ios, dealing with long unix socket paths, etc +void lock_fchdir(int dirfd); +void unlock_fchdir(); diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/util/fifo.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/fifo.c new file mode 100644 index 0000000000..77937aad41 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/fifo.c @@ -0,0 +1,67 @@ +#include <stdlib.h> +#include <string.h> +#include "util/fifo.h" + +void fifo_init(struct fifo *fifo, size_t capacity) { + fifo->buf = malloc(capacity); + fifo->capacity = capacity; + fifo->size = fifo->start = 0; +} + +void fifo_destroy(struct fifo *fifo) { + free(fifo->buf); +} + +size_t fifo_capacity(struct fifo *fifo) { + return fifo->capacity; +} +size_t fifo_size(struct fifo *fifo) { + return fifo->size; +} +size_t fifo_remaining(struct fifo *fifo) { + return fifo->capacity - fifo->size; +} + +int fifo_write(struct fifo *fifo, const void *data, size_t size, int flags) { + if (size > fifo_remaining(fifo)) { + if (!(flags & FIFO_OVERWRITE)) + return 1; + size_t excess = size - fifo_remaining(fifo); + fifo->start = (fifo->start + excess) % fifo->capacity; + fifo->size -= excess; + } + + size_t tail = (fifo->start + fifo->size) % fifo->capacity;; + size_t first_copy_size = fifo->capacity - tail; + if (first_copy_size > size) + first_copy_size = size; + memcpy(&fifo->buf[tail], data, first_copy_size); + memcpy(&fifo->buf[0], (char *) data + first_copy_size, size - first_copy_size); + fifo->size += size; + return 0; +} + +int fifo_read(struct fifo *fifo, void *buf, size_t size, int flags) { + if (size > fifo_size(fifo)) + return 1; + + size_t start = fifo->start; + if (flags & FIFO_LAST) + start = (start + (fifo->size - size)) % fifo->capacity; + + size_t first_copy_size = fifo->capacity - fifo->start; + if (first_copy_size > size) + first_copy_size = size; + memcpy(buf, &fifo->buf[start], first_copy_size); + memcpy((char *) buf + first_copy_size, &fifo->buf[0], size - first_copy_size); + + if (!(flags & FIFO_PEEK)) { + fifo->start = (start + size) % fifo->capacity; + fifo->size -= size; + } + return 0; +} + +void fifo_flush(struct fifo *fifo) { + fifo->size = 0; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/util/fifo.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/fifo.h new file mode 100644 index 0000000000..c75fc20cb4 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/fifo.h @@ -0,0 +1,31 @@ +#ifndef UTIL_FIFO_H +#define UTIL_FIFO_H +#include <sys/types.h> + +struct fifo { + char *buf; + size_t capacity; + size_t size; + size_t start; +}; + +#define FIFO_INIT(b) ((struct fifo) {.buf = b, .capacity = sizeof(b)}) +void fifo_init(struct fifo *fifo, size_t capacity); +void fifo_destroy(struct fifo *fifo); + +size_t fifo_capacity(struct fifo *fifo); +size_t fifo_size(struct fifo *fifo); +size_t fifo_remaining(struct fifo *fifo); + +// return 0 on success, 1 if size > fifo_remaining and FIFO_OVERWRITE was not specified +#define FIFO_OVERWRITE 1 +int fifo_write(struct fifo *fifo, const void *data, size_t size, int flags); + +// return 0 on success, 1 if size > fifo_size +#define FIFO_PEEK 1 // don't remove the bytes +#define FIFO_LAST 2 // return bytes from the end, not the start +int fifo_read(struct fifo *fifo, void *buf, size_t size, int flags); + +void fifo_flush(struct fifo *fifo); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/util/list.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/list.h new file mode 100644 index 0000000000..baccd1c850 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/list.h @@ -0,0 +1,101 @@ +#ifndef LIST_H +#define LIST_H + +#include <stdbool.h> +#include <stddef.h> + +struct list { + struct list *next, *prev; +}; + +#ifndef __KERNEL__ + +static inline void list_init(struct list *list) { + list->next = list; + list->prev = list; +} + +#define LIST_INITIALIZER(x) {.prev = &x, .next = &x} + +static inline bool list_null(struct list *list) { + return list->next == NULL && list->prev == NULL; +} + +static inline bool list_empty(struct list *list) { + return list->next == list || list_null(list); +} + +static inline void _list_add_between(struct list *prev, struct list *next, struct list *item) { + prev->next = item; + item->prev = prev; + item->next = next; + next->prev = item; +} + +static inline void list_add_tail(struct list *list, struct list *item) { + _list_add_between(list->prev, list, item); +} + +static inline void list_add(struct list *list, struct list *item) { + _list_add_between(list, list->next, item); +} + +static inline void list_add_before(struct list *before, struct list *item) { + list_add_tail(before, item); +} +static inline void list_add_after(struct list *after, struct list *item) { + list_add(after, item); +} + +static inline void list_init_add(struct list *list, struct list *item) { + if (list_null(list)) + list_init(list); + list_add(list, item); +} + +static inline void list_remove(struct list *item) { + item->prev->next = item->next; + item->next->prev = item->prev; + item->next = item->prev = NULL; +} + +static inline void list_remove_safe(struct list *item) { + if (!list_null(item)) + list_remove(item); +} + +#define list_entry(item, type, member) \ + container_of(item, type, member) +#define list_first_entry(list, type, member) \ + list_entry((list)->next, type, member) +#define list_next_entry(item, member) \ + list_entry((item)->member.next, typeof(*(item)), member) + +#define list_for_each(list, item) \ + for (item = (list)->next; item != (list); item = item->next) +#define list_for_each_safe(list, item, tmp) \ + for (item = (list)->next, tmp = item->next; item != (list); \ + item = tmp, tmp = item->next) + +#define list_for_each_entry(list, item, member) \ + for (item = list_entry((list)->next, typeof(*item), member); \ + &item->member != (list); \ + item = list_entry(item->member.next, typeof(*item), member)) +#define list_for_each_entry_safe(list, item, tmp, member) \ + for (item = list_first_entry(list, typeof(*(item)), member), \ + tmp = list_next_entry(item, member); \ + &item->member != (list); \ + item = tmp, tmp = list_next_entry(item, member)) + +static inline unsigned long list_size(struct list *list) { + unsigned long count = 0; + struct list *item; + list_for_each(list, item) { + count++; + } + return count; +} + +#endif + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/util/refcount.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/refcount.h new file mode 100644 index 0000000000..63eaae32d0 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/refcount.h @@ -0,0 +1,42 @@ +#ifndef UTIL_REFCOUNT_H +#define UTIL_REFCOUNT_H +#include <stdatomic.h> + +// An industrial-strength refcounting implementation. +// Safety first! Make sure to: +// - Write a release for every retain +// - Get exclusive access to the reference before retaining or releasing it + +struct refcount { + atomic_uint rc; +}; + +static inline void __refcount_init(struct refcount *refcount) { + refcount->rc = 1; +} +#define refcount_init(obj) __refcount_init(&(obj)->refcount) + +static inline int __refcount_get(struct refcount *refcount) { + return refcount->rc; +} +#define refcount_get(obj) __refcount_get(&(obj)->refcount) + +#define DECLARE_REFCOUNT(type) \ + void type##_retain(struct type *obj); \ + void type##_release(struct type *obj) + +#define __DEFINE_REFCOUNT(type, qualifiers) \ + qualifiers struct type *type##_retain(struct type *obj) { \ + obj->refcount.rc++; \ + return obj; \ + } \ + static void type##_cleanup(struct type *obj); \ + qualifiers void type##_release(struct type *obj) { \ + if (--obj->refcount.rc == 0) \ + type##_cleanup(obj); \ + } + +#define DEFINE_REFCOUNT(type) __DEFINE_REFCOUNT(type, ) +#define DEFINE_REFCOUNT_STATIC(type) __DEFINE_REFCOUNT(type, static) + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/util/sync.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/sync.c new file mode 100644 index 0000000000..c654d3959f --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/sync.c @@ -0,0 +1,131 @@ +#include <errno.h> +#include <limits.h> +#include "kernel/task.h" +#include "util/sync.h" +#include "debug.h" +#include "kernel/errno.h" + +void cond_init(cond_t *cond) { + pthread_condattr_t attr; + pthread_condattr_init(&attr); +#if __linux__ + pthread_condattr_setclock(&attr, CLOCK_MONOTONIC); +#endif + pthread_cond_init(&cond->cond, &attr); +} +void cond_destroy(cond_t *cond) { + pthread_cond_destroy(&cond->cond); +} + +static bool is_signal_pending(lock_t *lock) { + if (!current) + return false; + if (lock != ¤t->sighand->lock) + lock(¤t->sighand->lock); + bool pending = !!(current->pending & ~current->blocked); + if (lock != ¤t->sighand->lock) + unlock(¤t->sighand->lock); + return pending; +} + +int wait_for(cond_t *cond, lock_t *lock, struct timespec *timeout) { + if (is_signal_pending(lock)) + return _EINTR; + int err = wait_for_ignore_signals(cond, lock, timeout); + if (err < 0) + return _ETIMEDOUT; + if (is_signal_pending(lock)) + return _EINTR; + return 0; +} + +int wait_for_ignore_signals(cond_t *cond, lock_t *lock, struct timespec *timeout) { + if (current) { + lock(¤t->waiting_cond_lock); + current->waiting_cond = cond; + current->waiting_lock = lock; + unlock(¤t->waiting_cond_lock); + } + int rc = 0; +#if LOCK_DEBUG + struct lock_debug lock_tmp = lock->debug; + lock->debug = (struct lock_debug) { .initialized = lock->debug.initialized }; +#endif + if (!timeout) { + pthread_cond_wait(&cond->cond, &lock->m); + } else { +#if __linux__ + struct timespec abs_timeout; + clock_gettime(CLOCK_MONOTONIC, &abs_timeout); + abs_timeout.tv_sec += timeout->tv_sec; + abs_timeout.tv_nsec += timeout->tv_nsec; + if (abs_timeout.tv_nsec >= 1000000000) { + abs_timeout.tv_sec++; + abs_timeout.tv_nsec -= 1000000000; + } + rc = pthread_cond_timedwait(&cond->cond, &lock->m, &abs_timeout); +#elif __APPLE__ + rc = pthread_cond_timedwait_relative_np(&cond->cond, &lock->m, timeout); +#else +#error Unimplemented pthread_cond_wait relative timeout. +#endif + } +#if LOCK_DEBUG + lock->debug = lock_tmp; +#endif + + if (current) { + lock(¤t->waiting_cond_lock); + current->waiting_cond = NULL; + current->waiting_lock = NULL; + unlock(¤t->waiting_cond_lock); + } + if (rc == ETIMEDOUT) + return _ETIMEDOUT; + return 0; +} + +void notify(cond_t *cond) { + pthread_cond_broadcast(&cond->cond); +} +void notify_once(cond_t *cond) { + pthread_cond_signal(&cond->cond); +} + +__thread sigjmp_buf unwind_buf; +__thread bool should_unwind = false; + +void sigusr1_handler() { + if (should_unwind) { + should_unwind = false; + siglongjmp(unwind_buf, 1); + } +} + +// This is how you would mitigate the unlock/wait race if the wait +// is async signal safe. wait_for *should* be safe from this race +// because of synchronization involving the waiting_cond_lock. +#if 0 + sigset_t sigusr1; + sigemptyset(&sigusr1); + sigaddset(&sigusr1, SIGUSR1); + + if (current) { + if (sigsetjmp(unwind_buf, 1)) { + return _EINTR; + } + should_unwind = true; + sigprocmask(SIG_BLOCK, &sigusr1, NULL); + if (lock != ¤t->sighand->lock) + lock(¤t->sighand->lock); + bool pending = !!(current->pending & ~current->blocked); + if (lock != ¤t->sighand->lock) + unlock(¤t->sighand->lock); + sigprocmask(SIG_UNBLOCK, &sigusr1, NULL); + if (pending) { + should_unwind = false; + return _EINTR; + } + } +#endif + diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/util/sync.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/sync.h new file mode 100644 index 0000000000..beead16997 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/sync.h @@ -0,0 +1,216 @@ +#ifndef UTIL_SYNC_H +#define UTIL_SYNC_H + +#include <stdatomic.h> +#include <pthread.h> +#include <stdbool.h> +#include <assert.h> +#include <setjmp.h> +#include <errno.h> +#include <time.h> +#include <stdio.h> +#include "misc.h" +#include "debug.h" + +// locks, implemented using pthread + +#define LOCK_DEBUG 0 + +typedef struct { + pthread_mutex_t m; + pthread_t owner; +#if LOCK_DEBUG + struct lock_debug { + const char *file; // doubles as locked + int line; + int pid; + bool initialized; + } debug; +#endif +} lock_t; + +static inline void lock_init(lock_t *lock) { + pthread_mutex_init(&lock->m, NULL); +#if LOCK_DEBUG + lock->debug = (struct lock_debug) { + .initialized = true, + }; +#endif +} + +#if LOCK_DEBUG +#define LOCK_INITIALIZER {PTHREAD_MUTEX_INITIALIZER, 0, { .initialized = true }} +#else +#define LOCK_INITIALIZER {PTHREAD_MUTEX_INITIALIZER, 0} +#endif +static inline void __lock(lock_t *lock, __attribute__((unused)) const char *file, __attribute__((unused)) int line) { + pthread_mutex_lock(&lock->m); + lock->owner = pthread_self(); +#if LOCK_DEBUG + assert(lock->debug.initialized); + assert(!lock->debug.file && "Attempting to recursively lock"); + lock->debug.file = file; + lock->debug.line = line; + extern int current_pid(void); + lock->debug.pid = current_pid(); +#endif +} +#define lock(lock) __lock(lock, __FILE__, __LINE__) +static inline void unlock(lock_t *lock) { +#if LOCK_DEBUG + assert(lock->debug.initialized); + assert(lock->debug.file && "Attempting to unlock an unlocked lock"); + lock->debug = (struct lock_debug) { .initialized = true }; +#endif + lock->owner = zero_init(pthread_t); + pthread_mutex_unlock(&lock->m); +} + +static inline int trylock(lock_t *lock, __attribute__((unused)) const char *file, __attribute__((unused)) int line) { + int status = pthread_mutex_trylock(&lock->m); +#if LOCK_DEBUG + if (!status) { + lock->debug.file = file; + lock->debug.line = line; + extern int current_pid(void); + lock->debug.pid = current_pid(); + } +#endif + return status; +} +#define trylock(lock) trylock(lock, __FILE__, __LINE__) + +// conditions, implemented using pthread conditions but hacked so you can also +// be woken by a signal + +typedef struct { + pthread_cond_t cond; +} cond_t; +#define COND_INITIALIZER ((cond_t) {PTHREAD_COND_INITIALIZER}) + +// Must call before using the condition +void cond_init(cond_t *cond); +// Must call when finished with the condition (currently doesn't do much but might do something important eventually I guess) +void cond_destroy(cond_t *cond); +// Releases the lock, waits for the condition, and reacquires the lock. +// Returns _EINTR if waiting stopped because the thread received a signal, +// _ETIMEDOUT if waiting stopped because the timout expired, 0 otherwise. +// Will never return _ETIMEDOUT if timeout is NULL. +int must_check wait_for(cond_t *cond, lock_t *lock, struct timespec *timeout); +// Same as wait_for, except it will never return _EINTR +int wait_for_ignore_signals(cond_t *cond, lock_t *lock, struct timespec *timeout); +// Wake up all waiters. +void notify(cond_t *cond); +// Wake up one waiter. +void notify_once(cond_t *cond); + +// this is a read-write lock that prefers writers, i.e. if there are any +// writers waiting a read lock will block. +// on darwin pthread_rwlock_t is already like this, on linux you can configure +// it to prefer writers. not worrying about anything else right now. +typedef struct { + pthread_rwlock_t l; + // 0: unlocked + // -1: write-locked + // >0: read-locked with this many readers + atomic_int val; + const char *file; + int line; + int pid; +} wrlock_t; +static inline void wrlock_init(wrlock_t *lock) { + pthread_rwlockattr_t *pattr = NULL; +#if defined(__GLIBC__) + pthread_rwlockattr_t attr; + pattr = &attr; + pthread_rwlockattr_init(pattr); + pthread_rwlockattr_setkind_np(pattr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); +#endif + if (pthread_rwlock_init(&lock->l, pattr)) __builtin_trap(); + lock->val = lock->line = lock->pid = 0; + lock->file = NULL; +} + +extern int current_pid(void); +static inline void wrlock_destroy(wrlock_t *lock) { + if (pthread_rwlock_destroy(&lock->l) != 0) __builtin_trap(); +} +static inline void read_wrlock(wrlock_t *lock) { + if (pthread_rwlock_rdlock(&lock->l) != 0) __builtin_trap(); + assert(lock->val >= 0); + lock->val++; +} +static inline bool read_wrtrylock(wrlock_t *lock) { + int err = pthread_rwlock_tryrdlock(&lock->l); + if (err == EBUSY || err == EAGAIN) return false; + if (err != 0) __builtin_trap(); + assert(lock->val >= 0); + lock->val++; + return true; +} +static inline void read_wrunlock(wrlock_t *lock) { + assert(lock->val > 0); + lock->val--; + if (pthread_rwlock_unlock(&lock->l) != 0) __builtin_trap(); +} +static inline void __write_wrlock(wrlock_t *lock, const char *file, int line) { + // Acquire the write lock without letting a *waiting* writer freeze out + // readers (which macOS's writer-preferring pthread_rwlock does). We spin + // on trywrlock instead of a blocking wrlock: while we're merely retrying + // (not queued as a waiter), concurrent readers can still take the lock. + // + // This is load-bearing for the JIT: task_run_current holds mem->lock as a + // READER for the duration of each JIT quantum and re-acquires it every + // ~1024 blocks. Under a blocking writer-preferring wrlock, one thread + // requesting the write lock (mmap/munmap/CoW, e.g. JSC's GC sweep) freezes + // EVERY other JIT thread at its next read_wrlock — and if the writer is + // itself waiting on those threads to reach a GC safepoint, the whole VM + // deadlocks (observed intermittently in claude-cli startup). Spinning + // keeps readers live so they can progress and release, letting the writer + // eventually win a trylock. Back off from 1us to a steady 100us sleep; + // never fall back to blocking pthread_rwlock_wrlock(). + long pause_ns = 1000; + while (pthread_rwlock_trywrlock(&lock->l) != 0) { + const struct timespec pause = { .tv_sec = 0, .tv_nsec = pause_ns }; + nanosleep(&pause, NULL); + if (pause_ns < 100000) + pause_ns *= 2; + } + assert(lock->val == 0); + lock->val = -1; + lock->file = file; + lock->line = line; + lock->pid = current_pid(); +} +#define write_wrlock(lock) __write_wrlock(lock, __FILE__, __LINE__) +static inline bool write_wrtrylock(wrlock_t *lock) { + int err = pthread_rwlock_trywrlock(&lock->l); + if (err == EBUSY) return false; + if (err != 0) __builtin_trap(); + assert(lock->val == 0); + lock->val = -1; + return true; +} +static inline void write_wrunlock(wrlock_t *lock) { + assert(lock->val == -1); + lock->val = lock->line = lock->pid = 0; + lock->file = NULL; + if (pthread_rwlock_unlock(&lock->l) != 0) __builtin_trap(); +} + +extern __thread sigjmp_buf unwind_buf; +extern __thread bool should_unwind; +static inline int sigunwind_start(void) { + if (sigsetjmp(unwind_buf, 1)) { + should_unwind = false; + return 1; + } else { + should_unwind = true; + return 0; + } +} +static inline void sigunwind_end(void) { + should_unwind = false; +} + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/util/timer.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/timer.c new file mode 100644 index 0000000000..63b19a99a9 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/timer.c @@ -0,0 +1,82 @@ +#include <stdlib.h> +#include <signal.h> +#include <time.h> +#include "util/timer.h" +#include "misc.h" + +struct timer *timer_new(clockid_t clockid, timer_callback_t callback, void *data) { +// assert(clockid == CLOCK_MONOTONIC || clockid == CLOCK_REALTIME); + struct timer *timer = malloc(sizeof(struct timer)); + timer->clockid = clockid; + timer->callback = callback; + timer->data = data; + timer->active = false; + timer->thread_running = false; + lock_init(&timer->lock); + timer->dead = false; + return timer; +} + +void timer_free(struct timer *timer) { + lock(&timer->lock); + timer->active = false; + if (timer->thread_running) { + timer->dead = true; + pthread_kill(timer->thread, SIGUSR1); + unlock(&timer->lock); + } else { + unlock(&timer->lock); + free(timer); + } +} + +static void *timer_thread(void *param) { + struct timer *timer = param; + lock(&timer->lock); + while (true) { + struct timespec remaining = timespec_subtract(timer->end, timespec_now(timer->clockid)); + while (timer->active && timespec_positive(remaining)) { + unlock(&timer->lock); + nanosleep(&remaining, NULL); + lock(&timer->lock); + remaining = timespec_subtract(timer->end, timespec_now(timer->clockid)); + } + if (timer->active) + timer->callback(timer->data); + if (timer->active && timespec_positive(timer->interval)) { + timer->start = timer->end; + timer->end = timespec_add(timer->start, timer->interval); + } else { + break; + } + } + timer->thread_running = false; + if (timer->dead) + free(timer); + else + unlock(&timer->lock); + return NULL; +} + +int timer_set(struct timer *timer, struct timer_spec spec, struct timer_spec *oldspec) { + lock(&timer->lock); + struct timespec now = timespec_now(timer->clockid); + if (oldspec != NULL) { + oldspec->value = timespec_subtract(timer->end, now); + oldspec->interval = timer->interval; + } + + timer->start = now; + timer->end = timespec_add(timer->start, spec.value); + timer->interval = spec.interval; + timer->active = !timespec_is_zero(spec.value); + if (timer->thread_running) { + pthread_kill(timer->thread, SIGUSR1); + } else if (timer->active) { + timer->thread_running = true; + pthread_create(&timer->thread, NULL, timer_thread, timer); + pthread_detach(timer->thread); + } + unlock(&timer->lock); + return 0; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/util/timer.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/timer.h new file mode 100644 index 0000000000..f01189a04c --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/util/timer.h @@ -0,0 +1,81 @@ +#ifndef UTIL_TIMER_H +#define UTIL_TIMER_H + +#include <stdbool.h> +#include <time.h> +#include <pthread.h> +#include <assert.h> +#include "util/sync.h" + +static inline struct timespec timespec_now(clockid_t clockid) { + assert(clockid == CLOCK_MONOTONIC || clockid == CLOCK_REALTIME); + struct timespec now; + clock_gettime(clockid, &now); // can't fail, according to posix spec + return now; +} + +static inline struct timespec timespec_add(struct timespec x, struct timespec y) { + x.tv_sec += y.tv_sec; + x.tv_nsec += y.tv_nsec; + if (x.tv_nsec >= 1000000000) { + x.tv_nsec -= 1000000000; + x.tv_sec++; + } + return x; +} + +static inline struct timespec timespec_subtract(struct timespec x, struct timespec y) { + struct timespec result; + if (x.tv_nsec < y.tv_nsec) { + x.tv_sec -= 1; + x.tv_nsec += 1000000000; + } + result.tv_sec = x.tv_sec - y.tv_sec; + result.tv_nsec = x.tv_nsec - y.tv_nsec; + return result; +} + +static inline bool timespec_is_zero(struct timespec ts) { + return ts.tv_sec == 0 && ts.tv_nsec == 0; +} + +static inline bool timespec_positive(struct timespec ts) { + return ts.tv_sec > 0 || (ts.tv_sec == 0 && ts.tv_nsec > 0); +} + +static inline struct timespec timespec_normalize(struct timespec ts) { + ts.tv_sec += ts.tv_nsec / 1000000000; + ts.tv_nsec %= 1000000000; + return ts; +} + +typedef void (*timer_callback_t)(void *data); +struct timer { + clockid_t clockid; + struct timespec start; + struct timespec end; + struct timespec interval; + + bool active; + bool thread_running; + pthread_t thread; + timer_callback_t callback; + void *data; + lock_t lock; + + bool dead; // set by timer_free, the thread will free the timer if this is set when it finishes +}; + +struct timer *timer_new(clockid_t clockid, timer_callback_t callback, void *data); +void timer_free(struct timer *timer); +// value is how long to wait until the next fire +// interval is how long after that to wait until the next fire (if non-zero) +// bizarre interface is based off setitimer, because this is going to be used +// to implement setitimer +struct timer_spec { + struct timespec value; + struct timespec interval; +}; +int timer_set(struct timer *timer, struct timer_spec spec, struct timer_spec *oldspec); + +#endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/check-cc-arm64.sh b/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/check-cc-arm64.sh new file mode 100755 index 0000000000..4d80651de8 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/check-cc-arm64.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# Check if the provided compiler can target aarch64 + +CLANG="$1" + +if [ -z "$CLANG" ]; then + echo "Usage: $0 <clang-path>" + exit 1 +fi + +# Try to compile and link a simple aarch64 ELF shared object +TMPFILE=$(mktemp /tmp/check-cc-arm64.XXXXXX.c) +TMPOUT=$(mktemp /tmp/check-cc-arm64.XXXXXX.so) + +cat > "$TMPFILE" << 'EOF' +void _start(void) { + __asm__ volatile("svc #0"); +} +EOF + +"$CLANG" -target aarch64-linux-gnu -fuse-ld=lld -shared -nostdlib -x c "$TMPFILE" -o "$TMPOUT" 2>/dev/null +RESULT=$? + +rm -f "$TMPFILE" "$TMPOUT" + +if [ $RESULT -ne 0 ]; then + echo "Error: $CLANG cannot link aarch64-linux-gnu with lld" + exit 1 +fi + +echo "ARM64 cross-compiler/linker check passed" +exit 0 diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/meson.build b/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/meson.build new file mode 100644 index 0000000000..79a7ab8709 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/meson.build @@ -0,0 +1,47 @@ +# ARM64 VDSO Build Configuration +# +# The VDSO gets inserted into the address space of emulated processes, so it +# needs to be compiled as an aarch64 ELF shared library. This requires a cross +# compiler and linker. +# +# On macOS, you need an aarch64 cross-compiler toolchain. +# On Linux, you can use the native compiler if running on arm64, or a cross compiler. + +# Try to find an aarch64 compiler +clang = find_program('/usr/local/opt/llvm/bin/clang', '/opt/homebrew/opt/llvm/bin/clang', '/opt/local/bin/clang', 'clang', required: false) +has_vdso_compiler = false + +if clang.found() + # Check if the compiler supports aarch64 target + check_cc = find_program('./check-cc-arm64.sh', required: false) + if check_cc.found() + result = run_command(check_cc, clang, check: false) + if result.returncode() == 0 + has_vdso_compiler = true + else + message('ARM64 VDSO: Cross-compiler check failed') + message(result.stdout() + result.stderr()) + endif + endif +endif + +if has_vdso_compiler + vdso_compiler = [clang, '-target', 'aarch64-linux-gnu', '-fuse-ld=lld'] + + vdso = custom_target('vdso-arm64', + input: ['vdso.S', 'vdso.c', 'vdso.lds'], + output: 'libvdso.so.elf', + command: vdso_compiler + [ + '-o', '@OUTPUT@', '@INPUT0@', '@INPUT1@', + '-nostdlib', '-Wl,-T,@INPUT2@', '-Wl,--hash-style,sysv', + '-shared', '-fPIC', '-ffreestanding' + ] + get_option('vdso_c_args').split()) +else + # Create a dummy vdso target if no complete compiler/linker is available + # This allows building for ARM64 guest even without a vdso + message('ARM64 VDSO: No suitable cross-compiler/linker found, VDSO will not be built') + # Create an empty file as placeholder + vdso = custom_target('vdso-arm64-stub', + output: 'libvdso.so.elf', + command: ['touch', '@OUTPUT@']) +endif diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/vdso.S b/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/vdso.S new file mode 100644 index 0000000000..a0c75e3065 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/vdso.S @@ -0,0 +1,61 @@ +/* + * ARM64 VDSO assembly code + * + * This provides the low-level entry points for the VDSO functions. + * The actual implementations are in vdso.c, but we need assembly + * wrappers to ensure the correct ABI is used. + */ + + .text + +/* + * Signal return trampolines + * + * These are used by the kernel to return from signal handlers. + * The sigreturn call restores the process state that was saved + * when the signal was delivered. + */ + + .globl __kernel_rt_sigreturn + .type __kernel_rt_sigreturn, @function + .align 4 +__kernel_rt_sigreturn: + mov x8, #139 // __NR_rt_sigreturn + svc #0 + // Never returns + .size __kernel_rt_sigreturn, . - __kernel_rt_sigreturn + +/* + * Simple syscall wrappers + * These are fallback implementations if the C versions can't be used + */ + + .globl __vdso_clock_gettime_asm + .type __vdso_clock_gettime_asm, @function + .align 4 +__vdso_clock_gettime_asm: + // x0 = clockid, x1 = timespec* + mov x8, #113 // __NR_clock_gettime + svc #0 + ret + .size __vdso_clock_gettime_asm, . - __vdso_clock_gettime_asm + + .globl __vdso_gettimeofday_asm + .type __vdso_gettimeofday_asm, @function + .align 4 +__vdso_gettimeofday_asm: + // x0 = timeval*, x1 = timezone* + mov x8, #169 // __NR_gettimeofday + svc #0 + ret + .size __vdso_gettimeofday_asm, . - __vdso_gettimeofday_asm + + .globl __vdso_clock_getres_asm + .type __vdso_clock_getres_asm, @function + .align 4 +__vdso_clock_getres_asm: + // x0 = clockid, x1 = timespec* + mov x8, #114 // __NR_clock_getres + svc #0 + ret + .size __vdso_clock_getres_asm, . - __vdso_clock_getres_asm diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/vdso.c b/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/vdso.c new file mode 100644 index 0000000000..124f0201b2 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/vdso.c @@ -0,0 +1,104 @@ +/* + * ARM64 VDSO (Virtual Dynamic Shared Object) + * + * The VDSO is a small shared library that the kernel maps into the address + * space of all user processes. It provides fast implementations of certain + * system calls that don't require a full context switch. + * + * For ARM64 Linux, the VDSO provides: + * - __kernel_gettimeofday + * - __kernel_clock_gettime + * - __kernel_clock_getres + * - __kernel_rt_sigreturn + * + * In iSH, we implement these as simple wrappers that invoke the SVC #0 + * instruction to perform the actual system call. + */ + +#include <stddef.h> +#include <stdint.h> + +// ARM64 uses SVC #0 for system calls +// Syscall number goes in x8, arguments in x0-x5, return value in x0 + +// ARM64 Linux syscall numbers +#define __NR_clock_gettime 113 +#define __NR_clock_getres 114 +#define __NR_gettimeofday 169 +#define __NR_rt_sigreturn 139 + +// Clock IDs +#define CLOCK_REALTIME 0 +#define CLOCK_MONOTONIC 1 + +struct timespec { + long tv_sec; + long tv_nsec; +}; + +struct timeval { + long tv_sec; + long tv_usec; +}; + +struct timezone { + int tz_minuteswest; + int tz_dsttime; +}; + +// Inline syscall helper +static inline long syscall0(long n) { + register long x8 __asm__("x8") = n; + register long x0 __asm__("x0"); + __asm__ volatile("svc #0" : "=r"(x0) : "r"(x8) : "memory"); + return x0; +} + +static inline long syscall1(long n, long a0) { + register long x8 __asm__("x8") = n; + register long x0 __asm__("x0") = a0; + __asm__ volatile("svc #0" : "+r"(x0) : "r"(x8) : "memory"); + return x0; +} + +static inline long syscall2(long n, long a0, long a1) { + register long x8 __asm__("x8") = n; + register long x0 __asm__("x0") = a0; + register long x1 __asm__("x1") = a1; + __asm__ volatile("svc #0" : "+r"(x0) : "r"(x1), "r"(x8) : "memory"); + return x0; +} + +// VDSO function implementations +int __vdso_clock_gettime(int clk, struct timespec *ts) { + return syscall2(__NR_clock_gettime, clk, (long)ts); +} + +int __vdso_gettimeofday(struct timeval *tv, struct timezone *tz) { + return syscall2(__NR_gettimeofday, (long)tv, (long)tz); +} + +int __vdso_clock_getres(int clk, struct timespec *res) { + return syscall2(__NR_clock_getres, clk, (long)res); +} + +void __vdso_rt_sigreturn(void) { + syscall0(__NR_rt_sigreturn); + __builtin_unreachable(); +} + +// Version symbol (required by glibc) +const char vdso_version[] __attribute__((section(".data"))) = "LINUX_2.6.39"; + +// Weak aliases for the kernel entry points +__attribute__((weak, alias("__vdso_clock_gettime"))) +int __kernel_clock_gettime(int clk, struct timespec *ts); + +__attribute__((weak, alias("__vdso_gettimeofday"))) +int __kernel_gettimeofday(struct timeval *tv, struct timezone *tz); + +__attribute__((weak, alias("__vdso_clock_getres"))) +int __kernel_clock_getres(int clk, struct timespec *res); + +__attribute__((weak, alias("__vdso_rt_sigreturn"))) +void __kernel_rt_sigreturn(void); diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/vdso.lds b/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/vdso.lds new file mode 100644 index 0000000000..50ff7646eb --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/vdso/arm64/vdso.lds @@ -0,0 +1,74 @@ +/* + * ARM64 VDSO Linker Script + * + * This script controls the layout of the VDSO shared library. + * The VDSO is mapped into the guest process's address space + * and provides fast paths for certain system calls. + */ + +SECTIONS +{ + . = SIZEOF_HEADERS; + + .hash : { *(.hash) } :text + .gnu.hash : { *(.gnu.hash) } + .dynsym : { *(.dynsym) } + .dynstr : { *(.dynstr) } + .gnu.version : { *(.gnu.version) } + .gnu.version_d : { *(.gnu.version_d) } + .gnu.version_r : { *(.gnu.version_r) } + + .dynamic : { *(.dynamic) } :text :dynamic + + .rodata : { *(.rodata*) } :text + + .note : { *(.note*) } :text :note + + .eh_frame_hdr : { *(.eh_frame_hdr) } :text :eh_frame_hdr + .eh_frame : { KEEP(*(.eh_frame)) } :text + + .text : { + *(.text*) + } :text =0xd503201f + + .data : { + *(.data*) + *(.sdata*) + *(.got.plt) + *(.got) + *(.bss*) + } :text + + /DISCARD/ : { + *(.note.GNU-stack) + *(.interp) + } +} + +/* + * Program headers + */ +PHDRS +{ + /* Include ELF/PHDR in the load segment so p_vaddr starts at 0 */ + text PT_LOAD FLAGS(5) FILEHDR PHDRS; /* PF_R|PF_X */ + dynamic PT_DYNAMIC FLAGS(4); /* PF_R */ + note PT_NOTE FLAGS(4); /* PF_R */ + eh_frame_hdr PT_GNU_EH_FRAME; +} + +/* + * Version script - defines the symbols exported by the VDSO + */ +VERSION +{ + LINUX_2.6.39 { + global: + __kernel_rt_sigreturn; + __kernel_clock_gettime; + __kernel_clock_getres; + __kernel_gettimeofday; + local: + *; + }; +} diff --git a/platforms/ios/Alpine/Vendor/ios-linuxkit/xX_main_Xx.h b/platforms/ios/Alpine/Vendor/ios-linuxkit/xX_main_Xx.h new file mode 100644 index 0000000000..968225bb92 --- /dev/null +++ b/platforms/ios/Alpine/Vendor/ios-linuxkit/xX_main_Xx.h @@ -0,0 +1,266 @@ +#include <string.h> +#include <unistd.h> +#include <signal.h> +#include <errno.h> +#include <syslog.h> +#include <sys/stat.h> +#include "kernel/init.h" +#include "kernel/fs.h" +#include "fs/devices.h" +#include "fs/dev.h" +#include "fs/path.h" +#include "fs/real.h" +#include "kernel/native_offload.h" +#ifdef __APPLE__ +#include <sys/resource.h> +#define IOPOL_TYPE_VFS_HFS_CASE_SENSITIVITY 1 +#define IOPOL_VFS_HFS_CASE_SENSITIVITY_FORCE_CASE_SENSITIVE 1 +#endif + +void real_tty_reset_term(void); + +static inline int append_exec_arg(char *buf, size_t cap, size_t *pos, const char *arg) { + size_t len = strlen(arg) + 1; + if (*pos > cap || len > cap - *pos) + return _E2BIG; + memcpy(buf + *pos, arg, len); + *pos += len; + return 0; +} + +static void exit_handler(struct task *task, int code) { + if (task->parent != NULL) + return; + real_tty_reset_term(); + if (code & 0xff) { + // Guest died from a signal. Don't raise on the host (our crash_handler + // would intercept it). Just exit with the conventional 128+signal code. + _exit(128 + (code & 0xff)); + } + exit(code >> 8); +} + +// this function parses command line arguments and initializes global +// data structures. thanks programming discussions discord server for the name. +// https://discord.gg/9zT7NHP +static inline int xX_main_Xx(int argc, char *const argv[], const char *envp) { +#ifdef __APPLE__ + // Enable case-sensitive filesystem mode on macOS, if possible. + // In order for this to succeed, either we need to be running as root, or + // be given the com.apple.private.iopol.case_sensitivity entitlement. The + // second option isn't possible so you'll need to give iSH the setuid root + // bit. In that case it's important to drop root permissions ASAP. + // https://worthdoingbadly.com/casesensitive-iossim/ + int iopol_err = setiopolicy_np(IOPOL_TYPE_VFS_HFS_CASE_SENSITIVITY, + IOPOL_SCOPE_PROCESS, + IOPOL_VFS_HFS_CASE_SENSITIVITY_FORCE_CASE_SENSITIVE); + if (iopol_err != 0 && errno != EPERM) + perror("could not enable case sensitivity"); + setgid(getgid()); + setuid(getuid()); +#endif + + // parse cli options + int opt; + const char *root = NULL; + const char *workdir = NULL; + const struct fs_ops *fs = &realfs; + const char *console = "/dev/tty1"; + while ((opt = getopt(argc, argv, "+r:f:d:c:n:")) != -1) { + switch (opt) { + case 'r': + case 'f': + root = optarg; + if (opt == 'f') + fs = &fakefs; + break; + case 'd': + workdir = optarg; + break; + case 'c': + console = optarg; + break; + case 'n': + if (native_offload_add(optarg) < 0) + fprintf(stderr, "warning: ignoring -n %s\n", optarg); + break; + } + } + + openlog(argv[0], 0, LOG_USER); + + char root_realpath[MAX_PATH + 1] = "/"; + if (root != NULL && realpath(root, root_realpath) == NULL) { + perror(root); + exit(1); + } + if (fs == &fakefs) { + if (strlen(root_realpath) + strlen("/data") >= sizeof(root_realpath)) + return _ENAMETOOLONG; + strcat(root_realpath, "/data"); + } + int err = mount_root(fs, root_realpath); + if (err < 0) + return err; + + become_first_process(); + current->thread = pthread_self(); + + // Create essential device nodes (only works with fakefs) + if (fs != &realfs) { + generic_mknodat(AT_PWD, "/dev/null", S_IFCHR|0666, dev_make(MEM_MAJOR, DEV_NULL_MINOR)); + generic_mknodat(AT_PWD, "/dev/zero", S_IFCHR|0666, dev_make(MEM_MAJOR, DEV_ZERO_MINOR)); + generic_mknodat(AT_PWD, "/dev/full", S_IFCHR|0666, dev_make(MEM_MAJOR, DEV_FULL_MINOR)); + generic_mknodat(AT_PWD, "/dev/random", S_IFCHR|0666, dev_make(MEM_MAJOR, DEV_RANDOM_MINOR)); + generic_mknodat(AT_PWD, "/dev/urandom", S_IFCHR|0666, dev_make(MEM_MAJOR, DEV_URANDOM_MINOR)); + generic_mknodat(AT_PWD, "/dev/tty", S_IFCHR|0666, dev_make(TTY_ALTERNATE_MAJOR, DEV_TTY_MINOR)); + generic_mknodat(AT_PWD, "/dev/console", S_IFCHR|0666, dev_make(TTY_ALTERNATE_MAJOR, DEV_CONSOLE_MINOR)); + generic_mknodat(AT_PWD, "/dev/ptmx", S_IFCHR|0666, dev_make(TTY_ALTERNATE_MAJOR, DEV_PTMX_MINOR)); + } + + char cwd[MAX_PATH + 1]; + if (root == NULL && workdir == NULL) { + getcwd(cwd, sizeof(cwd)); + workdir = cwd; + } + if (workdir != NULL) { + struct fd *pwd = generic_open(workdir, O_RDONLY_, 0); + if (IS_ERR(pwd)) { + fprintf(stderr, "error opening working dir: %ld\n", PTR_ERR(pwd)); + return 1; + } + fs_chdir(current->fs, pwd); + } + + char argv_copy[4096]; + int i = optind; + size_t p = 0; + size_t exec_argc = 0; + if (argv[optind] == NULL) + return _ENOENT; +#ifdef GUEST_ARM64 + // Inject V8 flags for node to work around scope corruption in emulation. + // --jitless: disable JIT (avoids V8 code gen incompatible with our JIT) + // --predictable: disable concurrent GC/compilation (avoids race conditions) + // --no-lazy: eager compilation (avoids Zone reuse patterns that corrupt scopes) + // --single-generation: skip young gen (reduces GC-triggered Zone resets) + // This is needed here because the initial do_execve bypasses sys_execve. + { + const char *base = strrchr(argv[optind], '/'); + base = base ? base + 1 : argv[optind]; + if (strcmp(base, "node") == 0) { + // Copy argv[0] first + if ((err = append_exec_arg(argv_copy, sizeof(argv_copy) - 1, &p, argv[optind])) < 0) + return err; + exec_argc++; + // Inject V8 flags to work around scope corruption + static const char *v8_flags[] = { + "--jitless", + "--no-lazy", + "--no-expose-wasm", + "--max-old-space-size=512", + }; + for (int fi = 0; fi < (int)(sizeof(v8_flags)/sizeof(v8_flags[0])); fi++) { + if ((err = append_exec_arg(argv_copy, sizeof(argv_copy) - 1, &p, v8_flags[fi])) < 0) + return err; + exec_argc++; + } + // Copy remaining args (skip argv[optind]) + for (i = optind + 1; i < argc; i++) { + if ((err = append_exec_arg(argv_copy, sizeof(argv_copy) - 1, &p, argv[i])) < 0) + return err; + exec_argc++; + } + argv_copy[p] = '\0'; + goto do_exec; + } + } +#endif + while (i < argc) { + if ((err = append_exec_arg(argv_copy, sizeof(argv_copy) - 1, &p, argv[i])) < 0) + return err; + exec_argc++; + i++; + } + argv_copy[p] = '\0'; +#ifdef GUEST_ARM64 +do_exec: + // Inject environment variables for the initial exec. + // sys_execve has its own injection, but the initial do_execve bypasses it. + { + static char envp_buf[4096]; + size_t ep = 0; + if (envp != NULL) { + const char *e = envp; + while (*e) { + size_t len = strlen(e) + 1; + if (ep + len < sizeof(envp_buf) - 256) { + memcpy(&envp_buf[ep], e, len); + ep += len; + } + e += len; + } + } + // Inject env vars that sys_execve would normally add. + // These are injected only if not already present. + static const char *inject_vars[] = { + "GODEBUG=asyncpreemptoff=1", // Disable Go async preemption + "GOMAXPROCS=2", // Limit Go thread count + "NO_COLOR=1", // Disable color output + "PYTHONMALLOC=malloc", // Bypass pymalloc arenas + "PYTHONDONTWRITEBYTECODE=1", // Skip .pyc generation + }; + for (size_t vi = 0; vi < sizeof(inject_vars)/sizeof(inject_vars[0]); vi++) { + // Check if already present (search by prefix up to '=') + const char *eq = strchr(inject_vars[vi], '='); + size_t prefix_len = eq ? (size_t)(eq - inject_vars[vi] + 1) : strlen(inject_vars[vi]); + int found = 0; + const char *scan = envp_buf; + const char *scan_end = envp_buf + ep; + while (scan < scan_end && *scan) { + if (strncmp(scan, inject_vars[vi], prefix_len) == 0) { + found = 1; + break; + } + scan += strlen(scan) + 1; + } + if (!found) { + size_t vlen = strlen(inject_vars[vi]) + 1; + if (ep + vlen < sizeof(envp_buf) - 64) { + memcpy(&envp_buf[ep], inject_vars[vi], vlen); + ep += vlen; + } + } + } + // Node-specific: LD_PRELOAD for zero_free.so + const char *base2 = strrchr(argv[optind], '/'); + base2 = base2 ? base2 + 1 : argv[optind]; + if (strcmp(base2, "node") == 0) { + static const char *ld_preload = "LD_PRELOAD=/lib/zero_free.so"; + size_t plen = strlen(ld_preload) + 1; + if (ep + plen < sizeof(envp_buf) - 2) { + memcpy(&envp_buf[ep], ld_preload, plen); + ep += plen; + } + } + envp_buf[ep] = '\0'; + err = do_execve(argv[optind], exec_argc, argv_copy, envp_buf); + } +#else + err = do_execve(argv[optind], exec_argc, argv_copy, envp == NULL ? "\0" : envp); +#endif + if (err < 0) + return err; + tty_drivers[TTY_CONSOLE_MAJOR] = &real_tty_driver; + if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) { + err = create_stdio(console, TTY_CONSOLE_MAJOR, 1); + if (err < 0) + return err; + } else { + err = create_piped_stdio(); + if (err < 0) + return err; + } + exit_hook = exit_handler; + return 0; +} diff --git a/platforms/ios/Alpine/build.sh b/platforms/ios/Alpine/build.sh new file mode 100755 index 0000000000..8183e0d41a --- /dev/null +++ b/platforms/ios/Alpine/build.sh @@ -0,0 +1,72 @@ +#!/bin/bash +set -euo pipefail + +alpine_dir=$(cd "$(dirname "$0")" && pwd) +printf '%s %s\n' '2f2f07e388fd5701eec4d008e67f2a9a2c05564dbd09a3fea96c9dc1cee42765' "$alpine_dir/Assets/axs" | shasum -a 256 -c - +export PATH="${ACODE_BUILD_TOOLS:-/opt/homebrew/bin}:/usr/local/bin:$PATH" +export PATH="${ACODE_LLD_BIN:-/opt/homebrew/opt/lld/bin}:$PATH" +for tool in meson ninja ld.lld; do + command -v "$tool" >/dev/null || { echo "error: Install Alpine build tools: brew install meson ninja llvm lld"; exit 1; } +done + +sdk=${SDKROOT:-$(xcrun --sdk iphonesimulator --show-sdk-path)} +platform=${PLATFORM_NAME:-iphonesimulator} +build_dir=${DERIVED_FILE_DIR:-"$alpine_dir/../../../.ios-build/alpine"}/Alpine-$platform +mkdir -p "$build_dir" +target="arm64-apple-ios${IPHONEOS_DEPLOYMENT_TARGET:-18.6}" +if [[ "$platform" == iphonesimulator ]]; then target="$target-simulator"; fi +if [[ "${ARCHS:-arm64}" != arm64 ]]; then + echo "error: The Alpine runtime requires an ARM64 device or Apple Silicon simulator." + exit 1 +fi + +crossfile="$build_dir.cross.ini" +cat > "$crossfile.tmp" <<EOF +[binaries] +c = '/usr/bin/clang' +ar = '/usr/bin/ar' +[host_machine] +system = 'darwin' +cpu_family = 'aarch64' +cpu = 'arm64' +endian = 'little' +[built-in options] +c_args = ['-target', '$target', '-isysroot', '$sdk', '-D_XOPEN_SOURCE=700', '-D_DARWIN_C_SOURCE'] +c_link_args = ['-target', '$target', '-isysroot', '$sdk'] +[properties] +needs_exe_wrapper = true +sdk_path = '$sdk' +EOF +# Preserve timestamps so an unchanged Xcode build remains incremental. +if ! cmp -s "$crossfile.tmp" "$crossfile"; then mv "$crossfile.tmp" "$crossfile"; else rm "$crossfile.tmp"; fi +export CC_FOR_BUILD=/usr/bin/clang +# Meson caches compiler flags separately; rewriting the cross file is not enough +# after an SDK or deployment-target change. Keep it outside the directory wiped. +if [[ ! -f "$build_dir/build.ninja" ]] || ! cmp -s "$crossfile" "$build_dir/configured-cross.ini"; then + setup_options=(setup) + if [[ -d "$build_dir/meson-private" ]]; then setup_options+=(--wipe); fi + meson "${setup_options[@]}" "$build_dir" "$alpine_dir/Vendor/ios-linuxkit" --cross-file "$crossfile" -Dbuildtype=release + cp "$crossfile" "$build_dir/configured-cross.ini" +fi +ninja -C "$build_dir" libish.a libish_emu.a libfakefs.a libacode_alpine.a libacode_archive.a +test -s "$build_dir/vdso/arm64/libvdso.so.elf" || { echo "error: ARM64 Linux VDSO was not built. Install llvm and lld."; exit 1; } +archives=("$build_dir/libacode_alpine.a" "$build_dir/libish.a" "$build_dir/libish_emu.a" "$build_dir/libfakefs.a" "$build_dir/libacode_archive.a") +for archive in "${archives[@]}"; do + if [[ "$archive" -nt "$build_dir/libAcodeAlpine.a" ]]; then + /usr/bin/libtool -static -o "$build_dir/libAcodeAlpine.a" "${archives[@]}" + break + fi +done + +if [[ -n "${TARGET_BUILD_DIR:-}" ]]; then + resources="$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/Alpine" + mkdir -p "$resources" + cp "$alpine_dir/../../android/app/src/store/assets/alpine_assets/arm64/alpine.rootfs" "$resources/alpine.rootfs" + cp "$alpine_dir/../../android/app/src/main/assets/init-alpine.sh" "$resources/init-alpine.sh" + cp "$alpine_dir/Assets/axs" "$resources/axs" + cp "$alpine_dir/Vendor/ios-linuxkit/LICENSE.md" "$resources/ios-linuxkit-LICENSE.md" + cp "$alpine_dir/Vendor/ios-linuxkit/LICENSE.IOS" "$resources/LICENSE.IOS" + cp "$alpine_dir/GPL-3.0.txt" "$resources/GPL-3.0.txt" + cp "$alpine_dir/Vendor/ios-linuxkit/deps/libarchive/COPYING" "$resources/libarchive-COPYING" + cp "$alpine_dir/README.md" "$resources/README.md" +fi diff --git a/platforms/ios/Alpine/include/AcodeAlpine.h b/platforms/ios/Alpine/include/AcodeAlpine.h new file mode 100644 index 0000000000..e6ff6a4124 --- /dev/null +++ b/platforms/ios/Alpine/include/AcodeAlpine.h @@ -0,0 +1,42 @@ +#pragma once +#include <stdbool.h> +#include <stddef.h> + +typedef void (*AlpineExitCallback)(int pid, int status); +typedef struct AlpineTerminal AlpineTerminal; +// `output` and `congested` run on guest threads. `congested` tells blocking writers +// to wait until alpine_terminal_drained; `release` runs once the terminal is gone. +typedef struct { + void (*output)(void *context, const char *data, size_t length); + bool (*congested)(void *context); + void (*release)(void *context); +} AlpineTerminalCallbacks; + +// Calls that access guest state are serialized by AlpineRuntime.queue. +int alpine_boot(const char *root, AlpineExitCallback callback); +int alpine_bind(const char *guest, const char *host, bool readOnly); +int alpine_chmod(const char *path, unsigned int mode); +int alpine_start(const char *command, const char *environment, int input, int output, int error); +int alpine_kill(int pid); +bool alpine_running(int pid); +void alpine_reap(void); +void alpine_stop_all(void); +bool alpine_idle(void); +int alpine_unmount(void); +bool alpine_import(const char *archive, const char *root, char *error, size_t capacity); +void alpine_install_fault_handlers(void); +// Recreate guest listening sockets that iOS reclaims while the app is suspended. +void alpine_suspend(void); +void alpine_resume(void); + +// Runs a command on a new pseudo-terminal and returns its pid. The context is +// owned by the terminal from this call on, including when starting fails. +int alpine_terminal_start(const char *command, const char *environment, int rows, int cols, + void *context, AlpineTerminalCallbacks callbacks, AlpineTerminal **terminal); +// Input, resize, drained and close are thread-safe and do not need AlpineRuntime.queue. +long alpine_terminal_input(AlpineTerminal *terminal, const char *data, size_t length); +void alpine_terminal_resize(AlpineTerminal *terminal, int rows, int cols); +void alpine_terminal_drained(AlpineTerminal *terminal); +// Releases waiting writers, hangs up the session and drops the host's reference; +// the handle is invalid afterwards. +void alpine_terminal_close(AlpineTerminal *terminal); diff --git a/platforms/ios/Alpine/include/module.modulemap b/platforms/ios/Alpine/include/module.modulemap new file mode 100644 index 0000000000..eefc3777aa --- /dev/null +++ b/platforms/ios/Alpine/include/module.modulemap @@ -0,0 +1,4 @@ +module AcodeAlpine { + header "AcodeAlpine.h" + export * +} diff --git a/platforms/ios/Alpine/lldbinit b/platforms/ios/Alpine/lldbinit new file mode 100644 index 0000000000..77152c7d27 --- /dev/null +++ b/platforms/ios/Alpine/lldbinit @@ -0,0 +1,2 @@ +# Alpine uses SIGUSR1 to wake guest threads; pausing here freezes the entire app. +process handle -p true -s false -n false SIGUSR1 diff --git a/platforms/ios/Config.xcconfig.example b/platforms/ios/Config.xcconfig.example new file mode 100644 index 0000000000..08f573e937 --- /dev/null +++ b/platforms/ios/Config.xcconfig.example @@ -0,0 +1 @@ +DEVELOPMENT_TEAM = diff --git a/platforms/ios/Packages/CCurl/Bridge/AcodeCurl.c b/platforms/ios/Packages/CCurl/Bridge/AcodeCurl.c new file mode 100644 index 0000000000..fae93c350b --- /dev/null +++ b/platforms/ios/Packages/CCurl/Bridge/AcodeCurl.c @@ -0,0 +1,43 @@ +#include "AcodeCurl.h" + +CURLcode acode_curl_long(CURL *handle, CURLoption option, long value) { + return curl_easy_setopt(handle, option, value); +} +CURLcode acode_curl_string(CURL *handle, CURLoption option, const char *value) { + return curl_easy_setopt(handle, option, value); +} +CURLcode acode_curl_pointer(CURL *handle, CURLoption option, void *value) { + return curl_easy_setopt(handle, option, value); +} +CURLcode acode_curl_write(CURL *handle, CURLoption option, curl_write_callback callback) { + return curl_easy_setopt(handle, option, callback); +} +CURLcode acode_curl_read(CURL *handle, curl_read_callback callback) { + return curl_easy_setopt(handle, CURLOPT_READFUNCTION, callback); +} +CURLcode acode_curl_progress(CURL *handle, curl_xferinfo_callback callback) { + return curl_easy_setopt(handle, CURLOPT_XFERINFOFUNCTION, callback); +} +CURLcode acode_curl_offset(CURL *handle, CURLoption option, curl_off_t value) { + return curl_easy_setopt(handle, option, value); +} +long acode_curl_response(CURL *handle) { + long code = 0; + curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &code); + return code; +} +const char *acode_curl_directory(CURL *handle) { + char *directory = NULL; + curl_easy_getinfo(handle, CURLINFO_FTP_ENTRY_PATH, &directory); + return directory; +} +CURLcode acode_curl_debug(CURL *handle, curl_debug_callback callback) { + return curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, callback); +} +CURLcode acode_curl_chunk(CURL *handle, curl_chunk_bgn_callback callback) { + return curl_easy_setopt(handle, CURLOPT_CHUNK_BGN_FUNCTION, callback); +} +CURLcode acode_curl_ca(CURL *handle, const void *data, size_t length) { + struct curl_blob blob = {(void *)data, length, CURL_BLOB_COPY}; + return curl_easy_setopt(handle, CURLOPT_CAINFO_BLOB, &blob); +} diff --git a/platforms/ios/Packages/CCurl/Bridge/include/AcodeCurl.h b/platforms/ios/Packages/CCurl/Bridge/include/AcodeCurl.h new file mode 100644 index 0000000000..92aa224790 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Bridge/include/AcodeCurl.h @@ -0,0 +1,14 @@ +#include <curl/curl.h> + +CURLcode acode_curl_long(CURL *handle, CURLoption option, long value); +CURLcode acode_curl_string(CURL *handle, CURLoption option, const char *value); +CURLcode acode_curl_pointer(CURL *handle, CURLoption option, void *value); +CURLcode acode_curl_write(CURL *handle, CURLoption option, curl_write_callback callback); +CURLcode acode_curl_read(CURL *handle, curl_read_callback callback); +CURLcode acode_curl_progress(CURL *handle, curl_xferinfo_callback callback); +CURLcode acode_curl_offset(CURL *handle, CURLoption option, curl_off_t value); +long acode_curl_response(CURL *handle); +const char *acode_curl_directory(CURL *handle); +CURLcode acode_curl_debug(CURL *handle, curl_debug_callback callback); +CURLcode acode_curl_chunk(CURL *handle, curl_chunk_bgn_callback callback); +CURLcode acode_curl_ca(CURL *handle, const void *data, size_t length); diff --git a/platforms/ios/Packages/CCurl/COPYING b/platforms/ios/Packages/CCurl/COPYING new file mode 100644 index 0000000000..2f71d999a9 --- /dev/null +++ b/platforms/ios/Packages/CCurl/COPYING @@ -0,0 +1,22 @@ +COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 1996 - 2026, Daniel Stenberg, <daniel@haxx.se>, and many +contributors, see the THANKS file. + +All rights reserved. + +Permission to use, copy, modify, and distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright +notice and this permission notice appear in all copies. + +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 OF THIRD PARTY RIGHTS. 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. + +Except as contained in this notice, the name of a copyright holder shall not +be used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization of the copyright holder. diff --git a/platforms/ios/Packages/CCurl/Package.swift b/platforms/ios/Packages/CCurl/Package.swift new file mode 100644 index 0000000000..1a909e80bc --- /dev/null +++ b/platforms/ios/Packages/CCurl/Package.swift @@ -0,0 +1,16 @@ +// swift-tools-version:6.0 +import PackageDescription + +let package = Package( + name: "AcodeCurl", + platforms: [.iOS(.v18)], + products: [.library(name: "AcodeCurl", targets: ["AcodeCurl"])], + dependencies: [.package(url: "https://github.com/Lakr233/openssl-spm.git", exact: "3.6.2")], + targets: [ + .target(name: "CCurl", dependencies: [.product(name: "OpenSSL", package: "openssl-spm")], + path: "Vendor/curl", sources: ["lib"], publicHeadersPath: "include", + cSettings: [.headerSearchPath("lib"), .define("HAVE_CONFIG_H"), .define("CURL_STATICLIB"), .define("BUILDING_LIBCURL"), .define("USE_APPLE_SECTRUST")], + linkerSettings: [.linkedFramework("Security"), .linkedFramework("CoreFoundation")]), + .target(name: "AcodeCurl", dependencies: ["CCurl"], path: "Bridge", publicHeadersPath: "include"), + ] +) diff --git a/platforms/ios/Packages/CCurl/README.md b/platforms/ios/Packages/CCurl/README.md new file mode 100644 index 0000000000..5f7592a5b6 --- /dev/null +++ b/platforms/ios/Packages/CCurl/README.md @@ -0,0 +1,55 @@ +# Acode's iOS curl package + +This local Swift package builds upstream curl's FTP/FTPS implementation. It shares +the exact OpenSSL 3.6.2 package used by libssh2; it does not bundle a second crypto +library. `Bridge/` only wraps C varargs and callback setters for Swift. + +Source: <https://curl.se/download/curl-8.22.0.tar.xz> + +SHA-256: `f7ef3ae8a22e521f289803fe93543eb64c329b58aa73a9e224dfd915a2a5f4f7` + +`Vendor/curl/lib` and `Vendor/curl/include/curl` contain the release's `.c` and `.h` +files, retaining their upstream relative paths and contents. The sole added file +is `lib/curl_config.h`, containing the defined configuration macros for the +64-bit Apple ABI. `COPYING` is the upstream license, also copied into the app's +`FTP-Licenses.txt` resource. Upstream sources are intentionally kept together; +unselected protocols compile out through curl's feature guards. + +## Configuration and updates + +Use an extracted, checksum-verified release and an out-of-tree configure directory. +Point `--with-openssl` at a temporary prefix whose `include/` and `lib/` expose the +headers and libraries from the pinned OpenSSL simulator artifact. Configure with +the iOS simulator clang target (minimum deployment target 18.6): + +```sh +CC='xcrun --sdk iphonesimulator clang' \ +CFLAGS='-target arm64-apple-ios18.6-simulator' \ +LDFLAGS='-target arm64-apple-ios18.6-simulator -framework Security -framework CoreFoundation' \ +<curl-source>/configure \ + --host=aarch64-apple-darwin --build=aarch64-acode-darwin \ + --with-openssl=<temporary-openssl-prefix> --with-apple-sectrust \ + --enable-threaded-resolver --enable-ipv6 --enable-ftp \ + --disable-shared --enable-static \ + --without-libpsl --without-libidn2 --without-zlib --without-brotli --without-zstd \ + --without-nghttp2 --without-nghttp3 --without-libssh2 --without-ca-bundle --without-ca-path \ + --disable-http --disable-file --disable-ipfs --disable-ldap --disable-ldaps \ + --disable-rtsp --disable-proxy --disable-dict --disable-telnet --disable-tftp \ + --disable-pop3 --disable-imap --disable-smb --disable-smtp --disable-gopher \ + --disable-mqtt --disable-ntlm --disable-cookies --disable-manual --disable-libcurl-option +``` + +The package explicitly defines `USE_APPLE_SECTRUST`, equivalent to configure's +`--with-apple-sectrust` option. Keep defined macros from the generated +`lib/curl_config.h`, checking any conditional sections before compacting it. +SwiftPM supplies architecture and deployment flags for each actual build. + +FTPS retains peer and hostname verification and uses Apple's trust store through +`CURLSSLOPT_NATIVE_CA`. Explicit TLS protects both control and data channels; +port 990 selects implicit TLS. The native test adapter can supply a disposable CA +blob without installing roots or changing the public JavaScript API. + +When updating, verify the archive hash, replace upstream source/header files, +regenerate configuration, update the license resource, and run the FTP/FTPS +simulator fixtures plus a device build. Tests cover active/passive binary +transfers, directory operations, command replies, TLS rejection and cancellation. diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/curl.h b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/curl.h new file mode 100644 index 0000000000..b904e49530 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/curl.h @@ -0,0 +1,3373 @@ +#ifndef CURLINC_CURL_H +#define CURLINC_CURL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * If you have libcurl problems, all docs and details are found here: + * https://curl.se/libcurl/ + */ + +#ifdef CURL_NO_OLDIES +#define CURL_STRICTER /* not used since 8.11.0 */ +#endif + +/* Compile-time deprecation macros. */ +#if (defined(__GNUC__) && \ + ((__GNUC__ > 12) || ((__GNUC__ == 12) && (__GNUC_MINOR__ >= 1))) || \ + (defined(__clang__) && __clang_major__ >= 3) || \ + defined(__IAR_SYSTEMS_ICC__)) && \ + !defined(__INTEL_COMPILER) && \ + !defined(CURL_DISABLE_DEPRECATION) && !defined(BUILDING_LIBCURL) +#define CURL_DEPRECATED(version, message) \ + __attribute__((deprecated("since " # version ". " message))) +#ifdef __IAR_SYSTEMS_ICC__ +#define CURL_IGNORE_DEPRECATION(statements) \ + _Pragma("diag_suppress=Pe1444") \ + statements \ + _Pragma("diag_default=Pe1444") +#else +#define CURL_IGNORE_DEPRECATION(statements) \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") \ + statements \ + _Pragma("GCC diagnostic pop") +#endif +#else +#define CURL_DEPRECATED(version, message) +#define CURL_IGNORE_DEPRECATION(statements) statements +#endif + +#include "curlver.h" /* libcurl version defines */ +#include "system.h" /* determine things runtime */ + +#include <stdio.h> +#include <limits.h> + +#if defined(__FreeBSD__) || defined(__MidnightBSD__) +/* Needed for __FreeBSD_version or __MidnightBSD_version symbol definition */ +#include <sys/param.h> +#endif + +/* The include stuff here below is mainly for time_t! */ +#include <sys/types.h> +#include <time.h> + +#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__CYGWIN__) +#if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H) || \ + defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H)) +/* The check above prevents the winsock2.h inclusion if winsock.h already was + included, since they cannot co-exist without problems */ +#include <winsock2.h> +#include <ws2tcpip.h> +#endif +#endif + +/* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish + libc5-based Linux systems. Only include it on systems that are known to + require it! */ +#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \ + defined(__minix) || defined(__INTEGRITY) || \ + defined(ANDROID) || defined(__ANDROID__) || defined(__OpenBSD__) || \ + defined(__CYGWIN__) || defined(AMIGA) || defined(__NuttX__) || \ + (defined(__FreeBSD_version) && (__FreeBSD_version < 800000)) || \ + (defined(__MidnightBSD_version) && (__MidnightBSD_version < 100000)) || \ + defined(__sun__) || defined(__serenity__) || defined(__vxworks__) || \ + (defined(__linux__) && defined(_POSIX_C_SOURCE) && \ + _POSIX_C_SOURCE >= 200112L) +#include <sys/select.h> +#endif + +#ifndef _WIN32 +#include <sys/socket.h> +#include <sys/time.h> +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void CURL; +typedef void CURLSH; + +/* + * libcurl external API function linkage decorations. + */ + +#ifdef __has_declspec_attribute +#define CURL_HAS_DECLSPEC_ATTRIBUTE(x) __has_declspec_attribute(x) +#else +#define CURL_HAS_DECLSPEC_ATTRIBUTE(x) 0 +#endif + +#ifdef CURL_STATICLIB +# define CURL_EXTERN +#elif defined(_WIN32) || \ + (CURL_HAS_DECLSPEC_ATTRIBUTE(dllexport) && \ + CURL_HAS_DECLSPEC_ATTRIBUTE(dllimport)) +# ifdef BUILDING_LIBCURL +# define CURL_EXTERN __declspec(dllexport) +# else +# define CURL_EXTERN __declspec(dllimport) +# endif +#elif defined(BUILDING_LIBCURL) && defined(CURL_HIDDEN_SYMBOLS) +# define CURL_EXTERN CURL_EXTERN_SYMBOL +#else +# define CURL_EXTERN +#endif + +#ifndef curl_socket_typedef +/* socket typedef */ +#if defined(_WIN32) && !defined(__LWIP_OPT_H__) && !defined(LWIP_HDR_OPT_H) +typedef SOCKET curl_socket_t; +#define CURL_SOCKET_BAD INVALID_SOCKET +#else +typedef int curl_socket_t; +#define CURL_SOCKET_BAD (-1) +#endif +#define curl_socket_typedef +#endif /* curl_socket_typedef */ + +/* enum for the different supported SSL backends */ +typedef enum { + CURLSSLBACKEND_NONE = 0, + CURLSSLBACKEND_OPENSSL = 1, + CURLSSLBACKEND_GNUTLS = 2, + CURLSSLBACKEND_NSS CURL_DEPRECATED(8.3.0, "") = 3, + CURLSSLBACKEND_OBSOLETE4 = 4, /* Was QSOSSL. */ + CURLSSLBACKEND_GSKIT CURL_DEPRECATED(8.3.0, "") = 5, + CURLSSLBACKEND_POLARSSL CURL_DEPRECATED(7.69.0, "") = 6, + CURLSSLBACKEND_WOLFSSL = 7, + CURLSSLBACKEND_SCHANNEL = 8, + CURLSSLBACKEND_SECURETRANSPORT CURL_DEPRECATED(8.15.0, "") = 9, + CURLSSLBACKEND_AXTLS CURL_DEPRECATED(7.61.0, "") = 10, + CURLSSLBACKEND_MBEDTLS = 11, + CURLSSLBACKEND_MESALINK CURL_DEPRECATED(7.82.0, "") = 12, + CURLSSLBACKEND_BEARSSL CURL_DEPRECATED(8.15.0, "") = 13, + CURLSSLBACKEND_RUSTLS = 14 +} curl_sslbackend; + +/* aliases for library clones and renames */ +#define CURLSSLBACKEND_AWSLC CURLSSLBACKEND_OPENSSL +#define CURLSSLBACKEND_BORINGSSL CURLSSLBACKEND_OPENSSL +#define CURLSSLBACKEND_LIBRESSL CURLSSLBACKEND_OPENSSL + +/* deprecated names: */ +#define CURLSSLBACKEND_CYASSL CURLSSLBACKEND_WOLFSSL +#define CURLSSLBACKEND_DARWINSSL CURLSSLBACKEND_SECURETRANSPORT + +/* bits for the CURLOPT_FOLLOWLOCATION option */ +#define CURLFOLLOW_ALL 1L /* generic follow redirects */ + +/* Do not use the custom method in the follow-up request if the HTTP code + instructs so (301, 302, 303). */ +#define CURLFOLLOW_OBEYCODE 2L + +/* Only use the custom method in the first request, always reset in the next */ +#define CURLFOLLOW_FIRSTONLY 3L + +struct curl_httppost { + struct curl_httppost *next; /* next entry in the list */ + char *name; /* pointer to allocated name */ + long namelength; /* length of name length */ + char *contents; /* pointer to allocated data contents */ + long contentslength; /* length of contents field, see also + CURL_HTTPPOST_LARGE */ + char *buffer; /* pointer to allocated buffer contents */ + long bufferlength; /* length of buffer field */ + char *contenttype; /* Content-Type */ + struct curl_slist *contentheader; /* list of extra headers for this form */ + struct curl_httppost *more; /* if one field name has more than one + file, this link should link to following + files */ + long flags; /* as defined below */ + +/* specified content is a filename */ +#define CURL_HTTPPOST_FILENAME (1 << 0) +/* specified content is a filename */ +#define CURL_HTTPPOST_READFILE (1 << 1) +/* name is only stored pointer do not free in formfree */ +#define CURL_HTTPPOST_PTRNAME (1 << 2) +/* contents is only stored pointer do not free in formfree */ +#define CURL_HTTPPOST_PTRCONTENTS (1 << 3) +/* upload file from buffer */ +#define CURL_HTTPPOST_BUFFER (1 << 4) +/* upload file from pointer contents */ +#define CURL_HTTPPOST_PTRBUFFER (1 << 5) +/* upload file contents by using the regular read callback to get the data and + pass the given pointer as custom pointer */ +#define CURL_HTTPPOST_CALLBACK (1 << 6) +/* use size in 'contentlen', added in 7.46.0 */ +#define CURL_HTTPPOST_LARGE (1 << 7) + + char *showfilename; /* The filename to show. If not set, the + actual filename is used (if this is + a file part) */ + void *userp; /* custom pointer used for + HTTPPOST_CALLBACK posts */ + curl_off_t contentlen; /* alternative length of contents + field. Used if CURL_HTTPPOST_LARGE is + set. Added in 7.46.0 */ +}; + +/* This is a return code for the progress callback that, when returned, + signals libcurl to continue executing the default progress function */ +#define CURL_PROGRESSFUNC_CONTINUE 0x10000001 + +/* This is the CURLOPT_PROGRESSFUNCTION callback prototype. It is now + considered deprecated but was the only choice up until 7.31.0 */ +typedef int (*curl_progress_callback)(void *clientp, + double dltotal, + double dlnow, + double ultotal, + double ulnow); + +/* This is the CURLOPT_XFERINFOFUNCTION callback prototype. It was introduced + in 7.32.0, avoids the use of floating point numbers and provides more + detailed information. */ +typedef int (*curl_xferinfo_callback)(void *clientp, + curl_off_t dltotal, + curl_off_t dlnow, + curl_off_t ultotal, + curl_off_t ulnow); + +#ifndef CURL_MAX_READ_SIZE + /* The maximum receive buffer size configurable via CURLOPT_BUFFERSIZE. */ +#define CURL_MAX_READ_SIZE (10 * 1024 * 1024) +#endif + +#ifndef CURL_MAX_WRITE_SIZE + /* Tests have proven that 20K is a bad buffer size for uploads on Windows, + while 16K for some odd reason performed a lot better. We do the ifndef + check to allow this value to easier be changed at build time for those + who feel adventurous. The practical minimum is about 400 bytes since + libcurl uses a buffer of this size as a scratch area (unrelated to + network send operations). */ +#define CURL_MAX_WRITE_SIZE 16384 +#endif + +#ifndef CURL_MAX_HTTP_HEADER +/* The only reason to have a max limit for this is to avoid the risk of a bad + server feeding libcurl with a never-ending header that causes reallocs + infinitely */ +#define CURL_MAX_HTTP_HEADER (100 * 1024) +#endif + +/* This is a magic return code for the write callback that, when returned, + signals libcurl to pause receiving on the current transfer. */ +#define CURL_WRITEFUNC_PAUSE 0x10000001 + +/* This is a magic return code for the write callback that, when returned, + signals an error from the callback. */ +#define CURL_WRITEFUNC_ERROR 0xFFFFFFFF + +typedef size_t (*curl_write_callback)(char *buffer, + size_t size, + size_t nitems, + void *outstream); + +/* This callback is called when a new resolver request is made */ +typedef int (*curl_resolver_start_callback)(void *resolver_state, + void *reserved, void *userdata); + +/* enumeration of file types */ +typedef enum { + CURLFILETYPE_FILE = 0, + CURLFILETYPE_DIRECTORY, + CURLFILETYPE_SYMLINK, + CURLFILETYPE_DEVICE_BLOCK, + CURLFILETYPE_DEVICE_CHAR, + CURLFILETYPE_NAMEDPIPE, + CURLFILETYPE_SOCKET, + CURLFILETYPE_DOOR, /* is possible only on Sun Solaris now */ + + CURLFILETYPE_UNKNOWN /* should never occur */ +} curlfiletype; + +#define CURLFINFOFLAG_KNOWN_FILENAME (1 << 0) +#define CURLFINFOFLAG_KNOWN_FILETYPE (1 << 1) +#define CURLFINFOFLAG_KNOWN_TIME (1 << 2) +#define CURLFINFOFLAG_KNOWN_PERM (1 << 3) +#define CURLFINFOFLAG_KNOWN_UID (1 << 4) +#define CURLFINFOFLAG_KNOWN_GID (1 << 5) +#define CURLFINFOFLAG_KNOWN_SIZE (1 << 6) +#define CURLFINFOFLAG_KNOWN_HLINKCOUNT (1 << 7) + +/* Information about a single file, used when doing FTP wildcard matching */ +struct curl_fileinfo { + char *filename; + curlfiletype filetype; + time_t time; /* always zero! */ + unsigned int perm; + int uid; + int gid; + curl_off_t size; + long int hardlinks; + + struct { + /* If some of these fields is not NULL, it is a pointer to b_data. */ + char *time; + char *perm; + char *user; + char *group; + char *target; /* pointer to the target filename of a symlink */ + } strings; + + unsigned int flags; + + /* These are libcurl private struct fields. Previously used by libcurl, so + they must never be interfered with. */ + char *b_data; + size_t b_size; + size_t b_used; +}; + +/* return codes for CURLOPT_CHUNK_BGN_FUNCTION */ +#define CURL_CHUNK_BGN_FUNC_OK 0 +#define CURL_CHUNK_BGN_FUNC_FAIL 1 /* tell the lib to end the task */ +#define CURL_CHUNK_BGN_FUNC_SKIP 2 /* skip this chunk over */ + +/* if splitting of data transfer is enabled, this callback is called before + download of an individual chunk started. Note that parameter "remains" works + only for FTP wildcard downloading (for now), otherwise is not used */ +typedef long (*curl_chunk_bgn_callback)(const void *transfer_info, + void *ptr, + int remains); + +/* return codes for CURLOPT_CHUNK_END_FUNCTION */ +#define CURL_CHUNK_END_FUNC_OK 0 +#define CURL_CHUNK_END_FUNC_FAIL 1 /* tell the lib to end the task */ + +/* If splitting of data transfer is enabled this callback is called after + download of an individual chunk finished. + Note! After this callback was set then it have to be called FOR ALL chunks. + Even if downloading of this chunk was skipped in CHUNK_BGN_FUNC. + This is the reason why we do not need "transfer_info" parameter in this + callback and we are not interested in "remains" parameter too. */ +typedef long (*curl_chunk_end_callback)(void *ptr); + +/* return codes for FNMATCHFUNCTION */ +#define CURL_FNMATCHFUNC_MATCH 0 /* string corresponds to the pattern */ +#define CURL_FNMATCHFUNC_NOMATCH 1 /* pattern does not match the string */ +#define CURL_FNMATCHFUNC_FAIL 2 /* an error occurred */ + +/* callback type for wildcard downloading pattern matching. If the + string matches the pattern, return CURL_FNMATCHFUNC_MATCH value, etc. */ +typedef int (*curl_fnmatch_callback)(void *ptr, + const char *pattern, + const char *string); + +/* These are the return codes for the seek callbacks */ +#define CURL_SEEKFUNC_OK 0 +#define CURL_SEEKFUNC_FAIL 1 /* fail the entire transfer */ +#define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking cannot be done, so + libcurl might try other means instead */ +typedef int (*curl_seek_callback)(void *instream, + curl_off_t offset, + int origin); /* 'whence' */ + +/* This is a return code for the read callback that, when returned, + signals libcurl to immediately abort the current transfer. */ +#define CURL_READFUNC_ABORT 0x10000000 +/* This is a return code for the read callback that, when returned, + signals libcurl to pause sending data on the current transfer. */ +#define CURL_READFUNC_PAUSE 0x10000001 + +/* Return code for when the trailing headers' callback has terminated + without any errors */ +#define CURL_TRAILERFUNC_OK 0 +/* Return code for when was an error in the trailing header's list and we + want to abort the request */ +#define CURL_TRAILERFUNC_ABORT 1 + +typedef size_t (*curl_read_callback)(char *buffer, + size_t size, + size_t nitems, + void *instream); + +typedef int (*curl_trailer_callback)(struct curl_slist **list, + void *userdata); + +typedef enum { + CURLSOCKTYPE_IPCXN, /* socket created for a specific IP connection */ + CURLSOCKTYPE_ACCEPT, /* socket created by accept() call */ + CURLSOCKTYPE_LAST /* never use */ +} curlsocktype; + +/* The return code from the sockopt_callback can signal information back + to libcurl: */ +#define CURL_SOCKOPT_OK 0 +#define CURL_SOCKOPT_ERROR 1 /* causes libcurl to abort and return + CURLE_ABORTED_BY_CALLBACK */ +#define CURL_SOCKOPT_ALREADY_CONNECTED 2 + +typedef int (*curl_sockopt_callback)(void *clientp, + curl_socket_t curlfd, + curlsocktype purpose); + +struct curl_sockaddr { + int family; + int socktype; + int protocol; + unsigned int addrlen; /* addrlen was a socklen_t type before 7.18.0 but it + turned really ugly and painful on the systems that + lack this type */ + struct sockaddr addr; +}; + +typedef curl_socket_t +(*curl_opensocket_callback)(void *clientp, + curlsocktype purpose, + struct curl_sockaddr *address); + +typedef int +(*curl_closesocket_callback)(void *clientp, curl_socket_t item); + +typedef enum { + CURLIOE_OK, /* I/O operation successful */ + CURLIOE_UNKNOWNCMD, /* command was unknown to callback */ + CURLIOE_FAILRESTART, /* failed to restart the read */ + CURLIOE_LAST /* never use */ +} curlioerr; + +typedef enum { + CURLIOCMD_NOP, /* no operation */ + CURLIOCMD_RESTARTREAD, /* restart the read stream from start */ + CURLIOCMD_LAST /* never use */ +} curliocmd; + +typedef curlioerr (*curl_ioctl_callback)(CURL *handle, + int cmd, + void *clientp); + +#ifndef CURL_DID_MEMORY_FUNC_TYPEDEFS +/* + * The following typedef's are signatures of malloc, free, realloc, strdup and + * calloc respectively. Function pointers of these types can be passed to the + * curl_global_init_mem() function to set user defined memory management + * callback routines. + */ +typedef void *(*curl_malloc_callback)(size_t size); +typedef void (*curl_free_callback)(void *ptr); +typedef void *(*curl_realloc_callback)(void *ptr, size_t size); +typedef char *(*curl_strdup_callback)(const char *str); +typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size); + +#define CURL_DID_MEMORY_FUNC_TYPEDEFS +#endif + +/* the kind of data that is passed to information_callback */ +typedef enum { + CURLINFO_TEXT = 0, + CURLINFO_HEADER_IN, /* 1 */ + CURLINFO_HEADER_OUT, /* 2 */ + CURLINFO_DATA_IN, /* 3 */ + CURLINFO_DATA_OUT, /* 4 */ + CURLINFO_SSL_DATA_IN, /* 5 */ + CURLINFO_SSL_DATA_OUT, /* 6 */ + CURLINFO_END +} curl_infotype; + +typedef int (*curl_debug_callback) + (CURL *handle, /* the handle/transfer this concerns */ + curl_infotype type, /* what kind of data */ + char *data, /* points to the data */ + size_t size, /* size of the data pointed to */ + void *userptr); /* whatever the user please */ + +/* This is the CURLOPT_PREREQFUNCTION callback prototype. */ +typedef int (*curl_prereq_callback)(void *clientp, + char *conn_primary_ip, + char *conn_local_ip, + int conn_primary_port, + int conn_local_port); + +/* Return code for when the pre-request callback has terminated without + any errors */ +#define CURL_PREREQFUNC_OK 0 +/* Return code for when the pre-request callback wants to abort the + request */ +#define CURL_PREREQFUNC_ABORT 1 + +/* All possible error codes from all sorts of curl functions. Future versions + may return other values, stay prepared. + + Always add new return codes last. Never *EVER* remove any. The return + codes must remain the same! + */ + +typedef enum { + CURLE_OK = 0, + CURLE_UNSUPPORTED_PROTOCOL, /* 1 */ + CURLE_FAILED_INIT, /* 2 */ + CURLE_URL_MALFORMAT, /* 3 */ + CURLE_NOT_BUILT_IN, /* 4 - [was obsoleted in August 2007 for + 7.17.0, reused in April 2011 for 7.21.5] */ + CURLE_COULDNT_RESOLVE_PROXY, /* 5 */ + CURLE_COULDNT_RESOLVE_HOST, /* 6 */ + CURLE_COULDNT_CONNECT, /* 7 */ + CURLE_WEIRD_SERVER_REPLY, /* 8 */ + CURLE_REMOTE_ACCESS_DENIED, /* 9 a service was denied by the server + due to lack of access - when login fails + this is not returned. */ + CURLE_FTP_ACCEPT_FAILED, /* 10 - [was obsoleted in April 2006 for + 7.15.4, reused in Dec 2011 for 7.24.0]*/ + CURLE_FTP_WEIRD_PASS_REPLY, /* 11 */ + CURLE_FTP_ACCEPT_TIMEOUT, /* 12 - timeout occurred accepting server + [was obsoleted in August 2007 for 7.17.0, + reused in Dec 2011 for 7.24.0]*/ + CURLE_FTP_WEIRD_PASV_REPLY, /* 13 */ + CURLE_FTP_WEIRD_227_FORMAT, /* 14 */ + CURLE_FTP_CANT_GET_HOST, /* 15 */ + CURLE_HTTP2, /* 16 - A problem in the http2 framing layer. + [was obsoleted in August 2007 for 7.17.0, + reused in July 2014 for 7.38.0] */ + CURLE_FTP_COULDNT_SET_TYPE, /* 17 */ + CURLE_PARTIAL_FILE, /* 18 */ + CURLE_FTP_COULDNT_RETR_FILE, /* 19 */ + CURLE_OBSOLETE20, /* 20 - NOT USED */ + CURLE_QUOTE_ERROR, /* 21 - quote command failure */ + CURLE_HTTP_RETURNED_ERROR, /* 22 */ + CURLE_WRITE_ERROR, /* 23 */ + CURLE_OBSOLETE24, /* 24 - NOT USED */ + CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */ + CURLE_READ_ERROR, /* 26 - could not open/read from file */ + CURLE_OUT_OF_MEMORY, /* 27 */ + CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */ + CURLE_OBSOLETE29, /* 29 - NOT USED */ + CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */ + CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */ + CURLE_OBSOLETE32, /* 32 - NOT USED */ + CURLE_RANGE_ERROR, /* 33 - RANGE "command" did not work */ + CURLE_OBSOLETE34, /* 34 */ + CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */ + CURLE_BAD_DOWNLOAD_RESUME, /* 36 - could not resume download */ + CURLE_FILE_COULDNT_READ_FILE, /* 37 */ + CURLE_LDAP_CANNOT_BIND, /* 38 */ + CURLE_LDAP_SEARCH_FAILED, /* 39 */ + CURLE_OBSOLETE40, /* 40 - NOT USED */ + CURLE_OBSOLETE41, /* 41 - NOT USED starting with 7.53.0 */ + CURLE_ABORTED_BY_CALLBACK, /* 42 */ + CURLE_BAD_FUNCTION_ARGUMENT, /* 43 */ + CURLE_OBSOLETE44, /* 44 - NOT USED */ + CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */ + CURLE_OBSOLETE46, /* 46 - NOT USED */ + CURLE_TOO_MANY_REDIRECTS, /* 47 - catch endless re-direct loops */ + CURLE_UNKNOWN_OPTION, /* 48 - User specified an unknown option */ + CURLE_SETOPT_OPTION_SYNTAX, /* 49 - Malformed setopt option */ + CURLE_OBSOLETE50, /* 50 - NOT USED */ + CURLE_OBSOLETE51, /* 51 - NOT USED */ + CURLE_GOT_NOTHING, /* 52 - when this is a specific error */ + CURLE_SSL_ENGINE_NOTFOUND, /* 53 - SSL crypto engine not found */ + CURLE_SSL_ENGINE_SETFAILED, /* 54 - can not set SSL crypto engine as + default */ + CURLE_SEND_ERROR, /* 55 - failed sending network data */ + CURLE_RECV_ERROR, /* 56 - failure in receiving network data */ + CURLE_OBSOLETE57, /* 57 - NOT IN USE */ + CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */ + CURLE_SSL_CIPHER, /* 59 - could not use specified cipher */ + CURLE_PEER_FAILED_VERIFICATION, /* 60 - peer's certificate or fingerprint + was not verified fine */ + CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized/bad encoding */ + CURLE_OBSOLETE62, /* 62 - NOT IN USE since 7.82.0 */ + CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */ + CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */ + CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind + that failed */ + CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialize ENGINE */ + CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not + accepted and we failed to login */ + CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */ + CURLE_TFTP_PERM, /* 69 - permission problem on server */ + CURLE_REMOTE_DISK_FULL, /* 70 - out of disk space on server */ + CURLE_TFTP_ILLEGAL, /* 71 - Illegal TFTP operation */ + CURLE_TFTP_UNKNOWNID, /* 72 - Unknown transfer ID */ + CURLE_REMOTE_FILE_EXISTS, /* 73 - File already exists */ + CURLE_TFTP_NOSUCHUSER, /* 74 - No such user */ + CURLE_OBSOLETE75, /* 75 - NOT IN USE since 7.82.0 */ + CURLE_OBSOLETE76, /* 76 - NOT IN USE since 7.82.0 */ + CURLE_SSL_CACERT_BADFILE, /* 77 - could not load CACERT file, missing + or wrong format */ + CURLE_REMOTE_FILE_NOT_FOUND, /* 78 - remote file not found */ + CURLE_SSH, /* 79 - error from the SSH layer, somewhat + generic so the error message is of + interest when this has happened */ + + CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL + connection */ + CURLE_AGAIN, /* 81 - socket is not ready for send/recv, + wait till it is ready and try again (Added + in 7.18.2) */ + CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or + wrong format (Added in 7.19.0) */ + CURLE_SSL_ISSUER_ERROR, /* 83 - Issuer check failed. (Added in + 7.19.0) */ + CURLE_FTP_PRET_FAILED, /* 84 - a PRET command failed */ + CURLE_RTSP_CSEQ_ERROR, /* 85 - mismatch of RTSP CSeq numbers */ + CURLE_RTSP_SESSION_ERROR, /* 86 - mismatch of RTSP Session Ids */ + CURLE_FTP_BAD_FILE_LIST, /* 87 - unable to parse FTP file list */ + CURLE_CHUNK_FAILED, /* 88 - chunk callback reported error */ + CURLE_NO_CONNECTION_AVAILABLE, /* 89 - No connection available, the + session is queued */ + CURLE_SSL_PINNEDPUBKEYNOTMATCH, /* 90 - specified pinned public key did not + match */ + CURLE_SSL_INVALIDCERTSTATUS, /* 91 - invalid certificate status */ + CURLE_HTTP2_STREAM, /* 92 - stream error in HTTP/2 framing layer + */ + CURLE_RECURSIVE_API_CALL, /* 93 - an api function was called from + inside a callback */ + CURLE_AUTH_ERROR, /* 94 - an authentication function returned an + error */ + CURLE_HTTP3, /* 95 - An HTTP/3 layer problem */ + CURLE_QUIC_CONNECT_ERROR, /* 96 - QUIC connection error */ + CURLE_PROXY, /* 97 - proxy handshake error */ + CURLE_SSL_CLIENTCERT, /* 98 - client-side certificate required */ + CURLE_UNRECOVERABLE_POLL, /* 99 - poll/select returned fatal error */ + CURLE_TOO_LARGE, /* 100 - a value/data met its maximum */ + CURLE_ECH_REQUIRED, /* 101 - ECH tried but failed */ + CURL_LAST /* never use! */ +} CURLcode; + +#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all + the obsolete stuff removed! */ + +/* removed in 7.53.0 */ +#define CURLE_FUNCTION_NOT_FOUND CURLE_OBSOLETE41 + +/* removed in 7.56.0 */ +#define CURLE_HTTP_POST_ERROR CURLE_OBSOLETE34 + +/* Previously obsolete error code reused in 7.38.0 */ +#define CURLE_OBSOLETE16 CURLE_HTTP2 + +/* Previously obsolete error codes reused in 7.24.0 */ +#define CURLE_OBSOLETE10 CURLE_FTP_ACCEPT_FAILED +#define CURLE_OBSOLETE12 CURLE_FTP_ACCEPT_TIMEOUT + +/* compatibility with older names */ +#define CURLOPT_ENCODING CURLOPT_ACCEPT_ENCODING +#define CURLE_FTP_WEIRD_SERVER_REPLY CURLE_WEIRD_SERVER_REPLY + +/* The following were added in 7.62.0 */ +#define CURLE_SSL_CACERT CURLE_PEER_FAILED_VERIFICATION + +/* The following were added in 7.21.5, April 2011 */ +#define CURLE_UNKNOWN_TELNET_OPTION CURLE_UNKNOWN_OPTION + +/* Added for 7.78.0 */ +#define CURLE_TELNET_OPTION_SYNTAX CURLE_SETOPT_OPTION_SYNTAX + +/* The following were added in 7.17.1 */ +/* These are scheduled to disappear by 2009 */ +#define CURLE_SSL_PEER_CERTIFICATE CURLE_PEER_FAILED_VERIFICATION + +/* The following were added in 7.17.0 */ +/* These are scheduled to disappear by 2009 */ +#define CURLE_OBSOLETE CURLE_OBSOLETE50 /* no one should be using this! */ +#define CURLE_BAD_PASSWORD_ENTERED CURLE_OBSOLETE46 +#define CURLE_BAD_CALLING_ORDER CURLE_OBSOLETE44 +#define CURLE_FTP_USER_PASSWORD_INCORRECT CURLE_OBSOLETE10 +#define CURLE_FTP_CANT_RECONNECT CURLE_OBSOLETE16 +#define CURLE_FTP_COULDNT_GET_SIZE CURLE_OBSOLETE32 +#define CURLE_FTP_COULDNT_SET_ASCII CURLE_OBSOLETE29 +#define CURLE_FTP_WEIRD_USER_REPLY CURLE_OBSOLETE12 +#define CURLE_FTP_WRITE_ERROR CURLE_OBSOLETE20 +#define CURLE_LIBRARY_NOT_FOUND CURLE_OBSOLETE40 +#define CURLE_MALFORMAT_USER CURLE_OBSOLETE24 +#define CURLE_SHARE_IN_USE CURLE_OBSOLETE57 +#define CURLE_URL_MALFORMAT_USER CURLE_NOT_BUILT_IN + +#define CURLE_FTP_ACCESS_DENIED CURLE_REMOTE_ACCESS_DENIED +#define CURLE_FTP_COULDNT_SET_BINARY CURLE_FTP_COULDNT_SET_TYPE +#define CURLE_FTP_QUOTE_ERROR CURLE_QUOTE_ERROR +#define CURLE_TFTP_DISKFULL CURLE_REMOTE_DISK_FULL +#define CURLE_TFTP_EXISTS CURLE_REMOTE_FILE_EXISTS +#define CURLE_HTTP_RANGE_ERROR CURLE_RANGE_ERROR +#define CURLE_FTP_SSL_FAILED CURLE_USE_SSL_FAILED + +/* The following were added earlier */ + +#define CURLE_OPERATION_TIMEOUTED CURLE_OPERATION_TIMEDOUT +#define CURLE_HTTP_NOT_FOUND CURLE_HTTP_RETURNED_ERROR +#define CURLE_HTTP_PORT_FAILED CURLE_INTERFACE_FAILED +#define CURLE_FTP_COULDNT_STOR_FILE CURLE_UPLOAD_FAILED +#define CURLE_FTP_PARTIAL_FILE CURLE_PARTIAL_FILE +#define CURLE_FTP_BAD_DOWNLOAD_RESUME CURLE_BAD_DOWNLOAD_RESUME +#define CURLE_LDAP_INVALID_URL CURLE_OBSOLETE62 +#define CURLE_CONV_REQD CURLE_OBSOLETE76 +#define CURLE_CONV_FAILED CURLE_OBSOLETE75 + +/* This was the error code 50 in 7.7.3 and a few earlier versions, this + is no longer used by libcurl but is instead #defined here only to not + make programs break */ +#define CURLE_ALREADY_COMPLETE 99999 + +/* Provide defines for really old option names */ +#define CURLOPT_FILE CURLOPT_WRITEDATA /* name changed in 7.9.7 */ +#define CURLOPT_INFILE CURLOPT_READDATA /* name changed in 7.9.7 */ +#define CURLOPT_WRITEHEADER CURLOPT_HEADERDATA + +/* Since long deprecated options with no code in the lib that does anything + with them. */ +#define CURLOPT_WRITEINFO CURLOPT_OBSOLETE40 +#define CURLOPT_CLOSEPOLICY CURLOPT_OBSOLETE72 +#define CURLOPT_OBSOLETE72 9999 +#define CURLOPT_OBSOLETE40 9999 + +#endif /* !CURL_NO_OLDIES */ + +/* + * Proxy error codes. Returned in CURLINFO_PROXY_ERROR if CURLE_PROXY was + * return for the transfers. + */ +typedef enum { + CURLPX_OK, + CURLPX_BAD_ADDRESS_TYPE, + CURLPX_BAD_VERSION, + CURLPX_CLOSED, + CURLPX_GSSAPI, + CURLPX_GSSAPI_PERMSG, + CURLPX_GSSAPI_PROTECTION, + CURLPX_IDENTD, + CURLPX_IDENTD_DIFFER, + CURLPX_LONG_HOSTNAME, + CURLPX_LONG_PASSWD, + CURLPX_LONG_USER, + CURLPX_NO_AUTH, + CURLPX_RECV_ADDRESS, + CURLPX_RECV_AUTH, + CURLPX_RECV_CONNECT, + CURLPX_RECV_REQACK, + CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED, + CURLPX_REPLY_COMMAND_NOT_SUPPORTED, + CURLPX_REPLY_CONNECTION_REFUSED, + CURLPX_REPLY_GENERAL_SERVER_FAILURE, + CURLPX_REPLY_HOST_UNREACHABLE, + CURLPX_REPLY_NETWORK_UNREACHABLE, + CURLPX_REPLY_NOT_ALLOWED, + CURLPX_REPLY_TTL_EXPIRED, + CURLPX_REPLY_UNASSIGNED, + CURLPX_REQUEST_FAILED, + CURLPX_RESOLVE_HOST, + CURLPX_SEND_AUTH, + CURLPX_SEND_CONNECT, + CURLPX_SEND_REQUEST, + CURLPX_UNKNOWN_FAIL, + CURLPX_UNKNOWN_MODE, + CURLPX_USER_REJECTED, + CURLPX_LAST /* never use */ +} CURLproxycode; + +/* This prototype applies to all conversion callbacks */ +typedef CURLcode (*curl_conv_callback)(char *buffer, size_t length); + +typedef CURLcode (*curl_ssl_ctx_callback)(CURL *curl, /* easy handle */ + void *ssl_ctx, /* actually an OpenSSL + or wolfSSL SSL_CTX, + or an mbedTLS + mbedtls_ssl_config */ + void *userptr); + +#define CURLPROXY_HTTP 0L /* added in 7.10, new in 7.19.4 default is + to use CONNECT HTTP/1.1 */ +#define CURLPROXY_HTTP_1_0 1L /* force to use CONNECT HTTP/1.0 + added in 7.19.4 */ +#define CURLPROXY_HTTPS 2L /* HTTPS but stick to HTTP/1 + added in 7.52.0 */ +#define CURLPROXY_HTTPS2 3L /* HTTPS and attempt HTTP/2 + added in 8.2.0 */ +#define CURLPROXY_SOCKS4 4L /* support added in 7.15.2, enum existed + already in 7.10 */ +#define CURLPROXY_SOCKS5 5L /* added in 7.10 */ +#define CURLPROXY_SOCKS4A 6L /* added in 7.18.0 */ +#define CURLPROXY_SOCKS5_HOSTNAME 7L /* Use the SOCKS5 protocol but pass along + the hostname rather than the IP + address. added in 7.18.0 */ +#define CURLPROXY_HTTPS3 8L /* HTTPS and attempt HTTP/3 + added in 8.21.0 */ + +typedef enum { + CURLPROXY_LAST = 9 /* never use */ +} curl_proxytype; /* this enum was added in 7.10 */ + +/* + * Bitmasks for CURLOPT_HTTPAUTH and CURLOPT_PROXYAUTH options: + * + * CURLAUTH_NONE - No HTTP authentication + * CURLAUTH_BASIC - HTTP Basic authentication (default) + * CURLAUTH_DIGEST - HTTP Digest authentication + * CURLAUTH_NEGOTIATE - HTTP Negotiate (SPNEGO) authentication + * CURLAUTH_GSSNEGOTIATE - Alias for CURLAUTH_NEGOTIATE (deprecated) + * CURLAUTH_NTLM - HTTP NTLM authentication + * CURLAUTH_DIGEST_IE - HTTP Digest authentication with IE flavor + * CURLAUTH_NTLM_WB - HTTP NTLM authentication delegated to winbind helper + * CURLAUTH_BEARER - HTTP Bearer token authentication + * CURLAUTH_ONLY - Use together with a single other type to force no + * authentication or that single type + * CURLAUTH_ANY - All fine types set + * CURLAUTH_ANYSAFE - All fine types except Basic + */ + +#define CURLAUTH_NONE ((unsigned long)0) +#define CURLAUTH_BASIC (((unsigned long)1) << 0) +#define CURLAUTH_DIGEST (((unsigned long)1) << 1) +#define CURLAUTH_NEGOTIATE (((unsigned long)1) << 2) +/* Deprecated since the advent of CURLAUTH_NEGOTIATE */ +#define CURLAUTH_GSSNEGOTIATE CURLAUTH_NEGOTIATE +/* Used for CURLOPT_SOCKS5_AUTH to stay terminologically correct */ +#define CURLAUTH_GSSAPI CURLAUTH_NEGOTIATE +#define CURLAUTH_NTLM (((unsigned long)1) << 3) +#define CURLAUTH_DIGEST_IE (((unsigned long)1) << 4) +#ifndef CURL_NO_OLDIES + /* functionality removed since 8.8.0 */ +#define CURLAUTH_NTLM_WB (((unsigned long)1) << 5) +#endif +#define CURLAUTH_BEARER (((unsigned long)1) << 6) +#define CURLAUTH_AWS_SIGV4 (((unsigned long)1) << 7) +#define CURLAUTH_HTTPSIG (((unsigned long)1) << 8) +#define CURLAUTH_ONLY (((unsigned long)1) << 31) +#define CURLAUTH_ANY ((~(CURLAUTH_DIGEST_IE | \ + CURLAUTH_HTTPSIG)) & \ + ((unsigned long)0xffffffff)) +#define CURLAUTH_ANYSAFE ((~(CURLAUTH_BASIC | CURLAUTH_DIGEST_IE | \ + CURLAUTH_HTTPSIG)) & \ + ((unsigned long)0xffffffff)) + +/* constants for CURLOPT_HTTPSIG_ALGORITHM */ +#define CURLHTTPSIG_NONE 0L +#define CURLHTTPSIG_ED25519 1L +#define CURLHTTPSIG_HMAC_SHA256 2L + +/* all types supported by server */ +#define CURLSSH_AUTH_ANY ((unsigned long)0xffffffff) +#define CURLSSH_AUTH_NONE 0L /* none allowed, silly but complete */ +#define CURLSSH_AUTH_PUBLICKEY (1L << 0) /* public/private key files */ +#define CURLSSH_AUTH_PASSWORD (1L << 1) /* password */ +#define CURLSSH_AUTH_HOST (1L << 2) /* host key files */ +#define CURLSSH_AUTH_KEYBOARD (1L << 3) /* keyboard interactive */ +#define CURLSSH_AUTH_AGENT (1L << 4) /* agent (ssh-agent, pageant...) */ +#define CURLSSH_AUTH_GSSAPI (1L << 5) /* gssapi (kerberos, ...) */ +#define CURLSSH_AUTH_DEFAULT CURLSSH_AUTH_ANY + +#define CURLGSSAPI_DELEGATION_NONE 0L /* no delegation (default) */ +#define CURLGSSAPI_DELEGATION_POLICY_FLAG (1L<<0) /* if permitted by policy */ +#define CURLGSSAPI_DELEGATION_FLAG (1L<<1) /* delegate always */ + +#define CURL_ERROR_SIZE 256 + +enum curl_khtype { + CURLKHTYPE_UNKNOWN, + CURLKHTYPE_RSA1, + CURLKHTYPE_RSA, + CURLKHTYPE_DSS, + CURLKHTYPE_ECDSA, + CURLKHTYPE_ED25519 +}; + +struct curl_khkey { + const char *key; /* points to a null-terminated string encoded with base64 + if len is zero, otherwise to the "raw" data */ + size_t len; + enum curl_khtype keytype; +}; + +/* this is the set of return values expected from the curl_sshkeycallback + callback */ +enum curl_khstat { + CURLKHSTAT_FINE_ADD_TO_FILE, + CURLKHSTAT_FINE, + CURLKHSTAT_REJECT, /* reject the connection, return an error */ + CURLKHSTAT_DEFER, /* do not accept it, but we cannot answer right now. + Causes a CURLE_PEER_FAILED_VERIFICATION error but the + connection is left intact etc */ + CURLKHSTAT_FINE_REPLACE, /* accept and replace the wrong key */ + CURLKHSTAT_LAST /* not for use, only a marker for last-in-list */ +}; + +/* this is the set of status codes pass in to the callback */ +enum curl_khmatch { + CURLKHMATCH_OK, /* match */ + CURLKHMATCH_MISMATCH, /* host found, key mismatch! */ + CURLKHMATCH_MISSING, /* no matching host/key found */ + CURLKHMATCH_LAST /* not for use, only a marker for last-in-list */ +}; + +typedef int + (*curl_sshkeycallback)(CURL *easy, /* easy handle */ + const struct curl_khkey *knownkey, /* known */ + const struct curl_khkey *foundkey, /* found */ + enum curl_khmatch, /* libcurl's view on the keys */ + void *clientp); /* custom pointer passed with */ + /* CURLOPT_SSH_KEYDATA */ + +typedef int + (*curl_sshhostkeycallback)(void *clientp,/* custom pointer passed */ + /* with CURLOPT_SSH_HOSTKEYDATA */ + int keytype, /* CURLKHTYPE */ + const char *key, /* hostkey to check */ + size_t keylen); /* length of the key */ + /* return CURLE_OK to accept */ + /* or something else to refuse */ + +/* parameter for the CURLOPT_USE_SSL option */ +#define CURLUSESSL_NONE 0L /* do not attempt to use SSL */ +#define CURLUSESSL_TRY 1L /* try using SSL, proceed anyway otherwise */ +#define CURLUSESSL_CONTROL 2L /* SSL for the control connection or fail */ +#define CURLUSESSL_ALL 3L /* SSL for all communication or fail */ + +typedef enum { + CURLUSESSL_LAST = 4 /* not an option, never use */ +} curl_usessl; + +/* Definition of bits for the CURLOPT_SSL_OPTIONS argument: */ + +/* - ALLOW_BEAST tells libcurl to allow the BEAST SSL vulnerability in the + name of improving interoperability with older servers. Some SSL libraries + have introduced workarounds for this flaw but those workarounds sometimes + make the SSL communication fail. To regain functionality with those broken + servers, a user can this way allow the vulnerability back. */ +#define CURLSSLOPT_ALLOW_BEAST (1L << 0) + +/* - NO_REVOKE tells libcurl to disable certificate revocation checks for those + SSL backends where such behavior is present. */ +#define CURLSSLOPT_NO_REVOKE (1L << 1) + +/* - NO_PARTIALCHAIN tells libcurl to *NOT* accept a partial certificate chain + if possible. The OpenSSL backend has this ability. */ +#define CURLSSLOPT_NO_PARTIALCHAIN (1L << 2) + +/* - REVOKE_BEST_EFFORT tells libcurl to ignore certificate revocation offline + checks and ignore missing revocation list for those SSL backends where such + behavior is present. */ +#define CURLSSLOPT_REVOKE_BEST_EFFORT (1L << 3) + +/* - CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of + operating system. Currently implemented under MS-Windows. */ +#define CURLSSLOPT_NATIVE_CA (1L << 4) + +/* - CURLSSLOPT_AUTO_CLIENT_CERT tells libcurl to automatically locate and use + a client certificate for authentication. (Schannel) */ +#define CURLSSLOPT_AUTO_CLIENT_CERT (1L << 5) + +/* If possible, send data using TLS 1.3 early data */ +#define CURLSSLOPT_EARLYDATA (1L << 6) + +/* The default connection attempt delay in milliseconds for happy eyeballs. + CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS.3 and happy-eyeballs-timeout-ms.d document + this value, keep them in sync. */ +#define CURL_HET_DEFAULT 200L + +/* The default connection upkeep interval in milliseconds. */ +#define CURL_UPKEEP_INTERVAL_DEFAULT 60000L + +#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all + the obsolete stuff removed! */ + +/* Backwards compatibility with older names */ +/* These are scheduled to disappear by 2009 */ + +#define CURLFTPSSL_NONE CURLUSESSL_NONE +#define CURLFTPSSL_TRY CURLUSESSL_TRY +#define CURLFTPSSL_CONTROL CURLUSESSL_CONTROL +#define CURLFTPSSL_ALL CURLUSESSL_ALL +#define CURLFTPSSL_LAST CURLUSESSL_LAST +#define curl_ftpssl curl_usessl +#endif /* !CURL_NO_OLDIES */ + +/* parameter for the CURLOPT_FTP_SSL_CCC option */ +#define CURLFTPSSL_CCC_NONE 0L /* do not send CCC */ +#define CURLFTPSSL_CCC_PASSIVE 1L /* Let the server initiate the shutdown */ +#define CURLFTPSSL_CCC_ACTIVE 2L /* Initiate the shutdown */ + +typedef enum { + CURLFTPSSL_CCC_LAST = 3 /* not an option, never use */ +} curl_ftpccc; + +/* parameter for the CURLOPT_FTPSSLAUTH option */ +#define CURLFTPAUTH_DEFAULT 0L /* let libcurl decide */ +#define CURLFTPAUTH_SSL 1L /* use "AUTH SSL" */ +#define CURLFTPAUTH_TLS 2L /* use "AUTH TLS" */ + +typedef enum { + CURLFTPAUTH_LAST = 3 /* not an option, never use */ +} curl_ftpauth; + +/* parameter for the CURLOPT_FTP_CREATE_MISSING_DIRS option */ +#define CURLFTP_CREATE_DIR_NONE 0L /* do NOT create missing dirs! */ +#define CURLFTP_CREATE_DIR 1L /* (FTP/SFTP) if CWD fails, try MKD and + then CWD again if MKD succeeded, for + SFTP this does similar magic */ +#define CURLFTP_CREATE_DIR_RETRY 2L /* (FTP only) if CWD fails, try MKD and + then CWD again even if MKD failed! */ + +typedef enum { + CURLFTP_CREATE_DIR_LAST = 3 /* not an option, never use */ +} curl_ftpcreatedir; + +/* parameter for the CURLOPT_FTP_FILEMETHOD option */ +#define CURLFTPMETHOD_DEFAULT 0L /* let libcurl pick */ +#define CURLFTPMETHOD_MULTICWD 1L /* single CWD operation for each path + part */ +#define CURLFTPMETHOD_NOCWD 2L /* no CWD at all */ +#define CURLFTPMETHOD_SINGLECWD 3L /* one CWD to full dir, then work on file */ + +typedef enum { + CURLFTPMETHOD_LAST = 4 /* not an option, never use */ +} curl_ftpmethod; + +/* bitmask defines for CURLOPT_HEADEROPT */ +#define CURLHEADER_UNIFIED 0L +#define CURLHEADER_SEPARATE (1L << 0) + +/* CURLALTSVC_* are bits for the CURLOPT_ALTSVC_CTRL option */ +#define CURLALTSVC_READONLYFILE (1L << 2) +#define CURLALTSVC_H1 (1L << 3) +#define CURLALTSVC_H2 (1L << 4) +#define CURLALTSVC_H3 (1L << 5) + +/* bitmask values for CURLOPT_UPLOAD_FLAGS */ +#define CURLULFLAG_ANSWERED (1L << 0) +#define CURLULFLAG_DELETED (1L << 1) +#define CURLULFLAG_DRAFT (1L << 2) +#define CURLULFLAG_FLAGGED (1L << 3) +#define CURLULFLAG_SEEN (1L << 4) + +struct curl_hstsentry { + char *name; + size_t namelen; + unsigned int includeSubDomains:1; + char expire[18]; /* YYYYMMDD HH:MM:SS [null-terminated] */ +}; + +struct curl_index { + size_t index; /* the provided entry's "index" or count */ + size_t total; /* total number of entries to save */ +}; + +typedef enum { + CURLSTS_OK, + CURLSTS_DONE, + CURLSTS_FAIL +} CURLSTScode; + +typedef CURLSTScode (*curl_hstsread_callback)(CURL *easy, + struct curl_hstsentry *e, + void *userp); +typedef CURLSTScode (*curl_hstswrite_callback)(CURL *easy, + struct curl_hstsentry *e, + struct curl_index *i, + void *userp); + +/* CURLHSTS_* are bits for the CURLOPT_HSTS option */ +#define CURLHSTS_ENABLE (1L << 0) +#define CURLHSTS_READONLYFILE (1L << 1) + +/* The CURLPROTO_ defines below are for the **deprecated** CURLOPT_*PROTOCOLS + options. Do not use. */ +#define CURLPROTO_HTTP (1L << 0) +#define CURLPROTO_HTTPS (1L << 1) +#define CURLPROTO_FTP (1L << 2) +#define CURLPROTO_FTPS (1L << 3) +#define CURLPROTO_SCP (1L << 4) +#define CURLPROTO_SFTP (1L << 5) +#define CURLPROTO_TELNET (1L << 6) +#define CURLPROTO_LDAP (1L << 7) +#define CURLPROTO_LDAPS (1L << 8) +#define CURLPROTO_DICT (1L << 9) +#define CURLPROTO_FILE (1L << 10) +#define CURLPROTO_TFTP (1L << 11) +#define CURLPROTO_IMAP (1L << 12) +#define CURLPROTO_IMAPS (1L << 13) +#define CURLPROTO_POP3 (1L << 14) +#define CURLPROTO_POP3S (1L << 15) +#define CURLPROTO_SMTP (1L << 16) +#define CURLPROTO_SMTPS (1L << 17) +#define CURLPROTO_RTSP (1L << 18) +#define CURLPROTO_RTMP (1L << 19) +#define CURLPROTO_RTMPT (1L << 20) +#define CURLPROTO_RTMPE (1L << 21) +#define CURLPROTO_RTMPTE (1L << 22) +#define CURLPROTO_RTMPS (1L << 23) +#define CURLPROTO_RTMPTS (1L << 24) +#define CURLPROTO_GOPHER (1L << 25) +#define CURLPROTO_SMB (1L << 26) +#define CURLPROTO_SMBS (1L << 27) +#define CURLPROTO_MQTT (1L << 28) +#define CURLPROTO_GOPHERS (1L << 29) +#define CURLPROTO_ALL ((unsigned long)0xffffffff) /* old-style enable + "everything" */ + +/* long may be 32 or 64 bits, but we should never depend on anything else + but 32 */ +#define CURLOPTTYPE_LONG 0 +#define CURLOPTTYPE_OBJECTPOINT 10000 +#define CURLOPTTYPE_FUNCTIONPOINT 20000 +#define CURLOPTTYPE_OFF_T 30000 +#define CURLOPTTYPE_BLOB 40000 + +/* *STRINGPOINT is an alias for OBJECTPOINT to allow tools to extract the + string options from the header file */ + +#define CURLOPT(na, t, nu) na = ((t) + (nu)) +#define CURLOPTDEPRECATED(na, t, nu, v, m) na CURL_DEPRECATED(v, m) \ + = ((t) + (nu)) + +/* CURLOPT aliases that make no runtime difference */ + +/* 'char *' argument to a string with a trailing zero */ +#define CURLOPTTYPE_STRINGPOINT CURLOPTTYPE_OBJECTPOINT + +/* 'struct curl_slist *' argument */ +#define CURLOPTTYPE_SLISTPOINT CURLOPTTYPE_OBJECTPOINT + +/* 'void *' argument passed untouched to callback */ +#define CURLOPTTYPE_CBPOINT CURLOPTTYPE_OBJECTPOINT + +/* 'long' argument with a set of values/bitmask */ +#define CURLOPTTYPE_VALUES CURLOPTTYPE_LONG + +/* + * All CURLOPT_* values. + */ + +typedef enum { + /* This is the FILE * or void * the regular output should be written to. */ + CURLOPT(CURLOPT_WRITEDATA, CURLOPTTYPE_CBPOINT, 1), + + /* The full URL to get/put */ + CURLOPT(CURLOPT_URL, CURLOPTTYPE_STRINGPOINT, 2), + + /* Port number to connect to, if other than default. */ + CURLOPT(CURLOPT_PORT, CURLOPTTYPE_LONG, 3), + + /* Name of proxy to use. */ + CURLOPT(CURLOPT_PROXY, CURLOPTTYPE_STRINGPOINT, 4), + + /* "user:password;options" to use when fetching. */ + CURLOPT(CURLOPT_USERPWD, CURLOPTTYPE_STRINGPOINT, 5), + + /* "user:password" to use with proxy. */ + CURLOPT(CURLOPT_PROXYUSERPWD, CURLOPTTYPE_STRINGPOINT, 6), + + /* Range to get, specified as an ASCII string. */ + CURLOPT(CURLOPT_RANGE, CURLOPTTYPE_STRINGPOINT, 7), + + /* not used */ + + /* Specified file stream to upload from (use as input): */ + CURLOPT(CURLOPT_READDATA, CURLOPTTYPE_CBPOINT, 9), + + /* Buffer to receive error messages in, must be at least CURL_ERROR_SIZE + * bytes big. */ + CURLOPT(CURLOPT_ERRORBUFFER, CURLOPTTYPE_OBJECTPOINT, 10), + + /* Function that is called to store the output (instead of fwrite). The + * parameters use fwrite() syntax, make sure to follow them. */ + CURLOPT(CURLOPT_WRITEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 11), + + /* Function that is called to read the input (instead of fread). The + * parameters use fread() syntax, make sure to follow them. */ + CURLOPT(CURLOPT_READFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 12), + + /* Time-out the read operation after this amount of seconds */ + CURLOPT(CURLOPT_TIMEOUT, CURLOPTTYPE_LONG, 13), + + /* If CURLOPT_READDATA is used, this can be used to inform libcurl about + * how large the file being sent really is. That allows better error + * checking and better verifies that the upload was successful. -1 means + * unknown size. + * + * For large file support, there is also a _LARGE version of the key + * which takes an off_t type, allowing platforms with larger off_t + * sizes to handle larger files. See below for INFILESIZE_LARGE. + */ + CURLOPT(CURLOPT_INFILESIZE, CURLOPTTYPE_LONG, 14), + + /* POST static input fields. */ + CURLOPT(CURLOPT_POSTFIELDS, CURLOPTTYPE_OBJECTPOINT, 15), + + /* Set the referrer page (needed by some CGIs) */ + CURLOPT(CURLOPT_REFERER, CURLOPTTYPE_STRINGPOINT, 16), + + /* Set the FTP PORT string (interface name, named or numerical IP address) + Use i.e '-' to use default address. */ + CURLOPT(CURLOPT_FTPPORT, CURLOPTTYPE_STRINGPOINT, 17), + + /* Set the User-Agent string (examined by some CGIs) */ + CURLOPT(CURLOPT_USERAGENT, CURLOPTTYPE_STRINGPOINT, 18), + + /* If the download receives less than "low speed limit" bytes/second + * during "low speed time" seconds, the operations is aborted. + * You could i.e if you have a pretty high speed connection, abort if + * it is less than 2000 bytes/sec during 20 seconds. + */ + + /* Set the "low speed limit" */ + CURLOPT(CURLOPT_LOW_SPEED_LIMIT, CURLOPTTYPE_LONG, 19), + + /* Set the "low speed time" */ + CURLOPT(CURLOPT_LOW_SPEED_TIME, CURLOPTTYPE_LONG, 20), + + /* Set the continuation offset. + * + * Note there is also a _LARGE version of this key which uses + * off_t types, allowing for large file offsets on platforms which + * use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE. + */ + CURLOPT(CURLOPT_RESUME_FROM, CURLOPTTYPE_LONG, 21), + + /* Set cookie in request: */ + CURLOPT(CURLOPT_COOKIE, CURLOPTTYPE_STRINGPOINT, 22), + + /* This points to a linked list of headers, struct curl_slist kind. This + list is also used for RTSP (in spite of its name) */ + CURLOPT(CURLOPT_HTTPHEADER, CURLOPTTYPE_SLISTPOINT, 23), + + /* This points to a linked list of post entries, struct curl_httppost */ + CURLOPTDEPRECATED(CURLOPT_HTTPPOST, CURLOPTTYPE_OBJECTPOINT, 24, + 7.56.0, "Use CURLOPT_MIMEPOST"), + + /* name of the file keeping your private SSL-certificate */ + CURLOPT(CURLOPT_SSLCERT, CURLOPTTYPE_STRINGPOINT, 25), + + /* password for the SSL or SSH private key */ + CURLOPT(CURLOPT_KEYPASSWD, CURLOPTTYPE_STRINGPOINT, 26), + + /* send TYPE parameter? */ + CURLOPT(CURLOPT_CRLF, CURLOPTTYPE_LONG, 27), + + /* send linked-list of QUOTE commands */ + CURLOPT(CURLOPT_QUOTE, CURLOPTTYPE_SLISTPOINT, 28), + + /* send FILE * or void * to store headers to, if you use a callback it + is passed to the callback unmodified */ + CURLOPT(CURLOPT_HEADERDATA, CURLOPTTYPE_CBPOINT, 29), + + /* point to a file to read the initial cookies from, also enables + "cookie awareness" */ + CURLOPT(CURLOPT_COOKIEFILE, CURLOPTTYPE_STRINGPOINT, 31), + + /* What version to specifically try to use. + See CURL_SSLVERSION defines below. */ + CURLOPT(CURLOPT_SSLVERSION, CURLOPTTYPE_VALUES, 32), + + /* What kind of HTTP time condition to use, see defines */ + CURLOPT(CURLOPT_TIMECONDITION, CURLOPTTYPE_VALUES, 33), + + /* Time to use with the above condition. Specified in number of seconds + since 1 Jan 1970 */ + CURLOPT(CURLOPT_TIMEVALUE, CURLOPTTYPE_LONG, 34), + + /* 35 = OBSOLETE */ + + /* Custom request, for customizing the get command like + HTTP: DELETE, TRACE and others + FTP: to use a different list command + */ + CURLOPT(CURLOPT_CUSTOMREQUEST, CURLOPTTYPE_STRINGPOINT, 36), + + /* FILE handle to use instead of stderr */ + CURLOPT(CURLOPT_STDERR, CURLOPTTYPE_OBJECTPOINT, 37), + + /* 38 is not used */ + + /* send linked-list of post-transfer QUOTE commands */ + CURLOPT(CURLOPT_POSTQUOTE, CURLOPTTYPE_SLISTPOINT, 39), + + /* 40 is not used */ + + /* talk a lot */ + CURLOPT(CURLOPT_VERBOSE, CURLOPTTYPE_LONG, 41), + + /* throw the header out too */ + CURLOPT(CURLOPT_HEADER, CURLOPTTYPE_LONG, 42), + + /* shut off the progress meter */ + CURLOPT(CURLOPT_NOPROGRESS, CURLOPTTYPE_LONG, 43), + + /* use HEAD to get http document */ + CURLOPT(CURLOPT_NOBODY, CURLOPTTYPE_LONG, 44), + + /* no output on http error codes >= 400 */ + CURLOPT(CURLOPT_FAILONERROR, CURLOPTTYPE_LONG, 45), + + /* this is an upload */ + CURLOPT(CURLOPT_UPLOAD, CURLOPTTYPE_LONG, 46), + + /* HTTP POST method */ + CURLOPT(CURLOPT_POST, CURLOPTTYPE_LONG, 47), + + /* bare names when listing directories */ + CURLOPT(CURLOPT_DIRLISTONLY, CURLOPTTYPE_LONG, 48), + + /* Append instead of overwrite on upload! */ + CURLOPT(CURLOPT_APPEND, CURLOPTTYPE_LONG, 50), + + /* Specify whether to read the user+password from the .netrc or the URL. + * This must be one of the CURL_NETRC_* enums below. */ + CURLOPT(CURLOPT_NETRC, CURLOPTTYPE_VALUES, 51), + + /* use Location: Luke! */ + CURLOPT(CURLOPT_FOLLOWLOCATION, CURLOPTTYPE_LONG, 52), + + /* transfer data in text/ASCII format */ + CURLOPT(CURLOPT_TRANSFERTEXT, CURLOPTTYPE_LONG, 53), + + /* HTTP PUT */ + CURLOPTDEPRECATED(CURLOPT_PUT, CURLOPTTYPE_LONG, 54, + 7.12.1, "Use CURLOPT_UPLOAD"), + + /* 55 = OBSOLETE */ + + /* DEPRECATED + * Function that is called instead of the internal progress display + * function. This function should be defined as the curl_progress_callback + * prototype defines. */ + CURLOPTDEPRECATED(CURLOPT_PROGRESSFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 56, + 7.32.0, "Use CURLOPT_XFERINFOFUNCTION"), + + /* Data passed to the CURLOPT_PROGRESSFUNCTION and CURLOPT_XFERINFOFUNCTION + callbacks */ + CURLOPT(CURLOPT_XFERINFODATA, CURLOPTTYPE_CBPOINT, 57), +#define CURLOPT_PROGRESSDATA CURLOPT_XFERINFODATA + + /* We want the referrer field set automatically when following locations */ + CURLOPT(CURLOPT_AUTOREFERER, CURLOPTTYPE_LONG, 58), + + /* Port of the proxy, can be set in the proxy string as well with: + "[host]:[port]" */ + CURLOPT(CURLOPT_PROXYPORT, CURLOPTTYPE_LONG, 59), + + /* size of the POST input data, if strlen() is not good to use */ + CURLOPT(CURLOPT_POSTFIELDSIZE, CURLOPTTYPE_LONG, 60), + + /* tunnel non-http operations through an HTTP proxy */ + CURLOPT(CURLOPT_HTTPPROXYTUNNEL, CURLOPTTYPE_LONG, 61), + + /* Set the interface string to use as outgoing network interface */ + CURLOPT(CURLOPT_INTERFACE, CURLOPTTYPE_STRINGPOINT, 62), + + /* Set the krb4/5 security level, this also enables krb4/5 awareness. This + * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string + * is set but does not match one of these, 'private' is used. */ + CURLOPTDEPRECATED(CURLOPT_KRBLEVEL, CURLOPTTYPE_STRINGPOINT, 63, + 8.17.0, "removed"), + + /* Set if we should verify the peer in SSL handshake, set 1 to verify. */ + CURLOPT(CURLOPT_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 64), + + /* The CApath or CAfile used to validate the peer certificate + this option is used only if SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_CAINFO, CURLOPTTYPE_STRINGPOINT, 65), + + /* 66 = OBSOLETE */ + /* 67 = OBSOLETE */ + + /* Maximum number of http redirects to follow */ + CURLOPT(CURLOPT_MAXREDIRS, CURLOPTTYPE_LONG, 68), + + /* Pass a long set to 1 to get the date of the requested document (if + possible)! Pass a zero to shut it off. */ + CURLOPT(CURLOPT_FILETIME, CURLOPTTYPE_LONG, 69), + + /* This points to a linked list of telnet options */ + CURLOPT(CURLOPT_TELNETOPTIONS, CURLOPTTYPE_SLISTPOINT, 70), + + /* Max amount of cached alive connections */ + CURLOPT(CURLOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 71), + + /* 72 = OBSOLETE */ + /* 73 = OBSOLETE */ + + /* Set to explicitly use a new connection for the upcoming transfer. + Do not use this unless you are absolutely sure of this, as it makes the + operation slower and is less friendly for the network. */ + CURLOPT(CURLOPT_FRESH_CONNECT, CURLOPTTYPE_LONG, 74), + + /* Set to explicitly forbid the upcoming transfer's connection to be reused + when done. Do not use this unless you are absolutely sure of this, as it + makes the operation slower and is less friendly for the network. */ + CURLOPT(CURLOPT_FORBID_REUSE, CURLOPTTYPE_LONG, 75), + + /* Set to a filename that contains random data for libcurl to use to + seed the random engine when doing SSL connects. */ + CURLOPTDEPRECATED(CURLOPT_RANDOM_FILE, CURLOPTTYPE_STRINGPOINT, 76, + 7.84.0, "Serves no purpose anymore"), + + /* Set to the Entropy Gathering Daemon socket pathname */ + CURLOPTDEPRECATED(CURLOPT_EGDSOCKET, CURLOPTTYPE_STRINGPOINT, 77, + 7.84.0, "Serves no purpose anymore"), + + /* Time-out connect operations after this amount of seconds, if connects are + OK within this time, then fine... This only aborts the connect phase. */ + CURLOPT(CURLOPT_CONNECTTIMEOUT, CURLOPTTYPE_LONG, 78), + + /* Function that is called to store headers (instead of fwrite). The + * parameters use fwrite() syntax, make sure to follow them. */ + CURLOPT(CURLOPT_HEADERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 79), + + /* Set this to force the HTTP request to get back to GET. Only really usable + if POST, PUT or a custom request have been used first. + */ + CURLOPT(CURLOPT_HTTPGET, CURLOPTTYPE_LONG, 80), + + /* Set if we should verify the Common name from the peer certificate in SSL + * handshake, set 1 to check existence, 2 to ensure that it matches the + * provided hostname. */ + CURLOPT(CURLOPT_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 81), + + /* Specify which filename to write all known cookies in after completed + operation. Set filename to "-" (dash) to make it go to stdout. */ + CURLOPT(CURLOPT_COOKIEJAR, CURLOPTTYPE_STRINGPOINT, 82), + + /* Specify which TLS 1.2 (1.1, 1.0) ciphers to use */ + CURLOPT(CURLOPT_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 83), + + /* Specify which HTTP version to use! This must be set to one of the + CURL_HTTP_VERSION* enums set below. */ + CURLOPT(CURLOPT_HTTP_VERSION, CURLOPTTYPE_VALUES, 84), + + /* Specifically switch on or off the FTP engine's use of the EPSV command. By + default, that one is always attempted before the more traditional + PASV command. */ + CURLOPT(CURLOPT_FTP_USE_EPSV, CURLOPTTYPE_LONG, 85), + + /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */ + CURLOPT(CURLOPT_SSLCERTTYPE, CURLOPTTYPE_STRINGPOINT, 86), + + /* name of the file keeping your private SSL-key */ + CURLOPT(CURLOPT_SSLKEY, CURLOPTTYPE_STRINGPOINT, 87), + + /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */ + CURLOPT(CURLOPT_SSLKEYTYPE, CURLOPTTYPE_STRINGPOINT, 88), + + /* crypto engine for the SSL-sub system */ + CURLOPT(CURLOPT_SSLENGINE, CURLOPTTYPE_STRINGPOINT, 89), + + /* set the crypto engine for the SSL-sub system as default + the param has no meaning... + */ + CURLOPT(CURLOPT_SSLENGINE_DEFAULT, CURLOPTTYPE_LONG, 90), + + /* Non-zero value means to use the global dns cache */ + /* DEPRECATED, do not use! */ + CURLOPTDEPRECATED(CURLOPT_DNS_USE_GLOBAL_CACHE, CURLOPTTYPE_LONG, 91, + 7.11.1, "Use CURLOPT_SHARE"), + + /* DNS cache timeout */ + CURLOPT(CURLOPT_DNS_CACHE_TIMEOUT, CURLOPTTYPE_LONG, 92), + + /* send linked-list of pre-transfer QUOTE commands */ + CURLOPT(CURLOPT_PREQUOTE, CURLOPTTYPE_SLISTPOINT, 93), + + /* set the debug function */ + CURLOPT(CURLOPT_DEBUGFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 94), + + /* set the data for the debug function */ + CURLOPT(CURLOPT_DEBUGDATA, CURLOPTTYPE_CBPOINT, 95), + + /* mark this as start of a cookie session */ + CURLOPT(CURLOPT_COOKIESESSION, CURLOPTTYPE_LONG, 96), + + /* The CApath directory used to validate the peer certificate + this option is used only if SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_CAPATH, CURLOPTTYPE_STRINGPOINT, 97), + + /* Instruct libcurl to use a smaller receive buffer */ + CURLOPT(CURLOPT_BUFFERSIZE, CURLOPTTYPE_LONG, 98), + + /* Instruct libcurl to not use any signal/alarm handlers, even when using + timeouts. This option is useful for multi-threaded applications. + See libcurl-the-guide for more background information. */ + CURLOPT(CURLOPT_NOSIGNAL, CURLOPTTYPE_LONG, 99), + + /* Provide a CURLShare for mutexing non-ts data */ + CURLOPT(CURLOPT_SHARE, CURLOPTTYPE_OBJECTPOINT, 100), + + /* indicates type of proxy. accepted values are CURLPROXY_HTTP (default), + CURLPROXY_HTTPS, CURLPROXY_HTTPS2, CURLPROXY_HTTPS3, CURLPROXY_SOCKS4, + CURLPROXY_SOCKS4A and CURLPROXY_SOCKS5. */ + CURLOPT(CURLOPT_PROXYTYPE, CURLOPTTYPE_VALUES, 101), + + /* Set the Accept-Encoding string. Use this to tell a server you would like + the response to be compressed. Before 7.21.6, this was known as + CURLOPT_ENCODING */ + CURLOPT(CURLOPT_ACCEPT_ENCODING, CURLOPTTYPE_STRINGPOINT, 102), + + /* Set pointer to private data */ + CURLOPT(CURLOPT_PRIVATE, CURLOPTTYPE_OBJECTPOINT, 103), + + /* Set aliases for HTTP 200 in the HTTP Response header */ + CURLOPT(CURLOPT_HTTP200ALIASES, CURLOPTTYPE_SLISTPOINT, 104), + + /* Continue to send authentication (user+password) when following locations, + even when hostname changed. This can potentially send off the name + and password to whatever host the server decides. */ + CURLOPT(CURLOPT_UNRESTRICTED_AUTH, CURLOPTTYPE_LONG, 105), + + /* Specifically switch on or off the FTP engine's use of the EPRT command ( + it also disables the LPRT attempt). By default, those ones are always + attempted before the good old traditional PORT command. */ + CURLOPT(CURLOPT_FTP_USE_EPRT, CURLOPTTYPE_LONG, 106), + + /* Set this to a bitmask value to enable the particular authentications + methods you like. Use this in combination with CURLOPT_USERPWD. + Note that setting multiple bits may cause extra network round-trips. */ + CURLOPT(CURLOPT_HTTPAUTH, CURLOPTTYPE_VALUES, 107), + + /* Set the SSL context callback function, currently only for OpenSSL or + wolfSSL ssl_ctx, or mbedTLS mbedtls_ssl_config in the second argument. + The function must match the curl_ssl_ctx_callback prototype. */ + CURLOPT(CURLOPT_SSL_CTX_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 108), + + /* Set the userdata for the SSL context callback function's third + argument */ + CURLOPT(CURLOPT_SSL_CTX_DATA, CURLOPTTYPE_CBPOINT, 109), + + /* FTP Option that causes missing dirs to be created on the remote server. + In 7.19.4 we introduced the convenience enums for this option using the + CURLFTP_CREATE_DIR prefix. */ + CURLOPT(CURLOPT_FTP_CREATE_MISSING_DIRS, CURLOPTTYPE_LONG, 110), + + /* Set this to a bitmask value to enable the particular authentications + methods you like. Use this in combination with CURLOPT_PROXYUSERPWD. + Note that setting multiple bits may cause extra network round-trips. */ + CURLOPT(CURLOPT_PROXYAUTH, CURLOPTTYPE_VALUES, 111), + + /* Option that changes the timeout, in seconds, associated with getting a + response. This is different from transfer timeout time and essentially + places a demand on the server to acknowledge commands in a timely + manner. For FTP, SMTP, IMAP and POP3. */ + CURLOPT(CURLOPT_SERVER_RESPONSE_TIMEOUT, CURLOPTTYPE_LONG, 112), + + /* Set this option to one of the CURL_IPRESOLVE_* defines (see below) to + tell libcurl to use those IP versions only. This only has effect on + systems with support for more than one, i.e IPv4 _and_ IPv6. */ + CURLOPT(CURLOPT_IPRESOLVE, CURLOPTTYPE_VALUES, 113), + + /* Set this option to limit the size of a file that is to be downloaded from + an HTTP or FTP server. + + Note there is also _LARGE version which adds large file support for + platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */ + CURLOPT(CURLOPT_MAXFILESIZE, CURLOPTTYPE_LONG, 114), + + /* See the comment for INFILESIZE above, but in short, specifies + * the size of the file being uploaded. -1 means unknown. + */ + CURLOPT(CURLOPT_INFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 115), + + /* Sets the continuation offset. There is also a CURLOPTTYPE_LONG version + * of this; look above for RESUME_FROM. + */ + CURLOPT(CURLOPT_RESUME_FROM_LARGE, CURLOPTTYPE_OFF_T, 116), + + /* Sets the maximum size of data that is to be downloaded from + * an HTTP or FTP server. See MAXFILESIZE above for the LONG version. + */ + CURLOPT(CURLOPT_MAXFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 117), + + /* Set this option to the filename of your .netrc file you want libcurl + to parse (using the CURLOPT_NETRC option). If not set, libcurl does + a poor attempt to find the user's home directory and check for a .netrc + file in there. */ + CURLOPT(CURLOPT_NETRC_FILE, CURLOPTTYPE_STRINGPOINT, 118), + + /* Enable SSL/TLS for FTP, pick one of: + CURLUSESSL_TRY - try using SSL, proceed anyway otherwise + CURLUSESSL_CONTROL - SSL for the control connection or fail + CURLUSESSL_ALL - SSL for all communication or fail + */ + CURLOPT(CURLOPT_USE_SSL, CURLOPTTYPE_VALUES, 119), + + /* The _LARGE version of the standard POSTFIELDSIZE option */ + CURLOPT(CURLOPT_POSTFIELDSIZE_LARGE, CURLOPTTYPE_OFF_T, 120), + + /* Enable/disable the TCP Nagle algorithm */ + CURLOPT(CURLOPT_TCP_NODELAY, CURLOPTTYPE_LONG, 121), + + /* 122 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ + /* 123 OBSOLETE. Gone in 7.16.0 */ + /* 124 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ + /* 125 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ + /* 126 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ + /* 127 OBSOLETE. Gone in 7.16.0 */ + /* 128 OBSOLETE. Gone in 7.16.0 */ + + /* When FTP over SSL/TLS is selected (with CURLOPT_USE_SSL), this option + can be used to change libcurl's default action which is to first try + "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK + response has been received. + + Available parameters are: + CURLFTPAUTH_DEFAULT - let libcurl decide + CURLFTPAUTH_SSL - try "AUTH SSL" first, then TLS + CURLFTPAUTH_TLS - try "AUTH TLS" first, then SSL + */ + CURLOPT(CURLOPT_FTPSSLAUTH, CURLOPTTYPE_VALUES, 129), + + CURLOPTDEPRECATED(CURLOPT_IOCTLFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 130, + 7.18.0, "Use CURLOPT_SEEKFUNCTION"), + CURLOPTDEPRECATED(CURLOPT_IOCTLDATA, CURLOPTTYPE_CBPOINT, 131, + 7.18.0, "Use CURLOPT_SEEKDATA"), + + /* 132 OBSOLETE. Gone in 7.16.0 */ + /* 133 OBSOLETE. Gone in 7.16.0 */ + + /* null-terminated string for pass on to the FTP server when asked for + "account" info */ + CURLOPT(CURLOPT_FTP_ACCOUNT, CURLOPTTYPE_STRINGPOINT, 134), + + /* feed cookie into cookie engine */ + CURLOPT(CURLOPT_COOKIELIST, CURLOPTTYPE_STRINGPOINT, 135), + + /* ignore Content-Length */ + CURLOPT(CURLOPT_IGNORE_CONTENT_LENGTH, CURLOPTTYPE_LONG, 136), + + /* Set to non-zero to skip the IP address received in a 227 PASV FTP server + response. Typically used for FTP-SSL purposes but is not restricted to + that. libcurl is then instead using the same IP address it used for the + control connection. */ + CURLOPT(CURLOPT_FTP_SKIP_PASV_IP, CURLOPTTYPE_LONG, 137), + + /* Select "file method" to use when doing FTP, see the curl_ftpmethod + above. */ + CURLOPT(CURLOPT_FTP_FILEMETHOD, CURLOPTTYPE_VALUES, 138), + + /* Local port number to bind the socket to */ + CURLOPT(CURLOPT_LOCALPORT, CURLOPTTYPE_LONG, 139), + + /* Number of ports to try, including the first one set with LOCALPORT. + Thus, setting it to 1 makes no additional attempts but the first. */ + CURLOPT(CURLOPT_LOCALPORTRANGE, CURLOPTTYPE_LONG, 140), + + /* no transfer, set up connection and let application use the socket by + extracting it with CURLINFO_LASTSOCKET */ + CURLOPT(CURLOPT_CONNECT_ONLY, CURLOPTTYPE_LONG, 141), + + /* Function that is called to convert from the + network encoding (instead of using the iconv calls in libcurl) */ + CURLOPTDEPRECATED(CURLOPT_CONV_FROM_NETWORK_FUNCTION, + CURLOPTTYPE_FUNCTIONPOINT, 142, + 7.82.0, "Serves no purpose anymore"), + + /* Function that is called to convert to the + network encoding (instead of using the iconv calls in libcurl) */ + CURLOPTDEPRECATED(CURLOPT_CONV_TO_NETWORK_FUNCTION, + CURLOPTTYPE_FUNCTIONPOINT, 143, + 7.82.0, "Serves no purpose anymore"), + + /* Function that is called to convert from UTF8 + (instead of using the iconv calls in libcurl) + Note that this is used only for SSL certificate processing */ + CURLOPTDEPRECATED(CURLOPT_CONV_FROM_UTF8_FUNCTION, + CURLOPTTYPE_FUNCTIONPOINT, 144, + 7.82.0, "Serves no purpose anymore"), + + /* if the connection proceeds too quickly then need to slow it down */ + /* limit-rate: maximum number of bytes per second to send or receive */ + CURLOPT(CURLOPT_MAX_SEND_SPEED_LARGE, CURLOPTTYPE_OFF_T, 145), + CURLOPT(CURLOPT_MAX_RECV_SPEED_LARGE, CURLOPTTYPE_OFF_T, 146), + + /* Pointer to command string to send if USER/PASS fails. */ + CURLOPT(CURLOPT_FTP_ALTERNATIVE_TO_USER, CURLOPTTYPE_STRINGPOINT, 147), + + /* callback function for setting socket options */ + CURLOPT(CURLOPT_SOCKOPTFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 148), + CURLOPT(CURLOPT_SOCKOPTDATA, CURLOPTTYPE_CBPOINT, 149), + + /* set to 0 to disable session ID reuse for this transfer, default is + enabled (== 1) */ + CURLOPT(CURLOPT_SSL_SESSIONID_CACHE, CURLOPTTYPE_LONG, 150), + + /* allowed SSH authentication methods */ + CURLOPT(CURLOPT_SSH_AUTH_TYPES, CURLOPTTYPE_VALUES, 151), + + /* Used by scp/sftp to do public/private key authentication */ + CURLOPT(CURLOPT_SSH_PUBLIC_KEYFILE, CURLOPTTYPE_STRINGPOINT, 152), + CURLOPT(CURLOPT_SSH_PRIVATE_KEYFILE, CURLOPTTYPE_STRINGPOINT, 153), + + /* Send CCC (Clear Command Channel) after authentication */ + CURLOPT(CURLOPT_FTP_SSL_CCC, CURLOPTTYPE_LONG, 154), + + /* Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution */ + CURLOPT(CURLOPT_TIMEOUT_MS, CURLOPTTYPE_LONG, 155), + CURLOPT(CURLOPT_CONNECTTIMEOUT_MS, CURLOPTTYPE_LONG, 156), + + /* set to zero to disable the libcurl's decoding and thus pass the raw body + data to the application even when it is encoded/compressed */ + CURLOPT(CURLOPT_HTTP_TRANSFER_DECODING, CURLOPTTYPE_LONG, 157), + CURLOPT(CURLOPT_HTTP_CONTENT_DECODING, CURLOPTTYPE_LONG, 158), + + /* Permission used when creating new files and directories on the remote + server for protocols that support it, SFTP/SCP/FILE */ + CURLOPT(CURLOPT_NEW_FILE_PERMS, CURLOPTTYPE_LONG, 159), + CURLOPT(CURLOPT_NEW_DIRECTORY_PERMS, CURLOPTTYPE_LONG, 160), + + /* Set the behavior of POST when redirecting. Values must be set to one + of CURL_REDIR* defines below. This used to be called CURLOPT_POST301 */ + CURLOPT(CURLOPT_POSTREDIR, CURLOPTTYPE_VALUES, 161), + + /* used by scp/sftp to verify the host's public key */ + CURLOPT(CURLOPT_SSH_HOST_PUBLIC_KEY_MD5, CURLOPTTYPE_STRINGPOINT, 162), + + /* Callback function for opening socket (instead of socket(2)). Optionally, + callback is able change the address or refuse to connect returning + CURL_SOCKET_BAD. The callback should have type + curl_opensocket_callback */ + CURLOPT(CURLOPT_OPENSOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 163), + CURLOPT(CURLOPT_OPENSOCKETDATA, CURLOPTTYPE_CBPOINT, 164), + + /* POST volatile input fields. */ + CURLOPT(CURLOPT_COPYPOSTFIELDS, CURLOPTTYPE_OBJECTPOINT, 165), + + /* set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy */ + CURLOPT(CURLOPT_PROXY_TRANSFER_MODE, CURLOPTTYPE_LONG, 166), + + /* Callback function for seeking in the input stream */ + CURLOPT(CURLOPT_SEEKFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 167), + CURLOPT(CURLOPT_SEEKDATA, CURLOPTTYPE_CBPOINT, 168), + + /* CRL file */ + CURLOPT(CURLOPT_CRLFILE, CURLOPTTYPE_STRINGPOINT, 169), + + /* Issuer certificate */ + CURLOPT(CURLOPT_ISSUERCERT, CURLOPTTYPE_STRINGPOINT, 170), + + /* (IPv6) Address scope */ + CURLOPT(CURLOPT_ADDRESS_SCOPE, CURLOPTTYPE_LONG, 171), + + /* Collect certificate chain info and allow it to get retrievable with + CURLINFO_CERTINFO after the transfer is complete. */ + CURLOPT(CURLOPT_CERTINFO, CURLOPTTYPE_LONG, 172), + + /* "name" and "pwd" to use when fetching. */ + CURLOPT(CURLOPT_USERNAME, CURLOPTTYPE_STRINGPOINT, 173), + CURLOPT(CURLOPT_PASSWORD, CURLOPTTYPE_STRINGPOINT, 174), + + /* "name" and "pwd" to use with Proxy when fetching. */ + CURLOPT(CURLOPT_PROXYUSERNAME, CURLOPTTYPE_STRINGPOINT, 175), + CURLOPT(CURLOPT_PROXYPASSWORD, CURLOPTTYPE_STRINGPOINT, 176), + + /* Comma separated list of hostnames defining no-proxy zones. These should + match both hostnames directly, and hostnames within a domain. For + example, local.com matches local.com and www.local.com, but NOT + notlocal.com or www.notlocal.com. For compatibility with other + implementations of this, .local.com is considered to be the same as + local.com. A single * is the only valid wildcard, and effectively + disables the use of proxy. */ + CURLOPT(CURLOPT_NOPROXY, CURLOPTTYPE_STRINGPOINT, 177), + + /* block size for TFTP transfers */ + CURLOPT(CURLOPT_TFTP_BLKSIZE, CURLOPTTYPE_LONG, 178), + + /* Socks Service */ + /* DEPRECATED, do not use! */ + CURLOPTDEPRECATED(CURLOPT_SOCKS5_GSSAPI_SERVICE, + CURLOPTTYPE_STRINGPOINT, 179, + 7.49.0, "Use CURLOPT_PROXY_SERVICE_NAME"), + + /* Socks Service */ + CURLOPT(CURLOPT_SOCKS5_GSSAPI_NEC, CURLOPTTYPE_LONG, 180), + + /* set the bitmask for the protocols that are allowed to be used for the + transfer, which thus helps the app which takes URLs from users or other + external inputs and want to restrict what protocol(s) to deal + with. Defaults to CURLPROTO_ALL. */ + CURLOPTDEPRECATED(CURLOPT_PROTOCOLS, CURLOPTTYPE_LONG, 181, + 7.85.0, "Use CURLOPT_PROTOCOLS_STR"), + + /* set the bitmask for the protocols that libcurl is allowed to follow to, + as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs + to be set in both bitmasks to be allowed to get redirected to. */ + CURLOPTDEPRECATED(CURLOPT_REDIR_PROTOCOLS, CURLOPTTYPE_LONG, 182, + 7.85.0, "Use CURLOPT_REDIR_PROTOCOLS_STR"), + + /* set the SSH knownhost filename to use */ + CURLOPT(CURLOPT_SSH_KNOWNHOSTS, CURLOPTTYPE_STRINGPOINT, 183), + + /* set the SSH host key callback, must point to a curl_sshkeycallback + function */ + CURLOPT(CURLOPT_SSH_KEYFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 184), + + /* set the SSH host key callback custom pointer */ + CURLOPT(CURLOPT_SSH_KEYDATA, CURLOPTTYPE_CBPOINT, 185), + + /* set the SMTP mail originator */ + CURLOPT(CURLOPT_MAIL_FROM, CURLOPTTYPE_STRINGPOINT, 186), + + /* set the list of SMTP mail receiver(s) */ + CURLOPT(CURLOPT_MAIL_RCPT, CURLOPTTYPE_SLISTPOINT, 187), + + /* FTP: send PRET before PASV */ + CURLOPT(CURLOPT_FTP_USE_PRET, CURLOPTTYPE_LONG, 188), + + /* RTSP request method (OPTIONS, SETUP, PLAY, etc...) */ + CURLOPT(CURLOPT_RTSP_REQUEST, CURLOPTTYPE_VALUES, 189), + + /* The RTSP session identifier */ + CURLOPT(CURLOPT_RTSP_SESSION_ID, CURLOPTTYPE_STRINGPOINT, 190), + + /* The RTSP stream URI */ + CURLOPT(CURLOPT_RTSP_STREAM_URI, CURLOPTTYPE_STRINGPOINT, 191), + + /* The Transport: header to use in RTSP requests */ + CURLOPT(CURLOPT_RTSP_TRANSPORT, CURLOPTTYPE_STRINGPOINT, 192), + + /* Manually initialize the client RTSP CSeq for this handle */ + CURLOPT(CURLOPT_RTSP_CLIENT_CSEQ, CURLOPTTYPE_LONG, 193), + + /* Manually initialize the server RTSP CSeq for this handle */ + CURLOPT(CURLOPT_RTSP_SERVER_CSEQ, CURLOPTTYPE_LONG, 194), + + /* The stream to pass to INTERLEAVEFUNCTION. */ + CURLOPT(CURLOPT_INTERLEAVEDATA, CURLOPTTYPE_CBPOINT, 195), + + /* Let the application define a custom write method for RTP data */ + CURLOPT(CURLOPT_INTERLEAVEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 196), + + /* Turn on wildcard matching */ + CURLOPT(CURLOPT_WILDCARDMATCH, CURLOPTTYPE_LONG, 197), + + /* Directory matching callback called before downloading of an + individual file (chunk) started */ + CURLOPT(CURLOPT_CHUNK_BGN_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 198), + + /* Directory matching callback called after the file (chunk) + was downloaded, or skipped */ + CURLOPT(CURLOPT_CHUNK_END_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 199), + + /* Change match (fnmatch-like) callback for wildcard matching */ + CURLOPT(CURLOPT_FNMATCH_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 200), + + /* Let the application define custom chunk data pointer */ + CURLOPT(CURLOPT_CHUNK_DATA, CURLOPTTYPE_CBPOINT, 201), + + /* FNMATCH_FUNCTION user pointer */ + CURLOPT(CURLOPT_FNMATCH_DATA, CURLOPTTYPE_CBPOINT, 202), + + /* send linked-list of name:port:address sets */ + CURLOPT(CURLOPT_RESOLVE, CURLOPTTYPE_SLISTPOINT, 203), + + /* Set a username for authenticated TLS */ + CURLOPTDEPRECATED(CURLOPT_TLSAUTH_USERNAME, CURLOPTTYPE_STRINGPOINT, 204, + 8.22.0, "Support was removed"), + + /* Set a password for authenticated TLS */ + CURLOPTDEPRECATED(CURLOPT_TLSAUTH_PASSWORD, CURLOPTTYPE_STRINGPOINT, 205, + 8.22.0, "Support was removed"), + + /* Set authentication type for authenticated TLS */ + CURLOPTDEPRECATED(CURLOPT_TLSAUTH_TYPE, CURLOPTTYPE_STRINGPOINT, 206, + 8.22.0, "Support was removed"), + + /* Set to 1 to enable the "TE:" header in HTTP requests to ask for + compressed transfer-encoded responses. Set to 0 to disable the use of TE: + in outgoing requests. The current default is 0, but it might change in a + future libcurl release. + + libcurl asks for the compressed methods it knows of, and if that + is not any, it does not ask for transfer-encoding at all even if this + option is set to 1. */ + CURLOPT(CURLOPT_TRANSFER_ENCODING, CURLOPTTYPE_LONG, 207), + + /* Callback function for closing socket (instead of close(2)). The callback + should have type curl_closesocket_callback */ + CURLOPT(CURLOPT_CLOSESOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 208), + CURLOPT(CURLOPT_CLOSESOCKETDATA, CURLOPTTYPE_CBPOINT, 209), + + /* allow GSSAPI credential delegation */ + CURLOPT(CURLOPT_GSSAPI_DELEGATION, CURLOPTTYPE_VALUES, 210), + + /* Set the name servers to use for DNS resolution. + * Only supported by the c-ares DNS backend */ + CURLOPT(CURLOPT_DNS_SERVERS, CURLOPTTYPE_STRINGPOINT, 211), + + /* Time-out accept operations (currently for FTP only) after this amount + of milliseconds. */ + CURLOPT(CURLOPT_ACCEPTTIMEOUT_MS, CURLOPTTYPE_LONG, 212), + + /* Set TCP keepalive */ + CURLOPT(CURLOPT_TCP_KEEPALIVE, CURLOPTTYPE_LONG, 213), + + /* non-universal keepalive knobs (Linux, AIX, HP-UX, more) */ + CURLOPT(CURLOPT_TCP_KEEPIDLE, CURLOPTTYPE_LONG, 214), + CURLOPT(CURLOPT_TCP_KEEPINTVL, CURLOPTTYPE_LONG, 215), + + /* Enable/disable specific SSL features with a bitmask, see CURLSSLOPT_* */ + CURLOPT(CURLOPT_SSL_OPTIONS, CURLOPTTYPE_VALUES, 216), + + /* Set the SMTP auth originator */ + CURLOPT(CURLOPT_MAIL_AUTH, CURLOPTTYPE_STRINGPOINT, 217), + + /* Enable/disable SASL initial response */ + CURLOPT(CURLOPT_SASL_IR, CURLOPTTYPE_LONG, 218), + + /* Function that is called instead of the internal progress display + * function. This function should be defined as the curl_xferinfo_callback + * prototype defines. (Deprecates CURLOPT_PROGRESSFUNCTION) */ + CURLOPT(CURLOPT_XFERINFOFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 219), + + /* The XOAUTH2 bearer token */ + CURLOPT(CURLOPT_XOAUTH2_BEARER, CURLOPTTYPE_STRINGPOINT, 220), + + /* Set the interface string to use as outgoing network + * interface for DNS requests. + * Only supported by the c-ares DNS backend */ + CURLOPT(CURLOPT_DNS_INTERFACE, CURLOPTTYPE_STRINGPOINT, 221), + + /* Set the local IPv4 address to use for outgoing DNS requests. + * Only supported by the c-ares DNS backend */ + CURLOPT(CURLOPT_DNS_LOCAL_IP4, CURLOPTTYPE_STRINGPOINT, 222), + + /* Set the local IPv6 address to use for outgoing DNS requests. + * Only supported by the c-ares DNS backend */ + CURLOPT(CURLOPT_DNS_LOCAL_IP6, CURLOPTTYPE_STRINGPOINT, 223), + + /* Set authentication options directly */ + CURLOPT(CURLOPT_LOGIN_OPTIONS, CURLOPTTYPE_STRINGPOINT, 224), + + /* Enable/disable TLS NPN extension (http2 over SSL might fail without) */ + CURLOPTDEPRECATED(CURLOPT_SSL_ENABLE_NPN, CURLOPTTYPE_LONG, 225, + 7.86.0, "Has no function"), + + /* Enable/disable TLS ALPN extension (http2 over SSL might fail without) */ + CURLOPT(CURLOPT_SSL_ENABLE_ALPN, CURLOPTTYPE_LONG, 226), + + /* Time to wait for a response to an HTTP request containing an + * Expect: 100-continue header before sending the data anyway. */ + CURLOPT(CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOPTTYPE_LONG, 227), + + /* This points to a linked list of headers used for proxy requests only, + struct curl_slist kind */ + CURLOPT(CURLOPT_PROXYHEADER, CURLOPTTYPE_SLISTPOINT, 228), + + /* Pass in a bitmask of "header options" */ + CURLOPT(CURLOPT_HEADEROPT, CURLOPTTYPE_VALUES, 229), + + /* The public key used to validate the peer public key */ + CURLOPT(CURLOPT_PINNEDPUBLICKEY, CURLOPTTYPE_STRINGPOINT, 230), + + /* Path to Unix domain socket */ + CURLOPT(CURLOPT_UNIX_SOCKET_PATH, CURLOPTTYPE_STRINGPOINT, 231), + + /* Set if we should verify the certificate status. */ + CURLOPT(CURLOPT_SSL_VERIFYSTATUS, CURLOPTTYPE_LONG, 232), + + /* Set if we should enable TLS false start. */ + CURLOPTDEPRECATED(CURLOPT_SSL_FALSESTART, CURLOPTTYPE_LONG, 233, + 8.15.0, "Has no function"), + + /* Do not squash dot-dot sequences */ + CURLOPT(CURLOPT_PATH_AS_IS, CURLOPTTYPE_LONG, 234), + + /* Proxy Service Name */ + CURLOPT(CURLOPT_PROXY_SERVICE_NAME, CURLOPTTYPE_STRINGPOINT, 235), + + /* Service Name */ + CURLOPT(CURLOPT_SERVICE_NAME, CURLOPTTYPE_STRINGPOINT, 236), + + /* Wait/do not wait for pipe/mutex to clarify */ + CURLOPT(CURLOPT_PIPEWAIT, CURLOPTTYPE_LONG, 237), + + /* Set the protocol used when curl is given a URL without a protocol */ + CURLOPT(CURLOPT_DEFAULT_PROTOCOL, CURLOPTTYPE_STRINGPOINT, 238), + + /* Set stream weight, 1 - 256 (default is 16) */ + CURLOPT(CURLOPT_STREAM_WEIGHT, CURLOPTTYPE_LONG, 239), + + /* Set stream dependency on another curl handle */ + CURLOPTDEPRECATED(CURLOPT_STREAM_DEPENDS, CURLOPTTYPE_OBJECTPOINT, 240, + 8.21.0, "Has no function"), + + /* Set E-xclusive stream dependency on another curl handle */ + CURLOPTDEPRECATED(CURLOPT_STREAM_DEPENDS_E, CURLOPTTYPE_OBJECTPOINT, 241, + 8.21.0, "Has no function"), + + /* Do not send any tftp option requests to the server */ + CURLOPT(CURLOPT_TFTP_NO_OPTIONS, CURLOPTTYPE_LONG, 242), + + /* Linked-list of host:port:connect-to-host:connect-to-port, + overrides the URL's host:port (only for the network layer) */ + CURLOPT(CURLOPT_CONNECT_TO, CURLOPTTYPE_SLISTPOINT, 243), + + /* Set TCP Fast Open */ + CURLOPT(CURLOPT_TCP_FASTOPEN, CURLOPTTYPE_LONG, 244), + + /* Continue to send data if the server responds early with an + * HTTP status code >= 300 */ + CURLOPT(CURLOPT_KEEP_SENDING_ON_ERROR, CURLOPTTYPE_LONG, 245), + + /* The CApath or CAfile used to validate the proxy certificate + this option is used only if PROXY_SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_PROXY_CAINFO, CURLOPTTYPE_STRINGPOINT, 246), + + /* The CApath directory used to validate the proxy certificate + this option is used only if PROXY_SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_PROXY_CAPATH, CURLOPTTYPE_STRINGPOINT, 247), + + /* Set if we should verify the proxy in SSL handshake, + set 1 to verify. */ + CURLOPT(CURLOPT_PROXY_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 248), + + /* Set if we should verify the Common name from the proxy certificate in SSL + * handshake, set 1 to check existence, 2 to ensure that it matches + * the provided hostname. */ + CURLOPT(CURLOPT_PROXY_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 249), + + /* What version to specifically try to use for proxy. + See CURL_SSLVERSION defines below. */ + CURLOPT(CURLOPT_PROXY_SSLVERSION, CURLOPTTYPE_VALUES, 250), + + /* Set a username for authenticated TLS for proxy */ + CURLOPTDEPRECATED(CURLOPT_PROXY_TLSAUTH_USERNAME, CURLOPTTYPE_STRINGPOINT, + 251, 8.22.0, "Support was removed"), + + /* Set a password for authenticated TLS for proxy */ + CURLOPTDEPRECATED(CURLOPT_PROXY_TLSAUTH_PASSWORD, CURLOPTTYPE_STRINGPOINT, + 252, 8.22.0, "Support was removed"), + + /* Set authentication type for authenticated TLS for proxy */ + CURLOPTDEPRECATED(CURLOPT_PROXY_TLSAUTH_TYPE, CURLOPTTYPE_STRINGPOINT, 253, + 8.22.0, "Support was removed"), + + /* name of the file keeping your private SSL-certificate for proxy */ + CURLOPT(CURLOPT_PROXY_SSLCERT, CURLOPTTYPE_STRINGPOINT, 254), + + /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") for + proxy */ + CURLOPT(CURLOPT_PROXY_SSLCERTTYPE, CURLOPTTYPE_STRINGPOINT, 255), + + /* name of the file keeping your private SSL-key for proxy */ + CURLOPT(CURLOPT_PROXY_SSLKEY, CURLOPTTYPE_STRINGPOINT, 256), + + /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") for + proxy */ + CURLOPT(CURLOPT_PROXY_SSLKEYTYPE, CURLOPTTYPE_STRINGPOINT, 257), + + /* password for the SSL private key for proxy */ + CURLOPT(CURLOPT_PROXY_KEYPASSWD, CURLOPTTYPE_STRINGPOINT, 258), + + /* Specify which TLS 1.2 (1.1, 1.0) ciphers to use for proxy */ + CURLOPT(CURLOPT_PROXY_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 259), + + /* CRL file for proxy */ + CURLOPT(CURLOPT_PROXY_CRLFILE, CURLOPTTYPE_STRINGPOINT, 260), + + /* Enable/disable specific SSL features with a bitmask for proxy, see + CURLSSLOPT_* */ + CURLOPT(CURLOPT_PROXY_SSL_OPTIONS, CURLOPTTYPE_LONG, 261), + + /* Name of pre proxy to use. */ + CURLOPT(CURLOPT_PRE_PROXY, CURLOPTTYPE_STRINGPOINT, 262), + + /* The public key in DER form used to validate the proxy public key + this option is used only if PROXY_SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_PROXY_PINNEDPUBLICKEY, CURLOPTTYPE_STRINGPOINT, 263), + + /* Path to an abstract Unix domain socket */ + CURLOPT(CURLOPT_ABSTRACT_UNIX_SOCKET, CURLOPTTYPE_STRINGPOINT, 264), + + /* Suppress proxy CONNECT response headers from user callbacks */ + CURLOPT(CURLOPT_SUPPRESS_CONNECT_HEADERS, CURLOPTTYPE_LONG, 265), + + /* The request target, instead of extracted from the URL */ + CURLOPT(CURLOPT_REQUEST_TARGET, CURLOPTTYPE_STRINGPOINT, 266), + + /* bitmask of allowed auth methods for connections to SOCKS5 proxies */ + CURLOPT(CURLOPT_SOCKS5_AUTH, CURLOPTTYPE_LONG, 267), + + /* Enable/disable SSH compression */ + CURLOPT(CURLOPT_SSH_COMPRESSION, CURLOPTTYPE_LONG, 268), + + /* Post MIME data. */ + CURLOPT(CURLOPT_MIMEPOST, CURLOPTTYPE_OBJECTPOINT, 269), + + /* Time to use with the CURLOPT_TIMECONDITION. Specified in number of + seconds since 1 Jan 1970. */ + CURLOPT(CURLOPT_TIMEVALUE_LARGE, CURLOPTTYPE_OFF_T, 270), + + /* Head start in milliseconds to give happy eyeballs. */ + CURLOPT(CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, CURLOPTTYPE_LONG, 271), + + /* Function that is called before a resolver request is made */ + CURLOPT(CURLOPT_RESOLVER_START_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 272), + + /* User data to pass to the resolver start callback. */ + CURLOPT(CURLOPT_RESOLVER_START_DATA, CURLOPTTYPE_CBPOINT, 273), + + /* send HAProxy PROXY protocol header? */ + CURLOPT(CURLOPT_HAPROXYPROTOCOL, CURLOPTTYPE_LONG, 274), + + /* shuffle addresses before use when DNS returns multiple */ + CURLOPT(CURLOPT_DNS_SHUFFLE_ADDRESSES, CURLOPTTYPE_LONG, 275), + + /* Specify which TLS 1.3 ciphers suites to use */ + CURLOPT(CURLOPT_TLS13_CIPHERS, CURLOPTTYPE_STRINGPOINT, 276), + CURLOPT(CURLOPT_PROXY_TLS13_CIPHERS, CURLOPTTYPE_STRINGPOINT, 277), + + /* Disallow specifying username/login in URL. */ + CURLOPT(CURLOPT_DISALLOW_USERNAME_IN_URL, CURLOPTTYPE_LONG, 278), + + /* DNS-over-HTTPS URL */ + CURLOPT(CURLOPT_DOH_URL, CURLOPTTYPE_STRINGPOINT, 279), + + /* Preferred buffer size to use for uploads */ + CURLOPT(CURLOPT_UPLOAD_BUFFERSIZE, CURLOPTTYPE_LONG, 280), + + /* Time in ms between connection upkeep calls for long-lived connections. */ + CURLOPT(CURLOPT_UPKEEP_INTERVAL_MS, CURLOPTTYPE_LONG, 281), + + /* Specify URL using CURL URL API. */ + CURLOPT(CURLOPT_CURLU, CURLOPTTYPE_OBJECTPOINT, 282), + + /* add trailing data after no more data is available */ + CURLOPT(CURLOPT_TRAILERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 283), + + /* pointer to be passed to HTTP_TRAILER_FUNCTION */ + CURLOPT(CURLOPT_TRAILERDATA, CURLOPTTYPE_CBPOINT, 284), + + /* set this to 1L to allow HTTP/0.9 responses or 0L to disallow */ + CURLOPT(CURLOPT_HTTP09_ALLOWED, CURLOPTTYPE_LONG, 285), + + /* alt-svc control bitmask */ + CURLOPT(CURLOPT_ALTSVC_CTRL, CURLOPTTYPE_LONG, 286), + + /* alt-svc cache filename to possibly read from/write to */ + CURLOPT(CURLOPT_ALTSVC, CURLOPTTYPE_STRINGPOINT, 287), + + /* maximum age (idle time) of a connection to consider it for reuse + * (in seconds) */ + CURLOPT(CURLOPT_MAXAGE_CONN, CURLOPTTYPE_LONG, 288), + + /* SASL authorization identity */ + CURLOPT(CURLOPT_SASL_AUTHZID, CURLOPTTYPE_STRINGPOINT, 289), + + /* allow RCPT TO command to fail for some recipients */ + CURLOPT(CURLOPT_MAIL_RCPT_ALLOWFAILS, CURLOPTTYPE_LONG, 290), + + /* the private SSL-certificate as a "blob" */ + CURLOPT(CURLOPT_SSLCERT_BLOB, CURLOPTTYPE_BLOB, 291), + CURLOPT(CURLOPT_SSLKEY_BLOB, CURLOPTTYPE_BLOB, 292), + CURLOPT(CURLOPT_PROXY_SSLCERT_BLOB, CURLOPTTYPE_BLOB, 293), + CURLOPT(CURLOPT_PROXY_SSLKEY_BLOB, CURLOPTTYPE_BLOB, 294), + CURLOPT(CURLOPT_ISSUERCERT_BLOB, CURLOPTTYPE_BLOB, 295), + + /* Issuer certificate for proxy */ + CURLOPT(CURLOPT_PROXY_ISSUERCERT, CURLOPTTYPE_STRINGPOINT, 296), + CURLOPT(CURLOPT_PROXY_ISSUERCERT_BLOB, CURLOPTTYPE_BLOB, 297), + + /* the EC curves requested by the TLS client (RFC 8422, 5.1); + * OpenSSL support via 'set_groups'/'set_curves': + * https://docs.openssl.org/master/man3/SSL_CTX_set1_curves/ + */ + CURLOPT(CURLOPT_SSL_EC_CURVES, CURLOPTTYPE_STRINGPOINT, 298), + + /* HSTS bitmask */ + CURLOPT(CURLOPT_HSTS_CTRL, CURLOPTTYPE_LONG, 299), + /* HSTS filename */ + CURLOPT(CURLOPT_HSTS, CURLOPTTYPE_STRINGPOINT, 300), + + /* HSTS read callback */ + CURLOPT(CURLOPT_HSTSREADFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 301), + CURLOPT(CURLOPT_HSTSREADDATA, CURLOPTTYPE_CBPOINT, 302), + + /* HSTS write callback */ + CURLOPT(CURLOPT_HSTSWRITEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 303), + CURLOPT(CURLOPT_HSTSWRITEDATA, CURLOPTTYPE_CBPOINT, 304), + + /* Parameters for V4 signature */ + CURLOPT(CURLOPT_AWS_SIGV4, CURLOPTTYPE_STRINGPOINT, 305), + + /* Same as CURLOPT_SSL_VERIFYPEER but for DoH (DNS-over-HTTPS) servers. */ + CURLOPT(CURLOPT_DOH_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 306), + + /* Same as CURLOPT_SSL_VERIFYHOST but for DoH (DNS-over-HTTPS) servers. */ + CURLOPT(CURLOPT_DOH_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 307), + + /* Same as CURLOPT_SSL_VERIFYSTATUS but for DoH (DNS-over-HTTPS) servers. */ + CURLOPT(CURLOPT_DOH_SSL_VERIFYSTATUS, CURLOPTTYPE_LONG, 308), + + /* The CA certificates as "blob" used to validate the peer certificate + this option is used only if SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_CAINFO_BLOB, CURLOPTTYPE_BLOB, 309), + + /* The CA certificates as "blob" used to validate the proxy certificate + this option is used only if PROXY_SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_PROXY_CAINFO_BLOB, CURLOPTTYPE_BLOB, 310), + + /* used by scp/sftp to verify the host's public key */ + CURLOPT(CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256, CURLOPTTYPE_STRINGPOINT, 311), + + /* Function that is called immediately before the initial request + is made on a connection (after any protocol negotiation step). */ + CURLOPT(CURLOPT_PREREQFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 312), + + /* Data passed to the CURLOPT_PREREQFUNCTION callback */ + CURLOPT(CURLOPT_PREREQDATA, CURLOPTTYPE_CBPOINT, 313), + + /* maximum age (since creation) of a connection to consider it for reuse + * (in seconds) */ + CURLOPT(CURLOPT_MAXLIFETIME_CONN, CURLOPTTYPE_LONG, 314), + + /* Set MIME option flags. */ + CURLOPT(CURLOPT_MIME_OPTIONS, CURLOPTTYPE_LONG, 315), + + /* set the SSH host key callback, must point to a curl_sshkeycallback + function */ + CURLOPT(CURLOPT_SSH_HOSTKEYFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 316), + + /* set the SSH host key callback custom pointer */ + CURLOPT(CURLOPT_SSH_HOSTKEYDATA, CURLOPTTYPE_CBPOINT, 317), + + /* specify which protocols that are allowed to be used for the transfer, + which thus helps the app which takes URLs from users or other external + inputs and want to restrict what protocol(s) to deal with. Defaults to + all built-in protocols. */ + CURLOPT(CURLOPT_PROTOCOLS_STR, CURLOPTTYPE_STRINGPOINT, 318), + + /* specify which protocols that libcurl is allowed to follow directs to */ + CURLOPT(CURLOPT_REDIR_PROTOCOLS_STR, CURLOPTTYPE_STRINGPOINT, 319), + + /* WebSockets options */ + CURLOPT(CURLOPT_WS_OPTIONS, CURLOPTTYPE_LONG, 320), + + /* CA cache timeout */ + CURLOPT(CURLOPT_CA_CACHE_TIMEOUT, CURLOPTTYPE_LONG, 321), + + /* Can leak things, gonna exit() soon */ + CURLOPT(CURLOPT_QUICK_EXIT, CURLOPTTYPE_LONG, 322), + + /* set a specific client IP for HAProxy PROXY protocol header? */ + CURLOPT(CURLOPT_HAPROXY_CLIENT_IP, CURLOPTTYPE_STRINGPOINT, 323), + + /* millisecond version */ + CURLOPT(CURLOPT_SERVER_RESPONSE_TIMEOUT_MS, CURLOPTTYPE_LONG, 324), + + /* set ECH configuration */ + CURLOPT(CURLOPT_ECH, CURLOPTTYPE_STRINGPOINT, 325), + + /* maximum number of keepalive probes (Linux, *BSD, macOS, etc.) */ + CURLOPT(CURLOPT_TCP_KEEPCNT, CURLOPTTYPE_LONG, 326), + + CURLOPT(CURLOPT_UPLOAD_FLAGS, CURLOPTTYPE_LONG, 327), + + /* set TLS supported signature algorithms */ + CURLOPT(CURLOPT_SSL_SIGNATURE_ALGORITHMS, CURLOPTTYPE_STRINGPOINT, 328), + + /* RFC 9421 HTTP Message Signatures algorithm */ + CURLOPT(CURLOPT_HTTPSIG_ALGORITHM, CURLOPTTYPE_VALUES, 329), + + /* Hex-encoded key for HTTP Message Signatures */ + CURLOPT(CURLOPT_HTTPSIG_KEY, CURLOPTTYPE_STRINGPOINT, 330), + + /* Key identifier for HTTP Message Signatures */ + CURLOPT(CURLOPT_HTTPSIG_KEYID, CURLOPTTYPE_STRINGPOINT, 331), + + /* Space-separated list of components to sign for HTTP Message Signatures */ + CURLOPT(CURLOPT_HTTPSIG_HEADERS, CURLOPTTYPE_STRINGPOINT, 332), + + CURLOPT_LASTENTRY /* the last unused */ +} CURLoption; + +#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all + the obsolete stuff removed! */ + +/* Backwards compatibility with older names */ +/* These are scheduled to disappear by 2011 */ + +/* This was added in version 7.19.1 */ +#define CURLOPT_POST301 CURLOPT_POSTREDIR + +/* These are scheduled to disappear by 2009 */ + +/* The following were added in 7.17.0 */ +#define CURLOPT_SSLKEYPASSWD CURLOPT_KEYPASSWD +#define CURLOPT_FTPAPPEND CURLOPT_APPEND +#define CURLOPT_FTPLISTONLY CURLOPT_DIRLISTONLY +#define CURLOPT_FTP_SSL CURLOPT_USE_SSL + +/* The following were added earlier */ + +#define CURLOPT_SSLCERTPASSWD CURLOPT_KEYPASSWD +#define CURLOPT_KRB4LEVEL CURLOPT_KRBLEVEL + +#define CURLOPT_FTP_RESPONSE_TIMEOUT CURLOPT_SERVER_RESPONSE_TIMEOUT + +/* Added in 8.2.0 */ +#define CURLOPT_MAIL_RCPT_ALLLOWFAILS CURLOPT_MAIL_RCPT_ALLOWFAILS + +#else +/* This is set if CURL_NO_OLDIES is defined at compile-time */ +#undef CURLOPT_DNS_USE_GLOBAL_CACHE /* soon obsolete */ +#endif + +/* Below here follows defines for the CURLOPT_IPRESOLVE option. If a host + name resolves addresses using more than one IP protocol version, this + option might be handy to force libcurl to use a specific IP version. */ +#define CURL_IPRESOLVE_WHATEVER 0L /* default, uses addresses to all IP + versions that your system allows */ +#define CURL_IPRESOLVE_V4 1L /* uses only IPv4 addresses/connections */ +#define CURL_IPRESOLVE_V6 2L /* uses only IPv6 addresses/connections */ + + /* Convenient "aliases" */ +#define CURLOPT_RTSPHEADER CURLOPT_HTTPHEADER + +/* These constants are for use with the CURLOPT_HTTP_VERSION option. */ +#define CURL_HTTP_VERSION_NONE 0L /* setting this means we do not care, and + that we would like the library to choose + the best possible for us! */ +#define CURL_HTTP_VERSION_1_0 1L /* please use HTTP 1.0 in the request */ +#define CURL_HTTP_VERSION_1_1 2L /* please use HTTP 1.1 in the request */ +#define CURL_HTTP_VERSION_2_0 3L /* please use HTTP 2 in the request */ +#define CURL_HTTP_VERSION_2TLS 4L /* use version 2 for HTTPS, version 1.1 for + HTTP */ +#define CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE 5L /* please use HTTP 2 without + HTTP/1.1 Upgrade */ +#define CURL_HTTP_VERSION_3 30L /* Use HTTP/3, fallback to HTTP/2 or + HTTP/1 if needed. For HTTPS only. For + HTTP, this option makes libcurl + return error. */ +#define CURL_HTTP_VERSION_3ONLY 31L /* Use HTTP/3 without fallback. For + HTTPS only. For HTTP, this makes + libcurl return error. */ +#define CURL_HTTP_VERSION_LAST 32L /* *ILLEGAL* http version */ + +/* Convenience definition simple because the name of the version is HTTP/2 and + not 2.0. The 2_0 version of the enum name was set while the version was + still planned to be 2.0 and we stick to it for compatibility. */ +#define CURL_HTTP_VERSION_2 CURL_HTTP_VERSION_2_0 + +/* + * Public API enums for RTSP requests + */ + +#define CURL_RTSPREQ_NONE 0L +#define CURL_RTSPREQ_OPTIONS 1L +#define CURL_RTSPREQ_DESCRIBE 2L +#define CURL_RTSPREQ_ANNOUNCE 3L +#define CURL_RTSPREQ_SETUP 4L +#define CURL_RTSPREQ_PLAY 5L +#define CURL_RTSPREQ_PAUSE 6L +#define CURL_RTSPREQ_TEARDOWN 7L +#define CURL_RTSPREQ_GET_PARAMETER 8L +#define CURL_RTSPREQ_SET_PARAMETER 9L +#define CURL_RTSPREQ_RECORD 10L +#define CURL_RTSPREQ_RECEIVE 11L +#define CURL_RTSPREQ_LAST 12L /* not used */ + + /* These enums are for use with the CURLOPT_NETRC option. */ +#define CURL_NETRC_IGNORED 0L /* The .netrc is never read. + This is the default. */ +#define CURL_NETRC_OPTIONAL 1L /* A user:password in the URL is preferred + to one in the .netrc. */ +#define CURL_NETRC_REQUIRED 2L /* A user:password in the URL is ignored. + Unless one is set programmatically, the + .netrc is queried. */ +enum CURL_NETRC_OPTION { + /* we set a single member here, to make sure we still provide the enum, but + the values to use are defined above with L suffixes */ + CURL_NETRC_LAST = 3 +}; + +#define CURL_SSLVERSION_DEFAULT 0L +#define CURL_SSLVERSION_TLSv1 1L /* TLS 1.x */ +#define CURL_SSLVERSION_SSLv2 2L +#define CURL_SSLVERSION_SSLv3 3L +#define CURL_SSLVERSION_TLSv1_0 4L +#define CURL_SSLVERSION_TLSv1_1 5L +#define CURL_SSLVERSION_TLSv1_2 6L +#define CURL_SSLVERSION_TLSv1_3 7L + +#define CURL_SSLVERSION_LAST 8L /* never use, keep last */ + +#define CURL_SSLVERSION_MAX_NONE 0L +#define CURL_SSLVERSION_MAX_DEFAULT (CURL_SSLVERSION_TLSv1 << 16) +#define CURL_SSLVERSION_MAX_TLSv1_0 (CURL_SSLVERSION_TLSv1_0 << 16) +#define CURL_SSLVERSION_MAX_TLSv1_1 (CURL_SSLVERSION_TLSv1_1 << 16) +#define CURL_SSLVERSION_MAX_TLSv1_2 (CURL_SSLVERSION_TLSv1_2 << 16) +#define CURL_SSLVERSION_MAX_TLSv1_3 (CURL_SSLVERSION_TLSv1_3 << 16) + +/* never use, keep last */ +#define CURL_SSLVERSION_MAX_LAST (CURL_SSLVERSION_LAST << 16) + +#define CURL_TLSAUTH_NONE 0L +#define CURL_TLSAUTH_SRP 1L + +enum CURL_TLSAUTH { + /* we set a single member here, to make sure we still provide the enum, + but the values to use are defined above with L suffixes */ + CURL_TLSAUTH_LAST = 2 +}; + +/* symbols to use with CURLOPT_POSTREDIR. + CURL_REDIR_POST_301, CURL_REDIR_POST_302 and CURL_REDIR_POST_303 + can be bitwise ORed so that CURL_REDIR_POST_301 | CURL_REDIR_POST_302 + | CURL_REDIR_POST_303 == CURL_REDIR_POST_ALL */ + +#define CURL_REDIR_GET_ALL 0L +#define CURL_REDIR_POST_301 1L +#define CURL_REDIR_POST_302 2L +#define CURL_REDIR_POST_303 4L +#define CURL_REDIR_POST_ALL \ + (CURL_REDIR_POST_301 | CURL_REDIR_POST_302 | CURL_REDIR_POST_303) + +#define CURL_TIMECOND_NONE 0L +#define CURL_TIMECOND_IFMODSINCE 1L +#define CURL_TIMECOND_IFUNMODSINCE 2L +#define CURL_TIMECOND_LASTMOD 3L + +typedef enum { + /* we set a single member here, to make sure we still provide + the enum typedef, but the values to use are defined above with L + suffixes */ + CURL_TIMECOND_LAST = 4 +} curl_TimeCond; + +/* Special size_t value signaling a null-terminated string. */ +#define CURL_ZERO_TERMINATED ((size_t)-1) + +/* curl_strequal() and curl_strnequal() are subject for removal in a future + release */ +CURL_EXTERN int curl_strequal(const char *s1, const char *s2); +CURL_EXTERN int curl_strnequal(const char *s1, const char *s2, size_t n); + +/* Mime/form handling support. */ +typedef struct curl_mime curl_mime; /* Mime context. */ +typedef struct curl_mimepart curl_mimepart; /* Mime part context. */ + +/* CURLMIMEOPT_ defines are for the CURLOPT_MIME_OPTIONS option. */ +#define CURLMIMEOPT_FORMESCAPE (1L << 0) /* Use backslash-escaping for forms */ + +/* + * NAME curl_mime_init() + * + * DESCRIPTION + * + * Create a mime context and return its handle. The easy parameter is the + * target handle. + */ +CURL_EXTERN curl_mime *curl_mime_init(CURL *easy); + +/* + * NAME curl_mime_free() + * + * DESCRIPTION + * + * release a mime handle and its substructures. + */ +CURL_EXTERN void curl_mime_free(curl_mime *mime); + +/* + * NAME curl_mime_addpart() + * + * DESCRIPTION + * + * Append a new empty part to the given mime context and return a handle to + * the created part. + */ +CURL_EXTERN curl_mimepart *curl_mime_addpart(curl_mime *mime); + +/* + * NAME curl_mime_name() + * + * DESCRIPTION + * + * Set mime/form part name. + */ +CURL_EXTERN CURLcode curl_mime_name(curl_mimepart *part, const char *name); + +/* + * NAME curl_mime_filename() + * + * DESCRIPTION + * + * Set mime part remote filename. + */ +CURL_EXTERN CURLcode curl_mime_filename(curl_mimepart *part, + const char *filename); + +/* + * NAME curl_mime_type() + * + * DESCRIPTION + * + * Set mime part type. + */ +CURL_EXTERN CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype); + +/* + * NAME curl_mime_encoder() + * + * DESCRIPTION + * + * Set mime data transfer encoder. + */ +CURL_EXTERN CURLcode curl_mime_encoder(curl_mimepart *part, + const char *encoding); + +/* + * NAME curl_mime_data() + * + * DESCRIPTION + * + * Set mime part data source from memory data, + */ +CURL_EXTERN CURLcode curl_mime_data(curl_mimepart *part, + const char *data, size_t datasize); + +/* + * NAME curl_mime_filedata() + * + * DESCRIPTION + * + * Set mime part data source from named file. + */ +CURL_EXTERN CURLcode curl_mime_filedata(curl_mimepart *part, + const char *filename); + +/* + * NAME curl_mime_data_cb() + * + * DESCRIPTION + * + * Set mime part data source from callback function. + */ +CURL_EXTERN CURLcode curl_mime_data_cb(curl_mimepart *part, + curl_off_t datasize, + curl_read_callback readfunc, + curl_seek_callback seekfunc, + curl_free_callback freefunc, + void *arg); + +/* + * NAME curl_mime_subparts() + * + * DESCRIPTION + * + * Set mime part data source from subparts. + */ +CURL_EXTERN CURLcode curl_mime_subparts(curl_mimepart *part, + curl_mime *subparts); +/* + * NAME curl_mime_headers() + * + * DESCRIPTION + * + * Set mime part headers. + */ +CURL_EXTERN CURLcode curl_mime_headers(curl_mimepart *part, + struct curl_slist *headers, + int take_ownership); + +typedef enum { + /********* the first one is unused ************/ + CURLFORM_NOTHING CURL_DEPRECATED(7.56.0, ""), + CURLFORM_COPYNAME CURL_DEPRECATED(7.56.0, "Use curl_mime_name()"), + CURLFORM_PTRNAME CURL_DEPRECATED(7.56.0, "Use curl_mime_name()"), + CURLFORM_NAMELENGTH CURL_DEPRECATED(7.56.0, ""), + CURLFORM_COPYCONTENTS CURL_DEPRECATED(7.56.0, "Use curl_mime_data()"), + CURLFORM_PTRCONTENTS CURL_DEPRECATED(7.56.0, "Use curl_mime_data()"), + CURLFORM_CONTENTSLENGTH CURL_DEPRECATED(7.56.0, "Use curl_mime_data()"), + CURLFORM_FILECONTENT CURL_DEPRECATED(7.56.0, "Use curl_mime_data_cb()"), + CURLFORM_ARRAY CURL_DEPRECATED(7.56.0, ""), + CURLFORM_OBSOLETE, + CURLFORM_FILE CURL_DEPRECATED(7.56.0, "Use curl_mime_filedata()"), + + CURLFORM_BUFFER CURL_DEPRECATED(7.56.0, "Use curl_mime_filename()"), + CURLFORM_BUFFERPTR CURL_DEPRECATED(7.56.0, "Use curl_mime_data()"), + CURLFORM_BUFFERLENGTH CURL_DEPRECATED(7.56.0, "Use curl_mime_data()"), + + CURLFORM_CONTENTTYPE CURL_DEPRECATED(7.56.0, "Use curl_mime_type()"), + CURLFORM_CONTENTHEADER CURL_DEPRECATED(7.56.0, "Use curl_mime_headers()"), + CURLFORM_FILENAME CURL_DEPRECATED(7.56.0, "Use curl_mime_filename()"), + CURLFORM_END, + CURLFORM_OBSOLETE2, + + CURLFORM_STREAM CURL_DEPRECATED(7.56.0, "Use curl_mime_data_cb()"), + CURLFORM_CONTENTLEN /* added in 7.46.0, provide a curl_off_t length */ + CURL_DEPRECATED(7.56.0, "Use curl_mime_data()"), + + CURLFORM_LASTENTRY /* the last unused */ +} CURLformoption; + +/* structure to be used as parameter for CURLFORM_ARRAY */ +struct curl_forms { + CURLformoption option; + const char *value; +}; + +/* use this for multipart formpost building */ +/* Returns code for curl_formadd() + * + * Returns: + * CURL_FORMADD_OK on success + * CURL_FORMADD_MEMORY if the FormInfo allocation fails + * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form + * CURL_FORMADD_NULL if a null pointer was given for a char + * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed + * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used + * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error) + * CURL_FORMADD_MEMORY if a curl_httppost struct cannot be allocated + * CURL_FORMADD_MEMORY if some allocation for string copying failed. + * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array + * + ***************************************************************************/ +typedef enum { + CURL_FORMADD_OK CURL_DEPRECATED(7.56.0, ""), /* 1st, no error */ + + CURL_FORMADD_MEMORY CURL_DEPRECATED(7.56.0, ""), + CURL_FORMADD_OPTION_TWICE CURL_DEPRECATED(7.56.0, ""), + CURL_FORMADD_NULL CURL_DEPRECATED(7.56.0, ""), + CURL_FORMADD_UNKNOWN_OPTION CURL_DEPRECATED(7.56.0, ""), + CURL_FORMADD_INCOMPLETE CURL_DEPRECATED(7.56.0, ""), + CURL_FORMADD_ILLEGAL_ARRAY CURL_DEPRECATED(7.56.0, ""), + /* libcurl was built with form api disabled */ + CURL_FORMADD_DISABLED CURL_DEPRECATED(7.56.0, ""), + + CURL_FORMADD_LAST /* last */ +} CURLFORMcode; + +/* + * NAME curl_formadd() + * + * DESCRIPTION + * + * Pretty advanced function for building multi-part formposts. Each invoke + * adds one part that together construct a full post. Then use + * CURLOPT_HTTPPOST to send it off to libcurl. + */ +CURL_EXTERN CURLFORMcode CURL_DEPRECATED(7.56.0, "Use curl_mime_init()") +curl_formadd(struct curl_httppost **httppost, + struct curl_httppost **last_post, + ...); + +/* + * callback function for curl_formget() + * The void *arg pointer is the one passed as second argument to + * curl_formget(). + * The character buffer passed to it must not be freed. + * Should return the buffer length passed to it as the argument "len" on + * success. + */ +typedef size_t (*curl_formget_callback)(void *arg, const char *buf, + size_t len); + +/* + * NAME curl_formget() + * + * DESCRIPTION + * + * Serialize a curl_httppost struct built with curl_formadd(). + * Accepts a void pointer as second argument which is passed to + * the curl_formget_callback function. + * Returns 0 on success. + */ +CURL_EXTERN int CURL_DEPRECATED(7.56.0, "") +curl_formget(struct curl_httppost *form, void *arg, + curl_formget_callback append); +/* + * NAME curl_formfree() + * + * DESCRIPTION + * + * Free a multipart formpost previously built with curl_formadd(). + */ +CURL_EXTERN void CURL_DEPRECATED(7.56.0, "Use curl_mime_free()") +curl_formfree(struct curl_httppost *form); + +/* + * NAME curl_getenv() + * + * DESCRIPTION + * + * Returns a malloc()'ed string that MUST be curl_free()ed after usage is + * complete. DEPRECATED - see lib/README.curlx + */ +CURL_EXTERN char *curl_getenv(const char *variable); + +/* + * NAME curl_version() + * + * DESCRIPTION + * + * Returns a static ASCII string of the libcurl version. + */ +CURL_EXTERN char *curl_version(void); + +/* + * NAME curl_easy_escape() + * + * DESCRIPTION + * + * Escapes URL strings (converts all letters consider illegal in URLs to their + * %XX versions). This function returns a new allocated string or NULL if an + * error occurred. + */ +CURL_EXTERN char *curl_easy_escape(CURL *curl, + const char *string, + int length); + +/* the previous version: */ +CURL_EXTERN char *curl_escape(const char *string, + int length); + +/* + * NAME curl_easy_unescape() + * + * DESCRIPTION + * + * Unescapes URL encoding in strings (converts all %XX codes to their 8-bit + * versions). This function returns a new allocated string or NULL if an error + * occurred. + * Conversion Note: On non-ASCII platforms the ASCII %XX codes are + * converted into the host encoding. + */ +CURL_EXTERN char *curl_easy_unescape(CURL *curl, + const char *string, + int inlength, + int *outlength); + +/* the previous version */ +CURL_EXTERN char *curl_unescape(const char *string, + int length); + +/* + * NAME curl_free() + * + * DESCRIPTION + * + * Provided for de-allocation in the same translation unit that did the + * allocation. Added in libcurl 7.10 + */ +CURL_EXTERN void curl_free(void *p); + +/* + * NAME curl_global_init() + * + * DESCRIPTION + * + * curl_global_init() should be invoked exactly once for each application that + * uses libcurl and before any call of other libcurl functions. + * + * This function is thread-safe if CURL_VERSION_THREADSAFE is set in the + * curl_version_info_data.features flag (fetch by curl_version_info()). + */ +CURL_EXTERN CURLcode curl_global_init(long flags); + +/* + * NAME curl_global_init_mem() + * + * DESCRIPTION + * + * curl_global_init() or curl_global_init_mem() should be invoked exactly once + * for each application that uses libcurl. This function can be used to + * initialize libcurl and set user defined memory management callback + * functions. Users can implement memory management routines to check for + * memory leaks, check for misuse of the curl library etc. User registered + * callback routines is invoked by this library instead of the system + * memory management routines like malloc, free etc. + */ +CURL_EXTERN CURLcode curl_global_init_mem(long flags, + curl_malloc_callback m, + curl_free_callback f, + curl_realloc_callback r, + curl_strdup_callback s, + curl_calloc_callback c); + +/* + * NAME curl_global_cleanup() + * + * DESCRIPTION + * + * curl_global_cleanup() should be invoked exactly once for each application + * that uses libcurl + */ +CURL_EXTERN void curl_global_cleanup(void); + +/* + * NAME curl_global_trace() + * + * DESCRIPTION + * + * curl_global_trace() can be invoked at application start to + * configure which components in curl should participate in tracing. + * + * This function is thread-safe if CURL_VERSION_THREADSAFE is set in the + * curl_version_info_data.features flag (fetch by curl_version_info()). + */ +CURL_EXTERN CURLcode curl_global_trace(const char *config); + +/* linked-list structure for the CURLOPT_QUOTE option (and other) */ +struct curl_slist { + char *data; + struct curl_slist *next; +}; + +/* + * NAME curl_global_sslset() + * + * DESCRIPTION + * + * When built with multiple SSL backends, curl_global_sslset() allows to + * choose one. This function can only be called once, and it must be called + * *before* curl_global_init(). + * + * The backend can be identified by the id (e.g. CURLSSLBACKEND_OPENSSL). The + * backend can also be specified via the name parameter (passing -1 as id). If + * both id and name are specified, the name is ignored. If neither id nor + * name are specified, the function fails with CURLSSLSET_UNKNOWN_BACKEND + * and set the "avail" pointer to the null-terminated list of available + * backends. + * + * Upon success, the function returns CURLSSLSET_OK. + * + * If the specified SSL backend is not available, the function returns + * CURLSSLSET_UNKNOWN_BACKEND and sets the "avail" pointer to a + * null-terminated list of available SSL backends. + * + * The SSL backend can be set only once. If it has already been set, a + * subsequent attempt to change it results in a CURLSSLSET_TOO_LATE. + */ + +struct curl_ssl_backend { + curl_sslbackend id; + const char *name; +}; +typedef struct curl_ssl_backend curl_ssl_backend; + +typedef enum { + CURLSSLSET_OK = 0, + CURLSSLSET_UNKNOWN_BACKEND, + CURLSSLSET_TOO_LATE, + CURLSSLSET_NO_BACKENDS /* libcurl was built without any SSL support */ +} CURLsslset; + +CURL_EXTERN CURLsslset curl_global_sslset(curl_sslbackend id, const char *name, + const curl_ssl_backend ***avail); + +/* + * NAME curl_slist_append() + * + * DESCRIPTION + * + * Appends a string to a linked list. If no list exists, it is created first. + * Returns the new list, after appending. + */ +CURL_EXTERN struct curl_slist *curl_slist_append(struct curl_slist *list, + const char *data); + +/* + * NAME curl_slist_free_all() + * + * DESCRIPTION + * + * free a previously built curl_slist. + */ +CURL_EXTERN void curl_slist_free_all(struct curl_slist *list); + +/* + * NAME curl_getdate() + * + * DESCRIPTION + * + * Returns the time, in seconds since 1 Jan 1970 of the time string given in + * the first argument. The time argument in the second parameter is unused + * and should be set to NULL. + */ +CURL_EXTERN time_t curl_getdate(const char *p, const time_t *unused); + +/* info about the certificate chain, for SSL backends that support it. Asked + for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */ +struct curl_certinfo { + int num_of_certs; /* number of certificates with information */ + struct curl_slist **certinfo; /* for each index in this array, there is a + linked list with textual information for a + certificate in the format "name:content". + eg "Subject:foo", "Issuer:bar", etc. */ +}; + +/* Information about the SSL library used and the respective internal SSL + handle, which can be used to obtain further information regarding the + connection. Asked for with CURLINFO_TLS_SSL_PTR or CURLINFO_TLS_SESSION. */ +struct curl_tlssessioninfo { + curl_sslbackend backend; + void *internals; +}; + +#define CURLINFO_STRING 0x100000 +#define CURLINFO_LONG 0x200000 +#define CURLINFO_DOUBLE 0x300000 +#define CURLINFO_SLIST 0x400000 +#define CURLINFO_PTR 0x400000 /* same as SLIST */ +#define CURLINFO_SOCKET 0x500000 +#define CURLINFO_OFF_T 0x600000 +#define CURLINFO_MASK 0x0fffff +#define CURLINFO_TYPEMASK 0xf00000 + +typedef enum { + CURLINFO_NONE, /* first, never use this */ + CURLINFO_EFFECTIVE_URL = CURLINFO_STRING + 1, + CURLINFO_RESPONSE_CODE = CURLINFO_LONG + 2, + CURLINFO_TOTAL_TIME = CURLINFO_DOUBLE + 3, + CURLINFO_NAMELOOKUP_TIME = CURLINFO_DOUBLE + 4, + CURLINFO_CONNECT_TIME = CURLINFO_DOUBLE + 5, + CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6, + CURLINFO_SIZE_UPLOAD CURL_DEPRECATED(7.55.0, "Use CURLINFO_SIZE_UPLOAD_T") + = CURLINFO_DOUBLE + 7, + CURLINFO_SIZE_UPLOAD_T = CURLINFO_OFF_T + 7, + CURLINFO_SIZE_DOWNLOAD + CURL_DEPRECATED(7.55.0, "Use CURLINFO_SIZE_DOWNLOAD_T") + = CURLINFO_DOUBLE + 8, + CURLINFO_SIZE_DOWNLOAD_T = CURLINFO_OFF_T + 8, + CURLINFO_SPEED_DOWNLOAD + CURL_DEPRECATED(7.55.0, "Use CURLINFO_SPEED_DOWNLOAD_T") + = CURLINFO_DOUBLE + 9, + CURLINFO_SPEED_DOWNLOAD_T = CURLINFO_OFF_T + 9, + CURLINFO_SPEED_UPLOAD + CURL_DEPRECATED(7.55.0, "Use CURLINFO_SPEED_UPLOAD_T") + = CURLINFO_DOUBLE + 10, + CURLINFO_SPEED_UPLOAD_T = CURLINFO_OFF_T + 10, + CURLINFO_HEADER_SIZE = CURLINFO_LONG + 11, + CURLINFO_REQUEST_SIZE = CURLINFO_LONG + 12, + CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG + 13, + CURLINFO_FILETIME = CURLINFO_LONG + 14, + CURLINFO_FILETIME_T = CURLINFO_OFF_T + 14, + CURLINFO_CONTENT_LENGTH_DOWNLOAD + CURL_DEPRECATED(7.55.0, + "Use CURLINFO_CONTENT_LENGTH_DOWNLOAD_T") + = CURLINFO_DOUBLE + 15, + CURLINFO_CONTENT_LENGTH_DOWNLOAD_T = CURLINFO_OFF_T + 15, + CURLINFO_CONTENT_LENGTH_UPLOAD + CURL_DEPRECATED(7.55.0, + "Use CURLINFO_CONTENT_LENGTH_UPLOAD_T") + = CURLINFO_DOUBLE + 16, + CURLINFO_CONTENT_LENGTH_UPLOAD_T = CURLINFO_OFF_T + 16, + CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17, + CURLINFO_CONTENT_TYPE = CURLINFO_STRING + 18, + CURLINFO_REDIRECT_TIME = CURLINFO_DOUBLE + 19, + CURLINFO_REDIRECT_COUNT = CURLINFO_LONG + 20, + CURLINFO_PRIVATE = CURLINFO_STRING + 21, + CURLINFO_HTTP_CONNECTCODE = CURLINFO_LONG + 22, + CURLINFO_HTTPAUTH_AVAIL = CURLINFO_LONG + 23, + CURLINFO_PROXYAUTH_AVAIL = CURLINFO_LONG + 24, + CURLINFO_OS_ERRNO = CURLINFO_LONG + 25, + CURLINFO_NUM_CONNECTS = CURLINFO_LONG + 26, + CURLINFO_SSL_ENGINES = CURLINFO_SLIST + 27, + CURLINFO_COOKIELIST = CURLINFO_SLIST + 28, + CURLINFO_LASTSOCKET CURL_DEPRECATED(7.45.0, "Use CURLINFO_ACTIVESOCKET") + = CURLINFO_LONG + 29, + CURLINFO_FTP_ENTRY_PATH = CURLINFO_STRING + 30, + CURLINFO_REDIRECT_URL = CURLINFO_STRING + 31, + CURLINFO_PRIMARY_IP = CURLINFO_STRING + 32, + CURLINFO_APPCONNECT_TIME = CURLINFO_DOUBLE + 33, + CURLINFO_CERTINFO = CURLINFO_PTR + 34, + CURLINFO_CONDITION_UNMET = CURLINFO_LONG + 35, + CURLINFO_RTSP_SESSION_ID = CURLINFO_STRING + 36, + CURLINFO_RTSP_CLIENT_CSEQ = CURLINFO_LONG + 37, + CURLINFO_RTSP_SERVER_CSEQ = CURLINFO_LONG + 38, + CURLINFO_RTSP_CSEQ_RECV = CURLINFO_LONG + 39, + CURLINFO_PRIMARY_PORT = CURLINFO_LONG + 40, + CURLINFO_LOCAL_IP = CURLINFO_STRING + 41, + CURLINFO_LOCAL_PORT = CURLINFO_LONG + 42, + CURLINFO_TLS_SESSION CURL_DEPRECATED(7.48.0, "Use CURLINFO_TLS_SSL_PTR") + = CURLINFO_PTR + 43, + CURLINFO_ACTIVESOCKET = CURLINFO_SOCKET + 44, + CURLINFO_TLS_SSL_PTR = CURLINFO_PTR + 45, + CURLINFO_HTTP_VERSION = CURLINFO_LONG + 46, + CURLINFO_PROXY_SSL_VERIFYRESULT = CURLINFO_LONG + 47, + CURLINFO_PROTOCOL CURL_DEPRECATED(7.85.0, "Use CURLINFO_SCHEME") + = CURLINFO_LONG + 48, + CURLINFO_SCHEME = CURLINFO_STRING + 49, + CURLINFO_TOTAL_TIME_T = CURLINFO_OFF_T + 50, + CURLINFO_NAMELOOKUP_TIME_T = CURLINFO_OFF_T + 51, + CURLINFO_CONNECT_TIME_T = CURLINFO_OFF_T + 52, + CURLINFO_PRETRANSFER_TIME_T = CURLINFO_OFF_T + 53, + CURLINFO_STARTTRANSFER_TIME_T = CURLINFO_OFF_T + 54, + CURLINFO_REDIRECT_TIME_T = CURLINFO_OFF_T + 55, + CURLINFO_APPCONNECT_TIME_T = CURLINFO_OFF_T + 56, + CURLINFO_RETRY_AFTER = CURLINFO_OFF_T + 57, + CURLINFO_EFFECTIVE_METHOD = CURLINFO_STRING + 58, + CURLINFO_PROXY_ERROR = CURLINFO_LONG + 59, + CURLINFO_REFERER = CURLINFO_STRING + 60, + CURLINFO_CAINFO = CURLINFO_STRING + 61, + CURLINFO_CAPATH = CURLINFO_STRING + 62, + CURLINFO_XFER_ID = CURLINFO_OFF_T + 63, + CURLINFO_CONN_ID = CURLINFO_OFF_T + 64, + CURLINFO_QUEUE_TIME_T = CURLINFO_OFF_T + 65, + CURLINFO_USED_PROXY = CURLINFO_LONG + 66, + CURLINFO_POSTTRANSFER_TIME_T = CURLINFO_OFF_T + 67, + CURLINFO_EARLYDATA_SENT_T = CURLINFO_OFF_T + 68, + CURLINFO_HTTPAUTH_USED = CURLINFO_LONG + 69, + CURLINFO_PROXYAUTH_USED = CURLINFO_LONG + 70, + CURLINFO_SIZE_DELIVERED = CURLINFO_OFF_T + 71, + CURLINFO_LASTONE = 71 +} CURLINFO; + +/* CURLINFO_RESPONSE_CODE is the new name for the option previously known as + CURLINFO_HTTP_CODE */ +#define CURLINFO_HTTP_CODE CURLINFO_RESPONSE_CODE + +typedef enum { + CURLCLOSEPOLICY_NONE, /* first, never use this */ + + CURLCLOSEPOLICY_OLDEST, + CURLCLOSEPOLICY_LEAST_RECENTLY_USED, + CURLCLOSEPOLICY_LEAST_TRAFFIC, + CURLCLOSEPOLICY_SLOWEST, + CURLCLOSEPOLICY_CALLBACK, + + CURLCLOSEPOLICY_LAST /* last, never use this */ +} curl_closepolicy; + +#define CURL_GLOBAL_SSL (1 << 0) /* no purpose since 7.57.0 */ +#define CURL_GLOBAL_WIN32 (1 << 1) +#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL | CURL_GLOBAL_WIN32) +#define CURL_GLOBAL_NOTHING 0 +#define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL +#define CURL_GLOBAL_ACK_EINTR (1 << 2) + +/***************************************************************************** + * Setup defines, protos etc for the sharing stuff. + */ + +/* Different data locks for a single share */ +typedef enum { + CURL_LOCK_DATA_NONE = 0, + /* CURL_LOCK_DATA_SHARE is used internally to say that the locking is made + * to change the internal state of the share itself. + */ + CURL_LOCK_DATA_SHARE, + CURL_LOCK_DATA_COOKIE, + CURL_LOCK_DATA_DNS, + CURL_LOCK_DATA_SSL_SESSION, + CURL_LOCK_DATA_CONNECT, + CURL_LOCK_DATA_PSL, + CURL_LOCK_DATA_HSTS, + CURL_LOCK_DATA_LAST +} curl_lock_data; + +/* Different lock access types */ +typedef enum { + CURL_LOCK_ACCESS_NONE = 0, /* unspecified action */ + CURL_LOCK_ACCESS_SHARED = 1, /* for read perhaps */ + CURL_LOCK_ACCESS_SINGLE = 2, /* for write perhaps */ + CURL_LOCK_ACCESS_LAST /* never use */ +} curl_lock_access; + +typedef void (*curl_lock_function)(CURL *handle, + curl_lock_data data, + curl_lock_access locktype, + void *userptr); +typedef void (*curl_unlock_function)(CURL *handle, + curl_lock_data data, + void *userptr); + +typedef enum { + CURLSHE_OK, /* all is fine */ + CURLSHE_BAD_OPTION, /* 1 */ + CURLSHE_IN_USE, /* 2 */ + CURLSHE_INVALID, /* 3 */ + CURLSHE_NOMEM, /* 4 out of memory */ + CURLSHE_NOT_BUILT_IN, /* 5 feature not present in lib */ + CURLSHE_LAST /* never use */ +} CURLSHcode; + +typedef enum { + CURLSHOPT_NONE, /* do not use */ + CURLSHOPT_SHARE, /* specify a data type to share */ + CURLSHOPT_UNSHARE, /* specify which data type to stop sharing */ + CURLSHOPT_LOCKFUNC, /* pass in a 'curl_lock_function' pointer */ + CURLSHOPT_UNLOCKFUNC, /* pass in a 'curl_unlock_function' pointer */ + CURLSHOPT_USERDATA, /* pass in a user data pointer used in the lock/unlock + callback functions */ + CURLSHOPT_LAST /* never use */ +} CURLSHoption; + +CURL_EXTERN CURLSH *curl_share_init(void); +CURL_EXTERN CURLSHcode curl_share_setopt(CURLSH *sh, CURLSHoption option, ...); +CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *sh); + +/**************************************************************************** + * Structures for querying information about the curl library at runtime. + */ + +typedef enum { + CURLVERSION_FIRST, /* 7.10 */ + CURLVERSION_SECOND, /* 7.11.1 */ + CURLVERSION_THIRD, /* 7.12.0 */ + CURLVERSION_FOURTH, /* 7.16.1 */ + CURLVERSION_FIFTH, /* 7.57.0 */ + CURLVERSION_SIXTH, /* 7.66.0 */ + CURLVERSION_SEVENTH, /* 7.70.0 */ + CURLVERSION_EIGHTH, /* 7.72.0 */ + CURLVERSION_NINTH, /* 7.75.0 */ + CURLVERSION_TENTH, /* 7.77.0 */ + CURLVERSION_ELEVENTH, /* 7.87.0 */ + CURLVERSION_TWELFTH, /* 8.8.0 */ + CURLVERSION_LAST /* never actually use this */ +} CURLversion; + +/* The 'CURLVERSION_NOW' is the symbolic name meant to be used by programs + that want to get version information. It is meant to be a built-in + version number for what kind of struct the caller expects. If the struct + ever changes, we redefine the NOW to another enum from above. */ +#define CURLVERSION_NOW CURLVERSION_TWELFTH + +struct curl_version_info_data { + CURLversion age; /* age of the returned struct */ + const char *version; /* LIBCURL_VERSION */ + unsigned int version_num; /* LIBCURL_VERSION_NUM */ + const char *host; /* OS/host/cpu/machine when configured */ + int features; /* bitmask, see defines below */ + const char *ssl_version; /* human readable string */ + long ssl_version_num; /* not used anymore, always 0 */ + const char *libz_version; /* human readable string */ + /* protocols is terminated by an entry with a NULL protoname */ + const char * const *protocols; + + /* The fields below this were added in CURLVERSION_SECOND */ + const char *ares; + int ares_num; + + /* This field was added in CURLVERSION_THIRD */ + const char *libidn; + + /* These field were added in CURLVERSION_FOURTH */ + + /* Same as '_libiconv_version' if built with HAVE_ICONV */ + int iconv_ver_num; + + const char *libssh_version; /* human readable string */ + + /* These fields were added in CURLVERSION_FIFTH */ + unsigned int brotli_ver_num; /* Numeric Brotli version + (MAJOR << 24) | (MINOR << 12) | PATCH */ + const char *brotli_version; /* human readable string. */ + + /* These fields were added in CURLVERSION_SIXTH */ + unsigned int nghttp2_ver_num; /* Numeric nghttp2 version + (MAJOR << 16) | (MINOR << 8) | PATCH */ + const char *nghttp2_version; /* human readable string. */ + const char *quic_version; /* human readable quic (+ HTTP/3) library + + version or NULL */ + + /* These fields were added in CURLVERSION_SEVENTH */ + const char *cainfo; /* the built-in default CURLOPT_CAINFO, might + be NULL */ + const char *capath; /* the built-in default CURLOPT_CAPATH, might + be NULL */ + + /* These fields were added in CURLVERSION_EIGHTH */ + unsigned int zstd_ver_num; /* Numeric Zstd version + (MAJOR << 24) | (MINOR << 12) | PATCH */ + const char *zstd_version; /* human readable string. */ + + /* These fields were added in CURLVERSION_NINTH */ + const char *hyper_version; /* human readable string. */ + + /* These fields were added in CURLVERSION_TENTH */ + const char *gsasl_version; /* human readable string. */ + + /* These fields were added in CURLVERSION_ELEVENTH */ + /* feature_names is terminated by an entry with a NULL feature name */ + const char * const *feature_names; + + /* These fields were added in CURLVERSION_TWELFTH */ + const char *rtmp_version; /* human readable string. */ +}; +typedef struct curl_version_info_data curl_version_info_data; + +#define CURL_VERSION_IPV6 (1<<0) /* IPv6-enabled */ +#define CURL_VERSION_KERBEROS4 (1<<1) /* Kerberos V4 auth is supported + (deprecated) */ +#define CURL_VERSION_SSL (1<<2) /* SSL options are present */ +#define CURL_VERSION_LIBZ (1<<3) /* libz features are present */ +#define CURL_VERSION_NTLM (1<<4) /* NTLM auth is supported */ +#define CURL_VERSION_GSSNEGOTIATE (1<<5) /* Negotiate auth is supported + (deprecated) */ +#define CURL_VERSION_DEBUG (1<<6) /* Built with debug capabilities */ +#define CURL_VERSION_ASYNCHDNS (1<<7) /* Asynchronous DNS resolves */ +#define CURL_VERSION_SPNEGO (1<<8) /* SPNEGO auth is supported */ +#define CURL_VERSION_LARGEFILE (1<<9) /* Supports files larger than 2GB */ +#define CURL_VERSION_IDN (1<<10) /* Internationized Domain Names are + supported */ +#define CURL_VERSION_SSPI (1<<11) /* Built against Windows SSPI */ +#define CURL_VERSION_CONV (1<<12) /* Character conversions supported */ +#define CURL_VERSION_CURLDEBUG (1<<13) /* Debug memory tracking supported + (deprecated) */ +#define CURL_VERSION_TLSAUTH_SRP (1<<14) /* TLS-SRP auth is supported */ +#define CURL_VERSION_NTLM_WB (1<<15) /* NTLM delegation to winbind helper + is supported */ +#define CURL_VERSION_HTTP2 (1<<16) /* HTTP2 support built-in */ +#define CURL_VERSION_GSSAPI (1<<17) /* Built against a GSS-API library */ +#define CURL_VERSION_KERBEROS5 (1<<18) /* Kerberos V5 auth is supported */ +#define CURL_VERSION_UNIX_SOCKETS (1<<19) /* Unix domain sockets support */ +#define CURL_VERSION_PSL (1<<20) /* Mozilla's Public Suffix List, used + for cookie domain verification */ +#define CURL_VERSION_HTTPS_PROXY (1<<21) /* HTTPS-proxy support built-in */ +#define CURL_VERSION_MULTI_SSL (1<<22) /* Multiple SSL backends available */ +#define CURL_VERSION_BROTLI (1<<23) /* Brotli features are present. */ +#define CURL_VERSION_ALTSVC (1<<24) /* Alt-Svc handling built-in */ +#define CURL_VERSION_HTTP3 (1<<25) /* HTTP3 support built-in */ +#define CURL_VERSION_ZSTD (1<<26) /* zstd features are present */ +#define CURL_VERSION_UNICODE (1<<27) /* Unicode support on Windows */ +#define CURL_VERSION_HSTS (1<<28) /* HSTS is supported */ +#define CURL_VERSION_GSASL (1<<29) /* libgsasl is supported */ +#define CURL_VERSION_THREADSAFE (1<<30) /* libcurl API is thread-safe */ + +/* + * NAME curl_version_info() + * + * DESCRIPTION + * + * This function returns a pointer to a static copy of the version info + * struct. See above. + */ +CURL_EXTERN curl_version_info_data *curl_version_info(CURLversion stamp); + +/* + * NAME curl_easy_strerror() + * + * DESCRIPTION + * + * The curl_easy_strerror function may be used to turn a CURLcode value + * into the equivalent human readable error string. This is useful + * for printing meaningful error messages. + */ +CURL_EXTERN const char *curl_easy_strerror(CURLcode error); + +/* + * NAME curl_share_strerror() + * + * DESCRIPTION + * + * The curl_share_strerror function may be used to turn a CURLSHcode value + * into the equivalent human readable error string. This is useful + * for printing meaningful error messages. + */ +CURL_EXTERN const char *curl_share_strerror(CURLSHcode error); + +/* + * NAME curl_easy_pause() + * + * DESCRIPTION + * + * The curl_easy_pause function pauses or unpauses transfers. Select the new + * state by setting the action bitmask, use the convenience defines below. + * + */ +CURL_EXTERN CURLcode curl_easy_pause(CURL *curl, int action); + +#define CURLPAUSE_RECV (1 << 0) +#define CURLPAUSE_RECV_CONT 0 + +#define CURLPAUSE_SEND (1 << 2) +#define CURLPAUSE_SEND_CONT 0 + +#define CURLPAUSE_ALL (CURLPAUSE_RECV | CURLPAUSE_SEND) +#define CURLPAUSE_CONT (CURLPAUSE_RECV_CONT | CURLPAUSE_SEND_CONT) + +/* + * NAME curl_easy_ssls_import() + * + * DESCRIPTION + * + * The curl_easy_ssls_import function adds a previously exported SSL session + * to the SSL session cache of the easy handle (or the underlying share). + */ +CURL_EXTERN CURLcode curl_easy_ssls_import(CURL *curl, + const char *session_key, + const unsigned char *shmac, + size_t shmac_len, + const unsigned char *sdata, + size_t sdata_len); + +/* This is the curl_ssls_export_cb callback prototype. It + * is passed to curl_easy_ssls_export() to extract SSL sessions/tickets. */ +typedef CURLcode curl_ssls_export_cb(CURL *curl, + void *userptr, + const char *session_key, + const unsigned char *shmac, + size_t shmac_len, + const unsigned char *sdata, + size_t sdata_len, + curl_off_t valid_until, + int ietf_tls_id, + const char *alpn, + size_t earlydata_max); + +/* + * NAME curl_easy_ssls_export() + * + * DESCRIPTION + * + * The curl_easy_ssls_export function iterates over all SSL sessions stored + * in the easy handle (or underlying share) and invokes the passed + * callback. + * + */ +CURL_EXTERN CURLcode curl_easy_ssls_export(CURL *curl, + curl_ssls_export_cb *export_fn, + void *userptr); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +/* unfortunately, the easy.h and multi.h include files need options and info + stuff before they can be included! */ +#include "easy.h" /* nothing in curl is fun without the easy stuff */ +#include "multi.h" +#include "urlapi.h" +#include "options.h" +#include "header.h" +#include "websockets.h" +#include "mprintf.h" + +/* the typechecker does not work in C++ (yet) */ +#if ((defined(__GNUC__) && defined(__GNUC_MINOR__) && \ + ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) || \ + (defined(__clang__) && __clang_major__ >= 14)) && \ + !defined(__cplusplus) && !defined(CURL_DISABLE_TYPECHECK) +#include "typecheck-gcc.h" +#else +#if defined(__STDC__) && (__STDC__ >= 1) +/* This preprocessor magic ensures that application authors pass exactly three + arguments to these functions. For compatibility with C++ global namespace + '::' and reusing these symbols as method names, while also avoiding + recursive macros, use a two-stage solution. */ +#define curl_exactly_three_arguments(a, b, c) (a, b, c) +#define curl_easy_setopt(handle, opt, param) \ + curl_easy_setopt curl_exactly_three_arguments(handle, opt, param) +#define curl_easy_getinfo(handle, info, arg) \ + curl_easy_getinfo curl_exactly_three_arguments(handle, info, arg) +#define curl_share_setopt(share, opt, param) \ + curl_share_setopt curl_exactly_three_arguments(share, opt, param) +#define curl_multi_setopt(handle, opt, param) \ + curl_multi_setopt curl_exactly_three_arguments(handle, opt, param) +#endif /* __STDC__ >= 1 */ +#endif /* gcc >= 4.3 && !__cplusplus && !CURL_DISABLE_TYPECHECK */ + +#endif /* CURLINC_CURL_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/curlver.h b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/curlver.h new file mode 100644 index 0000000000..a5ba358840 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/curlver.h @@ -0,0 +1,77 @@ +#ifndef CURLINC_CURLVER_H +#define CURLINC_CURLVER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* This header file contains nothing but libcurl version info, generated by + a script at release-time. This was made its own header file in 7.11.2 */ + +/* This is the global package copyright */ +#define LIBCURL_COPYRIGHT "Daniel Stenberg, <daniel@haxx.se>." + +/* This is the version number of the libcurl package from which this header + file origins: */ +#define LIBCURL_VERSION "8.22.0" + +/* The numeric version number is also available "in parts" by using these + defines: */ +#define LIBCURL_VERSION_MAJOR 8 +#define LIBCURL_VERSION_MINOR 22 +#define LIBCURL_VERSION_PATCH 0 +/* This is the numeric version of the libcurl version number, meant for easier + parsing and comparisons by programs. The LIBCURL_VERSION_NUM define always + follows this syntax: + + 0xXXYYZZ + + Where XX, YY and ZZ are the main version, release and patch numbers in + hexadecimal (using 8 bits each). All three numbers are always represented + using two digits. Version 1.2 would appear as "0x010200" while 9.11.7 + appears as "0x090b07". + + This 6-digit (24 bits) hexadecimal number does not show pre-release number, + and it is always a greater number in a more recent release. It makes + comparisons with greater than and less than work. + + Note: This define is the full hex number and _does not_ use the + CURL_VERSION_BITS() macro since curl's own configure script greps for it + and needs it to contain the full number. */ +#define LIBCURL_VERSION_NUM 0x081600 + +/* + * This is the date and time when the full source package was created. The + * timestamp is not stored in git, as the timestamp is properly set in the + * tarballs by the maketgz script. + * + * The format of the date follows this template: + * + * "2007-11-23" + */ +#define LIBCURL_TIMESTAMP "2026-09-02" + +#define CURL_VERSION_BITS(x, y, z) ((x) << 16 | (y) << 8 | (z)) +#define CURL_AT_LEAST_VERSION(x, y, z) \ + (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z)) + +#endif /* CURLINC_CURLVER_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/easy.h b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/easy.h new file mode 100644 index 0000000000..197e6e7b92 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/easy.h @@ -0,0 +1,123 @@ +#ifndef CURLINC_EASY_H +#define CURLINC_EASY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifdef __cplusplus +extern "C" { +#endif + +/* Flag bits in the curl_blob struct: */ +#define CURL_BLOB_COPY 1 /* tell libcurl to copy the data */ +#define CURL_BLOB_NOCOPY 0 /* tell libcurl to NOT copy the data */ + +struct curl_blob { + void *data; + size_t len; + unsigned int flags; /* bit 0 is defined, the rest are reserved and should be + left zeroes */ +}; + +CURL_EXTERN CURL *curl_easy_init(void); +CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...); +CURL_EXTERN CURLcode curl_easy_perform(CURL *curl); +CURL_EXTERN void curl_easy_cleanup(CURL *curl); + +/* + * NAME curl_easy_getinfo() + * + * DESCRIPTION + * + * Request internal information from the curl session with this function. + * The third argument MUST be pointing to the specific type of the used option + * which is documented in each man page of the option. The data pointed to + * is filled in accordingly and can be relied upon only if the function + * returns CURLE_OK. This function is intended to get used *AFTER* a performed + * transfer, all results from this function are undefined until the transfer + * is completed. + */ +CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...); + +/* + * NAME curl_easy_duphandle() + * + * DESCRIPTION + * + * Creates a new curl session handle with the same options set for the handle + * passed in. Duplicating a handle could only be a matter of cloning data and + * options, internal state info and things like persistent connections cannot + * be transferred. It is useful in multi-threaded applications when you can run + * curl_easy_duphandle() for each new thread to avoid a series of identical + * curl_easy_setopt() invokes in every thread. + */ +CURL_EXTERN CURL *curl_easy_duphandle(CURL *curl); + +/* + * NAME curl_easy_reset() + * + * DESCRIPTION + * + * Re-initializes a curl handle to the default values. This puts back the + * handle to the same state as it was in when it was created. + * + * It does keep: live connections, the Session ID cache, the DNS cache and the + * cookies. + */ +CURL_EXTERN void curl_easy_reset(CURL *curl); + +/* + * NAME curl_easy_recv() + * + * DESCRIPTION + * + * Receives data from the connected socket. Use after successful + * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. + */ +CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, + size_t *n); + +/* + * NAME curl_easy_send() + * + * DESCRIPTION + * + * Sends data over the connected socket. Use after successful + * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. + */ +CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer, + size_t buflen, size_t *n); + +/* + * NAME curl_easy_upkeep() + * + * DESCRIPTION + * + * Performs connection upkeep for the given session handle. + */ +CURL_EXTERN CURLcode curl_easy_upkeep(CURL *curl); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/header.h b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/header.h new file mode 100644 index 0000000000..5c3281a531 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/header.h @@ -0,0 +1,74 @@ +#ifndef CURLINC_HEADER_H +#define CURLINC_HEADER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifdef __cplusplus +extern "C" { +#endif + +struct curl_header { + char *name; /* this might not use the same case */ + char *value; + size_t amount; /* number of headers using this name */ + size_t index; /* ... of this instance, 0 or higher */ + unsigned int origin; /* see bits below */ + void *anchor; /* handle privately used by libcurl */ +}; + +/* 'origin' bits */ +#define CURLH_HEADER (1 << 0) /* plain server header */ +#define CURLH_TRAILER (1 << 1) /* trailers */ +#define CURLH_CONNECT (1 << 2) /* CONNECT headers */ +#define CURLH_1XX (1 << 3) /* 1xx headers */ +#define CURLH_PSEUDO (1 << 4) /* pseudo headers */ + +typedef enum { + CURLHE_OK, + CURLHE_BADINDEX, /* header exists but not with this index */ + CURLHE_MISSING, /* no such header exists */ + CURLHE_NOHEADERS, /* no headers at all exist (yet) */ + CURLHE_NOREQUEST, /* no request with this number was used */ + CURLHE_OUT_OF_MEMORY, /* out of memory while processing */ + CURLHE_BAD_ARGUMENT, /* a function argument was not okay */ + CURLHE_NOT_BUILT_IN /* if API was disabled in the build */ +} CURLHcode; + +CURL_EXTERN CURLHcode curl_easy_header(CURL *curl, + const char *name, + size_t nameindex, + unsigned int origin, + int request, + struct curl_header **hout); + +CURL_EXTERN struct curl_header *curl_easy_nextheader(CURL *curl, + unsigned int origin, + int request, + struct curl_header *prev); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif /* CURLINC_HEADER_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/mprintf.h b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/mprintf.h new file mode 100644 index 0000000000..9272e74891 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/mprintf.h @@ -0,0 +1,85 @@ +#ifndef CURLINC_MPRINTF_H +#define CURLINC_MPRINTF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include <stdarg.h> +#include <stdio.h> /* needed for FILE */ +#include "curl.h" /* for CURL_EXTERN */ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef CURL_TEMP_PRINTF +#if (defined(__GNUC__) || defined(__clang__) || \ + defined(__IAR_SYSTEMS_ICC__)) && \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(CURL_NO_FMT_CHECKS) +#if defined(__MINGW32__) && !defined(__clang__) +#ifdef __MINGW_PRINTF_FORMAT /* mingw-w64 3.0.0+. Needs stdio.h. */ +#define CURL_TEMP_PRINTF(fmt, arg) \ + __attribute__((format(__MINGW_PRINTF_FORMAT, fmt, arg))) +#else +#define CURL_TEMP_PRINTF(fmt, arg) +#endif +#else +#define CURL_TEMP_PRINTF(fmt, arg) \ + __attribute__((format(printf, fmt, arg))) +#endif +#else +#define CURL_TEMP_PRINTF(fmt, arg) +#endif +#endif + +CURL_EXTERN int curl_mprintf(const char *format, ...) + CURL_TEMP_PRINTF(1, 2); +CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...) + CURL_TEMP_PRINTF(2, 3); +CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...) + CURL_TEMP_PRINTF(2, 3); +CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength, + const char *format, ...) + CURL_TEMP_PRINTF(3, 4); +CURL_EXTERN int curl_mvprintf(const char *format, va_list args) + CURL_TEMP_PRINTF(1, 0); +CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args) + CURL_TEMP_PRINTF(2, 0); +CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args) + CURL_TEMP_PRINTF(2, 0); +CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength, + const char *format, va_list args) + CURL_TEMP_PRINTF(3, 0); +CURL_EXTERN char *curl_maprintf(const char *format, ...) + CURL_TEMP_PRINTF(1, 2); +CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args) + CURL_TEMP_PRINTF(1, 0); + +#undef CURL_TEMP_PRINTF + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif /* CURLINC_MPRINTF_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/multi.h b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/multi.h new file mode 100644 index 0000000000..8cef6e774e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/multi.h @@ -0,0 +1,560 @@ +#ifndef CURLINC_MULTI_H +#define CURLINC_MULTI_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * This is an "external" header file. Do not give away any internals here! + * + * GOALS + * + * o Enable a "pull" interface. The application that uses libcurl decides where + * and when to ask libcurl to get/send data. + * + * o Enable multiple simultaneous transfers in the same thread without making + * it complicated for the application. + * + * o Enable the application to select() on its own file descriptors and curl's + * file descriptors simultaneous easily. + * + */ + +/* + * This header file should not really need to include "curl.h" since curl.h + * itself includes this file and we expect user applications to do #include + * <curl/curl.h> without the need for especially including multi.h. + * + * For some reason we added this include here at one point, and rather than to + * break existing (wrongly written) libcurl applications, we leave it as-is + * but with this warning attached. + */ +#include "curl.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void CURLM; + +typedef enum { + CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or + curl_multi_socket*() soon */ + CURLM_OK, + CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */ + CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */ + CURLM_OUT_OF_MEMORY, /* if you ever get this, you are in deep sh*t */ + CURLM_INTERNAL_ERROR, /* this is a libcurl bug */ + CURLM_BAD_SOCKET, /* the passed in socket argument did not match */ + CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */ + CURLM_ADDED_ALREADY, /* an easy handle already added to a multi handle was + attempted to get added - again */ + CURLM_RECURSIVE_API_CALL, /* an api function was called from inside a + callback */ + CURLM_WAKEUP_FAILURE, /* wakeup is unavailable or failed */ + CURLM_BAD_FUNCTION_ARGUMENT, /* function called with a bad parameter */ + CURLM_ABORTED_BY_CALLBACK, + CURLM_UNRECOVERABLE_POLL, + CURLM_LAST +} CURLMcode; + +/* You can check for CURLM_CALL_MULTI_SOCKET too in the same style it works + for curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */ +#define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM + +/* bitmask bits for CURLMOPT_PIPELINING */ +#define CURLPIPE_NOTHING 0L +#define CURLPIPE_HTTP1 1L +#define CURLPIPE_MULTIPLEX 2L + +typedef enum { + CURLMSG_NONE, /* first, not used */ + CURLMSG_DONE, /* This easy handle has completed. 'result' contains + the CURLcode of the transfer */ + CURLMSG_LAST /* last, not used */ +} CURLMSG; + +struct CURLMsg { + CURLMSG msg; /* what this message means */ + CURL *easy_handle; /* the handle it concerns */ + union { + void *whatever; /* message-specific data */ + CURLcode result; /* return code for transfer */ + } data; +}; +typedef struct CURLMsg CURLMsg; + +/* Based on poll(2) structure and values. + * We do not use pollfd and POLL* constants explicitly + * to cover platforms without poll(). */ +#define CURL_WAIT_POLLIN 0x0001 +#define CURL_WAIT_POLLPRI 0x0002 +#define CURL_WAIT_POLLOUT 0x0004 + +struct curl_waitfd { + curl_socket_t fd; + short events; + short revents; +}; + +/* + * Name: curl_multi_init() + * + * Desc: initialize multi-style curl usage + * + * Returns: a new CURLM handle to use in all 'curl_multi' functions. + */ +CURL_EXTERN CURLM *curl_multi_init(void); + +/* + * Name: curl_multi_add_handle() + * + * Desc: add a standard curl handle to the multi stack + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *m, + CURL *curl); + +/* + * Name: curl_multi_remove_handle() + * + * Desc: removes a curl handle from the multi stack again + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *m, + CURL *curl); + +/* + * Name: curl_multi_fdset() + * + * Desc: Ask curl for its fd_set sets. The app can use these to select() or + * poll() on. We want curl_multi_perform() called as soon as one of + * them are ready. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *m, + fd_set *read_fd_set, + fd_set *write_fd_set, + fd_set *exc_fd_set, + int *max_fd); + +/* + * Name: curl_multi_wait() + * + * Desc: Poll on all fds within a CURLM set as well as any + * additional fds passed to the function. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_wait(CURLM *m, + struct curl_waitfd extra_fds[], + unsigned int extra_nfds, + int timeout_ms, + int *ret); + +/* + * Name: curl_multi_poll() + * + * Desc: Poll on all fds within a CURLM set as well as any + * additional fds passed to the function. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_poll(CURLM *m, + struct curl_waitfd extra_fds[], + unsigned int extra_nfds, + int timeout_ms, + int *ret); + +/* + * Name: curl_multi_wakeup() + * + * Desc: wakes up a sleeping curl_multi_poll call. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_wakeup(CURLM *m); + +/* + * Name: curl_multi_perform() + * + * Desc: When the app thinks there is data available for curl it calls this + * function to read/write whatever there is right now. This returns + * as soon as the reads and writes are done. This function does not + * require that there actually is data available for reading or that + * data can be written, it can be called. It returns the number of + * handles that still transfer data in the second argument's + * integer-pointer. + * + * Returns: CURLMcode type, general multi error code. *NOTE* that this only + * returns errors etc regarding the whole multi stack. There might + * still have occurred problems on individual transfers even when + * this returns OK. + */ +CURL_EXTERN CURLMcode curl_multi_perform(CURLM *m, + int *running_handles); + +/* + * Name: curl_multi_cleanup() + * + * Desc: Cleans up and removes a whole multi stack. It does not free or + * touch any individual easy handles in any way. We need to define + * in what state those handles are going to be if this function is + * called in the middle of a transfer. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *m); + +/* + * Name: curl_multi_info_read() + * + * Desc: Ask the multi handle if there is any messages/informationals from + * the individual transfers. Messages include informationals such as + * error code from the transfer or the fact that a transfer is + * completed. More details on these should be written down as well. + * + * Repeated calls to this function return a new struct each time, + * until a special "end of msgs" struct is returned as a signal that + * there is no more to get at this point. + * + * The data the returned pointer points to does not survive calling + * curl_multi_cleanup(). + * + * The 'CURLMsg' struct is meant to be simple and only contain basic + * information. If more involved information is wanted, we provide + * the particular "transfer handle" in that struct and that + * should/could/would be used in subsequent curl_easy_getinfo() calls + * (or similar). The point being that we must never expose complex + * structs to applications, as then we undoubtably get backwards + * compatibility problems in the future. + * + * Returns: A pointer to a filled-in struct, or NULL if it failed or ran out + * of structs. It also writes the number of messages left in the + * queue (after this read) in the integer the second argument points + * to. + */ +CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *m, + int *msgs_in_queue); + +/* + * Name: curl_multi_strerror() + * + * Desc: The curl_multi_strerror function may be used to turn a CURLMcode + * value into the equivalent human readable error string. This is + * useful for printing meaningful error messages. + * + * Returns: A pointer to a null-terminated error message. + */ +CURL_EXTERN const char *curl_multi_strerror(CURLMcode error); + +/* + * Name: curl_multi_socket() and + * curl_multi_socket_all() + * + * Desc: An alternative version of curl_multi_perform() that allows the + * application to pass in one of the file descriptors that have been + * detected to have "action" on them and let libcurl perform. + * See man page for details. + */ +#define CURL_POLL_NONE 0 +#define CURL_POLL_IN 1 +#define CURL_POLL_OUT 2 +#define CURL_POLL_INOUT 3 +#define CURL_POLL_REMOVE 4 + +#define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD + +#define CURL_CSELECT_IN 0x01 +#define CURL_CSELECT_OUT 0x02 +#define CURL_CSELECT_ERR 0x04 + +typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */ + curl_socket_t s, /* socket */ + int what, /* see above */ + void *userp, /* private callback + pointer */ + void *socketp); /* private socket + pointer */ +/* + * Name: curl_multi_timer_callback + * + * Desc: Called by libcurl whenever the library detects a change in the + * maximum number of milliseconds the app is allowed to wait before + * curl_multi_socket() or curl_multi_perform() must be called + * (to allow libcurl's timed events to take place). + * + * Returns: The callback should return zero. + */ +typedef int (*curl_multi_timer_callback)(CURLM *m, /* multi handle */ + long timeout_ms, /* see above */ + void *userp); /* private callback + pointer */ + +CURL_EXTERN CURLMcode CURL_DEPRECATED(7.19.5, "Use curl_multi_socket_action()") +curl_multi_socket(CURLM *m, curl_socket_t s, int *running_handles); + +CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *m, + curl_socket_t s, + int ev_bitmask, + int *running_handles); + +CURL_EXTERN CURLMcode CURL_DEPRECATED(7.19.5, "Use curl_multi_socket_action()") +curl_multi_socket_all(CURLM *m, int *running_handles); + +#ifndef CURL_ALLOW_OLD_MULTI_SOCKET +/* This macro below was added in 7.16.3 to push users who recompile to use + * the new curl_multi_socket_action() instead of the old curl_multi_socket() + */ +#define curl_multi_socket(x, y, z) curl_multi_socket_action(x, y, 0, z) +#endif + +/* + * Name: curl_multi_timeout() + * + * Desc: Returns the maximum number of milliseconds the app is allowed to + * wait before curl_multi_socket() or curl_multi_perform() must be + * called (to allow libcurl's timed events to take place). + * + * Returns: CURLM error code. + */ +CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *m, + long *timeout_ms); + +typedef enum { + /* This is the socket callback function pointer */ + CURLOPT(CURLMOPT_SOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 1), + + /* This is the argument passed to the socket callback */ + CURLOPT(CURLMOPT_SOCKETDATA, CURLOPTTYPE_OBJECTPOINT, 2), + + /* set to 1 to enable pipelining for this multi handle */ + CURLOPT(CURLMOPT_PIPELINING, CURLOPTTYPE_LONG, 3), + + /* This is the timer callback function pointer */ + CURLOPT(CURLMOPT_TIMERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 4), + + /* This is the argument passed to the timer callback */ + CURLOPT(CURLMOPT_TIMERDATA, CURLOPTTYPE_OBJECTPOINT, 5), + + /* maximum number of entries in the connection cache */ + CURLOPT(CURLMOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 6), + + /* maximum number of (pipelining) connections to one host */ + CURLOPT(CURLMOPT_MAX_HOST_CONNECTIONS, CURLOPTTYPE_LONG, 7), + + /* maximum number of requests in a pipeline */ + CURLOPT(CURLMOPT_MAX_PIPELINE_LENGTH, CURLOPTTYPE_LONG, 8), + + /* a connection with a content-length longer than this + is not considered for pipelining */ + CURLOPT(CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 9), + + /* a connection with a chunk length longer than this + is not considered for pipelining */ + CURLOPT(CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 10), + + /* a list of site names(+port) that are blocked from pipelining */ + CURLOPT(CURLMOPT_PIPELINING_SITE_BL, CURLOPTTYPE_OBJECTPOINT, 11), + + /* a list of server types that are blocked from pipelining */ + CURLOPT(CURLMOPT_PIPELINING_SERVER_BL, CURLOPTTYPE_OBJECTPOINT, 12), + + /* maximum number of open connections in total */ + CURLOPT(CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPTTYPE_LONG, 13), + + /* This is the server push callback function pointer */ + CURLOPT(CURLMOPT_PUSHFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 14), + + /* This is the argument passed to the server push callback */ + CURLOPT(CURLMOPT_PUSHDATA, CURLOPTTYPE_OBJECTPOINT, 15), + + /* maximum number of concurrent streams to support on a connection */ + CURLOPT(CURLMOPT_MAX_CONCURRENT_STREAMS, CURLOPTTYPE_LONG, 16), + + /* network has changed, adjust caches/connection reuse */ + CURLOPT(CURLMOPT_NETWORK_CHANGED, CURLOPTTYPE_LONG, 17), + + /* This is the notify callback function pointer */ + CURLOPT(CURLMOPT_NOTIFYFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 18), + + /* This is the argument passed to the notify callback */ + CURLOPT(CURLMOPT_NOTIFYDATA, CURLOPTTYPE_OBJECTPOINT, 19), + + /* maximum number of threads used with threaded DNS resolver */ + CURLOPT(CURLMOPT_RESOLVE_THREADS_MAX, CURLOPTTYPE_LONG, 20), + + /* set to 1L for not joining threads when multi is cleaned up */ + CURLOPT(CURLMOPT_QUICK_EXIT, CURLOPTTYPE_LONG, 21), + + CURLMOPT_LASTENTRY /* the last unused */ +} CURLMoption; + +/* Definition of bits for the CURLMOPT_NETWORK_CHANGED argument: */ + +/* - CURLMNWC_CLEAR_ALL tells libcurl to clear "everything" that could be + associated with this network, including both connections and DNS data. */ +#define CURLMNWC_CLEAR_ALL (1L << 0) + +/* - CURLMNWC_CLEAR_CONNS tells libcurl to prevent further reuse of existing + connections. Connections that are idle are closed. Ongoing transfers do + continue with the connection they have. */ +#define CURLMNWC_CLEAR_CONNS (1L << 1) + +/* - CURLMNWC_CLEAR_DNS tells libcurl to clear the DNS cache associated with + this multi handle. Ongoing transfers keep using their already resolved + addresses, but future name resolutions are performed again. */ +#define CURLMNWC_CLEAR_DNS (1L << 2) + +/* + * Name: curl_multi_setopt() + * + * Desc: Sets options for the multi handle. + * + * Returns: CURLM error code. + */ +CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *m, + CURLMoption option, ...); + +/* + * Name: curl_multi_assign() + * + * Desc: This function sets an association in the multi handle between the + * given socket and a private pointer of the application. This is + * (only) useful for curl_multi_socket uses. + * + * Returns: CURLM error code. + */ +CURL_EXTERN CURLMcode curl_multi_assign(CURLM *m, + curl_socket_t sockfd, void *sockp); + +/* + * Name: curl_multi_get_handles() + * + * Desc: Returns an allocated array holding all handles currently added to + * the multi handle. Marks the final entry with a NULL pointer. If + * there is no easy handle added to the multi handle, this function + * returns an array with the first entry as a NULL pointer. + * + * Returns: NULL on failure, otherwise a CURL **array pointer + */ +CURL_EXTERN CURL **curl_multi_get_handles(CURLM *m); + +typedef enum { + CURLMINFO_NONE, /* first, never use this */ + /* The number of easy handles currently managed by the multi handle, + * e.g. have been added but not yet removed. */ + CURLMINFO_XFERS_CURRENT = 1, + /* The number of easy handles running, e.g. not done and not queueing. */ + CURLMINFO_XFERS_RUNNING = 2, + /* The number of easy handles waiting to start, e.g. for a connection + * to become available due to limits on parallelism, max connections + * or other factors. */ + CURLMINFO_XFERS_PENDING = 3, + /* The number of easy handles finished, waiting for their results to + * be read via `curl_multi_info_read()`. */ + CURLMINFO_XFERS_DONE = 4, + /* The total number of easy handles added to the multi handle, ever. */ + CURLMINFO_XFERS_ADDED = 5, + + CURLMINFO_LASTENTRY /* the last unused */ +} CURLMinfo_offt; + +/* + * Name: curl_multi_get_offt() + * + * Desc: Retrieves a numeric value for the `CURLMINFO_*` enums. + * + * Returns: CULRM_OK or error when value could not be obtained. + */ +CURL_EXTERN CURLMcode curl_multi_get_offt(CURLM *m, + CURLMinfo_offt info, + curl_off_t *pvalue); + +/* + * Name: curl_push_callback + * + * Desc: This callback gets called when a new stream is being pushed by the + * server. It approves or denies the new stream. It can also decide + * to completely fail the connection. + * + * Returns: CURL_PUSH_OK, CURL_PUSH_DENY or CURL_PUSH_ERROROUT + */ +#define CURL_PUSH_OK 0 +#define CURL_PUSH_DENY 1 +#define CURL_PUSH_ERROROUT 2 /* added in 7.72.0 */ + +struct curl_pushheaders; /* forward declaration only */ + +CURL_EXTERN char *curl_pushheader_bynum(struct curl_pushheaders *h, + size_t num); +CURL_EXTERN char *curl_pushheader_byname(struct curl_pushheaders *h, + const char *name); + +typedef int (*curl_push_callback)(CURL *parent, + CURL *easy, + size_t num_headers, + struct curl_pushheaders *headers, + void *userp); + +/* + * Name: curl_multi_waitfds() + * + * Desc: Ask curl for fds for polling. The app can use these to poll on. + * We want curl_multi_perform() called as soon as one of them are + * ready. Passing zero size allows to get a number of fds. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_waitfds(CURLM *m, + struct curl_waitfd *ufds, + unsigned int size, + unsigned int *fd_count); + +/* + * Notifications dispatched by a multi handle, when enabled. + */ +#define CURLMNOTIFY_INFO_READ 0 +#define CURLMNOTIFY_EASY_DONE 1 + +/* + * Callback to install via CURLMOPT_NOTIFYFUNCTION. + */ +typedef void (*curl_notify_callback)(CURLM *m, + unsigned int notification, + CURL *easy, + void *user_data); + +CURL_EXTERN CURLMcode curl_multi_notify_disable(CURLM *m, + unsigned int notification); + +CURL_EXTERN CURLMcode curl_multi_notify_enable(CURLM *m, + unsigned int notification); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/options.h b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/options.h new file mode 100644 index 0000000000..835a722e91 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/options.h @@ -0,0 +1,70 @@ +#ifndef CURLINC_OPTIONS_H +#define CURLINC_OPTIONS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + CURLOT_LONG, /* long (a range of values) */ + CURLOT_VALUES, /* (a defined set or bitmask) */ + CURLOT_OFF_T, /* curl_off_t (a range of values) */ + CURLOT_OBJECT, /* pointer (void *) */ + CURLOT_STRING, /* (char * to null-terminated buffer) */ + CURLOT_SLIST, /* (struct curl_slist *) */ + CURLOT_CBPTR, /* (void * passed as-is to a callback) */ + CURLOT_BLOB, /* blob (struct curl_blob *) */ + CURLOT_FUNCTION /* function pointer */ +} curl_easytype; + +/* Flag bits */ + +/* "alias" means it is provided for old programs to remain functional, + we prefer another name */ +#define CURLOT_FLAG_ALIAS (1 << 0) + +/* The CURLOPTTYPE_* id ranges can still be used to figure out what type/size + to use for curl_easy_setopt() for the given id */ +struct curl_easyoption { + const char *name; + CURLoption id; + curl_easytype type; + unsigned int flags; +}; + +CURL_EXTERN const struct curl_easyoption * +curl_easy_option_by_name(const char *name); + +CURL_EXTERN const struct curl_easyoption * +curl_easy_option_by_id(CURLoption id); + +CURL_EXTERN const struct curl_easyoption * +curl_easy_option_next(const struct curl_easyoption *prev); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif +#endif /* CURLINC_OPTIONS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/stdcheaders.h b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/stdcheaders.h new file mode 100644 index 0000000000..7451aa3052 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/stdcheaders.h @@ -0,0 +1,35 @@ +#ifndef CURLINC_STDCHEADERS_H +#define CURLINC_STDCHEADERS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include <sys/types.h> + +size_t fread(void *, size_t, size_t, FILE *); +size_t fwrite(const void *, size_t, size_t, FILE *); + +int strcasecmp(const char *, const char *); +int strncasecmp(const char *, const char *, size_t); + +#endif /* CURLINC_STDCHEADERS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/system.h b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/system.h new file mode 100644 index 0000000000..30216ea34c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/system.h @@ -0,0 +1,399 @@ +#ifndef CURLINC_SYSTEM_H +#define CURLINC_SYSTEM_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Try to keep one section per platform, compiler and architecture, otherwise, + * if an existing section is reused for a different one and later on the + * original is adjusted, probably the piggybacking one can be adversely + * changed. + * + * In order to differentiate between platforms/compilers/architectures use + * only compiler built-in predefined preprocessor symbols. + * + * curl_off_t + * ---------- + * + * For any given platform/compiler curl_off_t MUST be typedef'ed to a 64-bit + * wide signed integral data type. The width of this data type must remain + * constant and independent of any possible large file support settings. + * + * As a general rule, curl_off_t shall not be mapped to off_t. This rule shall + * only be violated if off_t is the only 64-bit data type available and the + * size of off_t is independent of large file support settings. Keep your + * build on the safe side avoiding an off_t gating. If you have a 64-bit + * off_t then take for sure that another 64-bit data type exists, dig deeper + * to find it. + * + */ + +#ifdef __DJGPP__ +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +#elif defined(__BORLANDC__) +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +#elif defined(__POCC__) +# ifdef _MSC_VER +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# else +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +#elif defined(__LCC__) +# ifdef __MCST__ /* MCST eLbrus Compiler Collection */ +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 +# else /* Local (or Little) C Compiler */ +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# endif + +#elif defined(macintosh) +# include <ConditionalMacros.h> +# if TYPE_LONGLONG +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# else +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int + +#elif defined(__TANDEM) +# ifndef __LP64 +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# else +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int +# endif + +#elif defined(UNDER_CE) +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +#elif defined(__MINGW32__) +# include <inttypes.h> +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T PRId64 +# define CURL_FORMAT_CURL_OFF_TU PRIu64 +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# define CURL_PULL_SYS_TYPES_H 1 + +#elif defined(__VMS) +# ifdef __VAX +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# else +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int + +#elif defined(__OS400__) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 + +#elif defined(__MVS__) +# ifdef _LONG_LONG +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# else /* _LP64 and default */ +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 + +#elif defined(__370__) +# if defined(__IBMC__) || defined(__IBMCPP__) +# ifdef _LONG_LONG +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# else /* _LP64 and default */ +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 +# endif + +#elif defined(TPF) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +#elif defined(__TINYC__) /* also known as tcc */ +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 + +#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) /* Oracle Solaris Studio */ +# if !defined(__LP64) && (defined(__ILP32) || \ + defined(__i386) || \ + defined(__sparcv8) || \ + defined(__sparcv8plus)) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# elif defined(__LP64) || \ + defined(__amd64) || defined(__sparcv9) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 + +#elif defined(__xlc__) /* IBM xlc compiler */ +# ifndef _LP64 +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# else +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 + +#elif defined(__hpux) /* HP aCC compiler */ +# ifndef _LP64 +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# else +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 + +/* ===================================== */ +/* KEEP MSVC THE PENULTIMATE ENTRY */ +/* ===================================== */ + +#elif defined(_MSC_VER) +# if _MSC_VER >= 1800 +# include <inttypes.h> +# define CURL_FORMAT_CURL_OFF_T PRId64 +# define CURL_FORMAT_CURL_OFF_TU PRIu64 +# else +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# endif +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +/* ===================================== */ +/* KEEP GENERIC GCC THE LAST ENTRY */ +/* ===================================== */ + +#elif defined(__GNUC__) && !defined(_SCO_DS) +# if !defined(__LP64__) && \ + (defined(__ILP32__) || defined(__i386__) || defined(__hppa__) || \ + defined(__ppc__) || defined(__powerpc__) || defined(__arm__) || \ + defined(__sparc__) || defined(__mips__) || defined(__sh__) || \ + defined(__XTENSA__) || \ + (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 4) || \ + (defined(__LONG_MAX__) && __LONG_MAX__ == 2147483647L)) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# if (__GNUC__ >= 4) || \ + ((__GNUC__ == 3) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ >= 4)) +# define CURL_POPCOUNT64(x) __builtin_popcountll(x) +# define CURL_CTZ64(x) __builtin_ctzll(x) +# endif +# elif defined(__LP64__) || \ + defined(__x86_64__) || defined(__ppc64__) || defined(__sparc64__) || \ + defined(__e2k__) || \ + (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 8) || \ + (defined(__LONG_MAX__) && __LONG_MAX__ == 9223372036854775807L) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# if (__GNUC__ >= 4) || \ + ((__GNUC__ == 3) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ >= 4)) +# define CURL_POPCOUNT64(x) __builtin_popcountl(x) +# define CURL_CTZ64(x) __builtin_ctzl(x) +# endif +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 + +#else +/* generic "safe guess" on old 32-bit style */ +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# define CURL_TYPEOF_CURL_SOCKLEN_T int +#endif + +#ifdef _AIX +/* AIX needs <sys/poll.h> */ +#define CURL_PULL_SYS_POLL_H +#endif + +/* CURL_PULL_SYS_TYPES_H is defined above when inclusion of header file + sys/types.h is required here to properly make type definitions below. */ +#ifdef CURL_PULL_SYS_TYPES_H +# include <sys/types.h> +#endif + +/* CURL_PULL_SYS_SOCKET_H is defined above when inclusion of header file + sys/socket.h is required here to properly make type definitions below. */ +#ifdef CURL_PULL_SYS_SOCKET_H +# include <sys/socket.h> +#endif + +/* CURL_PULL_SYS_POLL_H is defined above when inclusion of header file + sys/poll.h is required here to properly make type definitions below. */ +#ifdef CURL_PULL_SYS_POLL_H +# include <sys/poll.h> +#endif + +/* Data type definition of curl_socklen_t. */ +#ifdef CURL_TYPEOF_CURL_SOCKLEN_T + typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t; +#endif + +/* Data type definition of curl_off_t. */ + +#ifdef CURL_TYPEOF_CURL_OFF_T + typedef CURL_TYPEOF_CURL_OFF_T curl_off_t; +#endif + +#endif /* CURLINC_SYSTEM_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/typecheck-gcc.h b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/typecheck-gcc.h new file mode 100644 index 0000000000..f2e4542772 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/typecheck-gcc.h @@ -0,0 +1,964 @@ +#ifndef CURLINC_TYPECHECK_GCC_H +#define CURLINC_TYPECHECK_GCC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* wraps curl_easy_setopt() with type checking */ + +/* To add a new kind of warning, add an + * if(curlcheck_sometype_option(_curl_opt)) + * if(!curlcheck_sometype(value)) + * Wcurl_easy_setopt_err_sometype(); + * block and define curlcheck_sometype_option, curlcheck_sometype and + * Wcurl_easy_setopt_err_sometype below + * + * NOTE: We use two nested 'if' statements here instead of the && operator, in + * order to work around gcc bug #32061. It affects only gcc 4.3.x/4.4.x + * when compiling with -Wlogical-op. + * + * To add an option that uses the same type as an existing option, you need + * to extend the appropriate _curl_*_option macro + */ + +#define curl_easy_setopt(handle, option, value) \ + __extension__({ \ + if(__builtin_constant_p(option)) { \ + CURL_IGNORE_DEPRECATION( \ + if(curlcheck_long_option(option)) \ + if(!curlcheck_long(value)) \ + Wcurl_easy_setopt_err_long(); \ + if(curlcheck_off_t_option(option)) \ + if(!curlcheck_off_t(value)) \ + Wcurl_easy_setopt_err_curl_off_t(); \ + if(curlcheck_string_option(option)) \ + if(!curlcheck_string(value)) \ + Wcurl_easy_setopt_err_string(); \ + if((option) == CURLOPT_PRIVATE) { } \ + if(curlcheck_write_cb_option(option)) \ + if(!curlcheck_write_cb(value)) \ + Wcurl_easy_setopt_err_write_callback(); \ + if(curlcheck_curl_option(option)) \ + if(!curlcheck_curl(value)) \ + Wcurl_easy_setopt_err_curl(); \ + if((option) == CURLOPT_RESOLVER_START_FUNCTION) \ + if(!curlcheck_resolver_start_callback(value)) \ + Wcurl_easy_setopt_err_resolver_start_callback(); \ + if((option) == CURLOPT_READFUNCTION) \ + if(!curlcheck_read_cb(value)) \ + Wcurl_easy_setopt_err_read_cb(); \ + if((option) == CURLOPT_IOCTLFUNCTION) \ + if(!curlcheck_ioctl_cb(value)) \ + Wcurl_easy_setopt_err_ioctl_cb(); \ + if((option) == CURLOPT_SOCKOPTFUNCTION) \ + if(!curlcheck_sockopt_cb(value)) \ + Wcurl_easy_setopt_err_sockopt_cb(); \ + if((option) == CURLOPT_OPENSOCKETFUNCTION) \ + if(!curlcheck_opensocket_cb(value)) \ + Wcurl_easy_setopt_err_opensocket_cb(); \ + if((option) == CURLOPT_PROGRESSFUNCTION) \ + if(!curlcheck_progress_cb(value)) \ + Wcurl_easy_setopt_err_progress_cb(); \ + if((option) == CURLOPT_XFERINFOFUNCTION) \ + if(!curlcheck_xferinfo_cb(value)) \ + Wcurl_easy_setopt_err_xferinfo_cb(); \ + if((option) == CURLOPT_DEBUGFUNCTION) \ + if(!curlcheck_debug_cb(value)) \ + Wcurl_easy_setopt_err_debug_cb(); \ + if((option) == CURLOPT_SSL_CTX_FUNCTION) \ + if(!curlcheck_ssl_ctx_cb(value)) \ + Wcurl_easy_setopt_err_ssl_ctx_cb(); \ + if(curlcheck_conv_cb_option(option)) \ + if(!curlcheck_conv_cb(value)) \ + Wcurl_easy_setopt_err_conv_cb(); \ + if((option) == CURLOPT_SEEKFUNCTION) \ + if(!curlcheck_seek_cb(value)) \ + Wcurl_easy_setopt_err_seek_cb(); \ + if((option) == CURLOPT_CHUNK_BGN_FUNCTION) \ + if(!curlcheck_chunk_bgn_cb(value)) \ + Wcurl_easy_setopt_err_chunk_bgn_cb(); \ + if((option) == CURLOPT_CHUNK_END_FUNCTION) \ + if(!curlcheck_chunk_end_cb(value)) \ + Wcurl_easy_setopt_err_chunk_end_cb(); \ + if((option) == CURLOPT_CLOSESOCKETFUNCTION) \ + if(!curlcheck_close_socket_cb(value)) \ + Wcurl_easy_setopt_err_close_socket_cb(); \ + if((option) == CURLOPT_FNMATCH_FUNCTION) \ + if(!curlcheck_fnmatch_cb(value)) \ + Wcurl_easy_setopt_err_fnmatch_cb(); \ + if((option) == CURLOPT_HSTSREADFUNCTION) \ + if(!curlcheck_hstsread_cb(value)) \ + Wcurl_easy_setopt_err_hstsread_cb(); \ + if((option) == CURLOPT_HSTSWRITEFUNCTION) \ + if(!curlcheck_hstswrite_cb(value)) \ + Wcurl_easy_setopt_err_hstswrite_cb(); \ + if((option) == CURLOPT_SSH_HOSTKEYFUNCTION) \ + if(!curlcheck_ssh_hostkey_cb(value)) \ + Wcurl_easy_setopt_err_ssh_hostkey_cb(); \ + if((option) == CURLOPT_SSH_KEYFUNCTION) \ + if(!curlcheck_ssh_key_cb(value)) \ + Wcurl_easy_setopt_err_ssh_key_cb(); \ + if((option) == CURLOPT_INTERLEAVEFUNCTION) \ + if(!curlcheck_interleave_cb(value)) \ + Wcurl_easy_setopt_err_interleave_cb(); \ + if((option) == CURLOPT_PREREQFUNCTION) \ + if(!curlcheck_prereq_cb(value)) \ + Wcurl_easy_setopt_err_prereq_cb(); \ + if((option) == CURLOPT_TRAILERFUNCTION) \ + if(!curlcheck_trailer_cb(value)) \ + Wcurl_easy_setopt_err_trailer_cb(); \ + if(curlcheck_cb_data_option(option)) \ + if(!curlcheck_cb_data(value)) \ + Wcurl_easy_setopt_err_cb_data(); \ + if((option) == CURLOPT_ERRORBUFFER) \ + if(!curlcheck_error_buffer(value)) \ + Wcurl_easy_setopt_err_error_buffer(); \ + if((option) == CURLOPT_CURLU) \ + if(!curlcheck_ptr((value), CURLU)) \ + Wcurl_easy_setopt_err_curlu(); \ + if((option) == CURLOPT_STDERR) \ + if(!curlcheck_FILE(value)) \ + Wcurl_easy_setopt_err_FILE(); \ + if(curlcheck_postfields_option(option)) \ + if(!curlcheck_postfields(value)) \ + Wcurl_easy_setopt_err_postfields(); \ + if((option) == CURLOPT_HTTPPOST) \ + if(!curlcheck_arr((value), struct curl_httppost)) \ + Wcurl_easy_setopt_err_curl_httpost(); \ + if((option) == CURLOPT_MIMEPOST) \ + if(!curlcheck_ptr((value), curl_mime)) \ + Wcurl_easy_setopt_err_curl_mimepost(); \ + if(curlcheck_slist_option(option)) \ + if(!curlcheck_arr((value), struct curl_slist)) \ + Wcurl_easy_setopt_err_curl_slist(); \ + if((option) == CURLOPT_SHARE) \ + if(!curlcheck_ptr((value), CURLSH)) \ + Wcurl_easy_setopt_err_CURLSH(); \ + ) \ + } \ + (curl_easy_setopt)(handle, option, value); \ + }) + +/* wraps curl_easy_getinfo() with type checking */ +#define curl_easy_getinfo(handle, info, arg) \ + __extension__({ \ + if(__builtin_constant_p(info)) { \ + CURL_IGNORE_DEPRECATION( \ + if(curlcheck_string_info(info)) \ + if(!curlcheck_arr((arg), char *)) \ + Wcurl_easy_getinfo_err_string(); \ + if(curlcheck_long_info(info)) \ + if(!curlcheck_arr((arg), long)) \ + Wcurl_easy_getinfo_err_long(); \ + if(curlcheck_double_info(info)) \ + if(!curlcheck_arr((arg), double)) \ + Wcurl_easy_getinfo_err_double(); \ + if(curlcheck_slist_info(info)) \ + if(!curlcheck_arr((arg), struct curl_slist *)) \ + Wcurl_easy_getinfo_err_curl_slist(); \ + if(curlcheck_tlssessioninfo_info(info)) \ + if(!curlcheck_arr((arg), struct curl_tlssessioninfo *)) \ + Wcurl_easy_getinfo_err_curl_tlssessioninfo(); \ + if(curlcheck_certinfo_info(info)) \ + if(!curlcheck_arr((arg), struct curl_certinfo *)) \ + Wcurl_easy_getinfo_err_curl_certinfo(); \ + if(curlcheck_socket_info(info)) \ + if(!curlcheck_arr((arg), curl_socket_t)) \ + Wcurl_easy_getinfo_err_curl_socket(); \ + if(curlcheck_off_t_info(info)) \ + if(!curlcheck_arr((arg), curl_off_t)) \ + Wcurl_easy_getinfo_err_curl_off_t(); \ + ) \ + } \ + (curl_easy_getinfo)(handle, info, arg); \ + }) + +#define curl_multi_setopt(handle, option, value) \ + __extension__({ \ + if(__builtin_constant_p(option)) { \ + if(curlcheck_long_option(option)) \ + if(!curlcheck_long(value)) \ + Wcurl_multi_setopt_err_long(); \ + if(curlcheck_off_t_option(option)) \ + if(!curlcheck_off_t(value)) \ + Wcurl_multi_setopt_err_curl_off_t(); \ + if(curlcheck_multicb_data_option(option)) \ + if(!curlcheck_cb_data(value)) \ + Wcurl_multi_setopt_err_cb_data(); \ + if(curlcheck_charpp_option(option)) \ + if(!curlcheck_ptrptr(value, char)) \ + Wcurl_multi_setopt_err_charpp(); \ + if((option) == CURLMOPT_NOTIFYFUNCTION) \ + if(!curlcheck_multinotify_cb(value)) \ + Wcurl_multi_setopt_err_notifycb(); \ + if((option) == CURLMOPT_PUSHFUNCTION) \ + if(!curlcheck_multipush_cb(value)) \ + Wcurl_multi_setopt_err_pushcb(); \ + if((option) == CURLMOPT_SOCKETFUNCTION) \ + if(!curlcheck_multisocket_cb(value)) \ + Wcurl_multi_setopt_err_socketcb(); \ + if((option) == CURLMOPT_TIMERFUNCTION) \ + if(!curlcheck_multitimer_cb(value)) \ + Wcurl_multi_setopt_err_timercb(); \ + } \ + (curl_multi_setopt)(handle, option, value); \ + }) + +/* evaluates to true if the option takes a data argument to pass to a + callback */ +#define curlcheck_multicb_data_option(option) \ + ((option) == CURLMOPT_NOTIFYDATA || \ + (option) == CURLMOPT_PUSHDATA || \ + (option) == CURLMOPT_SOCKETDATA || \ + (option) == CURLMOPT_TIMERDATA || \ + 0) + +/* evaluates to true if the option takes a char ** argument */ +#define curlcheck_charpp_option(option) \ + ((option) == CURLMOPT_PIPELINING_SERVER_BL || \ + (option) == CURLMOPT_PIPELINING_SITE_BL || \ + 0) + +/* evaluates to true if expr is of type curl_multi_timer_callback */ +#define curlcheck_multitimer_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_multi_timer_callback)) + +/* evaluates to true if expr is of type curl_socket_callback */ +#define curlcheck_multisocket_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_socket_callback)) + +/* evaluates to true if expr is of type curl_push_callback */ +#define curlcheck_multipush_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_push_callback)) + +/* evaluates to true if expr is of type curl_push_callback */ +#define curlcheck_multinotify_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_notify_callback)) + +/* + * Make sure that the functions are called with three arguments + */ +#define curl_share_setopt(share, opt, param) \ + (curl_share_setopt)(share, opt, param) + +/* the actual warnings, triggered by calling the Wcurl_easy_setopt_err* + * functions */ + +/* To define a new warning, use _CURL_WARNING(identifier, "message") */ +#define CURLWARNING(id, message) \ + static void __attribute__((__warning__(message))) \ + __attribute__((__unused__)) __attribute__((__noinline__)) \ + id(void) { __asm__(""); } + +CURLWARNING(Wcurl_multi_setopt_err_long, + "curl_multi_setopt expects a long argument") +CURLWARNING(Wcurl_multi_setopt_err_curl_off_t, + "curl_multi_setopt expects a curl_off_t argument") +CURLWARNING(Wcurl_multi_setopt_err_cb_data, + "curl_multi_setopt expects a 'void *' argument") +CURLWARNING(Wcurl_multi_setopt_err_charpp, + "curl_multi_setopt expects a 'char **' argument") +CURLWARNING(Wcurl_multi_setopt_err_pushcb, + "curl_multi_setopt expects a curl_push_callback argument") +CURLWARNING(Wcurl_multi_setopt_err_notifycb, + "curl_multi_setopt expects a curl_notify_callback argument") +CURLWARNING(Wcurl_multi_setopt_err_socketcb, + "curl_multi_setopt expects a curl_socket_callback argument") +CURLWARNING(Wcurl_multi_setopt_err_timercb, + "curl_multi_setopt expects a curl_multi_timer_callback argument") + +CURLWARNING(Wcurl_easy_setopt_err_long, + "curl_easy_setopt expects a long argument") +CURLWARNING(Wcurl_easy_setopt_err_curl_off_t, + "curl_easy_setopt expects a curl_off_t argument") +CURLWARNING(Wcurl_easy_setopt_err_string, + "curl_easy_setopt expects a " + "string ('char *' or char[]) argument") +CURLWARNING(Wcurl_easy_setopt_err_write_callback, + "curl_easy_setopt expects a curl_write_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_resolver_start_callback, + "curl_easy_setopt expects a " + "curl_resolver_start_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_read_cb, + "curl_easy_setopt expects a curl_read_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_ioctl_cb, + "curl_easy_setopt expects a curl_ioctl_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_sockopt_cb, + "curl_easy_setopt expects a curl_sockopt_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_opensocket_cb, + "curl_easy_setopt expects a " + "curl_opensocket_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_progress_cb, + "curl_easy_setopt expects a curl_progress_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_xferinfo_cb, + "curl_easy_setopt expects a curl_xferinfo_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_debug_cb, + "curl_easy_setopt expects a curl_debug_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_ssl_ctx_cb, + "curl_easy_setopt expects a curl_ssl_ctx_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_conv_cb, + "curl_easy_setopt expects a curl_conv_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_seek_cb, + "curl_easy_setopt expects a curl_seek_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_cb_data, + "curl_easy_setopt expects a " + "private data pointer as argument") +CURLWARNING(Wcurl_easy_setopt_err_chunk_bgn_cb, + "curl_easy_setopt expects a curl_chunk_bgn_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_chunk_end_cb, + "curl_easy_setopt expects a curl_chunk_end_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_close_socket_cb, + "curl_easy_setopt expects a curl_closesocket_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_fnmatch_cb, + "curl_easy_setopt expects a curl_fnmatch_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_hstsread_cb, + "curl_easy_setopt expects a curl_hstsread_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_hstswrite_cb, + "curl_easy_setopt expects a curl_hstswrite_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_ssh_key_cb, + "curl_easy_setopt expects a curl_sshkeycallback argument") +CURLWARNING(Wcurl_easy_setopt_err_ssh_hostkey_cb, + "curl_easy_setopt expects a curl_sshhostkeycallback argument") +CURLWARNING(Wcurl_easy_setopt_err_interleave_cb, + "curl_easy_setopt expects a curl_interleave_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_prereq_cb, + "curl_easy_setopt expects a curl_prereq_callback argument") +CURLWARNING(Wcurl_easy_setopt_err_trailer_cb, + "curl_easy_setopt expects a curl_trailerfunc_ok argument") +CURLWARNING(Wcurl_easy_setopt_err_error_buffer, + "curl_easy_setopt expects a " + "char buffer of CURL_ERROR_SIZE as argument") +CURLWARNING(Wcurl_easy_setopt_err_curlu, + "curl_easy_setopt expects a 'CURLU *' argument") +CURLWARNING(Wcurl_easy_setopt_err_curl, + "curl_easy_setopt expects a 'CURL *' argument") +CURLWARNING(Wcurl_easy_setopt_err_FILE, + "curl_easy_setopt expects a 'FILE *' argument") +CURLWARNING(Wcurl_easy_setopt_err_postfields, + "curl_easy_setopt expects a 'void *' or 'char *' argument") +CURLWARNING(Wcurl_easy_setopt_err_curl_httpost, + "curl_easy_setopt expects a 'struct curl_httppost *' " + "argument") +CURLWARNING(Wcurl_easy_setopt_err_curl_mimepost, + "curl_easy_setopt expects a 'curl_mime *' " + "argument") +CURLWARNING(Wcurl_easy_setopt_err_curl_slist, + "curl_easy_setopt expects a 'struct curl_slist *' argument") +CURLWARNING(Wcurl_easy_setopt_err_CURLSH, + "curl_easy_setopt expects a CURLSH* argument") +CURLWARNING(Wcurl_easy_getinfo_err_string, + "curl_easy_getinfo expects a pointer to 'char *'") +CURLWARNING(Wcurl_easy_getinfo_err_long, + "curl_easy_getinfo expects a pointer to long") +CURLWARNING(Wcurl_easy_getinfo_err_double, + "curl_easy_getinfo expects a pointer to double") +CURLWARNING(Wcurl_easy_getinfo_err_curl_slist, + "curl_easy_getinfo expects a pointer to 'struct curl_slist *'") +CURLWARNING(Wcurl_easy_getinfo_err_curl_tlssessioninfo, + "curl_easy_getinfo expects a pointer to " + "'struct curl_tlssessioninfo *'") +CURLWARNING(Wcurl_easy_getinfo_err_curl_certinfo, + "curl_easy_getinfo expects a pointer to " + "'struct curl_certinfo *'") +CURLWARNING(Wcurl_easy_getinfo_err_curl_socket, + "curl_easy_getinfo expects a pointer to curl_socket_t") +CURLWARNING(Wcurl_easy_getinfo_err_curl_off_t, + "curl_easy_getinfo expects a pointer to curl_off_t") + +/* groups of curl_easy_setops options that take the same type of argument */ + +/* evaluates to true if option takes a long argument */ +#define curlcheck_long_option(option) \ + (0 < (option) && (option) < CURLOPTTYPE_OBJECTPOINT) + +#define curlcheck_off_t_option(option) \ + (((option) > CURLOPTTYPE_OFF_T) && ((option) < CURLOPTTYPE_BLOB)) + +/* option takes a CURL * argument */ +#define curlcheck_curl_option(option) \ + ((option) == CURLOPT_STREAM_DEPENDS || \ + (option) == CURLOPT_STREAM_DEPENDS_E || \ + 0) + +/* evaluates to true if option takes a char* argument */ +#define curlcheck_string_option(option) \ + ((option) == CURLOPT_ABSTRACT_UNIX_SOCKET || \ + (option) == CURLOPT_ACCEPT_ENCODING || \ + (option) == CURLOPT_ALTSVC || \ + (option) == CURLOPT_CAINFO || \ + (option) == CURLOPT_CAPATH || \ + (option) == CURLOPT_COOKIE || \ + (option) == CURLOPT_COOKIEFILE || \ + (option) == CURLOPT_COOKIEJAR || \ + (option) == CURLOPT_COOKIELIST || \ + (option) == CURLOPT_CRLFILE || \ + (option) == CURLOPT_CUSTOMREQUEST || \ + (option) == CURLOPT_DEFAULT_PROTOCOL || \ + (option) == CURLOPT_DNS_INTERFACE || \ + (option) == CURLOPT_DNS_LOCAL_IP4 || \ + (option) == CURLOPT_DNS_LOCAL_IP6 || \ + (option) == CURLOPT_DNS_SERVERS || \ + (option) == CURLOPT_DOH_URL || \ + (option) == CURLOPT_ECH || \ + (option) == CURLOPT_EGDSOCKET || \ + (option) == CURLOPT_FTP_ACCOUNT || \ + (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \ + (option) == CURLOPT_FTPPORT || \ + (option) == CURLOPT_HAPROXY_CLIENT_IP || \ + (option) == CURLOPT_HSTS || \ + (option) == CURLOPT_INTERFACE || \ + (option) == CURLOPT_ISSUERCERT || \ + (option) == CURLOPT_KEYPASSWD || \ + (option) == CURLOPT_KRBLEVEL || \ + (option) == CURLOPT_LOGIN_OPTIONS || \ + (option) == CURLOPT_MAIL_AUTH || \ + (option) == CURLOPT_MAIL_FROM || \ + (option) == CURLOPT_NETRC_FILE || \ + (option) == CURLOPT_NOPROXY || \ + (option) == CURLOPT_PASSWORD || \ + (option) == CURLOPT_PINNEDPUBLICKEY || \ + (option) == CURLOPT_PRE_PROXY || \ + (option) == CURLOPT_PROTOCOLS_STR || \ + (option) == CURLOPT_PROXY || \ + (option) == CURLOPT_PROXY_CAINFO || \ + (option) == CURLOPT_PROXY_CAPATH || \ + (option) == CURLOPT_PROXY_CRLFILE || \ + (option) == CURLOPT_PROXY_ISSUERCERT || \ + (option) == CURLOPT_PROXY_KEYPASSWD || \ + (option) == CURLOPT_PROXY_PINNEDPUBLICKEY || \ + (option) == CURLOPT_PROXY_SERVICE_NAME || \ + (option) == CURLOPT_PROXY_SSL_CIPHER_LIST || \ + (option) == CURLOPT_PROXY_SSLCERT || \ + (option) == CURLOPT_PROXY_SSLCERTTYPE || \ + (option) == CURLOPT_PROXY_SSLKEY || \ + (option) == CURLOPT_PROXY_SSLKEYTYPE || \ + (option) == CURLOPT_PROXY_TLS13_CIPHERS || \ + (option) == CURLOPT_PROXY_TLSAUTH_PASSWORD || \ + (option) == CURLOPT_PROXY_TLSAUTH_TYPE || \ + (option) == CURLOPT_PROXY_TLSAUTH_USERNAME || \ + (option) == CURLOPT_PROXYPASSWORD || \ + (option) == CURLOPT_PROXYUSERNAME || \ + (option) == CURLOPT_PROXYUSERPWD || \ + (option) == CURLOPT_RANDOM_FILE || \ + (option) == CURLOPT_RANGE || \ + (option) == CURLOPT_REDIR_PROTOCOLS_STR || \ + (option) == CURLOPT_REFERER || \ + (option) == CURLOPT_REQUEST_TARGET || \ + (option) == CURLOPT_RTSP_SESSION_ID || \ + (option) == CURLOPT_RTSP_STREAM_URI || \ + (option) == CURLOPT_RTSP_TRANSPORT || \ + (option) == CURLOPT_SASL_AUTHZID || \ + (option) == CURLOPT_SERVICE_NAME || \ + (option) == CURLOPT_SOCKS5_GSSAPI_SERVICE || \ + (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 || \ + (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 || \ + (option) == CURLOPT_SSH_KNOWNHOSTS || \ + (option) == CURLOPT_SSH_PRIVATE_KEYFILE || \ + (option) == CURLOPT_SSH_PUBLIC_KEYFILE || \ + (option) == CURLOPT_SSLCERT || \ + (option) == CURLOPT_SSLCERTTYPE || \ + (option) == CURLOPT_SSLENGINE || \ + (option) == CURLOPT_SSLKEY || \ + (option) == CURLOPT_SSLKEYTYPE || \ + (option) == CURLOPT_SSL_CIPHER_LIST || \ + (option) == CURLOPT_SSL_EC_CURVES || \ + (option) == CURLOPT_SSL_SIGNATURE_ALGORITHMS || \ + (option) == CURLOPT_TLS13_CIPHERS || \ + (option) == CURLOPT_TLSAUTH_PASSWORD || \ + (option) == CURLOPT_TLSAUTH_TYPE || \ + (option) == CURLOPT_TLSAUTH_USERNAME || \ + (option) == CURLOPT_UNIX_SOCKET_PATH || \ + (option) == CURLOPT_URL || \ + (option) == CURLOPT_USERAGENT || \ + (option) == CURLOPT_USERNAME || \ + (option) == CURLOPT_AWS_SIGV4 || \ + (option) == CURLOPT_HTTPSIG_HEADERS || \ + (option) == CURLOPT_HTTPSIG_KEY || \ + (option) == CURLOPT_HTTPSIG_KEYID || \ + (option) == CURLOPT_USERPWD || \ + (option) == CURLOPT_XOAUTH2_BEARER || \ + 0) + +/* evaluates to true if option takes a curl_write_callback argument */ +#define curlcheck_write_cb_option(option) \ + ((option) == CURLOPT_HEADERFUNCTION || \ + (option) == CURLOPT_WRITEFUNCTION) + +/* evaluates to true if option takes a curl_conv_callback argument */ +#define curlcheck_conv_cb_option(option) \ + ((option) == CURLOPT_CONV_TO_NETWORK_FUNCTION || \ + (option) == CURLOPT_CONV_FROM_NETWORK_FUNCTION || \ + (option) == CURLOPT_CONV_FROM_UTF8_FUNCTION) + +/* evaluates to true if option takes a data argument to pass to a callback */ +#define curlcheck_cb_data_option(option) \ + ((option) == CURLOPT_CHUNK_DATA || \ + (option) == CURLOPT_CLOSESOCKETDATA || \ + (option) == CURLOPT_DEBUGDATA || \ + (option) == CURLOPT_FNMATCH_DATA || \ + (option) == CURLOPT_HEADERDATA || \ + (option) == CURLOPT_HSTSREADDATA || \ + (option) == CURLOPT_HSTSWRITEDATA || \ + (option) == CURLOPT_INTERLEAVEDATA || \ + (option) == CURLOPT_IOCTLDATA || \ + (option) == CURLOPT_OPENSOCKETDATA || \ + (option) == CURLOPT_PREREQDATA || \ + (option) == CURLOPT_XFERINFODATA || \ + (option) == CURLOPT_READDATA || \ + (option) == CURLOPT_SEEKDATA || \ + (option) == CURLOPT_SOCKOPTDATA || \ + (option) == CURLOPT_SSH_KEYDATA || \ + (option) == CURLOPT_SSL_CTX_DATA || \ + (option) == CURLOPT_WRITEDATA || \ + (option) == CURLOPT_RESOLVER_START_DATA || \ + (option) == CURLOPT_TRAILERDATA || \ + (option) == CURLOPT_SSH_HOSTKEYDATA || \ + 0) + +/* evaluates to true if option takes a POST data argument (void* or char*) */ +#define curlcheck_postfields_option(option) \ + ((option) == CURLOPT_POSTFIELDS || \ + (option) == CURLOPT_COPYPOSTFIELDS || \ + 0) + +/* evaluates to true if option takes a struct curl_slist * argument */ +#define curlcheck_slist_option(option) \ + ((option) == CURLOPT_HTTP200ALIASES || \ + (option) == CURLOPT_HTTPHEADER || \ + (option) == CURLOPT_MAIL_RCPT || \ + (option) == CURLOPT_POSTQUOTE || \ + (option) == CURLOPT_PREQUOTE || \ + (option) == CURLOPT_PROXYHEADER || \ + (option) == CURLOPT_QUOTE || \ + (option) == CURLOPT_RESOLVE || \ + (option) == CURLOPT_TELNETOPTIONS || \ + (option) == CURLOPT_CONNECT_TO || \ + 0) + +/* groups of curl_easy_getinfo infos that take the same type of argument */ + +/* evaluates to true if info expects a pointer to char * argument */ +#define curlcheck_string_info(info) \ + (CURLINFO_STRING < (info) && (info) < CURLINFO_LONG && \ + (info) != CURLINFO_PRIVATE) + +/* evaluates to true if info expects a pointer to long argument */ +#define curlcheck_long_info(info) \ + (CURLINFO_LONG < (info) && (info) < CURLINFO_DOUBLE) + +/* evaluates to true if info expects a pointer to double argument */ +#define curlcheck_double_info(info) \ + (CURLINFO_DOUBLE < (info) && (info) < CURLINFO_SLIST) + +/* true if info expects a pointer to struct curl_slist * argument */ +#define curlcheck_slist_info(info) \ + (((info) == CURLINFO_SSL_ENGINES) || \ + ((info) == CURLINFO_COOKIELIST)) + +/* true if info expects a pointer to struct curl_tlssessioninfo * argument */ +#define curlcheck_tlssessioninfo_info(info) \ + (((info) == CURLINFO_TLS_SSL_PTR) || \ + ((info) == CURLINFO_TLS_SESSION)) + +/* true if info expects a pointer to struct curl_certinfo * argument */ +#define curlcheck_certinfo_info(info) ((info) == CURLINFO_CERTINFO) + +/* true if info expects a pointer to struct curl_socket_t argument */ +#define curlcheck_socket_info(info) \ + (CURLINFO_SOCKET < (info) && (info) < CURLINFO_OFF_T) + +/* true if info expects a pointer to curl_off_t argument */ +#define curlcheck_off_t_info(info) \ + (CURLINFO_OFF_T < (info)) + +/* + * typecheck helpers -- check whether given expression has requested type + */ + +/* For pointers, you can use the curlcheck_ptr/curlcheck_arr macros, + * otherwise define a new macro. Search for __builtin_types_compatible_p + * in the GCC manual. + * NOTE: these macros MUST NOT EVALUATE their arguments! The argument is + * the actual expression passed to the curl_easy_setopt macro. This + * means that you can only apply the sizeof and __typeof__ operators, no + * == or whatsoever. + */ + +/* XXX: should evaluate to true if expr is a pointer or a char[] array */ +#define curlcheck_any_ptr(expr) \ + (sizeof(expr) == sizeof(void *) || \ + __builtin_types_compatible_p(__typeof__(expr), char[])) + +/* evaluates to true if expr is NULL */ +/* XXX: must not evaluate expr, so this check is not accurate */ +#define curlcheck_NULL(expr) \ + (__builtin_types_compatible_p(__typeof__(expr), __typeof__(NULL))) + +/* evaluates to true if expr is type*, const type* or NULL */ +#define curlcheck_ptr(expr, type) \ + (curlcheck_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), type *) || \ + __builtin_types_compatible_p(__typeof__(expr), const type *)) + +/* evaluates to true if expr is type**, const type** or NULL */ +#define curlcheck_ptrptr(expr, type) \ + (curlcheck_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), type **) || \ + __builtin_types_compatible_p(__typeof__(expr), type *[]) || \ + __builtin_types_compatible_p(__typeof__(expr), const type *[]) || \ + __builtin_types_compatible_p(__typeof__(expr), const type **)) + +/* evaluates to true if expr is one of type[], type*, NULL or const type* */ +#define curlcheck_arr(expr, type) \ + (curlcheck_ptr((expr), type) || \ + __builtin_types_compatible_p(__typeof__(expr), type [])) + +/* evaluates to true if expr is a string */ +#define curlcheck_string(expr) \ + (curlcheck_arr((expr), char) || \ + curlcheck_arr((expr), signed char) || \ + curlcheck_arr((expr), unsigned char)) + +/* evaluates to true if expr is a CURL * */ +#define curlcheck_curl(expr) \ + (curlcheck_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), CURL *)) + +/* evaluates to true if expr is a long (no matter the signedness) + * XXX: for now, int is also accepted (and therefore short and char, which + * are promoted to int when passed to a variadic function) */ +#define curlcheck_long(expr) \ + ( \ + ((sizeof(long) != sizeof(int)) && \ + (__builtin_types_compatible_p(__typeof__(expr), long) || \ + __builtin_types_compatible_p(__typeof__(expr), signed long) || \ + __builtin_types_compatible_p(__typeof__(expr), unsigned long))) \ + || \ + ((sizeof(long) == sizeof(int)) && \ + (__builtin_types_compatible_p(__typeof__(expr), long) || \ + __builtin_types_compatible_p(__typeof__(expr), signed long) || \ + __builtin_types_compatible_p(__typeof__(expr), unsigned long) || \ + __builtin_types_compatible_p(__typeof__(expr), int) || \ + __builtin_types_compatible_p(__typeof__(expr), signed int) || \ + __builtin_types_compatible_p(__typeof__(expr), unsigned int) || \ + __builtin_types_compatible_p(__typeof__(expr), short) || \ + __builtin_types_compatible_p(__typeof__(expr), signed short) || \ + __builtin_types_compatible_p(__typeof__(expr), unsigned short) || \ + __builtin_types_compatible_p(__typeof__(expr), char) || \ + __builtin_types_compatible_p(__typeof__(expr), signed char) || \ + __builtin_types_compatible_p(__typeof__(expr), unsigned char))) \ + ) + +/* evaluates to true if expr is of type curl_off_t */ +#define curlcheck_off_t(expr) \ + (__builtin_types_compatible_p(__typeof__(expr), curl_off_t)) + +/* evaluates to true if expr is abuffer suitable for CURLOPT_ERRORBUFFER */ +/* XXX: also check size of a char[] array? */ +#define curlcheck_error_buffer(expr) \ + (curlcheck_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), char *) || \ + __builtin_types_compatible_p(__typeof__(expr), char[])) + +/* evaluates to true if expr is of type (const) void* or (const) FILE* */ +#if 0 +#define curlcheck_cb_data(expr) \ + (curlcheck_ptr((expr), void) || \ + curlcheck_ptr((expr), FILE)) +#else /* be less strict */ +#define curlcheck_cb_data(expr) \ + curlcheck_any_ptr(expr) +#endif + +/* evaluates to true if expr is of type FILE* */ +#define curlcheck_FILE(expr) \ + (curlcheck_NULL(expr) || \ + (__builtin_types_compatible_p(__typeof__(expr), FILE *))) + +/* evaluates to true if expr can be passed as POST data (void* or char*) */ +#define curlcheck_postfields(expr) \ + (curlcheck_ptr((expr), void) || \ + curlcheck_arr((expr), char) || \ + curlcheck_arr((expr), unsigned char)) + +/* helper: __builtin_types_compatible_p distinguishes between functions and + * function pointers, hide it */ +#define curlcheck_cb_compatible(func, type) \ + (__builtin_types_compatible_p(__typeof__(func), type) || \ + __builtin_types_compatible_p(__typeof__(func) *, type)) + +/* evaluates to true if expr is of type curl_resolver_start_callback */ +#define curlcheck_resolver_start_callback(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_resolver_start_callback)) + +/* evaluates to true if expr is of type curl_read_callback or "similar" */ +#define curlcheck_read_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), __typeof__(fread) *) || \ + curlcheck_cb_compatible((expr), curl_read_callback) || \ + curlcheck_cb_compatible((expr), Wcurl_read_callback1) || \ + curlcheck_cb_compatible((expr), Wcurl_read_callback2) || \ + curlcheck_cb_compatible((expr), Wcurl_read_callback3) || \ + curlcheck_cb_compatible((expr), Wcurl_read_callback4) || \ + curlcheck_cb_compatible((expr), Wcurl_read_callback5) || \ + curlcheck_cb_compatible((expr), Wcurl_read_callback6)) +typedef size_t (*Wcurl_read_callback1)(char *, size_t, size_t, void *); +typedef size_t (*Wcurl_read_callback2)(char *, size_t, size_t, const void *); +typedef size_t (*Wcurl_read_callback3)(char *, size_t, size_t, FILE *); +typedef size_t (*Wcurl_read_callback4)(void *, size_t, size_t, void *); +typedef size_t (*Wcurl_read_callback5)(void *, size_t, size_t, const void *); +typedef size_t (*Wcurl_read_callback6)(void *, size_t, size_t, FILE *); + +/* evaluates to true if expr is of type curl_write_callback or "similar" */ +#define curlcheck_write_cb(expr) \ + (curlcheck_read_cb(expr) || \ + curlcheck_cb_compatible((expr), __typeof__(fwrite) *) || \ + curlcheck_cb_compatible((expr), curl_write_callback) || \ + curlcheck_cb_compatible((expr), Wcurl_write_callback1) || \ + curlcheck_cb_compatible((expr), Wcurl_write_callback2) || \ + curlcheck_cb_compatible((expr), Wcurl_write_callback3) || \ + curlcheck_cb_compatible((expr), Wcurl_write_callback4) || \ + curlcheck_cb_compatible((expr), Wcurl_write_callback5) || \ + curlcheck_cb_compatible((expr), Wcurl_write_callback6)) +typedef size_t (*Wcurl_write_callback1)(const char *, size_t, size_t, void *); +typedef size_t (*Wcurl_write_callback2)(const char *, size_t, size_t, + const void *); +typedef size_t (*Wcurl_write_callback3)(const char *, size_t, size_t, FILE *); +typedef size_t (*Wcurl_write_callback4)(const void *, size_t, size_t, void *); +typedef size_t (*Wcurl_write_callback5)(const void *, size_t, size_t, + const void *); +typedef size_t (*Wcurl_write_callback6)(const void *, size_t, size_t, FILE *); + +/* evaluates to true if expr is of type curl_ioctl_callback or "similar" */ +#define curlcheck_ioctl_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_ioctl_callback) || \ + curlcheck_cb_compatible((expr), Wcurl_ioctl_callback1) || \ + curlcheck_cb_compatible((expr), Wcurl_ioctl_callback2) || \ + curlcheck_cb_compatible((expr), Wcurl_ioctl_callback3) || \ + curlcheck_cb_compatible((expr), Wcurl_ioctl_callback4)) +typedef curlioerr (*Wcurl_ioctl_callback1)(CURL *, int, void *); +typedef curlioerr (*Wcurl_ioctl_callback2)(CURL *, int, const void *); +typedef curlioerr (*Wcurl_ioctl_callback3)(CURL *, curliocmd, void *); +typedef curlioerr (*Wcurl_ioctl_callback4)(CURL *, curliocmd, const void *); + +/* evaluates to true if expr is of type curl_sockopt_callback or "similar" */ +#define curlcheck_sockopt_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_sockopt_callback) || \ + curlcheck_cb_compatible((expr), Wcurl_sockopt_callback1) || \ + curlcheck_cb_compatible((expr), Wcurl_sockopt_callback2)) +typedef int (*Wcurl_sockopt_callback1)(void *, curl_socket_t, curlsocktype); +typedef int (*Wcurl_sockopt_callback2)(const void *, curl_socket_t, + curlsocktype); + +/* evaluates to true if expr is of type curl_opensocket_callback or + "similar" */ +#define curlcheck_opensocket_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_opensocket_callback) || \ + curlcheck_cb_compatible((expr), Wcurl_opensocket_callback1) || \ + curlcheck_cb_compatible((expr), Wcurl_opensocket_callback2) || \ + curlcheck_cb_compatible((expr), Wcurl_opensocket_callback3) || \ + curlcheck_cb_compatible((expr), Wcurl_opensocket_callback4)) +typedef curl_socket_t (*Wcurl_opensocket_callback1) + (void *, curlsocktype, struct curl_sockaddr *); +typedef curl_socket_t (*Wcurl_opensocket_callback2) + (void *, curlsocktype, const struct curl_sockaddr *); +typedef curl_socket_t (*Wcurl_opensocket_callback3) + (const void *, curlsocktype, struct curl_sockaddr *); +typedef curl_socket_t (*Wcurl_opensocket_callback4) + (const void *, curlsocktype, const struct curl_sockaddr *); + +/* evaluates to true if expr is of type curl_progress_callback or "similar" */ +#define curlcheck_progress_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_progress_callback) || \ + curlcheck_cb_compatible((expr), Wcurl_progress_callback1) || \ + curlcheck_cb_compatible((expr), Wcurl_progress_callback2)) +typedef int (*Wcurl_progress_callback1)(void *, + double, double, double, double); +typedef int (*Wcurl_progress_callback2)(const void *, + double, double, double, double); + +/* evaluates to true if expr is of type curl_xferinfo_callback */ +#define curlcheck_xferinfo_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_xferinfo_callback)) + +/* evaluates to true if expr is of type curl_debug_callback or "similar" */ +#define curlcheck_debug_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_debug_callback) || \ + curlcheck_cb_compatible((expr), Wcurl_debug_callback1) || \ + curlcheck_cb_compatible((expr), Wcurl_debug_callback2) || \ + curlcheck_cb_compatible((expr), Wcurl_debug_callback3) || \ + curlcheck_cb_compatible((expr), Wcurl_debug_callback4) || \ + curlcheck_cb_compatible((expr), Wcurl_debug_callback5) || \ + curlcheck_cb_compatible((expr), Wcurl_debug_callback6) || \ + curlcheck_cb_compatible((expr), Wcurl_debug_callback7) || \ + curlcheck_cb_compatible((expr), Wcurl_debug_callback8)) +typedef int (*Wcurl_debug_callback1)(CURL *, + curl_infotype, char *, size_t, void *); +typedef int (*Wcurl_debug_callback2)(CURL *, + curl_infotype, char *, size_t, const void *); +typedef int (*Wcurl_debug_callback3)(CURL *, + curl_infotype, const char *, size_t, void *); +typedef int (*Wcurl_debug_callback4)(CURL *, + curl_infotype, const char *, size_t, const void *); +typedef int (*Wcurl_debug_callback5)(CURL *, + curl_infotype, unsigned char *, size_t, void *); +typedef int (*Wcurl_debug_callback6)(CURL *, + curl_infotype, unsigned char *, size_t, const void *); +typedef int (*Wcurl_debug_callback7)(CURL *, + curl_infotype, const unsigned char *, size_t, void *); +typedef int (*Wcurl_debug_callback8)(CURL *, + curl_infotype, const unsigned char *, size_t, const void *); + +/* evaluates to true if expr is of type curl_ssl_ctx_callback or "similar" */ +/* this is getting even messier... */ +#define curlcheck_ssl_ctx_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_ssl_ctx_callback) || \ + curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback1) || \ + curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback2) || \ + curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback3) || \ + curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback4) || \ + curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback5) || \ + curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback6) || \ + curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback7) || \ + curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback8)) +typedef CURLcode (*Wcurl_ssl_ctx_callback1)(CURL *, void *, void *); +typedef CURLcode (*Wcurl_ssl_ctx_callback2)(CURL *, void *, const void *); +typedef CURLcode (*Wcurl_ssl_ctx_callback3)(CURL *, const void *, void *); +typedef CURLcode (*Wcurl_ssl_ctx_callback4)(CURL *, const void *, + const void *); +#ifdef HEADER_SSL_H +/* hack: if we included OpenSSL's ssl.h, we know about SSL_CTX + * this of course breaks if we are included before OpenSSL headers... + */ +typedef CURLcode (*Wcurl_ssl_ctx_callback5)(CURL *, SSL_CTX *, void *); +typedef CURLcode (*Wcurl_ssl_ctx_callback6)(CURL *, SSL_CTX *, const void *); +typedef CURLcode (*Wcurl_ssl_ctx_callback7)(CURL *, const SSL_CTX *, void *); +typedef CURLcode (*Wcurl_ssl_ctx_callback8)(CURL *, const SSL_CTX *, + const void *); +#else +typedef Wcurl_ssl_ctx_callback1 Wcurl_ssl_ctx_callback5; +typedef Wcurl_ssl_ctx_callback1 Wcurl_ssl_ctx_callback6; +typedef Wcurl_ssl_ctx_callback1 Wcurl_ssl_ctx_callback7; +typedef Wcurl_ssl_ctx_callback1 Wcurl_ssl_ctx_callback8; +#endif + +/* evaluates to true if expr is of type curl_conv_callback or "similar" */ +#define curlcheck_conv_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_conv_callback) || \ + curlcheck_cb_compatible((expr), Wcurl_conv_callback1) || \ + curlcheck_cb_compatible((expr), Wcurl_conv_callback2) || \ + curlcheck_cb_compatible((expr), Wcurl_conv_callback3) || \ + curlcheck_cb_compatible((expr), Wcurl_conv_callback4)) +typedef CURLcode (*Wcurl_conv_callback1)(char *, size_t length); +typedef CURLcode (*Wcurl_conv_callback2)(const char *, size_t length); +typedef CURLcode (*Wcurl_conv_callback3)(void *, size_t length); +typedef CURLcode (*Wcurl_conv_callback4)(const void *, size_t length); + +/* evaluates to true if expr is of type curl_seek_callback or "similar" */ +#define curlcheck_seek_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_seek_callback) || \ + curlcheck_cb_compatible((expr), Wcurl_seek_callback1) || \ + curlcheck_cb_compatible((expr), Wcurl_seek_callback2)) +typedef CURLcode (*Wcurl_seek_callback1)(void *, curl_off_t, int); +typedef CURLcode (*Wcurl_seek_callback2)(const void *, curl_off_t, int); + +/* evaluates to true if expr is of type curl_chunk_bgn_callback */ +#define curlcheck_chunk_bgn_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_chunk_bgn_callback) || \ + curlcheck_cb_compatible((expr), Wcurl_chunk_bgn_callback1) || \ + curlcheck_cb_compatible((expr), Wcurl_chunk_bgn_callback2)) +typedef long (*Wcurl_chunk_bgn_callback1)(struct curl_fileinfo *, + void *, int); +typedef long (*Wcurl_chunk_bgn_callback2)(void *, void *, int); + +/* evaluates to true if expr is of type curl_chunk_end_callback */ +#define curlcheck_chunk_end_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_chunk_end_callback)) + +/* evaluates to true if expr is of type curl_closesocket_callback */ +#define curlcheck_close_socket_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_closesocket_callback)) + +/* evaluates to true if expr is of type curl_fnmatch_callback */ +#define curlcheck_fnmatch_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_fnmatch_callback)) + +/* evaluates to true if expr is of type curl_hstsread_callback */ +#define curlcheck_hstsread_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_hstsread_callback)) + +/* evaluates to true if expr is of type curl_hstswrite_callback */ +#define curlcheck_hstswrite_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_hstswrite_callback)) + +/* evaluates to true if expr is of type curl_sshhostkeycallback */ +#define curlcheck_ssh_hostkey_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_sshhostkeycallback)) + +/* evaluates to true if expr is of type curl_sshkeycallback */ +#define curlcheck_ssh_key_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_sshkeycallback)) + +/* evaluates to true if expr is of type curl_interleave_callback */ +#define curlcheck_interleave_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), Wcurl_interleave_callback1) || \ + curlcheck_cb_compatible((expr), Wcurl_interleave_callback2)) +typedef size_t (*Wcurl_interleave_callback1)(void *p, size_t s, + size_t n, void *u); +typedef size_t (*Wcurl_interleave_callback2)(char *p, size_t s, + size_t n, void *u); + +/* evaluates to true if expr is of type curl_prereq_callback */ +#define curlcheck_prereq_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_prereq_callback)) + +/* evaluates to true if expr is of type curl_trailer_callback */ +#define curlcheck_trailer_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_trailer_callback)) + +#endif /* CURLINC_TYPECHECK_GCC_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/urlapi.h b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/urlapi.h new file mode 100644 index 0000000000..02553dfebf --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/urlapi.h @@ -0,0 +1,156 @@ +#ifndef CURLINC_URLAPI_H +#define CURLINC_URLAPI_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* the error codes for the URL API */ +typedef enum { + CURLUE_OK, + CURLUE_BAD_HANDLE, /* 1 */ + CURLUE_BAD_PARTPOINTER, /* 2 */ + CURLUE_MALFORMED_INPUT, /* 3 */ + CURLUE_BAD_PORT_NUMBER, /* 4 */ + CURLUE_UNSUPPORTED_SCHEME, /* 5 */ + CURLUE_URLDECODE, /* 6 */ + CURLUE_OUT_OF_MEMORY, /* 7 */ + CURLUE_USER_NOT_ALLOWED, /* 8 */ + CURLUE_UNKNOWN_PART, /* 9 */ + CURLUE_NO_SCHEME, /* 10 */ + CURLUE_NO_USER, /* 11 */ + CURLUE_NO_PASSWORD, /* 12 */ + CURLUE_NO_OPTIONS, /* 13 */ + CURLUE_NO_HOST, /* 14 */ + CURLUE_NO_PORT, /* 15 */ + CURLUE_NO_QUERY, /* 16 */ + CURLUE_NO_FRAGMENT, /* 17 */ + CURLUE_NO_ZONEID, /* 18 */ + CURLUE_BAD_FILE_URL, /* 19 */ + CURLUE_BAD_FRAGMENT, /* 20 */ + CURLUE_BAD_HOSTNAME, /* 21 */ + CURLUE_BAD_IPV6, /* 22 */ + CURLUE_BAD_LOGIN, /* 23 */ + CURLUE_BAD_PASSWORD, /* 24 */ + CURLUE_BAD_PATH, /* 25 */ + CURLUE_BAD_QUERY, /* 26 */ + CURLUE_BAD_SCHEME, /* 27 */ + CURLUE_BAD_SLASHES, /* 28 */ + CURLUE_BAD_USER, /* 29 */ + CURLUE_LACKS_IDN, /* 30 */ + CURLUE_TOO_LARGE, /* 31 */ + CURLUE_BACKSLASH, /* 32 */ + CURLUE_LAST +} CURLUcode; + +typedef enum { + CURLUPART_URL, + CURLUPART_SCHEME, + CURLUPART_USER, + CURLUPART_PASSWORD, + CURLUPART_OPTIONS, + CURLUPART_HOST, + CURLUPART_PORT, + CURLUPART_PATH, + CURLUPART_QUERY, + CURLUPART_FRAGMENT, + CURLUPART_ZONEID /* added in 7.65.0 */ +} CURLUPart; + +#define CURLU_DEFAULT_PORT (1 << 0) /* return default port number */ +#define CURLU_NO_DEFAULT_PORT (1 << 1) /* act as if no port number was set, + if the port number matches the + default for the scheme */ +#define CURLU_DEFAULT_SCHEME (1 << 2) /* return default scheme if + missing */ +#define CURLU_NON_SUPPORT_SCHEME (1 << 3) /* allow non-supported scheme */ +#define CURLU_PATH_AS_IS (1 << 4) /* leave dot sequences */ +#define CURLU_DISALLOW_USER (1 << 5) /* no user+password allowed */ +#define CURLU_URLDECODE (1 << 6) /* URL decode on get */ +#define CURLU_URLENCODE (1 << 7) /* URL encode on set */ +#define CURLU_APPENDQUERY (1 << 8) /* append a form style part */ +#define CURLU_GUESS_SCHEME (1 << 9) /* legacy curl-style guessing */ +#define CURLU_NO_AUTHORITY (1 << 10) /* Allow empty authority when the + scheme is unknown. */ +#define CURLU_ALLOW_SPACE (1 << 11) /* Allow spaces in the URL */ +#define CURLU_PUNYCODE (1 << 12) /* get the hostname in punycode */ +#define CURLU_PUNY2IDN (1 << 13) /* punycode => IDN conversion */ +#define CURLU_GET_EMPTY (1 << 14) /* allow empty queries and fragments + when extracting the URL or the + components */ +#define CURLU_NO_GUESS_SCHEME (1 << 15) /* for get, do not accept a guess */ + +typedef struct Curl_URL CURLU; + +/* + * curl_url() creates a new CURLU handle and returns a pointer to it. + * Must be freed with curl_url_cleanup(). + */ +CURL_EXTERN CURLU *curl_url(void); + +/* + * curl_url_cleanup() frees the CURLU handle and related resources used for + * the URL parsing. It does not free strings previously returned with the URL + * API. + */ +CURL_EXTERN void curl_url_cleanup(CURLU *u); + +/* + * curl_url_dup() duplicates a CURLU handle and returns a new copy. The new + * handle must also be freed with curl_url_cleanup(). + */ +CURL_EXTERN CURLU *curl_url_dup(const CURLU *in); + +/* + * curl_url_get() extracts a specific part of the URL from a CURLU + * handle. Returns error code. The returned pointer MUST be freed with + * curl_free() afterwards. + */ +CURL_EXTERN CURLUcode curl_url_get(const CURLU *u, CURLUPart what, + char **part, unsigned int flags); + +/* + * curl_url_set() sets a specific part of the URL in a CURLU handle. Returns + * error code. The passed in string is copied. Passing a NULL instead of + * a part string, clears that part. + */ +CURL_EXTERN CURLUcode curl_url_set(CURLU *u, CURLUPart what, + const char *part, unsigned int flags); + +/* + * curl_url_strerror() turns a CURLUcode value into the equivalent human + * readable error string. This is useful for printing meaningful error + * messages. + */ +CURL_EXTERN const char *curl_url_strerror(CURLUcode error); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif /* CURLINC_URLAPI_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/websockets.h b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/websockets.h new file mode 100644 index 0000000000..bf93715abf --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/include/curl/websockets.h @@ -0,0 +1,98 @@ +#ifndef CURLINC_WEBSOCKETS_H +#define CURLINC_WEBSOCKETS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifdef __cplusplus +extern "C" { +#endif + +struct curl_ws_frame { + int age; /* zero */ + int flags; /* See the CURLWS_* defines */ + curl_off_t offset; /* the offset of this data into the frame */ + curl_off_t bytesleft; /* number of pending bytes left of the payload */ + size_t len; /* size of the current data chunk */ +}; + +/* flag bits */ +#define CURLWS_TEXT (1 << 0) +#define CURLWS_BINARY (1 << 1) +#define CURLWS_CONT (1 << 2) +#define CURLWS_CLOSE (1 << 3) +#define CURLWS_PING (1 << 4) +#define CURLWS_OFFSET (1 << 5) + +/* + * NAME curl_ws_recv() + * + * DESCRIPTION + * + * Receives data from the websocket connection. Use after successful + * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. + */ +CURL_EXTERN CURLcode curl_ws_recv(CURL *curl, void *buffer, size_t buflen, + size_t *recv, + const struct curl_ws_frame **metap); + +/* flags for curl_ws_send() */ +#define CURLWS_PONG (1 << 6) + +/* + * NAME curl_ws_send() + * + * DESCRIPTION + * + * Sends data over the websocket connection. Use after successful + * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. + */ +CURL_EXTERN CURLcode curl_ws_send(CURL *curl, const void *buffer_arg, + size_t buflen, size_t *sent, + curl_off_t fragsize, + unsigned int flags); + +/* + * NAME curl_ws_start_frame() + * + * DESCRIPTION + * + * Buffers a websocket frame header with the given flags and length. + * Errors when a previous frame is not complete, e.g. not all its + * payload has been added. + */ +CURL_EXTERN CURLcode curl_ws_start_frame(CURL *curl, + unsigned int flags, + curl_off_t frame_len); + +/* bits for the CURLOPT_WS_OPTIONS bitmask: */ +#define CURLWS_RAW_MODE (1L << 0) +#define CURLWS_NOAUTOPONG (1L << 1) + +CURL_EXTERN const struct curl_ws_frame *curl_ws_meta(CURL *curl); + +#ifdef __cplusplus +} +#endif + +#endif /* CURLINC_WEBSOCKETS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/altsvc.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/altsvc.c new file mode 100644 index 0000000000..c57d3f6b40 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/altsvc.c @@ -0,0 +1,726 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * The Alt-Svc: header is defined in RFC 7838: + * https://datatracker.ietf.org/doc/html/rfc7838 + */ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_ALTSVC) +#include "urldata.h" +#include "altsvc.h" +#include "curl_fopen.h" +#include "curl_get_line.h" +#include "parsedate.h" +#include "curl_trc.h" +#include "curlx/inet_pton.h" +#include "curlx/strparse.h" +#include "connect.h" + +#define MAX_ALTSVC_LINE 4095 +#define MAX_ALTSVC_DATELEN 17 +#define MAX_ALTSVC_HOSTLEN 2048 +#define MAX_ALTSVC_ALPNLEN 10 + +#define H3VERSION "h3" + +#if defined(DEBUGBUILD) || defined(UNITTESTS) +/* to play well with debug builds, we can *set* a fixed time this will + return */ +static time_t altsvc_debugtime(void *unused) +{ + const char *timestr = getenv("CURL_TIME"); + (void)unused; + if(timestr) { + curl_off_t val; + curlx_str_number(×tr, &val, TIME_T_MAX); + return (time_t)val; + } + return time(NULL); +} +#undef time +#define time(x) altsvc_debugtime(x) +#endif + +/* Given the ALPN ID, return the name */ +const char *Curl_alpnid2str(enum alpnid id) +{ + switch(id) { + case ALPN_h1: + return "h1"; + case ALPN_h2: + return "h2"; + case ALPN_h3: + return H3VERSION; + default: + return ""; /* bad */ + } +} + +static enum alpnid Curl_str2alpnid(const struct Curl_str *cstr) +{ + return Curl_alpn2alpnid((const unsigned char *)curlx_str(cstr), + curlx_strlen(cstr)); +} + +#define altsvc_free(x) curlx_free(x) + +static struct altsvc *altsvc_createid(const char *srchost, + size_t hlen, + const char *dsthost, + size_t dlen, /* dsthost length */ + enum alpnid srcalpnid, + enum alpnid dstalpnid, + size_t srcport, + size_t dstport) +{ + struct altsvc *as; + if((hlen > 2) && srchost[0] == '[') { + /* IPv6 address, strip off brackets */ + srchost++; + hlen -= 2; + } + else if(hlen && (srchost[hlen - 1] == '.')) { + /* strip off trailing dot */ + hlen--; + } + if((dlen > 2) && dsthost[0] == '[') { + /* IPv6 address, strip off brackets */ + dsthost++; + dlen -= 2; + } + if(!hlen || !dlen) + /* bad input */ + return NULL; + /* struct size plus both strings */ + as = curlx_calloc(1, sizeof(struct altsvc) + (hlen + 1) + (dlen + 1)); + if(!as) + return NULL; + as->src.host = (char *)as + sizeof(struct altsvc); + memcpy(as->src.host, srchost, hlen); + /* the null-terminator is already there */ + + as->dst.host = (char *)as + sizeof(struct altsvc) + hlen + 1; + memcpy(as->dst.host, dsthost, dlen); + /* the null-terminator is already there */ + + as->src.alpnid = srcalpnid; + as->dst.alpnid = dstalpnid; + as->src.port = (unsigned short)srcport; + as->dst.port = (unsigned short)dstport; + + return as; +} + +static struct altsvc *altsvc_create(struct Curl_str *srchost, + struct Curl_str *dsthost, + struct Curl_str *srcalpn, + struct Curl_str *dstalpn, + size_t srcport, + size_t dstport) +{ + enum alpnid dstalpnid = Curl_str2alpnid(dstalpn); + enum alpnid srcalpnid = Curl_str2alpnid(srcalpn); + if(!srcalpnid || !dstalpnid) + return NULL; + return altsvc_createid(curlx_str(srchost), curlx_strlen(srchost), + curlx_str(dsthost), curlx_strlen(dsthost), + srcalpnid, dstalpnid, + srcport, dstport); +} + +/* append the new entry to the list after possibly removing an old entry + first */ +static void altsvc_append(struct altsvcinfo *asi, struct altsvc *as) +{ + while(Curl_llist_count(&asi->list) >= MAX_ALTSVC_ENTRIES) { + /* It is full. Remove the first entry in the list */ + struct Curl_llist_node *e = Curl_llist_head(&asi->list); + struct altsvc *oldas = Curl_node_elem(e); + Curl_node_remove(e); + altsvc_free(oldas); + } + Curl_llist_append(&asi->list, as, &as->node); +} + +/* only returns SERIOUS errors */ +static CURLcode altsvc_add(struct altsvcinfo *asi, const char *line) +{ + /* Example line: + h2 example.com 443 h3 shiny.example.com 8443 "20191231 10:00:00" 1 + */ + struct Curl_str srchost; + struct Curl_str dsthost; + struct Curl_str srcalpn; + struct Curl_str dstalpn; + struct Curl_str date; + curl_off_t srcport; + curl_off_t dstport; + curl_off_t persist; + curl_off_t prio; + + if(curlx_str_word(&line, &srcalpn, MAX_ALTSVC_ALPNLEN) || + curlx_str_singlespace(&line) || + curlx_str_word(&line, &srchost, MAX_ALTSVC_HOSTLEN) || + curlx_str_singlespace(&line) || + curlx_str_number(&line, &srcport, 65535) || + curlx_str_singlespace(&line) || + curlx_str_word(&line, &dstalpn, MAX_ALTSVC_ALPNLEN) || + curlx_str_singlespace(&line) || + curlx_str_word(&line, &dsthost, MAX_ALTSVC_HOSTLEN) || + curlx_str_singlespace(&line) || + curlx_str_number(&line, &dstport, 65535) || + curlx_str_singlespace(&line) || + curlx_str_quotedword(&line, &date, MAX_ALTSVC_DATELEN) || + curlx_str_singlespace(&line) || + curlx_str_number(&line, &persist, 1) || + curlx_str_singlespace(&line) || + curlx_str_number(&line, &prio, 0) || + curlx_str_newline(&line)) + ; + else { + char dbuf[MAX_ALTSVC_DATELEN + 1]; + time_t expires = 0; + time_t now = time(NULL); + + /* The date parser works on a null-terminated string. The maximum length + is upheld by curlx_str_quotedword(). */ + memcpy(dbuf, curlx_str(&date), curlx_strlen(&date)); + dbuf[curlx_strlen(&date)] = 0; + Curl_getdate_capped(dbuf, &expires); + + if(now < expires) { + struct altsvc *as = altsvc_create(&srchost, &dsthost, &srcalpn, &dstalpn, + (size_t)srcport, (size_t)dstport); + if(as) { + as->expires = expires; + as->persist = persist ? 1 : 0; + altsvc_append(asi, as); + } + else + return CURLE_OUT_OF_MEMORY; + } + } + + return CURLE_OK; +} + +/* + * Load alt-svc entries from the given file. The text based line-oriented file + * format is documented here: https://curl.se/docs/alt-svc.html + * + * This function only returns error on major problems that prevent alt-svc + * handling to work completely. It will ignore individual syntactical errors + * etc. + */ +static CURLcode altsvc_load(struct altsvcinfo *asi, const char *file) +{ + CURLcode result = CURLE_OK; + FILE *fp; + + /* we need a private copy of the filename so that the altsvc cache file + name survives an easy handle reset */ + curlx_free(asi->filename); + asi->filename = curlx_strdup(file); + if(!asi->filename) + return CURLE_OUT_OF_MEMORY; + + fp = curlx_fopen(file, FOPEN_READTEXT); + if(fp) { + curlx_struct_stat stat; + if((curlx_fstat(fileno(fp), &stat) == -1) || !S_ISDIR(stat.st_mode)) { + bool eof = FALSE; + struct dynbuf buf; + curlx_dyn_init(&buf, MAX_ALTSVC_LINE); + do { + result = Curl_get_line(&buf, fp, &eof); + if(!result) { + const char *lineptr = curlx_dyn_ptr(&buf); + curlx_str_passblanks(&lineptr); + if(curlx_str_single(&lineptr, '#')) + altsvc_add(asi, lineptr); + } + } while(!result && !eof); + curlx_dyn_free(&buf); /* free the line buffer */ + } + curlx_fclose(fp); + } + return result; +} + +/* + * Write this single altsvc entry to a single output line + */ +static CURLcode altsvc_out(struct altsvc *as, FILE *fp) +{ + struct tm stamp; + const char *dst6_pre = ""; + const char *dst6_post = ""; + const char *src6_pre = ""; + const char *src6_post = ""; + CURLcode result = curlx_gmtime(as->expires, &stamp); + if(result) + return result; +#ifdef USE_IPV6 + else { + char ipv6_unused[16]; + if(curlx_inet_pton(AF_INET6, as->dst.host, ipv6_unused) == 1) { + dst6_pre = "["; + dst6_post = "]"; + } + if(curlx_inet_pton(AF_INET6, as->src.host, ipv6_unused) == 1) { + src6_pre = "["; + src6_post = "]"; + } + } +#endif + curl_mfprintf(fp, + "%s %s%s%s %u " + "%s %s%s%s %u " + "\"%d%02d%02d " + "%02d:%02d:%02d\" " + "%d 0\n", /* prio still always zero */ + Curl_alpnid2str(as->src.alpnid), + src6_pre, as->src.host, src6_post, + as->src.port, + + Curl_alpnid2str(as->dst.alpnid), + dst6_pre, as->dst.host, dst6_post, + as->dst.port, + + stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday, + stamp.tm_hour, stamp.tm_min, stamp.tm_sec, + as->persist); + return CURLE_OK; +} + +/* ---- library-wide functions below ---- */ + +/* + * Curl_altsvc_init() creates a new altsvc cache. + * It returns the new instance or NULL if something goes wrong. + */ +struct altsvcinfo *Curl_altsvc_init(void) +{ + struct altsvcinfo *asi = curlx_calloc(1, sizeof(struct altsvcinfo)); + if(!asi) + return NULL; + Curl_llist_init(&asi->list, NULL); + + /* set default behavior */ + asi->flags = CURLALTSVC_H1 +#ifdef USE_HTTP2 + | CURLALTSVC_H2 +#endif +#ifdef USE_HTTP3 + | CURLALTSVC_H3 +#endif + ; + return asi; +} + +/* + * Curl_altsvc_load() loads alt-svc from file. + */ +CURLcode Curl_altsvc_load(struct altsvcinfo *asi, const char *file) +{ + DEBUGASSERT(asi); + return altsvc_load(asi, file); +} + +/* + * Curl_altsvc_ctrl() passes on the external bitmask. + */ +CURLcode Curl_altsvc_ctrl(struct Curl_easy *data, const long ctrl) +{ + DEBUGASSERT(data); + if(!ctrl) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(!data->asi) { + data->asi = Curl_altsvc_init(); + if(!data->asi) + return CURLE_OUT_OF_MEMORY; + } + data->asi->flags = ctrl; + return CURLE_OK; +} + +/* + * Curl_altsvc_cleanup() frees an altsvc cache instance and all associated + * resources. + */ +void Curl_altsvc_cleanup(struct altsvcinfo **asi) +{ + if(*asi) { + struct Curl_llist_node *e; + struct Curl_llist_node *n; + struct altsvcinfo *altsvc = *asi; + for(e = Curl_llist_head(&altsvc->list); e; e = n) { + struct altsvc *as = Curl_node_elem(e); + n = Curl_node_next(e); + altsvc_free(as); + } + curlx_free(altsvc->filename); + curlx_free(altsvc); + *asi = NULL; /* clear the pointer */ + } +} + +/* + * Curl_altsvc_save() writes the altsvc cache to a file. + */ +CURLcode Curl_altsvc_save(struct Curl_easy *data, + struct altsvcinfo *asi, const char *file) +{ + CURLcode result = CURLE_OK; + FILE *out; + char *tempstore = NULL; + + if(!asi) + /* no cache activated */ + return CURLE_OK; + + /* if not new name is given, use the one we stored from the load */ + if(!file && asi->filename) + file = asi->filename; + + if((asi->flags & CURLALTSVC_READONLYFILE) || !file || !file[0]) + /* marked as read-only, no file or zero length filename */ + return CURLE_OK; + + result = Curl_fopen(data, file, &out, &tempstore); + if(!result) { + struct Curl_llist_node *e; + struct Curl_llist_node *n; + fputs("# Your alt-svc cache. https://curl.se/docs/alt-svc.html\n" + "# This file was generated by libcurl! Edit at your own risk.\n", + out); + for(e = Curl_llist_head(&asi->list); e; e = n) { + struct altsvc *as = Curl_node_elem(e); + n = Curl_node_next(e); + result = altsvc_out(as, out); + if(result) + break; + } + curlx_fclose(out); + if(!result && tempstore && curlx_rename(tempstore, file)) + result = CURLE_WRITE_ERROR; + + if(result && tempstore) + unlink(tempstore); + } + curlx_free(tempstore); + return result; +} + +/* hostcompare() returns true if 'host' matches 'check'. The first host + * argument may have a trailing dot present that will be ignored. + */ +static bool hostcompare(const char *host, const char *check) +{ + size_t hlen = strlen(host); + size_t clen = strlen(check); + + if(hlen && (host[hlen - 1] == '.')) + hlen--; + if(hlen != clen) + /* they cannot match if they have different lengths */ + return FALSE; + return curl_strnequal(host, check, hlen); +} + +/* altsvc_flush() removes all alternatives for this source origin from the + list */ +static void altsvc_flush(struct altsvcinfo *asi, + struct Curl_peer *origin, + enum alpnid origin_alpnid) +{ + struct Curl_llist_node *e; + struct Curl_llist_node *n; + for(e = Curl_llist_head(&asi->list); e; e = n) { + struct altsvc *as = Curl_node_elem(e); + n = Curl_node_next(e); + if((origin_alpnid == as->src.alpnid) && + (origin->port == as->src.port) && + hostcompare(origin->hostname, as->src.host)) { + Curl_node_remove(e); + altsvc_free(as); + } + } +} + +#define ALTSVC_MA 1 +#define ALTSVC_PERSIST 2 +static void altsvc_parse_params(const char **pp, + time_t *pmaxage, + bool *ppersist) +{ + curlx_str_passblanks(pp); + if(curlx_str_single(pp, ';')) + return; + + for(;;) { + struct Curl_str name; + struct Curl_str val; + curl_off_t num; + int keyword = 0; + + /* allow some extra whitespaces around name and value */ + if(curlx_str_until(pp, &name, MAX_ALTSVC_LINE, '=') || + curlx_str_single(pp, '=')) + break; /* skip further parameter parsing */ + + curlx_str_trimblanks(&name); + curlx_str_passblanks(pp); + if(**pp == '\"') { + if(curlx_str_quotedword(pp, &val, MAX_ALTSVC_LINE)) + break; + } + else { + if(curlx_str_cspn(pp, &val, ",;\r\n")) + break; + } + curlx_str_trimblanks(&val); + + if(curlx_str_casecompare(&name, "ma")) + keyword = ALTSVC_MA; + else if(curlx_str_casecompare(&name, "persist")) + keyword = ALTSVC_PERSIST; + + if(keyword) { + const char *vp = curlx_str(&val); + const char *vend = vp + curlx_strlen(&val); + if(curlx_str_number(&vp, &num, TIME_T_MAX)) + break; /* not a number, skip further parameter parsing */ + if(vp != vend) + break; /* not entirely a number, skip further parameter parsing */ + if(keyword == ALTSVC_MA) + *pmaxage = (time_t)num; + else if(num == 1) + *ppersist = TRUE; + } + + curlx_str_passblanks(pp); + if(curlx_str_single(pp, ';')) + break; /* no further parameters */ + } +} + +static bool altsvc_parse_dest(const char **pp, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_str *dsthost, + uint16_t *pdstport) +{ + curl_off_t port = 0; + + if(curlx_str_single(pp, '\"')) + return FALSE; + + /* quoted string, with hostname or just :port ? */ + if(curlx_str_single(pp, ':')) { /* is hostname:port ? */ + if(curlx_str_single(pp, '[')) { /* DNS hostname/IPv4 */ + if(curlx_str_until(pp, dsthost, MAX_ALTSVC_HOSTLEN, ':')) { + infof(data, "Bad alt-svc hostname, ignoring."); + return FALSE; + } + } + else { /* IPv6 hostname */ + if(curlx_str_until(pp, dsthost, MAX_IPADR_LEN, ']') || + curlx_str_single(pp, ']')) { + infof(data, "Bad alt-svc IPv6 hostname, ignoring."); + return FALSE; + } + } + if(curlx_str_single(pp, ':')) + return FALSE; /* not followed by ':' */ + } + else /* is only :port, hostname is effectively origin */ + curlx_str_assign(dsthost, origin->hostname, + strlen(origin->hostname)); + + if(curlx_str_number(pp, &port, 0xffff)) { + infof(data, "Unknown alt-svc port number, ignoring."); + return FALSE; + } + + *pdstport = (uint16_t)port; + if(curlx_str_single(pp, '\"')) + return FALSE; /* quoted string not ending here as expected */ + return TRUE; +} + +/* + * Curl_altsvc_parse() takes an incoming alt-svc response header and stores + * the data correctly in the cache. + * + * 'value' points to the header *value*. That is contents to the right of the + * header name. + * + * Currently this function rejects invalid data without returning an error. + * Invalid hostname, port number will result in the specific alternative + * being rejected. Unknown protocols are skipped. + */ +CURLcode Curl_altsvc_parse(struct Curl_easy *data, + struct altsvcinfo *asi, const char *value, + struct Curl_peer *origin, + enum alpnid origin_alpnid) +{ + struct altsvc *as; + size_t entries = 0; + struct Curl_str alpn; + const char *p; + + DEBUGASSERT(asi); + DEBUGASSERT(origin); + /* RFC 7838, The "Alt-Svc" header field value is basically + * Alt-Svc: (clear|alpn="(host)?:port"\s*(;\s*parameter=value)*) + * This can be repeated, comma-separated. + * + * We parse "best effort", ignoring values we do not recognize. + */ + + /* Try to catch a standalone "clear" */ + p = value; + if(!curlx_str_cspn(&p, &alpn, ";\n\r")) { + curlx_str_trimblanks(&alpn); + /* "clear" is a magic keyword */ + if(curlx_str_casecompare(&alpn, "clear")) { + /* Flush cached alternatives for this source origin */ + altsvc_flush(asi, origin, origin_alpnid); + return CURLE_OK; + } + } + + /* Not a standalone "clear", parse from start for alpn entries */ + for(p = value; *p;) { + time_t maxage = 24 * 3600; /* default is 24 hours */ + bool persist = FALSE; + enum alpnid dstalpnid; + struct Curl_str dsthost; + uint16_t dstport; + + if(curlx_str_until(&p, &alpn, MAX_ALTSVC_LINE, '=')) + break; /* not another entry, leave */ + curlx_str_trimblanks(&alpn); + dstalpnid = Curl_str2alpnid(&alpn); + + if(curlx_str_single(&p, '=')) + break; + + /* Parse altsvc hostname:port */ + if(!altsvc_parse_dest(&p, data, origin, &dsthost, &dstport)) + break; + + /* Parse optional parameters */ + altsvc_parse_params(&p, &maxage, &persist); + + if(dstalpnid) { /* this is a known ALPN id, e.g. not ALPN_none */ + if(!entries++) + /* Flush cached alternatives for this source origin, if any - when + this is the first entry of the line. */ + altsvc_flush(asi, origin, origin_alpnid); + + as = altsvc_createid(origin->hostname, strlen(origin->hostname), + curlx_str(&dsthost), + curlx_strlen(&dsthost), + origin_alpnid, dstalpnid, + origin->port, dstport); + if(as) { + time_t secs = time(NULL); + /* The expires time also needs to take the Age: value (if any) + into account. [See RFC 7838 section 3.1] */ + if(maxage > (TIME_T_MAX - secs)) + as->expires = TIME_T_MAX; + else + as->expires = maxage + secs; + as->persist = persist; + altsvc_append(asi, as); + infof(data, "Added alt-svc: %.*s:%u over %s", + (int)curlx_strlen(&dsthost), curlx_str(&dsthost), + dstport, Curl_alpnid2str(dstalpnid)); + } + else + return CURLE_OUT_OF_MEMORY; + } + + /* When this is followed by a comma, we expect another entry */ + if(curlx_str_single(&p, ',')) + break; + } + + return CURLE_OK; +} + +/* + * Return TRUE on a match + */ +bool Curl_altsvc_lookup(struct altsvcinfo *asi, + struct Curl_peer *origin, + enum alpnid origin_alpnid, + struct altsvc **dstentry, + const int versions, /* one or more bits */ + bool *psame_destination) +{ + DEBUGASSERT(asi); + DEBUGASSERT(origin); + DEBUGASSERT(dstentry); + *psame_destination = FALSE; + + if(Curl_llist_count(&asi->list)) { + struct Curl_llist_node *e; + struct Curl_llist_node *n; + time_t now = time(NULL); + + for(e = Curl_llist_head(&asi->list); e; e = n) { + struct altsvc *as = Curl_node_elem(e); + n = Curl_node_next(e); + if(as->expires < now) { + /* an expired entry, remove */ + Curl_node_remove(e); + altsvc_free(as); + continue; + } + if((origin_alpnid == as->src.alpnid) && + (versions & (int)as->dst.alpnid) && + (origin->port == as->src.port) && + hostcompare(origin->hostname, as->src.host)) { + /* match */ + *dstentry = as; + /* alt-svc on the same host+port or another one? */ + *psame_destination = (origin->port == as->dst.port) && + hostcompare(origin->hostname, as->dst.host); + return TRUE; + } + } + } + return FALSE; +} + +#if defined(DEBUGBUILD) || defined(UNITTESTS) +#undef time +#endif + +#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_ALTSVC */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/altsvc.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/altsvc.h new file mode 100644 index 0000000000..cf9e21808e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/altsvc.h @@ -0,0 +1,78 @@ +#ifndef HEADER_CURL_ALTSVC_H +#define HEADER_CURL_ALTSVC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_ALTSVC) +#include "llist.h" + +struct Curl_peer; + +/* the maximum number of alt-svc entries kept in a single cache */ +#define MAX_ALTSVC_ENTRIES 5000 + +struct althost { + char *host; + uint16_t port; + enum alpnid alpnid; +}; + +struct altsvc { + struct althost src; + struct althost dst; + time_t expires; + struct Curl_llist_node node; + BIT(persist); +}; + +struct altsvcinfo { + char *filename; + struct Curl_llist list; /* list of entries */ + long flags; /* the publicly set bitmask */ +}; + +const char *Curl_alpnid2str(enum alpnid id); +struct altsvcinfo *Curl_altsvc_init(void); +CURLcode Curl_altsvc_load(struct altsvcinfo *asi, const char *file); +CURLcode Curl_altsvc_save(struct Curl_easy *data, + struct altsvcinfo *asi, const char *file); +CURLcode Curl_altsvc_ctrl(struct Curl_easy *data, const long ctrl); +void Curl_altsvc_cleanup(struct altsvcinfo **asi); +CURLcode Curl_altsvc_parse(struct Curl_easy *data, + struct altsvcinfo *asi, const char *value, + struct Curl_peer *origin, + enum alpnid origin_alpnid); +bool Curl_altsvc_lookup(struct altsvcinfo *asi, + struct Curl_peer *origin, + enum alpnid origin_alpnid, + struct altsvc **dstentry, + const int versions, /* CURLALTSVC_H* bits */ + bool *psame_destination); +#else +/* disabled */ +#define Curl_altsvc_save(a, b, c) +#define Curl_altsvc_cleanup(x) +#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_ALTSVC */ +#endif /* HEADER_CURL_ALTSVC_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/amigaos.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/amigaos.c new file mode 100644 index 0000000000..3f61565183 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/amigaos.c @@ -0,0 +1,239 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef __AMIGA__ + +#include "vdns/hostip.h" +#include "curl_addrinfo.h" +#include "amigaos.h" + +#ifdef HAVE_PROTO_BSDSOCKET_H +# ifdef __amigaos4__ +# include <bsdsocket/socketbasetags.h> +# elif !defined(USE_AMISSL) +# include <amitcp/socketbasetags.h> +# endif +# ifdef __libnix__ +# include <stabs.h> +# endif +#endif + +#ifdef HAVE_PROTO_BSDSOCKET_H + +#ifdef __amigaos4__ +/* + * AmigaOS 4.x specific code + */ + +/* + * hostip4.c - Curl_ipv4_resolve_r() replacement code + * + * Logic that needs to be considered are the following build cases: + * - newlib networking + * - clib2 networking + * - direct bsdsocket.library networking (usually AmiSSL builds) + * Each with the threaded resolver enabled or not. + * + * With the threaded resolver enabled, try to use gethostbyname_r() where + * available, otherwise (re)open bsdsocket.library and fallback to + * gethostbyname(). + */ + +#include <proto/bsdsocket.h> + +static struct SocketIFace *__CurlISocket = NULL; +static uint32 SocketFeatures = 0; + +#define HAVE_BSDSOCKET_GETHOSTBYNAME_R 0x01 +#define HAVE_BSDSOCKET_GETADDRINFO 0x02 + +CURLcode Curl_amiga_init(void) +{ + struct SocketIFace *ISocket; + struct Library *base = OpenLibrary("bsdsocket.library", 4); + + if(base) { + ISocket = (struct SocketIFace *)GetInterface(base, "main", 1, NULL); + if(ISocket) { + ULONG enabled = 0; + + SocketBaseTags(SBTM_SETVAL(SBTC_CAN_SHARE_LIBRARY_BASES), TRUE, + SBTM_GETREF(SBTC_HAVE_GETHOSTADDR_R_API), (ULONG)&enabled, + TAG_DONE); + + if(enabled) { + SocketFeatures |= HAVE_BSDSOCKET_GETHOSTBYNAME_R; + } + + __CurlISocket = ISocket; + + atexit(Curl_amiga_cleanup); + + return CURLE_OK; + } + CloseLibrary(base); + } + + return CURLE_FAILED_INIT; +} + +void Curl_amiga_cleanup(void) +{ + if(__CurlISocket) { + struct Library *base = __CurlISocket->Data.LibBase; + DropInterface((struct Interface *)__CurlISocket); + CloseLibrary(base); + __CurlISocket = NULL; + } +} + +#ifdef CURLRES_AMIGA +/* + * Because we need to handle the different cases in hostip4.c at runtime, + * not at compile-time, based on what was detected in Curl_amiga_init(), + * we replace it completely with our own as to not complicate the baseline + * code. Assumes malloc/calloc/free are thread-safe because Curl_he2ai() + * allocates memory also. + */ + +struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname, uint16_t port) +{ + struct Curl_addrinfo *ai = NULL; + struct hostent *h; + struct SocketIFace *ISocket = __CurlISocket; + + if(SocketFeatures & HAVE_BSDSOCKET_GETHOSTBYNAME_R) { + LONG h_errnop = 0; + struct hostent *buf; + + buf = curlx_calloc(1, CURL_HOSTENT_SIZE); + if(buf) { + h = gethostbyname_r((STRPTR)hostname, buf, + (char *)buf + sizeof(struct hostent), + CURL_HOSTENT_SIZE - sizeof(struct hostent), + &h_errnop); + if(h) { + ai = Curl_he2ai(h, port); + } + curlx_free(buf); + } + } + else { +#ifdef USE_RESOLV_THREADED + /* gethostbyname() is not thread-safe, so we need to reopen bsdsocket + * on the thread's context + */ + struct Library *base = OpenLibrary("bsdsocket.library", 4); + if(base) { + ISocket = (struct SocketIFace *)GetInterface(base, "main", 1, NULL); + if(ISocket) { + h = gethostbyname((STRPTR)hostname); + if(h) { + ai = Curl_he2ai(h, port); + } + DropInterface((struct Interface *)ISocket); + } + CloseLibrary(base); + } +#else + /* not using threaded resolver - safe to use this as-is */ + h = gethostbyname(hostname); + if(h) { + ai = Curl_he2ai(h, port); + } +#endif + } + + return ai; +} +#endif /* CURLRES_AMIGA */ + +#ifdef USE_AMISSL +#include <signal.h> +int Curl_amiga_select(int nfds, fd_set *readfds, fd_set *writefds, + fd_set *errorfds, struct timeval *timeout) +{ + int r = WaitSelect(nfds, readfds, writefds, errorfds, timeout, 0); + /* Ensure Ctrl-C signal is actioned */ + if((r == -1) && (SOCKERRNO == SOCKEINTR)) + raise(SIGINT); + return r; +} +#endif /* USE_AMISSL */ + +#elif !defined(USE_AMISSL) /* __amigaos4__ */ +/* + * Amiga OS3 specific code + */ + +struct Library *SocketBase = NULL; + +#ifdef __libnix__ +void __request(const char *msg); +#define CURL_AMIGA_REQUEST(msg) __request(msg) +#else +#define CURL_AMIGA_REQUEST(msg) Printf((const unsigned char *)(msg "\n\a"), 0) +#endif + +void Curl_amiga_cleanup(void) +{ + if(SocketBase) { + CloseLibrary(SocketBase); + SocketBase = NULL; + } +} + +CURLcode Curl_amiga_init(void) +{ + if(!SocketBase) + SocketBase = OpenLibrary((const unsigned char *)"bsdsocket.library", 4); + + if(!SocketBase) { + CURL_AMIGA_REQUEST("No TCP/IP Stack running!"); + return CURLE_FAILED_INIT; + } + + if(SocketBaseTags(SBTM_SETVAL(SBTC_ERRNOPTR(sizeof(errno))), (ULONG)&errno, + SBTM_SETVAL(SBTC_LOGTAGPTR), (ULONG)"curl", TAG_DONE)) { + CURL_AMIGA_REQUEST("SocketBaseTags ERROR"); + return CURLE_FAILED_INIT; + } + +#ifndef __libnix__ + atexit(Curl_amiga_cleanup); +#endif + + return CURLE_OK; +} + +#ifdef __libnix__ +ADD2EXIT(Curl_amiga_cleanup, -50); +#endif + +#endif /* !USE_AMISSL */ + +#endif /* HAVE_PROTO_BSDSOCKET_H */ + +#endif /* __AMIGA__ */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/amigaos.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/amigaos.h new file mode 100644 index 0000000000..58278f0935 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/amigaos.h @@ -0,0 +1,41 @@ +#ifndef HEADER_CURL_AMIGAOS_H +#define HEADER_CURL_AMIGAOS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(__AMIGA__) && defined(HAVE_PROTO_BSDSOCKET_H) && \ + (!defined(USE_AMISSL) || defined(__amigaos4__)) + +CURLcode Curl_amiga_init(void); +void Curl_amiga_cleanup(void); + +#else + +#define Curl_amiga_init() CURLE_OK +#define Curl_amiga_cleanup() Curl_nop_stmt + +#endif + +#endif /* HEADER_CURL_AMIGAOS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/api.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/api.c new file mode 100644 index 0000000000..15e3789861 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/api.c @@ -0,0 +1,451 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "api.h" +#include "curl_threads.h" +#include "multiif.h" +#include "vtls/vtls_scache.h" + +struct Curl_eapi_fn_props { + Curl_eapi_fn fn; + uint8_t data_is_killed; /* easy handle is killed in call */ + uint8_t recurse; /* may be called when another call is in progress */ + uint8_t no_event_cb; /* may not be called during a multi event callback */ + uint8_t no_scache_lock; /* may not be called with easy's vtls_scache + locked by current thread */ +}; + +static const struct Curl_eapi_fn_props eapi_fn_props[CURL_EAPI_FN_LAST] = { + /* function kill rec !ev !scach */ + { CURL_EAPI_FN_easy_cleanup, 1, 0, 0, 0 }, + { CURL_EAPI_FN_easy_duphandle, 0, 1, 0, 0 }, + { CURL_EAPI_FN_easy_getinfo, 0, 1, 0, 0 }, + { CURL_EAPI_FN_easy_header, 0, 1, 0, 0 }, + { CURL_EAPI_FN_easy_nextheader, 0, 1, 0, 0 }, + { CURL_EAPI_FN_easy_pause, 0, 1, 1, 0 }, + { CURL_EAPI_FN_easy_perform_ev, 0, 0, 0, 1 }, + { CURL_EAPI_FN_easy_perform, 0, 0, 0, 1 }, + { CURL_EAPI_FN_easy_recv, 0, 0, 0, 1 }, + { CURL_EAPI_FN_easy_reset, 0, 0, 0, 0 }, + { CURL_EAPI_FN_easy_send, 0, 0, 0, 1 }, + { CURL_EAPI_FN_easy_setopt, 0, 1, 0, 0 }, + { CURL_EAPI_FN_easy_ssls_export, 0, 0, 0, 1 }, + { CURL_EAPI_FN_easy_ssls_import, 0, 0, 0, 1 }, + { CURL_EAPI_FN_easy_upkeep, 0, 0, 0, 1 }, + { CURL_EAPI_FN_ws_recv, 0, 1, 0, 1 }, + { CURL_EAPI_FN_ws_send, 0, 1, 0, 1 }, + { CURL_EAPI_FN_ws_start_frame, 0, 1, 0, 0 }, +}; + +struct Curl_mapi_fn_props { + Curl_mapi_fn fn; + uint8_t multi_is_killed; /* multi handle is killed during call */ + uint8_t recurse; /* may be called when another call is in progress */ + uint8_t allow_ntfy_cb; /* may be called during a notify callback */ + uint8_t no_scache_lock; /* may not be called with multi's vtls_scache + locked by current thread */ +}; + +static const struct Curl_mapi_fn_props mapi_fn_props[CURL_MAPI_FN_LAST] = { + /* function kill rec ntfy !scach */ + { CURL_MAPI_FN_multi_add_handle, 0, 0, 1, 0 }, + { CURL_MAPI_FN_multi_assign, 0, 1, 1, 0 }, + { CURL_MAPI_FN_multi_cleanup, 1, 0, 0, 1 }, + { CURL_MAPI_FN_multi_fdset, 0, 0, 1, 0 }, + { CURL_MAPI_FN_multi_get_handles, 0, 1, 1, 0 }, + { CURL_MAPI_FN_multi_get_offt, 0, 1, 1, 0 }, + { CURL_MAPI_FN_multi_info_read, 0, 1, 1, 0 }, + { CURL_MAPI_FN_multi_notify_disable, 0, 1, 1, 0 }, + { CURL_MAPI_FN_multi_notify_enable, 0, 1, 1, 0 }, + { CURL_MAPI_FN_multi_perform, 0, 0, 0, 1 }, + { CURL_MAPI_FN_multi_poll, 0, 0, 1, 0 }, + { CURL_MAPI_FN_multi_remove_handle, 0, 0, 1, 0 }, + { CURL_MAPI_FN_multi_setopt, 0, 0, 1, 0 }, + { CURL_MAPI_FN_multi_socket_action, 0, 0, 0, 1 }, + { CURL_MAPI_FN_multi_socket_all, 0, 0, 0, 1 }, + { CURL_MAPI_FN_multi_socket, 0, 0, 0, 1 }, + { CURL_MAPI_FN_multi_timeout, 0, 0, 1, 1 }, + { CURL_MAPI_FN_multi_wait, 0, 0, 1, 0 }, + { CURL_MAPI_FN_multi_waitfds, 0, 0, 1, 0 }, +}; + +struct Curl_cbapi_fn_props { + Curl_cbapi_fn fn; + uint8_t is_event_cb; /* is a multi event processing callback */ +}; + +static const struct Curl_cbapi_fn_props +cbapi_fn_props[CURL_CBAPI_FN_LAST - CURL_CBAPI_FN_START] = { + { CURL_CBAPI_FN_easy_chunk_bgn, 0 }, + { CURL_CBAPI_FN_easy_chunk_end, 0 }, + { CURL_CBAPI_FN_easy_closesocket, 0 }, + { CURL_CBAPI_FN_easy_cr_in_read, 0 }, + { CURL_CBAPI_FN_easy_cr_in_resume_from, 0 }, + { CURL_CBAPI_FN_easy_cw_out_cb, 0 }, + { CURL_CBAPI_FN_easy_fdebug, 0 }, + { CURL_CBAPI_FN_easy_fnmatch_data, 0 }, + { CURL_CBAPI_FN_easy_fopensocket, 0 }, + { CURL_CBAPI_FN_easy_fprereq, 0 }, + { CURL_CBAPI_FN_easy_fprogress, 0 }, + { CURL_CBAPI_FN_easy_fread_func, 0 }, + { CURL_CBAPI_FN_easy_fsockopt, 0 }, + { CURL_CBAPI_FN_easy_fsslctx, 0 }, + { CURL_CBAPI_FN_easy_fwrite_rtp, 0 }, + { CURL_CBAPI_FN_easy_fxferinfo, 0 }, + { CURL_CBAPI_FN_easy_ioctl_func, 0 }, + { CURL_CBAPI_FN_easy_resolver_start, 0 }, + { CURL_CBAPI_FN_easy_seek_func, 0 }, + { CURL_CBAPI_FN_easy_ssh_hostkeyfunc, 0 }, + { CURL_CBAPI_FN_easy_ssh_keyfunc, 0 }, + { CURL_CBAPI_FN_easy_trailer_callback, 0 }, + + { CURL_CBAPI_FN_multi_ntfy_cb, 0 }, + { CURL_CBAPI_FN_multi_push_cb, 0 }, + { CURL_CBAPI_FN_multi_socket_cb, 1 }, + { CURL_CBAPI_FN_multi_timer_cb, 1 }, +}; + +static bool eapi_in_event_cb(struct Curl_easy *data) +{ + struct Curl_multi *multi = data->multi; + if(multi && multi->callstack.count) { + size_t i; + for(i = 0; i < multi->callstack.count; ++i) { + if(multi->callstack.calls[i] >= CURL_CBAPI_FN_START) { + uint16_t fn = multi->callstack.calls[i]; + if((fn < CURL_CBAPI_FN_LAST) && + cbapi_fn_props[fn - CURL_CBAPI_FN_START].is_event_cb) + return TRUE; + } + } + } + return FALSE; +} + +static bool mapi_in_ntfy_cb(struct Curl_multi *multi) +{ + if(multi && multi->callstack.count) { + size_t i; + for(i = 0; i < multi->callstack.count; ++i) { + if(multi->callstack.calls[i] == CURL_CBAPI_FN_multi_ntfy_cb) + return TRUE; + } + } + return FALSE; +} + +bool Curl_api_multi_is_in_callback(struct Curl_multi *multi) +{ + if(multi && multi->callstack.count) { + size_t i; + for(i = 0; i < multi->callstack.count; ++i) { + if(multi->callstack.calls[i] >= CURL_CBAPI_FN_START) + return TRUE; + } + } + return FALSE; +} + +bool Curl_api_is_in_callback(struct Curl_easy *data) +{ + if(data && data->multi) { + return Curl_api_multi_is_in_callback(data->multi); + } + return FALSE; +} + +bool Curl_eapi_enter(struct Curl_eapi_guard *guard, + CURL *curl, + Curl_eapi_fn fn, + CURLcode *presult) +{ + struct Curl_easy *data = curl; + const struct Curl_eapi_fn_props *fn_props; + CURLcode result = CURLE_OK; + + guard->depth = 0; + + /* Verify that we got an easy handle we can work with. */ + if(!GOOD_EASY_HANDLE(data)) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + /* verify that is either not added to a multi handle OR has a + * GOOD multi handle that knows `data` for `data->mid`. */ + if(data->mid != UINT32_MAX) { + if(GOOD_MULTI_HANDLE(data->multi)) { + if(!Curl_multi_knows_easy(data->multi, data)) { + /* But multi does not know it, something is fishy, better deny call */ + DEBUGASSERT(0); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + } + else { + DEBUGASSERT(0); /* data needs to have a GOOD multi handle */ + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + } + else if(data->multi) { + DEBUGASSERT(0); /* data should not have a multi handle */ + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + /* verify that the call `fn` we're about to enter is known + * and check call properties to be admitting. */ + if(fn >= CURL_EAPI_FN_LAST) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + fn_props = &eapi_fn_props[fn]; + DEBUGASSERT(fn_props->fn == fn); + if(!fn_props->recurse) { + if(data->callstack.count) { +#ifdef CURLVERBOSE + DEBUGF(curl_mfprintf(stderr, + "EAPI guard: calling %hu with call to %u ongoing\n", (uint16_t)fn, + data->callstack.calls[data->callstack.count-1])); +#endif + result = CURLE_RECURSIVE_API_CALL; + goto out; + } + if(data->multi && data->multi->callstack.count) { +#ifdef CURLVERBOSE + + DEBUGF(curl_mfprintf(stderr, + "EAPI guard: calling %hu with multi call to %u ongoing\n", + (uint16_t)fn, + data->multi->callstack.calls[data->multi->callstack.count-1])); +#endif + result = CURLE_RECURSIVE_API_CALL; + goto out; + } + } + + if(fn_props->no_event_cb && eapi_in_event_cb(data)) { + /* Not allowed to be invoked while an event cb is ongoing */ +#ifdef CURLVERBOSE + DEBUGF(curl_mfprintf(stderr, + "EAPI guard: calling %hu while event callback ongoing\n", + (uint16_t)fn)); +#endif + result = CURLE_RECURSIVE_API_CALL; + goto out; + } + +#if defined(USE_SSL) && defined(USE_MUTEX) + if(fn_props->no_scache_lock && + Curl_ssl_scache_is_locked_by_current_thread(data)) { +#ifdef CURLVERBOSE + DEBUGF(curl_mfprintf(stderr, + "EAPI guard: calling %hu while vtls_scache is locked by " + "current thread\n", (uint16_t)fn)); +#endif + result = CURLE_RECURSIVE_API_CALL; + goto out; + } +#endif + + /* all fine, add to data's callstack */ + if(data->callstack.count >= CURL_EAPI_MAX_RECURSION) { + result = CURLE_RECURSIVE_API_CALL; + goto out; + } + data->callstack.calls[data->callstack.count] = (uint16_t)fn; + ++data->callstack.count; + guard->depth = data->callstack.count; + guard->data = fn_props->data_is_killed ? NULL : data; + +out: + if(presult) + *presult = result; + return guard->depth > 0; +} + +void Curl_eapi_leave(struct Curl_eapi_guard *guard) +{ + if(guard->depth) { + /* guard->data is set when handle is supposed to stay alive during call */ + if(guard->data && GOOD_EASY_HANDLE(guard->data)) { + if(guard->depth > guard->data->callstack.count) { + DEBUGASSERT(0); /* something very wrong */ + } + else { + if(guard->depth < guard->data->callstack.count) { + DEBUGASSERT(0); /* someone forgot to clean up */ + } + /* reset to depth the guard was entered in */ + guard->data->callstack.count = (uint16_t)(guard->depth - 1); + } + } + } +} + +CURLHcode Curl_eapi_hcode(CURLcode result) +{ + switch(result) { + case CURLE_OK: + return CURLHE_OK; + case CURLE_BAD_FUNCTION_ARGUMENT: + return CURLHE_BAD_ARGUMENT; + case CURLE_OUT_OF_MEMORY: + return CURLHE_OUT_OF_MEMORY; + case CURLE_NOT_BUILT_IN: + return CURLHE_NOT_BUILT_IN; + default: + /* Unfortunately, we cannot convert RECURSIVE_API_CALL, + * but since the header API is reentrant, this should not happen. */ + return CURLHE_BAD_ARGUMENT; + } +} + +bool Curl_mapi_enter(struct Curl_mapi_guard *guard, + CURLM *m, + Curl_mapi_fn fn, + CURLMcode *pmresult) +{ + struct Curl_multi *multi = m; + const struct Curl_mapi_fn_props *fn_props; + CURLMcode mresult = CURLM_OK; + + guard->depth = 0; + + /* Verify that we got an easy handle we can work with. */ + if(!GOOD_MULTI_HANDLE(multi)) { + mresult = CURLM_BAD_HANDLE; + goto out; + } + if(fn >= CURL_MAPI_FN_LAST) { + mresult = CURLM_BAD_FUNCTION_ARGUMENT; + goto out; + } + fn_props = &mapi_fn_props[fn]; + DEBUGASSERT(fn_props->fn == fn); + if(fn_props->allow_ntfy_cb && mapi_in_ntfy_cb(multi)) { + /* explicitly allowed, even though normal recursion may not */ + } + else if(!fn_props->recurse && multi->callstack.count) { +#ifdef CURLVERBOSE + DEBUGF(curl_mfprintf(stderr, + "MAPI guard: calling %hu with call to %u ongoing\n", (uint16_t)fn, + multi->callstack.calls[multi->callstack.count-1])); +#endif + mresult = CURLM_RECURSIVE_API_CALL; + goto out; + } + +#if defined(USE_SSL) && defined(USE_MUTEX) + if(fn_props->no_scache_lock && multi->ssl_scache && + Curl_ssl_scache_is_locked_by_current_thread(multi->admin)) { +#ifdef CURLVERBOSE + DEBUGF(curl_mfprintf(stderr, + "MAPI guard: calling %hu while its vtls_scache is locked by " + "current thread\n", (uint16_t)fn)); +#endif + mresult = CURLM_RECURSIVE_API_CALL; + goto out; + } +#endif + + /* all fine, add to data's callstack */ + if(multi->callstack.count >= CURL_MAPI_MAX_RECURSION) { + mresult = CURLM_RECURSIVE_API_CALL; + goto out; + } + multi->callstack.calls[multi->callstack.count] = (uint16_t)fn; + ++multi->callstack.count; + guard->depth = multi->callstack.count; + guard->multi = fn_props->multi_is_killed ? NULL : multi; + +out: + if(pmresult) + *pmresult = mresult; + return guard->depth > 0; +} + +void Curl_mapi_leave(struct Curl_mapi_guard *guard) +{ + if(guard->depth) { + /* guard->data is set when handle is supposed to stay alive during call */ + if(guard->multi && GOOD_MULTI_HANDLE(guard->multi)) { + if(guard->depth > guard->multi->callstack.count) { + DEBUGASSERT(0); /* something very wrong */ + } + else { + if(guard->depth < guard->multi->callstack.count) { + DEBUGASSERT(0); /* someone forgot to clean up */ + } + /* reset to depth the guard was entered in */ + guard->multi->callstack.count = (uint16_t)(guard->depth - 1); + } + } + } +} + +void Curl_cbapi_enter(struct Curl_mapi_guard *guard, + struct Curl_easy *data, + struct Curl_multi *multi, + Curl_cbapi_fn fn) +{ + guard->depth = 0; + + if(!multi) + multi = data ? data->multi : NULL; + /* if not multi is involved here, just leave */ + if(!multi) + return; + /* invalid callback specifier? */ + if((fn >= CURL_CBAPI_FN_LAST) || (fn < CURL_CBAPI_FN_START)) { + DEBUGASSERT(0); + return; + } + DEBUGASSERT(cbapi_fn_props[fn - CURL_CBAPI_FN_START].fn == fn); + if(multi->callstack.count) { + size_t i; + for(i = multi->callstack.count; i; --i) { + if(multi->callstack.calls[i - 1] == fn) { + /* recursive invocation of the same callback */ + DEBUGASSERT(0); + return; + } + } + } + + /* all fine, add to data's callstack */ + /* if multi callstack already at max depth, leave */ + if(multi->callstack.count >= CURL_MAPI_MAX_RECURSION) + return; + multi->callstack.calls[multi->callstack.count] = (uint16_t)fn; + ++multi->callstack.count; + guard->depth = multi->callstack.count; + guard->multi = multi; +} + +void Curl_cbapi_leave(struct Curl_mapi_guard *guard) +{ + Curl_mapi_leave(guard); +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/api.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/api.h new file mode 100644 index 0000000000..337d686bb5 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/api.h @@ -0,0 +1,212 @@ +#ifndef HEADER_CURL_API_H +#define HEADER_CURL_API_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#define CURLEASY_MAGIC_NUMBER 0xc0dedbadU +#ifdef DEBUGBUILD +/* On a debug build, we want to fail hard on easy handles that + * are not NULL, but no longer have the MAGIC touch. This gives + * us early warning on things only discovered by valgrind otherwise. */ +#define GOOD_EASY_HANDLE(x) \ + (((x) && ((x)->magic == CURLEASY_MAGIC_NUMBER)) ? TRUE : \ + (DEBUGASSERT(!(x)), FALSE)) +#else +#define GOOD_EASY_HANDLE(x) \ + ((x) && ((x)->magic == CURLEASY_MAGIC_NUMBER)) +#endif + +#define CURLMULTI_MAGIC_NUMBER 0x000bab1e + +#ifdef DEBUGBUILD +/* On a debug build, we want to fail hard on multi handles that + * are not NULL, but no longer have the MAGIC touch. This gives + * us early warning on things only discovered by valgrind otherwise. */ +#define GOOD_MULTI_HANDLE(x) \ + (((x) && (x)->magic == CURLMULTI_MAGIC_NUMBER) ? TRUE : \ + (DEBUGASSERT(!(x)), FALSE)) +#else +#define GOOD_MULTI_HANDLE(x) \ + ((x) && (x)->magic == CURLMULTI_MAGIC_NUMBER) +#endif + +/* the API functions called on a CURL* */ +typedef enum { + CURL_EAPI_FN_easy_cleanup, + CURL_EAPI_FN_easy_duphandle, + CURL_EAPI_FN_easy_getinfo, + CURL_EAPI_FN_easy_header, + CURL_EAPI_FN_easy_nextheader, + CURL_EAPI_FN_easy_pause, + CURL_EAPI_FN_easy_perform_ev, + CURL_EAPI_FN_easy_perform, + CURL_EAPI_FN_easy_recv, + CURL_EAPI_FN_easy_reset, + CURL_EAPI_FN_easy_send, + CURL_EAPI_FN_easy_setopt, + CURL_EAPI_FN_easy_ssls_export, + CURL_EAPI_FN_easy_ssls_import, + CURL_EAPI_FN_easy_upkeep, + CURL_EAPI_FN_ws_recv, + CURL_EAPI_FN_ws_send, + CURL_EAPI_FN_ws_start_frame, + CURL_EAPI_FN_LAST +} Curl_eapi_fn; + +/* the API functions called on a CURLM* */ +typedef enum { + CURL_MAPI_FN_multi_add_handle, + CURL_MAPI_FN_multi_assign, + CURL_MAPI_FN_multi_cleanup, + CURL_MAPI_FN_multi_fdset, + CURL_MAPI_FN_multi_get_handles, + CURL_MAPI_FN_multi_get_offt, + CURL_MAPI_FN_multi_info_read, + CURL_MAPI_FN_multi_notify_disable, + CURL_MAPI_FN_multi_notify_enable, + CURL_MAPI_FN_multi_perform, + CURL_MAPI_FN_multi_poll, + CURL_MAPI_FN_multi_remove_handle, + CURL_MAPI_FN_multi_setopt, + CURL_MAPI_FN_multi_socket_action, + CURL_MAPI_FN_multi_socket_all, + CURL_MAPI_FN_multi_socket, + CURL_MAPI_FN_multi_timeout, + CURL_MAPI_FN_multi_wait, + CURL_MAPI_FN_multi_waitfds, + CURL_MAPI_FN_LAST +} Curl_mapi_fn; + +#define CURL_CBAPI_FN_START (16 * 1024) + +/* the callback functions */ +typedef enum { + CURL_CBAPI_FN_easy_chunk_bgn = CURL_CBAPI_FN_START, + CURL_CBAPI_FN_easy_chunk_end, + CURL_CBAPI_FN_easy_closesocket, + CURL_CBAPI_FN_easy_cr_in_read, + CURL_CBAPI_FN_easy_cr_in_resume_from, + CURL_CBAPI_FN_easy_cw_out_cb, + CURL_CBAPI_FN_easy_fdebug, + CURL_CBAPI_FN_easy_fnmatch_data, + CURL_CBAPI_FN_easy_fopensocket, + CURL_CBAPI_FN_easy_fprereq, + CURL_CBAPI_FN_easy_fprogress, + CURL_CBAPI_FN_easy_fread_func, + CURL_CBAPI_FN_easy_fsockopt, + CURL_CBAPI_FN_easy_fsslctx, + CURL_CBAPI_FN_easy_fwrite_rtp, + CURL_CBAPI_FN_easy_fxferinfo, + CURL_CBAPI_FN_easy_ioctl_func, + CURL_CBAPI_FN_easy_resolver_start, + CURL_CBAPI_FN_easy_seek_func, + CURL_CBAPI_FN_easy_ssh_hostkeyfunc, + CURL_CBAPI_FN_easy_ssh_keyfunc, + CURL_CBAPI_FN_easy_trailer_callback, + + CURL_CBAPI_FN_multi_ntfy_cb, + CURL_CBAPI_FN_multi_push_cb, + CURL_CBAPI_FN_multi_socket_cb, + CURL_CBAPI_FN_multi_timer_cb, + + CURL_CBAPI_FN_LAST +} Curl_cbapi_fn; + +/* EAPI */ + +#define CURL_EAPI_MAX_RECURSION 7 + +struct Curl_eapi_stack { + uint16_t count; + uint16_t calls[CURL_EAPI_MAX_RECURSION]; +}; + +struct Curl_eapi_guard { + struct Curl_easy *data; /* != NULL if handle stays */ + uint16_t depth; /* > 0 if this guard was entered */ +}; + +bool Curl_eapi_enter(struct Curl_eapi_guard *guard, + CURL *curl, + Curl_eapi_fn fn, + CURLcode *presult); +void Curl_eapi_leave(struct Curl_eapi_guard *guard); + +/* Convert an EAPI failure to a header API result */ +CURLHcode Curl_eapi_hcode(CURLcode result); + +/* Curl_eapi_enter() checks for curl being NULL, but windows compiler + * analyzers do not realize this. *sigh* */ +#define CURL_EAPI_ENTER(g, curl, fn, r) \ + Curl_eapi_enter((g), (curl), CURL_EAPI_FN_##fn, (r)) && (curl) +#define CURL_EAPI_LEAVE(g) \ + Curl_eapi_leave(g) + +/* MAPI */ + +#define CURL_MAPI_MAX_RECURSION 15 + +struct Curl_mapi_stack { + uint16_t count; + uint16_t calls[CURL_MAPI_MAX_RECURSION]; +}; + +struct Curl_mapi_guard { + struct Curl_multi *multi; /* != NULL if handle stays */ + uint16_t depth; /* > 0 if this guard was entered */ +}; + +bool Curl_mapi_enter(struct Curl_mapi_guard *guard, + CURLM *m, + Curl_mapi_fn fn, + CURLMcode *pmresult); +void Curl_mapi_leave(struct Curl_mapi_guard *guard); + +/* Curl_mapi_enter() checks for m being NULL, but windows compiler + * analyzers do not realize this. *sigh* */ +#define CURL_MAPI_ENTER(g, m, fn, r) \ + Curl_mapi_enter((g), (m), CURL_MAPI_FN_##fn, (r)) && (m) +#define CURL_MAPI_LEAVE(g) \ + Curl_mapi_leave(g) + +void Curl_cbapi_enter(struct Curl_mapi_guard *guard, + struct Curl_easy *data, + struct Curl_multi *multi, + Curl_cbapi_fn fn); +void Curl_cbapi_leave(struct Curl_mapi_guard *guard); + +#define CURL_CBAPI_START(g, d, fn) \ + Curl_cbapi_enter((g), (d), NULL, CURL_CBAPI_FN_##fn) +#define CURL_CBAPI_MULTI_START(g, m, fn) \ + Curl_cbapi_enter((g), NULL, (m), CURL_CBAPI_FN_##fn) +#define CURL_CBAPI_END(g) \ + Curl_cbapi_leave(g) +#define CURL_CBAPI_MULTI_END(g) \ + Curl_cbapi_leave(g) + +bool Curl_api_is_in_callback(struct Curl_easy *data); +bool Curl_api_multi_is_in_callback(struct Curl_multi *multi); + +#endif /* HEADER_CURL_API_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/arpa_telnet.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/arpa_telnet.h new file mode 100644 index 0000000000..826f937537 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/arpa_telnet.h @@ -0,0 +1,116 @@ +#ifndef HEADER_CURL_ARPA_TELNET_H +#define HEADER_CURL_ARPA_TELNET_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_TELNET +/* + * Telnet option defines. Add more here if in need. + */ +#define CURL_TELOPT_BINARY 0 /* binary 8-bit data */ +#define CURL_TELOPT_ECHO 1 /* echo */ +#define CURL_TELOPT_SGA 3 /* Suppress Go Ahead */ +#define CURL_TELOPT_EXOPL 255 /* EXtended OPtions List */ +#define CURL_TELOPT_TTYPE 24 /* Terminal TYPE */ +#define CURL_TELOPT_NAWS 31 /* Negotiate About Window Size */ +#define CURL_TELOPT_XDISPLOC 35 /* X DISPlay LOCation */ +#define CURL_TELOPT_NEW_ENVIRON 39 /* NEW ENVIRONment variables */ + +#define CURL_NEW_ENV_VAR 0 +#define CURL_NEW_ENV_VALUE 1 + +#ifdef CURLVERBOSE +/* + * The telnet options represented as strings + */ +static const char * const telnetoptions[] = { + "BINARY", "ECHO", "RCP", "SUPPRESS GO AHEAD", + "NAME", "STATUS", "TIMING MARK", "RCTE", + "NAOL", "NAOP", "NAOCRD", "NAOHTS", + "NAOHTD", "NAOFFD", "NAOVTS", "NAOVTD", + "NAOLFD", "EXTEND ASCII", "LOGOUT", "BYTE MACRO", + "DE TERMINAL", "SUPDUP", "SUPDUP OUTPUT", "SEND LOCATION", + "TERM TYPE", "END OF RECORD", "TACACS UID", "OUTPUT MARKING", + "TTYLOC", "3270 REGIME", "X3 PAD", "NAWS", + "TERM SPEED", "LFLOW", "LINEMODE", "XDISPLOC", + "OLD-ENVIRON", "AUTHENTICATION", "ENCRYPT", "NEW-ENVIRON" +}; +#define CURL_TELOPT(x) telnetoptions[x] +#else +#define CURL_TELOPT(x) "" +#endif + +#define CURL_TELOPT_MAXIMUM CURL_TELOPT_NEW_ENVIRON + +#define CURL_TELOPT_OK(x) ((x) <= CURL_TELOPT_MAXIMUM) + +#define CURL_NTELOPTS 40 + +/* + * First some defines + */ +#define CURL_xEOF 236 /* End Of File */ +#define CURL_SE 240 /* Sub negotiation End */ +#define CURL_NOP 241 /* No OPeration */ +#define CURL_DM 242 /* Data Mark */ +#define CURL_GA 249 /* Go Ahead, reverse the line */ +#define CURL_SB 250 /* SuBnegotiation */ +#define CURL_WILL 251 /* Our side WILL use this option */ +#define CURL_WONT 252 /* Our side will not use this option */ +#define CURL_DO 253 /* DO use this option! */ +#define CURL_DONT 254 /* DO NOT use this option! */ +#define CURL_IAC 255 /* Interpret As Command */ + +#ifdef CURLVERBOSE +/* + * Then those numbers represented as strings: + */ +static const char * const telnetcmds[] = { + "EOF", "SUSP", "ABORT", "EOR", "SE", + "NOP", "DMARK", "BRK", "IP", "AO", + "AYT", "EC", "EL", "GA", "SB", + "WILL", "WONT", "DO", "DONT", "IAC" +}; +#endif + +#define CURL_TELCMD_MINIMUM CURL_xEOF /* the first one */ +#define CURL_TELCMD_MAXIMUM CURL_IAC /* surprise, 255 is the last one! ;-) */ + +#define CURL_TELQUAL_IS 0 +#define CURL_TELQUAL_SEND 1 +#define CURL_TELQUAL_INFO 2 +#define CURL_TELQUAL_NAME 3 + +#define CURL_TELCMD_OK(x) \ + (((unsigned int)(x) >= CURL_TELCMD_MINIMUM) && \ + ((unsigned int)(x) <= CURL_TELCMD_MAXIMUM)) + +#ifdef CURLVERBOSE +#define CURL_TELCMD(x) telnetcmds[(x) - CURL_TELCMD_MINIMUM] +#else +#define CURL_TELCMD(x) "" +#endif + +#endif /* CURL_DISABLE_TELNET */ + +#endif /* HEADER_CURL_ARPA_TELNET_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/bufq.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/bufq.c new file mode 100644 index 0000000000..750d86888f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/bufq.c @@ -0,0 +1,619 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "bufq.h" + +static bool chunk_is_empty(const struct buf_chunk *chunk) +{ + return chunk->r_offset >= chunk->w_offset; +} + +static bool chunk_is_full(const struct buf_chunk *chunk) +{ + return chunk->w_offset >= chunk->dlen; +} + +static size_t chunk_len(const struct buf_chunk *chunk) +{ + return chunk->w_offset - chunk->r_offset; +} + +static void chunk_reset(struct buf_chunk *chunk) +{ + chunk->next = NULL; + chunk->r_offset = chunk->w_offset = 0; +} + +static size_t chunk_append(struct buf_chunk *chunk, + const uint8_t *buf, size_t len) +{ + uint8_t *p = &chunk->x.data[chunk->w_offset]; + size_t n = chunk->dlen - chunk->w_offset; + DEBUGASSERT(chunk->dlen >= chunk->w_offset); + if(n) { + n = CURLMIN(n, len); + memcpy(p, buf, n); + chunk->w_offset += n; + } + return n; +} + +static size_t chunk_read(struct buf_chunk *chunk, + uint8_t *buf, size_t len) +{ + uint8_t *p = &chunk->x.data[chunk->r_offset]; + size_t n = chunk->w_offset - chunk->r_offset; + DEBUGASSERT(chunk->w_offset >= chunk->r_offset); + if(!n) { + return 0; + } + else if(n <= len) { + memcpy(buf, p, n); + chunk->r_offset = chunk->w_offset = 0; + return n; + } + else { + memcpy(buf, p, len); + chunk->r_offset += len; + return len; + } +} + +static CURLcode chunk_slurpn(struct buf_chunk *chunk, size_t max_len, + Curl_bufq_reader *reader, + void *reader_ctx, size_t *pnread) +{ + uint8_t *p = &chunk->x.data[chunk->w_offset]; + size_t n = chunk->dlen - chunk->w_offset; /* free amount */ + CURLcode result; + + *pnread = 0; + DEBUGASSERT(chunk->dlen >= chunk->w_offset); + if(!n) + return CURLE_AGAIN; + if(max_len && n > max_len) + n = max_len; + result = reader(reader_ctx, p, n, pnread); + if(!result) { + DEBUGASSERT(*pnread <= n); + chunk->w_offset += *pnread; + } + return result; +} + +static void chunk_peek(const struct buf_chunk *chunk, + const uint8_t **pbuf, size_t *plen) +{ + DEBUGASSERT(chunk->w_offset >= chunk->r_offset); + *pbuf = &chunk->x.data[chunk->r_offset]; + *plen = chunk->w_offset - chunk->r_offset; +} + +static void chunk_peek_at(const struct buf_chunk *chunk, size_t offset, + const uint8_t **pbuf, size_t *plen) +{ + offset += chunk->r_offset; + DEBUGASSERT(chunk->w_offset >= offset); + *pbuf = &chunk->x.data[offset]; + *plen = chunk->w_offset - offset; +} + +static size_t chunk_skip(struct buf_chunk *chunk, size_t amount) +{ + size_t n = chunk->w_offset - chunk->r_offset; + DEBUGASSERT(chunk->w_offset >= chunk->r_offset); + if(n) { + n = CURLMIN(n, amount); + chunk->r_offset += n; + if(chunk->r_offset == chunk->w_offset) + chunk->r_offset = chunk->w_offset = 0; + } + return n; +} + +static void chunk_list_free(struct buf_chunk **anchor) +{ + struct buf_chunk *chunk; + while(*anchor) { + chunk = *anchor; + *anchor = chunk->next; + curlx_free(chunk); + } +} + +void Curl_bufcp_init(struct bufc_pool *pool, + size_t chunk_size, size_t spare_max) +{ + DEBUGASSERT(chunk_size > 0); + DEBUGASSERT(spare_max > 0); + memset(pool, 0, sizeof(*pool)); + pool->chunk_size = chunk_size; + pool->spare_max = spare_max; +} + +static CURLcode bufcp_take(struct bufc_pool *pool, + struct buf_chunk **pchunk) +{ + struct buf_chunk *chunk = NULL; + + if(pool->spare) { + chunk = pool->spare; + pool->spare = chunk->next; + --pool->spare_count; + chunk_reset(chunk); + *pchunk = chunk; + return CURLE_OK; + } + + /* Check for integer overflow before allocation */ + if(pool->chunk_size > SIZE_MAX - sizeof(*chunk)) { + *pchunk = NULL; + return CURLE_OUT_OF_MEMORY; + } + + chunk = curlx_calloc(1, sizeof(*chunk) + pool->chunk_size); + if(!chunk) { + *pchunk = NULL; + return CURLE_OUT_OF_MEMORY; + } + chunk->dlen = pool->chunk_size; + *pchunk = chunk; + return CURLE_OK; +} + +static void bufcp_put(struct bufc_pool *pool, + struct buf_chunk *chunk) +{ + if(pool->spare_count >= pool->spare_max) { + curlx_free(chunk); + } + else { + chunk_reset(chunk); + chunk->next = pool->spare; + pool->spare = chunk; + ++pool->spare_count; + } +} + +void Curl_bufcp_free(struct bufc_pool *pool) +{ + chunk_list_free(&pool->spare); + pool->spare_count = 0; +} + +static void bufq_init(struct bufq *q, struct bufc_pool *pool, + size_t chunk_size, size_t max_chunks, int opts) +{ + DEBUGASSERT(chunk_size > 0); + DEBUGASSERT(max_chunks > 0); + memset(q, 0, sizeof(*q)); + q->chunk_size = chunk_size; + q->max_chunks = max_chunks; + q->pool = pool; + q->opts = opts; +} + +void Curl_bufq_init2(struct bufq *q, size_t chunk_size, size_t max_chunks, + int opts) +{ + bufq_init(q, NULL, chunk_size, max_chunks, opts); +} + +void Curl_bufq_init(struct bufq *q, size_t chunk_size, size_t max_chunks) +{ + bufq_init(q, NULL, chunk_size, max_chunks, BUFQ_OPT_NONE); +} + +void Curl_bufq_initp(struct bufq *q, struct bufc_pool *pool, + size_t max_chunks, int opts) +{ + bufq_init(q, pool, pool->chunk_size, max_chunks, opts); +} + +void Curl_bufq_free(struct bufq *q) +{ + chunk_list_free(&q->head); + chunk_list_free(&q->spare); + q->tail = NULL; + q->chunk_count = 0; +} + +void Curl_bufq_reset(struct bufq *q) +{ + struct buf_chunk *chunk; + while(q->head) { + chunk = q->head; + q->head = chunk->next; + chunk->next = q->spare; + q->spare = chunk; + } + q->tail = NULL; +} + +size_t Curl_bufq_len(const struct bufq *q) +{ + const struct buf_chunk *chunk = q->head; + size_t len = 0; + while(chunk) { + len += chunk_len(chunk); + chunk = chunk->next; + } + return len; +} + +bool Curl_bufq_is_empty(const struct bufq *q) +{ + return !q->head || chunk_is_empty(q->head); +} + +bool Curl_bufq_is_full(const struct bufq *q) +{ + if(!q->tail || q->spare) + return FALSE; + if(q->chunk_count < q->max_chunks) + return FALSE; + if(q->chunk_count > q->max_chunks) + return TRUE; + /* we have no spares and cannot make more, is the tail full? */ + return chunk_is_full(q->tail); +} + +static struct buf_chunk *get_spare(struct bufq *q) +{ + struct buf_chunk *chunk = NULL; + + if(q->spare) { + chunk = q->spare; + q->spare = chunk->next; + chunk_reset(chunk); + return chunk; + } + + if(q->chunk_count >= q->max_chunks && (!(q->opts & BUFQ_OPT_SOFT_LIMIT))) + return NULL; + + if(q->pool) { + if(bufcp_take(q->pool, &chunk)) + return NULL; + ++q->chunk_count; + return chunk; + } + else { + /* Check for integer overflow before allocation */ + if(q->chunk_size > SIZE_MAX - sizeof(*chunk)) { + return NULL; + } + + chunk = curlx_calloc(1, sizeof(*chunk) + q->chunk_size); + if(!chunk) + return NULL; + chunk->dlen = q->chunk_size; + ++q->chunk_count; + return chunk; + } +} + +static void prune_head(struct bufq *q) +{ + struct buf_chunk *chunk; + + while(q->head && chunk_is_empty(q->head)) { + chunk = q->head; + q->head = chunk->next; + if(q->tail == chunk) + q->tail = q->head; + if(q->pool) { + bufcp_put(q->pool, chunk); + --q->chunk_count; + } + else if((q->chunk_count > q->max_chunks) || + (q->opts & BUFQ_OPT_NO_SPARES)) { + /* SOFT_LIMIT allowed us more than max. free spares until + * we are at max again. Or free them if we are configured + * to not use spares. */ + curlx_free(chunk); + --q->chunk_count; + } + else { + chunk->next = q->spare; + q->spare = chunk; + } + } +} + +static struct buf_chunk *get_non_full_tail(struct bufq *q) +{ + struct buf_chunk *chunk; + + if(q->tail && !chunk_is_full(q->tail)) + return q->tail; + chunk = get_spare(q); + if(chunk) { + /* new tail, and possibly new head */ + if(q->tail) { + q->tail->next = chunk; + q->tail = chunk; + } + else { + DEBUGASSERT(!q->head); + q->head = q->tail = chunk; + } + } + return chunk; +} + +CURLcode Curl_bufq_write(struct bufq *q, + const uint8_t *buf, size_t len, + size_t *pnwritten) +{ + struct buf_chunk *tail; + size_t n; + + DEBUGASSERT(q->max_chunks > 0); + *pnwritten = 0; + while(len) { + tail = get_non_full_tail(q); + if(!tail) { + if((q->chunk_count < q->max_chunks) || (q->opts & BUFQ_OPT_SOFT_LIMIT)) + /* should have gotten a tail, but did not */ + return CURLE_OUT_OF_MEMORY; + break; + } + n = chunk_append(tail, buf, len); + if(!n) + break; + *pnwritten += n; + buf += n; + len -= n; + } + return (!*pnwritten && len) ? CURLE_AGAIN : CURLE_OK; +} + +CURLcode Curl_bufq_cwrite(struct bufq *q, + const char *buf, size_t len, + size_t *pnwritten) +{ + return Curl_bufq_write(q, (const uint8_t *)buf, len, pnwritten); +} + +CURLcode Curl_bufq_read(struct bufq *q, uint8_t *buf, size_t len, + size_t *pnread) +{ + *pnread = 0; + while(len && q->head) { + size_t n = chunk_read(q->head, buf, len); + if(n) { + *pnread += n; + buf += n; + len -= n; + } + prune_head(q); + } + return (!*pnread) ? CURLE_AGAIN : CURLE_OK; +} + +CURLcode Curl_bufq_cread(struct bufq *q, char *buf, size_t len, + size_t *pnread) +{ + return Curl_bufq_read(q, (uint8_t *)buf, len, pnread); +} + +bool Curl_bufq_peek(struct bufq *q, + const uint8_t **pbuf, size_t *plen) +{ + if(q->head && chunk_is_empty(q->head)) { + prune_head(q); + } + if(q->head && !chunk_is_empty(q->head)) { + chunk_peek(q->head, pbuf, plen); + return TRUE; + } + *pbuf = NULL; + *plen = 0; + return FALSE; +} + +bool Curl_bufq_peek_at(struct bufq *q, size_t offset, + const uint8_t **pbuf, size_t *plen) +{ + struct buf_chunk *c = q->head; + size_t clen; + + while(c) { + clen = chunk_len(c); + if(!clen) + break; + if(offset >= clen) { + offset -= clen; + c = c->next; + continue; + } + chunk_peek_at(c, offset, pbuf, plen); + return TRUE; + } + *pbuf = NULL; + *plen = 0; + return FALSE; +} + +void Curl_bufq_skip(struct bufq *q, size_t amount) +{ + size_t n; + + while(amount && q->head) { + n = chunk_skip(q->head, amount); + amount -= n; + prune_head(q); + } +} + +CURLcode Curl_bufq_pass(struct bufq *q, Curl_bufq_writer *writer, + void *writer_ctx, size_t *pwritten) +{ + const uint8_t *buf; + size_t blen; + CURLcode result = CURLE_OK; + + *pwritten = 0; + while(Curl_bufq_peek(q, &buf, &blen)) { + size_t chunk_written; + + result = writer(writer_ctx, buf, blen, &chunk_written); + if(result) { + if((result == CURLE_AGAIN) && *pwritten) { + /* blocked on subsequent write, report success */ + result = CURLE_OK; + } + break; + } + if(!chunk_written) { + if(!*pwritten) { + /* treat as blocked */ + result = CURLE_AGAIN; + } + break; + } + *pwritten += chunk_written; + Curl_bufq_skip(q, chunk_written); + } + return result; +} + +CURLcode Curl_bufq_write_pass(struct bufq *q, + const uint8_t *buf, size_t len, + Curl_bufq_writer *writer, void *writer_ctx, + size_t *pwritten) +{ + CURLcode result = CURLE_OK; + size_t n; + + *pwritten = 0; + while(len) { + if(Curl_bufq_is_full(q)) { + /* try to make room in case we are full */ + result = Curl_bufq_pass(q, writer, writer_ctx, &n); + if(result) { + if(result != CURLE_AGAIN) { + /* real error, fail */ + return result; + } + /* would block, bufq is full, give up */ + break; + } + } + + /* Add to bufq as much as there is room for */ + result = Curl_bufq_write(q, buf, len, &n); + if(result) { + if(result != CURLE_AGAIN) + /* real error, fail */ + return result; + /* result == CURLE_AGAIN */ + if(*pwritten) + /* we did write successfully before */ + result = CURLE_OK; + return result; + } + else if(n == 0) + /* edge case of writer returning 0 (and len is >0) + * break or we might enter an infinite loop here */ + break; + + /* Track what we added to bufq */ + buf += n; + len -= n; + *pwritten += n; + } + + return (!*pwritten && len) ? CURLE_AGAIN : CURLE_OK; +} + +CURLcode Curl_bufq_sipn(struct bufq *q, size_t max_len, + Curl_bufq_reader *reader, void *reader_ctx, + size_t *pnread) +{ + struct buf_chunk *tail = NULL; + + *pnread = 0; + tail = get_non_full_tail(q); + if(!tail) { + if(q->chunk_count < q->max_chunks) + return CURLE_OUT_OF_MEMORY; + /* full, blocked */ + return CURLE_AGAIN; + } + + return chunk_slurpn(tail, max_len, reader, reader_ctx, pnread); +} + +/** + * Read up to `max_len` bytes and append it to the end of the buffer queue. + * if `max_len` is 0, no limit is imposed and the call behaves exactly + * the same as `Curl_bufq_slurp()`. + * Returns the total amount of buf read (may be 0) in `pnread` or error + * Note that even in case of an error chunks may have been read and + * the buffer queue will have different length than before. + */ +static CURLcode bufq_slurpn(struct bufq *q, size_t max_len, + Curl_bufq_reader *reader, void *reader_ctx, + size_t *pnread) +{ + CURLcode result; + + *pnread = 0; + while(1) { + size_t n; + result = Curl_bufq_sipn(q, max_len, reader, reader_ctx, &n); + if(result) { + if(!*pnread || result != CURLE_AGAIN) { + /* blocked on first read or real error, fail */ + return result; + } + result = CURLE_OK; + break; + } + else if(n == 0) { + /* eof, result remains CURLE_OK */ + break; + } + *pnread += n; + if(max_len) { + DEBUGASSERT(n <= max_len); + max_len -= n; + if(!max_len) + break; + } + /* give up slurping when we get less bytes than we asked for */ + if(q->tail && !chunk_is_full(q->tail)) + break; + } + return result; +} + +CURLcode Curl_bufq_slurp(struct bufq *q, Curl_bufq_reader *reader, + void *reader_ctx, size_t *pnread) +{ + return bufq_slurpn(q, 0, reader, reader_ctx, pnread); +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/bufq.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/bufq.h new file mode 100644 index 0000000000..c53749d84e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/bufq.h @@ -0,0 +1,257 @@ +#ifndef HEADER_CURL_BUFQ_H +#define HEADER_CURL_BUFQ_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/** + * A chunk of bytes for reading and writing. + * The size is fixed a creation with read and write offset + * for where unread content is. + */ +struct buf_chunk { + struct buf_chunk *next; /* to keep it in a list */ + size_t dlen; /* the amount of allocated x.data[] */ + size_t r_offset; /* first unread bytes */ + size_t w_offset; /* one after last written byte */ + union { + uint8_t data[1]; /* the buffer for `dlen` bytes */ + void *dummy; /* alignment */ + } x; +}; + +/** + * A pool for providing/keeping a number of chunks of the same size + * + * The same pool can be shared by many `bufq` instances. A pool is not thread + * safe. All bufqs using it are supposed to operate in the same thread. + */ +struct bufc_pool { + struct buf_chunk *spare; /* list of available spare chunks */ + size_t chunk_size; /* the size of chunks in this pool */ + size_t spare_count; /* current number of spare chunks in list */ + size_t spare_max; /* max number of spares to keep */ +}; + +void Curl_bufcp_init(struct bufc_pool *pool, + size_t chunk_size, size_t spare_max); + +void Curl_bufcp_free(struct bufc_pool *pool); + +/** + * A queue of byte chunks for reading and writing. + * Reading is done from `head`, writing is done to `tail`. + * + * `bufq`s can be empty or full or neither. Its `len` is the number + * of bytes that can be read. For an empty bufq, `len` will be 0. + * + * By default, a bufq can hold up to `max_chunks * chunk_size` number + * of bytes. When `max_chunks` are used (in the `head` list) and the + * `tail` chunk is full, the bufq will report that it is full. + * + * On a full bufq, `len` may be less than the maximum number of bytes, + * e.g. when the head chunk is partially read. `len` may also become + * larger than the max when option `BUFQ_OPT_SOFT_LIMIT` is used. + * + * By default, writing to a full bufq will return (-1, CURLE_AGAIN). Same + * as reading from an empty bufq. + * With `BUFQ_OPT_SOFT_LIMIT` set, a bufq will allow writing beyond this limit + * and use more than `max_chunks`. It will report that it is full + * nevertheless. This is provided for situation where writes preferably never + * fail (except for memory exhaustion). + * + * By default and without a pool, a bufq will keep chunks that read + * empty in its `spare` list. Option `BUFQ_OPT_NO_SPARES` will + * disable that and free chunks once they become empty. + * + * When providing a pool to a bufq, all chunk creation and spare handling + * will be delegated to that pool. + */ +struct bufq { + struct buf_chunk *head; /* chunk with bytes to read from */ + struct buf_chunk *tail; /* chunk to write to */ + struct buf_chunk *spare; /* list of free chunks, unless `pool` */ + struct bufc_pool *pool; /* optional pool for free chunks */ + size_t chunk_count; /* current number of chunks in `head+spare` */ + size_t max_chunks; /* max `head` chunks to use */ + size_t chunk_size; /* size of chunks to manage */ + int opts; /* options for handling queue, see below */ +}; + +/** + * Default behaviour: chunk limit is "hard", meaning attempts to write + * more bytes than can be hold in `max_chunks` is refused and will return + * -1, CURLE_AGAIN. */ +#define BUFQ_OPT_NONE 0 +/** + * Make `max_chunks` a "soft" limit. A bufq will report that it is "full" + * when `max_chunks` are used, but allows writing beyond this limit. + */ +#define BUFQ_OPT_SOFT_LIMIT (1 << 0) +/** + * Do not keep spare chunks. + */ +#define BUFQ_OPT_NO_SPARES (1 << 1) + +/** + * Initialize a buffer queue that can hold up to `max_chunks` buffers + * each of size `chunk_size`. The bufq will not allow writing of + * more bytes than can be held in `max_chunks`. + */ +void Curl_bufq_init(struct bufq *q, size_t chunk_size, size_t max_chunks); + +/** + * Initialize a buffer queue that can hold up to `max_chunks` buffers + * each of size `chunk_size` with the given options. See `BUFQ_OPT_*`. + */ +void Curl_bufq_init2(struct bufq *q, size_t chunk_size, + size_t max_chunks, int opts); + +void Curl_bufq_initp(struct bufq *q, struct bufc_pool *pool, + size_t max_chunks, int opts); + +/** + * Reset the buffer queue to be empty. Keep any allocated buffer chunks + * around. + */ +void Curl_bufq_reset(struct bufq *q); + +/** + * Free all resources held by the buffer queue. + */ +void Curl_bufq_free(struct bufq *q); + +/** + * Return the total amount of data in the queue. + */ +size_t Curl_bufq_len(const struct bufq *q); + +/** + * Returns TRUE iff there is no data in the buffer queue. + */ +bool Curl_bufq_is_empty(const struct bufq *q); + +/** + * Returns TRUE iff there is no space left in the buffer queue. + */ +bool Curl_bufq_is_full(const struct bufq *q); + +/** + * Write buf to the end of the buffer queue. The buf is copied + * and the amount of copied bytes is returned. + * CURLE_AGAIN is returned if the buffer queue is full. + */ +CURLcode Curl_bufq_write(struct bufq *q, + const uint8_t *buf, size_t len, + size_t *pnwritten); + +CURLcode Curl_bufq_cwrite(struct bufq *q, + const char *buf, size_t len, + size_t *pnwritten); + +/** + * Read buf from the start of the buffer queue. The buf is copied + * and the amount of copied bytes is returned. + */ +CURLcode Curl_bufq_read(struct bufq *q, uint8_t *buf, size_t len, + size_t *pnread); + +CURLcode Curl_bufq_cread(struct bufq *q, char *buf, size_t len, + size_t *pnread); + +/** + * Peek at the head chunk in the buffer queue. Returns a pointer to + * the chunk buf (at the current offset) and its length. Does not + * modify the buffer queue. + * Returns TRUE iff bytes are available. Sets `pbuf` to NULL and `plen` + * to 0 when no bytes are available. + * Repeated calls return the same information until the buffer queue + * is modified, see `Curl_bufq_skip()`` + */ +bool Curl_bufq_peek(struct bufq *q, + const uint8_t **pbuf, size_t *plen); + +bool Curl_bufq_peek_at(struct bufq *q, size_t offset, + const uint8_t **pbuf, size_t *plen); + +/** + * Tell the buffer queue to discard `amount` buf bytes at the head of the + * queue. Skipping more buf than is currently buffered will empty the queue. + */ +void Curl_bufq_skip(struct bufq *q, size_t amount); + +typedef CURLcode Curl_bufq_writer(void *writer_ctx, + const uint8_t *buf, size_t len, + size_t *pwritten); + +/** + * Passes the chunks in the buffer queue to the writer and returns + * the amount of buf written. A writer may return -1 and CURLE_AGAIN + * to indicate blocking at which point the queue will stop and return + * the amount of buf passed so far. + * -1 is returned on any other errors reported by the writer. + * Note that in case of a -1 chunks may have been written and + * the buffer queue will have different length than before. + */ +CURLcode Curl_bufq_pass(struct bufq *q, Curl_bufq_writer *writer, + void *writer_ctx, size_t *pwritten); + +typedef CURLcode Curl_bufq_reader(void *reader_ctx, + uint8_t *buf, size_t len, + size_t *pnread); + +/** + * Read bytes and append them to the end of the buffer queue until the + * reader returns blocking or the queue is full. A reader returns + * CURLE_AGAIN to indicate blocking. + * Returns the total amount of buf read (may be 0) in `pnread` on success. + * Note that in case of an error chunks may have been read and + * the buffer queue will have different length than before. + */ +CURLcode Curl_bufq_slurp(struct bufq *q, Curl_bufq_reader *reader, + void *reader_ctx, size_t *pnread); + +/** + * Read *once* up to `max_len` bytes and append it to the buffer. + * if `max_len` is 0, no limit is imposed besides the chunk space. + * Returns the total amount of buf read (may be 0) or -1 on other + * reader errors. + */ +CURLcode Curl_bufq_sipn(struct bufq *q, size_t max_len, + Curl_bufq_reader *reader, void *reader_ctx, + size_t *pnread); + +/** + * Write buf to the end of the buffer queue. + * Write bufq content or passed `buf` directly using the `writer` + * callback when it sees fit. 'buf' might get passed directly + * on or is placed into the buffer, depending on `len` and current + * amount buffered, chunk size, etc. + */ +CURLcode Curl_bufq_write_pass(struct bufq *q, + const uint8_t *buf, size_t len, + Curl_bufq_writer *writer, void *writer_ctx, + size_t *pwritten); + +#endif /* HEADER_CURL_BUFQ_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/bufref.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/bufref.c new file mode 100644 index 0000000000..50fafdac03 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/bufref.c @@ -0,0 +1,138 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "bufref.h" +#include "curlx/strdup.h" + +#ifdef DEBUGBUILD +#define SIGNATURE 0x5c48e9b2 /* Random pattern. */ +#endif + +/* + * Init a bufref struct. + */ +void Curl_bufref_init(struct bufref *br) +{ + DEBUGASSERT(br); + br->dtor = NULL; + br->ptr = NULL; + br->len = 0; + +#ifdef DEBUGBUILD + br->signature = SIGNATURE; +#endif +} + +/* + * Free the buffer and re-init the necessary fields. It does not touch the + * 'signature' field and thus this buffer reference can be reused. + */ + +void Curl_bufref_free(struct bufref *br) +{ + DEBUGASSERT(br); + DEBUGASSERT(br->signature == SIGNATURE); + DEBUGASSERT(br->ptr || !br->len); + + if(br->ptr && br->dtor) + br->dtor(CURL_UNCONST(br->ptr)); + + br->dtor = NULL; + br->ptr = NULL; + br->len = 0; +} + +/* + * Set the buffer reference to new values. The previously referenced buffer + * is released before assignment. + */ +void Curl_bufref_set(struct bufref *br, const void *ptr, size_t len, + void (*dtor)(void *)) +{ + DEBUGASSERT(ptr || !len); + DEBUGASSERT(len <= CURL_MAX_INPUT_LENGTH); + + Curl_bufref_free(br); + br->ptr = (const unsigned char *)ptr; + br->len = len; + br->dtor = dtor; +} + +/* + * Get a pointer to the referenced buffer. + */ +const unsigned char *Curl_bufref_uptr(const struct bufref *br) +{ + DEBUGASSERT(br); + DEBUGASSERT(br->signature == SIGNATURE); + DEBUGASSERT(br->ptr || !br->len); + + return br->ptr; +} + +/* + * Get a pointer to the referenced string. + */ +const char *Curl_bufref_ptr(const struct bufref *br) +{ + DEBUGASSERT(br); + DEBUGASSERT(br->signature == SIGNATURE); + DEBUGASSERT(br->ptr || !br->len); + + return (const char *)br->ptr; +} + +/* + * Get the length of the referenced buffer data. + */ +size_t Curl_bufref_len(const struct bufref *br) +{ + DEBUGASSERT(br); + DEBUGASSERT(br->signature == SIGNATURE); + DEBUGASSERT(br->ptr || !br->len); + + return br->len; +} + +CURLcode Curl_bufref_memdup0(struct bufref *br, const void *ptr, size_t len) +{ + unsigned char *cpy = NULL; + + DEBUGASSERT(br); + DEBUGASSERT(br->signature == SIGNATURE); + DEBUGASSERT(br->ptr || !br->len); + DEBUGASSERT(ptr || !len); + DEBUGASSERT(len <= CURL_MAX_INPUT_LENGTH); + + if(ptr) { + cpy = curlx_memdup0(ptr, len); + if(!cpy) + return CURLE_OUT_OF_MEMORY; + } + + Curl_bufref_set(br, cpy, len, curl_free); + return CURLE_OK; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/bufref.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/bufref.h new file mode 100644 index 0000000000..5d331adbdf --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/bufref.h @@ -0,0 +1,51 @@ +#ifndef HEADER_CURL_BUFREF_H +#define HEADER_CURL_BUFREF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Generic buffer reference. + */ +struct bufref { + void (*dtor)(void *); /* Associated destructor. */ + const unsigned char *ptr; /* Referenced data buffer. */ + size_t len; /* The data size in bytes. */ +#ifdef DEBUGBUILD + int signature; /* Detect API use mistakes. */ +#endif +}; + +void Curl_bufref_init(struct bufref *br); +void Curl_bufref_set(struct bufref *br, const void *ptr, size_t len, + void (*dtor)(void *)); +const char *Curl_bufref_ptr(const struct bufref *br); +const unsigned char *Curl_bufref_uptr(const struct bufref *br); +size_t Curl_bufref_len(const struct bufref *br); +CURLcode Curl_bufref_memdup0(struct bufref *br, const void *ptr, size_t len); +void Curl_bufref_free(struct bufref *br); + +/* return a strdup() version of the buffer */ +#define Curl_bufref_dup(x) curlx_strdup(Curl_bufref_ptr(x)) + +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-h1-proxy.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-h1-proxy.c new file mode 100644 index 0000000000..49b157bb3a --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-h1-proxy.c @@ -0,0 +1,1005 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP) + + +#include <curl/curl.h> +#include "urldata.h" +#include "curlx/dynbuf.h" +#include "sendf.h" +#include "http.h" +#include "http1.h" +#include "http_proxy.h" +#include "select.h" +#include "progress.h" +#include "multiif.h" +#include "cfilters.h" +#include "cf-h1-proxy.h" +#include "connect.h" +#include "curl_trc.h" +#include "strcase.h" +#include "curlx/strparse.h" + +typedef enum { + H1_TUNNEL_INIT, /* init/default/no tunnel state */ + H1_TUNNEL_CONNECT, /* CONNECT request is being send */ + H1_TUNNEL_RECEIVE, /* CONNECT answer is being received */ + H1_TUNNEL_RESPONSE, /* CONNECT response received completely */ + H1_TUNNEL_ESTABLISHED, + H1_TUNNEL_FAILED +} h1_tunnel_state; + +/* struct for HTTP CONNECT tunneling */ +struct h1_tunnel_state { + struct Curl_peer *dest; + struct dynbuf rcvbuf; + struct dynbuf request_data; + size_t nsent; + size_t headerlines; + struct Curl_chunker ch; + int httpversion; + enum keeponval { + KEEPON_DONE, + KEEPON_CONNECT, + KEEPON_IGNORE + } keepon; + curl_off_t cl; /* size of content to read and ignore */ + h1_tunnel_state tunnel_state; + BIT(chunked_encoding); + BIT(close_connection); + BIT(maybe_folded); + BIT(leading_unfold); +}; + +/* Persistent context for the H1-PROXY filter */ +struct cf_h1_proxy_ctx { + struct h1_tunnel_state *ts; + BIT(udp_tunnel); +}; + +static bool tunnel_is_established(struct h1_tunnel_state *ts) +{ + return ts && (ts->tunnel_state == H1_TUNNEL_ESTABLISHED); +} + +static bool tunnel_is_failed(struct h1_tunnel_state *ts) +{ + return ts && (ts->tunnel_state == H1_TUNNEL_FAILED); +} + +static bool h1_proxy_is_udp(struct Curl_cfilter *cf) +{ + struct cf_h1_proxy_ctx *pctx = cf->ctx; + return (pctx->udp_tunnel ? TRUE : FALSE); +} + +static CURLcode tunnel_reinit(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts) +{ + (void)data; + (void)cf; + DEBUGASSERT(ts); + curlx_dyn_reset(&ts->rcvbuf); + curlx_dyn_reset(&ts->request_data); + ts->tunnel_state = H1_TUNNEL_INIT; + ts->keepon = KEEPON_CONNECT; + ts->cl = 0; + ts->close_connection = FALSE; + ts->maybe_folded = FALSE; + ts->leading_unfold = FALSE; + ts->nsent = 0; + ts->headerlines = 0; + return CURLE_OK; +} + +static CURLcode tunnel_init(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state **pts) +{ + struct h1_tunnel_state *ts; + + if(cf->conn->scheme->flags & PROTOPT_NOTCPPROXY) { + failf(data, "%s cannot be done over CONNECT", cf->conn->scheme->name); + return CURLE_UNSUPPORTED_PROTOCOL; + } + + ts = curlx_calloc(1, sizeof(*ts)); + if(!ts) + return CURLE_OUT_OF_MEMORY; + + infof(data, "allocate connect buffer"); + + curlx_dyn_init(&ts->rcvbuf, DYN_PROXY_CONNECT_HEADERS); + curlx_dyn_init(&ts->request_data, DYN_HTTP_REQUEST); + Curl_httpchunk_init(data, &ts->ch, TRUE, TRUE); + + *pts = ts; + return tunnel_reinit(cf, data, ts); +} + +static void h1_tunnel_go_state(struct Curl_cfilter *cf, + struct h1_tunnel_state *ts, + h1_tunnel_state new_state, + struct Curl_easy *data) +{ + if(ts->tunnel_state == new_state) + return; + /* entering this one */ + switch(new_state) { + case H1_TUNNEL_INIT: + CURL_TRC_CF(data, cf, "new tunnel state 'init'"); + tunnel_reinit(cf, data, ts); + break; + + case H1_TUNNEL_CONNECT: + CURL_TRC_CF(data, cf, "new tunnel state 'connect'"); + ts->tunnel_state = H1_TUNNEL_CONNECT; + ts->keepon = KEEPON_CONNECT; + curlx_dyn_reset(&ts->rcvbuf); + break; + + case H1_TUNNEL_RECEIVE: + CURL_TRC_CF(data, cf, "new tunnel state 'receive'"); + ts->tunnel_state = H1_TUNNEL_RECEIVE; + break; + + case H1_TUNNEL_RESPONSE: + CURL_TRC_CF(data, cf, "new tunnel state 'response'"); + ts->tunnel_state = H1_TUNNEL_RESPONSE; + break; + + case H1_TUNNEL_ESTABLISHED: + CURL_TRC_CF(data, cf, "new tunnel state 'established'"); + infof(data, "CONNECT%s phase completed for HTTP proxy", + h1_proxy_is_udp(cf) ? "-UDP" : ""); + + data->state.authproxy.done = TRUE; + data->state.authproxy.multipass = FALSE; + FALLTHROUGH(); + case H1_TUNNEL_FAILED: + if(new_state == H1_TUNNEL_FAILED) + CURL_TRC_CF(data, cf, "new tunnel state 'failed'"); + ts->tunnel_state = new_state; + curlx_dyn_reset(&ts->rcvbuf); + curlx_dyn_reset(&ts->request_data); + /* restore the protocol pointer */ + data->info.httpcode = 0; /* clear it as it might have been used for the + proxy */ + /* If a proxy-authorization header was used for the proxy, then we should + make sure that it is not accidentally used for the document request + after we have connected. Let's thus free and clear it here. */ + curlx_safefree(data->req.hd_proxy_auth); + break; + } +} + +static void tunnel_free(struct h1_tunnel_state *ts, + struct Curl_easy *data) +{ + if(ts) { + Curl_peer_unlink(&ts->dest); + curlx_dyn_free(&ts->rcvbuf); + curlx_dyn_free(&ts->request_data); + Curl_httpchunk_free(data, &ts->ch); + curlx_free(ts); + } +} + +static void cf_tunnel_free(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + if(cf) { + struct cf_h1_proxy_ctx *pctx = cf->ctx; + struct h1_tunnel_state *ts = pctx ? pctx->ts : NULL; + if(ts) { + h1_tunnel_go_state(cf, ts, H1_TUNNEL_FAILED, data); + tunnel_free(ts, data); + pctx->ts = NULL; + } + } +} + +static bool tunnel_want_send(struct h1_tunnel_state *ts) +{ + return ts->tunnel_state == H1_TUNNEL_CONNECT; +} + +static CURLcode start_CONNECT(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts) +{ + struct httpreq *req = NULL; + int http_minor; + CURLcode result; + + DEBUGASSERT(data); + /* This only happens if we have looped here due to authentication reasons, + and we do not really use the newly cloned URL here then. Free it. */ + curlx_safefree(data->req.newurl); + + result = Curl_http_proxy_create_tunnel_request(&req, cf, data, ts->dest, + PROXY_HTTP_V1, + h1_proxy_is_udp(cf)); + if(result) + goto out; + + curlx_dyn_reset(&ts->request_data); + ts->nsent = 0; + ts->headerlines = 0; + http_minor = ts->httpversion % 10; + + result = Curl_h1_req_write_head(req, http_minor, &ts->request_data); + if(!result) + result = Curl_creader_set_null(data); + +out: + if(result) + failf(data, "Failed sending CONNECT to proxy"); + if(req) + Curl_http_req_free(req); + return result; +} + +static CURLcode send_CONNECT(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts, + bool *done) +{ + const uint8_t *buf = curlx_dyn_uptr(&ts->request_data); + size_t request_len = curlx_dyn_len(&ts->request_data); + size_t blen = request_len; + CURLcode result = CURLE_OK; + size_t nwritten; + + if(blen <= ts->nsent) + goto out; /* we are done */ + + blen -= ts->nsent; + buf += ts->nsent; + + result = cf->next->cft->do_send(cf->next, data, buf, blen, FALSE, &nwritten); + if(result) { + if(result == CURLE_AGAIN) + result = CURLE_OK; + goto out; + } + + DEBUGASSERT(blen >= nwritten); + ts->nsent += nwritten; + Curl_debug(data, CURLINFO_HEADER_OUT, (const char *)buf, nwritten); + +out: + if(result) + failf(data, "Failed sending CONNECT to proxy"); + *done = (!result && (ts->nsent >= request_len)); + return result; +} + +static CURLcode on_resp_header_udp(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts, + const char *header) +{ + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + + if((checkprefix("WWW-Authenticate:", header) && (401 == k->httpcode)) || + (checkprefix("Proxy-authenticate:", header) && (407 == k->httpcode))) { + + bool proxy = (k->httpcode == 407); + char *auth = Curl_copy_header_value(header); + if(!auth) + return CURLE_OUT_OF_MEMORY; + + CURL_TRC_CF(data, cf, "CONNECT-UDP: fwd auth header '%s'", header); + result = Curl_http_input_auth(data, proxy, auth); + + curlx_free(auth); + + if(result) + return result; + } + else if(checkprefix("Content-Length:", header)) { + if(k->httpcode / 100 == 2 || k->httpcode == 101) { + infof(data, "Ignoring Content-Length in CONNECT-UDP %03d response", + k->httpcode); + } + else { + const char *p = header + CURL_CSTRLEN("Content-Length:"); + if(curlx_str_numblanks(&p, &ts->cl)) { + failf(data, "Unsupported Content-Length value"); + return CURLE_WEIRD_SERVER_REPLY; + } + } + } + else if(checkprefix("Transfer-Encoding:", header)) { + if(k->httpcode / 100 == 2 || k->httpcode == 101) { + infof(data, "Ignoring Transfer-Encoding in " + "CONNECT-UDP %03d response", k->httpcode); + } + else if(Curl_compareheader(header, + STRCONST("Transfer-Encoding:"), + STRCONST("chunked"))) { + CURL_TRC_CF(data, cf, "CONNECT-UDP Response --> " + "Transfer-Encoding: chunked"); + ts->chunked_encoding = TRUE; + /* reset our chunky engine */ + Curl_httpchunk_reset(data, &ts->ch, TRUE); + } + } + else if(checkprefix("Capsule-protocol:", header)) { + if(Curl_compareheader(header, + STRCONST("Capsule-protocol:"), + STRCONST("?1"))) { + CURL_TRC_CF(data, cf, "CONNECT-UDP Response --> Capsule-protocol: ?1"); + } + } + else if(Curl_compareheader(header, + STRCONST("Connection:"), STRCONST("close"))) { + ts->close_connection = TRUE; + CURL_TRC_CF(data, cf, "CONNECT-UDP Response --> Connection: close"); + } + else if(Curl_compareheader(header, + STRCONST("Proxy-Connection:"), + STRCONST("close"))) { + ts->close_connection = TRUE; + CURL_TRC_CF(data, cf, + "CONNECT-UDP Response --> Proxy-Connection: close"); + } + else if(!strncmp(header, "HTTP/1.", 7) && + ((header[7] == '0') || (header[7] == '1')) && + (header[8] == ' ') && + ISDIGIT(header[9]) && ISDIGIT(header[10]) && ISDIGIT(header[11]) && + !ISDIGIT(header[12])) { + /* store the HTTP code from the proxy */ + data->info.httpproxycode = k->httpcode = + ((header[9] - '0') * 100) + + ((header[10] - '0') * 10) + + (header[11] - '0'); + CURL_TRC_CF(data, cf, "CONNECT-UDP Response --> %d", k->httpcode); + } + return result; +} + +static CURLcode on_resp_header(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts, + const char *header) +{ + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + (void)cf; + + if((checkprefix("WWW-Authenticate:", header) && (401 == k->httpcode)) || + (checkprefix("Proxy-authenticate:", header) && (407 == k->httpcode))) { + + bool proxy = (k->httpcode == 407); + char *auth = Curl_copy_header_value(header); + if(!auth) + return CURLE_OUT_OF_MEMORY; + + CURL_TRC_CF(data, cf, "CONNECT: fwd auth header '%s'", header); + result = Curl_http_input_auth(data, proxy, auth); + + curlx_free(auth); + + if(result) + return result; + } + else if(checkprefix("Content-Length:", header)) { + if(k->httpcode / 100 == 2) { + /* A client MUST ignore any Content-Length or Transfer-Encoding + header fields received in a successful response to CONNECT. + "Successful" described as: 2xx (Successful). RFC 7231 4.3.6 */ + infof(data, "Ignoring Content-Length in CONNECT %03d response", + k->httpcode); + } + else { + const char *p = header + CURL_CSTRLEN("Content-Length:"); + if(curlx_str_numblanks(&p, &ts->cl)) { + failf(data, "Unsupported Content-Length value"); + return CURLE_WEIRD_SERVER_REPLY; + } + } + } + else if(Curl_compareheader(header, + STRCONST("Connection:"), STRCONST("close"))) + ts->close_connection = TRUE; + else if(checkprefix("Transfer-Encoding:", header)) { + if(k->httpcode / 100 == 2) { + /* A client MUST ignore any Content-Length or Transfer-Encoding + header fields received in a successful response to CONNECT. + "Successful" described as: 2xx (Successful). RFC 7231 4.3.6 */ + infof(data, "Ignoring Transfer-Encoding in " + "CONNECT %03d response", k->httpcode); + } + else if(Curl_compareheader(header, + STRCONST("Transfer-Encoding:"), + STRCONST("chunked"))) { + infof(data, "CONNECT responded chunked"); + ts->chunked_encoding = TRUE; + /* reset our chunky engine */ + Curl_httpchunk_reset(data, &ts->ch, TRUE); + } + } + else if(Curl_compareheader(header, + STRCONST("Proxy-Connection:"), + STRCONST("close"))) + ts->close_connection = TRUE; + else if(!strncmp(header, "HTTP/1.", 7) && + ((header[7] == '0') || (header[7] == '1')) && + (header[8] == ' ') && + ISDIGIT(header[9]) && ISDIGIT(header[10]) && ISDIGIT(header[11]) && + !ISDIGIT(header[12])) { + /* store the HTTP code from the proxy */ + data->info.httpproxycode = k->httpcode = ((header[9] - '0') * 100) + + ((header[10] - '0') * 10) + (header[11] - '0'); + } + return result; +} + +static CURLcode single_header(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts) +{ + CURLcode result = CURLE_OK; + const char *linep = curlx_dyn_ptr(&ts->rcvbuf); + size_t line_len = curlx_dyn_len(&ts->rcvbuf); /* bytes in this line */ + const struct SingleRequest *k = &data->req; + int writetype; + ts->headerlines++; + + /* output debug if that is requested */ + Curl_debug(data, CURLINFO_HEADER_IN, linep, line_len); + + /* a CONNECT response line is handed to the client as a header, so it must + pass the same checks as a regular response header before delivery */ + result = Curl_verify_header(data, linep, line_len); + if(result) + return result; + + /* send the header to the callback */ + writetype = CLIENTWRITE_HEADER | CLIENTWRITE_CONNECT | + (ts->headerlines == 1 ? CLIENTWRITE_STATUS : 0); + result = Curl_client_write(data, writetype, linep, line_len); + if(result) + return result; + + result = Curl_bump_headersize(data, line_len, TRUE); + if(result) + return result; + + /* Newlines are CRLF, so the CR is ignored as the line is not + really terminated until the LF comes. Treat a following CR + as end-of-headers as well.*/ + + if(ISNEWLINE(linep[0])) { + /* end of response-headers from the proxy */ + + if((407 == k->httpcode) && !data->state.authproblem) { + /* If we get a 407 response code with content length + when we have no auth problem, we must ignore the + whole response-body */ + ts->keepon = KEEPON_IGNORE; + + if(ts->cl) { + infof(data, "Ignore %" FMT_OFF_T " bytes of response-body", ts->cl); + } + else if(ts->chunked_encoding) { + infof(data, "Ignore chunked response-body"); + } + else { + /* without content-length or chunked encoding, we + cannot keep the connection alive since the close is + the end signal so we bail out at once instead */ + CURL_TRC_CF(data, cf, "CONNECT: no content-length or chunked"); + ts->keepon = KEEPON_DONE; + } + } + else { + ts->keepon = KEEPON_DONE; + } + + DEBUGASSERT(ts->keepon == KEEPON_IGNORE || + ts->keepon == KEEPON_DONE); + return result; + } + + if(h1_proxy_is_udp(cf)) { + result = on_resp_header_udp(cf, data, ts, linep); + } + else { + result = on_resp_header(cf, data, ts, linep); + } + + if(result) + return result; + + curlx_dyn_reset(&ts->rcvbuf); + return result; +} + +static CURLcode recv_CONNECT_resp(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts, + bool *done) +{ + CURLcode result = CURLE_OK; + int error; + +#define SELECT_OK 0 +#define SELECT_ERROR 1 + + error = SELECT_OK; + *done = FALSE; + + while(ts->keepon) { + size_t nread; + char byte; + + /* Read one byte at a time to avoid a race condition. Wait at most one + second before looping to ensure continuous pgrsUpdates. */ + result = Curl_conn_recv(data, cf->sockindex, &byte, 1, &nread); + if(result == CURLE_AGAIN) + /* socket buffer drained, return */ + return CURLE_OK; + + if(!result) + result = Curl_pgrsUpdate(data); + + if(result) { + ts->keepon = KEEPON_DONE; + break; + } + + if(!nread) { + if(ts->maybe_folded) { + /* EOF right after LF: finalize the pending header line. */ + result = single_header(cf, data, ts); + if(result) + return result; + ts->maybe_folded = FALSE; + } + if(data->set.proxyauth && data->state.authproxy.avail && + data->req.hd_proxy_auth) { + /* proxy auth was requested and there was proxy auth available, + then deem this as "mere" proxy disconnect */ + ts->close_connection = TRUE; + infof(data, "Proxy CONNECT connection closed"); + } + else { + error = SELECT_ERROR; + failf(data, "Proxy CONNECT aborted"); + } + ts->keepon = KEEPON_DONE; + break; + } + + if(ts->keepon == KEEPON_IGNORE) { + /* This means we are currently ignoring a response-body */ + if(ts->chunked_encoding) { + /* chunked-encoded body, so we need to do the chunked dance + properly to know when the end of the body is reached */ + size_t consumed = 0; + + /* now parse the chunked piece of data so that we can + properly tell when the stream ends */ + result = Curl_httpchunk_read(data, &ts->ch, &byte, 1, &consumed); + if(result) + return result; + if(Curl_httpchunk_is_done(data, &ts->ch)) { + /* we are done reading chunks! */ + infof(data, "chunk reading DONE"); + ts->keepon = KEEPON_DONE; + } + } + else if(ts->cl) { + /* A Content-Length based body: count down the counter + and make sure to break out of the loop when we are done! */ + ts->cl--; + if(ts->cl <= 0) { + ts->keepon = KEEPON_DONE; + break; + } + } + continue; + } + + if(ts->maybe_folded) { + if(ISBLANK(byte)) { + Curl_http_to_fold(&ts->rcvbuf); + ts->leading_unfold = TRUE; + } + else { + result = single_header(cf, data, ts); + if(result) + return result; + /* now handle the new byte */ + } + ts->maybe_folded = FALSE; + } + + if(ts->leading_unfold) { + if(ISBLANK(byte)) + /* skip a bit brother */ + continue; + /* non-blank, insert a space then continue the unfolding */ + if(curlx_dyn_addn(&ts->rcvbuf, " ", 1)) { + failf(data, "CONNECT response too large"); + return CURLE_RECV_ERROR; + } + ts->leading_unfold = FALSE; + } + if(curlx_dyn_addn(&ts->rcvbuf, &byte, 1)) { + failf(data, "CONNECT response too large"); + return CURLE_RECV_ERROR; + } + + /* if this is not the end of a header line then continue */ + if(byte != 0x0a) + continue; + else { + const char *linep = curlx_dyn_ptr(&ts->rcvbuf); + size_t hlen = curlx_dyn_len(&ts->rcvbuf); + if(hlen && ISNEWLINE(linep[0])) { + /* end of headers */ + result = single_header(cf, data, ts); + if(result) + return result; + } + else + ts->maybe_folded = TRUE; + } + + if(result) + return result; + } /* while there is buffer left and loop is requested */ + + if(error) + result = CURLE_RECV_ERROR; + *done = (ts->keepon == KEEPON_DONE); + if(!result && *done && + data->info.httpproxycode / 100 != 2 && + !(h1_proxy_is_udp(cf) && data->info.httpproxycode == 101)) { + /* Deal with the possibly already received authenticate + headers. 'newurl' is set to a new URL if we must loop. */ + result = Curl_http_auth_act(data); + } + return result; +} + +static CURLcode H1_CONNECT(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h1_tunnel_state *ts) +{ + struct connectdata *conn = cf->conn; + CURLcode result; + bool done; + + if(tunnel_is_established(ts)) + return CURLE_OK; + if(tunnel_is_failed(ts)) + return CURLE_RECV_ERROR; /* Need a cfilter close and new bootstrap */ + + do { + + if(Curl_timeleft_ms(data) < 0) { + failf(data, "Proxy CONNECT aborted due to timeout"); + result = CURLE_OPERATION_TIMEDOUT; + goto out; + } + + switch(ts->tunnel_state) { + case H1_TUNNEL_INIT: + /* Prepare the CONNECT request and make a first attempt to send. */ + CURL_TRC_CF(data, cf, "CONNECT start"); + result = start_CONNECT(cf, data, ts); + if(result) + goto out; + h1_tunnel_go_state(cf, ts, H1_TUNNEL_CONNECT, data); + FALLTHROUGH(); + + case H1_TUNNEL_CONNECT: + /* see that the request is completely sent */ + CURL_TRC_CF(data, cf, "CONNECT send"); + result = send_CONNECT(cf, data, ts, &done); + if(result || !done) + goto out; + h1_tunnel_go_state(cf, ts, H1_TUNNEL_RECEIVE, data); + FALLTHROUGH(); + + case H1_TUNNEL_RECEIVE: + /* read what is there */ + CURL_TRC_CF(data, cf, "CONNECT receive"); + result = recv_CONNECT_resp(cf, data, ts, &done); + if(result) + CURL_TRC_CF(data, cf, "error receiving CONNECT response: %d", + (int)result); + if(!result) + result = Curl_pgrsUpdate(data); + /* error or not complete yet. return for more multi-multi */ + if(result || !done) + goto out; + /* got it */ + h1_tunnel_go_state(cf, ts, H1_TUNNEL_RESPONSE, data); + FALLTHROUGH(); + + case H1_TUNNEL_RESPONSE: + CURL_TRC_CF(data, cf, "CONNECT response"); + if(data->req.newurl) { + /* not the "final" response, we need to do a follow up request. + * If the other side indicated a connection close, or if someone + * else told us to close this connection, do so now. + */ + Curl_req_soft_reset(&data->req, data); + if(ts->close_connection || conn->bits.close) { + /* Close this filter and the sub-chain, re-connect the + * sub-chain and continue. Closing this filter will + * reset our tunnel state. To avoid recursion, we return + * and expect to be called again. + */ + CURL_TRC_CF(data, cf, "CONNECT need to close+open"); + infof(data, "Connect me again please"); + return CURLE_AGAIN; + } + else { + /* staying on this connection, reset state */ + h1_tunnel_go_state(cf, ts, H1_TUNNEL_INIT, data); + } + } + break; + + default: + break; + } + + } while(data->req.newurl); + + DEBUGASSERT(ts->tunnel_state == H1_TUNNEL_RESPONSE); + if(h1_proxy_is_udp(cf)) { + /* RFC 9298: Accept 101 Upgrade for HTTP/1.1 and + * 2xx responses for HTTP/2 and HTTP/3 proxies. */ + if(data->info.httpproxycode / 100 != 2 && + data->info.httpproxycode != 101) { + curlx_safefree(data->req.newurl); + h1_tunnel_go_state(cf, ts, H1_TUNNEL_FAILED, data); + failf(data, "CONNECT-UDP tunnel failed, response %d", + data->req.httpcode); + return CURLE_COULDNT_CONNECT; + } + } + else { + if(data->info.httpproxycode / 100 != 2) { + /* a non-2xx response and we have no next URL to try. */ + curlx_safefree(data->req.newurl); + h1_tunnel_go_state(cf, ts, H1_TUNNEL_FAILED, data); + failf(data, "CONNECT tunnel failed, response %d", data->req.httpcode); + return CURLE_COULDNT_CONNECT; + } + } + /* 2xx response, SUCCESS! */ + /* 101 Switching Protocol for CONNECT-UDP */ + h1_tunnel_go_state(cf, ts, H1_TUNNEL_ESTABLISHED, data); + if(h1_proxy_is_udp(cf)) + infof(data, "CONNECT-UDP tunnel established, response %d", + data->info.httpproxycode); + else + infof(data, "CONNECT tunnel established, response %d", + data->info.httpproxycode); + result = CURLE_OK; + +out: + if(result) + h1_tunnel_go_state(cf, ts, H1_TUNNEL_FAILED, data); + return result; +} + +static CURLcode cf_h1_proxy_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + CURLcode result; + struct cf_h1_proxy_ctx *pctx = cf->ctx; + struct h1_tunnel_state *ts = pctx->ts; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + CURL_TRC_CF(data, cf, "connect"); + result = cf->next->cft->do_connect(cf->next, data, done); + if(result || !*done) + return result; + + *done = FALSE; + if(!ts) { + result = tunnel_init(cf, data, &ts); + if(result) + return result; + pctx->ts = ts; + } + + /* We want "seamless" operations through HTTP proxy tunnel */ + + result = H1_CONNECT(cf, data, ts); + if(result) + goto out; + curlx_safefree(data->req.hd_proxy_auth); + +out: + *done = (result == CURLE_OK) && tunnel_is_established(pctx->ts); + if(*done) { + cf->connected = TRUE; + /* The real request will follow the CONNECT, reset request partially */ + Curl_req_soft_reset(&data->req, data); + Curl_client_reset(data); + Curl_pgrsReset(data); + cf_tunnel_free(cf, data); + } + return result; +} + +static CURLcode cf_h1_proxy_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_h1_proxy_ctx *pctx = cf->ctx; + struct h1_tunnel_state *ts = pctx->ts; + CURLcode result = CURLE_OK; + + if(!cf->connected) { + /* If we are not connected, but the filter "below" is + * and not waiting on something, we are tunneling. */ + curl_socket_t sock = Curl_conn_cf_get_socket(cf, data); + if(ts) { + /* when we have sent a CONNECT to a proxy, we should rather either + wait for the socket to become readable to be able to get the + response headers or if we are still sending the request, wait + for write. */ + if(tunnel_want_send(ts)) + result = Curl_pollset_set_out_only(data, ps, sock); + else + result = Curl_pollset_set_in_only(data, ps, sock); + } + else + result = Curl_pollset_set_out_only(data, ps, sock); + } + else { + if(cf->next) + result = cf->next->cft->adjust_pollset(cf->next, data, ps); + } + return result; +} + +static bool cf_h1_proxy_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + return cf->next ? cf->next->cft->has_data_pending(cf->next, data) : FALSE; +} + +static void cf_h1_proxy_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURL_TRC_CF(data, cf, "destroy"); + cf_tunnel_free(cf, data); + curlx_safefree(cf->ctx); +} + +static CURLcode cf_h1_proxy_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_h1_proxy_ctx *pctx = cf->ctx; + struct h1_tunnel_state *ts = pctx ? pctx->ts : NULL; + switch(query) { + case CF_QUERY_HOST_PORT: + if(!ts || !ts->dest) + break; + *pres1 = (int)ts->dest->port; + *((const char **)pres2) = ts->dest->hostname; + return CURLE_OK; + case CF_QUERY_ALPN_NEGOTIATED: { + const char **palpn = pres2; + DEBUGASSERT(palpn); + *palpn = NULL; + return CURLE_OK; + } + default: + break; + } + return cf->next ? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +struct Curl_cftype Curl_cft_h1_proxy = { + "H1-PROXY", + CF_TYPE_IP_CONNECT | CF_TYPE_PROXY, + 0, + cf_h1_proxy_destroy, + cf_h1_proxy_connect, + Curl_cf_def_shutdown, + cf_h1_proxy_adjust_pollset, + cf_h1_proxy_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_h1_proxy_query, +}; + +CURLcode Curl_cf_h1_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *dest, + int httpversion, + bool udp_tunnel) +{ + struct Curl_cfilter *cf; + struct cf_h1_proxy_ctx *pctx; + struct h1_tunnel_state *ts; + CURLcode result; + + (void)data; + if(!dest) + return CURLE_FAILED_INIT; + if((httpversion < 10) || (httpversion >= 20)) + return CURLE_FAILED_INIT; + + ts = curlx_calloc(1, sizeof(*ts)); + if(!ts) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + Curl_peer_link(&ts->dest, dest); + ts->httpversion = httpversion; + curlx_dyn_init(&ts->rcvbuf, DYN_PROXY_CONNECT_HEADERS); + curlx_dyn_init(&ts->request_data, DYN_HTTP_REQUEST); + Curl_httpchunk_init(data, &ts->ch, TRUE, TRUE); + + pctx = curlx_calloc(1, sizeof(*pctx)); + if(!pctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + pctx->udp_tunnel = udp_tunnel; + pctx->ts = ts; + result = Curl_cf_create(&cf, &Curl_cft_h1_proxy, pctx); + if(result) { + curlx_free(pctx); + goto out; + } + ts = NULL; + Curl_conn_cf_insert_after(cf_at, cf); + +out: + tunnel_free(ts, data); + return result; +} + +#endif /* !CURL_DISABLE_PROXY && !CURL_DISABLE_HTTP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-h1-proxy.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-h1-proxy.h new file mode 100644 index 0000000000..3255bf79f2 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-h1-proxy.h @@ -0,0 +1,42 @@ +#ifndef HEADER_CURL_H1_PROXY_H +#define HEADER_CURL_H1_PROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP) + +struct Curl_peer; + +CURLcode Curl_cf_h1_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *dest, + int httpversion, + bool udp_tunnel); + +extern struct Curl_cftype Curl_cft_h1_proxy; + +#endif /* !CURL_DISABLE_PROXY && !CURL_DISABLE_HTTP */ + +#endif /* HEADER_CURL_H1_PROXY_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-h2-proxy.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-h2-proxy.c new file mode 100644 index 0000000000..fde9e1bc79 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-h2-proxy.c @@ -0,0 +1,1515 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_PROXY) && \ + defined(USE_NGHTTP2) + +#include <nghttp2/nghttp2.h> + +#include "urldata.h" +#include "url.h" +#include "cfilters.h" +#include "connect.h" +#include "curl_trc.h" +#include "bufq.h" +#include "curlx/dynbuf.h" +#include "dynhds.h" +#include "http2.h" +#include "http_proxy.h" +#include "multiif.h" +#include "sendf.h" +#include "select.h" +#include "cf-h2-proxy.h" + +#define PROXY_H2_CHUNK_SIZE (16 * 1024) + +#define PROXY_HTTP2_HUGE_WINDOW_SIZE (100 * 1024 * 1024) +#define H2_TUNNEL_WINDOW_SIZE (10 * 1024 * 1024) + +#define PROXY_H2_NW_RECV_CHUNKS (H2_TUNNEL_WINDOW_SIZE / PROXY_H2_CHUNK_SIZE) +#define PROXY_H2_NW_SEND_CHUNKS 1 + +#define H2_TUNNEL_RECV_CHUNKS (H2_TUNNEL_WINDOW_SIZE / PROXY_H2_CHUNK_SIZE) +#define H2_TUNNEL_SEND_CHUNKS ((128 * 1024) / PROXY_H2_CHUNK_SIZE) + + +typedef enum { + H2_TUNNEL_INIT, /* init/default/no tunnel state */ + H2_TUNNEL_CONNECT, /* CONNECT request is being send */ + H2_TUNNEL_RESPONSE, /* CONNECT response received completely */ + H2_TUNNEL_ESTABLISHED, + H2_TUNNEL_FAILED +} h2_tunnel_state; + +struct tunnel_stream { + struct http_resp *resp; + struct bufq recvbuf; + struct bufq sendbuf; + char *authority; + int32_t stream_id; + uint32_t error; + h2_tunnel_state state; + BIT(has_final_response); + BIT(closed); + BIT(reset); +}; + +static CURLcode tunnel_stream_init(struct tunnel_stream *ts, + struct Curl_peer *dest) +{ + ts->state = H2_TUNNEL_INIT; + ts->stream_id = -1; + Curl_bufq_init2(&ts->recvbuf, PROXY_H2_CHUNK_SIZE, H2_TUNNEL_RECV_CHUNKS, + BUFQ_OPT_SOFT_LIMIT); + Curl_bufq_init(&ts->sendbuf, PROXY_H2_CHUNK_SIZE, H2_TUNNEL_SEND_CHUNKS); + + /* host:port with IPv6 support */ + ts->authority = curl_maprintf("%s%s%s:%u", dest->ipv6 ? "[" : "", + dest->hostname, + dest->ipv6 ? "]" : "", + dest->port); + if(!ts->authority) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static void tunnel_stream_reset(struct tunnel_stream *ts) +{ + Curl_http_resp_free(ts->resp); + ts->resp = NULL; + Curl_bufq_reset(&ts->recvbuf); + Curl_bufq_reset(&ts->sendbuf); + ts->stream_id = -1; + ts->error = 0; + ts->has_final_response = FALSE; + ts->closed = FALSE; + ts->reset = FALSE; + ts->state = H2_TUNNEL_INIT; +} + +static void tunnel_stream_clear(struct tunnel_stream *ts) +{ + Curl_http_resp_free(ts->resp); + Curl_bufq_free(&ts->recvbuf); + Curl_bufq_free(&ts->sendbuf); + curlx_safefree(ts->authority); + memset(ts, 0, sizeof(*ts)); + ts->state = H2_TUNNEL_INIT; +} + +static void h2_tunnel_go_state(struct Curl_cfilter *cf, + struct tunnel_stream *ts, + h2_tunnel_state new_state, + struct Curl_easy *data, + bool udp_tunnel) +{ + (void)cf; + (void)udp_tunnel; + + if(ts->state == new_state) + return; + /* leaving this one */ + switch(ts->state) { + case H2_TUNNEL_CONNECT: + data->req.ignorebody = FALSE; + break; + default: + break; + } + /* entering this one */ + switch(new_state) { + case H2_TUNNEL_INIT: + CURL_TRC_CF(data, cf, "[%d] new tunnel state 'init'", ts->stream_id); + tunnel_stream_reset(ts); + break; + + case H2_TUNNEL_CONNECT: + CURL_TRC_CF(data, cf, "[%d] new tunnel state 'connect'", ts->stream_id); + ts->state = H2_TUNNEL_CONNECT; + break; + + case H2_TUNNEL_RESPONSE: + CURL_TRC_CF(data, cf, "[%d] new tunnel state 'response'", ts->stream_id); + ts->state = H2_TUNNEL_RESPONSE; + break; + + case H2_TUNNEL_ESTABLISHED: + CURL_TRC_CF(data, cf, "[%d] new tunnel state 'established'", + ts->stream_id); + infof(data, "CONNECT%s phase completed for HTTP/2 proxy", + udp_tunnel ? "-UDP" : ""); + data->state.authproxy.done = TRUE; + data->state.authproxy.multipass = FALSE; + FALLTHROUGH(); + case H2_TUNNEL_FAILED: + if(new_state == H2_TUNNEL_FAILED) + CURL_TRC_CF(data, cf, "[%d] new tunnel state 'failed'", ts->stream_id); + ts->state = new_state; + /* If a proxy-authorization header was used for the proxy, then we should + make sure that it is not accidentally used for the document request + after we have connected. Let's thus free and clear it here. */ + curlx_safefree(data->req.hd_proxy_auth); + break; + } +} + +struct cf_h2_proxy_ctx { + nghttp2_session *h2; + /* The easy handle used in the current filter call, cleared at return */ + struct cf_call_data call_data; + + struct bufq inbufq; /* network receive buffer */ + struct bufq outbufq; /* network send buffer */ + + struct Curl_peer *dest; /* where to tunnel to */ + struct tunnel_stream tunnel; /* our tunnel CONNECT stream */ + int32_t goaway_error; + int32_t remote_max_sid; + BIT(conn_closed); + BIT(rcvd_goaway); + BIT(sent_goaway); + BIT(nw_out_blocked); + BIT(udp_tunnel); +}; + +/* How to access `call_data` from a cf_h2 filter */ +#undef CF_CTX_CALL_DATA +#define CF_CTX_CALL_DATA(cf) ((struct cf_h2_proxy_ctx *)(cf)->ctx)->call_data + +static void cf_h2_proxy_ctx_clear(struct cf_h2_proxy_ctx *ctx) +{ + struct cf_call_data save = ctx->call_data; + + if(ctx->h2) { + nghttp2_session_del(ctx->h2); + } + Curl_bufq_free(&ctx->inbufq); + Curl_bufq_free(&ctx->outbufq); + Curl_peer_unlink(&ctx->dest); + tunnel_stream_clear(&ctx->tunnel); + memset(ctx, 0, sizeof(*ctx)); + ctx->call_data = save; +} + +static void cf_h2_proxy_ctx_free(struct cf_h2_proxy_ctx *ctx) +{ + if(ctx) { + cf_h2_proxy_ctx_clear(ctx); + curlx_free(ctx); + } +} + +static void drain_tunnel(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct tunnel_stream *tunnel) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + (void)cf; + if(!tunnel->closed && !tunnel->reset && + (!Curl_bufq_is_empty(&ctx->tunnel.sendbuf) || + !Curl_bufq_is_empty(&ctx->tunnel.recvbuf))) + Curl_multi_mark_dirty(data); +} + +static CURLcode proxy_h2_nw_out_writer(void *writer_ctx, + const uint8_t *buf, size_t buflen, + size_t *pnwritten) +{ + struct Curl_cfilter *cf = writer_ctx; + *pnwritten = 0; + if(cf) { + struct Curl_easy *data = CF_DATA_CURRENT(cf); + CURLcode result; + result = Curl_conn_cf_send(cf->next, data, buf, buflen, FALSE, pnwritten); + CURL_TRC_CF(data, cf, "[0] nw_out_writer(len=%zu) -> %d, %zu", + buflen, (int)result, *pnwritten); + return result; + } + return CURLE_FAILED_INIT; +} + +static int proxy_h2_client_new(struct Curl_cfilter *cf, + nghttp2_session_callbacks *cbs) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + nghttp2_option *o; + nghttp2_mem mem = { NULL, Curl_nghttp2_malloc, Curl_nghttp2_free, + Curl_nghttp2_calloc, Curl_nghttp2_realloc }; + + int rc = nghttp2_option_new(&o); + if(rc) + return rc; + /* We handle window updates ourself to enforce buffer limits */ + nghttp2_option_set_no_auto_window_update(o, 1); +#if NGHTTP2_VERSION_NUM >= 0x013200 /* with 1.50.0 */ + /* turn off RFC 9113 leading and trailing white spaces validation against + HTTP field value. */ + nghttp2_option_set_no_rfc9113_leading_and_trailing_ws_validation(o, 1); +#endif + rc = nghttp2_session_client_new3(&ctx->h2, cbs, cf, o, &mem); + nghttp2_option_del(o); + return rc; +} + +static int proxy_h2_should_close_session(struct cf_h2_proxy_ctx *ctx) +{ + return !nghttp2_session_want_read(ctx->h2) && + !nghttp2_session_want_write(ctx->h2); +} + +static CURLcode proxy_h2_nw_out_flush(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + size_t nwritten; + CURLcode result; + + if(Curl_bufq_is_empty(&ctx->outbufq)) + return CURLE_OK; + + result = Curl_bufq_pass(&ctx->outbufq, proxy_h2_nw_out_writer, cf, + &nwritten); + if(result) { + if(result == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "[0] flush nw send buffer(%zu) -> EAGAIN", + Curl_bufq_len(&ctx->outbufq)); + ctx->nw_out_blocked = 1; + } + return result; + } + CURL_TRC_CF(data, cf, "[0] nw send buffer flushed"); + return Curl_bufq_is_empty(&ctx->outbufq) ? CURLE_OK : CURLE_AGAIN; +} + +/* + * Processes pending input left in network input buffer. + * This function returns 0 if it succeeds, or -1 and error code will + * be assigned to *err. + */ +static CURLcode proxy_h2_process_pending_input(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + const unsigned char *buf; + size_t blen, nread; + ssize_t rv; + + while(Curl_bufq_peek(&ctx->inbufq, &buf, &blen)) { + + rv = nghttp2_session_mem_recv(ctx->h2, (const uint8_t *)buf, blen); + CURL_TRC_CF(data, cf, "[0] %zu bytes to nghttp2 -> %zd", blen, rv); + if(!curlx_sztouz(rv, &nread)) { + failf(data, + "process_pending_input: nghttp2_session_mem_recv() returned " + "%zd:%s", rv, nghttp2_strerror((int)rv)); + return CURLE_RECV_ERROR; + } + else if(!nread) { + /* nghttp2 does not want to process more, but has no error. This + * probably cannot happen, but be safe. */ + break; + } + Curl_bufq_skip(&ctx->inbufq, nread); + if(Curl_bufq_is_empty(&ctx->inbufq)) { + CURL_TRC_CF(data, cf, "[0] all data in connection buffer processed"); + break; + } + else { + CURL_TRC_CF(data, cf, "[0] process_pending_input: %zu bytes left " + "in connection buffer", Curl_bufq_len(&ctx->inbufq)); + } + } + return CURLE_OK; +} + +static CURLcode proxy_h2_progress_ingress(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + size_t nread; + + /* Process network input buffer first */ + if(!Curl_bufq_is_empty(&ctx->inbufq)) { + CURL_TRC_CF(data, cf, "[0] process %zu bytes in connection buffer", + Curl_bufq_len(&ctx->inbufq)); + result = proxy_h2_process_pending_input(cf, data); + if(result) + return result; + } + + /* Receive data from the "lower" filters, e.g. network until + * it is time to stop or we have enough data for this stream */ + while(!ctx->conn_closed && /* not closed the connection */ + !ctx->tunnel.closed && /* nor the tunnel */ + Curl_bufq_is_empty(&ctx->inbufq) && /* and we consumed our input */ + !Curl_bufq_is_full(&ctx->tunnel.recvbuf)) { + + result = Curl_cf_recv_bufq(cf->next, data, &ctx->inbufq, 0, &nread); + CURL_TRC_CF(data, cf, "[0] read %zu bytes nw data -> %d, %zu", + Curl_bufq_len(&ctx->inbufq), (int)result, nread); + if(result) { + if(result != CURLE_AGAIN) { + failf(data, "Failed receiving HTTP2 proxy data"); + return result; + } + break; + } + else if(nread == 0) { + CURL_TRC_CF(data, cf, "server closed connection"); + ctx->conn_closed = TRUE; + break; + } + + result = proxy_h2_process_pending_input(cf, data); + if(result) + return result; + } + + return CURLE_OK; +} + +static CURLcode proxy_h2_progress_egress(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + int rv = 0; + + ctx->nw_out_blocked = 0; + while(!rv && !ctx->nw_out_blocked && nghttp2_session_want_write(ctx->h2)) + rv = nghttp2_session_send(ctx->h2); + + if(nghttp2_is_fatal(rv)) { + CURL_TRC_CF(data, cf, "[0] nghttp2_session_send error (%s)%d", + nghttp2_strerror(rv), rv); + return CURLE_SEND_ERROR; + } + return proxy_h2_nw_out_flush(cf, data); +} + +static ssize_t on_session_send(nghttp2_session *h2, + const uint8_t *buf, size_t blen, int flags, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + size_t nwritten; + CURLcode result = CURLE_OK; + + (void)h2; + (void)flags; + DEBUGASSERT(data); + + result = Curl_bufq_write_pass(&ctx->outbufq, buf, blen, + proxy_h2_nw_out_writer, cf, &nwritten); + if(result) { + if(result == CURLE_AGAIN) { + ctx->nw_out_blocked = 1; + return NGHTTP2_ERR_WOULDBLOCK; + } + failf(data, "Failed sending HTTP2 data"); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + + if(!nwritten) + return NGHTTP2_ERR_WOULDBLOCK; + + return (nwritten > SSIZE_MAX) ? + NGHTTP2_ERR_CALLBACK_FAILURE : (ssize_t)nwritten; +} + +#ifdef CURLVERBOSE +static int proxy_h2_on_frame_send(nghttp2_session *session, + const nghttp2_frame *frame, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + + (void)session; + DEBUGASSERT(data); + if(Curl_trc_cf_is_verbose(cf, data)) { + char buffer[256]; + int len; + len = Curl_nghttp2_fr_print(frame, buffer, sizeof(buffer) - 1); + buffer[len] = 0; + CURL_TRC_CF(data, cf, "[%d] -> %s", frame->hd.stream_id, buffer); + } + return 0; +} +#endif /* CURLVERBOSE */ + +static int proxy_h2_on_frame_recv(nghttp2_session *session, + const nghttp2_frame *frame, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + int32_t stream_id = frame->hd.stream_id; + + (void)session; + DEBUGASSERT(data); +#ifdef CURLVERBOSE + if(Curl_trc_cf_is_verbose(cf, data)) { + char buffer[256]; + int len; + len = Curl_nghttp2_fr_print(frame, buffer, sizeof(buffer) - 1); + buffer[len] = 0; + CURL_TRC_CF(data, cf, "[%d] <- %s", frame->hd.stream_id, buffer); + } +#endif /* CURLVERBOSE */ + + if(!stream_id) { + /* stream ID zero is for connection-oriented stuff */ + DEBUGASSERT(data); + switch(frame->hd.type) { + case NGHTTP2_SETTINGS: + /* Since the initial stream window is 64K, a request might be on HOLD, + * due to exhaustion. The (initial) SETTINGS may announce a much larger + * window and *assume* that we treat this like a WINDOW_UPDATE. Some + * servers send an explicit WINDOW_UPDATE, but not all seem to do that. + * To be safe, we UNHOLD a stream in order not to stall. */ + if(CURL_REQ_WANT_SEND(data)) { + drain_tunnel(cf, data, &ctx->tunnel); + } + break; + case NGHTTP2_GOAWAY: + ctx->rcvd_goaway = TRUE; + ctx->remote_max_sid = frame->goaway.last_stream_id; + if(data) { + infof(data, "received GOAWAY, error=%u, last_stream=%d", + frame->goaway.error_code, ctx->remote_max_sid); + } + break; + default: + break; + } + return 0; + } + + if(stream_id != ctx->tunnel.stream_id) { + CURL_TRC_CF(data, cf, "[%d] rcvd FRAME not for tunnel", stream_id); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + + switch(frame->hd.type) { + case NGHTTP2_HEADERS: + /* nghttp2 guarantees that :status is received, and we store it to + stream->status_code. Fuzzing has proven this can still be reached + without status code having been set. */ + if(!ctx->tunnel.resp) + return NGHTTP2_ERR_CALLBACK_FAILURE; + /* Only final status code signals the end of header */ + CURL_TRC_CF(data, cf, "[%d] got http status: %d", + stream_id, ctx->tunnel.resp->status); + if(!ctx->tunnel.has_final_response) { + if(ctx->tunnel.resp->status / 100 != 1) { + ctx->tunnel.has_final_response = TRUE; + } + } + break; + case NGHTTP2_WINDOW_UPDATE: + if(CURL_REQ_WANT_SEND(data)) { + drain_tunnel(cf, data, &ctx->tunnel); + } + break; + case NGHTTP2_RST_STREAM: + if(frame->rst_stream.error_code) + ctx->tunnel.reset = TRUE; + break; + default: + break; + } + return 0; +} + +static int proxy_h2_on_header(nghttp2_session *session, + const nghttp2_frame *frame, + const uint8_t *name, size_t namelen, + const uint8_t *value, size_t valuelen, + uint8_t flags, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + int32_t stream_id = frame->hd.stream_id; + CURLcode result; + + (void)flags; + (void)session; + DEBUGASSERT(stream_id); /* should never be a zero stream ID here */ + if(stream_id != ctx->tunnel.stream_id) { + CURL_TRC_CF(data, cf, "[%d] header for non-tunnel stream: " + "%.*s: %.*s", stream_id, + (int)namelen, name, (int)valuelen, value); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + + if(frame->hd.type == NGHTTP2_PUSH_PROMISE) + return NGHTTP2_ERR_CALLBACK_FAILURE; + + if(ctx->tunnel.has_final_response) { + /* we do not do anything with trailers for tunnel streams */ + return 0; + } + + if(namelen == CURL_CSTRLEN(HTTP_PSEUDO_STATUS) && + !memcmp(HTTP_PSEUDO_STATUS, name, namelen)) { + int http_status; + struct http_resp *resp; + + /* status: always comes first, we might get more than one response, + * discard previous, interim responses */ + result = Curl_http_decode_status(&http_status, + (const char *)value, valuelen); + if(result) + return NGHTTP2_ERR_CALLBACK_FAILURE; + result = Curl_http_resp_make(&resp, http_status, NULL); + if(result) + return NGHTTP2_ERR_CALLBACK_FAILURE; + if(ctx->tunnel.resp) + Curl_http_resp_free(ctx->tunnel.resp); + ctx->tunnel.resp = resp; + CURL_TRC_CF(data, cf, "[%d] status: HTTP/2 %03d", + stream_id, ctx->tunnel.resp->status); + return 0; + } + + if(!ctx->tunnel.resp) + return NGHTTP2_ERR_CALLBACK_FAILURE; + + result = Curl_dynhds_add(&ctx->tunnel.resp->headers, + (const char *)name, namelen, + (const char *)value, valuelen); + if(result) + return NGHTTP2_ERR_CALLBACK_FAILURE; + + CURL_TRC_CF(data, cf, "[%d] header: %.*s: %.*s", + stream_id, (int)namelen, name, (int)valuelen, value); + + return 0; /* 0 is successful */ +} + +static ssize_t tunnel_send_callback(nghttp2_session *session, + int32_t stream_id, + uint8_t *buf, size_t length, + uint32_t *data_flags, + nghttp2_data_source *source, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + struct tunnel_stream *ts; + CURLcode result; + size_t nread; + + (void)source; + (void)ctx; + + if(!stream_id) + return NGHTTP2_ERR_INVALID_ARGUMENT; + + ts = nghttp2_session_get_stream_user_data(session, stream_id); + if(!ts) + return NGHTTP2_ERR_CALLBACK_FAILURE; + DEBUGASSERT(ts == &ctx->tunnel); + + result = Curl_bufq_read(&ts->sendbuf, buf, length, &nread); + if(result) { + if(result != CURLE_AGAIN) + return NGHTTP2_ERR_CALLBACK_FAILURE; + return NGHTTP2_ERR_DEFERRED; + } + if(ts->closed && Curl_bufq_is_empty(&ts->sendbuf)) + *data_flags = NGHTTP2_DATA_FLAG_EOF; + + CURL_TRC_CF(data, cf, "[%d] tunnel_send_callback -> %zu", + ts->stream_id, nread); + return (nread > SSIZE_MAX) ? + NGHTTP2_ERR_CALLBACK_FAILURE : (ssize_t)nread; +} + +static int tunnel_recv_callback(nghttp2_session *session, uint8_t flags, + int32_t stream_id, + const uint8_t *mem, size_t len, void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_proxy_ctx *ctx = cf->ctx; + size_t nwritten; + CURLcode result; + + (void)flags; + (void)session; + DEBUGASSERT(stream_id); /* should never be a zero stream ID here */ + + if(stream_id != ctx->tunnel.stream_id) + return NGHTTP2_ERR_CALLBACK_FAILURE; + + result = Curl_bufq_write(&ctx->tunnel.recvbuf, mem, len, &nwritten); + if(result) { + if(result != CURLE_AGAIN) + return NGHTTP2_ERR_CALLBACK_FAILURE; +#ifdef DEBUGBUILD + nwritten = 0; +#endif + } + /* tunnel.recbuf has soft limit, any success MUST add all data */ + DEBUGASSERT(nwritten == len); + return 0; +} + +static int proxy_h2_on_stream_close(nghttp2_session *session, + int32_t stream_id, + uint32_t error_code, void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + + (void)session; + + if(stream_id != ctx->tunnel.stream_id) + return 0; + + CURL_TRC_CF(data, cf, "[%d] proxy_h2_on_stream_close, %s (err %u)", + stream_id, nghttp2_http2_strerror(error_code), error_code); + ctx->tunnel.closed = TRUE; + ctx->tunnel.error = error_code; + if(error_code) + ctx->tunnel.reset = TRUE; + + return 0; +} + +static CURLcode proxy_h2_submit( + int32_t *pstream_id, + struct Curl_cfilter *cf, + struct Curl_easy *data, + nghttp2_session *h2, + struct httpreq *req, + const nghttp2_priority_spec *pri_spec, + void *stream_user_data, + nghttp2_data_source_read_callback read_callback, + void *read_ctx) +{ + struct dynhds h2_headers; + nghttp2_nv *nva = NULL; + int32_t stream_id = -1; + size_t nheader; + CURLcode result; + + (void)cf; + Curl_dynhds_init(&h2_headers, 0, DYN_HTTP_REQUEST); + result = Curl_http_req_to_h2(&h2_headers, req, data); + if(result) + goto out; + + nva = Curl_dynhds_to_nva(&h2_headers, &nheader); + if(!nva) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + if(read_callback) { + nghttp2_data_provider data_prd; + + data_prd.read_callback = read_callback; + data_prd.source.ptr = read_ctx; + stream_id = nghttp2_submit_request(h2, pri_spec, nva, nheader, + &data_prd, stream_user_data); + } + else { + stream_id = nghttp2_submit_request(h2, pri_spec, nva, nheader, + NULL, stream_user_data); + } + + if(stream_id < 0) { + failf(data, "nghttp2_session_upgrade2() failed: %s(%d)", + nghttp2_strerror(stream_id), stream_id); + result = CURLE_SEND_ERROR; + goto out; + } + result = CURLE_OK; + +out: + curlx_free(nva); + Curl_dynhds_free(&h2_headers); + *pstream_id = stream_id; + return result; +} + +static CURLcode submit_CONNECT(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct tunnel_stream *ts) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + CURLcode result; + struct httpreq *req = NULL; + + result = Curl_http_proxy_create_tunnel_request(&req, cf, data, ctx->dest, + PROXY_HTTP_V2, + (bool)ctx->udp_tunnel); + if(result) + goto out; + result = Curl_creader_set_null(data); + if(result) + goto out; + + result = proxy_h2_submit(&ts->stream_id, cf, data, ctx->h2, req, + NULL, ts, tunnel_send_callback, cf); + if(result) { + CURL_TRC_CF(data, cf, "[%d] send, nghttp2_submit_request error: %s", + ts->stream_id, nghttp2_strerror(ts->stream_id)); + } + +out: + if(req) + Curl_http_req_free(req); + if(result) + failf(data, "Failed sending CONNECT to proxy"); + return result; +} + +static CURLcode inspect_response(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct tunnel_stream *ts) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + proxy_inspect_result res; + CURLcode result; + + result = Curl_http_proxy_inspect_tunnel_response( + cf, data, ts->resp, (bool)ctx->udp_tunnel, &res); + if(result) + return result; + switch(res) { + case PROXY_INSPECT_OK: + h2_tunnel_go_state(cf, ts, H2_TUNNEL_ESTABLISHED, data, + (bool)ctx->udp_tunnel); + break; + case PROXY_INSPECT_FAILED: + h2_tunnel_go_state(cf, ts, H2_TUNNEL_FAILED, data, + (bool)ctx->udp_tunnel); + result = CURLE_COULDNT_CONNECT; + break; + case PROXY_INSPECT_AUTH_RETRY: + h2_tunnel_go_state(cf, ts, H2_TUNNEL_INIT, data, + (bool)ctx->udp_tunnel); + break; + } + return result; +} + +static CURLcode H2_CONNECT(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct tunnel_stream *ts) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + DEBUGASSERT(ts); + DEBUGASSERT(ts->authority); + if(ctx->conn_closed) { + failf(data, "proxy closed connection"); + return CURLE_COULDNT_CONNECT; + } + + do { + switch(ts->state) { + case H2_TUNNEL_INIT: + /* Prepare the CONNECT request and make a first attempt to send. */ + CURL_TRC_CF(data, cf, "[0] CONNECT start for %s", ts->authority); + result = submit_CONNECT(cf, data, ts); + if(result) + goto out; + h2_tunnel_go_state(cf, ts, H2_TUNNEL_CONNECT, data, + (bool)ctx->udp_tunnel); + FALLTHROUGH(); + + case H2_TUNNEL_CONNECT: + /* see that the request is completely sent */ + result = proxy_h2_progress_ingress(cf, data); + if(!result) + result = proxy_h2_progress_egress(cf, data); + if(result && result != CURLE_AGAIN) { + h2_tunnel_go_state(cf, ts, H2_TUNNEL_FAILED, data, + (bool)ctx->udp_tunnel); + break; + } + + if(ts->has_final_response) { + h2_tunnel_go_state(cf, ts, H2_TUNNEL_RESPONSE, data, + (bool)ctx->udp_tunnel); + } + else { + result = CURLE_OK; + goto out; + } + FALLTHROUGH(); + + case H2_TUNNEL_RESPONSE: + DEBUGASSERT(ts->has_final_response); + result = inspect_response(cf, data, ts); + if(result) + goto out; + break; + + case H2_TUNNEL_ESTABLISHED: + return CURLE_OK; + + case H2_TUNNEL_FAILED: + return CURLE_RECV_ERROR; + + default: + break; + } + + } while(ts->state == H2_TUNNEL_INIT); + +out: + if((result && (result != CURLE_AGAIN)) || ctx->tunnel.closed) + h2_tunnel_go_state(cf, ts, H2_TUNNEL_FAILED, data, + (bool)ctx->udp_tunnel); + return result; +} + +/* + * Initialize the cfilter context + */ +static CURLcode cf_h2_proxy_ctx_init(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OUT_OF_MEMORY; + nghttp2_session_callbacks *cbs = NULL; + int rc; + + DEBUGASSERT(!ctx->h2); + memset(&ctx->tunnel, 0, sizeof(ctx->tunnel)); + + Curl_bufq_init(&ctx->inbufq, PROXY_H2_CHUNK_SIZE, PROXY_H2_NW_RECV_CHUNKS); + Curl_bufq_init(&ctx->outbufq, PROXY_H2_CHUNK_SIZE, PROXY_H2_NW_SEND_CHUNKS); + ctx->remote_max_sid = INT32_MAX; + + if(tunnel_stream_init(&ctx->tunnel, ctx->dest)) + goto out; + + rc = nghttp2_session_callbacks_new(&cbs); + if(rc) { + failf(data, "Could not initialize nghttp2 callbacks"); + goto out; + } + + nghttp2_session_callbacks_set_send_callback(cbs, on_session_send); + nghttp2_session_callbacks_set_on_frame_recv_callback( + cbs, proxy_h2_on_frame_recv); +#ifdef CURLVERBOSE + nghttp2_session_callbacks_set_on_frame_send_callback(cbs, + proxy_h2_on_frame_send); +#endif + nghttp2_session_callbacks_set_on_data_chunk_recv_callback( + cbs, tunnel_recv_callback); + nghttp2_session_callbacks_set_on_stream_close_callback( + cbs, proxy_h2_on_stream_close); + nghttp2_session_callbacks_set_on_header_callback(cbs, proxy_h2_on_header); + + /* The nghttp2 session is not yet setup, do it */ + rc = proxy_h2_client_new(cf, cbs); + if(rc) { + failf(data, "Could not initialize nghttp2"); + goto out; + } + + { + nghttp2_settings_entry iv[3]; + + iv[0].settings_id = NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; + iv[0].value = Curl_multi_max_concurrent_streams(data->multi); + iv[1].settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; + iv[1].value = H2_TUNNEL_WINDOW_SIZE; + iv[2].settings_id = NGHTTP2_SETTINGS_ENABLE_PUSH; + iv[2].value = 0; + rc = nghttp2_submit_settings(ctx->h2, NGHTTP2_FLAG_NONE, iv, 3); + if(rc) { + failf(data, "nghttp2_submit_settings() failed: %s(%d)", + nghttp2_strerror(rc), rc); + result = CURLE_HTTP2; + goto out; + } + } + + rc = nghttp2_session_set_local_window_size(ctx->h2, NGHTTP2_FLAG_NONE, 0, + PROXY_HTTP2_HUGE_WINDOW_SIZE); + if(rc) { + failf(data, "nghttp2_session_set_local_window_size() failed: %s(%d)", + nghttp2_strerror(rc), rc); + result = CURLE_HTTP2; + goto out; + } + + /* all set, traffic will be send on connect */ + result = CURLE_OK; + +out: + if(cbs) + nghttp2_session_callbacks_del(cbs); + CURL_TRC_CF(data, cf, "[0] init proxy ctx -> %d", (int)result); + return result; +} + +static CURLcode cf_h2_proxy_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + struct cf_call_data save; + struct tunnel_stream *ts = &ctx->tunnel; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* Connect the lower filters first */ + if(!cf->next->connected) { + result = Curl_conn_cf_connect(cf->next, data, done); + if(result || !*done) + return result; + } + + *done = FALSE; + + CF_DATA_SAVE(save, cf, data); + if(!ctx->h2) { + result = cf_h2_proxy_ctx_init(cf, data); + if(result) + goto out; + } + DEBUGASSERT(ts->authority); + + if(Curl_timeleft_ms(data) < 0) { + failf(data, "Proxy CONNECT aborted due to timeout"); + result = CURLE_OPERATION_TIMEDOUT; + goto out; + } + + /* for the secondary socket (FTP), use the "connect to host" + * but ignore the "connect to port" (use the secondary port) + */ + result = H2_CONNECT(cf, data, ts); + +out: + *done = (result == CURLE_OK) && (ts->state == H2_TUNNEL_ESTABLISHED); + if(*done) { + cf->connected = TRUE; + /* The real request will follow the CONNECT, reset request partially */ + Curl_req_soft_reset(&data->req, data); + Curl_client_reset(data); + } + CF_DATA_RESTORE(cf, save); + return result; +} + +static void cf_h2_proxy_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + + (void)data; + if(ctx) { + cf_h2_proxy_ctx_free(ctx); + cf->ctx = NULL; + } +} + +static CURLcode cf_h2_proxy_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct cf_call_data save; + CURLcode result; + int rv; + + if(!cf->connected || !ctx->h2 || cf->shutdown || ctx->conn_closed) { + *done = TRUE; + return CURLE_OK; + } + + CF_DATA_SAVE(save, cf, data); + + if(!ctx->sent_goaway) { + rv = nghttp2_submit_goaway(ctx->h2, NGHTTP2_FLAG_NONE, + 0, 0, + (const uint8_t *)"shutdown", + sizeof("shutdown")); + if(rv) { + failf(data, "nghttp2_submit_goaway() failed: %s(%d)", + nghttp2_strerror(rv), rv); + result = CURLE_SEND_ERROR; + goto out; + } + ctx->sent_goaway = TRUE; + } + /* GOAWAY submitted, process egress and ingress until nghttp2 is done. */ + result = CURLE_OK; + if(nghttp2_session_want_write(ctx->h2)) + result = proxy_h2_progress_egress(cf, data); + if(!result && nghttp2_session_want_read(ctx->h2)) + result = proxy_h2_progress_ingress(cf, data); + + *done = (ctx->conn_closed || + (!result && !nghttp2_session_want_write(ctx->h2) && + !nghttp2_session_want_read(ctx->h2))); +out: + CF_DATA_RESTORE(cf, save); + cf->shutdown = (result || *done); + return result; +} + +static bool cf_h2_proxy_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + if((ctx && !Curl_bufq_is_empty(&ctx->inbufq)) || + (ctx && ctx->tunnel.state == H2_TUNNEL_ESTABLISHED && + !Curl_bufq_is_empty(&ctx->tunnel.recvbuf))) + return TRUE; + return cf->next ? cf->next->cft->has_data_pending(cf->next, data) : FALSE; +} + +static CURLcode cf_h2_proxy_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct cf_call_data save; + curl_socket_t sock = Curl_conn_cf_get_socket(cf, data); + bool want_recv, want_send; + CURLcode result = CURLE_OK; + + if(!cf->connected && ctx->h2) { + want_send = nghttp2_session_want_write(ctx->h2) || + !Curl_bufq_is_empty(&ctx->outbufq) || + !Curl_bufq_is_empty(&ctx->tunnel.sendbuf); + want_recv = nghttp2_session_want_read(ctx->h2); + } + else + Curl_pollset_check(data, ps, sock, &want_recv, &want_send); + + if(ctx->h2 && (want_recv || want_send)) { + bool c_exhaust, s_exhaust; + + CF_DATA_SAVE(save, cf, data); + c_exhaust = !nghttp2_session_get_remote_window_size(ctx->h2); + s_exhaust = ctx->tunnel.stream_id >= 0 && + !nghttp2_session_get_stream_remote_window_size( + ctx->h2, ctx->tunnel.stream_id); + want_recv = (want_recv || c_exhaust || s_exhaust); + want_send = (!s_exhaust && want_send) || + (!c_exhaust && nghttp2_session_want_write(ctx->h2)) || + !Curl_bufq_is_empty(&ctx->outbufq) || + !Curl_bufq_is_empty(&ctx->tunnel.sendbuf); + + result = Curl_pollset_set(data, ps, sock, want_recv, want_send); + CURL_TRC_CF(data, cf, "adjust_pollset, want_recv=%d want_send=%d -> %d", + want_recv, want_send, (int)result); + CF_DATA_RESTORE(cf, save); + } + else if(ctx->sent_goaway && !cf->shutdown) { + /* shutdown in progress */ + CF_DATA_SAVE(save, cf, data); + want_send = nghttp2_session_want_write(ctx->h2) || + !Curl_bufq_is_empty(&ctx->outbufq) || + !Curl_bufq_is_empty(&ctx->tunnel.sendbuf); + want_recv = nghttp2_session_want_read(ctx->h2); + result = Curl_pollset_set(data, ps, sock, want_recv, want_send); + CURL_TRC_CF(data, cf, "adjust_pollset, want_recv=%d want_send=%d -> %d", + want_recv, want_send, (int)result); + CF_DATA_RESTORE(cf, save); + } + return result; +} + +static CURLcode h2_handle_tunnel_close(struct Curl_cfilter *cf, + struct Curl_easy *data, + size_t *pnread) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + + *pnread = 0; + if(ctx->tunnel.error) { + failf(data, "HTTP/2 stream %d reset by %s (error 0x%x %s)", + ctx->tunnel.stream_id, ctx->tunnel.reset ? "server" : "curl", + ctx->tunnel.error, nghttp2_http2_strerror(ctx->tunnel.error)); + return CURLE_RECV_ERROR; + } + + CURL_TRC_CF(data, cf, "[%d] handle_tunnel_close -> 0", + ctx->tunnel.stream_id); + return CURLE_OK; +} + +static CURLcode tunnel_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, size_t *pnread) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + CURLcode result = CURLE_AGAIN; + + *pnread = 0; + if(!Curl_bufq_is_empty(&ctx->tunnel.recvbuf)) + result = Curl_bufq_cread(&ctx->tunnel.recvbuf, buf, len, pnread); + else { + if(ctx->tunnel.closed) { + result = h2_handle_tunnel_close(cf, data, pnread); + } + else if(ctx->tunnel.reset || + (ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) || + (ctx->rcvd_goaway && + ctx->remote_max_sid < ctx->tunnel.stream_id)) { + result = CURLE_RECV_ERROR; + } + else + result = CURLE_AGAIN; + } + + CURL_TRC_CF(data, cf, "[%d] tunnel_recv(len=%zu) -> %d, %zu", + ctx->tunnel.stream_id, len, (int)result, *pnread); + return result; +} + +static CURLcode cf_h2_proxy_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, size_t len, + size_t *pnread) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct cf_call_data save; + CURLcode result; + + *pnread = 0; + CF_DATA_SAVE(save, cf, data); + + if(ctx->tunnel.state != H2_TUNNEL_ESTABLISHED) { + result = CURLE_RECV_ERROR; + goto out; + } + + if(Curl_bufq_is_empty(&ctx->tunnel.recvbuf)) { + result = proxy_h2_progress_ingress(cf, data); + if(result) + goto out; + } + + result = tunnel_recv(cf, data, buf, len, pnread); + + if(!result) { + CURL_TRC_CF(data, cf, "[%d] increase window by %zu", + ctx->tunnel.stream_id, *pnread); + nghttp2_session_consume(ctx->h2, ctx->tunnel.stream_id, *pnread); + } + + result = Curl_1st_fatal(result, proxy_h2_progress_egress(cf, data)); + +out: + if((!Curl_bufq_is_empty(&ctx->tunnel.recvbuf) || + !Curl_bufq_is_empty(&ctx->tunnel.sendbuf)) && + (!result || (result == CURLE_AGAIN))) { + /* data pending and no fatal error to report. Need to trigger + * draining to avoid stalling when no socket events happen. */ + drain_tunnel(cf, data, &ctx->tunnel); + } + CURL_TRC_CF(data, cf, "[%d] cf_recv(len=%zu) -> %d, %zu", + ctx->tunnel.stream_id, len, (int)result, *pnread); + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode cf_h2_proxy_send(struct Curl_cfilter *cf, + struct Curl_easy *data, + const uint8_t *buf, size_t len, bool eos, + size_t *pnwritten) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct cf_call_data save; + int rv; + CURLcode result; + + (void)eos; + *pnwritten = 0; + CF_DATA_SAVE(save, cf, data); + + if(ctx->tunnel.state != H2_TUNNEL_ESTABLISHED) { + result = CURLE_SEND_ERROR; + goto out; + } + + if(ctx->tunnel.closed) { + result = CURLE_SEND_ERROR; + goto out; + } + + result = Curl_bufq_write(&ctx->tunnel.sendbuf, buf, len, pnwritten); + CURL_TRC_CF(data, cf, "cf_send(), bufq_write %d, %zu", (int)result, + *pnwritten); + if(result && (result != CURLE_AGAIN)) + goto out; + + if(!Curl_bufq_is_empty(&ctx->tunnel.sendbuf)) { + /* req body data is buffered, resume the potentially suspended stream */ + rv = nghttp2_session_resume_data(ctx->h2, ctx->tunnel.stream_id); + if(nghttp2_is_fatal(rv)) { + result = CURLE_SEND_ERROR; + goto out; + } + } + + result = Curl_1st_fatal(result, proxy_h2_progress_ingress(cf, data)); + result = Curl_1st_fatal(result, proxy_h2_progress_egress(cf, data)); + + if(!result && proxy_h2_should_close_session(ctx)) { + /* nghttp2 thinks this session is done. If the stream has not been + * closed, this is an error state for out transfer */ + if(ctx->tunnel.closed) { + result = CURLE_SEND_ERROR; + } + else { + CURL_TRC_CF(data, cf, "[0] send: nothing to do in this session"); + result = CURLE_HTTP2; + } + } + +out: + if((!Curl_bufq_is_empty(&ctx->tunnel.recvbuf) || + !Curl_bufq_is_empty(&ctx->tunnel.sendbuf)) && + (!result || (result == CURLE_AGAIN))) { + /* data pending and no fatal error to report. Need to trigger + * draining to avoid stalling when no socket events happen. */ + drain_tunnel(cf, data, &ctx->tunnel); + } + CURL_TRC_CF(data, cf, "[%d] cf_send(len=%zu) -> %d, %zu, " + "h2 windows %d-%d (stream-conn), buffers %zu-%zu (stream-conn)", + ctx->tunnel.stream_id, len, (int)result, *pnwritten, + nghttp2_session_get_stream_remote_window_size( + ctx->h2, ctx->tunnel.stream_id), + nghttp2_session_get_remote_window_size(ctx->h2), + Curl_bufq_len(&ctx->tunnel.sendbuf), + Curl_bufq_len(&ctx->outbufq)); + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode cf_h2_proxy_flush(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + struct cf_call_data save; + CURLcode result = CURLE_OK; + + CF_DATA_SAVE(save, cf, data); + if(!Curl_bufq_is_empty(&ctx->tunnel.sendbuf)) { + /* resume the potentially suspended tunnel */ + int rv = nghttp2_session_resume_data(ctx->h2, ctx->tunnel.stream_id); + if(nghttp2_is_fatal(rv)) { + result = CURLE_SEND_ERROR; + goto out; + } + } + + result = proxy_h2_progress_egress(cf, data); + +out: + CURL_TRC_CF(data, cf, "[%d] flush -> %d, " + "h2 windows %d-%d (stream-conn), buffers %zu-%zu (stream-conn)", + ctx->tunnel.stream_id, (int)result, + nghttp2_session_get_stream_remote_window_size( + ctx->h2, ctx->tunnel.stream_id), + nghttp2_session_get_remote_window_size(ctx->h2), + Curl_bufq_len(&ctx->tunnel.sendbuf), + Curl_bufq_len(&ctx->outbufq)); + CF_DATA_RESTORE(cf, save); + return result; +} + +static bool proxy_h2_connisalive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + bool alive = TRUE; + + *input_pending = FALSE; + if(!cf->next || !cf->next->cft->is_alive(cf->next, data, input_pending)) + return FALSE; + + if(*input_pending) { + /* This happens before we have sent off a request and the connection is + not in use by any other transfer, there should not be any data here, + only "protocol frames" */ + CURLcode result; + size_t nread; + + *input_pending = FALSE; + result = Curl_cf_recv_bufq(cf->next, data, &ctx->inbufq, 0, &nread); + if(!result) { + if(proxy_h2_process_pending_input(cf, data)) + /* immediate error, considered dead */ + alive = FALSE; + else { + alive = !proxy_h2_should_close_session(ctx); + } + } + else if(result != CURLE_AGAIN) { + /* the read failed so let's say this is dead anyway */ + alive = FALSE; + } + } + + return alive; +} + +static bool cf_h2_proxy_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + bool alive; + struct cf_call_data save; + + *input_pending = FALSE; + CF_DATA_SAVE(save, cf, data); + alive = (ctx && ctx->h2 && proxy_h2_connisalive(cf, data, input_pending)); + CURL_TRC_CF(data, cf, "[0] conn alive -> %d, input_pending=%d", + alive, *input_pending); + CF_DATA_RESTORE(cf, save); + return alive; +} + +static CURLcode cf_h2_proxy_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_h2_proxy_ctx *ctx = cf->ctx; + + switch(query) { + case CF_QUERY_HOST_PORT: + *pres1 = (int)ctx->dest->port; + *((const char **)pres2) = ctx->dest->hostname; + return CURLE_OK; + case CF_QUERY_NEED_FLUSH: { + if(!Curl_bufq_is_empty(&ctx->outbufq) || + !Curl_bufq_is_empty(&ctx->tunnel.sendbuf)) { + CURL_TRC_CF(data, cf, "needs flush"); + *pres1 = TRUE; + return CURLE_OK; + } + break; + } + case CF_QUERY_ALPN_NEGOTIATED: { + const char **palpn = pres2; + DEBUGASSERT(palpn); + *palpn = NULL; + return CURLE_OK; + } + default: + break; + } + return cf->next ? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +static CURLcode cf_h2_proxy_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + CURLcode result = CURLE_OK; + struct cf_call_data save; + + (void)arg1; + (void)arg2; + + switch(event) { + case CF_CTRL_FLUSH: + CF_DATA_SAVE(save, cf, data); + result = cf_h2_proxy_flush(cf, data); + CF_DATA_RESTORE(cf, save); + break; + default: + break; + } + return result; +} + +struct Curl_cftype Curl_cft_h2_proxy = { + "H2-PROXY", + CF_TYPE_IP_CONNECT | CF_TYPE_PROXY, + CURL_LOG_LVL_NONE, + cf_h2_proxy_destroy, + cf_h2_proxy_connect, + cf_h2_proxy_shutdown, + cf_h2_proxy_adjust_pollset, + cf_h2_proxy_data_pending, + cf_h2_proxy_send, + cf_h2_proxy_recv, + cf_h2_proxy_cntrl, + cf_h2_proxy_is_alive, + Curl_cf_def_conn_keep_alive, + cf_h2_proxy_query, +}; + +CURLcode Curl_cf_h2_proxy_insert_after(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct Curl_peer *dest, + bool udp_tunnel) +{ + struct Curl_cfilter *cf_h2_proxy = NULL; + struct cf_h2_proxy_ctx *ctx; + CURLcode result = CURLE_OUT_OF_MEMORY; + + (void)data; + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) + goto out; + Curl_peer_link(&ctx->dest, dest); + ctx->udp_tunnel = udp_tunnel; + + result = Curl_cf_create(&cf_h2_proxy, &Curl_cft_h2_proxy, ctx); + if(result) + goto out; + ctx = NULL; + Curl_conn_cf_insert_after(cf, cf_h2_proxy); + +out: + cf_h2_proxy_ctx_free(ctx); + return result; +} + +#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_PROXY && USE_NGHTTP2 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-h2-proxy.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-h2-proxy.h new file mode 100644 index 0000000000..07e3c9aedf --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-h2-proxy.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_H2_PROXY_H +#define HEADER_CURL_H2_PROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_NGHTTP2) && !defined(CURL_DISABLE_PROXY) + +CURLcode Curl_cf_h2_proxy_insert_after(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct Curl_peer *dest, + bool udp_tunnel); + +extern struct Curl_cftype Curl_cft_h2_proxy; + +#endif /* USE_NGHTTP2 && !CURL_DISABLE_PROXY */ + +#endif /* HEADER_CURL_H2_PROXY_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-haproxy.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-haproxy.c new file mode 100644 index 0000000000..e3286107a3 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-haproxy.c @@ -0,0 +1,241 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_PROXY + +#include "urldata.h" +#include "cfilters.h" +#include "cf-haproxy.h" +#include "connect.h" +#include "curl_addrinfo.h" +#include "curl_trc.h" +#include "select.h" + + +typedef enum { + HAPROXY_INIT, /* init/default/no tunnel state */ + HAPROXY_SEND, /* data_out being sent */ + HAPROXY_DONE /* all work done */ +} haproxy_state; + +struct cf_haproxy_ctx { + int state; + struct dynbuf data_out; +}; + +static void cf_haproxy_ctx_free(struct cf_haproxy_ctx *ctx) +{ + if(ctx) { + curlx_dyn_free(&ctx->data_out); + curlx_free(ctx); + } +} + +static CURLcode cf_haproxy_date_out_set(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + /* We fake a client connection report to the upstream server + * with the HAProxy protocol, reporting the client's source + * and destination IP addresses and ports. + * addresses: either the ones used to talk to the upstream + * OR the value supplied by the user + * ports: the ports used in the upstream connection */ + const char *client_source_ip; + const char *client_dest_ip; + struct cf_haproxy_ctx *ctx = cf->ctx; + CURLcode result; + struct ip_quadruple ipquad; + bool is_ipv6; + + DEBUGASSERT(ctx); + DEBUGASSERT(ctx->state == HAPROXY_INIT); +#ifdef USE_UNIX_SOCKETS + if(Curl_conn_get_first_peer(cf->conn, cf->sockindex)->unix_socket) + /* the buffer is large enough to hold this! */ + result = curlx_dyn_addn(&ctx->data_out, STRCONST("PROXY UNKNOWN\r\n")); + else { +#endif /* USE_UNIX_SOCKETS */ + result = Curl_conn_cf_get_ip_info(cf->next, data, &is_ipv6, &ipquad); + if(result) + return result; + + client_source_ip = CURL_EASY_STR(data, STRING_HAPROXY_CLIENT_IP); + if(client_source_ip) { + client_dest_ip = client_source_ip; + is_ipv6 = !Curl_is_ipv4addr(client_source_ip); + } + else { + client_source_ip = ipquad.local_ip; + client_dest_ip = ipquad.remote_ip; + } + + result = curlx_dyn_addf(&ctx->data_out, "PROXY %s %s %s %d %d\r\n", + is_ipv6 ? "TCP6" : "TCP4", + client_source_ip, client_dest_ip, + ipquad.local_port, ipquad.remote_port); + +#ifdef USE_UNIX_SOCKETS + } +#endif /* USE_UNIX_SOCKETS */ + return result; +} + +static CURLcode cf_haproxy_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_haproxy_ctx *ctx = cf->ctx; + CURLcode result; + size_t len; + + DEBUGASSERT(ctx); + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + result = cf->next->cft->do_connect(cf->next, data, done); + if(result || !*done) + return result; + + switch(ctx->state) { + case HAPROXY_INIT: + result = cf_haproxy_date_out_set(cf, data); + if(result) + goto out; + ctx->state = HAPROXY_SEND; + FALLTHROUGH(); + case HAPROXY_SEND: + len = curlx_dyn_len(&ctx->data_out); + if(len > 0) { + size_t nwritten; + result = Curl_conn_cf_send(cf->next, data, + curlx_dyn_uptr(&ctx->data_out), len, FALSE, + &nwritten); + if(result) { + if(result != CURLE_AGAIN) + goto out; + result = CURLE_OK; + nwritten = 0; + } + curlx_dyn_tail(&ctx->data_out, len - nwritten); + if(curlx_dyn_len(&ctx->data_out) > 0) { + result = CURLE_OK; + goto out; + } + } + ctx->state = HAPROXY_DONE; + FALLTHROUGH(); + default: + curlx_dyn_free(&ctx->data_out); + break; + } + +out: + *done = (!result) && (ctx->state == HAPROXY_DONE); + cf->connected = *done; + return result; +} + +static void cf_haproxy_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURL_TRC_CF(data, cf, "destroy"); + cf_haproxy_ctx_free(cf->ctx); +} + +static CURLcode cf_haproxy_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + if(cf->next->connected && !cf->connected) { + /* If we are not connected, but the filter "below" is + * and not waiting on something, we are sending. */ + return Curl_pollset_set_out_only( + data, ps, Curl_conn_cf_get_socket(cf, data)); + } + return CURLE_OK; +} + +struct Curl_cftype Curl_cft_haproxy = { + "HAPROXY", + CF_TYPE_PROXY | CF_TYPE_SETUP, + 0, + cf_haproxy_destroy, + cf_haproxy_connect, + Curl_cf_def_shutdown, + cf_haproxy_adjust_pollset, + Curl_cf_def_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + Curl_cf_def_query, +}; + +static CURLcode cf_haproxy_create(struct Curl_cfilter **pcf, + struct Curl_easy *data) +{ + struct Curl_cfilter *cf = NULL; + struct cf_haproxy_ctx *ctx; + CURLcode result; + + (void)data; + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + ctx->state = HAPROXY_INIT; + curlx_dyn_init(&ctx->data_out, DYN_HAXPROXY); + + result = Curl_cf_create(&cf, &Curl_cft_haproxy, ctx); + if(result) + goto out; + ctx = NULL; + +out: + cf_haproxy_ctx_free(ctx); + *pcf = result ? NULL : cf; + return result; +} + +CURLcode Curl_cf_haproxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data) +{ + struct Curl_cfilter *cf; + CURLcode result; + + result = cf_haproxy_create(&cf, data); + if(result) + goto out; + Curl_conn_cf_insert_after(cf_at, cf); + +out: + return result; +} + +#endif /* !CURL_DISABLE_PROXY */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-haproxy.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-haproxy.h new file mode 100644 index 0000000000..6d67597cd7 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-haproxy.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_CF_HAPROXY_H +#define HEADER_CURL_CF_HAPROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" + +#ifndef CURL_DISABLE_PROXY + +CURLcode Curl_cf_haproxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data); + +extern struct Curl_cftype Curl_cft_haproxy; + +#endif /* !CURL_DISABLE_PROXY */ + +#endif /* HEADER_CURL_CF_HAPROXY_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-https-connect.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-https-connect.c new file mode 100644 index 0000000000..2e13a5cc09 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-https-connect.c @@ -0,0 +1,821 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_HTTP + +#include "urldata.h" +#include "curl_trc.h" +#include "cfilters.h" +#include "cf-setup.h" +#include "connect.h" +#include "multiif.h" +#include "cf-https-connect.h" +#include "http2.h" +#include "progress.h" +#include "select.h" +#include "vdns/cf-dns.h" +#include "vdns/hostip.h" +#include "vdns/httpsrr.h" +#include "vquic/vquic.h" + +typedef enum { + CF_HC_RESOLV, + CF_HC_INIT, + CF_HC_CONNECT, + CF_HC_SUCCESS, + CF_HC_FAILURE +} cf_hc_state; + +struct cf_hc_baller { + const char *name; + struct Curl_cfilter *cf; + CURLcode result; + int reply_ms; + uint8_t transport; + enum alpnid alpn_id; + BIT(shutdown); +}; + +static void cf_hc_baller_discard(struct cf_hc_baller *b, + struct Curl_easy *data) +{ + if(b->cf) { + Curl_conn_cf_discard_chain(&b->cf, data); + b->cf = NULL; + } +} + +static bool cf_hc_baller_is_connecting(struct cf_hc_baller *b) +{ + return b->cf && !b->result; +} + +static bool cf_hc_baller_has_started(struct cf_hc_baller *b) +{ + return !!b->cf; +} + +static int cf_hc_baller_reply_ms(struct cf_hc_baller *b, + struct Curl_easy *data) +{ + if(b->cf && (b->reply_ms < 0)) + b->cf->cft->query(b->cf, data, CF_QUERY_CONNECT_REPLY_MS, + &b->reply_ms, NULL); + return b->reply_ms; +} + +static bool cf_hc_baller_data_pending(struct cf_hc_baller *b, + const struct Curl_easy *data) +{ + return b->cf && !b->result && b->cf->cft->has_data_pending(b->cf, data); +} + +static bool cf_hc_baller_needs_flush(struct cf_hc_baller *b, + struct Curl_easy *data) +{ + return b->cf && !b->result && Curl_conn_cf_needs_flush(b->cf, data); +} + +static CURLcode cf_hc_baller_cntrl(struct cf_hc_baller *b, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + if(b->cf && !b->result) + return Curl_conn_cf_cntrl(b->cf, data, FALSE, event, arg1, arg2); + return CURLE_OK; +} + +struct cf_hc_ctx { + cf_hc_state state; + struct Curl_peer *destination; /* who we ultimately want to talk to */ + struct curltime started; /* when connect started */ + CURLcode result; /* overall result */ + CURLcode check_h3_result; + struct cf_hc_baller ballers[2]; + size_t baller_count; + timediff_t soft_eyeballs_timeout_ms; + timediff_t hard_eyeballs_timeout_ms; + uint8_t def_transport; + BIT(httpsrr_resolved); + BIT(checked_h3); + BIT(ballers_complete); +}; + +static void cf_hc_ctx_destroy(struct Curl_easy *data, + struct cf_hc_ctx *ctx) +{ + if(ctx) { + size_t i; + for(i = 0; i < ctx->baller_count; ++i) + cf_hc_baller_discard(&ctx->ballers[i], data); + Curl_peer_unlink(&ctx->destination); + curlx_free(ctx); + } +} + +static void cf_hc_baller_assign(struct cf_hc_baller *b, + enum alpnid alpn_id, + uint8_t def_transport) +{ + b->alpn_id = alpn_id; + b->transport = def_transport; + b->cf = NULL; + b->result = CURLE_OK; + b->reply_ms = -1; + b->shutdown = FALSE; + switch(b->alpn_id) { + case ALPN_h3: + b->name = "h3"; + b->transport = TRNSPRT_QUIC; + break; + case ALPN_h2: + b->name = "h2"; + break; + case ALPN_h1: + b->name = "h1"; + break; + case ALPN_none: + b->name = "no-alpn"; + break; + default: + b->result = CURLE_FAILED_INIT; + break; + } +} + +static void cf_hc_baller_init(struct cf_hc_baller *b, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct Curl_cfilter *save = cf->next; + + cf->next = NULL; + b->result = Curl_cf_setup_insert_after(cf, data, b->transport, + CURL_CF_SSL_ENABLE); + b->cf = cf->next; + cf->next = save; +} + +static CURLcode cf_hc_baller_connect(struct cf_hc_baller *b, + struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct Curl_cfilter *save = cf->next; + + cf->next = b->cf; + b->result = Curl_conn_cf_connect(cf->next, data, done); + b->cf = cf->next; /* it might mutate */ + cf->next = save; + return b->result; +} + +static CURLcode baller_connected(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_hc_baller *winner) +{ + struct cf_hc_ctx *ctx = cf->ctx; + + /* Make the winner's connection filter out own sub-filter, check, move, + * close all remaining. */ + if(cf->next) { + DEBUGASSERT(0); + return CURLE_FAILED_INIT; + } + if(!winner->cf) { + DEBUGASSERT(0); + return CURLE_FAILED_INIT; + } + + cf->next = winner->cf; + winner->cf = NULL; + ctx->state = CF_HC_SUCCESS; + cf->connected = TRUE; + + /* ballers may have failf()'d, the winner resets it, so our + * errorbuf is clean again. */ + Curl_reset_fail(data); + +#ifdef USE_NGHTTP2 + { + /* For a negotiated HTTP/2 connection insert the h2 filter. */ + const char *alpn = Curl_conn_cf_get_alpn_negotiated(cf->next, data); + if(alpn && !strcmp("h2", alpn)) { + CURLcode result = Curl_http2_switch_at(cf, data); + if(result) { + ctx->state = CF_HC_FAILURE; + ctx->result = result; + return result; + } + } + } +#endif + return CURLE_OK; +} + +static bool time_to_start_baller2(struct Curl_cfilter *cf, + struct Curl_easy *data, + const struct curltime *pnow) +{ + struct cf_hc_ctx *ctx = cf->ctx; + timediff_t elapsed_ms; + + if(ctx->baller_count < 2) + return FALSE; + else if(cf_hc_baller_has_started(&ctx->ballers[1])) + return FALSE; + else if(ctx->ballers[0].result) { + CURL_TRC_CF(data, cf, "%s baller failed, starting %s", + ctx->ballers[0].name, ctx->ballers[1].name); + return TRUE; + } + + elapsed_ms = curlx_ptimediff_ms(pnow, &ctx->started); + if(elapsed_ms >= ctx->hard_eyeballs_timeout_ms) { + CURL_TRC_CF(data, cf, "%s inconclusive after %" FMT_TIMEDIFF_T ", " + "starting %s", ctx->ballers[0].name, + ctx->hard_eyeballs_timeout_ms, ctx->ballers[1].name); + return TRUE; + } + else if(elapsed_ms >= ctx->soft_eyeballs_timeout_ms) { + if(cf_hc_baller_reply_ms(&ctx->ballers[0], data) < 0) { + CURL_TRC_CF(data, cf, "%s has not seen any data after %" + FMT_TIMEDIFF_T "ms, starting %s", + ctx->ballers[0].name, ctx->soft_eyeballs_timeout_ms, + ctx->ballers[1].name); + return TRUE; + } + } + return FALSE; +} + +static bool cf_hc_may_h3(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_hc_ctx *ctx = cf->ctx; + if(!ctx->checked_h3) { + ctx->check_h3_result = + Curl_conn_may_http3(data, cf->conn, ctx->def_transport); + ctx->checked_h3 = TRUE; + } + return !ctx->check_h3_result; +} + +static enum alpnid cf_hc_get_httpsrr_alpn(struct Curl_cfilter *cf, + struct Curl_easy *data, + enum alpnid not_this_one) +{ +#ifdef USE_HTTPSRR + struct cf_hc_ctx *ctx = cf->ctx; + /* Is there an HTTPSRR use its ALPNs here. + * We are here after having selected a connection to a host+port and + * can no longer change that. Any HTTPSRR advice for other hosts and ports + * we need to ignore. */ + const struct Curl_https_rrinfo *rr; + size_t i; + + /* Do we have HTTPS-RR information? */ + rr = Curl_conn_dns_get_https(data, cf->sockindex, ctx->destination); + + CURL_TRC_CF(data, cf, "HTTPS-RR %savailable", rr ? "" : "not "); + /* We do not support `rr->no_def_alpn`. */ + if(Curl_httpsrr_applicable(data, rr) && !rr->no_def_alpn) { + for(i = 0; i < CURL_ARRAYSIZE(rr->alpns); ++i) { + enum alpnid alpn_rr = (enum alpnid)rr->alpns[i]; + if(alpn_rr == not_this_one) /* do not want this one */ + continue; + switch(alpn_rr) { + case ALPN_h3: + if((data->state.http_neg.allowed & CURL_HTTP_V3x) && + cf_hc_may_h3(cf, data)) { + return alpn_rr; + } + break; + case ALPN_h2: + if(data->state.http_neg.allowed & CURL_HTTP_V2x) { + return alpn_rr; + } + break; + case ALPN_h1: + if(data->state.http_neg.allowed & CURL_HTTP_V1x) { + return alpn_rr; + } + break; + default: /* ignore */ + break; + } + } + } +#else + (void)cf; + (void)data; + (void)not_this_one; +#endif + return ALPN_none; +} + +static enum alpnid cf_hc_get_pref_alpn(struct Curl_cfilter *cf, + struct Curl_easy *data, + enum alpnid not_this_one) +{ + if((data->state.http_neg.preferred & data->state.http_neg.allowed)) { + switch(data->state.http_neg.preferred) { + case CURL_HTTP_V3x: + if(cf_hc_may_h3(cf, data) && (ALPN_h3 != not_this_one)) + return ALPN_h3; + break; + case CURL_HTTP_V2x: + if(ALPN_h2 != not_this_one) + return ALPN_h2; + break; + case CURL_HTTP_V1x: + /* If we are trying h2 already, h1 is already used as fallback */ + if((ALPN_h1 != not_this_one) && (ALPN_h2 != not_this_one)) + return ALPN_h1; + break; + default: + break; + } + } + return ALPN_none; +} + +static enum alpnid cf_hc_get_first_alpn(struct Curl_cfilter *cf, + struct Curl_easy *data, + http_majors choices, + enum alpnid not_this_one) +{ + /* When told to not try h2, we also do not try h1 and vice versa */ + bool allow_h1_or_h2 = (not_this_one != ALPN_h1) && + (not_this_one != ALPN_h2); + if((ALPN_h3 != not_this_one) && (choices & CURL_HTTP_V3x) && + cf_hc_may_h3(cf, data)) { + return ALPN_h3; + } + if(allow_h1_or_h2 && (choices & CURL_HTTP_V2x)) { + return ALPN_h2; + } + if(allow_h1_or_h2 && (choices & CURL_HTTP_V1x)) { + return ALPN_h1; + } + return ALPN_none; +} + +static CURLcode cf_hc_set_baller1(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_hc_ctx *ctx = cf->ctx; + enum alpnid alpn1 = ALPN_none; + VERBOSE(const char *source = "HTTPS-RR"); + + DEBUGASSERT(cf->conn->bits.tls_enable_alpn); + + alpn1 = cf_hc_get_httpsrr_alpn(cf, data, ALPN_none); + if(alpn1 == ALPN_none) { + /* preference is configured and allowed, can we use it? */ + VERBOSE(source = "preferred version"); + alpn1 = cf_hc_get_pref_alpn(cf, data, ALPN_none); + } + if(alpn1 == ALPN_none) { + VERBOSE(source = "wanted versions"); + alpn1 = cf_hc_get_first_alpn(cf, data, + data->state.http_neg.wanted, + ALPN_none); + } + if(alpn1 == ALPN_none) { + VERBOSE(source = "allowed versions"); + alpn1 = cf_hc_get_first_alpn(cf, data, + data->state.http_neg.allowed, + ALPN_none); + } + + if(alpn1 == ALPN_none) { + /* None of the wanted/allowed HTTP versions could be chosen */ + if(ctx->check_h3_result) { + CURL_TRC_CF(data, cf, "unable to use HTTP/3"); + return ctx->check_h3_result; + } + CURL_TRC_CF(data, cf, "unable to select HTTP version"); + return CURLE_FAILED_INIT; + } + + cf_hc_baller_assign(&ctx->ballers[0], alpn1, ctx->def_transport); + ctx->baller_count = 1; + CURL_TRC_CF(data, cf, "1st attempt uses %s from %s", + ctx->ballers[0].name, source); + + switch(alpn1) { + case ALPN_h1: + /* We really want h1, switch off h2 to make it disappear in ALPN */ + data->state.http_neg.wanted &= (uint8_t)~CURL_HTTP_V2x; + break; + default: + break; + } + + return CURLE_OK; +} + +static void cf_hc_set_baller2(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_hc_ctx *ctx = cf->ctx; + enum alpnid alpn2 = ALPN_none, alpn1 = ctx->ballers[0].alpn_id; + VERBOSE(const char *source = "HTTPS-RR"); + + if(ctx->ballers_complete) + return; /* already done */ + if(!ctx->httpsrr_resolved) + return; /* HTTPS-RR pending */ + + alpn2 = cf_hc_get_httpsrr_alpn(cf, data, alpn1); + if(alpn2 == ALPN_none) { + /* preference is configured and allowed, can we use it? */ + VERBOSE(source = "preferred version"); + alpn2 = cf_hc_get_pref_alpn(cf, data, alpn1); + } + if(alpn2 == ALPN_none) { + VERBOSE(source = "wanted versions"); + alpn2 = cf_hc_get_first_alpn(cf, data, + data->state.http_neg.wanted, + alpn1); + } + + if(alpn2 != ALPN_none) { + cf_hc_baller_assign(&ctx->ballers[1], alpn2, ctx->def_transport); + ctx->baller_count = 2; + CURL_TRC_CF(data, cf, "2nd attempt uses %s from %s", + ctx->ballers[1].name, source); + } + ctx->ballers_complete = TRUE; +} + +static CURLcode cf_hc_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_hc_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + const struct curltime *pnow = NULL; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; + + if(!ctx->httpsrr_resolved) { + ctx->httpsrr_resolved = Curl_conn_dns_resolved_https( + data, cf->sockindex, ctx->destination); +#ifdef DEBUGBUILD + if(!ctx->httpsrr_resolved && getenv("CURL_DBG_AWAIT_HTTPSRR")) { + CURL_TRC_CF(data, cf, "awaiting HTTPS-RR"); + return CURLE_OK; + } +#endif + } + + switch(ctx->state) { + case CF_HC_RESOLV: + ctx->state = CF_HC_INIT; + FALLTHROUGH(); + + case CF_HC_INIT: + DEBUGASSERT(!cf->next); + CURL_TRC_CF(data, cf, "connect, init"); + result = cf_hc_set_baller1(cf, data); + if(result) { + ctx->result = result; + ctx->state = CF_HC_FAILURE; + goto out; + } + cf_hc_set_baller2(cf, data); + pnow = Curl_pgrs_now(data); + ctx->started = *pnow; + cf_hc_baller_init(&ctx->ballers[0], cf, data); + if((ctx->baller_count > 1) || !ctx->ballers_complete) { + Curl_expire_set(data, EXPIRE_ALPN_EYEBALLS, + ctx->soft_eyeballs_timeout_ms, pnow); + } + ctx->state = CF_HC_CONNECT; + FALLTHROUGH(); + + case CF_HC_CONNECT: + if(!ctx->ballers_complete) + cf_hc_set_baller2(cf, data); + + if(cf_hc_baller_is_connecting(&ctx->ballers[0])) { + result = cf_hc_baller_connect(&ctx->ballers[0], cf, data, done); + if(!result && *done) { + result = baller_connected(cf, data, &ctx->ballers[0]); + goto out; + } + } + + pnow = Curl_pgrs_now(data); + if(time_to_start_baller2(cf, data, pnow)) { + cf_hc_baller_init(&ctx->ballers[1], cf, data); + } + + if(cf_hc_baller_is_connecting(&ctx->ballers[1])) { + result = cf_hc_baller_connect(&ctx->ballers[1], cf, data, done); + if(!result && *done) { + result = baller_connected(cf, data, &ctx->ballers[1]); + goto out; + } + } + + if(ctx->ballers[0].result && + (ctx->ballers[1].result || + (ctx->ballers_complete && (ctx->baller_count < 2)))) { + /* all have failed. we give up */ + CURL_TRC_CF(data, cf, "connect, all attempts failed"); + ctx->result = result = ctx->ballers[0].result; + ctx->state = CF_HC_FAILURE; + goto out; + } + result = CURLE_OK; + *done = FALSE; + break; + + case CF_HC_FAILURE: + result = ctx->result; + cf->connected = FALSE; + *done = FALSE; + break; + + case CF_HC_SUCCESS: + result = CURLE_OK; + cf->connected = TRUE; + *done = TRUE; + break; + } + +out: + CURL_TRC_CF(data, cf, "connect -> %d, done=%d", (int)result, *done); + return result; +} + +static CURLcode cf_hc_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + struct cf_hc_ctx *ctx = cf->ctx; + size_t i; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* shutdown all ballers that have not done so already. If one fails, + * continue shutting down others until all are shutdown. */ + for(i = 0; i < ctx->baller_count; i++) { + struct cf_hc_baller *b = &ctx->ballers[i]; + bool bdone = FALSE; + if(!cf_hc_baller_is_connecting(b) || b->shutdown) + continue; + b->result = b->cf->cft->do_shutdown(b->cf, data, &bdone); + if(b->result || bdone) + b->shutdown = TRUE; /* treat a failed shutdown as done */ + } + + *done = TRUE; + for(i = 0; i < ctx->baller_count; i++) { + if(!ctx->ballers[i].shutdown) + *done = FALSE; + } + if(*done) { + for(i = 0; i < ctx->baller_count; i++) { + if(ctx->ballers[i].result) + result = ctx->ballers[i].result; + } + } + CURL_TRC_CF(data, cf, "shutdown -> %d, done=%d", (int)result, *done); + return result; +} + +static CURLcode cf_hc_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + CURLcode result = CURLE_OK; + if(!cf->connected) { + struct cf_hc_ctx *ctx = cf->ctx; + size_t i; + + for(i = 0; (i < ctx->baller_count) && !result; i++) { + struct cf_hc_baller *b = &ctx->ballers[i]; + if(!cf_hc_baller_is_connecting(b)) + continue; + result = Curl_conn_cf_adjust_pollset(b->cf, data, ps); + } + CURL_TRC_CF(data, cf, "adjust_pollset -> %d, %u socks", (int)result, + ps->n); + } + return result; +} + +static bool cf_hc_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_hc_ctx *ctx = cf->ctx; + size_t i; + + if(cf->connected) + return cf->next->cft->has_data_pending(cf->next, data); + + for(i = 0; i < ctx->baller_count; i++) + if(cf_hc_baller_data_pending(&ctx->ballers[i], data)) + return TRUE; + return FALSE; +} + +static CURLcode cf_hc_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_hc_ctx *ctx = cf->ctx; + size_t i; + + if(!cf->connected) { + switch(query) { + case CF_QUERY_NEED_FLUSH: { + for(i = 0; i < ctx->baller_count; i++) + if(cf_hc_baller_needs_flush(&ctx->ballers[i], data)) { + *pres1 = TRUE; + return CURLE_OK; + } + break; + } + default: + break; + } + } + return cf->next ? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +static CURLcode cf_hc_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + struct cf_hc_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + size_t i; + + if(!cf->connected) { + switch(event) { + case CF_CTRL_REPORT_STATS: + for(i = 0; i < ctx->baller_count; i++) { + /* Make the first baller that connected at network level report */ + if(Curl_conn_cf_is_ip_connected(ctx->ballers[i].cf, data)) { + Curl_conn_cf_cntrl(ctx->ballers[i].cf, data, TRUE, + event, arg1, arg2); + break; + } + } + break; + default: + for(i = 0; i < ctx->baller_count; i++) { + result = cf_hc_baller_cntrl(&ctx->ballers[i], data, event, arg1, arg2); + if(result && (result != CURLE_AGAIN)) + goto out; + } + result = CURLE_OK; + break; + } + } +out: + return result; +} + +static void cf_hc_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_hc_ctx *ctx = cf->ctx; + + CURL_TRC_CF(data, cf, "destroy"); + cf_hc_ctx_destroy(data, ctx); +} + +struct Curl_cftype Curl_cft_http_connect = { + "HTTPS-CONNECT", + CF_TYPE_SETUP, + CURL_LOG_LVL_NONE, + cf_hc_destroy, + cf_hc_connect, + cf_hc_shutdown, + cf_hc_adjust_pollset, + cf_hc_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + cf_hc_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_hc_query, +}; + +static CURLcode cf_hc_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *destination, + uint8_t def_transport) +{ + struct Curl_cfilter *cf = NULL; + struct cf_hc_ctx *ctx; + CURLcode result = CURLE_OK; + + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + Curl_peer_link(&ctx->destination, destination); + ctx->def_transport = def_transport; + ctx->hard_eyeballs_timeout_ms = data->set.happy_eyeballs_timeout; + ctx->soft_eyeballs_timeout_ms = data->set.happy_eyeballs_timeout / 2; + + result = Curl_cf_create(&cf, &Curl_cft_http_connect, ctx); + if(result) + goto out; + ctx = NULL; + +out: + *pcf = result ? NULL : cf; + cf_hc_ctx_destroy(data, ctx); + return result; +} + +static CURLcode cf_hc_add(struct Curl_easy *data, + struct Curl_peer *destination, + struct connectdata *conn, + int8_t sockindex, + uint8_t def_transport) +{ + struct Curl_cfilter *cf; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + result = cf_hc_create(&cf, data, destination, def_transport); + if(result) + goto out; + Curl_conn_cf_add(data, conn, sockindex, cf); + +#ifdef USE_HTTPSRR + result = Curl_conn_dns_add_https_resolve(data, cf->conn, cf->sockindex, + destination); +#endif +out: + return result; +} + +CURLcode Curl_cf_https_setup(struct Curl_easy *data, + struct Curl_peer *destination, + struct connectdata *conn, + int8_t sockindex) +{ + CURLcode result = CURLE_OK; + + DEBUGASSERT(conn->scheme->protocol == CURLPROTO_HTTPS); + + /* This filter is intended for HTTPS using ALPN and does + * not support HTTPS Eyeballing to a proxy. */ + if((conn->scheme->protocol != CURLPROTO_HTTPS) || +#ifndef CURL_DISABLE_PROXY + conn->bits.origin_is_proxy || +#endif + !conn->bits.tls_enable_alpn) + goto out; + + result = cf_hc_add(data, destination, conn, sockindex, + conn->transport_wanted); + +out: + return result; +} + +#endif /* !CURL_DISABLE_HTTP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-https-connect.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-https-connect.h new file mode 100644 index 0000000000..efac194856 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-https-connect.h @@ -0,0 +1,44 @@ +#ifndef HEADER_CURL_CF_HTTP_H +#define HEADER_CURL_CF_HTTP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_HTTP + +struct Curl_cfilter; +struct Curl_easy; +struct connectdata; +struct Curl_cftype; +struct Curl_peer; + +extern struct Curl_cftype Curl_cft_http_connect; + +CURLcode Curl_cf_https_setup(struct Curl_easy *data, + struct Curl_peer *destination, + struct connectdata *conn, + int8_t sockindex); + +#endif /* !CURL_DISABLE_HTTP */ +#endif /* HEADER_CURL_CF_HTTP_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-ip-happy.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-ip-happy.c new file mode 100644 index 0000000000..baca4682f0 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-ip-happy.c @@ -0,0 +1,1019 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> /* <netinet/tcp.h> may need it */ +#endif +#ifdef HAVE_LINUX_TCP_H +#include <linux/tcp.h> +#elif defined(HAVE_NETINET_TCP_H) +#include <netinet/tcp.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif + +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include "urldata.h" +#include "connect.h" +#include "cfilters.h" +#include "cf-ip-happy.h" +#include "curl_addrinfo.h" +#include "curl_trc.h" +#include "multiif.h" +#include "progress.h" +#include "select.h" +#include "sockaddr.h" +#include "vdns/cf-dns.h" +#include "vquic/vquic.h" /* for quic cfilters */ + + +struct transport_provider { + cf_ip_connect_create *cf_create; + uint8_t transport; + bool tunnel; +}; + +static +#ifndef UNITTESTS +const +#endif +struct transport_provider transport_providers[] = { + { Curl_cf_tcp_create, TRNSPRT_TCP, FALSE }, + { Curl_cf_tcp_create, TRNSPRT_TCP, TRUE }, +#if !defined(CURL_DISABLE_HTTP) && defined(USE_HTTP3) + { Curl_cf_quic_create, TRNSPRT_QUIC, FALSE }, +#endif +#if !defined(CURL_DISABLE_HTTP) && defined(USE_PROXY_HTTP3) + { Curl_cf_h3_proxy_create, TRNSPRT_QUIC, TRUE }, +#endif +#ifndef CURL_DISABLE_TFTP + { Curl_cf_udp_create, TRNSPRT_UDP, FALSE }, +#endif +#ifdef USE_UNIX_SOCKETS + { Curl_cf_unix_create, TRNSPRT_UNIX, FALSE }, + { Curl_cf_unix_create, TRNSPRT_UNIX, TRUE }, +#endif +}; + +static cf_ip_connect_create *get_cf_create(uint8_t transport, + bool tunnel) +{ + size_t i; + for(i = 0; i < CURL_ARRAYSIZE(transport_providers); ++i) { + if((transport == transport_providers[i].transport) && + (tunnel == transport_providers[i].tunnel)) + return transport_providers[i].cf_create; + } + return NULL; +} + +#ifdef UNITTESTS +/* @unittest 2600 */ +UNITTEST void debug_set_transport_provider( + uint8_t transport, cf_ip_connect_create *cf_create); +UNITTEST void debug_set_transport_provider( + uint8_t transport, cf_ip_connect_create *cf_create) +{ + size_t i; + for(i = 0; i < CURL_ARRAYSIZE(transport_providers); ++i) { + if(transport == transport_providers[i].transport) { + transport_providers[i].cf_create = cf_create; + } + } +} +#endif /* UNITTESTS */ + +struct cf_ai_iter { + struct Curl_cfilter *cf; + struct Curl_peer *peer; + int ai_family; + unsigned int n; +}; + +static void cf_ai_iter_init(struct cf_ai_iter *iter, + struct Curl_cfilter *cf, + struct Curl_peer *peer, + int ai_family) +{ + iter->cf = cf; + iter->peer = peer; /* not linked, ctx->ballers owns and has same lifetime */ + iter->ai_family = ai_family; + iter->n = 0; +} + +static const struct Curl_addrinfo *cf_ai_iter_next(struct cf_ai_iter *iter, + struct Curl_easy *data) +{ + const struct Curl_addrinfo *addr; + + if(!iter->cf) + return NULL; + + addr = Curl_conn_dns_get_ai(data, iter->peer, iter->cf->sockindex, + iter->ai_family, iter->n); + if(addr) + iter->n++; + return addr; +} + +static bool cf_ai_iter_has_more(struct cf_ai_iter *iter, + struct Curl_easy *data) +{ + return (iter->cf && + !!Curl_conn_dns_get_ai(data, iter->peer, iter->cf->sockindex, + iter->ai_family, iter->n)); +} + +struct cf_ip_attempt { + struct cf_ip_attempt *next; + struct Curl_peer *origin; + struct Curl_peer *peer; + struct Curl_peer *tunnel_peer; + struct Curl_sockaddr_ex addr; + struct Curl_cfilter *cf; /* current sub-cfilter connecting */ + cf_ip_connect_create *cf_create; + CURLcode result; + int ai_family; + uint8_t transport_peer; + uint8_t tunnel_transport; + int error; + BIT(connected); /* cf has connected */ + BIT(shutdown); /* cf has shutdown */ + BIT(inconclusive); /* connect was not a hard failure, we + * might talk to a restarting server */ +}; + +static void cf_ip_attempt_free(struct cf_ip_attempt *a, + struct Curl_easy *data) +{ + if(a) { + if(a->cf) + Curl_conn_cf_discard_chain(&a->cf, data); + Curl_peer_unlink(&a->origin); + Curl_peer_unlink(&a->peer); + Curl_peer_unlink(&a->tunnel_peer); + curlx_free(a); + } +} + +static CURLcode cf_ip_attempt_new(struct cf_ip_attempt **pa, + struct Curl_easy *data, + struct Curl_cfilter *cf, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct Curl_sockaddr_ex *addr, + int ai_family, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport, + cf_ip_connect_create *cf_create) +{ + struct Curl_cfilter *wcf; + struct cf_ip_attempt *a; + CURLcode result = CURLE_OK; + + *pa = NULL; + a = curlx_calloc(1, sizeof(*a)); + if(!a) + return CURLE_OUT_OF_MEMORY; + + Curl_peer_link(&a->origin, origin); + Curl_peer_link(&a->peer, peer); + a->transport_peer = transport_peer; + Curl_peer_link(&a->tunnel_peer, tunnel_peer); + a->tunnel_transport = tunnel_transport; + a->addr = *addr; + a->ai_family = ai_family; + a->result = CURLE_OK; + a->cf_create = cf_create; + *pa = a; + + result = a->cf_create(&a->cf, data, a->origin, a->peer, a->transport_peer, + cf->conn, &a->addr, a->tunnel_peer, + a->tunnel_transport); + if(result) + goto out; + + /* the new filter might have sub-filters */ + for(wcf = a->cf; wcf; wcf = wcf->next) { + wcf->conn = cf->conn; + wcf->sockindex = cf->sockindex; + } + +out: + if(result) { + cf_ip_attempt_free(a, data); + *pa = NULL; + } + return result; +} + +static CURLcode cf_ip_attempt_connect(struct cf_ip_attempt *a, + struct Curl_easy *data, + bool *connected) +{ + *connected = (bool)a->connected; + if(!a->result && !*connected) { + /* evaluate again */ + a->result = Curl_conn_cf_connect(a->cf, data, connected); + + if(!a->result) { + if(*connected) { + a->connected = TRUE; + } + } + else { + if(a->result == CURLE_WEIRD_SERVER_REPLY) + a->inconclusive = TRUE; + if(a->cf) + Curl_conn_cf_discard_chain(&a->cf, data); + } + } + return a->result; +} + +struct cf_ip_ballers { + struct cf_ip_attempt *running; + struct cf_ip_attempt *winner; + struct cf_ai_iter addr_iter; +#ifdef USE_IPV6 + struct cf_ai_iter ipv6_iter; +#endif + struct Curl_peer *origin; + struct Curl_peer *peer; + struct Curl_peer *tunnel_peer; + cf_ip_connect_create *cf_create; /* for creating cf */ + struct curltime last_attempt_started; + timediff_t attempt_delay_ms; + int last_attempt_ai_family; + uint32_t max_concurrent; + uint8_t transport_peer; + uint8_t tunnel_transport; +}; + +static CURLcode cf_ip_attempt_restart(struct cf_ip_attempt *a, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct Curl_cfilter *wcf; + CURLcode result; + + if(a->cf) + Curl_conn_cf_discard_chain(&a->cf, data); + + a->result = CURLE_OK; + a->connected = FALSE; + a->inconclusive = FALSE; + a->cf = NULL; + + result = a->cf_create(&a->cf, data, a->origin, a->peer, a->transport_peer, + cf->conn, &a->addr, + a->tunnel_peer, a->tunnel_transport); + if(!result) { + bool dummy; + /* the new filter might have sub-filters */ + for(wcf = a->cf; wcf; wcf = wcf->next) { + wcf->conn = cf->conn; + wcf->sockindex = cf->sockindex; + } + a->result = cf_ip_attempt_connect(a, data, &dummy); + } + return result; +} + +static void cf_ip_ballers_clear(struct Curl_easy *data, + struct cf_ip_ballers *bs) +{ + while(bs->running) { + struct cf_ip_attempt *a = bs->running; + bs->running = a->next; + cf_ip_attempt_free(a, data); + } + cf_ip_attempt_free(bs->winner, data); + bs->winner = NULL; + Curl_peer_unlink(&bs->origin); + Curl_peer_unlink(&bs->peer); + Curl_peer_unlink(&bs->tunnel_peer); +} + +static CURLcode cf_ip_ballers_init(struct cf_ip_ballers *bs, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport, + timediff_t attempt_delay_ms, + uint32_t max_concurrent) +{ + memset(bs, 0, sizeof(*bs)); + bs->cf_create = get_cf_create(transport_peer, !!tunnel_peer); + if(!bs->cf_create) { + failf(data, "unsupported transport type %u%s", + transport_peer, tunnel_peer ? " to proxy" : ""); + return CURLE_UNSUPPORTED_PROTOCOL; + } + Curl_peer_link(&bs->origin, origin); + Curl_peer_link(&bs->peer, peer); + bs->transport_peer = transport_peer; + Curl_peer_link(&bs->tunnel_peer, tunnel_peer); + bs->tunnel_transport = tunnel_transport; + bs->attempt_delay_ms = attempt_delay_ms; + bs->max_concurrent = max_concurrent; + bs->last_attempt_ai_family = AF_INET; /* so AF_INET6 is next */ + return CURLE_OK; +} + +static void cf_ip_ballers_prune(struct cf_ip_ballers *bs, + struct Curl_cfilter *cf, + struct Curl_easy *data, + uint32_t max_concurrent) +{ + struct cf_ip_attempt *a = NULL, **panchor; + uint32_t ongoing = 0; + + for(a = bs->running; a; a = a->next) { + if(!a->result && !a->connected) + ++ongoing; + } + + panchor = &bs->running; + while(*panchor && (ongoing > max_concurrent)) { + a = *panchor; + if(!a->result && !a->connected) { + *panchor = a->next; + a->next = NULL; + cf_ip_attempt_free(a, data); + --ongoing; + CURL_TRC_CF(data, cf, "discarding oldest attempt to keep limit"); + } + else { + panchor = &a->next; + } + } +} + +static CURLcode cf_ip_ballers_run(struct cf_ip_ballers *bs, + struct Curl_cfilter *cf, + struct Curl_easy *data, + bool dns_resolved, + bool *connected) +{ + CURLcode result = CURLE_OK; + struct cf_ip_attempt *a = NULL, **panchor; + bool do_more; + timediff_t next_expire_ms; + uint32_t inconclusive, ongoing; + const struct curltime *pnow = NULL; + VERBOSE(int i); + + if(bs->winner) + return CURLE_OK; + +evaluate: + ongoing = inconclusive = 0; + + /* check if a running baller connects now */ + VERBOSE(i = -1); + for(panchor = &bs->running; *panchor; panchor = &(*panchor)->next) { + VERBOSE(++i); + a = *panchor; + a->result = cf_ip_attempt_connect(a, data, connected); + if(!a->result) { + if(*connected) { + /* connected, declare the winner, remove from running, + * clear remaining running list. */ + CURL_TRC_CF(data, cf, "connect attempt #%d successful", i); + bs->winner = a; + *panchor = a->next; + a->next = NULL; + while(bs->running) { + a = bs->running; + bs->running = a->next; + cf_ip_attempt_free(a, data); + } + return CURLE_OK; + } + /* still running */ + ++ongoing; + } + else if(a->inconclusive) /* failed, but inconclusive */ + ++inconclusive; + } + if(bs->running) + CURL_TRC_CF(data, cf, "checked connect attempts: " + "%u ongoing, %u inconclusive", ongoing, inconclusive); + + /* no attempt connected yet, start another one? */ + pnow = Curl_pgrs_now(data); + if(!ongoing) { + do_more = TRUE; + } + else { + bool more_possible = cf_ai_iter_has_more(&bs->addr_iter, data); +#ifdef USE_IPV6 + if(!more_possible) + more_possible = cf_ai_iter_has_more(&bs->ipv6_iter, data); +#endif + do_more = more_possible && + (curlx_ptimediff_ms(pnow, &bs->last_attempt_started) >= + bs->attempt_delay_ms); + if(do_more) + CURL_TRC_CF(data, cf, "happy eyeballs timeout expired, " + "start next attempt"); + } + + if(do_more) { + /* start the next attempt if there is another ip address to try. + * Alternate between address families when possible. */ + const struct Curl_addrinfo *ai = NULL; + int ai_family = 0; + CURL_TRC_CF(data, cf, "want to do more"); +#ifdef USE_IPV6 + if((bs->last_attempt_ai_family == AF_INET) || + !cf_ai_iter_has_more(&bs->addr_iter, data)) { + ai = cf_ai_iter_next(&bs->ipv6_iter, data); + ai_family = bs->ipv6_iter.ai_family; + CURL_TRC_CF(data, cf, "check for next AAAA address: %s", + ai ? "found" : "none"); + } +#endif + if(!ai) { + ai = cf_ai_iter_next(&bs->addr_iter, data); + ai_family = bs->addr_iter.ai_family; + CURL_TRC_CF(data, cf, "check for next A address: %s", + ai ? "found" : "none"); + } + /* We are (re-)starting attempts. We are not interested in + * keeping old failure information. The new attempt will either + * succeed or persist new failure. */ + Curl_reset_fail(data); + + if(ai) { /* try another address */ + struct Curl_sockaddr_ex addr; + + /* Discard oldest to make room for new attempt */ + if(bs->max_concurrent) + cf_ip_ballers_prune(bs, cf, data, bs->max_concurrent - 1); + + result = Curl_socket_addr_from_ai(&addr, ai, bs->transport_peer); + if(result) + goto out; + + result = cf_ip_attempt_new(&a, data, cf, bs->origin, bs->peer, + bs->transport_peer, &addr, ai_family, + bs->tunnel_peer, bs->tunnel_transport, + bs->cf_create); + CURL_TRC_CF(data, cf, "starting %s attempt for ipv%s -> %d", + bs->running ? "next" : "first", + (ai_family == AF_INET) ? "4" : "6", (int)result); + if(result) + goto out; + DEBUGASSERT(a); + + /* append to running list */ + panchor = &bs->running; + while(*panchor) + panchor = &(*panchor)->next; + *panchor = a; + bs->last_attempt_started = *pnow; + bs->last_attempt_ai_family = ai_family; + /* and run everything again */ + goto evaluate; + } + else if(inconclusive) { + /* tried all addresses, no success but some where inconclusive. + * Let's restart the inconclusive ones. */ + timediff_t since_ms = + curlx_ptimediff_ms(pnow, &bs->last_attempt_started); + timediff_t delay_ms = bs->attempt_delay_ms - since_ms; + if(delay_ms <= 0) { + CURL_TRC_CF(data, cf, "all attempts inconclusive, restarting one"); + VERBOSE(i = -1); + for(a = bs->running; a; a = a->next) { + VERBOSE(++i); + if(!a->inconclusive) + continue; + result = cf_ip_attempt_restart(a, cf, data); + CURL_TRC_CF(data, cf, "restarted baller %d -> %d", i, (int)result); + if(result) /* serious failure */ + goto out; + bs->last_attempt_started = *pnow; + goto evaluate; + } + DEBUGASSERT(0); /* should not come here */ + } + else { + /* let's wait some more before restarting */ + infof(data, "connect attempts inconclusive, retrying " + "in %" FMT_TIMEDIFF_T "ms", delay_ms); + Curl_expire_set(data, EXPIRE_HAPPY_EYEBALLS, delay_ms, pnow); + } + /* attempt timeout for restart has not expired yet */ + goto out; + } + else if(!ongoing && dns_resolved) { + /* no more addresses, no inconclusive attempts */ + CURL_TRC_CF(data, cf, "no more attempts to try"); + result = CURLE_COULDNT_CONNECT; + VERBOSE(i = 0); + for(a = bs->running; a; a = a->next) { + CURL_TRC_CF(data, cf, "baller %d: result=%d", i, (int)a->result); + if(a->result) + result = a->result; + } + } + } + +out: + if(!result) { + bool more_possible; + + /* when do we need to be called again? */ + pnow = Curl_pgrs_now(data); + next_expire_ms = Curl_timeleft_now_ms(data, pnow); + if(next_expire_ms < 0) { + failf(data, "Connection timeout after %" FMT_OFF_T " ms", + Curl_pgrs_since_ms(data, NULL, TIMER_STARTSINGLE)); + return CURLE_OPERATION_TIMEDOUT; + } + + more_possible = cf_ai_iter_has_more(&bs->addr_iter, data); +#ifdef USE_IPV6 + if(!more_possible) + more_possible = cf_ai_iter_has_more(&bs->ipv6_iter, data); +#endif + if(more_possible) { + timediff_t expire_ms, elapsed_ms; + + elapsed_ms = curlx_ptimediff_ms(pnow, &bs->last_attempt_started); + expire_ms = CURLMAX(bs->attempt_delay_ms - elapsed_ms, 0); + next_expire_ms = CURLMIN(next_expire_ms, expire_ms); + if(next_expire_ms <= 0) { + CURL_TRC_CF(data, cf, "HAPPY_EYEBALLS timeout due, re-evaluate"); + goto evaluate; + } + CURL_TRC_CF(data, cf, "next HAPPY_EYEBALLS timeout in %" FMT_TIMEDIFF_T + "ms", next_expire_ms); + Curl_expire_set(data, EXPIRE_HAPPY_EYEBALLS, next_expire_ms, pnow); + } + } + return result; +} + +static CURLcode cf_ip_ballers_shutdown(struct cf_ip_ballers *bs, + struct Curl_easy *data, + bool *done) +{ + struct cf_ip_attempt *a; + + /* shutdown all ballers that have not done so already. If one fails, + * continue shutting down others until all are shutdown. */ + *done = TRUE; + for(a = bs->running; a; a = a->next) { + bool bdone = FALSE; + if(a->shutdown || !a->cf) + continue; + a->result = a->cf->cft->do_shutdown(a->cf, data, &bdone); + if(a->result || bdone) + a->shutdown = TRUE; /* treat a failed shutdown as done */ + else + *done = FALSE; + } + return CURLE_OK; +} + +static CURLcode cf_ip_ballers_pollset(struct cf_ip_ballers *bs, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_ip_attempt *a; + CURLcode result = CURLE_OK; + for(a = bs->running; a && !result; a = a->next) { + if(a->result) + continue; + result = Curl_conn_cf_adjust_pollset(a->cf, data, ps); + } + return result; +} + +static bool cf_ip_ballers_pending(struct cf_ip_ballers *bs, + const struct Curl_easy *data) +{ + struct cf_ip_attempt *a; + + for(a = bs->running; a; a = a->next) { + if(a->result) + continue; + if(a->cf && a->cf->cft->has_data_pending(a->cf, data)) + return TRUE; + } + return FALSE; +} + +static int cf_ip_ballers_min_reply_ms(struct cf_ip_ballers *bs, + struct Curl_easy *data) +{ + int reply_ms = -1, breply_ms; + struct cf_ip_attempt *a; + + for(a = bs->running; a; a = a->next) { + if(a->cf && !a->cf->cft->query(a->cf, data, CF_QUERY_CONNECT_REPLY_MS, + &breply_ms, NULL)) { + if(breply_ms >= 0 && (reply_ms < 0 || breply_ms < reply_ms)) + reply_ms = breply_ms; + } + } + return reply_ms; +} + +typedef enum { + SCFST_INIT, + SCFST_WAITING, + SCFST_DONE +} cf_connect_state; + +struct cf_ip_happy_ctx { + cf_ip_connect_create *cf_create; + cf_connect_state state; + struct cf_ip_ballers ballers; + BIT(dns_resolved); +}; + +static CURLcode is_connected(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *connected) +{ + struct cf_ip_happy_ctx *ctx = cf->ctx; + struct connectdata *conn = cf->conn; + CURLcode result; + + result = cf_ip_ballers_run(&ctx->ballers, cf, data, + (bool)ctx->dns_resolved, connected); + + if(!result) + return CURLE_OK; + else { + struct Curl_peer *peer = NULL, *proxy_peer = NULL; + char viamsg[160]; + + peer = Curl_conn_get_first_peer(conn, cf->sockindex); + if(!conn->origin || !peer) + return CURLE_FAILED_INIT; + +#ifndef CURL_DISABLE_PROXY + if(conn->socks_proxy.peer) + proxy_peer = conn->socks_proxy.peer; + else if(conn->http_proxy.peer) + proxy_peer = conn->http_proxy.peer; +#endif + + viamsg[0] = 0; + if(!Curl_peer_equal(peer, conn->origin) && + !Curl_peer_equal(peer, proxy_peer)) { +#ifdef USE_UNIX_SOCKETS + if(peer->unix_socket) + curl_msnprintf(viamsg, sizeof(viamsg), " over unix://%s", + peer->hostname); + else +#endif + curl_msnprintf(viamsg, sizeof(viamsg), " via %s:%u", + peer->hostname, peer->port); + } + + failf(data, "Failed to connect to %s:%u%s %s%s%safter " + "%" FMT_TIMEDIFF_T " ms: %s", + conn->origin->hostname, conn->origin->port, viamsg, + proxy_peer ? "over proxy " : "", + proxy_peer ? proxy_peer->hostname : "", + proxy_peer ? " " : "", + Curl_pgrs_since_ms(data, NULL, TIMER_STARTSINGLE), + curl_easy_strerror(result)); + +#ifdef SOCKETIMEDOUT + if(SOCKETIMEDOUT == data->state.os_errno) + result = CURLE_OPERATION_TIMEDOUT; +#endif + + return result; + } +} + +#define IP_HE_MAX_CONCURRENT_ATTEMPTS 6 + +static CURLcode cf_ip_happy_init(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_ip_happy_ctx *ctx = cf->ctx; + + if(Curl_timeleft_ms(data) < 0) { + /* a precaution, no need to continue if time already is up */ + failf(data, "Connection time-out"); + return CURLE_OPERATION_TIMEDOUT; + } + + if(ctx->ballers.transport_peer == TRNSPRT_UNIX) { +#ifdef USE_UNIX_SOCKETS + cf_ai_iter_init(&ctx->ballers.addr_iter, cf, ctx->ballers.peer, AF_UNIX); +#else + return CURLE_UNSUPPORTED_PROTOCOL; +#endif + } + else { /* TCP/UDP/QUIC */ +#ifdef USE_IPV6 + cf_ai_iter_init(&ctx->ballers.ipv6_iter, cf, ctx->ballers.peer, AF_INET6); +#endif + cf_ai_iter_init(&ctx->ballers.addr_iter, cf, ctx->ballers.peer, AF_INET); + } + + CURL_TRC_CF(data, cf, "init ip ballers for transport %u", + ctx->ballers.transport_peer); + return CURLE_OK; +} + +static void cf_ip_happy_ctx_clear(struct cf_ip_happy_ctx *ctx, + struct Curl_easy *data) +{ + DEBUGASSERT(ctx); + if(ctx) + cf_ip_ballers_clear(data, &ctx->ballers); +} + +static void cf_ip_happy_ctx_destroy(struct cf_ip_happy_ctx *ctx, + struct Curl_easy *data) +{ + if(ctx) { + cf_ip_happy_ctx_clear(ctx, data); + curlx_free(ctx); + } +} + +static CURLcode cf_ip_happy_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_ip_happy_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + result = cf_ip_ballers_shutdown(&ctx->ballers, data, done); + CURL_TRC_CF(data, cf, "shutdown -> %d, done=%d", (int)result, *done); + return result; +} + +static CURLcode cf_ip_happy_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_ip_happy_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(!cf->connected) { + result = cf_ip_ballers_pollset(&ctx->ballers, data, ps); + CURL_TRC_CF(data, cf, "adjust_pollset -> %d, %u socks", (int)result, + ps->n); + } + return result; +} + +static CURLcode cf_ip_happy_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_ip_happy_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + /* -Werror=null-dereference finds false positives suddenly. */ + if(!data) + return CURLE_FAILED_INIT; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + DEBUGASSERT(ctx); + *done = FALSE; + + if(!ctx->dns_resolved) { + result = Curl_conn_dns_addr_result(cf->conn, cf->sockindex, + ctx->ballers.peer); + if(!result) + ctx->dns_resolved = TRUE; + else if(result == CURLE_AGAIN) { + result = CURLE_OK; + } + else /* real error */ + goto out; + } + + switch(ctx->state) { + case SCFST_INIT: + DEBUGASSERT(CURL_SOCKET_BAD == Curl_conn_cf_get_socket(cf, data)); + DEBUGASSERT(!cf->connected); + result = cf_ip_happy_init(cf, data); + if(result) + goto out; + ctx->state = SCFST_WAITING; + FALLTHROUGH(); + case SCFST_WAITING: + result = is_connected(cf, data, done); + if(!result && *done) { + DEBUGASSERT(ctx->ballers.winner); + DEBUGASSERT(ctx->ballers.winner->cf); + DEBUGASSERT(ctx->ballers.winner->cf->connected); + /* we have a winner. Install and activate it. + * close/free all others. */ + ctx->state = SCFST_DONE; + cf->connected = TRUE; + cf->next = ctx->ballers.winner->cf; + ctx->ballers.winner->cf = NULL; + + if(cf->conn->scheme->protocol & PROTO_FAMILY_SSH) + Curl_pgrsTime(data, TIMER_APPCONNECT); /* we are connected already */ +#ifdef CURLVERBOSE + if(Curl_trc_cf_is_verbose(cf, data)) { + struct ip_quadruple ipquad; + bool is_ipv6; + if(!Curl_conn_cf_get_ip_info(cf->next, data, &is_ipv6, &ipquad)) { + CURL_TRC_CF(data, cf, "Connected to %s (%s) port %u", + ctx->ballers.peer->hostname, + ipquad.remote_ip, ipquad.remote_port); + } + } +#endif + cf_ip_happy_ctx_clear(ctx, data); + Curl_expire_clear(data, EXPIRE_HAPPY_EYEBALLS); + /* whatever errors were reported by ballers, clear our errorbuf */ + Curl_reset_fail(data); + data->info.numconnects++; /* to track the # of connections made */ + } + break; + case SCFST_DONE: + *done = TRUE; + break; + } +out: + return result; +} + +static bool cf_ip_happy_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_ip_happy_ctx *ctx = cf->ctx; + + if(!cf->connected) { + return cf_ip_ballers_pending(&ctx->ballers, data); + } + return cf->next->cft->has_data_pending(cf->next, data); +} + +static CURLcode cf_ip_happy_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_ip_happy_ctx *ctx = cf->ctx; + + if(!cf->connected) { + switch(query) { + case CF_QUERY_CONNECT_REPLY_MS: { + *pres1 = cf_ip_ballers_min_reply_ms(&ctx->ballers, data); + CURL_TRC_CF(data, cf, "query connect reply: %dms", *pres1); + return CURLE_OK; + } + default: + break; + } + } + + return cf->next ? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +static void cf_ip_happy_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_ip_happy_ctx *ctx = cf->ctx; + + CURL_TRC_CF(data, cf, "destroy"); + if(ctx) { + cf_ip_happy_ctx_clear(ctx, data); + cf_ip_happy_ctx_destroy(ctx, data); + } +} + +struct Curl_cftype Curl_cft_ip_happy = { + "HAPPY-EYEBALLS", + CF_TYPE_SETUP, + CURL_LOG_LVL_NONE, + cf_ip_happy_destroy, + cf_ip_happy_connect, + cf_ip_happy_shutdown, + cf_ip_happy_adjust_pollset, + cf_ip_happy_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_ip_happy_query, +}; + +static CURLcode cf_ip_happy_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct connectdata *conn, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport) +{ + struct cf_ip_happy_ctx *ctx = NULL; + CURLcode result; + + (void)data; + (void)conn; + *pcf = NULL; + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + result = cf_ip_ballers_init(&ctx->ballers, data, + origin, peer, transport_peer, + tunnel_peer, tunnel_transport, + data->set.happy_eyeballs_timeout, + IP_HE_MAX_CONCURRENT_ATTEMPTS); + if(result) + goto out; + + result = Curl_cf_create(pcf, &Curl_cft_ip_happy, ctx); + +out: + if(result) { + curlx_safefree(*pcf); + cf_ip_happy_ctx_destroy(ctx, data); + } + return result; +} + +CURLcode Curl_cf_ip_happy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport) +{ + struct Curl_cfilter *cf; + CURLcode result; + + /* Need to be first */ + DEBUGASSERT(cf_at); + result = cf_ip_happy_create(&cf, data, origin, peer, transport_peer, + cf_at->conn, tunnel_peer, tunnel_transport); + if(result) + return result; + + Curl_conn_cf_insert_after(cf_at, cf); + return CURLE_OK; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-ip-happy.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-ip-happy.h new file mode 100644 index 0000000000..88de0c3245 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-ip-happy.h @@ -0,0 +1,73 @@ +#ifndef HEADER_CURL_IP_HAPPY_H +#define HEADER_CURL_IP_HAPPY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct connectdata; +struct Curl_addrinfo; +struct Curl_cfilter; +struct Curl_easy; +struct Curl_peer; +struct Curl_sockaddr_ex; + +/** + * Create a cfilter to connect to `origin` via an optional `peer` + * using `transport_peer` and `addr`. + * With a `tunnel_peer` present, the filter will be used to proxy tunnel + * to it and the tunnel will use `tunnel_transport`. + * `pcf`: the filter created on success + * `data`: the transfer initiating the connect + * `conn`: the connection that gets connected + * + * The filter is used in "happy eyeball" scenarios. Once connected, + * it MAY be installed in the connection filter chain to serve transfers. + */ +typedef CURLcode cf_ip_connect_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport); + +/** + * Create an IP happy eyeball connection filter that connects to `origin` + * via an optional `peer` using `transport_peer`. + * With a `tunnel_peer` present, the filter will be used to proxy tunnel + * to it and the tunnel will use `tunnel_transport`. + */ +CURLcode Curl_cf_ip_happy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport); + +extern struct Curl_cftype Curl_cft_ip_happy; + +#endif /* HEADER_CURL_IP_HAPPY_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-recvbuf.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-recvbuf.c new file mode 100644 index 0000000000..55b01a26f5 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-recvbuf.c @@ -0,0 +1,157 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_WEBSOCKETS +/* only used for this protocol, so far */ + +#include "urldata.h" +#include "bufq.h" +#include "cfilters.h" +#include "cf-recvbuf.h" +#include "curl_trc.h" + +#define CURL_CF_RECVBUF_CHUNK (16 * 1024) + +struct cf_recvbuf_ctx { + struct bufq recvbuf; +}; + +static void cf_recvbuf_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_recvbuf_ctx *ctx = cf->ctx; + (void)data; + if(ctx) { + Curl_bufq_free(&ctx->recvbuf); + curlx_free(ctx); + } +} + +static CURLcode cf_recvbuf_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, size_t len, + size_t *pnread) +{ + struct cf_recvbuf_ctx *ctx = cf->ctx; + + if(!Curl_bufq_is_empty(&ctx->recvbuf)) { + return Curl_bufq_cread(&ctx->recvbuf, buf, len, pnread); + } + + if(cf->next) + return cf->next->cft->do_recv(cf->next, data, buf, len, pnread); + *pnread = 0; + return CURLE_RECV_ERROR; +} + +static bool cf_recvbuf_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_recvbuf_ctx *ctx = cf->ctx; + + if(!Curl_bufq_is_empty(&ctx->recvbuf)) + return TRUE; + + return cf->next ? + cf->next->cft->has_data_pending(cf->next, data) : FALSE; +} + +struct Curl_cftype Curl_cft_recvbuf = { + "RECVBUF", + 0, + CURL_LOG_LVL_NONE, + cf_recvbuf_destroy, + Curl_cf_def_connect, + Curl_cf_def_shutdown, + Curl_cf_def_adjust_pollset, + cf_recvbuf_data_pending, + Curl_cf_def_send, + cf_recvbuf_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + Curl_cf_def_query, +}; + +static CURLcode cf_recvbuf_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + const uint8_t *buf, size_t blen) +{ + struct Curl_cfilter *cf = NULL; + struct cf_recvbuf_ctx *ctx; + CURLcode result = CURLE_OK; + size_t nwritten = 0; + + (void)data; + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + Curl_bufq_init2(&ctx->recvbuf, CURL_CF_RECVBUF_CHUNK, + (blen / CURL_CF_RECVBUF_CHUNK) + 1, + (BUFQ_OPT_SOFT_LIMIT | BUFQ_OPT_NO_SPARES)); + result = Curl_bufq_write(&ctx->recvbuf, buf, blen, &nwritten); + if(result) + goto out; + if(nwritten != blen) { + result = CURLE_FAILED_INIT; + goto out; + } + + result = Curl_cf_create(&cf, &Curl_cft_recvbuf, ctx); + if(result) + goto out; + ctx = NULL; + +out: + *pcf = result ? NULL : cf; + if(ctx) { + Curl_bufq_free(&ctx->recvbuf); + curlx_free(ctx); + } + return result; +} + +CURLcode Curl_cf_recvbuf_add(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + const uint8_t *buf, size_t blen) +{ + struct Curl_cfilter *cf; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + result = cf_recvbuf_create(&cf, data, buf, blen); + if(result) + goto out; + + cf->connected = Curl_conn_is_connected(conn, sockindex); + Curl_conn_cf_add(data, conn, sockindex, cf); +out: + return result; +} + +#endif /* !CURL_DISABLE_WEBSOCKETS */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-recvbuf.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-recvbuf.h new file mode 100644 index 0000000000..e126c3c6b6 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-recvbuf.h @@ -0,0 +1,40 @@ +#ifndef HEADER_CURL_CF_RECVBUF_H +#define HEADER_CURL_CF_RECVBUF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_WEBSOCKETS +/* only used for this protocol, so far */ + +CURLcode Curl_cf_recvbuf_add(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + const uint8_t *buf, size_t blen); + +extern struct Curl_cftype Curl_cft_recvbuf; + +#endif /* !CURL_DISABLE_WEBSOCKETS */ + +#endif /* HEADER_CURL_CF_RECVBUF_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-setup.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-setup.c new file mode 100644 index 0000000000..2d77b1cb6d --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-setup.c @@ -0,0 +1,479 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "cfilters.h" +#include "cf-haproxy.h" +#include "cf-ip-happy.h" +#include "cf-setup.h" +#include "curl_trc.h" +#include "connect.h" +#include "http_proxy.h" +#include "socks.h" +#include "vquic/cf-capsule.h" +#include "vquic/vquic.h" +#include "vtls/vtls.h" + + +typedef enum { + CF_SETUP_INIT, + CF_SETUP_CNNCT_EYEBALLS, + CF_SETUP_CNNCT_SOCKS, + CF_SETUP_CNNCT_HTTP_PROXY, + CF_SETUP_CNNCT_HAPROXY, + CF_SETUP_CNNCT_SSL, + CF_SETUP_DONE +} cf_setup_state; + +struct cf_setup_ctx { + cf_setup_state state; + int ssl_mode; + uint8_t transport; + uint8_t retry_count; +}; + +#ifndef CURL_DISABLE_PROXY + +static CURLcode cf_setup_add_haproxy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_setup_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(ctx->state < CF_SETUP_CNNCT_HAPROXY) { + if(data->set.haproxyprotocol) { + if(ctx->transport == TRNSPRT_QUIC) { + failf(data, "haproxy protocol does not support QUIC"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + result = Curl_cf_haproxy_insert_after(cf, data); + if(result) { + CURL_TRC_CF(data, cf, "adding HAPROXY filter failed -> %d", + (int)result); + return result; + } + CURL_TRC_CF(data, cf, "added HAPROXY filter"); + } + ctx->state = CF_SETUP_CNNCT_HAPROXY; + } + return result; +} + +static CURLcode cf_setup_add_socks(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_setup_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + if(ctx->state < CF_SETUP_CNNCT_SOCKS && cf->conn->socks_proxy.peer) { + /* Add a SOCKS proxy to go through `first_peer` to `second_peer`*/ + struct Curl_peer *second_peer; + + if(cf->conn->http_proxy.peer) + second_peer = cf->conn->http_proxy.peer; + else + second_peer = Curl_conn_get_destination(cf->conn, cf->sockindex); + if(!second_peer) + return CURLE_FAILED_INIT; + + result = Curl_cf_socks_proxy_insert_after( + cf, data, second_peer, cf->conn->ip_version, + cf->conn->socks_proxy.proxytype, + cf->conn->socks_proxy.creds); + if(result) { + CURL_TRC_CF(data, cf, "adding SOCKS filter failed -> %d", (int)result); + return result; + } + + CURL_TRC_CF(data, cf, "added SOCKS filter to %s:%u", + second_peer->hostname, second_peer->port); + ctx->state = CF_SETUP_CNNCT_SOCKS; + } + return result; +} + +#ifndef CURL_DISABLE_HTTP +static CURLcode cf_setup_add_http_proxy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_setup_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(ctx->state < CF_SETUP_CNNCT_HTTP_PROXY && + cf->conn->http_proxy.peer && !cf->conn->bits.origin_is_proxy) { + struct Curl_peer *peer = cf->conn->http_proxy.peer; + struct Curl_peer *tunnel_peer = + Curl_conn_get_destination(cf->conn, cf->sockindex); + +#ifdef USE_SSL + if(CURL_PROXY_IS_HTTPS(cf->conn->http_proxy.proxytype) && + !Curl_conn_is_ssl(cf->conn, cf->sockindex)) { + result = Curl_cf_ssl_proxy_insert_after( + cf, data, cf->conn->http_proxy.peer); + if(result) { + CURL_TRC_CF(data, cf, "adding SSL filter for HTTP proxy failed -> %d", + (int)result); + return result; + } + CURL_TRC_CF(data, cf, "added SSL filter for HTTP proxy"); + } +#endif /* USE_SSL */ + + result = Curl_cf_http_proxy_insert_after( + cf, data, peer, tunnel_peer, + ctx->transport, cf->conn->http_proxy.proxytype); + if(result) { + CURL_TRC_CF(data, cf, "adding HTTP proxy tunnel filter failed -> %d", + (int)result); + return result; + } + CURL_TRC_CF(data, cf, "added HTTP proxy tunnel filter"); + ctx->state = CF_SETUP_CNNCT_HTTP_PROXY; + } + return result; +} +#endif /* !CURL_DISABLE_HTTP */ +#endif /* CURL_DISABLE_PROXY */ + +/* Get the origin curl connects its socket to. + * Can be origin or the first proxy. */ +static struct Curl_peer *conn_get_first_origin(struct connectdata *conn, + int8_t sockindex) +{ +#ifndef CURL_DISABLE_PROXY + if(conn->socks_proxy.peer) + return conn->socks_proxy.peer; + if(conn->http_proxy.peer) + return conn->http_proxy.peer; +#endif + return (sockindex == SECONDARYSOCKET) ? conn->origin2 : conn->origin; +} + +static CURLcode cf_setup_add_ip_happy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_setup_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(ctx->state < CF_SETUP_CNNCT_EYEBALLS) { + /* What is the first hop we directly connect to and what transport + * do we use for it? Only on the first hop we can do Happy Eyeballs. + * first_origin and first_peer differ on --connect-to. */ + struct Curl_peer *first_origin = + conn_get_first_origin(cf->conn, cf->sockindex); + struct Curl_peer *first_peer = + Curl_conn_get_first_peer(cf->conn, cf->sockindex); + struct Curl_peer *tunnel_peer = NULL; + uint8_t first_transport = ctx->transport; + + if(!first_peer) + return CURLE_FAILED_INIT; + +#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP) + if(cf->conn->http_proxy.peer && !cf->conn->bits.origin_is_proxy) { + first_transport = + Curl_http_proxy_transport(cf->conn->http_proxy.proxytype); + tunnel_peer = Curl_conn_get_destination(cf->conn, cf->sockindex); + if((first_transport == TRNSPRT_QUIC) && cf->conn->socks_proxy.peer) { + failf(data, "HTTP/3 proxy not possible via SOCKS"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + } +#endif /* !CURL_DISABLE_PROXY && !CURL_DISABLE_HTTP */ + + result = Curl_cf_ip_happy_insert_after(cf, data, first_origin, first_peer, + first_transport, + tunnel_peer, ctx->transport); + if(result) { + CURL_TRC_CF(data, cf, "adding happy eyeballs failed -> %d", (int)result); + return result; + } + + if(tunnel_peer && (first_transport == TRNSPRT_QUIC)) { + CURL_TRC_CF(data, cf, "happy eyeballing to HTTP/3 proxy %s:%u", + first_peer->hostname, first_peer->port); + ctx->state = CF_SETUP_CNNCT_HTTP_PROXY; + } + else { + CURL_TRC_CF(data, cf, "happy eyeballing to %s %s:%u", + tunnel_peer ? "proxy" : "origin", + first_peer->hostname, first_peer->port); + ctx->state = CF_SETUP_CNNCT_EYEBALLS; + } + } + return result; +} + +static CURLcode cf_setup_add_origin_filters(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_setup_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + (void)data; /* not used in all builds */ + if(ctx->state < CF_SETUP_CNNCT_SSL) { +#if !defined(CURL_DISABLE_HTTP) && defined(USE_HTTP3) && \ + !defined(CURL_DISABLE_PROXY) + + /* Wanting QUIC with an HTTP tunneling filter, we now need to add + * the QUIC filter on top. Without tunneling, this has already + * happened in the Happy Eyeball filter. */ + if(ctx->transport == TRNSPRT_QUIC && + cf->conn->http_proxy.peer && !cf->conn->bits.origin_is_proxy) { + struct Curl_peer *origin = Curl_conn_get_origin(cf->conn, cf->sockindex); + struct Curl_peer *peer = + Curl_conn_get_destination(cf->conn, cf->sockindex); + + result = Curl_cf_capsule_insert_after(cf, data); + if(result) { + CURL_TRC_CF(data, cf, "adding capsule filter failed -> %d", + (int)result); + return result; + } + result = Curl_cf_quic_insert_after(cf, data, origin, peer); + if(result) { + CURL_TRC_CF(data, cf, "adding QUIC filter failed -> %d", (int)result); + return result; + } + CURL_TRC_CF(data, cf, "added QUIC filter for origin"); + } + else +#endif /* !CURL_DISABLE_HTTP && USE_HTTP3 && CURL_DISABLE_PROXY */ +#ifdef USE_SSL + if((ctx->ssl_mode == CURL_CF_SSL_ENABLE || + (ctx->ssl_mode != CURL_CF_SSL_DISABLE && + cf->conn->scheme->flags & PROTOPT_SSL)) && /* we want SSL */ + !Curl_conn_is_ssl(cf->conn, cf->sockindex)) { /* it is missing */ + +#ifndef CURL_DISABLE_PROXY + if(cf->conn->bits.origin_is_proxy) { + result = Curl_cf_ssl_proxy_insert_after(cf, data, cf->conn->origin); + } + else +#endif + { + /* FTP is a bitch. Wherever we really connect to on the DATA + * (secondary) connection, many servers require TLS sessions reuse + * to prove they are talking to the same client. + * For the TLS session lookup to work, we need to instantiate + * the SSL filter with the same peers as FIRSTSOCKET. See #22225 + * Meaning: cf->sockindex does not matter here. */ + result = Curl_cf_ssl_insert_after(cf, data, + Curl_conn_get_origin(cf->conn, FIRSTSOCKET), + Curl_conn_get_destination(cf->conn, FIRSTSOCKET)); + } + if(result) { + CURL_TRC_CF(data, cf, "adding SSL filter for origin failed -> %d", + (int)result); + return result; + } + CURL_TRC_CF(data, cf, "added SSL filter for origin"); + } +#endif /* USE_SSL */ + ctx->state = CF_SETUP_CNNCT_SSL; + } + return result; +} + +static CURLcode cf_setup_connect_steps(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_setup_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* connect current sub-chain */ +connect_sub_chain: + VERBOSE(Curl_conn_trc_filters(data, cf->sockindex, "cf_setup_connect")); + + if(cf->next && !cf->next->connected) { + result = Curl_conn_cf_connect(cf->next, data, done); + if(result || !*done) + return result; + } + + result = cf_setup_add_ip_happy(cf, data); + if(result) + return result; + if(!cf->next || !cf->next->connected) + goto connect_sub_chain; + +#ifndef CURL_DISABLE_PROXY + result = cf_setup_add_socks(cf, data); + if(result) + return result; + if(!cf->next || !cf->next->connected) + goto connect_sub_chain; + +#ifndef CURL_DISABLE_HTTP + result = cf_setup_add_http_proxy(cf, data); + if(result) + return result; + if(!cf->next || !cf->next->connected) + goto connect_sub_chain; +#endif /* !CURL_DISABLE_HTTP */ + + result = cf_setup_add_haproxy(cf, data); + if(result) + return result; + if(!cf->next || !cf->next->connected) + goto connect_sub_chain; +#endif /* !CURL_DISABLE_PROXY */ + + result = cf_setup_add_origin_filters(cf, data); + if(result) + return result; + if(!cf->next || !cf->next->connected) + goto connect_sub_chain; + + ctx->state = CF_SETUP_DONE; + cf->connected = TRUE; + *done = TRUE; + return CURLE_OK; +} + +static CURLcode cf_setup_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_setup_ctx *ctx = cf->ctx; + CURLcode result; + + /* In some situations, a server/proxy may close the connection and + * we need to connect again (HTTP/1.x proxy auth, for example). + * We used to close the filters and reuse them for another attempt, + * however that complicates filter code and it is simpler to tear them + * all down and start over. */ +retry: + result = cf_setup_connect_steps(cf, data, done); + + if(result == CURLE_AGAIN) { + ++ctx->retry_count; + if(ctx->retry_count > 5) /* arbitrary limit, better just timeout? */ + return CURLE_COULDNT_CONNECT; + + CURL_TRC_CF(data, cf, "retrying connect, %d. time", ctx->retry_count); + Curl_conn_cf_discard_chain(&cf->next, data); + ctx->state = CF_SETUP_INIT; + goto retry; + } + return result; +} + +static void cf_setup_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_setup_ctx *ctx = cf->ctx; + + CURL_TRC_CF(data, cf, "destroy"); + curlx_safefree(ctx); +} + +struct Curl_cftype Curl_cft_setup = { + "SETUP", + CF_TYPE_SETUP, + CURL_LOG_LVL_NONE, + cf_setup_destroy, + cf_setup_connect, + Curl_cf_def_shutdown, + Curl_cf_def_adjust_pollset, + Curl_cf_def_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + Curl_cf_def_query, +}; + +static CURLcode cf_setup_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + uint8_t transport, + int ssl_mode) +{ + struct Curl_cfilter *cf = NULL; + struct cf_setup_ctx *ctx; + CURLcode result = CURLE_OK; + + (void)data; + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + ctx->state = CF_SETUP_INIT; + ctx->ssl_mode = ssl_mode; + ctx->transport = transport; + + result = Curl_cf_create(&cf, &Curl_cft_setup, ctx); + if(result) + goto out; + ctx = NULL; + +out: + *pcf = result ? NULL : cf; + if(ctx) { + curlx_free(ctx); + } + return result; +} + +CURLcode Curl_cf_setup_add(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + uint8_t transport, + int ssl_mode) +{ + struct Curl_cfilter *cf; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + result = cf_setup_create(&cf, data, transport, ssl_mode); + if(result) + goto out; + Curl_conn_cf_add(data, conn, sockindex, cf); +out: + return result; +} + +CURLcode Curl_cf_setup_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + uint8_t transport, + int ssl_mode) +{ + struct Curl_cfilter *cf; + CURLcode result; + + DEBUGASSERT(data); + result = cf_setup_create(&cf, data, transport, ssl_mode); + if(result) + goto out; + Curl_conn_cf_insert_after(cf_at, cf); +out: + return result; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-setup.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-setup.h new file mode 100644 index 0000000000..71c6093fe5 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-setup.h @@ -0,0 +1,46 @@ +#ifndef HEADER_CURL_CF_SETUP_H +#define HEADER_CURL_CF_SETUP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct Curl_dns_entry; +struct ip_quadruple; +struct Curl_peer; +struct Curl_str; + +CURLcode Curl_cf_setup_add(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + uint8_t transport, + int ssl_mode); + +CURLcode Curl_cf_setup_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + uint8_t transport, + int ssl_mode); + +extern struct Curl_cftype Curl_cft_setup; + +#endif /* HEADER_CURL_CF_SETUP_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-socket.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-socket.c new file mode 100644 index 0000000000..870a98ecbd --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-socket.c @@ -0,0 +1,2460 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> /* <netinet/tcp.h> may need it */ +#endif +#ifdef HAVE_SYS_UN_H +#include <sys/un.h> /* for sockaddr_un */ +#endif +#ifdef HAVE_LINUX_TCP_H +#include <linux/tcp.h> +#elif defined(HAVE_NETINET_TCP_H) +#include <netinet/tcp.h> +#endif +#ifdef HAVE_NETINET_UDP_H +#include <netinet/udp.h> +#endif +#ifdef HAVE_NETINET_IP_H +#include <netinet/ip.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif + +#ifdef HAVE_IFADDRS_H +#include <ifaddrs.h> +#endif +#ifdef HAVE_NET_IF_H +#include <net/if.h> +#endif +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include "urldata.h" +#include "curl_trc.h" +#include "if2ip.h" +#include "cfilters.h" +#include "cf-socket.h" +#include "connect.h" +#include "curl_addrinfo.h" +#include "select.h" +#include "multiif.h" +#include "curlx/inet_ntop.h" +#include "curlx/inet_pton.h" +#include "progress.h" +#include "conncache.h" +#include "multihandle.h" +#include "rand.h" +#include "sockaddr.h" +#include "curlx/strdup.h" +#include "curlx/nonblock.h" +#include "curlx/strcopy.h" +#include "curlx/version_win32.h" +#include "curlx/strerr.h" +#include "curlx/strparse.h" +#ifdef _WIN32 +#include <mstcpip.h> /* for TCP_INITIAL_RTO_PARAMETERS */ +#endif + +/* retrieves ip address and port from a sockaddr structure. note it calls + * curlx_inet_ntop() and returns CURLcode. + * @unittest 1607 + */ +UNITTEST CURLcode sockaddr2string(struct sockaddr *sa, curl_socklen_t salen, + char *addr, uint16_t *port); +UNITTEST CURLcode sockaddr2string(struct sockaddr *sa, curl_socklen_t salen, + char *addr, uint16_t *port) +{ + CURLcode result; + struct sockaddr_in *si = NULL; +#ifdef USE_IPV6 + struct sockaddr_in6 *si6 = NULL; +#endif +#ifdef USE_UNIX_SOCKETS + struct sockaddr_un *su = NULL; +#else + (void)salen; +#endif + + switch(sa->sa_family) { + case AF_INET: + si = (struct sockaddr_in *)(void *)sa; + result = curlx_inet_ntop(sa->sa_family, &si->sin_addr, addr, + MAX_IPADR_LEN); + if(!result) { + *port = ntohs(si->sin_port); + return result; + } + break; +#ifdef USE_IPV6 + case AF_INET6: + si6 = (struct sockaddr_in6 *)(void *)sa; + result = curlx_inet_ntop(sa->sa_family, &si6->sin6_addr, addr, + MAX_IPADR_LEN); + if(!result) { + *port = ntohs(si6->sin6_port); + return result; + } + break; +#endif +#ifdef USE_UNIX_SOCKETS + case AF_UNIX: + if(salen > (curl_socklen_t)sizeof(CURL_SA_FAMILY_T)) { + su = (struct sockaddr_un *)sa; + curl_msnprintf(addr, MAX_IPADR_LEN, "%s", su->sun_path); + } + else + addr[0] = 0; /* socket with no name */ + *port = 0; + return CURLE_OK; +#endif + default: + result = CURLE_UNSUPPORTED_PROTOCOL; + break; + } + + addr[0] = '\0'; + *port = 0; + return result; +} + +static void tcpnodelay(struct Curl_cfilter *cf, + struct Curl_easy *data, + curl_socket_t sockfd) +{ +#if defined(TCP_NODELAY) && defined(CURL_TCP_NODELAY_SUPPORTED) + curl_socklen_t onoff = (curl_socklen_t)1; + int level = IPPROTO_TCP; + VERBOSE(char buffer[STRERROR_LEN]); + + if(setsockopt(sockfd, level, TCP_NODELAY, (void *)&onoff, sizeof(onoff)) < 0) + CURL_TRC_CF(data, cf, "Could not set TCP_NODELAY: %s", + curlx_strerror(SOCKERRNO, buffer, sizeof(buffer))); +#else + (void)cf; + (void)data; + (void)sockfd; +#endif +} + +#if defined(USE_WINSOCK) || defined(TCP_KEEPIDLE) || \ + defined(TCP_KEEPALIVE) || defined(TCP_KEEPALIVE_THRESHOLD) || \ + defined(TCP_KEEPINTVL) || defined(TCP_KEEPALIVE_ABORT_THRESHOLD) +#if defined(USE_WINSOCK) || \ + (defined(__sun) && !defined(TCP_KEEPIDLE)) || \ + (defined(__DragonFly__) && __DragonFly_version < 500702) || \ + (defined(_WIN32) && !defined(TCP_KEEPIDLE)) +/* Solaris < 11.4, DragonFlyBSD < 500702 and Windows < 10.0.16299 + * use millisecond units. */ +#define KEEPALIVE_FACTOR(x) ((x) *= 1000) +#else +#define KEEPALIVE_FACTOR(x) +#endif +#endif + +static void tcpkeepalive(struct Curl_cfilter *cf, + struct Curl_easy *data, + curl_socket_t sockfd) +{ + int optval = data->set.tcp_keepalive ? 1 : 0; + + /* only set IDLE and INTVL if setting KEEPALIVE is successful */ + if(setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, + (void *)&optval, sizeof(optval)) < 0) { + CURL_TRC_CF(data, cf, "Failed to set SO_KEEPALIVE on fd " + "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO); + } + else { +#ifdef USE_WINSOCK + /* Windows 10, version 1709 (10.0.16299) and later versions can use + setsockopt() TCP_KEEP*. Older versions return with failure. */ + if(curlx_verify_windows_version(10, 0, 16299, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) { + CURL_TRC_CF(data, cf, "Set TCP_KEEP* on fd=%" FMT_SOCKET_T, sockfd); + optval = curlx_sltosi(data->set.tcp_keepidle); +/* Offered by mingw-w64 v12+, MS SDK 6.0A/VS2008+ */ +#ifndef TCP_KEEPALIVE +#define TCP_KEEPALIVE 3 +#endif +/* Offered by mingw-w64 v12+, MS SDK 10.0.15063.0/VS2017 15.1+ */ +#ifndef TCP_KEEPCNT +#define TCP_KEEPCNT 16 +#endif +/* Offered by mingw-w64 v12+, MS SDK 10.0.16299.0/VS2017 15.4+ */ +#ifndef TCP_KEEPIDLE +#define TCP_KEEPIDLE TCP_KEEPALIVE +#endif +#ifndef TCP_KEEPINTVL +#define TCP_KEEPINTVL 17 +#endif + if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, + (const char *)&optval, sizeof(optval)) < 0) { + CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPIDLE on fd " + "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO); + } + optval = curlx_sltosi(data->set.tcp_keepintvl); + if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, + (const char *)&optval, sizeof(optval)) < 0) { + CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPINTVL on fd " + "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO); + } + optval = curlx_sltosi(data->set.tcp_keepcnt); + if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPCNT, + (const char *)&optval, sizeof(optval)) < 0) { + CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPCNT on fd " + "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO); + } + } + else { +/* Offered by mingw-w64 and MS SDK. Latter only when targeting Win7+. */ +#ifndef SIO_KEEPALIVE_VALS +#define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR, 4) + struct tcp_keepalive { + u_long onoff; + u_long keepalivetime; + u_long keepaliveinterval; + }; +#endif + struct tcp_keepalive vals; + DWORD dummy; + vals.onoff = 1; + optval = curlx_sltosi(data->set.tcp_keepidle); + KEEPALIVE_FACTOR(optval); + vals.keepalivetime = (u_long)optval; + optval = curlx_sltosi(data->set.tcp_keepintvl); + KEEPALIVE_FACTOR(optval); + vals.keepaliveinterval = (u_long)optval; + if(WSAIoctl(sockfd, SIO_KEEPALIVE_VALS, (LPVOID)&vals, sizeof(vals), + NULL, 0, &dummy, NULL, NULL) != 0) { + CURL_TRC_CF(data, cf, "Failed to set SIO_KEEPALIVE_VALS on fd " + "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO); + } + } +#else /* !USE_WINSOCK */ +#ifdef TCP_KEEPIDLE + optval = curlx_sltosi(data->set.tcp_keepidle); + KEEPALIVE_FACTOR(optval); + if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, + (void *)&optval, sizeof(optval)) < 0) { + CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPIDLE on fd " + "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO); + } +#elif defined(TCP_KEEPALIVE) + /* macOS style */ + optval = curlx_sltosi(data->set.tcp_keepidle); + KEEPALIVE_FACTOR(optval); + if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE, + (void *)&optval, sizeof(optval)) < 0) { + CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPALIVE on fd " + "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO); + } +#elif defined(TCP_KEEPALIVE_THRESHOLD) + /* Solaris <11.4 style */ + optval = curlx_sltosi(data->set.tcp_keepidle); + KEEPALIVE_FACTOR(optval); + if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE_THRESHOLD, + (void *)&optval, sizeof(optval)) < 0) { + CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPALIVE_THRESHOLD on fd " + "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO); + } +#endif +#ifdef TCP_KEEPINTVL + optval = curlx_sltosi(data->set.tcp_keepintvl); + KEEPALIVE_FACTOR(optval); + if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, + (void *)&optval, sizeof(optval)) < 0) { + CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPINTVL on fd " + "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO); + } +#elif defined(TCP_KEEPALIVE_ABORT_THRESHOLD) + /* Solaris <11.4 style */ + /* TCP_KEEPALIVE_ABORT_THRESHOLD should equal to + * TCP_KEEPCNT * TCP_KEEPINTVL on other platforms. + * The default value of TCP_KEEPCNT is 9 on Linux, + * 8 on *BSD/macOS, 5 or 10 on Windows. We use the + * default config for Solaris <11.4 because there is + * no default value for TCP_KEEPCNT on Solaris 11.4. + * + * Note that the consequent probes will not be sent + * at equal intervals on Solaris, but will be sent + * using the exponential backoff algorithm. */ + { + int keepcnt = curlx_sltosi(data->set.tcp_keepcnt); + int keepintvl = curlx_sltosi(data->set.tcp_keepintvl); + + if(keepcnt > 0 && keepintvl > (INT_MAX / keepcnt)) + optval = INT_MAX; + else + optval = keepcnt * keepintvl; + } + KEEPALIVE_FACTOR(optval); + if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE_ABORT_THRESHOLD, + (void *)&optval, sizeof(optval)) < 0) { + CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPALIVE_ABORT_THRESHOLD" + " on fd %" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO); + } +#endif +#ifdef TCP_KEEPCNT + optval = curlx_sltosi(data->set.tcp_keepcnt); + if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPCNT, + (void *)&optval, sizeof(optval)) < 0) { + CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPCNT on fd " + "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO); + } +#endif +#endif /* USE_WINSOCK */ + } +} + +/** + * Assign the addrinfo `ai` to the Curl_sockaddr_ex `addr` with + * transport determining socktype and protocol. + */ +CURLcode Curl_socket_addr_from_ai(struct Curl_sockaddr_ex *addr, + const struct Curl_addrinfo *ai, + uint8_t transport) +{ + /* + * The Curl_sockaddr_ex structure is libcurl's external API + * curl_sockaddr structure with enough space available to directly hold + * any protocol-specific address structures. The variable declared here + * will be used to pass / receive data to/from the fopensocket callback + * if this has been set, before that, it is initialized from parameters. + */ + addr->family = ai->ai_family; + addr->socktype = Curl_socktype_for_transport(transport); + addr->protocol = Curl_protocol_for_transport(transport); + addr->addrlen = (unsigned int)ai->ai_addrlen; + + DEBUGASSERT(addr->addrlen <= sizeof(addr->curl_sa_addrbuf)); + if(addr->addrlen > sizeof(addr->curl_sa_addrbuf)) + return CURLE_TOO_LARGE; + + memcpy(&addr->curl_sa_addrbuf, ai->ai_addr, addr->addrlen); + return CURLE_OK; +} + +#ifdef USE_SO_NOSIGPIPE +int Curl_sock_nosigpipe(curl_socket_t sockfd) +{ + int onoff = 1; + return setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, + (void *)&onoff, sizeof(onoff)); +} +#endif /* USE_SO_NOSIGPIPE */ + +#if defined(USE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID) +static uint32_t get_scope_id(struct Curl_easy *data, + struct sockaddr_in6 *sa6) +{ + uint32_t scope_id = 0; + if(data->conn->scope_id) + return data->conn->scope_id; + /* NOLINTNEXTLINE(clang-analyzer-core.uninitialized.Assign) */ + scope_id = sa6->sin6_scope_id; + if(!scope_id && IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) { + /* The resolver did not set scope_id for this link-local address. + * Try to determine it from the system's network interfaces. + * Without a scope_id, connect() to a link-local address fails + * with EINVAL on Linux. + * NOTE: On multi-homed hosts with several interfaces having + * link-local addresses, this picks the first one found, which + * may not be the correct outgoing interface. */ +#if defined(HAVE_GETIFADDRS) && defined(HAVE_NET_IF_H) + struct ifaddrs *ifa, *ifa_list; + if(getifaddrs(&ifa_list) == 0) { + for(ifa = ifa_list; ifa; ifa = ifa->ifa_next) { + if(ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET6 && + (ifa->ifa_flags & IFF_UP) && + !(ifa->ifa_flags & IFF_LOOPBACK)) { + struct sockaddr_in6 *s6 = (void *)ifa->ifa_addr; + if(IN6_IS_ADDR_LINKLOCAL(&s6->sin6_addr) && s6->sin6_scope_id) { + scope_id = s6->sin6_scope_id; + infof(data, + "determined scope_id=%lu for link-local address " + "from local interface", + (unsigned long)scope_id); + break; + } + } + } + freeifaddrs(ifa_list); + } +#endif /* HAVE_GETIFADDRS && HAVE_NET_IF_H */ + } + return scope_id; +} +#endif + +static CURLcode socket_open(struct Curl_easy *data, + struct Curl_sockaddr_ex *addr, + curl_socket_t *sockfd) +{ + char errbuf[STRERROR_LEN]; + +#ifdef SOCK_CLOEXEC + addr->socktype |= SOCK_CLOEXEC; +#endif + + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + if(data->set.fopensocket) { + /* + * If the opensocket callback is set, all the destination address + * information is passed to the callback. Depending on this information the + * callback may opt to abort the connection, this is indicated returning + * CURL_SOCKET_BAD; otherwise it will return a not-connected socket. When + * the callback returns a valid socket the destination address information + * might have been changed and this 'new' address will actually be used + * here to connect. + */ + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_fopensocket); + *sockfd = data->set.fopensocket(data->set.opensocket_client, + CURLSOCKTYPE_IPCXN, + (struct curl_sockaddr *)addr); + CURL_CBAPI_END(&guard); + } + else { + /* opensocket callback not set, so create the socket now */ +#ifdef DEBUGBUILD + if((addr->family == AF_INET6) && getenv("CURL_DBG_SOCK_FAIL_IPV6")) { + failf(data, "CURL_DBG_SOCK_FAIL_IPV6: failed to open socket"); + return CURLE_COULDNT_CONNECT; + } +#endif + *sockfd = CURL_SOCKET(addr->family, addr->socktype, addr->protocol); + if((*sockfd == CURL_SOCKET_BAD) && (SOCKERRNO == SOCKENOMEM)) + return CURLE_OUT_OF_MEMORY; + } + + if(*sockfd == CURL_SOCKET_BAD) { + /* no socket, no connection */ + failf(data, "failed to open socket: %s", + curlx_strerror(SOCKERRNO, errbuf, sizeof(errbuf))); + return CURLE_COULDNT_CONNECT; + } + +#ifdef USE_SO_NOSIGPIPE + if(Curl_sock_nosigpipe(*sockfd) < 0) { + failf(data, "setsockopt enable SO_NOSIGPIPE: %s", + curlx_strerror(SOCKERRNO, errbuf, sizeof(errbuf))); + sclose(*sockfd); + *sockfd = CURL_SOCKET_BAD; + return CURLE_COULDNT_CONNECT; + } +#endif /* USE_SO_NOSIGPIPE */ + +#if defined(HAVE_FCNTL) && !defined(SOCK_CLOEXEC) + if(fcntl(*sockfd, F_SETFD, FD_CLOEXEC) < 0) { + failf(data, "fcntl set CLOEXEC: %s", + curlx_strerror(SOCKERRNO, errbuf, sizeof(errbuf))); + sclose(*sockfd); + *sockfd = CURL_SOCKET_BAD; + return CURLE_COULDNT_CONNECT; + } +#endif + +#if defined(USE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID) + if(addr->family == AF_INET6) { + struct sockaddr_in6 * const sa6 = (void *)&addr->curl_sa_addr; + sa6->sin6_scope_id = get_scope_id(data, sa6); + } +#endif + return CURLE_OK; +} + +/* + * Create a socket based on info from 'conn' and 'ai'. + * + * 'addr' should be a pointer to the correct struct to get data back, or NULL. + * 'sockfd' must be a pointer to a socket descriptor. + * + * If the open socket callback is set, used that! + * + */ +CURLcode Curl_socket_open(struct Curl_easy *data, + const struct Curl_addrinfo *ai, + struct Curl_sockaddr_ex *addr, + uint8_t transport, + curl_socket_t *sockfd) +{ + struct Curl_sockaddr_ex dummy; + CURLcode result; + + if(!addr) + /* if the caller does not want info back, use a local temp copy */ + addr = &dummy; + + result = Curl_socket_addr_from_ai(addr, ai, transport); + if(result) + return result; + + return socket_open(data, addr, sockfd); +} + +static int socket_close(struct Curl_easy *data, struct connectdata *conn, + int use_callback, curl_socket_t sock) +{ + if(sock == CURL_SOCKET_BAD) + return 0; + + if(use_callback && conn && conn->fclosesocket) { + struct Curl_mapi_guard guard; + int rc; + Curl_multi_will_close(data, sock); + CURL_CBAPI_START(&guard, data, easy_closesocket); + rc = conn->fclosesocket(conn->closesocket_client, sock); + CURL_CBAPI_END(&guard); + return rc; + } + + if(conn) + /* tell the multi-socket code about this */ + Curl_multi_will_close(data, sock); + + sclose(sock); + + return 0; +} + +/* + * Close a socket. + * + * 'conn' can be NULL, beware! + */ +int Curl_socket_close(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t sock) +{ + return socket_close(data, conn, FALSE, sock); +} + +/* + * Curl_parse_interface() + * + * This is used to parse interface argument in the following formats. + * In all the examples, `host` can be an IP address or a hostname. + * + * <iface_or_host> - can be either an interface name or a host. + * if!<iface> - interface name. + * host!<host> - hostname. + * ifhost!<iface>!<host> - interface name and hostname. + * + * Parameters: + * + * input [in] - input string. + * len [in] - length of the input string. + * dev [in/out] - address where a pointer to newly allocated memory + * holding the interface-or-host will be stored upon + * completion. + * iface [in/out] - address where a pointer to newly allocated memory + * holding the interface will be stored upon completion. + * host [in/out] - address where a pointer to newly allocated memory + * holding the host will be stored upon completion. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_parse_interface(const char *input, + char **dev, char **iface, char **host) +{ + static const char if_prefix[] = "if!"; + static const char host_prefix[] = "host!"; + static const char if_host_prefix[] = "ifhost!"; + size_t len; + + DEBUGASSERT(dev); + DEBUGASSERT(iface); + DEBUGASSERT(host); + + len = strlen(input); + if(len > 512) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(!strncmp(if_prefix, input, strlen(if_prefix))) { + input += strlen(if_prefix); + if(!*input) + return CURLE_BAD_FUNCTION_ARGUMENT; + *iface = curlx_memdup0(input, len - strlen(if_prefix)); + return *iface ? CURLE_OK : CURLE_OUT_OF_MEMORY; + } + else if(!strncmp(host_prefix, input, strlen(host_prefix))) { + input += strlen(host_prefix); + if(!*input) + return CURLE_BAD_FUNCTION_ARGUMENT; + *host = curlx_memdup0(input, len - strlen(host_prefix)); + return *host ? CURLE_OK : CURLE_OUT_OF_MEMORY; + } + else if(!strncmp(if_host_prefix, input, strlen(if_host_prefix))) { + const char *host_part; + input += strlen(if_host_prefix); + len -= strlen(if_host_prefix); + host_part = memchr(input, '!', len); + if(!host_part || !*(host_part + 1)) + return CURLE_BAD_FUNCTION_ARGUMENT; + *iface = curlx_memdup0(input, host_part - input); + if(!*iface) + return CURLE_OUT_OF_MEMORY; + ++host_part; + *host = curlx_memdup0(host_part, len - (host_part - input)); + if(!*host) { + curlx_safefree(*iface); + return CURLE_OUT_OF_MEMORY; + } + return CURLE_OK; + } + + if(!*input) + return CURLE_BAD_FUNCTION_ARGUMENT; + *dev = curlx_memdup0(input, len); + return *dev ? CURLE_OK : CURLE_OUT_OF_MEMORY; +} + +#ifndef CURL_DISABLE_BINDLOCAL +static CURLcode bindlocal(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t sockfd, int af, unsigned int scope, + uint8_t transport) +{ + struct Curl_sockaddr_storage sa; + struct sockaddr *sock = (struct sockaddr *)&sa; /* bind to this address */ + curl_socklen_t sizeof_sa = 0; /* size of the data sock points to */ + struct sockaddr_in *si4 = (struct sockaddr_in *)&sa; +#ifdef USE_IPV6 + struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)&sa; +#endif + + struct Curl_dns_entry *h = NULL; + unsigned short port = data->set.localport; /* use this port number, 0 for + "random" */ + /* how many port numbers to try to bind to, increasing one at a time */ + int portnum = data->set.localportrange; + const char *dev = CURL_EASY_STR(data, STRING_DEVICE); + const char *iface_input = CURL_EASY_STR(data, STRING_INTERFACE); + const char *host_input = CURL_EASY_STR(data, STRING_BINDHOST); + const char *iface = iface_input ? iface_input : dev; + const char *host = host_input ? host_input : dev; + int sockerr; +#ifdef IP_BIND_ADDRESS_NO_PORT + int on = 1; +#endif +#ifndef USE_IPV6 + (void)scope; +#endif + + /************************************************************* + * Select device to bind socket to + *************************************************************/ + if(!iface && !host && !port) + /* no local kind of binding was requested */ + return CURLE_OK; + else if(iface && (strlen(iface) >= 255)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + memset(&sa, 0, sizeof(struct Curl_sockaddr_storage)); + + if(iface || host) { + char myhost[256] = ""; + int done = 0; /* -1 for error, 1 for address found */ + if2ip_result_t if2ip_result = IF2IP_NOT_FOUND; + +#ifdef SO_BINDTODEVICE + if(iface) { + /* + * This binds the local socket to a particular interface. This will + * force even requests to other local interfaces to go out the external + * interface. Only bind to the interface when specified as interface, + * not as a hostname or ip address. + * + * The interface might be a VRF, eg: vrf-blue, which means it cannot be + * converted to an IP address and would fail Curl_if2ip. Try to + * use it straight away. + */ + if(setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, + iface, (curl_socklen_t)strlen(iface) + 1) == 0) { + /* This is often "errno 1, error: Operation not permitted" if you are + * not running as root or another suitable privileged user. If it + * succeeds it means the parameter was a valid interface and not an IP + * address. Return immediately. + */ + if(!host_input) { + infof(data, "socket successfully bound to interface '%s'", iface); + return CURLE_OK; + } + } + } +#endif + if(!host_input) { + /* Discover IP from input device, then bind to it */ + if2ip_result = Curl_if2ip(af, +#ifdef USE_IPV6 + scope, conn->scope_id, +#endif + iface, myhost, sizeof(myhost)); + } + switch(if2ip_result) { + case IF2IP_NOT_FOUND: + if(iface_input && !host_input) { + /* Do not fall back to treating it as a hostname */ + char buffer[STRERROR_LEN]; + data->state.os_errno = sockerr = SOCKERRNO; + failf(data, "Could not bind to interface '%s' with errno %d: %s", + iface, sockerr, curlx_strerror(sockerr, buffer, sizeof(buffer))); + return CURLE_INTERFACE_FAILED; + } + break; + case IF2IP_AF_NOT_SUPPORTED: + /* Signal the caller to try another address family if available */ + return CURLE_UNSUPPORTED_PROTOCOL; + case IF2IP_FOUND: + /* + * We now have the numerical IP address in the 'myhost' buffer + */ + host = myhost; + infof(data, "Local Interface %s is ip %s using address family %d", + iface, host, af); + done = 1; + break; + } + if(!iface_input || host_input) { + /* + * This was not an interface, resolve the name as a hostname + * or IP number + * + * Temporarily force name resolution to use only the address type + * of the connection. The resolve functions should really be changed + * to take a type parameter instead. + */ + uint8_t dns_queries = (af == AF_INET) ? + CURL_DNSQ_A : (CURL_DNSQ_A | CURL_DNSQ_AAAA); +#ifdef USE_IPV6 + if(af == AF_INET6) + dns_queries = CURL_DNSQ_AAAA; +#endif + + (void)Curl_resolv_blocking(data, dns_queries, host, 80, transport, &h); + if(h) { + int h_af = h->addr->ai_family; + /* convert the resolved address, sizeof myhost >= INET_ADDRSTRLEN */ + Curl_printable_address(h->addr, myhost, sizeof(myhost)); + infof(data, "Name '%s' family %d resolved to '%s' family %d", + host, af, myhost, h_af); + Curl_dns_entry_unlink(data, &h); /* this will NULL, potential free h */ + if(af != h_af) { + /* bad IP version combo, signal the caller to try another address + family if available */ + return CURLE_UNSUPPORTED_PROTOCOL; + } + done = 1; + } + else { + /* + * provided dev was no interface (or interfaces are not supported + * e.g. Solaris) no ip address and no domain we fail here + */ + done = -1; + } + } + + if(done > 0) { +#ifdef USE_IPV6 + /* IPv6 address */ + if(af == AF_INET6) { +#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID + char *scope_ptr = strchr(myhost, '%'); + if(scope_ptr) + *(scope_ptr++) = '\0'; +#endif + if(curlx_inet_pton(AF_INET6, myhost, &si6->sin6_addr) > 0) { + si6->sin6_family = AF_INET6; + si6->sin6_port = htons(port); +#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID + if(scope_ptr) { + /* The "myhost" string either comes from Curl_if2ip or from + Curl_printable_address. The latter returns only numeric scope + IDs and the former returns none at all. Making the scope ID, + if present, known to be numeric */ + curl_off_t scope_id; + if(curlx_str_number((const char **)CURL_UNCONST(&scope_ptr), + &scope_id, UINT_MAX)) + return CURLE_UNSUPPORTED_PROTOCOL; + si6->sin6_scope_id = (unsigned int)scope_id; + } +#endif + } + sizeof_sa = sizeof(struct sockaddr_in6); + } + else +#endif + /* IPv4 address */ + if((af == AF_INET) && + (curlx_inet_pton(AF_INET, myhost, &si4->sin_addr) > 0)) { + si4->sin_family = AF_INET; + si4->sin_port = htons(port); + sizeof_sa = sizeof(struct sockaddr_in); + } + } + + if(done < 1) { + /* errorbuf is set false so failf will overwrite any message already in + the error buffer, so the user receives this error message instead of a + generic resolve error. */ + char buffer[STRERROR_LEN]; + data->state.errorbuf = FALSE; + data->state.os_errno = sockerr = SOCKERRNO; + failf(data, "Could not bind to '%s' with errno %d: %s", host, + sockerr, curlx_strerror(sockerr, buffer, sizeof(buffer))); + return CURLE_INTERFACE_FAILED; + } + } + else { + /* no device was given, prepare sa to match af's needs */ +#ifdef USE_IPV6 + if(af == AF_INET6) { + si6->sin6_family = AF_INET6; + si6->sin6_port = htons(port); + sizeof_sa = sizeof(struct sockaddr_in6); + } + else +#endif + if(af == AF_INET) { + si4->sin_family = AF_INET; + si4->sin_port = htons(port); + sizeof_sa = sizeof(struct sockaddr_in); + } + } +#ifdef IP_BIND_ADDRESS_NO_PORT + (void)setsockopt(sockfd, SOL_IP, IP_BIND_ADDRESS_NO_PORT, &on, sizeof(on)); +#endif + for(;;) { + if(bind(sockfd, sock, sizeof_sa) >= 0) { + /* we succeeded to bind */ + infof(data, "Local port: %hu", port); + conn->bits.bound = TRUE; + return CURLE_OK; + } + + if(--portnum > 0) { + port++; /* try next port */ + if(port == 0) + break; + infof(data, "Bind to local port %d failed, trying next", port - 1); + /* We reuse/clobber the port variable here below */ + if(sock->sa_family == AF_INET) + si4->sin_port = htons(port); +#ifdef USE_IPV6 + else + si6->sin6_port = htons(port); +#endif + } + else + break; + } + { + char buffer[STRERROR_LEN]; + data->state.os_errno = sockerr = SOCKERRNO; + failf(data, "bind failed with errno %d: %s", + sockerr, curlx_strerror(sockerr, buffer, sizeof(buffer))); + } + + return CURLE_INTERFACE_FAILED; +} +#endif + +/* + * verifyconnect() returns TRUE if the connect really has happened. + */ +static bool verifyconnect(curl_socket_t sockfd, int *psockerr) +{ + bool rc = TRUE; +#ifdef SO_ERROR + int sockerr = 0; + curl_socklen_t errSize = sizeof(sockerr); + +#ifdef _WIN32 + /* + * In October 2003 we effectively nullified this function on Windows due to + * problems with it using all CPU in multi-threaded cases. + * + * In May 2004, we brought it back to offer more info back on connect + * failures. We could reproduce the former problems with this function, but + * could avoid them by adding this SleepEx() call below: + * + * "I do not have Rational Quantify, but the hint from his post was + * ntdll::NtRemoveIoCompletion(). I would assume the SleepEx (or maybe + * Sleep(0) would be enough?) would release whatever + * mutex/critical-section the ntdll call is waiting on. + * + * Someone got to verify this on Win-NT 4.0, 2000." + */ + SleepEx(0, FALSE); +#endif + + if(getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &errSize)) + sockerr = SOCKERRNO; +#if defined(EBADIOCTL) && defined(__minix) + /* Minix 3.1.x does not support getsockopt on UDP sockets */ + if(EBADIOCTL == sockerr) { + SET_SOCKERRNO(0); + sockerr = 0; + } +#endif + if((sockerr == 0) || (SOCKEISCONN == sockerr)) + /* we are connected, awesome! */ + rc = TRUE; + else + /* This was not a successful connect */ + rc = FALSE; + if(psockerr) + *psockerr = sockerr; +#else + (void)sockfd; + if(psockerr) + *psockerr = SOCKERRNO; +#endif + return rc; +} + +/** + * Determine the curl code for a socket connect() == -1 with errno. + */ +static CURLcode socket_connect_result(struct Curl_easy *data, + const char *ipaddress, int sockerr) +{ + if(sockerr == SOCKEINPROGRESS || SOCK_EAGAIN(sockerr)) + return CURLE_OK; + + /* unknown error, fallthrough and try another address! */ + { + VERBOSE(char buffer[STRERROR_LEN]); + infof(data, "Immediate connect fail for %s: %s", ipaddress, + curlx_strerror(sockerr, buffer, sizeof(buffer))); + NOVERBOSE((void)ipaddress); + } + data->state.os_errno = sockerr; + /* connect failed */ + return CURLE_COULDNT_CONNECT; +} + +struct cf_socket_ctx { + struct Curl_peer *peer; + struct Curl_sockaddr_ex addr; /* address to connect to */ + curl_socket_t sock; /* current attempt socket */ + struct ip_quadruple ip; /* The IP quadruple 2x(addr+port) */ + struct curltime started_at; /* when socket was created */ + struct curltime connected_at; /* when socket connected/got first byte */ + struct curltime first_byte_at; /* when first byte was recvd */ +#ifdef USE_WINSOCK + struct curltime last_sndbuf_query_at; /* when SO_SNDBUF last queried */ + ULONG sndbuf_size; /* the last set SO_SNDBUF size */ +#endif + int sockerr; /* socket error of last failure or 0 */ +#ifdef DEBUGBUILD + int wblock_percent; /* percent of writes doing EAGAIN */ + int wpartial_percent; /* percent of bytes written in send */ + int rblock_percent; /* percent of reads doing EAGAIN */ + size_t recv_max; /* max enforced read size */ +#endif + uint8_t transport; + BIT(got_first_byte); /* if first byte was received */ + BIT(listening); /* socket is listening */ + BIT(accepted); /* socket was accepted, not connected */ + BIT(sock_connected); /* socket is "connected", e.g. in UDP */ + BIT(active); + BIT(stats_reported); +}; + +static CURLcode cf_socket_ctx_init(struct cf_socket_ctx *ctx, + struct Curl_peer *peer, + struct Curl_sockaddr_ex *addr, + uint8_t transport) +{ + memset(ctx, 0, sizeof(*ctx)); + Curl_peer_link(&ctx->peer, peer); + ctx->sock = CURL_SOCKET_BAD; + ctx->transport = transport; + ctx->addr = *addr; + +#ifdef DEBUGBUILD + { + const char *p = getenv("CURL_DBG_SOCK_WBLOCK"); + if(p) { + curl_off_t l; + if(!curlx_str_number(&p, &l, 100)) + ctx->wblock_percent = (int)l; + } + p = getenv("CURL_DBG_SOCK_WPARTIAL"); + if(p) { + curl_off_t l; + if(!curlx_str_number(&p, &l, 100)) + ctx->wpartial_percent = (int)l; + } + p = getenv("CURL_DBG_SOCK_RBLOCK"); + if(p) { + curl_off_t l; + if(!curlx_str_number(&p, &l, 100)) + ctx->rblock_percent = (int)l; + } + p = getenv("CURL_DBG_SOCK_RMAX"); + if(p) { + curl_off_t l; + if(!curlx_str_number(&p, &l, CURL_OFF_T_MAX)) + ctx->recv_max = (size_t)l; + } + } +#endif + + return CURLE_OK; +} + +static void cf_socket_ctx_free(struct cf_socket_ctx *ctx) +{ + if(ctx) { + Curl_peer_unlink(&ctx->peer); + curlx_free(ctx); + } +} + +static CURLcode cf_socket_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + if(cf->connected) { + struct cf_socket_ctx *ctx = cf->ctx; + + CURL_TRC_CF(data, cf, "cf_socket_shutdown, fd=%" FMT_SOCKET_T, ctx->sock); + /* On TCP, and when the socket looks well and non-blocking mode + * can be enabled, receive dangling bytes before close to avoid + * entering RST states unnecessarily. */ + if(ctx->sock != CURL_SOCKET_BAD && + ctx->transport == TRNSPRT_TCP && + (curlx_nonblock(ctx->sock, TRUE) >= 0)) { + unsigned char buf[1024]; + (void)sread(ctx->sock, buf, sizeof(buf)); + } + } + *done = TRUE; + return CURLE_OK; +} + +static void cf_socket_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + + CURL_TRC_CF(data, cf, "destroy"); + if(ctx) { + if(ctx->sock != CURL_SOCKET_BAD) { + CURL_TRC_CF(data, cf, "cf_socket_close, fd=%" FMT_SOCKET_T, ctx->sock); + if(ctx->sock == cf->conn->sock[cf->sockindex]) + cf->conn->sock[cf->sockindex] = CURL_SOCKET_BAD; + socket_close(data, cf->conn, !ctx->accepted, ctx->sock); + } + cf_socket_ctx_free(ctx); + } +} + +static void set_local_ip(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + ctx->ip.local_ip[0] = 0; + ctx->ip.local_port = 0; + +#ifdef HAVE_GETSOCKNAME + if((ctx->sock != CURL_SOCKET_BAD) && + !(data->conn->scheme->protocol & CURLPROTO_TFTP)) { + /* TFTP does not connect, so it cannot get the IP like this */ + struct Curl_sockaddr_storage ssloc; + curl_socklen_t slen = sizeof(struct Curl_sockaddr_storage); + + memset(&ssloc, 0, sizeof(ssloc)); + if(getsockname(ctx->sock, (struct sockaddr *)&ssloc, &slen)) { + VERBOSE(char buffer[STRERROR_LEN]); + VERBOSE(int sockerr = SOCKERRNO); + infof(data, "getsockname() failed with errno %d: %s", + sockerr, curlx_strerror(sockerr, buffer, sizeof(buffer))); + } + else { + CURLcode result = sockaddr2string((struct sockaddr *)&ssloc, slen, + ctx->ip.local_ip, &ctx->ip.local_port); + if(result) + infof(data, "ssloc inet_ntop() failed with %d", (int)result); + } + } +#else + (void)data; +#endif +} + +static CURLcode set_remote_ip(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + CURLcode result; + + /* store remote address and port used in this connection attempt */ + ctx->ip.transport = ctx->transport; + result = sockaddr2string(&ctx->addr.curl_sa_addr, + (curl_socklen_t)ctx->addr.addrlen, + ctx->ip.remote_ip, &ctx->ip.remote_port); + if(result) { + ctx->sockerr = SOCKEAFNOSUPPORT; + /* malformed address or bug in inet_ntop, try next address */ + failf(data, "curl_sa_addr inet_ntop() failed with %d", (int)result); + return CURLE_FAILED_INIT; + } + return CURLE_OK; +} + +/* to figure out the type of the socket safely, remove the possibly ORed + bits before comparing */ +static int cf_socktype(int x) +{ +#ifdef SOCK_CLOEXEC + x &= ~SOCK_CLOEXEC; +#endif +#ifdef CURL_USE_SOCK_NONBLOCK + x &= ~SOCK_NONBLOCK; +#endif + return x; +} + +#ifdef _WIN32 +/* Offered by mingw-w64 v10+, MS SDK 8.0/~VS2012+ */ +#ifndef SIO_TCP_INITIAL_RTO +#define SIO_TCP_INITIAL_RTO _WSAIOW(IOC_VENDOR, 17) +#define TCP_INITIAL_RTO_DEFAULT_RTT 0 + +/* !checksrc! disable TYPEDEFSTRUCT 1 */ +typedef struct _TCP_INITIAL_RTO_PARAMETERS { + USHORT Rtt; + UCHAR MaxSynRetransmissions; +} TCP_INITIAL_RTO_PARAMETERS; +#endif /* SIO_TCP_INITIAL_RTO */ + +#ifndef TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS +#define TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS 0xFE /* -2 */ +#endif + +static bool targets_localhost(struct cf_socket_ctx *ctx) +{ + return (((ctx->addr.family == AF_INET) && + !strcmp(ctx->ip.remote_ip, "127.0.0.1")) || + ((ctx->addr.family == AF_INET6) && + !strcmp(ctx->ip.remote_ip, "::1"))); +} + +/* disable TCP SYN retransmissions for localhost connection on Windows to + detect problems faster */ +static void tcplocalhost(struct Curl_cfilter *cf, + curl_socket_t sockfd) +{ + if(targets_localhost(cf->ctx)) { + TCP_INITIAL_RTO_PARAMETERS rto; + DWORD bytes = 0; + memset(&rto, 0, sizeof(rto)); + rto.Rtt = TCP_INITIAL_RTO_DEFAULT_RTT; + rto.MaxSynRetransmissions = TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS; + (void)WSAIoctl(sockfd, SIO_TCP_INITIAL_RTO, &rto, sizeof(rto), + NULL, 0, &bytes, NULL, NULL); + } +} +#else +#define tcplocalhost(x, y) +#endif /* _WIN32 */ + +static CURLcode cf_socket_open(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + int error = 0; + bool isconnected = FALSE; + CURLcode result = CURLE_COULDNT_CONNECT; + bool is_tcp; + + DEBUGASSERT(ctx->sock == CURL_SOCKET_BAD); + ctx->started_at = *Curl_pgrs_now(data); +#ifdef CURL_USE_SOCK_NONBLOCK + /* Do not tuck SOCK_NONBLOCK into socktype when opensocket callback is set + * because we would not know how socktype is about to be used in the + * callback, SOCK_NONBLOCK might get factored out before calling socket(). + */ + if(!data->set.fopensocket) + ctx->addr.socktype |= SOCK_NONBLOCK; +#endif + result = socket_open(data, &ctx->addr, &ctx->sock); +#ifdef CURL_USE_SOCK_NONBLOCK + /* Restore the socktype after the socket is created. */ + if(!data->set.fopensocket) + ctx->addr.socktype &= ~SOCK_NONBLOCK; +#endif + if(result) + goto out; + + result = set_remote_ip(cf, data); + if(result) + goto out; + +#ifdef USE_IPV6 + if(ctx->addr.family == AF_INET6) { +#ifdef USE_WINSOCK + /* Turn on support for IPv4-mapped IPv6 addresses. + * Linux kernel, NetBSD, FreeBSD, Darwin, lwIP: default is off; + * Windows Vista and later: default is on; + * DragonFly BSD: acts like off, and dummy setting; + * OpenBSD and earlier Windows: unsupported. + * Linux: controlled by /proc/sys/net/ipv6/bindv6only. + */ + int on = 0; + (void)setsockopt(ctx->sock, IPPROTO_IPV6, IPV6_V6ONLY, + (void *)&on, sizeof(on)); +#endif +#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID + { + struct sockaddr_in6 *sa6 = (void *)&ctx->addr.curl_sa_addr; + if(sa6->sin6_scope_id) + infof(data, " Trying [%s]:%d scope_id=%lu...", + ctx->ip.remote_ip, ctx->ip.remote_port, + (unsigned long)sa6->sin6_scope_id); + else +#endif + infof(data, " Trying [%s]:%d...", + ctx->ip.remote_ip, ctx->ip.remote_port); +#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID + } +#endif + } + else +#endif + infof(data, " Trying %s:%d...", ctx->ip.remote_ip, ctx->ip.remote_port); + +#ifdef USE_IPV6 + is_tcp = (ctx->addr.family == AF_INET || + ctx->addr.family == AF_INET6) && + cf_socktype(ctx->addr.socktype) == SOCK_STREAM; +#else + is_tcp = (ctx->addr.family == AF_INET) && + cf_socktype(ctx->addr.socktype) == SOCK_STREAM; +#endif + if(is_tcp) { + if(data->set.tcp_nodelay) + tcpnodelay(cf, data, ctx->sock); + + if(data->set.tcp_keepalive) + tcpkeepalive(cf, data, ctx->sock); + + tcplocalhost(cf, ctx->sock); + } + + if(data->set.fsockopt) { + /* activate callback for setting socket options */ + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_fsockopt); + error = data->set.fsockopt(data->set.sockopt_client, + ctx->sock, + CURLSOCKTYPE_IPCXN); + CURL_CBAPI_END(&guard); + + if(error == CURL_SOCKOPT_ALREADY_CONNECTED) + isconnected = TRUE; + else if(error) { + result = CURLE_ABORTED_BY_CALLBACK; + goto out; + } + } + +#ifndef CURL_DISABLE_BINDLOCAL + /* possibly bind the local end to an IP, interface or port */ + if(ctx->addr.family == AF_INET +#ifdef USE_IPV6 + || ctx->addr.family == AF_INET6 +#endif + ) { + result = bindlocal(data, cf->conn, ctx->sock, ctx->addr.family, + Curl_ipv6_scope(&ctx->addr.curl_sa_addr), + ctx->transport); + if(result) { + if(result == CURLE_UNSUPPORTED_PROTOCOL) { + /* The address family is not supported on this interface. + We can continue trying addresses */ + result = CURLE_COULDNT_CONNECT; + } + goto out; + } + } +#endif + +#ifndef CURL_USE_SOCK_NONBLOCK + /* Set socket non-blocking, must be a non-blocking socket for + * a non-blocking connect. */ + error = curlx_nonblock(ctx->sock, TRUE); + if(error < 0) { + result = CURLE_UNSUPPORTED_PROTOCOL; + ctx->sockerr = SOCKERRNO; + goto out; + } +#else + if(data->set.fopensocket) { + /* Set socket non-blocking, must be a non-blocking socket for + * a non-blocking connect. */ + error = curlx_nonblock(ctx->sock, TRUE); + if(error < 0) { + result = CURLE_UNSUPPORTED_PROTOCOL; + ctx->sockerr = SOCKERRNO; + goto out; + } + } +#endif + ctx->sock_connected = (cf_socktype(ctx->addr.socktype) != SOCK_DGRAM); +out: + if(result) { + if(ctx->sock != CURL_SOCKET_BAD) { + socket_close(data, cf->conn, TRUE, ctx->sock); + ctx->sock = CURL_SOCKET_BAD; + } + } + else if(isconnected) { + set_local_ip(cf, data); + ctx->connected_at = *Curl_pgrs_now(data); + cf->connected = TRUE; + } + CURL_TRC_CF(data, cf, "cf_socket_open() -> %d, fd=%" FMT_SOCKET_T, + (int)result, ctx->sock); + return result; +} + +static int do_connect(struct Curl_cfilter *cf, struct Curl_easy *data, + bool is_tcp_fastopen) +{ + struct cf_socket_ctx *ctx = cf->ctx; +#ifdef TCP_FASTOPEN_CONNECT + int optval = 1; +#endif + int rc = -1; + + (void)data; + if(is_tcp_fastopen) { +#ifdef CONNECT_DATA_IDEMPOTENT /* Darwin */ +# ifdef HAVE_BUILTIN_AVAILABLE + /* while connectx function is available since macOS 10.11 / iOS 9, + it did not have the interface declared correctly until + Xcode 9 / macOS SDK 10.13 */ + if(__builtin_available(macOS 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *)) { + sa_endpoints_t endpoints; + endpoints.sae_srcif = 0; + endpoints.sae_srcaddr = NULL; + endpoints.sae_srcaddrlen = 0; + endpoints.sae_dstaddr = &ctx->addr.curl_sa_addr; + endpoints.sae_dstaddrlen = ctx->addr.addrlen; + + rc = connectx(ctx->sock, &endpoints, SAE_ASSOCID_ANY, + CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT, + NULL, 0, NULL, NULL); + } + else { + rc = connect(ctx->sock, &ctx->addr.curl_sa_addr, ctx->addr.addrlen); + } +# else + rc = connect(ctx->sock, &ctx->addr.curl_sa_addr, ctx->addr.addrlen); +# endif /* HAVE_BUILTIN_AVAILABLE */ +#elif defined(TCP_FASTOPEN_CONNECT) /* Linux >= 4.11 */ + if(setsockopt(ctx->sock, IPPROTO_TCP, TCP_FASTOPEN_CONNECT, + (void *)&optval, sizeof(optval)) < 0) + CURL_TRC_CF(data, cf, "Failed to enable TCP Fast Open on fd %" + FMT_SOCKET_T, ctx->sock); + + rc = connect(ctx->sock, &ctx->addr.curl_sa_addr, ctx->addr.addrlen); +#elif defined(MSG_FASTOPEN) /* old Linux */ + if(Curl_conn_is_ssl(cf->conn, cf->sockindex)) + rc = connect(ctx->sock, &ctx->addr.curl_sa_addr, ctx->addr.addrlen); + else + rc = 0; /* Do nothing */ +#endif + } + else { + rc = connect(ctx->sock, &ctx->addr.curl_sa_addr, + (curl_socklen_t)ctx->addr.addrlen); + } + return rc; +} + +static CURLcode cf_tcp_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_socket_ctx *ctx = cf->ctx; + CURLcode result = CURLE_COULDNT_CONNECT; + int rc = 0; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; /* a negative world view is best */ + if(ctx->sock == CURL_SOCKET_BAD) { + int sockerr; + + result = cf_socket_open(cf, data); + if(result) + goto out; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* Connect TCP socket */ + rc = do_connect(cf, data, (bool)cf->conn->bits.tcp_fastopen); + sockerr = SOCKERRNO; + set_local_ip(cf, data); + CURL_TRC_CF(data, cf, "local address %s port %d...", + ctx->ip.local_ip, ctx->ip.local_port); + if(rc == -1) { + ctx->sockerr = sockerr; + result = socket_connect_result(data, ctx->ip.remote_ip, sockerr); + goto out; + } + } + +#ifdef mpeix + /* Call this function once now, and ignore the results. We do this to + "clear" the error state on the socket so that we can later read it + reliably. This is reported necessary on the MPE/iX operating + system. */ + (void)verifyconnect(ctx->sock, NULL); +#endif + /* check socket for connect */ + rc = SOCKET_WRITABLE(ctx->sock, 0); + + if(rc == 0) { /* no connection yet */ + CURL_TRC_CF(data, cf, "not connected yet on fd=%" FMT_SOCKET_T, ctx->sock); + return CURLE_OK; + } + else if(rc == CURL_CSELECT_OUT || cf->conn->bits.tcp_fastopen) { + if(verifyconnect(ctx->sock, &ctx->sockerr)) { + /* we are connected with TCP, awesome! */ + ctx->connected_at = *Curl_pgrs_now(data); + set_local_ip(cf, data); + *done = TRUE; + cf->connected = TRUE; + CURL_TRC_CF(data, cf, "connected on fd=%" FMT_SOCKET_T, ctx->sock); + return CURLE_OK; + } + } + else if(rc & CURL_CSELECT_ERR) { + CURL_TRC_CF(data, cf, "poll/select error on fd=%" FMT_SOCKET_T, ctx->sock); + (void)verifyconnect(ctx->sock, &ctx->sockerr); + result = CURLE_COULDNT_CONNECT; + } + +out: + if(result) { + VERBOSE(char buffer[STRERROR_LEN]); + set_local_ip(cf, data); + if(ctx->sockerr) { + data->state.os_errno = ctx->sockerr; + SET_SOCKERRNO(ctx->sockerr); + VERBOSE(curlx_strerror(ctx->sockerr, buffer, sizeof(buffer))); + } + else { + VERBOSE(curlx_strcopy(buffer, sizeof(buffer), STRCONST("peer closed"))); + } + if(ctx->sock != CURL_SOCKET_BAD) { + socket_close(data, cf->conn, TRUE, ctx->sock); + ctx->sock = CURL_SOCKET_BAD; + } + infof(data, "connect to %s port %u from %s port %d failed: %s", + ctx->ip.remote_ip, ctx->ip.remote_port, + ctx->ip.local_ip, ctx->ip.local_port, + curlx_strerror(ctx->sockerr, buffer, sizeof(buffer))); + *done = FALSE; + } + return result; +} + +static CURLcode cf_socket_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_socket_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(ctx->sock != CURL_SOCKET_BAD) { + /* A listening socket filter needs to be connected before the accept + * for some weird FTP interaction. This should be rewritten, so that + * FTP no longer does the socket checks and accept calls and delegates + * all that to the filter. */ + if(ctx->listening) { + result = Curl_pollset_set_in_only(data, ps, ctx->sock); + CURL_TRC_CF(data, cf, "adjust_pollset, listening, POLLIN fd=%" + FMT_SOCKET_T, ctx->sock); + } + else if(!cf->connected) { + result = Curl_pollset_set_out_only(data, ps, ctx->sock); + CURL_TRC_CF(data, cf, "adjust_pollset, !connected, POLLOUT fd=%" + FMT_SOCKET_T, ctx->sock); + } + else if(!ctx->active) { + result = Curl_pollset_add_in(data, ps, ctx->sock); + CURL_TRC_CF(data, cf, "adjust_pollset, !active, POLLIN fd=%" + FMT_SOCKET_T, ctx->sock); + } + } + return result; +} + +#ifdef USE_WINSOCK + +/* Offered by mingw-w64 v13+, MS SDK 7.0A/VS2010+ */ +#ifndef SIO_IDEAL_SEND_BACKLOG_QUERY +#define SIO_IDEAL_SEND_BACKLOG_QUERY 0x4004747B +#endif + +static void win_update_sndbuf_size(struct Curl_easy *data, + struct cf_socket_ctx *ctx) +{ + ULONG ideal; + DWORD ideallen; + + if(curlx_ptimediff_ms(Curl_pgrs_now(data), + &ctx->last_sndbuf_query_at) > 1000) { + if(!WSAIoctl(ctx->sock, SIO_IDEAL_SEND_BACKLOG_QUERY, 0, 0, + &ideal, sizeof(ideal), &ideallen, 0, 0) && + ideal != ctx->sndbuf_size && + !setsockopt(ctx->sock, SOL_SOCKET, SO_SNDBUF, + (const char *)&ideal, sizeof(ideal))) { + ctx->sndbuf_size = ideal; + } + ctx->last_sndbuf_query_at = *Curl_pgrs_now(data); + } +} + +#endif /* USE_WINSOCK */ + +static CURLcode cf_socket_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const uint8_t *buf, size_t len, bool eos, + size_t *pnwritten) +{ + struct cf_socket_ctx *ctx = cf->ctx; + curl_socket_t fdsave; + ssize_t rv; + CURLcode result = CURLE_OK; + VERBOSE(size_t orig_len = len); + + (void)eos; + *pnwritten = 0; + fdsave = cf->conn->sock[cf->sockindex]; + cf->conn->sock[cf->sockindex] = ctx->sock; + +#ifdef DEBUGBUILD + /* simulate network blocking/partial writes */ + if(ctx->wblock_percent > 0) { + unsigned char c = 0; + Curl_rand_bytes(data, FALSE, &c, 1); + if(c >= ((100 - ctx->wblock_percent) * 256 / 100)) { + CURL_TRC_CF(data, cf, "send(len=%zu) SIMULATE EWOULDBLOCK", orig_len); + cf->conn->sock[cf->sockindex] = fdsave; + return CURLE_AGAIN; + } + } + if(cf->cft != &Curl_cft_udp && ctx->wpartial_percent > 0 && len > 8) { + len = len * ctx->wpartial_percent / 100; + if(!len) + len = 1; + CURL_TRC_CF(data, cf, "send(len=%zu) SIMULATE partial write of %zu bytes", + orig_len, len); + } +#endif + +#if defined(MSG_FASTOPEN) && !defined(TCP_FASTOPEN_CONNECT) /* Linux */ + if(cf->conn->bits.tcp_fastopen) { + rv = sendto(ctx->sock, buf, len, MSG_FASTOPEN, + &ctx->addr.curl_sa_addr, ctx->addr.addrlen); + cf->conn->bits.tcp_fastopen = FALSE; + } + else +#endif + rv = swrite(ctx->sock, buf, len); + + if(!curlx_sztouz(rv, pnwritten)) { + int sockerr = SOCKERRNO; + if(SOCK_EAGAIN(sockerr) +#ifndef USE_WINSOCK + || (sockerr == SOCKEINTR) || (sockerr == SOCKEINPROGRESS) +#endif + ) { + result = CURLE_AGAIN; /* EWOULDBLOCK */ + } + else { + char buffer[STRERROR_LEN]; + failf(data, "Send failure: %s", + curlx_strerror(sockerr, buffer, sizeof(buffer))); + data->state.os_errno = sockerr; + result = CURLE_SEND_ERROR; + } + } + +#ifdef USE_WINSOCK + if(!result) + win_update_sndbuf_size(data, ctx); +#endif + + CURL_TRC_CF(data, cf, "send(len=%zu) -> %d, %zu", + orig_len, (int)result, *pnwritten); + cf->conn->sock[cf->sockindex] = fdsave; + return result; +} + +static CURLcode cf_socket_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, size_t *pnread) +{ + struct cf_socket_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + ssize_t rv; + + *pnread = 0; +#ifdef DEBUGBUILD + /* simulate network blocking/partial reads */ + if(cf->cft != &Curl_cft_udp && ctx->rblock_percent > 0) { + unsigned char c = 0; + Curl_rand(data, &c, 1); + if(c >= ((100 - ctx->rblock_percent) * 256 / 100)) { + CURL_TRC_CF(data, cf, "recv(len=%zu) SIMULATE EWOULDBLOCK", len); + return CURLE_AGAIN; + } + } + if(cf->cft != &Curl_cft_udp && ctx->recv_max && ctx->recv_max < len) { + CURL_TRC_CF(data, cf, "recv(len=%zu) SIMULATE max read of %zu bytes", + len, ctx->recv_max); + len = ctx->recv_max; + } +#endif + + rv = sread(ctx->sock, buf, len); + + if(!curlx_sztouz(rv, pnread)) { + int sockerr = SOCKERRNO; + if(SOCK_EAGAIN(sockerr) +#ifndef USE_WINSOCK + || (sockerr == SOCKEINTR) +#endif + ) { + result = CURLE_AGAIN; /* EWOULDBLOCK */ + } + else { + char buffer[STRERROR_LEN]; + failf(data, "Recv failure: %s", + curlx_strerror(sockerr, buffer, sizeof(buffer))); + data->state.os_errno = sockerr; + result = CURLE_RECV_ERROR; + } + } + + CURL_TRC_CF(data, cf, "recv(len=%zu) -> %d, %zu", len, (int)result, *pnread); + if(!result && !ctx->got_first_byte) { + ctx->first_byte_at = *Curl_pgrs_now(data); + ctx->got_first_byte = TRUE; + } + return result; +} + +static void cf_socket_update_data(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + /* Update the IP info held in the transfer, if we have that. */ + if(cf->connected && (cf->sockindex == FIRSTSOCKET)) { + struct cf_socket_ctx *ctx = cf->ctx; + data->info.primary = ctx->ip; + } +} + +static void cf_socket_active(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + + /* use this socket from now on */ + cf->conn->sock[cf->sockindex] = ctx->sock; + set_local_ip(cf, data); +#ifdef USE_IPV6 + if(cf->sockindex == FIRSTSOCKET) + cf->conn->bits.ipv6 = (ctx->addr.family == AF_INET6); +#endif + ctx->active = TRUE; +} + +static CURLcode cf_socket_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + struct cf_socket_ctx *ctx = cf->ctx; + + (void)arg1; + (void)arg2; + switch(event) { + case CF_CTRL_CONN_INFO_UPDATE: + cf_socket_active(cf, data); + cf_socket_update_data(cf, data); + break; + case CF_CTRL_DATA_SETUP: + cf_socket_update_data(cf, data); + break; + case CF_CTRL_FORGET_SOCKET: + ctx->sock = CURL_SOCKET_BAD; + break; + case CF_CTRL_REPORT_STATS: + if(cf->connected && !ctx->stats_reported) { + struct curltime *ts = NULL; + switch(ctx->transport) { + case TRNSPRT_UDP: + case TRNSPRT_QUIC: + /* Since UDP connected sockets work different from TCP, we use the + * time of the first byte from the peer as the "connect" time. */ + if(ctx->got_first_byte) + ts = &ctx->first_byte_at; + break; + default: + ts = &ctx->connected_at; + break; + } + if(ts) { + Curl_pgrsTimeWas(data, TIMER_CONNECT, *ts); + ctx->stats_reported = TRUE; + } + } + } + return CURLE_OK; +} + +static bool cf_socket_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + struct cf_socket_ctx *ctx = cf->ctx; + struct pollfd pfd[1]; + int r; + + *input_pending = FALSE; + + if(!ctx || ctx->sock == CURL_SOCKET_BAD) + return FALSE; + + /* Check with 0 timeout if there are any events pending on the socket */ + pfd[0].fd = ctx->sock; + pfd[0].events = POLLRDNORM | POLLIN | POLLRDBAND | POLLPRI; + pfd[0].revents = 0; + + r = Curl_poll(pfd, 1, 0); + if(r < 0) { + CURL_TRC_CF(data, cf, "is_alive: poll error, assume dead"); + return FALSE; + } + else if(r == 0) { + CURL_TRC_CF(data, cf, "is_alive: poll timeout, assume alive"); + return TRUE; + } + else if(pfd[0].revents & (POLLERR | POLLHUP | POLLPRI | POLLNVAL)) { + CURL_TRC_CF(data, cf, "is_alive: err/hup/etc events, assume dead"); + return FALSE; + } + + CURL_TRC_CF(data, cf, "is_alive: valid events, looks alive"); + *input_pending = TRUE; + return TRUE; +} + +static CURLcode cf_socket_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_socket_ctx *ctx = cf->ctx; + + switch(query) { + case CF_QUERY_SOCKET: + DEBUGASSERT(pres2); + *((curl_socket_t *)pres2) = ctx->sock; + return CURLE_OK; + case CF_QUERY_TRANSPORT: + DEBUGASSERT(pres1); + *pres1 = ctx->transport; + return CURLE_OK; + case CF_QUERY_REMOTE_ADDR: + DEBUGASSERT(pres2); + *((const struct Curl_sockaddr_ex **)pres2) = cf->connected ? + &ctx->addr : NULL; + return CURLE_OK; + case CF_QUERY_CONNECT_REPLY_MS: + if(ctx->got_first_byte) { + timediff_t ms = curlx_ptimediff_ms(&ctx->first_byte_at, + &ctx->started_at); + *pres1 = (ms < INT_MAX) ? (int)ms : INT_MAX; + } + else + *pres1 = -1; + return CURLE_OK; + case CF_QUERY_IP_INFO: +#ifdef USE_IPV6 + *pres1 = (ctx->addr.family == AF_INET6); +#else + *pres1 = FALSE; +#endif + *(struct ip_quadruple *)pres2 = ctx->ip; + return CURLE_OK; + case CF_QUERY_REALLY_CONNECTED: + if(cf->cft != &Curl_cft_udp) + *pres1 = cf->connected; + else + *pres1 = ctx->got_first_byte; + return CURLE_OK; + default: + break; + } + return cf->next ? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +struct Curl_cftype Curl_cft_tcp = { + "TCP", + CF_TYPE_IP_CONNECT, + CURL_LOG_LVL_NONE, + cf_socket_destroy, + cf_tcp_connect, + cf_socket_shutdown, + cf_socket_adjust_pollset, + Curl_cf_def_data_pending, + cf_socket_send, + cf_socket_recv, + cf_socket_cntrl, + cf_socket_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_socket_query, +}; + +CURLcode Curl_cf_tcp_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport) +{ + struct cf_socket_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL; + CURLcode result; + + (void)data; + (void)origin; + (void)conn; + (void)tunnel_peer; + (void)tunnel_transport; + DEBUGASSERT(transport_peer == TRNSPRT_TCP); + if(!addr) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + result = cf_socket_ctx_init(ctx, peer, addr, transport_peer); + if(result) + goto out; + + result = Curl_cf_create(&cf, &Curl_cft_tcp, ctx); + +out: + *pcf = (!result) ? cf : NULL; + if(result) { + curlx_safefree(cf); + cf_socket_ctx_free(ctx); + } + + return result; +} + +#ifdef __linux__ +static void linux_quic_mtu(struct cf_socket_ctx *ctx) +{ + int val; + switch(ctx->addr.family) { +#ifdef IP_MTU_DISCOVER + case AF_INET: + val = IP_PMTUDISC_DO; + (void)setsockopt(ctx->sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, + sizeof(val)); + break; +#endif +#ifdef IPV6_MTU_DISCOVER + case AF_INET6: + val = IPV6_PMTUDISC_DO; + (void)setsockopt(ctx->sock, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &val, + sizeof(val)); + break; +#endif + } +} +#else +#define linux_quic_mtu(x) +#endif + +#if defined(UDP_GRO) && \ + (defined(HAVE_SENDMMSG) || defined(HAVE_SENDMSG)) && \ + ((defined(USE_NGTCP2) && defined(USE_NGHTTP3)) || defined(USE_QUICHE)) +static void linux_quic_gro(struct cf_socket_ctx *ctx) +{ + int one = 1; + (void)setsockopt(ctx->sock, IPPROTO_UDP, UDP_GRO, &one, + (socklen_t)sizeof(one)); +} +#else +#define linux_quic_gro(x) +#endif + +#if (defined(__linux__) || defined(__APPLE__)) && defined(IP_RECVTOS) +static void linux_quic_ecn(struct cf_socket_ctx *ctx) +{ + unsigned int tos = 1; + switch(ctx->addr.family) { + case AF_INET: + (void)setsockopt(ctx->sock, IPPROTO_IP, IP_RECVTOS, &tos, sizeof(tos)); + break; +#ifdef IPV6_RECVTCLASS + case AF_INET6: + (void)setsockopt(ctx->sock, IPPROTO_IPV6, IPV6_RECVTCLASS, + &tos, sizeof(tos)); + break; +#endif + } +} +#else +#define linux_quic_ecn(x) +#endif + +#if (defined(__linux__) || defined(__APPLE__)) && defined(IP_DONTFRAG) +static void linux_ip_dontfrag(struct cf_socket_ctx *ctx) +{ + int val = 1; + + switch(ctx->addr.family) { + case AF_INET: + (void)setsockopt(ctx->sock, IPPROTO_IP, IP_DONTFRAG, &val, sizeof(val)); + break; +#ifdef IPV6_DONTFRAG + case AF_INET6: + (void)setsockopt(ctx->sock, IPPROTO_IPV6, IPV6_DONTFRAG, + &val, sizeof(val)); + break; +#endif + } +} +#else +#define linux_ip_dontfrag(x) +#endif + +static CURLcode cf_udp_setup_quic(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + int rc; + + /* QUIC needs a connected socket, nonblocking */ + DEBUGASSERT(ctx->sock != CURL_SOCKET_BAD); + + /* error: The 1st argument to 'connect' is -1 but should be >= 0 + NOLINTNEXTLINE(clang-analyzer-unix.StdCLibraryFunctions) */ + rc = connect(ctx->sock, &ctx->addr.curl_sa_addr, + (curl_socklen_t)ctx->addr.addrlen); + if(rc == -1) { + return socket_connect_result(data, ctx->ip.remote_ip, SOCKERRNO); + } + ctx->sock_connected = TRUE; + set_local_ip(cf, data); + CURL_TRC_CF(data, cf, "%s socket %" FMT_SOCKET_T + " connected: [%s:%d] -> [%s:%d]", + (ctx->transport == TRNSPRT_QUIC) ? "QUIC" : "UDP", + ctx->sock, ctx->ip.local_ip, ctx->ip.local_port, + ctx->ip.remote_ip, ctx->ip.remote_port); + + /* Currently, cf->ctx->sock is always non-blocking because the only + * caller to cf_udp_setup_quic() is cf_udp_connect() that passes the + * non-blocking socket created by cf_socket_open() to it. Thus, we + * do not need to call curlx_nonblock() in cf_udp_setup_quic() anymore. + */ + linux_quic_ecn(ctx); + linux_quic_mtu(ctx); + linux_ip_dontfrag(ctx); + linux_quic_gro(ctx); + + return CURLE_OK; +} + +static CURLcode cf_udp_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_socket_ctx *ctx = cf->ctx; + CURLcode result = CURLE_COULDNT_CONNECT; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; + if(ctx->sock == CURL_SOCKET_BAD) { + result = cf_socket_open(cf, data); + if(result) { + CURL_TRC_CF(data, cf, "cf_udp_connect(), open failed -> %d", + (int)result); + goto out; + } + + if(ctx->transport == TRNSPRT_QUIC) { + result = cf_udp_setup_quic(cf, data); + if(result) + goto out; + CURL_TRC_CF(data, cf, "cf_udp_connect(), opened socket=%" + FMT_SOCKET_T " (%s:%d)", + ctx->sock, ctx->ip.local_ip, ctx->ip.local_port); + } + *done = TRUE; + cf->connected = TRUE; + } +out: + return result; +} + +struct Curl_cftype Curl_cft_udp = { + "UDP", + CF_TYPE_IP_CONNECT, + CURL_LOG_LVL_NONE, + cf_socket_destroy, + cf_udp_connect, + cf_socket_shutdown, + cf_socket_adjust_pollset, + Curl_cf_def_data_pending, + cf_socket_send, + cf_socket_recv, + cf_socket_cntrl, + cf_socket_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_socket_query, +}; + +CURLcode Curl_cf_udp_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport) +{ + struct cf_socket_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL; + CURLcode result; + + (void)data; + (void)origin; + (void)conn; + (void)tunnel_peer; + (void)tunnel_transport; + DEBUGASSERT(transport_peer == TRNSPRT_UDP || transport_peer == TRNSPRT_QUIC); + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + result = cf_socket_ctx_init(ctx, peer, addr, transport_peer); + if(result) + goto out; + + result = Curl_cf_create(&cf, &Curl_cft_udp, ctx); + +out: + *pcf = (!result) ? cf : NULL; + if(result) { + curlx_safefree(cf); + cf_socket_ctx_free(ctx); + } + + return result; +} + +/* this is the TCP filter which can also handle this case */ +struct Curl_cftype Curl_cft_unix = { + "UNIX", + CF_TYPE_IP_CONNECT, + CURL_LOG_LVL_NONE, + cf_socket_destroy, + cf_tcp_connect, + cf_socket_shutdown, + cf_socket_adjust_pollset, + Curl_cf_def_data_pending, + cf_socket_send, + cf_socket_recv, + cf_socket_cntrl, + cf_socket_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_socket_query, +}; + +CURLcode Curl_cf_unix_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport) +{ + struct cf_socket_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL; + CURLcode result; + + (void)data; + (void)origin; + (void)conn; + (void)tunnel_peer; + (void)tunnel_transport; + DEBUGASSERT(transport_peer == TRNSPRT_UNIX); + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + result = cf_socket_ctx_init(ctx, peer, addr, transport_peer); + if(result) + goto out; + + result = Curl_cf_create(&cf, &Curl_cft_unix, ctx); + +out: + *pcf = (!result) ? cf : NULL; + if(result) { + curlx_safefree(cf); + cf_socket_ctx_free(ctx); + } + + return result; +} + +static timediff_t cf_tcp_accept_timeleft(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; + timediff_t timeout_ms = DEFAULT_ACCEPT_TIMEOUT; + timediff_t other_ms; + +#ifndef CURL_DISABLE_FTP + if(data->set.accepttimeout > 0) + timeout_ms = data->set.accepttimeout; +#endif + + /* check if the generic timeout possibly is set shorter */ + other_ms = Curl_timeleft_ms(data); + if(other_ms && (other_ms < timeout_ms)) + /* note that this also works fine for when other_ms happens to be negative + due to it already having elapsed */ + timeout_ms = other_ms; + else { + /* subtract elapsed time */ + timeout_ms -= curlx_ptimediff_ms(Curl_pgrs_now(data), &ctx->started_at); + if(!timeout_ms) + /* avoid returning 0 as that means no timeout! */ + timeout_ms = -1; + } + return timeout_ms; +} + +static void cf_tcp_set_accepted_remote_ip(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_socket_ctx *ctx = cf->ctx; +#ifdef HAVE_GETPEERNAME + CURLcode result; + struct Curl_sockaddr_storage ssrem; + curl_socklen_t plen; + + ctx->ip.remote_ip[0] = 0; + ctx->ip.remote_port = 0; + plen = sizeof(ssrem); + memset(&ssrem, 0, plen); + if(getpeername(ctx->sock, (struct sockaddr *)&ssrem, &plen)) { + char buffer[STRERROR_LEN]; + int sockerr = SOCKERRNO; + failf(data, "getpeername() failed with errno %d: %s", + sockerr, curlx_strerror(sockerr, buffer, sizeof(buffer))); + return; + } + result = sockaddr2string((struct sockaddr *)&ssrem, plen, + ctx->ip.remote_ip, &ctx->ip.remote_port); + if(result) { + failf(data, "ssrem inet_ntop() failed with %d", (int)result); + return; + } +#else + ctx->ip.remote_ip[0] = 0; + ctx->ip.remote_port = 0; + (void)data; +#endif +} + +static CURLcode cf_tcp_accept_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_socket_ctx *ctx = cf->ctx; + char errbuf[STRERROR_LEN]; +#ifdef USE_IPV6 + struct Curl_sockaddr_storage add; +#else + struct sockaddr_in add; +#endif + curl_socklen_t size = (curl_socklen_t)sizeof(add); + curl_socket_t s_accepted = CURL_SOCKET_BAD; + timediff_t timeout_ms; + int socketstate = 0; + bool incoming = FALSE; + + /* we start accepted, if we ever close, we cannot go on */ + (void)data; + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; + timeout_ms = cf_tcp_accept_timeleft(cf, data); + if(timeout_ms < 0) { + /* if a timeout was already reached, bail out */ + failf(data, "Accept timeout occurred while waiting server connect"); + return CURLE_FTP_ACCEPT_TIMEOUT; + } + + CURL_TRC_CF(data, cf, "Checking for incoming on fd=%" FMT_SOCKET_T + " ip=%s:%d", ctx->sock, ctx->ip.local_ip, ctx->ip.local_port); + socketstate = SOCKET_READABLE(ctx->sock, 0); + CURL_TRC_CF(data, cf, "socket_check -> %x", (unsigned int)socketstate); + switch(socketstate) { + case -1: /* error */ + /* let's die here */ + failf(data, "Error while waiting for server connect"); + return CURLE_FTP_ACCEPT_FAILED; + default: + if(socketstate & CURL_CSELECT_IN) { + infof(data, "Ready to accept data connection from server"); + incoming = TRUE; + } + break; + } + + if(!incoming) { + CURL_TRC_CF(data, cf, "nothing heard from the server yet"); + return CURLE_OK; + } + + size = sizeof(add); +#ifdef HAVE_ACCEPT4 + s_accepted = CURL_ACCEPT4(ctx->sock, (struct sockaddr *)&add, &size, + SOCK_NONBLOCK | SOCK_CLOEXEC); +#else + s_accepted = CURL_ACCEPT(ctx->sock, (struct sockaddr *)&add, &size); +#endif + + if(s_accepted == CURL_SOCKET_BAD) { + failf(data, "Error accept()ing server connect: %s", + curlx_strerror(SOCKERRNO, errbuf, sizeof(errbuf))); + return CURLE_FTP_ACCEPT_FAILED; + } +#ifndef HAVE_ACCEPT4 +#ifdef HAVE_FCNTL + if(fcntl(s_accepted, F_SETFD, FD_CLOEXEC) < 0) { + failf(data, "fcntl set CLOEXEC: %s", + curlx_strerror(SOCKERRNO, errbuf, sizeof(errbuf))); + Curl_socket_close(data, cf->conn, s_accepted); + return CURLE_FTP_ACCEPT_FAILED; + } +#endif /* HAVE_FCNTL */ + if(curlx_nonblock(s_accepted, TRUE) < 0) { + failf(data, "set socket NONBLOCK: %s", + curlx_strerror(SOCKERRNO, errbuf, sizeof(errbuf))); + Curl_socket_close(data, cf->conn, s_accepted); + return CURLE_FTP_ACCEPT_FAILED; + } +#endif /* !HAVE_ACCEPT4 */ + infof(data, "Connection accepted from server"); + + /* Replace any filter on SECONDARY with one listening on this socket */ + ctx->listening = FALSE; + ctx->accepted = TRUE; + socket_close(data, cf->conn, TRUE, ctx->sock); + ctx->sock = s_accepted; + + cf->conn->sock[cf->sockindex] = ctx->sock; + cf_tcp_set_accepted_remote_ip(cf, data); + set_local_ip(cf, data); + ctx->active = TRUE; + ctx->connected_at = *Curl_pgrs_now(data); + cf->connected = TRUE; + CURL_TRC_CF(data, cf, "accepted_set(sock=%" FMT_SOCKET_T + ", remote=%s port=%d)", + ctx->sock, ctx->ip.remote_ip, ctx->ip.remote_port); + + if(data->set.fsockopt) { + struct Curl_mapi_guard guard; + int error = 0; + + /* activate callback for setting socket options */ + CURL_CBAPI_START(&guard, data, easy_fsockopt); + error = data->set.fsockopt(data->set.sockopt_client, + ctx->sock, CURLSOCKTYPE_ACCEPT); + CURL_CBAPI_END(&guard); + + if(error) + return CURLE_ABORTED_BY_CALLBACK; + } + *done = TRUE; + return CURLE_OK; +} + +struct Curl_cftype Curl_cft_tcp_accept = { + "TCP-ACCEPT", + CF_TYPE_IP_CONNECT, + CURL_LOG_LVL_NONE, + cf_socket_destroy, + cf_tcp_accept_connect, + cf_socket_shutdown, + cf_socket_adjust_pollset, + Curl_cf_def_data_pending, + cf_socket_send, + cf_socket_recv, + cf_socket_cntrl, + cf_socket_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_socket_query, +}; + +CURLcode Curl_conn_tcp_listen_set(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, curl_socket_t *s) +{ + CURLcode result; + struct Curl_cfilter *cf = NULL; + struct cf_socket_ctx *ctx = NULL; + + /* replace any existing */ + Curl_conn_cf_discard_all(data, conn, sockindex); + DEBUGASSERT(conn->sock[sockindex] == CURL_SOCKET_BAD); + + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + ctx->transport = TRNSPRT_TCP; + ctx->sock = *s; + ctx->listening = TRUE; + ctx->accepted = FALSE; + result = Curl_cf_create(&cf, &Curl_cft_tcp_accept, ctx); + if(result) + goto out; + Curl_conn_cf_add(data, conn, sockindex, cf); + + ctx->started_at = *Curl_pgrs_now(data); + conn->sock[sockindex] = ctx->sock; + set_local_ip(cf, data); + CURL_TRC_CF(data, cf, "set filter for listen socket fd=%" FMT_SOCKET_T + " ip=%s:%d", ctx->sock, + ctx->ip.local_ip, ctx->ip.local_port); + +out: + if(result) { + curlx_safefree(cf); + curlx_safefree(ctx); + } + return result; +} + +bool Curl_conn_is_tcp_listen(struct Curl_easy *data, + int8_t sockindex) +{ + struct Curl_cfilter *cf = data->conn->cfilter[sockindex]; + while(cf) { + if(cf->cft == &Curl_cft_tcp_accept) + return TRUE; + cf = cf->next; + } + return FALSE; +} + +/** + * Return TRUE iff `cf` is a socket filter. + */ +static bool cf_is_socket(struct Curl_cfilter *cf) +{ + return cf && (cf->cft == &Curl_cft_tcp || + cf->cft == &Curl_cft_udp || + cf->cft == &Curl_cft_unix || + cf->cft == &Curl_cft_tcp_accept); +} + +CURLcode Curl_cf_socket_peek(struct Curl_cfilter *cf, + struct Curl_easy *data, + curl_socket_t *psock, + const struct Curl_sockaddr_ex **paddr, + struct ip_quadruple *pip) +{ + (void)data; + if(cf_is_socket(cf) && cf->ctx) { + struct cf_socket_ctx *ctx = cf->ctx; + + if(psock) + *psock = ctx->sock; + if(paddr) + *paddr = &ctx->addr; + if(pip) + *pip = ctx->ip; + return CURLE_OK; + } + return CURLE_FAILED_INIT; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-socket.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-socket.h new file mode 100644 index 0000000000..f4a6755fe3 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cf-socket.h @@ -0,0 +1,154 @@ +#ifndef HEADER_CURL_CF_SOCKET_H +#define HEADER_CURL_CF_SOCKET_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct Curl_addrinfo; +struct Curl_cfilter; +struct Curl_easy; +struct connectdata; +struct Curl_sockaddr_ex; +struct ip_quadruple; + +#define curl_sa_addr addr.sa +#define curl_sa_addrbuf addr.buf + +/* + * Parse interface option, and return the interface name and the host part. + */ +CURLcode Curl_parse_interface(const char *input, + char **dev, char **iface, char **host); + +CURLcode Curl_socket_addr_from_ai(struct Curl_sockaddr_ex *addr, + const struct Curl_addrinfo *ai, + uint8_t transport); + +/* + * Create a socket based on info from 'conn' and 'ai'. + * + * Fill in 'addr' and 'sockfd' accordingly if OK is returned. If the open + * socket callback is set, used that! + * + */ +CURLcode Curl_socket_open(struct Curl_easy *data, + const struct Curl_addrinfo *ai, + struct Curl_sockaddr_ex *addr, + uint8_t transport, + curl_socket_t *sockfd); + +#ifdef USE_SO_NOSIGPIPE +/* Set SO_NOSIGPIPE on socket, return < 0 on error. */ +int Curl_sock_nosigpipe(curl_socket_t sockfd); +#endif + +int Curl_socket_close(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t sock); + +/** + * Creates a cfilter that opens a TCP socket to the given address + * when calling its `connect` implementation. + * The filter will not touch any connection/data flags and can be + * used in happy eyeballing. Once selected for use, its `_active()` + * method needs to be called. + */ +CURLcode Curl_cf_tcp_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport); + +/** + * Creates a cfilter that opens a UDP socket to the given address + * when calling its `connect` implementation. + * The filter will not touch any connection/data flags and can be + * used in happy eyeballing. Once selected for use, its `_active()` + * method needs to be called. + */ +CURLcode Curl_cf_udp_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport); + +/** + * Creates a cfilter that opens a UNIX socket to the given address + * when calling its `connect` implementation. + * The filter will not touch any connection/data flags and can be + * used in happy eyeballing. Once selected for use, its `_active()` + * method needs to be called. + */ +CURLcode Curl_cf_unix_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport); + +/** + * Creates a cfilter that keeps a listening socket. + */ +CURLcode Curl_conn_tcp_listen_set(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + curl_socket_t *s); + +/** + * Return TRUE iff the last filter at `sockindex` was set via + * Curl_conn_tcp_listen_set(). + */ +bool Curl_conn_is_tcp_listen(struct Curl_easy *data, + int8_t sockindex); + +/** + * Peek at the socket and remote ip/port the socket filter is using. + * The filter owns all returned values. + * @param psock pointer to hold socket descriptor or NULL + * @param paddr pointer to hold addr reference or NULL + * @param pip pointer to get IP quadruple or NULL + * Returns error if the filter is of invalid type. + */ +CURLcode Curl_cf_socket_peek(struct Curl_cfilter *cf, + struct Curl_easy *data, + curl_socket_t *psock, + const struct Curl_sockaddr_ex **paddr, + struct ip_quadruple *pip) WARN_UNUSED_RESULT; + +extern struct Curl_cftype Curl_cft_tcp; +extern struct Curl_cftype Curl_cft_udp; +extern struct Curl_cftype Curl_cft_unix; +extern struct Curl_cftype Curl_cft_tcp_accept; + +#endif /* HEADER_CURL_CF_SOCKET_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cfilters.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cfilters.c new file mode 100644 index 0000000000..6ffa262eb1 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cfilters.c @@ -0,0 +1,1103 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "strerror.h" +#include "cfilters.h" +#include "connect.h" +#include "url.h" +#include "curl_trc.h" +#include "progress.h" +#include "select.h" +#include "curlx/strparse.h" + +CURLcode Curl_cf_def_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + CURLcode result; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + if(cf->next) { + result = cf->next->cft->do_connect(cf->next, data, done); + if(result || !*done) + return result; + } + + cf->connected = TRUE; + *done = TRUE; + return CURLE_OK; +} + +CURLcode Curl_cf_def_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + (void)cf; + (void)data; + *done = TRUE; + return CURLE_OK; +} + +CURLcode Curl_cf_def_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + /* NOP */ + (void)cf; + (void)data; + (void)ps; + return CURLE_OK; +} + +bool Curl_cf_def_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + return cf->next ? + cf->next->cft->has_data_pending(cf->next, data) : FALSE; +} + +CURLcode Curl_cf_def_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const uint8_t *buf, size_t len, bool eos, + size_t *pnwritten) +{ + if(cf->next) + return cf->next->cft->do_send(cf->next, data, buf, len, eos, pnwritten); + *pnwritten = 0; + return CURLE_RECV_ERROR; +} + +CURLcode Curl_cf_def_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, size_t *pnread) +{ + if(cf->next) + return cf->next->cft->do_recv(cf->next, data, buf, len, pnread); + *pnread = 0; + return CURLE_SEND_ERROR; +} + +bool Curl_cf_def_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + return cf->next ? + cf->next->cft->is_alive(cf->next, data, input_pending) : + FALSE; /* pessimistic in absence of data */ +} + +CURLcode Curl_cf_def_conn_keep_alive(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + return cf->next ? + cf->next->cft->keep_alive(cf->next, data) : + CURLE_OK; +} + +CURLcode Curl_cf_def_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + return cf->next ? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +#ifdef CURLVERBOSE +void Curl_conn_trc_filters(struct Curl_easy *data, + int8_t sockindex, const char *info) +{ + if(CURL_TRC_M_is_verbose(data) && data->conn) { + struct Curl_cfilter *cf = data->conn->cfilter[sockindex]; + + if(cf) { + char msg[256], *buf; + int blen, n; + + buf = msg; + blen = sizeof(msg) - 1; + n = curl_msnprintf(buf, blen, "%s [%d]", info, sockindex); + buf += n; + blen -= n; + for(; cf && blen; cf = cf->next) { + n = curl_msnprintf(buf, blen, "[%s%s]", + cf->connected ? "" : "!", cf->cft->name); + buf += n; + blen -= n; + } + CURL_TRC_M(data, "%s%s", msg, blen ? "" : "..."); + } + else + CURL_TRC_M(data, "%s [%d][-]", info, sockindex); + } +} +#endif /* CURLVERBOSE */ + +void Curl_conn_cf_discard_chain(struct Curl_cfilter **pcf, + struct Curl_easy *data) +{ + struct Curl_cfilter *cfn, *cf = *pcf; + + if(cf) { + *pcf = NULL; + while(cf) { + cfn = cf->next; + /* prevent destroying filter to mess with its sub-chain, since + * we have the reference now and will call destroy on it. + */ + cf->next = NULL; + cf->cft->destroy(cf, data); + curlx_free(cf); + cf = cfn; + } + } +} + +void Curl_conn_cf_discard_all(struct Curl_easy *data, + struct connectdata *conn, int8_t sockindex) +{ + struct curltime *pt = &conn->shutdown.start[sockindex]; + memset(pt, 0, sizeof(*pt)); + Curl_conn_cf_discard_chain(&conn->cfilter[sockindex], data); +} + +CURLcode Curl_conn_shutdown(struct Curl_easy *data, + int8_t sockindex, bool *done) +{ + struct Curl_cfilter *cf; + CURLcode result = CURLE_OK; + timediff_t timeout_ms; + + DEBUGASSERT(data->conn); + + if(!CONN_SOCK_IDX_VALID(sockindex)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + /* Get the first connected filter that is not shut down already. */ + cf = data->conn->cfilter[sockindex]; + while(cf && (!cf->connected || cf->shutdown)) + cf = cf->next; + + if(!cf) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; + if(!Curl_shutdown_started(data->conn, sockindex)) { + Curl_shutdown_start(data, sockindex, 0); + } + else { + timeout_ms = Curl_shutdown_timeleft(data, data->conn, sockindex); + if(timeout_ms < 0) { + /* info message, since this might be regarded as acceptable */ + infof(data, "shutdown timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + } + + while(cf) { + if(!cf->shutdown) { + bool cfdone = FALSE; + result = cf->cft->do_shutdown(cf, data, &cfdone); + if(result) { + CURL_TRC_CF(data, cf, "shut down failed with %d", (int)result); + return result; + } + else if(!cfdone) { + CURL_TRC_CF(data, cf, "shut down not done yet"); + return CURLE_OK; + } + CURL_TRC_CF(data, cf, "shut down successfully"); + cf->shutdown = TRUE; + } + cf = cf->next; + } + *done = (!result); + return result; +} + +CURLcode Curl_cf_recv(struct Curl_easy *data, int8_t sockindex, char *buf, + size_t len, size_t *pnread) +{ + struct Curl_cfilter *cf; + + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + cf = data->conn->cfilter[sockindex]; + while(cf && !cf->connected) + cf = cf->next; + if(cf) + return cf->cft->do_recv(cf, data, buf, len, pnread); + failf(data, "recv: no filter connected"); + DEBUGASSERT(0); + *pnread = 0; + return CURLE_FAILED_INIT; +} + +CURLcode Curl_cf_send(struct Curl_easy *data, int8_t sockindex, + const uint8_t *buf, size_t len, bool eos, + size_t *pnwritten) +{ + struct Curl_cfilter *cf; + + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + cf = data->conn->cfilter[sockindex]; + while(cf && !cf->connected) + cf = cf->next; + if(cf) { + return cf->cft->do_send(cf, data, buf, len, eos, pnwritten); + } + failf(data, "send: no filter connected"); + DEBUGASSERT(0); + *pnwritten = 0; + return CURLE_FAILED_INIT; +} + +struct cf_io_ctx { + struct Curl_easy *data; + struct Curl_cfilter *cf; +}; + +static CURLcode cf_bufq_reader(void *writer_ctx, + unsigned char *buf, size_t blen, + size_t *pnread) +{ + struct cf_io_ctx *io = writer_ctx; + return Curl_conn_cf_recv(io->cf, io->data, (char *)buf, blen, pnread); +} + +CURLcode Curl_cf_recv_bufq(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct bufq *bufq, + size_t maxlen, + size_t *pnread) +{ + struct cf_io_ctx io; + + if(!cf || !data) { + *pnread = 0; + return CURLE_BAD_FUNCTION_ARGUMENT; + } + io.data = data; + io.cf = cf; + return Curl_bufq_sipn(bufq, maxlen, cf_bufq_reader, &io, pnread); +} + +static CURLcode cf_bufq_writer(void *writer_ctx, + const uint8_t *buf, size_t buflen, + size_t *pnwritten) +{ + struct cf_io_ctx *io = writer_ctx; + return Curl_conn_cf_send(io->cf, io->data, buf, buflen, FALSE, pnwritten); +} + +CURLcode Curl_cf_send_bufq(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct bufq *bufq, + const unsigned char *buf, size_t blen, + size_t *pnwritten) +{ + struct cf_io_ctx io; + + if(!cf || !data) { + *pnwritten = 0; + return CURLE_BAD_FUNCTION_ARGUMENT; + } + io.data = data; + io.cf = cf; + if(buf && blen) + return Curl_bufq_write_pass(bufq, buf, blen, cf_bufq_writer, &io, + pnwritten); + else + return Curl_bufq_pass(bufq, cf_bufq_writer, &io, pnwritten); +} + +CURLcode Curl_cf_create(struct Curl_cfilter **pcf, + const struct Curl_cftype *cft, + void *ctx) +{ + struct Curl_cfilter *cf; + CURLcode result = CURLE_OUT_OF_MEMORY; + + DEBUGASSERT(cft); + cf = curlx_calloc(1, sizeof(*cf)); + if(!cf) + goto out; + + cf->cft = cft; + cf->ctx = ctx; + result = CURLE_OK; +out: + *pcf = cf; + return result; +} + +void Curl_conn_cf_add(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + struct Curl_cfilter *cf) +{ + DEBUGASSERT(conn); + DEBUGASSERT(!cf->conn); + DEBUGASSERT(!cf->next); + + cf->next = conn->cfilter[sockindex]; + cf->conn = conn; + cf->sockindex = sockindex; + conn->cfilter[sockindex] = cf; + CURL_TRC_CF(data, cf, "added"); +} + +void Curl_conn_cf_insert_after(struct Curl_cfilter *cf_at, + struct Curl_cfilter *cf_new) +{ + struct Curl_cfilter *tail, **pnext; + + DEBUGASSERT(cf_at); + DEBUGASSERT(cf_new); + DEBUGASSERT(!cf_new->conn); + + tail = cf_at->next; + cf_at->next = cf_new; + do { + cf_new->conn = cf_at->conn; + cf_new->sockindex = cf_at->sockindex; + pnext = &cf_new->next; + cf_new = cf_new->next; + } while(cf_new); + *pnext = tail; +} + +bool Curl_conn_cf_discard(struct Curl_cfilter **pcf, + struct Curl_easy *data) +{ + struct Curl_cfilter *cf = pcf ? *pcf : NULL; + bool found = FALSE; + if(cf) { + if(cf->conn) { + /* unlink if present in connection filter chain */ + struct Curl_cfilter **pprev = &cf->conn->cfilter[cf->sockindex]; + while(*pprev) { + if(*pprev == *pcf) { + *pprev = (*pcf)->next; + cf->next = NULL; + found = TRUE; + break; + } + pprev = &(*pprev)->next; + } + } + Curl_conn_cf_discard_chain(pcf, data); + } + return found; +} + +CURLcode Curl_conn_cf_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + if(cf) + return cf->cft->do_connect(cf, data, done); + return CURLE_FAILED_INIT; +} + +CURLcode Curl_conn_cf_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const uint8_t *buf, size_t len, bool eos, + size_t *pnwritten) +{ + if(cf) + return cf->cft->do_send(cf, data, buf, len, eos, pnwritten); + *pnwritten = 0; + return CURLE_SEND_ERROR; +} + +CURLcode Curl_conn_cf_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, size_t *pnread) +{ + if(cf) + return cf->cft->do_recv(cf, data, buf, len, pnread); + *pnread = 0; + return CURLE_RECV_ERROR; +} + +static CURLcode cf_cntrl_all(struct connectdata *conn, + struct Curl_easy *data, + bool ignore_result, + int event, int arg1, void *arg2) +{ + CURLcode result = CURLE_OK; + int i; + + for(i = 0; i < (int)CURL_ARRAYSIZE(conn->cfilter); ++i) { + result = Curl_conn_cf_cntrl(conn->cfilter[i], data, ignore_result, + event, arg1, arg2); + if(!ignore_result && result) + break; + } + return result; +} + +bool Curl_conn_cf_is_ip_connected(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + if(cf) { + int value = 0; + if(!cf->cft->query(cf, data, CF_QUERY_REALLY_CONNECTED, &value, NULL)) + return !!value; + } + return FALSE; +} + +void Curl_conn_cntrl_update_info(struct Curl_easy *data, + struct connectdata *conn) +{ + cf_cntrl_all(conn, data, TRUE, CF_CTRL_CONN_INFO_UPDATE, 0, NULL); +} + +void Curl_conn_cntrl_report_stats(struct Curl_easy *data, + struct connectdata *conn, + int sockindex) +{ + if((unsigned)sockindex < CURL_ARRAYSIZE(conn->cfilter)) + (void)Curl_conn_cf_cntrl(conn->cfilter[sockindex], data, TRUE, + CF_CTRL_REPORT_STATS, 0, NULL); +} + +void Curl_conn_remove_setup_filters(struct Curl_easy *data, + int8_t sockindex) +{ + struct Curl_cfilter **anchor = &data->conn->cfilter[sockindex]; + while(*anchor) { + struct Curl_cfilter *cf = *anchor; + if(cf->connected && (cf->cft->flags & CF_TYPE_SETUP)) { + *anchor = cf->next; + cf->next = NULL; + CURL_TRC_CF(data, cf, "removing connected setup filter"); + cf->cft->destroy(cf, data); + curlx_free(cf); + } + else + anchor = &cf->next; + } +} + +bool Curl_conn_is_setup(struct connectdata *conn, int8_t sockindex) +{ + if(!CONN_SOCK_IDX_VALID(sockindex)) + return FALSE; + return !!conn->cfilter[sockindex]; +} + +bool Curl_conn_is_connected(struct connectdata *conn, int8_t sockindex) +{ + struct Curl_cfilter *cf; + + if(!CONN_SOCK_IDX_VALID(sockindex)) + return FALSE; + cf = conn->cfilter[sockindex]; + if(cf) + return (bool)cf->connected; + else if(conn->scheme->flags & PROTOPT_NONETWORK) + return TRUE; + return FALSE; +} + +bool Curl_conn_is_ip_connected(struct Curl_easy *data, int8_t sockindex) +{ + struct Curl_cfilter *cf; + + if(!CONN_SOCK_IDX_VALID(sockindex)) + return FALSE; + cf = data->conn->cfilter[sockindex]; + while(cf) { + if(cf->connected) + return TRUE; + if(cf->cft->flags & CF_TYPE_IP_CONNECT) + return FALSE; + cf = cf->next; + } + return FALSE; +} + +#ifndef CURL_DISABLE_PROXY +static bool cf_is_tunneling(struct Curl_cfilter *cf) +{ + for(; cf; cf = cf->next) { + if((cf->cft->flags & CF_TYPE_PROXY)) + return TRUE; + } + return FALSE; +} + +bool Curl_conn_is_tunneling(struct connectdata *conn, int8_t sockindex) +{ + if(!CONN_SOCK_IDX_VALID(sockindex)) + return FALSE; + return conn ? cf_is_tunneling(conn->cfilter[sockindex]) : FALSE; +} +#else +bool Curl_conn_is_tunneling(struct connectdata *conn, int8_t sockindex) +{ + (void)conn; + (void)sockindex; + return FALSE; +} +#endif /* CURL_DISABLE_PROXY */ + +static bool cf_is_ssl(struct Curl_cfilter *cf) +{ + for(; cf; cf = cf->next) { + /* A tunneling proxy does not offer end2end encryption, even if + * it does SSL itself (e.g. QUIC H3 proxy) */ + if((cf->cft->flags & CF_TYPE_SSL) && !(cf->cft->flags & CF_TYPE_PROXY)) + return TRUE; + if(cf->cft->flags & CF_TYPE_IP_CONNECT) + return FALSE; + } + return FALSE; +} + +bool Curl_conn_is_ssl(struct connectdata *conn, int8_t sockindex) +{ + if(!CONN_SOCK_IDX_VALID(sockindex)) + return FALSE; + return conn ? cf_is_ssl(conn->cfilter[sockindex]) : FALSE; +} + +bool Curl_conn_get_ssl_info(struct Curl_easy *data, + struct connectdata *conn, int8_t sockindex, + int query, + struct curl_tlssessioninfo *info) +{ + if(!CONN_SOCK_IDX_VALID(sockindex)) + return FALSE; + if(Curl_conn_is_ssl(conn, sockindex)) { + struct Curl_cfilter *cf = conn->cfilter[sockindex]; + CURLcode result = cf ? + cf->cft->query(cf, data, query, NULL, (void *)info) : + CURLE_UNKNOWN_OPTION; + return !result; + } + return FALSE; +} + +CURLcode Curl_conn_get_ip_info(struct Curl_easy *data, + struct connectdata *conn, int8_t sockindex, + bool *is_ipv6, struct ip_quadruple *ipquad) +{ + struct Curl_cfilter *cf; + if(!CONN_SOCK_IDX_VALID(sockindex)) + return CURLE_BAD_FUNCTION_ARGUMENT; + cf = conn ? conn->cfilter[sockindex] : NULL; + return Curl_conn_cf_get_ip_info(cf, data, is_ipv6, ipquad); +} + +bool Curl_conn_is_multiplex(struct connectdata *conn, int8_t sockindex) +{ + struct Curl_cfilter *cf; + + if(!conn || !CONN_SOCK_IDX_VALID(sockindex)) + return FALSE; + for(cf = conn->cfilter[sockindex]; cf; cf = cf->next) { + if(cf->cft->flags & CF_TYPE_MULTIPLEX) + return TRUE; + if(cf->cft->flags & (CF_TYPE_IP_CONNECT | CF_TYPE_SSL)) + return FALSE; + } + return FALSE; +} + +unsigned char Curl_conn_get_transport(struct Curl_easy *data, + struct connectdata *conn) +{ + struct Curl_cfilter *cf = conn->cfilter[FIRSTSOCKET]; + return Curl_conn_cf_get_transport(cf, data); +} + +int Curl_socktype_for_transport(uint8_t transport) +{ + switch(transport) { + case TRNSPRT_TCP: + return SOCK_STREAM; + case TRNSPRT_UNIX: + return SOCK_STREAM; + default: /* UDP and QUIC */ + return SOCK_DGRAM; + } +} + +int Curl_protocol_for_transport(uint8_t transport) +{ + switch(transport) { + case TRNSPRT_TCP: + return IPPROTO_TCP; + case TRNSPRT_UNIX: + return IPPROTO_IP; + default: /* UDP and QUIC */ + return IPPROTO_UDP; + } +} + +const char *Curl_conn_get_alpn_negotiated(struct Curl_easy *data, + struct connectdata *conn) +{ + struct Curl_cfilter *cf = conn->cfilter[FIRSTSOCKET]; + return Curl_conn_cf_get_alpn_negotiated(cf, data); +} + +unsigned char Curl_conn_http_version(struct Curl_easy *data, + struct connectdata *conn) +{ + struct Curl_cfilter *cf; + CURLcode result = CURLE_UNKNOWN_OPTION; + unsigned char v = 0; + + cf = conn->cfilter[FIRSTSOCKET]; + for(; cf; cf = cf->next) { + if(cf->cft->flags & CF_TYPE_HTTP) { + int value = 0; + result = cf->cft->query(cf, data, CF_QUERY_HTTP_VERSION, &value, NULL); + if(!result && ((value < 0) || (value > 255))) + result = CURLE_FAILED_INIT; + else + v = (unsigned char)value; + break; + } + if(cf->cft->flags & (CF_TYPE_IP_CONNECT | CF_TYPE_SSL)) + break; + } + return (unsigned char)(result ? 0 : v); +} + +bool Curl_conn_data_pending(struct Curl_easy *data, int8_t sockindex) +{ + struct Curl_cfilter *cf; + + (void)data; + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + if(!CONN_SOCK_IDX_VALID(sockindex)) + return FALSE; + + cf = data->conn->cfilter[sockindex]; + while(cf && !cf->connected) { + cf = cf->next; + } + if(cf) { + return cf->cft->has_data_pending(cf, data); + } + return FALSE; +} + +bool Curl_conn_cf_needs_flush(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURLcode result; + int pending = 0; + result = cf ? cf->cft->query(cf, data, CF_QUERY_NEED_FLUSH, + &pending, NULL) : CURLE_UNKNOWN_OPTION; + return (result || !pending) ? FALSE : TRUE; +} + +bool Curl_conn_needs_flush(struct Curl_easy *data, int8_t sockindex) +{ + if(!CONN_SOCK_IDX_VALID(sockindex)) + return FALSE; + return Curl_conn_cf_needs_flush(data->conn->cfilter[sockindex], data); +} + +CURLcode Curl_conn_cf_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + CURLcode result = CURLE_OK; + /* Go through all filters, top to bottom, and let them manage the pollset + * - connected filters can do so + * - CF_TYPE_DNS filters can + * - unconnected filters without next or connect next can + */ + for(; cf && !result; cf = cf->next) { + if(cf->shutdown) + continue; + if(cf->connected || (cf->cft->flags & CF_TYPE_DNS) || + !cf->next || cf->next->connected) + result = cf->cft->adjust_pollset(cf, data, ps); + } + return result; +} + +CURLcode Curl_conn_adjust_pollset(struct Curl_easy *data, + struct connectdata *conn, + struct easy_pollset *ps) +{ + CURLcode result = CURLE_OK; + bool want_io = !!ps->n; + int8_t i; + + DEBUGASSERT(data); + DEBUGASSERT(conn); + /* During connect time, connection filters may add sockets to the pollset + * even when the transfer neither wants to send nor receive. And those + * sockets, when having events, are served. The same applies to a + * filter chain whose shutdown has started. + * Once a filter chain is connected however and before its shutdown + * starts, a transfer that neither wants to send nor receive + * will never call the connection filters. Any sockets added by the filters + * will not change state and POLLIN/POLLOUT events will trigger forever, + * making us busy loop. See #21671. + * Gate each filter chain on its own state, so that one chain being in + * connect or shutdown does not add poll events for the other. Check + * against the transfer's own interest, before any chain added sockets + * of its own. */ + for(i = 0; (i < (int)CURL_ARRAYSIZE(conn->cfilter)) && !result; ++i) { + if(conn->cfilter[i] && + (want_io || !Curl_conn_is_connected(conn, i) || + Curl_shutdown_started(conn, i))) + result = Curl_conn_cf_adjust_pollset(conn->cfilter[i], data, ps); + } + return result; +} + +/* + * Return values: + * -1 = error + * 0 = timeout + * N = number of structures with non zero revent fields + */ +int Curl_conn_cf_poll(struct Curl_cfilter *cf, + struct Curl_easy *data, + timediff_t timeout_ms) +{ + struct easy_pollset ps; + int rc; + CURLcode result; + + DEBUGASSERT(cf); + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + Curl_pollset_init(&ps); + + result = Curl_conn_cf_adjust_pollset(cf, data, &ps); + if(!result) + rc = Curl_pollset_poll(data, &ps, timeout_ms); + else + rc = -1; + Curl_pollset_cleanup(&ps); + return rc; +} + +void Curl_conn_get_current_host(struct Curl_easy *data, int8_t sockindex, + const char **phost, int *pport) +{ + struct Curl_cfilter *cf, *cf_proxy = NULL; + int portarg = -1; + + if(!data->conn) { + DEBUGASSERT(0); + *phost = ""; + if(pport) + *pport = -1; + return; + } + + cf = CONN_SOCK_IDX_VALID(sockindex) ? data->conn->cfilter[sockindex] : NULL; + /* Find the "lowest" tunneling proxy filter that has not connected yet. */ + while(cf && !cf->connected) { + if((cf->cft->flags & (CF_TYPE_IP_CONNECT | CF_TYPE_PROXY)) == + (CF_TYPE_IP_CONNECT | CF_TYPE_PROXY)) + cf_proxy = cf; + cf = cf->next; + } + /* cf_proxy (!= NULL) is not connected yet. It is talking + * to an interim host and any authentication or other things apply + * to this interim host and port. */ + if(!cf_proxy || cf_proxy->cft->query(cf_proxy, data, CF_QUERY_HOST_PORT, + &portarg, CURL_UNCONST(phost))) { + /* Everything connected or query unsuccessful, the overall + * connection's destination is the answer */ + *phost = data->conn->origin->hostname; + portarg = data->conn->origin->port; + } + if(pport) + *pport = portarg; +} + +CURLcode Curl_cf_def_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + (void)cf; + (void)data; + (void)event; + (void)arg1; + (void)arg2; + return CURLE_OK; +} + +CURLcode Curl_conn_cf_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool ignore_result, + int event, int arg1, void *arg2) +{ + CURLcode result = CURLE_OK; + + for(; cf; cf = cf->next) { + if(cf->cft->cntrl == Curl_cf_def_cntrl) + continue; + result = cf->cft->cntrl(cf, data, event, arg1, arg2); + if(!ignore_result && result) + break; + } + return result; +} + +curl_socket_t Curl_conn_cf_get_socket(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + curl_socket_t sock; + if(cf && !cf->cft->query(cf, data, CF_QUERY_SOCKET, NULL, &sock)) + return sock; + return CURL_SOCKET_BAD; +} + +unsigned char Curl_conn_cf_get_transport(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + int transport = 0; + if(cf && !cf->cft->query(cf, data, CF_QUERY_TRANSPORT, &transport, NULL)) + return (unsigned char)transport; + return (unsigned char)(data->conn ? data->conn->transport_wanted : 0); +} + +const char *Curl_conn_cf_get_alpn_negotiated(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + const char *alpn = NULL; + CURL_TRC_CF(data, cf, "query ALPN"); + if(cf && !cf->cft->query(cf, data, CF_QUERY_ALPN_NEGOTIATED, NULL, + CURL_UNCONST(&alpn))) + return alpn; + return NULL; +} + +static const struct Curl_sockaddr_ex *cf_get_remote_addr( + struct Curl_cfilter *cf, struct Curl_easy *data) +{ + const struct Curl_sockaddr_ex *remote_addr = NULL; + if(cf && + !cf->cft->query(cf, data, CF_QUERY_REMOTE_ADDR, NULL, + CURL_UNCONST(&remote_addr))) + return remote_addr; + return NULL; +} + +CURLcode Curl_conn_cf_get_ip_info(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *is_ipv6, struct ip_quadruple *ipquad) +{ + CURLcode result = CURLE_UNKNOWN_OPTION; + if(cf) { + int ipv6 = 0; + result = cf->cft->query(cf, data, CF_QUERY_IP_INFO, &ipv6, ipquad); + *is_ipv6 = !!ipv6; + } + return result; +} + +curl_socket_t Curl_conn_get_first_socket(struct Curl_easy *data) +{ + struct Curl_cfilter *cf; + + if(!data->conn) + return CURL_SOCKET_BAD; + + cf = data->conn->cfilter[FIRSTSOCKET]; + /* if the top filter has not connected, ask it (and its sub-filters) + * for the socket. Otherwise conn->sock[sockindex] should have it. */ + if(cf && !cf->connected) + return Curl_conn_cf_get_socket(cf, data); + return data->conn->sock[FIRSTSOCKET]; +} + +const struct Curl_sockaddr_ex *Curl_conn_get_remote_addr( + struct Curl_easy *data, int8_t sockindex) +{ + struct Curl_cfilter *cf = + (data->conn && CONN_SOCK_IDX_VALID(sockindex)) ? + data->conn->cfilter[sockindex] : NULL; + return cf ? cf_get_remote_addr(cf, data) : NULL; +} + +CURLcode Curl_conn_ev_data_setup(struct Curl_easy *data) +{ + return cf_cntrl_all(data->conn, data, FALSE, CF_CTRL_DATA_SETUP, 0, NULL); +} + +CURLcode Curl_conn_flush(struct Curl_easy *data, int8_t sockindex) +{ + if(!CONN_SOCK_IDX_VALID(sockindex)) + return CURLE_BAD_FUNCTION_ARGUMENT; + return Curl_conn_cf_cntrl(data->conn->cfilter[sockindex], data, FALSE, + CF_CTRL_FLUSH, 0, NULL); +} + +/** + * Notify connection filters that the transfer represented by `data` + * is done with sending data (e.g. has uploaded everything). + */ +void Curl_conn_ev_data_done_send(struct Curl_easy *data) +{ + cf_cntrl_all(data->conn, data, TRUE, CF_CTRL_DATA_DONE_SEND, 0, NULL); +} + +/** + * Notify connection filters that the transfer represented by `data` + * is finished - eventually premature, e.g. before being complete. + */ +void Curl_conn_ev_data_done(struct Curl_easy *data, bool premature) +{ + cf_cntrl_all(data->conn, data, TRUE, CF_CTRL_DATA_DONE, premature, NULL); +} + +CURLcode Curl_conn_ev_data_pause(struct Curl_easy *data, bool do_pause) +{ + return cf_cntrl_all(data->conn, data, FALSE, + CF_CTRL_DATA_PAUSE, do_pause, NULL); +} + +bool Curl_conn_is_alive(struct Curl_easy *data, struct connectdata *conn, + bool *input_pending) +{ + struct Curl_cfilter *cf = conn->cfilter[FIRSTSOCKET]; + return cf && !cf->conn->bits.close && + cf->cft->is_alive(cf, data, input_pending); +} + +CURLcode Curl_conn_keep_alive(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + int i; + + for(i = 0; (i < (int)CURL_ARRAYSIZE(conn->cfilter)) && !result; ++i) { + struct Curl_cfilter *cf = conn->cfilter[i]; + if(cf) + result = cf->cft->keep_alive(cf, data); + } + return result; +} + +size_t Curl_conn_get_max_concurrent(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex) +{ + struct Curl_cfilter *cf; + CURLcode result; + int n = -1; + + if(!CONN_SOCK_IDX_VALID(sockindex)) + return 0; + + cf = conn->cfilter[sockindex]; + result = cf ? cf->cft->query(cf, data, CF_QUERY_MAX_CONCURRENT, + &n, NULL) : CURLE_UNKNOWN_OPTION; + /* If no filter answered the query, the default is a non-multiplexed + * connection with limit 1. Otherwise, the query may return 0 + * for connections that are in shutdown, e.g. server HTTP/2 GOAWAY. */ + return (result || n < 0) ? 1 : (size_t)n; +} + +int Curl_conn_get_stream_error(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex) +{ + struct Curl_cfilter *cf; + CURLcode result; + int n = 0; + + if(!CONN_SOCK_IDX_VALID(sockindex)) + return 0; + + cf = conn->cfilter[sockindex]; + result = cf ? cf->cft->query(cf, data, CF_QUERY_STREAM_ERROR, + &n, NULL) : CURLE_UNKNOWN_OPTION; + return (result || n < 0) ? 0 : n; +} + +int8_t Curl_conn_sockindex(struct Curl_easy *data, curl_socket_t sockfd) +{ + if(data && data->conn && + sockfd != CURL_SOCKET_BAD && sockfd == data->conn->sock[SECONDARYSOCKET]) + return SECONDARYSOCKET; + return FIRSTSOCKET; +} + +CURLcode Curl_conn_recv(struct Curl_easy *data, int8_t sockindex, + char *buf, size_t len, size_t *pnread) +{ + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + if(!CONN_SOCK_IDX_VALID(sockindex)) + return CURLE_BAD_FUNCTION_ARGUMENT; + if(data && data->conn && data->conn->recv[sockindex]) + return data->conn->recv[sockindex](data, sockindex, buf, len, pnread); + *pnread = 0; + return CURLE_FAILED_INIT; +} + +CURLcode Curl_conn_send(struct Curl_easy *data, int8_t sockindex, + const void *buf, size_t len, bool eos, + size_t *pnwritten) +{ + size_t write_len = len; + + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + DEBUGASSERT(CONN_SOCK_IDX_VALID(sockindex)); + if(!CONN_SOCK_IDX_VALID(sockindex)) + return CURLE_BAD_FUNCTION_ARGUMENT; +#ifdef DEBUGBUILD + if(write_len) { + /* Allow debug builds to override this logic to force short sends */ + const char *p = getenv("CURL_SMALLSENDS"); + if(p) { + curl_off_t altsize; + if(!curlx_str_number(&p, &altsize, write_len)) { + write_len = (size_t)altsize; + if(write_len != len) + eos = FALSE; + } + } + } +#endif + if(data && data->conn && data->conn->send[sockindex]) + return data->conn->send[sockindex](data, sockindex, buf, write_len, eos, + pnwritten); + *pnwritten = 0; + return CURLE_FAILED_INIT; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cfilters.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cfilters.h new file mode 100644 index 0000000000..979275b729 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cfilters.h @@ -0,0 +1,700 @@ +#ifndef HEADER_CURL_CFILTERS_H +#define HEADER_CURL_CFILTERS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curlx/timediff.h" + +struct bufq; +struct Curl_cfilter; +struct Curl_easy; +struct Curl_dns_entry; +struct connectdata; +struct ip_quadruple; +struct curl_tlssessioninfo; + +/* Callback to destroy resources held by this filter instance. + * Implementations MUST NOT chain calls to cf->next. + */ +typedef void Curl_cft_destroy_this(struct Curl_cfilter *cf, + struct Curl_easy *data); + +/* Callback to close the connection filter gracefully, non-blocking. + * Implementations MUST NOT chain calls to cf->next. + */ +typedef CURLcode Curl_cft_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done); + +typedef CURLcode Curl_cft_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done); + +struct easy_pollset; + +/* Passing in an easy_pollset for monitoring of sockets, let + * filters add or remove sockets actions (CURL_POLL_OUT, CURL_POLL_IN). + * This may add a socket or, in case no actions remain, remove + * a socket from the set. + * + * Filter implementations need to call filters "below" *after* they have + * made their adjustments. This allows lower filters to override "upper" + * actions. If a "lower" filter is unable to write, it needs to be able + * to disallow POLL_OUT. + * + * A filter without own restrictions/preferences should not modify + * the pollset. Filters, whose filter "below" is not connected, should + * also do no adjustments. + * + * Examples: a TLS handshake, while ongoing, might remove POLL_IN when it + * needs to write, or vice versa. An HTTP/2 filter might remove POLL_OUT when + * a stream window is exhausted and a WINDOW_UPDATE needs to be received first + * and add instead POLL_IN. + * + * @param cf the filter to ask + * @param data the easy handle the pollset is about + * @param ps the pollset (inout) for the easy handle + */ +typedef CURLcode Curl_cft_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps); + +typedef bool Curl_cft_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data); + +typedef CURLcode Curl_cft_send(struct Curl_cfilter *cf, + struct Curl_easy *data, /* transfer */ + const uint8_t *buf, /* data to write */ + size_t len, /* amount to write */ + bool eos, /* last chunk */ + size_t *pnwritten); /* how much sent */ + +typedef CURLcode Curl_cft_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, /* transfer */ + char *buf, /* store data here */ + size_t len, /* amount to read */ + size_t *pnread); /* how much received */ + +typedef bool Curl_cft_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending); + +typedef CURLcode Curl_cft_conn_keep_alive(struct Curl_cfilter *cf, + struct Curl_easy *data); + +/** + * Events/controls for connection filters, their arguments and + * return code handling. Filter callbacks are invoked "top down". + * Return code handling: + * "first fail" meaning that the first filter returning != CURLE_OK, will + * abort further event distribution and determine the result. + * "ignored" meaning return values are ignored and the event is distributed + * to all filters in the chain. Overall result is always CURLE_OK. + */ +/* data event arg1 arg2 return */ +#define CF_CTRL_DATA_SETUP 4 /* 0 NULL first fail */ +/* unused now 5 */ +#define CF_CTRL_DATA_PAUSE 6 /* on/off NULL first fail */ +#define CF_CTRL_DATA_DONE 7 /* premature NULL ignored */ +#define CF_CTRL_DATA_DONE_SEND 8 /* 0 NULL ignored */ +/* update conn info at connection and data */ +#define CF_CTRL_CONN_INFO_UPDATE (256 + 0) /* 0 NULL ignored */ +#define CF_CTRL_FORGET_SOCKET (256 + 1) /* 0 NULL ignored */ +#define CF_CTRL_FLUSH (256 + 2) /* 0 NULL first fail */ +#define CF_CTRL_REPORT_STATS (256 + 3) /* 0 NULL ignored */ + +/** + * Handle event/control for the filter. + * Implementations MUST NOT chain calls to cf->next. + */ +typedef CURLcode Curl_cft_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2); + +/** + * Queries to ask via a `Curl_cft_query *query` method on a cfilter chain. + * - MAX_CONCURRENT: the maximum number of parallel transfers the filter + * chain expects to handle at the same time. + * default: 1 if no filter overrides. + * - CONNECT_REPLY_MS: milliseconds until the first indication of a server + * response was received on a connect. For TCP, this + * reflects the time until the socket connected. On UDP + * this gives the time the first bytes from the server + * were received. + * -1 if not determined yet. + * - CF_QUERY_SOCKET: the socket used by the filter chain + * - CF_QUERY_NEED_FLUSH: TRUE iff any of the filters have unsent data + * - CF_QUERY_IP_INFO: res1 says if connection used IPv6, res2 is the + * ip quadruple + * - CF_QUERY_HOST_PORT: the remote hostname and port a filter talks to + * - CF_QUERY_SSL_INFO: fill out the passed curl_tlssessioninfo with the + * internal from the SSL secured connection when + * available. + * - CF_QUERY_SSL_CTX_INFO: same as CF_QUERY_SSL_INFO, but give the SSL_CTX + * when available, or the same internal pointer + * when the TLS stack does not differentiate. + * - CF_QUERY_ALPN_NEGOTIATED: The ALPN selected by the server as + null-terminated string or NULL if none + selected/handshake not done. Implemented by filter + types CF_TYPE_SSL or CF_TYPE_IP_CONNECT. + * - CF_QUERY_REALLY_CONNECTED: implemented in socket filters to return + * if a reply from a server has really arrived. For + * non-UDP sockets this is TRUE when the socket became + * writable. For UDP sockets, this is TRUE when the + * first byte from the peer was received. + */ +/* query res1 res2 */ +#define CF_QUERY_MAX_CONCURRENT 1 /* number - */ +#define CF_QUERY_CONNECT_REPLY_MS 2 /* number - */ +#define CF_QUERY_SOCKET 3 /* - curl_socket_t */ +/* unused 4 + 5 */ +#define CF_QUERY_STREAM_ERROR 6 /* error code - */ +#define CF_QUERY_NEED_FLUSH 7 /* TRUE/FALSE - */ +#define CF_QUERY_IP_INFO 8 /* TRUE/FALSE struct ip_quadruple */ +#define CF_QUERY_HTTP_VERSION 9 /* number (10/11/20/30) - */ +/* pass in a `const struct Curl_sockaddr_ex **` as `pres2`. Gets set + * to NULL when not connected. */ +#define CF_QUERY_REMOTE_ADDR 10 /* - `Curl_sockaddr_ex *` */ +#define CF_QUERY_HOST_PORT 11 /* port const char * */ +#define CF_QUERY_SSL_INFO 12 /* - struct curl_tlssessioninfo * */ +#define CF_QUERY_SSL_CTX_INFO 13 /* - struct curl_tlssessioninfo * */ +#define CF_QUERY_TRANSPORT 14 /* TRNSPRT_* - * */ +#define CF_QUERY_ALPN_NEGOTIATED 15 /* - const char * */ +#define CF_QUERY_REALLY_CONNECTED 16 /* TRUE/FALSE - */ + +/** + * Query the cfilter for properties. Filters ignorant of a query will + * pass it "down" the filter chain. + */ +typedef CURLcode Curl_cft_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2); + +/** + * Type flags for connection filters. A filter can have none, one or + * many of those. Use to evaluate state/capabilities of a filter chain. + * + * CF_TYPE_IP_CONNECT: provides an IP connection or sth equivalent, like + * a CONNECT tunnel, a UNIX domain socket, a QUIC + * connection, etc. + * CF_TYPE_SSL: provide SSL/TLS + * CF_TYPE_MULTIPLEX: provides multiplexing of easy handles + * CF_TYPE_PROXY provides proxying + * CF_TYPE_HTTP implement a version of the HTTP protocol + * CF_TYPE_SETUP filter is only needed for connection setup and + * can be removed once connected + * CF_TYPE_DNS filter managing DNS resolve operations + */ +#define CF_TYPE_IP_CONNECT (1 << 0) +#define CF_TYPE_SSL (1 << 1) +#define CF_TYPE_MULTIPLEX (1 << 2) +#define CF_TYPE_PROXY (1 << 3) +#define CF_TYPE_HTTP (1 << 4) +#define CF_TYPE_SETUP (1 << 5) +#define CF_TYPE_DNS (1 << 6) + +/* A connection filter type, e.g. specific implementation. */ +struct Curl_cftype { + const char *name; /* name of the filter type */ + int flags; /* flags of filter type */ + int log_level; /* log level for such filters */ + Curl_cft_destroy_this *destroy; /* destroy resources of this cf */ + Curl_cft_connect *do_connect; /* establish connection */ + Curl_cft_shutdown *do_shutdown; /* shutdown conn */ + Curl_cft_adjust_pollset *adjust_pollset; /* adjust transfer poll set */ + Curl_cft_data_pending *has_data_pending; /* conn has data pending */ + Curl_cft_send *do_send; /* send data */ + Curl_cft_recv *do_recv; /* receive data */ + Curl_cft_cntrl *cntrl; /* events/control */ + Curl_cft_conn_is_alive *is_alive; /* FALSE if conn is dead, Jim! */ + Curl_cft_conn_keep_alive *keep_alive; /* try to keep it alive */ + Curl_cft_query *query; /* query filter chain */ +}; + +/* A connection filter instance, e.g. registered at a connection */ +struct Curl_cfilter { + const struct Curl_cftype *cft; /* the type providing implementation */ + struct Curl_cfilter *next; /* next filter in chain */ + void *ctx; /* filter type specific settings */ + struct connectdata *conn; /* the connection this filter belongs to */ + int8_t sockindex; /* the index the filter is installed at */ + BIT(connected); /* != 0 iff this filter is connected */ + BIT(shutdown); /* != 0 iff this filter has shut down */ +}; + +/* Default implementations for the type functions, implementing nop. */ +void Curl_cf_def_destroy_this(struct Curl_cfilter *cf, + struct Curl_easy *data); + +/* Default implementations for the type functions, implementing pass-through + * the filter chain. */ +CURLcode Curl_cf_def_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps); +bool Curl_cf_def_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data); +CURLcode Curl_cf_def_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const uint8_t *buf, size_t len, bool eos, + size_t *pnwritten); +CURLcode Curl_cf_def_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, size_t *pnread); +CURLcode Curl_cf_def_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2); +bool Curl_cf_def_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending); +CURLcode Curl_cf_def_conn_keep_alive(struct Curl_cfilter *cf, + struct Curl_easy *data); +CURLcode Curl_cf_def_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2); +CURLcode Curl_cf_def_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done); +CURLcode Curl_cf_def_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done); + +/** + * Create a new filter instance, unattached to the filter chain. + * Use Curl_conn_cf_add() to add it to the chain. + * @param pcf on success holds the created instance + * @param cft the filter type + * @param ctx the type specific context to use + */ +CURLcode Curl_cf_create(struct Curl_cfilter **pcf, + const struct Curl_cftype *cft, + void *ctx); + +/** + * Add a filter instance to the `sockindex` filter chain at connection + * `conn`. The filter must not already be attached. It is inserted at + * the start of the chain (top). + */ +void Curl_conn_cf_add(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + struct Curl_cfilter *cf); + +/** + * Insert a filter (chain) after `cf_at`. + * `cf_new` must not already be attached. + */ +void Curl_conn_cf_insert_after(struct Curl_cfilter *cf_at, + struct Curl_cfilter *cf_new); + +/** + * Extract filter `*pcf` from its connection filter chain. + * Destroy `*pcf`, even if it was not part of the chain and NULL it. + * Returns TRUE of cf has been part of chain. + */ +bool Curl_conn_cf_discard(struct Curl_cfilter **pcf, + struct Curl_easy *data); + +/** + * Discard all cfilters starting with `*pcf` and clearing it afterwards. + */ +void Curl_conn_cf_discard_chain(struct Curl_cfilter **pcf, + struct Curl_easy *data); + +/** + * Remove and destroy all filters at chain `sockindex` on connection `conn`. + */ +void Curl_conn_cf_discard_all(struct Curl_easy *data, + struct connectdata *conn, int8_t sockindex); + +CURLcode Curl_conn_cf_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done); +CURLcode Curl_conn_cf_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const uint8_t *buf, size_t len, bool eos, + size_t *pnwritten); +CURLcode Curl_conn_cf_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, size_t *pnread); +CURLcode Curl_conn_cf_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool ignore_result, + int event, int arg1, void *arg2); + +/** + * Get the socket used by the filter chain starting at `cf`. + * Returns CURL_SOCKET_BAD if not available. + */ +curl_socket_t Curl_conn_cf_get_socket(struct Curl_cfilter *cf, + struct Curl_easy *data); + +CURLcode Curl_conn_cf_get_ip_info(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *is_ipv6, struct ip_quadruple *ipquad); + +bool Curl_conn_cf_needs_flush(struct Curl_cfilter *cf, + struct Curl_easy *data); + +bool Curl_conn_cf_is_ip_connected(struct Curl_cfilter *cf, + struct Curl_easy *data); + +unsigned char Curl_conn_cf_get_transport(struct Curl_cfilter *cf, + struct Curl_easy *data); + +int Curl_socktype_for_transport(uint8_t transport); +int Curl_protocol_for_transport(uint8_t transport); + +const char *Curl_conn_cf_get_alpn_negotiated(struct Curl_cfilter *cf, + struct Curl_easy *data); + +#define CURL_CF_SSL_DEFAULT (-1) +#define CURL_CF_SSL_DISABLE 0 +#define CURL_CF_SSL_ENABLE 1 + +/** + * Check if a filter chain at `sockindex` for connection `conn` exists. + */ +bool Curl_conn_is_setup(struct connectdata *conn, int8_t sockindex); + +/** + * Check if the filter chain at `sockindex` for connection `conn` is + * completely connected. + */ +bool Curl_conn_is_connected(struct connectdata *conn, int8_t sockindex); + +/** + * Determine if we have reached the remote host on IP level, e.g. + * have a TCP connection. This turns TRUE before a possible SSL + * handshake has been started/done. + */ +bool Curl_conn_is_ip_connected(struct Curl_easy *data, int8_t sockindex); + +/** + * Determine if the connection is using SSL to the remote host + * (or will be once connected). This will return FALSE, if SSL + * is only used in proxying and not for the tunnel itself. + */ +bool Curl_conn_is_ssl(struct connectdata *conn, int8_t sockindex); + +/* Determine if the connection has one or more proxy filters. + * e.g. is tunneling. */ +bool Curl_conn_is_tunneling(struct connectdata *conn, int8_t sockindex); + +/* + * Fill `info` with information about the TLS instance securing the connection + * when available, otherwise e.g. when Curl_conn_is_ssl() is FALSE, return + * FALSE. 'query' should be CF_QUERY_SSL_INFO or CF_QUERY_SSL_CTX_INFO. + */ +bool Curl_conn_get_ssl_info(struct Curl_easy *data, + struct connectdata *conn, int8_t sockindex, + int query, + struct curl_tlssessioninfo *info); + +CURLcode Curl_conn_get_ip_info(struct Curl_easy *data, + struct connectdata *conn, int8_t sockindex, + bool *is_ipv6, struct ip_quadruple *ipquad); + +/** + * Connection provides multiplexing of easy handles at `socketindex`. + */ +bool Curl_conn_is_multiplex(struct connectdata *conn, int8_t sockindex); + +/** + * Return the HTTP version used on the FIRSTSOCKET connection filters + * or 0 if unknown. Value otherwise is 09, 10, 11, etc. + */ +unsigned char Curl_conn_http_version(struct Curl_easy *data, + struct connectdata *conn); + +/* Get the TRNSPRT_* the connection is using */ +unsigned char Curl_conn_get_transport(struct Curl_easy *data, + struct connectdata *conn); + +/* Get the negotiated ALPN protocol or NULL if none in play */ +const char *Curl_conn_get_alpn_negotiated(struct Curl_easy *data, + struct connectdata *conn); + +void Curl_conn_cntrl_update_info(struct Curl_easy *data, + struct connectdata *conn); + +void Curl_conn_cntrl_report_stats(struct Curl_easy *data, + struct connectdata *conn, + int sockindex); + +void Curl_conn_remove_setup_filters(struct Curl_easy *data, + int8_t sockindex); + +/** + * Shutdown the connection at `sockindex` non-blocking, using timeout + * from `data->set.shutdowntimeout`, default DEFAULT_SHUTDOWN_TIMEOUT_MS. + * Return CURLE_OK and *done == FALSE if not finished. + */ +CURLcode Curl_conn_shutdown(struct Curl_easy *data, + int8_t sockindex, bool *done); + +/** + * Return if data is pending in some connection filter at chain + * `sockindex` for connection `data->conn`. + */ +bool Curl_conn_data_pending(struct Curl_easy *data, + int8_t sockindex); + +/** + * Return TRUE if any of the connection filters at chain `sockindex` + * have data still to send. + */ +bool Curl_conn_needs_flush(struct Curl_easy *data, int8_t sockindex); + +/** + * Flush any pending data on the connection filters at chain `sockindex`. + */ +CURLcode Curl_conn_flush(struct Curl_easy *data, int8_t sockindex); + +/** + * Return the socket used on data's connection for FIRSTSOCKET, + * querying filters if the whole chain has not connected yet. + * Returns CURL_SOCKET_BAD if not available. + */ +curl_socket_t Curl_conn_get_first_socket(struct Curl_easy *data); + +/* Return a pointer to the connected socket address or NULL. */ +const struct Curl_sockaddr_ex * +Curl_conn_get_remote_addr(struct Curl_easy *data, int8_t sockindex); + +/** + * Tell filters to forget about the socket at sockindex. + */ +void Curl_conn_forget_socket(struct Curl_easy *data, int8_t sockindex); + +/** + * Adjust the pollset for the filter chain starting at `cf`. + */ +CURLcode Curl_conn_cf_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps); + +/** + * Adjust pollset from filters installed at transfer's connection. + */ +CURLcode Curl_conn_adjust_pollset(struct Curl_easy *data, + struct connectdata *conn, + struct easy_pollset *ps); + +/** + * Curl_poll() the filter chain at `cf` with timeout `timeout_ms`. + * Returns 0 on timeout, negative on error or number of sockets + * with requested poll events. + */ +int Curl_conn_cf_poll(struct Curl_cfilter *cf, + struct Curl_easy *data, + timediff_t timeout_ms); + +/** + * Receive data through the filter chain at `sockindex` for connection + * `data->conn`. Copy at most `len` bytes into `buf`. Return the + * actual number of bytes copied in `*pnread`or an error. + */ +CURLcode Curl_cf_recv(struct Curl_easy *data, int8_t sockindex, char *buf, + size_t len, size_t *pnread); + +/** + * Send `len` bytes of data from `buf` through the filter chain `sockindex` + * at connection `data->conn`. Return the actual number of bytes written + * in `*pnwritten` or on error. + */ +CURLcode Curl_cf_send(struct Curl_easy *data, int8_t sockindex, + const uint8_t *buf, size_t len, bool eos, + size_t *pnwritten); + +/** + * Receive bytes from connection filter `cf` into `bufq`. + * Convenience wrapper around `Curl_bufq_sipn()`, + * so users do not have to implement a callback. + */ +CURLcode Curl_cf_recv_bufq(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct bufq *bufq, + size_t maxlen, + size_t *pnread); + +/** + * Send bytes in `bufq` using connection filter `cf`. + * A convenience wrapper around `Curl_bufq_write_pass()`, + * so users do not have to implement a callback. + */ +CURLcode Curl_cf_send_bufq(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct bufq *bufq, + const unsigned char *buf, size_t blen, + size_t *pnwritten); + +/** + * Notify connection filters that they need to setup data for + * a transfer. + */ +CURLcode Curl_conn_ev_data_setup(struct Curl_easy *data); + +/** + * Notify connection filters that the transfer represented by `data` + * is done with sending data (e.g. has uploaded everything). + */ +void Curl_conn_ev_data_done_send(struct Curl_easy *data); + +/** + * Notify connection filters that the transfer represented by `data` + * is finished - eventually premature, e.g. before being complete. + */ +void Curl_conn_ev_data_done(struct Curl_easy *data, bool premature); + +/** + * Notify connection filters that the transfer of data is paused/unpaused. + */ +CURLcode Curl_conn_ev_data_pause(struct Curl_easy *data, bool do_pause); + +/** + * Check if FIRSTSOCKET's cfilter chain deems connection alive. + */ +bool Curl_conn_is_alive(struct Curl_easy *data, struct connectdata *conn, + bool *input_pending); + +/** + * Try to upkeep the connection filters. + */ +CURLcode Curl_conn_keep_alive(struct Curl_easy *data, + struct connectdata *conn); + +/** + * Get the remote hostname and port that the connection is currently + * talking to (or will talk to). + * Once connected or before connect starts, + * it is `conn->origin->hostname` and `conn->origin->port`. + * During connect, when tunneling proxies are involved (http or socks), + * it will be the name and port the proxy currently negotiates with. + */ +void Curl_conn_get_current_host(struct Curl_easy *data, int8_t sockindex, + const char **phost, int *pport); + +/** + * Get the maximum number of parallel transfers the connection + * expects to be able to handle at `sockindex`. + */ +size_t Curl_conn_get_max_concurrent(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex); + +/** + * Get the underlying error code for a transfer stream or 0 if not known. + */ +int Curl_conn_get_stream_error(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex); + +#ifdef CURLVERBOSE +void Curl_conn_trc_filters(struct Curl_easy *data, + int8_t sockindex, const char *info); +#endif + +/** + * Get the index of the given socket in the connection's sockets. + * Useful in calling `Curl_conn_send()/Curl_conn_recv()` with the + * correct socket index. + */ +int8_t Curl_conn_sockindex(struct Curl_easy *data, curl_socket_t sockfd); + +/* + * Receive data on the connection, using FIRSTSOCKET/SECONDARYSOCKET. + * Return CURLE_AGAIN iff blocked on receiving. + */ +CURLcode Curl_conn_recv(struct Curl_easy *data, int8_t sockindex, + char *buf, size_t len, size_t *pnread); + +/* + * Send data on the connection, using FIRSTSOCKET/SECONDARYSOCKET. + * Return CURLE_AGAIN iff blocked on sending. + */ +CURLcode Curl_conn_send(struct Curl_easy *data, int8_t sockindex, + const void *buf, size_t len, bool eos, + size_t *pnwritten); + +/** + * Types and macros used to keep the current easy handle in filter calls, + * allowing for nested invocations. See #10336. + * + * `cf_call_data` is intended to be a member of the cfilter's `ctx` type. + * A filter defines the macro `CF_CTX_CALL_DATA` to give access to that. + * + * With all values 0, the default, this indicates that there is no cfilter + * call with `data` ongoing. + * Macro `CF_DATA_SAVE` preserves the current `cf_call_data` in a local + * variable and sets the `data` given, incrementing the `depth` counter. + * + * Macro `CF_DATA_RESTORE` restores the old values from the local variable, + * while checking that `depth` values are as expected (debug build), catching + * cases where a "lower" RESTORE was not called. + * + * Finally, macro `CF_DATA_CURRENT` gives the easy handle of the current + * invocation. + */ +struct cf_call_data { + struct Curl_easy *data; +#ifdef DEBUGBUILD + int depth; +#endif +}; + +/** + * define to access the `struct cf_call_data for a cfilter. Normally + * a member in the cfilter's `ctx`. + * + * #define CF_CTX_CALL_DATA(cf) -> struct cf_call_data instance + */ + +#ifdef DEBUGBUILD + +#define CF_DATA_SAVE(save, cf, data) \ + do { \ + (save) = CF_CTX_CALL_DATA(cf); \ + DEBUGASSERT(!(save).data || (save).depth > 0); \ + CF_CTX_CALL_DATA(cf).depth++; \ + CF_CTX_CALL_DATA(cf).data = (struct Curl_easy *)CURL_UNCONST(data); \ + } while(0) + +#define CF_DATA_RESTORE(cf, save) \ + do { \ + DEBUGASSERT(CF_CTX_CALL_DATA(cf).depth == (save).depth + 1); \ + DEBUGASSERT(!(save).data || (save).depth > 0); \ + CF_CTX_CALL_DATA(cf) = (save); \ + } while(0) + +#else /* DEBUGBUILD */ + +#define CF_DATA_SAVE(save, cf, data) \ + do { \ + (save) = CF_CTX_CALL_DATA(cf); \ + CF_CTX_CALL_DATA(cf).data = (struct Curl_easy *)CURL_UNCONST(data); \ + } while(0) + +#define CF_DATA_RESTORE(cf, save) \ + do { \ + CF_CTX_CALL_DATA(cf) = (save); \ + } while(0) + +#endif /* !DEBUGBUILD */ + +#define CF_DATA_CURRENT(cf) ((cf) ? (CF_CTX_CALL_DATA(cf).data) : NULL) + +#endif /* HEADER_CURL_CFILTERS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/config-mac.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/config-mac.h new file mode 100644 index 0000000000..1e88ca35d8 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/config-mac.h @@ -0,0 +1,83 @@ +#ifndef HEADER_CURL_CONFIG_MAC_H +#define HEADER_CURL_CONFIG_MAC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* =================================================================== */ +/* Handcrafted config file for Mac OS 9 */ +/* =================================================================== */ +/* On macOS you must run configure to generate curl_config.h file */ +/* =================================================================== */ + +#ifndef CURL_OS +#define CURL_OS "mac" +#endif + +#include <ConditionalMacros.h> + +/* Define if you want the built-in manual */ +#define USE_MANUAL 1 + +#define HAVE_NETINET_IN_H 1 +#define HAVE_NETDB_H 1 +#define HAVE_ARPA_INET_H 1 +#define HAVE_UNISTD_H 1 +#define HAVE_NET_IF_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_GETTIMEOFDAY 1 +#define HAVE_FCNTL_H 1 +#define HAVE_UTIME_H 1 +#define HAVE_SYS_UTIME_H 1 +#define HAVE_SYS_IOCTL_H 1 +#define HAVE_ALARM 1 +#define HAVE_UTIME 1 +#define HAVE_SOCKET 1 +#define HAVE_STRUCT_TIMEVAL 1 + +#define HAVE_SIGACTION 1 + +#define CURL_DISABLE_LDAP + +#define HAVE_IOCTL_FIONBIO 1 + +#define SIZEOF_INT 4 +#define SIZEOF_LONG 4 +#define SIZEOF_SIZE_T 4 +#define SIZEOF_CURL_OFF_T 8 + +#define HAVE_RECV 1 +#define RECV_TYPE_ARG1 int +#define RECV_TYPE_ARG2 void * +#define RECV_TYPE_ARG3 size_t +#define RECV_TYPE_ARG4 int +#define RECV_TYPE_RETV ssize_t + +#define HAVE_SEND 1 +#define SEND_TYPE_ARG1 int +#define SEND_TYPE_ARG2 void * +#define SEND_TYPE_ARG3 size_t +#define SEND_TYPE_ARG4 int +#define SEND_TYPE_RETV ssize_t + +#endif /* HEADER_CURL_CONFIG_MAC_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/config-os400.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/config-os400.h new file mode 100644 index 0000000000..95db6d424b --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/config-os400.h @@ -0,0 +1,289 @@ +#ifndef HEADER_CURL_CONFIG_OS400_H +#define HEADER_CURL_CONFIG_OS400_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* ================================================================ */ +/* Handcrafted config file for OS/400 */ +/* ================================================================ */ + +#pragma enum(int) + +/* ---------------------------------------------------------------- */ +/* Global configuration parameters: normally generated by autoconf. */ +/* ---------------------------------------------------------------- */ + +/* Location of default CA bundle */ +/* Use the system keyring as the default CA bundle. */ +#define CURL_CA_BUNDLE "/QIBM/UserData/ICSS/Cert/Server/DEFAULT.KDB" + +/* Definition to make a library symbol externally visible. */ +#define CURL_EXTERN_SYMBOL + +/* cpu-machine-OS */ +#ifndef CURL_OS +#define CURL_OS "OS/400" +#endif + +/* Define to 1 if you have the alarm function. */ +#define HAVE_ALARM 1 + +/* Define if you have the <arpa/inet.h> header file. */ +#define HAVE_ARPA_INET_H 1 + +/* if you have <dirent.h> */ +#define HAVE_DIRENT_H + +/* Define to 1 if you have the fcntl function. */ +#define HAVE_FCNTL 1 + +/* Define to 1 if you have the <fcntl.h> header file. */ +#define HAVE_FCNTL_H 1 + +/* Define to 1 if you have a working fcntl O_NONBLOCK function. */ +#define HAVE_FCNTL_O_NONBLOCK 1 + +/* Define to 1 if you have the freeaddrinfo function. */ +#define HAVE_FREEADDRINFO 1 + +/* Define to 1 if you have a working getaddrinfo function. */ +#define HAVE_GETADDRINFO 1 + +/* Define to 1 if the getaddrinfo function is thread-safe. */ +#define HAVE_GETADDRINFO_THREADSAFE 1 + +/* Define to 1 if you have the 'geteuid' function. */ +#define HAVE_GETEUID 1 + +/* Define to 1 if you have the gethostname function. */ +#define HAVE_GETHOSTNAME 1 + +/* Define to 1 if you have the getpeername function. */ +#define HAVE_GETPEERNAME 1 + +/* Define to 1 if you have the 'getppid' function. */ +#define HAVE_GETPPID 1 + +/* Define to 1 if you have the 'getpwuid' function. */ +#define HAVE_GETPWUID 1 + +/* Define to 1 if you have the getsockname function. */ +#define HAVE_GETSOCKNAME 1 + +/* Define to 1 if you have the 'gettimeofday' function. */ +#define HAVE_GETTIMEOFDAY 1 + +/* if you have GSS-API libraries */ +#define HAVE_GSSAPI + +/* Define to 1 if you have a working ioctl FIONBIO function. */ +#define HAVE_IOCTL_FIONBIO 1 + +/* Define to 1 if you have a working ioctl SIOCGIFADDR function. */ +#define HAVE_IOCTL_SIOCGIFADDR 1 + +/* Define to 1 if you have the lber.h header file. */ +#define HAVE_LBER_H 1 + +/* Define to 1 if you have the ldap.h header file. */ +#define HAVE_LDAP_H 1 + +/* Define to 1 if you have a working localtime_r function. */ +#define HAVE_LOCALTIME_R 1 + +/* Define to 1 if you have the <netdb.h> header file. */ +#define HAVE_NETDB_H 1 + +/* Define to 1 if you have the <netinet/in.h> header file. */ +#define HAVE_NETINET_IN_H 1 + +/* Define to 1 if you have the <netinet/tcp.h> header file. */ +#define HAVE_NETINET_TCP_H 1 + +/* Define to 1 if you have the <netinet/udp.h> header file. */ +#define HAVE_NETINET_UDP_H 1 + +/* Define to 1 if you have the <net/if.h> header file. */ +#define HAVE_NET_IF_H 1 + +/* if you have opendir */ +#define HAVE_OPENDIR + +/* Define to 1 if you have the 'pipe' function. */ +#define HAVE_PIPE 1 + +/* Define to 1 if you have the <pwd.h> header file. */ +#define HAVE_PWD_H 1 + +/* Define to 1 if you have the recv function. */ +#define HAVE_RECV 1 + +/* Define to 1 if symbol `sa_family_t' exists */ +#define HAVE_SA_FAMILY_T 1 + +/* Define to 1 if you have the send function. */ +#define HAVE_SEND 1 + +/* Define to 1 if you have the 'sendmsg' function. */ +#define HAVE_SENDMSG 1 + +/* Define to 1 if you have the sigaction function. */ +#define HAVE_SIGACTION 1 + +/* Define to 1 if struct sockaddr_in6 has the sin6_scope_id member */ +#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 + +/* Define to 1 if you have the socketpair function. */ +#define HAVE_SOCKET 1 + +/* Define to 1 if you have the <stdbool.h> header file. */ +#define HAVE_STDBOOL_H 1 + +/* Define to 1 if you have the <stdint.h> header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the <stdio.h> header file. */ +#define HAVE_STDIO_H 1 + +/* Define to 1 if you have the <stdlib.h> header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the stricmp function. */ +#define HAVE_STRICMP 1 + +/* Define to 1 if you have the <strings.h> header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the <string.h> header file. */ +#define HAVE_STRING_H 1 + +/* if struct sockaddr_storage is defined */ +#define HAVE_STRUCT_SOCKADDR_STORAGE + +/* Define to 1 if you have the timeval struct. */ +#define HAVE_STRUCT_TIMEVAL 1 + +/* Define to 1 if you have the <sys/ioctl.h> header file. */ +#define HAVE_SYS_IOCTL_H 1 + +/* Define to 1 if you have the <sys/param.h> header file. */ +#define HAVE_SYS_PARAM_H 1 + +/* Define to 1 if you have the <sys/resource.h> header file. */ +#define HAVE_SYS_RESOURCE_H 1 + +/* Define to 1 if you have the <sys/stat.h> header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the <sys/types.h> header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the <sys/un.h> header file. */ +#define HAVE_SYS_UN_H 1 + +/* Define to 1 if you have the <unicode/uidna.h> header file. */ +#define HAVE_UNICODE_UIDNA_H 1 + +/* Define to 1 if you have the <unistd.h> header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if you have the 'utime' function. */ +#define HAVE_UTIME 1 + +/* Define to 1 if you have the <utime.h> header file. */ +#define HAVE_UTIME_H 1 + +/* Size of curl_off_t in number of bytes */ +#define SIZEOF_CURL_OFF_T 8 + +/* Size of curl_socket_t in number of bytes */ +#define SIZEOF_CURL_SOCKET_T 4 + +/* Size of int in number of bytes */ +#define SIZEOF_INT 4 + +/* Size of long in number of bytes */ +#define SIZEOF_LONG 4 + +/* Size of off_t in number of bytes */ +#define SIZEOF_OFF_T 8 /* _LARGE_FILES (*IFS64IO) version. */ + +/* Size of size_t in number of bytes */ +#define SIZEOF_SIZE_T 4 + +/* Size of time_t in number of bytes */ +#define SIZEOF_TIME_T 4 + +/* Define if you want to enable IPv6 support */ +#define USE_IPV6 + +/* Use Unix domain sockets */ +#define USE_UNIX_SOCKETS + +/* Define to 1 if OS is AIX. */ +#ifndef _ALL_SOURCE +# undef _ALL_SOURCE +#endif + +/* ---------------------------------------------------------------- */ +/* recv/send parameter types (see lib/functypes.h) */ +/* ---------------------------------------------------------------- */ + +/* int recv(int, char *, int, int); */ +#define RECV_TYPE_ARG1 int +#define RECV_TYPE_ARG2 char * +#define RECV_TYPE_ARG3 int +#define RECV_TYPE_ARG4 int +#define RECV_TYPE_RETV int + +/* int send(int, char *, int, int); */ +#define SEND_TYPE_ARG1 int +#define SEND_NONCONST_ARG2 +#define SEND_TYPE_ARG2 char * +#define SEND_TYPE_ARG3 int +#define SEND_TYPE_ARG4 int +#define SEND_TYPE_RETV int + +/* ---------------------------------------------------------------- */ +/* Additional definitions specific to OS/400 */ +/* ---------------------------------------------------------------- */ + +/* The <gssapi.h> header file is in the main system include directory. */ +#define HAVE_GSSAPI_H + +/* Define to use the OS/400 crypto library. */ +#define USE_OS400CRYPTO + +/* The following definition is required on OS/400 to enable strcmpi(), + stricmp() and strdup(). */ +#define __cplusplus__strings__ + +/* The following must be defined BEFORE system header files inclusion. */ + +#define __ptr128 /* No teraspace. */ +#define qadrt_use_fputc_inline /* Generate fputc() wrapper inline. */ +#define qadrt_use_fread_inline /* Generate fread() wrapper inline. */ +#define qadrt_use_fwrite_inline /* Generate fwrite() wrapper inline. */ + +#endif /* HEADER_CURL_CONFIG_OS400_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/config-win32.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/config-win32.h new file mode 100644 index 0000000000..42387b2c09 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/config-win32.h @@ -0,0 +1,123 @@ +#ifndef HEADER_CURL_CONFIG_WIN32_H +#define HEADER_CURL_CONFIG_WIN32_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* Handcrafted config file for building via Visual Studio IDE Project Files */ + +#if !defined(_MSC_VER) || _MSC_VER > 1800 +#error This manual configuration requires MSVC 2010-2013 (IDE Project builds) +#endif + +/* + * Headers and functions + */ + +#define HAVE_FCNTL_H 1 +#define HAVE_IO_H 1 +#define HAVE_LOCALE_H 1 +#if _MSC_VER >= 1800 +#define HAVE_STDBOOL_H 1 +#define HAVE_BOOL_T 1 +#endif +#define HAVE_SYS_TYPES_H 1 +#define HAVE_SYS_UTIME_H 1 + +#define HAVE_CLOSESOCKET 1 +#define HAVE_FREEADDRINFO 1 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETADDRINFO_THREADSAFE 1 +#define HAVE_GETHOSTNAME 1 +#define HAVE_GETPEERNAME 1 +#define HAVE_GETSOCKNAME 1 +#define HAVE_IOCTLSOCKET 1 +#define HAVE_IOCTLSOCKET_FIONBIO 1 +#define HAVE_SETLOCALE 1 +#define HAVE_SOCKET 1 +#define HAVE_UTIME 1 +#define HAVE_RECV 1 +#define RECV_TYPE_ARG1 SOCKET +#define RECV_TYPE_ARG2 char * +#define RECV_TYPE_ARG3 int +#define RECV_TYPE_ARG4 int +#define RECV_TYPE_RETV int +#define HAVE_SEND 1 +#define SEND_TYPE_ARG1 SOCKET +#define SEND_TYPE_ARG2 char * +#define SEND_TYPE_ARG3 int +#define SEND_TYPE_ARG4 int +#define SEND_TYPE_RETV int +#define HAVE_SIGNAL 1 + +/* + * Types and sizes + */ + +#define SIZEOF_INT 4 +#define SIZEOF_LONG 4 +#ifdef _WIN64 +# define SIZEOF_SIZE_T 8 +# define ssize_t __int64 +#else +# define SIZEOF_SIZE_T 4 +# define ssize_t int +#endif +#define SIZEOF_CURL_OFF_T 8 +/* Default to 64-bit time_t unless _USE_32BIT_TIME_T is defined */ +#ifndef _USE_32BIT_TIME_T +# define SIZEOF_TIME_T 8 +#else +# define SIZEOF_TIME_T 4 +#endif +#define SIZEOF_OFF_T 4 + +#define HAVE_STRUCT_SOCKADDR_STORAGE 1 +#define HAVE_STRUCT_TIMEVAL 1 +#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 + +/* + * Additional definitions + */ + +/* Default define to enable threaded asynchronous DNS lookups. */ +#if !defined(USE_RESOLV_THREADED) && !defined(USE_SYNC_DNS) +# define USE_RESOLV_THREADED 1 +#endif + +#define HAVE_LDAP_SSL 1 +#define USE_WIN32_LDAP 1 +#define USE_WIN32_CRYPTO 1 +#define USE_UNIX_SOCKETS 1 + +#ifndef CURL_OS +# ifdef _M_IX86 +# define CURL_OS "i386-pc-win32" +# elif defined(_M_X64) +# define CURL_OS "x86_64-pc-win32" +# else +# define CURL_OS "unknown-pc-win32" +# endif +#endif + +#endif /* HEADER_CURL_CONFIG_WIN32_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/conncache.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/conncache.c new file mode 100644 index 0000000000..01681d4ebb --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/conncache.c @@ -0,0 +1,1019 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Linus Nielsen Feltzing, <linus@haxx.se> + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "url.h" +#include "cfilters.h" +#include "progress.h" +#include "multiif.h" +#include "curl_trc.h" +#include "cshutdn.h" +#include "conncache.h" +#include "curl_share.h" +#include "sigpipe.h" + + +#define CPOOL_IS_LOCKED(c) ((c) && (c)->locked) + +#define CPOOL_LOCK(c, d) \ + do { \ + if(c) { \ + if(CURL_SHARE_KEEP_CONNECT((c)->share)) \ + Curl_share_lock_share((c)->share, (d), CURL_LOCK_DATA_CONNECT, \ + CURL_LOCK_ACCESS_SINGLE); \ + DEBUGASSERT(!(c)->locked); \ + (c)->locked = TRUE; \ + } \ + } while(0) + +#define CPOOL_UNLOCK(c, d) \ + do { \ + if(c) { \ + DEBUGASSERT((c)->locked); \ + (c)->locked = FALSE; \ + if(CURL_SHARE_KEEP_CONNECT((c)->share)) \ + Curl_share_unlock_share((c)->share, (d), CURL_LOCK_DATA_CONNECT); \ + } \ + } while(0) + +/* A list of connections to the same destination. */ +struct cpool_bundle { + struct Curl_llist conns; /* connections in the bundle */ + size_t dest_len; /* total length of destination, including NUL */ + char dest[1]; /* destination of bundle, allocated to keep dest_len bytes */ +}; + +static struct cpool_bundle *cpool_bundle_create(const char *dest) +{ + struct cpool_bundle *bundle; + size_t dest_len = strlen(dest) + 1; + + bundle = curlx_calloc(1, sizeof(*bundle) + dest_len - 1); + if(!bundle) + return NULL; + Curl_llist_init(&bundle->conns, NULL); + bundle->dest_len = dest_len; + memcpy(bundle->dest, dest, bundle->dest_len); + return bundle; +} + +static void cpool_bundle_destroy(struct cpool_bundle *bundle) +{ + DEBUGASSERT(!Curl_llist_count(&bundle->conns)); + curlx_free(bundle); +} + +/* Add a connection to a bundle */ +static void cpool_bundle_add(struct cpool_bundle *bundle, + struct connectdata *conn) +{ + DEBUGASSERT(!Curl_node_llist(&conn->cpool_node)); + Curl_llist_append(&bundle->conns, conn, &conn->cpool_node); + conn->bits.in_cpool = TRUE; +} + +/* Remove a connection from a bundle */ +static void cpool_bundle_remove(struct cpool_bundle *bundle, + struct connectdata *conn) +{ + (void)bundle; + DEBUGASSERT(Curl_node_llist(&conn->cpool_node) == &bundle->conns); + Curl_node_remove(&conn->cpool_node); + conn->bits.in_cpool = FALSE; +} + +static void cpool_bundle_free_entry(void *freethis) +{ + cpool_bundle_destroy((struct cpool_bundle *)freethis); +} + +void Curl_cpool_init(struct cpool *cpool, + struct Curl_share *share, + size_t size) +{ + Curl_hash_init(&cpool->dest2bundle, size, Curl_hash_str, + curlx_str_key_compare, cpool_bundle_free_entry); + + cpool->share = share; + cpool->initialized = TRUE; +} + +/* Return the "first" connection in the pool or NULL. */ +static struct connectdata *cpool_get_first(struct cpool *cpool) +{ + struct Curl_hash_iterator iter; + struct Curl_hash_element *he; + struct cpool_bundle *bundle; + struct Curl_llist_node *conn_node; + + Curl_hash_start_iterate(&cpool->dest2bundle, &iter); + for(he = Curl_hash_next_element(&iter); he; + he = Curl_hash_next_element(&iter)) { + bundle = he->ptr; + conn_node = Curl_llist_head(&bundle->conns); + if(conn_node) + return Curl_node_elem(conn_node); + } + return NULL; +} + +static struct cpool_bundle *cpool_find_bundle(struct cpool *cpool, + struct connectdata *conn) +{ + return Curl_hash_pick(&cpool->dest2bundle, + conn->destination, strlen(conn->destination) + 1); +} + +static void cpool_remove_bundle(struct cpool *cpool, + struct cpool_bundle *bundle) +{ + if(!cpool) + return; + Curl_hash_delete(&cpool->dest2bundle, bundle->dest, bundle->dest_len); +} + +static void cpool_remove_conn(struct cpool *cpool, + struct connectdata *conn) +{ + struct Curl_llist *list = Curl_node_llist(&conn->cpool_node); + DEBUGASSERT(cpool); + if(list) { + /* The connection is certainly in the pool, but where? */ + struct cpool_bundle *bundle = cpool_find_bundle(cpool, conn); + if(bundle && (list == &bundle->conns)) { + cpool_bundle_remove(bundle, conn); + if(!Curl_llist_count(&bundle->conns)) + cpool_remove_bundle(cpool, bundle); + conn->bits.in_cpool = FALSE; + cpool->num_conn--; + } + else { + /* Should have been in the bundle list */ + DEBUGASSERT(NULL); + } + } +} + +static void cpool_discard_conn(struct cpool *cpool, + struct Curl_easy *data, + struct connectdata *conn, + bool aborted) +{ + struct cshutdn *cshutdn; + struct Curl_easy *admin; + bool done = FALSE; + + DEBUGASSERT(data); + DEBUGASSERT(!data->conn); + DEBUGASSERT(cpool); + DEBUGASSERT(!conn->bits.in_cpool); + + admin = Curl_get_admin(data); + /* + * If this connection is not marked to force-close, leave it open if there + * are other users of it + */ + if(CONN_INUSE(conn) && !aborted) { + CURL_TRC_M(admin, "[CPOOL] not discarding #%" FMT_OFF_T + " still in use by %u transfers", conn->connection_id, + conn->attached_xfers); + return; + } + + /* treat the connection as aborted in CONNECT_ONLY situations, we do + * not know what the APP did with it. */ + if(conn->bits.connect_only) + aborted = TRUE; + conn->bits.aborted = aborted; + + /* We do not shutdown dead connections. The term 'dead' can be misleading + * here, as we also mark errored connections/transfers as 'dead'. + * If we do a shutdown for an aborted transfer, the server might think + * it was successful otherwise (for example an ftps: upload). This is + * not what we want. */ + if(aborted) + done = TRUE; + if(!done) { + /* Attempt to shutdown the connection right away. */ + Curl_conn_shutdown_once(admin, conn, &done); + } + + cshutdn = Curl_cshutdn_get(data); + if(done || !cshutdn) + Curl_conn_terminate(admin, conn, FALSE); + else + Curl_cshutdn_add(cshutdn, conn, cpool->num_conn); +} + +void Curl_cpool_destroy(struct cpool *cpool, struct Curl_easy *admin) +{ + if(cpool && cpool->initialized && admin) { + struct connectdata *conn; + struct Curl_sigpipe_ctx pipe_ctx; + + CURL_TRC_M(admin, "%s[CPOOL] destroy, %zu connections", + cpool->share ? "[SHARE] " : "", cpool->num_conn); + /* Move all connections to the shutdown list */ + sigpipe_init(&pipe_ctx); + CPOOL_LOCK(cpool, admin); + conn = cpool_get_first(cpool); + if(conn) + sigpipe_apply(admin, &pipe_ctx); + while(conn) { + cpool_remove_conn(cpool, conn); + cpool_discard_conn(cpool, admin, conn, FALSE); + conn = cpool_get_first(cpool); + } + CPOOL_UNLOCK(cpool, admin); + sigpipe_restore(&pipe_ctx); + Curl_hash_destroy(&cpool->dest2bundle); + } +} + +static struct cpool *cpool_get_instance(struct Curl_easy *data) +{ + /* admin handles do not necessarily find the correct pool */ + DEBUGASSERT(data->mid); + if(CURL_SHARE_KEEP_CONNECT(data->share)) + return &data->share->cpool; + else if(data->multi_easy) + return &data->multi_easy->cpool; + else if(data->multi) + return &data->multi->cpool; + return NULL; +} + +struct cpool *Curl_cpool_get_instance(struct Curl_easy *data) +{ + return cpool_get_instance(data); +} + +void Curl_cpool_xfer_init(struct Curl_easy *data) +{ + struct cpool *cpool = cpool_get_instance(data); + + if(cpool) { + CPOOL_LOCK(cpool, data); + /* the identifier inside the connection cache */ + data->id = cpool->next_easy_id++; + if(cpool->next_easy_id == CURL_OFF_T_MAX) + cpool->next_easy_id = 0; + data->state.lastconnect_id = -1; + + CPOOL_UNLOCK(cpool, data); + } + else { + /* We should not get here, but in a non-debug build, do something */ + DEBUGASSERT(0); + data->id = 0; + data->state.lastconnect_id = -1; + } +} + +static struct cpool_bundle *cpool_add_bundle(struct cpool *cpool, + struct connectdata *conn) +{ + struct cpool_bundle *bundle; + + bundle = cpool_bundle_create(conn->destination); + if(!bundle) + return NULL; + + if(!Curl_hash_add(&cpool->dest2bundle, + bundle->dest, bundle->dest_len, bundle)) { + cpool_bundle_destroy(bundle); + return NULL; + } + return bundle; +} + +static struct connectdata *cpool_bundle_get_oldest_idle( + struct cpool_bundle *bundle, + const struct curltime *pnow) +{ + struct Curl_llist_node *curr; + timediff_t highscore = -1; + timediff_t score; + struct connectdata *oldest_idle = NULL; + struct connectdata *conn; + + curr = Curl_llist_head(&bundle->conns); + while(curr) { + conn = Curl_node_elem(curr); + + if(!CONN_INUSE(conn)) { + /* Set higher score for the age passed since the connection was used */ + score = curlx_ptimediff_ms(pnow, &conn->lastused); + + if(score > highscore) { + highscore = score; + oldest_idle = conn; + } + } + curr = Curl_node_next(curr); + } + return oldest_idle; +} + +static struct connectdata *cpool_get_oldest_idle(struct cpool *cpool, + const struct curltime *pnow, + timediff_t min_age_ms) +{ + struct Curl_hash_iterator iter; + struct Curl_llist_node *curr; + struct Curl_hash_element *he; + struct cpool_bundle *bundle; + struct connectdata *oldest_idle = NULL; + timediff_t oldest_idle_ms = -1; + timediff_t idle_ms; + + Curl_hash_start_iterate(&cpool->dest2bundle, &iter); + + for(he = Curl_hash_next_element(&iter); he; + he = Curl_hash_next_element(&iter)) { + struct connectdata *conn; + bundle = he->ptr; + + for(curr = Curl_llist_head(&bundle->conns); curr; + curr = Curl_node_next(curr)) { + conn = Curl_node_elem(curr); + if(CONN_INUSE(conn) || conn->bits.close || conn->bits.connect_only) + continue; + idle_ms = curlx_ptimediff_ms(pnow, &conn->lastused); + if((idle_ms >= min_age_ms) && (idle_ms > oldest_idle_ms)) { + oldest_idle_ms = idle_ms; + oldest_idle = conn; + } + } + } + return oldest_idle; +} + +static void cpool_conn_close(struct cpool *cpool, + struct Curl_easy *data, + struct connectdata *conn, + bool aborted) +{ + struct Curl_easy *admin; + bool do_lock; + + DEBUGASSERT(cpool); + DEBUGASSERT(data && !data->conn); + if(!cpool) + return; + + /* If this connection is not marked to force-close, leave it open if there + * are other users of it */ + if(CONN_INUSE(conn) && !aborted) { + DEBUGASSERT(0); /* does this ever happen? */ + DEBUGF(infof(data, "conn terminate when inuse: %u", conn->attached_xfers)); + return; + } + + /* This method may be called while we are under lock, e.g. from a + * user callback in find. */ + admin = Curl_get_admin(data); + do_lock = !CPOOL_IS_LOCKED(cpool); + if(do_lock) + CPOOL_LOCK(cpool, admin); + + if(conn->bits.in_cpool) { + cpool_remove_conn(cpool, conn); + DEBUGASSERT(!conn->bits.in_cpool); + } + + /* treat the connection as aborted in CONNECT_ONLY situations, + * so no graceful shutdown is attempted. */ + if(conn->bits.connect_only) + aborted = TRUE; + + if(data->multi) { + /* Add it to the multi's cpool for shutdown handling */ + infof(data, "%s connection #%" FMT_OFF_T, + aborted ? "closing" : "shutting down", conn->connection_id); + cpool_discard_conn(&data->multi->cpool, data, conn, aborted); + } + else { + /* No multi available, terminate */ + infof(data, "closing connection #%" FMT_OFF_T, conn->connection_id); + Curl_conn_terminate(admin, conn, !aborted); + } + + if(do_lock) + CPOOL_UNLOCK(cpool, admin); +} + +void Curl_conn_close(struct Curl_easy *data, + struct connectdata *conn, + bool aborted) +{ + struct cpool *cpool = cpool_get_instance(data); + cpool_conn_close(cpool, data, conn, aborted); +} + +/* Evict an idle connection to make room in the pool. A pool owned by + * a share has no multi that could perform a controlled shutdown of the + * connection; terminate it right away. Otherwise, hand it to the + * transfer's multi for shutdown. Expects the pool to be locked. */ +static void cpool_evict_conn(struct cpool *cpool, + struct Curl_easy *admin, + struct connectdata *conn) +{ + if(cpool->share) { + cpool_remove_conn(cpool, conn); + Curl_conn_terminate(admin, conn, TRUE); + } + else + cpool_conn_close(cpool, admin, conn, FALSE); +} + +int Curl_cpool_check_limits(struct Curl_easy *data, + struct connectdata *conn, + const struct curltime *pnow) +{ + struct cpool *cpool = cpool_get_instance(data); + struct cshutdn *cshutdn = Curl_cshutdn_get(data); + struct Curl_easy *admin; + struct cpool_bundle *bundle; + size_t dest_limit = 0; + size_t total_limit = 0; + size_t shutdowns; + int res = CPOOL_LIMIT_OK; + + if(!cpool) + return CPOOL_LIMIT_OK; + + /* multi determines the limits, no matter who owns the pool */ + if(data->multi) { + dest_limit = data->multi->max_host_connections; + total_limit = data->multi->max_total_connections; + } + + if(!dest_limit && !total_limit) + return CPOOL_LIMIT_OK; + + admin = Curl_get_admin(data); + CPOOL_LOCK(cpool, admin); + if(dest_limit) { + size_t live; + + bundle = cpool_find_bundle(cpool, conn); + live = bundle ? Curl_llist_count(&bundle->conns) : 0; + shutdowns = Curl_cshutdn_dest_count(cshutdn, conn->destination); + while((live + shutdowns) >= dest_limit) { + if(shutdowns) { + /* close one connection in shutdown right away, if we can */ + if(!Curl_cshutdn_close_oldest(cshutdn, conn->destination)) + break; + } + else if(!bundle) + break; + else { + struct connectdata *oldest_idle = NULL; + /* The bundle is full. Extract the oldest connection that may + * be removed now, if there is one. */ + oldest_idle = cpool_bundle_get_oldest_idle(bundle, pnow); + if(!oldest_idle) + break; + /* disconnect the old conn and continue */ + CURL_TRC_M(admin, "Discarding connection #%" FMT_OFF_T + " from %zu to reach destination limit of %zu", + oldest_idle->connection_id, + Curl_llist_count(&bundle->conns), dest_limit); + cpool_evict_conn(cpool, admin, oldest_idle); + + /* in case the bundle was destroyed in disconnect, look it up again */ + bundle = cpool_find_bundle(cpool, conn); + live = bundle ? Curl_llist_count(&bundle->conns) : 0; + } + shutdowns = Curl_cshutdn_dest_count(cshutdn, conn->destination); + } + if((live + shutdowns) >= dest_limit) { + res = CPOOL_LIMIT_DEST; + goto out; + } + } + + if(total_limit) { + shutdowns = Curl_cshutdn_count(cshutdn); + while((cpool->num_conn + shutdowns) >= total_limit) { + if(shutdowns) { + /* close one connection in shutdown right away, if we can */ + if(!Curl_cshutdn_close_oldest(cshutdn, NULL)) + break; + } + else { + struct connectdata *oldest_idle = + cpool_get_oldest_idle(cpool, pnow, 0); + if(!oldest_idle) + break; + /* disconnect the old conn and continue */ + CURL_TRC_M(admin, "Discarding connection #%" + FMT_OFF_T " from %zu to reach total " + "limit of %zu", + oldest_idle->connection_id, cpool->num_conn, total_limit); + cpool_evict_conn(cpool, admin, oldest_idle); + } + shutdowns = Curl_cshutdn_count(cshutdn); + } + if((cpool->num_conn + shutdowns) >= total_limit) { + res = CPOOL_LIMIT_TOTAL; + goto out; + } + } + +out: + CPOOL_UNLOCK(cpool, admin); + return res; +} + +CURLcode Curl_cpool_add(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct cpool_bundle *bundle = NULL; + struct cpool *cpool = cpool_get_instance(data); + DEBUGASSERT(conn); + + DEBUGASSERT(cpool); + if(!cpool) + return CURLE_FAILED_INIT; + + CPOOL_LOCK(cpool, data); + bundle = cpool_find_bundle(cpool, conn); + if(!bundle) { + bundle = cpool_add_bundle(cpool, conn); + if(!bundle) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + + cpool_bundle_add(bundle, conn); + conn->connection_id = cpool->next_connection_id++; + cpool->num_conn++; + CURL_TRC_M(data, "[CPOOL] added connection %" FMT_OFF_T ". " + "The cache now contains %zu members", + conn->connection_id, cpool->num_conn); +out: + CPOOL_UNLOCK(cpool, data); + + return result; +} + +/* This function iterates the entire connection pool and calls the function + func() with the connection pointer as the first argument and the supplied + 'param' argument as the other. + + The cpool lock is still held when the callback is called. It needs it, + so that it can safely continue traversing the lists once the callback + returns. + + Returns TRUE if the loop was aborted due to the callback's return code. + + Return 0 from func() to continue the loop, return 1 to abort it. + */ +static bool cpool_foreach(struct Curl_easy *data, + struct cpool *cpool, + void *param, + int (*func)(struct cpool *cpool, + struct Curl_easy *data, + struct connectdata *conn, void *param)) +{ + struct Curl_hash_iterator iter; + struct Curl_hash_element *he; + + if(!cpool) + return FALSE; + + Curl_hash_start_iterate(&cpool->dest2bundle, &iter); + + he = Curl_hash_next_element(&iter); + while(he) { + struct Curl_llist_node *curr; + struct cpool_bundle *bundle = he->ptr; + he = Curl_hash_next_element(&iter); + + curr = Curl_llist_head(&bundle->conns); + while(curr) { + /* Yes, we need to update curr before calling func(), because func() + might decide to remove the connection */ + struct connectdata *conn = Curl_node_elem(curr); + curr = Curl_node_next(curr); + + if(func(cpool, data, conn, param) == 1) { + return TRUE; + } + } + } + return FALSE; +} + +/* + * A connection (already in the pool) has become idle. Do any + * cleanups in regard to the pool's limits. + * + * Return TRUE if idle connection kept in pool, FALSE if closed. + */ +bool Curl_cpool_conn_now_idle(struct Curl_easy *data, + struct connectdata *conn) +{ + unsigned int maxconnects; + struct connectdata *oldest_idle = NULL; + struct cpool *cpool = cpool_get_instance(data); + struct Curl_easy *admin; + bool kept = TRUE; + timediff_t min_age_ms = 0; + + if(!data || !data->multi) + return kept; + + if(!data->multi->maxconnects) { + /* Attached transfers is a weak indicator of business. */ + uint32_t attached = Curl_multi_xfers_attached(data->multi); + maxconnects = (attached <= UINT_MAX / 2) ? attached * 2 : UINT_MAX; + /* We are guessing. So, only evict a "seemingly superfluous" connection + * when has not been used for this long, */ + min_age_ms = 1000; + } + else { + maxconnects = data->multi->maxconnects; + } + + /* remember times, connection had been used just before */ + conn->lastchecked = conn->lastupkeep = conn->lastused = *Curl_pgrs_now(data); + if(cpool && maxconnects) { + /* may be called form a callback already under lock */ + bool do_lock = !CPOOL_IS_LOCKED(cpool); + + admin = Curl_get_admin(data); + if(do_lock) + CPOOL_LOCK(cpool, admin); + if(cpool->num_conn > maxconnects) { + infof(data, "Connection pool is full, closing the oldest of %zu/%u", + cpool->num_conn, maxconnects); + + oldest_idle = cpool_get_oldest_idle(cpool, &conn->lastused, min_age_ms); + kept = (oldest_idle != conn); + if(oldest_idle) { + cpool_evict_conn(cpool, admin, oldest_idle); + } + } + if(do_lock) + CPOOL_UNLOCK(cpool, admin); + } + + return kept; +} + +bool Curl_cpool_find(struct Curl_easy *data, + const char *destination, + Curl_cpool_conn_match_cb *conn_cb, + Curl_cpool_done_match_cb *done_cb, + void *userdata) +{ + struct cpool *cpool = cpool_get_instance(data); + struct cpool_bundle *bundle; + bool found = FALSE; + + DEBUGASSERT(cpool); + DEBUGASSERT(conn_cb); + if(!cpool) + return FALSE; + + CPOOL_LOCK(cpool, data); + bundle = Curl_hash_pick(&cpool->dest2bundle, + CURL_UNCONST(destination), + strlen(destination) + 1); + if(bundle) { + struct Curl_llist_node *curr = Curl_llist_head(&bundle->conns); + while(curr) { + struct connectdata *conn = Curl_node_elem(curr); + /* Get next node now. callback might discard current */ + curr = Curl_node_next(curr); + + if(conn_cb(conn, userdata)) { + found = TRUE; + break; + } + } + } + + if(done_cb) { + found = done_cb(userdata); + } + CPOOL_UNLOCK(cpool, data); + return found; +} + +struct cpool_reaper_ctx { + size_t reaped; + struct curltime now; +}; + +static int cpool_reap_dead_cb(struct cpool *cpool, + struct Curl_easy *admin, + struct connectdata *conn, void *param) +{ + struct cpool_reaper_ctx *reaper = param; + + if(!CONN_INUSE(conn)) { + if(conn->bits.no_reuse || conn->bits.close || + !Curl_cpool_conn_seems_healthy(conn, admin, &reaper->now)) { + /* terminate conn and stop the iteration */ + reaper->reaped++; + cpool_conn_close(cpool, admin, conn, FALSE); + return 1; + } + } + return 0; /* continue iteration */ +} + +/* + * This function scans the data's connection pool for half-open/dead + * connections, closes and removes them. + * The cleanup is done at most once per second. + * + * When called, this transfer has no connection attached. + */ +void Curl_cpool_prune_dead(struct cpool *cpool, + struct Curl_easy *data) +{ + struct Curl_easy *admin; + timediff_t elapsed; + + if(!cpool) + return; + + admin = Curl_get_admin(data); + CPOOL_LOCK(cpool, admin); + elapsed = curlx_ptimediff_ms(Curl_pgrs_now(admin), &cpool->last_cleanup); + + if(elapsed >= 1000L) { + struct cpool_reaper_ctx reaper; + + memset(&reaper, 0, sizeof(reaper)); + reaper.now = *Curl_pgrs_now(admin); + while(cpool_foreach(admin, cpool, &reaper, cpool_reap_dead_cb)) + ; + cpool->last_cleanup = *Curl_pgrs_now(admin); + } + CPOOL_UNLOCK(cpool, admin); +} + +static int conn_upkeep(struct cpool *cpool, + struct Curl_easy *admin, + struct connectdata *conn, + void *param) +{ + const struct curltime *pnow = Curl_pgrs_now(admin); + + (void)param; + if(curlx_ptimediff_ms(pnow, &conn->lastupkeep) >= + admin->set.upkeep_interval_ms) { + CURLcode result; + + conn->lastupkeep = *pnow; + /* briefly attach for action */ + Curl_attach_connection(admin, conn, FALSE); + result = Curl_conn_keep_alive(admin, conn); + Curl_detach_connection(admin); + + if(result && !CONN_INUSE(conn)) { + cpool_conn_close(cpool, admin, conn, FALSE); + return 1; + } + } + return 0; /* continue iteration */ +} + +CURLcode Curl_cpool_upkeep(struct Curl_easy *data) +{ + struct cpool *cpool = cpool_get_instance(data); + struct Curl_easy *admin = Curl_get_admin(data); + + if(!cpool) + return CURLE_OK; + + CPOOL_LOCK(cpool, admin); + while(cpool_foreach(admin, cpool, NULL, conn_upkeep)) + ; + CPOOL_UNLOCK(cpool, admin); + return CURLE_OK; +} + +struct cpool_find_ctx { + curl_off_t id; + struct connectdata *conn; +}; + +static int cpool_find_conn(struct cpool *cpool, + struct Curl_easy *data, + struct connectdata *conn, void *param) +{ + struct cpool_find_ctx *fctx = param; + (void)cpool; + (void)data; + if(conn->connection_id == fctx->id) { + fctx->conn = conn; + return 1; + } + return 0; +} + +struct connectdata *Curl_cpool_get_conn(struct Curl_easy *data, + curl_off_t conn_id) +{ + struct cpool *cpool = cpool_get_instance(data); + struct cpool_find_ctx fctx; + + if(!cpool) + return NULL; + fctx.id = conn_id; + fctx.conn = NULL; + CPOOL_LOCK(cpool, data); + cpool_foreach(data, cpool, &fctx, cpool_find_conn); + CPOOL_UNLOCK(cpool, data); + return fctx.conn; +} + +void Curl_cpool_do_locked(struct Curl_easy *data, + struct connectdata *conn, + Curl_cpool_conn_do_cb *cb, void *cbdata) +{ + struct cpool *cpool = cpool_get_instance(data); + if(cpool) { + CPOOL_LOCK(cpool, data); + cb(conn, data, cbdata); + CPOOL_UNLOCK(cpool, data); + } + else + cb(conn, data, cbdata); +} + +static int cpool_mark_stale(struct cpool *cpool, + struct Curl_easy *admin, + struct connectdata *conn, void *param) +{ + (void)cpool; + (void)admin; + (void)param; + conn->bits.no_reuse = TRUE; + return 0; +} + +static int cpool_reap_no_reuse(struct cpool *cpool, + struct Curl_easy *admin, + struct connectdata *conn, void *param) +{ + (void)param; + if(!CONN_INUSE(conn) && conn->bits.no_reuse) { + cpool_conn_close(cpool, admin, conn, FALSE); + return 1; + } + return 0; /* continue iteration */ +} + +void Curl_cpool_nw_changed(struct cpool *cpool, struct Curl_easy *admin) +{ + if(cpool && admin) { + CPOOL_LOCK(cpool, admin); + cpool_foreach(admin, cpool, NULL, cpool_mark_stale); + while(cpool_foreach(admin, cpool, NULL, cpool_reap_no_reuse)) + ; + CPOOL_UNLOCK(cpool, admin); + } +} + +/* A connection has to have been idle for less than 'conn_max_idle_ms' + (the success rate is too low after this), or created less than + 'conn_max_age_ms' ago, to be subject for reuse. */ +static bool cpool_conn_maxage(struct Curl_easy *data, + struct connectdata *conn, + const struct curltime *pnow) +{ + timediff_t age_ms; + + if(data->set.conn_max_idle_ms) { + age_ms = curlx_ptimediff_ms(pnow, &conn->lastused); + if(age_ms > data->set.conn_max_idle_ms) { + infof(data, "Too old connection (%" FMT_TIMEDIFF_T + " ms idle, max idle is %" FMT_TIMEDIFF_T " ms), disconnect it", + age_ms, data->set.conn_max_idle_ms); + return TRUE; + } + } + + if(data->set.conn_max_age_ms) { + age_ms = curlx_ptimediff_ms(pnow, &conn->created); + if(age_ms > data->set.conn_max_age_ms) { + infof(data, + "Too old connection (created %" FMT_TIMEDIFF_T + " ms ago, max lifetime is %" FMT_TIMEDIFF_T " ms), disconnect it", + age_ms, data->set.conn_max_age_ms); + return TRUE; + } + } + + return FALSE; +} + +bool Curl_cpool_conn_seems_healthy(struct connectdata *conn, + struct Curl_easy *data, + const struct curltime *pnow) +{ + struct Curl_easy *admin; + bool healthy = TRUE; + + DEBUGASSERT(!data->conn); + if(!CONN_INUSE(conn) && cpool_conn_maxage(data, conn, pnow)) /* too old? */ + return FALSE; + if(curlx_ptimediff_ms(pnow, &conn->lastchecked) < 1000) + return TRUE; + + admin = Curl_get_admin(data); + if(conn->scheme->run->connection_is_dead) { + Curl_attach_connection(admin, conn, FALSE); + healthy = !conn->scheme->run->connection_is_dead(admin, conn); + Curl_detach_connection(admin); + } + else { + bool input_pending = FALSE; + + Curl_attach_connection(admin, conn, FALSE); + healthy = Curl_conn_is_alive(admin, conn, &input_pending); + Curl_detach_connection(admin); + if(healthy && input_pending && + !CONN_INUSE(conn) && !Curl_conn_is_multiplex(conn, FIRSTSOCKET)) { + /* Non-multiplexed connections without attached transfers should + * not have input pending. The input might be a TLS Notify Close, + * for all we know. */ + DEBUGF(infof(data, "connection has no transfer but input, not healthy")); + healthy = FALSE; + } + } + + if(healthy) + conn->lastchecked = *pnow; + return healthy; +} + +#if 0 +/* Useful for debugging the connection pool */ +void Curl_cpool_print(struct cpool *cpool) +{ + struct Curl_hash_iterator iter; + struct Curl_llist_node *curr; + struct Curl_hash_element *he; + + if(!cpool) + return; + + curl_mfprintf(stderr, "=Bundle cache=\n"); + + Curl_hash_start_iterate(cpool->dest2bundle, &iter); + + he = Curl_hash_next_element(&iter); + while(he) { + struct cpool_bundle *bundle; + struct connectdata *conn; + + bundle = he->ptr; + + curl_mfprintf(stderr, "%s -", he->key); + curr = Curl_llist_head(bundle->conns); + while(curr) { + conn = Curl_node_elem(curr); + + curl_mfprintf(stderr, " [%p %d]", (void *)conn, conn->refcount); + curr = Curl_node_next(curr); + } + curl_mfprintf(stderr, "\n"); + + he = Curl_hash_next_element(&iter); + } +} +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/conncache.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/conncache.h new file mode 100644 index 0000000000..5e766c99d7 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/conncache.h @@ -0,0 +1,167 @@ +#ifndef HEADER_CURL_CONNCACHE_H +#define HEADER_CURL_CONNCACHE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) Linus Nielsen Feltzing, <linus@haxx.se> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curlx/timeval.h" + +struct connectdata; +struct Curl_easy; +struct curl_pollfds; +struct Curl_waitfds; +struct Curl_multi; +struct Curl_share; + +/** + * Close and destroy the connection. + * If the connection is in a cpool, remove it. + * If a `cshutdn` is available (e.g. data has a multi handle), + * pass the connection to that for controlled shutdown. + * Otherwise terminate it right away. + * Takes ownership of `conn`. + * `data` should not be attached to a connection. + */ +void Curl_conn_close(struct Curl_easy *data, + struct connectdata *conn, + bool aborted); + +struct cpool { + /* the pooled connections, bundled per destination */ + struct Curl_hash dest2bundle; + size_t num_conn; + curl_off_t next_connection_id; + curl_off_t next_easy_id; + struct curltime last_cleanup; + struct Curl_share *share; /* != NULL if pool belongs to share */ + BIT(locked); + BIT(initialized); +}; + +/* Get connection pool instance for data or NULL if none exists */ +struct cpool *Curl_cpool_get_instance(struct Curl_easy *data); + +/* Init the pool, pass multi only if pool is owned by it. + * Cannot fail. + */ +void Curl_cpool_init(struct cpool *cpool, + struct Curl_share *share, + size_t size); + +/* Destroy all connections and free all members */ +void Curl_cpool_destroy(struct cpool *cpool, + struct Curl_easy *admin); + +/* Init the transfer to be used within its connection pool. + * Assigns `data->id`. */ +void Curl_cpool_xfer_init(struct Curl_easy *data); + +/* Get the connection with the given id from `data`'s conn pool. */ +struct connectdata *Curl_cpool_get_conn(struct Curl_easy *data, + curl_off_t conn_id); + +/* Add the connection to the pool. */ +CURLcode Curl_cpool_add(struct Curl_easy *data, + struct connectdata *conn) WARN_UNUSED_RESULT; + +/** + * Return if the pool has reached its configured limits for adding + * the given connection. Try to discard the oldest, idle connections + * to make space. + */ +#define CPOOL_LIMIT_OK 0 +#define CPOOL_LIMIT_DEST 1 +#define CPOOL_LIMIT_TOTAL 2 +int Curl_cpool_check_limits(struct Curl_easy *data, + struct connectdata *conn, + const struct curltime *pnow); + +/* Return of conn is suitable. If so, stops iteration. */ +typedef bool Curl_cpool_conn_match_cb(struct connectdata *conn, + void *userdata); + +/* Act on the result of the find, may override it. */ +typedef bool Curl_cpool_done_match_cb(void *userdata); + +/** + * Find a connection in the pool matching `destination`. + * All callbacks are invoked while the pool's lock is held. + * @param data current transfer + * @param destination match against `conn->destination` in pool + * @param conn_cb must be present, called for each connection in the + * bundle until it returns TRUE + * @return combined result of last conn_db and result_cb or FALSE if no + connections were present. + */ +bool Curl_cpool_find(struct Curl_easy *data, + const char *destination, + Curl_cpool_conn_match_cb *conn_cb, + Curl_cpool_done_match_cb *done_cb, + void *userdata); + +/* + * A connection (already in the pool) is now idle. Do any + * cleanups in regard to the pool's limits. + * + * Return TRUE if idle connection kept in pool, FALSE if closed. + */ +bool Curl_cpool_conn_now_idle(struct Curl_easy *data, + struct connectdata *conn); + +/** + * Scans the connection pool for half-open/dead + * connections, closes and removes them. + * The cleanup is done at most once per second. + */ +void Curl_cpool_prune_dead(struct cpool *cpool, + struct Curl_easy *data); + +/** + * Perform upkeep actions on connections in the transfer's pool. + */ +CURLcode Curl_cpool_upkeep(struct Curl_easy *data); + +typedef void Curl_cpool_conn_do_cb(struct connectdata *conn, + struct Curl_easy *data, + void *cbdata); + +/** + * Invoked the callback for the given data + connection under the + * connection pool's lock. + * The callback is always invoked, even if the transfer has no connection + * pool associated. + */ +void Curl_cpool_do_locked(struct Curl_easy *data, + struct connectdata *conn, + Curl_cpool_conn_do_cb *cb, void *cbdata); + +/* Close all unused connections, prevent reuse of existing ones. */ +void Curl_cpool_nw_changed(struct cpool *cpool, struct Curl_easy *admin); + +/* Return TRUE iff the given connection is considered healthy, e.g. + * usable for more transfers. */ +bool Curl_cpool_conn_seems_healthy(struct connectdata *conn, + struct Curl_easy *data, + const struct curltime *pnow); + +#endif /* HEADER_CURL_CONNCACHE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/connect.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/connect.c new file mode 100644 index 0000000000..cb3647544e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/connect.c @@ -0,0 +1,483 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "curl_trc.h" +#include "strerror.h" +#include "cfilters.h" +#include "connect.h" +#include "cf-https-connect.h" +#include "cf-setup.h" +#include "multiif.h" +#include "progress.h" +#include "conncache.h" +#include "multihandle.h" +#include "select.h" +#include "vdns/cf-dns.h" +#include "curlx/strparse.h" + +#if !defined(CURL_DISABLE_ALTSVC) || defined(USE_HTTPSRR) + +enum alpnid Curl_alpn2alpnid(const unsigned char *name, size_t len) +{ + if(len == 2) { + if(!memcmp(name, "h1", 2)) + return ALPN_h1; + if(!memcmp(name, "h2", 2)) + return ALPN_h2; + if(!memcmp(name, "h3", 2)) + return ALPN_h3; + } + else if(len == 8) { + if(!memcmp(name, "http/1.1", 8)) + return ALPN_h1; + } + return ALPN_none; /* unknown, probably rubbish input */ +} + +#endif + +/* + * timeleft_now_ms() returns the amount of milliseconds left allowed for the + * transfer/connection. If the value is 0, there is no timeout (ie there is + * infinite time left). If the value is negative, the timeout time has already + * elapsed. + * + * @unittest 1303 + */ +UNITTEST timediff_t timeleft_now_ms(struct Curl_easy *data, + const struct curltime *pnow); +UNITTEST timediff_t timeleft_now_ms(struct Curl_easy *data, + const struct curltime *pnow) +{ + timediff_t timeleft_ms = 0; + timediff_t ctimeleft_ms = 0; + + if(data->conn && Curl_shutdown_started(data->conn, FIRSTSOCKET)) + return Curl_shutdown_timeleft(data, data->conn, FIRSTSOCKET); + else if(Curl_is_connecting(data)) { + timediff_t ctimeout_ms = (data->set.connecttimeout > 0) ? + data->set.connecttimeout : DEFAULT_CONNECT_TIMEOUT; + ctimeleft_ms = ctimeout_ms - + Curl_pgrs_since_ms(data, pnow, TIMER_STARTSINGLE); + if(!ctimeleft_ms) + ctimeleft_ms = -1; /* 0 is "no limit", fake 1 ms expiry */ + } + else if(!data->set.timeout || data->set.connect_only) { + return 0; /* no timeout in place or checked, return "no limit" */ + } + + if(data->set.timeout) { + timeleft_ms = data->set.timeout - + Curl_pgrs_since_ms(data, pnow, TIMER_STARTOP); + if(!timeleft_ms) + timeleft_ms = -1; /* 0 is "no limit", fake 1 ms expiry */ + } + + if(!ctimeleft_ms) + return timeleft_ms; + else if(!timeleft_ms) + return ctimeleft_ms; + return CURLMIN(ctimeleft_ms, timeleft_ms); +} + +timediff_t Curl_timeleft_ms(struct Curl_easy *data) +{ + return timeleft_now_ms(data, Curl_pgrs_now(data)); +} + +timediff_t Curl_timeleft_now_ms(struct Curl_easy *data, + const struct curltime *pnow) +{ + return timeleft_now_ms(data, pnow); +} + +void Curl_shutdown_start(struct Curl_easy *data, int8_t sockindex, + int timeout_ms) +{ + struct connectdata *conn = data->conn; + const struct curltime *pnow = Curl_pgrs_now(data); + + DEBUGASSERT(conn); + conn->shutdown.start[sockindex] = *pnow; + conn->shutdown.timeout_ms = (timeout_ms > 0) ? + (timediff_t)timeout_ms : + ((data->set.shutdowntimeout > 0) ? + data->set.shutdowntimeout : DEFAULT_SHUTDOWN_TIMEOUT_MS); + /* Set a timer, unless we operate on the admin handle */ + if(data->mid) + Curl_expire_set(data, EXPIRE_SHUTDOWN, conn->shutdown.timeout_ms, pnow); + CURL_TRC_M(data, "shutdown start on%s connection", + sockindex ? " secondary" : ""); +} + +timediff_t Curl_shutdown_timeleft(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex) +{ + timediff_t left_ms; + + if(!conn->shutdown.start[sockindex].tv_sec || + (conn->shutdown.timeout_ms <= 0)) + return 0; /* not started or no limits */ + + left_ms = conn->shutdown.timeout_ms - + curlx_ptimediff_ms(Curl_pgrs_now(data), + &conn->shutdown.start[sockindex]); + return left_ms ? left_ms : -1; +} + +timediff_t Curl_conn_shutdown_timeleft(struct Curl_easy *data, + struct connectdata *conn) +{ + timediff_t left_ms = 0, ms; + int8_t i; + + for(i = 0; conn->shutdown.timeout_ms && (i < 2); ++i) { + if(!conn->shutdown.start[i].tv_sec) + continue; + ms = Curl_shutdown_timeleft(data, conn, i); + if(ms && (!left_ms || ms < left_ms)) + left_ms = ms; + } + return left_ms; +} + +void Curl_shutdown_clear(struct Curl_easy *data, int8_t sockindex) +{ + struct curltime *pt = &data->conn->shutdown.start[sockindex]; + memset(pt, 0, sizeof(*pt)); +} + +bool Curl_shutdown_started(struct connectdata *conn, int8_t sockindex) +{ + const struct curltime *pt = &conn->shutdown.start[sockindex]; + return (pt->tv_sec > 0) || (pt->tv_usec > 0); +} + +/* + * Used to extract socket and connectdata struct for the most recent + * transfer on the given Curl_easy. + * + * The returned socket will be CURL_SOCKET_BAD in case of failure! + */ +curl_socket_t Curl_getconnectinfo(struct Curl_easy *data, + struct connectdata **connp) +{ + DEBUGASSERT(data); + + /* this works for an easy handle: + * - that has been used for curl_easy_perform() + * - that is associated with a multi handle, and whose connection + * was detached with CURLOPT_CONNECT_ONLY + */ + if(data->state.lastconnect_id != -1) { + struct connectdata *conn; + + conn = Curl_cpool_get_conn(data, data->state.lastconnect_id); + if(!conn) { + data->state.lastconnect_id = -1; + if(connp) + *connp = NULL; + return CURL_SOCKET_BAD; + } + + if(connp) + *connp = conn; + return conn->sock[FIRSTSOCKET]; + } + if(connp) + *connp = NULL; + return CURL_SOCKET_BAD; +} + +void Curl_conncontrol(struct connectdata *conn, int ctrl) +{ + if(!conn) { + DEBUGASSERT(0); + return; + } + switch(ctrl) { + case CONNCTRL_CONN_KEEP: + conn->bits.close = FALSE; + break; + case CONNCTRL_CONN_CLOSE: + conn->bits.close = TRUE; + break; + case CONNCTRL_STREAM_CLOSE: + /* stream close when multiplexing does not affect connection */ + if(!Curl_conn_is_multiplex(conn, FIRSTSOCKET)) + conn->bits.close = TRUE; + break; + default: + DEBUGASSERT(0); + break; + } +} + +CURLcode Curl_conn_setup(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + int ssl_mode) +{ + struct Curl_peer *first_peer = Curl_conn_get_first_peer(conn, sockindex); + CURLcode result = CURLE_OK; + uint8_t dns_queries; + + DEBUGASSERT(data); + DEBUGASSERT(conn->scheme); + DEBUGASSERT(!conn->cfilter[sockindex]); + + if(!first_peer) + return CURLE_FAILED_INIT; + +#ifndef CURL_DISABLE_HTTP + if(!conn->cfilter[sockindex] && + conn->scheme->protocol == CURLPROTO_HTTPS) { + DEBUGASSERT(ssl_mode != CURL_CF_SSL_DISABLE); + result = Curl_cf_https_setup( + data, Curl_conn_get_destination(conn, sockindex), conn, sockindex); + if(result) + goto out; + } +#endif /* !CURL_DISABLE_HTTP */ + + /* Still no cfilter set, apply default. */ + if(!conn->cfilter[sockindex]) { + result = Curl_cf_setup_add(data, conn, sockindex, + conn->transport_wanted, ssl_mode); + if(result) + goto out; + } + + /* Whatever the filter chain will be in the end, it will need the + * resolving of `first_peer`. Add that now so the resolve is started + * right away. */ + dns_queries = Curl_resolv_dns_queries(data, conn->ip_version); + result = Curl_conn_dns_add_addr_resolve(data, conn, sockindex, + first_peer, dns_queries, + conn->transport_wanted); + if(result) + goto out; + + DEBUGASSERT(conn->cfilter[sockindex]); +out: + return result; +} + +#ifdef CURLVERBOSE +static CURLcode conn_connect_trace(struct Curl_easy *data, + struct Curl_cfilter *cf) +{ + if(Curl_trc_is_verbose(data)) { + struct ip_quadruple ipquad; + bool is_ipv6; + CURLcode result; + + result = Curl_conn_cf_get_ip_info(cf, data, &is_ipv6, &ipquad); + if(result) + return result; + + infof(data, "Established %sconnection to %s (%s port %u) from %s port %u ", + (cf->sockindex == SECONDARYSOCKET) ? "2nd " : "", + CURL_CONN_HOST_DISPNAME(data->conn), + ipquad.remote_ip, ipquad.remote_port, + ipquad.local_ip, ipquad.local_port); + } + return CURLE_OK; +} +#endif + +/** + * Update connection statistics + */ +static void conn_report_stats(struct Curl_easy *data, int sockindex) +{ + /* We do gather stats for the second socket...yet */ + if(sockindex == FIRSTSOCKET) { + Curl_conn_cntrl_report_stats(data, data->conn, sockindex); + } +} + +CURLcode Curl_conn_connect(struct Curl_easy *data, + int8_t sockindex, + bool blocking, + bool *done) +{ +#define CF_CONN_NUM_POLLS_ON_STACK 5 + struct pollfd a_few_on_stack[CF_CONN_NUM_POLLS_ON_STACK]; + struct easy_pollset ps; + struct curl_pollfds cpfds; + struct Curl_cfilter *cf; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + if(!CONN_SOCK_IDX_VALID(sockindex)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(data->conn->scheme->flags & PROTOPT_NONETWORK) { + *done = TRUE; + return CURLE_OK; + } + + cf = data->conn->cfilter[sockindex]; + if(!cf) { + *done = FALSE; + return CURLE_FAILED_INIT; + } + + *done = (bool)cf->connected; + if(*done) + return CURLE_OK; + + Curl_pollset_init(&ps); + Curl_pollfds_init(&cpfds, a_few_on_stack, CF_CONN_NUM_POLLS_ON_STACK); + while(!*done) { + if(Curl_conn_needs_flush(data, sockindex)) { + DEBUGF(infof(data, "Curl_conn_connect(index=%d), flush", sockindex)); + result = Curl_conn_flush(data, sockindex); + if(result && (result != CURLE_AGAIN)) + goto out; + } + + result = cf->cft->do_connect(cf, data, done); + CURL_TRC_CF(data, cf, "Curl_conn_connect(block=%d) -> %d, done=%d", + blocking, (int)result, *done); + if(!result && *done) { + /* A final sanity check on connection security */ + if((data->state.origin->scheme->flags & PROTOPT_SSL) && + (sockindex == FIRSTSOCKET) && + !Curl_conn_is_ssl(data->conn, FIRSTSOCKET)) { + DEBUGASSERT(0); + failf(data, "transfer requires SSL, but not connected via SSL"); + result = CURLE_FAILED_INIT; + goto out; + } + /* Now that the complete filter chain is connected, let all filters + * persist information at the connection. E.g. cf-socket sets the + * socket and ip related information. */ + Curl_conn_cntrl_update_info(data, data->conn); + conn_report_stats(data, sockindex); + data->conn->lastupkeep = *Curl_pgrs_now(data); + VERBOSE(result = conn_connect_trace(data, cf)); + VERBOSE(Curl_conn_trc_filters(data, sockindex, "connected")); + Curl_conn_remove_setup_filters(data, sockindex); + VERBOSE(Curl_conn_trc_filters(data, sockindex, "reduced to")); + goto out; + } + else if(result) { + CURL_TRC_CF(data, cf, "Curl_conn_connect(), filter returned %d", + (int)result); + VERBOSE(Curl_conn_trc_filters(data, sockindex, "failed to connect")); + conn_report_stats(data, sockindex); + goto out; + } + + if(!blocking) + goto out; + else { + /* check allowed time left */ + const timediff_t timeout_ms = Curl_timeleft_ms(data); + curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data); + int rc; + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "connect timeout"); + result = CURLE_OPERATION_TIMEDOUT; + goto out; + } + + CURL_TRC_CF(data, cf, "Curl_conn_connect(block=1), do poll"); + Curl_pollset_reset(&ps); + Curl_pollfds_reset(&cpfds); + /* In general, we want to send after connect, wait on that. */ + if(sockfd != CURL_SOCKET_BAD) + result = Curl_pollset_set_out_only(data, &ps, sockfd); + if(!result) + result = Curl_conn_adjust_pollset(data, data->conn, &ps); + if(result) + goto out; + result = Curl_pollfds_add_ps(&cpfds, &ps); + if(result) + goto out; + + rc = Curl_poll(cpfds.pfds, cpfds.n, + CURLMIN(timeout_ms, (cpfds.n ? 1000 : 10))); + CURL_TRC_CF(data, cf, "Curl_conn_connect(block=1), Curl_poll() -> %d", + rc); + if(rc < 0) { + result = CURLE_COULDNT_CONNECT; + goto out; + } + /* continue iterating */ + } + } + +out: + Curl_pollset_cleanup(&ps); + Curl_pollfds_cleanup(&cpfds); + return result; +} + +void Curl_conn_set_multiplex(struct connectdata *conn) +{ + if(!conn->bits.multiplex) { + conn->bits.multiplex = TRUE; + if(conn->attached_multi) { + Curl_multi_connchanged(conn->attached_multi); + } + } +} + +struct Curl_peer *Curl_conn_get_origin(struct connectdata *conn, + int8_t sockindex) +{ + return (sockindex == SECONDARYSOCKET) ? + conn->origin2 : conn->origin; +} + +struct Curl_peer *Curl_conn_get_destination(struct connectdata *conn, + int8_t sockindex) +{ + return (sockindex == SECONDARYSOCKET) ? + (conn->via_peer2 ? conn->via_peer2 : conn->origin2) : + (conn->via_peer ? conn->via_peer : conn->origin); +} + +struct Curl_peer *Curl_conn_get_first_peer(struct connectdata *conn, + int8_t sockindex) +{ +#ifndef CURL_DISABLE_PROXY + if(conn->socks_proxy.peer) + return conn->socks_proxy.peer; + if(conn->http_proxy.peer) + return conn->http_proxy.peer; +#endif + return (sockindex == SECONDARYSOCKET) ? + (conn->via_peer2 ? conn->via_peer2 : conn->origin2) : + (conn->via_peer ? conn->via_peer : conn->origin); +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/connect.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/connect.h new file mode 100644 index 0000000000..bc8c53aa83 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/connect.h @@ -0,0 +1,131 @@ +#ifndef HEADER_CURL_CONNECT_H +#define HEADER_CURL_CONNECT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "vdns/hostip.h" +#include "curlx/timeval.h" + +struct Curl_peer; +struct Curl_str; + +enum alpnid Curl_alpn2alpnid(const unsigned char *name, size_t len); + +/* generic function that returns how much time there is left to run, according + to the timeouts set */ +timediff_t Curl_timeleft_ms(struct Curl_easy *data); +timediff_t Curl_timeleft_now_ms(struct Curl_easy *data, + const struct curltime *pnow); + +#define DEFAULT_CONNECT_TIMEOUT 300000 /* milliseconds == five minutes */ + +#define DEFAULT_SHUTDOWN_TIMEOUT_MS (2 * 1000) + +void Curl_shutdown_start(struct Curl_easy *data, int8_t sockindex, + int timeout_ms); + +/* return how much time there is left to shutdown the connection at + * sockindex. Returns 0 if there is no limit or shutdown has not started. */ +timediff_t Curl_shutdown_timeleft(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex); + +/* return how much time there is left to shutdown the connection. + * Returns 0 if there is no limit or shutdown has not started. */ +timediff_t Curl_conn_shutdown_timeleft(struct Curl_easy *data, + struct connectdata *conn); + +void Curl_shutdown_clear(struct Curl_easy *data, int8_t sockindex); + +/* TRUE iff shutdown has been started */ +bool Curl_shutdown_started(struct connectdata *conn, int8_t sockindex); + +/* + * Used to extract socket and connectdata struct for the most recent + * transfer on the given Curl_easy. + * + * The returned socket will be CURL_SOCKET_BAD in case of failure! + */ +curl_socket_t Curl_getconnectinfo(struct Curl_easy *data, + struct connectdata **connp); + +/* + * Curl_conncontrol() manipulates the `conn->bits.close` bit on + * a connection: + * - CONNCTRL_CONN_KEEP: clear the bit + * - CONNCTRL_CONN_CLOSE: set the bit + * - CONNCTRL_STREAM_CLOSE: set the bit when the connection is not + * multiplexed + * The call does *NOT* cause any immediate connection close. + */ +#define CONNCTRL_CONN_KEEP 0 +#define CONNCTRL_CONN_CLOSE 1 +#define CONNCTRL_STREAM_CLOSE 2 + +void Curl_conncontrol(struct connectdata *conn, int ctrl); + +#define streamclose(x) Curl_conncontrol((x), CONNCTRL_STREAM_CLOSE) +#define connclose(x) Curl_conncontrol((x), CONNCTRL_CONN_CLOSE) +#define connkeep(x) Curl_conncontrol((x), CONNCTRL_CONN_KEEP) + +/** + * Setup the cfilters at `sockindex` in connection `conn`. + * If no filter chain is installed yet, inspects the configuration + * in `data` and `conn` to install a suitable filter chain. + */ +CURLcode Curl_conn_setup(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + int ssl_mode); + +/** + * Bring the filter chain at `sockindex` for connection `data->conn` into + * connected state. Which will set `*done` to TRUE. + * This can be called on an already connected chain with no side effects. + * When not `blocking`, calls may return without error and `*done != TRUE`, + * while the individual filters negotiated the connection. + */ +CURLcode Curl_conn_connect(struct Curl_easy *data, int8_t sockindex, + bool blocking, bool *done); + +/* Set conn to allow multiplexing. */ +void Curl_conn_set_multiplex(struct connectdata *conn); + +/* Get the origin peer at sockindex. */ +struct Curl_peer *Curl_conn_get_origin(struct connectdata *conn, + int8_t sockindex); + +/* Get the peer the connection actually connects to at sockindex. + * Often the same as "origin", but can be redirected via "connect-to" + * or "alt-svc". May tunnel through proxies. */ +struct Curl_peer *Curl_conn_get_destination(struct connectdata *conn, + int8_t sockindex); + +/* Get the peer curl connects its socket to. + * Can be origin, "connect-to" or the first proxy. */ +struct Curl_peer *Curl_conn_get_first_peer(struct connectdata *conn, + int8_t sockindex); + +#endif /* HEADER_CURL_CONNECT_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/content_encoding.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/content_encoding.c new file mode 100644 index 0000000000..0feecceedc --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/content_encoding.c @@ -0,0 +1,877 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "curlx/dynbuf.h" + +#ifdef HAVE_LIBZ +#include <zlib.h> +#endif + +#ifdef HAVE_BROTLI +#ifdef CURL_HAVE_DIAG +/* Ignore -Wvla warnings in brotli headers */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wvla" +#endif +#include <brotli/decode.h> +#ifdef CURL_HAVE_DIAG +#pragma GCC diagnostic pop +#endif +#endif + +#ifdef HAVE_ZSTD +#include <zstd.h> +#endif + +#include "connect.h" +#include "sendf.h" +#include "curl_trc.h" +#include "content_encoding.h" + +#define CONTENT_ENCODING_DEFAULT "identity" + +#ifndef CURL_DISABLE_HTTP + +/* allow no more than 5 "chained" compression steps */ +#define MAX_ENCODE_STACK 5 + +#if defined(HAVE_LIBZ) || defined(HAVE_BROTLI) || defined(HAVE_ZSTD) +#define DECOMPRESS_BUFFER_SIZE 16384 /* buffer size for decompressed data */ +#endif + +#ifdef HAVE_LIBZ + +#if !defined(ZLIB_VERNUM) || (ZLIB_VERNUM < 0x1252) +#error "zlib 1.2.5.2 or greater required" +#endif + +typedef enum { + ZLIB_UNINIT, /* uninitialized */ + ZLIB_INIT, /* initialized */ + ZLIB_INFLATING, /* inflating started. */ + ZLIB_EXTERNAL_TRAILER, /* reading external trailer */ + ZLIB_INIT_GZIP /* initialized in transparent gzip mode */ +} zlibInitState; + +/* Deflate and gzip writer. */ +struct zlib_writer { + struct Curl_cwriter super; + zlibInitState zlib_init; /* zlib init state */ + char buffer[DECOMPRESS_BUFFER_SIZE]; /* Put the decompressed data here. */ + uInt trailerlen; /* Remaining trailer byte count. */ + z_stream z; /* State structure for zlib. */ +}; + +static voidpf zalloc_cb(voidpf opaque, unsigned int items, unsigned int size) +{ + (void)opaque; + /* not a typo, keep it curlx_calloc() */ + return curlx_calloc(items, size); +} + +static void zfree_cb(voidpf opaque, voidpf ptr) +{ + (void)opaque; + curlx_free(ptr); +} + +static CURLcode process_zlib_error(struct Curl_easy *data, z_stream *z) +{ + if(z->msg) + failf(data, "Error while processing content unencoding: %s", z->msg); + else + failf(data, "Error while processing content unencoding: " + "Unknown failure within decompression software."); + + return CURLE_BAD_CONTENT_ENCODING; +} + +static CURLcode exit_zlib(struct Curl_easy *data, z_stream *z, + zlibInitState *zlib_init, CURLcode result) +{ + if(*zlib_init != ZLIB_UNINIT) { + if(inflateEnd(z) != Z_OK && result == CURLE_OK) + result = process_zlib_error(data, z); + *zlib_init = ZLIB_UNINIT; + } + + return result; +} + +static CURLcode process_trailer(struct Curl_easy *data, struct zlib_writer *zp) +{ + z_stream *z = &zp->z; + CURLcode result = CURLE_OK; + uInt len = z->avail_in < zp->trailerlen ? z->avail_in : zp->trailerlen; + + /* Consume expected trailer bytes. Terminate stream if exhausted. + Issue an error if unexpected bytes follow. */ + + zp->trailerlen -= len; + z->avail_in -= len; + z->next_in += len; + if(z->avail_in) + result = CURLE_WRITE_ERROR; + if(result || !zp->trailerlen) + result = exit_zlib(data, z, &zp->zlib_init, result); + else { + /* Only occurs for gzip with zlib < 1.2.0.4 or raw deflate. */ + zp->zlib_init = ZLIB_EXTERNAL_TRAILER; + } + return result; +} + +static CURLcode inflate_stream(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + zlibInitState started) +{ + struct zlib_writer *zp = (struct zlib_writer *)writer; + z_stream *z = &zp->z; /* zlib state structure */ + uInt nread = z->avail_in; + z_const Bytef *orig_in = z->next_in; + bool done = FALSE; + CURLcode result = CURLE_OK; /* Curl_client_write status */ + int i = 0; + + /* Check state. */ + if(zp->zlib_init != ZLIB_INIT && + zp->zlib_init != ZLIB_INFLATING && + zp->zlib_init != ZLIB_INIT_GZIP) + return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR); + + /* because the buffer size is fixed, iteratively decompress and transfer to + the client via next_write function. */ + while(!done) { + int status; /* zlib status */ + done = TRUE; + + if(++i > (1024 * 1024 / DECOMPRESS_BUFFER_SIZE)) { + /* check every MB of output if we are not exceeding time limit */ + i = 0; + if(Curl_timeleft_ms(data) < 0) { + failf(data, "Operation timed out while decoding payload"); + return exit_zlib(data, z, &zp->zlib_init, CURLE_OPERATION_TIMEDOUT); + } + } + + /* (re)set buffer for decompressed output for every iteration */ + z->next_out = (Bytef *)zp->buffer; + z->avail_out = DECOMPRESS_BUFFER_SIZE; + + status = inflate(z, Z_BLOCK); + + /* Flush output data if some. */ + if(z->avail_out != DECOMPRESS_BUFFER_SIZE) { + if(status == Z_OK || status == Z_STREAM_END) { + zp->zlib_init = started; /* Data started. */ + result = Curl_cwriter_write(data, writer->next, type, zp->buffer, + DECOMPRESS_BUFFER_SIZE - z->avail_out); + if(result) { + exit_zlib(data, z, &zp->zlib_init, result); + break; + } + } + } + + /* Dispatch by inflate() status. */ + switch(status) { + case Z_OK: + /* Always loop: there may be unflushed latched data in zlib state. */ + done = FALSE; + break; + case Z_BUF_ERROR: + /* No more data to flush: exit loop. */ + break; + case Z_STREAM_END: + if((started == ZLIB_INIT_GZIP) && (z->avail_in >= 2) && + (z->next_in[0] == 0x1f) && (z->next_in[1] == 0x8b)) { + /* a second gzip member follows; curl does not support + multi-member gzip responses */ + failf(data, "Multi-member gzip response not supported"); + result = exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR); + break; + } + result = process_trailer(data, zp); + break; + case Z_DATA_ERROR: + /* some servers seem to not generate zlib headers, so this is an attempt + to fix and continue anyway */ + if(zp->zlib_init == ZLIB_INIT) { + if(inflateReset2(z, -MAX_WBITS) == Z_OK) { + z->next_in = orig_in; + z->avail_in = nread; + zp->zlib_init = ZLIB_INFLATING; + zp->trailerlen = 4; /* Tolerate up to 4 unknown trailer bytes. */ + done = FALSE; + break; + } + zp->zlib_init = ZLIB_UNINIT; /* inflateEnd() already called. */ + } + result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z)); + break; + default: + result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z)); + break; + } + } + + /* We are about to leave this call so the `nread' data bytes will not be seen + again. If we are in a state that would wrongly allow restart in raw mode + at the next call, assume output has already started. */ + if(nread && zp->zlib_init == ZLIB_INIT) + zp->zlib_init = started; /* Cannot restart anymore. */ + + return result; +} + +/* Deflate handler. */ +static CURLcode deflate_do_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct zlib_writer *zp = (struct zlib_writer *)writer; + z_stream *z = &zp->z; /* zlib state structure */ + + /* Initialize zlib */ + z->zalloc = (alloc_func)zalloc_cb; + z->zfree = (free_func)zfree_cb; + + if(inflateInit(z) != Z_OK) + return process_zlib_error(data, z); + zp->zlib_init = ZLIB_INIT; + return CURLE_OK; +} + +static CURLcode deflate_do_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + struct zlib_writer *zp = (struct zlib_writer *)writer; + z_stream *z = &zp->z; /* zlib state structure */ + + if(!(type & CLIENTWRITE_BODY) || !nbytes) + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); + + /* Set the compressed input when this function is called */ + z->next_in = (z_const Bytef *)buf; + z->avail_in = (uInt)nbytes; + + if(zp->zlib_init == ZLIB_EXTERNAL_TRAILER) + return process_trailer(data, zp); + + /* Now uncompress the data */ + return inflate_stream(data, writer, type, ZLIB_INFLATING); +} + +static void deflate_do_close(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct zlib_writer *zp = (struct zlib_writer *)writer; + z_stream *z = &zp->z; /* zlib state structure */ + + exit_zlib(data, z, &zp->zlib_init, CURLE_OK); +} + +static const struct Curl_cwtype deflate_encoding = { + "deflate", + NULL, + CURL_CW_FLAG_BLOWUP, + deflate_do_init, + deflate_do_write, + Curl_cwriter_def_flush, + deflate_do_close, + sizeof(struct zlib_writer) +}; + +/* + * Gzip handler. + */ + +static CURLcode gzip_do_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct zlib_writer *zp = (struct zlib_writer *)writer; + z_stream *z = &zp->z; /* zlib state structure */ + + /* Initialize zlib */ + z->zalloc = (alloc_func)zalloc_cb; + z->zfree = (free_func)zfree_cb; + + if(inflateInit2(z, MAX_WBITS + 32) != Z_OK) + return process_zlib_error(data, z); + + zp->zlib_init = ZLIB_INIT_GZIP; /* Transparent gzip decompress state */ + return CURLE_OK; +} + +static CURLcode gzip_do_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + struct zlib_writer *zp = (struct zlib_writer *)writer; + z_stream *z = &zp->z; /* zlib state structure */ + + if(!(type & CLIENTWRITE_BODY) || !nbytes) + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); + + if(zp->zlib_init == ZLIB_INIT_GZIP) { + /* Let zlib handle the gzip decompression entirely */ + z->next_in = (z_const Bytef *)buf; + z->avail_in = (uInt)nbytes; + /* Now uncompress the data */ + return inflate_stream(data, writer, type, ZLIB_INIT_GZIP); + } + + /* We are running with an old version: return error. */ + return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR); +} + +static void gzip_do_close(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct zlib_writer *zp = (struct zlib_writer *)writer; + z_stream *z = &zp->z; /* zlib state structure */ + + exit_zlib(data, z, &zp->zlib_init, CURLE_OK); +} + +static const struct Curl_cwtype gzip_encoding = { + "gzip", + "x-gzip", + CURL_CW_FLAG_BLOWUP, + gzip_do_init, + gzip_do_write, + Curl_cwriter_def_flush, + gzip_do_close, + sizeof(struct zlib_writer) +}; + +#endif /* HAVE_LIBZ */ + +#ifdef HAVE_BROTLI +/* Brotli writer. */ +struct brotli_writer { + struct Curl_cwriter super; + char buffer[DECOMPRESS_BUFFER_SIZE]; + BrotliDecoderState *br; /* State structure for brotli. */ +}; + +static CURLcode brotli_map_error(BrotliDecoderErrorCode be) +{ + switch(be) { + case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: + case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: + case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: + case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: + case BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: + case BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: + case BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: + case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: + case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: + case BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: + case BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: + case BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: + case BROTLI_DECODER_ERROR_FORMAT_PADDING_1: + case BROTLI_DECODER_ERROR_FORMAT_PADDING_2: +#ifdef BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY /* brotli v1.1.0+ */ + case BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY: +#endif + case BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: + case BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: + return CURLE_BAD_CONTENT_ENCODING; + case BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: + case BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: + case BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: + case BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: + case BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: + case BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: + return CURLE_OUT_OF_MEMORY; + default: + break; + } + return CURLE_WRITE_ERROR; +} + +static CURLcode brotli_do_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct brotli_writer *bp = (struct brotli_writer *)writer; + (void)data; + + bp->br = BrotliDecoderCreateInstance(NULL, NULL, NULL); + return bp->br ? CURLE_OK : CURLE_OUT_OF_MEMORY; +} + +static CURLcode brotli_do_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + struct brotli_writer *bp = (struct brotli_writer *)writer; + const uint8_t *src = (const uint8_t *)buf; + uint8_t *dst; + size_t dstleft; + CURLcode result = CURLE_OK; + BrotliDecoderResult r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT; + int i = 0; + + if(!(type & CLIENTWRITE_BODY) || !nbytes) + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); + + if(!bp->br) + return CURLE_WRITE_ERROR; /* Stream already ended. */ + + while((nbytes || r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) && + result == CURLE_OK) { + + if(++i > (1024 * 1024 / DECOMPRESS_BUFFER_SIZE)) { + /* check every MB of output if we are not exceeding time limit */ + i = 0; + if(Curl_timeleft_ms(data) < 0) { + failf(data, "Operation timed out while decoding payload"); + return CURLE_OPERATION_TIMEDOUT; + } + } + + dst = (uint8_t *)bp->buffer; + dstleft = DECOMPRESS_BUFFER_SIZE; + r = BrotliDecoderDecompressStream(bp->br, + &nbytes, &src, &dstleft, &dst, NULL); + result = Curl_cwriter_write(data, writer->next, type, + bp->buffer, DECOMPRESS_BUFFER_SIZE - dstleft); + if(result) + break; + switch(r) { + case BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: + case BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: + break; + case BROTLI_DECODER_RESULT_SUCCESS: + BrotliDecoderDestroyInstance(bp->br); + bp->br = NULL; + if(nbytes) + result = CURLE_WRITE_ERROR; + break; + default: + result = brotli_map_error(BrotliDecoderGetErrorCode(bp->br)); + break; + } + } + return result; +} + +static void brotli_do_close(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct brotli_writer *bp = (struct brotli_writer *)writer; + (void)data; + + if(bp->br) { + BrotliDecoderDestroyInstance(bp->br); + bp->br = NULL; + } +} + +static const struct Curl_cwtype brotli_encoding = { + "br", + NULL, + CURL_CW_FLAG_BLOWUP, + brotli_do_init, + brotli_do_write, + Curl_cwriter_def_flush, + brotli_do_close, + sizeof(struct brotli_writer) +}; +#endif + +#ifdef HAVE_ZSTD +/* Zstd writer. */ +struct zstd_writer { + struct Curl_cwriter super; + ZSTD_DStream *zds; /* State structure for zstd. */ + char buffer[DECOMPRESS_BUFFER_SIZE]; +}; + +#ifdef ZSTD_STATIC_LINKING_ONLY +static void *Curl_zstd_alloc(void *opaque, size_t size) +{ + (void)opaque; + return Curl_cmalloc(size); +} + +static void Curl_zstd_free(void *opaque, void *address) +{ + (void)opaque; + Curl_cfree(address); +} +#endif + +static CURLcode zstd_do_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct zstd_writer *zp = (struct zstd_writer *)writer; + + (void)data; + +#ifdef ZSTD_STATIC_LINKING_ONLY + zp->zds = ZSTD_createDStream_advanced((ZSTD_customMem) { + .customAlloc = Curl_zstd_alloc, + .customFree = Curl_zstd_free, + .opaque = NULL + }); +#else + zp->zds = ZSTD_createDStream(); +#endif + + return zp->zds ? CURLE_OK : CURLE_OUT_OF_MEMORY; +} + +static CURLcode zstd_do_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + CURLcode result = CURLE_OK; + struct zstd_writer *zp = (struct zstd_writer *)writer; + ZSTD_inBuffer in; + ZSTD_outBuffer out; + size_t errorCode; + int i = 0; + + if(!(type & CLIENTWRITE_BODY) || !nbytes) + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); + + in.pos = 0; + in.src = buf; + in.size = nbytes; + + for(;;) { + if(++i > (1024 * 1024 / DECOMPRESS_BUFFER_SIZE)) { + /* check every MB of output if we are not exceeding time limit */ + i = 0; + if(Curl_timeleft_ms(data) < 0) { + failf(data, "Operation timed out while decoding payload"); + return CURLE_OPERATION_TIMEDOUT; + } + } + + out.pos = 0; + out.dst = zp->buffer; + out.size = DECOMPRESS_BUFFER_SIZE; + + errorCode = ZSTD_decompressStream(zp->zds, &out, &in); + if(ZSTD_isError(errorCode)) { + return CURLE_BAD_CONTENT_ENCODING; + } + if(out.pos > 0) { + result = Curl_cwriter_write(data, writer->next, type, + zp->buffer, out.pos); + if(result) + break; + } + if((in.pos == nbytes) && (out.pos < out.size)) + break; + } + + return result; +} + +static void zstd_do_close(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct zstd_writer *zp = (struct zstd_writer *)writer; + (void)data; + + if(zp->zds) { + ZSTD_freeDStream(zp->zds); + zp->zds = NULL; + } +} + +static const struct Curl_cwtype zstd_encoding = { + "zstd", + NULL, + CURL_CW_FLAG_BLOWUP, + zstd_do_init, + zstd_do_write, + Curl_cwriter_def_flush, + zstd_do_close, + sizeof(struct zstd_writer) +}; +#endif + +/* Identity handler. */ +static const struct Curl_cwtype identity_encoding = { + "identity", + "none", + 0, + Curl_cwriter_def_init, + Curl_cwriter_def_write, + Curl_cwriter_def_flush, + Curl_cwriter_def_close, + sizeof(struct Curl_cwriter) +}; + +/* supported general content decoders. */ +static const struct Curl_cwtype * const general_unencoders[] = { + &identity_encoding, +#ifdef HAVE_LIBZ + &deflate_encoding, + &gzip_encoding, +#endif +#ifdef HAVE_BROTLI + &brotli_encoding, +#endif +#ifdef HAVE_ZSTD + &zstd_encoding, +#endif + NULL +}; + +/* supported content decoders only for transfer encodings */ +static const struct Curl_cwtype * const transfer_unencoders[] = { + &Curl_httpchunk_unencoder, + NULL +}; + +/* Return the list of comma-separated names of supported encodings. + */ +char *Curl_get_content_encodings(void) +{ + struct dynbuf enc; + const struct Curl_cwtype * const *cep; + CURLcode result = CURLE_OK; + curlx_dyn_init(&enc, 255); + + for(cep = general_unencoders; *cep && !result; cep++) { + const struct Curl_cwtype *ce = *cep; + if(!curl_strequal(ce->name, CONTENT_ENCODING_DEFAULT)) { + if(curlx_dyn_len(&enc)) + result = curlx_dyn_addn(&enc, ", ", 2); + if(!result) + result = curlx_dyn_add(&enc, ce->name); + } + } + if(!result && !curlx_dyn_len(&enc)) + result = curlx_dyn_add(&enc, CONTENT_ENCODING_DEFAULT); + + if(!result) + return curlx_dyn_ptr(&enc); + return NULL; +} + +/* Deferred error dummy writer. */ +static CURLcode error_do_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + (void)data; + (void)writer; + return CURLE_OK; +} + +static CURLcode error_do_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + (void)writer; + (void)buf; + (void)nbytes; + + if(!(type & CLIENTWRITE_BODY) || !nbytes) + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); + failf(data, "Unrecognized content encoding type"); + return CURLE_BAD_CONTENT_ENCODING; +} + +static void error_do_close(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + (void)data; + (void)writer; +} + +static const struct Curl_cwtype error_writer = { + "ce-error", + NULL, + 0, + error_do_init, + error_do_write, + Curl_cwriter_def_flush, + error_do_close, + sizeof(struct Curl_cwriter) +}; + +/* Find the content encoding by name. */ +static const struct Curl_cwtype *find_unencode_writer(const char *name, + size_t len, + Curl_cwriter_phase phase) +{ + const struct Curl_cwtype * const *cep; + + if(phase == CURL_CW_TRANSFER_DECODE) { + for(cep = transfer_unencoders; *cep; cep++) { + const struct Curl_cwtype *ce = *cep; + if((curl_strnequal(name, ce->name, len) && !ce->name[len]) || + (ce->alias && curl_strnequal(name, ce->alias, len) && + !ce->alias[len])) + return ce; + } + } + /* look among the general decoders */ + for(cep = general_unencoders; *cep; cep++) { + const struct Curl_cwtype *ce = *cep; + if((curl_strnequal(name, ce->name, len) && !ce->name[len]) || + (ce->alias && curl_strnequal(name, ce->alias, len) && !ce->alias[len])) + return ce; + } + return NULL; +} + +/* Setup the unencoding stack from the Content-Encoding header value. + * See RFC 7231 section 3.1.2.2. */ +CURLcode Curl_build_unencoding_stack(struct Curl_easy *data, + const char *enclist, int is_transfer) +{ + Curl_cwriter_phase phase = is_transfer ? + CURL_CW_TRANSFER_DECODE : CURL_CW_CONTENT_DECODE; + CURLcode result; + bool has_chunked = FALSE; + + do { + const char *name; + size_t namelen; + bool is_chunked = FALSE; + + /* Parse a single encoding name. */ + while(ISBLANK(*enclist) || *enclist == ',') + enclist++; + + name = enclist; + + for(namelen = 0; *enclist && *enclist != ','; enclist++) + if(*enclist > ' ') + namelen = enclist - name + 1; + + if(namelen) { + const struct Curl_cwtype *cwt; + struct Curl_cwriter *writer; + + CURL_TRC_WRITE(data, "looking for %s decoder: %.*s", + is_transfer ? "transfer" : "content", (int)namelen, name); + is_chunked = (is_transfer && (namelen == 7) && + curl_strnequal(name, "chunked", 7)); + /* if we skip the decoding in this phase, do not look further. + * Exception is "chunked" transfer-encoding which always must happen */ + if((is_transfer && !data->set.http_transfer_encoding && !is_chunked) || + (!is_transfer && data->set.http_ce_skip)) { + bool is_identity = (namelen == 8) && + curl_strnequal(name, "identity", 8); + /* not requested, ignore */ + CURL_TRC_WRITE(data, "decoder not requested, ignored: %.*s", + (int)namelen, name); + if(is_transfer && !data->set.http_te_skip) { + if(has_chunked) + failf(data, "A Transfer-Encoding (%.*s) was listed after chunked", + (int)namelen, name); + else if(is_identity) + continue; + else + failf(data, "Unsolicited Transfer-Encoding (%.*s) found", + (int)namelen, name); + return CURLE_BAD_CONTENT_ENCODING; + } + return CURLE_OK; + } + + if(Curl_cwriter_count(data, phase) >= MAX_ENCODE_STACK) { + failf(data, "Reject response exceeding limit of %d %s encodings", + MAX_ENCODE_STACK, + is_transfer ? "transfer" : "content"); + return CURLE_BAD_CONTENT_ENCODING; + } + + cwt = find_unencode_writer(name, namelen, phase); + if(is_transfer && !is_chunked && + Curl_cwriter_get_by_name(data, "chunked")) { + /* RFC 9112, ch. 6.1: + * "If any transfer coding other than chunked is applied to a + * response's content, the sender MUST either apply chunked as the + * final transfer coding or terminate the message by closing the + * connection." + * "chunked" must be the last added to be the first in its phase, + * reject this. + */ + failf(data, "Reject response due to 'chunked' not being the last " + "Transfer-Encoding"); + return CURLE_BAD_CONTENT_ENCODING; + } + if(cwt && is_chunked && Curl_cwriter_get_by_type(data, cwt)) { + /* A 'chunked' transfer encoding has already been added. + * Ignore duplicates. See #13451. + * Also RFC 9112, ch. 6.1: + * "A sender MUST NOT apply the chunked transfer coding more than + * once to a message body." + */ + CURL_TRC_WRITE(data, "ignoring duplicate 'chunked' decoder"); + } + else { + if(!cwt) + cwt = &error_writer; /* Defer error at use. */ + + result = Curl_cwriter_create(&writer, data, cwt, phase); + CURL_TRC_WRITE(data, "added %s decoder %s -> %d", + is_transfer ? "transfer" : "content", cwt->name, + (int)result); + if(result) + return result; + + result = Curl_cwriter_add(data, writer); + if(result) { + Curl_cwriter_free(data, writer); + return result; + } + } + if(is_chunked) + has_chunked = TRUE; + } + } while(*enclist); + + return CURLE_OK; +} + +#else +/* Stubs for builds without HTTP. */ +CURLcode Curl_build_unencoding_stack(struct Curl_easy *data, + const char *enclist, int is_transfer) +{ + (void)data; + (void)enclist; + (void)is_transfer; + return CURLE_NOT_BUILT_IN; +} + +char *Curl_get_content_encodings(void) +{ + return curlx_strdup(CONTENT_ENCODING_DEFAULT); +} + +#endif /* CURL_DISABLE_HTTP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/content_encoding.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/content_encoding.h new file mode 100644 index 0000000000..e84a739761 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/content_encoding.h @@ -0,0 +1,35 @@ +#ifndef HEADER_CURL_CONTENT_ENCODING_H +#define HEADER_CURL_CONTENT_ENCODING_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct Curl_cwriter; + +/* returns an allocated string or NULL */ +char *Curl_get_content_encodings(void); + +CURLcode Curl_build_unencoding_stack(struct Curl_easy *data, + const char *enclist, int is_transfer); +#endif /* HEADER_CURL_CONTENT_ENCODING_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cookie.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cookie.c new file mode 100644 index 0000000000..3255668ec7 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cookie.c @@ -0,0 +1,1704 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) + +#include "urldata.h" +#include "cookie.h" +#include "psl.h" +#include "curl_trc.h" +#include "transfer.h" +#include "slist.h" +#include "curl_share.h" +#include "strcase.h" +#include "curl_fopen.h" +#include "curl_get_line.h" +#include "curl_memrchr.h" +#include "parsedate.h" +#include "curlx/strdup.h" +#include "llist.h" +#include "curlx/strparse.h" + +/* number of seconds in 400 days */ +#define COOKIES_MAXAGE (400 * 24 * 3600) + +/* Make sure cookies never expire further away in time than 400 days into the + future. (from RFC6265bis draft-19) + + For the sake of easier testing, align the capped time to an even 60 second + boundary. */ +static void cap_expires(time_t now, struct Cookie *co) +{ + if(co->expires && (TIME_T_MAX - COOKIES_MAXAGE - 30) > now) { + timediff_t cap = now + COOKIES_MAXAGE; + if(co->expires > cap) { + cap += 30; + co->expires = (cap / 60) * 60; + } + } +} + +static void freecookie(struct Cookie *co, bool maintoo) +{ + curlx_free(co->domain); + curlx_free(co->path); + curlx_free(co->name); + curlx_free(co->value); + if(maintoo) + curlx_free(co); +} + +static bool cookie_tailmatch(const char *cookie_domain, + const size_t cookie_domain_len, + const char *hostname) +{ + size_t hostname_len = strlen(hostname); + + if(hostname_len < cookie_domain_len) + return FALSE; + + if(!curl_strnequal(cookie_domain, + hostname + hostname_len - cookie_domain_len, + cookie_domain_len)) + return FALSE; + + /* + * A lead char of cookie_domain is not '.'. + * RFC6265 4.1.2.3. The Domain Attribute says: + * For example, if the value of the Domain attribute is + * "example.com", the user agent will include the cookie in the Cookie + * header when making HTTP requests to example.com, www.example.com, and + * www.corp.example.com. + */ + if(hostname_len == cookie_domain_len) + return TRUE; + if('.' == *(hostname + hostname_len - cookie_domain_len - 1)) + return TRUE; + return FALSE; +} + +/* + * matching cookie path and URL path + * RFC6265 5.1.4 Paths and Path-Match + */ +static bool pathmatch(const char *cookie_path, const char *uri_path) +{ + size_t cookie_path_len; + size_t uri_path_len; + bool ret = FALSE; + + /* cookie_path must not have last '/' separator. ex: /sample */ + cookie_path_len = strlen(cookie_path); + if(cookie_path_len == 1) { + /* cookie_path must be '/' */ + return TRUE; + } + + /* #-fragments are already cut off! */ + if(strlen(uri_path) == 0 || uri_path[0] != '/') + uri_path = "/"; + + /* + * here, RFC6265 5.1.4 says + * 4. Output the characters of the uri-path from the first character up + * to, but not including, the right-most %x2F ("/"). + * but URL path /hoge?fuga=xxx means /hoge/index.cgi?fuga=xxx in some site + * without redirect. + * Ignore this algorithm because /hoge is uri path for this case + * (uri path is not /). + */ + + uri_path_len = strlen(uri_path); + + if(uri_path_len < cookie_path_len) + goto pathmatched; + + /* not using checkprefix() because matching should be case-sensitive */ + if(strncmp(cookie_path, uri_path, cookie_path_len)) + goto pathmatched; + + /* The cookie-path and the uri-path are identical. */ + if(cookie_path_len == uri_path_len) { + ret = TRUE; + goto pathmatched; + } + + /* here, cookie_path_len < uri_path_len */ + if(uri_path[cookie_path_len] == '/') { + ret = TRUE; + goto pathmatched; + } + +pathmatched: + return ret; +} + +/* + * Return the top-level domain, for optimal hashing. + */ +static const char *get_top_domain(const char * const domain, size_t *outlen) +{ + size_t len = 0; + const char *first = NULL, *last; + + if(domain) { + len = strlen(domain); + last = memrchr(domain, '.', len); + if(last) { + first = memrchr(domain, '.', (last - domain)); + if(first) + len -= (++first - domain); + } + } + + if(outlen) + *outlen = len; + + return first ? first : domain; +} + +/* Avoid C1001, an "internal error" with MSVC14 */ +#if defined(_MSC_VER) && (_MSC_VER == 1900) +#pragma optimize("", off) +#endif + +/* + * A case-insensitive hash for the cookie domains. + */ +static size_t cookie_hash_domain(const char *domain, const size_t len) +{ + const char *end = domain + len; + size_t h = 5381; + + while(domain < end) { + size_t j = (size_t)Curl_raw_toupper(*domain++); + h += h << 5; + h ^= j; + } + + return (h % COOKIE_HASH_SIZE); +} + +#if defined(_MSC_VER) && (_MSC_VER == 1900) +#pragma optimize("", on) +#endif + +/* + * Hash this domain. + */ +static size_t cookiehash(const char * const domain) +{ + const char *top; + size_t len; + + if(!domain || Curl_host_is_ipnum(domain)) + return 0; + + top = get_top_domain(domain, &len); + return cookie_hash_domain(top, len); +} + +/* + * cookie path sanitize + */ +static char *sanitize_cookie_path(const char *cookie_path, size_t len) +{ + /* some sites send path attribute within '"'. */ + if(len && (cookie_path[0] == '\"')) { + cookie_path++; + len--; + + if(len && (cookie_path[len - 1] == '\"')) + len--; + } + + /* RFC6265 5.2.4 The Path Attribute */ + if(!len || (cookie_path[0] != '/')) + /* Let cookie-path be the default-path. */ + return curlx_strdup("/"); + + /* remove trailing slash when path is non-empty */ + /* convert /hoge/ to /hoge */ + if(len > 1 && cookie_path[len - 1] == '/') + len--; + + return curlx_memdup0(cookie_path, len); +} + +/* + * strstore + * + * A thin wrapper around curlx_memdup0(). + */ +static CURLcode strstore(char **str, const char *newstr, size_t len) +{ + DEBUGASSERT(str); + *str = curlx_memdup0(newstr, len); + if(!*str) + return CURLE_OUT_OF_MEMORY; + return CURLE_OK; +} + +/* + * remove_expired + * + * Remove expired cookies from the hash by inspecting the expires timestamp on + * each cookie in the hash, freeing and deleting any where the timestamp is in + * the past. If the cookiejar has recorded the next timestamp at which one or + * more cookies expire, then processing will exit early in case this timestamp + * is in the future. + */ +static void remove_expired(struct CookieInfo *ci) +{ + struct Cookie *co; + curl_off_t now = (curl_off_t)time(NULL); + unsigned int i; + + /* + * If the earliest expiration timestamp in the jar is in the future we can + * skip scanning the whole jar and instead exit early as there will not be + * any cookies to evict. If we need to evict, reset the next_expiration + * counter in order to track the next one. In case the recorded first + * expiration is the max offset, then perform the safe fallback of checking + * all cookies. + */ + if(now < ci->next_expiration && + ci->next_expiration != CURL_OFF_T_MAX) + return; + else + ci->next_expiration = CURL_OFF_T_MAX; + + for(i = 0; i < COOKIE_HASH_SIZE; i++) { + struct Curl_llist_node *n; + struct Curl_llist_node *e = NULL; + + for(n = Curl_llist_head(&ci->cookielist[i]); n; n = e) { + co = Curl_node_elem(n); + e = Curl_node_next(n); + if(co->expires) { + if(co->expires < now) { + Curl_node_remove(n); + freecookie(co, TRUE); + ci->numcookies--; + } + else if(co->expires < ci->next_expiration) + /* + * If this cookie has an expiration timestamp earlier than what we + * have seen so far then record it for the next round of expirations. + */ + ci->next_expiration = co->expires; + } + } + } +} + +#ifndef USE_LIBPSL +/* Make sure domain contains a dot or is localhost. */ +static bool bad_domain(const char *domain, size_t len) +{ + if((len == 9) && curl_strnequal(domain, "localhost", 9)) + return FALSE; + else { + /* there must be a dot present, but that dot must not be a trailing dot */ + const char *dot = memchr(domain, '.', len); + if(dot) { + size_t i = dot - domain; + if((len - i) > 1) + /* the dot is not the last byte */ + return FALSE; + } + } + return TRUE; +} +#endif + +/* RFC 6265 section 4.1.1 says a server should accept this range: + + cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + + Yet, Firefox and Chrome as of June 2022 accept space, comma and + double-quotes fine. The prime reason for filtering out control bytes is that + some HTTP servers return 400 for requests that contain such. + */ +static bool invalid_octets(const char *ptr, size_t len) +{ + const unsigned char *p = (const unsigned char *)ptr; + /* Reject all bytes \x01 - \x1f + \x7f */ + while(len && *p) { + if((*p < 0x20) || (*p == 0x7f)) + return TRUE; + p++; + len--; + } + return FALSE; +} + +/* The maximum length we accept a date string for the 'expire' keyword. The + standard date formats are within the 30 bytes range. This adds an extra + margin to make sure it realistically works with what is used out there. */ +#define MAX_DATE_LENGTH 80 + +#define COOKIE_NAME 0 +#define COOKIE_VALUE 1 +#define COOKIE_DOMAIN 2 +#define COOKIE_PATH 3 + +#define COOKIE_PIECES 4 /* the list above */ + +static CURLcode storecookie(struct Cookie *co, const struct Curl_str *cp, + const char *path, const char *domain) +{ + CURLcode result; + result = strstore(&co->name, curlx_str(&cp[COOKIE_NAME]), + curlx_strlen(&cp[COOKIE_NAME])); + if(!result) + result = strstore(&co->value, curlx_str(&cp[COOKIE_VALUE]), + curlx_strlen(&cp[COOKIE_VALUE])); + if(!result) { + size_t plen = 0; + if(curlx_strlen(&cp[COOKIE_PATH])) { + path = curlx_str(&cp[COOKIE_PATH]); + plen = curlx_strlen(&cp[COOKIE_PATH]); + } + else if(path) { + /* No path was given in the header line, set the default */ + const char *endslash = strrchr(path, '/'); + if(endslash) + plen = endslash - path + 1; /* include end slash */ + else + plen = strlen(path); + } + + if(path) { + co->path = sanitize_cookie_path(path, plen); + if(!co->path) + result = CURLE_OUT_OF_MEMORY; + } + } + if(!result) { + if(curlx_strlen(&cp[COOKIE_DOMAIN])) + result = strstore(&co->domain, curlx_str(&cp[COOKIE_DOMAIN]), + curlx_strlen(&cp[COOKIE_DOMAIN])); + else if(domain) { + /* no domain was given in the header line, set the default */ + co->domain = curlx_strdup(domain); + if(!co->domain) + result = CURLE_OUT_OF_MEMORY; + } + } + return result; +} + +/* + * Parse the first name/value pair of the cookie header, which is the actual + * cookie name and value. + */ +static bool parse_first_pair(struct Curl_easy *data, struct Cookie *co, + struct Curl_str *cookie, + struct Curl_str *name, + struct Curl_str *val, + bool sep) +{ + /* The first name/value pair is the actual cookie name */ + if(!sep || !curlx_strlen(name)) { + infof(data, "invalid cookie, dropped"); + return FALSE; + } + + /* + * Check for too long individual name or contents. Chrome and Firefox + * support 4095 or 4096 bytes combo + */ + if((curlx_strlen(name) + curlx_strlen(val)) > MAX_NAME) { + infof(data, "oversized cookie dropped, name/val %zu + %zu bytes", + curlx_strlen(name), curlx_strlen(val)); + return FALSE; + } + + /* Check if we have a reserved prefix set. */ + if(!strncmp("__Secure-", curlx_str(name), 9)) + co->prefix_secure = TRUE; + else if(!strncmp("__Host-", curlx_str(name), 7)) + co->prefix_host = TRUE; + + cookie[COOKIE_NAME] = *name; + cookie[COOKIE_VALUE] = *val; + return TRUE; +} + +static bool parse_flag(struct Curl_easy *data, struct Cookie *co, + const struct CookieInfo *ci, + struct Curl_str *name, bool secure) +{ + /* + * secure cookies are only allowed to be set when the connection is + * using a secure protocol, or when the cookie is being set by + * reading from file + */ + if(curlx_str_casecompare(name, "secure")) { + if(secure || !ci->running) + co->secure = TRUE; + else { + infof(data, "skipped cookie because not 'secure'"); + return FALSE; + } + } + else if(curlx_str_casecompare(name, "httponly")) + co->httponly = TRUE; + + return TRUE; +} + +static bool parse_domain(struct Curl_easy *data, struct Cookie *co, + struct Curl_str *cookie_domain, + struct Curl_str *val, + const char **domainp) +{ + bool is_ip; + const char *domain = *domainp; + const char *v = curlx_str(val); + /* + * Now, we make sure that our host is within the given domain, or + * the given domain is not valid and thus cannot be set. + */ + + if('.' == *v) + curlx_str_nudge(val, 1); + +#ifndef USE_LIBPSL + /* + * Without PSL we do not know when the incoming cookie is set on a + * TLD or otherwise "protected" suffix. To reduce risk, we require a + * dot OR the exact hostname being "localhost". + */ + if(bad_domain(curlx_str(val), curlx_strlen(val))) { + *domainp = ":"; + domain = ":"; + } +#endif + + is_ip = Curl_host_is_ipnum(domain ? domain : curlx_str(val)); + + if(!domain || + (is_ip && + !strncmp(curlx_str(val), domain, curlx_strlen(val)) && + (curlx_strlen(val) == strlen(domain))) || + (!is_ip && cookie_tailmatch(curlx_str(val), + curlx_strlen(val), domain))) { + *cookie_domain = *val; + if(!is_ip) + co->tailmatch = TRUE; /* we always do that if the domain name was + given */ + } + else { + /* + * We did not get a tailmatch and then the attempted set domain is + * not a domain to which the current host belongs. Mark as bad. + */ + infof(data, "skipped cookie with bad tailmatch domain: %s", + curlx_str(val)); + return FALSE; + } + return TRUE; +} + +static void parse_maxage(struct Cookie *co, struct Curl_str *val, + time_t *nowp) +{ + int rc; + const char *maxage = curlx_str(val); + if(*maxage == '\"') + maxage++; + rc = curlx_str_number(&maxage, &co->expires, CURL_OFF_T_MAX); + if(!*nowp) + *nowp = time(NULL); + switch(rc) { + case STRE_OVERFLOW: + /* overflow, used max value */ + co->expires = CURL_OFF_T_MAX; + break; + default: + /* negative or otherwise bad, expire */ + co->expires = 1; + break; + case STRE_OK: + if(!co->expires) + co->expires = 1; /* expire now */ + else if(CURL_OFF_T_MAX - *nowp < co->expires) + /* would overflow */ + co->expires = CURL_OFF_T_MAX; + else + co->expires += *nowp; + break; + } + cap_expires(*nowp, co); +} + +static void parse_expires(struct Cookie *co, struct Curl_str *val, + time_t *nowp) +{ + /* + * Let max-age have priority. + * + * If the date cannot get parsed for whatever reason, the cookie + * will be treated as a session cookie + */ + if(!co->expires && (curlx_strlen(val) < MAX_DATE_LENGTH)) { + char dbuf[MAX_DATE_LENGTH + 1]; + time_t date = 0; + memcpy(dbuf, curlx_str(val), curlx_strlen(val)); + dbuf[curlx_strlen(val)] = 0; + if(!Curl_getdate_capped(dbuf, &date)) { + if(!date) + date++; + co->expires = (curl_off_t)date; + } + else + co->expires = 0; + if(!*nowp) + *nowp = time(NULL); + cap_expires(*nowp, co); + } +} + +/* this function returns errors on OOM etc, not for cookie format problems */ +static CURLcode +parse_cookie_header(struct Curl_easy *data, + struct Cookie *co, + const struct CookieInfo *ci, + bool *okay, /* if the cookie was fine */ + const char *ptr, /* the header */ + const char *domain, /* default domain */ + /* full path used when this cookie is set */ + const char *path, + bool secure_origin) +{ + /* This line was read off an HTTP-header */ + time_t now = 0; + size_t linelength = strlen(ptr); + CURLcode result = CURLE_OK; + struct Curl_str cookie[COOKIE_PIECES]; + *okay = FALSE; + if(linelength > MAX_COOKIE_LINE) + /* discard overly long lines at once */ + return CURLE_OK; + + /* memset instead of initializer because gcc 4.8.1 is silly */ + memset(cookie, 0, sizeof(cookie)); + do { + struct Curl_str name; + + /* we have a <name>=<value> pair or a stand-alone word here */ + if(!curlx_str_cspn(&ptr, &name, ";\r\n=")) { + struct Curl_str val; + bool sep = FALSE; + curlx_str_trimblanks(&name); + + if(invalid_octets(curlx_str(&name), curlx_strlen(&name))) { + infof(data, "invalid octets in name, cookie dropped"); + return CURLE_OK; + } + + if(!curlx_str_single(&ptr, '=')) { + sep = TRUE; /* a '=' was used */ + if(!curlx_str_cspn(&ptr, &val, ";\r\n")) + curlx_str_trimblanks(&val); + + if(invalid_octets(curlx_str(&val), curlx_strlen(&val))) { + infof(data, "invalid octets in value, cookie dropped"); + return CURLE_OK; + } + } + else + curlx_str_init(&val); + + if(!curlx_strlen(&cookie[COOKIE_NAME])) { + if(!parse_first_pair(data, co, cookie, &name, &val, sep)) + return CURLE_OK; + } + else if(!sep) { + if(!parse_flag(data, co, ci, &name, secure_origin)) + return CURLE_OK; + } + else if(curlx_str_casecompare(&name, "path")) + cookie[COOKIE_PATH] = val; + else if(curlx_str_casecompare(&name, "domain") && curlx_strlen(&val)) { + if(!parse_domain(data, co, &cookie[COOKIE_DOMAIN], &val, &domain)) + return CURLE_OK; + } + else if(curlx_str_casecompare(&name, "max-age") && curlx_strlen(&val)) + parse_maxage(co, &val, &now); + else if(curlx_str_casecompare(&name, "expires") && curlx_strlen(&val)) + parse_expires(co, &val, &now); + } + } while(!curlx_str_single(&ptr, ';')); + + if(curlx_strlen(&cookie[COOKIE_NAME])) { + /* the header was fine, now store the data */ + result = storecookie(co, &cookie[0], path, domain); + if(!result) + *okay = TRUE; + } + return result; +} + +static CURLcode parse_netscape(struct Cookie *co, + const struct CookieInfo *ci, + bool *okay, + const char *lineptr, + bool secure_origin) +{ + /* + * This line is NOT an HTTP header style line, we do offer support for + * reading the odd netscape cookies-file format here + */ + const char *ptr, *next; + int fields; + size_t len; + *okay = FALSE; + + /* + * In 2008, Internet Explorer introduced HTTP-only cookies to prevent XSS + * attacks. Cookies marked httpOnly are not accessible to JavaScript. In + * Firefox's cookie files, they are prefixed #HttpOnly_ and the rest + * remains as usual, so we skip 10 characters of the line. + */ + if(!strncmp(lineptr, "#HttpOnly_", 10)) { + lineptr += 10; + co->httponly = TRUE; + } + + if(lineptr[0] == '#') + /* do not even try the comments */ + return CURLE_OK; + + /* + * Now loop through the fields and init the struct we already have + * allocated + */ + fields = 0; + for(next = lineptr; next; fields++) { + ptr = next; + len = strcspn(ptr, "\t\r\n"); + next = (ptr[len] == '\t' ? &ptr[len + 1] : NULL); + switch(fields) { + case 0: + if(ptr[0] == '.') { /* skip preceding dots */ + ptr++; + len--; + } + co->domain = curlx_memdup0(ptr, len); + if(!co->domain) + return CURLE_OUT_OF_MEMORY; + break; + case 1: + /* + * flag: A TRUE/FALSE value indicating if all machines within a given + * domain can access the variable. Set TRUE when the cookie says + * .example.com and to false when the domain is complete www.example.com + */ + co->tailmatch = !!curl_strnequal(ptr, "TRUE", len); + break; + case 2: + /* The file format allows the path field to remain not filled in */ + if(strncmp("TRUE", ptr, len) && strncmp("FALSE", ptr, len)) { + /* only if the path does not look like a boolean option! */ + co->path = sanitize_cookie_path(ptr, len); + if(!co->path) + return CURLE_OUT_OF_MEMORY; + break; + } + else { + /* this does not look like a path, make one up! */ + co->path = curlx_strdup("/"); + if(!co->path) + return CURLE_OUT_OF_MEMORY; + } + fields++; /* add a field and fall down to secure */ + FALLTHROUGH(); + case 3: + co->secure = FALSE; + if(curl_strnequal(ptr, "TRUE", len)) { + if(secure_origin || ci->running) + co->secure = TRUE; + else + return CURLE_OK; + } + break; + case 4: + if(curlx_str_number(&ptr, &co->expires, CURL_OFF_T_MAX)) + return CURLE_OK; + break; + case 5: + co->name = curlx_memdup0(ptr, len); + if(!co->name) + return CURLE_OUT_OF_MEMORY; + else { + /* For Netscape file format cookies we check prefix on the name. + These prefixes are matched case sensitively, same as on the + header path and as the 6265bis document specifies. */ + if(!strncmp("__Secure-", co->name, 9)) + co->prefix_secure = TRUE; + else if(!strncmp("__Host-", co->name, 7)) + co->prefix_host = TRUE; + } + break; + case 6: + co->value = curlx_memdup0(ptr, len); + if(!co->value) + return CURLE_OUT_OF_MEMORY; + break; + } + } + if(fields == 6) { + /* we got a cookie with blank contents, fix it */ + co->value = curlx_strdup(""); + if(!co->value) + return CURLE_OUT_OF_MEMORY; + else + fields++; + } + + if(fields != 7) + /* we did not find the sufficient number of fields */ + return CURLE_OK; + + /* Reject control octets in the name or value, matching the filtering done + for cookies set over HTTP. A cookie loaded from a file is later sent in + request headers, so the same bytes that make a server reject a request + must not slip in through the file. */ + if(invalid_octets(co->name, strlen(co->name)) || + invalid_octets(co->value, strlen(co->value))) + return CURLE_OK; + + *okay = TRUE; + return CURLE_OK; +} + +static bool is_public_suffix(struct Curl_easy *data, + struct Cookie *co, + const char *domain) +{ +#ifdef USE_LIBPSL + /* + * Check if the domain is a Public Suffix and if yes, ignore the cookie. + * 'domain' is NULL when the cookie is loaded from file or + * CURLOPT_COOKIELIST. + */ + DEBUGASSERT(data); + DEBUGASSERT(co); + DEBUGF(infof(data, "PSL check set-cookie '%s' for domain=%s in %s", + co->name, co->domain ? co->domain : "[blank]", + domain ? domain : "[file]")); + if(!co->domain || Curl_host_is_ipnum(co->domain)) + return FALSE; + + else { + bool acceptable = FALSE; + char lcase[256]; + char lcookie[256]; + size_t dlen = domain ? strlen(domain) : 0; + size_t clen = strlen(co->domain); + + /* trim trailing dots */ + if(dlen && (domain[dlen - 1] == '.')) + dlen--; + if(clen && (co->domain[clen - 1] == '.')) + clen--; + + if((dlen < sizeof(lcase)) && (clen < sizeof(lcookie))) { + const psl_ctx_t *psl = Curl_psl_use(data); + if(psl) { + /* the PSL check requires lowercase domain name and pattern */ + Curl_strntolower(lcookie, co->domain, clen); + lcookie[clen] = 0; + if(domain) { + Curl_strntolower(lcase, domain, dlen); + lcase[dlen] = 0; + acceptable = psl_is_cookie_domain_acceptable(psl, lcase, lcookie); + + /* if the cookie is acceptable, but is set for a PSL domain, then it + cannot be tailmatching */ + if(acceptable && co->tailmatch && + curl_strequal(co->domain, domain) && + psl_is_public_suffix(psl, lcookie)) + co->tailmatch = FALSE; + } + else { + /* libpsl says localhost is a PSL, we think not */ + acceptable = + curl_strequal(lcookie, "localhost") || + /* note that this PSL function returns the opposite value than + psl_is_cookie_domain_acceptable() does */ + !psl_is_public_suffix(psl, lcookie); + } + Curl_psl_release(data); + } + else + infof(data, "libpsl problem, rejecting cookie for safety"); + } + + if(!acceptable) { + infof(data, "cookie '%s' dropped, domain '%s' must not " + "set cookies for '%s'", co->name, + domain ? domain : "[file]", co->domain); + return TRUE; + } + } +#else + (void)data; + (void)co; + (void)domain; + DEBUGF(infof(data, "NO PSL to check set-cookie '%s' for domain=%s in %s", + co->name, co->domain, domain ? domain : "[file]")); +#endif + return FALSE; +} + +/* returns TRUE when replaced */ +static bool replace_existing(struct Curl_easy *data, + struct Cookie *co, + const struct CookieInfo *ci, + bool secure, + bool *replacep) +{ + bool replace_old = FALSE; + struct Curl_llist_node *replace_n = NULL; + struct Curl_llist_node *n; + size_t myhash = cookiehash(co->domain); + for(n = Curl_llist_head(&ci->cookielist[myhash]); n; n = Curl_node_next(n)) { + struct Cookie *clist = Curl_node_elem(n); + if(!strcmp(clist->name, co->name)) { + /* the names are identical */ + bool matching_domains = FALSE; + + if(clist->domain && co->domain) { + if(cookie_tailmatch(clist->domain, strlen(clist->domain), + co->domain) || + cookie_tailmatch(co->domain, strlen(co->domain), clist->domain)) + /* The existing one is a tail of the new or vice versa */ + matching_domains = TRUE; + } + else if(!clist->domain && !co->domain) + matching_domains = TRUE; + + if(matching_domains && /* the domains were identical */ + clist->path && co->path && /* both have paths */ + clist->secure && !co->secure && !secure) { + size_t cllen; + const char *sep = NULL; + + /* + * A non-secure cookie may not overlay an existing secure cookie. + * For an existing cookie "a" with path "/login", refuse a new + * cookie "a" with for example path "/login/en", while the path + * "/loginhelper" is ok. + */ + + DEBUGASSERT(clist->path[0]); + if(clist->path[0]) + sep = strchr(clist->path + 1, '/'); + if(sep) + cllen = sep - clist->path; + else + cllen = strlen(clist->path); + + if(!strncmp(clist->path, co->path, cllen)) { + infof(data, "cookie '%s' for domain '%s' dropped, would " + "overlay an existing cookie", co->name, co->domain); + return FALSE; + } + } + } + + if(!replace_n && !strcmp(clist->name, co->name)) { + /* the names are identical */ + + if(clist->domain && co->domain) { + if(curl_strequal(clist->domain, co->domain) && + (clist->tailmatch == co->tailmatch)) + /* The domains are identical */ + replace_old = TRUE; + } + else if(!clist->domain && !co->domain) + replace_old = TRUE; + + if(replace_old) { + /* the domains were identical */ + + if(clist->path && co->path && + strcmp(clist->path, co->path)) + replace_old = FALSE; + else if(!clist->path != !co->path) + replace_old = FALSE; + } + + if(replace_old && !co->livecookie && clist->livecookie) { + /* + * Both cookies matched fine, except that the already present cookie + * is "live", which means it was set from a header, while the new one + * was read from a file and thus is not "live". "live" cookies are + * preferred so the new cookie is freed. + */ + return FALSE; + } + if(replace_old) + replace_n = n; + } + } + if(replace_n) { + struct Cookie *repl = Curl_node_elem(replace_n); + + /* when replacing, creationtime is kept from old */ + co->creationtime = repl->creationtime; + + /* unlink the old */ + Curl_node_remove(replace_n); + + /* free the old cookie */ + freecookie(repl, TRUE); + } + *replacep = replace_old; + return TRUE; +} + +/* + * Curl_cookie_add + * + * Add a single cookie line to the cookie keeping object. Be aware that + * sometimes we get an IP-only hostname, and that might also be a numerical + * IPv6 address. + * + */ +CURLcode Curl_cookie_add(struct Curl_easy *data, + struct CookieInfo *ci, + const char *lineptr, /* first character of the line */ + const char *domain, /* default domain */ + const char *path, /* full path used when this + cookie is set, used to get + default path for the cookie + unless set */ + const int flags) +{ + struct Cookie comem; + struct Cookie *co; + size_t myhash; + CURLcode result; + bool replaces = FALSE; + bool okay; + + DEBUGASSERT(data); + DEBUGASSERT(MAX_SET_COOKIE_AMOUNT <= 255); /* counter is an unsigned char */ + if(data->req.setcookies >= MAX_SET_COOKIE_AMOUNT) + return CURLE_OK; /* silently ignore */ + + co = &comem; + memset(co, 0, sizeof(comem)); + + if(flags & COOKIE_HTTPHEADER) + result = parse_cookie_header(data, co, ci, &okay, + lineptr, domain, path, flags & COOKIE_SECURE); + else + result = parse_netscape(co, ci, &okay, lineptr, flags & COOKIE_SECURE); + + if(result || !okay) + goto fail; + + if(co->prefix_secure && !co->secure) + /* The __Secure- prefix only requires that the cookie be set secure */ + goto fail; + + if(!(flags & COOKIE_NOPSL) && is_public_suffix(data, co, domain)) + goto fail; + + if(co->prefix_host) { + /* + * The __Host- prefix requires the cookie to be secure, have a "/" path + * and not have a domain set. + */ + if(co->secure && co->path && !strcmp(co->path, "/") && !co->tailmatch) + ; + else + goto fail; + } + + if(!ci->running && /* read from a file */ + ci->newsession && /* clean session cookies */ + !co->expires) /* this is a session cookie */ + goto fail; + + co->livecookie = ci->running; + co->creationtime = ++ci->lastct; + + if(!(flags & COOKIE_NOEXPIRE)) + remove_expired(ci); + + /* + * Now we have parsed the incoming line, we must now check if this supersedes + * an already existing cookie, which it may if the previous have the same + * domain and path as this. + */ + if(!replace_existing(data, co, ci, flags & COOKIE_SECURE, &replaces)) + goto fail; + + /* clone the stack struct into heap */ + co = curlx_memdup(&comem, sizeof(comem)); + if(!co) { + co = &comem; + result = CURLE_OUT_OF_MEMORY; + goto fail; /* bail out if we are this low on memory */ + } + + /* add this cookie to the list */ + myhash = cookiehash(co->domain); + Curl_llist_append(&ci->cookielist[myhash], co, &co->node); + + if(ci->running) + /* Only show this when NOT reading the cookies from a file */ + infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, " + "expire %" FMT_OFF_T, + replaces ? "Replaced" : "Added", co->name, co->value, + co->domain, co->path, co->expires); + + if(!replaces) + ci->numcookies++; /* one more cookie in the jar */ + + /* + * Now that we have added a new cookie to the jar, update the expiration + * tracker in case it is the next one to expire. + */ + if(co->expires && (co->expires < ci->next_expiration)) + ci->next_expiration = co->expires; + + if(flags & COOKIE_HTTPHEADER) + data->req.setcookies++; + + return result; +fail: + freecookie(co, FALSE); + return result; +} + +/* + * Curl_cookie_init() + * + * Inits a cookie struct to read data from a local file. This is always + * called before any cookies are set. File may be NULL in which case only the + * struct is initialized. Is file is "-" then STDIN is read. + * + * If 'newsession' is TRUE, discard all "session cookies" on read from file. + * + * Note that 'data' might be called as NULL pointer. If data is NULL, 'file' + * will be ignored. + * + * Returns NULL on out of memory. + */ +struct CookieInfo *Curl_cookie_init(void) +{ + int i; + struct CookieInfo *ci = curlx_calloc(1, sizeof(struct CookieInfo)); + if(!ci) + return NULL; + + /* This does not use the destructor callback since we want to add + and remove to lists while keeping the cookie struct intact */ + for(i = 0; i < COOKIE_HASH_SIZE; i++) + Curl_llist_init(&ci->cookielist[i], NULL); + /* + * Initialize the next_expiration time to signal that we do not have enough + * information yet. + */ + ci->next_expiration = CURL_OFF_T_MAX; + + return ci; +} + +/* + * cookie_load() + * + * Reads cookies from a local file. This is always called before any cookies + * are set. If file is "-" then STDIN is read. + * + * If 'flags' has the COOKIE_NOSESSION bit set, discard all "session cookies" + * read from file. + */ +static CURLcode cookie_load(struct Curl_easy *data, const char *file, + struct CookieInfo *ci, int flags) +{ + FILE *handle = NULL; + CURLcode result = CURLE_OK; + FILE *fp = NULL; + DEBUGASSERT(ci); + DEBUGASSERT(data); + DEBUGASSERT(file); + + ci->newsession = !!(flags & COOKIE_NOSESSION); /* new session? */ + ci->running = FALSE; /* this is not running, this is init */ + + if(file && *file) { + if(!strcmp(file, "-")) + fp = stdin; + else { + fp = curlx_fopen(file, "rb"); + if(!fp) + infof(data, "WARNING: failed to open cookie file \"%s\"", file); + else { + curlx_struct_stat stat; + if((curlx_fstat(fileno(fp), &stat) != -1) && S_ISDIR(stat.st_mode)) { + curlx_fclose(fp); + fp = NULL; + infof(data, "WARNING: cookie filename points to a directory: \"%s\"", + file); + } + else + handle = fp; + } + } + } + + if(fp) { + struct dynbuf buf; + bool eof = FALSE; + curlx_dyn_init(&buf, MAX_COOKIE_LINE); + do { + result = Curl_get_line(&buf, fp, &eof); + if(!result) { + const char *lineptr = curlx_dyn_ptr(&buf); + bool headerline = FALSE; + if(checkprefix("Set-Cookie:", lineptr)) { + /* This is a cookie line, get it! */ + lineptr += 11; + headerline = TRUE; + curlx_str_passblanks(&lineptr); + } + + result = Curl_cookie_add(data, ci, lineptr, NULL, NULL, + (headerline ? COOKIE_HTTPHEADER : 0) | + COOKIE_NOEXPIRE | COOKIE_SECURE | + (flags & COOKIE_NOPSL)); + /* File reading cookie failures are not propagated back to the + caller because there is no way to do that */ + } + } while(!result && !eof); + curlx_dyn_free(&buf); /* free the line buffer */ + + /* + * Remove expired cookies from the hash. We must make sure to run this + * after reading the file, and not on every cookie. + */ + remove_expired(ci); + + if(handle) + curlx_fclose(handle); + } + data->state.cookie_engine = TRUE; + ci->running = TRUE; /* now, we are running */ + + return result; +} + +/* + * Load cookies from all given cookie files (CURLOPT_COOKIEFILE). + */ +CURLcode Curl_cookie_loadfiles(struct Curl_easy *data, + int flags) +{ + CURLcode result = CURLE_OK; + struct curl_slist *list = data->state.cookielist; + if(list) { + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + if(!data->cookies) + data->cookies = Curl_cookie_init(); + if(!data->cookies) + result = CURLE_OUT_OF_MEMORY; + else { + data->state.cookie_engine = TRUE; + while(list) { + result = cookie_load(data, list->data, data->cookies, flags); + if(result) + break; + list = list->next; + } + } + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); + } + return result; +} + +/* + * cookie_sort + * + * Helper function to sort cookies such that the longest path gets before the + * shorter path. Path, domain and name lengths are considered in that order, + * with the creationtime as the tiebreaker. The creationtime is guaranteed to + * be unique per cookie, so we know we will get an ordering at that point. + */ +static int cookie_sort(const void *p1, const void *p2) +{ + const struct Cookie *c1 = *(const struct Cookie * const *)p1; + const struct Cookie *c2 = *(const struct Cookie * const *)p2; + size_t l1, l2; + + /* 1 - compare cookie path lengths */ + l1 = c1->path ? strlen(c1->path) : 0; + l2 = c2->path ? strlen(c2->path) : 0; + + if(l1 != l2) + return (l2 > l1) ? 1 : -1; /* avoid size_t <=> int conversions */ + + /* 2 - compare cookie domain lengths */ + l1 = c1->domain ? strlen(c1->domain) : 0; + l2 = c2->domain ? strlen(c2->domain) : 0; + + if(l1 != l2) + return (l2 > l1) ? 1 : -1; /* avoid size_t <=> int conversions */ + + /* 3 - compare cookie name lengths */ + l1 = c1->name ? strlen(c1->name) : 0; + l2 = c2->name ? strlen(c2->name) : 0; + + if(l1 != l2) + return (l2 > l1) ? 1 : -1; + + /* 4 - compare cookie creation time */ + return (c2->creationtime > c1->creationtime) ? 1 : -1; +} + +/* + * cookie_sort_ct + * + * Helper function to sort cookies according to creation time. + */ +static int cookie_sort_ct(const void *p1, const void *p2) +{ + const struct Cookie *c1 = *(const struct Cookie * const *)p1; + const struct Cookie *c2 = *(const struct Cookie * const *)p2; + + return (c2->creationtime > c1->creationtime) ? 1 : -1; +} + +bool Curl_secure_context(struct Curl_easy *data, const char *host) +{ + return Curl_xfer_is_secure(data) || + curl_strequal("localhost", host) || + !strcmp(host, "127.0.0.1") || + !strcmp(host, "::1"); +} + +/* + * Curl_cookie_getlist + * + * For a given host and path, return a linked list of cookies that the client + * should send to the server if used now. + * + * It shall only return cookies that have not expired. + * + * 'okay' is TRUE when there is a list returned. + */ +CURLcode Curl_cookie_getlist(struct Curl_easy *data, + bool *okay, + const char *host, + struct Curl_llist *list) +{ + size_t matches = 0; + const bool is_ip = Curl_host_is_ipnum(host); + const size_t myhash = cookiehash(host); + struct Curl_llist_node *n; + const bool secure = Curl_secure_context(data, host); + struct CookieInfo *ci = data->cookies; + const char *path = data->state.up.path; + CURLcode result = CURLE_OK; + *okay = FALSE; + + Curl_llist_init(list, NULL); + + if(!ci || !Curl_llist_count(&ci->cookielist[myhash])) + return CURLE_OK; /* no cookie struct or no cookies in the struct */ + + /* at first, remove expired cookies */ + remove_expired(ci); + + for(n = Curl_llist_head(&ci->cookielist[myhash]); n; n = Curl_node_next(n)) { + struct Cookie *co = Curl_node_elem(n); + + /* if the cookie requires we are secure we must only continue if we are! */ + if(co->secure ? secure : TRUE) { + + /* now check if the domain is correct */ + if(!co->domain || + (co->tailmatch && !is_ip && + cookie_tailmatch(co->domain, strlen(co->domain), host)) || + ((!co->tailmatch || is_ip) && curl_strequal(host, co->domain))) { + /* + * the right part of the host matches the domain stuff in the + * cookie data + */ + + /* + * now check the left part of the path with the cookies path + * requirement + */ + if(!co->path || pathmatch(co->path, path)) { + + /* + * This is a match and we add it to the return-linked-list + */ + Curl_llist_append(list, co, &co->getnode); + matches++; + if(matches >= MAX_COOKIE_SEND_AMOUNT) { + infof(data, "Included max number of cookies (%zu) in request!", + matches); + break; + } + } + } + } + } + + if(matches) { + /* + * Now we need to make sure that if there is a name appearing more than + * once, the longest specified path version comes first. To make this the + * swiftest way, we sort them all based on path length. + */ + struct Cookie **array; + size_t i; + + /* alloc an array and store all cookie pointers */ + array = curlx_malloc(sizeof(struct Cookie *) * matches); + if(!array) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + n = Curl_llist_head(list); + + for(i = 0; n; n = Curl_node_next(n)) + array[i++] = Curl_node_elem(n); + + /* now sort the cookie pointers in path length order */ + qsort(array, matches, sizeof(struct Cookie *), cookie_sort); + + /* remake the linked list order according to the new order */ + Curl_llist_destroy(list, NULL); + + for(i = 0; i < matches; i++) + Curl_llist_append(list, array[i], &array[i]->getnode); + + curlx_free(array); /* remove the temporary data again */ + } + + *okay = TRUE; + return CURLE_OK; /* success */ + +fail: + /* failure, clear up the allocated chain and return NULL */ + Curl_llist_destroy(list, NULL); + return result; /* error */ +} + +/* + * Curl_cookie_clearall + * + * Clear all existing cookies and reset the counter. + */ +void Curl_cookie_clearall(struct CookieInfo *ci) +{ + if(ci) { + unsigned int i; + for(i = 0; i < COOKIE_HASH_SIZE; i++) { + struct Curl_llist_node *n; + for(n = Curl_llist_head(&ci->cookielist[i]); n;) { + struct Cookie *c = Curl_node_elem(n); + struct Curl_llist_node *e = Curl_node_next(n); + Curl_node_remove(n); + freecookie(c, TRUE); + n = e; + } + } + ci->numcookies = 0; + } +} + +/* + * Curl_cookie_clearsess + * + * Free all session cookies in the cookies list. + */ +void Curl_cookie_clearsess(struct CookieInfo *ci) +{ + unsigned int i; + + if(!ci) + return; + + for(i = 0; i < COOKIE_HASH_SIZE; i++) { + struct Curl_llist_node *n = Curl_llist_head(&ci->cookielist[i]); + struct Curl_llist_node *e = NULL; + + for(; n; n = e) { + struct Cookie *curr = Curl_node_elem(n); + e = Curl_node_next(n); /* in case the node is removed, get it early */ + if(!curr->expires) { + Curl_node_remove(n); + freecookie(curr, TRUE); + ci->numcookies--; + } + } + } +} + +/* + * Curl_cookie_cleanup() + * + * Free a "cookie object" previous created with Curl_cookie_init(). + */ +void Curl_cookie_cleanup(struct CookieInfo *ci) +{ + if(ci) { + Curl_cookie_clearall(ci); + curlx_free(ci); /* free the base struct as well */ + } +} + +/* + * get_netscape_format() + * + * Formats a string for Netscape output file, w/o a newline at the end. + * Function returns a char * to a formatted line. The caller is responsible + * for freeing the returned pointer. + */ +static char *get_netscape_format(const struct Cookie *co) +{ + return curl_maprintf( + "%s" /* httponly preamble */ + "%s%s\t" /* domain */ + "%s\t" /* tailmatch */ + "%s\t" /* path */ + "%s\t" /* secure */ + "%" FMT_OFF_T "\t" /* expires */ + "%s\t" /* name */ + "%s", /* value */ + co->httponly ? "#HttpOnly_" : "", + /* + * Make sure all domains are prefixed with a dot if they allow + * tailmatching. This is Mozilla-style. + */ + (co->tailmatch && co->domain && co->domain[0] != '.') ? "." : "", + co->domain ? co->domain : "unknown", + co->tailmatch ? "TRUE" : "FALSE", + co->path ? co->path : "/", + co->secure ? "TRUE" : "FALSE", + co->expires, + co->name, + co->value ? co->value : ""); +} + +/* + * cookie_output() + * + * Writes all internally known cookies to the specified file. Specify + * "-" as filename to write to stdout. + * + * The function returns non-zero on write failure. + */ +static CURLcode cookie_output(struct Curl_easy *data, + struct CookieInfo *ci, + const char *filename) +{ + FILE *out = NULL; + bool use_stdout = FALSE; + char *tempstore = NULL; + CURLcode result = CURLE_OK; + + if(!ci) + /* no cookie engine alive */ + return CURLE_OK; + + /* at first, remove expired cookies */ + remove_expired(ci); + + if(!strcmp("-", filename)) { + /* use stdout */ + out = stdout; + use_stdout = TRUE; + } + else { + result = Curl_fopen(data, filename, &out, &tempstore); + if(result) + goto error; + } + + fputs("# Netscape HTTP Cookie File\n" + "# https://curl.se/docs/http-cookies.html\n" + "# This file was generated by libcurl! Edit at your own risk.\n\n", + out); + + if(ci->numcookies) { + unsigned int i; + size_t nvalid = 0; + struct Cookie **array; + struct Curl_llist_node *n; + + array = curlx_calloc(1, sizeof(struct Cookie *) * ci->numcookies); + if(!array) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + /* only sort the cookies with a domain property */ + for(i = 0; i < COOKIE_HASH_SIZE; i++) { + for(n = Curl_llist_head(&ci->cookielist[i]); n; n = Curl_node_next(n)) { + struct Cookie *co = Curl_node_elem(n); + if(!co->domain) + continue; + array[nvalid++] = co; + } + } + + qsort(array, nvalid, sizeof(struct Cookie *), cookie_sort_ct); + + for(i = 0; i < nvalid; i++) { + char *format_ptr = get_netscape_format(array[i]); + if(!format_ptr) { + curlx_free(array); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + curl_mfprintf(out, "%s\n", format_ptr); + curlx_free(format_ptr); + } + + curlx_free(array); + } + + if(!use_stdout) { + curlx_fclose(out); + out = NULL; + if(tempstore && curlx_rename(tempstore, filename)) { + result = CURLE_WRITE_ERROR; + goto error; + } + } + + /* + * If we reach here we have successfully written a cookie file so there is + * no need to inspect the error, any error case should have jumped into the + * error block below. + */ + curlx_free(tempstore); + return CURLE_OK; + +error: + if(out && !use_stdout) + curlx_fclose(out); + if(tempstore) { + unlink(tempstore); + curlx_free(tempstore); + } + return result; +} + +static struct curl_slist *cookie_list(const struct Curl_easy *data) +{ + struct curl_slist *list = NULL; + struct curl_slist *beg; + unsigned int i; + struct Curl_llist_node *n; + + if(!data->cookies || (data->cookies->numcookies == 0)) + return NULL; + + /* at first, remove expired cookies */ + remove_expired(data->cookies); + + for(i = 0; i < COOKIE_HASH_SIZE; i++) { + for(n = Curl_llist_head(&data->cookies->cookielist[i]); n; + n = Curl_node_next(n)) { + struct Cookie *c = Curl_node_elem(n); + char *line; + if(!c->domain) + continue; + line = get_netscape_format(c); + if(!line) { + curl_slist_free_all(list); + return NULL; + } + beg = Curl_slist_append_nodup(list, line); + if(!beg) { + curlx_free(line); + curl_slist_free_all(list); + return NULL; + } + list = beg; + } + } + + return list; +} + +struct curl_slist *Curl_cookie_list(struct Curl_easy *data) +{ + struct curl_slist *list; + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + list = cookie_list(data); + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); + return list; +} + +void Curl_flush_cookies(struct Curl_easy *data, bool cleanup) +{ + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + /* only save the cookie file if a transfer was started (cookies->running is + set), as otherwise the cookies were not completely initialized and there + might be cookie files that were not loaded so saving the file is the + wrong thing. */ + if(data->cookies) { + const char *cookiejar = CURL_EASY_STR(data, STRING_COOKIEJAR); + if(cookiejar && data->cookies->running) { + /* if we have a destination file for all the cookies to get dumped to */ + CURLcode result = cookie_output(data, data->cookies, cookiejar); + if(result) + infof(data, "WARNING: failed to save cookies in %s: %s", + cookiejar, curl_easy_strerror(result)); + } + + if(cleanup && (!data->share || (data->cookies != data->share->cookies))) { + Curl_cookie_cleanup(data->cookies); + data->cookies = NULL; + } + } + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); +} + +void Curl_cookie_run(struct Curl_easy *data) +{ + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + if(data->cookies) + data->cookies->running = TRUE; + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); +} + +#endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cookie.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cookie.h new file mode 100644 index 0000000000..973ec09547 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cookie.h @@ -0,0 +1,149 @@ +#ifndef HEADER_CURL_COOKIE_H +#define HEADER_CURL_COOKIE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "llist.h" + +struct Cookie { + struct Curl_llist_node node; /* for the main cookie list */ + struct Curl_llist_node getnode; /* for getlist */ + char *name; /* <this> = value */ + char *value; /* name = <this> */ + char *path; /* canonical path */ + char *domain; /* domain = <this> */ + curl_off_t expires; /* expires = <this> */ + unsigned int creationtime; /* time when the cookie was written */ + BIT(tailmatch); /* tail-match the domain name */ + BIT(secure); /* the 'secure' keyword was used */ + BIT(livecookie); /* updated from server, not a stored file */ + BIT(httponly); /* the httponly directive is present */ + BIT(prefix_secure); /* secure prefix is set */ + BIT(prefix_host); /* host prefix is set */ +}; + +/* + * Available cookie prefixes, as defined in + * draft-ietf-httpbis-rfc6265bis-02 + */ +#define COOKIE_PREFIX__SECURE (1 << 0) +#define COOKIE_PREFIX__HOST (1 << 1) + +#define COOKIE_HASH_SIZE 63 + +struct CookieInfo { + /* linked lists of cookies we know of */ + struct Curl_llist cookielist[COOKIE_HASH_SIZE]; + curl_off_t next_expiration; /* the next time at which expiration happens */ + unsigned int numcookies; /* number of cookies in the "jar" */ + unsigned int lastct; /* last creation-time used in the jar */ + BIT(running); /* state info, for cookie adding information */ + BIT(newsession); /* new session, discard session cookies on load */ +}; + +/* The maximum sizes we accept for cookies. RFC 6265 section 6.1 says + "general-use user agents SHOULD provide each of the following minimum + capabilities": + + - At least 4096 bytes per cookie (as measured by the sum of the length of + the cookie's name, value, and attributes). + In the 6265bis draft document section 5.4 it is phrased even stronger: "If + the sum of the lengths of the name string and the value string is more than + 4096 octets, abort these steps and ignore the set-cookie-string entirely." + */ + +/** Limits for INCOMING cookies **/ + +/* The longest we allow a line to be when reading a cookie from an HTTP header + or from a cookie jar */ +#define MAX_COOKIE_LINE 5000 + +/* Maximum length of an incoming cookie name or content we deal with. Longer + cookies are ignored. */ +#define MAX_NAME 4096 + +/* Maximum number of Set-Cookie: lines accepted in a single response. If more + such header lines are received, they are ignored. This value must be less + than 256 since an unsigned char is used to count. */ +#define MAX_SET_COOKIE_AMOUNT 50 + +/** Limits for OUTGOING cookies **/ + +/* Maximum size for an outgoing cookie line libcurl will use in an http + request. This is the default maximum length used in some versions of Apache + httpd. */ +#define MAX_COOKIE_HEADER_LEN 8190 + +/* Maximum number of cookies libcurl will send in a single request, even if + there might be more cookies that match. One reason to cap the number is to + keep the maximum HTTP request within the maximum allowed size. */ +#define MAX_COOKIE_SEND_AMOUNT 150 + +struct Curl_easy; +struct connectdata; + +bool Curl_secure_context(struct Curl_easy *data, const char *host); + +/* + * Add a cookie to the internal list of cookies. The domain and path arguments + * are only used if the COOKIE_HTTPHEADER bit is set in the flags. + */ + +#define COOKIE_HTTPHEADER (1<<0) /* if HTTP header-style line */ +#define COOKIE_NOEXPIRE (1<<1) /* skip remove_expired() */ +#define COOKIE_SECURE (1<<2) /* connection is over secure origin */ +#define COOKIE_NOPSL (1<<3) /* skip PSL check */ +#define COOKIE_NOSESSION (1<<6) /* drop session cookies */ + +CURLcode Curl_cookie_add(struct Curl_easy *data, + struct CookieInfo *ci, + const char *lineptr, + const char *domain, + const char *path, + const int flags) WARN_UNUSED_RESULT; +CURLcode Curl_cookie_getlist(struct Curl_easy *data, + bool *okay, const char *host, + struct Curl_llist *list) WARN_UNUSED_RESULT; +void Curl_cookie_clearall(struct CookieInfo *ci); +void Curl_cookie_clearsess(struct CookieInfo *ci); + +#if defined(CURL_DISABLE_HTTP) || defined(CURL_DISABLE_COOKIES) +#define Curl_cookie_list(x) NULL +#define Curl_cookie_loadfiles(x, y) CURLE_OK +#define Curl_cookie_init() NULL +#define Curl_cookie_run(x) Curl_nop_stmt +#define Curl_cookie_cleanup(x) Curl_nop_stmt +#define Curl_flush_cookies(x, y) Curl_nop_stmt +#else +void Curl_flush_cookies(struct Curl_easy *data, bool cleanup); +void Curl_cookie_cleanup(struct CookieInfo *ci); +struct CookieInfo *Curl_cookie_init(void); +struct curl_slist *Curl_cookie_list(struct Curl_easy *data); +CURLcode Curl_cookie_loadfiles(struct Curl_easy *data, + int flags) WARN_UNUSED_RESULT; +void Curl_cookie_run(struct Curl_easy *data); +#endif + +#endif /* HEADER_CURL_COOKIE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/creds.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/creds.c new file mode 100644 index 0000000000..5507ae86f6 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/creds.c @@ -0,0 +1,192 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include <stddef.h> /* for offsetof() */ + +#include "creds.h" +#include "curl_trc.h" +#include "strcase.h" +#include "urldata.h" + + +CURLcode Curl_creds_create(const char *user, + const char *passwd, + const char *oauth_bearer, + const char *sasl_authzid, + const char *sasl_service, + uint8_t source, + struct Curl_creds **pcreds) +{ + struct Curl_creds *creds = NULL; + size_t ulen = user ? strlen(user) : 0; + size_t plen = passwd ? strlen(passwd) : 0; + size_t olen = oauth_bearer ? strlen(oauth_bearer) : 0; + size_t salen = sasl_authzid ? strlen(sasl_authzid) : 0; + size_t sslen = sasl_service ? strlen(sasl_service) : 0; + char *s, *buf; + size_t bufsize; + CURLcode result = CURLE_OK; + + Curl_creds_unlink(pcreds); + + /* Everything empty/NULL, this is the NULL credential */ + if(!user && !passwd && !olen && !salen && !sslen) + goto out; + + if((ulen > CURL_MAX_INPUT_LENGTH) || + (plen > CURL_MAX_INPUT_LENGTH) || + (olen > CURL_MAX_INPUT_LENGTH) || + (salen > CURL_MAX_INPUT_LENGTH) || + (sslen > CURL_MAX_INPUT_LENGTH)) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + + /* null-terminator for user already part of struct */ + bufsize = ulen + plen + 1 + olen + 1 + salen + 1 + sslen + 1; + creds = curlx_calloc(1, sizeof(*creds) + bufsize); + if(!creds) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + creds->bufsize = bufsize; + creds->refcount = 1; + creds->source = source; + /* Some compilers try to be too smart about our dynamic struct size */ + buf = ((char *)creds) + offsetof(struct Curl_creds, buf); + creds->user = s = buf; + if(ulen) + memcpy(s, user, ulen + 1); + creds->passwd = s = buf + ulen + 1; + if(plen) + memcpy(s, passwd, plen + 1); + creds->oauth_bearer = s = buf + ulen + 1 + plen + 1; + if(olen) + memcpy(s, oauth_bearer, olen + 1); + creds->sasl_authzid = s = buf + ulen + 1 + plen + 1 + olen + 1; + if(salen) + memcpy(s, sasl_authzid, salen + 1); + creds->sasl_service = s = buf + ulen + 1 + plen + 1 + olen + 1 + salen + 1; + if(sslen) + memcpy(s, sasl_service, sslen + 1); + +out: + if(!result) + *pcreds = creds; + else + Curl_creds_unlink(&creds); + return result; +} + +CURLcode Curl_creds_merge(const char *user, + const char *passwd, + struct Curl_creds *creds_in, + uint8_t source, + struct Curl_creds **pcreds_out) +{ + struct Curl_creds *creds_out = NULL; + CURLcode result; + + if(!creds_in) { + result = Curl_creds_create(user, passwd, NULL, NULL, NULL, + source, &creds_out); + } + else { + result = Curl_creds_create(user ? user : Curl_creds_user(creds_in), + passwd ? passwd : Curl_creds_passwd(creds_in), + Curl_creds_oauth_bearer(creds_in), + Curl_creds_sasl_authzid(creds_in), + Curl_creds_sasl_service(creds_in), + source, &creds_out); + } + Curl_creds_link(pcreds_out, creds_out); + Curl_creds_unlink(&creds_out); + return result; +} + +void Curl_creds_link(struct Curl_creds **pdest, struct Curl_creds *src) +{ + if(*pdest != src) { + Curl_creds_unlink(pdest); + *pdest = src; + if(src) { + DEBUGASSERT(src->refcount < UINT32_MAX); + src->refcount++; + } + } +} + +void Curl_creds_unlink(struct Curl_creds **pcreds) +{ + if(*pcreds) { + struct Curl_creds *creds = *pcreds; + + DEBUGASSERT(creds->refcount); + *pcreds = NULL; + if(creds->refcount) + creds->refcount--; + if(!creds->refcount) { + curlx_memzero(creds, sizeof(*creds) + creds->bufsize); + curlx_free(creds); + } + } +} + +bool Curl_creds_same(struct Curl_creds *c1, struct Curl_creds *c2) +{ + return (c1 == c2) || + (c1 && c2 && + !Curl_timestrcmp(c1->user, c2->user) && + !Curl_timestrcmp(c1->passwd, c2->passwd) && + !Curl_timestrcmp(c1->oauth_bearer, c2->oauth_bearer) && + !Curl_timestrcmp(c1->sasl_authzid, c2->sasl_authzid) && + !Curl_timestrcmp(c1->sasl_service, c2->sasl_service)); +} + +bool Curl_creds_equal(struct Curl_creds *c1, struct Curl_creds *c2) +{ + return Curl_creds_same(c1, c2) && + ((c1 == c2) || (c1 && c2 && (c1->source == c2->source))); +} + +#ifdef CURLVERBOSE +void Curl_creds_trace(struct Curl_easy *data, struct Curl_creds *creds, + const char *msg) +{ + if(creds) { + CURL_TRC_M(data, "%s: user=%s, passwd=%s, " + "sasl_authzid=%s, oauth_bearer=%s, source=%d", + msg, + Curl_creds_user(creds), + Curl_creds_has_passwd(creds) ? "***" : "", + Curl_creds_sasl_authzid(creds), + Curl_creds_has_oauth_bearer(creds) ? "***" : "", + creds->source); + } + else + CURL_TRC_M(data, "%s: -", msg); +} +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/creds.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/creds.h new file mode 100644 index 0000000000..5db3f8f22e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/creds.h @@ -0,0 +1,92 @@ +#ifndef HEADER_CURL_CREDS_H +#define HEADER_CURL_CREDS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +struct Curl_easy; + +#define CREDS_NONE 0 /* used for default username/passwd */ +#define CREDS_URL 1 /* username/passwd from URL */ +#define CREDS_OPTION 2 /* username/passwd set with a CURLOPT_ */ +#define CREDS_NETRC 3 /* username/passwd found in netrc */ + +struct Curl_creds { + const char *user; /* non-NULL, maybe empty string */ + const char *passwd; /* non-NULL, maybe empty string */ + const char *oauth_bearer; /* non-NULL, maybe empty string */ + const char *sasl_authzid; /* non-NULL, maybe empty string */ + const char *sasl_service; /* non-NULL, maybe empty string */ + uint32_t refcount; + uint8_t source; /* CREDS_* value */ + size_t bufsize; /* extra bytes added to sizeof(struct Curl_creds) */ + char buf[1]; +}; + +CURLcode Curl_creds_create(const char *user, + const char *passwd, + const char *oauth_bearer, + const char *sasl_authzid, + const char *sasl_service, + uint8_t source, + struct Curl_creds **pcreds); + +/* Create credentials by overriding `user` and/or `passwd` in `creds_in` */ +CURLcode Curl_creds_merge(const char *user, + const char *passwd, + struct Curl_creds *creds_in, + uint8_t source, + struct Curl_creds **pcreds_out); + +/* Unlink any creds in `*pdest`, assign src, increase src + * refcount when not NULL. */ +void Curl_creds_link(struct Curl_creds **pdest, struct Curl_creds *src); + +/* Drop a reference, creds may be passed as NULL */ +void Curl_creds_unlink(struct Curl_creds **pcreds); + +/* TRUE if both creds are NULL or have same values, except source. */ +bool Curl_creds_same(struct Curl_creds *c1, struct Curl_creds *c2); + +/* TRUE if both creds are NULL or have all values equal. */ +bool Curl_creds_equal(struct Curl_creds *c1, struct Curl_creds *c2); + +/* Provides properties for creds or, if creds is NULL, the empty string */ +#define Curl_creds_has_user(c) ((c) && (c)->user[0]) +#define Curl_creds_has_passwd(c) ((c) && (c)->passwd[0]) +#define Curl_creds_has_user_or_pass(c) \ + ((c) && ((c)->user[0] || (c)->passwd[0])) +#define Curl_creds_has_oauth_bearer(c) ((c) && (c)->oauth_bearer[0]) +#define Curl_creds_has_sasl_service(c) ((c) && (c)->sasl_service[0]) +#define Curl_creds_user(c) ((c) ? (c)->user : "") +#define Curl_creds_passwd(c) ((c) ? (c)->passwd : "") +#define Curl_creds_oauth_bearer(c) ((c) ? (c)->oauth_bearer : "") +#define Curl_creds_sasl_authzid(c) ((c) ? (c)->sasl_authzid : "") +#define Curl_creds_sasl_service(c) ((c) ? (c)->sasl_service : "") + +#ifdef CURLVERBOSE +void Curl_creds_trace(struct Curl_easy *data, struct Curl_creds *creds, + const char *msg); +#endif + +#endif /* HEADER_CURL_CREDS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cshutdn.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cshutdn.c new file mode 100644 index 0000000000..10cafdd065 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cshutdn.c @@ -0,0 +1,528 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Linus Nielsen Feltzing, <linus@haxx.se> + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "url.h" +#include "cfilters.h" +#include "progress.h" +#include "multiif.h" +#include "multi_ev.h" +#include "curl_trc.h" +#include "cshutdn.h" +#include "sigpipe.h" +#include "connect.h" +#include "select.h" +#include "curlx/strparse.h" + + +struct cshutdn *Curl_cshutdn_get(struct Curl_easy *data) +{ + if(data && data->multi) + return &data->multi->cshutdn; + return NULL; +} + +static void cshutdn_run_conn_handler(struct Curl_easy *data, + struct connectdata *conn) +{ + if(!conn->bits.shutdown_handler) { + + if(conn->scheme && conn->scheme->run->disconnect) { + /* Some disconnect handlers do a blocking wait on server responses. + * FTP/IMAP/SMTP and SFTP are among them. When using the internal + * handle, set an overall short timeout so we do not hang for the + * default 120 seconds. */ + if(data->state.internal) { + data->set.timeout = DEFAULT_SHUTDOWN_TIMEOUT_MS; + Curl_pgrsTime(data, TIMER_STARTOP); + } + + /* This is set if protocol-specific cleanups should be made */ + DEBUGF(infof(data, "connection #%" FMT_OFF_T + ", shutdown protocol handler (aborted=%d)", + conn->connection_id, conn->bits.aborted)); + /* There are protocol handlers that block on retrieving + * server responses here (FTP). Set a short timeout. */ + conn->scheme->run->disconnect(data, conn, (bool)conn->bits.aborted); + } + + conn->bits.shutdown_handler = TRUE; + } +} + +static void cshutdn_run_once(struct Curl_easy *data, + struct connectdata *conn, + bool *done) +{ + CURLcode r1, r2; + bool done1, done2; + + /* We expect to be attached when called */ + DEBUGASSERT(data->conn == conn); + + if(!Curl_shutdown_started(conn, FIRSTSOCKET)) { + Curl_shutdown_start(data, FIRSTSOCKET, 0); + } + + cshutdn_run_conn_handler(data, conn); + + if(conn->bits.shutdown_filters) { + *done = TRUE; + return; + } + + if(!conn->bits.connect_only && Curl_conn_is_connected(conn, FIRSTSOCKET)) + r1 = Curl_conn_shutdown(data, FIRSTSOCKET, &done1); + else { + r1 = CURLE_OK; + done1 = TRUE; + } + + if(!conn->bits.connect_only && Curl_conn_is_connected(conn, SECONDARYSOCKET)) + r2 = Curl_conn_shutdown(data, SECONDARYSOCKET, &done2); + else { + r2 = CURLE_OK; + done2 = TRUE; + } + + /* we are done when any failed or both report success */ + *done = (r1 || r2 || (done1 && done2)); + if(*done) + conn->bits.shutdown_filters = TRUE; +} + +void Curl_conn_shutdown_once(struct Curl_easy *admin, + struct connectdata *conn, + bool *done) +{ + DEBUGASSERT(!admin->conn); + DEBUGASSERT(!admin->mid); + Curl_attach_connection(admin, conn, FALSE); + cshutdn_run_once(admin, conn, done); + CURL_TRC_M(admin, "[SHUTDOWN] shutdown, done=%d", *done); + Curl_detach_connection(admin); +} + +void Curl_conn_terminate(struct Curl_easy *admin, + struct connectdata *conn, + bool do_shutdown) +{ + bool done; + + /* there must be a connection to close */ + DEBUGASSERT(conn); + /* it must be removed from the connection pool */ + DEBUGASSERT(!conn->bits.in_cpool); + /* the transfer must be detached from the connection */ + DEBUGASSERT(admin && !admin->conn); + DEBUGASSERT(!admin->mid); + + Curl_attach_connection(admin, conn, FALSE); + + cshutdn_run_conn_handler(admin, conn); + if(do_shutdown) { + /* Make a last attempt to shutdown handlers and filters, if + * not done so already. */ + cshutdn_run_once(admin, conn, &done); + } + CURL_TRC_M(admin, "[SHUTDOWN] %sclosing connection #%" FMT_OFF_T, + conn->bits.shutdown_filters ? "" : "force ", + conn->connection_id); + Curl_conn_cf_discard_all(admin, conn, SECONDARYSOCKET); + Curl_conn_cf_discard_all(admin, conn, FIRSTSOCKET); + Curl_detach_connection(admin); + + if(admin->multi) + Curl_multi_ev_conn_done(admin->multi, admin, conn); + Curl_conn_free(admin, conn); + + if(admin->multi) { + CURL_TRC_M(admin, "[SHUTDOWN] trigger multi connchanged"); + Curl_multi_connchanged(admin->multi); + } +} + +static bool cshutdn_destroy_oldest(struct cshutdn *cshutdn, + const char *destination) +{ + struct Curl_llist_node *e; + struct connectdata *conn; + + e = Curl_llist_head(&cshutdn->list); + while(e) { + conn = Curl_node_elem(e); + if(!destination || !strcmp(destination, conn->destination)) + break; + e = Curl_node_next(e); + } + + if(e) { + struct Curl_sigpipe_ctx sigpipe_ctx; + conn = Curl_node_elem(e); + Curl_node_remove(e); + sigpipe_init(&sigpipe_ctx); + sigpipe_apply(cshutdn->multi->admin, &sigpipe_ctx); + Curl_conn_terminate(cshutdn->multi->admin, conn, FALSE); + sigpipe_restore(&sigpipe_ctx); + return TRUE; + } + return FALSE; +} + +bool Curl_cshutdn_close_oldest(struct cshutdn *cshutdn, + const char *destination) +{ + if(cshutdn) { + return cshutdn_destroy_oldest(cshutdn, destination); + } + return FALSE; +} + +#define NUM_POLLS_ON_STACK 10 + +static CURLcode cshutdn_wait(struct cshutdn *cshutdn, + int timeout_ms) +{ + struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK]; + struct curl_pollfds cpfds; + CURLcode result; + + Curl_pollfds_init(&cpfds, a_few_on_stack, NUM_POLLS_ON_STACK); + + result = Curl_cshutdn_add_pollfds(cshutdn, &cpfds); + if(result) + goto out; + + Curl_poll(cpfds.pfds, cpfds.n, CURLMIN(timeout_ms, 1000)); + +out: + Curl_pollfds_cleanup(&cpfds); + return result; +} + +static void cshutdn_perform(struct cshutdn *cshutdn, + struct Curl_sigpipe_ctx *sigpipe_ctx) +{ + struct Curl_llist_node *e = Curl_llist_head(&cshutdn->list); + struct Curl_llist_node *enext; + struct Curl_easy *admin = cshutdn->multi->admin; + struct connectdata *conn; + timediff_t next_expire_ms = 0, ms; + bool done; + + if(!e) + return; + + CURL_TRC_M(admin, "[SHUTDOWN] perform on %zu connections", + Curl_llist_count(&cshutdn->list)); + sigpipe_apply(admin, sigpipe_ctx); + while(e) { + enext = Curl_node_next(e); + conn = Curl_node_elem(e); + Curl_conn_shutdown_once(admin, conn, &done); + if(done) { + Curl_node_remove(e); + Curl_conn_terminate(admin, conn, FALSE); + } + else { + /* idata has one timer list, but maybe more than one connection. + * Set EXPIRE_SHUTDOWN to the smallest time left for all. */ + ms = Curl_conn_shutdown_timeleft(admin, conn); + if(ms && (!next_expire_ms || (ms < next_expire_ms))) + next_expire_ms = ms; + } + e = enext; + } + + if(next_expire_ms) + Curl_expire(admin, next_expire_ms, EXPIRE_SHUTDOWN); +} + +static void cshutdn_terminate_all(struct cshutdn *cshutdn, + int timeout_ms) +{ + struct Curl_easy *admin = cshutdn->multi->admin; + struct curltime started = *Curl_pgrs_now(admin); + struct Curl_llist_node *e; + struct Curl_sigpipe_ctx sigpipe_ctx; + + CURL_TRC_M(admin, "[SHUTDOWN] shutdown all"); + sigpipe_init(&sigpipe_ctx); + + while(Curl_llist_head(&cshutdn->list)) { + timediff_t spent_ms; + int remain_ms; + + cshutdn_perform(cshutdn, &sigpipe_ctx); + + if(!Curl_llist_head(&cshutdn->list)) { + CURL_TRC_M(admin, "[SHUTDOWN] shutdown finished cleanly"); + break; + } + + /* wait for activity, timeout or "nothing" */ + spent_ms = curlx_ptimediff_ms(Curl_pgrs_now(admin), &started); + if(spent_ms >= (timediff_t)timeout_ms) { + CURL_TRC_M(admin, "[SHUTDOWN] shutdown finished, %s", + (timeout_ms > 0) ? "timeout" : "best effort done"); + break; + } + + remain_ms = timeout_ms - (int)spent_ms; + if(cshutdn_wait(cshutdn, remain_ms)) { + CURL_TRC_M(admin, "[SHUTDOWN] shutdown finished, aborted"); + break; + } + } + + /* Terminate any remaining. */ + e = Curl_llist_head(&cshutdn->list); + while(e) { + struct connectdata *conn = Curl_node_elem(e); + Curl_node_remove(e); + Curl_conn_terminate(admin, conn, FALSE); + e = Curl_llist_head(&cshutdn->list); + } + DEBUGASSERT(!Curl_llist_count(&cshutdn->list)); + + sigpipe_restore(&sigpipe_ctx); +} + +int Curl_cshutdn_init(struct cshutdn *cshutdn, + struct Curl_multi *multi) +{ + DEBUGASSERT(multi); + cshutdn->multi = multi; + Curl_llist_init(&cshutdn->list, NULL); + cshutdn->initialized = TRUE; + return 0; /* good */ +} + +void Curl_cshutdn_destroy(struct cshutdn *cshutdn, + struct Curl_easy *admin) +{ + if(cshutdn->initialized && admin) { + int timeout_ms = 0; + /* for testing, run graceful shutdown */ +#ifdef DEBUGBUILD + DEBUGASSERT(!admin->mid); + { + const char *p = getenv("CURL_GRACEFUL_SHUTDOWN"); + if(p) { + curl_off_t l; + if(!curlx_str_number(&p, &l, INT_MAX)) + timeout_ms = (int)l; + } + } +#endif + + CURL_TRC_M(admin, "[SHUTDOWN] destroy, %zu connections, timeout=%dms", + Curl_llist_count(&cshutdn->list), timeout_ms); + cshutdn_terminate_all(cshutdn, timeout_ms); + } + cshutdn->multi = NULL; + cshutdn->initialized = FALSE; +} + +size_t Curl_cshutdn_count(struct cshutdn *cshutdn) +{ + if(cshutdn) { + return Curl_llist_count(&cshutdn->list); + } + return 0; +} + +size_t Curl_cshutdn_dest_count(struct cshutdn *cshutdn, + const char *destination) +{ + if(cshutdn) { + size_t n = 0; + struct Curl_llist_node *e = Curl_llist_head(&cshutdn->list); + while(e) { + struct connectdata *conn = Curl_node_elem(e); + if(!strcmp(destination, conn->destination)) + ++n; + e = Curl_node_next(e); + } + return n; + } + return 0; +} + +static CURLMcode cshutdn_update_ev(struct cshutdn *cshutdn, + struct connectdata *conn) +{ + struct Curl_easy *admin = cshutdn->multi->admin; + CURLMcode mresult; + + DEBUGASSERT(cshutdn); + DEBUGASSERT(cshutdn->multi->socket_cb); + + Curl_attach_connection(admin, conn, FALSE); + mresult = Curl_multi_ev_assess_conn(cshutdn->multi, admin, conn); + Curl_detach_connection(admin); + return mresult; +} + +void Curl_cshutdn_add(struct cshutdn *cshutdn, + struct connectdata *conn, + size_t conns_in_pool) +{ + struct Curl_easy *admin = cshutdn->multi->admin; + size_t max_total = cshutdn->multi->max_total_connections; + + /* Add the connection to our shutdown list for non-blocking shutdown + * during multi processing. */ + if(max_total > 0 && + (max_total <= (conns_in_pool + Curl_llist_count(&cshutdn->list)))) { + CURL_TRC_M(admin, "[SHUTDOWN] discarding oldest shutdown connection " + "due to connection limit of %zu", max_total); + cshutdn_destroy_oldest(cshutdn, NULL); + } + + if(cshutdn->multi->socket_cb) { + if(cshutdn_update_ev(cshutdn, conn)) { + CURL_TRC_M(admin, "[SHUTDOWN] update events failed, discarding #%" + FMT_OFF_T, conn->connection_id); + Curl_conn_terminate(admin, conn, FALSE); + return; + } + } + + Curl_llist_append(&cshutdn->list, conn, &conn->cshutdn_node); + CURL_TRC_M(admin, "[SHUTDOWN] added #%" FMT_OFF_T + " to shutdowns, now %zu conns in shutdown", + conn->connection_id, Curl_llist_count(&cshutdn->list)); +} + +void Curl_cshutdn_perform(struct cshutdn *cshutdn, + struct Curl_sigpipe_ctx *sigpipe_ctx) +{ + cshutdn_perform(cshutdn, sigpipe_ctx); +} + +/* return fd_set info about the shutdown connections */ +void Curl_cshutdn_setfds(struct cshutdn *cshutdn, + fd_set *read_fd_set, fd_set *write_fd_set, + int *maxfd) +{ + if(Curl_llist_head(&cshutdn->list)) { + struct Curl_easy *admin = cshutdn->multi->admin; + struct Curl_llist_node *e; + struct easy_pollset ps; + + Curl_pollset_init(&ps); + for(e = Curl_llist_head(&cshutdn->list); e; e = Curl_node_next(e)) { + unsigned int i; + struct connectdata *conn = Curl_node_elem(e); + CURLcode result; + + Curl_pollset_reset(&ps); + Curl_attach_connection(admin, conn, FALSE); + result = Curl_conn_adjust_pollset(admin, conn, &ps); + Curl_detach_connection(admin); + + if(result) + continue; + + for(i = 0; i < ps.n; i++) { + curl_socket_t sock = ps.sockets[i]; + if(!FDSET_SOCK(sock)) + continue; + if(ps.actions[i] & CURL_POLL_IN) + FD_SET(sock, read_fd_set); + if(ps.actions[i] & CURL_POLL_OUT) + FD_SET(sock, write_fd_set); + if((ps.actions[i] & (CURL_POLL_OUT | CURL_POLL_IN)) && + ((int)sock > *maxfd)) + *maxfd = (int)sock; + } + } + Curl_pollset_cleanup(&ps); + } +} + +/* return information about the shutdown connections */ +unsigned int Curl_cshutdn_add_waitfds(struct cshutdn *cshutdn, + struct Curl_waitfds *cwfds) +{ + unsigned int need = 0; + + if(Curl_llist_head(&cshutdn->list)) { + struct Curl_llist_node *e; + struct Curl_easy *admin = cshutdn->multi->admin; + struct easy_pollset ps; + struct connectdata *conn; + CURLcode result; + + Curl_pollset_init(&ps); + for(e = Curl_llist_head(&cshutdn->list); e; e = Curl_node_next(e)) { + conn = Curl_node_elem(e); + Curl_pollset_reset(&ps); + Curl_attach_connection(admin, conn, FALSE); + result = Curl_conn_adjust_pollset(admin, conn, &ps); + Curl_detach_connection(admin); + + if(!result) + need += Curl_waitfds_add_ps(cwfds, &ps); + } + Curl_pollset_cleanup(&ps); + } + return need; +} + +CURLcode Curl_cshutdn_add_pollfds(struct cshutdn *cshutdn, + struct curl_pollfds *cpfds) +{ + CURLcode result = CURLE_OK; + + if(Curl_llist_head(&cshutdn->list)) { + struct Curl_llist_node *e; + struct easy_pollset ps; + struct Curl_easy *admin = cshutdn->multi->admin; + struct connectdata *conn; + + Curl_pollset_init(&ps); + for(e = Curl_llist_head(&cshutdn->list); e; e = Curl_node_next(e)) { + conn = Curl_node_elem(e); + Curl_pollset_reset(&ps); + Curl_attach_connection(admin, conn, FALSE); + result = Curl_conn_adjust_pollset(admin, conn, &ps); + Curl_detach_connection(admin); + + if(!result) + result = Curl_pollfds_add_ps(cpfds, &ps); + if(result) { + Curl_pollset_cleanup(&ps); + Curl_pollfds_cleanup(cpfds); + goto out; + } + } + Curl_pollset_cleanup(&ps); + } +out: + return result; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cshutdn.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cshutdn.h new file mode 100644 index 0000000000..a0338f6488 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cshutdn.h @@ -0,0 +1,105 @@ +#ifndef HEADER_CURL_CSHUTDN_H +#define HEADER_CURL_CSHUTDN_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) Linus Nielsen Feltzing, <linus@haxx.se> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +struct connectdata; +struct Curl_easy; +struct curl_pollfds; +struct Curl_waitfds; +struct Curl_multi; +struct Curl_share; +struct Curl_sigpipe_ctx; + +/* Run the shutdown of the connection once. + * Shortly attach/detach the admin handle to `conn` while doing so. + * `done` will be set TRUE if any error was encountered or if + * the connection was shut down completely. */ +void Curl_conn_shutdown_once(struct Curl_easy *admin, + struct connectdata *conn, + bool *done); + +/* Terminates the connection, e.g. closes and destroys it. + * If `do_shutdown` is TRUE, the shutdown will be run once before + * terminating it. + * Takes ownership of `conn`. */ +void Curl_conn_terminate(struct Curl_easy *admin, + struct connectdata *conn, + bool do_shutdown); + +/* A `cshutdown` is always owned by a multi handle to maintain + * the connections to be shut down. It registers timers and + * sockets to monitor via the multi handle. */ +struct cshutdn { + struct Curl_llist list; /* connections being shut down */ + struct Curl_multi *multi; /* the multi owning this */ + BIT(initialized); +}; + +/* Get the cshutdn instance relevant for `data` or NULL if there is none */ +struct cshutdn *Curl_cshutdn_get(struct Curl_easy *data); + +/* Init as part of the given multi handle. */ +int Curl_cshutdn_init(struct cshutdn *cshutdn, + struct Curl_multi *multi); + +/* Terminate all remaining connections and free resources. */ +void Curl_cshutdn_destroy(struct cshutdn *cshutdn, + struct Curl_easy *admin); + +/* Number of connections being shut down. */ +size_t Curl_cshutdn_count(struct cshutdn *cshutdn); + +/* Number of connections to the destination being shut down. */ +size_t Curl_cshutdn_dest_count(struct cshutdn *cshutdn, + const char *destination); + +/* Close the oldest connection in shutdown to destination or, + * when destination is NULL for any destination. + * Return TRUE if a connection has been closed. */ +bool Curl_cshutdn_close_oldest(struct cshutdn *cshutdn, + const char *destination); + +/* Add a connection to have it shut down. Terminate the oldest + * connection when total connection limit of multi is being reached. */ +void Curl_cshutdn_add(struct cshutdn *cshutdn, + struct connectdata *conn, + size_t conns_in_pool); + +/* Add sockets and POLLIN/OUT flags for connections being shut down. */ +CURLcode Curl_cshutdn_add_pollfds(struct cshutdn *cshutdn, + struct curl_pollfds *cpfds); + +unsigned int Curl_cshutdn_add_waitfds(struct cshutdn *cshutdn, + struct Curl_waitfds *cwfds); + +void Curl_cshutdn_setfds(struct cshutdn *cshutdn, + fd_set *read_fd_set, fd_set *write_fd_set, + int *maxfd); + +/* Run maintenance on all connections. */ +void Curl_cshutdn_perform(struct cshutdn *cshutdn, + struct Curl_sigpipe_ctx *sigpipe_ctx); + +#endif /* HEADER_CURL_CSHUTDN_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_addrinfo.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_addrinfo.c new file mode 100644 index 0000000000..98ba7aec1c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_addrinfo.c @@ -0,0 +1,647 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETINET_IN6_H +#include <netinet/in6.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_SYS_UN_H +#include <sys/un.h> +#endif + +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include <stddef.h> /* for offsetof() */ + +#include "curl_addrinfo.h" +#include "fake_addrinfo.h" +#include "curlx/inet_pton.h" +#include "curlx/strparse.h" + +/* + * Curl_freeaddrinfo() + * + * This is used to free a linked list of Curl_addrinfo structs along + * with all its associated allocated storage. This function should be + * called once for each successful call to Curl_getaddrinfo_ex() or to + * any function call which actually allocates a Curl_addrinfo struct. + */ + +#if defined(__INTEL_COMPILER) && (__INTEL_COMPILER == 910) && \ + defined(__OPTIMIZE__) && defined(__unix__) && defined(__i386__) + /* workaround icc 9.1 optimizer issue */ +# define vqualifier volatile +#else +# define vqualifier +#endif + +void Curl_freeaddrinfo(struct Curl_addrinfo *cahead) +{ + struct Curl_addrinfo *vqualifier canext; + struct Curl_addrinfo *ca; + + for(ca = cahead; ca; ca = canext) { + canext = ca->ai_next; + curlx_free(ca); + } +} + +struct Curl_addrinfo *Curl_addrinfo_get(struct Curl_addrinfo *ai, + int ai_family, + unsigned int n) +{ + unsigned int i; + for(i = 0; ai; ai = ai->ai_next) { + if(ai->ai_family == ai_family) { + if(i == n) + return ai; + ++i; + } + } + return NULL; +} + +#ifdef HAVE_GETADDRINFO +/* + * Curl_getaddrinfo_ex() + * + * This is a wrapper function around system's getaddrinfo(), with + * the only difference that instead of returning a linked list of + * addrinfo structs this one returns a linked list of Curl_addrinfo + * ones. The memory allocated by this function *MUST* be free'd with + * Curl_freeaddrinfo(). For each successful call to this function + * there must be an associated call later to Curl_freeaddrinfo(). + * + * There should be no single call to system's getaddrinfo() in the + * whole library, any such call should be 'routed' through this one. + */ +int Curl_getaddrinfo_ex(const char *nodename, + const char *servname, + const struct addrinfo *hints, + struct Curl_addrinfo **result) +{ + const struct addrinfo *ai; + struct addrinfo *aihead; + struct Curl_addrinfo *cafirst = NULL; + struct Curl_addrinfo *calast = NULL; + struct Curl_addrinfo *ca; + size_t ss_size; + int error; + + *result = NULL; /* assume failure */ + + error = CURL_GETADDRINFO(nodename, servname, hints, &aihead); + if(error) + return error; + + /* traverse the addrinfo list */ + + for(ai = aihead; ai; ai = ai->ai_next) { + size_t namelen = ai->ai_canonname ? strlen(ai->ai_canonname) + 1 : 0; + /* ignore elements with unsupported address family, + settle family-specific sockaddr structure size. */ + if(ai->ai_family == AF_INET) + ss_size = sizeof(struct sockaddr_in); +#ifdef USE_IPV6 + else if(ai->ai_family == AF_INET6) + ss_size = sizeof(struct sockaddr_in6); +#endif + else + continue; + + /* ignore elements without required address info */ + if(!ai->ai_addr || !(ai->ai_addrlen > 0)) + continue; + + /* ignore elements with bogus address size */ + if((size_t)ai->ai_addrlen < ss_size) + continue; + + ca = curlx_malloc(sizeof(struct Curl_addrinfo) + ss_size + namelen); + if(!ca) { + error = EAI_MEMORY; + break; + } + + /* copy each structure member individually, member ordering, + size, or padding might be different for each platform. */ + + ca->ai_flags = ai->ai_flags; + ca->ai_family = ai->ai_family; + ca->ai_socktype = ai->ai_socktype; + ca->ai_protocol = ai->ai_protocol; + ca->ai_addrlen = (curl_socklen_t)ss_size; + ca->ai_addr = NULL; + ca->ai_canonname = NULL; + ca->ai_next = NULL; + + ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo)); + memcpy(ca->ai_addr, ai->ai_addr, ss_size); + + if(namelen) { + ca->ai_canonname = (void *)((char *)ca->ai_addr + ss_size); + memcpy(ca->ai_canonname, ai->ai_canonname, namelen); + } + + /* if the return list is empty, this becomes the first element */ + if(!cafirst) + cafirst = ca; + + /* add this element last in the return list */ + if(calast) + calast->ai_next = ca; + calast = ca; + } + + /* destroy the addrinfo list */ + if(aihead) + CURL_FREEADDRINFO(aihead); + + /* if we failed, also destroy the Curl_addrinfo list */ + if(error) { + Curl_freeaddrinfo(cafirst); + cafirst = NULL; + } + else if(!cafirst) { +#ifdef EAI_NONAME + /* rfc3493 conformant */ + error = EAI_NONAME; +#else + /* rfc3493 obsoleted */ + error = EAI_NODATA; +#endif +#ifdef USE_WINSOCK + SET_SOCKERRNO(error); +#endif + } + + *result = cafirst; + + /* This is not a CURLcode */ + return error; +} +#endif /* HAVE_GETADDRINFO */ + +/* + * Curl_he2ai() + * + * This function returns a pointer to the first element of a newly allocated + * Curl_addrinfo struct linked list filled with the data of a given hostent. + * Curl_addrinfo is meant to work like the addrinfo struct does for an IPv6 + * stack, but usable also for IPv4, all hosts and environments. + * + * The memory allocated by this function *MUST* be free'd later on calling + * Curl_freeaddrinfo(). For each successful call to this function there + * must be an associated call later to Curl_freeaddrinfo(). + * + * Curl_addrinfo defined in "lib/curl_addrinfo.h" + * + * struct Curl_addrinfo { + * int ai_flags; + * int ai_family; + * int ai_socktype; + * int ai_protocol; + * curl_socklen_t ai_addrlen; * Follow rfc3493 struct addrinfo * + * char *ai_canonname; + * struct sockaddr *ai_addr; + * struct Curl_addrinfo *ai_next; + * }; + * + * hostent defined in <netdb.h> + * + * struct hostent { + * char *h_name; + * char **h_aliases; + * int h_addrtype; + * int h_length; + * char **h_addr_list; + * }; + * + * for backward compatibility: + * + * #define h_addr h_addr_list[0] + */ +#if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETADDRINFO_THREADSAFE)) +struct Curl_addrinfo *Curl_he2ai(const struct hostent *he, int port) +{ + struct Curl_addrinfo *ai; + struct Curl_addrinfo *prevai = NULL; + struct Curl_addrinfo *firstai = NULL; + struct sockaddr_in *addr; +#ifdef USE_IPV6 + struct sockaddr_in6 *addr6; +#endif + CURLcode result = CURLE_OK; + int i; + char *curr; + + if(!he) + /* no input == no output! */ + return NULL; + + DEBUGASSERT(he->h_name && he->h_addr_list); + + for(i = 0; (curr = he->h_addr_list[i]) != NULL; i++) { + size_t ss_size; + size_t namelen = strlen(he->h_name) + 1; /* include null-terminator */ +#ifdef USE_IPV6 + if(he->h_addrtype == AF_INET6) + ss_size = sizeof(struct sockaddr_in6); + else +#endif + ss_size = sizeof(struct sockaddr_in); + + /* allocate memory to hold the struct, the address and the name */ + ai = curlx_calloc(1, sizeof(struct Curl_addrinfo) + ss_size + namelen); + if(!ai) { + result = CURLE_OUT_OF_MEMORY; + break; + } + /* put the address after the struct */ + ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo)); + /* then put the name after the address */ + ai->ai_canonname = (char *)ai->ai_addr + ss_size; + memcpy(ai->ai_canonname, he->h_name, namelen); + + if(!firstai) + /* store the pointer we want to return from this function */ + firstai = ai; + + if(prevai) + /* make the previous entry point to this */ + prevai->ai_next = ai; + + ai->ai_family = he->h_addrtype; + + /* we return all names as STREAM, so when using this address for TFTP + the type must be ignored and conn->socktype be used instead! */ + ai->ai_socktype = SOCK_STREAM; + + ai->ai_addrlen = (curl_socklen_t)ss_size; + + /* leave the rest of the struct filled with zero */ + + switch(ai->ai_family) { + case AF_INET: + addr = (void *)ai->ai_addr; /* storage area for this info */ + + memcpy(&addr->sin_addr, curr, sizeof(struct in_addr)); + addr->sin_family = (CURL_SA_FAMILY_T)(he->h_addrtype); + addr->sin_port = htons((unsigned short)port); + break; + +#ifdef USE_IPV6 + case AF_INET6: + addr6 = (void *)ai->ai_addr; /* storage area for this info */ + + memcpy(&addr6->sin6_addr, curr, sizeof(struct in6_addr)); + addr6->sin6_family = (CURL_SA_FAMILY_T)(he->h_addrtype); + addr6->sin6_port = htons((unsigned short)port); + break; +#endif + } + + prevai = ai; + } + + if(result) { + Curl_freeaddrinfo(firstai); + firstai = NULL; + } + + return firstai; +} +#endif + +/* + * ip2addr() + * + * This function takes an Internet address, in binary form, as input parameter + * along with its address family and the string version of the address, and it + * returns a Curl_addrinfo chain filled in correctly with information for the + * given address/host + */ +static CURLcode ip2addr(struct Curl_addrinfo **addrp, int af, + const void *inaddr, const char *hostname, int port) +{ + struct Curl_addrinfo *ai; + size_t addrsize; + size_t namelen; + struct sockaddr_in *addr; +#ifdef USE_IPV6 + struct sockaddr_in6 *addr6; +#endif + + DEBUGASSERT(inaddr && hostname); + + namelen = strlen(hostname) + 1; + *addrp = NULL; + + if(af == AF_INET) + addrsize = sizeof(struct sockaddr_in); +#ifdef USE_IPV6 + else if(af == AF_INET6) + addrsize = sizeof(struct sockaddr_in6); +#endif + else + return CURLE_BAD_FUNCTION_ARGUMENT; + + /* allocate memory to hold the struct, the address and the name */ + ai = curlx_calloc(1, sizeof(struct Curl_addrinfo) + addrsize + namelen); + if(!ai) + return CURLE_OUT_OF_MEMORY; + /* put the address after the struct */ + ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo)); + /* then put the name after the address */ + ai->ai_canonname = (char *)ai->ai_addr + addrsize; + memcpy(ai->ai_canonname, hostname, namelen); + ai->ai_family = af; + ai->ai_socktype = SOCK_STREAM; + ai->ai_addrlen = (curl_socklen_t)addrsize; + /* leave the rest of the struct filled with zero */ + + switch(af) { + case AF_INET: + addr = (void *)ai->ai_addr; /* storage area for this info */ + + memcpy(&addr->sin_addr, inaddr, sizeof(struct in_addr)); + addr->sin_family = (CURL_SA_FAMILY_T)af; + addr->sin_port = htons((unsigned short)port); + break; + +#ifdef USE_IPV6 + case AF_INET6: + addr6 = (void *)ai->ai_addr; /* storage area for this info */ + + memcpy(&addr6->sin6_addr, inaddr, sizeof(struct in6_addr)); + addr6->sin6_family = (CURL_SA_FAMILY_T)af; + addr6->sin6_port = htons((unsigned short)port); + break; +#endif + } + *addrp = ai; + return CURLE_OK; +} + +/* + * Given an IPv4 or IPv6 dotted string address, this converts it to a proper + * allocated Curl_addrinfo struct and returns it. + */ +CURLcode Curl_str2addr(const char *dotted, uint16_t port, + struct Curl_addrinfo **addrp) +{ + struct in_addr in; + if(curlx_inet_pton(AF_INET, dotted, &in) > 0) + /* This is a dotted IP address 123.123.123.123-style */ + return ip2addr(addrp, AF_INET, &in, dotted, port); +#ifdef USE_IPV6 + { + struct in6_addr in6; + if(curlx_inet_pton(AF_INET6, dotted, &in6) > 0) + /* This is a dotted IPv6 address ::1-style */ + return ip2addr(addrp, AF_INET6, &in6, dotted, port); + } +#endif + return CURLE_BAD_FUNCTION_ARGUMENT; /* bad input format */ +} + +bool Curl_is_ipv4addr(const char *address) +{ + struct in_addr in; + return (curlx_inet_pton(AF_INET, address, &in) > 0); +} + +bool Curl_is_ipaddr(const char *address) +{ + if(Curl_is_ipv4addr(address)) + return TRUE; +#ifdef USE_IPV6 + { + struct in6_addr in6; + if(curlx_inet_pton(AF_INET6, address, &in6) > 0) + /* This is a dotted IPv6 address ::1-style */ + return TRUE; + } +#endif + return FALSE; +} + +bool Curl_looks_like_ipv6(const char *s, size_t len, bool maybe_url_encoded, + struct Curl_str *host, struct Curl_str *zone) +{ + const char *zonep = NULL; + size_t i = 0, hlen = 0, zlen = 0; + + if(host) + memset(host, 0, sizeof(*host)); + if(zone) + memset(zone, 0, sizeof(*zone)); + + for(i = 0; i < len; ++i, ++hlen) { + if(!s[i] || !(ISXDIGIT(s[i]) || (s[i] == ':') || (s[i] == '.'))) + break; + } + + if((i < len) && (s[i] == '%')) { /* address followed by a zone? */ + i += 1; + if(maybe_url_encoded && !strncmp("25", s + i, 2)) + i += 2; + zonep = s + i; + for(; i < len; ++i, ++zlen) { + /* Allow unreserved characters as defined in RFC 3986 */ + if(!s[i] || !(ISALPHA(s[i]) || ISXDIGIT(s[i]) || (s[i] == '-') || + (s[i] == '.') || (s[i] == '_') || (s[i] == '~'))) + break; + } + } + + if(i != len) + return FALSE; /* invalid chars in zone */ + if(host && hlen) { + host->str = s; + host->len = hlen; + } + if(zone && zlen) { + zone->str = zonep; + zone->len = zlen; + } + return TRUE; +} + +#ifdef USE_UNIX_SOCKETS +/** + * Given a path to a Unix domain socket, return a newly allocated Curl_addrinfo + * struct initialized with this path. + * Returns CURLE_TOO_LARGE when path is too long. + */ +CURLcode Curl_unix2addr(const char *path, bool abstract, + struct Curl_addrinfo **paddr) +{ + struct Curl_addrinfo *ai; + struct sockaddr_un *sa_un; + size_t path_len; + + *paddr = NULL; + + /* sun_path must be able to store the null-terminated path */ + path_len = strlen(path) + 1; + if(path_len > sizeof(sa_un->sun_path)) + return CURLE_TOO_LARGE; + + ai = curlx_calloc(1, + sizeof(struct Curl_addrinfo) + sizeof(struct sockaddr_un)); + if(!ai) + return CURLE_OUT_OF_MEMORY; + + ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo)); + sa_un = (void *)ai->ai_addr; + sa_un->sun_family = AF_UNIX; + + ai->ai_family = AF_UNIX; + ai->ai_socktype = SOCK_STREAM; /* assume reliable transport for HTTP */ + ai->ai_addrlen = (curl_socklen_t) + ((offsetof(struct sockaddr_un, sun_path) + path_len) & 0x7FFFFFFF); + + /* Abstract Unix domain socket have NULL prefix instead of suffix */ + if(abstract) + memcpy(sa_un->sun_path + 1, path, path_len - 1); + else + memcpy(sa_un->sun_path, path, path_len); /* copy NUL byte */ + + *paddr = ai; + return CURLE_OK; +} +#endif + +#if defined(CURL_MEMDEBUG) && defined(HAVE_GETADDRINFO) && \ + defined(HAVE_FREEADDRINFO) +/* + * curl_dbg_freeaddrinfo() + * + * This is strictly for memory tracing and are using the same style as the + * family otherwise present in memdebug.c. I put these ones here since they + * require a bunch of structs I did not want to include in memdebug.c + */ +void curl_dbg_freeaddrinfo(struct addrinfo *freethis, + int line, const char *source) +{ + curl_dbg_log("ADDR %s:%d freeaddrinfo(%p)\n", + source, line, (void *)freethis); +#ifdef USE_LWIPSOCK + lwip_freeaddrinfo(freethis); +#elif defined(USE_FAKE_GETADDRINFO) + { + const char *env = getenv("CURL_DNS_SERVER"); + if(env) + r_freeaddrinfo(freethis); + else + /* !checksrc! disable BANNEDFUNC 1 */ + freeaddrinfo(freethis); + } +#else + /* !checksrc! disable BANNEDFUNC 1 */ + freeaddrinfo(freethis); +#endif +} +#endif /* CURL_MEMDEBUG && HAVE_FREEADDRINFO */ + +#if defined(CURL_MEMDEBUG) && defined(HAVE_GETADDRINFO) +/* + * curl_dbg_getaddrinfo() + * + * This is strictly for memory tracing and are using the same style as the + * family otherwise present in memdebug.c. I put these ones here since they + * require a bunch of structs I did not want to include in memdebug.c + */ +int curl_dbg_getaddrinfo(const char *hostname, + const char *service, + const struct addrinfo *hints, + struct addrinfo **result, + int line, const char *source) +{ +#ifdef USE_LWIPSOCK + int res = lwip_getaddrinfo(hostname, service, hints, result); +#elif defined(USE_FAKE_GETADDRINFO) + int res; + const char *env = getenv("CURL_DNS_SERVER"); + if(env) + res = r_getaddrinfo(hostname, service, hints, result); + else + /* !checksrc! disable BANNEDFUNC 1 */ + res = getaddrinfo(hostname, service, hints, result); +#else + /* !checksrc! disable BANNEDFUNC 1 */ + int res = getaddrinfo(hostname, service, hints, result); +#endif + if(res == 0) + /* success */ + curl_dbg_log("ADDR %s:%d getaddrinfo() = %p\n", source, line, + (void *)*result); + else + curl_dbg_log("ADDR %s:%d getaddrinfo() failed\n", source, line); + return res; +} +#endif /* CURL_MEMDEBUG && HAVE_GETADDRINFO */ + +#if defined(HAVE_GETADDRINFO) && defined(USE_RESOLVE_ON_IPS) +/* + * Works around the sin6_port is always zero bug on iOS 9.3.2 and macOS + * 10.11.5. + */ +void Curl_addrinfo_set_port(struct Curl_addrinfo *addrinfo, int port) +{ + struct Curl_addrinfo *ca; + struct sockaddr_in *addr; +#ifdef USE_IPV6 + struct sockaddr_in6 *addr6; +#endif + for(ca = addrinfo; ca; ca = ca->ai_next) { + switch(ca->ai_family) { + case AF_INET: + addr = (void *)ca->ai_addr; /* storage area for this info */ + addr->sin_port = htons((unsigned short)port); + break; + +#ifdef USE_IPV6 + case AF_INET6: + addr6 = (void *)ca->ai_addr; /* storage area for this info */ + addr6->sin6_port = htons((unsigned short)port); + break; +#endif + } + } +} +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_addrinfo.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_addrinfo.h new file mode 100644 index 0000000000..7b2b4d2834 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_addrinfo.h @@ -0,0 +1,115 @@ +#ifndef HEADER_CURL_ADDRINFO_H +#define HEADER_CURL_ADDRINFO_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +# include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +# include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +# include <arpa/inet.h> +#endif + +#ifdef __VMS +# include <in.h> +# include <inet.h> +#endif + +struct Curl_str; + +/* + * Curl_addrinfo is our internal struct definition that we use to allow + * consistent internal handling of this data. We use this even when the system + * provides an addrinfo structure definition. We use this for all sorts of + * IPv4 and IPV6 builds. + */ + +struct Curl_addrinfo { + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + curl_socklen_t ai_addrlen; /* Follow rfc3493 struct addrinfo */ + char *ai_canonname; + struct sockaddr *ai_addr; + struct Curl_addrinfo *ai_next; +}; + +void Curl_freeaddrinfo(struct Curl_addrinfo *cahead); + +/* Get the n-th addrinfo of family ai_family. */ +struct Curl_addrinfo *Curl_addrinfo_get(struct Curl_addrinfo *ai, + int ai_family, + unsigned int n); + +#ifdef HAVE_GETADDRINFO +int Curl_getaddrinfo_ex(const char *nodename, + const char *servname, + const struct addrinfo *hints, + struct Curl_addrinfo **result); +#endif + +#if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETADDRINFO_THREADSAFE)) +struct Curl_addrinfo *Curl_he2ai(const struct hostent *he, int port); +#endif + +bool Curl_is_ipv4addr(const char *address); +bool Curl_is_ipaddr(const char *address); +bool Curl_looks_like_ipv6(const char *s, size_t len, bool maybe_url_encoded, + struct Curl_str *host, struct Curl_str *zone); + +CURLcode Curl_str2addr(const char *dotted, uint16_t port, + struct Curl_addrinfo **addrp); + +#ifdef USE_UNIX_SOCKETS +CURLcode Curl_unix2addr(const char *path, bool abstract, + struct Curl_addrinfo **paddr); +#endif + +#if defined(CURL_MEMDEBUG) && defined(HAVE_GETADDRINFO) && \ + defined(HAVE_FREEADDRINFO) +void curl_dbg_freeaddrinfo(struct addrinfo *freethis, int line, + const char *source); +#endif + +#if defined(CURL_MEMDEBUG) && defined(HAVE_GETADDRINFO) +int curl_dbg_getaddrinfo(const char *hostname, const char *service, + const struct addrinfo *hints, + struct addrinfo **result, int line, + const char *source); +#endif + +#ifdef HAVE_GETADDRINFO +#ifdef USE_RESOLVE_ON_IPS +void Curl_addrinfo_set_port(struct Curl_addrinfo *addrinfo, int port); +#else +#define Curl_addrinfo_set_port(x, y) +#endif +#endif + +#endif /* HEADER_CURL_ADDRINFO_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_config.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_config.h new file mode 100644 index 0000000000..2fe27e3529 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_config.h @@ -0,0 +1,154 @@ +/* Generated by curl 8.22.0 configure for 64-bit iOS; see README.md. */ +#define CURL_DISABLE_ALTSVC 1 +#define CURL_DISABLE_COOKIES 1 +#define CURL_DISABLE_DICT 1 +#define CURL_DISABLE_FILE 1 +#define CURL_DISABLE_GOPHER 1 +#define CURL_DISABLE_HSTS 1 +#define CURL_DISABLE_HTTP 1 +#define CURL_DISABLE_HTTPSIG 1 +#define CURL_DISABLE_IMAP 1 +#define CURL_DISABLE_IPFS 1 +#define CURL_DISABLE_LDAP 1 +#define CURL_DISABLE_LDAPS 1 +#define CURL_DISABLE_LIBCURL_OPTION 1 +#define CURL_DISABLE_MQTT 1 +#define CURL_DISABLE_POP3 1 +#define CURL_DISABLE_PROXY 1 +#define CURL_DISABLE_RTSP 1 +#define CURL_DISABLE_SMTP 1 +#define CURL_DISABLE_TELNET 1 +#define CURL_DISABLE_TFTP 1 +#define CURL_DISABLE_WEBSOCKETS 1 +#define CURL_EXTERN_SYMBOL __attribute__((__visibility__("default"))) +#define CURL_OS "aarch64-apple-darwin" +#define GETHOSTNAME_TYPE_ARG2 size_t +#define HAVE_ALARM 1 +#define HAVE_ARPA_INET_H 1 +#define HAVE_ATOMIC 1 +#define HAVE_BASENAME 1 +#define HAVE_BOOL_T 1 +#define HAVE_BUILTIN_AVAILABLE 1 +#define HAVE_CLOCK_GETTIME_MONOTONIC 1 +#define HAVE_CLOCK_GETTIME_MONOTONIC_RAW 1 +#define HAVE_DECL_FSEEKO 1 +#define HAVE_DES_ECB_ENCRYPT 1 +#define HAVE_DIRENT_H 1 +#define HAVE_DLFCN_H 1 +#define HAVE_FCNTL 1 +#define HAVE_FCNTL_H 1 +#define HAVE_FCNTL_O_NONBLOCK 1 +#define HAVE_FNMATCH 1 +#define HAVE_FREEADDRINFO 1 +#define HAVE_FSEEKO 1 +#define HAVE_FSETXATTR 1 +#define HAVE_FSETXATTR_6 1 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETADDRINFO_THREADSAFE 1 +#define HAVE_GETEUID 1 +#define HAVE_GETHOSTNAME 1 +#define HAVE_GETIFADDRS 1 +#define HAVE_GETPEERNAME 1 +#define HAVE_GETPPID 1 +#define HAVE_GETPWUID 1 +#define HAVE_GETPWUID_R 1 +#define HAVE_GETRLIMIT 1 +#define HAVE_GETSOCKNAME 1 +#define HAVE_GETTIMEOFDAY 1 +#define HAVE_GMTIME_R 1 +#define HAVE_IFADDRS_H 1 +#define HAVE_IF_NAMETOINDEX 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_IOCTL_FIONBIO 1 +#define HAVE_IOCTL_SIOCGIFADDR 1 +#define HAVE_LIBGEN_H 1 +#define HAVE_LIBSSL 1 +#define HAVE_LOCALE_H 1 +#define HAVE_LOCALTIME_R 1 +#define HAVE_MACH_ABSOLUTE_TIME 1 +#define HAVE_MEMSET_S 1 +#define HAVE_NETDB_H 1 +#define HAVE_NETINET_IN_H 1 +#define HAVE_NETINET_IP_H 1 +#define HAVE_NETINET_TCP_H 1 +#define HAVE_NETINET_UDP_H 1 +#define HAVE_NET_IF_H 1 +#define HAVE_OPENDIR 1 +#define HAVE_OPENSSL_CRYPTO_H 1 +#define HAVE_OPENSSL_ERR_H 1 +#define HAVE_OPENSSL_PEM_H 1 +#define HAVE_OPENSSL_RSA_H 1 +#define HAVE_OPENSSL_SSL_H 1 +#define HAVE_PIPE 1 +#define HAVE_POLL 1 +#define HAVE_POLL_H 1 +#define HAVE_POSIX_STRERROR_R 1 +#define HAVE_PWD_H 1 +#define HAVE_REALPATH 1 +#define HAVE_RECV 1 +#define HAVE_SA_FAMILY_T 1 +#define HAVE_SCHED_YIELD 1 +#define HAVE_SEND 1 +#define HAVE_SENDMSG 1 +#define HAVE_SETLOCALE 1 +#define HAVE_SETRLIMIT 1 +#define HAVE_SIGACTION 1 +#define HAVE_SIGINTERRUPT 1 +#define HAVE_SIGNAL 1 +#define HAVE_SIGSETJMP 1 +#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 +#define HAVE_SOCKET 1 +#define HAVE_SOCKETPAIR 1 +#define HAVE_SSL_SET0_WBIO 1 +#define HAVE_SSL_SET_QUIC_TLS_CBS 1 +#define HAVE_STDATOMIC_H 1 +#define HAVE_STDBOOL_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STRCASECMP 1 +#define HAVE_STRERROR_R 1 +#define HAVE_STRINGS_H 1 +#define HAVE_STRING_H 1 +#define HAVE_STRUCT_SOCKADDR_STORAGE 1 +#define HAVE_STRUCT_TIMEVAL 1 +#define HAVE_SUSECONDS_T 1 +#define HAVE_SYS_FILIO_H 1 +#define HAVE_SYS_IOCTL_H 1 +#define HAVE_SYS_PARAM_H 1 +#define HAVE_SYS_POLL_H 1 +#define HAVE_SYS_RESOURCE_H 1 +#define HAVE_SYS_SELECT_H 1 +#define HAVE_SYS_SOCKIO_H 1 +#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_SYS_UN_H 1 +#define HAVE_SYS_XATTR_H 1 +#define HAVE_TERMIOS_H 1 +#define HAVE_THREADS_POSIX 1 +#define HAVE_UNISTD_H 1 +#define HAVE_UTIME 1 +#define HAVE_UTIMES 1 +#define HAVE_UTIME_H 1 +#define HAVE_WRITABLE_ARGV 1 +#define LT_OBJDIR ".libs/" +#define PACKAGE "curl" +#define PACKAGE_BUGREPORT "a suitable curl mailing list: https://curl.se/mail/" +#define PACKAGE_NAME "curl" +#define PACKAGE_STRING "curl -" +#define PACKAGE_TARNAME "curl" +#define PACKAGE_URL "" +#define PACKAGE_VERSION "-" +#define SIZEOF_CURL_OFF_T 8 +#define SIZEOF_CURL_SOCKET_T 4 +#define SIZEOF_INT 4 +#define SIZEOF_LONG 8 +#define SIZEOF_OFF_T 8 +#define SIZEOF_SIZE_T 8 +#define SIZEOF_TIME_T 8 +#define STDC_HEADERS 1 +#define USE_IPV6 1 +#define USE_OPENSSL 1 +#define USE_RESOLV_THREADED 1 +#define USE_UNIX_SOCKETS 1 +#define VERSION "-" diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ctype.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ctype.h new file mode 100644 index 0000000000..fd6b7d723c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ctype.h @@ -0,0 +1,50 @@ +#ifndef HEADER_CURL_CTYPE_H +#define HEADER_CURL_CTYPE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#define ISLOWHEXALPHA(x) (((x) >= 'a') && ((x) <= 'f')) +#define ISUPHEXALPHA(x) (((x) >= 'A') && ((x) <= 'F')) + +#define ISLOWCNTRL(x) ((unsigned char)(x) <= 0x1f) +#define IS7F(x) ((x) == 0x7f) + +#define ISPRINT(x) (((x) >= ' ') && ((x) <= 0x7e)) +#define ISGRAPH(x) (((x) > ' ') && ((x) <= 0x7e)) +#define ISCNTRL(x) (ISLOWCNTRL(x) || IS7F(x)) +#define ISALPHA(x) (ISLOWER(x) || ISUPPER(x)) +#define ISXDIGIT(x) (ISDIGIT(x) || ISLOWHEXALPHA(x) || ISUPHEXALPHA(x)) +#define ISODIGIT(x) (((x) >= '0') && ((x) <= '7')) +#define ISALNUM(x) (ISDIGIT(x) || ISLOWER(x) || ISUPPER(x)) +#define ISUPPER(x) (((x) >= 'A') && ((x) <= 'Z')) +#define ISLOWER(x) (((x) >= 'a') && ((x) <= 'z')) +#define ISDIGIT(x) (((x) >= '0') && ((x) <= '9')) +#define ISBLANK(x) (((x) == ' ') || ((x) == '\t')) +#define ISSPACE(x) (ISBLANK(x) || (((x) >= 0xa) && ((x) <= 0x0d))) +#define ISURLPUNTCS(x) \ + (((x) == '-') || ((x) == '.') || ((x) == '_') || ((x) == '~')) +#define ISUNRESERVED(x) (ISALNUM(x) || ISURLPUNTCS(x)) +#define ISNEWLINE(x) (((x) == '\n') || (x) == '\r') + +#endif /* HEADER_CURL_CTYPE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ed25519.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ed25519.c new file mode 100644 index 0000000000..44311ec54e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ed25519.c @@ -0,0 +1,175 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HTTPSIG) + +/* Please keep the SSL backend-specific #if branches in this order: + * + * 1. USE_OPENSSL + * 2. USE_WOLFSSL + * 3. USE_GNUTLS + * 4. USE_MBEDTLS + */ + +#include "curl_ed25519.h" + +#ifdef USE_WOLFSSL +#include <wolfssl/options.h> +#include <wolfssl/wolfcrypt/settings.h> +#endif + +#ifdef USE_OPENSSL +#include <openssl/evp.h> + +CURLcode Curl_ed25519_sign(const unsigned char *key, size_t keylen, + const unsigned char *msg, size_t msglen, + unsigned char *sig, size_t *siglen) +{ + EVP_PKEY *pkey; + EVP_MD_CTX *mdctx; + size_t slen; + int rc; + + if(keylen != CURL_ED25519_KEYLEN) + return CURLE_BAD_FUNCTION_ARGUMENT; + + pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, NULL, key, keylen); + if(!pkey) + return CURLE_AUTH_ERROR; + + mdctx = EVP_MD_CTX_new(); + if(!mdctx) { + EVP_PKEY_free(pkey); + return CURLE_OUT_OF_MEMORY; + } + + rc = EVP_DigestSignInit(mdctx, NULL, NULL, NULL, pkey); + if(rc != 1) { + EVP_MD_CTX_free(mdctx); + EVP_PKEY_free(pkey); + return CURLE_AUTH_ERROR; + } + + slen = CURL_ED25519_SIGLEN; + rc = EVP_DigestSign(mdctx, sig, &slen, msg, msglen); + + EVP_MD_CTX_free(mdctx); + EVP_PKEY_free(pkey); + + if(rc != 1) + return CURLE_AUTH_ERROR; + + *siglen = slen; + return CURLE_OK; +} + +#elif defined(USE_WOLFSSL) && \ + (defined(HAVE_ED25519) || defined(WOLFSSL_CURVE25519_USE_ED25519)) && \ + defined(HAVE_ED25519_KEY_IMPORT) && defined(HAVE_ED25519_SIGN) +#include <wolfssl/wolfcrypt/ed25519.h> +#include <wolfssl/wolfcrypt/error-crypt.h> +#include <wolfssl/wolfcrypt/random.h> + +CURLcode Curl_ed25519_sign(const unsigned char *key, size_t keylen, + const unsigned char *msg, size_t msglen, + unsigned char *sig, size_t *siglen) +{ + int ret; + ed25519_key edkey; + word32 outlen; + unsigned char pubkey[ED25519_PUB_KEY_SIZE]; + + if(keylen != ED25519_KEY_SIZE) + return CURLE_BAD_FUNCTION_ARGUMENT; + + ret = wc_ed25519_init(&edkey); + if(ret) + return CURLE_AUTH_ERROR; + + ret = wc_ed25519_import_private_only(key, ED25519_KEY_SIZE, &edkey); + if(ret) + goto fail; + + ret = wc_ed25519_make_public(&edkey, pubkey, ED25519_PUB_KEY_SIZE); + if(ret) + goto fail; + + ret = wc_ed25519_import_private_key(key, ED25519_KEY_SIZE, + pubkey, ED25519_PUB_KEY_SIZE, &edkey); + if(ret) + goto fail; + + outlen = ED25519_SIG_SIZE; + ret = wc_ed25519_sign_msg(msg, (word32)msglen, sig, &outlen, &edkey); + if(ret) + goto fail; + + *siglen = (size_t)outlen; + wc_ed25519_free(&edkey); + return CURLE_OK; + +fail: + wc_ed25519_free(&edkey); + return CURLE_AUTH_ERROR; +} + +#elif defined(USE_GNUTLS) +#include <nettle/eddsa.h> + +CURLcode Curl_ed25519_sign(const unsigned char *key, size_t keylen, + const unsigned char *msg, size_t msglen, + unsigned char *sig, size_t *siglen) +{ + uint8_t pubkey[ED25519_KEY_SIZE]; + + if(keylen != ED25519_KEY_SIZE) + return CURLE_BAD_FUNCTION_ARGUMENT; + + nettle_ed25519_sha512_public_key(pubkey, key); + + nettle_ed25519_sha512_sign(pubkey, key, msglen, msg, sig); + *siglen = CURL_ED25519_SIGLEN; + + return CURLE_OK; +} + +#else /* no Ed25519-capable backend */ + +CURLcode Curl_ed25519_sign(const unsigned char *key, size_t keylen, + const unsigned char *msg, size_t msglen, + unsigned char *sig, size_t *siglen) +{ + (void)key; + (void)keylen; + (void)msg; + (void)msglen; + (void)sig; + (void)siglen; + return CURLE_NOT_BUILT_IN; +} + +#endif /* Ed25519 backends */ + +#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_HTTPSIG */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ed25519.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ed25519.h new file mode 100644 index 0000000000..381b6511eb --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ed25519.h @@ -0,0 +1,44 @@ +#ifndef HEADER_CURL_ED25519_H +#define HEADER_CURL_ED25519_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HTTPSIG) + +#define CURL_ED25519_SIGLEN 64 +#define CURL_ED25519_KEYLEN 32 + +/* Sign with Ed25519 (RFC 8032). + * key/keylen: raw 32-byte private seed + * msg/msglen: data to sign + * sig: output buffer (at least CURL_ED25519_SIGLEN bytes) + * siglen: out - actual signature length on success + * Returns CURLE_OK or CURLE_NOT_BUILT_IN if no backend supports Ed25519. */ +CURLcode Curl_ed25519_sign(const unsigned char *key, size_t keylen, + const unsigned char *msg, size_t msglen, + unsigned char *sig, size_t *siglen); + +#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_HTTPSIG */ +#endif /* HEADER_CURL_ED25519_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_endian.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_endian.c new file mode 100644 index 0000000000..b3689417a4 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_endian.c @@ -0,0 +1,83 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curl_endian.h" + +/* + * Curl_read16_le() + * + * This function converts a 16-bit integer from the little endian format, as + * used in the incoming package to whatever endian format we are using + * natively. + * + * Parameters: + * + * buf [in] - A pointer to a 2-byte buffer. + * + * Returns the integer. + */ +unsigned short Curl_read16_le(const unsigned char *buf) +{ + return (unsigned short)(((unsigned short)buf[0]) | + ((unsigned short)buf[1] << 8)); +} + +/* + * Curl_read32_le() + * + * This function converts a 32-bit integer from the little endian format, as + * used in the incoming package to whatever endian format we are using + * natively. + * + * Parameters: + * + * buf [in] - A pointer to a 4-byte buffer. + * + * Returns the integer. + */ +unsigned int Curl_read32_le(const unsigned char *buf) +{ + return ((unsigned int)buf[0]) | ((unsigned int)buf[1] << 8) | + ((unsigned int)buf[2] << 16) | ((unsigned int)buf[3] << 24); +} + +/* + * Curl_read16_be() + * + * This function converts a 16-bit integer from the big endian format, as + * used in the incoming package to whatever endian format we are using + * natively. + * + * Parameters: + * + * buf [in] - A pointer to a 2-byte buffer. + * + * Returns the integer. + */ +unsigned short Curl_read16_be(const unsigned char *buf) +{ + return (unsigned short)(((unsigned short)buf[0] << 8) | + ((unsigned short)buf[1])); +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_endian.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_endian.h new file mode 100644 index 0000000000..fa283214b1 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_endian.h @@ -0,0 +1,36 @@ +#ifndef HEADER_CURL_ENDIAN_H +#define HEADER_CURL_ENDIAN_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* Converts a 16-bit integer from little endian */ +unsigned short Curl_read16_le(const unsigned char *buf); + +/* Converts a 32-bit integer from little endian */ +unsigned int Curl_read32_le(const unsigned char *buf); + +/* Converts a 16-bit integer from big endian */ +unsigned short Curl_read16_be(const unsigned char *buf); + +#endif /* HEADER_CURL_ENDIAN_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_fnmatch.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_fnmatch.c new file mode 100644 index 0000000000..d165554f8d --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_fnmatch.c @@ -0,0 +1,385 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_FTP + +#include "curl_fnmatch.h" + +#ifndef HAVE_FNMATCH + +#define CURLFNM_CHARSET_LEN (sizeof(char) * 256) +#define CURLFNM_CHSET_SIZE (CURLFNM_CHARSET_LEN + 15) + +#define CURLFNM_NEGATE CURLFNM_CHARSET_LEN + +#define CURLFNM_ALNUM (CURLFNM_CHARSET_LEN + 1) +#define CURLFNM_DIGIT (CURLFNM_CHARSET_LEN + 2) +#define CURLFNM_XDIGIT (CURLFNM_CHARSET_LEN + 3) +#define CURLFNM_ALPHA (CURLFNM_CHARSET_LEN + 4) +#define CURLFNM_PRINT (CURLFNM_CHARSET_LEN + 5) +#define CURLFNM_BLANK (CURLFNM_CHARSET_LEN + 6) +#define CURLFNM_LOWER (CURLFNM_CHARSET_LEN + 7) +#define CURLFNM_GRAPH (CURLFNM_CHARSET_LEN + 8) +#define CURLFNM_SPACE (CURLFNM_CHARSET_LEN + 9) +#define CURLFNM_UPPER (CURLFNM_CHARSET_LEN + 10) + +typedef enum { + CURLFNM_SCHS_DEFAULT = 0, + CURLFNM_SCHS_RIGHTBR, + CURLFNM_SCHS_RIGHTBRLEFTBR +} setcharset_state; + +typedef enum { + CURLFNM_PKW_INIT = 0, + CURLFNM_PKW_DDOT +} parsekey_state; + +typedef enum { + CCLASS_OTHER = 0, + CCLASS_DIGIT, + CCLASS_UPPER, + CCLASS_LOWER +} char_class; + +#define SETCHARSET_OK 1 +#define SETCHARSET_FAIL 0 + +static int parsekeyword(const unsigned char **pattern, unsigned char *charset) +{ + parsekey_state state = CURLFNM_PKW_INIT; + char keyword[10] = { 0 }; + size_t i; + const unsigned char *p = *pattern; + bool found = FALSE; + for(i = 0; !found; i++) { + char c = (char)*p++; + if(i >= sizeof(keyword)) + return SETCHARSET_FAIL; + switch(state) { + case CURLFNM_PKW_INIT: + if(ISLOWER(c)) + keyword[i] = c; + else if(c == ':') + state = CURLFNM_PKW_DDOT; + else + return SETCHARSET_FAIL; + break; + case CURLFNM_PKW_DDOT: + if(c == ']') + found = TRUE; + else + return SETCHARSET_FAIL; + } + } +#undef KEYLEN + + *pattern = p; /* move caller's pattern pointer */ + if(!strcmp(keyword, "digit")) + charset[CURLFNM_DIGIT] = 1; + else if(!strcmp(keyword, "alnum")) + charset[CURLFNM_ALNUM] = 1; + else if(!strcmp(keyword, "alpha")) + charset[CURLFNM_ALPHA] = 1; + else if(!strcmp(keyword, "xdigit")) + charset[CURLFNM_XDIGIT] = 1; + else if(!strcmp(keyword, "print")) + charset[CURLFNM_PRINT] = 1; + else if(!strcmp(keyword, "graph")) + charset[CURLFNM_GRAPH] = 1; + else if(!strcmp(keyword, "space")) + charset[CURLFNM_SPACE] = 1; + else if(!strcmp(keyword, "blank")) + charset[CURLFNM_BLANK] = 1; + else if(!strcmp(keyword, "upper")) + charset[CURLFNM_UPPER] = 1; + else if(!strcmp(keyword, "lower")) + charset[CURLFNM_LOWER] = 1; + else + return SETCHARSET_FAIL; + return SETCHARSET_OK; +} + +/* Return the character class. */ +static char_class charclass(unsigned char c) +{ + if(ISUPPER(c)) + return CCLASS_UPPER; + if(ISLOWER(c)) + return CCLASS_LOWER; + if(ISDIGIT(c)) + return CCLASS_DIGIT; + return CCLASS_OTHER; +} + +/* Include a character or a range in set. */ +static void setcharorrange(const unsigned char **pp, unsigned char *charset) +{ + const unsigned char *p = (*pp)++; + unsigned char c = *p++; + + charset[c] = 1; + if(ISALNUM(c) && *p++ == '-') { + char_class cc = charclass(c); + unsigned char endrange = *p++; + + if(endrange == '\\') + endrange = *p++; + if(endrange >= c && charclass(endrange) == cc) { + while(c++ != endrange) + if(charclass(c) == cc) /* Chars in class may be not consecutive. */ + charset[c] = 1; + *pp = p; + } + } +} + +/* returns 1 (TRUE) if pattern is OK, 0 if is bad ("p" is pattern pointer) */ +static int setcharset(const unsigned char **p, unsigned char *charset) +{ + setcharset_state state = CURLFNM_SCHS_DEFAULT; + bool something_found = FALSE; + unsigned char c; + + memset(charset, 0, CURLFNM_CHSET_SIZE); + for(;;) { + c = **p; + if(!c) + return SETCHARSET_FAIL; + + switch(state) { + case CURLFNM_SCHS_DEFAULT: + if(c == ']') { + if(something_found) + return SETCHARSET_OK; + something_found = TRUE; + state = CURLFNM_SCHS_RIGHTBR; + charset[c] = 1; + (*p)++; + } + else if(c == '[') { + const unsigned char *pp = *p + 1; + + if(*pp++ == ':' && parsekeyword(&pp, charset)) + *p = pp; + else { + charset[c] = 1; + (*p)++; + } + something_found = TRUE; + } + else if(c == '^' || c == '!') { + if(!something_found) { + if(charset[CURLFNM_NEGATE]) { + charset[c] = 1; + something_found = TRUE; + } + else + charset[CURLFNM_NEGATE] = 1; /* negate charset */ + } + else + charset[c] = 1; + (*p)++; + } + else if(c == '\\') { + c = *(++(*p)); + if(c) + setcharorrange(p, charset); + else + charset['\\'] = 1; + something_found = TRUE; + } + else { + setcharorrange(p, charset); + something_found = TRUE; + } + break; + case CURLFNM_SCHS_RIGHTBR: + if(c == '[') { + state = CURLFNM_SCHS_RIGHTBRLEFTBR; + charset[c] = 1; + (*p)++; + } + else if(c == ']') { + return SETCHARSET_OK; + } + else if(ISPRINT(c)) { + charset[c] = 1; + (*p)++; + state = CURLFNM_SCHS_DEFAULT; + } + else + /* used 'goto fail' instead of 'return SETCHARSET_FAIL' to avoid a + * nonsense warning 'statement not reached' at end of the fnc when + * compiling on Solaris */ + goto fail; + break; + case CURLFNM_SCHS_RIGHTBRLEFTBR: + if(c == ']') + return SETCHARSET_OK; + state = CURLFNM_SCHS_DEFAULT; + charset[c] = 1; + (*p)++; + break; + } + } +fail: + return SETCHARSET_FAIL; +} + +static int loop(const unsigned char *pattern, const unsigned char *string, + int maxstars) +{ + const unsigned char *p = pattern; + const unsigned char *s = string; + unsigned char charset[CURLFNM_CHSET_SIZE] = { 0 }; + + for(;;) { + const unsigned char *pp; + + switch(*p) { + case '*': + if(!maxstars) + return CURL_FNMATCH_NOMATCH; + /* Regroup consecutive stars and question marks. This can be done because + '*?*?*' can be expressed as '??*'. */ + for(;;) { + if(*++p == '\0') + return CURL_FNMATCH_MATCH; + if(*p == '?') { + if(!*s++) + return CURL_FNMATCH_NOMATCH; + } + else if(*p != '*') + break; + } + /* Skip string characters until we find a match with pattern suffix. */ + for(maxstars--; *s; s++) { + if(loop(p, s, maxstars) == CURL_FNMATCH_MATCH) + return CURL_FNMATCH_MATCH; + } + return CURL_FNMATCH_NOMATCH; + case '?': + if(!*s) + return CURL_FNMATCH_NOMATCH; + s++; + p++; + break; + case '\0': + return *s ? CURL_FNMATCH_NOMATCH : CURL_FNMATCH_MATCH; + case '\\': + if(p[1]) + p++; + if(*s++ != *p++) + return CURL_FNMATCH_NOMATCH; + break; + case '[': + pp = p + 1; /* Copy in case of syntax error in set. */ + if(setcharset(&pp, charset)) { + bool found = FALSE; + if(!*s) + return CURL_FNMATCH_NOMATCH; + if(charset[(unsigned int)*s]) + found = TRUE; + else if(charset[CURLFNM_ALNUM]) + found = ISALNUM(*s); + else if(charset[CURLFNM_ALPHA]) + found = ISALPHA(*s); + else if(charset[CURLFNM_DIGIT]) + found = ISDIGIT(*s); + else if(charset[CURLFNM_XDIGIT]) + found = ISXDIGIT(*s); + else if(charset[CURLFNM_PRINT]) + found = ISPRINT(*s); + else if(charset[CURLFNM_SPACE]) + found = ISBLANK(*s); + else if(charset[CURLFNM_UPPER]) + found = ISUPPER(*s); + else if(charset[CURLFNM_LOWER]) + found = ISLOWER(*s); + else if(charset[CURLFNM_BLANK]) + found = ISBLANK(*s); + else if(charset[CURLFNM_GRAPH]) + found = ISGRAPH(*s); + + if(charset[CURLFNM_NEGATE]) + found = !found; + + if(!found) + return CURL_FNMATCH_NOMATCH; + p = pp + 1; + s++; + break; + } + /* Syntax error in set; mismatch! */ + return CURL_FNMATCH_NOMATCH; + + default: + if(*p++ != *s++) + return CURL_FNMATCH_NOMATCH; + break; + } + } +} + +/* + * @unittest: 1307 + */ +int Curl_fnmatch(void *ptr, const char *pattern, const char *string) +{ + (void)ptr; /* the argument is specified by the curl_fnmatch_callback + prototype, but not used by Curl_fnmatch() */ + if(!pattern || !string) { + return CURL_FNMATCH_FAIL; + } + return loop((const unsigned char *)pattern, + (const unsigned char *)string, 2); +} +#else /* HAVE_FNMATCH */ + +#include <fnmatch.h> +/* + * @unittest: 1307 + */ +int Curl_fnmatch(void *ptr, const char *pattern, const char *string) +{ + (void)ptr; /* the argument is specified by the curl_fnmatch_callback + prototype, but not used by Curl_fnmatch() */ + if(!pattern || !string) { + return CURL_FNMATCH_FAIL; + } + + switch(fnmatch(pattern, string, 0)) { + case 0: + return CURL_FNMATCH_MATCH; + case FNM_NOMATCH: + return CURL_FNMATCH_NOMATCH; + default: + return CURL_FNMATCH_FAIL; + } + /* not reached */ +} +#endif /* !HAVE_FNMATCH */ + +#endif /* !CURL_DISABLE_FTP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_fnmatch.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_fnmatch.h new file mode 100644 index 0000000000..61d2a0c4e9 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_fnmatch.h @@ -0,0 +1,45 @@ +#ifndef HEADER_CURL_FNMATCH_H +#define HEADER_CURL_FNMATCH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#define CURL_FNMATCH_MATCH 0 +#define CURL_FNMATCH_NOMATCH 1 +#define CURL_FNMATCH_FAIL 2 + +/* default pattern matching function + * ================================= + * Implemented with recursive backtracking, if you want to use Curl_fnmatch, + * please note that there is not implemented UTF/Unicode support. + * + * Implemented features: + * '?' notation, does not match UTF characters + * '*' can also work with UTF string + * [a-zA-Z0-9] enumeration support + * + * keywords: alnum, digit, xdigit, alpha, print, blank, lower, graph, space + * and upper (use as "[[:alnum:]]") + */ +int Curl_fnmatch(void *ptr, const char *pattern, const char *string); + +#endif /* HEADER_CURL_FNMATCH_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_fopen.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_fopen.c new file mode 100644 index 0000000000..75054ffb77 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_fopen.c @@ -0,0 +1,164 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_COOKIES) || !defined(CURL_DISABLE_ALTSVC) || \ + !defined(CURL_DISABLE_HSTS) + +#include "urldata.h" +#include "rand.h" +#include "curl_fopen.h" + +/* The dirslash() function breaks a null-terminated pathname string into + directory and filename components then returns the directory component up + to, *AND INCLUDING*, a final '/'. If there is no directory in the path, + this instead returns a "" string. + + This function returns a pointer to malloc'ed memory. + + The input path to this function is expected to have a filename part. + */ + +#ifdef _WIN32 +#define PATHSEP "\\" +#define IS_SEP(x) (((x) == '/') || ((x) == '\\')) +#elif defined(MSDOS) || defined(OS2) +#define PATHSEP "\\" +#define IS_SEP(x) ((x) == '\\') +#else +#define PATHSEP "/" +#define IS_SEP(x) ((x) == '/') +#endif + +static char *dirslash(const char *path) +{ + size_t n; + struct dynbuf out; + DEBUGASSERT(path); + curlx_dyn_init(&out, CURL_MAX_INPUT_LENGTH); + n = strlen(path); + if(n) { + /* find the rightmost path separator, if any */ + while(n && !IS_SEP(path[n - 1])) + --n; + /* skip over all the path separators, if any */ + while(n && IS_SEP(path[n - 1])) + --n; + } + if(curlx_dyn_addn(&out, path, n)) + return NULL; + /* if there was a directory, append a single trailing slash */ + if(n && curlx_dyn_addn(&out, PATHSEP, 1)) + return NULL; + return curlx_dyn_ptr(&out); +} + +/* + * Curl_fopen() opens a file for writing with a temp name, to be renamed + * to the final name when completed. If there is an existing file using this + * name at the time of the open, this function will clone the mode from that + * file. if 'tempname' is non-NULL, it needs a rename after the file is + * written. + */ +CURLcode Curl_fopen(struct Curl_easy *data, const char *filename, + FILE **fh, char **tempname) +{ + CURLcode result = CURLE_WRITE_ERROR; + unsigned char randbuf[41]; + char *tempstore = NULL; +#ifndef _WIN32 + curlx_struct_stat sb; +#endif + int fd = -1; + char *dir = NULL; + *tempname = NULL; + +#ifndef _WIN32 + *fh = curlx_fopen(filename, FOPEN_WRITETEXT); + if(!*fh) + goto fail; + if(curlx_fstat(fileno(*fh), &sb) == -1 || !S_ISREG(sb.st_mode)) { + return CURLE_OK; + } + curlx_fclose(*fh); +#ifdef HAVE_GETEUID + /* If the existing file is not owned by the user, do not inherit + * its permissions at the temp file created below. The permissions + * might be unsuitable for holding user private data. */ + if(sb.st_uid != geteuid()) + sb.st_mode = 0; +#endif +#endif /* !_WIN32 */ + *fh = NULL; + + result = Curl_rand_alnum(data, randbuf, sizeof(randbuf)); + if(result) + goto fail; + + dir = dirslash(filename); + if(dir) { + /* The temp filename should not end up too long for the target file + system */ + tempstore = curl_maprintf("%s%s.tmp", dir, randbuf); + curlx_free(dir); + } + + if(!tempstore) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + result = CURLE_WRITE_ERROR; +#ifdef _WIN32 + fd = curlx_open(tempstore, _O_WRONLY | _O_CREAT | _O_EXCL, + _S_IREAD | _S_IWRITE); +#elif (defined(ANDROID) || defined(__ANDROID__)) && \ + (defined(__i386__) || defined(__arm__)) + fd = curlx_open(tempstore, O_WRONLY | O_CREAT | O_EXCL, + (mode_t)(S_IRUSR | S_IWUSR | sb.st_mode)); +#else + fd = curlx_open(tempstore, O_WRONLY | O_CREAT | O_EXCL, + S_IRUSR | S_IWUSR | sb.st_mode); +#endif + if(fd == -1) + goto fail; + + *fh = curlx_fdopen(fd, FOPEN_WRITETEXT); + if(!*fh) + goto fail; + + *tempname = tempstore; + return CURLE_OK; + +fail: + if(fd != -1) { + curlx_close(fd); + unlink(tempstore); + } + + curlx_free(tempstore); + return result; +} + +#endif /* !disabled */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_fopen.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_fopen.h new file mode 100644 index 0000000000..bd402d4489 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_fopen.h @@ -0,0 +1,31 @@ +#ifndef HEADER_CURL_FOPEN_H +#define HEADER_CURL_FOPEN_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curlx/fopen.h" + +CURLcode Curl_fopen(struct Curl_easy *data, const char *filename, + FILE **fh, char **tempname); + +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_get_line.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_get_line.c new file mode 100644 index 0000000000..6fcd043c93 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_get_line.c @@ -0,0 +1,69 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_COOKIES) || !defined(CURL_DISABLE_ALTSVC) || \ + !defined(CURL_DISABLE_HSTS) || !defined(CURL_DISABLE_NETRC) + +#include "curl_get_line.h" + +/* + * Curl_get_line() returns only complete whole lines that end with newline. + * When 'eof' is set TRUE, the last line has been read. + */ +CURLcode Curl_get_line(struct dynbuf *buf, FILE *input, bool *eof) +{ + CURLcode result; + char buffer[128]; + curlx_dyn_reset(buf); + while(1) { + size_t rlen; + const char *b = fgets(buffer, sizeof(buffer), input); + if(!b && ferror(input)) + return CURLE_READ_ERROR; + + *eof = feof(input); + + rlen = b ? strlen(b) : 0; + if(rlen) { + result = curlx_dyn_addn(buf, b, rlen); + if(result) + /* too long line or out of memory */ + return result; + } + /* now check the full line */ + rlen = curlx_dyn_len(buf); + b = curlx_dyn_ptr(buf); + if(rlen && (b[rlen - 1] == '\n')) + /* LF at end of the line */ + return CURLE_OK; /* all good */ + if(*eof) + /* append a newline */ + return curlx_dyn_addn(buf, "\n", 1); + /* otherwise get next line to append */ + } + /* UNREACHABLE */ +} + +#endif /* if not disabled */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_get_line.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_get_line.h new file mode 100644 index 0000000000..6b90ac4727 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_get_line.h @@ -0,0 +1,31 @@ +#ifndef HEADER_CURL_GET_LINE_H +#define HEADER_CURL_GET_LINE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curlx/dynbuf.h" + +/* Curl_get_line() returns complete lines that end with a newline. */ +CURLcode Curl_get_line(struct dynbuf *buf, FILE *input, bool *eof); + +#endif /* HEADER_CURL_GET_LINE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_gethostname.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_gethostname.c new file mode 100644 index 0000000000..f154c837f6 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_gethostname.c @@ -0,0 +1,96 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curl_gethostname.h" +#include "curlx/strcopy.h" + +/* + * Curl_gethostname() is a wrapper around gethostname() which allows + * overriding the hostname that the function would normally return. + * This capability is used by the test suite to verify exact matching + * of NTLM authentication, which exercises libcurl's MD4 and DES code + * as well as by the SMTP module when a hostname is not provided. + * + * For libcurl debug enabled builds hostname overriding takes place + * when environment variable CURL_GETHOSTNAME is set, using the value + * held by the variable to override returned hostname. + * + * Note: The function always returns the un-qualified hostname rather + * than being provider dependent. + */ + +int Curl_gethostname(char * const name, GETHOSTNAME_TYPE_ARG2 namelen) +{ +#ifndef HAVE_GETHOSTNAME + + /* Allow compilation and return failure when unavailable */ + (void)name; + (void)namelen; + return -1; + +#else + int err; + char *dot; + +#ifdef DEBUGBUILD + + /* Override hostname when environment variable CURL_GETHOSTNAME is set */ + const char *force_hostname = getenv("CURL_GETHOSTNAME"); + if(force_hostname) { + if(strlen(force_hostname) < (size_t)namelen) + curlx_strcopy(name, namelen, force_hostname, strlen(force_hostname)); + else + return 1; /* cannot do it */ + err = 0; + } + else { + name[0] = '\0'; + err = gethostname(name, namelen); + } + +#else /* DEBUGBUILD */ + + name[0] = '\0'; +#ifdef __AMIGA__ + err = gethostname((unsigned char *)name, namelen); +#else + err = gethostname(name, namelen); +#endif + +#endif + + name[namelen - 1] = '\0'; + + if(err) + return err; + + /* Truncate domain, leave only machine name */ + dot = strchr(name, '.'); + if(dot) + *dot = '\0'; + + return 0; +#endif +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_gethostname.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_gethostname.h new file mode 100644 index 0000000000..9281d9c242 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_gethostname.h @@ -0,0 +1,33 @@ +#ifndef HEADER_CURL_GETHOSTNAME_H +#define HEADER_CURL_GETHOSTNAME_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* Hostname buffer size */ +#define HOSTNAME_MAX 1024 + +/* This returns the local machine's un-qualified hostname */ +int Curl_gethostname(char * const name, GETHOSTNAME_TYPE_ARG2 namelen); + +#endif /* HEADER_CURL_GETHOSTNAME_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_gssapi.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_gssapi.c new file mode 100644 index 0000000000..437f76d04a --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_gssapi.c @@ -0,0 +1,705 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_GSSAPI + +#include "curl_gssapi.h" +#include "curl_trc.h" +#include "curlx/strcopy.h" + +#ifdef DEBUGBUILD +#if defined(HAVE_GSSGNU) || !defined(_WIN32) +#define Curl_gss_alloc malloc /* freed via the GSS API gss_release_buffer() */ +#define Curl_gss_free free /* pair of the above */ +#define CURL_GSS_STUB +/* For correctness this would be required for all platforms, not only Windows, + but, as of v1.22.1, MIT Kerberos uses a special allocator only for Windows, + and the availability of 'gssapi/gssapi_alloc.h' is difficult to detect, + because GSS headers are not versioned, and there is also no other macro to + indicate 1.18+ vs. previous versions. On Windows we can use 'GSS_S_BAD_MIC'. + */ +#elif defined(_WIN32) && defined(GSS_S_BAD_MIC) /* MIT Kerberos 1.15+ */ +/* MIT Kerberos 1.10+ (Windows), 1.18+ (all platforms), missing from GNU GSS */ +#include <gssapi/gssapi_alloc.h> +#define Curl_gss_alloc gssalloc_malloc +#define Curl_gss_free gssalloc_free +#define CURL_GSS_STUB +#endif +#endif /* DEBUGBUILD */ + +#ifdef __GNUC__ +#define CURL_ALIGN8 __attribute__((aligned(8))) +#else +#define CURL_ALIGN8 +#endif + +#if defined(CURL_HAVE_DIAG) && defined(__APPLE__) && !defined(HAVE_GSSAPPLE) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + +gss_OID_desc Curl_spnego_mech_oid CURL_ALIGN8 = { + 6, CURL_UNCONST("\x2b\x06\x01\x05\x05\x02") +}; +gss_OID_desc Curl_krb5_mech_oid CURL_ALIGN8 = { + 9, CURL_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02") +}; + +#ifdef CURL_GSS_STUB +enum min_err_code { + STUB_GSS_OK = 0, + STUB_GSS_NO_MEMORY, + STUB_GSS_INVALID_ARGS, + STUB_GSS_INVALID_CREDS, + STUB_GSS_INVALID_CTX, + STUB_GSS_SERVER_ERR, + STUB_GSS_NO_MECH, + STUB_GSS_LAST +}; + +/* libcurl is also passing this struct to these functions, which are not yet + * stubbed: + * gss_unwrap() + * gss_wrap() + */ +struct stub_gss_ctx_id_t_desc { + enum { STUB_GSS_NONE, STUB_GSS_KRB5, STUB_GSS_NTLM1, STUB_GSS_NTLM3 } sent; + int have_krb5; + int have_ntlm; + OM_uint32 flags; + char creds[250]; +}; + +/* Stub credential: tracks which mechanisms are allowed */ +struct stub_gss_cred_id_t_desc { + int allow_krb5; + int allow_ntlm; +}; + +static OM_uint32 stub_gss_init_sec_context( + OM_uint32 *min, + gss_cred_id_t initiator_cred_handle, + struct stub_gss_ctx_id_t_desc **context, + gss_name_t target_name, + const gss_OID mech_type, + OM_uint32 req_flags, + OM_uint32 time_req, + const gss_channel_bindings_t input_chan_bindings, + gss_buffer_desc *input_token, + gss_OID *actual_mech_type, + gss_buffer_desc *output_token, + OM_uint32 *ret_flags, + OM_uint32 *time_rec) +{ + struct stub_gss_ctx_id_t_desc *ctx = NULL; + + /* The token will be encoded in base64 */ + size_t length = sizeof(ctx->creds) * 3 / 4; + size_t used = 0; + char *token = NULL; + const char *creds = NULL; + + (void)mech_type; + (void)time_req; + (void)input_chan_bindings; + (void)actual_mech_type; + + if(!min) + return GSS_S_FAILURE; + + *min = 0; + + if(!context || !target_name || !output_token) { + *min = STUB_GSS_INVALID_ARGS; + return GSS_S_FAILURE; + } + + creds = getenv("CURL_STUB_GSS_CREDS"); + if(!creds || strlen(creds) >= sizeof(ctx->creds)) { + *min = STUB_GSS_INVALID_CREDS; + return GSS_S_FAILURE; + } + + ctx = *context; + if(ctx && strcmp(ctx->creds, creds)) { + *min = STUB_GSS_INVALID_CREDS; + return GSS_S_FAILURE; + } + + output_token->length = 0; + output_token->value = NULL; + + if(input_token && input_token->length) { + if(!ctx) { + *min = STUB_GSS_INVALID_CTX; + return GSS_S_FAILURE; + } + + /* Server response, either D (RA==) or C (Qw==) */ + if(((char *)input_token->value)[0] == 'D') { + /* Done */ + switch(ctx->sent) { + case STUB_GSS_KRB5: + case STUB_GSS_NTLM3: + if(ret_flags) + *ret_flags = ctx->flags; + if(time_rec) + *time_rec = GSS_C_INDEFINITE; + return GSS_S_COMPLETE; + default: + *min = STUB_GSS_SERVER_ERR; + return GSS_S_FAILURE; + } + } + + if(((char *)input_token->value)[0] != 'C') { + /* We only support Done or Continue */ + *min = STUB_GSS_SERVER_ERR; + return GSS_S_FAILURE; + } + + /* Continue */ + switch(ctx->sent) { + case STUB_GSS_KRB5: + /* We sent KRB5 and it failed, let's try NTLM */ + if(ctx->have_ntlm) { + ctx->sent = STUB_GSS_NTLM1; + break; + } + else { + *min = STUB_GSS_SERVER_ERR; + return GSS_S_FAILURE; + } + case STUB_GSS_NTLM1: + ctx->sent = STUB_GSS_NTLM3; + break; + default: + *min = STUB_GSS_SERVER_ERR; + return GSS_S_FAILURE; + } + } + else { + if(ctx) { + *min = STUB_GSS_INVALID_CTX; + return GSS_S_FAILURE; + } + + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + *min = STUB_GSS_NO_MEMORY; + return GSS_S_FAILURE; + } + + if(strstr(creds, "KRB5")) + ctx->have_krb5 = 1; + + if(strstr(creds, "NTLM")) + ctx->have_ntlm = 1; + + /* If a credential restricts allowed mechs, honour it */ + if(initiator_cred_handle != GSS_C_NO_CREDENTIAL) { + struct stub_gss_cred_id_t_desc *cred = + (struct stub_gss_cred_id_t_desc *)initiator_cred_handle; + if(!cred->allow_krb5) + ctx->have_krb5 = 0; + if(!cred->allow_ntlm) + ctx->have_ntlm = 0; + } + + if(ctx->have_krb5) + ctx->sent = STUB_GSS_KRB5; + else if(ctx->have_ntlm) + ctx->sent = STUB_GSS_NTLM1; + else { + curlx_free(ctx); + *min = STUB_GSS_NO_MECH; + return GSS_S_FAILURE; + } + + curlx_strcopy(ctx->creds, sizeof(ctx->creds), creds, strlen(creds)); + ctx->flags = req_flags; + } + + token = Curl_gss_alloc(length); + if(!token) { + curlx_free(ctx); + *min = STUB_GSS_NO_MEMORY; + return GSS_S_FAILURE; + } + + { + gss_buffer_desc target_desc; + gss_OID name_type = GSS_C_NO_OID; + OM_uint32 minor_status; + OM_uint32 major_status; + major_status = gss_display_name(&minor_status, target_name, + &target_desc, &name_type); + if(GSS_ERROR(major_status)) { + Curl_gss_free(token); + curlx_free(ctx); + *min = STUB_GSS_NO_MEMORY; + return GSS_S_FAILURE; + } + + if(strlen(creds) + target_desc.length + 5 >= sizeof(ctx->creds)) { + Curl_gss_free(token); + curlx_free(ctx); + *min = STUB_GSS_NO_MEMORY; + return GSS_S_FAILURE; + } + + /* Token format: creds:target:type:padding */ + used = curl_msnprintf(token, length, "%s:%.*s:%d:", creds, + (int)target_desc.length, + (const char *)target_desc.value, + (int)ctx->sent); + + gss_release_buffer(&minor_status, &target_desc); + } + + if(used >= length) { + Curl_gss_free(token); + curlx_free(ctx); + *min = STUB_GSS_NO_MEMORY; + return GSS_S_FAILURE; + } + + /* Overwrite null-terminator */ + memset(token + used, 'A', length - used); + + *context = ctx; + + output_token->value = token; + output_token->length = length; + + return GSS_S_CONTINUE_NEEDED; +} + +static OM_uint32 stub_gss_delete_sec_context( + OM_uint32 *min, + struct stub_gss_ctx_id_t_desc **context, + gss_buffer_t output_token) +{ + (void)output_token; + + if(!min) + return GSS_S_FAILURE; + + if(!context) { + *min = STUB_GSS_INVALID_CTX; + return GSS_S_FAILURE; + } + if(!*context) { + *min = STUB_GSS_INVALID_CTX; + return GSS_S_FAILURE; + } + + curlx_safefree(*context); + *min = 0; + + return GSS_S_COMPLETE; +} + +/* NTLMSSP OID: 1.3.6.1.4.1.311.2.2.10 */ +static gss_OID_desc stub_ntlmssp_oid = { + 10, CURL_UNCONST("\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a") +}; + +static OM_uint32 stub_gss_inquire_context( + OM_uint32 *min, + struct stub_gss_ctx_id_t_desc *context, + gss_name_t *src_name, + gss_name_t *targ_name, + OM_uint32 *lifetime_rec, + gss_OID *mech_type, + OM_uint32 *ctx_flags, + int *locally_initiated, + int *open_context) +{ + (void)src_name; + (void)targ_name; + (void)lifetime_rec; + (void)ctx_flags; + (void)locally_initiated; + (void)open_context; + + if(!min) + return GSS_S_FAILURE; + + if(!context) { + *min = STUB_GSS_INVALID_CTX; + return GSS_S_FAILURE; + } + + *min = 0; + if(mech_type) { + switch(context->sent) { + case STUB_GSS_NTLM1: + case STUB_GSS_NTLM3: + *mech_type = &stub_ntlmssp_oid; + break; + default: + *mech_type = (gss_OID)&Curl_krb5_mech_oid; + break; + } + } + + return GSS_S_COMPLETE; +} +static OM_uint32 stub_gss_acquire_cred( + OM_uint32 *min, + gss_name_t desired_name, + OM_uint32 time_req, + gss_OID_set desired_mechs, + gss_cred_usage_t cred_usage, + gss_cred_id_t *output_cred_handle, + gss_OID_set *actual_mechs, + OM_uint32 *time_rec) +{ + (void)desired_name; + (void)time_req; + (void)desired_mechs; + (void)cred_usage; + (void)actual_mechs; + (void)time_rec; + + if(!min) + return GSS_S_FAILURE; + + *min = 0; + /* Allocate a stub credential that initially allows all mechanisms */ + if(output_cred_handle) { + struct stub_gss_cred_id_t_desc *cred = + curlx_calloc(1, sizeof(*cred)); + if(!cred) { + *min = STUB_GSS_NO_MEMORY; + return GSS_S_FAILURE; + } + cred->allow_krb5 = 1; + cred->allow_ntlm = 1; + *output_cred_handle = (gss_cred_id_t)cred; + } + return GSS_S_COMPLETE; +} + +static OM_uint32 stub_gss_indicate_mechs( + OM_uint32 *min, + gss_OID_set *mech_set) +{ + const char *creds; + OM_uint32 major; + + if(!min) + return GSS_S_FAILURE; + + *min = 0; + creds = getenv("CURL_STUB_GSS_CREDS"); + if(!creds) { + *min = STUB_GSS_INVALID_CREDS; + return GSS_S_FAILURE; + } + + major = gss_create_empty_oid_set(min, mech_set); + if(GSS_ERROR(major)) + return major; + + /* Always include Kerberos */ + gss_add_oid_set_member(min, (gss_OID)&Curl_krb5_mech_oid, mech_set); + + /* Include NTLM if the stub creds contain NTLM */ + if(strstr(creds, "NTLM")) + gss_add_oid_set_member(min, &stub_ntlmssp_oid, mech_set); + + return GSS_S_COMPLETE; +} + +#ifdef HAVE_GSS_SET_NEG_MECHS /* MIT Kerberos 1.8+ (2010-03-02), + missing from Apple GSS, GNU GSS */ +static OM_uint32 stub_gss_set_neg_mechs(OM_uint32 *min, + gss_cred_id_t cred_handle, + const gss_OID_set mech_set) +{ + struct stub_gss_cred_id_t_desc *cred; + size_t i; + int found_krb5 = 0; + int found_ntlm = 0; + + if(!min) + return GSS_S_FAILURE; + + *min = 0; + if(cred_handle == GSS_C_NO_CREDENTIAL) + return GSS_S_FAILURE; + + cred = (struct stub_gss_cred_id_t_desc *)cred_handle; + + /* Determine which mechs are in the allowed set */ + if(mech_set) { + for(i = 0; i < mech_set->count; i++) { + gss_OID oid = &mech_set->elements[i]; + if(oid->length == Curl_krb5_mech_oid.length && + !memcmp(oid->elements, Curl_krb5_mech_oid.elements, oid->length)) + found_krb5 = 1; + if(oid->length == stub_ntlmssp_oid.length && + !memcmp(oid->elements, stub_ntlmssp_oid.elements, oid->length)) + found_ntlm = 1; + } + } + + cred->allow_krb5 = found_krb5; + cred->allow_ntlm = found_ntlm; + return GSS_S_COMPLETE; +} +#endif /* HAVE_GSS_SET_NEG_MECHS */ + +static OM_uint32 stub_gss_release_cred( + OM_uint32 *min, + gss_cred_id_t *cred_handle) +{ + if(!min) + return GSS_S_FAILURE; + + *min = 0; + if(cred_handle && *cred_handle != GSS_C_NO_CREDENTIAL) { + curlx_free(*cred_handle); + *cred_handle = GSS_C_NO_CREDENTIAL; + } + return GSS_S_COMPLETE; +} + +#endif /* CURL_GSS_STUB */ + +OM_uint32 Curl_gss_init_sec_context(struct Curl_easy *data, + OM_uint32 *minor_status, + gss_ctx_id_t *context, + gss_name_t target_name, + gss_OID mech_type, + gss_channel_bindings_t input_chan_bindings, + gss_buffer_t input_token, + gss_buffer_t output_token, + const bool mutual_auth, + OM_uint32 *ret_flags, + gss_cred_id_t cred_handle) +{ + OM_uint32 req_flags = GSS_C_REPLAY_FLAG; + + if(mutual_auth) + req_flags |= GSS_C_MUTUAL_FLAG; + + if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_POLICY_FLAG) { +#ifdef GSS_C_DELEG_POLICY_FLAG /* MIT Kerberos 1.7+ (2009-06-02), Apple GSS, + missing from GNU GSS */ + req_flags |= GSS_C_DELEG_POLICY_FLAG; +#else + infof(data, "WARNING: support for CURLGSSAPI_DELEGATION_POLICY_FLAG not " + "compiled in"); +#endif + } + + if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_FLAG) + req_flags |= GSS_C_DELEG_FLAG; + +#ifdef CURL_GSS_STUB + if(getenv("CURL_STUB_GSS_CREDS")) + return stub_gss_init_sec_context(minor_status, + cred_handle, + (struct stub_gss_ctx_id_t_desc **)context, + target_name, + mech_type, + req_flags, + 0, /* time_req */ + input_chan_bindings, + input_token, + NULL, /* actual_mech_type */ + output_token, + ret_flags, + NULL /* time_rec */); +#endif /* CURL_GSS_STUB */ + + return gss_init_sec_context(minor_status, + cred_handle, + context, + target_name, + mech_type, + req_flags, + 0, /* time_req */ + input_chan_bindings, + input_token, + NULL, /* actual_mech_type */ + output_token, + ret_flags, + NULL /* time_rec */); +} + +OM_uint32 Curl_gss_delete_sec_context(OM_uint32 *min, + gss_ctx_id_t *context, + gss_buffer_t output_token) +{ +#ifdef CURL_GSS_STUB + if(getenv("CURL_STUB_GSS_CREDS")) + return stub_gss_delete_sec_context(min, + (struct stub_gss_ctx_id_t_desc **)context, + output_token); +#endif /* CURL_GSS_STUB */ + + return gss_delete_sec_context(min, context, output_token); +} + +OM_uint32 Curl_gss_inquire_context(OM_uint32 *minor_status, + gss_ctx_id_t context, + gss_OID *mech_type) +{ +#ifdef CURL_GSS_STUB + if(getenv("CURL_STUB_GSS_CREDS")) + return stub_gss_inquire_context(minor_status, + (struct stub_gss_ctx_id_t_desc *)context, + NULL, NULL, NULL, mech_type, + NULL, NULL, NULL); +#endif /* CURL_GSS_STUB */ + + return gss_inquire_context(minor_status, context, + NULL, NULL, NULL, mech_type, + NULL, NULL, NULL); +} + +OM_uint32 Curl_gss_acquire_cred(OM_uint32 *minor_status, + gss_name_t desired_name, + OM_uint32 time_req, + gss_OID_set desired_mechs, + gss_cred_usage_t cred_usage, + gss_cred_id_t *output_cred_handle, + gss_OID_set *actual_mechs, + OM_uint32 *time_rec) +{ +#ifdef CURL_GSS_STUB + if(getenv("CURL_STUB_GSS_CREDS")) + return stub_gss_acquire_cred(minor_status, desired_name, time_req, + desired_mechs, cred_usage, + output_cred_handle, actual_mechs, time_rec); +#endif /* CURL_GSS_STUB */ + + return gss_acquire_cred(minor_status, desired_name, time_req, + desired_mechs, cred_usage, + output_cred_handle, actual_mechs, time_rec); +} + +OM_uint32 Curl_gss_indicate_mechs(OM_uint32 *minor_status, + gss_OID_set *mech_set) +{ +#ifdef CURL_GSS_STUB + if(getenv("CURL_STUB_GSS_CREDS")) + return stub_gss_indicate_mechs(minor_status, mech_set); +#endif /* CURL_GSS_STUB */ + + return gss_indicate_mechs(minor_status, mech_set); +} + +#ifdef HAVE_GSS_SET_NEG_MECHS +OM_uint32 Curl_gss_set_neg_mechs(OM_uint32 *minor_status, + gss_cred_id_t cred_handle, + const gss_OID_set mech_set) +{ +#ifdef CURL_GSS_STUB + if(getenv("CURL_STUB_GSS_CREDS")) + return stub_gss_set_neg_mechs(minor_status, cred_handle, mech_set); +#endif /* CURL_GSS_STUB */ + + return gss_set_neg_mechs(minor_status, cred_handle, mech_set); +} +#endif /* HAVE_GSS_SET_NEG_MECHS */ + +OM_uint32 Curl_gss_release_cred(OM_uint32 *minor_status, + gss_cred_id_t *cred_handle) +{ +#ifdef CURL_GSS_STUB + if(getenv("CURL_STUB_GSS_CREDS")) + return stub_gss_release_cred(minor_status, cred_handle); +#endif /* CURL_GSS_STUB */ + + return gss_release_cred(minor_status, cred_handle); +} + +#ifdef CURLVERBOSE +#define GSS_LOG_BUFFER_LEN 1024 +static size_t display_gss_error(OM_uint32 status, int type, + char *buf, size_t len) +{ + OM_uint32 maj_stat; + OM_uint32 min_stat; + OM_uint32 msg_ctx = 0; + gss_buffer_desc status_string = GSS_C_EMPTY_BUFFER; + + do { + maj_stat = gss_display_status(&min_stat, + status, + type, + GSS_C_NO_OID, + &msg_ctx, + &status_string); + if(maj_stat == GSS_S_COMPLETE && status_string.length > 0) { + if(GSS_LOG_BUFFER_LEN > len + status_string.length + 3) { + len += curl_msnprintf(buf + len, GSS_LOG_BUFFER_LEN - len, + "%.*s. ", (int)status_string.length, + (char *)status_string.value); + } + } + gss_release_buffer(&min_stat, &status_string); + } while(!GSS_ERROR(maj_stat) && msg_ctx); + + return len; +} + +/* + * Curl_gss_log_error() + * + * This is used to log a GSS-API error status. + * + * Parameters: + * + * data [in] - The session handle. + * prefix [in] - The prefix of the log message. + * major [in] - The major status code. + * minor [in] - The minor status code. + */ +void Curl_gss_log_error(struct Curl_easy *data, const char *prefix, + OM_uint32 major, OM_uint32 minor) +{ + char buf[GSS_LOG_BUFFER_LEN] = ""; + size_t len = 0; + + if(major != GSS_S_FAILURE) + len = display_gss_error(major, GSS_C_GSS_CODE, buf, len); + + display_gss_error(minor, GSS_C_MECH_CODE, buf, len); + + infof(data, "%s%s", prefix, buf); +} +#endif /* CURLVERBOSE */ + +#if defined(CURL_HAVE_DIAG) && defined(__APPLE__) && !defined(HAVE_GSSAPPLE) +#pragma GCC diagnostic pop +#endif + +#endif /* HAVE_GSSAPI */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_gssapi.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_gssapi.h new file mode 100644 index 0000000000..b33df77c17 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_gssapi.h @@ -0,0 +1,96 @@ +#ifndef HEADER_CURL_GSSAPI_H +#define HEADER_CURL_GSSAPI_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" + +#ifdef HAVE_GSSAPI +extern gss_OID_desc Curl_spnego_mech_oid; +extern gss_OID_desc Curl_krb5_mech_oid; + +/* Common method for using GSS-API */ +OM_uint32 Curl_gss_init_sec_context(struct Curl_easy *data, + OM_uint32 *minor_status, + gss_ctx_id_t *context, + gss_name_t target_name, + gss_OID mech_type, + gss_channel_bindings_t input_chan_bindings, + gss_buffer_t input_token, + gss_buffer_t output_token, + const bool mutual_auth, + OM_uint32 *ret_flags, + gss_cred_id_t cred_handle); + +OM_uint32 Curl_gss_delete_sec_context(OM_uint32 *min, + gss_ctx_id_t *context, + gss_buffer_t output_token); + +OM_uint32 Curl_gss_inquire_context(OM_uint32 *minor_status, + gss_ctx_id_t context, + gss_OID *mech_type); + +OM_uint32 Curl_gss_acquire_cred(OM_uint32 *minor_status, + gss_name_t desired_name, + OM_uint32 time_req, + gss_OID_set desired_mechs, + gss_cred_usage_t cred_usage, + gss_cred_id_t *output_cred_handle, + gss_OID_set *actual_mechs, + OM_uint32 *time_rec); + +OM_uint32 Curl_gss_indicate_mechs(OM_uint32 *minor_status, + gss_OID_set *mech_set); + +#ifdef HAVE_GSS_SET_NEG_MECHS +OM_uint32 Curl_gss_set_neg_mechs(OM_uint32 *minor_status, + gss_cred_id_t cred_handle, + const gss_OID_set mech_set); +#endif + +OM_uint32 Curl_gss_release_cred(OM_uint32 *minor_status, + gss_cred_id_t *cred_handle); + +#ifdef CURLVERBOSE +/* Helper to log a GSS-API error status */ +void Curl_gss_log_error(struct Curl_easy *data, const char *prefix, + OM_uint32 major, OM_uint32 minor); +#else +#define Curl_gss_log_error(data, prefix, major, minor) \ + do { \ + (void)(data); \ + (void)(prefix); \ + (void)(major); \ + (void)(minor); \ + } while(0) +#endif + +/* Define our privacy and integrity protection values */ +#define GSSAUTH_P_NONE 1 +#define GSSAUTH_P_INTEGRITY 2 +#define GSSAUTH_P_PRIVACY 4 + +#endif /* HAVE_GSSAPI */ +#endif /* HEADER_CURL_GSSAPI_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_hmac.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_hmac.h new file mode 100644 index 0000000000..4fd8ec47bb --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_hmac.h @@ -0,0 +1,72 @@ +#ifndef HEADER_CURL_HMAC_H +#define HEADER_CURL_HMAC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#if (defined(USE_CURL_NTLM_CORE) && !defined(USE_WINDOWS_SSPI)) || \ + !defined(CURL_DISABLE_AWS) || !defined(CURL_DISABLE_DIGEST_AUTH) || \ + !defined(CURL_DISABLE_HTTPSIG) || \ + defined(USE_LIBSSH2) || defined(USE_SSL) + +#define HMAC_MD5_LENGTH 16 + +typedef CURLcode (*HMAC_hinit)(void *context); +typedef void (*HMAC_hupdate)(void *context, + const unsigned char *data, + unsigned int len); +typedef void (*HMAC_hfinal)(unsigned char *result, void *context); + +/* Per-hash function HMAC parameters. */ +struct HMAC_params { + HMAC_hinit hinit; /* Initialize context procedure. */ + HMAC_hupdate hupdate; /* Update context with data. */ + HMAC_hfinal hfinal; /* Get final result procedure. */ + unsigned int ctxtsize; /* Context structure size. */ + unsigned int maxkeylen; /* Maximum key length (bytes). */ + unsigned int resultlen; /* Result length (bytes). */ +}; + +/* HMAC computation context. */ +struct HMAC_context { + const struct HMAC_params *hash; /* Hash function definition. */ + void *hashctxt1; /* Hash function context 1. */ + void *hashctxt2; /* Hash function context 2. */ +}; + +/* Prototypes. */ +struct HMAC_context *Curl_HMAC_init(const struct HMAC_params *hashparams, + const unsigned char *key, + unsigned int keylen); +void Curl_HMAC_update(struct HMAC_context *ctxt, + const unsigned char *data, + unsigned int len); +int Curl_HMAC_final(struct HMAC_context *ctxt, unsigned char *output); + +CURLcode Curl_hmacit(const struct HMAC_params *hashparams, + const unsigned char *key, const size_t keylen, + const unsigned char *data, size_t datalen, + unsigned char *output); +#endif + +#endif /* HEADER_CURL_HMAC_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ldap.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ldap.h new file mode 100644 index 0000000000..0ccc1289e2 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ldap.h @@ -0,0 +1,30 @@ +#ifndef HEADER_CURL_LDAP_H +#define HEADER_CURL_LDAP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +extern const struct Curl_protocol Curl_protocol_ldap; + +void Curl_ldap_version(char *buf, size_t bufsz); + +#endif /* HEADER_CURL_LDAP_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_md4.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_md4.h new file mode 100644 index 0000000000..05d1624974 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_md4.h @@ -0,0 +1,37 @@ +#ifndef HEADER_CURL_MD4_H +#define HEADER_CURL_MD4_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_CURL_NTLM_CORE + +#define MD4_DIGEST_LENGTH 16 + +CURLcode Curl_md4it(unsigned char *output, const unsigned char *input, + const size_t len); + +#endif /* USE_CURL_NTLM_CORE */ + +#endif /* HEADER_CURL_MD4_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_md5.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_md5.h new file mode 100644 index 0000000000..1beaed5e66 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_md5.h @@ -0,0 +1,67 @@ +#ifndef HEADER_CURL_MD5_H +#define HEADER_CURL_MD5_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#if (defined(USE_CURL_NTLM_CORE) && !defined(USE_WINDOWS_SSPI)) || \ + !defined(CURL_DISABLE_DIGEST_AUTH) + +#include "curl_hmac.h" + +#define MD5_DIGEST_LEN 16 + +typedef CURLcode (*Curl_MD5_init_func)(void *context); +typedef void (*Curl_MD5_update_func)(void *context, + const unsigned char *data, + unsigned int len); +typedef void (*Curl_MD5_final_func)(unsigned char *result, void *context); + +struct MD5_params { + Curl_MD5_init_func md5_init_func; /* Initialize context procedure */ + Curl_MD5_update_func md5_update_func; /* Update context with data */ + Curl_MD5_final_func md5_final_func; /* Get final result procedure */ + unsigned int md5_ctxtsize; /* Context structure size */ + unsigned int md5_resultlen; /* Result length (bytes) */ +}; + +struct MD5_context { + const struct MD5_params *md5_hash; /* Hash function definition */ + void *md5_hashctx; /* Hash function context */ +}; + +extern const struct MD5_params Curl_DIGEST_MD5; +extern const struct HMAC_params Curl_HMAC_MD5; + +CURLcode Curl_md5it(unsigned char *output, const unsigned char *input, + size_t len); + +struct MD5_context *Curl_MD5_init(const struct MD5_params *md5params); +CURLcode Curl_MD5_update(struct MD5_context *context, + const unsigned char *input, + unsigned int len); +CURLcode Curl_MD5_final(struct MD5_context *context, unsigned char *result); + +#endif + +#endif /* HEADER_CURL_MD5_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_memrchr.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_memrchr.c new file mode 100644 index 0000000000..59ee176bc9 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_memrchr.c @@ -0,0 +1,53 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curl_memrchr.h" + +#ifndef HAVE_MEMRCHR +/* + * Curl_memrchr() + * + * Our memrchr() function clone for systems which lack this function. The + * memrchr() function is like the memchr() function, except that it searches + * backwards from the end of the n bytes pointed to by s instead of forward + * from the beginning. + */ +void *Curl_memrchr(const void *s, int c, size_t n) +{ + if(n > 0) { + const unsigned char *p = s; + const unsigned char *q = s; + + p += n - 1; + + while(p >= q) { + if(*p == (unsigned char)c) + return CURL_UNCONST(p); + p--; + } + } + return NULL; +} +#endif /* HAVE_MEMRCHR */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_memrchr.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_memrchr.h new file mode 100644 index 0000000000..248368b25c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_memrchr.h @@ -0,0 +1,40 @@ +#ifndef HEADER_CURL_MEMRCHR_H +#define HEADER_CURL_MEMRCHR_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_MEMRCHR + +#ifdef HAVE_STRINGS_H +# include <strings.h> +#endif + +#else /* HAVE_MEMRCHR */ +void *Curl_memrchr(const void *s, int c, size_t n); +#define memrchr(x, y, z) Curl_memrchr(x, y, z) + +#endif /* HAVE_MEMRCHR */ + +#endif /* HEADER_CURL_MEMRCHR_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ntlm_core.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ntlm_core.c new file mode 100644 index 0000000000..7aceb65e96 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ntlm_core.c @@ -0,0 +1,667 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_CURL_NTLM_CORE + +/* + * NTLM details: + * + * https://davenport.sourceforge.net/ntlm.html + * https://www.innovation.ch/java/ntlm.html + */ + +/* Please keep the SSL backend-specific #if branches in this order: + + 1. USE_OPENSSL + 2. USE_WOLFSSL + 3. USE_GNUTLS + 4. USE_MBEDTLS + 5. USE_OS400CRYPTO + 6. USE_WIN32_CRYPTO + + This ensures that: + - the same SSL branch gets activated throughout this source + file even if multiple backends are enabled at the same time. + - OpenSSL has higher priority than Windows Crypt, due + to issues with the latter supporting NTLM2Session responses + in NTLM type-3 messages. + */ + +#ifdef USE_GNUTLS +#include <nettle/version.h> +#if NETTLE_VERSION_MAJOR < 4 +#define USE_GNUTLS_DES +#endif +#endif + +#if defined(USE_OPENSSL) && defined(HAVE_DES_ECB_ENCRYPT) + +# include <openssl/des.h> +# ifdef OPENSSL_IS_AWSLC /* for versions 1.2.0 to 1.30.1 */ +# define DES_set_key_unchecked (void)DES_set_key +# endif +# define USE_OPENSSL_DES + +#elif defined(USE_WOLFSSL) && defined(HAVE_WC_DES_ECBENCRYPT) + +# include <wolfssl/options.h> +# include <wolfssl/wolfcrypt/des3.h> +# define USE_WOLFSSL_DES + +#elif defined(USE_GNUTLS_DES) +# include <nettle/des.h> +# define USE_CURL_DES_SET_ODD_PARITY +#elif defined(USE_MBEDTLS) && defined(HAVE_MBEDTLS_DES_CRYPT_ECB) +# include <mbedtls/version.h> +# if MBEDTLS_VERSION_NUMBER < 0x03020000 +# error "mbedTLS 3.2.0 or greater required" +# endif +# include <mbedtls/des.h> +# define USE_MBEDTLS_DES +#elif defined(USE_OS400CRYPTO) +# include "cipher.mih" /* mih/cipher */ +# define USE_CURL_DES_SET_ODD_PARITY +#elif defined(USE_WIN32_CRYPTO) +# include <wincrypt.h> +# define USE_CURL_DES_SET_ODD_PARITY +#else +# error "cannot compile NTLM support without a crypto library with DES." +#endif + +#include "urldata.h" +#include "strcase.h" +#include "curl_ntlm_core.h" +#include "curl_md5.h" +#include "curl_hmac.h" +#include "curl_md4.h" +#include "vauth/vauth.h" + +#ifdef USE_CURL_DES_SET_ODD_PARITY +/* + * curl_des_set_odd_parity() + * + * Copyright (C) Steve Holme, <steve_holme@hotmail.com> + * + * This is used to apply odd parity to the given byte array. It is typically + * used by when a cryptography engine does not have its own version. + * + * The function is a port of the Java based oddParity() function over at: + * + * https://davenport.sourceforge.net/ntlm.html + * + * Parameters: + * + * bytes [in/out] - The data whose parity bits are to be adjusted for + * odd parity. + * len [in] - The length of the data. + */ +static void curl_des_set_odd_parity(unsigned char *bytes, size_t len) +{ + size_t i; + + for(i = 0; i < len; i++) { + unsigned char b = bytes[i]; + + bool needs_parity = (((b >> 7) ^ (b >> 6) ^ (b >> 5) ^ + (b >> 4) ^ (b >> 3) ^ (b >> 2) ^ + (b >> 1)) & 0x01) == 0; + + if(needs_parity) + bytes[i] |= 0x01; + else + bytes[i] &= 0xfe; + } +} +#endif /* USE_CURL_DES_SET_ODD_PARITY */ + +/* + * Turns a 56-bit key into being 64-bit wide. + */ +static void extend_key_56_to_64(const unsigned char *key_56, char *key) +{ + key[0] = (char)key_56[0]; + key[1] = (char)(((key_56[0] << 7) & 0xFF) | (key_56[1] >> 1)); + key[2] = (char)(((key_56[1] << 6) & 0xFF) | (key_56[2] >> 2)); + key[3] = (char)(((key_56[2] << 5) & 0xFF) | (key_56[3] >> 3)); + key[4] = (char)(((key_56[3] << 4) & 0xFF) | (key_56[4] >> 4)); + key[5] = (char)(((key_56[4] << 3) & 0xFF) | (key_56[5] >> 5)); + key[6] = (char)(((key_56[5] << 2) & 0xFF) | (key_56[6] >> 6)); + key[7] = (char)((key_56[6] << 1) & 0xFF); +} + +#ifdef USE_OPENSSL_DES +/* + * Turns a 56-bit key into a 64-bit, odd parity key and sets the key. The + * key schedule ks is also set. + */ +static void setup_des_key(const unsigned char *key_56, DES_key_schedule *ks) +{ + DES_cblock key; + + /* Expand the 56-bit key to 64 bits */ + extend_key_56_to_64(key_56, (char *)&key); + + /* Set the key parity to odd */ + DES_set_odd_parity(&key); + + /* Set the key */ + DES_set_key_unchecked(&key, ks); +} + +#elif defined(USE_WOLFSSL_DES) +static void setup_des_key(const unsigned char *key_56, Des *des) +{ + byte key[8]; + + /* Expand the 56-bit key to 64 bits */ + extend_key_56_to_64(key_56, (char *)key); + + /* Set the key */ + wc_Des_SetKey(des, key, NULL, 0); +} + +#elif defined(USE_GNUTLS_DES) +static void setup_des_key(const unsigned char *key_56, struct des_ctx *des) +{ + char key[8]; + + /* Expand the 56-bit key to 64 bits */ + extend_key_56_to_64(key_56, key); + + /* Set the key parity to odd */ + curl_des_set_odd_parity((unsigned char *)key, sizeof(key)); + + /* Set the key */ + des_set_key(des, (const uint8_t *)key); +} + +#elif defined(USE_MBEDTLS_DES) +static bool encrypt_des(const unsigned char *in, unsigned char *out, + const unsigned char *key_56) +{ + mbedtls_des_context ctx; + char key[8]; + + /* Expand the 56-bit key to 64 bits */ + extend_key_56_to_64(key_56, key); + + /* Set the key parity to odd */ + mbedtls_des_key_set_parity((unsigned char *)key); + + /* Perform the encryption */ + mbedtls_des_init(&ctx); + mbedtls_des_setkey_enc(&ctx, (unsigned char *)key); + return mbedtls_des_crypt_ecb(&ctx, in, out) == 0; +} + +#elif defined(USE_OS400CRYPTO) +static bool encrypt_des(const unsigned char *in, unsigned char *out, + const unsigned char *key_56) +{ + char key[8]; + _CIPHER_Control_T ctl; + + /* Setup the cipher control structure */ + ctl.Func_ID = ENCRYPT_ONLY; + ctl.Data_Len = sizeof(key); + + /* Expand the 56-bit key to 64 bits */ + extend_key_56_to_64(key_56, ctl.Crypto_Key); + + /* Set the key parity to odd */ + curl_des_set_odd_parity((unsigned char *)ctl.Crypto_Key, ctl.Data_Len); + + /* Perform the encryption */ + _CIPHER((_SPCPTR *)&out, &ctl, (_SPCPTR *)&in); + + return TRUE; +} + +#elif defined(USE_WIN32_CRYPTO) +static bool encrypt_des(const unsigned char *in, unsigned char *out, + const unsigned char *key_56) +{ + HCRYPTPROV hprov; + HCRYPTKEY hkey; + struct { + BLOBHEADER hdr; + unsigned int len; + char key[8]; + } blob; + DWORD len = 8; + BOOL res; + + /* Acquire the crypto provider */ + if(!CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + return FALSE; + + /* Setup the key blob structure */ + memset(&blob, 0, sizeof(blob)); + blob.hdr.bType = PLAINTEXTKEYBLOB; + blob.hdr.bVersion = 2; + blob.hdr.aiKeyAlg = CALG_DES; + blob.len = sizeof(blob.key); + + /* Expand the 56-bit key to 64 bits */ + extend_key_56_to_64(key_56, blob.key); + + /* Set the key parity to odd */ + curl_des_set_odd_parity((unsigned char *)blob.key, sizeof(blob.key)); + + /* Import the key */ + if(!CryptImportKey(hprov, (BYTE *)&blob, sizeof(blob), 0, 0, &hkey)) { + CryptReleaseContext(hprov, 0); + + return FALSE; + } + + memcpy(out, in, 8); + + /* Perform the encryption */ + res = CryptEncrypt(hkey, 0, FALSE, 0, out, &len, len); + + CryptDestroyKey(hkey); + CryptReleaseContext(hprov, 0); + + return res; +} + +#endif /* crypto backends */ + +/* + * takes a 21-byte array and treats it as 3 56-bit DES keys. The + * 8-byte plaintext is encrypted with each key and the resulting 24 + * bytes are stored in the results array. + */ +void Curl_ntlm_core_lm_resp(const unsigned char *keys, + const unsigned char *plaintext, + unsigned char *results) +{ +#ifdef USE_OPENSSL_DES + DES_key_schedule ks; + + setup_des_key(keys, &ks); + DES_ecb_encrypt((DES_cblock *)CURL_UNCONST(plaintext), + (DES_cblock *)results, &ks, DES_ENCRYPT); + + setup_des_key(keys + 7, &ks); + DES_ecb_encrypt((DES_cblock *)CURL_UNCONST(plaintext), + (DES_cblock *)(results + 8), &ks, DES_ENCRYPT); + + setup_des_key(keys + 14, &ks); + DES_ecb_encrypt((DES_cblock *)CURL_UNCONST(plaintext), + (DES_cblock *)(results + 16), &ks, DES_ENCRYPT); +#elif defined(USE_WOLFSSL_DES) + Des des; + setup_des_key(keys, &des); + wc_Des_EcbEncrypt(&des, results, plaintext, DES_KEY_SIZE); + setup_des_key(keys + 7, &des); + wc_Des_EcbEncrypt(&des, results + 8, plaintext, DES_KEY_SIZE); + setup_des_key(keys + 14, &des); + wc_Des_EcbEncrypt(&des, results + 16, plaintext, DES_KEY_SIZE); +#elif defined(USE_GNUTLS_DES) + struct des_ctx des; + setup_des_key(keys, &des); + des_encrypt(&des, 8, results, plaintext); + setup_des_key(keys + 7, &des); + des_encrypt(&des, 8, results + 8, plaintext); + setup_des_key(keys + 14, &des); + des_encrypt(&des, 8, results + 16, plaintext); +#elif defined(USE_MBEDTLS_DES) || defined(USE_OS400CRYPTO) || \ + defined(USE_WIN32_CRYPTO) + encrypt_des(plaintext, results, keys); + encrypt_des(plaintext, results + 8, keys + 7); + encrypt_des(plaintext, results + 16, keys + 14); +#else + (void)keys; + (void)plaintext; + (void)results; +#endif +} + +/* + * Set up lanmanager hashed password + */ +CURLcode Curl_ntlm_core_mk_lm_hash(const char *password, + unsigned char *lmbuffer /* 21 bytes */) +{ + unsigned char pw[14]; + static const unsigned char magic[] = { + 0x4B, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25 /* i.e. KGS!@#$% */ + }; + size_t len = CURLMIN(strlen(password), 14); + + Curl_strntoupper((char *)pw, password, len); + memset(&pw[len], 0, 14 - len); + + { + /* Create LanManager hashed password. */ +#ifdef USE_OPENSSL_DES + DES_key_schedule ks; + + setup_des_key(pw, &ks); + DES_ecb_encrypt((DES_cblock *)CURL_UNCONST(magic), + (DES_cblock *)lmbuffer, &ks, DES_ENCRYPT); + + setup_des_key(pw + 7, &ks); + DES_ecb_encrypt((DES_cblock *)CURL_UNCONST(magic), + (DES_cblock *)(lmbuffer + 8), &ks, DES_ENCRYPT); +#elif defined(USE_WOLFSSL_DES) + Des des; + setup_des_key(pw, &des); + wc_Des_EcbEncrypt(&des, lmbuffer, magic, DES_KEY_SIZE); + setup_des_key(pw + 7, &des); + wc_Des_EcbEncrypt(&des, lmbuffer + 8, magic, DES_KEY_SIZE); +#elif defined(USE_GNUTLS_DES) + struct des_ctx des; + setup_des_key(pw, &des); + des_encrypt(&des, 8, lmbuffer, magic); + setup_des_key(pw + 7, &des); + des_encrypt(&des, 8, lmbuffer + 8, magic); +#elif defined(USE_MBEDTLS_DES) || defined(USE_OS400CRYPTO) || \ + defined(USE_WIN32_CRYPTO) + encrypt_des(magic, lmbuffer, pw); + encrypt_des(magic, lmbuffer + 8, pw + 7); +#endif + + memset(lmbuffer + 16, 0, 21 - 16); + } + + return CURLE_OK; +} + +static void ascii_to_unicode_le(unsigned char *dest, const char *src, + size_t srclen) +{ + size_t i; + for(i = 0; i < srclen; i++) { + dest[2 * i] = (unsigned char)src[i]; + dest[(2 * i) + 1] = '\0'; + } +} + +/* + * Set up nt hashed passwords + * @unittest: 1600 + */ +CURLcode Curl_ntlm_core_mk_nt_hash(const char *password, + unsigned char *ntbuffer /* 21 bytes */) +{ + size_t len = strlen(password); + unsigned char *pw; + CURLcode result; + if(len > SIZE_MAX / 2) /* avoid integer overflow */ + return CURLE_OUT_OF_MEMORY; + pw = len ? curlx_malloc(len * 2) : (unsigned char *)curlx_strdup(""); + if(!pw) + return CURLE_OUT_OF_MEMORY; + + ascii_to_unicode_le(pw, password, len); + + /* Create NT hashed password. */ + result = Curl_md4it(ntbuffer, pw, 2 * len); + if(!result) + memset(ntbuffer + 16, 0, 21 - 16); + + curlx_free(pw); + + return result; +} + +#ifndef USE_WINDOWS_SSPI + +#define NTLMv2_BLOB_SIGNATURE "\x01\x01\x00\x00" +#define NTLMv2_BLOB_LEN (44 - 16 + ntlm->target_info_len + 4) + +/* Timestamp in tenths of a microsecond since January 1, 1601 00:00:00 UTC. */ +struct ms_filetime { + unsigned int dwLowDateTime; + unsigned int dwHighDateTime; +}; + +/* Convert a time_t to an MS FILETIME (MS-DTYP section 2.3.3). */ +static void time2filetime(struct ms_filetime *ft, time_t t) +{ +#if SIZEOF_TIME_T > 4 + t = (t + (curl_off_t)11644473600) * 10000000; + ft->dwLowDateTime = (unsigned int)(t & 0xFFFFFFFF); + ft->dwHighDateTime = (unsigned int)(t >> 32); +#else + unsigned int r, s; + unsigned int i; + + ft->dwLowDateTime = (unsigned int)(t & 0xFFFFFFFF); + ft->dwHighDateTime = 0; + +#ifndef HAVE_TIME_T_UNSIGNED + /* Extend sign if needed. */ + if(ft->dwLowDateTime & 0x80000000) + ft->dwHighDateTime = ~(unsigned int)0; +#endif + + /* Bias seconds to Jan 1, 1601. + 134774 days = 11644473600 seconds = 0x2B6109100 */ + r = ft->dwLowDateTime; + ft->dwLowDateTime = (ft->dwLowDateTime + 0xB6109100U) & 0xFFFFFFFF; + ft->dwHighDateTime += ft->dwLowDateTime < r ? 0x03 : 0x02; + + /* Convert to tenths of microseconds. */ + ft->dwHighDateTime *= 10000000; + i = 32; + do { + i -= 8; + s = ((ft->dwLowDateTime >> i) & 0xFF) * (10000000 - 1); + r = (s << i) & 0xFFFFFFFF; + s >>= 1; /* Split shift to avoid width overflow. */ + s >>= 31 - i; + ft->dwLowDateTime = (ft->dwLowDateTime + r) & 0xFFFFFFFF; + if(ft->dwLowDateTime < r) + s++; + ft->dwHighDateTime += s; + } while(i); + ft->dwHighDateTime &= 0xFFFFFFFF; +#endif +} + +static void ascii_uppercase_to_unicode_le(unsigned char *dest, + const char *src, size_t srclen) +{ + size_t i; + for(i = 0; i < srclen; i++) { + dest[2 * i] = (unsigned char)(Curl_raw_toupper(src[i])); + dest[(2 * i) + 1] = '\0'; + } +} + +/* This creates the NTLMv2 hash by using NTLM hash as the key and Unicode + * (uppercase UserName + Domain) as the data + */ +CURLcode Curl_ntlm_core_mk_ntlmv2_hash(const char *user, size_t userlen, + const char *domain, size_t domlen, + unsigned char *ntlmhash, + unsigned char *ntlmv2hash) +{ + /* Unicode representation */ + size_t identity_len; + unsigned char *identity; + CURLcode result = CURLE_OK; + + if((userlen > CURL_MAX_INPUT_LENGTH) || (domlen > CURL_MAX_INPUT_LENGTH)) + return CURLE_OUT_OF_MEMORY; + + identity_len = (userlen + domlen) * 2; + identity = curlx_malloc(identity_len + 1); + + if(!identity) + return CURLE_OUT_OF_MEMORY; + + ascii_uppercase_to_unicode_le(identity, user, userlen); + ascii_to_unicode_le(identity + (userlen << 1), domain, domlen); + + result = Curl_hmacit(&Curl_HMAC_MD5, ntlmhash, 16, identity, identity_len, + ntlmv2hash); + curlx_free(identity); + + return result; +} + +/* + * Curl_ntlm_core_mk_ntlmv2_resp() + * + * This creates the NTLMv2 response as set in the NTLM type-3 message. + * + * Parameters: + * + * ntlmv2hash [in] - The NTLMv2 hash (16 bytes) + * challenge_client [in] - The client nonce (8 bytes) + * ntlm [in] - The NTLM data struct being used to read TargetInfo + and Server challenge received in the type-2 message + * ntresp [out] - The address where a pointer to newly allocated + * memory holding the NTLMv2 response. + * ntresp_len [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_ntlm_core_mk_ntlmv2_resp(const unsigned char *ntlmv2hash, + const unsigned char *challenge_client, + const struct ntlmdata *ntlm, + unsigned char **ntresp, + unsigned int *ntresp_len) +{ + /* NTLMv2 response structure: + ----------------------------------------------------------------------------- + 0 HMAC MD5 16 bytes + ------BLOB------------------------------------------------------------------- + 16 Signature 0x01010000 + 20 Reserved long (0x00000000) + 24 Timestamp LE, 64-bit signed value representing the number of + tenths of a microsecond since January 1, 1601. + 32 Client Nonce 8 bytes + 40 Unknown 4 bytes + 44 Target Info N bytes (from the type-2 message) + 44+N Unknown 4 bytes + ----------------------------------------------------------------------------- + */ + + unsigned int len = 0; + unsigned char *ptr = NULL; + unsigned char hmac_output[HMAC_MD5_LENGTH]; + struct ms_filetime tw; + + CURLcode result = CURLE_OK; + + /* Calculate the timestamp */ +#ifdef DEBUGBUILD + char *force_timestamp = getenv("CURL_FORCETIME"); + if(force_timestamp) + time2filetime(&tw, (time_t)0); + else +#endif + time2filetime(&tw, time(NULL)); + + /* Calculate the response len */ + len = HMAC_MD5_LENGTH + NTLMv2_BLOB_LEN; + + /* Allocate the response */ + ptr = curlx_calloc(1, len); + if(!ptr) + return CURLE_OUT_OF_MEMORY; + + /* Create the BLOB structure */ + curl_msnprintf((char *)ptr + HMAC_MD5_LENGTH, NTLMv2_BLOB_LEN, + "%c%c%c%c" /* NTLMv2_BLOB_SIGNATURE */ + "%c%c%c%c" /* Reserved = 0 */ + "%c%c%c%c%c%c%c%c", /* Timestamp */ + NTLMv2_BLOB_SIGNATURE[0], NTLMv2_BLOB_SIGNATURE[1], + NTLMv2_BLOB_SIGNATURE[2], NTLMv2_BLOB_SIGNATURE[3], + 0, 0, 0, 0, + LONGQUARTET(tw.dwLowDateTime), + LONGQUARTET(tw.dwHighDateTime)); + + memcpy(ptr + 32, challenge_client, 8); + if(ntlm->target_info_len) + memcpy(ptr + 44, ntlm->target_info, ntlm->target_info_len); + + /* Concatenate the Type 2 challenge with the BLOB and do HMAC MD5 */ + memcpy(ptr + 8, &ntlm->nonce[0], 8); + result = Curl_hmacit(&Curl_HMAC_MD5, ntlmv2hash, HMAC_MD5_LENGTH, ptr + 8, + NTLMv2_BLOB_LEN + 8, hmac_output); + if(result) { + curlx_free(ptr); + return result; + } + + /* Concatenate the HMAC MD5 output with the BLOB */ + memcpy(ptr, hmac_output, HMAC_MD5_LENGTH); + + /* Return the response */ + *ntresp = ptr; + *ntresp_len = len; + + return result; +} + +/* + * Curl_ntlm_core_mk_lmv2_resp() + * + * This creates the LMv2 response as used in the NTLM type-3 message. + * + * Parameters: + * + * ntlmv2hash [in] - The NTLMv2 hash (16 bytes) + * challenge_client [in] - The client nonce (8 bytes) + * challenge_server [in] - The server challenge (8 bytes) + * lmresp [out] - The LMv2 response (24 bytes) + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_ntlm_core_mk_lmv2_resp(const unsigned char *ntlmv2hash, + const unsigned char *challenge_client, + const unsigned char *challenge_server, + unsigned char *lmresp) +{ + unsigned char data[16]; + unsigned char hmac_output[16]; + CURLcode result = CURLE_OK; + + memcpy(&data[0], challenge_server, 8); + memcpy(&data[8], challenge_client, 8); + + result = Curl_hmacit(&Curl_HMAC_MD5, ntlmv2hash, 16, &data[0], 16, + hmac_output); + if(result) + return result; + + /* Concatenate the HMAC MD5 output with the client nonce */ + memcpy(lmresp, hmac_output, 16); + memcpy(lmresp + 16, challenge_client, 8); + + return result; +} + +#endif /* !USE_WINDOWS_SSPI */ + +#endif /* USE_CURL_NTLM_CORE */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ntlm_core.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ntlm_core.h new file mode 100644 index 0000000000..df24158f8e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_ntlm_core.h @@ -0,0 +1,73 @@ +#ifndef HEADER_CURL_NTLM_CORE_H +#define HEADER_CURL_NTLM_CORE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_CURL_NTLM_CORE + +struct ntlmdata; + +/* Helpers to generate function byte arguments in little endian order */ +#define SHORTPAIR(x) ((int)((x) & 0xff)), ((int)(((x) >> 8) & 0xff)) +#define LONGQUARTET(x) ((int)((x) & 0xff)), ((int)(((x) >> 8) & 0xff)), \ + ((int)(((x) >> 16) & 0xff)), ((int)(((x) >> 24) & 0xff)) + +void Curl_ntlm_core_lm_resp(const unsigned char *keys, + const unsigned char *plaintext, + unsigned char *results); + +CURLcode Curl_ntlm_core_mk_lm_hash(const char *password, + unsigned char *lmbuffer /* 21 bytes */); + +CURLcode Curl_ntlm_core_mk_nt_hash(const char *password, + unsigned char *ntbuffer /* 21 bytes */); + +#ifndef USE_WINDOWS_SSPI + +CURLcode Curl_hmac_md5(const unsigned char *key, unsigned int keylen, + const unsigned char *data, unsigned int datalen, + unsigned char *output); + +CURLcode Curl_ntlm_core_mk_ntlmv2_hash(const char *user, size_t userlen, + const char *domain, size_t domlen, + unsigned char *ntlmhash, + unsigned char *ntlmv2hash); + +CURLcode Curl_ntlm_core_mk_ntlmv2_resp(const unsigned char *ntlmv2hash, + const unsigned char *challenge_client, + const struct ntlmdata *ntlm, + unsigned char **ntresp, + unsigned int *ntresp_len); + +CURLcode Curl_ntlm_core_mk_lmv2_resp(const unsigned char *ntlmv2hash, + const unsigned char *challenge_client, + const unsigned char *challenge_server, + unsigned char *lmresp); + +#endif /* !USE_WINDOWS_SSPI */ + +#endif /* USE_CURL_NTLM_CORE */ + +#endif /* HEADER_CURL_NTLM_CORE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_printf.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_printf.h new file mode 100644 index 0000000000..3b1a5af3b4 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_printf.h @@ -0,0 +1,37 @@ +#ifndef HEADER_CURL_PRINTF_H +#define HEADER_CURL_PRINTF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#define MERR_OK 0 +#define MERR_MEM 1 +#define MERR_TOO_LARGE 2 + +/* Lower-case digits. */ +extern const unsigned char Curl_ldigits[]; + +/* Upper-case digits. */ +extern const unsigned char Curl_udigits[]; + +#endif /* HEADER_CURL_PRINTF_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_range.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_range.c new file mode 100644 index 0000000000..9bbafa40cf --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_range.c @@ -0,0 +1,91 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curl_range.h" +#include "curl_trc.h" +#include "curlx/strparse.h" + +/* Only include this function if one or more of FTP, FILE are enabled. */ +#if !defined(CURL_DISABLE_FTP) || !defined(CURL_DISABLE_FILE) + +/* Check if this is a range download, and if so, set the internal variables + properly. */ +CURLcode Curl_range(struct Curl_easy *data) +{ + if(data->state.use_range && data->state.range) { + curl_off_t from, to; + bool first_num = TRUE; + const char *p = data->state.range; + if(curlx_str_number(&p, &from, CURL_OFF_T_MAX)) + first_num = FALSE; + + if(curlx_str_single(&p, '-')) + /* no leading dash or after the first number is an error */ + return CURLE_RANGE_ERROR; + + if(curlx_str_number(&p, &to, CURL_OFF_T_MAX)) { + /* no second number */ + /* X - */ + data->state.resume_from = from; + DEBUGF(infof(data, "RANGE %" FMT_OFF_T " to end of file", from)); + } + else if(!first_num) { + /* -Y */ + if(!to) + /* "-0" is wrong */ + return CURLE_RANGE_ERROR; + + data->req.maxdownload = to; + data->state.resume_from = -to; + DEBUGF(infof(data, "RANGE the last %" FMT_OFF_T " bytes", to)); + } + else { + /* X-Y */ + curl_off_t totalsize; + + /* Ensure the range is sensible - to should follow from. */ + if(from > to) + return CURLE_RANGE_ERROR; + + totalsize = to - from; + if(totalsize == CURL_OFF_T_MAX) + return CURLE_RANGE_ERROR; + + data->req.maxdownload = totalsize + 1; /* include last byte */ + data->state.resume_from = from; + DEBUGF(infof(data, "RANGE from %" FMT_OFF_T + " getting %" FMT_OFF_T " bytes", + from, data->req.maxdownload)); + } + DEBUGF(infof(data, "range-download from %" FMT_OFF_T + " to %" FMT_OFF_T ", totally %" FMT_OFF_T " bytes", + from, to, data->req.maxdownload)); + } + else + data->req.maxdownload = -1; + return CURLE_OK; +} + +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_range.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_range.h new file mode 100644 index 0000000000..97354677c2 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_range.h @@ -0,0 +1,31 @@ +#ifndef HEADER_CURL_RANGE_H +#define HEADER_CURL_RANGE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" + +CURLcode Curl_range(struct Curl_easy *data); +#endif /* HEADER_CURL_RANGE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sasl.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sasl.c new file mode 100644 index 0000000000..c4ff1e5262 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sasl.c @@ -0,0 +1,908 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC2195 CRAM-MD5 authentication + * RFC2617 Basic and Digest Access Authentication + * RFC2831 DIGEST-MD5 authentication + * RFC4422 Simple Authentication and Security Layer (SASL) + * RFC4616 PLAIN authentication + * RFC5802 SCRAM-SHA-1 authentication + * RFC7677 SCRAM-SHA-256 authentication + * RFC6749 OAuth 2.0 Authorization Framework + * RFC7628 A Set of SASL Mechanisms for OAuth + * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt> + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_POP3) || \ + (!defined(CURL_DISABLE_LDAP) && defined(USE_OPENLDAP)) + +#include "urldata.h" +#include "curlx/base64.h" +#include "vauth/vauth.h" +#include "cfilters.h" +#include "curl_sasl.h" +#include "curl_trc.h" + +/* Supported mechanisms */ +static const struct { + const char *name; /* Name */ + size_t len; /* Name length */ + unsigned short bit; /* Flag bit */ +} mechtable[] = { + { "LOGIN", 5, SASL_MECH_LOGIN }, + { "PLAIN", 5, SASL_MECH_PLAIN }, + { "CRAM-MD5", 8, SASL_MECH_CRAM_MD5 }, + { "DIGEST-MD5", 10, SASL_MECH_DIGEST_MD5 }, + { "GSSAPI", 6, SASL_MECH_GSSAPI }, + { "EXTERNAL", 8, SASL_MECH_EXTERNAL }, + { "NTLM", 4, SASL_MECH_NTLM }, + { "XOAUTH2", 7, SASL_MECH_XOAUTH2 }, + { "OAUTHBEARER", 11, SASL_MECH_OAUTHBEARER }, + { "SCRAM-SHA-1", 11, SASL_MECH_SCRAM_SHA_1 }, + { "SCRAM-SHA-256",13, SASL_MECH_SCRAM_SHA_256 }, + { ZERO_NULL, 0, 0 } +}; + +/* + * Curl_sasl_decode_mech() + * + * Convert a SASL mechanism name into a token. + * + * Parameters: + * + * ptr [in] - The mechanism string. + * maxlen [in] - Maximum mechanism string length. + * len [out] - If not NULL, effective name length. + * + * Returns the SASL mechanism token or 0 if no match. + */ +unsigned short Curl_sasl_decode_mech(const char *ptr, size_t maxlen, + size_t *len) +{ + unsigned int i; + char c; + + for(i = 0; mechtable[i].name; i++) { + if(maxlen >= mechtable[i].len && + curl_strnequal(ptr, mechtable[i].name, mechtable[i].len)) { + if(len) + *len = mechtable[i].len; + + if(maxlen == mechtable[i].len) + return mechtable[i].bit; + + c = ptr[mechtable[i].len]; + if(!ISUPPER(c) && !ISDIGIT(c) && c != '-' && c != '_') + return mechtable[i].bit; + } + } + + return 0; +} + +/* + * Curl_sasl_parse_url_auth_option() + * + * Parse the URL login options. + */ +CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl, + const char *value, size_t len) +{ + CURLcode result = CURLE_OK; + size_t mechlen; + + if(!len) + return CURLE_URL_MALFORMAT; + + if(sasl->resetprefs) { + sasl->resetprefs = FALSE; + sasl->prefmech = SASL_AUTH_NONE; + } + + if(!strncmp(value, "*", len)) + sasl->prefmech = SASL_AUTH_DEFAULT; + else { + unsigned short mechbit = Curl_sasl_decode_mech(value, len, &mechlen); + if(mechbit && mechlen == len) + sasl->prefmech |= mechbit; + else + result = CURLE_URL_MALFORMAT; + } + + return result; +} + +/* + * Curl_sasl_init() + * + * Initializes the SASL structure. + */ +void Curl_sasl_init(struct SASL *sasl, struct Curl_easy *data, + const struct SASLproto *params) +{ + uint32_t auth = data->set.httpauth; + + sasl->params = params; /* Set protocol dependent parameters */ + sasl->state = SASL_STOP; /* Not yet running */ + sasl->curmech = NULL; /* No mechanism yet. */ + sasl->authmechs = SASL_AUTH_NONE; /* No known authentication mechanism yet */ + sasl->prefmech = params->defmechs; /* Default preferred mechanisms */ + sasl->authused = SASL_AUTH_NONE; /* The authentication mechanism used */ + sasl->resetprefs = TRUE; /* Reset prefmech upon AUTH parsing. */ + sasl->mutual_auth = FALSE; /* No mutual authentication (GSSAPI only) */ + sasl->force_ir = FALSE; /* Respect external option */ + + if(auth != CURLAUTH_BASIC) { + unsigned short mechs = SASL_AUTH_NONE; + + /* If some usable http authentication options have been set, determine + new defaults from them. */ + if(auth & CURLAUTH_BASIC) + mechs |= SASL_MECH_PLAIN | SASL_MECH_LOGIN; + if(auth & CURLAUTH_DIGEST) + mechs |= SASL_MECH_DIGEST_MD5; + if(auth & CURLAUTH_NTLM) + mechs |= SASL_MECH_NTLM; + if(auth & CURLAUTH_BEARER) + mechs |= SASL_MECH_OAUTHBEARER | SASL_MECH_XOAUTH2; + if(auth & CURLAUTH_GSSAPI) + mechs |= SASL_MECH_GSSAPI; + + if(mechs != SASL_AUTH_NONE) + sasl->prefmech = mechs; + } +} + +/* + * sasl_state() + * + * This is the ONLY way to change SASL state! + */ +static void sasl_state(struct SASL *sasl, struct Curl_easy *data, + saslstate newstate) +{ +#if defined(DEBUGBUILD) && defined(CURLVERBOSE) + /* for debug purposes */ + static const char * const names[] = { + "STOP", + "PLAIN", + "LOGIN", + "LOGIN_PASSWD", + "EXTERNAL", + "CRAMMD5", + "DIGESTMD5", + "DIGESTMD5_RESP", + "NTLM", + "NTLM_TYPE2MSG", + "GSSAPI", + "GSSAPI_TOKEN", + "GSSAPI_NO_DATA", + "OAUTH2", + "OAUTH2_RESP", + "GSASL", + "CANCEL", + "FINAL", + /* LAST */ + }; + + if(sasl->state != newstate) + infof(data, "SASL %p state change from %s to %s", + (void *)sasl, names[sasl->state], names[newstate]); +#else + (void)data; +#endif + + sasl->state = newstate; +} + +#if defined(USE_NTLM) || defined(USE_GSASL) || defined(USE_KERBEROS5) || \ + !defined(CURL_DISABLE_DIGEST_AUTH) +/* Get the SASL server message and convert it to binary. */ +static CURLcode get_server_message(struct SASL *sasl, struct Curl_easy *data, + struct bufref *out) +{ + CURLcode result = CURLE_OK; + + result = sasl->params->getmessage(data, out); + if(!result && (sasl->params->flags & SASL_FLAG_BASE64)) { + const char *serverdata = Curl_bufref_ptr(out); + + if(!*serverdata) + Curl_bufref_set(out, NULL, 0, NULL); + else { + unsigned char *msg; + size_t msglen; + + result = curlx_base64_decode(serverdata, &msg, &msglen); + if(!result) + Curl_bufref_set(out, msg, msglen, curl_free); + } + } + return result; +} +#endif + +/* Encode the outgoing SASL message. */ +static CURLcode build_message(struct SASL *sasl, struct bufref *msg) +{ + CURLcode result = CURLE_OK; + + if(sasl->params->flags & SASL_FLAG_BASE64) { + if(!Curl_bufref_ptr(msg)) /* Empty message. */ + Curl_bufref_set(msg, "", 0, NULL); + else if(Curl_bufref_len(msg)) { + char *base64; + size_t base64len; + + result = curlx_base64_encode(Curl_bufref_uptr(msg), + Curl_bufref_len(msg), &base64, &base64len); + if(!result) + Curl_bufref_set(msg, base64, base64len, curl_free); + } + } + + return result; +} + +/* + * Curl_sasl_can_authenticate() + * + * Check if we have enough auth data and capabilities to authenticate. + */ +bool Curl_sasl_can_authenticate(struct SASL *sasl, struct Curl_easy *data) +{ + /* Have credentials been provided? */ + if(data->conn->creds) + return TRUE; + + /* EXTERNAL can authenticate without a username and/or password */ + if(sasl->authmechs & sasl->prefmech & SASL_MECH_EXTERNAL) + return TRUE; + + return FALSE; +} + +struct sasl_ctx { + struct SASL *sasl; + struct connectdata *conn; + unsigned short enabledmechs; + const char *mech; + saslstate state1; + saslstate state2; + struct bufref resp; + CURLcode result; +}; + +static bool sasl_choose_external(struct Curl_easy *data, struct sasl_ctx *sctx) +{ + if((sctx->enabledmechs & SASL_MECH_EXTERNAL) && + !Curl_creds_has_passwd(sctx->conn->creds)) { + sctx->mech = SASL_MECH_STRING_EXTERNAL; + sctx->state1 = SASL_EXTERNAL; + sctx->sasl->authused = SASL_MECH_EXTERNAL; + + if(sctx->sasl->force_ir || data->set.sasl_ir) + Curl_auth_create_external_message( + Curl_creds_user(sctx->conn->creds), &sctx->resp); + return TRUE; + } + return FALSE; +} + +#ifdef USE_KERBEROS5 +static bool sasl_choose_krb5(struct Curl_easy *data, struct sasl_ctx *sctx) +{ + if((sctx->enabledmechs & SASL_MECH_GSSAPI) && + Curl_auth_is_gssapi_supported() && + Curl_auth_user_contains_domain(sctx->conn->creds)) { + const char *service = Curl_creds_has_sasl_service(sctx->conn->creds) ? + Curl_creds_sasl_service(sctx->conn->creds) : sctx->sasl->params->service; + + sctx->sasl->mutual_auth = FALSE; + sctx->mech = SASL_MECH_STRING_GSSAPI; + sctx->state1 = SASL_GSSAPI; + sctx->state2 = SASL_GSSAPI_TOKEN; + sctx->sasl->authused = SASL_MECH_GSSAPI; + + if(sctx->sasl->force_ir || data->set.sasl_ir) { + struct kerberos5data *krb5 = Curl_auth_krb5_get(sctx->conn); + sctx->result = !krb5 ? CURLE_OUT_OF_MEMORY : + Curl_auth_create_gssapi_user_message(data, sctx->conn->creds, + service, + sctx->conn->origin->hostname, + (bool)sctx->sasl->mutual_auth, + NULL, krb5, &sctx->resp); + } + return TRUE; + } + return FALSE; +} +#endif /* USE_KERBEROS5 */ + +#ifdef USE_GSASL +static bool sasl_choose_gsasl(struct Curl_easy *data, struct sasl_ctx *sctx) +{ + struct gsasldata *gsasl; + struct bufref nullmsg; + + if((sctx->enabledmechs & + (SASL_MECH_SCRAM_SHA_256 | SASL_MECH_SCRAM_SHA_1))) { + gsasl = Curl_auth_gsasl_get(sctx->conn); + if(!gsasl) { + sctx->result = CURLE_OUT_OF_MEMORY; + return TRUE; /* attempted, but failed */ + } + + if((sctx->enabledmechs & SASL_MECH_SCRAM_SHA_256) && + Curl_auth_gsasl_is_supported(data, SASL_MECH_STRING_SCRAM_SHA_256, + gsasl)) { + sctx->mech = SASL_MECH_STRING_SCRAM_SHA_256; + sctx->sasl->authused = SASL_MECH_SCRAM_SHA_256; + } + else if((sctx->enabledmechs & SASL_MECH_SCRAM_SHA_1) && + Curl_auth_gsasl_is_supported(data, SASL_MECH_STRING_SCRAM_SHA_1, + gsasl)) { + sctx->mech = SASL_MECH_STRING_SCRAM_SHA_1; + sctx->sasl->authused = SASL_MECH_SCRAM_SHA_1; + } + else + return FALSE; + + Curl_bufref_init(&nullmsg); + sctx->state1 = SASL_GSASL; + sctx->state2 = SASL_GSASL; + sctx->result = Curl_auth_gsasl_start(data, sctx->conn->creds, gsasl); + if(!sctx->result && (sctx->sasl->force_ir || data->set.sasl_ir)) + sctx->result = Curl_auth_gsasl_token(data, &nullmsg, gsasl, &sctx->resp); + return TRUE; + } + return FALSE; +} + +#endif /* USE_GSASL */ + +#ifndef CURL_DISABLE_DIGEST_AUTH +static bool sasl_choose_digest(struct Curl_easy *data, struct sasl_ctx *sctx) +{ + (void)data; + if((sctx->enabledmechs & SASL_MECH_DIGEST_MD5) && + Curl_auth_is_digest_supported()) { + sctx->mech = SASL_MECH_STRING_DIGEST_MD5; + sctx->state1 = SASL_DIGESTMD5; + sctx->sasl->authused = SASL_MECH_DIGEST_MD5; + return TRUE; + } + else if(sctx->enabledmechs & SASL_MECH_CRAM_MD5) { + sctx->mech = SASL_MECH_STRING_CRAM_MD5; + sctx->state1 = SASL_CRAMMD5; + sctx->sasl->authused = SASL_MECH_CRAM_MD5; + return TRUE; + } + return FALSE; +} +#endif /* !CURL_DISABLE_DIGEST_AUTH */ + +#ifdef USE_NTLM +static bool sasl_choose_ntlm(struct Curl_easy *data, struct sasl_ctx *sctx) +{ + if((sctx->enabledmechs & SASL_MECH_NTLM) && + Curl_auth_is_ntlm_supported()) { + const char *service = Curl_creds_has_sasl_service(sctx->conn->creds) ? + Curl_creds_sasl_service(sctx->conn->creds) : sctx->sasl->params->service; + const char *hostname; + + Curl_conn_get_current_host(data, FIRSTSOCKET, &hostname, NULL); + + sctx->mech = SASL_MECH_STRING_NTLM; + sctx->state1 = SASL_NTLM; + sctx->state2 = SASL_NTLM_TYPE2MSG; + sctx->sasl->authused = SASL_MECH_NTLM; + + if(sctx->sasl->force_ir || data->set.sasl_ir) { + struct ntlmdata *ntlm = Curl_auth_ntlm_get(sctx->conn, FALSE); + sctx->result = !ntlm ? CURLE_OUT_OF_MEMORY : + Curl_auth_create_ntlm_type1_message(data, sctx->conn->creds, + service, hostname, + ntlm, &sctx->resp); + } + return TRUE; + } + return FALSE; +} +#endif /* USE_NTLM */ + +static bool sasl_choose_oauth(struct Curl_easy *data, struct sasl_ctx *sctx) +{ + if(Curl_creds_has_oauth_bearer(data->state.creds) && + (sctx->enabledmechs & SASL_MECH_OAUTHBEARER)) { + const char *hostname; + int port; + Curl_conn_get_current_host(data, FIRSTSOCKET, &hostname, &port); + + sctx->mech = SASL_MECH_STRING_OAUTHBEARER; + sctx->state1 = SASL_OAUTH2; + sctx->state2 = SASL_OAUTH2_RESP; + sctx->sasl->authused = SASL_MECH_OAUTHBEARER; + + if(sctx->sasl->force_ir || data->set.sasl_ir) + sctx->result = + Curl_auth_create_oauth_bearer_message(sctx->conn->creds, + hostname, port, &sctx->resp); + return TRUE; + } + return FALSE; +} + +static bool sasl_choose_oauth2(struct Curl_easy *data, struct sasl_ctx *sctx) +{ + if(Curl_creds_has_oauth_bearer(sctx->conn->creds) && + (sctx->enabledmechs & SASL_MECH_XOAUTH2)) { + sctx->mech = SASL_MECH_STRING_XOAUTH2; + sctx->state1 = SASL_OAUTH2; + sctx->sasl->authused = SASL_MECH_XOAUTH2; + + if(sctx->sasl->force_ir || data->set.sasl_ir) + sctx->result = Curl_auth_create_xoauth_bearer_message( + sctx->conn->creds, &sctx->resp); + return TRUE; + } + return FALSE; +} + +static bool sasl_choose_plain(struct Curl_easy *data, struct sasl_ctx *sctx) +{ + if(sctx->enabledmechs & SASL_MECH_PLAIN) { + sctx->mech = SASL_MECH_STRING_PLAIN; + sctx->state1 = SASL_PLAIN; + sctx->sasl->authused = SASL_MECH_PLAIN; + + if(sctx->sasl->force_ir || data->set.sasl_ir) + sctx->result = + Curl_auth_create_plain_message(sctx->conn->creds, &sctx->resp); + return TRUE; + } + return FALSE; +} + +static bool sasl_choose_login(struct Curl_easy *data, struct sasl_ctx *sctx) +{ + if(sctx->enabledmechs & SASL_MECH_LOGIN) { + sctx->mech = SASL_MECH_STRING_LOGIN; + sctx->state1 = SASL_LOGIN; + sctx->state2 = SASL_LOGIN_PASSWD; + sctx->sasl->authused = SASL_MECH_LOGIN; + + if(sctx->sasl->force_ir || data->set.sasl_ir) + Curl_auth_create_login_message( + Curl_creds_user(sctx->conn->creds), &sctx->resp); + return TRUE; + } + return FALSE; +} + +/* + * Curl_sasl_start() + * + * Calculate the required login details for SASL authentication. + */ +CURLcode Curl_sasl_start(struct SASL *sasl, struct Curl_easy *data, + bool force_ir, saslprogress *progress) +{ + struct sasl_ctx sctx; + + sasl->force_ir = force_ir; /* Latch for future use */ + sasl->authused = 0; /* No mechanism used yet */ + *progress = SASL_IDLE; + + memset(&sctx, 0, sizeof(sctx)); + sctx.sasl = sasl; + sctx.conn = data->conn; + Curl_bufref_init(&sctx.resp); + sctx.enabledmechs = sasl->authmechs & sasl->prefmech; + sctx.state1 = SASL_STOP; + sctx.state2 = SASL_FINAL; + + /* Calculate the supported authentication mechanism, by decreasing order of + security, as well as the initial response where appropriate */ + if(sasl_choose_external(data, &sctx) || +#ifdef USE_KERBEROS5 + sasl_choose_krb5(data, &sctx) || +#endif +#ifdef USE_GSASL + sasl_choose_gsasl(data, &sctx) || +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + sasl_choose_digest(data, &sctx) || +#endif +#ifdef USE_NTLM + sasl_choose_ntlm(data, &sctx) || +#endif + sasl_choose_oauth(data, &sctx) || + sasl_choose_oauth2(data, &sctx) || + sasl_choose_plain(data, &sctx) || + sasl_choose_login(data, &sctx)) { + /* selected, either we have a mechanism or a failure */ + DEBUGASSERT(sctx.mech || sctx.result); + } + + if(!sctx.result && sctx.mech) { + sasl->curmech = sctx.mech; + if(Curl_bufref_ptr(&sctx.resp)) + sctx.result = build_message(sasl, &sctx.resp); + + if(sasl->params->maxirlen && + strlen(sctx.mech) + Curl_bufref_len(&sctx.resp) > + sasl->params->maxirlen) + Curl_bufref_free(&sctx.resp); + + if(!sctx.result) + sctx.result = sasl->params->sendauth(data, sctx.mech, &sctx.resp); + + if(!sctx.result) { + *progress = SASL_INPROGRESS; + sasl_state(sasl, data, Curl_bufref_ptr(&sctx.resp) ? + sctx.state2 : sctx.state1); + } + } + + Curl_bufref_free(&sctx.resp); + return sctx.result; +} + +/* + * Curl_sasl_continue() + * + * Continue the authentication. + */ +CURLcode Curl_sasl_continue(struct SASL *sasl, struct Curl_easy *data, + int code, saslprogress *progress) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + saslstate newstate = SASL_FINAL; + struct bufref resp; + const char *hostname; + int port; + struct bufref serverdata; + + Curl_conn_get_current_host(data, FIRSTSOCKET, &hostname, &port); + Curl_bufref_init(&serverdata); + Curl_bufref_init(&resp); + *progress = SASL_INPROGRESS; + + if(sasl->state == SASL_FINAL) { + if(code != sasl->params->finalcode) + result = CURLE_LOGIN_DENIED; + *progress = SASL_DONE; + sasl_state(sasl, data, SASL_STOP); + return result; + } + + if(sasl->state != SASL_CANCEL && sasl->state != SASL_OAUTH2_RESP && + code != sasl->params->contcode) { + *progress = SASL_DONE; + sasl_state(sasl, data, SASL_STOP); + return CURLE_LOGIN_DENIED; + } + + switch(sasl->state) { + case SASL_STOP: + *progress = SASL_DONE; + return result; + case SASL_PLAIN: + result = Curl_auth_create_plain_message(conn->creds, &resp); + break; + case SASL_LOGIN: + Curl_auth_create_login_message(Curl_creds_user(conn->creds), &resp); + newstate = SASL_LOGIN_PASSWD; + break; + case SASL_LOGIN_PASSWD: + Curl_auth_create_login_message(Curl_creds_passwd(conn->creds), &resp); + break; + case SASL_EXTERNAL: + Curl_auth_create_external_message(Curl_creds_user(conn->creds), &resp); + break; +#ifdef USE_GSASL + case SASL_GSASL: + result = get_server_message(sasl, data, &serverdata); + if(!result) { + struct gsasldata *gsasl = Curl_auth_gsasl_get(conn); + result = !gsasl ? CURLE_OUT_OF_MEMORY : + Curl_auth_gsasl_token(data, &serverdata, gsasl, &resp); + } + if(!result && Curl_bufref_len(&resp) > 0) + newstate = SASL_GSASL; + break; +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + case SASL_CRAMMD5: + result = get_server_message(sasl, data, &serverdata); + if(!result) + result = Curl_auth_create_cram_md5_message(&serverdata, conn->creds, + &resp); + break; + case SASL_DIGESTMD5: + result = get_server_message(sasl, data, &serverdata); + if(!result) + result = Curl_auth_create_digest_md5_message(data, &serverdata, + conn->creds, + sasl->params->service, + &resp); + if(!result && (sasl->params->flags & SASL_FLAG_BASE64)) + newstate = SASL_DIGESTMD5_RESP; + break; + case SASL_DIGESTMD5_RESP: + /* Keep response NULL to output an empty line. */ + break; +#endif + +#ifdef USE_NTLM + case SASL_NTLM: { + /* Create the type-1 message */ + struct ntlmdata *ntlm = Curl_auth_ntlm_get(conn, FALSE); + result = !ntlm ? CURLE_OUT_OF_MEMORY : + Curl_auth_create_ntlm_type1_message(data, conn->creds, + sasl->params->service, hostname, + ntlm, &resp); + newstate = SASL_NTLM_TYPE2MSG; + break; + } + case SASL_NTLM_TYPE2MSG: { + /* Decode the type-2 message */ + struct ntlmdata *ntlm = Curl_auth_ntlm_get(conn, FALSE); + result = !ntlm ? CURLE_OUT_OF_MEMORY : + get_server_message(sasl, data, &serverdata); + if(!result) + result = Curl_auth_decode_ntlm_type2_message(data, &serverdata, ntlm); + if(!result) + result = Curl_auth_create_ntlm_type3_message(data, conn->creds, + ntlm, &resp); + break; + } +#endif + +#ifdef USE_KERBEROS5 + case SASL_GSSAPI: { + struct kerberos5data *krb5 = Curl_auth_krb5_get(conn); + result = !krb5 ? CURLE_OUT_OF_MEMORY : + Curl_auth_create_gssapi_user_message(data, conn->creds, + sasl->params->service, + conn->origin->hostname, + (bool)sasl->mutual_auth, NULL, + krb5, &resp); + newstate = SASL_GSSAPI_TOKEN; + break; + } + case SASL_GSSAPI_TOKEN: + result = get_server_message(sasl, data, &serverdata); + if(!result) { + struct kerberos5data *krb5 = Curl_auth_krb5_get(conn); + if(!krb5) + result = CURLE_OUT_OF_MEMORY; + else if(sasl->mutual_auth) { + /* Decode the user token challenge and create the optional response + message */ + result = Curl_auth_create_gssapi_user_message(data, NULL, + NULL, NULL, + (bool)sasl->mutual_auth, + &serverdata, + krb5, &resp); + newstate = SASL_GSSAPI_NO_DATA; + } + else + /* Decode the security challenge and create the response message */ + result = Curl_auth_create_gssapi_security_message( + data, Curl_creds_sasl_authzid(conn->creds), &serverdata, + krb5, &resp); + } + break; + case SASL_GSSAPI_NO_DATA: + /* Decode the security challenge and create the response message */ + result = get_server_message(sasl, data, &serverdata); + if(!result) { + struct kerberos5data *krb5 = Curl_auth_krb5_get(conn); + if(!krb5) + result = CURLE_OUT_OF_MEMORY; + else + result = Curl_auth_create_gssapi_security_message( + data, Curl_creds_sasl_authzid(conn->creds), &serverdata, + krb5, &resp); + } + break; +#endif + + case SASL_OAUTH2: + /* Create the authorization message */ + if(sasl->authused == SASL_MECH_OAUTHBEARER) { + result = Curl_auth_create_oauth_bearer_message(conn->creds, + hostname, + port, + &resp); + + /* Failures maybe sent by the server as continuations for OAUTHBEARER */ + newstate = SASL_OAUTH2_RESP; + } + else + result = Curl_auth_create_xoauth_bearer_message(conn->creds, + &resp); + break; + + case SASL_OAUTH2_RESP: + /* The continuation is optional so check the response code */ + if(code == sasl->params->finalcode) { + /* Final response was received so we are done */ + *progress = SASL_DONE; + sasl_state(sasl, data, SASL_STOP); + return result; + } + else if(code == sasl->params->contcode) { + /* Acknowledge the continuation by sending a 0x01 response. */ + Curl_bufref_set(&resp, "\x01", 1, NULL); + break; + } + else { + *progress = SASL_DONE; + sasl_state(sasl, data, SASL_STOP); + return CURLE_LOGIN_DENIED; + } + + case SASL_CANCEL: + /* Remove the offending mechanism from the supported list */ + sasl->authmechs &= (unsigned short)~sasl->authused; + sasl->authused = SASL_AUTH_NONE; + sasl->curmech = NULL; + + /* Start an alternative SASL authentication */ + return Curl_sasl_start(sasl, data, (bool)sasl->force_ir, progress); + default: + failf(data, "Unsupported SASL authentication mechanism"); + result = CURLE_UNSUPPORTED_PROTOCOL; /* Should not happen */ + break; + } + + Curl_bufref_free(&serverdata); + + switch(result) { + case CURLE_BAD_CONTENT_ENCODING: + /* Cancel dialog */ + result = sasl->params->cancelauth(data, sasl->curmech); + newstate = SASL_CANCEL; + break; + case CURLE_OK: + result = build_message(sasl, &resp); + if(!result) + result = sasl->params->contauth(data, sasl->curmech, &resp); + break; + default: + newstate = SASL_STOP; /* Stop on error */ + *progress = SASL_DONE; + break; + } + + Curl_bufref_free(&resp); + + sasl_state(sasl, data, newstate); + + return result; +} + +#ifdef CURLVERBOSE +static void sasl_unchosen(struct Curl_easy *data, unsigned short mech, + unsigned short enabledmechs, + bool built_in, bool platform, + const char *param_missing) +{ + const char *mname = NULL; + size_t i; + + if(!(enabledmechs & mech)) + return; + + for(i = 0; mechtable[i].name; ++i) { + if(mechtable[i].bit == mech) { + mname = mechtable[i].name; + break; + } + } + if(!mname) /* should not happen */ + return; + if(!built_in) + infof(data, "SASL: %s not builtin", mname); + else if(!platform) + infof(data, "SASL: %s not supported by the platform/libraries", mname); + else { + if(param_missing) + infof(data, "SASL: %s is missing %s", mname, param_missing); + if(!Curl_creds_has_user(data->conn->creds)) + infof(data, "SASL: %s is missing username", mname); + } +} +#endif /* CURLVERBOSE */ + +CURLcode Curl_sasl_is_blocked(struct SASL *sasl, struct Curl_easy *data) +{ +#ifdef CURLVERBOSE +#ifdef USE_KERBEROS5 +#define CURL_SASL_KERBEROS5 TRUE +#else +#define CURL_SASL_KERBEROS5 FALSE +#endif +#ifdef USE_GSASL +#define CURL_SASL_GASL TRUE +#else +#define CURL_SASL_GASL FALSE +#endif +#ifdef CURL_DISABLE_DIGEST_AUTH +#define CURL_SASL_DIGEST TRUE +#else +#define CURL_SASL_DIGEST FALSE +#endif +#ifndef USE_NTLM +#define CURL_SASL_NTLM TRUE +#else +#define CURL_SASL_NTLM FALSE +#endif + /* Failing SASL authentication is a pain. Give a helping hand if + * we were unable to select an AUTH mechanism. + * `sasl->authmechs` are mechanisms offered by the peer + * `sasl->prefmech` are mechanisms preferred by us */ + unsigned short enabledmechs = sasl->authmechs & sasl->prefmech; + + if(!sasl->authmechs) + infof(data, "SASL: no auth mechanism was offered or recognized"); + else if(!enabledmechs) + infof(data, "SASL: no overlap between offered and configured " + "auth mechanisms"); + else { + infof(data, "SASL: no auth mechanism offered could be selected"); + if((enabledmechs & SASL_MECH_EXTERNAL) && + Curl_creds_has_passwd(data->conn->creds)) + infof(data, "SASL: auth EXTERNAL not chosen with password"); + sasl_unchosen(data, SASL_MECH_GSSAPI, enabledmechs, + CURL_SASL_KERBEROS5, Curl_auth_is_gssapi_supported(), NULL); + sasl_unchosen(data, SASL_MECH_SCRAM_SHA_256, enabledmechs, + CURL_SASL_GASL, FALSE, NULL); + sasl_unchosen(data, SASL_MECH_SCRAM_SHA_1, enabledmechs, + CURL_SASL_GASL, FALSE, NULL); + sasl_unchosen(data, SASL_MECH_DIGEST_MD5, enabledmechs, + CURL_SASL_DIGEST, Curl_auth_is_digest_supported(), NULL); + sasl_unchosen(data, SASL_MECH_CRAM_MD5, enabledmechs, + CURL_SASL_DIGEST, TRUE, NULL); + sasl_unchosen(data, SASL_MECH_NTLM, enabledmechs, + CURL_SASL_NTLM, Curl_auth_is_ntlm_supported(), NULL); + sasl_unchosen(data, SASL_MECH_OAUTHBEARER, enabledmechs, TRUE, TRUE, + Curl_creds_has_oauth_bearer(data->conn->creds) ? + NULL : "CURLOPT_XOAUTH2_BEARER"); + sasl_unchosen(data, SASL_MECH_XOAUTH2, enabledmechs, TRUE, TRUE, + Curl_creds_has_oauth_bearer(data->conn->creds) ? + NULL : "CURLOPT_XOAUTH2_BEARER"); + } +#endif /* CURLVERBOSE */ + (void)sasl; + (void)data; + return CURLE_LOGIN_DENIED; +} + +#endif /* protocols are enabled that use SASL */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sasl.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sasl.h new file mode 100644 index 0000000000..8a97f52adc --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sasl.h @@ -0,0 +1,160 @@ +#ifndef HEADER_CURL_SASL_H +#define HEADER_CURL_SASL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "bufref.h" + +struct Curl_easy; +struct connectdata; + +/* Authentication mechanism flags */ +#define SASL_MECH_LOGIN (1 << 0) +#define SASL_MECH_PLAIN (1 << 1) +#define SASL_MECH_CRAM_MD5 (1 << 2) +#define SASL_MECH_DIGEST_MD5 (1 << 3) +#define SASL_MECH_GSSAPI (1 << 4) +#define SASL_MECH_EXTERNAL (1 << 5) +#define SASL_MECH_NTLM (1 << 6) +#define SASL_MECH_XOAUTH2 (1 << 7) +#define SASL_MECH_OAUTHBEARER (1 << 8) +#define SASL_MECH_SCRAM_SHA_1 (1 << 9) +#define SASL_MECH_SCRAM_SHA_256 (1 << 10) + +/* Authentication mechanism values */ +#define SASL_AUTH_NONE 0 +#define SASL_AUTH_ANY 0xffff +#define SASL_AUTH_DEFAULT (SASL_AUTH_ANY & ~SASL_MECH_EXTERNAL) + +/* Authentication mechanism strings */ +#define SASL_MECH_STRING_LOGIN "LOGIN" +#define SASL_MECH_STRING_PLAIN "PLAIN" +#define SASL_MECH_STRING_CRAM_MD5 "CRAM-MD5" +#define SASL_MECH_STRING_DIGEST_MD5 "DIGEST-MD5" +#define SASL_MECH_STRING_GSSAPI "GSSAPI" +#define SASL_MECH_STRING_EXTERNAL "EXTERNAL" +#define SASL_MECH_STRING_NTLM "NTLM" +#define SASL_MECH_STRING_XOAUTH2 "XOAUTH2" +#define SASL_MECH_STRING_OAUTHBEARER "OAUTHBEARER" +#define SASL_MECH_STRING_SCRAM_SHA_1 "SCRAM-SHA-1" +#define SASL_MECH_STRING_SCRAM_SHA_256 "SCRAM-SHA-256" + +/* SASL flags */ +#define SASL_FLAG_BASE64 0x0001 /* Messages are base64-encoded */ + +/* SASL machine states */ +typedef enum { + SASL_STOP, + SASL_PLAIN, + SASL_LOGIN, + SASL_LOGIN_PASSWD, + SASL_EXTERNAL, + SASL_CRAMMD5, + SASL_DIGESTMD5, + SASL_DIGESTMD5_RESP, + SASL_NTLM, + SASL_NTLM_TYPE2MSG, + SASL_GSSAPI, + SASL_GSSAPI_TOKEN, + SASL_GSSAPI_NO_DATA, + SASL_OAUTH2, + SASL_OAUTH2_RESP, + SASL_GSASL, + SASL_CANCEL, + SASL_FINAL +} saslstate; + +/* Progress indicator */ +typedef enum { + SASL_IDLE, + SASL_INPROGRESS, + SASL_DONE +} saslprogress; + +/* Protocol dependent SASL parameters */ +struct SASLproto { + const char *service; /* The service name */ + CURLcode (*sendauth)(struct Curl_easy *data, const char *mech, + const struct bufref *ir); + /* Send authentication command */ + CURLcode (*contauth)(struct Curl_easy *data, const char *mech, + const struct bufref *contauth); + /* Send authentication continuation */ + CURLcode (*cancelauth)(struct Curl_easy *data, const char *mech); + /* Cancel authentication. */ + CURLcode (*getmessage)(struct Curl_easy *data, struct bufref *out); + /* Get SASL response message */ + size_t maxirlen; /* Maximum initial response + mechanism length, + or zero if no max. This is normally the max + command length - other characters count. + This has to be zero for non-base64 protocols. */ + int contcode; /* Code to receive when continuation is expected */ + int finalcode; /* Code to receive upon authentication success */ + unsigned short defmechs; /* Mechanisms enabled by default */ + unsigned short flags; /* Configuration flags. */ +}; + +/* Per-connection parameters */ +struct SASL { + const struct SASLproto *params; /* Protocol dependent parameters */ + saslstate state; /* Current machine state */ + const char *curmech; /* Current mechanism id. */ + unsigned short authmechs; /* Accepted authentication mechanisms */ + unsigned short prefmech; /* Preferred authentication mechanism */ + unsigned short authused; /* Auth mechanism used for the connection */ + BIT(resetprefs); /* For URL auth option parsing. */ + BIT(mutual_auth); /* Mutual authentication enabled (GSSAPI only) */ + BIT(force_ir); /* Protocol always supports initial response */ +}; + +/* This is used to test whether the line starts with the given mechanism */ +#define sasl_mech_equal(line, wordlen, mech) \ + ((wordlen) == (sizeof(mech) - 1) / sizeof(char) && \ + !memcmp(line, mech, wordlen)) + +/* Convert a mechanism name to a token */ +unsigned short Curl_sasl_decode_mech(const char *ptr, + size_t maxlen, size_t *len); + +/* Parse the URL login options */ +CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl, + const char *value, size_t len); + +/* Initializes an SASL structure */ +void Curl_sasl_init(struct SASL *sasl, struct Curl_easy *data, + const struct SASLproto *params); + +/* Check if we have enough auth data and capabilities to authenticate */ +bool Curl_sasl_can_authenticate(struct SASL *sasl, struct Curl_easy *data); + +/* Calculate the required login details for SASL authentication */ +CURLcode Curl_sasl_start(struct SASL *sasl, struct Curl_easy *data, + bool force_ir, saslprogress *progress); + +/* Continue an SASL authentication */ +CURLcode Curl_sasl_continue(struct SASL *sasl, struct Curl_easy *data, + int code, saslprogress *progress); + +CURLcode Curl_sasl_is_blocked(struct SASL *sasl, struct Curl_easy *data); + +#endif /* HEADER_CURL_SASL_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_setup.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_setup.h new file mode 100644 index 0000000000..0af3a67b6e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_setup.h @@ -0,0 +1,1663 @@ +#ifndef HEADER_CURL_SETUP_H +#define HEADER_CURL_SETUP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#if defined(BUILDING_LIBCURL) && !defined(CURL_NO_OLDIES) +#define CURL_NO_OLDIES +#endif + +/* Set default _WIN32_WINNT */ +#ifdef __MINGW32__ +#include <_mingw.h> +#endif + +/* Workaround for Homebrew gcc 12.4.0, 13.3.0, 14.1.0, 14.2.0 (initial build) + that started advertising the `availability` attribute, which then gets used + by Apple SDK, but, in a way incompatible with gcc, resulting in misc errors + inside SDK headers, e.g.: + error: attributes should be specified before the declarator in a function + definition + error: expected ',' or '}' before + Followed by missing declarations. + Work it around by overriding the built-in feature-check macro used by the + headers to enable the problematic attributes. This makes the feature check + fail. Fixed in 14.2.0_1. Disable the workaround if the fix is detected. */ +#if defined(__APPLE__) && !defined(__clang__) && defined(__GNUC__) && \ + defined(__has_attribute) +# if !defined(__has_feature) /* Keep this PP check separate from others */ +# define availability curl_pp_attribute_disabled +# elif !__has_feature(attribute_availability) +# define availability curl_pp_attribute_disabled +# endif +#endif + +#ifdef __APPLE__ +#include <sys/types.h> +#include <TargetConditionals.h> +/* Fixup faulty target macro initialization in macOS SDK since v14.4 (as of + 15.0 beta). The SDK target detection in `TargetConditionals.h` correctly + detects macOS, but fails to set the macro's old name `TARGET_OS_OSX`, then + continues to set it to a default value of 0. Other parts of the SDK still + rely on the old name, and with this inconsistency our builds fail due to + missing declarations. It happens when using mainline llvm older than v18. + Later versions fixed it by predefining these target macros, avoiding the + faulty dynamic detection. gcc is not affected (for now) because it lacks + the necessary dynamic detection features, so the SDK falls back to + a codepath that sets both the old and new macro to 1. */ +#if defined(TARGET_OS_MAC) && TARGET_OS_MAC && \ + defined(TARGET_OS_OSX) && !TARGET_OS_OSX && \ + (!defined(TARGET_OS_IPHONE) || !TARGET_OS_IPHONE) && \ + (!defined(TARGET_OS_SIMULATOR) || !TARGET_OS_SIMULATOR) +#undef TARGET_OS_OSX +#define TARGET_OS_OSX TARGET_OS_MAC +#endif +#endif + +#if defined(__MINGW32__) && \ + (!defined(__MINGW64_VERSION_MAJOR) || (__MINGW64_VERSION_MAJOR < 3)) +#error "mingw-w64 3.0 or greater required" +#endif + +/* Visual Studio 2010 is the minimum Visual Studio version we support. + Workarounds for older versions of Visual Studio have been removed. */ +#if defined(_MSC_VER) && (_MSC_VER < 1600) +#error "Ancient versions of Visual Studio are no longer supported due to bugs." +#endif + +#ifdef _MSC_VER +/* Disable Visual Studio warnings: 4127 "conditional expression is constant" */ +#pragma warning(disable:4127) +#ifndef _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS /* for getenv(), sscanf(), vsnprintf() */ +#endif +#endif /* _MSC_VER */ + +#ifdef _WIN32 +/* + * Do not include unneeded stuff in Windows headers to avoid compiler + * warnings and macro clashes. + * Make sure to define this macro before including any Windows headers. + */ +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# ifndef NOGDI +# define NOGDI +# endif + +/* Detect Windows App environment which has a restricted access + * to the Win32 APIs. */ +# if (defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0602)) || \ + defined(WINAPI_FAMILY) +# include <winapifamily.h> +# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \ + !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +# define CURL_WINDOWS_UWP +# endif +# endif + +/* Mandatory to define SECURITY_WIN32 or SECURITY_KERNEL to indicating who is + compiling the code. */ +#undef SECURITY_KERNEL +#undef SECURITY_WIN32 +#define SECURITY_WIN32 /* for <sspi.h> */ +#endif + +/* Compatibility */ +#ifdef ENABLE_IPV6 +#define USE_IPV6 1 +#endif + +/* + * Include configuration script results or hand-crafted + * configuration file for platforms which lack config tool. + */ + +#ifdef HAVE_CONFIG_H + +#include "curl_config.h" + +#else /* HAVE_CONFIG_H */ + +#ifdef _WIN32 +# include "config-win32.h" +#endif + +#ifdef macintosh +# include "config-mac.h" +#endif + +#ifdef __OS400__ +# include "config-os400.h" +#endif + +#endif /* HAVE_CONFIG_H */ + +#ifdef _WIN32 +# if defined(_WIN32_WINNT) && (_WIN32_WINNT < 0x0600) +# error The minimum build target is Windows Vista (0x0600) +# endif + +# if !defined(CURL_WINDOWS_UWP) && (defined(_MSC_VER) || defined(__MINGW32__)) +# ifndef HAVE_IF_NAMETOINDEX +# define HAVE_IF_NAMETOINDEX +# endif +# endif +#endif + +/* ================================================================ */ +/* Definition of preprocessor macros/symbols which modify compiler */ +/* behavior or generated code characteristics must be done here, */ +/* as appropriate, before any system header file is included. It is */ +/* also possible to have them defined in the config file included */ +/* before this point. As a result of all this we frown inclusion of */ +/* system header files in our config files, avoid this at any cost. */ +/* ================================================================ */ + +#ifdef HAVE_LIBZ +# ifndef ZLIB_CONST +# define ZLIB_CONST /* Use z_const. Supported by v1.2.5.2 or greater. */ +# endif +#endif + +/* + * AIX 4.3 and newer needs _THREAD_SAFE defined to build + * proper reentrant code. Others may also need it. + */ +#ifdef NEED_THREAD_SAFE +# ifndef _THREAD_SAFE +# define _THREAD_SAFE +# endif +#endif + +/* + * Tru64 needs _REENTRANT set for a few function prototypes and + * things to appear in the system header files. Unixware needs it + * to build proper reentrant code. Others may also need it. + */ +#ifdef NEED_REENTRANT +# ifndef _REENTRANT +# define _REENTRANT +# endif +#endif + +/* Solaris needs this to get a POSIX-conformant getpwuid_r */ +#if defined(sun) || defined(__sun) +# ifndef _POSIX_PTHREAD_SEMANTICS +# define _POSIX_PTHREAD_SEMANTICS 1 +# endif +#endif + +/* ================================================================ */ +/* If you need to include a system header file for your platform, */ +/* please, do it beyond the point further indicated in this file. */ +/* ================================================================ */ + +/* Give calloc a chance to be included early, so we do not redefine */ +#ifdef HAVE_THREADS_POSIX +# include <pthread.h> +#endif + +/* + * Disable other protocols when http is the only one desired. + */ +#ifdef HTTP_ONLY +# ifndef CURL_DISABLE_DICT +# define CURL_DISABLE_DICT +# endif +# ifndef CURL_DISABLE_FILE +# define CURL_DISABLE_FILE +# endif +# ifndef CURL_DISABLE_FTP +# define CURL_DISABLE_FTP +# endif +# ifndef CURL_DISABLE_GOPHER +# define CURL_DISABLE_GOPHER +# endif +# ifndef CURL_DISABLE_IMAP +# define CURL_DISABLE_IMAP +# endif +# ifndef CURL_DISABLE_LDAP +# define CURL_DISABLE_LDAP +# endif +# ifndef CURL_DISABLE_LDAPS +# define CURL_DISABLE_LDAPS +# endif +# ifndef CURL_DISABLE_MQTT +# define CURL_DISABLE_MQTT +# endif +# ifndef CURL_DISABLE_POP3 +# define CURL_DISABLE_POP3 +# endif +# ifndef CURL_DISABLE_RTSP +# define CURL_DISABLE_RTSP +# endif +# ifndef CURL_DISABLE_SMTP +# define CURL_DISABLE_SMTP +# endif +# ifndef CURL_DISABLE_TELNET +# define CURL_DISABLE_TELNET +# endif +# ifndef CURL_DISABLE_TFTP +# define CURL_DISABLE_TFTP +# endif +# ifndef CURL_DISABLE_WEBSOCKETS +# define CURL_DISABLE_WEBSOCKETS +# endif +#endif + +/* + * When HTTP is disabled, disable HTTP-only features + */ +#ifdef CURL_DISABLE_HTTP +# ifndef CURL_DISABLE_ALTSVC +# define CURL_DISABLE_ALTSVC +# endif +# ifndef CURL_DISABLE_AWS +# define CURL_DISABLE_AWS +# endif +# ifndef CURL_DISABLE_BASIC_AUTH +# define CURL_DISABLE_BASIC_AUTH +# endif +# ifndef CURL_DISABLE_BEARER_AUTH +# define CURL_DISABLE_BEARER_AUTH +# endif +# ifndef CURL_DISABLE_COOKIES +# define CURL_DISABLE_COOKIES +# endif +# ifndef CURL_DISABLE_DOH +# define CURL_DISABLE_DOH +# endif +# ifndef CURL_DISABLE_FORM_API +# define CURL_DISABLE_FORM_API +# endif +# ifndef CURL_DISABLE_HEADERS_API +# define CURL_DISABLE_HEADERS_API +# endif +# ifndef CURL_DISABLE_HSTS +# define CURL_DISABLE_HSTS +# endif +# ifndef CURL_DISABLE_HTTPSIG +# define CURL_DISABLE_HTTPSIG +# endif +# ifndef CURL_DISABLE_HTTP_AUTH +# define CURL_DISABLE_HTTP_AUTH +# endif +# ifndef CURL_DISABLE_RTSP +# define CURL_DISABLE_RTSP +# endif +# ifndef CURL_DISABLE_WEBSOCKETS +# define CURL_DISABLE_WEBSOCKETS /* no WebSockets without HTTP present */ +# endif +#endif + +/* ================================================================ */ +/* No system header file shall be included in this file before this */ +/* point. */ +/* ================================================================ */ + +/* + * OS/400 setup file includes some system headers. + */ +#ifdef __OS400__ +# include "setup-os400.h" +#endif + +/* + * VMS setup file includes some system headers. + */ +#ifdef __VMS +# include "setup-vms.h" +#endif + +/* + * Windows setup file includes some system headers. + */ +#ifdef _WIN32 +# include "setup-win32.h" +#endif + +#include <curl/system.h> + +/* Helper macro to expand and concatenate two macros. + * Direct macros concatenation does not work because macros + * are not expanded before direct concatenation. + */ +#define CURL_CONC_MACROS_(A, B) A ## B +#define CURL_CONC_MACROS(A, B) CURL_CONC_MACROS_(A, B) + +/* curl uses its own printf() function internally. It understands the GNU + * format. Use this format, so that it matches the GNU format attribute we + * use with the MinGW compiler, allowing it to verify them at compile-time. + */ +#ifdef __MINGW32__ +# undef CURL_FORMAT_CURL_OFF_T +# undef CURL_FORMAT_CURL_OFF_TU +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +#endif + +/* based on logic in "curl/mprintf.h" */ +#if (defined(__GNUC__) || defined(__clang__) || \ + defined(__IAR_SYSTEMS_ICC__)) && \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(CURL_NO_FMT_CHECKS) +#if defined(__MINGW32__) && !defined(__clang__) +#define CURL_PRINTF(fmt, arg) __attribute__((format(gnu_printf, fmt, arg))) +#else +#define CURL_PRINTF(fmt, arg) __attribute__((format(__printf__, fmt, arg))) +#endif +#else +#define CURL_PRINTF(fmt, arg) +#endif + +/* Override default printf mask check rules in "curl/mprintf.h" */ +#define CURL_TEMP_PRINTF CURL_PRINTF + +/* Workaround for mainline llvm v16 and earlier missing a built-in macro + expected by macOS SDK v14 / Xcode v15 (2023) and newer. + gcc (as of v14) is also missing it. */ +#if defined(__APPLE__) && \ + ((!defined(__apple_build_version__) && \ + defined(__clang__) && __clang_major__ < 17) || \ + (defined(__GNUC__) && __GNUC__ <= 14)) && \ + defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && \ + !defined(__ENVIRONMENT_OS_VERSION_MIN_REQUIRED__) +#define __ENVIRONMENT_OS_VERSION_MIN_REQUIRED__ \ + __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ +#endif + +/* + * Use getaddrinfo to resolve the IPv4 address literal. If the current network + * interface does not support IPv4, but supports IPv6, NAT64, and DNS64, + * performing this task will result in a synthesized IPv6 address. + */ +#if defined(__APPLE__) && !defined(USE_ARES) +# define USE_RESOLVE_ON_IPS 1 +# if TARGET_OS_MAC && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && \ + defined(USE_IPV6) +# define CURL_MACOS_CALL_COPYPROXIES 1 +# endif +#endif + +#ifdef USE_ARES +# ifndef CARES_NO_DEPRECATED +# define CARES_NO_DEPRECATED /* for ares_getsock() */ +# endif +# if defined(CURL_STATICLIB) && !defined(CARES_STATICLIB) && defined(_WIN32) +# define CARES_STATICLIB /* define it before including ares.h */ +# endif +#endif + +#ifdef USE_LWIPSOCK +# include <lwip/init.h> +# include <lwip/sockets.h> +# include <lwip/netdb.h> +#endif + +#ifdef macintosh +# include <extra/stricmp.h> +# include <extra/strdup.h> +#endif + +#ifdef __AMIGA__ +# ifdef __amigaos4__ +# define __USE_INLINE__ + /* use our own resolver which uses runtime feature detection */ +# define CURLRES_AMIGA + /* getaddrinfo() currently crashes bsdsocket.library, so disable */ +# undef HAVE_GETADDRINFO +# if !(defined(__NEWLIB__) || \ + (defined(__CLIB2__) && defined(__THREAD_SAFE))) + /* disable threaded resolver with clib2 - requires newlib or clib-ts */ +# undef USE_RESOLV_THREADED +# endif +# endif +# include <exec/types.h> +# include <exec/execbase.h> +# include <proto/exec.h> +# include <proto/dos.h> +# include <unistd.h> +# if defined(HAVE_PROTO_BSDSOCKET_H) && \ + (!defined(__amigaos4__) || defined(USE_AMISSL)) + /* use bsdsocket.library directly, instead of libc networking functions */ +# define _SYS_MBUF_H /* m_len define clashes with curl */ +# include <proto/bsdsocket.h> +# ifdef __amigaos4__ + int Curl_amiga_select(int nfds, fd_set *readfds, fd_set *writefds, + fd_set *errorfds, struct timeval *timeout); +# define select(a, b, c, d, e) Curl_amiga_select(a, b, c, d, e) +# else +# define select(a, b, c, d, e) WaitSelect(a, b, c, d, e, 0) +# endif + /* must not use libc's fcntl() on bsdsocket.library sockfds! */ +# undef HAVE_FCNTL +# undef HAVE_FCNTL_O_NONBLOCK +# else + /* use libc networking and hence close() and fcntl() */ +# undef HAVE_CLOSESOCKET_CAMEL +# undef HAVE_IOCTLSOCKET_CAMEL +# endif +/* + * In clib2 arpa/inet.h warns that some prototypes may clash + * with bsdsocket.library. This avoids the definition of those. + */ +# define __NO_NET_API +#endif + +/* Whether to use eventfd() */ +#if defined(HAVE_EVENTFD) && defined(HAVE_SYS_EVENTFD_H) +#define USE_EVENTFD +#endif + +#ifdef SO_NOSIGPIPE +#define USE_SO_NOSIGPIPE +#endif + +#include <stdio.h> +#include <assert.h> + +#ifdef __TANDEM /* for ns*-tandem-nsk systems */ +# ifndef __LP64 +# include <floss.h> /* FLOSS is only used for 32-bit builds. */ +# endif +#endif + +#include <stdint.h> +#define HAVE_UINTPTR_T /* assume uintptr_t is provided by stdint.h */ + +#ifdef __DJGPP__ +/* By default, DJGPP provides this type as a version of 'unsigned long' which + forces us to use a define use it in printf() format strings without + warnings. long and int are both 32 bits for this platform. */ +#define uint32_t unsigned int +#endif + +/* Disable uintptr_t for targets known to miss it from stdint.h */ +#ifdef __OS400__ +#undef HAVE_UINTPTR_T +#endif + +#include <limits.h> +/* Include after setting system macros that may affect type sizes + (e.g. 'off_t' or 'time_t'), or suppress warnings + (e.g. '_CRT_SECURE_NO_WARNINGS`), but before including sys/stat.h */ +#include <sys/types.h> + +#ifdef _WIN32 +# ifdef HAVE_IO_H +# include <io.h> +# endif +# include <sys/stat.h> + /* Large file (>2Gb) support using Win32 functions. */ +# define curl_lseek _lseeki64 +# define LSEEK_ERROR ((__int64)-1) +#elif defined(__DJGPP__) + /* Requires DJGPP 2.04 */ +# include <unistd.h> +# define curl_lseek llseek +# define LSEEK_ERROR ((offset_t)-1) +#elif defined(__AMIGA__) +# define curl_lseek(fd, offset, whence) lseek(fd, (off_t)(offset), whence) +# define LSEEK_ERROR ((off_t)-1) +#else +# define curl_lseek lseek +# define LSEEK_ERROR ((off_t)-1) +#endif + +#ifndef SIZEOF_TIME_T +/* assume default size of time_t to be 32 bits */ +#define SIZEOF_TIME_T 4 +#endif + +#ifndef SIZEOF_CURL_SOCKET_T +/* configure and cmake check and set the define */ +# if defined(USE_WINSOCK) && defined(_WIN64) +# define SIZEOF_CURL_SOCKET_T 8 +# else +/* default guess */ +# define SIZEOF_CURL_SOCKET_T 4 +# endif +#endif + +#if SIZEOF_CURL_SOCKET_T < 8 +#ifdef USE_WINSOCK +# define FMT_SOCKET_T "u" +#else +# define FMT_SOCKET_T "d" +#endif +#elif defined(USE_WINSOCK) +# define FMT_SOCKET_T "zu" +#else +# define FMT_SOCKET_T "qd" +#endif + +/* + * Default sizeof(off_t) in case it has not been defined in config file. + */ + +#ifndef SIZEOF_OFF_T +# if defined(__VMS) && !defined(__VAX) +# ifdef _LARGEFILE +# define SIZEOF_OFF_T 8 +# endif +# elif defined(__OS400__) && defined(__ILEC400__) +# ifdef _LARGE_FILES +# define SIZEOF_OFF_T 8 +# endif +# elif defined(__MVS__) && defined(__IBMC__) +# if defined(_LP64) || defined(_LARGE_FILES) +# define SIZEOF_OFF_T 8 +# endif +# elif defined(__370__) && defined(__IBMC__) +# if defined(_LP64) || defined(_LARGE_FILES) +# define SIZEOF_OFF_T 8 +# endif +# endif +# ifndef SIZEOF_OFF_T +# define SIZEOF_OFF_T 4 +# endif +#endif + +#if SIZEOF_CURL_OFF_T < 8 +#error "too small curl_off_t" +#else + /* assume SIZEOF_CURL_OFF_T == 8 */ +# define CURL_OFF_T_MAX 0x7FFFFFFFFFFFFFFF +#endif +#define CURL_OFF_T_MIN (-CURL_OFF_T_MAX - 1) + +#define FMT_OFF_T CURL_FORMAT_CURL_OFF_T +#define FMT_OFF_TU CURL_FORMAT_CURL_OFF_TU + +#if SIZEOF_TIME_T == 4 +# ifdef HAVE_TIME_T_UNSIGNED +# define TIME_T_MAX UINT_MAX +# define TIME_T_MIN 0 +# else +# define TIME_T_MAX INT_MAX +# define TIME_T_MIN INT_MIN +# endif +#else +# ifdef HAVE_TIME_T_UNSIGNED +# define TIME_T_MAX 0xFFFFFFFFFFFFFFFF +# define TIME_T_MIN 0 +# else +# define TIME_T_MAX 0x7FFFFFFFFFFFFFFF +# define TIME_T_MIN (-TIME_T_MAX - 1) +# endif +#endif + +#ifndef SIZE_MAX +/* some limits.h headers have this defined, some do not */ +#if defined(SIZEOF_SIZE_T) && (SIZEOF_SIZE_T > 4) +#define SIZE_MAX 18446744073709551615U +#else +#define SIZE_MAX 4294967295U +#endif +#endif + +#ifndef SSIZE_MAX +/* some limits.h headers have this defined, some do not */ +#if defined(SIZEOF_SIZE_T) && (SIZEOF_SIZE_T > 4) +#define SSIZE_MAX 9223372036854775807 +#else +#define SSIZE_MAX 2147483647 +#endif +#endif + +#if SIZEOF_LONG > SIZEOF_SIZE_T +#error "unexpected: 'long' is larger than 'size_t'" +#endif + +/* + * Arg 2 type for gethostname in case it has not been defined in config file. + */ +#ifndef GETHOSTNAME_TYPE_ARG2 +# ifdef USE_WINSOCK +# define GETHOSTNAME_TYPE_ARG2 int +# else +# define GETHOSTNAME_TYPE_ARG2 size_t +# endif +#endif + +/* Below we define some functions. They should + 4. set the SIGALRM signal timeout + 5. set dir/file naming defines + */ + +#ifdef _WIN32 + +# define DIR_CHAR "\\" + +#else /* _WIN32 */ + +# ifdef MSDOS /* Watt-32 */ + +# include <sys/ioctl.h> +# define select(n, r, w, x, t) select_s(n, r, w, x, t) +# define ioctl(x, y, z) ioctlsocket(x, y, (char *)(z)) +# include <tcp.h> +# undef word +# undef byte + +# endif /* MSDOS */ + +# ifdef __minix + /* Minix 3 versions up to at least 3.1.3 are missing these prototypes */ + extern struct tm *gmtime_r(const time_t * const timep, struct tm *tmp); +# endif + +# define DIR_CHAR "/" + +#endif /* _WIN32 */ + +/* We want to use mutex when available. */ +#if defined(HAVE_THREADS_POSIX) || defined(_WIN32) +#define USE_MUTEX +#endif + +/* threaded resolver is the only feature requiring threads. */ +#ifdef USE_RESOLV_THREADED +#define USE_THREADS +#endif + +/* ---------------------------------------------------------------- */ +/* resolver specialty compile-time defines */ +/* CURLRES_* defines to use in the host*.c sources */ +/* ---------------------------------------------------------------- */ + +/* + * Mutually exclusive CURLRES_* definitions. + */ +#if defined(USE_IPV6) && defined(HAVE_GETADDRINFO) +# define CURLRES_IPV6 +#elif defined(USE_IPV6) && (defined(_WIN32) || defined(__CYGWIN__)) +/* assume on Windows that IPv6 without getaddrinfo is a broken build */ +# error "Unexpected build: IPv6 is enabled but getaddrinfo was not found." +#else +# define CURLRES_IPV4 +#endif + +#ifdef USE_RESOLV_THREADED +# define CURLRES_ASYNCH +#elif defined(USE_RESOLV_ARES) +# define CURLRES_ASYNCH +/* now undef the stock libc functions to avoid them being used */ +# undef HAVE_GETADDRINFO +# undef HAVE_FREEADDRINFO +#else +# define CURLRES_SYNCH +#endif + +/* ---------------------------------------------------------------- */ + +#if defined(HAVE_LIBIDN2) && defined(HAVE_IDN2_H) && \ + !defined(USE_WIN32_IDN) && !defined(USE_APPLE_IDN) +/* The lib and header are present */ +#define USE_LIBIDN2 +#endif + +#if defined(USE_LIBIDN2) && (defined(USE_WIN32_IDN) || defined(USE_APPLE_IDN)) +#error "libidn2 cannot be enabled with WinIDN or AppleIDN, choose one." +#endif + +#if defined(USE_GNUTLS) || defined(USE_OPENSSL) || defined(USE_MBEDTLS) || \ + defined(USE_WOLFSSL) || defined(USE_SCHANNEL) || defined(USE_RUSTLS) +#define USE_SSL /* SSL support has been enabled */ +#endif + +#if defined(USE_OPENSSL) && defined(USE_WOLFSSL) +#ifndef OPENSSL_COEXIST +#define OPENSSL_COEXIST +#endif +#endif + +#if defined(USE_WOLFSSL) && defined(USE_GNUTLS) +/* Avoid defining unprefixed wolfSSL SHA macros colliding with nettle ones */ +#define NO_OLD_WC_NAMES +#endif + +/* Single point where USE_SPNEGO definition might be defined */ +#if !defined(CURL_DISABLE_NEGOTIATE_AUTH) && \ + (defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)) +#define USE_SPNEGO +#endif + +/* Single point where USE_KERBEROS5 definition might be defined */ +#if !defined(CURL_DISABLE_KERBEROS_AUTH) && \ + (defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)) +#define USE_KERBEROS5 +#endif + +/* Single point where USE_NTLM definition might be defined */ +#ifdef CURL_ENABLE_NTLM +# if (defined(USE_OPENSSL) && defined(HAVE_DES_ECB_ENCRYPT)) || \ + defined(USE_GNUTLS) || \ + (defined(USE_MBEDTLS) && defined(HAVE_MBEDTLS_DES_CRYPT_ECB)) || \ + defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO) || \ + (defined(USE_WOLFSSL) && defined(HAVE_WC_DES_ECBENCRYPT)) +# define USE_CURL_NTLM_CORE +# endif +# if defined(USE_CURL_NTLM_CORE) || defined(USE_WINDOWS_SSPI) +# define USE_NTLM +# endif +#endif + +#if defined(USE_LIBSSH2) || defined(USE_LIBSSH) +#define USE_SSH +#endif + +/* GCC <4.6 does not support '#pragma GCC diagnostic push' and does not support + 'pragma GCC diagnostic' inside functions. + Use CURL_HAVE_DIAG to guard the above in the curl codebase, instead of + defined(__GNUC__) || defined(__clang__). + */ +#if defined(__clang__) || (defined(__GNUC__) && \ + ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)))) +#define CURL_HAVE_DIAG +#endif + +/* + * Provide a mechanism to silence picky compilers, such as gcc 4.6+. + * Parameters should of course normally not be unused, but for example when + * we have multiple implementations of the same interface it may happen. + */ +#if defined(__GNUC__) && ((__GNUC__ >= 3) || \ + ((__GNUC__ == 2) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ >= 7))) +# define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ >= 9040001) +# define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) +#else +# define WARN_UNUSED_RESULT +#endif + +/* noreturn attribute */ + +#ifndef CURL_NORETURN +#if (defined(__GNUC__) && (__GNUC__ >= 3)) || defined(__clang__) || \ + defined(__IAR_SYSTEMS_ICC__) +# define CURL_NORETURN __attribute__((__noreturn__)) +#elif defined(_MSC_VER) +# define CURL_NORETURN __declspec(noreturn) +#else +# define CURL_NORETURN +#endif +#endif + +/* fallthrough attribute */ + +#ifndef FALLTHROUGH +#if (defined(__GNUC__) && __GNUC__ >= 7) || \ + (defined(__clang__) && __clang_major__ >= 10) +# define FALLTHROUGH() __attribute__((fallthrough)) +#else +# define FALLTHROUGH() do {} while(0) +#endif +#endif + +/* + * Inclusion of common header files. + */ + +#include <stdlib.h> +#include <string.h> +#include <stdarg.h> +#include <time.h> +#include <errno.h> + +#include <sys/stat.h> + +#if !defined(_WIN32) || defined(__MINGW32__) +#include <sys/time.h> +#endif + +#ifdef HAVE_IO_H +#include <io.h> +#endif + +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif + +#if defined(HAVE_STDBOOL_H) && defined(HAVE_BOOL_T) +#include <stdbool.h> +#endif + +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +/* Macro to strip 'const' without triggering a compiler warning. + Use it for APIs that do not or cannot support the const qualifier. */ +#ifdef HAVE_UINTPTR_T +#define CURL_UNCONST(p) ((void *)(uintptr_t)(const void *)(p)) +#else +#define CURL_UNCONST(p) ((void *)(p)) /* Fall back to simple cast */ +#endif + +#ifdef USE_SCHANNEL +/* Must set this before <schannel.h> is included directly or indirectly by + another Windows header. */ +# define SCHANNEL_USE_BLACKLISTS /* for SCH_CREDENTIALS */ +# include <subauth.h> /* for [P]UNICODE_STRING in SCH_CREDENTIALS */ +#endif + +#ifdef __hpux +# if !defined(_XOPEN_SOURCE_EXTENDED) || defined(_KERNEL) +# ifdef _APP32_64BIT_OFF_T +# define OLD_APP32_64BIT_OFF_T _APP32_64BIT_OFF_T +# undef _APP32_64BIT_OFF_T +# else +# undef OLD_APP32_64BIT_OFF_T +# endif +# endif +#endif + +#ifndef _WIN32 +#include <sys/socket.h> /* also for MSG_NOSIGNAL */ +#endif + +#include "functypes.h" + +#ifdef __hpux +# if !defined(_XOPEN_SOURCE_EXTENDED) || defined(_KERNEL) +# ifdef OLD_APP32_64BIT_OFF_T +# define _APP32_64BIT_OFF_T OLD_APP32_64BIT_OFF_T +# undef OLD_APP32_64BIT_OFF_T +# endif +# endif +#endif + +/* + * Definition of timeval struct for platforms that do not have it. + */ +#ifndef HAVE_STRUCT_TIMEVAL +struct timeval { + long tv_sec; + long tv_usec; +}; +#endif + +/* + * If we have the MSG_NOSIGNAL define, make sure we use + * it as the fourth argument of function send() + */ +#ifdef MSG_NOSIGNAL +#define SEND_4TH_ARG MSG_NOSIGNAL +#else +#define SEND_4TH_ARG 0 +#endif + +#ifdef __minix +/* Minix does not support recv on TCP sockets */ +#define sread(x, y, z) (ssize_t)read((RECV_TYPE_ARG1)(x), \ + (RECV_TYPE_ARG2)(y), \ + (RECV_TYPE_ARG3)(z)) + +#elif defined(HAVE_RECV) +/* + * The definitions for the return type and arguments types + * of functions recv() and send() belong and come from the + * configuration file. Do not define them in any other place. + * + * HAVE_RECV is defined if you have a function named recv() + * which is used to read incoming data from sockets. If your + * function has another name then do not define HAVE_RECV. + * + * If HAVE_RECV is defined then RECV_TYPE_ARG1, RECV_TYPE_ARG2, + * RECV_TYPE_ARG3, RECV_TYPE_ARG4 and RECV_TYPE_RETV must also + * be defined. + * + * HAVE_SEND is defined if you have a function named send() + * which is used to write outgoing data on a connected socket. + * If yours has another name then do not define HAVE_SEND. + * + * If HAVE_SEND is defined then SEND_TYPE_ARG1, SEND_TYPE_ARG2, + * SEND_TYPE_ARG3, SEND_TYPE_ARG4 and SEND_TYPE_RETV must also + * be defined. SEND_NONCONST_ARG2 must also be defined if ARG2 + * does not accept const. + */ + +#define sread(x, y, z) (ssize_t)recv((RECV_TYPE_ARG1)(x), \ + (RECV_TYPE_ARG2)(y), \ + (RECV_TYPE_ARG3)(z), \ + (RECV_TYPE_ARG4)(0)) +#else /* HAVE_RECV */ +#ifndef sread +#error "Missing definition of macro sread" +#endif +#endif /* HAVE_RECV */ + +#ifdef __minix +/* Minix does not support send on TCP sockets */ +#define swrite(x, y, z) (ssize_t)write((SEND_TYPE_ARG1)(x), \ + (SEND_TYPE_ARG2)CURL_UNCONST(y), \ + (SEND_TYPE_ARG3)(z)) +#elif defined(HAVE_SEND) +#ifdef SEND_NONCONST_ARG2 +#define swrite(x, y, z) (ssize_t)send((SEND_TYPE_ARG1)(x), \ + (SEND_TYPE_ARG2)CURL_UNCONST(y), \ + (SEND_TYPE_ARG3)(z), \ + (SEND_TYPE_ARG4)(SEND_4TH_ARG)) +#else +#define swrite(x, y, z) (ssize_t)send((SEND_TYPE_ARG1)(x), \ + (const SEND_TYPE_ARG2)(y), \ + (SEND_TYPE_ARG3)(z), \ + (SEND_TYPE_ARG4)(SEND_4TH_ARG)) +#endif /* SEND_NONCONST_ARG2 */ +#else /* HAVE_SEND */ +#ifndef swrite +#error "Missing definition of macro swrite" +#endif +#endif /* HAVE_SEND */ + +/* + * Function-like macro definition used to close a socket. + */ +#ifdef HAVE_CLOSESOCKET +# define CURL_SCLOSE(x) closesocket(x) +#elif defined(HAVE_CLOSESOCKET_CAMEL) +# define CURL_SCLOSE(x) CloseSocket(x) +#elif defined(MSDOS) /* Watt-32 */ +# define CURL_SCLOSE(x) close_s(x) +#elif defined(USE_LWIPSOCK) +# define CURL_SCLOSE(x) lwip_close(x) +#else +# define CURL_SCLOSE(x) close(x) +#endif + +/* + * Stack-independent version of fcntl() on sockets: + */ +#ifdef USE_LWIPSOCK +# define sfcntl lwip_fcntl +#else +# define sfcntl fcntl +#endif + +/* + * 'bool' stuff compatible with HP-UX headers. + */ +#if defined(__hpux) && !defined(HAVE_BOOL_T) +typedef int bool; +# define false 0 +# define true 1 +# define HAVE_BOOL_T +#endif + +/* + * 'bool' exists on platforms with <stdbool.h>, i.e. C99 platforms. + * On non-C99 platforms there is no bool, so define an enum for that. + * On C99 platforms 'false' and 'true' also exist. Enum uses a + * global namespace though, so use bool_false and bool_true. + */ +#ifndef HAVE_BOOL_T +typedef enum { + bool_false = 0, + bool_true = 1 +} bool; + +/* + * Use a define to let 'true' and 'false' use those enums. There + * are currently no use of true and false in libcurl proper, but + * there are some in the examples. This will cater for any later + * code happening to use true and false. + */ +# define false bool_false +# define true bool_true +# define HAVE_BOOL_T +#endif + +/* the type we use for storing a single boolean bit */ +typedef unsigned int curl_bit; +#define BIT(x) curl_bit x:1 + +/* + * Redefine TRUE and FALSE too, to catch current use. With this + * change, 'bool found = 1' will give a warning on MIPSPro, but + * 'bool found = TRUE' will not. Change tested on IRIX/MIPSPro, + * AIX 5.1/Xlc, Tru64 5.1/cc, w/make test too. + */ +#ifndef TRUE +#define TRUE true +#endif +#ifndef FALSE +#define FALSE false +#endif + +#include "curl_ctype.h" + +#if defined(DEBUGBUILD) && defined(NDEBUG) +#error "Debug-enabled builds cannot be combined with NDEBUG" +#endif + +/* + * Macro used to include code only in debug builds. + */ +#ifdef DEBUGBUILD +#define DEBUGF(x) x +#else +#define DEBUGF(x) do {} while(0) +#endif + +/* + * Macro used to include assertion code only in debug builds. + */ +#undef DEBUGASSERT +#ifdef DEBUGBUILD +#ifdef CURL_DEBUGASSERT +/* External assertion handler for custom integrations */ +#define DEBUGASSERT(x) CURL_DEBUGASSERT(x) +#else +#define DEBUGASSERT(x) assert(x) +#endif +#else +#define DEBUGASSERT(x) do {} while(0) +#endif + +/* + * Macro SOCKERRNO / SET_SOCKERRNO() returns / sets the *socket-related* errno + * (or equivalent) on this platform to hide platform details to code using it. + */ +#ifdef USE_WINSOCK +#define SOCKERRNO ((int)WSAGetLastError()) +#define SET_SOCKERRNO(x) WSASetLastError((int)(x)) +#else +#define SOCKERRNO errno +#define SET_SOCKERRNO(x) (errno = (x)) +#endif + +/* + * Portable error number symbolic names defined to Winsock error codes. + */ +#ifdef USE_WINSOCK +#define SOCKEACCES WSAEACCES +#define SOCKEADDRINUSE WSAEADDRINUSE +#define SOCKEADDRNOTAVAIL WSAEADDRNOTAVAIL +#define SOCKEAFNOSUPPORT WSAEAFNOSUPPORT +#define SOCKEBADF WSAEBADF +#define SOCKECONNREFUSED WSAECONNREFUSED +#define SOCKECONNRESET WSAECONNRESET +#define SOCKEINPROGRESS WSAEINPROGRESS +#define SOCKEINTR WSAEINTR +#define SOCKEINVAL WSAEINVAL +#define SOCKEISCONN WSAEISCONN +#define SOCKEMSGSIZE WSAEMSGSIZE +/* Use literal value to work around clang-tidy <=20 misreporting + 'readability-uppercase-literal-suffix' with mingw-w64 headers */ +#define SOCKENOMEM 8L /* WSA_NOT_ENOUGH_MEMORY */ +#define SOCKETIMEDOUT WSAETIMEDOUT +#define SOCKEWOULDBLOCK WSAEWOULDBLOCK +#else +#define SOCKEACCES EACCES +#define SOCKEADDRINUSE EADDRINUSE +#define SOCKEADDRNOTAVAIL EADDRNOTAVAIL +#define SOCKEAFNOSUPPORT EAFNOSUPPORT +#define SOCKEBADF EBADF +#define SOCKECONNREFUSED ECONNREFUSED +#define SOCKECONNRESET ECONNRESET +#define SOCKEINPROGRESS EINPROGRESS +#define SOCKEINTR EINTR +#define SOCKEINVAL EINVAL +#define SOCKEISCONN EISCONN +#define SOCKEMSGSIZE EMSGSIZE +#define SOCKENOMEM ENOMEM +#ifdef ETIMEDOUT +#define SOCKETIMEDOUT ETIMEDOUT +#endif +#define SOCKEWOULDBLOCK EWOULDBLOCK +#endif + +/* The socket error may be EWOULDBLOCK or on some systems EAGAIN when + it returned due to its inability to send/read data without blocking. + We treat both error codes the same here. */ +#if !defined(USE_WINSOCK) && EAGAIN != SOCKEWOULDBLOCK +#define SOCK_EAGAIN(e) ((e) == SOCKEWOULDBLOCK || (e) == EAGAIN) +#else +#define SOCK_EAGAIN(e) ((e) == SOCKEWOULDBLOCK) +#endif + +/* + * Macro argv_item_t hides platform details to code using it. + */ +#ifdef __VMS +#define argv_item_t __char_ptr32 +#elif defined(_UNICODE) +#define argv_item_t wchar_t * +#else +#define argv_item_t char * +#endif + +/* + * We use this ZERO_NULL to avoid picky compiler warnings, + * when assigning a NULL pointer to a function pointer var. + */ +#define ZERO_NULL 0 + +/* + * Macros and functions to safely suppress warnings + */ +#include "curlx/warnless.h" + +#ifdef _WIN32 +# undef read +# define read(fd, buf, count) (ssize_t)_read(fd, buf, curlx_uztoui(count)) +# undef write +# define write(fd, buf, count) (ssize_t)_write(fd, buf, curlx_uztoui(count)) +/* Avoid VS2005+ _CRT_NONSTDC_NO_DEPRECATE warnings about non-portable funcs */ +# undef fileno +# define fileno(fh) _fileno(fh) +# undef unlink +# define unlink(fn) _unlink(fn) +# undef isatty +# define isatty(fd) _isatty(fd) +#endif + +/* + * Definition of our NOP statement Object-like macro + */ +#ifndef Curl_nop_stmt +#define Curl_nop_stmt do {} while(0) +#endif + +/* + * Ensure that Winsock and lwIP TCP/IP stacks are not mixed. + */ +#if defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H) +# if defined(SOCKET) || defined(USE_WINSOCK) +# error "Winsock and lwIP TCP/IP stack definitions shall not coexist" +# endif +#endif + +/* + * shutdown() flags for systems that do not define them + */ +#ifndef SHUT_RD +#define SHUT_RD 0x00 +#endif + +#ifndef SHUT_WR +#define SHUT_WR 0x01 +#endif + +#ifndef SHUT_RDWR +#define SHUT_RDWR 0x02 +#endif + +/* Define S_ISREG if not defined by system headers, e.g. MSVC */ +#if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG) +#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) +#endif + +/* Define S_ISDIR if not defined by system headers, e.g. MSVC */ +#if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR) +#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) +#endif + +/* For MSVC (all versions as of VS2022) */ +#ifndef STDIN_FILENO +#define STDIN_FILENO fileno(stdin) +#endif +#ifndef STDOUT_FILENO +#define STDOUT_FILENO fileno(stdout) +#endif +#ifndef STDERR_FILENO +#define STDERR_FILENO fileno(stderr) +#endif + +/* Since O_BINARY is used in bitmasks, setting it to zero makes it usable in + source code but yet it does not ruin anything */ +#ifdef _O_BINARY /* for _WIN32 || MSDOS */ +#define CURL_O_BINARY _O_BINARY +#elif defined(O_BINARY) /* __CYGWIN__ */ +#define CURL_O_BINARY O_BINARY +#else +#define CURL_O_BINARY 0 +#endif + +/* Requires io.h when available */ +#ifdef MSDOS +#define CURL_BINMODE(stream) (void)setmode(fileno(stream), CURL_O_BINARY) +#elif defined(_WIN32) || defined(__CYGWIN__) +#define CURL_BINMODE(stream) (void)_setmode(fileno(stream), CURL_O_BINARY) +#else +#define CURL_BINMODE(stream) (void)(stream) +#endif + +/* In Windows the default file mode is text but an application can override it. + Therefore we specify it explicitly. https://github.com/curl/curl/pull/258 */ +#if defined(_WIN32) || defined(MSDOS) +#define FOPEN_READTEXT "rt" +#define FOPEN_WRITETEXT "wt" +#define FOPEN_APPENDTEXT "at" +#elif defined(__CYGWIN__) +/* Cygwin has specific behavior we need to address when _WIN32 is not defined. + https://cygwin.com/cygwin-ug-net/using-textbinary.html + For write we want our output to have line endings of LF and be compatible + with other Cygwin utilities. For read we want to handle input that may have + line endings either CRLF or LF so 't' is appropriate. */ +#define FOPEN_READTEXT "rt" +#define FOPEN_WRITETEXT "w" +#define FOPEN_APPENDTEXT "a" +#else +#define FOPEN_READTEXT "r" +#define FOPEN_WRITETEXT "w" +#define FOPEN_APPENDTEXT "a" +#endif + +/* for systems that do not detect this in configure */ +#ifndef CURL_SA_FAMILY_T +# ifdef USE_WINSOCK +# define CURL_SA_FAMILY_T ADDRESS_FAMILY +# elif defined(HAVE_SA_FAMILY_T) +# define CURL_SA_FAMILY_T sa_family_t +# elif defined(__AMIGA__) +# define CURL_SA_FAMILY_T unsigned char +# else +/* use a sensible default */ +# define CURL_SA_FAMILY_T unsigned short +# endif +#endif + +/* Some convenience macros to get the larger/smaller value out of two given. + We prefix with CURL to prevent name collisions. */ +#define CURLMAX(x, y) ((x) > (y) ? (x) : (y)) +#define CURLMIN(x, y) ((x) < (y) ? (x) : (y)) + +/* Convenience macro to provide the length of a string literal size without + the null-terminator. Equivalent to strlen() for constant strings. */ +#define CURL_CSTRLEN(x) (sizeof(x) - 1) + +/* A convenience macro to provide both the string literal and the length of + the string literal in one go, useful for functions that take "string,len" + as their argument */ +#define STRCONST(x) x, CURL_CSTRLEN(x) + +#define CURL_ARRAYSIZE(A) (sizeof(A) / sizeof((A)[0])) + +/* Buffer size for error messages retrieved via + curlx_strerror() and Curl_sspi_strerror() */ +#define STRERROR_LEN 256 + +#ifndef CURL_DID_MEMORY_FUNC_TYPEDEFS /* only if not already done */ +/* + * The following memory function replacement typedef's are COPIED from + * curl/curl.h and MUST match the originals. We copy them to avoid having to + * include curl/curl.h here. We avoid that include since it includes stdio.h + * and other headers that may get messed up with defines done here. + */ +typedef void *(*curl_malloc_callback)(size_t size); +typedef void (*curl_free_callback)(void *ptr); +typedef void *(*curl_realloc_callback)(void *ptr, size_t size); +typedef char *(*curl_strdup_callback)(const char *str); +typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size); +#define CURL_DID_MEMORY_FUNC_TYPEDEFS +#endif + +extern curl_malloc_callback Curl_cmalloc; +extern curl_free_callback Curl_cfree; +extern curl_realloc_callback Curl_crealloc; +extern curl_strdup_callback Curl_cstrdup; +extern curl_calloc_callback Curl_ccalloc; + +/* + * curlx_safefree() defined as a macro to allow MemoryTracking feature + * to log free() calls at same location where curlx_safefree() is used. + * This macro also assigns NULL to given pointer when free'd. + */ +#define curlx_safefree(ptr) \ + do { \ + curlx_free(ptr); \ + (ptr) = NULL; \ + } while(0) + +#include <curl/curl.h> /* for CURL_EXTERN, curl_socket_t, mprintf.h */ + +#ifdef DEBUGBUILD +#define CURL_MEMDEBUG +#endif + +#ifdef CURL_MEMDEBUG +#ifdef __clang__ +# define ALLOC_FUNC __attribute__((__malloc__)) +# if __clang_major__ >= 4 +# define ALLOC_SIZE(s) __attribute__((__alloc_size__(s))) +# define ALLOC_SIZE2(n, s) __attribute__((__alloc_size__(n, s))) +# else +# define ALLOC_SIZE(s) +# define ALLOC_SIZE2(n, s) +# endif +#elif defined(__GNUC__) && __GNUC__ >= 3 +# define ALLOC_FUNC __attribute__((__malloc__)) +# define ALLOC_SIZE(s) __attribute__((__alloc_size__(s))) +# define ALLOC_SIZE2(n, s) __attribute__((__alloc_size__(n, s))) +#elif defined(_MSC_VER) +# define ALLOC_FUNC __declspec(restrict) +# define ALLOC_SIZE(s) +# define ALLOC_SIZE2(n, s) +#else +# define ALLOC_FUNC +# define ALLOC_SIZE(s) +# define ALLOC_SIZE2(n, s) +#endif + +extern FILE *curl_dbg_logfile; + +/* memory functions */ +CURL_EXTERN void curl_dbg_free(void *ptr, int line, const char *source); +CURL_EXTERN ALLOC_FUNC ALLOC_SIZE(1) + void *curl_dbg_malloc(size_t wantedsize, int line, const char *source); +CURL_EXTERN ALLOC_FUNC ALLOC_SIZE2(1, 2) + void *curl_dbg_calloc(size_t wanted_elements, size_t wanted_size, + int line, const char *source); +CURL_EXTERN ALLOC_SIZE(2) + void *curl_dbg_realloc(void *ptr, size_t wantedsize, int line, + const char *source); +CURL_EXTERN ALLOC_FUNC + char *curl_dbg_strdup(const char *str, int line, const char *source); +#if defined(_WIN32) && defined(UNICODE) +CURL_EXTERN ALLOC_FUNC + wchar_t *curl_dbg_wcsdup(const wchar_t *str, int line, const char *source); +#endif + +CURL_EXTERN void curl_dbg_memdebug(const char *logname); +CURL_EXTERN void curl_dbg_memlimit(long limit); +CURL_EXTERN void curl_dbg_log(const char *format, ...) CURL_PRINTF(1, 2); + +/* file descriptor manipulators */ +CURL_EXTERN curl_socket_t curl_dbg_socket(int domain, int type, int protocol, + int line, const char *source); +CURL_EXTERN void curl_dbg_mark_sclose(curl_socket_t sockfd, + int line, const char *source); +CURL_EXTERN int curl_dbg_sclose(curl_socket_t sockfd, + int line, const char *source); +CURL_EXTERN curl_socket_t curl_dbg_accept(curl_socket_t s, + void *saddr, void *saddrlen, + int line, const char *source); +#ifdef HAVE_ACCEPT4 +CURL_EXTERN curl_socket_t curl_dbg_accept4(curl_socket_t s, void *saddr, + void *saddrlen, int flags, + int line, const char *source); +#endif +#ifdef HAVE_SOCKETPAIR +CURL_EXTERN int curl_dbg_socketpair(int domain, int type, int protocol, + curl_socket_t socket_vector[2], + int line, const char *source); +#endif + +/* FILE functions */ +CURL_EXTERN int curl_dbg_fclose(FILE *file, int line, const char *source); +CURL_EXTERN ALLOC_FUNC FILE *curl_dbg_fopen(const char *file, const char *mode, + int line, const char *source); +CURL_EXTERN ALLOC_FUNC FILE *curl_dbg_freopen(const char *file, + const char *mode, FILE *fh, + int line, const char *source); +CURL_EXTERN ALLOC_FUNC FILE *curl_dbg_fdopen(int filedes, const char *mode, + int line, const char *source); + +#define sclose(sockfd) curl_dbg_sclose(sockfd, __LINE__, __FILE__) +#define fake_sclose(sockfd) curl_dbg_mark_sclose(sockfd, __LINE__, __FILE__) + +#define CURL_GETADDRINFO(host, serv, hint, res) \ + curl_dbg_getaddrinfo(host, serv, hint, res, __LINE__, __FILE__) +#define CURL_FREEADDRINFO(data) \ + curl_dbg_freeaddrinfo(data, __LINE__, __FILE__) +#define CURL_SOCKET(domain, type, protocol) \ + curl_dbg_socket((int)(domain), type, protocol, __LINE__, __FILE__) +#ifdef HAVE_SOCKETPAIR +#define CURL_SOCKETPAIR(domain, type, protocol, socket_vector) \ + curl_dbg_socketpair((int)(domain), type, protocol, socket_vector, \ + __LINE__, __FILE__) +#endif +#define CURL_ACCEPT(sock, addr, len) \ + curl_dbg_accept(sock, addr, len, __LINE__, __FILE__) +#ifdef HAVE_ACCEPT4 +#define CURL_ACCEPT4(sock, addr, len, flags) \ + curl_dbg_accept4(sock, addr, len, flags, __LINE__, __FILE__) +#endif + +#else /* !CURL_MEMDEBUG */ + +#define sclose(x) CURL_SCLOSE(x) +#define fake_sclose(x) Curl_nop_stmt + +#define CURL_GETADDRINFO getaddrinfo +#define CURL_FREEADDRINFO freeaddrinfo +#define CURL_SOCKET socket +#ifdef HAVE_SOCKETPAIR +#define CURL_SOCKETPAIR socketpair +#endif +#define CURL_ACCEPT accept +#ifdef HAVE_ACCEPT4 +#define CURL_ACCEPT4 accept4 +#endif + +#endif /* CURL_MEMDEBUG */ + +/* Allocator macros */ + +#ifdef _WIN32 +#define CURLX_STRDUP_LOW _strdup +#else +#define CURLX_STRDUP_LOW strdup +#endif + +#ifdef CURL_MEMDEBUG + +#define curlx_strdup(ptr) curl_dbg_strdup(ptr, __LINE__, __FILE__) +#define curlx_malloc(size) curl_dbg_malloc(size, __LINE__, __FILE__) +#define curlx_calloc(nbelem, size) \ + curl_dbg_calloc(nbelem, size, __LINE__, __FILE__) +#define curlx_realloc(ptr, size) \ + curl_dbg_realloc(ptr, size, __LINE__, __FILE__) +#define curlx_free(ptr) curl_dbg_free(ptr, __LINE__, __FILE__) + +#ifdef _WIN32 +#ifdef UNICODE +#define curlx_tcsdup(ptr) curl_dbg_wcsdup(ptr, __LINE__, __FILE__) +#else +#define curlx_tcsdup curlx_strdup +#endif +#endif /* _WIN32 */ + +#else /* !CURL_MEMDEBUG */ + +#ifdef BUILDING_LIBCURL +#define curlx_strdup Curl_cstrdup +#define curlx_malloc Curl_cmalloc +#define curlx_calloc Curl_ccalloc +#define curlx_realloc Curl_crealloc +#define curlx_free Curl_cfree +#else /* !BUILDING_LIBCURL */ +#define curlx_strdup CURLX_STRDUP_LOW +#define curlx_malloc malloc +#define curlx_calloc calloc +#define curlx_realloc realloc +#define curlx_free free +#endif /* BUILDING_LIBCURL */ + +#ifdef _WIN32 +#ifdef UNICODE +#define curlx_tcsdup curlx_wcsdup +#else +#define curlx_tcsdup curlx_strdup +#endif +#endif /* _WIN32 */ + +#endif /* CURL_MEMDEBUG */ + +/* Some versions of the Android NDK is missing the declaration */ +#if defined(HAVE_GETPWUID_R) && \ + defined(__ANDROID_API__) && (__ANDROID_API__ < 21) +struct passwd; +int getpwuid_r(uid_t uid, struct passwd *pwd, char *buf, + size_t buflen, struct passwd **result); +#endif + +#ifdef UNITTESTS +#define UNITTEST +#else +#define UNITTEST static +#endif + +#ifdef USE_NGHTTP2 +#define USE_HTTP2 +#endif + +#if (defined(USE_NGTCP2) && defined(USE_NGHTTP3)) || defined(USE_QUICHE) + +#ifdef CURL_WITH_MULTI_SSL +#error "MultiSSL combined with QUIC is not supported" +#endif + +#define USE_HTTP3 +#endif + +/* WebAssembly builds have TCP_NODELAY, but runtime support is missing. */ +#ifndef __EMSCRIPTEN__ +#define CURL_TCP_NODELAY_SUPPORTED +#endif + +/* Certain Windows implementations are not aligned with what curl expects, + so always use the local one on this platform. E.g. the mingw-w64 + implementation can return wrong results for non-ASCII inputs. */ +#if defined(HAVE_BASENAME) && defined(_WIN32) +#undef HAVE_BASENAME +#endif + +#if defined(USE_UNIX_SOCKETS) && defined(_WIN32) +/* Offered by mingw-w64 v10+, MS SDK 10.0.16299.0/VS2017 15.4+ */ +#if defined(__MINGW32__) && (__MINGW64_VERSION_MAJOR >= 10) +# include <afunix.h> +#elif !defined(UNIX_PATH_MAX) /* Replicate logic present in afunix.h */ +# define UNIX_PATH_MAX 108 +/* !checksrc! disable TYPEDEFSTRUCT 1 */ +typedef struct sockaddr_un { + CURL_SA_FAMILY_T sun_family; + char sun_path[UNIX_PATH_MAX]; +} SOCKADDR_UN, *PSOCKADDR_UN; +#endif +#endif + +#ifdef USE_OPENSSL +/* OpenSSL 3 marks these functions deprecated but we have no replacements (yet) + so tell the compiler to not warn for them: + - DES_* (for NTLM) + - EVP_PKEY_get1_RSA, MD5_*, RSA_flags, RSA_free (auto-skipped for OpenSSL + built with no-deprecated) */ +# define OPENSSL_SUPPRESS_DEPRECATED +# ifdef _WIN32 +/* Silence LibreSSL warnings about wincrypt.h collision. Works in 3.8.2+ */ +# ifndef LIBRESSL_DISABLE_OVERRIDE_WINCRYPT_DEFINES_WARNING +# define LIBRESSL_DISABLE_OVERRIDE_WINCRYPT_DEFINES_WARNING +# endif +# endif +#endif + +#ifdef CURL_INLINE +/* 'CURL_INLINE' defined, use as-is */ +#elif defined(inline) +# define CURL_INLINE inline /* 'inline' defined, assumed correct */ +#elif defined(__cplusplus) +/* The code is compiled with C++ compiler. + C++ always supports 'inline'. */ +# define CURL_INLINE inline /* 'inline' keyword supported */ +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L +/* C99 (and later) supports 'inline' keyword */ +# define CURL_INLINE inline /* 'inline' keyword supported */ +#elif defined(__GNUC__) && __GNUC__ >= 3 +/* GCC supports '__inline__' as an extension */ +# define CURL_INLINE __inline__ +#elif defined(_MSC_VER) +# define CURL_INLINE __inline +#else +/* Probably 'inline' is not supported by compiler. + Define to the empty string to be on the safe side. */ +# define CURL_INLINE /* empty */ +#endif + +/* Detect if compiler supports C99 variadic macros */ +#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || \ + defined(_MSC_VER) +#define CURL_HAVE_MACRO_VARARG +#endif + +#if !defined(CURL_HAVE_MACRO_VARARG) || \ + (defined(CURL_HAVE_MACRO_VARARG) && !defined(CURL_DISABLE_VERBOSE_STRINGS)) +#define CURLVERBOSE +#define VERBOSE(x) x +#define NOVERBOSE(x) Curl_nop_stmt +#else +#define VERBOSE(x) Curl_nop_stmt +#define NOVERBOSE(x) x +#endif + +/* For FreeBSD it is included from curl/curl.h */ +#if defined(__DragonFly__) || defined(__OpenBSD__) || defined(__NetBSD__) +#include <sys/param.h> /* for __DragonFly_version, OpenBSD, + __NetBSD_Version__ */ +#endif + +/* NetBSD before 6.1 did not set SS_NBIO for SOCK_NONBLOCK. */ +#if defined(SOCK_NONBLOCK) && \ + (!defined(__NetBSD__) || (__NetBSD_Version__ >= 601000000)) +#define CURL_USE_SOCK_NONBLOCK +#endif + +#ifndef _CURL_LOCAL_MEMZERO /* to be removed after a couple of releases */ +#ifdef _WIN32 +#if defined(_MSC_VER) && defined(NTDDI_VERSION) && \ + (NTDDI_VERSION >= 0x0A000010) /* MS SDK 10.0.26100.0+ */ +#pragma comment(lib, "volatileaccessu.lib") +#define curlx_memzero_low(buf, size) SecureZeroMemory2(buf, size) +#else +#define curlx_memzero_low(buf, size) SecureZeroMemory(buf, size) +#endif +#elif defined(HAVE_MEMSET_S) +#define curlx_memzero_low(buf, size) (void)memset_s(buf, size, 0, size) +#elif defined(HAVE_MEMSET_EXPLICIT) +#define curlx_memzero_low(buf, size) (void)memset_explicit(buf, 0, size) +#elif defined(__CYGWIN__) || \ + (defined(__NEWLIB__) && !defined(__CLIB2__)) || \ + (defined(__GLIBC__) && \ + (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 25))) || \ + (defined(__DragonFly__) && __DragonFly_version >= 500600 /* 5.6+ */) || \ + (defined(__FreeBSD__) && __FreeBSD_version >= 1100037 /* 11.0+ */) || \ + (defined(__OpenBSD__) && OpenBSD >= 201405 /* 5.5+ */) +#define curlx_memzero_low(buf, size) explicit_bzero(buf, size) +#elif defined(__NetBSD__) && __NetBSD_Version__ >= 702000000 /* 7.2+ */ +#define curlx_memzero_low(buf, size) (void)explicit_memset(buf, 0, size) +#endif +#endif /* !_CURL_LOCAL_MEMZERO */ + +#ifndef curlx_memzero_low +#define USE_CURLX_MEMZERO +void curlx_memzero_low(void *buf, size_t size); +#endif +void curlx_memzero(void *buf, size_t size); +void curlx_strzero(void *buf); + +#endif /* HEADER_CURL_SETUP_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sha256.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sha256.h new file mode 100644 index 0000000000..fb823169f7 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sha256.h @@ -0,0 +1,46 @@ +#ifndef HEADER_CURL_SHA256_H +#define HEADER_CURL_SHA256_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Florin Petriuc, <petriuc.florin@gmail.com> + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_AWS) || !defined(CURL_DISABLE_HTTPSIG) || \ + !defined(CURL_DISABLE_DIGEST_AUTH) || \ + defined(USE_LIBSSH2) || defined(USE_SSL) + +#include "curl_hmac.h" + +extern const struct HMAC_params Curl_HMAC_SHA256; + +#ifndef CURL_SHA256_DIGEST_LENGTH +#define CURL_SHA256_DIGEST_LENGTH 32 /* fixed size */ +#endif + +CURLcode Curl_sha256it(unsigned char *output, const unsigned char *input, + size_t len); + +#endif + +#endif /* HEADER_CURL_SHA256_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sha512_256.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sha512_256.c new file mode 100644 index 0000000000..d0c81e7a55 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sha512_256.c @@ -0,0 +1,847 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Evgeny Grin (Karlson2k), <k2k@narod.ru>. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_DIGEST_AUTH) && !defined(CURL_DISABLE_SHA512_256) + +#include "curl_sha512_256.h" + +/* The recommended order of the TLS backends: + * 1. USE_OPENSSL + * 2. USE_WOLFSSL + * 3. USE_GNUTLS + * 4. USE_MBEDTLS (TBD) + * 5. USE_RUSTLS (TBD) + * 6. USE_WIN32_CRYPTO (TBD) + * Skip the backend if it does not support the required algorithm */ + +#ifdef USE_OPENSSL +# include <openssl/opensslv.h> +# if !defined(LIBRESSL_VERSION_NUMBER) || \ + (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x3080000fL) +# include <openssl/evp.h> +# define USE_OPENSSL_SHA512_256 1 +# define HAS_SHA512_256_IMPLEMENTATION 1 +# ifdef __NetBSD__ +/* Some NetBSD versions have a bug in SHA-512/256. + * See https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=58039 + * The problematic versions: + * - NetBSD before 9.4 + * - NetBSD 9 all development versions (9.99.x) + * - NetBSD 10 development versions (10.99.x) before 10.99.11 + * The bug was fixed in NetBSD 9.4 release, NetBSD 10.0 release, + * NetBSD 10.99.11 development. + * It is safe to apply the workaround even if the bug is not present, as + * the workaround reduces performance slightly. */ +# if __NetBSD_Version__ < 904000000 || \ + (__NetBSD_Version__ >= 999000000 && \ + __NetBSD_Version__ < 1000000000) || \ + (__NetBSD_Version__ >= 1099000000 && \ + __NetBSD_Version__ < 1099001100) +# define NEED_NETBSD_SHA512_256_WORKAROUND 1 +# endif +# endif +# endif +#endif /* USE_OPENSSL */ + +#if !defined(HAS_SHA512_256_IMPLEMENTATION) && defined(USE_WOLFSSL) +# include <wolfssl/options.h> +# ifndef WOLFSSL_NOSHA512_256 +# define USE_WOLFSSL_SHA512_256 1 +# define HAS_SHA512_256_IMPLEMENTATION 1 +# endif +#endif + +#if !defined(HAS_SHA512_256_IMPLEMENTATION) && defined(USE_GNUTLS) +# include <nettle/sha2.h> +# include <nettle/version.h> +# ifdef SHA512_256_DIGEST_SIZE +# define USE_GNUTLS_SHA512_256 1 +# endif +#endif /* !HAS_SHA512_256_IMPLEMENTATION && USE_GNUTLS */ + +#ifdef USE_OPENSSL_SHA512_256 + +/* OpenSSL does not provide macros for SHA-512/256 sizes */ + +/** + * Size of the SHA-512/256 single processing block in bytes. + */ +#define CURL_SHA512_256_BLOCK_SIZE 128 + +/** + * Size of the SHA-512/256 resulting digest in bytes. + * This is the final digest size, not intermediate hash. + */ +#define CURL_SHA512_256_DIGEST_SIZE CURL_SHA512_256_DIGEST_LENGTH + +/** + * Context type used for SHA-512/256 calculations + */ +typedef EVP_MD_CTX *Curl_sha512_256_ctx; + +/** + * Initialize structure for SHA-512/256 calculation. + * + * @param context the calculation context + * @return CURLE_OK if succeed, + * error code otherwise + */ +static CURLcode Curl_sha512_256_init(void *context) +{ + Curl_sha512_256_ctx * const ctx = (Curl_sha512_256_ctx *)context; + + *ctx = EVP_MD_CTX_new(); + if(!*ctx) + return CURLE_OUT_OF_MEMORY; + + if(EVP_DigestInit_ex(*ctx, EVP_sha512_256(), NULL)) { + /* Check whether the header and this file use the same numbers */ + DEBUGASSERT(EVP_MD_CTX_size(*ctx) == CURL_SHA512_256_DIGEST_SIZE); + /* Check whether the block size is correct */ + DEBUGASSERT(EVP_MD_CTX_block_size(*ctx) == CURL_SHA512_256_BLOCK_SIZE); + + return CURLE_OK; /* Success */ + } + + /* Cleanup */ + EVP_MD_CTX_free(*ctx); + return CURLE_FAILED_INIT; +} + +/** + * Process portion of bytes. + * + * @param context the calculation context + * @param data bytes to add to hash + * @return CURLE_OK if succeed, + * error code otherwise + */ +static CURLcode Curl_sha512_256_update(void *context, + const unsigned char *data, + size_t length) +{ + Curl_sha512_256_ctx * const ctx = (Curl_sha512_256_ctx *)context; + + if(!EVP_DigestUpdate(*ctx, data, length)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + return CURLE_OK; +} + +/** + * Finalise SHA-512/256 calculation, return digest. + * + * @param context the calculation context + * @param[out] digest set to the hash, must be #CURL_SHA512_256_DIGEST_SIZE + * bytes + * @return CURLE_OK if succeed, + * error code otherwise + */ +static CURLcode Curl_sha512_256_finish(unsigned char *digest, void *context) +{ + CURLcode result; + Curl_sha512_256_ctx * const ctx = (Curl_sha512_256_ctx *)context; + +#ifdef NEED_NETBSD_SHA512_256_WORKAROUND + /* Use a larger buffer to work around a bug in NetBSD: + https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=58039 */ + unsigned char tmp_digest[CURL_SHA512_256_DIGEST_SIZE * 2]; + result = EVP_DigestFinal_ex(*ctx, tmp_digest, NULL) ? + CURLE_OK : CURLE_BAD_FUNCTION_ARGUMENT; + if(result == CURLE_OK) + memcpy(digest, tmp_digest, CURL_SHA512_256_DIGEST_SIZE); + curlx_memzero(tmp_digest, sizeof(tmp_digest)); +#else /* !NEED_NETBSD_SHA512_256_WORKAROUND */ + result = EVP_DigestFinal_ex(*ctx, digest, NULL) ? + CURLE_OK : CURLE_BAD_FUNCTION_ARGUMENT; +#endif /* NEED_NETBSD_SHA512_256_WORKAROUND */ + + EVP_MD_CTX_free(*ctx); + *ctx = NULL; + + return result; +} + +#elif defined(USE_WOLFSSL_SHA512_256) +#include <wolfssl/wolfcrypt/sha512.h> + +#define CURL_SHA512_256_DIGEST_SIZE WC_SHA512_256_DIGEST_SIZE +#define CURL_SHA512_256_BLOCK_SIZE WC_SHA512_256_BLOCK_SIZE + +typedef struct wc_Sha512 Curl_sha512_256_ctx; + +static CURLcode Curl_sha512_256_init(void *ctx) +{ + if(wc_InitSha512_256(ctx)) + return CURLE_FAILED_INIT; + return CURLE_OK; +} + +static CURLcode Curl_sha512_256_update(void *ctx, + const unsigned char *data, + size_t length) +{ + do { + word32 ilen = (word32)CURLMIN(length, UINT_MAX); + if(wc_Sha512_256Update(ctx, data, ilen)) + return CURLE_BAD_FUNCTION_ARGUMENT; + length -= ilen; + data += ilen; + } while(length); + return CURLE_OK; +} + +static CURLcode Curl_sha512_256_finish(unsigned char *digest, void *ctx) +{ + if(wc_Sha512_256Final(ctx, digest)) + return CURLE_BAD_FUNCTION_ARGUMENT; + return CURLE_OK; +} + +#elif defined(USE_GNUTLS_SHA512_256) + +#define CURL_SHA512_256_BLOCK_SIZE SHA512_256_BLOCK_SIZE +#define CURL_SHA512_256_DIGEST_SIZE SHA512_256_DIGEST_SIZE + +/** + * Context type used for SHA-512/256 calculations + */ +typedef struct sha512_256_ctx Curl_sha512_256_ctx; + +/** + * Initialize structure for SHA-512/256 calculation. + * + * @param context the calculation context + * @return always CURLE_OK + */ +static CURLcode Curl_sha512_256_init(void *context) +{ + Curl_sha512_256_ctx * const ctx = (Curl_sha512_256_ctx *)context; + + /* Check whether the header and this file use the same numbers */ + DEBUGASSERT(CURL_SHA512_256_DIGEST_LENGTH == CURL_SHA512_256_DIGEST_SIZE); + + sha512_256_init(ctx); + + return CURLE_OK; +} + +/** + * Process portion of bytes. + * + * @param context the calculation context + * @param data bytes to add to hash + * @param length number of bytes in @a data + * @return always CURLE_OK + */ +static CURLcode Curl_sha512_256_update(void *context, + const unsigned char *data, + size_t length) +{ + Curl_sha512_256_ctx * const ctx = (Curl_sha512_256_ctx *)context; + + DEBUGASSERT(data || (length == 0)); + + sha512_256_update(ctx, length, (const uint8_t *)data); + + return CURLE_OK; +} + +/** + * Finalise SHA-512/256 calculation, return digest. + * + * @param context the calculation context + * @param[out] digest set to the hash, must be #CURL_SHA512_256_DIGEST_SIZE + * bytes + * @return always CURLE_OK + */ +static CURLcode Curl_sha512_256_finish(unsigned char *digest, void *context) +{ + Curl_sha512_256_ctx * const ctx = (Curl_sha512_256_ctx *)context; + +#if NETTLE_VERSION_MAJOR >= 4 + sha512_256_digest(ctx, (uint8_t *)digest); +#else + sha512_256_digest(ctx, + (size_t)CURL_SHA512_256_DIGEST_SIZE, (uint8_t *)digest); +#endif + + return CURLE_OK; +} + +#else /* No system or TLS backend SHA-512/256 implementation available */ + +/* ** This implementation of SHA-512/256 hash calculation was originally ** * + * ** written by Evgeny Grin (Karlson2k) for GNU libmicrohttpd. ** * + * ** The author ported the code to libcurl. The ported code is provided ** * + * ** under curl license. ** */ + +#ifdef __GNUC__ +# if defined(__has_attribute) && defined(__STDC_VERSION__) +# if __has_attribute(always_inline) && __STDC_VERSION__ >= 199901L +# define CURL_FORCEINLINE CURL_INLINE __attribute__((always_inline)) +# endif +# endif +#endif + +#if !defined(CURL_FORCEINLINE) && \ + defined(_MSC_VER) && !defined(__GNUC__) && !defined(__clang__) +#define CURL_FORCEINLINE __forceinline +#endif + +/* Assume that 'CURL_INLINE' keyword works or the + * macro was already defined correctly. */ +#ifndef CURL_FORCEINLINE +#define CURL_FORCEINLINE CURL_INLINE +#endif + +/* Bits manipulation macros and functions. + Can be moved to other headers to reuse. */ + +#define CURL_GET_64BIT_BE(ptr) \ + (((uint64_t)(((const uint8_t *)(ptr))[0]) << 56) | \ + ((uint64_t)(((const uint8_t *)(ptr))[1]) << 48) | \ + ((uint64_t)(((const uint8_t *)(ptr))[2]) << 40) | \ + ((uint64_t)(((const uint8_t *)(ptr))[3]) << 32) | \ + ((uint64_t)(((const uint8_t *)(ptr))[4]) << 24) | \ + ((uint64_t)(((const uint8_t *)(ptr))[5]) << 16) | \ + ((uint64_t)(((const uint8_t *)(ptr))[6]) << 8) | \ + (uint64_t)(((const uint8_t *)(ptr))[7])) + +#define CURL_PUT_64BIT_BE(ptr, val) \ + do { \ + ((uint8_t *)(ptr))[7] = (uint8_t)((uint64_t)(val)); \ + ((uint8_t *)(ptr))[6] = (uint8_t)(((uint64_t)(val)) >> 8); \ + ((uint8_t *)(ptr))[5] = (uint8_t)(((uint64_t)(val)) >> 16); \ + ((uint8_t *)(ptr))[4] = (uint8_t)(((uint64_t)(val)) >> 24); \ + ((uint8_t *)(ptr))[3] = (uint8_t)(((uint64_t)(val)) >> 32); \ + ((uint8_t *)(ptr))[2] = (uint8_t)(((uint64_t)(val)) >> 40); \ + ((uint8_t *)(ptr))[1] = (uint8_t)(((uint64_t)(val)) >> 48); \ + ((uint8_t *)(ptr))[0] = (uint8_t)(((uint64_t)(val)) >> 56); \ + } while(0) + +/* Defined as a function. The macro version may duplicate the binary code + * size as each argument is used twice, so if any calculation is used + * as an argument, the calculation could be done twice. */ +static CURL_FORCEINLINE uint64_t Curl_rotr64(uint64_t value, unsigned int bits) +{ + bits %= 64; + if(bits == 0) + return value; + /* Defined in a form which modern compiler could optimize. */ + return (value >> bits) | (value << (64 - bits)); +} + +/* SHA-512/256 specific data */ + +/** + * Number of bits in a single SHA-512/256 word. + */ +#define SHA512_256_WORD_SIZE_BITS 64 + +/** + * Number of bytes in a single SHA-512/256 word. + */ +#define SHA512_256_BYTES_IN_WORD (SHA512_256_WORD_SIZE_BITS / 8) + +/** + * Hash is kept internally as 8 64-bit words. + * This is the intermediate hash size, used during computing the final digest. + */ +#define SHA512_256_HASH_SIZE_WORDS 8 + +/** + * Size of the SHA-512/256 resulting digest in words. + * This is the final digest size, not intermediate hash. + */ +#define SHA512_256_DIGEST_SIZE_WORDS (SHA512_256_HASH_SIZE_WORDS / 2) + +/** + * Size of the SHA-512/256 resulting digest in bytes + * This is the final digest size, not intermediate hash. + */ +#define CURL_SHA512_256_DIGEST_SIZE \ + (SHA512_256_DIGEST_SIZE_WORDS * SHA512_256_BYTES_IN_WORD) + +/** + * Size of the SHA-512/256 single processing block in bits. + */ +#define SHA512_256_BLOCK_SIZE_BITS 1024 + +/** + * Size of the SHA-512/256 single processing block in bytes. + */ +#define CURL_SHA512_256_BLOCK_SIZE (SHA512_256_BLOCK_SIZE_BITS / 8) + +/** + * Size of the SHA-512/256 single processing block in words. + */ +#define SHA512_256_BLOCK_SIZE_WORDS \ + (SHA512_256_BLOCK_SIZE_BITS / SHA512_256_WORD_SIZE_BITS) + +/** + * SHA-512/256 calculation context + */ +struct Curl_sha512_256ctx { + /** + * Intermediate hash value. The variable is properly aligned. Smart + * compilers may automatically use fast load/store instruction for big + * endian data on little endian machine. + */ + uint64_t H[SHA512_256_HASH_SIZE_WORDS]; + /** + * SHA-512/256 input data buffer. The buffer is properly aligned. Smart + * compilers may automatically use fast load/store instruction for big + * endian data on little endian machine. + */ + uint64_t buffer[SHA512_256_BLOCK_SIZE_WORDS]; + /** + * The number of bytes, lower part + */ + uint64_t count; + /** + * The number of bits, high part. Unlike lower part, this counts the number + * of bits, not bytes. + */ + uint64_t count_bits_hi; +}; + +/** + * Context type used for SHA-512/256 calculations + */ +typedef struct Curl_sha512_256ctx Curl_sha512_256_ctx; + +/** + * Initialize structure for SHA-512/256 calculation. + * + * @param context the calculation context + * @return always CURLE_OK + */ +static CURLcode Curl_sha512_256_init(void *context) +{ + struct Curl_sha512_256ctx * const ctx = (struct Curl_sha512_256ctx *)context; + + /* Check whether the header and this file use the same numbers */ + DEBUGASSERT(CURL_SHA512_256_DIGEST_LENGTH == CURL_SHA512_256_DIGEST_SIZE); + + DEBUGASSERT(sizeof(uint64_t) == 8); + + /* Initial hash values, see FIPS PUB 180-4 section 5.3.6.2 */ + /* Values generated by "IV Generation Function" as described in + * section 5.3.6 */ + ctx->H[0] = UINT64_C(0x22312194FC2BF72C); + ctx->H[1] = UINT64_C(0x9F555FA3C84C64C2); + ctx->H[2] = UINT64_C(0x2393B86B6F53B151); + ctx->H[3] = UINT64_C(0x963877195940EABD); + ctx->H[4] = UINT64_C(0x96283EE2A88EFFE3); + ctx->H[5] = UINT64_C(0xBE5E1E2553863992); + ctx->H[6] = UINT64_C(0x2B0199FC2C85B8AA); + ctx->H[7] = UINT64_C(0x0EB72DDC81C52CA2); + + /* Initialize number of bytes and high part of number of bits. */ + ctx->count = UINT64_C(0); + ctx->count_bits_hi = UINT64_C(0); + + return CURLE_OK; +} + +/** + * Base of the SHA-512/256 transformation. + * Gets a full 128 bytes block of data and updates hash values; + * @param H hash values + * @param data the data buffer with #CURL_SHA512_256_BLOCK_SIZE bytes block + */ +static void Curl_sha512_256_transform(uint64_t H[SHA512_256_HASH_SIZE_WORDS], + const void *data) +{ + /* Working variables, + see FIPS PUB 180-4 section 6.7, 6.4. */ + uint64_t a = H[0]; + uint64_t b = H[1]; + uint64_t c = H[2]; + uint64_t d = H[3]; + uint64_t e = H[4]; + uint64_t f = H[5]; + uint64_t g = H[6]; + uint64_t h = H[7]; + + /* Data buffer, used as a cyclic buffer. + See FIPS PUB 180-4 section 5.2.2, 6.7, 6.4. */ + uint64_t W[16]; + + /* 'Ch' and 'Maj' macro functions are defined with widely-used optimization. + See FIPS PUB 180-4 formulae 4.8, 4.9. */ +#define Sha512_Ch(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) +#define Sha512_Maj(x, y, z) (((x) & (y)) ^ ((z) & ((x) ^ (y)))) + + /* Four 'Sigma' macro functions. + See FIPS PUB 180-4 formulae 4.10, 4.11, 4.12, 4.13. */ +#define SIG0(x) (Curl_rotr64(x, 28) ^ Curl_rotr64(x, 34) ^ Curl_rotr64(x, 39)) +#define SIG1(x) (Curl_rotr64(x, 14) ^ Curl_rotr64(x, 18) ^ Curl_rotr64(x, 41)) +#define sig0(x) (Curl_rotr64(x, 1) ^ Curl_rotr64(x, 8) ^ ((x) >> 7)) +#define sig1(x) (Curl_rotr64(x, 19) ^ Curl_rotr64(x, 61) ^ ((x) >> 6)) + + if(1) { + unsigned int t; + /* K constants array. + See FIPS PUB 180-4 section 4.2.3 for K values. */ + static const uint64_t K[80] = { + UINT64_C(0x428a2f98d728ae22), UINT64_C(0x7137449123ef65cd), + UINT64_C(0xb5c0fbcfec4d3b2f), UINT64_C(0xe9b5dba58189dbbc), + UINT64_C(0x3956c25bf348b538), UINT64_C(0x59f111f1b605d019), + UINT64_C(0x923f82a4af194f9b), UINT64_C(0xab1c5ed5da6d8118), + UINT64_C(0xd807aa98a3030242), UINT64_C(0x12835b0145706fbe), + UINT64_C(0x243185be4ee4b28c), UINT64_C(0x550c7dc3d5ffb4e2), + UINT64_C(0x72be5d74f27b896f), UINT64_C(0x80deb1fe3b1696b1), + UINT64_C(0x9bdc06a725c71235), UINT64_C(0xc19bf174cf692694), + UINT64_C(0xe49b69c19ef14ad2), UINT64_C(0xefbe4786384f25e3), + UINT64_C(0x0fc19dc68b8cd5b5), UINT64_C(0x240ca1cc77ac9c65), + UINT64_C(0x2de92c6f592b0275), UINT64_C(0x4a7484aa6ea6e483), + UINT64_C(0x5cb0a9dcbd41fbd4), UINT64_C(0x76f988da831153b5), + UINT64_C(0x983e5152ee66dfab), UINT64_C(0xa831c66d2db43210), + UINT64_C(0xb00327c898fb213f), UINT64_C(0xbf597fc7beef0ee4), + UINT64_C(0xc6e00bf33da88fc2), UINT64_C(0xd5a79147930aa725), + UINT64_C(0x06ca6351e003826f), UINT64_C(0x142929670a0e6e70), + UINT64_C(0x27b70a8546d22ffc), UINT64_C(0x2e1b21385c26c926), + UINT64_C(0x4d2c6dfc5ac42aed), UINT64_C(0x53380d139d95b3df), + UINT64_C(0x650a73548baf63de), UINT64_C(0x766a0abb3c77b2a8), + UINT64_C(0x81c2c92e47edaee6), UINT64_C(0x92722c851482353b), + UINT64_C(0xa2bfe8a14cf10364), UINT64_C(0xa81a664bbc423001), + UINT64_C(0xc24b8b70d0f89791), UINT64_C(0xc76c51a30654be30), + UINT64_C(0xd192e819d6ef5218), UINT64_C(0xd69906245565a910), + UINT64_C(0xf40e35855771202a), UINT64_C(0x106aa07032bbd1b8), + UINT64_C(0x19a4c116b8d2d0c8), UINT64_C(0x1e376c085141ab53), + UINT64_C(0x2748774cdf8eeb99), UINT64_C(0x34b0bcb5e19b48a8), + UINT64_C(0x391c0cb3c5c95a63), UINT64_C(0x4ed8aa4ae3418acb), + UINT64_C(0x5b9cca4f7763e373), UINT64_C(0x682e6ff3d6b2b8a3), + UINT64_C(0x748f82ee5defb2fc), UINT64_C(0x78a5636f43172f60), + UINT64_C(0x84c87814a1f0ab72), UINT64_C(0x8cc702081a6439ec), + UINT64_C(0x90befffa23631e28), UINT64_C(0xa4506cebde82bde9), + UINT64_C(0xbef9a3f7b2c67915), UINT64_C(0xc67178f2e372532b), + UINT64_C(0xca273eceea26619c), UINT64_C(0xd186b8c721c0c207), + UINT64_C(0xeada7dd6cde0eb1e), UINT64_C(0xf57d4f7fee6ed178), + UINT64_C(0x06f067aa72176fba), UINT64_C(0x0a637dc5a2c898a6), + UINT64_C(0x113f9804bef90dae), UINT64_C(0x1b710b35131c471b), + UINT64_C(0x28db77f523047d84), UINT64_C(0x32caab7b40c72493), + UINT64_C(0x3c9ebe0a15c9bebc), UINT64_C(0x431d67c49c100d4c), + UINT64_C(0x4cc5d4becb3e42b6), UINT64_C(0x597f299cfc657e2a), + UINT64_C(0x5fcb6fab3ad6faec), UINT64_C(0x6c44198c4a475817) + }; + + /* One step of SHA-512/256 computation, + see FIPS PUB 180-4 section 6.4.2 step 3. + * Note: this macro updates working variables in-place, without rotation. + * Note: the first (vH += SIG1(vE) + Ch(vE,vF,vG) + kt + wt) equals T1 in + FIPS PUB 180-4 section 6.4.2 step 3. + the second (vH += SIG0(vA) + Maj(vE,vF,vC) equals T1 + T2 in + FIPS PUB 180-4 section 6.4.2 step 3. + * Note: 'wt' must be used exactly one time in this macro as macro for + 'wt' calculation may change other data as well every time when + used. */ +#define SHA2STEP64(vA, vB, vC, vD, vE, vF, vG, vH, kt, wt) \ + do { \ + (vD) += ((vH) += SIG1(vE) + Sha512_Ch(vE, vF, vG) + (kt) + (wt)); \ + (vH) += SIG0(vA) + Sha512_Maj(vA, vB, vC); \ + } while(0) + + /* One step of SHA-512/256 computation with working variables rotation, + see FIPS PUB 180-4 section 6.4.2 step 3. This macro version reassigns + all working variables on each step. */ +#define SHA2STEP64RV(vA, vB, vC, vD, vE, vF, vG, vH, kt, wt) \ + do { \ + uint64_t tmp_h_ = (vH); \ + SHA2STEP64(vA, vB, vC, vD, vE, vF, vG, tmp_h_, kt, wt); \ + (vH) = (vG); \ + (vG) = (vF); \ + (vF) = (vE); \ + (vE) = (vD); \ + (vD) = (vC); \ + (vC) = (vB); \ + (vB) = (vA); \ + (vA) = tmp_h_; \ + } while(0) + + /* Get value of W(t) from input data buffer for 0 <= t <= 15, + See FIPS PUB 180-4 section 6.2. + Input data must be read in big-endian bytes order, + see FIPS PUB 180-4 section 3.1.2. */ +#define SHA512_GET_W_FROM_DATA(buf, t) \ + CURL_GET_64BIT_BE((const uint8_t *)(buf) + ((t) * SHA512_256_BYTES_IN_WORD)) + + /* During first 16 steps, before making any calculation on each step, the + W element is read from the input data buffer as a big-endian value and + stored in the array of W elements. */ + for(t = 0; t < 16; ++t) { + SHA2STEP64RV(a, b, c, d, e, f, g, h, K[t], + W[t] = SHA512_GET_W_FROM_DATA(data, t)); + } + + /* 'W' generation and assignment for 16 <= t <= 79. + See FIPS PUB 180-4 section 6.4.2. + As only the last 16 'W' are used in calculations, it is possible to + use 16 elements array of W as a cyclic buffer. + Note: ((t-16) & 15) have same value as (t & 15) */ +#define Wgen(w, t) \ + (uint64_t)((w)[((t) - 16) & 15] + sig1((w)[((t) - 2) & 15]) + \ + (w)[((t) - 7) & 15] + sig0((w)[((t) - 15) & 15])) + + /* During the last 64 steps, before making any calculation on each step, + current W element is generated from other W elements of the cyclic + buffer and the generated value is stored back in the cyclic buffer. */ + for(t = 16; t < 80; ++t) { + SHA2STEP64RV(a, b, c, d, e, f, g, h, K[t], + W[t & 15] = Wgen(W, t)); + } + } + + /* Compute and store the intermediate hash. + See FIPS PUB 180-4 section 6.4.2 step 4. */ + H[0] += a; + H[1] += b; + H[2] += c; + H[3] += d; + H[4] += e; + H[5] += f; + H[6] += g; + H[7] += h; +} + +/** + * Process portion of bytes. + * + * @param context the calculation context + * @param data bytes to add to hash + * @param length number of bytes in @a data + * @return always CURLE_OK + */ +static CURLcode Curl_sha512_256_update(void *context, + const unsigned char *data, + size_t length) +{ + unsigned int bytes_have; /* Number of bytes in the context buffer */ + struct Curl_sha512_256ctx * const ctx = (struct Curl_sha512_256ctx *)context; + /* the void pointer here is required to mute Intel compiler warning */ + void * const ctx_buf = ctx->buffer; + + DEBUGASSERT(data || (length == 0)); + + if(length == 0) + return CURLE_OK; /* Shortcut, do nothing */ + + /* Note: (count & (CURL_SHA512_256_BLOCK_SIZE - 1)) + equals (count % CURL_SHA512_256_BLOCK_SIZE) for this block size. */ + bytes_have = (unsigned int)(ctx->count & (CURL_SHA512_256_BLOCK_SIZE - 1)); + ctx->count += length; + if(length > ctx->count) + ctx->count_bits_hi += 1U << 3; /* Value wrap */ + ctx->count_bits_hi += ctx->count >> 61; + ctx->count &= UINT64_C(0x1FFFFFFFFFFFFFFF); + + if(bytes_have) { + unsigned int bytes_left = CURL_SHA512_256_BLOCK_SIZE - bytes_have; + if(length >= bytes_left) { + /* Combine new data with data in the buffer and process the full + block. */ + memcpy((unsigned char *)ctx_buf + bytes_have, data, bytes_left); + data += bytes_left; + length -= bytes_left; + Curl_sha512_256_transform(ctx->H, ctx->buffer); + bytes_have = 0; + } + } + + while(CURL_SHA512_256_BLOCK_SIZE <= length) { + /* Process any full blocks of new data directly, + without copying to the buffer. */ + Curl_sha512_256_transform(ctx->H, data); + data += CURL_SHA512_256_BLOCK_SIZE; + length -= CURL_SHA512_256_BLOCK_SIZE; + } + + if(length) { + /* Copy incomplete block of new data (if any) + to the buffer. */ + memcpy((unsigned char *)ctx_buf + bytes_have, data, length); + } + + return CURLE_OK; +} + +/** + * Size of "length" insertion in bits. + * See FIPS PUB 180-4 section 5.1.2. + */ +#define SHA512_256_SIZE_OF_LEN_ADD_BITS 128 + +/** + * Size of "length" insertion in bytes. + */ +#define SHA512_256_SIZE_OF_LEN_ADD (SHA512_256_SIZE_OF_LEN_ADD_BITS / 8) + +/** + * Finalise SHA-512/256 calculation, return digest. + * + * @param context the calculation context + * @param[out] digest set to the hash, must be #CURL_SHA512_256_DIGEST_SIZE + * bytes + * @return always CURLE_OK + */ +static CURLcode Curl_sha512_256_finish(unsigned char *digest, void *context) +{ + struct Curl_sha512_256ctx * const ctx = (struct Curl_sha512_256ctx *)context; + uint64_t num_bits; /* Number of processed bits */ + unsigned int bytes_have; /* Number of bytes in the context buffer */ + /* the void pointer here is required to mute Intel compiler warning */ + void * const ctx_buf = ctx->buffer; + + /* Memorise the number of processed bits. + The padding and other data added here during the postprocessing must + not change the amount of hashed data. */ + num_bits = ctx->count << 3; + + /* Note: (count & (CURL_SHA512_256_BLOCK_SIZE-1)) + equals (count % CURL_SHA512_256_BLOCK_SIZE) for this block size. */ + bytes_have = (unsigned int)(ctx->count & (CURL_SHA512_256_BLOCK_SIZE - 1)); + + /* Input data must be padded with a single bit "1", then with zeros and + the finally the length of data in bits must be added as the final bytes + of the last block. + See FIPS PUB 180-4 section 5.1.2. */ + + /* Data is always processed in form of bytes (not by individual bits), + therefore position of the first padding bit in byte is always + predefined (0x80). */ + /* Buffer always have space at least for one byte (as full buffers are + processed when formed). */ + ((unsigned char *)ctx_buf)[bytes_have++] = 0x80U; + + if(CURL_SHA512_256_BLOCK_SIZE - bytes_have < SHA512_256_SIZE_OF_LEN_ADD) { + /* No space in the current block to put the total length of message. + Pad the current block with zeros and process it. */ + if(bytes_have < CURL_SHA512_256_BLOCK_SIZE) + memset((unsigned char *)ctx_buf + bytes_have, 0, + CURL_SHA512_256_BLOCK_SIZE - bytes_have); + /* Process the full block. */ + Curl_sha512_256_transform(ctx->H, ctx->buffer); + /* Start the new block. */ + bytes_have = 0; + } + + /* Pad the rest of the buffer with zeros. */ + memset((unsigned char *)ctx_buf + bytes_have, 0, + CURL_SHA512_256_BLOCK_SIZE - SHA512_256_SIZE_OF_LEN_ADD - bytes_have); + /* Put high part of number of bits in processed message and then lower + part of number of bits as big-endian values. + See FIPS PUB 180-4 section 5.1.2. */ + /* Note: the target location is predefined and buffer is always aligned */ + CURL_PUT_64BIT_BE((unsigned char *)ctx_buf + + CURL_SHA512_256_BLOCK_SIZE - SHA512_256_SIZE_OF_LEN_ADD, + ctx->count_bits_hi); + CURL_PUT_64BIT_BE((unsigned char *)ctx_buf + + CURL_SHA512_256_BLOCK_SIZE - SHA512_256_SIZE_OF_LEN_ADD + + SHA512_256_BYTES_IN_WORD, + num_bits); + /* Process the full final block. */ + Curl_sha512_256_transform(ctx->H, ctx->buffer); + + /* Put in BE mode the leftmost part of the hash as the final digest. + See FIPS PUB 180-4 section 6.7. */ + + CURL_PUT_64BIT_BE(digest + (0 * SHA512_256_BYTES_IN_WORD), ctx->H[0]); + CURL_PUT_64BIT_BE(digest + (1 * SHA512_256_BYTES_IN_WORD), ctx->H[1]); + CURL_PUT_64BIT_BE(digest + (2 * SHA512_256_BYTES_IN_WORD), ctx->H[2]); + CURL_PUT_64BIT_BE(digest + (3 * SHA512_256_BYTES_IN_WORD), ctx->H[3]); + + /* Erase potentially sensitive data. */ + memset(ctx, 0, sizeof(struct Curl_sha512_256ctx)); + + return CURLE_OK; +} + +#endif /* Local SHA-512/256 code */ + +/** + * Compute SHA-512/256 hash for the given data in one function call + * @param[out] output the pointer to put the hash + * @param[in] input the pointer to the data to process + * @param input_size the size of the data pointed by @a input + * @return always #CURLE_OK + */ +CURLcode Curl_sha512_256it(unsigned char *output, const unsigned char *input, + size_t input_size) +{ + Curl_sha512_256_ctx ctx; + CURLcode result; + + result = Curl_sha512_256_init(&ctx); + if(result != CURLE_OK) + return result; + + result = Curl_sha512_256_update(&ctx, (const void *)input, input_size); + + if(result != CURLE_OK) { + (void)Curl_sha512_256_finish(output, &ctx); + return result; + } + + return Curl_sha512_256_finish(output, &ctx); +} + +/* Wrapper function, takes 'unsigned int' as length type, returns void */ +static void Curl_sha512_256_update_i(void *context, + const unsigned char *data, + unsigned int length) +{ + /* Hypothetically the function may fail, but assume it does not */ + (void)Curl_sha512_256_update(context, data, length); +} + +/* Wrapper function, returns void */ +static void Curl_sha512_256_finish_v(unsigned char *result, void *context) +{ + /* Hypothetically the function may fail, but assume it does not */ + (void)Curl_sha512_256_finish(result, context); +} + +/* Wrapper function, takes 'unsigned int' as length type, returns void */ + +const struct HMAC_params Curl_HMAC_SHA512_256[] = { + { + /* Initialize context procedure. */ + Curl_sha512_256_init, + /* Update context with data. */ + Curl_sha512_256_update_i, + /* Get final result procedure. */ + Curl_sha512_256_finish_v, + /* Context structure size. */ + sizeof(Curl_sha512_256_ctx), + /* Maximum key length (bytes). */ + CURL_SHA512_256_BLOCK_SIZE, + /* Result length (bytes). */ + CURL_SHA512_256_DIGEST_SIZE + } +}; + +#endif /* !CURL_DISABLE_DIGEST_AUTH && !CURL_DISABLE_SHA512_256 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sha512_256.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sha512_256.h new file mode 100644 index 0000000000..ddaf8be91d --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sha512_256.h @@ -0,0 +1,43 @@ +#ifndef HEADER_CURL_SHA512_256_H +#define HEADER_CURL_SHA512_256_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Evgeny Grin (Karlson2k), <k2k@narod.ru>. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_DIGEST_AUTH) && !defined(CURL_DISABLE_SHA512_256) + +#include "curl_hmac.h" + +#define CURL_HAVE_SHA512_256 + +extern const struct HMAC_params Curl_HMAC_SHA512_256[1]; + +#define CURL_SHA512_256_DIGEST_LENGTH 32 + +CURLcode Curl_sha512_256it(unsigned char *output, const unsigned char *input, + size_t input_size); + +#endif /* !CURL_DISABLE_DIGEST_AUTH && !CURL_DISABLE_SHA512_256 */ + +#endif /* HEADER_CURL_SHA256_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_share.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_share.c new file mode 100644 index 0000000000..cbadd57d37 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_share.c @@ -0,0 +1,490 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "multiif.h" +#include "curl_threads.h" +#include "curl_share.h" +#include "vtls/vtls.h" +#include "vtls/vtls_scache.h" +#include "hsts.h" +#include "url.h" + +static void share_destroy(struct Curl_share *share) +{ + if(!share) + return; + + if(share->specifier & (1 << CURL_LOCK_DATA_CONNECT)) { + Curl_cpool_destroy(&share->cpool, share->admin); + } + + Curl_dnscache_destroy(&share->dnscache); + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) + Curl_cookie_cleanup(share->cookies); +#endif + +#ifndef CURL_DISABLE_HSTS + Curl_hsts_cleanup(&share->hsts); +#endif + +#ifdef USE_SSL + if(share->ssl_scache) { + Curl_ssl_scache_destroy(share->ssl_scache); + share->ssl_scache = NULL; + } +#endif + + Curl_psl_destroy(&share->psl); + Curl_close(&share->admin); + +#ifdef USE_MUTEX + Curl_mutex_destroy(&share->lock); +#endif + curlx_memzero(share, sizeof(*share)); + curlx_free(share); +} + +CURLSH *curl_share_init(void) +{ + struct Curl_share *share = curlx_calloc(1, sizeof(struct Curl_share)); + if(share) { + share->magic = CURL_GOOD_SHARE; + share->specifier |= (1 << CURL_LOCK_DATA_SHARE); +#ifdef USE_MUTEX + Curl_mutex_init(&share->lock); +#endif + share->ref_count = 1; + Curl_dnscache_init(&share->dnscache, 23); + share->admin = curl_easy_init(); + if(!share->admin) { + share_destroy(share); + return NULL; + } + /* admin handles have mid 0 */ + share->admin->mid = 0; + share->admin->state.internal = TRUE; +#ifdef DEBUGBUILD + if(getenv("CURL_DEBUG")) + share->admin->set.verbose = TRUE; +#endif + } + return share; +} + +static uint32_t share_ref_inc(struct Curl_share *share) +{ + uint32_t n; +#ifdef USE_MUTEX + Curl_mutex_acquire(&share->lock); + n = ++share->ref_count; + share->has_been_shared = TRUE; + Curl_mutex_release(&share->lock); +#else + n = ++share->ref_count; + share->has_been_shared = TRUE; +#endif + return n; +} + +static uint32_t share_ref_dec(struct Curl_share *share) +{ + uint32_t n; +#ifdef USE_MUTEX + Curl_mutex_acquire(&share->lock); + DEBUGASSERT(share->ref_count); + n = --share->ref_count; + Curl_mutex_release(&share->lock); +#else + n = --share->ref_count; +#endif + return n; +} + +static bool share_has_been_shared(struct Curl_share *share) +{ + bool was_shared; +#ifdef USE_MUTEX + Curl_mutex_acquire(&share->lock); + was_shared = share->has_been_shared; + Curl_mutex_release(&share->lock); +#else + was_shared = share->has_been_shared; +#endif + return was_shared; +} + +static bool share_lock_acquire(struct Curl_share *share, + struct Curl_easy *data) +{ + if(share->lockfunc && share->unlockfunc && + (data || share_has_been_shared(share))) { + share->lockfunc(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE, + share->clientdata); + return TRUE; + } + return FALSE; +} + +static void share_lock_release(struct Curl_share *share, + struct Curl_easy *data, + bool locked) +{ + if(locked) { + DEBUGASSERT(share->unlockfunc); + if(share->unlockfunc) + share->unlockfunc(data, CURL_LOCK_DATA_SHARE, share->clientdata); + } +} + +static bool share_in_use(struct Curl_share *share) +{ + bool in_use; +#ifdef USE_MUTEX + Curl_mutex_acquire(&share->lock); + in_use = (share->ref_count > 1); + Curl_mutex_release(&share->lock); +#else + bool locked = share_lock_acquire(share, NULL); + in_use = (share->ref_count > 1); + share_lock_release(share, NULL, locked); +#endif + return in_use; +} + +static void share_unlink(struct Curl_share **pshare, + struct Curl_easy *data, + bool locked) +{ + struct Curl_share *share = *pshare; + uint32_t n; + + *pshare = NULL; + n = share_ref_dec(share); + if(locked) + share_lock_release(share, data, locked); + if(!n) /* last reference gone */ + share_destroy(share); +} + +#undef curl_share_setopt +CURLSHcode curl_share_setopt(CURLSH *sh, CURLSHoption option, ...) +{ + va_list param; + int type; + curl_lock_function lockfunc; + curl_unlock_function unlockfunc; + void *ptr; + CURLSHcode res = CURLSHE_OK; + struct Curl_share *share = sh; + + if(!GOOD_SHARE_HANDLE(share)) + return CURLSHE_INVALID; + + if(share_in_use(share)) { + /* do not allow setting options while one or more handles are already + using this share */ + return CURLSHE_IN_USE; + } + + va_start(param, option); + + switch(option) { + case CURLSHOPT_SHARE: + /* this is a type this share will share */ + type = va_arg(param, int); + + switch(type) { + case CURL_LOCK_DATA_DNS: + break; + + case CURL_LOCK_DATA_COOKIE: +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) + if(!share->cookies) { + share->cookies = Curl_cookie_init(); + if(!share->cookies) + res = CURLSHE_NOMEM; + } +#else /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */ + res = CURLSHE_NOT_BUILT_IN; +#endif + break; + + case CURL_LOCK_DATA_HSTS: +#ifndef CURL_DISABLE_HSTS + if(!share->hsts) { + share->hsts = Curl_hsts_init(); + if(!share->hsts) + res = CURLSHE_NOMEM; + } +#else /* CURL_DISABLE_HSTS */ + res = CURLSHE_NOT_BUILT_IN; +#endif + break; + + case CURL_LOCK_DATA_SSL_SESSION: +#ifdef USE_SSL + if(!share->ssl_scache) { + /* There is no way (yet) for the application to configure the + * session cache size, shared between many transfers. As for curl + * itself, a high session count will impact startup time. Also, the + * scache is not optimized for several hundreds of peers. + * Keep it at a reasonable level. */ + if(Curl_ssl_scache_create(25, 2, &share->ssl_scache)) + res = CURLSHE_NOMEM; + } +#else + res = CURLSHE_NOT_BUILT_IN; +#endif + break; + + case CURL_LOCK_DATA_CONNECT: + /* It is safe to set this option several times on a share. */ + if(!share->cpool.initialized) { + Curl_cpool_init(&share->cpool, share, 103); + } + break; + + case CURL_LOCK_DATA_PSL: +#ifndef USE_LIBPSL + res = CURLSHE_NOT_BUILT_IN; +#endif + break; + + default: + res = CURLSHE_BAD_OPTION; + } + if(!res) + share->specifier |= (unsigned int)(1 << type); + break; + + case CURLSHOPT_UNSHARE: + /* this is a type this share will no longer share */ + type = va_arg(param, int); + switch(type) { + case CURL_LOCK_DATA_DNS: + break; + + case CURL_LOCK_DATA_COOKIE: +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) + if(share->cookies) { + Curl_cookie_cleanup(share->cookies); + share->cookies = NULL; + } +#else /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */ + res = CURLSHE_NOT_BUILT_IN; +#endif + break; + + case CURL_LOCK_DATA_HSTS: +#ifndef CURL_DISABLE_HSTS + if(share->hsts) { + Curl_hsts_cleanup(&share->hsts); + } +#else /* CURL_DISABLE_HSTS */ + res = CURLSHE_NOT_BUILT_IN; +#endif + break; + + case CURL_LOCK_DATA_SSL_SESSION: +#ifdef USE_SSL + if(share->ssl_scache) { + Curl_ssl_scache_destroy(share->ssl_scache); + share->ssl_scache = NULL; + } +#else + res = CURLSHE_NOT_BUILT_IN; +#endif + break; + + case CURL_LOCK_DATA_CONNECT: + break; + + default: + res = CURLSHE_BAD_OPTION; + break; + } + if(!res) + share->specifier &= ~(unsigned int)(1 << type); + break; + + case CURLSHOPT_LOCKFUNC: + lockfunc = va_arg(param, curl_lock_function); + share->lockfunc = lockfunc; + break; + + case CURLSHOPT_UNLOCKFUNC: + unlockfunc = va_arg(param, curl_unlock_function); + share->unlockfunc = unlockfunc; + break; + + case CURLSHOPT_USERDATA: + ptr = va_arg(param, void *); + share->clientdata = ptr; + break; + + default: + res = CURLSHE_BAD_OPTION; + break; + } + + va_end(param); + + return res; +} + +CURLSHcode curl_share_cleanup(CURLSH *sh) +{ + struct Curl_share *share = sh; + bool locked; + if(!GOOD_SHARE_HANDLE(share)) + return CURLSHE_INVALID; + + if(share_in_use(share)) + return CURLSHE_IN_USE; + + locked = share_lock_acquire(share, NULL); + share_unlink(&share, NULL, locked); + return CURLSHE_OK; +} + +CURLSHcode Curl_share_lock_share(struct Curl_share *share, + struct Curl_easy *data, + curl_lock_data type, + curl_lock_access accesstype) +{ + if(!share) + return CURLSHE_INVALID; + + if(share->specifier & (unsigned int)(1 << type)) { + if(share->lockfunc) /* only call this if set! */ + share->lockfunc(data, type, accesstype, share->clientdata); + } + /* else if we do not share this, pretend successful lock */ + + return CURLSHE_OK; +} + +CURLSHcode Curl_share_lock(struct Curl_easy *data, curl_lock_data type, + curl_lock_access accesstype) +{ + return Curl_share_lock_share(data->share, data, type, accesstype); +} + +CURLSHcode Curl_share_unlock_share(struct Curl_share *share, + struct Curl_easy *data, + curl_lock_data type) +{ + if(!share) + return CURLSHE_INVALID; + + if(share->specifier & (unsigned int)(1 << type)) { + if(share->unlockfunc) /* only call this if set! */ + share->unlockfunc(data, type, share->clientdata); + } + + return CURLSHE_OK; +} + +CURLSHcode Curl_share_unlock(struct Curl_easy *data, curl_lock_data type) +{ + return Curl_share_unlock_share(data->share, data, type); +} + +CURLcode Curl_share_easy_unlink(struct Curl_easy *data) +{ + struct Curl_share *share = data->share; + + if(share) { + bool locked = share_lock_acquire(share, data); + + /* If share caches connections, detach any existing connection and + * forget its identifier. */ + if((share->specifier & (1 << CURL_LOCK_DATA_CONNECT))) { + if(data->conn) + Curl_detach_connection(data); + data->state.lastconnect_id = -1; + } + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) + if(share->cookies == data->cookies) + data->cookies = NULL; +#endif + +#ifndef CURL_DISABLE_HSTS + if(share->hsts == data->hsts) + data->hsts = NULL; +#endif +#ifdef USE_LIBPSL + if(&share->psl == data->psl) + data->psl = data->multi ? &data->multi->psl : NULL; +#endif + + share_unlink(&data->share, data, locked); + } + return CURLE_OK; +} + +CURLcode Curl_share_easy_link(struct Curl_easy *data, + struct Curl_share *share) +{ + if(data->share) { + DEBUGASSERT(0); + return CURLE_FAILED_INIT; + } + + if(share) { + bool locked = share_lock_acquire(share, data); + + share_ref_inc(share); + data->share = share; + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) + if(share->cookies) { + /* use shared cookie list, first free own one if any */ + Curl_cookie_cleanup(data->cookies); + /* enable cookies since we now use a share that uses cookies! */ + data->cookies = share->cookies; + } +#endif /* CURL_DISABLE_HTTP */ +#ifndef CURL_DISABLE_HSTS + if(share->hsts) { + /* first free the private one if any */ + Curl_hsts_cleanup(&data->hsts); + data->hsts = share->hsts; + } +#endif +#ifdef USE_LIBPSL + if(share->specifier & (1 << CURL_LOCK_DATA_PSL)) + data->psl = &share->psl; +#endif + + /* check for host cache not needed, + * it will be done by curl_easy_perform */ + share_lock_release(share, data, locked); + } + return CURLE_OK; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_share.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_share.h new file mode 100644 index 0000000000..5c687989e0 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_share.h @@ -0,0 +1,100 @@ +#ifndef HEADER_CURL_SHARE_H +#define HEADER_CURL_SHARE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curl_threads.h" +#include "cookie.h" +#include "psl.h" +#include "urldata.h" +#include "conncache.h" + +struct Curl_easy; +struct Curl_ssl_scache; + +#define CURL_GOOD_SHARE 0x7e117a1e +#define GOOD_SHARE_HANDLE(x) ((x) && (x)->magic == CURL_GOOD_SHARE) + +#define CURL_SHARE_KEEP_CONNECT(s) \ + ((s) && ((s)->specifier & (1 << CURL_LOCK_DATA_CONNECT))) + +/* this struct is libcurl-private, do not export details */ +struct Curl_share { + unsigned int magic; /* CURL_GOOD_SHARE */ + unsigned int specifier; + + uint32_t ref_count; +#ifdef USE_MUTEX + /* do `ref_count` and `has_been_shared` checks using this mutex. */ + curl_mutex_t lock; + int has_been_shared; +#else + /* this only ever goes from FALSE -> TRUE once. We need to check + * this without being able to use the `lockfunc`. */ + volatile int has_been_shared; +#endif + curl_lock_function lockfunc; + curl_unlock_function unlockfunc; + void *clientdata; + struct Curl_easy *admin; + + struct cpool cpool; + struct Curl_dnscache dnscache; /* DNS cache */ +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) + struct CookieInfo *cookies; +#endif +#ifdef USE_LIBPSL + struct PslCache psl; +#endif +#ifndef CURL_DISABLE_HSTS + struct hsts *hsts; +#endif +#ifdef USE_SSL + struct Curl_ssl_scache *ssl_scache; +#endif +}; + +CURLSHcode Curl_share_lock(struct Curl_easy *data, curl_lock_data type, + curl_lock_access accesstype); +CURLSHcode Curl_share_unlock(struct Curl_easy *data, curl_lock_data type); + +CURLSHcode Curl_share_lock_share(struct Curl_share *share, + struct Curl_easy *data, + curl_lock_data type, + curl_lock_access accesstype); +CURLSHcode Curl_share_unlock_share(struct Curl_share *share, + struct Curl_easy *data, + curl_lock_data type); + +/* convenience macro to check if this handle is using a shared SSL spool */ +#define CURL_SHARE_ssl_scache(data) \ + ((data)->share && \ + ((data)->share->specifier & (1 << CURL_LOCK_DATA_SSL_SESSION))) + +CURLcode Curl_share_easy_unlink(struct Curl_easy *data); +CURLcode Curl_share_easy_link(struct Curl_easy *data, + struct Curl_share *share); + +#endif /* HEADER_CURL_SHARE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sspi.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sspi.c new file mode 100644 index 0000000000..799f3429a4 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sspi.c @@ -0,0 +1,209 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_WINDOWS_SSPI + +#include "curl_sspi.h" +#include "curlx/strdup.h" +#include "curlx/multibyte.h" + +/* Pointer to SSPI dispatch table */ +PSecurityFunctionTable Curl_pSecFn = NULL; + +/* + * Curl_sspi_global_init() + * + * This is used to load the Security Service Provider Interface (SSPI) + * dynamic link library portably across all Windows versions, without + * the need to directly link libcurl, nor the application using it, at + * build time. + * + * Once this function has been executed, Windows SSPI functions can be + * called through the Security Service Provider Interface dispatch table. + * + * Parameters: + * + * None. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_sspi_global_init(void) +{ + /* If security interface is not yet initialized try to do this */ + if(!Curl_pSecFn) { + /* Get pointer to Security Service Provider Interface dispatch table */ + Curl_pSecFn = InitSecurityInterface(); + if(!Curl_pSecFn) + return CURLE_FAILED_INIT; + } + + return CURLE_OK; +} + +/* + * Curl_sspi_global_cleanup() + * + * This deinitializes the Security Service Provider Interface from libcurl. + * + * Parameters: + * + * None. + */ +void Curl_sspi_global_cleanup(void) +{ + if(Curl_pSecFn) { + Curl_pSecFn = NULL; + } +} + +/* + * Curl_create_sspi_identity() + * + * This is used to populate an SSPI identity structure based on the supplied + * username and password. + * + * Parameters: + * + * userp [in] - The username in the format User or Domain\User. + * passwdp [in] - The user's password. + * identity [in/out] - The identity structure. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_create_sspi_identity(const char *userp, const char *passwdp, + SEC_WINNT_AUTH_IDENTITY_EX *identity) +{ + xcharp_u useranddomain; + xcharp_u user, dup_user; + xcharp_u domain, dup_domain; + xcharp_u passwd, dup_passwd; + size_t domlen = 0; + size_t pwlen; + + domain.const_tchar_ptr = _TEXT(""); + + /* Initialize the identity */ + memset(identity, 0, sizeof(*identity)); + identity->Version = SEC_WINNT_AUTH_IDENTITY_VERSION; + identity->Length = sizeof(*identity); + + useranddomain.tchar_ptr = curlx_convert_UTF8_to_tchar(userp); + if(!useranddomain.tchar_ptr) + return CURLE_OUT_OF_MEMORY; + + user.const_tchar_ptr = _tcschr(useranddomain.const_tchar_ptr, _TEXT('\\')); + if(!user.const_tchar_ptr) + user.const_tchar_ptr = _tcschr(useranddomain.const_tchar_ptr, _TEXT('/')); + + if(user.tchar_ptr) { + domain.tchar_ptr = useranddomain.tchar_ptr; + domlen = user.tchar_ptr - useranddomain.tchar_ptr; + user.tchar_ptr++; + } + else { + user.tchar_ptr = useranddomain.tchar_ptr; + domain.const_tchar_ptr = _TEXT(""); + domlen = 0; + } + + /* Setup the identity's user and length */ + dup_user.tchar_ptr = curlx_tcsdup(user.tchar_ptr); + if(!dup_user.tchar_ptr) { + curlx_free(useranddomain.tchar_ptr); + return CURLE_OUT_OF_MEMORY; + } + + /* Setup the identity's domain and length */ + dup_domain.tchar_ptr = curlx_malloc(sizeof(TCHAR) * (domlen + 1)); + if(!dup_domain.tchar_ptr) { + curlx_free(dup_user.tchar_ptr); + curlx_free(useranddomain.tchar_ptr); + return CURLE_OUT_OF_MEMORY; + } + if(_tcsncpy_s(dup_domain.tchar_ptr, domlen + 1, domain.tchar_ptr, domlen)) { + curlx_free(dup_user.tchar_ptr); + curlx_free(dup_domain.tchar_ptr); + curlx_free(useranddomain.tchar_ptr); + return CURLE_OUT_OF_MEMORY; + } + + curlx_free(useranddomain.tchar_ptr); + + /* Setup the identity's password and length */ + passwd.tchar_ptr = curlx_convert_UTF8_to_tchar(passwdp); + if(!passwd.tchar_ptr) { + curlx_free(dup_user.tchar_ptr); + curlx_free(dup_domain.tchar_ptr); + return CURLE_OUT_OF_MEMORY; + } + pwlen = _tcslen(passwd.tchar_ptr); + dup_passwd.tchar_ptr = curlx_tcsdup(passwd.tchar_ptr); + if(!dup_passwd.tchar_ptr) { + curlx_free(dup_user.tchar_ptr); + curlx_free(dup_domain.tchar_ptr); + curlx_memzero(passwd.tchar_ptr, pwlen * sizeof(*passwd.tchar_ptr)); + curlx_free(passwd.tchar_ptr); + return CURLE_OUT_OF_MEMORY; + } + identity->Password = dup_passwd.tbyte_ptr; + identity->PasswordLength = curlx_uztoul(pwlen); + dup_passwd.tchar_ptr = NULL; + + curlx_memzero(passwd.tchar_ptr, pwlen * sizeof(*passwd.tchar_ptr)); + curlx_free(passwd.tchar_ptr); + + identity->User = dup_user.tbyte_ptr; + identity->UserLength = curlx_uztoul(_tcslen(dup_user.tchar_ptr)); + dup_user.tchar_ptr = NULL; + identity->Domain = dup_domain.tbyte_ptr; + identity->DomainLength = curlx_uztoul(domlen); + dup_domain.tchar_ptr = NULL; + + identity->Flags = CURL_SEC_WINNT_AUTH_IDENTITY; + + return CURLE_OK; +} + +/* + * Curl_sspi_free_identity() + * + * This is used to free the contents of an SSPI identifier structure. + * + * Parameters: + * + * identity [in/out] - The identity structure. + */ +void Curl_sspi_free_identity(SEC_WINNT_AUTH_IDENTITY_EX *identity) +{ + if(identity) { + curlx_safefree(identity->User); + curlx_memzero(identity->Password, + identity->PasswordLength * sizeof(*identity->Password)); + curlx_safefree(identity->Password); + curlx_safefree(identity->Domain); + } +} + +#endif /* USE_WINDOWS_SSPI */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sspi.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sspi.h new file mode 100644 index 0000000000..da8e26d642 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_sspi.h @@ -0,0 +1,103 @@ +#ifndef HEADER_CURL_SSPI_H +#define HEADER_CURL_SSPI_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_WINDOWS_SSPI + +#include <sspi.h> + +/* Local helper macro */ +#ifdef UNICODE +#define CURL_SEC_WINNT_AUTH_IDENTITY SEC_WINNT_AUTH_IDENTITY_UNICODE +#else +#define CURL_SEC_WINNT_AUTH_IDENTITY SEC_WINNT_AUTH_IDENTITY_ANSI +#endif + +/* Offered by mingw-w64 v9+, MS SDK 7.0A/VS2010+ */ +#ifndef SECPKG_ATTR_ENDPOINT_BINDINGS +#define SECPKG_ATTR_ENDPOINT_BINDINGS 26 +/* !checksrc! disable TYPEDEFSTRUCT 1 */ +typedef struct { + unsigned long BindingsLength; + SEC_CHANNEL_BINDINGS *Bindings; +} SecPkgContext_Bindings; +#endif + +CURLcode Curl_sspi_global_init(void); +void Curl_sspi_global_cleanup(void); + +/* This is used to populate the domain in an SSPI identity structure */ +CURLcode Curl_override_sspi_http_realm(const char *chlg, + SEC_WINNT_AUTH_IDENTITY_EX *identity); + +/* This is used to generate an SSPI identity structure */ +CURLcode Curl_create_sspi_identity(const char *userp, const char *passwdp, + SEC_WINNT_AUTH_IDENTITY_EX *identity); + +/* This is used to free an SSPI identity structure */ +void Curl_sspi_free_identity(SEC_WINNT_AUTH_IDENTITY_EX *identity); + +/* Forward-declaration of global variables defined in curl_sspi.c */ +extern PSecurityFunctionTable Curl_pSecFn; + +/* Provide Service Principal names as macros */ +#define SP_NAME_DIGEST "WDigest" +#define SP_NAME_NTLM "NTLM" +#define SP_NAME_NEGOTIATE "Negotiate" +#define SP_NAME_KERBEROS "Kerberos" + +/* Offered by mingw-w64 v9+, MS SDK 7.0A/VS2010+ */ +#ifndef ISC_REQ_USE_HTTP_STYLE +#define ISC_REQ_USE_HTTP_STYLE 0x01000000 +#endif + +/* Offered by mingw-w64 v8+, MS SDK 6.0A/VS2008+ */ +#ifndef SEC_E_INVALID_PARAMETER +#define SEC_E_INVALID_PARAMETER ((HRESULT)0x8009035DL) +#endif +/* Offered by mingw-w64 v8+, MS SDK 6.0A/VS2008+ */ +#ifndef SEC_E_DELEGATION_POLICY +#define SEC_E_DELEGATION_POLICY ((HRESULT)0x8009035EL) +#endif +/* Offered by mingw-w64 v8+, MS SDK 6.0A/VS2008+ */ +#ifndef SEC_E_POLICY_NLTM_ONLY +#define SEC_E_POLICY_NLTM_ONLY ((HRESULT)0x8009035FL) +#endif + +/* Offered by mingw-w64 v8+, MS SDK 6.0A/VS2008+ */ +#ifndef SEC_I_SIGNATURE_NEEDED +#define SEC_I_SIGNATURE_NEEDED ((HRESULT)0x0009035CL) +#endif + +/* + * Definitions required from ntsecapi.h are directly provided below this point + * to avoid including ntsecapi.h due to a conflict with OpenSSL's safestack.h + */ +#define KERB_WRAP_NO_ENCRYPT 0x80000001 + +#endif /* USE_WINDOWS_SSPI */ + +#endif /* HEADER_CURL_SSPI_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_threads.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_threads.c new file mode 100644 index 0000000000..a5857b43b9 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_threads.c @@ -0,0 +1,235 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "curl_threads.h" +#include "curlx/timeval.h" + +#ifdef USE_THREADS + +#ifdef _WIN32 + +curl_thread_t Curl_thread_create( + CURL_THREAD_RETURN_T(CURL_STDCALL *func)(void *), void *arg) +{ + curl_thread_t t = CreateThread(NULL, 0, func, arg, 0, NULL); + if(!t) { + DWORD gle = GetLastError(); + /* !checksrc! disable ERRNOVAR 1 */ + errno = (gle == ERROR_ACCESS_DENIED || + gle == ERROR_NOT_ENOUGH_MEMORY) ? + EACCES : EINVAL; + return curl_thread_t_null; + } + return t; +} + +void Curl_thread_destroy(curl_thread_t *hnd) +{ + if(*hnd != curl_thread_t_null) { + CloseHandle(*hnd); + *hnd = curl_thread_t_null; + } +} + +int Curl_thread_join(curl_thread_t *hnd) +{ + int ret = (WaitForSingleObjectEx(*hnd, INFINITE, FALSE) == WAIT_OBJECT_0); + + Curl_thread_destroy(hnd); + + return ret; +} + +#elif defined(HAVE_THREADS_POSIX) + +struct Curl_actual_call { + unsigned int (*func)(void *); + void *arg; +}; + +static void *curl_thread_create_thunk(void *arg) +{ + struct Curl_actual_call *ac = arg; + unsigned int (*func)(void *) = ac->func; + void *real_arg = ac->arg; + + curlx_free(ac); + + (*func)(real_arg); + + return 0; +} + +curl_thread_t Curl_thread_create( + CURL_THREAD_RETURN_T(CURL_STDCALL *func)(void *), void *arg) +{ + curl_thread_t t = curlx_malloc(sizeof(pthread_t)); + struct Curl_actual_call *ac = NULL; + int rc; + + if(t) + ac = curlx_malloc(sizeof(struct Curl_actual_call)); + if(!(ac && t)) + goto err; + + ac->func = func; + ac->arg = arg; + + rc = pthread_create(t, NULL, curl_thread_create_thunk, ac); + if(rc) { + errno = rc; + goto err; + } + + return t; + +err: + curlx_free(t); + curlx_free(ac); + return curl_thread_t_null; +} + +void Curl_thread_destroy(curl_thread_t *hnd) +{ + if(*hnd != curl_thread_t_null) { + pthread_detach(**hnd); + curlx_free(*hnd); + *hnd = curl_thread_t_null; + } +} + +int Curl_thread_join(curl_thread_t *hnd) +{ + int ret = (pthread_join(**hnd, NULL) == 0); + + curlx_free(*hnd); + *hnd = curl_thread_t_null; + + return ret; +} + +#else +#error neither HAVE_THREADS_POSIX nor _WIN32 defined +#endif +#endif /* USE_THREADS */ + +#ifdef USE_MUTEX + +#ifdef _WIN32 + +void Curl_cond_signal(CONDITION_VARIABLE *c) +{ + WakeConditionVariable(c); +} + +void Curl_cond_wait(CONDITION_VARIABLE *c, CRITICAL_SECTION *m) +{ + SleepConditionVariableCS(c, m, INFINITE); +} + +CURLcode Curl_cond_timedwait(CONDITION_VARIABLE *c, CRITICAL_SECTION *m, + uint32_t timeout_ms) +{ + if(!SleepConditionVariableCS(c, m, (DWORD)timeout_ms)) { + DWORD err = GetLastError(); + return (err == ERROR_TIMEOUT) ? + CURLE_OPERATION_TIMEDOUT : CURLE_UNRECOVERABLE_POLL; + } + return CURLE_OK; +} + +curl_thread_id_t Curl_thread_get_current_id(void) +{ + return GetCurrentThreadId(); +} + +bool Curl_thread_is_current(curl_thread_id_t tid) +{ + return tid == GetCurrentThreadId(); +} + +#elif defined(HAVE_THREADS_POSIX) + +void Curl_cond_signal(pthread_cond_t *c) +{ + /* return code defined as always 0 */ + (void)pthread_cond_signal(c); +} + +void Curl_cond_wait(pthread_cond_t *c, pthread_mutex_t *m) +{ + /* return code defined as always 0 */ + (void)pthread_cond_wait(c, m); +} + +CURLcode Curl_cond_timedwait(pthread_cond_t *c, pthread_mutex_t *m, + uint32_t timeout_ms) +{ + struct curltime now; + struct timespec ts; + timediff_t usec; + int rc; + + /* POSIX expects an "absolute" time until the condition wait ends. + * We cannot use `curlx_now()` here that may run on some monotonic clock + * that will be most likely in the past, as far as POSIX abstime is + * concerned. */ +#ifdef HAVE_GETTIMEOFDAY + struct timeval tv; + (void)gettimeofday(&tv, NULL); + now.tv_sec = tv.tv_sec; + now.tv_usec = (int)tv.tv_usec; +#else + now.tv_sec = time(NULL); + now.tv_usec = 0; +#endif + + ts.tv_sec = now.tv_sec + (timeout_ms / 1000); + usec = now.tv_usec + ((timeout_ms % 1000) * 1000); + if(usec >= 1000000) { + ++ts.tv_sec; + usec %= 1000000; + } + ts.tv_nsec = (long)usec * 1000; + + rc = pthread_cond_timedwait(c, m, &ts); + if(rc == SOCKETIMEDOUT) + return CURLE_OPERATION_TIMEDOUT; + return rc ? CURLE_UNRECOVERABLE_POLL : CURLE_OK; +} + +curl_thread_id_t Curl_thread_get_current_id(void) +{ + return pthread_self(); +} + +bool Curl_thread_is_current(curl_thread_id_t tid) +{ + return !!pthread_equal(tid, pthread_self()); +} + +#else +#error neither HAVE_THREADS_POSIX nor _WIN32 defined +#endif +#endif /* USE_MUTEX */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_threads.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_threads.h new file mode 100644 index 0000000000..fc73c1222e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_threads.h @@ -0,0 +1,83 @@ +#ifndef HEADER_CURL_THREADS_H +#define HEADER_CURL_THREADS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_MUTEX +#ifdef _WIN32 +# define CURL_THREAD_RETURN_T DWORD +# define CURL_STDCALL WINAPI +# define curl_mutex_t CRITICAL_SECTION +# define curl_thread_t HANDLE +# define curl_thread_id_t DWORD +# define curl_thread_t_null (HANDLE)0 +# define Curl_mutex_init(m) InitializeCriticalSectionEx(m, 0, 1) +# define Curl_mutex_acquire(m) EnterCriticalSection(m) +# define Curl_mutex_release(m) LeaveCriticalSection(m) +# define Curl_mutex_destroy(m) DeleteCriticalSection(m) +# define curl_cond_t CONDITION_VARIABLE +# define Curl_cond_init(c) InitializeConditionVariable(c) +# define Curl_cond_destroy(c) (void)(c) +#elif defined(HAVE_THREADS_POSIX) +# define CURL_THREAD_RETURN_T unsigned int +# define CURL_STDCALL +# define curl_mutex_t pthread_mutex_t +# define curl_thread_t pthread_t * +# define curl_thread_id_t pthread_t +# define curl_thread_t_null (pthread_t *)0 +# define Curl_mutex_init(m) pthread_mutex_init(m, NULL) +# define Curl_mutex_acquire(m) pthread_mutex_lock(m) +# define Curl_mutex_release(m) pthread_mutex_unlock(m) +# define Curl_mutex_destroy(m) pthread_mutex_destroy(m) +# define curl_cond_t pthread_cond_t +# define Curl_cond_init(c) pthread_cond_init(c, NULL) +# define Curl_cond_destroy(c) pthread_cond_destroy(c) +#else +#error neither HAVE_THREADS_POSIX nor _WIN32 defined +#endif + +void Curl_cond_signal(curl_cond_t *c); +void Curl_cond_wait(curl_cond_t *c, curl_mutex_t *m); +/* Returns CURLE_OPERATION_TIMEDOUT on timeout */ +CURLcode Curl_cond_timedwait(curl_cond_t *c, curl_mutex_t *m, + uint32_t timeout_ms); + +curl_thread_id_t Curl_thread_get_current_id(void); +bool Curl_thread_is_current(curl_thread_id_t tid); + +#endif /* USE_MUTEX */ + +#ifdef USE_THREADS + +curl_thread_t Curl_thread_create( + CURL_THREAD_RETURN_T(CURL_STDCALL *func)(void *), void *arg); + +void Curl_thread_destroy(curl_thread_t *hnd); + +int Curl_thread_join(curl_thread_t *hnd); + +#endif /* USE_THREADS */ + +#endif /* HEADER_CURL_THREADS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_trc.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_trc.c new file mode 100644 index 0000000000..2bf81e8119 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_trc.c @@ -0,0 +1,780 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curl_trc.h" +#include "urldata.h" +#include "cfilters.h" +#include "multiif.h" + +#include "cf-recvbuf.h" +#include "cf-socket.h" +#include "cf-setup.h" +#include "http2.h" +#include "http_proxy.h" +#include "cf-h1-proxy.h" +#include "cf-h2-proxy.h" +#include "cf-haproxy.h" +#include "cf-https-connect.h" +#include "cf-ip-happy.h" +#include "progress.h" +#include "socks.h" +#include "curlx/strparse.h" +#include "vdns/cf-dns.h" +#include "vtls/vtls.h" +#include "vquic/vquic.h" +#include "curlx/strcopy.h" + +static void trc_write(struct Curl_easy *data, curl_infotype type, + const char *ptr, size_t size) +{ + if(data->set.verbose) { + if(data->set.fdebug) { + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_fdebug); + (void)(*data->set.fdebug)(data, type, CURL_UNCONST(ptr), size, + data->set.debugdata); + CURL_CBAPI_END(&guard); + } + else { + static const char s_infotype[CURLINFO_END][3] = { + "* ", "< ", "> ", "{ ", "} ", "{ ", "} " }; + switch(type) { + case CURLINFO_TEXT: + case CURLINFO_HEADER_OUT: + case CURLINFO_HEADER_IN: + fwrite(s_infotype[type], 2, 1, data->set.err); + fwrite(ptr, size, 1, data->set.err); + break; + default: /* nada */ + break; + } + } + } +} + +/* max length we trace before ending in '...' */ +#define TRC_LINE_MAX 2048 + +#define CURL_TRC_FMT_IDSC "[x-%" CURL_FORMAT_CURL_OFF_T "] " +#define CURL_TRC_FMT_IDSD "[%" CURL_FORMAT_CURL_OFF_T "-x] " +#define CURL_TRC_FMT_IDSDC "[%" CURL_FORMAT_CURL_OFF_T "-%" \ + CURL_FORMAT_CURL_OFF_T "] " + +static struct curl_trc_feat Curl_trc_feat_ids = { + "LIB-IDS", + CURL_LOG_LVL_NONE, +}; +#define CURL_TRC_IDS(data) \ + (Curl_trc_is_verbose(data) && \ + Curl_trc_feat_ids.log_level >= CURL_LOG_LVL_INFO) + +static size_t trc_print_ids(struct Curl_easy *data, char *buf, size_t maxlen) +{ + curl_off_t cid = data->state.lastconnect_id; + if(data->id >= 0) { + if(cid >= 0) + return curl_msnprintf(buf, maxlen, CURL_TRC_FMT_IDSDC, data->id, cid); + else + return curl_msnprintf(buf, maxlen, CURL_TRC_FMT_IDSD, data->id); + } + else if(cid >= 0) + return curl_msnprintf(buf, maxlen, CURL_TRC_FMT_IDSC, cid); + else { + return curl_msnprintf(buf, maxlen, "[x-x] "); + } +} + +static size_t trc_end_buf(char *buf, size_t len, size_t maxlen, bool addnl) +{ + /* make sure we end the trace line in `buf` properly. It needs + * to end with a terminating '\0' or '\n\0' */ + if(len >= (maxlen - (addnl ? 2 : 1))) { + len = maxlen - 5; + buf[len++] = '.'; + buf[len++] = '.'; + buf[len++] = '.'; + buf[len++] = '\n'; + } + else if(addnl) + buf[len++] = '\n'; + buf[len] = '\0'; + return len; +} + +void Curl_debug(struct Curl_easy *data, curl_infotype type, + const char *ptr, size_t size) +{ + if(data->set.verbose) { + static const char s_infotype[CURLINFO_END][3] = { + "* ", "< ", "> ", "{ ", "} ", "{ ", "} " }; + char buf[TRC_LINE_MAX]; + size_t len; + if(data->set.fdebug) { + struct Curl_mapi_guard guard; + if(CURL_TRC_IDS(data) && (size < TRC_LINE_MAX)) { + len = trc_print_ids(data, buf, TRC_LINE_MAX); + len += curl_msnprintf(buf + len, TRC_LINE_MAX - len, "%.*s", + (int)size, ptr); + len = trc_end_buf(buf, len, TRC_LINE_MAX, FALSE); + CURL_CBAPI_START(&guard, data, easy_fdebug); + (void)(*data->set.fdebug)(data, type, buf, len, data->set.debugdata); + CURL_CBAPI_END(&guard); + } + else { + CURL_CBAPI_START(&guard, data, easy_fdebug); + (void)(*data->set.fdebug)(data, type, CURL_UNCONST(ptr), + size, data->set.debugdata); + CURL_CBAPI_END(&guard); + } + } + else { + switch(type) { + case CURLINFO_TEXT: + case CURLINFO_HEADER_OUT: + case CURLINFO_HEADER_IN: +#ifndef CURL_DISABLE_VERBOSE_STRINGS + if(CURL_TRC_IDS(data)) { + len = trc_print_ids(data, buf, TRC_LINE_MAX); + fwrite(buf, len, 1, data->set.err); + } +#endif + fwrite(s_infotype[type], 2, 1, data->set.err); + fwrite(ptr, size, 1, data->set.err); + break; + default: /* nada */ + break; + } + } + } +} + +/* Curl_failf() is for messages stating why we failed. + * The message SHALL NOT include any LF or CR. + */ +void Curl_failf(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(data->set.verbose || data->set.errorbuffer) { + va_list ap; + size_t len; + char error[CURL_ERROR_SIZE + 2]; + va_start(ap, fmt); + len = curl_mvsnprintf(error, CURL_ERROR_SIZE, fmt, ap); + + if(data->set.errorbuffer && !data->state.errorbuf) { + curlx_strcopy(data->set.errorbuffer, CURL_ERROR_SIZE, error, len); + data->state.errorbuf = TRUE; /* wrote error string */ + } + error[len++] = '\n'; + error[len] = '\0'; + trc_write(data, CURLINFO_TEXT, error, len); + va_end(ap); + } +} + +void Curl_reset_fail(struct Curl_easy *data) +{ + if(data->set.errorbuffer) + data->set.errorbuffer[0] = 0; + data->state.errorbuf = FALSE; +} + +#ifdef CURLVERBOSE +struct curl_trc_feat Curl_trc_feat_multi = { + "MULTI", + CURL_LOG_LVL_NONE, +}; +struct curl_trc_feat Curl_trc_feat_read = { + "READ", + CURL_LOG_LVL_NONE, +}; +struct curl_trc_feat Curl_trc_feat_write = { + "WRITE", + CURL_LOG_LVL_NONE, +}; +struct curl_trc_feat Curl_trc_feat_dns = { + "DNS", + CURL_LOG_LVL_NONE, +}; +#ifndef CURL_DISABLE_DOH +struct curl_trc_feat Curl_trc_feat_doh = { + "DoH", + CURL_LOG_LVL_NONE, +}; +#endif +struct curl_trc_feat Curl_trc_feat_timer = { + "TIMER", + CURL_LOG_LVL_NONE, +}; +#ifdef USE_THREADS +struct curl_trc_feat Curl_trc_feat_threads = { + "THREADS", + CURL_LOG_LVL_NONE, +}; +#endif +#endif + +#ifndef CURL_DISABLE_VERBOSE_STRINGS + +static void trc_infof(struct Curl_easy *data, + struct curl_trc_feat *feat, + const char *opt_id, int opt_id_idx, + const char * const fmt, va_list ap) CURL_PRINTF(5, 0); + +static void trc_infof(struct Curl_easy *data, + struct curl_trc_feat *feat, + const char *opt_id, int opt_id_idx, + const char * const fmt, va_list ap) +{ + size_t len = 0; + char buf[TRC_LINE_MAX]; + + if(CURL_TRC_IDS(data)) + len += trc_print_ids(data, buf + len, TRC_LINE_MAX - len); + if(feat) + len += curl_msnprintf(buf + len, TRC_LINE_MAX - len, "[%s] ", feat->name); + if(opt_id) { + if(opt_id_idx > 0) + len += curl_msnprintf(buf + len, TRC_LINE_MAX - len, "[%s-%d] ", + opt_id, opt_id_idx); + else + len += curl_msnprintf(buf + len, TRC_LINE_MAX - len, "[%s] ", opt_id); + } + len += curl_mvsnprintf(buf + len, TRC_LINE_MAX - len, fmt, ap); + len = trc_end_buf(buf, len, TRC_LINE_MAX, TRUE); + trc_write(data, CURLINFO_TEXT, buf, len); +} + +void Curl_infof(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_is_verbose(data)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, data->state.feat, NULL, 0, fmt, ap); + va_end(ap); + } +} + +void Curl_trc_cf_infof(struct Curl_easy *data, const struct Curl_cfilter *cf, + const char *fmt, ...) +{ + DEBUGASSERT(cf); + if(Curl_trc_cf_is_verbose(cf, data)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, data->state.feat, cf->cft->name, cf->sockindex, fmt, ap); + va_end(ap); + } +} + +void Curl_trc_feat_infof(struct Curl_easy *data, + struct curl_trc_feat *feat, + const char *fmt, ...) +{ + DEBUGASSERT(feat); + if(Curl_trc_ft_is_verbose(data, feat)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, feat, NULL, 0, fmt, ap); + va_end(ap); + } +} + +static const char * const Curl_trc_timer_names[] = { + "100_TIMEOUT", + "ASYNC_NAME", + "CONNECTTIMEOUT", + "HAPPY_EYEBALLS", + "MULTI_PENDING", + "SPEEDCHECK", + "TIMEOUT", + "TOOFAST", + "QUIC", + "FTP_ACCEPT", + "ALPN_EYEBALLS", + "SHUTDOWN", +}; + +static const char *trc_timer_name(int tid) +{ + if((tid >= 0) && ((size_t)tid < CURL_ARRAYSIZE(Curl_trc_timer_names))) + return Curl_trc_timer_names[(size_t)tid]; + return "TIMER-???"; +} + +void Curl_trc_timer(struct Curl_easy *data, int tid, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_timer)) { + const char *tname = trc_timer_name(tid); + va_list ap; + va_start(ap, fmt); + trc_infof(data, &Curl_trc_feat_timer, tname, 0, fmt, ap); + va_end(ap); + } +} + +void Curl_trc_easy_timers(struct Curl_easy *data) +{ + if(CURL_TRC_TIMER_is_verbose(data) && data->multi) { + if(data->state.timeouts.first < EXPIRE_LAST) { + struct expire_timers *timeouts = &data->state.timeouts; + timediff_t base_us = + Curl_timeouts_offset_us(&data->multi->timeouts, Curl_pgrs_now(data)); + uint8_t id = data->state.timeouts.first; + for(; id < EXPIRE_LAST; id = timeouts->next[id]) { + CURL_TRC_TIMER(data, id, "expires in %" FMT_TIMEDIFF_T "us", + timeouts->offset_us[id] - base_us); + } + } + } +} + +static const char * const Curl_trc_mstate_names[] = { + "INIT", + "PENDING", + "SETUP", + "CONNECT", + "CONNECTING", + "PROTOCONNECT", + "PROTOCONNECTING", + "DO", + "DOING", + "DOING_MORE", + "DID", + "PERFORMING", + "RATELIMITING", + "DONE", + "COMPLETED", + "MSGSENT", +}; + +const char *Curl_trc_mstate_name(int state) +{ + if((state >= 0) && ((size_t)state < CURL_ARRAYSIZE(Curl_trc_mstate_names))) + return Curl_trc_mstate_names[(size_t)state]; + return "?"; +} + +void Curl_trc_multi(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_multi)) { + const char *sname = (data->id >= 0) ? + Curl_trc_mstate_name(data->mstate) : NULL; + va_list ap; + va_start(ap, fmt); + trc_infof(data, &Curl_trc_feat_multi, sname, 0, fmt, ap); + va_end(ap); + } +} + +void Curl_trc_read(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_read)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, &Curl_trc_feat_read, NULL, 0, fmt, ap); + va_end(ap); + } +} + +void Curl_trc_write(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_write)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, &Curl_trc_feat_write, NULL, 0, fmt, ap); + va_end(ap); + } +} + +void Curl_trc_dns(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_dns)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, &Curl_trc_feat_dns, NULL, 0, fmt, ap); + va_end(ap); + } +} + +#ifndef CURL_DISABLE_FTP +struct curl_trc_feat Curl_trc_feat_ftp = { + "FTP", + CURL_LOG_LVL_NONE, +}; + +void Curl_trc_ftp(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_ftp)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, &Curl_trc_feat_ftp, NULL, 0, fmt, ap); + va_end(ap); + } +} +#endif /* !CURL_DISABLE_FTP */ + +#ifndef CURL_DISABLE_SMTP +struct curl_trc_feat Curl_trc_feat_smtp = { + "SMTP", + CURL_LOG_LVL_NONE, +}; + +void Curl_trc_smtp(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_smtp)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, &Curl_trc_feat_smtp, NULL, 0, fmt, ap); + va_end(ap); + } +} +#endif /* !CURL_DISABLE_SMTP */ + +#ifdef USE_SSL +struct curl_trc_feat Curl_trc_feat_ssls = { + "SSLS", + CURL_LOG_LVL_NONE, +}; + +void Curl_trc_ssls(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_ssls)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, &Curl_trc_feat_ssls, NULL, 0, fmt, ap); + va_end(ap); + } +} +#endif /* USE_SSL */ + +#ifdef USE_SSH +struct curl_trc_feat Curl_trc_feat_ssh = { + "SSH", + CURL_LOG_LVL_NONE, +}; + +void Curl_trc_ssh(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_ssh)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, &Curl_trc_feat_ssh, NULL, 0, fmt, ap); + va_end(ap); + } +} +#endif /* USE_SSH */ + +#if !defined(CURL_DISABLE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP) +struct curl_trc_feat Curl_trc_feat_ws = { + "WS", + CURL_LOG_LVL_NONE, +}; + +void Curl_trc_ws(struct Curl_easy *data, const char *fmt, ...) +{ + DEBUGASSERT(!strchr(fmt, '\n')); + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_ws)) { + va_list ap; + va_start(ap, fmt); + trc_infof(data, &Curl_trc_feat_ws, NULL, 0, fmt, ap); + va_end(ap); + } +} +#endif /* !CURL_DISABLE_WEBSOCKETS && !CURL_DISABLE_HTTP */ + +#define TRC_CT_NONE 0 +#define TRC_CT_PROTOCOL (1 << 0) +#define TRC_CT_NETWORK (1 << 1) +#define TRC_CT_PROXY (1 << 2) +#define TRC_CT_INTERNALS (1 << 3) + +struct trc_feat_def { + struct curl_trc_feat *feat; + unsigned int category; +}; + +static struct trc_feat_def trc_feats[] = { + { &Curl_trc_feat_ids, TRC_CT_INTERNALS }, + { &Curl_trc_feat_multi, TRC_CT_NETWORK }, + { &Curl_trc_feat_read, TRC_CT_NONE }, + { &Curl_trc_feat_write, TRC_CT_NONE }, + { &Curl_trc_feat_dns, TRC_CT_NETWORK }, +#ifndef CURL_DISABLE_DOH + { &Curl_trc_feat_doh, TRC_CT_NETWORK }, +#endif + { &Curl_trc_feat_timer, TRC_CT_NETWORK }, +#ifdef USE_THREADS + { &Curl_trc_feat_threads, TRC_CT_NONE }, +#endif +#ifndef CURL_DISABLE_FTP + { &Curl_trc_feat_ftp, TRC_CT_PROTOCOL }, +#endif +#ifndef CURL_DISABLE_SMTP + { &Curl_trc_feat_smtp, TRC_CT_PROTOCOL }, +#endif +#ifdef USE_SSL + { &Curl_trc_feat_ssls, TRC_CT_NETWORK }, +#endif +#ifdef USE_SSH + { &Curl_trc_feat_ssh, TRC_CT_PROTOCOL }, +#endif +#if !defined(CURL_DISABLE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP) + { &Curl_trc_feat_ws, TRC_CT_PROTOCOL }, +#endif +}; + +struct trc_cft_def { + struct Curl_cftype *cft; + unsigned int category; +}; + +static struct trc_cft_def trc_cfts[] = { + { &Curl_cft_dns, TRC_CT_NETWORK }, + { &Curl_cft_tcp, TRC_CT_NETWORK }, + { &Curl_cft_udp, TRC_CT_NETWORK }, + { &Curl_cft_unix, TRC_CT_NETWORK }, + { &Curl_cft_tcp_accept, TRC_CT_NETWORK }, + { &Curl_cft_ip_happy, TRC_CT_NETWORK }, +#ifndef CURL_DISABLE_WEBSOCKETS + { &Curl_cft_recvbuf, TRC_CT_PROTOCOL }, +#endif + { &Curl_cft_setup, TRC_CT_PROTOCOL }, +#if !defined(CURL_DISABLE_HTTP) && defined(USE_NGHTTP2) + { &Curl_cft_nghttp2, TRC_CT_PROTOCOL }, +#endif +#ifdef USE_SSL + { &Curl_cft_ssl, TRC_CT_NETWORK }, +#ifndef CURL_DISABLE_PROXY + { &Curl_cft_ssl_proxy, TRC_CT_PROXY }, +#endif +#endif +#ifndef CURL_DISABLE_PROXY +#ifndef CURL_DISABLE_HTTP + { &Curl_cft_h1_proxy, TRC_CT_PROXY }, +#ifdef USE_NGHTTP2 + { &Curl_cft_h2_proxy, TRC_CT_PROXY }, +#endif +#if defined(USE_PROXY_HTTP3) && defined(USE_NGHTTP3) + { &Curl_cft_h3_proxy, TRC_CT_PROXY }, +#endif + { &Curl_cft_http_proxy, TRC_CT_PROXY }, +#endif /* !CURL_DISABLE_HTTP */ + { &Curl_cft_haproxy, TRC_CT_PROXY }, + { &Curl_cft_socks_proxy, TRC_CT_PROXY }, +#endif /* !CURL_DISABLE_PROXY */ +#if !defined(CURL_DISABLE_HTTP) && defined(USE_HTTP3) + { &Curl_cft_http3, TRC_CT_PROTOCOL }, +#endif +#ifndef CURL_DISABLE_HTTP + { &Curl_cft_http_connect, TRC_CT_PROTOCOL }, +#endif +}; + +static void trc_apply_level_by_name(struct Curl_str *token, int lvl) +{ + size_t i; + + for(i = 0; i < CURL_ARRAYSIZE(trc_cfts); ++i) { + if(curlx_str_casecompare(token, trc_cfts[i].cft->name)) { + trc_cfts[i].cft->log_level = lvl; + break; + } + } + for(i = 0; i < CURL_ARRAYSIZE(trc_feats); ++i) { + if(curlx_str_casecompare(token, trc_feats[i].feat->name)) { + trc_feats[i].feat->log_level = lvl; + break; + } + } +} + +static void trc_apply_level_by_category(unsigned int category, int lvl) +{ + size_t i; + + for(i = 0; i < CURL_ARRAYSIZE(trc_cfts); ++i) { + if(!category || (trc_cfts[i].category & category)) + trc_cfts[i].cft->log_level = lvl; + } + for(i = 0; i < CURL_ARRAYSIZE(trc_feats); ++i) { + if(!category || (trc_feats[i].category & category)) + trc_feats[i].feat->log_level = lvl; + } +} + +static CURLcode trc_opt(const char *config) +{ + struct Curl_str out; + while(!curlx_str_until(&config, &out, 32, ',')) { + int lvl = CURL_LOG_LVL_INFO; + const char *token = curlx_str(&out); + + if(*token == '-') { + lvl = CURL_LOG_LVL_NONE; + curlx_str_nudge(&out, 1); + } + else if(*token == '+') + curlx_str_nudge(&out, 1); + + if(curlx_str_casecompare(&out, "all")) + trc_apply_level_by_category(TRC_CT_NONE, lvl); + else if(curlx_str_casecompare(&out, "protocol")) + trc_apply_level_by_category(TRC_CT_PROTOCOL, lvl); + else if(curlx_str_casecompare(&out, "network")) + trc_apply_level_by_category(TRC_CT_NETWORK, lvl); + else if(curlx_str_casecompare(&out, "proxy")) + trc_apply_level_by_category(TRC_CT_PROXY, lvl); + else + trc_apply_level_by_name(&out, lvl); + + if(curlx_str_single(&config, ',')) + break; + } + return CURLE_OK; +} + +CURLcode Curl_trc_opt(const char *config) +{ + CURLcode result = config ? trc_opt(config) : CURLE_OK; +#ifdef DEBUGBUILD + /* CURL_DEBUG can override anything */ + if(!result) { + const char *dbg_config = getenv("CURL_DEBUG"); + if(dbg_config) + result = trc_opt(dbg_config); + } +#endif /* DEBUGBUILD */ + return result; +} + +CURLcode Curl_trc_init(void) +{ +#ifdef DEBUGBUILD + return Curl_trc_opt(NULL); +#else + return CURLE_OK; +#endif +} + +#else /* CURL_DISABLE_VERBOSE_STRINGS */ + +CURLcode Curl_trc_init(void) +{ + return CURLE_OK; +} + +void Curl_infof(struct Curl_easy *data, const char *fmt, ...) +{ + (void)data; + (void)fmt; +} + +void Curl_trc_cf_infof(struct Curl_easy *data, const struct Curl_cfilter *cf, + const char *fmt, ...) +{ + (void)data; + (void)cf; + (void)fmt; +} + +void Curl_trc_multi(struct Curl_easy *data, const char *fmt, ...) +{ + (void)data; + (void)fmt; +} + +void Curl_trc_write(struct Curl_easy *data, const char *fmt, ...) +{ + (void)data; + (void)fmt; +} + +void Curl_trc_dns(struct Curl_easy *data, const char *fmt, ...) +{ + (void)data; + (void)fmt; +} + +void Curl_trc_timer(struct Curl_easy *data, int tid, const char *fmt, ...) +{ + (void)data; + (void)tid; + (void)fmt; +} + +void Curl_trc_read(struct Curl_easy *data, const char *fmt, ...) +{ + (void)data; + (void)fmt; +} + +#ifndef CURL_DISABLE_FTP +void Curl_trc_ftp(struct Curl_easy *data, const char *fmt, ...) +{ + (void)data; + (void)fmt; +} +#endif +#ifndef CURL_DISABLE_SMTP +void Curl_trc_smtp(struct Curl_easy *data, const char *fmt, ...) +{ + (void)data; + (void)fmt; +} +#endif +#if !defined(CURL_DISABLE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP) +void Curl_trc_ws(struct Curl_easy *data, const char *fmt, ...) +{ + (void)data; + (void)fmt; +} +#endif +#ifdef USE_SSH +void Curl_trc_ssh(struct Curl_easy *data, const char *fmt, ...) +{ + (void)data; + (void)fmt; +} +#endif +#ifdef USE_SSL +void Curl_trc_ssls(struct Curl_easy *data, const char *fmt, ...) +{ + (void)data; + (void)fmt; +} +#endif + +#endif /* !CURL_DISABLE_VERBOSE_STRINGS */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_trc.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_trc.h new file mode 100644 index 0000000000..fc0e6dedcf --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curl_trc.h @@ -0,0 +1,347 @@ +#ifndef HEADER_CURL_TRC_H +#define HEADER_CURL_TRC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +struct Curl_easy; +struct Curl_cfilter; + +/** + * Init logging, return != 0 on failure. + */ +CURLcode Curl_trc_init(void); + +/** + * Configure tracing. May be called several times during global + * initialization. Later calls may not take effect. + * + * Configuration format supported: + * - comma-separated list of component names to enable logging on. + * E.g. 'http/2,ssl'. Unknown names are ignored. Names are compared + * case-insensitive. + * - component 'all' applies to all known log components + * - prefixing a component with '+' or '-' will en-/disable logging for + * that component + * Example: 'all,-ssl' would enable logging for all components but the + * SSL filters. + * + * @param config configuration string + */ +CURLcode Curl_trc_opt(const char *config); + +/* the function used to output verbose information */ +void Curl_debug(struct Curl_easy *data, curl_infotype type, + const char *ptr, size_t size); + +/** + * Output a failure message on registered callbacks for transfer. + */ +void Curl_failf(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); + +#define failf Curl_failf + +/* In case failf() reported into the errorbuf, clear it again. + * This is used to clear information from happy eyeballing attempts + * when ultimately a successful attempt was made. */ +void Curl_reset_fail(struct Curl_easy *data); + +#define CURL_LOG_LVL_NONE 0 +#define CURL_LOG_LVL_INFO 1 + +/** + * Output an informational message when transfer's verbose logging is enabled. + */ +void Curl_infof(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); + +/** + * Output an informational message when both transfer's verbose logging + * and connection filters verbose logging are enabled. + */ +void Curl_trc_cf_infof(struct Curl_easy *data, const struct Curl_cfilter *cf, + const char *fmt, ...) CURL_PRINTF(3, 4); +void Curl_trc_multi(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); +const char *Curl_trc_mstate_name(int state); +const char *Curl_trc_timer_name(int tid); +void Curl_trc_easy_timers(struct Curl_easy *data); + +void Curl_trc_write(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); +void Curl_trc_read(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); +void Curl_trc_dns(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); +void Curl_trc_timer(struct Curl_easy *data, int tid, + const char *fmt, ...) CURL_PRINTF(3, 4); + +struct curl_trc_feat { + const char *name; + int log_level; +}; + +void Curl_trc_feat_infof(struct Curl_easy *data, + struct curl_trc_feat *feat, + const char *fmt, ...) CURL_PRINTF(3, 4); + +#ifndef CURL_DISABLE_FTP +extern struct curl_trc_feat Curl_trc_feat_ftp; +void Curl_trc_ftp(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); +#endif +#ifndef CURL_DISABLE_SMTP +extern struct curl_trc_feat Curl_trc_feat_smtp; +void Curl_trc_smtp(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); +#endif +#ifdef USE_SSL +extern struct curl_trc_feat Curl_trc_feat_ssls; +void Curl_trc_ssls(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); +#endif +#ifdef USE_SSH +extern struct curl_trc_feat Curl_trc_feat_ssh; +void Curl_trc_ssh(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); +#endif +#if !defined(CURL_DISABLE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP) +extern struct curl_trc_feat Curl_trc_feat_ws; +void Curl_trc_ws(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); +#endif + +#define CURL_TRC_M_is_verbose(data) \ + Curl_trc_ft_is_verbose(data, &Curl_trc_feat_multi) +#define CURL_TRC_DNS_is_verbose(data) \ + Curl_trc_ft_is_verbose(data, &Curl_trc_feat_dns) +#define CURL_TRC_TIMER_is_verbose(data) \ + Curl_trc_ft_is_verbose(data, &Curl_trc_feat_timer) + +#if defined(CURL_HAVE_MACRO_VARARG) && !defined(CURL_DISABLE_VERBOSE_STRINGS) +#define infof(data, ...) \ + do { \ + if(Curl_trc_is_verbose(data)) \ + Curl_infof(data, __VA_ARGS__); \ + } while(0) +#define CURL_TRC_M(data, ...) \ + do { \ + if(CURL_TRC_M_is_verbose(data)) \ + Curl_trc_multi(data, __VA_ARGS__); \ + } while(0) +#define CURL_TRC_CF(data, cf, ...) \ + do { \ + if(Curl_trc_cf_is_verbose(cf, data)) \ + Curl_trc_cf_infof(data, cf, __VA_ARGS__); \ + } while(0) +#define CURL_TRC_WRITE(data, ...) \ + do { \ + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_write)) \ + Curl_trc_write(data, __VA_ARGS__); \ + } while(0) +#define CURL_TRC_READ(data, ...) \ + do { \ + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_read)) \ + Curl_trc_read(data, __VA_ARGS__); \ + } while(0) +#define CURL_TRC_DNS(data, ...) \ + do { \ + if(CURL_TRC_DNS_is_verbose(data)) \ + Curl_trc_dns(data, __VA_ARGS__); \ + } while(0) +#define CURL_TRC_TIMER(data, tid, ...) \ + do { \ + if(CURL_TRC_TIMER_is_verbose(data)) \ + Curl_trc_timer(data, tid, __VA_ARGS__); \ + } while(0) + +#ifndef CURL_DISABLE_FTP +#define CURL_TRC_FTP(data, ...) \ + do { \ + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_ftp)) \ + Curl_trc_ftp(data, __VA_ARGS__); \ + } while(0) +#endif /* !CURL_DISABLE_FTP */ +#ifndef CURL_DISABLE_SMTP +#define CURL_TRC_SMTP(data, ...) \ + do { \ + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_smtp)) \ + Curl_trc_smtp(data, __VA_ARGS__); \ + } while(0) +#endif /* !CURL_DISABLE_SMTP */ +#ifdef USE_SSL +#define CURL_TRC_SSLS(data, ...) \ + do { \ + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_ssls)) \ + Curl_trc_ssls(data, __VA_ARGS__); \ + } while(0) +#endif /* USE_SSL */ +#ifdef USE_SSH +#define CURL_TRC_SSH(data, ...) \ + do { \ + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_ssh)) \ + Curl_trc_ssh(data, __VA_ARGS__); \ + } while(0) +#endif /* USE_SSH */ +#if !defined(CURL_DISABLE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP) +#define CURL_TRC_WS(data, ...) \ + do { \ + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_ws)) \ + Curl_trc_ws(data, __VA_ARGS__); \ + } while(0) +#endif /* !CURL_DISABLE_WEBSOCKETS && !CURL_DISABLE_HTTP */ + +#elif defined(CURL_HAVE_MACRO_VARARG) && defined(CURL_DISABLE_VERBOSE_STRINGS) + +#define infof(data, ...) \ + do { \ + (void)(data); \ + } while(0) +#define CURL_TRC_M(data, ...) \ + do { \ + (void)(data); \ + } while(0) +#define CURL_TRC_CF(data, cf, ...) \ + do { \ + (void)(data); \ + (void)(cf); \ + } while(0) +#define CURL_TRC_WRITE(data, ...) \ + do { \ + (void)(data); \ + } while(0) +#define CURL_TRC_READ(data, ...) \ + do { \ + (void)(data); \ + } while(0) +#define CURL_TRC_DNS(data, ...) \ + do { \ + (void)(data); \ + } while(0) +#define CURL_TRC_TIMER(data, tid, ...) \ + do { \ + (void)(data); \ + (void)(tid); \ + } while(0) +#ifndef CURL_DISABLE_FTP +#define CURL_TRC_FTP(data, ...) \ + do { \ + (void)(data); \ + } while(0) +#endif /* !CURL_DISABLE_FTP */ +#ifndef CURL_DISABLE_SMTP +#define CURL_TRC_SMTP(data, ...) \ + do { \ + (void)(data); \ + } while(0) +#endif /* !CURL_DISABLE_SMTP */ +#ifdef USE_SSL +#define CURL_TRC_SSLS(data, ...) \ + do { \ + (void)(data); \ + } while(0) +#endif /* USE_SSL */ +#ifdef USE_SSH +#define CURL_TRC_SSH(data, ...) \ + do { \ + (void)(data); \ + } while(0) +#endif /* USE_SSH */ +#if !defined(CURL_DISABLE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP) +#define CURL_TRC_WS(data, ...) \ + do { \ + (void)(data); \ + } while(0) +#endif + +#else /* !CURL_HAVE_MACRO_VARARG */ + +#define infof Curl_infof +#define CURL_TRC_M Curl_trc_multi +#define CURL_TRC_CF Curl_trc_cf_infof +#define CURL_TRC_WRITE Curl_trc_write +#define CURL_TRC_READ Curl_trc_read +#define CURL_TRC_DNS Curl_trc_dns +#define CURL_TRC_TIMER Curl_trc_timer + +#ifndef CURL_DISABLE_FTP +#define CURL_TRC_FTP Curl_trc_ftp +#endif +#ifndef CURL_DISABLE_SMTP +#define CURL_TRC_SMTP Curl_trc_smtp +#endif +#ifdef USE_SSL +#define CURL_TRC_SSLS Curl_trc_ssls +#endif +#ifdef USE_SSH +#define CURL_TRC_SSH Curl_trc_ssh +#endif +#if !defined(CURL_DISABLE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP) +#define CURL_TRC_WS Curl_trc_ws +#endif + +#endif /* CURL_HAVE_MACRO_VARARG */ + +#ifdef CURLVERBOSE +extern struct curl_trc_feat Curl_trc_feat_multi; +extern struct curl_trc_feat Curl_trc_feat_read; +extern struct curl_trc_feat Curl_trc_feat_write; +extern struct curl_trc_feat Curl_trc_feat_dns; +#ifndef CURL_DISABLE_DOH +extern struct curl_trc_feat Curl_trc_feat_doh; +#endif +extern struct curl_trc_feat Curl_trc_feat_timer; +#ifdef USE_THREADS +extern struct curl_trc_feat Curl_trc_feat_threads; +#endif +#endif + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +/* informational messages enabled */ +#define Curl_trc_is_verbose(data) \ + ((data) && (data)->set.verbose && \ + (!(data)->state.feat || \ + ((data)->state.feat->log_level >= CURL_LOG_LVL_INFO))) +#define Curl_trc_cf_is_verbose(cf, data) \ + (Curl_trc_is_verbose(data) && \ + (cf) && (cf)->cft->log_level >= CURL_LOG_LVL_INFO) +#define Curl_trc_ft_is_verbose(data, ft) \ + (Curl_trc_is_verbose(data) && \ + (ft)->log_level >= CURL_LOG_LVL_INFO) +#define CURL_MSTATE_NAME(s) Curl_trc_mstate_name((int)(s)) +#define CURL_TRC_EASY_TIMERS(data) \ + do { \ + if(CURL_TRC_TIMER_is_verbose(data)) \ + Curl_trc_easy_timers(data); \ + } while(0) + +#else /* CURL_DISABLE_VERBOSE_STRINGS */ +/* All informational messages are not compiled in for size savings */ +#define Curl_trc_is_verbose(d) FALSE +#define Curl_trc_cf_is_verbose(x, y) FALSE +#define Curl_trc_ft_is_verbose(x, y) FALSE +#define CURL_MSTATE_NAME(x) ((void)(x), "-") +#define CURL_TRC_EASY_TIMERS(x) Curl_nop_stmt +#endif /* !CURL_DISABLE_VERBOSE_STRINGS */ + +#endif /* HEADER_CURL_TRC_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/base64.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/base64.c new file mode 100644 index 0000000000..519b045cfe --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/base64.c @@ -0,0 +1,267 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* Base64 encoding/decoding */ + +#include "curl_setup.h" + +#include "curlx/base64.h" + +/* ---- Base64 Encoding/Decoding Table --- */ +const char curlx_base64encdec[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +/* The Base 64 encoding with a URL and filename safe alphabet, RFC 4648 + section 5 */ +static const char base64url[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + +static const unsigned char decodetable[] = { + 62, 255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, + 255, 255, 255, 255, 255, 255, 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, + 255, 255, 255, 255, 255, 255, 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 +}; +/* + * curlx_base64_decode() + * + * Given a base64 null-terminated string at src, decode it and return a + * pointer in *outptr to a newly allocated memory area holding decoded data. + * Size of decoded data is returned in variable pointed by outlen. + * + * Returns CURLE_OK on success, otherwise specific error code. Function + * output shall not be considered valid unless CURLE_OK is returned. + * + * When decoded data length is 0, returns NULL in *outptr. + * + * @unittest: 1302 + */ +CURLcode curlx_base64_decode(const char *src, + uint8_t **outptr, size_t *outlen) +{ + size_t srclen = 0; + size_t padding = 0; + size_t i; + size_t numQuantums; + size_t fullQuantums; + size_t rawlen = 0; + unsigned char *pos; + unsigned char *newstr; + unsigned char lookup[256]; + + *outptr = NULL; + *outlen = 0; + srclen = strlen(src); + + /* Check the length of the input string is valid */ + if(!srclen || srclen % 4) + return CURLE_BAD_CONTENT_ENCODING; + + /* srclen is at least 4 here */ + while(src[srclen - 1 - padding] == '=') { + /* count padding characters */ + padding++; + /* A maximum of two = padding characters is allowed */ + if(padding > 2) + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Calculate the number of quantums */ + numQuantums = srclen / 4; + fullQuantums = numQuantums - (padding ? 1 : 0); + + /* Calculate the size of the decoded string */ + rawlen = (numQuantums * 3) - padding; + + /* Allocate our buffer including room for a null-terminator */ + newstr = curlx_malloc(rawlen + 1); + if(!newstr) + return CURLE_OUT_OF_MEMORY; + + pos = newstr; + + memset(lookup, 0xff, sizeof(lookup)); + memcpy(&lookup['+'], decodetable, sizeof(decodetable)); + + /* Decode the complete quantums first */ + for(i = 0; i < fullQuantums; i++) { + unsigned char val; + unsigned int x = 0; + int j; + + for(j = 0; j < 4; j++) { + val = lookup[(unsigned char)*src++]; + if(val == 0xff) /* bad symbol */ + goto bad; + x = (x << 6) | val; + } + pos[2] = x & 0xff; + pos[1] = (x >> 8) & 0xff; + pos[0] = (x >> 16) & 0xff; + pos += 3; + } + if(padding) { + /* this means either 8 or 16 bits output */ + unsigned char val; + unsigned int x = 0; + int j; + size_t padc = 0; + for(j = 0; j < 4; j++) { + if(*src == '=') { + x <<= 6; + src++; + if(++padc > padding) + /* this is a badly placed '=' symbol! */ + goto bad; + } + else { + val = lookup[(unsigned char)*src++]; + if(val == 0xff) /* bad symbol */ + goto bad; + x = (x << 6) | val; + } + } + if(padding == 1) + pos[1] = (x >> 8) & 0xff; + pos[0] = (x >> 16) & 0xff; + pos += 3 - padding; + } + + /* null-terminate */ + *pos = '\0'; + + /* Return the decoded data */ + *outptr = newstr; + *outlen = rawlen; + + return CURLE_OK; +bad: + curlx_free(newstr); + return CURLE_BAD_CONTENT_ENCODING; +} + +static CURLcode base64_encode(const char *table64, + uint8_t padbyte, + const uint8_t *inputbuff, size_t insize, + char **outptr, size_t *outlen) +{ + char *output; + char *base64data; + const unsigned char *in = (const unsigned char *)inputbuff; + + *outptr = NULL; + *outlen = 0; + + if(!insize) + return CURLE_OK; + + /* safety precaution */ + DEBUGASSERT(insize <= CURL_MAX_BASE64_INPUT); + if(insize > CURL_MAX_BASE64_INPUT) + return CURLE_TOO_LARGE; + + base64data = output = curlx_malloc(((insize + 2) / 3 * 4) + 1); + if(!output) + return CURLE_OUT_OF_MEMORY; + + while(insize >= 3) { + *output++ = table64[in[0] >> 2]; + *output++ = table64[((in[0] & 0x03) << 4) | (in[1] >> 4)]; + *output++ = table64[((in[1] & 0x0F) << 2) | ((in[2] & 0xC0) >> 6)]; + *output++ = table64[in[2] & 0x3F]; + insize -= 3; + in += 3; + } + if(insize) { + /* this is only one or two bytes now */ + *output++ = table64[in[0] >> 2]; + if(insize == 1) { + *output++ = table64[((in[0] & 0x03) << 4)]; + if(padbyte) { + *output++ = padbyte; + *output++ = padbyte; + } + } + else { + /* insize == 2 */ + *output++ = table64[((in[0] & 0x03) << 4) | ((in[1] & 0xF0) >> 4)]; + *output++ = table64[((in[1] & 0x0F) << 2)]; + if(padbyte) + *output++ = padbyte; + } + } + + /* null-terminate */ + *output = '\0'; + + /* Return the pointer to the new data (allocated memory) */ + *outptr = base64data; + + /* Return the length of the new data */ + *outlen = (size_t)(output - base64data); + + return CURLE_OK; +} + +/* + * curlx_base64_encode() + * + * Given a pointer to an input buffer and an input size, encode it and + * return a pointer in *outptr to a newly allocated memory area holding + * encoded data. Size of encoded data is returned in variable pointed by + * outlen. + * + * Returns CURLE_OK on success, otherwise specific error code. Function + * output shall not be considered valid unless CURLE_OK is returned. + * + * @unittest: 1302 + */ +CURLcode curlx_base64_encode(const uint8_t *inputbuff, size_t insize, + char **outptr, size_t *outlen) +{ + return base64_encode(curlx_base64encdec, '=', + inputbuff, insize, outptr, outlen); +} + +/* + * curlx_base64url_encode() + * + * Given a pointer to an input buffer and an input size, encode it and + * return a pointer in *outptr to a newly allocated memory area holding + * encoded data. Size of encoded data is returned in variable pointed by + * outlen. + * + * Input length of 0 indicates input buffer holds a null-terminated string. + * + * Returns CURLE_OK on success, otherwise specific error code. Function + * output shall not be considered valid unless CURLE_OK is returned. + * + * @unittest: 1302 + */ +CURLcode curlx_base64url_encode(const uint8_t *inputbuff, size_t insize, + char **outptr, size_t *outlen) +{ + return base64_encode(base64url, 0, inputbuff, insize, outptr, outlen); +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/base64.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/base64.h new file mode 100644 index 0000000000..2e77814822 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/base64.h @@ -0,0 +1,40 @@ +#ifndef HEADER_CURL_BASE64_H +#define HEADER_CURL_BASE64_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +CURLcode curlx_base64_encode(const uint8_t *inputbuff, size_t insize, + char **outptr, size_t *outlen); +CURLcode curlx_base64url_encode(const uint8_t *inputbuff, size_t insize, + char **outptr, size_t *outlen); +CURLcode curlx_base64_decode(const char *src, + uint8_t **outptr, size_t *outlen); + +extern const char curlx_base64encdec[]; + +/* maximum input length acceptable to base64 encode, here to catch and prevent + mistakes */ +#define CURL_MAX_BASE64_INPUT 16000000 + +#endif /* HEADER_CURL_BASE64_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/basename.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/basename.c new file mode 100644 index 0000000000..eda3d1195a --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/basename.c @@ -0,0 +1,72 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef HAVE_BASENAME + +#include "curlx/basename.h" + +/* (Quote from The Open Group Base Specifications Issue 6 IEEE Std 1003.1, 2004 + Edition) + + The basename() function shall take the pathname pointed to by path and + return a pointer to the final component of the pathname, deleting any + trailing '/' characters. + + If the string pointed to by path consists entirely of the '/' character, + basename() shall return a pointer to the string "/". If the string pointed + to by path is exactly "//", it is implementation-defined whether '/' or "//" + is returned. + + If path is a null pointer or points to an empty string, basename() shall + return a pointer to the string ".". + + The basename() function may modify the string pointed to by path, and may + return a pointer to static storage that may then be overwritten by a + subsequent call to basename(). + + The basename() function need not be reentrant. A function that is not + required to be reentrant is not required to be thread-safe. + */ +char *curlx_basename(char *path) +{ + /* Ignore all the details above for now and make a quick and simple + implementation here */ + char *s1; + char *s2; + + s1 = strrchr(path, '/'); + s2 = strrchr(path, '\\'); + + if(s1 && s2) + path = ((s1 > s2) ? s1 : s2) + 1; + else if(s1) + path = s1 + 1; + else if(s2) + path = s2 + 1; + + return path; +} + +#endif /* !HAVE_BASENAME */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/basename.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/basename.h new file mode 100644 index 0000000000..fb79fed805 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/basename.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURLX_BASENAME_H +#define HEADER_CURLX_BASENAME_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef HAVE_BASENAME +char *curlx_basename(char *path); +#else + +#ifdef HAVE_LIBGEN_H +#include <libgen.h> +#endif + +#define curlx_basename(x) basename(x) +#endif /* !HAVE_BASENAME */ + +#endif /* HEADER_CURLX_BASENAME_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/dynbuf.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/dynbuf.c new file mode 100644 index 0000000000..1e5ea5177d --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/dynbuf.c @@ -0,0 +1,292 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curlx/dynbuf.h" +#include "curl_printf.h" + +#define MIN_FIRST_ALLOC 32 + +#ifdef DEBUGBUILD +#define DYNINIT 0xbee51da /* random pattern */ +#endif + +/* + * Init a dynbuf struct. + */ +void curlx_dyn_init(struct dynbuf *s, size_t toobig) +{ + DEBUGASSERT(s); + DEBUGASSERT(toobig); + DEBUGASSERT(toobig <= MAX_DYNBUF_SIZE); /* catch crazy mistakes */ + s->bufr = NULL; + s->leng = 0; + s->allc = 0; + s->toobig = toobig; +#ifdef DEBUGBUILD + s->init = DYNINIT; +#endif +} + +/* + * free the buffer and re-init the necessary fields. It does not touch the + * 'init' field and thus this buffer can be reused to add data to again. + */ +void curlx_dyn_free(struct dynbuf *s) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + curlx_safefree(s->bufr); + s->leng = s->allc = 0; +} + +/* + * Store/append an chunk of memory to the dynbuf. + */ +static CURLcode dyn_nappend(struct dynbuf *s, + const unsigned char *mem, size_t len) +{ + size_t idx = s->leng; + size_t a = s->allc; + size_t fit = len + idx + 1; /* new string + old string + zero byte */ + + /* try to detect if there is rubbish in the struct */ + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(s->toobig); + DEBUGASSERT(idx < s->toobig); + DEBUGASSERT(!s->leng || s->bufr); + DEBUGASSERT(a <= s->toobig); + DEBUGASSERT(!len || mem); + + if(fit > s->toobig) { + curlx_dyn_free(s); + return CURLE_TOO_LARGE; + } + else if(!a) { + DEBUGASSERT(!idx); + /* first invoke */ + if(MIN_FIRST_ALLOC > s->toobig) + a = s->toobig; + else if(fit < MIN_FIRST_ALLOC) + a = MIN_FIRST_ALLOC; + else + a = fit; + } + else { + while(a < fit) + a *= 2; + if(a > s->toobig) + /* no point in allocating a larger buffer than this is allowed to use */ + a = s->toobig; + } + + if(a != s->allc) { + void *p = curlx_realloc(s->bufr, a); + if(!p) { + curlx_dyn_free(s); + return CURLE_OUT_OF_MEMORY; + } + s->bufr = p; + s->allc = a; + } + + if(len) + memcpy(&s->bufr[idx], mem, len); + s->leng = idx + len; + s->bufr[s->leng] = 0; + return CURLE_OK; +} + +/* + * Clears the string, keeps the allocation. This can also be called on a + * buffer that already was freed. + */ +void curlx_dyn_reset(struct dynbuf *s) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + if(s->leng) + s->bufr[0] = 0; + s->leng = 0; +} + +/* + * Specify the size of the tail to keep (number of bytes from the end of the + * buffer). The rest is dropped. + */ +CURLcode curlx_dyn_tail(struct dynbuf *s, size_t trail) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + if(trail > s->leng) + return CURLE_BAD_FUNCTION_ARGUMENT; + else if(trail == s->leng) + return CURLE_OK; + else if(!trail) { + curlx_dyn_reset(s); + } + else { + memmove(&s->bufr[0], &s->bufr[s->leng - trail], trail); + s->leng = trail; + s->bufr[s->leng] = 0; + } + return CURLE_OK; +} + +/* + * Appends a buffer with length. + */ +CURLcode curlx_dyn_addn(struct dynbuf *s, const void *mem, size_t len) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + return dyn_nappend(s, mem, len); +} + +/* + * Append a null-terminated string at the end. + */ +CURLcode curlx_dyn_add(struct dynbuf *s, const char *str) +{ + size_t n; + DEBUGASSERT(str); + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + n = strlen(str); + return dyn_nappend(s, (const unsigned char *)str, n); +} + +/* + * Append a string vprintf()-style + */ +CURLcode curlx_dyn_vaddf(struct dynbuf *s, const char *fmt, va_list ap) +{ +#ifdef BUILDING_LIBCURL + int rc; + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + DEBUGASSERT(fmt); + rc = curlx_dyn_vprintf(s, fmt, ap); + + if(!rc) + return CURLE_OK; + else if(rc == MERR_TOO_LARGE) + return CURLE_TOO_LARGE; + return CURLE_OUT_OF_MEMORY; +#else + char *str; + str = curl_mvaprintf(fmt, ap); /* this allocs a new string to append */ + + if(str) { + CURLcode result = dyn_nappend(s, (const unsigned char *)str, strlen(str)); + curl_free(str); + return result; + } + /* If we failed, we cleanup the whole buffer and return error */ + curlx_dyn_free(s); + return CURLE_OUT_OF_MEMORY; +#endif +} + +/* + * Append a string printf()-style + */ +CURLcode curlx_dyn_addf(struct dynbuf *s, const char *fmt, ...) +{ + CURLcode result; + va_list ap; + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + DEBUGASSERT(strcmp(fmt, "%s")); /* use curlx_dyn_add instead */ + va_start(ap, fmt); + result = curlx_dyn_vaddf(s, fmt, ap); + va_end(ap); + return result; +} + +/* + * Returns a pointer to the buffer. + */ +char *curlx_dyn_ptr(const struct dynbuf *s) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + return s->bufr; +} + +char *curlx_dyn_take(struct dynbuf *s, size_t *plen) +{ + char *ptr = s->bufr; + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + *plen = s->leng; + s->bufr = NULL; + s->leng = 0; + s->allc = 0; + return ptr; +} + +/* + * Returns an unsigned pointer to the buffer. + */ +unsigned char *curlx_dyn_uptr(const struct dynbuf *s) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + return (unsigned char *)s->bufr; +} + +/* + * Returns the length of the buffer. + */ +size_t curlx_dyn_len(const struct dynbuf *s) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + return s->leng; +} + +/* + * Set a new (smaller) length. + */ +CURLcode curlx_dyn_setlen(struct dynbuf *s, size_t set) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->init == DYNINIT); + DEBUGASSERT(!s->leng || s->bufr); + if(set > s->leng) + return CURLE_BAD_FUNCTION_ARGUMENT; + s->leng = set; + s->bufr[s->leng] = 0; + return CURLE_OK; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/dynbuf.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/dynbuf.h new file mode 100644 index 0000000000..0cf4a2c576 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/dynbuf.h @@ -0,0 +1,83 @@ +#ifndef HEADER_CURL_DYNBUF_H +#define HEADER_CURL_DYNBUF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +struct dynbuf { + char *bufr; /* point to a null-terminated allocated buffer */ + size_t leng; /* number of bytes *EXCLUDING* the null-terminator */ + size_t allc; /* size of the current allocation */ + size_t toobig; /* size limit for the buffer */ +#ifdef DEBUGBUILD + int init; /* detect API usage mistakes */ +#endif +}; + +void curlx_dyn_init(struct dynbuf *s, size_t toobig); +void curlx_dyn_free(struct dynbuf *s); +CURLcode curlx_dyn_addn(struct dynbuf *s, const void *mem, size_t len) + WARN_UNUSED_RESULT; +CURLcode curlx_dyn_add(struct dynbuf *s, const char *str) + WARN_UNUSED_RESULT; +CURLcode curlx_dyn_addf(struct dynbuf *s, const char *fmt, ...) + WARN_UNUSED_RESULT CURL_PRINTF(2, 3); +CURLcode curlx_dyn_vaddf(struct dynbuf *s, const char *fmt, va_list ap) + WARN_UNUSED_RESULT CURL_PRINTF(2, 0); +void curlx_dyn_reset(struct dynbuf *s); +CURLcode curlx_dyn_tail(struct dynbuf *s, size_t trail); +CURLcode curlx_dyn_setlen(struct dynbuf *s, size_t set); +char *curlx_dyn_ptr(const struct dynbuf *s); +unsigned char *curlx_dyn_uptr(const struct dynbuf *s); +size_t curlx_dyn_len(const struct dynbuf *s); + +/* returns 0 on success, -1 on error */ +/* The implementation of this function exists in mprintf.c */ +int curlx_dyn_vprintf(struct dynbuf *dyn, const char *format, va_list args); + +/* Take the buffer out of the dynbuf. Caller has ownership and + * dynbuf resets to initial state. */ +char *curlx_dyn_take(struct dynbuf *s, size_t *plen); + +/* Dynamic buffer max sizes */ +#define MAX_DYNBUF_SIZE (SIZE_MAX / 2) + +#define DYN_DOH_RESPONSE 3000 +#define DYN_DOH_CNAME 256 +#define DYN_PAUSE_BUFFER (64 * 1024 * 1024) +#define DYN_HAXPROXY 2048 +#define DYN_HTTP_REQUEST (1024 * 1024) +#define DYN_APRINTF 8000000 +#define DYN_RTSP_REQ_HEADER (64 * 1024) +#define DYN_TRAILERS (64 * 1024) +#define DYN_PROXY_CONNECT_HEADERS 16384 +#define DYN_QLOG_NAME 1024 +#define DYN_H1_TRAILER 4096 +#define DYN_PINGPPONG_CMD (64 * 1024) +#define DYN_IMAP_CMD (64 * 1024) +#define DYN_MQTT_RECV (64 * 1024) +#define DYN_MQTT_SEND 0xFFFFFFF +#define DYN_CRLFILE_SIZE (400 * 1024 * 1024) /* 400MiB */ +#define DYN_CERTFILE_SIZE (100 * 1024) /* 100KiB */ +#define DYN_KEYFILE_SIZE (100 * 1024) /* 100KiB */ +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/fopen.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/fopen.c new file mode 100644 index 0000000000..09264aeb10 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/fopen.c @@ -0,0 +1,539 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curlx/fopen.h" + +int curlx_fseek(void *stream, curl_off_t offset, int whence) +{ +#ifdef _WIN32 + return _fseeki64(stream, (__int64)offset, whence); +#elif defined(HAVE_FSEEKO) && defined(HAVE_DECL_FSEEKO) + return fseeko(stream, (off_t)offset, whence); +#else + if(offset > LONG_MAX) + return -1; + return fseek(stream, (long)offset, whence); +#endif +} + +#ifdef _WIN32 + +#include <share.h> /* for _SH_DENYNO */ + +#include "curlx/multibyte.h" +#include "curlx/timeval.h" + +#ifdef CURL_MEMDEBUG +/* + * Use system allocators to avoid infinite recursion when called by curl's + * memory tracker memdebug functions. + */ +#define CURLX_MALLOC(x) malloc(x) +#define CURLX_FREE(x) free(x) +#else +#define CURLX_MALLOC(x) curlx_malloc(x) +#define CURLX_FREE(x) curlx_free(x) +#endif + +#ifdef _UNICODE +static wchar_t *fn_convert_UTF8_to_wchar(const char *str_utf8) +{ + wchar_t *str_w = NULL; + + if(str_utf8) { + int str_w_len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, + str_utf8, -1, NULL, 0); + if(str_w_len > 0) { + str_w = CURLX_MALLOC(str_w_len * sizeof(wchar_t)); + if(str_w) { + if(MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, + str_utf8, -1, str_w, str_w_len) == 0) { + CURLX_FREE(str_w); + return NULL; + } + } + } + } + return str_w; +} +#endif + +/* declare GetFullPathNameW for mingw-w64 UWP builds targeting old Windows */ +#if defined(CURL_WINDOWS_UWP) && defined(__MINGW32__) && \ + (_WIN32_WINNT < _WIN32_WINNT_WIN10) +WINBASEAPI DWORD WINAPI GetFullPathNameW(LPCWSTR, DWORD, LPWSTR, LPWSTR *); +#endif + +/* Fix excessive paths (paths that exceed MAX_PATH length of 260). + * + * This is a helper function to fix paths that would exceed the MAX_PATH + * limitation check done by Windows APIs. It does so by normalizing the passed + * in filename or path 'in' to its full canonical path, and if that path is + * longer than MAX_PATH then setting 'out' to "\\?\" prefix + that full path. + * + * For example 'in' filename255chars in current directory C:\foo\bar is + * fixed as \\?\C:\foo\bar\filename255chars for 'out' which tells Windows + * it is ok to access that filename even though the actual full path is longer + * than 260 chars. + * + * For non-Unicode builds this function may fail sometimes because only the + * Unicode versions of some Windows API functions can access paths longer than + * MAX_PATH, for example GetFullPathNameW which is used in this function. When + * the full path is then converted from Unicode to multibyte that fails if any + * directories in the path contain characters not in the current codepage. + */ +static bool fix_excessive_path(const TCHAR *in, TCHAR **out) +{ + size_t needed, count; + const wchar_t *in_w; + wchar_t *fbuf = NULL; + + /* MS-documented "approximate" limit for the maximum path length */ + const size_t max_path_len = 32767; + +#ifndef _UNICODE + wchar_t *ibuf = NULL; + char *obuf = NULL; +#endif + + *out = NULL; + + /* skip paths already normalized */ + if(!_tcsncmp(in, _TEXT("\\\\?\\"), 4)) + goto cleanup; + +#ifndef _UNICODE + /* convert multibyte input to unicode */ + if(mbstowcs_s(&needed, NULL, 0, in, 0)) + goto cleanup; + if(!needed || needed >= max_path_len) + goto cleanup; + ibuf = CURLX_MALLOC(needed * sizeof(wchar_t)); + if(!ibuf) + goto cleanup; + if(mbstowcs_s(&count, ibuf, needed, in, needed - 1)) + goto cleanup; + if(count != needed) + goto cleanup; + in_w = ibuf; +#else + in_w = in; +#endif + + /* GetFullPathNameW returns the normalized full path in unicode. It converts + forward slashes to backslashes, processes .. to remove directory segments, + etc. Unlike GetFullPathNameA it can process paths that exceed MAX_PATH. */ + needed = (size_t)GetFullPathNameW(in_w, 0, NULL, NULL); + if(!needed || needed > max_path_len) + goto cleanup; + /* skip paths that are not excessive and do not need modification */ + if(needed <= MAX_PATH) + goto cleanup; + fbuf = CURLX_MALLOC(needed * sizeof(wchar_t)); + if(!fbuf) + goto cleanup; + count = (size_t)GetFullPathNameW(in_w, (DWORD)needed, fbuf, NULL); + if(!count || count >= needed) + goto cleanup; + + /* prepend \\?\ or \\?\UNC\ to the excessively long path. + * + * c:\longpath ---> \\?\c:\longpath + * \\.\c:\longpath ---> \\?\c:\longpath + * \\?\c:\longpath ---> \\?\c:\longpath (unchanged) + * \\server\c$\longpath ---> \\?\UNC\server\c$\longpath + * + * https://learn.microsoft.com/dotnet/standard/io/file-path-formats + */ + if(!wcsncmp(fbuf, L"\\\\?\\", 4)) + ; /* do nothing */ + else if(!wcsncmp(fbuf, L"\\\\.\\", 4)) + fbuf[2] = '?'; + else if(!wcsncmp(fbuf, L"\\\\.", 3) || !wcsncmp(fbuf, L"\\\\?", 3)) { + /* Unexpected, not UNC. The formatting doc does not allow this AFAICT. */ + goto cleanup; + } + else { + wchar_t *temp; + + if(!wcsncmp(fbuf, L"\\\\", 2)) { + /* "\\?\UNC\" + full path without "\\" + null */ + needed = 8 + (count - 2) + 1; + if(needed > max_path_len) + goto cleanup; + + temp = CURLX_MALLOC(needed * sizeof(wchar_t)); + if(!temp) + goto cleanup; + + if(wcsncpy_s(temp, needed, L"\\\\?\\UNC\\", 8)) { + CURLX_FREE(temp); + goto cleanup; + } + if(wcscpy_s(temp + 8, needed, fbuf + 2)) { + CURLX_FREE(temp); + goto cleanup; + } + } + else { + /* "\\?\" + full path + null */ + needed = 4 + count + 1; + if(needed > max_path_len) + goto cleanup; + + temp = CURLX_MALLOC(needed * sizeof(wchar_t)); + if(!temp) + goto cleanup; + + if(wcsncpy_s(temp, needed, L"\\\\?\\", 4)) { + CURLX_FREE(temp); + goto cleanup; + } + if(wcscpy_s(temp + 4, needed, fbuf)) { + CURLX_FREE(temp); + goto cleanup; + } + } + + CURLX_FREE(fbuf); + fbuf = temp; + } + +#ifndef _UNICODE + /* convert unicode full path to multibyte output */ + if(wcstombs_s(&needed, NULL, 0, fbuf, 0)) + goto cleanup; + if(!needed || needed >= max_path_len) + goto cleanup; + obuf = CURLX_MALLOC(needed); + if(!obuf) + goto cleanup; + if(wcstombs_s(&count, obuf, needed, fbuf, needed - 1)) + goto cleanup; + if(count != needed) + goto cleanup; + *out = obuf; + obuf = NULL; +#else + *out = fbuf; + fbuf = NULL; +#endif + +cleanup: + CURLX_FREE(fbuf); +#ifndef _UNICODE + CURLX_FREE(ibuf); + CURLX_FREE(obuf); +#endif + return !!*out; +} + +#ifndef CURL_WINDOWS_UWP +HANDLE curlx_CreateFile(const char *filename, + DWORD dwDesiredAccess, + DWORD dwShareMode, + LPSECURITY_ATTRIBUTES lpSecurityAttributes, + DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, + HANDLE hTemplateFile) +{ + HANDLE handle = INVALID_HANDLE_VALUE; + +#ifdef UNICODE + TCHAR *filename_t = curlx_convert_UTF8_to_wchar(filename); +#else + const TCHAR *filename_t = filename; +#endif + + if(filename_t) { + TCHAR *fixed = NULL; + const TCHAR *target = NULL; + + if(fix_excessive_path(filename_t, &fixed)) + target = fixed; + else + target = filename_t; + /* !checksrc! disable BANNEDFUNC 1 */ + handle = CreateFile(target, + dwDesiredAccess, + dwShareMode, + lpSecurityAttributes, + dwCreationDisposition, + dwFlagsAndAttributes, + hTemplateFile); + CURLX_FREE(fixed); +#ifdef UNICODE + curlx_free(filename_t); +#endif + } + + return handle; +} + +HANDLE curlx_FindFirstFile(const char *filename, + WIN32_FIND_DATA *find_data) +{ + HANDLE handle = INVALID_HANDLE_VALUE; + +#ifdef UNICODE + TCHAR *filename_t = curlx_convert_UTF8_to_wchar(filename); +#else + const TCHAR *filename_t = filename; +#endif + + if(filename_t) { + TCHAR *fixed = NULL; + const TCHAR *target; + + if(fix_excessive_path(filename_t, &fixed)) + target = fixed; + else + target = filename_t; + + handle = FindFirstFile(target, find_data); + CURLX_FREE(fixed); + +#ifdef UNICODE + curlx_free(filename_t); +#endif + } + + return handle; +} +#endif /* !CURL_WINDOWS_UWP */ + +int curlx_win32_open(const char *filename, int oflag, ...) +{ + int pmode = 0; + int res = -1; + TCHAR *fixed = NULL; + const TCHAR *target = NULL; + +#ifdef _UNICODE + wchar_t *filename_w = fn_convert_UTF8_to_wchar(filename); +#endif + + va_list param; + va_start(param, oflag); + if(oflag & O_CREAT) + pmode = va_arg(param, int); + va_end(param); + +#ifdef _UNICODE + if(filename_w) { + if(fix_excessive_path(filename_w, &fixed)) + target = fixed; + else + target = filename_w; + errno = _wsopen_s(&res, target, oflag, _SH_DENYNO, pmode); + CURLX_FREE(filename_w); + } + else + /* !checksrc! disable ERRNOVAR 1 */ + errno = EINVAL; +#else + if(fix_excessive_path(filename, &fixed)) + target = fixed; + else + target = filename; + errno = _sopen_s(&res, target, oflag, _SH_DENYNO, pmode); +#endif + + CURLX_FREE(fixed); + return res; +} + +FILE *curlx_win32_fopen(const char *filename, const char *mode) +{ + FILE *file = NULL; + TCHAR *fixed = NULL; + const TCHAR *target = NULL; + +#ifdef _UNICODE + wchar_t *filename_w = fn_convert_UTF8_to_wchar(filename); + wchar_t *mode_w = fn_convert_UTF8_to_wchar(mode); + if(filename_w && mode_w) { + if(fix_excessive_path(filename_w, &fixed)) + target = fixed; + else + target = filename_w; + file = _wfsopen(target, mode_w, _SH_DENYNO); + } + else + /* !checksrc! disable ERRNOVAR 1 */ + errno = EINVAL; + CURLX_FREE(filename_w); + CURLX_FREE(mode_w); +#else + if(fix_excessive_path(filename, &fixed)) + target = fixed; + else + target = filename; + file = _fsopen(target, mode, _SH_DENYNO); +#endif + + CURLX_FREE(fixed); + return file; +} + +#if defined(__MINGW32__) && (__MINGW64_VERSION_MAJOR < 5) +_CRTIMP errno_t __cdecl freopen_s(FILE **file, const char *filename, + const char *mode, FILE *stream); +#endif + +FILE *curlx_win32_freopen(const char *filename, const char *mode, FILE *fp) +{ + FILE *file = NULL; + TCHAR *fixed = NULL; + const TCHAR *target = NULL; + +#ifdef _UNICODE + wchar_t *filename_w = fn_convert_UTF8_to_wchar(filename); + wchar_t *mode_w = fn_convert_UTF8_to_wchar(mode); + if(filename_w && mode_w) { + if(fix_excessive_path(filename_w, &fixed)) + target = fixed; + else + target = filename_w; + errno = _wfreopen_s(&file, target, mode_w, fp); + } + else + /* !checksrc! disable ERRNOVAR 1 */ + errno = EINVAL; + CURLX_FREE(filename_w); + CURLX_FREE(mode_w); +#else + if(fix_excessive_path(filename, &fixed)) + target = fixed; + else + target = filename; + errno = freopen_s(&file, target, mode, fp); +#endif + + CURLX_FREE(fixed); + return file; +} + +int curlx_win32_stat(const char *path, curlx_struct_stat *buffer) +{ + int res = -1; + TCHAR *fixed = NULL; + const TCHAR *target = NULL; + +#ifdef _UNICODE + wchar_t *path_w = curlx_convert_UTF8_to_wchar(path); + if(path_w) { + if(fix_excessive_path(path_w, &fixed)) + target = fixed; + else + target = path_w; + res = _wstati64(target, buffer); + curlx_free(path_w); + } + else + /* !checksrc! disable ERRNOVAR 1 */ + errno = EINVAL; +#else + if(fix_excessive_path(path, &fixed)) + target = fixed; + else + target = path; + res = _stati64(target, buffer); +#endif + + CURLX_FREE(fixed); + return res; +} + +#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_COOKIES) || \ + !defined(CURL_DISABLE_ALTSVC) +/* rename() on Windows does not overwrite, so we cannot use it here. + MoveFileEx() does overwrite and is usually atomic but fails when there are + open handles to the file. */ +int curlx_win32_rename(const char *oldpath, const char *newpath) +{ + int res = -1; /* fail */ + +#ifdef UNICODE + TCHAR *tchar_oldpath = curlx_convert_UTF8_to_wchar(oldpath); + TCHAR *tchar_newpath = curlx_convert_UTF8_to_wchar(newpath); +#else + const TCHAR *tchar_oldpath = oldpath; + const TCHAR *tchar_newpath = newpath; +#endif + + if(tchar_oldpath && tchar_newpath) { + const int max_wait_ms = 1000; + struct curltime start; + + TCHAR *oldpath_fixed = NULL; + TCHAR *newpath_fixed = NULL; + const TCHAR *target_oldpath; + const TCHAR *target_newpath; + + if(fix_excessive_path(tchar_oldpath, &oldpath_fixed)) + target_oldpath = oldpath_fixed; + else + target_oldpath = tchar_oldpath; + + if(fix_excessive_path(tchar_newpath, &newpath_fixed)) + target_newpath = newpath_fixed; + else + target_newpath = tchar_newpath; + + start = curlx_now(); + + for(;;) { + timediff_t diff; + /* !checksrc! disable BANNEDFUNC 1 */ + if(MoveFileEx(target_oldpath, target_newpath, + MOVEFILE_REPLACE_EXISTING)) { + res = 0; /* success */ + break; + } + diff = curlx_timediff_ms(curlx_now(), start); + if(diff < 0 || diff > max_wait_ms) { + break; + } + Sleep(1); + } + + CURLX_FREE(oldpath_fixed); + CURLX_FREE(newpath_fixed); + } + +#ifdef UNICODE + curlx_free(tchar_oldpath); + curlx_free(tchar_newpath); +#endif + + return res; +} +#endif + +#undef CURLX_MALLOC +#undef CURLX_FREE + +#endif /* _WIN32 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/fopen.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/fopen.h new file mode 100644 index 0000000000..469d3c8813 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/fopen.h @@ -0,0 +1,89 @@ +#ifndef HEADER_CURLX_FOPEN_H +#define HEADER_CURLX_FOPEN_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curlx/multibyte.h" + +#ifdef HAVE_FCNTL_H +#include <fcntl.h> /* for open() and attributes */ +#endif + +int curlx_fseek(void *stream, curl_off_t offset, int whence); + +#ifdef _WIN32 +#include <sys/stat.h> /* for _fstati64(), struct _stati64 */ +#ifndef CURL_WINDOWS_UWP +HANDLE curlx_CreateFile(const char *filename, + DWORD dwDesiredAccess, + DWORD dwShareMode, + LPSECURITY_ATTRIBUTES lpSecurityAttributes, + DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, + HANDLE hTemplateFile); +HANDLE curlx_FindFirstFile(const char *filename, + WIN32_FIND_DATA *find_data); +#endif /* !CURL_WINDOWS_UWP */ +#define curlx_fstat _fstati64 +#define curlx_struct_stat struct _stati64 +FILE *curlx_win32_fopen(const char *filename, const char *mode); +FILE *curlx_win32_freopen(const char *filename, const char *mode, FILE *fp); +int curlx_win32_stat(const char *path, curlx_struct_stat *buffer); +int curlx_win32_open(const char *filename, int oflag, ...); +int curlx_win32_rename(const char *oldpath, const char *newpath); +#define CURLX_FOPEN_LOW curlx_win32_fopen +#define CURLX_FREOPEN_LOW curlx_win32_freopen +#define CURLX_FDOPEN_LOW _fdopen +#define curlx_stat curlx_win32_stat +#define curlx_open curlx_win32_open +#define curlx_close _close +#define curlx_rename curlx_win32_rename +#else +#define curlx_fstat fstat +#define curlx_struct_stat struct stat +#define CURLX_FOPEN_LOW fopen +#define CURLX_FREOPEN_LOW freopen +#define CURLX_FDOPEN_LOW fdopen +#define curlx_stat stat +#define curlx_open open +#define curlx_close close +#define curlx_rename rename +#endif + +#ifdef CURL_MEMDEBUG +#define curlx_fopen(file, mode) curl_dbg_fopen(file, mode, __LINE__, __FILE__) +#define curlx_freopen(file, mode, fh) \ + curl_dbg_freopen(file, mode, fh, __LINE__, __FILE__) +#define curlx_fdopen(file, mode) \ + curl_dbg_fdopen(file, mode, __LINE__, __FILE__) +#define curlx_fclose(file) curl_dbg_fclose(file, __LINE__, __FILE__) +#else +#define curlx_fopen CURLX_FOPEN_LOW +#define curlx_freopen CURLX_FREOPEN_LOW +#define curlx_fdopen CURLX_FDOPEN_LOW +#define curlx_fclose fclose +#endif + +#endif /* HEADER_CURLX_FOPEN_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/inet_ntop.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/inet_ntop.c new file mode 100644 index 0000000000..ed06314520 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/inet_ntop.c @@ -0,0 +1,199 @@ +/* + * Copyright (C) 1996-2022 Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM + * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL + * INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING + * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, + * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION + * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * SPDX-License-Identifier: ISC + */ +#include "curl_setup.h" + +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif + +#include "curlx/inet_ntop.h" +#include "curlx/snprintf.h" +#include "curlx/strcopy.h" + +#define IN6ADDRSZ 16 +/* #define INADDRSZ 4 */ +#define INT16SZ 2 + +/* + * If USE_IPV6 is disabled, we still want to parse IPv6 addresses, so make + * sure we have _some_ value for AF_INET6 without polluting our fake value + * everywhere. + */ +#if !defined(USE_IPV6) && !defined(AF_INET6) +#define AF_INET6 (AF_INET + 1) +#endif + +/* + * Format an IPv4 address, more or less like inet_ntop(). + * + * Returns CURLcode. + * Note: + * - uses no static variables + * - takes an unsigned char* not an in_addr as input + */ +static CURLcode inet_ntop4(const unsigned char *src, char *dst, size_t size) +{ + char tmp[sizeof("255.255.255.255")]; + size_t len; + + DEBUGASSERT(size >= 16); + + /* this snprintf() does not overflow the buffer. */ + SNPRINTF(tmp, sizeof(tmp), "%d.%d.%d.%d", + ((int)((unsigned char)src[0])) & 0xff, + ((int)((unsigned char)src[1])) & 0xff, + ((int)((unsigned char)src[2])) & 0xff, + ((int)((unsigned char)src[3])) & 0xff); + + len = strlen(tmp); + if(len == 0 || len >= size) + return CURLE_TOO_LARGE; + curlx_strcopy(dst, size, tmp, len); + return CURLE_OK; +} + +/* + * Convert IPv6 binary address into presentation (printable) format. + */ +static CURLcode inet_ntop6(const unsigned char *src, char *dst, size_t size) +{ + /* + * Note that int32_t and int16_t need only be "at least" large enough + * to contain a value of the specified size. On some systems, like + * Crays, there is no such thing as an integer variable with 16 bits. + * Keep this in mind if you think this function should have been coded + * to use pointer overlays. All the world's not a VAX. + */ + char tmp[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")]; + char *tp; + struct { + int base; + int len; + } best, cur; + unsigned int words[IN6ADDRSZ / INT16SZ]; + int i; + + /* Preprocess: + * Copy the input (bytewise) array into a wordwise array. + * Find the longest run of 0x00's in src[] for :: shorthanding. + */ + memset(words, '\0', sizeof(words)); + for(i = 0; i < IN6ADDRSZ; i++) + words[i / 2] |= ((unsigned int)src[i] << ((1 - (i % 2)) << 3)); + + best.base = -1; + cur.base = -1; + best.len = 0; + cur.len = 0; + + for(i = 0; i < (IN6ADDRSZ / INT16SZ); i++) { + if(words[i] == 0) { + if(cur.base == -1) { + cur.base = i; + cur.len = 1; + } + else + cur.len++; + } + else if(cur.base != -1) { + if(best.base == -1 || cur.len > best.len) + best = cur; + cur.base = -1; + } + } + if((cur.base != -1) && (best.base == -1 || cur.len > best.len)) + best = cur; + if(best.base != -1 && best.len < 2) + best.base = -1; + /* Format the result. */ + tp = tmp; + for(i = 0; i < (IN6ADDRSZ / INT16SZ); i++) { + /* Are we inside the best run of 0x00's? */ + if(best.base != -1 && i >= best.base && i < (best.base + best.len)) { + if(i == best.base) + *tp++ = ':'; + continue; + } + + /* Are we following an initial run of 0x00s or any real hex? + */ + if(i) + *tp++ = ':'; + + /* Is this address an encapsulated IPv4? + */ + if(i == 6 && best.base == 0 && + (best.len == 6 || (best.len == 5 && words[5] == 0xffff))) { + CURLcode result = inet_ntop4(src + 12, tp, sizeof(tmp) - (tp - tmp)); + if(result) + return result; + tp += strlen(tp); + break; + } + else { + /* Lower-case digits. Cannot use the set from mprintf.c since this + needs to work as a curlx function */ + static const unsigned char ldigits[] = "0123456789abcdef"; + + unsigned int w = words[i]; + /* output lowercase 16-bit hex number but ignore leading zeroes */ + if(w & 0xf000) + *tp++ = ldigits[(w & 0xf000) >> 12]; + if(w & 0xff00) + *tp++ = ldigits[(w & 0x0f00) >> 8]; + if(w & 0xfff0) + *tp++ = ldigits[(w & 0x00f0) >> 4]; + *tp++ = ldigits[(w & 0x000f)]; + } + } + + /* Was it a trailing run of 0x00's? + */ + if(best.base != -1 && (best.base + best.len) == (IN6ADDRSZ / INT16SZ)) + *tp++ = ':'; + + /* Check for overflow, copy, and we are done. */ + if((size_t)(tp - tmp) >= size) + return CURLE_TOO_LARGE; + curlx_strcopy(dst, size, tmp, tp - tmp); + return CURLE_OK; +} + +/* + * Convert a network format address to presentation format. + * + * Copies result to 'buf' and returns CURLcode. + */ +CURLcode curlx_inet_ntop(int af, const void *src, char *buf, size_t size) +{ + switch(af) { + case AF_INET: + return inet_ntop4((const unsigned char *)src, buf, size); + case AF_INET6: + return inet_ntop6((const unsigned char *)src, buf, size); + default: + return CURLE_UNSUPPORTED_PROTOCOL; + } +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/inet_ntop.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/inet_ntop.h new file mode 100644 index 0000000000..f0abeb80b7 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/inet_ntop.h @@ -0,0 +1,30 @@ +#ifndef HEADER_CURL_INET_NTOP_H +#define HEADER_CURL_INET_NTOP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +CURLcode curlx_inet_ntop(int af, const void *src, char *buf, size_t size); + +#endif /* HEADER_CURL_INET_NTOP_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/inet_pton.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/inet_pton.c new file mode 100644 index 0000000000..23e76725fe --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/inet_pton.c @@ -0,0 +1,213 @@ +/* This is from the BIND 4.9.4 release, modified to compile by itself */ + +/* Copyright (c) Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS + * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE + * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + * + * SPDX-License-Identifier: ISC + */ +#include "curl_setup.h" + +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif + +#include "curlx/inet_pton.h" +#include "curlx/strparse.h" + +#define IN6ADDRSZ 16 +#define INADDRSZ 4 +#define INT16SZ 2 + +/* + * If USE_IPV6 is disabled, we still want to parse IPv6 addresses, so make + * sure we have _some_ value for AF_INET6 without polluting our fake value + * everywhere. + */ +#if !defined(USE_IPV6) && !defined(AF_INET6) +#define AF_INET6 (AF_INET + 1) +#endif + +/* + * WARNING: Do not even consider trying to compile this on a system where + * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX. + */ + +/* int inet_pton4(src, dst) + * like inet_aton() but without all the hexadecimal and shorthand. + * return: + * 1 if `src' is a valid dotted quad, else 0. + * notice: + * does not touch `dst' unless it is returning 1. + * author: + * Paul Vixie, 1996. + */ +static int inet_pton4(const char *src, unsigned char *dst) +{ + int saw_digit, octets, ch; + unsigned char tmp[INADDRSZ], *tp; + + saw_digit = 0; + octets = 0; + tp = tmp; + *tp = 0; + while((ch = (unsigned char)*src++) != '\0') { + if(ISDIGIT(ch)) { + unsigned int val = (*tp * 10) + (ch - '0'); + + if(saw_digit && *tp == 0) + return 0; + if(val > 255) + return 0; + *tp = (unsigned char)val; + if(!saw_digit) { + if(++octets > 4) + return 0; + saw_digit = 1; + } + } + else if(ch == '.' && saw_digit) { + if(octets == 4) + return 0; + *++tp = 0; + saw_digit = 0; + } + else + return 0; + } + if(octets < 4) + return 0; + memcpy(dst, tmp, INADDRSZ); + return 1; +} + +/* int inet_pton6(src, dst) + * convert presentation level address to network order binary form. + * return: + * 1 if `src' is a valid [RFC1884 2.2] address, else 0. + * notice: + * (1) does not touch `dst' unless it is returning 1. + * (2) :: in a full address is silently ignored. + * credit: + * inspired by Mark Andrews. + * author: + * Paul Vixie, 1996. + */ +static int inet_pton6(const char *src, unsigned char *dst) +{ + unsigned char tmp[IN6ADDRSZ], *tp, *endp, *colonp; + const char *curtok; + int ch, saw_xdigit; + size_t val; + + memset((tp = tmp), 0, IN6ADDRSZ); + endp = tp + IN6ADDRSZ; + colonp = NULL; + /* Leading :: requires some special handling. */ + if(*src == ':') + if(*++src != ':') + return 0; + curtok = src; + saw_xdigit = 0; + val = 0; + while((ch = (unsigned char)*src++) != '\0') { + if(ISXDIGIT(ch)) { + val <<= 4; + val |= curlx_hexval(ch); + if(++saw_xdigit > 4) + return 0; + continue; + } + if(ch == ':') { + curtok = src; + if(!saw_xdigit) { + if(colonp) + return 0; + colonp = tp; + continue; + } + if(tp + INT16SZ > endp) + return 0; + *tp++ = (unsigned char)((val >> 8) & 0xff); + *tp++ = (unsigned char)(val & 0xff); + saw_xdigit = 0; + val = 0; + continue; + } + if(ch == '.' && ((tp + INADDRSZ) <= endp) && + inet_pton4(curtok, tp) > 0) { + tp += INADDRSZ; + saw_xdigit = 0; + break; /* '\0' was seen by inet_pton4(). */ + } + return 0; + } + if(saw_xdigit) { + if(tp + INT16SZ > endp) + return 0; + *tp++ = (unsigned char)((val >> 8) & 0xff); + *tp++ = (unsigned char)(val & 0xff); + } + if(colonp) { + /* + * Since some memmove()'s erroneously fail to handle + * overlapping regions, we do the shift by hand. + */ + const ssize_t n = tp - colonp; + ssize_t i; + + if(tp == endp) + return 0; + for(i = 1; i <= n; i++) { + *(endp - i) = *(colonp + n - i); + *(colonp + n - i) = 0; + } + tp = endp; + } + if(tp != endp) + return 0; + memcpy(dst, tmp, IN6ADDRSZ); + return 1; +} + +/* + * Convert from presentation format (which usually means ASCII printable) + * to network format (which is usually some kind of binary format). + * + * Return: + * 1 if the address was valid for the specified address family + * 0 if the address was not valid (`dst' is untouched in this case) + * -1 if some other error occurred (`dst' is untouched in this case, too) + * + * author: + * Paul Vixie, 1996. + */ +int curlx_inet_pton(int af, const char *src, void *dst) +{ + switch(af) { + case AF_INET: + return inet_pton4(src, (unsigned char *)dst); + case AF_INET6: + return inet_pton6(src, (unsigned char *)dst); + default: + return -1; + } + /* NOTREACHED */ +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/inet_pton.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/inet_pton.h new file mode 100644 index 0000000000..4e45e83285 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/inet_pton.h @@ -0,0 +1,30 @@ +#ifndef HEADER_CURL_INET_PTON_H +#define HEADER_CURL_INET_PTON_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +int curlx_inet_pton(int af, const char *src, void *dst); + +#endif /* HEADER_CURL_INET_PTON_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/multibyte.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/multibyte.c new file mode 100644 index 0000000000..4ee39d962a --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/multibyte.c @@ -0,0 +1,78 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(_WIN32) && defined(UNICODE) + +#include "curlx/multibyte.h" + +/* + * MultiByte conversions using Windows kernel32 library. + */ + +wchar_t *curlx_convert_UTF8_to_wchar(const char *str_utf8) +{ + wchar_t *str_w = NULL; + + if(str_utf8) { + int str_w_len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, + str_utf8, -1, NULL, 0); + if(str_w_len > 0) { + str_w = curlx_malloc(str_w_len * sizeof(wchar_t)); + if(str_w) { + if(MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, + str_utf8, -1, str_w, str_w_len) == 0) { + curlx_free(str_w); + return NULL; + } + } + } + } + + return str_w; +} + +char *curlx_convert_wchar_to_UTF8(const wchar_t *str_w) +{ + char *str_utf8 = NULL; + + if(str_w) { + int bytes = WideCharToMultiByte(CP_UTF8, 0, str_w, -1, + NULL, 0, NULL, NULL); + if(bytes > 0) { + str_utf8 = curlx_malloc(bytes); + if(str_utf8) { + if(WideCharToMultiByte(CP_UTF8, 0, str_w, -1, str_utf8, bytes, + NULL, NULL) == 0) { + curlx_free(str_utf8); + return NULL; + } + } + } + } + + return str_utf8; +} + +#endif /* _WIN32 && UNICODE */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/multibyte.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/multibyte.h new file mode 100644 index 0000000000..8863fb0249 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/multibyte.h @@ -0,0 +1,73 @@ +#ifndef HEADER_CURL_MULTIBYTE_H +#define HEADER_CURL_MULTIBYTE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef _WIN32 + +/* + * Macros curlx_convert_UTF8_to_tchar(), curlx_convert_tchar_to_UTF8() + * main purpose is to minimize the number of preprocessor conditional + * directives needed by code using these to differentiate Unicode from + * non-Unicode builds. + * + * In the case of a non-Unicode build the tchar strings are char strings that + * are duplicated via strdup and remain in whatever the passed in encoding is, + * which is assumed to be UTF-8 but may be other encoding. Therefore the + * significance of the conversion functions is primarily for Unicode builds. + */ + +#ifdef UNICODE + +/* MultiByte conversions using Windows kernel32 library. */ +wchar_t *curlx_convert_UTF8_to_wchar(const char *str_utf8); +char *curlx_convert_wchar_to_UTF8(const wchar_t *str_w); + +#define curlx_convert_UTF8_to_tchar(ptr) curlx_convert_UTF8_to_wchar(ptr) +#define curlx_convert_tchar_to_UTF8(ptr) curlx_convert_wchar_to_UTF8(ptr) + +typedef union { + unsigned short *tchar_ptr; + const unsigned short *const_tchar_ptr; + unsigned short *tbyte_ptr; + const unsigned short *const_tbyte_ptr; +} xcharp_u; + +#else /* !UNICODE */ + +#define curlx_convert_UTF8_to_tchar(ptr) curlx_strdup(ptr) +#define curlx_convert_tchar_to_UTF8(ptr) curlx_strdup(ptr) + +typedef union { + char *tchar_ptr; + const char *const_tchar_ptr; + unsigned char *tbyte_ptr; + const unsigned char *const_tbyte_ptr; +} xcharp_u; + +#endif /* UNICODE */ +#endif /* _WIN32 */ + +#endif /* HEADER_CURL_MULTIBYTE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/nonblock.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/nonblock.c new file mode 100644 index 0000000000..6f6458f2b3 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/nonblock.c @@ -0,0 +1,92 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif + +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include "curlx/nonblock.h" + +/* + * curlx_nonblock() set the given socket to either blocking or non-blocking + * mode based on the 'nonblock' boolean argument. This function is highly + * portable. + */ +int curlx_nonblock(curl_socket_t sockfd, /* operate on this */ + int nonblock /* TRUE or FALSE */) +{ +#ifdef HAVE_FCNTL_O_NONBLOCK + /* most recent Unix versions */ + int flags; + flags = sfcntl(sockfd, F_GETFL, 0); + if(flags < 0) + return -1; + /* Check if the current file status flags have already satisfied + * the request, if so, it is no need to call fcntl() to replicate it. + */ + if(!!(flags & O_NONBLOCK) == !!nonblock) + return 0; + if(nonblock) + flags |= O_NONBLOCK; + else + flags &= ~O_NONBLOCK; + return sfcntl(sockfd, F_SETFL, flags); + +#elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO) + + /* Amiga */ + long flags = nonblock ? 1L : 0L; + return IoctlSocket(sockfd, FIONBIO, (char *)&flags); + +#elif defined(HAVE_IOCTL_FIONBIO) + + /* older Unix versions */ + int flags = nonblock ? 1 : 0; + return ioctl(sockfd, FIONBIO, &flags); + +#elif defined(HAVE_IOCTLSOCKET_FIONBIO) + + /* Windows */ + unsigned long flags = nonblock ? 1UL : 0UL; + return ioctlsocket(sockfd, (long)FIONBIO, &flags); + +#elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK) + + /* Orbis OS */ + long b = nonblock ? 1L : 0L; + return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b)); + +#else +#error "no non-blocking method was found/used/set" +#endif +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/nonblock.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/nonblock.h new file mode 100644 index 0000000000..ee2cd286a7 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/nonblock.h @@ -0,0 +1,30 @@ +#ifndef HEADER_CURL_NONBLOCK_H +#define HEADER_CURL_NONBLOCK_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +int curlx_nonblock(curl_socket_t sockfd, /* operate on this */ + int nonblock /* TRUE or FALSE */); + +#endif /* HEADER_CURL_NONBLOCK_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/snprintf.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/snprintf.c new file mode 100644 index 0000000000..911c42e6ad --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/snprintf.c @@ -0,0 +1,49 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curlx/snprintf.h" + +#ifdef _WIN32 +#include <stdarg.h> + +/* Simplified wrapper for the Windows platform to use the correct symbol and + ensuring null-termination. Omit returning a length to keep it simple. */ +void curlx_win32_snprintf(char *buf, size_t maxlen, const char *fmt, ...) +{ + va_list ap; + if(!maxlen) + return; + va_start(ap, fmt); +#ifdef CURL_HAVE_DIAG +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-nonliteral" +#endif + /* !checksrc! disable BANNEDFUNC 1 */ + (void)vsnprintf(buf, maxlen, fmt, ap); +#ifdef CURL_HAVE_DIAG +#pragma GCC diagnostic pop +#endif + buf[maxlen - 1] = 0; + va_end(ap); +} +#endif /* _WIN32 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/snprintf.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/snprintf.h new file mode 100644 index 0000000000..d6260e4e39 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/snprintf.h @@ -0,0 +1,45 @@ +#ifndef HEADER_CURLX_SNPRINTF_H +#define HEADER_CURLX_SNPRINTF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* Raw snprintf() for curlx */ + +#ifdef _WIN32 +void curlx_win32_snprintf(char *buf, size_t maxlen, const char *fmt, ...) + CURL_PRINTF(3, 4); +#endif + +#ifdef WITHOUT_LIBCURL /* when built for the test servers */ +#ifdef _WIN32 +#define SNPRINTF curlx_win32_snprintf +#else +#define SNPRINTF snprintf +#endif +#else /* !WITHOUT_LIBCURL */ +#include <curl/mprintf.h> +#define SNPRINTF curl_msnprintf +#endif /* WITHOUT_LIBCURL */ +#endif /* HEADER_CURLX_SNPRINTF_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strcopy.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strcopy.c new file mode 100644 index 0000000000..3b80930a19 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strcopy.c @@ -0,0 +1,50 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curlx/strcopy.h" + +/* + * curlx_strcopy() is a replacement for strcpy. + * + * Provide the target buffer @dest and size of the target buffer @dsize, If + * the source string @src with its *string length* @slen fits in the target + * buffer it is copied there - including storing a null-terminator. + * + * If the target buffer is too small, the copy is not performed but if the + * target buffer has a non-zero size it gets a null-terminator stored. + */ +void curlx_strcopy(char *dest, /* destination buffer */ + size_t dsize, /* size of target buffer */ + const char *src, /* source string */ + size_t slen) /* length of source string to copy */ +{ + DEBUGASSERT(slen < dsize); + if(slen < dsize) { + memcpy(dest, src, slen); + dest[slen] = 0; + } + else if(dsize) + dest[0] = 0; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strcopy.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strcopy.h new file mode 100644 index 0000000000..d671149cb8 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strcopy.h @@ -0,0 +1,32 @@ +#ifndef HEADER_CURLX_STRCOPY_H +#define HEADER_CURLX_STRCOPY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +void curlx_strcopy(char *dest, + size_t dsize, /* size of target buffer */ + const char *src, + size_t slen); /* length of string to copy */ + +#endif /* HEADER_CURLX_STRCOPY_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strdup.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strdup.c new file mode 100644 index 0000000000..ebc58c2363 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strdup.c @@ -0,0 +1,123 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef _WIN32 +#include <wchar.h> +#endif + +#include "curlx/strdup.h" + +#ifdef _WIN32 +/*************************************************************************** + * + * curlx_wcsdup(source) + * + * Copies the 'source' wchar string to a newly allocated buffer (that is + * returned). Used by macro curlx_tcsdup(). + * + * Returns the new pointer or NULL on failure. + * + ***************************************************************************/ +wchar_t *curlx_wcsdup(const wchar_t *src) +{ + size_t length = wcslen(src); + + if(length > (SIZE_MAX / sizeof(wchar_t)) - 1) + return (wchar_t *)NULL; /* integer overflow */ + + return (wchar_t *)curlx_memdup(src, (length + 1) * sizeof(wchar_t)); +} +#endif + +/*************************************************************************** + * + * curlx_memdup(source, length) + * + * Copies the 'source' data to a newly allocated buffer (that is + * returned). Copies 'length' bytes. + * + * Returns the new pointer or NULL on failure. + * + ***************************************************************************/ +void *curlx_memdup(const void *src, size_t length) +{ + void *buffer = curlx_malloc(length); + if(!buffer) + return NULL; /* fail */ + + memcpy(buffer, src, length); + + return buffer; +} + +/*************************************************************************** + * + * curlx_memdup0(source, length) + * + * Copies the 'source' string to a newly allocated buffer (that is returned). + * Copies 'length' bytes then adds a null-terminator. + * + * Returns the new pointer or NULL on failure. + * + ***************************************************************************/ +void *curlx_memdup0(const char *src, size_t length) +{ + char *buf = (length < SIZE_MAX) ? curlx_malloc(length + 1) : NULL; + if(!buf) + return NULL; + if(length) { + DEBUGASSERT(src); /* must never be NULL */ + memcpy(buf, src, length); + } + buf[length] = 0; + return buf; +} + +#ifdef USE_CURLX_MEMZERO +static void *(* const volatile p_curlx_memset)(void *buf, int val, + size_t size) = memset; + +/* Local fallback in case there is no system function to securely zero a memory + buffer. */ +void curlx_memzero_low(void *buf, size_t size) +{ + if(buf) + p_curlx_memset(buf, 0, size); +} +#endif + +/* Fill 'buf' with zeroes. */ +void curlx_memzero(void *buf, size_t size) +{ + if(buf) + curlx_memzero_low(buf, size); +} + +/* Fill 'buf' with zeroes, where 'buf' is null-terminated. */ +void curlx_strzero(void *buf) +{ + if(buf) + curlx_memzero_low(buf, strlen(buf)); +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strdup.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strdup.h new file mode 100644 index 0000000000..0c4b14161e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strdup.h @@ -0,0 +1,33 @@ +#ifndef HEADER_CURLX_STRDUP_H +#define HEADER_CURLX_STRDUP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef _WIN32 +wchar_t *curlx_wcsdup(const wchar_t *src); /* for curlx_tcsdup() */ +#endif +void *curlx_memdup(const void *src, size_t length); +void *curlx_memdup0(const char *src, size_t length); +#endif /* HEADER_CURLX_STRDUP_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strerr.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strerr.c new file mode 100644 index 0000000000..8e906cc6bd --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strerr.c @@ -0,0 +1,329 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_STRERROR_R +# if (!defined(HAVE_POSIX_STRERROR_R) && \ + !defined(HAVE_GLIBC_STRERROR_R)) || \ + (defined(HAVE_POSIX_STRERROR_R) && defined(HAVE_GLIBC_STRERROR_R)) +# error "strerror_r MUST be either POSIX, glibc style" +# endif +#endif + +#include "curlx/winapi.h" +#include "curlx/snprintf.h" +#include "curlx/strerr.h" +#include "curlx/strcopy.h" + +#ifdef USE_WINSOCK +/* This is a helper function for curlx_strerror that converts Winsock error + * codes (WSAGetLastError) to error messages. + * Returns NULL if no error message was found for error code. + */ +static const char *get_winsock_error(int err, char *buf, size_t len) +{ + VERBOSE(const char *p); + + if(!len) + return NULL; + + *buf = '\0'; + +#ifndef CURLVERBOSE + (void)err; + return NULL; +#else + switch(err) { + case WSAEINTR: + p = "Call interrupted"; + break; + case WSAEBADF: + p = "Bad file"; + break; + case WSAEACCES: + p = "Bad access"; + break; + case WSAEFAULT: + p = "Bad argument"; + break; + case WSAEINVAL: + p = "Invalid arguments"; + break; + case WSAEMFILE: + p = "Out of file descriptors"; + break; + case WSAEWOULDBLOCK: + p = "Call would block"; + break; + case WSAEINPROGRESS: + case WSAEALREADY: + p = "Blocking call in progress"; + break; + case WSAENOTSOCK: + p = "Descriptor is not a socket"; + break; + case WSAEDESTADDRREQ: + p = "Need destination address"; + break; + case WSAEMSGSIZE: + p = "Bad message size"; + break; + case WSAEPROTOTYPE: + p = "Bad protocol"; + break; + case WSAENOPROTOOPT: + p = "Protocol option is unsupported"; + break; + case WSAEPROTONOSUPPORT: + p = "Protocol is unsupported"; + break; + case WSAESOCKTNOSUPPORT: + p = "Socket is unsupported"; + break; + case WSAEOPNOTSUPP: + p = "Operation not supported"; + break; + case WSAEAFNOSUPPORT: + p = "Address family not supported"; + break; + case WSAEPFNOSUPPORT: + p = "Protocol family not supported"; + break; + case WSAEADDRINUSE: + p = "Address already in use"; + break; + case WSAEADDRNOTAVAIL: + p = "Address not available"; + break; + case WSAENETDOWN: + p = "Network down"; + break; + case WSAENETUNREACH: + p = "Network unreachable"; + break; + case WSAENETRESET: + p = "Network has been reset"; + break; + case WSAECONNABORTED: + p = "Connection was aborted"; + break; + case WSAECONNRESET: + p = "Connection was reset"; + break; + case WSAENOBUFS: + p = "No buffer space"; + break; + case WSAEISCONN: + p = "Socket is already connected"; + break; + case WSAENOTCONN: + p = "Socket is not connected"; + break; + case WSAESHUTDOWN: + p = "Socket has been shut down"; + break; + case WSAETOOMANYREFS: + p = "Too many references"; + break; + case WSAETIMEDOUT: + p = "Timed out"; + break; + case WSAECONNREFUSED: + p = "Connection refused"; + break; + case WSAELOOP: + p = "Loop??"; + break; + case WSAENAMETOOLONG: + p = "Name too long"; + break; + case WSAEHOSTDOWN: + p = "Host down"; + break; + case WSAEHOSTUNREACH: + p = "Host unreachable"; + break; + case WSAENOTEMPTY: + p = "Not empty"; + break; + case WSAEPROCLIM: + p = "Process limit reached"; + break; + case WSAEUSERS: + p = "Too many users"; + break; + case WSAEDQUOT: + p = "Bad quota"; + break; + case WSAESTALE: + p = "Something is stale"; + break; + case WSAEREMOTE: + p = "Remote error"; + break; + case WSAEDISCON: + p = "Disconnected"; + break; + /* Extended Winsock errors */ + case WSASYSNOTREADY: + p = "Winsock library is not ready"; + break; + case WSANOTINITIALISED: + p = "Winsock library not initialized"; + break; + case WSAVERNOTSUPPORTED: + p = "Winsock version not supported"; + break; + + /* getXbyY() errors (already handled in herrmsg): + * Authoritative Answer: Host not found */ + case WSAHOST_NOT_FOUND: + p = "Host not found"; + break; + + /* Non-Authoritative: Host not found, or SERVERFAIL */ + case WSATRY_AGAIN: + p = "Host not found, try again"; + break; + + /* Non recoverable errors, FORMERR, REFUSED, NOTIMP */ + case WSANO_RECOVERY: + p = "Unrecoverable error in call to nameserver"; + break; + + /* Valid name, no data record of requested type */ + case WSANO_DATA: + p = "No data record of requested type"; + break; + + default: + return NULL; + } + curlx_strcopy(buf, len, p, strlen(p)); + return buf; +#endif +} +#endif /* USE_WINSOCK */ + +/* + * Our thread-safe and smart strerror() replacement. + * + * The 'err' argument passed in to this function MUST be a true errno number + * as reported on this system. We do no range checking on the number before + * we pass it to the "number-to-message" conversion function and there might + * be systems that do not do proper range checking in there themselves. + * + * We do not do range checking (on systems other than Windows) since there is + * no good reliable and portable way to do it. + * + * On Windows different types of error codes overlap. This function has an + * order of preference when trying to match error codes: + * CRT (errno), Winsock (WSAGetLastError), Windows API (GetLastError). + * + * It may be more correct to call one of the variant functions instead: + * Call Curl_sspi_strerror if the error code is definitely Windows SSPI. + * Call curlx_winapi_strerror if the error code is definitely Windows API. + */ +const char *curlx_strerror(int err, char *buf, size_t buflen) +{ +#ifdef _WIN32 + DWORD old_win_err = GetLastError(); +#endif + int old_errno = errno; + char *p; + + if(!buflen) + return NULL; + +#ifndef _WIN32 + DEBUGASSERT(err >= 0); +#endif + + *buf = '\0'; + +#ifdef _WIN32 + if((strerror_s(buf, buflen, err) || !strcmp(buf, "Unknown error")) && +#ifdef USE_WINSOCK + !get_winsock_error(err, buf, buflen) && +#endif + !curlx_get_winapi_error((DWORD)err, buf, buflen)) + SNPRINTF(buf, buflen, "Unknown error %d (%#x)", err, (unsigned int)err); +#else /* !_WIN32 */ + +#if defined(HAVE_STRERROR_R) && defined(HAVE_POSIX_STRERROR_R) + /* + * The POSIX-style strerror_r() may set errno to ERANGE if insufficient + * storage is supplied via 'strerrbuf' and 'buflen' to hold the generated + * message string, or EINVAL if 'errnum' is not a valid error number. + */ + if(strerror_r(err, buf, buflen) && + buflen > sizeof("Unknown error ") + 20) { + if(buf[0] == '\0') + SNPRINTF(buf, buflen, "Unknown error %d", err); + } +#elif defined(HAVE_STRERROR_R) && defined(HAVE_GLIBC_STRERROR_R) + /* + * The glibc-style strerror_r() only *might* use the buffer we pass to + * the function, but it always returns the error message as a pointer, + * so we must copy that string unconditionally (if non-NULL). + */ + { + char buffer[256]; + const char *msg = strerror_r(err, buffer, sizeof(buffer)); + if(msg && buflen > 1) + SNPRINTF(buf, buflen, "%s", msg); + else if(buflen > sizeof("Unknown error ") + 20) + SNPRINTF(buf, buflen, "Unknown error %d", err); + } +#else + { + /* !checksrc! disable BANNEDFUNC 1 */ + const char *msg = strerror(err); + if(msg && buflen > 1) + SNPRINTF(buf, buflen, "%s", msg); + else if(buflen > sizeof("Unknown error ") + 20) + SNPRINTF(buf, buflen, "Unknown error %d", err); + } +#endif + +#endif /* _WIN32 */ + + /* strip trailing '\r\n' or '\n'. */ + p = strrchr(buf, '\n'); + if(p && (p - buf) >= 2) + *p = '\0'; + p = strrchr(buf, '\r'); + if(p && (p - buf) >= 1) + *p = '\0'; + + if(errno != old_errno) + errno = old_errno; + +#ifdef _WIN32 + if(old_win_err != GetLastError()) + SetLastError(old_win_err); +#endif + + return buf; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strerr.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strerr.h new file mode 100644 index 0000000000..4413e6738c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strerr.h @@ -0,0 +1,29 @@ +#ifndef HEADER_CURL_STRERR_H +#define HEADER_CURL_STRERR_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +const char *curlx_strerror(int err, char *buf, size_t buflen); + +#endif /* HEADER_CURL_STRERR_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strparse.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strparse.c new file mode 100644 index 0000000000..9e8fe4963d --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strparse.c @@ -0,0 +1,317 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curlx/strparse.h" + +void curlx_str_init(struct Curl_str *out) +{ + out->str = NULL; + out->len = 0; +} + +void curlx_str_assign(struct Curl_str *out, const char *str, size_t len) +{ + out->str = str; + out->len = len; +} + +/* remove bytes from the end of the string, never remove more bytes than what + the string holds! */ +void curlx_str_trim(struct Curl_str *out, size_t len) +{ + DEBUGASSERT(out); + DEBUGASSERT(out->len >= len); + out->len -= len; +} + +/* Get a word until the first DELIM or end of string. At least one byte long. + return non-zero on error. If 'max' is zero, it will always return error. */ +int curlx_str_until(const char **linep, struct Curl_str *out, + const size_t max, char delim) +{ + const char *s; + size_t len = 0; + DEBUGASSERT(linep); + DEBUGASSERT(*linep); + DEBUGASSERT(out); + DEBUGASSERT(delim); + s = *linep; + + curlx_str_init(out); + while(*s && (*s != delim)) { + s++; + if(++len > max) { + return STRE_BIG; + } + } + if(!len) + return STRE_SHORT; + out->str = *linep; + out->len = len; + *linep = s; /* point to the first byte after the word */ + return STRE_OK; +} + +/* Get a word until the first space or end of string. At least one byte long. + return non-zero on error */ +int curlx_str_word(const char **linep, struct Curl_str *out, const size_t max) +{ + return curlx_str_until(linep, out, max, ' '); +} + +/* Get a word until a newline byte or end of string. At least one byte long. + return non-zero on error */ +int curlx_str_untilnl(const char **linep, struct Curl_str *out, + const size_t max) +{ + const char *s = *linep; + size_t len = 0; + DEBUGASSERT(linep && *linep && out && max); + + curlx_str_init(out); + while(*s && !ISNEWLINE(*s)) { + s++; + if(++len > max) + return STRE_BIG; + } + if(!len) + return STRE_SHORT; + out->str = *linep; + out->len = len; + *linep = s; /* point to the first byte after the word */ + return STRE_OK; +} + +/* Get a "quoted" word. Escaped quotes are supported. + return non-zero on error */ +int curlx_str_quotedword(const char **linep, struct Curl_str *out, + const size_t max) +{ + const char *s = *linep; + size_t len = 0; + DEBUGASSERT(linep && *linep && out && max); + + curlx_str_init(out); + if(*s != '\"') + return STRE_BEGQUOTE; + s++; + while(*s && (*s != '\"')) { + if(*s == '\\' && s[1]) { + s++; + if(++len > max) + return STRE_BIG; + } + s++; + if(++len > max) + return STRE_BIG; + } + if(*s != '\"') + return STRE_ENDQUOTE; + out->str = (*linep) + 1; + out->len = len; + *linep = s + 1; + return STRE_OK; +} + +/* Advance over a single character. + return non-zero on error */ +int curlx_str_single(const char **linep, char byte) +{ + DEBUGASSERT(linep && *linep); + if(**linep != byte) + return STRE_BYTE; + (*linep)++; /* move over it */ + return STRE_OK; +} + +/* Advance over a single space. + return non-zero on error */ +int curlx_str_singlespace(const char **linep) +{ + return curlx_str_single(linep, ' '); +} + +/* given an ASCII character and max ascii, return TRUE if valid */ +#define valid_digit(x, m) \ + (((x) >= '0') && ((x) <= (m)) && curlx_hexasciitable[(x) - '0']) + +/* We use 16 for the zero index (and the necessary bitwise AND in the loop) + to be able to have a non-zero value there to make valid_digit() able to + use the info */ +const unsigned char curlx_hexasciitable[] = { + 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 0x30: 0 - 9 */ + 0, 0, 0, 0, 0, 0, 0, + 10, 11, 12, 13, 14, 15, /* 0x41: A - F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 10, 11, 12, 13, 14, 15 /* 0x61: a - f */ +}; + +/* no support for 0x prefix nor leading spaces */ +static int str_num_base(const char **linep, curl_off_t *nump, curl_off_t max, + int base) /* 8, 10 or 16, nothing else */ +{ + curl_off_t num = 0; + const char *p; + int m = (base == 10) ? '9' : /* the largest digit possible */ + (base == 16) ? 'f' : '7'; + DEBUGASSERT(linep && *linep && nump); + DEBUGASSERT((base == 8) || (base == 10) || (base == 16)); + DEBUGASSERT(max >= 0); /* mostly to catch SIZE_MAX, which is too large */ + *nump = 0; + p = *linep; + if(!valid_digit(*p, m)) + return STRE_NO_NUM; + if(max < base) { + /* special-case low max scenario because check needs to be different */ + do { + int n = curlx_hexval(*p++); + num = (num * base) + n; + if(num > max) + return STRE_OVERFLOW; + } while(valid_digit(*p, m)); + } + else { + do { + int n = curlx_hexval(*p++); + if(num > ((max - n) / base)) + return STRE_OVERFLOW; + num = (num * base) + n; + } while(valid_digit(*p, m)); + } + *nump = num; + *linep = p; + return STRE_OK; +} + +/* Get an unsigned decimal number with no leading space or minus. Leading + zeroes are accepted. return non-zero on error */ +int curlx_str_number(const char **linep, curl_off_t *nump, curl_off_t max) +{ + return str_num_base(linep, nump, max, 10); +} + +/* Get an unsigned hexadecimal number with no leading space or minus and no + "0x" support. Leading zeroes are accepted. return non-zero on error */ +int curlx_str_hex(const char **linep, curl_off_t *nump, curl_off_t max) +{ + return str_num_base(linep, nump, max, 16); +} + +/* Get an unsigned octal number with no leading space or minus and no "0" + prefix support. Leading zeroes are accepted. return non-zero on error */ +int curlx_str_octal(const char **linep, curl_off_t *nump, curl_off_t max) +{ + return str_num_base(linep, nump, max, 8); +} + +/* + * Parse a positive number up to 63-bit number written in ASCII. Skip leading + * blanks. No support for prefixes. + */ +int curlx_str_numblanks(const char **str, curl_off_t *num) +{ + curlx_str_passblanks(str); + return curlx_str_number(str, num, CURL_OFF_T_MAX); +} + +/* CR or LF + return non-zero on error */ +int curlx_str_newline(const char **linep) +{ + DEBUGASSERT(linep && *linep); + if(ISNEWLINE(**linep)) { + (*linep)++; + return STRE_OK; /* yessir */ + } + return STRE_NEWLINE; +} + +#ifndef WITHOUT_LIBCURL +/* case insensitive compare that the parsed string matches the given string. + Returns non-zero on match. */ +int curlx_str_casecompare(struct Curl_str *str, const char *check) +{ + size_t clen = check ? strlen(check) : 0; + return ((str->len == clen) && curl_strnequal(str->str, check, clen)); +} +#endif + +/* case sensitive string compare. Returns non-zero on match. */ +int curlx_str_cmp(struct Curl_str *str, const char *check) +{ + if(check) { + size_t clen = strlen(check); + return ((str->len == clen) && !strncmp(str->str, check, clen)); + } + return !!str->len; +} + +/* Trim off 'num' number of bytes from the beginning (left side) of the + string. If 'num' is larger than the string, return error. */ +int curlx_str_nudge(struct Curl_str *str, size_t num) +{ + if(num <= str->len) { + str->str += num; + str->len -= num; + return STRE_OK; + } + return STRE_OVERFLOW; +} + +/* Get the following character sequence that consists only of bytes not + present in the 'reject' string. Like strcspn(). */ +int curlx_str_cspn(const char **linep, struct Curl_str *out, + const char *reject) +{ + const char *s = *linep; + size_t len; + DEBUGASSERT(linep && *linep); + + len = strcspn(s, reject); + if(len) { + out->str = s; + out->len = len; + *linep = &s[len]; + return STRE_OK; + } + curlx_str_init(out); + return STRE_SHORT; +} + +/* remove ISBLANK()s from both ends of the string */ +void curlx_str_trimblanks(struct Curl_str *out) +{ + while(out->len && ISBLANK(*out->str)) + curlx_str_nudge(out, 1); + + /* trim trailing spaces and tabs */ + while(out->len && ISBLANK(out->str[out->len - 1])) + out->len--; +} + +/* increase the pointer until it has moved over all blanks */ +void curlx_str_passblanks(const char **linep) +{ + while(ISBLANK(**linep)) + (*linep)++; /* move over it */ +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strparse.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strparse.h new file mode 100644 index 0000000000..7963dd6212 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/strparse.h @@ -0,0 +1,113 @@ +#ifndef HEADER_CURL_STRPARSE_H +#define HEADER_CURL_STRPARSE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#define STRE_OK 0 +#define STRE_BIG 1 +#define STRE_SHORT 2 +#define STRE_BEGQUOTE 3 +#define STRE_ENDQUOTE 4 +#define STRE_BYTE 5 +#define STRE_NEWLINE 6 +#define STRE_OVERFLOW 7 +#define STRE_NO_NUM 8 + +/* public struct, but all accesses should be done using the provided + functions */ +struct Curl_str { + const char *str; + size_t len; +}; + +void curlx_str_init(struct Curl_str *out); +void curlx_str_assign(struct Curl_str *out, const char *str, size_t len); +void curlx_str_trim(struct Curl_str *out, size_t len); + +#define curlx_str(x) ((x)->str) +#define curlx_strlen(x) ((x)->len) + +/* Get a word until the first space + return non-zero on error */ +int curlx_str_word(const char **linep, struct Curl_str *out, const size_t max); + +/* Get a word until the first DELIM or end of string + return non-zero on error */ +int curlx_str_until(const char **linep, struct Curl_str *out, const size_t max, + char delim); + +/* Get a word until a newline byte or end of string. At least one byte long. + return non-zero on error */ +int curlx_str_untilnl(const char **linep, struct Curl_str *out, + const size_t max); + +/* Get a "quoted" word. Escaped quotes are supported. + return non-zero on error */ +int curlx_str_quotedword(const char **linep, struct Curl_str *out, + const size_t max); + +/* Advance over a single character. + return non-zero on error */ +int curlx_str_single(const char **linep, char byte); + +/* Advance over a single space. + return non-zero on error */ +int curlx_str_singlespace(const char **linep); + +/* Get an unsigned decimal number. Return non-zero on error */ +int curlx_str_number(const char **linep, curl_off_t *nump, curl_off_t max); + +/* As above with CURL_OFF_T_MAX but also pass leading blanks */ +int curlx_str_numblanks(const char **str, curl_off_t *num); + +/* Get an unsigned hexadecimal number. Return non-zero on error */ +int curlx_str_hex(const char **linep, curl_off_t *nump, curl_off_t max); + +/* Get an unsigned octal number. Return non-zero on error */ +int curlx_str_octal(const char **linep, curl_off_t *nump, curl_off_t max); + +/* Check for CR or LF + return non-zero on error */ +int curlx_str_newline(const char **linep); + +/* case insensitive compare that the parsed string matches the + given string. */ +int curlx_str_casecompare(struct Curl_str *str, const char *check); +int curlx_str_cmp(struct Curl_str *str, const char *check); + +int curlx_str_nudge(struct Curl_str *str, size_t num); + +int curlx_str_cspn(const char **linep, struct Curl_str *out, + const char *reject); +void curlx_str_trimblanks(struct Curl_str *out); +void curlx_str_passblanks(const char **linep); + +/* given a hexadecimal letter, return the binary value. '0' returns 0, 'a' + returns 10. THIS ONLY WORKS ON VALID HEXADECIMAL LETTER INPUT. Verify + before calling this. */ +extern const unsigned char curlx_hexasciitable[]; +#define curlx_hexval(x) (unsigned char)(curlx_hexasciitable[(x) - '0'] & 0x0f) + +#endif /* HEADER_CURL_STRPARSE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/timediff.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/timediff.c new file mode 100644 index 0000000000..2bf786941d --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/timediff.c @@ -0,0 +1,85 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curlx/timediff.h" + +/* + * Converts number of milliseconds into a timeval structure. + * + * Return values: + * NULL IF tv is NULL or ms < 0 (eg. no timeout -> blocking select) + * tv with 0 in both fields IF ms == 0 (eg. 0ms timeout -> polling select) + * tv with converted fields IF ms > 0 (eg. >0ms timeout -> waiting select) + */ +struct timeval *curlx_mstotv(struct timeval *tv, timediff_t ms) +{ + if(!tv) + return NULL; + + if(ms < 0) + return NULL; + + if(ms > 0) { + timediff_t tv_sec = ms / 1000; + timediff_t tv_usec = (ms % 1000) * 1000; /* max=999000 */ +#ifdef HAVE_SUSECONDS_T +#if TIMEDIFF_T_MAX > TIME_T_MAX + /* tv_sec overflow check in case time_t is signed */ + if(tv_sec > TIME_T_MAX) + tv_sec = TIME_T_MAX; +#endif + tv->tv_sec = (time_t)tv_sec; + tv->tv_usec = (suseconds_t)tv_usec; +#elif defined(_WIN32) /* maybe also others in the future */ +#if TIMEDIFF_T_MAX > LONG_MAX + /* tv_sec overflow check on Windows there we know it is long */ + if(tv_sec > LONG_MAX) + tv_sec = LONG_MAX; +#endif + tv->tv_sec = (long)tv_sec; + tv->tv_usec = (long)tv_usec; +#else +#if TIMEDIFF_T_MAX > INT_MAX + /* tv_sec overflow check in case time_t is signed */ + if(tv_sec > INT_MAX) + tv_sec = INT_MAX; +#endif + tv->tv_sec = (int)tv_sec; + tv->tv_usec = (int)tv_usec; +#endif + } + else { + tv->tv_sec = 0; + tv->tv_usec = 0; + } + + return tv; +} + +/* + * Converts a timeval structure into number of milliseconds. + */ +timediff_t curlx_tvtoms(struct timeval *tv) +{ + return (tv->tv_sec * 1000) + (timediff_t)(tv->tv_usec / 1000); +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/timediff.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/timediff.h new file mode 100644 index 0000000000..1081c75d1c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/timediff.h @@ -0,0 +1,51 @@ +#ifndef HEADER_CURL_TIMEDIFF_H +#define HEADER_CURL_TIMEDIFF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* Use a larger type even for 32-bit time_t systems so that we can keep + microsecond accuracy in it */ +typedef curl_off_t timediff_t; +#define FMT_TIMEDIFF_T FMT_OFF_T + +#define TIMEDIFF_T_MAX CURL_OFF_T_MAX +#define TIMEDIFF_T_MIN CURL_OFF_T_MIN + +/* + * Converts number of milliseconds into a timeval structure. + * + * Return values: + * NULL IF tv is NULL or ms < 0 (eg. no timeout -> blocking select) + * tv with 0 in both fields IF ms == 0 (eg. 0ms timeout -> polling select) + * tv with converted fields IF ms > 0 (eg. >0ms timeout -> waiting select) + */ +struct timeval *curlx_mstotv(struct timeval *tv, timediff_t ms); + +/* + * Converts a timeval structure into number of milliseconds. + */ +timediff_t curlx_tvtoms(struct timeval *tv); + +#endif /* HEADER_CURL_TIMEDIFF_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/timeval.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/timeval.c new file mode 100644 index 0000000000..b43aedf15c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/timeval.c @@ -0,0 +1,276 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curlx/timeval.h" + +#ifdef _WIN32 + +static LARGE_INTEGER s_time_freq; + +/* For tool or tests, we must initialize before calling curlx_now(). + Providing this function here is wrong. */ +void curlx_now_init(void) +{ + QueryPerformanceFrequency(&s_time_freq); +} + +/* In case of bug fix this function has a counterpart in tool_util.c */ +void curlx_pnow(struct curltime *pnow) +{ + LARGE_INTEGER count; + DEBUGASSERT(s_time_freq.QuadPart); + QueryPerformanceCounter(&count); + pnow->tv_sec = (time_t)(count.QuadPart / s_time_freq.QuadPart); + pnow->tv_usec = (int)((count.QuadPart % s_time_freq.QuadPart) * 1000000 / + s_time_freq.QuadPart); +} + +#elif defined(HAVE_CLOCK_GETTIME_MONOTONIC) || \ + defined(HAVE_CLOCK_GETTIME_MONOTONIC_RAW) + +void curlx_pnow(struct curltime *pnow) +{ + /* + * clock_gettime() is granted to be increased monotonically when the + * monotonic clock is queried. Time starting point is unspecified, it + * could be the system start-up time, the Epoch, or something else, + * in any case the time starting point does not change once that the + * system has started up. + */ + struct timespec tsnow; + + /* + * clock_gettime() may be defined by Apple's SDK as weak symbol thus + * code compiles but fails during runtime if clock_gettime() is + * called on unsupported OS version. + */ +#if defined(__APPLE__) && defined(HAVE_BUILTIN_AVAILABLE) && \ + (HAVE_BUILTIN_AVAILABLE == 1) + bool have_clock_gettime = FALSE; + if(__builtin_available(macOS 10.12, iOS 10, tvOS 10, watchOS 3, *)) + have_clock_gettime = TRUE; +#endif + +#ifdef HAVE_CLOCK_GETTIME_MONOTONIC_RAW + if( +#if defined(__APPLE__) && defined(HAVE_BUILTIN_AVAILABLE) && \ + (HAVE_BUILTIN_AVAILABLE == 1) + have_clock_gettime && +#endif + (clock_gettime(CLOCK_MONOTONIC_RAW, &tsnow) == 0)) { + pnow->tv_sec = tsnow.tv_sec; + pnow->tv_usec = (int)(tsnow.tv_nsec / 1000); + } + else +#endif + + if( +#if defined(__APPLE__) && defined(HAVE_BUILTIN_AVAILABLE) && \ + (HAVE_BUILTIN_AVAILABLE == 1) + have_clock_gettime && +#endif + (clock_gettime(CLOCK_MONOTONIC, &tsnow) == 0)) { + pnow->tv_sec = tsnow.tv_sec; + pnow->tv_usec = (int)(tsnow.tv_nsec / 1000); + } + /* + * Even when the configure process has truly detected monotonic clock + * availability, it might happen that it is not actually available at + * runtime. When this occurs, fallback to other time source. + */ +#ifdef HAVE_GETTIMEOFDAY + else { + struct timeval now; + (void)gettimeofday(&now, NULL); + pnow->tv_sec = now.tv_sec; + pnow->tv_usec = (int)now.tv_usec; + } +#else + else { + pnow->tv_sec = time(NULL); + pnow->tv_usec = 0; + } +#endif +} + +#elif defined(HAVE_MACH_ABSOLUTE_TIME) + +#include <mach/mach_time.h> + +void curlx_pnow(struct curltime *pnow) +{ + /* + * Monotonic timer on macOS is provided by mach_absolute_time(), which + * returns time in Mach "absolute time units," which are platform-dependent. + * To convert to nanoseconds, one must use conversion factors specified by + * mach_timebase_info(). + */ + static mach_timebase_info_data_t timebase; + uint64_t usecs; + + if(timebase.denom == 0) + (void)mach_timebase_info(&timebase); + + usecs = mach_absolute_time(); + usecs *= timebase.numer; /* spellchecker:disable-line */ + usecs /= timebase.denom; + usecs /= 1000; + + pnow->tv_sec = usecs / 1000000; + pnow->tv_usec = (int)(usecs % 1000000); +} + +#elif defined(HAVE_GETTIMEOFDAY) + +void curlx_pnow(struct curltime *pnow) +{ + /* + * gettimeofday() is not granted to be increased monotonically, due to + * clock drifting and external source time synchronization it can jump + * forward or backward in time. + */ + struct timeval now; + (void)gettimeofday(&now, NULL); + pnow->tv_sec = now.tv_sec; + pnow->tv_usec = (int)now.tv_usec; +} + +#else + +void curlx_pnow(struct curltime *pnow) +{ + /* + * time() returns the value of time in seconds since the Epoch. + */ + pnow->tv_sec = time(NULL); + pnow->tv_usec = 0; + if(!pnow->tv_sec) /* avoid a `now` fully zero */ + pnow->tv_usec = 1; +} + +#endif + +struct curltime curlx_now(void) +{ + struct curltime now; + curlx_pnow(&now); + return now; +} + +/* + * Returns: time difference in number of milliseconds. For too large diffs it + * returns max value. + * + * @unittest: 1323 + */ +timediff_t curlx_ptimediff_ms(const struct curltime *newer, + const struct curltime *older) +{ + timediff_t diff = (timediff_t)newer->tv_sec - older->tv_sec; + if(diff >= (TIMEDIFF_T_MAX / 1000)) + return TIMEDIFF_T_MAX; + else if(diff <= (TIMEDIFF_T_MIN / 1000)) + return TIMEDIFF_T_MIN; + return (diff * 1000) + ((newer->tv_usec - older->tv_usec) / 1000); +} + +timediff_t curlx_timediff_ms(struct curltime newer, struct curltime older) +{ + return curlx_ptimediff_ms(&newer, &older); +} + +/* + * Returns: time difference in number of milliseconds, rounded up. + * For too large diffs it returns max value. + */ +timediff_t curlx_timediff_ceil_ms(struct curltime newer, + struct curltime older) +{ + timediff_t diff = (timediff_t)newer.tv_sec - older.tv_sec; + if(diff >= (TIMEDIFF_T_MAX / 1000)) + return TIMEDIFF_T_MAX; + else if(diff <= (TIMEDIFF_T_MIN / 1000)) + return TIMEDIFF_T_MIN; + return (diff * 1000) + ((newer.tv_usec - older.tv_usec + 999) / 1000); +} + +timediff_t curlx_us_to_ceil_ms(timediff_t us) +{ + return (us / 1000) + ((us > 0) && (us % 1000)); +} + +/* + * Returns: time difference in number of microseconds. For too large diffs it + * returns max value. + */ +timediff_t curlx_ptimediff_us(const struct curltime *newer, + const struct curltime *older) +{ + timediff_t diff = (timediff_t)newer->tv_sec - older->tv_sec; + if(diff >= (TIMEDIFF_T_MAX / 1000000)) + return TIMEDIFF_T_MAX; + else if(diff <= (TIMEDIFF_T_MIN / 1000000)) + return TIMEDIFF_T_MIN; + return (diff * 1000000) + newer->tv_usec - older->tv_usec; +} + +timediff_t curlx_timediff_us(struct curltime newer, struct curltime older) +{ + return curlx_ptimediff_us(&newer, &older); +} + +#if defined(__MINGW32__) && (__MINGW64_VERSION_MAJOR <= 3) +#include <sec_api/time_s.h> /* for _gmtime32_s(), _gmtime64_s() */ +#ifdef _USE_32BIT_TIME_T +#define gmtime_s _gmtime32_s +#else +#define gmtime_s _gmtime64_s +#endif +#endif + +/* + * curlx_gmtime() is a gmtime() replacement for portability. Do not use + * the gmtime_s(), gmtime_r() or gmtime() functions anywhere else but here. + */ +CURLcode curlx_gmtime(time_t intime, struct tm *store) +{ +#ifdef _WIN32 + if(gmtime_s(store, &intime)) /* thread-safe */ + return CURLE_BAD_FUNCTION_ARGUMENT; +#elif defined(HAVE_GMTIME_R) + const struct tm *tm; + tm = gmtime_r(&intime, store); /* thread-safe */ + if(!tm) + return CURLE_BAD_FUNCTION_ARGUMENT; +#else + const struct tm *tm; + /* !checksrc! disable BANNEDFUNC 1 */ + tm = gmtime(&intime); /* not thread-safe */ + if(tm) + *store = *tm; /* copy the pointed struct to the local copy */ + else + return CURLE_BAD_FUNCTION_ARGUMENT; +#endif + + return CURLE_OK; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/timeval.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/timeval.h new file mode 100644 index 0000000000..284c452df0 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/timeval.h @@ -0,0 +1,77 @@ +#ifndef HEADER_CURL_TIMEVAL_H +#define HEADER_CURL_TIMEVAL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curlx/timediff.h" + +struct curltime { + time_t tv_sec; /* seconds */ + int tv_usec; /* microseconds */ +}; + +#ifdef _WIN32 +/* For tool or tests, we must initialize before calling curlx_now() */ +void curlx_now_init(void); +#endif + +struct curltime curlx_now(void); +void curlx_pnow(struct curltime *pnow); + +/* + * Make sure that the first argument (newer) is the more recent time and older + * is the older time, as otherwise you get a weird negative time-diff back... + * + * Returns: the time difference in number of milliseconds. + */ +timediff_t curlx_timediff_ms(struct curltime newer, struct curltime older); +timediff_t curlx_ptimediff_ms(const struct curltime *newer, + const struct curltime *older); + +/* + * Make sure that the first argument (newer) is the more recent time and older + * is the older time, as otherwise you get a weird negative time-diff back... + * + * Returns: the time difference in number of milliseconds, rounded up. + */ +timediff_t curlx_timediff_ceil_ms(struct curltime newer, + struct curltime older); + +/* Returns milliseconds from microseconds, rounded up. */ +timediff_t curlx_us_to_ceil_ms(timediff_t us); + +/* + * Make sure that the first argument (newer) is the more recent time and older + * is the older time, as otherwise you get a weird negative time-diff back... + * + * Returns: the time difference in number of microseconds. + */ +timediff_t curlx_timediff_us(struct curltime newer, struct curltime older); +timediff_t curlx_ptimediff_us(const struct curltime *newer, + const struct curltime *older); + +CURLcode curlx_gmtime(time_t intime, struct tm *store); + +#endif /* HEADER_CURL_TIMEVAL_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/version_win32.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/version_win32.c new file mode 100644 index 0000000000..296a38d924 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/version_win32.c @@ -0,0 +1,238 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, <steve_holme@hotmail.com>. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef _WIN32 + +#include "curlx/version_win32.h" + +#ifndef CURL_WINDOWS_UWP +/* This Unicode version struct works for VerifyVersionInfoW (OSVERSIONINFOEXW) + and RtlVerifyVersionInfo (RTLOSVERSIONINFOEXW) */ +struct OUR_OSVERSIONINFOEXW { + ULONG dwOSVersionInfoSize; + ULONG dwMajorVersion; + ULONG dwMinorVersion; + ULONG dwBuildNumber; + ULONG dwPlatformId; + WCHAR szCSDVersion[128]; + USHORT wServicePackMajor; + USHORT wServicePackMinor; + USHORT wSuiteMask; + UCHAR wProductType; + UCHAR wReserved; +}; + +typedef LONG (APIENTRY *RTLVERIFYVERSIONINFO_FN) + (struct OUR_OSVERSIONINFOEXW *, ULONG, ULONGLONG); +static RTLVERIFYVERSIONINFO_FN s_pRtlVerifyVersionInfo; + +void curlx_verify_windows_init(void) +{ +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcast-function-type-strict" +#endif + s_pRtlVerifyVersionInfo = CURLX_FUNCTION_CAST(RTLVERIFYVERSIONINFO_FN, + GetProcAddress(GetModuleHandle(TEXT("ntdll")), "RtlVerifyVersionInfo")); +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic pop +#endif +} +#endif /* !CURL_WINDOWS_UWP */ + +/* + * curlx_verify_windows_version() + * + * This is used to verify if we are running on a specific Windows version. + * + * Parameters: + * + * majorVersion [in] - The major version number. + * minorVersion [in] - The minor version number. + * buildVersion [in] - The build version number. If 0, this parameter is + * ignored. + * platform [in] - The optional platform identifier. + * condition [in] - The test condition used to specifier whether we are + * checking a version less than, equal to or greater than + * what is specified in the major and minor version + * numbers. + * + * Returns TRUE if matched; otherwise FALSE. + */ +bool curlx_verify_windows_version(const unsigned int majorVersion, + const unsigned int minorVersion, + const unsigned int buildVersion, + const PlatformIdentifier platform, + const VersionCondition condition) +{ + bool matched = FALSE; + +#ifdef CURL_WINDOWS_UWP + /* We have no way to determine the Windows version from Windows apps, + so let's assume we are running on the target Windows version. */ + const WORD fullVersion = MAKEWORD(minorVersion, majorVersion); + const WORD targetVersion = (WORD)_WIN32_WINNT; + + (void)buildVersion; + + switch(condition) { + case VERSION_LESS_THAN: + matched = targetVersion < fullVersion; + break; + + case VERSION_LESS_THAN_EQUAL: + matched = targetVersion <= fullVersion; + break; + + case VERSION_EQUAL: + matched = targetVersion == fullVersion; + break; + + case VERSION_GREATER_THAN_EQUAL: + matched = targetVersion >= fullVersion; + break; + + case VERSION_GREATER_THAN: + matched = targetVersion > fullVersion; + break; + } + + if(matched && (platform == PLATFORM_WINDOWS)) { + /* we are always running on PLATFORM_WINNT */ + matched = FALSE; + } +#else + ULONGLONG cm = 0; + struct OUR_OSVERSIONINFOEXW osver; + BYTE majorCondition; + BYTE minorCondition; + BYTE buildCondition; + BYTE spMajorCondition; + BYTE spMinorCondition; + DWORD dwTypeMask = VER_MAJORVERSION | VER_MINORVERSION | + VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR; + + switch(condition) { + case VERSION_LESS_THAN: + majorCondition = VER_LESS; + minorCondition = VER_LESS; + buildCondition = VER_LESS; + spMajorCondition = VER_LESS_EQUAL; + spMinorCondition = VER_LESS_EQUAL; + break; + + case VERSION_LESS_THAN_EQUAL: + majorCondition = VER_LESS_EQUAL; + minorCondition = VER_LESS_EQUAL; + buildCondition = VER_LESS_EQUAL; + spMajorCondition = VER_LESS_EQUAL; + spMinorCondition = VER_LESS_EQUAL; + break; + + case VERSION_EQUAL: + majorCondition = VER_EQUAL; + minorCondition = VER_EQUAL; + buildCondition = VER_EQUAL; + spMajorCondition = VER_GREATER_EQUAL; + spMinorCondition = VER_GREATER_EQUAL; + break; + + case VERSION_GREATER_THAN_EQUAL: + majorCondition = VER_GREATER_EQUAL; + minorCondition = VER_GREATER_EQUAL; + buildCondition = VER_GREATER_EQUAL; + spMajorCondition = VER_GREATER_EQUAL; + spMinorCondition = VER_GREATER_EQUAL; + break; + + case VERSION_GREATER_THAN: + majorCondition = VER_GREATER; + minorCondition = VER_GREATER; + buildCondition = VER_GREATER; + spMajorCondition = VER_GREATER_EQUAL; + spMinorCondition = VER_GREATER_EQUAL; + break; + + default: + return FALSE; + } + + memset(&osver, 0, sizeof(osver)); + osver.dwOSVersionInfoSize = sizeof(osver); + osver.dwMajorVersion = majorVersion; + osver.dwMinorVersion = minorVersion; + osver.dwBuildNumber = buildVersion; + if(platform == PLATFORM_WINDOWS) + osver.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS; + else if(platform == PLATFORM_WINNT) + osver.dwPlatformId = VER_PLATFORM_WIN32_NT; + + cm = VerSetConditionMask(cm, VER_MAJORVERSION, majorCondition); + cm = VerSetConditionMask(cm, VER_MINORVERSION, minorCondition); + cm = VerSetConditionMask(cm, VER_SERVICEPACKMAJOR, spMajorCondition); + cm = VerSetConditionMask(cm, VER_SERVICEPACKMINOR, spMinorCondition); + + if(platform != PLATFORM_DONT_CARE) { + cm = VerSetConditionMask(cm, VER_PLATFORMID, VER_EQUAL); + dwTypeMask |= VER_PLATFORMID; + } + + /* Later versions of Windows have version functions that may not return the + real version of Windows unless the application is so manifested. We prefer + the real version always, so we use the Rtl variant of the function when + possible. Note though the function signatures have underlying fundamental + types that are the same, the return values are different. */ + if(s_pRtlVerifyVersionInfo) + matched = !s_pRtlVerifyVersionInfo(&osver, dwTypeMask, cm); + else + matched = !!VerifyVersionInfoW((OSVERSIONINFOEXW *)&osver, dwTypeMask, cm); + + /* Compare the build number separately. VerifyVersionInfo normally compares + major.minor in hierarchical order (eg 1.9 is less than 2.0) but does not + do the same for build (eg 1.9 build 222 is not less than 2.0 build 111). + Build comparison is only needed when build numbers are equal (eg 1.9 is + always less than 2.0 so build comparison is not needed). */ + if(matched && buildVersion && + (condition == VERSION_EQUAL || + ((condition == VERSION_GREATER_THAN_EQUAL || + condition == VERSION_LESS_THAN_EQUAL) && + curlx_verify_windows_version(majorVersion, minorVersion, 0, + platform, VERSION_EQUAL)))) { + + cm = VerSetConditionMask(0, VER_BUILDNUMBER, buildCondition); + dwTypeMask = VER_BUILDNUMBER; + if(s_pRtlVerifyVersionInfo) + matched = !s_pRtlVerifyVersionInfo(&osver, dwTypeMask, cm); + else + matched = !!VerifyVersionInfoW((OSVERSIONINFOEXW *)&osver, + dwTypeMask, cm); + } + +#endif + + return matched; +} + +#endif /* _WIN32 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/version_win32.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/version_win32.h new file mode 100644 index 0000000000..c4a1c0f758 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/version_win32.h @@ -0,0 +1,60 @@ +#ifndef HEADER_CURL_VERSION_WIN32_H +#define HEADER_CURL_VERSION_WIN32_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, <steve_holme@hotmail.com>. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef _WIN32 + +/* Version condition */ +typedef enum { + VERSION_LESS_THAN, + VERSION_LESS_THAN_EQUAL, + VERSION_EQUAL, + VERSION_GREATER_THAN_EQUAL, + VERSION_GREATER_THAN +} VersionCondition; + +/* Platform identifier */ +typedef enum { + PLATFORM_DONT_CARE, + PLATFORM_WINDOWS, + PLATFORM_WINNT +} PlatformIdentifier; + +#ifdef CURL_WINDOWS_UWP +#define curlx_verify_windows_init() Curl_nop_stmt +#else +void curlx_verify_windows_init(void); +#endif +/* This is used to verify if we are running on a specific Windows version */ +bool curlx_verify_windows_version(const unsigned int majorVersion, + const unsigned int minorVersion, + const unsigned int buildVersion, + const PlatformIdentifier platform, + const VersionCondition condition); + +#endif /* _WIN32 */ + +#endif /* HEADER_CURL_VERSION_WIN32_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/wait.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/wait.c new file mode 100644 index 0000000000..7610a4ba36 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/wait.c @@ -0,0 +1,90 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_SYS_SELECT_H +#include <sys/select.h> +#elif defined(HAVE_UNISTD_H) +#include <unistd.h> +#endif + +#ifdef MSDOS +#include <dos.h> /* delay() */ +#endif + +#include "curlx/timediff.h" +#include "curlx/wait.h" + +/* + * Internal function used for waiting a specific amount of ms in + * Curl_socket_check() and Curl_poll() when no file descriptor is provided to + * wait on, being used to delay execution. Winsock select() and poll() timeout + * mechanisms need a valid socket descriptor in a not null file descriptor set + * to work. Waiting indefinitely with this function is not allowed, a zero or + * negative timeout value is returned immediately. Timeout resolution, + * accuracy, as well as maximum supported value is system dependent, neither + * factor is a critical issue for the intended use of this function in the + * library. + * + * Return values: + * -1 = system call error, or invalid timeout value + * 0 = specified timeout has elapsed, or interrupted + */ +int curlx_wait_ms(timediff_t timeout_ms) +{ + int r = 0; + + if(!timeout_ms) + return 0; + if(timeout_ms < 0) { + SET_SOCKERRNO(SOCKEINVAL); + return -1; + } +#ifdef MSDOS + delay((unsigned int)timeout_ms); +#elif defined(_WIN32) + /* prevent overflow, timeout_ms is typecast to ULONG/DWORD. */ +#if TIMEDIFF_T_MAX >= ULONG_MAX + if(timeout_ms >= ULONG_MAX) + timeout_ms = ULONG_MAX - 1; + /* do not use ULONG_MAX, because that is equal to INFINITE */ +#endif + Sleep((DWORD)timeout_ms); +#else + /* avoid using poll() for this since it behaves incorrectly with no sockets + on Apple operating systems */ + { + struct timeval pending_tv; + r = select(0, NULL, NULL, NULL, curlx_mstotv(&pending_tv, timeout_ms)); + } +#endif /* _WIN32 */ + if(r) { + if((r == -1) && (SOCKERRNO == SOCKEINTR)) + /* make EINTR from select or poll not a "lethal" error */ + r = 0; + else + r = -1; + } + return r; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/wait.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/wait.h new file mode 100644 index 0000000000..9b9c27386e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/wait.h @@ -0,0 +1,30 @@ +#ifndef HEADER_CURL_WAIT_H +#define HEADER_CURL_WAIT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +int curlx_wait_ms(timediff_t timeout_ms); + +#endif /* HEADER_CURL_WAIT_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/warnless.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/warnless.c new file mode 100644 index 0000000000..5fc36ac9a8 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/warnless.c @@ -0,0 +1,341 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curlx/warnless.h" + +#if defined(__INTEL_COMPILER) && defined(__unix__) + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif + +#endif /* __INTEL_COMPILER && __unix__ */ + +#define CURL_MASK_UCHAR ((unsigned char)~0) + +#define CURL_MASK_USHORT ((unsigned short)~0) + +#define CURL_MASK_UINT ((unsigned int)~0) +#define CURL_MASK_SINT (CURL_MASK_UINT >> 1) + +#define CURL_MASK_ULONG ((unsigned long)~0) + +#define CURL_MASK_USIZE_T ((size_t)~0) +#define CURL_MASK_SSIZE_T (CURL_MASK_USIZE_T >> 1) + +/* + * unsigned long to unsigned char + */ +unsigned char curlx_ultouc(unsigned long ulnum) +{ +#ifdef __INTEL_COMPILER +#pragma warning(push) +#pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(ulnum <= (unsigned long)CURL_MASK_UCHAR); + return (unsigned char)(ulnum & (unsigned long)CURL_MASK_UCHAR); + +#ifdef __INTEL_COMPILER +#pragma warning(pop) +#endif +} + +/* + * unsigned size_t to signed int + */ +int curlx_uztosi(size_t uznum) +{ +#ifdef __INTEL_COMPILER +#pragma warning(push) +#pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(uznum <= (size_t)CURL_MASK_SINT); + return (int)(uznum & (size_t)CURL_MASK_SINT); + +#ifdef __INTEL_COMPILER +#pragma warning(pop) +#endif +} + +/* + * unsigned size_t to unsigned long + */ +unsigned long curlx_uztoul(size_t uznum) +{ +#ifdef __INTEL_COMPILER +#pragma warning(push) +#pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + +#if ULONG_MAX < SIZE_MAX + DEBUGASSERT(uznum <= (size_t)CURL_MASK_ULONG); +#endif + return (unsigned long)(uznum & (size_t)CURL_MASK_ULONG); + +#ifdef __INTEL_COMPILER +#pragma warning(pop) +#endif +} + +/* + * unsigned size_t to unsigned int + */ +unsigned int curlx_uztoui(size_t uznum) +{ +#ifdef __INTEL_COMPILER +#pragma warning(push) +#pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + +#if UINT_MAX < SIZE_MAX + DEBUGASSERT(uznum <= (size_t)CURL_MASK_UINT); +#endif + return (unsigned int)(uznum & (size_t)CURL_MASK_UINT); + +#ifdef __INTEL_COMPILER +#pragma warning(pop) +#endif +} + +/* + * signed long to signed int + */ +int curlx_sltosi(long slnum) +{ +#ifdef __INTEL_COMPILER +#pragma warning(push) +#pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(slnum >= 0); +#if INT_MAX < LONG_MAX + DEBUGASSERT((unsigned long)slnum <= (unsigned long)CURL_MASK_SINT); +#endif + return (int)(slnum & (long)CURL_MASK_SINT); + +#ifdef __INTEL_COMPILER +#pragma warning(pop) +#endif +} + +/* + * signed long to unsigned int + */ +unsigned int curlx_sltoui(long slnum) +{ +#ifdef __INTEL_COMPILER +#pragma warning(push) +#pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(slnum >= 0); +#if UINT_MAX < LONG_MAX + DEBUGASSERT((unsigned long)slnum <= (unsigned long)CURL_MASK_UINT); +#endif + return (unsigned int)(slnum & (long)CURL_MASK_UINT); + +#ifdef __INTEL_COMPILER +#pragma warning(pop) +#endif +} + +/* + * signed long to unsigned short + */ +unsigned short curlx_sltous(long slnum) +{ +#ifdef __INTEL_COMPILER +#pragma warning(push) +#pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(slnum >= 0); + DEBUGASSERT((unsigned long)slnum <= (unsigned long)CURL_MASK_USHORT); + return (unsigned short)(slnum & (long)CURL_MASK_USHORT); + +#ifdef __INTEL_COMPILER +#pragma warning(pop) +#endif +} + +/* + * unsigned size_t to signed ssize_t + */ +ssize_t curlx_uztosz(size_t uznum) +{ +#ifdef __INTEL_COMPILER +#pragma warning(push) +#pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(uznum <= (size_t)CURL_MASK_SSIZE_T); + return (ssize_t)(uznum & (size_t)CURL_MASK_SSIZE_T); + +#ifdef __INTEL_COMPILER +#pragma warning(pop) +#endif +} + +/* + * signed curl_off_t to unsigned size_t + */ +size_t curlx_sotouz(curl_off_t sonum) +{ +#ifdef __INTEL_COMPILER +#pragma warning(push) +#pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(sonum >= 0); + return (size_t)(sonum & (curl_off_t)CURL_MASK_USIZE_T); + +#ifdef __INTEL_COMPILER +#pragma warning(pop) +#endif +} + +/* + * signed ssize_t to signed int + */ +int curlx_sztosi(ssize_t sznum) +{ +#ifdef __INTEL_COMPILER +#pragma warning(push) +#pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(sznum >= 0); +#if INT_MAX < SSIZE_MAX + DEBUGASSERT((size_t)sznum <= (size_t)CURL_MASK_SINT); +#endif + return (int)(sznum & (ssize_t)CURL_MASK_SINT); + +#ifdef __INTEL_COMPILER +#pragma warning(pop) +#endif +} + +/* + * unsigned int to unsigned short + */ +unsigned short curlx_uitous(unsigned int uinum) +{ +#ifdef __INTEL_COMPILER +#pragma warning(push) +#pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(uinum <= (unsigned int)CURL_MASK_USHORT); + return (unsigned short)(uinum & (unsigned int)CURL_MASK_USHORT); + +#ifdef __INTEL_COMPILER +#pragma warning(pop) +#endif +} + +/* + * signed int to unsigned size_t + */ +size_t curlx_sitouz(int sinum) +{ +#ifdef __INTEL_COMPILER +#pragma warning(push) +#pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(sinum >= 0); + return (size_t)sinum; + +#ifdef __INTEL_COMPILER +#pragma warning(pop) +#endif +} + +size_t curlx_uitouz(unsigned int uinum) +{ + return (size_t)uinum; +} + +size_t curlx_sotouz_range(curl_off_t sonum, size_t uzmin, size_t uzmax) +{ + if(sonum < 0) + return uzmin; +#if SIZEOF_CURL_OFF_T > SIZEOF_SIZE_T + if(sonum > SIZE_MAX) + return uzmax; +#endif + return CURLMIN(CURLMAX((size_t)sonum, uzmin), uzmax); +} + +bool curlx_sztouz(ssize_t sznum, size_t *puznum) +{ + if(sznum < 0) { + *puznum = 0; + return FALSE; + } + *puznum = (size_t)sznum; + return TRUE; +} + +bool curlx_sotouz_fits(curl_off_t sonum, size_t *puznum) +{ + if(sonum < 0) { + *puznum = 0; + return FALSE; + } +#if SIZEOF_CURL_OFF_T > SIZEOF_SIZE_T + if(sonum > SIZE_MAX) { + *puznum = 0; + return FALSE; + } +#endif + *puznum = (size_t)sonum; + return TRUE; +} + +bool curlx_sltouz(long slnum, size_t *puznum) +{ + if(slnum < 0) { + *puznum = 0; + return FALSE; + } + /* We error in curl_setup.h if SIZEOF_LONG > SIZEOF_SIZE_T */ + *puznum = (size_t)slnum; + return TRUE; +} + +curl_off_t curlx_uztoso(size_t uznum) +{ +#if SIZEOF_SIZE_T >= SIZEOF_CURL_OFF_T + if(uznum > (size_t)CURL_OFF_T_MAX) + return CURL_OFF_T_MAX; +#endif + return (curl_off_t)uznum; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/warnless.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/warnless.h new file mode 100644 index 0000000000..3d0341e418 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/warnless.h @@ -0,0 +1,74 @@ +#ifndef HEADER_CURL_WARNLESS_H +#define HEADER_CURL_WARNLESS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#define CURLX_FUNCTION_CAST(target_type, func) \ + (target_type)(void (*)(void))(func) + +unsigned char curlx_ultouc(unsigned long ulnum); + +int curlx_uztosi(size_t uznum); + +unsigned long curlx_uztoul(size_t uznum); + +unsigned int curlx_uztoui(size_t uznum); + +int curlx_sltosi(long slnum); + +unsigned int curlx_sltoui(long slnum); + +unsigned short curlx_sltous(long slnum); + +ssize_t curlx_uztosz(size_t uznum); + +size_t curlx_sotouz(curl_off_t sonum); + +int curlx_sztosi(ssize_t sznum); + +unsigned short curlx_uitous(unsigned int uinum); + +size_t curlx_sitouz(int sinum); + +size_t curlx_uitouz(unsigned int uinum); + +/* Convert a curl_off_t to fit into size_t interval [uzmin, uzmax]. + * values outside this interval give the lower/upper bound. */ +size_t curlx_sotouz_range(curl_off_t sonum, size_t uzmin, size_t uzmax); + +/* Convert a size_t to curl_off_t, return CURL_OFF_T_MAX if too large. */ +curl_off_t curlx_uztoso(size_t uznum); + +/* Convert a ssize_t to size_t, return FALSE if negative and set 0 */ +bool curlx_sztouz(ssize_t sznum, size_t *puznum); + +/* Convert a curl_off_t to size_t, return FALSE if negative or + * too large and set 0 */ +bool curlx_sotouz_fits(curl_off_t sonum, size_t *puznum); + +/* Convert a long to size_t, return FALSE if negative or too large + * and set 0 */ +bool curlx_sltouz(long slnum, size_t *puznum); + +#endif /* HEADER_CURL_WARNLESS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/winapi.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/winapi.c new file mode 100644 index 0000000000..1d6ef87abe --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/winapi.c @@ -0,0 +1,126 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* + * curlx_winapi_strerror: + * Variant of curlx_strerror if the error code is definitely Windows API. + */ +#ifdef _WIN32 +#include "curlx/winapi.h" +#include "curlx/snprintf.h" +#include "curlx/strcopy.h" + +/* This is a helper function for curlx_strerror that converts Windows API error + * codes (GetLastError) to error messages. + * Returns NULL if no error message was found for error code. + */ +const char *curlx_get_winapi_error(DWORD err, char *buf, size_t buflen) +{ + char *p; + + if(!buflen) + return NULL; + + /* We return the local codepage version of the error string because if it is + output to the user's terminal, it is likely done with functions which + expect the local codepage (eg fprintf, failf, infof). */ + if(!FormatMessageA((FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS), NULL, err, + LANG_NEUTRAL, buf, (DWORD)buflen, NULL)) { + *buf = '\0'; + return NULL; + } + + /* Truncate multiple lines */ + p = strchr(buf, '\n'); + if(p) { + if(p > buf && *(p - 1) == '\r') + *(p - 1) = '\0'; + else + *p = '\0'; + } + + return *buf ? buf : NULL; +} + +const char *curlx_winapi_strerror(DWORD err, char *buf, size_t buflen) +{ + DWORD old_win_err = GetLastError(); + int old_errno = errno; + + if(!buflen) + return NULL; + + *buf = '\0'; + +#ifdef CURLVERBOSE + if(!curlx_get_winapi_error(err, buf, buflen)) { +#if defined(__GNUC__) && __GNUC__ >= 7 +#pragma GCC diagnostic push +#pragma GCC diagnostic warning "-Wformat-truncation=1" +#endif + /* some GCC compilers cause false positive warnings if we allow this + warning */ + SNPRINTF(buf, buflen, "Unknown error %lu (0x%08lx)", err, err); +#if defined(__GNUC__) && __GNUC__ >= 7 +#pragma GCC diagnostic pop +#endif + } +#else + { + const char *txt = (err == ERROR_SUCCESS) ? "No error" : "Error"; + curlx_strcopy(buf, buflen, txt, strlen(txt)); + } +#endif + + if(errno != old_errno) + errno = old_errno; + + if(old_win_err != GetLastError()) + SetLastError(old_win_err); + + return buf; +} + +#ifndef WITHOUT_LIBCURL + +#include <bcrypt.h> +#ifndef STATUS_SUCCESS +#define STATUS_SUCCESS ((NTSTATUS)0x00000000L) +#endif + +CURLcode curlx_win32_random(unsigned char *entropy, size_t length) +{ + memset(entropy, 0, length); + + if(BCryptGenRandom(NULL, entropy, (ULONG)length, + BCRYPT_USE_SYSTEM_PREFERRED_RNG) != STATUS_SUCCESS) + return CURLE_FAILED_INIT; + + return CURLE_OK; +} +#endif /* WITHOUT_LIBCURL */ + +#endif /* _WIN32 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/winapi.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/winapi.h new file mode 100644 index 0000000000..21e864c028 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/curlx/winapi.h @@ -0,0 +1,34 @@ +#ifndef HEADER_CURLX_WINAPI_H +#define HEADER_CURLX_WINAPI_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifdef _WIN32 +#define WINAPI_ERROR_LEN 100 +const char *curlx_get_winapi_error(DWORD err, char *buf, size_t buflen); +const char *curlx_winapi_strerror(DWORD err, char *buf, size_t buflen); +CURLcode curlx_win32_random(unsigned char *entropy, size_t length); +#endif + +#endif /* HEADER_CURLX_WINAPI_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cw-out.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cw-out.c new file mode 100644 index 0000000000..0137975b1e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cw-out.c @@ -0,0 +1,503 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "cfilters.h" +#include "multiif.h" +#include "sendf.h" +#include "curl_trc.h" +#include "transfer.h" +#include "cw-out.h" +#include "cw-pause.h" +#include "progress.h" + +/** + * OVERALL DESIGN of this client writer + * + * The 'cw-out' writer is supposed to be the last writer in a transfer's + * stack. It is always added when that stack is initialized. Its purpose + * is to pass BODY and HEADER bytes to the client-installed callback + * functions. + * + * These callback may return `CURL_WRITEFUNC_PAUSE` to indicate that the + * data had not been written and the whole transfer should stop receiving + * new data. Or at least, stop calling the functions. When the transfer + * is "unpaused" by the client, the previous data shall be passed as + * if nothing happened. + * + * The `cw-out` writer therefore manages buffers for bytes that could + * not be written. Data that was already in flight from the server also + * needs buffering on paused transfer when it arrives. + * + * In addition, the writer allows buffering of "small" body writes, + * so client functions are called less often. That is only enabled on a + * number of conditions. + * + * HEADER and BODY data may arrive in any order. For paused transfers, + * a list of `struct cw_out_buf` is kept for `cw_out_type` types. The + * list may be: [BODY]->[HEADER]->[BODY]->[HEADER].... + * When unpausing, this list is "played back" to the client callbacks. + * + * The amount of bytes being buffered is limited by `DYN_PAUSE_BUFFER` + * and when that is exceeded `CURLE_TOO_LARGE` is returned as error. + */ +typedef enum { + CW_OUT_NONE, + CW_OUT_BODY, + CW_OUT_BODY_0LEN, + CW_OUT_HDS +} cw_out_type; + +struct cw_out_buf { + struct cw_out_buf *next; + struct dynbuf b; + cw_out_type type; +}; + +static struct cw_out_buf *cw_out_buf_create(cw_out_type otype) +{ + struct cw_out_buf *cwbuf = curlx_calloc(1, sizeof(*cwbuf)); + if(cwbuf) { + cwbuf->type = otype; + curlx_dyn_init(&cwbuf->b, DYN_PAUSE_BUFFER); + } + return cwbuf; +} + +static void cw_out_buf_free(struct cw_out_buf *cwbuf) +{ + if(cwbuf) { + curlx_dyn_free(&cwbuf->b); + curlx_free(cwbuf); + } +} + +struct cw_out_ctx { + struct Curl_cwriter super; + struct cw_out_buf *buf; + BIT(errored); +}; + +static CURLcode cw_out_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct cw_out_ctx *ctx = writer->ctx; + (void)data; + ctx->buf = NULL; + return CURLE_OK; +} + +static void cw_out_bufs_free(struct cw_out_ctx *ctx) +{ + while(ctx->buf) { + struct cw_out_buf *next = ctx->buf->next; + cw_out_buf_free(ctx->buf); + ctx->buf = next; + } +} + +static size_t cw_out_bufs_len(struct cw_out_ctx *ctx) +{ + struct cw_out_buf *cwbuf = ctx->buf; + size_t len = 0; + while(cwbuf) { + len += curlx_dyn_len(&cwbuf->b); + cwbuf = cwbuf->next; + } + return len; +} + +static void cw_out_close(struct Curl_easy *data, struct Curl_cwriter *writer) +{ + struct cw_out_ctx *ctx = writer->ctx; + + (void)data; + cw_out_bufs_free(ctx); +} + +/** + * Return the current curl_write_callback and user_data for the buf type + */ +static void cw_get_writefunc(struct Curl_easy *data, cw_out_type otype, + curl_write_callback *pwcb, void **pwcb_data, + size_t *pmax_write, size_t *pmin_write) +{ + switch(otype) { + case CW_OUT_BODY: + case CW_OUT_BODY_0LEN: + *pwcb = data->set.fwrite_func; + *pwcb_data = data->set.out; + *pmax_write = CURL_MAX_WRITE_SIZE; + /* if we ever want buffering of BODY output, we can set `min_write` + * the preferred size. The default should always be to pass data + * to the client as it comes without delay */ + *pmin_write = 0; + break; + case CW_OUT_HDS: + *pwcb = data->set.fwrite_header ? data->set.fwrite_header : + (data->set.writeheader ? data->set.fwrite_func : NULL); + *pwcb_data = data->set.writeheader; + *pmax_write = 0; /* do not chunk-write headers, write them as they are */ + *pmin_write = 0; + break; + default: + *pwcb = NULL; + *pwcb_data = NULL; + *pmax_write = CURL_MAX_WRITE_SIZE; + *pmin_write = 0; + } +} + +static CURLcode cw_out_cb_write(struct Curl_easy *data, + curl_write_callback wcb, + void *wcb_data, + cw_out_type otype, + const char *buf, size_t blen, + size_t *pnwritten) +{ + size_t nwritten; + CURLcode result; + + NOVERBOSE((void)otype); + + DEBUGASSERT(data->conn); + *pnwritten = 0; + { + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_cw_out_cb); + nwritten = wcb((char *)CURL_UNCONST(buf), 1, blen, wcb_data); + CURL_CBAPI_END(&guard); + } + CURL_TRC_WRITE(data, "[OUT] wrote %zu %s bytes, type=%x -> %zu", + blen, (otype == CW_OUT_HDS) ? "header" : "body", + (unsigned int)otype, nwritten); + if(nwritten == CURL_WRITEFUNC_PAUSE) { + if(data->conn->scheme->flags & PROTOPT_NONETWORK) { + /* Protocols that work without network cannot be paused. This is + actually only file:// now, and it cannot pause since the transfer is + not done using the "normal" procedure. */ + failf(data, "Write callback asked for PAUSE when not supported"); + return CURLE_WRITE_ERROR; + } + data->req.writer.paused = TRUE; + CURL_TRC_WRITE(data, "[OUT] PAUSE requested by client"); + result = Curl_xfer_pause_recv(data, TRUE); + return result ? result : CURLE_AGAIN; + } + else if(nwritten == CURL_WRITEFUNC_ERROR) { + failf(data, "client returned ERROR on write of %zu bytes", blen); + return CURLE_WRITE_ERROR; + } + else if(nwritten != blen) { + failf(data, "Failure writing output to destination, " + "passed %zu returned %zu", blen, nwritten); + return CURLE_WRITE_ERROR; + } + *pnwritten = nwritten; + return CURLE_OK; +} + +static CURLcode cw_out_ptr_flush(struct cw_out_ctx *ctx, + struct Curl_easy *data, + cw_out_type otype, + bool flush_all, + const char *buf, size_t blen, + size_t *pconsumed) +{ + curl_write_callback wcb = NULL; + void *wcb_data; + size_t max_write, min_write; + size_t wlen, nwritten = 0; + CURLcode result = CURLE_OK; + + /* If we errored once, we do not invoke the client callback again */ + if(ctx->errored) + return CURLE_WRITE_ERROR; + + /* write callbacks may get NULLed by the client between calls. */ + cw_get_writefunc(data, otype, &wcb, &wcb_data, &max_write, &min_write); + if(!wcb) { + *pconsumed = blen; + return CURLE_OK; + } + + *pconsumed = 0; + if(otype == CW_OUT_BODY_0LEN) { + DEBUGASSERT(!blen); + return cw_out_cb_write(data, wcb, wcb_data, otype, + buf, blen, &nwritten); + } + else { + while(blen && !data->req.writer.paused) { + if(!flush_all && blen < min_write) + break; + wlen = max_write ? CURLMIN(blen, max_write) : blen; + if(otype == CW_OUT_BODY) + result = Curl_pgrs_deliver_check(data, wlen); + if(!result) + result = cw_out_cb_write(data, wcb, wcb_data, otype, + buf, wlen, &nwritten); + if(result) + return result; + if(otype == CW_OUT_BODY) + Curl_pgrs_deliver_inc(data, nwritten); + *pconsumed += nwritten; + blen -= nwritten; + buf += nwritten; + } + } + return CURLE_OK; +} + +static CURLcode cw_out_buf_flush(struct cw_out_ctx *ctx, + struct Curl_easy *data, + struct cw_out_buf *cwbuf, + bool flush_all) +{ + CURLcode result = CURLE_OK; + + if(curlx_dyn_len(&cwbuf->b) || (cwbuf->type == CW_OUT_BODY_0LEN)) { + size_t consumed; + + result = cw_out_ptr_flush(ctx, data, cwbuf->type, flush_all, + curlx_dyn_ptr(&cwbuf->b), + curlx_dyn_len(&cwbuf->b), + &consumed); + if(result && (result != CURLE_AGAIN)) + return result; + result = CURLE_OK; + + if(consumed) { + if(consumed == curlx_dyn_len(&cwbuf->b)) { + curlx_dyn_free(&cwbuf->b); + } + else { + DEBUGASSERT(consumed < curlx_dyn_len(&cwbuf->b)); + result = curlx_dyn_tail(&cwbuf->b, + curlx_dyn_len(&cwbuf->b) - consumed); + if(result) + return result; + } + } + } + return result; +} + +static CURLcode cw_out_flush_chain(struct cw_out_ctx *ctx, + struct Curl_easy *data, + struct cw_out_buf **pcwbuf, + bool flush_all) +{ + struct cw_out_buf *cwbuf = *pcwbuf; + CURLcode result; + + if(!cwbuf) + return CURLE_OK; + if(data->req.writer.paused) + return CURLE_OK; + + /* write the end of the chain until it blocks or gets empty */ + while(cwbuf->next) { + struct cw_out_buf **plast = &cwbuf->next; + while((*plast)->next) + plast = &(*plast)->next; + result = cw_out_flush_chain(ctx, data, plast, flush_all); + if(result) + return result; + if(*plast) { + /* could not write last, paused again? */ + DEBUGASSERT(data->req.writer.paused); + return CURLE_OK; + } + } + + result = cw_out_buf_flush(ctx, data, cwbuf, flush_all); + if(result) + return result; + if(!curlx_dyn_len(&cwbuf->b)) { + cw_out_buf_free(cwbuf); + *pcwbuf = NULL; + } + return CURLE_OK; +} + +static CURLcode cw_out_append(struct cw_out_ctx *ctx, + struct Curl_easy *data, + cw_out_type otype, + const char *buf, size_t blen) +{ + CURL_TRC_WRITE(data, "[OUT] paused, buffering %zu more bytes (%zu/%d)", + blen, cw_out_bufs_len(ctx), DYN_PAUSE_BUFFER); + if(cw_out_bufs_len(ctx) + blen > DYN_PAUSE_BUFFER) { + failf(data, "pause buffer not large enough -> CURLE_TOO_LARGE"); + return CURLE_TOO_LARGE; + } + + /* if we do not have a buffer, or it is of another type, make a new one. + * For CW_OUT_HDS always make a new one, so we "replay" headers exactly + * as they came in */ + if(!ctx->buf || (ctx->buf->type != otype) || (otype == CW_OUT_HDS)) { + struct cw_out_buf *cwbuf = cw_out_buf_create(otype); + if(!cwbuf) + return CURLE_OUT_OF_MEMORY; + cwbuf->next = ctx->buf; + ctx->buf = cwbuf; + } + DEBUGASSERT(ctx->buf && (ctx->buf->type == otype)); + return curlx_dyn_addn(&ctx->buf->b, buf, blen); +} + +static CURLcode cw_out_do_write(struct cw_out_ctx *ctx, + struct Curl_easy *data, + cw_out_type otype, + bool flush_all, + const char *buf, size_t blen) +{ + CURLcode result = CURLE_OK; + + /* if we have buffered data and it is a different type than what + * we are writing now, try to flush all */ + if(ctx->buf && ctx->buf->type != otype) { + result = cw_out_flush_chain(ctx, data, &ctx->buf, TRUE); + if(result) + goto out; + } + + if(ctx->buf) { + /* still have buffered data, append and flush */ + result = cw_out_append(ctx, data, otype, buf, blen); + if(result) + goto out; + result = cw_out_flush_chain(ctx, data, &ctx->buf, flush_all); + if(result) + goto out; + } + else { + /* nothing buffered, try direct write */ + size_t consumed; + result = cw_out_ptr_flush(ctx, data, otype, flush_all, + buf, blen, &consumed); + if(result && (result != CURLE_AGAIN)) + return result; + result = CURLE_OK; + if(consumed < blen) { + /* did not write all, append the rest */ + result = cw_out_append(ctx, data, otype, + buf + consumed, blen - consumed); + if(result) + goto out; + } + } + +out: + if(result) { + /* We do not want to invoke client callbacks a second time after + * encountering an error. See issue #13337 */ + ctx->errored = TRUE; + cw_out_bufs_free(ctx); + } + return result; +} + +static CURLcode cw_out_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t blen) +{ + struct cw_out_ctx *ctx = writer->ctx; + CURLcode result; + bool flush_all = !!(type & CLIENTWRITE_EOS); + + if((type & CLIENTWRITE_BODY) || + ((type & CLIENTWRITE_HEADER) && data->set.include_header)) { + cw_out_type otype = (!blen && (type & CLIENTWRITE_0LEN)) ? + CW_OUT_BODY_0LEN : CW_OUT_BODY; + result = cw_out_do_write(ctx, data, otype, flush_all, buf, blen); + if(result) + return result; + } + + if(type & (CLIENTWRITE_HEADER | CLIENTWRITE_INFO)) { + result = cw_out_do_write(ctx, data, CW_OUT_HDS, flush_all, buf, blen); + if(result) + return result; + } + + return CURLE_OK; +} + +static CURLcode cw_out_do_flush(struct Curl_easy *data, + struct Curl_cwriter *cw_out, + bool flush_all) +{ + struct cw_out_ctx *ctx = (struct cw_out_ctx *)cw_out; + + if(ctx->errored) + return CURLE_WRITE_ERROR; + + if(!data->req.writer.paused && ctx->buf) { + CURLcode result; + + CURL_TRC_WRITE(data, "[OUT] flush"); + result = cw_out_flush_chain(ctx, data, &ctx->buf, flush_all); + if(result) { + ctx->errored = TRUE; + cw_out_bufs_free(ctx); + return result; + } + } + return CURLE_OK; +} + +static CURLcode cw_out_flush(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + return cw_out_do_flush(data, writer, FALSE); +} + +const struct Curl_cwtype Curl_cwt_out = { + "cw-out", + NULL, + 0, + cw_out_init, + cw_out_write, + cw_out_flush, + cw_out_close, + sizeof(struct cw_out_ctx) +}; + +CURLcode Curl_cw_out_done(struct Curl_easy *data) +{ + struct Curl_cwriter *cw_out; + CURLcode result = CURLE_OK; + + cw_out = Curl_cwriter_get_by_type(data, &Curl_cwt_out); + if(cw_out) { + CURL_TRC_WRITE(data, "[OUT] done"); + result = Curl_client_flush(data); + if(!result) + result = cw_out_do_flush(data, cw_out, TRUE); + } + return result; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cw-out.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cw-out.h new file mode 100644 index 0000000000..ee2b4b6307 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cw-out.h @@ -0,0 +1,42 @@ +#ifndef HEADER_CURL_CW_OUT_H +#define HEADER_CURL_CW_OUT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct Curl_easy; + +/** + * The client writer type "cw-out" that does the actual writing to + * the client callbacks. Intended to be the last installed in the + * client writer stack of a transfer. + */ +extern const struct Curl_cwtype Curl_cwt_out; + +/** + * Mark EndOfStream reached and flush ALL data to the client. + */ +CURLcode Curl_cw_out_done(struct Curl_easy *data); + +#endif /* HEADER_CURL_CW_OUT_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cw-pause.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cw-pause.c new file mode 100644 index 0000000000..a5b9ba148e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cw-pause.c @@ -0,0 +1,216 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "bufq.h" +#include "cfilters.h" +#include "sendf.h" +#include "curl_trc.h" +#include "cw-pause.h" + + +/* body dynbuf sizes */ +#define CW_PAUSE_BUF_CHUNK (16 * 1024) +/* when content decoding, write data in chunks */ +#define CW_PAUSE_DEC_WRITE_CHUNK 4096 + +struct cw_pause_buf { + struct cw_pause_buf *next; + struct bufq b; + int type; +}; + +static struct cw_pause_buf *cw_pause_buf_create(int type, size_t buflen) +{ + struct cw_pause_buf *cwbuf = curlx_calloc(1, sizeof(*cwbuf)); + if(cwbuf) { + cwbuf->type = type; + if(type & CLIENTWRITE_BODY) + Curl_bufq_init2(&cwbuf->b, CW_PAUSE_BUF_CHUNK, 1, + (BUFQ_OPT_SOFT_LIMIT | BUFQ_OPT_NO_SPARES)); + else + Curl_bufq_init(&cwbuf->b, buflen, 1); + } + return cwbuf; +} + +static void cw_pause_buf_free(struct cw_pause_buf *cwbuf) +{ + if(cwbuf) { + Curl_bufq_free(&cwbuf->b); + curlx_free(cwbuf); + } +} + +struct cw_pause_ctx { + struct Curl_cwriter super; + struct cw_pause_buf *buf; + size_t buf_total; +}; + +static CURLcode cw_pause_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct cw_pause_ctx *ctx = writer->ctx; + (void)data; + ctx->buf = NULL; + return CURLE_OK; +} + +static void cw_pause_bufs_free(struct cw_pause_ctx *ctx) +{ + while(ctx->buf) { + struct cw_pause_buf *next = ctx->buf->next; + cw_pause_buf_free(ctx->buf); + ctx->buf = next; + } +} + +static void cw_pause_close(struct Curl_easy *data, struct Curl_cwriter *writer) +{ + struct cw_pause_ctx *ctx = writer->ctx; + + (void)data; + cw_pause_bufs_free(ctx); +} + +static CURLcode cw_pause_flush(struct Curl_easy *data, + struct Curl_cwriter *cw_pause) +{ + struct cw_pause_ctx *ctx = (struct cw_pause_ctx *)cw_pause; + CURLcode result = CURLE_OK; + + /* write the end of the chain until it blocks or gets empty */ + while(ctx->buf && !Curl_cwriter_is_paused(data)) { + struct cw_pause_buf **plast = &ctx->buf; + size_t blen, wlen = 0; + const unsigned char *buf = NULL; + + while((*plast)->next) /* got to last in list */ + plast = &(*plast)->next; + if(Curl_bufq_peek(&(*plast)->b, &buf, &blen)) { + wlen = ((*plast)->type & CLIENTWRITE_BODY) ? + CURLMIN(blen, CW_PAUSE_DEC_WRITE_CHUNK) : blen; + result = Curl_cwriter_write(data, cw_pause->next, (*plast)->type, + (const char *)buf, wlen); + CURL_TRC_WRITE(data, "[PAUSE] flushed %zu/%zu bytes, type=%x -> %d", + wlen, ctx->buf_total, (unsigned int)(*plast)->type, + (int)result); + Curl_bufq_skip(&(*plast)->b, wlen); + DEBUGASSERT(ctx->buf_total >= wlen); + ctx->buf_total -= wlen; + if(result) + return result; + } + else if((*plast)->type & CLIENTWRITE_EOS) { + result = Curl_cwriter_write(data, cw_pause->next, (*plast)->type, + (const char *)buf, 0); + CURL_TRC_WRITE(data, "[PAUSE] flushed 0/%zu bytes, type=%x -> %d", + ctx->buf_total, (unsigned int)(*plast)->type, + (int)result); + } + + if(Curl_bufq_is_empty(&(*plast)->b)) { + cw_pause_buf_free(*plast); + *plast = NULL; + } + } + + if(!result) + result = Curl_cwriter_flush(data, cw_pause->next); + return result; +} + +static CURLcode cw_pause_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t blen) +{ + struct cw_pause_ctx *ctx = writer->ctx; + CURLcode result = CURLE_OK; + size_t wlen = 0; + + if(ctx->buf && !Curl_cwriter_is_paused(data)) { + result = cw_pause_flush(data, writer); + if(result) + return result; + } + + while(!ctx->buf && !Curl_cwriter_is_paused(data)) { + int wtype = type; + DEBUGASSERT(!ctx->buf); + /* content decoding might blow up size considerably, write smaller + * chunks to make pausing need buffer less. */ + wlen = (type & CLIENTWRITE_BODY) ? + CURLMIN(blen, CW_PAUSE_DEC_WRITE_CHUNK) : blen; + if(wlen < blen) + wtype &= ~CLIENTWRITE_EOS; + result = Curl_cwriter_write(data, writer->next, wtype, buf, wlen); + if(result) + return result; + buf += wlen; + blen -= wlen; + if(!blen) + return result; + } + + do { + size_t nwritten = 0; + if(ctx->buf && (ctx->buf->type == type) && (type & CLIENTWRITE_BODY)) { + /* same type and body, append to current buffer which has a soft + * limit and should take everything up to OOM. */ + result = Curl_bufq_cwrite(&ctx->buf->b, buf, blen, &nwritten); + } + else { + /* Need a new buf, type changed */ + struct cw_pause_buf *cwbuf = cw_pause_buf_create(type, blen); + if(!cwbuf) + return CURLE_OUT_OF_MEMORY; + cwbuf->next = ctx->buf; + ctx->buf = cwbuf; + result = Curl_bufq_cwrite(&ctx->buf->b, buf, blen, &nwritten); + } + CURL_TRC_WRITE(data, "[PAUSE] buffer %zu more bytes of type %x, " + "total=%zu -> %d", nwritten, (unsigned int)type, + ctx->buf_total + wlen, (int)result); + if(result) + return result; + buf += nwritten; + blen -= nwritten; + ctx->buf_total += nwritten; + } while(blen); + + return result; +} + +const struct Curl_cwtype Curl_cwt_pause = { + "cw-pause", + NULL, + 0, + cw_pause_init, + cw_pause_write, + cw_pause_flush, + cw_pause_close, + sizeof(struct cw_pause_ctx) +}; diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/cw-pause.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cw-pause.h new file mode 100644 index 0000000000..9a41a1c9b1 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/cw-pause.h @@ -0,0 +1,36 @@ +#ifndef HEADER_CURL_CW_PAUSE_H +#define HEADER_CURL_CW_PAUSE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct Curl_easy; + +/** + * The client writer type "cw-pause" that buffers writes for + * paused transfer writes. + */ +extern const struct Curl_cwtype Curl_cwt_pause; + +#endif /* HEADER_CURL_CW_PAUSE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/dict.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/dict.c new file mode 100644 index 0000000000..75cdac3714 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/dict.c @@ -0,0 +1,325 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" +#include "dict.h" + +#ifndef CURL_DISABLE_DICT + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NET_IF_H +#include <net/if.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif + +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif + +#ifdef HAVE_SYS_SELECT_H +#include <sys/select.h> +#elif defined(HAVE_UNISTD_H) +#include <unistd.h> +#endif + +#include "transfer.h" +#include "curl_trc.h" +#include "connect.h" +#include "select.h" +#include "escape.h" + +#define DICT_MATCH "/MATCH:" +#define DICT_MATCH2 "/M:" +#define DICT_MATCH3 "/FIND:" +#define DICT_DEFINE "/DEFINE:" +#define DICT_DEFINE2 "/D:" +#define DICT_DEFINE3 "/LOOKUP:" + +#define DYN_DICT_WORD 10000 +static char *unescape_word(const char *input) +{ + struct dynbuf out; + const char *ptr; + CURLcode result = CURLE_OK; + curlx_dyn_init(&out, DYN_DICT_WORD); + + /* According to RFC2229 section 2.2, these letters need to be escaped with + \[letter] */ + for(ptr = input; *ptr; ptr++) { + char ch = *ptr; + if((ch <= 32) || (ch == 127) || + (ch == '\'') || (ch == '\"') || (ch == '\\')) + result = curlx_dyn_addn(&out, "\\", 1); + if(!result) + result = curlx_dyn_addn(&out, ptr, 1); + if(result) + return NULL; + } + return curlx_dyn_ptr(&out); +} + +/* sendf() sends formatted data to the server */ +static CURLcode sendf(struct Curl_easy *data, + const char *fmt, ...) CURL_PRINTF(2, 3); + +static CURLcode sendf(struct Curl_easy *data, const char *fmt, ...) +{ + curl_socket_t sockfd = data->conn->sock[FIRSTSOCKET]; + size_t bytes_written; + size_t write_len; + CURLcode result = CURLE_OK; + timediff_t timeout_ms; + int what; + char *s; + char *sptr; + va_list ap; + va_start(ap, fmt); + s = curl_mvaprintf(fmt, ap); /* returns an allocated string */ + va_end(ap); + if(!s) + return CURLE_OUT_OF_MEMORY; /* failure */ + + bytes_written = 0; + write_len = strlen(s); + sptr = s; + + for(;;) { + /* Write the buffer to the socket */ + result = Curl_xfer_send(data, sptr, write_len, FALSE, &bytes_written); + + if(result) + break; + + Curl_debug(data, CURLINFO_DATA_OUT, sptr, bytes_written); + + if(bytes_written != write_len) { + /* if not all was written at once, we must advance the pointer, decrease + the size left and try again! */ + write_len -= bytes_written; + sptr += bytes_written; + } + else + break; + + timeout_ms = Curl_timeleft_ms(data); + if(timeout_ms < 0) { + result = CURLE_OPERATION_TIMEDOUT; + break; + } + if(!timeout_ms) + timeout_ms = TIMEDIFF_T_MAX; + + /* Do not busyloop. The entire loop thing is a workaround as it causes a + BLOCKING behavior which is a NO-NO. This function should rather be + split up in a do and a doing piece where the pieces that are not + possible to send now will be sent in the doing function repeatedly + until the entire request is sent. */ + what = SOCKET_WRITABLE(sockfd, timeout_ms); + if(what < 0) { + result = CURLE_SEND_ERROR; + break; + } + else if(!what) { + result = CURLE_OPERATION_TIMEDOUT; + break; + } + } + + curlx_free(s); /* free the output string */ + + return result; +} + +static CURLcode dict_do(struct Curl_easy *data, bool *done) +{ + char *word; + char *eword = NULL; + char *ppath; + char *database = NULL; + char *strategy = NULL; + char *nthdef = NULL; /* This is not part of the protocol, but required + by RFC 2229 */ + CURLcode result; + + char *path; + + *done = TRUE; /* unconditionally */ + + /* URL-decode path before further evaluation */ + result = Curl_urldecode(data->state.up.path, 0, &path, NULL, REJECT_CTRL); + if(result) + return result; + + if(curl_strnequal(path, DICT_MATCH, CURL_CSTRLEN(DICT_MATCH)) || + curl_strnequal(path, DICT_MATCH2, CURL_CSTRLEN(DICT_MATCH2)) || + curl_strnequal(path, DICT_MATCH3, CURL_CSTRLEN(DICT_MATCH3))) { + + word = strchr(path, ':'); + if(word) { + word++; + database = strchr(word, ':'); + if(database) { + *database++ = (char)0; + strategy = strchr(database, ':'); + if(strategy) { + *strategy++ = (char)0; + nthdef = strchr(strategy, ':'); + if(nthdef) { + *nthdef = (char)0; + } + } + } + } + + if(!word || (*word == (char)0)) { + infof(data, "lookup word is missing"); + } + eword = unescape_word((!word || (*word == (char)0)) ? "default" : word); + if(!eword) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + result = sendf(data, + "CLIENT " LIBCURL_NAME " " LIBCURL_VERSION "\r\n" + "MATCH " + "%s " /* database */ + "%s " /* strategy */ + "%s\r\n" /* word */ + "QUIT\r\n", + (!database || (*database == (char)0)) ? "!" : database, + (!strategy || (*strategy == (char)0)) ? "." : strategy, + eword); + + if(result) { + failf(data, "Failed sending DICT request"); + goto error; + } + Curl_xfer_setup_recv(data, FIRSTSOCKET, -1); + } + else if(curl_strnequal(path, DICT_DEFINE, CURL_CSTRLEN(DICT_DEFINE)) || + curl_strnequal(path, DICT_DEFINE2, CURL_CSTRLEN(DICT_DEFINE2)) || + curl_strnequal(path, DICT_DEFINE3, CURL_CSTRLEN(DICT_DEFINE3))) { + + word = strchr(path, ':'); + if(word) { + word++; + database = strchr(word, ':'); + if(database) { + *database++ = (char)0; + nthdef = strchr(database, ':'); + if(nthdef) { + *nthdef = (char)0; + } + } + } + + if(!word || (*word == (char)0)) { + infof(data, "lookup word is missing"); + } + eword = unescape_word((!word || (*word == (char)0)) ? "default" : word); + if(!eword) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + result = sendf(data, + "CLIENT " LIBCURL_NAME " " LIBCURL_VERSION "\r\n" + "DEFINE " + "%s " /* database */ + "%s\r\n" /* word */ + "QUIT\r\n", + (!database || (*database == (char)0)) ? "!" : database, + eword); + + if(result) { + failf(data, "Failed sending DICT request"); + goto error; + } + Curl_xfer_setup_recv(data, FIRSTSOCKET, -1); + } + else { + + ppath = strchr(path, '/'); + if(ppath) { + int i; + + ppath++; + for(i = 0; ppath[i]; i++) { + if(ppath[i] == ':') + ppath[i] = ' '; + } + result = sendf(data, + "CLIENT " LIBCURL_NAME " " LIBCURL_VERSION "\r\n" + "%s\r\n" + "QUIT\r\n", ppath); + if(result) { + failf(data, "Failed sending DICT request"); + goto error; + } + + Curl_xfer_setup_recv(data, FIRSTSOCKET, -1); + } + } + +error: + curlx_free(eword); + curlx_free(path); + return result; +} + +/* + * DICT protocol + */ +const struct Curl_protocol Curl_protocol_dict = { + ZERO_NULL, /* setup_connection */ + dict_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_pollset */ + ZERO_NULL, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#endif /* CURL_DISABLE_DICT */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/dict.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/dict.h new file mode 100644 index 0000000000..5bdfcff816 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/dict.h @@ -0,0 +1,30 @@ +#ifndef HEADER_CURL_DICT_H +#define HEADER_CURL_DICT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_DICT +extern const struct Curl_protocol Curl_protocol_dict; +#endif + +#endif /* HEADER_CURL_DICT_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/dllmain.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/dllmain.c new file mode 100644 index 0000000000..5aa6565010 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/dllmain.c @@ -0,0 +1,64 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_OPENSSL +#include <openssl/crypto.h> +#endif + +/* DllMain() must only be defined for Windows DLL builds. */ +#if defined(_WIN32) && !defined(CURL_STATICLIB) + +#if defined(USE_OPENSSL) && \ + !defined(OPENSSL_IS_AWSLC) && !defined(OPENSSL_IS_BORINGSSL) && \ + !defined(LIBRESSL_VERSION_NUMBER) +#define PREVENT_OPENSSL_MEMLEAK +#endif + +#ifdef PREVENT_OPENSSL_MEMLEAK +BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved); +BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) +{ + (void)hinstDLL; + (void)lpvReserved; + + switch(fdwReason) { + case DLL_PROCESS_ATTACH: + break; + case DLL_PROCESS_DETACH: + break; + case DLL_THREAD_ATTACH: + break; + case DLL_THREAD_DETACH: + /* Call OPENSSL_thread_stop to prevent a memory leak in case OpenSSL is + linked statically. + https://github.com/curl/curl/issues/12327#issuecomment-1826405944 */ + OPENSSL_thread_stop(); + break; + } + return TRUE; +} +#endif /* USE_OPENSSL (non-fork) */ + +#endif /* _WIN32 && !CURL_STATICLIB */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/dynhds.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/dynhds.c new file mode 100644 index 0000000000..097306cec9 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/dynhds.c @@ -0,0 +1,385 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "dynhds.h" +#include "strcase.h" + +static struct dynhds_entry *entry_new(const char *name, size_t namelen, + const char *value, size_t valuelen, + int opts) +{ + struct dynhds_entry *e; + char *p; + + DEBUGASSERT(name); + DEBUGASSERT(value); + e = curlx_calloc(1, sizeof(*e) + namelen + valuelen + 2); + if(!e) + return NULL; + e->name = p = (char *)e + sizeof(*e); + memcpy(p, name, namelen); + e->namelen = namelen; + e->value = p += namelen + 1; /* leave a \0 at the end of name */ + memcpy(p, value, valuelen); + e->valuelen = valuelen; + if(opts & DYNHDS_OPT_LOWERCASE) + Curl_strntolower(e->name, e->name, e->namelen); + return e; +} + +static void entry_free(struct dynhds_entry *e) +{ + curlx_free(e); +} + +void Curl_dynhds_init(struct dynhds *dynhds, size_t max_entries, + size_t max_strs_size) +{ + DEBUGASSERT(dynhds); + DEBUGASSERT(max_strs_size); + dynhds->hds = NULL; + dynhds->hds_len = dynhds->hds_allc = dynhds->strs_len = 0; + dynhds->max_entries = max_entries; + dynhds->max_strs_size = max_strs_size; + dynhds->opts = 0; +} + +void Curl_dynhds_free(struct dynhds *dynhds) +{ + DEBUGASSERT(dynhds); + if(dynhds->hds && dynhds->hds_len) { + size_t i; + DEBUGASSERT(dynhds->hds); + for(i = 0; i < dynhds->hds_len; ++i) { + entry_free(dynhds->hds[i]); + } + } + curlx_safefree(dynhds->hds); + dynhds->hds_len = dynhds->hds_allc = dynhds->strs_len = 0; +} + +void Curl_dynhds_reset(struct dynhds *dynhds) +{ + DEBUGASSERT(dynhds); + if(dynhds->hds_len) { + size_t i; + DEBUGASSERT(dynhds->hds); + for(i = 0; i < dynhds->hds_len; ++i) { + entry_free(dynhds->hds[i]); + dynhds->hds[i] = NULL; + } + } + dynhds->hds_len = dynhds->strs_len = 0; +} + +size_t Curl_dynhds_count(struct dynhds *dynhds) +{ + return dynhds->hds_len; +} + +void Curl_dynhds_set_opts(struct dynhds *dynhds, int opts) +{ + dynhds->opts = opts; +} + +struct dynhds_entry *Curl_dynhds_getn(struct dynhds *dynhds, size_t n) +{ + DEBUGASSERT(dynhds); + return (n < dynhds->hds_len) ? dynhds->hds[n] : NULL; +} + +struct dynhds_entry *Curl_dynhds_get(struct dynhds *dynhds, const char *name, + size_t namelen) +{ + size_t i; + for(i = 0; i < dynhds->hds_len; ++i) { + if(dynhds->hds[i]->namelen == namelen && + curl_strnequal(dynhds->hds[i]->name, name, namelen)) { + return dynhds->hds[i]; + } + } + return NULL; +} + +struct dynhds_entry *Curl_dynhds_cget(struct dynhds *dynhds, const char *name) +{ + return Curl_dynhds_get(dynhds, name, strlen(name)); +} + +CURLcode Curl_dynhds_add(struct dynhds *dynhds, + const char *name, size_t namelen, + const char *value, size_t valuelen) +{ + struct dynhds_entry *entry = NULL; + CURLcode result = CURLE_OUT_OF_MEMORY; + + DEBUGASSERT(dynhds); + if(dynhds->max_entries && dynhds->hds_len >= dynhds->max_entries) + return CURLE_OUT_OF_MEMORY; + if(dynhds->strs_len + namelen + valuelen > dynhds->max_strs_size) + return CURLE_OUT_OF_MEMORY; + + entry = entry_new(name, namelen, value, valuelen, dynhds->opts); + if(!entry) + goto out; + + if(dynhds->hds_len + 1 >= dynhds->hds_allc) { + size_t nallc = dynhds->hds_len + 16; + struct dynhds_entry **nhds; + + if(dynhds->max_entries && nallc > dynhds->max_entries) + nallc = dynhds->max_entries; + + nhds = curlx_calloc(nallc, sizeof(struct dynhds_entry *)); + if(!nhds) + goto out; + if(dynhds->hds) { + memcpy(nhds, dynhds->hds, + dynhds->hds_len * sizeof(struct dynhds_entry *)); + curlx_safefree(dynhds->hds); + } + dynhds->hds = nhds; + dynhds->hds_allc = nallc; + } + dynhds->hds[dynhds->hds_len++] = entry; + entry = NULL; + dynhds->strs_len += namelen + valuelen; + result = CURLE_OK; + +out: + if(entry) + entry_free(entry); + return result; +} + +CURLcode Curl_dynhds_cadd(struct dynhds *dynhds, + const char *name, const char *value) +{ + return Curl_dynhds_add(dynhds, name, strlen(name), value, strlen(value)); +} + +CURLcode Curl_dynhds_h1_add_line(struct dynhds *dynhds, + const char *line, size_t line_len) +{ + const char *p; + const char *name; + size_t namelen; + const char *value; + size_t valuelen, i; + + if(!line || !line_len) + return CURLE_OK; + + p = memchr(line, ':', line_len); + if(!p) + return CURLE_BAD_FUNCTION_ARGUMENT; + name = line; + namelen = p - line; + p++; /* move past the colon */ + for(i = namelen + 1; i < line_len; ++i, ++p) { + if(!ISBLANK(*p)) + break; + } + value = p; + valuelen = line_len - i; + + p = memchr(value, '\r', valuelen); + if(!p) + p = memchr(value, '\n', valuelen); + if(p) + valuelen = (size_t)(p - value); + + return Curl_dynhds_add(dynhds, name, namelen, value, valuelen); +} + +CURLcode Curl_dynhds_h1_cadd_line(struct dynhds *dynhds, const char *line) +{ + return Curl_dynhds_h1_add_line(dynhds, line, line ? strlen(line) : 0); +} + +#ifdef UNITTESTS +/* @unittest 2602 */ + +/** + * Return TRUE iff one or more headers with the given name exist. + */ +UNITTEST bool dynhds_contains(struct dynhds *dynhds, + const char *name, size_t namelen); +UNITTEST bool dynhds_contains(struct dynhds *dynhds, + const char *name, size_t namelen) +{ + return !!Curl_dynhds_get(dynhds, name, namelen); +} + +/* @unittest 2602 */ +UNITTEST bool dynhds_ccontains(struct dynhds *dynhds, const char *name); +UNITTEST bool dynhds_ccontains(struct dynhds *dynhds, const char *name) +{ + return dynhds_contains(dynhds, name, strlen(name)); +} + +/** + * Return how often the given name appears in `dynhds`. + * Names are case-insensitive. + * + * @unittest 2602 + */ +UNITTEST size_t dynhds_count_name(struct dynhds *dynhds, + const char *name, size_t namelen); +UNITTEST size_t dynhds_count_name(struct dynhds *dynhds, + const char *name, size_t namelen) +{ + size_t n = 0; + if(dynhds->hds_len) { + size_t i; + for(i = 0; i < dynhds->hds_len; ++i) { + if((namelen == dynhds->hds[i]->namelen) && + curl_strnequal(name, dynhds->hds[i]->name, namelen)) + ++n; + } + } + return n; +} + +/** + * Return how often the given null-terminated name appears in `dynhds`. + * Names are case-insensitive. + * + * @unittest 2602 + */ +UNITTEST size_t dynhds_ccount_name(struct dynhds *dynhds, + const char *name); +UNITTEST size_t dynhds_ccount_name(struct dynhds *dynhds, + const char *name) +{ + return dynhds_count_name(dynhds, name, strlen(name)); +} + +/** + * Remove all entries with the given name. + * Returns number of entries removed. + * + * @unittest 2602 + */ +UNITTEST size_t dynhds_remove(struct dynhds *dynhds, + const char *name, size_t namelen); +UNITTEST size_t dynhds_remove(struct dynhds *dynhds, + const char *name, size_t namelen) +{ + size_t n = 0; + if(dynhds->hds_len) { + size_t i, len; + for(i = 0; i < dynhds->hds_len; ++i) { + if((namelen == dynhds->hds[i]->namelen) && + curl_strnequal(name, dynhds->hds[i]->name, namelen)) { + ++n; + --dynhds->hds_len; + dynhds->strs_len -= (dynhds->hds[i]->namelen + + dynhds->hds[i]->valuelen); + entry_free(dynhds->hds[i]); + len = dynhds->hds_len - i; /* remaining entries */ + if(len) { + memmove(&dynhds->hds[i], &dynhds->hds[i + 1], + len * sizeof(dynhds->hds[i])); + } + --i; /* do this index again */ + } + } + } + return n; +} + +/** + * Set the give header name and value, replacing any entries with + * the same name. The header is added at the end of all (remaining) + * entries. + * + * @unittest 2602 + */ +UNITTEST CURLcode dynhds_set(struct dynhds *dynhds, + const char *name, size_t namelen, + const char *value, size_t valuelen); +UNITTEST CURLcode dynhds_set(struct dynhds *dynhds, + const char *name, size_t namelen, + const char *value, size_t valuelen) +{ + dynhds_remove(dynhds, name, namelen); + return Curl_dynhds_add(dynhds, name, namelen, value, valuelen); +} + +/* @unittest 2602 */ +UNITTEST size_t dynhds_cremove(struct dynhds *dynhds, const char *name); +UNITTEST size_t dynhds_cremove(struct dynhds *dynhds, const char *name) +{ + return dynhds_remove(dynhds, name, strlen(name)); +} + +#endif /* UNITTESTS */ + +CURLcode Curl_dynhds_h1_dprint(struct dynhds *dynhds, struct dynbuf *dbuf) +{ + CURLcode result = CURLE_OK; + size_t i; + + if(!dynhds->hds_len) + return result; + + for(i = 0; i < dynhds->hds_len; ++i) { + result = curlx_dyn_addf(dbuf, "%.*s: %.*s\r\n", + (int)dynhds->hds[i]->namelen, dynhds->hds[i]->name, + (int)dynhds->hds[i]->valuelen, + dynhds->hds[i]->value); + if(result) + break; + } + + return result; +} + +#ifdef USE_NGHTTP2 + +nghttp2_nv *Curl_dynhds_to_nva(struct dynhds *dynhds, size_t *pcount) +{ + nghttp2_nv *nva = curlx_calloc(1, sizeof(nghttp2_nv) * dynhds->hds_len); + size_t i; + + *pcount = 0; + if(!nva) + return NULL; + + for(i = 0; i < dynhds->hds_len; ++i) { + struct dynhds_entry *e = dynhds->hds[i]; + DEBUGASSERT(e); + nva[i].name = (unsigned char *)e->name; + nva[i].namelen = e->namelen; + nva[i].value = (unsigned char *)e->value; + nva[i].valuelen = e->valuelen; + nva[i].flags = NGHTTP2_NV_FLAG_NONE; + } + *pcount = dynhds->hds_len; + return nva; +} + +#endif /* USE_NGHTTP2 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/dynhds.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/dynhds.h new file mode 100644 index 0000000000..d5337eb353 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/dynhds.h @@ -0,0 +1,141 @@ +#ifndef HEADER_CURL_DYNHDS_H +#define HEADER_CURL_DYNHDS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curlx/dynbuf.h" + +struct dynbuf; + +/** + * A single header entry. + * `name` and `value` are non-NULL and always null-terminated. + */ +struct dynhds_entry { + char *name; + char *value; + size_t namelen; + size_t valuelen; +}; + +struct dynhds { + struct dynhds_entry **hds; + size_t hds_len; /* number of entries in hds */ + size_t hds_allc; /* size of hds allocation */ + size_t max_entries; /* size limit number of entries */ + size_t strs_len; /* length of all strings */ + size_t max_strs_size; /* max length of all strings */ + int opts; +}; + +#define DYNHDS_OPT_NONE 0 +#define DYNHDS_OPT_LOWERCASE (1 << 0) + +/** + * Init for use on first time or after a reset. + * Allow `max_entries` headers to be added, 0 for unlimited. + * Allow size of all name and values added to not exceed `max_strs_size`` + */ +void Curl_dynhds_init(struct dynhds *dynhds, size_t max_entries, + size_t max_strs_size); +/** + * Frees all data held in `dynhds`, but not the struct itself. + */ +void Curl_dynhds_free(struct dynhds *dynhds); + +/** + * Reset `dyndns` to the initial init state. May keep allocations + * around. + */ +void Curl_dynhds_reset(struct dynhds *dynhds); + +/** + * Return the number of header entries. + */ +size_t Curl_dynhds_count(struct dynhds *dynhds); + +/** + * Set the options to use, replacing any existing ones. + * This will not have an effect on already existing headers. + */ +void Curl_dynhds_set_opts(struct dynhds *dynhds, int opts); + +/** + * Return the n-th header entry or NULL if it does not exist. + */ +struct dynhds_entry *Curl_dynhds_getn(struct dynhds *dynhds, size_t n); + +/** + * Return the 1st header entry of the name or NULL if none exists. + */ +struct dynhds_entry *Curl_dynhds_get(struct dynhds *dynhds, + const char *name, size_t namelen); +struct dynhds_entry *Curl_dynhds_cget(struct dynhds *dynhds, const char *name); + +CURLcode Curl_dynhds_cset(struct dynhds *dynhds, + const char *name, const char *value); + +/** + * Add a header, name + value, to `dynhds` at the end. Does *not* + * check for duplicate names. + */ +CURLcode Curl_dynhds_add(struct dynhds *dynhds, + const char *name, size_t namelen, + const char *value, size_t valuelen); + +/** + * Add a header, c-string name + value, to `dynhds` at the end. + */ +CURLcode Curl_dynhds_cadd(struct dynhds *dynhds, + const char *name, const char *value); + +/** + * Add a single header from an HTTP/1.1 formatted line at the end. Line may + * contain a delimiting CRLF or LF. Any characters after that will be ignored. + */ +CURLcode Curl_dynhds_h1_cadd_line(struct dynhds *dynhds, const char *line); + +/** + * Add a single header from an HTTP/1.1 formatted line at the end. Line may + * contain a delimiting CRLF or LF. Any characters after that will be ignored. + */ +CURLcode Curl_dynhds_h1_add_line(struct dynhds *dynhds, + const char *line, size_t line_len); + +/** + * Add the headers to the given `dynbuf` in HTTP/1.1 format with + * CR+LF line endings. Does NOT output a last empty line. + */ +CURLcode Curl_dynhds_h1_dprint(struct dynhds *dynhds, struct dynbuf *dbuf); + +#ifdef USE_NGHTTP2 + +#include <nghttp2/nghttp2.h> + +nghttp2_nv *Curl_dynhds_to_nva(struct dynhds *dynhds, size_t *pcount); + +#endif /* USE_NGHTTP2 */ + +#endif /* HEADER_CURL_DYNHDS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/easy.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/easy.c new file mode 100644 index 0000000000..04c5a003a0 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/easy.c @@ -0,0 +1,1444 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NET_IF_H +#include <net/if.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif + +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif + +#include "urldata.h" +#include "api.h" +#include "transfer.h" +#include "vdns/hostip.h" +#include "vtls/vtls.h" +#include "vtls/vtls_scache.h" +#include "vquic/vquic.h" +#include "url.h" +#include "getinfo.h" +#include "curlx/strdup.h" +#include "easyif.h" +#include "multiif.h" +#include "multi_ev.h" +#include "select.h" +#include "cfilters.h" +#include "sendf.h" +#include "curl_trc.h" +#include "connect.h" /* for Curl_getconnectinfo */ +#include "slist.h" +#include "mime.h" +#include "amigaos.h" +#include "macos.h" +#include "curlx/wait.h" +#include "sigpipe.h" +#include "vssh/ssh.h" +#include "setopt.h" +#include "http_digest.h" +#include "system_win32.h" +#include "curlx/dynbuf.h" +#include "bufref.h" +#include "altsvc.h" +#include "hsts.h" + +#include "easy_lock.h" + +/* true globals -- for curl_global_init() and curl_global_cleanup() */ +static unsigned int initialized; +#ifdef _WIN32 +static long easy_init_flags; +#endif + +#ifdef GLOBAL_INIT_IS_THREADSAFE + +static curl_simple_lock s_lock = CURL_SIMPLE_LOCK_INIT; +#define global_init_lock() curl_simple_lock_lock(&s_lock) +#define global_init_unlock() curl_simple_lock_unlock(&s_lock) + +#else + +#define global_init_lock() +#define global_init_unlock() + +#endif + +#if defined(_MSC_VER) && defined(_DLL) +# pragma warning(push) +# pragma warning(disable:4232) /* MSVC extension, dllimport identity */ +#endif + +/* + * If a memory-using function (like curl_getenv) is used before + * curl_global_init() is called, we need to have these pointers set already. + */ +curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc; +curl_free_callback Curl_cfree = (curl_free_callback)free; +curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc; +curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)CURLX_STRDUP_LOW; +curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc; + +#if defined(_MSC_VER) && defined(_DLL) +# pragma warning(pop) +#endif + +#ifdef DEBUGBUILD +static char *leakpointer; +#endif + +/** + * curl_global_init() globally initializes curl given a bitwise set of the + * different features of what to initialize. + */ +static CURLcode global_init(long flags, bool memoryfuncs) +{ + if(initialized++) + return CURLE_OK; + + if(memoryfuncs) { + /* Setup the default memory functions here (again) */ + Curl_cmalloc = (curl_malloc_callback)malloc; + Curl_cfree = (curl_free_callback)free; + Curl_crealloc = (curl_realloc_callback)realloc; + Curl_cstrdup = (curl_strdup_callback)CURLX_STRDUP_LOW; + Curl_ccalloc = (curl_calloc_callback)calloc; + } + + if(Curl_win32_init(flags)) { + DEBUGF(curl_mfprintf(stderr, "Error: win32_init failed\n")); + goto fail; + } + + if(Curl_trc_init()) { + DEBUGF(curl_mfprintf(stderr, "Error: Curl_trc_init failed\n")); + goto fail; + } + + if(!Curl_ssl_init()) { + DEBUGF(curl_mfprintf(stderr, "Error: Curl_ssl_init failed\n")); + goto fail; + } + + if(!Curl_vquic_init()) { + DEBUGF(curl_mfprintf(stderr, "Error: Curl_vquic_init failed\n")); + goto fail; + } + + if(Curl_amiga_init()) { + DEBUGF(curl_mfprintf(stderr, "Error: Curl_amiga_init failed\n")); + goto fail; + } + + if(Curl_macos_init()) { + DEBUGF(curl_mfprintf(stderr, "Error: Curl_macos_init failed\n")); + goto fail; + } + + if(Curl_async_global_init()) { + DEBUGF(curl_mfprintf(stderr, "Error: Curl_async_global_init failed\n")); + goto fail; + } + + if(Curl_ssh_init()) { + DEBUGF(curl_mfprintf(stderr, "Error: Curl_ssh_init failed\n")); + goto fail; + } + +#ifdef _WIN32 + easy_init_flags = flags; +#else + (void)flags; +#endif + +#ifdef DEBUGBUILD + if(getenv("CURL_GLOBAL_INIT")) + /* alloc data that will leak if *cleanup() is not called! */ + leakpointer = curlx_malloc(1); +#endif + + return CURLE_OK; + +fail: + initialized--; /* undo the increase */ + return CURLE_FAILED_INIT; +} + +/** + * curl_global_init() globally initializes curl given a bitwise set of the + * different features of what to initialize. + */ +CURLcode curl_global_init(long flags) +{ + CURLcode result; + global_init_lock(); + + result = global_init(flags, TRUE); + + global_init_unlock(); + + return result; +} + +/* + * curl_global_init_mem() globally initializes curl and also registers the + * user provided callback routines. + */ +CURLcode curl_global_init_mem(long flags, curl_malloc_callback m, + curl_free_callback f, curl_realloc_callback r, + curl_strdup_callback s, curl_calloc_callback c) +{ + CURLcode result; + + /* Invalid input, return immediately */ + if(!m || !f || !r || !s || !c) + return CURLE_FAILED_INIT; + + global_init_lock(); + + if(initialized) { + /* Already initialized, do not do it again, but bump the variable anyway to + work like curl_global_init() and require the same amount of cleanup + calls. */ + initialized++; + global_init_unlock(); + return CURLE_OK; + } + + /* set memory functions before global_init() in case it wants memory + functions */ + Curl_cmalloc = m; + Curl_cfree = f; + Curl_cstrdup = s; + Curl_crealloc = r; + Curl_ccalloc = c; + + /* Call the actual init function, but without setting */ + result = global_init(flags, FALSE); + + global_init_unlock(); + + return result; +} + +/** + * curl_global_cleanup() globally cleanups curl, uses the value of + * "easy_init_flags" to determine what needs to be cleaned up and what does + * not. + */ +void curl_global_cleanup(void) +{ + global_init_lock(); + + if(!initialized) { + global_init_unlock(); + return; + } + + if(--initialized) { + global_init_unlock(); + return; + } + + Curl_ssl_cleanup(); + Curl_vquic_cleanup(); + Curl_async_global_cleanup(); + +#ifdef _WIN32 + Curl_win32_cleanup(easy_init_flags); + easy_init_flags = 0; +#endif + + Curl_amiga_cleanup(); + + Curl_ssh_cleanup(); + +#ifdef DEBUGBUILD + curlx_free(leakpointer); +#endif + + global_init_unlock(); +} + +/** + * curl_global_trace() globally initializes curl logging. + */ +CURLcode curl_global_trace(const char *config) +{ +#ifndef CURL_DISABLE_VERBOSE_STRINGS + CURLcode result; + global_init_lock(); + + result = Curl_trc_opt(config); + + global_init_unlock(); + + return result; +#else + (void)config; + return CURLE_OK; +#endif +} + +/* + * curl_global_sslset() globally initializes the SSL backend to use. + */ +CURLsslset curl_global_sslset(curl_sslbackend id, const char *name, + const curl_ssl_backend ***avail) +{ + CURLsslset rc; + + global_init_lock(); + + rc = Curl_init_sslset_nolock(id, name, avail); + + global_init_unlock(); + + return rc; +} + +/* + * curl_easy_init() is the external interface to alloc, setup and init an + * easy handle that is returned. If anything goes wrong, NULL is returned. + */ +CURL *curl_easy_init(void) +{ + CURLcode result; + struct Curl_easy *data; + + /* Make sure we inited the global SSL stuff */ + global_init_lock(); + + if(!initialized) { + result = global_init(CURL_GLOBAL_DEFAULT, TRUE); + if(result) { + /* something in the global init failed, return nothing */ + DEBUGF(curl_mfprintf(stderr, "Error: curl_global_init failed\n")); + global_init_unlock(); + return NULL; + } + } + global_init_unlock(); + + /* We use Curl_open() with undefined URL so far */ + result = Curl_open(&data); + if(result) { + DEBUGF(curl_mfprintf(stderr, "Error: Curl_open failed\n")); + return NULL; + } + + return data; +} + +#ifdef DEBUGBUILD + +struct socketmonitor { + struct socketmonitor *next; /* the next node in the list or NULL */ + struct pollfd socket; /* socket info of what to monitor */ +}; + +struct events { + long ms; /* timeout, run the timeout function when reached */ + bool msbump; /* set TRUE when timeout is set by callback */ + int num_sockets; /* number of nodes in the monitor list */ + struct socketmonitor *list; /* list of sockets to monitor */ + int running_handles; /* store the returned number */ +}; + +#define DEBUG_EV_POLL 0 + +/* events_timer + * + * Callback that gets called with a new value when the timeout should be + * updated. + */ +static int events_timer(CURLM *multi, /* multi handle */ + long timeout_ms, /* see above */ + void *userp) /* private callback pointer */ +{ + struct events *ev = userp; + (void)multi; +#if DEBUG_EV_POLL + curl_mfprintf(stderr, "events_timer: set timeout %ldms\n", timeout_ms); +#endif + ev->ms = timeout_ms; + ev->msbump = TRUE; + return 0; +} + +/* poll2cselect + * + * convert from poll() bit definitions to libcurl's CURL_CSELECT_* ones + */ +static int poll2cselect(int pollmask) +{ + int omask = 0; + if(pollmask & POLLIN) + omask |= CURL_CSELECT_IN; + if(pollmask & POLLOUT) + omask |= CURL_CSELECT_OUT; + if(pollmask & POLLERR) + omask |= CURL_CSELECT_ERR; + return omask; +} + +/* socketcb2poll + * + * convert from libcurl' CURL_POLL_* bit definitions to poll()'s + */ +static short socketcb2poll(int pollmask) +{ + short omask = 0; + if(pollmask & CURL_POLL_IN) + omask |= POLLIN; + if(pollmask & CURL_POLL_OUT) + omask |= POLLOUT; + return omask; +} + +/* events_socket + * + * Callback that gets called with information about socket activity to + * monitor. + */ +static int events_socket(CURL *easy, /* easy handle */ + curl_socket_t s, /* socket */ + int what, /* see above */ + void *userp, /* private callback + pointer */ + void *socketp) /* private socket + pointer */ +{ + struct events *ev = userp; + struct socketmonitor *m; + struct socketmonitor *prev = NULL; + bool found = FALSE; + struct Curl_easy *data = easy; + +#ifdef CURL_DISABLE_VERBOSE_STRINGS + (void)easy; +#endif + (void)socketp; + + m = ev->list; + while(m) { + if(m->socket.fd == s) { + found = TRUE; + if(what == CURL_POLL_REMOVE) { + struct socketmonitor *nxt = m->next; + /* remove this node from the list of monitored sockets */ + if(prev) + prev->next = nxt; + else + ev->list = nxt; + curlx_free(m); + infof(data, "socket cb: socket %" FMT_SOCKET_T " REMOVED", s); + } + else { + /* The socket 's' is already being monitored, update the activity + mask. Convert from libcurl bitmask to the poll one. */ + m->socket.events = socketcb2poll(what); + infof(data, "socket cb: socket %" FMT_SOCKET_T " UPDATED as %s%s", s, + (what & CURL_POLL_IN) ? "IN" : "", + (what & CURL_POLL_OUT) ? "OUT" : ""); + } + break; + } + prev = m; + m = m->next; /* move to next node */ + } + + if(!found) { + if(what == CURL_POLL_REMOVE) { + /* should not happen if our logic is correct, but is no drama. */ + DEBUGF(infof(data, "socket cb: asked to REMOVE socket %" + FMT_SOCKET_T "but not present!", s)); + DEBUGASSERT(0); + } + else { + m = curlx_malloc(sizeof(struct socketmonitor)); + if(m) { + m->next = ev->list; + m->socket.fd = s; + m->socket.events = socketcb2poll(what); + m->socket.revents = 0; + ev->list = m; + infof(data, "socket cb: socket %" FMT_SOCKET_T " ADDED as %s%s", s, + (what & CURL_POLL_IN) ? "IN" : "", + (what & CURL_POLL_OUT) ? "OUT" : ""); + } + else + return CURLE_OUT_OF_MEMORY; + } + } + + return 0; +} + +/* + * events_setup() + * + * Do the multi handle setups that only event-based transfers need. + */ +static void events_setup(struct Curl_multi *multi, struct events *ev) +{ + /* timer callback */ + curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, events_timer); + curl_multi_setopt(multi, CURLMOPT_TIMERDATA, ev); + + /* socket callback */ + curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, events_socket); + curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, ev); +} + +/* populate_fds() + * + * populate the fds[] array + */ +static unsigned int populate_fds(struct pollfd *fds, struct events *ev) +{ + unsigned int numfds = 0; + struct pollfd *f; + struct socketmonitor *m; + + f = &fds[0]; + for(m = ev->list; m; m = m->next) { + f->fd = m->socket.fd; + f->events = m->socket.events; + f->revents = 0; +#if DEBUG_EV_POLL + curl_mfprintf(stderr, "poll() %d check socket %d\n", numfds, f->fd); +#endif + f++; + numfds++; + } + return numfds; +} + +/* poll_fds() + * + * poll the fds[] array + */ +static CURLcode poll_fds(struct events *ev, + struct pollfd *fds, + const unsigned int numfds, + int *pollrc) +{ + if(numfds) { + /* wait for activity or timeout */ +#if DEBUG_EV_POLL + curl_mfprintf(stderr, "poll(numfds=%u, timeout=%ldms)\n", numfds, ev->ms); +#endif + *pollrc = Curl_poll(fds, numfds, ev->ms); +#if DEBUG_EV_POLL + curl_mfprintf(stderr, "poll(numfds=%u, timeout=%ldms) -> %d\n", + numfds, ev->ms, *pollrc); +#endif + if(*pollrc < 0) + return CURLE_UNRECOVERABLE_POLL; + } + else { +#if DEBUG_EV_POLL + curl_mfprintf(stderr, "poll, but no fds, wait timeout=%ldms\n", ev->ms); +#endif + *pollrc = 0; + if(ev->ms > 0) + curlx_wait_ms(ev->ms); + } + return CURLE_OK; +} + +/* wait_or_timeout() + * + * waits for activity on any of the given sockets, or the timeout to trigger. + */ +static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev) +{ + bool done = FALSE; + CURLMcode mresult = CURLM_OK; + CURLcode result = CURLE_OK; + + while(!done) { + CURLMsg *msg; + struct pollfd fds[4]; + int pollrc; + struct curltime start; + const unsigned int numfds = populate_fds(fds, ev); + + /* get the time stamp to use to figure out how long poll takes */ + curlx_pnow(&start); + + result = poll_fds(ev, fds, numfds, &pollrc); + if(result) + return result; + + ev->msbump = FALSE; /* reset here */ + + if(!pollrc) { + /* timeout! */ + ev->ms = 0; +#if 0 + curl_mfprintf(stderr, "call curl_multi_socket_action(TIMEOUT)\n"); +#endif + mresult = curl_multi_socket_action(multi, CURL_SOCKET_TIMEOUT, 0, + &ev->running_handles); + } + else { + /* here pollrc is > 0 */ + /* loop over the monitored sockets to see which ones had activity */ + unsigned int i; + for(i = 0; i < numfds; i++) { + if(fds[i].revents) { + /* socket activity, tell libcurl */ + int act = poll2cselect(fds[i].revents); /* convert */ + + /* sending infof "randomly" to the first easy handle */ + infof(multi->admin, "call curl_multi_socket_action(socket " + "%" FMT_SOCKET_T ")", (curl_socket_t)fds[i].fd); + mresult = curl_multi_socket_action(multi, fds[i].fd, act, + &ev->running_handles); + } + } + + if(!ev->msbump && ev->ms >= 0) { + /* If nothing updated the timeout, we decrease it by the spent time. + * If it was updated, it has the new timeout time stored already. + */ + timediff_t spent_ms = curlx_timediff_ms(curlx_now(), start); + if(spent_ms > 0) { +#if DEBUG_EV_POLL + curl_mfprintf(stderr, "poll timeout %ldms not updated, decrease by " + "time spent %ldms\n", ev->ms, (long)spent_ms); +#endif + if(spent_ms > ev->ms) + ev->ms = 0; + else + ev->ms -= (long)spent_ms; + } + } + } + + if(mresult) + return CURLE_URL_MALFORMAT; + + /* we do not really care about the "msgs_in_queue" value returned in the + second argument */ + msg = curl_multi_info_read(multi, &pollrc); + if(msg) { + result = msg->data.result; + done = TRUE; + } + } + + return result; +} + +/* easy_events() + * + * Runs a transfer in a blocking manner using the events-based API + */ +static CURLcode easy_events(struct Curl_multi *multi) +{ + /* this struct is made static to allow it to be used after this function + returns and curl_multi_remove_handle() is called */ + static struct events evs = { -1, FALSE, 0, NULL, 0 }; + + /* if running event-based, do some further multi inits */ + events_setup(multi, &evs); + + return wait_or_timeout(multi, &evs); +} +#else /* DEBUGBUILD */ +/* when not built with debug, this function does not exist */ +#define easy_events(x) CURLE_NOT_BUILT_IN +#endif + +static CURLcode easy_transfer(struct Curl_multi *multi) +{ + bool done = FALSE; + CURLMcode mresult = CURLM_OK; + CURLcode result = CURLE_OK; + + while(!done && !mresult) { + int still_running = 0; + + mresult = curl_multi_poll(multi, NULL, 0, 1000, NULL); + + if(!mresult) + mresult = curl_multi_perform(multi, &still_running); + + /* only read 'still_running' if curl_multi_perform() return OK */ + if(!mresult && !still_running) { + int rc; + CURLMsg *msg = curl_multi_info_read(multi, &rc); + if(msg) { + result = msg->data.result; + done = TRUE; + } + } + } + + /* Make sure to return some kind of error if there was a multi problem */ + if(mresult) { + result = (mresult == CURLM_OUT_OF_MEMORY) ? CURLE_OUT_OF_MEMORY : + /* The other multi errors should never happen, so return + something suitably generic */ + CURLE_BAD_FUNCTION_ARGUMENT; + } + + return result; +} + +/* + * easy_perform() is the internal interface that performs a blocking + * transfer as previously setup. + * + * CONCEPT: This function creates a multi handle, adds the easy handle to it, + * runs curl_multi_perform() until the transfer is done, then detaches the + * easy handle, destroys the multi handle and returns the easy handle's return + * code. + * + * REALITY: it cannot create and destroy the multi handle that easily. It + * needs to keep it around since if this easy handle is used again by this + * function, the same multi handle must be reused so that the same pools and + * caches can be used. + * + * DEBUG: if 'events' is set TRUE, this function will use a replacement engine + * instead of curl_multi_perform() and use curl_multi_socket_action(). + */ +static CURLcode easy_perform(struct Curl_easy *data, bool events) +{ + struct Curl_multi *multi; + CURLMcode mresult; + CURLcode result = CURLE_OK; + struct Curl_sigpipe_ctx sigpipe_ctx; + + if(!data) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(data->set.errorbuffer) + /* clear this as early as possible */ + data->set.errorbuffer[0] = 0; + + data->state.os_errno = 0; + + if(data->multi) { + failf(data, "easy handle already used in multi handle"); + return CURLE_FAILED_INIT; + } + + /* if the handle has a connection still attached (it is/was a connect-only + handle) then disconnect before performing */ + if(data->conn) { + struct connectdata *conn = data->conn; + Curl_detach_connection(data); + Curl_conn_close(data, conn, TRUE); + DEBUGASSERT(!data->conn); + } + + if(data->multi_easy) + multi = data->multi_easy; + else { + /* this multi handle will only ever have a single easy handle attached to + it, so make it use minimal hash sizes */ + multi = Curl_multi_handle(16, 1, 3, 7, 3); + if(!multi) + return CURLE_OUT_OF_MEMORY; + } + + if(Curl_api_multi_is_in_callback(multi)) + return CURLE_RECURSIVE_API_CALL; + + /* Copy relevant easy options to the multi handle */ + curl_multi_setopt(multi, CURLMOPT_MAXCONNECTS, (long)data->set.maxconnects); + curl_multi_setopt(multi, CURLMOPT_QUICK_EXIT, (long)data->set.quick_exit); + + data->multi_easy = NULL; /* pretend it does not exist */ + mresult = Curl_multi_add_handle(multi, data); + if(mresult) { + curl_multi_cleanup(multi); + if(mresult == CURLM_OUT_OF_MEMORY) + return CURLE_OUT_OF_MEMORY; + return CURLE_FAILED_INIT; + } + + /* assign this after curl_multi_add_handle() */ + data->multi_easy = multi; + + sigpipe_init(&sigpipe_ctx); + sigpipe_apply(data, &sigpipe_ctx); + + /* run the transfer */ + result = events ? easy_events(multi) : easy_transfer(multi); + + /* ignoring the return code is not nice, but atm we cannot really handle + a failure here, room for future improvement! */ + (void)Curl_multi_remove_handle(multi, data); + + sigpipe_restore(&sigpipe_ctx); + + /* The multi handle is kept alive, owned by the easy handle */ + return result; +} + +/* + * curl_easy_perform() is the external interface that performs a blocking + * transfer as previously setup. + */ +CURLcode curl_easy_perform(CURL *curl) +{ + struct Curl_eapi_guard guard = { 0 }; + CURLcode result; + + if(CURL_EAPI_ENTER(&guard, curl, easy_perform, &result)) { + result = easy_perform(curl, FALSE); + } + CURL_EAPI_LEAVE(&guard); + return result; +} + +#ifdef DEBUGBUILD +/* + * curl_easy_perform_ev() is the external interface that performs a blocking + * transfer using the event-based API internally. + */ +CURLcode curl_easy_perform_ev(struct Curl_easy *easy) +{ + struct Curl_eapi_guard guard; + CURLcode result; + + if(CURL_EAPI_ENTER(&guard, easy, easy_perform_ev, &result)) { + result = easy_perform(easy, TRUE); + } + CURL_EAPI_LEAVE(&guard); + return result; +} +#endif + +/* + * curl_easy_cleanup() is the external interface to cleaning/freeing the given + * easy handle. + */ +void curl_easy_cleanup(CURL *curl) +{ + struct Curl_eapi_guard guard; + + if(CURL_EAPI_ENTER(&guard, curl, easy_cleanup, NULL)) { + struct Curl_easy *data = curl; + struct Curl_sigpipe_ctx sigpipe_ctx; + sigpipe_ignore(data, &sigpipe_ctx); + Curl_close(&data); + sigpipe_restore(&sigpipe_ctx); + } + CURL_EAPI_LEAVE(&guard); +} + +/* + * curl_easy_getinfo() is an external interface that allows an app to retrieve + * information from a performed transfer and similar. + */ +#undef curl_easy_getinfo +CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...) +{ + struct Curl_eapi_guard guard; + CURLcode result; + + if(CURL_EAPI_ENTER(&guard, curl, easy_getinfo, &result)) { + struct Curl_easy *data = curl; + va_list arg; + void *paramp; + + va_start(arg, info); + paramp = va_arg(arg, void *); + + result = Curl_getinfo(data, info, paramp); + + va_end(arg); + } + CURL_EAPI_LEAVE(&guard); + return result; +} + +static CURLcode dupset(struct Curl_easy *dst, struct Curl_easy *src) +{ + CURLcode result = CURLE_OK; + enum dupblob j; + + /* Copy src->set into dst->set first, then deal with the strings + afterwards */ + dst->set = src->set; +#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API) + dst->set.mimepostp = NULL; +#endif + dst->set.str_copypostfields = NULL; + + Curl_u8_strset_init(&dst->set.strings); + /* clear all dest string and blob pointers first, in case we error out + mid-function */ + memset(dst->set.blobs, 0, BLOB_LAST * sizeof(struct curl_blob *)); + + /* duplicate all strings */ + result = Curl_u8_strset_copy(&dst->set.strings, &src->set.strings); + if(result) + return result; + + /* duplicate all blobs */ + for(j = (enum dupblob)0; j < BLOB_LAST; j++) { + result = Curl_setblobopt(&dst->set.blobs[j], src->set.blobs[j]); + if(result) + return result; + } + + /* duplicate memory areas pointed to */ + if(src->set.str_copypostfields) { + if(src->set.postfieldsize == -1) + dst->set.str_copypostfields = curlx_strdup(src->set.str_copypostfields); + else + /* postfieldsize is curl_off_t, curlx_memdup() takes a size_t ... */ + dst->set.str_copypostfields = + curlx_memdup(src->set.str_copypostfields, + curlx_sotouz(src->set.postfieldsize)); + if(!dst->set.str_copypostfields) + return CURLE_OUT_OF_MEMORY; + /* point to the new copy */ + dst->set.postfields = dst->set.str_copypostfields; + } + +#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API) + if(src->set.mimepostp) { + /* Duplicate mime data. Get a mimepost struct for the clone as well */ + dst->set.mimepostp = curlx_malloc(sizeof(*dst->set.mimepostp)); + if(!dst->set.mimepostp) + return CURLE_OUT_OF_MEMORY; + + Curl_mime_initpart(dst->set.mimepostp); + result = Curl_mime_duppart(dst, dst->set.mimepostp, src->set.mimepostp); + if(result) + return result; + } +#endif + + if(src->set.resolve) + dst->state.resolve = dst->set.resolve; + + return result; +} + +static void dupeasy_meta_freeentry(void *p) +{ + (void)p; + /* Always FALSE. Cannot use a 0 assert here since compilers + * are not in agreement if they then want a NORETURN attribute or + * not. *sigh* */ + DEBUGASSERT(!p); +} + +/* + * curl_easy_duphandle() is an external interface to allow duplication of a + * given input easy handle. The returned handle will be a new working handle + * with all options set exactly as the input source handle. + */ +CURL *curl_easy_duphandle(CURL *curl) +{ + struct Curl_eapi_guard guard; + struct Curl_easy *outcurl = NULL; + + if(CURL_EAPI_ENTER(&guard, curl, easy_duphandle, NULL)) { + struct Curl_easy *data = curl; + const char *str; + + outcurl = curlx_calloc(1, sizeof(struct Curl_easy)); + if(!outcurl) + goto fail; + + /* + * We setup a few buffers we need. We should probably make them + * get setup on-demand in the code, as that would probably decrease + * the likeliness of us forgetting to init a buffer here in the future. + */ + outcurl->set.buffer_size = data->set.buffer_size; + + Curl_hash_init(&outcurl->meta_hash, 23, + Curl_hash_str, curlx_str_key_compare, + dupeasy_meta_freeentry); + curlx_dyn_init(&outcurl->state.headerb, CURL_MAX_HTTP_HEADER); + Curl_bufref_init(&outcurl->state.url); + Curl_bufref_init(&outcurl->state.referer); + Curl_netrc_init(&outcurl->state.netrc); + + /* the connection pool is setup on demand */ + outcurl->state.lastconnect_id = -1; + outcurl->id = -1; + outcurl->mid = UINT32_MAX; + outcurl->master_mid = UINT32_MAX; + +#ifndef CURL_DISABLE_HTTP + Curl_llist_init(&outcurl->state.httphdrs, NULL); +#endif + Curl_initinfo(outcurl); + + /* copy all userdefined values */ + if(dupset(outcurl, data)) + goto fail; + + outcurl->progress.hide = data->progress.hide; + outcurl->progress.callback = data->progress.callback; + +#ifndef CURL_DISABLE_COOKIES + outcurl->state.cookielist = NULL; + if(data->cookies && data->state.cookie_engine) { + /* If cookies are enabled in the parent handle, we enable them + in the clone as well! */ + outcurl->cookies = Curl_cookie_init(); + if(!outcurl->cookies) + goto fail; + outcurl->state.cookie_engine = TRUE; + } + + if(data->state.cookielist) { + outcurl->state.cookielist = Curl_slist_duplicate(data->state.cookielist); + if(!outcurl->state.cookielist) + goto fail; + } +#endif + + if(Curl_bufref_ptr(&data->state.url)) { + Curl_bufref_set(&outcurl->state.url, + Curl_bufref_dup(&data->state.url), 0, + curl_free); + if(!Curl_bufref_ptr(&outcurl->state.url)) + goto fail; + } + if(Curl_bufref_ptr(&data->state.referer)) { + Curl_bufref_set(&outcurl->state.referer, + Curl_bufref_dup(&data->state.referer), 0, + curl_free); + if(!Curl_bufref_ptr(&outcurl->state.referer)) + goto fail; + } + + /* Reinitialize an SSL engine for the new handle + * note: the engine name has already been copied by dupset */ + str = CURL_EASY_STR(outcurl, STRING_SSL_ENGINE); + if(str) { + if(Curl_ssl_set_engine(outcurl, str)) + goto fail; + } + +#ifndef CURL_DISABLE_ALTSVC + if(data->asi) { + outcurl->asi = Curl_altsvc_init(); + if(!outcurl->asi) + goto fail; + str = CURL_EASY_STR(outcurl, STRING_ALTSVC); + if(str) + (void)Curl_altsvc_load(outcurl->asi, str); + } +#endif +#ifndef CURL_DISABLE_HSTS + if(data->hsts) { + outcurl->hsts = Curl_hsts_init(); + if(!outcurl->hsts) + goto fail; + str = CURL_EASY_STR(outcurl, STRING_HSTS); + if(str) + (void)Curl_hsts_loadfile(outcurl, outcurl->hsts, str); + (void)Curl_hsts_loadcb(outcurl, outcurl->hsts); + + /* Copy entries learned at runtime. (E.g. Strict-Transport-Security + headers.) */ + if(Curl_hsts_copy(outcurl->hsts, data->hsts)) + goto fail; + } +#endif + + /* we reach this point and thus we are OK */ + outcurl->magic = CURLEASY_MAGIC_NUMBER; + } + CURL_EAPI_LEAVE(&guard); + return outcurl; + +fail: + if(outcurl) { +#ifndef CURL_DISABLE_COOKIES + curlx_free(outcurl->cookies); +#endif + curlx_dyn_free(&outcurl->state.headerb); + Curl_altsvc_cleanup(&outcurl->asi); + Curl_hsts_cleanup(&outcurl->hsts); + Curl_freeset(outcurl); + curlx_free(outcurl); + } + + CURL_EAPI_LEAVE(&guard); + return NULL; +} + +/* + * curl_easy_reset() is an external interface that allows an app to re- + * initialize a session handle to the default values. + */ +void curl_easy_reset(CURL *curl) +{ + struct Curl_eapi_guard guard; + + if(CURL_EAPI_ENTER(&guard, curl, easy_reset, NULL)) { + struct Curl_easy *data = curl; + + data->state.lastconnect_id = -1; /* clear remembered connection id */ + Curl_req_hard_reset(&data->req, data); + Curl_hash_clean(&data->meta_hash); + + /* clear all meta data */ + Curl_meta_reset(data); + /* zero out UserDefined data: */ + Curl_freeset(data); + memset(&data->set, 0, sizeof(struct UserDefined)); + Curl_init_userdefined(data); + + /* zero out Progress data: */ + memset(&data->progress, 0, sizeof(struct Progress)); + + /* zero out PureInfo data: */ + Curl_initinfo(data); + + data->progress.hide = TRUE; + + /* zero out authentication data: */ + memset(&data->state.authhost, 0, sizeof(struct auth)); + memset(&data->state.authproxy, 0, sizeof(struct auth)); + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_DIGEST_AUTH) + Curl_http_auth_cleanup_digest(data); +#endif + data->master_mid = UINT32_MAX; + } + CURL_EAPI_LEAVE(&guard); +} + +/* + * curl_easy_pause() allows an application to pause or unpause a specific + * transfer and direction. This function sets the full new state for the + * current connection this easy handle operates on. + * + * NOTE: if you have the receiving paused and you call this function to remove + * the pausing, you may get your write callback called at this point. + * + * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h + * + * NOTE: This is one of few API functions that are allowed to be called from + * within a callback. + */ +CURLcode curl_easy_pause(CURL *curl, int action) +{ + struct Curl_eapi_guard guard; + CURLcode result = CURLE_OK; + + if(CURL_EAPI_ENTER(&guard, curl, easy_pause, &result)) { + bool changed = FALSE; + struct Curl_easy *data = curl; + bool recv_paused, recv_paused_new; + bool send_paused, send_paused_new; + + if(!data->conn) { + /* crazy input, do not continue */ + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + + recv_paused = Curl_xfer_recv_is_paused(data); + recv_paused_new = (action & CURLPAUSE_RECV); + send_paused = Curl_xfer_send_is_paused(data); + send_paused_new = (action & CURLPAUSE_SEND); + + if((send_paused != send_paused_new) || + (send_paused_new != Curl_creader_is_paused(data))) { + changed = TRUE; + result = Curl_1st_fatal( + result, Curl_xfer_pause_send(data, send_paused_new)); + } + + if(recv_paused != recv_paused_new) { + changed = TRUE; + result = Curl_1st_fatal( + result, Curl_xfer_pause_recv(data, recv_paused_new)); + } + + /* If not completely pausing both directions, run again in any case. */ + if(!Curl_xfer_is_blocked(data)) { + /* reset the too-slow time keeper */ + data->state.keeps_speed.tv_sec = 0; + if(data->multi) { + Curl_multi_mark_dirty(data); /* make it run */ + /* On changes, tell application to update its timers. */ + if(changed) { + if(Curl_update_timer(data->multi) && !result) + result = CURLE_ABORTED_BY_CALLBACK; + } + } + } + + if(!result && changed && !data->state.done && data->multi) + /* pause/unpausing may result in multi event changes */ + if(Curl_multi_ev_assess_xfer(data->multi, data) && !result) + result = CURLE_ABORTED_BY_CALLBACK; + } +out: + CURL_EAPI_LEAVE(&guard); + return result; +} + +static CURLcode easy_connection(struct Curl_easy *data, + struct connectdata **connp) +{ + curl_socket_t sfd; + + if(!data) + return CURLE_BAD_FUNCTION_ARGUMENT; + + /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */ + if(!data->set.connect_only) { + failf(data, "CONNECT_ONLY is required"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + + sfd = Curl_getconnectinfo(data, connp); + + if(sfd == CURL_SOCKET_BAD) { + failf(data, "Failed to get last socket used for connection #%" FMT_OFF_T, + data->state.lastconnect_id); + return CURLE_UNSUPPORTED_PROTOCOL; + } + + return CURLE_OK; +} + +/* + * Receives data from the connected socket. Use after successful + * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. + * Returns CURLE_OK on success, error code on error. + */ +CURLcode Curl_easy_recv(struct Curl_easy *data, + void *buffer, size_t buflen, size_t *n) +{ + CURLcode result; + struct connectdata *c; + + result = easy_connection(data, &c); + if(result) + return result; + + if(!data->conn) + /* on first invoke, the transfer has been detached from the connection and + needs to be reattached */ + Curl_attach_connection(data, c, TRUE); + + *n = 0; + return Curl_conn_recv(data, FIRSTSOCKET, buffer, buflen, n); +} + +CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, size_t *n) +{ + struct Curl_eapi_guard guard; + CURLcode result; + + if(CURL_EAPI_ENTER(&guard, curl, easy_recv, &result)) { + result = Curl_easy_recv(curl, buffer, buflen, n); + } + CURL_EAPI_LEAVE(&guard); + return result; +} + +#ifndef CURL_DISABLE_WEBSOCKETS +CURLcode Curl_connect_only_attach(struct Curl_easy *data) +{ + CURLcode result; + struct connectdata *c = NULL; + + result = easy_connection(data, &c); + if(result) + return result; + + if(!data->conn) + /* on first invoke, the transfer has been detached from the connection and + needs to be reattached */ + Curl_attach_connection(data, c, TRUE); + + return CURLE_OK; +} +#endif /* !CURL_DISABLE_WEBSOCKETS */ + +/* + * Sends data over the connected socket. + * + * This is the private internal version of curl_easy_send() + */ +CURLcode Curl_senddata(struct Curl_easy *data, const void *buffer, + size_t buflen, size_t *n) +{ + CURLcode result; + struct connectdata *c = NULL; + struct Curl_sigpipe_ctx sigpipe_ctx; + + *n = 0; + result = easy_connection(data, &c); + if(result) + return result; + + if(!data->conn) + /* on first invoke, the transfer has been detached from the connection and + needs to be reattached */ + Curl_attach_connection(data, c, TRUE); + + sigpipe_ignore(data, &sigpipe_ctx); + result = Curl_conn_send(data, FIRSTSOCKET, buffer, buflen, FALSE, n); + sigpipe_restore(&sigpipe_ctx); + + if(result && result != CURLE_AGAIN) + return CURLE_SEND_ERROR; + return result; +} + +/* + * Sends data over the connected socket. Use after successful + * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. + */ +CURLcode curl_easy_send(CURL *curl, const void *buffer, size_t buflen, + size_t *n) +{ + struct Curl_eapi_guard guard; + CURLcode result; + + if(CURL_EAPI_ENTER(&guard, curl, easy_send, &result)) { + struct Curl_easy *data = curl; + size_t written = 0; + + result = Curl_senddata(data, buffer, buflen, &written); + *n = written; + } + CURL_EAPI_LEAVE(&guard); + return result; +} + +/* + * Performs connection upkeep for the given session handle. + */ +CURLcode curl_easy_upkeep(CURL *curl) +{ + struct Curl_eapi_guard guard; + CURLcode result; + + if(CURL_EAPI_ENTER(&guard, curl, easy_upkeep, &result)) { + /* Use the common function to keep connections alive. */ + result = Curl_cpool_upkeep((struct Curl_easy *)curl); + } + CURL_EAPI_LEAVE(&guard); + return result; +} + +CURLcode curl_easy_ssls_import(CURL *curl, const char *session_key, + const unsigned char *shmac, size_t shmac_len, + const unsigned char *sdata, size_t sdata_len) +{ +#if defined(USE_SSL) && defined(USE_SSLS_EXPORT) + struct Curl_eapi_guard guard; + CURLcode result; + + if(CURL_EAPI_ENTER(&guard, curl, easy_ssls_import, &result)) { + result = Curl_ssl_session_import((struct Curl_easy *)curl, session_key, + shmac, shmac_len, sdata, sdata_len); + } + CURL_EAPI_LEAVE(&guard); + return result; +#else + (void)curl; + (void)session_key; + (void)shmac; + (void)shmac_len; + (void)sdata; + (void)sdata_len; + return CURLE_NOT_BUILT_IN; +#endif +} + +CURLcode curl_easy_ssls_export(CURL *curl, + curl_ssls_export_cb *export_fn, + void *userptr) +{ +#if defined(USE_SSL) && defined(USE_SSLS_EXPORT) + struct Curl_eapi_guard guard; + CURLcode result; + + if(CURL_EAPI_ENTER(&guard, curl, easy_ssls_export, &result)) { + result = Curl_ssl_session_export((struct Curl_easy *)curl, + export_fn, userptr); + } + CURL_EAPI_LEAVE(&guard); + return result; +#else + (void)curl; + (void)export_fn; + (void)userptr; + return CURLE_NOT_BUILT_IN; +#endif +} + +CURLcode Curl_meta_set(struct Curl_easy *data, const char *key, + void *meta_data, Curl_meta_dtor *meta_dtor) +{ + DEBUGASSERT(meta_data); /* never set to NULL */ + if(!Curl_hash_add2(&data->meta_hash, CURL_UNCONST(key), strlen(key) + 1, + meta_data, meta_dtor)) { + meta_dtor(CURL_UNCONST(key), strlen(key) + 1, meta_data); + return CURLE_OUT_OF_MEMORY; + } + return CURLE_OK; +} + +void Curl_meta_remove(struct Curl_easy *data, const char *key) +{ + Curl_hash_delete(&data->meta_hash, CURL_UNCONST(key), strlen(key) + 1); +} + +void *Curl_meta_get(struct Curl_easy *data, const char *key) +{ + return Curl_hash_pick(&data->meta_hash, CURL_UNCONST(key), strlen(key) + 1); +} + +void Curl_meta_reset(struct Curl_easy *data) +{ + Curl_hash_clean(&data->meta_hash); +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/easy_lock.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/easy_lock.h new file mode 100644 index 0000000000..9f21448cbe --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/easy_lock.h @@ -0,0 +1,101 @@ +#ifndef HEADER_CURL_EASY_LOCK_H +#define HEADER_CURL_EASY_LOCK_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#define GLOBAL_INIT_IS_THREADSAFE + +#ifdef _WIN32 + +#define curl_simple_lock SRWLOCK +#define CURL_SIMPLE_LOCK_INIT SRWLOCK_INIT + +#define curl_simple_lock_lock(m) AcquireSRWLockExclusive(m) +#define curl_simple_lock_unlock(m) ReleaseSRWLockExclusive(m) + +#elif defined(HAVE_ATOMIC) && defined(HAVE_STDATOMIC_H) +#include <stdatomic.h> +#ifdef HAVE_SCHED_YIELD +#include <sched.h> +#endif + +#define curl_simple_lock atomic_int +#define CURL_SIMPLE_LOCK_INIT 0 + +#ifndef __INTEL_COMPILER +/* The Intel compiler tries to look like GCC *and* clang *and* lies in its + __has_builtin() function, so override it. */ + +/* if GCC on i386/x86_64 or if the built-in is present */ +#if (defined(__GNUC__) && !defined(__clang__)) && \ + (defined(__i386__) || defined(__x86_64__)) +#define HAVE_BUILTIN_IA32_PAUSE +#elif defined(__has_builtin) /* Keep this PP check separate from others */ +#if __has_builtin(__builtin_ia32_pause) +#define HAVE_BUILTIN_IA32_PAUSE +#endif +#endif + +#endif /* !__INTEL_COMPILER */ + +static CURL_INLINE void curl_simple_lock_lock(curl_simple_lock *lock) +{ + for(;;) { + if(!atomic_exchange_explicit(lock, true, memory_order_acquire)) + break; + /* Reduce cache coherency traffic */ + while(atomic_load_explicit(lock, memory_order_relaxed)) { + /* Reduce load (not mandatory) */ +#ifdef HAVE_BUILTIN_IA32_PAUSE + __builtin_ia32_pause(); +#elif defined(__aarch64__) + /* NOLINTNEXTLINE(portability-no-assembler) */ + __asm__ volatile("yield" ::: "memory"); +#elif defined(HAVE_SCHED_YIELD) + sched_yield(); +#endif + } + } +} + +static CURL_INLINE void curl_simple_lock_unlock(curl_simple_lock *lock) +{ + atomic_store_explicit(lock, false, memory_order_release); +} + +#elif defined(HAVE_THREADS_POSIX) + +#define curl_simple_lock pthread_mutex_t +#define CURL_SIMPLE_LOCK_INIT PTHREAD_MUTEX_INITIALIZER +#define curl_simple_lock_lock(m) pthread_mutex_lock(m) +#define curl_simple_lock_unlock(m) pthread_mutex_unlock(m) + +#else + +#undef GLOBAL_INIT_IS_THREADSAFE + +#endif + +#endif /* HEADER_CURL_EASY_LOCK_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/easygetopt.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/easygetopt.c new file mode 100644 index 0000000000..533d7e3670 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/easygetopt.c @@ -0,0 +1,97 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "easyoptions.h" + +#ifndef CURL_DISABLE_GETOPTIONS + +/* Lookups easy options at runtime */ +static const struct curl_easyoption *lookup(const char *name, CURLoption id) +{ + DEBUGASSERT(name || id); + DEBUGASSERT(!Curl_easyopts_check()); + if(name || id) { + const struct curl_easyoption *o = &Curl_easyopts[0]; + do { + if(name) { + if(curl_strequal(o->name, name)) + return o; + } + else { + if((o->id == id) && !(o->flags & CURLOT_FLAG_ALIAS)) + /* do not match alias options */ + return o; + } + o++; + } while(o->name); + } + return NULL; +} + +const struct curl_easyoption *curl_easy_option_by_name(const char *name) +{ + /* when name is used, the id argument is ignored */ + return lookup(name, CURLOPT_LASTENTRY); +} + +const struct curl_easyoption *curl_easy_option_by_id(CURLoption id) +{ + return lookup(NULL, id); +} + +/* Iterates over available options */ +const struct curl_easyoption *curl_easy_option_next( + const struct curl_easyoption *prev) +{ + if(prev && prev->name) { + prev++; + if(prev->name) + return prev; + } + else if(!prev) + return &Curl_easyopts[0]; + return NULL; +} + +#else +const struct curl_easyoption *curl_easy_option_by_name(const char *name) +{ + (void)name; + return NULL; +} + +const struct curl_easyoption *curl_easy_option_by_id(CURLoption id) +{ + (void)id; + return NULL; +} + +const struct curl_easyoption *curl_easy_option_next( + const struct curl_easyoption *prev) +{ + (void)prev; + return NULL; +} +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/easyif.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/easyif.h new file mode 100644 index 0000000000..213fd027da --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/easyif.h @@ -0,0 +1,40 @@ +#ifndef HEADER_CURL_EASYIF_H +#define HEADER_CURL_EASYIF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Prototypes for library-wide functions provided by easy.c + */ +CURLcode Curl_senddata(struct Curl_easy *data, const void *buffer, + size_t buflen, size_t *n); + +#ifndef CURL_DISABLE_WEBSOCKETS +CURLcode Curl_connect_only_attach(struct Curl_easy *data); +#endif + +#ifdef DEBUGBUILD +CURL_EXTERN CURLcode curl_easy_perform_ev(struct Curl_easy *easy); +#endif + +#endif /* HEADER_CURL_EASYIF_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/easyoptions.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/easyoptions.c new file mode 100644 index 0000000000..1643ec3256 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/easyoptions.c @@ -0,0 +1,394 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* This source code is generated by optiontable.pl - DO NOT EDIT BY HAND */ + +#include "curl_setup.h" + +#include "easyoptions.h" + +/* all easy setopt options listed in alphabetical order */ +const struct curl_easyoption Curl_easyopts[] = { + { "ABSTRACT_UNIX_SOCKET", CURLOPT_ABSTRACT_UNIX_SOCKET, CURLOT_STRING, 0 }, + { "ACCEPTTIMEOUT_MS", CURLOPT_ACCEPTTIMEOUT_MS, CURLOT_LONG, 0 }, + { "ACCEPT_ENCODING", CURLOPT_ACCEPT_ENCODING, CURLOT_STRING, 0 }, + { "ADDRESS_SCOPE", CURLOPT_ADDRESS_SCOPE, CURLOT_LONG, 0 }, + { "ALTSVC", CURLOPT_ALTSVC, CURLOT_STRING, 0 }, + { "ALTSVC_CTRL", CURLOPT_ALTSVC_CTRL, CURLOT_LONG, 0 }, + { "APPEND", CURLOPT_APPEND, CURLOT_LONG, 0 }, + { "AUTOREFERER", CURLOPT_AUTOREFERER, CURLOT_LONG, 0 }, + { "AWS_SIGV4", CURLOPT_AWS_SIGV4, CURLOT_STRING, 0 }, + { "BUFFERSIZE", CURLOPT_BUFFERSIZE, CURLOT_LONG, 0 }, + { "CAINFO", CURLOPT_CAINFO, CURLOT_STRING, 0 }, + { "CAINFO_BLOB", CURLOPT_CAINFO_BLOB, CURLOT_BLOB, 0 }, + { "CAPATH", CURLOPT_CAPATH, CURLOT_STRING, 0 }, + { "CA_CACHE_TIMEOUT", CURLOPT_CA_CACHE_TIMEOUT, CURLOT_LONG, 0 }, + { "CERTINFO", CURLOPT_CERTINFO, CURLOT_LONG, 0 }, + { "CHUNK_BGN_FUNCTION", CURLOPT_CHUNK_BGN_FUNCTION, CURLOT_FUNCTION, 0 }, + { "CHUNK_DATA", CURLOPT_CHUNK_DATA, CURLOT_CBPTR, 0 }, + { "CHUNK_END_FUNCTION", CURLOPT_CHUNK_END_FUNCTION, CURLOT_FUNCTION, 0 }, + { "CLOSESOCKETDATA", CURLOPT_CLOSESOCKETDATA, CURLOT_CBPTR, 0 }, + { "CLOSESOCKETFUNCTION", CURLOPT_CLOSESOCKETFUNCTION, CURLOT_FUNCTION, 0 }, + { "CONNECTTIMEOUT", CURLOPT_CONNECTTIMEOUT, CURLOT_LONG, 0 }, + { "CONNECTTIMEOUT_MS", CURLOPT_CONNECTTIMEOUT_MS, CURLOT_LONG, 0 }, + { "CONNECT_ONLY", CURLOPT_CONNECT_ONLY, CURLOT_LONG, 0 }, + { "CONNECT_TO", CURLOPT_CONNECT_TO, CURLOT_SLIST, 0 }, + { "CONV_FROM_NETWORK_FUNCTION", CURLOPT_CONV_FROM_NETWORK_FUNCTION, + CURLOT_FUNCTION, 0 }, + { "CONV_FROM_UTF8_FUNCTION", CURLOPT_CONV_FROM_UTF8_FUNCTION, + CURLOT_FUNCTION, 0 }, + { "CONV_TO_NETWORK_FUNCTION", CURLOPT_CONV_TO_NETWORK_FUNCTION, + CURLOT_FUNCTION, 0 }, + { "COOKIE", CURLOPT_COOKIE, CURLOT_STRING, 0 }, + { "COOKIEFILE", CURLOPT_COOKIEFILE, CURLOT_STRING, 0 }, + { "COOKIEJAR", CURLOPT_COOKIEJAR, CURLOT_STRING, 0 }, + { "COOKIELIST", CURLOPT_COOKIELIST, CURLOT_STRING, 0 }, + { "COOKIESESSION", CURLOPT_COOKIESESSION, CURLOT_LONG, 0 }, + { "COPYPOSTFIELDS", CURLOPT_COPYPOSTFIELDS, CURLOT_OBJECT, 0 }, + { "CRLF", CURLOPT_CRLF, CURLOT_LONG, 0 }, + { "CRLFILE", CURLOPT_CRLFILE, CURLOT_STRING, 0 }, + { "CURLU", CURLOPT_CURLU, CURLOT_OBJECT, 0 }, + { "CUSTOMREQUEST", CURLOPT_CUSTOMREQUEST, CURLOT_STRING, 0 }, + { "DEBUGDATA", CURLOPT_DEBUGDATA, CURLOT_CBPTR, 0 }, + { "DEBUGFUNCTION", CURLOPT_DEBUGFUNCTION, CURLOT_FUNCTION, 0 }, + { "DEFAULT_PROTOCOL", CURLOPT_DEFAULT_PROTOCOL, CURLOT_STRING, 0 }, + { "DIRLISTONLY", CURLOPT_DIRLISTONLY, CURLOT_LONG, 0 }, + { "DISALLOW_USERNAME_IN_URL", CURLOPT_DISALLOW_USERNAME_IN_URL, + CURLOT_LONG, 0 }, + { "DNS_CACHE_TIMEOUT", CURLOPT_DNS_CACHE_TIMEOUT, CURLOT_LONG, 0 }, + { "DNS_INTERFACE", CURLOPT_DNS_INTERFACE, CURLOT_STRING, 0 }, + { "DNS_LOCAL_IP4", CURLOPT_DNS_LOCAL_IP4, CURLOT_STRING, 0 }, + { "DNS_LOCAL_IP6", CURLOPT_DNS_LOCAL_IP6, CURLOT_STRING, 0 }, + { "DNS_SERVERS", CURLOPT_DNS_SERVERS, CURLOT_STRING, 0 }, + { "DNS_SHUFFLE_ADDRESSES", CURLOPT_DNS_SHUFFLE_ADDRESSES, CURLOT_LONG, 0 }, + { "DNS_USE_GLOBAL_CACHE", CURLOPT_DNS_USE_GLOBAL_CACHE, CURLOT_LONG, 0 }, + { "DOH_SSL_VERIFYHOST", CURLOPT_DOH_SSL_VERIFYHOST, CURLOT_LONG, 0 }, + { "DOH_SSL_VERIFYPEER", CURLOPT_DOH_SSL_VERIFYPEER, CURLOT_LONG, 0 }, + { "DOH_SSL_VERIFYSTATUS", CURLOPT_DOH_SSL_VERIFYSTATUS, CURLOT_LONG, 0 }, + { "DOH_URL", CURLOPT_DOH_URL, CURLOT_STRING, 0 }, + { "ECH", CURLOPT_ECH, CURLOT_STRING, 0 }, + { "EGDSOCKET", CURLOPT_EGDSOCKET, CURLOT_STRING, 0 }, + { "ENCODING", CURLOPT_ACCEPT_ENCODING, CURLOT_STRING, CURLOT_FLAG_ALIAS }, + { "ERRORBUFFER", CURLOPT_ERRORBUFFER, CURLOT_OBJECT, 0 }, + { "EXPECT_100_TIMEOUT_MS", CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOT_LONG, 0 }, + { "FAILONERROR", CURLOPT_FAILONERROR, CURLOT_LONG, 0 }, + { "FILE", CURLOPT_WRITEDATA, CURLOT_CBPTR, CURLOT_FLAG_ALIAS }, + { "FILETIME", CURLOPT_FILETIME, CURLOT_LONG, 0 }, + { "FNMATCH_DATA", CURLOPT_FNMATCH_DATA, CURLOT_CBPTR, 0 }, + { "FNMATCH_FUNCTION", CURLOPT_FNMATCH_FUNCTION, CURLOT_FUNCTION, 0 }, + { "FOLLOWLOCATION", CURLOPT_FOLLOWLOCATION, CURLOT_LONG, 0 }, + { "FORBID_REUSE", CURLOPT_FORBID_REUSE, CURLOT_LONG, 0 }, + { "FRESH_CONNECT", CURLOPT_FRESH_CONNECT, CURLOT_LONG, 0 }, + { "FTPAPPEND", CURLOPT_APPEND, CURLOT_LONG, CURLOT_FLAG_ALIAS }, + { "FTPLISTONLY", CURLOPT_DIRLISTONLY, CURLOT_LONG, CURLOT_FLAG_ALIAS }, + { "FTPPORT", CURLOPT_FTPPORT, CURLOT_STRING, 0 }, + { "FTPSSLAUTH", CURLOPT_FTPSSLAUTH, CURLOT_VALUES, 0 }, + { "FTP_ACCOUNT", CURLOPT_FTP_ACCOUNT, CURLOT_STRING, 0 }, + { "FTP_ALTERNATIVE_TO_USER", CURLOPT_FTP_ALTERNATIVE_TO_USER, + CURLOT_STRING, 0 }, + { "FTP_CREATE_MISSING_DIRS", CURLOPT_FTP_CREATE_MISSING_DIRS, + CURLOT_LONG, 0 }, + { "FTP_FILEMETHOD", CURLOPT_FTP_FILEMETHOD, CURLOT_VALUES, 0 }, + { "FTP_RESPONSE_TIMEOUT", CURLOPT_SERVER_RESPONSE_TIMEOUT, + CURLOT_LONG, CURLOT_FLAG_ALIAS }, + { "FTP_SKIP_PASV_IP", CURLOPT_FTP_SKIP_PASV_IP, CURLOT_LONG, 0 }, + { "FTP_SSL", CURLOPT_USE_SSL, CURLOT_VALUES, CURLOT_FLAG_ALIAS }, + { "FTP_SSL_CCC", CURLOPT_FTP_SSL_CCC, CURLOT_LONG, 0 }, + { "FTP_USE_EPRT", CURLOPT_FTP_USE_EPRT, CURLOT_LONG, 0 }, + { "FTP_USE_EPSV", CURLOPT_FTP_USE_EPSV, CURLOT_LONG, 0 }, + { "FTP_USE_PRET", CURLOPT_FTP_USE_PRET, CURLOT_LONG, 0 }, + { "GSSAPI_DELEGATION", CURLOPT_GSSAPI_DELEGATION, CURLOT_VALUES, 0 }, + { "HAPPY_EYEBALLS_TIMEOUT_MS", CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, + CURLOT_LONG, 0 }, + { "HAPROXYPROTOCOL", CURLOPT_HAPROXYPROTOCOL, CURLOT_LONG, 0 }, + { "HAPROXY_CLIENT_IP", CURLOPT_HAPROXY_CLIENT_IP, CURLOT_STRING, 0 }, + { "HEADER", CURLOPT_HEADER, CURLOT_LONG, 0 }, + { "HEADERDATA", CURLOPT_HEADERDATA, CURLOT_CBPTR, 0 }, + { "HEADERFUNCTION", CURLOPT_HEADERFUNCTION, CURLOT_FUNCTION, 0 }, + { "HEADEROPT", CURLOPT_HEADEROPT, CURLOT_VALUES, 0 }, + { "HSTS", CURLOPT_HSTS, CURLOT_STRING, 0 }, + { "HSTSREADDATA", CURLOPT_HSTSREADDATA, CURLOT_CBPTR, 0 }, + { "HSTSREADFUNCTION", CURLOPT_HSTSREADFUNCTION, CURLOT_FUNCTION, 0 }, + { "HSTSWRITEDATA", CURLOPT_HSTSWRITEDATA, CURLOT_CBPTR, 0 }, + { "HSTSWRITEFUNCTION", CURLOPT_HSTSWRITEFUNCTION, CURLOT_FUNCTION, 0 }, + { "HSTS_CTRL", CURLOPT_HSTS_CTRL, CURLOT_LONG, 0 }, + { "HTTP09_ALLOWED", CURLOPT_HTTP09_ALLOWED, CURLOT_LONG, 0 }, + { "HTTP200ALIASES", CURLOPT_HTTP200ALIASES, CURLOT_SLIST, 0 }, + { "HTTPAUTH", CURLOPT_HTTPAUTH, CURLOT_VALUES, 0 }, + { "HTTPGET", CURLOPT_HTTPGET, CURLOT_LONG, 0 }, + { "HTTPHEADER", CURLOPT_HTTPHEADER, CURLOT_SLIST, 0 }, + { "HTTPPOST", CURLOPT_HTTPPOST, CURLOT_OBJECT, 0 }, + { "HTTPPROXYTUNNEL", CURLOPT_HTTPPROXYTUNNEL, CURLOT_LONG, 0 }, + { "HTTPSIG_ALGORITHM", CURLOPT_HTTPSIG_ALGORITHM, CURLOT_VALUES, 0 }, + { "HTTPSIG_HEADERS", CURLOPT_HTTPSIG_HEADERS, CURLOT_STRING, 0 }, + { "HTTPSIG_KEY", CURLOPT_HTTPSIG_KEY, CURLOT_STRING, 0 }, + { "HTTPSIG_KEYID", CURLOPT_HTTPSIG_KEYID, CURLOT_STRING, 0 }, + { "HTTP_CONTENT_DECODING", CURLOPT_HTTP_CONTENT_DECODING, CURLOT_LONG, 0 }, + { "HTTP_TRANSFER_DECODING", CURLOPT_HTTP_TRANSFER_DECODING, + CURLOT_LONG, 0 }, + { "HTTP_VERSION", CURLOPT_HTTP_VERSION, CURLOT_VALUES, 0 }, + { "IGNORE_CONTENT_LENGTH", CURLOPT_IGNORE_CONTENT_LENGTH, CURLOT_LONG, 0 }, + { "INFILE", CURLOPT_READDATA, CURLOT_CBPTR, CURLOT_FLAG_ALIAS }, + { "INFILESIZE", CURLOPT_INFILESIZE, CURLOT_LONG, 0 }, + { "INFILESIZE_LARGE", CURLOPT_INFILESIZE_LARGE, CURLOT_OFF_T, 0 }, + { "INTERFACE", CURLOPT_INTERFACE, CURLOT_STRING, 0 }, + { "INTERLEAVEDATA", CURLOPT_INTERLEAVEDATA, CURLOT_CBPTR, 0 }, + { "INTERLEAVEFUNCTION", CURLOPT_INTERLEAVEFUNCTION, CURLOT_FUNCTION, 0 }, + { "IOCTLDATA", CURLOPT_IOCTLDATA, CURLOT_CBPTR, 0 }, + { "IOCTLFUNCTION", CURLOPT_IOCTLFUNCTION, CURLOT_FUNCTION, 0 }, + { "IPRESOLVE", CURLOPT_IPRESOLVE, CURLOT_VALUES, 0 }, + { "ISSUERCERT", CURLOPT_ISSUERCERT, CURLOT_STRING, 0 }, + { "ISSUERCERT_BLOB", CURLOPT_ISSUERCERT_BLOB, CURLOT_BLOB, 0 }, + { "KEEP_SENDING_ON_ERROR", CURLOPT_KEEP_SENDING_ON_ERROR, CURLOT_LONG, 0 }, + { "KEYPASSWD", CURLOPT_KEYPASSWD, CURLOT_STRING, 0 }, + { "KRB4LEVEL", CURLOPT_KRBLEVEL, CURLOT_STRING, CURLOT_FLAG_ALIAS }, + { "KRBLEVEL", CURLOPT_KRBLEVEL, CURLOT_STRING, 0 }, + { "LOCALPORT", CURLOPT_LOCALPORT, CURLOT_LONG, 0 }, + { "LOCALPORTRANGE", CURLOPT_LOCALPORTRANGE, CURLOT_LONG, 0 }, + { "LOGIN_OPTIONS", CURLOPT_LOGIN_OPTIONS, CURLOT_STRING, 0 }, + { "LOW_SPEED_LIMIT", CURLOPT_LOW_SPEED_LIMIT, CURLOT_LONG, 0 }, + { "LOW_SPEED_TIME", CURLOPT_LOW_SPEED_TIME, CURLOT_LONG, 0 }, + { "MAIL_AUTH", CURLOPT_MAIL_AUTH, CURLOT_STRING, 0 }, + { "MAIL_FROM", CURLOPT_MAIL_FROM, CURLOT_STRING, 0 }, + { "MAIL_RCPT", CURLOPT_MAIL_RCPT, CURLOT_SLIST, 0 }, + { "MAIL_RCPT_ALLLOWFAILS", CURLOPT_MAIL_RCPT_ALLOWFAILS, + CURLOT_LONG, CURLOT_FLAG_ALIAS }, + { "MAIL_RCPT_ALLOWFAILS", CURLOPT_MAIL_RCPT_ALLOWFAILS, CURLOT_LONG, 0 }, + { "MAXAGE_CONN", CURLOPT_MAXAGE_CONN, CURLOT_LONG, 0 }, + { "MAXCONNECTS", CURLOPT_MAXCONNECTS, CURLOT_LONG, 0 }, + { "MAXFILESIZE", CURLOPT_MAXFILESIZE, CURLOT_LONG, 0 }, + { "MAXFILESIZE_LARGE", CURLOPT_MAXFILESIZE_LARGE, CURLOT_OFF_T, 0 }, + { "MAXLIFETIME_CONN", CURLOPT_MAXLIFETIME_CONN, CURLOT_LONG, 0 }, + { "MAXREDIRS", CURLOPT_MAXREDIRS, CURLOT_LONG, 0 }, + { "MAX_RECV_SPEED_LARGE", CURLOPT_MAX_RECV_SPEED_LARGE, CURLOT_OFF_T, 0 }, + { "MAX_SEND_SPEED_LARGE", CURLOPT_MAX_SEND_SPEED_LARGE, CURLOT_OFF_T, 0 }, + { "MIMEPOST", CURLOPT_MIMEPOST, CURLOT_OBJECT, 0 }, + { "MIME_OPTIONS", CURLOPT_MIME_OPTIONS, CURLOT_LONG, 0 }, + { "NETRC", CURLOPT_NETRC, CURLOT_VALUES, 0 }, + { "NETRC_FILE", CURLOPT_NETRC_FILE, CURLOT_STRING, 0 }, + { "NEW_DIRECTORY_PERMS", CURLOPT_NEW_DIRECTORY_PERMS, CURLOT_LONG, 0 }, + { "NEW_FILE_PERMS", CURLOPT_NEW_FILE_PERMS, CURLOT_LONG, 0 }, + { "NOBODY", CURLOPT_NOBODY, CURLOT_LONG, 0 }, + { "NOPROGRESS", CURLOPT_NOPROGRESS, CURLOT_LONG, 0 }, + { "NOPROXY", CURLOPT_NOPROXY, CURLOT_STRING, 0 }, + { "NOSIGNAL", CURLOPT_NOSIGNAL, CURLOT_LONG, 0 }, + { "OPENSOCKETDATA", CURLOPT_OPENSOCKETDATA, CURLOT_CBPTR, 0 }, + { "OPENSOCKETFUNCTION", CURLOPT_OPENSOCKETFUNCTION, CURLOT_FUNCTION, 0 }, + { "PASSWORD", CURLOPT_PASSWORD, CURLOT_STRING, 0 }, + { "PATH_AS_IS", CURLOPT_PATH_AS_IS, CURLOT_LONG, 0 }, + { "PINNEDPUBLICKEY", CURLOPT_PINNEDPUBLICKEY, CURLOT_STRING, 0 }, + { "PIPEWAIT", CURLOPT_PIPEWAIT, CURLOT_LONG, 0 }, + { "PORT", CURLOPT_PORT, CURLOT_LONG, 0 }, + { "POST", CURLOPT_POST, CURLOT_LONG, 0 }, + { "POST301", CURLOPT_POSTREDIR, CURLOT_VALUES, CURLOT_FLAG_ALIAS }, + { "POSTFIELDS", CURLOPT_POSTFIELDS, CURLOT_OBJECT, 0 }, + { "POSTFIELDSIZE", CURLOPT_POSTFIELDSIZE, CURLOT_LONG, 0 }, + { "POSTFIELDSIZE_LARGE", CURLOPT_POSTFIELDSIZE_LARGE, CURLOT_OFF_T, 0 }, + { "POSTQUOTE", CURLOPT_POSTQUOTE, CURLOT_SLIST, 0 }, + { "POSTREDIR", CURLOPT_POSTREDIR, CURLOT_VALUES, 0 }, + { "PREQUOTE", CURLOPT_PREQUOTE, CURLOT_SLIST, 0 }, + { "PREREQDATA", CURLOPT_PREREQDATA, CURLOT_CBPTR, 0 }, + { "PREREQFUNCTION", CURLOPT_PREREQFUNCTION, CURLOT_FUNCTION, 0 }, + { "PRE_PROXY", CURLOPT_PRE_PROXY, CURLOT_STRING, 0 }, + { "PRIVATE", CURLOPT_PRIVATE, CURLOT_OBJECT, 0 }, + { "PROGRESSDATA", CURLOPT_XFERINFODATA, CURLOT_CBPTR, CURLOT_FLAG_ALIAS }, + { "PROGRESSFUNCTION", CURLOPT_PROGRESSFUNCTION, CURLOT_FUNCTION, 0 }, + { "PROTOCOLS", CURLOPT_PROTOCOLS, CURLOT_LONG, 0 }, + { "PROTOCOLS_STR", CURLOPT_PROTOCOLS_STR, CURLOT_STRING, 0 }, + { "PROXY", CURLOPT_PROXY, CURLOT_STRING, 0 }, + { "PROXYAUTH", CURLOPT_PROXYAUTH, CURLOT_VALUES, 0 }, + { "PROXYHEADER", CURLOPT_PROXYHEADER, CURLOT_SLIST, 0 }, + { "PROXYPASSWORD", CURLOPT_PROXYPASSWORD, CURLOT_STRING, 0 }, + { "PROXYPORT", CURLOPT_PROXYPORT, CURLOT_LONG, 0 }, + { "PROXYTYPE", CURLOPT_PROXYTYPE, CURLOT_VALUES, 0 }, + { "PROXYUSERNAME", CURLOPT_PROXYUSERNAME, CURLOT_STRING, 0 }, + { "PROXYUSERPWD", CURLOPT_PROXYUSERPWD, CURLOT_STRING, 0 }, + { "PROXY_CAINFO", CURLOPT_PROXY_CAINFO, CURLOT_STRING, 0 }, + { "PROXY_CAINFO_BLOB", CURLOPT_PROXY_CAINFO_BLOB, CURLOT_BLOB, 0 }, + { "PROXY_CAPATH", CURLOPT_PROXY_CAPATH, CURLOT_STRING, 0 }, + { "PROXY_CRLFILE", CURLOPT_PROXY_CRLFILE, CURLOT_STRING, 0 }, + { "PROXY_ISSUERCERT", CURLOPT_PROXY_ISSUERCERT, CURLOT_STRING, 0 }, + { "PROXY_ISSUERCERT_BLOB", CURLOPT_PROXY_ISSUERCERT_BLOB, CURLOT_BLOB, 0 }, + { "PROXY_KEYPASSWD", CURLOPT_PROXY_KEYPASSWD, CURLOT_STRING, 0 }, + { "PROXY_PINNEDPUBLICKEY", CURLOPT_PROXY_PINNEDPUBLICKEY, + CURLOT_STRING, 0 }, + { "PROXY_SERVICE_NAME", CURLOPT_PROXY_SERVICE_NAME, CURLOT_STRING, 0 }, + { "PROXY_SSLCERT", CURLOPT_PROXY_SSLCERT, CURLOT_STRING, 0 }, + { "PROXY_SSLCERTTYPE", CURLOPT_PROXY_SSLCERTTYPE, CURLOT_STRING, 0 }, + { "PROXY_SSLCERT_BLOB", CURLOPT_PROXY_SSLCERT_BLOB, CURLOT_BLOB, 0 }, + { "PROXY_SSLKEY", CURLOPT_PROXY_SSLKEY, CURLOT_STRING, 0 }, + { "PROXY_SSLKEYTYPE", CURLOPT_PROXY_SSLKEYTYPE, CURLOT_STRING, 0 }, + { "PROXY_SSLKEY_BLOB", CURLOPT_PROXY_SSLKEY_BLOB, CURLOT_BLOB, 0 }, + { "PROXY_SSLVERSION", CURLOPT_PROXY_SSLVERSION, CURLOT_VALUES, 0 }, + { "PROXY_SSL_CIPHER_LIST", CURLOPT_PROXY_SSL_CIPHER_LIST, + CURLOT_STRING, 0 }, + { "PROXY_SSL_OPTIONS", CURLOPT_PROXY_SSL_OPTIONS, CURLOT_LONG, 0 }, + { "PROXY_SSL_VERIFYHOST", CURLOPT_PROXY_SSL_VERIFYHOST, CURLOT_LONG, 0 }, + { "PROXY_SSL_VERIFYPEER", CURLOPT_PROXY_SSL_VERIFYPEER, CURLOT_LONG, 0 }, + { "PROXY_TLS13_CIPHERS", CURLOPT_PROXY_TLS13_CIPHERS, CURLOT_STRING, 0 }, + { "PROXY_TLSAUTH_PASSWORD", CURLOPT_PROXY_TLSAUTH_PASSWORD, + CURLOT_STRING, 0 }, + { "PROXY_TLSAUTH_TYPE", CURLOPT_PROXY_TLSAUTH_TYPE, CURLOT_STRING, 0 }, + { "PROXY_TLSAUTH_USERNAME", CURLOPT_PROXY_TLSAUTH_USERNAME, + CURLOT_STRING, 0 }, + { "PROXY_TRANSFER_MODE", CURLOPT_PROXY_TRANSFER_MODE, CURLOT_LONG, 0 }, + { "PUT", CURLOPT_PUT, CURLOT_LONG, 0 }, + { "QUICK_EXIT", CURLOPT_QUICK_EXIT, CURLOT_LONG, 0 }, + { "QUOTE", CURLOPT_QUOTE, CURLOT_SLIST, 0 }, + { "RANDOM_FILE", CURLOPT_RANDOM_FILE, CURLOT_STRING, 0 }, + { "RANGE", CURLOPT_RANGE, CURLOT_STRING, 0 }, + { "READDATA", CURLOPT_READDATA, CURLOT_CBPTR, 0 }, + { "READFUNCTION", CURLOPT_READFUNCTION, CURLOT_FUNCTION, 0 }, + { "REDIR_PROTOCOLS", CURLOPT_REDIR_PROTOCOLS, CURLOT_LONG, 0 }, + { "REDIR_PROTOCOLS_STR", CURLOPT_REDIR_PROTOCOLS_STR, CURLOT_STRING, 0 }, + { "REFERER", CURLOPT_REFERER, CURLOT_STRING, 0 }, + { "REQUEST_TARGET", CURLOPT_REQUEST_TARGET, CURLOT_STRING, 0 }, + { "RESOLVE", CURLOPT_RESOLVE, CURLOT_SLIST, 0 }, + { "RESOLVER_START_DATA", CURLOPT_RESOLVER_START_DATA, CURLOT_CBPTR, 0 }, + { "RESOLVER_START_FUNCTION", CURLOPT_RESOLVER_START_FUNCTION, + CURLOT_FUNCTION, 0 }, + { "RESUME_FROM", CURLOPT_RESUME_FROM, CURLOT_LONG, 0 }, + { "RESUME_FROM_LARGE", CURLOPT_RESUME_FROM_LARGE, CURLOT_OFF_T, 0 }, + { "RTSPHEADER", CURLOPT_HTTPHEADER, CURLOT_SLIST, CURLOT_FLAG_ALIAS }, + { "RTSP_CLIENT_CSEQ", CURLOPT_RTSP_CLIENT_CSEQ, CURLOT_LONG, 0 }, + { "RTSP_REQUEST", CURLOPT_RTSP_REQUEST, CURLOT_VALUES, 0 }, + { "RTSP_SERVER_CSEQ", CURLOPT_RTSP_SERVER_CSEQ, CURLOT_LONG, 0 }, + { "RTSP_SESSION_ID", CURLOPT_RTSP_SESSION_ID, CURLOT_STRING, 0 }, + { "RTSP_STREAM_URI", CURLOPT_RTSP_STREAM_URI, CURLOT_STRING, 0 }, + { "RTSP_TRANSPORT", CURLOPT_RTSP_TRANSPORT, CURLOT_STRING, 0 }, + { "SASL_AUTHZID", CURLOPT_SASL_AUTHZID, CURLOT_STRING, 0 }, + { "SASL_IR", CURLOPT_SASL_IR, CURLOT_LONG, 0 }, + { "SEEKDATA", CURLOPT_SEEKDATA, CURLOT_CBPTR, 0 }, + { "SEEKFUNCTION", CURLOPT_SEEKFUNCTION, CURLOT_FUNCTION, 0 }, + { "SERVER_RESPONSE_TIMEOUT", CURLOPT_SERVER_RESPONSE_TIMEOUT, + CURLOT_LONG, 0 }, + { "SERVER_RESPONSE_TIMEOUT_MS", CURLOPT_SERVER_RESPONSE_TIMEOUT_MS, + CURLOT_LONG, 0 }, + { "SERVICE_NAME", CURLOPT_SERVICE_NAME, CURLOT_STRING, 0 }, + { "SHARE", CURLOPT_SHARE, CURLOT_OBJECT, 0 }, + { "SOCKOPTDATA", CURLOPT_SOCKOPTDATA, CURLOT_CBPTR, 0 }, + { "SOCKOPTFUNCTION", CURLOPT_SOCKOPTFUNCTION, CURLOT_FUNCTION, 0 }, + { "SOCKS5_AUTH", CURLOPT_SOCKS5_AUTH, CURLOT_LONG, 0 }, + { "SOCKS5_GSSAPI_NEC", CURLOPT_SOCKS5_GSSAPI_NEC, CURLOT_LONG, 0 }, + { "SOCKS5_GSSAPI_SERVICE", CURLOPT_SOCKS5_GSSAPI_SERVICE, + CURLOT_STRING, 0 }, + { "SSH_AUTH_TYPES", CURLOPT_SSH_AUTH_TYPES, CURLOT_VALUES, 0 }, + { "SSH_COMPRESSION", CURLOPT_SSH_COMPRESSION, CURLOT_LONG, 0 }, + { "SSH_HOSTKEYDATA", CURLOPT_SSH_HOSTKEYDATA, CURLOT_CBPTR, 0 }, + { "SSH_HOSTKEYFUNCTION", CURLOPT_SSH_HOSTKEYFUNCTION, CURLOT_FUNCTION, 0 }, + { "SSH_HOST_PUBLIC_KEY_MD5", CURLOPT_SSH_HOST_PUBLIC_KEY_MD5, + CURLOT_STRING, 0 }, + { "SSH_HOST_PUBLIC_KEY_SHA256", CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256, + CURLOT_STRING, 0 }, + { "SSH_KEYDATA", CURLOPT_SSH_KEYDATA, CURLOT_CBPTR, 0 }, + { "SSH_KEYFUNCTION", CURLOPT_SSH_KEYFUNCTION, CURLOT_FUNCTION, 0 }, + { "SSH_KNOWNHOSTS", CURLOPT_SSH_KNOWNHOSTS, CURLOT_STRING, 0 }, + { "SSH_PRIVATE_KEYFILE", CURLOPT_SSH_PRIVATE_KEYFILE, CURLOT_STRING, 0 }, + { "SSH_PUBLIC_KEYFILE", CURLOPT_SSH_PUBLIC_KEYFILE, CURLOT_STRING, 0 }, + { "SSLCERT", CURLOPT_SSLCERT, CURLOT_STRING, 0 }, + { "SSLCERTPASSWD", CURLOPT_KEYPASSWD, CURLOT_STRING, CURLOT_FLAG_ALIAS }, + { "SSLCERTTYPE", CURLOPT_SSLCERTTYPE, CURLOT_STRING, 0 }, + { "SSLCERT_BLOB", CURLOPT_SSLCERT_BLOB, CURLOT_BLOB, 0 }, + { "SSLENGINE", CURLOPT_SSLENGINE, CURLOT_STRING, 0 }, + { "SSLENGINE_DEFAULT", CURLOPT_SSLENGINE_DEFAULT, CURLOT_LONG, 0 }, + { "SSLKEY", CURLOPT_SSLKEY, CURLOT_STRING, 0 }, + { "SSLKEYPASSWD", CURLOPT_KEYPASSWD, CURLOT_STRING, CURLOT_FLAG_ALIAS }, + { "SSLKEYTYPE", CURLOPT_SSLKEYTYPE, CURLOT_STRING, 0 }, + { "SSLKEY_BLOB", CURLOPT_SSLKEY_BLOB, CURLOT_BLOB, 0 }, + { "SSLVERSION", CURLOPT_SSLVERSION, CURLOT_VALUES, 0 }, + { "SSL_CIPHER_LIST", CURLOPT_SSL_CIPHER_LIST, CURLOT_STRING, 0 }, + { "SSL_CTX_DATA", CURLOPT_SSL_CTX_DATA, CURLOT_CBPTR, 0 }, + { "SSL_CTX_FUNCTION", CURLOPT_SSL_CTX_FUNCTION, CURLOT_FUNCTION, 0 }, + { "SSL_EC_CURVES", CURLOPT_SSL_EC_CURVES, CURLOT_STRING, 0 }, + { "SSL_ENABLE_ALPN", CURLOPT_SSL_ENABLE_ALPN, CURLOT_LONG, 0 }, + { "SSL_ENABLE_NPN", CURLOPT_SSL_ENABLE_NPN, CURLOT_LONG, 0 }, + { "SSL_FALSESTART", CURLOPT_SSL_FALSESTART, CURLOT_LONG, 0 }, + { "SSL_OPTIONS", CURLOPT_SSL_OPTIONS, CURLOT_VALUES, 0 }, + { "SSL_SESSIONID_CACHE", CURLOPT_SSL_SESSIONID_CACHE, CURLOT_LONG, 0 }, + { "SSL_SIGNATURE_ALGORITHMS", CURLOPT_SSL_SIGNATURE_ALGORITHMS, + CURLOT_STRING, 0 }, + { "SSL_VERIFYHOST", CURLOPT_SSL_VERIFYHOST, CURLOT_LONG, 0 }, + { "SSL_VERIFYPEER", CURLOPT_SSL_VERIFYPEER, CURLOT_LONG, 0 }, + { "SSL_VERIFYSTATUS", CURLOPT_SSL_VERIFYSTATUS, CURLOT_LONG, 0 }, + { "STDERR", CURLOPT_STDERR, CURLOT_OBJECT, 0 }, + { "STREAM_DEPENDS", CURLOPT_STREAM_DEPENDS, CURLOT_OBJECT, 0 }, + { "STREAM_DEPENDS_E", CURLOPT_STREAM_DEPENDS_E, CURLOT_OBJECT, 0 }, + { "STREAM_WEIGHT", CURLOPT_STREAM_WEIGHT, CURLOT_LONG, 0 }, + { "SUPPRESS_CONNECT_HEADERS", CURLOPT_SUPPRESS_CONNECT_HEADERS, + CURLOT_LONG, 0 }, + { "TCP_FASTOPEN", CURLOPT_TCP_FASTOPEN, CURLOT_LONG, 0 }, + { "TCP_KEEPALIVE", CURLOPT_TCP_KEEPALIVE, CURLOT_LONG, 0 }, + { "TCP_KEEPCNT", CURLOPT_TCP_KEEPCNT, CURLOT_LONG, 0 }, + { "TCP_KEEPIDLE", CURLOPT_TCP_KEEPIDLE, CURLOT_LONG, 0 }, + { "TCP_KEEPINTVL", CURLOPT_TCP_KEEPINTVL, CURLOT_LONG, 0 }, + { "TCP_NODELAY", CURLOPT_TCP_NODELAY, CURLOT_LONG, 0 }, + { "TELNETOPTIONS", CURLOPT_TELNETOPTIONS, CURLOT_SLIST, 0 }, + { "TFTP_BLKSIZE", CURLOPT_TFTP_BLKSIZE, CURLOT_LONG, 0 }, + { "TFTP_NO_OPTIONS", CURLOPT_TFTP_NO_OPTIONS, CURLOT_LONG, 0 }, + { "TIMECONDITION", CURLOPT_TIMECONDITION, CURLOT_VALUES, 0 }, + { "TIMEOUT", CURLOPT_TIMEOUT, CURLOT_LONG, 0 }, + { "TIMEOUT_MS", CURLOPT_TIMEOUT_MS, CURLOT_LONG, 0 }, + { "TIMEVALUE", CURLOPT_TIMEVALUE, CURLOT_LONG, 0 }, + { "TIMEVALUE_LARGE", CURLOPT_TIMEVALUE_LARGE, CURLOT_OFF_T, 0 }, + { "TLS13_CIPHERS", CURLOPT_TLS13_CIPHERS, CURLOT_STRING, 0 }, + { "TLSAUTH_PASSWORD", CURLOPT_TLSAUTH_PASSWORD, CURLOT_STRING, 0 }, + { "TLSAUTH_TYPE", CURLOPT_TLSAUTH_TYPE, CURLOT_STRING, 0 }, + { "TLSAUTH_USERNAME", CURLOPT_TLSAUTH_USERNAME, CURLOT_STRING, 0 }, + { "TRAILERDATA", CURLOPT_TRAILERDATA, CURLOT_CBPTR, 0 }, + { "TRAILERFUNCTION", CURLOPT_TRAILERFUNCTION, CURLOT_FUNCTION, 0 }, + { "TRANSFERTEXT", CURLOPT_TRANSFERTEXT, CURLOT_LONG, 0 }, + { "TRANSFER_ENCODING", CURLOPT_TRANSFER_ENCODING, CURLOT_LONG, 0 }, + { "UNIX_SOCKET_PATH", CURLOPT_UNIX_SOCKET_PATH, CURLOT_STRING, 0 }, + { "UNRESTRICTED_AUTH", CURLOPT_UNRESTRICTED_AUTH, CURLOT_LONG, 0 }, + { "UPKEEP_INTERVAL_MS", CURLOPT_UPKEEP_INTERVAL_MS, CURLOT_LONG, 0 }, + { "UPLOAD", CURLOPT_UPLOAD, CURLOT_LONG, 0 }, + { "UPLOAD_BUFFERSIZE", CURLOPT_UPLOAD_BUFFERSIZE, CURLOT_LONG, 0 }, + { "UPLOAD_FLAGS", CURLOPT_UPLOAD_FLAGS, CURLOT_LONG, 0 }, + { "URL", CURLOPT_URL, CURLOT_STRING, 0 }, + { "USERAGENT", CURLOPT_USERAGENT, CURLOT_STRING, 0 }, + { "USERNAME", CURLOPT_USERNAME, CURLOT_STRING, 0 }, + { "USERPWD", CURLOPT_USERPWD, CURLOT_STRING, 0 }, + { "USE_SSL", CURLOPT_USE_SSL, CURLOT_VALUES, 0 }, + { "VERBOSE", CURLOPT_VERBOSE, CURLOT_LONG, 0 }, + { "WILDCARDMATCH", CURLOPT_WILDCARDMATCH, CURLOT_LONG, 0 }, + { "WRITEDATA", CURLOPT_WRITEDATA, CURLOT_CBPTR, 0 }, + { "WRITEFUNCTION", CURLOPT_WRITEFUNCTION, CURLOT_FUNCTION, 0 }, + { "WRITEHEADER", CURLOPT_HEADERDATA, CURLOT_CBPTR, CURLOT_FLAG_ALIAS }, + { "WS_OPTIONS", CURLOPT_WS_OPTIONS, CURLOT_LONG, 0 }, + { "XFERINFODATA", CURLOPT_XFERINFODATA, CURLOT_CBPTR, 0 }, + { "XFERINFOFUNCTION", CURLOPT_XFERINFOFUNCTION, CURLOT_FUNCTION, 0 }, + { "XOAUTH2_BEARER", CURLOPT_XOAUTH2_BEARER, CURLOT_STRING, 0 }, + { NULL, CURLOPT_LASTENTRY, CURLOT_LONG, 0 } /* end of table */ +}; + +#ifdef DEBUGBUILD +/* + * Curl_easyopts_check() is a debug-only function that returns non-zero + * if this source file is not in sync with the options listed in curl/curl.h + */ +int Curl_easyopts_check(void) +{ + return (CURLOPT_LASTENTRY % 10000) != (332 + 1); +} +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/easyoptions.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/easyoptions.h new file mode 100644 index 0000000000..d895653ce9 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/easyoptions.h @@ -0,0 +1,35 @@ +#ifndef HEADER_CURL_EASYOPTIONS_H +#define HEADER_CURL_EASYOPTIONS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* should probably go into the public header */ + +/* generated table with all easy options */ +extern const struct curl_easyoption Curl_easyopts[]; + +#ifdef DEBUGBUILD +int Curl_easyopts_check(void); +#endif + +#endif /* HEADER_CURL_EASYOPTIONS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/escape.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/escape.c new file mode 100644 index 0000000000..a1a714f8f5 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/escape.c @@ -0,0 +1,228 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* Escape and unescape URL encoding in strings. The functions return a new + * allocated string or NULL if an error occurred. */ +#include "curl_setup.h" + +struct Curl_easy; + +#include "urldata.h" +#include "escape.h" +#include "curlx/strparse.h" +#include "curl_printf.h" + +/* for ABI-compatibility with previous versions */ +char *curl_escape(const char *string, int length) +{ + return curl_easy_escape(NULL, string, length); +} + +/* for ABI-compatibility with previous versions */ +char *curl_unescape(const char *string, int length) +{ + return curl_easy_unescape(NULL, string, length, NULL); +} + +/* Escapes for URL the given unescaped string of given length. + * 'data' is ignored since 7.82.0. + */ +char *curl_easy_escape(CURL *curl, const char *string, int length) +{ + size_t len; + struct dynbuf d; + (void)curl; + + if(!string || (length < 0)) + return NULL; + + len = (length ? (size_t)length : strlen(string)); + if(!len) + return curlx_strdup(""); + + if(len > SIZE_MAX / 16) + return NULL; + + curlx_dyn_init(&d, (len * 3) + 1); + + while(len--) { + /* treat the characters unsigned */ + unsigned char in = (unsigned char)*string++; + + if(ISUNRESERVED(in)) { + /* append this */ + if(curlx_dyn_addn(&d, &in, 1)) + return NULL; + } + else { + /* encode it */ + unsigned char out[3] = { '%' }; + Curl_hexbyte(&out[1], in); + if(curlx_dyn_addn(&d, out, 3)) + return NULL; + } + } + + return curlx_dyn_ptr(&d); +} + +/* + * Curl_urldecode() URL decodes the given string. + * + * Returns a pointer to a malloced string in *ostring with length given in + * *olen. If length == 0, the length is assumed to be strlen(string). + * + * ctrl options: + * - REJECT_NADA: accept everything + * - REJECT_CTRL: rejects control characters (byte codes lower than 32) in + * the data + * - REJECT_ZERO: rejects decoded zero bytes + * + * The values for the enum starts at 2, to make the assert detect legacy + * invokes that used TRUE/FALSE (0 and 1). + */ + +CURLcode Curl_urldecode(const char *string, size_t length, + char **ostring, size_t *olen, + enum urlreject ctrl) +{ + size_t alloc; + char *ns; + + DEBUGASSERT(string); + DEBUGASSERT(ctrl >= REJECT_NADA); /* crash on TRUE/FALSE */ + + alloc = (length ? length : strlen(string)); + ns = curlx_malloc(alloc + 1); + + if(!ns) + return CURLE_OUT_OF_MEMORY; + + /* store output string */ + *ostring = ns; + + while(alloc) { + unsigned char in = (unsigned char)*string; + if(('%' == in) && (alloc > 2) && + ISXDIGIT(string[1]) && ISXDIGIT(string[2])) { + /* this is two hexadecimal digits following a '%' */ + in = (unsigned char)((curlx_hexval(string[1]) << 4) | + curlx_hexval(string[2])); + string += 3; + alloc -= 3; + } + else { + string++; + alloc--; + } + + if(((ctrl == REJECT_CTRL) && (in < 0x20)) || + ((ctrl == REJECT_ZERO) && (in == 0))) { + curlx_safefree(*ostring); + return CURLE_URL_MALFORMAT; + } + + *ns++ = (char)in; + } + *ns = 0; /* terminate it */ + + if(olen) + /* store output size */ + *olen = ns - *ostring; + + return CURLE_OK; +} + +/* + * Unescapes the given URL escaped string of given length. Returns a + * pointer to a malloced string with length given in *olen. + * If length == 0, the length is assumed to be strlen(string). + * If olen == NULL, no output length is stored. + * 'data' is ignored since 7.82.0. + */ +char *curl_easy_unescape(CURL *curl, const char *string, int inlength, + int *outlength) +{ + char *str = NULL; + (void)curl; + if(string && (inlength >= 0)) { + size_t inputlen = (size_t)inlength; + size_t outputlen; + CURLcode res = Curl_urldecode(string, inputlen, &str, &outputlen, + REJECT_NADA); + if(res) + return NULL; + + if(outlength) { + if(outputlen <= (size_t)INT_MAX) + *outlength = curlx_uztosi(outputlen); + else + /* too large to return in an int, fail! */ + curlx_safefree(str); + } + } + return str; +} + +/* For operating systems/environments that use different malloc/free + systems for the app and for this library, we provide a free that uses + the library's memory system */ +void curl_free(void *p) +{ + curlx_free(p); +} + +/* + * Curl_hexencode() + * + * Converts binary input to lowercase hex-encoded ASCII output. + * null-terminated. + */ +void Curl_hexencode(const unsigned char *src, size_t len, /* input length */ + unsigned char *out, size_t olen) /* output buffer size */ +{ + DEBUGASSERT(src && len && (olen >= 3)); + if(src && len && (olen >= 3)) { + while(len-- && (olen >= 3)) { + out[0] = Curl_ldigits[*src >> 4]; + out[1] = Curl_ldigits[*src & 0x0F]; + ++src; + out += 2; + olen -= 2; + } + *out = 0; + } + else if(olen) + *out = 0; +} + +/* Curl_hexbyte + * + * Output a single unsigned char as a two-digit UPPERCASE hex number. + */ +void Curl_hexbyte(unsigned char *dest, /* must fit two bytes */ + unsigned char val) +{ + dest[0] = Curl_udigits[val >> 4]; + dest[1] = Curl_udigits[val & 0x0F]; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/escape.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/escape.h new file mode 100644 index 0000000000..9f9a89e402 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/escape.h @@ -0,0 +1,45 @@ +#ifndef HEADER_CURL_ESCAPE_H +#define HEADER_CURL_ESCAPE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* Escape and unescape URL encoding in strings. The functions return a new + * allocated string or NULL if an error occurred. */ + +enum urlreject { + REJECT_NADA = 2, + REJECT_CTRL, + REJECT_ZERO +}; + +CURLcode Curl_urldecode(const char *string, size_t length, + char **ostring, size_t *olen, + enum urlreject ctrl); + +void Curl_hexencode(const unsigned char *src, size_t len, /* input length */ + unsigned char *out, size_t olen); /* output buffer size */ + +void Curl_hexbyte(unsigned char *dest, /* must fit two bytes */ + unsigned char val); + +#endif /* HEADER_CURL_ESCAPE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/fake_addrinfo.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/fake_addrinfo.c new file mode 100644 index 0000000000..6857d63485 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/fake_addrinfo.c @@ -0,0 +1,202 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "fake_addrinfo.h" + +#ifdef USE_FAKE_GETADDRINFO + +#include <ares.h> + +void r_freeaddrinfo(struct addrinfo *cahead) +{ + struct addrinfo *canext; + struct addrinfo *ca; + + for(ca = cahead; ca; ca = canext) { + canext = ca->ai_next; + curlx_free(ca); + } +} + +struct context { + struct ares_addrinfo *addr; + int status; +}; + +static void async_addrinfo_cb(void *userp, int status, int timeouts, + struct ares_addrinfo *addr) +{ + struct context *ctx = (struct context *)userp; + (void)timeouts; + ctx->status = status; + if(ARES_SUCCESS == status) { + ctx->addr = addr; + } +} + +/* convert the c-ares version into the "native" version */ +static struct addrinfo *mk_getaddrinfo(const struct ares_addrinfo *aihead) +{ + const struct ares_addrinfo_node *ai; + struct addrinfo *ca; + struct addrinfo *cafirst = NULL; + struct addrinfo *calast = NULL; + const char *name = aihead->name; + + /* traverse the addrinfo list */ + for(ai = aihead->nodes; ai; ai = ai->ai_next) { + size_t ss_size; + size_t namelen = name ? strlen(name) + 1 : 0; + /* ignore elements with unsupported address family, + settle family-specific sockaddr structure size. */ + if(ai->ai_family == AF_INET) + ss_size = sizeof(struct sockaddr_in); + else if(ai->ai_family == AF_INET6) + ss_size = sizeof(struct sockaddr_in6); + else + continue; + + /* ignore elements without required address info */ + if(!ai->ai_addr || !(ai->ai_addrlen > 0)) + continue; + + /* ignore elements with bogus address size */ + if((size_t)ai->ai_addrlen < ss_size) + continue; + + ca = curlx_malloc(sizeof(struct addrinfo) + ss_size + namelen); + if(!ca) { + r_freeaddrinfo(cafirst); + return NULL; + } + + /* copy each structure member individually, member ordering, + size, or padding might be different for each platform. */ + + ca->ai_flags = ai->ai_flags; + ca->ai_family = ai->ai_family; + ca->ai_socktype = ai->ai_socktype; + ca->ai_protocol = ai->ai_protocol; + ca->ai_addrlen = (curl_socklen_t)ss_size; + ca->ai_addr = NULL; + ca->ai_canonname = NULL; + ca->ai_next = NULL; + + ca->ai_addr = (void *)((char *)ca + sizeof(struct addrinfo)); + memcpy(ca->ai_addr, ai->ai_addr, ss_size); + + if(namelen) { + ca->ai_canonname = (void *)((char *)ca->ai_addr + ss_size); + memcpy(ca->ai_canonname, name, namelen); + + /* the name is only pointed to by the first entry in the "real" + addrinfo chain, so stop now */ + name = NULL; + } + + /* if the return list is empty, this becomes the first element */ + if(!cafirst) + cafirst = ca; + + /* add this element last in the return list */ + if(calast) + calast->ai_next = ca; + calast = ca; + } + + return cafirst; +} + +/* RETURN VALUE + getaddrinfo() returns 0 if it succeeds, or one of the following nonzero + error codes: + ... */ +int r_getaddrinfo(const char *node, + const char *service, + const struct addrinfo *hints, + struct addrinfo **res) +{ + int status; + struct context ctx; + struct ares_options options; + int optmask = 0; + struct ares_addrinfo_hints ahints; + ares_channel channel; + int rc = 0; + + memset(&options, 0, sizeof(options)); + optmask |= ARES_OPT_EVENT_THREAD; + options.evsys = ARES_EVSYS_DEFAULT; + + memset(&ahints, 0, sizeof(ahints)); + memset(&ctx, 0, sizeof(ctx)); + + if(hints) { + ahints.ai_flags = hints->ai_flags; + ahints.ai_family = hints->ai_family; + ahints.ai_socktype = hints->ai_socktype; + ahints.ai_protocol = hints->ai_protocol; + } + + status = ares_init_options(&channel, &options, optmask); + if(status) + return EAI_MEMORY; /* major problem */ + + else { + const char *env = getenv("CURL_DNS_SERVER"); + if(env) { + rc = ares_set_servers_ports_csv(channel, env); + if(rc) { + curl_mfprintf(stderr, "ares_set_servers_ports_csv failed: %d", rc); + /* Cleanup */ + ares_destroy(channel); + return EAI_MEMORY; /* we cannot run */ + } + } + } + + ares_getaddrinfo(channel, node, service, &ahints, async_addrinfo_cb, &ctx); + + /* Wait until no more requests are left to be processed */ + ares_queue_wait_empty(channel, -1); + + if(ctx.addr) { + /* convert the c-ares version */ + *res = mk_getaddrinfo(ctx.addr); + /* free the old */ + ares_freeaddrinfo(ctx.addr); + } + else if((ctx.status == ARES_ENOTFOUND) || (ctx.status == ARES_ENODATA)) + rc = EAI_NONAME; /* no such name */ + else + rc = EAI_AGAIN; /* failed without an authoritative answer */ + + /* Cleanup */ + ares_destroy(channel); + + return rc; +} + +#endif /* USE_FAKE_GETADDRINFO */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/fake_addrinfo.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/fake_addrinfo.h new file mode 100644 index 0000000000..69579da2e5 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/fake_addrinfo.h @@ -0,0 +1,53 @@ +#ifndef HEADER_FAKE_ADDRINFO_H +#define HEADER_FAKE_ADDRINFO_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_ARES +#include <ares.h> +#endif + +#if defined(CURL_MEMDEBUG) && defined(HAVE_GETADDRINFO) && \ + defined(USE_ARES) && (ARES_VERSION >= 0x011a00) /* >= 1.26.0 */ +#define USE_FAKE_GETADDRINFO 1 +#endif + +#ifdef USE_FAKE_GETADDRINFO + +#ifdef HAVE_NETDB_H +# include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +# include <arpa/inet.h> +#endif + +void r_freeaddrinfo(struct addrinfo *cahead); +int r_getaddrinfo(const char *node, + const char *service, + const struct addrinfo *hints, + struct addrinfo **res); +#endif /* USE_FAKE_GETADDRINFO */ + +#endif /* HEADER_FAKE_ADDRINFO_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/file.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/file.c new file mode 100644 index 0000000000..d3553b7df2 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/file.c @@ -0,0 +1,718 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" +#include "file.h" + +#ifndef CURL_DISABLE_FILE + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NET_IF_H +#include <net/if.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif + +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif + +#ifdef HAVE_DIRENT_H +#include <dirent.h> +#endif + +#include "progress.h" +#include "sendf.h" +#include "curl_trc.h" +#include "escape.h" +#include "multiif.h" +#include "transfer.h" +#include "url.h" +#include "parsedate.h" /* for the week day and month names */ +#include "curlx/fopen.h" +#include "curl_range.h" + +#if defined(_WIN32) || defined(MSDOS) +#define DOS_FILESYSTEM 1 +#elif defined(__amigaos4__) +#define AMIGA_FILESYSTEM 1 +#endif + +/* meta key for storing protocol meta at easy handle */ +#define CURL_META_FILE_EASY "meta:proto:file:easy" + +struct FILEPROTO { + char *path; /* the path we operate on */ + char *freepath; /* pointer to the allocated block we must free, this might + differ from the 'path' pointer */ + int fd; /* open file descriptor to read from! */ + bool is_dir; +}; + +static void file_cleanup(struct FILEPROTO *file) +{ + curlx_safefree(file->freepath); + file->path = NULL; + file->is_dir = FALSE; + if(file->fd != -1) { + curlx_close(file->fd); + file->fd = -1; + } +} + +static void file_easy_dtor(void *key, size_t klen, void *entry) +{ + struct FILEPROTO *file = entry; + (void)key; + (void)klen; + file_cleanup(file); + curlx_free(file); +} + +static CURLcode file_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + struct FILEPROTO *filep; + (void)conn; + /* allocate the FILE specific struct */ + filep = curlx_calloc(1, sizeof(*filep)); + if(filep) + filep->fd = -1; + if(!filep || + Curl_meta_set(data, CURL_META_FILE_EASY, filep, file_easy_dtor)) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static CURLcode file_done(struct Curl_easy *data, + CURLcode status, bool premature) +{ + struct FILEPROTO *file = Curl_meta_get(data, CURL_META_FILE_EASY); + (void)status; + (void)premature; + + if(file) + file_cleanup(file); + + return CURLE_OK; +} + +static int file_stat(const char *path, curlx_struct_stat *statbuf) +{ +#ifdef _WIN32 + int result = curlx_stat(path, statbuf); + + if(result) { + size_t pathlen = strlen(path); + + /* MSVCRT's narrow stat() rejects trailing directory separators. */ + if((pathlen > 3) && + ((path[pathlen - 1] == '\\') || (path[pathlen - 1] == '/'))) { + char *trimmed = curlx_strdup(path); + + if(trimmed) { + do { + trimmed[--pathlen] = '\0'; + } while((pathlen > 3) && + ((trimmed[pathlen - 1] == '\\') || + (trimmed[pathlen - 1] == '/'))); + + result = curlx_stat(trimmed, statbuf); + curlx_free(trimmed); + } + } + } + + return result; +#else + return curlx_stat(path, statbuf); +#endif +} + +/* + * file_connect() gets called from Curl_protocol_connect() to allow us to + * do protocol-specific actions at connect-time. We emulate a + * connect-then-transfer protocol and "connect" to the file here + */ +static CURLcode file_connect(struct Curl_easy *data, bool *done) +{ + char *real_path; + struct FILEPROTO *file = Curl_meta_get(data, CURL_META_FILE_EASY); +#ifdef _WIN32 + curlx_struct_stat statbuf; +#endif + int fd; +#ifdef DOS_FILESYSTEM + size_t i; + char *actual_path; +#endif + size_t real_path_len; + CURLcode result; + + if(!file) + return CURLE_FAILED_INIT; + + if(file->path) { + /* already connected. + * the handler->connect_it() is normally only called once, but + * FILE does a special check on setting up the connection which + * calls this explicitly. */ + *done = TRUE; + return CURLE_OK; + } + + result = Curl_urldecode(data->state.up.path, 0, &real_path, + &real_path_len, REJECT_ZERO); + if(result) + return result; + +#ifdef DOS_FILESYSTEM + /* If the first character is a slash, and there is + something that looks like a drive at the beginning of + the path, skip the slash. If we remove the initial + slash in all cases, paths without drive letters end up + relative to the current directory which is not how + browsers work. + + Some browsers accept | instead of : as the drive letter + separator, so we do too. + + On other platforms, we need the slash to indicate an + absolute pathname. On Windows, absolute paths start + with a drive letter. */ + actual_path = real_path; + if((actual_path[0] == '/') && + actual_path[1] && + (actual_path[2] == ':' || actual_path[2] == '|')) { + actual_path[2] = ':'; + actual_path++; + real_path_len--; + } + + /* change path separators from '/' to '\\' for DOS, Windows and OS/2 */ + for(i = 0; i < real_path_len; ++i) + if(actual_path[i] == '/') + actual_path[i] = '\\'; + else if(!actual_path[i]) { /* binary zero */ + curlx_safefree(real_path); + return CURLE_URL_MALFORMAT; + } + + fd = curlx_open(actual_path, O_RDONLY | CURL_O_BINARY); + file->path = actual_path; +#else + if(memchr(real_path, 0, real_path_len)) { + /* binary zeroes indicate foul play */ + curlx_safefree(real_path); + return CURLE_URL_MALFORMAT; + } + +#ifdef AMIGA_FILESYSTEM + /* + * A leading slash in an AmigaDOS path denotes the parent + * directory, and hence we block this as it is relative. + * Absolute paths start with 'volumename:', so we check for + * this first. Failing that, we treat the path as a real Unix + * path, but only if the application was compiled with -lunix. + */ + fd = -1; + file->path = real_path; + + if(real_path[0] == '/') { + extern int __unix_path_semantics; + if(strchr(real_path + 1, ':')) { + /* Amiga absolute path */ + fd = curlx_open(real_path + 1, O_RDONLY); + file->path++; + } + else if(__unix_path_semantics) { + /* -lunix fallback */ + fd = curlx_open(real_path, O_RDONLY); + } + } +#else + fd = curlx_open(real_path, O_RDONLY); + file->path = real_path; +#endif +#endif + curlx_free(file->freepath); + file->freepath = real_path; /* free this when done */ + + file->fd = fd; +#ifdef _WIN32 + if(!data->state.upload && (fd == -1) && + !file_stat(file->path, &statbuf) && S_ISDIR(statbuf.st_mode)) + file->is_dir = TRUE; +#endif + + if(!data->state.upload && (fd == -1) && !file->is_dir) { + failf(data, "Could not open file %s", data->state.up.path); + file_done(data, CURLE_FILE_COULDNT_READ_FILE, FALSE); + return CURLE_FILE_COULDNT_READ_FILE; + } + *done = TRUE; + + return CURLE_OK; +} + +static CURLcode file_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + (void)dead_connection; + (void)conn; + return file_done(data, CURLE_OK, FALSE); +} + +#ifdef DOS_FILESYSTEM +#define DIRSEP '\\' +#else +#define DIRSEP '/' +#endif + +static CURLcode file_upload(struct Curl_easy *data, + struct FILEPROTO *file) +{ + const char *dir = strchr(file->path, DIRSEP); + int fd; + int mode; + CURLcode result = CURLE_OK; + char *xfer_ulbuf; + size_t xfer_ulblen; + curlx_struct_stat file_stat; + const char *sendbuf; + bool eos = FALSE; + + /* + * Since FILE: does not do the full init, we need to provide some extra + * assignments here. + */ + + if(!dir) + return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */ + + if(!dir[1]) + return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */ + + mode = O_WRONLY | O_CREAT | CURL_O_BINARY; + if(data->state.resume_from) + mode |= O_APPEND; + else + mode |= O_TRUNC; + +#ifdef _WIN32 + fd = curlx_open(file->path, mode, + data->set.new_file_perms & (_S_IREAD | _S_IWRITE)); +#elif (defined(ANDROID) || defined(__ANDROID__)) && \ + (defined(__i386__) || defined(__arm__)) + fd = curlx_open(file->path, mode, (mode_t)data->set.new_file_perms); +#else + fd = curlx_open(file->path, mode, data->set.new_file_perms); +#endif + if(fd < 0) { + failf(data, "cannot open %s for writing", file->path); + return CURLE_WRITE_ERROR; + } + + if(data->state.infilesize != -1) + /* known size of data to "upload" */ + Curl_pgrsSetUploadSize(data, data->state.infilesize); + + /* treat the negative resume offset value as the case of "-" */ + if(data->state.resume_from < 0) { + if(curlx_fstat(fd, &file_stat)) { + curlx_close(fd); + failf(data, "cannot get the size of %s", file->path); + return CURLE_WRITE_ERROR; + } + data->state.resume_from = (curl_off_t)file_stat.st_size; + } + + result = Curl_multi_xfer_ulbuf_borrow(data, &xfer_ulbuf, &xfer_ulblen); + if(result) + goto out; + + while(!result && !eos) { + size_t nread, nwritten; + ssize_t rv; + size_t readcount; + + result = Curl_client_read(data, xfer_ulbuf, xfer_ulblen, &readcount, &eos); + if(result) + break; + + if(!readcount) + break; + + nread = readcount; + + /* skip bytes before resume point */ + if(data->state.resume_from) { + if((curl_off_t)nread <= data->state.resume_from) { + data->state.resume_from -= nread; + nread = 0; + sendbuf = xfer_ulbuf; + } + else { + sendbuf = xfer_ulbuf + data->state.resume_from; + nread -= (size_t)data->state.resume_from; + data->state.resume_from = 0; + } + } + else + sendbuf = xfer_ulbuf; + + /* write the data to the target */ + rv = write(fd, sendbuf, nread); + if(!curlx_sztouz(rv, &nwritten) || (nwritten != nread)) { + result = CURLE_SEND_ERROR; + break; + } + Curl_pgrs_upload_inc(data, nwritten); + + result = Curl_pgrsCheck(data); + } + if(!result) + result = Curl_pgrsUpdate(data); + +out: + curlx_close(fd); + Curl_multi_xfer_ulbuf_release(data, xfer_ulbuf); + + return result; +} + +#if defined(_WIN32) && !defined(CURL_WINDOWS_UWP) +static CURLcode win32_file_list(struct Curl_easy *data, const char *path) +{ + WIN32_FIND_DATA entry; + HANDLE handle; + char *pattern; + size_t pathlen = strlen(path); + CURLcode result = CURLE_OK; + DWORD error; + + pattern = curl_maprintf("%s%s*", path, + pathlen && + (path[pathlen - 1] == '\\' || + path[pathlen - 1] == '/') ? "" : "\\"); + if(!pattern) + return CURLE_OUT_OF_MEMORY; + + handle = curlx_FindFirstFile(pattern, &entry); + curlx_free(pattern); + if(handle == INVALID_HANDLE_VALUE) + return CURLE_READ_ERROR; + + do { + if(entry.cFileName[0] != TEXT('.')) { + char *name = curlx_convert_tchar_to_UTF8(entry.cFileName); + + if(!name) { + result = CURLE_OUT_OF_MEMORY; + break; + } + + result = Curl_client_write(data, CLIENTWRITE_BODY, + name, strlen(name)); + curlx_free(name); + if(result) + break; + + result = Curl_client_write(data, CLIENTWRITE_BODY, "\n", 1); + if(result) + break; + } + } while(FindNextFile(handle, &entry)); + + error = GetLastError(); + if(!result && error != ERROR_NO_MORE_FILES) + result = CURLE_READ_ERROR; + + FindClose(handle); + return result; +} +#endif + +/* + * file_do() is the protocol-specific function for the do-phase, separated + * from the connect-phase above. Other protocols merely setup the transfer in + * the do-phase, to have it done in the main transfer loop but since some + * platforms we support do not allow select()ing etc on file handles (as + * opposed to sockets) we instead perform the whole do-operation in this + * function. + */ +static CURLcode file_do(struct Curl_easy *data, bool *done) +{ + /* This implementation ignores the hostname in conformance with + RFC 1738. Only local files (reachable via the standard file system) + are supported. This means that files on remotely mounted directories + (via NFS, Samba, NT sharing) can be accessed through a file:// URL */ + struct FILEPROTO *file = Curl_meta_get(data, CURL_META_FILE_EASY); + CURLcode result = CURLE_OK; + curlx_struct_stat statbuf; + curl_off_t expected_size = -1; + bool size_known; + bool fstated = FALSE; + int fd; + char *xfer_buf; + size_t xfer_blen; + + *done = TRUE; /* unconditionally */ + if(!file) + return CURLE_FAILED_INIT; + + if(data->state.upload) + return file_upload(data, file); + + /* get the fd from the connection phase */ + fd = file->fd; + + /* VMS: This only works reliable for STREAMLF files */ + if((file->is_dir ? file_stat(file->path, &statbuf) : + curlx_fstat(fd, &statbuf)) != -1) { + file->is_dir = (fd == -1) || S_ISDIR(statbuf.st_mode); + if(!file->is_dir) + expected_size = statbuf.st_size; + /* and store the modification time */ + data->info.filetime = statbuf.st_mtime; + fstated = TRUE; + } + + if(fstated && !data->state.range && data->set.timecondition && + !Curl_meets_timecondition(data, data->info.filetime)) + return CURLE_OK; + + if(fstated) { + time_t filetime; + struct tm buffer; + const struct tm *tm = &buffer; + char header[80]; + int headerlen; + static const char accept_ranges[] = { "Accept-ranges: bytes\r\n" }; + if(expected_size >= 0) { + headerlen = + curl_msnprintf(header, sizeof(header), + "Content-Length: %" FMT_OFF_T "\r\n", expected_size); + result = Curl_client_write(data, CLIENTWRITE_HEADER, header, headerlen); + if(result) + return result; + + result = Curl_client_write(data, CLIENTWRITE_HEADER, + accept_ranges, CURL_CSTRLEN(accept_ranges)); + if(result != CURLE_OK) + return result; + } + + filetime = (time_t)statbuf.st_mtime; + result = curlx_gmtime(filetime, &buffer); + if(result) + return result; + + /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */ + headerlen = + curl_msnprintf(header, sizeof(header), + "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n", + Curl_wkday[tm->tm_wday ? tm->tm_wday - 1 : 6], + tm->tm_mday, + Curl_month[tm->tm_mon], + tm->tm_year + 1900, + tm->tm_hour, + tm->tm_min, + tm->tm_sec); + result = Curl_client_write(data, CLIENTWRITE_HEADER, header, headerlen); + if(!result) + /* end of headers */ + result = Curl_client_write(data, CLIENTWRITE_HEADER, "\r\n", 2); + if(result) + return result; + /* set the file size to make it available post transfer */ + Curl_pgrsSetDownloadSize(data, expected_size); + if(data->req.no_body) + return CURLE_OK; + } + + /* Check whether file range has been specified */ + result = Curl_range(data); + if(result) + return result; + + /* Adjust the start offset in case we want to get the N last bytes + * of the stream if the filesize could be determined */ + if(data->state.resume_from < 0) { + if(!fstated) { + failf(data, "cannot get the size of file."); + return CURLE_READ_ERROR; + } + data->state.resume_from += (curl_off_t)statbuf.st_size; + } + + if(data->state.resume_from > 0) { + /* We check explicitly if we have a start offset, because + * expected_size may be -1 if we do not know how large the file is, + * in which case we should not adjust it. */ + if(data->state.resume_from <= expected_size) + expected_size -= data->state.resume_from; + else { + failf(data, "failed to resume file:// transfer"); + return CURLE_BAD_DOWNLOAD_RESUME; + } + } + + /* A high water mark has been specified so we obey... */ + if(data->req.maxdownload > 0) + expected_size = data->req.maxdownload; + + if(!fstated || (expected_size <= 0)) + size_known = FALSE; + else + size_known = TRUE; + + /* The following is a shortcut implementation of file reading + this is both more efficient than the former call to download() and + it avoids problems with select() and recv() on file descriptors + in Winsock */ + if(size_known) + Curl_pgrsSetDownloadSize(data, expected_size); + + if(data->state.resume_from) { + if(!file->is_dir) { + if(data->state.resume_from != + curl_lseek(fd, data->state.resume_from, SEEK_SET)) + return CURLE_BAD_DOWNLOAD_RESUME; + } + else { + return CURLE_BAD_DOWNLOAD_RESUME; + } + } + + result = Curl_multi_xfer_buf_borrow(data, &xfer_buf, &xfer_blen); + if(result) + goto out; + + if(!file->is_dir) { + while(!result) { + ssize_t nread; + /* Do not fill a whole buffer if we want less than all data */ + size_t bytestoread; + + if(size_known) { + bytestoread = (expected_size < (curl_off_t)(xfer_blen - 1)) ? + curlx_sotouz(expected_size) : (xfer_blen - 1); + } + else + bytestoread = xfer_blen - 1; + + nread = read(fd, xfer_buf, bytestoread); + + if(nread > 0) + xfer_buf[nread] = 0; + + if(nread <= 0 || (size_known && (expected_size == 0))) + break; + + if(size_known) + expected_size -= nread; + + result = Curl_client_write(data, CLIENTWRITE_BODY, xfer_buf, nread); + if(result) + goto out; + + result = Curl_pgrsCheck(data); + if(result) + goto out; + } + } + else { +#if defined(_WIN32) && !defined(CURL_WINDOWS_UWP) + result = win32_file_list(data, file->path); + if(result) + goto out; +#elif defined(HAVE_OPENDIR) + DIR *dir = opendir(file->path); + struct dirent *entry; + + if(!dir) { + result = CURLE_READ_ERROR; + goto out; + } + else { + while((entry = readdir(dir))) { + if(entry->d_name[0] != '.') { + result = Curl_client_write(data, CLIENTWRITE_BODY, + entry->d_name, strlen(entry->d_name)); + if(result) + break; + result = Curl_client_write(data, CLIENTWRITE_BODY, "\n", 1); + if(result) + break; + } + } + closedir(dir); + } +#else + failf(data, "Directory listing not yet implemented on this platform."); + result = CURLE_READ_ERROR; +#endif + } + + if(!result) + result = Curl_pgrsUpdate(data); + +out: + Curl_multi_xfer_buf_release(data, xfer_buf); + return result; +} + +const struct Curl_protocol Curl_protocol_file = { + file_setup_connection, /* setup_connection */ + file_do, /* do_it */ + file_done, /* done */ + ZERO_NULL, /* do_more */ + file_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_pollset */ + ZERO_NULL, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + file_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/file.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/file.h new file mode 100644 index 0000000000..0aa411b19f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/file.h @@ -0,0 +1,30 @@ +#ifndef HEADER_CURL_FILE_H +#define HEADER_CURL_FILE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_FILE +extern const struct Curl_protocol Curl_protocol_file; +#endif + +#endif /* HEADER_CURL_FILE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/fileinfo.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/fileinfo.c new file mode 100644 index 0000000000..33e5acde01 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/fileinfo.c @@ -0,0 +1,44 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_FTP + +#include "fileinfo.h" + +struct fileinfo *Curl_fileinfo_alloc(void) +{ + return curlx_calloc(1, sizeof(struct fileinfo)); +} + +void Curl_fileinfo_cleanup(struct fileinfo *finfo) +{ + if(!finfo) + return; + + curlx_dyn_free(&finfo->buf); + curlx_free(finfo); +} + +#endif /* !CURL_DISABLE_FTP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/fileinfo.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/fileinfo.h new file mode 100644 index 0000000000..737966788c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/fileinfo.h @@ -0,0 +1,40 @@ +#ifndef HEADER_CURL_FILEINFO_H +#define HEADER_CURL_FILEINFO_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "llist.h" +#include "curlx/dynbuf.h" + +struct fileinfo { + struct curl_fileinfo info; + struct Curl_llist_node list; + struct dynbuf buf; +}; + +struct fileinfo *Curl_fileinfo_alloc(void); +void Curl_fileinfo_cleanup(struct fileinfo *finfo); + +#endif /* HEADER_CURL_FILEINFO_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/formdata.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/formdata.c new file mode 100644 index 0000000000..0c81d8c781 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/formdata.c @@ -0,0 +1,866 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct Curl_easy; + +#include "formdata.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_FORM_API) + +#include "urldata.h" /* for struct Curl_easy */ +#include "mime.h" +#include "curlx/strdup.h" +#include "bufref.h" +#include "curlx/fopen.h" + + +#define HTTPPOST_PTRNAME CURL_HTTPPOST_PTRNAME +#define HTTPPOST_FILENAME CURL_HTTPPOST_FILENAME +#define HTTPPOST_PTRCONTENTS CURL_HTTPPOST_PTRCONTENTS +#define HTTPPOST_READFILE CURL_HTTPPOST_READFILE +#define HTTPPOST_PTRBUFFER CURL_HTTPPOST_PTRBUFFER +#define HTTPPOST_CALLBACK CURL_HTTPPOST_CALLBACK +#define HTTPPOST_BUFFER CURL_HTTPPOST_BUFFER + +/*************************************************************************** + * + * httppost_add() + * + * Adds an HttpPost structure to the list, if parent_post is given becomes + * a subpost of parent_post instead of a direct list element. + * + * Returns newly allocated HttpPost on success and NULL if malloc failed. + * + ***************************************************************************/ +static struct curl_httppost *httppost_add(struct FormInfo *src, + struct curl_httppost *parent_post, + struct curl_httppost **httppost, + struct curl_httppost **last_post) +{ + struct curl_httppost *post; + size_t namelength = src->namelength; + if(!namelength && Curl_bufref_ptr(&src->name)) + namelength = strlen(Curl_bufref_ptr(&src->name)); + if((src->bufferlength > LONG_MAX) || (namelength > LONG_MAX)) + /* avoid overflow in typecasts below */ + return NULL; + post = curlx_calloc(1, sizeof(struct curl_httppost)); + if(post) { + post->name = CURL_UNCONST(Curl_bufref_ptr(&src->name)); + post->namelength = (long)namelength; + post->contents = CURL_UNCONST(Curl_bufref_ptr(&src->value)); + post->contentlen = src->contentslength; + post->buffer = src->buffer; + post->bufferlength = (long)src->bufferlength; + post->contenttype = CURL_UNCONST(Curl_bufref_ptr(&src->contenttype)); + post->flags = src->flags | CURL_HTTPPOST_LARGE; + post->contentheader = src->contentheader; + post->showfilename = CURL_UNCONST(Curl_bufref_ptr(&src->showfilename)); + post->userp = src->userp; + } + else + return NULL; + + if(parent_post) { + /* now, point our 'more' to the original 'more' */ + post->more = parent_post->more; + + /* then move the original 'more' to point to ourselves */ + parent_post->more = post; + } + else { + /* make the previous point to this */ + if(*last_post) + (*last_post)->next = post; + else + (*httppost) = post; + + (*last_post) = post; + } + return post; +} + +/* Allocate and initialize a new FormInfo structure. */ +static struct FormInfo *forminfo_new(void) +{ + struct FormInfo *form_info = curlx_calloc(1, sizeof(struct FormInfo)); + + if(form_info) { + Curl_bufref_init(&form_info->name); + Curl_bufref_init(&form_info->value); + Curl_bufref_init(&form_info->contenttype); + Curl_bufref_init(&form_info->showfilename); + } + + return form_info; +} + +/* Replace the target field data by a dynamic copy of it. */ +static CURLcode forminfo_copyfield(struct bufref *field, size_t len) +{ + const char *value = Curl_bufref_ptr(field); + CURLcode result = CURLE_OK; + + if(value) { + if(!len) + len = strlen(value); + result = Curl_bufref_memdup0(field, value, len); + } + + return result; +} + +/*************************************************************************** + * + * forminfo_add() + * + * Adds a FormInfo structure to the list presented by parent. + * + ***************************************************************************/ +static void forminfo_add(struct FormInfo *form_info, struct FormInfo *parent) +{ + form_info->flags |= HTTPPOST_FILENAME; + + if(parent) { + /* now, point our 'more' to the original 'more' */ + form_info->more = parent->more; + + /* then move the original 'more' to point to ourselves */ + parent->more = form_info; + } +} + +static void free_formlist(struct FormInfo *ptr) +{ + for(; ptr; ptr = ptr->more) { + Curl_bufref_free(&ptr->name); + Curl_bufref_free(&ptr->value); + Curl_bufref_free(&ptr->contenttype); + Curl_bufref_free(&ptr->showfilename); + } +} + +/*************************************************************************** + * + * formadd_check() + * + * Stores a formpost parameter and builds the appropriate linked list. + * + * Has two principal functionalities: using files and byte arrays as post + * parts. Byte arrays are either copied or the pointer is stored (as the user + * requests) while for files only the filename and not the content is stored. + * + * While you may have only one byte array for each name, multiple filenames + * are allowed (and because of this feature CURLFORM_END is needed after + * using CURLFORM_FILE). + * + * Examples: + * + * Simple name/value pair with copied contents: + * curl_formadd(&post, &last, CURLFORM_COPYNAME, "name", + * CURLFORM_COPYCONTENTS, "value", CURLFORM_END); + * + * name/value pair where only the content pointer is remembered: + * curl_formadd(&post, &last, CURLFORM_COPYNAME, "name", + * CURLFORM_PTRCONTENTS, ptr, CURLFORM_CONTENTSLENGTH, 10L, + * CURLFORM_END); + * (if CURLFORM_CONTENTSLENGTH is missing strlen() is used) + * + * storing a filename (CONTENTTYPE is optional!): + * curl_formadd(&post, &last, CURLFORM_COPYNAME, "name", + * CURLFORM_FILE, "filename1", CURLFORM_CONTENTTYPE, "plain/text", + * CURLFORM_END); + * + * storing multiple filenames: + * curl_formadd(&post, &last, CURLFORM_COPYNAME, "name", + * CURLFORM_FILE, "filename1", CURLFORM_FILE, "filename2", + * CURLFORM_END); + * + * Returns: + * CURL_FORMADD_OK on success + * CURL_FORMADD_MEMORY if the FormInfo allocation fails + * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form + * CURL_FORMADD_NULL if a null pointer was given for a char + * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed + * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used + * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error) + * CURL_FORMADD_MEMORY if an HttpPost struct cannot be allocated + * CURL_FORMADD_MEMORY if some allocation for string copying failed. + * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array + * + ***************************************************************************/ + +static CURLFORMcode formadd_check(struct FormInfo *first_form, + struct curl_httppost **httppost, + struct curl_httppost **last_post) +{ + const char *prevtype = NULL; + struct FormInfo *form = NULL; + struct curl_httppost *post = NULL; + + /* go through the list, check for completeness and if everything is + * alright add the HttpPost item otherwise set retval accordingly */ + + for(form = first_form; form; form = form->more) { + const char *name = Curl_bufref_ptr(&form->name); + + if(((!name || !Curl_bufref_ptr(&form->value)) && !post) || + (form->contentslength && + (form->flags & HTTPPOST_FILENAME)) || + ((form->flags & HTTPPOST_FILENAME) && + (form->flags & HTTPPOST_PTRCONTENTS)) || + + (!form->buffer && + (form->flags & HTTPPOST_BUFFER) && + (form->flags & HTTPPOST_PTRBUFFER)) || + + ((form->flags & HTTPPOST_READFILE) && + (form->flags & HTTPPOST_PTRCONTENTS)) + ) { + return CURL_FORMADD_INCOMPLETE; + } + if(((form->flags & HTTPPOST_FILENAME) || + (form->flags & HTTPPOST_BUFFER)) && + !Curl_bufref_ptr(&form->contenttype)) { + const char *f = Curl_bufref_ptr((form->flags & HTTPPOST_BUFFER) ? + &form->showfilename : &form->value); + const char *type = Curl_mime_contenttype(f); + if(!type) + type = prevtype; + if(!type) + type = FILE_CONTENTTYPE_DEFAULT; + + /* our contenttype is missing */ + if(Curl_bufref_memdup0(&form->contenttype, type, strlen(type))) + return CURL_FORMADD_MEMORY; + } + if(name && form->namelength) { + if(memchr(name, 0, form->namelength)) + return CURL_FORMADD_NULL; + } + if(!(form->flags & HTTPPOST_PTRNAME)) { + /* Note that there is small risk that form->name is NULL here if the app + passed in a bad combo, so we check for that. */ + if(forminfo_copyfield(&form->name, form->namelength)) + return CURL_FORMADD_MEMORY; + } + if(!(form->flags & (HTTPPOST_FILENAME | HTTPPOST_READFILE | + HTTPPOST_PTRCONTENTS | HTTPPOST_PTRBUFFER | + HTTPPOST_CALLBACK))) { + if(forminfo_copyfield(&form->value, (size_t)form->contentslength)) + return CURL_FORMADD_MEMORY; + } + post = httppost_add(form, post, httppost, last_post); + + if(!post) + return CURL_FORMADD_MEMORY; + + if(Curl_bufref_ptr(&form->contenttype)) + prevtype = Curl_bufref_ptr(&form->contenttype); + } + + return CURL_FORMADD_OK; +} + +/* Shallow cleanup. Remove the newly created chain, the structs only and not + the content they point to */ +static void free_chain(struct curl_httppost *c) +{ + while(c) { + struct curl_httppost *next = c->next; + if(c->more) + free_chain(c->more); + curlx_free(c); + c = next; + } +} + +static CURLFORMcode formadd(struct curl_httppost **httppost, + struct curl_httppost **last_post, va_list params) +{ + struct FormInfo *first_form, *curr, *form = NULL; + CURLFORMcode retval = CURL_FORMADD_OK; + CURLformoption option; + const struct curl_forms *forms = NULL; + char *avalue = NULL; + struct curl_httppost *newchain = NULL; + struct curl_httppost *lastnode = NULL; + +#define form_ptr_arg(t) (forms ? (t)(void *)avalue : va_arg(params, t)) +#ifdef HAVE_UINTPTR_T +#define form_int_arg(t) (forms ? (t)(uintptr_t)avalue : va_arg(params, t)) +#else +#define form_int_arg(t) (forms ? (t)(void *)avalue : va_arg(params, t)) +#endif + + /* + * We need to allocate the first struct to fill in. + */ + first_form = forminfo_new(); + if(!first_form) + return CURL_FORMADD_MEMORY; + + curr = first_form; + + /* + * Loop through all the options set. Break if we have an error to report. + */ + while(retval == CURL_FORMADD_OK) { + + /* first see if we have more parts of the array param */ + if(forms) { + /* get the upcoming option from the given array */ + option = forms->option; + avalue = (char *)CURL_UNCONST(forms->value); + + forms++; /* advance this to next entry */ + if(CURLFORM_END == option) { + /* end of array state */ + forms = NULL; + continue; + } + } + else { + /* This is not array-state, get next option. This gets an 'int' with + va_arg() because CURLformoption might be a smaller type than int and + might cause compiler warnings and wrong behavior. */ + option = (CURLformoption)va_arg(params, int); + if(CURLFORM_END == option) + break; + } + + switch(option) { + case CURLFORM_ARRAY: + if(forms) + /* we do not support an array from within an array */ + retval = CURL_FORMADD_ILLEGAL_ARRAY; + else { + forms = va_arg(params, struct curl_forms *); + if(!forms) + retval = CURL_FORMADD_NULL; + } + break; + + /* + * Set the Name property. + */ + case CURLFORM_PTRNAME: + curr->flags |= HTTPPOST_PTRNAME; + FALLTHROUGH(); + case CURLFORM_COPYNAME: + if(Curl_bufref_ptr(&curr->name)) + retval = CURL_FORMADD_OPTION_TWICE; + else { + avalue = form_ptr_arg(char *); + if(avalue) + Curl_bufref_set(&curr->name, avalue, 0, NULL); /* No copy yet. */ + else + retval = CURL_FORMADD_NULL; + } + break; + case CURLFORM_NAMELENGTH: + if(curr->namelength) + retval = CURL_FORMADD_OPTION_TWICE; + else + curr->namelength = (size_t)form_int_arg(long); + break; + + /* + * Set the contents property. + */ + case CURLFORM_PTRCONTENTS: + curr->flags |= HTTPPOST_PTRCONTENTS; + FALLTHROUGH(); + case CURLFORM_COPYCONTENTS: + if(Curl_bufref_ptr(&curr->value)) + retval = CURL_FORMADD_OPTION_TWICE; + else { + avalue = form_ptr_arg(char *); + if(avalue) + Curl_bufref_set(&curr->value, avalue, 0, NULL); /* No copy yet. */ + else + retval = CURL_FORMADD_NULL; + } + break; + case CURLFORM_CONTENTSLENGTH: + curr->contentslength = (curl_off_t)(size_t)form_int_arg(long); + break; + + case CURLFORM_CONTENTLEN: + curr->flags |= CURL_HTTPPOST_LARGE; + curr->contentslength = form_int_arg(curl_off_t); + break; + + /* Get contents from a given filename */ + case CURLFORM_FILECONTENT: + if(curr->flags & (HTTPPOST_PTRCONTENTS | HTTPPOST_READFILE)) + retval = CURL_FORMADD_OPTION_TWICE; + else { + avalue = form_ptr_arg(char *); + if(avalue) { + if(Curl_bufref_memdup0(&curr->value, avalue, strlen(avalue))) + retval = CURL_FORMADD_MEMORY; + else + curr->flags |= HTTPPOST_READFILE; + } + else + retval = CURL_FORMADD_NULL; + } + break; + + /* We upload a file */ + case CURLFORM_FILE: + avalue = form_ptr_arg(char *); + if(Curl_bufref_ptr(&curr->value)) { + if(curr->flags & HTTPPOST_FILENAME) { + if(avalue) { + form = forminfo_new(); + if(!form || + Curl_bufref_memdup0(&form->value, avalue, strlen(avalue))) { + curlx_free(form); + retval = CURL_FORMADD_MEMORY; + } + else { + forminfo_add(form, curr); + curr = form; + form = NULL; + } + } + else + retval = CURL_FORMADD_NULL; + } + else + retval = CURL_FORMADD_OPTION_TWICE; + } + else { + if(avalue) { + if(Curl_bufref_memdup0(&curr->value, avalue, strlen(avalue))) + retval = CURL_FORMADD_MEMORY; + else + curr->flags |= HTTPPOST_FILENAME; + } + else + retval = CURL_FORMADD_NULL; + } + break; + + case CURLFORM_BUFFERPTR: + curr->flags |= HTTPPOST_PTRBUFFER | HTTPPOST_BUFFER; + if(curr->buffer) + retval = CURL_FORMADD_OPTION_TWICE; + else { + avalue = form_ptr_arg(char *); + if(avalue) { + curr->buffer = avalue; /* store for the moment */ + /* Make value non-NULL to be accepted as fine */ + Curl_bufref_set(&curr->value, avalue, 0, NULL); + } + else + retval = CURL_FORMADD_NULL; + } + break; + + case CURLFORM_BUFFERLENGTH: + if(curr->bufferlength) + retval = CURL_FORMADD_OPTION_TWICE; + else + curr->bufferlength = (size_t)form_int_arg(long); + break; + + case CURLFORM_STREAM: + curr->flags |= HTTPPOST_CALLBACK; + if(curr->userp) + retval = CURL_FORMADD_OPTION_TWICE; + else { + avalue = form_ptr_arg(char *); + if(avalue) { + curr->userp = avalue; + /* The following line is not strictly true but we derive a value + from this later on and we need this non-NULL to be accepted as + a fine form part */ + Curl_bufref_set(&curr->value, avalue, 0, NULL); + } + else + retval = CURL_FORMADD_NULL; + } + break; + + case CURLFORM_CONTENTTYPE: + avalue = form_ptr_arg(char *); + if(Curl_bufref_ptr(&curr->contenttype)) { + if(curr->flags & HTTPPOST_FILENAME) { + if(avalue) { + form = forminfo_new(); + if(!form || Curl_bufref_memdup0(&form->contenttype, avalue, + strlen(avalue))) { + curlx_free(form); + retval = CURL_FORMADD_MEMORY; + } + else { + forminfo_add(form, curr); + curr = form; + form = NULL; + } + } + else + retval = CURL_FORMADD_NULL; + } + else + retval = CURL_FORMADD_OPTION_TWICE; + } + else if(avalue) { + if(Curl_bufref_memdup0(&curr->contenttype, avalue, strlen(avalue))) + retval = CURL_FORMADD_MEMORY; + } + else + retval = CURL_FORMADD_NULL; + break; + + case CURLFORM_CONTENTHEADER: { + /* this "cast increases required alignment of target type" but + we consider it OK anyway */ + struct curl_slist *list = form_ptr_arg(struct curl_slist *); + + if(curr->contentheader) + retval = CURL_FORMADD_OPTION_TWICE; + else + curr->contentheader = list; + + break; + } + case CURLFORM_FILENAME: + case CURLFORM_BUFFER: + avalue = form_ptr_arg(char *); + if(Curl_bufref_ptr(&curr->showfilename)) + retval = CURL_FORMADD_OPTION_TWICE; + else if(Curl_bufref_memdup0(&curr->showfilename, avalue, strlen(avalue))) + retval = CURL_FORMADD_MEMORY; + break; + + default: + retval = CURL_FORMADD_UNKNOWN_OPTION; + break; + } + } + + if(!retval) + retval = formadd_check(first_form, &newchain, &lastnode); + + if(retval) + /* On error, free allocated fields for all nodes of the FormInfo linked + list without deallocating nodes. List nodes are deallocated later on */ + free_formlist(first_form); + + /* Always deallocate FormInfo linked list nodes without touching node + fields given that these have either been deallocated or are owned + now by the httppost linked list */ + while(first_form) { + struct FormInfo *ptr = first_form->more; + curlx_free(first_form); + first_form = ptr; + } + + if(!retval) { + /* Only if all is fine, link the new chain into the provided list */ + if(*last_post) + (*last_post)->next = newchain; + else + (*httppost) = newchain; + + (*last_post) = lastnode; + } + else + free_chain(newchain); + + return retval; +#undef form_ptr_arg +#undef form_int_arg +} + +/* + * curl_formadd() is a public API to add a section to the multipart formpost. + * + * @unittest: 1308 + */ + +CURLFORMcode curl_formadd(struct curl_httppost **httppost, + struct curl_httppost **last_post, ...) +{ + va_list arg; + CURLFORMcode form; + va_start(arg, last_post); + form = formadd(httppost, last_post, arg); + va_end(arg); + return form; +} + +/* + * curl_formget() + * Serialize a curl_httppost struct. + * Returns 0 on success. + * + * @unittest: 1308 + */ +int curl_formget(struct curl_httppost *form, void *arg, + curl_formget_callback append) +{ + CURLcode result; + curl_mimepart toppart; + + /* Validate callback is provided */ + if(!append) + return (int)CURLE_BAD_FUNCTION_ARGUMENT; + + Curl_mime_initpart(&toppart); /* default form is empty */ + result = Curl_getformdata(NULL, &toppart, form, NULL); + if(!result) + result = Curl_mime_prepare_headers(NULL, &toppart, "multipart/form-data", + NULL, MIMESTRATEGY_FORM); + + while(!result) { + char buffer[8192]; + size_t nread = Curl_mime_read(buffer, 1, sizeof(buffer), &toppart); + + if(!nread) + break; + + if(nread > sizeof(buffer) || append(arg, buffer, nread) != nread) { + result = CURLE_READ_ERROR; + if(nread == CURL_READFUNC_ABORT) + result = CURLE_ABORTED_BY_CALLBACK; + } + } + + Curl_mime_cleanpart(&toppart); + return (int)result; +} + +/* + * curl_formfree() is an external function to free up a whole form post + * chain + */ +void curl_formfree(struct curl_httppost *form) +{ + struct curl_httppost *next; + + if(!form) + /* no form to free, get out of this */ + return; + + do { + next = form->next; /* the following form line */ + + /* recurse to sub-contents */ + curl_formfree(form->more); + + if(!(form->flags & HTTPPOST_PTRNAME)) + curlx_free(form->name); /* free the name */ + if(!(form->flags & + (HTTPPOST_PTRCONTENTS | HTTPPOST_BUFFER | HTTPPOST_CALLBACK))) + curlx_free(form->contents); /* free the contents */ + curlx_free(form->contenttype); /* free the content type */ + curlx_free(form->showfilename); /* free the faked filename */ + curlx_free(form); /* free the struct */ + form = next; + } while(form); /* continue */ +} + +/* Set mime part name, taking care of non null-terminated name string. */ +static CURLcode setname(curl_mimepart *part, const char *name, size_t len) +{ + char *zname; + CURLcode result; + + if(!name || !len) + return curl_mime_name(part, name); + zname = curlx_memdup0(name, len); + if(!zname) + return CURLE_OUT_OF_MEMORY; + result = curl_mime_name(part, zname); + curlx_free(zname); + return result; +} + +/* + * Curl_getformdata() converts a linked list of "meta data" into a mime + * structure. The input list is in 'post', while the output is stored in + * mime part at '*finalform'. + * + * This function will not do a failf() for the potential memory failures but + * should for all other errors it spots. Note that this function MAY get a + * NULL pointer in the 'data' argument. + */ + +CURLcode Curl_getformdata(CURL *data, + curl_mimepart *finalform, + struct curl_httppost *post, + curl_read_callback fread_func) +{ + CURLcode result = CURLE_OK; + curl_mime *form = NULL; + curl_mimepart *part; + struct curl_httppost *file; + + Curl_mime_cleanpart(finalform); /* default form is empty */ + + if(!post) + return result; /* no input => no output! */ + + form = curl_mime_init(data); + if(!form) + result = CURLE_OUT_OF_MEMORY; + + if(!result) + result = curl_mime_subparts(finalform, form); + + /* Process each top part. */ + for(; !result && post; post = post->next) { + /* If we have more than a file here, create a mime subpart and fill it. */ + curl_mime *multipart = form; + if(post->more) { + part = curl_mime_addpart(form); + if(!part) + result = CURLE_OUT_OF_MEMORY; + if(!result) + result = setname(part, post->name, post->namelength); + if(!result) { + multipart = curl_mime_init(data); + if(!multipart) + result = CURLE_OUT_OF_MEMORY; + } + if(!result) + result = curl_mime_subparts(part, multipart); + } + + /* Generate all the part contents. */ + for(file = post; !result && file; file = file->more) { + /* Create the part. */ + part = curl_mime_addpart(multipart); + if(!part) + result = CURLE_OUT_OF_MEMORY; + + /* Set the headers. */ + if(!result) + result = curl_mime_headers(part, file->contentheader, 0); + + /* Set the content type. */ + if(!result && file->contenttype) + result = curl_mime_type(part, file->contenttype); + + /* Set field name. */ + if(!result && !post->more) + result = setname(part, post->name, post->namelength); + + /* Process contents. */ + if(!result) { + curl_off_t clen = post->contentslength; + + if(post->flags & CURL_HTTPPOST_LARGE) + clen = post->contentlen; + + if(post->flags & (HTTPPOST_FILENAME | HTTPPOST_READFILE)) { + if(!strcmp(file->contents, "-")) { + /* There are a few cases where the code below will not work; in + particular, freopen(stdin) by the caller is not guaranteed + to result as expected. This feature has been kept for backward + compatibility: use of "-" pseudo filename should be avoided. */ +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcast-function-type-strict" +#endif + result = curl_mime_data_cb(part, (curl_off_t)-1, + (curl_read_callback)fread, + curlx_fseek, + NULL, (void *)stdin); +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic pop +#endif + } + else + result = curl_mime_filedata(part, file->contents); + if(!result && (post->flags & HTTPPOST_READFILE)) + result = curl_mime_filename(part, NULL); + } + else if(post->flags & HTTPPOST_BUFFER) + result = curl_mime_data(part, post->buffer, + post->bufferlength ? + post->bufferlength : -1); + else if(post->flags & HTTPPOST_CALLBACK) { + /* the contents should be read with the callback and the size is set + with the contentslength */ + if(!clen) + clen = -1; + result = curl_mime_data_cb(part, clen, + fread_func, NULL, NULL, post->userp); + } + else { + size_t uclen; + if(!clen) + uclen = CURL_ZERO_TERMINATED; + else + uclen = (size_t)clen; + result = curl_mime_data(part, post->contents, uclen); + } + } + + /* Set fake filename. */ + if(!result && post->showfilename) + if(post->more || (post->flags & (HTTPPOST_FILENAME | HTTPPOST_BUFFER | + HTTPPOST_CALLBACK))) + result = curl_mime_filename(part, post->showfilename); + } + } + + if(result) + Curl_mime_cleanpart(finalform); + + return result; +} + +#else /* if disabled */ +CURLFORMcode curl_formadd(struct curl_httppost **httppost, + struct curl_httppost **last_post, ...) +{ + (void)httppost; + (void)last_post; + return CURL_FORMADD_DISABLED; +} + +int curl_formget(struct curl_httppost *form, void *arg, + curl_formget_callback append) +{ + (void)form; + (void)arg; + (void)append; + return CURL_FORMADD_DISABLED; +} + +void curl_formfree(struct curl_httppost *form) +{ + (void)form; + /* Nothing to do. */ +} + +#endif /* if disabled */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/formdata.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/formdata.h new file mode 100644 index 0000000000..33d7d0ae33 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/formdata.h @@ -0,0 +1,55 @@ +#ifndef HEADER_CURL_FORMDATA_H +#define HEADER_CURL_FORMDATA_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_FORM_API + +#include "bufref.h" + +/* used by FormAdd for temporary storage */ +struct FormInfo { + struct bufref name; + struct bufref value; + struct bufref contenttype; + struct bufref showfilename; /* The filename to show. If not set, the actual + filename will be used */ + char *buffer; /* pointer to existing buffer used for file upload */ + char *userp; /* pointer for the read callback */ + struct FormInfo *more; + struct curl_slist *contentheader; + curl_off_t contentslength; + size_t namelength; + size_t bufferlength; + unsigned char flags; +}; + +CURLcode Curl_getformdata(CURL *data, + curl_mimepart *finalform, + struct curl_httppost *post, + curl_read_callback fread_func); +#endif /* CURL_DISABLE_FORM_API */ + +#endif /* HEADER_CURL_FORMDATA_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftp-int.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftp-int.h new file mode 100644 index 0000000000..8d7e141274 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftp-int.h @@ -0,0 +1,160 @@ +#ifndef HEADER_CURL_FTP_INT_H +#define HEADER_CURL_FTP_INT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "pingpong.h" + +#ifndef CURL_DISABLE_FTP + +/**************************************************************************** + * FTP unique setup + ***************************************************************************/ +enum { + FTP_STOP, /* do nothing state, stops the state machine */ + FTP_WAIT220, /* waiting for the initial 220 response immediately after + a connect */ + FTP_AUTH, + FTP_USER, + FTP_PASS, + FTP_ACCT, + FTP_PBSZ, + FTP_PROT, + FTP_CCC, + FTP_PWD, + FTP_SYST, + FTP_NAMEFMT, + FTP_QUOTE, /* waiting for a response to a command sent in a quote list */ + FTP_RETR_PREQUOTE, + FTP_STOR_PREQUOTE, + FTP_LIST_PREQUOTE, + FTP_POSTQUOTE, + FTP_CWD, /* change directory */ + FTP_MKD, /* if the directory did not exist */ + FTP_MDTM, /* to figure out the datestamp */ + FTP_TYPE, /* to set type when doing a head-like request */ + FTP_LIST_TYPE, /* set type when about to do a directory list */ + FTP_RETR_LIST_TYPE, + FTP_RETR_TYPE, /* set type when about to RETR a file */ + FTP_STOR_TYPE, /* set type when about to STOR a file */ + FTP_SIZE, /* get the remote file's size for head-like request */ + FTP_RETR_SIZE, /* get the remote file's size for RETR */ + FTP_STOR_SIZE, /* get the size for STOR */ + FTP_REST, /* when used to check if the server supports it in head-like */ + FTP_RETR_REST, /* when asking for "resume" in for RETR */ + FTP_PORT, /* generic state for PORT, LPRT and EPRT, check count1 */ + FTP_PRET, /* generic state for PRET RETR, PRET STOR and PRET LIST/NLST */ + FTP_PASV, /* generic state for PASV and EPSV, check count1 */ + FTP_LIST, /* generic state for LIST, NLST or a custom list command */ + FTP_RETR, + FTP_STOR, /* generic state for STOR and APPE */ + FTP_QUIT, + FTP_LAST /* never used */ +}; +typedef unsigned char ftpstate; /* use the enum values */ + +struct ftp_parselist_data; /* defined later in ftplistparser.c */ + +struct ftp_wc { + struct ftp_parselist_data *parser; + + struct { + curl_write_callback write_function; + FILE *file_descriptor; + } backup; +}; + +/* This FTP struct is used in the Curl_easy. All FTP data that is + connection-oriented must be in FTP_conn to properly deal with the fact that + perhaps the Curl_easy is changed between the times the connection is + used. */ +struct FTP { + char *path; /* points to the urlpieces struct field */ + char *pathalloc; /* if non-NULL a pointer to an allocated path */ + + /* transfer a file/body or not, done as a typedefed enum to make debuggers + display the full symbol and not the numerical value */ + curl_pp_transfer transfer; + curl_off_t downloadsize; +}; + +/* one struct entry for each path component (of 'rawpath') */ +struct pathcomp { + int start; /* start column */ + int len; /* length in bytes */ +}; + +/* ftp_conn is used for struct connection-oriented data in the connectdata + struct */ +struct ftp_conn { + struct pingpong pp; + char *account; + char *alternative_to_user; + char *entrypath; /* the PWD reply when we logged on */ + const char *file; /* URL-decoded filename (or path), points into rawpath */ + char *rawpath; /* URL decoded, allocated, version of the path */ + struct pathcomp *dirs; /* allocated array for path components */ + char *prevpath; /* URL-decoded conn->path from the previous transfer */ + char transfertype; /* set by ftp_transfertype for use by Curl_client_write()a + and others (A/I or zero) */ + char *server_os; /* The target server operating system. */ + curl_off_t known_filesize; /* file size is different from -1, if wildcard + LIST parsing was done and wc_statemach set + it */ + int count1; /* general purpose counter for the state machine */ + int count2; /* general purpose counter for the state machine */ + int count3; /* general purpose counter for the state machine */ + unsigned short dirdepth; /* number of entries used in the 'dirs' array, + < FTP_MAX_DIR_DEPTH */ + unsigned short cwdcount; /* number of CWD commands issued, + < FTP_MAX_DIR_DEPTH */ + unsigned char state; /* (ftpstate enum) always use ftp.c:state() to change + state! */ + unsigned char use_ssl; /* if AUTH TLS is to be attempted etc, for FTP or + IMAP or POP3 or others! (type: curl_usessl)*/ + unsigned char ccc; /* ccc level for this connection */ + BIT(ftp_trying_alternative); + BIT(dont_check); /* Set to TRUE to prevent the final (post-transfer) + file size and 226/250 status check. It should still + read the line, ignore the result. */ + BIT(ctl_valid); /* Tells Curl_ftp_quit() whether or not to do anything. If + the connection has timed out or been closed, this + should be FALSE when it gets to Curl_ftp_quit() */ + BIT(cwddone); /* if it has been determined that the proper CWD combo + already has been done */ + BIT(cwdfail); /* set TRUE if a CWD command fails, as then we must prevent + caching the current directory */ + BIT(wait_data_conn); /* this is set TRUE if data connection is waited */ + BIT(shutdown); /* connection is being shutdown, e.g. QUIT */ +}; + +/* meta key for storing `struct FTP` as easy meta data */ +#define CURL_META_FTP_EASY "meta:proto:ftp:easy" +/* meta key for storing `struct ftp_conn` as connection meta data */ +#define CURL_META_FTP_CONN "meta:proto:ftp:conn" + +#endif /* CURL_DISABLE_FTP */ + +#endif /* HEADER_CURL_FTP_INT_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftp.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftp.c new file mode 100644 index 0000000000..70bf654bf9 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftp.c @@ -0,0 +1,4518 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" + +#ifndef CURL_DISABLE_FTP + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include "sendf.h" +#include "curl_addrinfo.h" +#include "curl_trc.h" +#include "if2ip.h" +#include "progress.h" +#include "transfer.h" +#include "escape.h" +#include "ftp.h" +#include "ftp-int.h" +#include "ftplistparser.h" +#include "curl_range.h" +#include "strcase.h" +#include "vtls/vtls.h" +#include "cfilters.h" +#include "cf-socket.h" +#include "connect.h" +#include "curlx/inet_ntop.h" +#include "curlx/inet_pton.h" +#include "select.h" +#include "parsedate.h" /* for the week day and month names */ +#include "sockaddr.h" /* required for Curl_sockaddr_storage */ +#include "multiif.h" +#include "url.h" +#include "http_proxy.h" +#include "vdns/hostip.h" +#include "curlx/strdup.h" +#include "curlx/strerr.h" +#include "curlx/strparse.h" +#include "curl_ctype.h" + +#ifndef NI_MAXHOST +#define NI_MAXHOST 1025 +#endif +#ifndef INET_ADDRSTRLEN +#define INET_ADDRSTRLEN 16 +#endif + +/* macro to check for a three-digit ftp status code at the start of the + given string */ +#define STATUSCODE(line) \ + (ISDIGIT((line)[0]) && ISDIGIT((line)[1]) && ISDIGIT((line)[2])) + +/* macro to check for the last line in an FTP server response */ +#define LASTLINE(line) (STATUSCODE(line) && (' ' == (line)[3])) + +#ifdef CURLVERBOSE +/* for tracing purposes */ +static const char * const ftp_state_names[] = { + "STOP", + "WAIT220", + "AUTH", + "USER", + "PASS", + "ACCT", + "PBSZ", + "PROT", + "CCC", + "PWD", + "SYST", + "NAMEFMT", + "QUOTE", + "RETR_PREQUOTE", + "STOR_PREQUOTE", + "LIST_PREQUOTE", + "POSTQUOTE", + "CWD", + "MKD", + "MDTM", + "TYPE", + "LIST_TYPE", + "RETR_LIST_TYPE", + "RETR_TYPE", + "STOR_TYPE", + "SIZE", + "RETR_SIZE", + "STOR_SIZE", + "REST", + "RETR_REST", + "PORT", + "PRET", + "PASV", + "LIST", + "RETR", + "STOR", + "QUIT" +}; +#define FTP_CSTATE(ftpc) ((ftpc) ? ftp_state_names[(ftpc)->state] : "???") + +#endif /* CURLVERBOSE */ + +/* This is the ONLY way to change FTP state! */ +static void ftp_state_low(struct Curl_easy *data, + struct ftp_conn *ftpc, + ftpstate newstate +#ifdef DEBUGBUILD + , int lineno +#endif + ) +{ + if(ftpc->state != newstate) { +#ifdef DEBUGBUILD + NOVERBOSE((void)lineno); + CURL_TRC_FTP(data, "[%s] -> [%s] (line %d)", FTP_CSTATE(ftpc), + ftp_state_names[newstate], lineno); +#else + CURL_TRC_FTP(data, "[%s] -> [%s]", FTP_CSTATE(ftpc), + ftp_state_names[newstate]); +#endif + } + ftpc->state = newstate; +} + +/* Local API functions */ +#ifndef DEBUGBUILD +#define ftp_state(x, y, z) ftp_state_low(x, y, z) +#else /* !DEBUGBUILD */ +#define ftp_state(x, y, z) ftp_state_low(x, y, z, __LINE__) +#endif /* DEBUGBUILD */ + +static CURLcode ftp_state_mdtm(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp); +static CURLcode ftp_state_quote(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + bool init, ftpstate instate); +static CURLcode ftp_nb_type(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + bool ascii, ftpstate newstate); +static CURLcode getftpresponse(struct Curl_easy *data, size_t *nreadp, + int *ftpcodep); + +static void freedirs(struct ftp_conn *ftpc) +{ + curlx_safefree(ftpc->dirs); + ftpc->dirdepth = 0; + curlx_safefree(ftpc->rawpath); + ftpc->file = NULL; +} + +static size_t numof_slashes(const char *str) +{ + const char *slashPos; + size_t num = 0; + do { + slashPos = strchr(str, '/'); + if(slashPos) { + ++num; + str = slashPos + 1; + } + } while(slashPos); + return num; +} + +#define FTP_MAX_DIR_DEPTH 1000 + +/*********************************************************************** + * + * ftp_parse_url_path() + * + * Parse the URL path into separate path components. + * + */ +static CURLcode ftp_parse_url_path(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp) +{ + const char *slashPos = NULL; + const char *fileName = NULL; + CURLcode result = CURLE_OK; + const char *rawPath = NULL; /* URL-decoded "raw" path */ + size_t pathLen = 0; + + ftpc->ctl_valid = FALSE; + ftpc->cwdfail = FALSE; + + if(ftpc->rawpath) + freedirs(ftpc); + /* URL-decode ftp path before further evaluation */ + result = Curl_urldecode(ftp->path, 0, &ftpc->rawpath, &pathLen, REJECT_CTRL); + if(result) { + failf(data, "path contains control characters"); + return result; + } + rawPath = ftpc->rawpath; + + switch(data->set.ftp_filemethod) { + case FTPFILE_NOCWD: /* fastest, but less standard-compliant */ + + if((pathLen > 0) && (rawPath[pathLen - 1] != '/')) + fileName = rawPath; /* this is a full file path */ + /* else: ftpc->file is not used anywhere other than for operations on + a file. In other words, never for directory operations, + so we can safely leave filename as NULL here and use it as a + argument in dir/file decisions. */ + break; + + case FTPFILE_SINGLECWD: + slashPos = strrchr(rawPath, '/'); + if(slashPos) { + /* get path before last slash, except for / */ + size_t dirlen = slashPos - rawPath; + if(dirlen == 0) + dirlen = 1; + + ftpc->dirs = curlx_calloc(1, sizeof(ftpc->dirs[0])); + if(!ftpc->dirs) + return CURLE_OUT_OF_MEMORY; + + ftpc->dirs[0].start = 0; + ftpc->dirs[0].len = (int)dirlen; + ftpc->dirdepth = 1; /* we consider it to be a single directory */ + fileName = slashPos + 1; /* rest is filename */ + } + else + fileName = rawPath; /* filename only (or empty) */ + break; + + default: /* allow pretty much anything */ + case FTPFILE_MULTICWD: { + /* current position: begin of next path component */ + const char *curPos = rawPath; + + /* number of entries to allocate for the 'dirs' array */ + size_t dirAlloc = numof_slashes(rawPath); + + if(dirAlloc >= FTP_MAX_DIR_DEPTH) + /* suspiciously deep directory hierarchy */ + return CURLE_URL_MALFORMAT; + + if(dirAlloc) { + ftpc->dirs = curlx_calloc(dirAlloc, sizeof(ftpc->dirs[0])); + if(!ftpc->dirs) + return CURLE_OUT_OF_MEMORY; + + /* parse the URL path into separate path components */ + while(dirAlloc--) { + const char *spos = strchr(curPos, '/'); + size_t clen = spos - curPos; + + /* path starts with a slash: add that as a directory */ + if(!clen && (ftpc->dirdepth == 0)) + ++clen; + + /* we skip empty path components, like "x//y" since the FTP command + CWD requires a parameter and a non-existent parameter a) does not + work on many servers and b) has no effect on the others. */ + if(clen) { + ftpc->dirs[ftpc->dirdepth].start = (int)(curPos - rawPath); + ftpc->dirs[ftpc->dirdepth].len = (int)clen; + ftpc->dirdepth++; + } + curPos = spos + 1; + } + } + fileName = curPos; /* the rest is the filename (or empty) */ + } + break; + } /* switch */ + + if(fileName && *fileName) + ftpc->file = fileName; + else + ftpc->file = NULL; /* instead of point to a zero byte, + we make it a NULL pointer */ + + if(data->state.upload && !ftpc->file && (ftp->transfer == PPTRANSFER_BODY)) { + /* We need a filename when uploading. Return error! */ + failf(data, "Uploading to a URL without a filename"); + return CURLE_URL_MALFORMAT; + } + + ftpc->cwddone = FALSE; /* default to not done */ + + if((data->set.ftp_filemethod == FTPFILE_NOCWD) && (rawPath[0] == '/')) + ftpc->cwddone = TRUE; /* skip CWD for absolute paths */ + else { /* newly created FTP connections are already in entry path */ + const char *oldPath = data->conn->bits.reuse ? ftpc->prevpath : ""; + if(oldPath) { + size_t n = pathLen; + if(data->set.ftp_filemethod == FTPFILE_NOCWD) + n = 0; /* CWD to entry for relative paths */ + else + n -= ftpc->file ? strlen(ftpc->file) : 0; + + if((strlen(oldPath) == n) && rawPath && !strncmp(rawPath, oldPath, n)) { + infof(data, "Request has same path as previous transfer"); + ftpc->cwddone = TRUE; + } + } + } + + return CURLE_OK; +} + +/*********************************************************************** + * + * ftp_need_type() + * + * Returns TRUE if we in the current situation should send TYPE + */ +static int ftp_need_type(struct ftp_conn *ftpc, + bool ascii_wanted) +{ + return ftpc->transfertype != (ascii_wanted ? 'A' : 'I'); +} + +static void close_secondarysocket(struct Curl_easy *data, + struct ftp_conn *ftpc) +{ + (void)ftpc; + CURL_TRC_FTP(data, "[%s] closing DATA connection", FTP_CSTATE(ftpc)); + Curl_conn_cf_discard_all(data, data->conn, SECONDARYSOCKET); +} + +#ifdef CURL_PREFER_LF_LINEENDS +/* + * Lineend Conversions + * On ASCII transfers, e.g. directory listings, we might get lines + * ending in '\r\n' and we prefer '\n'. + * We might also get a lonely '\r' which we convert into a '\n'. + */ +struct ftp_cw_lc_ctx { + struct Curl_cwriter super; + bool newline_pending; +}; + +static CURLcode ftp_cw_lc_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t blen) +{ + static const char nl = '\n'; + struct ftp_cw_lc_ctx *ctx = writer->ctx; + struct ftp_conn *ftpc = Curl_conn_meta_get(data->conn, CURL_META_FTP_CONN); + + if(!ftpc) + return CURLE_FAILED_INIT; + + if(!(type & CLIENTWRITE_BODY) || ftpc->transfertype != 'A') + return Curl_cwriter_write(data, writer->next, type, buf, blen); + + /* ASCII mode BODY data, convert lineends */ + while(blen) { + /* do not pass EOS when writing parts */ + int chunk_type = (type & ~CLIENTWRITE_EOS); + const char *cp; + size_t chunk_len; + CURLcode result; + + if(ctx->newline_pending) { + if(buf[0] != '\n') { + /* previous chunk ended in '\r' and we do not see a '\n' in this one, + * need to write a newline. */ + result = Curl_cwriter_write(data, writer->next, chunk_type, &nl, 1); + if(result) + return result; + } + /* either we wrote the newline or it is part of the next chunk of bytes + * we write. */ + ctx->newline_pending = FALSE; + } + + cp = memchr(buf, '\r', blen); + if(!cp) + break; + + /* write the bytes before the '\r', excluding the '\r' */ + chunk_len = cp - buf; + if(chunk_len) { + result = Curl_cwriter_write(data, writer->next, chunk_type, + buf, chunk_len); + if(result) + return result; + } + /* skip the '\r', we now have a newline pending */ + buf = cp + 1; + blen = blen - chunk_len - 1; + ctx->newline_pending = TRUE; + } + + /* Any remaining data does not contain a '\r' */ + if(blen) { + DEBUGASSERT(!ctx->newline_pending); + return Curl_cwriter_write(data, writer->next, type, buf, blen); + } + else if(type & CLIENTWRITE_EOS) { + /* EndOfStream, if we have a trailing cr, now is the time to write it */ + if(ctx->newline_pending) { + ctx->newline_pending = FALSE; + return Curl_cwriter_write(data, writer->next, type, &nl, 1); + } + /* Always pass on the EOS type indicator */ + return Curl_cwriter_write(data, writer->next, type, buf, 0); + } + return CURLE_OK; +} + +static const struct Curl_cwtype ftp_cw_lc = { + "ftp-lineconv", + NULL, + 0, + Curl_cwriter_def_init, + ftp_cw_lc_write, + Curl_cwriter_def_flush, + Curl_cwriter_def_close, + sizeof(struct ftp_cw_lc_ctx) +}; + +#endif /* CURL_PREFER_LF_LINEENDS */ + +/*********************************************************************** + * + * ftp_check_ctrl_on_data_wait() + * + */ +static CURLcode ftp_check_ctrl_on_data_wait(struct Curl_easy *data, + struct ftp_conn *ftpc) +{ + struct connectdata *conn = data->conn; + curl_socket_t ctrl_sock = conn->sock[FIRSTSOCKET]; + struct pingpong *pp = &ftpc->pp; + size_t nread; + int ftpcode; + bool response = FALSE; + + /* First check whether there is a cached response from server */ + if(curlx_dyn_len(&pp->recvbuf)) { + const char *l = curlx_dyn_ptr(&pp->recvbuf); + if(!ISDIGIT(*l) || (*l > '3')) { + /* Data connection could not be established, let's return */ + infof(data, "There is negative response in cache while serv connect"); + (void)getftpresponse(data, &nread, &ftpcode); + return CURLE_FTP_ACCEPT_FAILED; + } + } + + if(pp->overflow) + /* there is pending control data still in the buffer to read */ + response = TRUE; + else { + int socketstate = SOCKET_READABLE(ctrl_sock, 0); + /* see if the connection request is already here */ + switch(socketstate) { + case -1: /* error */ + /* let's die here */ + failf(data, "Error while waiting for server connect"); + return CURLE_FTP_ACCEPT_FAILED; + default: + if(socketstate & CURL_CSELECT_IN) + response = TRUE; + break; + } + } + + if(response) { + infof(data, "Ctrl conn has data while waiting for data conn"); + if(pp->overflow > 3) { + const char *r = curlx_dyn_ptr(&pp->recvbuf); + size_t len = curlx_dyn_len(&pp->recvbuf); + + DEBUGASSERT((pp->overflow + pp->nfinal) <= curlx_dyn_len(&pp->recvbuf)); + /* move over the most recently handled response line */ + r += pp->nfinal; + len -= pp->nfinal; + + if((len > 3) && LASTLINE(r)) { + curl_off_t status; + if(!curlx_str_number(&r, &status, 999) && (status == 226)) { + /* funny timing situation where we get the final message on the + control connection before traffic on the data connection has been + noticed. Leave the 226 in there and use this as a trigger to read + the data socket. */ + infof(data, "Got 226 before data activity"); + return CURLE_OK; + } + } + } + + (void)getftpresponse(data, &nread, &ftpcode); + + infof(data, "FTP code: %03d", ftpcode); + + if(ftpcode / 100 > 3) + return CURLE_FTP_ACCEPT_FAILED; + + return CURLE_WEIRD_SERVER_REPLY; + } + + return CURLE_OK; +} + +/*********************************************************************** + * + * ftp_initiate_transfer() + * + * After connection from server is accepted this function is called to + * setup transfer parameters and initiate the data transfer. + * + */ +static CURLcode ftp_initiate_transfer(struct Curl_easy *data, + struct ftp_conn *ftpc) +{ + CURLcode result = CURLE_OK; + bool connected; + + CURL_TRC_FTP(data, "ftp_initiate_transfer()"); + result = Curl_conn_connect(data, SECONDARYSOCKET, TRUE, &connected); + if(result || !connected) + return result; + + if(data->state.upload) { + /* When we know we are uploading a specified file, we can get the file + size prior to the actual upload. */ + Curl_pgrsSetUploadSize(data, data->state.infilesize); + + /* FTP upload, shutdown DATA, ignore shutdown errors, as we rely + * on the server response on the CONTROL connection. */ + Curl_xfer_setup_send(data, SECONDARYSOCKET); + Curl_xfer_set_shutdown(data, TRUE, TRUE); + } + else { + /* FTP download, shutdown, do not ignore errors */ + Curl_xfer_setup_recv(data, SECONDARYSOCKET, data->req.size); + Curl_xfer_set_shutdown(data, TRUE, FALSE); + } + + ftpc->pp.pending_resp = TRUE; /* expect server response */ + ftp_state(data, ftpc, FTP_STOP); + + return CURLE_OK; +} + +static bool ftp_endofresp(struct Curl_easy *data, struct connectdata *conn, + const char *line, size_t len, int *code) +{ + curl_off_t status; + (void)data; + (void)conn; + + if((len > 3) && LASTLINE(line) && !curlx_str_number(&line, &status, 999)) { + *code = (int)status; + return TRUE; + } + + return FALSE; +} + +static CURLcode ftp_readresp(struct Curl_easy *data, + struct ftp_conn *ftpc, + int8_t sockindex, + struct pingpong *pp, + int *ftpcodep, /* return the ftp-code if done */ + size_t *size) /* size of the response */ +{ + int code; + CURLcode result = Curl_pp_readresp(data, sockindex, pp, &code, size); + DEBUGASSERT(ftpcodep); + + /* store the latest code for later retrieval, except during shutdown */ + if(!ftpc->shutdown) + data->info.httpcode = code; + + *ftpcodep = code; + + if(code == 421) { + /* 421 means "Service not available, closing control connection." and FTP + * servers use it to signal that idle session timeout has been exceeded. + * If we ignored the response, it could end up hanging in some cases. + * + * This response code can come at any point so having it treated + * generically is a good idea. + */ + infof(data, "We got a 421 - timeout"); + ftp_state(data, ftpc, FTP_STOP); + return CURLE_OPERATION_TIMEDOUT; + } + + return result; +} + +/* --- parse FTP server responses --- */ + +/* + * getftpresponse() is a BLOCKING function to read the full response from a + * server after a command. + * + */ +static CURLcode getftpresponse(struct Curl_easy *data, + size_t *nreadp, /* return number of bytes + read */ + int *ftpcodep) /* return the ftp-code */ +{ + /* + * We cannot read one byte per read() and then go back to select() as the + * OpenSSL read() does not grok that properly. + * + * Alas, read as much as possible, split up into lines, use the ending + * line in a response or continue reading. */ + + struct connectdata *conn = data->conn; + curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; + CURLcode result = CURLE_OK; + struct ftp_conn *ftpc = Curl_conn_meta_get(data->conn, CURL_META_FTP_CONN); + struct pingpong *pp = &ftpc->pp; + size_t nread; + int cache_skip = 0; + DEBUGASSERT(ftpcodep); + + CURL_TRC_FTP(data, "getftpresponse start"); + *nreadp = 0; + *ftpcodep = 0; /* 0 for errors */ + + if(!ftpc) + return CURLE_FAILED_INIT; + + while(!*ftpcodep && !result) { + /* check and reset timeout value every lap */ + timediff_t timeout = Curl_pp_state_timeleft_ms(data, pp); + timediff_t interval_ms; + + if(timeout <= 0) { + failf(data, "FTP response timeout"); + return CURLE_OPERATION_TIMEDOUT; /* already too little time */ + } + + interval_ms = 1000; /* use 1 second timeout intervals */ + if(timeout < interval_ms) + interval_ms = timeout; + + /* + * Since this function is blocking, we need to wait here for input on the + * connection and only then we call the response reading function. We do + * timeout at least every second to make the timeout check run. + * + * A caution here is that the ftp_readresp() function has a cache that may + * contain pieces of a response from the previous invoke and we need to + * make sure we do not wait for input while there is unhandled data in + * that cache. Also, if the cache is there, we call ftp_readresp() and + * the cache was not good enough to continue we must not busy-loop around + * this function. + * + */ + + if(curlx_dyn_len(&pp->recvbuf) && (cache_skip < 2)) { + /* + * There is a cache left since before. We then skipping the wait for + * socket action, unless this is the same cache like the previous round + * as then the cache was deemed not enough to act on and we then need to + * wait for more data anyway. + */ + } + else if(!Curl_conn_data_pending(data, FIRSTSOCKET)) { + curl_socket_t wsock = Curl_pp_needs_flush(data, pp) ? + sockfd : CURL_SOCKET_BAD; + int ev = Curl_socket_check(sockfd, CURL_SOCKET_BAD, wsock, interval_ms); + if(ev < 0) { + failf(data, "FTP response aborted due to select/poll error: %d", + SOCKERRNO); + return CURLE_RECV_ERROR; + } + else if(ev == 0) { + result = Curl_pgrsUpdate(data); + continue; /* continue in our loop for the timeout duration */ + } + } + + if(Curl_pp_needs_flush(data, pp)) { + result = Curl_pp_flushsend(data, pp); + if(result) + break; + } + + result = ftp_readresp(data, ftpc, FIRSTSOCKET, pp, ftpcodep, &nread); + if(result) + break; + + if(!nread && curlx_dyn_len(&pp->recvbuf)) + /* bump cache skip counter as on repeated skips we must wait for more + data */ + cache_skip++; + else + /* when we got data or there is no cache left, we reset the cache skip + counter */ + cache_skip = 0; + + *nreadp += nread; + + } /* while there is buffer left and loop is requested */ + + pp->pending_resp = FALSE; + CURL_TRC_FTP(data, "getftpresponse -> result=%d, nread=%zu, ftpcode=%d", + (int)result, *nreadp, *ftpcodep); + + return result; +} + +static CURLcode ftp_state_user(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct connectdata *conn) +{ + CURLcode result = Curl_pp_sendf(data, &ftpc->pp, "USER %s", + Curl_creds_user(conn->creds)); + if(!result) { + ftpc->ftp_trying_alternative = FALSE; + ftp_state(data, ftpc, FTP_USER); + } + return result; +} + +static CURLcode ftp_state_pwd(struct Curl_easy *data, + struct ftp_conn *ftpc) +{ + CURLcode result; +#ifdef DEBUGBUILD + if(!data->id && getenv("CURL_FTP_PWD_STOP")) + return CURLE_OK; +#endif + result = Curl_pp_sendf(data, &ftpc->pp, "%s", "PWD"); + if(!result) + ftp_state(data, ftpc, FTP_PWD); + + return result; +} + +/* For the FTP "protocol connect" and "doing" phases only */ +static CURLcode ftp_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct ftp_conn *ftpc = Curl_conn_meta_get(data->conn, CURL_META_FTP_CONN); + return ftpc ? Curl_pp_pollset(data, &ftpc->pp, ps) : CURLE_OK; +} + +/* For the FTP "DO_MORE" phase only */ +static CURLcode ftp_domore_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct ftp_conn *ftpc = Curl_conn_meta_get(data->conn, CURL_META_FTP_CONN); + + if(!ftpc) + return CURLE_OK; + + /* When in DO_MORE state, we could be either waiting for us to connect to a + * remote site, or we could wait for that site to connect to us. Or handle + * ordinary commands. + */ + CURL_TRC_FTP(data, "[%s] ftp_domore_pollset()", FTP_CSTATE(ftpc)); + + if(FTP_STOP == ftpc->state) { + /* if stopped and still in this state, then we are also waiting for a + connect on the secondary connection */ + DEBUGASSERT(data->conn->sock[SECONDARYSOCKET] != CURL_SOCKET_BAD || + (data->conn->cfilter[SECONDARYSOCKET] && + !Curl_conn_is_connected(data->conn, SECONDARYSOCKET))); + /* An unconnected SECONDARY will add its socket by itself + * via its adjust_pollset() */ + return Curl_pollset_add_in(data, ps, data->conn->sock[FIRSTSOCKET]); + } + return Curl_pp_pollset(data, &ftpc->pp, ps); +} + +static int pathlen(struct ftp_conn *ftpc, int num) +{ + DEBUGASSERT(ftpc->dirs); + DEBUGASSERT(ftpc->dirdepth > num); + return ftpc->dirs[num].len; +} + +static const char *pathpiece(struct ftp_conn *ftpc, int num) +{ + DEBUGASSERT(ftpc->dirs); + DEBUGASSERT(ftpc->dirdepth > num); + return &ftpc->rawpath[ftpc->dirs[num].start]; +} + +/* This is called after the FTP_QUOTE state is passed. + + ftp_state_cwd() sends the range of CWD commands to the server to change to + the correct directory. It may also need to send MKD commands to create + missing ones, if that option is enabled. */ +static CURLcode ftp_state_cwd(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp) +{ + CURLcode result = CURLE_OK; + + if(ftpc->cwddone) + /* already done and fine */ + result = ftp_state_mdtm(data, ftpc, ftp); + else { + /* FTPFILE_NOCWD with full path: expect ftpc->cwddone! */ + DEBUGASSERT((data->set.ftp_filemethod != FTPFILE_NOCWD) || + !(ftpc->dirdepth && ftpc->rawpath[0] == '/')); + + ftpc->count2 = 0; /* count2 counts failed CWDs */ + + if(data->conn->bits.reuse && ftpc->entrypath && + /* no need to go to entrypath when we have an absolute path */ + !(ftpc->dirdepth && ftpc->rawpath[0] == '/')) { + /* This is a reused connection. Since we change directory to where the + transfer is taking place, we must first get back to the original dir + where we ended up after login: */ + ftpc->cwdcount = 0; /* we count this as the first path, then we add one + for all upcoming ones in the ftp->dirs[] array */ + result = Curl_pp_sendf(data, &ftpc->pp, "CWD %s", ftpc->entrypath); + if(!result) + ftp_state(data, ftpc, FTP_CWD); + } + else { + if(ftpc->dirdepth) { + ftpc->cwdcount = 1; + /* issue the first CWD, the rest is sent when the CWD responses are + received... */ + result = Curl_pp_sendf(data, &ftpc->pp, "CWD %.*s", + pathlen(ftpc, 0), pathpiece(ftpc, 0)); + if(!result) + ftp_state(data, ftpc, FTP_CWD); + } + else { + /* No CWD necessary */ + result = ftp_state_mdtm(data, ftpc, ftp); + } + } + } + return result; +} + +typedef enum { + EPRT, + PORT, + DONE +} ftpport; + +/* + * Parse the CURLOPT_FTPPORT string + * "(ipv4|ipv6|domain|interface)?(:port(-range)?)?" + * and extract addr/addrlen and port_min/port_max. + */ +static CURLcode ftp_port_parse_string(struct Curl_easy *data, + struct connectdata *conn, + const char *string_ftpport, + struct Curl_sockaddr_storage *ss, + unsigned short *port_minp, + unsigned short *port_maxp, + const char **hostp, + char *hbuf, size_t hbuflen) +{ + const char *ip_end = NULL; + const char *addr = NULL; + size_t addrlen = 0; + unsigned short port_min = 0; + unsigned short port_max = 0; + char ipstr[50]; +#ifndef USE_IPV6 + (void)conn; + (void)ss; +#endif + + /* default to nothing */ + *hostp = NULL; + *port_minp = *port_maxp = 0; + + if(!string_ftpport || (strlen(string_ftpport) <= 1)) + goto done; + +#ifdef USE_IPV6 + if(*string_ftpport == '[') { + /* [ipv6]:port(-range) */ + const char *ip_start = string_ftpport + 1; + ip_end = strchr(ip_start, ']'); + if(ip_end) { + addrlen = ip_end - ip_start; + addr = ip_start; + } + } + else +#endif + if(*string_ftpport == ':') { + /* :port */ + ip_end = string_ftpport; + } + else { + ip_end = strchr(string_ftpport, ':'); + addr = string_ftpport; + if(ip_end) { +#ifdef USE_IPV6 + struct sockaddr_in6 * const sa6 = (void *)ss; +#endif + /* either IPv6 or (ipv4|domain|interface):port(-range) */ + addrlen = ip_end - string_ftpport; +#ifdef USE_IPV6 + if(curlx_inet_pton(AF_INET6, string_ftpport, &sa6->sin6_addr) == 1) { + /* IPv6 */ + addrlen = strlen(string_ftpport); + ip_end = NULL; /* this got no port ! */ + } +#endif + } + else + /* ipv4|interface */ + addrlen = strlen(string_ftpport); + } + + /* parse the port */ + if(ip_end) { + const char *portp = strchr(ip_end, ':'); + if(portp) { + curl_off_t start; + curl_off_t end; + portp++; + if(!curlx_str_number(&portp, &start, 0xffff)) { + port_min = (unsigned short)start; + if(!curlx_str_single(&portp, '-') && + !curlx_str_number(&portp, &end, 0xffff)) + port_max = (unsigned short)end; + else + port_max = port_min; + } + } + } + + /* correct errors like :1234-1230 or :-4711 */ + if(port_min > port_max) + port_min = port_max = 0; + + if(addrlen) { + const struct Curl_sockaddr_ex *remote_addr = + Curl_conn_get_remote_addr(data, FIRSTSOCKET); + + DEBUGASSERT(remote_addr); + DEBUGASSERT(addr); + if(!remote_addr || (addrlen >= sizeof(ipstr)) || (addrlen >= hbuflen)) + return CURLE_FTP_PORT_FAILED; + memcpy(ipstr, addr, addrlen); + ipstr[addrlen] = 0; + + /* attempt to get the address of the given interface name */ + switch(Curl_if2ip(remote_addr->family, +#ifdef USE_IPV6 + Curl_ipv6_scope(&remote_addr->curl_sa_addr), + conn->scope_id, +#endif + ipstr, hbuf, hbuflen)) { + case IF2IP_NOT_FOUND: + /* not an interface, use the string as hostname instead */ + memcpy(hbuf, addr, addrlen); + hbuf[addrlen] = 0; + *hostp = hbuf; + break; + case IF2IP_AF_NOT_SUPPORTED: + return CURLE_FTP_PORT_FAILED; + case IF2IP_FOUND: + *hostp = hbuf; /* use the hbuf for hostname */ + break; + } + } + /* else: only a port(-range) given, leave host as NULL */ + +done: + *port_minp = port_min; + *port_maxp = port_max; + return CURLE_OK; +} + +/* + * If no host was derived from the FTPPORT string, fall back to the IP address + * of the control connection's local socket. + */ +static CURLcode ftp_port_default_host(struct Curl_easy *data, + struct connectdata *conn, + struct Curl_sockaddr_storage *ss, + curl_socklen_t *sslenp, + const char **hostp, + char *hbuf, size_t hbuflen, + bool *non_localp) +{ + struct sockaddr *sa = (struct sockaddr *)ss; + struct sockaddr_in * const sa4 = (void *)sa; +#ifdef USE_IPV6 + struct sockaddr_in6 * const sa6 = (void *)sa; +#endif + char buffer[STRERROR_LEN]; + CURLcode result; + + *sslenp = sizeof(*ss); + if(getsockname(conn->sock[FIRSTSOCKET], sa, sslenp)) { + failf(data, "getsockname() failed: %s", + curlx_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_FTP_PORT_FAILED; + } + switch(sa->sa_family) { +#ifdef USE_IPV6 + case AF_INET6: + result = curlx_inet_ntop(sa->sa_family, &sa6->sin6_addr, hbuf, hbuflen); + break; +#endif + default: + result = curlx_inet_ntop(sa->sa_family, &sa4->sin_addr, hbuf, hbuflen); + break; + } + if(result) + return CURLE_FTP_PORT_FAILED; + + *hostp = hbuf; + *non_localp = FALSE; /* we know it is local now */ + return CURLE_OK; +} + +/* + * Resolve the host string to a list of addresses. + */ +static CURLcode ftp_port_resolve_host(struct Curl_easy *data, + struct connectdata *conn, + const char *host, + struct Curl_dns_entry **dns_entryp, + const struct Curl_addrinfo **resp) +{ + CURLcode result; + + *resp = NULL; + result = Curl_resolv_blocking( + data, Curl_resolv_dns_queries(data, conn->ip_version), + host, 0, Curl_conn_get_transport(data, conn), dns_entryp); + if(result) + failf(data, "failed to resolve the address provided to PORT: %s", host); + else { + DEBUGASSERT(*dns_entryp); + *resp = (*dns_entryp)->addr; + } + return result; +} + +/* + * Open a TCP socket for the resolved address family. + */ +static CURLcode ftp_port_open_socket(struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *res, + const struct Curl_addrinfo **aip, + curl_socket_t *portsockp) +{ + char buffer[STRERROR_LEN]; + int sockerr = 0; + const struct Curl_addrinfo *ai; + CURLcode result = CURLE_FTP_PORT_FAILED; + + for(ai = res; ai; ai = ai->ai_next) { + result = + Curl_socket_open(data, ai, NULL, + Curl_conn_get_transport(data, conn), portsockp); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + return result; + result = CURLE_FTP_PORT_FAILED; + sockerr = SOCKERRNO; + continue; + } + break; + } + if(!ai) { + failf(data, "socket failure: %s", + curlx_strerror(sockerr, buffer, sizeof(buffer))); + return CURLE_FTP_PORT_FAILED; + } + *aip = ai; + return result; +} + +/* + * Bind the socket to a local address and port within the requested range. + * Falls back to the control-connection address if the user-requested address + * is non-local. + */ +static CURLcode ftp_port_bind_socket(struct Curl_easy *data, + struct connectdata *conn, + curl_socket_t portsock, + const struct Curl_addrinfo *ai, + struct Curl_sockaddr_storage *ss, + curl_socklen_t *sslen_io, + unsigned short port_min, + unsigned short port_max, + bool non_local) +{ + struct sockaddr *sa = (struct sockaddr *)ss; + struct sockaddr_in * const sa4 = (void *)sa; +#ifdef USE_IPV6 + struct sockaddr_in6 * const sa6 = (void *)sa; +#endif + char buffer[STRERROR_LEN]; + unsigned short port; + int sockerr; + + memcpy(sa, ai->ai_addr, ai->ai_addrlen); + *sslen_io = ai->ai_addrlen; + + for(port = port_min; port <= port_max;) { + if(sa->sa_family == AF_INET) + sa4->sin_port = htons(port); +#ifdef USE_IPV6 + else + sa6->sin6_port = htons(port); +#endif + if(bind(portsock, sa, *sslen_io)) { + sockerr = SOCKERRNO; + if(non_local && (sockerr == SOCKEADDRNOTAVAIL)) { + /* The requested bind address is not local. Use the address used for + * the control connection instead and restart the port loop. + */ + infof(data, "bind(port=%hu) on non-local address failed: %s", port, + curlx_strerror(sockerr, buffer, sizeof(buffer))); + + *sslen_io = sizeof(*ss); + if(getsockname(conn->sock[FIRSTSOCKET], sa, sslen_io)) { + failf(data, "getsockname() failed: %s", + curlx_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_FTP_PORT_FAILED; + } + port = port_min; + non_local = FALSE; /* do not try this again */ + continue; + } + if(sockerr != SOCKEADDRINUSE && sockerr != SOCKEACCES) { + failf(data, "bind(port=%hu) failed: %s", port, + curlx_strerror(sockerr, buffer, sizeof(buffer))); + return CURLE_FTP_PORT_FAILED; + } + } + else + break; + + /* check if port is the maximum value here, because it might be 0xffff + and then the increment below will wrap the 16-bit counter */ + if(port == port_max) { + failf(data, "bind() failed, ran out of ports"); + return CURLE_FTP_PORT_FAILED; + } + port++; + } + + /* re-read the name so we can extract the actual port chosen */ + *sslen_io = sizeof(*ss); + if(getsockname(portsock, sa, sslen_io)) { + failf(data, "getsockname() failed: %s", + curlx_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_FTP_PORT_FAILED; + } + CURL_TRC_FTP(data, "ftp_port_bind_socket(), socket bound to port %d", port); + return CURLE_OK; +} + +/* + * Start listening on the data socket. + */ +static CURLcode ftp_port_listen(struct Curl_easy *data, curl_socket_t portsock) +{ + char buffer[STRERROR_LEN]; + + if(listen(portsock, 1)) { + failf(data, "socket failure: %s", + curlx_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_FTP_PORT_FAILED; + } + CURL_TRC_FTP(data, "ftp_port_listen(), listening on port"); + return CURLE_OK; +} + +/* + * Send the EPRT or PORT command to the server. + */ +static CURLcode ftp_port_send_command(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct connectdata *conn, + struct Curl_sockaddr_storage *ss, + const struct Curl_addrinfo *ai, + ftpport fcmd) +{ + static const char mode[][5] = { "EPRT", "PORT" }; + struct sockaddr *sa = (struct sockaddr *)ss; + struct sockaddr_in * const sa4 = (void *)sa; +#ifdef USE_IPV6 + struct sockaddr_in6 * const sa6 = (void *)sa; +#endif + char myhost[MAX_IPADR_LEN + 1] = ""; + unsigned short port; + CURLcode result; + + /* Get a plain printable version of the numerical address to work with. This + logic uses the address provided by the FTPPORT option, which at times + might differ from the address in 'ss' used to bind to: when a user asks + the server to connect to a specific address knowing that it works, but + curl instead selects to listen to the local address because it cannot use + the provided address. FTP is strange. */ + Curl_printable_address(ai, myhost, sizeof(myhost)); + +#ifdef USE_IPV6 + if(!conn->bits.ftp_use_eprt && conn->bits.ipv6) + /* EPRT is disabled but we are connected to an IPv6 host, so we ignore the + request and enable EPRT again! */ + conn->bits.ftp_use_eprt = TRUE; +#endif + + for(; fcmd != DONE; fcmd++) { + + if(!conn->bits.ftp_use_eprt && (EPRT == fcmd)) + /* if disabled, goto next */ + continue; + + if((PORT == fcmd) && sa->sa_family != AF_INET) + /* PORT is IPv4 only */ + continue; + + switch(sa->sa_family) { + case AF_INET: + port = ntohs(sa4->sin_port); + break; +#ifdef USE_IPV6 + case AF_INET6: + port = ntohs(sa6->sin6_port); + break; +#endif + default: + continue; /* might as well skip this */ + } + + if(EPRT == fcmd) { + /* + * Two fine examples from RFC2428; + * + * EPRT |1|132.235.1.2|6275| + * + * EPRT |2|1080::8:800:200C:417A|5282| + */ + result = Curl_pp_sendf(data, &ftpc->pp, "%s |%d|%s|%hu|", mode[fcmd], + sa->sa_family == AF_INET ? 1 : 2, myhost, port); + if(result) { + failf(data, "Failure sending EPRT command: %s", + curl_easy_strerror(result)); + return result; + } + break; + } + if(PORT == fcmd) { + /* large enough for [IP address],[num],[num] */ + char target[sizeof(myhost) + 20]; + const char *source = myhost; + char *dest = target; + + /* translate x.x.x.x to x,x,x,x */ + while(*source) { + if(*source == '.') + *dest = ','; + else + *dest = *source; + dest++; + source++; + } + *dest = 0; + curl_msnprintf(dest, 20, ",%d,%d", (int)(port >> 8), (int)(port & 0xff)); + + result = Curl_pp_sendf(data, &ftpc->pp, "%s %s", mode[fcmd], target); + if(result) { + failf(data, "Failure sending PORT command: %s", + curl_easy_strerror(result)); + return result; + } + break; + } + } + + /* store which command was sent */ + ftpc->count1 = fcmd; + ftp_state(data, ftpc, FTP_PORT); + return CURLE_OK; +} + +/* + * ftp_state_use_port() + * + * Set up an active-mode FTP data connection (using PORT or EPRT) and start + * listening for the server's incoming connection on SECONDARYSOCKET. + */ +static CURLcode ftp_state_use_port(struct Curl_easy *data, + struct ftp_conn *ftpc, + ftpport fcmd) /* start with this */ +{ + CURLcode result = CURLE_FTP_PORT_FAILED; + struct connectdata *conn = data->conn; + curl_socket_t portsock = CURL_SOCKET_BAD; + + struct Curl_sockaddr_storage ss; + curl_socklen_t sslen; + char hbuf[NI_MAXHOST]; + const char *host = NULL; + const char *string_ftpport = CURL_EASY_STR(data, STRING_FTPPORT); + struct Curl_dns_entry *dns_entry = NULL; + const struct Curl_addrinfo *res = NULL; + const struct Curl_addrinfo *ai = NULL; + unsigned short port_min = 0; + unsigned short port_max = 0; + bool non_local = TRUE; + + /* parse the FTPPORT string for address and port range */ + result = ftp_port_parse_string(data, conn, string_ftpport, + &ss, &port_min, &port_max, + &host, hbuf, sizeof(hbuf)); + if(!result && !host) + /* if no host was specified, use the control connection's local IP */ + result = ftp_port_default_host(data, conn, &ss, &sslen, &host, + hbuf, sizeof(hbuf), &non_local); + + /* resolve host string to address list */ + if(!result) + result = ftp_port_resolve_host(data, conn, host, &dns_entry, &res); + + /* Open a TCP socket for the data connection */ + if(!result) + result = ftp_port_open_socket(data, conn, res, &ai, &portsock); + if(!result) { + CURL_TRC_FTP(data, "[%s] ftp_state_use_port(), opened socket", + FTP_CSTATE(ftpc)); + + /* bind to a suitable local address / port */ + result = ftp_port_bind_socket(data, conn, portsock, ai, &ss, &sslen, + port_min, port_max, non_local); + } + + /* listen */ + if(!result) + result = ftp_port_listen(data, portsock); + + /* send the PORT / EPRT command */ + if(!result) + result = ftp_port_send_command(data, ftpc, conn, &ss, ai, fcmd); + + /* replace any filter on SECONDARY with one listening on this socket */ + if(!result) + result = Curl_conn_tcp_listen_set(data, conn, SECONDARYSOCKET, &portsock); + + if(!result) + portsock = CURL_SOCKET_BAD; /* now held in filter */ + + /* cleanup */ + + if(dns_entry) + Curl_dns_entry_unlink(data, &dns_entry); + if(result) { + ftp_state(data, ftpc, FTP_STOP); + } + else { + /* successfully set up the listen socket filter. SSL needed? + * Use the control connections origin for cert verification. */ + if(conn->bits.ftp_use_data_ssl && data->set.ftp_use_port && + !Curl_conn_is_ssl(conn, SECONDARYSOCKET)) { + result = Curl_ssl_cfilter_add( + data, Curl_conn_get_origin(conn, FIRSTSOCKET), + conn, SECONDARYSOCKET); + } + conn->bits.do_more = FALSE; + Curl_expire(data, (data->set.accepttimeout > 0) ? + data->set.accepttimeout: DEFAULT_ACCEPT_TIMEOUT, + EXPIRE_FTP_ACCEPT); + } + if(portsock != CURL_SOCKET_BAD) + Curl_socket_close(data, conn, portsock); + return result; +} + +static CURLcode ftp_state_use_pasv(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + /* Here's the executive summary on what to do: + + PASV is RFC959, expect: + 227 Entering Passive Mode (a1,a2,a3,a4,p1,p2) + + LPSV is RFC1639, expect: + 228 Entering Long Passive Mode (4,4,a1,a2,a3,a4,2,p1,p2) + + EPSV is RFC2428, expect: + 229 Entering Extended Passive Mode (|||port|) + */ + + static const char mode[][5] = { "EPSV", "PASV" }; + int modeoff; + +#ifdef PF_INET6 + if(!conn->bits.ftp_use_epsv && conn->bits.ipv6) + /* EPSV is disabled but we are connected to an IPv6 host, so we ignore the + request and enable EPSV again! */ + conn->bits.ftp_use_epsv = TRUE; +#endif + + modeoff = conn->bits.ftp_use_epsv ? 0 : 1; + + result = Curl_pp_sendf(data, &ftpc->pp, "%s", mode[modeoff]); + if(!result) { + ftpc->count1 = modeoff; + ftp_state(data, ftpc, FTP_PASV); + infof(data, "Connect data stream passively"); + } + return result; +} + +/* + * ftp_state_prepare_transfer() starts PORT, PASV or PRET etc. + * + * REST is the last command in the chain of commands when a "head"-like + * request is made. Thus, if an actual transfer is to be made this is where we + * take off for real. + */ +static CURLcode ftp_state_prepare_transfer(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + if(ftp->transfer != PPTRANSFER_BODY) { + /* does not transfer any data */ + + /* still possibly do PRE QUOTE jobs */ + ftp_state(data, ftpc, FTP_RETR_PREQUOTE); + result = ftp_state_quote(data, ftpc, ftp, TRUE, FTP_RETR_PREQUOTE); + } + else if(data->set.ftp_use_port) { + /* We have chosen to use the PORT (or similar) command */ + result = ftp_state_use_port(data, ftpc, EPRT); + } + else { + /* We have chosen (this is default) to use the PASV (or similar) command */ + if(data->set.ftp_use_pret) { + /* The user has requested that we send a PRET command + to prepare the server for the upcoming PASV */ + if(!ftpc->file) + result = Curl_pp_sendf(data, &ftpc->pp, "PRET %s", + CURL_EASY_STR(data, STRING_CUSTOMREQUEST) ? + CURL_EASY_STR(data, STRING_CUSTOMREQUEST) : + (data->state.list_only ? "NLST" : "LIST")); + else if(data->state.upload) + result = Curl_pp_sendf(data, &ftpc->pp, "PRET STOR %s", ftpc->file); + else + result = Curl_pp_sendf(data, &ftpc->pp, "PRET RETR %s", ftpc->file); + if(!result) + ftp_state(data, ftpc, FTP_PRET); + } + else + result = ftp_state_use_pasv(data, ftpc, conn); + } + return result; +} + +static CURLcode ftp_state_rest(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp) +{ + CURLcode result = CURLE_OK; + + if((ftp->transfer != PPTRANSFER_BODY) && ftpc->file) { + /* if a "head"-like request is being made (on a file) */ + + /* Determine if server can respond to REST command and therefore + whether it supports range */ + result = Curl_pp_sendf(data, &ftpc->pp, "REST %d", 0); + if(!result) + ftp_state(data, ftpc, FTP_REST); + } + else + result = ftp_state_prepare_transfer(data, ftpc, ftp); + + return result; +} + +static CURLcode ftp_state_size(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp) +{ + CURLcode result = CURLE_OK; + + if((ftp->transfer == PPTRANSFER_INFO) && ftpc->file) { + /* if a "head"-like request is being made (on a file) */ + + /* we know ftpc->file is a valid pointer to a filename */ + result = Curl_pp_sendf(data, &ftpc->pp, "SIZE %s", ftpc->file); + if(!result) + ftp_state(data, ftpc, FTP_SIZE); + } + else + result = ftp_state_rest(data, ftpc, ftp); + + return result; +} + +static CURLcode ftp_state_list(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp) +{ + CURLcode result = CURLE_OK; + + /* If this output is to be machine-parsed, the NLST command might be better + to use, since the LIST command output is not specified or standard in any + way. It has turned out that the NLST list output is not the same on all + servers either... */ + + /* if FTPFILE_NOCWD was specified, we should add the path + as argument for the LIST / NLST / or custom command. + Whether the server will support this, is uncertain. + + The other ftp_filemethods will CWD into dir/dir/ first and + then do LIST (in that case: nothing to do here) */ + const char *lstArg = NULL; + int lstArglen = 0; + char *cmd; + + if((data->set.ftp_filemethod == FTPFILE_NOCWD) && ftp->path) { + /* URL-decode before evaluation: e.g. paths starting/ending with %2f */ + const char *rawPath = ftpc->rawpath; + const char *slashPos = strrchr(rawPath, '/'); + if(slashPos) { + /* chop off the file part if format is dir/file otherwise remove + the trailing slash for dir/dir/ except for absolute path / */ + size_t n = slashPos - rawPath; + if(n == 0) + ++n; + + lstArg = rawPath; + lstArglen = (int)n; + } + } + + cmd = curl_maprintf("%s%s%.*s", + CURL_EASY_STR(data, STRING_CUSTOMREQUEST) ? + CURL_EASY_STR(data, STRING_CUSTOMREQUEST) : + (data->state.list_only ? "NLST" : "LIST"), + lstArg ? " " : "", + lstArglen, lstArg ? lstArg : ""); + + if(!cmd) + return CURLE_OUT_OF_MEMORY; + + result = Curl_pp_sendf(data, &ftpc->pp, "%s", cmd); + curlx_free(cmd); + + if(!result) + ftp_state(data, ftpc, FTP_LIST); + + return result; +} + +static CURLcode ftp_state_list_prequote(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp) +{ + /* We have sent the TYPE, now we must send the list of prequote strings */ + return ftp_state_quote(data, ftpc, ftp, TRUE, FTP_LIST_PREQUOTE); +} + +static CURLcode ftp_state_retr_prequote(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp) +{ + /* We have sent the TYPE, now we must send the list of prequote strings */ + return ftp_state_quote(data, ftpc, ftp, TRUE, FTP_RETR_PREQUOTE); +} + +static CURLcode ftp_state_stor_prequote(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp) +{ + /* We have sent the TYPE, now we must send the list of prequote strings */ + return ftp_state_quote(data, ftpc, ftp, TRUE, FTP_STOR_PREQUOTE); +} + +static CURLcode ftp_state_type(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp) +{ + CURLcode result = CURLE_OK; + + /* If we have selected NOBODY and HEADER, it means that we only want file + information. Which in FTP cannot be much more than the file size and + date. */ + if(data->req.no_body && ftpc->file && + ftp_need_type(ftpc, (bool)data->state.prefer_ascii)) { + /* The SIZE command is _not_ RFC 959 specified, and therefore many servers + may not support it! It is however the only way we have to get a file's + size! */ + + ftp->transfer = PPTRANSFER_INFO; + /* this means no actual transfer will be made */ + + /* Some servers return different sizes for different modes, and thus we + must set the proper type before we check the size */ + result = ftp_nb_type(data, ftpc, ftp, (bool)data->state.prefer_ascii, + FTP_TYPE); + if(result) + return result; + } + else + result = ftp_state_size(data, ftpc, ftp); + + return result; +} + +/* This is called after the CWD commands have been done in the beginning of + the DO phase */ +static CURLcode ftp_state_mdtm(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp) +{ + CURLcode result = CURLE_OK; + + /* Requested time of file or time-depended transfer? */ + if((data->set.get_filetime || data->set.timecondition) && ftpc->file) { + + /* we have requested to get the modified-time of the file, this is a white + spot as the MDTM is not mentioned in RFC959 */ + result = Curl_pp_sendf(data, &ftpc->pp, "MDTM %s", ftpc->file); + + if(!result) + ftp_state(data, ftpc, FTP_MDTM); + } + else + result = ftp_state_type(data, ftpc, ftp); + + return result; +} + +/* This is called after the TYPE and possible quote commands have been sent */ +static CURLcode ftp_state_ul_setup(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + bool sizechecked) +{ + CURLcode result = CURLE_OK; + curl_bit append = data->set.remote_append; + + if((data->state.resume_from && !sizechecked) || + ((data->state.resume_from > 0) && sizechecked)) { + /* we are about to continue the uploading of a file + 1. get already existing file's size. We use the SIZE command for this + which may not exist in the server! The SIZE command is not in + RFC959. + + 2. This used to set REST, but since we can do append, we issue no + another ftp command. Skip the source file offset and APPEND the rest + on the file instead + + 3. pass file-size number of bytes in the source file + 4. lower the infilesize counter */ + /* => transfer as usual */ + int seekerr = CURL_SEEKFUNC_OK; + + if(data->state.resume_from < 0) { + /* Got no given size to start from, figure it out */ + result = Curl_pp_sendf(data, &ftpc->pp, "SIZE %s", ftpc->file); + if(!result) + ftp_state(data, ftpc, FTP_STOR_SIZE); + return result; + } + + /* enable append */ + append = TRUE; + + /* Let's read off the proper amount of bytes from the input. */ + if(data->set.seek_func) { + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_seek_func); + seekerr = data->set.seek_func(data->set.seek_client, + data->state.resume_from, SEEK_SET); + CURL_CBAPI_END(&guard); + } + + if(seekerr != CURL_SEEKFUNC_OK) { + curl_off_t passed = 0; + if(seekerr != CURL_SEEKFUNC_CANTSEEK) { + failf(data, "Could not seek stream"); + return CURLE_FTP_COULDNT_USE_REST; + } + /* seekerr == CURL_SEEKFUNC_CANTSEEK (cannot seek to offset) */ + do { + char scratch[4 * 1024]; + size_t readthisamountnow = + (data->state.resume_from - passed > (curl_off_t)sizeof(scratch)) ? + sizeof(scratch) : + curlx_sotouz(data->state.resume_from - passed); + + size_t actuallyread = + data->state.fread_func(scratch, 1, readthisamountnow, + data->state.in); + + passed += actuallyread; + if((actuallyread == 0) || (actuallyread > readthisamountnow)) { + /* this checks for greater-than only to make sure that the + CURL_READFUNC_ABORT return code still aborts */ + failf(data, "Failed to read data"); + return CURLE_FTP_COULDNT_USE_REST; + } + } while(passed < data->state.resume_from); + } + /* now, decrease the size of the read */ + if(data->state.infilesize > 0) { + data->state.infilesize -= data->state.resume_from; + + if(data->state.infilesize <= 0) { + infof(data, "File already completely uploaded"); + + /* no data to transfer */ + Curl_xfer_setup_nop(data); + + /* Set ->transfer so that we will not get any error in + * ftp_done() because we did not transfer anything! */ + ftp->transfer = PPTRANSFER_NONE; + + ftp_state(data, ftpc, FTP_STOP); + return CURLE_OK; + } + } + /* we have passed, proceed as normal */ + } /* resume_from */ + + result = Curl_pp_sendf(data, &ftpc->pp, append ? "APPE %s" : "STOR %s", + ftpc->file); + if(!result) + ftp_state(data, ftpc, FTP_STOR); + + return result; +} + +static CURLcode ftp_state_retr(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + curl_off_t filesize) +{ + CURLcode result = CURLE_OK; + + CURL_TRC_FTP(data, "[%s] ftp_state_retr()", FTP_CSTATE(ftpc)); + if(data->set.max_filesize && (filesize > data->set.max_filesize)) { + failf(data, "Maximum file size exceeded"); + return CURLE_FILESIZE_EXCEEDED; + } + ftp->downloadsize = filesize; + + if(data->state.resume_from) { + /* We always (attempt to) get the size of downloads, so it is done before + this even when not doing resumes. */ + if(filesize == -1) { + infof(data, "ftp server does not support SIZE"); + /* We could not get the size and therefore we cannot know if there + really is a part of the file left to get, although the server will + close the connection when we start the connection so it will not + cause us any harm, not make us exit as nicely. */ + } + else { + /* We got a file size report, so we check that there actually is a + part of the file left to get, or else we go home. */ + if(data->state.resume_from < 0) { + /* We are supposed to download the last abs(from) bytes */ + if(filesize < -data->state.resume_from) { + failf(data, "Offset (%" FMT_OFF_T + ") was beyond file size (%" FMT_OFF_T ")", + data->state.resume_from, filesize); + return CURLE_BAD_DOWNLOAD_RESUME; + } + /* convert to size to download */ + ftp->downloadsize = -data->state.resume_from; + /* download from where? */ + data->state.resume_from = filesize - ftp->downloadsize; + } + else { + if(filesize < data->state.resume_from) { + failf(data, "Offset (%" FMT_OFF_T + ") was beyond file size (%" FMT_OFF_T ")", + data->state.resume_from, filesize); + return CURLE_BAD_DOWNLOAD_RESUME; + } + /* Now store the number of bytes we are expected to download */ + ftp->downloadsize = filesize - data->state.resume_from; + } + } + + if(ftp->downloadsize == 0) { + /* no data to transfer */ + Curl_xfer_setup_nop(data); + infof(data, "File already completely downloaded"); + + /* Set ->transfer so that we will not get any error in ftp_done() + * because we did not transfer the any file */ + ftp->transfer = PPTRANSFER_NONE; + ftp_state(data, ftpc, FTP_STOP); + return CURLE_OK; + } + + /* Set resume file transfer offset */ + infof(data, "Instructs server to resume from offset %" FMT_OFF_T, + data->state.resume_from); + + result = Curl_pp_sendf(data, &ftpc->pp, "REST %" FMT_OFF_T, + data->state.resume_from); + if(!result) + ftp_state(data, ftpc, FTP_RETR_REST); + } + else { + /* no resume */ + result = Curl_pp_sendf(data, &ftpc->pp, "RETR %s", ftpc->file); + if(!result) + ftp_state(data, ftpc, FTP_RETR); + } + + return result; +} + +static CURLcode ftp_state_quote(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + bool init, + ftpstate instate) +{ + CURLcode result = CURLE_OK; + bool quote = FALSE; + struct curl_slist *item; + + switch(instate) { + case FTP_QUOTE: + default: + item = data->set.quote; + break; + case FTP_RETR_PREQUOTE: + case FTP_STOR_PREQUOTE: + case FTP_LIST_PREQUOTE: + item = data->set.prequote; + break; + case FTP_POSTQUOTE: + item = data->set.postquote; + break; + } + + /* + * This state uses: + * 'count1' to iterate over the commands to send + * 'count2' to store whether to allow commands to fail + */ + + if(init) + ftpc->count1 = 0; + else + ftpc->count1++; + + if(item) { + int i = 0; + + /* Skip count1 items in the linked list */ + while((i < ftpc->count1) && item) { + item = item->next; + i++; + } + if(item) { + const char *cmd = item->data; + if(cmd[0] == '*') { + cmd++; + ftpc->count2 = 1; /* the sent command is allowed to fail */ + } + else + ftpc->count2 = 0; /* failure means cancel operation */ + + result = Curl_pp_sendf(data, &ftpc->pp, "%s", cmd); + if(result) + return result; + ftp_state(data, ftpc, instate); + quote = TRUE; + } + } + + if(!quote) { + /* No more quote to send, continue to ... */ + switch(instate) { + case FTP_QUOTE: + default: + result = ftp_state_cwd(data, ftpc, ftp); + break; + case FTP_RETR_PREQUOTE: + if(ftp->transfer != PPTRANSFER_BODY) + ftp_state(data, ftpc, FTP_STOP); + else { + if(ftpc->known_filesize != -1) { + Curl_pgrsSetDownloadSize(data, ftpc->known_filesize); + result = ftp_state_retr(data, ftpc, ftp, ftpc->known_filesize); + } + else { + if(data->set.ignorecl || data->state.prefer_ascii) { + /* 'ignorecl' is used to support download of growing files. It + prevents the state machine from requesting the file size from + the server. With an unknown file size the download continues + until the server terminates it, otherwise the client stops if + the received byte count exceeds the reported file size. Set + option CURLOPT_IGNORE_CONTENT_LENGTH to 1 to enable this + behavior. + + In addition: asking for the size for 'TYPE A' transfers is not + constructive since servers do not report the converted size. + Thus, skip it. */ + result = Curl_pp_sendf(data, &ftpc->pp, "RETR %s", ftpc->file); + if(!result) + ftp_state(data, ftpc, FTP_RETR); + } + else { + result = Curl_pp_sendf(data, &ftpc->pp, "SIZE %s", ftpc->file); + if(!result) + ftp_state(data, ftpc, FTP_RETR_SIZE); + } + } + } + break; + case FTP_STOR_PREQUOTE: + result = ftp_state_ul_setup(data, ftpc, ftp, FALSE); + break; + case FTP_POSTQUOTE: + break; + case FTP_LIST_PREQUOTE: + ftp_state(data, ftpc, FTP_LIST_TYPE); + result = ftp_state_list(data, ftpc, ftp); + break; + } + } + + return result; +} + +/* called from ftp_state_pasv_resp to switch to PASV in case of EPSV + problems */ +static CURLcode ftp_epsv_disable(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + + if(conn->bits.ipv6 && !Curl_conn_is_tunneling(conn, FIRSTSOCKET)) { + /* We cannot disable EPSV when doing IPv6, so this is instead a fail */ + failf(data, "Failed EPSV attempt, exiting"); + return CURLE_WEIRD_SERVER_REPLY; + } + + infof(data, "Failed EPSV attempt. Disabling EPSV"); + /* disable it for next transfer */ + conn->bits.ftp_use_epsv = FALSE; + close_secondarysocket(data, ftpc); + data->state.errorbuf = FALSE; /* allow error message to get + rewritten */ + result = Curl_pp_sendf(data, &ftpc->pp, "%s", "PASV"); + if(!result) { + ftpc->count1++; + /* remain in/go to the FTP_PASV state */ + ftp_state(data, ftpc, FTP_PASV); + } + return result; +} + +static CURLcode ftp_control_addr_dup(struct Curl_easy *data, char **newhostp) +{ + struct connectdata *conn = data->conn; + struct ip_quadruple ipquad; + bool is_ipv6; + + /* Returns the control connection IP address. + If a proxy tunnel is used, returns the original hostname instead, because + the effective control connection address is the proxy address, + not the ftp host. */ +#ifndef CURL_DISABLE_PROXY + if(Curl_conn_is_tunneling(conn, FIRSTSOCKET)) + *newhostp = curlx_strdup(conn->origin->hostname); + else +#endif + if(!Curl_conn_get_ip_info(data, conn, FIRSTSOCKET, &is_ipv6, &ipquad) && + *ipquad.remote_ip) + *newhostp = curlx_strdup(ipquad.remote_ip); + else { + /* failed to get the remote_ip of the DATA connection */ + failf(data, "unable to get peername of DATA connection"); + *newhostp = NULL; + return CURLE_FTP_CANT_GET_HOST; + } + return *newhostp ? CURLE_OK : CURLE_OUT_OF_MEMORY; +} + +static bool match_pasv_6nums(const char *p, + unsigned int *array) /* 6 numbers */ +{ + int i; + for(i = 0; i < 6; i++) { + curl_off_t num; + if(i) { + if(*p != ',') + return FALSE; + p++; + } + if(curlx_str_number(&p, &num, 0xff)) + return FALSE; + array[i] = (unsigned int)num; + } + return TRUE; +} + +static CURLcode ftp_state_pasv_resp(struct Curl_easy *data, + struct ftp_conn *ftpc, + int ftpcode) +{ + struct connectdata *conn = data->conn; + CURLcode result; + const struct pingpong *pp = &ftpc->pp; + char *newhost = NULL; + unsigned short newport = 0; + const char *str = curlx_dyn_ptr(&pp->recvbuf) + 4; /* start on the first + letter */ + if((ftpc->count1 == 0) && + (ftpcode == 229)) { + /* positive EPSV response */ + const char *ptr = strchr(str, '('); + if(ptr) { + char sep; + ptr++; + /* |||12345| */ + sep = ptr[0]; + if(sep && (ptr[1] == sep) && (ptr[2] == sep) && ISDIGIT(ptr[3])) { + const char *p = &ptr[3]; + curl_off_t num; + if(curlx_str_number(&p, &num, 0xffff) || (*p != sep)) { + failf(data, "Illegal port number in EPSV reply"); + return CURLE_FTP_WEIRD_PASV_REPLY; + } + newport = (unsigned short)num; + result = ftp_control_addr_dup(data, &newhost); + if(result) + return result; + } + else + ptr = NULL; + } + if(!ptr) { + failf(data, "Weirdly formatted EPSV reply"); + return CURLE_FTP_WEIRD_PASV_REPLY; + } + } + else if((ftpc->count1 == 1) && + (ftpcode == 227)) { + /* positive PASV response */ + unsigned int ip[6]; + + /* + * Scan for a sequence of six comma-separated numbers and use them as + * IP+port indicators. + * + * Found reply-strings include: + * "227 Entering Passive Mode (127,0,0,1,4,51)" + * "227 Data transfer will passively listen to 127,0,0,1,4,51" + * "227 Entering passive mode. 127,0,0,1,4,51" + */ + while(*str) { + if(match_pasv_6nums(str, ip)) + break; + str++; + } + + if(!*str) { + failf(data, "Could not interpret the 227-response"); + return CURLE_FTP_WEIRD_227_FORMAT; + } + + /* we got OK from server */ + if(data->set.ftp_skip_ip) { + /* told to ignore the remotely given IP but instead use the host we used + for the control connection */ + infof(data, "Skip %u.%u.%u.%u for data connection, reuse %s instead", + ip[0], ip[1], ip[2], ip[3], conn->origin->hostname); + result = ftp_control_addr_dup(data, &newhost); + if(result) + return result; + } + else + newhost = curl_maprintf("%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]); + + if(!newhost) + return CURLE_OUT_OF_MEMORY; + + newport = (unsigned short)(((ip[4] << 8) + ip[5]) & 0xffff); + } + else if(ftpc->count1 == 0) { + /* EPSV failed, move on to PASV */ + return ftp_epsv_disable(data, ftpc, conn); + } + else { + failf(data, "Bad PASV/EPSV response: %03d", ftpcode); + return CURLE_FTP_WEIRD_PASV_REPLY; + } + + DEBUGASSERT(newhost); + Curl_peer_unlink(&conn->origin2); + result = Curl_peer_create(data, conn->scheme, newhost, newport, + &conn->origin2); + if(result) + goto error; + + /* If FIRSTSOCKET goes via another peer, SECONDARY needs as well, + * but with its new port. */ + if(conn->via_peer) { + Curl_peer_unlink(&conn->via_peer2); + result = Curl_peer_create(data, conn->via_peer->scheme, + conn->via_peer->hostname, newport, + &conn->via_peer2); + if(result) + goto error; + } + + result = Curl_conn_setup(data, conn, SECONDARYSOCKET, + conn->bits.ftp_use_data_ssl ? + CURL_CF_SSL_ENABLE : CURL_CF_SSL_DISABLE); + + if(result) { + if((result != CURLE_OUT_OF_MEMORY) && + (ftpc->count1 == 0) && (ftpcode == 229)) { + result = ftp_epsv_disable(data, ftpc, conn); + } + goto error; + } + + /* + * When this is used from the multi interface, this might have returned with + * the 'connected' set to FALSE and thus we are now awaiting a non-blocking + * connect to connect. + */ + +#ifdef CURLVERBOSE + if(data->set.verbose) { + /* Dump information about this second connection when we have issued + * a PASV command. */ + infof(data, "Connecting to %s port %d", + conn->origin2->hostname, conn->origin2->port); + } +#endif + + conn->bits.do_more = TRUE; + ftp_state(data, ftpc, FTP_STOP); /* this phase is completed */ + +error: + curlx_free(newhost); + return result; +} + +/* called repeatedly until done from multi.c */ +static CURLcode ftp_statemach(struct Curl_easy *data, + struct ftp_conn *ftpc, + bool *done) +{ + CURLcode result = Curl_pp_statemach(data, &ftpc->pp, FALSE, FALSE); + + /* Check for the state outside of the Curl_socket_check() return code checks + since at times we are in fact already in this state when this function + gets called. */ + *done = (ftpc->state == FTP_STOP); + + return result; +} + +/* + * ftp_do_more() + * + * This function shall be called when the second FTP (data) connection is + * connected. + * + * 'more' can return DOMORE_INCOMPLETE, DOMORE_DONE or DOMORE_GOBACK + * (which is for when PASV is being sent to retry a failed EPSV). + */ +static CURLcode ftp_do_more(struct Curl_easy *data, domore *more) +{ + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = Curl_conn_meta_get(data->conn, CURL_META_FTP_CONN); + struct FTP *ftp = Curl_meta_get(data, CURL_META_FTP_EASY); + CURLcode result = CURLE_OK; + bool connected = FALSE; + bool complete = FALSE; + /* the ftp struct is inited in ftp_connect(). If we are connecting to an HTTP + * proxy then the state will not be valid until after that connection is + * complete */ + + if(!ftpc || !ftp) + return CURLE_FAILED_INIT; + + *more = DOMORE_INCOMPLETE; /* default to stay in the state */ + + /* if the second connection has been set up, try to connect it fully + * to the remote host. This may not complete at this time, for several + * reasons: + * - we do EPTR and the server will not connect to our listen socket + * until we send more FTP commands + * - an SSL filter is in place and the server will not start the TLS + * handshake until we send more FTP commands + */ + if(conn->cfilter[SECONDARYSOCKET]) { + bool is_eptr = Curl_conn_is_tcp_listen(data, SECONDARYSOCKET); + result = Curl_conn_connect(data, SECONDARYSOCKET, FALSE, &connected); + if(result == CURLE_OUT_OF_MEMORY) + return result; + if(result || (!connected && !is_eptr && + !Curl_conn_is_ip_connected(data, SECONDARYSOCKET))) { + if(result && !is_eptr && (ftpc->count1 == 0)) { + *more = DOMORE_GOBACK; /* go back to DOING please */ + /* this is a EPSV connect failing, try PASV instead */ + return ftp_epsv_disable(data, ftpc, conn); + } + return result; + } + } + + if(ftpc->state) { + /* already in a state so skip the initial commands. + They are only done to kickstart the do_more state */ + result = ftp_statemach(data, ftpc, &complete); + + if(complete) + *more = DOMORE_DONE; + + /* if we got an error or if we do not wait for a data connection return + immediately */ + if(result || !ftpc->wait_data_conn) + return result; + + /* if we reach the end of the FTP state machine here, *complete will be + TRUE but so is ftpc->wait_data_conn, which says we need to wait for the + data connection and therefore we are not actually complete */ + *more = DOMORE_INCOMPLETE; + } + + if(ftp->transfer <= PPTRANSFER_INFO) { + /* a transfer is about to take place, or if not a filename was given so we + will do a SIZE on it later and then we need the right TYPE first */ + + if(ftpc->wait_data_conn) { + bool serv_conned; + + result = Curl_conn_connect(data, SECONDARYSOCKET, FALSE, &serv_conned); + if(result) + return result; /* Failed to accept data connection */ + + if(serv_conned) { + /* It looks data connection is established */ + ftpc->wait_data_conn = FALSE; + result = ftp_initiate_transfer(data, ftpc); + + if(result) + return result; + + *more = DOMORE_DONE; /* this state is now complete when the server has + connected back to us */ + } + else { + result = ftp_check_ctrl_on_data_wait(data, ftpc); + if(result) + return result; + } + } + else if(data->state.upload) { + result = ftp_nb_type(data, ftpc, ftp, (bool)data->state.prefer_ascii, + FTP_STOR_TYPE); + if(result) + return result; + + result = ftp_statemach(data, ftpc, &complete); + /* ftp_nb_type() might have skipped sending `TYPE A|I` when not + * deemed necessary and directly sent `STORE name`. If this was + * then complete, but we are still waiting on the data connection, + * the transfer has not been initiated yet. */ + *more = (!ftpc->wait_data_conn && complete) ? + DOMORE_DONE : DOMORE_INCOMPLETE; + } + else { + /* download */ + ftp->downloadsize = -1; /* unknown as of yet */ + + result = Curl_range(data); + + if(result == CURLE_OK && data->req.maxdownload >= 0) { + /* Do not check for successful transfer */ + ftpc->dont_check = TRUE; + } + + if(result) + ; + else if((data->state.list_only || !ftpc->file) && + !data->set.prequote) { + /* The specified path ends with a slash, and therefore we think this + is a directory that is requested, use LIST. Before that, we also + need to set ASCII transfer mode. */ + + /* Only if a body transfer was requested. */ + if(ftp->transfer == PPTRANSFER_BODY) { + result = ftp_nb_type(data, ftpc, ftp, TRUE, FTP_LIST_TYPE); + if(result) + return result; + } + /* otherwise fall through */ + } + else { + if(data->set.prequote && !ftpc->file) { + result = ftp_nb_type(data, ftpc, ftp, TRUE, + FTP_RETR_LIST_TYPE); + } + else { + result = ftp_nb_type(data, ftpc, ftp, (bool)data->state.prefer_ascii, + FTP_RETR_TYPE); + } + if(result) + return result; + } + + result = ftp_statemach(data, ftpc, &complete); + if(complete) + *more = DOMORE_DONE; + } + return result; + } + + /* no data to transfer */ + Curl_xfer_setup_nop(data); + + if(!ftpc->wait_data_conn) { + /* no waiting for the data connection so this is now complete */ + *more = DOMORE_DONE; + CURL_TRC_FTP(data, "[%s] DO-MORE phase ends with %d", FTP_CSTATE(ftpc), + (int)result); + } + + return result; +} + +/* call this when the DO phase has completed */ +static CURLcode ftp_dophase_done(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + bool connected) +{ + if(connected) { + domore completed; + CURLcode result = ftp_do_more(data, &completed); + + if(result) { + close_secondarysocket(data, ftpc); + return result; + } + } + + if(ftp->transfer != PPTRANSFER_BODY) + /* no data to transfer */ + Curl_xfer_setup_nop(data); + else if(!connected) + /* since we did not connect now, we want do_more to get called */ + data->conn->bits.do_more = TRUE; + + ftpc->ctl_valid = TRUE; /* seems good */ + + return CURLE_OK; +} + +static CURLcode ftp_state_port_resp(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + int ftpcode) +{ + struct connectdata *conn = data->conn; + ftpport fcmd = (ftpport)ftpc->count1; + CURLcode result = CURLE_OK; + + /* The FTP spec tells a positive response should have code 200. + Be more permissive here to tolerate deviant servers. */ + if(ftpcode / 100 != 2) { + /* the command failed */ + + if(EPRT == fcmd) { + infof(data, "disabling EPRT usage"); + conn->bits.ftp_use_eprt = FALSE; + } + fcmd++; + + if(fcmd == DONE) { + failf(data, "Failed to do PORT"); + result = CURLE_FTP_PORT_FAILED; + } + else + /* try next */ + result = ftp_state_use_port(data, ftpc, fcmd); + } + else { + infof(data, "Connect data stream actively"); + ftp_state(data, ftpc, FTP_STOP); /* end of DO phase */ + result = ftp_dophase_done(data, ftpc, ftp, FALSE); + } + + return result; +} + +/* return TRUE on error, FALSE on success */ +static bool twodigit(const char *p, int *val) +{ + if(!ISDIGIT(p[0]) || !ISDIGIT(p[1])) + return TRUE; + /* curlx_hexval() works fine here since we make sure it is decimal above */ + *val = (curlx_hexval(p[0]) * 10) + curlx_hexval(p[1]); + return FALSE; +} + +/* + * @unittest 1668 + */ +UNITTEST bool ftp_213_date(const char *p, int *year, int *month, int *day, + int *hour, int *minute, int *second); +UNITTEST bool ftp_213_date(const char *p, int *year, int *month, int *day, + int *hour, int *minute, int *second) +{ + int century; + if((strlen(p) < 14) || twodigit(&p[0], ¢ury) || twodigit(&p[2], year) || + twodigit(&p[4], month) || twodigit(&p[6], day) || + twodigit(&p[8], hour) || twodigit(&p[10], minute) || + twodigit(&p[12], second)) + return FALSE; + + *year += century * 100; + if((*month > 12) || (*day > 31) || (*hour > 23) || (*minute > 59) || + (*second > 60)) + return FALSE; + return TRUE; +} + +static CURLcode client_write_header(struct Curl_easy *data, + char *buf, size_t blen) +{ + /* Some replies from an FTP server are written to the client + * as CLIENTWRITE_HEADER, formatted as if they came from a + * HTTP conversation. + * In all protocols, CLIENTWRITE_HEADER data is only passed to + * the body write callback when data->set.include_header is set + * via CURLOPT_HEADER. + * For historic reasons, FTP never played this game and expects + * all its headers to do that always. Set that flag during the + * call to Curl_client_write() so it does the right thing. + * + * Notice that we cannot enable this flag for FTP in general, + * as an FTP transfer might involve an HTTP proxy connection and + * headers from CONNECT should not automatically be part of the + * output. */ + CURLcode result; + bool save = (bool)data->set.include_header; + data->set.include_header = TRUE; + result = Curl_client_write(data, CLIENTWRITE_HEADER, buf, blen); + data->set.include_header = save; + return result; +} + +static CURLcode ftp_state_mdtm_resp(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + int ftpcode) +{ + CURLcode result = CURLE_OK; + + switch(ftpcode) { + case 213: { + /* we got a time. Format should be: "YYYYMMDDHHMMSS[.sss]" where the + last .sss part is optional and means fractions of a second */ + int year, month, day, hour, minute, second; + struct pingpong *pp = &ftpc->pp; + const char *resp = curlx_dyn_ptr(&pp->recvbuf) + 4; + bool showtime = FALSE; + if(ftp_213_date(resp, &year, &month, &day, &hour, &minute, &second)) { + /* we have a time, reformat it */ + char timebuf[24]; + curl_msnprintf(timebuf, sizeof(timebuf), + "%04d%02d%02d %02d:%02d:%02d GMT", + year, month, day, hour, minute, second); + /* now, convert this into a time() value: */ + if(!Curl_getdate_capped(timebuf, &data->info.filetime)) + showtime = TRUE; + } + + /* If we asked for a time of the file and we actually got one as well, + we "emulate" an HTTP-style header in our output. */ + +#if defined(CURL_HAVE_DIAG) && (defined(__DJGPP__) || defined(__AMIGA__)) +#pragma GCC diagnostic push +/* 'time_t' is unsigned in MSDOS and AmigaOS. Silence: + warning: comparison of unsigned expression in '>= 0' is always true */ +#pragma GCC diagnostic ignored "-Wtype-limits" +#endif + if(data->req.no_body && ftpc->file && + data->set.get_filetime && showtime) { +#if defined(CURL_HAVE_DIAG) && (defined(__DJGPP__) || defined(__AMIGA__)) +#pragma GCC diagnostic pop +#endif + char headerbuf[128]; + int headerbuflen; + time_t filetime = data->info.filetime; + struct tm buffer; + const struct tm *tm = &buffer; + + result = curlx_gmtime(filetime, &buffer); + if(result) + return result; + + /* format: "Tue, 15 Nov 1994 12:45:26" */ + headerbuflen = + curl_msnprintf(headerbuf, sizeof(headerbuf), + "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d " + "GMT\r\n", + Curl_wkday[tm->tm_wday ? tm->tm_wday-1 : 6], + tm->tm_mday, + Curl_month[tm->tm_mon], + tm->tm_year + 1900, + tm->tm_hour, + tm->tm_min, + tm->tm_sec); + result = client_write_header(data, headerbuf, headerbuflen); + if(result) + return result; + } /* end of a ridiculous amount of conditionals */ + } + break; + default: + infof(data, "unsupported MDTM reply format"); + break; + case 550: /* 550 is used for several different problems, e.g. + "No such file or directory" or "Permission denied". + It does not mean that the file does not exist at all. */ + infof(data, "MDTM failed: file does not exist or permission problem," + " continuing"); + break; + } + + if(data->set.timecondition) { + if((data->info.filetime > 0) && (data->set.timevalue > 0)) { + switch(data->set.timecondition) { + case CURL_TIMECOND_IFMODSINCE: + default: + if(data->info.filetime <= data->set.timevalue) { + infof(data, "The requested document is not new enough"); + ftp->transfer = PPTRANSFER_NONE; /* mark to not transfer data */ + data->info.timecond = TRUE; + ftp_state(data, ftpc, FTP_STOP); + return CURLE_OK; + } + break; + case CURL_TIMECOND_IFUNMODSINCE: + if(data->info.filetime > data->set.timevalue) { + infof(data, "The requested document is not old enough"); + ftp->transfer = PPTRANSFER_NONE; /* mark to not transfer data */ + data->info.timecond = TRUE; + ftp_state(data, ftpc, FTP_STOP); + return CURLE_OK; + } + break; + } /* switch */ + } + else { + infof(data, "Skipping time comparison"); + } + } + + if(!result) + result = ftp_state_type(data, ftpc, ftp); + + return result; +} + +static CURLcode ftp_state_type_resp(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + int ftpcode, + ftpstate instate) +{ + CURLcode result = CURLE_OK; + + if(ftpcode / 100 != 2) { + /* "sasserftpd" and "(u)r(x)bot ftpd" both responds with 226 after a + successful 'TYPE I'. While that is not as RFC959 says, it is still a + positive response code and we allow that. */ + failf(data, "Could not set desired mode"); + return CURLE_FTP_COULDNT_SET_TYPE; + } + if(ftpcode != 200) + infof(data, "Got a %03d response code instead of the assumed 200", + ftpcode); + + if(instate == FTP_TYPE) + result = ftp_state_size(data, ftpc, ftp); + else if(instate == FTP_LIST_TYPE) + result = ftp_state_list(data, ftpc, ftp); + else if(instate == FTP_RETR_TYPE) + result = ftp_state_retr_prequote(data, ftpc, ftp); + else if(instate == FTP_STOR_TYPE) + result = ftp_state_stor_prequote(data, ftpc, ftp); + else if(instate == FTP_RETR_LIST_TYPE) + result = ftp_state_list_prequote(data, ftpc, ftp); + + return result; +} + +static CURLcode ftp_state_size_resp(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + int ftpcode, + ftpstate instate) +{ + CURLcode result = CURLE_OK; + curl_off_t filesize = -1; + const char *buf = curlx_dyn_ptr(&ftpc->pp.recvbuf); + size_t len = ftpc->pp.nfinal; + + /* get the size from the ascii string: */ + if(ftpcode == 213) { + /* To allow servers to prepend "rubbish" in the response string, we scan + for all the digits at the end of the response and parse only those as a + number. */ + const char *start = &buf[4]; + const char *fdigit = memchr(start, '\r', len - 4); + if(fdigit) { + fdigit--; + if(*fdigit == '\n') + fdigit--; + while(ISDIGIT(fdigit[-1]) && (fdigit > start)) + fdigit--; + } + else + fdigit = start; + if(curlx_str_number(&fdigit, &filesize, CURL_OFF_T_MAX)) + filesize = -1; /* size remain unknown */ + } + else if(ftpcode == 550) { /* "No such file or directory" */ + /* allow a SIZE failure for (resumed) uploads, when probing what command + to use */ + if(instate != FTP_STOR_SIZE) { + failf(data, "The file does not exist"); + return CURLE_REMOTE_FILE_NOT_FOUND; + } + } + + if(instate == FTP_SIZE) { + if(filesize != -1) { + char clbuf[128]; + int clbuflen = curl_msnprintf(clbuf, sizeof(clbuf), + "Content-Length: %" FMT_OFF_T "\r\n", + filesize); + result = client_write_header(data, clbuf, clbuflen); + if(result) + return result; + } + Curl_pgrsSetDownloadSize(data, filesize); + result = ftp_state_rest(data, ftpc, ftp); + } + else if(instate == FTP_RETR_SIZE) { + Curl_pgrsSetDownloadSize(data, filesize); + result = ftp_state_retr(data, ftpc, ftp, filesize); + } + else if(instate == FTP_STOR_SIZE) { + data->state.resume_from = filesize; + result = ftp_state_ul_setup(data, ftpc, ftp, TRUE); + } + + return result; +} + +static CURLcode ftp_state_rest_resp(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + int ftpcode, + ftpstate instate) +{ + CURLcode result = CURLE_OK; + + switch(instate) { + case FTP_REST: + default: + if(ftpcode == 350) { + char buffer[24] = { "Accept-ranges: bytes\r\n" }; + result = client_write_header(data, buffer, strlen(buffer)); + if(result) + return result; + } + result = ftp_state_prepare_transfer(data, ftpc, ftp); + break; + + case FTP_RETR_REST: + if(ftpcode != 350) { + failf(data, "Could not use REST"); + result = CURLE_FTP_COULDNT_USE_REST; + } + else { + result = Curl_pp_sendf(data, &ftpc->pp, "RETR %s", ftpc->file); + if(!result) + ftp_state(data, ftpc, FTP_RETR); + } + break; + } + + return result; +} + +static CURLcode ftp_state_stor_resp(struct Curl_easy *data, + struct ftp_conn *ftpc, + int ftpcode) +{ + CURLcode result = CURLE_OK; + + if(ftpcode >= 400) { + failf(data, "Failed FTP upload: %0d", ftpcode); + ftp_state(data, ftpc, FTP_STOP); + return CURLE_UPLOAD_FAILED; + } + + /* PORT means we are now awaiting the server to connect to us. */ + if(data->set.ftp_use_port) { + bool connected; + + ftp_state(data, ftpc, FTP_STOP); /* no longer in STOR state */ + + result = Curl_conn_connect(data, SECONDARYSOCKET, FALSE, &connected); + if(result) + return result; + + if(!connected) { + infof(data, "Data conn was not available immediately"); + ftpc->wait_data_conn = TRUE; + return ftp_check_ctrl_on_data_wait(data, ftpc); + } + ftpc->wait_data_conn = FALSE; + } + return ftp_initiate_transfer(data, ftpc); +} + +/* for LIST and RETR responses */ +static CURLcode ftp_state_get_resp(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + int ftpcode, + ftpstate instate) +{ + CURLcode result = CURLE_OK; + + if((ftpcode == 150) || (ftpcode == 125)) { + + /* + A; + 150 Opening BINARY mode data connection for /etc/passwd (2241 + bytes). (ok, the file is being transferred) + + B: + 150 Opening ASCII mode data connection for /bin/ls + + C: + 150 ASCII data connection for /bin/ls (137.167.104.91,37445) (0 bytes). + + D: + 150 Opening ASCII mode data connection for [file] (0.0.0.0,0) (545 bytes) + + E: + 125 Data connection already open; Transfer starting. */ + + data->req.size = -1; /* default unknown size */ + + /* + * It appears that there are FTP-servers that return size 0 for files when + * SIZE is used on the file while being in BINARY mode. To work around + * that (stupid) behavior, we attempt to parse the RETR response even if + * the SIZE returned size zero. + * + * Debugging help from Salvatore Sorrentino on February 26, 2003. + */ + + if((instate != FTP_LIST) && + !data->state.prefer_ascii && + !data->set.ignorecl && + (ftp->downloadsize < 1)) { + /* + * It seems directory listings either do not show the size or often uses + * size 0 anyway. ASCII transfers may cause that the transferred amount + * of data is not the same as this line tells, why using this number in + * those cases only confuses us. + * + * Example D above makes this parsing a little tricky */ + size_t len = curlx_dyn_len(&ftpc->pp.recvbuf); + if(len >= 7) { /* "1 bytes" is 7 characters */ + size_t i; + for(i = 0; i < len - 7; i++) { + curl_off_t what; + const char *buf = curlx_dyn_ptr(&ftpc->pp.recvbuf); + const char *c = &buf[i]; + if(!curlx_str_number(&c, &what, CURL_OFF_T_MAX) && + !curlx_str_single(&c, ' ') && + !strncmp(c, "bytes", 5)) { + data->req.size = what; + break; + } + } + } + } + else if(ftp->downloadsize > -1) + data->req.size = ftp->downloadsize; + + if(data->req.size > data->req.maxdownload && data->req.maxdownload > 0) + data->req.size = data->req.maxdownload; + else if((instate != FTP_LIST) && data->state.prefer_ascii) + data->req.size = -1; /* for servers that understate ASCII mode file + size */ + + infof(data, "Maxdownload = %" FMT_OFF_T, data->req.maxdownload); + + if(instate != FTP_LIST) + infof(data, "Getting file with size: %" FMT_OFF_T, data->req.size); + + if(data->set.ftp_use_port) { + bool connected; + + result = Curl_conn_connect(data, SECONDARYSOCKET, FALSE, &connected); + if(result) + return result; + + if(!connected) { + infof(data, "Data conn was not available immediately"); + ftp_state(data, ftpc, FTP_STOP); + ftpc->wait_data_conn = TRUE; + return ftp_check_ctrl_on_data_wait(data, ftpc); + } + ftpc->wait_data_conn = FALSE; + } + return ftp_initiate_transfer(data, ftpc); + } + else { + if((instate == FTP_LIST) && (ftpcode == 450)) { + /* no matching files in the directory listing */ + ftp->transfer = PPTRANSFER_NONE; /* do not download anything */ + ftp_state(data, ftpc, FTP_STOP); /* this phase is over */ + } + else { + failf(data, "RETR response: %03d", ftpcode); + return instate == FTP_RETR && ftpcode == 550 ? + CURLE_REMOTE_FILE_NOT_FOUND : + CURLE_FTP_COULDNT_RETR_FILE; + } + } + + return result; +} + +/* after USER, PASS and ACCT */ +static CURLcode ftp_state_loggedin(struct Curl_easy *data, + struct ftp_conn *ftpc) +{ + CURLcode result = CURLE_OK; + + if(Curl_conn_is_ssl(data->conn, FIRSTSOCKET)) { + /* PBSZ = PROTECTION BUFFER SIZE. + + The 'draft-murray-auth-ftp-ssl' (draft 12, page 7) says: + + Specifically, the PROT command MUST be preceded by a PBSZ + command and a PBSZ command MUST be preceded by a successful + security data exchange (the TLS negotiation in this case) + + ... (and on page 8): + + Thus the PBSZ command must still be issued, but must have a + parameter of '0' to indicate that no buffering is taking place + and the data connection should not be encapsulated. + */ + result = Curl_pp_sendf(data, &ftpc->pp, "PBSZ %d", 0); + if(!result) + ftp_state(data, ftpc, FTP_PBSZ); + } + else { + result = ftp_state_pwd(data, ftpc); + } + return result; +} + +/* A value that becomes part of an FTP control command must not carry a + control byte: a CR or LF would end the command line and let a second + command be smuggled onto the control connection. */ +static bool ftp_has_ctrl(const char *string) +{ + const unsigned char *s = (const unsigned char *)string; + while(*s) { + if(*s < 0x20) + return TRUE; + s++; + } + return FALSE; +} + +/* for USER and PASS responses */ +static CURLcode ftp_state_user_resp(struct Curl_easy *data, + struct ftp_conn *ftpc, + int ftpcode) +{ + CURLcode result = CURLE_OK; + + /* some need password anyway, and others return 2xx ignored */ + if((ftpcode == 331) && (ftpc->state == FTP_USER)) { + /* 331 Password required for ... + (the server requires to send the user's password too) */ + result = Curl_pp_sendf(data, &ftpc->pp, "PASS %s", + Curl_creds_passwd(data->conn->creds)); + if(!result) + ftp_state(data, ftpc, FTP_PASS); + } + else if(ftpcode / 100 == 2) { + /* 230 User ... logged in. + (the user logged in with or without password) */ + result = ftp_state_loggedin(data, ftpc); + } + else if(ftpcode == 332) { + const char *account = CURL_EASY_STR(data, STRING_FTP_ACCOUNT); + if(!account) { + failf(data, "ACCT requested but none available"); + result = CURLE_LOGIN_DENIED; + } + else if(ftp_has_ctrl(account)) { + failf(data, "Control byte in FTP account"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + } + else { + result = Curl_pp_sendf(data, &ftpc->pp, "ACCT %s", account); + if(!result) + ftp_state(data, ftpc, FTP_ACCT); + } + } + else { + /* All other response codes, like: + + 530 User ... access denied + (the server denies to log the specified user) */ + + const char *alt = CURL_EASY_STR(data, STRING_FTP_ALTERNATIVE_TO_USER); + if(alt && !ftpc->ftp_trying_alternative) { + /* Ok, USER failed. Let's try the supplied command. */ + if(ftp_has_ctrl(alt)) { + failf(data, "Control byte in FTP alternative-to-user command"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + } + else { + result = Curl_pp_sendf(data, &ftpc->pp, "%s", alt); + if(!result) { + ftpc->ftp_trying_alternative = TRUE; + ftp_state(data, ftpc, FTP_USER); + } + } + } + else { + failf(data, "Access denied: %03d", ftpcode); + result = CURLE_LOGIN_DENIED; + } + } + return result; +} + +/* for ACCT response */ +static CURLcode ftp_state_acct_resp(struct Curl_easy *data, + struct ftp_conn *ftpc, + int ftpcode) +{ + CURLcode result = CURLE_OK; + if(ftpcode != 230) { + failf(data, "ACCT rejected by server: %03d", ftpcode); + result = CURLE_FTP_WEIRD_PASS_REPLY; /* FIX */ + } + else + result = ftp_state_loggedin(data, ftpc); + + return result; +} + +static CURLcode ftp_pwd_resp(struct Curl_easy *data, + struct ftp_conn *ftpc, + int ftpcode) +{ + struct pingpong *pp = &ftpc->pp; + CURLcode result; + + if(ftpcode == 257) { + const char *ptr = curlx_dyn_ptr(&pp->recvbuf) + 4; /* start on the first + letter */ + bool entry_extracted = FALSE; + struct dynbuf out; + curlx_dyn_init(&out, 1000); + + /* Reply format is like + 257<space>[rubbish]"<directory-name>"<space><commentary> and the + RFC959 says + + The directory name can contain any character; embedded + double-quotes should be escaped by double-quotes (the + "quote-doubling" convention). + */ + + /* scan for the first double-quote for non-standard responses */ + while(*ptr != '\n' && *ptr != '\0' && *ptr != '"') + ptr++; + + if('\"' == *ptr) { + /* it started good */ + for(ptr++; *ptr; ptr++) { + if('\"' == *ptr) { + if('\"' == ptr[1]) { + /* "quote-doubling" */ + result = curlx_dyn_addn(&out, &ptr[1], 1); + ptr++; + } + else { + /* end of path */ + if(curlx_dyn_len(&out)) + entry_extracted = TRUE; + break; /* get out of this loop */ + } + } + else { + if(ISCNTRL(*ptr)) { + /* control characters have no business in a path */ + curlx_dyn_free(&out); + return CURLE_WEIRD_SERVER_REPLY; + } + result = curlx_dyn_addn(&out, ptr, 1); + } + if(result) { + curlx_dyn_free(&out); + return result; + } + } + } + if(entry_extracted) { + /* If the path name does not look like an absolute path (i.e.: it + does not start with a '/'), we probably need some server-dependent + adjustments. For example, this is the case when connecting to + an OS400 FTP server: this server supports two name syntaxes, + the default one being incompatible with standard paths. In + addition, this server switches automatically to the regular path + syntax when one is encountered in a command: this results in + having an entrypath in the wrong syntax when later used in CWD. + The method used here is to check the server OS: we do it only + if the path name looks strange to minimize overhead on other + systems. */ + char *dir = curlx_dyn_ptr(&out); + + if(!ftpc->server_os && dir[0] != '/') { + result = Curl_pp_sendf(data, &ftpc->pp, "%s", "SYST"); + if(result) { + curlx_dyn_free(&out); + return result; + } + } + + curlx_free(ftpc->entrypath); + ftpc->entrypath = dir; /* remember this */ + infof(data, "Entry path is '%s'", ftpc->entrypath); + /* also save it where getinfo can access it: */ + curlx_free(data->state.most_recent_ftp_entrypath); + data->state.most_recent_ftp_entrypath = curlx_strdup(ftpc->entrypath); + if(!data->state.most_recent_ftp_entrypath) + return CURLE_OUT_OF_MEMORY; + + if(!ftpc->server_os && dir[0] != '/') { + ftp_state(data, ftpc, FTP_SYST); + return CURLE_OK; + } + } + else { + /* could not get the path */ + curlx_dyn_free(&out); + infof(data, "Failed to figure out path"); + } + } + ftp_state(data, ftpc, FTP_STOP); /* we are done with CONNECT phase! */ + CURL_TRC_FTP(data, "[%s] protocol connect phase DONE", FTP_CSTATE(ftpc)); + return CURLE_OK; +} + +static const char * const ftpauth[] = { "SSL", "TLS" }; + +static CURLcode ftp_wait_resp(struct Curl_easy *data, + struct connectdata *conn, + struct ftp_conn *ftpc, + int ftpcode) +{ + CURLcode result = CURLE_OK; + if(ftpcode == 230) { + /* 230 User logged in - already! Take as 220 if TLS required. */ + if(ftpc->use_ssl <= CURLUSESSL_TRY || + Curl_conn_is_ssl(conn, FIRSTSOCKET)) + return ftp_state_user_resp(data, ftpc, ftpcode); + } + else if(ftpcode != 220) { + failf(data, "Got a %03d ftp-server response when 220 was expected", + ftpcode); + return CURLE_WEIRD_SERVER_REPLY; + } + + if(ftpc->use_ssl && !Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + /* We do not have an SSL/TLS control connection yet, but FTPS is + requested. Try an FTPS connection now */ + + ftpc->count3 = 0; + switch((long)data->set.ftpsslauth) { + case CURLFTPAUTH_DEFAULT: + case CURLFTPAUTH_SSL: + ftpc->count2 = 1; /* add one to get next */ + ftpc->count1 = 0; + break; + case CURLFTPAUTH_TLS: + ftpc->count2 = -1; /* subtract one to get next */ + ftpc->count1 = 1; + break; + default: + failf(data, "unsupported parameter to CURLOPT_FTPSSLAUTH: %d", + (int)data->set.ftpsslauth); + return CURLE_UNKNOWN_OPTION; /* we do not know what to do */ + } + result = Curl_pp_sendf(data, &ftpc->pp, "AUTH %s", ftpauth[ftpc->count1]); + if(!result) + ftp_state(data, ftpc, FTP_AUTH); + } + else + result = ftp_state_user(data, ftpc, conn); + return result; +} + +static CURLcode ftp_pp_statemachine(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result; + int ftpcode; + struct ftp_conn *ftpc = Curl_conn_meta_get(conn, CURL_META_FTP_CONN); + struct FTP *ftp = Curl_meta_get(data, CURL_META_FTP_EASY); + struct pingpong *pp; + size_t nread = 0; + + if(!ftpc || !ftp) + return CURLE_FAILED_INIT; + pp = &ftpc->pp; + if(pp->sendleft) + return Curl_pp_flushsend(data, pp); + + result = ftp_readresp(data, ftpc, FIRSTSOCKET, pp, &ftpcode, &nread); + if(result || !ftpcode) + return result; + + /* we have now received a full FTP server response */ + switch(ftpc->state) { + case FTP_WAIT220: + result = ftp_wait_resp(data, conn, ftpc, ftpcode); + break; + + case FTP_AUTH: + /* we have gotten the response to a previous AUTH command */ + + if(pp->overflow) + return CURLE_WEIRD_SERVER_REPLY; /* Forbid pipelining in response. */ + + /* RFC2228 (page 5) says: + * + * If the server is willing to accept the named security mechanism, + * and does not require any security data, it must respond with + * reply code 234/334. + */ + + if((ftpcode == 234) || (ftpcode == 334)) { + /* this was BLOCKING, keep it so for now */ + bool done; + if(!Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + result = Curl_ssl_cfilter_add( + data, Curl_conn_get_origin(conn, FIRSTSOCKET), conn, FIRSTSOCKET); + if(result) { + /* we failed and bail out */ + return CURLE_USE_SSL_FAILED; + } + } + /* BLOCKING */ + result = Curl_conn_connect(data, FIRSTSOCKET, TRUE, &done); + if(!result) { + conn->bits.ftp_use_data_ssl = FALSE; /* clear-text data */ + result = ftp_state_user(data, ftpc, conn); + } + } + else if(ftpc->count3 < 1) { + ftpc->count3++; + ftpc->count1 += ftpc->count2; /* get next attempt */ + result = Curl_pp_sendf(data, &ftpc->pp, "AUTH %s", + ftpauth[ftpc->count1]); + /* remain in this same state */ + } + else { + if(ftpc->use_ssl > CURLUSESSL_TRY) + /* we failed and CURLUSESSL_CONTROL or CURLUSESSL_ALL is set */ + result = CURLE_USE_SSL_FAILED; + else + /* ignore the failure and continue */ + result = ftp_state_user(data, ftpc, conn); + } + break; + + case FTP_USER: + case FTP_PASS: + result = ftp_state_user_resp(data, ftpc, ftpcode); + break; + + case FTP_ACCT: + result = ftp_state_acct_resp(data, ftpc, ftpcode); + break; + + case FTP_PBSZ: + result = + Curl_pp_sendf(data, &ftpc->pp, "PROT %c", + ftpc->use_ssl == CURLUSESSL_CONTROL ? 'C' : 'P'); + if(!result) + ftp_state(data, ftpc, FTP_PROT); + break; + + case FTP_PROT: + if(ftpcode / 100 == 2) + /* We have enabled SSL for the data connection! */ + conn->bits.ftp_use_data_ssl = (ftpc->use_ssl != CURLUSESSL_CONTROL); + /* FTP servers typically responds with 500 if they decide to reject + our 'P' request */ + else if(ftpc->use_ssl > CURLUSESSL_CONTROL) + /* we failed and bails out */ + return CURLE_USE_SSL_FAILED; + + if(data->set.ftp_ccc) { + /* CCC - Clear Command Channel + */ + result = Curl_pp_sendf(data, &ftpc->pp, "%s", "CCC"); + if(!result) + ftp_state(data, ftpc, FTP_CCC); + } + else + result = ftp_state_pwd(data, ftpc); + break; + + case FTP_CCC: + if(ftpcode < 500) { + /* First shut down the SSL layer (note: this call will block) */ + /* This has only been tested on the proftpd server, and the mod_tls + * code sends a close notify alert without waiting for a close notify + * alert in response. Thus we wait for a close notify alert from the + * server, but we do not send one. Let's hope other servers do + * the same... */ + result = Curl_ssl_cfilter_remove(data, FIRSTSOCKET, + (data->set.ftp_ccc == + (unsigned char)CURLFTPSSL_CCC_ACTIVE)); + if(result) + failf(data, "Failed to clear the command channel (CCC)"); + } + if(!result) + /* Then continue as normal */ + result = ftp_state_pwd(data, ftpc); + break; + + case FTP_PWD: + result = ftp_pwd_resp(data, ftpc, ftpcode); + break; + + case FTP_SYST: + if(ftpcode == 215) { + const char *ptr = curlx_dyn_ptr(&pp->recvbuf) + 4; /* start on the first + letter */ + const char *start; + char *os; + + /* Reply format is like + 215<space><OS-name><space><commentary> + */ + while(*ptr == ' ') + ptr++; + for(start = ptr; *ptr && *ptr != ' '; ptr++) + ; + os = curlx_memdup0(start, ptr - start); + if(!os) + return CURLE_OUT_OF_MEMORY; + + /* Check for special servers here. */ + if(curl_strequal(os, "OS/400")) { + /* Force OS400 name format 1. */ + result = Curl_pp_sendf(data, &ftpc->pp, "%s", "SITE NAMEFMT 1"); + if(result) { + curlx_free(os); + return result; + } + /* remember target server OS */ + curlx_free(ftpc->server_os); + ftpc->server_os = os; + ftp_state(data, ftpc, FTP_NAMEFMT); + break; + } + /* Nothing special for the target server. */ + /* remember target server OS */ + curlx_free(ftpc->server_os); + ftpc->server_os = os; + } + else { + /* Cannot identify server OS. Continue anyway and cross fingers. */ + } + + ftp_state(data, ftpc, FTP_STOP); /* we are done with CONNECT phase! */ + CURL_TRC_FTP(data, "[%s] protocol connect phase DONE", FTP_CSTATE(ftpc)); + break; + + case FTP_NAMEFMT: + if(ftpcode == 250) { + /* Name format change successful: reload initial path. */ + ftp_state_pwd(data, ftpc); + break; + } + + ftp_state(data, ftpc, FTP_STOP); /* we are done with CONNECT phase! */ + CURL_TRC_FTP(data, "[%s] protocol connect phase DONE", FTP_CSTATE(ftpc)); + break; + + case FTP_QUOTE: + case FTP_POSTQUOTE: + case FTP_RETR_PREQUOTE: + case FTP_STOR_PREQUOTE: + case FTP_LIST_PREQUOTE: + if((ftpcode >= 400) && !ftpc->count2) { + /* failure response code, and not allowed to fail */ + failf(data, "QUOT command failed with %03d", ftpcode); + result = CURLE_QUOTE_ERROR; + } + else + result = ftp_state_quote(data, ftpc, ftp, FALSE, ftpc->state); + break; + + case FTP_CWD: + if(ftpcode / 100 != 2) { + /* failure to CWD there */ + if(data->set.ftp_create_missing_dirs && + ftpc->cwdcount && !ftpc->count2) { + /* try making it */ + ftpc->count2++; /* counter to prevent CWD-MKD loops */ + + /* count3 is set to allow MKD to fail once per dir. In the case when + CWD fails and then MKD fails (due to another session raced it to + create the dir) this then allows for a second try to CWD to it. */ + ftpc->count3 = (data->set.ftp_create_missing_dirs == 2) ? 1 : 0; + + result = Curl_pp_sendf(data, &ftpc->pp, "MKD %.*s", + pathlen(ftpc, ftpc->cwdcount - 1), + pathpiece(ftpc, ftpc->cwdcount - 1)); + if(!result) + ftp_state(data, ftpc, FTP_MKD); + } + else { + /* return failure */ + failf(data, "Server denied you to change to the given directory"); + ftpc->cwdfail = TRUE; /* do not remember this path as we failed + to enter it */ + result = CURLE_REMOTE_ACCESS_DENIED; + } + } + else { + /* success */ + ftpc->count2 = 0; + if(ftpc->cwdcount >= ftpc->dirdepth) + result = ftp_state_mdtm(data, ftpc, ftp); + else { + ftpc->cwdcount++; + /* send next CWD */ + result = Curl_pp_sendf(data, &ftpc->pp, "CWD %.*s", + pathlen(ftpc, ftpc->cwdcount - 1), + pathpiece(ftpc, ftpc->cwdcount - 1)); + } + } + break; + + case FTP_MKD: + if((ftpcode / 100 != 2) && !ftpc->count3--) { + /* failure to MKD the directory */ + failf(data, "Failed to MKD dir: %03d", ftpcode); + result = CURLE_REMOTE_ACCESS_DENIED; + } + else { + ftp_state(data, ftpc, FTP_CWD); + /* send CWD */ + result = Curl_pp_sendf(data, &ftpc->pp, "CWD %.*s", + pathlen(ftpc, ftpc->cwdcount - 1), + pathpiece(ftpc, ftpc->cwdcount - 1)); + } + break; + + case FTP_MDTM: + result = ftp_state_mdtm_resp(data, ftpc, ftp, ftpcode); + break; + + case FTP_TYPE: + case FTP_LIST_TYPE: + case FTP_RETR_TYPE: + case FTP_STOR_TYPE: + case FTP_RETR_LIST_TYPE: + result = ftp_state_type_resp(data, ftpc, ftp, ftpcode, ftpc->state); + break; + + case FTP_SIZE: + case FTP_RETR_SIZE: + case FTP_STOR_SIZE: + result = ftp_state_size_resp(data, ftpc, ftp, ftpcode, ftpc->state); + break; + + case FTP_REST: + case FTP_RETR_REST: + result = ftp_state_rest_resp(data, ftpc, ftp, ftpcode, ftpc->state); + break; + + case FTP_PRET: + if(ftpcode != 200) { + /* there only is this one standard OK return code. */ + failf(data, "PRET command not accepted: %03d", ftpcode); + return CURLE_FTP_PRET_FAILED; + } + result = ftp_state_use_pasv(data, ftpc, conn); + break; + + case FTP_PASV: + result = ftp_state_pasv_resp(data, ftpc, ftpcode); + break; + + case FTP_PORT: + result = ftp_state_port_resp(data, ftpc, ftp, ftpcode); + break; + + case FTP_LIST: + case FTP_RETR: + result = ftp_state_get_resp(data, ftpc, ftp, ftpcode, ftpc->state); + break; + + case FTP_STOR: + result = ftp_state_stor_resp(data, ftpc, ftpcode); + break; + + case FTP_QUIT: + default: + /* internal error */ + ftp_state(data, ftpc, FTP_STOP); + break; + } + + return result; +} + +/* called repeatedly until done from multi.c */ +static CURLcode ftp_multi_statemach(struct Curl_easy *data, + bool *done) +{ + struct ftp_conn *ftpc = Curl_conn_meta_get(data->conn, CURL_META_FTP_CONN); + return ftpc ? ftp_statemach(data, ftpc, done) : CURLE_FAILED_INIT; +} + +static CURLcode ftp_block_statemach(struct Curl_easy *data, + struct ftp_conn *ftpc) +{ + struct pingpong *pp = &ftpc->pp; + CURLcode result = CURLE_OK; + + while(ftpc->state != FTP_STOP) { + if(ftpc->shutdown) + CURL_TRC_FTP(data, "in shutdown, waiting for server response"); + result = Curl_pp_statemach(data, pp, TRUE, TRUE /* disconnecting */); + if(result) + break; + } + + return result; +} + +/* + * ftp_connect() should do everything that is to be considered a part of + * the connection phase. + * + * The variable 'done' points to will be TRUE if the protocol-layer connect + * phase is done when this function returns, or FALSE if not. + * + */ +static CURLcode ftp_connect(struct Curl_easy *data, + bool *done) /* see description above */ +{ + CURLcode result; + struct connectdata *conn = data->conn; + struct ftp_conn *ftpc = Curl_conn_meta_get(data->conn, CURL_META_FTP_CONN); + struct pingpong *pp; + + *done = FALSE; /* default to not done yet */ + if(!ftpc) + return CURLE_FAILED_INIT; + pp = &ftpc->pp; + PINGPONG_SETUP(pp, ftp_pp_statemachine, ftp_endofresp); + + if(Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + /* BLOCKING */ + result = Curl_conn_connect(data, FIRSTSOCKET, TRUE, done); + if(result) + return result; + } + + Curl_pp_init(pp, Curl_pgrs_now(data)); /* once per transfer */ + + /* When we connect, we start in the state where we await the 220 + response */ + ftp_state(data, ftpc, FTP_WAIT220); + + result = ftp_statemach(data, ftpc, done); + + return result; +} + +/*********************************************************************** + * + * ftp_sendquote() + * + * Where a 'quote' means a list of custom commands to send to the server. + * The quote list is passed as an argument. + * + * BLOCKING + */ +static CURLcode ftp_sendquote(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct curl_slist *quote) +{ + struct curl_slist *item; + struct pingpong *pp = &ftpc->pp; + + item = quote; + while(item) { + if(item->data) { + size_t nread; + const char *cmd = item->data; + bool acceptfail = FALSE; + CURLcode result; + int ftpcode = 0; + + /* if a command starts with an asterisk, which a legal FTP command never + can, the command will be allowed to fail without it causing any + aborts or cancels etc. It will cause libcurl to act as if the command + is successful, whatever the server responds. */ + + if(cmd[0] == '*') { + cmd++; + acceptfail = TRUE; + } + + result = Curl_pp_sendf(data, &ftpc->pp, "%s", cmd); + if(!result) { + pp->response = *Curl_pgrs_now(data); /* timeout relative now */ + result = getftpresponse(data, &nread, &ftpcode); + } + if(result) + return result; + + if(!acceptfail && (ftpcode >= 400)) { + failf(data, "QUOT string not accepted: %s", cmd); + return CURLE_QUOTE_ERROR; + } + } + + item = item->next; + } + + return CURLE_OK; +} + +static CURLcode ftp_done_status(struct Curl_easy *data, + struct ftp_conn *ftpc, CURLcode status, + bool premature) +{ + switch(status) { + case CURLE_BAD_DOWNLOAD_RESUME: + case CURLE_FTP_WEIRD_PASV_REPLY: + case CURLE_FTP_PORT_FAILED: + case CURLE_FTP_ACCEPT_FAILED: + case CURLE_FTP_ACCEPT_TIMEOUT: + case CURLE_FTP_COULDNT_SET_TYPE: + case CURLE_FTP_COULDNT_RETR_FILE: + case CURLE_PARTIAL_FILE: + case CURLE_UPLOAD_FAILED: + case CURLE_REMOTE_ACCESS_DENIED: + case CURLE_FILESIZE_EXCEEDED: + case CURLE_REMOTE_FILE_NOT_FOUND: + case CURLE_WRITE_ERROR: + /* the connection stays alive fine even though this happened */ + case CURLE_OK: /* does not affect the control connection's status */ + if(!premature) + break; + + /* until we cope better with prematurely ended requests, let them + * fallback as if in complete failure */ + FALLTHROUGH(); + default: /* by default, an error means the control connection is + wedged and should not be used anymore */ + ftpc->ctl_valid = FALSE; + ftpc->cwdfail = TRUE; /* set this TRUE to prevent us to remember the + current path, as this connection is going */ + CURL_TRC_FTP(data, "FTP ended with bad error code"); + connclose(data->conn); + return status; /* use the already set error code */ + } + return CURLE_OK; +} + +static void ftp_done_wildcard(struct Curl_easy *data, struct ftp_conn *ftpc) +{ + if(data->state.wildcardmatch) { + if(data->set.chunk_end && ftpc->file) { + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_chunk_end); + data->set.chunk_end(data->set.wildcardptr); + CURL_CBAPI_END(&guard); + freedirs(ftpc); + } + ftpc->known_filesize = -1; + } +} + +static void ftp_done_path(struct Curl_easy *data, struct ftp_conn *ftpc, + CURLcode result) +{ + struct connectdata *conn = data->conn; + if(result) { + /* We can limp along anyway (and should try to since we may already be in + * the error path) */ + ftpc->ctl_valid = FALSE; /* mark control connection as bad */ + connclose(conn); /* mark for connection closure */ + curlx_safefree(ftpc->prevpath); /* no path remembering */ + } + else { /* remember working directory for connection reuse */ + const char *rawPath = ftpc->rawpath; + if(rawPath) { + if((data->set.ftp_filemethod == FTPFILE_NOCWD) && (rawPath[0] == '/')) + ; /* full path => no CWDs happened => keep ftpc->prevpath */ + else { + size_t pathLen = strlen(ftpc->rawpath); + + curlx_free(ftpc->prevpath); + + if(!ftpc->cwdfail) { + if(data->set.ftp_filemethod == FTPFILE_NOCWD) + pathLen = 0; /* relative path => working directory is FTP home */ + else + /* file is URL-decoded */ + pathLen -= ftpc->file ? strlen(ftpc->file) : 0; + ftpc->prevpath = curlx_memdup0(rawPath, pathLen); + } + else + ftpc->prevpath = NULL; /* no path */ + } + } + if(ftpc->prevpath) + infof(data, "Remembering we are in directory \"%s\"", ftpc->prevpath); + } +} + +static CURLcode ftp_done_secondary_socket(struct Curl_easy *data, + struct ftp_conn *ftpc, + CURLcode result) +{ + struct connectdata *conn = data->conn; + if(Curl_conn_is_setup(conn, SECONDARYSOCKET)) { + if(!result && ftpc->dont_check && data->req.maxdownload > 0) { + /* partial download completed */ + result = Curl_pp_sendf(data, &ftpc->pp, "%s", "ABOR"); + if(result) { + failf(data, "Failure sending ABOR command: %s", + curl_easy_strerror(result)); + ftpc->ctl_valid = FALSE; /* mark control connection as bad */ + connclose(conn); /* connection closure */ + } + } + + close_secondarysocket(data, ftpc); + } + return result; +} + +static CURLcode ftp_done_control_reply(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, CURLcode result, + bool premature) +{ + struct connectdata *conn = data->conn; + size_t nread; + int ftpcode; + + if(!result && (ftp->transfer == PPTRANSFER_BODY) && ftpc->ctl_valid && + ftpc->pp.pending_resp && !premature) { + /* + * Let's see what the server says about the transfer we performed, but + * lower the timeout as sometimes this connection has died while the data + * has been transferred. This happens when doing through NATs etc that + * abandon old silent connections. + */ + ftpc->pp.response = *Curl_pgrs_now(data); /* timeout relative now */ + result = getftpresponse(data, &nread, &ftpcode); + + if(!nread && (result == CURLE_OPERATION_TIMEDOUT)) { + failf(data, "control connection looks dead"); + ftpc->ctl_valid = FALSE; /* mark control connection as bad */ + connclose(conn); /* close */ + } + + if(result) + return result; + + if(ftpc->dont_check && data->req.maxdownload > 0) { + /* we have sent ABOR and there is no reliable way to check if it was + * successful or not; we have to close the connection now */ + infof(data, "partial download completed, closing connection"); + connclose(conn); + return result; + } + + if(!ftpc->dont_check) { + /* 226 Transfer complete, 250 Requested file action okay, completed. */ + switch(ftpcode) { + case 226: + case 250: + break; + case 552: + failf(data, "Exceeded storage allocation"); + result = CURLE_REMOTE_DISK_FULL; + break; + default: + failf(data, "server did not report OK, got %d", ftpcode); + result = CURLE_PARTIAL_FILE; + break; + } + } + } + return result; +} + +static CURLcode ftp_done_check_partial(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, CURLcode result, + bool premature) +{ + if(result || premature) + /* the response code from the transfer showed an error already so no + use checking further */ + ; + else if(data->state.upload) { + if((ftp->transfer == PPTRANSFER_BODY) && + (data->state.infilesize != -1) && /* upload with known size */ + ((!data->set.crlf && !data->state.prefer_ascii && /* no conversion */ + (data->state.infilesize != data->req.writebytecount)) || + ((data->set.crlf || data->state.prefer_ascii) && /* maybe CRLF conv */ + (data->state.infilesize > data->req.writebytecount)) + )) { + failf(data, "Uploaded unaligned file size (%" FMT_OFF_T + " out of %" FMT_OFF_T " bytes)", + data->req.writebytecount, data->state.infilesize); + result = CURLE_PARTIAL_FILE; + } + } + else { + if((data->req.size != -1) && + (data->req.size != data->req.bytecount) && + (data->req.maxdownload != data->req.bytecount)) { + failf(data, "Received only partial file: %" FMT_OFF_T " bytes", + data->req.bytecount); + result = CURLE_PARTIAL_FILE; + } + else if(!ftpc->dont_check && + !data->req.bytecount && + (data->req.size > 0)) { + failf(data, "No data was received"); + result = CURLE_FTP_COULDNT_RETR_FILE; + } + } + return result; +} + +/*********************************************************************** + * + * ftp_done() + * + * The DONE function. This does what needs to be done after a single DO has + * performed. + * + * Input argument is already checked for validity. + */ +static CURLcode ftp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + struct FTP *ftp = Curl_meta_get(data, CURL_META_FTP_EASY); + struct ftp_conn *ftpc = Curl_conn_meta_get(data->conn, CURL_META_FTP_CONN); + CURLcode result; + + if(!ftp || !ftpc) + return CURLE_OK; + + result = ftp_done_status(data, ftpc, status, premature); + + ftp_done_wildcard(data, ftpc); + ftp_done_path(data, ftpc, result); + result = ftp_done_secondary_socket(data, ftpc, result); + result = ftp_done_control_reply(data, ftpc, ftp, result, premature); + result = ftp_done_check_partial(data, ftpc, ftp, result, premature); + + /* clear these for next connection */ + ftp->transfer = PPTRANSFER_BODY; + ftpc->dont_check = FALSE; + + /* Send any post-transfer QUOTE strings? */ + if(!status && !result && !premature && data->set.postquote) + result = ftp_sendquote(data, ftpc, data->set.postquote); + CURL_TRC_FTP(data, "[%s] done, result=%d", FTP_CSTATE(ftpc), (int)result); + return result; +} + +/*********************************************************************** + * + * ftp_nb_type() + * + * Set TYPE. We only deal with ASCII or BINARY so this function + * sets one of them. + * If the transfer type is not sent, simulate on OK response in newstate + */ +static CURLcode ftp_nb_type(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + bool ascii, ftpstate newstate) +{ + CURLcode result; + char want = (char)(ascii ? 'A' : 'I'); + + if(ftpc->transfertype == want) { + ftp_state(data, ftpc, newstate); + return ftp_state_type_resp(data, ftpc, ftp, 200, newstate); + } + + result = Curl_pp_sendf(data, &ftpc->pp, "TYPE %c", want); + if(!result) { + ftp_state(data, ftpc, newstate); + + /* keep track of our current transfer type */ + ftpc->transfertype = want; + } + return result; +} + +/*********************************************************************** + * + * ftp_perform() + * + * This is the actual DO function for FTP. Get a file/directory according to + * the options previously setup. + */ +static CURLcode ftp_perform( + struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + bool *connected, /* connect status after PASV / PORT */ + bool *dophase_done) +{ + /* this is FTP and no proxy */ + CURLcode result = CURLE_OK; + + CURL_TRC_FTP(data, "[%s] DO phase starts", FTP_CSTATE(ftpc)); + + if(data->req.no_body) { + /* requested no body means no transfer... */ + ftp->transfer = PPTRANSFER_INFO; + } + + *dophase_done = FALSE; /* not done yet */ + + /* start the first command in the DO phase */ + result = ftp_state_quote(data, ftpc, ftp, TRUE, FTP_QUOTE); + if(result) + return result; + + /* run the state-machine */ + result = ftp_statemach(data, ftpc, dophase_done); + + *connected = Curl_conn_is_connected(data->conn, SECONDARYSOCKET); + + if(*connected) + infof(data, "[FTP] [%s] perform, DATA connection established", + FTP_CSTATE(ftpc)); + else + CURL_TRC_FTP(data, "[%s] perform, awaiting DATA connect", + FTP_CSTATE(ftpc)); + + if(*dophase_done) + CURL_TRC_FTP(data, "[%s] DO phase is complete1", FTP_CSTATE(ftpc)); + + return result; +} + +static void wc_data_dtor(void *ptr) +{ + struct ftp_wc *ftpwc = ptr; + if(ftpwc && ftpwc->parser) + Curl_ftp_parselist_data_free(&ftpwc->parser); + curlx_free(ftpwc); +} + +static CURLcode init_wc_data(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp) +{ + char *last_slash; + char *path = ftp->path; + struct WildcardData *wildcard = data->wildcard; + CURLcode result = CURLE_OK; + struct ftp_wc *ftpwc = NULL; + + last_slash = strrchr(ftp->path, '/'); + if(last_slash) { + last_slash++; + if(last_slash[0] == '\0') { + wildcard->state = CURLWC_CLEAN; + return ftp_parse_url_path(data, ftpc, ftp); + } + wildcard->pattern = curlx_strdup(last_slash); + if(!wildcard->pattern) + return CURLE_OUT_OF_MEMORY; + last_slash[0] = '\0'; /* cut file from path */ + } + else { /* there is only 'wildcard pattern' or nothing */ + if(path[0]) { + wildcard->pattern = curlx_strdup(path); + if(!wildcard->pattern) + return CURLE_OUT_OF_MEMORY; + path[0] = '\0'; + } + else { /* only list */ + wildcard->state = CURLWC_CLEAN; + return ftp_parse_url_path(data, ftpc, ftp); + } + } + + /* program continues only if URL is not ending with slash, allocate needed + resources for wildcard transfer */ + + /* allocate ftp protocol specific wildcard data */ + ftpwc = curlx_calloc(1, sizeof(struct ftp_wc)); + if(!ftpwc) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + /* INITIALIZE parselist structure */ + ftpwc->parser = Curl_ftp_parselist_data_alloc(); + if(!ftpwc->parser) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + wildcard->ftpwc = ftpwc; /* put it to the WildcardData tmp pointer */ + wildcard->dtor = wc_data_dtor; + + /* wildcard does not support NOCWD option (assert it?) */ + if(data->set.ftp_filemethod == FTPFILE_NOCWD) + data->set.ftp_filemethod = FTPFILE_MULTICWD; + + /* try to parse ftp URL */ + result = ftp_parse_url_path(data, ftpc, ftp); + if(result) { + goto fail; + } + + wildcard->path = curlx_strdup(ftp->path); + if(!wildcard->path) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + /* backup old write_function */ + ftpwc->backup.write_function = data->set.fwrite_func; + /* parsing write function */ + data->set.fwrite_func = Curl_ftp_parselist; + /* backup old file descriptor */ + ftpwc->backup.file_descriptor = data->set.out; + /* let the writefunc callback know the transfer */ + data->set.out = data; + + infof(data, "Wildcard - Parsing started"); + return CURLE_OK; + +fail: + if(ftpwc) { + Curl_ftp_parselist_data_free(&ftpwc->parser); + curlx_free(ftpwc); + } + curlx_safefree(wildcard->pattern); + wildcard->dtor = ZERO_NULL; + wildcard->ftpwc = NULL; + return result; +} + +static CURLcode wc_statemach(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp) +{ + struct WildcardData * const wildcard = data->wildcard; + CURLcode result = CURLE_OK; + + for(;;) { + switch(wildcard->state) { + case CURLWC_INIT: + result = init_wc_data(data, ftpc, ftp); + if(wildcard->state == CURLWC_CLEAN) + /* only listing! */ + return result; + wildcard->state = result ? CURLWC_ERROR : CURLWC_MATCHING; + return result; + + case CURLWC_MATCHING: { + /* In this state is LIST response successfully parsed, so lets restore + previous WRITEFUNCTION callback and WRITEDATA pointer */ + struct ftp_wc *ftpwc = wildcard->ftpwc; + data->set.fwrite_func = ftpwc->backup.write_function; + data->set.out = ftpwc->backup.file_descriptor; + ftpwc->backup.write_function = ZERO_NULL; + ftpwc->backup.file_descriptor = NULL; + wildcard->state = CURLWC_DOWNLOADING; + + if(Curl_ftp_parselist_geterror(ftpwc->parser)) { + /* error found in LIST parsing */ + wildcard->state = CURLWC_CLEAN; + continue; + } + if(Curl_llist_count(&wildcard->filelist) == 0) { + /* no corresponding file */ + wildcard->state = CURLWC_CLEAN; + return CURLE_REMOTE_FILE_NOT_FOUND; + } + continue; + } + + case CURLWC_DOWNLOADING: { + /* filelist has at least one file, lets get first one */ + struct Curl_llist_node *head = Curl_llist_head(&wildcard->filelist); + struct curl_fileinfo *finfo = Curl_node_elem(head); + + char *tmp_path = curl_maprintf("%s%s", wildcard->path, finfo->filename); + if(!tmp_path) + return CURLE_OUT_OF_MEMORY; + + /* switch default ftp->path and tmp_path */ + curlx_free(ftp->pathalloc); + ftp->pathalloc = ftp->path = tmp_path; + + infof(data, "Wildcard - START of \"%s\"", finfo->filename); + if(data->set.chunk_bgn) { + long userresponse; + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_chunk_bgn); + userresponse = data->set.chunk_bgn( + finfo, data->set.wildcardptr, + (int)Curl_llist_count(&wildcard->filelist)); + CURL_CBAPI_END(&guard); + switch(userresponse) { + case CURL_CHUNK_BGN_FUNC_SKIP: + infof(data, "Wildcard - \"%s\" skipped by user", finfo->filename); + wildcard->state = CURLWC_SKIP; + continue; + case CURL_CHUNK_BGN_FUNC_FAIL: + return CURLE_CHUNK_FAILED; + } + } + + if(finfo->filetype != CURLFILETYPE_FILE) { + wildcard->state = CURLWC_SKIP; + continue; + } + + if(finfo->flags & CURLFINFOFLAG_KNOWN_SIZE) + ftpc->known_filesize = finfo->size; + + result = ftp_parse_url_path(data, ftpc, ftp); + if(result) + return result; + + /* we do not need the Curl_fileinfo of first file anymore */ + Curl_node_remove(Curl_llist_head(&wildcard->filelist)); + + if(Curl_llist_count(&wildcard->filelist) == 0) { + /* remains only one file to down. */ + wildcard->state = CURLWC_CLEAN; + /* after that will be ftp_do called once again and no transfer + will be done because of CURLWC_CLEAN state */ + return CURLE_OK; + } + return result; + } + + case CURLWC_SKIP: { + if(data->set.chunk_end) { + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_chunk_end); + data->set.chunk_end(data->set.wildcardptr); + CURL_CBAPI_END(&guard); + } + Curl_node_remove(Curl_llist_head(&wildcard->filelist)); + wildcard->state = (Curl_llist_count(&wildcard->filelist) == 0) ? + CURLWC_CLEAN : CURLWC_DOWNLOADING; + continue; + } + + case CURLWC_CLEAN: { + struct ftp_wc *ftpwc = wildcard->ftpwc; + result = CURLE_OK; + if(ftpwc) + result = Curl_ftp_parselist_geterror(ftpwc->parser); + + wildcard->state = result ? CURLWC_ERROR : CURLWC_DONE; + return result; + } + + case CURLWC_DONE: + case CURLWC_ERROR: + case CURLWC_CLEAR: + if(wildcard->dtor) { + wildcard->dtor(wildcard->ftpwc); + wildcard->ftpwc = NULL; + } + return result; + } + } + /* UNREACHABLE */ +} + +/*********************************************************************** + * + * ftp_regular_transfer() + * + * The input argument is already checked for validity. + * + * Performs all commands done before a regular transfer between a local and a + * remote host. + * + * ftp->ctl_valid starts out as FALSE, and gets set to TRUE if we reach the + * ftp_done() function without finding any major problem. + */ +static CURLcode ftp_regular_transfer(struct Curl_easy *data, + struct ftp_conn *ftpc, + struct FTP *ftp, + bool *dophase_done) +{ + CURLcode result = CURLE_OK; + bool connected = FALSE; + data->req.size = -1; /* make sure this is unknown at this point */ + + Curl_pgrsReset(data); + + ftpc->ctl_valid = TRUE; /* starts good */ + + result = ftp_perform(data, ftpc, ftp, + &connected, /* have we connected after PASV/PORT */ + dophase_done); /* all commands in the DO-phase done? */ + + if(!result) { + + if(!*dophase_done) + /* the DO phase has not completed yet */ + return CURLE_OK; + + result = ftp_dophase_done(data, ftpc, ftp, connected); + + if(result) + return result; + } + else + freedirs(ftpc); + + return result; +} + +/*********************************************************************** + * + * ftp_do() + * + * This function is registered as 'curl_do' function. It decodes the path + * parts etc as a wrapper to the actual DO function (ftp_perform). + * + * The input argument is already checked for validity. + */ +static CURLcode ftp_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct ftp_conn *ftpc = Curl_conn_meta_get(data->conn, CURL_META_FTP_CONN); + struct FTP *ftp = Curl_meta_get(data, CURL_META_FTP_EASY); + + *done = FALSE; /* default to false */ + if(!ftpc || !ftp) + return CURLE_FAILED_INIT; + ftpc->wait_data_conn = FALSE; /* default to no such wait */ + +#ifdef CURL_PREFER_LF_LINEENDS + { + /* FTP data may need conversion. */ + struct Curl_cwriter *ftp_lc_writer; + + result = Curl_cwriter_create(&ftp_lc_writer, data, &ftp_cw_lc, + CURL_CW_CONTENT_DECODE); + if(result) + return result; + + result = Curl_cwriter_add(data, ftp_lc_writer); + if(result) { + Curl_cwriter_free(data, ftp_lc_writer); + return result; + } + } +#endif /* CURL_PREFER_LF_LINEENDS */ + + if(data->state.wildcardmatch) { + result = wc_statemach(data, ftpc, ftp); + if(data->wildcard->state == CURLWC_SKIP || + data->wildcard->state == CURLWC_DONE) { + /* do not call ftp_regular_transfer */ + return CURLE_OK; + } + if(result) /* error, loop or skipping the file */ + return result; + } + else { /* no wildcard FSM needed */ + result = ftp_parse_url_path(data, ftpc, ftp); + if(result) + return result; + } + + result = ftp_regular_transfer(data, ftpc, ftp, done); + + return result; +} + +/*********************************************************************** + * + * ftp_quit() + * + * This should be called before calling sclose() on an ftp control connection + * (not data connections). We should then wait for the response from the + * server before returning. The calling code should then try to close the + * connection. + * + */ +static CURLcode ftp_quit(struct Curl_easy *data, + struct ftp_conn *ftpc) +{ + CURLcode result = CURLE_OK; + + if(ftpc->ctl_valid) { + CURL_TRC_FTP(data, "sending QUIT to close session"); + result = Curl_pp_sendf(data, &ftpc->pp, "%s", "QUIT"); + if(result) { + failf(data, "Failure sending QUIT command: %s", + curl_easy_strerror(result)); + ftpc->ctl_valid = FALSE; /* mark control connection as bad */ + connclose(data->conn); /* mark for closure */ + ftp_state(data, ftpc, FTP_STOP); + return result; + } + + ftp_state(data, ftpc, FTP_QUIT); + + result = ftp_block_statemach(data, ftpc); + } + + return result; +} + +/*********************************************************************** + * + * ftp_disconnect() + * + * Disconnect from an FTP server. Cleanup protocol-specific per-connection + * resources. BLOCKING. + */ +static CURLcode ftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + struct ftp_conn *ftpc = Curl_conn_meta_get(conn, CURL_META_FTP_CONN); + + if(!ftpc) + return CURLE_FAILED_INIT; + /* We cannot send quit unconditionally. If this connection is stale or + bad in any way, sending quit and waiting around here will make the + disconnect wait in vain and cause more problems than we need to. + + ftp_quit() will check the state of ftp->ctl_valid. If it is ok it + will try to send the QUIT command, otherwise it will return. */ + ftpc->shutdown = TRUE; + if(dead_connection || Curl_pp_needs_flush(data, &ftpc->pp)) + ftpc->ctl_valid = FALSE; + + /* The FTP session may or may not have been allocated/setup at this point! */ + (void)ftp_quit(data, ftpc); /* ignore errors on the QUIT */ + return CURLE_OK; +} + +/* called from multi.c while DOing */ +static CURLcode ftp_doing(struct Curl_easy *data, + bool *dophase_done) +{ + struct ftp_conn *ftpc = Curl_conn_meta_get(data->conn, CURL_META_FTP_CONN); + struct FTP *ftp = Curl_meta_get(data, CURL_META_FTP_EASY); + CURLcode result; + + if(!ftpc || !ftp) + return CURLE_FAILED_INIT; + result = ftp_statemach(data, ftpc, dophase_done); + + if(result) + CURL_TRC_FTP(data, "[%s] DO phase failed", FTP_CSTATE(ftpc)); + else if(*dophase_done) { + result = ftp_dophase_done(data, ftpc, ftp, FALSE /* not connected */); + + CURL_TRC_FTP(data, "[%s] DO phase is complete2", FTP_CSTATE(ftpc)); + } + return result; +} + +static void ftp_easy_dtor(void *key, size_t klen, void *entry) +{ + struct FTP *ftp = entry; + (void)key; + (void)klen; + curlx_safefree(ftp->pathalloc); + curlx_free(ftp); +} + +static void ftp_conn_dtor(void *key, size_t klen, void *entry) +{ + struct ftp_conn *ftpc = entry; + (void)key; + (void)klen; + freedirs(ftpc); + curlx_safefree(ftpc->account); + curlx_safefree(ftpc->alternative_to_user); + curlx_safefree(ftpc->entrypath); + curlx_safefree(ftpc->prevpath); + curlx_safefree(ftpc->server_os); + Curl_pp_disconnect(&ftpc->pp); + curlx_free(ftpc); +} + +static void type_url_check(struct Curl_easy *data, struct FTP *ftp) +{ + size_t len = strlen(ftp->path); + /* FTP URLs support an extension like ";type=<typecode>" that + * we will try to get now! */ + if((len >= 7) && !memcmp(&ftp->path[len - 7], ";type=", 6)) { + char *type = &ftp->path[len - 7]; + char command = Curl_raw_toupper(type[6]); + + *type = 0; /* cut it off */ + + switch(command) { + case 'A': /* ASCII mode */ + data->state.prefer_ascii = TRUE; + break; + + case 'D': /* directory mode */ + data->state.list_only = TRUE; + break; + + case 'I': /* binary mode */ + default: + /* switch off ASCII */ + data->state.prefer_ascii = FALSE; + break; + } + } +} + +static CURLcode ftp_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + struct FTP *ftp; + CURLcode result = CURLE_OK; + struct ftp_conn *ftpc; + + ftp = curlx_calloc(1, sizeof(*ftp)); + if(!ftp || + Curl_meta_set(data, CURL_META_FTP_EASY, ftp, ftp_easy_dtor)) + return CURLE_OUT_OF_MEMORY; + + ftpc = curlx_calloc(1, sizeof(*ftpc)); + if(!ftpc || + Curl_conn_meta_set(conn, CURL_META_FTP_CONN, ftpc, ftp_conn_dtor)) + return CURLE_OUT_OF_MEMORY; + + /* clone connection related data that is FTP specific */ + if(CURL_EASY_STR(data, STRING_FTP_ACCOUNT)) { + ftpc->account = curlx_strdup(CURL_EASY_STR(data, STRING_FTP_ACCOUNT)); + if(!ftpc->account) { + Curl_conn_meta_remove(conn, CURL_META_FTP_CONN); + return CURLE_OUT_OF_MEMORY; + } + } + if(CURL_EASY_STR(data, STRING_FTP_ALTERNATIVE_TO_USER)) { + ftpc->alternative_to_user = + curlx_strdup(CURL_EASY_STR(data, STRING_FTP_ALTERNATIVE_TO_USER)); + if(!ftpc->alternative_to_user) { + curlx_safefree(ftpc->account); + Curl_conn_meta_remove(conn, CURL_META_FTP_CONN); + return CURLE_OUT_OF_MEMORY; + } + } + + ftp->path = &data->state.up.path[1]; /* do not include the initial slash */ + + type_url_check(data, ftp); + + /* get some initial data into the ftp struct */ + ftp->transfer = PPTRANSFER_BODY; + ftp->downloadsize = 0; + ftpc->known_filesize = -1; /* unknown size for now */ + ftpc->use_ssl = data->set.use_ssl; + ftpc->ccc = data->set.ftp_ccc; + + CURL_TRC_FTP(data, "[%s] setup connection -> %d", FTP_CSTATE(ftpc), + (int)result); + return result; +} + +bool Curl_ftp_conns_match(struct connectdata *needle, struct connectdata *conn) +{ + struct ftp_conn *nftpc = Curl_conn_meta_get(needle, CURL_META_FTP_CONN); + struct ftp_conn *cftpc = Curl_conn_meta_get(conn, CURL_META_FTP_CONN); + /* Also match ACCOUNT, ALTERNATIVE-TO-USER and CCC options */ + if(!nftpc || !cftpc || + Curl_timestrcmp(nftpc->account, cftpc->account) || + Curl_timestrcmp(nftpc->alternative_to_user, + cftpc->alternative_to_user) || + (nftpc->ccc != cftpc->ccc)) + return FALSE; + /* A mismatch on `use_ssl` MUST have been found in connection matching + * before we come here. This is a check on MAYBE/MUST use of STARTTLS and + * it only works on FTP. But IMAP/SMTP etc have the same `use_ssl` and + * no extra match like FTP. We lack tests in this area, so let FTP fail + * loudly here to help other cases. */ + if(nftpc->use_ssl > cftpc->use_ssl) { + DEBUGASSERT(0); + return FALSE; + } + return TRUE; +} + +/* + * FTP protocol. + */ +const struct Curl_protocol Curl_protocol_ftp = { + ftp_setup_connection, /* setup_connection */ + ftp_do, /* do_it */ + ftp_done, /* done */ + ftp_do_more, /* do_more */ + ftp_connect, /* connect_it */ + ftp_multi_statemach, /* connecting */ + ftp_doing, /* doing */ + ftp_pollset, /* proto_pollset */ + ftp_pollset, /* doing_pollset */ + ftp_domore_pollset, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + ftp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#endif /* CURL_DISABLE_FTP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftp.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftp.h new file mode 100644 index 0000000000..3ce02c8793 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftp.h @@ -0,0 +1,45 @@ +#ifndef HEADER_CURL_FTP_H +#define HEADER_CURL_FTP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_FTP +extern const struct Curl_protocol Curl_protocol_ftp; + +bool Curl_ftp_conns_match(struct connectdata *needle, + struct connectdata *conn); + +typedef enum { + FTPFILE_MULTICWD = 1, /* as defined by RFC1738 */ + FTPFILE_NOCWD = 2, /* use SIZE / RETR / STOR on the full path */ + FTPFILE_SINGLECWD = 3 /* make one CWD, then SIZE / RETR / STOR on the + file */ +} curl_ftpfile; + +#endif /* CURL_DISABLE_FTP */ + +#define DEFAULT_ACCEPT_TIMEOUT 60000 /* milliseconds == one minute */ + +#endif /* HEADER_CURL_FTP_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftplistparser.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftplistparser.c new file mode 100644 index 0000000000..47e3d75d94 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftplistparser.c @@ -0,0 +1,1093 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_FTP + +/** + * Now implemented: + * + * 1) Unix version 1 + * drwxr-xr-x 1 user01 ftp 512 Jan 29 23:32 prog + * 2) Unix version 2 + * drwxr-xr-x 1 user01 ftp 512 Jan 29 1997 prog + * 3) Unix version 3 + * drwxr-xr-x 1 1 1 512 Jan 29 23:32 prog + * 4) Unix symlink + * lrwxr-xr-x 1 user01 ftp 512 Jan 29 23:32 prog -> prog2000 + * 5) DOS style + * 01-29-97 11:32PM <DIR> prog + */ + +#include "urldata.h" +#include "fileinfo.h" +#include "llist.h" +#include "ftp.h" +#include "ftp-int.h" +#include "ftplistparser.h" +#include "curl_fnmatch.h" +#include "multiif.h" +#include "curlx/strparse.h" + +typedef enum { + PL_UNIX_TOTALSIZE = 0, + PL_UNIX_FILETYPE, + PL_UNIX_PERMISSION, + PL_UNIX_HLINKS, + PL_UNIX_USER, + PL_UNIX_GROUP, + PL_UNIX_SIZE, + PL_UNIX_TIME, + PL_UNIX_FILENAME, + PL_UNIX_SYMLINK +} pl_unix_mainstate; + +typedef union { + enum { + PL_UNIX_TOTALSIZE_INIT = 0, + PL_UNIX_TOTALSIZE_READING + } total_dirsize; + + enum { + PL_UNIX_HLINKS_PRESPACE = 0, + PL_UNIX_HLINKS_NUMBER + } hlinks; + + enum { + PL_UNIX_USER_PRESPACE = 0, + PL_UNIX_USER_PARSING + } user; + + enum { + PL_UNIX_GROUP_PRESPACE = 0, + PL_UNIX_GROUP_NAME + } group; + + enum { + PL_UNIX_SIZE_PRESPACE = 0, + PL_UNIX_SIZE_NUMBER + } size; + + enum { + PL_UNIX_TIME_PREPART1 = 0, + PL_UNIX_TIME_PART1, + PL_UNIX_TIME_PREPART2, + PL_UNIX_TIME_PART2, + PL_UNIX_TIME_PREPART3, + PL_UNIX_TIME_PART3 + } time; + + enum { + PL_UNIX_FILENAME_PRESPACE = 0, + PL_UNIX_FILENAME_NAME, + PL_UNIX_FILENAME_WINDOWSEOL + } filename; + + enum { + PL_UNIX_SYMLINK_PRESPACE = 0, + PL_UNIX_SYMLINK_NAME, + PL_UNIX_SYMLINK_PRETARGET1, + PL_UNIX_SYMLINK_PRETARGET2, + PL_UNIX_SYMLINK_PRETARGET3, + PL_UNIX_SYMLINK_PRETARGET4, + PL_UNIX_SYMLINK_TARGET, + PL_UNIX_SYMLINK_WINDOWSEOL + } symlink; +} pl_unix_substate; + +typedef enum { + PL_WINNT_DATE = 0, + PL_WINNT_TIME, + PL_WINNT_DIRORSIZE, + PL_WINNT_FILENAME +} pl_winNT_mainstate; + +typedef union { + enum { + PL_WINNT_TIME_PRESPACE = 0, + PL_WINNT_TIME_TIME + } time; + enum { + PL_WINNT_DIRORSIZE_PRESPACE = 0, + PL_WINNT_DIRORSIZE_CONTENT + } dirorsize; + enum { + PL_WINNT_FILENAME_PRESPACE = 0, + PL_WINNT_FILENAME_CONTENT, + PL_WINNT_FILENAME_WINEOL + } filename; +} pl_winNT_substate; + +/* This struct is used in wildcard downloading - for parsing LIST response */ +struct ftp_parselist_data { + enum { + OS_TYPE_UNKNOWN = 0, + OS_TYPE_UNIX, + OS_TYPE_WIN_NT + } os_type; + + union { + struct { + pl_unix_mainstate main; + pl_unix_substate sub; + } UNIX; + + struct { + pl_winNT_mainstate main; + pl_winNT_substate sub; + } NT; + } state; + + CURLcode error; + struct fileinfo *file_data; + unsigned int item_length; + size_t item_offset; + struct { + size_t filename; + size_t user; + size_t group; + size_t time; + size_t perm; + size_t symlink_target; + } offsets; +}; + +static void fileinfo_dtor(void *user, void *element) +{ + (void)user; + Curl_fileinfo_cleanup(element); +} + +void Curl_wildcard_init(struct WildcardData *wc) +{ + Curl_llist_init(&wc->filelist, fileinfo_dtor); + wc->state = CURLWC_INIT; +} + +void Curl_wildcard_dtor(struct WildcardData **wcp) +{ + struct WildcardData *wc = *wcp; + if(!wc) + return; + + if(wc->dtor) { + wc->dtor(wc->ftpwc); + wc->dtor = ZERO_NULL; + wc->ftpwc = NULL; + } + DEBUGASSERT(!wc->ftpwc); + + Curl_llist_destroy(&wc->filelist, NULL); + curlx_safefree(wc->path); + curlx_safefree(wc->pattern); + wc->state = CURLWC_INIT; + curlx_free(wc); + *wcp = NULL; +} + +struct ftp_parselist_data *Curl_ftp_parselist_data_alloc(void) +{ + return curlx_calloc(1, sizeof(struct ftp_parselist_data)); +} + +void Curl_ftp_parselist_data_free(struct ftp_parselist_data **parserp) +{ + struct ftp_parselist_data *parser = *parserp; + if(parser) + Curl_fileinfo_cleanup(parser->file_data); + curlx_free(parser); + *parserp = NULL; +} + +CURLcode Curl_ftp_parselist_geterror(struct ftp_parselist_data *pl_data) +{ + return pl_data->error; +} + +#define FTP_LP_MALFORMATED_PERM 0x01000000 + +static unsigned int ftp_pl_get_permission(const char *str) +{ + unsigned int permissions = 0; + /* USER */ + if(str[0] == 'r') + permissions |= 1 << 8; + else if(str[0] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + if(str[1] == 'w') + permissions |= 1 << 7; + else if(str[1] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + + if(str[2] == 'x') + permissions |= 1 << 6; + else if(str[2] == 's') { + permissions |= 1 << 6; + permissions |= 1 << 11; + } + else if(str[2] == 'S') + permissions |= 1 << 11; + else if(str[2] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + /* GROUP */ + if(str[3] == 'r') + permissions |= 1 << 5; + else if(str[3] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + if(str[4] == 'w') + permissions |= 1 << 4; + else if(str[4] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + if(str[5] == 'x') + permissions |= 1 << 3; + else if(str[5] == 's') { + permissions |= 1 << 3; + permissions |= 1 << 10; + } + else if(str[5] == 'S') + permissions |= 1 << 10; + else if(str[5] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + /* others */ + if(str[6] == 'r') + permissions |= 1 << 2; + else if(str[6] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + if(str[7] == 'w') + permissions |= 1 << 1; + else if(str[7] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + if(str[8] == 'x') + permissions |= 1; + else if(str[8] == 't') { + permissions |= 1; + permissions |= 1 << 9; + } + else if(str[8] == 'T') + permissions |= 1 << 9; + else if(str[8] != '-') + permissions |= FTP_LP_MALFORMATED_PERM; + + return permissions; +} + +static CURLcode ftp_pl_insert_finfo(struct Curl_easy *data, + struct fileinfo *infop) +{ + curl_fnmatch_callback compare; + struct WildcardData *wc = data->wildcard; + struct ftp_wc *ftpwc = wc->ftpwc; + struct Curl_llist *llist = &wc->filelist; + struct ftp_parselist_data *parser = ftpwc->parser; + bool add = TRUE; + struct curl_fileinfo *finfo = &infop->info; + + /* set the finfo pointers */ + char *str = curlx_dyn_ptr(&infop->buf); + finfo->filename = str + parser->offsets.filename; + finfo->strings.group = parser->offsets.group ? + str + parser->offsets.group : NULL; + finfo->strings.perm = parser->offsets.perm ? + str + parser->offsets.perm : NULL; + finfo->strings.target = parser->offsets.symlink_target && + (finfo->filetype == CURLFILETYPE_SYMLINK) ? + str + parser->offsets.symlink_target : NULL; + finfo->strings.time = str + parser->offsets.time; + finfo->strings.user = parser->offsets.user ? + str + parser->offsets.user : NULL; + + /* get correct fnmatch callback */ + compare = data->set.fnmatch; + if(!compare) + compare = Curl_fnmatch; + + /* filter pattern-corresponding filenames */ + { + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_fnmatch_data); + if(compare(data->set.fnmatch_data, wc->pattern, finfo->filename) == 0) { + /* discard symlink which is containing multiple " -> " */ + if((finfo->filetype == CURLFILETYPE_SYMLINK) && finfo->strings.target && + strstr(finfo->strings.target, " -> ")) { + add = FALSE; + } + } + else { + add = FALSE; + } + CURL_CBAPI_END(&guard); + } + + if(add) { + Curl_llist_append(llist, finfo, &infop->list); + } + else { + Curl_fileinfo_cleanup(infop); + } + + ftpwc->parser->file_data = NULL; + return CURLE_OK; +} + +#define MAX_FTPLIST_BUFFER 10000 /* arbitrarily set */ + +static CURLcode unix_filetype(const char c, curlfiletype *t) +{ + switch(c) { + case '-': + *t = CURLFILETYPE_FILE; + break; + case 'd': + *t = CURLFILETYPE_DIRECTORY; + break; + case 'l': + *t = CURLFILETYPE_SYMLINK; + break; + case 'p': + *t = CURLFILETYPE_NAMEDPIPE; + break; + case 's': + *t = CURLFILETYPE_SOCKET; + break; + case 'c': + *t = CURLFILETYPE_DEVICE_CHAR; + break; + case 'b': + *t = CURLFILETYPE_DEVICE_BLOCK; + break; + case 'D': + *t = CURLFILETYPE_DOOR; + break; + default: + return CURLE_FTP_BAD_FILE_LIST; + } + return CURLE_OK; +} + +static CURLcode parse_unix_totalsize(struct ftp_parselist_data *parser, + struct fileinfo *infop, + const char c) +{ + size_t len = curlx_dyn_len(&infop->buf); + char *mem = curlx_dyn_ptr(&infop->buf); + switch(parser->state.UNIX.sub.total_dirsize) { + case PL_UNIX_TOTALSIZE_INIT: + if(c == 't') { + parser->state.UNIX.sub.total_dirsize = PL_UNIX_TOTALSIZE_READING; + parser->item_length++; + } + else { + parser->state.UNIX.main = PL_UNIX_FILETYPE; + /* continue to fall through */ + } + break; + case PL_UNIX_TOTALSIZE_READING: + parser->item_length++; + if(c == '\r') { + parser->item_length--; + if(len) + curlx_dyn_setlen(&infop->buf, --len); + } + else if(c == '\n') { + mem[parser->item_length - 1] = 0; + if(!strncmp("total ", mem, 6)) { + const char *endptr = mem + 6; + /* here we can deal with directory size, pass the leading + whitespace and then the digits */ + curlx_str_passblanks(&endptr); + while(ISDIGIT(*endptr)) + endptr++; + if(*endptr) { + return CURLE_FTP_BAD_FILE_LIST; + } + parser->state.UNIX.main = PL_UNIX_FILETYPE; + curlx_dyn_reset(&infop->buf); + } + else + return CURLE_FTP_BAD_FILE_LIST; + } + break; + } + return CURLE_OK; +} + +static CURLcode parse_unix_permission(struct ftp_parselist_data *parser, + struct fileinfo *infop, + const char c) +{ + char *mem = curlx_dyn_ptr(&infop->buf); + parser->item_length++; + if((parser->item_length <= 9) && !strchr("rwx-tTsS", c)) + return CURLE_FTP_BAD_FILE_LIST; + + else if(parser->item_length == 10) { + unsigned int perm; + if(c != ' ') + return CURLE_FTP_BAD_FILE_LIST; + + mem[10] = 0; /* terminate permissions */ + perm = ftp_pl_get_permission(mem + parser->item_offset); + if(perm & FTP_LP_MALFORMATED_PERM) + return CURLE_FTP_BAD_FILE_LIST; + + parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_PERM; + parser->file_data->info.perm = perm; + parser->offsets.perm = parser->item_offset; + + parser->item_length = 0; + parser->state.UNIX.main = PL_UNIX_HLINKS; + parser->state.UNIX.sub.hlinks = PL_UNIX_HLINKS_PRESPACE; + } + return CURLE_OK; +} + +static CURLcode parse_unix_hlinks(struct ftp_parselist_data *parser, + struct fileinfo *infop, + const char c) +{ + size_t len = curlx_dyn_len(&infop->buf); + char *mem = curlx_dyn_ptr(&infop->buf); + + switch(parser->state.UNIX.sub.hlinks) { + case PL_UNIX_HLINKS_PRESPACE: + if(c != ' ') { + if(ISDIGIT(c) && len) { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.UNIX.sub.hlinks = PL_UNIX_HLINKS_NUMBER; + } + else + return CURLE_FTP_BAD_FILE_LIST; + } + break; + case PL_UNIX_HLINKS_NUMBER: + parser->item_length++; + if(c == ' ') { + const char *p = &mem[parser->item_offset]; + curl_off_t hlinks; + mem[parser->item_offset + parser->item_length - 1] = 0; + + if(!curlx_str_number(&p, &hlinks, LONG_MAX)) { + parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_HLINKCOUNT; + parser->file_data->info.hardlinks = (long)hlinks; + } + parser->item_length = 0; + parser->item_offset = 0; + parser->state.UNIX.main = PL_UNIX_USER; + parser->state.UNIX.sub.user = PL_UNIX_USER_PRESPACE; + } + else if(!ISDIGIT(c)) + return CURLE_FTP_BAD_FILE_LIST; + + break; + } + return CURLE_OK; +} + +static CURLcode parse_unix_user(struct ftp_parselist_data *parser, + struct fileinfo *infop, + const char c) +{ + size_t len = curlx_dyn_len(&infop->buf); + char *mem = curlx_dyn_ptr(&infop->buf); + switch(parser->state.UNIX.sub.user) { + case PL_UNIX_USER_PRESPACE: + if(c != ' ' && len) { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.UNIX.sub.user = PL_UNIX_USER_PARSING; + } + break; + case PL_UNIX_USER_PARSING: + parser->item_length++; + if(c == ' ') { + mem[parser->item_offset + parser->item_length - 1] = 0; + parser->offsets.user = parser->item_offset; + parser->state.UNIX.main = PL_UNIX_GROUP; + parser->state.UNIX.sub.group = PL_UNIX_GROUP_PRESPACE; + parser->item_offset = 0; + parser->item_length = 0; + } + break; + } + return CURLE_OK; +} + +static CURLcode parse_unix_group(struct ftp_parselist_data *parser, + struct fileinfo *infop, + const char c) +{ + size_t len = curlx_dyn_len(&infop->buf); + char *mem = curlx_dyn_ptr(&infop->buf); + switch(parser->state.UNIX.sub.group) { + case PL_UNIX_GROUP_PRESPACE: + if(c != ' ' && len) { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.UNIX.sub.group = PL_UNIX_GROUP_NAME; + } + break; + case PL_UNIX_GROUP_NAME: + parser->item_length++; + if(c == ' ') { + mem[parser->item_offset + parser->item_length - 1] = 0; + parser->offsets.group = parser->item_offset; + parser->state.UNIX.main = PL_UNIX_SIZE; + parser->state.UNIX.sub.size = PL_UNIX_SIZE_PRESPACE; + parser->item_offset = 0; + parser->item_length = 0; + } + break; + } + return CURLE_OK; +} + +static CURLcode parse_unix_size(struct ftp_parselist_data *parser, + struct fileinfo *infop, + const char c) +{ + size_t len = curlx_dyn_len(&infop->buf); + char *mem = curlx_dyn_ptr(&infop->buf); + switch(parser->state.UNIX.sub.size) { + case PL_UNIX_SIZE_PRESPACE: + if(c != ' ') { + if(ISDIGIT(c) && len) { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.UNIX.sub.size = PL_UNIX_SIZE_NUMBER; + } + else + return CURLE_FTP_BAD_FILE_LIST; + } + break; + case PL_UNIX_SIZE_NUMBER: + parser->item_length++; + if(c == ' ') { + const char *p = mem + parser->item_offset; + curl_off_t fsize; + mem[parser->item_offset + parser->item_length - 1] = 0; + if(!curlx_str_numblanks(&p, &fsize)) { + if(p[0] == '\0' && fsize != CURL_OFF_T_MAX) { + parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_SIZE; + parser->file_data->info.size = fsize; + } + parser->item_length = 0; + parser->item_offset = 0; + parser->state.UNIX.main = PL_UNIX_TIME; + parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART1; + } + } + else if(!ISDIGIT(c)) + return CURLE_FTP_BAD_FILE_LIST; + + break; + } + return CURLE_OK; +} + +static CURLcode parse_unix_time(struct ftp_parselist_data *parser, + struct fileinfo *infop, + const char c) +{ + size_t len = curlx_dyn_len(&infop->buf); + char *mem = curlx_dyn_ptr(&infop->buf); + struct curl_fileinfo *finfo = &infop->info; + + switch(parser->state.UNIX.sub.time) { + case PL_UNIX_TIME_PREPART1: + if(c != ' ') { + if(ISALNUM(c) && len) { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.UNIX.sub.time = PL_UNIX_TIME_PART1; + } + else + return CURLE_FTP_BAD_FILE_LIST; + } + break; + case PL_UNIX_TIME_PART1: + parser->item_length++; + if(c == ' ') + parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART2; + + else if(!ISALNUM(c) && c != '.') + return CURLE_FTP_BAD_FILE_LIST; + + break; + case PL_UNIX_TIME_PREPART2: + parser->item_length++; + if(c != ' ') { + if(ISALNUM(c)) + parser->state.UNIX.sub.time = PL_UNIX_TIME_PART2; + else + return CURLE_FTP_BAD_FILE_LIST; + } + break; + case PL_UNIX_TIME_PART2: + parser->item_length++; + if(c == ' ') + parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART3; + else if(!ISALNUM(c) && c != '.') + return CURLE_FTP_BAD_FILE_LIST; + break; + case PL_UNIX_TIME_PREPART3: + parser->item_length++; + if(c != ' ') { + if(ISALNUM(c)) + parser->state.UNIX.sub.time = PL_UNIX_TIME_PART3; + else + return CURLE_FTP_BAD_FILE_LIST; + } + break; + case PL_UNIX_TIME_PART3: + parser->item_length++; + if(c == ' ') { + mem[parser->item_offset + parser->item_length - 1] = 0; + parser->offsets.time = parser->item_offset; + if(finfo->filetype == CURLFILETYPE_SYMLINK) { + parser->state.UNIX.main = PL_UNIX_SYMLINK; + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRESPACE; + } + else { + parser->state.UNIX.main = PL_UNIX_FILENAME; + parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_PRESPACE; + } + } + else if(!ISALNUM(c) && c != '.' && c != ':') + return CURLE_FTP_BAD_FILE_LIST; + break; + } + return CURLE_OK; +} + +static CURLcode parse_unix_filename(struct Curl_easy *data, + struct ftp_parselist_data *parser, + struct fileinfo *infop, + const char c) +{ + size_t len = curlx_dyn_len(&infop->buf); + char *mem = curlx_dyn_ptr(&infop->buf); + CURLcode result = CURLE_OK; + + switch(parser->state.UNIX.sub.filename) { + case PL_UNIX_FILENAME_PRESPACE: + if(c != ' ' && len) { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_NAME; + } + break; + case PL_UNIX_FILENAME_NAME: + parser->item_length++; + if(c == '\r') + parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_WINDOWSEOL; + + else if(c == '\n') { + mem[parser->item_offset + parser->item_length - 1] = 0; + parser->offsets.filename = parser->item_offset; + parser->state.UNIX.main = PL_UNIX_FILETYPE; + result = ftp_pl_insert_finfo(data, infop); + } + break; + case PL_UNIX_FILENAME_WINDOWSEOL: + if(c == '\n') { + mem[parser->item_offset + parser->item_length - 1] = 0; + parser->offsets.filename = parser->item_offset; + parser->state.UNIX.main = PL_UNIX_FILETYPE; + result = ftp_pl_insert_finfo(data, infop); + } + else + result = CURLE_FTP_BAD_FILE_LIST; + break; + } + return result; +} + +static CURLcode parse_unix_symlink(struct Curl_easy *data, + struct ftp_parselist_data *parser, + struct fileinfo *infop, + const char c) +{ + size_t len = curlx_dyn_len(&infop->buf); + char *mem = curlx_dyn_ptr(&infop->buf); + CURLcode result = CURLE_OK; + + switch(parser->state.UNIX.sub.symlink) { + case PL_UNIX_SYMLINK_PRESPACE: + if(c != ' ' && len) { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME; + } + break; + case PL_UNIX_SYMLINK_NAME: + parser->item_length++; + if(c == ' ') + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET1; + + else if(c == '\r' || c == '\n') + return CURLE_FTP_BAD_FILE_LIST; + + break; + case PL_UNIX_SYMLINK_PRETARGET1: + parser->item_length++; + if(c == '-') + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET2; + + else if(c == '\r' || c == '\n') + return CURLE_FTP_BAD_FILE_LIST; + else + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME; + break; + case PL_UNIX_SYMLINK_PRETARGET2: + parser->item_length++; + if(c == '>') + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET3; + else if(c == '\r' || c == '\n') + return CURLE_FTP_BAD_FILE_LIST; + else + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME; + + break; + case PL_UNIX_SYMLINK_PRETARGET3: + parser->item_length++; + if(c == ' ') { + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET4; + /* now place where is symlink following */ + mem[parser->item_offset + parser->item_length - 4] = 0; + parser->offsets.filename = parser->item_offset; + parser->item_length = 0; + parser->item_offset = 0; + } + else if(c == '\r' || c == '\n') + return CURLE_FTP_BAD_FILE_LIST; + else + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME; + break; + case PL_UNIX_SYMLINK_PRETARGET4: + if(c != '\r' && c != '\n' && len) { + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_TARGET; + parser->item_offset = len - 1; + parser->item_length = 1; + } + else + return CURLE_FTP_BAD_FILE_LIST; + + break; + case PL_UNIX_SYMLINK_TARGET: + parser->item_length++; + if(c == '\r') + parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_WINDOWSEOL; + + else if(c == '\n') { + mem[parser->item_offset + parser->item_length - 1] = 0; + parser->offsets.symlink_target = parser->item_offset; + result = ftp_pl_insert_finfo(data, infop); + if(result) + break; + + parser->state.UNIX.main = PL_UNIX_FILETYPE; + } + break; + case PL_UNIX_SYMLINK_WINDOWSEOL: + if(c == '\n') { + mem[parser->item_offset + parser->item_length - 1] = 0; + parser->offsets.symlink_target = parser->item_offset; + result = ftp_pl_insert_finfo(data, infop); + if(result) + break; + + parser->state.UNIX.main = PL_UNIX_FILETYPE; + } + else + result = CURLE_FTP_BAD_FILE_LIST; + + break; + } + return result; +} + +static CURLcode parse_unix(struct Curl_easy *data, + struct ftp_parselist_data *parser, + struct fileinfo *infop, + const char c) +{ + struct curl_fileinfo *finfo = &infop->info; + CURLcode result = CURLE_OK; + + switch(parser->state.UNIX.main) { + case PL_UNIX_TOTALSIZE: + result = parse_unix_totalsize(parser, infop, c); + if(result) + break; + if(parser->state.UNIX.main != PL_UNIX_FILETYPE) + break; + FALLTHROUGH(); + case PL_UNIX_FILETYPE: + result = unix_filetype(c, &finfo->filetype); + if(!result) { + parser->state.UNIX.main = PL_UNIX_PERMISSION; + parser->item_length = 0; + parser->item_offset = 1; + } + break; + case PL_UNIX_PERMISSION: + result = parse_unix_permission(parser, infop, c); + break; + case PL_UNIX_HLINKS: + result = parse_unix_hlinks(parser, infop, c); + break; + case PL_UNIX_USER: + result = parse_unix_user(parser, infop, c); + break; + case PL_UNIX_GROUP: + result = parse_unix_group(parser, infop, c); + break; + case PL_UNIX_SIZE: + result = parse_unix_size(parser, infop, c); + break; + case PL_UNIX_TIME: + result = parse_unix_time(parser, infop, c); + break; + case PL_UNIX_FILENAME: + result = parse_unix_filename(data, parser, infop, c); + break; + case PL_UNIX_SYMLINK: + result = parse_unix_symlink(data, parser, infop, c); + break; + } + return result; +} + +static CURLcode parse_winnt(struct Curl_easy *data, + struct ftp_parselist_data *parser, + struct fileinfo *infop, + const char c) +{ + struct curl_fileinfo *finfo = &infop->info; + size_t len = curlx_dyn_len(&infop->buf); + char *mem = curlx_dyn_ptr(&infop->buf); + CURLcode result = CURLE_OK; + + switch(parser->state.NT.main) { + case PL_WINNT_DATE: + parser->item_length++; + if(parser->item_length < 9) { + if(!strchr("0123456789-", c)) { /* only simple control */ + return CURLE_FTP_BAD_FILE_LIST; + } + } + else if(parser->item_length == 9) { + if(c == ' ') { + parser->state.NT.main = PL_WINNT_TIME; + parser->state.NT.sub.time = PL_WINNT_TIME_PRESPACE; + } + else + return CURLE_FTP_BAD_FILE_LIST; + } + else + return CURLE_FTP_BAD_FILE_LIST; + break; + case PL_WINNT_TIME: + parser->item_length++; + switch(parser->state.NT.sub.time) { + case PL_WINNT_TIME_PRESPACE: + if(!ISBLANK(c)) + parser->state.NT.sub.time = PL_WINNT_TIME_TIME; + break; + case PL_WINNT_TIME_TIME: + if(c == ' ') { + parser->offsets.time = parser->item_offset; + mem[parser->item_offset + parser->item_length - 1] = 0; + parser->state.NT.main = PL_WINNT_DIRORSIZE; + parser->state.NT.sub.dirorsize = PL_WINNT_DIRORSIZE_PRESPACE; + parser->item_length = 0; + } + else if(!strchr("APM0123456789:", c)) + return CURLE_FTP_BAD_FILE_LIST; + break; + } + break; + case PL_WINNT_DIRORSIZE: + switch(parser->state.NT.sub.dirorsize) { + case PL_WINNT_DIRORSIZE_PRESPACE: + if(c != ' ' && len) { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.NT.sub.dirorsize = PL_WINNT_DIRORSIZE_CONTENT; + } + break; + case PL_WINNT_DIRORSIZE_CONTENT: + parser->item_length++; + if(c == ' ') { + mem[parser->item_offset + parser->item_length - 1] = 0; + if(!strcmp("<DIR>", mem + parser->item_offset)) { + finfo->filetype = CURLFILETYPE_DIRECTORY; + finfo->size = 0; + } + else { + const char *p = mem + parser->item_offset; + if(curlx_str_numblanks(&p, &finfo->size)) { + return CURLE_FTP_BAD_FILE_LIST; + } + /* correct file type */ + parser->file_data->info.filetype = CURLFILETYPE_FILE; + } + + parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_SIZE; + parser->item_length = 0; + parser->state.NT.main = PL_WINNT_FILENAME; + parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE; + } + break; + } + break; + case PL_WINNT_FILENAME: + switch(parser->state.NT.sub.filename) { + case PL_WINNT_FILENAME_PRESPACE: + if(c != ' ' && len) { + parser->item_offset = len - 1; + parser->item_length = 1; + parser->state.NT.sub.filename = PL_WINNT_FILENAME_CONTENT; + } + break; + case PL_WINNT_FILENAME_CONTENT: + parser->item_length++; + if(!len) + return CURLE_FTP_BAD_FILE_LIST; + if(c == '\r') { + parser->state.NT.sub.filename = PL_WINNT_FILENAME_WINEOL; + mem[len - 1] = 0; + } + else if(c == '\n') { + parser->offsets.filename = parser->item_offset; + mem[len - 1] = 0; + result = ftp_pl_insert_finfo(data, infop); + if(result) + return result; + + parser->state.NT.main = PL_WINNT_DATE; + parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE; + } + break; + case PL_WINNT_FILENAME_WINEOL: + if(c == '\n') { + parser->offsets.filename = parser->item_offset; + result = ftp_pl_insert_finfo(data, infop); + if(result) + return result; + + parser->state.NT.main = PL_WINNT_DATE; + parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE; + } + else + return CURLE_FTP_BAD_FILE_LIST; + + break; + } + break; + } + + return CURLE_OK; +} + +size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb, + void *connptr) +{ + size_t bufflen = size * nmemb; + struct Curl_easy *data = (struct Curl_easy *)connptr; + struct ftp_wc *ftpwc = data->wildcard->ftpwc; + struct ftp_parselist_data *parser = ftpwc->parser; + size_t i = 0; + CURLcode result; + size_t retsize = bufflen; + + if(parser->error) { /* error in previous call */ + /* scenario: + * 1. call => OK.. + * 2. call => OUT_OF_MEMORY (or other error) + * 3. (last) call => is skipped RIGHT HERE and the error is handled later + * in wc_statemach() + */ + goto fail; + } + + if(parser->os_type == OS_TYPE_UNKNOWN && bufflen > 0) { + /* considering info about FILE response format */ + parser->os_type = ISDIGIT(buffer[0]) ? OS_TYPE_WIN_NT : OS_TYPE_UNIX; + } + + while(i < bufflen) { /* FSM */ + char c = buffer[i]; + struct fileinfo *infop; + if(!parser->file_data) { /* tmp file data is not allocated yet */ + parser->file_data = Curl_fileinfo_alloc(); + if(!parser->file_data) { + parser->error = CURLE_OUT_OF_MEMORY; + goto fail; + } + parser->item_offset = 0; + parser->item_length = 0; + curlx_dyn_init(&parser->file_data->buf, MAX_FTPLIST_BUFFER); + } + + infop = parser->file_data; + + if(curlx_dyn_addn(&infop->buf, &c, 1)) { + parser->error = CURLE_OUT_OF_MEMORY; + goto fail; + } + + switch(parser->os_type) { + case OS_TYPE_UNIX: + result = parse_unix(data, parser, infop, c); + break; + case OS_TYPE_WIN_NT: + result = parse_winnt(data, parser, infop, c); + break; + default: + retsize = bufflen + 1; + goto fail; + } + if(result) { + parser->error = result; + goto fail; + } + + i++; + } + return retsize; + +fail: + + /* Clean up any allocated memory. */ + if(parser->file_data) { + Curl_fileinfo_cleanup(parser->file_data); + parser->file_data = NULL; + } + + return retsize; +} + +#endif /* !CURL_DISABLE_FTP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftplistparser.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftplistparser.h new file mode 100644 index 0000000000..5d7aa492ba --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ftplistparser.h @@ -0,0 +1,77 @@ +#ifndef HEADER_CURL_FTPLISTPARSER_H +#define HEADER_CURL_FTPLISTPARSER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_FTP + +/* WRITEFUNCTION callback for parsing LIST responses */ +size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb, + void *connptr); + +struct ftp_parselist_data; /* defined inside ftplibparser.c */ + +CURLcode Curl_ftp_parselist_geterror(struct ftp_parselist_data *pl_data); + +struct ftp_parselist_data *Curl_ftp_parselist_data_alloc(void); + +void Curl_ftp_parselist_data_free(struct ftp_parselist_data **parserp); + +/* list of wildcard process states */ +typedef enum { + CURLWC_CLEAR = 0, + CURLWC_INIT = 1, + CURLWC_MATCHING, /* library is trying to get list of addresses for + downloading */ + CURLWC_DOWNLOADING, + CURLWC_CLEAN, /* deallocate resources and reset settings */ + CURLWC_SKIP, /* skip over concrete file */ + CURLWC_ERROR, /* error cases */ + CURLWC_DONE /* if is wildcard->state == CURLWC_DONE wildcard loop + will end */ +} wildcard_states; + +typedef void (*wildcard_dtor)(void *ptr); + +/* struct keeping information about wildcard download process */ +struct WildcardData { + char *path; /* path to the directory, where we trying wildcard-match */ + char *pattern; /* wildcard pattern */ + struct Curl_llist filelist; /* llist with struct Curl_fileinfo */ + struct ftp_wc *ftpwc; /* pointer to FTP wildcard data */ + wildcard_dtor dtor; + unsigned char state; /* wildcard_states */ +}; + +void Curl_wildcard_init(struct WildcardData *wc); +void Curl_wildcard_dtor(struct WildcardData **wcp); + +struct Curl_easy; + +#else /* CURL_DISABLE_FTP */ +#define Curl_wildcard_dtor(x) +#endif /* !CURL_DISABLE_FTP */ + +#endif /* HEADER_CURL_FTPLISTPARSER_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/functypes.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/functypes.h new file mode 100644 index 0000000000..7fcee834ff --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/functypes.h @@ -0,0 +1,108 @@ +#ifndef HEADER_CURL_FUNCTYPES_H +#define HEADER_CURL_FUNCTYPES_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* defaults: + + ssize_t recv(int, void *, size_t, int); + ssize_t send(int, const void *, size_t, int); + + If other argument or return types are needed: + + 1. For systems that run configure or cmake, the alternatives are provided + here. + 2. For systems with config-*.h files, define them there. + */ + +#ifdef USE_WINSOCK +/* int recv(SOCKET, char *, int, int) */ +#define RECV_TYPE_ARG1 SOCKET +#define RECV_TYPE_ARG2 char * +#define RECV_TYPE_ARG3 int +#define RECV_TYPE_RETV int + +/* int send(SOCKET, const char *, int, int); */ +#define SEND_TYPE_ARG1 SOCKET +#define SEND_TYPE_ARG2 char * +#define SEND_TYPE_ARG3 int +#define SEND_TYPE_RETV int + +#elif defined(__AMIGA__) /* Any AmigaOS flavor */ + +/* long recv(long, char *, long, long); */ +#define RECV_TYPE_ARG1 long +#define RECV_TYPE_ARG2 char * +#define RECV_TYPE_ARG3 long +#define RECV_TYPE_ARG4 long +#define RECV_TYPE_RETV long + +/* int send(int, char *, int, int); */ +#define SEND_TYPE_ARG1 int +#define SEND_NONCONST_ARG2 +#define SEND_TYPE_ARG2 char * +#define SEND_TYPE_ARG3 int +#define SEND_TYPE_RETV int +#endif + +#ifndef RECV_TYPE_ARG1 +#define RECV_TYPE_ARG1 int +#endif + +#ifndef RECV_TYPE_ARG2 +#define RECV_TYPE_ARG2 void * +#endif + +#ifndef RECV_TYPE_ARG3 +#define RECV_TYPE_ARG3 size_t +#endif + +#ifndef RECV_TYPE_ARG4 +#define RECV_TYPE_ARG4 int +#endif + +#ifndef RECV_TYPE_RETV +#define RECV_TYPE_RETV ssize_t +#endif + +#ifndef SEND_TYPE_ARG1 +#define SEND_TYPE_ARG1 int +#endif + +#ifndef SEND_TYPE_ARG2 +#define SEND_TYPE_ARG2 void * +#endif + +#ifndef SEND_TYPE_ARG3 +#define SEND_TYPE_ARG3 size_t +#endif + +#ifndef SEND_TYPE_ARG4 +#define SEND_TYPE_ARG4 int +#endif + +#ifndef SEND_TYPE_RETV +#define SEND_TYPE_RETV ssize_t +#endif + +#endif /* HEADER_CURL_FUNCTYPES_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/getenv.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/getenv.c new file mode 100644 index 0000000000..a957e6e801 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/getenv.c @@ -0,0 +1,69 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +char *curl_getenv(const char *variable) +{ +#if defined(CURL_WINDOWS_UWP) || \ + defined(__ORBIS__) || defined(__PROSPERO__) /* PlayStation 4 and 5 */ + (void)variable; + return NULL; +#elif defined(_WIN32) + /* This uses Windows API instead of C runtime getenv() to get the environment + variable since some changes are not always visible to the latter. #4774 */ + char *buf = NULL; + char *tmp; + DWORD bufsize; + DWORD rc = 1; + const DWORD max = 32768; /* max env var size from MSCRT source */ + + for(;;) { + tmp = curlx_realloc(buf, rc); + if(!tmp) { + curlx_free(buf); + return NULL; + } + + buf = tmp; + bufsize = rc; + + /* it is possible for rc to be 0 if the variable was found but empty. + Since getenv does not make that distinction we ignore it as well. */ + rc = GetEnvironmentVariableA(variable, buf, bufsize); + if(!rc || rc == bufsize || rc > max) { + curlx_free(buf); + return NULL; + } + + /* if rc < bufsize then rc is bytes written not including null */ + if(rc < bufsize) + return buf; + + /* else rc is bytes needed, try again */ + } +#else + char *env = getenv(variable); + return (env && env[0]) ? curlx_strdup(env) : NULL; +#endif +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/getinfo.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/getinfo.c new file mode 100644 index 0000000000..23f1de270c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/getinfo.c @@ -0,0 +1,672 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "getinfo.h" +#include "cfilters.h" +#include "vtls/vtls.h" +#include "connect.h" /* Curl_getconnectinfo() */ +#include "bufref.h" +#include "curlx/strparse.h" + +/* + * Initialize statistical and informational data. + * + * This function is called in curl_easy_reset, curl_easy_duphandle and at the + * beginning of a perform session. It must reset the session-info variables, + * in particular all variables in struct PureInfo. + */ +void Curl_initinfo(struct Curl_easy *data) +{ + struct Progress *pro = &data->progress; + struct PureInfo *info = &data->info; + + memset(&pro->delta, 0, sizeof(pro->delta)); + memset(&pro->total, 0, sizeof(pro->total)); + pro->startransfer_added = FALSE; + + info->httpcode = 0; + info->httpproxycode = 0; + info->httpversion = 0; + info->filetime = -1; /* -1 is an illegal time and thus means unknown */ + info->timecond = FALSE; + + info->header_size = 0; + info->request_size = 0; + info->proxyauthavail = 0; + info->httpauthavail = 0; + info->proxyauthpicked = 0; + info->httpauthpicked = 0; + info->numconnects = 0; + + curlx_safefree(info->contenttype); + curlx_safefree(info->wouldredirect); + + memset(&info->primary, 0, sizeof(info->primary)); + info->retry_after = 0; + + info->conn_scheme = 0; + info->conn_protocol = 0; + info->used_proxy = 0; + +#ifdef USE_SSL + Curl_ssl_free_certinfo(data); +#endif +} + +static CURLcode getinfo_char(struct Curl_easy *data, CURLINFO info, + const char **param_charp) +{ + switch(info) { + case CURLINFO_EFFECTIVE_URL: { + const char *s = Curl_bufref_ptr(&data->state.url); + *param_charp = s ? s : ""; + } + break; + case CURLINFO_EFFECTIVE_METHOD: { + const char *m = CURL_EASY_STR(data, STRING_CUSTOMREQUEST); + if(!m) { + if(data->set.opt_no_body) + m = "HEAD"; +#ifndef CURL_DISABLE_HTTP + else { + switch(data->state.httpreq) { + case HTTPREQ_POST: + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + m = "POST"; + break; + case HTTPREQ_PUT: + m = "PUT"; + break; + default: /* this should never happen */ + case HTTPREQ_GET: + m = "GET"; + break; + case HTTPREQ_HEAD: + m = "HEAD"; + break; + } + } +#endif + } + *param_charp = m; + } + break; + case CURLINFO_CONTENT_TYPE: + *param_charp = data->info.contenttype; + break; + case CURLINFO_PRIVATE: + *param_charp = (const char *)data->set.private_data; + break; + case CURLINFO_FTP_ENTRY_PATH: + /* Return the entrypath string from the most recent connection. + This pointer was copied from the connectdata structure by FTP. + The actual string may be freed by subsequent libcurl calls so + it must be copied to a safer area before the next libcurl call. + Callers must never free it themselves. */ + *param_charp = data->state.most_recent_ftp_entrypath; + break; + case CURLINFO_REDIRECT_URL: + /* Return the URL this request would have been redirected to if that + option had been enabled! */ + *param_charp = data->info.wouldredirect; + break; + case CURLINFO_REFERER: + /* Return the referrer header for this request, or NULL if unset */ + *param_charp = Curl_bufref_ptr(&data->state.referer); + break; + case CURLINFO_PRIMARY_IP: + /* Return the ip address of the most recent (primary) connection */ + *param_charp = data->info.primary.remote_ip; + break; + case CURLINFO_LOCAL_IP: + /* Return the source/local ip address of the most recent (primary) + connection */ + *param_charp = data->info.primary.local_ip; + break; + case CURLINFO_RTSP_SESSION_ID: +#ifndef CURL_DISABLE_RTSP + *param_charp = CURL_EASY_STR(data, STRING_RTSP_SESSION_ID); +#else + *param_charp = NULL; +#endif + break; + case CURLINFO_SCHEME: + *param_charp = data->info.conn_scheme; + break; + case CURLINFO_CAPATH: +#ifdef CURL_CA_PATH + *param_charp = CURL_CA_PATH; +#else + *param_charp = NULL; +#endif + break; + case CURLINFO_CAINFO: +#ifdef CURL_CA_BUNDLE + *param_charp = CURL_CA_BUNDLE; +#else + *param_charp = NULL; +#endif + break; + default: + return CURLE_UNKNOWN_OPTION; + } + + return CURLE_OK; +} + +static CURLcode getinfo_long(struct Curl_easy *data, CURLINFO info, + long *param_longp) +{ + curl_socket_t sockfd; + + union { + unsigned long *to_ulong; + long *to_long; + } lptr; + +#ifdef DEBUGBUILD + const char *envstr; + + /* use another variable for this to allow different values */ + switch(info) { + case CURLINFO_LOCAL_PORT: + envstr = getenv("CURL_TIME"); + if(envstr) { + curl_off_t val; + curlx_str_number(&envstr, &val, TIME_T_MAX); + *param_longp = (long)val; + return CURLE_OK; + } + break; + case CURLINFO_HEADER_SIZE: + case CURLINFO_REQUEST_SIZE: + envstr = getenv("CURL_DEBUG_SIZE"); + if(envstr) { + curl_off_t val; + curlx_str_number(&envstr, &val, LONG_MAX); + *param_longp = (long)val; + return CURLE_OK; + } + break; + default: + break; + } +#endif + + switch(info) { + case CURLINFO_RESPONSE_CODE: + *param_longp = data->info.httpcode; + break; + case CURLINFO_HTTP_CONNECTCODE: + *param_longp = data->info.httpproxycode; + break; + case CURLINFO_FILETIME: + if(data->info.filetime > LONG_MAX) + *param_longp = LONG_MAX; +#if !defined(MSDOS) && !defined(__AMIGA__) + else if(data->info.filetime < LONG_MIN) + *param_longp = LONG_MIN; +#endif + else + *param_longp = (long)data->info.filetime; + break; + case CURLINFO_HEADER_SIZE: + *param_longp = (long)data->info.header_size; + break; + case CURLINFO_REQUEST_SIZE: + *param_longp = (long)data->info.request_size; + break; + case CURLINFO_SSL_VERIFYRESULT: + *param_longp = data->set.ssl.certverifyresult; + break; + case CURLINFO_PROXY_SSL_VERIFYRESULT: +#ifndef CURL_DISABLE_PROXY + *param_longp = data->set.proxy_ssl.certverifyresult; +#else + *param_longp = 0; +#endif + break; + case CURLINFO_REDIRECT_COUNT: + *param_longp = data->state.followlocation; + break; + case CURLINFO_HTTPAUTH_AVAIL: + lptr.to_long = param_longp; + *lptr.to_ulong = data->info.httpauthavail; + break; + case CURLINFO_PROXYAUTH_AVAIL: + lptr.to_long = param_longp; + *lptr.to_ulong = data->info.proxyauthavail; + break; + case CURLINFO_HTTPAUTH_USED: + lptr.to_long = param_longp; + *lptr.to_ulong = data->info.httpauthpicked; + break; + case CURLINFO_PROXYAUTH_USED: + lptr.to_long = param_longp; + *lptr.to_ulong = data->info.proxyauthpicked; + break; + case CURLINFO_OS_ERRNO: + *param_longp = data->state.os_errno; + break; + case CURLINFO_NUM_CONNECTS: +#if SIZEOF_LONG < SIZEOF_CURL_OFF_T + if(data->info.numconnects > LONG_MAX) + *param_longp = LONG_MAX; + else +#endif + *param_longp = (long)data->info.numconnects; + break; + case CURLINFO_LASTSOCKET: + sockfd = Curl_getconnectinfo(data, NULL); + + /* note: this is not a good conversion for systems with 64-bit sockets and + 32-bit longs */ + if(sockfd != CURL_SOCKET_BAD) + *param_longp = (long)sockfd; + else + /* this interface is documented to return -1 in case of badness, which + may not be the same as the CURL_SOCKET_BAD value */ + *param_longp = -1; + break; + case CURLINFO_PRIMARY_PORT: + /* Return the (remote) port of the most recent (primary) connection */ + if(CUR_IP_QUAD_HAS_PORTS(&data->info.primary)) + *param_longp = data->info.primary.remote_port; + else + *param_longp = -1; + break; + case CURLINFO_LOCAL_PORT: + /* Return the local port of the most recent (primary) connection */ + if(CUR_IP_QUAD_HAS_PORTS(&data->info.primary)) + *param_longp = data->info.primary.local_port; + else + *param_longp = -1; + break; + case CURLINFO_PROXY_ERROR: + *param_longp = (long)data->info.pxcode; + break; + case CURLINFO_CONDITION_UNMET: + if(data->info.httpcode == 304) + *param_longp = 1L; + else + /* return if the condition prevented the document to get transferred */ + *param_longp = data->info.timecond ? 1L : 0L; + break; +#ifndef CURL_DISABLE_RTSP + case CURLINFO_RTSP_CLIENT_CSEQ: + *param_longp = data->state.rtsp_next_client_CSeq; + break; + case CURLINFO_RTSP_SERVER_CSEQ: + *param_longp = data->state.rtsp_next_server_CSeq; + break; + case CURLINFO_RTSP_CSEQ_RECV: + *param_longp = data->state.rtsp_CSeq_recv; + break; +#else + case CURLINFO_RTSP_CLIENT_CSEQ: + case CURLINFO_RTSP_SERVER_CSEQ: + case CURLINFO_RTSP_CSEQ_RECV: + *param_longp = 0; + break; +#endif + case CURLINFO_HTTP_VERSION: + switch(data->info.httpversion) { + case 10: + *param_longp = CURL_HTTP_VERSION_1_0; + break; + case 11: + *param_longp = CURL_HTTP_VERSION_1_1; + break; + case 20: + *param_longp = CURL_HTTP_VERSION_2_0; + break; + case 30: + *param_longp = CURL_HTTP_VERSION_3; + break; + default: + *param_longp = CURL_HTTP_VERSION_NONE; + break; + } + break; + case CURLINFO_PROTOCOL: + *param_longp = (long)data->info.conn_protocol; + break; + case CURLINFO_USED_PROXY: + *param_longp = +#ifdef CURL_DISABLE_PROXY + 0 +#else + data->info.used_proxy +#endif + ; + break; + default: + return CURLE_UNKNOWN_OPTION; + } + + return CURLE_OK; +} + +#define DOUBLE_SECS(x) ((double)(x) / 1000000) + +static CURLcode getinfo_offt(struct Curl_easy *data, CURLINFO info, + curl_off_t *param_offt) +{ +#ifdef DEBUGBUILD + const char *envstr; + switch(info) { + case CURLINFO_TOTAL_TIME_T: + case CURLINFO_NAMELOOKUP_TIME_T: + case CURLINFO_CONNECT_TIME_T: + case CURLINFO_APPCONNECT_TIME_T: + case CURLINFO_PRETRANSFER_TIME_T: + case CURLINFO_POSTTRANSFER_TIME_T: + case CURLINFO_QUEUE_TIME_T: + case CURLINFO_STARTTRANSFER_TIME_T: + case CURLINFO_REDIRECT_TIME_T: + case CURLINFO_SPEED_DOWNLOAD_T: + case CURLINFO_SPEED_UPLOAD_T: + envstr = getenv("CURL_TIME"); + if(envstr) { + curl_off_t val; + curlx_str_number(&envstr, &val, CURL_OFF_T_MAX); + *param_offt = (curl_off_t)val; + return CURLE_OK; + } + break; + default: + break; + } +#endif + switch(info) { + case CURLINFO_FILETIME_T: + *param_offt = (curl_off_t)data->info.filetime; + break; + case CURLINFO_SIZE_DELIVERED: + *param_offt = data->progress.deliver; + break; + case CURLINFO_SIZE_UPLOAD_T: + *param_offt = data->progress.ul.cur_size; + break; + case CURLINFO_SIZE_DOWNLOAD_T: + *param_offt = data->progress.dl.cur_size; + break; + case CURLINFO_SPEED_DOWNLOAD_T: + *param_offt = data->progress.dl.speed; + break; + case CURLINFO_SPEED_UPLOAD_T: + *param_offt = data->progress.ul.speed; + break; + case CURLINFO_CONTENT_LENGTH_DOWNLOAD_T: + *param_offt = data->progress.dl_size_known ? + data->progress.dl.total_size : -1; + break; + case CURLINFO_CONTENT_LENGTH_UPLOAD_T: + *param_offt = data->progress.ul_size_known ? + data->progress.ul.total_size : -1; + break; + case CURLINFO_TOTAL_TIME_T: + *param_offt = data->progress.total.spent_us; + break; + case CURLINFO_NAMELOOKUP_TIME_T: + *param_offt = data->progress.total.nslookup_us; + break; + case CURLINFO_CONNECT_TIME_T: + *param_offt = data->progress.total.connect_us; + break; + case CURLINFO_APPCONNECT_TIME_T: + *param_offt = data->progress.total.appconnect_us; + break; + case CURLINFO_PRETRANSFER_TIME_T: + *param_offt = data->progress.total.pretransfer_us; + break; + case CURLINFO_POSTTRANSFER_TIME_T: + *param_offt = data->progress.total.posttransfer_us; + break; + case CURLINFO_STARTTRANSFER_TIME_T: + *param_offt = data->progress.total.starttransfer_us; + break; + case CURLINFO_QUEUE_TIME_T: + *param_offt = data->progress.total.queued_us; + break; + case CURLINFO_REDIRECT_TIME_T: + *param_offt = data->progress.delta.startredirect_us; + break; + case CURLINFO_RETRY_AFTER: + *param_offt = data->info.retry_after; + break; + case CURLINFO_XFER_ID: + *param_offt = data->id; + break; + case CURLINFO_CONN_ID: + *param_offt = data->state.lastconnect_id; + break; + case CURLINFO_EARLYDATA_SENT_T: + *param_offt = data->progress.earlydata_sent; + break; + default: + return CURLE_UNKNOWN_OPTION; + } + + return CURLE_OK; +} + +static CURLcode getinfo_double(struct Curl_easy *data, CURLINFO info, + double *param_doublep) +{ +#ifdef DEBUGBUILD + const char *envstr; + + switch(info) { + case CURLINFO_TOTAL_TIME: + case CURLINFO_NAMELOOKUP_TIME: + case CURLINFO_CONNECT_TIME: + case CURLINFO_APPCONNECT_TIME: + case CURLINFO_PRETRANSFER_TIME: + case CURLINFO_STARTTRANSFER_TIME: + case CURLINFO_REDIRECT_TIME: + case CURLINFO_SPEED_DOWNLOAD: + case CURLINFO_SPEED_UPLOAD: + envstr = getenv("CURL_TIME"); + if(envstr) { + curl_off_t val; + curlx_str_number(&envstr, &val, CURL_OFF_T_MAX); + *param_doublep = (double)val; + return CURLE_OK; + } + break; + default: + break; + } +#endif + switch(info) { + case CURLINFO_TOTAL_TIME: + *param_doublep = DOUBLE_SECS(data->progress.total.spent_us); + break; + case CURLINFO_NAMELOOKUP_TIME: + *param_doublep = DOUBLE_SECS(data->progress.total.nslookup_us); + break; + case CURLINFO_CONNECT_TIME: + *param_doublep = DOUBLE_SECS(data->progress.total.connect_us); + break; + case CURLINFO_APPCONNECT_TIME: + *param_doublep = DOUBLE_SECS(data->progress.total.appconnect_us); + break; + case CURLINFO_PRETRANSFER_TIME: + *param_doublep = DOUBLE_SECS(data->progress.total.pretransfer_us); + break; + case CURLINFO_STARTTRANSFER_TIME: + *param_doublep = DOUBLE_SECS(data->progress.total.starttransfer_us); + break; + case CURLINFO_SIZE_UPLOAD: + *param_doublep = (double)data->progress.ul.cur_size; + break; + case CURLINFO_SIZE_DOWNLOAD: + *param_doublep = (double)data->progress.dl.cur_size; + break; + case CURLINFO_SPEED_DOWNLOAD: + *param_doublep = (double)data->progress.dl.speed; + break; + case CURLINFO_SPEED_UPLOAD: + *param_doublep = (double)data->progress.ul.speed; + break; + case CURLINFO_CONTENT_LENGTH_DOWNLOAD: + *param_doublep = data->progress.dl_size_known ? + (double)data->progress.dl.total_size : -1; + break; + case CURLINFO_CONTENT_LENGTH_UPLOAD: + *param_doublep = data->progress.ul_size_known ? + (double)data->progress.ul.total_size : -1; + break; + case CURLINFO_REDIRECT_TIME: + *param_doublep = DOUBLE_SECS(data->progress.delta.startredirect_us); + break; + + default: + return CURLE_UNKNOWN_OPTION; + } + + return CURLE_OK; +} + +static CURLcode getinfo_slist(struct Curl_easy *data, CURLINFO info, + struct curl_slist **param_slistp) +{ + union { + struct curl_certinfo *to_certinfo; + struct curl_slist *to_slist; + } ptr; + + switch(info) { + case CURLINFO_SSL_ENGINES: + *param_slistp = Curl_ssl_engines_list(data); + break; + case CURLINFO_COOKIELIST: + *param_slistp = Curl_cookie_list(data); + break; + case CURLINFO_CERTINFO: + /* Return the a pointer to the certinfo struct. Not really an slist + pointer but we can pretend it is here */ + ptr.to_certinfo = &data->info.certs; + *param_slistp = ptr.to_slist; + break; + case CURLINFO_TLS_SESSION: + case CURLINFO_TLS_SSL_PTR: { + int query = (info == CURLINFO_TLS_SSL_PTR) ? + CF_QUERY_SSL_INFO : CF_QUERY_SSL_CTX_INFO; + struct curl_tlssessioninfo **tsip = (struct curl_tlssessioninfo **) + param_slistp; + struct curl_tlssessioninfo *tsi = &data->tsi; + + /* we are exposing a pointer to internal memory with unknown + * lifetime here. */ + *tsip = tsi; + if(!Curl_conn_get_ssl_info(data, data->conn, FIRSTSOCKET, query, tsi)) { + tsi->backend = Curl_ssl_backend(); + tsi->internals = NULL; + } + } + break; + default: + return CURLE_UNKNOWN_OPTION; + } + + return CURLE_OK; +} + +static CURLcode getinfo_socket(struct Curl_easy *data, CURLINFO info, + curl_socket_t *param_socketp) +{ + switch(info) { + case CURLINFO_ACTIVESOCKET: + *param_socketp = Curl_getconnectinfo(data, NULL); + break; + default: + return CURLE_UNKNOWN_OPTION; + } + + return CURLE_OK; +} + +CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...) +{ + va_list arg; + long *param_longp = NULL; + double *param_doublep = NULL; + curl_off_t *param_offt = NULL; + const char **param_charp = NULL; + struct curl_slist **param_slistp = NULL; + curl_socket_t *param_socketp = NULL; + int type; + CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT; + + if(!data) + return CURLE_BAD_FUNCTION_ARGUMENT; + + va_start(arg, info); + + type = CURLINFO_TYPEMASK & (int)info; + switch(type) { + case CURLINFO_STRING: + param_charp = va_arg(arg, const char **); + if(param_charp) + result = getinfo_char(data, info, param_charp); + break; + case CURLINFO_LONG: + param_longp = va_arg(arg, long *); + if(param_longp) + result = getinfo_long(data, info, param_longp); + break; + case CURLINFO_DOUBLE: + param_doublep = va_arg(arg, double *); + if(param_doublep) + result = getinfo_double(data, info, param_doublep); + break; + case CURLINFO_OFF_T: + param_offt = va_arg(arg, curl_off_t *); + if(param_offt) + result = getinfo_offt(data, info, param_offt); + break; + case CURLINFO_SLIST: + param_slistp = va_arg(arg, struct curl_slist **); + if(param_slistp) + result = getinfo_slist(data, info, param_slistp); + break; + case CURLINFO_SOCKET: + param_socketp = va_arg(arg, curl_socket_t *); + if(param_socketp) + result = getinfo_socket(data, info, param_socketp); + break; + default: + result = CURLE_UNKNOWN_OPTION; + break; + } + + va_end(arg); + + return result; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/getinfo.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/getinfo.h new file mode 100644 index 0000000000..f5efe4185c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/getinfo.h @@ -0,0 +1,29 @@ +#ifndef HEADER_CURL_GETINFO_H +#define HEADER_CURL_GETINFO_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...); +void Curl_initinfo(struct Curl_easy *data); + +#endif /* HEADER_CURL_GETINFO_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/gopher.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/gopher.c new file mode 100644 index 0000000000..a5d0a4b0b4 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/gopher.c @@ -0,0 +1,242 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" +#include "gopher.h" + +#ifndef CURL_DISABLE_GOPHER + +#include "transfer.h" +#include "sendf.h" +#include "curl_trc.h" +#include "cfilters.h" +#include "connect.h" +#include "select.h" +#include "url.h" +#include "escape.h" + +#ifdef USE_SSL +static CURLcode gopher_connect(struct Curl_easy *data, bool *done) +{ + (void)data; + (void)done; + return CURLE_OK; +} + +static CURLcode gopher_connecting(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + CURLcode result; + + result = Curl_conn_connect(data, FIRSTSOCKET, TRUE, done); + if(result) + connclose(conn); + *done = TRUE; + return result; +} +#endif + +/* Sends buf to the server and, optionally, writes it to the client too. */ +static CURLcode send_buf(struct Curl_easy *data, + const char *buf, + size_t buf_len, + bool client_write) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; + size_t nwritten; + timediff_t timeout_ms; + int what; + + while(buf_len) { + result = Curl_xfer_send(data, buf, buf_len, FALSE, &nwritten); + if(!result) { /* Which may not have written it all! */ + if(client_write) { + result = Curl_client_write(data, CLIENTWRITE_HEADER, buf, nwritten); + if(result) + break; + } + + if(nwritten > buf_len) { + DEBUGASSERT(0); + break; + } + buf_len -= nwritten; + buf += nwritten; + if(!buf_len) + break; /* but it did write it all */ + } + else + break; + + timeout_ms = Curl_timeleft_ms(data); + if(timeout_ms < 0) { + result = CURLE_OPERATION_TIMEDOUT; + break; + } + if(!timeout_ms) + timeout_ms = TIMEDIFF_T_MAX; + + /* Do not busyloop. The entire loop thing is a workaround as it causes a + BLOCKING behavior which is a NO-NO. This function should rather be + split up in a do and a doing piece where the pieces that are not + possible to send now will be sent in the doing function repeatedly + until the entire request is sent. */ + what = SOCKET_WRITABLE(sockfd, timeout_ms); + if(what < 0) { + result = CURLE_SEND_ERROR; + break; + } + else if(!what) { + result = CURLE_OPERATION_TIMEDOUT; + break; + } + } + + return result; +} + +static CURLcode gopher_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + char *gopherpath; + const char *path = data->state.up.path; + const char *query = data->state.up.query; + const char *buf = NULL; + char *buf_alloc = NULL; + size_t buf_len; + + *done = TRUE; /* unconditionally */ + + /* path is guaranteed non-NULL */ + DEBUGASSERT(path); + + if(query) + gopherpath = curl_maprintf("%s?%s", path, query); + else + gopherpath = curlx_strdup(path); + + if(!gopherpath) + return CURLE_OUT_OF_MEMORY; + + /* Create selector. Degenerate cases: / and /1 => convert to "" */ + if(strlen(gopherpath) <= 2) { + buf = ""; + buf_len = 0; + curlx_free(gopherpath); + } + else { + const char *newp; + + /* Otherwise, drop / and the first character (i.e., item type) ... */ + newp = gopherpath; + newp += 2; + + /* ... and finally unescape */ + result = Curl_urldecode(newp, 0, &buf_alloc, &buf_len, REJECT_ZERO); + curlx_free(gopherpath); + if(result) + return result; + buf = buf_alloc; + + /* A decoded CR or LF would terminate the single-line gopher request and + let a crafted URL smuggle additional bytes onto the wire. REJECT_ZERO + only blocks NUL; reject CR and LF here too. A TAB is left alone as it + is the legitimate gopher type-7 selector/search separator. */ + if(memchr(buf, '\r', buf_len) || memchr(buf, '\n', buf_len)) { + curlx_free(buf_alloc); + failf(data, "Bad gopher selector, CR or LF not allowed"); + return CURLE_URL_MALFORMAT; + } + } + + result = send_buf(data, buf, buf_len, TRUE); + curlx_free(buf_alloc); + + if(!result) + /* Send CRLF to the server now, but defer writing it to the client to + preserve the historical behavior of this file. */ + result = send_buf(data, "\r\n", 2, FALSE); + if(result) { + failf(data, "Failed sending Gopher request"); + return result; + } + result = Curl_client_write(data, CLIENTWRITE_HEADER, "\r\n", 2); + if(result) + return result; + + Curl_xfer_setup_recv(data, FIRSTSOCKET, -1); + return CURLE_OK; +} + +/* + * Gopher protocol handler. + * This is also a nice simple template to build off for simple + * connect-command-download protocols. + */ + +const struct Curl_protocol Curl_protocol_gopher = { + ZERO_NULL, /* setup_connection */ + gopher_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_pollset */ + ZERO_NULL, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#ifdef USE_SSL +const struct Curl_protocol Curl_protocol_gophers = { + ZERO_NULL, /* setup_connection */ + gopher_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + gopher_connect, /* connect_it */ + gopher_connecting, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_pollset */ + ZERO_NULL, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; +#endif + +#endif /* CURL_DISABLE_GOPHER */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/gopher.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/gopher.h new file mode 100644 index 0000000000..1c126be16a --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/gopher.h @@ -0,0 +1,31 @@ +#ifndef HEADER_CURL_GOPHER_H +#define HEADER_CURL_GOPHER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_GOPHER +extern const struct Curl_protocol Curl_protocol_gopher; +extern const struct Curl_protocol Curl_protocol_gophers; +#endif + +#endif /* HEADER_CURL_GOPHER_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/hash.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/hash.c new file mode 100644 index 0000000000..3eae1d26a7 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/hash.c @@ -0,0 +1,388 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "hash.h" + +/* random patterns for API verification */ +#ifdef DEBUGBUILD +#define HASHINIT 0x7017e781 +#define ITERINIT 0x5FEDCBA9 +#endif + +#if 0 /* useful function for debugging hashes and their contents */ +void Curl_hash_print(struct Curl_hash *h, void (*func)(void *)) +{ + struct Curl_hash_iterator iter; + struct Curl_hash_element *he; + size_t last_index = UINT_MAX; + + if(!h) + return; + + curl_mfprintf(stderr, "=Hash dump=\n"); + + Curl_hash_start_iterate(h, &iter); + + he = Curl_hash_next_element(&iter); + while(he) { + if(iter.slot_index != last_index) { + curl_mfprintf(stderr, "index %d:", (int)iter.slot_index); + if(last_index != UINT_MAX) { + curl_mfprintf(stderr, "\n"); + } + last_index = iter.slot_index; + } + + if(func) + func(he->ptr); + else + curl_mfprintf(stderr, " [key=%.*s, he=%p, ptr=%p]", + (int)he->key_len, (char *)he->key, + (void *)he, (void *)he->ptr); + + he = Curl_hash_next_element(&iter); + } + curl_mfprintf(stderr, "\n"); +} +#endif + +/* Initializes a hash structure. + * Return 1 on error, 0 is fine. + * + * @unittest: 1602 + * @unittest: 1603 + */ +void Curl_hash_init(struct Curl_hash *h, + size_t slots, + hash_function hfunc, + comp_function comparator, + Curl_hash_dtor dtor) +{ + DEBUGASSERT(h); + DEBUGASSERT(slots); + DEBUGASSERT(hfunc); + DEBUGASSERT(comparator); + DEBUGASSERT(dtor); + + h->table = NULL; + h->hash_func = hfunc; + h->comp_func = comparator; + h->dtor = dtor; + h->size = 0; + h->slots = slots; +#ifdef DEBUGBUILD + h->init = HASHINIT; +#endif +} + +static struct Curl_hash_element *hash_elem_create(const void *key, + size_t key_len, + const void *p, + Curl_hash_elem_dtor dtor) +{ + struct Curl_hash_element *he; + + /* allocate the struct plus memory after it to store the key */ + he = curlx_malloc(sizeof(struct Curl_hash_element) + key_len); + if(he) { + he->next = NULL; + /* copy the key */ + memcpy(he->key, key, key_len); + he->key_len = key_len; + he->ptr = CURL_UNCONST(p); + he->dtor = dtor; + } + return he; +} + +static void hash_elem_clear_ptr(struct Curl_hash *h, + struct Curl_hash_element *he) +{ + DEBUGASSERT(h); + DEBUGASSERT(he); + if(he->ptr) { + if(he->dtor) + he->dtor(he->key, he->key_len, he->ptr); + else + h->dtor(he->ptr); + he->ptr = NULL; + } +} + +static void hash_elem_destroy(struct Curl_hash *h, + struct Curl_hash_element *he) +{ + hash_elem_clear_ptr(h, he); + curlx_free(he); +} + +static void hash_elem_unlink(struct Curl_hash *h, + struct Curl_hash_element **he_anchor, + struct Curl_hash_element *he) +{ + *he_anchor = he->next; + --h->size; +} + +static void hash_elem_link(struct Curl_hash *h, + struct Curl_hash_element **he_anchor, + struct Curl_hash_element *he) +{ + he->next = *he_anchor; + *he_anchor = he; + ++h->size; +} + +#define CURL_HASH_SLOT(x, y, z) x->table[(x)->hash_func(y, z, (x)->slots)] +#define CURL_HASH_SLOT_ADDR(x, y, z) &CURL_HASH_SLOT(x, y, z) + +void *Curl_hash_add2(struct Curl_hash *h, void *key, size_t key_len, void *p, + Curl_hash_elem_dtor dtor) +{ + struct Curl_hash_element *he, **slot; + + DEBUGASSERT(h); + DEBUGASSERT(h->slots); + DEBUGASSERT(h->init == HASHINIT); + if(!h->table) { + h->table = curlx_calloc(h->slots, sizeof(struct Curl_hash_element *)); + if(!h->table) + return NULL; /* OOM */ + } + + slot = CURL_HASH_SLOT_ADDR(h, key, key_len); + for(he = *slot; he; he = he->next) { + if(h->comp_func(he->key, he->key_len, key, key_len)) { + /* existing key entry, overwrite by clearing old pointer */ + hash_elem_clear_ptr(h, he); + he->ptr = p; + he->dtor = dtor; + return p; + } + } + + he = hash_elem_create(key, key_len, p, dtor); + if(!he) + return NULL; /* OOM */ + + hash_elem_link(h, slot, he); + return p; /* return the new entry */ +} + +/* Insert the data in the hash. If there already was a match in the hash, that + * data is replaced. This function also "lazily" allocates the table if + * needed, as it is not done in the _init function (anymore). + * + * @unittest: 1305 + * @unittest: 1602 + * @unittest: 1603 + */ +void *Curl_hash_add(struct Curl_hash *h, void *key, size_t key_len, void *p) +{ + return Curl_hash_add2(h, key, key_len, p, NULL); +} + +/* Remove the identified hash entry. + * Returns non-zero on failure. + * + * @unittest: 1603 + */ +int Curl_hash_delete(struct Curl_hash *h, void *key, size_t key_len) +{ + DEBUGASSERT(h); + DEBUGASSERT(h->slots); + DEBUGASSERT(h->init == HASHINIT); + if(h->table) { + struct Curl_hash_element *he, **he_anchor; + + he_anchor = CURL_HASH_SLOT_ADDR(h, key, key_len); + while(*he_anchor) { + he = *he_anchor; + if(h->comp_func(he->key, he->key_len, key, key_len)) { + hash_elem_unlink(h, he_anchor, he); + hash_elem_destroy(h, he); + return 0; + } + he_anchor = &he->next; + } + } + return 1; +} + +/* Retrieves a hash element. + * + * @unittest: 1603 + */ +void *Curl_hash_pick(struct Curl_hash *h, void *key, size_t key_len) +{ + DEBUGASSERT(h); + DEBUGASSERT(h->init == HASHINIT); + if(h->table) { + struct Curl_hash_element *he; + DEBUGASSERT(h->slots); + he = CURL_HASH_SLOT(h, key, key_len); + while(he) { + if(h->comp_func(he->key, he->key_len, key, key_len)) { + return he->ptr; + } + he = he->next; + } + } + return NULL; +} + +/* Destroys all the entries in the given hash and resets its attributes, + * prepping the given hash for [static|dynamic] deallocation. + * + * @unittest: 1305 + * @unittest: 1602 + * @unittest: 1603 + */ +void Curl_hash_destroy(struct Curl_hash *h) +{ + DEBUGASSERT(h->init == HASHINIT); + if(h->table) { + Curl_hash_clean(h); + curlx_safefree(h->table); + } + DEBUGASSERT(h->size == 0); + h->slots = 0; +} + +/* Removes all the entries in the given hash. + * + * @unittest: 1602 + */ +void Curl_hash_clean(struct Curl_hash *h) +{ + if(h && h->table) { + struct Curl_hash_element *he, **he_anchor; + size_t i; + DEBUGASSERT(h->init == HASHINIT); + for(i = 0; i < h->slots; ++i) { + he_anchor = &h->table[i]; + while(*he_anchor) { + he = *he_anchor; + hash_elem_unlink(h, he_anchor, he); + hash_elem_destroy(h, he); + } + } + } +} + +size_t Curl_hash_count(struct Curl_hash *h) +{ + DEBUGASSERT(h->init == HASHINIT); + return h->size; +} + +/* Cleans all entries that pass the comp function criteria. */ +void Curl_hash_clean_with_criterium(struct Curl_hash *h, void *user, + int (*comp)(void *, void *)) +{ + size_t i; + + if(!h || !h->table) + return; + + DEBUGASSERT(h->init == HASHINIT); + for(i = 0; i < h->slots; ++i) { + struct Curl_hash_element *he, **he_anchor = &h->table[i]; + while(*he_anchor) { + /* ask the callback function if we shall remove this entry or not */ + if(!comp || comp(user, (*he_anchor)->ptr)) { + he = *he_anchor; + hash_elem_unlink(h, he_anchor, he); + hash_elem_destroy(h, he); + } + else + he_anchor = &(*he_anchor)->next; + } + } +} + +size_t Curl_hash_str(void *key, size_t key_length, size_t slots_num) +{ + const char *key_str = (const char *)key; + const char *end = key_str + key_length; + size_t h = 5381; + + while(key_str < end) { + size_t j = (size_t)*key_str++; + h += h << 5; + h ^= j; + } + + return (h % slots_num); +} + +size_t curlx_str_key_compare(void *k1, size_t key1_len, + void *k2, size_t key2_len) +{ + if((key1_len == key2_len) && !memcmp(k1, k2, key1_len)) + return 1; + + return 0; +} + +void Curl_hash_start_iterate(struct Curl_hash *hash, + struct Curl_hash_iterator *iter) +{ + DEBUGASSERT(hash->init == HASHINIT); + iter->hash = hash; + iter->slot_index = 0; + iter->current = NULL; +#ifdef DEBUGBUILD + iter->init = ITERINIT; +#endif +} + +struct Curl_hash_element *Curl_hash_next_element( + struct Curl_hash_iterator *iter) +{ + struct Curl_hash *h; + DEBUGASSERT(iter->init == ITERINIT); + h = iter->hash; + if(!h->table) + return NULL; /* empty hash, nothing to return */ + + /* Get the next element in the current list, if any */ + if(iter->current) + iter->current = iter->current->next; + + /* If we have reached the end of the list, find the next one */ + if(!iter->current) { + size_t i; + for(i = iter->slot_index; i < h->slots; i++) { + if(h->table[i]) { + iter->current = h->table[i]; + iter->slot_index = i + 1; + break; + } + } + } + + return iter->current; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/hash.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/hash.h new file mode 100644 index 0000000000..d4c73b7786 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/hash.h @@ -0,0 +1,105 @@ +#ifndef HEADER_CURL_HASH_H +#define HEADER_CURL_HASH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* Hash function prototype */ +typedef size_t (*hash_function)(void *key, + size_t key_length, + size_t slots_num); + +/* + * Comparator function prototype. Compares two keys. + */ +typedef size_t (*comp_function)(void *key1, + size_t key1_len, + void *key2, + size_t key2_len); + +typedef void (*Curl_hash_dtor)(void *); + +typedef void (*Curl_hash_elem_dtor)(void *key, size_t key_len, void *p); + +struct Curl_hash_element { + struct Curl_hash_element *next; + void *ptr; + Curl_hash_elem_dtor dtor; + size_t key_len; + char key[1]; /* allocated memory following the struct */ +}; + +struct Curl_hash { + struct Curl_hash_element **table; + + /* Hash function to be used for this hash table */ + hash_function hash_func; + /* Comparator function to compare keys */ + comp_function comp_func; + /* General element construct, unless element itself carries one */ + Curl_hash_dtor dtor; + size_t slots; + size_t size; +#ifdef DEBUGBUILD + int init; +#endif +}; + +struct Curl_hash_iterator { + struct Curl_hash *hash; + size_t slot_index; + struct Curl_hash_element *current; +#ifdef DEBUGBUILD + int init; +#endif +}; + +void Curl_hash_init(struct Curl_hash *h, + size_t slots, + hash_function hfunc, + comp_function comparator, + Curl_hash_dtor dtor); + +void *Curl_hash_add(struct Curl_hash *h, void *key, size_t key_len, void *p); +void *Curl_hash_add2(struct Curl_hash *h, void *key, size_t key_len, void *p, + Curl_hash_elem_dtor dtor); +int Curl_hash_delete(struct Curl_hash *h, void *key, size_t key_len); +void *Curl_hash_pick(struct Curl_hash *h, void *key, size_t key_len); + +void Curl_hash_destroy(struct Curl_hash *h); +size_t Curl_hash_count(struct Curl_hash *h); +void Curl_hash_clean(struct Curl_hash *h); +void Curl_hash_clean_with_criterium(struct Curl_hash *h, void *user, + int (*comp)(void *, void *)); +size_t Curl_hash_str(void *key, size_t key_length, size_t slots_num); +size_t curlx_str_key_compare(void *k1, size_t key1_len, void *k2, + size_t key2_len); +void Curl_hash_start_iterate(struct Curl_hash *hash, + struct Curl_hash_iterator *iter); +struct Curl_hash_element *Curl_hash_next_element( + struct Curl_hash_iterator *iter); + +void Curl_hash_print(struct Curl_hash *h, void (*func)(void *)); + +#endif /* HEADER_CURL_HASH_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/headers.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/headers.c new file mode 100644 index 0000000000..a6416b0f07 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/headers.c @@ -0,0 +1,425 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "sendf.h" +#include "curl_trc.h" +#include "headers.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HEADERS_API) + +/* Generate the curl_header struct for the user. This function MUST assign all + struct fields in the output struct. */ +static void copy_header_external(struct Curl_header_store *hs, + size_t index, + size_t amount, + struct Curl_llist_node *e, + struct curl_header *hout) +{ + struct curl_header *h = hout; + h->name = hs->name; + h->value = hs->value; + h->amount = amount; + h->index = index; + /* this will randomly OR a reserved bit for the sole purpose of making it + impossible for applications to do == comparisons, as that would otherwise + be tempting and then lead to the reserved bits not being reserved + anymore. */ + h->origin = (unsigned int)(hs->type | (1 << 27)); + h->anchor = e; +} + +/* public API */ +CURLHcode curl_easy_header(CURL *curl, + const char *name, + size_t nameindex, + unsigned int origin, + int request, + struct curl_header **hout) +{ + struct Curl_eapi_guard guard; + CURLHcode hresult = CURLHE_OK; + CURLcode result; + + if(CURL_EAPI_ENTER(&guard, curl, easy_header, &result)) { + struct Curl_easy *data = curl; + struct Curl_llist_node *e; + struct Curl_llist_node *e_pick = NULL; + size_t match = 0; + size_t amount = 0; + struct Curl_header_store *hs = NULL; + struct Curl_header_store *pick = NULL; + if(!name || !hout || !data || + (origin > (CURLH_HEADER | CURLH_TRAILER | CURLH_CONNECT | CURLH_1XX | + CURLH_PSEUDO)) || !origin || (request < -1)) { + hresult = CURLHE_BAD_ARGUMENT; + goto out; + } + if(!Curl_llist_count(&data->state.httphdrs)) { + hresult = CURLHE_NOHEADERS; /* no headers available */ + goto out; + } + if(request > data->state.requests) { + hresult = CURLHE_NOREQUEST; + goto out; + } + if(request == -1) + request = data->state.requests; + + /* we need a first round to count amount of this header */ + for(e = Curl_llist_head(&data->state.httphdrs); e; e = Curl_node_next(e)) { + hs = Curl_node_elem(e); + if(curl_strequal(hs->name, name) && + (hs->type & origin) && + (hs->request == request)) { + amount++; + pick = hs; + e_pick = e; + } + } + if(!amount) + hresult = CURLHE_MISSING; + else if(nameindex >= amount) + hresult = CURLHE_BADINDEX; + if(hresult) + goto out; + + if(nameindex == amount - 1) + /* if the last or only occurrence is what's asked for, then we know it */ + hs = pick; + else { + for(e = Curl_llist_head(&data->state.httphdrs); e; + e = Curl_node_next(e)) { + hs = Curl_node_elem(e); + if(curl_strequal(hs->name, name) && + (hs->type & origin) && + (hs->request == request) && + (match++ == nameindex)) { + e_pick = e; + break; + } + } + if(!e) { /* this should not happen */ + hresult = CURLHE_MISSING; + goto out; + } + } + /* this is the name we want */ + copy_header_external(hs, nameindex, amount, e_pick, + &data->state.headerout[0]); + *hout = &data->state.headerout[0]; + hresult = CURLHE_OK; + } +out: + CURL_EAPI_LEAVE(&guard); + if(result) + hresult = Curl_eapi_hcode(result); + return hresult; +} + +/* public API */ +struct curl_header *curl_easy_nextheader(CURL *curl, + unsigned int origin, + int request, + struct curl_header *prev) +{ + struct Curl_eapi_guard guard; + struct curl_header *hd = NULL; + CURLcode result; + + if(CURL_EAPI_ENTER(&guard, curl, easy_nextheader, &result)) { + struct Curl_easy *data = curl; + struct Curl_llist_node *pick; + struct Curl_llist_node *e; + struct Curl_header_store *hs; + size_t amount = 0; + size_t index = 0; + + if(request > data->state.requests) + goto out; + if(request == -1) + request = data->state.requests; + + if(prev) { + pick = prev->anchor; + if(!pick) + /* something is wrong */ + goto out; + pick = Curl_node_next(pick); + } + else + pick = Curl_llist_head(&data->state.httphdrs); + + if(pick) { + /* make sure it is the next header of the desired type */ + do { + hs = Curl_node_elem(pick); + if((hs->type & origin) && (hs->request == request)) + break; + pick = Curl_node_next(pick); + } while(pick); + } + + if(!pick) + /* no more headers available */ + goto out; + + hs = Curl_node_elem(pick); + + /* count number of occurrences of this name within the mask and figure out + the index for the currently selected entry */ + for(e = Curl_llist_head(&data->state.httphdrs); e; e = Curl_node_next(e)) { + struct Curl_header_store *check = Curl_node_elem(e); + if(curl_strequal(hs->name, check->name) && + (check->request == request) && + (check->type & origin)) + amount++; + if(e == pick) + index = amount - 1; + } + + copy_header_external(hs, index, amount, pick, + &data->state.headerout[1]); + hd = &data->state.headerout[1]; + } +out: + CURL_EAPI_LEAVE(&guard); + return hd; +} + +static CURLcode namevalue(char *header, size_t hlen, unsigned int type, + char **name, char **value) +{ + char *end = header + hlen - 1; /* point to the last byte */ + DEBUGASSERT(hlen); + *name = header; + + if(type == CURLH_PSEUDO) { + if(*header != ':') + return CURLE_BAD_FUNCTION_ARGUMENT; + header++; + } + + /* Find the end of the header name */ + while(*header && (*header != ':')) + ++header; + + if(*header) + /* Skip over colon, null it */ + *header++ = 0; + else + return CURLE_BAD_FUNCTION_ARGUMENT; + + /* skip all leading blank letters */ + while(ISBLANK(*header)) + header++; + + *value = header; + + /* skip all trailing space letters */ + while((end > header) && ISBLANK(*end)) + *end-- = 0; /* null-terminate */ + return CURLE_OK; +} + +/* + * Curl_headers_push() gets passed a full HTTP header to store. It gets called + * immediately before the header callback. The header is CRLF, CR or LF + * terminated. + */ +CURLcode Curl_headers_push(struct Curl_easy *data, const char *header, + size_t hlen, /* length of header */ + unsigned char type) +{ + char *value = NULL; + char *name = NULL; + struct Curl_header_store *hs; + CURLcode result = CURLE_OUT_OF_MEMORY; + const size_t ilen = hlen; + + if((header[0] == '\r') || (header[0] == '\n')) + /* ignore the body separator */ + return CURLE_OK; + + /* trim off newline characters */ + if(hlen && (header[hlen - 1] == '\n')) + hlen--; + if(hlen && (header[hlen - 1] == '\r')) + hlen--; + if(hlen == ilen) + /* neither CR nor LF as terminator is not a valid header */ + return CURLE_WEIRD_SERVER_REPLY; + + if(ISBLANK(header[0])) { + /* pass leading blanks */ + while(hlen && ISBLANK(*header)) { + header++; + hlen--; + } + if(!hlen) + return CURLE_WEIRD_SERVER_REPLY; + } + if(Curl_llist_count(&data->state.httphdrs) >= MAX_HTTP_RESP_HEADER_COUNT) { + failf(data, "Too many response headers, %d is max", + MAX_HTTP_RESP_HEADER_COUNT); + return CURLE_TOO_LARGE; + } + + hs = curlx_calloc(1, sizeof(*hs) + hlen); + if(!hs) + return CURLE_OUT_OF_MEMORY; + memcpy(hs->buffer, header, hlen); + hs->buffer[hlen] = 0; /* null-terminate */ + + result = namevalue(hs->buffer, hlen, type, &name, &value); + if(!result) { + hs->name = name; + hs->value = value; + hs->type = type; + hs->request = data->state.requests; + + /* insert this node into the list of headers */ + Curl_llist_append(&data->state.httphdrs, hs, &hs->node); + } + else { + failf(data, "Invalid response header"); + curlx_free(hs); + } + return result; +} + +/* + * Curl_headers_reset(). Reset the headers subsystem. + */ +static void headers_reset(struct Curl_easy *data) +{ + Curl_llist_init(&data->state.httphdrs, NULL); +} + +struct hds_cw_collect_ctx { + struct Curl_cwriter super; +}; + +static CURLcode hds_cw_collect_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t blen) +{ + if((type & CLIENTWRITE_HEADER) && !(type & CLIENTWRITE_STATUS)) { + unsigned char htype = (unsigned char) + (type & CLIENTWRITE_CONNECT ? CURLH_CONNECT : + (type & CLIENTWRITE_1XX ? CURLH_1XX : + (type & CLIENTWRITE_TRAILER ? CURLH_TRAILER : + CURLH_HEADER))); + CURLcode result = Curl_headers_push(data, buf, blen, htype); + CURL_TRC_WRITE(data, "header_collect pushed(type=%x, len=%zu) -> %d", + htype, blen, (int)result); + if(result) + return result; + } + return Curl_cwriter_write(data, writer->next, type, buf, blen); +} + +static const struct Curl_cwtype hds_cw_collect = { + "hds-collect", + NULL, + 0, + Curl_cwriter_def_init, + hds_cw_collect_write, + Curl_cwriter_def_flush, + Curl_cwriter_def_close, + sizeof(struct hds_cw_collect_ctx) +}; + +CURLcode Curl_headers_init(struct Curl_easy *data) +{ + struct Curl_cwriter *writer; + CURLcode result; + + if(data->conn && (data->conn->scheme->protocol & PROTO_FAMILY_HTTP)) { + /* avoid installing it twice */ + if(Curl_cwriter_get_by_name(data, hds_cw_collect.name)) + return CURLE_OK; + + result = Curl_cwriter_create(&writer, data, &hds_cw_collect, + CURL_CW_PROTOCOL); + if(result) + return result; + + result = Curl_cwriter_add(data, writer); + if(result) { + Curl_cwriter_free(data, writer); + return result; + } + } + return CURLE_OK; +} + +/* + * Curl_headers_cleanup(). Free all stored headers and associated memory. + */ +CURLcode Curl_headers_cleanup(struct Curl_easy *data) +{ + struct Curl_llist_node *e; + struct Curl_llist_node *n; + + for(e = Curl_llist_head(&data->state.httphdrs); e; e = n) { + struct Curl_header_store *hs = Curl_node_elem(e); + n = Curl_node_next(e); + curlx_free(hs); + } + headers_reset(data); + return CURLE_OK; +} + +#else /* HTTP-disabled builds below */ + +CURLHcode curl_easy_header(CURL *easy, + const char *name, + size_t index, + unsigned int origin, + int request, + struct curl_header **hout) +{ + (void)easy; + (void)name; + (void)index; + (void)origin; + (void)request; + (void)hout; + return CURLHE_NOT_BUILT_IN; +} + +struct curl_header *curl_easy_nextheader(CURL *easy, + unsigned int type, + int request, + struct curl_header *prev) +{ + (void)easy; + (void)type; + (void)request; + (void)prev; + return NULL; +} +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/headers.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/headers.h new file mode 100644 index 0000000000..283179acdc --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/headers.h @@ -0,0 +1,63 @@ +#ifndef HEADER_CURL_HEADER_H +#define HEADER_CURL_HEADER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HEADERS_API) + +struct Curl_header_store { + struct Curl_llist_node node; + char *name; /* points into 'buffer' */ + char *value; /* points into 'buffer' */ + int request; /* 0 is the first request, then 1.. 2.. */ + unsigned char type; /* CURLH_* defines */ + char buffer[1]; /* this is the raw header blob */ +}; + +/* + * Initialize header collecting for a transfer. + * Add a client writer that catches CLIENTWRITE_HEADER writes. + */ +CURLcode Curl_headers_init(struct Curl_easy *data); + +/* + * Curl_headers_push() gets passed a full header to store. + */ +CURLcode Curl_headers_push(struct Curl_easy *data, const char *header, + size_t hlen, unsigned char type); + +/* + * Curl_headers_cleanup(). Free all stored headers and associated memory. + */ +CURLcode Curl_headers_cleanup(struct Curl_easy *data); + +#else +#define Curl_headers_init(x) CURLE_OK +#define Curl_headers_push(x, y, z, a) \ + ((void)(x), (void)(y), (void)(z), (void)(a), CURLE_OK) +#define Curl_headers_cleanup(x) Curl_nop_stmt +#endif + +#endif /* HEADER_CURL_HEADER_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/hmac.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/hmac.c new file mode 100644 index 0000000000..a4d6ebdd8a --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/hmac.c @@ -0,0 +1,170 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC2104 Keyed-Hashing for Message Authentication + * + ***************************************************************************/ +#include "curl_setup.h" + +#if (defined(USE_CURL_NTLM_CORE) && !defined(USE_WINDOWS_SSPI)) || \ + !defined(CURL_DISABLE_AWS) || !defined(CURL_DISABLE_DIGEST_AUTH) || \ + defined(USE_SSL) + +#include "curl_hmac.h" + +/* + * Generic HMAC algorithm. + * + * This module computes HMAC digests based on any hash function. Parameters + * and computing procedures are setup dynamically at HMAC computation context + * initialization. + */ + +static const unsigned char hmac_ipad = 0x36; +static const unsigned char hmac_opad = 0x5C; + +struct HMAC_context *Curl_HMAC_init(const struct HMAC_params *hashparams, + const unsigned char *key, + unsigned int keylen) +{ + size_t i; + struct HMAC_context *ctxt; + unsigned char *hkey; + unsigned char b; + + /* Create HMAC context. */ + i = sizeof(*ctxt) + (2 * hashparams->ctxtsize) + hashparams->resultlen; + ctxt = curlx_malloc(i); + + if(!ctxt) + return ctxt; + + ctxt->hash = hashparams; + ctxt->hashctxt1 = (void *)(ctxt + 1); + ctxt->hashctxt2 = (void *)((char *)ctxt->hashctxt1 + hashparams->ctxtsize); + + /* If the key is too long, replace it by its hash digest. */ + if(keylen > hashparams->maxkeylen) { + if(hashparams->hinit(ctxt->hashctxt1)) + goto fail; + hashparams->hupdate(ctxt->hashctxt1, key, keylen); + hkey = (unsigned char *)ctxt->hashctxt2 + hashparams->ctxtsize; + hashparams->hfinal(hkey, ctxt->hashctxt1); + key = hkey; + keylen = hashparams->resultlen; + } + + /* Prime the two hash contexts with the modified key. */ + if(hashparams->hinit(ctxt->hashctxt1) || + hashparams->hinit(ctxt->hashctxt2)) + goto fail; + + for(i = 0; i < keylen; i++) { + b = (unsigned char)(*key ^ hmac_ipad); + hashparams->hupdate(ctxt->hashctxt1, &b, 1); + b = (unsigned char)(*key++ ^ hmac_opad); + hashparams->hupdate(ctxt->hashctxt2, &b, 1); + } + + for(; i < hashparams->maxkeylen; i++) { + hashparams->hupdate(ctxt->hashctxt1, &hmac_ipad, 1); + hashparams->hupdate(ctxt->hashctxt2, &hmac_opad, 1); + } + + /* Done, return pointer to HMAC context. */ + return ctxt; + +fail: + curlx_free(ctxt); + return NULL; +} + +void Curl_HMAC_update(struct HMAC_context *ctxt, + const unsigned char *data, + unsigned int len) +{ + /* Update first hash calculation. */ + ctxt->hash->hupdate(ctxt->hashctxt1, data, len); +} + +int Curl_HMAC_final(struct HMAC_context *ctxt, unsigned char *output) +{ + const struct HMAC_params *hashparams = ctxt->hash; + + /* Do not get output if called with a null parameter: only release + storage. */ + + if(!output) + output = (unsigned char *)ctxt->hashctxt2 + ctxt->hash->ctxtsize; + + hashparams->hfinal(output, ctxt->hashctxt1); + hashparams->hupdate(ctxt->hashctxt2, output, hashparams->resultlen); + hashparams->hfinal(output, ctxt->hashctxt2); + curlx_free(ctxt); + return 0; +} + +/* + * Curl_hmacit() + * + * This is used to generate a HMAC hash, for the specified input data, given + * the specified hash function and key. + * + * Parameters: + * + * hashparams [in] - The hash function (Curl_HMAC_MD5). + * key [in] - The key to use. + * keylen [in] - The length of the key. + * buf [in] - The data to encrypt. + * buflen [in] - The length of the data. + * output [in/out] - The output buffer. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_hmacit(const struct HMAC_params *hashparams, + const unsigned char *key, const size_t keylen, + const unsigned char *data, size_t datalen, + unsigned char *output) +{ + struct HMAC_context *ctxt; + if(keylen > UINT_MAX) /* unlikely to ever happen */ + return CURLE_BAD_FUNCTION_ARGUMENT; + ctxt = Curl_HMAC_init(hashparams, key, curlx_uztoui(keylen)); + + if(!ctxt) + return CURLE_OUT_OF_MEMORY; + + /* Update the digest with the given challenge */ + do { + unsigned int ilen = (unsigned int)CURLMIN(datalen, UINT_MAX); + Curl_HMAC_update(ctxt, data, ilen); + datalen -= ilen; + data += ilen; + } while(datalen); + + /* Finalise the digest */ + Curl_HMAC_final(ctxt, output); + + return CURLE_OK; +} + +#endif /* Using NTLM (without SSPI) or AWS */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/hsts.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/hsts.c new file mode 100644 index 0000000000..73c01db018 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/hsts.c @@ -0,0 +1,648 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * The Strict-Transport-Security header is defined in RFC 6797: + * https://datatracker.ietf.org/doc/html/rfc6797 + */ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HSTS) +#include "urldata.h" +#include "llist.h" +#include "hsts.h" +#include "curl_fopen.h" +#include "curl_get_line.h" +#include "parsedate.h" +#include "curl_share.h" +#include "curlx/strparse.h" +#include "curlx/strcopy.h" + +#define MAX_HSTS_LINE 4095 +#define MAX_HSTS_HOSTLEN 2048 +#define MAX_HSTS_DATELEN 17 +#define UNLIMITED "unlimited" + +#if defined(DEBUGBUILD) || defined(UNITTESTS) +/* to play well with debug builds, we can *set* a fixed time this will + return */ +time_t deltatime; /* allow for "adjustments" for unit test purposes */ +static time_t hsts_debugtime(void *unused) +{ + const char *timestr = getenv("CURL_TIME"); + (void)unused; + if(timestr) { + curl_off_t val; + if(!curlx_str_number(×tr, &val, TIME_T_MAX)) + val += (curl_off_t)deltatime; + return (time_t)val; + } + return time(NULL); +} +#undef time +#define time(x) hsts_debugtime(x) +#endif + +struct hsts *Curl_hsts_init(void) +{ + struct hsts *h = curlx_calloc(1, sizeof(struct hsts)); + if(h) { + Curl_llist_init(&h->list, NULL); + } + return h; +} + +#define hsts_free(x) curlx_free(x) + +void Curl_hsts_cleanup(struct hsts **hp) +{ + struct hsts *h = *hp; + if(h) { + struct Curl_llist_node *e; + struct Curl_llist_node *n; + for(e = Curl_llist_head(&h->list); e; e = n) { + struct stsentry *sts = Curl_node_elem(e); + n = Curl_node_next(e); + hsts_free(sts); + } + curlx_free(h->filename); + curlx_free(h); + *hp = NULL; + } +} + +/* append the new entry to the list after possibly removing an old entry + first */ +static void hsts_append(struct hsts *h, struct stsentry *sts) +{ + if(Curl_llist_count(&h->list) == MAX_HSTS_ENTRIES) { + /* It is full. Remove the first entry in the list */ + struct Curl_llist_node *e = Curl_llist_head(&h->list); + struct stsentry *oldsts = Curl_node_elem(e); + Curl_node_remove(e); + hsts_free(oldsts); + } + Curl_llist_append(&h->list, sts, &sts->node); +} + +static CURLcode hsts_create(struct hsts *h, + const char *hostname, + size_t hlen, + bool subdomains, + curl_off_t expires) +{ + DEBUGASSERT(h); + DEBUGASSERT(hostname); + + if(hlen && (hostname[hlen - 1] == '.')) + /* strip off any trailing dot */ + --hlen; + if(hlen) { + struct stsentry *sts = curlx_calloc(1, sizeof(struct stsentry) + hlen); + if(!sts) + return CURLE_OUT_OF_MEMORY; + /* the null-terminator is already there */ + memcpy(sts->host, hostname, hlen); + sts->expires = expires; + sts->includeSubDomains = subdomains; + hsts_append(h, sts); + } + return CURLE_OK; +} + +/* Copy all live entries from src into dst. Used by curl_easy_duphandle so the + * clone inherits entries learned at runtime. E.g. Strict-Transport-Security. + */ +CURLcode Curl_hsts_copy(struct hsts *dst, struct hsts *src) +{ + struct Curl_llist_node *e; + time_t now = time(NULL); + for(e = Curl_llist_head(&src->list); e; e = Curl_node_next(e)) { + struct stsentry *sts = Curl_node_elem(e); + if(sts->expires > now) { + CURLcode result = hsts_create(dst, sts->host, strlen(sts->host), + sts->includeSubDomains != 0, sts->expires); + if(result) + return result; + } + } + return CURLE_OK; +} + +/* + * Return the matching HSTS entry, or NULL if the given hostname is not + * currently an HSTS one. + * + * The 'subdomain' argument tells the function if subdomain matching should be + * attempted. + * + * @unittest 1660 + */ +UNITTEST struct stsentry *hsts_check(struct hsts *h, const char *hostname, + size_t hlen, bool subdomain); +UNITTEST struct stsentry *hsts_check(struct hsts *h, const char *hostname, + size_t hlen, bool subdomain) +{ + struct stsentry *bestsub = NULL; + if(h) { + time_t now = time(NULL); + struct Curl_llist_node *e; + struct Curl_llist_node *n; + size_t blen = 0; + + if((hlen > MAX_HSTS_HOSTLEN) || !hlen) + return NULL; + if(hostname[hlen - 1] == '.') + /* remove the trailing dot */ + --hlen; + + for(e = Curl_llist_head(&h->list); e; e = n) { + struct stsentry *sts = Curl_node_elem(e); + size_t ntail; + n = Curl_node_next(e); + if(sts->expires <= now) { + /* remove expired entries */ + Curl_node_remove(&sts->node); + hsts_free(sts); + continue; + } + ntail = strlen(sts->host); + if((subdomain && sts->includeSubDomains) && (ntail < hlen)) { + size_t offs = hlen - ntail; + if((hostname[offs - 1] == '.') && + curl_strnequal(&hostname[offs], sts->host, ntail) && + (ntail > blen)) { + /* save the tail match with the longest tail */ + bestsub = sts; + blen = ntail; + } + } + /* avoid curl_strequal because the hostname is not null-terminated */ + if((hlen == ntail) && curl_strnequal(hostname, sts->host, hlen)) + return sts; + } + } + return bestsub; +} + +CURLcode Curl_hsts_parse(struct hsts *h, const char *hostname, + const char *header) +{ + const char *p = header; + curl_off_t expires = 0; + bool gotma = FALSE; + bool gotinc = FALSE; + bool subdomains = FALSE; + struct stsentry *sts; + time_t now = time(NULL); + size_t hlen = strlen(hostname); + + if(Curl_host_is_ipnum(hostname)) + /* "explicit IP address identification of all forms is excluded." + / RFC 6797 */ + return CURLE_OK; + + do { + struct Curl_str word; + struct Curl_str val = { 0 }; + int rc; + bool assign = FALSE; + + do { + curlx_str_passblanks(&p); + if(*p == ';') + p++; + else + break; + } while(1); + if(curlx_str_cspn(&p, &word, ";=\r\n \t")) + break; + + curlx_str_passblanks(&p); + if(!curlx_str_single(&p, '=')) { + assign = TRUE; + curlx_str_passblanks(&p); + + if(*p == '\"') { + if(curlx_str_quotedword(&p, &val, MAX_HSTS_LINE)) + break; + } + else { + if(curlx_str_cspn(&p, &val, ", ;\r\n")) + break; + } + } + + if(assign && curlx_str_casecompare(&word, "max-age")) { + const char *vp = curlx_str(&val); + if(gotma) + return CURLE_BAD_FUNCTION_ARGUMENT; + rc = curlx_str_number(&vp, &expires, TIME_T_MAX); + if(rc == STRE_OVERFLOW) + expires = CURL_OFF_T_MAX; + else if(rc) + /* invalid max-age */ + return CURLE_BAD_FUNCTION_ARGUMENT; + + gotma = TRUE; + } + else if(curlx_str_casecompare(&word, "includesubdomains")) { + if(gotinc) + return CURLE_BAD_FUNCTION_ARGUMENT; + subdomains = TRUE; + gotinc = TRUE; + } + } while(*p); + + if(!gotma) + /* max-age is mandatory */ + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(!expires) { + /* remove the entry if present verbatim (without subdomain match) */ + sts = hsts_check(h, hostname, hlen, FALSE); + if(sts) { + Curl_node_remove(&sts->node); + hsts_free(sts); + } + return CURLE_OK; + } + + if(CURL_OFF_T_MAX - now < expires) + /* would overflow, use maximum value */ + expires = CURL_OFF_T_MAX; + else + expires += now; + + /* check if it already exists */ + sts = hsts_check(h, hostname, hlen, FALSE); + if(sts) { + /* update these fields */ + sts->expires = expires; + sts->includeSubDomains = subdomains; + } + else + return hsts_create(h, hostname, hlen, subdomains, expires); + + return CURLE_OK; +} + +/* + * Send this HSTS entry to the write callback. + */ +static CURLcode hsts_push(struct Curl_easy *data, + struct curl_index *i, + struct stsentry *sts, + bool *stop) +{ + struct curl_hstsentry e; + CURLSTScode sc; + struct tm stamp; + CURLcode result; + + e.name = (char *)sts->host; + e.namelen = strlen(sts->host); + e.includeSubDomains = sts->includeSubDomains; + + if(sts->expires != TIME_T_MAX) { + result = curlx_gmtime((time_t)sts->expires, &stamp); + if(result) + return result; + + curl_msnprintf(e.expire, sizeof(e.expire), "%d%02d%02d %02d:%02d:%02d", + stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday, + stamp.tm_hour, stamp.tm_min, stamp.tm_sec); + } + else + curlx_strcopy(e.expire, sizeof(e.expire), STRCONST(UNLIMITED)); + + sc = data->set.hsts_write(data, &e, i, data->set.hsts_write_userp); + *stop = (sc != CURLSTS_OK); + return sc == CURLSTS_FAIL ? CURLE_BAD_FUNCTION_ARGUMENT : CURLE_OK; +} + +/* + * Write this single hsts entry to a single output line + */ +static CURLcode hsts_out(struct stsentry *sts, FILE *fp) +{ + struct tm stamp; + if(sts->expires != TIME_T_MAX) { + CURLcode result = curlx_gmtime((time_t)sts->expires, &stamp); + if(result) + return result; + curl_mfprintf(fp, "%s%s \"%d%02d%02d %02d:%02d:%02d\"\n", + sts->includeSubDomains ? "." : "", sts->host, + stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday, + stamp.tm_hour, stamp.tm_min, stamp.tm_sec); + } + else + curl_mfprintf(fp, "%s%s \"%s\"\n", + sts->includeSubDomains ? "." : "", sts->host, UNLIMITED); + return CURLE_OK; +} + +/* + * Curl_https_save() writes the HSTS cache to file and callback. + */ +CURLcode Curl_hsts_save(struct Curl_easy *data, struct hsts *h, + const char *file) +{ + struct Curl_llist_node *e; + struct Curl_llist_node *n; + CURLcode result = CURLE_OK; + FILE *out; + char *tempstore = NULL; + + if(!h) + /* no cache activated */ + return CURLE_OK; + + /* if no new name is given, use the one we stored from the load */ + if(!file && h->filename) + file = h->filename; + + if((h->flags & CURLHSTS_READONLYFILE) || !file || !file[0]) + /* marked as read-only, no file or zero length filename */ + goto skipsave; + + result = Curl_fopen(data, file, &out, &tempstore); + if(!result) { + fputs("# Your HSTS cache. https://curl.se/docs/hsts.html\n" + "# This file was generated by libcurl! Edit at your own risk.\n", + out); + for(e = Curl_llist_head(&h->list); e; e = n) { + struct stsentry *sts = Curl_node_elem(e); + n = Curl_node_next(e); + result = hsts_out(sts, out); + if(result) + break; + } + curlx_fclose(out); + if(!result && tempstore && curlx_rename(tempstore, file)) + result = CURLE_WRITE_ERROR; + + if(result && tempstore) + unlink(tempstore); + } + curlx_free(tempstore); +skipsave: + if(data->set.hsts_write) { + /* if there is a write callback */ + struct curl_index i; /* count */ + i.total = Curl_llist_count(&h->list); + i.index = 0; + for(e = Curl_llist_head(&h->list); e; e = n) { + struct stsentry *sts = Curl_node_elem(e); + bool stop; + n = Curl_node_next(e); + result = hsts_push(data, &i, sts, &stop); + if(result || stop) + break; + i.index++; + } + } + return result; +} + +/* only returns SERIOUS errors */ +static CURLcode hsts_add_host_expire(struct hsts *h, + const char *host, size_t hostlen, + const char *expire, size_t explen, + bool subdomain) /* default */ +{ + CURLcode result = CURLE_OK; + struct stsentry *e; + char dbuf[MAX_HSTS_DATELEN + 1]; + time_t expires = 0; + time_t now = time(NULL); + + /* The date parser works on a null-terminated string. */ + if(explen > MAX_HSTS_DATELEN) + return CURLE_BAD_FUNCTION_ARGUMENT; + memcpy(dbuf, expire, explen); + dbuf[explen] = 0; + + if(!strcmp(dbuf, UNLIMITED)) + expires = TIME_T_MAX; + else + Curl_getdate_capped(dbuf, &expires); + + if(expires <= now) + /* this entry already expired */ + return CURLE_OK; + + if(host[0] == '.') { + host++; + hostlen--; + subdomain = TRUE; + } + if(hostlen && (host[hostlen - 1] == '.')) + /* strip off any trailing dot */ + hostlen--; + + if(hostlen) { + /* only add it if not already present */ + e = hsts_check(h, host, hostlen, subdomain); + if(!e) + result = hsts_create(h, host, hostlen, subdomain, expires); + /* 'host' is not necessarily null-terminated */ + else if((hostlen == strlen(e->host) && + curl_strnequal(host, e->host, hostlen))) { + /* the same hostname, use the largest expire time and keep the strictest + subdomain policy */ + if(expires > e->expires) + e->expires = expires; + if(subdomain) + e->includeSubDomains = TRUE; + } + } + return result; +} + +/* only returns SERIOUS errors */ +static CURLcode hsts_add(struct hsts *h, const char *line) +{ + /* Example lines: + example.com "20191231 10:00:00" + .example.net "20191231 10:00:00" + */ + struct Curl_str host; + struct Curl_str date; + + if(curlx_str_word(&line, &host, MAX_HSTS_HOSTLEN) || + curlx_str_singlespace(&line) || + curlx_str_quotedword(&line, &date, MAX_HSTS_DATELEN) || + curlx_str_newline(&line)) + ; + else { + return hsts_add_host_expire(h, curlx_str(&host), curlx_strlen(&host), + curlx_str(&date), curlx_strlen(&date), + FALSE); + } + + return CURLE_OK; +} + +/* + * Load HSTS data from callback. + * + */ +static CURLcode hsts_pull(struct Curl_easy *data, struct hsts *h) +{ + /* if the HSTS read callback is set, use it */ + if(data->set.hsts_read) { + CURLSTScode sc; + DEBUGASSERT(h); + do { + char buffer[MAX_HSTS_HOSTLEN + 1]; + struct curl_hstsentry e; + e.name = buffer; + e.namelen = sizeof(buffer) - 1; + e.includeSubDomains = FALSE; /* default */ + e.expire[0] = 0; + e.expire[MAX_HSTS_DATELEN] = 0; + e.name[0] = 0; /* to make it clean */ + e.name[MAX_HSTS_HOSTLEN] = 0; + sc = data->set.hsts_read(data, &e, data->set.hsts_read_userp); + if(sc == CURLSTS_OK) { + CURLcode result; + const char *date = e.expire; + if(!e.name[0] || e.expire[MAX_HSTS_DATELEN] || + e.name[MAX_HSTS_HOSTLEN]) + /* bail out if no name was stored or if a null-terminator is gone */ + return CURLE_BAD_FUNCTION_ARGUMENT; + if(!date[0]) + date = UNLIMITED; + result = hsts_add_host_expire(h, e.name, strlen(e.name), + date, strlen(date), + /* bitfield to bool conversion: */ + e.includeSubDomains ? TRUE : FALSE); + if(result) + return result; + } + else if(sc == CURLSTS_FAIL) + return CURLE_ABORTED_BY_CALLBACK; + } while(sc == CURLSTS_OK); + } + return CURLE_OK; +} + +/* + * Load the HSTS cache from the given file. The text based line-oriented file + * format is documented here: https://curl.se/docs/hsts.html + * + * This function only returns error on major problems that prevent hsts + * handling to work completely. It will ignore individual syntactical errors + * etc. + */ +static CURLcode hsts_load(struct hsts *h, const char *file) +{ + CURLcode result = CURLE_OK; + FILE *fp; + + /* we need a private copy of the filename so that the hsts cache file + name survives an easy handle reset */ + curlx_free(h->filename); + h->filename = curlx_strdup(file); + if(!h->filename) + return CURLE_OUT_OF_MEMORY; + + fp = curlx_fopen(file, FOPEN_READTEXT); + if(fp) { + curlx_struct_stat stat; + if((curlx_fstat(fileno(fp), &stat) == -1) || !S_ISDIR(stat.st_mode)) { + struct dynbuf buf; + bool eof = FALSE; + curlx_dyn_init(&buf, MAX_HSTS_LINE); + do { + result = Curl_get_line(&buf, fp, &eof); + if(!result) { + const char *lineptr = curlx_dyn_ptr(&buf); + curlx_str_passblanks(&lineptr); + + /* Skip empty or commented lines, since we know the line will have + a trailing newline from Curl_get_line we can treat length 1 as + empty. */ + if((*lineptr == '#') || strlen(lineptr) <= 1) + continue; + + hsts_add(h, lineptr); + } + } while(!result && !eof); + curlx_dyn_free(&buf); /* free the line buffer */ + } + curlx_fclose(fp); + } + return result; +} + +/* + * Curl_hsts_loadfile() loads HSTS from file + */ +CURLcode Curl_hsts_loadfile(struct Curl_easy *data, + struct hsts *h, const char *file) +{ + DEBUGASSERT(h); + (void)data; + return hsts_load(h, file); +} + +/* + * Curl_hsts_loadcb() loads HSTS from callback + */ +CURLcode Curl_hsts_loadcb(struct Curl_easy *data, struct hsts *h) +{ + if(h) + return hsts_pull(data, h); + return CURLE_OK; +} + +CURLcode Curl_hsts_loadfiles(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct curl_slist *l = data->state.hstslist; + if(l) { + Curl_share_lock(data, CURL_LOCK_DATA_HSTS, CURL_LOCK_ACCESS_SINGLE); + + while(l) { + result = Curl_hsts_loadfile(data, data->hsts, l->data); + if(result) + break; + l = l->next; + } + Curl_share_unlock(data, CURL_LOCK_DATA_HSTS); + } + return result; +} + +bool Curl_hsts_applies(struct hsts *h, const struct Curl_peer *dest) +{ + return !!hsts_check(h, dest->hostname, strlen(dest->hostname), TRUE); +} + +#if defined(DEBUGBUILD) || defined(UNITTESTS) +#undef time +#endif + +#endif /* CURL_DISABLE_HTTP || CURL_DISABLE_HSTS */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/hsts.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/hsts.h new file mode 100644 index 0000000000..08215f5eaa --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/hsts.h @@ -0,0 +1,76 @@ +#ifndef HEADER_CURL_HSTS_H +#define HEADER_CURL_HSTS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct hsts; + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HSTS) +#include "llist.h" + +struct Curl_peer; + +#define MAX_HSTS_ENTRIES 10000 + +#if defined(DEBUGBUILD) || defined(UNITTESTS) +extern time_t deltatime; +#endif + +struct stsentry { + struct Curl_llist_node node; + curl_off_t expires; /* the timestamp of this entry's expiry */ + BIT(includeSubDomains); + char host[1]; +}; + +/* The HSTS cache. Needs to be able to tailmatch hostnames. */ +struct hsts { + struct Curl_llist list; + char *filename; + unsigned int flags; +}; + +struct hsts *Curl_hsts_init(void); +void Curl_hsts_cleanup(struct hsts **hp); +CURLcode Curl_hsts_copy(struct hsts *dst, struct hsts *src); +CURLcode Curl_hsts_parse(struct hsts *h, const char *hostname, + const char *header); +CURLcode Curl_hsts_save(struct Curl_easy *data, struct hsts *h, + const char *file); +CURLcode Curl_hsts_loadfile(struct Curl_easy *data, + struct hsts *h, const char *file); +CURLcode Curl_hsts_loadcb(struct Curl_easy *data, + struct hsts *h); +CURLcode Curl_hsts_loadfiles(struct Curl_easy *data); + +bool Curl_hsts_applies(struct hsts *h, const struct Curl_peer *dest); + +#else +#define Curl_hsts_cleanup(x) +#define Curl_hsts_loadcb(x, y) CURLE_OK +#define Curl_hsts_save(x, y, z) +#define Curl_hsts_loadfiles(x) CURLE_OK +#endif /* CURL_DISABLE_HTTP || CURL_DISABLE_HSTS */ +#endif /* HEADER_CURL_HSTS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http.c new file mode 100644 index 0000000000..4b79b2ab93 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http.c @@ -0,0 +1,5098 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" + +#ifndef CURL_DISABLE_HTTP + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif + +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NET_IF_H +#include <net/if.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif + +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif + +#include "transfer.h" +#include "sendf.h" +#include "curl_trc.h" +#include "formdata.h" +#include "mime.h" +#include "progress.h" +#include "curlx/base64.h" +#include "cookie.h" +#include "vauth/vauth.h" +#include "vquic/vquic.h" +#include "http_digest.h" +#include "http_ntlm.h" +#include "http_negotiate.h" +#include "http_aws_sigv4.h" +#include "http_httpsig.h" +#include "url.h" +#include "urlapi-int.h" +#include "curl_share.h" +#include "dynhds.h" +#include "http.h" +#include "headers.h" +#include "select.h" +#include "parsedate.h" /* for the week day and month names */ +#include "multiif.h" +#include "strcase.h" +#include "content_encoding.h" +#include "http_proxy.h" +#include "http2.h" +#include "cfilters.h" +#include "connect.h" +#include "curlx/strdup.h" +#include "altsvc.h" +#include "hsts.h" +#include "rtsp.h" +#include "ws.h" +#include "bufref.h" +#include "curlx/strparse.h" + +void Curl_http_neg_init(struct Curl_easy *data, struct http_negotiation *neg) +{ + memset(neg, 0, sizeof(*neg)); + neg->accept_09 = data->set.http09_allowed; + switch(data->set.httpwant) { + case CURL_HTTP_VERSION_1_0: + neg->wanted = neg->allowed = (CURL_HTTP_V1x); + neg->only_10 = TRUE; + break; + case CURL_HTTP_VERSION_1_1: + neg->wanted = neg->allowed = (CURL_HTTP_V1x); + break; + case CURL_HTTP_VERSION_2_0: + neg->wanted = neg->allowed = (CURL_HTTP_V1x | CURL_HTTP_V2x); + neg->h2_upgrade = TRUE; + break; + case CURL_HTTP_VERSION_2TLS: + neg->wanted = neg->allowed = (CURL_HTTP_V1x | CURL_HTTP_V2x); + break; + case CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE: + neg->wanted = neg->allowed = (CURL_HTTP_V2x); + data->state.http_neg.h2_prior_knowledge = TRUE; + break; + case CURL_HTTP_VERSION_3: + neg->wanted = (CURL_HTTP_V1x | CURL_HTTP_V2x | CURL_HTTP_V3x); + neg->allowed = neg->wanted; + break; + case CURL_HTTP_VERSION_3ONLY: + neg->wanted = neg->allowed = (CURL_HTTP_V3x); + break; + case CURL_HTTP_VERSION_NONE: + default: + neg->wanted = (CURL_HTTP_V1x | CURL_HTTP_V2x); + neg->allowed = (CURL_HTTP_V1x | CURL_HTTP_V2x | CURL_HTTP_V3x); + break; + } +} + +CURLcode Curl_http_setup_conn(struct Curl_easy *data, + struct connectdata *conn) +{ + /* allocate the HTTP-specific struct for the Curl_easy, only to survive + during this request */ + if(data->state.http_neg.wanted == CURL_HTTP_V3x) { + /* only HTTP/3, needs to work */ + CURLcode result = Curl_conn_may_http3(data, conn, conn->transport_wanted); + if(result) + return result; + } + return CURLE_OK; +} + +#ifndef CURL_DISABLE_PROXY +/* + * checkProxyHeaders() checks the linked list of custom proxy headers + * if proxy headers are not available, then it will lookup into http header + * link list + * + * It takes a connectdata struct as input to see if this is a proxy request or + * not, as it then might check a different header list. Provide the header + * prefix without colon! + */ +char *Curl_checkProxyheaders(struct Curl_easy *data, + const struct connectdata *conn, + const char *thisheader, + const size_t thislen) +{ + struct curl_slist *head; + + for(head = (conn->http_proxy.peer && data->set.sep_headers) ? + data->set.proxyheaders : data->set.headers; + head; head = head->next) { + if(curl_strnequal(head->data, thisheader, thislen) && + Curl_headersep(head->data[thislen])) + return head->data; + } + + return NULL; +} +#endif + +/* If the header has a value, this function returns TRUE and the value is in + 'outp' with blanks trimmed off. */ +static bool header_has_value(const char **headerp, struct Curl_str *outp) +{ + bool value = !curlx_str_cspn(headerp, outp, ";:") && + (!curlx_str_single(headerp, ':') || !curlx_str_single(headerp, ';')); + + if(value) { + curlx_str_cspn(headerp, outp, "\r\n"); + curlx_str_trimblanks(outp); + } + return value; +} + +static bool http_header_is_empty(const char *header) +{ + struct Curl_str out; + + if(header_has_value(&header, &out)) { + return curlx_strlen(&out) == 0; + } + return TRUE; /* invalid header format, treat as empty */ +} + +/* + * Strip off leading and trailing whitespace from the value in the given HTTP + * header line and return a strdup-ed copy in 'valp' - returns an empty + * string if the header value consists entirely of whitespace. + * + * If the header is provided as "name;", ending with a semicolon, it returns a + * blank string. + */ +static CURLcode copy_custom_value(const char *header, char **valp) +{ + struct Curl_str out = { 0 }; + + /* find the end of the header name */ + if(header_has_value(&header, &out)) { + *valp = curlx_memdup0(curlx_str(&out), curlx_strlen(&out)); + if(*valp) + return CURLE_OK; + return CURLE_OUT_OF_MEMORY; + } + /* bad input */ + *valp = NULL; + return CURLE_BAD_FUNCTION_ARGUMENT; +} + +/* + * Strip off leading and trailing whitespace from the value in the given HTTP + * header line and return a strdup-ed copy in 'valp' - returns an empty + * string if the header value consists entirely of whitespace. + * + * This function MUST be used after the header has already been confirmed to + * lead with "word:". + * + * @unittest: 1626 + */ +char *Curl_copy_header_value(const char *header) +{ + struct Curl_str out; + + /* find the end of the header name */ + if(!curlx_str_until(&header, &out, MAX_HTTP_RESP_HEADER_SIZE, ':') && + !curlx_str_single(&header, ':')) { + curlx_str_untilnl(&header, &out, MAX_HTTP_RESP_HEADER_SIZE); + curlx_str_trimblanks(&out); + return curlx_memdup0(curlx_str(&out), curlx_strlen(&out)); + } + /* bad input, should never happen */ + DEBUGASSERT(0); + return NULL; +} + +#ifndef CURL_DISABLE_HTTP_AUTH + +#ifndef CURL_DISABLE_BASIC_AUTH +/* + * http_output_basic() sets up an Authorization: header (or the proxy version) + * for HTTP Basic authentication. + * + * Returns CURLcode. + */ +static CURLcode http_output_basic(struct Curl_easy *data, + struct connectdata *conn, bool proxy) +{ + size_t size = 0; + char *authorization = NULL; + char **p_hd; + CURLcode result; + struct Curl_creds *creds = NULL; + char *out; + + /* credentials are unique per transfer for HTTP, do not use the ones for the + connection */ + if(proxy) { +#ifndef CURL_DISABLE_PROXY + p_hd = &data->req.hd_proxy_auth; + creds = conn->http_proxy.creds; +#else + (void)conn; + return CURLE_NOT_BUILT_IN; +#endif + } + else { + p_hd = &data->req.hd_auth; + creds = data->state.creds; + } + + if(!creds) { + DEBUGASSERT(0); + return CURLE_FAILED_INIT; + } + + out = curl_maprintf("%s:%s", creds->user, creds->passwd); + if(!out) + return CURLE_OUT_OF_MEMORY; + + result = curlx_base64_encode((uint8_t *)out, strlen(out), + &authorization, &size); + if(result) + goto fail; + + if(!authorization) { + result = CURLE_REMOTE_ACCESS_DENIED; + goto fail; + } + + curlx_free(*p_hd); + *p_hd = curl_maprintf("%sAuthorization: Basic %s\r\n", + proxy ? "Proxy-" : "", + authorization); + curlx_free(authorization); + if(!*p_hd) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + +fail: + curlx_free(out); + return result; +} + +#endif + +#ifndef CURL_DISABLE_BEARER_AUTH +/* + * http_output_bearer() sets up an Authorization: header + * for HTTP Bearer authentication. + * + * Returns CURLcode. + */ +static CURLcode http_output_bearer(struct Curl_easy *data) +{ + char **userp; + CURLcode result = CURLE_OK; + + DEBUGASSERT(Curl_creds_has_oauth_bearer(data->state.creds)); + userp = &data->req.hd_auth; + curlx_free(*userp); + *userp = curl_maprintf("Authorization: Bearer %s\r\n", + Curl_creds_oauth_bearer(data->state.creds)); + + if(!*userp) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + +fail: + return result; +} +#endif + +#endif + +/* pickoneauth() selects the most favorable authentication method from the + * ones available and the ones we want. + * + * return TRUE if one was picked + */ +static bool pickoneauth(struct auth *pick, unsigned long mask, + struct Curl_creds *creds) +{ + bool have_user_pass = Curl_creds_has_user_or_pass(creds); + bool picked; + /* only deal with authentication we want */ + unsigned long avail = pick->avail & pick->want & mask; + picked = TRUE; + + /* The order of these checks is highly relevant, as this will be the order + of preference in case of the existence of multiple accepted types. */ + if(avail & CURLAUTH_NEGOTIATE) /* available on empty creds */ + pick->picked = CURLAUTH_NEGOTIATE; +#ifndef CURL_DISABLE_BEARER_AUTH + else if((avail & CURLAUTH_BEARER) && Curl_creds_has_oauth_bearer(creds)) + pick->picked = CURLAUTH_BEARER; +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + else if((avail & CURLAUTH_DIGEST) && have_user_pass) + pick->picked = CURLAUTH_DIGEST; +#endif + else if(avail & CURLAUTH_NTLM) + pick->picked = CURLAUTH_NTLM; +#ifndef CURL_DISABLE_BASIC_AUTH + else if((avail & CURLAUTH_BASIC) && have_user_pass) + pick->picked = CURLAUTH_BASIC; +#endif +#ifndef CURL_DISABLE_AWS + else if(avail & CURLAUTH_AWS_SIGV4) + pick->picked = CURLAUTH_AWS_SIGV4; +#endif +#ifndef CURL_DISABLE_HTTPSIG + else if(avail & CURLAUTH_HTTPSIG) + pick->picked = CURLAUTH_HTTPSIG; +#endif + else { + pick->picked = CURLAUTH_PICKNONE; /* we select to use nothing */ + picked = FALSE; + } + pick->avail = CURLAUTH_NONE; /* clear it here */ + + return picked; +} + +/* + * http_perhapsrewind() + * + * The current request needs to be done again - maybe due to a follow + * or authentication negotiation. Check if: + * 1) a rewind of the data sent to the server is necessary + * 2) the current transfer should continue or be stopped early + */ +static CURLcode http_perhapsrewind(struct Curl_easy *data, + struct connectdata *conn) +{ + curl_off_t bytessent = data->req.writebytecount; + curl_off_t expectsend = Curl_creader_total_length(data); + curl_off_t upload_remain = (expectsend >= 0) ? (expectsend - bytessent) : -1; + bool little_upload_remains = (upload_remain >= 0 && upload_remain < 2000); + bool needs_rewind = Curl_creader_needs_rewind(data); + /* By default, we would like to abort the transfer when little or unknown + * amount remains. This may be overridden by authentications further + * below! */ + bool abort_upload = (!data->req.upload_done && !little_upload_remains); + VERBOSE(const char *ongoing_auth = NULL); + + /* We need a rewind before uploading client read data again. The + * checks below influence of the upload is to be continued + * or aborted early. + * This depends on how much remains to be sent and in what state + * the authentication is. Some auth schemes such as NTLM do not work + * for a new connection. */ + if(needs_rewind) { + infof(data, "Need to rewind upload for next request"); + Curl_creader_set_rewind(data, TRUE); + } + + if(conn->bits.close) + /* If we already decided to close this connection, we cannot veto. */ + return CURLE_OK; + + if(abort_upload) { + /* We would like to abort the upload - but should we? */ +#ifdef USE_NTLM + if((data->state.authproxy.picked == CURLAUTH_NTLM) || + (data->state.authhost.picked == CURLAUTH_NTLM)) { + VERBOSE(ongoing_auth = "NTLM"); + if((conn->http_ntlm_state != NTLMSTATE_NONE) || + (conn->proxy_ntlm_state != NTLMSTATE_NONE)) { + /* The NTLM-negotiation has started, keep on sending. + * Need to do further work on same connection */ + abort_upload = FALSE; + } + } +#endif +#ifdef USE_SPNEGO + /* There is still data left to send */ + if((data->state.authproxy.picked == CURLAUTH_NEGOTIATE) || + (data->state.authhost.picked == CURLAUTH_NEGOTIATE)) { + VERBOSE(ongoing_auth = "NEGOTIATE"); + if((conn->http_negotiate_state != GSS_AUTHNONE) || + (conn->proxy_negotiate_state != GSS_AUTHNONE)) { + /* The NEGOTIATE-negotiation has started, keep on sending. + * Need to do further work on same connection */ + abort_upload = FALSE; + } + } +#endif + } + + if(abort_upload) { + if(upload_remain >= 0) + infof(data, "%s%sclose instead of sending %" FMT_OFF_T " more bytes", + ongoing_auth ? ongoing_auth : "", + ongoing_auth ? " send, " : "", + upload_remain); + else + infof(data, "%s%sclose instead of sending unknown amount " + "of more bytes", + ongoing_auth ? ongoing_auth : "", + ongoing_auth ? " send, " : ""); + /* We decided to abort the ongoing transfer */ + streamclose(conn); + data->req.size = 0; /* do not download any more than 0 bytes */ + data->req.http_bodyless = TRUE; + } + return CURLE_OK; +} + +/** + * http_should_fail() determines whether an HTTP response code has gotten us + * into an error state or not. + * + * @retval FALSE communications should continue + * + * @retval TRUE communications should not continue + */ +static bool http_should_fail(struct Curl_easy *data, int httpcode) +{ + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + + /* + * If we have not been asked to fail on error, + * do not fail. + */ + if(!data->set.http_fail_on_error) + return FALSE; + + /* + * Any code < 400 is never terminal. + */ + if(httpcode < 400) + return FALSE; + + /* + * A 416 response to a resume request is presumably because the file is + * already completely downloaded and thus not actually a fail. + */ + if(data->state.resume_from && data->state.httpreq == HTTPREQ_GET && + httpcode == 416) + return FALSE; + + /* + * Any code >= 400 that is not 401 or 407 is always + * a terminal error + */ + if((httpcode != 401) && (httpcode != 407)) + return TRUE; + + /* + * All we have left to deal with is 401 and 407 + */ + DEBUGASSERT((httpcode == 401) || (httpcode == 407)); + + /* + * Examine the current authentication state to see if this is an error. The + * idea is for this function to get called after processing all the headers + * in a response message. If we have been asked to authenticate at + * a particular stage, and we have done it, we are OK. If we are already + * completely authenticated, it is not OK to get another 401 or 407. + * + * It is possible for authentication to go stale such that the client needs + * to reauthenticate. Once that info is available, use it here. + */ + + /* + * Either we are not authenticating, or we are supposed to be authenticating + * something else. This is an error. + */ + if((httpcode == 401) && !data->state.creds) + return TRUE; +#ifndef CURL_DISABLE_PROXY + if((httpcode == 407) && !data->conn->http_proxy.creds) + return TRUE; +#endif + + return (bool)data->state.authproblem; +} + +/* + * Curl_http_auth_act() gets called when all HTTP headers have been received + * and it checks what authentication methods that are available and decides + * which one (if any) to use. It will set 'newurl' if an auth method was + * picked. + */ +CURLcode Curl_http_auth_act(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + bool pickhost = FALSE; + bool pickproxy = FALSE; + CURLcode result = CURLE_OK; + unsigned long authmask = ~0UL; + + if(!Curl_creds_has_oauth_bearer(data->state.creds)) + authmask &= (unsigned long)~CURLAUTH_BEARER; + + if(100 <= data->req.httpcode && data->req.httpcode <= 199) + /* this is a transient response code, ignore */ + return CURLE_OK; + + if(data->state.authproblem) + return data->set.http_fail_on_error ? CURLE_HTTP_RETURNED_ERROR : CURLE_OK; + + if(data->state.creds && + ((data->req.httpcode == 401) || + (data->req.authneg && data->req.httpcode < 300))) { + pickhost = pickoneauth(&data->state.authhost, authmask, data->state.creds); + if(!pickhost) + data->state.authproblem = TRUE; + else + data->info.httpauthpicked = data->state.authhost.picked; + if(data->state.authhost.picked == CURLAUTH_NTLM && + (data->req.httpversion_sent > 11)) { + infof(data, "Forcing HTTP/1.1 for NTLM"); + connclose(conn); + data->state.http_neg.wanted = CURL_HTTP_V1x; + data->state.http_neg.allowed = CURL_HTTP_V1x; + } + } +#ifndef CURL_DISABLE_PROXY + if(conn->http_proxy.creds && + ((data->req.httpcode == 407) || + (data->req.authneg && data->req.httpcode < 300))) { + pickproxy = pickoneauth(&data->state.authproxy, + authmask & ~CURLAUTH_BEARER, + conn->http_proxy.creds); + if(!pickproxy) + data->state.authproblem = TRUE; + else + data->info.proxyauthpicked = data->state.authproxy.picked; + } +#endif + + if(pickhost || pickproxy) { + result = http_perhapsrewind(data, conn); + if(result) + return result; + + /* In case this is GSS auth, the newurl field is already allocated so + we must make sure to free it before allocating a new one. As figured + out in bug #2284386 */ + curlx_free(data->req.newurl); + /* clone URL */ + data->req.newurl = Curl_bufref_dup(&data->state.url); + if(!data->req.newurl) + return CURLE_OUT_OF_MEMORY; + } + else if((data->req.httpcode < 300) && + !data->state.authhost.done && + data->req.authneg) { + /* no (known) authentication available, + authentication is not "done" yet and + no authentication seems to be required and + we did not try HEAD or GET */ + if((data->state.httpreq != HTTPREQ_GET) && + (data->state.httpreq != HTTPREQ_HEAD)) { + /* clone URL */ + data->req.newurl = Curl_bufref_dup(&data->state.url); + if(!data->req.newurl) + return CURLE_OUT_OF_MEMORY; + data->state.authhost.done = TRUE; + } + } + if(http_should_fail(data, data->req.httpcode)) { + failf(data, "The requested URL returned error: %d", + data->req.httpcode); + result = CURLE_HTTP_RETURNED_ERROR; + } + + return result; +} + +#ifndef CURL_DISABLE_HTTP_AUTH +/* + * Output the correct authentication header depending on the auth type + * and whether or not it is to a proxy. + */ +static CURLcode output_auth_headers(struct Curl_easy *data, + struct connectdata *conn, + struct auth *authstatus, + const char *request, + const char *path, + bool proxy) +{ + const char *auth = NULL; + CURLcode result = CURLE_OK; + (void)conn; + +#ifdef CURL_DISABLE_DIGEST_AUTH + (void)request; + (void)path; +#endif +#ifndef CURL_DISABLE_AWS + if((authstatus->picked == CURLAUTH_AWS_SIGV4) && !proxy) { + /* this method is never for proxy */ + auth = "AWS_SIGV4"; + result = Curl_output_aws_sigv4(data); + if(result) + return result; + } + else +#endif +#ifndef CURL_DISABLE_HTTPSIG + if((authstatus->picked == CURLAUTH_HTTPSIG) && !proxy) { + /* HTTPSIG uses its own configured key material rather than + data->state.creds. Do not let unrelated credentials from a + redirected URL bypass the cross-host auth boundary. */ + if(Curl_auth_allowed_to_host(data)) { + auth = "HTTPSIG"; + result = Curl_output_httpsig(data); + if(result) + return result; + } + else + authstatus->done = TRUE; + } + else +#endif +#ifdef USE_SPNEGO + if(authstatus->picked == CURLAUTH_NEGOTIATE) { + if( +#ifndef CURL_DISABLE_PROXY + (proxy && !Curl_checkProxyheaders(data, conn, + STRCONST("Proxy-authorization"))) || +#endif + (!proxy && !Curl_checkheaders(data, STRCONST("Authorization")))) { + auth = "Negotiate"; + result = Curl_output_negotiate(data, conn, proxy); + if(result) + return result; + } + else + authstatus->done = TRUE; + } + else +#endif +#ifdef USE_NTLM + if(authstatus->picked == CURLAUTH_NTLM) { + auth = "NTLM"; + result = Curl_output_ntlm(data, proxy); + if(result) + return result; + } + else +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + if(authstatus->picked == CURLAUTH_DIGEST) { + auth = "Digest"; + result = Curl_output_digest(data, + proxy, + (const unsigned char *)request, + (const unsigned char *)path); + if(result) + return result; + } + else +#endif +#ifndef CURL_DISABLE_BASIC_AUTH + if(authstatus->picked == CURLAUTH_BASIC) { + /* Basic */ + if( +#ifndef CURL_DISABLE_PROXY + (proxy && conn->http_proxy.creds && + Curl_creds_has_user_or_pass(conn->http_proxy.creds) && + !Curl_checkProxyheaders(data, conn, + STRCONST("Proxy-authorization"))) || +#endif + (!proxy && data->state.creds && + Curl_creds_has_user_or_pass(data->state.creds) && + !Curl_checkheaders(data, STRCONST("Authorization")))) { + auth = "Basic"; + result = http_output_basic(data, conn, proxy); + if(result) + return result; + } + + /* NOTE: this function should set 'done' TRUE, as the other auth + functions work that way */ + authstatus->done = TRUE; + } +#endif +#ifndef CURL_DISABLE_BEARER_AUTH + if(authstatus->picked == CURLAUTH_BEARER) { + /* Bearer */ + if(!proxy && Curl_creds_has_oauth_bearer(data->state.creds) && + !Curl_checkheaders(data, STRCONST("Authorization"))) { + auth = "Bearer"; + result = http_output_bearer(data); + if(result) + return result; + } + + /* NOTE: this function should set 'done' TRUE, as the other auth + functions work that way */ + authstatus->done = TRUE; + } +#endif + + if(auth) { +#ifndef CURL_DISABLE_PROXY + if(proxy) + data->info.proxyauthpicked = authstatus->picked; + else + data->info.httpauthpicked = authstatus->picked; + infof(data, "%s auth using %s with user '%s'", + proxy ? "Proxy" : "Server", auth, + proxy ? (conn->http_proxy.creds ? + conn->http_proxy.creds->user : "") : + (data->state.creds ? + data->state.creds->user : "")); +#else + (void)proxy; + infof(data, "Server auth using %s with user '%s'", + auth, data->state.creds ? + data->state.creds->user : ""); +#endif + authstatus->multipass = !authstatus->done; + } + else { + authstatus->multipass = FALSE; + if(proxy) + data->info.proxyauthpicked = 0; + else + data->info.httpauthpicked = 0; + } + + return result; +} + +CURLcode Curl_http_output_auth(struct Curl_easy *data, + struct connectdata *conn, + const char *request, + Curl_HttpReq httpreq, + const char *path, + const char *query, + bool is_connect) +{ + CURLcode result = CURLE_OK; + struct auth *authhost; + struct auth *authproxy; + const char *path_and_query = path; + char *tmp_str = NULL; + + DEBUGASSERT(data); + authhost = &data->state.authhost; + authproxy = &data->state.authproxy; + + if( +#ifndef CURL_DISABLE_PROXY + (!conn->http_proxy.peer || !conn->http_proxy.creds) && +#endif +#ifdef USE_SPNEGO + !(authhost->want & CURLAUTH_NEGOTIATE) && + !(authproxy->want & CURLAUTH_NEGOTIATE) && +#endif +#ifndef CURL_DISABLE_HTTPSIG + !(authhost->want & CURLAUTH_HTTPSIG) && +#endif + !data->state.creds) { + /* no authentication with no user or password */ + authhost->done = TRUE; + authproxy->done = TRUE; + result = CURLE_OK; + goto out; + } + + if(query) { + tmp_str = curl_maprintf("%s?%s", path, query); + if(!tmp_str) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + path_and_query = tmp_str; + } + + if(authhost->want && !authhost->picked) + /* The app has selected one or more methods, but none has been picked + so far by a server round-trip. Then we set the picked one to the + want one, and if this is one single bit it will be used instantly. */ + authhost->picked = authhost->want; + + if(authproxy->want && !authproxy->picked) + /* The app has selected one or more methods, but none has been picked so + far by a proxy round-trip. Then we set the picked one to the want one, + and if this is one single bit it will be used instantly. */ + authproxy->picked = authproxy->want; + +#ifndef CURL_DISABLE_PROXY + /* Send proxy authentication header if needed */ + if(conn->bits.origin_is_proxy || is_connect) { + result = output_auth_headers(data, conn, authproxy, request, + path_and_query, TRUE); + if(result) + goto out; + } + else +#else + (void)is_connect; +#endif /* CURL_DISABLE_PROXY */ + /* we have no proxy so let's pretend we are done authenticating + with it */ + authproxy->done = TRUE; + + /* Either we have credentials for the origin we talk to or + performing authentication is allowed here */ + if(data->state.creds || Curl_auth_allowed_to_host(data)) + result = output_auth_headers(data, conn, authhost, request, + path_and_query, FALSE); + else + authhost->done = TRUE; + + if(((authhost->multipass && !authhost->done) || + (authproxy->multipass && !authproxy->done)) && + (httpreq != HTTPREQ_GET) && + (httpreq != HTTPREQ_HEAD)) { + /* Auth is required and we are not authenticated yet. Make a PUT or POST + with content-length zero as a "probe". */ + data->req.authneg = TRUE; + } + else + data->req.authneg = FALSE; + +out: + curlx_free(tmp_str); + return result; +} + +#else /* !CURL_DISABLE_HTTP_AUTH */ +/* when disabled */ +CURLcode Curl_http_output_auth(struct Curl_easy *data, + struct connectdata *conn, + const char *request, + Curl_HttpReq httpreq, + const char *path, + const char *query, + bool is_connect) +{ + (void)data; + (void)conn; + (void)request; + (void)httpreq; + (void)path; + (void)query; + (void)is_connect; + return CURLE_OK; +} +#endif /* !CURL_DISABLE_HTTP_AUTH, else */ + +#if defined(USE_SPNEGO) || defined(USE_NTLM) || \ + !defined(CURL_DISABLE_DIGEST_AUTH) || \ + !defined(CURL_DISABLE_BASIC_AUTH) || \ + !defined(CURL_DISABLE_BEARER_AUTH) +static bool authcmp(const char *auth, const char *line) +{ + /* the auth string must not have an alnum following */ + size_t n = strlen(auth); + return curl_strnequal(auth, line, n) && !ISALNUM(line[n]); +} +#endif + +#ifdef USE_SPNEGO +static CURLcode auth_spnego(struct Curl_easy *data, + bool proxy, + const char *auth, + struct auth *authp, + uint32_t *availp) +{ + if((authp->avail & CURLAUTH_NEGOTIATE) || Curl_auth_is_spnego_supported()) { + *availp |= CURLAUTH_NEGOTIATE; + authp->avail |= CURLAUTH_NEGOTIATE; + + if(authp->picked == CURLAUTH_NEGOTIATE) { + struct connectdata *conn = data->conn; + CURLcode result = Curl_input_negotiate(data, conn, proxy, auth); + curlnegotiate *negstate = proxy ? &conn->proxy_negotiate_state : + &conn->http_negotiate_state; + if(!result) { + curlx_free(data->req.newurl); + data->req.newurl = Curl_bufref_dup(&data->state.url); + if(!data->req.newurl) + return CURLE_OUT_OF_MEMORY; + data->state.authproblem = FALSE; + /* we received a GSS auth token and we dealt with it fine */ + *negstate = GSS_AUTHRECV; + } + else + data->state.authproblem = TRUE; + } + } + return CURLE_OK; +} +#endif + +#ifdef USE_NTLM +static CURLcode auth_ntlm(struct Curl_easy *data, + bool proxy, + const char *auth, + struct auth *authp, + uint32_t *availp) +{ + /* NTLM support requires the SSL crypto libs */ + if((authp->avail & CURLAUTH_NTLM) || Curl_auth_is_ntlm_supported()) { + *availp |= CURLAUTH_NTLM; + authp->avail |= CURLAUTH_NTLM; + + if(authp->picked == CURLAUTH_NTLM) { + /* NTLM authentication is picked and activated */ + CURLcode result = Curl_input_ntlm(data, proxy, auth); + if(!result) + data->state.authproblem = FALSE; + else { + if(result == CURLE_OUT_OF_MEMORY) + return result; + infof(data, "NTLM authentication problem, ignoring."); + data->state.authproblem = TRUE; + } + } + } + return CURLE_OK; +} +#endif + +#ifndef CURL_DISABLE_DIGEST_AUTH +static CURLcode auth_digest(struct Curl_easy *data, + bool proxy, + const char *auth, + struct auth *authp, + uint32_t *availp) +{ + if(authp->avail & CURLAUTH_DIGEST) { + *availp |= CURLAUTH_DIGEST; + infof(data, "Ignoring duplicate digest auth header."); + } + else if(Curl_auth_is_digest_supported()) { + CURLcode result; + + *availp |= CURLAUTH_DIGEST; + authp->avail |= CURLAUTH_DIGEST; + + /* We call this function on input Digest headers even if Digest + * authentication is not activated yet, as we need to store the + * incoming data from this header in case we are going to use + * Digest */ + result = Curl_input_digest(data, proxy, auth); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + return result; + infof(data, "Digest authentication problem, ignoring."); + data->state.authproblem = TRUE; + } + } + return CURLE_OK; +} +#endif + +#ifndef CURL_DISABLE_BASIC_AUTH +static CURLcode auth_basic(struct Curl_easy *data, + struct auth *authp, + uint32_t *availp) +{ + *availp |= CURLAUTH_BASIC; + authp->avail |= CURLAUTH_BASIC; + if(authp->picked == CURLAUTH_BASIC) { + /* We asked for Basic authentication but got a 40X back anyway, which + means our name+password is not valid. */ + authp->avail = CURLAUTH_NONE; + infof(data, "Basic authentication problem, ignoring."); + data->state.authproblem = TRUE; + } + return CURLE_OK; +} +#endif + +#ifndef CURL_DISABLE_BEARER_AUTH +static CURLcode auth_bearer(struct Curl_easy *data, + struct auth *authp, + uint32_t *availp) +{ + *availp |= CURLAUTH_BEARER; + authp->avail |= CURLAUTH_BEARER; + if(authp->picked == CURLAUTH_BEARER) { + /* We asked for Bearer authentication but got a 40X back anyway, which + means our token is not valid. */ + authp->avail = CURLAUTH_NONE; + infof(data, "Bearer authentication problem, ignoring."); + data->state.authproblem = TRUE; + } + return CURLE_OK; +} +#endif + +/* + * Curl_http_input_auth() deals with Proxy-Authenticate: and WWW-Authenticate: + * headers. They are dealt with both in the transfer.c main loop and in the + * proxy CONNECT loop. + * + * The 'auth' line ends with a null byte without CR or LF present. + */ +CURLcode Curl_http_input_auth(struct Curl_easy *data, bool proxy, + const char *auth) /* the first non-space */ +{ + /* + * This resource requires authentication + */ +#if defined(USE_SPNEGO) || \ + defined(USE_NTLM) || \ + !defined(CURL_DISABLE_DIGEST_AUTH) || \ + !defined(CURL_DISABLE_BASIC_AUTH) || \ + !defined(CURL_DISABLE_BEARER_AUTH) + + uint32_t *availp; + struct auth *authp; + CURLcode result = CURLE_OK; + DEBUGASSERT(auth); + DEBUGASSERT(data); + + if(proxy) { + availp = &data->info.proxyauthavail; + authp = &data->state.authproxy; + } + else { + availp = &data->info.httpauthavail; + authp = &data->state.authhost; + } + + /* + * Here we check if we want the specific single authentication (using ==) and + * if we do, we initiate usage of it. + * + * If the provided authentication is wanted as one out of several accepted + * types (using &), we OR this authentication type to the authavail + * variable. + * + * Note: + * + * ->picked is first set to the 'want' value (one or more bits) before the + * request is sent, and then it is again set _after_ all response 401/407 + * headers have been received but then only to a single preferred method + * (bit). + */ + + while(*auth) { +#ifdef USE_SPNEGO + if(authcmp("Negotiate", auth)) + result = auth_spnego(data, proxy, auth, authp, availp); +#endif +#ifdef USE_NTLM + if(!result && authcmp("NTLM", auth)) + result = auth_ntlm(data, proxy, auth, authp, availp); +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + if(!result && authcmp("Digest", auth)) + result = auth_digest(data, proxy, auth, authp, availp); +#endif +#ifndef CURL_DISABLE_BASIC_AUTH + if(!result && authcmp("Basic", auth)) + result = auth_basic(data, authp, availp); +#endif +#ifndef CURL_DISABLE_BEARER_AUTH + if(authcmp("Bearer", auth)) + result = auth_bearer(data, authp, availp); +#endif + + if(result) + break; + + /* there may be multiple methods on one line, so keep reading */ + auth = strchr(auth, ','); + if(auth) /* if we are on a comma, skip it */ + auth++; + else + break; + curlx_str_passblanks(&auth); + } + return result; +#else + (void)data; + (void)proxy; + (void)auth; + /* nothing to do when disabled */ + return CURLE_OK; +#endif +} + +static void http_switch_to_get(struct Curl_easy *data, int code) +{ + const char *req = CURL_EASY_STR(data, STRING_CUSTOMREQUEST); + + if((req || data->state.httpreq != HTTPREQ_GET) && + (data->set.http_follow_mode == CURLFOLLOW_OBEYCODE)) { + NOVERBOSE((void)code); + infof(data, "Switch to GET because of %d response", code); + data->state.http_ignorecustom = TRUE; + } + else if(req && (data->set.http_follow_mode != CURLFOLLOW_FIRSTONLY)) + infof(data, "Stick to %s instead of GET", req); + + data->state.httpreq = HTTPREQ_GET; + Curl_creader_set_rewind(data, FALSE); +} + +#define HTTPREQ_IS_POST(data) \ + ((data)->state.httpreq == HTTPREQ_POST || \ + (data)->state.httpreq == HTTPREQ_POST_FORM || \ + (data)->state.httpreq == HTTPREQ_POST_MIME) + +CURLcode Curl_http_follow(struct Curl_easy *data, const char *newurl, + followtype type) +{ + bool disallowport = FALSE; + bool reachedmax = FALSE; + char *follow_url = NULL; + CURLUcode uc; + CURLcode rewind_result; + bool switch_to_get = FALSE; + + DEBUGASSERT(type != FOLLOW_NONE); + + if(type != FOLLOW_FAKE) + data->state.requests++; /* count all real follows */ + if(type == FOLLOW_REDIR) { + if((data->set.maxredirs != -1) && + (data->state.followlocation >= data->set.maxredirs)) { + reachedmax = TRUE; + type = FOLLOW_FAKE; /* switch to fake to store the would-be-redirected + to URL */ + } + else { + data->state.followlocation++; /* count redirect-followings, including + auth reloads */ + + if(data->set.http_auto_referer) { + CURLU *u; + char *referer = NULL; + + /* We are asked to automatically set the previous URL as the referer + when we get the next URL. We pick the ->url field, which may or may + not be 100% correct */ + Curl_bufref_free(&data->state.referer); + + /* Make a copy of the URL without credentials and fragment */ + u = curl_url(); + if(!u) + return CURLE_OUT_OF_MEMORY; + + uc = curl_url_set(u, CURLUPART_URL, + Curl_bufref_ptr(&data->state.url), 0); + if(!uc) + uc = curl_url_set(u, CURLUPART_FRAGMENT, NULL, 0); + if(!uc) + uc = curl_url_set(u, CURLUPART_USER, NULL, 0); + if(!uc) + uc = curl_url_set(u, CURLUPART_PASSWORD, NULL, 0); + if(!uc) + uc = curl_url_get(u, CURLUPART_URL, &referer, 0); + + curl_url_cleanup(u); + + if(uc || !referer) + return CURLE_OUT_OF_MEMORY; + + Curl_bufref_set(&data->state.referer, referer, 0, curl_free); + } + } + } + + if((type != FOLLOW_RETRY) && + (data->req.httpcode != 401) && (data->req.httpcode != 407) && + Curl_is_absolute_url(newurl, NULL, 0, FALSE)) { + /* If this is not redirect due to a 401 or 407 response and an absolute + URL: do not allow a custom port number */ + disallowport = TRUE; + } + + DEBUGASSERT(data->state.uh); + uc = curl_url_set(data->state.uh, CURLUPART_URL, newurl, (unsigned int) + ((type == FOLLOW_FAKE) ? CURLU_NON_SUPPORT_SCHEME : + ((type == FOLLOW_REDIR) ? CURLU_URLENCODE : 0) | + CURLU_ALLOW_SPACE | + (data->set.path_as_is ? CURLU_PATH_AS_IS : 0))); + if(uc) { + if((uc == CURLUE_OUT_OF_MEMORY) || (type != FOLLOW_FAKE)) { + failf(data, "The redirect target URL could not be parsed: %s", + curl_url_strerror(uc)); + return Curl_uc_to_curlcode(uc); + } + + /* the URL could not be parsed for some reason, but since this is FAKE + mode, duplicate the field as-is */ + follow_url = curlx_strdup(newurl); + if(!follow_url) + return CURLE_OUT_OF_MEMORY; + } + else { + CURLU *u = curl_url(); + if(!u) + return CURLE_OUT_OF_MEMORY; + uc = curl_url_set(u, CURLUPART_URL, + Curl_bufref_ptr(&data->state.url), + CURLU_URLENCODE | CURLU_ALLOW_SPACE); + if(!uc) + uc = curl_url_get(data->state.uh, CURLUPART_URL, &follow_url, 0); + if(uc) { + curl_url_cleanup(u); + return Curl_uc_to_curlcode(uc); + } + +#ifndef CURL_DISABLE_DIGEST_AUTH + { + bool same_origin = Curl_url_same_origin(u, data->state.uh); + curl_url_cleanup(u); + if(!same_origin) + Curl_auth_digest_cleanup(&data->state.digest); + } +#else + curl_url_cleanup(u); +#endif + } + DEBUGASSERT(follow_url); + + if(type == FOLLOW_FAKE) { + /* we are only figuring out the new URL if we would have followed locations + but now we are done so we can get out! */ + data->info.wouldredirect = follow_url; + + if(reachedmax) { + failf(data, "Maximum (%d) redirects followed", data->set.maxredirs); + return CURLE_TOO_MANY_REDIRECTS; + } + return CURLE_OK; + } + + if(disallowport) + data->state.allow_port = FALSE; + + Curl_bufref_set(&data->state.url, follow_url, 0, curl_free); + rewind_result = Curl_req_soft_reset(&data->req, data); + infof(data, "Issue another request to this URL: '%s'", follow_url); + if((data->set.http_follow_mode == CURLFOLLOW_FIRSTONLY) && + !data->state.http_ignorecustom && + CURL_EASY_STR(data, STRING_CUSTOMREQUEST)) { + data->state.http_ignorecustom = TRUE; + infof(data, "Drop custom request method for next request"); + } + + /* + * We get here when the HTTP code is 300-399 (and 401). We need to perform + * differently based on exactly what return code there was. + * + * News from 7.10.6: we can also get here on a 401 or 407, in case we act on + * an HTTP (proxy-) authentication scheme other than Basic. + */ + switch(data->info.httpcode) { + /* 401 - Act on a WWW-Authenticate, we keep on moving and do the + Authorization: XXXX header in the HTTP request code snippet */ + /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the + Proxy-Authorization: XXXX header in the HTTP request code snippet */ + /* 300 - Multiple Choices */ + /* 306 - Not used */ + /* 307 - Temporary Redirect */ + default: /* for all above (and the unknown ones) */ + /* Some codes are explicitly mentioned since I have checked RFC2616 and + * they seem to be OK to POST to. + */ + break; + case 301: /* Moved Permanently */ + /* (quote from RFC7231, section 6.4.2) + * + * Note: For historical reasons, a user agent MAY change the request + * method from POST to GET for the subsequent request. If this + * behavior is undesired, the 307 (Temporary Redirect) status code + * can be used instead. + * + * ---- + * + * Many webservers expect this, so these servers often answers to a POST + * request with an error page. To be sure that libcurl gets the page that + * most user agents would get, libcurl has to force GET. + * + * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and + * can be overridden with CURLOPT_POSTREDIR. + */ + if(HTTPREQ_IS_POST(data) && !data->set.post301) { + http_switch_to_get(data, 301); + switch_to_get = TRUE; + } + break; + case 302: /* Found */ + /* (quote from RFC7231, section 6.4.3) + * + * Note: For historical reasons, a user agent MAY change the request + * method from POST to GET for the subsequent request. If this + * behavior is undesired, the 307 (Temporary Redirect) status code + * can be used instead. + * + * ---- + * + * Many webservers expect this, so these servers often answers to a POST + * request with an error page. To be sure that libcurl gets the page that + * most user agents would get, libcurl has to force GET. + * + * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and + * can be overridden with CURLOPT_POSTREDIR. + */ + if(HTTPREQ_IS_POST(data) && !data->set.post302) { + http_switch_to_get(data, 302); + switch_to_get = TRUE; + } + break; + + case 303: /* See Other */ + /* 'See Other' location is not the resource but a substitute for the + * resource. In this case we switch the method to GET/HEAD, unless the + * method is POST and the user specified to keep it as POST. + */ + if(!HTTPREQ_IS_POST(data) || !data->set.post303) { + http_switch_to_get(data, 303); + switch_to_get = TRUE; + } + break; + case 304: /* Not Modified */ + /* 304 means we did a conditional request and it was "Not modified". + * We should not get any Location: header in this response! + */ + break; + case 305: /* Use Proxy */ + /* (quote from RFC2616, section 10.3.6): + * "The requested resource MUST be accessed through the proxy given + * by the Location field. The Location field gives the URI of the + * proxy. The recipient is expected to repeat this single request + * via the proxy. 305 responses MUST only be generated by origin + * servers." + */ + break; + } + + /* When rewind of upload data failed and we are not switching to GET, + * we need to fail the follow, as we cannot send the data again. */ + if(rewind_result && !switch_to_get) + return rewind_result; + + Curl_pgrsTime(data, TIMER_REDIRECT); + Curl_pgrsResetTransferSizes(data); + + return CURLE_OK; +} + +/* + * Curl_compareheader() + * + * Returns TRUE if 'headerline' contains the 'header' with given 'content' + * (within a comma-separated list of tokens). Pass 'header' WITH the colon. + * + * @unittest: 1625 + */ +bool Curl_compareheader(const char *headerline, /* line to check */ + const char *header, /* header keyword _with_ colon */ + const size_t hlen, /* len of the keyword in bytes */ + const char *content, /* content string to find */ + const size_t clen) /* len of the content in bytes */ +{ + /* RFC2616, section 4.2 says: "Each header field consists of a name followed + * by a colon (":") and the field value. Field names are case-insensitive. + * The field value MAY be preceded by any amount of LWS, though a single SP + * is preferred." */ + + const char *p; + struct Curl_str val; + DEBUGASSERT(hlen); + DEBUGASSERT(clen); + DEBUGASSERT(header); + DEBUGASSERT(content); + + if(!curl_strnequal(headerline, header, hlen)) + return FALSE; /* does not start with header */ + + /* pass the header */ + p = &headerline[hlen]; + + if(curlx_str_cspn(&p, &val, "\r\n")) + return FALSE; + curlx_str_trimblanks(&val); + + /* find the content string in the rest of the line */ + if(curlx_strlen(&val) >= clen) { + size_t len; + p = curlx_str(&val); + for(len = curlx_strlen(&val); len >= clen;) { + struct Curl_str next; + const char *o = p; + /* after a match there must be a comma, space, newline or null byte */ + if(curl_strnequal(p, content, clen) && + ((p[clen] == ',') || ISBLANK(p[clen]) || ISNEWLINE(p[clen]) || + !p[clen])) + return TRUE; /* match! */ + /* advance to the next comma */ + if(curlx_str_until(&p, &next, len, ',') || + curlx_str_single(&p, ',')) + break; /* no comma, get out */ + + /* if there are more dummy commas, move over them as well */ + do + curlx_str_passblanks(&p); + while(!curlx_str_single(&p, ',')); + /* trailing blanks may move the parsing point past the value end, + then there is nothing left to match */ + if((size_t)(p - o) > len) + break; + len -= (p - o); + } + } + return FALSE; /* no match */ +} + +struct cr_exp100_ctx { + struct Curl_creader super; + struct curltime start; /* time started waiting */ + enum expect100 state; +}; + +/* Expect: 100-continue client reader, blocking uploads */ + +static void http_exp100_continue(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_exp100_ctx *ctx = reader->ctx; + if(ctx->state > EXP100_SEND_DATA) { + ctx->state = EXP100_SEND_DATA; + Curl_expire_clear(data, EXPIRE_100_TIMEOUT); + } +} + +static CURLcode cr_exp100_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *nread, bool *eos) +{ + struct cr_exp100_ctx *ctx = reader->ctx; + timediff_t ms; + + switch(ctx->state) { + case EXP100_SENDING_REQUEST: + if(!Curl_req_sendbuf_empty(data)) { + /* The initial request data has not been fully sent yet. Do + * not start the timer yet. */ + DEBUGF(infof(data, "cr_exp100_read, request not full sent yet")); + *nread = 0; + *eos = FALSE; + return CURLE_OK; + } + /* We are now waiting for a reply from the server or + * a timeout on our side IFF the request has been fully sent. */ + DEBUGF(infof(data, "cr_exp100_read, start AWAITING_CONTINUE, " + "timeout %dms", data->set.expect_100_timeout)); + ctx->state = EXP100_AWAITING_CONTINUE; + ctx->start = *Curl_pgrs_now(data); + Curl_expire_set(data, EXPIRE_100_TIMEOUT, + data->set.expect_100_timeout, &ctx->start); + *nread = 0; + *eos = FALSE; + return CURLE_OK; + case EXP100_FAILED: + DEBUGF(infof(data, "cr_exp100_read, expectation failed, error")); + *nread = 0; + *eos = FALSE; + return CURLE_READ_ERROR; + case EXP100_AWAITING_CONTINUE: + ms = curlx_ptimediff_ms(Curl_pgrs_now(data), &ctx->start); + if(ms < data->set.expect_100_timeout) { + DEBUGF(infof(data, "cr_exp100_read, AWAITING_CONTINUE, not expired")); + *nread = 0; + *eos = FALSE; + return CURLE_OK; + } + /* we have waited long enough, continue anyway */ + http_exp100_continue(data, reader); + infof(data, "Done waiting for 100-continue"); + FALLTHROUGH(); + default: + DEBUGF(infof(data, "cr_exp100_read, pass through")); + return Curl_creader_read(data, reader->next, buf, blen, nread, eos); + } +} + +static void cr_exp100_done(struct Curl_easy *data, + struct Curl_creader *reader, int premature) +{ + struct cr_exp100_ctx *ctx = reader->ctx; + ctx->state = premature ? EXP100_FAILED : EXP100_SEND_DATA; + Curl_expire_clear(data, EXPIRE_100_TIMEOUT); +} + +static const struct Curl_crtype cr_exp100 = { + "cr-exp100", + Curl_creader_def_init, + cr_exp100_read, + Curl_creader_def_close, + Curl_creader_def_needs_rewind, + Curl_creader_def_total_length, + Curl_creader_def_resume_from, + Curl_creader_def_cntrl, + Curl_creader_def_is_paused, + cr_exp100_done, + sizeof(struct cr_exp100_ctx) +}; + +static CURLcode http_exp100_add_reader(struct Curl_easy *data) +{ + struct Curl_creader *reader = NULL; + CURLcode result; + + result = Curl_creader_create(&reader, data, &cr_exp100, CURL_CR_PROTOCOL); + if(!result) + result = Curl_creader_add(data, reader); + if(!result) { + struct cr_exp100_ctx *ctx = reader->ctx; + ctx->state = EXP100_SENDING_REQUEST; + } + + if(result && reader) + Curl_creader_free(data, reader); + return result; +} + +static void http_exp100_got100(struct Curl_easy *data) +{ + struct Curl_creader *r = Curl_creader_get_by_type(data, &cr_exp100); + if(r) + http_exp100_continue(data, r); +} + +static bool http_exp100_is_waiting(struct Curl_easy *data) +{ + struct Curl_creader *r = Curl_creader_get_by_type(data, &cr_exp100); + if(r) { + struct cr_exp100_ctx *ctx = r->ctx; + return ctx->state == EXP100_AWAITING_CONTINUE; + } + return FALSE; +} + +static void http_exp100_send_anyway(struct Curl_easy *data) +{ + struct Curl_creader *r = Curl_creader_get_by_type(data, &cr_exp100); + if(r) + http_exp100_continue(data, r); +} + +static bool http_exp100_is_selected(struct Curl_easy *data) +{ + struct Curl_creader *r = Curl_creader_get_by_type(data, &cr_exp100); + return !!r; +} + +/* this returns the socket to wait for in the DO and DOING state for the multi + interface and then we are always _sending_ a request and thus we wait for + the single socket to become writable only */ +CURLcode Curl_http_doing_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + /* write mode */ + return Curl_pollset_add_out(data, ps, data->conn->sock[FIRSTSOCKET]); +} + +CURLcode Curl_http_perform_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + + if(CURL_REQ_WANT_RECV(data)) { + result = Curl_pollset_add_in(data, ps, conn->sock[FIRSTSOCKET]); + } + + /* on a "Expect: 100-continue" timed wait, do not poll for outgoing */ + if(!result && Curl_req_want_send(data) && !http_exp100_is_waiting(data)) { + result = Curl_pollset_add_out(data, ps, conn->sock[FIRSTSOCKET]); + } + return result; +} + +static CURLcode http_write_header(struct Curl_easy *data, + const char *hd, size_t hdlen) +{ + CURLcode result; + int writetype; + + /* now, only output this if the header AND body are requested: + */ + Curl_debug(data, CURLINFO_HEADER_IN, hd, hdlen); + + writetype = CLIENTWRITE_HEADER | + ((data->req.httpcode / 100 == 1) ? CLIENTWRITE_1XX : 0); + + result = Curl_client_write(data, writetype, hd, hdlen); + if(result) + return result; + + result = Curl_bump_headersize(data, hdlen, FALSE); + if(result) + return result; + + data->req.deductheadercount = (100 <= data->req.httpcode && + 199 >= data->req.httpcode) ? + data->req.headerbytecount : 0; + return result; +} + +/* + * Curl_http_done() gets called after a single HTTP request has been + * performed. + */ + +CURLcode Curl_http_done(struct Curl_easy *data, + CURLcode status, bool premature) +{ + struct connectdata *conn = data->conn; + + /* Clear multipass flag. If authentication is not done yet, then it will get + * a chance to be set back to true when we output the next auth header */ + data->state.authhost.multipass = FALSE; + data->state.authproxy.multipass = FALSE; + + if(curlx_dyn_len(&data->state.headerb)) { + (void)http_write_header(data, curlx_dyn_ptr(&data->state.headerb), + curlx_dyn_len(&data->state.headerb)); + } + curlx_dyn_reset(&data->state.headerb); + + if(status) + return status; + + if(!premature && /* this check is pointless when DONE is called before the + entire operation is complete */ + !conn->bits.retry && + !data->set.connect_only && + (data->req.bytecount + + data->req.headerbytecount - + data->req.deductheadercount) <= 0) { + /* If this connection is not closed to be retried, AND nothing was + read from the HTTP server (that counts), this cannot be right so we + return an error here */ + failf(data, "Empty reply from server"); + /* Mark it as closed to avoid the "left intact" message */ + streamclose(conn); + return CURLE_GOT_NOTHING; + } + + return CURLE_OK; +} + +/* Determine if we may use HTTP 1.1 for this request. */ +static bool http_may_use_1_1(const struct Curl_easy *data) +{ + const struct connectdata *conn = data->conn; + /* We have seen a previous response for *this* transfer with 1.0, + * on another connection or the same one. */ + if(data->state.http_neg.rcvd_min == 10) + return FALSE; + /* We have seen a previous response on *this* connection with 1.0. */ + if(conn && conn->httpversion_seen == 10) + return FALSE; + /* We want 1.0 and have seen no previous response on *this* connection + with a higher version (maybe no response at all yet). */ + if(data->state.http_neg.only_10 && + (!conn || conn->httpversion_seen <= 10)) + return FALSE; + /* We are not restricted to use 1.0 only. */ + return !data->state.http_neg.only_10; +} + +static unsigned char http_request_version(struct Curl_easy *data) +{ + unsigned char v = Curl_conn_http_version(data, data->conn); + if(!v) { + /* No specific HTTP connection filter installed. */ + v = http_may_use_1_1(data) ? 11 : 10; + } + return v; +} + +static const char *get_http_string(int httpversion) +{ + switch(httpversion) { + case 30: + return "3"; + case 20: + return "2"; + case 11: + return "1.1"; + default: + return "1.0"; + } +} + +CURLcode Curl_add_custom_headers(struct Curl_easy *data, + bool is_connect, int httpversion, + struct dynbuf *req) +{ + struct curl_slist *h[2]; + struct curl_slist *headers; + int numlists = 1; /* by default */ + int i; + +#ifndef CURL_DISABLE_PROXY + enum Curl_proxy_use proxy; + + if(is_connect) + proxy = HEADER_CONNECT; + else + proxy = data->conn->bits.origin_is_proxy ? HEADER_PROXY : HEADER_SERVER; + + switch(proxy) { + case HEADER_SERVER: + h[0] = data->set.headers; + break; + case HEADER_PROXY: + h[0] = data->set.headers; + if(data->set.sep_headers) { + h[1] = data->set.proxyheaders; + numlists++; + } + break; + case HEADER_CONNECT: + if(data->set.sep_headers) + h[0] = data->set.proxyheaders; + else + h[0] = data->set.headers; + break; + case HEADER_CONNECT_UDP: + if(data->set.sep_headers) + h[0] = data->set.proxyheaders; + else + h[0] = data->set.headers; + break; + } +#else + (void)is_connect; + h[0] = data->set.headers; +#endif + + /* loop through one or two lists */ + for(i = 0; i < numlists; i++) { + for(headers = h[i]; headers; headers = headers->next) { + CURLcode result = CURLE_OK; + bool blankheader = FALSE; + struct Curl_str name; + const char *p = headers->data; + const char *origp = p; + size_t hlen = strlen(origp); + + /* explicitly asked to send header without content is done by a header + that ends with a semicolon, but there must be no colon present in the + name */ + if(!curlx_str_until(&p, &name, hlen, ';') && + !curlx_str_single(&p, ';') && + !curlx_str_single(&p, '\0') && + !memchr(curlx_str(&name), ':', curlx_strlen(&name))) + blankheader = TRUE; + else { + p = origp; + if(!curlx_str_until(&p, &name, hlen, ':') && + !curlx_str_single(&p, ':')) { + struct Curl_str val; + curlx_str_untilnl(&p, &val, hlen); + curlx_str_trimblanks(&val); + if(!curlx_strlen(&val)) + /* no content, do not send this */ + continue; + } + else + /* no colon */ + continue; + } + + /* a field name is a token and carries no surrounding whitespace, so + trim the parsed name before matching. Otherwise `Authorization :` + (space before the colon) slips past the Authorization/Cookie check + below and gets forwarded to another host on a redirect. */ + curlx_str_trimblanks(&name); + + /* only send this if the contents was non-blank or done special */ + + if(data->state.http_host && + /* a Host: header was sent already, do not pass on any custom + Host: header as that will produce *two* in the same + request! */ + curlx_str_casecompare(&name, "Host")) + ; + else if(data->state.httpreq == HTTPREQ_POST_FORM && + /* this header (extended by formdata.c) is sent later */ + curlx_str_casecompare(&name, "Content-Type")) + ; + else if(data->state.httpreq == HTTPREQ_POST_MIME && + /* this header is sent later */ + curlx_str_casecompare(&name, "Content-Type")) + ; + else if(data->req.authneg && + /* while doing auth neg, do not allow the custom length since + we will force length zero then */ + curlx_str_casecompare(&name, "Content-Length")) + ; + else if(curlx_str_casecompare(&name, "Connection")) + /* Connection headers are handled specially */ + ; + else if((httpversion >= 20) && + curlx_str_casecompare(&name, "Transfer-Encoding")) + /* HTTP/2 does not support chunked requests */ + ; + else if((curlx_str_casecompare(&name, "Authorization") || + curlx_str_casecompare(&name, "Cookie")) && + /* be careful of sending this potentially sensitive header to + other hosts */ + !Curl_auth_allowed_to_host(data)) + ; + else if(blankheader) { + result = curlx_dyn_addn(req, curlx_str(&name), curlx_strlen(&name)); + if(!result) + result = curlx_dyn_addn(req, STRCONST(":\r\n")); + } + else + result = curlx_dyn_addf(req, "%s\r\n", origp); + + if(result) + return result; + } + } + + return CURLE_OK; +} + +#ifndef CURL_DISABLE_PARSEDATE +CURLcode Curl_add_timecondition(struct Curl_easy *data, + struct dynbuf *req) +{ + const struct tm *tm; + struct tm keeptime; + CURLcode result; + char datestr[80]; + const char *condp; + size_t len; + + if(data->set.timecondition == CURL_TIMECOND_NONE) + /* no condition was asked for */ + return CURLE_OK; + + result = curlx_gmtime(data->set.timevalue, &keeptime); + if(result) { + failf(data, "Invalid TIMEVALUE"); + return result; + } + tm = &keeptime; + + switch(data->set.timecondition) { + default: + DEBUGF(infof(data, "invalid time condition")); + return CURLE_BAD_FUNCTION_ARGUMENT; + + case CURL_TIMECOND_IFMODSINCE: + condp = "If-Modified-Since"; + len = 17; + break; + case CURL_TIMECOND_IFUNMODSINCE: + condp = "If-Unmodified-Since"; + len = 19; + break; + case CURL_TIMECOND_LASTMOD: + condp = "Last-Modified"; + len = 13; + break; + } + + if(Curl_checkheaders(data, condp, len)) { + /* A custom header was specified; it will be sent instead. */ + return CURLE_OK; + } + + /* The If-Modified-Since header family should have their times set in + * GMT as RFC2616 defines: "All HTTP date/time stamps MUST be + * represented in Greenwich Mean Time (GMT), without exception. For the + * purposes of HTTP, GMT is exactly equal to UTC (Coordinated Universal + * Time)." (see page 20 of RFC2616). + */ + + /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */ + curl_msnprintf(datestr, sizeof(datestr), + "%s: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n", + condp, + Curl_wkday[tm->tm_wday ? tm->tm_wday - 1 : 6], + tm->tm_mday, + Curl_month[tm->tm_mon], + tm->tm_year + 1900, + tm->tm_hour, + tm->tm_min, + tm->tm_sec); + + result = curlx_dyn_add(req, datestr); + return result; +} +#else +/* disabled */ +CURLcode Curl_add_timecondition(struct Curl_easy *data, + struct dynbuf *req) +{ + (void)data; + (void)req; + return CURLE_OK; +} +#endif + +void Curl_http_method(struct Curl_easy *data, + const char **method, Curl_HttpReq *reqp) +{ + Curl_HttpReq httpreq = (Curl_HttpReq)data->state.httpreq; + const char *request; +#ifndef CURL_DISABLE_WEBSOCKETS + if(data->conn->scheme->protocol & (CURLPROTO_WS | CURLPROTO_WSS)) + httpreq = HTTPREQ_GET; + else +#endif + if((data->conn->scheme->protocol & (PROTO_FAMILY_HTTP | CURLPROTO_FTP)) && + data->state.upload) + httpreq = HTTPREQ_PUT; + + /* Now set the 'request' pointer to the proper request string */ + if(!data->state.http_ignorecustom && + CURL_EASY_STR(data, STRING_CUSTOMREQUEST)) { + request = CURL_EASY_STR(data, STRING_CUSTOMREQUEST); + } + else { + if(data->req.no_body) + request = "HEAD"; + else { + DEBUGASSERT((httpreq >= HTTPREQ_GET) && (httpreq <= HTTPREQ_HEAD)); + switch(httpreq) { + case HTTPREQ_POST: + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + request = "POST"; + break; + case HTTPREQ_PUT: + request = "PUT"; + break; + default: /* this should never happen */ + case HTTPREQ_GET: + request = "GET"; + break; + case HTTPREQ_HEAD: + request = "HEAD"; + break; + } + } + } + *method = request; + *reqp = httpreq; +} + +static CURLcode http_set_aptr_host(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + const char *ptr = NULL; + + curlx_safefree(data->state.http_host); +#ifndef CURL_DISABLE_COOKIES + curlx_safefree(data->req.cookiehost); +#endif + + if(Curl_peer_equal(data->state.initial_origin, data->state.origin)) + ptr = Curl_checkheaders(data, STRCONST("Host")); + + if(ptr) { +#ifndef CURL_DISABLE_COOKIES + /* If we have a given custom Host: header, we extract the hostname in + order to possibly use it for cookie reasons later on. We only allow the + custom Host: header if this is NOT a redirect, as setting Host: in the + redirected request is being out on thin ice. Except if the hostname + is the same as the first one! */ + char *cookiehost; + CURLcode result = copy_custom_value(ptr, &cookiehost); + if(result) + return result; + if(!*cookiehost) + /* ignore empty data */ + curlx_free(cookiehost); + else { + /* If the host begins with '[', we start searching for the port after + the bracket has been closed */ + if(*cookiehost == '[') { + char *closingbracket; + /* since the 'cookiehost' is an allocated memory area that will be + freed later we cannot increment the pointer */ + memmove(cookiehost, cookiehost + 1, strlen(cookiehost) - 1); + closingbracket = strchr(cookiehost, ']'); + if(closingbracket) + *closingbracket = 0; + } + else { + int startsearch = 0; + char *colon = strchr(cookiehost + startsearch, ':'); + if(colon) + *colon = 0; /* The host must not include an embedded port number */ + } + data->req.cookiehost = cookiehost; + } +#endif + + if(!curl_strequal("Host:", ptr)) { + data->state.http_host = curl_maprintf("Host:%s", &ptr[5]); + if(!data->state.http_host) + return CURLE_OUT_OF_MEMORY; + } + } + else { + /* This is the HTTP Host: header, so we want + * - for IPv6 origins: "[ipv6-address]" where the IPv6 address is + * found in origin->hostname, stripped of zoneid/scopeid. + * - the (IDN converted) origin->hostname (DNS name or IPv4) otherwise. + * Note: zoneid/scopeid only applies to local routing and has no + * meaning on the remote HTTP server (eg. would confuse it). */ + bool ipv6 = (bool)data->state.origin->ipv6; + struct dynbuf tmp; + size_t hlen; + CURLcode result; + + curlx_dyn_init(&tmp, DYN_HTTP_REQUEST); + result = curlx_dyn_addn(&tmp, STRCONST("Host: ")); + if(!result && ipv6) + result = curlx_dyn_addn(&tmp, STRCONST("[")); + if(!result) + result = curlx_dyn_add(&tmp, data->state.origin->hostname); + if(!result && ipv6) + result = curlx_dyn_addn(&tmp, STRCONST("]")); + if(!result && + ((data->state.origin->port != data->state.origin->scheme->defport) || + (data->state.origin->scheme->family != conn->scheme->family))) { + result = curlx_dyn_addf(&tmp, ":%u", data->state.origin->port); + } + + data->state.http_host = result ? NULL : curlx_dyn_take(&tmp, &hlen); + curlx_dyn_free(&tmp); + return result; + } + return CURLE_OK; +} + +/* + * Append the request-target to the HTTP request + */ +static CURLcode http_target(struct Curl_easy *data, + struct dynbuf *r) +{ + CURLcode result = CURLE_OK; + const char *path = data->state.up.path; + const char *query = data->state.up.query; +#ifndef CURL_DISABLE_PROXY + struct connectdata *conn = data->conn; +#endif + + if(CURL_EASY_STR(data, STRING_TARGET)) { + path = CURL_EASY_STR(data, STRING_TARGET); + query = NULL; + } + +#ifndef CURL_DISABLE_PROXY + if(conn->bits.origin_is_proxy) { + /* Using a proxy but does not tunnel through it */ + + /* The path sent to the proxy is in fact the entire URL, but if the remote + host is a IDN-name, we must make sure that the request we produce only + uses the decoded hostname! */ + + /* and no fragment part */ + CURLUcode uc; + char *url; + CURLU *h = curl_url_dup(data->state.uh); + if(!h) + return CURLE_OUT_OF_MEMORY; + + if(!data->state.origin->ipv6 && + (data->state.origin->user_hostname != data->state.origin->hostname)) { + uc = curl_url_set(h, CURLUPART_HOST, data->state.origin->hostname, 0); + if(uc) { + curl_url_cleanup(h); + return CURLE_OUT_OF_MEMORY; + } + } + uc = curl_url_set(h, CURLUPART_FRAGMENT, NULL, 0); + if(uc) { + curl_url_cleanup(h); + return CURLE_OUT_OF_MEMORY; + } + + if(data->state.origin->scheme == &Curl_scheme_http) { + /* when getting HTTP, we do not want the userinfo the URL */ + uc = curl_url_set(h, CURLUPART_USER, NULL, 0); + if(uc) { + curl_url_cleanup(h); + return CURLE_OUT_OF_MEMORY; + } + uc = curl_url_set(h, CURLUPART_PASSWORD, NULL, 0); + if(uc) { + curl_url_cleanup(h); + return CURLE_OUT_OF_MEMORY; + } + } + else if(data->state.creds && (data->state.creds->source != CREDS_URL)) { + /* credentials not from the URL need to be set */ + uc = curl_url_set(h, CURLUPART_USER, + data->state.creds->user, CURLU_URLENCODE); + if(!uc) + uc = curl_url_set(h, CURLUPART_PASSWORD, + data->state.creds->passwd, CURLU_URLENCODE); + if(uc) { + curl_url_cleanup(h); + return Curl_uc_to_curlcode(uc); + } + } + + /* Extract the URL to use in the request. */ + uc = curl_url_get(h, CURLUPART_URL, &url, CURLU_NO_DEFAULT_PORT); + if(uc) { + curl_url_cleanup(h); + return CURLE_OUT_OF_MEMORY; + } + + curl_url_cleanup(h); + + /* target or URL */ + result = curlx_dyn_add(r, CURL_EASY_STR(data, STRING_TARGET) ? + CURL_EASY_STR(data, STRING_TARGET) : url); + curlx_free(url); + if(result) + return result; + + if((data->state.origin->scheme == &Curl_scheme_ftp) && + data->set.proxy_transfer_mode) { + /* when doing ftp, append ;type=<a|i> if not present */ + size_t len = strlen(path); + bool type_present = FALSE; + if((len >= 7) && !memcmp(&path[len - 7], ";type=", 6)) { + switch(Curl_raw_toupper(path[len - 1])) { + case 'A': + case 'D': + case 'I': + type_present = TRUE; + break; + } + } + if(!type_present) { + result = curlx_dyn_addf(r, ";type=%c", + data->state.prefer_ascii ? 'a' : 'i'); + if(result) + return result; + } + } + } + + else +#endif + { + result = curlx_dyn_add(r, path); + if(result) + return result; + if(query) + result = curlx_dyn_addf(r, "?%s", query); + } + + return result; +} + +#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API) +static CURLcode set_post_reader(struct Curl_easy *data, Curl_HttpReq httpreq) +{ + CURLcode result; + + switch(httpreq) { +#ifndef CURL_DISABLE_MIME + case HTTPREQ_POST_MIME: + data->state.mimepost = data->set.mimepostp; + break; +#endif +#ifndef CURL_DISABLE_FORM_API + case HTTPREQ_POST_FORM: + /* Convert the form structure into a mime structure, then keep + the conversion */ + if(!data->state.formp) { + data->state.formp = curlx_calloc(1, sizeof(curl_mimepart)); + if(!data->state.formp) + return CURLE_OUT_OF_MEMORY; + Curl_mime_cleanpart(data->state.formp); + result = Curl_getformdata(data, data->state.formp, data->set.httppost, + data->state.fread_func); + if(result) { + curlx_safefree(data->state.formp); + return result; + } + data->state.mimepost = data->state.formp; + } + break; +#endif + default: + data->state.mimepost = NULL; + break; + } + + switch(httpreq) { + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + /* This is form posting using mime data. */ +#ifndef CURL_DISABLE_MIME + if(data->state.mimepost) { + const char *cthdr = Curl_checkheaders(data, STRCONST("Content-Type")); + + /* Read and seek body only. */ + data->state.mimepost->flags |= MIME_BODY_ONLY; + + /* Prepare the mime structure headers & set content type. */ + + if(cthdr) + for(cthdr += 13; *cthdr == ' '; cthdr++) + ; + else if(data->state.mimepost->kind == MIMEKIND_MULTIPART) + cthdr = "multipart/form-data"; + + curl_mime_headers(data->state.mimepost, data->set.headers, 0); + result = Curl_mime_prepare_headers(data, data->state.mimepost, cthdr, + NULL, MIMESTRATEGY_FORM); + if(result) + return result; + curl_mime_headers(data->state.mimepost, NULL, 0); + result = Curl_creader_set_mime(data, data->state.mimepost); + if(result) + return result; + } + else +#endif + { + result = Curl_creader_set_null(data); + } + data->state.infilesize = Curl_creader_total_length(data); + return result; + + default: + return Curl_creader_set_null(data); + } + /* never reached */ +} +#endif + +static CURLcode set_reader(struct Curl_easy *data, Curl_HttpReq httpreq) +{ + CURLcode result = CURLE_OK; + curl_off_t postsize = data->state.infilesize; + + DEBUGASSERT(data->conn); + + if(data->req.authneg) { + return Curl_creader_set_null(data); + } + + switch(httpreq) { + case HTTPREQ_PUT: /* Let's PUT the data to the server! */ + return postsize ? Curl_creader_set_fread(data, postsize) : + Curl_creader_set_null(data); + +#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API) + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + return set_post_reader(data, httpreq); +#endif + + case HTTPREQ_POST: + /* this is the simple POST, using x-www-form-urlencoded style */ + /* the size of the post body */ + if(!postsize) { + result = Curl_creader_set_null(data); + } + else if(data->set.postfields) { + size_t plen = curlx_sotouz_range(postsize, 0, SIZE_MAX); + if(plen == SIZE_MAX) + return CURLE_OUT_OF_MEMORY; + else if(plen) + result = Curl_creader_set_buf(data, data->set.postfields, plen); + else + result = Curl_creader_set_null(data); + } + else { + /* we read the bytes from the callback. In case "chunked" encoding + * is forced by the application, we disregard `postsize`. This is + * a backward compatibility decision to earlier versions where + * chunking disregarded this. See issue #13229. */ + bool chunked = FALSE; + char *ptr = Curl_checkheaders(data, STRCONST("Transfer-Encoding")); + if(ptr) { + /* Some kind of TE is requested, check if 'chunked' is chosen */ + chunked = Curl_compareheader(ptr, STRCONST("Transfer-Encoding:"), + STRCONST("chunked")); + } + result = Curl_creader_set_fread(data, chunked ? -1 : postsize); + } + return result; + + default: + /* HTTP GET/HEAD download, has no body, needs no Content-Length */ + data->state.infilesize = 0; + return Curl_creader_set_null(data); + } + /* not reached */ +} + +static CURLcode http_resume(struct Curl_easy *data, Curl_HttpReq httpreq) +{ + if((HTTPREQ_POST == httpreq || HTTPREQ_PUT == httpreq) && + data->state.resume_from) { + /********************************************************************** + * Resuming upload in HTTP means that we PUT or POST and that we have + * got a resume_from value set. The resume value has already created + * a Range: header that will be passed along. We need to "fast forward" + * the file the given number of bytes and decrease the assume upload + * file size before we continue this venture in the dark lands of HTTP. + * Resuming mime/form posting at an offset > 0 has no sense and is ignored. + *********************************************************************/ + + if(data->state.resume_from < 0) { + /* + * This is meant to get the size of the present remote-file by itself. + * We do not support this now. Bail out! + */ + data->state.resume_from = 0; + } + + if(data->state.resume_from && !data->req.authneg) { + /* only act on the first request */ + CURLcode result; + result = Curl_creader_resume_from(data, data->state.resume_from); + if(result) { + failf(data, "Unable to resume from offset %" FMT_OFF_T, + data->state.resume_from); + return result; + } + } + } + return CURLE_OK; +} + +static CURLcode http_req_set_TE(struct Curl_easy *data, + struct dynbuf *req, + int httpversion) +{ + CURLcode result = CURLE_OK; + const char *ptr; + + ptr = Curl_checkheaders(data, STRCONST("Transfer-Encoding")); + if(ptr) { + /* Some kind of TE is requested, check if 'chunked' is chosen */ + data->req.upload_chunky = + Curl_compareheader(ptr, + STRCONST("Transfer-Encoding:"), STRCONST("chunked")); + if(data->req.upload_chunky && (httpversion >= 20)) { + infof(data, "suppressing chunked transfer encoding on connection " + "using HTTP version 2 or higher"); + data->req.upload_chunky = FALSE; + } + } + else { + curl_off_t req_clen = Curl_creader_total_length(data); + + if(req_clen < 0) { + /* indeterminate request content length */ + if(httpversion > 10) { + /* On HTTP/1.1, enable chunked, on HTTP/2 and later we do not + * need it */ + data->req.upload_chunky = (httpversion < 20); + } + else { + failf(data, "Chunky upload is not supported by HTTP 1.0"); + return CURLE_UPLOAD_FAILED; + } + } + else { + /* else, no chunky upload */ + data->req.upload_chunky = FALSE; + } + + if(data->req.upload_chunky) + result = curlx_dyn_add(req, "Transfer-Encoding: chunked\r\n"); + } + return result; +} + +static CURLcode addexpect(struct Curl_easy *data, struct dynbuf *r, + int httpversion, bool *announced_exp100) +{ + CURLcode result; + char *ptr; + + *announced_exp100 = FALSE; + /* Avoid Expect: 100-continue if Upgrade: is used */ + if(data->req.upgr101 != UPGR101_NONE) + return CURLE_OK; + + /* For really small puts we do not use Expect: headers at all, and for + the somewhat bigger ones we allow the app to disable it. Make + sure that the expect100header is always set to the preferred value + here. */ + ptr = Curl_checkheaders(data, STRCONST("Expect")); + if(ptr) { + *announced_exp100 = + Curl_compareheader(ptr, STRCONST("Expect:"), STRCONST("100-continue")); + } + else if(!data->state.disableexpect && (httpversion == 11)) { + /* if not doing HTTP 1.0 or version 2, or disabled explicitly, we add an + Expect: 100-continue to the headers which actually speeds up post + operations (as there is one packet coming back from the web server) */ + curl_off_t client_len = Curl_creader_client_length(data); + if(client_len > EXPECT_100_THRESHOLD || client_len < 0) { + result = curlx_dyn_addn(r, STRCONST("Expect: 100-continue\r\n")); + if(result) + return result; + *announced_exp100 = TRUE; + } + } + return CURLE_OK; +} + +static CURLcode http_add_content_hds(struct Curl_easy *data, + struct dynbuf *r, + int httpversion, + Curl_HttpReq httpreq) +{ + CURLcode result = CURLE_OK; + curl_off_t req_clen; + bool announced_exp100 = FALSE; + + DEBUGASSERT(data->conn); + if(data->req.upload_chunky) { + result = Curl_httpchunk_add_reader(data); + if(result) + return result; + } + + /* Get the request body length that has been set up */ + req_clen = Curl_creader_total_length(data); + switch(httpreq) { + case HTTPREQ_PUT: + case HTTPREQ_POST: +#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API) + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: +#endif + /* We only set Content-Length and allow a custom Content-Length if + we do not upload data chunked, as RFC2616 forbids us to set both + kinds of headers (Transfer-Encoding: chunked and Content-Length). + We do not override a custom "Content-Length" header, but during + authentication negotiation that header is suppressed. + */ + if(req_clen >= 0 && !data->req.upload_chunky && + (data->req.authneg || + !Curl_checkheaders(data, STRCONST("Content-Length")))) { + /* we allow replacing this header if not during auth negotiation, + although it is not wise to actually set your own */ + result = curlx_dyn_addf(r, "Content-Length: %" FMT_OFF_T "\r\n", + req_clen); + } + if(result) + goto out; + +#ifndef CURL_DISABLE_MIME + /* Output mime-generated headers. */ + if(data->state.mimepost && + ((httpreq == HTTPREQ_POST_FORM) || (httpreq == HTTPREQ_POST_MIME))) { + struct curl_slist *hdr; + + for(hdr = data->state.mimepost->curlheaders; hdr; hdr = hdr->next) { + result = curlx_dyn_addf(r, "%s\r\n", hdr->data); + if(result) + goto out; + } + } +#endif + if(httpreq == HTTPREQ_POST) { + if(!Curl_checkheaders(data, STRCONST("Content-Type"))) { + result = curlx_dyn_addn(r, STRCONST("Content-Type: application/" + "x-www-form-urlencoded\r\n")); + if(result) + goto out; + } + } + result = addexpect(data, r, httpversion, &announced_exp100); + if(result) + goto out; + break; + default: + break; + } + + Curl_pgrsSetUploadSize(data, req_clen); + if(announced_exp100) + result = http_exp100_add_reader(data); + +out: + return result; +} + +#ifndef CURL_DISABLE_COOKIES + +static CURLcode http_cookies(struct Curl_easy *data, + struct dynbuf *r) +{ + CURLcode result = CURLE_OK; + const char *addcookies = NULL; + bool linecap = FALSE; + if(CURL_EASY_STR(data, STRING_COOKIE) && + !Curl_checkheaders(data, STRCONST("Cookie")) && + Curl_auth_allowed_to_host(data)) + addcookies = CURL_EASY_STR(data, STRING_COOKIE); + + if(data->cookies || addcookies) { + struct Curl_llist list; + int count = 0; + + if(data->cookies && data->state.cookie_engine) { + bool okay; + const char *host = data->req.cookiehost ? + data->req.cookiehost : data->state.origin->hostname; + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + result = Curl_cookie_getlist(data, &okay, host, &list); + if(!result && okay) { + struct Curl_llist_node *n; + size_t clen = 8; /* hold the size of the generated Cookie: header */ + + /* loop through all cookies that matched */ + for(n = Curl_llist_head(&list); n; n = Curl_node_next(n)) { + struct Cookie *co = Curl_node_elem(n); + if(co->value) { + size_t add; + if(!count) { + result = curlx_dyn_addn(r, STRCONST("Cookie: ")); + if(result) + break; + } + add = strlen(co->name) + strlen(co->value) + 1; + if(clen + add >= MAX_COOKIE_HEADER_LEN) { + infof(data, "Restricted outgoing cookies due to header size, " + "'%s' not sent", co->name); + linecap = TRUE; + break; + } + result = curlx_dyn_addf(r, "%s%s=%s", count ? "; " : "", + co->name, co->value); + if(result) + break; + clen += add + (count ? 2 : 0); + count++; + } + } + Curl_llist_destroy(&list, NULL); + } + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); + } + if(addcookies && !result && !linecap) { + if(!count) + result = curlx_dyn_addn(r, STRCONST("Cookie: ")); + if(!result) { + result = curlx_dyn_addf(r, "%s%s", count ? "; " : "", addcookies); + count++; + } + } + if(count && !result) + result = curlx_dyn_addn(r, STRCONST("\r\n")); + + if(result) + return result; + } + return result; +} +#else +#define http_cookies(a, b) CURLE_OK +#endif + +static CURLcode http_range(struct Curl_easy *data, + Curl_HttpReq httpreq) +{ + if(data->state.use_range) { + /* + * A range is selected. We use different headers whether we are downloading + * or uploading and we always let customized headers override our internal + * ones if any such are specified. + */ + if(((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) && + !Curl_checkheaders(data, STRCONST("Range"))) { + /* if a line like this was already allocated, free the previous one */ + curlx_free(data->state.rangeline); + data->state.rangeline = curl_maprintf("Range: bytes=%s\r\n", + data->state.range); + if(!data->state.rangeline) + return CURLE_OUT_OF_MEMORY; + } + else if((httpreq == HTTPREQ_POST || httpreq == HTTPREQ_PUT) && + !Curl_checkheaders(data, STRCONST("Content-Range"))) { + curl_off_t req_clen = Curl_creader_total_length(data); + /* if a line like this was already allocated, free the previous one */ + curlx_free(data->state.rangeline); + + if(data->set.set_resume_from < 0) { + /* Upload resume was asked for, but we do not know the size of the + remote part so we tell the server (and act accordingly) that we + upload the whole file (again) */ + data->state.rangeline = + curl_maprintf("Content-Range: bytes 0-%" FMT_OFF_T "/" + "%" FMT_OFF_T "\r\n", req_clen - 1, req_clen); + } + else if(data->state.resume_from) { + /* This is because "resume" was selected */ + /* Not sure if we want to send this header during authentication + * negotiation, but test1084 checks for it. In which case we have a + * "null" client reader installed that gives an unexpected length. */ + curl_off_t total_len = data->req.authneg ? + data->state.infilesize : + (data->state.resume_from + req_clen); + data->state.rangeline = + curl_maprintf("Content-Range: bytes %s%" FMT_OFF_T "/" + "%" FMT_OFF_T "\r\n", + data->state.range, total_len - 1, total_len); + } + else { + /* Range was selected and then we pass the incoming range and append + total size */ + data->state.rangeline = + curl_maprintf("Content-Range: bytes %s/%" FMT_OFF_T "\r\n", + data->state.range, req_clen); + } + if(!data->state.rangeline) + return CURLE_OUT_OF_MEMORY; + } + } + return CURLE_OK; +} + +static CURLcode http_firstwrite(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + struct SingleRequest *k = &data->req; + + if(data->req.newurl) { + if(conn->bits.close) { + /* Abort after the headers if "follow Location" is set + and we are set to close anyway. */ + CURL_REQ_CLEAR_RECV(data); + k->done = TRUE; + return CURLE_OK; + } + /* We have a new URL to load, but since we want to be able to reuse this + connection properly, we read the full response in "ignore more" */ + k->ignorebody = TRUE; + infof(data, "Ignoring the response-body"); + } + if(data->state.resume_from && !k->content_range && + (data->state.httpreq == HTTPREQ_GET) && + !k->ignorebody) { + + if(k->size == data->state.resume_from) { + /* The resume point is at the end of file, consider this fine even if it + does not allow resume from here. */ + infof(data, "The entire document is already downloaded"); + streamclose(conn); + /* Abort download */ + CURL_REQ_CLEAR_RECV(data); + k->done = TRUE; + return CURLE_OK; + } + + /* we wanted to resume a download, although the server does not seem to + * support this and we did this with a GET (if it was not a GET we did a + * POST or PUT resume) */ + failf(data, "HTTP server does not seem to support " + "byte ranges. Cannot resume."); + return CURLE_RANGE_ERROR; + } + + if(data->set.timecondition && !data->state.range) { + /* A time condition has been set AND no ranges have been requested. This + seems to be what chapter 13.3.4 of RFC 2616 defines to be the correct + action for an HTTP/1.1 client */ + + if(!Curl_meets_timecondition(data, k->timeofdoc)) { + k->done = TRUE; + /* We are simulating an HTTP 304 from server so we return + what should have been returned from the server */ + data->info.httpcode = 304; + infof(data, "Simulate an HTTP 304 response"); + /* we abort the transfer before it is completed == we ruin the + reuse ability. Close the connection */ + streamclose(conn); + return CURLE_OK; + } + } /* we have a time condition */ + + return CURLE_OK; +} + +static CURLcode http_check_new_conn(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + const char *info_version = NULL; + const char *alpn; + CURLcode result; + + alpn = Curl_conn_get_alpn_negotiated(data, conn); + if(alpn && !strcmp("h3", alpn)) { +#ifndef CURL_DISABLE_PROXY + if(!conn->bits.origin_is_proxy) +#endif + DEBUGASSERT(Curl_conn_http_version(data, conn) == 30); + info_version = "HTTP/3"; + } + else if(alpn && !strcmp("h2", alpn)) { +#ifndef CURL_DISABLE_PROXY + if((Curl_conn_http_version(data, conn) != 20) && + conn->bits.origin_is_proxy) { + result = Curl_http2_switch(data); + if(result) + return result; + } + else +#endif + DEBUGASSERT(Curl_conn_http_version(data, conn) == 20); + info_version = "HTTP/2"; + } + else { + /* Check if user wants to use HTTP/2 with clear TCP */ + if(Curl_http2_may_switch(data)) { + DEBUGF(infof(data, "HTTP/2 over clean TCP")); + result = Curl_http2_switch(data); + if(result) + return result; + info_version = "HTTP/2"; + /* There is no ALPN here, but the connection is now definitely h2 */ + conn->httpversion_seen = 20; + Curl_conn_set_multiplex(conn); + } + else + info_version = "HTTP/1.x"; + } + + if(info_version) + infof(data, "using %s", info_version); + return CURLE_OK; +} + +static CURLcode http_add_connection_hd(struct Curl_easy *data, + struct dynbuf *req) +{ + struct curl_slist *head; + const char *sep = "Connection: "; + CURLcode result = CURLE_OK; + size_t rlen = curlx_dyn_len(req); + bool skip; + + /* Add the 1st custom "Connection: " header, if there is one */ + for(head = data->set.headers; head; head = head->next) { + if(curl_strnequal(head->data, "Connection", 10) && + Curl_headersep(head->data[10]) && + !http_header_is_empty(head->data)) { + char *value; + result = copy_custom_value(head->data, &value); + if(result) + return result; + result = curlx_dyn_addf(req, "%s%s", sep, value); + sep = ", "; + curlx_free(value); + break; /* leave, having added 1st one */ + } + } + + /* add our internal Connection: header values, if we have any */ + if(!result && data->state.http_hd_te) { + result = curlx_dyn_addf(req, "%s%s", sep, "TE"); + sep = ", "; + } + if(!result && data->state.http_hd_upgrade) { + result = curlx_dyn_addf(req, "%s%s", sep, "Upgrade"); + sep = ", "; + } + if(!result && data->state.http_hd_h2_settings) { + result = curlx_dyn_addf(req, "%s%s", sep, "HTTP2-Settings"); + } + if(!result && (rlen < curlx_dyn_len(req))) + result = curlx_dyn_addn(req, STRCONST("\r\n")); + if(result) + return result; + + /* Add all user-defined Connection: headers after the first */ + skip = TRUE; + for(head = data->set.headers; head; head = head->next) { + if(curl_strnequal(head->data, "Connection", 10) && + Curl_headersep(head->data[10]) && + !http_header_is_empty(head->data)) { + if(skip) { + skip = FALSE; + continue; + } + result = curlx_dyn_addf(req, "%s\r\n", head->data); + if(result) + return result; + } + } + + return CURLE_OK; +} + +/* Header identifier in order we send them by default */ +typedef enum { + H1_HD_REQUEST, + H1_HD_HOST, +#ifndef CURL_DISABLE_PROXY + H1_HD_PROXY_AUTH, +#endif + H1_HD_AUTH, + H1_HD_RANGE, + H1_HD_USER_AGENT, + H1_HD_ACCEPT, + H1_HD_TE, + H1_HD_ACCEPT_ENCODING, + H1_HD_REFERER, +#ifndef CURL_DISABLE_PROXY + H1_HD_PROXY_CONNECTION, +#endif + H1_HD_TRANSFER_ENCODING, +#ifndef CURL_DISABLE_ALTSVC + H1_HD_ALT_USED, +#endif + H1_HD_UPGRADE, + H1_HD_COOKIES, + H1_HD_CONDITIONALS, + H1_HD_CUSTOM, + H1_HD_CONTENT, + H1_HD_CONNECTION, + H1_HD_LAST /* the last, empty header line */ +} http_hd_t; + +static CURLcode http_add_hd(struct Curl_easy *data, + struct dynbuf *req, + http_hd_t id, + unsigned char httpversion, + const char *method, + Curl_HttpReq httpreq) +{ + CURLcode result = CURLE_OK; +#if !defined(CURL_DISABLE_ALTSVC) || \ + !defined(CURL_DISABLE_PROXY) || \ + !defined(CURL_DISABLE_WEBSOCKETS) + struct connectdata *conn = data->conn; +#endif + switch(id) { + case H1_HD_REQUEST: + /* add the main request stuff */ + /* GET/HEAD/POST/PUT */ + result = curlx_dyn_addf(req, "%s ", method); + if(!result) + result = http_target(data, req); + if(!result) + result = curlx_dyn_addf(req, " HTTP/%s\r\n", + get_http_string(httpversion)); + break; + + case H1_HD_HOST: + if(data->state.http_host) { + result = curlx_dyn_add(req, data->state.http_host); + if(!result) + result = curlx_dyn_addn(req, STRCONST("\r\n")); + } + break; + +#ifndef CURL_DISABLE_PROXY + case H1_HD_PROXY_AUTH: + if(data->req.hd_proxy_auth) + result = curlx_dyn_add(req, data->req.hd_proxy_auth); + break; +#endif + + case H1_HD_AUTH: + if(data->req.hd_auth) + result = curlx_dyn_add(req, data->req.hd_auth); + break; + + case H1_HD_RANGE: + if(data->state.use_range && data->state.rangeline) + result = curlx_dyn_add(req, data->state.rangeline); + break; + + case H1_HD_USER_AGENT: { + const char *ua = CURL_EASY_STR(data, STRING_USERAGENT); + if(ua && *ua && !Curl_checkheaders(data, STRCONST("User-Agent"))) + result = curlx_dyn_addf(req, "User-Agent: %s\r\n", ua); + break; + } + + case H1_HD_ACCEPT: + if(!Curl_checkheaders(data, STRCONST("Accept"))) + result = curlx_dyn_add(req, "Accept: */*\r\n"); + break; + + case H1_HD_TE: +#ifdef HAVE_LIBZ + if(!Curl_checkheaders(data, STRCONST("TE")) && + data->set.http_transfer_encoding) { + data->state.http_hd_te = TRUE; + result = curlx_dyn_add(req, "TE: gzip\r\n"); + } +#endif + break; + + case H1_HD_ACCEPT_ENCODING: { + const char *enc = CURL_EASY_STR(data, STRING_ENCODING); + if(enc && !Curl_checkheaders(data, STRCONST("Accept-Encoding"))) + result = curlx_dyn_addf(req, "Accept-Encoding: %s\r\n", enc); + break; + } + + case H1_HD_REFERER: + if(Curl_bufref_ptr(&data->state.referer) && + !Curl_checkheaders(data, STRCONST("Referer"))) + result = curlx_dyn_addf(req, "Referer: %s\r\n", + Curl_bufref_ptr(&data->state.referer)); + break; + +#ifndef CURL_DISABLE_PROXY + case H1_HD_PROXY_CONNECTION: + if(conn->bits.origin_is_proxy && + !Curl_checkheaders(data, STRCONST("Proxy-Connection")) && + !Curl_checkProxyheaders(data, data->conn, STRCONST("Proxy-Connection"))) + result = curlx_dyn_add(req, "Proxy-Connection: Keep-Alive\r\n"); + break; +#endif + + case H1_HD_TRANSFER_ENCODING: + result = http_req_set_TE(data, req, httpversion); + break; + +#ifndef CURL_DISABLE_ALTSVC + case H1_HD_ALT_USED: + if(conn->bits.altused && conn->via_peer && + !Curl_checkheaders(data, STRCONST("Alt-Used"))) + result = curlx_dyn_addf(req, "Alt-Used: %s:%u\r\n", + conn->via_peer->hostname, conn->via_peer->port); + break; +#endif + + case H1_HD_UPGRADE: + if(!Curl_conn_is_ssl(data->conn, FIRSTSOCKET) && (httpversion < 20) && + (data->state.http_neg.wanted & CURL_HTTP_V2x) && + data->state.http_neg.h2_upgrade) { + /* append HTTP2 upgrade magic stuff to the HTTP request if it is not done + over SSL */ + result = Curl_http2_request_upgrade(req, data); + } +#ifndef CURL_DISABLE_WEBSOCKETS + if(!result && conn->scheme->protocol & (CURLPROTO_WS | CURLPROTO_WSS)) + result = Curl_ws_request(data, req); +#endif + break; + + case H1_HD_COOKIES: + result = http_cookies(data, req); + break; + + case H1_HD_CONDITIONALS: + result = Curl_add_timecondition(data, req); + break; + + case H1_HD_CUSTOM: + result = Curl_add_custom_headers(data, FALSE, httpversion, req); + break; + + case H1_HD_CONTENT: + result = http_add_content_hds(data, req, httpversion, httpreq); + break; + + case H1_HD_CONNECTION: { + result = http_add_connection_hd(data, req); + break; + } + + case H1_HD_LAST: + result = curlx_dyn_addn(req, STRCONST("\r\n")); + break; + } + return result; +} + +/* + * Curl_http() gets called from the generic multi_do() function when an HTTP + * request is to be performed. This creates and sends a properly constructed + * HTTP request. + */ +CURLcode Curl_http(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + Curl_HttpReq httpreq; + const char *method; + struct dynbuf req; + unsigned char httpversion; + size_t hd_id; + + /* Always consider the DO phase done after this function call, even if there + may be parts of the request that are not yet sent, since we can deal with + the rest of the request in the PERFORM phase. */ + *done = TRUE; + /* initialize a dynamic send-buffer */ + curlx_dyn_init(&req, DYN_HTTP_REQUEST); + /* make sure the header buffer is reset - if there are leftovers from a + previous transfer */ + curlx_dyn_reset(&data->state.headerb); + data->state.maybe_folded = FALSE; + + if(!data->conn->bits.reuse) { + result = http_check_new_conn(data); + if(result) + goto out; + } + + /* Add collecting of headers written to client. For a new connection, + * we might have done that already, but reuse + * or multiplex needs it here as well. */ + result = Curl_headers_init(data); + if(result) + goto out; + + data->state.http_hd_te = FALSE; + data->state.http_hd_upgrade = FALSE; + data->state.http_hd_h2_settings = FALSE; + + /* what kind of request do we need to send? */ + Curl_http_method(data, &method, &httpreq); + + /* select host to send */ + result = http_set_aptr_host(data); + /* setup the authentication headers, how that method and host are known */ + if(!result) + result = Curl_http_output_auth(data, data->conn, method, httpreq, + data->state.up.path, + data->state.up.query, FALSE); + /* Setup input reader, resume information and ranges */ + if(!result) + result = set_reader(data, httpreq); + if(!result) + result = http_resume(data, httpreq); + if(!result) + result = http_range(data, httpreq); + if(result) + goto out; + + httpversion = http_request_version(data); + /* Add request line and all headers to `req` */ + for(hd_id = 0; hd_id <= H1_HD_LAST; ++hd_id) { + result = http_add_hd(data, &req, (http_hd_t)hd_id, + httpversion, method, httpreq); + if(result) + goto out; + } + + /* setup variables for the upcoming transfer and send */ + Curl_xfer_setup_sendrecv(data, FIRSTSOCKET, -1); + result = Curl_req_send(data, &req, httpversion); + + if((httpversion >= 20) && data->req.upload_chunky) + /* upload_chunky was set above to set up the request in a chunky fashion, + but is disabled here again to avoid that the chunked encoded version is + actually used when sending the request body over h2 */ + data->req.upload_chunky = FALSE; + +out: + if(result == CURLE_TOO_LARGE) + failf(data, "HTTP request too large"); + + curlx_dyn_free(&req); + return result; +} + +typedef enum { + STATUS_UNKNOWN, /* not enough data to tell yet */ + STATUS_DONE, /* a status line was read */ + STATUS_BAD /* not a status line */ +} statusline; + +/* Check a string for a prefix. Check no more than 'len' bytes */ +static bool checkprefixmax(const char *prefix, const char *buffer, size_t len) +{ + size_t ch = CURLMIN(strlen(prefix), len); + return curl_strnequal(prefix, buffer, ch); +} + +/* + * checkhttpprefix() + * + * Returns TRUE if member of the list matches prefix of string + */ +static statusline checkhttpprefix(struct Curl_easy *data, + const char *s, size_t len) +{ + struct curl_slist *head = data->set.http200aliases; + statusline rc = STATUS_BAD; + statusline onmatch = len >= 5 ? STATUS_DONE : STATUS_UNKNOWN; + + while(head) { + if(checkprefixmax(head->data, s, len)) { + rc = onmatch; + break; + } + head = head->next; + } + + if((rc != STATUS_DONE) && checkprefixmax("HTTP/", s, len)) + rc = onmatch; + + return rc; +} + +#ifndef CURL_DISABLE_RTSP +static statusline checkrtspprefix(struct Curl_easy *data, + const char *s, size_t len) +{ + statusline status = STATUS_BAD; + statusline onmatch = len >= 5 ? STATUS_DONE : STATUS_UNKNOWN; + (void)data; + if(checkprefixmax("RTSP/", s, len)) + status = onmatch; + + return status; +} +#endif /* CURL_DISABLE_RTSP */ + +static statusline checkprotoprefix(struct Curl_easy *data, + struct connectdata *conn, + const char *s, size_t len) +{ +#ifndef CURL_DISABLE_RTSP + if(conn->scheme->protocol & CURLPROTO_RTSP) + return checkrtspprefix(data, s, len); +#else + (void)conn; +#endif /* CURL_DISABLE_RTSP */ + + return checkhttpprefix(data, s, len); +} + +/* HTTP header has field name `n` (a string constant) */ +#define HD_IS(hd, hdlen, n) \ + (((hdlen) >= (sizeof(n) - 1)) && curl_strnequal(n, hd, sizeof(n) - 1)) + +#define HD_VAL(hd, hdlen, n) \ + ((((hdlen) >= (sizeof(n) - 1)) && (hd) && \ + curl_strnequal(n, hd, sizeof(n) - 1)) ? ((hd) + (sizeof(n) - 1)) : NULL) + +/* HTTP header has field name `n` (a string constant) and contains `v` + * (a string constant) in its value(s) */ +#define HD_IS_AND_SAYS(hd, hdlen, n, v) \ + (HD_IS(hd, hdlen, n) && \ + ((hdlen) > ((sizeof(n) - 1) + (sizeof(v) - 1))) && \ + Curl_compareheader(hd, STRCONST(n), STRCONST(v))) + +/* + * http_header_a() parses a single response header starting with A. + */ +static CURLcode http_header_a(struct Curl_easy *data, + const char *hd, size_t hdlen) +{ +#ifndef CURL_DISABLE_ALTSVC + const char *v; + v = (data->asi && + (Curl_xfer_is_secure(data) || +#ifdef DEBUGBUILD + /* allow debug builds to circumvent the HTTPS restriction */ + getenv("CURL_ALTSVC_HTTP") +#else + 0 +#endif + )) ? HD_VAL(hd, hdlen, "Alt-Svc:") : NULL; + if(v) { + /* the ALPN of the current request */ + struct SingleRequest *k = &data->req; + enum alpnid id = (k->httpversion == 30) ? ALPN_h3 : + (k->httpversion == 20) ? ALPN_h2 : ALPN_h1; + return Curl_altsvc_parse(data, data->asi, v, data->state.origin, id); + } +#else + (void)data; + (void)hd; + (void)hdlen; +#endif + return CURLE_OK; +} + +/* + * http_header_c() parses a single response header starting with C. + */ +static CURLcode http_header_c(struct Curl_easy *data, + const char *hd, size_t hdlen) +{ + struct connectdata *conn = data->conn; + struct SingleRequest *k = &data->req; + const char *v; + + /* Check for Content-Length: header lines to get size. Browsers insist we + should accept multiple Content-Length headers and that a comma separated + list also is fine and then we should accept them all as long as they are + the same value. Different values trigger error. + */ + v = (!k->http_bodyless && !data->set.ignorecl) ? + HD_VAL(hd, hdlen, "Content-Length:") : NULL; + if(v) { + do { + curl_off_t contentlength; + int offt = curlx_str_numblanks(&v, &contentlength); + + if(offt == STRE_OVERFLOW) { + /* out of range */ + if(data->set.max_filesize) { + failf(data, "Maximum file size exceeded"); + return CURLE_FILESIZE_EXCEEDED; + } + streamclose(conn); + infof(data, "Overflow Content-Length: value"); + return CURLE_OK; + } + else { + if((offt == STRE_OK) && + ((k->size == -1) || /* not set to something before */ + (k->size == contentlength))) { /* or the same value */ + + k->size = contentlength; + curlx_str_passblanks(&v); + + /* on a comma, loop and get the next instead */ + if(!curlx_str_single(&v, ',')) + continue; + + if(!curlx_str_newline(&v)) { + k->maxdownload = k->size; + return CURLE_OK; + } + } + /* negative, different value or rubbish - bad HTTP */ + failf(data, "Invalid Content-Length: value"); + return CURLE_WEIRD_SERVER_REPLY; + } + } while(1); + } + v = (!k->http_bodyless && CURL_EASY_STR(data, STRING_ENCODING)) ? + HD_VAL(hd, hdlen, "Content-Encoding:") : NULL; + if(v) { + /* + * Process Content-Encoding. Look for the values: identity, gzip, deflate, + * compress, x-gzip and x-compress. x-gzip and x-compress are the same as + * gzip and compress. (Sec 3.5 RFC 2616). zlib cannot handle compress. + * Errors are handled further down when the response body is processed + */ + return Curl_build_unencoding_stack(data, v, FALSE); + } + /* check for Content-Type: header lines to get the MIME-type */ + v = HD_VAL(hd, hdlen, "Content-Type:"); + if(v) { + char *contenttype = Curl_copy_header_value(hd); + if(!contenttype) + return CURLE_OUT_OF_MEMORY; + if(!*contenttype) + /* ignore empty data */ + curlx_free(contenttype); + else { + curlx_free(data->info.contenttype); + data->info.contenttype = contenttype; + } + return CURLE_OK; + } + if((k->httpversion < 20) && + HD_IS_AND_SAYS(hd, hdlen, "Connection:", "close")) { + /* + * [RFC 2616, section 8.1.2.1] + * "Connection: close" is HTTP/1.1 language and means that + * the connection will close when this request has been + * served. + */ + connclose(conn); + return CURLE_OK; + } + if((k->httpversion == 10) && + HD_IS_AND_SAYS(hd, hdlen, "Connection:", "keep-alive")) { + /* + * An HTTP/1.0 reply with the 'Connection: keep-alive' line + * tells us the connection will be kept alive for our + * pleasure. Default action for 1.0 is to close. + * + * [RFC2068, section 19.7.1] */ + connkeep(conn); + infof(data, "HTTP/1.0 connection set to keep alive"); + return CURLE_OK; + } + v = !k->http_bodyless ? HD_VAL(hd, hdlen, "Content-Range:") : NULL; + if(v) { + /* Content-Range: bytes [num]- + Content-Range: bytes: [num]- + Content-Range: [num]- + Content-Range: [asterisk]/[total] + + The second format was added since Sun's webserver + JavaWebServer/1.1.1 obviously sends the header this way! + The third added since some servers use that! + The fourth means the requested range was unsatisfied. + */ + + const char *ptr = v; + + /* Move forward until first digit or asterisk */ + while(*ptr && !ISDIGIT(*ptr) && *ptr != '*') + ptr++; + + /* if it truly stopped on a digit */ + if(ISDIGIT(*ptr)) { + if(!curlx_str_number(&ptr, &k->offset, CURL_OFF_T_MAX) && + (data->state.resume_from == k->offset)) + /* we asked for a resume and we got it */ + k->content_range = TRUE; + } + else if(k->httpcode < 300) + data->state.resume_from = 0; /* get everything */ + } + return CURLE_OK; +} + +/* + * http_header_l() parses a single response header starting with L. + */ +static CURLcode http_header_l(struct Curl_easy *data, + const char *hd, size_t hdlen) +{ + struct connectdata *conn = data->conn; + struct SingleRequest *k = &data->req; + const char *v = (!k->http_bodyless && + (data->set.timecondition || data->set.get_filetime)) ? + HD_VAL(hd, hdlen, "Last-Modified:") : NULL; + if(v) { + if(Curl_getdate_capped(v, &k->timeofdoc)) + k->timeofdoc = 0; + if(data->set.get_filetime) + data->info.filetime = k->timeofdoc; + return CURLE_OK; + } + if(HD_IS(hd, hdlen, "Location:")) { + /* this is the URL that the server advises us to use instead */ + char *location = Curl_copy_header_value(hd); + if(!location) + return CURLE_OUT_OF_MEMORY; + if(!*location || + (data->req.location && !strcmp(data->req.location, location))) { + /* ignore empty header, or exact repeat of a previous one */ + curlx_free(location); + return CURLE_OK; + } + else { + /* has value and is not an exact repeat */ + if(data->req.location) { + failf(data, "Multiple Location headers"); + curlx_free(location); + return CURLE_WEIRD_SERVER_REPLY; + } + data->req.location = location; + + if((k->httpcode >= 300 && k->httpcode < 400) && + data->set.http_follow_mode) { + CURLcode result; + DEBUGASSERT(!data->req.newurl); + data->req.newurl = curlx_strdup(data->req.location); /* clone */ + if(!data->req.newurl) + return CURLE_OUT_OF_MEMORY; + + /* some cases of POST and PUT etc needs to rewind the data + stream at this point */ + result = http_perhapsrewind(data, conn); + if(result) + return result; + + /* mark the next request as a followed location: */ + data->state.this_is_a_follow = TRUE; + } + } + } + return CURLE_OK; +} + +/* + * http_header_p() parses a single response header starting with P. + */ +static CURLcode http_header_p(struct Curl_easy *data, + const char *hd, size_t hdlen) +{ + struct SingleRequest *k = &data->req; + +#ifndef CURL_DISABLE_PROXY + const char *v = HD_VAL(hd, hdlen, "Proxy-Connection:"); + if(v) { + struct connectdata *conn = data->conn; + if((k->httpversion == 10) && conn->http_proxy.peer && + HD_IS_AND_SAYS(hd, hdlen, "Proxy-Connection:", "keep-alive")) { + /* + * When an HTTP/1.0 reply comes when using a proxy, the + * 'Proxy-Connection: keep-alive' line tells us the + * connection will be kept alive for our pleasure. + * Default action for 1.0 is to close. + */ + connkeep(conn); /* do not close */ + infof(data, "HTTP/1.0 proxy connection set to keep alive"); + } + else if((k->httpversion == 11) && conn->http_proxy.peer && + HD_IS_AND_SAYS(hd, hdlen, "Proxy-Connection:", "close")) { + /* + * We get an HTTP/1.1 response from a proxy and it says it will + * close down after this transfer. + */ + connclose(conn); + infof(data, "HTTP/1.1 proxy connection set close"); + } + return CURLE_OK; + } +#endif + if((407 == k->httpcode) && HD_IS(hd, hdlen, "Proxy-authenticate:")) { + char *auth = Curl_copy_header_value(hd); + CURLcode result = auth ? CURLE_OK : CURLE_OUT_OF_MEMORY; + if(!result) { + result = Curl_http_input_auth(data, TRUE, auth); + curlx_free(auth); + } + return result; + } +#ifdef USE_SPNEGO + if(HD_IS(hd, hdlen, "Persistent-Auth:")) { + struct connectdata *conn = data->conn; + struct negotiatedata *negdata = Curl_auth_nego_get(conn, FALSE); + struct auth *authp = &data->state.authhost; + if(!negdata) + return CURLE_OUT_OF_MEMORY; + if(authp->picked == CURLAUTH_NEGOTIATE) { + char *persistentauth = Curl_copy_header_value(hd); + if(!persistentauth) + return CURLE_OUT_OF_MEMORY; + negdata->noauthpersist = !!checkprefix("false", persistentauth); + negdata->havenoauthpersist = TRUE; + infof(data, "Negotiate: noauthpersist -> %d, header part: %s", + negdata->noauthpersist, persistentauth); + curlx_free(persistentauth); + } + } +#endif + return CURLE_OK; +} + +/* + * http_header_r() parses a single response header starting with R. + */ +static CURLcode http_header_r(struct Curl_easy *data, + const char *hd, size_t hdlen) +{ + const char *v = HD_VAL(hd, hdlen, "Retry-After:"); + if(v) { + /* Retry-After = HTTP-date / delay-seconds */ + curl_off_t retry_after = 0; /* zero for unknown or "now" */ + time_t date = 0; + curlx_str_passblanks(&v); + + /* try it as a date first, because a date can otherwise start with and + get treated as a number */ + if(!Curl_getdate_capped(v, &date)) { + time_t current = time(NULL); + if(date >= current) + /* convert date to number of seconds into the future */ + retry_after = date - current; + } + else + /* Try it as a decimal number, ignore errors */ + (void)curlx_str_number(&v, &retry_after, CURL_OFF_T_MAX); + /* limit to 6 hours max. this is not documented so that it can be changed + in the future if necessary. */ + if(retry_after > 21600) + retry_after = 21600; + data->info.retry_after = retry_after; + } + return CURLE_OK; +} + +/* + * http_header_s() parses a single response header starting with S. + */ +static CURLcode http_header_s(struct Curl_easy *data, + const char *hd, size_t hdlen) +{ +#if !defined(CURL_DISABLE_COOKIES) || !defined(CURL_DISABLE_HSTS) + const char *v; +#else + (void)data; + (void)hd; + (void)hdlen; +#endif + +#ifndef CURL_DISABLE_COOKIES + v = (data->cookies && data->state.cookie_engine) ? + HD_VAL(hd, hdlen, "Set-Cookie:") : NULL; + if(v) { + /* If there is a custom-set Host: name, use it here, or else use + * real peer hostname. */ + const char *host = data->req.cookiehost ? + data->req.cookiehost : data->state.origin->hostname; + const unsigned char secure_context = Curl_secure_context(data, host) ? + COOKIE_SECURE : 0; + CURLcode result; + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + result = Curl_cookie_add(data, data->cookies, v, host, + data->state.up.path, + COOKIE_HTTPHEADER | secure_context); + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); + return result; + } +#endif +#ifndef CURL_DISABLE_HSTS + /* If enabled, the header is incoming and this is over HTTPS */ + v = (data->hsts && + (Curl_xfer_is_secure(data) || +#ifdef DEBUGBUILD + /* allow debug builds to circumvent the HTTPS restriction */ + getenv("CURL_HSTS_HTTP") +#else + 0 +#endif + ) + ) ? HD_VAL(hd, hdlen, "Strict-Transport-Security:") : NULL; + if(v) { + CURLcode result = Curl_hsts_parse( + data->hsts, data->state.origin->hostname, v); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + return result; + infof(data, "Illegal STS header skipped"); + } +#ifdef DEBUGBUILD + else + infof(data, "Parsed STS header fine (%zu entries)", + Curl_llist_count(&data->hsts->list)); +#endif + } +#endif + + return CURLE_OK; +} + +/* + * http_header_t() parses a single response header starting with T. + */ +static CURLcode http_header_t(struct Curl_easy *data, + const char *hd, size_t hdlen) +{ + struct connectdata *conn = data->conn; + struct SingleRequest *k = &data->req; + + /* RFC 9112, ch. 6.1 + * "Transfer-Encoding MAY be sent in a response to a HEAD request or + * in a 304 (Not Modified) response (Section 15.4.5 of [HTTP]) to a + * GET request, neither of which includes a message body, to indicate + * that the origin server would have applied a transfer coding to the + * message body if the request had been an unconditional GET." + * + * Read: in these cases the 'Transfer-Encoding' does not apply + * to any data following the response headers. Do not add any decoders. + */ + const char *v = (!k->http_bodyless && + (data->state.httpreq != HTTPREQ_HEAD) && + (k->httpcode != 304)) ? + HD_VAL(hd, hdlen, "Transfer-Encoding:") : NULL; + if(v) { + /* One or more encodings. We check for chunked and/or a compression + algorithm. */ + CURLcode result = Curl_build_unencoding_stack(data, v, TRUE); + if(result) + return result; + if(!k->chunk && data->set.http_transfer_encoding) { + /* if this is not chunked, only close can signal the end of this + * transfer as Content-Length is said not to be trusted for + * transfer-encoding! */ + CURL_TRC_M(data, "HTTP/1.1 transfer-encoding without chunks"); + connclose(conn); + k->ignore_cl = TRUE; + } + return CURLE_OK; + } + v = HD_VAL(hd, hdlen, "Trailer:"); + if(v) { + data->req.resp_trailer = TRUE; + return CURLE_OK; + } + return CURLE_OK; +} + +/* + * http_header_w() parses a single response header starting with W. + */ +static CURLcode http_header_w(struct Curl_easy *data, + const char *hd, size_t hdlen) +{ + struct SingleRequest *k = &data->req; + CURLcode result = CURLE_OK; + + if((401 == k->httpcode) && HD_IS(hd, hdlen, "WWW-Authenticate:")) { + char *auth = Curl_copy_header_value(hd); + if(!auth) + result = CURLE_OUT_OF_MEMORY; + else { + result = Curl_http_input_auth(data, FALSE, auth); + curlx_free(auth); + } + } + return result; +} + +/* + * http_header() parses a single response header. + */ +static CURLcode http_header(struct Curl_easy *data, + const char *hd, size_t hdlen) +{ + CURLcode result = CURLE_OK; + + switch(hd[0]) { + case 'a': + case 'A': + result = http_header_a(data, hd, hdlen); + break; + case 'c': + case 'C': + result = http_header_c(data, hd, hdlen); + break; + case 'l': + case 'L': + result = http_header_l(data, hd, hdlen); + break; + case 'p': + case 'P': + result = http_header_p(data, hd, hdlen); + break; + case 'r': + case 'R': + result = http_header_r(data, hd, hdlen); + break; + case 's': + case 'S': + result = http_header_s(data, hd, hdlen); + break; + case 't': + case 'T': + result = http_header_t(data, hd, hdlen); + break; + case 'w': + case 'W': + result = http_header_w(data, hd, hdlen); + break; + } + + if(!result) { + struct connectdata *conn = data->conn; + if(conn->scheme->protocol & CURLPROTO_RTSP) + result = Curl_rtsp_parseheader(data, hd); + } + return result; +} + +/* + * Called after the first HTTP response line (the status line) has been + * received and parsed. + */ +static CURLcode http_statusline(struct Curl_easy *data, + struct connectdata *conn) +{ + struct SingleRequest *k = &data->req; + + switch(k->httpversion) { + case 10: + case 11: +#ifdef USE_HTTP2 + case 20: +#endif +#ifdef USE_HTTP3 + case 30: +#endif + /* no major version switch mid-connection */ + if(k->httpversion_sent && + (k->httpversion / 10 != k->httpversion_sent / 10)) { + failf(data, "Version mismatch (from HTTP/%d to HTTP/%d)", + k->httpversion_sent / 10, k->httpversion / 10); + return CURLE_WEIRD_SERVER_REPLY; + } + break; + default: + failf(data, "Unsupported HTTP version (%d.%d) in response", + k->httpversion / 10, k->httpversion % 10); + return CURLE_UNSUPPORTED_PROTOCOL; + } + + data->info.httpcode = k->httpcode; + data->info.httpversion = k->httpversion; + conn->httpversion_seen = k->httpversion; + + if(!data->state.http_neg.rcvd_min || + data->state.http_neg.rcvd_min > k->httpversion) + /* store the lowest server version we encounter */ + data->state.http_neg.rcvd_min = k->httpversion; + + /* + * This code executes as part of processing the header. As a + * result, it is not totally clear how to interpret the + * response code yet as that depends on what other headers may + * be present. 401 and 407 may be errors, but may be OK + * depending on how authentication is working. Other codes + * are definitely errors, so give up here. + */ + if(data->state.resume_from && data->state.httpreq == HTTPREQ_GET && + k->httpcode == 416) { + /* "Requested Range Not Satisfiable", proceed and pretend this is no + error */ + k->ignorebody = TRUE; /* Avoid appending error msg to good data. */ + } + + if(k->httpversion == 10) { + /* Default action for HTTP/1.0 must be to close, unless + we get one of those fancy headers that tell us the + server keeps it open for us! */ + infof(data, "HTTP 1.0, assume close after body"); + connclose(conn); + } + + k->http_bodyless = k->httpcode >= 100 && k->httpcode < 200; + switch(k->httpcode) { + case 304: + /* (quote from RFC2616, section 10.3.5): The 304 response + * MUST NOT contain a message-body, and thus is always + * terminated by the first empty line after the header + * fields. */ + if(data->set.timecondition) + data->info.timecond = TRUE; + FALLTHROUGH(); + case 204: + /* (quote from RFC2616, section 10.2.5): The server has + * fulfilled the request but does not need to return an + * entity-body ... The 204 response MUST NOT include a + * message-body, and thus is always terminated by the first + * empty line after the header fields. */ + k->size = 0; + k->maxdownload = 0; + k->http_bodyless = TRUE; + break; + default: + break; + } + return CURLE_OK; +} + +/* Content-Length must be ignored if any Transfer-Encoding is present in the + response. Refer to RFC 7230 section 3.3.3 and RFC2616 section 4.4. This is + figured out here after all headers have been received but before the final + call to the user's header callback, so that a valid content length can be + retrieved by the user in the final call. */ +static CURLcode http_size(struct Curl_easy *data) +{ + struct SingleRequest *k = &data->req; + if(data->req.ignore_cl || k->chunk) { + k->size = k->maxdownload = -1; + } + else if(k->size != -1) { + if(data->set.max_filesize && + !k->ignorebody && + (k->size > data->set.max_filesize)) { + failf(data, "Maximum file size exceeded"); + return CURLE_FILESIZE_EXCEEDED; + } + if(k->ignorebody) + infof(data, "setting size while ignoring"); + Curl_pgrsSetDownloadSize(data, k->size); + k->maxdownload = k->size; + } + return CURLE_OK; +} + +CURLcode Curl_verify_header(struct Curl_easy *data, + const char *hd, size_t hdlen) +{ + struct SingleRequest *k = &data->req; + const char *ptr = memchr(hd, 0x00, hdlen); + if(ptr) { + /* this is bad, bail out */ + failf(data, "Nul byte in header"); + return CURLE_WEIRD_SERVER_REPLY; + } + if(hdlen > 2) { + ptr = memchr(hd, '\r', hdlen - 2); + if(ptr) { + /* CR may only precede the LF, nothing else */ + failf(data, "Carriage return found in header"); + return CURLE_WEIRD_SERVER_REPLY; + } + } + if(k->headerline < 2) + /* the first "header" is the status-line and it has no colon */ + return CURLE_OK; + if(((hd[0] == ' ') || (hd[0] == '\t')) && k->headerline > 2) + /* line folding, cannot happen on line 2 */ + ; + else { + ptr = memchr(hd, ':', hdlen); + if(!ptr) { + /* this is bad, bail out */ + failf(data, "Header without colon"); + return CURLE_WEIRD_SERVER_REPLY; + } + } + return CURLE_OK; +} + +CURLcode Curl_bump_headersize(struct Curl_easy *data, + size_t delta, + bool connect_only) +{ + size_t bad = 0; + unsigned int max = MAX_HTTP_RESP_HEADER_SIZE; + if(delta < MAX_HTTP_RESP_HEADER_SIZE) { + data->info.header_size += (unsigned int)delta; + data->req.allheadercount += (unsigned int)delta; + if(!connect_only) + data->req.headerbytecount += (unsigned int)delta; + if(data->req.allheadercount > max) + bad = data->req.allheadercount; + else if(data->info.header_size > (max * 20)) { + bad = data->info.header_size; + max *= 20; + } + } + else + bad = data->req.allheadercount + delta; + if(bad) { + failf(data, "Too large response headers: %zu > %u", bad, max); + return CURLE_RECV_ERROR; + } + return CURLE_OK; +} + +/* + * Handle a 101 Switching Protocols response. Performs the actual protocol + * upgrade to HTTP/2 or WebSocket based on what was requested. + */ +static CURLcode http_on_101_upgrade(struct Curl_easy *data, + const char *buf, size_t blen, + size_t *pconsumed, + bool *conn_changed) +{ + struct connectdata *conn = data->conn; + struct SingleRequest *k = &data->req; + +#if !defined(USE_NGHTTP2) && defined(CURL_DISABLE_WEBSOCKETS) + (void)buf; + (void)blen; + (void)pconsumed; +#else + CURLcode result; + int upgr101_requested = k->upgr101; +#endif + + if(k->httpversion_sent != 11) { + /* invalid for other HTTP versions */ + failf(data, "server sent 101 response while not talking HTTP/1.1"); + return CURLE_WEIRD_SERVER_REPLY; + } + + /* Whatever the success, upgrade was selected. */ + k->upgr101 = UPGR101_RECEIVED; + conn->bits.upgrade_in_progress = FALSE; + *conn_changed = TRUE; + + /* To be fully compliant, we would check the "Upgrade:" response header to + * mention the protocol we requested. */ +#ifdef USE_NGHTTP2 + if(upgr101_requested == UPGR101_H2) { + /* Switch to HTTP/2, where we will get more responses. blen bytes in buf + * are already h2 protocol bytes */ + infof(data, "Received 101, Switching to HTTP/2"); + result = Curl_http2_upgrade(data, conn, FIRSTSOCKET, buf, blen); + if(!result) + *pconsumed += blen; + return result; + } +#endif +#ifndef CURL_DISABLE_WEBSOCKETS + if(upgr101_requested == UPGR101_WS) { + /* Switch to WebSocket, where we now stream ws frames. blen bytes in buf + * are already ws protocol bytes */ + infof(data, "Received 101, Switching to WebSocket"); + result = Curl_ws_accept(data, buf, blen); + if(!result) + *pconsumed += blen; /* ws accept handled the data */ + return result; + } +#endif + /* We silently accept this as the final response. What are we switching to + * if we did not ask for an Upgrade? Maybe the application provided an + * `Upgrade: xxx` header? */ + k->header = FALSE; + return CURLE_OK; +} + +/* + * Handle 1xx intermediate HTTP responses. Sets up state for more + * headers and processes 100-continue and 101 upgrade responses. + */ +static CURLcode http_on_1xx_response(struct Curl_easy *data, + const char *buf, size_t blen, + size_t *pconsumed, + bool *conn_changed) +{ + struct SingleRequest *k = &data->req; + + /* "A user agent MAY ignore unexpected 1xx status responses." + * By default, we expect to get more responses after this one. */ + k->header = TRUE; + k->headerline = 0; /* restart the header line counter */ + + switch(k->httpcode) { + case 100: + /* We have made an HTTP PUT or POST and this is 1.1-lingo that tells us + * that the server is OK with this and ready to receive the data. */ + http_exp100_got100(data); + break; + case 101: + return http_on_101_upgrade(data, buf, blen, pconsumed, conn_changed); + default: + /* The server may send us other 1xx responses, like informative 103. This + * has no influence on request processing and we expect to receive a + * final response eventually. */ + break; + } + return CURLE_OK; +} + +#if defined(USE_NTLM) || defined(USE_SPNEGO) +/* + * Check if NTLM or SPNEGO authentication negotiation failed due to + * connection closure (typically on HTTP/1.0 servers). + */ +static void http_check_auth_closure(struct Curl_easy *data, + struct connectdata *conn) +{ + /* At this point we have some idea about the fate of the connection. If we + are closing the connection it may result auth failure. */ +#ifdef USE_NTLM + if(conn->bits.close && + (((data->req.httpcode == 401) && + (conn->http_ntlm_state == NTLMSTATE_TYPE2)) || + ((data->req.httpcode == 407) && + (conn->proxy_ntlm_state == NTLMSTATE_TYPE2)))) { + infof(data, "Connection closure while negotiating auth (HTTP 1.0?)"); + data->state.authproblem = TRUE; + } +#endif +#ifdef USE_SPNEGO + if(conn->bits.close && + (((data->req.httpcode == 401) && + (conn->http_negotiate_state == GSS_AUTHRECV)) || + ((data->req.httpcode == 407) && + (conn->proxy_negotiate_state == GSS_AUTHRECV)))) { + infof(data, "Connection closure while negotiating auth (HTTP 1.0?)"); + data->state.authproblem = TRUE; + } + if((conn->http_negotiate_state == GSS_AUTHDONE) && + (data->req.httpcode != 401)) { + conn->http_negotiate_state = GSS_AUTHSUCC; + } + if((conn->proxy_negotiate_state == GSS_AUTHDONE) && + (data->req.httpcode != 407)) { + conn->proxy_negotiate_state = GSS_AUTHSUCC; + } +#endif +} +#else +#define http_check_auth_closure(x, y) /* empty */ +#endif + +/* + * Handle an error response (>= 300) received while still sending the + * request body. Deals with 417 Expectation Failed retries, keep-sending + * on error, and aborting the send. + */ +static CURLcode http_handle_send_error(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + struct SingleRequest *k = &data->req; + CURLcode result = CURLE_OK; + + if(!data->req.authneg && !conn->bits.close && + !Curl_creader_will_rewind(data)) { + /* + * General treatment of errors when about to send data. + * Including: "417 Expectation Failed", while waiting for + * 100-continue. + * + * The check for close above is done because if something + * else has already deemed the connection to get closed then + * something else should have considered the big picture and + * we avoid this check. + */ + + switch(data->state.httpreq) { + case HTTPREQ_PUT: + case HTTPREQ_POST: + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + /* We got an error response. If this happened before the + * whole request body has been sent we stop sending and + * mark the connection for closure after we have read the + * entire response. */ + if(!Curl_req_done_sending(data)) { + if((k->httpcode == 417) && http_exp100_is_selected(data)) { + /* 417 Expectation Failed - try again without the + Expect header */ + if(!k->writebytecount && http_exp100_is_waiting(data)) { + infof(data, "Got HTTP failure 417 while waiting for a 100"); + } + else { + infof(data, "Got HTTP failure 417 while sending data"); + streamclose(conn); + result = http_perhapsrewind(data, conn); + if(result) + return result; + } + data->state.disableexpect = TRUE; + Curl_req_abort_sending(data); + DEBUGASSERT(!data->req.newurl); + data->req.newurl = Curl_bufref_dup(&data->state.url); + if(!data->req.newurl) + return CURLE_OUT_OF_MEMORY; + } + else if(data->set.http_keep_sending_on_error) { + infof(data, "HTTP error before end of send, keep sending"); + http_exp100_send_anyway(data); + } + else { + infof(data, "HTTP error before end of send, stop sending"); + streamclose(conn); + result = Curl_req_abort_sending(data); + if(result) + return result; + } + } + break; + + default: /* default label present to avoid compiler warnings */ + break; + } + } + + if(Curl_creader_will_rewind(data) && !Curl_req_done_sending(data)) { + /* We rewind before next send, continue sending now */ + infof(data, "Keep sending data to get tossed away"); + CURL_REQ_SET_SEND(data); + } + return result; +} + +static CURLcode http_on_response(struct Curl_easy *data, + const char *last_hd, size_t last_hd_len, + const char *buf, size_t blen, + size_t *pconsumed) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + bool conn_changed = FALSE; + + (void)buf; /* not used without HTTP2 enabled */ + *pconsumed = 0; + + if(k->upgr101 == UPGR101_RECEIVED) { + /* supposedly upgraded to http2 now */ + if(data->req.httpversion != 20) + infof(data, "Lying server, not serving HTTP/2"); + } + + if(k->httpcode < 200 && last_hd) { + /* Intermediate responses might trigger processing of more responses, + * write the last header to the client before proceeding. */ + result = http_write_header(data, last_hd, last_hd_len); + last_hd = NULL; /* handled it */ + if(result) + goto out; + } + + if(k->httpcode < 100) { + failf(data, "Unsupported response code in HTTP response"); + result = CURLE_UNSUPPORTED_PROTOCOL; + goto out; + } + else if(k->httpcode < 200) { + result = http_on_1xx_response(data, buf, blen, pconsumed, &conn_changed); + goto out; + } + + /* k->httpcode >= 200, final response */ + k->header = FALSE; + if(conn->bits.upgrade_in_progress) { + /* Asked for protocol upgrade, but it was not selected */ + conn->bits.upgrade_in_progress = FALSE; + conn_changed = TRUE; + } + + if((k->size == -1) && !k->chunk && !conn->bits.close && + (k->httpversion == 11) && + !(conn->scheme->protocol & CURLPROTO_RTSP) && + data->state.httpreq != HTTPREQ_HEAD) { + /* On HTTP 1.1, when connection is not to get closed, but no + Content-Length nor Transfer-Encoding chunked have been received, + according to RFC2616 section 4.4 point 5, we assume that the server + will close the connection to signal the end of the document. */ + infof(data, "no chunk, no close, no size. Assume close to signal end"); + streamclose(conn); + } + + http_check_auth_closure(data, conn); + +#ifndef CURL_DISABLE_WEBSOCKETS + /* All >=200 HTTP status codes are errors when wanting ws */ + if(data->req.upgr101 == UPGR101_WS) { + failf(data, "Refused WebSocket upgrade: %d", k->httpcode); + result = CURLE_HTTP_RETURNED_ERROR; + goto out; + } +#endif + + /* Check if this response means the transfer errored. */ + if(http_should_fail(data, data->req.httpcode)) { + failf(data, "The requested URL returned error: %d", + k->httpcode); + result = CURLE_HTTP_RETURNED_ERROR; + goto out; + } + + /* Curl_http_auth_act() checks what authentication methods that are + * available and decides which one (if any) to use. It will set 'newurl' if + * an auth method was picked. */ + result = Curl_http_auth_act(data); + if(result) + goto out; + + if(k->httpcode >= 300) { + result = http_handle_send_error(data); + if(result) + goto out; + } + + /* final response without error, prepare to receive the body */ + result = http_firstwrite(data); + if(result) + goto out; + + /* This is the last response that we get for the current request. Check on + * the body size and determine if the response is complete. */ + result = http_size(data); + if(result) + goto out; + + /* If we requested a "no body", this is a good time to get + * out and return home. + */ + if(data->req.no_body) + k->download_done = TRUE; + + /* If max download size is *zero* (nothing) we already have nothing and can + safely return ok now! For HTTP/2, we would like to call + http2_handle_stream_close to properly close a stream. In order to do + this, we keep reading until we close the stream. */ + if((k->maxdownload == 0) && (k->httpversion_sent < 20)) + k->download_done = TRUE; + +out: + if(last_hd) + /* if not written yet, write it now */ + result = Curl_1st_fatal(result, + http_write_header(data, last_hd, last_hd_len)); + if(conn_changed) + /* poke the multi handle to allow pending pipewait to retry */ + Curl_multi_connchanged(data->multi); + return result; +} + +static CURLcode http_rw_hd(struct Curl_easy *data, + const char *hd, size_t hdlen, + const char *buf_remain, size_t blen, + size_t *pconsumed) +{ + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + int writetype; + DEBUGASSERT(!hd[hdlen]); /* null-terminated */ + + *pconsumed = 0; + if((0x0a == *hd) || (0x0d == *hd)) { + /* Empty header line means end of headers! */ + struct dynbuf last_header; + size_t consumed; + + curlx_dyn_init(&last_header, hdlen + 1); + result = curlx_dyn_addn(&last_header, hd, hdlen); + if(result) + return result; + + /* analyze the response to find out what to do. */ + /* Caveat: we clear anything in the header brigade, because a + * response might switch HTTP version which may call use recursively. + * Not nice, but that is currently the way of things. */ + curlx_dyn_reset(&data->state.headerb); + result = http_on_response(data, curlx_dyn_ptr(&last_header), + curlx_dyn_len(&last_header), + buf_remain, blen, &consumed); + *pconsumed += consumed; + curlx_dyn_free(&last_header); + return result; + } + + /* + * Checks for special headers coming up. + */ + + writetype = CLIENTWRITE_HEADER; + if(!k->headerline++) { + /* This is the first header, it MUST be the error code line + or else we consider this to be the body right away! */ + bool fine_statusline = FALSE; + + k->httpversion = 0; /* Do not know yet */ + if(data->conn->scheme->protocol & PROTO_FAMILY_HTTP) { + /* + * https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2 + * + * The response code is always a three-digit number in HTTP as the spec + * says. We allow any three-digit number here, but we cannot make + * guarantees on future behaviors since it is not within the protocol. + */ + const char *p = hd; + + curlx_str_passblanks(&p); + if(!strncmp(p, "HTTP/", 5)) { + p += 5; + switch(*p) { + case '1': + p++; + if((p[0] == '.') && (p[1] == '0' || p[1] == '1')) { + if(ISBLANK(p[2])) { + k->httpversion = (unsigned char)(10 + (p[1] - '0')); + p += 3; + if(ISDIGIT(p[0]) && ISDIGIT(p[1]) && ISDIGIT(p[2])) { + k->httpcode = ((p[0] - '0') * 100) + ((p[1] - '0') * 10) + + (p[2] - '0'); + /* RFC 9112 requires a single space following the status code, + but the browsers do not so let's not insist */ + fine_statusline = TRUE; + } + } + } + if(!fine_statusline) { + failf(data, "Unsupported HTTP/1 subversion in response"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + break; + case '2': + case '3': + if(!ISBLANK(p[1])) + break; + k->httpversion = (unsigned char)((*p - '0') * 10); + p += 2; + if(ISDIGIT(p[0]) && ISDIGIT(p[1]) && ISDIGIT(p[2])) { + k->httpcode = ((p[0] - '0') * 100) + ((p[1] - '0') * 10) + + (p[2] - '0'); + p += 3; + if(!ISBLANK(*p)) + break; + fine_statusline = TRUE; + } + break; + default: /* unsupported */ + failf(data, "Unsupported HTTP version in response"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + } + + if(!fine_statusline) { + /* If user has set option HTTP200ALIASES, + compare header line against list of aliases */ + statusline check = checkhttpprefix(data, hd, hdlen); + if(check == STATUS_DONE) { + fine_statusline = TRUE; + k->httpcode = 200; + k->httpversion = 10; + } + } + } + else if(data->conn->scheme->protocol & CURLPROTO_RTSP) { + const char *p = hd; + struct Curl_str ver; + curl_off_t status; + /* we set the max string a little excessive to forgive some leading + spaces */ + if(!curlx_str_until(&p, &ver, 32, ' ') && + !curlx_str_single(&p, ' ') && + !curlx_str_number(&p, &status, 999)) { + curlx_str_trimblanks(&ver); + if(curlx_str_cmp(&ver, "RTSP/1.0")) { + k->httpcode = (int)status; + fine_statusline = TRUE; + k->httpversion = 11; /* RTSP acts like HTTP 1.1 */ + } + } + if(!fine_statusline) + return CURLE_WEIRD_SERVER_REPLY; + } + + if(fine_statusline) { + result = http_statusline(data, data->conn); + if(result) + return result; + writetype |= CLIENTWRITE_STATUS; + } + else { + k->header = FALSE; /* this is not a header line */ + return CURLE_WEIRD_SERVER_REPLY; + } + } + + result = Curl_verify_header(data, hd, hdlen); + if(result) + return result; + + result = http_header(data, hd, hdlen); + if(result) + return result; + + /* + * Taken in one (more) header. Write it to the client. + */ + Curl_debug(data, CURLINFO_HEADER_IN, hd, hdlen); + + if(k->httpcode / 100 == 1) + writetype |= CLIENTWRITE_1XX; + result = Curl_client_write(data, writetype, hd, hdlen); + if(result) + return result; + + result = Curl_bump_headersize(data, hdlen, FALSE); + if(result) + return result; + + return CURLE_OK; +} + +/* remove trailing CRLF then all trailing whitespace */ +void Curl_http_to_fold(struct dynbuf *bf) +{ + size_t len = curlx_dyn_len(bf); + const char *hd = curlx_dyn_ptr(bf); + if(len && (hd[len - 1] == '\n')) + len--; + if(len && (hd[len - 1] == '\r')) + len--; + while(len && ISBLANK(hd[len - 1])) /* strip off trailing whitespace */ + len--; + curlx_dyn_setlen(bf, len); +} + +static void unfold_header(struct Curl_easy *data) +{ + Curl_http_to_fold(&data->state.headerb); + data->state.leading_unfold = TRUE; +} + +/* + * Read any HTTP header lines from the server and pass them to the client app. + */ +static CURLcode http_parse_headers(struct Curl_easy *data, + const char *buf, size_t blen, + size_t *pconsumed) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + const char *end_ptr; + bool leftover_body = FALSE; + + /* we have bytes for the next header, make sure it is not a folded header + before passing it on */ + if(data->state.maybe_folded && blen) { + if(ISBLANK(buf[0])) { + /* folded, remove the trailing newlines and append the next header */ + unfold_header(data); + } + else { + /* the header data we hold is a complete header, pass it on */ + size_t ignore_this; + result = http_rw_hd(data, curlx_dyn_ptr(&data->state.headerb), + curlx_dyn_len(&data->state.headerb), + NULL, 0, &ignore_this); + curlx_dyn_reset(&data->state.headerb); + if(result) + return result; + } + data->state.maybe_folded = FALSE; + } + + /* header line within buffer loop */ + *pconsumed = 0; + while(blen && k->header) { + size_t consumed; + size_t hlen; + const char *hd; + size_t unfold_len = 0; + + if(data->state.leading_unfold) { + /* immediately after an unfold, keep only a single whitespace */ + while(blen && ISBLANK(buf[0])) { + buf++; + blen--; + unfold_len++; + } + if(blen) { + /* insert a single space */ + result = curlx_dyn_addn(&data->state.headerb, " ", 1); + if(result) + return result; + data->state.leading_unfold = FALSE; /* done now */ + } + } + + end_ptr = memchr(buf, '\n', blen); + if(!end_ptr) { + /* Not a complete header line within buffer, append the data to + the end of the headerbuff. */ + result = curlx_dyn_addn(&data->state.headerb, buf, blen); + if(result) + return result; + *pconsumed += blen + unfold_len; + + if(!k->headerline) { + /* check if this looks like a protocol header */ + statusline st = + checkprotoprefix(data, conn, + curlx_dyn_ptr(&data->state.headerb), + curlx_dyn_len(&data->state.headerb)); + + if(st == STATUS_BAD) { + /* this is not the beginning of a protocol first header line. + * Cannot be 0.9 if version was detected or connection was reused. */ + k->header = FALSE; + streamclose(conn); + if((k->httpversion >= 10) || conn->bits.reuse) { + failf(data, "Invalid status line"); + return CURLE_WEIRD_SERVER_REPLY; + } + if(!data->state.http_neg.accept_09) { + failf(data, "Received HTTP/0.9 when not allowed"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + leftover_body = TRUE; + goto out; + } + } + goto out; /* read more and try again */ + } + + /* the size of the remaining header line */ + consumed = (end_ptr - buf) + 1; + + result = curlx_dyn_addn(&data->state.headerb, buf, consumed); + if(result) + return result; + blen -= consumed; + buf += consumed; + *pconsumed += consumed + unfold_len; + + /**** + * We now have a FULL header line in 'headerb'. + *****/ + + hlen = curlx_dyn_len(&data->state.headerb); + hd = curlx_dyn_ptr(&data->state.headerb); + + if(!k->headerline) { + /* the first read "header", the status line */ + statusline st = checkprotoprefix(data, conn, hd, hlen); + if(st == STATUS_BAD) { + streamclose(conn); + /* this is not the beginning of a protocol first header line. + * Cannot be 0.9 if version was detected or connection was reused. */ + if((k->httpversion >= 10) || conn->bits.reuse) { + failf(data, "Invalid status line"); + return CURLE_WEIRD_SERVER_REPLY; + } + if(!data->state.http_neg.accept_09) { + failf(data, "Received HTTP/0.9 when not allowed"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + k->header = FALSE; + leftover_body = TRUE; + goto out; + } + } + else { + if(hlen && !ISNEWLINE(hd[0])) { + /* this is NOT the header separator */ + + /* if we have bytes for the next header, check for folding */ + if(blen && ISBLANK(buf[0])) { + /* remove the trailing CRLF and append the next header */ + unfold_header(data); + continue; + } + else if(!blen) { + /* this might be a folded header so deal with it in next invoke */ + data->state.maybe_folded = TRUE; + break; + } + } + } + + result = http_rw_hd(data, hd, hlen, buf, blen, &consumed); + /* We are done with this line. We reset because response + * processing might switch to HTTP/2 and that might call us + * directly again. */ + curlx_dyn_reset(&data->state.headerb); + if(consumed) { + blen -= consumed; + buf += consumed; + *pconsumed += consumed; + } + if(result) + return result; + } + + /* We might have reached the end of the header part here, but + there might be a non-header part left in the end of the read + buffer. */ +out: + if(!k->header && !leftover_body) { + curlx_dyn_free(&data->state.headerb); + } + return CURLE_OK; +} + +CURLcode Curl_http_write_resp_hd(struct Curl_easy *data, + const char *hd, size_t hdlen, + bool is_eos) +{ + CURLcode result; + size_t consumed; + char tmp = 0; + DEBUGASSERT(!hd[hdlen]); /* null-terminated */ + + result = http_rw_hd(data, hd, hdlen, &tmp, 0, &consumed); + if(!result && is_eos) { + result = Curl_client_write(data, (CLIENTWRITE_BODY | CLIENTWRITE_EOS), + &tmp, 0); + } + return result; +} + +/* + * HTTP protocol `write_resp` implementation. Parse headers + * when not done yet and otherwise return without consuming data. + */ +CURLcode Curl_http_write_resp_hds(struct Curl_easy *data, + const char *buf, size_t blen, + size_t *pconsumed) +{ + if(!data->req.header) { + *pconsumed = 0; + return CURLE_OK; + } + else { + CURLcode result; + + result = http_parse_headers(data, buf, blen, pconsumed); + if(!result && !data->req.header) { + if(!data->req.no_body && curlx_dyn_len(&data->state.headerb)) { + /* leftover from parsing something that turned out not + * to be a header, only happens if we allow for + * HTTP/0.9 like responses */ + result = Curl_client_write(data, CLIENTWRITE_BODY, + curlx_dyn_ptr(&data->state.headerb), + curlx_dyn_len(&data->state.headerb)); + } + curlx_dyn_free(&data->state.headerb); + } + return result; + } +} + +CURLcode Curl_http_write_resp(struct Curl_easy *data, + const char *buf, size_t blen, + bool is_eos) +{ + CURLcode result; + size_t consumed; + int flags; + + result = Curl_http_write_resp_hds(data, buf, blen, &consumed); + if(result || data->req.done) + goto out; + + DEBUGASSERT(consumed <= blen); + blen -= consumed; + buf += consumed; + /* either all was consumed in header parsing, or we have data left + * and are done with headers, e.g. it is BODY data */ + DEBUGASSERT(!blen || !data->req.header); + if(!data->req.header && (blen || is_eos)) { + /* BODY data after header been parsed, write and consume */ + flags = CLIENTWRITE_BODY; + if(is_eos) + flags |= CLIENTWRITE_EOS; + result = Curl_client_write(data, flags, buf, blen); + } +out: + return result; +} + +/* Decode HTTP status code string. */ +CURLcode Curl_http_decode_status(int *pstatus, const char *s, size_t len) +{ + CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT; + int status = 0; + int i; + + if(len != 3) + goto out; + + for(i = 0; i < 3; ++i) { + char c = s[i]; + + if(c < '0' || c > '9') + goto out; + + status *= 10; + status += c - '0'; + } + result = CURLE_OK; +out: + *pstatus = result ? -1 : status; + return result; +} + +CURLcode Curl_http_req_make(struct httpreq **preq, + const char *method, size_t m_len, + const char *scheme, size_t s_len, + const char *authority, size_t a_len, + const char *path, size_t p_len) +{ + struct httpreq *req; + CURLcode result = CURLE_OUT_OF_MEMORY; + + DEBUGASSERT(method && m_len); + + req = curlx_calloc(1, sizeof(*req) + m_len); + if(!req) + goto out; +#if defined(__GNUC__) && __GNUC__ >= 13 +#pragma GCC diagnostic push +/* error: 'memcpy' offset [137, 142] from the object at 'req' is out of + the bounds of referenced subobject 'method' with type 'char[1]' at + offset 136 */ +#pragma GCC diagnostic ignored "-Warray-bounds" +#endif + memcpy(req->method, method, m_len); +#if defined(__GNUC__) && __GNUC__ >= 13 +#pragma GCC diagnostic pop +#endif + if(scheme) { + req->scheme = curlx_memdup0(scheme, s_len); + if(!req->scheme) + goto out; + } + if(authority) { + req->authority = curlx_memdup0(authority, a_len); + if(!req->authority) + goto out; + } + if(path) { + req->path = curlx_memdup0(path, p_len); + if(!req->path) + goto out; + } + Curl_dynhds_init(&req->headers, 0, DYN_HTTP_REQUEST); + Curl_dynhds_init(&req->trailers, 0, DYN_HTTP_REQUEST); + result = CURLE_OK; + +out: + if(result && req) + Curl_http_req_free(req); + *preq = result ? NULL : req; + return result; +} + +static CURLcode req_assign_url_authority(struct httpreq *req, CURLU *url) +{ + char *host, *port; + struct dynbuf buf; + CURLUcode uc; + CURLcode result = CURLE_URL_MALFORMAT; + + host = port = NULL; + curlx_dyn_init(&buf, DYN_HTTP_REQUEST); + + uc = curl_url_get(url, CURLUPART_HOST, &host, 0); + if(uc && uc != CURLUE_NO_HOST) + goto out; + if(!host) { + req->authority = NULL; + result = CURLE_OK; + goto out; + } + + uc = curl_url_get(url, CURLUPART_PORT, &port, CURLU_NO_DEFAULT_PORT); + if(uc && uc != CURLUE_NO_PORT) + goto out; + + result = curlx_dyn_add(&buf, host); + if(result) + goto out; + if(port) { + result = curlx_dyn_addf(&buf, ":%s", port); + if(result) + goto out; + } + req->authority = curlx_dyn_ptr(&buf); +out: + curlx_free(host); + curlx_free(port); + if(result) + curlx_dyn_free(&buf); + return result; +} + +static CURLcode req_assign_url_path(struct httpreq *req, CURLU *url) +{ + char *path, *query; + struct dynbuf buf; + CURLUcode uc; + CURLcode result = CURLE_URL_MALFORMAT; + + path = query = NULL; + curlx_dyn_init(&buf, DYN_HTTP_REQUEST); + + uc = curl_url_get(url, CURLUPART_PATH, &path, 0); + if(uc) + goto out; + uc = curl_url_get(url, CURLUPART_QUERY, &query, 0); + if(uc && uc != CURLUE_NO_QUERY) + goto out; + + if(!query) { + req->path = path; + path = NULL; + } + else { + result = curlx_dyn_add(&buf, path); + if(!result) + result = curlx_dyn_addf(&buf, "?%s", query); + if(result) + goto out; + req->path = curlx_dyn_ptr(&buf); + } + result = CURLE_OK; + +out: + curlx_free(path); + curlx_free(query); + if(result) + curlx_dyn_free(&buf); + return result; +} + +CURLcode Curl_http_req_make2(struct httpreq **preq, + const char *method, size_t m_len, + CURLU *url, const char *scheme_default) +{ + struct httpreq *req; + CURLcode result = CURLE_OUT_OF_MEMORY; + CURLUcode uc; + + DEBUGASSERT(method && m_len); + + req = curlx_calloc(1, sizeof(*req) + m_len); + if(!req) + goto out; + memcpy(req->method, method, m_len); + + uc = curl_url_get(url, CURLUPART_SCHEME, &req->scheme, 0); + if(uc && uc != CURLUE_NO_SCHEME) + goto out; + if(!req->scheme && scheme_default) { + req->scheme = curlx_strdup(scheme_default); + if(!req->scheme) + goto out; + } + + result = req_assign_url_authority(req, url); + if(result) + goto out; + result = req_assign_url_path(req, url); + if(result) + goto out; + + Curl_dynhds_init(&req->headers, 0, DYN_HTTP_REQUEST); + Curl_dynhds_init(&req->trailers, 0, DYN_HTTP_REQUEST); + result = CURLE_OK; + +out: + if(result && req) + Curl_http_req_free(req); + *preq = result ? NULL : req; + return result; +} + +void Curl_http_req_free(struct httpreq *req) +{ + if(req) { + curlx_free(req->scheme); + curlx_free(req->authority); + curlx_free(req->path); + Curl_dynhds_free(&req->headers); + Curl_dynhds_free(&req->trailers); + curlx_free(req); + } +} + +struct name_const { + const char *name; + size_t namelen; +}; + +static const struct name_const H2_NON_FIELD[] = { + { STRCONST("Host") }, + { STRCONST("Upgrade") }, + { STRCONST("Connection") }, + { STRCONST("Keep-Alive") }, + { STRCONST("Proxy-Connection") }, + { STRCONST("Transfer-Encoding") }, +}; + +static bool h2_permissible_field(struct dynhds_entry *e) +{ + size_t i; + for(i = 0; i < CURL_ARRAYSIZE(H2_NON_FIELD); ++i) { + if(e->namelen == H2_NON_FIELD[i].namelen && + curl_strnequal(H2_NON_FIELD[i].name, e->name, e->namelen)) + return FALSE; + } + return TRUE; +} + +static bool http_TE_has_token(const char *fvalue, const char *token) +{ + while(*fvalue) { + struct Curl_str name; + + /* skip to first token */ + while(ISBLANK(*fvalue) || *fvalue == ',') + fvalue++; + if(curlx_str_cspn(&fvalue, &name, " \t\r;,")) + return FALSE; + if(curlx_str_casecompare(&name, token)) + return TRUE; + + /* skip any remainder after token, e.g. parameters with quoted strings */ + while(*fvalue && *fvalue != ',') { + if(*fvalue == '"') { + struct Curl_str qw; + /* if we do not cleanly find a quoted word here, the header value + * does not follow HTTP syntax and we reject */ + if(curlx_str_quotedword(&fvalue, &qw, CURL_MAX_HTTP_HEADER)) + return FALSE; + } + else + fvalue++; + } + } + return FALSE; +} + +CURLcode Curl_http_req_to_h2(struct dynhds *h2_headers, + struct httpreq *req, struct Curl_easy *data) +{ + const char *scheme = NULL, *authority = NULL; + struct dynhds_entry *e; + size_t i; + CURLcode result; + + DEBUGASSERT(req); + DEBUGASSERT(h2_headers); + + if(req->scheme) { + scheme = req->scheme; + } + else if(strcmp("CONNECT", req->method)) { + scheme = Curl_checkheaders(data, STRCONST(HTTP_PSEUDO_SCHEME)); + if(scheme) { + scheme += sizeof(HTTP_PSEUDO_SCHEME); + curlx_str_passblanks(&scheme); + infof(data, "set pseudo header %s to %s", HTTP_PSEUDO_SCHEME, scheme); + } + else { + scheme = data->state.origin->scheme->name; + } + } + + if(req->authority) { + authority = req->authority; + } + else { + e = Curl_dynhds_get(&req->headers, STRCONST("Host")); + if(e) + authority = e->value; + } + + Curl_dynhds_reset(h2_headers); + Curl_dynhds_set_opts(h2_headers, DYNHDS_OPT_LOWERCASE); + result = Curl_dynhds_add(h2_headers, STRCONST(HTTP_PSEUDO_METHOD), + req->method, strlen(req->method)); + if(!result && scheme) { + result = Curl_dynhds_add(h2_headers, STRCONST(HTTP_PSEUDO_SCHEME), + scheme, strlen(scheme)); + } + if(!result && authority) { + result = Curl_dynhds_add(h2_headers, STRCONST(HTTP_PSEUDO_AUTHORITY), + authority, strlen(authority)); + } + if(!result && req->path) { + result = Curl_dynhds_add(h2_headers, STRCONST(HTTP_PSEUDO_PATH), + req->path, strlen(req->path)); + } + for(i = 0; !result && i < Curl_dynhds_count(&req->headers); ++i) { + e = Curl_dynhds_getn(&req->headers, i); + /* "TE" is special in that it is only permissible when it + * has only value "trailers". RFC 9113 ch. 8.2.2 */ + if(e->namelen == 2 && curl_strequal("TE", e->name)) { + if(http_TE_has_token(e->value, "trailers")) + result = Curl_dynhds_add(h2_headers, e->name, e->namelen, + "trailers", CURL_CSTRLEN("trailers")); + } + else if(h2_permissible_field(e)) { + result = Curl_dynhds_add(h2_headers, e->name, e->namelen, + e->value, e->valuelen); + } + } + + return result; +} + +CURLcode Curl_http_resp_make(struct http_resp **presp, + int status, + const char *description) +{ + struct http_resp *resp; + CURLcode result = CURLE_OUT_OF_MEMORY; + + resp = curlx_calloc(1, sizeof(*resp)); + if(!resp) + goto out; + + resp->status = status; + if(description) { + resp->description = curlx_strdup(description); + if(!resp->description) + goto out; + } + Curl_dynhds_init(&resp->headers, 0, DYN_HTTP_REQUEST); + Curl_dynhds_init(&resp->trailers, 0, DYN_HTTP_REQUEST); + result = CURLE_OK; + +out: + if(result && resp) + Curl_http_resp_free(resp); + *presp = result ? NULL : resp; + return result; +} + +void Curl_http_resp_free(struct http_resp *resp) +{ + if(resp) { + curlx_free(resp->description); + Curl_dynhds_free(&resp->headers); + Curl_dynhds_free(&resp->trailers); + if(resp->prev) + Curl_http_resp_free(resp->prev); + curlx_free(resp); + } +} + +/* + * HTTP handler interface. + */ +const struct Curl_protocol Curl_protocol_http = { + Curl_http_setup_conn, /* setup_connection */ + Curl_http, /* do_it */ + Curl_http_done, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_pollset */ + Curl_http_doing_pollset, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + Curl_http_perform_pollset, /* perform_pollset */ + ZERO_NULL, /* disconnect */ + Curl_http_write_resp, /* write_resp */ + Curl_http_write_resp_hd, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + Curl_http_follow, /* follow */ +}; + +#endif /* CURL_DISABLE_HTTP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http.h new file mode 100644 index 0000000000..83b4cc6c64 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http.h @@ -0,0 +1,273 @@ +#ifndef HEADER_CURL_HTTP_H +#define HEADER_CURL_HTTP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "bufq.h" +#include "dynhds.h" + +typedef enum { + HTTPREQ_GET, + HTTPREQ_POST, + HTTPREQ_POST_FORM, /* we make a difference internally */ + HTTPREQ_POST_MIME, /* we make a difference internally */ + HTTPREQ_PUT, + HTTPREQ_HEAD +} Curl_HttpReq; + +#define CURL_HTTP_V1x (1 << 0) +#define CURL_HTTP_V2x (1 << 1) +#define CURL_HTTP_V3x (1 << 2) +/* bitmask of CURL_HTTP_V* values */ +typedef unsigned char http_majors; + +#ifndef CURL_DISABLE_HTTP + +extern const struct Curl_protocol Curl_protocol_http; + +struct dynhds; + +struct http_negotiation { + unsigned char rcvd_min; /* minimum version seen in responses, 09, 10, 11 */ + http_majors wanted; /* wanted major versions when talking to server */ + http_majors allowed; /* allowed major versions when talking to server */ + http_majors preferred; /* preferred major version when talking to server */ + BIT(h2_upgrade); /* Do HTTP Upgrade from 1.1 to 2 */ + BIT(h2_prior_knowledge); /* Directly do HTTP/2 without ALPN/SSL */ + BIT(accept_09); /* Accept an HTTP/0.9 response */ + BIT(only_10); /* When using major version 1x, use only 1.0 */ +}; + +void Curl_http_neg_init(struct Curl_easy *data, struct http_negotiation *neg); + +CURLcode Curl_bump_headersize(struct Curl_easy *data, + size_t delta, + bool connect_only); + +/* Header specific functions */ +bool Curl_compareheader(const char *headerline, /* line to check */ + const char *header, /* header keyword _with_ colon */ + const size_t hlen, /* len of the keyword in bytes */ + const char *content, /* content string to find */ + const size_t clen); /* len of the content in bytes */ + +char *Curl_copy_header_value(const char *header); + +char *Curl_checkProxyheaders(struct Curl_easy *data, + const struct connectdata *conn, + const char *thisheader, + const size_t thislen); + +CURLcode Curl_add_timecondition(struct Curl_easy *data, struct dynbuf *req); +CURLcode Curl_add_custom_headers(struct Curl_easy *data, bool is_connect, + int httpversion, struct dynbuf *req); + +void Curl_http_to_fold(struct dynbuf *bf); + +void Curl_http_method(struct Curl_easy *data, + const char **method, Curl_HttpReq *reqp); + +/* protocol-specific functions set up to be called by the main engine */ +CURLcode Curl_http_setup_conn(struct Curl_easy *data, + struct connectdata *conn); +CURLcode Curl_http(struct Curl_easy *data, bool *done); +CURLcode Curl_http_done(struct Curl_easy *data, + CURLcode status, bool premature); +CURLcode Curl_http_doing_pollset(struct Curl_easy *data, + struct easy_pollset *ps); +CURLcode Curl_http_perform_pollset(struct Curl_easy *data, + struct easy_pollset *ps); +CURLcode Curl_http_write_resp(struct Curl_easy *data, + const char *buf, size_t blen, + bool is_eos); +CURLcode Curl_http_write_resp_hd(struct Curl_easy *data, + const char *hd, size_t hdlen, + bool is_eos); + +/* check a received header line for forbidden bytes/format, the same checks + applied to regular response headers */ +CURLcode Curl_verify_header(struct Curl_easy *data, + const char *hd, size_t hdlen); + +/* These functions are in http.c */ +CURLcode Curl_http_input_auth(struct Curl_easy *data, bool proxy, + const char *auth); + +CURLcode Curl_http_auth_act(struct Curl_easy *data); + +/* follow a redirect or not */ +CURLcode Curl_http_follow(struct Curl_easy *data, const char *newurl, + followtype type); + +/* If only the PICKNONE bit is set, there has been a round-trip and we + selected to use no auth at all. Ie, we actively select no auth, as opposed + to not having one selected. The other CURLAUTH_* defines are present in the + public curl/curl.h header. */ +#define CURLAUTH_PICKNONE (1 << 30) /* do not use auth */ + +/* MAX_INITIAL_POST_SIZE indicates the number of bytes that will make the POST + data get included in the initial data chunk sent to the server. If the + data is larger than this, it will automatically get split up in multiple + system calls. + + This value used to be fairly big (100K), but we must take into account that + if the server rejects the POST due for authentication reasons, this data + will always be unconditionally sent and thus it may not be larger than can + always be afforded to send twice. + + It must not be greater than 64K to work on VMS. */ +#ifndef MAX_INITIAL_POST_SIZE +#define MAX_INITIAL_POST_SIZE (64 * 1024) +#endif + +/* EXPECT_100_THRESHOLD is the request body size limit for when libcurl will + * automatically add an "Expect: 100-continue" header in HTTP requests. When + * the size is unknown, it will always add it. + * + */ +#ifndef EXPECT_100_THRESHOLD +#define EXPECT_100_THRESHOLD (1024 * 1024) +#endif + +/* MAX_HTTP_RESP_HEADER_SIZE is the maximum size of all response headers + combined that libcurl allows for a single HTTP response, any HTTP + version. This count includes CONNECT response headers. */ +#define MAX_HTTP_RESP_HEADER_SIZE (300 * 1024) + +/* MAX_HTTP_RESP_HEADER_COUNT is the maximum number of response headers that + libcurl allows for a single HTTP response, including CONNECT and + redirects. */ +#define MAX_HTTP_RESP_HEADER_COUNT 5000 + +#endif /* CURL_DISABLE_HTTP */ + +/**************************************************************************** + * HTTP unique setup + ***************************************************************************/ + +CURLcode Curl_http_write_resp_hds(struct Curl_easy *data, + const char *buf, size_t blen, + size_t *pconsumed); + +/** + * Curl_http_output_auth() setups the authentication headers for the + * host/proxy and the correct authentication + * method. data->state.authdone is set to TRUE when authentication is + * done. + * + * @param data all information about the current transfer + * @param conn all information about the current connection + * @param request pointer to the request keyword + * @param httpreq is the request type + * @param path pointer to the requested path + * @param query pointer to the requested query or NULL + * @param is_connect boolean if this is a CONNECT request + * (where httpreq is HTTPREQ_GET since there is no HTTPREQ_CONNECT) + * + * @returns CURLcode + */ +CURLcode Curl_http_output_auth(struct Curl_easy *data, + struct connectdata *conn, + const char *request, + Curl_HttpReq httpreq, + const char *path, + const char *query, + bool is_connect); + +/* Decode HTTP status code string. */ +CURLcode Curl_http_decode_status(int *pstatus, const char *s, size_t len); + +/** + * All about a core HTTP request, excluding body and trailers + */ +struct httpreq { + struct dynhds headers; + struct dynhds trailers; + char *scheme; + char *authority; + char *path; + char method[1]; +}; + +/** + * Create an HTTP request struct. + */ +CURLcode Curl_http_req_make(struct httpreq **preq, + const char *method, size_t m_len, + const char *scheme, size_t s_len, + const char *authority, size_t a_len, + const char *path, size_t p_len); + +CURLcode Curl_http_req_make2(struct httpreq **preq, + const char *method, size_t m_len, + CURLU *url, const char *scheme_default); + +void Curl_http_req_free(struct httpreq *req); + +#define HTTP_PSEUDO_METHOD ":method" +#define HTTP_PSEUDO_SCHEME ":scheme" +#define HTTP_PSEUDO_AUTHORITY ":authority" +#define HTTP_PSEUDO_PATH ":path" +#define HTTP_PSEUDO_STATUS ":status" + +/** + * Create the list of HTTP/2 headers which represent the request, + * using HTTP/2 pseudo headers preceding the `req->headers`. + * + * Applies the following transformations: + * - if `authority` is set, any "Host" header is removed. + * - if `authority` is unset and a "Host" header is present, use + * that as `authority` and remove "Host" + * - removes and Connection header fields as defined in rfc9113 ch. 8.2.2 + * - lower-cases the header field names + * + * @param h2_headers will contain the HTTP/2 headers on success + * @param req the request to transform + * @param data the handle to lookup defaults like ' :scheme' from + */ +CURLcode Curl_http_req_to_h2(struct dynhds *h2_headers, + struct httpreq *req, struct Curl_easy *data); + +/** + * All about a core HTTP response, excluding body and trailers + */ +struct http_resp { + int status; + char *description; + struct dynhds headers; + struct dynhds trailers; + struct http_resp *prev; +}; + +/** + * Create an HTTP response struct. + */ +CURLcode Curl_http_resp_make(struct http_resp **presp, + int status, + const char *description); + +void Curl_http_resp_free(struct http_resp *resp); + +#endif /* HEADER_CURL_HTTP_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http1.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http1.c new file mode 100644 index 0000000000..60ad32ce89 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http1.c @@ -0,0 +1,347 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_HTTP + +#include "urldata.h" +#include "http.h" +#include "http1.h" +#include "urlapi-int.h" + + +#define H1_MAX_URL_LEN (8 * 1024) + +void Curl_h1_req_parse_init(struct h1_req_parser *parser, size_t max_line_len) +{ + memset(parser, 0, sizeof(*parser)); + parser->max_line_len = max_line_len; + curlx_dyn_init(&parser->scratch, max_line_len); +} + +void Curl_h1_req_parse_free(struct h1_req_parser *parser) +{ + if(parser) { + Curl_http_req_free(parser->req); + curlx_dyn_free(&parser->scratch); + parser->req = NULL; + parser->done = FALSE; + } +} + +static CURLcode trim_line(struct h1_req_parser *parser, int options) +{ + DEBUGASSERT(parser->line); + if(parser->line_len) { + if(parser->line[parser->line_len - 1] == '\n') + --parser->line_len; + if(parser->line_len) { + if(parser->line[parser->line_len - 1] == '\r') + --parser->line_len; + else if(options & H1_PARSE_OPT_STRICT) + return CURLE_URL_MALFORMAT; + } + else if(options & H1_PARSE_OPT_STRICT) + return CURLE_URL_MALFORMAT; + } + else if(options & H1_PARSE_OPT_STRICT) + return CURLE_URL_MALFORMAT; + + if(parser->line_len > parser->max_line_len) { + return CURLE_URL_MALFORMAT; + } + return CURLE_OK; +} + +static CURLcode detect_line(struct h1_req_parser *parser, + const uint8_t *buf, const size_t buflen, + size_t *pnread) +{ + const char *line_end; + + DEBUGASSERT(!parser->line); + *pnread = 0; + line_end = memchr(buf, '\n', buflen); + if(!line_end) + return CURLE_AGAIN; + parser->line = (const char *)buf; + parser->line_len = line_end - parser->line + 1; + *pnread = parser->line_len; + return CURLE_OK; +} + +static CURLcode next_line(struct h1_req_parser *parser, + const uint8_t *buf, const size_t buflen, int options, + size_t *pnread) +{ + CURLcode result; + + *pnread = 0; + if(parser->line) { + parser->line = NULL; + parser->line_len = 0; + curlx_dyn_reset(&parser->scratch); + } + + result = detect_line(parser, buf, buflen, pnread); + if(!result) { + if(curlx_dyn_len(&parser->scratch)) { + /* append detected line to scratch to have the complete line */ + result = curlx_dyn_addn(&parser->scratch, parser->line, + parser->line_len); + if(result) + return result; + parser->line = curlx_dyn_ptr(&parser->scratch); + parser->line_len = curlx_dyn_len(&parser->scratch); + } + result = trim_line(parser, options); + if(result) + return result; + } + else if(result == CURLE_AGAIN) { + /* no line end in `buf`, add it to our scratch */ + result = curlx_dyn_addn(&parser->scratch, (const unsigned char *)buf, + buflen); + *pnread = buflen; + } + return result; +} + +static CURLcode start_req(struct h1_req_parser *parser, + const char *scheme_default, + const char *custom_method, + int options) +{ + const char *p, *m, *target, *hv, *scheme, *authority, *path; + size_t m_len, target_len, hv_len, scheme_len, authority_len, path_len; + size_t i; + CURLU *url = NULL; + CURLcode result = CURLE_URL_MALFORMAT; /* Use this as default fail */ + + DEBUGASSERT(!parser->req); + /* line must match: "METHOD TARGET HTTP_VERSION" */ + if(custom_method && custom_method[0] && + !strncmp(custom_method, parser->line, strlen(custom_method))) { + p = parser->line + strlen(custom_method); + } + else { + p = memchr(parser->line, ' ', parser->line_len); + if(!p || p == parser->line) + goto out; + } + + m = parser->line; + m_len = p - parser->line; + target = p + 1; + target_len = hv_len = 0; + hv = NULL; + + /* URL may contain spaces so scan backwards */ + for(i = parser->line_len; i > m_len; --i) { + if(parser->line[i] == ' ') { + hv = &parser->line[i + 1]; + hv_len = parser->line_len - i; + target_len = (hv - target) - 1; + break; + } + } + /* no SPACE found or empty TARGET or empty HTTP_VERSION */ + if(!target_len || !hv_len) + goto out; + + (void)hv; + + /* The TARGET can be (rfc 9112, ch. 3.2): + * origin-form: path + optional query + * absolute-form: absolute URI + * authority-form: host+port for CONNECT + * asterisk-form: '*' for OPTIONS + * + * from TARGET, we derive `scheme` `authority` `path` + * origin-form -- -- TARGET + * absolute-form URL* URL* URL* + * authority-form -- TARGET -- + * asterisk-form -- -- TARGET + */ + scheme = authority = path = NULL; + scheme_len = authority_len = path_len = 0; + + if(target_len == 1 && target[0] == '*') { + /* asterisk-form */ + path = target; + path_len = target_len; + } + else if(!strncmp("CONNECT", m, m_len)) { + /* authority-form */ + authority = target; + authority_len = target_len; + } + else if(target[0] == '/') { + /* origin-form */ + path = target; + path_len = target_len; + } + else { + /* origin-form OR absolute-form */ + CURLUcode uc; + char tmp[H1_MAX_URL_LEN]; + + /* default, unless we see an absolute URL */ + path = target; + path_len = target_len; + + /* URL parser wants null-termination */ + if(target_len >= sizeof(tmp)) + goto out; + memcpy(tmp, target, target_len); + tmp[target_len] = '\0'; + /* See if treating TARGET as an absolute URL makes sense */ + if(Curl_is_absolute_url(tmp, NULL, 0, FALSE)) { + unsigned int url_options; + + url = curl_url(); + if(!url) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + url_options = (CURLU_NON_SUPPORT_SCHEME | + CURLU_PATH_AS_IS | + CURLU_NO_DEFAULT_PORT); + if(!(options & H1_PARSE_OPT_STRICT)) + url_options |= CURLU_ALLOW_SPACE; + uc = curl_url_set(url, CURLUPART_URL, tmp, url_options); + if(uc) { + goto out; + } + } + + if(!url && (options & H1_PARSE_OPT_STRICT)) { + /* we should have an absolute URL or have seen `/` earlier */ + goto out; + } + } + + if(url) { + result = Curl_http_req_make2(&parser->req, m, m_len, url, scheme_default); + } + else { + if(!scheme && scheme_default) { + scheme = scheme_default; + scheme_len = strlen(scheme_default); + } + result = Curl_http_req_make(&parser->req, m, m_len, scheme, scheme_len, + authority, authority_len, path, path_len); + } + +out: + curl_url_cleanup(url); + return result; +} + +CURLcode Curl_h1_req_parse_read(struct h1_req_parser *parser, + const uint8_t *buf, size_t buflen, + const char *scheme_default, + const char *custom_method, + int options, size_t *pnread) +{ + CURLcode result = CURLE_OK; + size_t nread; + + *pnread = 0; + + DEBUGASSERT(buf); + if(!buf) + return CURLE_BAD_FUNCTION_ARGUMENT; + + while(!parser->done) { + result = next_line(parser, buf, buflen, options, &nread); + if(result) { + if(result == CURLE_AGAIN) + result = CURLE_OK; + goto out; + } + + /* Consume this line */ + *pnread += nread; + buf += nread; + buflen -= nread; + + if(!parser->line) { + /* consumed bytes, but line not complete */ + if(!buflen) + goto out; + } + else if(!parser->req) { + result = start_req(parser, scheme_default, custom_method, options); + if(result) + goto out; + } + else if(parser->line_len == 0) { + /* last, empty line, we are finished */ + if(!parser->req) { + result = CURLE_URL_MALFORMAT; + goto out; + } + parser->done = TRUE; + curlx_dyn_reset(&parser->scratch); + /* last chance adjustments */ + } + else { + result = Curl_dynhds_h1_add_line(&parser->req->headers, + parser->line, parser->line_len); + if(result) + goto out; + } + } + +out: + return result; +} + +CURLcode Curl_h1_req_write_head(struct httpreq *req, int http_minor, + struct dynbuf *dbuf) +{ + CURLcode result; + + result = curlx_dyn_addf(dbuf, "%s %s%s%s%s HTTP/1.%d\r\n", + req->method, + req->scheme ? req->scheme : "", + req->scheme ? "://" : "", + req->authority ? req->authority : "", + req->path ? req->path : "", + http_minor); + if(result) + goto out; + + result = Curl_dynhds_h1_dprint(&req->headers, dbuf); + if(result) + goto out; + + result = curlx_dyn_addn(dbuf, STRCONST("\r\n")); + +out: + return result; +} + +#endif /* !CURL_DISABLE_HTTP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http1.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http1.h new file mode 100644 index 0000000000..c2894613de --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http1.h @@ -0,0 +1,63 @@ +#ifndef HEADER_CURL_HTTP1_H +#define HEADER_CURL_HTTP1_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_HTTP +#include "bufq.h" +#include "http.h" + +#define H1_PARSE_OPT_NONE 0 +#define H1_PARSE_OPT_STRICT (1 << 0) + +#define H1_PARSE_DEFAULT_MAX_LINE_LEN DYN_HTTP_REQUEST + +struct h1_req_parser { + struct httpreq *req; + struct dynbuf scratch; + size_t scratch_skip; + const char *line; + size_t max_line_len; + size_t line_len; + BIT(done); +}; + +void Curl_h1_req_parse_init(struct h1_req_parser *parser, size_t max_line_len); +void Curl_h1_req_parse_free(struct h1_req_parser *parser); + +CURLcode Curl_h1_req_parse_read(struct h1_req_parser *parser, + const uint8_t *buf, size_t buflen, + const char *scheme_default, + const char *custom_method, + int options, size_t *pnread); + +CURLcode Curl_h1_req_dprint(const struct httpreq *req, + struct dynbuf *dbuf); + +CURLcode Curl_h1_req_write_head(struct httpreq *req, int http_minor, + struct dynbuf *dbuf); + +#endif /* !CURL_DISABLE_HTTP */ +#endif /* HEADER_CURL_HTTP1_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http2.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http2.c new file mode 100644 index 0000000000..0cfdf20571 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http2.c @@ -0,0 +1,2999 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_NGHTTP2) +#include <nghttp2/nghttp2.h> + +#include "urldata.h" +#include "bufq.h" +#include "uint-hash.h" +#include "http1.h" +#include "http2.h" +#include "http.h" +#include "sendf.h" +#include "curl_trc.h" +#include "select.h" +#include "curlx/base64.h" +#include "multiif.h" +#include "progress.h" +#include "url.h" +#include "urlapi-int.h" +#include "cfilters.h" +#include "connect.h" +#include "transfer.h" +#include "bufref.h" +#include "curlx/dynbuf.h" +#include "headers.h" +#include "curl_share.h" + +#if NGHTTP2_VERSION_NUM < 0x010f00 +#error "nghttp2 1.15.0 or greater required" +#endif + +#define NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE 1 + +/* buffer dimensioning: + * use 16K as chunk size, as that fits H2 DATA frames well */ +#define H2_CHUNK_SIZE (16 * 1024) +/* connection window size */ +#define H2_CONN_WINDOW_SIZE (10 * 1024 * 1024) +/* on receiving from TLS, we prep for holding a full stream window */ +#define H2_NW_RECV_CHUNKS (H2_CONN_WINDOW_SIZE / H2_CHUNK_SIZE) +/* on send into TLS, we want to accumulate small frames */ +#define H2_NW_SEND_CHUNKS 1 +/* this is how much we want "in flight" for a stream, unthrottled */ +#define H2_STREAM_WINDOW_SIZE_MAX (10 * 1024 * 1024) +/* this is how much we want "in flight" for a stream, initially, IFF + * nghttp2 allows us to tweak the local window size. */ +#if NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE +#define H2_STREAM_WINDOW_SIZE_INITIAL (64 * 1024) +#else +#define H2_STREAM_WINDOW_SIZE_INITIAL H2_STREAM_WINDOW_SIZE_MAX +#endif +/* keep smaller stream upload buffer (default h2 window size) to have + * our progress bars and "upload done" reporting closer to reality */ +#define H2_STREAM_SEND_CHUNKS ((64 * 1024) / H2_CHUNK_SIZE) +/* spare chunks we keep for a full window */ +#define H2_STREAM_POOL_SPARES (H2_CONN_WINDOW_SIZE / H2_CHUNK_SIZE) + +/* We need to accommodate the max number of streams with their window sizes on + * the overall connection. Streams might become PAUSED which will block their + * received QUOTA in the connection window. If we run out of space, the server + * is blocked from sending us any data. See #10988 for an issue with this. */ +#define HTTP2_HUGE_WINDOW_SIZE (100 * H2_STREAM_WINDOW_SIZE_MAX) + +#define H2_SETTINGS_IV_LEN 3 +#define H2_BINSETTINGS_LEN 80 + +struct cf_h2_ctx { + nghttp2_session *h2; + /* The easy handle used in the current filter call, cleared at return */ + struct cf_call_data call_data; + + struct bufq inbufq; /* network input */ + struct bufq outbufq; /* network output */ + struct bufc_pool stream_bufcp; /* spares for stream buffers */ + struct dynbuf scratch; /* scratch buffer for temp use */ + + struct uint_hash streams; /* hash of `data->mid` to `h2_stream_ctx` */ + size_t drain_total; /* sum of all stream's UrlState drain */ + uint32_t initial_win_size; /* current initial window size (settings) */ + uint32_t max_concurrent_streams; + uint32_t goaway_error; /* goaway error code from server */ + int32_t remote_max_sid; /* max id processed by server */ + int32_t local_max_sid; /* max id processed by us */ + BIT(initialized); + BIT(via_h1_upgrade); + BIT(conn_closed); + BIT(rcvd_goaway); + BIT(sent_goaway); + BIT(enable_push); + BIT(nw_out_blocked); +}; + +/* How to access `call_data` from a cf_h2 filter */ +#undef CF_CTX_CALL_DATA +#define CF_CTX_CALL_DATA(cf) ((struct cf_h2_ctx *)(cf)->ctx)->call_data + +/** + * All about the H2 internals of a stream + */ +struct h2_stream_ctx { + struct bufq sendbuf; /* request buffer */ + struct h1_req_parser h1; /* parsing the request */ + struct dynhds resp_trailers; /* response trailer fields */ + size_t resp_hds_len; /* amount of response header bytes in recvbuf */ + curl_off_t nrcvd_data; /* number of DATA bytes received */ + + char **push_headers; /* allocated array */ + size_t push_headers_used; /* number of entries filled in */ + size_t push_headers_alloc; /* number of entries allocated */ + + int status_code; /* HTTP response status code */ + uint32_t error; /* stream error code */ + CURLcode xfer_result; /* Result of writing out response */ + int32_t local_window_size; /* the local recv window size */ + int32_t id; /* HTTP/2 protocol identifier for stream */ + BIT(resp_hds_complete); /* we have a complete, final response */ + BIT(closed); /* TRUE on stream close */ + BIT(reset); /* TRUE on stream reset */ + BIT(reset_by_server); /* TRUE on stream reset by server */ + BIT(close_handled); /* TRUE if stream closure is handled by libcurl */ + BIT(bodystarted); + BIT(body_eos); /* the complete body has been added to `sendbuf` and + * is being/has been processed from there. */ + BIT(write_paused); /* stream write is paused */ +}; + +static void free_push_headers(struct h2_stream_ctx *stream) +{ + size_t i; + for(i = 0; i < stream->push_headers_used; i++) + curlx_free(stream->push_headers[i]); + curlx_safefree(stream->push_headers); + stream->push_headers_used = 0; +} + +static void h2_stream_ctx_free(struct h2_stream_ctx *stream) +{ + Curl_bufq_free(&stream->sendbuf); + Curl_h1_req_parse_free(&stream->h1); + Curl_dynhds_free(&stream->resp_trailers); + free_push_headers(stream); + curlx_free(stream); +} + +static void h2_stream_hash_free(unsigned int id, void *stream) +{ + (void)id; + DEBUGASSERT(stream); + h2_stream_ctx_free((struct h2_stream_ctx *)stream); +} + +static void cf_h2_ctx_init(struct cf_h2_ctx *ctx, bool via_h1_upgrade) +{ + Curl_bufcp_init(&ctx->stream_bufcp, H2_CHUNK_SIZE, H2_STREAM_POOL_SPARES); + Curl_bufq_initp(&ctx->inbufq, &ctx->stream_bufcp, H2_NW_RECV_CHUNKS, 0); + Curl_bufq_initp(&ctx->outbufq, &ctx->stream_bufcp, H2_NW_SEND_CHUNKS, 0); + curlx_dyn_init(&ctx->scratch, CURL_MAX_HTTP_HEADER); + Curl_uint32_hash_init(&ctx->streams, 63, h2_stream_hash_free); + ctx->remote_max_sid = INT32_MAX; + ctx->via_h1_upgrade = via_h1_upgrade; + ctx->initialized = TRUE; +} + +static void cf_h2_ctx_free(struct cf_h2_ctx *ctx) +{ + if(ctx && ctx->initialized) { + if(ctx->h2) + nghttp2_session_del(ctx->h2); + Curl_bufq_free(&ctx->inbufq); + Curl_bufq_free(&ctx->outbufq); + Curl_bufcp_free(&ctx->stream_bufcp); + curlx_dyn_free(&ctx->scratch); + Curl_uint32_hash_destroy(&ctx->streams); + memset(ctx, 0, sizeof(*ctx)); + } + curlx_free(ctx); +} + +static uint32_t cf_h2_initial_win_size(struct Curl_easy *data) +{ +#if NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE + /* If the transfer has a rate-limit lower than the default initial + * stream window size, use that. It needs to be at least 8k or servers + * may be unhappy. */ + curl_off_t rps = Curl_rlimit_per_step(&data->progress.dl.rlimit); + if((rps > 0) && (rps < H2_STREAM_WINDOW_SIZE_INITIAL)) + return CURLMAX((uint32_t)rps, 8192); +#endif + return H2_STREAM_WINDOW_SIZE_INITIAL; +} + +static size_t populate_settings(nghttp2_settings_entry *iv, + struct Curl_easy *data, + struct cf_h2_ctx *ctx) +{ + iv[0].settings_id = NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; + iv[0].value = Curl_multi_max_concurrent_streams(data->multi); + + iv[1].settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; + iv[1].value = cf_h2_initial_win_size(data); + if(ctx) + ctx->initial_win_size = iv[1].value; + iv[2].settings_id = NGHTTP2_SETTINGS_ENABLE_PUSH; + iv[2].value = !!data->multi->push_cb; + + return 3; +} + +static ssize_t populate_binsettings(uint8_t *binsettings, + struct Curl_easy *data) +{ + nghttp2_settings_entry iv[H2_SETTINGS_IV_LEN]; + size_t ivlen; + + ivlen = populate_settings(iv, data, NULL); + /* this returns number of bytes it wrote or a negative number on error. */ + return nghttp2_pack_settings_payload(binsettings, H2_BINSETTINGS_LEN, + iv, ivlen); +} + +static CURLcode cf_h2_update_settings(struct cf_h2_ctx *ctx, + uint32_t initial_win_size) +{ + nghttp2_settings_entry entry; + entry.settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; + entry.value = initial_win_size; + if(nghttp2_submit_settings(ctx->h2, NGHTTP2_FLAG_NONE, &entry, 1)) + return CURLE_SEND_ERROR; + ctx->initial_win_size = initial_win_size; + return CURLE_OK; +} + +#define H2_STREAM_CTX(ctx, data) \ + ((struct h2_stream_ctx *)( \ + (data) ? Curl_uint32_hash_get(&(ctx)->streams, (data)->mid) : NULL)) + +static struct h2_stream_ctx *h2_stream_ctx_create(struct cf_h2_ctx *ctx) +{ + struct h2_stream_ctx *stream; + + (void)ctx; + stream = curlx_calloc(1, sizeof(*stream)); + if(!stream) + return NULL; + + stream->id = -1; + Curl_bufq_initp(&stream->sendbuf, &ctx->stream_bufcp, + H2_STREAM_SEND_CHUNKS, BUFQ_OPT_NONE); + Curl_h1_req_parse_init(&stream->h1, H1_PARSE_DEFAULT_MAX_LINE_LEN); + Curl_dynhds_init(&stream->resp_trailers, 0, DYN_HTTP_REQUEST); + stream->bodystarted = FALSE; + stream->status_code = -1; + stream->closed = FALSE; + stream->close_handled = FALSE; + stream->error = NGHTTP2_NO_ERROR; + stream->local_window_size = H2_STREAM_WINDOW_SIZE_INITIAL; + stream->nrcvd_data = 0; + return stream; +} + +#ifdef NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE +static int32_t cf_h2_get_desired_local_win(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + curl_off_t avail = Curl_rlimit_avail(&data->progress.dl.rlimit, NULL); + + (void)cf; + if(avail < CURL_OFF_T_MAX) { /* limit in place */ + if(avail <= 0) + return 0; + else if(avail < INT32_MAX) + return (int32_t)avail; + } + return H2_STREAM_WINDOW_SIZE_MAX; +} + +static CURLcode cf_h2_update_local_win(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h2_stream_ctx *stream) +{ + struct cf_h2_ctx *ctx = cf->ctx; + int32_t dwsize; + int rv; + + dwsize = (stream->write_paused || stream->xfer_result) ? + 0 : cf_h2_get_desired_local_win(cf, data); + if(dwsize != stream->local_window_size) { + int32_t wsize = nghttp2_session_get_stream_effective_local_window_size( + ctx->h2, stream->id); + if(dwsize > wsize) { + rv = nghttp2_session_set_local_window_size(ctx->h2, NGHTTP2_FLAG_NONE, + stream->id, dwsize); + if(rv) { + failf(data, "[%d] nghttp2 set_local_window_size(%d) failed: " + "%s(%d)", stream->id, dwsize, nghttp2_strerror(rv), rv); + return CURLE_HTTP2; + } + rv = nghttp2_submit_window_update(ctx->h2, NGHTTP2_FLAG_NONE, + stream->id, dwsize - wsize); + if(rv) { + failf(data, "[%d] nghttp2_submit_window_update() failed: " + "%s(%d)", stream->id, nghttp2_strerror(rv), rv); + return CURLE_HTTP2; + } + stream->local_window_size = dwsize; + CURL_TRC_CF(data, cf, "[%d] local window update by %d", + stream->id, dwsize - wsize); + } + else { + rv = nghttp2_session_set_local_window_size(ctx->h2, NGHTTP2_FLAG_NONE, + stream->id, dwsize); + if(rv) { + failf(data, "[%d] nghttp2_session_set_local_window_size() failed: " + "%s(%d)", stream->id, nghttp2_strerror(rv), rv); + return CURLE_HTTP2; + } + stream->local_window_size = dwsize; + CURL_TRC_CF(data, cf, "[%d] local window size now %d", + stream->id, dwsize); + } + } + return CURLE_OK; +} + +#else /* NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE */ + +static CURLcode cf_h2_update_local_win(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h2_stream_ctx *stream) +{ + (void)cf; + (void)data; + (void)stream; + return CURLE_OK; +} +#endif /* !NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE */ + +static CURLcode http2_data_setup(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h2_stream_ctx **pstream) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream; + + (void)cf; + DEBUGASSERT(data); + + if(!data) + return CURLE_BAD_FUNCTION_ARGUMENT; + + stream = H2_STREAM_CTX(ctx, data); + if(stream) { + *pstream = stream; + return CURLE_OK; + } + + stream = h2_stream_ctx_create(ctx); + if(!stream) + return CURLE_OUT_OF_MEMORY; + + if(!Curl_uint32_hash_set(&ctx->streams, data->mid, stream)) { + h2_stream_ctx_free(stream); + return CURLE_OUT_OF_MEMORY; + } + + *pstream = stream; + return CURLE_OK; +} + +static CURLcode nw_out_flush(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + size_t nwritten; + CURLcode result; + + if(Curl_bufq_is_empty(&ctx->outbufq)) + return CURLE_OK; + + result = Curl_cf_send_bufq(cf->next, data, &ctx->outbufq, NULL, 0, + &nwritten); + if(result) { + if(result == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "flush nw send buffer(%zu) -> EAGAIN", + Curl_bufq_len(&ctx->outbufq)); + ctx->nw_out_blocked = 1; + } + return result; + } + return Curl_bufq_is_empty(&ctx->outbufq) ? CURLE_OK : CURLE_AGAIN; +} + +static void http2_data_done(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + + DEBUGASSERT(ctx); + if(!stream || !ctx->initialized) + return; + + if(ctx->h2) { + bool flush_egress = FALSE; + /* returns error if stream not known, which is fine here */ + (void)nghttp2_session_set_stream_user_data(ctx->h2, stream->id, NULL); + + if(!stream->closed && stream->id > 0) { + /* RST_STREAM */ + CURL_TRC_CF(data, cf, "[%d] premature DATA_DONE, RST stream", + stream->id); + stream->closed = TRUE; + stream->reset = TRUE; + nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE, + stream->id, NGHTTP2_STREAM_CLOSED); + flush_egress = TRUE; + } + + if(flush_egress) { + (void)nghttp2_session_send(ctx->h2); + (void)nw_out_flush(cf, data); + } + } + + Curl_uint32_hash_remove(&ctx->streams, data->mid); +} + +static int h2_client_new(struct Curl_cfilter *cf, + nghttp2_session_callbacks *cbs) +{ + struct cf_h2_ctx *ctx = cf->ctx; + nghttp2_option *o; + nghttp2_mem mem = { NULL, Curl_nghttp2_malloc, Curl_nghttp2_free, + Curl_nghttp2_calloc, Curl_nghttp2_realloc }; + + int rc = nghttp2_option_new(&o); + if(rc) + return rc; + /* We handle window updates ourself to enforce buffer limits */ + nghttp2_option_set_no_auto_window_update(o, 1); +#if NGHTTP2_VERSION_NUM >= 0x013200 /* with 1.50.0 */ + /* turn off RFC 9113 leading and trailing white spaces validation against + HTTP field value. */ + nghttp2_option_set_no_rfc9113_leading_and_trailing_ws_validation(o, 1); +#endif + rc = nghttp2_session_client_new3(&ctx->h2, cbs, cf, o, &mem); + nghttp2_option_del(o); + return rc; +} + +/* + * Returns nonzero if current HTTP/2 session should be closed. + */ +static int should_close_session(struct cf_h2_ctx *ctx) +{ + return ctx->drain_total == 0 && !nghttp2_session_want_read(ctx->h2) && + !nghttp2_session_want_write(ctx->h2); +} + +/* + * Processes pending input left in network input buffer. + * This function returns 0 if it succeeds, or -1 and error code will + * be assigned to *err. + */ +static CURLcode h2_process_pending_input(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + const unsigned char *buf; + size_t blen, nread; + ssize_t rv; + + while(Curl_bufq_peek(&ctx->inbufq, &buf, &blen)) { + rv = nghttp2_session_mem_recv(ctx->h2, (const uint8_t *)buf, blen); + if(!curlx_sztouz(rv, &nread)) { + failf(data, "nghttp2 recv error %zd: %s", rv, nghttp2_strerror((int)rv)); + return CURLE_HTTP2; + } + Curl_bufq_skip(&ctx->inbufq, nread); + if(Curl_bufq_is_empty(&ctx->inbufq)) { + break; + } + else { + CURL_TRC_CF(data, cf, "process_pending_input: %zu bytes left " + "in connection buffer", Curl_bufq_len(&ctx->inbufq)); + } + } + + if(nghttp2_session_check_request_allowed(ctx->h2) == 0) { + /* No more requests are allowed in the current session, so + the connection may not be reused. This is set when a + GOAWAY frame has been received or when the limit of stream + identifiers has been reached. */ + CURL_TRC_M(data, "http/2: No new requests allowed"); + connclose(cf->conn); + } + + return CURLE_OK; +} + +/* + * The server may send us data at any point (e.g. PING frames). Therefore, we + * cannot assume that an HTTP/2 socket is dead because it is readable. + * + * Check the lower filters first and, if successful, peek at the socket + * and distinguish between closed and data. + */ +static bool http2_connisalive(struct Curl_cfilter *cf, struct Curl_easy *data, + bool *input_pending) +{ + struct cf_h2_ctx *ctx = cf->ctx; + bool alive = TRUE; + + *input_pending = FALSE; + if(!cf->next || !cf->next->cft->is_alive(cf->next, data, input_pending)) + return FALSE; + + if(*input_pending) { + /* This happens before we have sent off a request and the connection is + not in use by any other transfer, there should not be any data here, + only "protocol frames" */ + CURLcode result; + size_t nread; + + *input_pending = FALSE; + result = Curl_cf_recv_bufq(cf->next, data, &ctx->inbufq, 0, &nread); + CURL_TRC_CF(data, cf, "connisalive, recv pending input -> %d, %zu", + (int)result, nread); + if(!result) { + result = h2_process_pending_input(cf, data); + if(result) + /* immediate error, considered dead */ + alive = FALSE; + else { + alive = !should_close_session(ctx); + } + } + else if(result != CURLE_AGAIN) { + /* the read failed so let's say this is dead anyway */ + alive = FALSE; + } + } + + return alive; +} + +static CURLcode http2_send_ping(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + int rc; + + rc = nghttp2_submit_ping(ctx->h2, 0, ZERO_NULL); + if(rc) { + failf(data, "nghttp2_submit_ping() failed: %s(%d)", + nghttp2_strerror(rc), rc); + return CURLE_HTTP2; + } + + rc = nghttp2_session_send(ctx->h2); + if(rc) { + failf(data, "nghttp2_session_send() failed: %s(%d)", + nghttp2_strerror(rc), rc); + return CURLE_SEND_ERROR; + } + return CURLE_OK; +} + +/* + * Store nghttp2 version info in this buffer. + */ +void Curl_http2_ver(char *p, size_t len) +{ + nghttp2_info *h2 = nghttp2_version(0); + (void)curl_msnprintf(p, len, "nghttp2/%s", h2->version_str); +} + +/* + * The implementation of nghttp2_send_callback type. Here we write |data| with + * size |length| to the network and return the number of bytes actually + * written. See the documentation of nghttp2_send_callback for the details. + */ +static ssize_t send_callback(nghttp2_session *h2, + const uint8_t *buf, size_t blen, int flags, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + size_t nwritten; + CURLcode result = CURLE_OK; + + (void)h2; + (void)flags; + DEBUGASSERT(data); + + if(!cf->connected) + result = Curl_bufq_write(&ctx->outbufq, buf, blen, &nwritten); + else + result = Curl_cf_send_bufq(cf->next, data, &ctx->outbufq, buf, blen, + &nwritten); + + if(result) { + if(result == CURLE_AGAIN) { + ctx->nw_out_blocked = 1; + return NGHTTP2_ERR_WOULDBLOCK; + } + failf(data, "Failed sending HTTP2 data"); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + + if(!nwritten) { + ctx->nw_out_blocked = 1; + return NGHTTP2_ERR_WOULDBLOCK; + } + return (nwritten > SSIZE_MAX) ? + NGHTTP2_ERR_CALLBACK_FAILURE : (ssize_t)nwritten; +} + +/* We pass a pointer to this struct in the push callback, but the contents of + the struct are hidden from the user. */ +struct curl_pushheaders { + struct Curl_easy *data; + struct h2_stream_ctx *stream; + const nghttp2_push_promise *frame; +}; + +/* + * push header access function. Only to be used from within the push callback + */ +char *curl_pushheader_bynum(struct curl_pushheaders *h, size_t num) +{ + /* Verify that we got a good easy handle in the push header struct, mostly to + detect rubbish input fast(er). */ + if(!h || !GOOD_EASY_HANDLE(h->data)) + return NULL; + else { + if(h->stream && num < h->stream->push_headers_used) + return h->stream->push_headers[num]; + } + return NULL; +} + +/* + * push header access function. Only to be used from within the push callback + */ +char *curl_pushheader_byname(struct curl_pushheaders *h, const char *name) +{ + struct h2_stream_ctx *stream; + size_t len; + size_t i; + /* Verify that we got a good easy handle in the push header struct, + mostly to detect rubbish input fast(er). Also empty header name + is rubbish too. We have to allow ":" at the beginning of + the header, but header == ":" must be rejected. If we have ':' in + the middle of header, it could be matched in middle of the value, + this is because we do prefix match.*/ + if(!h || !GOOD_EASY_HANDLE(h->data) || !name || !name[0] || + !strcmp(name, ":") || strchr(name + 1, ':')) + return NULL; + + stream = h->stream; + if(!stream) + return NULL; + + len = strlen(name); + for(i = 0; i < stream->push_headers_used; i++) { + if(!strncmp(name, stream->push_headers[i], len)) { + /* sub-match, make sure that it is followed by a colon */ + if(stream->push_headers[i][len] != ':') + continue; + return &stream->push_headers[i][len + 1]; + } + } + return NULL; +} + +static struct Curl_easy *h2_duphandle(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct Curl_easy *second = curl_easy_init(); + if(second) { + struct h2_stream_ctx *second_stream; + http2_data_setup(cf, second, &second_stream); + second->state.weight = data->state.weight; + if(data->share) + (void)Curl_share_easy_link(second, data->share); + } + return second; +} + +static int set_transfer_url(struct Curl_easy *newhandle, + struct curl_pushheaders *hp, + struct Curl_easy *data) +{ + const char *v; + CURLUcode uc; + char *url = NULL; + int rc = 0; + CURLU *u = curl_url(); + + if(!u) + return 5; + + v = curl_pushheader_byname(hp, HTTP_PSEUDO_SCHEME); + if(v) { + uc = curl_url_set(u, CURLUPART_SCHEME, v, 0); + if(uc) { + rc = 1; + goto fail; + } + } + + v = curl_pushheader_byname(hp, HTTP_PSEUDO_AUTHORITY); + if(v) { + uc = Curl_url_set_authority(u, v); + if(uc) { + rc = 2; + goto fail; + } + } + + v = curl_pushheader_byname(hp, HTTP_PSEUDO_PATH); + if(v) { + uc = curl_url_set(u, CURLUPART_PATH, v, 0); + if(uc) { + rc = 3; + goto fail; + } + } + + /* We can only allow PUSH of resource from the same origin, e.g. + * scheme + hostname + port */ + if(!Curl_url_same_origin(data->state.uh, u)) { + rc = 1; + goto fail; + } + + uc = curl_url_get(u, CURLUPART_URL, &url, 0); + if(uc) + rc = 4; +fail: + curl_url_cleanup(u); + if(rc) + return rc; + + Curl_bufref_set(&newhandle->state.url, url, 0, curl_free); + return 0; +} + +static void discard_newhandle(struct Curl_cfilter *cf, + struct Curl_easy *newhandle) +{ + http2_data_done(cf, newhandle); + (void)Curl_close(&newhandle); +} + +static int push_promise(struct Curl_cfilter *cf, + struct Curl_easy *data, + const nghttp2_push_promise *frame) +{ + struct cf_h2_ctx *ctx = cf->ctx; + int rv; /* one of the CURL_PUSH_* defines */ + + CURL_TRC_CF(data, cf, "[%d] PUSH_PROMISE received", + frame->promised_stream_id); + if(data->multi->push_cb) { + struct h2_stream_ctx *stream; + struct h2_stream_ctx *newstream; + struct curl_pushheaders heads; + CURLMcode mresult; + CURLcode result; + /* clone the parent */ + struct Curl_easy *newhandle = h2_duphandle(cf, data); + if(!newhandle) { + infof(data, "failed to duplicate handle"); + rv = CURL_PUSH_DENY; /* FAIL HARD */ + goto fail; + } + + stream = H2_STREAM_CTX(ctx, data); + if(!stream) { + failf(data, "Internal NULL stream"); + discard_newhandle(cf, newhandle); + rv = CURL_PUSH_DENY; + goto fail; + } + + heads.data = data; + heads.stream = stream; + heads.frame = frame; + + rv = set_transfer_url(newhandle, &heads, data); + if(rv) { + CURL_TRC_CF(data, cf, "[%d] PUSH_PROMISE, failed to set URL -> %d", + frame->promised_stream_id, rv); + discard_newhandle(cf, newhandle); + rv = CURL_PUSH_DENY; + goto fail; + } + + { + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, multi_push_cb); + rv = data->multi->push_cb(data, newhandle, + stream->push_headers_used, &heads, + data->multi->push_userp); + CURL_CBAPI_END(&guard); + } + + /* free the headers again */ + free_push_headers(stream); + + if(rv) { + DEBUGASSERT((rv > CURL_PUSH_OK) && (rv <= CURL_PUSH_ERROROUT)); + /* denied, kill off the new handle again */ + CURL_TRC_CF(data, cf, "[%d] PUSH_PROMISE, denied by application -> %d", + frame->promised_stream_id, rv); + discard_newhandle(cf, newhandle); + goto fail; + } + + /* approved, add to the multi handle for processing. This + * assigns newhandle->mid. For the new `mid` we assign the + * h2_stream instance and remember the stream_id already known. */ + mresult = Curl_multi_add_perform(data->multi, newhandle, cf->conn); + if(mresult) { + infof(data, "failed to add handle to multi"); + discard_newhandle(cf, newhandle); + rv = CURL_PUSH_DENY; + goto fail; + } + + result = http2_data_setup(cf, newhandle, &newstream); + if(result) { + failf(data, "error setting up stream: %d", (int)result); + discard_newhandle(cf, newhandle); + rv = CURL_PUSH_DENY; + goto fail; + } + + DEBUGASSERT(newstream); + newstream->id = frame->promised_stream_id; + newhandle->req.maxdownload = -1; + newhandle->req.size = -1; + + CURL_TRC_CF(data, cf, "promise easy handle added to multi, mid=%u", + newhandle->mid); + rv = nghttp2_session_set_stream_user_data(ctx->h2, + newstream->id, + newhandle); + if(rv) { + infof(data, "failed to set user_data for stream %d", + newstream->id); + DEBUGASSERT(0); + discard_newhandle(cf, newhandle); + rv = CURL_PUSH_DENY; + goto fail; + } + + /* success, remember max stream id processed */ + if(newstream->id > ctx->local_max_sid) + ctx->local_max_sid = newstream->id; + } + else { + CURL_TRC_CF(data, cf, "Got PUSH_PROMISE, ignore it"); + rv = CURL_PUSH_DENY; + } +fail: + return rv; +} + +static void h2_xfer_write_resp_hd(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h2_stream_ctx *stream, + const char *buf, size_t blen, bool eos) +{ + /* If we already encountered an error, skip further writes */ + if(!stream->xfer_result) { + stream->xfer_result = Curl_xfer_write_resp_hd(data, buf, blen, eos); + if(!stream->xfer_result && !eos) + stream->xfer_result = cf_h2_update_local_win(cf, data, stream); + if(stream->xfer_result) + CURL_TRC_CF(data, cf, "[%d] error %d writing %zu bytes of headers", + stream->id, (int)stream->xfer_result, blen); + } +} + +static void h2_xfer_write_resp(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h2_stream_ctx *stream, + const char *buf, size_t blen, bool eos) +{ + /* If we already encountered an error, skip further writes */ + if(!stream->xfer_result) + stream->xfer_result = Curl_xfer_write_resp(data, buf, blen, eos); + /* If the transfer write is errored, we do not want any more data */ + if(stream->xfer_result) { + struct cf_h2_ctx *ctx = cf->ctx; + CURL_TRC_CF(data, cf, "[%d] error %d writing %zu bytes of data, " + "RST-ing stream", + stream->id, (int)stream->xfer_result, blen); + nghttp2_submit_rst_stream(ctx->h2, 0, stream->id, + (uint32_t)NGHTTP2_ERR_CALLBACK_FAILURE); + } + else if(!stream->write_paused && Curl_xfer_write_is_paused(data)) { + CURL_TRC_CF(data, cf, "[%d] stream output paused", stream->id); + stream->write_paused = TRUE; + } + else if(stream->write_paused && !Curl_xfer_write_is_paused(data)) { + CURL_TRC_CF(data, cf, "[%d] stream output unpaused", stream->id); + stream->write_paused = FALSE; + } + + if(!stream->xfer_result && !eos) + stream->xfer_result = cf_h2_update_local_win(cf, data, stream); +} + +static CURLcode on_stream_frame(struct Curl_cfilter *cf, + struct Curl_easy *data, + const nghttp2_frame *frame) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + int32_t stream_id = frame->hd.stream_id; + int rv; + + if(!stream) { + CURL_TRC_CF(data, cf, "[%d] No stream_ctx set", stream_id); + return CURLE_FAILED_INIT; + } + + switch(frame->hd.type) { + case NGHTTP2_DATA: + CURL_TRC_CF(data, cf, "[%d] DATA, window=%d/%d", + stream_id, + nghttp2_session_get_stream_effective_recv_data_length( + ctx->h2, stream->id), + nghttp2_session_get_stream_effective_local_window_size( + ctx->h2, stream->id)); + /* If !body started on this stream, then receiving DATA is illegal. */ + if(!stream->bodystarted) { + rv = nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE, + stream_id, NGHTTP2_PROTOCOL_ERROR); + + if(nghttp2_is_fatal(rv)) { + return CURLE_RECV_ERROR; + } + } + break; + case NGHTTP2_HEADERS: + if(stream->bodystarted) { + /* Only valid HEADERS after body started is trailer HEADERS. We + buffer them in on_header callback. */ + break; + } + + /* nghttp2 guarantees that :status is received, and we store it to + stream->status_code. Fuzzing has proven this can still be reached + without status code having been set. */ + if(stream->status_code == -1) + return CURLE_RECV_ERROR; + + /* Only final status code signals the end of header */ + if(stream->status_code / 100 != 1) + stream->bodystarted = TRUE; + else + stream->status_code = -1; + + h2_xfer_write_resp_hd(cf, data, stream, STRCONST("\r\n"), + (bool)stream->closed); + + if(stream->status_code / 100 != 1) { + stream->resp_hds_complete = TRUE; + } + Curl_multi_mark_dirty(data); + break; + case NGHTTP2_PUSH_PROMISE: + rv = push_promise(cf, data, &frame->push_promise); + if(rv) { /* deny! */ + DEBUGASSERT((rv > CURL_PUSH_OK) && (rv <= CURL_PUSH_ERROROUT)); + rv = nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE, + frame->push_promise.promised_stream_id, + NGHTTP2_CANCEL); + if(nghttp2_is_fatal(rv)) + return CURLE_SEND_ERROR; + else if(rv == CURL_PUSH_ERROROUT) { + CURL_TRC_CF(data, cf, "[%d] fail in PUSH_PROMISE received", + stream_id); + return CURLE_RECV_ERROR; + } + } + break; + case NGHTTP2_RST_STREAM: + if(frame->rst_stream.error_code) + stream->reset_by_server = TRUE; + Curl_multi_mark_dirty(data); + break; + case NGHTTP2_WINDOW_UPDATE: + if(CURL_REQ_WANT_SEND(data) && Curl_bufq_is_empty(&stream->sendbuf)) { + /* need more data, force processing of transfer */ + Curl_multi_mark_dirty(data); + } + else if(!Curl_bufq_is_empty(&stream->sendbuf)) { + /* resume the potentially suspended stream */ + rv = nghttp2_session_resume_data(ctx->h2, stream->id); + if(nghttp2_is_fatal(rv)) + return CURLE_SEND_ERROR; + } + break; + default: + break; + } + + if(frame->hd.flags & NGHTTP2_FLAG_END_STREAM) { + if(!stream->closed && !stream->body_eos && + ((stream->status_code >= 400) || (stream->status_code < 200))) { + /* The server did not give us a positive response and we are not + * done uploading the request body. We need to stop doing that and + * also inform the server that we aborted our side. */ + CURL_TRC_CF(data, cf, "[%d] EOS frame with unfinished upload and " + "HTTP status %d, abort upload by RST", + stream_id, stream->status_code); + nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE, + stream->id, NGHTTP2_STREAM_CLOSED); + stream->closed = TRUE; + } + Curl_multi_mark_dirty(data); + } + return CURLE_OK; +} + +#ifdef CURLVERBOSE +int Curl_nghttp2_fr_print(const nghttp2_frame *frame, char *buffer, + size_t blen) +{ + switch(frame->hd.type) { + case NGHTTP2_DATA: { + return curl_msnprintf(buffer, blen, + "FRAME[DATA, len=%d, eos=%d, padlen=%d]", + (int)frame->hd.length, + !!(frame->hd.flags & NGHTTP2_FLAG_END_STREAM), + (int)frame->data.padlen); + } + case NGHTTP2_HEADERS: { + return curl_msnprintf(buffer, blen, + "FRAME[HEADERS, len=%d, hend=%d, eos=%d]", + (int)frame->hd.length, + !!(frame->hd.flags & NGHTTP2_FLAG_END_HEADERS), + !!(frame->hd.flags & NGHTTP2_FLAG_END_STREAM)); + } + case NGHTTP2_PRIORITY: { + return curl_msnprintf(buffer, blen, + "FRAME[PRIORITY, len=%d, flags=%d]", + (int)frame->hd.length, frame->hd.flags); + } + case NGHTTP2_RST_STREAM: { + return curl_msnprintf(buffer, blen, + "FRAME[RST_STREAM, len=%d, flags=%d, error=%u]", + (int)frame->hd.length, frame->hd.flags, + frame->rst_stream.error_code); + } + case NGHTTP2_SETTINGS: { + if(frame->hd.flags & NGHTTP2_FLAG_ACK) { + return curl_msnprintf(buffer, blen, "FRAME[SETTINGS, ack=1]"); + } + return curl_msnprintf(buffer, blen, + "FRAME[SETTINGS, len=%d]", (int)frame->hd.length); + } + case NGHTTP2_PUSH_PROMISE: + return curl_msnprintf(buffer, blen, + "FRAME[PUSH_PROMISE, len=%d, hend=%d]", + (int)frame->hd.length, + !!(frame->hd.flags & NGHTTP2_FLAG_END_HEADERS)); + case NGHTTP2_PING: + return curl_msnprintf(buffer, blen, + "FRAME[PING, len=%d, ack=%d]", + (int)frame->hd.length, + frame->hd.flags & NGHTTP2_FLAG_ACK); + case NGHTTP2_GOAWAY: { + char scratch[128]; + size_t s_len = CURL_ARRAYSIZE(scratch); + size_t len = (frame->goaway.opaque_data_len < s_len) ? + frame->goaway.opaque_data_len : s_len - 1; + if(len) + memcpy(scratch, frame->goaway.opaque_data, len); + scratch[len] = '\0'; + return curl_msnprintf(buffer, blen, + "FRAME[GOAWAY, error=%u, reason='%s', " + "last_stream=%d]", frame->goaway.error_code, + scratch, frame->goaway.last_stream_id); + } + case NGHTTP2_WINDOW_UPDATE: { + return curl_msnprintf(buffer, blen, + "FRAME[WINDOW_UPDATE, incr=%d]", + frame->window_update.window_size_increment); + } + default: + return curl_msnprintf(buffer, blen, "FRAME[%d, len=%d, flags=%d]", + frame->hd.type, (int)frame->hd.length, + frame->hd.flags); + } +} + +static int on_frame_send(nghttp2_session *session, const nghttp2_frame *frame, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + + (void)session; + DEBUGASSERT(data); + if(Curl_trc_cf_is_verbose(cf, data)) { + char buffer[256]; + int len; + len = Curl_nghttp2_fr_print(frame, buffer, sizeof(buffer) - 1); + buffer[len] = 0; + CURL_TRC_CF(data, cf, "[%d] -> %s", frame->hd.stream_id, buffer); + } + if((frame->hd.type == NGHTTP2_GOAWAY) && !ctx->sent_goaway) { + /* A GOAWAY not initiated by us, but by nghttp2 itself on detecting + * a protocol error on the connection */ + failf(data, "nghttp2 shuts down connection with error %u: %s", + frame->goaway.error_code, + nghttp2_http2_strerror(frame->goaway.error_code)); + } + return 0; +} +#endif /* CURLVERBOSE */ + +static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf), *data_s; + int32_t stream_id = frame->hd.stream_id; + + DEBUGASSERT(data); +#ifdef CURLVERBOSE + if(Curl_trc_cf_is_verbose(cf, data)) { + char buffer[256]; + int len; + len = Curl_nghttp2_fr_print(frame, buffer, sizeof(buffer) - 1); + buffer[len] = 0; + CURL_TRC_CF(data, cf, "[%d] <- %s", frame->hd.stream_id, buffer); + } +#endif /* CURLVERBOSE */ + + if(!stream_id) { + /* stream ID zero is for connection-oriented stuff */ + DEBUGASSERT(data); + switch(frame->hd.type) { + case NGHTTP2_SETTINGS: { + if(!(frame->hd.flags & NGHTTP2_FLAG_ACK)) { + uint32_t max_conn = ctx->max_concurrent_streams; + ctx->max_concurrent_streams = nghttp2_session_get_remote_settings( + session, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS); + ctx->enable_push = nghttp2_session_get_remote_settings( + session, NGHTTP2_SETTINGS_ENABLE_PUSH) != 0; + CURL_TRC_CF(data, cf, "[0] MAX_CONCURRENT_STREAMS: %u", + ctx->max_concurrent_streams); + CURL_TRC_CF(data, cf, "[0] ENABLE_PUSH: %s", + ctx->enable_push ? "TRUE" : "false"); + if(data && max_conn != ctx->max_concurrent_streams) { + /* only signal change if the value actually changed */ + CURL_TRC_CF(data, cf, "[0] notify MAX_CONCURRENT_STREAMS: %u", + ctx->max_concurrent_streams); + Curl_multi_connchanged(data->multi); + } + /* Since the initial stream window is 64K, a request might be on HOLD, + * due to exhaustion. The (initial) SETTINGS may announce a much larger + * window and *assume* that we treat this like a WINDOW_UPDATE. Some + * servers send an explicit WINDOW_UPDATE, but not all seem to do that. + * To be safe, we UNHOLD a stream in order not to stall. */ + if(CURL_REQ_WANT_SEND(data)) + Curl_multi_mark_dirty(data); + } + break; + } + case NGHTTP2_GOAWAY: + ctx->rcvd_goaway = TRUE; + ctx->goaway_error = frame->goaway.error_code; + ctx->remote_max_sid = frame->goaway.last_stream_id; + if(data) { + infof(data, "received GOAWAY, error=%u, last_stream=%d", + ctx->goaway_error, ctx->remote_max_sid); + Curl_multi_connchanged(data->multi); + } + break; + default: + break; + } + return 0; + } + + data_s = nghttp2_session_get_stream_user_data(session, stream_id); + if(!data_s) { + CURL_TRC_CF(data, cf, "[%d] No Curl_easy associated", stream_id); + return 0; + } + + return on_stream_frame(cf, data_s, frame) ? NGHTTP2_ERR_CALLBACK_FAILURE : 0; +} + +static int cf_h2_on_invalid_frame_recv(nghttp2_session *session, + const nghttp2_frame *frame, + int ngerr, void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct Curl_easy *data; + int32_t stream_id = frame->hd.stream_id; + + data = nghttp2_session_get_stream_user_data(session, stream_id); + if(data) { + struct h2_stream_ctx *stream; +#ifdef CURLVERBOSE + char buffer[256]; + int len; + len = Curl_nghttp2_fr_print(frame, buffer, sizeof(buffer) - 1); + buffer[len] = 0; + failf(data, "[HTTP2] [%d] received invalid frame: %s, error %d: %s", + stream_id, buffer, ngerr, nghttp2_strerror(ngerr)); +#endif /* CURLVERBOSE */ + stream = H2_STREAM_CTX(ctx, data); + if(stream) { + nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE, + stream->id, NGHTTP2_STREAM_CLOSED); + stream->error = ngerr; + stream->closed = TRUE; + stream->reset = TRUE; + return 0; /* keep the connection alive */ + } + } + return NGHTTP2_ERR_CALLBACK_FAILURE; +} + +static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags, + int32_t stream_id, + const uint8_t *mem, size_t len, void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream; + struct Curl_easy *data_s; + (void)flags; + + DEBUGASSERT(stream_id); /* should never be a zero stream ID here */ + DEBUGASSERT(CF_DATA_CURRENT(cf)); + + /* get the stream from the hash based on Stream ID */ + data_s = nghttp2_session_get_stream_user_data(session, stream_id); + if(!data_s) { + /* Receiving a Stream ID not in the hash should not happen - unless + we have aborted a transfer artificially and there were more data + in the pipeline. Silently ignore. */ + CURL_TRC_CF(CF_DATA_CURRENT(cf), cf, "[%d] Data for unknown", stream_id); + /* consumed explicitly as no one will read it */ + nghttp2_session_consume(session, stream_id, len); + return 0; + } + + stream = H2_STREAM_CTX(ctx, data_s); + if(!stream) + return NGHTTP2_ERR_CALLBACK_FAILURE; + + h2_xfer_write_resp(cf, data_s, stream, (const char *)mem, len, FALSE); + + nghttp2_session_consume(ctx->h2, stream_id, len); + stream->nrcvd_data += (curl_off_t)len; + return 0; +} + +static int on_stream_close(nghttp2_session *session, int32_t stream_id, + uint32_t error_code, void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct Curl_easy *data_s, *call_data = CF_DATA_CURRENT(cf); + struct h2_stream_ctx *stream; + int rv; + (void)session; + + DEBUGASSERT(call_data); + /* stream id 0 is the connection, do not look there for streams. */ + data_s = stream_id ? + nghttp2_session_get_stream_user_data(session, stream_id) : NULL; + if(!data_s) { + CURL_TRC_CF(call_data, cf, + "[%d] on_stream_close, no easy set on stream", stream_id); + return 0; + } + if(!GOOD_EASY_HANDLE(data_s)) { + /* nghttp2 still has an easy registered for the stream which has + * been freed be libcurl. This points to a code path that does not + * trigger DONE or DETACH events as it must. */ + CURL_TRC_CF(call_data, cf, + "[%d] on_stream_close, not a GOOD easy on stream", stream_id); + (void)nghttp2_session_set_stream_user_data(session, stream_id, 0); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + stream = H2_STREAM_CTX(ctx, data_s); + if(!stream) { + CURL_TRC_CF(data_s, cf, + "[%d] on_stream_close, GOOD easy but no stream", stream_id); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + + stream->closed = TRUE; + stream->error = error_code; + if(stream->error) + stream->reset = TRUE; + + if(stream->error) + CURL_TRC_CF(data_s, cf, "[%d] RESET: %s (err %u)", + stream_id, nghttp2_http2_strerror(error_code), error_code); + else + CURL_TRC_CF(data_s, cf, "[%d] CLOSED", stream_id); + Curl_multi_mark_dirty(data_s); + + /* remove `data_s` from the nghttp2 stream */ + rv = nghttp2_session_set_stream_user_data(session, stream_id, 0); + if(rv) { + infof(data_s, "http/2: failed to clear user_data for stream %d", + stream_id); + DEBUGASSERT(0); + } + return 0; +} + +static int on_begin_headers(nghttp2_session *session, + const nghttp2_frame *frame, void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream; + struct Curl_easy *data_s = NULL; + + (void)cf; + data_s = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id); + if(!data_s) { + return 0; + } + + if(frame->hd.type != NGHTTP2_HEADERS) { + return 0; + } + + stream = H2_STREAM_CTX(ctx, data_s); + if(!stream || !stream->bodystarted) { + return 0; + } + + return 0; +} + +static void cf_h2_header_error(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h2_stream_ctx *stream, + CURLcode result) +{ + struct cf_h2_ctx *ctx = cf->ctx; + + failf(data, "Error receiving HTTP2 header: %d(%s)", (int)result, + curl_easy_strerror(result)); + if(stream) { + nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE, + stream->id, NGHTTP2_STREAM_CLOSED); + stream->closed = TRUE; + stream->reset = TRUE; + } +} + +/* frame->hd.type is either NGHTTP2_HEADERS or NGHTTP2_PUSH_PROMISE */ +static int on_header(nghttp2_session *session, const nghttp2_frame *frame, + const uint8_t *name, size_t namelen, + const uint8_t *value, size_t valuelen, + uint8_t flags, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream; + struct Curl_easy *data; + int32_t stream_id = frame->hd.stream_id; + CURLcode result; + (void)flags; + + DEBUGASSERT(stream_id); /* should never be a zero stream ID here */ + + /* get the stream from the hash based on Stream ID */ + data = nghttp2_session_get_stream_user_data(session, stream_id); + if(!GOOD_EASY_HANDLE(data)) + /* Receiving a Stream ID not in the hash should not happen, this is an + internal error more than anything else! */ + return NGHTTP2_ERR_CALLBACK_FAILURE; + + stream = H2_STREAM_CTX(ctx, data); + if(!stream) { + failf(data, "Internal NULL stream"); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + + /* Store received PUSH_PROMISE headers to be used when the subsequent + PUSH_PROMISE callback comes */ + if(frame->hd.type == NGHTTP2_PUSH_PROMISE) { + char *h; + + if((namelen == CURL_CSTRLEN(HTTP_PSEUDO_AUTHORITY)) && + !strncmp(HTTP_PSEUDO_AUTHORITY, (const char *)name, namelen)) { + /* pseudo headers are lower case */ + int rc = 0; + char *check = curl_maprintf("%s:%d", data->state.origin->hostname, + data->state.origin->port); + if(!check) + /* no memory */ + return NGHTTP2_ERR_CALLBACK_FAILURE; + if(!curl_strequal(check, (const char *)value) && + ((data->state.origin->port != cf->conn->given->defport) || + !curl_strequal(data->state.origin->hostname, (const char *)value))) { + /* This is push is not for the same authority that was asked for in + * the URL. RFC 7540 section 8.2 says: "A client MUST treat a + * PUSH_PROMISE for which the server is not authoritative as a stream + * error of type PROTOCOL_ERROR." + */ + (void)nghttp2_submit_rst_stream(session, NGHTTP2_FLAG_NONE, + stream_id, NGHTTP2_PROTOCOL_ERROR); + rc = NGHTTP2_ERR_CALLBACK_FAILURE; + } + curlx_free(check); + if(rc) + return rc; + } + + if(!stream->push_headers) { + stream->push_headers_alloc = 10; + stream->push_headers = curlx_malloc(stream->push_headers_alloc * + sizeof(char *)); + if(!stream->push_headers) + return NGHTTP2_ERR_CALLBACK_FAILURE; + stream->push_headers_used = 0; + } + else if(stream->push_headers_used == + stream->push_headers_alloc) { + char **headp; + if(stream->push_headers_alloc > 1000) { + /* this is beyond crazy many headers, bail out */ + failf(data, "Too many PUSH_PROMISE headers"); + free_push_headers(stream); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + stream->push_headers_alloc *= 2; + headp = curlx_realloc(stream->push_headers, + stream->push_headers_alloc * sizeof(char *)); + if(!headp) { + free_push_headers(stream); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + stream->push_headers = headp; + } + h = curl_maprintf("%s:%s", name, value); + if(!h) { + free_push_headers(stream); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + stream->push_headers[stream->push_headers_used++] = h; + return 0; + } + + if(stream->bodystarted) { + /* This is a trailer */ + CURL_TRC_CF(data, cf, "[%d] trailer: %.*s: %.*s", + stream->id, (int)namelen, name, (int)valuelen, value); + result = Curl_dynhds_add(&stream->resp_trailers, + (const char *)name, namelen, + (const char *)value, valuelen); + if(result) { + cf_h2_header_error(cf, data, stream, result); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + + return 0; + } + + if(namelen == CURL_CSTRLEN(HTTP_PSEUDO_STATUS) && + !memcmp(HTTP_PSEUDO_STATUS, name, namelen)) { + /* nghttp2 guarantees :status is received first and only once. */ + char buffer[32]; + size_t hlen; + result = Curl_http_decode_status(&stream->status_code, + (const char *)value, valuelen); + if(result) { + cf_h2_header_error(cf, data, stream, result); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + hlen = curl_msnprintf(buffer, sizeof(buffer), HTTP_PSEUDO_STATUS ":%d\r", + stream->status_code); + result = Curl_headers_push(data, buffer, hlen, CURLH_PSEUDO); + if(result) { + cf_h2_header_error(cf, data, stream, result); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + curlx_dyn_reset(&ctx->scratch); + result = curlx_dyn_addn(&ctx->scratch, STRCONST("HTTP/2 ")); + if(!result) + result = curlx_dyn_addn(&ctx->scratch, value, valuelen); + if(!result) + result = curlx_dyn_addn(&ctx->scratch, STRCONST(" \r\n")); + if(!result) + h2_xfer_write_resp_hd(cf, data, stream, curlx_dyn_ptr(&ctx->scratch), + curlx_dyn_len(&ctx->scratch), FALSE); + if(result) { + cf_h2_header_error(cf, data, stream, result); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + /* if we receive data for another handle, wake that up */ + if(CF_DATA_CURRENT(cf) != data) + Curl_multi_mark_dirty(data); + + CURL_TRC_CF(data, cf, "[%d] status: HTTP/2 %03d", + stream->id, stream->status_code); + return 0; + } + + /* nghttp2 guarantees that namelen > 0, and :status was already + received, and this is not pseudo-header field . */ + /* convert to an HTTP1-style header */ + curlx_dyn_reset(&ctx->scratch); + result = curlx_dyn_addn(&ctx->scratch, (const char *)name, namelen); + if(!result) + result = curlx_dyn_addn(&ctx->scratch, STRCONST(": ")); + if(!result) + result = curlx_dyn_addn(&ctx->scratch, (const char *)value, valuelen); + if(!result) + result = curlx_dyn_addn(&ctx->scratch, STRCONST("\r\n")); + if(!result) + h2_xfer_write_resp_hd(cf, data, stream, curlx_dyn_ptr(&ctx->scratch), + curlx_dyn_len(&ctx->scratch), FALSE); + if(result) { + cf_h2_header_error(cf, data, stream, result); + return NGHTTP2_ERR_CALLBACK_FAILURE; + } + /* if we receive data for another handle, wake that up */ + if(CF_DATA_CURRENT(cf) != data) + Curl_multi_mark_dirty(data); + + CURL_TRC_CF(data, cf, "[%d] header: %.*s: %.*s", + stream->id, (int)namelen, name, (int)valuelen, value); + + return 0; /* 0 is successful */ +} + +static ssize_t req_body_read_callback(nghttp2_session *session, + int32_t stream_id, + uint8_t *buf, size_t length, + uint32_t *data_flags, + nghttp2_data_source *source, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct cf_h2_ctx *ctx = cf->ctx; + struct Curl_easy *data_s; + struct h2_stream_ctx *stream = NULL; + CURLcode result; + ssize_t nread; + size_t n; + (void)source; + + (void)cf; + if(!stream_id) + return NGHTTP2_ERR_INVALID_ARGUMENT; + + /* get the stream from the hash based on Stream ID, stream ID zero is for + connection-oriented stuff */ + data_s = nghttp2_session_get_stream_user_data(session, stream_id); + if(!data_s) + /* Receiving a Stream ID not in the hash should not happen, this is an + internal error more than anything else! */ + return NGHTTP2_ERR_CALLBACK_FAILURE; + + stream = H2_STREAM_CTX(ctx, data_s); + if(!stream) + return NGHTTP2_ERR_CALLBACK_FAILURE; + + result = Curl_bufq_read(&stream->sendbuf, buf, length, &n); + if(result) { + if(result != CURLE_AGAIN) + return NGHTTP2_ERR_CALLBACK_FAILURE; + nread = 0; + } + else + nread = (ssize_t)n; + + CURL_TRC_CF(data_s, cf, "[%d] req_body_read(len=%zu) eos=%d -> %zd, %d", + stream_id, length, stream->body_eos, nread, (int)result); + + if(stream->body_eos && Curl_bufq_is_empty(&stream->sendbuf)) { + *data_flags = NGHTTP2_DATA_FLAG_EOF; + return nread; + } + return (nread == 0) ? NGHTTP2_ERR_DEFERRED : nread; +} + +#ifdef CURLVERBOSE +static int error_callback(nghttp2_session *session, + const char *msg, + size_t len, + void *userp) +{ + struct Curl_cfilter *cf = userp; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + (void)session; + failf(data, "%.*s", (int)len, msg); + return 0; +} +#endif + +/* + * Append headers to ask for an HTTP1.1 to HTTP2 upgrade. + */ +CURLcode Curl_http2_request_upgrade(struct dynbuf *req, + struct Curl_easy *data) +{ + CURLcode result; + char *base64; + size_t blen; + struct SingleRequest *k = &data->req; + uint8_t binsettings[H2_BINSETTINGS_LEN]; + ssize_t rc; + size_t binlen; /* length of the binsettings data */ + + rc = populate_binsettings(binsettings, data); + if(!curlx_sztouz(rc, &binlen) || !binlen) { + failf(data, "nghttp2 unexpectedly failed on pack_settings_payload"); + curlx_dyn_free(req); + return CURLE_FAILED_INIT; + } + + result = curlx_base64url_encode(binsettings, binlen, &base64, &blen); + if(result) { + curlx_dyn_free(req); + return result; + } + + data->state.http_hd_upgrade = TRUE; + data->state.http_hd_h2_settings = TRUE; + result = curlx_dyn_addf(req, + "Upgrade: %s\r\n" + "HTTP2-Settings: %s\r\n", + NGHTTP2_CLEARTEXT_PROTO_VERSION_ID, base64); + curlx_free(base64); + + k->upgr101 = UPGR101_H2; + data->conn->bits.upgrade_in_progress = TRUE; + + return result; +} + +static CURLcode http2_handle_stream_close(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h2_stream_ctx *stream, + size_t *pnlen) +{ + CURLcode result; + + *pnlen = 0; + if(stream->reset) { + if(stream->error == NGHTTP2_REFUSED_STREAM) { + infof(data, "HTTP/2 stream %d refused by server, try again on a new " + "connection", stream->id); + connclose(cf->conn); /* do not use this anymore */ + data->state.refused_stream = TRUE; + return CURLE_RECV_ERROR; /* trigger Curl_retry_request() later */ + } + else if(stream->resp_hds_complete && data->req.no_body) { + CURL_TRC_CF(data, cf, "[%d] error after response headers, but we did " + "not want a body anyway, ignore: %s (err %u)", + stream->id, nghttp2_http2_strerror(stream->error), + stream->error); + stream->close_handled = TRUE; + return CURLE_OK; + } + failf(data, "HTTP/2 stream %d reset by %s (error 0x%x %s)", + stream->id, stream->reset_by_server ? "server" : "curl", + stream->error, nghttp2_http2_strerror(stream->error)); + return stream->error ? CURLE_HTTP2_STREAM : + (data->req.bytecount ? CURLE_PARTIAL_FILE : CURLE_HTTP2); + } + else if(!stream->bodystarted) { + failf(data, "HTTP/2 stream %d was closed cleanly, but before getting " + "all response header fields, treated as error", stream->id); + return CURLE_HTTP2_STREAM; + } + + if(Curl_dynhds_count(&stream->resp_trailers)) { + struct dynhds_entry *e; + struct dynbuf dbuf; + size_t i; + + result = CURLE_OK; + curlx_dyn_init(&dbuf, DYN_TRAILERS); + for(i = 0; i < Curl_dynhds_count(&stream->resp_trailers); ++i) { + e = Curl_dynhds_getn(&stream->resp_trailers, i); + if(!e) + break; + curlx_dyn_reset(&dbuf); + result = curlx_dyn_addf(&dbuf, "%.*s: %.*s\x0d\x0a", + (int)e->namelen, e->name, + (int)e->valuelen, e->value); + if(result) + break; + Curl_debug(data, CURLINFO_HEADER_IN, curlx_dyn_ptr(&dbuf), + curlx_dyn_len(&dbuf)); + result = Curl_client_write(data, + CLIENTWRITE_HEADER | CLIENTWRITE_TRAILER, + curlx_dyn_ptr(&dbuf), curlx_dyn_len(&dbuf)); + if(result) + break; + } + curlx_dyn_free(&dbuf); + if(result) + goto out; + } + + stream->close_handled = TRUE; + result = CURLE_OK; + +out: + CURL_TRC_CF(data, cf, "handle_stream_close -> %d, %zu", (int)result, *pnlen); + return result; +} + +static int sweight_wanted(const struct Curl_easy *data) +{ + /* 0 weight is not set by user and we take the nghttp2 default one */ + return data->set.weight ? + data->set.weight : NGHTTP2_DEFAULT_WEIGHT; +} + +static int sweight_in_effect(const struct Curl_easy *data) +{ + /* 0 weight is not set by user and we take the nghttp2 default one */ + return data->state.weight ? + data->state.weight : NGHTTP2_DEFAULT_WEIGHT; +} + +/* + * h2_pri_spec() fills in the pri_spec struct, used by nghttp2 to send weight + * and dependency to the peer. It also stores the updated values in the state + * struct. + */ + +static void h2_pri_spec(struct Curl_easy *data, + nghttp2_priority_spec *pri_spec) +{ + int prio = data->set.weight; + nghttp2_priority_spec_init(pri_spec, 0, sweight_wanted(data), FALSE); + data->state.weight = prio; +} + +/* + * Check if there is been an update in the priority / + * dependency settings and if so it submits a PRIORITY frame with the updated + * info. + * Flush any out data pending in the network buffer. + */ +static CURLcode h2_progress_egress(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + int rv = 0; + + if(stream && stream->id > 0 && + (sweight_wanted(data) != sweight_in_effect(data))) { + /* send new weight and/or dependency */ + nghttp2_priority_spec pri_spec; + + h2_pri_spec(data, &pri_spec); + CURL_TRC_CF(data, cf, "[%d] Queuing PRIORITY", stream->id); + DEBUGASSERT(stream->id != -1); + rv = nghttp2_submit_priority(ctx->h2, NGHTTP2_FLAG_NONE, + stream->id, &pri_spec); + if(rv) + goto out; + } + + ctx->nw_out_blocked = 0; + while(!rv && !ctx->nw_out_blocked && nghttp2_session_want_write(ctx->h2)) + rv = nghttp2_session_send(ctx->h2); + +out: + if(nghttp2_is_fatal(rv)) { + CURL_TRC_CF(data, cf, "nghttp2_session_send error (%s)%d", + nghttp2_strerror(rv), rv); + return CURLE_SEND_ERROR; + } + /* Defer flushing during the connect phase so that the SETTINGS and + * other initial frames are sent together with the first request. + * Unless we are 'connect_only' where the request will never come. */ + if(!cf->connected && !cf->conn->bits.connect_only) + return CURLE_OK; + return nw_out_flush(cf, data); +} + +static CURLcode stream_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + struct h2_stream_ctx *stream, + char *buf, size_t len, size_t *pnread) +{ + struct cf_h2_ctx *ctx = cf->ctx; + CURLcode result = CURLE_AGAIN; + + (void)buf; + (void)len; + *pnread = 0; + + if(!stream->xfer_result) + stream->xfer_result = cf_h2_update_local_win(cf, data, stream); + + if(stream->xfer_result) { + CURL_TRC_CF(data, cf, "[%d] xfer write failed", stream->id); + result = stream->xfer_result; + } + else if(stream->closed) { + CURL_TRC_CF(data, cf, "[%d] returning CLOSE", stream->id); + result = http2_handle_stream_close(cf, data, stream, pnread); + } + else if(stream->reset || + (ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) || + (ctx->rcvd_goaway && ctx->remote_max_sid < stream->id)) { + CURL_TRC_CF(data, cf, "[%d] returning ERR", stream->id); + result = data->req.bytecount ? CURLE_PARTIAL_FILE : CURLE_HTTP2; + } + + if(result && (result != CURLE_AGAIN)) + CURL_TRC_CF(data, cf, "[%d] stream_recv(len=%zu) -> %d, %zu", + stream->id, len, (int)result, *pnread); + return result; +} + +static CURLcode h2_progress_ingress(struct Curl_cfilter *cf, + struct Curl_easy *data, + size_t data_max_bytes) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream; + CURLcode result = CURLE_OK; + size_t nread; + + if(should_close_session(ctx)) { + CURL_TRC_CF(data, cf, "[0] ingress: session is closed"); + return CURLE_HTTP2; + } + + /* Process network input buffer first */ + if(!Curl_bufq_is_empty(&ctx->inbufq)) { + CURL_TRC_CF(data, cf, "Process %zu bytes in connection buffer", + Curl_bufq_len(&ctx->inbufq)); + result = h2_process_pending_input(cf, data); + if(result) + return result; + } + + if(!data_max_bytes) + data_max_bytes = H2_CHUNK_SIZE; + + /* Receive data from the "lower" filters, e.g. network until + * it is time to stop due to connection close or us not processing + * all network input */ + while(!ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) { + stream = H2_STREAM_CTX(ctx, data); + if(stream && (stream->closed || !data_max_bytes)) { + /* We would like to abort here and stop processing, so that the transfer + * loop can handle the data/close here. This may leave data in + * underlying buffers that will not be consumed. */ + if(!cf->next || !cf->next->cft->has_data_pending(cf->next, data)) + Curl_multi_mark_dirty(data); + break; + } + + result = Curl_cf_recv_bufq(cf->next, data, &ctx->inbufq, 0, &nread); + if(result) { + if(result != CURLE_AGAIN) { + failf(data, "Failed receiving HTTP2 data: %d(%s)", (int)result, + curl_easy_strerror(result)); + return result; + } + break; + } + else if(nread == 0) { + CURL_TRC_CF(data, cf, "[0] ingress: connection closed"); + ctx->conn_closed = TRUE; + break; + } + else { + CURL_TRC_CF(data, cf, "[0] ingress: read %zu bytes", nread); + data_max_bytes = (data_max_bytes > nread) ? (data_max_bytes - nread) : 0; + } + + result = h2_process_pending_input(cf, data); + if(result) + return result; + CURL_TRC_CF(data, cf, "[0] ingress: nw-in buffered %zu", + Curl_bufq_len(&ctx->inbufq)); + } + + if(ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) { + CURL_TRC_CF(data, cf, "server closed %s", + ctx->rcvd_goaway ? "with GOAWAY" : "abruptly"); + connclose(cf->conn); + } + + CURL_TRC_CF(data, cf, "[0] ingress: done"); + return CURLE_OK; +} + +static CURLcode cf_h2_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, size_t *pnread) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream; + CURLcode result, r2; + struct cf_call_data save; + + if(!data) + return CURLE_HTTP2; + + stream = H2_STREAM_CTX(ctx, data); + + *pnread = 0; + if(!stream) { + /* Abnormal call sequence: either this transfer has never opened a stream + * (unlikely) or the transfer has been done, cleaned up its resources, but + * a read() is called anyway. It is not clear what the calling sequence + * is for such a case. */ + failf(data, "http/2 recv on a transfer never opened " + "or already cleared, mid=%u", data->mid); + return CURLE_HTTP2; + } + + CF_DATA_SAVE(save, cf, data); + + result = stream_recv(cf, data, stream, buf, len, pnread); + if(result && (result != CURLE_AGAIN)) + goto out; + + if(result) { + result = h2_progress_ingress(cf, data, len); + if(result) + goto out; + + result = stream_recv(cf, data, stream, buf, len, pnread); + } + + if(*pnread > 0) { + /* Now that we transferred this to the upper layer, we report + * the actual amount of DATA consumed to the H2 session, so + * that it adjusts stream flow control */ + nghttp2_session_consume(ctx->h2, stream->id, *pnread); + if(stream->closed) { + CURL_TRC_CF(data, cf, "[%d] DRAIN closed stream", stream->id); + Curl_multi_mark_dirty(data); + } + } + +out: + r2 = h2_progress_egress(cf, data); + if(r2 == CURLE_AGAIN) { + /* pending data to send, need to be called again. Ideally, we + * monitor the socket for POLLOUT, but when not SENDING + * any more, we force processing of the transfer. */ + if(!CURL_REQ_WANT_SEND(data)) + Curl_multi_mark_dirty(data); + } + else if(r2) { + result = r2; + } + CURL_TRC_CF(data, cf, "[%d] cf_recv(len=%zu) -> %d, %zu, " + "window=%d/%d, connection %d/%d", + stream->id, len, (int)result, *pnread, + nghttp2_session_get_stream_effective_recv_data_length( + ctx->h2, stream->id), + nghttp2_session_get_stream_effective_local_window_size( + ctx->h2, stream->id), + nghttp2_session_get_local_window_size(ctx->h2), + HTTP2_HUGE_WINDOW_SIZE); + + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode cf_h2_body_send(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h2_stream_ctx *stream, + const void *buf, size_t blen, bool eos, + size_t *pnwritten) +{ + struct cf_h2_ctx *ctx = cf->ctx; + CURLcode result; + + *pnwritten = 0; + if(stream->closed) { + if(stream->resp_hds_complete) { + /* Server decided to close the stream after having sent us a final + * response. This is valid if it is not interested in the request + * body. This happens on 30x or 40x responses. + * We silently discard the data sent, since this is not a transport + * error situation. */ + CURL_TRC_CF(data, cf, "[%d] discarding data" + "on closed stream with response", stream->id); + if(eos) + stream->body_eos = TRUE; + *pnwritten = blen; + return CURLE_OK; + } + /* Server closed before we got a response, this is an error */ + infof(data, "stream %d closed", stream->id); + return CURLE_SEND_ERROR; + } + + result = Curl_bufq_write(&stream->sendbuf, buf, blen, pnwritten); + if(result) + return result; + + if(eos && (blen == *pnwritten)) + stream->body_eos = TRUE; + + if(eos || !Curl_bufq_is_empty(&stream->sendbuf)) { + /* resume the potentially suspended stream */ + int rv = nghttp2_session_resume_data(ctx->h2, stream->id); + if(nghttp2_is_fatal(rv)) + return CURLE_SEND_ERROR; + } + + return CURLE_OK; +} + +static CURLcode h2_submit(struct h2_stream_ctx **pstream, + struct Curl_cfilter *cf, struct Curl_easy *data, + const uint8_t *buf, size_t len, + bool eos, size_t *pnwritten) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = NULL; + struct dynhds h2_headers; + nghttp2_nv *nva = NULL; + const void *body = NULL; + size_t nheader, bodylen; + nghttp2_data_provider data_prd; + int32_t stream_id; + nghttp2_priority_spec pri_spec; + size_t nwritten; + CURLcode result = CURLE_OK; + uint32_t initial_win_size; + + *pnwritten = 0; + Curl_dynhds_init(&h2_headers, 0, DYN_HTTP_REQUEST); + + result = http2_data_setup(cf, data, &stream); + if(result) + goto out; + + result = Curl_h1_req_parse_read( + &stream->h1, buf, len, NULL, + !data->state.http_ignorecustom ? + CURL_EASY_STR(data, STRING_CUSTOMREQUEST) : NULL, + 0, &nwritten); + if(result) + goto out; + *pnwritten = nwritten; + if(!stream->h1.done) { + /* need more data */ + goto out; + } + DEBUGASSERT(stream->h1.req); + + result = Curl_http_req_to_h2(&h2_headers, stream->h1.req, data); + if(result) + goto out; + /* no longer needed */ + Curl_h1_req_parse_free(&stream->h1); + + nva = Curl_dynhds_to_nva(&h2_headers, &nheader); + if(!nva) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + h2_pri_spec(data, &pri_spec); + if(!nghttp2_session_check_request_allowed(ctx->h2)) + CURL_TRC_CF(data, cf, "send request NOT allowed (via nghttp2)"); + + /* Check the initial windows size of the transfer (rate-limits?) and + * send an updated settings on changes from previous value. */ + initial_win_size = cf_h2_initial_win_size(data); + if(initial_win_size != ctx->initial_win_size) { + result = cf_h2_update_settings(ctx, initial_win_size); + if(result) + goto out; + } + + switch(data->state.httpreq) { + case HTTPREQ_POST: + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + case HTTPREQ_PUT: + data_prd.read_callback = req_body_read_callback; + data_prd.source.ptr = NULL; + stream_id = nghttp2_submit_request(ctx->h2, &pri_spec, nva, nheader, + &data_prd, data); + break; + default: + stream_id = nghttp2_submit_request(ctx->h2, &pri_spec, nva, nheader, + NULL, data); + } + + if(stream_id < 0) { + CURL_TRC_CF(data, cf, "send: nghttp2_submit_request error (%s)%d", + nghttp2_strerror(stream_id), stream_id); + result = CURLE_SEND_ERROR; + goto out; + } + +#ifdef CURLVERBOSE +#define MAX_ACC 60000 /* <64KB to account for some overhead */ + if(Curl_trc_is_verbose(data)) { + size_t acc = 0, i; + + infof(data, "[HTTP/2] [%d] OPENED stream for %s", + stream_id, Curl_bufref_ptr(&data->state.url)); + for(i = 0; i < nheader; ++i) { + acc += nva[i].namelen + nva[i].valuelen; + + infof(data, "[HTTP/2] [%d] [%.*s: %.*s]", stream_id, + (int)nva[i].namelen, nva[i].name, + (int)nva[i].valuelen, nva[i].value); + } + + if(acc > MAX_ACC) { + infof(data, "[HTTP/2] Warning: The cumulative length of all " + "headers exceeds %d bytes and that could cause the " + "stream to be rejected.", MAX_ACC); + } + } +#endif + + stream->id = stream_id; + + body = (const char *)buf + *pnwritten; + bodylen = len - *pnwritten; + + if(bodylen || eos) { + size_t n; + result = cf_h2_body_send(cf, data, stream, body, bodylen, eos, &n); + if(!result) + *pnwritten += n; + else if(result == CURLE_AGAIN) + result = CURLE_OK; + else { + result = CURLE_SEND_ERROR; + } + } + +out: + CURL_TRC_CF(data, cf, "[%d] submit -> %d, %zu", + stream ? stream->id : -1, (int)result, *pnwritten); + curlx_safefree(nva); + *pstream = stream; + Curl_dynhds_free(&h2_headers); + return result; +} + +static CURLcode cf_h2_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const uint8_t *buf, size_t len, bool eos, + size_t *pnwritten) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + struct cf_call_data save; + CURLcode result = CURLE_OK, r2; + + CF_DATA_SAVE(save, cf, data); + *pnwritten = 0; + + if(!stream || stream->id == -1) { + result = h2_submit(&stream, cf, data, buf, len, eos, pnwritten); + if(result) + goto out; + DEBUGASSERT(stream); + } + else if(stream->body_eos) { + /* We already wrote this, but CURLE_AGAIN-ed the call due to not + * being able to flush stream->sendbuf. Make a 0-length write + * to trigger flushing again. + * If this works, we report to have written `len` bytes. */ + size_t n; + DEBUGASSERT(eos); + result = cf_h2_body_send(cf, data, stream, buf, 0, eos, &n); + CURL_TRC_CF(data, cf, "[%d] cf_body_send last CHUNK -> %d, %zu, eos=%d", + stream->id, (int)result, n, eos); + if(result) + goto out; + *pnwritten = len; + } + else { + result = cf_h2_body_send(cf, data, stream, buf, len, eos, pnwritten); + CURL_TRC_CF(data, cf, "[%d] cf_body_send(len=%zu) -> %d, %zu, eos=%d", + stream->id, len, (int)result, *pnwritten, eos); + } + + /* Call the nghttp2 send loop and flush to write ALL buffered data, + * headers and/or request body completely out to the network */ + r2 = h2_progress_egress(cf, data); + + /* if the stream has been closed in egress handling (nghttp2 does that + * when it does not like the headers, for example */ + if(stream && stream->closed) { + infof(data, "stream %d closed", stream->id); + result = CURLE_SEND_ERROR; + goto out; + } + else if(r2 && (r2 != CURLE_AGAIN)) { + result = r2; + goto out; + } + + if(should_close_session(ctx)) { + /* nghttp2 thinks this session is done. If the stream has not been + * closed, this is an error state for out transfer */ + if(stream && stream->closed) { + result = http2_handle_stream_close(cf, data, stream, pnwritten); + } + else { + CURL_TRC_CF(data, cf, "send: nothing to do in this session"); + result = CURLE_HTTP2; + } + } + +out: + if(stream) { + CURL_TRC_CF(data, cf, "[%d] cf_send(len=%zu) -> %d, %zu, " + "eos=%d, h2 windows %d-%d (stream-conn), " + "buffers %zu-%zu (stream-conn)", + stream->id, len, (int)result, *pnwritten, + stream->body_eos, + nghttp2_session_get_stream_remote_window_size( + ctx->h2, stream->id), + nghttp2_session_get_remote_window_size(ctx->h2), + Curl_bufq_len(&stream->sendbuf), + Curl_bufq_len(&ctx->outbufq)); + } + else { + CURL_TRC_CF(data, cf, "cf_send(len=%zu) -> %d, %zu, " + "connection-window=%d, nw_send_buffer(%zu)", + len, (int)result, *pnwritten, + nghttp2_session_get_remote_window_size(ctx->h2), + Curl_bufq_len(&ctx->outbufq)); + } + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode cf_h2_flush(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + struct cf_call_data save; + CURLcode result = CURLE_OK; + + CF_DATA_SAVE(save, cf, data); + if(stream && !Curl_bufq_is_empty(&stream->sendbuf)) { + /* resume the potentially suspended stream */ + int rv = nghttp2_session_resume_data(ctx->h2, stream->id); + if(nghttp2_is_fatal(rv)) { + result = CURLE_SEND_ERROR; + goto out; + } + } + + result = h2_progress_egress(cf, data); + +out: + if(stream) { + CURL_TRC_CF(data, cf, "[%d] flush -> %d, " + "h2 windows %d-%d (stream-conn), " + "buffers %zu-%zu (stream-conn)", + stream->id, (int)result, + nghttp2_session_get_stream_remote_window_size( + ctx->h2, stream->id), + nghttp2_session_get_remote_window_size(ctx->h2), + Curl_bufq_len(&stream->sendbuf), + Curl_bufq_len(&ctx->outbufq)); + } + else { + CURL_TRC_CF(data, cf, "flush -> %d, " + "connection-window=%d, nw_send_buffer(%zu)", + (int)result, nghttp2_session_get_remote_window_size(ctx->h2), + Curl_bufq_len(&ctx->outbufq)); + } + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode cf_h2_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct cf_call_data save; + curl_socket_t sock; + bool want_recv, want_send; + CURLcode result = CURLE_OK; + + if(!ctx->h2) + return CURLE_OK; + + sock = Curl_conn_cf_get_socket(cf, data); + Curl_pollset_check(data, ps, sock, &want_recv, &want_send); + if(want_recv || want_send) { + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + bool c_exhaust, s_exhaust; + + CF_DATA_SAVE(save, cf, data); + c_exhaust = want_send && !nghttp2_session_get_remote_window_size(ctx->h2); + s_exhaust = want_send && stream && stream->id >= 0 && + !nghttp2_session_get_stream_remote_window_size(ctx->h2, + stream->id); + want_recv = (want_recv || c_exhaust || s_exhaust); + want_send = (!s_exhaust && want_send) || + (!c_exhaust && nghttp2_session_want_write(ctx->h2)) || + !Curl_bufq_is_empty(&ctx->outbufq); + + result = Curl_pollset_set(data, ps, sock, want_recv, want_send); + CF_DATA_RESTORE(cf, save); + } + else if(ctx->sent_goaway && !cf->shutdown) { + /* shutdown in progress */ + CF_DATA_SAVE(save, cf, data); + want_send = nghttp2_session_want_write(ctx->h2) || + !Curl_bufq_is_empty(&ctx->outbufq); + want_recv = nghttp2_session_want_read(ctx->h2); + result = Curl_pollset_set(data, ps, sock, want_recv, want_send); + CF_DATA_RESTORE(cf, save); + } + return result; +} + +static CURLcode cf_h2_ctx_open(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream; + CURLcode result = CURLE_OUT_OF_MEMORY; + int rc; + nghttp2_session_callbacks *cbs = NULL; + + DEBUGASSERT(!ctx->h2); + DEBUGASSERT(ctx->initialized); + + rc = nghttp2_session_callbacks_new(&cbs); + if(rc) { + failf(data, "Could not initialize nghttp2 callbacks"); + goto out; + } + + nghttp2_session_callbacks_set_send_callback(cbs, send_callback); + nghttp2_session_callbacks_set_on_frame_recv_callback(cbs, on_frame_recv); + nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(cbs, + cf_h2_on_invalid_frame_recv); +#ifdef CURLVERBOSE + nghttp2_session_callbacks_set_on_frame_send_callback(cbs, on_frame_send); +#endif + nghttp2_session_callbacks_set_on_data_chunk_recv_callback( + cbs, on_data_chunk_recv); + nghttp2_session_callbacks_set_on_stream_close_callback(cbs, on_stream_close); + nghttp2_session_callbacks_set_on_begin_headers_callback( + cbs, on_begin_headers); + nghttp2_session_callbacks_set_on_header_callback(cbs, on_header); +#ifdef CURLVERBOSE + nghttp2_session_callbacks_set_error_callback(cbs, error_callback); +#endif + + /* The nghttp2 session is not yet setup, do it */ + rc = h2_client_new(cf, cbs); + if(rc) { + failf(data, "Could not initialize nghttp2"); + goto out; + } + ctx->max_concurrent_streams = data->multi ? + Curl_multi_max_concurrent_streams(data->multi) : + DEFAULT_MAX_CONCURRENT_STREAMS; + + if(ctx->via_h1_upgrade) { + /* HTTP/1.1 Upgrade issued. H2 Settings have already been submitted + * in the H1 request and we upgrade from there. This stream + * is opened implicitly as #1. */ + uint8_t binsettings[H2_BINSETTINGS_LEN]; + ssize_t rclen; + size_t binlen; /* length of the binsettings data */ + + rclen = populate_binsettings(binsettings, data); + + if(!curlx_sztouz(rclen, &binlen) || !binlen) { + failf(data, "nghttp2 unexpectedly failed on pack_settings_payload"); + result = CURLE_FAILED_INIT; + goto out; + } + + result = http2_data_setup(cf, data, &stream); + if(result) + goto out; + DEBUGASSERT(stream); + stream->id = 1; + /* queue SETTINGS frame (again) */ + rc = nghttp2_session_upgrade2(ctx->h2, binsettings, binlen, + data->state.httpreq == HTTPREQ_HEAD, + NULL); + if(rc) { + failf(data, "nghttp2_session_upgrade2() failed: %s(%d)", + nghttp2_strerror(rc), rc); + result = CURLE_HTTP2; + goto out; + } + + rc = nghttp2_session_set_stream_user_data(ctx->h2, stream->id, + data); + if(rc) { + infof(data, "http/2: failed to set user_data for stream %d", + stream->id); + DEBUGASSERT(0); + } + CURL_TRC_CF(data, cf, "created session via Upgrade"); + } + else { + nghttp2_settings_entry iv[H2_SETTINGS_IV_LEN]; + size_t ivlen; + + ivlen = populate_settings(iv, data, ctx); + rc = nghttp2_submit_settings(ctx->h2, NGHTTP2_FLAG_NONE, + iv, ivlen); + if(rc) { + failf(data, "nghttp2_submit_settings() failed: %s(%d)", + nghttp2_strerror(rc), rc); + result = CURLE_HTTP2; + goto out; + } + } + + rc = nghttp2_session_set_local_window_size(ctx->h2, NGHTTP2_FLAG_NONE, 0, + HTTP2_HUGE_WINDOW_SIZE); + if(rc) { + failf(data, "nghttp2_session_set_local_window_size() failed: %s(%d)", + nghttp2_strerror(rc), rc); + result = CURLE_HTTP2; + goto out; + } + + /* all set, traffic will be send on connect */ + result = CURLE_OK; + CURL_TRC_CF(data, cf, "[0] created h2 session%s", + ctx->via_h1_upgrade ? " (via h1 upgrade)" : ""); + +out: + if(cbs) + nghttp2_session_callbacks_del(cbs); + return result; +} + +static CURLcode cf_h2_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_h2_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + struct cf_call_data save; + bool first_time = FALSE; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* Connect the lower filters first */ + if(!cf->next->connected) { + result = Curl_conn_cf_connect(cf->next, data, done); + if(result || !*done) + return result; + } + + *done = FALSE; + + CF_DATA_SAVE(save, cf, data); + DEBUGASSERT(ctx->initialized); + if(!ctx->h2) { + result = cf_h2_ctx_open(cf, data); + if(result) + goto out; + first_time = TRUE; + } + + if(!first_time) { + result = h2_progress_ingress(cf, data, 0); + if(result) + goto out; + } + + /* Send out our SETTINGS and ACKs and such. If that blocks, we + * have it buffered and can count this filter as being connected */ + result = h2_progress_egress(cf, data); + if(result && (result != CURLE_AGAIN)) + goto out; + + *done = TRUE; + cf->connected = TRUE; + result = CURLE_OK; + +out: + CURL_TRC_CF(data, cf, "cf_connect() -> %d, %d, ", (int)result, *done); + CF_DATA_RESTORE(cf, save); + return result; +} + +static void cf_h2_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + + (void)data; + if(ctx) { + cf_h2_ctx_free(ctx); + cf->ctx = NULL; + } +} + +static CURLcode cf_h2_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct cf_call_data save; + CURLcode result; + int rv; + + if(!cf->connected || !ctx->h2 || cf->shutdown || ctx->conn_closed) { + *done = TRUE; + return CURLE_OK; + } + + CF_DATA_SAVE(save, cf, data); + + if(!ctx->sent_goaway) { + ctx->sent_goaway = TRUE; + rv = nghttp2_submit_goaway(ctx->h2, NGHTTP2_FLAG_NONE, + ctx->local_max_sid, 0, + (const uint8_t *)"shutdown", + sizeof("shutdown")); + if(rv) { + failf(data, "nghttp2_submit_goaway() failed: %s(%d)", + nghttp2_strerror(rv), rv); + result = CURLE_SEND_ERROR; + goto out; + } + } + /* GOAWAY submitted, process egress and ingress until nghttp2 is done. */ + result = CURLE_OK; + if(nghttp2_session_want_write(ctx->h2) || + !Curl_bufq_is_empty(&ctx->outbufq)) + result = h2_progress_egress(cf, data); + if(!result && nghttp2_session_want_read(ctx->h2)) + result = h2_progress_ingress(cf, data, 0); + + if(result == CURLE_AGAIN) + result = CURLE_OK; + + *done = (ctx->conn_closed || + (!result && !nghttp2_session_want_write(ctx->h2) && + !nghttp2_session_want_read(ctx->h2) && + Curl_bufq_is_empty(&ctx->outbufq))); + +out: + CF_DATA_RESTORE(cf, save); + cf->shutdown = (result || *done); + return result; +} + +static CURLcode http2_data_pause(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool pause) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + + DEBUGASSERT(data); + if(ctx && ctx->h2 && stream) { + CURLcode result; + + stream->write_paused = pause; + result = cf_h2_update_local_win(cf, data, stream); + if(result) + return result; + + /* attempt to send the window update */ + (void)h2_progress_egress(cf, data); + + if(!pause) { + /* Unpausing a h2 transfer, requires it to be run again. The server + * may send new DATA on us increasing the flow window, and it may + * not. We may have already buffered and exhausted the new window + * by operating on things in flight during the handling of other + * transfers. */ + Curl_multi_mark_dirty(data); + } + CURL_TRC_CF(data, cf, "[%d] stream now %spaused", stream->id, + pause ? "" : "un"); + } + return CURLE_OK; +} + +static CURLcode cf_h2_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + CURLcode result = CURLE_OK; + struct cf_call_data save; + + (void)arg2; + + CF_DATA_SAVE(save, cf, data); + switch(event) { + case CF_CTRL_DATA_SETUP: + break; + case CF_CTRL_DATA_PAUSE: + result = http2_data_pause(cf, data, (arg1 != 0)); + break; + case CF_CTRL_FLUSH: + result = cf_h2_flush(cf, data); + break; + case CF_CTRL_DATA_DONE: + http2_data_done(cf, data); + break; + case CF_CTRL_CONN_INFO_UPDATE: + if(!cf->sockindex && cf->connected) { + cf->conn->httpversion_seen = 20; + Curl_conn_set_multiplex(cf->conn); + } + break; + default: + break; + } + CF_DATA_RESTORE(cf, save); + return result; +} + +static bool cf_h2_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_h2_ctx *ctx = cf->ctx; + + if(ctx && !Curl_bufq_is_empty(&ctx->inbufq)) + return TRUE; + return cf->next ? cf->next->cft->has_data_pending(cf->next, data) : FALSE; +} + +static bool cf_h2_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + struct cf_h2_ctx *ctx = cf->ctx; + bool alive; + struct cf_call_data save; + + *input_pending = FALSE; + CF_DATA_SAVE(save, cf, data); + alive = (ctx && ctx->h2 && http2_connisalive(cf, data, input_pending)); + CURL_TRC_CF(data, cf, "conn alive -> %d, input_pending=%d", + alive, *input_pending); + CF_DATA_RESTORE(cf, save); + return alive; +} + +static CURLcode cf_h2_keep_alive(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURLcode result; + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + result = http2_send_ping(cf, data); + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode cf_h2_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_h2_ctx *ctx = cf->ctx; + struct cf_call_data save; + size_t effective_max; + + switch(query) { + case CF_QUERY_MAX_CONCURRENT: + DEBUGASSERT(pres1); + + CF_DATA_SAVE(save, cf, data); + if(!ctx->h2 || !nghttp2_session_check_request_allowed(ctx->h2)) { + /* the limit is what we have in use right now */ + effective_max = cf->conn->attached_xfers; + } + else { + effective_max = ctx->max_concurrent_streams; + } + *pres1 = (effective_max > INT_MAX) ? INT_MAX : (int)effective_max; + CF_DATA_RESTORE(cf, save); + return CURLE_OK; + case CF_QUERY_STREAM_ERROR: { + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + *pres1 = stream ? (int)stream->error : 0; + return CURLE_OK; + } + case CF_QUERY_NEED_FLUSH: { + struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data); + if(!Curl_bufq_is_empty(&ctx->outbufq) || + (stream && !Curl_bufq_is_empty(&stream->sendbuf))) { + *pres1 = TRUE; + return CURLE_OK; + } + break; + } + case CF_QUERY_HTTP_VERSION: + *pres1 = 20; + return CURLE_OK; + default: + break; + } + return cf->next ? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +struct Curl_cftype Curl_cft_nghttp2 = { + "HTTP/2", + CF_TYPE_MULTIPLEX | CF_TYPE_HTTP, + CURL_LOG_LVL_NONE, + cf_h2_destroy, + cf_h2_connect, + cf_h2_shutdown, + cf_h2_adjust_pollset, + cf_h2_data_pending, + cf_h2_send, + cf_h2_recv, + cf_h2_cntrl, + cf_h2_is_alive, + cf_h2_keep_alive, + cf_h2_query, +}; + +static CURLcode http2_cfilter_add(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + bool via_h1_upgrade) +{ + struct Curl_cfilter *cf = NULL; + struct cf_h2_ctx *ctx; + CURLcode result = CURLE_OUT_OF_MEMORY; + + DEBUGASSERT(data->conn); + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) + goto out; + cf_h2_ctx_init(ctx, via_h1_upgrade); + + result = Curl_cf_create(&cf, &Curl_cft_nghttp2, ctx); + if(result) + goto out; + + ctx = NULL; + Curl_conn_cf_add(data, conn, sockindex, cf); + +out: + if(result) + cf_h2_ctx_free(ctx); + *pcf = result ? NULL : cf; + return result; +} + +static CURLcode http2_cfilter_insert_after(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool via_h1_upgrade) +{ + struct Curl_cfilter *cf_h2 = NULL; + struct cf_h2_ctx *ctx; + CURLcode result = CURLE_OUT_OF_MEMORY; + + (void)data; + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) + goto out; + cf_h2_ctx_init(ctx, via_h1_upgrade); + + result = Curl_cf_create(&cf_h2, &Curl_cft_nghttp2, ctx); + if(result) + goto out; + + ctx = NULL; + Curl_conn_cf_insert_after(cf, cf_h2); + +out: + if(result) + cf_h2_ctx_free(ctx); + return result; +} + +bool Curl_http2_may_switch(struct Curl_easy *data) +{ + if(Curl_conn_http_version(data, data->conn) < 20 && + (data->state.http_neg.wanted & CURL_HTTP_V2x) && + data->state.http_neg.h2_prior_knowledge) { +#ifndef CURL_DISABLE_PROXY + if(data->conn->bits.origin_is_proxy) { + infof(data, "Ignoring HTTP/2 prior knowledge due to proxy"); + return FALSE; + } +#endif + return TRUE; + } + return FALSE; +} + +CURLcode Curl_http2_switch(struct Curl_easy *data) +{ + struct Curl_cfilter *cf; + CURLcode result; + + DEBUGASSERT(Curl_conn_http_version(data, data->conn) < 20); + + result = http2_cfilter_add(&cf, data, data->conn, FIRSTSOCKET, FALSE); + if(result) + return result; + CURL_TRC_CF(data, cf, "switching connection to HTTP/2"); + + if(cf->next) { + bool done; + return Curl_conn_cf_connect(cf, data, &done); + } + return CURLE_OK; +} + +CURLcode Curl_http2_switch_at(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct Curl_cfilter *cf_h2; + CURLcode result; + + DEBUGASSERT(Curl_conn_http_version(data, data->conn) < 20); + + result = http2_cfilter_insert_after(cf, data, FALSE); + if(result) + return result; + + cf_h2 = cf->next; + + if(cf_h2->next) { + bool done; + return Curl_conn_cf_connect(cf_h2, data, &done); + } + return CURLE_OK; +} + +CURLcode Curl_http2_upgrade(struct Curl_easy *data, + struct connectdata *conn, int8_t sockindex, + const char *mem, size_t nread) +{ + struct Curl_cfilter *cf; + struct cf_h2_ctx *ctx; + CURLcode result; + + DEBUGASSERT(Curl_conn_http_version(data, conn) < 20); + + result = http2_cfilter_add(&cf, data, conn, sockindex, TRUE); + if(result) + return result; + CURL_TRC_CF(data, cf, "upgrading connection to HTTP/2"); + + DEBUGASSERT(cf->cft == &Curl_cft_nghttp2); + ctx = cf->ctx; + + data->req.httpversion_sent = 20; /* it is an h2 request now */ + data->req.header = TRUE; /* we expect the real response to come in h2 */ + data->req.headerline = 0; /* restart the header line counter */ + + if(nread > 0) { + /* Remaining data from the protocol switch reply is already using + * the switched protocol, ie. HTTP/2. We add that to the network + * inbufq. */ + size_t copied; + + result = Curl_bufq_write(&ctx->inbufq, + (const unsigned char *)mem, nread, &copied); + if(result) { + failf(data, "error on copying HTTP Upgrade response: %d", (int)result); + return CURLE_RECV_ERROR; + } + if(copied < nread) { + failf(data, "connection buffer size could not take all data " + "from HTTP Upgrade response header: copied=%zu, datalen=%zu", + copied, nread); + return CURLE_HTTP2; + } + infof(data, "Copied HTTP/2 data in stream buffer to connection buffer" + " after upgrade: len=%zu", nread); + } + + if(cf->next) { + bool done; + result = Curl_conn_cf_connect(cf, data, &done); + if(!result) + cf->cft->cntrl(cf, data, CF_CTRL_CONN_INFO_UPDATE, 0, NULL); + } + return result; +} + +/* Only call this function for a transfer that already got an HTTP/2 + CURLE_HTTP2_STREAM error! */ +bool Curl_h2_http_1_1_error(struct Curl_easy *data) +{ + if(Curl_conn_http_version(data, data->conn) == 20) { + int err = Curl_conn_get_stream_error(data, data->conn, FIRSTSOCKET); + return err == NGHTTP2_HTTP_1_1_REQUIRED; + } + return FALSE; +} + +void *Curl_nghttp2_malloc(size_t size, void *user_data) +{ + (void)user_data; + return Curl_cmalloc(size); +} + +void Curl_nghttp2_free(void *ptr, void *user_data) +{ + (void)user_data; + Curl_cfree(ptr); +} + +void *Curl_nghttp2_calloc(size_t nmemb, size_t size, void *user_data) +{ + (void)user_data; + return Curl_ccalloc(nmemb, size); +} + +void *Curl_nghttp2_realloc(void *ptr, size_t size, void *user_data) +{ + (void)user_data; + return Curl_crealloc(ptr, size); +} + +#else /* CURL_DISABLE_HTTP || !USE_NGHTTP2 */ + +/* Satisfy external references even if http2 is not compiled in. */ + +char *curl_pushheader_bynum(struct curl_pushheaders *h, size_t num) +{ + (void)h; + (void)num; + return NULL; +} + +char *curl_pushheader_byname(struct curl_pushheaders *h, const char *name) +{ + (void)h; + (void)name; + return NULL; +} + +#endif /* !CURL_DISABLE_HTTP && USE_NGHTTP2 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http2.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http2.h new file mode 100644 index 0000000000..c3270da1cc --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http2.h @@ -0,0 +1,76 @@ +#ifndef HEADER_CURL_HTTP2_H +#define HEADER_CURL_HTTP2_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_NGHTTP2 + +/* value for MAX_CONCURRENT_STREAMS we use until we get an updated setting + from the peer */ +#define DEFAULT_MAX_CONCURRENT_STREAMS 100 + +/* + * Store nghttp2 version info in this buffer. + */ +void Curl_http2_ver(char *p, size_t len); + +#ifdef CURLVERBOSE +int Curl_nghttp2_fr_print(const nghttp2_frame *frame, char *buffer, + size_t blen); +#endif + +CURLcode Curl_http2_request_upgrade(struct dynbuf *req, + struct Curl_easy *data); + +/* returns true if the HTTP/2 stream error was HTTP_1_1_REQUIRED */ +bool Curl_h2_http_1_1_error(struct Curl_easy *data); + +bool Curl_http2_may_switch(struct Curl_easy *data); + +CURLcode Curl_http2_switch(struct Curl_easy *data); + +CURLcode Curl_http2_switch_at(struct Curl_cfilter *cf, struct Curl_easy *data); + +CURLcode Curl_http2_upgrade(struct Curl_easy *data, + struct connectdata *conn, int8_t sockindex, + const char *mem, size_t nread); + +void *Curl_nghttp2_malloc(size_t size, void *user_data); +void Curl_nghttp2_free(void *ptr, void *user_data); +void *Curl_nghttp2_calloc(size_t nmemb, size_t size, void *user_data); +void *Curl_nghttp2_realloc(void *ptr, size_t size, void *user_data); + +extern struct Curl_cftype Curl_cft_nghttp2; + +#else /* USE_NGHTTP2 */ + +#define Curl_http2_may_switch(a) FALSE + +#define Curl_http2_request_upgrade(x, y) CURLE_UNSUPPORTED_PROTOCOL +#define Curl_http2_switch(a) CURLE_UNSUPPORTED_PROTOCOL +#define Curl_h2_http_1_1_error(x) 0 +#endif + +#endif /* HEADER_CURL_HTTP2_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_aws_sigv4.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_aws_sigv4.c new file mode 100644 index 0000000000..b16c2cd2aa --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_aws_sigv4.c @@ -0,0 +1,1238 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_AWS) + +#include "urldata.h" +#include "strcase.h" +#include "curlx/strdup.h" +#include "http_aws_sigv4.h" +#include "curl_sha256.h" +#include "transfer.h" +#include "curl_trc.h" +#include "escape.h" +#include "curlx/strparse.h" +#include "slist.h" + +#include <time.h> + +#define HMAC_SHA256(k, kl, d, dl, o) \ + do { \ + result = Curl_hmacit(&Curl_HMAC_SHA256, \ + (const unsigned char *)(k), \ + kl, \ + (const unsigned char *)(d), \ + dl, o); \ + if(result) { \ + goto fail; \ + } \ + } while(0) + +#define TIMESTAMP_SIZE 17 + +/* hex-encoded with null-terminator */ +#define SHA256_HEX_LENGTH ((2 * CURL_SHA256_DIGEST_LENGTH) + 1) + +#define MAX_QUERY_COMPONENTS 128 + +struct pair { + struct dynbuf key; + struct dynbuf value; +}; + +static void sha256_to_hex(char *dst, unsigned char *sha) +{ + Curl_hexencode(sha, CURL_SHA256_DIGEST_LENGTH, + (unsigned char *)dst, SHA256_HEX_LENGTH); +} + +static char *find_date_hdr(struct Curl_easy *data, const char *sig_hdr) +{ + char *tmp = Curl_checkheaders(data, sig_hdr, strlen(sig_hdr)); + + if(tmp) + return tmp; + return Curl_checkheaders(data, STRCONST("Date")); +} + +/* remove whitespace, and lowercase all headers */ +static void trim_headers(struct curl_slist *head) +{ + struct curl_slist *l; + for(l = head; l; l = l->next) { + const char *value; /* to read from */ + char *store; + size_t colon = strcspn(l->data, ":"); + Curl_strntolower(l->data, l->data, colon); + + value = &l->data[colon]; + if(!*value) + continue; + ++value; + store = (char *)CURL_UNCONST(value); + + /* skip leading whitespace */ + curlx_str_passblanks(&value); + + while(*value) { + int space = 0; + while(ISBLANK(*value)) { + value++; + space++; + } + if(space) { + /* replace any number of consecutive whitespace with a single space, + unless at the end of the string, then nothing */ + if(*value) + *store++ = ' '; + } + else + *store++ = *value++; + } + *store = 0; /* null-terminate */ + } +} + +/* + * Frees all allocated strings in a dynbuf pair array, and the dynbuf itself + */ +static void pair_array_free(struct pair *pair_array, size_t num_elements) +{ + size_t index; + + for(index = 0; index != num_elements; index++) { + curlx_dyn_free(&pair_array[index].key); + curlx_dyn_free(&pair_array[index].value); + } +} + +/* + * Frees all allocated strings in a split dynbuf, and the dynbuf itself + */ +static void dyn_array_free(struct dynbuf *db, size_t num_elements) +{ + size_t index; + + for(index = 0; index < num_elements; index++) + curlx_dyn_free((&db[index])); +} + +/* + * Splits source string by SPLIT_BY, and creates an array of dynbuf in db. + * db is initialized by this function. + * Caller is responsible for freeing the array elements with dyn_array_free + */ + +#define SPLIT_BY '&' + +static CURLcode split_to_dyn_array(const char *source, + struct dynbuf db[MAX_QUERY_COMPONENTS], + size_t *num_splits_out) +{ + CURLcode result = CURLE_OK; + size_t len = strlen(source); + size_t pos; /* Position in result buffer */ + size_t start = 0; /* Start of current segment */ + size_t segment_length = 0; + size_t index = 0; + size_t num_splits = 0; + + /* Split source_ptr on SPLIT_BY and store the segment offsets and length in + * array */ + for(pos = 0; pos < len; pos++) { + if(source[pos] == SPLIT_BY) { + if(segment_length) { + curlx_dyn_init(&db[index], segment_length + 1); + result = curlx_dyn_addn(&db[index], &source[start], segment_length); + if(result) + goto fail; + + segment_length = 0; + index++; + if(++num_splits == MAX_QUERY_COMPONENTS) { + result = CURLE_TOO_LARGE; + goto fail; + } + } + start = pos + 1; + } + else { + segment_length++; + } + } + + if(segment_length) { + curlx_dyn_init(&db[index], segment_length + 1); + result = curlx_dyn_addn(&db[index], &source[start], segment_length); + if(!result) { + if(++num_splits == MAX_QUERY_COMPONENTS) + result = CURLE_TOO_LARGE; + } + } +fail: + *num_splits_out = num_splits; + return result; +} + +static bool is_reserved_char(const char c) +{ + return (ISALNUM(c) || ISURLPUNTCS(c)); +} + +static CURLcode uri_encode_path(struct Curl_str *original_path, + struct dynbuf *new_path) +{ + const char *p = curlx_str(original_path); + size_t i; + + for(i = 0; i < curlx_strlen(original_path); i++) { + /* Do not encode slashes or unreserved chars from RFC 3986 */ + CURLcode result = CURLE_OK; + unsigned char c = p[i]; + if(is_reserved_char(c) || c == '/') + result = curlx_dyn_addn(new_path, &c, 1); + else + result = curlx_dyn_addf(new_path, "%%%02X", c); + if(result) + return result; + } + + return CURLE_OK; +} + +/* Normalize the query part. Make sure %2B is left percent encoded, and not + decoded to plus, then encoded to space. */ +static CURLcode normalize_query(const char *string, size_t len, + struct dynbuf *db) +{ + CURLcode result = CURLE_OK; + + while(len && !result) { + unsigned char in = (unsigned char)*string; + if(('%' == in) && (len > 2) && + ISXDIGIT(string[1]) && ISXDIGIT(string[2])) { + /* this is two hexadecimal digits following a '%' */ + in = (unsigned char)((curlx_hexval(string[1]) << 4) | + curlx_hexval(string[2])); + string += 3; + len -= 3; + if(in == '+') { + /* decodes to plus, so leave this encoded */ + result = curlx_dyn_addn(db, "%2B", 3); + continue; + } + } + else { + string++; + len--; + } + + if(is_reserved_char(in)) + /* Escape unreserved chars from RFC 3986 */ + result = curlx_dyn_addn(db, &in, 1); + else if(in == '+') + /* Encode '+' as space */ + result = curlx_dyn_add(db, "%20"); + else + result = curlx_dyn_addf(db, "%%%02X", in); + } + + return result; +} + +static bool should_urlencode(struct Curl_str *service_name) +{ + /* + * These services require unmodified (not additionally URL-encoded) URL + * paths. + * should_urlencode == true is equivalent to should_urlencode_uri_path + * from the AWS SDK. Urls are already normalized by the curl URL parser + */ + if(curlx_str_cmp(service_name, "s3") || + curlx_str_cmp(service_name, "s3-express") || + curlx_str_cmp(service_name, "s3-outposts")) { + return FALSE; + } + return TRUE; +} + +/* maximum length for the aws sivg4 parts */ +#define MAX_SIGV4_LEN 64 +#define DATE_HDR_KEY_LEN (MAX_SIGV4_LEN + sizeof("X--Date")) + +/* string been x-PROVIDER-date:TIMESTAMP, I need +1 for ':' */ +#define DATE_FULL_HDR_LEN (DATE_HDR_KEY_LEN + TIMESTAMP_SIZE + 1) + +/* alphabetically compare two headers by their name, expecting + headers to use ':' at this point */ +static int compare_header_names(const char *a, const char *b) +{ + const char *colon_a; + const char *colon_b; + size_t len_a; + size_t len_b; + size_t min_len; + int cmp; + + colon_a = strchr(a, ':'); + colon_b = strchr(b, ':'); + + DEBUGASSERT(colon_a); + DEBUGASSERT(colon_b); + + len_a = colon_a ? (size_t)(colon_a - a) : strlen(a); + len_b = colon_b ? (size_t)(colon_b - b) : strlen(b); + + min_len = (len_a < len_b) ? len_a : len_b; + + cmp = strncmp(a, b, min_len); + + /* return the shorter of the two if one is shorter */ + if(!cmp) + return (int)(len_a - len_b); + + return cmp; +} + +/* Merge duplicate header definitions by comma delimiting their values + in the order defined the headers are defined, expecting headers to + be alpha-sorted and use ':' at this point */ +static CURLcode merge_duplicate_headers(struct curl_slist *head) +{ + struct curl_slist *curr = head; + CURLcode result = CURLE_OK; + + while(curr) { + struct curl_slist *next = curr->next; + if(!next) + break; + + if(compare_header_names(curr->data, next->data) == 0) { + struct dynbuf buf; + const char *colon_next; + const char *val_next; + + curlx_dyn_init(&buf, CURL_MAX_HTTP_HEADER); + + result = curlx_dyn_add(&buf, curr->data); + if(result) + return result; + + colon_next = strchr(next->data, ':'); + DEBUGASSERT(colon_next); + val_next = colon_next + 1; + + result = curlx_dyn_addn(&buf, ",", 1); + if(result) + return result; + + result = curlx_dyn_add(&buf, val_next); + if(result) + return result; + + curlx_free(curr->data); + curr->data = curlx_dyn_ptr(&buf); + + curr->next = next->next; + curlx_free(next->data); + curlx_free(next); + } + else { + curr = curr->next; + } + } + + return CURLE_OK; +} + +/* timestamp should point to a buffer of at last TIMESTAMP_SIZE bytes */ +static CURLcode make_headers(struct Curl_easy *data, + char *timestamp, + const char *provider1, + size_t plen, /* length of provider1 */ + char **date_header, + char *content_sha256_header, + struct dynbuf *canonical_headers, + struct dynbuf *signed_headers) +{ + char date_hdr_key[DATE_HDR_KEY_LEN]; + char date_full_hdr[DATE_FULL_HDR_LEN]; + struct curl_slist *head = NULL; + struct curl_slist *tmp_head = NULL; + CURLcode result = CURLE_OUT_OF_MEMORY; + struct curl_slist *l; + bool again = TRUE; + + curl_msnprintf(date_hdr_key, DATE_HDR_KEY_LEN, "X-%.*s-Date", + (int)plen, provider1); + /* provider1 ucfirst */ + Curl_strntolower(&date_hdr_key[2], provider1, plen); + date_hdr_key[2] = Curl_raw_toupper(provider1[0]); + + curl_msnprintf(date_full_hdr, DATE_FULL_HDR_LEN, + "x-%.*s-date:%s", (int)plen, provider1, timestamp); + /* provider1 lowercase */ + Curl_strntolower(&date_full_hdr[2], provider1, plen); + + if(!Curl_checkheaders(data, STRCONST("Host")) && + data->state.http_host) { + /* Host: [host]:[port] */ + char *fullhost = curlx_strdup(data->state.http_host); + + if(fullhost) + head = Curl_slist_append_nodup(NULL, fullhost); + if(!head) { + curlx_free(fullhost); + goto fail; + } + } + + if(*content_sha256_header) { + tmp_head = curl_slist_append(head, content_sha256_header); + if(!tmp_head) + goto fail; + head = tmp_head; + } + + /* copy user headers to our header list. the logic is based on how http.c + handles user headers. + + user headers in format 'name:' with no value are used to signal that an + internal header of that name should be removed. those user headers are not + added to this list. + + user headers in format 'name;' with no value are used to signal that a + header of that name with no value should be sent. those user headers are + added to this list but in the format that they will be sent, ie the + semi-colon is changed to a colon for format 'name:'. + + user headers with a value of whitespace only, or without a colon or + semi-colon, are not added to this list. + */ + for(l = data->set.headers; l; l = l->next) { + char *dupdata; + const char *ptr; + const char *sep = strchr(l->data, ':'); + if(!sep) + sep = strchr(l->data, ';'); + if(!sep || (*sep == ':' && !*(sep + 1))) + continue; + for(ptr = sep + 1; ISBLANK(*ptr); ++ptr) + ; + if(!*ptr && ptr != sep + 1) /* a value of whitespace only */ + continue; + dupdata = curlx_strdup(l->data); + if(!dupdata) + goto fail; + dupdata[sep - l->data] = ':'; + tmp_head = Curl_slist_append_nodup(head, dupdata); + if(!tmp_head) { + curlx_free(dupdata); + goto fail; + } + head = tmp_head; + } + + trim_headers(head); + + *date_header = find_date_hdr(data, date_hdr_key); + if(!*date_header) { + tmp_head = curl_slist_append(head, date_full_hdr); + if(!tmp_head) + goto fail; + head = tmp_head; + *date_header = curl_maprintf("%s: %s\r\n", date_hdr_key, timestamp); + if(!*date_header) + goto fail; + } + else { + const char *value; + const char *endp; + value = strchr(*date_header, ':'); + if(!value) { + *date_header = NULL; + goto fail; + } + ++value; + curlx_str_passblanks(&value); + endp = value; + while(*endp && ISALNUM(*endp)) + ++endp; + /* 16 bytes => "19700101T000000Z" */ + if((endp - value) == TIMESTAMP_SIZE - 1) { + memcpy(timestamp, value, TIMESTAMP_SIZE - 1); + timestamp[TIMESTAMP_SIZE - 1] = 0; + } + else + /* bad timestamp length */ + timestamp[0] = 0; + *date_header = NULL; + } + + /* alpha-sort by header name in a case sensitive manner */ + do { + again = FALSE; + for(l = head; l; l = l->next) { + struct curl_slist *next = l->next; + + if(next && compare_header_names(l->data, next->data) > 0) { + char *tmp = l->data; + + l->data = next->data; + next->data = tmp; + again = TRUE; + } + } + } while(again); + + result = merge_duplicate_headers(head); + if(result) + goto fail; + + for(l = head; l; l = l->next) { + char *tmp; + + if(curlx_dyn_add(canonical_headers, l->data)) + goto fail; + if(curlx_dyn_add(canonical_headers, "\n")) + goto fail; + + tmp = strchr(l->data, ':'); + if(tmp) + *tmp = 0; + + if(l != head) { + if(curlx_dyn_add(signed_headers, ";")) + goto fail; + } + if(curlx_dyn_add(signed_headers, l->data)) + goto fail; + } + + result = CURLE_OK; +fail: + curl_slist_free_all(head); + + return result; +} + +#define CONTENT_SHA256_KEY_LEN (MAX_SIGV4_LEN + sizeof("X--Content-Sha256")) +/* add 2 for ": " between header name and value */ +#define CONTENT_SHA256_HDR_LEN (CONTENT_SHA256_KEY_LEN + 2 + SHA256_HEX_LENGTH) + +/* try to parse a payload hash from the content-sha256 header */ +static const char *parse_content_sha_hdr(struct Curl_easy *data, + const char *provider1, + size_t plen, + size_t *value_len) +{ + char key[CONTENT_SHA256_KEY_LEN]; + size_t key_len; + const char *value; + size_t len; + + key_len = curl_msnprintf(key, sizeof(key), "x-%.*s-content-sha256", + (int)plen, provider1); + + value = Curl_checkheaders(data, key, key_len); + if(!value) + return NULL; + + value = strchr(value, ':'); + if(!value) + return NULL; + ++value; + + curlx_str_passblanks(&value); + + len = strlen(value); + while(len > 0 && ISBLANK(value[len - 1])) + --len; + + *value_len = len; + return value; +} + +static CURLcode calc_payload_hash(struct Curl_easy *data, + unsigned char *sha_hash, char *sha_hex) +{ + const char *post_data = data->set.postfields; + size_t post_data_len = 0; + CURLcode result; + + if(post_data) { + if(data->set.postfieldsize < 0) + post_data_len = strlen(post_data); + else + post_data_len = (size_t)data->set.postfieldsize; + } + result = Curl_sha256it(sha_hash, (const unsigned char *)post_data, + post_data_len); + if(!result) + sha256_to_hex(sha_hex, sha_hash); + return result; +} + +#define S3_UNSIGNED_PAYLOAD "UNSIGNED-PAYLOAD" + +static CURLcode calc_s3_payload_hash(struct Curl_easy *data, + Curl_HttpReq httpreq, + const char *provider1, + size_t plen, + unsigned char *sha_hash, + char *sha_hex, char *header) +{ + bool empty_method = (httpreq == HTTPREQ_GET || httpreq == HTTPREQ_HEAD); + /* The request method or filesize indicate no request payload */ + bool empty_payload = (empty_method || data->set.filesize == 0); + /* The POST payload is in memory */ + bool post_payload = (httpreq == HTTPREQ_POST && data->set.postfields); + CURLcode result = CURLE_OUT_OF_MEMORY; + + if(empty_payload || post_payload) { + /* Calculate a real hash when we know the request payload */ + result = calc_payload_hash(data, sha_hash, sha_hex); + if(result) + goto fail; + } + else { + /* Fall back to s3's UNSIGNED-PAYLOAD */ + size_t len = CURL_CSTRLEN(S3_UNSIGNED_PAYLOAD); + DEBUGASSERT(len < SHA256_HEX_LENGTH); /* 16 < 65 */ + memcpy(sha_hex, S3_UNSIGNED_PAYLOAD, len); + sha_hex[len] = 0; + } + + /* format the required content-sha256 header */ + curl_msnprintf(header, CONTENT_SHA256_HDR_LEN, + "x-%.*s-content-sha256: %s", (int)plen, provider1, sha_hex); + + result = CURLE_OK; +fail: + return result; +} + +static int compare_func(const void *a, const void *b) +{ + const struct pair *aa = a; + const struct pair *bb = b; + const size_t aa_key_len = curlx_dyn_len(&aa->key); + const size_t bb_key_len = curlx_dyn_len(&bb->key); + const size_t aa_value_len = curlx_dyn_len(&aa->value); + const size_t bb_value_len = curlx_dyn_len(&bb->value); + int compare; + + /* If one element is empty, the other is always sorted higher */ + + /* Compare keys */ + if((aa_key_len == 0) && (bb_key_len == 0)) + return 0; + if(aa_key_len == 0) + return -1; + if(bb_key_len == 0) + return 1; + compare = strcmp(curlx_dyn_ptr(&aa->key), curlx_dyn_ptr(&bb->key)); + if(compare) { + return compare; + } + + /* Compare values */ + if((aa_value_len == 0) && (bb_value_len == 0)) + return 0; + if(aa_value_len == 0) + return -1; + if(bb_value_len == 0) + return 1; + compare = strcmp(curlx_dyn_ptr(&aa->value), curlx_dyn_ptr(&bb->value)); + + return compare; +} + +/* @unittest 1979 */ +UNITTEST CURLcode canon_path(const char *q, size_t len, + struct dynbuf *new_path, + bool do_uri_encode); +UNITTEST CURLcode canon_path(const char *q, size_t len, + struct dynbuf *new_path, + bool do_uri_encode) +{ + CURLcode result = CURLE_OK; + + struct Curl_str original_path; + + curlx_str_assign(&original_path, q, len); + + /* Normalized path will be either the same or shorter than the original + * path, plus trailing slash */ + + if(do_uri_encode) + result = uri_encode_path(&original_path, new_path); + else + result = curlx_dyn_addn(new_path, q, len); + + if(!result) { + if(curlx_dyn_len(new_path) == 0) + result = curlx_dyn_add(new_path, "/"); + } + + return result; +} + +/* @unittest 1980 */ +UNITTEST CURLcode canon_query(const char *query, struct dynbuf *dq); +UNITTEST CURLcode canon_query(const char *query, struct dynbuf *dq) +{ + CURLcode result = CURLE_OK; + + struct dynbuf query_array[MAX_QUERY_COMPONENTS]; + struct pair encoded_query_array[MAX_QUERY_COMPONENTS]; + size_t num_query_components; + size_t counted_query_components = 0; + size_t index; + + if(!query) + return result; + + result = split_to_dyn_array(query, &query_array[0], &num_query_components); + if(result) { + goto fail; + } + + /* Create list of pairs, each pair containing an encoded query + * component */ + + for(index = 0; index < num_query_components; index++) { + const char *in_key; + size_t in_key_len; + const char *offset; + size_t query_part_len = curlx_dyn_len(&query_array[index]); + const char *query_part = curlx_dyn_ptr(&query_array[index]); + + in_key = query_part; + + offset = strchr(query_part, '='); + /* If there is no equals, this key has no value */ + if(!offset) { + in_key_len = strlen(in_key); + } + else { + in_key_len = offset - in_key; + } + + curlx_dyn_init(&encoded_query_array[index].key, + (query_part_len * 3) + 1); + curlx_dyn_init(&encoded_query_array[index].value, + (query_part_len * 3) + 1); + counted_query_components++; + + /* Decode/encode the key */ + result = normalize_query(in_key, in_key_len, + &encoded_query_array[index].key); + if(result) { + goto fail; + } + + /* Decode/encode the value if it exists */ + if(offset && offset != (query_part + query_part_len - 1)) { + size_t in_value_len; + const char *in_value = offset + 1; + in_value_len = query_part + query_part_len - (offset + 1); + result = normalize_query(in_value, in_value_len, + &encoded_query_array[index].value); + if(result) { + goto fail; + } + } + else { + /* If there is no value, the value is an empty string */ + curlx_dyn_init(&encoded_query_array[index].value, 2); + result = curlx_dyn_addn(&encoded_query_array[index].value, "", 1); + } + + if(result) { + goto fail; + } + } + + /* Sort the encoded query components by key and value */ + qsort(&encoded_query_array, num_query_components, + sizeof(struct pair), compare_func); + + /* Append the query components together to make a full query string */ + for(index = 0; index < num_query_components; index++) { + + if(index) + result = curlx_dyn_addn(dq, "&", 1); + if(!result) { + const char *key_ptr = curlx_dyn_ptr(&encoded_query_array[index].key); + const char *value_ptr = curlx_dyn_ptr(&encoded_query_array[index].value); + size_t vlen = curlx_dyn_len(&encoded_query_array[index].value); + if(value_ptr && vlen) { + result = curlx_dyn_addf(dq, "%s=%s", key_ptr, value_ptr); + } + else { + /* Empty value is always encoded to key= */ + result = curlx_dyn_addf(dq, "%s=", key_ptr); + } + } + if(result) + break; + } + +fail: + if(counted_query_components) + /* the encoded_query_array might not be initialized yet */ + pair_array_free(&encoded_query_array[0], counted_query_components); + dyn_array_free(&query_array[0], num_query_components); + return result; +} + +static CURLcode parse_sigv4_params(struct Curl_easy *data, + const char *hostname, + struct Curl_str *provider0, + struct Curl_str *provider1, + struct Curl_str *region, + struct Curl_str *service) +{ + const char *line = CURL_EASY_STR(data, STRING_AWS_SIGV4); + if(!line || !*line) + line = "aws:amz"; + + /* provider0[:provider1[:region[:service]]] + + No string can be longer than N bytes of non-whitespace */ + if(curlx_str_until(&line, provider0, MAX_SIGV4_LEN, ':')) { + failf(data, "first aws-sigv4 provider cannot be empty"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if(curlx_str_single(&line, ':') || + curlx_str_until(&line, provider1, MAX_SIGV4_LEN, ':')) { + *provider1 = *provider0; + } + else if(curlx_str_single(&line, ':') || + curlx_str_until(&line, region, MAX_SIGV4_LEN, ':') || + curlx_str_single(&line, ':') || + curlx_str_until(&line, service, MAX_SIGV4_LEN, ':')) { + /* nothing to do */ + } + + if(!curlx_strlen(service)) { + const char *p = hostname; + if(curlx_str_until(&p, service, MAX_SIGV4_LEN, '.') || + curlx_str_single(&p, '.')) { + failf(data, "aws-sigv4: service missing in parameters and hostname"); + return CURLE_URL_MALFORMAT; + } + + infof(data, "aws_sigv4: picked service %.*s from host", + (int)curlx_strlen(service), curlx_str(service)); + + if(!curlx_strlen(region)) { + if(curlx_str_until(&p, region, MAX_SIGV4_LEN, '.') || + curlx_str_single(&p, '.')) { + failf(data, "aws-sigv4: region missing in parameters and hostname"); + return CURLE_URL_MALFORMAT; + } + infof(data, "aws_sigv4: picked region %.*s from host", + (int)curlx_strlen(region), curlx_str(region)); + } + } + + return CURLE_OK; +} + +static CURLcode get_payload_hash(struct Curl_easy *data, + Curl_HttpReq httpreq, + struct Curl_str *provider0, + struct Curl_str *provider1, + struct Curl_str *service, + unsigned char *sha_hash, + char *sha_hex, + char *content_sha256_hdr, + const char **payload_hash_out, + size_t *payload_hash_len_out) +{ + *payload_hash_out = + parse_content_sha_hdr(data, curlx_str(provider1), + curlx_strlen(provider1), payload_hash_len_out); + + if(!*payload_hash_out) { + CURLcode result; + /* AWS S3 requires a x-amz-content-sha256 header, and supports special + * values like UNSIGNED-PAYLOAD */ + bool sign_as_s3 = curlx_str_casecompare(provider0, "aws") && + curlx_str_casecompare(service, "s3"); + + if(sign_as_s3) + result = calc_s3_payload_hash(data, httpreq, curlx_str(provider1), + curlx_strlen(provider1), sha_hash, + sha_hex, content_sha256_hdr); + else + result = calc_payload_hash(data, sha_hash, sha_hex); + if(result) + return result; + + *payload_hash_out = sha_hex; + /* may be shorter than SHA256_HEX_LENGTH, like S3_UNSIGNED_PAYLOAD */ + *payload_hash_len_out = strlen(sha_hex); + } + return CURLE_OK; +} + +static CURLcode get_timestamp(char *timestamp, size_t stampsize) +{ + time_t clock; + struct tm tm; + CURLcode result; + +#ifdef DEBUGBUILD + { + char *force_timestamp = getenv("CURL_FORCETIME"); + if(force_timestamp) + clock = 0; + else + clock = time(NULL); + } +#else + clock = time(NULL); +#endif + result = curlx_gmtime(clock, &tm); + if(result) + return result; + + if(!strftime(timestamp, stampsize, "%Y%m%dT%H%M%SZ", &tm)) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static CURLcode make_canonical_request(struct Curl_easy *data, + char *timestamp, + struct Curl_str *provider1, + struct Curl_str *service, + const char *method, + const char *payload_hash, + size_t payload_hash_len, + char **date_header_out, + char *content_sha256_hdr, + struct dynbuf *canonical_headers, + struct dynbuf *signed_headers, + char **canonical_request_out) +{ + struct dynbuf canonical_query; + struct dynbuf canonical_path; + CURLcode result; + + curlx_dyn_init(&canonical_query, CURL_MAX_HTTP_HEADER); + curlx_dyn_init(&canonical_path, CURL_MAX_HTTP_HEADER); + + result = make_headers(data, timestamp, + curlx_str(provider1), curlx_strlen(provider1), + date_header_out, content_sha256_hdr, + canonical_headers, signed_headers); + if(result) + goto fail; + + result = canon_query(data->state.up.query, &canonical_query); + if(result) + goto fail; + + result = canon_path(data->state.up.path, strlen(data->state.up.path), + &canonical_path, + should_urlencode(service)); + if(result) + goto fail; + + *canonical_request_out = + curl_maprintf("%s\n" /* HTTPRequestMethod */ + "%s\n" /* CanonicalURI */ + "%s\n" /* CanonicalQueryString */ + "%s\n" /* CanonicalHeaders */ + "%s\n" /* SignedHeaders */ + "%.*s", /* HashedRequestPayload in hex */ + method, + curlx_dyn_ptr(&canonical_path), + curlx_dyn_ptr(&canonical_query) ? + curlx_dyn_ptr(&canonical_query) : "", + curlx_dyn_ptr(canonical_headers), + curlx_dyn_ptr(signed_headers), + (int)payload_hash_len, payload_hash); + if(!*canonical_request_out) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + result = CURLE_OK; +fail: + curlx_dyn_free(&canonical_query); + curlx_dyn_free(&canonical_path); + return result; +} + +static CURLcode make_string_to_sign(struct Curl_easy *data, + struct Curl_str *provider0, + struct Curl_str *region, + struct Curl_str *service, + const char *date, + const char *timestamp, + const char *canonical_request, + char **request_type_out, + char **credential_scope_out, + char **str_to_sign_out) +{ + char *request_type; + char *credential_scope; + char *str_to_sign; + unsigned char sha_hash[CURL_SHA256_DIGEST_LENGTH]; + char sha_hex[SHA256_HEX_LENGTH]; + + request_type = curl_maprintf("%.*s4_request", + (int)curlx_strlen(provider0), + curlx_str(provider0)); + if(!request_type) + return CURLE_OUT_OF_MEMORY; + + /* provider0 is lowercased *after* curl_maprintf() so that the buffer + can be written to */ + Curl_strntolower(request_type, request_type, curlx_strlen(provider0)); + + credential_scope = curl_maprintf("%s/%.*s/%.*s/%s", date, + (int)curlx_strlen(region), + curlx_str(region), + (int)curlx_strlen(service), + curlx_str(service), + request_type); + if(!credential_scope) { + curlx_free(request_type); + return CURLE_OUT_OF_MEMORY; + } + + if(Curl_sha256it(sha_hash, (const unsigned char *)canonical_request, + strlen(canonical_request))) { + curlx_free(request_type); + curlx_free(credential_scope); + return CURLE_OUT_OF_MEMORY; + } + + sha256_to_hex(sha_hex, sha_hash); + + /* + * Google allows using RSA key instead of HMAC, so this code might change + * in the future. For now we only support HMAC. + */ + str_to_sign = curl_maprintf("%.*s4-HMAC-SHA256\n" /* Algorithm */ + "%s\n" /* RequestDateTime */ + "%s\n" /* CredentialScope */ + "%s", /* HashedCanonicalRequest in hex */ + (int)curlx_strlen(provider0), + curlx_str(provider0), + timestamp, + credential_scope, + sha_hex); + if(!str_to_sign) { + curlx_free(request_type); + curlx_free(credential_scope); + return CURLE_OUT_OF_MEMORY; + } + + /* make provider0 part done uppercase */ + Curl_strntoupper(str_to_sign, curlx_str(provider0), + curlx_strlen(provider0)); + + infof(data, "aws_sigv4: String to sign (enclosed in []) - [%s]", + str_to_sign); + + *request_type_out = request_type; + *credential_scope_out = credential_scope; + *str_to_sign_out = str_to_sign; + return CURLE_OK; +} + +static CURLcode sign_and_set_auth_headers(struct Curl_easy *data, + struct Curl_str *provider0, + struct Curl_str *region, + struct Curl_str *service, + const char *request_type, + const char *credential_scope, + const char *date, + const char *str_to_sign, + const char *date_header, + const char *content_sha256_hdr, + struct dynbuf *signed_headers) +{ + CURLcode result = CURLE_OUT_OF_MEMORY; + const char *passwd = Curl_creds_passwd(data->state.creds); + char *secret = NULL; + unsigned char sign0[CURL_SHA256_DIGEST_LENGTH] = { 0 }; + unsigned char sign1[CURL_SHA256_DIGEST_LENGTH] = { 0 }; + char sha_hex[SHA256_HEX_LENGTH]; + char *auth_headers = NULL; + char *user = curl_escape(Curl_creds_user(data->state.creds), 0); + if(!user) + return CURLE_OUT_OF_MEMORY; + + secret = curl_maprintf("%.*s4%s", (int)curlx_strlen(provider0), + curlx_str(provider0), passwd); + if(!secret) + goto fail; + /* make provider0 part done uppercase */ + Curl_strntoupper(secret, curlx_str(provider0), curlx_strlen(provider0)); + + HMAC_SHA256(secret, strlen(secret), date, strlen(date), sign0); + HMAC_SHA256(sign0, sizeof(sign0), + curlx_str(region), curlx_strlen(region), sign1); + HMAC_SHA256(sign1, sizeof(sign1), + curlx_str(service), curlx_strlen(service), sign0); + HMAC_SHA256(sign0, sizeof(sign0), + request_type, strlen(request_type), sign1); + HMAC_SHA256(sign1, sizeof(sign1), + str_to_sign, strlen(str_to_sign), sign0); + + sha256_to_hex(sha_hex, sign0); + + infof(data, "aws_sigv4: Signature - %s", sha_hex); + + auth_headers = curl_maprintf("Authorization: %.*s4-HMAC-SHA256 " + "Credential=%s/%s, " + "SignedHeaders=%s, " + "Signature=%s\r\n" + "%s" + "%s%s", + (int)curlx_strlen(provider0), + curlx_str(provider0), + user, + credential_scope, + curlx_dyn_ptr(signed_headers), + sha_hex, + /* + * date_header is added here, only if it was not + * user-specified (using CURLOPT_HTTPHEADER). + * date_header includes \r\n + */ + date_header ? date_header : "", + content_sha256_hdr, + content_sha256_hdr[0] ? "\r\n": ""); + if(!auth_headers) + goto fail; + + /* provider 0 uppercase */ + Curl_strntoupper(&auth_headers[CURL_CSTRLEN("Authorization: ")], + curlx_str(provider0), curlx_strlen(provider0)); + + curlx_free(data->req.hd_auth); + data->req.hd_auth = auth_headers; + data->state.authhost.done = TRUE; + result = CURLE_OK; + +fail: + curlx_free(user); + curlx_free(secret); + return result; +} + +CURLcode Curl_output_aws_sigv4(struct Curl_easy *data) +{ + CURLcode result = CURLE_OUT_OF_MEMORY; + struct Curl_str provider0 = { NULL, 0 }; + struct Curl_str provider1 = { NULL, 0 }; + struct Curl_str region = { NULL, 0 }; + struct Curl_str service = { NULL, 0 }; + const char *hostname = data->state.origin->hostname; + char timestamp[TIMESTAMP_SIZE]; + char date[9]; + struct dynbuf canonical_headers; + struct dynbuf signed_headers; + char *date_header = NULL; + Curl_HttpReq httpreq; + const char *method = NULL; + const char *payload_hash = NULL; + size_t payload_hash_len = 0; + unsigned char sha_hash[CURL_SHA256_DIGEST_LENGTH]; + char sha_hex[SHA256_HEX_LENGTH]; + char content_sha256_hdr[CONTENT_SHA256_HDR_LEN + 2] = ""; /* add \r\n */ + char *canonical_request = NULL; + char *request_type = NULL; + char *credential_scope = NULL; + char *str_to_sign = NULL; + + if(data->set.path_as_is) { + failf(data, "Cannot use sigv4 authentication with path-as-is flag"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + if(Curl_checkheaders(data, STRCONST("Authorization"))) + /* Authorization already present, Bailing out */ + return CURLE_OK; + + /* we init those buffers here, so goto fail will free initialized dynbuf */ + curlx_dyn_init(&canonical_headers, CURL_MAX_HTTP_HEADER); + curlx_dyn_init(&signed_headers, CURL_MAX_HTTP_HEADER); + + result = parse_sigv4_params(data, hostname, &provider0, &provider1, + ®ion, &service); + if(!result) { + Curl_http_method(data, &method, &httpreq); + result = get_payload_hash(data, httpreq, &provider0, &provider1, &service, + sha_hash, sha_hex, content_sha256_hdr, + &payload_hash, &payload_hash_len); + } + + if(!result) + result = get_timestamp(timestamp, sizeof(timestamp)); + + if(!result) + result = make_canonical_request(data, timestamp, + &provider1, &service, + method, payload_hash, payload_hash_len, + &date_header, content_sha256_hdr, + &canonical_headers, &signed_headers, + &canonical_request); + if(!result) { + /* the timestamp might have been updated in make_canonical_request */ + memcpy(date, timestamp, sizeof(date) - 1); + date[sizeof(date) - 1] = 0; + + result = make_string_to_sign(data, &provider0, ®ion, &service, + date, timestamp, canonical_request, + &request_type, &credential_scope, + &str_to_sign); + } + if(!result) + result = sign_and_set_auth_headers(data, &provider0, ®ion, &service, + request_type, credential_scope, + date, str_to_sign, date_header, + content_sha256_hdr, &signed_headers); + + curlx_dyn_free(&canonical_headers); + curlx_dyn_free(&signed_headers); + curlx_free(canonical_request); + curlx_free(request_type); + curlx_free(credential_scope); + curlx_free(str_to_sign); + curlx_free(date_header); + return result; +} + +#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_AWS */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_aws_sigv4.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_aws_sigv4.h new file mode 100644 index 0000000000..7dd002476a --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_aws_sigv4.h @@ -0,0 +1,34 @@ +#ifndef HEADER_CURL_HTTP_AWS_SIGV4_H +#define HEADER_CURL_HTTP_AWS_SIGV4_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curlx/dynbuf.h" +#include "urldata.h" + +/* this is for creating aws_sigv4 header output */ +CURLcode Curl_output_aws_sigv4(struct Curl_easy *data); + +#endif /* HEADER_CURL_HTTP_AWS_SIGV4_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_chunks.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_chunks.c new file mode 100644 index 0000000000..95929d27ba --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_chunks.c @@ -0,0 +1,685 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_HTTP + +#include "urldata.h" /* it includes http_chunks.h */ +#include "curl_trc.h" +#include "http.h" /* for Curl_verify_header */ +#include "sendf.h" /* for the client write stuff */ +#include "curlx/dynbuf.h" +#include "multiif.h" +#include "curlx/strparse.h" + +/* + Chunk format (simplified): + + <HEX SIZE>[ chunk extension ] CRLF + <DATA> CRLF + + Highlights from RFC2616 section 3.6 say: + + The chunked encoding modifies the body of a message in order to + transfer it as a series of chunks, each with its own size indicator, + followed by an OPTIONAL trailer containing entity-header fields. This + allows dynamically produced content to be transferred along with the + information necessary for the recipient to verify that it has + received the full message. + + Chunked-Body = *chunk + last-chunk + trailer + CRLF + + chunk = chunk-size [ chunk-extension ] CRLF + chunk-data CRLF + chunk-size = 1*HEX + last-chunk = 1*("0") [ chunk-extension ] CRLF + + chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] ) + chunk-ext-name = token + chunk-ext-val = token | quoted-string + chunk-data = chunk-size(OCTET) + trailer = *(entity-header CRLF) + + The chunk-size field is a string of hex digits indicating the size of + the chunk. The chunked encoding is ended by any chunk whose size is + zero, followed by the trailer, which is terminated by an empty line. + + */ + +void Curl_httpchunk_init(struct Curl_easy *data, struct Curl_chunker *ch, + bool ignore_body, bool in_connect) +{ + (void)data; + ch->hexindex = 0; /* start at 0 */ + ch->state = CHUNK_HEX; /* we get hex first! */ + ch->last_code = CHUNKE_OK; + curlx_dyn_init(&ch->trailer, DYN_H1_TRAILER); + ch->ignore_body = ignore_body; + ch->in_connect = in_connect; +} + +void Curl_httpchunk_reset(struct Curl_easy *data, struct Curl_chunker *ch, + bool ignore_body) +{ + (void)data; + ch->hexindex = 0; /* start at 0 */ + ch->state = CHUNK_HEX; /* we get hex first! */ + ch->last_code = CHUNKE_OK; + curlx_dyn_reset(&ch->trailer); + ch->ignore_body = ignore_body; +} + +void Curl_httpchunk_free(struct Curl_easy *data, struct Curl_chunker *ch) +{ + (void)data; + curlx_dyn_free(&ch->trailer); +} + +bool Curl_httpchunk_is_done(struct Curl_easy *data, struct Curl_chunker *ch) +{ + (void)data; + return ch->state == CHUNK_DONE; +} + +static CURLcode httpchunk_readwrite(struct Curl_easy *data, + struct Curl_chunker *ch, + struct Curl_cwriter *cw_next, + const char *buf, size_t blen, + size_t *pconsumed) +{ + CURLcode result = CURLE_OK; + size_t piece; + + *pconsumed = 0; /* nothing's written yet */ + /* first check terminal states that will not progress anywhere */ + if(ch->state == CHUNK_DONE) + return CURLE_OK; + if(ch->state == CHUNK_FAILED) + return CURLE_RECV_ERROR; + + /* the original data is written to the client, but we go on with the + chunk read process, to properly calculate the content length */ + if(data->set.http_te_skip && !ch->ignore_body) { + if(cw_next) + result = Curl_cwriter_write(data, cw_next, CLIENTWRITE_BODY, buf, blen); + else + result = Curl_client_write(data, CLIENTWRITE_BODY, buf, blen); + if(result) { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_PASSTHRU_ERROR; + return result; + } + } + + while(blen) { + switch(ch->state) { + case CHUNK_HEX: + if(ISXDIGIT(*buf)) { + if(ch->hexindex >= CHUNK_MAXNUM_LEN) { + failf(data, "chunk hex-length longer than %d", CHUNK_MAXNUM_LEN); + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_TOO_LONG_HEX; /* longer than we support */ + return CURLE_RECV_ERROR; + } + ch->hexbuffer[ch->hexindex++] = *buf; + buf++; + blen--; + (*pconsumed)++; + } + else { + const char *p; + if(ch->hexindex == 0) { + /* This is illegal data, we received junk where we expected + a hexadecimal digit. */ + failf(data, "chunk hex-length char not a hex digit: 0x%x", + (unsigned int)*buf); + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_ILLEGAL_HEX; + return CURLE_RECV_ERROR; + } + /* blen and buf are unmodified */ + ch->hexbuffer[ch->hexindex] = 0; + p = &ch->hexbuffer[0]; + if(curlx_str_hex(&p, &ch->datasize, CURL_OFF_T_MAX)) { + failf(data, "invalid chunk size: '%s'", ch->hexbuffer); + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_ILLEGAL_HEX; + return CURLE_RECV_ERROR; + } + ch->state = CHUNK_LF; /* now wait for the CRLF */ + } + break; + + case CHUNK_LF: + /* waiting for the LF after a chunk size */ + if(*buf == 0x0a) { + /* we are now expecting data to come, unless size was zero! */ + if(ch->datasize == 0) { + ch->state = CHUNK_TRAILER; /* now check for trailers */ + } + else { + ch->state = CHUNK_DATA; + CURL_TRC_WRITE(data, "http_chunked, chunk start of %" + FMT_OFF_T " bytes", ch->datasize); + } + } + + buf++; + blen--; + (*pconsumed)++; + break; + + case CHUNK_DATA: + /* We expect 'datasize' of data. We have 'blen' right now, it can be + more or less than 'datasize'. Get the smallest piece. */ + piece = blen; + if(ch->datasize < (curl_off_t)blen) + piece = curlx_sotouz(ch->datasize); + + /* Write the data portion available */ + if(!data->set.http_te_skip && !ch->ignore_body) { + if(cw_next) + result = Curl_cwriter_write(data, cw_next, CLIENTWRITE_BODY, + buf, piece); + else + result = Curl_client_write(data, CLIENTWRITE_BODY, buf, piece); + if(result) { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_PASSTHRU_ERROR; + return result; + } + } + + *pconsumed += piece; + ch->datasize -= piece; /* decrease amount left to expect */ + buf += piece; /* move read pointer forward */ + blen -= piece; /* decrease space left in this round */ + CURL_TRC_WRITE(data, "http_chunked, write %zu body bytes, %" + FMT_OFF_T " bytes in chunk remain", + piece, ch->datasize); + + if(ch->datasize == 0) + /* end of data this round, we now expect a trailing CRLF */ + ch->state = CHUNK_POSTLF; + break; + + case CHUNK_POSTLF: + if(*buf == 0x0a) { + /* The last one before we go back to hex state and start all over. */ + Curl_httpchunk_reset(data, ch, (bool)ch->ignore_body); + } + else if(*buf != 0x0d) { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_BAD_CHUNK; + return CURLE_RECV_ERROR; + } + buf++; + blen--; + (*pconsumed)++; + break; + + case CHUNK_TRAILER: + if((*buf == 0x0d) || (*buf == 0x0a)) { + const char *tr = curlx_dyn_ptr(&ch->trailer); + /* this is the end of a trailer, but if the trailer was zero bytes + there was no trailer and we move on */ + + if(tr) { + size_t trlen; + result = curlx_dyn_addn(&ch->trailer, STRCONST("\x0d\x0a")); + if(result) { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_OUT_OF_MEMORY; + return result; + } + tr = curlx_dyn_ptr(&ch->trailer); + trlen = curlx_dyn_len(&ch->trailer); + + /* a trailer is delivered to the client as a header, so it must pass + the same checks as a regular response header */ + result = Curl_verify_header(data, tr, trlen); + if(result) { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_BAD_CHUNK; + return result; + } + + if(!data->set.http_te_skip) { + int hd_type = CLIENTWRITE_HEADER | CLIENTWRITE_TRAILER; + if(ch->in_connect) + hd_type |= CLIENTWRITE_CONNECT; + if(cw_next) + result = Curl_cwriter_write(data, cw_next, hd_type, tr, trlen); + else + result = Curl_client_write(data, hd_type, tr, trlen); + CURL_TRC_WRITE(data, "wrote trailer '%s'", tr); + if(result) { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_PASSTHRU_ERROR; + return result; + } + } + curlx_dyn_reset(&ch->trailer); + ch->state = CHUNK_TRAILER_CR; + if(*buf == 0x0a) + /* already on the LF */ + break; + } + else { + /* no trailer, we are on the final CRLF pair */ + ch->state = CHUNK_TRAILER_POSTCR; + break; /* do not advance the pointer */ + } + } + else { + result = curlx_dyn_addn(&ch->trailer, buf, 1); + if(result) { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_OUT_OF_MEMORY; + return result; + } + } + buf++; + blen--; + (*pconsumed)++; + break; + + case CHUNK_TRAILER_CR: + if(*buf == 0x0a) { + ch->state = CHUNK_TRAILER_POSTCR; + buf++; + blen--; + (*pconsumed)++; + } + else { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_BAD_CHUNK; + return CURLE_RECV_ERROR; + } + break; + + case CHUNK_TRAILER_POSTCR: + /* We enter this state when a CR should arrive so we expect to + have to first pass a CR before we wait for LF */ + if((*buf != 0x0d) && (*buf != 0x0a)) { + /* not a CR then it must be another header in the trailer */ + ch->state = CHUNK_TRAILER; + break; + } + if(*buf == 0x0d) { + /* skip if CR */ + buf++; + blen--; + (*pconsumed)++; + } + /* now wait for the final LF */ + ch->state = CHUNK_STOP; + break; + + case CHUNK_STOP: + if(*buf == 0x0a) { + blen--; + (*pconsumed)++; + /* Record the length of any data left in the end of the buffer + even if there is no more chunks to read */ + ch->datasize = blen; + ch->state = CHUNK_DONE; + CURL_TRC_WRITE(data, "http_chunk, response complete"); + return CURLE_OK; + } + else { + ch->state = CHUNK_FAILED; + ch->last_code = CHUNKE_BAD_CHUNK; + CURL_TRC_WRITE(data, "http_chunk error, expected 0x0a, seeing 0x%ux", + (unsigned int)*buf); + return CURLE_RECV_ERROR; + } + case CHUNK_DONE: + return CURLE_OK; + + case CHUNK_FAILED: + return CURLE_RECV_ERROR; + } + } + return CURLE_OK; +} + +static const char *Curl_chunked_strerror(CHUNKcode code) +{ + switch(code) { + default: + return "OK"; + case CHUNKE_TOO_LONG_HEX: + return "Too long hexadecimal number"; + case CHUNKE_ILLEGAL_HEX: + return "Illegal or missing hexadecimal sequence"; + case CHUNKE_BAD_CHUNK: + return "Malformed encoding found"; + case CHUNKE_PASSTHRU_ERROR: + return "Error writing data to client"; + case CHUNKE_BAD_ENCODING: + return "Bad content-encoding found"; + case CHUNKE_OUT_OF_MEMORY: + return "Out of memory"; + } +} + +CURLcode Curl_httpchunk_read(struct Curl_easy *data, + struct Curl_chunker *ch, + char *buf, size_t blen, + size_t *pconsumed) +{ + return httpchunk_readwrite(data, ch, NULL, buf, blen, pconsumed); +} + +struct chunked_writer { + struct Curl_cwriter super; + struct Curl_chunker ch; +}; + +static CURLcode cw_chunked_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct chunked_writer *ctx = writer->ctx; + + data->req.chunk = TRUE; /* chunks coming our way. */ + Curl_httpchunk_init(data, &ctx->ch, FALSE, FALSE); + return CURLE_OK; +} + +static void cw_chunked_close(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct chunked_writer *ctx = writer->ctx; + Curl_httpchunk_free(data, &ctx->ch); +} + +static CURLcode cw_chunked_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t blen) +{ + struct chunked_writer *ctx = writer->ctx; + CURLcode result; + size_t consumed; + + if(!(type & CLIENTWRITE_BODY)) + return Curl_cwriter_write(data, writer->next, type, buf, blen); + + consumed = 0; + result = httpchunk_readwrite(data, &ctx->ch, writer->next, buf, blen, + &consumed); + + if(result) { + if(CHUNKE_PASSTHRU_ERROR == ctx->ch.last_code) { + failf(data, "Failed reading the chunked-encoded stream"); + } + else { + failf(data, "%s in chunked-encoding", + Curl_chunked_strerror(ctx->ch.last_code)); + } + return result; + } + + blen -= consumed; + if(CHUNK_DONE == ctx->ch.state) { + /* chunks read successfully, download is complete */ + data->req.download_done = TRUE; + if(blen) { + infof(data, "Leftovers after chunking: %zu bytes", blen); + } + } + else if((type & CLIENTWRITE_EOS) && !data->req.no_body) { + failf(data, "transfer closed with outstanding read data remaining"); + return CURLE_PARTIAL_FILE; + } + + return CURLE_OK; +} + +/* HTTP chunked Transfer-Encoding decoder */ +const struct Curl_cwtype Curl_httpchunk_unencoder = { + "chunked", + NULL, + 0, + cw_chunked_init, + cw_chunked_write, + Curl_cwriter_def_flush, + cw_chunked_close, + sizeof(struct chunked_writer) +}; + +/* max length of an HTTP chunk that we want to generate */ +#define CURL_CHUNKED_MINLEN 1024 +#define CURL_CHUNKED_MAXLEN (64 * 1024) + +struct chunked_reader { + struct Curl_creader super; + struct bufq chunkbuf; + BIT(read_eos); /* we read an EOS from the next reader */ + BIT(eos); /* we have returned an EOS */ +}; + +static CURLcode cr_chunked_init(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct chunked_reader *ctx = reader->ctx; + (void)data; + Curl_bufq_init2(&ctx->chunkbuf, CURL_CHUNKED_MAXLEN, 2, BUFQ_OPT_SOFT_LIMIT); + return CURLE_OK; +} + +static void cr_chunked_close(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct chunked_reader *ctx = reader->ctx; + (void)data; + Curl_bufq_free(&ctx->chunkbuf); +} + +static CURLcode add_last_chunk(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct chunked_reader *ctx = reader->ctx; + struct curl_slist *trailers = NULL, *tr; + CURLcode result; + size_t n; + int rc; + + if(!data->set.trailer_callback) { + CURL_TRC_READ(data, "http_chunk, added last, empty chunk"); + return Curl_bufq_cwrite(&ctx->chunkbuf, STRCONST("0\r\n\r\n"), &n); + } + + result = Curl_bufq_cwrite(&ctx->chunkbuf, STRCONST("0\r\n"), &n); + if(result) + goto out; + + { + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_trailer_callback); + rc = data->set.trailer_callback(&trailers, data->set.trailer_data); + CURL_CBAPI_END(&guard); + } + + if(rc != CURL_TRAILERFUNC_OK) { + failf(data, "operation aborted by trailing headers callback"); + result = CURLE_ABORTED_BY_CALLBACK; + goto out; + } + + for(tr = trailers; tr; tr = tr->next) { + /* only add correctly formatted trailers */ + const char *ptr = strchr(tr->data, ':'); + if(!ptr || *(ptr + 1) != ' ') { + infof(data, "Malformatted trailing header, skipping trailer"); + continue; + } + + result = Curl_bufq_cwrite(&ctx->chunkbuf, tr->data, strlen(tr->data), &n); + if(!result) + result = Curl_bufq_cwrite(&ctx->chunkbuf, STRCONST("\r\n"), &n); + if(result) + goto out; + } + + result = Curl_bufq_cwrite(&ctx->chunkbuf, STRCONST("\r\n"), &n); + +out: + curl_slist_free_all(trailers); + CURL_TRC_READ(data, "http_chunk, added last chunk with trailers " + "from client -> %d", (int)result); + return result; +} + +static CURLcode add_chunk(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen) +{ + struct chunked_reader *ctx = reader->ctx; + CURLcode result; + char tmp[CURL_CHUNKED_MINLEN]; + size_t nread; + bool eos; + + DEBUGASSERT(!ctx->read_eos); + blen = CURLMIN(blen, CURL_CHUNKED_MAXLEN); /* respect our buffer pref */ + if(blen < sizeof(tmp)) { + /* small read, make a chunk of decent size */ + buf = tmp; + blen = sizeof(tmp); + } + else { + /* larger read, make a chunk that will fit when read back */ + blen -= (8 + 2 + 2); /* deduct max overhead, 8 hex + 2*crlf */ + } + + result = Curl_creader_read(data, reader->next, buf, blen, &nread, &eos); + if(result) + return result; + if(eos) + ctx->read_eos = TRUE; + + if(nread) { + /* actually got bytes, wrap them into the chunkbuf */ + char hd[11] = ""; + int hdlen; + size_t n; + + hdlen = curl_msnprintf(hd, sizeof(hd), "%zx\r\n", nread); + if(hdlen <= 0) + return CURLE_READ_ERROR; + /* On a soft-limited bufq, we do not need to check that all was written */ + result = Curl_bufq_cwrite(&ctx->chunkbuf, hd, hdlen, &n); + if(!result) + result = Curl_bufq_cwrite(&ctx->chunkbuf, buf, nread, &n); + if(!result) + result = Curl_bufq_cwrite(&ctx->chunkbuf, "\r\n", 2, &n); + CURL_TRC_READ(data, "http_chunk, made chunk of %zu bytes -> %d", + nread, (int)result); + if(result) + return result; + } + + if(ctx->read_eos) + return add_last_chunk(data, reader); + return CURLE_OK; +} + +static CURLcode cr_chunked_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + struct chunked_reader *ctx = reader->ctx; + CURLcode result = CURLE_READ_ERROR; + + *pnread = 0; + *peos = (bool)ctx->eos; + + if(!ctx->eos) { + if(!ctx->read_eos && Curl_bufq_is_empty(&ctx->chunkbuf)) { + /* Still getting data form the next reader, buffer is empty */ + result = add_chunk(data, reader, buf, blen); + if(result) + return result; + } + + if(!Curl_bufq_is_empty(&ctx->chunkbuf)) { + result = Curl_bufq_cread(&ctx->chunkbuf, buf, blen, pnread); + if(!result && ctx->read_eos && Curl_bufq_is_empty(&ctx->chunkbuf)) { + /* no more data, read all, done. */ + ctx->eos = TRUE; + *peos = TRUE; + } + return result; + } + } + /* We may get here, because we are done or because callbacks paused */ + DEBUGASSERT(ctx->eos || !ctx->read_eos); + return CURLE_OK; +} + +static curl_off_t cr_chunked_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + /* this reader changes length depending on input */ + (void)data; + (void)reader; + return -1; +} + +/* HTTP chunked Transfer-Encoding encoder */ +const struct Curl_crtype Curl_httpchunk_encoder = { + "chunked", + cr_chunked_init, + cr_chunked_read, + cr_chunked_close, + Curl_creader_def_needs_rewind, + cr_chunked_total_length, + Curl_creader_def_resume_from, + Curl_creader_def_cntrl, + Curl_creader_def_is_paused, + Curl_creader_def_done, + sizeof(struct chunked_reader) +}; + +CURLcode Curl_httpchunk_add_reader(struct Curl_easy *data) +{ + struct Curl_creader *reader = NULL; + CURLcode result; + + result = Curl_creader_create(&reader, data, &Curl_httpchunk_encoder, + CURL_CR_TRANSFER_ENCODE); + if(!result) + result = Curl_creader_add(data, reader); + + if(result && reader) + Curl_creader_free(data, reader); + return result; +} + +#endif /* CURL_DISABLE_HTTP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_chunks.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_chunks.h new file mode 100644 index 0000000000..0cb1f88340 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_chunks.h @@ -0,0 +1,147 @@ +#ifndef HEADER_CURL_HTTP_CHUNKS_H +#define HEADER_CURL_HTTP_CHUNKS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_HTTP + +#include "curlx/dynbuf.h" + +struct connectdata; + +/* + * The longest possible hexadecimal number we support in a chunked transfer. + * Neither RFC2616 nor the later HTTP specs define a maximum chunk size. + * For 64-bit curl_off_t we support 16 digits. For 32-bit, 8 digits. + */ +#define CHUNK_MAXNUM_LEN (SIZEOF_CURL_OFF_T * 2) + +typedef enum { + /* await and buffer all hexadecimal digits until we get one that is not a + hexadecimal digit. When done, we go CHUNK_LF */ + CHUNK_HEX, + + /* wait for LF, ignore all else */ + CHUNK_LF, + + /* We eat the amount of data specified. When done, we move on to the + POST_CR state. */ + CHUNK_DATA, + + /* POSTLF should get a CR and then an LF and nothing else, then move back to + HEX as the CRLF combination marks the end of a chunk. A missing CR is no + big deal. */ + CHUNK_POSTLF, + + /* Used to mark that we are out of the game. NOTE: that there is a + 'datasize' field in the struct that will tell how many bytes that were + not passed to the client in the end of the last buffer! */ + CHUNK_STOP, + + /* At this point optional trailer headers can be found, unless the next line + is CRLF */ + CHUNK_TRAILER, + + /* A trailer CR has been found - next state is CHUNK_TRAILER_POSTCR. + Next char must be an LF */ + CHUNK_TRAILER_CR, + + /* A trailer LF must be found now, otherwise CHUNKE_BAD_CHUNK will be + signalled If this is an empty trailer CHUNKE_STOP will be signalled. + Otherwise the trailer will be broadcasted via Curl_client_write() and the + next state will be CHUNK_TRAILER */ + CHUNK_TRAILER_POSTCR, + + /* Successfully de-chunked everything */ + CHUNK_DONE, + + /* Failed on seeing a bad or not correctly terminated chunk */ + CHUNK_FAILED +} ChunkyState; + +typedef enum { + CHUNKE_OK = 0, + CHUNKE_TOO_LONG_HEX = 1, + CHUNKE_ILLEGAL_HEX, + CHUNKE_BAD_CHUNK, + CHUNKE_BAD_ENCODING, + CHUNKE_OUT_OF_MEMORY, + CHUNKE_PASSTHRU_ERROR /* Curl_httpchunk_read() returns a CURLcode to use */ +} CHUNKcode; + +struct Curl_chunker { + curl_off_t datasize; + ChunkyState state; + CHUNKcode last_code; + struct dynbuf trailer; /* for chunked-encoded trailer */ + unsigned char hexindex; + char hexbuffer[CHUNK_MAXNUM_LEN + 1]; /* +1 for null-terminator */ + BIT(ignore_body); /* never write response body data */ + BIT(in_connect); /* this is a CONNECT response body */ +}; + +/* The following functions are defined in http_chunks.c */ +void Curl_httpchunk_init(struct Curl_easy *data, struct Curl_chunker *ch, + bool ignore_body, bool in_connect); +void Curl_httpchunk_free(struct Curl_easy *data, struct Curl_chunker *ch); +void Curl_httpchunk_reset(struct Curl_easy *data, struct Curl_chunker *ch, + bool ignore_body); + +/* + * Read BODY bytes in HTTP/1.1 chunked encoding from `buf` and return + * the amount of bytes consumed. The actual response bytes and trailer + * headers are written out to the client. + * On success, this will consume all bytes up to the end of the response, + * e.g. the last chunk, has been processed. + * @param data the transfer involved + * @param ch the chunker instance keeping state across calls + * @param buf the response data + * @param blen amount of bytes in `buf` + * @param pconsumed on successful return, the number of bytes in `buf` + * consumed + * + * This function always uses ASCII hex values to accommodate non-ASCII hosts. + * For example, 0x0d and 0x0a are used instead of '\r' and '\n'. + */ +CURLcode Curl_httpchunk_read(struct Curl_easy *data, struct Curl_chunker *ch, + char *buf, size_t blen, size_t *pconsumed); + +/** + * @return TRUE iff chunked decoded has finished successfully. + */ +bool Curl_httpchunk_is_done(struct Curl_easy *data, struct Curl_chunker *ch); + +extern const struct Curl_cwtype Curl_httpchunk_unencoder; + +extern const struct Curl_crtype Curl_httpchunk_encoder; + +/** + * Add a transfer-encoding "chunked" reader to the transfers reader stack + */ +CURLcode Curl_httpchunk_add_reader(struct Curl_easy *data); + +#endif /* !CURL_DISABLE_HTTP */ + +#endif /* HEADER_CURL_HTTP_CHUNKS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_digest.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_digest.c new file mode 100644 index 0000000000..1ec29bd391 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_digest.c @@ -0,0 +1,188 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_DIGEST_AUTH) + +#include "urldata.h" +#include "curl_trc.h" +#include "strcase.h" +#include "vauth/vauth.h" +#include "http_digest.h" +#include "curlx/strparse.h" + +/* Flush the Digest state if it was created for a different origin or with + different credentials than the ones now in use, then link the current + ones. */ +static void digest_flush_stale(struct Curl_easy *data, + struct digestdata *digest, + struct Curl_peer *peer, + struct Curl_creds *creds) +{ + bool flush = FALSE; + if(digest->origin && !Curl_peer_same_destination(peer, digest->origin)) { + CURL_TRC_M(data, "http_digest, reset on peer change to %s:%u", + peer->hostname, peer->port); + flush = TRUE; + } + else if(digest->creds && !Curl_creds_same(creds, digest->creds)) { + CURL_TRC_M(data, "http_digest, reset on creds change to %s", + creds ? creds->user : "-"); + flush = TRUE; + } + + if(flush) { + /* flush Digest state */ + Curl_auth_digest_cleanup(digest); + } + + Curl_peer_link(&digest->origin, peer); + Curl_creds_link(&digest->creds, creds); +} + +/* Test example headers: + + WWW-Authenticate: Digest realm="testrealm", nonce="1053604598" + Proxy-Authenticate: Digest realm="testrealm", nonce="1053604598" + */ +CURLcode Curl_input_digest(struct Curl_easy *data, + bool proxy, + const char *header) /* rest of the *-authenticate: + header */ +{ + /* Point to the correct struct with this */ + struct digestdata *digest; + struct Curl_peer *origin = NULL; + CURLcode result; + + if(proxy) { + digest = &data->state.proxydigest; +#ifdef CURL_DISABLE_PROXY + Curl_auth_digest_cleanup(digest); + return CURLE_OK; /* just ignore such a header without proxy support */ +#else + origin = data->conn->http_proxy.peer; +#endif + } + else { + digest = &data->state.digest; + origin = data->state.origin; + } + + if(!checkprefix("Digest", header) || !ISBLANK(header[6])) { + Curl_auth_digest_cleanup(digest); + return CURLE_AUTH_ERROR; + } + + header += CURL_CSTRLEN("Digest"); + curlx_str_passblanks(&header); + + /* This resets the digest struct before decoding */ + result = Curl_auth_decode_digest_http_message(header, digest); + /* Remember only the peer, the data we take in has no relation to creds + * at this time. We can use it even if creds change. */ + Curl_peer_link(&digest->origin, origin); + return result; +} + +CURLcode Curl_output_digest(struct Curl_easy *data, + bool proxy, + const unsigned char *request, + const unsigned char *uripath) +{ + struct Curl_peer *origin = NULL; + CURLcode result; + char *response; + size_t len; + bool have_chlg; + + /* Point to the address of the pointer that holds the string to send to the + server, which is for a plain host or for an HTTP proxy */ + char **allocuserpwd; + + /* Point to the name and password for this */ + struct Curl_creds *creds = NULL; + + /* Point to the correct struct with this */ + struct digestdata *digest; + struct auth *authp; + + if(proxy) { +#ifdef CURL_DISABLE_PROXY + return CURLE_NOT_BUILT_IN; +#else + digest = &data->state.proxydigest; + origin = data->conn->http_proxy.peer; + creds = data->conn->http_proxy.creds; + allocuserpwd = &data->req.hd_proxy_auth; + authp = &data->state.authproxy; +#endif + } + else { + DEBUGASSERT(data->state.origin); + digest = &data->state.digest; + origin = data->state.origin; + creds = data->state.creds; + allocuserpwd = &data->req.hd_auth; + authp = &data->state.authhost; + } + + digest_flush_stale(data, digest, origin, creds); + curlx_safefree(*allocuserpwd); + +#ifdef USE_WINDOWS_SSPI + have_chlg = !!digest->input_token; +#else + have_chlg = !!digest->nonce; +#endif + + if(!have_chlg) { + authp->done = FALSE; + return CURLE_OK; + } + + result = Curl_auth_create_digest_http_message(data, creds, request, + uripath, digest, + &response, &len); + if(result) + return result; + + *allocuserpwd = curl_maprintf("%sAuthorization: Digest %s\r\n", + proxy ? "Proxy-" : "", response); + curlx_free(response); + if(!*allocuserpwd) + return CURLE_OUT_OF_MEMORY; + + authp->done = TRUE; + + return CURLE_OK; +} + +void Curl_http_auth_cleanup_digest(struct Curl_easy *data) +{ + Curl_auth_digest_cleanup(&data->state.digest); + Curl_auth_digest_cleanup(&data->state.proxydigest); +} + +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_digest.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_digest.h new file mode 100644 index 0000000000..5f797310fd --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_digest.h @@ -0,0 +1,44 @@ +#ifndef HEADER_CURL_HTTP_DIGEST_H +#define HEADER_CURL_HTTP_DIGEST_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_DIGEST_AUTH) + +/* this is for digest header input */ +CURLcode Curl_input_digest(struct Curl_easy *data, + bool proxy, const char *header); + +/* this is for creating digest header output */ +CURLcode Curl_output_digest(struct Curl_easy *data, + bool proxy, + const unsigned char *request, + const unsigned char *uripath); + +void Curl_http_auth_cleanup_digest(struct Curl_easy *data); + +#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_DIGEST_AUTH */ + +#endif /* HEADER_CURL_HTTP_DIGEST_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_httpsig.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_httpsig.c new file mode 100644 index 0000000000..37f23a09cb --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_httpsig.c @@ -0,0 +1,689 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HTTPSIG) + +#include "urldata.h" +#include "http_httpsig.h" +#include "curl_ed25519.h" +#include "curl_hmac.h" +#include "curl_sha256.h" +#include "http.h" +#include "transfer.h" +#include "curl_trc.h" +#include "slist.h" +#include "curlx/dynbuf.h" +#include "curlx/base64.h" +#include "curlx/strdup.h" +#include "curlx/strparse.h" +#include "strcase.h" + +#include <time.h> + +#define HTTPSIG_MAX_SIG_BASE CURL_MAX_HTTP_HEADER +#define HTTPSIG_MAX_COMPONENTS 16 +#define HTTPSIG_MAX_RAW_SIG CURL_ED25519_SIGLEN +#define HTTPSIG_DEFAULT_LABEL "sig1" + +enum httpsig_alg { + HTTPSIG_ALG_ED25519, + HTTPSIG_ALG_HMAC_SHA256, + HTTPSIG_ALG_UNKNOWN +}; + +static const char *alg_to_str(enum httpsig_alg alg) +{ + switch(alg) { + case HTTPSIG_ALG_ED25519: + return "ed25519"; + case HTTPSIG_ALG_HMAC_SHA256: + return "hmac-sha256"; + default: + break; + } + return NULL; +} + +static enum httpsig_alg id_to_alg(uint8_t val) +{ + switch(val) { + case CURLHTTPSIG_ED25519: + return HTTPSIG_ALG_ED25519; + case CURLHTTPSIG_HMAC_SHA256: + return HTTPSIG_ALG_HMAC_SHA256; + default: + break; + } + return HTTPSIG_ALG_UNKNOWN; +} + +static CURLcode decode_hex_key(struct Curl_easy *data, + const char *hexstr, + unsigned char **keyout, + size_t *keylen) +{ + size_t len, i; + unsigned char *keybuf; + + *keyout = NULL; + *keylen = 0; + + len = strlen(hexstr); + while(len > 0 && ISNEWLINE(hexstr[len - 1])) + len--; + + if(len == 0 || (len & 1) != 0) { + failf(data, "httpsig: invalid hex key (length %zu)", len); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + if(len > CURL_MAX_INPUT_LENGTH) { + failf(data, "httpsig: hex key too long"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + keybuf = curlx_malloc(len / 2); + if(!keybuf) + return CURLE_OUT_OF_MEMORY; + + for(i = 0; i < len; i += 2) { + if(!ISXDIGIT(hexstr[i]) || !ISXDIGIT(hexstr[i + 1])) { + failf(data, "httpsig: invalid hex at position %zu ('%c%c')", + i, hexstr[i], hexstr[i + 1]); + curlx_free(keybuf); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + keybuf[i / 2] = (unsigned char)((curlx_hexval(hexstr[i]) << 4) | + curlx_hexval(hexstr[i + 1])); + } + + *keyout = keybuf; + *keylen = len / 2; + return CURLE_OK; +} + +/* @authority matches the Host header field-value when available (RFC 9421). + data->state.http_host is produced by http_set_aptr_host() before auth. */ +static CURLcode httpsig_authority(struct Curl_easy *data, + struct connectdata *conn, + struct dynbuf *authority_buf) +{ + const char *h = data->state.http_host; + + if(h && curl_strnequal(h, "host:", 5)) { + const char *value = h + 5; + const char *end; + + while(ISBLANK(*value)) + value++; + if(*value) { + CURLcode result; + + end = value; + while(*end && !ISNEWLINE(*end)) + end++; + while(end > value && ISBLANK(end[-1])) + end--; + result = curlx_dyn_addn(authority_buf, value, (size_t)(end - value)); + if(result) + return result; + return CURLE_OK; + } + } + + { + const char *hostname = conn->origin->hostname; + uint16_t port = conn->origin->port; + + if((conn->given->defport != port) && port) + return curlx_dyn_addf(authority_buf, "%s:%u", hostname, port); + return curlx_dyn_add(authority_buf, hostname); + } +} + +static CURLcode sf_append_quoted(struct dynbuf *buf, const char *str) +{ + CURLcode result = curlx_dyn_addn(buf, "\"", 1); + if(result) + return result; + while(*str) { + if(ISCNTRL(*str)) + return CURLE_BAD_FUNCTION_ARGUMENT; + if(*str == '\\' || *str == '"') { + result = curlx_dyn_addn(buf, "\\", 1); + if(result) + return result; + } + result = curlx_dyn_addn(buf, str, 1); + if(result) + return result; + str++; + } + return curlx_dyn_addn(buf, "\"", 1); +} + +/* base64-encode raw bytes into an RFC 8941 byte sequence (:base64:) */ +static CURLcode sf_encode_byte_seq(const unsigned char *raw, size_t rawlen, + struct dynbuf *out) +{ + CURLcode result; + size_t b64len; + char *b64; + + result = curlx_base64_encode(raw, rawlen, &b64, &b64len); + if(result) + return result; + + result = curlx_dyn_addn(out, ":", 1); + if(!result) + result = curlx_dyn_addn(out, b64, b64len); + if(!result) + result = curlx_dyn_addn(out, ":", 1); + + curlx_free(b64); + return result; +} + +static CURLcode build_sig_params(struct dynbuf *params, + const char **components, size_t count, + time_t created, const char *keyid, + enum httpsig_alg alg) +{ + CURLcode result; + size_t i; + + result = curlx_dyn_addn(params, "(", 1); + if(result) + return result; + + for(i = 0; i < count; i++) { + if(i > 0) { + result = curlx_dyn_addn(params, " ", 1); + if(result) + return result; + } + result = sf_append_quoted(params, components[i]); + if(result) + return result; + } + + result = curlx_dyn_addn(params, ")", 1); + if(result) + return result; + + result = curlx_dyn_addf(params, ";created=%lld", (long long)created); + if(result) + return result; + + if(keyid && *keyid) { + result = curlx_dyn_add(params, ";keyid="); + if(result) + return result; + result = sf_append_quoted(params, keyid); + if(result) + return result; + } + + result = curlx_dyn_addf(params, ";alg=\"%s\"", alg_to_str(alg)); + return result; +} + +/* strings defined by RFC 9421 */ +#define SIG_METHOD "@method" +#define SIG_AUTHORITY "@authority" +#define SIG_PATH "@path" +#define SIG_QUERY "@query" + +/* Resolve a component identifier to its value. + * For headers, we walk the full user-supplied header list to combine + * duplicate field values with ", " per RFC 9421 Section 2.1. Each + * individual value is trimmed of leading/trailing OWS and the trailing + * \r\n. The combined result is written into the caller-provided buffer. */ +static CURLcode resolve_component(const char *name, + const char *method, + const char *authority, + const char *path, + const char *query, + struct Curl_easy *data, + struct dynbuf *valbuf, + const char **out) +{ + *out = NULL; + + if(name[0] == '@') { + if(curl_strequal(name, SIG_METHOD)) + *out = method; + else if(curl_strequal(name, SIG_AUTHORITY)) + *out = authority; + else if(curl_strequal(name, SIG_PATH)) + *out = path; + else if(curl_strequal(name, SIG_QUERY)) + *out = query; + else { + failf(data, "httpsig: unsupported derived component '%s'", name); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if(!*out) { + failf(data, "httpsig: derived component '%s' has no value", name); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + return CURLE_OK; + } + else { + /* RFC 9421 Section 2.1: walk all user-supplied headers and combine + duplicate field values with ", " per HTTP field combination rules. */ + struct curl_slist *head; + size_t namelen = strlen(name); + bool found = FALSE; + + curlx_dyn_reset(valbuf); + + for(head = data->set.headers; head; head = head->next) { + if(curl_strnequal(head->data, name, namelen) && + Curl_headersep(head->data[namelen])) { + const char *p = strchr(head->data, ':'); + if(p) { + CURLcode result; + struct Curl_str content; + curlx_str_assign(&content, p + 1, strlen(p + 1)); + curlx_str_trimblanks(&content); + if(found) { + result = curlx_dyn_addn(valbuf, ", ", 2); + if(result) + return result; + } + result = curlx_dyn_addn(valbuf, curlx_str(&content), + curlx_strlen(&content)); + if(result) + return result; + found = TRUE; + } + } + } + + if(found) { + *out = curlx_dyn_ptr(valbuf); + return CURLE_OK; + } + failf(data, "httpsig: header '%s' not found in request", name); + return CURLE_BAD_FUNCTION_ARGUMENT; + } +} + +static CURLcode build_sig_base(struct dynbuf *base, + const char **components, size_t count, + const char *method, + const char *authority, + const char *path, + const char *query, + struct Curl_easy *data, + const char *sig_params) +{ + CURLcode result; + size_t i; + struct dynbuf hdrvalbuf; + + curlx_dyn_init(&hdrvalbuf, CURL_MAX_HTTP_HEADER); + + for(i = 0; i < count; i++) { + const char *val = NULL; + result = resolve_component(components[i], method, + authority, path, query, data, + &hdrvalbuf, &val); + if(result || !val) { + failf(data, "httpsig: cannot resolve component '%s'", components[i]); + curlx_dyn_free(&hdrvalbuf); + return result ? result : CURLE_BAD_FUNCTION_ARGUMENT; + } + + result = curlx_dyn_addf(base, "\"%s\": %s\n", components[i], val); + if(result) { + curlx_dyn_free(&hdrvalbuf); + return result; + } + } + + curlx_dyn_free(&hdrvalbuf); + result = curlx_dyn_addf(base, "\"@signature-params\": %s", sig_params); + return result; +} + +static CURLcode parse_components(struct Curl_easy *data, + const char *query, + const char **components, + size_t *ncomp_out, + char **hdrs_copy_out) +{ + const char *hdrs = CURL_EASY_STR(data, STRING_HTTPSIG_HEADERS); + size_t ncomp = 0; + + *hdrs_copy_out = NULL; + if(hdrs && *hdrs) { + char *p; + char *hdrs_copy = curlx_strdup(hdrs); + if(!hdrs_copy) + return CURLE_OUT_OF_MEMORY; + *hdrs_copy_out = hdrs_copy; + p = hdrs_copy; + while(*p && ncomp < HTTPSIG_MAX_COMPONENTS) { + char *start; + size_t tlen = 0; + const char *p2 = p; + + curlx_str_passblanks(&p2); + if(!*p2) + break; + p = start = CURL_UNCONST(p2); + while(*p && !ISBLANK(*p)) { + if((*p == '\"') || (*p == '\\')) + return CURLE_BAD_FUNCTION_ARGUMENT; + p++; + tlen++; + } + if(*p) + *p++ = '\0'; + + if(tlen && start[tlen - 1] == ':') { + /* Header field: drop the trailing ':' marker. RFC 9421 field + names are canonically lowercase (Section 2.1). */ + start[--tlen] = '\0'; + if(!tlen) { + failf(data, "httpsig: empty header component name"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + Curl_strntolower(start, start, tlen); + components[ncomp++] = start; + } + else { + /* Derived component: map the bare name to its canonical RFC 9421 + '@'-prefixed identifier (Section 2.2). */ + Curl_strntolower(start, start, tlen); + if(!strcmp(start, "method")) + components[ncomp++] = SIG_METHOD; + else if(!strcmp(start, "authority")) + components[ncomp++] = SIG_AUTHORITY; + else if(!strcmp(start, "path")) + components[ncomp++] = SIG_PATH; + else if(!strcmp(start, "query")) + components[ncomp++] = SIG_QUERY; + else { + failf(data, "httpsig: unknown component '%s'", start); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + } + } + if(!ncomp) { + failf(data, "httpsig: no signature components specified"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if(*p) { + failf(data, "httpsig: too many signature components (max %u)", + (unsigned int)HTTPSIG_MAX_COMPONENTS); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + /* RFC 9421 Section 2: each covered component MUST occur only once */ + { + size_t i, j; + + for(i = 0; i < ncomp; i++) { + for(j = i + 1; j < ncomp; j++) { + if(!strcmp(components[i], components[j])) { + failf(data, "httpsig: duplicate signature component '%s'", + components[i]); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + } + } + } + } + else { + components[ncomp++] = SIG_METHOD; + components[ncomp++] = SIG_AUTHORITY; + components[ncomp++] = SIG_PATH; + if(query) + components[ncomp++] = SIG_QUERY; + } + + *ncomp_out = ncomp; + return CURLE_OK; +} + +static time_t httpsig_get_created(void) +{ +#ifdef DEBUGBUILD + char *force = getenv("CURL_FORCETIME"); + if(force && *force) { + char *sigts = getenv("CURL_HTTPSIG_CREATED"); + if(sigts && *sigts) { + const char *p = sigts; + curl_off_t num; + if(!curlx_str_number(&p, &num, CURL_OFF_T_MAX)) + return (time_t)num; + } + return 0; + } +#endif + return time(NULL); +} + +static CURLcode httpsig_sign_base(struct Curl_easy *data, + enum httpsig_alg alg, + const unsigned char *keybuf, + size_t keylen, + const struct dynbuf *sig_base, + unsigned char *raw_sig, + size_t *raw_sig_len) +{ + CURLcode result; + + switch(alg) { + case HTTPSIG_ALG_ED25519: + result = Curl_ed25519_sign( + keybuf, keylen, + (const unsigned char *)curlx_dyn_ptr(sig_base), + curlx_dyn_len(sig_base), + raw_sig, raw_sig_len); + break; + case HTTPSIG_ALG_HMAC_SHA256: + result = Curl_hmacit(&Curl_HMAC_SHA256, keybuf, keylen, + (const unsigned char *)curlx_dyn_ptr(sig_base), + curlx_dyn_len(sig_base), raw_sig); + if(!result) + *raw_sig_len = CURL_SHA256_DIGEST_LENGTH; + break; + default: + result = CURLE_BAD_FUNCTION_ARGUMENT; + break; + } + + if(result && result == CURLE_NOT_BUILT_IN) { + failf(data, "httpsig: algorithm '%s' not supported by TLS backend", + alg_to_str(alg)); + } + return result; +} + +CURLcode Curl_output_httpsig(struct Curl_easy *data) +{ + CURLcode result = CURLE_OUT_OF_MEMORY; + struct connectdata *conn = data->conn; + const char *path; + const char *query; + Curl_HttpReq httpreq; + const char *method = NULL; + const char *hexkey = CURL_EASY_STR(data, STRING_HTTPSIG_KEY); + const char *keyid = CURL_EASY_STR(data, STRING_HTTPSIG_KEYID); + enum httpsig_alg alg; + time_t created; + struct dynbuf sig_params; + struct dynbuf sig_base; + struct dynbuf sig_hdr; + struct dynbuf input_hdr; + struct dynbuf authority_buf; + const char *authority; + const char *components[HTTPSIG_MAX_COMPONENTS]; + size_t ncomp = 0; + unsigned char *keybuf = NULL; + size_t keylen = 0; + unsigned char raw_sig[HTTPSIG_MAX_RAW_SIG]; + size_t raw_sig_len = 0; + char *auth_headers = NULL; + char *hdrs_copy = NULL; + struct dynbuf query_dyn; + + alg = id_to_alg(data->set.httpsig_algorithm); + if(alg == HTTPSIG_ALG_UNKNOWN) { + failf(data, "httpsig: CURLOPT_HTTPSIG_ALGORITHM is required"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + if(!hexkey || !*hexkey) { + failf(data, "httpsig: CURLOPT_HTTPSIG_KEY is required"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if(!keyid || !*keyid) { + failf(data, "httpsig: CURLOPT_HTTPSIG_KEYID is required"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + curlx_dyn_init(&sig_params, CURL_MAX_HTTP_HEADER); + curlx_dyn_init(&sig_base, HTTPSIG_MAX_SIG_BASE); + curlx_dyn_init(&sig_hdr, CURL_MAX_HTTP_HEADER); + curlx_dyn_init(&input_hdr, CURL_MAX_HTTP_HEADER); + curlx_dyn_init(&authority_buf, CURL_MAX_HTTP_HEADER); + curlx_dyn_init(&query_dyn, CURL_MAX_HTTP_HEADER); + + if(Curl_checkheaders(data, STRCONST("Signature")) || + Curl_checkheaders(data, STRCONST("Signature-Input"))) { + /* user provides their own Signature / Signature-Input headers, consider + this done */ + goto done; + } + + result = decode_hex_key(data, hexkey, &keybuf, &keylen); + if(result) + goto fail; + + if(alg == HTTPSIG_ALG_ED25519 && keylen != 32) { + failf(data, "httpsig: ed25519 requires a 32-byte key (got %zu)", keylen); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto fail; + } + + Curl_http_method(data, &method, &httpreq); + + path = data->state.up.path; + if(!path || !*path) + path = "/"; + + query = data->state.up.query; + + result = httpsig_authority(data, conn, &authority_buf); + if(result) + goto fail; + authority = curlx_dyn_ptr(&authority_buf); + + /* Build @query value: RFC 9421 Section 2.2.7 - always starts with "?" */ + if(query && *query) + result = curlx_dyn_addf(&query_dyn, "?%s", query); + else + result = curlx_dyn_add(&query_dyn, "?"); + if(result) + goto fail; + + result = parse_components(data, query, components, &ncomp, &hdrs_copy); + if(result) + goto fail; + + created = httpsig_get_created(); + + result = build_sig_params(&sig_params, components, ncomp, + created, keyid, alg); + if(result) + goto fail; + + infof(data, "httpsig: Signature-Input params: %s", + curlx_dyn_ptr(&sig_params)); + + result = build_sig_base(&sig_base, components, ncomp, + method, authority, path, + curlx_dyn_ptr(&query_dyn), + data, curlx_dyn_ptr(&sig_params)); + if(result) + goto fail; + + infof(data, "httpsig: Signature base: [%s]", + curlx_dyn_ptr(&sig_base)); + + result = httpsig_sign_base(data, alg, keybuf, keylen, &sig_base, + raw_sig, &raw_sig_len); + if(result) + goto fail; + + result = curlx_dyn_add(&sig_hdr, HTTPSIG_DEFAULT_LABEL "="); + if(result) + goto fail; + result = sf_encode_byte_seq(raw_sig, raw_sig_len, &sig_hdr); + if(result) + goto fail; + + result = curlx_dyn_addf(&input_hdr, "%s=%s", HTTPSIG_DEFAULT_LABEL, + curlx_dyn_ptr(&sig_params)); + if(result) + goto fail; + + auth_headers = curl_maprintf("Signature-Input: %s\r\n" + "Signature: %s\r\n", + curlx_dyn_ptr(&input_hdr), + curlx_dyn_ptr(&sig_hdr)); + if(!auth_headers) + goto fail; + + infof(data, "httpsig: Signature-Input: %s", curlx_dyn_ptr(&input_hdr)); + infof(data, "httpsig: Signature: %s", curlx_dyn_ptr(&sig_hdr)); +done: + curlx_free(data->req.hd_auth); + data->req.hd_auth = auth_headers; + data->state.authhost.done = TRUE; + result = CURLE_OK; + +fail: + if(keybuf) { + memset(keybuf, 0, keylen); + curlx_free(keybuf); + } + memset(raw_sig, 0, sizeof(raw_sig)); + curlx_free(hdrs_copy); + curlx_dyn_free(&sig_params); + curlx_dyn_free(&sig_base); + curlx_dyn_free(&sig_hdr); + curlx_dyn_free(&input_hdr); + curlx_dyn_free(&authority_buf); + curlx_dyn_free(&query_dyn); + return result; +} + +#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_HTTPSIG */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_httpsig.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_httpsig.h new file mode 100644 index 0000000000..410755d7e0 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_httpsig.h @@ -0,0 +1,35 @@ +#ifndef HEADER_CURL_HTTP_HTTPSIG_H +#define HEADER_CURL_HTTP_HTTPSIG_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HTTPSIG) + +#include "urldata.h" + +CURLcode Curl_output_httpsig(struct Curl_easy *data); + +#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_HTTPSIG */ +#endif /* HEADER_CURL_HTTP_HTTPSIG_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_negotiate.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_negotiate.c new file mode 100644 index 0000000000..5e8798134f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_negotiate.c @@ -0,0 +1,266 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO) + +#include "urldata.h" +#include "cfilters.h" +#include "curl_trc.h" +#include "http_negotiate.h" +#include "vauth/vauth.h" +#include "vtls/vtls.h" +#include "curlx/strparse.h" + + +static void http_auth_nego_reset(struct connectdata *conn, + struct negotiatedata *neg_ctx, + bool proxy) +{ + if(proxy) + conn->proxy_negotiate_state = GSS_AUTHNONE; + else { + conn->http_negotiate_state = GSS_AUTHNONE; + Curl_peer_unlink(&conn->creds_origin); + Curl_creds_unlink(&conn->creds); + } + if(neg_ctx) + Curl_auth_cleanup_spnego(neg_ctx); +} + +CURLcode Curl_input_negotiate(struct Curl_easy *data, struct connectdata *conn, + bool proxy, const char *header) +{ + CURLcode result; + size_t len; + + /* Point to credentials and host */ + struct Curl_creds *creds = NULL; + const char *host; + + /* Point to the correct struct with this */ + struct negotiatedata *neg_ctx; + curlnegotiate state; + + if(proxy) { +#ifndef CURL_DISABLE_PROXY + creds = conn->http_proxy.creds; + host = conn->http_proxy.peer->hostname; + state = conn->proxy_negotiate_state; +#else + return CURLE_NOT_BUILT_IN; +#endif + } + else { + creds = data->state.creds; + host = data->state.origin->hostname; + state = conn->http_negotiate_state; + } + + neg_ctx = Curl_auth_nego_get(conn, proxy); + if(!neg_ctx) + return CURLE_OUT_OF_MEMORY; + + /* Obtain the input token, if any */ + header += CURL_CSTRLEN("Negotiate"); + curlx_str_passblanks(&header); + + len = strlen(header); + neg_ctx->havenegdata = len != 0; + if(!len) { + if(state == GSS_AUTHSUCC) { + infof(data, "Negotiate auth restarted"); + http_auth_nego_reset(conn, neg_ctx, proxy); + } + else if(state != GSS_AUTHNONE) { + /* The server rejected our authentication and has not supplied any more + negotiation mechanisms */ + http_auth_nego_reset(conn, neg_ctx, proxy); + return CURLE_LOGIN_DENIED; + } + } + + /* Supports SSL channel binding for Windows ISS extended protection */ +#ifdef USE_WINDOWS_SSPI + neg_ctx->sslContext = conn->sslContext; +#endif + /* Check if the connection is using SSL and get the channel binding data */ +#ifdef GSS_C_CHANNEL_BOUND_FLAG +#ifdef USE_SSL + curlx_dyn_init(&neg_ctx->channel_binding_data, SSL_CB_MAX_SIZE + 1); + if(Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + result = Curl_ssl_get_channel_binding(data, FIRSTSOCKET, + &neg_ctx->channel_binding_data); + if(result) { + http_auth_nego_reset(conn, neg_ctx, proxy); + return result; + } + } +#else + curlx_dyn_init(&neg_ctx->channel_binding_data, 1); +#endif /* USE_SSL */ +#endif /* GSS_C_CHANNEL_BOUND_FLAG */ + + /* Initialize the security context and decode our challenge */ + result = Curl_auth_decode_spnego_message(data, creds, "HTTP", + host, header, neg_ctx); + +#ifdef GSS_C_CHANNEL_BOUND_FLAG + curlx_dyn_free(&neg_ctx->channel_binding_data); +#endif + + if(result) + http_auth_nego_reset(conn, neg_ctx, proxy); + + if(!result && !proxy) { + /* Start it up. From this time onwards, the connection is tied + * tp the credentials used. */ + if(conn->creds_origin && + !Curl_peer_equal(conn->creds_origin, data->state.origin)) { + DEBUGASSERT(0); /* should not happen. */ + return CURLE_FAILED_INIT; + } + if(conn->creds && !Curl_creds_same(creds, conn->creds)) { + DEBUGASSERT(0); /* should not happen. */ + return CURLE_FAILED_INIT; + } + Curl_peer_link(&conn->creds_origin, data->state.origin); + Curl_creds_link(&conn->creds, creds); + } + + return result; +} + +CURLcode Curl_output_negotiate(struct Curl_easy *data, + struct connectdata *conn, bool proxy) +{ + struct negotiatedata *neg_ctx; + struct auth *authp; + curlnegotiate *state; + char *base64 = NULL; + size_t len = 0; + char *userp; + CURLcode result; + + if(proxy) { +#ifndef CURL_DISABLE_PROXY + authp = &data->state.authproxy; + state = &conn->proxy_negotiate_state; +#else + return CURLE_NOT_BUILT_IN; +#endif + } + else { + authp = &data->state.authhost; + state = &conn->http_negotiate_state; + } + neg_ctx = Curl_auth_nego_get(conn, proxy); + if(!neg_ctx) + return CURLE_OUT_OF_MEMORY; + + authp->done = FALSE; + + if(*state == GSS_AUTHRECV) { + if(neg_ctx->havenegdata) { + neg_ctx->havemultiplerequests = TRUE; + } + } + else if(*state == GSS_AUTHSUCC) { + if(!neg_ctx->havenoauthpersist) { + neg_ctx->noauthpersist = !neg_ctx->havemultiplerequests; + } + } + + if(neg_ctx->noauthpersist || + (*state != GSS_AUTHDONE && *state != GSS_AUTHSUCC)) { + + if(neg_ctx->noauthpersist && *state == GSS_AUTHSUCC) { + infof(data, "Curl_output_negotiate, " + "no persistent authentication: cleanup existing context"); + http_auth_nego_reset(conn, neg_ctx, proxy); + } + if(!neg_ctx->context) { + result = Curl_input_negotiate(data, conn, proxy, "Negotiate"); + if(result == CURLE_AUTH_ERROR) { + /* negotiate auth failed, let's continue unauthenticated to stay + * compatible with the behavior before curl-7_64_0-158-g6c6035532 */ + authp->done = TRUE; + return CURLE_OK; + } + else if(result) + return result; + } + + result = Curl_auth_create_spnego_message(neg_ctx, &base64, &len); + if(result) + return result; + + userp = curl_maprintf("%sAuthorization: Negotiate %s\r\n", + proxy ? "Proxy-" : "", base64); + + if(proxy) { +#ifndef CURL_DISABLE_PROXY + curlx_free(data->req.hd_proxy_auth); + data->req.hd_proxy_auth = userp; +#endif + } + else { + curlx_free(data->req.hd_auth); + data->req.hd_auth = userp; + } + + curlx_free(base64); + + if(!userp) { + return CURLE_OUT_OF_MEMORY; + } + + *state = GSS_AUTHSENT; +#ifdef HAVE_GSSAPI + if(neg_ctx->status == GSS_S_COMPLETE || + neg_ctx->status == GSS_S_CONTINUE_NEEDED) { + *state = GSS_AUTHDONE; + } +#else +#ifdef USE_WINDOWS_SSPI + if(neg_ctx->status == SEC_E_OK || + neg_ctx->status == SEC_I_CONTINUE_NEEDED) { + *state = GSS_AUTHDONE; + } +#endif +#endif + } + + if(*state == GSS_AUTHDONE || *state == GSS_AUTHSUCC) { + /* connection is already authenticated, + * do not send a header in future requests */ + authp->done = TRUE; + } + + neg_ctx->havenegdata = FALSE; + + return CURLE_OK; +} + +#endif /* !CURL_DISABLE_HTTP && USE_SPNEGO */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_negotiate.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_negotiate.h new file mode 100644 index 0000000000..6c285f152f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_negotiate.h @@ -0,0 +1,40 @@ +#ifndef HEADER_CURL_HTTP_NEGOTIATE_H +#define HEADER_CURL_HTTP_NEGOTIATE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO) + +/* this is for Negotiate header input */ +CURLcode Curl_input_negotiate(struct Curl_easy *data, struct connectdata *conn, + bool proxy, const char *header); + +/* this is for creating Negotiate header output */ +CURLcode Curl_output_negotiate(struct Curl_easy *data, + struct connectdata *conn, bool proxy); + +#endif + +#endif /* HEADER_CURL_HTTP_NEGOTIATE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_ntlm.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_ntlm.c new file mode 100644 index 0000000000..a1de75fc07 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_ntlm.c @@ -0,0 +1,253 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) + +/* + * NTLM details: + * + * https://davenport.sourceforge.net/ntlm.html + * https://www.innovation.ch/java/ntlm.html + */ + +#include "urldata.h" +#include "curl_trc.h" +#include "strcase.h" +#include "http_ntlm.h" +#include "curl_ntlm_core.h" +#include "curlx/base64.h" +#include "vauth/vauth.h" +#include "url.h" +#include "curlx/strparse.h" + +/* SSL backend-specific #if branches in this file must be kept in the order + documented in curl_ntlm_core. */ +#ifdef USE_WINDOWS_SSPI +#include "curl_sspi.h" +#endif + +CURLcode Curl_input_ntlm(struct Curl_easy *data, + bool proxy, /* if proxy or not */ + const char *header) /* rest of the www-authenticate: + header */ +{ + /* point to the correct struct with this */ + curlntlm *state; + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + state = proxy ? &conn->proxy_ntlm_state : &conn->http_ntlm_state; + + if(checkprefix("NTLM", header)) { + struct ntlmdata *ntlm = Curl_auth_ntlm_get(conn, proxy); + if(!ntlm) + return CURLE_OUT_OF_MEMORY; + + header += CURL_CSTRLEN("NTLM"); + curlx_str_passblanks(&header); + if(*header) { + unsigned char *hdr; + size_t hdrlen; + + result = curlx_base64_decode(header, &hdr, &hdrlen); + if(!result) { + struct bufref hdrbuf; + + Curl_bufref_init(&hdrbuf); + Curl_bufref_set(&hdrbuf, hdr, hdrlen, curl_free); + result = Curl_auth_decode_ntlm_type2_message(data, &hdrbuf, ntlm); + Curl_bufref_free(&hdrbuf); + } + if(result) + return result; + + *state = NTLMSTATE_TYPE2; /* We got a type-2 message */ + } + else { + if(*state == NTLMSTATE_LAST) { + infof(data, "NTLM auth restarted"); + Curl_auth_ntlm_remove(conn, proxy); + } + else if(*state == NTLMSTATE_TYPE3) { + infof(data, "NTLM handshake rejected"); + Curl_auth_ntlm_remove(conn, proxy); + Curl_peer_unlink(&conn->creds_origin); + Curl_creds_unlink(&conn->creds); + *state = NTLMSTATE_NONE; + return CURLE_REMOTE_ACCESS_DENIED; + } + else if(*state >= NTLMSTATE_TYPE1) { + infof(data, "NTLM handshake failure (internal error)"); + return CURLE_REMOTE_ACCESS_DENIED; + } + + *state = NTLMSTATE_TYPE1; /* We should send away a type-1 */ + } + } + + return result; +} + +/* + * This is for creating NTLM header output + */ +CURLcode Curl_output_ntlm(struct Curl_easy *data, bool proxy) +{ + char *base64 = NULL; + size_t len = 0; + CURLcode result = CURLE_OK; + struct bufref ntlmmsg; + + /* point to the address of the pointer that holds the string to send to the + server, which is for a plain host or for an HTTP proxy */ + char **allocuserpwd; + + /* point to credentials and host */ + struct Curl_creds *creds = NULL; + const char *hostname = NULL; + + /* point to the correct struct with this */ + struct ntlmdata *ntlm; + curlntlm *state; + struct auth *authp; + struct connectdata *conn = data->conn; + + DEBUGASSERT(conn); + DEBUGASSERT(data); + + if(proxy) { +#ifndef CURL_DISABLE_PROXY + allocuserpwd = &data->req.hd_proxy_auth; + creds = conn->http_proxy.creds; + hostname = conn->http_proxy.peer->hostname; + state = &conn->proxy_ntlm_state; + authp = &data->state.authproxy; +#else + return CURLE_NOT_BUILT_IN; +#endif + } + else { + allocuserpwd = &data->req.hd_auth; + creds = data->state.creds; + hostname = data->state.origin->hostname; + state = &conn->http_ntlm_state; + authp = &data->state.authhost; + } + + ntlm = Curl_auth_ntlm_get(conn, proxy); + if(!ntlm) + return CURLE_OUT_OF_MEMORY; + authp->done = FALSE; + +#ifdef USE_WINDOWS_SSPI + if(!Curl_pSecFn) { + /* not thread-safe and leaks - use curl_global_init() to avoid */ + result = Curl_sspi_global_init(); + if(!Curl_pSecFn) + return result; + } + ntlm->sslContext = conn->sslContext; +#endif + + Curl_bufref_init(&ntlmmsg); + + /* connection is already authenticated, do not send a header in future + * requests so go directly to NTLMSTATE_LAST */ + if(*state == NTLMSTATE_TYPE3) + *state = NTLMSTATE_LAST; + + switch(*state) { + case NTLMSTATE_TYPE1: + default: /* for the weird cases we (re)start here */ + if(!proxy) { + /* Start it up. From this time onwards, the connection is tied + * tp the credentials used. */ + if(conn->creds_origin && + !Curl_peer_equal(conn->creds_origin, data->state.origin)) { + DEBUGASSERT(0); /* should not happen. */ + return CURLE_FAILED_INIT; + } + if(conn->creds && !Curl_creds_same(creds, conn->creds)) { + DEBUGASSERT(0); /* should not happen. */ + return CURLE_FAILED_INIT; + } + Curl_peer_link(&conn->creds_origin, data->state.origin); + Curl_creds_link(&conn->creds, creds); + } + result = Curl_auth_create_ntlm_type1_message(data, creds, "HTTP", + hostname, ntlm, &ntlmmsg); + if(!result) { + DEBUGASSERT(Curl_bufref_len(&ntlmmsg) != 0); + result = curlx_base64_encode(Curl_bufref_uptr(&ntlmmsg), + Curl_bufref_len(&ntlmmsg), &base64, &len); + if(!result) { + curlx_free(*allocuserpwd); + *allocuserpwd = curl_maprintf("%sAuthorization: NTLM %s\r\n", + proxy ? "Proxy-" : "", base64); + curlx_free(base64); + if(!*allocuserpwd) + result = CURLE_OUT_OF_MEMORY; + } + } + break; + + case NTLMSTATE_TYPE2: + /* We already received the type-2 message, create a type-3 message */ + result = Curl_auth_create_ntlm_type3_message(data, creds, ntlm, &ntlmmsg); + if(!result && Curl_bufref_len(&ntlmmsg)) { + result = curlx_base64_encode(Curl_bufref_uptr(&ntlmmsg), + Curl_bufref_len(&ntlmmsg), &base64, &len); + if(!result) { + curlx_free(*allocuserpwd); + *allocuserpwd = curl_maprintf("%sAuthorization: NTLM %s\r\n", + proxy ? "Proxy-" : "", base64); + curlx_free(base64); + if(!*allocuserpwd) + result = CURLE_OUT_OF_MEMORY; + else { + *state = NTLMSTATE_TYPE3; /* we send a type-3 */ + authp->done = TRUE; + } + } + } + break; + + case NTLMSTATE_LAST: + /* since this is a little artificial in that this is used without any + outgoing auth headers being set, we need to set the bit by force */ + if(proxy) + data->info.proxyauthpicked = CURLAUTH_NTLM; + else + data->info.httpauthpicked = CURLAUTH_NTLM; + curlx_safefree(*allocuserpwd); + authp->done = TRUE; + break; + } + Curl_bufref_free(&ntlmmsg); + + return result; +} + +#endif /* !CURL_DISABLE_HTTP && USE_NTLM */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_ntlm.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_ntlm.h new file mode 100644 index 0000000000..ff5218d89f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_ntlm.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_HTTP_NTLM_H +#define HEADER_CURL_HTTP_NTLM_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) + +/* this is for NTLM header input */ +CURLcode Curl_input_ntlm(struct Curl_easy *data, bool proxy, + const char *header); + +/* this is for creating NTLM header output */ +CURLcode Curl_output_ntlm(struct Curl_easy *data, bool proxy); + +#endif + +#endif /* HEADER_CURL_HTTP_NTLM_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_proxy.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_proxy.c new file mode 100644 index 0000000000..7774589ecd --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_proxy.c @@ -0,0 +1,779 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "http_proxy.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_PROXY) + +#include "curl_trc.h" +#include "http.h" +#include "url.h" +#include "cfilters.h" +#include "cf-h1-proxy.h" +#include "cf-h2-proxy.h" +#include "connect.h" +#include "vauth/vauth.h" +#include "vquic/vquic.h" +#include "curlx/strparse.h" + +static CURLcode dynhds_add_custom(struct Curl_easy *data, + bool is_connect, int httpversion, + bool is_udp, struct dynhds *hds) +{ + struct connectdata *conn = data->conn; + struct curl_slist *h[2]; + struct curl_slist *headers; + int numlists = 1; /* by default */ + int i; + + enum Curl_proxy_use proxy; + + if(is_connect && !is_udp) + proxy = HEADER_CONNECT; + else if(is_connect && is_udp) + proxy = HEADER_CONNECT_UDP; + else + proxy = conn->bits.origin_is_proxy ? HEADER_PROXY : HEADER_SERVER; + + switch(proxy) { + case HEADER_SERVER: + h[0] = data->set.headers; + break; + case HEADER_PROXY: + h[0] = data->set.headers; + if(data->set.sep_headers) { + h[1] = data->set.proxyheaders; + numlists++; + } + break; + case HEADER_CONNECT: + if(data->set.sep_headers) + h[0] = data->set.proxyheaders; + else + h[0] = data->set.headers; + break; + case HEADER_CONNECT_UDP: + if(data->set.sep_headers) + h[0] = data->set.proxyheaders; + else + h[0] = data->set.headers; + break; + } + + /* loop through one or two lists */ + for(i = 0; i < numlists; i++) { + for(headers = h[i]; headers; headers = headers->next) { + struct Curl_str name; + const char *value = NULL; + size_t valuelen = 0; + const char *ptr = headers->data; + + /* There are 2 quirks in place for custom headers: + * 1. setting only 'name:' to suppress a header from being sent + * 2. setting only 'name;' to send an empty (illegal) header + */ + if(!curlx_str_cspn(&ptr, &name, ";:")) { + if(!curlx_str_single(&ptr, ':')) { + curlx_str_passblanks(&ptr); + if(*ptr) { + value = ptr; + valuelen = strlen(value); + } + else { + /* quirk #1, suppress this header */ + continue; + } + } + else if(!curlx_str_single(&ptr, ';')) { + curlx_str_passblanks(&ptr); + if(!*ptr) { + /* quirk #2, send an empty header */ + value = ""; + valuelen = 0; + } + else { + /* this may be used for something else in the future, + * ignore this for now */ + continue; + } + } + else + /* neither : nor ; in provided header value. We ignore this + * silently */ + continue; + } + else + /* no name, move on */ + continue; + + DEBUGASSERT(curlx_strlen(&name) && value); + /* trim surrounding whitespace so a padded field name (e.g. + `Authorization :`) cannot slip past the Authorization/Cookie check */ + curlx_str_trimblanks(&name); + if(data->state.http_host && + /* a Host: header was sent already, do not pass on any custom Host: + header as that will produce *two* in the same request! */ + curlx_str_casecompare(&name, "Host")) + ; + else if(data->state.httpreq == HTTPREQ_POST_FORM && + /* this header (extended by formdata.c) is sent later */ + curlx_str_casecompare(&name, "Content-Type")) + ; + else if(data->state.httpreq == HTTPREQ_POST_MIME && + /* this header is sent later */ + curlx_str_casecompare(&name, "Content-Type")) + ; + else if(data->req.authneg && + /* while doing auth neg, do not allow the custom length since + we will force length zero then */ + curlx_str_casecompare(&name, "Content-Length")) + ; + else if((httpversion >= 20) && + curlx_str_casecompare(&name, "Transfer-Encoding")) + ; + /* HTTP/2 and HTTP/3 do not support chunked requests */ + else if((curlx_str_casecompare(&name, "Authorization") || + curlx_str_casecompare(&name, "Cookie")) && + /* be careful of sending this potentially sensitive header to + other hosts */ + !Curl_auth_allowed_to_host(data)) + ; + else { + CURLcode result = + Curl_dynhds_add(hds, curlx_str(&name), curlx_strlen(&name), + value, valuelen); + if(result) + return result; + } + } + } + + return CURLE_OK; +} + +struct cf_proxy_ctx { + struct Curl_peer *peer; /* proxy */ + struct Curl_peer *tunnel_peer; /* tunnel destination */ + uint8_t proxytype; + uint8_t tunnel_transport; + BIT(sub_filter_installed); +}; + +static int proxy_http_ver_major(proxy_http_ver ver) +{ + switch(ver) { + case PROXY_HTTP_V1: + return 11; + case PROXY_HTTP_V2: + return 20; + case PROXY_HTTP_V3: + return 30; + } + return 0; +} + +static CURLcode http_proxy_create_CONNECT(struct httpreq **preq, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct Curl_peer *dest, + proxy_http_ver ver) +{ + char *authority = NULL; + const char *ua; + int httpversion = proxy_http_ver_major(ver); + CURLcode result; + struct httpreq *req = NULL; + + authority = curl_maprintf("%s%s%s:%u", + dest->ipv6 ? "[" : "", + dest->hostname, + dest->ipv6 ? "]" : "", + dest->port); + if(!authority) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + result = Curl_http_req_make(&req, "CONNECT", CURL_CSTRLEN("CONNECT"), + NULL, 0, authority, strlen(authority), + NULL, 0); + if(result) + goto out; + + /* Setup the proxy-authorization header, if any */ + result = Curl_http_output_auth(data, cf->conn, req->method, HTTPREQ_GET, + req->authority, NULL, TRUE); + if(result) + goto out; + + /* If user is not overriding Host: header, we add for HTTP/1.x */ + if(ver == PROXY_HTTP_V1 && + !Curl_checkProxyheaders(data, cf->conn, STRCONST("Host"))) { + result = Curl_dynhds_cadd(&req->headers, "Host", authority); + if(result) + goto out; + } + + if(data->req.hd_proxy_auth) { + result = Curl_dynhds_h1_cadd_line(&req->headers, + data->req.hd_proxy_auth); + if(result) + goto out; + } + + ua = CURL_EASY_STR(data, STRING_USERAGENT); + if(!Curl_checkProxyheaders(data, cf->conn, STRCONST("User-Agent")) && + ua && *ua) { + result = Curl_dynhds_cadd(&req->headers, "User-Agent", ua); + if(result) + goto out; + } + + if(ver == PROXY_HTTP_V1 && + !Curl_checkProxyheaders(data, cf->conn, STRCONST("Proxy-Connection"))) { + result = Curl_dynhds_cadd(&req->headers, "Proxy-Connection", "Keep-Alive"); + if(result) + goto out; + } + + result = dynhds_add_custom(data, TRUE, httpversion, + FALSE, &req->headers); + +out: + if(result && req) { + Curl_http_req_free(req); + req = NULL; + } + curlx_free(authority); + *preq = req; + return result; +} + +static CURLcode http_proxy_create_CONNECTUDP(struct httpreq **preq, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct Curl_peer *dest, + proxy_http_ver ver) +{ + const char *proxy_scheme = "http", *ua; + const char *proxy_host = cf->conn->http_proxy.peer->hostname; + int httpversion = proxy_http_ver_major(ver); + char *authority = NULL; + char *path = NULL; + char *encoded_host = NULL; + struct httpreq *req = NULL; + bool proxy_ipv6_ip; + CURLcode result; + + if(cf->conn->http_proxy.proxytype == CURLPROXY_HTTPS || + cf->conn->http_proxy.proxytype == CURLPROXY_HTTPS2 || + cf->conn->http_proxy.proxytype == CURLPROXY_HTTPS3) + proxy_scheme = "https"; + + proxy_ipv6_ip = cf->conn->http_proxy.peer->ipv6 != 0; + + authority = curl_maprintf("%s%s%s:%d", + proxy_ipv6_ip ? "[" : "", + proxy_host, + proxy_ipv6_ip ? "]" : "", + cf->conn->http_proxy.peer->port); + if(!authority) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + if(dest->ipv6) { + /* RFC 9298: colons in IPv6 addresses MUST be percent-encoded + * in the URI template (e.g. "2001:db8::1" -> "2001%3Adb8%3A%3A1") */ + const char *s = dest->hostname; + char *d; + size_t hlen = strlen(s); + encoded_host = curlx_malloc(hlen * 3 + 1); + if(!encoded_host) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + d = encoded_host; + while(*s) { + if(*s == ':') { + *d++ = '%'; + *d++ = '3'; + *d++ = 'A'; + } + else + *d++ = *s; + s++; + } + *d = '\0'; + path = curl_maprintf("/.well-known/masque/udp/%s/%u/", + encoded_host, (unsigned int)dest->port); + } + else { + path = curl_maprintf("/.well-known/masque/udp/%s/%u/", + dest->hostname, (unsigned int)dest->port); + } + + if(!path) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + if(ver == PROXY_HTTP_V1) { + result = Curl_http_req_make(&req, "GET", CURL_CSTRLEN("GET"), + proxy_scheme, strlen(proxy_scheme), + authority, strlen(authority), + path, strlen(path)); + if(result) + goto out; + } + else if(ver == PROXY_HTTP_V2 || ver == PROXY_HTTP_V3) { + result = Curl_http_req_make(&req, "CONNECT", CURL_CSTRLEN("CONNECT"), + proxy_scheme, strlen(proxy_scheme), + authority, strlen(authority), + path, strlen(path)); + if(result) + goto out; + } + else { + result = CURLE_FAILED_INIT; + goto out; + } + + /* Setup the proxy-authorization header, if any */ + result = Curl_http_output_auth(data, cf->conn, req->method, HTTPREQ_GET, + req->authority, NULL, TRUE); + if(result) + goto out; + + /* If user is not overriding Host: header, we add for HTTP/1.x */ + if(ver == PROXY_HTTP_V1 && + !Curl_checkProxyheaders(data, cf->conn, STRCONST("Host"))) { + result = Curl_dynhds_cadd(&req->headers, "Host", authority); + if(result) + goto out; + } + + if(data->req.hd_proxy_auth) { + result = Curl_dynhds_h1_cadd_line(&req->headers, + data->req.hd_proxy_auth); + if(result) + goto out; + } + + ua = CURL_EASY_STR(data, STRING_USERAGENT); + if(ver == PROXY_HTTP_V1 && + !Curl_checkProxyheaders(data, cf->conn, STRCONST("User-Agent")) && + ua && *ua) { + result = Curl_dynhds_cadd(&req->headers, "User-Agent", ua); + if(result) + goto out; + } + + if(ver == PROXY_HTTP_V1 && + !Curl_checkProxyheaders(data, cf->conn, STRCONST("Proxy-Connection"))) { + result = Curl_dynhds_cadd(&req->headers, "Proxy-Connection", "Keep-Alive"); + if(result) + goto out; + } + + if(ver == PROXY_HTTP_V1) { + result = Curl_dynhds_cadd(&req->headers, "Connection", "Upgrade"); + if(result) + goto out; + + result = Curl_dynhds_cadd(&req->headers, "Upgrade", "connect-udp"); + if(result) + goto out; + + result = Curl_dynhds_cadd(&req->headers, "Capsule-Protocol", "?1"); + if(result) + goto out; + } + else { + result = Curl_dynhds_cadd(&req->headers, ":Protocol", "connect-udp"); + if(result) + goto out; + + if(ver >= PROXY_HTTP_V2) { + result = Curl_dynhds_cadd(&req->headers, "Capsule-Protocol", "?1"); + if(result) + goto out; + } + } + + result = dynhds_add_custom(data, TRUE, httpversion, + TRUE, &req->headers); + +out: + if(result && req) { + Curl_http_req_free(req); + req = NULL; + } + curlx_free(authority); + curlx_free(path); + curlx_free(encoded_host); + *preq = req; + return result; +} + +CURLcode Curl_http_proxy_create_tunnel_request( + struct httpreq **preq, struct Curl_cfilter *cf, + struct Curl_easy *data, struct Curl_peer *dest, + proxy_http_ver ver, bool udp_tunnel) +{ + CURLcode result; + + if(udp_tunnel) + result = http_proxy_create_CONNECTUDP(preq, cf, data, dest, ver); + else + result = http_proxy_create_CONNECT(preq, cf, data, dest, ver); + if(result) + return result; + + if(udp_tunnel) + infof(data, "Establishing %s proxy UDP tunnel to %s:%u", + (ver == PROXY_HTTP_V2) ? "HTTP/2" : + (ver == PROXY_HTTP_V3) ? "HTTP/3" : "HTTP", + dest->user_hostname, dest->port); + else + infof(data, "Establishing %s proxy tunnel to %s", + (ver == PROXY_HTTP_V2) ? "HTTP/2" : + (ver == PROXY_HTTP_V3) ? "HTTP/3" : "HTTP", + (*preq)->authority); + return CURLE_OK; +} + +CURLcode Curl_http_proxy_inspect_tunnel_response( + struct Curl_cfilter *cf, struct Curl_easy *data, + struct http_resp *resp, bool udp_tunnel, + proxy_inspect_result *presult) +{ + struct dynhds_entry *capsule_protocol = NULL; + struct dynhds_entry *auth_reply = NULL; + size_t i, header_count; + CURLcode result = CURLE_OK; + + DEBUGASSERT(resp); + + header_count = Curl_dynhds_count(&resp->headers); + if(udp_tunnel) + infof(data, "CONNECT-UDP Response Status %d", resp->status); + else + infof(data, "CONNECT Response Status %d", resp->status); + infof(data, "Response Headers (%zu total):", header_count); + for(i = 0; i < header_count; i++) { + struct dynhds_entry *entry = Curl_dynhds_getn(&resp->headers, i); + if(entry) + infof(data, " %s: %s", entry->name, entry->value); + } + + if(resp->status == 401) { + auth_reply = Curl_dynhds_cget(&resp->headers, "WWW-Authenticate"); + } + else if(resp->status == 407) { + auth_reply = Curl_dynhds_cget(&resp->headers, "Proxy-Authenticate"); + } + + if(auth_reply) { + CURL_TRC_CF(data, cf, "[0] CONNECT%s: fwd auth header '%s'", + udp_tunnel ? "-UDP" : "", auth_reply->value); + result = Curl_http_input_auth(data, resp->status == 407, + auth_reply->value); + if(result) + return result; + if(data->req.newurl) { + curlx_safefree(data->req.newurl); + *presult = PROXY_INSPECT_AUTH_RETRY; + return CURLE_OK; + } + } + + if(udp_tunnel) { + if(resp->status / 100 == 2) { + capsule_protocol = Curl_dynhds_cget(&resp->headers, + "capsule-protocol"); + if(capsule_protocol) { + if(!strncmp(capsule_protocol->value, "?1", 2) && + !capsule_protocol->value[2]) { + infof(data, "CONNECT-UDP tunnel established, response %d", + resp->status); + *presult = PROXY_INSPECT_OK; + return CURLE_OK; + } + failf(data, "Failed to establish CONNECT-UDP tunnel, response %d, " + "unsupported capsule-protocol value '%s'", + resp->status, capsule_protocol->value); + *presult = PROXY_INSPECT_FAILED; + return CURLE_COULDNT_CONNECT; + } + else { + /* NOTE proxies may not set capsule protocol in the headers */ + infof(data, "CONNECT-UDP tunnel established, response %d " + "but no capsule-protocol header found", resp->status); + *presult = PROXY_INSPECT_OK; + return CURLE_OK; + } + } + else { + failf(data, "Failed to establish CONNECT-UDP tunnel, " + "response %d", resp->status); + *presult = PROXY_INSPECT_FAILED; + return CURLE_COULDNT_CONNECT; + } + } + + if(resp->status / 100 == 2) { + infof(data, "CONNECT tunnel established, response %d", resp->status); + *presult = PROXY_INSPECT_OK; + return CURLE_OK; + } + + *presult = PROXY_INSPECT_FAILED; + return CURLE_COULDNT_CONNECT; +} + +static CURLcode http_proxy_cf_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_proxy_ctx *ctx = cf->ctx; + CURLcode result; + bool udp_tunnel = TRNSPRT_IS_DGRAM(ctx->tunnel_transport); + const char *tunnel_type = udp_tunnel ? "CONNECT-UDP" : "CONNECT"; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + CURL_TRC_CF(data, cf, "%s", tunnel_type); +connect_sub: + /* in case of h3_proxy, cf->next will be NULL initially */ + if(cf->next) { + result = cf->next->cft->do_connect(cf->next, data, done); + if(result || !*done) + return result; + } + + *done = FALSE; + if(!ctx->sub_filter_installed) { + const char *alpn = NULL; + + /* in case of h3_proxy, cf->next will be NULL initially */ + if(cf->next) { + alpn = Curl_conn_cf_get_alpn_negotiated(cf->next, data); + } + + if(alpn) + infof(data, "%s: '%s' negotiated", tunnel_type, alpn); + else if(!alpn) { + /* No ALPN, proxytype rules. Fake ALPN */ + infof(data, "%s: no ALPN negotiated", tunnel_type); + switch(ctx->proxytype) { + case CURLPROXY_HTTP_1_0: + alpn = "http/1.0"; + break; + case CURLPROXY_HTTPS2: + alpn = "h2"; + break; + case CURLPROXY_HTTPS3: + alpn = "h3"; + break; + default: + alpn = "http/1.1"; + break; + } + } + + if(!strcmp(alpn, "http/1.0")) { + CURL_TRC_CF(data, cf, "installing subfilter for HTTP/1.0"); + result = Curl_cf_h1_proxy_insert_after(cf, data, ctx->tunnel_peer, 10, + udp_tunnel); + if(result) + goto out; + } + else if(!strcmp(alpn, "http/1.1")) { + int httpversion = (ctx->proxytype == CURLPROXY_HTTP_1_0) ? 10 : 11; + CURL_TRC_CF(data, cf, "installing subfilter for HTTP/1.%d", + httpversion % 10); + result = Curl_cf_h1_proxy_insert_after(cf, data, ctx->tunnel_peer, + httpversion, udp_tunnel); + if(result) + goto out; + } +#ifdef USE_NGHTTP2 + else if(!strcmp(alpn, "h2")) { + CURL_TRC_CF(data, cf, "installing subfilter for HTTP/2"); + result = Curl_cf_h2_proxy_insert_after(cf, data, ctx->tunnel_peer, + udp_tunnel); + if(result) + goto out; + } +#endif /* USE_NGHTTP2 */ +#if defined(USE_PROXY_HTTP3) && defined(USE_NGHTTP3) && \ + defined(USE_NGTCP2) && defined(USE_OPENSSL) + else if(!strcmp(alpn, "h3")) { + CURL_TRC_CF(data, cf, "installing subfilter for HTTP/3"); + result = Curl_cf_h3_proxy_insert_after(cf, data, ctx->peer, ctx->peer, + ctx->tunnel_peer, + ctx->tunnel_transport); + if(result) + goto out; + } +#endif /* USE_PROXY_HTTP3 && USE_NGHTTP3 && USE_NGTCP2 && USE_OPENSSL */ + else { + failf(data, "%s: negotiated ALPN '%s' not supported", tunnel_type, alpn); + result = CURLE_COULDNT_CONNECT; + goto out; + } + + ctx->sub_filter_installed = TRUE; + /* after we installed the filter "below" us, we call connect + * on out sub-chain again. + */ + goto connect_sub; + } + else { + /* subchain connected and we had already installed the protocol filter. + * This means the protocol tunnel is established, we are done. */ + DEBUGASSERT(ctx->sub_filter_installed); + result = CURLE_OK; + } + +out: + if(!result) { + cf->connected = TRUE; + *done = TRUE; + } + return result; +} + +static CURLcode cf_http_proxy_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_proxy_ctx *ctx = cf->ctx; + switch(query) { + case CF_QUERY_HOST_PORT: + *pres1 = (int)ctx->tunnel_peer->port; + *((const char **)pres2) = ctx->tunnel_peer->hostname; + return CURLE_OK; + case CF_QUERY_ALPN_NEGOTIATED: { + const char **palpn = pres2; + DEBUGASSERT(palpn); + *palpn = NULL; + return CURLE_OK; + } + default: + break; + } + return cf->next ? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +static void cf_https_proxy_ctx_free(struct cf_proxy_ctx *ctx) +{ + if(ctx) { + Curl_peer_unlink(&ctx->peer); + Curl_peer_unlink(&ctx->tunnel_peer); + curlx_free(ctx); + } +} + +static void http_proxy_cf_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_proxy_ctx *ctx = cf->ctx; + if(ctx) { + CURL_TRC_CF(data, cf, "destroy"); + cf_https_proxy_ctx_free(ctx); + } +} + +struct Curl_cftype Curl_cft_http_proxy = { + "HTTP-PROXY", + CF_TYPE_IP_CONNECT | CF_TYPE_PROXY | CF_TYPE_SETUP, + 0, + http_proxy_cf_destroy, + http_proxy_cf_connect, + Curl_cf_def_shutdown, + Curl_cf_def_adjust_pollset, + Curl_cf_def_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_http_proxy_query, +}; + +CURLcode Curl_cf_http_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *peer, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport, + uint8_t proxytype) +{ + struct Curl_cfilter *cf; + struct cf_proxy_ctx *ctx = NULL; + CURLcode result; + + (void)data; + if(!peer || !tunnel_peer) + return CURLE_FAILED_INIT; + + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + Curl_peer_link(&ctx->peer, peer); + Curl_peer_link(&ctx->tunnel_peer, tunnel_peer); + ctx->proxytype = proxytype; + ctx->tunnel_transport = tunnel_transport; + + result = Curl_cf_create(&cf, &Curl_cft_http_proxy, ctx); + if(result) + goto out; + ctx = NULL; + Curl_conn_cf_insert_after(cf_at, cf); + +out: + cf_https_proxy_ctx_free(ctx); + return result; +} + +uint8_t Curl_http_proxy_transport(uint8_t proxytype) +{ + switch(proxytype) { + case CURLPROXY_HTTPS3: + return TRNSPRT_QUIC; + default: + return TRNSPRT_TCP; + } +} + +#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_PROXY */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_proxy.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_proxy.h new file mode 100644 index 0000000000..86c9088093 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/http_proxy.h @@ -0,0 +1,82 @@ +#ifndef HEADER_CURL_HTTP_PROXY_H +#define HEADER_CURL_HTTP_PROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP) + +#include "urldata.h" + +enum Curl_proxy_use { + HEADER_SERVER, /* direct to server */ + HEADER_PROXY, /* regular request to proxy */ + HEADER_CONNECT, /* sending CONNECT to a proxy */ + HEADER_CONNECT_UDP /* sending CONNECT-UDP to a proxy */ +}; + +/* HTTP version for proxy tunnel request creation */ +typedef enum { + PROXY_HTTP_V1 = 1, + PROXY_HTTP_V2 = 2, + PROXY_HTTP_V3 = 3 +} proxy_http_ver; + +/* Result from inspecting a proxy tunnel response */ +typedef enum { + PROXY_INSPECT_OK, /* Tunnel established */ + PROXY_INSPECT_FAILED, /* Tunnel failed */ + PROXY_INSPECT_AUTH_RETRY /* Retry with auth */ +} proxy_inspect_result; + +/* Create CONNECT or CONNECT-UDP request */ +CURLcode Curl_http_proxy_create_tunnel_request( + struct httpreq **preq, struct Curl_cfilter *cf, + struct Curl_easy *data, struct Curl_peer *dest, + proxy_http_ver ver, bool udp_tunnel); + +/* Inspect tunnel response for H2/H3 proxy (capsule-protocol, auth) */ +struct http_resp; +CURLcode Curl_http_proxy_inspect_tunnel_response( + struct Curl_cfilter *cf, struct Curl_easy *data, + struct http_resp *resp, bool udp_tunnel, + proxy_inspect_result *presult); + +/* Default proxy timeout in milliseconds */ +#define PROXY_TIMEOUT (3600 * 1000) + +CURLcode Curl_cf_http_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *peer, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport, + uint8_t proxytype); + +extern struct Curl_cftype Curl_cft_http_proxy; + +uint8_t Curl_http_proxy_transport(uint8_t proxytype); + +#endif /* !CURL_DISABLE_PROXY && !CURL_DISABLE_HTTP */ + +#endif /* HEADER_CURL_HTTP_PROXY_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/idn.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/idn.c new file mode 100644 index 0000000000..943a520eff --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/idn.c @@ -0,0 +1,388 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * IDN conversions + */ +#include "curl_setup.h" + +#include "urldata.h" +#include "curlx/strparse.h" +#include "idn.h" + +#ifdef USE_LIBIDN2 +#include <idn2.h> + +#if defined(_WIN32) && defined(UNICODE) +#define IDN2_LOOKUP(name, host, flags) \ + idn2_lookup_u8((const uint8_t *)name, (uint8_t **)host, flags) +#else +#define IDN2_LOOKUP(name, host, flags) \ + idn2_lookup_ul((const char *)(name), (char **)(host), flags) +#endif +#endif /* USE_LIBIDN2 */ + +/* for macOS and iOS targets */ +#ifdef USE_APPLE_IDN +#include <unicode/uidna.h> +#include <iconv.h> +#include <langinfo.h> + +#define MAX_HOST_LENGTH 512 + +static CURLcode iconv_to_utf8(const char *in, size_t inlen, + char **out, size_t *outlen) +{ + iconv_t cd = iconv_open("UTF-8", nl_langinfo(CODESET)); + if(cd != (iconv_t)-1) { + size_t iconv_outlen = *outlen; + char *iconv_in = (char *)CURL_UNCONST(in); + size_t iconv_inlen = inlen; + size_t iconv_result = iconv(cd, &iconv_in, &iconv_inlen, + out, &iconv_outlen); + *outlen -= iconv_outlen; + iconv_close(cd); + if(iconv_result == (size_t)-1) { + /* !checksrc! disable ERRNOVAR 1 */ + if(errno == ENOMEM) + return CURLE_OUT_OF_MEMORY; + else + return CURLE_URL_MALFORMAT; + } + + return CURLE_OK; + } + else { + /* !checksrc! disable ERRNOVAR 1 */ + if(errno == ENOMEM) + return CURLE_OUT_OF_MEMORY; + else + return CURLE_FAILED_INIT; + } +} + +static CURLcode mac_idn_to_ascii(const char *in, char **out) +{ + size_t inlen = strlen(in); + if(inlen < MAX_HOST_LENGTH) { + char iconv_buffer[MAX_HOST_LENGTH] = { 0 }; + char *iconv_outptr = iconv_buffer; + size_t iconv_outlen = sizeof(iconv_buffer); + CURLcode iconv_result = iconv_to_utf8(in, inlen, + &iconv_outptr, &iconv_outlen); + if(!iconv_result) { + UErrorCode err = U_ZERO_ERROR; + UIDNA *idna = uidna_openUTS46( + UIDNA_CHECK_BIDI | UIDNA_NONTRANSITIONAL_TO_ASCII, &err); + if(!U_FAILURE(err)) { + UIDNAInfo info = UIDNA_INFO_INITIALIZER; + char buffer[MAX_HOST_LENGTH] = { 0 }; + (void)uidna_nameToASCII_UTF8(idna, iconv_buffer, (int)iconv_outlen, + buffer, sizeof(buffer) - 1, &info, &err); + uidna_close(idna); + if(!U_FAILURE(err) && !info.errors) { + *out = curlx_strdup(buffer); + if(*out) + return CURLE_OK; + else + return CURLE_OUT_OF_MEMORY; + } + } + } + else + return iconv_result; + } + return CURLE_URL_MALFORMAT; +} + +static CURLcode mac_ascii_to_idn(const char *in, char **out) +{ + size_t inlen = strlen(in); + if(inlen < MAX_HOST_LENGTH) { + UErrorCode err = U_ZERO_ERROR; + UIDNA *idna = uidna_openUTS46( + UIDNA_CHECK_BIDI | UIDNA_NONTRANSITIONAL_TO_UNICODE, &err); + if(!U_FAILURE(err)) { + UIDNAInfo info = UIDNA_INFO_INITIALIZER; + char buffer[MAX_HOST_LENGTH] = { 0 }; + (void)uidna_nameToUnicodeUTF8(idna, in, -1, buffer, + sizeof(buffer) - 1, &info, &err); + uidna_close(idna); + if(!U_FAILURE(err)) { + *out = curlx_strdup(buffer); + if(*out) + return CURLE_OK; + else + return CURLE_OUT_OF_MEMORY; + } + } + } + return CURLE_URL_MALFORMAT; +} +#endif + +#ifdef USE_WIN32_IDN +/* using Windows kernel32 and normaliz libraries. */ + +#define IDN_MAX_LENGTH 255 + +static char *idn_curlx_convert_wchar_to_UTF8(const wchar_t *str_w, int chars) +{ + char *str_utf8 = NULL; + int bytes = WideCharToMultiByte(CP_UTF8, 0, str_w, chars, NULL, 0, + NULL, NULL); + if(bytes > 0) { + str_utf8 = curlx_malloc(bytes); + if(str_utf8) { + if(WideCharToMultiByte(CP_UTF8, 0, str_w, chars, str_utf8, bytes, + NULL, NULL) == 0) { + curlx_free(str_utf8); + return NULL; + } + } + } + return str_utf8; +} + +static CURLcode win32_idn_to_ascii(const char *in, char **out) +{ + wchar_t in_w[IDN_MAX_LENGTH]; + int in_w_len; + *out = NULL; + /* Returned in_w_len includes the null-terminator, which then gets + preserved across the calls that follow, ending up terminating + the buffer returned to the caller. */ + in_w_len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, + in, -1, in_w, IDN_MAX_LENGTH); + if(in_w_len) { + wchar_t punycode[IDN_MAX_LENGTH]; + int chars = IdnToAscii(0, in_w, in_w_len, punycode, IDN_MAX_LENGTH); + if(chars > 0) { + *out = idn_curlx_convert_wchar_to_UTF8(punycode, chars); + if(!*out) + return CURLE_OUT_OF_MEMORY; + } + else + return CURLE_URL_MALFORMAT; + } + else + return CURLE_URL_MALFORMAT; + + return CURLE_OK; +} + +static CURLcode win32_ascii_to_idn(const char *in, char **out) +{ + wchar_t in_w[IDN_MAX_LENGTH]; + int in_w_len; + *out = NULL; + /* Returned in_w_len includes the null-terminator, which then gets + preserved across the calls that follow, ending up terminating + the buffer returned to the caller. */ + in_w_len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, + in, -1, in_w, IDN_MAX_LENGTH); + if(in_w_len) { + WCHAR idn[IDN_MAX_LENGTH]; /* stores a UTF-16 string */ + int chars = IdnToUnicode(0, in_w, in_w_len, idn, IDN_MAX_LENGTH); + if(chars > 0) { /* 'chars' is "the number of characters retrieved" */ + *out = idn_curlx_convert_wchar_to_UTF8(idn, chars); + if(!*out) + return CURLE_OUT_OF_MEMORY; + } + else + return CURLE_URL_MALFORMAT; + } + else + return CURLE_URL_MALFORMAT; + + return CURLE_OK; +} + +#endif /* USE_WIN32_IDN */ + +/* + * Helpers for IDNA conversions. + */ +bool Curl_is_ASCII_name(const char *hostname) +{ + if(hostname) { + struct Curl_str s; + s.str = hostname; + s.len = strlen(hostname); + return Curl_is_ASCII_str(&s); + } + return TRUE; +} + +bool Curl_is_ASCII_str(struct Curl_str *s) +{ + if(s && s->len) { + const unsigned char *ch = (const unsigned char *)s->str; + size_t i; + for(i = 0; i < s->len; ++i) { + if(ch[i] & 0x80) + return FALSE; + } + } + return TRUE; +} + +#ifdef USE_IDN +/* + * Curl_idn_decode() returns an allocated IDN decoded string if it was + * possible. NULL on error. + * + * CURLE_URL_MALFORMAT - the hostname could not be converted + * CURLE_OUT_OF_MEMORY - memory problem + * + */ +static CURLcode idn_decode(const char *input, char **output) +{ + char *decoded = NULL; + CURLcode result = CURLE_OK; +#ifdef USE_LIBIDN2 + if(idn2_check_version(IDN2_VERSION)) { + int flags = IDN2_NFC_INPUT +#if IDN2_VERSION_NUMBER >= 0x00140000 + /* IDN2_NFC_INPUT: Normalize input string using normalization form C. + IDN2_NONTRANSITIONAL: Perform Unicode TR46 non-transitional + processing. */ + | IDN2_NONTRANSITIONAL +#endif + ; + int rc = IDN2_LOOKUP(input, &decoded, flags); + if(rc != IDN2_OK) + /* fallback to TR46 Transitional mode for better IDNA2003 + compatibility */ + rc = IDN2_LOOKUP(input, &decoded, IDN2_TRANSITIONAL); + if(rc != IDN2_OK) + result = CURLE_URL_MALFORMAT; + } + else + /* a too old libidn2 version */ + result = CURLE_NOT_BUILT_IN; +#elif defined(USE_WIN32_IDN) + result = win32_idn_to_ascii(input, &decoded); +#elif defined(USE_APPLE_IDN) + result = mac_idn_to_ascii(input, &decoded); +#endif + if(!result) + *output = decoded; + return result; +} + +static CURLcode idn_encode(const char *puny, char **output) +{ + char *enc = NULL; +#ifdef USE_LIBIDN2 + int rc = idn2_to_unicode_8z8z(puny, &enc, 0); + if(rc != IDNA_SUCCESS) + return rc == IDNA_MALLOC_ERROR ? CURLE_OUT_OF_MEMORY : CURLE_URL_MALFORMAT; +#elif defined(USE_WIN32_IDN) + CURLcode result = win32_ascii_to_idn(puny, &enc); + if(result) + return result; +#elif defined(USE_APPLE_IDN) + CURLcode result = mac_ascii_to_idn(puny, &enc); + if(result) + return result; +#endif + *output = enc; + return CURLE_OK; +} + +CURLcode Curl_idn_decode(const char *input, char **output) +{ + char *d = NULL; + CURLcode result = idn_decode(input, &d); +#ifdef USE_LIBIDN2 + if(!result) { + char *c = curlx_strdup(d); + idn2_free(d); + if(c) + d = c; + else + result = CURLE_OUT_OF_MEMORY; + } +#endif + if(!result) { + if(!d[0]) { /* ended up zero length, not acceptable */ + result = CURLE_URL_MALFORMAT; + curlx_free(d); + } + else + *output = d; + } + return result; +} + +CURLcode Curl_idn_encode(const char *puny, char **output) +{ + char *d = NULL; + CURLcode result = idn_encode(puny, &d); +#ifdef USE_LIBIDN2 + if(!result) { + char *c = curlx_strdup(d); + idn2_free(d); + if(c) + d = c; + else + result = CURLE_OUT_OF_MEMORY; + } +#endif + if(!result) + *output = d; + return result; +} + +/* + * Frees data allocated by idnconvert_hostname() + */ +void Curl_free_idnconverted_hostname(struct hostname *host) +{ + curlx_safefree(host->encalloc); +} + +#endif /* USE_IDN */ + +/* + * Perform any necessary IDN conversion of hostname + */ +CURLcode Curl_idnconvert_hostname(struct hostname *host) +{ + /* set the name we use to display the hostname */ + host->dispname = host->name; + +#ifdef USE_IDN + /* Check name for non-ASCII and convert hostname if we can */ + if(!Curl_is_ASCII_name(host->name)) { + char *decoded; + CURLcode result = Curl_idn_decode(host->name, &decoded); + if(result) + return result; + /* successful */ + host->name = host->encalloc = decoded; + } +#endif + return CURLE_OK; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/idn.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/idn.h new file mode 100644 index 0000000000..c73b870a70 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/idn.h @@ -0,0 +1,45 @@ +#ifndef HEADER_CURL_IDN_H +#define HEADER_CURL_IDN_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +struct Curl_str; +struct hostname; + +bool Curl_is_ASCII_name(const char *hostname); +bool Curl_is_ASCII_str(struct Curl_str *s); + +CURLcode Curl_idnconvert_hostname(struct hostname *host); + +#if defined(USE_LIBIDN2) || defined(USE_WIN32_IDN) || defined(USE_APPLE_IDN) +#define USE_IDN +void Curl_free_idnconverted_hostname(struct hostname *host); +CURLcode Curl_idn_decode(const char *input, char **output); +CURLcode Curl_idn_encode(const char *puny, char **output); +#else +#define Curl_free_idnconverted_hostname(x) +#define Curl_idn_decode(x) NULL +#endif + +#endif /* HEADER_CURL_IDN_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/if2ip.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/if2ip.c new file mode 100644 index 0000000000..9a9fbe7691 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/if2ip.c @@ -0,0 +1,262 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NET_IF_H +#include <net/if.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_SYS_SOCKIO_H +#include <sys/sockio.h> +#endif +#ifdef HAVE_IFADDRS_H +#include <ifaddrs.h> +#endif +#ifdef HAVE_STROPTS_H +#include <stropts.h> +#endif +#ifdef __VMS +#include <inet.h> +#endif + +#include "curlx/inet_ntop.h" +#include "if2ip.h" + +/* ------------------------------------------------------------------ */ + +#ifdef USE_IPV6 +/* Return the scope of the given address. */ +unsigned int Curl_ipv6_scope(const struct sockaddr *sa) +{ + if(sa->sa_family == AF_INET6) { + const struct sockaddr_in6 *sa6 = + (const struct sockaddr_in6 *)(const void *)sa; + const unsigned char *b = sa6->sin6_addr.s6_addr; + unsigned short w = (unsigned short)((b[0] << 8) | b[1]); + + if((b[0] & 0xFE) == 0xFC) /* Handle ULAs */ + return IPV6_SCOPE_UNIQUELOCAL; + switch(w & 0xFFC0) { + case 0xFE80: + return IPV6_SCOPE_LINKLOCAL; + case 0xFEC0: + return IPV6_SCOPE_SITELOCAL; + case 0x0000: + w = b[1] | b[2] | b[3] | b[4] | b[5] | b[6] | b[7] | b[8] | b[9] | + b[10] | b[11] | b[12] | b[13] | b[14]; + if(w || b[15] != 0x01) + break; + return IPV6_SCOPE_NODELOCAL; + default: + break; + } + } + return IPV6_SCOPE_GLOBAL; +} +#endif + +#if !defined(CURL_DISABLE_BINDLOCAL) || !defined(CURL_DISABLE_FTP) + +#ifdef HAVE_GETIFADDRS + +if2ip_result_t Curl_if2ip(int af, +#ifdef USE_IPV6 + unsigned int remote_scope, + unsigned int local_scope_id, +#endif + const char *interf, + char *buf, size_t buf_size) +{ + struct ifaddrs *iface, *head; + if2ip_result_t res = IF2IP_NOT_FOUND; + +#if defined(USE_IPV6) && !defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID) + (void)local_scope_id; +#endif + + if(getifaddrs(&head) >= 0) { + for(iface = head; iface; iface = iface->ifa_next) { + if(iface->ifa_addr) { + if(iface->ifa_addr->sa_family == af) { + if(curl_strequal(iface->ifa_name, interf)) { + void *addr; + char scope[12] = ""; + char ipstr[64]; + CURLcode result; +#ifdef USE_IPV6 + if(af == AF_INET6) { +#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID + unsigned int scopeid = 0; +#endif + unsigned int ifscope = Curl_ipv6_scope(iface->ifa_addr); + + if(ifscope != remote_scope) { + /* We are interested only in interface addresses whose scope + matches the remote address we want to connect to: global + for global, link-local for link-local, etc... */ + if(res == IF2IP_NOT_FOUND) + res = IF2IP_AF_NOT_SUPPORTED; + continue; + } + + addr = + &((struct sockaddr_in6 *)(void *)iface->ifa_addr)->sin6_addr; +#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID + /* Include the scope of this interface as part of the address */ + scopeid = ((struct sockaddr_in6 *)(void *)iface->ifa_addr) + ->sin6_scope_id; + + /* If given, scope id should match. */ + if(local_scope_id && scopeid != local_scope_id) { + if(res == IF2IP_NOT_FOUND) + res = IF2IP_AF_NOT_SUPPORTED; + + continue; + } + + if(scopeid) + curl_msnprintf(scope, sizeof(scope), "%%%u", scopeid); +#endif + } + else +#endif + addr = + &((struct sockaddr_in *)(void *)iface->ifa_addr)->sin_addr; + res = IF2IP_FOUND; + result = curlx_inet_ntop(af, addr, ipstr, sizeof(ipstr)); + curl_msnprintf(buf, buf_size, "%s%s", result ? "" : ipstr, scope); + break; + } + } + else if((res == IF2IP_NOT_FOUND) && + curl_strequal(iface->ifa_name, interf)) { + res = IF2IP_AF_NOT_SUPPORTED; + } + } + } + + freeifaddrs(head); + } + + return res; +} + +#elif defined(HAVE_IOCTL_SIOCGIFADDR) + +if2ip_result_t Curl_if2ip(int af, +#ifdef USE_IPV6 + unsigned int remote_scope, + unsigned int local_scope_id, +#endif + const char *interf, + char *buf, size_t buf_size) +{ + struct ifreq req; + struct in_addr in; + struct sockaddr_in *s; + curl_socket_t dummy; + size_t len; + CURLcode result; + +#ifdef USE_IPV6 + (void)remote_scope; + (void)local_scope_id; +#endif + + if(!interf || (af != AF_INET)) + return IF2IP_NOT_FOUND; + + len = strlen(interf); + if(len >= sizeof(req.ifr_name)) + return IF2IP_NOT_FOUND; + + dummy = CURL_SOCKET(AF_INET, SOCK_STREAM, 0); + if(dummy == CURL_SOCKET_BAD) + return IF2IP_NOT_FOUND; + + memset(&req, 0, sizeof(req)); + memcpy(req.ifr_name, interf, len + 1); + req.ifr_addr.sa_family = AF_INET; + +#if defined(CURL_HAVE_DIAG) && defined(_AIX) +/* Suppress warning inside system headers */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wshift-sign-overflow" +#endif + if(ioctl(dummy, SIOCGIFADDR, &req) < 0) { +#if defined(CURL_HAVE_DIAG) && defined(_AIX) +#pragma GCC diagnostic pop +#endif + sclose(dummy); + /* With SIOCGIFADDR, we cannot tell the difference between an interface + that does not exist and an interface that has no address of the + correct family. Assume the interface does not exist */ + return IF2IP_NOT_FOUND; + } + + s = (struct sockaddr_in *)(void *)&req.ifr_addr; + memcpy(&in, &s->sin_addr, sizeof(in)); + result = curlx_inet_ntop(s->sin_family, &in, buf, buf_size); + + sclose(dummy); + if(result) + return IF2IP_NOT_FOUND; + return IF2IP_FOUND; +} + +#else + +if2ip_result_t Curl_if2ip(int af, +#ifdef USE_IPV6 + unsigned int remote_scope, + unsigned int local_scope_id, +#endif + const char *interf, + char *buf, size_t buf_size) +{ + (void)af; +#ifdef USE_IPV6 + (void)remote_scope; + (void)local_scope_id; +#endif + (void)interf; + (void)buf; + (void)buf_size; + return IF2IP_NOT_FOUND; +} + +#endif + +#endif /* CURL_DISABLE_BINDLOCAL && CURL_DISABLE_FTP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/if2ip.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/if2ip.h new file mode 100644 index 0000000000..dc79c383b7 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/if2ip.h @@ -0,0 +1,91 @@ +#ifndef HEADER_CURL_IF2IP_H +#define HEADER_CURL_IF2IP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* IPv6 address scopes. */ +#define IPV6_SCOPE_GLOBAL 0 /* Global scope. */ +#define IPV6_SCOPE_LINKLOCAL 1 /* Link-local scope. */ +#define IPV6_SCOPE_SITELOCAL 2 /* Site-local scope (deprecated). */ +#define IPV6_SCOPE_UNIQUELOCAL 3 /* Unique local */ +#define IPV6_SCOPE_NODELOCAL 4 /* Loopback. */ + +#ifdef USE_IPV6 +unsigned int Curl_ipv6_scope(const struct sockaddr *sa); +#else +#define Curl_ipv6_scope(x) 0 +#endif + +typedef enum { + IF2IP_NOT_FOUND = 0, /* Interface not found */ + IF2IP_AF_NOT_SUPPORTED = 1, /* Int. exists but has no address for this af */ + IF2IP_FOUND = 2 /* The address has been stored in "buf" */ +} if2ip_result_t; + +if2ip_result_t Curl_if2ip(int af, +#ifdef USE_IPV6 + unsigned int remote_scope, + unsigned int local_scope_id, +#endif + const char *interf, + char *buf, size_t buf_size); + +#ifdef __INTERIX + +/* Nedelcho Stanev's workaround for SFU 3.0 */ +struct ifreq { +#define IFNAMSIZ 16 +#define IFHWADDRLEN 6 + union { + char ifrn_name[IFNAMSIZ]; /* if name, e.g. "en0" */ + } ifr_ifrn; + + union { + struct sockaddr ifru_addr; + struct sockaddr ifru_broadaddr; + struct sockaddr ifru_netmask; + struct sockaddr ifru_hwaddr; + short ifru_flags; + int ifru_metric; + int ifru_mtu; + } ifr_ifru; +}; + +/* This define exists to avoid an extra #ifdef INTERIX in the C code. */ + +#define ifr_name ifr_ifrn.ifrn_name /* interface name */ +#define ifr_addr ifr_ifru.ifru_addr /* address */ +#define ifr_broadaddr ifr_ifru.ifru_broadaddr /* broadcast address */ +#define ifr_netmask ifr_ifru.ifru_netmask /* interface net mask */ +#define ifr_flags ifr_ifru.ifru_flags /* flags */ +#define ifr_hwaddr ifr_ifru.ifru_hwaddr /* MAC address */ +#define ifr_metric ifr_ifru.ifru_metric /* metric */ +#define ifr_mtu ifr_ifru.ifru_mtu /* mtu */ + +#define SIOCGIFADDR _IOW('s', 102, struct ifreq) /* Get if addr */ + +#endif /* __INTERIX */ + +#endif /* HEADER_CURL_IF2IP_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/imap.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/imap.c new file mode 100644 index 0000000000..62ab0a283b --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/imap.c @@ -0,0 +1,2333 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC2195 CRAM-MD5 authentication + * RFC2595 Using TLS with IMAP, POP3 and ACAP + * RFC2831 DIGEST-MD5 authentication + * RFC3501 IMAPv4 protocol + * RFC4422 Simple Authentication and Security Layer (SASL) + * RFC4616 PLAIN authentication + * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism + * RFC4959 IMAP Extension for SASL Initial Client Response + * RFC5092 IMAP URL Scheme + * RFC6749 OAuth 2.0 Authorization Framework + * RFC8314 Use of TLS for Email Submission and Access + * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt> + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" +#include "imap.h" + +#ifndef CURL_DISABLE_IMAP + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include "curlx/dynbuf.h" +#include "sendf.h" +#include "curl_trc.h" +#include "progress.h" +#include "transfer.h" +#include "escape.h" +#include "pingpong.h" +#include "mime.h" +#include "curlx/strparse.h" +#include "strcase.h" +#include "vtls/vtls.h" +#include "cfilters.h" +#include "connect.h" +#include "select.h" +#include "url.h" +#include "bufref.h" +#include "curl_sasl.h" +#include "curlx/strcopy.h" + +/* meta key for storing protocol meta at easy handle */ +#define CURL_META_IMAP_EASY "meta:proto:imap:easy" +/* meta key for storing protocol meta at connection */ +#define CURL_META_IMAP_CONN "meta:proto:imap:conn" + +typedef enum { + IMAP_STOP, /* do nothing state, stops the state machine */ + IMAP_SERVERGREET, /* waiting for the initial greeting immediately after + a connect */ + IMAP_CAPABILITY, + IMAP_STARTTLS, + IMAP_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS + (multi mode only) */ + IMAP_AUTHENTICATE, + IMAP_LOGIN, + IMAP_LIST, + IMAP_SELECT, + IMAP_FETCH, + IMAP_FETCH_FINAL, + IMAP_APPEND, + IMAP_APPEND_FINAL, + IMAP_SEARCH, + IMAP_LOGOUT, + IMAP_LAST /* never used */ +} imapstate; + +/* imap_conn is used for struct connection-oriented data */ +struct imap_conn { + struct pingpong pp; + struct SASL sasl; /* SASL-related parameters */ + struct dynbuf dyn; /* for the IMAP commands */ + char *mailbox; /* The last selected mailbox */ + imapstate state; /* Always use imap.c:state() to change state! */ + unsigned int mb_uidvalidity; /* UIDVALIDITY parsed from select response */ + char resptag[5]; /* Response tag to wait for */ + unsigned char preftype; /* Preferred authentication type */ + unsigned char cmdid; /* Last used command ID */ + BIT(ssldone); /* Is connect() over SSL done? */ + BIT(preauth); /* Is this connection PREAUTH? */ + BIT(tls_supported); /* StartTLS capability supported by server */ + BIT(login_disabled); /* LOGIN command disabled by server */ + BIT(ir_supported); /* Initial response supported by server */ + BIT(mb_uidvalidity_set); +}; + +/* This IMAP struct is used in the Curl_easy. All IMAP data that is + connection-oriented must be in imap_conn to properly deal with the fact that + perhaps the Curl_easy is changed between the times the connection is + used. */ +struct IMAP { + curl_pp_transfer transfer; + char *mailbox; /* Mailbox to select */ + char *uid; /* Message UID to fetch */ + char *mindex; /* Index in mail box of mail to fetch */ + char *section; /* Message SECTION to fetch */ + char *partial; /* Message PARTIAL to fetch */ + char *query; /* Query to search for */ + char *custom; /* Custom request */ + char *custom_params; /* Parameters for the custom request */ + unsigned int uidvalidity; /* UIDVALIDITY to check in select */ + BIT(uidvalidity_set); +}; + +#define IMAP_RESP_OK 1 +#define IMAP_RESP_NOT_OK 2 +#define IMAP_RESP_PREAUTH 3 + +struct ulbits { + int bit; + const char *flag; +}; + +/*********************************************************************** + * + * imap_sendf() + * + * Sends the formatted string as an IMAP command to the server. + * + * Designed to never block. + */ +static CURLcode imap_sendf(struct Curl_easy *data, + struct imap_conn *imapc, + const char *fmt, ...) CURL_PRINTF(3, 0); +static CURLcode imap_sendf(struct Curl_easy *data, + struct imap_conn *imapc, + const char *fmt, ...) +{ + CURLcode result = CURLE_OK; + + DEBUGASSERT(fmt); + + /* Calculate the tag based on the connection ID and command ID */ + curl_msnprintf(imapc->resptag, sizeof(imapc->resptag), "%c%03d", + 'A' + curlx_sltosi((long)(data->conn->connection_id % 26)), + ++imapc->cmdid); + + /* start with a blank buffer */ + curlx_dyn_reset(&imapc->dyn); + + /* append tag + space + fmt */ + result = curlx_dyn_addf(&imapc->dyn, "%s %s", imapc->resptag, fmt); + if(!result) { + va_list ap; + va_start(ap, fmt); +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wformat-nonliteral" +#endif + result = Curl_pp_vsendf(data, &imapc->pp, curlx_dyn_ptr(&imapc->dyn), ap); +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + va_end(ap); + } + return result; +} + +/*********************************************************************** + * + * imap_atom() + * + * Checks the input string for characters that need escaping and returns an + * atom ready for sending to the server. + * + * The returned string needs to be freed. + * + */ +static char *imap_atom(const char *str, bool escape_only) +{ + struct dynbuf line; + size_t nclean; + size_t len; + + if(!str) + return NULL; + + len = strlen(str); + nclean = strcspn(str, "() {%*]\\\""); + if(len == nclean) + /* nothing to escape, return a strdup */ + return curlx_strdup(str); + + curlx_dyn_init(&line, 2000); + + if(!escape_only && curlx_dyn_addn(&line, "\"", 1)) + return NULL; + + while(*str) { + if((*str == '\\' || *str == '"') && + curlx_dyn_addn(&line, "\\", 1)) + return NULL; + if(curlx_dyn_addn(&line, str, 1)) + return NULL; + str++; + } + + if(!escape_only && curlx_dyn_addn(&line, "\"", 1)) + return NULL; + + return curlx_dyn_ptr(&line); +} + +/* + * Finds the start of a literal '{size}' in line, skipping over quoted strings. + */ +static const char *imap_find_literal(const char *line, size_t len) +{ + const char *end = line + len; + bool in_quote = FALSE; + + while(line < end) { + if(in_quote) { + if(*line == '\\' && (line + 1) < end) { + line += 2; + continue; + } + if(*line == '"') + in_quote = FALSE; + } + else { + if(*line == '"') + in_quote = TRUE; + else if(*line == '{') + return line; + } + line++; + } + return NULL; +} + +/*********************************************************************** + * + * imap_matchresp() + * + * Determines whether the untagged response is related to the specified + * command by checking if it is in format "* <command-name> ..." or + * "* <number> <command-name> ...". + * + * The "* " marker is assumed to have already been checked by the caller. + */ +static bool imap_matchresp(const char *line, size_t len, const char *cmd) +{ + const char *end = line + len; + size_t cmd_len = strlen(cmd); + + /* Skip the untagged response marker */ + line += 2; + + /* Do we have a number after the marker? */ + if(line < end && ISDIGIT(*line)) { + /* Skip the number */ + do + line++; + while(line < end && ISDIGIT(*line)); + + /* Do we have the space character? */ + if(line == end || *line != ' ') + return FALSE; + + line++; + } + + /* Does the command name match and is it followed by a space character or at + the end of line? */ + if(line + cmd_len <= end && curl_strnequal(line, cmd, cmd_len) && + (line[cmd_len] == ' ' || line + cmd_len + 2 == end)) + return TRUE; + + return FALSE; +} + +/*********************************************************************** + * + * imap_endofresp() + * + * Checks whether the given string is a valid tagged, untagged or continuation + * response which can be processed by the response handler. + */ +static bool imap_endofresp(struct Curl_easy *data, struct connectdata *conn, + const char *line, size_t len, int *resp) +{ + struct imap_conn *imapc = Curl_conn_meta_get(conn, CURL_META_IMAP_CONN); + struct IMAP *imap = Curl_meta_get(data, CURL_META_IMAP_EASY); + const char *id; + size_t id_len; + + DEBUGASSERT(imapc); + DEBUGASSERT(imap); + if(!imapc || !imap) + return FALSE; + + /* Do we have a tagged command response? */ + id = imapc->resptag; + id_len = strlen(id); + if(len >= id_len + 1 && !memcmp(id, line, id_len) && line[id_len] == ' ') { + line += id_len + 1; + len -= id_len + 1; + + if(len >= 2 && !memcmp(line, "OK", 2)) + *resp = IMAP_RESP_OK; + else if(len >= 7 && !memcmp(line, "PREAUTH", 7)) + *resp = IMAP_RESP_PREAUTH; + else + *resp = IMAP_RESP_NOT_OK; + + return TRUE; + } + + /* Do we have an untagged command response? */ + if(len >= 2 && !memcmp("* ", line, 2)) { + switch(imapc->state) { + /* States which are interested in untagged responses */ + case IMAP_CAPABILITY: + if(!imap_matchresp(line, len, "CAPABILITY")) + return FALSE; + break; + + case IMAP_LIST: + if((!imap->custom && !imap_matchresp(line, len, "LIST")) || + (imap->custom && !imap_matchresp(line, len, imap->custom) && + (!curl_strequal(imap->custom, "STORE") || + !imap_matchresp(line, len, "FETCH")) && + !curl_strequal(imap->custom, "SELECT") && + !curl_strequal(imap->custom, "EXAMINE") && + !curl_strequal(imap->custom, "SEARCH") && + !curl_strequal(imap->custom, "EXPUNGE") && + !curl_strequal(imap->custom, "LSUB") && + !curl_strequal(imap->custom, "UID") && + !curl_strequal(imap->custom, "GETQUOTAROOT") && + !curl_strequal(imap->custom, "NOOP"))) + return FALSE; + break; + + case IMAP_SELECT: + /* SELECT is special in that its untagged responses do not have a + common prefix so accept anything! */ + break; + + case IMAP_FETCH: + if(!imap_matchresp(line, len, "FETCH")) + return FALSE; + break; + + case IMAP_SEARCH: + if(!imap_matchresp(line, len, "SEARCH")) + return FALSE; + break; + + /* Ignore other untagged responses */ + default: + return FALSE; + } + + *resp = '*'; + return TRUE; + } + + /* Do we have a continuation response? This should be a + symbol followed by + a space and optionally some text as per RFC-3501 for the AUTHENTICATE and + APPEND commands and as outlined in Section 4. Examples of RFC-4959 but + some email servers ignore this and only send a single + instead. */ + if(!imap->custom && ((len == 3 && line[0] == '+') || + (len >= 2 && !memcmp("+ ", line, 2)))) { + switch(imapc->state) { + /* States which are interested in continuation responses */ + case IMAP_AUTHENTICATE: + case IMAP_APPEND: + *resp = '+'; + break; + + default: + failf(data, "Unexpected continuation response"); + *resp = -1; + break; + } + + return TRUE; + } + + return FALSE; /* Nothing for us */ +} + +/*********************************************************************** + * + * imap_get_message() + * + * Gets the authentication message from the response buffer. + */ +static CURLcode imap_get_message(struct Curl_easy *data, struct bufref *out) +{ + struct imap_conn *imapc = + Curl_conn_meta_get(data->conn, CURL_META_IMAP_CONN); + char *message; + size_t len; + + if(!imapc) + return CURLE_FAILED_INIT; + + message = curlx_dyn_ptr(&imapc->pp.recvbuf); + len = imapc->pp.nfinal; + if(len > 2) { + /* Find the start of the message */ + len -= 2; + for(message += 2; ISBLANK(*message); message++, len--) + ; + + /* Find the end of the message */ + while(len--) + if(!ISNEWLINE(message[len]) && !ISBLANK(message[len])) + break; + + /* Terminate the message */ + message[++len] = '\0'; + Curl_bufref_set(out, message, len, NULL); + } + else + /* junk input => zero length output */ + Curl_bufref_set(out, "", 0, NULL); + + return CURLE_OK; +} + +/*********************************************************************** + * + * imap_state() + * + * This is the ONLY way to change IMAP state! + */ +static void imap_state(struct Curl_easy *data, + struct imap_conn *imapc, + imapstate newstate) +{ +#if defined(DEBUGBUILD) && defined(CURLVERBOSE) + /* for debug purposes */ + static const char * const names[] = { + "STOP", + "SERVERGREET", + "CAPABILITY", + "STARTTLS", + "UPGRADETLS", + "AUTHENTICATE", + "LOGIN", + "LIST", + "SELECT", + "FETCH", + "FETCH_FINAL", + "APPEND", + "APPEND_FINAL", + "SEARCH", + "LOGOUT", + /* LAST */ + }; + + if(imapc->state != newstate) + infof(data, "IMAP %p state change from %s to %s", + (void *)imapc, names[imapc->state], names[newstate]); +#else + (void)data; +#endif + imapc->state = newstate; +} + +/*********************************************************************** + * + * imap_perform_capability() + * + * Sends the CAPABILITY command in order to obtain a list of server side + * supported capabilities. + */ +static CURLcode imap_perform_capability(struct Curl_easy *data, + struct imap_conn *imapc) +{ + CURLcode result = CURLE_OK; + + imapc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanisms yet */ + imapc->sasl.authused = SASL_AUTH_NONE; /* Clear the auth. mechanism used */ + imapc->tls_supported = FALSE; /* Clear the TLS capability */ + + /* Send the CAPABILITY command */ + result = imap_sendf(data, imapc, "CAPABILITY"); + + if(!result) + imap_state(data, imapc, IMAP_CAPABILITY); + + return result; +} + +/*********************************************************************** + * + * imap_perform_starttls() + * + * Sends the STARTTLS command to start the upgrade to TLS. + */ +static CURLcode imap_perform_starttls(struct Curl_easy *data, + struct imap_conn *imapc) +{ + /* Send the STARTTLS command */ + CURLcode result = imap_sendf(data, imapc, "STARTTLS"); + + if(!result) + imap_state(data, imapc, IMAP_STARTTLS); + + return result; +} + +/*********************************************************************** + * + * imap_perform_upgrade_tls() + * + * Performs the upgrade to TLS. + */ +static CURLcode imap_perform_upgrade_tls(struct Curl_easy *data, + struct imap_conn *imapc, + struct connectdata *conn) +{ +#ifdef USE_SSL + /* Start the SSL connection */ + CURLcode result; + bool ssldone = FALSE; + + if(!Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + result = Curl_ssl_cfilter_add( + data, Curl_conn_get_origin(conn, FIRSTSOCKET), conn, FIRSTSOCKET); + if(result) + goto out; + /* Change the connection handler */ + conn->scheme = &Curl_scheme_imaps; + } + + DEBUGASSERT(!imapc->ssldone); + result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssldone); + DEBUGF(infof(data, "imap_perform_upgrade_tls, connect -> %d, %d", + (int)result, ssldone)); + if(!result && ssldone) { + imapc->ssldone = ssldone; + /* perform CAPA now, changes imapc->state out of IMAP_UPGRADETLS */ + result = imap_perform_capability(data, imapc); + } +out: + return result; +#else + (void)data; + (void)imapc; + (void)conn; + return CURLE_NOT_BUILT_IN; +#endif +} + +/*********************************************************************** + * + * imap_perform_login() + * + * Sends a clear text LOGIN command to authenticate with. + */ +static CURLcode imap_perform_login(struct Curl_easy *data, + struct imap_conn *imapc, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + char *user; + char *passwd; + + /* Check we have a username and password to authenticate with and end the + connect phase if we do not */ + if(!conn->creds) { + imap_state(data, imapc, IMAP_STOP); + + return result; + } + + /* Make sure the username and password are in the correct atom format */ + user = imap_atom(Curl_creds_user(conn->creds), FALSE); + passwd = imap_atom(Curl_creds_passwd(conn->creds), FALSE); + + /* Send the LOGIN command */ + result = imap_sendf(data, imapc, "LOGIN %s %s", user ? user : "", + passwd ? passwd : ""); + + curlx_free(user); + curlx_strzero(passwd); + curlx_free(passwd); + + if(!result) + imap_state(data, imapc, IMAP_LOGIN); + + return result; +} + +/*********************************************************************** + * + * imap_perform_authenticate() + * + * Sends an AUTHENTICATE command allowing the client to login with the given + * SASL authentication mechanism. + */ +static CURLcode imap_perform_authenticate(struct Curl_easy *data, + const char *mech, + const struct bufref *initresp) +{ + struct imap_conn *imapc = + Curl_conn_meta_get(data->conn, CURL_META_IMAP_CONN); + CURLcode result = CURLE_OK; + const char *ir = Curl_bufref_ptr(initresp); + + if(!imapc) + return CURLE_FAILED_INIT; + if(ir) { + /* Send the AUTHENTICATE command with the initial response */ + result = imap_sendf(data, imapc, "AUTHENTICATE %s %s", + mech, *ir ? ir : "="); + } + else { + /* Send the AUTHENTICATE command */ + result = imap_sendf(data, imapc, "AUTHENTICATE %s", mech); + } + + return result; +} + +/*********************************************************************** + * + * imap_continue_authenticate() + * + * Sends SASL continuation data. + */ +static CURLcode imap_continue_authenticate(struct Curl_easy *data, + const char *mech, + const struct bufref *resp) +{ + struct imap_conn *imapc = + Curl_conn_meta_get(data->conn, CURL_META_IMAP_CONN); + + (void)mech; + if(!imapc) + return CURLE_FAILED_INIT; + return Curl_pp_sendf(data, &imapc->pp, "%s", Curl_bufref_ptr(resp)); +} + +/*********************************************************************** + * + * imap_cancel_authenticate() + * + * Sends SASL cancellation. + */ +static CURLcode imap_cancel_authenticate(struct Curl_easy *data, + const char *mech) +{ + struct imap_conn *imapc = + Curl_conn_meta_get(data->conn, CURL_META_IMAP_CONN); + + (void)mech; + if(!imapc) + return CURLE_FAILED_INIT; + return Curl_pp_sendf(data, &imapc->pp, "*"); +} + +/*********************************************************************** + * + * imap_perform_authentication() + * + * Initiates the authentication sequence, with the appropriate SASL + * authentication mechanism, falling back to clear text should a common + * mechanism not be available between the client and server. + */ +static CURLcode imap_perform_authentication(struct Curl_easy *data, + struct imap_conn *imapc) +{ + CURLcode result = CURLE_OK; + saslprogress progress; + + /* Check if already authenticated OR if there is enough data to authenticate + with and end the connect phase if we do not */ + if(imapc->preauth || + !Curl_sasl_can_authenticate(&imapc->sasl, data)) { + imap_state(data, imapc, IMAP_STOP); + return result; + } + + /* Calculate the SASL login details */ + result = Curl_sasl_start(&imapc->sasl, data, (bool)imapc->ir_supported, + &progress); + if(!result) { + if(progress == SASL_INPROGRESS) + imap_state(data, imapc, IMAP_AUTHENTICATE); + else if(!imapc->login_disabled && (imapc->preftype & IMAP_TYPE_CLEARTEXT)) + /* Perform clear text authentication */ + result = imap_perform_login(data, imapc, data->conn); + else + result = Curl_sasl_is_blocked(&imapc->sasl, data); + } + + return result; +} + +/*********************************************************************** + * + * imap_perform_list() + * + * Sends a LIST command or an alternative custom request. + */ +static CURLcode imap_perform_list(struct Curl_easy *data, + struct imap_conn *imapc, + struct IMAP *imap) +{ + CURLcode result = CURLE_OK; + + if(imap->custom) + /* Send the custom request */ + result = imap_sendf(data, imapc, "%s%s", imap->custom, + imap->custom_params ? imap->custom_params : ""); + else { + /* Make sure the mailbox is in the correct atom format if necessary */ + char *mailbox = imap->mailbox ? imap_atom(imap->mailbox, TRUE) + : curlx_strdup(""); + if(!mailbox) + return CURLE_OUT_OF_MEMORY; + + /* Send the LIST command */ + result = imap_sendf(data, imapc, "LIST \"%s\" *", mailbox); + + curlx_free(mailbox); + } + + if(!result) + imap_state(data, imapc, IMAP_LIST); + + return result; +} + +/*********************************************************************** + * + * imap_perform_select() + * + * Sends a SELECT command to ask the server to change the selected mailbox. + */ +static CURLcode imap_perform_select(struct Curl_easy *data, + struct imap_conn *imapc, + struct IMAP *imap) +{ + CURLcode result = CURLE_OK; + char *mailbox; + + /* Invalidate old information as we are switching mailboxes */ + curlx_safefree(imapc->mailbox); + imapc->mb_uidvalidity_set = FALSE; + + /* Check we have a mailbox */ + if(!imap->mailbox) { + failf(data, "Cannot SELECT without a mailbox."); + return CURLE_URL_MALFORMAT; + } + + /* Make sure the mailbox is in the correct atom format */ + mailbox = imap_atom(imap->mailbox, FALSE); + if(!mailbox) + return CURLE_OUT_OF_MEMORY; + + /* Send the SELECT command */ + result = imap_sendf(data, imapc, "SELECT %s", mailbox); + + curlx_free(mailbox); + + if(!result) + imap_state(data, imapc, IMAP_SELECT); + + return result; +} + +/*********************************************************************** + * + * imap_perform_fetch() + * + * Sends a FETCH command to initiate the download of a message. + */ +static CURLcode imap_perform_fetch(struct Curl_easy *data, + struct imap_conn *imapc, + struct IMAP *imap) +{ + CURLcode result = CURLE_OK; + /* Check we have a UID */ + if(imap->uid) { + + /* Send the FETCH command */ + if(imap->partial) + result = imap_sendf(data, imapc, "UID FETCH %s BODY[%s]<%s>", + imap->uid, imap->section ? imap->section : "", + imap->partial); + else + result = imap_sendf(data, imapc, "UID FETCH %s BODY[%s]", + imap->uid, imap->section ? imap->section : ""); + } + else if(imap->mindex) { + /* Send the FETCH command */ + if(imap->partial) + result = imap_sendf(data, imapc, "FETCH %s BODY[%s]<%s>", + imap->mindex, imap->section ? imap->section : "", + imap->partial); + else + result = imap_sendf(data, imapc, "FETCH %s BODY[%s]", + imap->mindex, imap->section ? imap->section : ""); + } + else { + failf(data, "Cannot FETCH without a UID."); + return CURLE_URL_MALFORMAT; + } + if(!result) + imap_state(data, imapc, IMAP_FETCH); + + return result; +} + +/*********************************************************************** + * + * imap_perform_append() + * + * Sends an APPEND command to initiate the upload of a message. + */ +static CURLcode imap_perform_append(struct Curl_easy *data, + struct imap_conn *imapc, + struct IMAP *imap) +{ + CURLcode result = CURLE_OK; + char *mailbox; + struct dynbuf flags; + + /* Check we have a mailbox */ + if(!imap->mailbox) { + failf(data, "Cannot APPEND without a mailbox."); + return CURLE_URL_MALFORMAT; + } + +#ifndef CURL_DISABLE_MIME + /* Prepare the mime data if some. */ + if(IS_MIME_POST(data)) { + curl_mimepart *postp = data->set.mimepostp; + + /* Use the whole structure as data. */ + postp->flags &= ~(unsigned int)MIME_BODY_ONLY; + + /* Add external headers and mime version. */ + curl_mime_headers(postp, data->set.headers, 0); + result = Curl_mime_prepare_headers(data, postp, NULL, + NULL, MIMESTRATEGY_MAIL); + + if(!result) + if(!Curl_checkheaders(data, STRCONST("Mime-Version"))) + result = Curl_mime_add_header(&postp->curlheaders, + "Mime-Version: 1.0"); + + if(!result) + result = Curl_creader_set_mime(data, postp); + if(result) + return result; + } + else +#endif + { + result = Curl_creader_set_fread(data, data->state.infilesize); + if(result) + return result; + } + + /* Check we know the size of the upload. This takes all readers + * into account. Especially crlf conversions which make the size + * unpredictable, e.g. -1. */ + data->state.infilesize = Curl_creader_total_length(data); + if(data->state.infilesize < 0) { + if(data->set.crlf) + failf(data, "Cannot APPEND with CRLF conversion making size unknown"); + else + failf(data, "Cannot APPEND with unknown input file size"); + return CURLE_UPLOAD_FAILED; + } + + /* Make sure the mailbox is in the correct atom format */ + mailbox = imap_atom(imap->mailbox, FALSE); + if(!mailbox) + return CURLE_OUT_OF_MEMORY; + + /* Generate flags string and send the APPEND command */ + curlx_dyn_init(&flags, 100); + if(data->set.upload_flags) { + int i; + struct ulbits ulflag[] = { + { CURLULFLAG_ANSWERED, "Answered" }, + { CURLULFLAG_DELETED, "Deleted" }, + { CURLULFLAG_DRAFT, "Draft" }, + { CURLULFLAG_FLAGGED, "Flagged" }, + { CURLULFLAG_SEEN, "Seen" }, + { 0, NULL } + }; + + result = CURLE_OUT_OF_MEMORY; + if(curlx_dyn_add(&flags, " (")) { + goto cleanup; + } + + for(i = 0; ulflag[i].bit; i++) { + if(data->set.upload_flags & ulflag[i].bit) { + if((curlx_dyn_len(&flags) > 2 && curlx_dyn_add(&flags, " ")) || + curlx_dyn_add(&flags, "\\") || + curlx_dyn_add(&flags, ulflag[i].flag)) + goto cleanup; + } + } + + if(curlx_dyn_add(&flags, ")")) + goto cleanup; + } + else if(curlx_dyn_add(&flags, "")) + goto cleanup; + + result = imap_sendf(data, imapc, "APPEND %s%s {%" FMT_OFF_T "}", + mailbox, curlx_dyn_ptr(&flags), data->state.infilesize); + +cleanup: + curlx_dyn_free(&flags); + curlx_free(mailbox); + + if(!result) + imap_state(data, imapc, IMAP_APPEND); + + return result; +} + +/*********************************************************************** + * + * imap_perform_search() + * + * Sends a SEARCH command. + */ +static CURLcode imap_perform_search(struct Curl_easy *data, + struct imap_conn *imapc, + struct IMAP *imap) +{ + CURLcode result = CURLE_OK; + + /* Check we have a query string */ + if(!imap->query) { + failf(data, "Cannot SEARCH without a query string."); + return CURLE_URL_MALFORMAT; + } + + /* Send the SEARCH command */ + result = imap_sendf(data, imapc, "SEARCH %s", imap->query); + + if(!result) + imap_state(data, imapc, IMAP_SEARCH); + + return result; +} + +/*********************************************************************** + * + * imap_perform_logout() + * + * Performs the logout action prior to sclose() being called. + */ +static CURLcode imap_perform_logout(struct Curl_easy *data, + struct imap_conn *imapc) +{ + /* Send the LOGOUT command */ + CURLcode result = imap_sendf(data, imapc, "LOGOUT"); + + if(!result) + imap_state(data, imapc, IMAP_LOGOUT); + + return result; +} + +/* For the initial server greeting */ +static CURLcode imap_state_servergreet_resp(struct Curl_easy *data, + struct imap_conn *imapc, + int imapcode, + imapstate instate) +{ + (void)instate; + + if(imapcode == IMAP_RESP_PREAUTH) { + /* PREAUTH */ + imapc->preauth = TRUE; + infof(data, "PREAUTH connection, already authenticated"); + } + else if(imapcode != IMAP_RESP_OK) { + failf(data, "Got unexpected imap-server response"); + return CURLE_WEIRD_SERVER_REPLY; + } + + return imap_perform_capability(data, imapc); +} + +/* For CAPABILITY responses */ +static CURLcode imap_state_capability_resp(struct Curl_easy *data, + struct imap_conn *imapc, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + const char *line = curlx_dyn_ptr(&imapc->pp.recvbuf); + + (void)instate; + + /* Do we have an untagged response? */ + if(imapcode == '*') { + line += 2; + + /* Loop through the data line */ + for(;;) { + size_t wordlen; + while(*line && (ISBLANK(*line) || ISNEWLINE(*line))) + line++; + + if(!*line) + break; + + /* Extract the word */ + for(wordlen = 0; line[wordlen] && !ISBLANK(line[wordlen]) && + !ISNEWLINE(line[wordlen]);) + wordlen++; + + /* Does the server support the STARTTLS capability? */ + if(wordlen == 8 && curl_strnequal(line, "STARTTLS", 8)) + imapc->tls_supported = TRUE; + + /* Has the server explicitly disabled clear text authentication? */ + else if(wordlen == 13 && curl_strnequal(line, "LOGINDISABLED", 13)) + imapc->login_disabled = TRUE; + + /* Does the server support the SASL-IR capability? */ + else if(wordlen == 7 && curl_strnequal(line, "SASL-IR", 7)) + imapc->ir_supported = TRUE; + + /* Do we have a SASL based authentication mechanism? */ + else if(wordlen > 5 && curl_strnequal(line, "AUTH=", 5)) { + size_t llen; + unsigned short mechbit; + + line += 5; + wordlen -= 5; + + /* Test the word for a matching authentication mechanism */ + mechbit = Curl_sasl_decode_mech(line, wordlen, &llen); + if(mechbit && llen == wordlen) + imapc->sasl.authmechs |= mechbit; + } + + line += wordlen; + } + } + else if(data->set.use_ssl && !Curl_conn_is_ssl(data->conn, FIRSTSOCKET)) { + /* PREAUTH is not compatible with STARTTLS. */ + if(imapcode == IMAP_RESP_OK && imapc->tls_supported && !imapc->preauth) { + /* Switch to TLS connection now */ + result = imap_perform_starttls(data, imapc); + } + else if(data->set.use_ssl <= CURLUSESSL_TRY) + result = imap_perform_authentication(data, imapc); + else { + failf(data, "STARTTLS not available."); + result = CURLE_USE_SSL_FAILED; + } + } + else + result = imap_perform_authentication(data, imapc); + + return result; +} + +/* For STARTTLS responses */ +static CURLcode imap_state_starttls_resp(struct Curl_easy *data, + struct imap_conn *imapc, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + + (void)instate; + + /* Pipelining in response is forbidden. */ + if(imapc->pp.overflow) + return CURLE_WEIRD_SERVER_REPLY; + + if(imapcode != IMAP_RESP_OK) { + if(data->set.use_ssl != CURLUSESSL_TRY) { + failf(data, "STARTTLS denied"); + result = CURLE_USE_SSL_FAILED; + } + else + result = imap_perform_authentication(data, imapc); + } + else + imap_state(data, imapc, IMAP_UPGRADETLS); + + return result; +} + +/* For SASL authentication responses */ +static CURLcode imap_state_auth_resp(struct Curl_easy *data, + struct imap_conn *imapc, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + saslprogress progress; + + (void)instate; + + result = Curl_sasl_continue(&imapc->sasl, data, imapcode, &progress); + if(!result) + switch(progress) { + case SASL_DONE: + imap_state(data, imapc, IMAP_STOP); /* Authenticated */ + break; + case SASL_IDLE: /* No mechanism left after cancellation */ + if(!imapc->login_disabled && (imapc->preftype & IMAP_TYPE_CLEARTEXT)) + /* Perform clear text authentication */ + result = imap_perform_login(data, imapc, data->conn); + else { + failf(data, "Authentication cancelled"); + result = CURLE_LOGIN_DENIED; + } + break; + default: + break; + } + + return result; +} + +/* For LOGIN responses */ +static CURLcode imap_state_login_resp(struct Curl_easy *data, + struct imap_conn *imapc, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; + + if(imapcode != IMAP_RESP_OK) { + failf(data, "Access denied. %c", imapcode); + result = CURLE_LOGIN_DENIED; + } + else + /* End of connect phase */ + imap_state(data, imapc, IMAP_STOP); + + return result; +} + +/* Detect IMAP listings vs. downloading a single email */ +static bool is_custom_fetch_listing_match(const char *params) +{ + /* match " 1:* (FLAGS ..." or " 1,2,3 (FLAGS ..." */ + if(*params++ != ' ') + return FALSE; + + while(ISDIGIT(*params)) { + params++; + if(*params == 0) + return FALSE; + } + if(*params == ':') + return TRUE; + if(*params == ',') + return TRUE; + return FALSE; +} + +static bool is_custom_fetch_listing(struct IMAP *imap) +{ + /* filter out "UID FETCH 1:* (FLAGS ..." queries to list emails */ + if(!imap->custom) + return FALSE; + else if(curl_strequal(imap->custom, "FETCH") && imap->custom_params) { + const char *p = imap->custom_params; + return is_custom_fetch_listing_match(p); + } + else if(curl_strequal(imap->custom, "UID") && imap->custom_params) { + if(curl_strnequal(imap->custom_params, " FETCH ", 7)) { + const char *p = imap->custom_params + 6; + return is_custom_fetch_listing_match(p); + } + } + return FALSE; +} + +/* For LIST and SEARCH responses */ +static CURLcode imap_state_listsearch_resp(struct Curl_easy *data, + struct imap_conn *imapc, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + const char *line = curlx_dyn_ptr(&imapc->pp.recvbuf); + size_t len = imapc->pp.nfinal; + struct IMAP *imap = Curl_meta_get(data, CURL_META_IMAP_EASY); + + DEBUGASSERT(imap); + if(!imap) + return CURLE_FAILED_INIT; + (void)instate; + + if(imapcode == '*' && is_custom_fetch_listing(imap)) { + /* custom FETCH or UID FETCH for listing is not handled here */ + } + else if(imapcode == '*') { + /* Check if this response contains a literal (e.g. FETCH responses with + body data). Literal syntax is {size}\r\n */ + const char *cr = memchr(line, '\r', len); + size_t line_len = cr ? (size_t)(cr - line) : len; + const char *ptr = imap_find_literal(line, line_len); + if(ptr) { + curl_off_t size = 0; + bool parsed = FALSE; + ptr++; + if(!curlx_str_number(&ptr, &size, CURL_OFF_T_MAX) && + !curlx_str_single(&ptr, '}')) + parsed = TRUE; + + if(parsed) { + struct pingpong *pp = &imapc->pp; + size_t buffer_len = curlx_dyn_len(&pp->recvbuf); + size_t after_header = buffer_len - pp->nfinal; + + /* This is a literal response, setup to receive the body data */ + infof(data, "Found %" FMT_OFF_T " bytes to download", size); + + /* First write the header line */ + result = Curl_client_write(data, CLIENTWRITE_BODY, line, len); + if(result) + return result; + + /* Handle data already in buffer after the header line */ + if(after_header > 0) { + /* There is already data in the buffer that is part of the literal + body or subsequent responses */ + size_t chunk = after_header; + + /* Keep only the data after the header line */ + curlx_dyn_tail(&pp->recvbuf, chunk); + pp->nfinal = 0; /* done */ + + /* Limit chunk to the literal size */ + if(chunk > (size_t)size) + chunk = (size_t)size; + + if(chunk) { + /* Write the literal body data */ + result = Curl_client_write(data, CLIENTWRITE_BODY, + curlx_dyn_ptr(&pp->recvbuf), chunk); + if(result) + return result; + } + + /* Handle remaining data in buffer (either more literal data or + subsequent responses) */ + if(after_header > chunk) { + /* Keep the data after the literal body */ + pp->overflow = after_header - chunk; + curlx_dyn_tail(&pp->recvbuf, pp->overflow); + } + else { + pp->overflow = 0; + curlx_dyn_reset(&pp->recvbuf); + } + } + else { + /* No data in buffer yet, reset overflow */ + pp->overflow = 0; + } + + if((CURL_OFF_T_MAX - size) < (curl_off_t)len) + /* unlikely to actually be a transfer this big, but avoid integer + overflow */ + size = CURL_OFF_T_MAX; + else + size += len; + + /* Progress size includes both header line and literal body */ + Curl_pgrsSetDownloadSize(data, size); + + if(data->req.bytecount == size) + /* All data already transferred (header + literal body) */ + Curl_xfer_setup_nop(data); + else { + /* Setup to receive the literal body data. + maxdownload and transfer size include both header line and + literal body */ + data->req.maxdownload = size; + Curl_xfer_setup_recv(data, FIRSTSOCKET, size); + } + /* End of DO phase */ + imap_state(data, imapc, IMAP_STOP); + } + else { + /* Failed to parse literal, write the line */ + result = Curl_client_write(data, CLIENTWRITE_BODY, line, len); + } + } + else { + /* No literal, write the line as-is */ + result = Curl_client_write(data, CLIENTWRITE_BODY, line, len); + } + } + else if(imapcode != IMAP_RESP_OK) + result = CURLE_QUOTE_ERROR; + else + /* End of DO phase */ + imap_state(data, imapc, IMAP_STOP); + + return result; +} + +/* For SELECT responses */ +static CURLcode imap_state_select_resp(struct Curl_easy *data, + struct imap_conn *imapc, + struct IMAP *imap, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; + + if(imapcode == '*') { + /* See if this is an UIDVALIDITY response */ + const char *line = curlx_dyn_ptr(&imapc->pp.recvbuf); + size_t len = curlx_dyn_len(&imapc->pp.recvbuf); + if((len >= 18) && checkprefix("OK [UIDVALIDITY ", &line[2])) { + curl_off_t value; + const char *p = &line[2] + CURL_CSTRLEN("OK [UIDVALIDITY "); + if(!curlx_str_number(&p, &value, UINT_MAX)) { + imapc->mb_uidvalidity = (unsigned int)value; + imapc->mb_uidvalidity_set = TRUE; + } + } + } + else if(imapcode == IMAP_RESP_OK) { + /* Check if the UIDVALIDITY has been specified and matches */ + if(imap->uidvalidity_set && imapc->mb_uidvalidity_set && + (imap->uidvalidity != imapc->mb_uidvalidity)) { + failf(data, "Mailbox UIDVALIDITY has changed"); + result = CURLE_REMOTE_FILE_NOT_FOUND; + } + else { + /* Note the currently opened mailbox on this connection */ + DEBUGASSERT(!imapc->mailbox); + imapc->mailbox = curlx_strdup(imap->mailbox); + if(!imapc->mailbox) + return CURLE_OUT_OF_MEMORY; + + if(imap->custom) + result = imap_perform_list(data, imapc, imap); + else if(imap->query) + result = imap_perform_search(data, imapc, imap); + else + result = imap_perform_fetch(data, imapc, imap); + } + } + else { + failf(data, "Select failed"); + result = CURLE_LOGIN_DENIED; + } + + return result; +} + +/* For the (first line of the) FETCH responses */ +static CURLcode imap_state_fetch_resp(struct Curl_easy *data, + struct imap_conn *imapc, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + struct pingpong *pp = &imapc->pp; + const char *ptr = curlx_dyn_ptr(&imapc->pp.recvbuf); + size_t len = imapc->pp.nfinal; + bool parsed = FALSE; + curl_off_t size = 0; + + (void)instate; + + if(imapcode != '*') { + Curl_pgrsSetDownloadSize(data, -1); + imap_state(data, imapc, IMAP_STOP); + return CURLE_REMOTE_FILE_NOT_FOUND; + } + + /* Something like this is received "* 1 FETCH (BODY[TEXT] {2021}\r" so parse + the continuation data contained within the curly brackets */ + ptr = imap_find_literal(ptr, len); + if(ptr) { + ptr++; + if(!curlx_str_number(&ptr, &size, CURL_OFF_T_MAX) && + !curlx_str_single(&ptr, '}')) + parsed = TRUE; + } + + if(parsed) { + infof(data, "Found %" FMT_OFF_T " bytes to download", size); + Curl_pgrsSetDownloadSize(data, size); + + if(pp->overflow) { + /* At this point there is a data in the receive buffer that is body + content, send it as body and then skip it. Do note that there may + even be additional "headers" after the body. */ + size_t chunk = pp->overflow; + + /* keep only the overflow */ + curlx_dyn_tail(&pp->recvbuf, chunk); + pp->nfinal = 0; /* done */ + + if(chunk > (size_t)size) + /* The conversion from curl_off_t to size_t is always fine here */ + chunk = (size_t)size; + + if(!chunk) { + /* no size, we are done with the data */ + imap_state(data, imapc, IMAP_STOP); + return CURLE_OK; + } + result = Curl_client_write(data, CLIENTWRITE_BODY, + curlx_dyn_ptr(&pp->recvbuf), chunk); + if(result) + return result; + + infof(data, "Written %zu bytes, %" FMT_OFF_T + " bytes are left for transfer", chunk, (curl_off_t)(size - chunk)); + + /* Have we used the entire overflow or part of it?*/ + if(pp->overflow > chunk) { + /* remember the remaining trailing overflow data */ + pp->overflow -= chunk; + curlx_dyn_tail(&pp->recvbuf, pp->overflow); + } + else { + pp->overflow = 0; /* handled */ + /* Free the cache */ + curlx_dyn_reset(&pp->recvbuf); + } + } + + if(data->req.bytecount == size) + /* The entire data is already transferred! */ + Curl_xfer_setup_nop(data); + else { + /* IMAP download */ + data->req.maxdownload = size; + Curl_xfer_setup_recv(data, FIRSTSOCKET, size); + } + } + else { + /* We do not know how to parse this line */ + failf(data, "Failed to parse FETCH response."); + result = CURLE_WEIRD_SERVER_REPLY; + } + + /* End of DO phase */ + imap_state(data, imapc, IMAP_STOP); + + return result; +} + +/* For final FETCH responses performed after the download */ +static CURLcode imap_state_fetch_final_resp(struct Curl_easy *data, + struct imap_conn *imapc, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + + (void)instate; + + if(imapcode != IMAP_RESP_OK) + result = CURLE_WEIRD_SERVER_REPLY; + else + /* End of DONE phase */ + imap_state(data, imapc, IMAP_STOP); + + return result; +} + +/* For APPEND responses */ +static CURLcode imap_state_append_resp(struct Curl_easy *data, + struct imap_conn *imapc, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; + + if(imapcode != '+') { + result = CURLE_UPLOAD_FAILED; + } + else { + /* Set the progress upload size */ + Curl_pgrsSetUploadSize(data, data->state.infilesize); + + /* IMAP upload */ + Curl_xfer_setup_send(data, FIRSTSOCKET); + + /* End of DO phase */ + imap_state(data, imapc, IMAP_STOP); + } + + return result; +} + +/* For final APPEND responses performed after the upload */ +static CURLcode imap_state_append_final_resp(struct Curl_easy *data, + struct imap_conn *imapc, + int imapcode, + imapstate instate) +{ + CURLcode result = CURLE_OK; + + (void)instate; + + if(imapcode != IMAP_RESP_OK) + result = CURLE_UPLOAD_FAILED; + else + /* End of DONE phase */ + imap_state(data, imapc, IMAP_STOP); + + return result; +} + +static CURLcode imap_pp_statemachine(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + int imapcode; + struct imap_conn *imapc = Curl_conn_meta_get(conn, CURL_META_IMAP_CONN); + struct IMAP *imap = Curl_meta_get(data, CURL_META_IMAP_EASY); + struct pingpong *pp; + size_t nread = 0; + + if(!imapc || !imap) + return CURLE_FAILED_INIT; + pp = &imapc->pp; + /* Busy upgrading the connection; right now all I/O is SSL/TLS, not IMAP */ +upgrade_tls: + if(imapc->state == IMAP_UPGRADETLS) { + result = imap_perform_upgrade_tls(data, imapc, conn); + if(result || (imapc->state == IMAP_UPGRADETLS)) + return result; + } + + /* Flush any data that needs to be sent */ + if(pp->sendleft) + return Curl_pp_flushsend(data, pp); + + do { + /* Read the response from the server */ + result = Curl_pp_readresp(data, FIRSTSOCKET, pp, &imapcode, &nread); + if(result) + return result; + + /* Was there an error parsing the response line? */ + if(imapcode == -1) + return CURLE_WEIRD_SERVER_REPLY; + + if(!imapcode) + break; + + /* We have now received a full IMAP server response */ + switch(imapc->state) { + case IMAP_SERVERGREET: + result = imap_state_servergreet_resp(data, imapc, + imapcode, imapc->state); + break; + + case IMAP_CAPABILITY: + result = imap_state_capability_resp(data, imapc, imapcode, imapc->state); + break; + + case IMAP_STARTTLS: + result = imap_state_starttls_resp(data, imapc, imapcode, imapc->state); + /* During UPGRADETLS, leave the read loop as we need to connect + * (e.g. TLS handshake) before we continue sending/receiving. */ + if(!result && (imapc->state == IMAP_UPGRADETLS)) + goto upgrade_tls; + break; + + case IMAP_AUTHENTICATE: + result = imap_state_auth_resp(data, imapc, imapcode, imapc->state); + break; + + case IMAP_LOGIN: + result = imap_state_login_resp(data, imapc, imapcode, imapc->state); + break; + + case IMAP_LIST: + case IMAP_SEARCH: + result = imap_state_listsearch_resp(data, imapc, imapcode, imapc->state); + break; + + case IMAP_SELECT: + result = imap_state_select_resp(data, imapc, imap, + imapcode, imapc->state); + break; + + case IMAP_FETCH: + result = imap_state_fetch_resp(data, imapc, imapcode, imapc->state); + break; + + case IMAP_FETCH_FINAL: + result = imap_state_fetch_final_resp(data, imapc, + imapcode, imapc->state); + break; + + case IMAP_APPEND: + result = imap_state_append_resp(data, imapc, imapcode, imapc->state); + break; + + case IMAP_APPEND_FINAL: + result = imap_state_append_final_resp(data, imapc, + imapcode, imapc->state); + break; + + case IMAP_LOGOUT: + default: + /* internal error */ + imap_state(data, imapc, IMAP_STOP); + break; + } + } while(!result && imapc->state != IMAP_STOP && Curl_pp_moredata(pp)); + + return result; +} + +/* Called repeatedly until done from multi.c */ +static CURLcode imap_multi_statemach(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct imap_conn *imapc = + Curl_conn_meta_get(data->conn, CURL_META_IMAP_CONN); + + *done = FALSE; + if(!imapc) + return CURLE_FAILED_INIT; + result = Curl_pp_statemach(data, &imapc->pp, FALSE, FALSE); + *done = (imapc->state == IMAP_STOP); + + return result; +} + +static CURLcode imap_block_statemach(struct Curl_easy *data, + struct imap_conn *imapc, + bool disconnecting) +{ + CURLcode result = CURLE_OK; + + while(imapc->state != IMAP_STOP && !result) + result = Curl_pp_statemach(data, &imapc->pp, TRUE, disconnecting); + + return result; +} + +/* For the IMAP "protocol connect" and "doing" phases only */ +static CURLcode imap_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct imap_conn *imapc = + Curl_conn_meta_get(data->conn, CURL_META_IMAP_CONN); + return imapc ? Curl_pp_pollset(data, &imapc->pp, ps) : CURLE_OK; +} + +static void imap_easy_reset(struct IMAP *imap) +{ + curlx_safefree(imap->mailbox); + curlx_safefree(imap->uid); + curlx_safefree(imap->mindex); + curlx_safefree(imap->section); + curlx_safefree(imap->partial); + curlx_safefree(imap->query); + curlx_safefree(imap->custom); + curlx_safefree(imap->custom_params); + imap->uidvalidity_set = FALSE; + /* Clear the transfer mode for the next request */ + imap->transfer = PPTRANSFER_BODY; +} + +/*********************************************************************** + * + * imap_is_bchar() + * + * Portable test of whether the specified char is a "bchar" as defined in the + * grammar of RFC-5092. + */ +static bool imap_is_bchar(char ch) +{ + /* Performing the alnum check first with macro is faster because of ASCII + arithmetic */ + return ch && (ISALNUM(ch) || strchr(":@/&=-._~!$\'()*+,%", ch)); +} + +/*********************************************************************** + * + * imap_parse_url_options() + * + * Parse the URL login options. + */ +static CURLcode imap_parse_url_options(struct connectdata *conn, + struct imap_conn *imapc) +{ + CURLcode result = CURLE_OK; + const char *ptr = conn->options; + bool prefer_login = FALSE; + + while(!result && ptr && *ptr) { + const char *key = ptr; + const char *value; + + while(*ptr && *ptr != '=') + ptr++; + + value = ptr + 1; + + while(*ptr && *ptr != ';') + ptr++; + + if(curl_strnequal(key, "AUTH=+LOGIN", 11)) { + /* User prefers plaintext LOGIN over any SASL, including SASL LOGIN */ + prefer_login = TRUE; + imapc->sasl.prefmech = SASL_AUTH_NONE; + } + else if(curl_strnequal(key, "AUTH=", 5)) { + prefer_login = FALSE; + result = Curl_sasl_parse_url_auth_option(&imapc->sasl, + value, ptr - value); + } + else { + prefer_login = FALSE; + result = CURLE_URL_MALFORMAT; + } + + if(*ptr == ';') + ptr++; + } + + if(prefer_login) + imapc->preftype = IMAP_TYPE_CLEARTEXT; + else { + switch(imapc->sasl.prefmech) { + case SASL_AUTH_NONE: + imapc->preftype = IMAP_TYPE_NONE; + break; + case SASL_AUTH_DEFAULT: + imapc->preftype = IMAP_TYPE_ANY; + break; + default: + imapc->preftype = IMAP_TYPE_SASL; + break; + } + } + + return result; +} + +/*********************************************************************** + * + * imap_parse_url_path() + * + * Parse the URL path into separate path components. + * + */ +static CURLcode imap_parse_url_path(struct Curl_easy *data, + struct IMAP *imap) +{ + /* The imap struct is already initialized in imap_connect() */ + CURLcode result = CURLE_OK; + const char *begin = &data->state.up.path[1]; /* skip leading slash */ + const char *ptr = begin; + + /* See how much of the URL is a valid path and decode it */ + while(imap_is_bchar(*ptr)) + ptr++; + + if(ptr != begin) { + /* Remove the trailing slash if present */ + const char *end = ptr; + if(end > begin && end[-1] == '/') + end--; + + result = Curl_urldecode(begin, end - begin, &imap->mailbox, NULL, + REJECT_CTRL); + if(result) + return result; + } + else + imap->mailbox = NULL; + + /* There can be any number of parameters in the form ";NAME=VALUE" */ + while(*ptr == ';') { + char *name; + char *value; + size_t valuelen; + + /* Find the length of the name parameter */ + begin = ++ptr; + while(*ptr && *ptr != '=') + ptr++; + + if(!*ptr) + return CURLE_URL_MALFORMAT; + + /* Decode the name parameter */ + result = Curl_urldecode(begin, ptr - begin, &name, NULL, + REJECT_CTRL); + if(result) + return result; + + /* Find the length of the value parameter */ + begin = ++ptr; + while(imap_is_bchar(*ptr)) + ptr++; + + /* Decode the value parameter */ + result = Curl_urldecode(begin, ptr - begin, &value, &valuelen, + REJECT_CTRL); + if(result) { + curlx_free(name); + return result; + } + + DEBUGF(infof(data, "IMAP URL parameter '%s' = '%s'", name, value)); + + /* Process the known hierarchical parameters (UIDVALIDITY, UID, SECTION + and PARTIAL) stripping of the trailing slash character if it is + present. + + Note: Unknown parameters trigger a URL_MALFORMAT error. */ + if(valuelen > 0 && value[valuelen - 1] == '/') + value[valuelen - 1] = '\0'; + if(valuelen) { + if(curl_strequal(name, "UIDVALIDITY") && !imap->uidvalidity_set) { + curl_off_t num; + const char *p = (const char *)value; + if(!curlx_str_number(&p, &num, UINT_MAX)) { + imap->uidvalidity = (unsigned int)num; + imap->uidvalidity_set = TRUE; + } + curlx_free(value); + } + else if(curl_strequal(name, "UID") && !imap->uid) { + imap->uid = value; + } + else if(curl_strequal(name, "MAILINDEX") && !imap->mindex) { + imap->mindex = value; + } + else if(curl_strequal(name, "SECTION") && !imap->section) { + imap->section = value; + } + else if(curl_strequal(name, "PARTIAL") && !imap->partial) { + imap->partial = value; + } + else { + curlx_free(name); + curlx_free(value); + return CURLE_URL_MALFORMAT; + } + } + else + /* blank? */ + curlx_free(value); + curlx_free(name); + } + + /* Does the URL contain a query parameter? Only valid when we have a mailbox + and no UID as per RFC-5092 */ + if(imap->mailbox && !imap->uid && !imap->mindex) { + /* Get the query parameter, URL decoded */ + CURLUcode uc = curl_url_get(data->state.uh, CURLUPART_QUERY, &imap->query, + CURLU_URLDECODE); + if(uc == CURLUE_OUT_OF_MEMORY) + return CURLE_OUT_OF_MEMORY; + } + + /* Any extra stuff at the end of the URL is an error */ + if(*ptr) + return CURLE_URL_MALFORMAT; + + return CURLE_OK; +} + +/*********************************************************************** + * + * imap_parse_custom_request() + * + * Parse the custom request. + */ +static CURLcode imap_parse_custom_request(struct Curl_easy *data, + struct IMAP *imap) +{ + CURLcode result = CURLE_OK; + const char *custom = CURL_EASY_STR(data, STRING_CUSTOMREQUEST); + + if(custom) { + /* URL decode the custom request */ + result = Curl_urldecode(custom, 0, &imap->custom, NULL, REJECT_CTRL); + + /* Extract the parameters if specified */ + if(!result) { + const char *params = imap->custom; + + while(*params && *params != ' ') + params++; + + if(*params) { + imap->custom_params = curlx_strdup(params); + imap->custom[params - imap->custom] = '\0'; + + if(!imap->custom_params) + result = CURLE_OUT_OF_MEMORY; + } + } + } + + return result; +} + +/*********************************************************************** + * + * imap_connect() + * + * This function should do everything that is to be considered a part of the + * connection phase. + * + * The variable 'done' points to will be TRUE if the protocol-layer connect + * phase is done when this function returns, or FALSE if not. + */ +static CURLcode imap_connect(struct Curl_easy *data, bool *done) +{ + struct imap_conn *imapc = + Curl_conn_meta_get(data->conn, CURL_META_IMAP_CONN); + CURLcode result = CURLE_OK; + + *done = FALSE; /* default to not done yet */ + if(!imapc) + return CURLE_FAILED_INIT; + + /* Parse the URL options */ + result = imap_parse_url_options(data->conn, imapc); + if(result) + return result; + + /* Start off waiting for the server greeting response */ + imap_state(data, imapc, IMAP_SERVERGREET); + + /* Start off with an response id of '*' */ + curlx_strcopy(imapc->resptag, sizeof(imapc->resptag), STRCONST("*")); + + result = imap_multi_statemach(data, done); + + return result; +} + +/*********************************************************************** + * + * imap_done() + * + * The DONE function. This does what needs to be done after a single DO has + * performed. + * + * Input argument is already checked for validity. + */ +static CURLcode imap_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct imap_conn *imapc = Curl_conn_meta_get(conn, CURL_META_IMAP_CONN); + struct IMAP *imap = Curl_meta_get(data, CURL_META_IMAP_EASY); + + (void)premature; + + if(!imapc) + return CURLE_FAILED_INIT; + if(!imap) + return CURLE_OK; + + if(status) { + CURL_TRC_M(data, "IMAP done with bad status"); + connclose(conn); /* marked for closure */ + result = status; /* use the already set error code */ + } + else if(!data->set.connect_only && + ((!imap->custom && (imap->uid || imap->mindex)) || + (imap->custom && data->req.maxdownload > 0) || + data->state.upload || IS_MIME_POST(data))) { + /* Handle responses after FETCH or APPEND transfer has finished. + For custom commands, check if we set up a download which indicates + a FETCH-like command with literal data. */ + + if(!data->state.upload && !IS_MIME_POST(data)) + imap_state(data, imapc, IMAP_FETCH_FINAL); + else { + /* End the APPEND command first by sending an empty line */ + result = Curl_pp_sendf(data, &imapc->pp, "%s", ""); + if(!result) + imap_state(data, imapc, IMAP_APPEND_FINAL); + } + + /* Run the state-machine */ + if(!result) + result = imap_block_statemach(data, imapc, FALSE); + } + + imap_easy_reset(imap); + return result; +} + +/*********************************************************************** + * + * imap_perform() + * + * This is the actual DO function for IMAP. Fetch or append a message, or do + * other things according to the options previously setup. + */ +static CURLcode imap_perform(struct Curl_easy *data, bool *connected, + bool *dophase_done) +{ + /* This is IMAP and no proxy */ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct imap_conn *imapc = Curl_conn_meta_get(conn, CURL_META_IMAP_CONN); + struct IMAP *imap = Curl_meta_get(data, CURL_META_IMAP_EASY); + bool selected = FALSE; + + DEBUGF(infof(data, "DO phase starts")); + if(!imapc || !imap) + return CURLE_FAILED_INIT; + + if(data->req.no_body) { + /* Requested no body means no transfer */ + imap->transfer = PPTRANSFER_INFO; + } + + *dophase_done = FALSE; /* not done yet */ + + /* Determine if the requested mailbox (with the same UIDVALIDITY if set) + has already been selected on this connection */ + if(imap->mailbox && imapc->mailbox && + curl_strequal(imap->mailbox, imapc->mailbox) && + (!imap->uidvalidity_set || !imapc->mb_uidvalidity_set || + (imap->uidvalidity == imapc->mb_uidvalidity))) + selected = TRUE; + + /* Start the first command in the DO phase */ + if(data->state.upload || IS_MIME_POST(data)) + /* APPEND can be executed directly */ + result = imap_perform_append(data, imapc, imap); + else if(imap->custom && (selected || !imap->mailbox)) + /* Custom command using the same mailbox or no mailbox */ + result = imap_perform_list(data, imapc, imap); + else if(!imap->custom && selected && (imap->uid || imap->mindex)) + /* FETCH from the same mailbox */ + result = imap_perform_fetch(data, imapc, imap); + else if(!imap->custom && selected && imap->query) + /* SEARCH the current mailbox */ + result = imap_perform_search(data, imapc, imap); + else if(imap->mailbox && !selected && + (imap->custom || imap->uid || imap->mindex || imap->query)) + /* SELECT the mailbox */ + result = imap_perform_select(data, imapc, imap); + else + /* LIST */ + result = imap_perform_list(data, imapc, imap); + + if(result) + return result; + + /* Run the state-machine */ + result = imap_multi_statemach(data, dophase_done); + + *connected = Curl_conn_is_connected(conn, FIRSTSOCKET); + + if(*dophase_done) + DEBUGF(infof(data, "DO phase is complete")); + + return result; +} + +/* Call this when the DO phase has completed */ +static CURLcode imap_dophase_done(struct Curl_easy *data, + struct IMAP *imap, + bool connected) +{ + (void)connected; + + if(imap->transfer != PPTRANSFER_BODY) + /* no data to transfer */ + Curl_xfer_setup_nop(data); + + return CURLE_OK; +} + +/*********************************************************************** + * + * imap_regular_transfer() + * + * The input argument is already checked for validity. + * + * Performs all commands done before a regular transfer between a local and a + * remote host. + */ +static CURLcode imap_regular_transfer(struct Curl_easy *data, + struct IMAP *imap, + bool *dophase_done) +{ + CURLcode result = CURLE_OK; + bool connected = FALSE; + + /* Make sure size is unknown at this point */ + data->req.size = -1; + + /* Set the progress data */ + Curl_pgrsReset(data); + + /* Carry out the perform */ + result = imap_perform(data, &connected, dophase_done); + + /* Perform post DO phase operations if necessary */ + if(!result && *dophase_done) + result = imap_dophase_done(data, imap, connected); + + return result; +} + +/*********************************************************************** + * + * imap_do() + * + * This function is registered as 'curl_do' function. It decodes the path + * parts etc as a wrapper to the actual DO function (imap_perform). + * + * The input argument is already checked for validity. + */ +static CURLcode imap_do(struct Curl_easy *data, bool *done) +{ + struct IMAP *imap = Curl_meta_get(data, CURL_META_IMAP_EASY); + CURLcode result = CURLE_OK; + *done = FALSE; /* default to false */ + + if(!imap) + return CURLE_FAILED_INIT; + /* Parse the URL path */ + result = imap_parse_url_path(data, imap); + if(result) + return result; + + /* Parse the custom request */ + result = imap_parse_custom_request(data, imap); + if(result) + return result; + + result = imap_regular_transfer(data, imap, done); + + return result; +} + +/*********************************************************************** + * + * imap_disconnect() + * + * Disconnect from an IMAP server. Cleanup protocol-specific per-connection + * resources. BLOCKING. + */ +static CURLcode imap_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead_connection) +{ + struct imap_conn *imapc = Curl_conn_meta_get(conn, CURL_META_IMAP_CONN); + + if(imapc) { + /* We cannot send quit unconditionally. If this connection is stale or + bad in any way (pingpong has pending data to send), + sending quit and waiting around here will make the + disconnect wait in vain and cause more problems than we need to. */ + if(!dead_connection && conn->bits.protoconnstart && + !Curl_pp_needs_flush(data, &imapc->pp)) { + if(!imap_perform_logout(data, imapc)) + (void)imap_block_statemach(data, imapc, TRUE); /* ignore errors */ + } + } + return CURLE_OK; +} + +/* Called from multi.c while DOing */ +static CURLcode imap_doing(struct Curl_easy *data, bool *dophase_done) +{ + struct IMAP *imap = Curl_meta_get(data, CURL_META_IMAP_EASY); + CURLcode result; + + if(!imap) + return CURLE_FAILED_INIT; + + result = imap_multi_statemach(data, dophase_done); + if(result) + DEBUGF(infof(data, "DO phase failed")); + else if(*dophase_done) { + result = imap_dophase_done(data, imap, FALSE /* not connected */); + + DEBUGF(infof(data, "DO phase is complete")); + } + + return result; +} + +static void imap_easy_dtor(void *key, size_t klen, void *entry) +{ + struct IMAP *imap = entry; + (void)key; + (void)klen; + imap_easy_reset(imap); + curlx_free(imap); +} + +static void imap_conn_dtor(void *key, size_t klen, void *entry) +{ + struct imap_conn *imapc = entry; + (void)key; + (void)klen; + Curl_pp_disconnect(&imapc->pp); + curlx_dyn_free(&imapc->dyn); + curlx_safefree(imapc->mailbox); + curlx_free(imapc); +} + +/* SASL parameters for the imap protocol */ +static const struct SASLproto saslimap = { + "imap", /* The service name */ + imap_perform_authenticate, /* Send authentication command */ + imap_continue_authenticate, /* Send authentication continuation */ + imap_cancel_authenticate, /* Send authentication cancellation */ + imap_get_message, /* Get SASL response message */ + 0, /* No maximum initial response length */ + '+', /* Code received when continuation is expected */ + IMAP_RESP_OK, /* Code to receive upon authentication success */ + SASL_AUTH_DEFAULT, /* Default mechanisms */ + SASL_FLAG_BASE64 /* Configuration flags */ +}; + +static CURLcode imap_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + struct imap_conn *imapc; + struct pingpong *pp; + struct IMAP *imap; + + imapc = curlx_calloc(1, sizeof(*imapc)); + if(!imapc) + return CURLE_OUT_OF_MEMORY; + + pp = &imapc->pp; + PINGPONG_SETUP(pp, imap_pp_statemachine, imap_endofresp); + + /* Set the default preferred authentication type and mechanism */ + imapc->preftype = IMAP_TYPE_ANY; + Curl_sasl_init(&imapc->sasl, data, &saslimap); + + curlx_dyn_init(&imapc->dyn, DYN_IMAP_CMD); + Curl_pp_init(pp, Curl_pgrs_now(data)); + + if(Curl_conn_meta_set(conn, CURL_META_IMAP_CONN, imapc, imap_conn_dtor)) + return CURLE_OUT_OF_MEMORY; + + imap = curlx_calloc(1, sizeof(struct IMAP)); + if(!imap || + Curl_meta_set(data, CURL_META_IMAP_EASY, imap, imap_easy_dtor)) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +/* + * IMAP protocol. + */ +const struct Curl_protocol Curl_protocol_imap = { + imap_setup_connection, /* setup_connection */ + imap_do, /* do_it */ + imap_done, /* done */ + ZERO_NULL, /* do_more */ + imap_connect, /* connect_it */ + imap_multi_statemach, /* connecting */ + imap_doing, /* doing */ + imap_pollset, /* proto_pollset */ + imap_pollset, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + imap_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#endif /* CURL_DISABLE_IMAP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/imap.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/imap.h new file mode 100644 index 0000000000..ecfb1ec9b9 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/imap.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_IMAP_H +#define HEADER_CURL_IMAP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* Authentication type flags */ +#define IMAP_TYPE_CLEARTEXT (1 << 0) +#define IMAP_TYPE_SASL (1 << 1) + +/* Authentication type values */ +#define IMAP_TYPE_NONE 0 +#define IMAP_TYPE_ANY (IMAP_TYPE_CLEARTEXT | IMAP_TYPE_SASL) + +#ifndef CURL_DISABLE_IMAP +extern const struct Curl_protocol Curl_protocol_imap; +#endif + +#endif /* HEADER_CURL_IMAP_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/ldap.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ldap.c new file mode 100644 index 0000000000..2676f732bb --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ldap.c @@ -0,0 +1,987 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" +#include "curl_ldap.h" + +#if !defined(CURL_DISABLE_LDAP) && !defined(USE_OPENLDAP) + +#if defined(CURL_HAVE_DIAG) && defined(__APPLE__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + +/* + * Notice that USE_OPENLDAP is only a source code selection switch. When + * libcurl is built with USE_OPENLDAP defined the libcurl source code that + * gets compiled is the code from openldap.c, otherwise the code that gets + * compiled is the code from ldap.c. + * + * When USE_OPENLDAP is defined a recent version of the OpenLDAP library + * might be required for compilation and runtime. In order to use ancient + * OpenLDAP library versions, USE_OPENLDAP shall not be defined. + */ + +#ifdef USE_WIN32_LDAP /* Use Windows LDAP implementation. */ +# include <winldap.h> +/* Undefine indirect <wincrypt.h> symbols conflicting with AWS-LC/BoringSSL. */ +# undef X509_NAME +# undef X509_EXTENSIONS +# undef PKCS7_ISSUER_AND_SERIAL +# undef PKCS7_SIGNER_INFO +# undef OCSP_REQUEST +# undef OCSP_RESPONSE +# include <winber.h> +#else +# define LDAP_DEPRECATED 1 /* Be sure ldap_init() is defined. */ +# ifdef HAVE_LBER_H +# include <lber.h> +# endif +# include <ldap.h> +# if defined(HAVE_LDAP_SSL) && defined(HAVE_LDAP_SSL_H) +# include <ldap_ssl.h> +# endif /* HAVE_LDAP_SSL && HAVE_LDAP_SSL_H */ +#endif + +#include "cfilters.h" +#include "sendf.h" +#include "curl_trc.h" +#include "escape.h" +#include "progress.h" +#include "transfer.h" +#include "curlx/strparse.h" +#include "bufref.h" +#include "curlx/multibyte.h" +#include "curlx/base64.h" +#include "connect.h" + +#ifdef USE_WIN32_LDAP +#define FREE_ON_WINLDAP(x) curlx_free(x) +#define curl_ldap_num_t ULONG +#else +#define FREE_ON_WINLDAP(x) do {} while(0) +#define curl_ldap_num_t int +#endif + +#ifndef HAVE_LDAP_URL_PARSE + +/* Use our own implementation. */ + +struct ldap_urldesc { + char *lud_host; + int lud_port; +#ifdef USE_WIN32_LDAP + TCHAR *lud_dn; + TCHAR **lud_attrs; +#else + char *lud_dn; + char **lud_attrs; +#endif + int lud_scope; +#ifdef USE_WIN32_LDAP + TCHAR *lud_filter; +#else + char *lud_filter; +#endif + char **lud_exts; + size_t lud_attrs_dups; /* how many were dup'ed, this field is not in the + "real" struct so can only be used in code + without HAVE_LDAP_URL_PARSE defined */ +}; + +#undef LDAPURLDesc +#define LDAPURLDesc struct ldap_urldesc + +static curl_ldap_num_t ldap_url_parse_low(struct Curl_easy *data, + const struct connectdata *conn, + LDAPURLDesc **ludpp); +static void ldap_free_urldesc_low(LDAPURLDesc *ludp); + +#undef ldap_free_urldesc +#define ldap_free_urldesc ldap_free_urldesc_low + +#endif /* !HAVE_LDAP_URL_PARSE */ + +#ifdef DEBUG_LDAP +#define LDAP_TRACE(x) \ + do { \ + ldap_trace_low("%u: ", __LINE__); \ + ldap_trace_low x; \ + } while(0) + +static void ldap_trace_low(const char *fmt, ...) CURL_PRINTF(1, 2); +#else +#define LDAP_TRACE(x) Curl_nop_stmt +#endif + +#if defined(USE_WIN32_LDAP) && defined(ldap_err2string) +/* Use ANSI error strings in Unicode builds */ +#undef ldap_err2string +#define ldap_err2string ldap_err2stringA +#endif + +#if defined(USE_WIN32_LDAP) && defined(_MSC_VER) && (_MSC_VER <= 1700) +/* Workaround for warning: + 'type cast' : conversion from 'int' to 'void *' of greater size */ +#undef LDAP_OPT_ON +#undef LDAP_OPT_OFF +#define LDAP_OPT_ON ((void *)(size_t)1) +#define LDAP_OPT_OFF ((void *)(size_t)0) +#endif + +#ifdef USE_WIN32_LDAP + +#ifdef USE_WINDOWS_SSPI +static ULONG ldap_win_bind_auth(LDAP *server, const char *user, + const char *passwd, unsigned long authflags) +{ + ULONG method = 0; + SEC_WINNT_AUTH_IDENTITY_EX cred; + ULONG rc = LDAP_AUTH_METHOD_NOT_SUPPORTED; + + memset(&cred, 0, sizeof(cred)); + +#ifdef USE_SPNEGO + if(authflags & CURLAUTH_NEGOTIATE) { + method = LDAP_AUTH_NEGOTIATE; + } + else +#endif +#ifdef USE_NTLM + if(authflags & CURLAUTH_NTLM) { + method = LDAP_AUTH_NTLM; + } + else +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + if(authflags & CURLAUTH_DIGEST) { + method = LDAP_AUTH_DIGEST; + } + else +#endif + { + /* required anyway if one of upper preprocessor definitions enabled */ + } + + if(method && user && passwd) { + CURLcode result = Curl_create_sspi_identity(user, passwd, &cred); + if(!result) { + rc = ldap_bind_s(server, NULL, (TCHAR *)&cred, method); + Curl_sspi_free_identity(&cred); + } + else { + rc = LDAP_NO_MEMORY; + } + } + else { + /* proceed with current user credentials */ + method = LDAP_AUTH_NEGOTIATE; + rc = ldap_bind_s(server, NULL, NULL, method); + } + return rc; +} +#endif /* USE_WINDOWS_SSPI */ + +static ULONG ldap_win_bind(struct Curl_easy *data, LDAP *server, + const char *user, const char *passwd) +{ + ULONG rc = LDAP_INVALID_CREDENTIALS; + + PTCHAR inuser = NULL; + PTCHAR inpass = NULL; + + if(user && passwd && (data->set.httpauth & CURLAUTH_BASIC)) { + inuser = curlx_convert_UTF8_to_tchar(user); + inpass = curlx_convert_UTF8_to_tchar(passwd); + + rc = ldap_simple_bind_s(server, inuser, inpass); + + curlx_free(inuser); + curlx_free(inpass); + } +#ifdef USE_WINDOWS_SSPI + else { + rc = ldap_win_bind_auth(server, user, passwd, data->set.httpauth); + } +#endif + + return rc; +} +#endif /* USE_WIN32_LDAP */ + +static bool ldap_value_needs_base64(const char *attr, size_t attr_len, + const BerValue *val) +{ + ber_len_t j; + + if((attr_len > 7) && curl_strequal(";binary", attr + attr_len - 7)) + return TRUE; + + /* check for a leading ':' or '<' (not a SAFE-INIT-CHAR per RFC 2849) or + leading or trailing whitespace */ + if(val->bv_len && ((val->bv_val[0] == ':') || (val->bv_val[0] == '<') || + ISBLANK(val->bv_val[0]) || + ISBLANK(val->bv_val[val->bv_len - 1]))) + return TRUE; + + /* check for unprintable characters */ + for(j = 0; j < val->bv_len; j++) + if(!ISPRINT(val->bv_val[j])) + return TRUE; + + return FALSE; +} + +#ifdef USE_WIN32_LDAP +static BOOLEAN bypass_cert_verify(PLDAP Connection, + PCCERT_CONTEXT *ppServerCert) +{ + (void)Connection; + CertFreeCertificateContext(*ppServerCert); + /* approve any certificate since the verification is set to bypass */ + return TRUE; +} +#endif + +static CURLcode show_vals(struct Curl_easy *data, BerValue **vals, + const char *attr) +{ + CURLcode result = CURLE_OK; + int i; + size_t attr_len = strlen(attr); + + for(i = 0; vals[i] && !result; i++) { + result = Curl_client_write(data, CLIENTWRITE_BODY, "\t", 1); + if(!result) + result = Curl_client_write(data, CLIENTWRITE_BODY, attr, attr_len); + if(!result) + result = Curl_client_write(data, CLIENTWRITE_BODY, ":", 1); + + if(result) + break; + + if(ldap_value_needs_base64(attr, attr_len, vals[i])) { + char *val_b64 = NULL; + size_t val_b64_sz = 0; + + /* Binary attribute, encode to base64. */ + if(vals[i]->bv_len) + result = curlx_base64_encode((uint8_t *)vals[i]->bv_val, + vals[i]->bv_len, + &val_b64, &val_b64_sz); + if(!result) + result = Curl_client_write(data, CLIENTWRITE_BODY, ": ", 2); + if(!result && val_b64_sz) + result = Curl_client_write(data, CLIENTWRITE_BODY, val_b64, + val_b64_sz); + curlx_free(val_b64); + } + else { + result = Curl_client_write(data, CLIENTWRITE_BODY, " ", 1); + if(!result) + result = Curl_client_write(data, CLIENTWRITE_BODY, + vals[i]->bv_val, vals[i]->bv_len); + } + + if(!result) + result = Curl_client_write(data, CLIENTWRITE_BODY, "\n", 1); + } + return result; +} + +static CURLcode ldap_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + curl_ldap_num_t rc = LDAP_SUCCESS; + LDAP *server = NULL; + LDAPURLDesc *ludp = NULL; + LDAPMessage *ldapmsg = NULL; + LDAPMessage *entryIterator; + int num = 0; + struct connectdata *conn = data->conn; + int ldap_proto = LDAP_VERSION3; + bool ldap_ssl = FALSE; +#ifdef LDAP_OPT_NETWORK_TIMEOUT + struct timeval ldap_timeout = { 10, 0 }; /* 10s connection/search timeout */ +#endif +#ifdef USE_WIN32_LDAP + TCHAR *host = NULL; +#else + char *host = NULL; +#endif + const char *user = data->state.creds ? data->state.creds->user : NULL; + const char *passwd = data->state.creds ? data->state.creds->passwd : NULL; + struct ip_quadruple ipquad; + bool is_ipv6; + BerElement *ber = NULL; + + *done = TRUE; /* unconditionally */ + infof(data, "LDAP local: LDAP Vendor = %s ; LDAP Version = %d", + LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION); + infof(data, "LDAP local: %s", Curl_bufref_ptr(&data->state.url)); + +#ifdef HAVE_LDAP_URL_PARSE + rc = ldap_url_parse(Curl_bufref_ptr(&data->state.url), &ludp); +#else + rc = ldap_url_parse_low(data, conn, &ludp); +#endif + if(rc) { + failf(data, "Bad LDAP URL: %s", ldap_err2string(rc)); + result = CURLE_URL_MALFORMAT; + goto quit; + } + + result = Curl_conn_get_ip_info(data, conn, FIRSTSOCKET, &is_ipv6, &ipquad); + if(result) + goto quit; + + /* Get the URL scheme (either ldap or ldaps) */ + ldap_ssl = Curl_conn_is_ssl(conn, FIRSTSOCKET); + infof(data, "LDAP local: trying to establish %s connection", + ldap_ssl ? "encrypted" : "cleartext"); + +#ifdef USE_WIN32_LDAP + host = curlx_convert_UTF8_to_tchar(conn->origin->hostname); + if(!host) { + result = CURLE_OUT_OF_MEMORY; + + goto quit; + } +#else + host = conn->origin->hostname; +#endif + +#ifdef USE_WIN32_LDAP + if(ldap_ssl) + server = ldap_sslinit(host, (curl_ldap_num_t)ipquad.remote_port, 1); + else +#endif + server = ldap_init(host, (curl_ldap_num_t)ipquad.remote_port); + if(!server) { + failf(data, "LDAP: cannot setup connect to %s:%u", + conn->origin->user_hostname, ipquad.remote_port); + result = CURLE_COULDNT_CONNECT; + goto quit; + } + +#ifdef LDAP_OPT_NETWORK_TIMEOUT + ldap_set_option(server, LDAP_OPT_NETWORK_TIMEOUT, &ldap_timeout); +#endif + ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); + + /* Do not chase referrals. */ + ldap_set_option(server, LDAP_OPT_REFERRALS, LDAP_OPT_OFF); + + if(ldap_ssl) { +#ifdef HAVE_LDAP_SSL +#ifdef USE_WIN32_LDAP + /* Win32 LDAP uses the Windows CA store to verify certificates */ + ldap_set_option(server, LDAP_OPT_SSL, LDAP_OPT_ON); + if(!conn->ssl_config.verifypeer) { + if(conn->ssl_config.verifyhost) { + failf(data, "LDAP local: host verification cannot be enabled when " + "peer verification is disabled for Windows native LDAP"); + result = CURLE_NOT_BUILT_IN; + goto quit; + } + ldap_set_option(server, LDAP_OPT_SERVER_CERTIFICATE, + (void *)(uintptr_t)bypass_cert_verify); + } +#else /* !USE_WIN32_LDAP */ + int ldap_option; + const char *ldap_ca = conn->ssl_config.CAfile; +#ifdef LDAP_OPT_X_TLS + if(conn->ssl_config.verifypeer) { + /* OpenLDAP SDK supports BASE64 files. */ + if(data->set.ssl.primary.cert_type && + !curl_strequal(data->set.ssl.primary.cert_type, "PEM")) { + failf(data, "LDAP local: ERROR OpenLDAP only supports PEM cert-type"); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + if(!ldap_ca) { + failf(data, "LDAP local: ERROR PEM CA cert not set"); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + infof(data, "LDAP local: using PEM CA cert: %s", ldap_ca); + rc = ldap_set_option(server, LDAP_OPT_X_TLS_CACERTFILE, ldap_ca); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR setting PEM CA cert: %s", + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + ldap_option = LDAP_OPT_X_TLS_DEMAND; + } + else + ldap_option = LDAP_OPT_X_TLS_NEVER; + + rc = ldap_set_option(server, LDAP_OPT_X_TLS_REQUIRE_CERT, &ldap_option); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR setting cert verify mode: %s", + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + ldap_option = LDAP_OPT_X_TLS_HARD; + rc = ldap_set_option(server, LDAP_OPT_X_TLS, &ldap_option); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR setting SSL/TLS mode: %s", + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } +#else /* !LDAP_OPT_X_TLS */ + (void)ldap_option; + (void)ldap_ca; + /* we should probably never come up to here since configure + should check in first place if we can support LDAP SSL/TLS */ + failf(data, "LDAP local: SSL/TLS not supported with this version " + "of the OpenLDAP toolkit"); + result = CURLE_SSL_CERTPROBLEM; + goto quit; +#endif /* LDAP_OPT_X_TLS */ +#endif /* USE_WIN32_LDAP */ +#endif /* HAVE_LDAP_SSL */ + } + else if(data->set.use_ssl > CURLUSESSL_TRY) { + failf(data, "LDAP local: explicit TLS not supported"); + result = CURLE_NOT_BUILT_IN; + goto quit; + } + +#ifdef USE_WIN32_LDAP + rc = ldap_win_bind(data, server, user, passwd); +#else + rc = ldap_simple_bind_s(server, user, passwd); +#endif + if(!ldap_ssl && rc != LDAP_SUCCESS) { + ldap_proto = LDAP_VERSION2; + ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); +#ifdef USE_WIN32_LDAP + rc = ldap_win_bind(data, server, user, passwd); +#else + rc = ldap_simple_bind_s(server, user, passwd); +#endif + } + if(rc != LDAP_SUCCESS) { +#ifdef USE_WIN32_LDAP + failf(data, "LDAP local: bind via ldap_win_bind %s", + ldap_err2string(rc)); +#else + failf(data, "LDAP local: bind via ldap_simple_bind_s %s", + ldap_err2string(rc)); +#endif + result = CURLE_LDAP_CANNOT_BIND; + goto quit; + } + + Curl_pgrsReset(data); + rc = ldap_search_s(server, ludp->lud_dn, + ludp->lud_scope, + ludp->lud_filter, ludp->lud_attrs, 0, &ldapmsg); + + if(rc != LDAP_SUCCESS && rc != LDAP_SIZELIMIT_EXCEEDED) { + failf(data, "LDAP remote: %s", ldap_err2string(rc)); + result = CURLE_LDAP_SEARCH_FAILED; + goto quit; + } + + num = 0; + for(entryIterator = ldap_first_entry(server, ldapmsg); + entryIterator; + entryIterator = ldap_next_entry(server, entryIterator), num++) { +#ifdef USE_WIN32_LDAP + TCHAR *attribute; +#else + char *attribute; +#endif + + /* Get the DN and write it to the client */ + { + char *name = NULL; + size_t name_len = 0; +#ifdef USE_WIN32_LDAP + TCHAR *dn = ldap_get_dn(server, entryIterator); + if(dn) + name = curlx_convert_tchar_to_UTF8(dn); +#else + char *dn = name = ldap_get_dn(server, entryIterator); +#endif + if(!name) + result = dn ? CURLE_OUT_OF_MEMORY : CURLE_FAILED_INIT; + else { + name_len = strlen(name); + result = Curl_client_write(data, CLIENTWRITE_BODY, "DN: ", 4); + } + if(!result) + result = Curl_client_write(data, CLIENTWRITE_BODY, name, name_len); + if(!result) + result = Curl_client_write(data, CLIENTWRITE_BODY, "\n", 1); + FREE_ON_WINLDAP(name); + ldap_memfree(dn); + if(result) + goto quit; + } + + /* Get the attributes and write them to the client */ + for(attribute = ldap_first_attribute(server, entryIterator, &ber); + attribute; + attribute = ldap_next_attribute(server, entryIterator, ber)) { + BerValue **vals; +#ifdef USE_WIN32_LDAP + char *attr = curlx_convert_tchar_to_UTF8(attribute); + if(!attr) { + ldap_memfree(attribute); + result = CURLE_OUT_OF_MEMORY; + goto quit; + } +#else + char *attr = attribute; +#endif + vals = ldap_get_values_len(server, entryIterator, attribute); + if(vals) { + result = show_vals(data, vals, attr); + /* Free memory used to store values */ + ldap_value_free_len(vals); + } + + /* Free the attribute as we are done with it */ + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + + if(!result) + result = Curl_client_write(data, CLIENTWRITE_BODY, "\n", 1); + if(result) + goto quit; + } + + if(ber) { + ber_free(ber, 0); + ber = NULL; + } + } + +quit: + if(ber) + ber_free(ber, 0); + if(ldapmsg) { + ldap_msgfree(ldapmsg); + LDAP_TRACE(("Received %d entries\n", num)); + } + if(rc == LDAP_SIZELIMIT_EXCEEDED) + infof(data, "There are more than %d entries", num); + if(ludp) + ldap_free_urldesc(ludp); + if(server) + ldap_unbind_s(server); + + FREE_ON_WINLDAP(host); + + /* no data to transfer */ + Curl_xfer_setup_nop(data); + connclose(conn); + + return result; +} + +#ifdef DEBUG_LDAP +static void ldap_trace_low(const char *fmt, ...) +{ + static int do_trace = -1; + va_list args; + + if(do_trace == -1) { + const char *env = getenv("CURL_TRACE"); + curl_off_t e = 0; + if(!curlx_str_number(&env, &e, INT_MAX)) + do_trace = e > 0; + } + if(!do_trace) + return; + + va_start(args, fmt); + curl_mvfprintf(stderr, fmt, args); + va_end(args); +} +#endif /* DEBUG_LDAP */ + +#ifndef HAVE_LDAP_URL_PARSE + +/* + * Return scope-value for a scope-string. + */ +static int str2scope(const char *p) +{ + if(curl_strequal(p, "one")) + return LDAP_SCOPE_ONELEVEL; + if(curl_strequal(p, "onetree")) + return LDAP_SCOPE_ONELEVEL; + if(curl_strequal(p, "base")) + return LDAP_SCOPE_BASE; + if(curl_strequal(p, "sub")) + return LDAP_SCOPE_SUBTREE; + if(curl_strequal(p, "subtree")) + return LDAP_SCOPE_SUBTREE; + return -1; +} + +/* number of entries in the attributes list */ +static size_t num_entries(const char *s) +{ + size_t items = 1; + + s = strchr(s, ','); + while(s) { + items++; + s = strchr(s + 1, ','); + } + return items; +} + +/* + * Break apart the pieces of an LDAP URL. + * Syntax: + * ldap://<hostname>:<port>/<base_dn>?<attributes>?<scope>?<filter>?<ext> + * + * <hostname> already known from 'conn->origin->hostname'. + * <port> already known from 'conn->origin->port'. + * extract the rest from 'data->state.path+1'. All fields are optional. + * e.g. + * ldap://<hostname>:<port>/?<attributes>?<scope>?<filter> + * yields ludp->lud_dn = "". + * + * Defined in RFC4516 section 2. + */ +static curl_ldap_num_t ldap_url_parse2_low(struct Curl_easy *data, + const struct connectdata *conn, + LDAPURLDesc *ludp) +{ + curl_ldap_num_t rc = LDAP_SUCCESS; + char *p; + char *path; + char *q = NULL; + char *query = NULL; + size_t i; + + if(!data || + !data->state.up.path || + data->state.up.path[0] != '/' || + ((data->state.origin->scheme != &Curl_scheme_ldap) && + (data->state.origin->scheme != &Curl_scheme_ldaps))) + return LDAP_INVALID_SYNTAX; + + ludp->lud_scope = LDAP_SCOPE_BASE; + ludp->lud_port = conn->origin->port; + ludp->lud_host = conn->origin->hostname; + + /* Duplicate the path */ + p = path = curlx_strdup(data->state.up.path + 1); + if(!path) + return LDAP_NO_MEMORY; + + /* Duplicate the query if present */ + if(data->state.up.query) { + q = query = curlx_strdup(data->state.up.query); + if(!query) { + curlx_free(path); + return LDAP_NO_MEMORY; + } + } + + /* Parse the DN (Distinguished Name) */ + if(*p) { + char *dn = p; + char *unescaped; + CURLcode result; + + LDAP_TRACE(("DN '%s'\n", dn)); + + /* Unescape the DN */ + result = Curl_urldecode(dn, 0, &unescaped, NULL, REJECT_ZERO); + if(result) { + rc = LDAP_NO_MEMORY; + + goto quit; + } + +#ifdef USE_WIN32_LDAP + /* Convert the unescaped string to a tchar */ + ludp->lud_dn = curlx_convert_UTF8_to_tchar(unescaped); + + /* Free the unescaped string as we are done with it */ + curlx_free(unescaped); + + if(!ludp->lud_dn) { + rc = LDAP_NO_MEMORY; + + goto quit; + } +#else + ludp->lud_dn = unescaped; +#endif + } + + p = q; + if(!p) + goto quit; + + /* Parse the attributes. skip "??" */ + q = strchr(p, '?'); + if(q) + *q++ = '\0'; + + if(*p) { + size_t count = num_entries(p); /* at least one */ + const char *atp = p; + + /* Allocate our array (+1 for the NULL entry) */ +#ifdef USE_WIN32_LDAP + ludp->lud_attrs = curlx_calloc(count + 1, sizeof(TCHAR *)); +#else + ludp->lud_attrs = curlx_calloc(count + 1, sizeof(char *)); +#endif + if(!ludp->lud_attrs) { + rc = LDAP_NO_MEMORY; + goto quit; + } + + for(i = 0; i < count; i++) { + char *unescaped; + CURLcode result; + struct Curl_str out; + + if(curlx_str_until(&atp, &out, 1024, ',')) + break; + + LDAP_TRACE(("attr[%zu] '%.*s'\n", i, (int)out.len, out.str)); + + /* Unescape the attribute */ + result = Curl_urldecode(out.str, out.len, &unescaped, NULL, REJECT_ZERO); + if(result) { + rc = LDAP_NO_MEMORY; + goto quit; + } + +#ifdef USE_WIN32_LDAP + /* Convert the unescaped string to a tchar */ + ludp->lud_attrs[i] = curlx_convert_UTF8_to_tchar(unescaped); + + /* Free the unescaped string as we are done with it */ + curlx_free(unescaped); + + if(!ludp->lud_attrs[i]) { + rc = LDAP_NO_MEMORY; + goto quit; + } +#else + ludp->lud_attrs[i] = unescaped; +#endif + + ludp->lud_attrs_dups++; + if(curlx_str_single(&atp, ',')) + break; + } + } + + p = q; + if(!p) + goto quit; + + /* Parse the scope. skip "??" */ + q = strchr(p, '?'); + if(q) + *q++ = '\0'; + + if(*p) { + ludp->lud_scope = str2scope(p); + if(ludp->lud_scope == -1) { + rc = LDAP_INVALID_SYNTAX; + + goto quit; + } + LDAP_TRACE(("scope %d\n", ludp->lud_scope)); + } + + p = q; + if(!p) + goto quit; + + /* Parse the filter */ + q = strchr(p, '?'); + if(q) + *q++ = '\0'; + + if(*p) { + char *filter = p; + char *unescaped; + CURLcode result; + + LDAP_TRACE(("filter '%s'\n", filter)); + + /* Unescape the filter */ + result = Curl_urldecode(filter, 0, &unescaped, NULL, REJECT_CTRL); + if(result) { + rc = LDAP_NO_MEMORY; + + goto quit; + } + +#ifdef USE_WIN32_LDAP + /* Convert the unescaped string to a tchar */ + ludp->lud_filter = curlx_convert_UTF8_to_tchar(unescaped); + + /* Free the unescaped string as we are done with it */ + curlx_free(unescaped); + + if(!ludp->lud_filter) { + rc = LDAP_NO_MEMORY; + + goto quit; + } +#else + ludp->lud_filter = unescaped; +#endif + } + + p = q; + if(p && !*p) { + rc = LDAP_INVALID_SYNTAX; + + goto quit; + } + +quit: + curlx_free(path); + curlx_free(query); + + return rc; +} + +static curl_ldap_num_t ldap_url_parse_low(struct Curl_easy *data, + const struct connectdata *conn, + LDAPURLDesc **ludpp) +{ + LDAPURLDesc *ludp = curlx_calloc(1, sizeof(*ludp)); + curl_ldap_num_t rc; + + *ludpp = NULL; + if(!ludp) + return LDAP_NO_MEMORY; + + rc = ldap_url_parse2_low(data, conn, ludp); + if(rc != LDAP_SUCCESS) { + ldap_free_urldesc_low(ludp); + ludp = NULL; + } + *ludpp = ludp; + return rc; +} + +static void ldap_free_urldesc_low(LDAPURLDesc *ludp) +{ + if(!ludp) + return; + + curlx_free(ludp->lud_dn); + curlx_free(ludp->lud_filter); + + if(ludp->lud_attrs) { + size_t i; + for(i = 0; i < ludp->lud_attrs_dups; i++) { + curlx_free(ludp->lud_attrs[i]); + } + curlx_free(ludp->lud_attrs); + } + + curlx_free(ludp); +} +#endif /* !HAVE_LDAP_URL_PARSE */ + +void Curl_ldap_version(char *buf, size_t bufsz) +{ +#ifdef USE_WIN32_LDAP + curl_msnprintf(buf, bufsz, "WinLDAP"); +#else +#ifdef LDAP_OPT_X_TLS_PASSPHRASE + static const char flavor[] = "/Apple"; +#else + static const char flavor[] = ""; +#endif + LDAPAPIInfo api; + api.ldapai_info_version = LDAP_API_INFO_VERSION; + + /* Comparing against 0, as different platforms + disagree on the success define name */ + if(ldap_get_option(NULL, LDAP_OPT_API_INFO, &api) == 0) { + unsigned int patch = (unsigned int)(api.ldapai_vendor_version % 100); + unsigned int major = (unsigned int)(api.ldapai_vendor_version / 10000); + unsigned int minor = + (((unsigned int)api.ldapai_vendor_version - (major * 10000)) + - patch) / 100; +#ifdef __OS400__ + curl_msnprintf(buf, bufsz, "IBMLDAP/%u.%u.%u", major, minor, patch); + ldap_value_free(api.ldapai_extensions); + (void)flavor; +#else + curl_msnprintf(buf, bufsz, "%s/%u.%u.%u%s", + api.ldapai_vendor_name, major, minor, patch, flavor); + ldap_memfree(api.ldapai_vendor_name); + ber_memvfree((void **)api.ldapai_extensions); +#endif + } + else + curl_msnprintf(buf, bufsz, "LDAP/1"); +#endif /* USE_WIN32_LDAP */ +} + +/* + * LDAP protocol handler. + */ +const struct Curl_protocol Curl_protocol_ldap = { + ZERO_NULL, /* setup_connection */ + ldap_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_pollset */ + ZERO_NULL, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#if defined(CURL_HAVE_DIAG) && defined(__APPLE__) +#pragma GCC diagnostic pop +#endif + +#endif /* !CURL_DISABLE_LDAP && !USE_OPENLDAP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/llist.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/llist.c new file mode 100644 index 0000000000..6528ebaef2 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/llist.c @@ -0,0 +1,270 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "llist.h" + +#ifdef DEBUGBUILD +#define LLISTINIT 0x100cc001 /* random pattern */ +#define NODEINIT 0x12344321 /* random pattern */ +#define NODEREM 0x54321012 /* random pattern */ + +#define VERIFYNODE(x) verifynode(x) +static struct Curl_llist_node *verifynode(struct Curl_llist_node *n) +{ + DEBUGASSERT(!n || (n->_init == NODEINIT)); + return n; +} +#else +#define VERIFYNODE(x) x +#endif +/* + * @unittest 1300 + */ +void Curl_llist_init(struct Curl_llist *l, Curl_llist_dtor dtor) +{ + l->_size = 0; + l->_dtor = dtor; + l->_head = NULL; + l->_tail = NULL; +#ifdef DEBUGBUILD + l->_init = LLISTINIT; +#endif +} + +/* + * Curl_llist_insert_next() + * + * Inserts a new list element after the given one 'e'. If the given existing + * entry is NULL and the list already has elements, the new one will be + * inserted first in the list. + * + * The 'ne' argument should be a pointer into the object to store. + * + * @unittest 1300 + */ +void Curl_llist_insert_next(struct Curl_llist *list, + struct Curl_llist_node *e, /* may be NULL */ + const void *p, + struct Curl_llist_node *ne) +{ + DEBUGASSERT(list); + DEBUGASSERT(list->_init == LLISTINIT); + DEBUGASSERT(ne); + +#ifdef DEBUGBUILD + ne->_init = NODEINIT; +#endif + ne->_ptr = CURL_UNCONST(p); + ne->_list = list; + if(list->_size == 0) { + list->_head = ne; + list->_head->_prev = NULL; + list->_head->_next = NULL; + list->_tail = ne; + } + else { + /* if 'e' is NULL here, we insert the new element first in the list */ + ne->_next = e ? e->_next : list->_head; + ne->_prev = e; + if(!e) { + list->_head->_prev = ne; + list->_head = ne; + } + else if(e->_next) { + e->_next->_prev = ne; + } + else { + list->_tail = ne; + } + if(e) + e->_next = ne; + } + + ++list->_size; +} + +/* + * Curl_llist_append() + * + * Adds a new list element to the end of the list. + * + * The 'ne' argument should be a pointer into the object to store. + * + * @unittest 1300 + */ +void Curl_llist_append(struct Curl_llist *list, const void *p, + struct Curl_llist_node *ne) +{ + DEBUGASSERT(list); + DEBUGASSERT(list->_init == LLISTINIT); + DEBUGASSERT(ne); + Curl_llist_insert_next(list, list->_tail, p, ne); +} + +void *Curl_node_take_elem(struct Curl_llist_node *e) +{ + void *ptr; + struct Curl_llist *list; + if(!e) + return NULL; + + list = e->_list; + DEBUGASSERT(list); + DEBUGASSERT(list->_init == LLISTINIT); + DEBUGASSERT(list->_size); + DEBUGASSERT(e->_init == NODEINIT); + if(list) { + if(e == list->_head) { + list->_head = e->_next; + + if(!list->_head) + list->_tail = NULL; + else + e->_next->_prev = NULL; + } + else { + if(e->_prev) + e->_prev->_next = e->_next; + + if(!e->_next) + list->_tail = e->_prev; + else + e->_next->_prev = e->_prev; + } + --list->_size; + } + ptr = e->_ptr; + + e->_list = NULL; + e->_ptr = NULL; + e->_prev = NULL; + e->_next = NULL; +#ifdef DEBUGBUILD + e->_init = NODEREM; /* specific pattern on remove - not zero */ +#endif + + return ptr; +} + +static void node_uremove(struct Curl_llist_node *e, void *user) +{ + struct Curl_llist *list; + void *ptr; + if(!e) + return; + + list = e->_list; + DEBUGASSERT(list); + if(list) { + ptr = Curl_node_take_elem(e); + if(list->_dtor) + list->_dtor(user, ptr); + } +} + +void Curl_node_remove(struct Curl_llist_node *e) +{ + node_uremove(e, NULL); +} + +void Curl_llist_destroy(struct Curl_llist *list, void *user) +{ + if(list) { + DEBUGASSERT(list->_init == LLISTINIT); + while(list->_size > 0) + node_uremove(list->_tail, user); + } +} + +/* Curl_llist_head() returns the first 'struct Curl_llist_node *', which + might be NULL */ +struct Curl_llist_node *Curl_llist_head(const struct Curl_llist *list) +{ + DEBUGASSERT(list); + DEBUGASSERT(list->_init == LLISTINIT); + return VERIFYNODE(list->_head); +} + +#ifdef UNITTESTS +/* llist_tail() returns the last 'struct Curl_llist_node *', which might be + NULL + + @unittest 1300 */ +UNITTEST struct Curl_llist_node *llist_tail(const struct Curl_llist *list); +UNITTEST struct Curl_llist_node *llist_tail(const struct Curl_llist *list) +{ + DEBUGASSERT(list); + DEBUGASSERT(list->_init == LLISTINIT); + return VERIFYNODE(list->_tail); +} +#endif + +/* Curl_llist_count() returns a size_t the number of nodes in the list */ +size_t Curl_llist_count(const struct Curl_llist *list) +{ + DEBUGASSERT(list); + DEBUGASSERT(list->_init == LLISTINIT); + return list->_size; +} + +/* Curl_node_elem() returns the custom data from a Curl_llist_node */ +void *Curl_node_elem(const struct Curl_llist_node *n) +{ + DEBUGASSERT(n); + DEBUGASSERT(n->_init == NODEINIT); + return n->_ptr; +} + +/* Curl_node_next() returns the next element in a list from a given + Curl_llist_node */ +struct Curl_llist_node *Curl_node_next(const struct Curl_llist_node *n) +{ + DEBUGASSERT(n); + DEBUGASSERT(n->_init == NODEINIT); + return VERIFYNODE(n->_next); +} + +#ifdef UNITTESTS +/* llist_node_prev() returns the previous element in a list from a given + Curl_llist_node + + @unittest 1300 */ +UNITTEST struct Curl_llist_node *llist_node_prev( + const struct Curl_llist_node *n); +UNITTEST struct Curl_llist_node *llist_node_prev( + const struct Curl_llist_node *n) +{ + DEBUGASSERT(n); + DEBUGASSERT(n->_init == NODEINIT); + return VERIFYNODE(n->_prev); +} +#endif + +struct Curl_llist *Curl_node_llist(const struct Curl_llist_node *n) +{ + DEBUGASSERT(n); + DEBUGASSERT(!n->_list || n->_init == NODEINIT); + return n->_list; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/llist.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/llist.h new file mode 100644 index 0000000000..de4adc972f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/llist.h @@ -0,0 +1,82 @@ +#ifndef HEADER_CURL_LLIST_H +#define HEADER_CURL_LLIST_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +typedef void (*Curl_llist_dtor)(void *user, void *elem); + +/* none of these struct members should be referenced directly, use the + dedicated functions */ + +struct Curl_llist { + struct Curl_llist_node *_head; + struct Curl_llist_node *_tail; + Curl_llist_dtor _dtor; + size_t _size; +#ifdef DEBUGBUILD + int _init; /* detect API usage mistakes */ +#endif +}; + +struct Curl_llist_node { + struct Curl_llist *_list; /* the list where this belongs */ + void *_ptr; + struct Curl_llist_node *_prev; + struct Curl_llist_node *_next; +#ifdef DEBUGBUILD + int _init; /* detect API usage mistakes */ +#endif +}; + +void Curl_llist_init(struct Curl_llist *l, Curl_llist_dtor dtor); +void Curl_llist_insert_next(struct Curl_llist *list, struct Curl_llist_node *e, + const void *p, struct Curl_llist_node *ne); +void Curl_llist_append(struct Curl_llist *list, const void *p, + struct Curl_llist_node *ne); +void Curl_node_remove(struct Curl_llist_node *e); +void Curl_llist_destroy(struct Curl_llist *list, void *user); + +/* Curl_llist_head() returns the first 'struct Curl_llist_node *', which + might be NULL */ +struct Curl_llist_node *Curl_llist_head(const struct Curl_llist *list); + +/* Curl_llist_count() returns a size_t the number of nodes in the list */ +size_t Curl_llist_count(const struct Curl_llist *list); + +/* Curl_node_elem() returns the custom data from a Curl_llist_node */ +void *Curl_node_elem(const struct Curl_llist_node *n); + +/* Remove the node from the list and return the custom data + * from a Curl_llist_node. Does NOT invoke a registered `dtor`. */ +void *Curl_node_take_elem(struct Curl_llist_node *e); + +/* Curl_node_next() returns the next element in a list from a given + Curl_llist_node */ +struct Curl_llist_node *Curl_node_next(const struct Curl_llist_node *n); + +/* Curl_node_llist() return the list the node is in or NULL. */ +struct Curl_llist *Curl_node_llist(const struct Curl_llist_node *n); + +#endif /* HEADER_CURL_LLIST_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/macos.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/macos.c new file mode 100644 index 0000000000..334dbc7d1d --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/macos.c @@ -0,0 +1,50 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef CURL_MACOS_CALL_COPYPROXIES + +#include "macos.h" + +#include <SystemConfiguration/SCDynamicStoreCopySpecific.h> + +CURLcode Curl_macos_init(void) +{ + /* + * The automagic conversion from IPv4 literals to IPv6 literals only + * works if the SCDynamicStoreCopyProxies system function gets called + * first. As curl currently does not support system-wide HTTP proxies, we + * therefore do not use any value this function might return. + * + * This function is only available on macOS and is not needed for + * IPv4-only builds, hence the conditions for defining + * CURL_MACOS_CALL_COPYPROXIES in curl_setup.h. + */ + CFDictionaryRef dict = SCDynamicStoreCopyProxies(NULL); + if(dict) + CFRelease(dict); + return CURLE_OK; +} + +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/macos.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/macos.h new file mode 100644 index 0000000000..0a72a30272 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/macos.h @@ -0,0 +1,34 @@ +#ifndef HEADER_CURL_MACOS_H +#define HEADER_CURL_MACOS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef CURL_MACOS_CALL_COPYPROXIES +CURLcode Curl_macos_init(void); +#else +#define Curl_macos_init() CURLE_OK +#endif + +#endif /* HEADER_CURL_MACOS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/md4.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/md4.c new file mode 100644 index 0000000000..e030ffac30 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/md4.c @@ -0,0 +1,466 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_CURL_NTLM_CORE + +#include "curl_md4.h" + +#ifdef USE_OPENSSL +#include <openssl/opensslv.h> +#if OPENSSL_VERSION_NUMBER >= 0x30000000L && !defined(USE_AMISSL) +/* OpenSSL 3.0.0 marks the MD4 functions as deprecated */ +#define OPENSSL_NO_MD4 +#else +/* Cover also OPENSSL_NO_MD4 configured in OpenSSL */ +#include <openssl/opensslconf.h> +#endif +#endif /* USE_OPENSSL */ + +#ifdef USE_WOLFSSL +#include <wolfssl/options.h> +#endif + +/* When OpenSSL or wolfSSL is available, we use their MD4 functions. */ + +#if defined(USE_OPENSSL) && !defined(OPENSSL_NO_MD4) +#include <openssl/md4.h> + +/* Map directly to OpenSSL implementation */ +#define my_md4_ctx MD4_CTX +#define my_md4_init MD4_Init +#define my_md4_update MD4_Update +#define my_md4_final MD4_Final + +#elif defined(USE_WOLFSSL) && !defined(NO_MD4) +#include <wolfssl/wolfcrypt/md4.h> +#include <wolfssl/version.h> + +#if LIBWOLFSSL_VERSION_HEX >= 0x05007006 +typedef wc_Md4 my_md4_ctx; +#else +typedef Md4 my_md4_ctx; +#endif + +static int my_md4_init(my_md4_ctx *ctx) +{ + wc_InitMd4(ctx); + return 1; +} + +static void my_md4_update(my_md4_ctx *ctx, + const void *input, unsigned long len) +{ + wc_Md4Update(ctx, input, (word32)len); +} + +static void my_md4_final(unsigned char *digest, my_md4_ctx *ctx) +{ + wc_Md4Final(ctx, digest); +} + +#elif (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \ + (__MAC_OS_X_VERSION_MAX_ALLOWED >= 1040) && \ + defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && \ + (__MAC_OS_X_VERSION_MIN_REQUIRED < 101500)) || \ + (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ + (__IPHONE_OS_VERSION_MAX_ALLOWED >= 20000) && \ + defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && \ + (__IPHONE_OS_VERSION_MIN_REQUIRED < 130000)) +#include <CommonCrypto/CommonDigest.h> + +typedef CC_MD4_CTX my_md4_ctx; + +static int my_md4_init(my_md4_ctx *ctx) +{ + return CC_MD4_Init(ctx); +} + +static void my_md4_update(my_md4_ctx *ctx, + const void *input, unsigned long len) +{ + (void)CC_MD4_Update(ctx, input, (CC_LONG)len); +} + +static void my_md4_final(unsigned char *digest, my_md4_ctx *ctx) +{ + (void)CC_MD4_Final(digest, ctx); +} + +#elif defined(USE_WIN32_CRYPTO) +#include <wincrypt.h> + +struct md4_ctx { + HCRYPTPROV hCryptProv; + HCRYPTHASH hHash; +}; +typedef struct md4_ctx my_md4_ctx; + +static int my_md4_init(my_md4_ctx *ctx) +{ + ctx->hCryptProv = 0; + ctx->hHash = 0; + + if(!CryptAcquireContext(&ctx->hCryptProv, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + return 0; + + if(!CryptCreateHash(ctx->hCryptProv, CALG_MD4, 0, 0, &ctx->hHash)) { + CryptReleaseContext(ctx->hCryptProv, 0); + ctx->hCryptProv = 0; + return 0; + } + + return 1; +} + +static void my_md4_update(my_md4_ctx *ctx, + const void *input, unsigned long len) +{ + CryptHashData(ctx->hHash, (const BYTE *)input, (unsigned int)len, 0); +} + +static void my_md4_final(unsigned char *digest, my_md4_ctx *ctx) +{ + unsigned long length = 0; + + CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0); + if(length == MD4_DIGEST_LENGTH) + CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &length, 0); + + if(ctx->hHash) + CryptDestroyHash(ctx->hHash); + + if(ctx->hCryptProv) + CryptReleaseContext(ctx->hCryptProv, 0); +} + +#elif defined(USE_GNUTLS) +#include <nettle/md4.h> +#include <nettle/version.h> + +typedef struct md4_ctx my_md4_ctx; + +static int my_md4_init(my_md4_ctx *ctx) +{ + md4_init(ctx); + return 1; +} + +static void my_md4_update(my_md4_ctx *ctx, + const void *input, unsigned long len) +{ + md4_update(ctx, len, input); +} + +static void my_md4_final(unsigned char *digest, my_md4_ctx *ctx) +{ +#if NETTLE_VERSION_MAJOR >= 4 + md4_digest(ctx, digest); +#else + md4_digest(ctx, MD4_DIGEST_SIZE, digest); +#endif +} + +#else +/* When no other crypto library is available, or the crypto library does not + * support MD4, we use this code segment this implementation of it + * + * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. + * MD4 Message-Digest Algorithm (RFC 1320). + * + * Homepage: + * https://openwall.info/wiki/people/solar/software/public-domain-source-code/md4 + * + * Author: + * Alexander Peslyak, better known as Solar Designer <solar at openwall.com> + * + * This software was written by Alexander Peslyak in 2001. No copyright is + * claimed, and the software is hereby placed in the public domain. In case + * this attempt to disclaim copyright and place the software in the public + * domain is deemed null and void, then the software is Copyright (c) 2001 + * Alexander Peslyak and it is hereby released to the general public under + * the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There is ABSOLUTELY NO WARRANTY, express or implied. + * + * (This is a heavily cut-down "BSD license".) + */ + +struct md4_ctx { + uint32_t lo, hi; + uint32_t a, b, c, d; + unsigned char buffer[64]; + uint32_t block[16]; +}; +typedef struct md4_ctx my_md4_ctx; + +/* + * The basic MD4 functions. + * + * F and G are optimized compared to their RFC 1320 definitions, with the + * optimization for F borrowed from Colin Plumb's MD5 implementation. + */ +#define MD4_F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) +#define MD4_G(x, y, z) (((x) & ((y) | (z))) | ((y) & (z))) +#define MD4_H(x, y, z) ((x) ^ (y) ^ (z)) + +/* + * The MD4 transformation for all three rounds. + */ +#define MD4_STEP(f, a, b, c, d, x, s) \ + (a) += f(b, c, d) + (x); \ + (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); + +/* + * SET reads 4 input bytes in little-endian byte order and stores them + * in a properly aligned word in host byte order. + * + * The check for little-endian architectures that tolerate unaligned memory + * accesses is an optimization. Nothing will break if it does not work. + */ +#if defined(__i386__) || defined(__x86_64__) || defined(__vax__) +#define MD4_SET(n) (*(const uint32_t *)(const void *)&ptr[(n) * 4]) +#define MD4_GET(n) MD4_SET(n) +#else +#define MD4_SET(n) (ctx->block[n] = \ + (uint32_t)ptr[(n) * 4] | \ + ((uint32_t)ptr[((n) * 4) + 1] << 8) | \ + ((uint32_t)ptr[((n) * 4) + 2] << 16) | \ + ((uint32_t)ptr[((n) * 4) + 3] << 24)) +#define MD4_GET(n) ctx->block[n] +#endif + +/* + * This processes one or more 64-byte data blocks, but does NOT update + * the bit counters. There are no alignment requirements. + */ +static const void *my_md4_body(my_md4_ctx *ctx, + const void *input, unsigned long size) +{ + const unsigned char *ptr; + uint32_t a, b, c, d; + + ptr = (const unsigned char *)input; + + a = ctx->a; + b = ctx->b; + c = ctx->c; + d = ctx->d; + + do { + uint32_t saved_a, saved_b, saved_c, saved_d; + + saved_a = a; + saved_b = b; + saved_c = c; + saved_d = d; + + /* Round 1 */ + MD4_STEP(MD4_F, a, b, c, d, MD4_SET(0), 3) + MD4_STEP(MD4_F, d, a, b, c, MD4_SET(1), 7) + MD4_STEP(MD4_F, c, d, a, b, MD4_SET(2), 11) + MD4_STEP(MD4_F, b, c, d, a, MD4_SET(3), 19) + MD4_STEP(MD4_F, a, b, c, d, MD4_SET(4), 3) + MD4_STEP(MD4_F, d, a, b, c, MD4_SET(5), 7) + MD4_STEP(MD4_F, c, d, a, b, MD4_SET(6), 11) + MD4_STEP(MD4_F, b, c, d, a, MD4_SET(7), 19) + MD4_STEP(MD4_F, a, b, c, d, MD4_SET(8), 3) + MD4_STEP(MD4_F, d, a, b, c, MD4_SET(9), 7) + MD4_STEP(MD4_F, c, d, a, b, MD4_SET(10), 11) + MD4_STEP(MD4_F, b, c, d, a, MD4_SET(11), 19) + MD4_STEP(MD4_F, a, b, c, d, MD4_SET(12), 3) + MD4_STEP(MD4_F, d, a, b, c, MD4_SET(13), 7) + MD4_STEP(MD4_F, c, d, a, b, MD4_SET(14), 11) + MD4_STEP(MD4_F, b, c, d, a, MD4_SET(15), 19) + + /* Round 2 */ + MD4_STEP(MD4_G, a, b, c, d, MD4_GET(0) + 0x5a827999, 3) + MD4_STEP(MD4_G, d, a, b, c, MD4_GET(4) + 0x5a827999, 5) + MD4_STEP(MD4_G, c, d, a, b, MD4_GET(8) + 0x5a827999, 9) + MD4_STEP(MD4_G, b, c, d, a, MD4_GET(12) + 0x5a827999, 13) + MD4_STEP(MD4_G, a, b, c, d, MD4_GET(1) + 0x5a827999, 3) + MD4_STEP(MD4_G, d, a, b, c, MD4_GET(5) + 0x5a827999, 5) + MD4_STEP(MD4_G, c, d, a, b, MD4_GET(9) + 0x5a827999, 9) + MD4_STEP(MD4_G, b, c, d, a, MD4_GET(13) + 0x5a827999, 13) + MD4_STEP(MD4_G, a, b, c, d, MD4_GET(2) + 0x5a827999, 3) + MD4_STEP(MD4_G, d, a, b, c, MD4_GET(6) + 0x5a827999, 5) + MD4_STEP(MD4_G, c, d, a, b, MD4_GET(10) + 0x5a827999, 9) + MD4_STEP(MD4_G, b, c, d, a, MD4_GET(14) + 0x5a827999, 13) + MD4_STEP(MD4_G, a, b, c, d, MD4_GET(3) + 0x5a827999, 3) + MD4_STEP(MD4_G, d, a, b, c, MD4_GET(7) + 0x5a827999, 5) + MD4_STEP(MD4_G, c, d, a, b, MD4_GET(11) + 0x5a827999, 9) + MD4_STEP(MD4_G, b, c, d, a, MD4_GET(15) + 0x5a827999, 13) + + /* Round 3 */ + MD4_STEP(MD4_H, a, b, c, d, MD4_GET(0) + 0x6ed9eba1, 3) + MD4_STEP(MD4_H, d, a, b, c, MD4_GET(8) + 0x6ed9eba1, 9) + MD4_STEP(MD4_H, c, d, a, b, MD4_GET(4) + 0x6ed9eba1, 11) + MD4_STEP(MD4_H, b, c, d, a, MD4_GET(12) + 0x6ed9eba1, 15) + MD4_STEP(MD4_H, a, b, c, d, MD4_GET(2) + 0x6ed9eba1, 3) + MD4_STEP(MD4_H, d, a, b, c, MD4_GET(10) + 0x6ed9eba1, 9) + MD4_STEP(MD4_H, c, d, a, b, MD4_GET(6) + 0x6ed9eba1, 11) + MD4_STEP(MD4_H, b, c, d, a, MD4_GET(14) + 0x6ed9eba1, 15) + MD4_STEP(MD4_H, a, b, c, d, MD4_GET(1) + 0x6ed9eba1, 3) + MD4_STEP(MD4_H, d, a, b, c, MD4_GET(9) + 0x6ed9eba1, 9) + MD4_STEP(MD4_H, c, d, a, b, MD4_GET(5) + 0x6ed9eba1, 11) + MD4_STEP(MD4_H, b, c, d, a, MD4_GET(13) + 0x6ed9eba1, 15) + MD4_STEP(MD4_H, a, b, c, d, MD4_GET(3) + 0x6ed9eba1, 3) + MD4_STEP(MD4_H, d, a, b, c, MD4_GET(11) + 0x6ed9eba1, 9) + MD4_STEP(MD4_H, c, d, a, b, MD4_GET(7) + 0x6ed9eba1, 11) + MD4_STEP(MD4_H, b, c, d, a, MD4_GET(15) + 0x6ed9eba1, 15) + + a += saved_a; + b += saved_b; + c += saved_c; + d += saved_d; + + ptr += 64; + } while(size -= 64); + + ctx->a = a; + ctx->b = b; + ctx->c = c; + ctx->d = d; + + return ptr; +} + +static int my_md4_init(my_md4_ctx *ctx) +{ + ctx->a = 0x67452301; + ctx->b = 0xefcdab89; + ctx->c = 0x98badcfe; + ctx->d = 0x10325476; + + ctx->lo = 0; + ctx->hi = 0; + + return 1; +} + +static void my_md4_update(my_md4_ctx *ctx, + const void *input, unsigned long len) +{ + uint32_t saved_lo; + unsigned long used; + + saved_lo = ctx->lo; + ctx->lo = (saved_lo + len) & 0x1fffffff; + if(ctx->lo < saved_lo) + ctx->hi++; + ctx->hi += (uint32_t)len >> 29; + + used = saved_lo & 0x3f; + + if(used) { + unsigned long available = 64 - used; + + if(len < available) { + memcpy(&ctx->buffer[used], input, len); + return; + } + + memcpy(&ctx->buffer[used], input, available); + input = (const unsigned char *)input + available; + len -= available; + my_md4_body(ctx, ctx->buffer, 64); + } + + if(len >= 64) { + input = my_md4_body(ctx, input, len & ~(unsigned long)0x3f); + len &= 0x3f; + } + + memcpy(ctx->buffer, input, len); +} + +static void my_md4_final(unsigned char *digest, my_md4_ctx *ctx) +{ + unsigned long used, available; + + used = ctx->lo & 0x3f; + + ctx->buffer[used++] = 0x80; + + available = 64 - used; + + if(available < 8) { + memset(&ctx->buffer[used], 0, available); + my_md4_body(ctx, ctx->buffer, 64); + used = 0; + available = 64; + } + + memset(&ctx->buffer[used], 0, available - 8); + + ctx->lo <<= 3; + ctx->buffer[56] = curlx_ultouc((ctx->lo) & 0xff); + ctx->buffer[57] = curlx_ultouc((ctx->lo >> 8) & 0xff); + ctx->buffer[58] = curlx_ultouc((ctx->lo >> 16) & 0xff); + ctx->buffer[59] = curlx_ultouc((ctx->lo >> 24) & 0xff); + ctx->buffer[60] = curlx_ultouc((ctx->hi) & 0xff); + ctx->buffer[61] = curlx_ultouc((ctx->hi >> 8) & 0xff); + ctx->buffer[62] = curlx_ultouc((ctx->hi >> 16) & 0xff); + ctx->buffer[63] = curlx_ultouc(ctx->hi >> 24); + + my_md4_body(ctx, ctx->buffer, 64); + + digest[0] = curlx_ultouc((ctx->a) & 0xff); + digest[1] = curlx_ultouc((ctx->a >> 8) & 0xff); + digest[2] = curlx_ultouc((ctx->a >> 16) & 0xff); + digest[3] = curlx_ultouc(ctx->a >> 24); + digest[4] = curlx_ultouc((ctx->b) & 0xff); + digest[5] = curlx_ultouc((ctx->b >> 8) & 0xff); + digest[6] = curlx_ultouc((ctx->b >> 16) & 0xff); + digest[7] = curlx_ultouc(ctx->b >> 24); + digest[8] = curlx_ultouc((ctx->c) & 0xff); + digest[9] = curlx_ultouc((ctx->c >> 8) & 0xff); + digest[10] = curlx_ultouc((ctx->c >> 16) & 0xff); + digest[11] = curlx_ultouc(ctx->c >> 24); + digest[12] = curlx_ultouc((ctx->d) & 0xff); + digest[13] = curlx_ultouc((ctx->d >> 8) & 0xff); + digest[14] = curlx_ultouc((ctx->d >> 16) & 0xff); + digest[15] = curlx_ultouc(ctx->d >> 24); + + memset(ctx, 0, sizeof(*ctx)); +} + +#endif /* CRYPTO LIBS */ + +CURLcode Curl_md4it(unsigned char *output, + const unsigned char *input, const size_t len) +{ + my_md4_ctx ctx; + if(!my_md4_init(&ctx)) + return CURLE_FAILED_INIT; + my_md4_update(&ctx, input, curlx_uztoui(len)); + my_md4_final(output, &ctx); + return CURLE_OK; +} + +#endif /* USE_CURL_NTLM_CORE */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/md5.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/md5.c new file mode 100644 index 0000000000..f842c7ae63 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/md5.c @@ -0,0 +1,613 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if (defined(USE_CURL_NTLM_CORE) && !defined(USE_WINDOWS_SSPI)) || \ + !defined(CURL_DISABLE_DIGEST_AUTH) + +#include "curl_md5.h" +#include "curl_hmac.h" + +#ifdef USE_OPENSSL +#include <openssl/opensslconf.h> +#endif + +#ifdef USE_WOLFSSL +#include <wolfssl/options.h> +#endif + +#ifdef USE_MBEDTLS +#include <mbedtls/version.h> +#if MBEDTLS_VERSION_NUMBER < 0x03020000 +#error "mbedTLS 3.2.0 or greater required" +#endif +#include <psa/crypto_config.h> +#endif + +#ifdef USE_GNUTLS +#include <nettle/md5.h> +#include <nettle/version.h> + +typedef struct md5_ctx my_md5_ctx; + +static CURLcode my_md5_init(void *ctx) +{ + md5_init(ctx); + return CURLE_OK; +} + +static void my_md5_update(void *ctx, + const unsigned char *input, unsigned int len) +{ + md5_update(ctx, len, input); +} + +static void my_md5_final(unsigned char *digest, void *ctx) +{ +#if NETTLE_VERSION_MAJOR >= 4 + md5_digest(ctx, digest); +#else + md5_digest(ctx, MD5_DIGEST_LEN, digest); +#endif +} + +#elif defined(USE_OPENSSL) && \ + !defined(OPENSSL_NO_MD5) && !defined(OPENSSL_NO_DEPRECATED_3_0) +#include <openssl/md5.h> + +typedef MD5_CTX my_md5_ctx; + +static CURLcode my_md5_init(void *ctx) +{ + if(!MD5_Init(ctx)) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static void my_md5_update(void *ctx, + const unsigned char *input, unsigned int len) +{ + (void)MD5_Update(ctx, input, len); +} + +static void my_md5_final(unsigned char *digest, void *ctx) +{ + (void)MD5_Final(digest, ctx); +} + +#elif defined(USE_WOLFSSL) && !defined(NO_MD5) +#include <wolfssl/wolfcrypt/md5.h> + +typedef wc_Md5 my_md5_ctx; + +static CURLcode my_md5_init(void *ctx) +{ + if(wc_InitMd5(ctx)) + return CURLE_OUT_OF_MEMORY; + return CURLE_OK; +} + +static void my_md5_update(void *ctx, + const unsigned char *input, unsigned int len) +{ + (void)wc_Md5Update(ctx, input, (word32)len); +} + +static void my_md5_final(unsigned char *digest, void *ctx) +{ + (void)wc_Md5Final(ctx, digest); +} + +#elif defined(USE_MBEDTLS) && \ + defined(PSA_WANT_ALG_MD5) && PSA_WANT_ALG_MD5 +#include <psa/crypto.h> + +typedef psa_hash_operation_t my_md5_ctx; + +static CURLcode my_md5_init(void *ctx) +{ + psa_hash_operation_t *pctx = (psa_hash_operation_t *)ctx; + *pctx = psa_hash_operation_init(); + if(psa_hash_setup(pctx, PSA_ALG_MD5) != PSA_SUCCESS) + return CURLE_OUT_OF_MEMORY; + return CURLE_OK; +} + +static void my_md5_update(void *ctx, + const unsigned char *input, unsigned int len) +{ + (void)psa_hash_update(ctx, input, len); +} + +static void my_md5_final(unsigned char *digest, void *ctx) +{ + size_t actual_length; + (void)psa_hash_finish(ctx, digest, MD5_DIGEST_LEN, &actual_length); +} + +#elif (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \ + (__MAC_OS_X_VERSION_MAX_ALLOWED >= 1040) && \ + defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && \ + (__MAC_OS_X_VERSION_MIN_REQUIRED < 101500)) || \ + (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ + (__IPHONE_OS_VERSION_MAX_ALLOWED >= 20000) && \ + defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && \ + (__IPHONE_OS_VERSION_MIN_REQUIRED < 130000)) +#include <CommonCrypto/CommonDigest.h> + +/* For Apple operating systems: CommonCrypto has the functions we need. + These functions are available on Tiger and later, as well as iOS 2.0 + and later. If you are building for an older cat, well, sorry. + + Declaring the functions as static like this seems to be a bit more + reliable than defining COMMON_DIGEST_FOR_OPENSSL on older cats. */ +# define my_md5_ctx CC_MD5_CTX + +static CURLcode my_md5_init(void *ctx) +{ + if(!CC_MD5_Init(ctx)) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static void my_md5_update(void *ctx, + const unsigned char *input, unsigned int len) +{ + CC_MD5_Update(ctx, input, len); +} + +static void my_md5_final(unsigned char *digest, void *ctx) +{ + CC_MD5_Final(digest, ctx); +} + +#elif defined(USE_WIN32_CRYPTO) +#include <wincrypt.h> + +struct md5_ctx { + HCRYPTPROV hCryptProv; + HCRYPTHASH hHash; +}; +typedef struct md5_ctx my_md5_ctx; + +static CURLcode my_md5_init(void *in) +{ + my_md5_ctx *ctx = (my_md5_ctx *)in; + if(!CryptAcquireContext(&ctx->hCryptProv, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + return CURLE_OUT_OF_MEMORY; + + if(!CryptCreateHash(ctx->hCryptProv, CALG_MD5, 0, 0, &ctx->hHash)) { + CryptReleaseContext(ctx->hCryptProv, 0); + ctx->hCryptProv = 0; + return CURLE_FAILED_INIT; + } + + return CURLE_OK; +} + +static void my_md5_update(void *in, + const unsigned char *input, unsigned int len) +{ + my_md5_ctx *ctx = in; + CryptHashData(ctx->hHash, (const BYTE *)input, len, 0); +} + +static void my_md5_final(unsigned char *digest, void *in) +{ + my_md5_ctx *ctx = (my_md5_ctx *)in; + unsigned long length = 0; + CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0); + if(length == MD5_DIGEST_LEN) + CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &length, 0); + if(ctx->hHash) + CryptDestroyHash(ctx->hHash); + if(ctx->hCryptProv) + CryptReleaseContext(ctx->hCryptProv, 0); +} + +#else + +/* When no other crypto library is available we use this code segment */ + +/* + * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. + * MD5 Message-Digest Algorithm (RFC 1321). + * + * Homepage: + * https://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 + * + * Author: + * Alexander Peslyak, better known as Solar Designer <solar at openwall.com> + * + * This software was written by Alexander Peslyak in 2001. No copyright is + * claimed, and the software is hereby placed in the public domain. In case + * this attempt to disclaim copyright and place the software in the public + * domain is deemed null and void, then the software is Copyright (c) 2001 + * Alexander Peslyak and it is hereby released to the general public under + * the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There is ABSOLUTELY NO WARRANTY, express or implied. + * + * (This is a heavily cut-down "BSD license".) + */ + +struct md5_ctx { + uint32_t lo, hi; + uint32_t a, b, c, d; + unsigned char buffer[64]; + uint32_t block[16]; +}; +typedef struct md5_ctx my_md5_ctx; + +/* + * The basic MD5 functions. + * + * F and G are optimized compared to their RFC 1321 definitions for + * architectures that lack an AND-NOT instruction, like in Colin Plumb's + * implementation. + */ +#define MD5_F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) +#define MD5_G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) +#define MD5_H(x, y, z) (((x) ^ (y)) ^ (z)) +#define MD5_H2(x, y, z) ((x) ^ ((y) ^ (z))) +#define MD5_I(x, y, z) ((y) ^ ((x) | ~(z))) + +/* + * The MD5 transformation for all four rounds. + */ +#define MD5_STEP(f, a, b, c, d, x, t, s) \ + (a) += f(b, c, d) + (x) + (t); \ + (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ + (a) += (b); + +/* + * SET reads 4 input bytes in little-endian byte order and stores them + * in a properly aligned word in host byte order. + * + * The check for little-endian architectures that tolerate unaligned memory + * accesses is an optimization. Nothing will break if it does not work. + */ +#if defined(__i386__) || defined(__x86_64__) || defined(__vax__) +#define MD5_SET(n) (*(const uint32_t *)(const void *)&ptr[(n) * 4]) +#define MD5_GET(n) MD5_SET(n) +#else +#define MD5_SET(n) (ctx->block[n] = \ + (uint32_t)ptr[(n) * 4] | \ + ((uint32_t)ptr[((n) * 4) + 1] << 8) | \ + ((uint32_t)ptr[((n) * 4) + 2] << 16) | \ + ((uint32_t)ptr[((n) * 4) + 3] << 24)) +#define MD5_GET(n) ctx->block[n] +#endif + +/* + * This processes one or more 64-byte data blocks, but does NOT update + * the bit counters. There are no alignment requirements. + */ +static const void *my_md5_body(my_md5_ctx *ctx, + const void *data, unsigned long size) +{ + const unsigned char *ptr; + uint32_t a, b, c, d; + + ptr = (const unsigned char *)data; + + a = ctx->a; + b = ctx->b; + c = ctx->c; + d = ctx->d; + + do { + uint32_t saved_a, saved_b, saved_c, saved_d; + + saved_a = a; + saved_b = b; + saved_c = c; + saved_d = d; + + /* Round 1 */ + MD5_STEP(MD5_F, a, b, c, d, MD5_SET(0), 0xd76aa478, 7) + MD5_STEP(MD5_F, d, a, b, c, MD5_SET(1), 0xe8c7b756, 12) + MD5_STEP(MD5_F, c, d, a, b, MD5_SET(2), 0x242070db, 17) + MD5_STEP(MD5_F, b, c, d, a, MD5_SET(3), 0xc1bdceee, 22) + MD5_STEP(MD5_F, a, b, c, d, MD5_SET(4), 0xf57c0faf, 7) + MD5_STEP(MD5_F, d, a, b, c, MD5_SET(5), 0x4787c62a, 12) + MD5_STEP(MD5_F, c, d, a, b, MD5_SET(6), 0xa8304613, 17) + MD5_STEP(MD5_F, b, c, d, a, MD5_SET(7), 0xfd469501, 22) + MD5_STEP(MD5_F, a, b, c, d, MD5_SET(8), 0x698098d8, 7) + MD5_STEP(MD5_F, d, a, b, c, MD5_SET(9), 0x8b44f7af, 12) + MD5_STEP(MD5_F, c, d, a, b, MD5_SET(10), 0xffff5bb1, 17) + MD5_STEP(MD5_F, b, c, d, a, MD5_SET(11), 0x895cd7be, 22) + MD5_STEP(MD5_F, a, b, c, d, MD5_SET(12), 0x6b901122, 7) + MD5_STEP(MD5_F, d, a, b, c, MD5_SET(13), 0xfd987193, 12) + MD5_STEP(MD5_F, c, d, a, b, MD5_SET(14), 0xa679438e, 17) + MD5_STEP(MD5_F, b, c, d, a, MD5_SET(15), 0x49b40821, 22) + + /* Round 2 */ + MD5_STEP(MD5_G, a, b, c, d, MD5_GET(1), 0xf61e2562, 5) + MD5_STEP(MD5_G, d, a, b, c, MD5_GET(6), 0xc040b340, 9) + MD5_STEP(MD5_G, c, d, a, b, MD5_GET(11), 0x265e5a51, 14) + MD5_STEP(MD5_G, b, c, d, a, MD5_GET(0), 0xe9b6c7aa, 20) + MD5_STEP(MD5_G, a, b, c, d, MD5_GET(5), 0xd62f105d, 5) + MD5_STEP(MD5_G, d, a, b, c, MD5_GET(10), 0x02441453, 9) + MD5_STEP(MD5_G, c, d, a, b, MD5_GET(15), 0xd8a1e681, 14) + MD5_STEP(MD5_G, b, c, d, a, MD5_GET(4), 0xe7d3fbc8, 20) + MD5_STEP(MD5_G, a, b, c, d, MD5_GET(9), 0x21e1cde6, 5) + MD5_STEP(MD5_G, d, a, b, c, MD5_GET(14), 0xc33707d6, 9) + MD5_STEP(MD5_G, c, d, a, b, MD5_GET(3), 0xf4d50d87, 14) + MD5_STEP(MD5_G, b, c, d, a, MD5_GET(8), 0x455a14ed, 20) + MD5_STEP(MD5_G, a, b, c, d, MD5_GET(13), 0xa9e3e905, 5) + MD5_STEP(MD5_G, d, a, b, c, MD5_GET(2), 0xfcefa3f8, 9) + MD5_STEP(MD5_G, c, d, a, b, MD5_GET(7), 0x676f02d9, 14) + MD5_STEP(MD5_G, b, c, d, a, MD5_GET(12), 0x8d2a4c8a, 20) + + /* Round 3 */ + MD5_STEP(MD5_H, a, b, c, d, MD5_GET(5), 0xfffa3942, 4) + MD5_STEP(MD5_H2, d, a, b, c, MD5_GET(8), 0x8771f681, 11) + MD5_STEP(MD5_H, c, d, a, b, MD5_GET(11), 0x6d9d6122, 16) + MD5_STEP(MD5_H2, b, c, d, a, MD5_GET(14), 0xfde5380c, 23) + MD5_STEP(MD5_H, a, b, c, d, MD5_GET(1), 0xa4beea44, 4) + MD5_STEP(MD5_H2, d, a, b, c, MD5_GET(4), 0x4bdecfa9, 11) + MD5_STEP(MD5_H, c, d, a, b, MD5_GET(7), 0xf6bb4b60, 16) + MD5_STEP(MD5_H2, b, c, d, a, MD5_GET(10), 0xbebfbc70, 23) + MD5_STEP(MD5_H, a, b, c, d, MD5_GET(13), 0x289b7ec6, 4) + MD5_STEP(MD5_H2, d, a, b, c, MD5_GET(0), 0xeaa127fa, 11) + MD5_STEP(MD5_H, c, d, a, b, MD5_GET(3), 0xd4ef3085, 16) + MD5_STEP(MD5_H2, b, c, d, a, MD5_GET(6), 0x04881d05, 23) + MD5_STEP(MD5_H, a, b, c, d, MD5_GET(9), 0xd9d4d039, 4) + MD5_STEP(MD5_H2, d, a, b, c, MD5_GET(12), 0xe6db99e5, 11) + MD5_STEP(MD5_H, c, d, a, b, MD5_GET(15), 0x1fa27cf8, 16) + MD5_STEP(MD5_H2, b, c, d, a, MD5_GET(2), 0xc4ac5665, 23) + + /* Round 4 */ + MD5_STEP(MD5_I, a, b, c, d, MD5_GET(0), 0xf4292244, 6) + MD5_STEP(MD5_I, d, a, b, c, MD5_GET(7), 0x432aff97, 10) + MD5_STEP(MD5_I, c, d, a, b, MD5_GET(14), 0xab9423a7, 15) + MD5_STEP(MD5_I, b, c, d, a, MD5_GET(5), 0xfc93a039, 21) + MD5_STEP(MD5_I, a, b, c, d, MD5_GET(12), 0x655b59c3, 6) + MD5_STEP(MD5_I, d, a, b, c, MD5_GET(3), 0x8f0ccc92, 10) + MD5_STEP(MD5_I, c, d, a, b, MD5_GET(10), 0xffeff47d, 15) + MD5_STEP(MD5_I, b, c, d, a, MD5_GET(1), 0x85845dd1, 21) + MD5_STEP(MD5_I, a, b, c, d, MD5_GET(8), 0x6fa87e4f, 6) + MD5_STEP(MD5_I, d, a, b, c, MD5_GET(15), 0xfe2ce6e0, 10) + MD5_STEP(MD5_I, c, d, a, b, MD5_GET(6), 0xa3014314, 15) + MD5_STEP(MD5_I, b, c, d, a, MD5_GET(13), 0x4e0811a1, 21) + MD5_STEP(MD5_I, a, b, c, d, MD5_GET(4), 0xf7537e82, 6) + MD5_STEP(MD5_I, d, a, b, c, MD5_GET(11), 0xbd3af235, 10) + MD5_STEP(MD5_I, c, d, a, b, MD5_GET(2), 0x2ad7d2bb, 15) + MD5_STEP(MD5_I, b, c, d, a, MD5_GET(9), 0xeb86d391, 21) + + a += saved_a; + b += saved_b; + c += saved_c; + d += saved_d; + + ptr += 64; + } while(size -= 64); + + ctx->a = a; + ctx->b = b; + ctx->c = c; + ctx->d = d; + + return ptr; +} + +static CURLcode my_md5_init(void *in) +{ + my_md5_ctx *ctx = (my_md5_ctx *)in; + ctx->a = 0x67452301; + ctx->b = 0xefcdab89; + ctx->c = 0x98badcfe; + ctx->d = 0x10325476; + + ctx->lo = 0; + ctx->hi = 0; + + return CURLE_OK; +} + +static void my_md5_update(void *in, + const unsigned char *input, unsigned int len) +{ + uint32_t saved_lo; + unsigned int used; + my_md5_ctx *ctx = (my_md5_ctx *)in; + + saved_lo = ctx->lo; + ctx->lo = (saved_lo + len) & 0x1fffffff; + if(ctx->lo < saved_lo) + ctx->hi++; + ctx->hi += (uint32_t)len >> 29; + + used = saved_lo & 0x3f; + + if(used) { + unsigned int available = 64 - used; + + if(len < available) { + memcpy(&ctx->buffer[used], input, len); + return; + } + + memcpy(&ctx->buffer[used], input, available); + input = (const unsigned char *)input + available; + len -= available; + my_md5_body(ctx, ctx->buffer, 64); + } + + if(len >= 64) { + input = my_md5_body(ctx, input, len & ~(unsigned long)0x3f); + len &= 0x3f; + } + + memcpy(ctx->buffer, input, len); +} + +static void my_md5_final(unsigned char *digest, void *in) +{ + unsigned int used, available; + my_md5_ctx *ctx = (my_md5_ctx *)in; + + used = ctx->lo & 0x3f; + + ctx->buffer[used++] = 0x80; + + available = 64 - used; + + if(available < 8) { + memset(&ctx->buffer[used], 0, available); + my_md5_body(ctx, ctx->buffer, 64); + used = 0; + available = 64; + } + + memset(&ctx->buffer[used], 0, available - 8); + + ctx->lo <<= 3; + ctx->buffer[56] = curlx_ultouc((ctx->lo) & 0xff); + ctx->buffer[57] = curlx_ultouc((ctx->lo >> 8) & 0xff); + ctx->buffer[58] = curlx_ultouc((ctx->lo >> 16) & 0xff); + ctx->buffer[59] = curlx_ultouc(ctx->lo >> 24); + ctx->buffer[60] = curlx_ultouc((ctx->hi) & 0xff); + ctx->buffer[61] = curlx_ultouc((ctx->hi >> 8) & 0xff); + ctx->buffer[62] = curlx_ultouc((ctx->hi >> 16) & 0xff); + ctx->buffer[63] = curlx_ultouc(ctx->hi >> 24); + + my_md5_body(ctx, ctx->buffer, 64); + + digest[0] = curlx_ultouc((ctx->a) & 0xff); + digest[1] = curlx_ultouc((ctx->a >> 8) & 0xff); + digest[2] = curlx_ultouc((ctx->a >> 16) & 0xff); + digest[3] = curlx_ultouc(ctx->a >> 24); + digest[4] = curlx_ultouc((ctx->b) & 0xff); + digest[5] = curlx_ultouc((ctx->b >> 8) & 0xff); + digest[6] = curlx_ultouc((ctx->b >> 16) & 0xff); + digest[7] = curlx_ultouc(ctx->b >> 24); + digest[8] = curlx_ultouc((ctx->c) & 0xff); + digest[9] = curlx_ultouc((ctx->c >> 8) & 0xff); + digest[10] = curlx_ultouc((ctx->c >> 16) & 0xff); + digest[11] = curlx_ultouc(ctx->c >> 24); + digest[12] = curlx_ultouc((ctx->d) & 0xff); + digest[13] = curlx_ultouc((ctx->d >> 8) & 0xff); + digest[14] = curlx_ultouc((ctx->d >> 16) & 0xff); + digest[15] = curlx_ultouc(ctx->d >> 24); + + memset(ctx, 0, sizeof(*ctx)); +} + +#endif /* CRYPTO LIBS */ + +const struct HMAC_params Curl_HMAC_MD5 = { + my_md5_init, /* Hash initialization function. */ + my_md5_update, /* Hash update function. */ + my_md5_final, /* Hash computation end function. */ + sizeof(my_md5_ctx), /* Size of hash context structure. */ + 64, /* Maximum key length. */ + MD5_DIGEST_LEN /* Result size. */ +}; + +const struct MD5_params Curl_DIGEST_MD5 = { + my_md5_init, /* Digest initialization function */ + my_md5_update, /* Digest update function */ + my_md5_final, /* Digest computation end function */ + sizeof(my_md5_ctx), /* Size of digest context struct */ + MD5_DIGEST_LEN /* Result size */ +}; + +/* + * @unittest: 1601 + * Returns CURLE_OK on success. + */ +CURLcode Curl_md5it(unsigned char *output, + const unsigned char *input, size_t len) +{ + CURLcode result; + my_md5_ctx ctx; + + result = my_md5_init(&ctx); + if(!result) { + do { + unsigned int ilen = (unsigned int)CURLMIN(len, UINT_MAX); + my_md5_update(&ctx, input, ilen); + input += ilen; + len -= ilen; + } while(len); + my_md5_final(output, &ctx); + } + return result; +} + +struct MD5_context *Curl_MD5_init(const struct MD5_params *md5params) +{ + struct MD5_context *ctxt; + + /* Create MD5 context */ + ctxt = curlx_malloc(sizeof(*ctxt)); + + if(!ctxt) + return ctxt; + + ctxt->md5_hashctx = curlx_malloc(md5params->md5_ctxtsize); + + if(!ctxt->md5_hashctx) { + curlx_free(ctxt); + return NULL; + } + + ctxt->md5_hash = md5params; + + if((*md5params->md5_init_func)(ctxt->md5_hashctx)) { + curlx_free(ctxt->md5_hashctx); + curlx_free(ctxt); + return NULL; + } + + return ctxt; +} + +CURLcode Curl_MD5_update(struct MD5_context *context, + const unsigned char *input, unsigned int len) +{ + (*context->md5_hash->md5_update_func)(context->md5_hashctx, input, len); + + return CURLE_OK; +} + +CURLcode Curl_MD5_final(struct MD5_context *context, unsigned char *result) +{ + (*context->md5_hash->md5_final_func)(result, context->md5_hashctx); + + curlx_free(context->md5_hashctx); + curlx_free(context); + + return CURLE_OK; +} + +#endif /* Using NTLM (without SSPI) || Digest */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/memdebug.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/memdebug.c new file mode 100644 index 0000000000..b6af2c6d35 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/memdebug.c @@ -0,0 +1,579 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef CURL_MEMDEBUG + +#include <stddef.h> /* for offsetof() */ + +#include "urldata.h" +#include "curl_threads.h" +#include "curlx/fopen.h" /* for CURLX_FOPEN_LOW(), CURLX_FREOPEN_LOW() */ + +#ifdef USE_BACKTRACE +#include <backtrace.h> +#endif + +struct memdebug { + size_t size; + union { + curl_off_t o; + double d; + void *p; + } mem[1]; + /* I am hoping this is the thing with the strictest alignment + * requirements. That also means we waste some space :-( */ +}; + +/* + * Note that these debug functions are simple and they are meant to remain so. + * For advanced analysis, record a log file and write perl scripts to analyze + * them! + * + * Do not use these with multi-threaded test programs! + */ + +FILE *curl_dbg_logfile = NULL; +static bool registered_cleanup = FALSE; /* atexit registered cleanup */ +static bool memlimit = FALSE; /* enable memory limit */ +static long memsize = 0; /* set number of mallocs allowed */ +#ifdef USE_BACKTRACE +static struct backtrace_state *btstate; +#endif + +static char membuf[10000]; +static size_t memwidx = 0; /* write index */ + +#ifdef USE_MUTEX +static bool dbg_mutex_init = 0; +static curl_mutex_t dbg_mutex; +#endif + +static bool curl_dbg_lock(void) +{ +#ifdef USE_MUTEX + if(dbg_mutex_init) { + Curl_mutex_acquire(&dbg_mutex); + return TRUE; + } +#endif + return FALSE; +} + +static void curl_dbg_unlock(bool was_locked) +{ +#ifdef USE_MUTEX + if(was_locked) + Curl_mutex_release(&dbg_mutex); +#else + (void)was_locked; +#endif +} + +static void curl_dbg_log_locked(const char *format, ...) CURL_PRINTF(1, 2); + +/* LeakSantizier (LSAN) calls _exit() instead of exit() when a leak is detected + on exit so the logfile must be closed explicitly or data could be lost. + Though _exit() does not call atexit handlers such as this, LSAN's call to + _exit() comes after the atexit handlers are called. curl/curl#6620 */ +static void curl_dbg_cleanup(void) +{ + bool locked = curl_dbg_lock(); + if(curl_dbg_logfile && + curl_dbg_logfile != stderr && + curl_dbg_logfile != stdout) { + if(memwidx) + fwrite(membuf, 1, memwidx, curl_dbg_logfile); + /* !checksrc! disable BANNEDFUNC 1 */ + fclose(curl_dbg_logfile); + } + curl_dbg_logfile = NULL; + curl_dbg_unlock(locked); +#ifdef USE_MUTEX + if(dbg_mutex_init) { + Curl_mutex_destroy(&dbg_mutex); + dbg_mutex_init = FALSE; + } +#endif +} + +#ifdef USE_BACKTRACE +static void error_bt_callback(void *data, const char *message, + int error_number) +{ + (void)data; + if(error_number == -1) + curl_dbg_log("compile with -g\n\n"); + else + curl_dbg_log("Backtrace error %d: %s\n", error_number, message); +} + +static int full_callback(void *data, uintptr_t pc, const char *pathname, + int line_number, const char *function) +{ + (void)data; + (void)pc; + if(pathname || function || line_number) + curl_dbg_log("BT %s:%d -- %s\n", pathname, line_number, function); + return 0; +} + +static void dump_bt(void) +{ + backtrace_full(btstate, 0, full_callback, error_bt_callback, NULL); +} +#else +#define dump_bt() /* nothing to do */ +#endif + +/* this sets the log filename */ +void curl_dbg_memdebug(const char *logname) +{ + if(!curl_dbg_logfile) { + if(logname && *logname) + curl_dbg_logfile = CURLX_FOPEN_LOW(logname, FOPEN_WRITETEXT); +#ifdef MEMDEBUG_LOG_SYNC + /* Flush the log file after every line so the log is not lost in a crash */ + if(curl_dbg_logfile) + setbuf(curl_dbg_logfile, (char *)NULL); +#endif + } +#ifdef USE_MUTEX + if(!dbg_mutex_init) { + dbg_mutex_init = TRUE; + Curl_mutex_init(&dbg_mutex); + } +#endif +#ifdef USE_BACKTRACE + btstate = backtrace_create_state(NULL, 0, error_bt_callback, NULL); +#endif + if(!registered_cleanup) + registered_cleanup = !atexit(curl_dbg_cleanup); +} + +/* This function sets the number of malloc() calls that should return + successfully! */ +void curl_dbg_memlimit(long limit) +{ + if(!memlimit) { + memlimit = TRUE; + memsize = limit; + } +} + +/* returns TRUE if this is not allowed! */ +static bool countcheck(const char *func, int line, const char *source) +{ + /* if source is NULL, then the call is made internally and this check + should not be made */ + if(memlimit && source) { + if(!memsize) { + /* log to file */ + curl_dbg_log("LIMIT %s:%d %s reached memlimit\n", source, line, func); + /* log to stderr also */ + curl_mfprintf(stderr, "LIMIT %s:%d %s reached memlimit\n", + source, line, func); + dump_bt(); + fflush(curl_dbg_logfile); /* because it might crash now */ + /* !checksrc! disable ERRNOVAR 1 */ + errno = ENOMEM; + return TRUE; /* RETURN ERROR! */ + } + else + memsize--; /* countdown */ + } + + return FALSE; /* allow this */ +} + +ALLOC_FUNC +void *curl_dbg_malloc(size_t wantedsize, int line, const char *source) +{ + struct memdebug *mem; + size_t size; + + DEBUGASSERT(wantedsize != 0); + + if(countcheck("malloc", line, source)) + return NULL; + + /* alloc at least 64 bytes */ + size = sizeof(struct memdebug) + wantedsize; + + mem = Curl_cmalloc(size); + if(mem) { + mem->size = wantedsize; + } + + if(source) + curl_dbg_log("MEM %s:%d malloc(%zu) = %p\n", + source, line, wantedsize, + mem ? (void *)mem->mem : (void *)0); + + return mem ? mem->mem : NULL; +} + +ALLOC_FUNC +void *curl_dbg_calloc(size_t wanted_elements, size_t wanted_size, + int line, const char *source) +{ + struct memdebug *mem; + size_t size, user_size; + + DEBUGASSERT(wanted_elements != 0); + DEBUGASSERT(wanted_size != 0); + + if(countcheck("calloc", line, source)) + return NULL; + + /* alloc at least 64 bytes */ + user_size = wanted_size * wanted_elements; + size = sizeof(struct memdebug) + user_size; + + mem = Curl_ccalloc(1, size); + if(mem) + mem->size = user_size; + + if(source) + curl_dbg_log("MEM %s:%d calloc(%zu,%zu) = %p\n", + source, line, wanted_elements, wanted_size, + mem ? (void *)mem->mem : (void *)0); + + return mem ? mem->mem : NULL; +} + +ALLOC_FUNC +char *curl_dbg_strdup(const char *str, int line, const char *source) +{ + char *mem; + size_t len; + + DEBUGASSERT(str); + + if(countcheck("strdup", line, source)) + return NULL; + + len = strlen(str) + 1; + + mem = curl_dbg_malloc(len, 0, NULL); /* NULL prevents logging */ + if(mem) + memcpy(mem, str, len); + + if(source) + curl_dbg_log("MEM %s:%d strdup(%p) (%zu) = %p\n", + source, line, (const void *)str, len, (const void *)mem); + + return mem; +} + +#if defined(_WIN32) && defined(UNICODE) +ALLOC_FUNC +wchar_t *curl_dbg_wcsdup(const wchar_t *str, int line, const char *source) +{ + wchar_t *mem; + size_t wsiz, bsiz; + + DEBUGASSERT(str); + + if(countcheck("wcsdup", line, source)) + return NULL; + + wsiz = wcslen(str) + 1; + bsiz = wsiz * sizeof(wchar_t); + + mem = curl_dbg_malloc(bsiz, 0, NULL); /* NULL prevents logging */ + if(mem) + memcpy(mem, str, bsiz); + + if(source) + curl_dbg_log("MEM %s:%d wcsdup(%p) (%zu) = %p\n", + source, line, (const void *)str, bsiz, (void *)mem); + + return mem; +} +#endif + +/* We provide a realloc() that accepts a NULL as pointer, which then + performs a malloc(). In order to work with ares. */ +void *curl_dbg_realloc(void *ptr, size_t wantedsize, + int line, const char *source) +{ + struct memdebug *mem = NULL; + bool was_locked; + + size_t size = sizeof(struct memdebug) + wantedsize; + + DEBUGASSERT(wantedsize != 0); + + if(countcheck("realloc", line, source)) + return NULL; + + /* need to realloc under lock, as we get out-of-order log + * entries otherwise, since another thread might alloc the + * memory released by realloc() before otherwise would log it. */ + was_locked = curl_dbg_lock(); +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:1684) + /* 1684: conversion from pointer to same-sized integral type */ +#endif + + if(ptr) + mem = (void *)((char *)ptr - offsetof(struct memdebug, mem)); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif + + mem = Curl_crealloc(mem, size); + if(source) + curl_dbg_log_locked("MEM %s:%d realloc(%p, %zu) = %p\n", + source, line, (void *)ptr, wantedsize, + mem ? (void *)mem->mem : (void *)0); + + curl_dbg_unlock(was_locked); + if(mem) { + mem->size = wantedsize; + return mem->mem; + } + + return NULL; +} + +void curl_dbg_free(void *ptr, int line, const char *source) +{ + if(ptr) { + struct memdebug *mem; + + if(source) + curl_dbg_log("MEM %s:%d free(%p)\n", source, line, (void *)ptr); + +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:1684) + /* 1684: conversion from pointer to same-sized integral type */ +#endif + + mem = (void *)((char *)ptr - offsetof(struct memdebug, mem)); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif + + /* free for real */ + Curl_cfree(mem); + } +} + +curl_socket_t curl_dbg_socket(int domain, int type, int protocol, + int line, const char *source) +{ + curl_socket_t sockfd; + + if(countcheck("socket", line, source)) + return CURL_SOCKET_BAD; + + /* !checksrc! disable BANNEDFUNC 1 */ + sockfd = socket(domain, type, protocol); + + if(source && (sockfd != CURL_SOCKET_BAD)) + curl_dbg_log("FD %s:%d socket() = %" FMT_SOCKET_T "\n", + source, line, sockfd); + + return sockfd; +} + +#ifdef HAVE_SOCKETPAIR +int curl_dbg_socketpair(int domain, int type, int protocol, + curl_socket_t socket_vector[2], + int line, const char *source) +{ + /* !checksrc! disable BANNEDFUNC 1 */ + int res = socketpair(domain, type, protocol, socket_vector); + + if(source && (res == 0)) + curl_dbg_log("FD %s:%d socketpair() = " + "%" FMT_SOCKET_T " %" FMT_SOCKET_T "\n", + source, line, socket_vector[0], socket_vector[1]); + + return res; +} +#endif + +curl_socket_t curl_dbg_accept(curl_socket_t s, void *saddr, void *saddrlen, + int line, const char *source) +{ + struct sockaddr *addr = (struct sockaddr *)saddr; + curl_socklen_t *addrlen = (curl_socklen_t *)saddrlen; + + /* !checksrc! disable BANNEDFUNC 1 */ + curl_socket_t sockfd = accept(s, addr, addrlen); + + if(source && (sockfd != CURL_SOCKET_BAD)) + curl_dbg_log("FD %s:%d accept() = %" FMT_SOCKET_T "\n", + source, line, sockfd); + + return sockfd; +} + +#ifdef HAVE_ACCEPT4 +curl_socket_t curl_dbg_accept4(curl_socket_t s, void *saddr, void *saddrlen, + int flags, + int line, const char *source) +{ + struct sockaddr *addr = (struct sockaddr *)saddr; + curl_socklen_t *addrlen = (curl_socklen_t *)saddrlen; + + /* !checksrc! disable BANNEDFUNC 1 */ + curl_socket_t sockfd = accept4(s, addr, addrlen, flags); + + if(source && (sockfd != CURL_SOCKET_BAD)) + curl_dbg_log("FD %s:%d accept() = %" FMT_SOCKET_T "\n", + source, line, sockfd); + + return sockfd; +} +#endif + +/* separate function to allow libcurl to mark a "faked" close */ +void curl_dbg_mark_sclose(curl_socket_t sockfd, int line, const char *source) +{ + if(source) + curl_dbg_log("FD %s:%d sclose(%" FMT_SOCKET_T ")\n", + source, line, sockfd); +} + +/* this is our own defined way to close sockets on *ALL* platforms */ +int curl_dbg_sclose(curl_socket_t sockfd, int line, const char *source) +{ + curl_dbg_mark_sclose(sockfd, line, source); + return CURL_SCLOSE(sockfd); +} + +ALLOC_FUNC +FILE *curl_dbg_fopen(const char *file, const char *mode, + int line, const char *source) +{ + FILE *res = CURLX_FOPEN_LOW(file, mode); + if(source) + curl_dbg_log("FILE %s:%d fopen(\"%s\",\"%s\") = %p\n", + source, line, file, mode, (void *)res); + + return res; +} + +ALLOC_FUNC +FILE *curl_dbg_freopen(const char *file, const char *mode, FILE *fh, + int line, const char *source) +{ + FILE *res = CURLX_FREOPEN_LOW(file, mode, fh); + if(source) + curl_dbg_log("FILE %s:%d freopen(\"%s\",\"%s\",%p) = %p\n", + source, line, file, mode, (void *)fh, (void *)res); + + return res; +} + +ALLOC_FUNC +FILE *curl_dbg_fdopen(int filedes, const char *mode, + int line, const char *source) +{ + FILE *res = CURLX_FDOPEN_LOW(filedes, mode); + if(source) + curl_dbg_log("FILE %s:%d fdopen(\"%d\",\"%s\") = %p\n", + source, line, filedes, mode, (void *)res); + return res; +} + +int curl_dbg_fclose(FILE *file, int line, const char *source) +{ + int res; + + DEBUGASSERT(file); + + if(source) + curl_dbg_log("FILE %s:%d fclose(%p)\n", source, line, (void *)file); + + /* !checksrc! disable BANNEDFUNC 1 */ + res = fclose(file); + + return res; +} + +static void curl_dbg_vlog(const char * const fmt, + va_list ap) CURL_PRINTF(1, 0); + +static void curl_dbg_vlog(const char * const fmt, va_list ap) +{ + char buf[1024]; + size_t nchars = curl_mvsnprintf(buf, sizeof(buf), fmt, ap); + + if(nchars > (int)sizeof(buf) - 1) + nchars = (int)sizeof(buf) - 1; + + if(nchars > 0) { + if(sizeof(membuf) - nchars < memwidx) { + /* flush */ + fwrite(membuf, 1, memwidx, curl_dbg_logfile); + fflush(curl_dbg_logfile); + memwidx = 0; + } + if(memwidx) { + /* the previous line ends with a newline */ + DEBUGASSERT(membuf[memwidx - 1] == '\n'); + } + memcpy(&membuf[memwidx], buf, nchars); + memwidx += nchars; + } +} + +static void curl_dbg_log_locked(const char *format, ...) +{ + va_list ap; + + if(!curl_dbg_logfile) + return; + + va_start(ap, format); + curl_dbg_vlog(format, ap); + va_end(ap); +} + +/* this does the writing to the memory tracking log file */ +void curl_dbg_log(const char *format, ...) +{ + bool was_locked; + va_list ap; + + if(!curl_dbg_logfile) + return; + + was_locked = curl_dbg_lock(); + va_start(ap, format); + curl_dbg_vlog(format, ap); + va_end(ap); + curl_dbg_unlock(was_locked); +} + +#endif /* CURL_MEMDEBUG */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/mime.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/mime.c new file mode 100644 index 0000000000..6004375765 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/mime.c @@ -0,0 +1,2282 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct Curl_easy; + +#include "mime.h" +#include "urldata.h" +#include "sendf.h" +#include "curl_trc.h" +#include "transfer.h" +#include "curlx/strdup.h" +#include "curlx/basename.h" +#include "curlx/strcopy.h" +#include "curlx/fopen.h" +#include "curlx/base64.h" + +#if !defined(CURL_DISABLE_MIME) && (!defined(CURL_DISABLE_HTTP) || \ + !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_IMAP)) + +#include "rand.h" +#include "slist.h" +#include "curlx/dynbuf.h" + +#define MAX_MIME_LEVELS 40 /* avoid deep nesting */ + +#define READ_ERROR ((size_t)-1) +#define STOP_FILLING ((size_t)-2) + +static size_t mime_subparts_read(char *buffer, size_t size, size_t nitems, + void *instream, bool *hasread, + size_t call_depth); +static curl_off_t mime_size(curl_mimepart *part); + +/* Quoted-printable character class table. + * + * We cannot rely on ctype functions since quoted-printable input data + * is assumed to be ASCII-compatible, even on non-ASCII platforms. */ +#define QP_OK 1 /* Can be represented by itself. */ +#define QP_SP 2 /* Space or tab. */ +#define QP_CR 3 /* Carriage return. */ +#define QP_LF 4 /* Line-feed. */ +static const unsigned char qp_class[] = { + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 - 07 */ + 0, QP_SP, QP_LF, 0, 0, QP_CR, 0, 0, /* 08 - 0F */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 17 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 18 - 1F */ + QP_SP, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 20 - 27 */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 28 - 2F */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 30 - 37 */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, 0 , QP_OK, QP_OK, /* 38 - 3F */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 40 - 47 */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 48 - 4F */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 50 - 57 */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 58 - 5F */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 60 - 67 */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 68 - 6F */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 70 - 77 */ + QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, 0, /* 78 - 7F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */ +}; + +/* Binary --> hexadecimal ASCII table. */ +static const char aschex[] = + "\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x41\x42\x43\x44\x45\x46"; + +#ifndef __VMS +#define filesize(name, stat_data) stat_data.st_size +#define fopen_read curlx_fopen + +#else + +#include <fabdef.h> +/* + * get_vms_file_size does what it takes to get the real size of the file + * + * For fixed files, find out the size of the EOF block and adjust. + * + * For all others, have to read the entire file in, discarding the contents. + * Most posted text files will be small, and binary files like zlib archives + * and CD/DVD images should be either a STREAM_LF format or a fixed format. + * + */ +curl_off_t VmsRealFileSize(const char *name, const curlx_struct_stat *stat_buf) +{ + char buffer[8192]; + curl_off_t count; + int ret_stat; + FILE *file; + + file = curlx_fopen(name, FOPEN_READTEXT); /* VMS */ + if(!file) + return 0; + + count = 0; + ret_stat = 1; + while(ret_stat > 0) { + ret_stat = fread(buffer, 1, sizeof(buffer), file); + if(ret_stat) + count += ret_stat; + } + curlx_fclose(file); + + return count; +} + +/* + * + * VmsSpecialSize checks to see if the stat st_size can be trusted and + * if not to call a routine to get the correct size. + * + */ +static curl_off_t VmsSpecialSize(const char *name, + const curlx_struct_stat *stat_buf) +{ + switch(stat_buf->st_fab_rfm) { + case FAB$C_VAR: + case FAB$C_VFC: + return VmsRealFileSize(name, stat_buf); + break; + default: + return stat_buf->st_size; + } +} + +#define filesize(name, stat_data) VmsSpecialSize(name, &stat_data) + +/* + * vmsfopenread + * + * For upload to work as expected on VMS, different optional + * parameters must be added to the fopen command based on + * record format of the file. + * + */ +static FILE *vmsfopenread(const char *file, const char *mode) +{ + curlx_struct_stat statbuf; + int res = curlx_stat(file, &statbuf); + + if(res != -1) { + switch(statbuf.st_fab_rfm) { + case FAB$C_VAR: + case FAB$C_VFC: + case FAB$C_STMCR: + return curlx_fopen(file, FOPEN_READTEXT); /* VMS */ + break; + default: + return curlx_fopen(file, FOPEN_READTEXT, "rfm=stmlf", "ctx=stm"); + } + } + return NULL; +} + +#define fopen_read vmsfopenread +#endif /* !__VMS */ + +/* Set readback state. */ +static void mimesetstate(struct mime_state *state, + enum mimestate tok, void *ptr) +{ + state->state = tok; + state->ptr = ptr; + state->offset = 0; +} + +/* Escape header string into allocated memory. */ +static char *escape_string(struct Curl_easy *data, + const char *src, enum mimestrategy strategy) +{ + CURLcode result; + struct dynbuf db; + const char * const *table; + const char * const *p; + /* replace first character by rest of string. */ + static const char * const mimetable[] = { + "\\\\\\", + "\"\\\"", + NULL + }; + /* WHATWG HTML living standard 4.10.21.8 2 specifies: + For field names and filenames for file fields, the result of the + encoding in the previous bullet point must be escaped by replacing + any 0x0A (LF) bytes with the byte sequence `%0A`, 0x0D (CR) with `%0D` + and 0x22 (") with `%22`. + The user agent must not perform any other escapes. */ + static const char * const formtable[] = { + "\"%22", + "\r%0D", + "\n%0A", + NULL + }; + + table = formtable; + /* data can be NULL when this function is called indirectly from + curl_formget(). */ + if(strategy == MIMESTRATEGY_MAIL || (data && data->set.mime_formescape)) + table = mimetable; + + curlx_dyn_init(&db, CURL_MAX_INPUT_LENGTH); + + for(result = curlx_dyn_addn(&db, STRCONST("")); !result && *src; src++) { + for(p = table; *p && **p != *src; p++) + ; + + if(*p) + result = curlx_dyn_add(&db, *p + 1); + else + result = curlx_dyn_addn(&db, src, 1); + } + + return curlx_dyn_ptr(&db); +} + +/* Check if header matches. */ +static char *match_header(struct curl_slist *hdr, const char *lbl, size_t len) +{ + char *value = NULL; + + if(curl_strnequal(hdr->data, lbl, len) && hdr->data[len] == ':') + for(value = hdr->data + len + 1; *value == ' '; value++) + ; + return value; +} + +/* Get a header from an slist. */ +static char *search_header(struct curl_slist *hdrlist, + const char *hdr, size_t len) +{ + char *value = NULL; + + for(; !value && hdrlist; hdrlist = hdrlist->next) + value = match_header(hdrlist, hdr, len); + + return value; +} + +static char *strippath(const char *fullfile) +{ + char *filename; + char *base; + filename = curlx_strdup(fullfile); /* duplicate since basename() may ruin + the buffer it works on */ + if(!filename) + return NULL; + base = curlx_strdup(curlx_basename(filename)); + + curlx_free(filename); /* free temporary buffer */ + + return base; /* returns an allocated string or NULL ! */ +} + +/* Initialize data encoder state. */ +static void cleanup_encoder_state(struct mime_encoder_state *p) +{ + p->pos = 0; + p->bufbeg = 0; + p->bufend = 0; +} + +/* Dummy encoder. This is used for 8-bit and binary content encodings. */ +static size_t encoder_nop_read(char *buffer, size_t size, bool ateof, + struct curl_mimepart *part) +{ + struct mime_encoder_state *st = &part->encstate; + size_t insize = st->bufend - st->bufbeg; + + (void)ateof; + + if(!size) + return STOP_FILLING; + + if(size > insize) + size = insize; + + if(size) + memcpy(buffer, st->buf + st->bufbeg, size); + + st->bufbeg += size; + return size; +} + +static curl_off_t encoder_nop_size(curl_mimepart *part) +{ + return part->datasize; +} + +/* 7-bit encoder: the encoder is a data validity check. */ +static size_t encoder_7bit_read(char *buffer, size_t size, bool ateof, + curl_mimepart *part) +{ + struct mime_encoder_state *st = &part->encstate; + size_t cursize = st->bufend - st->bufbeg; + + (void)ateof; + + if(!size) + return STOP_FILLING; + + if(size > cursize) + size = cursize; + + for(cursize = 0; cursize < size; cursize++) { + *buffer = st->buf[st->bufbeg]; + if(*buffer++ & 0x80) + return cursize ? cursize : READ_ERROR; + st->bufbeg++; + } + + return cursize; +} + +/* Base64 content encoder. */ +static size_t encoder_base64_read(char *buffer, size_t size, bool ateof, + curl_mimepart *part) +{ + struct mime_encoder_state *st = &part->encstate; + size_t cursize = 0; + int i; + char *ptr = buffer; + + while(st->bufbeg < st->bufend) { + /* Line full ? */ + if(st->pos > MAX_ENCODED_LINE_LENGTH - 4) { + /* Yes, we need 2 characters for CRLF. */ + if(size < 2) { + if(!cursize) + return STOP_FILLING; + break; + } + *ptr++ = '\r'; + *ptr++ = '\n'; + st->pos = 0; + cursize += 2; + size -= 2; + } + + /* Be sure there is enough space and input data for a base64 group. */ + if(size < 4) { + if(!cursize) + return STOP_FILLING; + break; + } + if(st->bufend - st->bufbeg < 3) + break; + + /* Encode three bytes as four characters. */ + i = st->buf[st->bufbeg++] & 0xFF; + i = (i << 8) | (st->buf[st->bufbeg++] & 0xFF); + i = (i << 8) | (st->buf[st->bufbeg++] & 0xFF); + *ptr++ = curlx_base64encdec[(i >> 18) & 0x3F]; + *ptr++ = curlx_base64encdec[(i >> 12) & 0x3F]; + *ptr++ = curlx_base64encdec[(i >> 6) & 0x3F]; + *ptr++ = curlx_base64encdec[i & 0x3F]; + cursize += 4; + st->pos += 4; + size -= 4; + } + + /* If at eof, we have to flush the buffered data. */ + if(ateof) { + if(size < 4) { + if(!cursize) + return STOP_FILLING; + } + else { + /* Buffered data size can only be 0, 1 or 2. */ + ptr[2] = ptr[3] = '='; + i = 0; + + /* If there is buffered data */ + if(st->bufend != st->bufbeg) { + + if(st->bufend - st->bufbeg == 2) + i = (st->buf[st->bufbeg + 1] & 0xFF) << 8; + + i |= (st->buf[st->bufbeg] & 0xFF) << 16; + ptr[0] = curlx_base64encdec[(i >> 18) & 0x3F]; + ptr[1] = curlx_base64encdec[(i >> 12) & 0x3F]; + if(++st->bufbeg != st->bufend) { + ptr[2] = curlx_base64encdec[(i >> 6) & 0x3F]; + st->bufbeg++; + } + cursize += 4; + st->pos += 4; + } + } + } + + return cursize; +} + +/* The maximum input size that does not cause an overflow. */ +#define BASE64_MAX_INPUT_SIZE \ + (((CURL_OFF_T_MAX / (MAX_ENCODED_LINE_LENGTH + 2)) * \ + MAX_ENCODED_LINE_LENGTH / 4) * 3 - 3) + +static curl_off_t encoder_base64_size(curl_mimepart *part) +{ + curl_off_t size = part->datasize; + + if(size <= 0) + return size; /* Unknown size or no data. */ + + /* Prevent integer overflows */ + if(size > BASE64_MAX_INPUT_SIZE) + return -1; + + /* Compute base64 character count. */ + size = 4 * (1 + ((size - 1) / 3)); + + /* Effective character count must include CRLFs. */ + return size + (2 * ((size - 1) / MAX_ENCODED_LINE_LENGTH)); +} + +/* Quoted-printable lookahead. + * + * Check if a CRLF or end of data is in input buffer at current position + n. + * Return -1 if more data needed, 1 if CRLF or end of data, else 0. + */ +static int qp_lookahead_eol(struct mime_encoder_state *st, int ateof, size_t n) +{ + n += st->bufbeg; + if(n >= st->bufend && ateof) + return 1; + if(n + 2 > st->bufend) + return ateof ? 0 : -1; + if(qp_class[st->buf[n] & 0xFF] == QP_CR && + qp_class[st->buf[n + 1] & 0xFF] == QP_LF) + return 1; + return 0; +} + +/* Quoted-printable encoder. */ +static size_t encoder_qp_read(char *buffer, size_t size, bool ateof, + curl_mimepart *part) +{ + struct mime_encoder_state *st = &part->encstate; + char *ptr = buffer; + size_t cursize = 0; + int softlinebreak; + char buf[4]; + + /* On all platforms, input is supposed to be ASCII compatible: for this + reason, we use hexadecimal ASCII codes in this function rather than + character constants that can be interpreted as non-ASCII on some + platforms. Preserve ASCII encoding on output too. */ + while(st->bufbeg < st->bufend) { + size_t len = 1; + size_t consumed = 1; + int i = (unsigned char)st->buf[st->bufbeg]; + buf[0] = (char)i; + buf[1] = aschex[(i >> 4) & 0xF]; + buf[2] = aschex[i & 0xF]; + + switch(qp_class[st->buf[st->bufbeg] & 0xFF]) { + case QP_OK: /* Not a special character. */ + break; + case QP_SP: /* Space or tab. */ + /* Spacing must be escaped if followed by CRLF. */ + switch(qp_lookahead_eol(st, ateof, 1)) { + case -1: /* More input data needed. */ + return cursize; + case 0: /* No encoding needed. */ + break; + default: /* CRLF after space or tab. */ + buf[0] = '\x3D'; /* '=' */ + len = 3; + break; + } + break; + case QP_CR: /* Carriage return. */ + /* If followed by a line-feed, output the CRLF pair. + Else escape it. */ + switch(qp_lookahead_eol(st, ateof, 0)) { + case -1: /* Need more data. */ + return cursize; + case 1: /* CRLF found. */ + buf[len++] = '\x0A'; /* Append '\n'. */ + consumed = 2; + break; + default: /* Not followed by LF: escape. */ + buf[0] = '\x3D'; /* '=' */ + len = 3; + break; + } + break; + default: /* Character must be escaped. */ + buf[0] = '\x3D'; /* '=' */ + len = 3; + break; + } + + /* Be sure the encoded character fits within maximum line length. */ + if(buf[len - 1] != '\x0A') { /* '\n' */ + softlinebreak = st->pos + len > MAX_ENCODED_LINE_LENGTH; + if(!softlinebreak && st->pos + len == MAX_ENCODED_LINE_LENGTH) { + /* We may use the current line only if end of data or followed by + a CRLF. */ + switch(qp_lookahead_eol(st, ateof, consumed)) { + case -1: /* Need more data. */ + return cursize; + case 0: /* Not followed by a CRLF. */ + softlinebreak = 1; + break; + } + } + if(softlinebreak) { + curlx_strcopy(buf, sizeof(buf), STRCONST("\x3D\x0D\x0A")); /* =\r\n */ + len = 3; + consumed = 0; + } + } + + /* If the output buffer would overflow, do not store. */ + if(len > size) { + if(!cursize) + return STOP_FILLING; + break; + } + + /* Append to output buffer. */ + memcpy(ptr, buf, len); + cursize += len; + ptr += len; + size -= len; + st->pos += len; + if(buf[len - 1] == '\x0A') /* '\n' */ + st->pos = 0; + st->bufbeg += consumed; + } + + return cursize; +} + +static curl_off_t encoder_qp_size(curl_mimepart *part) +{ + /* Determining the size can only be done by reading the data: unless the + data size is 0, we return it as unknown (-1). */ + return part->datasize ? -1 : 0; +} + +/* In-memory data callbacks. */ +/* Argument is a pointer to the mime part. */ +static size_t mime_mem_read(char *buffer, size_t size, size_t nitems, + void *instream) +{ + curl_mimepart *part = (curl_mimepart *)instream; + size_t sz = curlx_sotouz(part->datasize - part->state.offset); + (void)size; /* Always 1 */ + + if(!nitems) + return STOP_FILLING; + + if(sz > nitems) + sz = nitems; + + if(sz) + memcpy(buffer, part->data + curlx_sotouz(part->state.offset), sz); + + return sz; +} + +static int mime_mem_seek(void *instream, curl_off_t offset, int whence) +{ + curl_mimepart *part = (curl_mimepart *)instream; + + switch(whence) { + case SEEK_CUR: + offset += part->state.offset; + break; + case SEEK_END: + offset += part->datasize; + break; + } + + if(offset < 0 || offset > part->datasize) + return CURL_SEEKFUNC_FAIL; + + part->state.offset = offset; + return CURL_SEEKFUNC_OK; +} + +static void mime_mem_free(void *ptr) +{ + curlx_safefree(((curl_mimepart *)ptr)->data); +} + +/* Named file callbacks. */ +/* Argument is a pointer to the mime part. */ +static bool mime_open_file(curl_mimepart *part) +{ + /* Open a MIMEKIND_FILE part. */ + + if(part->fp) + return FALSE; + part->fp = fopen_read(part->data, "rb"); + return part->fp ? FALSE : TRUE; +} + +static size_t mime_file_read(char *buffer, size_t size, size_t nitems, + void *instream) +{ + curl_mimepart *part = (curl_mimepart *)instream; + + if(!nitems) + return STOP_FILLING; + + if(mime_open_file(part)) + return READ_ERROR; + + return fread(buffer, size, nitems, part->fp); +} + +static int mime_file_seek(void *instream, curl_off_t offset, int whence) +{ + curl_mimepart *part = (curl_mimepart *)instream; + + if(whence == SEEK_SET && !offset && !part->fp) + return CURL_SEEKFUNC_OK; /* Not open: implicitly already at BOF. */ + + if(mime_open_file(part)) + return CURL_SEEKFUNC_FAIL; + + return curlx_fseek(part->fp, offset, whence) ? + CURL_SEEKFUNC_CANTSEEK : CURL_SEEKFUNC_OK; +} + +static void mime_file_free(void *ptr) +{ + curl_mimepart *part = (curl_mimepart *)ptr; + + if(part->fp) { + curlx_fclose(part->fp); + part->fp = NULL; + } + curlx_safefree(part->data); +} + +/* Subparts callbacks. */ +/* Argument is a pointer to the mime structure. */ + +/* Readback a byte string segment. */ +static size_t readback_bytes(struct mime_state *state, + char *buffer, size_t bufsize, + const char *bytes, size_t numbytes, + const char *trail, size_t traillen) +{ + size_t sz; + size_t offset = curlx_sotouz(state->offset); + + if(numbytes > offset) { + sz = numbytes - offset; + bytes += offset; + } + else { + sz = offset - numbytes; + if(sz >= traillen) + return 0; + bytes = trail + sz; + sz = traillen - sz; + } + + if(sz > bufsize) + sz = bufsize; + + memcpy(buffer, bytes, sz); + state->offset += sz; + return sz; +} + +/* Read a non-encoded part content. */ + +static size_t read_part_content(curl_mimepart *part, char *buffer, + size_t bufsize, bool *hasread, + size_t call_depth) +{ + size_t sz = 0; + + if(++call_depth > MAX_MIME_LEVELS) + return READ_ERROR; + + switch(part->lastreadstatus) { + case 0: + case CURL_READFUNC_ABORT: + case CURL_READFUNC_PAUSE: + case READ_ERROR: + return part->lastreadstatus; + default: + break; + } + + /* If we can determine we are at end of part data, spare a read. */ + if(part->datasize != (curl_off_t)-1 && + part->state.offset >= part->datasize) { + /* sz is already zero. */ + } + else { + switch(part->kind) { + case MIMEKIND_MULTIPART: + /* + * Cannot be processed as other kinds since read function requires + * an additional parameter and is highly recursive. + */ + sz = mime_subparts_read(buffer, 1, bufsize, part->arg, hasread, + call_depth); + break; + case MIMEKIND_FILE: + if(part->fp && feof(part->fp)) + break; /* At EOF. */ + FALLTHROUGH(); + default: + if(part->readfunc) { + if(!(part->flags & MIME_FAST_READ)) { + if(*hasread) + return STOP_FILLING; + *hasread = TRUE; + } + sz = part->readfunc(buffer, 1, bufsize, part->arg); + } + break; + } + } + + switch(sz) { + case STOP_FILLING: + break; + case 0: + case CURL_READFUNC_ABORT: + case CURL_READFUNC_PAUSE: + case READ_ERROR: + part->lastreadstatus = sz; + break; + default: + part->state.offset += sz; + part->lastreadstatus = sz; + break; + } + + return sz; +} + +/* Read and encode part content. */ +static size_t read_encoded_part_content(curl_mimepart *part, char *buffer, + size_t bufsize, bool *hasread, + size_t call_depth) +{ + struct mime_encoder_state *st = &part->encstate; + size_t cursize = 0; + size_t sz; + bool ateof = FALSE; + + if(++call_depth > MAX_MIME_LEVELS) + return READ_ERROR; + + for(;;) { + if(st->bufbeg < st->bufend || ateof) { + /* Encode buffered data. */ + sz = part->encoder->encodefunc(buffer, bufsize, ateof, part); + switch(sz) { + case 0: + if(ateof) + return cursize; + break; + case READ_ERROR: + case STOP_FILLING: + return cursize ? cursize : sz; + default: + cursize += sz; + buffer += sz; + bufsize -= sz; + continue; + } + } + + /* We need more data in input buffer. */ + if(st->bufbeg) { + size_t len = st->bufend - st->bufbeg; + + if(len) + memmove(st->buf, st->buf + st->bufbeg, len); + st->bufbeg = 0; + st->bufend = len; + } + if(st->bufend >= sizeof(st->buf)) + return cursize ? cursize : READ_ERROR; /* Buffer full. */ + sz = read_part_content(part, st->buf + st->bufend, + sizeof(st->buf) - st->bufend, hasread, call_depth); + switch(sz) { + case 0: + ateof = TRUE; + break; + case CURL_READFUNC_ABORT: + case CURL_READFUNC_PAUSE: + case READ_ERROR: + case STOP_FILLING: + return cursize ? cursize : sz; + default: + st->bufend += sz; + break; + } + } + + /* NOTREACHED */ +} + +/* Readback a mime part. */ +static size_t readback_part(curl_mimepart *part, + char *buffer, size_t bufsize, bool *hasread, + size_t call_depth) +{ + size_t cursize = 0; + + if(++call_depth > MAX_MIME_LEVELS) + return READ_ERROR; + + /* Readback from part. */ + while(bufsize) { + size_t sz = 0; + struct curl_slist *hdr = (struct curl_slist *)part->state.ptr; + switch(part->state.state) { + case MIMESTATE_BEGIN: + mimesetstate(&part->state, + (part->flags & MIME_BODY_ONLY) ? + MIMESTATE_BODY : MIMESTATE_CURLHEADERS, + part->curlheaders); + break; + case MIMESTATE_USERHEADERS: + if(!hdr) { + mimesetstate(&part->state, MIMESTATE_EOH, NULL); + break; + } + if(match_header(hdr, "Content-Type", 12)) { + mimesetstate(&part->state, MIMESTATE_USERHEADERS, hdr->next); + break; + } + FALLTHROUGH(); + case MIMESTATE_CURLHEADERS: + if(!hdr) + mimesetstate(&part->state, MIMESTATE_USERHEADERS, part->userheaders); + else { + sz = readback_bytes(&part->state, buffer, bufsize, + hdr->data, strlen(hdr->data), STRCONST("\r\n")); + if(!sz) + mimesetstate(&part->state, part->state.state, hdr->next); + } + break; + case MIMESTATE_EOH: + sz = readback_bytes(&part->state, buffer, bufsize, STRCONST("\r\n"), + STRCONST("")); + if(!sz) + mimesetstate(&part->state, MIMESTATE_BODY, NULL); + break; + case MIMESTATE_BODY: + cleanup_encoder_state(&part->encstate); + mimesetstate(&part->state, MIMESTATE_CONTENT, NULL); + break; + case MIMESTATE_CONTENT: + if(part->encoder) + sz = read_encoded_part_content(part, buffer, bufsize, hasread, + call_depth); + else + sz = read_part_content(part, buffer, bufsize, hasread, call_depth); + switch(sz) { + case 0: + mimesetstate(&part->state, MIMESTATE_END, NULL); + /* Try sparing open file descriptors. */ + if(part->kind == MIMEKIND_FILE && part->fp) { + curlx_fclose(part->fp); + part->fp = NULL; + } + FALLTHROUGH(); + case CURL_READFUNC_ABORT: + case CURL_READFUNC_PAUSE: + case READ_ERROR: + case STOP_FILLING: + return cursize ? cursize : sz; + } + break; + case MIMESTATE_END: + return cursize; + default: + break; /* Other values not in part state. */ + } + + /* Bump buffer and counters according to read size. */ + cursize += sz; + buffer += sz; + bufsize -= sz; + } + + return cursize; +} + +/* Readback from mime. Warning: not a read callback function. */ +static size_t mime_subparts_read(char *buffer, size_t size, size_t nitems, + void *instream, bool *hasread, + size_t call_depth) +{ + curl_mime *mime = (curl_mime *)instream; + size_t cursize = 0; + (void)size; /* Always 1 */ + + if(++call_depth > MAX_MIME_LEVELS) + return READ_ERROR; + + while(nitems) { + size_t sz = 0; + curl_mimepart *part = mime->state.ptr; + switch(mime->state.state) { + case MIMESTATE_BEGIN: + case MIMESTATE_BODY: + mimesetstate(&mime->state, MIMESTATE_BOUNDARY1, mime->firstpart); + /* The first boundary always follows the header termination empty line, + so is always preceded by a CRLF. We can then spare 2 characters + by skipping the leading CRLF in boundary. */ + mime->state.offset += 2; + break; + case MIMESTATE_BOUNDARY1: + sz = readback_bytes(&mime->state, buffer, nitems, STRCONST("\r\n--"), + STRCONST("")); + if(!sz) + mimesetstate(&mime->state, MIMESTATE_BOUNDARY2, part); + break; + case MIMESTATE_BOUNDARY2: + if(part) + sz = readback_bytes(&mime->state, buffer, nitems, mime->boundary, + MIME_BOUNDARY_LEN, STRCONST("\r\n")); + else + sz = readback_bytes(&mime->state, buffer, nitems, mime->boundary, + MIME_BOUNDARY_LEN, STRCONST("--\r\n")); + if(!sz) { + mimesetstate(&mime->state, MIMESTATE_CONTENT, part); + } + break; + case MIMESTATE_CONTENT: + if(!part) { + mimesetstate(&mime->state, MIMESTATE_END, NULL); + break; + } + sz = readback_part(part, buffer, nitems, hasread, call_depth); + switch(sz) { + case CURL_READFUNC_ABORT: + case CURL_READFUNC_PAUSE: + case READ_ERROR: + case STOP_FILLING: + return cursize ? cursize : sz; + case 0: + mimesetstate(&mime->state, MIMESTATE_BOUNDARY1, part->nextpart); + break; + } + break; + case MIMESTATE_END: + return cursize; + default: + break; /* other values not used in mime state. */ + } + + /* Bump buffer and counters according to read size. */ + cursize += sz; + buffer += sz; + nitems -= sz; + } + + return cursize; +} + +static int mime_part_rewind(curl_mimepart *part) +{ + int res = CURL_SEEKFUNC_OK; + enum mimestate targetstate = MIMESTATE_BEGIN; + + if(part->flags & MIME_BODY_ONLY) + targetstate = MIMESTATE_BODY; + cleanup_encoder_state(&part->encstate); + if(part->state.state > targetstate) { + res = CURL_SEEKFUNC_CANTSEEK; + if(part->seekfunc) { + res = part->seekfunc(part->arg, (curl_off_t)0, SEEK_SET); + switch(res) { + case CURL_SEEKFUNC_OK: + case CURL_SEEKFUNC_FAIL: + case CURL_SEEKFUNC_CANTSEEK: + break; + case -1: /* For fseek() error. */ + res = CURL_SEEKFUNC_CANTSEEK; + break; + default: + res = CURL_SEEKFUNC_FAIL; + break; + } + } + } + + if(res == CURL_SEEKFUNC_OK) + mimesetstate(&part->state, targetstate, NULL); + + part->lastreadstatus = 1; /* Successful read status. */ + return res; +} + +static int mime_subparts_seek(void *instream, curl_off_t offset, int whence) +{ + curl_mime *mime = (curl_mime *)instream; + curl_mimepart *part; + int rc = CURL_SEEKFUNC_OK; + + if(whence != SEEK_SET || offset) + return CURL_SEEKFUNC_CANTSEEK; /* Only support full rewind. */ + + if(mime->state.state == MIMESTATE_BEGIN) + return CURL_SEEKFUNC_OK; /* Already rewound. */ + + for(part = mime->firstpart; part; part = part->nextpart) { + int res = mime_part_rewind(part); + if(res != CURL_SEEKFUNC_OK) + rc = res; + } + + if(rc == CURL_SEEKFUNC_OK) + mimesetstate(&mime->state, MIMESTATE_BEGIN, NULL); + + return rc; +} + +/* Release part content. */ +static void cleanup_part_content(curl_mimepart *part) +{ + if(part->freefunc) + part->freefunc(part->arg); + + part->readfunc = NULL; + part->seekfunc = NULL; + part->freefunc = NULL; + part->arg = (void *)part; /* Defaults to part itself. */ + part->data = NULL; + part->fp = NULL; + part->datasize = (curl_off_t)0; /* No size yet. */ + cleanup_encoder_state(&part->encstate); + part->kind = MIMEKIND_NONE; + part->flags &= ~(unsigned int)MIME_FAST_READ; + part->lastreadstatus = 1; /* Successful read status. */ + part->state.state = MIMESTATE_BEGIN; +} + +static void mime_subparts_free(void *ptr) +{ + curl_mime *mime = (curl_mime *)ptr; + + if(mime && mime->parent) { + mime->parent->freefunc = NULL; /* Be sure we will not be called again. */ + cleanup_part_content(mime->parent); /* Avoid dangling pointer in part. */ + } + curl_mime_free(mime); +} + +/* Do not free subparts: unbind them. This is used for the top level only. */ +static void mime_subparts_unbind(void *ptr) +{ + curl_mime *mime = (curl_mime *)ptr; + + if(mime && mime->parent) { + mime->parent->freefunc = NULL; /* Be sure we will not be called again. */ + cleanup_part_content(mime->parent); /* Avoid dangling pointer in part. */ + mime->parent = NULL; + } +} + +void Curl_mime_cleanpart(curl_mimepart *part) +{ + if(part) { + cleanup_part_content(part); + curl_slist_free_all(part->curlheaders); + if(part->flags & MIME_USERHEADERS_OWNER) + curl_slist_free_all(part->userheaders); + curlx_safefree(part->mimetype); + curlx_safefree(part->name); + curlx_safefree(part->filename); + Curl_mime_initpart(part); + } +} + +/* Recursively delete a mime handle and its parts. */ +void curl_mime_free(curl_mime *mime) +{ + curl_mimepart *part; + + if(mime) { + mime_subparts_unbind(mime); /* Be sure it is not referenced anymore. */ + while(mime->firstpart) { + part = mime->firstpart; + mime->firstpart = part->nextpart; + Curl_mime_cleanpart(part); + curlx_free(part); + } + curlx_free(mime); + } +} + +CURLcode Curl_mime_duppart(struct Curl_easy *data, + curl_mimepart *dst, const curl_mimepart *src) +{ + curl_mime *mime; + curl_mimepart *d; + const curl_mimepart *s; + CURLcode result = CURLE_OK; + + DEBUGASSERT(dst); + + /* Duplicate content. */ + switch(src->kind) { + case MIMEKIND_NONE: + break; + case MIMEKIND_DATA: + result = curl_mime_data(dst, src->data, (size_t)src->datasize); + break; + case MIMEKIND_FILE: + result = curl_mime_filedata(dst, src->data); + /* Do not abort duplication if file is not readable. */ + if(result == CURLE_READ_ERROR) + result = CURLE_OK; + break; + case MIMEKIND_CALLBACK: + result = curl_mime_data_cb(dst, src->datasize, src->readfunc, + src->seekfunc, src->freefunc, src->arg); + break; + case MIMEKIND_MULTIPART: + /* No one knows about the cloned subparts, thus always attach ownership + to the part. */ + mime = curl_mime_init(data); + result = mime ? curl_mime_subparts(dst, mime) : CURLE_OUT_OF_MEMORY; + + /* Duplicate subparts. */ + for(s = ((curl_mime *)src->arg)->firstpart; !result && s; + s = s->nextpart) { + d = curl_mime_addpart(mime); + result = d ? Curl_mime_duppart(data, d, s) : CURLE_OUT_OF_MEMORY; + } + break; + default: /* Invalid kind: should not occur. */ + DEBUGF(infof(data, "invalid MIMEKIND* attempt")); + result = CURLE_BAD_FUNCTION_ARGUMENT; /* Internal error? */ + break; + } + + /* Duplicate headers. */ + if(!result && src->userheaders) { + struct curl_slist *hdrs = Curl_slist_duplicate(src->userheaders); + + if(!hdrs) + result = CURLE_OUT_OF_MEMORY; + else { + /* No one but this procedure knows about the new header list, + so always take ownership. */ + result = curl_mime_headers(dst, hdrs, TRUE); + if(result) + curl_slist_free_all(hdrs); + } + } + + if(!result) { + /* Duplicate other fields. */ + dst->encoder = src->encoder; + result = curl_mime_type(dst, src->mimetype); + } + if(!result) + result = curl_mime_name(dst, src->name); + if(!result) + result = curl_mime_filename(dst, src->filename); + + /* If an error occurred, rollback. */ + if(result) + Curl_mime_cleanpart(dst); + + return result; +} + +/* + * Mime build functions. + */ + +/* Create a mime handle. */ +curl_mime *curl_mime_init(void *easy) +{ + curl_mime *mime = curlx_malloc(sizeof(*mime)); + + if(mime) { + mime->parent = NULL; + mime->firstpart = NULL; + mime->lastpart = NULL; + + memset(mime->boundary, '-', MIME_BOUNDARY_DASHES); + if(Curl_rand_alnum(easy, + (unsigned char *)&mime->boundary[MIME_BOUNDARY_DASHES], + MIME_RAND_BOUNDARY_CHARS + 1)) { + /* failed to get random separator, bail out */ + curlx_free(mime); + return NULL; + } + mimesetstate(&mime->state, MIMESTATE_BEGIN, NULL); + } + + return mime; +} + +/* Initialize a mime part. */ +void Curl_mime_initpart(curl_mimepart *part) +{ + memset(part, 0, sizeof(*part)); + part->lastreadstatus = 1; /* Successful read status. */ + mimesetstate(&part->state, MIMESTATE_BEGIN, NULL); +} + +/* Create a mime part and append it to a mime handle's part list. */ +curl_mimepart *curl_mime_addpart(curl_mime *mime) +{ + curl_mimepart *part; + + if(!mime) + return NULL; + + part = curlx_malloc(sizeof(*part)); + + if(part) { + Curl_mime_initpart(part); + part->parent = mime; + + if(mime->lastpart) + mime->lastpart->nextpart = part; + else + mime->firstpart = part; + + mime->lastpart = part; + } + + return part; +} + +/* Set mime part name. */ +CURLcode curl_mime_name(curl_mimepart *part, const char *name) +{ + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + curlx_safefree(part->name); + + if(name) { + part->name = curlx_strdup(name); + if(!part->name) + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +/* Set mime part remote filename. */ +CURLcode curl_mime_filename(curl_mimepart *part, const char *filename) +{ + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + curlx_safefree(part->filename); + + if(filename) { + part->filename = curlx_strdup(filename); + if(!part->filename) + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +/* Set mime part content from memory data. */ +CURLcode curl_mime_data(curl_mimepart *part, const char *data, size_t datasize) +{ + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + cleanup_part_content(part); + + if(data) { + if(datasize == CURL_ZERO_TERMINATED) + datasize = strlen(data); + + part->data = curlx_memdup0(data, datasize); + if(!part->data) + return CURLE_OUT_OF_MEMORY; + + part->datasize = datasize; + part->readfunc = mime_mem_read; + part->seekfunc = mime_mem_seek; + part->freefunc = mime_mem_free; + part->flags |= MIME_FAST_READ; + part->kind = MIMEKIND_DATA; + } + + return CURLE_OK; +} + +/* Set mime part content from named local file. */ +CURLcode curl_mime_filedata(curl_mimepart *part, const char *filename) +{ + CURLcode result = CURLE_OK; + + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + cleanup_part_content(part); + + if(filename) { + char *base; + curlx_struct_stat sbuf; + + if(curlx_stat(filename, &sbuf)) + result = CURLE_READ_ERROR; + else { + part->data = curlx_strdup(filename); + if(!part->data) + result = CURLE_OUT_OF_MEMORY; + else { + part->datasize = -1; + if(S_ISREG(sbuf.st_mode)) { + part->datasize = filesize(filename, sbuf); + part->seekfunc = mime_file_seek; + } + + part->readfunc = mime_file_read; + part->freefunc = mime_file_free; + part->kind = MIMEKIND_FILE; + + /* As a side effect, set the filename to the current file's base name. + It is possible to withdraw this by explicitly calling + curl_mime_filename() with a NULL filename argument after the current + call. */ + base = strippath(filename); + if(!base) + result = CURLE_OUT_OF_MEMORY; + else { + result = curl_mime_filename(part, base); + curlx_free(base); + } + } + } + } + return result; +} + +/* Set mime part type. */ +CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype) +{ + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + curlx_safefree(part->mimetype); + + if(mimetype) { + part->mimetype = curlx_strdup(mimetype); + if(!part->mimetype) + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +static const struct mime_encoder encoders[] = { + { "binary", encoder_nop_read, encoder_nop_size }, + { "8bit", encoder_nop_read, encoder_nop_size }, + { "7bit", encoder_7bit_read, encoder_nop_size }, + { "base64", encoder_base64_read, encoder_base64_size }, + { "quoted-printable", encoder_qp_read, encoder_qp_size }, + { ZERO_NULL, ZERO_NULL, ZERO_NULL } +}; + +/* Set mime data transfer encoder. */ +CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding) +{ + CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT; + const struct mime_encoder *mep; + + if(!part) + return result; + + part->encoder = NULL; + + if(!encoding) + return CURLE_OK; /* Removing current encoder. */ + + for(mep = encoders; mep->name; mep++) + if(curl_strequal(encoding, mep->name)) { + part->encoder = mep; + result = CURLE_OK; + } + + return result; +} + +/* Set mime part headers. */ +CURLcode curl_mime_headers(curl_mimepart *part, + struct curl_slist *headers, int take_ownership) +{ + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(part->flags & MIME_USERHEADERS_OWNER) { + if(part->userheaders != headers) /* Allow setting twice the same list. */ + curl_slist_free_all(part->userheaders); + part->flags &= ~(unsigned int)MIME_USERHEADERS_OWNER; + } + part->userheaders = headers; + if(headers && take_ownership) + part->flags |= MIME_USERHEADERS_OWNER; + return CURLE_OK; +} + +/* Set mime part content from callback. */ +CURLcode curl_mime_data_cb(curl_mimepart *part, curl_off_t datasize, + curl_read_callback readfunc, + curl_seek_callback seekfunc, + curl_free_callback freefunc, void *arg) +{ + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + cleanup_part_content(part); + + if(readfunc) { + part->readfunc = readfunc; + part->seekfunc = seekfunc; + part->freefunc = freefunc; + part->arg = arg; + part->datasize = datasize; + part->kind = MIMEKIND_CALLBACK; + } + + return CURLE_OK; +} + +/* Set mime part content from subparts. */ +CURLcode Curl_mime_set_subparts(curl_mimepart *part, + curl_mime *subparts, int take_ownership) +{ + curl_mime *root; + + if(!part) + return CURLE_BAD_FUNCTION_ARGUMENT; + + /* Accept setting twice the same subparts. */ + if(part->kind == MIMEKIND_MULTIPART && part->arg == subparts) + return CURLE_OK; + + cleanup_part_content(part); + + if(subparts) { + /* Should not have been attached already. */ + if(subparts->parent) + return CURLE_BAD_FUNCTION_ARGUMENT; + + /* Should not be the part's root. */ + root = part->parent; + if(root) { + while(root->parent && root->parent->parent) + root = root->parent->parent; + if(subparts == root) { + /* cannot add as a subpart of itself. */ + return CURLE_BAD_FUNCTION_ARGUMENT; + } + } + + /* If subparts have already been used as a top-level MIMEPOST, + they might not be positioned at start. Rewind them now, as + a future check while rewinding the parent may cause this + content to be skipped. */ + if(mime_subparts_seek(subparts, (curl_off_t)0, SEEK_SET) != + CURL_SEEKFUNC_OK) + return CURLE_SEND_FAIL_REWIND; + + subparts->parent = part; + /* Subparts are processed internally: no read callback. */ + part->seekfunc = mime_subparts_seek; + part->freefunc = take_ownership ? mime_subparts_free : + mime_subparts_unbind; + part->arg = subparts; + part->datasize = -1; + part->kind = MIMEKIND_MULTIPART; + } + + return CURLE_OK; +} + +CURLcode curl_mime_subparts(curl_mimepart *part, curl_mime *subparts) +{ + return Curl_mime_set_subparts(part, subparts, TRUE); +} + +/* Readback from top mime. */ +/* Argument is the dummy top part. */ +size_t Curl_mime_read(char *buffer, size_t size, size_t nitems, void *instream) +{ + curl_mimepart *part = (curl_mimepart *)instream; + size_t ret; + bool hasread; + + (void)size; /* Always 1 */ + + /* If `nitems` is <= 4, some encoders will return STOP_FILLING without + * adding any data and this loops infinitely. */ + do { + hasread = FALSE; + ret = readback_part(part, buffer, nitems, &hasread, 0); + /* + * If this is not possible to get some data without calling more than + * one read callback (probably because a content encoder is not able to + * deliver a new bunch for the few data accumulated so far), force another + * read until we get enough data or a special exit code. + */ + } while(ret == STOP_FILLING); + + return ret; +} + +/* Rewind mime stream. */ +static CURLcode mime_rewind(curl_mimepart *part) +{ + return mime_part_rewind(part) == CURL_SEEKFUNC_OK ? + CURLE_OK : CURLE_SEND_FAIL_REWIND; +} + +/* Compute header list size. */ +static size_t slist_size(struct curl_slist *s, + size_t overhead, const char *skip, size_t skiplen) +{ + size_t size = 0; + + for(; s; s = s->next) + if(!skip || !match_header(s, skip, skiplen)) + size += strlen(s->data) + overhead; + return size; +} + +/* Get/compute multipart size. */ +static curl_off_t multipart_size(curl_mime *mime) +{ + curl_off_t size; + curl_off_t boundarysize; + curl_mimepart *part; + + if(!mime) + return 0; /* Not present -> empty. */ + + boundarysize = 4 + MIME_BOUNDARY_LEN + 2; + size = boundarysize; /* Final boundary - CRLF after headers. */ + + for(part = mime->firstpart; part; part = part->nextpart) { + curl_off_t sz = mime_size(part); + + if(sz < 0) + size = sz; + + if(size >= 0) + size += boundarysize + sz; + } + + return size; +} + +/* Get/compute mime size. */ +static curl_off_t mime_size(curl_mimepart *part) +{ + curl_off_t size; + + if(part->kind == MIMEKIND_MULTIPART) + part->datasize = multipart_size(part->arg); + + size = part->datasize; + + if(part->encoder) + size = part->encoder->sizefunc(part); + + if(size >= 0 && !(part->flags & MIME_BODY_ONLY)) { + /* Compute total part size. */ + size += slist_size(part->curlheaders, 2, NULL, 0); + size += slist_size(part->userheaders, 2, STRCONST("Content-Type")); + size += 2; /* CRLF after headers. */ + } + return size; +} + +/* Add a header. */ +/* VARARGS2 */ +CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...) +{ + struct curl_slist *hdr = NULL; + char *s = NULL; + va_list ap; + + va_start(ap, fmt); + s = curl_mvaprintf(fmt, ap); + va_end(ap); + + if(s) { + hdr = Curl_slist_append_nodup(*slp, s); + if(hdr) + *slp = hdr; + else + curlx_free(s); + } + + return hdr ? CURLE_OK : CURLE_OUT_OF_MEMORY; +} + +/* Add a content type header. */ +static CURLcode add_content_type(struct curl_slist **slp, + const char *type, const char *boundary) +{ + return Curl_mime_add_header(slp, "Content-Type: %s%s%s", type, + boundary ? "; boundary=" : "", + boundary ? boundary : ""); +} + +const char *Curl_mime_contenttype(const char *filename) +{ + /* + * If no content type was specified, we scan through a few well-known + * extensions and pick the first we match! + */ + struct ContentType { + const char *extension; + const char *type; + }; + static const struct ContentType ctts[] = { + { ".gif", "image/gif" }, + { ".jpg", "image/jpeg" }, + { ".jpeg", "image/jpeg" }, + { ".png", "image/png" }, + { ".svg", "image/svg+xml" }, + { ".txt", "text/plain" }, + { ".htm", "text/html" }, + { ".html", "text/html" }, + { ".pdf", "application/pdf" }, + { ".xml", "application/xml" } + }; + + if(filename) { + size_t len1 = strlen(filename); + const char *nameend = filename + len1; + unsigned int i; + + for(i = 0; i < CURL_ARRAYSIZE(ctts); i++) { + size_t len2 = strlen(ctts[i].extension); + + if(len1 >= len2 && curl_strequal(nameend - len2, ctts[i].extension)) + return ctts[i].type; + } + } + return NULL; +} + +static bool content_type_match(const char *contenttype, + const char *target, size_t len) +{ + if(contenttype && curl_strnequal(contenttype, target, len)) + switch(contenttype[len]) { + case '\0': + case '\t': + case '\r': + case '\n': + case ' ': + case ';': + return TRUE; + } + return FALSE; +} + +static CURLcode add_content_disposition(struct Curl_easy *data, + curl_mimepart *part, + const char *disposition, + const char *contenttype, + enum mimestrategy strategy) +{ + if(!disposition) + if(part->filename || part->name || + (contenttype && !curl_strnequal(contenttype, "multipart/", 10))) + disposition = DISPOSITION_DEFAULT; + if(disposition && curl_strequal(disposition, "attachment") && + !part->name && !part->filename) + disposition = NULL; + if(disposition) { + CURLcode result = CURLE_OK; + char *name = NULL; + char *filename = NULL; + /* The mail (and legacy mime_formescape) strategy quotes the name and + filename with a backslash and has no in-band way to represent a CR or + LF, so one embedded in the value would split the generated header. The + form strategy percent-encodes CR/LF (see escape_string) and is safe. */ + bool backslash = (strategy == MIMESTRATEGY_MAIL) || + (data && data->set.mime_formescape); + if(backslash && + ((part->name && part->name[strcspn(part->name, "\r\n")]) || + (part->filename && part->filename[strcspn(part->filename, "\r\n")]))) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(part->name) { + name = escape_string(data, part->name, strategy); + if(!name) + return CURLE_OUT_OF_MEMORY; + } + if(part->filename) { + filename = escape_string(data, part->filename, strategy); + if(!filename) + result = CURLE_OUT_OF_MEMORY; + } + if(!result) + result = Curl_mime_add_header(&part->curlheaders, + "Content-Disposition: %s%s%s%s%s%s%s", + disposition, + name ? "; name=\"" : "", + name ? name : "", + name ? "\"" : "", + filename ? "; filename=\"" : "", + filename ? filename : "", + filename ? "\"" : ""); + curlx_safefree(name); + curlx_safefree(filename); + if(result) + return result; + } + return CURLE_OK; +} + +CURLcode Curl_mime_prepare_headers(struct Curl_easy *data, + curl_mimepart *part, + const char *contenttype, + const char *disposition, + enum mimestrategy strategy) +{ + curl_mime *mime = NULL; + const char *boundary = NULL; + char *customct; + const char *cte = NULL; + CURLcode result = CURLE_OK; + + /* Get rid of previously prepared headers. */ + curl_slist_free_all(part->curlheaders); + part->curlheaders = NULL; + + /* Be sure we will not access old headers later. */ + if(part->state.state == MIMESTATE_CURLHEADERS) + mimesetstate(&part->state, MIMESTATE_CURLHEADERS, NULL); + + /* Check if content type is specified. */ + customct = part->mimetype; + if(!customct) + customct = search_header(part->userheaders, STRCONST("Content-Type")); + if(customct) + contenttype = customct; + + /* If content type is not specified, try to determine it. */ + if(!contenttype) { + switch(part->kind) { + case MIMEKIND_MULTIPART: + contenttype = MULTIPART_CONTENTTYPE_DEFAULT; + break; + case MIMEKIND_FILE: + contenttype = Curl_mime_contenttype(part->filename); + if(!contenttype) + contenttype = Curl_mime_contenttype(part->data); + if(!contenttype && part->filename) + contenttype = FILE_CONTENTTYPE_DEFAULT; + break; + default: + contenttype = Curl_mime_contenttype(part->filename); + break; + } + } + + if(part->kind == MIMEKIND_MULTIPART) { + mime = (curl_mime *)part->arg; + if(mime) + boundary = mime->boundary; + } + else if(contenttype && !customct && + content_type_match(contenttype, STRCONST("text/plain"))) + if(strategy == MIMESTRATEGY_MAIL || !part->filename) + contenttype = NULL; + + /* Issue content-disposition header only if not already set by caller. */ + if(!search_header(part->userheaders, STRCONST("Content-Disposition"))) { + result = add_content_disposition(data, part, disposition, + contenttype, strategy); + if(result) + return result; + } + + /* Issue Content-Type header. */ + if(contenttype) { + result = add_content_type(&part->curlheaders, contenttype, boundary); + if(result) + return result; + } + + /* Content-Transfer-Encoding header. */ + if(!search_header(part->userheaders, + STRCONST("Content-Transfer-Encoding"))) { + if(part->encoder) + cte = part->encoder->name; + else if(contenttype && strategy == MIMESTRATEGY_MAIL && + part->kind != MIMEKIND_MULTIPART) + cte = "8bit"; + if(cte) { + result = Curl_mime_add_header(&part->curlheaders, + "Content-Transfer-Encoding: %s", cte); + if(result) + return result; + } + } + + /* If we were reading curl-generated headers, restart with new ones (this + should not occur). */ + if(part->state.state == MIMESTATE_CURLHEADERS) + mimesetstate(&part->state, MIMESTATE_CURLHEADERS, part->curlheaders); + + /* Process subparts. */ + if(part->kind == MIMEKIND_MULTIPART && mime) { + curl_mimepart *subpart; + + disposition = NULL; + if(content_type_match(contenttype, STRCONST("multipart/form-data"))) + disposition = "form-data"; + for(subpart = mime->firstpart; subpart; subpart = subpart->nextpart) { + result = Curl_mime_prepare_headers(data, subpart, NULL, + disposition, strategy); + if(result) + return result; + } + } + return result; +} + +/* Recursively reset paused status in the given part. */ +static void mime_unpause(curl_mimepart *part) +{ + if(part) { + if(part->lastreadstatus == CURL_READFUNC_PAUSE) + part->lastreadstatus = 1; /* Successful read status. */ + if(part->kind == MIMEKIND_MULTIPART) { + curl_mime *mime = (curl_mime *)part->arg; + + if(mime) { + curl_mimepart *subpart; + + for(subpart = mime->firstpart; subpart; subpart = subpart->nextpart) + mime_unpause(subpart); + } + } + } +} + +struct cr_mime_ctx { + struct Curl_creader super; + curl_mimepart *part; + curl_off_t total_len; + curl_off_t read_len; + CURLcode error_result; + struct bufq tmpbuf; + BIT(seen_eos); + BIT(errored); +}; + +static CURLcode cr_mime_init(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_mime_ctx *ctx = reader->ctx; + (void)data; + ctx->total_len = -1; + ctx->read_len = 0; + Curl_bufq_init2(&ctx->tmpbuf, 1024, 1, BUFQ_OPT_NO_SPARES); + return CURLE_OK; +} + +static void cr_mime_close(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_mime_ctx *ctx = reader->ctx; + (void)data; + Curl_bufq_free(&ctx->tmpbuf); +} + +/* Real client reader to installed client callbacks. */ +static CURLcode cr_mime_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + struct cr_mime_ctx *ctx = reader->ctx; + CURLcode result = CURLE_OK; + size_t nread; + char tmp[256]; + + /* Once we have errored, we will return the same error forever */ + if(ctx->errored) { + CURL_TRC_READ(data, "cr_mime_read(len=%zu) is errored -> %d, eos=0", + blen, (int)ctx->error_result); + *pnread = 0; + *peos = FALSE; + return ctx->error_result; + } + if(ctx->seen_eos) { + CURL_TRC_READ(data, "cr_mime_read(len=%zu) seen eos -> 0, eos=1", blen); + *pnread = 0; + *peos = TRUE; + return CURLE_OK; + } + /* respect length limitations */ + if(ctx->total_len >= 0) { + curl_off_t remain = ctx->total_len - ctx->read_len; + if(remain <= 0) + blen = 0; + else if(remain < (curl_off_t)blen) + blen = (size_t)remain; + } + + if(!Curl_bufq_is_empty(&ctx->tmpbuf)) { + result = Curl_bufq_read(&ctx->tmpbuf, (unsigned char *)buf, blen, &nread); + if(result) { + ctx->errored = TRUE; + ctx->error_result = result; + return result; + } + } + else if(blen <= 4) { + /* Curl_mime_read() may go into an infinite loop when reading + * via a base64 encoder, as it stalls when the read buffer is too small + * to contain a complete 3-byte encoding. Read into a larger buffer + * and use that until empty. */ + CURL_TRC_READ(data, "cr_mime_read(len=%zu), small read, using tmp", blen); + nread = Curl_mime_read(tmp, 1, sizeof(tmp), ctx->part); + if(nread <= sizeof(tmp)) { + size_t n; + result = Curl_bufq_write(&ctx->tmpbuf, (unsigned char *)tmp, nread, &n); + if(result) { + ctx->errored = TRUE; + ctx->error_result = result; + return result; + } + /* stored it, read again */ + result = Curl_bufq_cread(&ctx->tmpbuf, buf, blen, &nread); + if(result) { + ctx->errored = TRUE; + ctx->error_result = result; + return result; + } + } + } + else + nread = Curl_mime_read(buf, 1, blen, ctx->part); + + CURL_TRC_READ(data, "cr_mime_read(len=%zu), mime_read() -> %zu", + blen, nread); + + switch(nread) { + case 0: + if((ctx->total_len >= 0) && (ctx->read_len < ctx->total_len)) { + failf(data, "client mime read EOF fail, " + "only %" FMT_OFF_T "/%" FMT_OFF_T + " of needed bytes read", ctx->read_len, ctx->total_len); + return CURLE_READ_ERROR; + } + *pnread = 0; + *peos = TRUE; + ctx->seen_eos = TRUE; + break; + + case CURL_READFUNC_ABORT: + failf(data, "operation aborted by callback"); + *pnread = 0; + *peos = FALSE; + ctx->errored = TRUE; + ctx->error_result = CURLE_ABORTED_BY_CALLBACK; + result = CURLE_ABORTED_BY_CALLBACK; + break; + + case CURL_READFUNC_PAUSE: + /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */ + CURL_TRC_READ(data, "cr_mime_read(len=%zu), paused by callback", blen); + *pnread = 0; + *peos = FALSE; + result = Curl_xfer_pause_send(data, TRUE); + break; /* nothing was read */ + + case STOP_FILLING: + case READ_ERROR: + failf(data, "read error getting mime data"); + *pnread = 0; + *peos = FALSE; + ctx->errored = TRUE; + ctx->error_result = CURLE_READ_ERROR; + result = CURLE_READ_ERROR; + break; + + default: + if(nread > blen) { + /* the read function returned a too large value */ + failf(data, "read function returned funny value"); + *pnread = 0; + *peos = FALSE; + ctx->errored = TRUE; + ctx->error_result = CURLE_READ_ERROR; + return CURLE_READ_ERROR; + } + ctx->read_len += nread; + if(ctx->total_len >= 0) + ctx->seen_eos = (ctx->read_len >= ctx->total_len); + *pnread = nread; + *peos = (bool)ctx->seen_eos; + break; + } + + CURL_TRC_READ(data, "cr_mime_read(len=%zu, total=%" FMT_OFF_T + ", read=%" FMT_OFF_T ") -> %d, %zu, %d", blen, + ctx->total_len, ctx->read_len, (int)result, *pnread, *peos); + return result; +} + +static bool cr_mime_needs_rewind(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_mime_ctx *ctx = reader->ctx; + (void)data; + return ctx->read_len > 0; +} + +static curl_off_t cr_mime_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_mime_ctx *ctx = reader->ctx; + (void)data; + return ctx->total_len; +} + +static CURLcode cr_mime_resume_from(struct Curl_easy *data, + struct Curl_creader *reader, + curl_off_t offset) +{ + struct cr_mime_ctx *ctx = reader->ctx; + + if(offset > 0) { + curl_off_t passed = 0; + + do { + char scratch[4 * 1024]; + size_t readthisamountnow = + (offset - passed > (curl_off_t)sizeof(scratch)) ? + sizeof(scratch) : + curlx_sotouz(offset - passed); + size_t nread; + + nread = Curl_mime_read(scratch, 1, readthisamountnow, ctx->part); + passed += (curl_off_t)nread; + if((nread == 0) || (nread > readthisamountnow)) { + /* this checks for greater-than only to make sure that the + CURL_READFUNC_ABORT return code still aborts */ + failf(data, "Could only read %" FMT_OFF_T + " bytes from the mime post", passed); + return CURLE_READ_ERROR; + } + } while(passed < offset); + + /* now, decrease the size of the read */ + if(ctx->total_len > 0) { + ctx->total_len -= offset; + + if(ctx->total_len <= 0) { + failf(data, "Mime post already completely uploaded"); + return CURLE_PARTIAL_FILE; + } + } + /* we have passed, proceed as normal */ + } + return CURLE_OK; +} + +static CURLcode cr_mime_cntrl(struct Curl_easy *data, + struct Curl_creader *reader, + Curl_creader_cntrl opcode) +{ + struct cr_mime_ctx *ctx = reader->ctx; + switch(opcode) { + case CURL_CRCNTRL_REWIND: { + CURLcode result = mime_rewind(ctx->part); + if(result) + failf(data, "Cannot rewind mime/post data"); + return result; + } + case CURL_CRCNTRL_UNPAUSE: + mime_unpause(ctx->part); + break; + case CURL_CRCNTRL_CLEAR_EOS: + ctx->seen_eos = FALSE; + break; + default: + break; + } + return CURLE_OK; +} + +static bool cr_mime_is_paused(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_mime_ctx *ctx = reader->ctx; + (void)data; + return ctx->part && ctx->part->lastreadstatus == CURL_READFUNC_PAUSE; +} + +static const struct Curl_crtype cr_mime = { + "cr-mime", + cr_mime_init, + cr_mime_read, + cr_mime_close, + cr_mime_needs_rewind, + cr_mime_total_length, + cr_mime_resume_from, + cr_mime_cntrl, + cr_mime_is_paused, + Curl_creader_def_done, + sizeof(struct cr_mime_ctx) +}; + +CURLcode Curl_creader_set_mime(struct Curl_easy *data, curl_mimepart *part) +{ + struct Curl_creader *r; + struct cr_mime_ctx *ctx; + CURLcode result; + + result = Curl_creader_create(&r, data, &cr_mime, CURL_CR_CLIENT); + if(result) + return result; + ctx = r->ctx; + ctx->part = part; + /* Make sure we will read the entire mime structure. */ + result = mime_rewind(ctx->part); + if(result) { + Curl_creader_free(data, r); + return result; + } + ctx->total_len = mime_size(ctx->part); + + return Curl_creader_set(data, r); +} + +#else /* !CURL_DISABLE_MIME && (!CURL_DISABLE_HTTP || + !CURL_DISABLE_SMTP || + !CURL_DISABLE_IMAP) */ + +/* Mime not compiled in: define stubs for externally-referenced functions. */ +curl_mime *curl_mime_init(CURL *easy) +{ + (void)easy; + return NULL; +} + +void curl_mime_free(curl_mime *mime) +{ + (void)mime; +} + +curl_mimepart *curl_mime_addpart(curl_mime *mime) +{ + (void)mime; + return NULL; +} + +CURLcode curl_mime_name(curl_mimepart *part, const char *name) +{ + (void)part; + (void)name; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_filename(curl_mimepart *part, const char *filename) +{ + (void)part; + (void)filename; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype) +{ + (void)part; + (void)mimetype; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding) +{ + (void)part; + (void)encoding; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_data(curl_mimepart *part, const char *data, size_t datasize) +{ + (void)part; + (void)data; + (void)datasize; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_filedata(curl_mimepart *part, const char *filename) +{ + (void)part; + (void)filename; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_data_cb(curl_mimepart *part, curl_off_t datasize, + curl_read_callback readfunc, + curl_seek_callback seekfunc, + curl_free_callback freefunc, + void *arg) +{ + (void)part; + (void)datasize; + (void)readfunc; + (void)seekfunc; + (void)freefunc; + (void)arg; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_subparts(curl_mimepart *part, curl_mime *subparts) +{ + (void)part; + (void)subparts; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_mime_headers(curl_mimepart *part, + struct curl_slist *headers, int take_ownership) +{ + (void)part; + (void)headers; + (void)take_ownership; + return CURLE_NOT_BUILT_IN; +} + +CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...) +{ + (void)slp; + (void)fmt; + return CURLE_NOT_BUILT_IN; +} + +#endif /* if disabled */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/mime.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/mime.h new file mode 100644 index 0000000000..e84f04051b --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/mime.h @@ -0,0 +1,173 @@ +#ifndef HEADER_CURL_MIME_H +#define HEADER_CURL_MIME_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#define MIME_BOUNDARY_DASHES 24 /* leading boundary dashes */ +#define MIME_RAND_BOUNDARY_CHARS 22 /* Nb. of random boundary chars. */ +#define MAX_ENCODED_LINE_LENGTH 76 /* Maximum encoded line length. */ +#define ENCODING_BUFFER_SIZE 256 /* Encoding temp buffers size. */ + +/* Part flags. */ +#define MIME_USERHEADERS_OWNER (1 << 0) +#define MIME_BODY_ONLY (1 << 1) +#define MIME_FAST_READ (1 << 2) + +#define FILE_CONTENTTYPE_DEFAULT "application/octet-stream" +#define MULTIPART_CONTENTTYPE_DEFAULT "multipart/mixed" +#define DISPOSITION_DEFAULT "attachment" + +/* Part source kinds. */ +enum mimekind { + MIMEKIND_NONE = 0, /* Part not set. */ + MIMEKIND_DATA, /* Allocated mime data. */ + MIMEKIND_FILE, /* Data from file. */ + MIMEKIND_CALLBACK, /* Data from `read' callback. */ + MIMEKIND_MULTIPART, /* Data is a mime subpart. */ + MIMEKIND_LAST +}; + +/* Readback state tokens. */ +enum mimestate { + MIMESTATE_BEGIN, /* Readback has not yet started. */ + MIMESTATE_CURLHEADERS, /* In curl-generated headers. */ + MIMESTATE_USERHEADERS, /* In caller's supplied headers. */ + MIMESTATE_EOH, /* End of headers. */ + MIMESTATE_BODY, /* Placeholder. */ + MIMESTATE_BOUNDARY1, /* In boundary prefix. */ + MIMESTATE_BOUNDARY2, /* In boundary. */ + MIMESTATE_CONTENT, /* In content. */ + MIMESTATE_END, /* End of part reached. */ + MIMESTATE_LAST +}; + +/* Mime headers strategies. */ +enum mimestrategy { + MIMESTRATEGY_MAIL, /* Mime mail. */ + MIMESTRATEGY_FORM, /* HTTP post form. */ + MIMESTRATEGY_LAST +}; + +/* Content transfer encoder. */ +struct mime_encoder { + const char * name; /* Encoding name. */ + size_t (*encodefunc)(char *buffer, size_t size, bool ateof, + curl_mimepart *part); /* Encoded read. */ + curl_off_t (*sizefunc)(curl_mimepart *part); /* Encoded size. */ +}; + +/* Content transfer encoder state. */ +struct mime_encoder_state { + size_t pos; /* Position on output line. */ + size_t bufbeg; /* Next data index in input buffer. */ + size_t bufend; /* First unused byte index in input buffer. */ + char buf[ENCODING_BUFFER_SIZE]; /* Input buffer. */ +}; + +/* Mime readback state. */ +struct mime_state { + enum mimestate state; /* Current state token. */ + void *ptr; /* State-dependent pointer. */ + curl_off_t offset; /* State-dependent offset. */ +}; + +/* Boundary string length. */ +#define MIME_BOUNDARY_LEN (MIME_BOUNDARY_DASHES + MIME_RAND_BOUNDARY_CHARS) + +/* A mime multipart. */ +struct curl_mime { + curl_mimepart *parent; /* Parent part. */ + curl_mimepart *firstpart; /* First part. */ + curl_mimepart *lastpart; /* Last part. */ + char boundary[MIME_BOUNDARY_LEN + 1]; /* The part boundary. */ + struct mime_state state; /* Current readback state. */ +}; + +/* A mime part. */ +struct curl_mimepart { + curl_mime *parent; /* Parent mime structure. */ + curl_mimepart *nextpart; /* Forward linked list. */ + enum mimekind kind; /* The part kind. */ + unsigned int flags; /* Flags. */ + char *data; /* Memory data or filename. */ + curl_read_callback readfunc; /* Read function. */ + curl_seek_callback seekfunc; /* Seek function. */ + curl_free_callback freefunc; /* Argument free function. */ + void *arg; /* Argument to callback functions. */ + FILE *fp; /* File pointer. */ + struct curl_slist *curlheaders; /* Part headers. */ + struct curl_slist *userheaders; /* Part headers. */ + char *mimetype; /* Part mime type. */ + char *filename; /* Remote filename. */ + char *name; /* Data name. */ + curl_off_t datasize; /* Expected data size. */ + struct mime_state state; /* Current readback state. */ + const struct mime_encoder *encoder; /* Content data encoder. */ + struct mime_encoder_state encstate; /* Data encoder state. */ + size_t lastreadstatus; /* Last read callback returned status. */ +}; + +CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...) + CURL_PRINTF(2, 3); + +#if !defined(CURL_DISABLE_MIME) && (!defined(CURL_DISABLE_HTTP) || \ + !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_IMAP)) + +/* Prototypes. */ +void Curl_mime_initpart(struct curl_mimepart *part); +void Curl_mime_cleanpart(struct curl_mimepart *part); +CURLcode Curl_mime_duppart(struct Curl_easy *data, + struct curl_mimepart *dst, + const curl_mimepart *src); +CURLcode Curl_mime_set_subparts(struct curl_mimepart *part, + struct curl_mime *subparts, + int take_ownership); +CURLcode Curl_mime_prepare_headers(struct Curl_easy *data, + struct curl_mimepart *part, + const char *contenttype, + const char *disposition, + enum mimestrategy strategy); +size_t Curl_mime_read(char *buffer, size_t size, size_t nitems, + void *instream); +const char *Curl_mime_contenttype(const char *filename); + +/** + * Install a client reader as upload source that reads the given + * mime part. + */ +CURLcode Curl_creader_set_mime(struct Curl_easy *data, curl_mimepart *part); + +#else /* if disabled */ +#define Curl_mime_initpart(x) +#define Curl_mime_cleanpart(x) +#define Curl_mime_duppart(x, y, z) CURLE_OK /* Nothing to duplicate. Succeed */ +#define Curl_mime_set_subparts(a, b, c) CURLE_NOT_BUILT_IN +#define Curl_mime_prepare_headers(a, b, c, d, e) CURLE_NOT_BUILT_IN +#define Curl_mime_read NULL +#define Curl_creader_set_mime(x, y) ((void)(x), CURLE_NOT_BUILT_IN) +#endif + +#endif /* HEADER_CURL_MIME_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/mprintf.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/mprintf.c new file mode 100644 index 0000000000..d4725c905f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/mprintf.c @@ -0,0 +1,1263 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curlx/dynbuf.h" +#include "curl_printf.h" +#include "curlx/strparse.h" +#include "curlx/snprintf.h" /* for curlx_win32_snprintf() */ + +#define BUFFSIZE 326 /* buffer for long-to-str and float-to-str calcs, should + fit negative DBL_MAX (317 letters) */ +#define MAX_PARAMETERS 128 /* number of input arguments */ +#define MAX_SEGMENTS 128 /* number of output segments */ + +/* Lower-case digits. */ +const unsigned char Curl_ldigits[] = "0123456789abcdef"; + +/* Upper-case digits. */ +const unsigned char Curl_udigits[] = "0123456789ABCDEF"; + +#define OUTCHAR(x) \ + do { \ + if(stream((unsigned char)(x), userp)) \ + return TRUE; \ + (*donep)++; \ + } while(0) + +/* Data type to read from the arglist */ +typedef enum { + MTYPE_STRING, + MTYPE_PTR, + MTYPE_INTPTR, + MTYPE_INT, + MTYPE_LONG, + MTYPE_LONGLONG, + MTYPE_INTU, + MTYPE_LONGU, + MTYPE_LONGLONGU, + MTYPE_DOUBLE, + MTYPE_LONGDOUBLE, + MTYPE_WIDTH, + MTYPE_PRECISION +} FormatType; + +/* conversion and display flags */ +enum { + FLAGS_SPACE = 1 << 0, + FLAGS_SHOWSIGN = 1 << 1, + FLAGS_LEFT = 1 << 2, + FLAGS_ALT = 1 << 3, + FLAGS_SHORT = 1 << 4, + FLAGS_LONG = 1 << 5, + FLAGS_LONGLONG = 1 << 6, + FLAGS_LONGDOUBLE = 1 << 7, + FLAGS_PAD_NIL = 1 << 8, + FLAGS_UNSIGNED = 1 << 9, + FLAGS_OCTAL = 1 << 10, + FLAGS_HEX = 1 << 11, + FLAGS_UPPER = 1 << 12, + FLAGS_WIDTH = 1 << 13, /* '*' or '*<num>$' used */ + FLAGS_WIDTHPARAM = 1 << 14, /* width PARAMETER was specified */ + FLAGS_PREC = 1 << 15, /* precision was specified */ + FLAGS_PRECPARAM = 1 << 16, /* precision PARAMETER was specified */ + FLAGS_CHAR = 1 << 17, /* %c story */ + FLAGS_FLOATE = 1 << 18, /* %e or %E */ + FLAGS_FLOATG = 1 << 19, /* %g or %G */ + FLAGS_SUBSTR = 1 << 20 /* no input, only substring */ +}; + +enum { + DOLLAR_UNKNOWN, + DOLLAR_NOPE, + DOLLAR_USE +}; + +/* + * Describes an input va_arg type and hold its value. + */ +struct va_input { + FormatType type; /* FormatType */ + union { + const char *str; + void *ptr; + int64_t nums; /* signed */ + uint64_t numu; /* unsigned */ + double dnum; + } val; +}; + +/* + * Describes an output segment. + */ +struct outsegment { + int width; /* width OR width parameter number */ + int precision; /* precision OR precision parameter number */ + unsigned int flags; + unsigned int input; /* input argument array index */ + const char *start; /* format string start to output */ + size_t outlen; /* number of bytes from the format string to output */ +}; + +struct nsprintf { + char *buffer; + size_t length; + size_t max; +}; + +struct asprintf { + struct dynbuf *b; + char merr; +}; + +/* the provided input number is 1-based but this returns the number 0-based. + * + * returns -1 if no valid number was provided. + */ +static int dollarstring(const char *p, const char **end) +{ + curl_off_t num; + if(curlx_str_number(&p, &num, MAX_PARAMETERS) || + curlx_str_single(&p, '$') || !num) + return -1; + *end = p; + return (int)num - 1; +} + +#define is_arg_used(x, y) ((x)[(y) / 8] & (1 << ((y) & 7))) +#define mark_arg_used(x, y) ((x)[(y) / 8] |= (unsigned char)(1 << ((y) & 7))) + +/* + * Parse the format string. + * + * Create two arrays. One describes the inputs, one describes the outputs. + * + * Returns zero on success. + */ + +#define PFMT_OK 0 +#define PFMT_DOLLAR 1 /* bad dollar for main param */ +#define PFMT_DOLLARWIDTH 2 /* bad dollar use for width */ +#define PFMT_DOLLARPREC 3 /* bad dollar use for precision */ +#define PFMT_MANYARGS 4 /* too many input arguments used */ +#define PFMT_PREC 5 /* precision overflow */ +#define PFMT_PRECMIX 6 /* bad mix of precision specifiers */ +#define PFMT_WIDTH 7 /* width overflow */ +#define PFMT_INPUTGAP 8 /* gap in arguments */ +#define PFMT_WIDTHARG 9 /* attempted to use same arg twice, for width */ +#define PFMT_PRECARG 10 /* attempted to use same arg twice, for prec */ +#define PFMT_MANYSEGS 11 /* maxed out output segments */ + +static int parse_flags(const char **fmtp, unsigned int *flagsp, int use_dollar, + int *precp, int *widthp) +{ + const char *fmt = *fmtp; + bool loopit = TRUE; + unsigned int flags = 0; + int width = 0; + int precision = 0; + + /* Handle the flags */ + do { + switch(*fmt++) { + case ' ': + flags |= FLAGS_SPACE; + break; + case '+': + flags |= FLAGS_SHOWSIGN; + break; + case '-': + flags |= FLAGS_LEFT; + flags &= ~(unsigned int)FLAGS_PAD_NIL; + break; + case '#': + flags |= FLAGS_ALT; + break; + case '.': + if('*' == *fmt) { + /* The precision is picked from a specified parameter */ + flags |= FLAGS_PRECPARAM; + fmt++; + + if(use_dollar == DOLLAR_USE) { + precision = dollarstring(fmt, &fmt); + if(precision < 0) + /* illegal combo */ + return PFMT_DOLLARPREC; + } + else + /* get it from the next argument */ + precision = -1; + } + else { + bool is_neg; + curl_off_t num; + flags |= FLAGS_PREC; + is_neg = ('-' == *fmt); + if(is_neg) + fmt++; + if(curlx_str_number(&fmt, &num, INT_MAX)) + return PFMT_PREC; + precision = (int)num; + if(is_neg) + precision = -precision; + } + if((flags & (FLAGS_PREC | FLAGS_PRECPARAM)) == + (FLAGS_PREC | FLAGS_PRECPARAM)) + /* it is not permitted to use both kinds of precision for the same + argument */ + return PFMT_PRECMIX; + break; + case 'h': + flags |= FLAGS_SHORT; + break; +#ifdef _WIN32 + case 'I': + /* Non-ANSI integer extensions I32 I64 */ + if((fmt[0] == '3') && (fmt[1] == '2')) { + flags |= FLAGS_LONG; + fmt += 2; + } + else if((fmt[0] == '6') && (fmt[1] == '4')) { + flags |= FLAGS_LONGLONG; + fmt += 2; + } + else { +#if SIZEOF_CURL_OFF_T > SIZEOF_LONG + flags |= FLAGS_LONGLONG; +#else + flags |= FLAGS_LONG; +#endif + } + break; +#endif /* _WIN32 */ + case 'l': + if(flags & FLAGS_LONG) + flags |= FLAGS_LONGLONG; + else + flags |= FLAGS_LONG; + break; + case 'L': + flags |= FLAGS_LONGDOUBLE; + break; + case 'q': + flags |= FLAGS_LONGLONG; + break; + case 'z': + /* the code below generates a warning if -Wunreachable-code is + used */ +#if SIZEOF_SIZE_T > SIZEOF_LONG + flags |= FLAGS_LONGLONG; +#else + flags |= FLAGS_LONG; +#endif + break; + case 'O': +#if SIZEOF_CURL_OFF_T > SIZEOF_LONG + flags |= FLAGS_LONGLONG; +#else + flags |= FLAGS_LONG; +#endif + break; + case '0': + if(!(flags & FLAGS_LEFT)) + flags |= FLAGS_PAD_NIL; + FALLTHROUGH(); + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': { + curl_off_t num; + flags |= FLAGS_WIDTH; + fmt--; + if(curlx_str_number(&fmt, &num, INT_MAX)) + return PFMT_WIDTH; + width = (int)num; + break; + } + case '*': /* read width from argument list */ + flags |= FLAGS_WIDTHPARAM; + if(use_dollar == DOLLAR_USE) { + width = dollarstring(fmt, &fmt); + if(width < 0) + /* illegal combo */ + return PFMT_DOLLARWIDTH; + } + else + /* pick from the next argument */ + width = -1; + break; + default: + loopit = FALSE; + fmt--; + break; + } /* switch */ + } while(loopit); /* do */ + *flagsp = flags; + *precp = precision; + *widthp = width; + *fmtp = fmt; + return PFMT_OK; +} + +static bool parse_conversion(const char f, unsigned int *flagp, + FormatType *typep) +{ + unsigned int flags = *flagp; + FormatType type; + switch(f) { + case 'S': + flags |= FLAGS_ALT; + type = MTYPE_STRING; + break; + case 's': + type = MTYPE_STRING; + break; + case 'n': + type = MTYPE_INTPTR; + break; + case 'p': + type = MTYPE_PTR; + break; + case 'd': + case 'i': + if(flags & FLAGS_LONGLONG) + type = MTYPE_LONGLONG; + else if(flags & FLAGS_LONG) + type = MTYPE_LONG; + else + type = MTYPE_INT; + break; + case 'u': + if(flags & FLAGS_LONGLONG) + type = MTYPE_LONGLONGU; + else if(flags & FLAGS_LONG) + type = MTYPE_LONGU; + else + type = MTYPE_INTU; + flags |= FLAGS_UNSIGNED; + break; + case 'o': + if(flags & FLAGS_LONGLONG) + type = MTYPE_LONGLONGU; + else if(flags & FLAGS_LONG) + type = MTYPE_LONGU; + else + type = MTYPE_INTU; + flags |= FLAGS_OCTAL | FLAGS_UNSIGNED; + break; + case 'x': + if(flags & FLAGS_LONGLONG) + type = MTYPE_LONGLONGU; + else if(flags & FLAGS_LONG) + type = MTYPE_LONGU; + else + type = MTYPE_INTU; + flags |= FLAGS_HEX | FLAGS_UNSIGNED; + break; + case 'X': + if(flags & FLAGS_LONGLONG) + type = MTYPE_LONGLONGU; + else if(flags & FLAGS_LONG) + type = MTYPE_LONGU; + else + type = MTYPE_INTU; + flags |= FLAGS_HEX | FLAGS_UPPER | FLAGS_UNSIGNED; + break; + case 'c': + type = MTYPE_INT; + flags |= FLAGS_CHAR; + break; + case 'f': + type = flags & FLAGS_LONGDOUBLE ? MTYPE_LONGDOUBLE : MTYPE_DOUBLE; + break; + case 'F': + type = flags & FLAGS_LONGDOUBLE ? MTYPE_LONGDOUBLE : MTYPE_DOUBLE; + flags |= FLAGS_UPPER; + break; + case 'e': + type = flags & FLAGS_LONGDOUBLE ? MTYPE_LONGDOUBLE : MTYPE_DOUBLE; + flags |= FLAGS_FLOATE; + break; + case 'E': + type = flags & FLAGS_LONGDOUBLE ? MTYPE_LONGDOUBLE : MTYPE_DOUBLE; + flags |= FLAGS_FLOATE | FLAGS_UPPER; + break; + case 'g': + type = flags & FLAGS_LONGDOUBLE ? MTYPE_LONGDOUBLE : MTYPE_DOUBLE; + flags |= FLAGS_FLOATG; + break; + case 'G': + type = flags & FLAGS_LONGDOUBLE ? MTYPE_LONGDOUBLE : MTYPE_DOUBLE; + flags |= FLAGS_FLOATG | FLAGS_UPPER; + break; + default: + /* invalid instruction, disregard and continue */ + return TRUE; + } /* switch */ + + *flagp |= flags; + *typep = type; + return FALSE; +} + +static int parsefmt(const char *format, + struct outsegment *out, + struct va_input *in, + int *opieces, + int *ipieces, va_list arglist) +{ + const char *fmt = format; + int param_num = 0; + int max_param = -1; + int i; + int ocount = 0; + unsigned char usedinput[MAX_PARAMETERS / 8]; + size_t outlen = 0; + struct outsegment *optr; + int use_dollar = DOLLAR_UNKNOWN; + const char *start = fmt; + + /* clear, set a bit for each used input */ + memset(usedinput, 0, sizeof(usedinput)); + + while(*fmt) { + if(*fmt == '%') { + struct va_input *iptr; + FormatType type; + unsigned int flags = 0; + int width = 0; + int precision = 0; + int param = -1; + int rc; + fmt++; + outlen = (size_t)(fmt - start - 1); + if(*fmt == '%') { + /* this means a %% that should be output only as %. Create an output + segment. */ + if(outlen) { + optr = &out[ocount++]; + if(ocount > MAX_SEGMENTS) + return PFMT_MANYSEGS; + optr->input = 0; + optr->flags = FLAGS_SUBSTR; + optr->start = start; + optr->outlen = outlen; + } + start = fmt; + fmt++; + continue; /* while */ + } + + if(use_dollar != DOLLAR_NOPE) { + param = dollarstring(fmt, &fmt); + if(param < 0) { + if(use_dollar == DOLLAR_USE) + /* illegal combo */ + return PFMT_DOLLAR; + + /* we got no positional, get the next arg */ + param = -1; + use_dollar = DOLLAR_NOPE; + } + else + use_dollar = DOLLAR_USE; + } + + rc = parse_flags(&fmt, &flags, use_dollar, &precision, &width); + if(rc) + return rc; + + if(parse_conversion(*fmt, &flags, &type)) + continue; + + if(flags & FLAGS_WIDTHPARAM) { + if(width < 0) + width = param_num++; + else { + /* if this identifies a parameter already used, this is illegal */ + if(is_arg_used(usedinput, width)) + return PFMT_WIDTHARG; + } + if(width >= MAX_PARAMETERS) + return PFMT_MANYARGS; + if(width >= max_param) + max_param = width; + + in[width].type = MTYPE_WIDTH; + /* mark as used */ + mark_arg_used(usedinput, width); + } + + if(flags & FLAGS_PRECPARAM) { + if(precision < 0) + precision = param_num++; + else { + /* if this identifies a parameter already used, this is illegal */ + if(is_arg_used(usedinput, precision)) + return PFMT_PRECARG; + } + if(precision >= MAX_PARAMETERS) + return PFMT_MANYARGS; + if(precision >= max_param) + max_param = precision; + + in[precision].type = MTYPE_PRECISION; + mark_arg_used(usedinput, precision); + } + + /* Handle the specifier */ + if(param < 0) + param = param_num++; + if(param >= MAX_PARAMETERS) + return PFMT_MANYARGS; + if(param >= max_param) + max_param = param; + + iptr = &in[param]; + iptr->type = type; + + /* mark this input as used */ + mark_arg_used(usedinput, param); + + fmt++; + optr = &out[ocount++]; + if(ocount > MAX_SEGMENTS) + return PFMT_MANYSEGS; + optr->input = (unsigned int)param; + optr->flags = flags; + optr->width = width; + optr->precision = precision; + optr->start = start; + optr->outlen = outlen; + start = fmt; + } + else + fmt++; + } + + /* is there a trailing piece */ + outlen = (size_t)(fmt - start); + if(outlen) { + optr = &out[ocount++]; + if(ocount > MAX_SEGMENTS) + return PFMT_MANYSEGS; + optr->input = 0; + optr->flags = FLAGS_SUBSTR; + optr->start = start; + optr->outlen = outlen; + } + + /* Read the arg list parameters into our data list */ + for(i = 0; i < max_param + 1; i++) { + struct va_input *iptr = &in[i]; + if(!is_arg_used(usedinput, i)) + /* bad input */ + return PFMT_INPUTGAP; + + /* based on the type, read the correct argument */ + switch(iptr->type) { + case MTYPE_STRING: + iptr->val.str = va_arg(arglist, const char *); + break; + + case MTYPE_INTPTR: + case MTYPE_PTR: + iptr->val.ptr = va_arg(arglist, void *); + break; + + case MTYPE_LONGLONGU: + iptr->val.numu = va_arg(arglist, uint64_t); + break; + + case MTYPE_LONGLONG: + iptr->val.nums = va_arg(arglist, int64_t); + break; + + case MTYPE_LONGU: + iptr->val.numu = va_arg(arglist, unsigned long); + break; + + case MTYPE_LONG: + iptr->val.nums = va_arg(arglist, long); + break; + + case MTYPE_INTU: + iptr->val.numu = va_arg(arglist, unsigned int); + break; + + case MTYPE_INT: + case MTYPE_WIDTH: + case MTYPE_PRECISION: + iptr->val.nums = va_arg(arglist, int); + break; + + case MTYPE_DOUBLE: + iptr->val.dnum = va_arg(arglist, double); + break; + + case MTYPE_LONGDOUBLE: + iptr->val.dnum = (double)va_arg(arglist, long double); + break; + + default: + DEBUGASSERT(NULL); /* unexpected */ + break; + } + } + *ipieces = max_param + 1; + *opieces = ocount; + + return PFMT_OK; +} + +struct mproperty { + int width; /* Width of a field. */ + int prec; /* Precision of a field. */ + unsigned int flags; +}; + +static bool out_double(void *userp, + int (*stream)(unsigned char, void *), + struct mproperty *p, + double dnum, + char *work, int *donep) +{ + char fmt[32] = "%"; + char *fptr = &fmt[1]; + size_t left = sizeof(fmt) - strlen(fmt); + int flags = p->flags; + int width = p->width; + int prec = p->prec; + + if(flags & FLAGS_LEFT) + *fptr++ = '-'; + if(flags & FLAGS_SHOWSIGN) + *fptr++ = '+'; + if(flags & FLAGS_SPACE) + *fptr++ = ' '; + if(flags & FLAGS_ALT) + *fptr++ = '#'; + + *fptr = 0; + + if(width >= 0) { + size_t dlen; + if(width >= BUFFSIZE) + width = BUFFSIZE - 1; + /* RECURSIVE USAGE */ + dlen = (size_t)curl_msnprintf(fptr, left, "%d", width); + fptr += dlen; + left -= dlen; + } + if(prec >= 0) { + /* for each digit in the integer part, we can have one less + precision */ + int maxprec = BUFFSIZE - 1; + double val = dnum; + int len; + if(prec > maxprec) + prec = maxprec - 1; + if(width > 0 && prec <= width) + maxprec -= width; + while(maxprec && (val >= 10.0)) { + val /= 10; + maxprec--; + } + + if(prec > maxprec) + prec = maxprec - 1; + if(prec < 0) + prec = 0; + /* RECURSIVE USAGE */ + len = curl_msnprintf(fptr, left, ".%d", prec); + fptr += len; + } + if(flags & FLAGS_LONG) + *fptr++ = 'l'; + + if(flags & FLAGS_FLOATE) + *fptr++ = (char)((flags & FLAGS_UPPER) ? 'E' : 'e'); + else if(flags & FLAGS_FLOATG) + *fptr++ = (char)((flags & FLAGS_UPPER) ? 'G' : 'g'); + else + *fptr++ = (flags & FLAGS_UPPER) ? 'F' : 'f'; + + *fptr = 0; /* and a final null-termination */ + + /* NOTE NOTE NOTE!! Not all sprintf implementations return number of + output characters */ +#ifdef CURL_HAVE_DIAG +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-nonliteral" +#endif +#ifdef _WIN32 + curlx_win32_snprintf(work, BUFFSIZE, fmt, dnum); +#else + /* !checksrc! disable BANNEDFUNC 2 */ + snprintf(work, BUFFSIZE, fmt, dnum); +#endif +#ifdef CURL_HAVE_DIAG +#pragma GCC diagnostic pop +#endif + DEBUGASSERT(strlen(work) < BUFFSIZE); + while(*work) { + if(stream(*work++, userp)) + return TRUE; + (*donep)++; + } + return 0; +} + +static bool out_number(void *userp, + int (*stream)(unsigned char, void *), + struct mproperty *p, + uint64_t num, + int64_t nums, + char *work, int *donep) +{ + const unsigned char *digits = Curl_ldigits; + int flags = p->flags; + int width = p->width; + int prec = p->prec; + bool is_alt = flags & FLAGS_ALT; + bool is_neg = FALSE; + int base = 10; + + /* 'workend' points to the final buffer byte position, but with an extra + byte as margin to avoid the (FALSE?) warning Coverity gives us + otherwise */ + char *workend = &work[BUFFSIZE - 2]; + char *w; + + if(flags & FLAGS_CHAR) { + /* Character. */ + if(!(flags & FLAGS_LEFT)) + while(--width > 0) + OUTCHAR(' '); + OUTCHAR((char)num); + if(flags & FLAGS_LEFT) + while(--width > 0) + OUTCHAR(' '); + return FALSE; + } + if(flags & FLAGS_OCTAL) + /* Octal unsigned integer */ + base = 8; + + else if(flags & FLAGS_HEX) { + /* Hexadecimal unsigned integer */ + digits = (flags & FLAGS_UPPER) ? Curl_udigits : Curl_ldigits; + base = 16; + } + else if(flags & FLAGS_UNSIGNED) + /* Decimal unsigned integer */ + ; + + else { + /* Decimal integer. */ + is_neg = (nums < 0); + if(is_neg) { + /* signed_num might fail to hold absolute negative minimum by 1 */ + int64_t signed_num; /* Used to convert negative in positive. */ + signed_num = nums + (int64_t)1; + signed_num = -signed_num; + num = (uint64_t)signed_num; + num += (uint64_t)1; + } + } + + /* Supply a default precision if none was given. */ + if(prec == -1) + prec = 1; + + /* Put the number in WORK. */ + w = workend; + DEBUGASSERT(base <= 16); + switch(base) { + case 10: + while(num > 0) { + *w-- = (char)('0' + (num % 10)); + num /= 10; + } + break; + default: + while(num > 0) { + *w-- = digits[num % base]; + num /= base; + } + break; + } + width -= (int)(workend - w); + prec -= (int)(workend - w); + + if(is_alt && base == 8 && prec <= 0) { + *w-- = '0'; + --width; + } + + if(prec > 0) { + width -= prec; + while(prec-- > 0 && w >= work) + *w-- = '0'; + } + + if(is_alt && base == 16) + width -= 2; + + if(is_neg || (flags & FLAGS_SHOWSIGN) || (flags & FLAGS_SPACE)) + --width; + + if(!(flags & FLAGS_LEFT) && !(flags & FLAGS_PAD_NIL)) + while(width-- > 0) + OUTCHAR(' '); + + if(is_neg) + OUTCHAR('-'); + else if(flags & FLAGS_SHOWSIGN) + OUTCHAR('+'); + else if(flags & FLAGS_SPACE) + OUTCHAR(' '); + + if(is_alt && base == 16) { + OUTCHAR('0'); + if(flags & FLAGS_UPPER) + OUTCHAR('X'); + else + OUTCHAR('x'); + } + + if(!(flags & FLAGS_LEFT) && (flags & FLAGS_PAD_NIL)) + while(width-- > 0) + OUTCHAR('0'); + + /* Write the number. */ + while(++w <= workend) { + OUTCHAR(*w); + } + + if(flags & FLAGS_LEFT) + while(width-- > 0) + OUTCHAR(' '); + + return FALSE; +} + +static const char nilstr[] = "(nil)"; + +static bool out_string(void *userp, + int (*stream)(unsigned char, void *), + struct mproperty *p, + const char *str, + int *donep) +{ + int flags = p->flags; + int width = p->width; + int prec = p->prec; + size_t len; + + if(!str) { + /* Write null string if there is space. */ + if(prec == -1 || prec >= (int)CURL_CSTRLEN(nilstr)) { + str = nilstr; + len = CURL_CSTRLEN(nilstr); + /* Disable quotes around (nil) */ + flags &= ~(unsigned int)FLAGS_ALT; + } + else { + str = ""; + len = 0; + } + } + else if(prec != -1) + len = (size_t)prec; + else if(*str == '\0') + len = 0; + else + len = strlen(str); + + width -= (len > INT_MAX) ? INT_MAX : (int)len; + + if(flags & FLAGS_ALT) + OUTCHAR('"'); + + if(!(flags & FLAGS_LEFT)) + while(width-- > 0) + OUTCHAR(' '); + + for(; len && *str; len--) + OUTCHAR(*str++); + if(flags & FLAGS_LEFT) + while(width-- > 0) + OUTCHAR(' '); + + if(flags & FLAGS_ALT) + OUTCHAR('"'); + + return FALSE; +} + +static bool out_pointer(void *userp, + int (*stream)(unsigned char, void *), + struct mproperty *p, + const char *ptr, + char *work, + int *donep) +{ + /* Generic pointer. */ + if(ptr) { + size_t num = (size_t)ptr; + + /* If the pointer is not NULL, write it as a %#x spec. */ + p->flags |= FLAGS_HEX | FLAGS_ALT; + if(out_number(userp, stream, p, num, 0, work, donep)) + return TRUE; + } + else { + /* Write "(nil)" for a nil pointer. */ + const char *point; + int width = p->width; + int flags = p->flags; + + width -= (int)CURL_CSTRLEN(nilstr); + if(flags & FLAGS_LEFT) + while(width-- > 0) + OUTCHAR(' '); + for(point = nilstr; *point; ++point) + OUTCHAR(*point); + if(!(flags & FLAGS_LEFT)) + while(width-- > 0) + OUTCHAR(' '); + } + return FALSE; +} + +/* + * formatf() - the general printf function. + * + * It calls parsefmt() to parse the format string. It populates two arrays; + * one that describes the input arguments and one that describes a number of + * output segments. + * + * On success, the input array describes the type of all arguments and their + * values. + * + * The function then iterates over the output segments and outputs them one + * by one until done. Using the appropriate input arguments (if any). + * + * All output is sent to the 'stream()' callback, one byte at a time. + */ +static int formatf(void *userp, /* untouched by format(), sent to the + stream() function in the second argument */ + /* function pointer called for each output character */ + int (*stream)(unsigned char, void *), + const char *format, /* %-formatted string */ + va_list ap_save) /* list of parameters */ +{ + int done = 0; /* number of characters written */ + int i; + int ocount = 0; /* number of output segments */ + int icount = 0; /* number of input arguments */ + + struct outsegment output[MAX_SEGMENTS]; + struct va_input input[MAX_PARAMETERS]; + char work[BUFFSIZE + 2]; + + /* Parse the format string */ + if(parsefmt(format, output, input, &ocount, &icount, ap_save)) + return 0; + + for(i = 0; i < ocount; i++) { + struct outsegment *optr = &output[i]; + struct va_input *iptr = &input[optr->input]; + struct mproperty p; + size_t outlen = optr->outlen; + + if(outlen) { + const char *str = optr->start; + for(; outlen && *str; outlen--) { + if(stream(*str++, userp)) + return done; + done++; + } + if(optr->flags & FLAGS_SUBSTR) + /* this is a substring */ + continue; + } + + p.flags = optr->flags; + + /* pick up the specified width */ + if(p.flags & FLAGS_WIDTHPARAM) { + p.width = (int)input[optr->width].val.nums; + if(p.width < 0) { + /* "A negative field width is taken as a '-' flag followed by a + positive field width." */ + if(p.width == INT_MIN) + p.width = INT_MAX; + else + p.width = -p.width; + p.flags |= FLAGS_LEFT; + p.flags &= ~(unsigned int)FLAGS_PAD_NIL; + } + } + else + p.width = optr->width; + + /* pick up the specified precision */ + if(p.flags & FLAGS_PRECPARAM) { + p.prec = (int)input[optr->precision].val.nums; + if(p.prec < 0) + /* "A negative precision is taken as if the precision were + omitted." */ + p.prec = -1; + } + else if(p.flags & FLAGS_PREC) + p.prec = optr->precision; + else + p.prec = -1; + + switch(iptr->type) { + case MTYPE_INTU: + case MTYPE_LONGU: + case MTYPE_LONGLONGU: + p.flags |= FLAGS_UNSIGNED; + if(out_number(userp, stream, &p, iptr->val.numu, 0, work, &done)) + return done; + break; + + case MTYPE_INT: + case MTYPE_LONG: + case MTYPE_LONGLONG: + if(out_number(userp, stream, &p, iptr->val.numu, + iptr->val.nums, work, &done)) + return done; + break; + + case MTYPE_STRING: + if(out_string(userp, stream, &p, iptr->val.str, &done)) + return done; + break; + + case MTYPE_PTR: + if(out_pointer(userp, stream, &p, iptr->val.ptr, work, &done)) + return done; + break; + + case MTYPE_DOUBLE: + case MTYPE_LONGDOUBLE: + if(out_double(userp, stream, &p, iptr->val.dnum, work, &done)) + return done; + break; + + case MTYPE_INTPTR: + /* Answer the count of characters written. */ + if(p.flags & FLAGS_LONGLONG) + *(int64_t *)iptr->val.ptr = (int64_t)done; + else if(p.flags & FLAGS_LONG) + *(long *)iptr->val.ptr = (long)done; + else if(!(p.flags & FLAGS_SHORT)) + *(int *)iptr->val.ptr = done; + else + *(short *)iptr->val.ptr = (short)done; + break; + + default: + break; + } + } + return done; +} + +/* fputc() look-alike */ +static int addbyter(unsigned char outc, void *f) +{ + struct nsprintf *infop = f; + if(infop->length < infop->max) { + /* only do this if we have not reached max length yet */ + *infop->buffer++ = (char)outc; /* store */ + infop->length++; /* we are now one byte larger */ + return 0; /* fputc() returns like this on success */ + } + return 1; +} + +int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format, + va_list args) +{ + int retcode; + struct nsprintf info; + + info.buffer = buffer; + info.length = 0; + info.max = maxlength; + + retcode = formatf(&info, addbyter, format, args); + if(info.max) { + /* we terminate this with a zero byte */ + if(info.max == info.length) { + /* we are at maximum, scrap the last letter */ + info.buffer[-1] = 0; + DEBUGASSERT(retcode); + retcode--; /* do not count the nul byte */ + } + else + info.buffer[0] = 0; + } + return retcode; +} + +int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...) +{ + int retcode; + va_list args; /* argument pointer */ + va_start(args, format); + retcode = curl_mvsnprintf(buffer, maxlength, format, args); + va_end(args); + return retcode; +} + +/* fputc() look-alike */ +static int alloc_addbyter(unsigned char outc, void *f) +{ + struct asprintf *infop = f; + CURLcode result = curlx_dyn_addn(infop->b, &outc, 1); + if(result) { + infop->merr = result == CURLE_TOO_LARGE ? MERR_TOO_LARGE : MERR_MEM; + return 1; /* fail */ + } + return 0; +} + +/* appends the formatted string, returns MERR error code */ +int curlx_dyn_vprintf(struct dynbuf *dyn, const char *format, va_list args) +{ + struct asprintf info; + info.b = dyn; + info.merr = MERR_OK; + + (void)formatf(&info, alloc_addbyter, format, args); + if(info.merr) { + curlx_dyn_free(info.b); + return info.merr; + } + return 0; +} + +char *curl_mvaprintf(const char *format, va_list args) +{ + struct asprintf info; + struct dynbuf dyn; + info.b = &dyn; + curlx_dyn_init(info.b, DYN_APRINTF); + info.merr = MERR_OK; + + (void)formatf(&info, alloc_addbyter, format, args); + if(info.merr) { + curlx_dyn_free(info.b); + return NULL; + } + if(curlx_dyn_len(info.b)) + return curlx_dyn_ptr(info.b); + return curlx_strdup(""); +} + +char *curl_maprintf(const char *format, ...) +{ + va_list args; + char *s; + va_start(args, format); + s = curl_mvaprintf(format, args); + va_end(args); + return s; +} + +static int storebuffer(unsigned char outc, void *f) +{ + char **buffer = f; + **buffer = (char)outc; + (*buffer)++; + return 0; +} + +int curl_msprintf(char *buffer, const char *format, ...) +{ + va_list args; /* argument pointer */ + int retcode; + va_start(args, format); + retcode = formatf(&buffer, storebuffer, format, args); + va_end(args); + *buffer = 0; /* we terminate this with a zero byte */ + return retcode; +} + +static int fputc_wrapper(unsigned char outc, void *f) +{ + int out = outc; + FILE *s = f; + int rc = fputc(out, s); + return rc == EOF; +} + +int curl_mprintf(const char *format, ...) +{ + int retcode; + va_list args; /* argument pointer */ + va_start(args, format); + retcode = formatf(stdout, fputc_wrapper, format, args); + va_end(args); + return retcode; +} + +int curl_mfprintf(FILE *fd, const char *format, ...) +{ + int retcode; + va_list args; /* argument pointer */ + va_start(args, format); + retcode = formatf(fd, fputc_wrapper, format, args); + va_end(args); + return retcode; +} + +int curl_mvsprintf(char *buffer, const char *format, va_list args) +{ + int retcode = formatf(&buffer, storebuffer, format, args); + *buffer = 0; /* we terminate this with a zero byte */ + return retcode; +} + +int curl_mvprintf(const char *format, va_list args) +{ + return formatf(stdout, fputc_wrapper, format, args); +} + +int curl_mvfprintf(FILE *fd, const char *format, va_list args) +{ + return formatf(fd, fputc_wrapper, format, args); +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/mqtt.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/mqtt.c new file mode 100644 index 0000000000..29e92ce5c1 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/mqtt.c @@ -0,0 +1,1032 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) Björn Stenberg, <bjorn@haxx.se> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" + +#ifndef CURL_DISABLE_MQTT + +#include "transfer.h" +#include "sendf.h" +#include "curl_trc.h" +#include "progress.h" +#include "mqtt.h" +#include "select.h" +#include "url.h" +#include "escape.h" +#include "rand.h" +#include "cfilters.h" +#include "connect.h" + +/* first byte is command. + second byte is for flags. */ +#define MQTT_MSG_CONNECT 0x10 +/* #define MQTT_MSG_CONNACK 0x20 */ +#define MQTT_MSG_PUBLISH 0x30 +#define MQTT_MSG_SUBSCRIBE 0x82 +#define MQTT_MSG_SUBACK 0x90 +#define MQTT_MSG_DISCONNECT 0xe0 +/* #define MQTT_MSG_PINGREQ 0xC0 */ +#define MQTT_MSG_PINGRESP 0xD0 + +#define MQTT_CONNACK_LEN 2 +#define MQTT_SUBACK_LEN 3 +#define MQTT_CLIENTID_LEN 12 /* "curl0123abcd" */ + +/* meta key for storing protocol meta at easy handle */ +#define CURL_META_MQTT_EASY "meta:proto:mqtt:easy" +/* meta key for storing protocol meta at connection */ +#define CURL_META_MQTT_CONN "meta:proto:mqtt:conn" + +enum mqttstate { + MQTT_FIRST, /* 0 */ + MQTT_REMAINING_LENGTH, /* 1 */ + MQTT_CONNACK, /* 2 */ + MQTT_SUBACK, /* 3 */ + MQTT_SUBACK_COMING, /* 4 - the SUBACK remainder */ + MQTT_PUBWAIT, /* 5 - wait for publish */ + MQTT_PUB_REMAIN, /* 6 - wait for the remainder of the publish */ + + MQTT_NOSTATE /* 7 - never used an actual state */ +}; + +struct mqtt_conn { + enum mqttstate state; + enum mqttstate nextstate; /* switch to this after remaining length is + done */ + unsigned int packetid; +}; + +/* protocol-specific transfer-related data */ +struct MQTT { + struct dynbuf sendbuf; + /* when receiving */ + struct dynbuf recvbuf; + size_t npacket; /* byte counter */ + size_t remaining_length; + unsigned char pkt_hd[4]; /* for decoding the arriving packet length */ + struct curltime lastTime; /* last time we sent or received data */ + unsigned char firstbyte; + BIT(pingsent); /* 1 while we wait for ping response */ +}; + +static void mqtt_easy_dtor(void *key, size_t klen, void *entry) +{ + struct MQTT *mq = entry; + (void)key; + (void)klen; + curlx_dyn_free(&mq->sendbuf); + curlx_dyn_free(&mq->recvbuf); + curlx_free(mq); +} + +static void mqtt_conn_dtor(void *key, size_t klen, void *entry) +{ + (void)key; + (void)klen; + curlx_free(entry); +} + +static CURLcode mqtt_setup_conn(struct Curl_easy *data, + struct connectdata *conn) +{ + /* setup MQTT specific meta data at easy handle and connection */ + struct mqtt_conn *mqtt; + struct MQTT *mq; + + mqtt = curlx_calloc(1, sizeof(*mqtt)); + if(!mqtt || + Curl_conn_meta_set(conn, CURL_META_MQTT_CONN, mqtt, mqtt_conn_dtor)) + return CURLE_OUT_OF_MEMORY; + + mq = curlx_calloc(1, sizeof(struct MQTT)); + if(!mq) + return CURLE_OUT_OF_MEMORY; + curlx_dyn_init(&mq->recvbuf, DYN_MQTT_RECV); + curlx_dyn_init(&mq->sendbuf, DYN_MQTT_SEND); + if(Curl_meta_set(data, CURL_META_MQTT_EASY, mq, mqtt_easy_dtor)) + return CURLE_OUT_OF_MEMORY; + return CURLE_OK; +} + +static CURLcode mqtt_send(struct Curl_easy *data, + const char *buf, size_t len) +{ + size_t n; + CURLcode result; + struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY); + + if(!mq) + return CURLE_FAILED_INIT; + + result = Curl_xfer_send(data, buf, len, FALSE, &n); + if(result) + return result; + mq->lastTime = *Curl_pgrs_now(data); + Curl_debug(data, CURLINFO_HEADER_OUT, buf, n); + if(len != n) { + size_t nsend = len - n; + if(curlx_dyn_len(&mq->sendbuf)) { + DEBUGASSERT(curlx_dyn_len(&mq->sendbuf) >= nsend); + result = curlx_dyn_tail(&mq->sendbuf, nsend); /* keep this much */ + } + else { + result = curlx_dyn_addn(&mq->sendbuf, &buf[n], nsend); + } + } + else + curlx_dyn_reset(&mq->sendbuf); + return result; +} + +/* Generic function called by the multi interface to figure out what socket(s) + to wait for and for what actions during the DOING and PROTOCONNECT + states */ +static CURLcode mqtt_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + return Curl_pollset_add_in(data, ps, data->conn->sock[FIRSTSOCKET]); +} + +static int mqtt_encode_len(char *buf, size_t len) +{ + int i; + + for(i = 0; (len > 0) && (i < 4); i++) { + unsigned char encoded; + encoded = len % 0x80; + len /= 0x80; + if(len) + encoded |= 0x80; + buf[i] = (char)encoded; + } + + return i; +} + +/* add the passwd to the CONNECT packet */ +static int add_passwd(const char *passwd, const size_t plen, + char *pkt, const size_t start, int remain_pos) +{ + /* magic number that need to be set properly */ + const size_t conn_flags_pos = remain_pos + 8; + if(plen > 0xffff) + return 1; + + /* set password flag */ + pkt[conn_flags_pos] |= 0x40; + + /* length of password provided */ + pkt[start] = (char)((plen >> 8) & 0xFF); + pkt[start + 1] = (char)(plen & 0xFF); + memcpy(&pkt[start + 2], passwd, plen); + return 0; +} + +/* add user to the CONNECT packet */ +static int add_user(const char *username, const size_t ulen, + unsigned char *pkt, const size_t start, int remain_pos) +{ + /* magic number that need to be set properly */ + const size_t conn_flags_pos = remain_pos + 8; + if(ulen > 0xffff) + return 1; + + /* set username flag */ + pkt[conn_flags_pos] |= 0x80; + /* length of username provided */ + pkt[start] = (unsigned char)((ulen >> 8) & 0xFF); + pkt[start + 1] = (unsigned char)(ulen & 0xFF); + memcpy(&pkt[start + 2], username, ulen); + return 0; +} + +/* add client ID to the CONNECT packet */ +static int add_client_id(const char *client_id, const size_t client_id_len, + char *pkt, const size_t start) +{ + if(client_id_len != MQTT_CLIENTID_LEN) + return 1; + pkt[start] = 0x00; + pkt[start + 1] = MQTT_CLIENTID_LEN; + memcpy(&pkt[start + 2], client_id, MQTT_CLIENTID_LEN); + return 0; +} + +/* Set initial values of CONNECT packet */ +static int init_connpack(char *packet, char *remain, int remain_pos) +{ + /* Fixed header starts */ + /* packet type */ + packet[0] = MQTT_MSG_CONNECT; + /* remaining length field */ + memcpy(&packet[1], remain, remain_pos); + /* Fixed header ends */ + + /* Variable header starts */ + /* protocol length */ + packet[remain_pos + 1] = 0x00; + packet[remain_pos + 2] = 0x04; + /* protocol name */ + packet[remain_pos + 3] = 'M'; + packet[remain_pos + 4] = 'Q'; + packet[remain_pos + 5] = 'T'; + packet[remain_pos + 6] = 'T'; + /* protocol level */ + packet[remain_pos + 7] = 0x04; + /* CONNECT flag: CleanSession */ + packet[remain_pos + 8] = 0x02; + /* keep-alive 0 = disabled */ + packet[remain_pos + 9] = 0x00; + packet[remain_pos + 10] = 0x3c; + /* end of variable header */ + return remain_pos + 10; +} + +static CURLcode mqtt_connect(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + int pos = 0; + int rc = 0; + /* remain length */ + int remain_pos = 0; + char remain[4] = { 0 }; + size_t packetlen = 0; + size_t start_user = 0; + size_t start_pwd = 0; + char client_id[MQTT_CLIENTID_LEN + 1] = "curl"; + const size_t clen = CURL_CSTRLEN("curl"); + char *packet = NULL; + + /* extracting username from request */ + struct Curl_creds *creds = data->state.creds; + const size_t ulen = creds ? strlen(creds->user) : 0; + const size_t plen = creds ? strlen(creds->passwd) : 0; + const size_t payloadlen = ulen + plen + MQTT_CLIENTID_LEN + 2 + + /* The plus 2s below are for the MSB and LSB describing the length of the + string to be added on the payload. Refer to spec 1.5.2 and 1.5.4 */ + (ulen ? 2 : 0) + + (plen ? 2 : 0); + + /* getting how much occupy the remain length */ + remain_pos = mqtt_encode_len(remain, payloadlen + 10); + + /* 10 length of variable header and 1 the first byte of the fixed header */ + packetlen = payloadlen + 10 + remain_pos + 1; + + /* allocating packet */ + if(packetlen > 0xFFFFFFF) + return CURLE_WEIRD_SERVER_REPLY; + packet = curlx_calloc(1, packetlen); + if(!packet) + return CURLE_OUT_OF_MEMORY; + + /* set initial values for the CONNECT packet */ + pos = init_connpack(packet, remain, remain_pos); + + result = Curl_rand_alnum(data, (unsigned char *)&client_id[clen], + MQTT_CLIENTID_LEN - clen + 1); + /* add client id */ + rc = add_client_id(client_id, strlen(client_id), packet, pos + 1); + if(rc) { + failf(data, "Client ID length mismatched: [%zu]", strlen(client_id)); + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } + infof(data, "Using client id '%s'", client_id); + + /* position where the user payload starts */ + start_user = pos + 3 + MQTT_CLIENTID_LEN; + /* position where the password payload starts */ + start_pwd = start_user + ulen; + /* if username was provided, add it to the packet */ + if(ulen) { + start_pwd += 2; + + rc = add_user(creds->user, ulen, + (unsigned char *)packet, start_user, remain_pos); + if(rc) { + failf(data, "Username too long: [%zu]", ulen); + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } + } + + /* if passwd was provided, add it to the packet */ + if(plen) { + rc = add_passwd(creds->passwd, plen, packet, start_pwd, remain_pos); + if(rc) { + failf(data, "Password too long: [%zu]", plen); + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } + } + + if(!result) + result = mqtt_send(data, packet, packetlen); + +end: + if(packet) { + curlx_memzero(packet, packetlen); + curlx_free(packet); + } + Curl_creds_unlink(&data->state.creds); + return result; +} + +static CURLcode mqtt_disconnect(struct Curl_easy *data) +{ + return mqtt_send(data, "\xe0\x00", 2); +} + +static CURLcode mqtt_recv_atleast(struct Curl_easy *data, size_t nbytes) +{ + struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY); + size_t rlen; + CURLcode result; + + if(!mq) + return CURLE_FAILED_INIT; + rlen = curlx_dyn_len(&mq->recvbuf); + + if(rlen < nbytes) { + unsigned char readbuf[1024]; + size_t nread; + + DEBUGASSERT(nbytes - rlen < sizeof(readbuf)); + result = Curl_xfer_recv(data, (char *)readbuf, nbytes - rlen, &nread); + if(result) + return result; + if(!nread) /* EOF */ + return CURLE_RECV_ERROR; + if(curlx_dyn_addn(&mq->recvbuf, readbuf, nread)) + return CURLE_OUT_OF_MEMORY; + rlen = curlx_dyn_len(&mq->recvbuf); + } + return (rlen >= nbytes) ? CURLE_OK : CURLE_AGAIN; +} + +static void mqtt_recv_consume(struct Curl_easy *data, size_t nbytes) +{ + struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY); + DEBUGASSERT(mq); + if(mq) { + size_t rlen = curlx_dyn_len(&mq->recvbuf); + if(rlen <= nbytes) + curlx_dyn_reset(&mq->recvbuf); + else + curlx_dyn_tail(&mq->recvbuf, rlen - nbytes); + } +} + +static CURLcode mqtt_verify_connack(struct Curl_easy *data) +{ + struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY); + CURLcode result; + const char *ptr; + + DEBUGASSERT(mq); + if(!mq) + return CURLE_FAILED_INIT; + if(mq->remaining_length != 2) { + failf(data, "CONNACK expected Remaining Length 2, got %zu", + mq->remaining_length); + return CURLE_WEIRD_SERVER_REPLY; + } + + result = mqtt_recv_atleast(data, MQTT_CONNACK_LEN); + if(result) + return result; + + /* verify CONNACK */ + DEBUGASSERT(curlx_dyn_len(&mq->recvbuf) >= MQTT_CONNACK_LEN); + ptr = curlx_dyn_ptr(&mq->recvbuf); + Curl_debug(data, CURLINFO_HEADER_IN, ptr, MQTT_CONNACK_LEN); + + if(ptr[0] != 0x00 || ptr[1] != 0x00) { + failf(data, "Expected %02x%02x but got %02x%02x", + 0x00U, 0x00U, (unsigned char)ptr[0], (unsigned char)ptr[1]); + curlx_dyn_reset(&mq->recvbuf); + return CURLE_WEIRD_SERVER_REPLY; + } + mqtt_recv_consume(data, MQTT_CONNACK_LEN); + return CURLE_OK; +} + +static CURLcode mqtt_get_topic(struct Curl_easy *data, + char **topic, size_t *topiclen) +{ + const char *path = data->state.up.path; + CURLcode result = CURLE_URL_MALFORMAT; + if(strlen(path) > 1) { + result = Curl_urldecode(path + 1, 0, topic, topiclen, REJECT_CTRL); + if(!result && (*topiclen > 0xffff)) { + failf(data, "Too long MQTT topic"); + result = CURLE_URL_MALFORMAT; + } + } + else + failf(data, "No MQTT topic found. Forgot to URL encode it?"); + + return result; +} + +static CURLcode mqtt_subscribe(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + char *topic = NULL; + size_t topiclen; + unsigned char *packet = NULL; + size_t packetlen; + char encodedsize[4]; + size_t n; + struct connectdata *conn = data->conn; + struct mqtt_conn *mqtt = Curl_conn_meta_get(conn, CURL_META_MQTT_CONN); + + if(!mqtt) + return CURLE_FAILED_INIT; + + result = mqtt_get_topic(data, &topic, &topiclen); + if(result) + goto fail; + + mqtt->packetid++; + + packetlen = topiclen + 5; /* packetid + topic (has a two byte length field) + + 2 bytes topic length + QoS byte */ + n = mqtt_encode_len((char *)encodedsize, packetlen); + packetlen += n + 1; /* add one for the control packet type byte */ + + packet = curlx_malloc(packetlen); + if(!packet) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + packet[0] = MQTT_MSG_SUBSCRIBE; + memcpy(&packet[1], encodedsize, n); + packet[1 + n] = (mqtt->packetid >> 8) & 0xff; + packet[2 + n] = mqtt->packetid & 0xff; + packet[3 + n] = (topiclen >> 8) & 0xff; + packet[4 + n] = topiclen & 0xff; + memcpy(&packet[5 + n], topic, topiclen); + packet[5 + n + topiclen] = 0; /* QoS zero */ + + result = mqtt_send(data, (const char *)packet, packetlen); + +fail: + curlx_free(topic); + curlx_free(packet); + return result; +} + +/* + * Called when the first byte was already read. + */ +static CURLcode mqtt_verify_suback(struct Curl_easy *data) +{ + struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY); + struct connectdata *conn = data->conn; + struct mqtt_conn *mqtt = Curl_conn_meta_get(conn, CURL_META_MQTT_CONN); + CURLcode result; + const char *ptr; + + if(!mqtt || !mq) + return CURLE_FAILED_INIT; + + if(mq->remaining_length != 3) { + failf(data, "SUBACK expected Remaining Length 3, got %zu", + mq->remaining_length); + return CURLE_WEIRD_SERVER_REPLY; + } + + result = mqtt_recv_atleast(data, MQTT_SUBACK_LEN); + if(result) + goto fail; + + /* verify SUBACK */ + DEBUGASSERT(curlx_dyn_len(&mq->recvbuf) >= MQTT_SUBACK_LEN); + ptr = curlx_dyn_ptr(&mq->recvbuf); + Curl_debug(data, CURLINFO_HEADER_IN, ptr, MQTT_SUBACK_LEN); + + if(((unsigned char)ptr[0]) != ((mqtt->packetid >> 8) & 0xff) || + ((unsigned char)ptr[1]) != (mqtt->packetid & 0xff) || + ptr[2] != 0x00) { + curlx_dyn_reset(&mq->recvbuf); + result = CURLE_WEIRD_SERVER_REPLY; + goto fail; + } + mqtt_recv_consume(data, MQTT_SUBACK_LEN); +fail: + return result; +} + +#define MAX_MQTT_MESSAGE_SIZE 0xFFFFFFF + +static CURLcode mqtt_publish(struct Curl_easy *data) +{ + CURLcode result; + char *payload = data->set.postfields; + size_t payloadlen; + char *topic = NULL; + size_t topiclen; + unsigned char *pkt = NULL; + size_t i = 0; + size_t remaininglength; + size_t encodelen; + char encodedbytes[4]; + curl_off_t postfieldsize = data->set.postfieldsize; + + if(!payload) { + DEBUGF(infof(data, "mqtt_publish without payload, return bad arg")); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if(!curlx_sotouz_fits(postfieldsize, &payloadlen)) { + if(postfieldsize > 0) /* off_t does not fit into size_t */ + return CURLE_BAD_FUNCTION_ARGUMENT; + payloadlen = strlen(payload); + } + + result = mqtt_get_topic(data, &topic, &topiclen); + if(result) + goto fail; + + remaininglength = payloadlen + 2 + topiclen; + encodelen = mqtt_encode_len(encodedbytes, remaininglength); + if(remaininglength > (MAX_MQTT_MESSAGE_SIZE - encodelen - 1)) { + result = CURLE_TOO_LARGE; + goto fail; + } + + /* add the control byte and the encoded remaining length */ + pkt = curlx_malloc(remaininglength + 1 + encodelen); + if(!pkt) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + /* assemble packet */ + pkt[i++] = MQTT_MSG_PUBLISH; + memcpy(&pkt[i], encodedbytes, encodelen); + i += encodelen; + pkt[i++] = (topiclen >> 8) & 0xff; + pkt[i++] = (topiclen & 0xff); + memcpy(&pkt[i], topic, topiclen); + i += topiclen; + memcpy(&pkt[i], payload, payloadlen); + i += payloadlen; + result = mqtt_send(data, (const char *)pkt, i); + +fail: + curlx_free(pkt); + curlx_free(topic); + return result; +} + +/* return FALSE on success, TRUE on error */ +static bool mqtt_decode_len(size_t *lenp, const unsigned char *buf, + size_t buflen) +{ + size_t len = 0; + size_t mult = 1; + size_t i; + unsigned char encoded = 128; + + for(i = 0; (i < buflen) && (encoded & 128); i++) { + if(i == 4) + return TRUE; /* bad size */ + encoded = buf[i]; + len += (encoded & 127) * mult; + mult *= 128; + } + if(encoded & 128) + /* truncated size */ + return TRUE; + + *lenp = len; + return FALSE; +} + +#if defined(DEBUGBUILD) && defined(CURLVERBOSE) +static const char * const statenames[] = { + "MQTT_FIRST", + "MQTT_REMAINING_LENGTH", + "MQTT_CONNACK", + "MQTT_SUBACK", + "MQTT_SUBACK_COMING", + "MQTT_PUBWAIT", + "MQTT_PUB_REMAIN", + + "NOT A STATE" +}; +#endif + +/* The only way to change state */ +static void mqstate(struct Curl_easy *data, + enum mqttstate state, + enum mqttstate nextstate) /* used if state == FIRST */ +{ + struct connectdata *conn = data->conn; + struct mqtt_conn *mqtt = Curl_conn_meta_get(conn, CURL_META_MQTT_CONN); + DEBUGASSERT(mqtt); + if(!mqtt) + return; +#ifdef DEBUGBUILD + infof(data, "%s (from %s) (next is %s)", + statenames[state], + statenames[mqtt->state], + (state == MQTT_FIRST) ? statenames[nextstate] : ""); +#endif + mqtt->state = state; + if(state == MQTT_FIRST) + mqtt->nextstate = nextstate; +} + +static CURLcode mqtt_read_publish(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + size_t nread; + size_t remlen; + struct mqtt_conn *mqtt = Curl_conn_meta_get(conn, CURL_META_MQTT_CONN); + struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY); + unsigned char packet; + + DEBUGASSERT(mqtt); + if(!mqtt || !mq) + return CURLE_FAILED_INIT; + + switch(mqtt->state) { +MQTT_SUBACK_COMING: + case MQTT_SUBACK_COMING: + result = mqtt_verify_suback(data); + if(result) + break; + + mqstate(data, MQTT_FIRST, MQTT_PUBWAIT); + break; + + case MQTT_SUBACK: + case MQTT_PUBWAIT: + /* we are expecting PUBLISH or SUBACK */ + packet = mq->firstbyte & 0xf0; + if(packet == MQTT_MSG_PUBLISH) + mqstate(data, MQTT_PUB_REMAIN, MQTT_NOSTATE); + else if(packet == MQTT_MSG_SUBACK) { + mqstate(data, MQTT_SUBACK_COMING, MQTT_NOSTATE); + goto MQTT_SUBACK_COMING; + } + else if(packet == MQTT_MSG_DISCONNECT) { + infof(data, "Got DISCONNECT"); + *done = TRUE; + goto end; + } + else { + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } + + /* -- switched state -- */ + remlen = mq->remaining_length; + infof(data, "Remaining length: %zu bytes", remlen); + if(data->set.max_filesize && + (curl_off_t)remlen > data->set.max_filesize) { + failf(data, "Maximum file size exceeded"); + result = CURLE_FILESIZE_EXCEEDED; + goto end; + } + Curl_pgrsSetDownloadSize(data, remlen); + data->req.bytecount = 0; + data->req.size = remlen; + mq->npacket = remlen; /* get this many bytes */ + FALLTHROUGH(); + case MQTT_PUB_REMAIN: { + /* read rest of packet, but no more. Cap to buffer size */ + char buffer[4 * 1024]; + size_t rest = mq->npacket; + if(rest > sizeof(buffer)) + rest = sizeof(buffer); + result = Curl_xfer_recv(data, buffer, rest, &nread); + if(result) { + if(result == CURLE_AGAIN) { + infof(data, "EEEE AAAAGAIN"); + } + goto end; + } + if(!nread) { + infof(data, "server disconnected"); + result = CURLE_PARTIAL_FILE; + goto end; + } + + /* we received something */ + mq->lastTime = *Curl_pgrs_now(data); + + /* if QoS is set, message contains packet id */ + result = Curl_client_write(data, CLIENTWRITE_BODY, buffer, nread); + if(result) + goto end; + + mq->npacket -= nread; + if(!mq->npacket) + /* no more PUBLISH payload, back to subscribe wait state */ + mqstate(data, MQTT_FIRST, MQTT_PUBWAIT); + break; + } + default: + DEBUGASSERT(NULL); /* illegal state */ + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } +end: + return result; +} + +static CURLcode mqtt_do(struct Curl_easy *data, bool *done) +{ + struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY); + CURLcode result = CURLE_OK; + *done = FALSE; /* unconditionally */ + + if(!mq) + return CURLE_FAILED_INIT; + mq->lastTime = *Curl_pgrs_now(data); + mq->pingsent = FALSE; + + result = mqtt_connect(data); + if(result) { + failf(data, "Error %d sending MQTT CONNECT request", (int)result); + return result; + } + mqstate(data, MQTT_FIRST, MQTT_CONNACK); + return CURLE_OK; +} + +static CURLcode mqtt_done(struct Curl_easy *data, + CURLcode status, bool premature) +{ + struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY); + (void)status; + (void)premature; + if(mq) { + curlx_dyn_free(&mq->sendbuf); + curlx_dyn_free(&mq->recvbuf); + } + return CURLE_OK; +} + +/* we ping regularly to avoid being disconnected by the server */ +static CURLcode mqtt_ping(struct Curl_easy *data) +{ + struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY); + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct mqtt_conn *mqtt = Curl_conn_meta_get(conn, CURL_META_MQTT_CONN); + + if(!mqtt || !mq) + return CURLE_FAILED_INIT; + + if(mqtt->state == MQTT_FIRST && + !mq->pingsent && + data->set.upkeep_interval_ms > 0) { + struct curltime t = *Curl_pgrs_now(data); + timediff_t diff = curlx_ptimediff_ms(&t, &mq->lastTime); + + if(diff > data->set.upkeep_interval_ms) { + /* 0xC0 is PINGREQ, and 0x00 is remaining length */ + unsigned char packet[2] = { 0xC0, 0x00 }; + size_t packetlen = sizeof(packet); + + result = mqtt_send(data, (char *)packet, packetlen); + if(!result) { + mq->pingsent = TRUE; + } + infof(data, "mqtt_ping: sent ping request."); + } + } + return result; +} + +static CURLcode mqtt_doing(struct Curl_easy *data, bool *done) +{ + struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY); + CURLcode result = CURLE_OK; + size_t nread; + unsigned char recvbyte; + struct mqtt_conn *mqtt = Curl_conn_meta_get(data->conn, CURL_META_MQTT_CONN); + + if(!mqtt || !mq) + return CURLE_FAILED_INIT; + + *done = FALSE; + + if(curlx_dyn_len(&mq->sendbuf)) { + /* send the remainder of an outgoing packet */ + result = mqtt_send(data, curlx_dyn_ptr(&mq->sendbuf), + curlx_dyn_len(&mq->sendbuf)); + if(result) + return result; + } + + result = mqtt_ping(data); + if(result) + return result; + + infof(data, "mqtt_doing: state [%d]", (int)mqtt->state); + switch(mqtt->state) { + case MQTT_FIRST: + /* Read the initial byte only */ + result = Curl_xfer_recv(data, (char *)&mq->firstbyte, 1, &nread); + if(result) + break; + else if(!nread) { + failf(data, "Connection disconnected"); + *done = TRUE; + result = CURLE_RECV_ERROR; + break; + } + Curl_debug(data, CURLINFO_HEADER_IN, (const char *)&mq->firstbyte, 1); + + /* we received something */ + mq->lastTime = *Curl_pgrs_now(data); + + /* remember the first byte */ + mq->npacket = 0; + mqstate(data, MQTT_REMAINING_LENGTH, MQTT_NOSTATE); + FALLTHROUGH(); + case MQTT_REMAINING_LENGTH: + do { + result = Curl_xfer_recv(data, (char *)&recvbyte, 1, &nread); + if(result || !nread) + break; + Curl_debug(data, CURLINFO_HEADER_IN, (const char *)&recvbyte, 1); + mq->pkt_hd[mq->npacket++] = recvbyte; + } while((recvbyte & 0x80) && (mq->npacket < 4)); + if(!result && nread && (recvbyte & 0x80)) + /* MQTT supports up to 127 * 128^0 + 127 * 128^1 + 127 * 128^2 + + 127 * 128^3 bytes. server tried to send more */ + result = CURLE_WEIRD_SERVER_REPLY; + if(result) + break; + if(mqtt_decode_len(&mq->remaining_length, mq->pkt_hd, mq->npacket)) { + result = CURLE_WEIRD_SERVER_REPLY; + break; + } + mq->npacket = 0; + /* PINGRESP and DISCONNECT must have remaining_length == 0 and + * reserved bits (low nibble) must be zero per MQTT 3.1.1 + * sections 2.2.2, 3.13.1 and 3.14.1. Reject before state + * dispatch to prevent nextstate confusion. */ + { + const unsigned char type = mq->firstbyte & 0xF0; + const unsigned char reserved = mq->firstbyte & 0x0F; + if((type == MQTT_MSG_DISCONNECT || type == MQTT_MSG_PINGRESP) && + (mq->remaining_length || reserved)) { + failf(data, + "Broker sent malformed %s " + "(remaining_length=%zu, header byte=0x%02x)", + type == MQTT_MSG_DISCONNECT ? "DISCONNECT" : "PINGRESP", + mq->remaining_length, mq->firstbyte); + result = CURLE_WEIRD_SERVER_REPLY; + break; + } + } + if(mq->remaining_length) { + mqstate(data, mqtt->nextstate, MQTT_NOSTATE); + break; + } + mqstate(data, MQTT_FIRST, MQTT_FIRST); + + if(mq->firstbyte == MQTT_MSG_DISCONNECT) { + infof(data, "Got DISCONNECT"); + *done = TRUE; + } + + /* ping response */ + if(mq->firstbyte == MQTT_MSG_PINGRESP) { + infof(data, "Received ping response."); + mq->pingsent = FALSE; + mqstate(data, MQTT_FIRST, MQTT_PUBWAIT); + } + break; + case MQTT_CONNACK: + result = mqtt_verify_connack(data); + if(result) + break; + + if(data->state.httpreq == HTTPREQ_POST) { + result = mqtt_publish(data); + if(!result) { + result = mqtt_disconnect(data); + *done = TRUE; + } + mqtt->nextstate = MQTT_FIRST; + } + else { + result = mqtt_subscribe(data); + if(!result) { + mqstate(data, MQTT_FIRST, MQTT_SUBACK); + } + } + break; + + case MQTT_SUBACK: + case MQTT_PUBWAIT: + case MQTT_PUB_REMAIN: + result = mqtt_read_publish(data, done); + break; + + default: + failf(data, "State not handled yet"); + *done = TRUE; + break; + } + + if(result == CURLE_AGAIN) + result = CURLE_OK; + return result; +} + +#ifdef USE_SSL + +static CURLcode mqtts_connecting(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + CURLcode result; + + result = Curl_conn_connect(data, FIRSTSOCKET, TRUE, done); + if(result) + connclose(conn); + return result; +} + +/* + * MQTTS protocol. + */ +const struct Curl_protocol Curl_protocol_mqtts = { + mqtt_setup_conn, /* setup_connection */ + mqtt_do, /* do_it */ + mqtt_done, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + mqtts_connecting, /* connecting */ + mqtt_doing, /* doing */ + ZERO_NULL, /* proto_pollset */ + mqtt_pollset, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#endif + +/* + * MQTT protocol. + */ +const struct Curl_protocol Curl_protocol_mqtt = { + mqtt_setup_conn, /* setup_connection */ + mqtt_do, /* do_it */ + mqtt_done, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + mqtt_doing, /* doing */ + ZERO_NULL, /* proto_pollset */ + mqtt_pollset, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#endif /* CURL_DISABLE_MQTT */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/mqtt.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/mqtt.h new file mode 100644 index 0000000000..3d95293f12 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/mqtt.h @@ -0,0 +1,33 @@ +#ifndef HEADER_CURL_MQTT_H +#define HEADER_CURL_MQTT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Björn Stenberg, <bjorn@haxx.se> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_MQTT +extern const struct Curl_protocol Curl_protocol_mqtt; +#ifdef USE_SSL +extern const struct Curl_protocol Curl_protocol_mqtts; +#endif +#endif + +#endif /* HEADER_CURL_MQTT_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi.c new file mode 100644 index 0000000000..fbefa6f30d --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi.c @@ -0,0 +1,4272 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "transfer.h" +#include "url.h" +#include "cfilters.h" +#include "connect.h" +#include "progress.h" +#include "curl_share.h" +#include "psl.h" +#include "multiif.h" +#include "multi_ev.h" +#include "sendf.h" +#include "curl_trc.h" +#include "http.h" +#include "select.h" +#include "curlx/wait.h" +#include "conncache.h" +#include "multihandle.h" +#include "sigpipe.h" +#include "vtls/vtls.h" +#include "vtls/vtls_scache.h" +#include "http_proxy.h" +#include "http2.h" +#include "socketpair.h" +#include "bufref.h" + +/* initial multi->xfers table size for a full multi */ +#define CURL_XFER_TABLE_SIZE 128 + +/* CURL_SOCKET_HASH_TABLE_SIZE should be a prime number. Increasing it from 97 + to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every + curl handle takes 6K memory, therefore this 3K are not significant. */ +#ifndef CURL_SOCKET_HASH_TABLE_SIZE +#define CURL_SOCKET_HASH_TABLE_SIZE 911 +#endif + +#ifndef CURL_CONNECTION_HASH_SIZE +#define CURL_CONNECTION_HASH_SIZE 97 +#endif + +#ifndef CURL_DNS_HASH_SIZE +#define CURL_DNS_HASH_SIZE 71 +#endif + +#ifndef CURL_TLS_SESSION_SIZE +#define CURL_TLS_SESSION_SIZE 25 +#endif + +static void move_pending_to_connect(struct Curl_multi *multi, + struct Curl_easy *data); +static CURLMcode add_next_timeout(const struct curltime *pnow, + struct Curl_multi *multi, + struct Curl_easy *data); +static void multi_timeout(struct Curl_multi *multi, + timediff_t *pexire_offset_us, + int *timeout_ms); +static void multi_schedule_pending(struct Curl_multi *multi); +static void multi_xfer_bufs_free(struct Curl_multi *multi); +#ifdef DEBUGBUILD +static void multi_xfer_tbl_dump(struct Curl_multi *multi); +#endif + +static const struct curltime *multi_now(struct Curl_multi *multi) +{ + curlx_pnow(&multi->now); + return &multi->now; +} + +/* function pointer called once when entering a state */ +typedef void (*mstate_enter_func)(struct Curl_easy *data, + CURLMstate from_state); + +static void mstate_enter_connect(struct Curl_easy *data, + CURLMstate from_state) +{ + (void)from_state; + Curl_init_CONNECT(data); +} + +static void mstate_enter_did(struct Curl_easy *data, + CURLMstate from_state) +{ + (void)from_state; + data->req.chunk = FALSE; + Curl_pgrsTime(data, TIMER_PRETRANSFER); + if(!CURL_REQ_WANT_SEND(data)) + Curl_pgrsTime(data, TIMER_POSTRANSFER); +} + +static void mstate_enter_done(struct Curl_easy *data, + CURLMstate from_state) +{ + (void)from_state; + CURLM_NTFY(data, CURLMNOTIFY_EASY_DONE); +} + +static void mstate_enter_completed(struct Curl_easy *data, + CURLMstate from_state) +{ + /* we sometimes directly jump to COMPLETED, trigger things + * we then missed. */ + if(from_state < MSTATE_DID) { + Curl_pgrsTime(data, TIMER_PRETRANSFER); + Curl_pgrsTime(data, TIMER_POSTRANSFER); + Curl_pgrsTime(data, TIMER_STARTTRANSFER); + } + Curl_pgrsCompleted(data); + if(from_state < MSTATE_DONE) + CURLM_NTFY(data, CURLMNOTIFY_EASY_DONE); + /* changing to COMPLETED means it is in process and needs to go */ + DEBUGASSERT(Curl_uint32_bset_contains(&data->multi->process, data->mid)); + Curl_uint32_bset_remove(&data->multi->process, data->mid); + Curl_uint32_bset_remove(&data->multi->pending, data->mid); /* to be sure */ + + if(Curl_uint32_bset_empty(&data->multi->process)) { + /* free the transfer buffer when we have no more active transfers */ + multi_xfer_bufs_free(data->multi); + } + /* Important: reset the conn pointer so that we do not point to memory + that could be freed anytime */ + Curl_detach_connection(data); + Curl_expire_clear_all(data); /* stop all timers */ +} + +/* always use this function to change state, to make debugging easier */ +static void mstate(struct Curl_easy *data, CURLMstate state +#ifdef DEBUGBUILD + , int lineno +#endif +) +{ + CURLMstate oldstate = data->mstate; + static const mstate_enter_func state_enter[MSTATE_LAST] = { + NULL, /* INIT */ + NULL, /* PENDING */ + NULL, /* SETUP */ + mstate_enter_connect, /* CONNECT */ + NULL, /* CONNECTING */ + NULL, /* PROTOCONNECT */ + NULL, /* PROTOCONNECTING */ + NULL, /* DO */ + NULL, /* DOING */ + NULL, /* DOING_MORE */ + mstate_enter_did, /* DID */ + NULL, /* PERFORMING */ + NULL, /* RATELIMITING */ + mstate_enter_done, /* DONE */ + mstate_enter_completed, /* COMPLETED */ + NULL /* MSGSENT */ + }; + + if(oldstate == state) + /* do not bother when the new state is the same as the old state */ + return; + +#ifdef DEBUGBUILD + NOVERBOSE((void)lineno); + CURL_TRC_M(data, "-> [%s] (line %d)", CURL_MSTATE_NAME(state), lineno); +#else + CURL_TRC_M(data, "-> [%s]", CURL_MSTATE_NAME(state)); +#endif + + /* really switching state */ + data->mstate = state; + if(state_enter[state]) + state_enter[state](data, oldstate); +} + +#ifndef DEBUGBUILD +#define multistate(x, y) mstate(x, y) +#else +#define multistate(x, y) mstate(x, y, __LINE__) +#endif + +/* multi->proto_hash destructor. Should never be called as elements + * MUST be added with their own destructor */ +static void ph_freeentry(void *p) +{ + (void)p; + /* Always FALSE. Cannot use a 0 assert here since compilers + * are not in agreement if they then want a NORETURN attribute or + * not. *sigh* */ + DEBUGASSERT(!p); +} + +/* + * multi_addmsg() + * + * Called when a transfer is completed. Adds the given msg pointer to + * the list kept in the multi handle. + */ +static void multi_addmsg(struct Curl_multi *multi, struct Curl_message *msg) +{ + if(!Curl_llist_count(&multi->msglist)) + CURLM_NTFY(multi->admin, CURLMNOTIFY_INFO_READ); + Curl_llist_append(&multi->msglist, msg, &msg->list); +} + +static void multi_timeouts_init(struct Curl_easy *data); + +struct Curl_multi *Curl_multi_handle(uint32_t xfer_table_size, + size_t ev_hashsize, /* event hash */ + size_t chashsize, /* connection hash */ + size_t dnssize, /* dns hash */ + size_t sesssize) /* TLS session cache */ +{ + struct Curl_multi *multi = curlx_calloc(1, sizeof(struct Curl_multi)); + + if(!multi) + return NULL; + + multi->magic = CURLMULTI_MAGIC_NUMBER; + + /* Initialisation order is important here! + * easy_init() does a lazy check on curl_global_init() which sets + * up platform specific things we need. For example calling curlx_pnow() + * before this is not safe. */ + multi->admin = curl_easy_init(); + if(!multi->admin) { + curlx_free(multi); + return NULL; + } + multi->admin->multi = multi; + multi->admin->state.internal = TRUE; + + /* Now we can use curlx_* things safely */ + curlx_pnow(&multi->now); + Curl_timeouts_init(&multi->timeouts, &multi->now); + multi_timeouts_init(multi->admin); + + Curl_dnscache_init(&multi->dnscache, dnssize); + Curl_mntfy_init(multi); + Curl_multi_ev_init(multi, ev_hashsize); + Curl_uint32_tbl_init(&multi->xfers, NULL); + Curl_uint32_bset_init(&multi->process); + Curl_uint32_bset_init(&multi->dirty); + Curl_uint32_bset_init(&multi->pending); + Curl_uint32_bset_init(&multi->msgsent); + Curl_hash_init(&multi->proto_hash, 23, + Curl_hash_str, curlx_str_key_compare, ph_freeentry); + Curl_llist_init(&multi->msglist, NULL); + + multi->multiplexing = TRUE; + multi->max_concurrent_streams = 100; + multi->last_timeout_ms = -1; +#ifdef ENABLE_WAKEUP + multi->wakeup_pair[0] = CURL_SOCKET_BAD; + multi->wakeup_pair[1] = CURL_SOCKET_BAD; +#endif +#ifdef ENABLE_INTERNAL_WAKEUP + multi->wakeup_internal[0] = CURL_SOCKET_BAD; + multi->wakeup_internal[1] = CURL_SOCKET_BAD; +#endif + + if(Curl_mntfy_resize(multi) || + Curl_uint32_bset_resize(&multi->process, xfer_table_size) || + Curl_uint32_bset_resize(&multi->pending, xfer_table_size) || + Curl_uint32_bset_resize(&multi->dirty, xfer_table_size) || + Curl_uint32_bset_resize(&multi->msgsent, xfer_table_size) || + Curl_uint32_tbl_resize(&multi->xfers, xfer_table_size)) + goto error; + +#ifdef DEBUGBUILD + if(getenv("CURL_DEBUG")) + multi->admin->set.verbose = TRUE; +#endif + Curl_uint32_tbl_add(&multi->xfers, multi->admin, &multi->admin->mid); + Curl_uint32_bset_add(&multi->process, multi->admin->mid); + + if(Curl_cshutdn_init(&multi->cshutdn, multi)) + goto error; + + Curl_cpool_init(&multi->cpool, NULL, chashsize); + +#ifdef USE_SSL + if(Curl_ssl_scache_create(sesssize, 2, &multi->ssl_scache)) + goto error; +#else + (void)sesssize; +#endif + +#ifdef USE_WINSOCK + multi->wsa_event = WSACreateEvent(); + if(multi->wsa_event == WSA_INVALID_EVENT) + goto error; +#endif +#ifdef ENABLE_WAKEUP + /* When enabled, rely on this to work. We ignore this in previous + * versions, but that seems an unnecessary complication. */ + if(Curl_wakeup_init(multi->wakeup_pair, TRUE) < 0) + goto error; +#endif +#ifdef ENABLE_INTERNAL_WAKEUP + if(Curl_wakeup_init(multi->wakeup_internal, TRUE) < 0) + goto error; +#endif + + if(Curl_probeipv6(multi)) + goto error; + +#ifdef USE_RESOLV_THREADED + if(xfer_table_size < CURL_XFER_TABLE_SIZE) { /* easy multi */ + if(Curl_async_thrdd_multi_init(multi, 0, 2, 10)) + goto error; + } + else { /* real multi handle */ + if(Curl_async_thrdd_multi_init(multi, 0, 20, 2000)) + goto error; + } +#endif + + return multi; + +error: + +#ifdef USE_RESOLV_THREADED + Curl_async_thrdd_multi_destroy(multi, TRUE); +#endif + Curl_multi_ev_cleanup(multi); + Curl_hash_destroy(&multi->proto_hash); + Curl_dnscache_destroy(&multi->dnscache); + Curl_cpool_destroy(&multi->cpool, multi->admin); + Curl_cshutdn_destroy(&multi->cshutdn, multi->admin); +#ifdef USE_SSL + Curl_ssl_scache_destroy(multi->ssl_scache); +#endif + if(multi->admin) { + Curl_multi_ev_xfer_done(multi, multi->admin); + multi->admin->multi = NULL; + Curl_close(&multi->admin); + } + Curl_mntfy_cleanup(multi); + + Curl_uint32_bset_destroy(&multi->process); + Curl_uint32_bset_destroy(&multi->dirty); + Curl_uint32_bset_destroy(&multi->pending); + Curl_uint32_bset_destroy(&multi->msgsent); + Curl_uint32_tbl_destroy(&multi->xfers); +#ifdef ENABLE_WAKEUP + Curl_wakeup_destroy(multi->wakeup_pair); +#endif +#ifdef ENABLE_INTERNAL_WAKEUP + Curl_wakeup_destroy(multi->wakeup_internal); +#endif + + curlx_free(multi); + return NULL; +} + +CURLM *curl_multi_init(void) +{ + return Curl_multi_handle(CURL_XFER_TABLE_SIZE, + CURL_SOCKET_HASH_TABLE_SIZE, + CURL_CONNECTION_HASH_SIZE, + CURL_DNS_HASH_SIZE, + CURL_TLS_SESSION_SIZE); +} + +#if defined(DEBUGBUILD) && defined(CURLVERBOSE) +static void multi_warn_debug(struct Curl_multi *multi, struct Curl_easy *data) +{ + if(!multi->warned) { + infof(data, "!!! WARNING !!!"); + infof(data, "This is a debug build of libcurl, " + "do not use in production."); + multi->warned = TRUE; + } +} +#else +#define multi_warn_debug(x, y) Curl_nop_stmt +#endif + +bool Curl_is_connecting(struct Curl_easy *data) +{ + return data->mstate < MSTATE_DO; +} + +static CURLMcode multi_assess_wakeup(struct Curl_multi *multi) +{ +#ifdef ENABLE_INTERNAL_WAKEUP + if(multi->socket_cb) + return Curl_multi_ev_assess_xfer(multi, multi->admin); +#else + (void)multi; +#endif + return CURLM_OK; +} + +static CURLMcode multi_xfers_add(struct Curl_multi *multi, + struct Curl_easy *data) +{ + uint32_t capacity = Curl_uint32_tbl_capacity(&multi->xfers); + uint32_t new_size = 0; + /* Prepare to make this into a CURLMOPT_MAX_TRANSFERS, because some + * applications may want to prevent a run-away of their memory use. */ + /* UINT_MAX is our "invalid" id, do not let the table grow up to that. */ + const uint32_t max_capacity = UINT_MAX - 1; + + if(capacity < max_capacity) { + /* We want `multi->xfers` to have "sufficient" free rows, so that we do + * not have to reuse the `mid` from a removed easy right away. + * Check if an 8th of the capacity is still free */ + uint32_t used = Curl_uint32_tbl_count(&multi->xfers); + uint32_t unused = capacity - used; + uint32_t min_unused = CURLMAX(capacity >> 3, 4); + if(unused < min_unused) { + /* Grow by 50% of current capacity, in range of [128, 2048], + * which means the table grows max by 16kb on 64-bit arch. */ + uint32_t growth = CURLMIN(CURLMAX(capacity >> 1, 128), 2048); + /* Make sure the uint arithmetic here works on the corner + * cases where we are close to max_capacity or UINT_MAX */ + if((max_capacity - growth) <= capacity) + new_size = max_capacity; + else + new_size = capacity + growth; + } + } + + if(new_size > capacity) { + /* Grow the bitsets first. Should one fail, we do not need + * to downsize the already resized ones. The sets continue + * to work properly when larger than the table, but not + * the other way around. */ + CURL_TRC_M(data, "increasing xfer table size to %u", new_size); + if(Curl_uint32_bset_resize(&multi->process, new_size) || + Curl_uint32_bset_resize(&multi->dirty, new_size) || + Curl_uint32_bset_resize(&multi->pending, new_size) || + Curl_uint32_bset_resize(&multi->msgsent, new_size) || + Curl_uint32_tbl_resize(&multi->xfers, new_size)) + return CURLM_OUT_OF_MEMORY; + } + + /* Insert the easy into the table now */ + if(!Curl_uint32_tbl_add(&multi->xfers, data, &data->mid)) { + /* MUST only happen when table is full */ + DEBUGASSERT(Curl_uint32_tbl_capacity(&multi->xfers) <= + Curl_uint32_tbl_count(&multi->xfers)); + return CURLM_OUT_OF_MEMORY; + } + return CURLM_OK; +} + +CURLMcode Curl_multi_add_handle(struct Curl_multi *multi, + struct Curl_easy *data) +{ + CURLMcode mresult; + + /* Prevent users from adding same easy handle more than once and prevent + adding to more than one multi stack */ + if(data->multi) + return CURLM_ADDED_ALREADY; + + if(multi->dead) { + /* a "dead" handle cannot get added transfers while any existing easy + handles are still alive - but if there are none alive anymore, it is + fine to start over and unmark the "deadness" of this handle. + This means only the admin handle MUST be present. */ + if((Curl_uint32_tbl_count(&multi->xfers) != 1) || + !Curl_uint32_tbl_contains(&multi->xfers, 0)) + return CURLM_ABORTED_BY_CALLBACK; + multi->dead = FALSE; + Curl_uint32_bset_clear(&multi->process); + Curl_uint32_bset_clear(&multi->dirty); + Curl_uint32_bset_clear(&multi->pending); + Curl_uint32_bset_clear(&multi->msgsent); + } + + if(data->multi_easy) { + /* if this easy handle was previously used for curl_easy_perform(), there + is a private multi handle here that we can kill */ + curl_multi_cleanup(data->multi_easy); + data->multi_easy = NULL; + } + + /* Insert the easy into the multi->xfers table, assigning it a `mid`. */ + if(multi_xfers_add(multi, data)) + return CURLM_OUT_OF_MEMORY; + + /* Initialize timeouts for this handle */ + multi_timeouts_init(data); + + /* + * No failure allowed in this function beyond this point. No modification + * of easy nor multi handle allowed before this except for potential + * multi's connection pool growing which will not be undone in this + * function no matter what. + */ + if(data->set.errorbuffer) + data->set.errorbuffer[0] = 0; + + data->state.os_errno = 0; + + /* make the Curl_easy refer back to this multi handle - before + Curl_expire() is called. */ + data->multi = multi; + + /* set the easy handle */ + multistate(data, MSTATE_INIT); + /* not yet passed INIT state */ + data->state.really_alive = FALSE; + +#ifdef USE_LIBPSL + /* Do the same for PSL. */ + if(data->share && (data->share->specifier & (1 << CURL_LOCK_DATA_PSL))) + data->psl = &data->share->psl; + else + data->psl = &multi->psl; +#endif + + /* add the easy handle to the process set */ + Curl_uint32_bset_add(&multi->process, data->mid); + ++multi->xfers_alive; + ++multi->xfers_total_ever; + + Curl_cpool_xfer_init(data); + multi_warn_debug(multi, data); + + /* Make sure the new handle will run */ + Curl_multi_mark_dirty(data); + + /* Necessary in event based processing, where dirty handles trigger + * a timeout callback invocation. */ + mresult = Curl_update_timer(multi); + if(mresult) { + data->multi = NULL; /* not anymore */ + Curl_uint32_tbl_remove(&multi->xfers, data->mid); + data->mid = UINT32_MAX; + return mresult; + } + + /* The admin handle only ever has default timeouts set. To improve the + state somewhat we clone the timeouts from each added handle so that the + admin handle always has the same timeouts as the most recently added + easy handle. */ + multi->admin->set.timeout = data->set.timeout; + multi->admin->set.server_response_timeout = + data->set.server_response_timeout; + multi->admin->set.no_signal = data->set.no_signal; + + CURL_TRC_M(data, "added to multi, mid=%u, running=%u, total=%u", + data->mid, Curl_multi_xfers_running(multi), + Curl_uint32_tbl_count(&multi->xfers)); + return CURLM_OK; +} + +CURLMcode curl_multi_add_handle(CURLM *m, CURL *curl) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult; + + if(CURL_MAPI_ENTER(&guard, m, multi_add_handle, &mresult)) { + struct Curl_easy *data = curl; + /* Verify that we got a somewhat good easy handle too */ + if(!GOOD_EASY_HANDLE(data)) + mresult = CURLM_BAD_EASY_HANDLE; + else + mresult = Curl_multi_add_handle(m, data); + } + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +struct multi_done_ctx { + BIT(premature); +}; + +static bool multi_conn_should_close(struct connectdata *conn, + struct Curl_easy *data, + bool premature) +{ + /* if conn->bits.close is TRUE, it means that the connection should be + closed in spite of everything else. */ + if(conn->bits.close) + return TRUE; + + /* if data->set.reuse_forbid is TRUE, it means the libcurl client has + forced us to close this connection. This is ignored for requests taking + place in a NTLM/NEGOTIATE authentication handshake. */ + if(data->set.reuse_forbid +#ifdef USE_NTLM + && !(conn->http_ntlm_state == NTLMSTATE_TYPE2 || + conn->proxy_ntlm_state == NTLMSTATE_TYPE2) +#endif +#ifdef USE_SPNEGO + && !(conn->http_negotiate_state == GSS_AUTHRECV || + conn->proxy_negotiate_state == GSS_AUTHRECV) +#endif + ) + return TRUE; + + /* Unless this connection is for a "connect-only" transfer, it + * needs to be closed if the protocol handler does not support reuse. */ + if(!data->set.connect_only && conn->scheme && + !(conn->scheme->flags & PROTOPT_CONN_REUSE)) + return TRUE; + + /* if premature is TRUE, it means this connection was said to be DONE before + the entire request operation is complete and thus we cannot know in what + state it is for reusing, so we are forced to close it. In a perfect world + we can add code that keep track of if we really must close it here or not, + but currently we have no such detail knowledge. */ + if(premature && !Curl_conn_is_multiplex(conn, FIRSTSOCKET)) + return TRUE; + + return FALSE; +} + +static void multi_done_locked(struct connectdata *conn, + struct Curl_easy *data, + void *userdata) +{ + struct multi_done_ctx *mdctx = userdata; + + Curl_detach_connection(data); + + CURL_TRC_M(data, "multi_done_locked, in use=%u", conn->attached_xfers); + if(CONN_INUSE(conn)) { + /* Stop if still used. */ + CURL_TRC_M(data, "Connection still in use %u, no more multi_done now!", + conn->attached_xfers); + return; + } + + data->state.done = TRUE; /* called now! */ + + Curl_dnscache_prune(data); + + if(multi_conn_should_close(conn, data, (bool)mdctx->premature)) { + CURL_TRC_M(data, "multi_done, terminating conn #%" FMT_OFF_T " to %s:%u, " + "forbid=%d, close=%d, premature=%d, conn_multiplex=%d", + conn->connection_id, conn->origin->user_hostname, + conn->origin->port, + data->set.reuse_forbid, conn->bits.close, mdctx->premature, + Curl_conn_is_multiplex(conn, FIRSTSOCKET)); + connclose(conn); + Curl_conn_close(data, conn, (bool)mdctx->premature); + } + else if(!Curl_conn_get_max_concurrent(data, conn, FIRSTSOCKET)) { + CURL_TRC_M(data, "multi_done, conn #%" FMT_OFF_T " to %s:%u was shutdown" + " by server, not reusing", conn->connection_id, + conn->origin->user_hostname, conn->origin->port); + connclose(conn); + Curl_conn_close(data, conn, (bool)mdctx->premature); + } + else { + /* the connection is no longer in use by any transfer */ + if(Curl_cpool_conn_now_idle(data, conn)) { + /* connection kept in the cpool */ + infof(data, "Connection #%" FMT_OFF_T " to host %s:%u left intact", + conn->connection_id, conn->origin->user_hostname, + conn->origin->port); + } + else { + /* connection was removed from the cpool and destroyed. */ + data->state.lastconnect_id = -1; + } + } +} + +static CURLcode multi_done(struct Curl_easy *data, + CURLcode status, /* an error if this is called + after an error was detected */ + bool premature) +{ + CURLcode result; + struct connectdata *conn = data->conn; + + CURL_TRC_M(data, "multi_done: status: %d prem: %d done: %d", + (int)status, (int)premature, data->state.done); + + if(data->state.done) + /* Stop if multi_done() has already been called */ + return CURLE_OK; + + /* Shut down any ongoing async resolver operation. */ + Curl_resolv_shutdown_all(data); + + /* Cleanup possible redirect junk */ + curlx_safefree(data->req.newurl); + curlx_safefree(data->req.location); + + switch(status) { + case CURLE_ABORTED_BY_CALLBACK: + case CURLE_READ_ERROR: + case CURLE_WRITE_ERROR: + /* When we are aborted due to a callback return code it has to be counted + as premature as there is trouble ahead if we do not. We have many + callbacks and protocols work differently, we could potentially do this + more fine-grained in the future. */ + premature = TRUE; + FALLTHROUGH(); + default: + break; + } + + /* this calls the protocol-specific function pointer previously set */ + if(conn && conn->scheme->run->done && (data->mstate >= MSTATE_PROTOCONNECT)) + result = conn->scheme->run->done(data, status, premature); + else + result = status; + + if(data->mstate > MSTATE_CONNECTING && + (result != CURLE_ABORTED_BY_CALLBACK)) { + /* avoid this if + * - the transfer has not connected + * - we already aborted by callback to avoid this calling another callback + */ + int rc = Curl_pgrsDone(data); + if(!result && rc) + result = CURLE_ABORTED_BY_CALLBACK; + } + + /* Make sure that transfer client writes are really done now. */ + result = Curl_1st_fatal(result, Curl_xfer_write_done(data, premature)); + + /* Inform connection filters that this transfer is done */ + if(conn) + Curl_conn_ev_data_done(data, premature); + + multi_schedule_pending(data->multi); /* connection / multiplex */ + + if(!result) + result = Curl_req_done(&data->req, data, premature); + + if(conn) { + /* Under the potential connection pool's share lock, decide what to + * do with the transfer's connection. */ + struct multi_done_ctx mdctx; + + memset(&mdctx, 0, sizeof(mdctx)); + mdctx.premature = premature; + Curl_cpool_do_locked(data, data->conn, multi_done_locked, &mdctx); + } + + /* flush the netrc cache */ + Curl_netrc_cleanup(&data->state.netrc); + return result; +} + +CURLMcode Curl_multi_remove_handle(struct Curl_multi *multi, + struct Curl_easy *data) +{ + CURLMcode mresult; + bool premature; + struct Curl_llist_node *e; + uint32_t mid; + + /* Prevent users from trying to remove same easy handle more than once */ + if(!data->multi) + return CURLM_OK; /* it is already removed so let's say it is fine! */ + + /* Prevent users from trying to remove an easy handle from the wrong multi */ + if(data->multi != multi) + return CURLM_BAD_EASY_HANDLE; + + if(data->mid == UINT32_MAX) { + DEBUGASSERT(0); + return CURLM_INTERNAL_ERROR; + } + if(Curl_uint32_tbl_get(&multi->xfers, data->mid) != data) { + DEBUGASSERT(0); + return CURLM_INTERNAL_ERROR; + } + + premature = (data->mstate < MSTATE_COMPLETED); + + if(data->conn) { + /* If the 'state' is not INIT or COMPLETED, we might need to do something + nice to put the easy_handle in a good known state when this returns. */ + if(premature && (data->mstate > MSTATE_DO)) + streamclose(data->conn); + + /* multi_done() clears the association between the easy handle and the + connection. + Note that this ignores the return code because there is + nothing really useful to do with it anyway! */ + (void)multi_done(data, data->result, premature); + } + + /* The timer must be shut down before data->multi is set to NULL, else + data's splaynode would remain in the splay tree after curl_easy_cleanup is + called. Do it after multi_done() in case that sets another time! */ + Curl_expire_clear_all(data); + + /* If in `msgsent`, it was deducted from `multi->xfers_alive` already. */ + if(!Curl_uint32_bset_contains(&multi->msgsent, data->mid)) + --multi->xfers_alive; + + if(data->state.really_alive) { + data->state.really_alive = FALSE; + --multi->xfers_really_alive; + if(!multi->xfers_really_alive) + (void)multi_assess_wakeup(multi); + } + + Curl_wildcard_dtor(&data->wildcard); + + data->mstate = MSTATE_COMPLETED; + + /* Remove the association between the connection and the handle */ + Curl_detach_connection(data); + + /* Tell event handling that this transfer is definitely going away */ + Curl_multi_ev_xfer_done(multi, data); + + if(data->set.connect_only) { + if(data->multi_easy) { + if(data->state.lastconnect_id != -1) { + /* Mark any connect-only connection for closure */ + struct connectdata *conn; + (void)Curl_getconnectinfo(data, &conn); + if(conn && conn->bits.connect_only) + connclose(conn); + } + } + else { + /* This removes a handle that was part the multi interface that used + CONNECT_ONLY, that connection is now left alive but since this handle + has bits.close set nothing can use that connection anymore and it is + forbidden from reuse. This easy handle cannot find the connection + anymore once removed from the multi handle + + Better close the connection here, at once. */ + struct connectdata *conn; + (void)Curl_getconnectinfo(data, &conn); + if(conn) + Curl_conn_close(data, conn, TRUE); + } + } + +#ifdef USE_LIBPSL + /* Remove the PSL association. */ + if(data->psl == &multi->psl) + data->psl = NULL; +#endif + + /* make sure there is no pending message in the queue sent from this easy + handle */ + for(e = Curl_llist_head(&multi->msglist); e; e = Curl_node_next(e)) { + struct Curl_message *msg = Curl_node_elem(e); + + if(msg->extmsg.easy_handle == data) { + Curl_node_remove(e); + /* there can only be one from this specific handle */ + break; + } + } + + /* clear the association to this multi handle */ + mid = data->mid; + DEBUGASSERT(Curl_uint32_tbl_contains(&multi->xfers, mid)); + Curl_uint32_tbl_remove(&multi->xfers, mid); + Curl_uint32_bset_remove(&multi->process, mid); + Curl_uint32_bset_remove(&multi->dirty, mid); + Curl_uint32_bset_remove(&multi->pending, mid); + Curl_uint32_bset_remove(&multi->msgsent, mid); + data->multi = NULL; + data->mid = UINT32_MAX; + data->master_mid = UINT32_MAX; + + /* A pending transfer *might* be able to run now. */ + multi_schedule_pending(multi); + mresult = Curl_update_timer(multi); + if(mresult) + return mresult; + + mresult = multi_assess_wakeup(multi); + if(mresult) { + failf(data, "error enabling wakeup listening: %d", mresult); + return mresult; + } + + CURL_TRC_M(data, "removed from multi, mid=%u, running=%u, total=%u", + mid, Curl_multi_xfers_running(multi), + Curl_uint32_tbl_count(&multi->xfers)); + return CURLM_OK; +} + +CURLMcode curl_multi_remove_handle(CURLM *m, CURL *curl) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult; + + if(CURL_MAPI_ENTER(&guard, m, multi_remove_handle, &mresult)) { + struct Curl_easy *data = curl; + if(!GOOD_EASY_HANDLE(data)) + mresult = CURLM_BAD_EASY_HANDLE; + else + mresult = Curl_multi_remove_handle(m, data); + } + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +/* Return TRUE if the application asked for multiplexing */ +bool Curl_multiplex_wanted(const struct Curl_multi *multi) +{ + return multi && multi->multiplexing; +} + +/* + * Curl_detach_connection() removes the given transfer from the connection. + * + * This is the only function that should clear data->conn. This will + * occasionally be called with the data->conn pointer already cleared. + */ +void Curl_detach_connection(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + if(conn) { + /* this should never happen, prevent underflow */ + DEBUGASSERT(conn->attached_xfers); + if(conn->attached_xfers) { + conn->attached_xfers--; + if(!conn->attached_xfers) + conn->attached_multi = NULL; + } + } + data->conn = NULL; +} + +/* + * Curl_attach_connection() attaches this transfer to this connection. + * + * This is the only function that should assign data->conn. + * `matched == TRUE` means the transfer's properties match this + * connection and it is not a temporary attach for maintenance. + */ +void Curl_attach_connection(struct Curl_easy *data, + struct connectdata *conn, + bool matched) +{ + DEBUGASSERT(data); + DEBUGASSERT(!data->conn); + DEBUGASSERT(conn); + DEBUGASSERT(conn->attached_xfers < UINT32_MAX); + data->conn = conn; + if(matched) + data->state.lastconnect_id = conn->connection_id; + else + DEBUGASSERT(!data->mid); /* admin handle */ + conn->attached_xfers++; + /* all attached transfers must be from the same multi */ + if(!conn->attached_multi) + conn->attached_multi = data->multi; + DEBUGASSERT(conn->attached_multi == data->multi); + + if(conn->scheme && conn->scheme->run->attach) + conn->scheme->run->attach(data, conn); +} + +/* adjust pollset for rate limits/pauses */ +static CURLcode multi_adjust_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + CURLcode result = CURLE_OK; + + if(ps->n) { + bool send_blocked, recv_blocked; + + recv_blocked = (Curl_rlimit_avail(&data->progress.dl.rlimit, NULL) <= 0); + send_blocked = (Curl_rlimit_avail(&data->progress.ul.rlimit, NULL) <= 0); + if(send_blocked || recv_blocked) { + int i; + for(i = 0; i <= SECONDARYSOCKET; ++i) { + curl_socket_t sock = data->conn->sock[i]; + if(sock == CURL_SOCKET_BAD) + continue; + if(recv_blocked && Curl_pollset_want_recv(data, ps, sock)) { + result = Curl_pollset_remove_in(data, ps, sock); + if(result) + break; + } + if(send_blocked && Curl_pollset_want_send(data, ps, sock)) { + result = Curl_pollset_remove_out(data, ps, sock); + if(result) + break; + } + } + } + + /* Not blocked and wanting to receive. If there is data pending + * in the connection filters, make transfer run again. */ + if(!recv_blocked && + ((Curl_pollset_want_recv(data, ps, data->conn->sock[FIRSTSOCKET]) && + Curl_conn_data_pending(data, FIRSTSOCKET)) || + (Curl_pollset_want_recv(data, ps, data->conn->sock[SECONDARYSOCKET]) && + Curl_conn_data_pending(data, SECONDARYSOCKET)))) { + CURL_TRC_M(data, "pollset[] has POLLIN, but there is still " + "buffered input -> mark as dirty"); + Curl_multi_mark_dirty(data); + } + } + return result; +} + +static CURLcode mstate_connecting_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct connectdata *conn = data->conn; + curl_socket_t sockfd; + CURLcode result = CURLE_OK; + + if(Curl_xfer_recv_is_paused(data)) + return CURLE_OK; + /* If a socket is set, receiving is default. If the socket + * has not been determined yet (eyeballing), always ask the + * connection filters for what to monitor. */ + sockfd = Curl_conn_get_first_socket(data); + if(sockfd != CURL_SOCKET_BAD) { + result = Curl_pollset_change(data, ps, sockfd, CURL_POLL_IN, 0); + if(!result) + result = multi_adjust_pollset(data, ps); + } + if(!result) + result = Curl_conn_adjust_pollset(data, conn, ps); + return result; +} + +static CURLcode mstate_protocol_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + + if(conn->scheme->run->proto_pollset) + result = conn->scheme->run->proto_pollset(data, ps); + else { + curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; + if(sockfd != CURL_SOCKET_BAD) { + /* Default is to wait to something from the server */ + result = Curl_pollset_change(data, ps, sockfd, CURL_POLL_IN, 0); + } + } + if(!result) + result = multi_adjust_pollset(data, ps); + if(!result) + result = Curl_conn_adjust_pollset(data, conn, ps); + return result; +} + +static CURLcode mstate_do_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + + if(conn->scheme->run->doing_pollset) + result = conn->scheme->run->doing_pollset(data, ps); + else if(CONN_SOCK_IDX_VALID(conn->send_idx)) { + /* Default is that we want to send something to the server */ + result = Curl_pollset_add_out(data, ps, conn->sock[conn->send_idx]); + } + if(!result) + result = multi_adjust_pollset(data, ps); + if(!result) + result = Curl_conn_adjust_pollset(data, conn, ps); + return result; +} + +static CURLcode mstate_domore_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + + if(conn->scheme->run->domore_pollset) + result = conn->scheme->run->domore_pollset(data, ps); + else if(CONN_SOCK_IDX_VALID(conn->send_idx)) { + /* Default is that we want to send something to the server */ + result = Curl_pollset_add_out(data, ps, conn->sock[conn->send_idx]); + } + if(!result) + result = multi_adjust_pollset(data, ps); + if(!result) + result = Curl_conn_adjust_pollset(data, conn, ps); + return result; +} + +static CURLcode mstate_perform_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + + if(conn->scheme->run->perform_pollset) + result = conn->scheme->run->perform_pollset(data, ps); + else { + /* Default is to obey the request flags for send/recv */ + if(Curl_req_want_recv(data) && CONN_SOCK_IDX_VALID(conn->recv_idx)) { + result = Curl_pollset_add_in(data, ps, conn->sock[conn->recv_idx]); + } + if(!result && Curl_req_want_send(data) && + CONN_SOCK_IDX_VALID(conn->send_idx)) { + result = Curl_pollset_add_out(data, ps, conn->sock[conn->send_idx]); + } + } + if(!result) + result = multi_adjust_pollset(data, ps); + if(!result) + result = Curl_conn_adjust_pollset(data, conn, ps); + return result; +} + +#ifdef CURLVERBOSE +static size_t multi_timeouts_count(struct expire_timers *timeouts) +{ + size_t n = 0; + uint8_t eid = timeouts->first; + for(; eid < EXPIRE_LAST; eid = timeouts->next[eid]) + ++n; + return n; +} +#endif + +/* Initializes `poll_set` with the current socket poll actions needed + * for transfer `data`. */ +CURLMcode Curl_multi_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + CURLcode result = CURLE_OK; + + Curl_pollset_reset(ps); +#ifdef ENABLE_INTERNAL_WAKEUP + /* The admin handle always listens on the wakeup socket when there + * are transfers alive. */ + if(data->multi && (data == data->multi->admin) && + data->multi->xfers_really_alive) { + CURL_TRC_M(data, "adding wakeup, %u xfers really alive", + data->multi->xfers_really_alive); + result = Curl_pollset_add_in(data, ps, data->multi->wakeup_internal[0]); + } +#endif + /* If the transfer has no connection, this is fine. Happens when + called via curl_multi_remove_handle() => Curl_multi_ev_assess() => + Curl_multi_pollset(). */ + if(!result && data->conn) { + switch(data->mstate) { + case MSTATE_INIT: + case MSTATE_PENDING: + case MSTATE_SETUP: + case MSTATE_CONNECT: + /* nothing to poll for yet */ + break; + + case MSTATE_CONNECTING: + result = mstate_connecting_pollset(data, ps); + break; + + case MSTATE_PROTOCONNECT: + case MSTATE_PROTOCONNECTING: + result = mstate_protocol_pollset(data, ps); + break; + + case MSTATE_DO: + case MSTATE_DOING: + result = mstate_do_pollset(data, ps); + break; + + case MSTATE_DOING_MORE: + result = mstate_domore_pollset(data, ps); + break; + + case MSTATE_DID: /* same as PERFORMING in regard to polling */ + case MSTATE_PERFORMING: + result = mstate_perform_pollset(data, ps); + break; + + case MSTATE_RATELIMITING: + /* we need to let time pass, ignore socket(s) */ + break; + + case MSTATE_DONE: + case MSTATE_COMPLETED: + case MSTATE_MSGSENT: + /* nothing more to poll for */ + break; + + default: + failf(data, "multi_getsock: unexpected multi state %d", + (int)data->mstate); + DEBUGASSERT(0); + break; + } + } + + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + return CURLM_OUT_OF_MEMORY; + failf(data, "error determining pollset: %d", (int)result); + return CURLM_INTERNAL_ERROR; + } + +#ifdef CURLVERBOSE + if(CURL_TRC_M_is_verbose(data)) { + size_t timeout_count = multi_timeouts_count(&data->state.timeouts); + switch(ps->n) { + case 0: + CURL_TRC_M(data, "pollset[], timeouts=%zu, paused %d/%d (r/w)", + timeout_count, + Curl_xfer_send_is_paused(data), + Curl_xfer_recv_is_paused(data)); + break; + case 1: + CURL_TRC_M(data, "pollset[fd=%" FMT_SOCKET_T " %s%s], timeouts=%zu", + ps->sockets[0], + (ps->actions[0] & CURL_POLL_IN) ? "IN" : "", + (ps->actions[0] & CURL_POLL_OUT) ? "OUT" : "", + timeout_count); + break; + case 2: + CURL_TRC_M(data, "pollset[fd=%" FMT_SOCKET_T " %s%s, " + "fd=%" FMT_SOCKET_T " %s%s], timeouts=%zu", + ps->sockets[0], + (ps->actions[0] & CURL_POLL_IN) ? "IN" : "", + (ps->actions[0] & CURL_POLL_OUT) ? "OUT" : "", + ps->sockets[1], + (ps->actions[1] & CURL_POLL_IN) ? "IN" : "", + (ps->actions[1] & CURL_POLL_OUT) ? "OUT" : "", + timeout_count); + break; + default: + CURL_TRC_M(data, "pollset[fds=%u], timeouts=%zu", ps->n, timeout_count); + break; + } + CURL_TRC_EASY_TIMERS(data); + } +#endif + + return CURLM_OK; +} + +CURLMcode curl_multi_fdset(CURLM *m, + fd_set *read_fd_set, fd_set *write_fd_set, + fd_set *exc_fd_set, int *max_fd) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult; + + if(CURL_MAPI_ENTER(&guard, m, multi_fdset, &mresult)) { + /* Scan through all the easy handles to get the file descriptors set. + Some easy handles may not have connected to the remote host yet, + and then we must make sure that is done. */ + struct Curl_multi *multi = m; + struct easy_pollset ps; + int this_max_fd = -1; + unsigned int i; + uint32_t mid; + (void)exc_fd_set; + + Curl_pollset_init(&ps); + if(Curl_uint32_bset_first(&multi->process, &mid)) { + do { + struct Curl_easy *data = Curl_multi_get_easy(multi, mid); + + if(!data) { + DEBUGASSERT(0); + continue; + } + + Curl_multi_pollset(data, &ps); + for(i = 0; i < ps.n; i++) { + if(!FDSET_SOCK(ps.sockets[i])) + /* pretend it does not exist */ + continue; + if(ps.actions[i] & CURL_POLL_IN) + FD_SET(ps.sockets[i], read_fd_set); + if(ps.actions[i] & CURL_POLL_OUT) + FD_SET(ps.sockets[i], write_fd_set); + if((int)ps.sockets[i] > this_max_fd) + this_max_fd = (int)ps.sockets[i]; + } + } while(Curl_uint32_bset_next(&multi->process, mid, &mid)); + } + + Curl_cshutdn_setfds(&multi->cshutdn, read_fd_set, write_fd_set, + &this_max_fd); + + *max_fd = this_max_fd; + Curl_pollset_cleanup(&ps); + + mresult = CURLM_OK; + } + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +CURLMcode curl_multi_waitfds(CURLM *m, + struct curl_waitfd *ufds, + unsigned int size, + unsigned int *fd_count) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult; + + if(CURL_MAPI_ENTER(&guard, m, multi_waitfds, &mresult)) { + struct Curl_waitfds cwfds; + struct Curl_multi *multi = m; + struct easy_pollset ps; + unsigned int need = 0; + uint32_t mid; + + if(!ufds && (size || !fd_count)) { + mresult = CURLM_BAD_FUNCTION_ARGUMENT; + goto out; + } + + Curl_pollset_init(&ps); + Curl_waitfds_init(&cwfds, ufds, size); + mresult = CURLM_OK; + if(Curl_uint32_bset_first(&multi->process, &mid)) { + do { + struct Curl_easy *data = Curl_multi_get_easy(multi, mid); + if(!data) { + DEBUGASSERT(0); + Curl_uint32_bset_remove(&multi->process, mid); + Curl_uint32_bset_remove(&multi->dirty, mid); + continue; + } + Curl_multi_pollset(data, &ps); + need += Curl_waitfds_add_ps(&cwfds, &ps); + } while(Curl_uint32_bset_next(&multi->process, mid, &mid)); + } + + need += Curl_cshutdn_add_waitfds(&multi->cshutdn, &cwfds); + + if(need != cwfds.n && ufds) + mresult = CURLM_OUT_OF_MEMORY; + + if(fd_count) + *fd_count = need; + Curl_pollset_cleanup(&ps); + } +out: + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +#ifdef USE_WINSOCK +/* Reset FD_WRITE for TCP sockets. Nothing is actually sent. UDP sockets cannot + * be reset this way because an empty datagram would be sent. #9203 + * + * "On Windows the internal state of FD_WRITE as returned from + * WSAEnumNetworkEvents is only reset after successful send()." + */ +static void reset_socket_fdwrite(curl_socket_t s) +{ + int t; + int l = (int)sizeof(t); + if(!getsockopt(s, SOL_SOCKET, SO_TYPE, (char *)&t, &l) && t == SOCK_STREAM) + swrite(s, NULL, 0); +} + +static CURLMcode multi_winsock_select(struct Curl_multi *multi, + struct curl_pollfds *cpfds, + unsigned int curl_nfds, + struct curl_waitfd extra_fds[], + unsigned int extra_nfds, + int timeout_ms, + bool extrawait, + int *pnevents) +{ + CURLMcode mresult = CURLM_OK; + WSANETWORKEVENTS wsa_events; + int nevents = 0; + size_t i; + + DEBUGASSERT(multi->wsa_event != WSA_INVALID_EVENT); + + /* Set the WSA events based on the collected pollds */ + for(i = 0; i < cpfds->n; i++) { + long mask = 0; + if(cpfds->pfds[i].events & POLLIN) + mask |= FD_READ | FD_ACCEPT | FD_CLOSE; + if(cpfds->pfds[i].events & POLLPRI) + mask |= FD_OOB; + if(cpfds->pfds[i].events & POLLOUT) { + mask |= FD_WRITE | FD_CONNECT | FD_CLOSE; + reset_socket_fdwrite(cpfds->pfds[i].fd); + } + if(mask) { + if(WSAEventSelect(cpfds->pfds[i].fd, multi->wsa_event, mask)) { + mresult = CURLM_OUT_OF_MEMORY; + goto out; + } + } + } + + if(cpfds->n || extrawait) { + int pollrc = 0; + + if(cpfds->n) { /* pre-check with Winsock */ + pollrc = Curl_poll(cpfds->pfds, cpfds->n, 0); + if(pollrc < 0) { + mresult = CURLM_UNRECOVERABLE_POLL; + goto out; + } + nevents = pollrc; + } + + if(!nevents) { + /* now wait... if not ready during the pre-check (pollrc == 0) */ + WSAWaitForMultipleEvents(1, &multi->wsa_event, FALSE, (DWORD)timeout_ms, + FALSE); + } + + /* With Winsock, we have to run the following section unconditionally + to call WSAEventSelect(fd, event, 0) on all the sockets */ + /* copy revents results from the poll to the curl_multi_wait poll + struct, the bit values of the actual underlying poll() implementation + may not be the same as the ones in the public libcurl API! */ + for(i = 0; i < extra_nfds; i++) { + unsigned short mask = 0; + curl_socket_t s = extra_fds[i].fd; + + wsa_events.lNetworkEvents = 0; + if(WSAEnumNetworkEvents(s, NULL, &wsa_events) == 0) { + if(wsa_events.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE)) + mask |= CURL_WAIT_POLLIN; + if(wsa_events.lNetworkEvents & (FD_WRITE | FD_CONNECT | FD_CLOSE)) + mask |= CURL_WAIT_POLLOUT; + if(wsa_events.lNetworkEvents & FD_OOB) + mask |= CURL_WAIT_POLLPRI; + if(!pollrc && wsa_events.lNetworkEvents) + nevents++; + } + WSAEventSelect(s, multi->wsa_event, 0); + if(!pollrc) { + extra_fds[i].revents = (short)mask; + continue; + } + else { + unsigned r = (unsigned)cpfds->pfds[curl_nfds + i].revents; + if(r & POLLIN) + mask |= CURL_WAIT_POLLIN; + if(r & POLLOUT) + mask |= CURL_WAIT_POLLOUT; + if(r & POLLPRI) + mask |= CURL_WAIT_POLLPRI; + extra_fds[i].revents = (short)mask; + } + } + + /* Count up all our own sockets that had activity, + and remove them from the event. */ + for(i = 0; i < curl_nfds; ++i) { + wsa_events.lNetworkEvents = 0; + if(WSAEnumNetworkEvents(cpfds->pfds[i].fd, NULL, &wsa_events) == 0) { + if(!pollrc && wsa_events.lNetworkEvents) + nevents++; + } + WSAEventSelect(cpfds->pfds[i].fd, multi->wsa_event, 0); + } + WSAResetEvent(multi->wsa_event); + } + +out: + *pnevents = nevents; + return mresult; +} + +#else /* USE_WINSOCK */ + +static CURLMcode multi_posix_poll(struct Curl_multi *multi, + struct curl_pollfds *cpfds, + unsigned int curl_nfds, + struct curl_waitfd extra_fds[], + unsigned int extra_nfds, + int timeout_ms, + bool extrawait, + int *pnevents) +{ + CURLMcode mresult = CURLM_OK; + int nevents = 0; + size_t i; + + (void)multi; + if(cpfds->n) { + int pollrc = Curl_poll(cpfds->pfds, cpfds->n, timeout_ms); /* wait... */ + if(pollrc < 0) { + mresult = CURLM_UNRECOVERABLE_POLL; + goto out; + } + nevents = pollrc; + + /* copy revents results from the poll to the curl_multi_wait poll + struct, the bit values of the actual underlying poll() implementation + may not be the same as the ones in the public libcurl API! */ + for(i = 0; i < extra_nfds; i++) { + unsigned r = (unsigned)cpfds->pfds[curl_nfds + i].revents; + unsigned short mask = 0; + if(r & POLLIN) + mask |= CURL_WAIT_POLLIN; + if(r & POLLOUT) + mask |= CURL_WAIT_POLLOUT; + if(r & POLLPRI) + mask |= CURL_WAIT_POLLPRI; + extra_fds[i].revents = (short)mask; + } + } + else if(extrawait) { + /* No fds to poll, but asked to obey timeout_ms anyway. We cannot + * use Curl_poll() as it, on some platforms, returns immediately + * without fds. */ + curlx_wait_ms(timeout_ms); + } + +out: + *pnevents = nevents; + return mresult; +} + +#endif /* !USE_WINSOCK */ + +#define NUM_POLLS_ON_STACK 10 + +static CURLMcode multi_wait(struct Curl_multi *multi, + struct curl_waitfd extra_fds[], + unsigned int extra_nfds, + int timeout_ms, + int *ret, + bool extrawait) /* when no socket, wait */ +{ + size_t i; + int timeout_internal; + int nevents = 0; + struct easy_pollset ps; + struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK]; + struct curl_pollfds cpfds; + unsigned int curl_nfds = 0; /* how many pfds are for curl transfers */ + struct Curl_easy *data = NULL; + CURLMcode mresult = CURLM_OK; + uint32_t mid; +#ifdef ENABLE_WAKEUP + int wakeup_idx = -1; +#endif + + if(timeout_ms < 0) + return CURLM_BAD_FUNCTION_ARGUMENT; + + Curl_pollset_init(&ps); + Curl_pollfds_init(&cpfds, a_few_on_stack, NUM_POLLS_ON_STACK); + + /* Add the curl handles to our pollfds first */ + if(Curl_uint32_bset_first(&multi->process, &mid)) { + do { + data = Curl_multi_get_easy(multi, mid); + if(!data) { + DEBUGASSERT(0); + Curl_uint32_bset_remove(&multi->process, mid); + Curl_uint32_bset_remove(&multi->dirty, mid); + continue; + } + Curl_multi_pollset(data, &ps); + if(Curl_pollfds_add_ps(&cpfds, &ps)) { + mresult = CURLM_OUT_OF_MEMORY; + goto out; + } + } while(Curl_uint32_bset_next(&multi->process, mid, &mid)); + } + + if(Curl_cshutdn_add_pollfds(&multi->cshutdn, &cpfds)) { + mresult = CURLM_OUT_OF_MEMORY; + goto out; + } + +#ifdef ENABLE_WAKEUP + /* If `extrawait` is TRUE *or* we have `extra_fds`to poll *or* we + * have transfer sockets to poll, we obey `timeout_ms`. + * Then we need to also monitor the multi's wakeup + * socket to catch calls to `curl_multi_wakeup()` during the wait. */ + if(extrawait || cpfds.n || extra_nfds) { + wakeup_idx = cpfds.n; + if(Curl_pollfds_add_sock(&cpfds, multi->wakeup_pair[0], POLLIN)) { + mresult = CURLM_OUT_OF_MEMORY; + goto out; + } + } +#endif + + curl_nfds = cpfds.n; /* what curl internally uses in cpfds */ + /* Add external file descriptions from poll-like struct curl_waitfd */ + for(i = 0; i < extra_nfds; i++) { + unsigned short events = 0; + if(extra_fds[i].events & CURL_WAIT_POLLIN) + events |= POLLIN; + if(extra_fds[i].events & CURL_WAIT_POLLPRI) + events |= POLLPRI; + if(extra_fds[i].events & CURL_WAIT_POLLOUT) + events |= POLLOUT; + if(Curl_pollfds_add_sock(&cpfds, extra_fds[i].fd, events)) { + mresult = CURLM_OUT_OF_MEMORY; + goto out; + } + } + + /* We check the internal timeout *AFTER* we collected all sockets to + * poll. Collecting the sockets may install new timers by protocols + * and connection filters. + * Use the shorter one of the internal and the caller requested timeout. + * If we are called with `!extrawait` and multi_timeout() reports no + * timeouts exist, do not wait. */ + multi_timeout(multi, NULL, &timeout_internal); + if((timeout_internal >= 0) && (timeout_internal < timeout_ms)) + timeout_ms = timeout_internal; + + if(data) + CURL_TRC_M(data, "multi_wait(fds=%u, timeout=%d) tinternal=%d", + cpfds.n, timeout_ms, timeout_internal); + +#ifdef USE_WINSOCK + mresult = multi_winsock_select(multi, &cpfds, curl_nfds, + extra_fds, extra_nfds, + timeout_ms, extrawait, &nevents); +#else + mresult = multi_posix_poll(multi, &cpfds, curl_nfds, + extra_fds, extra_nfds, + timeout_ms, extrawait, &nevents); +#endif + +#ifdef ENABLE_WAKEUP + if(nevents && (wakeup_idx >= 0)) { + if(cpfds.pfds[wakeup_idx].revents & POLLIN) { + (void)Curl_wakeup_consume(multi->wakeup_pair, TRUE); + /* do not count the wakeup socket into the returned value */ + nevents--; + } + } +#endif + +out: + Curl_pollset_cleanup(&ps); + Curl_pollfds_cleanup(&cpfds); + if(ret) + *ret = nevents; + return mresult; +} + +CURLMcode curl_multi_wait(CURLM *m, + struct curl_waitfd extra_fds[], + unsigned int extra_nfds, + int timeout_ms, + int *ret) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult; + + if(CURL_MAPI_ENTER(&guard, m, multi_wait, &mresult)) { + mresult = multi_wait(m, extra_fds, extra_nfds, timeout_ms, ret, FALSE); + } + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +CURLMcode curl_multi_poll(CURLM *m, + struct curl_waitfd extra_fds[], + unsigned int extra_nfds, + int timeout_ms, + int *ret) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult; + + if(CURL_MAPI_ENTER(&guard, m, multi_poll, &mresult)) { + mresult = multi_wait(m, extra_fds, extra_nfds, timeout_ms, ret, TRUE); + } + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +CURLMcode curl_multi_wakeup(CURLM *m) +{ + /* this function is usually called from another thread, + it has to be careful only to access parts of the + Curl_multi struct that are constant */ + struct Curl_multi *multi = m; + CURLMcode mresult = CURLM_WAKEUP_FAILURE; + + /* GOOD_MULTI_HANDLE can be safely called */ + if(!GOOD_MULTI_HANDLE(multi)) + return CURLM_BAD_HANDLE; + +#ifdef ENABLE_WAKEUP + /* the wakeup_pair variable is only written during init and cleanup, + making it safe to access from another thread after the init part + and before cleanup */ + if(!Curl_wakeup_signal(multi->wakeup_pair)) + mresult = CURLM_OK; +#endif +#ifdef USE_WINSOCK + if(WSASetEvent(multi->wsa_event)) + mresult = CURLM_OK; +#endif + return mresult; +} + +#ifdef ENABLE_INTERNAL_WAKEUP +void Curl_multi_wakeup_internal(struct Curl_multi *multi) +{ + /* This is expected to be invocable from another thread which + * does NOT outlive the multi handle. Check for sanity. */ + if(GOOD_MULTI_HANDLE(multi)) + Curl_wakeup_signal(multi->wakeup_internal); + else + DEBUGASSERT(0); +} +#endif + +/* + * multi_ischanged() is called + * + * Returns TRUE/FALSE whether the state is changed to trigger a CONNECT_PEND + * => CONNECT action. + * + * Set 'clear' to TRUE to have it also clear the state variable. + */ +static bool multi_ischanged(struct Curl_multi *multi, bool clear) +{ + bool retval = FALSE; + DEBUGASSERT(multi); + if(multi) { + retval = (bool)multi->recheckstate; + if(clear) + multi->recheckstate = FALSE; + } + return retval; +} + +/* + * Curl_multi_connchanged() is called to tell that there is a connection in + * this multi handle that has changed state (multiplexing become possible, the + * number of allowed streams changed or similar), and a subsequent use of this + * multi handle should move CONNECT_PEND handles back to CONNECT to have them + * retry. + */ +void Curl_multi_connchanged(struct Curl_multi *multi) +{ + multi->recheckstate = TRUE; +} + +CURLMcode Curl_multi_add_perform(struct Curl_multi *multi, + struct Curl_easy *data, + struct connectdata *conn) +{ + CURLMcode mresult; + + mresult = Curl_multi_add_handle(multi, data); + if(!mresult) { + CURLcode result; + + /* pass in NULL for 'conn' here since we do not want to init the + connection, only this transfer */ + result = Curl_init_transfer(data, NULL); + if(result) { + Curl_multi_remove_handle(multi, data); + return CURLM_INTERNAL_ERROR; + } + + /* take this handle to the perform state right away */ + multistate(data, MSTATE_PERFORMING); + Curl_attach_connection(data, conn, TRUE); + CURL_REQ_SET_RECV(data); + } + return mresult; +} + +static CURLcode multi_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + DEBUGASSERT(conn); + DEBUGASSERT(conn->scheme); + + if(conn->scheme->run->do_it) + result = conn->scheme->run->do_it(data, done); + + return result; +} + +/* + * multi_do_more() is called during the DO_MORE multi state. It is a second + * stage DO state which (wrongly) was introduced to support FTP's second + * connection. + * + * 'complete' can return DOMORE_INCOMPLETE, DOMORE_DONE or DOMORE_GOBACK + * (to DOING state when there is more work to do) + */ + +static CURLcode multi_do_more(struct Curl_easy *data, domore *complete) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + *complete = DOMORE_INCOMPLETE; + + if(conn->scheme->run->do_more) + result = conn->scheme->run->do_more(data, complete); + + return result; +} + +/* + * Check whether a timeout occurred, and handle it if it did + */ +static bool multi_handle_timeout(struct Curl_easy *data, + const struct curltime *pnow, + bool *stream_error, + CURLcode *result) +{ + timediff_t timeout_ms; + + timeout_ms = Curl_timeleft_now_ms(data, pnow); + if(timeout_ms < 0) { + /* Handle timed out */ + timerid base_timer = Curl_is_connecting(data) ? + TIMER_STARTSINGLE : TIMER_STARTOP; + timediff_t elapsed_ms = Curl_pgrs_since_ms(data, NULL, base_timer); + if(data->mstate == MSTATE_CONNECTING) + failf(data, "%s timed out after %" FMT_TIMEDIFF_T " milliseconds", + data->conn->bits.dns_resolved ? "Connection" : "Resolving", + elapsed_ms); + else { + struct SingleRequest *k = &data->req; + if(k->size != -1) { + failf(data, "Operation timed out after %" FMT_TIMEDIFF_T + " milliseconds with %" FMT_OFF_T " out of %" + FMT_OFF_T " bytes received", + elapsed_ms, k->bytecount, k->size); + } + else { + failf(data, "Operation timed out after %" FMT_TIMEDIFF_T + " milliseconds with %" FMT_OFF_T " bytes received", + elapsed_ms, k->bytecount); + } + } + *result = CURLE_OPERATION_TIMEDOUT; + if(data->conn) { + /* Force connection closed if the connection has indeed been used */ + if(data->mstate > MSTATE_DO) { + streamclose(data->conn); + *stream_error = TRUE; + } + (void)multi_done(data, *result, TRUE); + } + return TRUE; + } + + return FALSE; +} + +/* + * We are doing protocol-specific connecting and this is being called over and + * over from the multi interface until the connection phase is done on + * protocol layer. + */ + +static CURLcode protocol_connecting(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + if(conn && conn->scheme->run->connecting) { + *done = FALSE; + result = conn->scheme->run->connecting(data, done); + } + else + *done = TRUE; + + return result; +} + +/* + * We are DOING this is being called over and over from the multi interface + * until the DOING phase is done on protocol layer. + */ + +static CURLcode protocol_doing(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + if(conn && conn->scheme->run->doing) { + *done = FALSE; + result = conn->scheme->run->doing(data, done); + } + else + *done = TRUE; + + return result; +} + +/* + * We have discovered that the TCP connection has been successful, we can now + * proceed with some action. + * + */ +static CURLcode protocol_connect(struct Curl_easy *data, bool *protocol_done) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + + DEBUGASSERT(conn); + DEBUGASSERT(protocol_done); + DEBUGASSERT(Curl_conn_is_connected(conn, FIRSTSOCKET)); + + *protocol_done = FALSE; + if(!conn->bits.protoconnstart) { + if(conn->scheme->run->connect_it) { + /* Call the protocol-specific connect function */ + result = conn->scheme->run->connect_it(data, protocol_done); + if(result) + return result; + } + conn->bits.protoconnstart = TRUE; + } + + /* Unless this protocol does not have any protocol-connect callback, as + then we know we are done. */ + if(!conn->scheme->run->connecting) + *protocol_done = TRUE; + return CURLE_OK; +} + +/* + * posttransfer() is called immediately after a transfer ends + */ +static void multi_posttransfer(struct Curl_easy *data) +{ +#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(MSG_NOSIGNAL) + /* restore the signal handler for SIGPIPE before we get back */ + if(!data->set.no_signal) + signal(SIGPIPE, data->state.prev_signal); +#else + (void)data; +#endif +} + +/* + * multi_follow() handles the URL redirect magic. Pass in the 'newurl' string + * as given by the remote server and set up the new URL to request. + * + * This function DOES NOT FREE the given URL. + */ +static CURLcode multi_follow(struct Curl_easy *data, + const struct Curl_scheme *handler, + const char *newurl, /* the Location: string */ + followtype type) /* see transfer.h */ +{ + if(handler && handler->run->follow) + return handler->run->follow(data, newurl, type); + + if(type == FOLLOW_RETRY) + /* Retries are generic and do not require protocol-specific redirect + handling. */ + return CURLE_OK; + + return CURLE_TOO_MANY_REDIRECTS; +} + +static CURLcode mspeed_check(struct Curl_easy *data) +{ + if(Curl_rlimit_active(&data->progress.dl.rlimit) || + Curl_rlimit_active(&data->progress.ul.rlimit)) { + /* check if our send/recv limits require idle waits */ + const struct curltime *pnow = Curl_pgrs_now(data); + timediff_t recv_ms, send_ms; + + send_ms = Curl_rlimit_wait_ms(&data->progress.ul.rlimit, pnow); + recv_ms = Curl_rlimit_wait_ms(&data->progress.dl.rlimit, pnow); + + if(send_ms || recv_ms) { + if(data->mstate != MSTATE_RATELIMITING) { + multistate(data, MSTATE_RATELIMITING); + } + Curl_expire_set(data, EXPIRE_TOOFAST, CURLMAX(send_ms, recv_ms), pnow); + Curl_multi_clear_dirty(data); + CURL_TRC_M(data, "[RLIMIT] waiting %" FMT_TIMEDIFF_T "ms", + CURLMAX(send_ms, recv_ms)); + return CURLE_AGAIN; + } + else { + /* when will the rate limits increase next? The transfer needs + * to run again at that time or it may stall. */ + send_ms = Curl_rlimit_next_step_ms(&data->progress.ul.rlimit, pnow); + recv_ms = Curl_rlimit_next_step_ms(&data->progress.dl.rlimit, pnow); + if(send_ms || recv_ms) { + timediff_t next_ms = CURLMIN(send_ms, recv_ms); + if(!next_ms) + next_ms = CURLMAX(send_ms, recv_ms); + Curl_expire_set(data, EXPIRE_TOOFAST, next_ms, pnow); + CURL_TRC_M(data, "[RLIMIT] next token update in %" FMT_TIMEDIFF_T "ms", + next_ms); + } + } + } + + if(data->mstate != MSTATE_PERFORMING) { + CURL_TRC_M(data, "[RLIMIT] wait over, continue"); + multistate(data, MSTATE_PERFORMING); + } + return CURLE_OK; +} + +static CURLMcode multistate_performing(struct Curl_easy *data, + bool *stream_errorp, + CURLcode *resultp) +{ + char *newurl = NULL; + bool retry = FALSE; + CURLMcode mresult = CURLM_OK; + CURLcode result = *resultp = CURLE_OK; + *stream_errorp = FALSE; + + if(mspeed_check(data) == CURLE_AGAIN) + return CURLM_OK; + + /* read/write data if it is ready to do so */ + result = Curl_sendrecv(data); + + if(data->req.done || (result == CURLE_RECV_ERROR)) { + /* If CURLE_RECV_ERROR happens early enough, we assume it was a race + * condition and the server closed the reused connection exactly when we + * wanted to use it, so figure out if that is indeed the case. + */ + CURLcode ret = Curl_retry_request(data, &newurl); + if(!ret) + retry = !!newurl; + else if(!result) + result = ret; + + if(retry) { + /* if we are to retry, set the result to OK and consider the + request as done */ + result = CURLE_OK; + data->req.done = TRUE; + } + } +#ifndef CURL_DISABLE_HTTP + else if((result == CURLE_HTTP2_STREAM) && + Curl_h2_http_1_1_error(data)) { + CURLcode ret = Curl_retry_request(data, &newurl); + + if(!ret) { + infof(data, "Downgrades to HTTP/1.1"); + streamclose(data->conn); + data->state.http_neg.wanted = CURL_HTTP_V1x; + data->state.http_neg.allowed = CURL_HTTP_V1x; + /* clear the error message bit too as we ignore the one we got */ + data->state.errorbuf = FALSE; + if(!newurl) + /* typically for HTTP_1_1_REQUIRED error on first flight */ + newurl = Curl_bufref_dup(&data->state.url); + if(!newurl) { + result = CURLE_OUT_OF_MEMORY; + } + else { + /* if we are to retry, set the result to OK and consider the request + as done */ + retry = TRUE; + result = CURLE_OK; + data->req.done = TRUE; + } + } + else + result = ret; + } +#endif + + if(result) { + /* + * The transfer phase returned error, we mark the connection to get closed + * to prevent being reused. This is because we cannot possibly know if the + * connection is in a good shape or not now. Unless it is a protocol which + * uses two "channels" like FTP, as then the error happened in the data + * connection. + */ + + if(!(data->conn->scheme->flags & PROTOPT_DUAL) && + result != CURLE_HTTP2_STREAM) + streamclose(data->conn); + + multi_posttransfer(data); + multi_done(data, result, TRUE); + } + else if(data->req.done && !Curl_cwriter_is_paused(data)) { + const struct Curl_scheme *handler = data->conn->scheme; + + /* call this even if the readwrite function returned error */ + multi_posttransfer(data); + + /* When we follow redirects or is set to retry the connection, we must to + go back to the CONNECT state */ + if(data->req.newurl || retry) { + followtype follow = FOLLOW_NONE; + if(!retry) { + /* if the URL is a follow-location and not a retried request then + figure out the URL here */ + curlx_free(newurl); + newurl = data->req.newurl; + data->req.newurl = NULL; + follow = FOLLOW_REDIR; + } + else + follow = FOLLOW_RETRY; + (void)multi_done(data, CURLE_OK, FALSE); + /* multi_done() might return CURLE_GOT_NOTHING */ + result = multi_follow(data, handler, newurl, follow); + if(!result) { + multistate(data, MSTATE_SETUP); + mresult = CURLM_CALL_MULTI_PERFORM; + } + } + else { + /* after the transfer is done, go DONE */ + + /* but first check to see if we got a location info even though we are + not following redirects */ + if(data->req.location) { + curlx_free(newurl); + newurl = data->req.location; + data->req.location = NULL; + result = multi_follow(data, handler, newurl, FOLLOW_FAKE); + if(result) { + *stream_errorp = TRUE; + result = multi_done(data, result, TRUE); + } + } + + if(!result) { + multistate(data, MSTATE_DONE); + mresult = CURLM_CALL_MULTI_PERFORM; + } + } + } + else { /* not errored, not done */ + mspeed_check(data); + } + curlx_free(newurl); + *resultp = result; + return mresult; +} + +static CURLMcode multistate_do(struct Curl_easy *data, + bool *stream_errorp, + CURLcode *resultp) +{ + CURLMcode mresult = CURLM_OK; + CURLcode result = CURLE_OK; + if(data->set.fprereq) { + struct Curl_mapi_guard guard; + int prereq_rc; + + /* call the prerequest callback function */ + CURL_CBAPI_START(&guard, data, easy_fprereq); + prereq_rc = data->set.fprereq(data->set.prereq_userp, + data->info.primary.remote_ip, + data->info.primary.local_ip, + data->info.primary.remote_port, + data->info.primary.local_port); + CURL_CBAPI_END(&guard); + if(prereq_rc != CURL_PREREQFUNC_OK) { + failf(data, "operation aborted by pre-request callback"); + /* failure in pre-request callback - do not do any other processing */ + result = CURLE_ABORTED_BY_CALLBACK; + multi_posttransfer(data); + multi_done(data, result, FALSE); + *stream_errorp = TRUE; + goto end; + } + } + + if(data->set.connect_only && !data->set.connect_only_ws) { + multistate(data, MSTATE_DONE); + mresult = CURLM_CALL_MULTI_PERFORM; + } + else { + bool dophase_done = FALSE; + /* Perform the protocol's DO action */ + result = multi_do(data, &dophase_done); + + if(!result) { + if(!dophase_done) { +#ifndef CURL_DISABLE_FTP + /* some steps needed for wildcard matching */ + if(data->state.wildcardmatch) { + struct WildcardData *wc = data->wildcard; + if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) { + /* skip some states if it is important */ + multi_done(data, CURLE_OK, FALSE); + + /* if there is no connection left, skip the DONE state */ + multistate(data, data->conn ? MSTATE_DONE : MSTATE_COMPLETED); + mresult = CURLM_CALL_MULTI_PERFORM; + goto end; + } + } +#endif + /* DO was not completed in one function call, we must continue + DOING... */ + multistate(data, MSTATE_DOING); + mresult = CURLM_CALL_MULTI_PERFORM; + } + + /* after DO, go DO_DONE... or DO_MORE */ + else if(data->conn->bits.do_more) { + /* we are supposed to do more, but we need to sit down, relax and wait + a little while first */ + multistate(data, MSTATE_DOING_MORE); + mresult = CURLM_CALL_MULTI_PERFORM; + } + else { + /* we are done with the DO, now DID */ + multistate(data, MSTATE_DID); + mresult = CURLM_CALL_MULTI_PERFORM; + } + } + else if((result == CURLE_SEND_ERROR) && + data->conn->bits.reuse) { + /* + * In this situation, a connection that we were trying to use may have + * unexpectedly died. If possible, send the connection back to the + * CONNECT phase so we can try again. + */ + const struct Curl_scheme *handler = data->conn->scheme; + char *newurl = NULL; + followtype follow = FOLLOW_NONE; + CURLcode drc; + + drc = Curl_retry_request(data, &newurl); + if(drc) { + /* a failure here pretty much implies an out of memory */ + result = drc; + *stream_errorp = TRUE; + } + + multi_posttransfer(data); + drc = multi_done(data, result, FALSE); + + /* When set to retry the connection, we must go back to the CONNECT + * state */ + if(newurl) { + if(!drc || (drc == CURLE_SEND_ERROR)) { + follow = FOLLOW_RETRY; + drc = multi_follow(data, handler, newurl, follow); + if(!drc) { + multistate(data, MSTATE_SETUP); + mresult = CURLM_CALL_MULTI_PERFORM; + result = CURLE_OK; + } + else { + /* Follow failed */ + result = drc; + } + } + else { + /* done did not return OK or SEND_ERROR */ + result = drc; + } + } + else { + /* Have error handler disconnect conn if we cannot retry */ + *stream_errorp = TRUE; + } + curlx_free(newurl); + } + else { + /* failure detected */ + multi_posttransfer(data); + if(data->conn) + multi_done(data, result, FALSE); + *stream_errorp = TRUE; + } + } +end: + *resultp = result; + return mresult; +} + +static CURLMcode multistate_ratelimiting(struct Curl_easy *data, + CURLcode *resultp) +{ + CURLcode result = CURLE_OK; + CURLMcode mresult = CURLM_OK; + DEBUGASSERT(data->conn); + /* if both rates are within spec, resume transfer */ + result = Curl_pgrsCheck(data); + + if(result) { + if(!(data->conn->scheme->flags & PROTOPT_DUAL) && + result != CURLE_HTTP2_STREAM) + streamclose(data->conn); + + multi_posttransfer(data); + multi_done(data, result, TRUE); + } + else { + if(!mspeed_check(data)) + mresult = CURLM_CALL_MULTI_PERFORM; + } + *resultp = result; + return mresult; +} + +static CURLMcode multistate_connect(struct Curl_multi *multi, + struct Curl_easy *data, + CURLcode *resultp) +{ + /* Connect. We want to get a connection identifier filled in. This state can + be entered from SETUP and from PENDING. */ + bool connected; + CURLMcode mresult = CURLM_OK; + CURLcode result = Curl_connect(data, &connected); + if(result == CURLE_NO_CONNECTION_AVAILABLE) { + /* There was no connection available. We will go to the pending state and + wait for an available connection. */ + multistate(data, MSTATE_PENDING); + /* move from process to pending set */ + Curl_uint32_bset_remove(&multi->process, data->mid); + Curl_uint32_bset_remove(&multi->dirty, data->mid); + Curl_uint32_bset_add(&multi->pending, data->mid); + *resultp = CURLE_OK; + return mresult; + } + else + multi_schedule_pending(data->multi); + + if(!result) { + /* after the connect has been sent off, go WAITCONNECT unless the + protocol connect is already done and we can go directly to WAITDO or + DO! */ + mresult = CURLM_CALL_MULTI_PERFORM; + + if(connected) { + if(!data->conn->bits.reuse && + Curl_conn_is_multiplex(data->conn, FIRSTSOCKET)) { + /* new connection, can multiplex, wake pending handles */ + multi_schedule_pending(data->multi); + } + multistate(data, MSTATE_PROTOCONNECT); + } + else { + multistate(data, MSTATE_CONNECTING); + } + } + *resultp = result; + return mresult; +} + +/* returns the possibly updated result */ +static CURLcode is_finished(struct Curl_multi *multi, + struct Curl_easy *data, + const struct curltime *pnow, + bool stream_error, + CURLcode result) +{ + if(data->mstate < MSTATE_COMPLETED) { + if(result) { + /* + * If an error was returned, and we are not in completed state now, + * then we go to completed and consider this transfer aborted. + */ + + /* No attempt to disconnect connections must be made before this - + connection detach and termination happens only here */ + + /* Check if we can move pending requests to send pipe */ + multi_schedule_pending(multi); /* connection */ + + if(data->conn) { + if(stream_error) { + /* Do not attempt to send data over a connection that timed out */ + bool dead_connection = result == CURLE_OPERATION_TIMEDOUT; + struct connectdata *conn = data->conn; + + /* This is where we make sure that the conn pointer is reset. + We do not have to do this in every case block above where a + failure is detected */ + Curl_detach_connection(data); + Curl_conn_close(data, conn, dead_connection); + } + } + else if(data->mstate == MSTATE_CONNECT) { + /* Curl_connect() failed */ + multi_posttransfer(data); + Curl_pgrsUpdate_nometer(data); + } + + multistate(data, MSTATE_COMPLETED); + return result; + } + /* if there is still a connection to use, call the progress function */ + else if(data->conn && Curl_conn_is_connected(data->conn, FIRSTSOCKET)) { + result = Curl_pgrsUpdateX(data, pnow); + if(result) { + /* aborted due to progress callback return code must close the + connection */ + streamclose(data->conn); + + /* if not yet in DONE state, go there, otherwise COMPLETED */ + multistate(data, (data->mstate < MSTATE_DONE) ? + MSTATE_DONE : MSTATE_COMPLETED); + return result; + } + } + } + return result; +} + +static void handle_completed(struct Curl_multi *multi, + struct Curl_easy *data, + CURLcode result) +{ + if(data->master_mid != UINT32_MAX) { + /* A sub transfer, not for msgsent to application. Is anyone still + * interested in processing its results? */ + if(data->sub_xfer_done) { + struct Curl_easy *master = Curl_multi_get_easy(multi, data->master_mid); + + CURL_TRC_M(data, "sub xfer done for master %u", data->master_mid); + if(master) + data->sub_xfer_done(data, master, result); + else + CURL_TRC_M(data, "master easy %u already gone.", data->master_mid); + } + } + else { + /* now fill in the Curl_message with this info */ + struct Curl_message *msg = &data->msg; + + msg->extmsg.msg = CURLMSG_DONE; + msg->extmsg.easy_handle = data; + msg->extmsg.data.result = result; + + multi_addmsg(multi, msg); + DEBUGASSERT(!data->conn); + } + multistate(data, MSTATE_MSGSENT); + + /* remove from the other sets, add to msgsent */ + Curl_uint32_bset_remove(&multi->process, data->mid); + Curl_uint32_bset_remove(&multi->dirty, data->mid); + Curl_uint32_bset_remove(&multi->pending, data->mid); + Curl_uint32_bset_add(&multi->msgsent, data->mid); + if(data->state.really_alive) { + data->state.really_alive = FALSE; + --multi->xfers_really_alive; + if(!multi->xfers_really_alive) + (void)multi_assess_wakeup(multi); + } + --multi->xfers_alive; + if(!multi->xfers_alive) + multi_assess_wakeup(multi); +} + +static CURLMcode multistate_init(struct Curl_easy *data, CURLcode *result) +{ + if(!data->state.really_alive) { + data->state.really_alive = TRUE; + ++data->multi->xfers_really_alive; + if(data->multi->xfers_really_alive == 1) { + CURLMcode mresult = multi_assess_wakeup(data->multi); + if(mresult) { + failf(data, "error enabling wakeup listening: %d", mresult); + return mresult; + } + } + } + + *result = Curl_pretransfer(data); + if(*result) + return CURLM_OK; + + /* after init, go SETUP */ + multistate(data, MSTATE_SETUP); + Curl_pgrsTime(data, TIMER_STARTOP); + return CURLM_CALL_MULTI_PERFORM; +} + +static CURLMcode multistate_setup(struct Curl_easy *data) +{ + const struct curltime *pnow = Curl_pgrs_now(data); + Curl_pgrsTimeWas(data, TIMER_STARTSINGLE, *pnow); + if(data->set.timeout) + Curl_expire_set(data, EXPIRE_TIMEOUT, data->set.timeout, pnow); + if(data->set.connecttimeout) + /* Since a connection might go to pending and back to CONNECT several + times before it actually takes off, we need to set the timeout once + in SETUP before we enter CONNECT the first time. */ + Curl_expire_set(data, EXPIRE_CONNECTTIMEOUT, + data->set.connecttimeout, pnow); + + multistate(data, MSTATE_CONNECT); + return CURLM_CALL_MULTI_PERFORM; +} + +static CURLMcode multistate_connecting(struct Curl_easy *data, + bool *stream_error, + CURLcode *result) +{ + bool connected; + + if(!data->conn) { + DEBUGASSERT(0); + *result = CURLE_FAILED_INIT; + return CURLM_OK; + } + if(!Curl_xfer_recv_is_paused(data)) { + *result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &connected); + if(connected && !*result) { + if(!data->conn->bits.reuse && + Curl_conn_is_multiplex(data->conn, FIRSTSOCKET)) { + /* new connection, can multiplex, wake pending handles */ + multi_schedule_pending(data->multi); + } + multistate(data, MSTATE_PROTOCONNECT); + return CURLM_CALL_MULTI_PERFORM; + } + else if(*result) { + /* failure detected */ + CURL_TRC_M(data, "connect failed -> %d", (int)*result); + multi_posttransfer(data); + multi_done(data, *result, TRUE); + *stream_error = TRUE; + return CURLM_OK; + } + } + return CURLM_OK; +} + +static CURLMcode multistate_protoconnect(struct Curl_easy *data, + bool *stream_error, + CURLcode *result) +{ + bool protocol_connected = FALSE; + + if(!*result && data->conn->bits.reuse) { + /* ftp seems to hang when protoconnect on reused connection since we + * handle PROTOCONNECT in general inside the filters, it seems wrong to + * restart this on a reused connection. + */ + multistate(data, MSTATE_DO); + return CURLM_CALL_MULTI_PERFORM; + } + if(!*result) + *result = protocol_connect(data, &protocol_connected); + if(!*result && !protocol_connected) { + /* switch to waiting state */ + multistate(data, MSTATE_PROTOCONNECTING); + return CURLM_CALL_MULTI_PERFORM; + } + else if(!*result) { + /* protocol connect has completed, go WAITDO or DO */ + multistate(data, MSTATE_DO); + return CURLM_CALL_MULTI_PERFORM; + } + + /* failure detected */ + multi_posttransfer(data); + multi_done(data, *result, TRUE); + *stream_error = TRUE; + return CURLM_OK; +} + +static CURLMcode multistate_protoconnecting(struct Curl_easy *data, + bool *stream_error, + CURLcode *result) +{ + bool protocol_connected = FALSE; + + /* protocol-specific connect phase */ + *result = protocol_connecting(data, &protocol_connected); + if(!*result && protocol_connected) { + /* after the connect has completed, go WAITDO or DO */ + multistate(data, MSTATE_DO); + return CURLM_CALL_MULTI_PERFORM; + } + else if(*result) { + /* failure detected */ + multi_posttransfer(data); + multi_done(data, *result, TRUE); + *stream_error = TRUE; + } + return CURLM_OK; +} + +static CURLMcode multistate_doing(struct Curl_easy *data, + bool *stream_error, + CURLcode *result) +{ + bool dophase_done = FALSE; + + /* we continue DOING until the DO phase is complete */ + DEBUGASSERT(data->conn); + *result = protocol_doing(data, &dophase_done); + if(!*result) { + if(dophase_done) { + /* after DO, go DO_DONE or DO_MORE */ + multistate(data, data->conn->bits.do_more ? + MSTATE_DOING_MORE : MSTATE_DID); + return CURLM_CALL_MULTI_PERFORM; + } /* dophase_done */ + } + else { + /* failure detected */ + multi_posttransfer(data); + multi_done(data, *result, FALSE); + *stream_error = TRUE; + } + return CURLM_OK; +} + +static CURLMcode multistate_doing_more(struct Curl_easy *data, + bool *stream_error, + CURLcode *result) +{ + domore control; + + /* + * When we are connected, DOING MORE and then go DID + */ + DEBUGASSERT(data->conn); + *result = multi_do_more(data, &control); + + if(!*result) { + if(control != DOMORE_INCOMPLETE) { + /* if DONE, advance to DO_DONE + if GOBACK, go back to DOING */ + multistate(data, control == DOMORE_DONE ? MSTATE_DID : MSTATE_DOING); + return CURLM_CALL_MULTI_PERFORM; + } + /* else + stay in DO_MORE */ + } + else { + /* failure detected */ + multi_posttransfer(data); + multi_done(data, *result, FALSE); + *stream_error = TRUE; + } + return CURLM_OK; +} + +static CURLMcode multistate_did(struct Curl_multi *multi, + struct Curl_easy *data) +{ + DEBUGASSERT(data->conn); + if(data->conn->bits.multiplex) + /* Check if we can move pending requests to send pipe */ + multi_schedule_pending(multi); /* multiplexed */ + + /* Only perform the transfer if there is a good socket to work with. + Having both BAD is a signal to skip immediately to DONE */ + if(CONN_SOCK_IDX_VALID(data->conn->recv_idx) || + CONN_SOCK_IDX_VALID(data->conn->send_idx)) { + multistate(data, MSTATE_PERFORMING); + /* Do not return CURLM_CALL_MULTI_PERFORM to give other transfers + * a chance to send off their requests. + * Note: Some SFTP handlers do not seem to like this. + * Restrict it to HTTP families. */ + return ((multi->xfers_alive > 1) && + (data->conn->scheme->protocol & PROTO_FAMILY_HTTP)) ? + CURLM_OK : CURLM_CALL_MULTI_PERFORM; + } + else { +#ifndef CURL_DISABLE_FTP + if(data->state.wildcardmatch && + ((data->conn->scheme->flags & PROTOPT_WILDCARD) == 0)) { + data->wildcard->state = CURLWC_DONE; + } +#endif + multistate(data, MSTATE_DONE); + return CURLM_CALL_MULTI_PERFORM; + } +} + +static CURLMcode multistate_done(struct Curl_easy *data, CURLcode *presult) +{ + if(data->conn) { + CURLcode result; + + /* post-transfer command */ + result = multi_done(data, *presult, FALSE); + + /* allow a previously set error code take precedence */ + if(!(*presult)) + *presult = result; + } + +#ifndef CURL_DISABLE_FTP + if(data->state.wildcardmatch) { + if(data->wildcard->state != CURLWC_DONE) { + /* if a wildcard is set and we are not ending -> lets start again + with MSTATE_INIT */ + multistate(data, MSTATE_INIT); + return CURLM_CALL_MULTI_PERFORM; + } + } +#endif + /* after we have DONE what we are supposed to do, go COMPLETED, and + it does not matter what the multi_done() returned! */ + multistate(data, MSTATE_COMPLETED); + return CURLM_CALL_MULTI_PERFORM; +} + +static CURLMcode multi_runsingle(struct Curl_multi *multi, + struct Curl_easy *data, + struct Curl_sigpipe_ctx *sigpipe_ctx) +{ + CURLMcode mresult = CURLM_OK; + CURLcode result = CURLE_OK; + const struct curltime *pnow = NULL; + + if(multi->dead) { + /* a multi-level callback returned error before, meaning every individual + transfer now has failed */ + result = CURLE_ABORTED_BY_CALLBACK; + multi_posttransfer(data); + multi_done(data, result, FALSE); + multistate(data, MSTATE_COMPLETED); + } + + multi_warn_debug(multi, data); + + /* transfer runs now, clear the dirty bit. This may be set + * again during processing, triggering a re-run later. */ + Curl_uint32_bset_remove(&multi->dirty, data->mid); + + if(data == multi->admin) { +#ifdef ENABLE_INTERNAL_WAKEUP + /* Consume any pending wakeup signals before processing. + * This is necessary for event based processing. See #21547 */ + (void)Curl_wakeup_consume(multi->wakeup_internal, TRUE); +#endif +#ifdef USE_RESOLV_THREADED + Curl_async_thrdd_multi_process(multi); +#endif + Curl_cshutdn_perform(&multi->cshutdn, sigpipe_ctx); + goto out; + } + + sigpipe_apply(data, sigpipe_ctx); + do { + /* A "stream" here is a logical stream if the protocol can handle that + (HTTP/2), or the full connection for older protocols */ + bool stream_error = FALSE; + mresult = CURLM_OK; + pnow = NULL; + + if(multi_ischanged(multi, TRUE)) { + CURL_TRC_M(data, "multi changed, check CONNECT_PEND queue"); + multi_schedule_pending(multi); /* multiplexed */ + } + + if(data->mstate > MSTATE_CONNECT && + data->mstate < MSTATE_COMPLETED) { + /* Make sure we set the connection's current owner */ + DEBUGASSERT(data->conn); + if(!data->conn) { + mresult = CURLM_INTERNAL_ERROR; + goto out; + } + } + + /* Wait for the connect state as only then is the start time stored, but + we must not check already completed handles */ + if((data->mstate >= MSTATE_CONNECT) && (data->mstate < MSTATE_COMPLETED)) { + pnow = Curl_pgrs_now(data); + if(multi_handle_timeout(data, pnow, &stream_error, &result)) + /* Skip the statemachine and go directly to error handling section. */ + goto statemachine_end; + pnow = NULL; + } + + switch(data->mstate) { + case MSTATE_INIT: + /* Transitional state. init this transfer. A handle never comes back to + this state. */ + mresult = multistate_init(data, &result); + break; + + case MSTATE_SETUP: + /* Transitional state. Setup things for a new transfer. The handle + can come back to this state on a redirect. */ + mresult = multistate_setup(data); + break; + + case MSTATE_CONNECT: + mresult = multistate_connect(multi, data, &result); + break; + + case MSTATE_CONNECTING: + /* awaiting a completion of an asynch TCP connect */ + mresult = multistate_connecting(data, &stream_error, &result); + break; + + case MSTATE_PROTOCONNECT: + mresult = multistate_protoconnect(data, &stream_error, &result); + break; + + case MSTATE_PROTOCONNECTING: + /* protocol-specific connect phase */ + mresult = multistate_protoconnecting(data, &stream_error, &result); + break; + + case MSTATE_DO: + mresult = multistate_do(data, &stream_error, &result); + break; + + case MSTATE_DOING: + /* we continue DOING until the DO phase is complete */ + mresult = multistate_doing(data, &stream_error, &result); + break; + + case MSTATE_DOING_MORE: + /* + * When we are connected, DOING MORE and then go DID + */ + mresult = multistate_doing_more(data, &stream_error, &result); + break; + + case MSTATE_DID: + mresult = multistate_did(multi, data); + break; + + case MSTATE_RATELIMITING: /* limit-rate exceeded in either direction */ + mresult = multistate_ratelimiting(data, &result); + break; + + case MSTATE_PERFORMING: + mresult = multistate_performing(data, &stream_error, &result); + break; + + case MSTATE_DONE: + mresult = multistate_done(data, &result); + break; + + case MSTATE_COMPLETED: + break; + + case MSTATE_PENDING: + case MSTATE_MSGSENT: + /* handles in these states should NOT be in this list */ + break; + + default: + mresult = CURLM_INTERNAL_ERROR; + goto out; + } + + if(data->mstate >= MSTATE_CONNECT && + data->mstate < MSTATE_DO && + mresult != CURLM_CALL_MULTI_PERFORM && + !multi_ischanged(multi, FALSE)) { + /* We now handle stream timeouts if and only if this will be the last + * loop iteration. We only check this on the last iteration to ensure + * that if we know we have additional work to do immediately + * (i.e. CURLM_CALL_MULTI_PERFORM == TRUE) then we should do that before + * declaring the connection timed out as we may almost have a completed + * connection. */ + pnow = Curl_pgrs_now(data); + multi_handle_timeout(data, pnow, &stream_error, &result); + } + +statemachine_end: + if(!pnow) + pnow = Curl_pgrs_now(data); + result = is_finished(multi, data, pnow, stream_error, result); + if(result) + mresult = CURLM_CALL_MULTI_PERFORM; + + if(MSTATE_COMPLETED == data->mstate) { + handle_completed(multi, data, result); + mresult = CURLM_OK; + goto out; + } + } while((mresult == CURLM_CALL_MULTI_PERFORM) || + multi_ischanged(multi, FALSE)); + +out: + data->result = result; + return mresult; +} + +static CURLMcode multi_perform(struct Curl_multi *multi, + int *running_handles) +{ + CURLMcode returncode = CURLM_OK; + struct curltime start = *multi_now(multi); + uint32_t mid; + struct Curl_sigpipe_ctx sigpipe_ctx; + + sigpipe_init(&sigpipe_ctx); + + if(Curl_uint32_bset_first(&multi->process, &mid)) { + CURL_TRC_M(multi->admin, "multi_perform(running=%u)", + Curl_multi_xfers_running(multi)); + do { + struct Curl_easy *data = Curl_multi_get_easy(multi, mid); + CURLMcode mresult; + if(!data) { + DEBUGASSERT(0); + Curl_uint32_bset_remove(&multi->process, mid); + Curl_uint32_bset_remove(&multi->dirty, mid); + continue; + } + mresult = multi_runsingle(multi, data, &sigpipe_ctx); + if(mresult) + returncode = mresult; + } while(Curl_uint32_bset_next(&multi->process, mid, &mid)); + } + sigpipe_restore(&sigpipe_ctx); + + if(multi_ischanged(multi, TRUE)) + multi_schedule_pending(multi); + + if(!returncode && CURL_MNTFY_HAS_ENTRIES(multi)) + returncode = Curl_mntfy_dispatch_all(multi); + + /* + * Remove all expired timers from the splay since handles are dealt + * with unconditionally by this function and curl_multi_timeout() requires + * that already passed/handled expire times are removed from the splay. + * + * It is important that the 'now' value is set at the entry of this function + * and not for the current time as it may have ticked a little while since + * then and then we risk this loop to remove timers that actually have not + * been handled! + */ + while(Curl_timeouts_remove_expired(&multi->timeouts, &start, &mid)) { + /* the removed may have another timeout in queue */ + struct Curl_easy *data = Curl_multi_get_easy(multi, mid); + if(!data) { + DEBUGASSERT(0); + continue; + } + (void)add_next_timeout(&start, multi, data); + if(data->mstate == MSTATE_PENDING) { + bool stream_unused; + CURLcode result_unused; + if(multi_handle_timeout(data, multi_now(multi), + &stream_unused, &result_unused)) { + infof(data, "PENDING handle timeout"); + move_pending_to_connect(multi, data); + } + } + } + + if(running_handles) { + uint32_t running = Curl_multi_xfers_running(multi); + *running_handles = (running < INT_MAX) ? (int)running : INT_MAX; + } + + if(CURLM_OK >= returncode) + returncode = Curl_update_timer(multi); + + return returncode; +} + +CURLMcode curl_multi_perform(CURLM *m, int *running_handles) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult; + + if(CURL_MAPI_ENTER(&guard, m, multi_perform, &mresult)) { + mresult = multi_perform(m, running_handles); + } + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +CURLMcode curl_multi_cleanup(CURLM *m) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult; + + if(CURL_MAPI_ENTER(&guard, m, multi_cleanup, &mresult)) { + struct Curl_multi *multi = m; + void *entry; + uint32_t mid; + + /* First remove all remaining easy handles, + * close internal ones. admin handle is special */ + if(Curl_uint32_tbl_first(&multi->xfers, &mid, &entry)) { + do { + struct Curl_easy *data = entry; + if(!GOOD_EASY_HANDLE(data)) { + mresult = CURLM_BAD_HANDLE; + goto out; + } + +#ifdef DEBUGBUILD + if(mid != data->mid) { + CURL_TRC_M(data, "multi_cleanup: still present with mid=%u, " + "but unexpected data->mid=%u\n", mid, data->mid); + DEBUGASSERT(0); + } +#endif + + if(data == multi->admin) + continue; + + if(!data->state.done && data->conn) + /* if DONE was never called for this handle */ + (void)multi_done(data, CURLE_OK, TRUE); + + data->multi = NULL; /* clear the association */ + Curl_uint32_tbl_remove(&multi->xfers, mid); + data->mid = UINT32_MAX; + +#ifdef USE_LIBPSL + if(data->psl == &multi->psl) + data->psl = NULL; +#endif + if(data->state.internal) + Curl_close(&data); + } while(Curl_uint32_tbl_next(&multi->xfers, mid, &mid, &entry)); + } + +#ifdef USE_RESOLV_THREADED + Curl_async_thrdd_multi_destroy(multi, !multi->quick_exit); +#endif + Curl_cpool_destroy(&multi->cpool, multi->admin); + Curl_cshutdn_destroy(&multi->cshutdn, multi->admin); + if(multi->admin) { + CURL_TRC_M(multi->admin, "multi_cleanup, closing admin handle, done"); + multi->admin->multi = NULL; + Curl_uint32_tbl_remove(&multi->xfers, multi->admin->mid); + Curl_close(&multi->admin); + } + + multi->magic = 0; /* not good anymore */ + + Curl_multi_ev_cleanup(multi); + Curl_hash_destroy(&multi->proto_hash); + Curl_dnscache_destroy(&multi->dnscache); + Curl_psl_destroy(&multi->psl); +#ifdef USE_SSL + Curl_ssl_scache_destroy(multi->ssl_scache); +#endif + +#ifdef USE_WINSOCK + WSACloseEvent(multi->wsa_event); +#endif +#ifdef ENABLE_WAKEUP + Curl_wakeup_destroy(multi->wakeup_pair); +#endif +#ifdef ENABLE_INTERNAL_WAKEUP + Curl_wakeup_destroy(multi->wakeup_internal); +#endif + + multi_xfer_bufs_free(multi); + Curl_mntfy_cleanup(multi); +#ifdef DEBUGBUILD + if(Curl_uint32_tbl_count(&multi->xfers)) { + multi_xfer_tbl_dump(multi); + DEBUGASSERT(0); + } +#endif + Curl_uint32_bset_destroy(&multi->process); + Curl_uint32_bset_destroy(&multi->dirty); + Curl_uint32_bset_destroy(&multi->pending); + Curl_uint32_bset_destroy(&multi->msgsent); + Curl_uint32_tbl_destroy(&multi->xfers); + curlx_memzero(multi, sizeof(*multi)); + curlx_free(multi); + + mresult = CURLM_OK; + } +out: + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +/* + * curl_multi_info_read() + * + * This function is the primary way for a multi/multi_socket application to + * figure out if a transfer has ended. We MUST make this function as fast as + * possible as it will be polled frequently and we MUST NOT scan any lists in + * here to figure out things. We must scale fine to thousands of handles and + * beyond. The current design is fully O(1). + */ + +CURLMsg *curl_multi_info_read(CURLM *m, int *msgs_in_queue) +{ + struct Curl_mapi_guard guard; + CURLMsg *msg_result = NULL; + + *msgs_in_queue = 0; /* default to none */ + if(CURL_MAPI_ENTER(&guard, m, multi_info_read, NULL)) { + struct Curl_multi *multi = m; + if(Curl_llist_count(&multi->msglist)) { + /* there is one or more messages in the list */ + struct Curl_llist_node *e; + struct Curl_message *msg; + + /* extract the head of the list to return */ + e = Curl_llist_head(&multi->msglist); + + msg = Curl_node_elem(e); + + /* remove the extracted entry */ + Curl_node_remove(e); + + *msgs_in_queue = curlx_uztosi(Curl_llist_count(&multi->msglist)); + + msg_result = &msg->extmsg; + } + } + CURL_MAPI_LEAVE(&guard); + return msg_result; +} + +void Curl_multi_will_close(struct Curl_easy *data, curl_socket_t s) +{ + if(data) { + struct Curl_multi *multi = data->multi; + if(multi) { + CURL_TRC_M(data, "Curl_multi_will_close fd=%" FMT_SOCKET_T, s); + Curl_multi_ev_socket_done(multi, data, s); + } + } +} + +static void multi_timeouts_init(struct Curl_easy *data) +{ + data->state.timeouts.first = EXPIRE_LAST; + data->state.timeouts.splaynode.registered = FALSE; +} + +/* + * Each Curl_easy has a list of timeouts. The add_next_timeout() is called + * when it has been removed from the splay tree because the timeout has + * expired. This function is then to advance in the list to pick the next + * timeout to use (skip the already expired ones) and add this node back to + * the splay tree again. + * + * The splay tree only has each Curl_easy as a single node and the nearest + * timeout is used to sort it on. + */ +static CURLMcode add_next_timeout(const struct curltime *pnow, + struct Curl_multi *multi, + struct Curl_easy *data) +{ + struct expire_timers *timeouts = &data->state.timeouts; + timediff_t now_us = Curl_timeouts_offset_us(&multi->timeouts, pnow); + + while(timeouts->first < EXPIRE_LAST) { + if(timeouts->offset_us[timeouts->first] <= now_us) /* already expired */ + timeouts->first = timeouts->next[timeouts->first]; + else /* timeouts are sorted, first is first in the future now */ + break; + } + + if(timeouts->first < EXPIRE_LAST) { + /* Insert this node again into the splay. Keep the timer in the list in + case we need to recompute future timers. */ + Curl_timeouts_add(&multi->timeouts, data, + timeouts->offset_us[timeouts->first]); + } + return CURLM_OK; +} + +static void multi_mark_expired_as_dirty(struct Curl_multi *multi, + const struct curltime *ts) +{ + struct Curl_easy *data = NULL; + uint32_t mid; + + /* + * The loop following here will go on as long as there are expire-times left + * to process (compared to `ts`) in the splay and 'data' will be + * re-assigned for every expired handle we deal with. + */ + while(Curl_timeouts_remove_expired(&multi->timeouts, ts, &mid)) { + /* Check if there is one (more) expired timer to deal with! This function + extracts a matching node if there is one */ + data = Curl_multi_get_easy(multi, mid); + if(!data) { + DEBUGASSERT(0); + continue; + } +#ifdef CURLVERBOSE + if(CURL_TRC_TIMER_is_verbose(data)) { + if(data->state.timeouts.first < EXPIRE_LAST) { + CURL_TRC_TIMER(data, data->state.timeouts.first, "has expired"); + } + } +#endif + (void)add_next_timeout(ts, multi, data); + Curl_multi_mark_dirty(data); + } +} + +static CURLMcode multi_run_dirty(struct Curl_multi *multi, + struct Curl_sigpipe_ctx *sigpipe_ctx, + uint32_t *pnum) +{ + CURLMcode mresult = CURLM_OK; + uint32_t mid; + + *pnum = 0; + if(Curl_uint32_bset_first(&multi->dirty, &mid)) { + do { + struct Curl_easy *data = Curl_multi_get_easy(multi, mid); + if(data) { + CURL_TRC_M(data, "multi_run_dirty"); + + if(!Curl_uint32_bset_contains(&multi->process, mid)) { + /* We are no longer processing this transfer */ + Curl_uint32_bset_remove(&multi->dirty, mid); + continue; + } + + (*pnum)++; + /* runsingle() clears the dirty mid */ + mresult = multi_runsingle(multi, data, sigpipe_ctx); + + if(CURLM_OK >= mresult) { + /* reassess event handling of data */ + mresult = Curl_multi_ev_assess_xfer(multi, data); + if(mresult) + goto out; + } + } + else { + CURL_TRC_M(multi->admin, "multi_run_dirty, %u no longer found", mid); + Curl_uint32_bset_remove(&multi->dirty, mid); + } + } while(Curl_uint32_bset_next(&multi->dirty, mid, &mid)); + } + +out: + return mresult; +} + +static CURLMcode multi_socket(struct Curl_multi *multi, + bool checkall, + curl_socket_t s, + int ev_bitmask, + int *running_handles) +{ + CURLMcode mresult = CURLM_OK; + struct Curl_sigpipe_ctx pipe_ctx; + uint32_t run_xfers; + + (void)ev_bitmask; + sigpipe_init(&pipe_ctx); + + if(checkall) { + /* *perform() deals with running_handles on its own */ + mresult = multi_perform(multi, running_handles); + + if(mresult != CURLM_BAD_HANDLE) { + /* Reassess event status of all active transfers */ + mresult = Curl_multi_ev_assess_xfer_bset(multi, &multi->process); + } + goto out; + } + + if(s != CURL_SOCKET_TIMEOUT) { + /* Mark all transfers of that socket as dirty */ + Curl_multi_ev_dirty_xfers(multi, s); + } + else { + /* Asked to run due to time-out. Clear the 'last_expire_ts' variable to + force Curl_update_timer() to trigger a callback to the app again even + if the same timeout is still the one to run after this call. That + handles the case when the application asks libcurl to run the timeout + prematurely. */ + multi->last_expire_offset_us = 0; + + /* Applications may set `socket_cb` *after* having added transfers + * first. *Then* kick off processing with a + * curl_multi_socket_action(TIMEOUT) afterwards. Make sure our + * admin handle registers its pollset with the callbacks present. */ + mresult = multi_assess_wakeup(multi); + if(mresult) + goto out; + } + + multi_mark_expired_as_dirty(multi, multi_now(multi)); + mresult = multi_run_dirty(multi, &pipe_ctx, &run_xfers); + if(mresult) + goto out; + + if(run_xfers) { + /* Running transfers takes time. With a new timestamp, we might catch + * other expires which are due now. Instead of telling the application + * to set a 0 timeout and call us again, we run them here. + * Do that only once or it might be unfair to transfers on other + * sockets. */ + multi_mark_expired_as_dirty(multi, &multi->now); + mresult = multi_run_dirty(multi, &pipe_ctx, &run_xfers); + } + +out: + sigpipe_restore(&pipe_ctx); + + if(multi_ischanged(multi, TRUE)) + multi_schedule_pending(multi); + + if(!mresult && CURL_MNTFY_HAS_ENTRIES(multi)) + mresult = Curl_mntfy_dispatch_all(multi); + + if(running_handles) { + uint32_t running = Curl_multi_xfers_running(multi); + *running_handles = (running < INT_MAX) ? (int)running : INT_MAX; + } + + if(CURLM_OK >= mresult) + mresult = Curl_update_timer(multi); + return mresult; +} + +#undef curl_multi_setopt +CURLMcode curl_multi_setopt(CURLM *m, CURLMoption option, ...) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult = CURLM_OK; + + if(CURL_MAPI_ENTER(&guard, m, multi_setopt, &mresult)) { + struct Curl_multi *multi = m; + va_list param; + unsigned long uarg; + + va_start(param, option); + + switch(option) { + case CURLMOPT_SOCKETFUNCTION: + multi->socket_cb = va_arg(param, curl_socket_callback); + break; + case CURLMOPT_SOCKETDATA: + multi->socket_userp = va_arg(param, void *); + break; + case CURLMOPT_PUSHFUNCTION: + multi->push_cb = va_arg(param, curl_push_callback); + break; + case CURLMOPT_PUSHDATA: + multi->push_userp = va_arg(param, void *); + break; + case CURLMOPT_PIPELINING: + multi->multiplexing = va_arg(param, long) & CURLPIPE_MULTIPLEX ? 1 : 0; + break; + case CURLMOPT_TIMERFUNCTION: + multi->timer_cb = va_arg(param, curl_multi_timer_callback); + break; + case CURLMOPT_TIMERDATA: + multi->timer_userp = va_arg(param, void *); + break; + case CURLMOPT_MAXCONNECTS: + uarg = va_arg(param, unsigned long); + if(uarg <= UINT_MAX) + multi->maxconnects = (unsigned int)uarg; + break; + case CURLMOPT_MAX_HOST_CONNECTIONS: + if(!curlx_sltouz(va_arg(param, long), &multi->max_host_connections)) + mresult = CURLM_BAD_FUNCTION_ARGUMENT; + break; + case CURLMOPT_MAX_TOTAL_CONNECTIONS: + if(!curlx_sltouz(va_arg(param, long), &multi->max_total_connections)) + mresult = CURLM_BAD_FUNCTION_ARGUMENT; + break; + /* options formerly used for pipelining */ + case CURLMOPT_MAX_PIPELINE_LENGTH: + break; + case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE: + break; + case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE: + break; + case CURLMOPT_PIPELINING_SITE_BL: + break; + case CURLMOPT_PIPELINING_SERVER_BL: + break; + case CURLMOPT_MAX_CONCURRENT_STREAMS: { + long streams = va_arg(param, long); + if((streams < 1) || (streams > INT_MAX)) + streams = 100; + multi->max_concurrent_streams = (unsigned int)streams; + break; + } + case CURLMOPT_NETWORK_CHANGED: { + long val = va_arg(param, long); + if(val & CURLMNWC_CLEAR_ALL) + /* In the beginning, all values available to set were 1 by mistake. We + converted this to mean "all", thus setting all the bits + automatically */ + val = CURLMNWC_CLEAR_DNS | CURLMNWC_CLEAR_CONNS; + if(val & CURLMNWC_CLEAR_DNS) { + Curl_dnscache_clear(multi->admin); + } + if(val & CURLMNWC_CLEAR_CONNS) { + Curl_cpool_nw_changed(&multi->cpool, multi->admin); + } + break; + } + case CURLMOPT_NOTIFYFUNCTION: + multi->ntfy.ntfy_cb = va_arg(param, curl_notify_callback); + break; + case CURLMOPT_NOTIFYDATA: + multi->ntfy.ntfy_cb_data = va_arg(param, void *); + break; + case CURLMOPT_RESOLVE_THREADS_MAX: +#ifdef USE_RESOLV_THREADED + uarg = va_arg(param, long); + if((uarg <= 0) || (uarg > UINT32_MAX)) + mresult = CURLM_BAD_FUNCTION_ARGUMENT; + else { + CURLcode result = Curl_async_thrdd_multi_set_props( + multi, 0, (uint32_t)uarg, 2000); + switch(result) { + case CURLE_OK: + mresult = CURLM_OK; + break; + case CURLE_BAD_FUNCTION_ARGUMENT: + mresult = CURLM_BAD_FUNCTION_ARGUMENT; + break; + case CURLE_OUT_OF_MEMORY: + mresult = CURLM_OUT_OF_MEMORY; + break; + default: + mresult = CURLM_INTERNAL_ERROR; + break; + } + } +#endif + break; + case CURLMOPT_QUICK_EXIT: + multi->quick_exit = va_arg(param, long) ? 1 : 0; + break; + default: + mresult = CURLM_UNKNOWN_OPTION; + break; + } + va_end(param); + } + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +/* we define curl_multi_socket() in the public multi.h header */ +#undef curl_multi_socket + +CURLMcode curl_multi_socket(CURLM *m, curl_socket_t s, int *running_handles) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult; + + if(CURL_MAPI_ENTER(&guard, m, multi_socket, &mresult)) { + mresult = multi_socket(m, FALSE, s, 0, running_handles); + } + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +CURLMcode curl_multi_socket_action(CURLM *m, curl_socket_t s, + int ev_bitmask, int *running_handles) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult; + + if(CURL_MAPI_ENTER(&guard, m, multi_socket_action, &mresult)) { + mresult = multi_socket(m, FALSE, s, ev_bitmask, running_handles); + } + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +CURLMcode curl_multi_socket_all(CURLM *m, int *running_handles) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult; + + if(CURL_MAPI_ENTER(&guard, m, multi_socket_all, &mresult)) { + mresult = multi_socket(m, TRUE, CURL_SOCKET_BAD, 0, running_handles); + } + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +static bool multi_has_dirties(struct Curl_multi *multi) +{ + uint32_t mid; + if(Curl_uint32_bset_first(&multi->dirty, &mid)) { + do { + struct Curl_easy *data = Curl_multi_get_easy(multi, mid); + if(data) { + if(Curl_uint32_bset_contains(&multi->process, mid)) + return TRUE; + /* We are no longer processing this transfer */ + Curl_uint32_bset_remove(&multi->dirty, mid); + } + else { + CURL_TRC_M(multi->admin, "dirty transfer %u no longer found", mid); + Curl_uint32_bset_remove(&multi->dirty, mid); + } + } while(Curl_uint32_bset_next(&multi->dirty, mid, &mid)); + } + return FALSE; +} + +static void multi_timeout(struct Curl_multi *multi, + timediff_t *pexire_offset_us, + int *timeout_ms) +{ + if(multi->dead) { + if(pexire_offset_us) + *pexire_offset_us = 0; + *timeout_ms = 0; + return; + } + + if(multi_has_dirties(multi)) { + if(pexire_offset_us) + *pexire_offset_us = Curl_timeouts_offset_us(&multi->timeouts, + multi_now(multi)); + *timeout_ms = 0; + return; + } + else { + const struct curltime *pnow = multi_now(multi); + uint32_t mid; + + *timeout_ms = Curl_timeouts_next_ms(&multi->timeouts, pnow, + pexire_offset_us, &mid); +#ifdef CURLVERBOSE + if(mid != UINT32_MAX) { + struct Curl_easy *data = Curl_multi_get_easy(multi, mid); + if(data && CURL_TRC_TIMER_is_verbose(data) && + (data->state.timeouts.first < EXPIRE_LAST)) { + CURL_TRC_TIMER(data, data->state.timeouts.first, + "gives multi timeout in %dms", *timeout_ms); + } + } +#endif + } +} + +CURLMcode curl_multi_timeout(CURLM *m, + long *timeout_ms) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult; + + if(CURL_MAPI_ENTER(&guard, m, multi_timeout, &mresult)) { + int itimeout_ms; + + multi_timeout(m, NULL, &itimeout_ms); + *timeout_ms = (long)itimeout_ms; + mresult = CURLM_OK; + } + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +/* + * Tell the application it should update its timers, if it subscribes to the + * update timer callback. + */ +CURLMcode Curl_update_timer(struct Curl_multi *multi) +{ + timediff_t timeouts_offset_us = 0; + int timeout_ms; + int rc; + bool set_value = FALSE; + + if(!multi->timer_cb || multi->dead) + return CURLM_OK; + multi_timeout(multi, &timeouts_offset_us, &timeout_ms); + + if(timeout_ms < 0 && multi->last_timeout_ms < 0) { + /* nothing to do */ + } + else if(timeout_ms < 0) { + /* there is no timeout now but there was one previously */ + CURL_TRC_M(multi->admin, "[TIMER] clear"); + timeout_ms = -1; /* normalize */ + set_value = TRUE; + } + else if(multi->last_timeout_ms < 0) { + CURL_TRC_M(multi->admin, "[TIMER] set %dms, none before", timeout_ms); + set_value = TRUE; + } + else if(multi->last_expire_offset_us != timeouts_offset_us) { + /* We had a timeout before and have one now, the absolute timestamp + * differs. The relative timeout_ms may be the same, but the starting + * point differs. Let the application restart its timer. */ + CURL_TRC_M(multi->admin, "[TIMER] set %dms, replace previous", + timeout_ms); + set_value = TRUE; + } + else { + /* We have same expire time as previously. Our relative 'timeout_ms' + * may be different now, but the application has the timer running + * and we do not to tell it to start this again. */ + } + + if(set_value) { + struct Curl_mapi_guard guard; + + multi->last_expire_offset_us = timeouts_offset_us; + multi->last_timeout_ms = timeout_ms; + CURL_CBAPI_MULTI_START(&guard, multi, multi_timer_cb); + rc = multi->timer_cb(multi, timeout_ms, multi->timer_userp); + CURL_CBAPI_MULTI_END(&guard); + if(rc == -1) { + multi->dead = TRUE; + return CURLM_ABORTED_BY_CALLBACK; + } + } + return CURLM_OK; +} + +#ifdef DEBUGBUILD +static bool multi_timeouts_check(struct Curl_easy *data) +{ + struct expire_timers *timeouts = &data->state.timeouts; + uint8_t id; + int i = 0; + for(id = timeouts->first; id < EXPIRE_LAST; id = timeouts->next[id]) { + if(++i >= EXPIRE_LAST) { + failf(data, "expire timeouts looped: %d iterations and no end", i); + return FALSE; + } + if(id == timeouts->next[id]) { + failf(data, "expire timeouts wrong: %d points to itself", (int)id); + return FALSE; + } + if((timeouts->next[id] < EXPIRE_LAST) && + (timeouts->offset_us[id] > timeouts->offset_us[timeouts->next[id]])) { + failf(data, "expire timeouts not sorted: %d happens after %d but " + "is listed before", (int)id, (int)timeouts->next[id]); + return FALSE; + } + } + return TRUE; +} +#endif + +/* + * Remove a given timestamp from the list of timeouts. + */ +static void multi_clear_timeout(struct Curl_easy *data, expire_id eid) +{ + struct expire_timers *timeouts = &data->state.timeouts; + uint8_t orig_first = timeouts->first; + uint8_t *anchor = &timeouts->first; + uint8_t id = (uint8_t)eid; + + if((unsigned)eid >= EXPIRE_LAST) { + DEBUGASSERT(0); + return; + } + + while(*anchor < EXPIRE_LAST) { + if(*anchor == id) { + *anchor = timeouts->next[id]; + break; + } + anchor = &timeouts->next[*anchor]; + } + DEBUGASSERT(multi_timeouts_check(data)); + if(Curl_timeouts_has(data)) { + struct Curl_multi *multi = data->multi; + + if(!multi) { + DEBUGASSERT(0); + return; + } + if((timeouts->first >= EXPIRE_LAST) || /* no more timeouts */ + (timeouts->first != orig_first)) { /* active timeout changed */ + Curl_timeouts_remove(&multi->timeouts, data); + } + if((timeouts->first < EXPIRE_LAST) && !Curl_timeouts_has(data)) { + Curl_timeouts_add(&multi->timeouts, data, + timeouts->offset_us[timeouts->first]); + } + } +} + +/* + * Add a timestamp to the list of timeouts. Keep the list sorted so that head + * of list is always the timeout nearest in time. + */ +static CURLMcode multi_set_timeout(struct Curl_easy *data, + const struct curltime *stamp, + expire_id eid) +{ + struct expire_timers *timeouts = &data->state.timeouts; + uint8_t *anchor = &timeouts->first; + uint8_t id = (uint8_t)eid; + + if((unsigned)eid >= EXPIRE_LAST) { + DEBUGASSERT(0); + return CURLM_BAD_FUNCTION_ARGUMENT; + } + /* remove from list, store time and re-insert */ + multi_clear_timeout(data, eid); + timeouts->offset_us[id] = + Curl_timeouts_offset_us(&data->multi->timeouts, stamp); + + while(*anchor < EXPIRE_LAST) { + if(timeouts->offset_us[*anchor] > timeouts->offset_us[id]) + break; + anchor = &timeouts->next[*anchor]; + } + timeouts->next[eid] = *anchor; + timeouts->next[eid] = *anchor; + *anchor = id; + DEBUGASSERT(multi_timeouts_check(data)); + CURL_TRC_TIMER(data, eid, "set for %" FMT_TIMEDIFF_T "us", + curlx_ptimediff_us(stamp, Curl_pgrs_now(data))); + return CURLM_OK; +} + +/* + * given a number of milliseconds from now to use to set the 'act before + * this'-time for the transfer, to be extracted by curl_multi_timeout() + * + * The timeout will be added to a queue of timeouts if it defines a moment in + * time that is later than the current head of queue. + * + * Expire replaces a former timeout using the same id if already set. + */ +void Curl_expire_set(struct Curl_easy *data, + expire_id eid, timediff_t ms, + const struct curltime *pnow) +{ + struct Curl_multi *multi = data->multi; + struct expire_timers *timeouts = &data->state.timeouts; + uint8_t prev_id = timeouts->first; + struct curltime set; + + /* this is only interesting while there is still an associated multi struct + remaining! */ + if(!multi) + return; + DEBUGASSERT(eid < EXPIRE_LAST); + if(ms > INT_MAX) + /* Cap ridiculous timeouts, 31-bit ms is still 3.5 weeks. When the time + goes to the user, it must fit in this size. */ + ms = INT_MAX; + + set = *pnow; + set.tv_sec += (time_t)(ms / 1000); /* may be a 64 to 32-bit conversion */ + set.tv_usec += (int)(ms % 1000) * 1000; + if(set.tv_usec >= 1000000) { + set.tv_sec++; + set.tv_usec -= 1000000; + } + + /* Add the timeout, will replace any previous value for this timer. */ + multi_set_timeout(data, &set, eid); + DEBUGASSERT(timeouts->first < EXPIRE_LAST); + + if(Curl_timeouts_has(data)) { + /* data has already a timeout registered. If the first timer + * was NOT the one we just set AND is still the first one, + * nothing changed from the timeouts point of view. The + * set timer triggers after the one already registered. Leave. */ + if((prev_id != eid) && (prev_id == timeouts->first)) + return; + + /* Since this is an updated time, we must remove data from + * timeouts and then add it again. */ + Curl_timeouts_remove(&multi->timeouts, data); + } + + /* Insert the new timer expiry since it is our local minimum. */ + Curl_timeouts_add(&multi->timeouts, data, + timeouts->offset_us[timeouts->first]); +} + +void Curl_expire(struct Curl_easy *data, + timediff_t milli, expire_id eid) +{ + Curl_expire_set(data, eid, milli, Curl_pgrs_now(data)); +} + +/* + * Removes the expire timer. Marks it as done. + */ +void Curl_expire_clear(struct Curl_easy *data, expire_id eid) +{ + /* remove the timer, if there */ + multi_clear_timeout(data, eid); + CURL_TRC_TIMER(data, eid, "cleared"); +} + +/* + * Clear ALL timeout values for this handle. + */ +void Curl_expire_clear_all(struct Curl_easy *data) +{ + struct Curl_multi *multi = data->multi; + + /* this is only interesting while there is still an associated multi struct + remaining! */ + if(!multi) + return; + + if(Curl_timeouts_remove(&multi->timeouts, data)) { + /* Since this is an cleared time, we must remove the previous entry from + the splay tree */ + multi_timeouts_init(data); + + if(data->id >= 0) + CURL_TRC_M(data, "[TIMEOUT] all cleared"); + } +} + +CURLMcode curl_multi_assign(CURLM *m, curl_socket_t sockfd, + void *sockp) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult; + + if(CURL_MAPI_ENTER(&guard, m, multi_assign, &mresult)) { + mresult = Curl_multi_ev_assign(m, sockfd, sockp); + } + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +static void move_pending_to_connect(struct Curl_multi *multi, + struct Curl_easy *data) +{ + DEBUGASSERT(data->mstate == MSTATE_PENDING); + + /* Remove this node from the pending set, add into process set */ + Curl_uint32_bset_remove(&multi->pending, data->mid); + Curl_uint32_bset_add(&multi->process, data->mid); + + multistate(data, MSTATE_CONNECT); + Curl_multi_mark_dirty(data); /* make it run */ +} + +/* multi_schedule_pending() moves a handle from PENDING back into the process + list and change state to CONNECT. + + We do not move all transfers because that can be a significant amount. + Since this is tried every now and then doing too many too often becomes a + performance problem. + + When there is a change for connection limits like max host connections etc, + this likely only allows one new transfer. When there is a pipewait change, + it can potentially allow hundreds of new transfers. + + We could consider an improvement where we store the queue reason and allow + more pipewait rechecks than others. */ +static void multi_schedule_pending(struct Curl_multi *multi) +{ + uint32_t mid = multi->last_pending_mid; + + if(mid) { + while(Curl_uint32_bset_next(&multi->pending, mid, &mid)) { + struct Curl_easy *data = Curl_multi_get_easy(multi, mid); + if(data) { + move_pending_to_connect(multi, data); + multi->last_pending_mid = mid; + return; + } + /* transfer no longer known, should not happen */ + Curl_uint32_bset_remove(&multi->pending, mid); + DEBUGASSERT(0); + } + /* found no pending transfers with `mid` larger than `last_pending_mid`. + * Start at the beginning of the pending set again. */ + multi->last_pending_mid = 0; + } + + if(Curl_uint32_bset_first(&multi->pending, &mid)) { + do { + struct Curl_easy *data = Curl_multi_get_easy(multi, mid); + if(data) { + move_pending_to_connect(multi, data); + multi->last_pending_mid = mid; + return; + } + /* transfer no longer known, should not happen */ + Curl_uint32_bset_remove(&multi->pending, mid); + DEBUGASSERT(0); + } while(Curl_uint32_bset_next(&multi->pending, mid, &mid)); + } +} + +unsigned int Curl_multi_max_concurrent_streams(struct Curl_multi *multi) +{ + DEBUGASSERT(multi); + return multi->max_concurrent_streams; +} + +CURL **curl_multi_get_handles(CURLM *m) +{ + struct Curl_mapi_guard guard; + CURL **a = NULL; + + if(CURL_MAPI_ENTER(&guard, m, multi_get_handles, NULL)) { + struct Curl_multi *multi = m; + void *entry; + size_t count = Curl_uint32_tbl_count(&multi->xfers); + + a = curlx_malloc(sizeof(struct Curl_easy *) * (count + 1)); + if(a) { + unsigned int i = 0; + uint32_t mid; + + if(Curl_uint32_tbl_first(&multi->xfers, &mid, &entry)) { + do { + struct Curl_easy *data = entry; + DEBUGASSERT(i < count); + if(!data->state.internal) + a[i++] = data; + } while(Curl_uint32_tbl_next(&multi->xfers, mid, &mid, &entry)); + } + a[i] = NULL; /* last entry is a NULL */ + } + } + CURL_MAPI_LEAVE(&guard); + return a; +} + +CURLMcode curl_multi_get_offt(CURLM *m, + CURLMinfo_offt info, + curl_off_t *pvalue) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult = CURLM_OK; + + if(CURL_MAPI_ENTER(&guard, m, multi_get_offt, &mresult)) { + struct Curl_multi *multi = m; + uint32_t n; + + if(!pvalue) { + mresult = CURLM_BAD_FUNCTION_ARGUMENT; + goto out; + } + + switch(info) { + case CURLMINFO_XFERS_CURRENT: + n = Curl_uint32_tbl_count(&multi->xfers); + if(n && multi->admin) + --n; + *pvalue = (curl_off_t)n; + break; + case CURLMINFO_XFERS_RUNNING: + n = Curl_uint32_bset_count(&multi->process); + if(n && Curl_uint32_bset_contains(&multi->process, multi->admin->mid)) + --n; + *pvalue = (curl_off_t)n; + break; + case CURLMINFO_XFERS_PENDING: + *pvalue = (curl_off_t)Curl_uint32_bset_count(&multi->pending); + break; + case CURLMINFO_XFERS_DONE: + *pvalue = (curl_off_t)Curl_uint32_bset_count(&multi->msgsent); + break; + case CURLMINFO_XFERS_ADDED: + *pvalue = multi->xfers_total_ever; + break; + default: + *pvalue = -1; + mresult = CURLM_UNKNOWN_OPTION; + break; + } + } +out: + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +CURLcode Curl_multi_xfer_buf_borrow(struct Curl_easy *data, + char **pbuf, size_t *pbuflen) +{ + DEBUGASSERT(data); + DEBUGASSERT(data->multi); + *pbuf = NULL; + *pbuflen = 0; + if(!data->multi) { + failf(data, "transfer has no multi handle"); + return CURLE_FAILED_INIT; + } + if(!data->set.buffer_size) { + failf(data, "transfer buffer size is 0"); + return CURLE_FAILED_INIT; + } + if(data->multi->xfer_buf_borrowed) { + failf(data, "attempt to borrow xfer_buf when already borrowed"); + return CURLE_AGAIN; + } + + if(data->multi->xfer_buf && + data->set.buffer_size > data->multi->xfer_buf_len) { + /* not large enough, get a new one */ + curlx_safefree(data->multi->xfer_buf); + data->multi->xfer_buf_len = 0; + } + + if(!data->multi->xfer_buf) { + data->multi->xfer_buf = curlx_malloc(curlx_uitouz(data->set.buffer_size)); + if(!data->multi->xfer_buf) { + failf(data, "could not allocate xfer_buf of %u bytes", + data->set.buffer_size); + return CURLE_OUT_OF_MEMORY; + } + data->multi->xfer_buf_len = data->set.buffer_size; + } + + data->multi->xfer_buf_borrowed = TRUE; + *pbuf = data->multi->xfer_buf; + *pbuflen = data->multi->xfer_buf_len; + return CURLE_OK; +} + +void Curl_multi_xfer_buf_release(struct Curl_easy *data, char *buf) +{ + (void)buf; + DEBUGASSERT(data); + DEBUGASSERT(data->multi); + DEBUGASSERT(!buf || data->multi->xfer_buf == buf); + data->multi->xfer_buf_borrowed = FALSE; +} + +CURLcode Curl_multi_xfer_ulbuf_borrow(struct Curl_easy *data, + char **pbuf, size_t *pbuflen) +{ + DEBUGASSERT(data); + DEBUGASSERT(data->multi); + *pbuf = NULL; + *pbuflen = 0; + if(!data->multi) { + failf(data, "transfer has no multi handle"); + return CURLE_FAILED_INIT; + } + if(!data->set.upload_buffer_size) { + failf(data, "transfer upload buffer size is 0"); + return CURLE_FAILED_INIT; + } + if(data->multi->xfer_ulbuf_borrowed) { + failf(data, "attempt to borrow xfer_ulbuf when already borrowed"); + return CURLE_AGAIN; + } + + if(data->multi->xfer_ulbuf && + data->set.upload_buffer_size > data->multi->xfer_ulbuf_len) { + /* not large enough, get a new one */ + curlx_safefree(data->multi->xfer_ulbuf); + data->multi->xfer_ulbuf_len = 0; + } + + if(!data->multi->xfer_ulbuf) { + data->multi->xfer_ulbuf = + curlx_malloc(curlx_uitouz(data->set.upload_buffer_size)); + if(!data->multi->xfer_ulbuf) { + failf(data, "could not allocate xfer_ulbuf of %u bytes", + data->set.upload_buffer_size); + return CURLE_OUT_OF_MEMORY; + } + data->multi->xfer_ulbuf_len = data->set.upload_buffer_size; + } + + data->multi->xfer_ulbuf_borrowed = TRUE; + *pbuf = data->multi->xfer_ulbuf; + *pbuflen = data->multi->xfer_ulbuf_len; + return CURLE_OK; +} + +void Curl_multi_xfer_ulbuf_release(struct Curl_easy *data, char *buf) +{ + (void)buf; + DEBUGASSERT(data); + DEBUGASSERT(data->multi); + DEBUGASSERT(!buf || data->multi->xfer_ulbuf == buf); + data->multi->xfer_ulbuf_borrowed = FALSE; +} + +CURLcode Curl_multi_xfer_sockbuf_borrow(struct Curl_easy *data, + size_t blen, char **pbuf) +{ + DEBUGASSERT(data); + *pbuf = NULL; + if(!data->multi) { + /* When a SHARE gets destroyed and has a connection pool, we get + * call with share->admin which does not have a multi handle. */ + *pbuf = curlx_malloc(blen); + return *pbuf ? CURLE_OK : CURLE_OUT_OF_MEMORY; + } + if(data->multi->xfer_sockbuf_borrowed) { + failf(data, "attempt to borrow xfer_sockbuf when already borrowed"); + return CURLE_AGAIN; + } + + if(data->multi->xfer_sockbuf && blen > data->multi->xfer_sockbuf_len) { + /* not large enough, get a new one */ + curlx_safefree(data->multi->xfer_sockbuf); + data->multi->xfer_sockbuf_len = 0; + } + + if(!data->multi->xfer_sockbuf) { + data->multi->xfer_sockbuf = curlx_malloc(blen); + if(!data->multi->xfer_sockbuf) { + failf(data, "could not allocate xfer_sockbuf of %zu bytes", blen); + return CURLE_OUT_OF_MEMORY; + } + data->multi->xfer_sockbuf_len = blen; + } + + data->multi->xfer_sockbuf_borrowed = TRUE; + *pbuf = data->multi->xfer_sockbuf; + return CURLE_OK; +} + +void Curl_multi_xfer_sockbuf_release(struct Curl_easy *data, char *buf) +{ + DEBUGASSERT(data); + if(!data->multi) { + /* When a SHARE gets destroyed and has a connection pool, we get + * call with share->admin which does not have a multi handle. */ + curlx_free(buf); + } + else { + DEBUGASSERT(!buf || data->multi->xfer_sockbuf == buf); + data->multi->xfer_sockbuf_borrowed = FALSE; + } +} + +static void multi_xfer_bufs_free(struct Curl_multi *multi) +{ + DEBUGASSERT(multi); + curlx_safefree(multi->xfer_buf); + multi->xfer_buf_len = 0; + multi->xfer_buf_borrowed = FALSE; + curlx_safefree(multi->xfer_ulbuf); + multi->xfer_ulbuf_len = 0; + multi->xfer_ulbuf_borrowed = FALSE; + curlx_safefree(multi->xfer_sockbuf); + multi->xfer_sockbuf_len = 0; + multi->xfer_sockbuf_borrowed = FALSE; +} + +struct Curl_easy *Curl_multi_get_easy(struct Curl_multi *multi, + uint32_t mid) +{ + struct Curl_easy *data = Curl_uint32_tbl_get(&multi->xfers, mid); + if(GOOD_EASY_HANDLE(data)) + return data; + CURL_TRC_M(multi->admin, "invalid easy handle in xfer table for mid=%u", + mid); + Curl_uint32_tbl_remove(&multi->xfers, mid); + return NULL; +} + +bool Curl_multi_knows_easy(struct Curl_multi *multi, struct Curl_easy *data) +{ + return Curl_uint32_tbl_get(&multi->xfers, data->mid) == data; +} + +uint32_t Curl_multi_xfers_running(struct Curl_multi *multi) +{ + if(!multi) { + DEBUGASSERT(0); + return 0; + } + return multi->xfers_alive; +} + +uint32_t Curl_multi_xfers_attached(struct Curl_multi *multi) +{ + if(!multi || !multi->admin) { + DEBUGASSERT(0); + return 0; + } + /* Discount the admin handle */ + return Curl_uint32_tbl_count(&multi->xfers) - 1; +} + +void Curl_multi_mark_dirty(struct Curl_easy *data) +{ + if(data->multi && data->mid != UINT32_MAX) + Curl_uint32_bset_add(&data->multi->dirty, data->mid); +} + +void Curl_multi_clear_dirty(struct Curl_easy *data) +{ + if(data->multi && data->mid != UINT32_MAX) + Curl_uint32_bset_remove(&data->multi->dirty, data->mid); +} + +CURLMcode curl_multi_notify_enable(CURLM *m, unsigned int notification) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult = CURLM_OK; + + if(CURL_MAPI_ENTER(&guard, m, multi_notify_enable, &mresult)) { + mresult = Curl_mntfy_enable(m, notification); + } + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +CURLMcode curl_multi_notify_disable(CURLM *m, unsigned int notification) +{ + struct Curl_mapi_guard guard; + CURLMcode mresult = CURLM_OK; + + if(CURL_MAPI_ENTER(&guard, m, multi_notify_disable, &mresult)) { + mresult = Curl_mntfy_disable(m, notification); + } + CURL_MAPI_LEAVE(&guard); + return mresult; +} + +#ifdef DEBUGBUILD +static void multi_xfer_dump(struct Curl_multi *multi, uint32_t mid, + void *entry) +{ + struct Curl_easy *data = entry; + + (void)multi; + if(!data) { + curl_mfprintf(stderr, "mid=%u, entry=NULL, bug in xfer table?\n", mid); + } + else { + curl_mfprintf(stderr, "mid=%u, magic=%s, p=%p, id=%" FMT_OFF_T + ", url=%s\n", + mid, + (data->magic == CURLEASY_MAGIC_NUMBER) ? "GOOD" : "BAD!", + (void *)data, data->id, Curl_bufref_ptr(&data->state.url)); + } +} + +static void multi_xfer_tbl_dump(struct Curl_multi *multi) +{ + uint32_t mid; + void *entry; + curl_mfprintf(stderr, "=== multi xfer table (count=%u, capacity=%u\n", + Curl_uint32_tbl_count(&multi->xfers), + Curl_uint32_tbl_capacity(&multi->xfers)); + if(Curl_uint32_tbl_first(&multi->xfers, &mid, &entry)) { + multi_xfer_dump(multi, mid, entry); + while(Curl_uint32_tbl_next(&multi->xfers, mid, &mid, &entry)) + multi_xfer_dump(multi, mid, entry); + } + curl_mfprintf(stderr, "===\n"); + fflush(stderr); +} +#endif /* DEBUGBUILD */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi_ev.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi_ev.c new file mode 100644 index 0000000000..3b7eeb0dc3 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi_ev.c @@ -0,0 +1,647 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "url.h" +#include "cfilters.h" +#include "curl_trc.h" +#include "multiif.h" +#include "multi_ev.h" +#include "select.h" +#include "uint-bset.h" +#include "uint-spbset.h" +#include "multihandle.h" + +#ifdef DEBUGBUILD +#define SH_ENTRY_MAGIC 0x570091d +#endif + +/* Information about a socket for which we inform the libcurl application + * what to supervise (CURL_POLL_IN/CURL_POLL_OUT/CURL_POLL_REMOVE) + */ +struct mev_sh_entry { + struct uint32_spbset xfers; /* bitset of transfers `mid`s on this socket */ + struct connectdata *conn; /* connection using this socket or NULL */ + void *user_data; /* libcurl app data via curl_multi_assign() */ + unsigned int action; /* CURL_POLL_IN/CURL_POLL_OUT we last told the + * libcurl application to watch out for */ + unsigned int readers; /* this many transfers want to read */ + unsigned int writers; /* this many transfers want to write */ +#ifdef DEBUGBUILD + unsigned int magic; +#endif + BIT(announced); /* this socket has been passed to the socket + callback at least once */ +}; + +static size_t mev_sh_entry_hash(void *key, size_t key_length, size_t slots_num) +{ + curl_socket_t fd = *((curl_socket_t *)key); + (void)key_length; + return (fd % (curl_socket_t)slots_num); +} + +static size_t mev_sh_entry_compare(void *k1, size_t k1_len, + void *k2, size_t k2_len) +{ + (void)k1_len; + (void)k2_len; + return (*((curl_socket_t *)k1)) == (*((curl_socket_t *)k2)); +} + +/* sockhash entry destructor callback */ +static void mev_sh_entry_dtor(void *freethis) +{ + struct mev_sh_entry *entry = (struct mev_sh_entry *)freethis; + Curl_uint32_spbset_destroy(&entry->xfers); +#ifdef DEBUGBUILD + entry->magic = 0; +#endif + curlx_free(entry); +} + +/* look up a given socket in the socket hash, skip invalid sockets */ +static struct mev_sh_entry *mev_sh_entry_get(struct Curl_hash *sh, + curl_socket_t s) +{ + if(s != CURL_SOCKET_BAD) { + /* only look for proper sockets */ + return Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t)); + } + return NULL; +} + +/* make sure this socket is present in the hash for this handle */ +static struct mev_sh_entry *mev_sh_entry_add(struct Curl_hash *sh, + curl_socket_t s) +{ + struct mev_sh_entry *there = mev_sh_entry_get(sh, s); + struct mev_sh_entry *check; + + if(there) { + /* it is present, return fine */ + return there; + } + + /* not present, add it */ + check = curlx_calloc(1, sizeof(struct mev_sh_entry)); + if(!check) + return NULL; /* major failure */ + + Curl_uint32_spbset_init(&check->xfers); + + /* make/add new hash entry */ + if(!Curl_hash_add(sh, (char *)&s, sizeof(curl_socket_t), check)) { + mev_sh_entry_dtor(check); + return NULL; /* major failure */ + } +#ifdef DEBUGBUILD + check->magic = SH_ENTRY_MAGIC; +#endif + return check; /* things are good in sockhash land */ +} + +/* delete the given socket entry from the hash */ +static void mev_sh_entry_kill(struct Curl_multi *multi, curl_socket_t s) +{ + Curl_hash_delete(&multi->ev.sh_entries, (char *)&s, sizeof(curl_socket_t)); +} + +static size_t mev_sh_entry_user_count(struct mev_sh_entry *e) +{ + return Curl_uint32_spbset_count(&e->xfers) + (e->conn ? 1 : 0); +} + +static bool mev_sh_entry_xfer_known(struct mev_sh_entry *e, + struct Curl_easy *data) +{ + return Curl_uint32_spbset_contains(&e->xfers, data->mid); +} + +static bool mev_sh_entry_conn_known(struct mev_sh_entry *e, + struct connectdata *conn) +{ + return (e->conn == conn); +} + +static bool mev_sh_entry_xfer_add(struct mev_sh_entry *e, + struct Curl_easy *data) +{ + /* detect weird values */ + DEBUGASSERT(mev_sh_entry_user_count(e) < 100000); + return Curl_uint32_spbset_add(&e->xfers, data->mid); +} + +static bool mev_sh_entry_conn_add(struct mev_sh_entry *e, + struct connectdata *conn) +{ + /* detect weird values */ + DEBUGASSERT(mev_sh_entry_user_count(e) < 100000); + DEBUGASSERT(!e->conn); + if(e->conn) + return FALSE; + e->conn = conn; + return TRUE; +} + +static bool mev_sh_entry_xfer_remove(struct mev_sh_entry *e, + struct Curl_easy *data) +{ + bool present = Curl_uint32_spbset_contains(&e->xfers, data->mid); + if(present) + Curl_uint32_spbset_remove(&e->xfers, data->mid); + return present; +} + +static bool mev_sh_entry_conn_remove(struct mev_sh_entry *e, + struct connectdata *conn) +{ + DEBUGASSERT(e->conn == conn); + if(e->conn == conn) { + e->conn = NULL; + return TRUE; + } + return FALSE; +} + +/* Purge any information about socket `s`. + * Let the socket callback know as well when necessary */ +static CURLMcode mev_forget_socket(struct Curl_multi *multi, + struct Curl_easy *data, + curl_socket_t s, + const char *cause) +{ + struct mev_sh_entry *entry = mev_sh_entry_get(&multi->ev.sh_entries, s); + int rc = 0; + + if(!entry) /* we never knew or already forgot about this socket */ + return CURLM_OK; + + /* We managed this socket before, tell the socket callback to forget it. */ + if(entry->announced && multi->socket_cb) { + struct Curl_mapi_guard guard; + + NOVERBOSE((void)cause); + CURL_TRC_M(data, "ev %s, call(fd=%" FMT_SOCKET_T ", ev=REMOVE)", cause, s); + CURL_CBAPI_MULTI_START(&guard, multi, multi_socket_cb); + rc = multi->socket_cb(data, s, CURL_POLL_REMOVE, + multi->socket_userp, entry->user_data); + CURL_CBAPI_END(&guard); + entry = mev_sh_entry_get(&multi->ev.sh_entries, s); + if(entry) + entry->announced = FALSE; + } + + mev_sh_entry_kill(multi, s); + if(rc == -1) { + multi->dead = TRUE; + return CURLM_ABORTED_BY_CALLBACK; + } + return CURLM_OK; +} + +static CURLMcode mev_sh_entry_update(struct Curl_multi *multi, + struct Curl_easy *data, + struct mev_sh_entry *entry, + curl_socket_t s, + unsigned char last_action, + unsigned char cur_action) +{ + int rc, comboaction; + + /* we should only be called when the callback exists */ + DEBUGASSERT(multi->socket_cb); + DEBUGASSERT(entry->magic == SH_ENTRY_MAGIC); + if(!multi->socket_cb) + return CURLM_OK; + + /* Transfer `data` goes from `last_action` to `cur_action` on socket `s` + * with `multi->ev.sh_entries` entry `entry`. Update `entry` and trigger + * `multi->socket_cb` on change, if the callback is set. */ + if(last_action == cur_action) /* nothing from `data` changed */ + return CURLM_OK; + + if(last_action & CURL_POLL_IN) { + DEBUGASSERT(entry->readers); + if(!(cur_action & CURL_POLL_IN)) + entry->readers--; + } + else if(cur_action & CURL_POLL_IN) + entry->readers++; + + if(last_action & CURL_POLL_OUT) { + DEBUGASSERT(entry->writers); + if(!(cur_action & CURL_POLL_OUT)) + entry->writers--; + } + else if(cur_action & CURL_POLL_OUT) + entry->writers++; + + DEBUGASSERT(entry->readers <= mev_sh_entry_user_count(entry)); + DEBUGASSERT(entry->writers <= mev_sh_entry_user_count(entry)); + DEBUGASSERT(entry->writers + entry->readers); + + CURL_TRC_M(data, "ev update fd=%" FMT_SOCKET_T ", action '%s%s' -> '%s%s'" + " (%u/%u r/w)", s, + (last_action & CURL_POLL_IN) ? "IN" : "", + (last_action & CURL_POLL_OUT) ? "OUT" : "", + (cur_action & CURL_POLL_IN) ? "IN" : "", + (cur_action & CURL_POLL_OUT) ? "OUT" : "", + entry->readers, entry->writers); + + comboaction = (entry->writers ? CURL_POLL_OUT : 0) | + (entry->readers ? CURL_POLL_IN : 0); + if(((int)entry->action == comboaction)) /* nothing for socket changed */ + return CURLM_OK; + + CURL_TRC_M(data, "ev update call(fd=%" FMT_SOCKET_T ", ev=%s%s)", + s, (comboaction & CURL_POLL_IN) ? "IN" : "", + (comboaction & CURL_POLL_OUT) ? "OUT" : ""); + { + struct Curl_mapi_guard guard; + CURL_CBAPI_MULTI_START(&guard, multi, multi_socket_cb); + rc = multi->socket_cb(data, s, comboaction, multi->socket_userp, + entry->user_data); + CURL_CBAPI_MULTI_END(&guard); + } + if(rc == -1) { + multi->dead = TRUE; + return CURLM_ABORTED_BY_CALLBACK; + } + /* curl_easy_pause() is documented as callable from any callback; it + * re-enters mev_assess() which may free this 'entry'. Re-fetch. */ + entry = mev_sh_entry_get(&multi->ev.sh_entries, s); + if(entry) { + DEBUGASSERT(entry->magic == SH_ENTRY_MAGIC); + entry->announced = TRUE; + entry->action = (unsigned int)comboaction; + } + return CURLM_OK; +} + +static CURLMcode mev_pollset_diff(struct Curl_multi *multi, + struct Curl_easy *data, + struct connectdata *conn, + struct easy_pollset *ps, + struct easy_pollset *prev_ps) +{ + struct mev_sh_entry *entry; + curl_socket_t s; + unsigned int i, j; + CURLMcode mresult; + + /* The transfer `data` reports in `ps` the sockets it is interested + * in and which combination of CURL_POLL_IN/CURL_POLL_OUT it wants + * to have monitored for events. + * There can be more than 1 transfer interested in the same socket + * and 1 transfer might be interested in more than 1 socket. + * `prev_ps` is the pollset copy from the previous call here. On + * the 1st call it will be empty. + */ + DEBUGASSERT(ps); + DEBUGASSERT(prev_ps); + + /* Handle changes to sockets the transfer is interested in. */ + for(i = 0; i < ps->n; i++) { + unsigned char last_action; + bool first_time = FALSE; /* data/conn appears first time on socket */ + + s = ps->sockets[i]; + /* Have we handled this socket before? */ + entry = mev_sh_entry_get(&multi->ev.sh_entries, s); + if(!entry) { + /* new socket, add new entry */ + first_time = TRUE; + entry = mev_sh_entry_add(&multi->ev.sh_entries, s); + if(!entry) /* fatal */ + return CURLM_OUT_OF_MEMORY; + CURL_TRC_M(data, "ev new entry fd=%" FMT_SOCKET_T, s); + } + else if(conn) { + first_time = !mev_sh_entry_conn_known(entry, conn); + } + else { + first_time = !mev_sh_entry_xfer_known(entry, data); + } + + /* What was the previous action the transfer had regarding this socket? + * If the transfer is new to the socket, disregard the information + * in `last_poll`, because the socket might have been destroyed and + * reopened. We would have cleared the sh_entry for that, but the socket + * might still be mentioned in the hashed pollsets. */ + last_action = 0; + if(first_time) { + if(conn) { + if(!mev_sh_entry_conn_add(entry, conn)) + return CURLM_OUT_OF_MEMORY; + } + else { + if(!mev_sh_entry_xfer_add(entry, data)) + return CURLM_OUT_OF_MEMORY; + } + CURL_TRC_M(data, "ev entry fd=%" FMT_SOCKET_T ", added %s #%" FMT_OFF_T + ", total=%u/%d (xfer/conn)", s, + conn ? "connection" : "transfer", + conn ? conn->connection_id : data->mid, + Curl_uint32_spbset_count(&entry->xfers), + entry->conn ? 1 : 0); + } + else { + for(j = 0; j < prev_ps->n; j++) { + if(s == prev_ps->sockets[j]) { + last_action = prev_ps->actions[j]; + break; + } + } + } + /* track readers/writers changes and report to socket callback */ + mresult = mev_sh_entry_update(multi, data, entry, s, + last_action, ps->actions[i]); + if(mresult) + return mresult; + } + + /* Handle changes to sockets the transfer is NO LONGER interested in. */ + for(i = 0; i < prev_ps->n; i++) { + bool stillused = FALSE; + + s = prev_ps->sockets[i]; + for(j = 0; j < ps->n; j++) { + if(s == ps->sockets[j]) { + /* socket is still supervised */ + stillused = TRUE; + break; + } + } + if(stillused) + continue; + + entry = mev_sh_entry_get(&multi->ev.sh_entries, s); + /* if entry does not exist, we were either never told about it or + * have already cleaned up this socket via Curl_multi_ev_socket_done(). + * In other words: this is perfectly normal */ + if(!entry) + continue; + + if(conn && !mev_sh_entry_conn_remove(entry, conn)) { + /* `conn` says in `prev_ps` that it had been using a socket, + * but `conn` has not been registered for it. + * This should not happen if our book-keeping is correct? */ + CURL_TRC_M(data, "ev entry fd=%" FMT_SOCKET_T ", conn lost " + "interest but is not registered", s); + DEBUGASSERT(NULL); + continue; + } + + if(!conn && !mev_sh_entry_xfer_remove(entry, data)) { + /* `data` says in `prev_ps` that it had been using a socket, + * but `data` has not been registered for it. + * This should not happen if our book-keeping is correct? */ + CURL_TRC_M(data, "ev entry fd=%" FMT_SOCKET_T ", transfer lost " + "interest but is not registered", s); + DEBUGASSERT(NULL); + continue; + } + + if(mev_sh_entry_user_count(entry)) { + /* track readers/writers changes and report to socket callback */ + mresult = mev_sh_entry_update(multi, data, entry, s, + prev_ps->actions[i], 0); + if(mresult) + return mresult; + CURL_TRC_M(data, "ev entry fd=%" FMT_SOCKET_T ", removed transfer, " + "total=%u/%d (xfer/conn)", s, + Curl_uint32_spbset_count(&entry->xfers), + entry->conn ? 1 : 0); + } + else { + mresult = mev_forget_socket(multi, data, s, "last user gone"); + if(mresult) + return mresult; + } + } /* for loop over num */ + + /* Remember for next time */ + Curl_pollset_move(prev_ps, ps); + return CURLM_OK; +} + +static void mev_pollset_dtor(void *key, size_t klen, void *entry) +{ + struct easy_pollset *ps = entry; + (void)key; + (void)klen; + if(ps) { + Curl_pollset_cleanup(ps); + curlx_free(ps); + } +} + +static struct easy_pollset *mev_add_new_conn_pollset(struct connectdata *conn) +{ + struct easy_pollset *ps; + + ps = Curl_pollset_create(); + if(!ps) + return NULL; + if(Curl_conn_meta_set(conn, CURL_META_MEV_POLLSET, ps, mev_pollset_dtor)) + return NULL; + return ps; +} + +static struct easy_pollset *mev_add_new_xfer_pollset(struct Curl_easy *data) +{ + struct easy_pollset *ps; + + ps = Curl_pollset_create(); + if(!ps) + return NULL; + if(Curl_meta_set(data, CURL_META_MEV_POLLSET, ps, mev_pollset_dtor)) + return NULL; + return ps; +} + +static struct easy_pollset *mev_get_last_pollset(struct Curl_easy *data, + struct connectdata *conn) +{ + if(data) { + if(conn) + return Curl_conn_meta_get(conn, CURL_META_MEV_POLLSET); + return Curl_meta_get(data, CURL_META_MEV_POLLSET); + } + return NULL; +} + +static CURLMcode mev_assess(struct Curl_multi *multi, + struct Curl_easy *data, + struct connectdata *conn) +{ + struct easy_pollset ps, *last_ps; + CURLMcode mresult = CURLM_OK; + + if(!multi || !multi->socket_cb) + return CURLM_OK; + + Curl_pollset_init(&ps); + if(conn) { + CURLcode result = Curl_conn_adjust_pollset(data, conn, &ps); + if(result) { + mresult = (result == CURLE_OUT_OF_MEMORY) ? + CURLM_OUT_OF_MEMORY : CURLM_INTERNAL_ERROR; + goto out; + } + } + else + Curl_multi_pollset(data, &ps); + last_ps = mev_get_last_pollset(data, conn); + + if(!last_ps && ps.n) { + if(conn) + last_ps = mev_add_new_conn_pollset(conn); + else + last_ps = mev_add_new_xfer_pollset(data); + if(!last_ps) { + mresult = CURLM_OUT_OF_MEMORY; + goto out; + } + } + + if(last_ps) + mresult = mev_pollset_diff(multi, data, conn, &ps, last_ps); + else + DEBUGASSERT(!ps.n); +out: + Curl_pollset_cleanup(&ps); + return mresult; +} + +CURLMcode Curl_multi_ev_assess_xfer(struct Curl_multi *multi, + struct Curl_easy *data) +{ + return mev_assess(multi, data, NULL); +} + +CURLMcode Curl_multi_ev_assess_conn(struct Curl_multi *multi, + struct Curl_easy *data, + struct connectdata *conn) +{ + return mev_assess(multi, data, conn); +} + +CURLMcode Curl_multi_ev_assess_xfer_bset(struct Curl_multi *multi, + struct uint32_bset *set) +{ + uint32_t mid; + CURLMcode mresult = CURLM_OK; + + if(multi && multi->socket_cb && Curl_uint32_bset_first(set, &mid)) { + do { + struct Curl_easy *data = Curl_multi_get_easy(multi, mid); + if(data) { + mresult = Curl_multi_ev_assess_xfer(multi, data); + } + } while(!mresult && Curl_uint32_bset_next(set, mid, &mid)); + } + return mresult; +} + +CURLMcode Curl_multi_ev_assign(struct Curl_multi *multi, + curl_socket_t s, + void *user_data) +{ + struct mev_sh_entry *e = mev_sh_entry_get(&multi->ev.sh_entries, s); + if(!e) + return CURLM_BAD_SOCKET; + e->user_data = user_data; + return CURLM_OK; +} + +void Curl_multi_ev_dirty_xfers(struct Curl_multi *multi, + curl_socket_t s) +{ + struct mev_sh_entry *entry; + + DEBUGASSERT(s != CURL_SOCKET_TIMEOUT); + entry = mev_sh_entry_get(&multi->ev.sh_entries, s); + + /* Unmatched socket, we cannot act on it but we ignore this fact. In + real-world tests it has been proved that libevent can in fact give + the application actions even though the socket was previously + asked to get removed, so thus we better survive stray socket actions + and move on. */ + if(entry) { + struct Curl_easy *data; + uint32_t mid; + + if(Curl_uint32_spbset_first(&entry->xfers, &mid)) { + do { + data = Curl_multi_get_easy(multi, mid); + if(data) { + Curl_multi_mark_dirty(data); + } + else { + CURL_TRC_M(multi->admin, "socket transfer %u no longer found", mid); + Curl_uint32_spbset_remove(&entry->xfers, mid); + } + } while(Curl_uint32_spbset_next(&entry->xfers, mid, &mid)); + } + + if(entry->conn) + Curl_multi_mark_dirty(multi->admin); + } +} + +void Curl_multi_ev_socket_done(struct Curl_multi *multi, + struct Curl_easy *data, curl_socket_t s) +{ + mev_forget_socket(multi, data, s, "socket done"); +} + +void Curl_multi_ev_xfer_done(struct Curl_multi *multi, + struct Curl_easy *data) +{ + DEBUGASSERT(!data->conn); /* transfer should have been detached */ + (void)mev_assess(multi, data, NULL); + Curl_meta_remove(data, CURL_META_MEV_POLLSET); +} + +void Curl_multi_ev_conn_done(struct Curl_multi *multi, + struct Curl_easy *data, + struct connectdata *conn) +{ + (void)mev_assess(multi, data, conn); + Curl_conn_meta_remove(conn, CURL_META_MEV_POLLSET); +} + +void Curl_multi_ev_init(struct Curl_multi *multi, size_t hashsize) +{ + Curl_hash_init(&multi->ev.sh_entries, hashsize, mev_sh_entry_hash, + mev_sh_entry_compare, mev_sh_entry_dtor); +} + +void Curl_multi_ev_cleanup(struct Curl_multi *multi) +{ + Curl_hash_destroy(&multi->ev.sh_entries); +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi_ev.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi_ev.h new file mode 100644 index 0000000000..ddbb9331d3 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi_ev.h @@ -0,0 +1,80 @@ +#ifndef HEADER_CURL_MULTI_EV_H +#define HEADER_CURL_MULTI_EV_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "hash.h" + +struct Curl_easy; +struct Curl_multi; +struct easy_pollset; +struct uint32_bset; + +/* meta key for event pollset at easy handle or connection */ +#define CURL_META_MEV_POLLSET "meta:mev:ps" + +struct curl_multi_ev { + struct Curl_hash sh_entries; +}; + +/* Setup/teardown of multi event book-keeping. */ +void Curl_multi_ev_init(struct Curl_multi *multi, size_t hashsize); +void Curl_multi_ev_cleanup(struct Curl_multi *multi); + +/* Assign a 'user_data' to be passed to the socket callback when + * invoked with the given socket. This will fail if this socket + * is not active, e.g. the application has not been told to monitor it. */ +CURLMcode Curl_multi_ev_assign(struct Curl_multi *multi, curl_socket_t s, + void *user_data); + +/* Assess the transfer by getting its current pollset, compute + * any changes to the last one and inform the application's socket + * callback if things have changed. */ +CURLMcode Curl_multi_ev_assess_xfer(struct Curl_multi *multi, + struct Curl_easy *data); +/* Assess all easy handles on the list */ +CURLMcode Curl_multi_ev_assess_xfer_bset(struct Curl_multi *multi, + struct uint32_bset *set); +/* Assess the connection by getting its current pollset */ +CURLMcode Curl_multi_ev_assess_conn(struct Curl_multi *multi, + struct Curl_easy *data, + struct connectdata *conn); + +/* Mark all transfers tied to the given socket as dirty */ +void Curl_multi_ev_dirty_xfers(struct Curl_multi *multi, + curl_socket_t s); + +/* Socket will be closed, forget anything we know about it. */ +void Curl_multi_ev_socket_done(struct Curl_multi *multi, + struct Curl_easy *data, curl_socket_t s); + +/* Transfer is removed from the multi */ +void Curl_multi_ev_xfer_done(struct Curl_multi *multi, + struct Curl_easy *data); + +/* Connection is being destroyed */ +void Curl_multi_ev_conn_done(struct Curl_multi *multi, + struct Curl_easy *data, + struct connectdata *conn); + +#endif /* HEADER_CURL_MULTI_EV_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi_ntfy.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi_ntfy.c new file mode 100644 index 0000000000..48c3723951 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi_ntfy.c @@ -0,0 +1,213 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "curl_trc.h" +#include "multihandle.h" +#include "multiif.h" +#include "multi_ntfy.h" + + +struct mntfy_entry { + uint32_t mid; + uint32_t type; +}; + +#define CURL_MNTFY_CHUNK_SIZE 128 + +struct mntfy_chunk { + struct mntfy_chunk *next; + size_t r_offset; + size_t w_offset; + struct mntfy_entry entries[CURL_MNTFY_CHUNK_SIZE]; +}; + +static struct mntfy_chunk *mnfty_chunk_create(void) +{ + return curlx_calloc(1, sizeof(struct mntfy_chunk)); +} + +static void mnfty_chunk_destroy(struct mntfy_chunk *chunk) +{ + curlx_free(chunk); +} + +static void mnfty_chunk_reset(struct mntfy_chunk *chunk) +{ + memset(chunk, 0, sizeof(*chunk)); +} + +static bool mntfy_chunk_append(struct mntfy_chunk *chunk, + struct Curl_easy *data, + uint32_t type) +{ + struct mntfy_entry *e; + + if(chunk->w_offset >= CURL_MNTFY_CHUNK_SIZE) + return FALSE; + e = &chunk->entries[chunk->w_offset++]; + e->mid = data->mid; + e->type = type; + return TRUE; +} + +static struct mntfy_chunk *mntfy_non_full_tail(struct curl_multi_ntfy *mntfy) +{ + struct mntfy_chunk *chunk; + if(!mntfy->tail) { + chunk = mnfty_chunk_create(); + if(!chunk) + return NULL; + DEBUGASSERT(!mntfy->head); + mntfy->head = mntfy->tail = chunk; + return chunk; + } + else if(mntfy->tail->w_offset < CURL_MNTFY_CHUNK_SIZE) + return mntfy->tail; + else { /* tail is full. */ + chunk = mnfty_chunk_create(); + if(!chunk) + return NULL; + DEBUGASSERT(mntfy->head); + mntfy->tail->next = chunk; + mntfy->tail = chunk; + return chunk; + } +} + +static void mntfy_chunk_dispatch_all(struct Curl_multi *multi, + struct mntfy_chunk *chunk) +{ + struct mntfy_entry *e; + struct Curl_easy *data; + + if(multi->ntfy.ntfy_cb) { + while((chunk->r_offset < chunk->w_offset) && !multi->ntfy.failure) { + e = &chunk->entries[chunk->r_offset]; + data = e->mid ? Curl_multi_get_easy(multi, e->mid) : multi->admin; + /* only when notification has not been disabled in the meantime */ + if(data && Curl_uint32_bset_contains(&multi->ntfy.enabled, e->type)) { + /* this may cause new notifications to be added! */ + CURL_TRC_M(multi->admin, "[NTFY] dispatch %u to xfer %u", + e->type, e->mid); + multi->ntfy.ntfy_cb(multi, e->type, data, multi->ntfy.ntfy_cb_data); + } + /* once dispatched, safe to increment */ + chunk->r_offset++; + } + } + mnfty_chunk_reset(chunk); +} + +void Curl_mntfy_init(struct Curl_multi *multi) +{ + memset(&multi->ntfy, 0, sizeof(multi->ntfy)); + Curl_uint32_bset_init(&multi->ntfy.enabled); +} + +CURLMcode Curl_mntfy_resize(struct Curl_multi *multi) +{ + if(Curl_uint32_bset_resize(&multi->ntfy.enabled, CURLMNOTIFY_EASY_DONE + 1)) + return CURLM_OUT_OF_MEMORY; + return CURLM_OK; +} + +void Curl_mntfy_cleanup(struct Curl_multi *multi) +{ + while(multi->ntfy.head) { + struct mntfy_chunk *chunk = multi->ntfy.head; + multi->ntfy.head = chunk->next; + mnfty_chunk_destroy(chunk); + } + multi->ntfy.tail = NULL; + Curl_uint32_bset_destroy(&multi->ntfy.enabled); +} + +CURLMcode Curl_mntfy_enable(struct Curl_multi *multi, unsigned int type) +{ + if(type > CURLMNOTIFY_EASY_DONE) + return CURLM_UNKNOWN_OPTION; + Curl_uint32_bset_add(&multi->ntfy.enabled, type); + return CURLM_OK; +} + +CURLMcode Curl_mntfy_disable(struct Curl_multi *multi, unsigned int type) +{ + if(type > CURLMNOTIFY_EASY_DONE) + return CURLM_UNKNOWN_OPTION; + Curl_uint32_bset_remove(&multi->ntfy.enabled, (uint32_t)type); + return CURLM_OK; +} + +void Curl_mntfy_add(struct Curl_easy *data, unsigned int type) +{ + struct Curl_multi *multi = data ? data->multi : NULL; + if(multi && multi->ntfy.ntfy_cb && !multi->ntfy.failure && + Curl_uint32_bset_contains(&multi->ntfy.enabled, (uint32_t)type)) { + /* append to list of outstanding notifications */ + struct mntfy_chunk *tail = mntfy_non_full_tail(&multi->ntfy); + CURL_TRC_M(data, "[NTFY] add %u for xfer %u", type, data->mid); + if(tail) + mntfy_chunk_append(tail, data, (uint32_t)type); + else + multi->ntfy.failure = CURLM_OUT_OF_MEMORY; + multi->ntfy.has_entries = TRUE; + } +} + +CURLMcode Curl_mntfy_dispatch_all(struct Curl_multi *multi) +{ + struct Curl_mapi_guard guard; + + if(!multi) + return CURLM_BAD_FUNCTION_ARGUMENT; + + CURL_CBAPI_MULTI_START(&guard, multi, multi_ntfy_cb); + + while(multi->ntfy.head && !multi->ntfy.failure) { + struct mntfy_chunk *chunk = multi->ntfy.head; + /* this may cause new notifications to be added! */ + mntfy_chunk_dispatch_all(multi, chunk); + DEBUGASSERT(chunk->r_offset == chunk->w_offset); + + if(chunk == multi->ntfy.tail) /* last one, keep */ + break; + DEBUGASSERT(chunk->next); + DEBUGASSERT(multi->ntfy.head != multi->ntfy.tail); + multi->ntfy.head = chunk->next; + mnfty_chunk_destroy(chunk); + } + + CURL_CBAPI_MULTI_END(&guard); + + if(multi->ntfy.failure) { + CURLMcode mresult = multi->ntfy.failure; + multi->ntfy.failure = CURLM_OK; /* reset, once delivered */ + return mresult; + } + else + multi->ntfy.has_entries = FALSE; + return CURLM_OK; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi_ntfy.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi_ntfy.h new file mode 100644 index 0000000000..05df2d6681 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/multi_ntfy.h @@ -0,0 +1,60 @@ +#ifndef HEADER_CURL_MULTI_NTFY_H +#define HEADER_CURL_MULTI_NTFY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "uint-bset.h" + +struct Curl_easy; +struct Curl_multi; + +struct curl_multi_ntfy { + curl_notify_callback ntfy_cb; + void *ntfy_cb_data; + struct uint32_bset enabled; + struct mntfy_chunk *head; + struct mntfy_chunk *tail; + CURLMcode failure; + BIT(has_entries); +}; + +void Curl_mntfy_init(struct Curl_multi *multi); +CURLMcode Curl_mntfy_resize(struct Curl_multi *multi); +void Curl_mntfy_cleanup(struct Curl_multi *multi); + +CURLMcode Curl_mntfy_enable(struct Curl_multi *multi, unsigned int type); +CURLMcode Curl_mntfy_disable(struct Curl_multi *multi, unsigned int type); + +void Curl_mntfy_add(struct Curl_easy *data, unsigned int type); + +#define CURLM_NTFY(d, t) \ + do { \ + if((d) && (d)->multi && (d)->multi->ntfy.ntfy_cb) \ + Curl_mntfy_add((d), (t)); \ + } while(0) + +#define CURL_MNTFY_HAS_ENTRIES(m) ((m)->ntfy.has_entries) + +CURLMcode Curl_mntfy_dispatch_all(struct Curl_multi *multi); + +#endif /* HEADER_CURL_MULTI_NTFY_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/multihandle.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/multihandle.h new file mode 100644 index 0000000000..2a8fba1583 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/multihandle.h @@ -0,0 +1,215 @@ +#ifndef HEADER_CURL_MULTIHANDLE_H +#define HEADER_CURL_MULTIHANDLE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "api.h" +#include "llist.h" +#include "hash.h" +#include "conncache.h" +#include "cshutdn.h" +#include "multi_ev.h" +#include "multi_ntfy.h" +#include "psl.h" +#include "socketpair.h" +#include "splay.h" +#include "uint-bset.h" +#include "uint-spbset.h" +#include "uint-table.h" +#include "vdns/dnscache.h" + +struct connectdata; +struct Curl_easy; + +struct Curl_message { + struct Curl_llist_node list; + /* the 'CURLMsg' is the part that is visible to the external user */ + struct CURLMsg extmsg; +}; + +/* NOTE: if you add a state here, add the name to the statenames[] array + * in curl_trc.c as well! + */ +typedef enum { + MSTATE_INIT, /* 0 - start in this state */ + MSTATE_PENDING, /* no connections, waiting for one */ + MSTATE_SETUP, /* start a new transfer */ + MSTATE_CONNECT, /* resolve/connect has been sent off */ + MSTATE_CONNECTING, /* awaiting the TCP connect to finalize */ + MSTATE_PROTOCONNECT, /* initiate protocol connect procedure */ + MSTATE_PROTOCONNECTING, /* completing the protocol-specific connect phase */ + MSTATE_DO, /* start send off the request (part 1) */ + MSTATE_DOING, /* sending off the request (part 1) */ + MSTATE_DOING_MORE, /* send off the request (part 2) */ + MSTATE_DID, /* done sending off request */ + MSTATE_PERFORMING, /* transfer data */ + MSTATE_RATELIMITING, /* wait because limit-rate exceeded */ + MSTATE_DONE, /* post data transfer operation */ + MSTATE_COMPLETED, /* operation complete */ + MSTATE_MSGSENT, /* the operation complete message is sent */ + MSTATE_LAST /* not a true state, never use this */ +} CURLMstate; + +#define CURLPIPE_ANY (CURLPIPE_MULTIPLEX) + +#if !defined(CURL_DISABLE_SOCKETPAIR) && !defined(USE_WINSOCK) +#define ENABLE_WAKEUP +#endif +#if !defined(CURL_DISABLE_SOCKETPAIR) && \ + defined(USE_RESOLV_THREADED) && \ + !defined(USE_WINSOCK) +#define ENABLE_INTERNAL_WAKEUP +#endif + +/* value for MAXIMUM CONCURRENT STREAMS upper limit */ +#define INITIAL_MAX_CONCURRENT_STREAMS ((1U << 31) - 1) + +/* This is the struct known as CURLM on the outside */ +struct Curl_multi { + /* First a simple identifier to more easily detect if a user mixes up + this multi handle with an easy handle. + Set this to CURLMULTI_MAGIC_NUMBER. */ + uint32_t magic; + uint32_t xfers_alive; /* amount of added transfers that have + not yet reached COMPLETE state */ + uint32_t xfers_really_alive; /* amount of added transfers that have + passed INIT state but are not COMPLETE yet */ + uint32_t max_concurrent_streams; + + struct uint32_tbl xfers; /* transfers added to this multi */ + /* Each transfer's mid may be present in at most one of these */ + struct uint32_bset process; /* transfer being processed */ + struct uint32_bset dirty; /* transfer to be run NOW, e.g. ASAP. */ + struct uint32_bset pending; /* transfers in waiting (conn limit etc.) */ + struct uint32_bset msgsent; /* transfers done with message for application */ + + struct Curl_mapi_stack callstack; /* multi api calls ongoing */ + + struct Curl_llist msglist; /* a list of messages from completed transfers */ + + curl_off_t xfers_total_ever; /* total of added transfers, ever. */ + + struct Curl_easy *admin; /* internal easy handle for admin operations. + gets assigned `mid` 0 on multi init */ + + /* callback function and user data pointer for the *socket() API */ + curl_socket_callback socket_cb; + void *socket_userp; + + /* callback function and user data pointer for server push */ + curl_push_callback push_cb; + void *push_userp; + + struct Curl_dnscache dnscache; /* DNS cache */ + struct Curl_ssl_scache *ssl_scache; /* TLS session pool */ +#ifdef USE_RESOLV_THREADED + struct curl_thrdq *resolv_thrdq; +#endif + +#ifdef USE_LIBPSL + /* PSL cache. */ + struct PslCache psl; +#endif + + /* current time for transfers running in this multi handle */ + struct curltime now; + /* expiration times for all attached easy handles */ + struct Curl_timeouts timeouts; + + /* buffer used for transfer data, lazy initialized */ + char *xfer_buf; /* the actual buffer */ + size_t xfer_buf_len; /* the allocated length */ + /* buffer used for upload data, lazy initialized */ + char *xfer_ulbuf; /* the actual buffer */ + size_t xfer_ulbuf_len; /* the allocated length */ + /* buffer used for socket I/O operations, lazy initialized */ + char *xfer_sockbuf; /* the actual buffer */ + size_t xfer_sockbuf_len; /* the allocated length */ + + /* multi event related things */ + struct curl_multi_ev ev; + /* multi notification related things */ + struct curl_multi_ntfy ntfy; + + /* `proto_hash` is a general key-value store for protocol implementations + * with the lifetime of the multi handle. The number of elements kept here + * should be in the order of supported protocols (and sub-protocols like + * TLS), *not* in the order of connections or current transfers! + * Elements need to be added with their own destructor to be invoked when + * the multi handle is cleaned up (see Curl_hash_add2()).*/ + struct Curl_hash proto_hash; + + struct cshutdn cshutdn; /* connection shutdown handling */ + struct cpool cpool; /* connection pool (bundles) */ + timediff_t last_expire_offset_us; /* times offset of last expiry */ + + size_t max_host_connections; /* if >0, a fixed limit of the maximum number + of connections per host */ + size_t max_total_connections; /* if >0, a fixed limit of the maximum number + of connections in total */ + + /* timer callback and user data pointer for the *socket() API */ + curl_multi_timer_callback timer_cb; + void *timer_userp; + int last_timeout_ms; /* the last timeout value set via timer_cb */ + +#ifdef USE_WINSOCK + WSAEVENT wsa_event; /* Winsock event used for waits */ +#endif +#ifdef ENABLE_WAKEUP + curl_socket_t wakeup_pair[2]; /* eventfd()/pipe()/socketpair() used for + wakeup 0 is used for read, 1 is used + for write. Used by curl_multi_wakeup() */ +#endif +#ifdef ENABLE_INTERNAL_WAKEUP + curl_socket_t wakeup_internal[2]; /* eventfd()/pipe()/socketpair() used for + wakeup 0 is used for read, 1 is used + for write. Used for internal wakeups, + e.g. threaded resolver. */ +#endif + unsigned int maxconnects; /* if >0, a fixed limit of the maximum number of + entries we are allowed to grow the connection + cache to */ +#ifdef DEBUGBUILD + unsigned int now_access_count; +#endif + uint32_t last_pending_mid; /* mid of last pending transfer rescheduled */ + uint32_t last_resolv_id; /* id of the last DNS resolve operation */ + BIT(ipv6_works); + BIT(multiplexing); /* multiplexing wanted */ + BIT(recheckstate); /* see Curl_multi_connchanged */ +#ifdef USE_OPENSSL + BIT(ssl_seeded); +#endif + BIT(dead); /* a callback returned error, everything needs to crash and + burn */ + BIT(xfer_buf_borrowed); /* xfer_buf is currently being borrowed */ + BIT(xfer_ulbuf_borrowed); /* xfer_ulbuf is currently being borrowed */ + BIT(xfer_sockbuf_borrowed); /* xfer_sockbuf is currently being borrowed */ + BIT(quick_exit); /* do not join threads on cleanup */ +#ifdef DEBUGBUILD + BIT(warned); /* true after user warned of DEBUGBUILD */ +#endif +}; + +#endif /* HEADER_CURL_MULTIHANDLE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/multiif.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/multiif.h new file mode 100644 index 0000000000..d3ad8fffb3 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/multiif.h @@ -0,0 +1,183 @@ +#ifndef HEADER_CURL_MULTIIF_H +#define HEADER_CURL_MULTIIF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Prototypes for library-wide functions provided by multi.c + */ + +void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id eid); +void Curl_expire_set(struct Curl_easy *data, + expire_id eid, timediff_t ms, + const struct curltime *pnow); +void Curl_expire_clear(struct Curl_easy *data, expire_id eid); +void Curl_expire_clear_all(struct Curl_easy *data); +CURLMcode Curl_update_timer(struct Curl_multi *multi) WARN_UNUSED_RESULT; +void Curl_attach_connection(struct Curl_easy *data, + struct connectdata *conn, + bool matched); +void Curl_detach_connection(struct Curl_easy *data); +bool Curl_multiplex_wanted(const struct Curl_multi *multi); +CURLcode Curl_preconnect(struct Curl_easy *data); +bool Curl_is_connecting(struct Curl_easy *data); + +void Curl_multi_connchanged(struct Curl_multi *multi); + +CURLMcode Curl_multi_add_handle(struct Curl_multi *multi, + struct Curl_easy *data); +CURLMcode Curl_multi_remove_handle(struct Curl_multi *multi, + struct Curl_easy *data); + +/* Internal version of curl_multi_init() accepts size parameters for the + socket, connection and dns hashes */ +struct Curl_multi *Curl_multi_handle(uint32_t xfer_table_size, + size_t ev_hashsize, + size_t chashsize, + size_t dnssize, + size_t sesssize); + +/** + * Let the multi handle know that the socket is about to be closed. + * The multi will then remove anything it knows about the socket, so + * when the OS is using this socket (number) again subsequently, + * the internal book keeping will not get confused. + */ +void Curl_multi_will_close(struct Curl_easy *data, curl_socket_t s); + +/* + * Add a handle and move it into PERFORM state at once. For pushed streams. + */ +CURLMcode Curl_multi_add_perform(struct Curl_multi *multi, + struct Curl_easy *data, + struct connectdata *conn); + +/* Return the value of the CURLMOPT_MAX_CONCURRENT_STREAMS option */ +unsigned int Curl_multi_max_concurrent_streams(struct Curl_multi *multi); + +CURLMcode Curl_multi_pollset(struct Curl_easy *data, + struct easy_pollset *ps); + +/** + * Borrow the transfer buffer from the multi, suitable + * for the given transfer `data`. The buffer may only be used in one + * multi processing of the easy handle. It MUST be returned to the + * multi before it can be borrowed again. + * Pointers into the buffer remain only valid as long as it is borrowed. + * + * @param data the easy handle + * @param pbuf on return, the buffer to use or NULL on error + * @param pbuflen on return, the size of *pbuf or 0 on error + * @return CURLE_OK when buffer is available and is returned. + * CURLE_OUT_OF_MEMORy on failure to allocate the buffer, + * CURLE_FAILED_INIT if the easy handle is without multi. + * CURLE_AGAIN if the buffer is borrowed already. + */ +CURLcode Curl_multi_xfer_buf_borrow(struct Curl_easy *data, + char **pbuf, size_t *pbuflen); +/** + * Release the borrowed buffer. All references into the buffer become + * invalid after this. + * @param buf the buffer pointer borrowed for coding error checks. + */ +void Curl_multi_xfer_buf_release(struct Curl_easy *data, char *buf); + +/** + * Borrow the upload buffer from the multi, suitable + * for the given transfer `data`. The buffer may only be used in one + * multi processing of the easy handle. It MUST be returned to the + * multi before it can be borrowed again. + * Pointers into the buffer remain only valid as long as it is borrowed. + * + * @param data the easy handle + * @param pbuf on return, the buffer to use or NULL on error + * @param pbuflen on return, the size of *pbuf or 0 on error + * @return CURLE_OK when buffer is available and is returned. + * CURLE_OUT_OF_MEMORy on failure to allocate the buffer, + * CURLE_FAILED_INIT if the easy handle is without multi. + * CURLE_AGAIN if the buffer is borrowed already. + */ +CURLcode Curl_multi_xfer_ulbuf_borrow(struct Curl_easy *data, + char **pbuf, size_t *pbuflen); + +/** + * Release the borrowed upload buffer. All references into the buffer become + * invalid after this. + * @param buf the upload buffer pointer borrowed for coding error checks. + */ +void Curl_multi_xfer_ulbuf_release(struct Curl_easy *data, char *buf); + +/** + * Borrow the socket scratch buffer from the multi, suitable + * for the given transfer `data`. The buffer may only be used for + * direct socket I/O operation by one connection at a time and MUST be + * returned to the multi before the I/O call returns. + * Pointers into the buffer remain only valid as long as it is borrowed. + * + * @param data the easy handle + * @param blen requested length of the buffer + * @param pbuf on return, the buffer to use or NULL on error + * @return CURLE_OK when buffer is available and is returned. + * CURLE_OUT_OF_MEMORy on failure to allocate the buffer, + * CURLE_FAILED_INIT if the easy handle is without multi. + * CURLE_AGAIN if the buffer is borrowed already. + */ +CURLcode Curl_multi_xfer_sockbuf_borrow(struct Curl_easy *data, + size_t blen, char **pbuf); +/** + * Release the borrowed buffer. All references into the buffer become + * invalid after this. + * @param buf the buffer pointer borrowed for coding error checks. + */ +void Curl_multi_xfer_sockbuf_release(struct Curl_easy *data, char *buf); + +/** + * Get the easy handle for the given mid. + * Returns NULL if not found or not a GOOD_EASY_HANDLE() + */ +struct Curl_easy *Curl_multi_get_easy(struct Curl_multi *multi, + uint32_t mid); + +/* TRUE if multi knows about data via its `mid` */ +bool Curl_multi_knows_easy(struct Curl_multi *multi, struct Curl_easy *data); + +/* Get the # of transfers attached to the multi, without the internal + * admin handle. */ +uint32_t Curl_multi_xfers_attached(struct Curl_multi *multi); + +/* Get the # of transfers current in process/pending. */ +uint32_t Curl_multi_xfers_running(struct Curl_multi *multi); + +/* Mark a transfer as dirty, e.g. to be rerun at earliest convenience. + * A cheap operation, can be done many times repeatedly. */ +void Curl_multi_mark_dirty(struct Curl_easy *data); +/* Clear transfer from the dirty set. */ +void Curl_multi_clear_dirty(struct Curl_easy *data); + +void Curl_multi_set_now(struct Curl_multi *multi); + +#ifdef ENABLE_INTERNAL_WAKEUP +void Curl_multi_wakeup_internal(struct Curl_multi *multi); +#endif + +#endif /* HEADER_CURL_MULTIIF_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/netrc.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/netrc.c new file mode 100644 index 0000000000..7c8e1fb2ab --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/netrc.c @@ -0,0 +1,694 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_NETRC + +#ifdef HAVE_PWD_H +#ifdef __AMIGA__ +#undef __NO_NET_API /* required for AmigaOS to declare getpwuid() */ +#endif +#include <pwd.h> +#ifdef __AMIGA__ +#define __NO_NET_API +#endif +#endif + +#include "netrc.h" +#include "urldata.h" +#include "creds.h" +#include "curl_trc.h" +#include "strcase.h" +#include "curl_get_line.h" +#include "curlx/fopen.h" +#include "curlx/strparse.h" + + +/* .netrc is not really a standard. The GNU definition can be found here: + * https://www.gnu.org/software/inetutils/manual/html_node/The-_002enetrc-file.html + * This gives grammar like: + * + * LITERAL := \S+ | QUOTED + * QUOTED := "(\\[rnt\]|[^"])*" + * ANYTHING := . + * EMPTY_LINE := \r*\n\r*\n + * MACHINE := machine # case-insensitive + * LOGIN := login # case-insensitive + * PASSWD := password # case-insensitive + * ACCOUNT := account # case-insensitive + * MACDEF := macdef # case-insensitive + * DEFAULT := default # case-insensitive + * + * MACRO := MACDEF ANYTHING* EMPTY_LINE + * JUNK := LITERAL + * LKEY := ( LOGIN | PASSWD | ACCOUNT ) LITERAL + * MENTRY := MACHINE LITERAL LKEY* + * DENTRY := DEFAULT LKEY* + * NETRC := (MENTRY | DENTRY | MACRO | JUNK )* EOF + * + * Tokens are separated by whitespace or newlines. which have otherwise + * no special meaning, apart from the empty line ending a MACRO. + * + * Parsing is not strict, unmatched LITERALs are ignored + */ + +#define MAX_NETRC_LINE 16384 +#define MAX_NETRC_FILE (128 * 1024) +#define MAX_NETRC_TOKEN 4096 + +#define NETRC_DEBUG 0 + +/* convert a dynbuf call CURLcode error to a NETRCcode error */ +#define curl2netrc(r) \ + ((!(r)) ? NETRC_OK : (((r) == CURLE_OUT_OF_MEMORY) ? \ + NETRC_OUT_OF_MEMORY : NETRC_SYNTAX_ERROR)) + +typedef enum { + NETRC_TOK_EOF, + NETRC_TOK_LITERAL, + NETRC_TOK_MACHINE, + NETRC_TOK_DEFAULT, + NETRC_TOK_ACCOUNT, + NETRC_TOK_LOGIN, + NETRC_TOK_PASSWD, + NETRC_TOK_MACDEF, + NETRC_TOK_JUNK +} curl_netrc_token; + +struct netrc_lexer { + struct Curl_easy *data; + const char *content; + const char *pos; + struct dynbuf literal; + curl_netrc_token token; + bool pushed; +}; + +#if NETRC_DEBUG +static const char *netrc_tokenstr(curl_netrc_token token) +{ + switch(token) { + case NETRC_TOK_EOF: + return "[EOF]"; + case NETRC_TOK_LITERAL: + return "[LITERAL]"; + case NETRC_TOK_MACHINE: + return "[MACHINE]"; + case NETRC_TOK_DEFAULT: + return "[DEFAULT]"; + case NETRC_TOK_ACCOUNT: + return "[ACCOUNT]"; + case NETRC_TOK_LOGIN: + return "[LOGIN]"; + case NETRC_TOK_PASSWD: + return "[PASSWORD]"; + case NETRC_TOK_MACDEF: + return "[MACDEF]"; + case NETRC_TOK_JUNK: + return "[JUNK]"; + default: + return "[???]"; + } +} +#endif + +static void netrc_lexer_init(struct netrc_lexer *lexer, + struct Curl_easy *data, + const char *content) +{ + curlx_dyn_init(&lexer->literal, MAX_NETRC_TOKEN); + lexer->data = data; + lexer->content = lexer->pos = content; +} + +static void netrc_lexer_cleanup(struct netrc_lexer *lexer) +{ + lexer->content = lexer->pos = NULL; + lexer->data = NULL; + curlx_dyn_free(&lexer->literal); +} + +static void netrc_skip_blanks(struct netrc_lexer *lexer) +{ + const char *s = lexer->pos; + while(*s) { + curlx_str_passblanks(&s); + while(*s == '\r') + ++s; + if(*s == '\n') { + ++s; + } + else + break; + } + lexer->pos = s; +} + +static void netrc_skip_to_empty_line(struct netrc_lexer *lexer) +{ + const char *s = lexer->pos; + while(*s) { + if(*s == '\r') + ++s; + else if(*s == '\n') { + ++s; + while(*s == '\r') + ++s; + if(*s == '\n') + goto out; + } + else + ++s; + } +out: + lexer->pos = s; +} + +/* + * Parse a quoted token starting after the opening '"'. Handles \n, \r, \t + * escape sequences. Advances *tok_endp past the closing '"'. + * + * Returns NETRC_OK or error. + */ +static NETRCcode netrc_lexer_quoted(struct netrc_lexer *lexer) +{ + NETRCcode rc = NETRC_SYNTAX_ERROR; + const char *s = lexer->pos; + bool escape = FALSE; + CURLcode result; + + DEBUGASSERT(*s == '\"'); + ++s; /* pass the leading quote */ + while(*s) { + char c = *s; + if(escape) { + escape = FALSE; + switch(c) { + case 'n': + c = '\n'; + break; + case 'r': + c = '\r'; + break; + case 't': + c = '\t'; + break; + } + } + else if(c == '\\') { + escape = TRUE; + ++s; + continue; + } + else if(c == '\"') { + ++s; /* pass the ending quote */ + rc = NETRC_OK; + goto out; + } + result = curlx_dyn_addn(&lexer->literal, &c, 1); + if(result) { + rc = curl2netrc(result); + goto out; + } + ++s; + } +out: + lexer->pos = s; + return rc; +} + +static void netrc_lexer_push(struct netrc_lexer *lexer) +{ + lexer->pushed = TRUE; +} + +static NETRCcode netrc_lexer_next(struct netrc_lexer *lexer, + bool want_literal) +{ + const char *s = lexer->pos, *start; + NETRCcode rc = NETRC_OK; + size_t slen; + CURLcode result; + + if(lexer->pushed) { + lexer->pushed = FALSE; + goto out; + } + + curlx_dyn_reset(&lexer->literal); + netrc_skip_blanks(lexer); + s = lexer->pos; + + switch(*s) { + case 0: + lexer->token = NETRC_TOK_EOF; + break; + case '\"': + rc = netrc_lexer_quoted(lexer); + lexer->token = NETRC_TOK_LITERAL; + s = lexer->pos; + break; + default: + /* unquoted token */ + start = s; + while(*s && !ISBLANK(*s) && !ISNEWLINE(*s)) + ++s; + slen = s - start; + if(!slen) { + rc = NETRC_SYNTAX_ERROR; + } + if(want_literal) { + lexer->token = NETRC_TOK_LITERAL; + result = curlx_dyn_addn(&lexer->literal, start, slen); + rc = curl2netrc(result); + } + else if((slen == 7) && curl_strnequal(start, "machine", slen)) { + lexer->token = NETRC_TOK_MACHINE; + } + else if((slen == 7) && curl_strnequal(start, "default", slen)) { + lexer->token = NETRC_TOK_DEFAULT; + } + else if((slen == 7) && curl_strnequal(start, "account", slen)) { + lexer->token = NETRC_TOK_ACCOUNT; + } + else if((slen == 5) && curl_strnequal(start, "login", slen)) { + lexer->token = NETRC_TOK_LOGIN; + } + else if((slen == 8) && curl_strnequal(start, "password", slen)) { + lexer->token = NETRC_TOK_PASSWD; + } + else if((slen == 6) && curl_strnequal(start, "macdef", slen)) { + lexer->token = NETRC_TOK_MACDEF; + } + else { + lexer->token = NETRC_TOK_JUNK; + } + break; + } + +out: +#if NETRC_DEBUG + CURL_TRC_M(lexer->data, "[NETRC] token %s '%s', rc=%d", + netrc_tokenstr(lexer->token), + curlx_dyn_ptr(&lexer->literal), rc); +#endif + lexer->pos = s; + return rc; +} + +struct netrc_scanner { + struct netrc_lexer lexer; + const char *hostname; /* non-NULL, machine to scan for */ + const char *user; /* maybe NULL, login to scan for */ + char *login; + char *passwd; + struct Curl_creds *creds; + bool matches_host; + bool found; +}; + +static void netrc_scan_reset(struct netrc_scanner *sc) +{ + curlx_safefree(sc->login); + curlx_safefree(sc->passwd); + sc->matches_host = FALSE; +} + +static void netrc_scan_init(struct netrc_scanner *sc, + struct Curl_easy *data, + const char *content, + const char *hostname, + const char *user) +{ + memset(sc, 0, sizeof(*sc)); + netrc_lexer_init(&sc->lexer, data, content); + sc->hostname = hostname; + sc->user = (user && user[0]) ? user : NULL; + netrc_scan_reset(sc); +} + +static void netrc_scan_cleanup(struct netrc_scanner *sc) +{ + netrc_scan_reset(sc); + sc->hostname = NULL; + sc->user = NULL; + Curl_creds_unlink(&sc->creds); + netrc_lexer_cleanup(&sc->lexer); +} + +static NETRCcode netrc_scan_literal(struct netrc_scanner *sc, + char **pdest) +{ + NETRCcode rc = netrc_lexer_next(&sc->lexer, TRUE); + if(!rc) { + if(sc->lexer.token == NETRC_TOK_LITERAL) { + if(pdest && sc->matches_host) { + curlx_free(*pdest); + *pdest = curlx_strdup(curlx_dyn_ptr(&sc->lexer.literal)); + if(!*pdest) + rc = NETRC_OUT_OF_MEMORY; + } + } + else + netrc_lexer_push(&sc->lexer); + } + return rc; +} + +static NETRCcode netrc_scan_end_entry(struct netrc_scanner *sc) +{ + NETRCcode rc = NETRC_OK; +#if NETRC_DEBUG + CURL_TRC_M(sc->lexer.data, + "[NETRC] entry matches_host=%d, login='%s', passwd='%s'", + sc->matches_host, sc->login, sc->passwd); +#endif + if(sc->matches_host) { + if(sc->login) { + if(sc->user) { + if(Curl_timestrcmp(sc->user, sc->login)) + goto out; + /* We look for a specific user, + * entry is only interesting with password */ + sc->found = !!sc->passwd; + } + else { + sc->found = TRUE; + } + } + else if(sc->passwd) { + /* found a passwd that applies to any user */ + sc->found = TRUE; + } + else { + /* entry has nothing interesting */ + } + if(sc->found) { +#if NETRC_DEBUG + CURL_TRC_M(sc->lexer.data, "[NETRC] entry match found"); +#endif + if(Curl_creds_create(sc->user ? sc->user : sc->login, sc->passwd, + NULL, NULL, NULL, CREDS_NETRC, &sc->creds)) + rc = NETRC_OUT_OF_MEMORY; + } + } +out: + netrc_scan_reset(sc); + return rc; +} + +static NETRCcode netrc_scan(struct Curl_easy *data, + const char *content, + const char *hostname, + const char *user, + struct Curl_creds **pcreds) +{ + struct netrc_scanner sc; + NETRCcode rc = NETRC_OK; + + Curl_creds_unlink(pcreds); + netrc_scan_init(&sc, data, content, hostname, user); + + while(!rc && !sc.found) { + rc = netrc_lexer_next(&sc.lexer, FALSE); + if(!rc) { + /* Does this token end any previous entry? */ + switch(sc.lexer.token) { + case NETRC_TOK_EOF: + case NETRC_TOK_MACHINE: + case NETRC_TOK_DEFAULT: + case NETRC_TOK_MACDEF: + rc = netrc_scan_end_entry(&sc); + if(rc || sc.found) + goto out; + break; + default: + break; + } + + switch(sc.lexer.token) { + case NETRC_TOK_EOF: + goto out; + case NETRC_TOK_MACHINE: + rc = netrc_lexer_next(&sc.lexer, TRUE); + if(!rc) { + if(sc.lexer.token == NETRC_TOK_LITERAL) { + sc.matches_host = curl_strequal( + sc.hostname, curlx_dyn_ptr(&sc.lexer.literal)); + } + else { + sc.matches_host = FALSE; + netrc_lexer_push(&sc.lexer); + } + } + break; + case NETRC_TOK_DEFAULT: + sc.matches_host = TRUE; + break; + case NETRC_TOK_ACCOUNT: + rc = netrc_scan_literal(&sc, NULL); /* ignore, not used */ + break; + case NETRC_TOK_LOGIN: + rc = netrc_scan_literal(&sc, &sc.login); + break; + case NETRC_TOK_PASSWD: + rc = netrc_scan_literal(&sc, &sc.passwd); + break; + case NETRC_TOK_MACDEF: + netrc_skip_to_empty_line(&sc.lexer); + break; + case NETRC_TOK_LITERAL: + case NETRC_TOK_JUNK: + default: + /* skip this */ + break; + } + } + } + +out: + if(!rc) { + if(sc.creds) + Curl_creds_link(pcreds, sc.creds); + else + rc = NETRC_NO_MATCH; + } + netrc_scan_cleanup(&sc); + return rc; +} + +static NETRCcode file2memory(const char *filename, struct dynbuf *filebuf) +{ + NETRCcode ret = NETRC_FILE_MISSING; /* if it cannot open the file */ + FILE *file = curlx_fopen(filename, FOPEN_READTEXT); + + curlx_dyn_reset(filebuf); + if(file) { + curlx_struct_stat stat; + if((curlx_fstat(fileno(file), &stat) == -1) || !S_ISDIR(stat.st_mode)) { + CURLcode result = CURLE_OK; + bool eof; + struct dynbuf linebuf; + curlx_dyn_init(&linebuf, MAX_NETRC_LINE); + ret = NETRC_OK; + do { + const char *line; + /* Curl_get_line always returns lines ending with a newline */ + result = Curl_get_line(&linebuf, file, &eof); + if(!result) { + line = curlx_dyn_ptr(&linebuf); + /* skip comments on load */ + curlx_str_passblanks(&line); + if(*line == '#') + continue; + result = curlx_dyn_add(filebuf, line); + } + if(result) { + curlx_dyn_free(filebuf); + ret = curl2netrc(result); + break; + } + } while(!eof); + curlx_dyn_free(&linebuf); + } + curlx_fclose(file); + } + return ret; +} + +static NETRCcode netrc_scan_file(struct Curl_easy *data, + struct store_netrc *store, + const char *hostname, + const char *user, + const char *netrcfile, + struct Curl_creds **pcreds) +{ + struct dynbuf *filebuf = &store->filebuf; + + if(!store->loaded || strcmp(netrcfile, store->filename)) { + NETRCcode ret; + store->loaded = FALSE; + ret = file2memory(netrcfile, filebuf); + if(ret) { + CURL_TRC_M(data, "[NETRC] could not load '%s'", netrcfile); + return ret; + } + curlx_free(store->filename); + store->filename = curlx_strdup(netrcfile); + if(!store->filename) { + curlx_dyn_reset(&store->filebuf); + return NETRC_OUT_OF_MEMORY; + } + store->loaded = TRUE; + } + + return netrc_scan(data, curlx_dyn_ptr(filebuf), hostname, user, pcreds); +} + +/* + * @unittest: 1304 + * + * *loginp and *passwordp MUST be allocated if they are not NULL when passed + * in. + */ +NETRCcode Curl_netrc_scan(struct Curl_easy *data, + struct store_netrc *store, + const char *hostname, + const char *user, + const char *netrcfile, + struct Curl_creds **pcreds) +{ + NETRCcode retcode = NETRC_OK; + + CURL_TRC_M(data, "[NETRC] scanning '%s' for host '%s' user '%s'", + netrcfile, hostname, user); + Curl_creds_unlink(pcreds); + if(!netrcfile) { + char *home = NULL; + char *homea = NULL; + char *filealloc = NULL; +#if defined(HAVE_GETPWUID_R) && defined(HAVE_GETEUID) + char pwbuf[1024]; +#endif + filealloc = curl_getenv("NETRC"); + if(!filealloc) { + homea = curl_getenv("HOME"); /* portable environment reader */ + if(homea) { + home = homea; +#if defined(HAVE_GETPWUID_R) && defined(HAVE_GETEUID) + } + else { + struct passwd pw, *pw_res; + if(!getpwuid_r(geteuid(), &pw, pwbuf, sizeof(pwbuf), &pw_res) && + pw_res) { + home = pw.pw_dir; + } +#elif defined(HAVE_GETPWUID) && defined(HAVE_GETEUID) + } + else { + struct passwd *pw; + pw = getpwuid(geteuid()); + if(pw) { + home = pw->pw_dir; + } +#elif defined(_WIN32) + } + else { + homea = curl_getenv("USERPROFILE"); + if(homea) { + home = homea; + } +#endif + } + + if(!home) + return NETRC_FILE_MISSING; /* no home directory found (or possibly out + of memory) */ + + filealloc = curl_maprintf("%s%s.netrc", home, DIR_CHAR); + if(!filealloc) { + curlx_free(homea); + retcode = NETRC_OUT_OF_MEMORY; + goto out; + } + } + retcode = netrc_scan_file( + data, store, hostname, user, filealloc, pcreds); + curlx_free(filealloc); +#ifdef _WIN32 + if(retcode == NETRC_FILE_MISSING) { + /* fallback to the old-style "_netrc" file */ + filealloc = curl_maprintf("%s%s_netrc", home, DIR_CHAR); + if(!filealloc) { + curlx_free(homea); + return NETRC_OUT_OF_MEMORY; + } + retcode = netrc_scan_file( + data, store, hostname, user, filealloc, pcreds); + curlx_free(filealloc); + } +#endif + curlx_free(homea); + } + else + retcode = netrc_scan_file( + data, store, hostname, user, netrcfile, pcreds); + +out: + if(retcode) + Curl_creds_unlink(pcreds); + return retcode; +} + +void Curl_netrc_init(struct store_netrc *store) +{ + curlx_dyn_init(&store->filebuf, MAX_NETRC_FILE); + store->loaded = FALSE; + store->filename = NULL; +} +void Curl_netrc_cleanup(struct store_netrc *store) +{ + curlx_dyn_free(&store->filebuf); + curlx_safefree(store->filename); + store->loaded = FALSE; +} + +const char *Curl_netrc_strerror(NETRCcode ret) +{ + switch(ret) { + default: + return ""; /* not a legit error */ + case NETRC_FILE_MISSING: + return "no such file"; + case NETRC_NO_MATCH: + return "no matching entry"; + case NETRC_OUT_OF_MEMORY: + return "out of memory"; + case NETRC_SYNTAX_ERROR: + return "syntax error"; + } + /* never reached */ +} + +#endif /* !CURL_DISABLE_NETRC */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/netrc.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/netrc.h new file mode 100644 index 0000000000..6be9b83316 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/netrc.h @@ -0,0 +1,68 @@ +#ifndef HEADER_CURL_NETRC_H +#define HEADER_CURL_NETRC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_NETRC + +#include "curlx/dynbuf.h" + +struct Curl_easy; +struct Curl_creds; + +struct store_netrc { + struct dynbuf filebuf; + char *filename; + BIT(loaded); +}; + +typedef enum { + NETRC_OK, + NETRC_NO_MATCH, /* no matching entry in the file */ + NETRC_SYNTAX_ERROR, /* in the netrc file */ + NETRC_FILE_MISSING, /* the netrc file does not exist */ + NETRC_OUT_OF_MEMORY, /* while parsing netrc */ + NETRC_LAST /* never used */ +} NETRCcode; + +const char *Curl_netrc_strerror(NETRCcode ret); +void Curl_netrc_init(struct store_netrc *store); +void Curl_netrc_cleanup(struct store_netrc *store); + +/* Scan a netrc file for credentials matching hostname + * and optional user. */ +NETRCcode Curl_netrc_scan(struct Curl_easy *data, + struct store_netrc *store, + const char *hostname, + const char *user, + const char *netrcfile, + struct Curl_creds **pcreds); +#else +/* disabled */ +#define Curl_netrc_init(x) +#define Curl_netrc_cleanup(x) +#endif + +#endif /* HEADER_CURL_NETRC_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/openldap.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/openldap.c new file mode 100644 index 0000000000..887336e5ca --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/openldap.c @@ -0,0 +1,1313 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) Howard Chu, <hyc@openldap.org> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_LDAP) && defined(USE_OPENLDAP) + +/* + * Notice that USE_OPENLDAP is only a source code selection switch. When + * libcurl is built with USE_OPENLDAP defined the libcurl source code that + * gets compiled is the code from openldap.c, otherwise the code that gets + * compiled is the code from ldap.c. + * + * When USE_OPENLDAP is defined a recent version of the OpenLDAP library + * might be required for compilation and runtime. In order to use ancient + * OpenLDAP library versions, USE_OPENLDAP shall not be defined. + */ + +#include <ldap.h> + +#include "urldata.h" +#include "url.h" +#include "sendf.h" +#include "curl_trc.h" +#include "vtls/vtls.h" +#include "transfer.h" +#include "curl_ldap.h" +#include "curlx/base64.h" +#include "cfilters.h" +#include "connect.h" +#include "curl_sasl.h" +#include "strcase.h" +#include "bufref.h" + +/* + * Uncommenting this will enable the built-in debug logging of the openldap + * library. The debug log level can be set using the CURL_OPENLDAP_TRACE + * environment variable. The debug output is written to stderr. + * + * The library supports the following debug flags: + * LDAP_DEBUG_NONE 0x0000 + * LDAP_DEBUG_TRACE 0x0001 + * LDAP_DEBUG_CONSTRUCT 0x0002 + * LDAP_DEBUG_DESTROY 0x0004 + * LDAP_DEBUG_PARAMETER 0x0008 + * LDAP_DEBUG_ANY 0xffff + * + * For example, use CURL_OPENLDAP_TRACE=0 for no debug, + * CURL_OPENLDAP_TRACE=2 for LDAP_DEBUG_CONSTRUCT messages only, + * CURL_OPENLDAP_TRACE=65535 for all debug message levels. + */ +/* #define CURL_OPENLDAP_DEBUG */ + +/* Machine states. */ +typedef enum { + OLDAP_STOP, /* Do nothing state, stops the state machine */ + OLDAP_SSL, /* Performing SSL handshake. */ + OLDAP_STARTTLS, /* STARTTLS request sent. */ + OLDAP_TLS, /* Performing TLS handshake. */ + OLDAP_MECHS, /* Get SASL authentication mechanisms. */ + OLDAP_SASL, /* SASL binding reply. */ + OLDAP_BIND, /* Simple bind reply. */ + OLDAP_BINDV2, /* Simple bind reply in protocol version 2. */ + OLDAP_LAST /* Never used */ +} ldapstate; + +#ifndef _LDAP_PVT_H +extern int ldap_pvt_url_scheme2proto(const char *); +extern int ldap_init_fd(ber_socket_t fd, int proto, const char *url, + LDAP **ld); +#endif + +static Curl_recv oldap_recv; + +struct ldapconninfo { + struct SASL sasl; /* SASL-related parameters */ + LDAP *ld; /* Openldap connection handle. */ + Curl_recv *recv; /* For stacking SSL handler */ + Curl_send *send; + struct berval *servercred; /* SASL data from server. */ + ldapstate state; /* Current machine state. */ + int proto; /* LDAP_PROTO_TCP/LDAP_PROTO_UDP/LDAP_PROTO_IPC */ + int msgid; /* Current message id. */ +}; + +struct ldapreqinfo { + int msgid; + int nument; +}; + +/* meta key for storing ldapconninfo at easy handle */ +#define CURL_META_LDAP_EASY "meta:proto:ldap:easy" +/* meta key for storing ldapconninfo at connection */ +#define CURL_META_LDAP_CONN "meta:proto:ldap:conn" + +/* + * oldap_state() + * + * This is the ONLY way to change LDAP state! + */ +static void oldap_state(struct Curl_easy *data, struct ldapconninfo *li, + ldapstate newstate) +{ +#if defined(DEBUGBUILD) && defined(CURLVERBOSE) + /* for debug purposes */ + static const char * const names[] = { + "STOP", + "SSL", + "STARTTLS", + "TLS", + "MECHS", + "SASL", + "BIND", + "BINDV2", + /* LAST */ + }; + + if(li->state != newstate) + infof(data, "LDAP %p state change from %s to %s", + (void *)li, names[li->state], names[newstate]); +#else + (void)data; +#endif + li->state = newstate; +} + +/* Map some particular LDAP error codes to CURLcode values. */ +static CURLcode oldap_map_error(int rc, CURLcode result) +{ + switch(rc) { + case LDAP_NO_MEMORY: + return CURLE_OUT_OF_MEMORY; + case LDAP_INVALID_CREDENTIALS: + return CURLE_LOGIN_DENIED; + case LDAP_PROTOCOL_ERROR: + return CURLE_UNSUPPORTED_PROTOCOL; + case LDAP_INSUFFICIENT_ACCESS: + return CURLE_REMOTE_ACCESS_DENIED; + } + return result; +} + +static CURLcode oldap_url_parse(struct Curl_easy *data, LDAPURLDesc **ludp) +{ + CURLcode result = CURLE_OK; + int rc; + static const char * const url_errs[] = { + "success", + "out of memory", + "bad parameter", + "unrecognized scheme", + "unbalanced delimiter", + "bad URL", + "bad host or port", + "bad or missing attributes", + "bad or missing scope", + "bad or missing filter", + "bad or missing extensions" + }; + + *ludp = NULL; + /* `ldap_url_parse() seems to be terrible with urls + * that have user/pass/options in it. So when we have options or + * creds from the url, fail without calling the function. + * Yes, this is super-weird code and I do not like it. */ + if((data->state.creds && (data->state.creds->source == CREDS_URL)) || + data->state.up.options) + rc = LDAP_URL_ERR_BADURL; + else + rc = ldap_url_parse(Curl_bufref_ptr(&data->state.url), ludp); + + if(rc != LDAP_URL_SUCCESS) { + const char *msg = "url parsing problem"; + + result = rc == LDAP_URL_ERR_MEM ? CURLE_OUT_OF_MEMORY : + CURLE_URL_MALFORMAT; + rc -= LDAP_URL_SUCCESS; + if((size_t)rc < CURL_ARRAYSIZE(url_errs)) + msg = url_errs[rc]; + failf(data, "LDAP local: %s", msg); + } + return result; +} + +/* Parse the login options. */ +static CURLcode oldap_parse_login_options(struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + const char *ptr = conn->options; + + DEBUGASSERT(li); + if(!li) + return CURLE_FAILED_INIT; + + while(!result && ptr && *ptr) { + const char *key = ptr; + const char *value; + + while(*ptr && *ptr != '=') + ptr++; + + value = ptr + 1; + + while(*ptr && *ptr != ';') + ptr++; + + if(checkprefix("AUTH=", key)) + result = Curl_sasl_parse_url_auth_option(&li->sasl, value, ptr - value); + else + result = CURLE_SETOPT_OPTION_SYNTAX; + + if(*ptr == ';') + ptr++; + } + + return result == CURLE_URL_MALFORMAT ? CURLE_SETOPT_OPTION_SYNTAX : result; +} + +static CURLcode oldap_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result; + LDAPURLDesc *lud; + (void)conn; + + /* Early URL syntax check. */ + result = oldap_url_parse(data, &lud); + ldap_free_urldesc(lud); + + return result; +} + +/* + * Get the SASL authentication challenge from the server credential buffer. + */ +static CURLcode oldap_get_message(struct Curl_easy *data, struct bufref *out) +{ + struct ldapconninfo *li = + Curl_conn_meta_get(data->conn, CURL_META_LDAP_CONN); + struct berval *servercred = li ? li->servercred : NULL; + DEBUGASSERT(li); + if(!li) + return CURLE_FAILED_INIT; + + if(!servercred || !servercred->bv_val) + return CURLE_WEIRD_SERVER_REPLY; + Curl_bufref_set(out, servercred->bv_val, servercred->bv_len, NULL); + return CURLE_OK; +} + +/* + * Sends an initial SASL bind request to the server. + */ +static CURLcode oldap_perform_auth(struct Curl_easy *data, const char *mech, + const struct bufref *initresp) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + struct berval cred; + struct berval *pcred = &cred; + int rc; + + DEBUGASSERT(li); + if(!li) + return CURLE_FAILED_INIT; + cred.bv_val = (char *)CURL_UNCONST(Curl_bufref_ptr(initresp)); + cred.bv_len = Curl_bufref_len(initresp); + if(!cred.bv_val) + pcred = NULL; + rc = ldap_sasl_bind(li->ld, NULL, mech, pcred, NULL, NULL, &li->msgid); + if(rc != LDAP_SUCCESS) + return oldap_map_error(rc, CURLE_LDAP_CANNOT_BIND); + return CURLE_OK; +} + +/* + * Sends SASL continuation. + */ +static CURLcode oldap_continue_auth(struct Curl_easy *data, const char *mech, + const struct bufref *resp) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + struct berval cred; + struct berval *pcred = &cred; + int rc; + + if(!li) + return CURLE_FAILED_INIT; + cred.bv_val = (char *)CURL_UNCONST(Curl_bufref_ptr(resp)); + cred.bv_len = Curl_bufref_len(resp); + if(!cred.bv_val) + pcred = NULL; + rc = ldap_sasl_bind(li->ld, NULL, mech, pcred, NULL, NULL, &li->msgid); + if(rc != LDAP_SUCCESS) + return oldap_map_error(rc, CURLE_LDAP_CANNOT_BIND); + return CURLE_OK; +} + +/* + * Sends SASL bind cancellation. + */ +static CURLcode oldap_cancel_auth(struct Curl_easy *data, const char *mech) +{ + struct ldapconninfo *li = + Curl_conn_meta_get(data->conn, CURL_META_LDAP_CONN); + int rc; + + (void)mech; + if(!li) + return CURLE_FAILED_INIT; + rc = ldap_sasl_bind(li->ld, NULL, LDAP_SASL_NULL, NULL, NULL, NULL, + &li->msgid); + if(rc != LDAP_SUCCESS) + return oldap_map_error(rc, CURLE_LDAP_CANNOT_BIND); + return CURLE_OK; +} + +/* Starts LDAP simple bind. */ +static CURLcode oldap_perform_bind(struct Curl_easy *data, ldapstate newstate) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + const char *binddn = NULL; + struct berval passwd; + int rc; + + if(!li) + return CURLE_FAILED_INIT; + passwd.bv_val = NULL; + passwd.bv_len = 0; + + if(conn->creds) { + binddn = Curl_creds_user(conn->creds); + passwd.bv_val = CURL_UNCONST(Curl_creds_passwd(conn->creds)); + passwd.bv_len = strlen(passwd.bv_val); + } + + rc = ldap_sasl_bind(li->ld, binddn, LDAP_SASL_SIMPLE, &passwd, + NULL, NULL, &li->msgid); + if(rc != LDAP_SUCCESS) + return oldap_map_error(rc, + data->state.creds ? + CURLE_LOGIN_DENIED : CURLE_LDAP_CANNOT_BIND); + oldap_state(data, li, newstate); + return CURLE_OK; +} + +/* Query the supported SASL authentication mechanisms. */ +static CURLcode oldap_perform_mechs(struct Curl_easy *data) +{ + struct ldapconninfo *li = + Curl_conn_meta_get(data->conn, CURL_META_LDAP_CONN); + int rc; + static const char * const supportedSASLMechanisms[] = { + "supportedSASLMechanisms", + NULL + }; + + if(!li) + return CURLE_FAILED_INIT; + /* Casting away the const for the 3rd parameter that the LDAP API expects as + a non-const char ** is potentially unsafe but we believe the lack of + const in the API was an oversight and that no LDAP implementation + actually modifies the input. */ + rc = ldap_search_ext(li->ld, "", LDAP_SCOPE_BASE, "(objectclass=*)", + (char **)CURL_UNCONST(supportedSASLMechanisms), 0, + NULL, NULL, NULL, 0, &li->msgid); + if(rc != LDAP_SUCCESS) + return oldap_map_error(rc, CURLE_LOGIN_DENIED); + oldap_state(data, li, OLDAP_MECHS); + return CURLE_OK; +} + +/* Starts SASL bind. */ +static CURLcode oldap_perform_sasl(struct Curl_easy *data) +{ + struct ldapconninfo *li = + Curl_conn_meta_get(data->conn, CURL_META_LDAP_CONN); + saslprogress progress = SASL_IDLE; + CURLcode result; + + if(!li) + return CURLE_FAILED_INIT; + result = Curl_sasl_start(&li->sasl, data, TRUE, &progress); + + oldap_state(data, li, OLDAP_SASL); + if(!result && progress != SASL_INPROGRESS) + result = Curl_sasl_is_blocked(&li->sasl, data); + return result; +} + +#ifdef USE_SSL +static int ldapsb_tls_setup(Sockbuf_IO_Desc *sbiod, void *arg) +{ + sbiod->sbiod_pvt = arg; + return 0; +} + +static int ldapsb_tls_remove(Sockbuf_IO_Desc *sbiod) +{ + sbiod->sbiod_pvt = NULL; + return 0; +} + +/* We do not need to do anything because libcurl does it already */ +static int ldapsb_tls_close(Sockbuf_IO_Desc *sbiod) +{ + (void)sbiod; + return 0; +} + +static int ldapsb_tls_ctrl(Sockbuf_IO_Desc *sbiod, int opt, void *arg) +{ + (void)arg; + if(opt == LBER_SB_OPT_DATA_READY) { + struct Curl_easy *data = sbiod->sbiod_pvt; + return Curl_conn_data_pending(data, FIRSTSOCKET); + } + return 0; +} + +static ber_slen_t ldapsb_tls_read(Sockbuf_IO_Desc *sbiod, void *buf, + ber_len_t len) +{ + struct Curl_easy *data = sbiod->sbiod_pvt; + ber_slen_t ret = 0; + if(data) { + struct connectdata *conn = data->conn; + if(conn) { + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + CURLcode result = CURLE_RECV_ERROR; + size_t nread; + + if(!li) { + SET_SOCKERRNO(SOCKEINVAL); + return -1; + } + result = (li->recv)(data, FIRSTSOCKET, buf, len, &nread); + if(result == CURLE_AGAIN) { + SET_SOCKERRNO(SOCKEWOULDBLOCK); + } + ret = result ? -1 : (ber_slen_t)nread; + } + } + return ret; +} + +static ber_slen_t ldapsb_tls_write(Sockbuf_IO_Desc *sbiod, void *buf, + ber_len_t len) +{ + struct Curl_easy *data = sbiod->sbiod_pvt; + ber_slen_t ret = 0; + if(data) { + struct connectdata *conn = data->conn; + if(conn) { + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + CURLcode result = CURLE_SEND_ERROR; + size_t nwritten; + + if(!li) { + SET_SOCKERRNO(SOCKEINVAL); + return -1; + } + result = (li->send)(data, FIRSTSOCKET, buf, len, FALSE, &nwritten); + if(result == CURLE_AGAIN) { + SET_SOCKERRNO(SOCKEWOULDBLOCK); + } + ret = result ? -1 : (ber_slen_t)nwritten; + } + } + return ret; +} + +static Sockbuf_IO ldapsb_tls = { + ldapsb_tls_setup, + ldapsb_tls_remove, + ldapsb_tls_ctrl, + ldapsb_tls_read, + ldapsb_tls_write, + ldapsb_tls_close +}; + +static bool ssl_installed(struct connectdata *conn) +{ + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + return li && li->recv; +} + +static CURLcode oldap_ssl_connect(struct Curl_easy *data, ldapstate newstate) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + bool ssldone = FALSE; + CURLcode result; + + if(!li) + return CURLE_FAILED_INIT; + result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssldone); + if(result) + return result; + oldap_state(data, li, newstate); + + if(ssldone) { + Sockbuf *sb; + + /* Install the libcurl SSL handlers into the sockbuf. */ + if((ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb) != LDAP_OPT_SUCCESS) || + ber_sockbuf_add_io(sb, &ldapsb_tls, LBER_SBIOD_LEVEL_TRANSPORT, data)) + return CURLE_FAILED_INIT; + li->recv = conn->recv[FIRSTSOCKET]; + li->send = conn->send[FIRSTSOCKET]; + } + + return result; +} + +/* Send the STARTTLS request */ +static CURLcode oldap_perform_starttls(struct Curl_easy *data) +{ + struct ldapconninfo *li = + Curl_conn_meta_get(data->conn, CURL_META_LDAP_CONN); + int rc; + + if(!li) + return CURLE_FAILED_INIT; + rc = ldap_start_tls(li->ld, NULL, NULL, &li->msgid); + if(rc != LDAP_SUCCESS) + return oldap_map_error(rc, CURLE_USE_SSL_FAILED); + oldap_state(data, li, OLDAP_STARTTLS); + return CURLE_OK; +} +#endif + +static void oldap_easy_dtor(void *key, size_t klen, void *entry) +{ + struct ldapreqinfo *lr = entry; + (void)key; + (void)klen; + curlx_free(lr); +} + +static void oldap_conn_dtor(void *key, size_t klen, void *entry) +{ + struct ldapconninfo *li = entry; + (void)key; + (void)klen; + if(li->ld) { + ldap_unbind_ext(li->ld, NULL, NULL); + li->ld = NULL; + } + curlx_free(li); +} + +/* SASL parameters for the ldap protocol */ +static const struct SASLproto saslldap = { + "ldap", /* The service name */ + oldap_perform_auth, /* Send authentication command */ + oldap_continue_auth, /* Send authentication continuation */ + oldap_cancel_auth, /* Send authentication cancellation */ + oldap_get_message, /* Get SASL response message */ + 0, /* Maximum initial response length (no max) */ + LDAP_SASL_BIND_IN_PROGRESS, /* Code received when continuation is expected */ + LDAP_SUCCESS, /* Code to receive upon authentication success */ + SASL_AUTH_NONE, /* Default mechanisms */ + 0 /* Configuration flags */ +}; + +static CURLcode oldap_connect(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li; + static const int version = LDAP_VERSION3; + char *hosturl = NULL; + CURLcode result; + int rc; +#ifdef CURL_OPENLDAP_DEBUG + static int do_trace = -1; +#endif + + (void)done; + + li = curlx_calloc(1, sizeof(struct ldapconninfo)); + if(!li) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + result = Curl_conn_meta_set(conn, CURL_META_LDAP_CONN, li, oldap_conn_dtor); + if(result) + goto out; + + li->proto = ldap_pvt_url_scheme2proto(data->state.origin->scheme->name); + + /* Initialize the SASL storage */ + Curl_sasl_init(&li->sasl, data, &saslldap); + + result = oldap_parse_login_options(conn); + if(result) + goto out; + + hosturl = curl_maprintf("%s://%s:%u", + conn->scheme->name, + conn->origin->ipv6 ? + conn->origin->user_hostname : + conn->origin->hostname, + conn->origin->port); + if(!hosturl) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + rc = ldap_init_fd(conn->sock[FIRSTSOCKET], li->proto, hosturl, &li->ld); + if(rc) { + failf(data, "LDAP local: Cannot connect to %s, %s", + hosturl, ldap_err2string(rc)); + result = CURLE_COULDNT_CONNECT; + goto out; + } + +#ifdef CURL_OPENLDAP_DEBUG + if(do_trace < 0) { + const char *env = getenv("CURL_OPENLDAP_TRACE"); + curl_off_t e = 0; + if(!curlx_str_number(&env, &e, INT_MAX)) + do_trace = e > 0; + } + if(do_trace) + ldap_set_option(li->ld, LDAP_OPT_DEBUG_LEVEL, &do_trace); +#endif + + /* Try version 3 first. */ + ldap_set_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &version); + + /* Do not chase referrals. */ + ldap_set_option(li->ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF); + + { + ber_len_t max = 256 * 1024; + Sockbuf *sb; + if((ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb) != LDAP_OPT_SUCCESS) || + /* Set the maximum allowed size of an incoming message, which to + OpenLDAP means that it will malloc() memory up to this size. If not + set, there is no limit and we instead risk a malloc() failure. */ + !ber_sockbuf_ctrl(sb, LBER_SB_OPT_SET_MAX_INCOMING, &max)) { + result = CURLE_FAILED_INIT; + goto out; + } + } + +#ifdef USE_SSL + if(Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + result = oldap_ssl_connect(data, OLDAP_SSL); + goto out; + } + + if(data->set.use_ssl) { + result = oldap_perform_starttls(data); + if(!result || data->set.use_ssl != CURLUSESSL_TRY) + goto out; + } +#endif + + if(li->sasl.prefmech != SASL_AUTH_NONE) { + result = oldap_perform_mechs(data); + goto out; + } + + /* Force bind even if anonymous bind is not needed in protocol version 3 + to detect missing version 3 support. */ + result = oldap_perform_bind(data, OLDAP_BIND); + +out: + curlx_free(hosturl); + return result; +} + +/* Handle the supported SASL mechanisms query response */ +static CURLcode oldap_state_mechs_resp(struct Curl_easy *data, + LDAPMessage *msg, int code) +{ + struct connectdata *conn; + struct ldapconninfo *li; + int rc; + BerElement *ber = NULL; + CURLcode result = CURLE_OK; + struct berval bv, *bvals; + + if(!data) + return CURLE_FAILED_INIT; + + conn = data->conn; + li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + + if(!li) + return CURLE_FAILED_INIT; + switch(ldap_msgtype(msg)) { + case LDAP_RES_SEARCH_ENTRY: + /* Got a list of supported SASL mechanisms. */ + if(code != LDAP_SUCCESS && code != LDAP_NO_RESULTS_RETURNED) + return CURLE_LOGIN_DENIED; + + rc = ldap_get_dn_ber(li->ld, msg, &ber, &bv); + if(rc < 0) + return oldap_map_error(rc, CURLE_BAD_CONTENT_ENCODING); + for(rc = ldap_get_attribute_ber(li->ld, msg, ber, &bv, &bvals); + rc == LDAP_SUCCESS; + rc = ldap_get_attribute_ber(li->ld, msg, ber, &bv, &bvals)) { + int i; + + if(!bv.bv_val) + break; + + if(bvals) { + for(i = 0; bvals[i].bv_val; i++) { + size_t llen; + unsigned short mech = + Curl_sasl_decode_mech((const char *)bvals[i].bv_val, + bvals[i].bv_len, &llen); + if(bvals[i].bv_len == llen) + li->sasl.authmechs |= mech; + } + ber_memfree(bvals); + } + } + ber_free(ber, 0); + break; + + case LDAP_RES_SEARCH_RESULT: + switch(code) { + case LDAP_SIZELIMIT_EXCEEDED: + infof(data, "Too many authentication mechanisms"); + FALLTHROUGH(); + case LDAP_SUCCESS: + case LDAP_NO_RESULTS_RETURNED: + if(Curl_sasl_can_authenticate(&li->sasl, data)) + result = oldap_perform_sasl(data); + else + result = CURLE_LOGIN_DENIED; + break; + default: + result = oldap_map_error(code, CURLE_LOGIN_DENIED); + break; + } + break; + default: + break; + } + return result; +} + +/* Handle a SASL bind response. */ +static CURLcode oldap_state_sasl_resp(struct Curl_easy *data, + LDAPMessage *msg, int code) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + CURLcode result = CURLE_OK; + saslprogress progress; + int rc; + + if(!li) + return CURLE_FAILED_INIT; + li->servercred = NULL; + rc = ldap_parse_sasl_bind_result(li->ld, msg, &li->servercred, 0); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: sasl ldap_parse_result %s", ldap_err2string(rc)); + result = oldap_map_error(rc, CURLE_LOGIN_DENIED); + } + else { + result = Curl_sasl_continue(&li->sasl, data, code, &progress); + if(!result) { + switch(progress) { + case SASL_DONE: + oldap_state(data, li, OLDAP_STOP); /* Authenticated */ + break; + case SASL_IDLE: /* No mechanism left after cancellation */ + failf(data, "Authentication cancelled"); + result = CURLE_LOGIN_DENIED; + break; + default: + break; + } + } + } + + if(li->servercred) + ber_bvfree(li->servercred); + return result; +} + +/* Handle a simple bind response. */ +static CURLcode oldap_state_bind_resp(struct Curl_easy *data, LDAPMessage *msg, + int code) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + CURLcode result = CURLE_OK; + struct berval *bv = NULL; + int rc; + + if(!li) + return CURLE_FAILED_INIT; + + if(code != LDAP_SUCCESS) + return oldap_map_error(code, CURLE_LDAP_CANNOT_BIND); + + rc = ldap_parse_sasl_bind_result(li->ld, msg, &bv, 0); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: bind ldap_parse_sasl_bind_result %s", + ldap_err2string(rc)); + result = oldap_map_error(rc, CURLE_LDAP_CANNOT_BIND); + } + else + oldap_state(data, li, OLDAP_STOP); + + if(bv) + ber_bvfree(bv); + return result; +} + +static CURLcode oldap_connecting(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + LDAPMessage *msg = NULL; + struct timeval tv = { 0, 0 }; + int code = LDAP_SUCCESS; + int rc; + + if(!li) + return CURLE_FAILED_INIT; + + if(li->state != OLDAP_SSL && li->state != OLDAP_TLS) { + /* Get response to last command. */ + rc = ldap_result(li->ld, li->msgid, LDAP_MSG_ONE, &tv, &msg); + switch(rc) { + case 0: /* Timed out. */ + return CURLE_OK; + case LDAP_RES_SEARCH_ENTRY: + case LDAP_RES_SEARCH_REFERENCE: + break; + default: + li->msgid = 0; /* Nothing to abandon upon error. */ + if(rc < 0) { + failf(data, "LDAP local: connecting ldap_result %s", + ldap_err2string(rc)); + return oldap_map_error(rc, CURLE_COULDNT_CONNECT); + } + break; + } + + /* Get error code from message. */ + rc = ldap_parse_result(li->ld, msg, &code, NULL, NULL, NULL, NULL, 0); + if(rc) + code = rc; + else { + /* store the latest code for later retrieval */ + data->info.httpcode = code; + } + + /* If protocol version 3 is not supported, fallback to version 2. */ + if(code == LDAP_PROTOCOL_ERROR && li->state != OLDAP_BINDV2 && +#ifdef USE_SSL + (ssl_installed(conn) || data->set.use_ssl <= CURLUSESSL_TRY) && +#endif + li->sasl.prefmech == SASL_AUTH_NONE) { + static const int version = LDAP_VERSION2; + + ldap_set_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &version); + ldap_msgfree(msg); + return oldap_perform_bind(data, OLDAP_BINDV2); + } + } + + /* Handle response message according to current state. */ + switch(li->state) { + +#ifdef USE_SSL + case OLDAP_SSL: + result = oldap_ssl_connect(data, OLDAP_SSL); + if(!result && ssl_installed(conn)) { + if(li->sasl.prefmech != SASL_AUTH_NONE) + result = oldap_perform_mechs(data); + else + result = oldap_perform_bind(data, OLDAP_BIND); + } + break; + case OLDAP_STARTTLS: + if(code != LDAP_SUCCESS) { + if(data->set.use_ssl != CURLUSESSL_TRY) + result = oldap_map_error(code, CURLE_USE_SSL_FAILED); + else if(li->sasl.prefmech != SASL_AUTH_NONE) + result = oldap_perform_mechs(data); + else + result = oldap_perform_bind(data, OLDAP_BIND); + break; + } + result = Curl_ssl_cfilter_add( + data, Curl_conn_get_origin(conn, FIRSTSOCKET), conn, FIRSTSOCKET); + if(result) + break; + FALLTHROUGH(); + case OLDAP_TLS: + result = oldap_ssl_connect(data, OLDAP_TLS); + if(result) + result = oldap_map_error(code, CURLE_USE_SSL_FAILED); + else if(ssl_installed(conn)) { + if(li->sasl.prefmech != SASL_AUTH_NONE) + result = oldap_perform_mechs(data); + else if(data->state.creds) + result = oldap_perform_bind(data, OLDAP_BIND); + else { + /* Version 3 supported: no bind required */ + oldap_state(data, li, OLDAP_STOP); + result = CURLE_OK; + } + } + break; +#endif + + case OLDAP_MECHS: + result = oldap_state_mechs_resp(data, msg, code); + break; + case OLDAP_SASL: + result = oldap_state_sasl_resp(data, msg, code); + break; + case OLDAP_BIND: + case OLDAP_BINDV2: + result = oldap_state_bind_resp(data, msg, code); + break; + default: + /* internal error */ + result = CURLE_COULDNT_CONNECT; + break; + } + + ldap_msgfree(msg); + + *done = li->state == OLDAP_STOP; + if(*done) + conn->recv[FIRSTSOCKET] = oldap_recv; + + if(result && li->msgid) { + ldap_abandon_ext(li->ld, li->msgid, NULL, NULL); + li->msgid = 0; + } + return result; +} + +static CURLcode oldap_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + (void)dead_connection; +#ifndef USE_SSL + (void)data; +#endif + + if(li && li->ld) { +#ifdef USE_SSL + if(ssl_installed(conn)) { + Sockbuf *sb; + if(ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb) != LDAP_OPT_SUCCESS || + ber_sockbuf_add_io(sb, &ldapsb_tls, LBER_SBIOD_LEVEL_TRANSPORT, data)) + return CURLE_FAILED_INIT; + } +#endif + ldap_unbind_ext(li->ld, NULL, NULL); + li->ld = NULL; + } + return CURLE_OK; +} + +static CURLcode oldap_do(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + struct ldapreqinfo *lr; + CURLcode result; + int rc; + LDAPURLDesc *lud; + int msgid; + + if(!li) + return CURLE_FAILED_INIT; + + infof(data, "LDAP local: %s", Curl_bufref_ptr(&data->state.url)); + + result = oldap_url_parse(data, &lud); + if(result) + goto out; + +#ifdef USE_SSL + if(ssl_installed(conn)) { + Sockbuf *sb; + /* re-install the libcurl SSL handlers into the sockbuf. */ + if((ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb) != LDAP_OPT_SUCCESS) || + ber_sockbuf_add_io(sb, &ldapsb_tls, LBER_SBIOD_LEVEL_TRANSPORT, data)) { + ldap_free_urldesc(lud); + return CURLE_FAILED_INIT; + } + } +#endif + + rc = ldap_search_ext(li->ld, lud->lud_dn, lud->lud_scope, + lud->lud_filter, lud->lud_attrs, 0, + NULL, NULL, NULL, 0, &msgid); + ldap_free_urldesc(lud); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ldap_search_ext %s", ldap_err2string(rc)); + result = CURLE_LDAP_SEARCH_FAILED; + goto out; + } + + lr = curlx_calloc(1, sizeof(struct ldapreqinfo)); + if(!lr || + Curl_meta_set(data, CURL_META_LDAP_EASY, lr, oldap_easy_dtor)) { + ldap_abandon_ext(li->ld, msgid, NULL, NULL); + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + lr->msgid = msgid; + Curl_xfer_setup_recv(data, FIRSTSOCKET, -1); + *done = TRUE; + +out: + return result; +} + +static CURLcode oldap_done(struct Curl_easy *data, CURLcode res, + bool premature) +{ + struct connectdata *conn = data->conn; + struct ldapreqinfo *lr = Curl_meta_get(data, CURL_META_LDAP_EASY); + + (void)res; + (void)premature; + + if(lr) { + /* if there was a search in progress, abandon it */ + if(lr->msgid) { + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + if(li && li->ld) { + ldap_abandon_ext(li->ld, lr->msgid, NULL, NULL); + } + lr->msgid = 0; + } + Curl_meta_remove(data, CURL_META_LDAP_EASY); + } + + return CURLE_OK; +} + +static CURLcode client_write(struct Curl_easy *data, + const char *prefix, size_t plen, + const char *value, size_t len, + const char *suffix, size_t slen) +{ + CURLcode result = CURLE_OK; + + if(prefix) { + /* If we have a zero-length value and the prefix ends with a space + separator, drop the latter. */ + if(!len && plen && prefix[plen - 1] == ' ') + plen--; + result = Curl_client_write(data, CLIENTWRITE_BODY, prefix, plen); + } + if(!result && value) { + result = Curl_client_write(data, CLIENTWRITE_BODY, value, len); + } + if(!result && suffix) { + result = Curl_client_write(data, CLIENTWRITE_BODY, suffix, slen); + } + return result; +} + +static CURLcode oldap_recv(struct Curl_easy *data, int8_t sockindex, char *buf, + size_t len, size_t *pnread) +{ + struct connectdata *conn = data->conn; + struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN); + struct ldapreqinfo *lr = Curl_meta_get(data, CURL_META_LDAP_EASY); + int rc; + LDAPMessage *msg = NULL; + BerElement *ber = NULL; + struct timeval tv = { 0, 0 }; + struct berval bv, *bvals; + CURLcode result = CURLE_AGAIN; + int code; + char *info = NULL; + + (void)len; + (void)buf; + (void)sockindex; + *pnread = 0; + if(!li || !lr) + return CURLE_FAILED_INIT; + + rc = ldap_result(li->ld, lr->msgid, LDAP_MSG_ONE, &tv, &msg); + if(rc < 0) { + failf(data, "LDAP local: search ldap_result %s", ldap_err2string(rc)); + result = CURLE_RECV_ERROR; + } + + /* error or timed out */ + if(!msg) + return result; + + result = CURLE_OK; + + switch(ldap_msgtype(msg)) { + case LDAP_RES_SEARCH_RESULT: + lr->msgid = 0; + rc = ldap_parse_result(li->ld, msg, &code, NULL, &info, NULL, NULL, 0); + if(rc) { + failf(data, "LDAP local: search ldap_parse_result %s", + ldap_err2string(rc)); + result = CURLE_LDAP_SEARCH_FAILED; + break; + } + + /* store the latest code for later retrieval */ + data->info.httpcode = code; + + switch(code) { + case LDAP_SIZELIMIT_EXCEEDED: + infof(data, "There are more than %d entries", lr->nument); + FALLTHROUGH(); + case LDAP_SUCCESS: + data->req.size = data->req.bytecount; + break; + default: + failf(data, "LDAP remote: search failed %s %s", ldap_err2string(code), + info ? info : ""); + result = CURLE_LDAP_SEARCH_FAILED; + break; + } + if(info) + ldap_memfree(info); + break; + case LDAP_RES_SEARCH_ENTRY: + lr->nument++; + rc = ldap_get_dn_ber(li->ld, msg, &ber, &bv); + if(rc < 0) { + result = CURLE_RECV_ERROR; + break; + } + + result = client_write(data, STRCONST("DN: "), bv.bv_val, bv.bv_len, + STRCONST("\n")); + if(result) + break; + + for(rc = ldap_get_attribute_ber(li->ld, msg, ber, &bv, &bvals); + rc == LDAP_SUCCESS; + rc = ldap_get_attribute_ber(li->ld, msg, ber, &bv, &bvals)) { + int i; + bool binary; + + if(!bv.bv_val) + break; + + if(!bvals) { + result = client_write(data, STRCONST("\t"), bv.bv_val, bv.bv_len, + STRCONST(":\n")); + if(result) + break; + continue; + } + + binary = bv.bv_len > 7 && + curl_strnequal(bv.bv_val + bv.bv_len - 7, ";binary", 7); + + for(i = 0; bvals[i].bv_val; i++) { + bool binval = FALSE; + + result = client_write(data, STRCONST("\t"), bv.bv_val, bv.bv_len, + STRCONST(":")); + if(result) + break; + + if(!binary) { + /* check for a leading ':' or '<' (not a SAFE-INIT-CHAR per RFC + 2849) or leading or trailing whitespace */ + if(bvals[i].bv_len && + ((bvals[i].bv_val[0] == ':') || (bvals[i].bv_val[0] == '<') || + ISBLANK(bvals[i].bv_val[0]) || + ISBLANK(bvals[i].bv_val[bvals[i].bv_len - 1]))) + binval = TRUE; + else { + /* check for unprintable characters */ + unsigned int j; + for(j = 0; j < bvals[i].bv_len; j++) + if(!ISPRINT(bvals[i].bv_val[j])) { + binval = TRUE; + break; + } + } + } + if(binary || binval) { + char *val_b64 = NULL; + size_t val_b64_sz = 0; + + /* Binary value, encode to base64. */ + if(bvals[i].bv_len) + result = curlx_base64_encode((uint8_t *)bvals[i].bv_val, + bvals[i].bv_len, + &val_b64, &val_b64_sz); + if(!result) + result = client_write(data, STRCONST(": "), val_b64, val_b64_sz, + STRCONST("\n")); + curlx_free(val_b64); + } + else + result = client_write(data, STRCONST(" "), + bvals[i].bv_val, bvals[i].bv_len, + STRCONST("\n")); + if(result) + break; + } + + ber_memfree(bvals); + bvals = NULL; + if(!result) + result = client_write(data, STRCONST("\n"), NULL, 0, NULL, 0); + if(result) + break; + } + + if(!result) + result = client_write(data, STRCONST("\n"), NULL, 0, NULL, 0); + if(!result) + result = CURLE_AGAIN; + break; + } + + ber_free(ber, 0); + ldap_msgfree(msg); + return result; +} + +void Curl_ldap_version(char *buf, size_t bufsz) +{ + LDAPAPIInfo api; + api.ldapai_info_version = LDAP_API_INFO_VERSION; + + if(ldap_get_option(NULL, LDAP_OPT_API_INFO, &api) == LDAP_OPT_SUCCESS) { + unsigned int patch = (unsigned int)(api.ldapai_vendor_version % 100); + unsigned int major = (unsigned int)(api.ldapai_vendor_version / 10000); + unsigned int minor = + (((unsigned int)api.ldapai_vendor_version - (major * 10000)) + - patch) / 100; + curl_msnprintf(buf, bufsz, "%s/%u.%u.%u", + api.ldapai_vendor_name, major, minor, patch); + ldap_memfree(api.ldapai_vendor_name); + ber_memvfree((void **)api.ldapai_extensions); + } + else + curl_msnprintf(buf, bufsz, "OpenLDAP"); +} + +/* + * LDAP protocol handler. + */ +const struct Curl_protocol Curl_protocol_ldap = { + oldap_setup_connection, /* setup_connection */ + oldap_do, /* do_it */ + oldap_done, /* done */ + ZERO_NULL, /* do_more */ + oldap_connect, /* connect_it */ + oldap_connecting, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_pollset */ + ZERO_NULL, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + oldap_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#endif /* !CURL_DISABLE_LDAP && USE_OPENLDAP */ + +/* The LDAP scheme structs are in ldap.c */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/parsedate.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/parsedate.c new file mode 100644 index 0000000000..ec9f21296b --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/parsedate.c @@ -0,0 +1,606 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "parsedate.h" +#include "curlx/strparse.h" +#include "curlx/strcopy.h" + +/* A brief summary of the date string formats this parser groks: + + RFC 2616 3.3.1 + + Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 + Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 + Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format + + we support dates without week day name: + + 06 Nov 1994 08:49:37 GMT + 06-Nov-94 08:49:37 GMT + Nov 6 08:49:37 1994 + + without the time zone: + + 06 Nov 1994 08:49:37 + 06-Nov-94 08:49:37 + + weird order: + + 1994 Nov 6 08:49:37 (GNU date fails) + GMT 08:49:37 06-Nov-94 Sunday + 94 6 Nov 08:49:37 (GNU date fails) + + time left out: + + 1994 Nov 6 + 06-Nov-94 + Sun Nov 6 94 + + unusual separators: + + 1994.Nov.6 + Sun/Nov/6/94/GMT + + commonly used time zone names: + + Sun, 06 Nov 1994 08:49:37 CET + 06 Nov 1994 08:49:37 EST + + time zones specified using RFC822 style: + + Sun, 12 Sep 2004 15:05:58 -0700 + Sat, 11 Sep 2004 21:32:11 +0200 + + compact numerical date strings: + + 20040912 15:05:58 -0700 + 20040911 +0200 + */ + +#if !defined(CURL_DISABLE_PARSEDATE) || !defined(CURL_DISABLE_FTP) || \ + !defined(CURL_DISABLE_FILE) || defined(USE_GNUTLS) +/* These names are also used by FTP and FILE code */ +const char * const Curl_wkday[] = { + "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" +}; +const char * const Curl_month[] = { + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" +}; +#endif + +#define PARSEDATE_OK 0 +#define PARSEDATE_FAIL (-1) + +#ifndef CURL_DISABLE_PARSEDATE + +#if SIZEOF_TIME_T < 5 +#define PARSEDATE_LATER 1 +#endif +#if SIZEOF_TIME_T < 5 || defined(HAVE_TIME_T_UNSIGNED) +#define PARSEDATE_SOONER 2 +#endif + +static const char * const weekday[] = { + "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" +}; + +struct tzinfo { + char name[5]; + int16_t offset; /* +/- in minutes */ +}; + +#define tDAYZONE (-60) /* offset for daylight savings time */ + +/* alpha-sorted list of time zones */ +static const struct tzinfo tz[] = { + { "A", -1 * 60 }, /* Alpha */ + { "ADT", 240 + tDAYZONE }, /* Atlantic Daylight */ + { "AHST", 600 }, /* Alaska-Hawaii Standard */ + { "AST", 240 }, /* Atlantic Standard */ + { "B", -2 * 60 }, /* Bravo */ + { "BST", 0 + tDAYZONE }, /* British Summer */ + { "C", -3 * 60 }, /* Charlie */ + { "CAT", 600 }, /* Central Alaska */ + { "CCT", -480 }, /* China Coast, USSR Zone 7 */ + { "CDT", 360 + tDAYZONE }, /* Central Daylight */ + { "CEST", -60 + tDAYZONE }, /* Central European Summer */ + { "CET", -60 }, /* Central European */ + { "CST", 360 }, /* Central Standard */ + { "D", -4 * 60 }, /* Delta */ + { "E", -5 * 60 }, /* Echo */ + { "EADT", -600 + tDAYZONE }, /* Eastern Australian Daylight */ + { "EAST", -600 }, /* Eastern Australian Standard */ + { "EDT", 300 + tDAYZONE }, /* Eastern Daylight */ + { "EET", -120 }, /* Eastern Europe, USSR Zone 1 */ + { "EST", 300 }, /* Eastern Standard */ + { "F", -6 * 60 }, /* Foxtrot */ + { "FST", -60 + tDAYZONE }, /* French Summer */ + { "FWT", -60 }, /* French Winter */ + { "G", -7 * 60 }, /* Golf */ + { "GMT", 0 }, /* Greenwich Mean */ + { "GST", -600 }, /* Guam Standard, USSR Zone 9 */ + { "H", -8 * 60 }, /* Hotel */ + { "HDT", 600 + tDAYZONE }, /* Hawaii Daylight */ + { "HST", 600 }, /* Hawaii Standard */ + { "I", -9 * 60 }, /* India */ + { "IDLE", -720 }, /* International Date Line East */ + { "IDLW", 720 }, /* International Date Line West */ + { "JST", -540 }, /* Japan Standard, USSR Zone 8 */ + { "K", -10 * 60 }, /* Kilo */ + { "L", -11 * 60 }, /* Lima */ + { "M", -12 * 60 }, /* Mike */ + { "MDT", 420 + tDAYZONE }, /* Mountain Daylight */ + { "MEST", -60 + tDAYZONE }, /* Middle European Summer */ + { "MESZ", -60 + tDAYZONE }, /* Middle European Summer */ + { "MET", -60 }, /* Middle European */ + { "MEWT", -60 }, /* Middle European Winter */ + { "MST", 420 }, /* Mountain Standard */ + { "N", 60 }, /* November */ + { "NT", 660 }, /* Nome */ /* spellchecker:disable-line */ + { "NZDT", -720 + tDAYZONE }, /* New Zealand Daylight */ + { "NZST", -720 }, /* New Zealand Standard */ + { "NZT", -720 }, /* New Zealand */ + { "O", 2 * 60 }, /* Oscar */ + { "P", 3 * 60 }, /* Papa */ + { "PDT", 480 + tDAYZONE }, /* Pacific Daylight */ + { "PST", 480 }, /* Pacific Standard */ + { "Q", 4 * 60 }, /* Quebec */ + { "R", 5 * 60 }, /* Romeo */ + { "S", 6 * 60 }, /* Sierra */ + { "T", 7 * 60 }, /* Tango */ + { "U", 8 * 60 }, /* Uniform */ + { "UT", 0 }, /* Universal Time */ + { "UTC", 0 }, /* Universal (Coordinated) */ + { "V", 9 * 60 }, /* Victor */ + { "W", 10 * 60 }, /* Whiskey */ + { "WADT", -420 + tDAYZONE }, /* West Australian Daylight */ + { "WAST", -420 }, /* spellchecker:disable-line */ + /* West Australian Standard */ + { "WAT", 60 }, /* West Africa */ + { "WET", 0 }, /* Western European */ + { "X", 11 * 60 }, /* X-ray */ + { "Y", 12 * 60 }, /* Yankee */ + { "YDT", 540 + tDAYZONE }, /* Yukon Daylight */ + { "YST", 540 }, /* Yukon Standard */ + { "Z", 0 }, /* Zulu, zero meridian, a.k.a. UTC */ +}; + +/* returns: + -1 no day + 0 monday - 6 sunday + */ +static int checkday(const char *check, size_t len) +{ + int i; + const char * const *what; + if(len > 3) + what = &weekday[0]; + else if(len == 3) + what = &Curl_wkday[0]; + else + return -1; /* too short */ + for(i = 0; i < 7; i++) { + size_t ilen = strlen(what[0]); + if((ilen == len) && + curl_strnequal(check, what[0], len)) + return i; + what++; + } + return -1; +} + +static int checkmonth(const char *check, size_t len) +{ + int i; + const char * const *what = &Curl_month[0]; + if(len != 3) + return -1; /* not a month */ + + for(i = 0; i < 12; i++) { + if(curl_strnequal(check, what[0], 3)) + return i; + what++; + } + return -1; /* return the offset or -1, no real offset is -1 */ +} + +static int tzcompare(const void *m1, const void *m2) +{ + const struct tzinfo *tz1 = m1; + const struct tzinfo *tz2 = m2; + return strcmp(tz1->name, tz2->name); +} + +/* return the time zone offset between GMT and the input one, in number of + seconds or -1 if the timezone was not found/legal */ +static int checktz(const char *check, size_t len) +{ + if(len <= 4) { + const struct tzinfo *what; + struct tzinfo find; + curlx_strcopy(find.name, sizeof(find.name), check, len); + what = bsearch(&find, tz, CURL_ARRAYSIZE(tz), sizeof(tz[0]), tzcompare); + if(what) + return what->offset * 60; + } + return -1; +} + +static void skip(const char **date) +{ + /* skip everything that are not letters or digits */ + while(**date && !ISALNUM(**date)) + (*date)++; +} + +/* each field is exactly -1 when unknown */ +struct when { + int wday; /* day of the week, 0-6 (mon-sun) */ + int mon; /* month of the year, 0-11 */ + int mday; /* day of month, 1 - 31 */ + int hour; /* hour of day, 0 - 23 */ + int min; /* minute of hour, 0 - 59 */ + int sec; /* second of minute, 0 - 60 (leap second) */ + int year; /* year, >= 1583 */ + int tzoff; /* time zone offset in seconds */ +}; + +enum assume { + DATE_MDAY, + DATE_YEAR, + DATE_TIME +}; + +/* (1969 / 4) - (1969 / 100) + (1969 / 400) = 492 - 19 + 4 = 477 */ +#define LEAP_DAYS_BEFORE_1969 477 + +/* + * time2epoch: time stamp to seconds since epoch in GMT time zone. Similar to + * mktime but for GMT only. + */ +static curl_off_t time2epoch(struct when *w) +{ + static const int cumulative_days[12] = { + 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 + }; + int y = w->year - (w->mon <= 1); + int leap_days = (y / 4) - (y / 100) + (y / 400) - LEAP_DAYS_BEFORE_1969; + curl_off_t days = (curl_off_t)(w->year - 1970) * 365 + leap_days + + cumulative_days[w->mon] + w->mday - 1; + + return (((days * 24 + w->hour) * 60 + w->min) * 60) + w->sec; +} + +/* Returns the value of a single-digit or two-digit decimal number, return + then pointer to after the number. The 'date' pointer is known to point to a + digit. */ +static int oneortwodigit(const char *date, const char **endp) +{ + int num = date[0] - '0'; + if(ISDIGIT(date[1])) { + *endp = &date[2]; + return (num * 10) + (date[1] - '0'); + } + *endp = &date[1]; + return num; +} + +/* HH:MM:SS or HH:MM and accept single-digits too */ +static bool match_time(const char *date, struct when *w, char **endp) +{ + const char *p; + int hh, mm, ss = 0; + hh = oneortwodigit(date, &p); + if((hh < 24) && (*p == ':') && ISDIGIT(p[1])) { + mm = oneortwodigit(&p[1], &p); + if(mm < 60) { + if((*p == ':') && ISDIGIT(p[1])) { + ss = oneortwodigit(&p[1], &p); + if(ss <= 60) { + /* valid HH:MM:SS */ + goto match; + } + } + else { + /* valid HH:MM */ + goto match; + } + } + } + return FALSE; /* not a time string */ +match: + w->hour = hh; + w->min = mm; + w->sec = ss; + *endp = (char *)CURL_UNCONST(p); + return TRUE; +} + +/* + * parsedate() + * + * Returns: + * + * PARSEDATE_OK - a fine conversion + * PARSEDATE_FAIL - failed to convert + * PARSEDATE_LATER - time overflow at the far end of time_t + * PARSEDATE_SOONER - time underflow at the low end of time_t + */ + +/* Wednesday is the longest name this parser knows about */ +#define NAME_LEN 12 + +static void initwhen(struct when *w) +{ + w->wday = w->mon = w->mday = w->hour = w->min = w->sec = w->year = w->tzoff = + -1; +} + +static int datestring(const char **datep, struct when *w) +{ + /* a name coming up */ + size_t len = 0; + const char *p = *datep; + bool found = FALSE; + while(ISALPHA(*p) && (len < NAME_LEN)) { + p++; + len++; + } + + if(len != NAME_LEN) { + if(w->wday == -1) { + w->wday = checkday(*datep, len); + if(w->wday != -1) + found = TRUE; + } + if(!found && (w->mon == -1)) { + w->mon = checkmonth(*datep, len); + if(w->mon != -1) + found = TRUE; + } + + if(!found && (w->tzoff == -1)) { + /* this must be a time zone string */ + w->tzoff = checktz(*datep, len); + if(w->tzoff != -1) + found = TRUE; + } + } + if(!found) + return PARSEDATE_FAIL; /* bad string */ + + *datep += len; + return PARSEDATE_OK; +} + +static int datenum(const char *indate, const char **datep, struct when *w, + enum assume *dignextp) +{ + /* a digit */ + unsigned int val; + char *end; + const char *date = *datep; + enum assume dignext = *dignextp; + + if((w->sec == -1) && match_time(date, w, &end)) { + /* time stamp */ + date = end; + } + else { + bool found = FALSE; + curl_off_t lval; + int num_digits = 0; + const char *p = *datep; + if(curlx_str_number(&p, &lval, 99999999)) + return PARSEDATE_FAIL; + + /* we know num_digits cannot be larger than 8 */ + num_digits = (int)(p - *datep); + val = (unsigned int)lval; + + if((w->tzoff == -1) && + (num_digits == 4) && + (val <= 1400) && + (indate < date) && + (date[-1] == '+' || date[-1] == '-')) { + /* four digits and a value less than or equal to 1400 (to take into + account all sorts of funny time zone diffs) and it is preceded + with a plus or minus. This is a time zone indication. 1400 is + picked since +1300 is frequently used and +1400 is mentioned as + an edge number in the document "ISO C 200X Proposal: Timezone + Functions" at http://david.tribble.com/text/c0xtimezone.html If + anyone has a more authoritative source for the exact maximum time + zone offsets, please speak up! */ + found = TRUE; + w->tzoff = ((val / 100 * 60) + (val % 100)) * 60; + + /* the + and - prefix indicates the local time compared to GMT, + this we need their reversed math to get what we want */ + w->tzoff = date[-1] == '+' ? -w->tzoff : w->tzoff; + } + + else if((num_digits == 8) && (w->year == -1) && + (w->mon == -1) && (w->mday == -1)) { + /* 8 digits, no year, month or day yet. This is YYYYMMDD */ + found = TRUE; + w->year = val / 10000; + w->mon = ((val % 10000) / 100) - 1; /* month is 0 - 11 */ + w->mday = val % 100; + } + + if(!found && (dignext == DATE_MDAY) && (w->mday == -1)) { + if((val > 0) && (val < 32)) { + w->mday = val; + found = TRUE; + } + dignext = DATE_YEAR; + } + + if(!found && (dignext == DATE_YEAR) && (w->year == -1)) { + w->year = val; + found = TRUE; + if(w->year < 100) { + if(w->year > 70) + w->year += 1900; + else + w->year += 2000; + } + if(w->mday == -1) + dignext = DATE_MDAY; + } + + if(!found) + return PARSEDATE_FAIL; + + date = p; + } + *datep = date; + *dignextp = dignext; + return PARSEDATE_OK; +} + +static int datecheck(struct when *w) +{ + if(w->sec == -1) + w->sec = w->min = w->hour = 0; /* no time, make it zero */ + + if((w->mday == -1) || (w->mon == -1) || (w->year == -1)) + /* lacks vital info, fail */ + return PARSEDATE_FAIL; + + /* The Gregorian calendar was introduced 1582 */ + else if(w->year < 1583) + return PARSEDATE_FAIL; + + else if((w->mday > 31) || (w->mon > 11) || (w->hour > 23) || + (w->min > 59) || (w->sec > 60)) + return PARSEDATE_FAIL; /* clearly an illegal date */ + + return PARSEDATE_OK; +} + +static void tzadjust(curl_off_t *tp, struct when *w) +{ + if(w->tzoff == -1) /* unknown tz means no offset */ + w->tzoff = 0; + + /* Add the time zone diff between local time zone and GMT. */ + if((w->tzoff > 0) && (*tp > (curl_off_t)(CURL_OFF_T_MAX - w->tzoff))) + *tp = CURL_OFF_T_MAX; + else + *tp += w->tzoff; + /* this needs no minimum check since we require a year > 1582 */ +} + +static int mktimet(curl_off_t seconds, time_t *output) +{ +#if SIZEOF_TIME_T < 5 + if(seconds > TIME_T_MAX) { + *output = TIME_T_MAX; + return PARSEDATE_LATER; + } + else if(seconds < TIME_T_MIN) { + *output = TIME_T_MIN; + return PARSEDATE_SOONER; + } +#elif defined(HAVE_TIME_T_UNSIGNED) + if(seconds < 0) { + *output = 0; + return PARSEDATE_SOONER; + } +#endif + *output = (time_t)seconds; + return PARSEDATE_OK; +} + +static int parsedate(const char *date, time_t *output) +{ + curl_off_t seconds = 0; + enum assume dignext = DATE_MDAY; + const char *indate = date; /* save the original pointer */ + int part = 0; /* max 6 parts */ + int rc = 0; + struct when w; + initwhen(&w); + + while(*date && (part < 6)) { + skip(&date); + + if(ISALPHA(*date)) + rc = datestring(&date, &w); + else if(ISDIGIT(*date)) + rc = datenum(indate, &date, &w, &dignext); + if(rc) + return rc; + + part++; + } + + rc = datecheck(&w); + if(rc) + return rc; + + seconds = time2epoch(&w); /* get number of seconds */ + tzadjust(&seconds, &w); /* handle the time zone offset */ + rc = mktimet(seconds, output); /* squeeze seconds into a time_t */ + + return rc; +} +#else +/* disabled */ +static int parsedate(const char *date, time_t *output) +{ + (void)date; + *output = 0; + return PARSEDATE_OK; /* a lie */ +} +#endif + +time_t curl_getdate(const char *p, const time_t *unused) +{ + time_t parsed = -1; + int rc = parsedate(p, &parsed); + (void)unused; /* legacy argument from the past that we ignore */ + + if(rc == PARSEDATE_OK) { + if(parsed == (time_t)-1) + /* avoid returning -1 for a working scenario */ + parsed++; + return parsed; + } + /* everything else is fail */ + return -1; +} + +/* Curl_getdate_capped() differs from curl_getdate() in that this will return + TIME_T_MAX in case the parsed time value was too big, instead of an + error. Returns non-zero on error. */ + +int Curl_getdate_capped(const char *p, time_t *tp) +{ + int rc = parsedate(p, tp); + return (rc == PARSEDATE_FAIL); +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/parsedate.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/parsedate.h new file mode 100644 index 0000000000..ea136bd301 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/parsedate.h @@ -0,0 +1,35 @@ +#ifndef HEADER_CURL_PARSEDATE_H +#define HEADER_CURL_PARSEDATE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +extern const char * const Curl_wkday[7]; +extern const char * const Curl_month[12]; + +/* Curl_getdate_capped() differs from curl_getdate() in that this returns + TIME_T_MAX in case the parsed time value was too big, instead of an + error. */ + +int Curl_getdate_capped(const char *p, time_t *tp); + +#endif /* HEADER_CURL_PARSEDATE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/peer.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/peer.c new file mode 100644 index 0000000000..4a7a12d8cf --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/peer.c @@ -0,0 +1,732 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * IDN conversions + */ +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NET_IF_H +#include <net/if.h> +#endif +#ifdef HAVE_IPHLPAPI_H +#include <Iphlpapi.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif + +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#ifdef HAVE_SYS_UN_H +#include <sys/un.h> +#endif + +#if defined(HAVE_IF_NAMETOINDEX) && defined(USE_WINSOCK) +#if defined(__MINGW32__) && (__MINGW64_VERSION_MAJOR <= 5) +#include <wincrypt.h> /* workaround for old mingw-w64 missing to include it */ +#endif +#include <iphlpapi.h> +#endif + +#include "curl_addrinfo.h" +#include "curl_trc.h" +#include "protocol.h" +#include "http_proxy.h" +#include "idn.h" +#include "curlx/strdup.h" +#include "curlx/strparse.h" +#include "peer.h" +#include "urldata.h" +#include "url.h" +#include "urlapi-int.h" +#include "vtls/vtls.h" + +struct peer_parse { + const struct Curl_scheme *scheme; + struct Curl_str host_user; + struct Curl_str host; + struct Curl_str zoneid; + char *tmp_host_user; + char *tmp_host; + char *tmp_zoneid; + uint32_t scopeid; + uint16_t port; + bool ipv6; + bool unix_socket; + bool abstract_uds; +}; + +static void peer_parse_clear(struct peer_parse *pp) +{ + curlx_free(pp->tmp_host_user); + curlx_free(pp->tmp_host); + curlx_free(pp->tmp_zoneid); + memset(pp, 0, sizeof(*pp)); +} + +static CURLcode peer_create(struct peer_parse *pp, + struct Curl_peer **ppeer) +{ + struct Curl_peer *peer = NULL; + CURLcode result = CURLE_OK; + size_t zone_alen = 0, host_alen = 0; + + if(!pp || !pp->scheme) + return CURLE_FAILED_INIT; + if(!pp->host.len && !(pp->scheme->flags & PROTOPT_NONETWORK)) + return CURLE_FAILED_INIT; + + if((pp->host.str != pp->host_user.str) || + (pp->host.len != pp->host_user.len)) { + host_alen = pp->host.len + 1; + } + zone_alen = pp->zoneid.len ? (pp->zoneid.len + 1) : 0; + + /* null-terminator already part of struct */ + peer = curlx_calloc(1, sizeof(*peer) + + pp->host_user.len + host_alen + zone_alen); + if(!peer) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + peer->refcount = 1; + peer->scheme = pp->scheme; + peer->hostname = peer->user_hostname; + peer->port = pp->port; + peer->scopeid = pp->scopeid; + peer->ipv6 = pp->ipv6; + peer->unix_socket = pp->unix_socket; + peer->abstract_uds = pp->abstract_uds; + + if(pp->host_user.len) + memcpy(peer->user_hostname, pp->host_user.str, pp->host_user.len); + + if(host_alen) { + peer->hostname = peer->user_hostname + pp->host_user.len + 1; + memcpy(peer->hostname, pp->host.str, pp->host.len); + } + + if(zone_alen) { + peer->zoneid = peer->user_hostname + pp->host_user.len + 1 + host_alen; + memcpy(peer->zoneid, pp->zoneid.str, pp->zoneid.len); +#ifdef USE_IPV6 + /* Determine scope_id if not already provided */ + if(!peer->scopeid) { + const char *p = peer->zoneid; + curl_off_t scope; + if(!curlx_str_number(&p, &scope, UINT_MAX)) { + /* A plain number, use it directly as a scope id. */ + peer->scopeid = (uint32_t)scope; + } +#ifdef HAVE_IF_NAMETOINDEX + else { + /* Zone identifier is not numeric */ + unsigned int idx = 0; + idx = if_nametoindex(peer->zoneid); + if(idx) { + peer->scopeid = (uint32_t)idx; + } + else { + /* Do we want to return an error here? */ + } + } +#endif /* HAVE_IF_NAMETOINDEX */ + } +#endif /* USE_IPV6 */ + } + +out: + if(!result) + *ppeer = peer; + else + Curl_peer_unlink(&peer); + return result; +} + +static CURLcode peer_parse_host(struct Curl_easy *data, + struct peer_parse *pp, + bool scan_for_ipv6) +{ + if(!pp || !pp->host_user.str || !pp->host_user.len) + return CURLE_FAILED_INIT; + + if(pp->host_user.str[0] == '[') { + const char *s = pp->host_user.str + 1; + struct Curl_str tmp; + if(curlx_str_until(&s, &tmp, pp->host_user.len - 1, ']')) + return CURLE_URL_MALFORMAT; + + if(!Curl_looks_like_ipv6(tmp.str, tmp.len, TRUE, + &pp->host, &pp->zoneid)) { + failf(data, "Invalid IPv6 address format in '%.*s'", + (int)pp->host_user.len, pp->host_user.str); + return CURLE_URL_MALFORMAT; + } + pp->ipv6 = TRUE; + } + else { +#ifdef USE_IDN + if(!Curl_is_ASCII_str(&pp->host_user)) { + CURLcode result; + if(!pp->tmp_host_user) { + /* need a null-terminated string for IDN */ + pp->tmp_host_user = curlx_memdup0(pp->host_user.str, + pp->host_user.len); + if(!pp->tmp_host_user) + return CURLE_OUT_OF_MEMORY; + } + result = Curl_idn_decode(pp->tmp_host_user, &pp->tmp_host); + if(result) + return result; + pp->host.str = pp->tmp_host; + pp->host.len = strlen(pp->host.str); + } + else +#endif + if(scan_for_ipv6 && + Curl_looks_like_ipv6(pp->host_user.str, pp->host_user.len, TRUE, + &pp->host, &pp->zoneid)) { + if(pp->host_user.len < MAX_IPADR_LEN) { + char tmp[MAX_IPADR_LEN]; + memcpy(tmp, pp->host_user.str, pp->host_user.len); + tmp[pp->host_user.len] = 0; + pp->ipv6 = !Curl_is_ipv4addr(tmp); + } + else + pp->ipv6 = TRUE; + } + else + pp->host = pp->host_user; + } + return CURLE_OK; +} + +CURLcode Curl_peer_create(struct Curl_easy *data, + const struct Curl_scheme *scheme, + const char *hostname, + uint16_t port, + struct Curl_peer **ppeer) +{ + struct peer_parse pp; + CURLcode result; + + Curl_peer_unlink(ppeer); + memset(&pp, 0, sizeof(pp)); + pp.scheme = scheme; + pp.host_user.str = hostname; + pp.host_user.len = strlen(hostname); + pp.port = port; + + result = peer_parse_host(data, &pp, TRUE); + if(!result) + result = peer_create(&pp, ppeer); + + peer_parse_clear(&pp); + return result; +} + +#ifdef USE_UNIX_SOCKETS +CURLcode Curl_peer_uds_create(const struct Curl_scheme *scheme, + const char *path, + bool abstract_unix_socket, + struct Curl_peer **ppeer) +{ + struct peer_parse pp; + size_t pathlen = path ? strlen(path) : 0; + CURLcode result = CURLE_OK; + + Curl_peer_unlink(ppeer); + memset(&pp, 0, sizeof(pp)); + if(!scheme) + return CURLE_FAILED_INIT; + if(!pathlen) + return CURLE_FAILED_INIT; + + pp.scheme = scheme; + pp.host_user.str = pp.host.str = path; + pp.host_user.len = pp.host.len = pathlen; + pp.unix_socket = TRUE; + pp.abstract_uds = abstract_unix_socket; + + result = peer_create(&pp, ppeer); + peer_parse_clear(&pp); + return result; +} +#endif /* USE_UNIX_SOCKETS */ + +void Curl_peer_link(struct Curl_peer **pdest, struct Curl_peer *src) +{ + if(*pdest != src) { + Curl_peer_unlink(pdest); + *pdest = src; + if(src) { + DEBUGASSERT(src->refcount < UINT32_MAX); + src->refcount++; + } + } +} + +void Curl_peer_unlink(struct Curl_peer **ppeer) +{ + if(*ppeer) { + struct Curl_peer *peer = *ppeer; + + DEBUGASSERT(peer->refcount); + *ppeer = NULL; + if(peer->refcount) + peer->refcount--; + if(!peer->refcount) { + curlx_free(peer); + } + } +} + +bool Curl_peer_equal(struct Curl_peer *p1, struct Curl_peer *p2) +{ + return (p1 == p2) || + (p1 && p2 && + (p1->scheme == p2->scheme) && + Curl_peer_same_destination(p1, p2)); +} + +static bool peer_same_hostname(struct Curl_peer *p1, struct Curl_peer *p2) +{ + /* UNIX domain socket paths must be compared case-sensitive, + * as many filesystem are like that. */ + return (p1->unix_socket == p2->unix_socket) && + (p1->abstract_uds == p2->abstract_uds) && + (p1->ipv6 == p2->ipv6) && + (p1->unix_socket ? + !strcmp(p1->hostname, p2->hostname) : + curl_strequal(p1->hostname, p2->hostname)); +} + +bool Curl_peer_same_destination(struct Curl_peer *p1, struct Curl_peer *p2) +{ + return (p1 == p2) || + (p1 && p2 && + (p1->port == p2->port) && + peer_same_hostname(p1, p2) && + (p1->scopeid == p2->scopeid) && + (p1->scopeid || curl_strequal(p1->zoneid, p2->zoneid))); +} + +CURLcode Curl_peer_from_url(CURLU *uh, struct Curl_easy *data, + uint16_t port_override, + uint32_t scopeid_override, + struct Curl_peer **ppeer) +{ + struct peer_parse pp; + char *zoneid = NULL, *scheme = NULL, *hostname = NULL; + CURLUcode uc; + CURLcode result; + + Curl_peer_unlink(ppeer); + memset(&pp, 0, sizeof(pp)); + + uc = curl_url_get(uh, CURLUPART_SCHEME, &scheme, 0); + if(uc) + return Curl_uc_to_curlcode(uc); + pp.scheme = Curl_get_scheme(scheme); + if(!pp.scheme) { + failf(data, "Protocol \"%s\" not supported%s", scheme, + data->state.this_is_a_follow ? " (in redirect)" : ""); + result = CURLE_UNSUPPORTED_PROTOCOL; + goto out; + } + + uc = curl_url_get(uh, CURLUPART_HOST, &hostname, 0); + if(uc) { + if((uc == CURLUE_NO_HOST) && (pp.scheme->flags & PROTOPT_NONETWORK)) + ; /* acceptable */ + else { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + else if(strlen(hostname) > MAX_URL_LEN) { + failf(data, "Too long hostname (maximum is %d)", MAX_URL_LEN); + result = CURLE_URL_MALFORMAT; + goto out; + } + + pp.host_user.str = hostname ? hostname : ""; + pp.host_user.len = strlen(pp.host_user.str); + if(pp.host_user.len) { + result = peer_parse_host(data, &pp, FALSE); + if(result) + goto out; + } + else + pp.host = pp.host_user; + + if(port_override) { + /* if set, we use this instead of the port possibly given in the URL */ + char portbuf[16]; + curl_msnprintf(portbuf, sizeof(portbuf), "%d", port_override); + uc = curl_url_set(uh, CURLUPART_PORT, portbuf, 0); + if(uc) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + else + pp.port = port_override; + } + else { + uc = Curl_url_get_port(uh, &pp.port); + if(uc) { + if(uc == CURLUE_OUT_OF_MEMORY) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + else if(!(pp.scheme->flags & PROTOPT_NONETWORK)) { + result = CURLE_URL_MALFORMAT; + goto out; + } + /* no port ok when not a network scheme */ + } + } + + if(scopeid_override) + /* Override any scope id from an URL zone. */ + pp.scopeid = scopeid_override; + else { + if(curl_url_get(uh, CURLUPART_ZONEID, &zoneid, 0) == + CURLUE_OUT_OF_MEMORY) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + if(zoneid) { + pp.zoneid.str = zoneid; + pp.zoneid.len = strlen(zoneid); + } + } + + result = peer_create(&pp, ppeer); + if(result) + failf(data, "Error %d creating peer for %s:%u", + (int)result, pp.host_user.str, pp.port); + +out: + peer_parse_clear(&pp); + curlx_free(scheme); + curlx_free(hostname); + curlx_free(zoneid); + return result; +} + +/* Parse a "host:port" string to connect to into a peer. + * IPv6 addresses might appear in brackets or without them. */ +CURLcode Curl_peer_from_connect_to(struct Curl_easy *data, + const struct Curl_peer *dest, + const char *connect_to, + struct Curl_peer **ppeer) +{ + struct peer_parse pp; + const char *portstr = NULL; + CURLcode result; + + Curl_peer_unlink(ppeer); + memset(&pp, 0, sizeof(pp)); + if(!connect_to || !*connect_to) + return CURLE_FAILED_INIT; + + pp.scheme = dest->scheme; + + /* detect and extract RFC6874-style IPv6-addresses */ + if(connect_to[0] == '[') { + const char *s = strchr(connect_to + 1, ']'); + if(!s) { + failf(data, "Invalid IPv6 address format in '%s'", connect_to); + result = CURLE_SETOPT_OPTION_SYNTAX; + goto out; + } + portstr = strchr(s, ':'); + pp.host_user.str = connect_to; + pp.host_user.len = s - pp.host_user.str + 1; + pp.ipv6 = TRUE; + } + else { + portstr = strchr(connect_to, ':'); + pp.host_user.str = connect_to; + pp.host_user.len = portstr ? + (size_t)(portstr - connect_to) : strlen(connect_to); + } + + if(!pp.host_user.len) { /* no hostname found, only port switch */ + pp.host_user.str = dest->user_hostname; + pp.host_user.len = strlen(dest->user_hostname); + } + + result = peer_parse_host(data, &pp, FALSE); + if(result) + goto out; + + if(portstr && portstr[1]) { + const char *p = portstr + 1; + curl_off_t portparse; + if(curlx_str_number(&p, &portparse, 0xffff)) { + failf(data, "No valid port number in '%s'", connect_to); + result = CURLE_SETOPT_OPTION_SYNTAX; + goto out; + } + pp.port = (uint16_t)portparse; /* we know it will fit */ + } + else + pp.port = dest->port; + +#ifndef USE_IPV6 + if(pp.ipv6) { + failf(data, "Use of IPv6 in *_CONNECT_TO without IPv6 support built-in"); + result = CURLE_NOT_BUILT_IN; + goto out; + } +#endif + + result = peer_create(&pp, ppeer); + CURL_TRC_M(data, "connect-to peer_create2 -> %d", (int)result); + +out: + CURL_TRC_M(data, "parse connect_to peer: %s -> %d", connect_to, (int)result); + peer_parse_clear(&pp); + return result; +} + +#ifndef CURL_DISABLE_PROXY + +#ifdef USE_UNIX_SOCKETS +#define UNIX_SOCKET_PREFIX "localhost" +#endif + +CURLcode Curl_scheme_to_proxytype(struct Curl_easy *data, + const char *scheme, + uint8_t *proxytype, const char *url) +{ + if(!scheme) + return CURLE_OK; + + if(curl_strequal("https", scheme)) { + if(*proxytype != CURLPROXY_HTTPS2 && *proxytype != CURLPROXY_HTTPS3) + *proxytype = CURLPROXY_HTTPS; + } + else if(curl_strequal("socks5h", scheme)) + *proxytype = CURLPROXY_SOCKS5_HOSTNAME; + else if(curl_strequal("socks5", scheme)) + *proxytype = CURLPROXY_SOCKS5; + else if(curl_strequal("socks4a", scheme)) + *proxytype = CURLPROXY_SOCKS4A; + else if(curl_strequal("socks4", scheme) || curl_strequal("socks", scheme)) + *proxytype = CURLPROXY_SOCKS4; + else if(curl_strequal("http", scheme)) { + if(*proxytype != CURLPROXY_HTTP_1_0) + *proxytype = CURLPROXY_HTTP; + } + else { + /* Any other xxx:// reject! */ + failf(data, "Unsupported proxy scheme for \'%s\'", url); + return CURLE_COULDNT_CONNECT; + } + return CURLE_OK; +} + +CURLcode Curl_peer_from_proxy_url(CURLU *uh, + struct Curl_easy *data, + const char *url, + uint8_t proxytype, + struct Curl_peer **ppeer, + uint8_t *pproxytype) +{ + struct peer_parse pp; + char *scheme = NULL; + char *portptr = NULL; +#ifdef USE_UNIX_SOCKETS + bool is_socks = FALSE; +#endif + CURLUcode uc; + CURLcode result = CURLE_OK; + + Curl_peer_unlink(ppeer); + memset(&pp, 0, sizeof(pp)); + pp.port = CURL_DEFAULT_PROXY_PORT; + uc = curl_url_get(uh, CURLUPART_SCHEME, &scheme, + CURLU_NON_SUPPORT_SCHEME | CURLU_NO_GUESS_SCHEME); + if(uc) { + if(uc == CURLUE_OUT_OF_MEMORY) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + /* URL came without scheme, the passed `proxytype` determines it */ + switch(proxytype) { + case CURLPROXY_HTTP: + case CURLPROXY_HTTP_1_0: + pp.scheme = &Curl_scheme_http; + break; + case CURLPROXY_HTTPS: + case CURLPROXY_HTTPS2: + case CURLPROXY_HTTPS3: + pp.scheme = &Curl_scheme_https; + break; + case CURLPROXY_SOCKS4: + pp.scheme = &Curl_scheme_socks4; + break; + case CURLPROXY_SOCKS4A: + pp.scheme = &Curl_scheme_socks4a; + break; + case CURLPROXY_SOCKS5: + pp.scheme = &Curl_scheme_socks5; + break; + case CURLPROXY_SOCKS5_HOSTNAME: + pp.scheme = &Curl_scheme_socks5h; + break; + default: + failf(data, "Unsupported proxy type %u for \'%s\'", proxytype, url); + result = CURLE_COULDNT_RESOLVE_PROXY; + goto out; + } + } + else { + pp.scheme = Curl_get_scheme(scheme); + result = Curl_scheme_to_proxytype(data, scheme, &proxytype, url); + if(result) + goto out; + } + DEBUGASSERT(pp.scheme); + + if(CURL_PROXY_IS_HTTPS(proxytype) && + !Curl_ssl_supports(data, SSLSUPP_HTTPS_PROXY)) { + failf(data, "Unsupported proxy \'%s\', libcurl is built without the " + "HTTPS-proxy support.", url); + result = CURLE_NOT_BUILT_IN; + goto out; + } + + switch(pp.scheme->family) { + case CURLPROTO_SOCKS: +#ifdef USE_UNIX_SOCKETS + is_socks = TRUE; +#endif + break; + case CURLPROTO_HTTP: + break; + default: + failf(data, "Unsupported proxy protocol for \'%s\'", url); + result = CURLE_COULDNT_CONNECT; + goto out; + } + + uc = curl_url_get(uh, CURLUPART_PORT, &portptr, CURLU_NO_DEFAULT_PORT); + if(uc == CURLUE_OUT_OF_MEMORY) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + if(portptr) { + curl_off_t num; + const char *p = portptr; + if(!curlx_str_number(&p, &num, UINT16_MAX)) + pp.port = (uint16_t)num; + /* Should we not error out when the port number is invalid? */ + curlx_free(portptr); + } + else { + /* No port in URL, take the set one or the scheme's default */ + if(data->set.proxyport) + pp.port = data->set.proxyport; + else + pp.port = pp.scheme->defport; + } + + /* now, clone the proxy hostname */ + uc = curl_url_get(uh, CURLUPART_HOST, &pp.tmp_host_user, CURLU_URLDECODE); + if(uc) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + pp.host_user.str = pp.tmp_host_user; + pp.host_user.len = strlen(pp.tmp_host_user); + +#ifdef USE_UNIX_SOCKETS + if(is_socks && curl_strequal(UNIX_SOCKET_PREFIX, pp.tmp_host_user)) { + uc = curl_url_get(uh, CURLUPART_PATH, &pp.tmp_host, CURLU_URLDECODE); + if(uc) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + /* path will be "/", if no path was found */ + if(strcmp("/", pp.tmp_host)) { + pp.host.str = pp.tmp_host; + pp.host.len = strlen(pp.tmp_host); + pp.unix_socket = TRUE; + } + else { + pp.host = pp.host_user; + } + } +#endif /* USE_UNIX_SOCKETS */ + + if(!pp.host.len) { + result = peer_parse_host(data, &pp, FALSE); + if(result) + goto out; + } + + uc = curl_url_get(uh, CURLUPART_ZONEID, &pp.tmp_zoneid, 0); + if(uc == CURLUE_OUT_OF_MEMORY) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + if(pp.tmp_zoneid) { + pp.zoneid.str = pp.tmp_zoneid; + pp.zoneid.len = strlen(pp.tmp_zoneid); + } + + *pproxytype = proxytype; + result = peer_create(&pp, ppeer); + +out: + peer_parse_clear(&pp); + curlx_free(scheme); +#ifdef DEBUGBUILD + if(!result) + DEBUGASSERT(*ppeer); +#endif + return result; +} + +#endif /* !CURL_DISABLE_PROXY */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/peer.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/peer.h new file mode 100644 index 0000000000..a0a3054cd8 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/peer.h @@ -0,0 +1,108 @@ +#ifndef HEADER_CURL_PEER_H +#define HEADER_CURL_PEER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +struct Curl_scheme; + +/* if peer hostname starts with this, the peer is a unix domain socket + * path, e.g. the remainder after 'localhost'. */ +#define CURL_PEER_UDS_PREFIX "localhost/" + +struct Curl_peer { + const struct Curl_scheme *scheme; /* url scheme */ + char *hostname; /* normalized hostname (IDN decoded when supported) */ + char *zoneid; /* NULL or IPv6 zone identifier */ + uint32_t refcount; /* created with 1, freed when dropping to 0 */ + uint32_t scopeid; /* != 0, IPv6 scope to use */ + uint16_t port; + BIT(unix_socket); /* hostname is a UDS path without the prefix */ + BIT(abstract_uds); /* only TRUE when `unix_socket` also TRUE */ + BIT(ipv6); /* hostname is an IPv6 address stripped of '[]' */ + char user_hostname[1]; /* hostname supplied by user/url */ +}; + +/* Create a new peer: + * - `peer->user_hostname` is the passed `hostname` + * - `peer->hostname` is the normalized `hostname` via + * + IDN conversion if it has non-ASCII characters + * + stripping of surrounding '[]' for URL formatted IPv6 addresses + * + the path alone in case of a unix domain socket, e.g. hostname + * starts with CURL_PEER_UDS_PREFIX and is longer + * Scans for IPv6 addresses even without surrounding '[]'. + * - `zoneid` IPv6 zone identifier or NULL + * - `scopeid` IPv6 scopeid of zoneid, when known. + */ +CURLcode Curl_peer_create(struct Curl_easy *data, + const struct Curl_scheme *scheme, + const char *hostname, + uint16_t port, + struct Curl_peer **ppeer); + +#ifdef USE_UNIX_SOCKETS +CURLcode Curl_peer_uds_create(const struct Curl_scheme *scheme, + const char *path, + bool abstract_unix_socket, + struct Curl_peer **ppeer); +#endif + +/* Unlink any peer in `*pdest`, assign src, increase src + * refcount when not NULL. */ +void Curl_peer_link(struct Curl_peer **pdest, struct Curl_peer *src); + +/* Drop a reference, peer may be passed as NULL */ +void Curl_peer_unlink(struct Curl_peer **ppeer); + +/* TRUE if both peers are NULL or have completely same properties. */ +bool Curl_peer_equal(struct Curl_peer *p1, struct Curl_peer *p2); + +/* TRUE if both peers are NULL or have same properties except the scheme. */ +bool Curl_peer_same_destination(struct Curl_peer *p1, struct Curl_peer *p2); + +CURLcode Curl_peer_from_url(CURLU *uh, struct Curl_easy *data, + uint16_t port_override, + uint32_t scopeid_override, + struct Curl_peer **ppeer); + +CURLcode Curl_peer_from_connect_to(struct Curl_easy *data, + const struct Curl_peer *dest, + const char *connect_to, + struct Curl_peer **ppeer); + +#ifndef CURL_DISABLE_PROXY + +CURLcode Curl_scheme_to_proxytype(struct Curl_easy *data, + const char *scheme, + uint8_t *proxytype, + const char *url); + +CURLcode Curl_peer_from_proxy_url(CURLU *uh, + struct Curl_easy *data, + const char *url, + uint8_t proxytype, + struct Curl_peer **ppeer, + uint8_t *pproxytype); +#endif /* !CURL_DISABLE_PROXY */ + +#endif /* HEADER_CURL_PEER_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/pingpong.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/pingpong.c new file mode 100644 index 0000000000..b365772fb7 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/pingpong.c @@ -0,0 +1,412 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * 'pingpong' is for generic back-and-forth support functions used by FTP, + * IMAP, POP3, SMTP and whatever more that likes them. + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "pingpong.h" + +#ifdef USE_PINGPONG + +#include "cfilters.h" +#include "connect.h" +#include "multiif.h" +#include "sendf.h" +#include "curl_trc.h" +#include "select.h" +#include "progress.h" + +timediff_t Curl_pp_state_timeleft_ms(struct Curl_easy *data, + struct pingpong *pp) +{ + timediff_t xfer_remain_ms; + timediff_t remain_ms = data->set.server_response_timeout ? + data->set.server_response_timeout : PINGPONG_TIMEOUT_MS; + + /* If the overall transfer has less time remaining than pingpong + * has otherwise for the state, return that. */ + remain_ms -= curlx_ptimediff_ms(Curl_pgrs_now(data), &pp->response); + /* transfer remaining time is 0, when it has no timeout. */ + xfer_remain_ms = Curl_timeleft_ms(data); + if(xfer_remain_ms) + return CURLMIN(remain_ms, xfer_remain_ms); + return remain_ms; +} + +/* + * Curl_pp_statemach() + */ +CURLcode Curl_pp_statemach(struct Curl_easy *data, + struct pingpong *pp, bool block, + bool disconnecting) +{ + struct connectdata *conn = data->conn; + curl_socket_t sock = conn->sock[FIRSTSOCKET]; + int rc; + timediff_t interval_ms; + timediff_t timeout_ms = Curl_pp_state_timeleft_ms(data, pp); + CURLcode result = CURLE_OK; + + if(timeout_ms <= 0) { + failf(data, "server response timeout"); + return CURLE_OPERATION_TIMEDOUT; /* already too little time */ + } + + if(block) { + interval_ms = 1000; /* use 1 second timeout intervals */ + if(timeout_ms < interval_ms) + interval_ms = timeout_ms; + } + else + interval_ms = 0; /* immediate */ + + if(Curl_conn_data_pending(data, FIRSTSOCKET)) + rc = 1; + else if(pp->overflow) + /* We are receiving and there is data in the cache so read it */ + rc = 1; + else if(!pp->sendleft && Curl_conn_data_pending(data, FIRSTSOCKET)) + /* We are receiving and there is data ready in the SSL library */ + rc = 1; + else { + rc = Curl_socket_check(pp->sendleft ? CURL_SOCKET_BAD : sock, /* reading */ + CURL_SOCKET_BAD, + pp->sendleft ? sock : CURL_SOCKET_BAD, /* writing */ + interval_ms); + } + + if(block) { + /* if we did not wait, we do not have to spend time on this now */ + result = Curl_pgrsCheck(data); + if(result) + return result; + } + + if(rc == -1) { + failf(data, "select/poll error"); + result = CURLE_OUT_OF_MEMORY; + } + else if(rc) + result = pp->statemachine(data, data->conn); + else if(disconnecting) + return CURLE_OPERATION_TIMEDOUT; + + return result; +} + +/* initialize stuff to prepare for reading a fresh new response */ +void Curl_pp_init(struct pingpong *pp, const struct curltime *pnow) +{ + DEBUGASSERT(!pp->initialized); + pp->nread_resp = 0; + pp->response = *pnow; /* start response time-out */ + pp->pending_resp = TRUE; + curlx_dyn_init(&pp->sendbuf, DYN_PINGPPONG_CMD); + curlx_dyn_init(&pp->recvbuf, DYN_PINGPPONG_CMD); + pp->initialized = TRUE; +} + +/*********************************************************************** + * + * Curl_pp_vsendf() + * + * Send the formatted string as a command to a pingpong server. Note that + * the string should not have any CRLF appended, as this function will + * append the necessary things itself. + * + * made to never block + */ +CURLcode Curl_pp_vsendf(struct Curl_easy *data, + struct pingpong *pp, + const char *fmt, + va_list args) +{ + size_t bytes_written = 0; + size_t write_len; + char *s; + CURLcode result; + struct connectdata *conn = data->conn; + + DEBUGASSERT(pp->sendleft == 0); + DEBUGASSERT(pp->sendsize == 0); + DEBUGASSERT(!pp->sendthis); + + if(!conn) + /* cannot send without a connection! */ + return CURLE_SEND_ERROR; + + curlx_dyn_reset(&pp->sendbuf); + result = curlx_dyn_vaddf(&pp->sendbuf, fmt, args); + if(result) + return result; + + /* append CRLF */ + result = curlx_dyn_addn(&pp->sendbuf, "\r\n", 2); + if(result) + return result; + + pp->pending_resp = TRUE; + write_len = curlx_dyn_len(&pp->sendbuf); + s = curlx_dyn_ptr(&pp->sendbuf); + + result = Curl_conn_send(data, FIRSTSOCKET, s, write_len, FALSE, + &bytes_written); + if(result == CURLE_AGAIN) { + bytes_written = 0; + } + else if(result) + return result; + + Curl_debug(data, CURLINFO_HEADER_OUT, s, bytes_written); + + if(bytes_written != write_len) { + /* the whole chunk was not sent, keep it around and adjust sizes */ + pp->sendthis = s; + pp->sendsize = write_len; + pp->sendleft = write_len - bytes_written; + } + else { + pp->sendthis = NULL; + pp->sendleft = pp->sendsize = 0; + pp->response = *Curl_pgrs_now(data); + } + + return CURLE_OK; +} + +/*********************************************************************** + * + * Curl_pp_sendf() + * + * Send the formatted string as a command to a pingpong server. Note that + * the string should not have any CRLF appended, as this function will + * append the necessary things itself. + * + * made to never block + */ +CURLcode Curl_pp_sendf(struct Curl_easy *data, struct pingpong *pp, + const char *fmt, ...) +{ + CURLcode result; + va_list ap; + va_start(ap, fmt); + + result = Curl_pp_vsendf(data, pp, fmt, ap); + + va_end(ap); + + return result; +} + +static CURLcode pingpong_read(struct Curl_easy *data, + int8_t sockindex, + char *buffer, + size_t buflen, + size_t *nread) +{ + return Curl_conn_recv(data, sockindex, buffer, buflen, nread); +} + +/* + * Curl_pp_readresp() + * + * Reads a piece of a server response. + */ +CURLcode Curl_pp_readresp(struct Curl_easy *data, + int8_t sockindex, + struct pingpong *pp, + int *code, /* return the server code if done */ + size_t *size) /* size of the response */ +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + size_t gotbytes; + char buffer[900]; + + *code = 0; /* 0 for errors or not done */ + *size = 0; + + do { + gotbytes = 0; + if(pp->nfinal) { + /* a previous call left this many bytes in the beginning of the buffer as + that was the final line; now ditch that */ + size_t full = curlx_dyn_len(&pp->recvbuf); + + /* trim off the "final" leading part */ + curlx_dyn_tail(&pp->recvbuf, full - pp->nfinal); + + pp->nfinal = 0; /* now gone */ + } + if(!pp->overflow) { + result = pingpong_read(data, sockindex, buffer, sizeof(buffer), + &gotbytes); + if(result == CURLE_AGAIN) + return CURLE_OK; + + if(result) + return result; + + if(!gotbytes) { + failf(data, "response reading failed (errno: %d)", SOCKERRNO); + return CURLE_RECV_ERROR; + } + + result = curlx_dyn_addn(&pp->recvbuf, buffer, gotbytes); + if(result) + return result; + + data->req.headerbytecount += (unsigned int)gotbytes; + + pp->nread_resp += gotbytes; + } + + do { + const char *line = curlx_dyn_ptr(&pp->recvbuf); + const char *nl = memchr(line, '\n', curlx_dyn_len(&pp->recvbuf)); + if(nl) { + /* a newline is CRLF in pp-talk, so the CR is ignored as + the line is not really terminated until the LF comes */ + size_t length = nl - line + 1; + + if(memchr(line, 0, length)) { + /* The response line is passed on as a "header" below, so reject an + embedded nul the same way verify_header() does for HTTP. */ + failf(data, "Nul byte in server response line"); + return CURLE_WEIRD_SERVER_REPLY; + } + + /* output debug output if that is requested */ + Curl_debug(data, CURLINFO_HEADER_IN, line, length); + + /* + * Pass all response-lines to the callback function registered for + * "headers". The response lines can be seen as a kind of headers. + */ + result = Curl_client_write(data, CLIENTWRITE_INFO, line, length); + if(result) + return result; + + if(pp->endofresp(data, conn, line, length, code)) { + /* When at "end of response", keep the endofresp line first in the + buffer since it will be accessed outside (by pingpong + parsers). Store the overflow counter to inform about additional + data in this buffer after the endofresp line. */ + pp->nfinal = length; + if(curlx_dyn_len(&pp->recvbuf) > length) + pp->overflow = curlx_dyn_len(&pp->recvbuf) - length; + else + pp->overflow = 0; + *size = pp->nread_resp; /* size of the response */ + pp->nread_resp = 0; /* restart */ + gotbytes = 0; /* force break out of outer loop */ + break; + } + if(curlx_dyn_len(&pp->recvbuf) > length) + /* keep the remaining piece */ + curlx_dyn_tail((&pp->recvbuf), curlx_dyn_len(&pp->recvbuf) - length); + else + curlx_dyn_reset(&pp->recvbuf); + } + else { + /* without a newline, there is no overflow */ + pp->overflow = 0; + break; + } + + } while(1); /* while there is buffer left to scan */ + + } while(gotbytes == sizeof(buffer)); + + pp->pending_resp = FALSE; + + return result; +} + +CURLcode Curl_pp_pollset(struct Curl_easy *data, + struct pingpong *pp, + struct easy_pollset *ps) +{ + int flags = pp->sendleft ? CURL_POLL_OUT : CURL_POLL_IN; + return Curl_pollset_change(data, ps, data->conn->sock[FIRSTSOCKET], + flags, 0); +} + +bool Curl_pp_needs_flush(struct Curl_easy *data, + struct pingpong *pp) +{ + (void)data; + return pp->sendleft > 0; +} + +CURLcode Curl_pp_flushsend(struct Curl_easy *data, + struct pingpong *pp) +{ + /* we have a piece of a command still left to send */ + size_t written; + CURLcode result; + + if(!Curl_pp_needs_flush(data, pp)) + return CURLE_OK; + + result = Curl_conn_send(data, FIRSTSOCKET, + pp->sendthis + pp->sendsize - pp->sendleft, + pp->sendleft, FALSE, &written); + if(result == CURLE_AGAIN) { + result = CURLE_OK; + written = 0; + } + if(result) + return result; + + if(written != pp->sendleft) { + /* only a fraction was sent */ + pp->sendleft -= written; + } + else { + pp->sendthis = NULL; + pp->sendleft = pp->sendsize = 0; + pp->response = *Curl_pgrs_now(data); + } + return CURLE_OK; +} + +CURLcode Curl_pp_disconnect(struct pingpong *pp) +{ + if(pp->initialized) { + curlx_dyn_free(&pp->sendbuf); + curlx_dyn_free(&pp->recvbuf); + memset(pp, 0, sizeof(*pp)); + } + return CURLE_OK; +} + +bool Curl_pp_moredata(struct pingpong *pp) +{ + return !pp->sendleft && curlx_dyn_len(&pp->recvbuf) > pp->nfinal; +} + +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/pingpong.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/pingpong.h new file mode 100644 index 0000000000..09dca414eb --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/pingpong.h @@ -0,0 +1,162 @@ +#ifndef HEADER_CURL_PINGPONG_H +#define HEADER_CURL_PINGPONG_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_FTP) || \ + !defined(CURL_DISABLE_POP3) || !defined(CURL_DISABLE_SMTP) +#define USE_PINGPONG +#endif + +/* forward-declaration, this is defined in urldata.h */ +struct connectdata; + +typedef enum { + PPTRANSFER_BODY, /* yes do transfer a body */ + PPTRANSFER_INFO, /* do still go through to get info/headers */ + PPTRANSFER_NONE /* do not get anything and do not get info */ +} curl_pp_transfer; + +/* + * 'pingpong' is the generic struct used for protocols doing server<->client + * conversations in a back-and-forth style such as FTP, IMAP, POP3, SMTP etc. + * + * It holds response cache and non-blocking sending data. + */ +struct pingpong { + size_t nread_resp; /* number of bytes currently read of a server response */ + char *sendthis; /* pointer to a buffer that is to be sent to the server */ + size_t sendleft; /* number of bytes left to send from the sendthis buffer */ + size_t sendsize; /* total size of the sendthis buffer */ + struct curltime response; /* set to Curl_now() when a command has been sent + off, used to time-out response reading */ + struct dynbuf sendbuf; + struct dynbuf recvbuf; + size_t overflow; /* number of bytes left after a final response line */ + size_t nfinal; /* number of bytes in the final response line, which + after a match is first in the receive buffer */ + + /* Function pointers the protocols MUST implement and provide for the + pingpong layer to function */ + + CURLcode (*statemachine)(struct Curl_easy *data, struct connectdata *conn); + bool (*endofresp)(struct Curl_easy *data, struct connectdata *conn, + const char *ptr, size_t len, int *code); + BIT(initialized); + BIT(pending_resp); /* set TRUE when a server response is pending or in + progress, and is cleared once the last response is + read */ +}; + +/* Default pingpong response timeout in milliseconds, unless a transfer + * has CURLOPT_SERVER_RESPONSE_TIMEOUT(_MS) set. */ +#define PINGPONG_TIMEOUT_MS (60 * 1000) + +#define PINGPONG_SETUP(pp, s, e) \ + do { \ + (pp)->statemachine = s; \ + (pp)->endofresp = e; \ + } while(0) + +/* + * Curl_pp_statemach() + * + * called repeatedly until done. Set 'wait' to make it wait a while on the + * socket if there is no traffic. + */ +CURLcode Curl_pp_statemach(struct Curl_easy *data, struct pingpong *pp, + bool block, bool disconnecting); + +/* initialize stuff to prepare for reading a fresh new response */ +void Curl_pp_init(struct pingpong *pp, const struct curltime *pnow); + +/* Returns time remaining in ms. 0 or negative number means the + timeout has already triggered */ +timediff_t Curl_pp_state_timeleft_ms(struct Curl_easy *data, + struct pingpong *pp); + +/*********************************************************************** + * + * Curl_pp_sendf() + * + * Send the formatted string as a command to a pingpong server. Note that + * the string should not have any CRLF appended, as this function will + * append the necessary things itself. + * + * made to never block + */ +CURLcode Curl_pp_sendf(struct Curl_easy *data, + struct pingpong *pp, + const char *fmt, ...) CURL_PRINTF(3, 4); + +/*********************************************************************** + * + * Curl_pp_vsendf() + * + * Send the formatted string as a command to a pingpong server. Note that + * the string should not have any CRLF appended, as this function will + * append the necessary things itself. + * + * made to never block + */ +CURLcode Curl_pp_vsendf(struct Curl_easy *data, + struct pingpong *pp, + const char *fmt, + va_list args) CURL_PRINTF(3, 0); + +/* + * Curl_pp_readresp() + * + * Reads a piece of a server response. + */ +CURLcode Curl_pp_readresp(struct Curl_easy *data, + int8_t sockindex, + struct pingpong *pp, + int *code, /* return the server code if done */ + size_t *size); /* size of the response */ + +bool Curl_pp_needs_flush(struct Curl_easy *data, + struct pingpong *pp); + +CURLcode Curl_pp_flushsend(struct Curl_easy *data, + struct pingpong *pp); + +/* call this when a pingpong connection is disconnected */ +CURLcode Curl_pp_disconnect(struct pingpong *pp); + +CURLcode Curl_pp_pollset(struct Curl_easy *data, + struct pingpong *pp, + struct easy_pollset *ps); + +/*********************************************************************** + * + * Curl_pp_moredata() + * + * Returns whether there are still more data in the cache and so a call + * to Curl_pp_readresp() will not block. + */ +bool Curl_pp_moredata(struct pingpong *pp); + +#endif /* HEADER_CURL_PINGPONG_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/pop3.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/pop3.c new file mode 100644 index 0000000000..b32663ce14 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/pop3.c @@ -0,0 +1,1718 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC1734 POP3 Authentication + * RFC1939 POP3 protocol + * RFC2195 CRAM-MD5 authentication + * RFC2384 POP URL Scheme + * RFC2449 POP3 Extension Mechanism + * RFC2595 Using TLS with IMAP, POP3 and ACAP + * RFC2831 DIGEST-MD5 authentication + * RFC4422 Simple Authentication and Security Layer (SASL) + * RFC4616 PLAIN authentication + * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism + * RFC5034 POP3 SASL Authentication Mechanism + * RFC6749 OAuth 2.0 Authorization Framework + * RFC8314 Use of TLS for Email Submission and Access + * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt> + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" +#include "pop3.h" + +#ifndef CURL_DISABLE_POP3 + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include "sendf.h" +#include "curl_trc.h" +#include "progress.h" +#include "transfer.h" +#include "escape.h" +#include "pingpong.h" +#include "vtls/vtls.h" +#include "cfilters.h" +#include "connect.h" +#include "select.h" +#include "url.h" +#include "bufref.h" +#include "curl_sasl.h" +#include "curl_md5.h" +#include "curlx/strdup.h" + +/* Authentication type flags */ +#define POP3_TYPE_CLEARTEXT (1 << 0) +#define POP3_TYPE_APOP (1 << 1) +#define POP3_TYPE_SASL (1 << 2) + +/* Authentication type values */ +#define POP3_TYPE_NONE 0 +#define POP3_TYPE_ANY (POP3_TYPE_CLEARTEXT | POP3_TYPE_APOP | POP3_TYPE_SASL) + +/* This is the 5-bytes End-Of-Body marker for POP3 */ +#define POP3_EOB "\x0d\x0a\x2e\x0d\x0a" +#define POP3_EOB_LEN 5 + +/* meta key for storing protocol meta at easy handle */ +#define CURL_META_POP3_EASY "meta:proto:pop3:easy" +/* meta key for storing protocol meta at connection */ +#define CURL_META_POP3_CONN "meta:proto:pop3:conn" + +/* + * POP3 easy handle state + */ +struct POP3 { + curl_pp_transfer transfer; + char *id; /* Message ID */ + char *custom; /* Custom Request */ +}; + +/* + * POP3 connection state + */ +typedef enum { + POP3_STOP, /* do nothing state, stops the state machine */ + POP3_SERVERGREET, /* waiting for the initial greeting immediately after + a connect */ + POP3_CAPA, + POP3_STARTTLS, + POP3_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS + (multi mode only) */ + POP3_AUTH, + POP3_APOP, + POP3_USER, + POP3_PASS, + POP3_COMMAND, + POP3_QUIT, + POP3_LAST /* never used */ +} pop3state; + +struct pop3_conn { + struct pingpong pp; + pop3state state; /* Always use pop3.c:state() to change state! */ + size_t eob; /* Number of bytes of the EOB (End Of Body) that + have been received so far */ + size_t strip; /* Number of bytes from the start to ignore as + non-body */ + struct SASL sasl; /* SASL-related storage */ + char *apoptimestamp; /* APOP timestamp from the server greeting */ + unsigned char authtypes; /* Accepted authentication types */ + unsigned char preftype; /* Preferred authentication type */ + BIT(ssldone); /* Is connect() over SSL done? */ + BIT(tls_supported); /* StartTLS capability supported by server */ +}; + +struct pop3_cmd { + const char *name; + unsigned short nlen; + BIT(multiline); /* response is multi-line with last '.' line */ + BIT(multiline_with_args); /* is multi-line when command has args */ +}; + +static const struct pop3_cmd pop3cmds[] = { + { "APOP", 4, FALSE, FALSE }, + { "AUTH", 4, FALSE, FALSE }, + { "CAPA", 4, TRUE, TRUE }, + { "DELE", 4, FALSE, FALSE }, + { "LIST", 4, TRUE, FALSE }, + { "MSG", 3, TRUE, TRUE }, + { "NOOP", 4, FALSE, FALSE }, + { "PASS", 4, FALSE, FALSE }, + { "QUIT", 4, FALSE, FALSE }, + { "RETR", 4, TRUE, TRUE }, + { "RSET", 4, FALSE, FALSE }, + { "STAT", 4, FALSE, FALSE }, + { "STLS", 4, FALSE, FALSE }, + { "TOP", 3, TRUE, TRUE }, + { "UIDL", 4, TRUE, FALSE }, + { "USER", 4, FALSE, FALSE }, + { "UTF8", 4, FALSE, FALSE }, + { "XTND", 4, TRUE, TRUE }, +}; + +/*********************************************************************** + * + * pop3_parse_url_options() + * + * Parse the URL login options. + */ +static CURLcode pop3_parse_url_options(struct connectdata *conn) +{ + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + CURLcode result = CURLE_OK; + const char *ptr = conn->options; + + if(!pop3c) + return CURLE_FAILED_INIT; + + while(!result && ptr && *ptr) { + const char *key = ptr; + const char *value; + + while(*ptr && *ptr != '=') + ptr++; + + value = ptr + 1; + + while(*ptr && *ptr != ';') + ptr++; + + if(curl_strnequal(key, "AUTH=", 5)) { + result = Curl_sasl_parse_url_auth_option(&pop3c->sasl, + value, ptr - value); + + if(result && curl_strnequal(value, "+APOP", ptr - value)) { + pop3c->preftype = POP3_TYPE_APOP; + pop3c->sasl.prefmech = SASL_AUTH_NONE; + result = CURLE_OK; + } + } + else + result = CURLE_URL_MALFORMAT; + + if(*ptr == ';') + ptr++; + } + + if(pop3c->preftype != POP3_TYPE_APOP) + switch(pop3c->sasl.prefmech) { + case SASL_AUTH_NONE: + pop3c->preftype = POP3_TYPE_NONE; + break; + case SASL_AUTH_DEFAULT: + pop3c->preftype = POP3_TYPE_ANY; + break; + default: + pop3c->preftype = POP3_TYPE_SASL; + break; + } + + return result; +} + +/*********************************************************************** + * + * pop3_parse_url_path() + * + * Parse the URL path into separate path components. + */ +static CURLcode pop3_parse_url_path(struct Curl_easy *data) +{ + /* The POP3 struct is already initialized in pop3_connect() */ + struct POP3 *pop3 = Curl_meta_get(data, CURL_META_POP3_EASY); + const char *path = &data->state.up.path[1]; /* skip leading path */ + + if(!pop3) + return CURLE_FAILED_INIT; + /* URL decode the path for the message ID */ + return Curl_urldecode(path, 0, &pop3->id, NULL, REJECT_CTRL); +} + +/*********************************************************************** + * + * pop3_parse_custom_request() + * + * Parse the custom request. + */ +static CURLcode pop3_parse_custom_request(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct POP3 *pop3 = Curl_meta_get(data, CURL_META_POP3_EASY); + const char *custom = CURL_EASY_STR(data, STRING_CUSTOMREQUEST); + + if(!pop3) + return CURLE_FAILED_INIT; + /* URL decode the custom request */ + if(custom) + result = Curl_urldecode(custom, 0, &pop3->custom, NULL, REJECT_CTRL); + + return result; +} + +/* Return iff a command is defined as "multi-line" (RFC 1939), + * has a response terminated by a last line with a '.'. + */ +static bool pop3_is_multiline(const char *cmdline) +{ + size_t i; + for(i = 0; i < CURL_ARRAYSIZE(pop3cmds); ++i) { + if(curl_strnequal(pop3cmds[i].name, cmdline, pop3cmds[i].nlen)) { + if(!cmdline[pop3cmds[i].nlen]) + return (bool)pop3cmds[i].multiline; + else if(cmdline[pop3cmds[i].nlen] == ' ') + return (bool)pop3cmds[i].multiline_with_args; + } + } + /* Unknown command, assume multi-line for backward compatibility with + * earlier curl versions that only could do multi-line responses. */ + return TRUE; +} + +/*********************************************************************** + * + * pop3_endofresp() + * + * Checks for an ending POP3 status code at the start of the given string, but + * also detects the APOP timestamp from the server greeting and various + * capabilities from the CAPA response including the supported authentication + * types and allowed SASL mechanisms. + */ +static bool pop3_endofresp(struct Curl_easy *data, struct connectdata *conn, + const char *line, size_t len, int *resp) +{ + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + (void)data; + DEBUGASSERT(pop3c); + if(!pop3c) /* internal error */ + return TRUE; + + /* Do we have an error response? */ + if(len >= 4 && !memcmp("-ERR", line, 4)) { + *resp = '-'; + + return TRUE; + } + + /* Are we processing CAPA command responses? */ + if(pop3c->state == POP3_CAPA) { + /* Do we have the terminating line? Per RFC 2449 this is a line + containing only a single dot */ + if((len == 3 && line[0] == '.' && line[1] == '\r') || + (len == 2 && line[0] == '.' && line[1] == '\n')) + /* Treat the response as a success */ + *resp = '+'; + else + /* Treat the response as an untagged continuation */ + *resp = '*'; + + return TRUE; + } + + /* Do we have a success response? */ + if(len >= 3 && !memcmp("+OK", line, 3)) { + *resp = '+'; + + return TRUE; + } + + /* Do we have a continuation response? */ + if(len >= 1 && line[0] == '+') { + *resp = '*'; + + return TRUE; + } + + return FALSE; /* Nothing for us */ +} + +/*********************************************************************** + * + * pop3_get_message() + * + * Gets the authentication message from the response buffer. + */ +static CURLcode pop3_get_message(struct Curl_easy *data, struct bufref *out) +{ + struct pop3_conn *pop3c = + Curl_conn_meta_get(data->conn, CURL_META_POP3_CONN); + char *message; + size_t len; + + if(!pop3c) + return CURLE_FAILED_INIT; + message = curlx_dyn_ptr(&pop3c->pp.recvbuf); + len = pop3c->pp.nfinal; + if(len > 2) { + /* Find the start of the message */ + len -= 2; + for(message += 2; ISBLANK(*message); message++, len--) + ; + + /* Find the end of the message */ + while(len--) + if(!ISBLANK(message[len]) && !ISNEWLINE(message[len])) + break; + + /* Terminate the message */ + message[++len] = '\0'; + Curl_bufref_set(out, message, len, NULL); + } + else + /* junk input => zero length output */ + Curl_bufref_set(out, "", 0, NULL); + + return CURLE_OK; +} + +/*********************************************************************** + * + * pop3_state() + * + * This is the ONLY way to change POP3 state! + */ +static void pop3_state(struct Curl_easy *data, pop3state newstate) +{ + struct pop3_conn *pop3c = + Curl_conn_meta_get(data->conn, CURL_META_POP3_CONN); + if(pop3c) { +#if defined(DEBUGBUILD) && defined(CURLVERBOSE) + /* for debug purposes */ + static const char * const names[] = { + "STOP", + "SERVERGREET", + "CAPA", + "STARTTLS", + "UPGRADETLS", + "AUTH", + "APOP", + "USER", + "PASS", + "COMMAND", + "QUIT", + /* LAST */ + }; + + if(pop3c->state != newstate) + infof(data, "POP3 %p state change from %s to %s", + (void *)pop3c, names[pop3c->state], names[newstate]); +#endif + + pop3c->state = newstate; + } +} + +/*********************************************************************** + * + * pop3_perform_capa() + * + * Sends the CAPA command in order to obtain a list of server side supported + * capabilities. + */ +static CURLcode pop3_perform_capa(struct Curl_easy *data, + struct connectdata *conn) +{ + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + CURLcode result = CURLE_OK; + + if(!pop3c) + return CURLE_FAILED_INIT; + + pop3c->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanisms yet */ + pop3c->sasl.authused = SASL_AUTH_NONE; /* Clear the auth. mechanism used */ + pop3c->tls_supported = FALSE; /* Clear the TLS capability */ + + /* Send the CAPA command */ + result = Curl_pp_sendf(data, &pop3c->pp, "%s", "CAPA"); + + if(!result) + pop3_state(data, POP3_CAPA); + + return result; +} + +/*********************************************************************** + * + * pop3_perform_starttls() + * + * Sends the STLS command to start the upgrade to TLS. + */ +static CURLcode pop3_perform_starttls(struct Curl_easy *data, + struct connectdata *conn) +{ + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + CURLcode result; + + if(!pop3c) + return CURLE_FAILED_INIT; + + /* Send the STLS command */ + result = Curl_pp_sendf(data, &pop3c->pp, "%s", "STLS"); + if(!result) + pop3_state(data, POP3_STARTTLS); + + return result; +} + +/*********************************************************************** + * + * pop3_perform_upgrade_tls() + * + * Performs the upgrade to TLS. + */ +static CURLcode pop3_perform_upgrade_tls(struct Curl_easy *data, + struct connectdata *conn) +{ +#ifdef USE_SSL + /* Start the SSL connection */ + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + CURLcode result; + bool ssldone = FALSE; + + if(!pop3c) + return CURLE_FAILED_INIT; + + if(!Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + result = Curl_ssl_cfilter_add( + data, Curl_conn_get_origin(conn, FIRSTSOCKET), conn, FIRSTSOCKET); + if(result) + goto out; + /* Change the connection handler */ + conn->scheme = &Curl_scheme_pop3s; + } + + DEBUGASSERT(!pop3c->ssldone); + result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssldone); + DEBUGF(infof(data, "pop3_perform_upgrade_tls, connect -> %d, %d", + (int)result, ssldone)); + if(!result && ssldone) { + pop3c->ssldone = ssldone; + /* perform CAPA now, changes pop3c->state out of POP3_UPGRADETLS */ + result = pop3_perform_capa(data, conn); + } +out: + return result; +#else + (void)data; + (void)conn; + return CURLE_NOT_BUILT_IN; +#endif +} + +/*********************************************************************** + * + * pop3_perform_user() + * + * Sends a clear text USER command to authenticate with. + */ +static CURLcode pop3_perform_user(struct Curl_easy *data, + struct connectdata *conn) +{ + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + CURLcode result = CURLE_OK; + + if(!pop3c) + return CURLE_FAILED_INIT; + + /* Check we have a username and password to authenticate with and end the + connect phase if we do not */ + if(!conn->creds) { + pop3_state(data, POP3_STOP); + + return result; + } + + /* Send the USER command */ + result = Curl_pp_sendf(data, &pop3c->pp, "USER %s", + Curl_creds_user(conn->creds)); + if(!result) + pop3_state(data, POP3_USER); + + return result; +} + +#ifndef CURL_DISABLE_DIGEST_AUTH +/*********************************************************************** + * + * pop3_perform_apop() + * + * Sends an APOP command to authenticate with. + */ +static CURLcode pop3_perform_apop(struct Curl_easy *data, + struct connectdata *conn) +{ + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + CURLcode result = CURLE_OK; + size_t i; + struct MD5_context *ctxt; + unsigned char digest[MD5_DIGEST_LEN]; + char secret[(2 * MD5_DIGEST_LEN) + 1]; + + if(!pop3c) + return CURLE_FAILED_INIT; + + /* Check we have a username and password to authenticate with and end the + connect phase if we do not */ + if(!data->state.creds) { + pop3_state(data, POP3_STOP); + + return result; + } + + /* Create the digest */ + ctxt = Curl_MD5_init(&Curl_DIGEST_MD5); + if(!ctxt) + return CURLE_OUT_OF_MEMORY; + + Curl_MD5_update(ctxt, (const unsigned char *)pop3c->apoptimestamp, + curlx_uztoui(strlen(pop3c->apoptimestamp))); + + Curl_MD5_update(ctxt, (const unsigned char *)Curl_creds_passwd(conn->creds), + curlx_uztoui(strlen(Curl_creds_passwd(conn->creds)))); + + /* Finalise the digest */ + Curl_MD5_final(ctxt, digest); + + /* Convert the calculated 16 octet digest into a 32-byte hex string */ + for(i = 0; i < MD5_DIGEST_LEN; i++) + curl_msnprintf(&secret[2 * i], 3, "%02x", digest[i]); + + result = Curl_pp_sendf(data, &pop3c->pp, "APOP %s %s", + Curl_creds_user(conn->creds), secret); + + if(!result) + pop3_state(data, POP3_APOP); + + return result; +} +#endif + +/*********************************************************************** + * + * pop3_perform_auth() + * + * Sends an AUTH command allowing the client to login with the given SASL + * authentication mechanism. + */ +static CURLcode pop3_perform_auth(struct Curl_easy *data, + const char *mech, + const struct bufref *initresp) +{ + struct pop3_conn *pop3c = + Curl_conn_meta_get(data->conn, CURL_META_POP3_CONN); + CURLcode result = CURLE_OK; + const char *ir = Curl_bufref_ptr(initresp); + + if(!pop3c) + return CURLE_FAILED_INIT; + + if(ir) { /* AUTH <mech> ...<crlf> */ + /* Send the AUTH command with the initial response */ + result = Curl_pp_sendf(data, &pop3c->pp, "AUTH %s %s", + mech, *ir ? ir : "="); + } + else { + /* Send the AUTH command */ + result = Curl_pp_sendf(data, &pop3c->pp, "AUTH %s", mech); + } + + return result; +} + +/*********************************************************************** + * + * pop3_continue_auth() + * + * Sends SASL continuation data. + */ +static CURLcode pop3_continue_auth(struct Curl_easy *data, + const char *mech, + const struct bufref *resp) +{ + struct pop3_conn *pop3c = + Curl_conn_meta_get(data->conn, CURL_META_POP3_CONN); + + (void)mech; + if(!pop3c) + return CURLE_FAILED_INIT; + + return Curl_pp_sendf(data, &pop3c->pp, "%s", Curl_bufref_ptr(resp)); +} + +/*********************************************************************** + * + * pop3_cancel_auth() + * + * Sends SASL cancellation. + */ +static CURLcode pop3_cancel_auth(struct Curl_easy *data, const char *mech) +{ + struct pop3_conn *pop3c = + Curl_conn_meta_get(data->conn, CURL_META_POP3_CONN); + + (void)mech; + if(!pop3c) + return CURLE_FAILED_INIT; + + return Curl_pp_sendf(data, &pop3c->pp, "*"); +} + +/*********************************************************************** + * + * pop3_perform_authentication() + * + * Initiates the authentication sequence, with the appropriate SASL + * authentication mechanism, falling back to APOP and clear text should a + * common mechanism not be available between the client and server. + */ +static CURLcode pop3_perform_authentication(struct Curl_easy *data, + struct connectdata *conn) +{ + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + CURLcode result = CURLE_OK; + saslprogress progress = SASL_IDLE; + + if(!pop3c) + return CURLE_FAILED_INIT; + + /* Check we have enough data to authenticate with and end the + connect phase if we do not */ + if(!Curl_sasl_can_authenticate(&pop3c->sasl, data)) { + pop3_state(data, POP3_STOP); + return result; + } + + if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_SASL) { + /* Calculate the SASL login details */ + result = Curl_sasl_start(&pop3c->sasl, data, FALSE, &progress); + + if(!result) + if(progress == SASL_INPROGRESS) + pop3_state(data, POP3_AUTH); + } + + if(!result && progress == SASL_IDLE) { +#ifndef CURL_DISABLE_DIGEST_AUTH + if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_APOP) + /* Perform APOP authentication */ + result = pop3_perform_apop(data, conn); + else +#endif + if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_CLEARTEXT) + /* Perform clear text authentication */ + result = pop3_perform_user(data, conn); + else + result = Curl_sasl_is_blocked(&pop3c->sasl, data); + } + + return result; +} + +/*********************************************************************** + * + * pop3_perform_command() + * + * Sends a POP3 based command. + */ +static CURLcode pop3_perform_command(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct POP3 *pop3 = Curl_meta_get(data, CURL_META_POP3_EASY); + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + const char *command = NULL; + + if(!pop3 || !pop3c) + return CURLE_FAILED_INIT; + + /* Calculate the default command */ + if(pop3->id[0] == '\0' || data->set.list_only) { + command = "LIST"; + + if(pop3->id[0] != '\0') + /* Message specific LIST so skip the BODY transfer */ + pop3->transfer = PPTRANSFER_INFO; + } + else + command = "RETR"; + + if(pop3->custom && pop3->custom[0] != '\0') + command = pop3->custom; + + /* Send the command */ + if(pop3->id[0] != '\0') + result = Curl_pp_sendf(data, &pop3c->pp, "%s %s", command, pop3->id); + else + result = Curl_pp_sendf(data, &pop3c->pp, "%s", command); + + if(!result) { + pop3_state(data, POP3_COMMAND); + data->req.no_body = !pop3_is_multiline(command); + } + + return result; +} + +/*********************************************************************** + * + * pop3_perform_quit() + * + * Performs the quit action prior to sclose() be called. + */ +static CURLcode pop3_perform_quit(struct Curl_easy *data, + struct connectdata *conn) +{ + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + CURLcode result; + + if(!pop3c) + return CURLE_FAILED_INIT; + + /* Send the QUIT command */ + result = Curl_pp_sendf(data, &pop3c->pp, "%s", "QUIT"); + if(!result) + pop3_state(data, POP3_QUIT); + + return result; +} + +/* For the initial server greeting */ +static CURLcode pop3_state_servergreet_resp(struct Curl_easy *data, + int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + const char *line; + size_t len; + + (void)instate; + if(!pop3c) + return CURLE_FAILED_INIT; + + line = curlx_dyn_ptr(&pop3c->pp.recvbuf); + len = pop3c->pp.nfinal; + + if(pop3code != '+') { + failf(data, "Got unexpected pop3-server response"); + result = CURLE_WEIRD_SERVER_REPLY; + } + else if(len > 3) { + /* Does the server support APOP authentication? */ + const char *lt; + const char *gt = NULL; + + /* Look for the APOP timestamp */ + lt = memchr(line, '<', len); + if(lt) + /* search the remainder for '>' */ + gt = memchr(lt, '>', len - (lt - line)); + if(gt) { + /* the length of the timestamp, including the brackets */ + size_t timestamplen = gt - lt + 1; + const char *at = memchr(lt, '@', timestamplen); + /* If the timestamp does not contain '@' it is not (as required by + RFC-1939) conformant to the RFC-822 message id syntax, and we + therefore do not use APOP authentication. */ + if(at) { + /* dupe the timestamp */ + pop3c->apoptimestamp = curlx_memdup0(lt, timestamplen); + if(!pop3c->apoptimestamp) + return CURLE_OUT_OF_MEMORY; + /* Store the APOP capability */ + pop3c->authtypes |= POP3_TYPE_APOP; + } + } + + if(!result) + result = pop3_perform_capa(data, conn); + } + + return result; +} + +/* For CAPA responses */ +static CURLcode pop3_state_capa_resp(struct Curl_easy *data, int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + const char *line; + size_t len; + + (void)instate; + if(!pop3c) + return CURLE_FAILED_INIT; + + line = curlx_dyn_ptr(&pop3c->pp.recvbuf); + len = pop3c->pp.nfinal; + + /* Do we have an untagged continuation response? */ + if(pop3code == '*') { + /* Does the server support the STLS capability? */ + if(len >= 4 && curl_strnequal(line, "STLS", 4)) + pop3c->tls_supported = TRUE; + + /* Does the server support clear text authentication? */ + else if(len >= 4 && curl_strnequal(line, "USER", 4)) + pop3c->authtypes |= POP3_TYPE_CLEARTEXT; + + /* Does the server support SASL based authentication? */ + else if(len >= 5 && curl_strnequal(line, "SASL ", 5)) { + pop3c->authtypes |= POP3_TYPE_SASL; + + /* Advance past the SASL keyword */ + line += 5; + len -= 5; + + /* Loop through the data line */ + for(;;) { + size_t llen; + size_t wordlen = 0; + unsigned short mechbit; + + while(len && (ISBLANK(*line) || ISNEWLINE(*line))) { + line++; + len--; + } + + if(!len) + break; + + /* Extract the word */ + while(wordlen < len && !ISBLANK(line[wordlen]) && + !ISNEWLINE(line[wordlen])) + wordlen++; + + /* Test the word for a matching authentication mechanism */ + mechbit = Curl_sasl_decode_mech(line, wordlen, &llen); + if(mechbit && llen == wordlen) + pop3c->sasl.authmechs |= mechbit; + + line += wordlen; + len -= wordlen; + } + } + } + else { + /* Clear text is supported when CAPA is not recognised */ + if(pop3code != '+') + pop3c->authtypes |= POP3_TYPE_CLEARTEXT; + + if(!data->set.use_ssl || Curl_conn_is_ssl(conn, FIRSTSOCKET)) + result = pop3_perform_authentication(data, conn); + else if(pop3code == '+' && pop3c->tls_supported) + /* Switch to TLS connection now */ + result = pop3_perform_starttls(data, conn); + else if(data->set.use_ssl <= CURLUSESSL_TRY) + /* Fallback and carry on with authentication */ + result = pop3_perform_authentication(data, conn); + else { + failf(data, "STLS not supported."); + result = CURLE_USE_SSL_FAILED; + } + } + + return result; +} + +/* For STARTTLS responses */ +static CURLcode pop3_state_starttls_resp(struct Curl_easy *data, + struct connectdata *conn, + int pop3code, + pop3state instate) +{ + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + CURLcode result = CURLE_OK; + (void)instate; + + if(!pop3c) + return CURLE_FAILED_INIT; + + /* Pipelining in response is forbidden. */ + if(pop3c->pp.overflow) + return CURLE_WEIRD_SERVER_REPLY; + + if(pop3code != '+') { + if(data->set.use_ssl != CURLUSESSL_TRY) { + failf(data, "STARTTLS denied"); + result = CURLE_USE_SSL_FAILED; + } + else + result = pop3_perform_authentication(data, conn); + } + else + pop3_state(data, POP3_UPGRADETLS); + + return result; +} + +/* For SASL authentication responses */ +static CURLcode pop3_state_auth_resp(struct Curl_easy *data, + int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + saslprogress progress; + + (void)instate; + if(!pop3c) + return CURLE_FAILED_INIT; + + result = Curl_sasl_continue(&pop3c->sasl, data, pop3code, &progress); + if(!result) + switch(progress) { + case SASL_DONE: + pop3_state(data, POP3_STOP); /* Authenticated */ + break; + case SASL_IDLE: /* No mechanism left after cancellation */ +#ifndef CURL_DISABLE_DIGEST_AUTH + if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_APOP) + /* Perform APOP authentication */ + result = pop3_perform_apop(data, conn); + else +#endif + if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_CLEARTEXT) + /* Perform clear text authentication */ + result = pop3_perform_user(data, conn); + else { + failf(data, "Authentication cancelled"); + result = CURLE_LOGIN_DENIED; + } + break; + default: + break; + } + + return result; +} + +#ifndef CURL_DISABLE_DIGEST_AUTH +/* For APOP responses */ +static CURLcode pop3_state_apop_resp(struct Curl_easy *data, int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + (void)instate; + + if(pop3code != '+') { + failf(data, "Authentication failed: %d", pop3code); + result = CURLE_LOGIN_DENIED; + } + else + /* End of connect phase */ + pop3_state(data, POP3_STOP); + + return result; +} +#endif + +/* For USER responses */ +static CURLcode pop3_state_user_resp(struct Curl_easy *data, int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + (void)instate; + + if(!pop3c) + return CURLE_FAILED_INIT; + + if(pop3code != '+') { + failf(data, "Access denied. %c", pop3code); + result = CURLE_LOGIN_DENIED; + } + else + /* Send the PASS command */ + result = Curl_pp_sendf(data, &pop3c->pp, "PASS %s", + Curl_creds_passwd(conn->creds)); + if(!result) + pop3_state(data, POP3_PASS); + + return result; +} + +/* For PASS responses */ +static CURLcode pop3_state_pass_resp(struct Curl_easy *data, int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + (void)instate; + + if(pop3code != '+') { + failf(data, "Access denied. %c", pop3code); + result = CURLE_LOGIN_DENIED; + } + else + /* End of connect phase */ + pop3_state(data, POP3_STOP); + + return result; +} + +/*********************************************************************** + * + * pop3_write() + * + * This function scans the body after the end-of-body and writes everything + * until the end is found. + */ +static CURLcode pop3_write(struct Curl_easy *data, const char *str, + size_t nread, bool is_eos) +{ + /* This code could be made into a special function in the handler struct */ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + bool strip_dot = FALSE; + size_t last = 0; + size_t i; + (void)is_eos; + + if(!pop3c) + return CURLE_FAILED_INIT; + + /* Search through the buffer looking for the end-of-body marker which is + 5 bytes (0d 0a 2e 0d 0a). Note that a line starting with a dot matches + the eob so the server will have prefixed it with an extra dot which we + need to strip out. Additionally the marker could of course be spread out + over 5 different data chunks. */ + for(i = 0; i < nread; i++) { + size_t prev = pop3c->eob; + + switch(str[i]) { + case 0x0d: + if(pop3c->eob == 0) { + pop3c->eob++; + + if(i) { + /* Write out the body part that did not match */ + result = Curl_client_write(data, CLIENTWRITE_BODY, &str[last], + i - last); + + if(result) + return result; + + last = i; + } + } + else if(pop3c->eob == 3) + pop3c->eob++; + else + /* If the character match was not at position 0 or 3 then restart the + pattern matching */ + pop3c->eob = 1; + break; + + case 0x0a: + if(pop3c->eob == 1 || pop3c->eob == 4) + pop3c->eob++; + else + /* If the character match was not at position 1 or 4 then start the + search again */ + pop3c->eob = 0; + break; + + case 0x2e: + if(pop3c->eob == 2) + pop3c->eob++; + else if(pop3c->eob == 3) { + /* We have an extra dot after the CRLF which we need to strip off */ + strip_dot = TRUE; + pop3c->eob = 0; + } + else + /* If the character match was not at position 2 then start the search + again */ + pop3c->eob = 0; + break; + + default: + pop3c->eob = 0; + break; + } + + /* Did we have a partial match which has subsequently failed? */ + if(prev && prev >= pop3c->eob) { + /* Strip can only be non-zero for the first mismatch after CRLF and + then both prev and strip are equal and nothing will be output below */ + while(prev && pop3c->strip) { + prev--; + pop3c->strip--; + } + + if(prev) { + /* If the partial match was the CRLF and dot then only write the CRLF + as the server would have inserted the dot */ + if(strip_dot && prev - 1 > 0) { + result = Curl_client_write(data, CLIENTWRITE_BODY, POP3_EOB, + prev - 1); + } + else if(!strip_dot) { + result = Curl_client_write(data, CLIENTWRITE_BODY, POP3_EOB, + prev); + } + else { + result = CURLE_OK; + } + + if(result) + return result; + + last = i; + strip_dot = FALSE; + } + } + } + + if(pop3c->eob == POP3_EOB_LEN) { + /* We have a full match so the transfer is done, however we must transfer + the CRLF at the start of the EOB as this is considered to be part of the + message as per RFC-1939, sect. 3 */ + result = Curl_client_write(data, CLIENTWRITE_BODY, POP3_EOB, 2); + + CURL_REQ_CLEAR_RECV(data); + pop3c->eob = 0; + + return result; + } + + if(pop3c->eob) + /* While EOB is matching nothing should be output */ + return CURLE_OK; + + if(nread - last) { + result = Curl_client_write(data, CLIENTWRITE_BODY, &str[last], + nread - last); + } + + return result; +} + +/* For command responses */ +static CURLcode pop3_state_command_resp(struct Curl_easy *data, + int pop3code, + pop3state instate) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct POP3 *pop3 = Curl_meta_get(data, CURL_META_POP3_EASY); + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + struct pingpong *pp; + + (void)instate; + if(!pop3 || !pop3c) + return CURLE_FAILED_INIT; + + pp = &pop3c->pp; + if(pop3code != '+') { + pop3_state(data, POP3_STOP); + return CURLE_WEIRD_SERVER_REPLY; + } + + /* This 'OK' line ends with a CR LF pair which is the two first bytes of the + EOB string so count this is two matching bytes. This is necessary to make + the code detect the EOB if the only data than comes now is %2e CR LF like + when there is no body to return. */ + pop3c->eob = 2; + + /* Since this initial CR LF pair is not part of the actual body, we set + the strip counter here so that these bytes will not be delivered. */ + pop3c->strip = 2; + + if(pop3->transfer == PPTRANSFER_BODY) { + /* POP3 download */ + Curl_xfer_setup_recv(data, FIRSTSOCKET, -1); + + if(pp->overflow) { + /* The recv buffer contains data that is actually body content so send + it as such. Note that there may even be additional "headers" after + the body */ + + /* keep only the overflow */ + curlx_dyn_tail(&pp->recvbuf, pp->overflow); + pp->nfinal = 0; /* done */ + + if(!data->req.no_body) { + result = pop3_write(data, curlx_dyn_ptr(&pp->recvbuf), + curlx_dyn_len(&pp->recvbuf), FALSE); + if(result) + return result; + } + + /* reset the buffer */ + curlx_dyn_reset(&pp->recvbuf); + pp->overflow = 0; + } + } + else + pp->overflow = 0; + + /* End of DO phase */ + pop3_state(data, POP3_STOP); + + return result; +} + +static CURLcode pop3_statemachine(struct Curl_easy *data, + struct connectdata *conn) +{ + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + CURLcode result = CURLE_OK; + int pop3code; + struct pingpong *pp; + size_t nread = 0; + (void)data; + + if(!pop3c) + return CURLE_FAILED_INIT; + + pp = &pop3c->pp; + /* Busy upgrading the connection; right now all I/O is SSL/TLS, not POP3 */ +upgrade_tls: + if(pop3c->state == POP3_UPGRADETLS) { + result = pop3_perform_upgrade_tls(data, conn); + if(result || (pop3c->state == POP3_UPGRADETLS)) + return result; + } + + /* Flush any data that needs to be sent */ + if(pp->sendleft) + return Curl_pp_flushsend(data, pp); + + do { + /* Read the response from the server */ + result = Curl_pp_readresp(data, FIRSTSOCKET, pp, &pop3code, &nread); + if(result) + return result; + + if(!pop3code) + break; + + /* We have now received a full POP3 server response */ + switch(pop3c->state) { + case POP3_SERVERGREET: + result = pop3_state_servergreet_resp(data, pop3code, pop3c->state); + break; + + case POP3_CAPA: + result = pop3_state_capa_resp(data, pop3code, pop3c->state); + break; + + case POP3_STARTTLS: + result = pop3_state_starttls_resp(data, conn, pop3code, pop3c->state); + /* During UPGRADETLS, leave the read loop as we need to connect + * (e.g. TLS handshake) before we continue sending/receiving. */ + if(!result && (pop3c->state == POP3_UPGRADETLS)) + goto upgrade_tls; + break; + + case POP3_AUTH: + result = pop3_state_auth_resp(data, pop3code, pop3c->state); + break; + +#ifndef CURL_DISABLE_DIGEST_AUTH + case POP3_APOP: + result = pop3_state_apop_resp(data, pop3code, pop3c->state); + break; +#endif + + case POP3_USER: + result = pop3_state_user_resp(data, pop3code, pop3c->state); + break; + + case POP3_PASS: + result = pop3_state_pass_resp(data, pop3code, pop3c->state); + break; + + case POP3_COMMAND: + result = pop3_state_command_resp(data, pop3code, pop3c->state); + break; + + case POP3_QUIT: + pop3_state(data, POP3_STOP); + break; + + default: + /* internal error */ + pop3_state(data, POP3_STOP); + break; + } + } while(!result && pop3c->state != POP3_STOP && Curl_pp_moredata(pp)); + + return result; +} + +/* Called repeatedly until done from multi.c */ +static CURLcode pop3_multi_statemach(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + + if(!pop3c) + return CURLE_FAILED_INIT; + result = Curl_pp_statemach(data, &pop3c->pp, FALSE, FALSE); + *done = (pop3c->state == POP3_STOP); + + return result; +} + +static CURLcode pop3_block_statemach(struct Curl_easy *data, + struct connectdata *conn, + bool disconnecting) +{ + CURLcode result = CURLE_OK; + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + + if(!pop3c) + return CURLE_FAILED_INIT; + + while(pop3c->state != POP3_STOP && !result) + result = Curl_pp_statemach(data, &pop3c->pp, TRUE, disconnecting); + + return result; +} + +/* For the POP3 "protocol connect" and "doing" phases only */ +static CURLcode pop3_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct pop3_conn *pop3c = + Curl_conn_meta_get(data->conn, CURL_META_POP3_CONN); + return pop3c ? Curl_pp_pollset(data, &pop3c->pp, ps) : CURLE_OK; +} + +/* SASL parameters for the pop3 protocol */ +static const struct SASLproto saslpop3 = { + "pop", /* The service name */ + pop3_perform_auth, /* Send authentication command */ + pop3_continue_auth, /* Send authentication continuation */ + pop3_cancel_auth, /* Send authentication cancellation */ + pop3_get_message, /* Get SASL response message */ + 255 - 8, /* Max line len - strlen("AUTH ") - 1 space - CRLF */ + '*', /* Code received when continuation is expected */ + '+', /* Code to receive upon authentication success */ + SASL_AUTH_DEFAULT, /* Default mechanisms */ + SASL_FLAG_BASE64 /* Configuration flags */ +}; + +/*********************************************************************** + * + * pop3_connect() + * + * This function should do everything that is to be considered a part of the + * connection phase. + * + * The variable 'done' points to will be TRUE if the protocol-layer connect + * phase is done when this function returns, or FALSE if not. + */ +static CURLcode pop3_connect(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + struct pingpong *pp = pop3c ? &pop3c->pp : NULL; + + *done = FALSE; /* default to not done yet */ + if(!pop3c) + return CURLE_FAILED_INIT; + + PINGPONG_SETUP(pp, pop3_statemachine, pop3_endofresp); + + /* Set the default preferred authentication type and mechanism */ + pop3c->preftype = POP3_TYPE_ANY; + Curl_sasl_init(&pop3c->sasl, data, &saslpop3); + + /* Initialize the pingpong layer */ + Curl_pp_init(pp, Curl_pgrs_now(data)); + + /* Parse the URL options */ + result = pop3_parse_url_options(conn); + if(result) + return result; + + /* Start off waiting for the server greeting response */ + pop3_state(data, POP3_SERVERGREET); + + result = pop3_multi_statemach(data, done); + + return result; +} + +/*********************************************************************** + * + * pop3_done() + * + * The DONE function. This does what needs to be done after a single DO has + * performed. + * + * Input argument is already checked for validity. + */ +static CURLcode pop3_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + CURLcode result = CURLE_OK; + struct POP3 *pop3 = Curl_meta_get(data, CURL_META_POP3_EASY); + + (void)premature; + + if(!pop3) + return CURLE_OK; + + if(status) { + CURL_TRC_M(data, "POP3 done with bad status"); + connclose(data->conn); + result = status; /* use the already set error code */ + } + + /* Cleanup our per-request based variables */ + curlx_safefree(pop3->id); + curlx_safefree(pop3->custom); + + /* Clear the transfer mode for the next request */ + pop3->transfer = PPTRANSFER_BODY; + + return result; +} + +/*********************************************************************** + * + * pop3_perform() + * + * This is the actual DO function for POP3. Get a message/listing according to + * the options previously setup. + */ +static CURLcode pop3_perform(struct Curl_easy *data, bool *connected, + bool *dophase_done) +{ + /* This is POP3 and no proxy */ + CURLcode result = CURLE_OK; + struct POP3 *pop3 = Curl_meta_get(data, CURL_META_POP3_EASY); + + if(!pop3) + return CURLE_FAILED_INIT; + + DEBUGF(infof(data, "DO phase starts")); + + /* Start the first command in the DO phase, may alter data->req.no_body */ + result = pop3_perform_command(data); + if(result) + return result; + + if(data->req.no_body) + /* Requested no body means no transfer */ + pop3->transfer = PPTRANSFER_INFO; + + *dophase_done = FALSE; /* not done yet */ + + /* Run the state-machine */ + result = pop3_multi_statemach(data, dophase_done); + *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET); + + if(*dophase_done) + DEBUGF(infof(data, "DO phase is complete")); + + return result; +} + +/* Call this when the DO phase has completed */ +static CURLcode pop3_dophase_done(struct Curl_easy *data, bool connected) +{ + (void)data; + (void)connected; + + return CURLE_OK; +} + +/*********************************************************************** + * + * pop3_regular_transfer() + * + * The input argument is already checked for validity. + * + * Performs all commands done before a regular transfer between a local and a + * remote host. + */ +static CURLcode pop3_regular_transfer(struct Curl_easy *data, + bool *dophase_done) +{ + CURLcode result = CURLE_OK; + bool connected = FALSE; + + /* Make sure size is unknown at this point */ + data->req.size = -1; + + /* Set the progress data */ + Curl_pgrsReset(data); + + /* Carry out the perform */ + result = pop3_perform(data, &connected, dophase_done); + + /* Perform post DO phase operations if necessary */ + if(!result && *dophase_done) + result = pop3_dophase_done(data, connected); + + return result; +} + +/*********************************************************************** + * + * pop3_do() + * + * This function is registered as 'curl_do' function. It decodes the path + * parts etc as a wrapper to the actual DO function (pop3_perform). + * + * The input argument is already checked for validity. + */ +static CURLcode pop3_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + *done = FALSE; /* default to false */ + + /* Parse the URL path */ + result = pop3_parse_url_path(data); + if(result) + return result; + + /* Parse the custom request */ + result = pop3_parse_custom_request(data); + if(result) + return result; + + result = pop3_regular_transfer(data, done); + + return result; +} + +/*********************************************************************** + * + * pop3_disconnect() + * + * Disconnect from an POP3 server. Cleanup protocol-specific per-connection + * resources. BLOCKING. + */ +static CURLcode pop3_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead_connection) +{ + struct pop3_conn *pop3c = Curl_conn_meta_get(conn, CURL_META_POP3_CONN); + (void)data; + + if(!pop3c) + return CURLE_FAILED_INIT; + + /* We cannot send quit unconditionally. If this connection is stale or + bad in any way, sending quit and waiting around here will make the + disconnect wait in vain and cause more problems than we need to. */ + + if(!dead_connection && conn->bits.protoconnstart && + !Curl_pp_needs_flush(data, &pop3c->pp)) { + if(!pop3_perform_quit(data, conn)) + (void)pop3_block_statemach(data, conn, TRUE); /* ignore errors on QUIT */ + } + + /* Disconnect from the server */ + Curl_pp_disconnect(&pop3c->pp); + + /* Cleanup our connection based variables */ + curlx_safefree(pop3c->apoptimestamp); + + return CURLE_OK; +} + +/* Called from multi.c while DOing */ +static CURLcode pop3_doing(struct Curl_easy *data, bool *dophase_done) +{ + CURLcode result = pop3_multi_statemach(data, dophase_done); + + if(result) + DEBUGF(infof(data, "DO phase failed")); + else if(*dophase_done) { + result = pop3_dophase_done(data, FALSE /* not connected */); + + DEBUGF(infof(data, "DO phase is complete")); + } + + return result; +} + +static void pop3_easy_dtor(void *key, size_t klen, void *entry) +{ + struct POP3 *pop3 = entry; + (void)key; + (void)klen; + DEBUGASSERT(pop3); + /* Cleanup our per-request based variables */ + curlx_safefree(pop3->id); + curlx_safefree(pop3->custom); + curlx_free(pop3); +} + +static void pop3_conn_dtor(void *key, size_t klen, void *entry) +{ + struct pop3_conn *pop3c = entry; + (void)key; + (void)klen; + DEBUGASSERT(pop3c); + Curl_pp_disconnect(&pop3c->pp); + curlx_safefree(pop3c->apoptimestamp); + curlx_free(pop3c); +} + +static CURLcode pop3_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + struct pop3_conn *pop3c; + struct POP3 *pop3 = curlx_calloc(1, sizeof(*pop3)); + if(!pop3 || + Curl_meta_set(data, CURL_META_POP3_EASY, pop3, pop3_easy_dtor)) + return CURLE_OUT_OF_MEMORY; + + pop3c = curlx_calloc(1, sizeof(*pop3c)); + if(!pop3c || + Curl_conn_meta_set(conn, CURL_META_POP3_CONN, pop3c, pop3_conn_dtor)) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +/* + * POP3 protocol. + */ +const struct Curl_protocol Curl_protocol_pop3 = { + pop3_setup_connection, /* setup_connection */ + pop3_do, /* do_it */ + pop3_done, /* done */ + ZERO_NULL, /* do_more */ + pop3_connect, /* connect_it */ + pop3_multi_statemach, /* connecting */ + pop3_doing, /* doing */ + pop3_pollset, /* proto_pollset */ + pop3_pollset, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + pop3_disconnect, /* disconnect */ + pop3_write, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#endif /* CURL_DISABLE_POP3 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/pop3.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/pop3.h new file mode 100644 index 0000000000..75c3a67da7 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/pop3.h @@ -0,0 +1,30 @@ +#ifndef HEADER_CURL_POP3_H +#define HEADER_CURL_POP3_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_POP3 +extern const struct Curl_protocol Curl_protocol_pop3; +#endif + +#endif /* HEADER_CURL_POP3_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/progress.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/progress.c new file mode 100644 index 0000000000..fcb8bf2422 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/progress.c @@ -0,0 +1,771 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "curl_trc.h" +#include "multiif.h" +#include "progress.h" +#include "transfer.h" +#include "curlx/strcopy.h" + +#ifndef CURL_DISABLE_PROGRESS_METER +/* Provide a string that is 7 letters long (plus the zero byte). + + @unittest 1636 */ +UNITTEST void time2str(char *r, size_t rsize, curl_off_t seconds); +UNITTEST void time2str(char *r, size_t rsize, curl_off_t seconds) +{ + curl_off_t h; + if(seconds <= 0) { + curlx_strcopy(r, rsize, STRCONST(" ")); + return; + } + h = seconds / 3600; + if(h <= 99) { + curl_off_t m = (seconds - (h * 3600)) / 60; + if(h <= 9) { + curl_off_t s = (seconds - (h * 3600)) - (m * 60); + if(h) + curl_msnprintf(r, rsize, "%" FMT_OFF_T ":%02" FMT_OFF_T ":" + "%02" FMT_OFF_T, h, m, s); + else + curl_msnprintf(r, rsize, " %02" FMT_OFF_T ":%02" FMT_OFF_T, m, s); + } + else + curl_msnprintf(r, rsize, "%" FMT_OFF_T "h %02" FMT_OFF_T "m", h, m); + } + else { + curl_off_t d = seconds / 86400; + h = (seconds - (d * 86400)) / 3600; + if(d <= 99) + curl_msnprintf(r, rsize, "%2" FMT_OFF_T "d %02" FMT_OFF_T "h", d, h); + else if(d <= 999) + curl_msnprintf(r, rsize, "%6" FMT_OFF_T "d", d); + else { /* more than 999 days */ + curl_off_t m = d / 30; + if(m <= 999) + curl_msnprintf(r, rsize, "%6" FMT_OFF_T "m", m); + else { /* more than 999 months */ + curl_off_t y = d / 365; + if(y <= 99999) + curl_msnprintf(r, rsize, "%6" FMT_OFF_T "y", y); + else + curlx_strcopy(r, rsize, STRCONST(">99999y")); + } + } + } +} + +/* The point of this function would be to return a string of the input data, + but never longer than 6 columns (+ one zero byte). + Add suffix k, M, G when suitable... + + @unittest 1636 */ +UNITTEST char *max6out(curl_off_t bytes, char *max6, size_t mlen); +UNITTEST char *max6out(curl_off_t bytes, char *max6, size_t mlen) +{ + /* a signed 64-bit value is 8192 petabytes maximum, shown as + 8.0E (exabytes)*/ + if(bytes < 100000) + curl_msnprintf(max6, mlen, "%6" CURL_FORMAT_CURL_OFF_T, bytes); + else { + static const char unit[] = { 'k', 'M', 'G', 'T', 'P', 'E', 0 }; + int k = 0; + curl_off_t nbytes; + curl_off_t rest; + do { + nbytes = bytes / 1024; + if(nbytes < 1000) + break; + bytes = nbytes; + k++; + DEBUGASSERT(unit[k]); + } while(unit[k]); + rest = bytes % 1024; + if(nbytes <= 99) + /* xx.yyU */ + curl_msnprintf(max6, mlen, "%2" CURL_FORMAT_CURL_OFF_T + ".%02" CURL_FORMAT_CURL_OFF_T "%c", nbytes, + rest * 100 / 1024, unit[k]); + else + /* xxx.yU */ + curl_msnprintf(max6, mlen, "%3" CURL_FORMAT_CURL_OFF_T + ".%" CURL_FORMAT_CURL_OFF_T "%c", nbytes, + rest * 10 / 1024, unit[k]); + } + return max6; +} +#endif + +static void pgrs_speedinit(struct Curl_easy *data) +{ + memset(&data->state.keeps_speed, 0, sizeof(struct curltime)); +} + +/* + * @unittest 1606 + */ +UNITTEST CURLcode pgrs_speedcheck(struct Curl_easy *data, + const struct curltime *pnow); +UNITTEST CURLcode pgrs_speedcheck(struct Curl_easy *data, + const struct curltime *pnow) +{ + if(!data->set.low_speed_time || !data->set.low_speed_limit || + Curl_xfer_recv_is_paused(data) || Curl_xfer_send_is_paused(data)) + /* A paused transfer is not qualified for speed checks */ + return CURLE_OK; + + if(data->progress.current_speed >= 0) { + if(data->progress.current_speed < data->set.low_speed_limit) { + if(!data->state.keeps_speed.tv_sec) + /* under the limit at this moment */ + data->state.keeps_speed = *pnow; + else { + /* how long has it been under the limit */ + timediff_t howlong = + curlx_ptimediff_ms(pnow, &data->state.keeps_speed); + + if(howlong >= data->set.low_speed_time * 1000) { + /* too long */ + failf(data, "Operation too slow. Less than %" FMT_OFF_T + " bytes/sec transferred the last %u seconds", + data->set.low_speed_limit, data->set.low_speed_time); + return CURLE_OPERATION_TIMEDOUT; + } + } + } + else + /* faster right now */ + data->state.keeps_speed.tv_sec = 0; + } + + /* since low speed limit is enabled, set the expire timer to make this + connection's speed get checked again in a second */ + Curl_expire_set(data, EXPIRE_SPEEDCHECK, 1000, pnow); + + return CURLE_OK; +} + +const struct curltime *Curl_pgrs_now(struct Curl_easy *data) +{ + curlx_pnow(&data->progress.now); + return &data->progress.now; +} + +/* New proposed interface, 9th of February 2000: + + pgrsStartNow() - sets start time + pgrsSetDownloadSize(x) - known expected download size + pgrsSetUploadSize(x) - known expected upload size + pgrsSetDownloadCounter() - amount of data currently downloaded + pgrsSetUploadCounter() - amount of data currently uploaded + pgrsUpdate() - show progress + pgrsDone() - transfer complete + */ + +int Curl_pgrsDone(struct Curl_easy *data) +{ + int rc; + data->progress.delta.lastshow_us = -1; + rc = Curl_pgrsUpdate(data); /* the final (forced) update */ + if(rc) + return rc; + + if(!data->progress.hide && !data->progress.callback) + /* only output if we do not use a progress callback and we are not + * hidden */ + curl_mfprintf(data->set.err, "\n"); + + return 0; +} + +void Curl_pgrsReset(struct Curl_easy *data) +{ + Curl_pgrsSetUploadCounter(data, 0); + data->progress.dl.cur_size = 0; + Curl_pgrsSetUploadSize(data, -1); + Curl_pgrsSetDownloadSize(data, -1); + data->progress.speeder_c = 0; /* reset speed records */ + data->progress.deliver = 0; + pgrs_speedinit(data); +} + +/* reset the known transfer sizes */ +void Curl_pgrsResetTransferSizes(struct Curl_easy *data) +{ + Curl_pgrsSetDownloadSize(data, -1); + Curl_pgrsSetUploadSize(data, -1); +} + +void Curl_pgrsRecvPause(struct Curl_easy *data, bool enable) +{ + if(!enable) { + data->progress.speeder_c = 0; /* reset speed records */ + pgrs_speedinit(data); /* reset low speed measurements */ + } +} + +void Curl_pgrsSendPause(struct Curl_easy *data, bool enable) +{ + if(!enable) { + data->progress.speeder_c = 0; /* reset speed records */ + pgrs_speedinit(data); /* reset low speed measurements */ + } +} + +#ifdef CURLVERBOSE +static const char * const pgrs_timer_names[] = { + "PGRS-NONE", + "PGRS-STARTOP", + "PGRS-STARTSINGLE", + "PGRS-POSTQUEUE", + "PGRS-NAMELOOKUP", + "PGRS-CONNECT", + "PGRS-APPCONNECT", + "PGRS-PRETRANSFER", + "PGRS-STARTTRANSFER", + "PGRS-POSTRANSFER", + "PGRS-REDIRECT", +}; + +static const char *pgrs_timer_name(timerid timer) +{ + if((size_t)timer < CURL_ARRAYSIZE(pgrs_timer_names)) + return pgrs_timer_names[(size_t)timer]; + return "?"; +} +#endif /* CURLVERBOSE */ + +/* + * Curl_pgrsTimeWas(). Store the timestamp time at the given label. + */ +void Curl_pgrsTimeWas(struct Curl_easy *data, timerid timer, + struct curltime timestamp) +{ + timediff_t *delta = NULL; + + switch(timer) { + default: + case TIMER_NONE: + /* mistake filter */ + break; + case TIMER_STARTOP: + /* This is set at the start of a transfer */ + data->progress.delta.startop_us = + curlx_ptimediff_us(×tamp, &data->progress.start); + data->progress.delta.startqueue_us = data->progress.delta.startop_us; + break; + case TIMER_STARTSINGLE: + /* This is set at the start of each single transfer */ + data->progress.delta.startsingle_us = + curlx_ptimediff_us(×tamp, &data->progress.start); + data->progress.startransfer_added = FALSE; + break; + case TIMER_POSTQUEUE: + /* Queue time is accumulative from all involved redirects */ + data->progress.total.queued_us += + curlx_ptimediff_us(×tamp, &data->progress.start) - + data->progress.delta.startqueue_us; + break; + case TIMER_NAMELOOKUP: + delta = &data->progress.total.nslookup_us; + break; + case TIMER_CONNECT: + delta = &data->progress.total.connect_us; + break; + case TIMER_APPCONNECT: + delta = &data->progress.total.appconnect_us; + break; + case TIMER_PRETRANSFER: + delta = &data->progress.total.pretransfer_us; + break; + case TIMER_STARTTRANSFER: + /* prevent updating t_starttransfer unless: + * 1. this is the first time we are setting t_starttransfer + * 2. a redirect has occurred since the last time t_starttransfer was set + * This prevents repeated invocations of the function from incorrectly + * changing the t_starttransfer time. + */ + if(data->progress.startransfer_added) { + CURL_TRC_M(data, "[%s] ignored", pgrs_timer_name(timer)); + return; + } + data->progress.startransfer_added = TRUE; + delta = &data->progress.total.starttransfer_us; + break; + case TIMER_POSTRANSFER: + delta = &data->progress.total.posttransfer_us; + break; + case TIMER_REDIRECT: + data->progress.delta.startredirect_us = + curlx_ptimediff_us(×tamp, &data->progress.start); + /* transfer starts queueing again */ + data->progress.delta.startqueue_us = + data->progress.delta.startredirect_us; + break; + } + if(delta) { + timediff_t us = curlx_ptimediff_us(×tamp, &data->progress.start) - + data->progress.delta.startsingle_us; + if(us < 1) + us = 1; /* make sure at least one microsecond passed */ + *delta += us; + CURL_TRC_M(data, "[%s] added %" FMT_TIMEDIFF_T "us", + pgrs_timer_name(timer), us); + } + else + CURL_TRC_M(data, "[%s] set", pgrs_timer_name(timer)); +} + +/* + * Curl_pgrsTime(). Store the current time at the given label. This fetches a + * fresh "now" and returns it. + * + * @unittest: 1399 + */ +void Curl_pgrsTime(struct Curl_easy *data, timerid timer) +{ + Curl_pgrsTimeWas(data, timer, *Curl_pgrs_now(data)); +} + +void Curl_pgrsStart(struct Curl_easy *data, const struct curltime *pnow) +{ + struct Progress *p = &data->progress; + + if(!pnow) + pnow = Curl_pgrs_now(data); + p->speeder_c = 0; /* reset the progress meter display */ + p->start = *pnow; + memset(&p->delta, 0, sizeof(p->delta)); + memset(&p->total, 0, sizeof(p->total)); + p->startransfer_added = FALSE; + p->dl.cur_size = 0; + p->ul.cur_size = 0; + /* the sizes are unknown at start */ + p->dl_size_known = FALSE; + p->ul_size_known = FALSE; +} + +/* check that the 'delta' amount of bytes are okay to deliver to the + application, or return error if not. */ +CURLcode Curl_pgrs_deliver_check(struct Curl_easy *data, size_t delta) +{ + if(data->set.max_filesize && + ((curl_off_t)delta > data->set.max_filesize - data->progress.deliver)) { + failf(data, "Would have exceeded max file size"); + return CURLE_FILESIZE_EXCEEDED; + } + return CURLE_OK; +} + +/* this counts how much data is delivered to the application, which + in compressed cases may differ from downloaded amount */ +void Curl_pgrs_deliver_inc(struct Curl_easy *data, size_t delta) +{ + data->progress.deliver += delta; +} + +void Curl_pgrs_download_inc(struct Curl_easy *data, size_t delta) +{ + if(delta) { + data->progress.dl.cur_size += delta; + Curl_rlimit_drain(&data->progress.dl.rlimit, delta, NULL); + } +} + +void Curl_pgrs_upload_inc(struct Curl_easy *data, size_t delta) +{ + if(delta) { + data->progress.ul.cur_size += delta; + Curl_rlimit_drain(&data->progress.ul.rlimit, delta, NULL); + } +} + +/* + * Set the number of uploaded bytes so far. + */ +void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size) +{ + data->progress.ul.cur_size = size; +} + +void Curl_pgrsSetDownloadSize(struct Curl_easy *data, curl_off_t size) +{ + if(size >= 0) { + data->progress.dl.total_size = size; + data->progress.dl_size_known = TRUE; + } + else { + data->progress.dl.total_size = 0; + data->progress.dl_size_known = FALSE; + } +} + +void Curl_pgrsSetUploadSize(struct Curl_easy *data, curl_off_t size) +{ + if(size >= 0) { + data->progress.ul.total_size = size; + data->progress.ul_size_known = TRUE; + } + else { + data->progress.ul.total_size = 0; + data->progress.ul_size_known = FALSE; + } +} + +void Curl_pgrsEarlyData(struct Curl_easy *data, curl_off_t sent) +{ + data->progress.earlydata_sent = sent; +} + +/* returns the average speed in bytes / second */ +static curl_off_t trspeed(curl_off_t size, /* number of bytes */ + curl_off_t us) /* microseconds */ +{ + if(us < 1) + return size * 1000000; + else if(size < CURL_OFF_T_MAX / 1000000) + return (size * 1000000) / us; + else if(us >= 1000000) + return size / (us / 1000000); + else + return CURL_OFF_T_MAX; +} + +/* returns TRUE if it is time to show the progress meter */ +static bool progress_calc(struct Curl_easy *data, + const struct curltime *pnow) +{ + struct Progress * const p = &data->progress; + int i_next, i_oldest, i_latest; + timediff_t duration_us, elapsed_us; + curl_off_t amount; + + /* The time spent so far (from the start) in microseconds */ + elapsed_us = curlx_ptimediff_us(pnow, &p->start); + p->total.spent_us = elapsed_us; + p->dl.speed = trspeed(p->dl.cur_size, p->total.spent_us); + p->ul.speed = trspeed(p->ul.cur_size, p->total.spent_us); + + if(!p->speeder_c) { /* no previous record exists */ + p->speed_amount[0] = p->dl.cur_size + p->ul.cur_size; + p->speed_time[0] = elapsed_us; + p->speeder_c++; + /* use the overall average at the start */ + p->current_speed = p->ul.speed + p->dl.speed; + p->delta.lastshow_us = elapsed_us; + return TRUE; + } + /* We have at least one record now. Where to put the next and + * where is the latest one? */ + i_next = p->speeder_c % CURL_SPEED_RECORDS; + i_latest = (i_next > 0) ? (i_next - 1) : (CURL_SPEED_RECORDS - 1); + + /* Make a new record only when some time has passed. + * Too frequent calls otherwise ruin the history. */ + if((elapsed_us - p->speed_time[i_latest]) >= (1000 * 1000)) { + p->speeder_c++; + i_latest = i_next; + p->speed_amount[i_latest] = p->dl.cur_size + p->ul.cur_size; + p->speed_time[i_latest] = elapsed_us; + } + else if(data->req.done) { + /* When a transfer is done, and we did not have a current speed + * already, update the last record. Otherwise, stay at the speed + * we have. The last chunk of data, when rate limiting, would increase + * reported speed since it no longer measures a full second. */ + if(!p->current_speed) { + p->speed_amount[i_latest] = p->dl.cur_size + p->ul.cur_size; + p->speed_time[i_latest] = elapsed_us; + } + } + else { + /* transfer ongoing, wait for more time to pass. */ + return FALSE; + } + + i_oldest = (p->speeder_c < CURL_SPEED_RECORDS) ? 0 : + ((i_latest + 1) % CURL_SPEED_RECORDS); + + /* How much we transferred between oldest and current records */ + amount = p->speed_amount[i_latest] - p->speed_amount[i_oldest]; + /* How long this took */ + duration_us = p->speed_time[i_latest] - p->speed_time[i_oldest]; + if(duration_us <= 0) + duration_us = 1; + + if(amount > (CURL_OFF_T_MAX / 1000000)) { + /* the 'amount' value is bigger than would fit in 64 bits if + multiplied with 1000000, so we use the double math for this */ + p->current_speed = + (curl_off_t)(((double)amount * 1000000.0) / (double)duration_us); + } + else { + p->current_speed = amount * 1000000 / duration_us; + } + + if((p->delta.lastshow_us >= 0) && !data->req.done && + ((elapsed_us - p->delta.lastshow_us) < (1000 * 1000))) + return FALSE; + p->delta.lastshow_us = elapsed_us; + return TRUE; +} + +#ifndef CURL_DISABLE_PROGRESS_METER + +struct pgrs_estimate { + curl_off_t secs; + curl_off_t percent; +}; + +static curl_off_t pgrs_est_percent(curl_off_t total, curl_off_t cur) +{ + if(total > 10000) + return cur / (total / 100); + else if(total > 0) + return (cur * 100) / total; + return 0; +} + +static void pgrs_estimates(struct pgrs_dir *d, + bool total_known, + struct pgrs_estimate *est) +{ + est->secs = 0; + est->percent = 0; + if(total_known && (d->speed > 0)) { + est->secs = d->total_size / d->speed; + est->percent = pgrs_est_percent(d->total_size, d->cur_size); + } +} + +static void progress_meter(struct Curl_easy *data) +{ + struct Progress *p = &data->progress; + char max6[6][7]; + struct pgrs_estimate dl_estm; + struct pgrs_estimate ul_estm; + struct pgrs_estimate total_estm; + curl_off_t total_cur_size; + curl_off_t total_expected_size; + curl_off_t dl_size; + char time_left[8]; + char time_total[8]; + char time_spent[8]; + curl_off_t cur_secs = (curl_off_t)p->total.spent_us / 1000000; + + if(!p->headers_out) { + if(data->state.resume_from) { + curl_mfprintf(data->set.err, + "** Resuming transfer from byte position %" FMT_OFF_T "\n", + data->state.resume_from); + } + curl_mfprintf(data->set.err, + " %% Total %% Received %% Xferd Average Speed " + "Time Time Time Current\n" + " Dload Upload " + "Total Spent Left Speed\n"); + p->headers_out = TRUE; /* headers are shown */ + } + + /* Figure out the estimated time of arrival for upload and download */ + pgrs_estimates(&p->ul, (bool)p->ul_size_known, &ul_estm); + pgrs_estimates(&p->dl, (bool)p->dl_size_known, &dl_estm); + + /* Since both happen at the same time, total expected duration is max. */ + total_estm.secs = CURLMAX(ul_estm.secs, dl_estm.secs); + /* create the three time strings */ + time2str(time_left, sizeof(time_left), + total_estm.secs > 0 ? (total_estm.secs - cur_secs) : 0); + time2str(time_total, sizeof(time_total), total_estm.secs); + time2str(time_spent, sizeof(time_spent), cur_secs); + + /* Get the total amount of data expected to get transferred */ + total_expected_size = p->ul_size_known ? p->ul.total_size : p->ul.cur_size; + + dl_size = p->dl_size_known ? p->dl.total_size : p->dl.cur_size; + + /* integer overflow check */ + if((CURL_OFF_T_MAX - total_expected_size) < dl_size) + total_expected_size = CURL_OFF_T_MAX; /* capped */ + else + total_expected_size += dl_size; + + /* We have transferred this much so far */ + total_cur_size = p->dl.cur_size + p->ul.cur_size; + + /* Get the percentage of data transferred so far */ + total_estm.percent = pgrs_est_percent(total_expected_size, total_cur_size); + + curl_mfprintf(data->set.err, + "\r" + "%3" FMT_OFF_T " %s " + "%3" FMT_OFF_T " %s " + "%3" FMT_OFF_T " %s %s %s %s %s %s %s", + total_estm.percent, /* 3 letters */ /* total % */ + max6out(total_expected_size, max6[2], + sizeof(max6[2])), /* total size */ + dl_estm.percent, /* 3 letters */ /* rcvd % */ + max6out(p->dl.cur_size, max6[0], + sizeof(max6[0])), /* rcvd size */ + ul_estm.percent, /* 3 letters */ /* xfer % */ + max6out(p->ul.cur_size, max6[1], + sizeof(max6[1])), /* xfer size */ + max6out(p->dl.speed, max6[3], + sizeof(max6[3])), /* avrg dl speed */ + max6out(p->ul.speed, max6[4], + sizeof(max6[4])), /* avrg ul speed */ + time_total, /* 7 letters */ /* total time */ + time_spent, /* 7 letters */ /* time spent */ + time_left, /* 7 letters */ /* time left */ + max6out(p->current_speed, max6[5], + sizeof(max6[5])) /* current speed */ + ); + + /* we flush the output stream to make it appear as soon as possible */ + fflush(data->set.err); +} +#else /* CURL_DISABLE_PROGRESS_METER */ +#define progress_meter(x) Curl_nop_stmt +#endif + +/* + * Curl_pgrsUpdate() returns 0 for success or the value returned by the + * progress callback! + */ +static CURLcode pgrsupdate(struct Curl_easy *data, bool showprogress) +{ + if(!data->progress.hide) { + int rc; + if(data->set.fxferinfo) { + /* There is a callback set, call that */ + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_fxferinfo); + rc = data->set.fxferinfo(data->set.progress_client, + data->progress.dl.total_size, + data->progress.dl.cur_size, + data->progress.ul.total_size, + data->progress.ul.cur_size); + CURL_CBAPI_END(&guard); + if(rc != CURL_PROGRESSFUNC_CONTINUE) { + if(rc) { + failf(data, "Callback aborted"); + return CURLE_ABORTED_BY_CALLBACK; + } + return CURLE_OK; + } + } + else if(data->set.fprogress) { + /* The older deprecated callback is set, call that */ + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_fprogress); + rc = data->set.fprogress(data->set.progress_client, + (double)data->progress.dl.total_size, + (double)data->progress.dl.cur_size, + (double)data->progress.ul.total_size, + (double)data->progress.ul.cur_size); + CURL_CBAPI_END(&guard); + if(rc != CURL_PROGRESSFUNC_CONTINUE) { + if(rc) { + failf(data, "Callback aborted"); + return CURLE_ABORTED_BY_CALLBACK; + } + return CURLE_OK; + } + } + + if(showprogress) + progress_meter(data); + } + + return CURLE_OK; +} + +static CURLcode pgrs_update(struct Curl_easy *data, + const struct curltime *pnow) +{ + bool showprogress = progress_calc(data, pnow); + return pgrsupdate(data, showprogress); +} + +CURLcode Curl_pgrsUpdate(struct Curl_easy *data) +{ + return pgrs_update(data, Curl_pgrs_now(data)); +} + +CURLcode Curl_pgrsUpdateX(struct Curl_easy *data, + const struct curltime *pnow) +{ + return pgrs_update(data, pnow); +} + +CURLcode Curl_pgrsCheckX(struct Curl_easy *data, + const struct curltime *pnow) +{ + CURLcode result; + + result = pgrs_update(data, pnow); + if(!result && !data->req.done) + result = pgrs_speedcheck(data, pnow); + return result; +} + +CURLcode Curl_pgrsCheck(struct Curl_easy *data) +{ + return Curl_pgrsCheckX(data, Curl_pgrs_now(data)); +} + +/* + * Update all progress, do not do progress meter/callbacks. + */ +void Curl_pgrsUpdate_nometer(struct Curl_easy *data) +{ + (void)progress_calc(data, Curl_pgrs_now(data)); +} + +void Curl_pgrsCompleted(struct Curl_easy *data) +{ + struct Progress * const p = &data->progress; + p->total.spent_us = curlx_ptimediff_us(Curl_pgrs_now(data), &p->start); +} + +timediff_t Curl_pgrs_since_ms(struct Curl_easy *data, + const struct curltime *pnow, + timerid timer) +{ + if(!pnow) + pnow = Curl_pgrs_now(data); + switch(timer) { + case TIMER_STARTOP: + return (curlx_ptimediff_us(pnow, &data->progress.start) - + data->progress.delta.startop_us) / 1000; + case TIMER_STARTSINGLE: + return (curlx_ptimediff_us(pnow, &data->progress.start) - + data->progress.delta.startsingle_us) / 1000; + default: + DEBUGASSERT(0); + return 0; + } +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/progress.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/progress.h new file mode 100644 index 0000000000..19bb09517c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/progress.h @@ -0,0 +1,93 @@ +#ifndef HEADER_CURL_PROGRESS_H +#define HEADER_CURL_PROGRESS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curlx/timeval.h" + +struct Curl_easy; + +typedef enum { + TIMER_NONE, + TIMER_STARTOP, + TIMER_STARTSINGLE, /* start of transfer, might get queued */ + TIMER_POSTQUEUE, /* start, immediately after dequeue */ + TIMER_NAMELOOKUP, + TIMER_CONNECT, + TIMER_APPCONNECT, + TIMER_PRETRANSFER, + TIMER_STARTTRANSFER, + TIMER_POSTRANSFER, + TIMER_REDIRECT, + TIMER_LAST /* must be last */ +} timerid; + +/* Get the current timestamp of the transfer */ +const struct curltime *Curl_pgrs_now(struct Curl_easy *data); + +int Curl_pgrsDone(struct Curl_easy *data); +void Curl_pgrsStart(struct Curl_easy *data, const struct curltime *pnow); +void Curl_pgrsSetDownloadSize(struct Curl_easy *data, curl_off_t size); +void Curl_pgrsSetUploadSize(struct Curl_easy *data, curl_off_t size); +CURLcode Curl_pgrs_deliver_check(struct Curl_easy *data, size_t delta); +void Curl_pgrs_deliver_inc(struct Curl_easy *data, size_t delta); +void Curl_pgrs_download_inc(struct Curl_easy *data, size_t delta); +void Curl_pgrs_upload_inc(struct Curl_easy *data, size_t delta); +void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size); + +/* perform progress update, invoking callbacks at intervals */ +CURLcode Curl_pgrsUpdate(struct Curl_easy *data); +CURLcode Curl_pgrsUpdateX(struct Curl_easy *data, const struct curltime *pnow); +/* perform progress update, no callbacks invoked */ +void Curl_pgrsUpdate_nometer(struct Curl_easy *data); +/* perform progress update with callbacks and speed checks */ +CURLcode Curl_pgrsCheck(struct Curl_easy *data); +CURLcode Curl_pgrsCheckX(struct Curl_easy *data, const struct curltime *pnow); + +/* Inform progress/speedcheck about receive/send pausing */ +void Curl_pgrsRecvPause(struct Curl_easy *data, bool enable); +void Curl_pgrsSendPause(struct Curl_easy *data, bool enable); + +/* Reset sizes and counters for up- and download. */ +void Curl_pgrsReset(struct Curl_easy *data); +/* Reset sizes for up- and download. */ +void Curl_pgrsResetTransferSizes(struct Curl_easy *data); + +void Curl_pgrsTime(struct Curl_easy *data, timerid timer); +/** + * Update progress timer with the elapsed time from its start to `timestamp`. + * This allows updating timers later and is used by happy eyeballing, where + * we only want to record the winner's times. + */ +void Curl_pgrsTimeWas(struct Curl_easy *data, timerid timer, + struct curltime timestamp); + +void Curl_pgrsEarlyData(struct Curl_easy *data, curl_off_t sent); + +void Curl_pgrsCompleted(struct Curl_easy *data); + +timediff_t Curl_pgrs_since_ms(struct Curl_easy *data, + const struct curltime *pnow, + timerid timer); + +#endif /* HEADER_CURL_PROGRESS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/protocol.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/protocol.c new file mode 100644 index 0000000000..3bfcd88ebe --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/protocol.c @@ -0,0 +1,662 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "protocol.h" +#include "strcase.h" + +#include "dict.h" +#include "file.h" +#include "ftp.h" +#include "gopher.h" +#include "http.h" +#include "imap.h" +#include "curl_ldap.h" +#include "mqtt.h" +#include "pop3.h" +#include "rtsp.h" +#include "smb.h" +#include "smtp.h" +#include "telnet.h" +#include "tftp.h" +#include "ws.h" +#include "vssh/ssh.h" + + +/* All URI schemes known to libcurl, but not necessarily implemented + * by protocol handlers. */ +const struct Curl_scheme Curl_scheme_dict = { + "dict", /* scheme */ +#ifdef CURL_DISABLE_DICT + ZERO_NULL, +#else + &Curl_protocol_dict, +#endif + CURLPROTO_DICT, /* protocol */ + CURLPROTO_DICT, /* family */ + PROTOPT_NONE | PROTOPT_NOURLQUERY, /* flags */ + PORT_DICT, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_file = { + "file", /* scheme */ +#ifdef CURL_DISABLE_FILE + ZERO_NULL, +#else + &Curl_protocol_file, +#endif + CURLPROTO_FILE, /* protocol */ + CURLPROTO_FILE, /* family */ + PROTOPT_NONETWORK | PROTOPT_NOURLQUERY, /* flags */ + 0 /* defport */ +}; + +const struct Curl_scheme Curl_scheme_ftp = { + "ftp", /* scheme */ +#ifdef CURL_DISABLE_FTP + ZERO_NULL, +#else + &Curl_protocol_ftp, +#endif + CURLPROTO_FTP, /* protocol */ + CURLPROTO_FTP, /* family */ + PROTOPT_DUAL | PROTOPT_CLOSEACTION | PROTOPT_NEEDSPWD | + PROTOPT_NOURLQUERY | PROTOPT_PROXY_AS_HTTP | + PROTOPT_WILDCARD | PROTOPT_SSL_REUSE | + PROTOPT_CONN_REUSE, /* flags */ + PORT_FTP, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_ftps = { + "ftps", /* scheme */ +#if defined(CURL_DISABLE_FTP) || !defined(USE_SSL) + ZERO_NULL, +#else + &Curl_protocol_ftp, +#endif + CURLPROTO_FTPS, /* protocol */ + CURLPROTO_FTP, /* family */ + PROTOPT_SSL | PROTOPT_DUAL | PROTOPT_CLOSEACTION | + PROTOPT_NEEDSPWD | PROTOPT_NOURLQUERY | PROTOPT_WILDCARD | + PROTOPT_CONN_REUSE, /* flags */ + PORT_FTPS, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_gopher = { + "gopher", /* scheme */ +#ifdef CURL_DISABLE_GOPHER + ZERO_NULL, +#else + &Curl_protocol_gopher, +#endif + CURLPROTO_GOPHER, /* protocol */ + CURLPROTO_GOPHER, /* family */ + PROTOPT_NONE, /* flags */ + PORT_GOPHER, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_gophers = { + "gophers", /* scheme */ +#if defined(CURL_DISABLE_GOPHER) || !defined(USE_SSL) + ZERO_NULL, +#else + &Curl_protocol_gophers, +#endif + CURLPROTO_GOPHERS, /* protocol */ + CURLPROTO_GOPHER, /* family */ + PROTOPT_SSL, /* flags */ + PORT_GOPHER, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_http = { + "http", /* scheme */ +#ifdef CURL_DISABLE_HTTP + ZERO_NULL, +#else + &Curl_protocol_http, +#endif + CURLPROTO_HTTP, /* protocol */ + CURLPROTO_HTTP, /* family */ + PROTOPT_CREDSPERREQUEST | /* flags */ + PROTOPT_USERPWDCTRL | PROTOPT_CONN_REUSE, + PORT_HTTP, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_https = { + "https", /* scheme */ +#if defined(CURL_DISABLE_HTTP) || !defined(USE_SSL) + ZERO_NULL, +#else + &Curl_protocol_http, +#endif + CURLPROTO_HTTPS, /* protocol */ + CURLPROTO_HTTP, /* family */ + PROTOPT_SSL | PROTOPT_CREDSPERREQUEST | PROTOPT_ALPN | /* flags */ + PROTOPT_USERPWDCTRL | PROTOPT_CONN_REUSE | + PROTOPT_HTTP_PROXY_TUNNEL, + PORT_HTTPS, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_imap = { + "imap", /* scheme */ +#ifdef CURL_DISABLE_IMAP + ZERO_NULL, +#else + &Curl_protocol_imap, +#endif + CURLPROTO_IMAP, /* protocol */ + CURLPROTO_IMAP, /* family */ + PROTOPT_CLOSEACTION | /* flags */ + PROTOPT_URLOPTIONS | PROTOPT_SSL_REUSE | + PROTOPT_CONN_REUSE, + PORT_IMAP, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_imaps = { + "imaps", /* scheme */ +#if defined(CURL_DISABLE_IMAP) || !defined(USE_SSL) + ZERO_NULL, +#else + &Curl_protocol_imap, +#endif + CURLPROTO_IMAPS, /* protocol */ + CURLPROTO_IMAP, /* family */ + PROTOPT_CLOSEACTION | PROTOPT_SSL | /* flags */ + PROTOPT_URLOPTIONS | PROTOPT_CONN_REUSE, + PORT_IMAPS, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_ldap = { + "ldap", /* scheme */ +#ifdef CURL_DISABLE_LDAP + ZERO_NULL, +#else + &Curl_protocol_ldap, +#endif + CURLPROTO_LDAP, /* protocol */ + CURLPROTO_LDAP, /* family */ + PROTOPT_SSL_REUSE, /* flags */ + PORT_LDAP, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_ldaps = { + "ldaps", /* scheme */ +#if defined(CURL_DISABLE_LDAP) || !defined(HAVE_LDAP_SSL) + ZERO_NULL, +#else + &Curl_protocol_ldap, +#endif + CURLPROTO_LDAPS, /* protocol */ + CURLPROTO_LDAP, /* family */ + PROTOPT_SSL, /* flags */ + PORT_LDAPS, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_mqtt = { + "mqtt", /* scheme */ +#ifdef CURL_DISABLE_MQTT + ZERO_NULL, +#else + &Curl_protocol_mqtt, +#endif + CURLPROTO_MQTT, /* protocol */ + CURLPROTO_MQTT, /* family */ + PROTOPT_NONE, /* flags */ + PORT_MQTT, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_mqtts = { + "mqtts", /* scheme */ +#if defined(CURL_DISABLE_MQTT) || !defined(USE_SSL) + ZERO_NULL, +#else + &Curl_protocol_mqtts, +#endif + CURLPROTO_MQTTS, /* protocol */ + CURLPROTO_MQTT, /* family */ + PROTOPT_SSL, /* flags */ + PORT_MQTTS, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_pop3 = { + "pop3", /* scheme */ +#ifdef CURL_DISABLE_POP3 + ZERO_NULL, +#else + &Curl_protocol_pop3, +#endif + CURLPROTO_POP3, /* protocol */ + CURLPROTO_POP3, /* family */ + PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY | /* flags */ + PROTOPT_URLOPTIONS | PROTOPT_SSL_REUSE | PROTOPT_CONN_REUSE, + PORT_POP3, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_pop3s = { + "pop3s", /* scheme */ +#if defined(CURL_DISABLE_POP3) || !defined(USE_SSL) + ZERO_NULL, +#else + &Curl_protocol_pop3, +#endif + CURLPROTO_POP3S, /* protocol */ + CURLPROTO_POP3, /* family */ + PROTOPT_CLOSEACTION | PROTOPT_SSL | /* flags */ + PROTOPT_NOURLQUERY | PROTOPT_URLOPTIONS | PROTOPT_CONN_REUSE, + PORT_POP3S, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_rtsp = { + "rtsp", /* scheme */ +#ifdef CURL_DISABLE_RTSP + ZERO_NULL, +#else + &Curl_protocol_rtsp, +#endif + CURLPROTO_RTSP, /* protocol */ + CURLPROTO_RTSP, /* family */ + PROTOPT_CONN_REUSE, /* flags */ + PORT_RTSP, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_sftp = { + "sftp", /* scheme */ +#ifndef USE_SSH + NULL, +#else + &Curl_protocol_sftp, +#endif + CURLPROTO_SFTP, /* protocol */ + CURLPROTO_SFTP, /* family */ + PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION | /* flags */ + PROTOPT_NOURLQUERY | PROTOPT_CONN_REUSE, + PORT_SSH /* defport */ +}; + +const struct Curl_scheme Curl_scheme_scp = { + "scp", /* scheme */ +#ifndef USE_SSH + NULL, +#else + &Curl_protocol_scp, +#endif + CURLPROTO_SCP, /* protocol */ + CURLPROTO_SCP, /* family */ + PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION | /* flags */ + PROTOPT_NOURLQUERY | PROTOPT_CONN_REUSE, + PORT_SSH, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_smb = { + "smb", /* scheme */ +#if defined(CURL_ENABLE_SMB) && defined(USE_CURL_NTLM_CORE) + &Curl_protocol_smb, +#else + ZERO_NULL, +#endif + CURLPROTO_SMB, /* protocol */ + CURLPROTO_SMB, /* family */ + PROTOPT_NONE, /* flags */ + PORT_SMB, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_smbs = { + "smbs", /* scheme */ +#if defined(CURL_ENABLE_SMB) && defined(USE_CURL_NTLM_CORE) && defined(USE_SSL) + &Curl_protocol_smb, +#else + ZERO_NULL, +#endif + CURLPROTO_SMBS, /* protocol */ + CURLPROTO_SMB, /* family */ + PROTOPT_SSL, /* flags */ + PORT_SMBS, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_smtp = { + "smtp", /* scheme */ +#ifdef CURL_DISABLE_SMTP + ZERO_NULL, +#else + &Curl_protocol_smtp, +#endif + CURLPROTO_SMTP, /* protocol */ + CURLPROTO_SMTP, /* family */ + PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY | /* flags */ + PROTOPT_URLOPTIONS | PROTOPT_SSL_REUSE | PROTOPT_CONN_REUSE, + PORT_SMTP, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_smtps = { + "smtps", /* scheme */ +#if defined(CURL_DISABLE_SMTP) || !defined(USE_SSL) + ZERO_NULL, +#else + &Curl_protocol_smtp, +#endif + CURLPROTO_SMTPS, /* protocol */ + CURLPROTO_SMTP, /* family */ + PROTOPT_CLOSEACTION | PROTOPT_SSL | /* flags */ + PROTOPT_NOURLQUERY | PROTOPT_URLOPTIONS | PROTOPT_CONN_REUSE, + PORT_SMTPS, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_socks = { + "socks", /* scheme */ + ZERO_NULL, + CURLPROTO_SOCKS, /* protocol */ + CURLPROTO_SOCKS, /* family */ + PROTOPT_NO_TRANSFER, /* flags */ + PORT_SOCKS, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_socks4 = { + "socks4", /* scheme */ + ZERO_NULL, + CURLPROTO_SOCKS, /* protocol */ + CURLPROTO_SOCKS, /* family */ + PROTOPT_NO_TRANSFER, /* flags */ + PORT_SOCKS, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_socks4a = { + "socks4a", /* scheme */ + ZERO_NULL, + CURLPROTO_SOCKS, /* protocol */ + CURLPROTO_SOCKS, /* family */ + PROTOPT_NO_TRANSFER, /* flags */ + PORT_SOCKS, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_socks5 = { + "socks5", /* scheme */ + ZERO_NULL, + CURLPROTO_SOCKS, /* protocol */ + CURLPROTO_SOCKS, /* family */ + PROTOPT_NO_TRANSFER, /* flags */ + PORT_SOCKS, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_socks5h = { + "socks5h", /* scheme */ + ZERO_NULL, + CURLPROTO_SOCKS, /* protocol */ + CURLPROTO_SOCKS, /* family */ + PROTOPT_NO_TRANSFER, /* flags */ + PORT_SOCKS, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_telnet = { + "telnet", /* scheme */ +#ifdef CURL_DISABLE_TELNET + ZERO_NULL, +#else + &Curl_protocol_telnet, +#endif + CURLPROTO_TELNET, /* protocol */ + CURLPROTO_TELNET, /* family */ + PROTOPT_NONE | PROTOPT_NOURLQUERY, /* flags */ + PORT_TELNET, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_tftp = { + "tftp", /* scheme */ +#ifdef CURL_DISABLE_TFTP + ZERO_NULL, +#else + &Curl_protocol_tftp, +#endif + CURLPROTO_TFTP, /* protocol */ + CURLPROTO_TFTP, /* family */ + PROTOPT_NOTCPPROXY | PROTOPT_NOURLQUERY, /* flags */ + PORT_TFTP, /* defport */ +}; + +const struct Curl_scheme Curl_scheme_ws = { + "ws", /* scheme */ +#if defined(CURL_DISABLE_WEBSOCKETS) || defined(CURL_DISABLE_HTTP) + ZERO_NULL, +#else + &Curl_protocol_ws, +#endif + CURLPROTO_WS, /* protocol */ + CURLPROTO_HTTP, /* family */ + PROTOPT_CREDSPERREQUEST | /* flags */ + PROTOPT_USERPWDCTRL | PROTOPT_HTTP_PROXY_TUNNEL, + PORT_HTTP /* defport */ +}; + +const struct Curl_scheme Curl_scheme_wss = { + "wss", /* scheme */ +#if defined(CURL_DISABLE_WEBSOCKETS) || defined(CURL_DISABLE_HTTP) || \ + !defined(USE_SSL) + ZERO_NULL, +#else + &Curl_protocol_ws, +#endif + CURLPROTO_WSS, /* protocol */ + CURLPROTO_HTTP, /* family */ + PROTOPT_SSL | PROTOPT_CREDSPERREQUEST | /* flags */ + PROTOPT_USERPWDCTRL | PROTOPT_HTTP_PROXY_TUNNEL, + PORT_HTTPS /* defport */ +}; + +static const struct Curl_scheme *two_letter_scheme(const char *scheme) +{ + if((Curl_raw_tolower(scheme[0]) == 'w') && + (Curl_raw_tolower(scheme[1]) == 's')) + return &Curl_scheme_ws; + return NULL; +} + +static const struct Curl_scheme *three_letter_scheme(const char *scheme) +{ + char s0 = Curl_raw_tolower(scheme[0]); + char s1 = Curl_raw_tolower(scheme[1]); + char s2 = Curl_raw_tolower(scheme[2]); + if(s0 == 'f') { + if(s1 == 't' && s2 == 'p') + return &Curl_scheme_ftp; + } + else if(s0 == 'w') { + if(s1 == 's' && s2 == 's') + return &Curl_scheme_wss; + } + else if(s0 == 's') { + if(s1 == 'c' && s2 == 'p') + return &Curl_scheme_scp; + if(s1 == 'm' && s2 == 'b') + return &Curl_scheme_smb; + } + return NULL; +} + +static const struct Curl_scheme *four_letter_scheme(const char *scheme) +{ + char s0 = Curl_raw_tolower(scheme[0]); + char s1 = Curl_raw_tolower(scheme[1]); + char s2 = Curl_raw_tolower(scheme[2]); + char s3 = Curl_raw_tolower(scheme[3]); + if(s3 == 'p') { + if(s0 == 'h') { + if(s1 == 't' && s2 == 't') + return &Curl_scheme_http; + } + else if(s0 == 'i') { + if(s1 == 'm' && s2 == 'a') + return &Curl_scheme_imap; + } + else if(s0 == 'l') { + if(s1 == 'd' && s2 == 'a') + return &Curl_scheme_ldap; + } + else if(s0 == 'r') { + if(s1 == 't' && s2 == 's') + return &Curl_scheme_rtsp; + } + else if(s0 == 't') { + if(s1 == 'f' && s2 == 't') + return &Curl_scheme_tftp; + } + else if(s0 == 's') { + if(s1 == 'f' && s2 == 't') + return &Curl_scheme_sftp; + if(s1 == 'm' && s2 == 't') + return &Curl_scheme_smtp; + } + } + else if(s0 == 'f') { + if(s1 == 't' && s2 == 'p' && s3 == 's') + return &Curl_scheme_ftps; + if(s1 == 'i' && s2 == 'l' && s3 == 'e') + return &Curl_scheme_file; + } + else if(s0 == 'm') { + if(s1 == 'q' && s2 == 't' && s3 == 't') + return &Curl_scheme_mqtt; + } + else if(s0 == 'p') { + if(s1 == 'o' && s2 == 'p' && s3 == '3') + return &Curl_scheme_pop3; + } + else if(s0 == 'd') { + if(s1 == 'i' && s2 == 'c' && s3 == 't') + return &Curl_scheme_dict; + } + else if(s0 == 's') { + if(s1 == 'm' && s2 == 'b' && s3 == 's') + return &Curl_scheme_smbs; + } + return NULL; +} + +static const struct Curl_scheme *five_letter_scheme(const char *scheme) +{ + char s4 = Curl_raw_tolower(scheme[4]); + if(s4 == 's') { + char s0 = Curl_raw_tolower(scheme[0]); + char s1 = Curl_raw_tolower(scheme[1]); + char s2 = Curl_raw_tolower(scheme[2]); + char s3 = Curl_raw_tolower(scheme[3]); + if(s3 == 'p') { + switch(s0) { + case 'h': + if(s1 == 't' && s2 == 't') + return &Curl_scheme_https; + break; + case 'l': + if(s1 == 'd' && s2 == 'a') + return &Curl_scheme_ldaps; + break; + case 'i': + if(s1 == 'm' && s2 == 'a') + return &Curl_scheme_imaps; + break; + case 's': + if(s1 == 'm' && s2 == 't') + return &Curl_scheme_smtps; + break; + default: + break; + } + } + else if(s0 == 'p') { + if(s1 == 'o' && s2 == 'p' && s3 == '3') + return &Curl_scheme_pop3s; + } + else if(s0 == 'm') { + if(s1 == 'q' && s2 == 't' && s3 == 't') + return &Curl_scheme_mqtts; + } + else if(s0 == 's') { + if(s1 == 'o' && s2 == 'c' && s3 == 'k') + return &Curl_scheme_socks; + } + } + return NULL; +} + +static const struct Curl_scheme *six_letter_scheme(const char *scheme) +{ + char s0 = Curl_raw_tolower(scheme[0]); + switch(s0) { + case 's': + if(curl_strnequal("ocks4", &scheme[1], 5)) + return &Curl_scheme_socks4; + if(curl_strnequal("ocks5", &scheme[1], 5)) + return &Curl_scheme_socks5; + break; + case 'g': + if(curl_strnequal("opher", &scheme[1], 5)) + return &Curl_scheme_gopher; + break; + case 't': + if(curl_strnequal("elnet", &scheme[1], 5)) + return &Curl_scheme_telnet; + break; + } + return NULL; +} + +static const struct Curl_scheme *seven_letter_scheme(const char *scheme) +{ + char s0 = Curl_raw_tolower(scheme[0]); + if(s0 == 's') { + if(curl_strnequal("ocks4a", &scheme[1], 6)) + return &Curl_scheme_socks4a; + if(curl_strnequal("ocks5h", &scheme[1], 6)) + return &Curl_scheme_socks5h; + } + else if(s0 == 'g') { + if(curl_strnequal("ophers", &scheme[1], 6)) + return &Curl_scheme_gophers; + } + return NULL; +} + +/* Returns a struct scheme pointer if the name is a known scheme. Check the + ->run struct field for non-NULL to figure out if an implementation is + present. */ +const struct Curl_scheme *Curl_getn_scheme(const char *scheme, size_t len) +{ + typedef const struct Curl_scheme *(*letterfunc)(const char *ptr); + static const letterfunc parse[] = { + two_letter_scheme, + three_letter_scheme, + four_letter_scheme, + five_letter_scheme, + six_letter_scheme, + seven_letter_scheme + }; + + if(len < 2 || len > 7) + return NULL; + + return parse[len - 2](scheme); +} + +const struct Curl_scheme *Curl_get_scheme(const char *scheme) +{ + return Curl_getn_scheme(scheme, strlen(scheme)); +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/protocol.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/protocol.h new file mode 100644 index 0000000000..031bb834e4 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/protocol.h @@ -0,0 +1,295 @@ +#ifndef HEADER_CURL_PROTOCOL_H +#define HEADER_CURL_PROTOCOL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* This file is for lib internal stuff */ +#include "curl_setup.h" + +struct Curl_easy; +struct connectdata; +struct easy_pollset; + +/* Known protocol default port numbers */ +#define PORT_FTP 21 +#define PORT_FTPS 990 +#define PORT_TELNET 23 +#define PORT_HTTP 80 +#define PORT_HTTPS 443 +#define PORT_DICT 2628 +#define PORT_LDAP 389 +#define PORT_LDAPS 636 +#define PORT_TFTP 69 +#define PORT_SSH 22 +#define PORT_IMAP 143 +#define PORT_IMAPS 993 +#define PORT_POP3 110 +#define PORT_POP3S 995 +#define PORT_SMB 445 +#define PORT_SMBS 445 +#define PORT_SMTP 25 +#define PORT_SMTPS 465 /* sometimes called SSMTP */ +#define PORT_RTSP 554 +#define PORT_GOPHER 70 +#define PORT_SOCKS 1080 +#define PORT_MQTT 1883 +#define PORT_MQTTS 8883 + +/* CURLPROTO_GOPHERS (29) is the highest publicly used protocol bit number, + * the rest are internal information. If we use higher bits we only do this on + * platforms that have a >= 64-bit type and then we use such a type for the + * protocol fields in the scheme definition. + */ +#define CURLPROTO_WS (1L << 30) +#define CURLPROTO_WSS ((curl_prot_t)1 << 31) +#define CURLPROTO_MQTTS (1LL << 32) +#define CURLPROTO_SOCKS (1LL << 33) + +#define CURLPROTO_64ALL ((uint64_t)0xffffffffffffffff) + +/* the default protocols accepting a redirect to */ +#define CURLPROTO_REDIR (CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_FTP | \ + CURLPROTO_FTPS) + +typedef curl_off_t curl_prot_t; + +/* This mask is for all the old protocols that are provided and defined in the + public header and shall exclude protocols added since which are not exposed + in the API */ +#define CURLPROTO_MASK 0x3fffffff + +/* Convenience defines for checking protocols or their SSL based version. Each + protocol scheme should only ever have a single CURLPROTO_ in its protocol + field. */ +#define PROTO_FAMILY_HTTP (CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_WS | \ + CURLPROTO_WSS) +#define PROTO_FAMILY_FTP (CURLPROTO_FTP | CURLPROTO_FTPS) +#define PROTO_FAMILY_POP3 (CURLPROTO_POP3 | CURLPROTO_POP3S) +#define PROTO_FAMILY_SMB (CURLPROTO_SMB | CURLPROTO_SMBS) +#define PROTO_FAMILY_SMTP (CURLPROTO_SMTP | CURLPROTO_SMTPS) +#define PROTO_FAMILY_SSH (CURLPROTO_SCP | CURLPROTO_SFTP) + +#if !defined(CURL_DISABLE_FTP) || defined(USE_SSH) || \ + !defined(CURL_DISABLE_POP3) +/* these protocols support CURLOPT_DIRLISTONLY */ +#define CURL_LIST_ONLY_PROTOCOL 1 +#endif + +/* When redirecting transfers. */ +typedef enum { + FOLLOW_NONE, /* not used within the function, a placeholder to allow + initing to this */ + FOLLOW_FAKE, /* only records stuff, not actually following */ + FOLLOW_RETRY, /* set if this is a request retry as opposed to a real + redirect following */ + FOLLOW_REDIR /* a full true redirect */ +} followtype; + +typedef enum { + DOMORE_GOBACK = -1, + DOMORE_INCOMPLETE = 0, + DOMORE_DONE = 1 +} domore; + +/* + * Specific protocol handler, an implementation of one or more URI schemes. + */ +struct Curl_protocol { + /* Complement to setup_connection_internals(). This is done before the + transfer "owns" the connection. */ + CURLcode (*setup_connection)(struct Curl_easy *data, + struct connectdata *conn); + + /* These two functions MUST be set to be protocol dependent */ + CURLcode (*do_it)(struct Curl_easy *data, bool *done); + CURLcode (*done)(struct Curl_easy *, CURLcode, bool); + + /* If the curl_do() function is better made in two halves, this + * curl_do_more() function will be called afterwards, if set. For example + * for doing the FTP stuff after the PASV/PORT command. The second + * argument is an output parameter that MUST be set to one of the + * DOMORE_* values: DOMORE_INCOMPLETE if more do_more work remains, + * DOMORE_DONE when the second phase is complete, or DOMORE_GOBACK + * to return to the regular DO/DOING handling. + */ + CURLcode (*do_more)(struct Curl_easy *, domore *); + + /* This function *MAY* be set to a protocol-dependent function that is run + * after the connect() and everything is done, as a step in the connection. + * The 'done' pointer points to a bool that should be set to TRUE if the + * function completes before return. If it does not complete, the caller + * should call the ->connecting() function until it is. + */ + CURLcode (*connect_it)(struct Curl_easy *data, bool *done); + + /* See above. */ + CURLcode (*connecting)(struct Curl_easy *data, bool *done); + CURLcode (*doing)(struct Curl_easy *data, bool *done); + + /* Called from the multi interface during the PROTOCONNECT phase, and it + should then return a proper fd set */ + CURLcode (*proto_pollset)(struct Curl_easy *data, + struct easy_pollset *ps); + + /* Called from the multi interface during the DOING phase, and it should + then return a proper fd set */ + CURLcode (*doing_pollset)(struct Curl_easy *data, + struct easy_pollset *ps); + + /* Called from the multi interface during the DO_MORE phase, and it should + then return a proper fd set */ + CURLcode (*domore_pollset)(struct Curl_easy *data, + struct easy_pollset *ps); + + /* Called from the multi interface during the DO_DONE, PERFORM and + WAITPERFORM phases, and it should then return a proper fd set. Not setting + this will make libcurl use the generic default one. */ + CURLcode (*perform_pollset)(struct Curl_easy *data, + struct easy_pollset *ps); + + /* This function *MAY* be set to a protocol-dependent function that is run + * by the curl_disconnect(), as a step in the disconnection. If the handler + * is called because the connection has been considered dead, + * dead_connection is set to TRUE. The connection is (again) associated with + * the transfer here. + */ + CURLcode (*disconnect)(struct Curl_easy *, struct connectdata *, + bool dead_connection); + + /* If used, this function gets called from transfer.c to + allow the protocol to do extra handling in writing response to + the client. */ + CURLcode (*write_resp)(struct Curl_easy *data, const char *buf, size_t blen, + bool is_eos); + + /* If used, this function gets called from transfer.c to + allow the protocol to do extra handling in writing a single response + header line to the client. */ + CURLcode (*write_resp_hd)(struct Curl_easy *data, + const char *hd, size_t hdlen, bool is_eos); + + /* If used, this function checks for a connection managed by this + protocol and currently not in use, if it should be considered dead. */ + bool (*connection_is_dead)(struct Curl_easy *data, + struct connectdata *conn); + + /* attach() attaches this transfer to this connection */ + void (*attach)(struct Curl_easy *data, struct connectdata *conn); + + /* return CURLE_OK if a redirect to `newurl` should be followed, + CURLE_TOO_MANY_REDIRECTS otherwise. May alter `data` to change + the way the follow request is performed. */ + CURLcode (*follow)(struct Curl_easy *data, const char *newurl, + followtype type); +}; + +#define PROTOPT_NONE 0 /* nothing extra */ +#define PROTOPT_SSL (1 << 0) /* uses SSL */ +#define PROTOPT_DUAL (1 << 1) /* this protocol uses two connections */ +#define PROTOPT_CLOSEACTION (1 << 2) /* need action before socket close */ +/* some protocols will have to call the underlying functions without regard to + what exact state the socket signals. IE even if the socket says "readable", + the send function might need to be called while uploading, or vice versa. */ +#define PROTOPT_DIRLOCK (1 << 3) +#define PROTOPT_NONETWORK (1 << 4) /* protocol does not use the network! */ +#define PROTOPT_NEEDSPWD (1 << 5) /* needs a password, and if none is set it + gets a default */ +#define PROTOPT_NOURLQUERY (1 << 6) /* protocol cannot handle + URL query strings (?foo=bar) ! */ +#define PROTOPT_CREDSPERREQUEST (1 << 7) /* requires login credentials per + request instead of per + connection */ +#define PROTOPT_ALPN (1 << 8) /* set ALPN for this */ +/* (1 << 9) was PROTOPT_STREAM, now free */ +#define PROTOPT_URLOPTIONS (1 << 10) /* allow options part in the userinfo + field of the URL */ +#define PROTOPT_PROXY_AS_HTTP (1 << 11) /* allow this non-HTTP scheme over a + HTTP proxy as HTTP proxies may know + this protocol and act as + a gateway */ +#define PROTOPT_WILDCARD (1 << 12) /* protocol supports wildcard matching */ +#define PROTOPT_USERPWDCTRL (1 << 13) /* Allow "control bytes" (< 32 ASCII) in + username and password */ +#define PROTOPT_NOTCPPROXY (1 << 14) /* this protocol cannot proxy over TCP */ +#define PROTOPT_SSL_REUSE (1 << 15) /* this protocol may reuse an existing + SSL connection in the same family + without having PROTOPT_SSL. */ +#define PROTOPT_CONN_REUSE (1 << 16) /* this protocol can reuse connections */ +#define PROTOPT_NO_TRANSFER (1 << 17) /* this protocol is not for transfers */ +#define PROTOPT_HTTP_PROXY_TUNNEL (1 << 18) /* Using this protocol with a + * HTTP proxy requires tunneling */ + +/* Everything about a URI scheme. */ +struct Curl_scheme { + const char *name; /* URL scheme name in lowercase */ + const struct Curl_protocol *run; /* implementation, optional */ + curl_prot_t protocol; /* See CURLPROTO_* - this needs to be the single + specific protocol bit */ + curl_prot_t family; /* single bit for protocol family; the non-TLS name + of the protocol this is */ + uint32_t flags; /* Extra particular characteristics, see PROTOPT_* */ + uint16_t defport; /* Default port. */ +}; + +/* Get scheme definition for a URI scheme name + * @param scheme URI scheme name, case-insensitive + * @return NULL if scheme is not known + */ +const struct Curl_scheme *Curl_get_scheme(const char *scheme); +const struct Curl_scheme *Curl_getn_scheme(const char *scheme, size_t len); + +/* For direct access to a URI scheme */ +extern const struct Curl_scheme Curl_scheme_dict; +extern const struct Curl_scheme Curl_scheme_file; +extern const struct Curl_scheme Curl_scheme_ftp; +extern const struct Curl_scheme Curl_scheme_ftps; +extern const struct Curl_scheme Curl_scheme_gopher; +extern const struct Curl_scheme Curl_scheme_gophers; +extern const struct Curl_scheme Curl_scheme_http; +extern const struct Curl_scheme Curl_scheme_https; +extern const struct Curl_scheme Curl_scheme_imap; +extern const struct Curl_scheme Curl_scheme_imaps; +extern const struct Curl_scheme Curl_scheme_ldap; +extern const struct Curl_scheme Curl_scheme_ldaps; +extern const struct Curl_scheme Curl_scheme_mqtt; +extern const struct Curl_scheme Curl_scheme_mqtts; +extern const struct Curl_scheme Curl_scheme_pop3; +extern const struct Curl_scheme Curl_scheme_pop3s; +extern const struct Curl_scheme Curl_scheme_rtsp; +extern const struct Curl_scheme Curl_scheme_scp; +extern const struct Curl_scheme Curl_scheme_sftp; +extern const struct Curl_scheme Curl_scheme_smb; +extern const struct Curl_scheme Curl_scheme_smbs; +extern const struct Curl_scheme Curl_scheme_smtp; +extern const struct Curl_scheme Curl_scheme_smtps; +extern const struct Curl_scheme Curl_scheme_socks; +extern const struct Curl_scheme Curl_scheme_socks4; +extern const struct Curl_scheme Curl_scheme_socks4a; +extern const struct Curl_scheme Curl_scheme_socks5; +extern const struct Curl_scheme Curl_scheme_socks5h; +extern const struct Curl_scheme Curl_scheme_telnet; +extern const struct Curl_scheme Curl_scheme_tftp; +extern const struct Curl_scheme Curl_scheme_ws; +extern const struct Curl_scheme Curl_scheme_wss; + +#endif /* HEADER_CURL_PROTOCOL_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/proxy.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/proxy.c new file mode 100644 index 0000000000..5d7c02579d --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/proxy.c @@ -0,0 +1,679 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_PROXY + +#include "urldata.h" +#include "curl_trc.h" +#include "protocol.h" +#include "proxy.h" +#include "http_proxy.h" +#include "strcase.h" +#include "url.h" +#include "vauth/vauth.h" +#include "curlx/inet_pton.h" +#include "curlx/strparse.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif + +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif + +/* + * cidr4_match() returns TRUE if the given IPv4 address is within the + * specified CIDR address range. + * + * @unittest 1614 + */ +UNITTEST bool cidr4_match(const char *ipv4, /* 1.2.3.4 address */ + const char *network, /* 1.2.3.4 address */ + unsigned int bits); +UNITTEST bool cidr4_match(const char *ipv4, /* 1.2.3.4 address */ + const char *network, /* 1.2.3.4 address */ + unsigned int bits) +{ + unsigned int address = 0; + unsigned int check = 0; + + if(bits > 32) + /* strange input */ + return FALSE; + + if(curlx_inet_pton(AF_INET, ipv4, &address) != 1) + return FALSE; + if(curlx_inet_pton(AF_INET, network, &check) != 1) + return FALSE; + + if(bits && (bits != 32)) { + unsigned int mask = 0xffffffff << (32 - bits); + unsigned int haddr = htonl(address); + unsigned int hcheck = htonl(check); +#if 0 + curl_mfprintf(stderr, "Host %s (%x) network %s (%x) " + "bits %u mask %x => %x\n", + ipv4, haddr, network, hcheck, bits, mask, + (haddr ^ hcheck) & mask); +#endif + if((haddr ^ hcheck) & mask) + return FALSE; + return TRUE; + } + return address == check; +} + +/* @unittest 1614 */ +UNITTEST bool cidr6_match(const char *ipv6, const char *network, + unsigned int bits); +UNITTEST bool cidr6_match(const char *ipv6, const char *network, + unsigned int bits) +{ +#ifdef USE_IPV6 + unsigned int bytes; + unsigned int rest; + unsigned char address[16]; + unsigned char check[16]; + + if(!bits) + bits = 128; + + bytes = bits / 8; + rest = bits & 0x07; + if((bytes > 16) || ((bytes == 16) && rest)) + return FALSE; + if(curlx_inet_pton(AF_INET6, ipv6, address) != 1) + return FALSE; + if(curlx_inet_pton(AF_INET6, network, check) != 1) + return FALSE; + if(bytes && memcmp(address, check, bytes)) + return FALSE; + if(rest && ((address[bytes] ^ check[bytes]) & (0xff << (8 - rest)))) + return FALSE; + + return TRUE; +#else + (void)ipv6; + (void)network; + (void)bits; + return FALSE; +#endif +} + +enum nametype { + TYPE_HOST, + TYPE_IPV4, + TYPE_IPV6 +}; + +static bool match_host(const char *token, size_t tokenlen, + const char *name, size_t namelen) +{ + bool match = FALSE; + + /* ignore trailing dots in the token to check */ + if(token[tokenlen - 1] == '.') + tokenlen--; + + if(tokenlen && (*token == '.')) { + /* ignore leading token dot as well */ + token++; + tokenlen--; + } + /* A: example.com matches 'example.com' + B: www.example.com matches 'example.com' + C: nonexample.com DOES NOT match 'example.com' + */ + if(tokenlen == namelen) + /* case A, exact match */ + match = curl_strnequal(token, name, namelen); + else if(tokenlen < namelen) { + /* case B, tailmatch domain */ + match = (name[namelen - tokenlen - 1] == '.') && + curl_strnequal(token, name + (namelen - tokenlen), tokenlen); + } + /* case C passes through, not a match */ + return match; +} + +static bool match_ip(int type, const char *token, size_t tokenlen, + const char *name) +{ + char *slash; + unsigned int bits = 0; + char checkip[128]; + if(tokenlen >= sizeof(checkip)) + /* this cannot match */ + return FALSE; + /* copy the check name to a temp buffer */ + memcpy(checkip, token, tokenlen); + checkip[tokenlen] = 0; + + slash = strchr(checkip, '/'); + /* if the slash is part of this token, use it */ + if(slash) { + curl_off_t value; + const char *p = &slash[1]; + if(curlx_str_number(&p, &value, 128) || *p) + return FALSE; + /* a too large value is rejected in the cidr function below */ + bits = (unsigned int)value; + *slash = 0; /* null-terminate there */ + } + if(type == TYPE_IPV6) + return cidr6_match(name, checkip, bits); + else + return cidr4_match(name, checkip, bits); +} + +/**************************************************************** + * Checks if the host is in the noproxy list. returns TRUE if it matches and + * therefore the proxy should NOT be used. + ****************************************************************/ +/* @unittest 1614 */ +UNITTEST bool proxy_check_noproxy(const char *name, const char *no_proxy); +UNITTEST bool proxy_check_noproxy(const char *name, const char *no_proxy) +{ + /* + * If we do not have a hostname at all, like for example with a FILE + * transfer, we have nothing to interrogate the noproxy list with. + */ + if(!name || name[0] == '\0') + return FALSE; + + /* no_proxy=domain1.dom,host.domain2.dom + * (a comma-separated list of hosts which should + * not be proxied, or an asterisk to override + * all proxy variables) + */ + if(no_proxy && no_proxy[0]) { + const char *p = no_proxy; + size_t namelen; + char address[16]; + enum nametype type = TYPE_HOST; + if(!strcmp("*", no_proxy)) + return TRUE; + + /* NO_PROXY was specified and it was not only an asterisk */ + + /* Check if name is an IP address; if not, assume it being a hostname. */ + namelen = strlen(name); + if(curlx_inet_pton(AF_INET, name, &address) == 1) + type = TYPE_IPV4; +#ifdef USE_IPV6 + else if(curlx_inet_pton(AF_INET6, name, &address) == 1) + type = TYPE_IPV6; +#endif + else { + /* ignore trailing dots in the hostname */ + if(name[namelen - 1] == '.') + namelen--; + } + + while(*p) { + const char *token; + size_t tokenlen = 0; + + /* pass blanks */ + curlx_str_passblanks(&p); + + token = p; + /* pass over the pattern */ + while(*p && !ISBLANK(*p) && (*p != ',')) { + p++; + tokenlen++; + } + + if(tokenlen) { + bool match = FALSE; + if(type == TYPE_HOST) + match = match_host(token, tokenlen, name, namelen); + else + match = match_ip(type, token, tokenlen, name); + + if(match) + return TRUE; + } + + /* pass blanks after pattern */ + curlx_str_passblanks(&p); + /* if not a comma, this ends the loop */ + if(*p != ',') + break; + /* pass any number of commas */ + while(*p == ',') + p++; + } /* while(*p) */ + } /* NO_PROXY was specified and it was not only an asterisk */ + + return FALSE; +} + +#ifndef CURL_DISABLE_HTTP + +/**************************************************************** + * Detect what (if any) proxy to use. Remember that this selects a host + * name and is not limited to HTTP proxies only. + * The returned pointer must be freed by the caller. + ****************************************************************/ +static char *proxy_detect_proxy(struct Curl_easy *data, + const struct Curl_scheme *scheme) +{ + /* If proxy was not specified, we check for default proxy environment + * variables, to enable i.e Lynx compliance: + * + * http_proxy=http://some.server.dom:port/ + * https_proxy=http://some.server.dom:port/ + * ftp_proxy=http://some.server.dom:port/ + * no_proxy=domain1.dom,host.domain2.dom + * (a comma-separated list of hosts which should + * not be proxied, or an asterisk to override + * all proxy variables) + * all_proxy=http://some.server.dom:port/ + * (seems to exist for the CERN www lib. Probably + * the first to check for.) + * + * For compatibility, the all-uppercase versions of these variables are + * checked if the lowercase versions do not exist. + */ + const char *env_name = NULL; + char *proxy = NULL; + char name_buf[20]; + + /* Try scheme specific env var first, unless http(s). + * lowercase first, then uppercase. */ + if((scheme != &Curl_scheme_https) && (scheme != &Curl_scheme_http)) { + curl_msnprintf(name_buf, sizeof(name_buf), "%s_proxy", scheme->name); + env_name = name_buf; + proxy = curl_getenv(env_name); + if(!proxy) { + Curl_strntoupper(name_buf, name_buf, sizeof(name_buf)); + proxy = curl_getenv(env_name); + } + } + + if(!proxy && + ((scheme == &Curl_scheme_https) || (scheme == &Curl_scheme_wss))) { + /* Not found, check 'https' env vars, also for 'wss'. + * Again, first lowercase then uppercase. */ + env_name = "https_proxy"; + proxy = curl_getenv(env_name); + if(!proxy) { + env_name = "HTTPS_PROXY"; + proxy = curl_getenv(env_name); + } + } + else if(!proxy && + ((scheme == &Curl_scheme_http) || (scheme == &Curl_scheme_ws))) { + /* Not found, check 'http' env vars, also for 'ws'. + * We do NOT try the uppercase version 'HTTP_PROXY' because of + * security reasons: + * + * When curl is used in a webserver application + * environment (cgi or php), this environment variable can + * be controlled by the web server user by setting the + * http header 'Proxy:' to some value. + * + * This can cause 'internal' http/ftp requests to be + * arbitrarily redirected by any external attacker. + */ + env_name = "http_proxy"; + proxy = curl_getenv(env_name); + } + + if(!proxy) { + /* still not found, last resort checks. */ + env_name = "all_proxy"; + proxy = curl_getenv(env_name); + if(!proxy) { + env_name = "ALL_PROXY"; + proxy = curl_getenv(env_name); + } + } + + if(proxy) + infof(data, "Uses proxy env variable %s == '%s'", env_name, proxy); + + return proxy; +} +#endif /* CURL_DISABLE_HTTP */ + +/* + * If this is supposed to use a proxy, we need to figure out the proxy + * hostname, so that we can reuse an existing connection + * that may exist registered to the same proxy host. + */ +static CURLcode parse_proxy(struct Curl_easy *data, + const char *proxy, + bool for_pre_proxy, + struct proxy_info *proxyinfo) +{ + char *proxyuser = NULL; + char *proxypasswd = NULL; + char *scheme = NULL; + CURLcode result = CURLE_OK; + /* Set the start proxy type for URL scheme guessing */ + uint8_t proxytype = for_pre_proxy ? CURLPROXY_SOCKS4 : data->set.proxytype; + CURLU *uhp = curl_url(); + CURLUcode uc; + + if(!uhp) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + /* When parsing the proxy, allowing non-supported schemes since we have + these made up ones for proxies. Guess scheme for URLs without it. */ + uc = curl_url_set(uhp, CURLUPART_URL, proxy, + CURLU_NON_SUPPORT_SCHEME | CURLU_GUESS_SCHEME); + if(!uc) { + /* parsed okay as a URL - only update proxytype when scheme was explicit */ + uc = curl_url_get(uhp, CURLUPART_SCHEME, &scheme, CURLU_NO_GUESS_SCHEME); + if(!uc) { + result = Curl_scheme_to_proxytype(data, scheme, &proxytype, proxy); + if(result) + goto error; + } + else if(uc != CURLUE_NO_SCHEME) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + /* else: no explicit scheme, keep the configured proxytype */ + } + else { + failf(data, "Unsupported proxy syntax in \'%s\': %s", proxy, + curl_url_strerror(uc)); + result = CURLE_COULDNT_RESOLVE_PROXY; + goto error; + } + + result = Curl_peer_from_proxy_url(uhp, data, proxy, proxytype, + &proxyinfo->peer, &proxytype); + if(result) + goto error; + + switch(proxytype) { + case CURLPROXY_HTTP: + case CURLPROXY_HTTP_1_0: + case CURLPROXY_HTTPS: + case CURLPROXY_HTTPS2: + case CURLPROXY_HTTPS3: + if(for_pre_proxy) { + failf(data, "Unsupported pre-proxy type for \'%s\'", proxy); + result = CURLE_COULDNT_RESOLVE_PROXY; + goto error; + } + break; + case CURLPROXY_SOCKS4: + case CURLPROXY_SOCKS4A: + case CURLPROXY_SOCKS5: + case CURLPROXY_SOCKS5_HOSTNAME: + break; + default: + failf(data, "Unsupported proxy type %u for \'%s\'", proxytype, proxy); + result = CURLE_COULDNT_RESOLVE_PROXY; + goto error; + } + + /* Is there a username and password given in this proxy URL? */ + uc = curl_url_get(uhp, CURLUPART_USER, &proxyuser, CURLU_URLDECODE); + if(uc && (uc != CURLUE_NO_USER)) { + result = Curl_uc_to_curlcode(uc); + goto error; + } + uc = curl_url_get(uhp, CURLUPART_PASSWORD, &proxypasswd, CURLU_URLDECODE); + if(uc && (uc != CURLUE_NO_PASSWORD)) { + result = Curl_uc_to_curlcode(uc); + goto error; + } + + if(proxyuser || proxypasswd) { + result = Curl_creds_create(proxyuser, proxypasswd, NULL, NULL, + CURL_EASY_STR(data, STRING_PROXY_SERVICE_NAME), + CREDS_URL, &proxyinfo->creds); + if(result) + goto error; + } + else if(!for_pre_proxy && + (CURL_EASY_STR(data, STRING_PROXYUSERNAME) || + CURL_EASY_STR(data, STRING_PROXYPASSWORD) || + CURL_EASY_STR(data, STRING_PROXY_SERVICE_NAME))) { + /* No user/passwd in URL, if this is not a pre-proxy, the + * CURLOPT_PROXY* settings apply. */ + result = Curl_creds_create(CURL_EASY_STR(data, STRING_PROXYUSERNAME), + CURL_EASY_STR(data, STRING_PROXYPASSWORD), + NULL, NULL, + CURL_EASY_STR(data, STRING_PROXY_SERVICE_NAME), + CREDS_OPTION, &proxyinfo->creds); + } + else + Curl_creds_unlink(&proxyinfo->creds); + + proxyinfo->proxytype = proxytype; + +error: + curlx_free(scheme); + curlx_free(proxyuser); + curlx_free(proxypasswd); + curl_url_cleanup(uhp); +#ifdef DEBUGBUILD + if(!result) { + DEBUGASSERT(proxyinfo); + DEBUGASSERT(proxyinfo->peer); + } +#endif + return result; +} + +/* Is transfer's origin exempted from proxy use? */ +static bool proxy_do_not_proxy(struct Curl_easy *data) +{ + const char *no_proxy; + char *env_no_proxy = NULL; + bool do_not_proxy; + + /* no proxying if the transfer does not use the network */ + if(data->state.origin->scheme->flags & PROTOPT_NONETWORK) + return TRUE; + + no_proxy = CURL_EASY_STR(data, STRING_NOPROXY); + if(!no_proxy) { + const char *p = "no_proxy"; + env_no_proxy = curl_getenv(p); + if(!env_no_proxy) { + p = "NO_PROXY"; + env_no_proxy = curl_getenv(p); + } + if(env_no_proxy) + infof(data, "Uses proxy env variable %s == '%s'", p, env_no_proxy); + no_proxy = env_no_proxy; + } + + do_not_proxy = proxy_check_noproxy(data->state.origin->hostname, no_proxy); + curlx_safefree(env_no_proxy); + return do_not_proxy; +} + +CURLcode Curl_proxy_init_conn(struct Curl_easy *data, + struct connectdata *conn) +{ + char *proxy = NULL; + char *pre_proxy = NULL; + const char *str = NULL; + bool do_env_detect = TRUE; + CURLcode result = CURLE_OK; + + /* Enforce no proxy use unless we decide to use one */ + conn->bits.origin_is_proxy = FALSE; + DEBUGASSERT(!conn->socks_proxy.peer); + DEBUGASSERT(!conn->http_proxy.peer); + + if(proxy_do_not_proxy(data)) + goto out; + + /************************************************************* + * Detect what (if any) proxy to use + *************************************************************/ + /* the empty config strings disable proxy use and env detects */ + str = CURL_EASY_STR(data, STRING_PROXY); + if(str) { + if(*str) { + proxy = curlx_strdup(str); + /* if global proxy is set, this is it */ + if(!proxy) { + failf(data, "memory shortage"); + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + else + do_env_detect = FALSE; + } + + str = CURL_EASY_STR(data, STRING_PRE_PROXY); + if(str) { + if(*str) { + pre_proxy = curlx_strdup(str); + /* if global socks proxy is set, this is it */ + if(!pre_proxy) { + failf(data, "memory shortage"); + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + else + do_env_detect = FALSE; + } + +#ifndef CURL_DISABLE_HTTP + /* None configured, detect possible proxy from environment. */ + if(!proxy && !pre_proxy && do_env_detect) + proxy = proxy_detect_proxy(data, conn->scheme); +#else + (void)do_env_detect; +#endif /* CURL_DISABLE_HTTP */ + + if(!proxy && !pre_proxy) + goto out; + + if(pre_proxy) { + result = parse_proxy(data, pre_proxy, TRUE, &conn->socks_proxy); + if(result) + goto out; + } + + if(proxy) { + result = parse_proxy(data, proxy, FALSE, &conn->http_proxy); + if(result) + goto out; + + switch(conn->http_proxy.proxytype) { + case CURLPROXY_SOCKS4: + case CURLPROXY_SOCKS4A: + case CURLPROXY_SOCKS5: + case CURLPROXY_SOCKS5_HOSTNAME: + /* Whoops, it is not an HTTP proxy */ + if(pre_proxy) { + /* and we already have a SOCKS pre-proxy. Cannot have both */ + failf(data, "Having a SOCKS pre-proxy and proxy is not " + "supported with \'%s\'", proxy); + result = CURLE_COULDNT_RESOLVE_PROXY; + goto out; + } + /* switch */ + conn->socks_proxy = conn->http_proxy; + memset(&conn->http_proxy, 0, sizeof(conn->http_proxy)); + break; + default: + /* all other types are HTTP */ + break; + } + } + + if(conn->socks_proxy.peer) { + DEBUGASSERT(!CURL_PROXY_IS_ANY_HTTP(conn->socks_proxy.proxytype)); + } + +#ifdef CURL_DISABLE_HTTP + if(conn->http_proxy.peer) { + /* asking for an HTTP proxy is a bit funny when HTTP is disabled... */ + result = CURLE_UNSUPPORTED_PROTOCOL; + goto out; + } + +#else /* CURL_DISABLE_HTTP */ + if(conn->http_proxy.peer) { + const struct Curl_scheme *scheme = data->state.origin->scheme; + bool tunnel_proxy = (bool)data->set.tunnel_thru_httpproxy; + DEBUGASSERT(CURL_PROXY_IS_ANY_HTTP(conn->http_proxy.proxytype)); + + if(!tunnel_proxy) { + /* Decide if we tunnel through proxy automatically */ + if(conn->via_peer) { + /* With connect-to, we always tunnel */ + tunnel_proxy = TRUE; + } + else if(scheme->flags & PROTOPT_SSL) { + /* If the transfer is supposed to be secure, we tunnel */ + tunnel_proxy = TRUE; + } + else if(scheme->flags & PROTOPT_HTTP_PROXY_TUNNEL) { + /* transfer scheme required tunneling */ + tunnel_proxy = TRUE; + } + else if(!(scheme->protocol & PROTO_FAMILY_HTTP) && + !(scheme->flags & PROTOPT_PROXY_AS_HTTP)) { + /* Cannot delegate transfer URL to HTTP proxy */ + tunnel_proxy = TRUE; + } + } + + if(!tunnel_proxy) { + /* HTTP proxy used in forwarding mode. This means the connection + * is really to the proxy and NOT the origin of the transfer. */ + DEBUGASSERT(!conn->via_peer); + Curl_peer_link(&conn->origin, conn->http_proxy.peer); + conn->scheme = conn->http_proxy.peer->scheme; + conn->bits.origin_is_proxy = TRUE; + } + +#ifndef CURL_DISABLE_DIGEST_AUTH + if(!Curl_safecmp(data->state.envproxy, proxy)) { + /* proxy changed */ + Curl_auth_digest_cleanup(&data->state.proxydigest); + curlx_free(data->state.envproxy); + data->state.envproxy = curlx_strdup(proxy); + } +#endif + } +#endif /* !CURL_DISABLE_HTTP */ + +out: + curlx_free(pre_proxy); + curlx_free(proxy); + return result; +} + +#endif /* CURL_DISABLE_PROXY */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/proxy.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/proxy.h new file mode 100644 index 0000000000..307ee003e6 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/proxy.h @@ -0,0 +1,59 @@ +#ifndef HEADER_CURL_PROXY_H +#define HEADER_CURL_PROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_PROXY + +struct Curl_easy; +struct Curl_peer; +struct Curl_creds; +struct connectdata; + +struct proxy_info { + struct Curl_peer *peer; /* proxy to this peer */ + struct Curl_creds *creds; /* use these credentials, maybe NULL */ + uint8_t proxytype; /* what kind of proxy that is in use */ +}; + +#define CURL_PROXY_IS_HTTPS(t) \ + (((t) == CURLPROXY_HTTPS) || \ + ((t) == CURLPROXY_HTTPS2) || \ + ((t) == CURLPROXY_HTTPS3)) + +#define CURL_PROXY_IS_HTTP(t) \ + (((t) == CURLPROXY_HTTP) || \ + ((t) == CURLPROXY_HTTP_1_0)) + +#define CURL_PROXY_IS_ANY_HTTP(t) \ + (CURL_PROXY_IS_HTTP(t) || \ + CURL_PROXY_IS_HTTPS(t)) + +CURLcode Curl_proxy_init_conn(struct Curl_easy *data, + struct connectdata *conn); + +#endif /* !CURL_DISABLE_PROXY */ + +#endif /* HEADER_CURL_PROXY_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/psl.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/psl.c new file mode 100644 index 0000000000..1e3efbb0fa --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/psl.c @@ -0,0 +1,104 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_LIBPSL + +#include "psl.h" +#include "progress.h" +#include "curl_share.h" + +#if !defined(PSL_VERSION_NUMBER) || PSL_VERSION_NUMBER < 0x001000 +#error "libpsl 0.16.0 or greater required" +#endif + +void Curl_psl_destroy(struct PslCache *pslcache) +{ + if(pslcache->psl) { + if(pslcache->dynamic) + psl_free((psl_ctx_t *)CURL_UNCONST(pslcache->psl)); + pslcache->psl = NULL; + pslcache->dynamic = FALSE; + } +} + +const psl_ctx_t *Curl_psl_use(struct Curl_easy *easy) +{ + struct PslCache *pslcache = easy->psl; + const psl_ctx_t *psl; + time_t now_sec; + + if(!pslcache) + return NULL; + + Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SHARED); + now_sec = Curl_pgrs_now(easy)->tv_sec; + if(!pslcache->psl || pslcache->expires <= now_sec) { + /* Release the shared lock so another thread can refresh the cache and + avoid deadlock. */ + Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); + + /* Update cache: this needs an exclusive lock. */ + Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SINGLE); + + /* Recheck in case another thread did the job. */ + if(pslcache->expires <= now_sec) { + now_sec = Curl_pgrs_now(easy)->tv_sec; + } + if(!pslcache->psl || pslcache->expires <= now_sec) { + bool dynamic = FALSE; + time_t expires = TIME_T_MAX; + + psl = psl_latest(NULL); + dynamic = !!psl; + /* Take care of possible time computation overflow. */ + expires = (now_sec < TIME_T_MAX - PSL_TTL) ? + (now_sec + PSL_TTL) : TIME_T_MAX; + + /* Only get the built-in PSL if we do not already have the "latest". */ + if(!psl && !pslcache->dynamic) + psl = psl_builtin(); + + if(psl) { + Curl_psl_destroy(pslcache); + pslcache->psl = psl; + pslcache->dynamic = dynamic; + pslcache->expires = expires; + } + } + Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); /* Release exclusive lock. */ + Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SHARED); + } + psl = pslcache->psl; + if(!psl) + Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); + return psl; +} + +void Curl_psl_release(struct Curl_easy *easy) +{ + Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); +} + +#endif /* USE_LIBPSL */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/psl.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/psl.h new file mode 100644 index 0000000000..97871f9634 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/psl.h @@ -0,0 +1,51 @@ +#ifndef HEADER_PSL_H +#define HEADER_PSL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifdef USE_LIBPSL + +#include <libpsl.h> + +struct Curl_easy; + +#define PSL_TTL (72 * 3600) /* PSL time to live before a refresh. */ + +struct PslCache { + const psl_ctx_t *psl; /* The PSL. */ + time_t expires; /* Time this PSL life expires. */ + BIT(dynamic); /* PSL should be released when no longer needed. */ +}; + +const psl_ctx_t *Curl_psl_use(struct Curl_easy *easy); +void Curl_psl_release(struct Curl_easy *easy); +void Curl_psl_destroy(struct PslCache *pslcache); + +#else + +#define Curl_psl_use(easy) NULL +#define Curl_psl_release(easy) +#define Curl_psl_destroy(pslcache) + +#endif /* USE_LIBPSL */ +#endif /* HEADER_PSL_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/rand.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/rand.c new file mode 100644 index 0000000000..d0527aa3c0 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/rand.c @@ -0,0 +1,230 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif + +#include "urldata.h" +#include "vtls/vtls.h" +#include "curl_trc.h" +#include "rand.h" +#include "escape.h" + +#include "curlx/winapi.h" + +#ifndef USE_SSL +/* ---- possibly non-cryptographic version following ---- */ +static CURLcode weak_random(struct Curl_easy *data, + unsigned char *entropy, + size_t length) /* always 4, size of int */ +{ + unsigned int r; + DEBUGASSERT(length == sizeof(int)); + + /* Trying cryptographically secure functions first */ +#ifdef _WIN32 + (void)data; + { + CURLcode result = curlx_win32_random(entropy, length); + if(result != CURLE_NOT_BUILT_IN) + return result; + } +#endif + +#ifdef HAVE_ARC4RANDOM + (void)data; + r = (unsigned int)arc4random(); + memcpy(entropy, &r, length); +#else + infof(data, "WARNING: using weak random seed"); + { + static unsigned int randseed; + static bool seeded = FALSE; + unsigned int rnd; + if(!seeded) { + struct curltime now; + curlx_pnow(&now); + randseed += (unsigned int)now.tv_usec + (unsigned int)now.tv_sec; + randseed = randseed * 1103515245 + 12345; + randseed = randseed * 1103515245 + 12345; + randseed = randseed * 1103515245 + 12345; + seeded = TRUE; + } + + /* Return an unsigned 32-bit pseudo-random number. */ + r = randseed = randseed * 1103515245 + 12345; + rnd = (r << 16) | ((r >> 16) & 0xFFFF); + memcpy(entropy, &rnd, length); + } +#endif + return CURLE_OK; +} +#endif + +static CURLcode randit(struct Curl_easy *data, unsigned int *rnd, + bool env_override) +{ +#ifdef DEBUGBUILD + if(env_override) { + char *force_entropy = getenv("CURL_ENTROPY"); + if(force_entropy) { + static unsigned int randseed; + static bool seeded = FALSE; + + if(!seeded) { + unsigned int seed = 0; + size_t elen = strlen(force_entropy); + size_t clen = sizeof(seed); + size_t min = elen < clen ? elen : clen; + memcpy((char *)&seed, force_entropy, min); + randseed = ntohl(seed); + seeded = TRUE; + } + else + randseed++; + *rnd = randseed; + return CURLE_OK; + } + } +#else + (void)env_override; +#endif + + /* data may be NULL! */ +#ifdef USE_SSL + return Curl_ssl_random(data, (unsigned char *)rnd, sizeof(*rnd)); +#else + return weak_random(data, (unsigned char *)rnd, sizeof(*rnd)); +#endif +} + +/* + * Curl_rand() stores 'num' number of random unsigned characters in the buffer + * 'rnd' points to. + * + * If libcurl is built without TLS support or arc4random, this function will + * use "weak" random. + * + * When built *with* TLS support, it will return error if it cannot provide + * strong random values. + * + * NOTE: 'data' may be passed in as NULL when coming from external API without + * easy handle! + * + */ + +CURLcode Curl_rand_bytes(struct Curl_easy *data, +#ifdef DEBUGBUILD + bool env_override, +#endif + unsigned char *rnd, size_t num) +{ + CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT; +#ifndef DEBUGBUILD + const bool env_override = FALSE; +#endif + + DEBUGASSERT(num); + + while(num) { + unsigned int r; + size_t left = num < sizeof(unsigned int) ? num : sizeof(unsigned int); + + result = randit(data, &r, env_override); + if(result) + return result; + + while(left) { + *rnd++ = (unsigned char)(r & 0xFF); + r >>= 8; + --num; + --left; + } + } + + return result; +} + +/* + * Curl_rand_hex() fills the 'rnd' buffer with a given 'num' size with random + * hexadecimal digits PLUS a null-terminator byte. It must be an odd number + * size. + */ + +CURLcode Curl_rand_hex(struct Curl_easy *data, unsigned char *rnd, size_t num) +{ + CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT; + unsigned char buffer[128]; + DEBUGASSERT(num > 1); + + if((num / 2 >= sizeof(buffer)) || !(num & 1)) { + /* make sure it fits in the local buffer and that it is an odd number! */ + DEBUGF(infof(data, "invalid buffer size with Curl_rand_hex")); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + num--; /* save one for null-termination */ + + result = Curl_rand(data, buffer, num / 2); + if(result) + return result; + + Curl_hexencode(buffer, num / 2, rnd, num + 1); + return result; +} + +/* + * Curl_rand_alnum() fills the 'rnd' buffer with a given 'num' size with random + * alphanumerical chars PLUS a null-terminator byte. + */ + +static const char alnum[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + +CURLcode Curl_rand_alnum(struct Curl_easy *data, unsigned char *rnd, + size_t num) +{ + CURLcode result = CURLE_OK; + const unsigned int alnumspace = CURL_CSTRLEN(alnum); + unsigned int r; + DEBUGASSERT(num > 1); + + num--; /* save one for null-termination */ + + while(num) { + do { + result = randit(data, &r, TRUE); + if(result) + return result; + } while(r >= (UINT_MAX - UINT_MAX % alnumspace)); + + *rnd++ = (unsigned char)alnum[r % alnumspace]; + num--; + } + *rnd = 0; + + return result; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/rand.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/rand.h new file mode 100644 index 0000000000..452c1b67ef --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/rand.h @@ -0,0 +1,52 @@ +#ifndef HEADER_CURL_RAND_H +#define HEADER_CURL_RAND_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +CURLcode Curl_rand_bytes(struct Curl_easy *data, +#ifdef DEBUGBUILD + bool env_override, +#endif + unsigned char *rnd, size_t num); + +#ifdef DEBUGBUILD +#define Curl_rand(a, b, c) Curl_rand_bytes(a, TRUE, b, c) +#else +#define Curl_rand(a, b, c) Curl_rand_bytes(a, b, c) +#endif + +/* + * Curl_rand_hex() fills the 'rnd' buffer with a given 'num' size with random + * hexadecimal digits PLUS a null-terminator byte. It must be an odd number + * size. + */ +CURLcode Curl_rand_hex(struct Curl_easy *data, unsigned char *rnd, size_t num); + +/* + * Curl_rand_alnum() fills the 'rnd' buffer with a given 'num' size with random + * alphanumerical chars PLUS a null-terminator byte. + */ +CURLcode Curl_rand_alnum(struct Curl_easy *data, unsigned char *rnd, + size_t num); + +#endif /* HEADER_CURL_RAND_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/ratelimit.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ratelimit.c new file mode 100644 index 0000000000..a5efc7c11a --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ratelimit.c @@ -0,0 +1,306 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "ratelimit.h" + +#define CURL_US_PER_SEC 1000000 +#define CURL_RLIMIT_MIN_RATE (4 * 1024) /* minimum step rate */ +#define CURL_RLIMIT_STEP_MIN_MS 2 /* minimum step duration */ + +static void rlimit_update(struct Curl_rlimit *r, + const struct curltime *pts) +{ + timediff_t elapsed_us, elapsed_steps; + int64_t token_gain; + + DEBUGASSERT(r->rate_per_step); + if((r->ts.tv_sec == pts->tv_sec) && (r->ts.tv_usec == pts->tv_usec)) + return; + + elapsed_us = curlx_ptimediff_us(pts, &r->ts); + if(elapsed_us < 0) { /* not going back in time */ + DEBUGASSERT(0); + return; + } + + elapsed_us += r->spare_us; + if(elapsed_us < r->step_us) + return; + + /* we do the update */ + r->ts = *pts; + elapsed_steps = elapsed_us / r->step_us; + r->spare_us = elapsed_us % r->step_us; + + /* How many tokens did we gain since the last update? */ + if(r->rate_per_step > (INT64_MAX / elapsed_steps)) + token_gain = INT64_MAX; + else { + token_gain = r->rate_per_step * elapsed_steps; + } + + if((INT64_MAX - token_gain) > r->tokens) + r->tokens += token_gain; + else + r->tokens = INT64_MAX; + + /* Limit the token again by the burst rate (if set), so we + * do not suddenly have a huge number of tokens after inactivity. */ + if(r->burst_per_step && (r->tokens > r->burst_per_step)) { + r->tokens = r->burst_per_step; + } +} + +static void rlimit_tune_steps(struct Curl_rlimit *r, + int64_t tokens_total) +{ + int64_t tokens_last, tokens_main, msteps; + + /* Tune the ratelimit at the start *if* we know how many tokens + * are expected to be consumed in total. + * The reason for tuning is that rlimit provides tokens to be consumed + * per "step" which starts out to be a second. The tokens may be consumed + * in full at the beginning of a step. The remainder of the second will + * have no tokens available, effectively blocking the consumption and + * so keeping the "step average" in line. + * This works will up to the last step. When no more tokens are needed, + * no wait will happen and the last step would be too fast. This is + * especially noticeable when only a few steps are needed. + * + * Example: downloading 1.5kb with a ratelimit of 1k could be done in + * roughly 1 second (1k in the first second and the 0.5 at the start of + * the second one). + * + * The tuning tries to make the last step small, using only + * 1 percent of the total tokens (at least 1). The rest of the tokens + * are to be consumed in the steps before by adjusting the duration of + * the step and the amount of tokens it provides. */ + if(!r->rate_per_step || + (tokens_total <= 1) || + (tokens_total > (INT64_MAX / 1000))) + return; + + /* Calculate tokens for the last step and the ones before. */ + tokens_last = tokens_total / 100; + if(!tokens_last) /* less than 100 total, use 1 */ + tokens_last = 1; + else if(tokens_last > CURL_RLIMIT_MIN_RATE) + tokens_last = CURL_RLIMIT_MIN_RATE; + DEBUGASSERT(tokens_last); + tokens_main = tokens_total - tokens_last; + DEBUGASSERT(tokens_main); + + /* how many milli-steps will it take to consume those, give the + * original rate limit per second? */ + DEBUGASSERT(r->step_us == CURL_US_PER_SEC); + + msteps = (tokens_main * 1000 / r->rate_per_step); + if(msteps < CURL_RLIMIT_STEP_MIN_MS) { + /* Steps this small will not work. Do not tune. */ + return; + } + else if(msteps < 1000) { + /* It needs less than one step to provide the needed tokens. + * Make it exactly that long and with exactly those tokens. */ + r->step_us = (timediff_t)msteps * 1000; + r->rate_per_step = tokens_main; + r->tokens = r->rate_per_step; + } + else { + /* More than 1 step. Spread the remainder milli steps and + * the tokens they need to provide across all steps. If integer + * arithmetic can do it. */ + curl_off_t ms_unaccounted = (msteps % 1000); + curl_off_t mstep_inc = (ms_unaccounted / (msteps / 1000)); + if(mstep_inc) { + curl_off_t rate_inc = ((r->rate_per_step * mstep_inc) / 1000); + if(rate_inc) { + r->step_us = CURL_US_PER_SEC + ((timediff_t)mstep_inc * 1000); + r->rate_per_step += rate_inc; + r->tokens = r->rate_per_step; + if(r->burst_per_step) { + curl_off_t burst_inc = ((r->burst_per_step * mstep_inc) / 1000); + if(burst_inc) + r->burst_per_step += burst_inc; + } + } + } + } +} + +void Curl_rlimit_init(struct Curl_rlimit *r, + int64_t rate_per_sec, + int64_t burst_per_sec, + const struct curltime *pts) +{ + DEBUGASSERT(rate_per_sec >= 0); + DEBUGASSERT(burst_per_sec >= rate_per_sec || !burst_per_sec); + DEBUGASSERT(pts); + r->rate_per_step = r->rate_per_sec = rate_per_sec; + r->burst_per_step = r->burst_per_sec = burst_per_sec; + r->step_us = CURL_US_PER_SEC; + r->spare_us = 0; + r->tokens = r->rate_per_step; + r->ts = *pts; + r->blocked = FALSE; +} + +void Curl_rlimit_start(struct Curl_rlimit *r, const struct curltime *pts, + int64_t total_tokens) +{ + /* A start always resets the values to initial defaults, then + * fine tunes the intervals for the total_tokens expected. */ + r->rate_per_step = r->rate_per_sec; + r->burst_per_step = r->burst_per_sec; + r->step_us = CURL_US_PER_SEC; + r->spare_us = 0; + r->tokens = r->rate_per_step; + r->ts = *pts; + rlimit_tune_steps(r, total_tokens); +} + +int64_t Curl_rlimit_per_step(struct Curl_rlimit *r) +{ + return r->rate_per_step; +} + +bool Curl_rlimit_active(struct Curl_rlimit *r) +{ + return (r->rate_per_step > 0) || r->blocked; +} + +bool Curl_rlimit_is_blocked(struct Curl_rlimit *r) +{ + return (bool)r->blocked; +} + +int64_t Curl_rlimit_avail(struct Curl_rlimit *r, + const struct curltime *pts) +{ + struct curltime ts; + + if(r->blocked) + return 0; + else if(r->rate_per_step) { + if(!pts) { + curlx_pnow(&ts); + pts = &ts; + } + rlimit_update(r, pts); + return r->tokens; + } + else + return INT64_MAX; +} + +void Curl_rlimit_drain(struct Curl_rlimit *r, size_t tokens, + const struct curltime *pts) +{ + struct curltime ts; + + if(r->blocked || !r->rate_per_step) + return; + + if(!pts) { + curlx_pnow(&ts); + pts = &ts; + } + rlimit_update(r, pts); +#if 8 <= SIZEOF_SIZE_T + if(tokens > INT64_MAX) { + r->tokens = INT64_MAX; + } + else +#endif + { + int64_t val = (int64_t)tokens; + if((INT64_MIN + val) < r->tokens) + r->tokens -= val; + else + r->tokens = INT64_MIN; + } +} + +timediff_t Curl_rlimit_wait_ms(struct Curl_rlimit *r, + const struct curltime *pts) +{ + timediff_t wait_us, elapsed_us; + + if(r->blocked || !r->rate_per_step) + return 0; + rlimit_update(r, pts); + if(r->tokens > 0) + return 0; + + /* How much time will it take tokens to become positive again? + * Deduct `spare_us` and check against already elapsed time */ + wait_us = r->step_us - r->spare_us; + if(r->tokens < 0) { + curl_off_t debt_pct = ((-r->tokens) * 100 / r->rate_per_step); + if(debt_pct) + wait_us += (r->step_us * debt_pct / 100); + } + + elapsed_us = curlx_ptimediff_us(pts, &r->ts); + if(elapsed_us >= wait_us) + return 0; + wait_us -= elapsed_us; + return (wait_us + 999) / 1000; /* in milliseconds */ +} + +timediff_t Curl_rlimit_next_step_ms(struct Curl_rlimit *r, + const struct curltime *pts) +{ + if(!r->blocked && r->rate_per_step) { + timediff_t elapsed_us, next_us; + + elapsed_us = curlx_ptimediff_us(pts, &r->ts) + r->spare_us; + if(r->step_us > elapsed_us) { + next_us = r->step_us - elapsed_us; + return (next_us + 999) / 1000; /* in milliseconds */ + } + } + return 0; +} + +void Curl_rlimit_block(struct Curl_rlimit *r, + bool activate, + const struct curltime *pts) +{ + if(!activate == !r->blocked) + return; + + r->ts = *pts; + r->blocked = activate; + if(!r->blocked) { + /* Start rate limiting fresh. The amount of time this was blocked + * does not generate extra tokens. */ + Curl_rlimit_start(r, pts, -1); + } + else { + r->tokens = 0; + } +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/ratelimit.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ratelimit.h new file mode 100644 index 0000000000..3548f55608 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ratelimit.h @@ -0,0 +1,109 @@ +#ifndef HEADER_CURL_RLIMIT_H +#define HEADER_CURL_RLIMIT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curlx/timeval.h" + +struct Curl_easy; + +/* This is a rate limiter that provides "tokens" to be consumed + * per second. In the literature, this is referred to as a + * "token bucket" (https://en.wikipedia.org/wiki/Token_bucket). + * Example: + * A rate limit of 1 megabyte per second. + * - initially 1 million tokens are available. + * - these are drained in the first second. + * - checking available tokens before the 2nd second will return 0. + * - at/after the 2nd second, 1 million tokens are available again. + * - nothing happens for a second, the 1 million tokens would grow + * to 2 million, however the burst limit caps those at 1.5 million. + * Thus: + * - setting "burst" to CURL_OFF_T_MAX would average tokens over the + * complete lifetime. E.g. for a download, at the *end* of it, the + * average rate from start to finish would be the rate limit. + * - setting "burst" to the same value as "rate" would make a + * download always try to stay *at/below* the rate and slow times will + * not generate extra tokens. + * + * A rate limit can be blocked, causing the available tokens to become + * always 0 until unblocked. After unblocking, the rate limiting starts + * again with no history of the past. + * + * Finally, a rate limiter with rate 0 will always have CURL_OFF_T_MAX + * tokens available, unless blocked. + */ + +struct Curl_rlimit { + int64_t rate_per_sec; /* rate tokens generated per second */ + int64_t burst_per_sec; /* burst rate of tokens per second */ + int64_t rate_per_step; /* rate tokens generated per step us */ + int64_t burst_per_step; /* burst rate of tokens per step us */ + timediff_t step_us; /* microseconds between token increases */ + int64_t tokens; /* tokens available in the next second */ + timediff_t spare_us; /* microseconds unaffecting tokens */ + struct curltime ts; /* time of the last update */ + BIT(blocked); /* blocking sets available tokens to 0 */ +}; + +void Curl_rlimit_init(struct Curl_rlimit *r, + int64_t rate_per_sec, + int64_t burst_per_sec, + const struct curltime *pts); + +/* Start ratelimiting with the given timestamp. Resets available tokens. + * `total_tokens` is either -1 or the number of total tokens expected + * to be consumed. */ +void Curl_rlimit_start(struct Curl_rlimit *r, const struct curltime *pts, + int64_t total_tokens); + +/* How many milliseconds to wait until token are available again. */ +timediff_t Curl_rlimit_wait_ms(struct Curl_rlimit *r, + const struct curltime *pts); + +/* When the rate limit will update its tokens again */ +timediff_t Curl_rlimit_next_step_ms(struct Curl_rlimit *r, + const struct curltime *pts); + +/* Return if rate limiting of tokens is active */ +bool Curl_rlimit_active(struct Curl_rlimit *r); +bool Curl_rlimit_is_blocked(struct Curl_rlimit *r); +int64_t Curl_rlimit_per_step(struct Curl_rlimit *r); + +/* Return how many tokens are available to spend, may be negative. + * Pass timestamp or NULL. */ +int64_t Curl_rlimit_avail(struct Curl_rlimit *r, + const struct curltime *pts); + +/* Drain tokens from the ratelimit, give an estimate of how many tokens + * remain to be drained in the future (-1 for unknown). + * Pass timestamp or NULL. */ +void Curl_rlimit_drain(struct Curl_rlimit *r, size_t tokens, + const struct curltime *pts); + +/* Block/unblock ratelimiting. A blocked ratelimit has 0 tokens available. */ +void Curl_rlimit_block(struct Curl_rlimit *r, + bool activate, + const struct curltime *pts); + +#endif /* HEADER_CURL_RLIMIT_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/request.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/request.c new file mode 100644 index 0000000000..51672bfe00 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/request.c @@ -0,0 +1,502 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "cfilters.h" +#include "curlx/dynbuf.h" +#include "progress.h" +#include "request.h" +#include "sendf.h" +#include "curl_trc.h" +#include "transfer.h" +#include "url.h" +#include "curlx/strparse.h" + +void Curl_req_init(struct SingleRequest *req) +{ + memset(req, 0, sizeof(*req)); +} + +CURLcode Curl_req_soft_reset(struct SingleRequest *req, + struct Curl_easy *data) +{ + CURLcode result; + + req->done = FALSE; + req->upload_done = FALSE; + req->upload_aborted = FALSE; + req->download_done = FALSE; + req->eos_written = FALSE; + req->eos_read = FALSE; + req->eos_sent = FALSE; + req->ignorebody = FALSE; + req->shutdown = FALSE; + req->bytecount = 0; + req->writebytecount = 0; + req->header = FALSE; + req->headerline = 0; + req->headerbytecount = 0; + req->allheadercount = 0; + req->deductheadercount = 0; + req->httpversion_sent = 0; + req->httpversion = 0; + req->sendbuf_hds_len = 0; + + curlx_safefree(req->hd_auth); +#ifndef CURL_DISABLE_PROXY + curlx_safefree(req->hd_proxy_auth); +#endif + + result = Curl_client_start(data); + if(result) + return result; + + if(!req->sendbuf_init) { + Curl_bufq_init2(&req->sendbuf, data->set.upload_buffer_size, 1, + BUFQ_OPT_SOFT_LIMIT); + req->sendbuf_init = TRUE; + } + else { + Curl_bufq_reset(&req->sendbuf); + if(data->set.upload_buffer_size != req->sendbuf.chunk_size) { + Curl_bufq_free(&req->sendbuf); + Curl_bufq_init2(&req->sendbuf, data->set.upload_buffer_size, 1, + BUFQ_OPT_SOFT_LIMIT); + } + } + + return CURLE_OK; +} + +CURLcode Curl_req_start(struct SingleRequest *req, + struct Curl_easy *data) +{ + req->start = *Curl_pgrs_now(data); + return Curl_req_soft_reset(req, data); +} + +static CURLcode req_flush(struct Curl_easy *data); + +CURLcode Curl_req_done(struct SingleRequest *req, + struct Curl_easy *data, bool aborted) +{ + (void)req; + if(!aborted) + (void)req_flush(data); + Curl_client_reset(data); + return CURLE_OK; +} + +void Curl_req_hard_reset(struct SingleRequest *req, struct Curl_easy *data) +{ + struct curltime t0 = { 0, 0 }; + + curlx_safefree(req->newurl); + curlx_safefree(req->hd_auth); +#ifndef CURL_DISABLE_PROXY + curlx_safefree(req->hd_proxy_auth); +#endif +#ifndef CURL_DISABLE_COOKIES + curlx_safefree(req->cookiehost); +#endif + Curl_client_reset(data); + if(req->sendbuf_init) + Curl_bufq_reset(&req->sendbuf); + + /* clear any resolve data */ + Curl_resolv_destroy_all(data); + /* Can no longer memset() this struct as we need to keep some state */ + req->size = -1; + req->maxdownload = -1; + req->bytecount = 0; + req->writebytecount = 0; + req->start = t0; + req->headerbytecount = 0; + req->allheadercount = 0; + req->deductheadercount = 0; + req->headerline = 0; + req->offset = 0; + req->httpcode = 0; + req->io_flags = 0; + req->upgr101 = UPGR101_NONE; + req->sendbuf_hds_len = 0; + req->timeofdoc = 0; + req->location = NULL; + req->newurl = NULL; +#ifndef CURL_DISABLE_COOKIES + req->setcookies = 0; +#endif + req->header = FALSE; + req->content_range = FALSE; + req->download_done = FALSE; + req->eos_written = FALSE; + req->eos_read = FALSE; + req->eos_sent = FALSE; + req->rewind_read = FALSE; + req->upload_done = FALSE; + req->upload_aborted = FALSE; + req->ignorebody = FALSE; + req->http_bodyless = FALSE; + req->chunk = FALSE; + req->resp_trailer = FALSE; + req->ignore_cl = FALSE; + req->upload_chunky = FALSE; + req->no_body = data->set.opt_no_body; + req->authneg = FALSE; + req->shutdown = FALSE; + /* Unpause all directions */ + Curl_rlimit_block(&data->progress.dl.rlimit, FALSE, &t0); + Curl_rlimit_block(&data->progress.ul.rlimit, FALSE, &t0); +} + +void Curl_req_free(struct SingleRequest *req, struct Curl_easy *data) +{ + curlx_safefree(req->newurl); + curlx_safefree(req->hd_auth); +#ifndef CURL_DISABLE_PROXY + curlx_safefree(req->hd_proxy_auth); +#endif + if(req->sendbuf_init) + Curl_bufq_free(&req->sendbuf); + Curl_client_cleanup(data); +} + +static CURLcode xfer_send(struct Curl_easy *data, + const char *buf, size_t blen, + size_t hds_len, size_t *pnwritten) +{ + CURLcode result = CURLE_OK; + bool eos = FALSE; + + *pnwritten = 0; + DEBUGASSERT(hds_len <= blen); +#ifdef DEBUGBUILD + { + /* Allow debug builds to override this logic to force short initial + sends */ + size_t body_len = blen - hds_len; + if(body_len) { + const char *p = getenv("CURL_SMALLREQSEND"); + if(p) { + curl_off_t body_small; + if(!curlx_str_number(&p, &body_small, body_len)) + blen = hds_len + (size_t)body_small; + } + } + } +#endif + /* Make sure this does not send more body bytes than what the max send + speed says. The headers do not count to the max speed. */ + if(data->set.max_send_speed) { + size_t body_bytes = blen - hds_len; + if((curl_off_t)body_bytes > data->set.max_send_speed) + blen = hds_len + (size_t)data->set.max_send_speed; + } + + if(data->req.eos_read && + (Curl_bufq_is_empty(&data->req.sendbuf) || + Curl_bufq_len(&data->req.sendbuf) == blen)) { + DEBUGF(infof(data, "sending last upload chunk of %zu bytes", blen)); + eos = TRUE; + } + result = Curl_xfer_send(data, buf, blen, eos, pnwritten); + if(!result) { + if(eos && (blen == *pnwritten)) + data->req.eos_sent = TRUE; + if(*pnwritten) { + if(hds_len) + Curl_debug(data, CURLINFO_HEADER_OUT, buf, + CURLMIN(hds_len, *pnwritten)); + if(*pnwritten > hds_len) { + size_t body_len = *pnwritten - hds_len; + Curl_debug(data, CURLINFO_DATA_OUT, buf + hds_len, body_len); + data->req.writebytecount += body_len; + Curl_pgrs_upload_inc(data, body_len); + } + } + } + return result; +} + +static CURLcode req_send_buffer_flush(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + const unsigned char *buf; + size_t blen; + + while(Curl_bufq_peek(&data->req.sendbuf, &buf, &blen)) { + size_t nwritten, hds_len = CURLMIN(data->req.sendbuf_hds_len, blen); + result = xfer_send(data, (const char *)buf, blen, hds_len, &nwritten); + if(result) + break; + + Curl_bufq_skip(&data->req.sendbuf, nwritten); + if(hds_len) { + data->req.sendbuf_hds_len -= CURLMIN(hds_len, nwritten); + } + /* leave if we could not send all. Maybe network blocking or + * speed limits on transfer */ + if(nwritten < blen) + break; + } + return result; +} + +static CURLcode req_set_upload_done(struct Curl_easy *data) +{ + DEBUGASSERT(!data->req.upload_done); + data->req.upload_done = TRUE; + CURL_REQ_CLEAR_SEND(data); + + if(data->mstate >= MSTATE_DID) + Curl_pgrsTime(data, TIMER_POSTRANSFER); + Curl_creader_done(data, data->req.upload_aborted); + + if(data->req.upload_aborted) { + Curl_bufq_reset(&data->req.sendbuf); + if(data->req.writebytecount) + infof(data, "abort upload after having sent %" FMT_OFF_T " bytes", + data->req.writebytecount); + else + infof(data, "abort upload"); + } + else if(data->req.writebytecount) + infof(data, "upload completely sent off: %" FMT_OFF_T " bytes", + data->req.writebytecount); + else if(!data->req.download_done) { + DEBUGASSERT(Curl_bufq_is_empty(&data->req.sendbuf)); + infof(data, Curl_creader_total_length(data) ? + "We are completely uploaded and fine" : + "Request completely sent off"); + } + + return Curl_xfer_send_close(data); +} + +static CURLcode req_flush(struct Curl_easy *data) +{ + CURLcode result; + + if(!data || !data->conn) + return CURLE_FAILED_INIT; + + if(!Curl_bufq_is_empty(&data->req.sendbuf)) { + result = req_send_buffer_flush(data); + if(result) + return result; + if(!Curl_bufq_is_empty(&data->req.sendbuf)) { + DEBUGF(infof(data, "Curl_req_flush(len=%zu) -> EAGAIN", + Curl_bufq_len(&data->req.sendbuf))); + return CURLE_AGAIN; + } + } + else if(Curl_xfer_needs_flush(data)) { + DEBUGF(infof(data, "Curl_req_flush(), xfer send_pending")); + return Curl_xfer_flush(data); + } + + if(data->req.eos_read && !data->req.eos_sent) { + char tmp = 0; + size_t nwritten; + result = xfer_send(data, &tmp, 0, 0, &nwritten); + if(result) + return result; + DEBUGASSERT(data->req.eos_sent); + } + + if(!data->req.upload_done && data->req.eos_read && data->req.eos_sent) { + DEBUGASSERT(Curl_bufq_is_empty(&data->req.sendbuf)); + if(data->req.shutdown) { + bool done; + result = Curl_xfer_send_shutdown(data, &done); + if(result && data->req.shutdown_err_ignore) { + infof(data, "Shutdown send direction error: %d. Broken server? " + "Proceeding as if everything is ok.", (int)result); + result = CURLE_OK; + done = TRUE; + } + + if(result) + return result; + if(!done) + return CURLE_AGAIN; + } + return req_set_upload_done(data); + } + return CURLE_OK; +} + +static CURLcode add_from_client(void *reader_ctx, + unsigned char *buf, size_t buflen, + size_t *pnread) +{ + struct Curl_easy *data = reader_ctx; + CURLcode result; + bool eos; + + result = Curl_client_read(data, (char *)buf, buflen, pnread, &eos); + if(!result && eos) + data->req.eos_read = TRUE; + return result; +} + +static CURLcode req_send_buffer_add(struct Curl_easy *data, + const char *buf, size_t blen, + size_t hds_len) +{ + CURLcode result = CURLE_OK; + size_t n; + result = Curl_bufq_cwrite(&data->req.sendbuf, buf, blen, &n); + if(result) + return result; + /* We rely on a SOFTLIMIT on sendbuf, so it can take all data in */ + DEBUGASSERT(n == blen); + data->req.sendbuf_hds_len += hds_len; + return CURLE_OK; +} + +CURLcode Curl_req_send(struct Curl_easy *data, struct dynbuf *req, + unsigned char httpversion) +{ + CURLcode result; + const char *buf; + size_t blen, nwritten; + + if(!data || !data->conn) + return CURLE_FAILED_INIT; + + data->req.httpversion_sent = httpversion; + buf = curlx_dyn_ptr(req); + blen = curlx_dyn_len(req); + /* if the sendbuf is empty and the request without body and + * the length to send fits info a sendbuf chunk, we send it directly. + * If `blen` is larger than `chunk_size`, we can not. Because we + * might have to retry a blocked send later from sendbuf and that + * would result in retry sends with a shrunken length. That is trouble. */ + if(Curl_bufq_is_empty(&data->req.sendbuf) && + !Curl_creader_total_length(data) && + (blen <= data->req.sendbuf.chunk_size)) { + data->req.eos_read = TRUE; + result = xfer_send(data, buf, blen, blen, &nwritten); + if(result) + return result; + buf += nwritten; + blen -= nwritten; + if(!blen) { + result = req_set_upload_done(data); + if(result) + return result; + } + } + + if(blen) { + /* Either we have a request body, or we could not send the complete + * request in one go. Buffer the remainder and try to add as much + * body bytes as room is left in the buffer. Then flush. */ + result = req_send_buffer_add(data, buf, blen, blen); + if(result) + return result; + + return Curl_req_send_more(data); + } + return CURLE_OK; +} + +bool Curl_req_sendbuf_empty(struct Curl_easy *data) +{ + return !data->req.sendbuf_init || Curl_bufq_is_empty(&data->req.sendbuf); +} + +bool Curl_req_want_send(struct Curl_easy *data) +{ + /* Not done and upload not blocked and either one of + * - REQ_IO_SEND + * - request has buffered data to send + * - connection has pending data to send */ + return !data->req.done && + !Curl_rlimit_is_blocked(&data->progress.ul.rlimit) && + (CURL_REQ_WANT_SEND(data) || + !Curl_req_sendbuf_empty(data) || + Curl_xfer_needs_flush(data)); +} + +bool Curl_req_want_recv(struct Curl_easy *data) +{ + /* Not done and download not blocked and want RECV */ + return !data->req.done && + !Curl_rlimit_is_blocked(&data->progress.dl.rlimit) && + CURL_REQ_WANT_RECV(data); +} + +bool Curl_req_done_sending(struct Curl_easy *data) +{ + return data->req.upload_done && !Curl_req_want_send(data); +} + +CURLcode Curl_req_send_more(struct Curl_easy *data) +{ + CURLcode result; + + /* Fill our send buffer if more from client can be read. */ + if(!data->req.upload_aborted && + !data->req.eos_read && + !Curl_xfer_send_is_paused(data) && + !Curl_bufq_is_full(&data->req.sendbuf)) { + size_t nread; + result = Curl_bufq_sipn(&data->req.sendbuf, 0, + add_from_client, data, &nread); + if(result && result != CURLE_AGAIN) + return result; + } + + result = req_flush(data); + if(result == CURLE_AGAIN) + result = CURLE_OK; + + return result; +} + +CURLcode Curl_req_abort_sending(struct Curl_easy *data) +{ + if(!data->req.upload_done) { + Curl_bufq_reset(&data->req.sendbuf); + data->req.upload_aborted = TRUE; + CURL_REQ_CLEAR_SEND(data); + return req_set_upload_done(data); + } + return CURLE_OK; +} + +CURLcode Curl_req_stop_send_recv(struct Curl_easy *data) +{ + /* stop receiving and ALL sending as well, including PAUSE and HOLD. + * We might still be paused on receive client writes though, so + * keep those bits around. */ + CURLcode result = CURLE_OK; + if(CURL_REQ_WANT_SEND(data)) + result = Curl_req_abort_sending(data); + CURL_REQ_CLEAR_IO(data); + return result; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/request.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/request.h new file mode 100644 index 0000000000..a7c0a93dd3 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/request.h @@ -0,0 +1,256 @@ +#ifndef HEADER_CURL_REQUEST_H +#define HEADER_CURL_REQUEST_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* This file is for lib internal stuff */ +#include "curl_setup.h" + +#include "bufq.h" + +/* forward declarations */ +struct UserDefined; + +/* Bits on the io_flags member of SingleRequest */ +#define REQ_IO_RECV (1 << 0) /* there is or may be data to read */ +#define REQ_IO_SEND (1 << 1) /* there is or may be data to write */ + +/* Low level request receive/send io_flags checks. */ +#define CURL_REQ_WANT_SEND(d) ((d)->req.io_flags & REQ_IO_SEND) +#define CURL_REQ_WANT_RECV(d) ((d)->req.io_flags & REQ_IO_RECV) +#define CURL_REQ_WANT_IO(d) \ + ((d)->req.io_flags & (REQ_IO_RECV | REQ_IO_SEND)) +/* Low level request receive/send io_flags manipulations. */ +#define CURL_REQ_SET_SEND(d) ((d)->req.io_flags |= REQ_IO_SEND) +#define CURL_REQ_SET_RECV(d) ((d)->req.io_flags |= REQ_IO_RECV) +#define CURL_REQ_CLEAR_SEND(d) \ + ((d)->req.io_flags &= (uint8_t)~REQ_IO_SEND) +#define CURL_REQ_CLEAR_RECV(d) \ + ((d)->req.io_flags &= (uint8_t)~REQ_IO_RECV) +#define CURL_REQ_CLEAR_IO(d) \ + ((d)->req.io_flags &= (uint8_t)~(REQ_IO_RECV | REQ_IO_SEND)) + +enum expect100 { + EXP100_SEND_DATA, /* enough waiting, send the body now */ + EXP100_AWAITING_CONTINUE, /* waiting for the 100 Continue header */ + EXP100_SENDING_REQUEST, /* still sending the request but will wait for + the 100 header once done with the request */ + EXP100_FAILED /* used on 417 Expectation Failed */ +}; + +enum upgrade101 { + UPGR101_NONE, /* default state */ + UPGR101_WS, /* upgrade to WebSocket requested */ + UPGR101_H2, /* upgrade to HTTP/2 requested */ + UPGR101_RECEIVED /* 101 response received */ +}; + +/* + * Request specific data in the easy handle (Curl_easy). Previously, + * these members were on the connectdata struct but since a conn struct may + * now be shared between different Curl_easys, we store connection-specific + * data here. This struct only keeps stuff that is interesting for *this* + * request, as it will be cleared between multiple ones + */ +struct SingleRequest { + curl_off_t size; /* -1 if unknown at this point */ + curl_off_t maxdownload; /* in bytes, the maximum amount of data to fetch, + -1 means unlimited */ + curl_off_t bytecount; /* total number of bytes read */ + curl_off_t writebytecount; /* number of bytes written */ + curl_off_t offset; /* possible resume offset read from the + Content-Range: header */ + + struct curltime start; /* transfer started at this time */ + unsigned int headerbytecount; /* received server headers (not CONNECT + headers) */ + unsigned int allheadercount; /* all received headers (server + CONNECT) */ + unsigned int deductheadercount; /* this amount of bytes does not count when + we check if anything has been transferred + at the end of a connection. We use this + counter to make only a 100 reply (without + a following second response code) result + in a CURLE_GOT_NOTHING error code */ + int headerline; /* counts header lines to better track the + first one */ + int httpcode; /* error code from the 'HTTP/1.? XXX' or + 'RTSP/1.? XXX' line */ + uint8_t httpversion_sent; /* Version in request (09, 10, 11, etc.) */ + uint8_t httpversion; /* Version in response (09, 10, 11, etc.) */ + uint8_t upgr101; /* 101 upgrade state */ + uint8_t io_flags; /* REQ_IO_RECV | REQ_IO_SEND */ + + /* Client Writer stack, handles transfer- and content-encodings, protocol + * checks, pausing by client callbacks. */ + struct { + struct Curl_cwriter *stack; + BIT(paused); + } writer; + /* Client Reader stack, handles transfer- and content-encodings, protocol + * checks, pausing by client callbacks. */ + struct { + struct Curl_creader *stack; + } reader; + struct bufq sendbuf; /* data which needs to be send to the server */ + size_t sendbuf_hds_len; /* amount of header bytes in sendbuf */ + time_t timeofdoc; + char *location; /* This points to an allocated version of the Location: + header data */ + char *newurl; /* Set to the new URL to use when a redirect or a retry is + wanted */ + + char *hd_auth; /* Authorization header, full HTTP/1.x line */ +#ifndef CURL_DISABLE_PROXY + char *hd_proxy_auth; /* Proxy-Authorization header, full HTTP/1.x line */ +#endif +#ifndef CURL_DISABLE_COOKIES + char *cookiehost; +#endif +#ifndef CURL_DISABLE_COOKIES + unsigned char setcookies; +#endif + BIT(header); /* incoming data has HTTP header */ + BIT(done); /* request is done, e.g. no more send/recv should + * happen. This can be TRUE before `upload_done` or + * `download_done` is TRUE. */ + BIT(content_range); /* set TRUE if Content-Range: was found */ + BIT(download_done); /* set to TRUE when download is complete */ + BIT(eos_written); /* iff EOS has been written to client */ + BIT(eos_read); /* iff EOS has been read from the client */ + BIT(eos_sent); /* iff EOS has been sent to the server */ + BIT(rewind_read); /* iff reader needs rewind at next start */ + BIT(upload_done); /* set to TRUE when all request data has been sent */ + BIT(upload_aborted); /* set to TRUE when upload was aborted. Also + * shows `upload_done` as TRUE. */ + BIT(ignorebody); /* we read a response-body but we ignore it! */ + BIT(http_bodyless); /* HTTP response status code is between 100 and 199, + 204 or 304 */ + BIT(chunk); /* if set, this is a chunked transfer-encoding */ + BIT(resp_trailer); /* response carried 'Trailer:' header field */ + BIT(ignore_cl); /* ignore content-length */ + BIT(upload_chunky); /* set TRUE if we are doing chunked transfer-encoding + on upload */ + BIT(no_body); /* the response has no body */ + BIT(authneg); /* TRUE when the auth phase has started, which means + that we are creating a request with an auth header, + but it is not the final request in the auth + negotiation. */ + BIT(sendbuf_init); /* sendbuf is initialized */ + BIT(shutdown); /* request end will shutdown connection */ + BIT(shutdown_err_ignore); /* errors in shutdown will not fail request */ + BIT(reader_started); /* client reads have started */ +}; + +/** + * Initialize the state of the request for first use. + */ +void Curl_req_init(struct SingleRequest *req); + +/** + * The request is about to start. Record time and do a soft reset. + */ +CURLcode Curl_req_start(struct SingleRequest *req, + struct Curl_easy *data); + +/** + * The request may continue with a follow up. Reset + * members, but keep start time for overall duration calc. + */ +CURLcode Curl_req_soft_reset(struct SingleRequest *req, + struct Curl_easy *data); + +/** + * The request is done. If not aborted, make sure that buffers are + * flushed to the client. + * @param req the request + * @param data the transfer + * @param aborted TRUE iff the request was aborted/errored + */ +CURLcode Curl_req_done(struct SingleRequest *req, + struct Curl_easy *data, bool aborted); + +/** + * Free the state of the request, not usable afterwards. + */ +void Curl_req_free(struct SingleRequest *req, struct Curl_easy *data); + +/** + * Hard reset the state of the request to virgin state base on + * transfer settings. + */ +void Curl_req_hard_reset(struct SingleRequest *req, struct Curl_easy *data); + +/** + * Send request headers. If not all could be sent + * they will be buffered. Use `Curl_req_flush()` to make sure + * bytes are really send. + * @param data the transfer making the request + * @param req the complete header bytes, no body + * @param httpversion version used in request (09, 10, 11, etc.) + * @return CURLE_OK (on blocking with *pnwritten == 0) or error. + */ +CURLcode Curl_req_send(struct Curl_easy *data, struct dynbuf *req, + unsigned char httpversion); + +/** + * TRUE iff the request has sent all request headers and data. + */ +bool Curl_req_done_sending(struct Curl_easy *data); + +/* + * Read more from client and flush all buffered request bytes. + * @return CURLE_OK on success or the error on the sending. + * Never returns CURLE_AGAIN. + */ +CURLcode Curl_req_send_more(struct Curl_easy *data); + +/* TRUE if the request wants to send, e.g. is not done sending + * and is not blocked. */ +bool Curl_req_want_send(struct Curl_easy *data); + +/* TRUE if the request wants to receive and is not blocked. */ +bool Curl_req_want_recv(struct Curl_easy *data); + +/** + * TRUE iff the request has no buffered bytes yet to send. + */ +bool Curl_req_sendbuf_empty(struct Curl_easy *data); + +/** + * Stop sending any more request data to the server. + * Clear the send buffer and mark request sending as done. + */ +CURLcode Curl_req_abort_sending(struct Curl_easy *data); + +/** + * Stop sending and receiving any more request data. + * Abort sending if not done. + */ +CURLcode Curl_req_stop_send_recv(struct Curl_easy *data); + +/** + * Invoked when all request data has been uploaded. + */ +CURLcode Curl_req_set_upload_done(struct Curl_easy *data); + +#endif /* HEADER_CURL_REQUEST_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/rtsp.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/rtsp.c new file mode 100644 index 0000000000..fabdda3d3e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/rtsp.c @@ -0,0 +1,1055 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" +#include "rtsp.h" + +#ifndef CURL_DISABLE_RTSP + +#include "transfer.h" +#include "sendf.h" +#include "curl_trc.h" +#include "multiif.h" +#include "http.h" +#include "url.h" +#include "progress.h" +#include "strcase.h" +#include "select.h" +#include "connect.h" +#include "cfilters.h" +#include "curlx/strdup.h" +#include "bufref.h" +#include "curlx/strparse.h" + +/* meta key for storing protocol meta at easy handle */ +#define CURL_META_RTSP_EASY "meta:proto:rtsp:easy" +/* meta key for storing protocol meta at connection */ +#define CURL_META_RTSP_CONN "meta:proto:rtsp:conn" + +typedef enum { + RTP_PARSE_SKIP, + RTP_PARSE_CHANNEL, + RTP_PARSE_LEN, + RTP_PARSE_DATA +} rtp_parse_st; + +/* RTSP Connection data + * Currently, only used for tracking incomplete RTP data reads */ +struct rtsp_conn { + struct dynbuf buf; + int rtp_channel; + size_t rtp_len; + rtp_parse_st state; + BIT(in_header); +}; + +/* RTSP transfer data */ +struct RTSP { + uint32_t CSeq_sent; /* CSeq of this request */ + uint32_t CSeq_recv; /* CSeq received */ +}; + +#define RTP_PKT_LENGTH(p) ((((unsigned int)((unsigned char)((p)[2]))) << 8) | \ + ((unsigned int)((unsigned char)((p)[3])))) + +/* this returns the socket to wait for in the DO and DOING state for the multi + interface and then we are always _sending_ a request and thus we wait for + the single socket to become writable only */ +static CURLcode rtsp_do_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + /* write mode */ + return Curl_pollset_add_out(data, ps, data->conn->sock[FIRSTSOCKET]); +} + +#define MAX_RTP_BUFFERSIZE 1000000 /* arbitrary */ + +static void rtsp_easy_dtor(void *key, size_t klen, void *entry) +{ + struct RTSP *rtsp = entry; + (void)key; + (void)klen; + curlx_free(rtsp); +} + +static void rtsp_conn_dtor(void *key, size_t klen, void *entry) +{ + struct rtsp_conn *rtspc = entry; + (void)key; + (void)klen; + curlx_dyn_free(&rtspc->buf); + curlx_free(rtspc); +} + +static CURLcode rtsp_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + struct rtsp_conn *rtspc; + struct RTSP *rtsp; + + rtspc = curlx_calloc(1, sizeof(*rtspc)); + if(!rtspc) + return CURLE_OUT_OF_MEMORY; + curlx_dyn_init(&rtspc->buf, MAX_RTP_BUFFERSIZE); + if(Curl_conn_meta_set(conn, CURL_META_RTSP_CONN, rtspc, rtsp_conn_dtor)) + return CURLE_OUT_OF_MEMORY; + + rtsp = curlx_calloc(1, sizeof(struct RTSP)); + if(!rtsp || + Curl_meta_set(data, CURL_META_RTSP_EASY, rtsp, rtsp_easy_dtor)) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +/* + * Function to check on various aspects of a connection. + */ +static bool rtsp_conn_is_dead(struct Curl_easy *data, + struct connectdata *conn) +{ + bool input_pending; + /* Contrary to default handling, this protocol allows pending + * input on an unused connection. */ + return !Curl_conn_is_alive(data, conn, &input_pending); +} + +static CURLcode rtsp_connect(struct Curl_easy *data, bool *done) +{ + struct rtsp_conn *rtspc = + Curl_conn_meta_get(data->conn, CURL_META_RTSP_CONN); + + if(!rtspc) + return CURLE_FAILED_INIT; + + /* Initialize the CSeq if not already done */ + if(data->state.rtsp_next_client_CSeq == 0) + data->state.rtsp_next_client_CSeq = 1; + if(data->state.rtsp_next_server_CSeq == 0) + data->state.rtsp_next_server_CSeq = 1; + + rtspc->rtp_channel = -1; + *done = TRUE; + return CURLE_OK; +} + +static CURLcode rtsp_done(struct Curl_easy *data, + CURLcode status, bool premature) +{ + struct rtsp_conn *rtspc = + Curl_conn_meta_get(data->conn, CURL_META_RTSP_CONN); + struct RTSP *rtsp = Curl_meta_get(data, CURL_META_RTSP_EASY); + CURLcode result; + + if(!rtspc || !rtsp) + return CURLE_FAILED_INIT; + + /* Bypass HTTP empty-reply checks on receive */ + if(data->set.rtspreq == RTSPREQ_RECEIVE) + premature = TRUE; + + result = Curl_http_done(data, status, premature); + + if(!status && !result) { + /* Check the sequence numbers */ + uint32_t CSeq_sent = rtsp->CSeq_sent; + uint32_t CSeq_recv = rtsp->CSeq_recv; + if((data->set.rtspreq != RTSPREQ_RECEIVE) && (CSeq_sent != CSeq_recv)) { + failf(data, + "The CSeq of this request %u did not match the response %u", + CSeq_sent, CSeq_recv); + return CURLE_RTSP_CSEQ_ERROR; + } + if(data->set.rtspreq == RTSPREQ_RECEIVE && (rtspc->rtp_channel == -1)) { + infof(data, "Got an RTP Receive with a CSeq of %u", CSeq_recv); + } + if(data->set.rtspreq == RTSPREQ_RECEIVE && + data->req.eos_written) { + failf(data, "Server prematurely closed the RTSP connection."); + return CURLE_RECV_ERROR; + } + } + + return result; +} + +static CURLcode rtsp_setup_body(struct Curl_easy *data, + unsigned char rtspreq, + struct dynbuf *reqp) +{ + CURLcode result; + if(rtspreq == RTSPREQ_ANNOUNCE || + rtspreq == RTSPREQ_SET_PARAMETER || + rtspreq == RTSPREQ_GET_PARAMETER) { + curl_off_t req_clen; /* request content length */ + + if(data->state.upload) { + req_clen = data->state.infilesize; + data->state.httpreq = HTTPREQ_PUT; + result = Curl_creader_set_fread(data, req_clen); + if(result) + return result; + } + else { + if(data->set.postfields) { + size_t plen = (data->set.postfieldsize >= 0) ? + (size_t)data->set.postfieldsize : strlen(data->set.postfields); + req_clen = (curl_off_t)plen; + result = Curl_creader_set_buf(data, data->set.postfields, plen); + } + else if(data->state.infilesize >= 0) { + req_clen = data->state.infilesize; + result = Curl_creader_set_fread(data, req_clen); + } + else { + req_clen = 0; + result = Curl_creader_set_null(data); + } + if(result) + return result; + } + + if(req_clen > 0) { + /* As stated in the http comments, it is probably not wise to + * actually set a custom Content-Length in the headers */ + if(!Curl_checkheaders(data, STRCONST("Content-Length"))) { + result = curlx_dyn_addf(reqp, "Content-Length: %" FMT_OFF_T "\r\n", + req_clen); + if(result) + return result; + } + + if(rtspreq == RTSPREQ_SET_PARAMETER || + rtspreq == RTSPREQ_GET_PARAMETER) { + if(!Curl_checkheaders(data, STRCONST("Content-Type"))) { + result = curlx_dyn_addn(reqp, STRCONST("Content-Type: " + "text/parameters\r\n")); + if(result) + return result; + } + } + + if(rtspreq == RTSPREQ_ANNOUNCE) { + if(!Curl_checkheaders(data, STRCONST("Content-Type"))) { + result = curlx_dyn_addn(reqp, STRCONST("Content-Type: " + "application/sdp\r\n")); + if(result) + return result; + } + } + } + else if(rtspreq == RTSPREQ_GET_PARAMETER) { + /* Check for an empty GET_PARAMETER (heartbeat) request */ + data->state.httpreq = HTTPREQ_HEAD; + data->req.no_body = TRUE; + } + } + else + result = Curl_creader_set_null(data); + return result; +} + +struct rtspselect { + const char *method; + bool no_body; +}; + +static CURLcode pick_method(struct Curl_easy *data, + const unsigned char rtspreq, + const char **p) +{ + static const struct rtspselect req[] = { + { "OPTIONS", TRUE }, + { "DESCRIBE", FALSE }, + { "ANNOUNCE", TRUE }, + { "SETUP", TRUE }, + { "PLAY", TRUE }, + { "PAUSE", TRUE }, + { "TEARDOWN", TRUE }, + { "GET_PARAMETER", FALSE }, + { "SET_PARAMETER", TRUE }, + { "RECORD", TRUE }, + { "", FALSE }, /* RECEIVE: treat interleaved RTP as body */ + }; + /* this is verified already in setopt, this is just added precaution */ + DEBUGASSERT((rtspreq > RTSPREQ_NONE) && (rtspreq < RTSPREQ_LAST)); + if((rtspreq <= RTSPREQ_NONE) || (rtspreq >= RTSPREQ_LAST)) + return CURLE_BAD_FUNCTION_ARGUMENT; + *p = req[rtspreq - 1].method; + data->req.no_body = req[rtspreq - 1].no_body; + return CURLE_OK; +} + +/* Allocate and store a header string. */ +static CURLcode rtsp_header_alloc(const char *header_name, + const char *value, + char **target) +{ + if(!value) + return CURLE_OK; + curlx_free(*target); + *target = curl_maprintf("%s: %s\r\n", header_name, value); + if(!*target) + return CURLE_OUT_OF_MEMORY; + return CURLE_OK; +} + +struct rtsp_blocks { + const char *request; + const char *session_id; + const char *accept; + const char *range; + const char *stream_uri; + const char *hd_proxy_auth; + const char *hd_auth; + char *referrer; + char *accept_encoding; + char *transport; + BIT(transport_alloc); /* if 'transport' is allocated */ +}; + +static CURLcode rtsp_setup_request(struct Curl_easy *data, + struct rtsp_blocks *b, + const unsigned char rtspreq) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + b->session_id = CURL_EASY_STR(data, STRING_RTSP_SESSION_ID); + + /* Stream URI. Default to server '*' if not specified */ + if(CURL_EASY_STR(data, STRING_RTSP_STREAM_URI)) + b->stream_uri = CURL_EASY_STR(data, STRING_RTSP_STREAM_URI); + else + b->stream_uri = "*"; + + /* Transport Header for SETUP requests */ + b->transport = Curl_checkheaders(data, STRCONST("Transport")); + if(rtspreq == RTSPREQ_SETUP && !b->transport) { + /* New Transport: setting? */ + if(CURL_EASY_STR(data, STRING_RTSP_TRANSPORT)) { + result = rtsp_header_alloc( + "Transport", CURL_EASY_STR(data, STRING_RTSP_TRANSPORT), + &b->transport); + if(result) + return result; + b->transport_alloc = TRUE; + } + else { + failf(data, + "Refusing to issue an RTSP SETUP without a Transport: header."); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + } + + /* Accept Headers for DESCRIBE requests */ + if(rtspreq == RTSPREQ_DESCRIBE) { + /* Accept Header */ + b->accept = Curl_checkheaders(data, STRCONST("Accept")) ? + NULL : "Accept: application/sdp\r\n"; + + /* Accept-Encoding header */ + if(!Curl_checkheaders(data, STRCONST("Accept-Encoding")) && + CURL_EASY_STR(data, STRING_ENCODING)) { + result = rtsp_header_alloc("Accept-Encoding", + CURL_EASY_STR(data, STRING_ENCODING), + &b->accept_encoding); + if(result) + return result; + } + } + + /* setup the authentication headers */ + result = Curl_http_output_auth(data, conn, b->request, HTTPREQ_GET, + b->stream_uri, NULL, FALSE); + if(result) + return result; + +#ifndef CURL_DISABLE_PROXY + b->hd_proxy_auth = data->req.hd_proxy_auth; +#endif + b->hd_auth = data->req.hd_auth; + + /* Referrer */ + if(Curl_bufref_ptr(&data->state.referer) && + !Curl_checkheaders(data, STRCONST("Referer"))) { + b->referrer = + curl_maprintf("Referer: %s\r\n", Curl_bufref_ptr(&data->state.referer)); + if(!b->referrer) + result = CURLE_OUT_OF_MEMORY; + } + + /* + * Range Header + * Only applies to PLAY, PAUSE, RECORD + * + * Go ahead and use the Range stuff supplied for HTTP + */ + if(!result && + data->state.use_range && + ((rtspreq == RTSPREQ_PLAY) || + (rtspreq == RTSPREQ_PAUSE) || + (rtspreq == RTSPREQ_RECORD))) { + + /* Check to see if there is a range set in the custom headers */ + if(!Curl_checkheaders(data, STRCONST("Range")) && data->state.range) { + result = rtsp_header_alloc("Range", + data->state.range, + &data->state.rangeline); + if(!result) + b->range = data->state.rangeline; + } + } + return result; +} + +#define HTTPVERSION 11 /* RTSP is close to HTTP/1.1, sort of... */ + +static CURLcode rtsp_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + const unsigned char rtspreq = data->set.rtspreq; + const char *str; + struct RTSP *rtsp = Curl_meta_get(data, CURL_META_RTSP_EASY); + struct dynbuf req_buffer; + struct rtsp_blocks block; + memset(&block, 0, sizeof(block)); + + *done = TRUE; + if(!rtsp) + return CURLE_FAILED_INIT; + + /* Initialize a dynamic send buffer */ + curlx_dyn_init(&req_buffer, DYN_RTSP_REQ_HEADER); + + rtsp->CSeq_sent = data->state.rtsp_next_client_CSeq; + rtsp->CSeq_recv = 0; + + /* Setup the 'p_request' pointer to the proper method. */ + result = pick_method(data, rtspreq, &block.request); + if(result) + goto out; + + if(rtspreq == RTSPREQ_RECEIVE) { + Curl_xfer_setup_recv(data, FIRSTSOCKET, -1); + goto out; + } + + result = rtsp_setup_request(data, &block, rtspreq); + if(result) + goto out; + /* + * Sanity check the custom headers + */ + if(Curl_checkheaders(data, STRCONST("CSeq"))) { + failf(data, "CSeq cannot be set as a custom header."); + result = CURLE_RTSP_CSEQ_ERROR; + goto out; + } + if(Curl_checkheaders(data, STRCONST("Session"))) { + failf(data, "Session ID cannot be set as a custom header."); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + + result = + curlx_dyn_addf(&req_buffer, + "%s %s RTSP/1.0\r\n" /* Request Stream-URI RTSP/1.0 */ + "CSeq: %u\r\n", /* CSeq */ + block.request, block.stream_uri, rtsp->CSeq_sent); + if(result) + goto out; + + /* + * Rather than do a normal alloc line, keep the session_id unformatted + * to make comparison easier + */ + if(block.session_id) { + result = curlx_dyn_addf(&req_buffer, "Session: %s\r\n", block.session_id); + if(result) + goto out; + } + + /* + * Shared HTTP-like options + */ + result = curlx_dyn_addf(&req_buffer, + "%s" /* transport */ + "%s" /* accept */ + "%s" /* accept-encoding */ + "%s" /* range */ + "%s" /* referrer */ + , + block.transport ? block.transport : "", + block.accept ? block.accept : "", + block.accept_encoding ? block.accept_encoding : "", + block.range ? block.range : "", + block.referrer ? block.referrer : ""); + + str = CURL_EASY_STR(data, STRING_USERAGENT); + if(!result && str && *str && + !Curl_checkheaders(data, STRCONST("User-Agent"))) + result = curlx_dyn_addf(&req_buffer, + "User-Agent: %s\r\n", str); + + if(!result) + result = curlx_dyn_addf(&req_buffer, + "%s" /* hd_proxy_auth */ + "%s", /* hd_auth */ + block.hd_proxy_auth ? block.hd_proxy_auth : "", + block.hd_auth ? block.hd_auth : ""); + if(result) + goto out; + + if((rtspreq == RTSPREQ_SETUP) || (rtspreq == RTSPREQ_DESCRIBE)) { + result = Curl_add_timecondition(data, &req_buffer); + if(result) + goto out; + } + + result = Curl_add_custom_headers(data, FALSE, HTTPVERSION, &req_buffer); + if(result) + goto out; + + result = rtsp_setup_body(data, rtspreq, &req_buffer); + if(result) + goto out; + + /* Finish the request buffer */ + result = curlx_dyn_addn(&req_buffer, STRCONST("\r\n")); + if(result) + goto out; + + Curl_xfer_setup_sendrecv(data, FIRSTSOCKET, -1); + + /* issue the request */ + result = Curl_req_send(data, &req_buffer, HTTPVERSION); + if(result) { + failf(data, "Failed sending RTSP request"); + goto out; + } + + /* Increment the CSeq on success */ + data->state.rtsp_next_client_CSeq++; + + if(data->req.writebytecount) { + /* if a request-body has been sent off, we make sure this progress is + noted properly */ + Curl_pgrsSetUploadCounter(data, data->req.writebytecount); + result = Curl_pgrsUpdate(data); + } +out: + if(block.transport_alloc) + curlx_free(block.transport); + curlx_free(block.accept_encoding); + curlx_free(block.referrer); + curlx_dyn_free(&req_buffer); + return result; +} + +/** + * write any BODY bytes missing to the client, ignore the rest. + */ +static CURLcode rtp_write_body_junk(struct Curl_easy *data, + struct rtsp_conn *rtspc, + const char *buf, + size_t blen) +{ + curl_off_t body_remain; + bool in_body; + + in_body = (data->req.headerline && !rtspc->in_header) && + (data->req.size >= 0) && + (data->req.bytecount < data->req.size); + body_remain = in_body ? (data->req.size - data->req.bytecount) : 0; + DEBUGASSERT(body_remain >= 0); + if(body_remain) { + if((curl_off_t)blen > body_remain) + blen = (size_t)body_remain; + return Curl_client_write(data, CLIENTWRITE_BODY, buf, blen); + } + return CURLE_OK; +} + +static CURLcode rtp_client_write(struct Curl_easy *data, const char *ptr, + size_t len) +{ + struct Curl_mapi_guard guard; + size_t wrote; + curl_write_callback writeit; + void *user_ptr; + + if(len == 0) { + failf(data, "Cannot write a 0 size RTP packet."); + return CURLE_WRITE_ERROR; + } + + /* If the user has configured CURLOPT_INTERLEAVEFUNCTION then use that + function and any configured CURLOPT_INTERLEAVEDATA to write out the RTP + data. Otherwise, use the CURLOPT_WRITEFUNCTION with the CURLOPT_WRITEDATA + pointer to write out the RTP data. */ + if(data->set.fwrite_rtp) { + writeit = data->set.fwrite_rtp; + user_ptr = data->set.rtp_out; + } + else { + writeit = data->set.fwrite_func; + user_ptr = data->set.out; + } + + CURL_CBAPI_START(&guard, data, easy_fwrite_rtp); + wrote = writeit((char *)CURL_UNCONST(ptr), 1, len, user_ptr); + CURL_CBAPI_END(&guard); + + if(wrote == CURL_WRITEFUNC_PAUSE) { + failf(data, "Cannot pause RTP"); + return CURLE_WRITE_ERROR; + } + + if(wrote != len) { + failf(data, "Failed writing RTP data"); + return CURLE_WRITE_ERROR; + } + + return CURLE_OK; +} + +static CURLcode rtsp_filter_rtp(struct Curl_easy *data, + struct rtsp_conn *rtspc, + const char *buf, + size_t blen, + size_t *pconsumed) +{ + CURLcode result = CURLE_OK; + size_t skip_len = 0; + + *pconsumed = 0; + while(blen) { + bool in_body = (data->req.headerline && !rtspc->in_header) && + (data->req.size >= 0) && + (data->req.bytecount < data->req.size); + switch(rtspc->state) { + + case RTP_PARSE_SKIP: { + DEBUGASSERT(curlx_dyn_len(&rtspc->buf) == 0); + while(blen && buf[0] != '$') { + if(!in_body && buf[0] == 'R' && + data->set.rtspreq != RTSPREQ_RECEIVE) { + if(!strncmp(buf, "RTSP/", (blen < 5) ? blen : 5)) { + /* This could be the next response, no consume and return */ + if(*pconsumed) { + DEBUGF(infof(data, "RTP rtsp_filter_rtp[SKIP] RTSP/ prefix, " + "skipping %zu bytes of junk", *pconsumed)); + } + rtspc->state = RTP_PARSE_SKIP; + rtspc->in_header = TRUE; + goto out; + } + } + /* junk/BODY, consume without buffering */ + *pconsumed += 1; + ++buf; + --blen; + ++skip_len; + } + if(blen && buf[0] == '$') { + /* possible start of an RTP message, buffer */ + if(skip_len) { + /* end of junk/BODY bytes, flush */ + result = rtp_write_body_junk(data, rtspc, buf - skip_len, skip_len); + skip_len = 0; + if(result) + goto out; + } + if(curlx_dyn_addn(&rtspc->buf, buf, 1)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + *pconsumed += 1; + ++buf; + --blen; + rtspc->state = RTP_PARSE_CHANNEL; + } + break; + } + + case RTP_PARSE_CHANNEL: { + int idx = ((unsigned char)buf[0]) / 8; + int off = ((unsigned char)buf[0]) % 8; + DEBUGASSERT(curlx_dyn_len(&rtspc->buf) == 1); + if(!(data->state.rtp_channel_mask[idx] & (1 << off))) { + /* invalid channel number, junk or BODY data */ + rtspc->state = RTP_PARSE_SKIP; + DEBUGASSERT(skip_len == 0); + /* we do not consume this byte, it is BODY data */ + DEBUGF(infof(data, "RTSP: invalid RTP channel %d, skipping", idx)); + if(*pconsumed == 0) { + /* We did not consume the initial '$' in our buffer, but had + * it from an earlier call. We cannot un-consume it and have + * to write it directly as BODY data */ + result = rtp_write_body_junk(data, rtspc, + curlx_dyn_ptr(&rtspc->buf), 1); + if(result) + goto out; + } + else { + /* count the '$' as skip and continue */ + skip_len = 1; + } + curlx_dyn_free(&rtspc->buf); + break; + } + /* a valid channel, so we expect this to be a real RTP message */ + rtspc->rtp_channel = (unsigned char)buf[0]; + if(curlx_dyn_addn(&rtspc->buf, buf, 1)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + *pconsumed += 1; + ++buf; + --blen; + rtspc->state = RTP_PARSE_LEN; + break; + } + + case RTP_PARSE_LEN: { + size_t rtp_len = curlx_dyn_len(&rtspc->buf); + const char *rtp_buf; + DEBUGASSERT(rtp_len >= 2 && rtp_len < 4); + if(curlx_dyn_addn(&rtspc->buf, buf, 1)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + *pconsumed += 1; + ++buf; + --blen; + if(rtp_len == 2) + break; + rtp_buf = curlx_dyn_ptr(&rtspc->buf); + rtspc->rtp_len = RTP_PKT_LENGTH(rtp_buf) + 4; + if(rtspc->rtp_len == 4) { + /* zero-length payload, the 4-byte header is the complete RTP + message. Dispatch immediately without entering RTP_PARSE_DATA. */ + DEBUGF(infof(data, "RTP write channel %d rtp_len %zu (no payload)", + rtspc->rtp_channel, rtspc->rtp_len)); + result = rtp_client_write(data, rtp_buf, rtspc->rtp_len); + curlx_dyn_free(&rtspc->buf); + rtspc->state = RTP_PARSE_SKIP; + if(result) + goto out; + break; + } + rtspc->state = RTP_PARSE_DATA; + break; + } + + case RTP_PARSE_DATA: { + size_t rtp_len = curlx_dyn_len(&rtspc->buf); + size_t needed; + DEBUGASSERT(rtp_len < rtspc->rtp_len); + needed = rtspc->rtp_len - rtp_len; + if(needed <= blen) { + if(curlx_dyn_addn(&rtspc->buf, buf, needed)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + *pconsumed += needed; + buf += needed; + blen -= needed; + /* complete RTP message in buffer */ + DEBUGF(infof(data, "RTP write channel %d rtp_len %zu", + rtspc->rtp_channel, rtspc->rtp_len)); + result = rtp_client_write(data, curlx_dyn_ptr(&rtspc->buf), + rtspc->rtp_len); + curlx_dyn_free(&rtspc->buf); + rtspc->state = RTP_PARSE_SKIP; + if(result) + goto out; + } + else { + if(curlx_dyn_addn(&rtspc->buf, buf, blen)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + *pconsumed += blen; + buf += blen; + blen = 0; + } + break; + } + + default: + DEBUGASSERT(0); + return CURLE_RECV_ERROR; + } + } +out: + if(!result && skip_len) + result = rtp_write_body_junk(data, rtspc, buf - skip_len, skip_len); + return result; +} + +/* + * Parse and write out an RTSP response. + * @param data the transfer + * @param conn the connection + * @param buf data read from connection + * @param blen amount of data in buf + * @param is_eos TRUE iff this is the last write + * @param readmore out, TRUE iff complete buf was consumed and more data + * is needed + */ +static CURLcode rtsp_rtp_write_resp(struct Curl_easy *data, + const char *buf, + size_t blen, + bool is_eos) +{ + struct rtsp_conn *rtspc = + Curl_conn_meta_get(data->conn, CURL_META_RTSP_CONN); + CURLcode result = CURLE_OK; + size_t consumed = 0; + + if(!rtspc) + return CURLE_FAILED_INIT; + + if(!data->req.header) + rtspc->in_header = FALSE; + if(!blen) { + goto out; + } + + DEBUGF(infof(data, "rtsp_rtp_write_resp(len=%zu, in_header=%d, eos=%d)", + blen, rtspc->in_header, is_eos)); + + /* If header parsing is not ongoing, extract RTP messages */ + if(!rtspc->in_header) { + result = rtsp_filter_rtp(data, rtspc, buf, blen, &consumed); + if(result) + goto out; + buf += consumed; + blen -= consumed; + /* either we consumed all or are at the start of header parsing */ + if(blen && !data->req.header) + DEBUGF(infof(data, "RTSP: %zu bytes, possibly excess in response body", + blen)); + } + + /* we want to parse headers, do so */ + if(data->req.header && blen) { + rtspc->in_header = TRUE; + result = Curl_http_write_resp_hds(data, buf, blen, &consumed); + if(result) + goto out; + + buf += consumed; + blen -= consumed; + + if(!data->req.header) + rtspc->in_header = FALSE; + + if(!rtspc->in_header) { + /* If header parsing is done, extract interleaved RTP messages */ + if(data->req.size <= -1) { + /* Respect section 4.4 of rfc2326: If the Content-Length header is + absent, a length 0 must be assumed. */ + data->req.size = 0; + data->req.download_done = TRUE; + } + result = rtsp_filter_rtp(data, rtspc, buf, blen, &consumed); + if(result) + goto out; + buf += consumed; + blen -= consumed; + } + } + + if(rtspc->state != RTP_PARSE_SKIP) + data->req.done = FALSE; + /* we SHOULD have consumed all bytes, unless the response is borked. + * In which case we write out the left over bytes, letting the client + * writer deal with it (it will report EXCESS and fail the transfer). */ + DEBUGF(infof(data, "rtsp_rtp_write_resp(len=%zu, in_header=%d, done=%d, " + "rtspc->state=%d, req.size=%" FMT_OFF_T ")", + blen, rtspc->in_header, data->req.done, (int)rtspc->state, + data->req.size)); + if(!result && (is_eos || blen)) { + result = Curl_client_write(data, CLIENTWRITE_BODY | + (is_eos ? CLIENTWRITE_EOS : 0), buf, blen); + } + +out: + if((data->set.rtspreq == RTSPREQ_RECEIVE) && + (rtspc->state == RTP_PARSE_SKIP)) { + /* In special mode RECEIVE, we process one chunk of network + * data, so we stop the transfer here, if we have no incomplete + * RTP message pending. */ + data->req.download_done = TRUE; + } + return result; +} + +static CURLcode rtsp_rtp_write_resp_hd(struct Curl_easy *data, + const char *buf, + size_t blen, + bool is_eos) +{ + return rtsp_rtp_write_resp(data, buf, blen, is_eos); +} + +static CURLcode rtsp_parse_transport(struct Curl_easy *data, + const char *transport) +{ + /* If we receive multiple Transport response-headers, the interleaved + channels of each response header is recorded and used together for + subsequent data validity checks.*/ + /* e.g.: ' RTP/AVP/TCP;unicast;interleaved=5-6' */ + const char *start, *end; + start = transport; + while(start && *start) { + curlx_str_passblanks(&start); + end = strchr(start, ';'); + if(checkprefix("interleaved=", start)) { + curl_off_t chan1, chan2, chan; + const char *p = start + 12; + if(!curlx_str_number(&p, &chan1, 255)) { + unsigned char *rtp_channel_mask = data->state.rtp_channel_mask; + chan2 = chan1; + if(!curlx_str_single(&p, '-')) { + if(curlx_str_number(&p, &chan2, 255)) { + infof(data, "Unable to read the interleaved parameter from " + "Transport header: [%s]", transport); + chan2 = chan1; + } + } + for(chan = chan1; chan <= chan2; chan++) { + int idx = (int)chan / 8; + int off = (int)chan % 8; + rtp_channel_mask[idx] |= (unsigned char)(1 << off); + } + } + else { + infof(data, "Unable to read the interleaved parameter from " + "Transport header: [%s]", transport); + } + break; + } + /* skip to next parameter */ + start = (!end) ? end : (end + 1); + } + return CURLE_OK; +} + +CURLcode Curl_rtsp_parseheader(struct Curl_easy *data, const char *header) +{ + if(checkprefix("CSeq:", header)) { + curl_off_t CSeq = 0; + struct RTSP *rtsp = Curl_meta_get(data, CURL_META_RTSP_EASY); + const char *p = &header[5]; + if(!rtsp) + return CURLE_FAILED_INIT; + curlx_str_passblanks(&p); + if(curlx_str_number(&p, &CSeq, UINT_MAX)) { + failf(data, "Unable to read the CSeq header: [%s]", header); + return CURLE_RTSP_CSEQ_ERROR; + } + data->state.rtsp_CSeq_recv = rtsp->CSeq_recv = (uint32_t)CSeq; + } + else if(checkprefix("Session:", header)) { + const char *start, *end, *str; + size_t idlen; + + /* Find the first non-space letter */ + start = header + 8; + curlx_str_passblanks(&start); + + if(!*start) { + failf(data, "Got a blank Session ID"); + return CURLE_RTSP_SESSION_ERROR; + } + + /* Find the end of Session ID + * + * Allow any non whitespace content, up to the field separator or end of + * line. RFC 2326 is not 100% clear on the session ID and for example + * gstreamer does URL-encoded session ID's not covered by the standard. + */ + end = start; + while((*end > ' ') && (*end != ';')) + end++; + idlen = end - start; + + str = CURL_EASY_STR(data, STRING_RTSP_SESSION_ID); + if(str) { + + /* If the Session ID is set, then compare */ + if(strlen(str) != idlen || + strncmp(start, str, idlen)) { + failf(data, "Got RTSP Session ID Line [%s], but wanted ID [%s]", + start, str); + return CURLE_RTSP_SESSION_ERROR; + } + } + else { + /* If the Session ID is not set, and we find it in a response, then set + * it. + * Copy the id substring into a new buffer */ + void *mem = curlx_memdup0(start, idlen); + if(!mem || + CURL_EASY_STR_SETN(data, STRING_RTSP_SESSION_ID, mem)) + return CURLE_OUT_OF_MEMORY; + } + } + else if(checkprefix("Transport:", header)) { + CURLcode result; + result = rtsp_parse_transport(data, header + 10); + if(result) + return result; + } + return CURLE_OK; +} + +/* + * RTSP handler interface. + */ +const struct Curl_protocol Curl_protocol_rtsp = { + rtsp_setup_connection, /* setup_connection */ + rtsp_do, /* do_it */ + rtsp_done, /* done */ + ZERO_NULL, /* do_more */ + rtsp_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_pollset */ + rtsp_do_pollset, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + Curl_http_perform_pollset, /* perform_pollset */ + ZERO_NULL, /* disconnect */ + rtsp_rtp_write_resp, /* write_resp */ + rtsp_rtp_write_resp_hd, /* write_resp_hd */ + rtsp_conn_is_dead, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + Curl_http_follow, /* follow */ +}; + +#endif /* CURL_DISABLE_RTSP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/rtsp.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/rtsp.h new file mode 100644 index 0000000000..791cbff337 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/rtsp.h @@ -0,0 +1,47 @@ +#ifndef HEADER_CURL_RTSP_H +#define HEADER_CURL_RTSP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_RTSP +CURLcode Curl_rtsp_parseheader(struct Curl_easy *data, const char *header); +extern const struct Curl_protocol Curl_protocol_rtsp; +#else +#define Curl_rtsp_parseheader(x, y) CURLE_NOT_BUILT_IN +#endif + +#define RTSPREQ_NONE CURL_RTSPREQ_NONE +#define RTSPREQ_OPTIONS CURL_RTSPREQ_OPTIONS +#define RTSPREQ_DESCRIBE CURL_RTSPREQ_DESCRIBE +#define RTSPREQ_ANNOUNCE CURL_RTSPREQ_ANNOUNCE +#define RTSPREQ_SETUP CURL_RTSPREQ_SETUP +#define RTSPREQ_PLAY CURL_RTSPREQ_PLAY +#define RTSPREQ_PAUSE CURL_RTSPREQ_PAUSE +#define RTSPREQ_TEARDOWN CURL_RTSPREQ_TEARDOWN +#define RTSPREQ_GET_PARAMETER CURL_RTSPREQ_GET_PARAMETER +#define RTSPREQ_SET_PARAMETER CURL_RTSPREQ_SET_PARAMETER +#define RTSPREQ_RECORD CURL_RTSPREQ_RECORD +#define RTSPREQ_RECEIVE CURL_RTSPREQ_RECEIVE +#define RTSPREQ_LAST CURL_RTSPREQ_LAST + +#endif /* HEADER_CURL_RTSP_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/select.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/select.c new file mode 100644 index 0000000000..76b56bc042 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/select.c @@ -0,0 +1,727 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_SYS_SELECT_H +#include <sys/select.h> +#elif defined(HAVE_UNISTD_H) +#include <unistd.h> +#endif + +#include "urldata.h" +#include "connect.h" +#include "select.h" +#include "curl_trc.h" +#include "curlx/timediff.h" +#include "curlx/wait.h" + +#ifndef HAVE_POLL /* use select() */ +/* + * This is a wrapper around select() to aid in Windows compatibility. A + * negative timeout value makes this function wait indefinitely, unless no + * valid file descriptor is given, when this happens the negative timeout is + * ignored and the function times out immediately. + * + * Return values: + * -1 = system call error or fd >= FD_SETSIZE + * 0 = timeout + * N = number of signalled file descriptors + */ +static int our_select(curl_socket_t maxfd, /* highest socket number */ + fd_set *fds_read, /* sockets ready for reading */ + fd_set *fds_write, /* sockets ready for writing */ + fd_set *fds_err, /* sockets with errors */ + timediff_t timeout_ms) /* milliseconds to wait */ +{ + struct timeval pending_tv; + struct timeval *ptimeout; + +#ifdef USE_WINSOCK + /* Winsock select() cannot handle zero events. See the comment below. */ + if((!fds_read || fds_read->fd_count == 0) && + (!fds_write || fds_write->fd_count == 0) && + (!fds_err || fds_err->fd_count == 0)) { + /* no sockets, wait */ + return curlx_wait_ms(timeout_ms); + } +#endif + + ptimeout = curlx_mstotv(&pending_tv, timeout_ms); + +#ifdef USE_WINSOCK + /* Winsock select() must not be called with an fd_set that contains zero + fd flags, or it will return WSAEINVAL. It also cannot be called with + no fd_sets at all! From the documentation: + + Any two of the parameters, readfds, writefds, or exceptfds, can be + given as null. At least one must be non-null, and any non-null + descriptor set must contain at least one handle to a socket. + + It is unclear why Winsock does not handle this for us instead of + calling this an error. Luckily, with Winsock, we can _also_ ask how + many bits are set on an fd_set. Therefore, let's check it beforehand. + */ + return select((int)maxfd + 1, + fds_read && fds_read->fd_count ? fds_read : NULL, + fds_write && fds_write->fd_count ? fds_write : NULL, + fds_err && fds_err->fd_count ? fds_err : NULL, ptimeout); +#else + return select((int)maxfd + 1, fds_read, fds_write, fds_err, ptimeout); +#endif +} + +#endif + +/* + * Wait for read or write events on a set of file descriptors. It uses poll() + * when poll() is available, in order to avoid limits with FD_SETSIZE, + * otherwise select() is used. An error is returned if select() is being used + * and a file descriptor is too large for FD_SETSIZE. + * + * A negative timeout value makes this function wait indefinitely, unless no + * valid file descriptor is given, when this happens the negative timeout is + * ignored and the function times out immediately. + * + * Return values: + * -1 = system call error or fd >= FD_SETSIZE + * 0 = timeout + * [bitmask] = action as described below + * + * CURL_CSELECT_IN - first socket is readable + * CURL_CSELECT_IN2 - second socket is readable + * CURL_CSELECT_OUT - write socket is writable + * CURL_CSELECT_ERR - an error condition occurred + */ +int Curl_socket_check(curl_socket_t readfd0, /* two sockets to read from */ + curl_socket_t readfd1, + curl_socket_t writefd, /* socket to write to */ + timediff_t timeout_ms) /* milliseconds to wait */ +{ + struct pollfd pfd[3]; + int num; + int r; + + if((readfd0 == CURL_SOCKET_BAD) && (readfd1 == CURL_SOCKET_BAD) && + (writefd == CURL_SOCKET_BAD)) { + /* no sockets, wait */ + return curlx_wait_ms(timeout_ms); + } + + /* Avoid initial timestamp, avoid curlx_now() call, when elapsed + time in this function does not need to be measured. This happens + when function is called with a zero timeout or a negative timeout + value indicating a blocking call should be performed. */ + + num = 0; + if(readfd0 != CURL_SOCKET_BAD) { + pfd[num].fd = readfd0; + pfd[num].events = POLLRDNORM | POLLIN | POLLRDBAND | POLLPRI; + pfd[num].revents = 0; + num++; + } + if(readfd1 != CURL_SOCKET_BAD) { + pfd[num].fd = readfd1; + pfd[num].events = POLLRDNORM | POLLIN | POLLRDBAND | POLLPRI; + pfd[num].revents = 0; + num++; + } + if(writefd != CURL_SOCKET_BAD) { + pfd[num].fd = writefd; + pfd[num].events = POLLWRNORM | POLLOUT | POLLPRI; + pfd[num].revents = 0; + num++; + } + + r = Curl_poll(pfd, (unsigned int)num, timeout_ms); + if(r <= 0) + return r; + + r = 0; + num = 0; + if(readfd0 != CURL_SOCKET_BAD) { + if(pfd[num].revents & (POLLRDNORM | POLLIN | POLLERR | POLLHUP)) + r |= CURL_CSELECT_IN; + if(pfd[num].revents & (POLLPRI | POLLNVAL)) + r |= CURL_CSELECT_ERR; + num++; + } + if(readfd1 != CURL_SOCKET_BAD) { + if(pfd[num].revents & (POLLRDNORM | POLLIN | POLLERR | POLLHUP)) + r |= CURL_CSELECT_IN2; + if(pfd[num].revents & (POLLPRI | POLLNVAL)) + r |= CURL_CSELECT_ERR; + num++; + } + if(writefd != CURL_SOCKET_BAD) { + if(pfd[num].revents & (POLLWRNORM | POLLOUT)) + r |= CURL_CSELECT_OUT; + if(pfd[num].revents & (POLLERR | POLLHUP | POLLPRI | POLLNVAL)) + r |= CURL_CSELECT_ERR; + } + + return r; +} + +/* + * This is a wrapper around poll(). If poll() does not exist, then + * select() is used instead. An error is returned if select() is + * being used and a file descriptor is too large for FD_SETSIZE. + * A negative timeout value makes this function wait indefinitely, + * unless no valid file descriptor is given, when this happens the + * negative timeout is ignored and the function times out immediately. + * + * Return values: + * -1 = system call error or fd >= FD_SETSIZE + * 0 = timeout + * N = number of structures with non zero revent fields + */ +int Curl_poll(struct pollfd ufds[], unsigned int nfds, timediff_t timeout_ms) +{ +#ifdef HAVE_POLL + int pending_ms; +#else + fd_set fds_read; + fd_set fds_write; + fd_set fds_err; + curl_socket_t maxfd; +#endif + bool fds_none = TRUE; + unsigned int i; + int r; + + if(ufds) { + for(i = 0; i < nfds; i++) { + if(ufds[i].fd != CURL_SOCKET_BAD) { + fds_none = FALSE; + break; + } + } + } + if(fds_none) { + /* no sockets, wait */ + return curlx_wait_ms(timeout_ms); + } + + /* Avoid initial timestamp, avoid curlx_now() call, when elapsed + time in this function does not need to be measured. This happens + when function is called with a zero timeout or a negative timeout + value indicating a blocking call should be performed. */ + +#ifdef HAVE_POLL + + /* prevent overflow, timeout_ms is typecast to int. */ +#if TIMEDIFF_T_MAX > INT_MAX + if(timeout_ms > INT_MAX) + timeout_ms = INT_MAX; +#endif + if(timeout_ms > 0) + pending_ms = (int)timeout_ms; + else if(timeout_ms < 0) + pending_ms = -1; + else + pending_ms = 0; + r = poll(ufds, nfds, pending_ms); + if(r <= 0) { + if((r == -1) && (SOCKERRNO == SOCKEINTR)) + /* make EINTR from select or poll not a "lethal" error */ + r = 0; + return r; + } + + for(i = 0; i < nfds; i++) { + if(ufds[i].fd == CURL_SOCKET_BAD) + continue; + if(ufds[i].revents & POLLHUP) + ufds[i].revents |= POLLIN; + if(ufds[i].revents & POLLERR) + ufds[i].revents |= POLLIN | POLLOUT; + } + +#else /* !HAVE_POLL */ + + FD_ZERO(&fds_read); + FD_ZERO(&fds_write); + FD_ZERO(&fds_err); + maxfd = (curl_socket_t)-1; + + for(i = 0; i < nfds; i++) { + ufds[i].revents = 0; + if(ufds[i].fd == CURL_SOCKET_BAD) + continue; + VERIFY_SOCK(ufds[i].fd); + if(ufds[i].events & (POLLIN | POLLOUT | POLLPRI | + POLLRDNORM | POLLWRNORM | POLLRDBAND)) { + if(ufds[i].fd > maxfd) + maxfd = ufds[i].fd; + if(ufds[i].events & (POLLRDNORM | POLLIN)) + FD_SET(ufds[i].fd, &fds_read); + if(ufds[i].events & (POLLWRNORM | POLLOUT)) + FD_SET(ufds[i].fd, &fds_write); + if(ufds[i].events & (POLLRDBAND | POLLPRI)) + FD_SET(ufds[i].fd, &fds_err); + } + } + + /* Note also that Winsock ignores the first argument, so we do not worry + about the fact that maxfd is computed incorrectly with Winsock (since + curl_socket_t is unsigned in such cases and thus -1 is the largest + value). */ + r = our_select(maxfd, &fds_read, &fds_write, &fds_err, timeout_ms); + if(r <= 0) { + if((r == -1) && (SOCKERRNO == SOCKEINTR)) + /* make EINTR from select or poll not a "lethal" error */ + r = 0; + return r; + } + + r = 0; + for(i = 0; i < nfds; i++) { + ufds[i].revents = 0; + if(ufds[i].fd == CURL_SOCKET_BAD) + continue; + if(FD_ISSET(ufds[i].fd, &fds_read)) { + if(ufds[i].events & POLLRDNORM) + ufds[i].revents |= POLLRDNORM; + if(ufds[i].events & POLLIN) + ufds[i].revents |= POLLIN; + } + if(FD_ISSET(ufds[i].fd, &fds_write)) { + if(ufds[i].events & POLLWRNORM) + ufds[i].revents |= POLLWRNORM; + if(ufds[i].events & POLLOUT) + ufds[i].revents |= POLLOUT; + } + if(FD_ISSET(ufds[i].fd, &fds_err)) { + if(ufds[i].events & POLLRDBAND) + ufds[i].revents |= POLLRDBAND; + if(ufds[i].events & POLLPRI) + ufds[i].revents |= POLLPRI; + } + if(ufds[i].revents) + r++; + } + +#endif /* HAVE_POLL */ + + return r; +} + +void Curl_pollfds_init(struct curl_pollfds *cpfds, + struct pollfd *static_pfds, + unsigned int static_count) +{ + DEBUGASSERT(cpfds); + memset(cpfds, 0, sizeof(*cpfds)); + if(static_pfds && static_count) { + cpfds->pfds = static_pfds; + cpfds->count = static_count; + } +} + +void Curl_pollfds_reset(struct curl_pollfds *cpfds) +{ + cpfds->n = 0; +} + +void Curl_pollfds_cleanup(struct curl_pollfds *cpfds) +{ + DEBUGASSERT(cpfds); + if(cpfds->allocated_pfds) { + curlx_free(cpfds->pfds); + } + memset(cpfds, 0, sizeof(*cpfds)); +} + +static CURLcode cpfds_increase(struct curl_pollfds *cpfds, unsigned int inc) +{ + struct pollfd *new_fds; + unsigned int new_count = cpfds->count + inc; + + new_fds = curlx_calloc(new_count, sizeof(struct pollfd)); + if(!new_fds) + return CURLE_OUT_OF_MEMORY; + + memcpy(new_fds, cpfds->pfds, cpfds->count * sizeof(struct pollfd)); + if(cpfds->allocated_pfds) + curlx_free(cpfds->pfds); + cpfds->pfds = new_fds; + cpfds->count = new_count; + cpfds->allocated_pfds = TRUE; + return CURLE_OK; +} + +static CURLcode cpfds_add_sock(struct curl_pollfds *cpfds, + curl_socket_t sock, short events, bool fold) +{ + int i; + + if(fold && cpfds->n <= INT_MAX) { + for(i = (int)cpfds->n - 1; i >= 0; --i) { + if(sock == cpfds->pfds[i].fd) { + cpfds->pfds[i].events |= events; + return CURLE_OK; + } + } + } + /* not folded, add new entry */ + if(cpfds->n >= cpfds->count) { + if(cpfds_increase(cpfds, 100)) + return CURLE_OUT_OF_MEMORY; + } + cpfds->pfds[cpfds->n].fd = sock; + cpfds->pfds[cpfds->n].events = events; + ++cpfds->n; + return CURLE_OK; +} + +CURLcode Curl_pollfds_add_sock(struct curl_pollfds *cpfds, + curl_socket_t sock, short events) +{ + return cpfds_add_sock(cpfds, sock, events, FALSE); +} + +CURLcode Curl_pollfds_add_ps(struct curl_pollfds *cpfds, + struct easy_pollset *ps) +{ + size_t i; + + DEBUGASSERT(cpfds); + DEBUGASSERT(ps); + for(i = 0; i < ps->n; i++) { + short events = 0; + if(ps->actions[i] & CURL_POLL_IN) + events |= POLLIN; + if(ps->actions[i] & CURL_POLL_OUT) + events |= POLLOUT; + if(events) { + if(cpfds_add_sock(cpfds, ps->sockets[i], events, TRUE)) + return CURLE_OUT_OF_MEMORY; + } + } + return CURLE_OK; +} + +void Curl_waitfds_init(struct Curl_waitfds *cwfds, + struct curl_waitfd *static_wfds, + unsigned int static_count) +{ + DEBUGASSERT(cwfds); + DEBUGASSERT(static_wfds || !static_count); + memset(cwfds, 0, sizeof(*cwfds)); + cwfds->wfds = static_wfds; + cwfds->count = static_count; +} + +static unsigned int cwfds_add_sock(struct Curl_waitfds *cwfds, + curl_socket_t sock, short events) +{ + int i; + if(!cwfds->wfds) { + DEBUGASSERT(!cwfds->count && !cwfds->n); + return 1; + } + if(cwfds->n <= INT_MAX) { + for(i = (int)cwfds->n - 1; i >= 0; --i) { + if(sock == cwfds->wfds[i].fd) { + cwfds->wfds[i].events |= events; + return 0; + } + } + } + /* not folded, add new entry */ + if(cwfds->n < cwfds->count) { + cwfds->wfds[cwfds->n].fd = sock; + cwfds->wfds[cwfds->n].events = events; + ++cwfds->n; + } + return 1; +} + +unsigned int Curl_waitfds_add_ps(struct Curl_waitfds *cwfds, + struct easy_pollset *ps) +{ + size_t i; + unsigned int need = 0; + + DEBUGASSERT(cwfds); + DEBUGASSERT(ps); + for(i = 0; i < ps->n; i++) { + short events = 0; + if(ps->actions[i] & CURL_POLL_IN) + events |= CURL_WAIT_POLLIN; + if(ps->actions[i] & CURL_POLL_OUT) + events |= CURL_WAIT_POLLOUT; + if(events) + need += cwfds_add_sock(cwfds, ps->sockets[i], events); + } + return need; +} + +void Curl_pollset_reset(struct easy_pollset *ps) +{ + unsigned int i; + ps->n = 0; +#ifdef DEBUGBUILD + DEBUGASSERT(ps->init == CURL_EASY_POLLSET_MAGIC); +#endif + DEBUGASSERT(ps->count); + for(i = 0; i < ps->count; i++) + ps->sockets[i] = CURL_SOCKET_BAD; + memset(ps->actions, 0, ps->count * sizeof(ps->actions[0])); +} + +void Curl_pollset_init(struct easy_pollset *ps) +{ +#ifdef DEBUGBUILD + ps->init = CURL_EASY_POLLSET_MAGIC; +#endif + ps->sockets = ps->def_sockets; + ps->actions = ps->def_actions; + ps->count = CURL_ARRAYSIZE(ps->def_sockets); + ps->n = 0; + Curl_pollset_reset(ps); +} + +struct easy_pollset *Curl_pollset_create(void) +{ + struct easy_pollset *ps = curlx_calloc(1, sizeof(*ps)); + if(ps) + Curl_pollset_init(ps); + return ps; +} + +void Curl_pollset_cleanup(struct easy_pollset *ps) +{ +#ifdef DEBUGBUILD + DEBUGASSERT(ps->init == CURL_EASY_POLLSET_MAGIC); +#endif + if(ps->sockets != ps->def_sockets) { + curlx_free(ps->sockets); + ps->sockets = ps->def_sockets; + } + if(ps->actions != ps->def_actions) { + curlx_free(ps->actions); + ps->actions = ps->def_actions; + } + ps->count = CURL_ARRAYSIZE(ps->def_sockets); + Curl_pollset_reset(ps); +} + +void Curl_pollset_move(struct easy_pollset *to, struct easy_pollset *from) +{ + Curl_pollset_cleanup(to); /* deallocate anything in to */ + if(from->sockets != from->def_sockets) { + DEBUGASSERT(from->actions != from->def_actions); + to->sockets = from->sockets; + to->actions = from->actions; + to->count = from->count; + to->n = from->n; + Curl_pollset_init(from); + } + else { + DEBUGASSERT(to->sockets == to->def_sockets); + DEBUGASSERT(to->actions == to->def_actions); + memcpy(to->sockets, from->sockets, to->count * sizeof(to->sockets[0])); + memcpy(to->actions, from->actions, to->count * sizeof(to->actions[0])); + to->n = from->n; + Curl_pollset_init(from); + } +} + +/** + * + */ +CURLcode Curl_pollset_change(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + int add_flags, int remove_flags) +{ + unsigned int i; + +#ifdef DEBUGBUILD + DEBUGASSERT(ps->init == CURL_EASY_POLLSET_MAGIC); +#endif + + DEBUGASSERT(VALID_SOCK(sock)); + if(!VALID_SOCK(sock)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + DEBUGASSERT(add_flags <= (CURL_POLL_IN | CURL_POLL_OUT)); + DEBUGASSERT(remove_flags <= (CURL_POLL_IN | CURL_POLL_OUT)); + DEBUGASSERT((add_flags & remove_flags) == 0); /* no overlap */ + for(i = 0; i < ps->n; ++i) { + if(ps->sockets[i] == sock) { + ps->actions[i] &= (unsigned char)(~remove_flags); + ps->actions[i] |= (unsigned char)add_flags; + /* all gone? remove socket */ + if(!ps->actions[i]) { + if((i + 1) < ps->n) { + memmove(&ps->sockets[i], &ps->sockets[i + 1], + (ps->n - (i + 1)) * sizeof(ps->sockets[0])); + memmove(&ps->actions[i], &ps->actions[i + 1], + (ps->n - (i + 1)) * sizeof(ps->actions[0])); + } + --ps->n; + } + return CURLE_OK; + } + } + /* not present */ + if(add_flags) { + if(i >= ps->count) { /* need to grow */ + unsigned int new_count = CURLMAX(ps->count * 2, 8); + curl_socket_t *nsockets; + unsigned char *nactions; + + CURL_TRC_M(data, "growing pollset capacity from %u to %u", + ps->count, new_count); + if(new_count <= ps->count) + return CURLE_OUT_OF_MEMORY; + nsockets = curlx_calloc(new_count, sizeof(nsockets[0])); + if(!nsockets) + return CURLE_OUT_OF_MEMORY; + nactions = curlx_calloc(new_count, sizeof(nactions[0])); + if(!nactions) { + curlx_free(nsockets); + return CURLE_OUT_OF_MEMORY; + } + memcpy(nsockets, ps->sockets, ps->count * sizeof(ps->sockets[0])); + memcpy(nactions, ps->actions, ps->count * sizeof(ps->actions[0])); + if(ps->sockets != ps->def_sockets) + curlx_free(ps->sockets); + ps->sockets = nsockets; + if(ps->actions != ps->def_actions) + curlx_free(ps->actions); + ps->actions = nactions; + ps->count = new_count; + } + DEBUGASSERT(i < ps->count); + if(i < ps->count) { + ps->sockets[i] = sock; + ps->actions[i] = (unsigned char)add_flags; + ps->n = i + 1; + } + } + return CURLE_OK; +} + +CURLcode Curl_pollset_set(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + bool do_in, bool do_out) +{ + return Curl_pollset_change(data, ps, sock, + (do_in ? CURL_POLL_IN : 0) | + (do_out ? CURL_POLL_OUT : 0), + (!do_in ? CURL_POLL_IN : 0) | + (!do_out ? CURL_POLL_OUT : 0)); +} + +/* + * Return values: + * -1 = error + * 0 = timeout + * N = number of structures with non zero revent fields + */ +int Curl_pollset_poll(struct Curl_easy *data, + struct easy_pollset *ps, + timediff_t timeout_ms) +{ + struct pollfd *pfds; + unsigned int i, npfds; + int rc; + + (void)data; + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + + if(!ps->n) + return curlx_wait_ms(timeout_ms); + + pfds = curlx_calloc(ps->n, sizeof(*pfds)); + if(!pfds) + return -1; + + npfds = 0; + for(i = 0; i < ps->n; ++i) { + short events = 0; + if(ps->actions[i] & CURL_POLL_IN) { + events |= POLLIN; + } + if(ps->actions[i] & CURL_POLL_OUT) { + events |= POLLOUT; + } + if(events) { + pfds[npfds].fd = ps->sockets[i]; + pfds[npfds].events = events; + ++npfds; + } + } + + rc = Curl_poll(pfds, npfds, timeout_ms); + curlx_free(pfds); + return rc; +} + +void Curl_pollset_check(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + bool *pwant_read, bool *pwant_write) +{ + unsigned int i; + + (void)data; + DEBUGASSERT(VALID_SOCK(sock)); + for(i = 0; i < ps->n; ++i) { + if(ps->sockets[i] == sock) { + *pwant_read = !!(ps->actions[i] & CURL_POLL_IN); + *pwant_write = !!(ps->actions[i] & CURL_POLL_OUT); + return; + } + } + *pwant_read = *pwant_write = FALSE; +} + +bool Curl_pollset_want_recv(struct Curl_easy *data, + struct easy_pollset *ps, + curl_socket_t sock) +{ + unsigned int i; + (void)data; + for(i = 0; i < ps->n; ++i) { + if((ps->sockets[i] == sock) && (ps->actions[i] & CURL_POLL_IN)) + return TRUE; + } + return FALSE; +} + +bool Curl_pollset_want_send(struct Curl_easy *data, + struct easy_pollset *ps, + curl_socket_t sock) +{ + unsigned int i; + (void)data; + for(i = 0; i < ps->n; ++i) { + if((ps->sockets[i] == sock) && (ps->actions[i] & CURL_POLL_OUT)) + return TRUE; + } + return FALSE; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/select.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/select.h new file mode 100644 index 0000000000..8fe519aee6 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/select.h @@ -0,0 +1,230 @@ +#ifndef HEADER_CURL_SELECT_H +#define HEADER_CURL_SELECT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_POLL_H +#include <poll.h> +#elif defined(HAVE_SYS_POLL_H) +#include <sys/poll.h> +#endif + +/* + * Definition of pollfd struct and constants for platforms lacking them. + */ + +#if !defined(HAVE_SYS_POLL_H) && !defined(HAVE_POLL_H) && !defined(POLLIN) + +#define POLLIN 0x01 +#define POLLPRI 0x02 +#define POLLOUT 0x04 +#define POLLERR 0x08 +#define POLLHUP 0x10 +#define POLLNVAL 0x20 + +struct pollfd { + curl_socket_t fd; + short events; + short revents; +}; + +#endif + +#ifndef POLLRDNORM +#define POLLRDNORM POLLIN +#endif + +#ifndef POLLWRNORM +#define POLLWRNORM POLLOUT +#endif + +#ifndef POLLRDBAND +#define POLLRDBAND POLLPRI +#endif + +/* there are three CSELECT defines that are defined in the public header that + are exposed to users, but this *IN2 bit is only ever used internally and + therefore defined here */ +#define CURL_CSELECT_IN2 (CURL_CSELECT_ERR << 1) + +int Curl_socket_check(curl_socket_t readfd0, + curl_socket_t readfd1, + curl_socket_t writefd, + timediff_t timeout_ms); +#define SOCKET_READABLE(x, z) \ + Curl_socket_check(x, CURL_SOCKET_BAD, CURL_SOCKET_BAD, z) +#define SOCKET_WRITABLE(x, z) \ + Curl_socket_check(CURL_SOCKET_BAD, CURL_SOCKET_BAD, x, z) + +int Curl_poll(struct pollfd ufds[], unsigned int nfds, timediff_t timeout_ms); + +/* With Winsock the valid range is [0..INVALID_SOCKET-1] according to + https://learn.microsoft.com/windows/win32/winsock/socket-data-type-2 */ +#ifdef USE_WINSOCK +#define VALID_SOCK(s) ((s) < INVALID_SOCKET) +#define FDSET_SOCK(x) 1 +#define VERIFY_SOCK(x) \ + do { \ + if(!VALID_SOCK(x)) { \ + SET_SOCKERRNO(SOCKEINVAL); \ + return -1; \ + } \ + } while(0) +#else +#define VALID_SOCK(s) ((s) >= 0) + +/* If the socket is small enough to get set or read from an fdset */ +#define FDSET_SOCK(s) ((s) < FD_SETSIZE) + +#define VERIFY_SOCK(x) \ + do { \ + if(!VALID_SOCK(x) || !FDSET_SOCK(x)) { \ + SET_SOCKERRNO(SOCKEINVAL); \ + return -1; \ + } \ + } while(0) +#endif + +/* Keep the sockets to poll for an easy handle. + * `actions` are bitmaps of CURL_POLL_IN and CURL_POLL_OUT. + * Starts with small capacity, grows on demand. + */ +#define EZ_POLLSET_DEF_COUNT 2 + +struct easy_pollset { + curl_socket_t *sockets; + unsigned char *actions; + unsigned int n; + unsigned int count; +#ifdef DEBUGBUILD + int init; +#endif + curl_socket_t def_sockets[EZ_POLLSET_DEF_COUNT]; + unsigned char def_actions[EZ_POLLSET_DEF_COUNT]; +}; + +#ifdef DEBUGBUILD +#define CURL_EASY_POLLSET_MAGIC 0x7a657370 +#endif + +/* allocate and initialize */ +struct easy_pollset *Curl_pollset_create(void); + +/* Initialize before first use */ +void Curl_pollset_init(struct easy_pollset *ps); +/* Free any allocated resources */ +void Curl_pollset_cleanup(struct easy_pollset *ps); +/* Reset to an empty pollset */ +void Curl_pollset_reset(struct easy_pollset *ps); +/* Move pollset from to pollset to, replacing all in to, + * leaving from empty. */ +void Curl_pollset_move(struct easy_pollset *to, struct easy_pollset *from); + +/* Change the poll flags (CURL_POLL_IN/CURL_POLL_OUT) to the poll set for + * socket `sock`. If the socket is not already part of the poll set, it + * will be added. + * If the socket is present and all poll flags are cleared, it will be removed. + */ +CURLcode Curl_pollset_change(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + int add_flags, + int remove_flags) WARN_UNUSED_RESULT; + +CURLcode Curl_pollset_set(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + bool do_in, bool do_out) WARN_UNUSED_RESULT; + +#define Curl_pollset_add_in(data, ps, sock) \ + Curl_pollset_change(data, ps, sock, CURL_POLL_IN, 0) +#define Curl_pollset_remove_in(data, ps, sock) \ + Curl_pollset_change(data, ps, sock, 0, CURL_POLL_IN) +#define Curl_pollset_add_out(data, ps, sock) \ + Curl_pollset_change(data, ps, sock, CURL_POLL_OUT, 0) +#define Curl_pollset_remove_out(data, ps, sock) \ + Curl_pollset_change(data, ps, sock, 0, CURL_POLL_OUT) +#define Curl_pollset_add_inout(data, ps, sock) \ + Curl_pollset_change(data, ps, sock, CURL_POLL_IN | CURL_POLL_OUT, 0) +#define Curl_pollset_set_in_only(data, ps, sock) \ + Curl_pollset_change(data, ps, sock, CURL_POLL_IN, CURL_POLL_OUT) +#define Curl_pollset_set_out_only(data, ps, sock) \ + Curl_pollset_change(data, ps, sock, CURL_POLL_OUT, CURL_POLL_IN) + +/* return < = on error, 0 on timeout or how many sockets are ready */ +int Curl_pollset_poll(struct Curl_easy *data, + struct easy_pollset *ps, + timediff_t timeout_ms); + +/** + * Check if the pollset, as is, wants to read and/or write regarding + * the given socket. + */ +void Curl_pollset_check(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + bool *pwant_read, bool *pwant_write); + +/* TRUE if the pollset contains socket with CURL_POLL_IN. */ +bool Curl_pollset_want_recv(struct Curl_easy *data, + struct easy_pollset *ps, + curl_socket_t sock); +/* TRUE if the pollset contains socket with CURL_POLL_OUT. */ +bool Curl_pollset_want_send(struct Curl_easy *data, + struct easy_pollset *ps, + curl_socket_t sock); + +struct curl_pollfds { + struct pollfd *pfds; + unsigned int n; + unsigned int count; + BIT(allocated_pfds); +}; + +void Curl_pollfds_init(struct curl_pollfds *cpfds, + struct pollfd *static_pfds, + unsigned int static_count); + +void Curl_pollfds_reset(struct curl_pollfds *cpfds); + +void Curl_pollfds_cleanup(struct curl_pollfds *cpfds); + +CURLcode Curl_pollfds_add_ps(struct curl_pollfds *cpfds, + struct easy_pollset *ps); + +CURLcode Curl_pollfds_add_sock(struct curl_pollfds *cpfds, + curl_socket_t sock, short events); + +struct Curl_waitfds { + struct curl_waitfd *wfds; + unsigned int n; + unsigned int count; +}; + +void Curl_waitfds_init(struct Curl_waitfds *cwfds, + struct curl_waitfd *static_wfds, + unsigned int static_count); + +unsigned int Curl_waitfds_add_ps(struct Curl_waitfds *cwfds, + struct easy_pollset *ps); + +#endif /* HEADER_CURL_SELECT_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/sendf.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/sendf.c new file mode 100644 index 0000000000..abd2e3fdbf --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/sendf.c @@ -0,0 +1,1502 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif + +#ifdef HAVE_LINUX_TCP_H +#include <linux/tcp.h> +#elif defined(HAVE_NETINET_TCP_H) +#include <netinet/tcp.h> +#endif + +#include "urldata.h" +#include "sendf.h" +#include "curl_trc.h" +#include "transfer.h" +#include "cfilters.h" +#include "connect.h" +#include "cw-out.h" +#include "cw-pause.h" +#include "multiif.h" +#include "progress.h" + +static void cl_reset_writer(struct Curl_easy *data) +{ + struct Curl_cwriter *writer = data->req.writer.stack; + while(writer) { + data->req.writer.stack = writer->next; + writer->cwt->do_close(data, writer); + curlx_free(writer); + writer = data->req.writer.stack; + } + data->req.writer.paused = FALSE; +} + +static void cl_reset_reader(struct Curl_easy *data) +{ + struct Curl_creader *reader = data->req.reader.stack; + data->req.reader_started = FALSE; + while(reader) { + data->req.reader.stack = reader->next; + reader->crt->do_close(data, reader); + curlx_free(reader); + reader = data->req.reader.stack; + } +} + +void Curl_client_cleanup(struct Curl_easy *data) +{ + cl_reset_reader(data); + cl_reset_writer(data); + + data->req.bytecount = 0; + data->req.headerline = 0; +} + +void Curl_client_reset(struct Curl_easy *data) +{ + if(data->req.rewind_read) { + /* already requested */ + CURL_TRC_READ(data, "client_reset, will rewind reader"); + } + else { + CURL_TRC_READ(data, "client_reset, clear readers"); + cl_reset_reader(data); + } + cl_reset_writer(data); + + data->req.bytecount = 0; + data->req.headerline = 0; +} + +CURLcode Curl_client_start(struct Curl_easy *data) +{ + if(data->req.rewind_read) { + struct Curl_creader *r = data->req.reader.stack; + CURLcode result = CURLE_OK; + + CURL_TRC_READ(data, "client start, rewind readers"); + while(r) { + result = r->crt->cntrl(data, r, CURL_CRCNTRL_REWIND); + if(result) { + failf(data, "rewind of client reader '%s' failed: %d", + r->crt->name, (int)result); + return result; + } + r = r->next; + } + data->req.rewind_read = FALSE; + cl_reset_reader(data); + } + return CURLE_OK; +} + +bool Curl_creader_will_rewind(struct Curl_easy *data) +{ + return (bool)data->req.rewind_read; +} + +void Curl_creader_set_rewind(struct Curl_easy *data, bool enable) +{ + data->req.rewind_read = !!enable; +} + +CURLcode Curl_cwriter_def_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + (void)data; + (void)writer; + return CURLE_OK; +} + +CURLcode Curl_cwriter_def_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); +} + +CURLcode Curl_cwriter_def_flush(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + return Curl_cwriter_flush(data, writer->next); +} + +void Curl_cwriter_def_close(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + (void)data; + (void)writer; +} + +static size_t get_max_body_write_len(struct Curl_easy *data, curl_off_t limit) +{ + if(limit != -1) { + /* How much more are we allowed to write? */ + return curlx_sotouz_range(limit - data->req.bytecount, 0, SIZE_MAX); + } + return SIZE_MAX; +} + +struct cw_download_ctx { + struct Curl_cwriter super; + BIT(started_response); + BIT(started_body); +}; + +/* Download client writer in phase CURL_CW_PROTOCOL that + * sees the "real" download body data. */ +static CURLcode cw_download_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + struct cw_download_ctx *ctx = writer->ctx; + CURLcode result; + size_t nwrite, excess_len = 0; + bool is_connect = !!(type & CLIENTWRITE_CONNECT); + + if(!ctx->started_response && + !(type & CLIENTWRITE_CONNECT) && + (!(type & CLIENTWRITE_INFO) || data->req.upload_done)) { + Curl_pgrsTime(data, TIMER_STARTTRANSFER); + ctx->started_response = TRUE; + } + + if(!(type & CLIENTWRITE_BODY)) { + if(is_connect && data->set.suppress_connect_headers) + return CURLE_OK; +#ifdef DEBUGBUILD + if(is_connect && getenv("CURL_DBG_SUPPRESS_CONNECT_HDS")) + return CURLE_OK; +#endif + result = Curl_cwriter_write(data, writer->next, type, buf, nbytes); + CURL_TRC_WRITE(data, "download_write header(type=%x, blen=%zu) -> %d", + (unsigned int)type, nbytes, (int)result); + return result; + } + + if(!ctx->started_body && + !(type & (CLIENTWRITE_INFO | CLIENTWRITE_CONNECT))) { + Curl_rlimit_start(&data->progress.dl.rlimit, Curl_pgrs_now(data), + data->req.size); + ctx->started_body = TRUE; + } + + /* Here, we deal with REAL BODY bytes. All filtering and transfer + * encodings have been applied and only the true content, e.g. BODY, + * bytes are passed here. + * This allows us to check sizes, update stats, etc. independent + * from the protocol in play. */ + + if(data->req.no_body && nbytes > 0) { + /* BODY arrives although we want none, bail out */ + streamclose(data->conn); + CURL_TRC_WRITE(data, "download_write body(type=%x, blen=%zu), " + "did not want a BODY", (unsigned int)type, nbytes); + data->req.download_done = TRUE; + if(data->info.header_size) + /* if headers have been received, this is fine */ + return CURLE_OK; + return CURLE_WEIRD_SERVER_REPLY; + } + + /* Determine if we see any bytes in excess to what is allowed. + * We write the allowed bytes and handle excess further below. + * This gives deterministic BODY writes on varying buffer receive + * lengths. */ + nwrite = nbytes; + if(data->req.maxdownload != -1) { + size_t wmax = get_max_body_write_len(data, data->req.maxdownload); + if(nwrite > wmax) { + excess_len = nbytes - wmax; + nwrite = wmax; + } + + if(nwrite == wmax) { + data->req.download_done = TRUE; + } + + if((type & CLIENTWRITE_EOS) && !data->req.no_body && + (data->req.size > data->req.bytecount)) { + failf(data, "end of response with %" FMT_OFF_T " bytes missing", + data->req.size - data->req.bytecount); + return CURLE_PARTIAL_FILE; + } + } + + /* Error on too large filesize is handled below, after writing + * the permitted bytes */ + if(data->set.max_filesize && !data->req.ignorebody) { + size_t wmax = get_max_body_write_len(data, data->set.max_filesize); + if(nwrite > wmax) { + nwrite = wmax; + } + } + + if(!data->req.ignorebody && (nwrite || (type & CLIENTWRITE_EOS))) { + result = Curl_cwriter_write(data, writer->next, type, buf, nwrite); + CURL_TRC_WRITE(data, "download_write body(type=%x, blen=%zu) -> %d", + (unsigned int)type, nbytes, (int)result); + if(result) + return result; + } + + /* Update stats, write and report progress */ + if(nwrite) { + data->req.bytecount += nwrite; + Curl_pgrs_download_inc(data, nwrite); + } + + if(excess_len) { + if(!data->req.ignorebody) { + infof(data, + "Excess found writing body:" + " excess = %zu" + ", size = %" FMT_OFF_T + ", maxdownload = %" FMT_OFF_T + ", bytecount = %" FMT_OFF_T, + excess_len, data->req.size, data->req.maxdownload, + data->req.bytecount); + connclose(data->conn); + } + } + else if((nwrite < nbytes) && !data->req.ignorebody) { + failf(data, "Exceeded the maximum allowed file size " + "(%" FMT_OFF_T ") with %" FMT_OFF_T " bytes", + data->set.max_filesize, data->req.bytecount); + return CURLE_FILESIZE_EXCEEDED; + } + + return CURLE_OK; +} + +static const struct Curl_cwtype cw_download = { + "protocol", + NULL, + 0, + Curl_cwriter_def_init, + cw_download_write, + Curl_cwriter_def_flush, + Curl_cwriter_def_close, + sizeof(struct cw_download_ctx) +}; + +/* RAW client writer in phase CURL_CW_RAW that + * enabled tracing of raw data. */ +static CURLcode cw_raw_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + if(type & CLIENTWRITE_BODY && data->set.verbose && !data->req.ignorebody) { + Curl_debug(data, CURLINFO_DATA_IN, buf, nbytes); + } + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); +} + +static const struct Curl_cwtype cw_raw = { + "raw", + NULL, + 0, + Curl_cwriter_def_init, + cw_raw_write, + Curl_cwriter_def_flush, + Curl_cwriter_def_close, + sizeof(struct Curl_cwriter) +}; + +static void cwriter_add(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct Curl_cwriter **anchor = &data->req.writer.stack; + + /* Insert the writer as first in its phase. + * Skip existing writers of lower phases. */ + while(*anchor && (*anchor)->phase < writer->phase) + anchor = &(*anchor)->next; + writer->next = *anchor; + *anchor = writer; +} + +static CURLcode do_init_writer_stack(struct Curl_easy *data) +{ + struct Curl_cwriter *writer; + CURLcode result; + + DEBUGASSERT(!data->req.writer.stack); + result = Curl_cwriter_create(&data->req.writer.stack, + data, &Curl_cwt_out, CURL_CW_CLIENT); + if(result) + return result; + + result = Curl_cwriter_create(&writer, data, &cw_download, CURL_CW_PROTOCOL); + if(result) + return result; + cwriter_add(data, writer); + + result = Curl_cwriter_create(&writer, data, &cw_raw, CURL_CW_RAW); + if(result) + return result; + cwriter_add(data, writer); + + return result; +} + +/* Curl_client_write() sends data to the write callback(s) + + The bit pattern defines to what "streams" to write to. Body and/or header. + The defines are in sendf.h of course. + */ +CURLcode Curl_client_write(struct Curl_easy *data, int type, const char *buf, + size_t len) +{ + CURLcode result; + + /* it is one of those, at least */ + DEBUGASSERT(type & + (CLIENTWRITE_BODY | CLIENTWRITE_HEADER | CLIENTWRITE_INFO)); + /* BODY is only BODY (with optional EOS) */ + DEBUGASSERT(!(type & CLIENTWRITE_BODY) || + ((type & ~(CLIENTWRITE_BODY | CLIENTWRITE_EOS)) == 0)); + /* INFO is only INFO (with optional EOS) */ + DEBUGASSERT(!(type & CLIENTWRITE_INFO) || + ((type & ~(CLIENTWRITE_INFO | CLIENTWRITE_EOS)) == 0)); + + if(!data->req.writer.stack) { + result = do_init_writer_stack(data); + if(result) + return result; + DEBUGASSERT(data->req.writer.stack); + } + + result = Curl_cwriter_write(data, data->req.writer.stack, type, buf, len); + CURL_TRC_WRITE(data, "client_write(type=%x, len=%zu) -> %d", + (unsigned int)type, len, (int)result); + return result; +} + +CURLcode Curl_client_flush(struct Curl_easy *data) +{ + CURLcode result; + + if(!data->req.writer.stack) { + result = do_init_writer_stack(data); + if(result) + return result; + DEBUGASSERT(data->req.writer.stack); + } + + result = Curl_cwriter_flush(data, data->req.writer.stack); + CURL_TRC_WRITE(data, "client_flush() -> %d", (int)result); + return result; +} + +/* Create an unencoding writer stage using the given handler. */ +CURLcode Curl_cwriter_create(struct Curl_cwriter **pwriter, + struct Curl_easy *data, + const struct Curl_cwtype *cwt, + Curl_cwriter_phase phase) +{ + struct Curl_cwriter *writer = NULL; + CURLcode result = CURLE_OUT_OF_MEMORY; + void *p; + + DEBUGASSERT(cwt->cwriter_size >= sizeof(struct Curl_cwriter)); + p = curlx_calloc(1, cwt->cwriter_size); + if(!p) + goto out; + + writer = (struct Curl_cwriter *)p; + writer->cwt = cwt; + writer->ctx = p; + writer->phase = phase; + result = cwt->do_init(data, writer); + +out: + *pwriter = result ? NULL : writer; + if(result) + curlx_free(writer); + return result; +} + +void Curl_cwriter_free(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + if(writer) { + writer->cwt->do_close(data, writer); + curlx_free(writer); + } +} + +size_t Curl_cwriter_count(struct Curl_easy *data, Curl_cwriter_phase phase) +{ + struct Curl_cwriter *w; + size_t n = 0; + + for(w = data->req.writer.stack; w; w = w->next) { + if(w->phase == phase) + ++n; + } + return n; +} + +static CURLcode cwriter_ensure_pause_writer(struct Curl_easy *data) +{ + struct Curl_cwriter *writer = + Curl_cwriter_get_by_type(data, &Curl_cwt_pause); + CURLcode result = CURLE_OK; + + if(!writer) { + result = Curl_cwriter_create(&writer, data, &Curl_cwt_pause, + CURL_CW_BEFORE_DECODE); + if(!result) + cwriter_add(data, writer); + } + return result; +} + +CURLcode Curl_cwriter_add(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + CURLcode result; + struct Curl_cwriter **anchor = &data->req.writer.stack; + + if(!*anchor) { + result = do_init_writer_stack(data); + if(result) + return result; + } + + if(writer->cwt->flags & CURL_CW_FLAG_BLOWUP) { + /* On adding a writer that may blow up write sizes, e.g. zip bombs, + * add the pause writer. Do this first as any failure will make the + * caller destroy the writer again. */ + result = cwriter_ensure_pause_writer(data); + if(result) + return result; + } + + cwriter_add(data, writer); + return CURLE_OK; +} + +struct Curl_cwriter *Curl_cwriter_get_by_name(struct Curl_easy *data, + const char *name) +{ + struct Curl_cwriter *writer; + for(writer = data->req.writer.stack; writer; writer = writer->next) { + if(!strcmp(name, writer->cwt->name)) + return writer; + } + return NULL; +} + +struct Curl_cwriter *Curl_cwriter_get_by_type(struct Curl_easy *data, + const struct Curl_cwtype *cwt) +{ + struct Curl_cwriter *writer; + for(writer = data->req.writer.stack; writer; writer = writer->next) { + if(writer->cwt == cwt) + return writer; + } + return NULL; +} + +CURLcode Curl_cwriter_unpause(struct Curl_easy *data) +{ + data->req.writer.paused = FALSE; + return Curl_cwriter_flush(data, data->req.writer.stack); +} + +CURLcode Curl_creader_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, size_t *nread, bool *eos) +{ + *nread = 0; + *eos = FALSE; + if(!reader) + return CURLE_READ_ERROR; + return reader->crt->do_read(data, reader, buf, blen, nread, eos); +} + +void Curl_creader_clear_eos(struct Curl_easy *data, + struct Curl_creader *reader) +{ + while(reader) { + (void)reader->crt->cntrl(data, reader, CURL_CRCNTRL_CLEAR_EOS); + reader = reader->next; + } +} + +CURLcode Curl_creader_def_init(struct Curl_easy *data, + struct Curl_creader *reader) +{ + (void)data; + (void)reader; + return CURLE_OK; +} + +void Curl_creader_def_close(struct Curl_easy *data, + struct Curl_creader *reader) +{ + (void)data; + (void)reader; +} + +CURLcode Curl_creader_def_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *nread, bool *eos) +{ + if(reader->next) + return reader->next->crt->do_read(data, reader->next, buf, blen, + nread, eos); + else { + *nread = 0; + *eos = FALSE; + return CURLE_READ_ERROR; + } +} + +bool Curl_creader_def_needs_rewind(struct Curl_easy *data, + struct Curl_creader *reader) +{ + (void)data; + (void)reader; + return FALSE; +} + +curl_off_t Curl_creader_def_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + return reader->next ? + reader->next->crt->total_length(data, reader->next) : -1; +} + +CURLcode Curl_creader_def_resume_from(struct Curl_easy *data, + struct Curl_creader *reader, + curl_off_t offset) +{ + (void)data; + (void)reader; + (void)offset; + return CURLE_READ_ERROR; +} + +CURLcode Curl_creader_def_cntrl(struct Curl_easy *data, + struct Curl_creader *reader, + Curl_creader_cntrl opcode) +{ + (void)data; + (void)reader; + (void)opcode; + return CURLE_OK; +} + +bool Curl_creader_def_is_paused(struct Curl_easy *data, + struct Curl_creader *reader) +{ + (void)data; + (void)reader; + return FALSE; +} + +void Curl_creader_def_done(struct Curl_easy *data, + struct Curl_creader *reader, int premature) +{ + (void)data; + (void)reader; + (void)premature; +} + +struct cr_in_ctx { + struct Curl_creader super; + curl_read_callback read_cb; + void *cb_user_data; + curl_off_t total_len; + curl_off_t read_len; + CURLcode error_result; + BIT(seen_eos); + BIT(errored); + BIT(has_used_cb); + BIT(is_paused); +}; + +static CURLcode cr_in_init(struct Curl_easy *data, struct Curl_creader *reader) +{ + struct cr_in_ctx *ctx = reader->ctx; + ctx->read_cb = data->state.fread_func; + ctx->cb_user_data = data->state.in; + ctx->total_len = -1; + ctx->read_len = 0; + return CURLE_OK; +} + +/* Real client reader to installed client callbacks. */ +static CURLcode cr_in_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + struct cr_in_ctx *ctx = reader->ctx; + CURLcode result = CURLE_OK; + size_t nread; + + ctx->is_paused = FALSE; + + /* Once we have errored, we will return the same error forever */ + if(ctx->errored) { + *pnread = 0; + *peos = FALSE; + return ctx->error_result; + } + if(ctx->seen_eos) { + *pnread = 0; + *peos = TRUE; + return CURLE_OK; + } + /* respect length limitations */ + if(ctx->total_len >= 0) { + blen = curlx_sotouz_range(ctx->total_len - ctx->read_len, 0, blen); + } + nread = 0; + if(ctx->read_cb && blen) { + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_cr_in_read); + nread = ctx->read_cb(buf, 1, blen, ctx->cb_user_data); + CURL_CBAPI_END(&guard); + ctx->has_used_cb = TRUE; + } + + switch(nread) { + case 0: + if((ctx->total_len >= 0) && (ctx->read_len < ctx->total_len)) { + failf(data, "client read function EOF fail, " + "only %" FMT_OFF_T "/%" FMT_OFF_T " of needed bytes read", + ctx->read_len, ctx->total_len); + result = CURLE_READ_ERROR; + break; + } + *pnread = 0; + *peos = TRUE; + ctx->seen_eos = TRUE; + break; + + case CURL_READFUNC_ABORT: + failf(data, "operation aborted by callback"); + *pnread = 0; + *peos = FALSE; + ctx->errored = TRUE; + ctx->error_result = CURLE_ABORTED_BY_CALLBACK; + result = CURLE_ABORTED_BY_CALLBACK; + break; + + case CURL_READFUNC_PAUSE: + if(data->conn->scheme->flags & PROTOPT_NONETWORK) { + /* protocols that work without network cannot be paused. This is + actually only file:// now, and it cannot pause since the transfer + is not done using the "normal" procedure. */ + failf(data, "Read callback asked for PAUSE when not supported"); + result = CURLE_READ_ERROR; + break; + } + /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */ + CURL_TRC_READ(data, "cr_in_read, callback returned CURL_READFUNC_PAUSE"); + ctx->is_paused = TRUE; + *pnread = 0; + *peos = FALSE; + result = Curl_xfer_pause_send(data, TRUE); + break; /* nothing was read */ + + default: + if(nread > blen) { + /* the read function returned a too large value */ + failf(data, "read function returned funny value"); + *pnread = 0; + *peos = FALSE; + ctx->errored = TRUE; + ctx->error_result = CURLE_READ_ERROR; + result = CURLE_READ_ERROR; + break; + } + ctx->read_len += nread; + if(ctx->total_len >= 0) + ctx->seen_eos = (ctx->read_len >= ctx->total_len); + *pnread = nread; + *peos = (bool)ctx->seen_eos; + break; + } + CURL_TRC_READ(data, "cr_in_read(len=%zu, total=%" FMT_OFF_T + ", read=%" FMT_OFF_T ") -> %d, nread=%zu, eos=%d", + blen, ctx->total_len, ctx->read_len, (int)result, + *pnread, *peos); + return result; +} + +static bool cr_in_needs_rewind(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_in_ctx *ctx = reader->ctx; + (void)data; + return (bool)ctx->has_used_cb; +} + +static curl_off_t cr_in_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_in_ctx *ctx = reader->ctx; + (void)data; + return ctx->total_len; +} + +static CURLcode cr_in_resume_from(struct Curl_easy *data, + struct Curl_creader *reader, + curl_off_t offset) +{ + struct cr_in_ctx *ctx = reader->ctx; + int seekerr = CURL_SEEKFUNC_CANTSEEK; + + DEBUGASSERT(data->conn); + /* already started reading? */ + if(ctx->read_len) + return CURLE_READ_ERROR; + + if(data->set.seek_func) { + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_seek_func); + seekerr = data->set.seek_func(data->set.seek_client, offset, SEEK_SET); + CURL_CBAPI_END(&guard); + } + + if(seekerr != CURL_SEEKFUNC_OK) { + curl_off_t passed = 0; + + if(seekerr != CURL_SEEKFUNC_CANTSEEK) { + failf(data, "Could not seek stream"); + return CURLE_READ_ERROR; + } + /* when seekerr == CURL_SEEKFUNC_CANTSEEK (cannot seek to offset) */ + do { + struct Curl_mapi_guard guard; + char scratch[4 * 1024]; + size_t readthisamountnow = + (offset - passed > (curl_off_t)sizeof(scratch)) ? + sizeof(scratch) : + curlx_sotouz(offset - passed); + size_t actuallyread; + + CURL_CBAPI_START(&guard, data, easy_cr_in_resume_from); + actuallyread = ctx->read_cb(scratch, 1, readthisamountnow, + ctx->cb_user_data); + CURL_CBAPI_END(&guard); + + passed += actuallyread; + if((actuallyread == 0) || (actuallyread > readthisamountnow)) { + /* this checks for greater-than only to make sure that the + CURL_READFUNC_ABORT return code still aborts */ + failf(data, "Could only read %" FMT_OFF_T " bytes from the input", + passed); + return CURLE_READ_ERROR; + } + } while(passed < offset); + } + + /* now, decrease the size of the read */ + if(ctx->total_len > 0) { + ctx->total_len -= offset; + + if(ctx->total_len <= 0) { + failf(data, "File already completely uploaded"); + return CURLE_PARTIAL_FILE; + } + } + /* we have passed, proceed as normal */ + return CURLE_OK; +} + +static CURLcode cr_in_rewind(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_in_ctx *ctx = reader->ctx; + + /* If we never invoked the callback, there is noting to rewind */ + if(!ctx->has_used_cb) + return CURLE_OK; + + if(data->set.seek_func) { + struct Curl_mapi_guard guard; + int err; + + CURL_CBAPI_START(&guard, data, easy_seek_func); + err = data->set.seek_func(data->set.seek_client, 0, SEEK_SET); + CURL_CBAPI_END(&guard); + CURL_TRC_READ(data, "cr_in, rewind via set.seek_func -> %d", err); + if(err) { + failf(data, "seek callback returned error %d", err); + return CURLE_SEND_FAIL_REWIND; + } + } + else if(data->set.ioctl_func) { + struct Curl_mapi_guard guard; + curlioerr err; + + CURL_CBAPI_START(&guard, data, easy_ioctl_func); + err = data->set.ioctl_func(data, CURLIOCMD_RESTARTREAD, + data->set.ioctl_client); + CURL_CBAPI_END(&guard); + CURL_TRC_READ(data, "cr_in, rewind via set.ioctl_func -> %d", (int)err); + if(err) { + failf(data, "ioctl callback returned error %d", (int)err); + return CURLE_SEND_FAIL_REWIND; + } + } + else { + /* If no CURLOPT_READFUNCTION is used, we know that we operate on a + given FILE * stream and we can actually attempt to rewind that + ourselves with fseek() */ +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcast-function-type-strict" +#endif + if(data->state.fread_func == (curl_read_callback)fread) { +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic pop +#endif + int err = fseek(data->state.in, 0, SEEK_SET); + CURL_TRC_READ(data, "cr_in, rewind via fseek -> %d(%d)", + (int)err, (int)errno); + if(err != -1) + /* successful rewind */ + return CURLE_OK; + } + + /* no callback set or failure above, makes us fail at once */ + failf(data, "necessary data rewind was not possible"); + return CURLE_SEND_FAIL_REWIND; + } + return CURLE_OK; +} + +static CURLcode cr_in_cntrl(struct Curl_easy *data, + struct Curl_creader *reader, + Curl_creader_cntrl opcode) +{ + struct cr_in_ctx *ctx = reader->ctx; + + switch(opcode) { + case CURL_CRCNTRL_REWIND: + return cr_in_rewind(data, reader); + case CURL_CRCNTRL_UNPAUSE: + ctx->is_paused = FALSE; + break; + case CURL_CRCNTRL_CLEAR_EOS: + ctx->seen_eos = FALSE; + break; + default: + break; + } + return CURLE_OK; +} + +static bool cr_in_is_paused(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_in_ctx *ctx = reader->ctx; + (void)data; + return (bool)ctx->is_paused; +} + +static const struct Curl_crtype cr_in = { + "cr-in", + cr_in_init, + cr_in_read, + Curl_creader_def_close, + cr_in_needs_rewind, + cr_in_total_length, + cr_in_resume_from, + cr_in_cntrl, + cr_in_is_paused, + Curl_creader_def_done, + sizeof(struct cr_in_ctx) +}; + +CURLcode Curl_creader_create(struct Curl_creader **preader, + struct Curl_easy *data, + const struct Curl_crtype *crt, + Curl_creader_phase phase) +{ + struct Curl_creader *reader = NULL; + CURLcode result = CURLE_OUT_OF_MEMORY; + void *p; + + DEBUGASSERT(crt->creader_size >= sizeof(struct Curl_creader)); + p = curlx_calloc(1, crt->creader_size); + if(!p) + goto out; + + reader = (struct Curl_creader *)p; + reader->crt = crt; + reader->ctx = p; + reader->phase = phase; + result = crt->do_init(data, reader); + +out: + *preader = result ? NULL : reader; + if(result) + curlx_free(reader); + return result; +} + +void Curl_creader_free(struct Curl_easy *data, struct Curl_creader *reader) +{ + if(reader) { + reader->crt->do_close(data, reader); + curlx_free(reader); + } +} + +struct cr_lc_ctx { + struct Curl_creader super; + struct bufq buf; + BIT(read_eos); /* we read an EOS from the next reader */ + BIT(eos); /* we have returned an EOS */ + BIT(prev_cr); /* the last byte was a CR */ +}; + +static CURLcode cr_lc_init(struct Curl_easy *data, struct Curl_creader *reader) +{ + struct cr_lc_ctx *ctx = reader->ctx; + (void)data; + Curl_bufq_init2(&ctx->buf, (16 * 1024), 1, BUFQ_OPT_SOFT_LIMIT); + return CURLE_OK; +} + +static void cr_lc_close(struct Curl_easy *data, struct Curl_creader *reader) +{ + struct cr_lc_ctx *ctx = reader->ctx; + (void)data; + Curl_bufq_free(&ctx->buf); +} + +/* client reader doing line end conversions. */ +static CURLcode cr_lc_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + struct cr_lc_ctx *ctx = reader->ctx; + CURLcode result; + size_t nread, i, start, n; + bool eos; + + if(ctx->eos) { + *pnread = 0; + *peos = TRUE; + return CURLE_OK; + } + + if(Curl_bufq_is_empty(&ctx->buf)) { + if(ctx->read_eos) { + ctx->eos = TRUE; + *pnread = 0; + *peos = TRUE; + return CURLE_OK; + } + /* Still getting data form the next reader, ctx->buf is empty */ + result = Curl_creader_read(data, reader->next, buf, blen, &nread, &eos); + if(result) + return result; + ctx->read_eos = eos; + + if(!nread || !memchr(buf, '\n', nread)) { + /* nothing to convert, return this right away */ + if(nread) + ctx->prev_cr = (buf[nread - 1] == '\r'); + if(ctx->read_eos) + ctx->eos = TRUE; + *pnread = nread; + *peos = (bool)ctx->eos; + goto out; + } + + /* at least one \n might need conversion to '\r\n', place into ctx->buf */ + for(i = start = 0; i < nread; ++i) { + /* if this byte is not an LF character, or if the preceding character is + a CR (meaning this already is a CRLF pair), go to next */ + if((buf[i] != '\n') || ctx->prev_cr) { + ctx->prev_cr = (buf[i] == '\r'); + continue; + } + ctx->prev_cr = FALSE; + /* on a soft limit bufq, we do not need to check length */ + result = Curl_bufq_cwrite(&ctx->buf, buf + start, i - start, &n); + if(!result) + result = Curl_bufq_cwrite(&ctx->buf, STRCONST("\r\n"), &n); + if(result) + return result; + start = i + 1; + } + + if(start < i) { /* leftover */ + result = Curl_bufq_cwrite(&ctx->buf, buf + start, i - start, &n); + if(result) + return result; + } + } + + DEBUGASSERT(!Curl_bufq_is_empty(&ctx->buf)); + *peos = FALSE; + result = Curl_bufq_cread(&ctx->buf, buf, blen, pnread); + if(!result && ctx->read_eos && Curl_bufq_is_empty(&ctx->buf)) { + /* no more data, read all, done. */ + ctx->eos = TRUE; + *peos = TRUE; + } + +out: + CURL_TRC_READ(data, "cr_lc_read(len=%zu) -> %d, nread=%zu, eos=%d", + blen, (int)result, *pnread, *peos); + return result; +} + +static curl_off_t cr_lc_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + /* this reader changes length depending on input */ + (void)data; + (void)reader; + return -1; +} + +static const struct Curl_crtype cr_lc = { + "cr-lineconv", + cr_lc_init, + cr_lc_read, + cr_lc_close, + Curl_creader_def_needs_rewind, + cr_lc_total_length, + Curl_creader_def_resume_from, + Curl_creader_def_cntrl, + Curl_creader_def_is_paused, + Curl_creader_def_done, + sizeof(struct cr_lc_ctx) +}; + +static CURLcode cr_lc_add(struct Curl_easy *data) +{ + struct Curl_creader *reader = NULL; + CURLcode result; + + result = Curl_creader_create(&reader, data, &cr_lc, CURL_CR_CONTENT_ENCODE); + if(!result) + result = Curl_creader_add(data, reader); + + if(result && reader) + Curl_creader_free(data, reader); + return result; +} + +static CURLcode do_init_reader_stack(struct Curl_easy *data, + struct Curl_creader *r) +{ + CURLcode result = CURLE_OK; + curl_off_t clen; + + DEBUGASSERT(r); + DEBUGASSERT(r->crt); + DEBUGASSERT(r->phase == CURL_CR_CLIENT); + DEBUGASSERT(!data->req.reader.stack); + + data->req.reader.stack = r; + clen = r->crt->total_length(data, r); + /* if we do not have 0 length init, and CRLF conversion is wanted, + * add the reader for it */ + if(clen && +#ifdef CURL_PREFER_LF_LINEENDS + (data->set.crlf || data->state.prefer_ascii) +#else + data->set.crlf +#endif + ) { + result = cr_lc_add(data); + if(result) + return result; + } + + return result; +} + +CURLcode Curl_creader_set_fread(struct Curl_easy *data, curl_off_t len) +{ + CURLcode result; + struct Curl_creader *r; + struct cr_in_ctx *ctx; + + result = Curl_creader_create(&r, data, &cr_in, CURL_CR_CLIENT); + if(result || !r) + goto out; + ctx = r->ctx; + ctx->total_len = len; + + cl_reset_reader(data); + result = do_init_reader_stack(data, r); +out: + CURL_TRC_READ(data, "add fread reader, len=%" FMT_OFF_T " -> %d", + len, (int)result); + return result; +} + +CURLcode Curl_creader_add(struct Curl_easy *data, + struct Curl_creader *reader) +{ + CURLcode result; + struct Curl_creader **anchor = &data->req.reader.stack; + + if(!*anchor) { + result = Curl_creader_set_fread(data, data->state.infilesize); + if(result) + return result; + } + + /* Insert the writer as first in its phase. + * Skip existing readers of lower phases. */ + while(*anchor && (*anchor)->phase < reader->phase) + anchor = &(*anchor)->next; + reader->next = *anchor; + *anchor = reader; + return CURLE_OK; +} + +CURLcode Curl_creader_set(struct Curl_easy *data, struct Curl_creader *r) +{ + CURLcode result; + + DEBUGASSERT(r); + DEBUGASSERT(r->crt); + DEBUGASSERT(r->phase == CURL_CR_CLIENT); + + cl_reset_reader(data); + result = do_init_reader_stack(data, r); + if(result) + Curl_creader_free(data, r); + return result; +} + +CURLcode Curl_client_read(struct Curl_easy *data, char *buf, size_t blen, + size_t *nread, bool *eos) +{ + CURLcode result; + + DEBUGASSERT(buf); + DEBUGASSERT(blen); + DEBUGASSERT(nread); + DEBUGASSERT(eos); + *nread = 0; + + if(!data->req.reader.stack) { + result = Curl_creader_set_fread(data, data->state.infilesize); + if(result) + return result; + DEBUGASSERT(data->req.reader.stack); + } + if(!data->req.reader_started) { + Curl_rlimit_start(&data->progress.ul.rlimit, Curl_pgrs_now(data), -1); + data->req.reader_started = TRUE; + } + + if(Curl_rlimit_active(&data->progress.ul.rlimit)) { + curl_off_t ul_avail = Curl_rlimit_avail(&data->progress.ul.rlimit, NULL); + if(ul_avail <= 0) { + result = CURLE_OK; + *eos = FALSE; + goto out; + } + if(ul_avail < (curl_off_t)blen) + blen = (size_t)ul_avail; + } + result = Curl_creader_read(data, data->req.reader.stack, buf, blen, + nread, eos); + +out: + CURL_TRC_READ(data, "client_read(len=%zu) -> %d, nread=%zu, eos=%d", + blen, (int)result, *nread, *eos); + return result; +} + +bool Curl_creader_needs_rewind(struct Curl_easy *data) +{ + struct Curl_creader *reader = data->req.reader.stack; + while(reader) { + if(reader->crt->needs_rewind(data, reader)) { + CURL_TRC_READ(data, "client reader needs rewind before next request"); + return TRUE; + } + reader = reader->next; + } + return FALSE; +} + +static CURLcode cr_null_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + (void)data; + (void)reader; + (void)buf; + (void)blen; + *pnread = 0; + *peos = TRUE; + return CURLE_OK; +} + +static curl_off_t cr_null_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + /* this reader changes length depending on input */ + (void)data; + (void)reader; + return 0; +} + +static const struct Curl_crtype cr_null = { + "cr-null", + Curl_creader_def_init, + cr_null_read, + Curl_creader_def_close, + Curl_creader_def_needs_rewind, + cr_null_total_length, + Curl_creader_def_resume_from, + Curl_creader_def_cntrl, + Curl_creader_def_is_paused, + Curl_creader_def_done, + sizeof(struct Curl_creader) +}; + +CURLcode Curl_creader_set_null(struct Curl_easy *data) +{ + struct Curl_creader *r; + CURLcode result; + + result = Curl_creader_create(&r, data, &cr_null, CURL_CR_CLIENT); + if(result) + return result; + + cl_reset_reader(data); + return do_init_reader_stack(data, r); +} + +struct cr_buf_ctx { + struct Curl_creader super; + const char *buf; + size_t blen; + size_t index; +}; + +static CURLcode cr_buf_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + struct cr_buf_ctx *ctx = reader->ctx; + size_t nread = ctx->blen - ctx->index; + + if(!nread || !ctx->buf) { + *pnread = 0; + *peos = TRUE; + } + else { + if(nread > blen) + nread = blen; + memcpy(buf, ctx->buf + ctx->index, nread); + *pnread = nread; + ctx->index += nread; + *peos = (ctx->index == ctx->blen); + } + CURL_TRC_READ(data, "cr_buf_read(len=%zu) -> 0, nread=%zu, eos=%d", + blen, *pnread, *peos); + return CURLE_OK; +} + +static bool cr_buf_needs_rewind(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_buf_ctx *ctx = reader->ctx; + (void)data; + return ctx->index > 0; +} + +static CURLcode cr_buf_cntrl(struct Curl_easy *data, + struct Curl_creader *reader, + Curl_creader_cntrl opcode) +{ + struct cr_buf_ctx *ctx = reader->ctx; + (void)data; + switch(opcode) { + case CURL_CRCNTRL_REWIND: + ctx->index = 0; + break; + default: + break; + } + return CURLE_OK; +} + +static curl_off_t cr_buf_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_buf_ctx *ctx = reader->ctx; + (void)data; + return (curl_off_t)ctx->blen; +} + +static CURLcode cr_buf_resume_from(struct Curl_easy *data, + struct Curl_creader *reader, + curl_off_t offset) +{ + struct cr_buf_ctx *ctx = reader->ctx; + size_t boffset; + + (void)data; + DEBUGASSERT(data->conn); + /* already started reading? */ + if(ctx->index) + return CURLE_READ_ERROR; + boffset = curlx_sotouz_range(offset, 0, SIZE_MAX); + if(!boffset) + return CURLE_OK; + if(boffset > ctx->blen) + return CURLE_READ_ERROR; + + ctx->buf += boffset; + ctx->blen -= boffset; + return CURLE_OK; +} + +static const struct Curl_crtype cr_buf = { + "cr-buf", + Curl_creader_def_init, + cr_buf_read, + Curl_creader_def_close, + cr_buf_needs_rewind, + cr_buf_total_length, + cr_buf_resume_from, + cr_buf_cntrl, + Curl_creader_def_is_paused, + Curl_creader_def_done, + sizeof(struct cr_buf_ctx) +}; + +CURLcode Curl_creader_set_buf(struct Curl_easy *data, + const char *buf, size_t blen) +{ + CURLcode result; + struct Curl_creader *r; + struct cr_buf_ctx *ctx; + + result = Curl_creader_create(&r, data, &cr_buf, CURL_CR_CLIENT); + if(result) + goto out; + ctx = r->ctx; + ctx->buf = buf; + ctx->blen = blen; + ctx->index = 0; + + cl_reset_reader(data); + result = do_init_reader_stack(data, r); +out: + CURL_TRC_READ(data, "add buf reader, len=%zu -> %d", blen, (int)result); + return result; +} + +curl_off_t Curl_creader_total_length(struct Curl_easy *data) +{ + struct Curl_creader *r = data->req.reader.stack; + return r ? r->crt->total_length(data, r) : -1; +} + +curl_off_t Curl_creader_client_length(struct Curl_easy *data) +{ + struct Curl_creader *r = data->req.reader.stack; + while(r && r->phase != CURL_CR_CLIENT) + r = r->next; + return r ? r->crt->total_length(data, r) : -1; +} + +CURLcode Curl_creader_resume_from(struct Curl_easy *data, curl_off_t offset) +{ + struct Curl_creader *r = data->req.reader.stack; + while(r && r->phase != CURL_CR_CLIENT) + r = r->next; + return r ? r->crt->resume_from(data, r, offset) : CURLE_READ_ERROR; +} + +CURLcode Curl_creader_unpause(struct Curl_easy *data) +{ + struct Curl_creader *reader = data->req.reader.stack; + CURLcode result = CURLE_OK; + + while(reader) { + result = reader->crt->cntrl(data, reader, CURL_CRCNTRL_UNPAUSE); + CURL_TRC_READ(data, "unpausing %s -> %d", reader->crt->name, (int)result); + if(result) + break; + reader = reader->next; + } + return result; +} + +bool Curl_creader_is_paused(struct Curl_easy *data) +{ + struct Curl_creader *reader = data->req.reader.stack; + + while(reader) { + if(reader->crt->is_paused(data, reader)) + return TRUE; + reader = reader->next; + } + return FALSE; +} + +void Curl_creader_done(struct Curl_easy *data, int premature) +{ + struct Curl_creader *reader = data->req.reader.stack; + while(reader) { + reader->crt->done(data, reader, premature); + reader = reader->next; + } +} + +struct Curl_creader *Curl_creader_get_by_type(struct Curl_easy *data, + const struct Curl_crtype *crt) +{ + struct Curl_creader *r; + for(r = data->req.reader.stack; r; r = r->next) { + if(r->crt == crt) + return r; + } + return NULL; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/sendf.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/sendf.h new file mode 100644 index 0000000000..9863c5b0dc --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/sendf.h @@ -0,0 +1,431 @@ +#ifndef HEADER_CURL_SENDF_H +#define HEADER_CURL_SENDF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "cw-out.h" + +/** + * Type of data that is being written to the client (application) + * - data written can be either BODY or META data + * - META data is either INFO or HEADER + * - INFO is meta information, e.g. not BODY, that cannot be interpreted + * as headers of a response. Example FTP/IMAP pingpong answers. + * - HEADER can have additional bits set (more than one) + * - STATUS special "header", e.g. response status line in HTTP + * - CONNECT header was received during proxying the connection + * - 1XX header is part of an intermediate response, e.g. HTTP 1xx code + * - TRAILER header is trailing response data, e.g. HTTP trailers + * BODY, INFO and HEADER should not be mixed, as this would lead to + * confusion on how to interpret/format/convert the data. + */ +#define CLIENTWRITE_BODY (1 << 0) /* non-meta information, BODY */ +#define CLIENTWRITE_INFO (1 << 1) /* meta information, not a HEADER */ +#define CLIENTWRITE_HEADER (1 << 2) /* meta information, HEADER */ +#define CLIENTWRITE_STATUS (1 << 3) /* a special status HEADER */ +#define CLIENTWRITE_CONNECT (1 << 4) /* a CONNECT related HEADER */ +#define CLIENTWRITE_1XX (1 << 5) /* a 1xx response related HEADER */ +#define CLIENTWRITE_TRAILER (1 << 6) /* a trailer HEADER */ +#define CLIENTWRITE_EOS (1 << 7) /* End Of transfer download Stream */ +#define CLIENTWRITE_0LEN (1 << 8) /* write even 0-length buffers */ + +/* Forward declarations */ +struct Curl_creader; +struct Curl_cwriter; +struct Curl_easy; + +/** + * Write `len` bytes at `buf` to the client. `type` indicates what + * kind of data is being written. + */ +CURLcode Curl_client_write(struct Curl_easy *data, int type, const char *buf, + size_t len) WARN_UNUSED_RESULT; + +CURLcode Curl_client_flush(struct Curl_easy *data); + +/** + * Free all resources related to client writing. + */ +void Curl_client_cleanup(struct Curl_easy *data); + +/** + * Reset readers and writer chains, keep rewind information + * when necessary. + */ +void Curl_client_reset(struct Curl_easy *data); + +/** + * A new request is starting, perform any ops like rewinding + * previous readers when needed. + */ +CURLcode Curl_client_start(struct Curl_easy *data); + +/** + * Client Writers - a chain passing transfer BODY data to the client. + * Main application: HTTP and related protocols + * Other uses: monitoring of download progress + * + * Writers in the chain are order by their `phase`. First come all + * writers in CURL_CW_RAW, followed by any in CURL_CW_TRANSFER_DECODE, + * followed by any in CURL_CW_PROTOCOL, etc. + * + * When adding a writer, it is inserted as first in its phase. This means + * the order of adding writers of the same phase matters, but writers for + * different phases may be added in any order. + * + * Writers which do modify the BODY data written are expected to be of + * phases TRANSFER_DECODE or CONTENT_DECODE. The other phases are intended + * for monitoring writers. Which do *not* modify the data but gather + * statistics or update progress reporting. + */ + +/* Phase a writer operates at. */ +typedef enum { + CURL_CW_RAW, /* raw data written, before any decoding */ + CURL_CW_TRANSFER_DECODE, /* remove transfer-encodings */ + CURL_CW_PROTOCOL, /* after transfer, but before content decoding */ + CURL_CW_BEFORE_DECODE, /* after protocol, but before content decoding */ + CURL_CW_CONTENT_DECODE, /* remove content-encodings */ + CURL_CW_CLIENT /* data written to client */ +} Curl_cwriter_phase; + +/* writer may blow up size of write data, e.g. zip bombs */ +#define CURL_CW_FLAG_BLOWUP (1U << 0) + +/* Client Writer Type, provides the implementation */ +struct Curl_cwtype { + const char *name; /* writer name. */ + const char *alias; /* writer name alias, maybe NULL. */ + uint8_t flags; /* flags for writer behaviour */ + CURLcode (*do_init)(struct Curl_easy *data, + struct Curl_cwriter *writer); + CURLcode (*do_write)(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes); + CURLcode (*do_flush)(struct Curl_easy *data, + struct Curl_cwriter *writer); + void (*do_close)(struct Curl_easy *data, + struct Curl_cwriter *writer); + size_t cwriter_size; /* sizeof() allocated struct Curl_cwriter */ +}; + +/* Client writer instance, allocated on creation. + * `void *ctx` is the pointer from the allocation of + * the `struct Curl_cwriter` itself. This is suitable for "downcasting" + * by the writers implementation. See https://github.com/curl/curl/pull/13054 + * for the alignment problems that arise otherwise. + */ +struct Curl_cwriter { + const struct Curl_cwtype *cwt; /* type implementation */ + struct Curl_cwriter *next; /* Downstream writer. */ + void *ctx; /* allocated instance pointer */ + Curl_cwriter_phase phase; /* phase at which it operates */ +}; + +/** + * Create a new cwriter instance with given type and phase. Is not + * inserted into the writer chain by this call. + * Invokes `writer->do_init()`. + */ +CURLcode Curl_cwriter_create(struct Curl_cwriter **pwriter, + struct Curl_easy *data, + const struct Curl_cwtype *cwt, + Curl_cwriter_phase phase); + +/** + * Free a cwriter instance. + * Invokes `writer->do_close()`. + */ +void Curl_cwriter_free(struct Curl_easy *data, + struct Curl_cwriter *writer); + +/** + * Count the number of writers installed of the given phase. + */ +size_t Curl_cwriter_count(struct Curl_easy *data, Curl_cwriter_phase phase); + +/** + * Adds a writer to the transfer's writer chain. + * The writers `phase` determines where in the chain it is inserted. + */ +CURLcode Curl_cwriter_add(struct Curl_easy *data, + struct Curl_cwriter *writer); + +/** + * Look up an installed client writer on `data` by its type. + * @return first writer with that type or NULL + */ +struct Curl_cwriter *Curl_cwriter_get_by_type(struct Curl_easy *data, + const struct Curl_cwtype *cwt); + +struct Curl_cwriter *Curl_cwriter_get_by_name(struct Curl_easy *data, + const char *name); + +/* Convenience method for calling `writer->do_write()` that + * checks for NULL writer. */ +#define Curl_cwriter_write(d, w, t, b, n) \ + ((w) ? (w)->cwt->do_write((d), (w), (t), (b), (n)) : CURLE_WRITE_ERROR) + +#define Curl_cwriter_flush(d, w) \ + ((w) ? (w)->cwt->do_flush((d), (w)) : CURLE_WRITE_ERROR) + +/* TRUE if client writer is paused. */ +#define Curl_cwriter_is_paused(d) ((bool)(d)->req.writer.paused) + +/** + * Unpause client writer and flush any buffered date to the client. + */ +CURLcode Curl_cwriter_unpause(struct Curl_easy *data); + +/** + * Default implementations for do_init, do_write, do_close that + * do nothing and pass the data through. + */ +CURLcode Curl_cwriter_def_init(struct Curl_easy *data, + struct Curl_cwriter *writer); +CURLcode Curl_cwriter_def_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes); +CURLcode Curl_cwriter_def_flush(struct Curl_easy *data, + struct Curl_cwriter *writer); +void Curl_cwriter_def_close(struct Curl_easy *data, + struct Curl_cwriter *writer); + +typedef enum { + CURL_CRCNTRL_REWIND, + CURL_CRCNTRL_UNPAUSE, + CURL_CRCNTRL_CLEAR_EOS +} Curl_creader_cntrl; + +/* Client Reader Type, provides the implementation */ +struct Curl_crtype { + const char *name; /* writer name. */ + CURLcode (*do_init)(struct Curl_easy *data, struct Curl_creader *reader); + CURLcode (*do_read)(struct Curl_easy *data, struct Curl_creader *reader, + char *buf, size_t blen, size_t *nread, bool *eos); + void (*do_close)(struct Curl_easy *data, struct Curl_creader *reader); + bool (*needs_rewind)(struct Curl_easy *data, struct Curl_creader *reader); + curl_off_t (*total_length)(struct Curl_easy *data, + struct Curl_creader *reader); + CURLcode (*resume_from)(struct Curl_easy *data, + struct Curl_creader *reader, curl_off_t offset); + CURLcode (*cntrl)(struct Curl_easy *data, struct Curl_creader *reader, + Curl_creader_cntrl opcode); + bool (*is_paused)(struct Curl_easy *data, struct Curl_creader *reader); + void (*done)(struct Curl_easy *data, + struct Curl_creader *reader, int premature); + size_t creader_size; /* sizeof() allocated struct Curl_creader */ +}; + +/* Phase a reader operates at. */ +typedef enum { + CURL_CR_NET, /* data send to the network (connection filters) */ + CURL_CR_TRANSFER_ENCODE, /* add transfer-encodings */ + CURL_CR_PROTOCOL, /* before transfer, but after content decoding */ + CURL_CR_CONTENT_ENCODE, /* add content-encodings */ + CURL_CR_CLIENT /* data read from client */ +} Curl_creader_phase; + +/* Client reader instance, allocated on creation. + * `void *ctx` is the pointer from the allocation of + * the `struct Curl_cwriter` itself. This is suitable for "downcasting" + * by the writers implementation. See https://github.com/curl/curl/pull/13054 + * for the alignment problems that arise otherwise. + */ +struct Curl_creader { + const struct Curl_crtype *crt; /* type implementation */ + struct Curl_creader *next; /* Downstream reader. */ + void *ctx; + Curl_creader_phase phase; /* phase at which it operates */ +}; + +/** + * Default implementations for do_init, do_write, do_close that + * do nothing and pass the data through. + */ +CURLcode Curl_creader_def_init(struct Curl_easy *data, + struct Curl_creader *reader); +void Curl_creader_def_close(struct Curl_easy *data, + struct Curl_creader *reader); +CURLcode Curl_creader_def_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *nread, bool *eos); +bool Curl_creader_def_needs_rewind(struct Curl_easy *data, + struct Curl_creader *reader); +curl_off_t Curl_creader_def_total_length(struct Curl_easy *data, + struct Curl_creader *reader); +CURLcode Curl_creader_def_resume_from(struct Curl_easy *data, + struct Curl_creader *reader, + curl_off_t offset); +CURLcode Curl_creader_def_cntrl(struct Curl_easy *data, + struct Curl_creader *reader, + Curl_creader_cntrl opcode); +bool Curl_creader_def_is_paused(struct Curl_easy *data, + struct Curl_creader *reader); +void Curl_creader_def_done(struct Curl_easy *data, + struct Curl_creader *reader, int premature); + +/** + * Convenience method for calling `reader->do_read()` that + * checks for NULL reader. + */ +CURLcode Curl_creader_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, size_t *nread, bool *eos); + +/* Tell the reader and all below that any EOS state is to be cleared */ +void Curl_creader_clear_eos(struct Curl_easy *data, + struct Curl_creader *reader); + +/** + * Create a new creader instance with given type and phase. Is not + * inserted into the writer chain by this call. + * Invokes `reader->do_init()`. + */ +CURLcode Curl_creader_create(struct Curl_creader **preader, + struct Curl_easy *data, + const struct Curl_crtype *crt, + Curl_creader_phase phase); + +/** + * Free a creader instance. + * Invokes `reader->do_close()`. + */ +void Curl_creader_free(struct Curl_easy *data, struct Curl_creader *reader); + +/** + * Adds a reader to the transfer's reader chain. + * The readers `phase` determines where in the chain it is inserted. + */ +CURLcode Curl_creader_add(struct Curl_easy *data, + struct Curl_creader *reader); + +/** + * Set the given reader, which needs to be of type CURL_CR_CLIENT, + * as the new first reader. Discard any installed readers and init + * the reader chain anew. + * The function takes ownership of `r`. + */ +CURLcode Curl_creader_set(struct Curl_easy *data, struct Curl_creader *r); + +/** + * Read at most `blen` bytes at `buf` from the client. + * @param data the transfer to read client bytes for + * @param buf the memory location to read to + * @param blen the amount of memory at `buf` + * @param nread on return the number of bytes read into `buf` + * @param eos TRUE iff bytes are the end of data from client + * @return CURLE_OK on successful read (even 0 length) or error + */ +CURLcode Curl_client_read(struct Curl_easy *data, char *buf, size_t blen, + size_t *nread, bool *eos) WARN_UNUSED_RESULT; + +/** + * TRUE iff client reader needs rewing before it can be used for + * a retry request. + */ +bool Curl_creader_needs_rewind(struct Curl_easy *data); + +/** + * TRUE iff client reader will rewind at next start + */ +bool Curl_creader_will_rewind(struct Curl_easy *data); + +/** + * En-/disable rewind of client reader at next start. + */ +void Curl_creader_set_rewind(struct Curl_easy *data, bool enable); + +/** + * Get the total length of bytes provided by the installed readers. + * This is independent of the amount already delivered and is calculated + * by all readers in the stack. If a reader like "chunked" or + * "crlf conversion" is installed, the returned length will be -1. + * @return -1 if length is indeterminate + */ +curl_off_t Curl_creader_total_length(struct Curl_easy *data); + +/** + * Get the total length of bytes provided by the reader at phase + * CURL_CR_CLIENT. This may not match the amount of bytes read + * for a request, depending if other, encoding readers are also installed. + * However it allows for rough estimation of the overall length. + * @return -1 if length is indeterminate + */ +curl_off_t Curl_creader_client_length(struct Curl_easy *data); + +/** + * Ask the installed reader at phase CURL_CR_CLIENT to start + * reading from the given offset. On success, this will reduce + * the `total_length()` by the amount. + * @param data the transfer to read client bytes for + * @param offset the offset where to start reads from, negative + * values will be ignored. + * @return CURLE_OK if offset could be set + * CURLE_READ_ERROR if not supported by reader or seek/read failed + * of offset larger than total length + * CURLE_PARTIAL_FILE if offset led to 0 total length + */ +CURLcode Curl_creader_resume_from(struct Curl_easy *data, curl_off_t offset); + +/** + * Unpause all installed readers. + */ +CURLcode Curl_creader_unpause(struct Curl_easy *data); + +/** + * Return TRUE iff any of the installed readers is paused. + */ +bool Curl_creader_is_paused(struct Curl_easy *data); + +/** + * Tell all client readers that they are done. + */ +void Curl_creader_done(struct Curl_easy *data, int premature); + +/** + * Look up an installed client reader on `data` by its type. + * @return first reader with that type or NULL + */ +struct Curl_creader *Curl_creader_get_by_type(struct Curl_easy *data, + const struct Curl_crtype *crt); + +/** + * Set the client reader to provide 0 bytes, immediate EOS. + */ +CURLcode Curl_creader_set_null(struct Curl_easy *data); + +/** + * Set the client reader the reads from fread callback. + */ +CURLcode Curl_creader_set_fread(struct Curl_easy *data, curl_off_t len); + +/** + * Set the client reader the reads from the supplied buf (NOT COPIED). + */ +CURLcode Curl_creader_set_buf(struct Curl_easy *data, + const char *buf, size_t blen); + +#endif /* HEADER_CURL_SENDF_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/setopt.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/setopt.c new file mode 100644 index 0000000000..0e15980b8f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/setopt.c @@ -0,0 +1,2955 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif + +#ifdef HAVE_LINUX_TCP_H +#include <linux/tcp.h> +#elif defined(HAVE_NETINET_TCP_H) +#include <netinet/tcp.h> +#endif + +#include "urldata.h" +#include "url.h" +#include "progress.h" +#include "content_encoding.h" +#include "strcase.h" +#include "curl_share.h" +#include "vtls/vtls.h" +#include "curl_trc.h" +#include "setopt.h" +#include "altsvc.h" +#include "hsts.h" +#include "tftp.h" +#include "curlx/strdup.h" +#include "escape.h" +#include "bufref.h" +#include "vauth/vauth.h" + +static CURLcode setopt_set_timeout_sec(timediff_t *ptimeout_ms, long secs) +{ + if(secs < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; +#if LONG_MAX > (TIMEDIFF_T_MAX / 1000) + if(secs > (TIMEDIFF_T_MAX / 1000)) { + *ptimeout_ms = TIMEDIFF_T_MAX; + return CURLE_OK; + } +#endif + *ptimeout_ms = (timediff_t)secs * 1000; + return CURLE_OK; +} + +static CURLcode setopt_set_timeout_ms(timediff_t *ptimeout_ms, long ms) +{ + if(ms < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; +#if LONG_MAX > TIMEDIFF_T_MAX + if(ms > TIMEDIFF_T_MAX) { + *ptimeout_ms = TIMEDIFF_T_MAX; + return CURLE_OK; + } +#endif + *ptimeout_ms = (timediff_t)ms; + return CURLE_OK; +} + +CURLcode Curl_setstropt(struct Curl_easy *data, + enum dupstring id, const char *s) +{ + size_t slen = s ? strlen(s) : 0; + DEBUGASSERT((unsigned)id <= UINT8_MAX); + if(s && (slen > CURL_MAX_INPUT_LENGTH)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + return CURL_EASY_STR_SET(data, (uint8_t)id, s, slen); +} + +CURLcode Curl_setblobopt(struct curl_blob **blobp, + const struct curl_blob *blob) +{ + /* free the previous storage at `blobp' and replace by a dynamic storage + copy of blob. If CURL_BLOB_COPY is set, the data is copied. */ + + curlx_safefree(*blobp); + + if(blob) { + struct curl_blob *nblob; + if(!blob->data || !blob->len || (blob->len > CURL_MAX_INPUT_LENGTH)) + return CURLE_BAD_FUNCTION_ARGUMENT; + nblob = (struct curl_blob *) + curlx_malloc(sizeof(struct curl_blob) + + ((blob->flags & CURL_BLOB_COPY) ? blob->len : 0)); + if(!nblob) + return CURLE_OUT_OF_MEMORY; + *nblob = *blob; + if(blob->flags & CURL_BLOB_COPY) { + /* put the data after the blob struct in memory */ + nblob->data = (char *)nblob + sizeof(struct curl_blob); + memcpy(nblob->data, blob->data, blob->len); + } + + *blobp = nblob; + return CURLE_OK; + } + + return CURLE_OK; +} + +static CURLcode setstropt_userpwd(const char *option, char **userp, + char **passwdp) +{ + char *user = NULL; + char *passwd = NULL; + + DEBUGASSERT(userp); + DEBUGASSERT(passwdp); + + /* Parse the login details if specified. If not, then we treat NULL as a + hint to clear the existing data */ + if(option) { + size_t len = strlen(option); + CURLcode result; + if(len > CURL_MAX_INPUT_LENGTH) + return CURLE_BAD_FUNCTION_ARGUMENT; + + result = Curl_parse_login_details(option, len, &user, &passwd, NULL); + if(result) + return result; + } + + curlx_free(*userp); + *userp = user; + + curlx_strzero(*passwdp); + curlx_free(*passwdp); + *passwdp = passwd; + + return CURLE_OK; +} + +static CURLcode setstropt_interface(struct Curl_easy *data, char *option) +{ + char *dev = NULL; + char *iface = NULL; + char *host = NULL; + CURLcode result; + + if(option) { + /* Parse the interface details if set, otherwise clear them all */ + result = Curl_parse_interface(option, &dev, &iface, &host); + if(result) + return result; + } + + result = CURL_EASY_STR_SETN(data, STRING_DEVICE, dev); + dev = NULL; + if(!result) { + result = CURL_EASY_STR_SETN(data, STRING_INTERFACE, iface); + iface = NULL; + } + if(!result) { + result = CURL_EASY_STR_SETN(data, STRING_BINDHOST, host); + host = NULL; + } + curlx_free(dev); + curlx_free(iface); + curlx_free(host); + return result; +} + +#ifdef USE_SSL +#define C_SSLVERSION_VALUE(x) ((x) & 0xffff) +#define C_SSLVERSION_MAX_VALUE(x) ((unsigned long)(x) & 0xffff0000) +#endif + +static CURLcode protocol2num(const char *str, curl_prot_t *val) +{ + /* + * We are asked to cherry-pick protocols, so play it safe and disallow all + * protocols to start with, and re-add the wanted ones back in. + */ + *val = 0; + + if(!str) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(curl_strequal(str, "all")) { + *val = ~(curl_prot_t)0; + return CURLE_OK; + } + + do { + const char *token = str; + size_t tlen; + + str = strchr(str, ','); + tlen = str ? (size_t)(str - token) : strlen(token); + if(tlen) { + const struct Curl_scheme *h = Curl_getn_scheme(token, tlen); + + if(!h || !h->run) + return CURLE_UNSUPPORTED_PROTOCOL; + + *val |= h->protocol; + } + } while(str && str++); + + if(!*val) + /* no protocol listed */ + return CURLE_BAD_FUNCTION_ARGUMENT; + return CURLE_OK; +} + +#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_PROXY) +static CURLcode httpauth(struct Curl_easy *data, bool proxy, + unsigned long auth) +{ + if(auth != CURLAUTH_NONE) { + int bitcheck = 0; + bool authbits = FALSE; + if(auth & CURLAUTH_DIGEST_IE) { + auth |= CURLAUTH_DIGEST; /* set standard digest bit */ + auth &= ~CURLAUTH_DIGEST_IE; /* drop the legacy bit */ + } + + /* switch off bits we cannot support */ +#ifndef USE_NTLM + auth &= ~CURLAUTH_NTLM; /* no NTLM support */ +#endif +#ifndef USE_SPNEGO + auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without GSS-API + or SSPI */ +#endif + + /* check if any auth bit lower than CURLAUTH_ONLY is still set */ + while(bitcheck < 31) { + if(auth & (1UL << bitcheck++)) { + authbits = TRUE; + break; + } + } + if(!authbits) + return CURLE_NOT_BUILT_IN; /* no supported types left! */ + } + if(proxy) + data->set.proxyauth = (uint32_t)auth; + else + data->set.httpauth = (uint32_t)auth; + return CURLE_OK; +} +#endif /* !CURL_DISABLE_HTTP || !CURL_DISABLE_PROXY */ + +#ifndef CURL_DISABLE_HTTP +static CURLcode setopt_HTTP_VERSION(struct Curl_easy *data, long arg) +{ + /* + * This sets a requested HTTP version to be used. The value is one of + * the listed enums in curl/curl.h. + */ + switch(arg) { + case CURL_HTTP_VERSION_NONE: + /* accepted */ + break; + case CURL_HTTP_VERSION_1_0: + case CURL_HTTP_VERSION_1_1: + /* accepted */ + break; +#ifdef USE_HTTP2 + case CURL_HTTP_VERSION_2_0: + case CURL_HTTP_VERSION_2TLS: + case CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE: + /* accepted */ + break; +#endif +#ifdef USE_HTTP3 + case CURL_HTTP_VERSION_3: + case CURL_HTTP_VERSION_3ONLY: + /* accepted */ + break; +#endif + default: + /* not accepted */ + if(arg < CURL_HTTP_VERSION_NONE) + return CURLE_BAD_FUNCTION_ARGUMENT; + return CURLE_UNSUPPORTED_PROTOCOL; + } + data->set.httpwant = (unsigned char)arg; + return CURLE_OK; +} +#endif /* !CURL_DISABLE_HTTP */ + +#ifdef USE_SSL +CURLcode Curl_setopt_SSLVERSION(struct Curl_easy *data, CURLoption option, + long arg) +{ + /* + * Set explicit SSL version to try to connect with, as some SSL + * implementations are lame. + */ + { + long version, version_max; + struct ssl_primary_config *primary = &data->set.ssl.primary; +#ifndef CURL_DISABLE_PROXY + if(option != CURLOPT_SSLVERSION) + primary = &data->set.proxy_ssl.primary; +#else + (void)option; /* unused */ +#endif + version = C_SSLVERSION_VALUE(arg); + version_max = (long)C_SSLVERSION_MAX_VALUE(arg); + + if(version < CURL_SSLVERSION_DEFAULT || + version == CURL_SSLVERSION_SSLv2 || + version == CURL_SSLVERSION_SSLv3 || + version >= CURL_SSLVERSION_LAST || + version_max < CURL_SSLVERSION_MAX_NONE || + version_max >= CURL_SSLVERSION_MAX_LAST) + return CURLE_BAD_FUNCTION_ARGUMENT; + if(version == CURL_SSLVERSION_DEFAULT) + version = CURL_SSLVERSION_TLSv1_2; + + primary->version = (unsigned char)version; + primary->version_max = (unsigned int)version_max; + } + return CURLE_OK; +} +#endif /* !USE_SSL */ + +#ifndef CURL_DISABLE_RTSP +static CURLcode setopt_RTSP_REQUEST(struct Curl_easy *data, long arg) +{ + /* + * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...) Would this be + * better if the RTSPREQ_* were moved into here? + */ + if((arg <= CURL_RTSPREQ_NONE) || (arg >= CURL_RTSPREQ_LAST)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + data->set.rtspreq = (unsigned char)arg; + return CURLE_OK; +} +#endif /* !CURL_DISABLE_RTSP */ + +static CURLcode setopt_long_bool(struct Curl_easy *data, CURLoption option, + long arg) +{ + bool enabled = !!arg; + int ok = 1; + struct UserDefined *s = &data->set; + switch(option) { + case CURLOPT_FORBID_REUSE: + /* + * When this transfer is done, it must not be left to be reused by a + * subsequent transfer but shall be closed immediately. + */ + s->reuse_forbid = enabled; + break; + case CURLOPT_FRESH_CONNECT: + /* + * This transfer shall not use a previously cached connection but + * should be made with a fresh new connect! + */ + s->reuse_fresh = enabled; + break; + case CURLOPT_VERBOSE: + /* + * Verbose means infof() calls that give a lot of information about + * the connection and transfer procedures as well as internal choices. + */ + s->verbose = enabled; + break; + case CURLOPT_HEADER: + /* + * Set to include the header in the general data output stream. + */ + s->include_header = enabled; + break; + case CURLOPT_NOPROGRESS: + /* + * Shut off the internal supported progress meter + */ + data->progress.hide = enabled; + break; + case CURLOPT_NOBODY: + /* + * Do not include the body part in the output data stream. + */ + s->opt_no_body = enabled; +#ifndef CURL_DISABLE_HTTP + if(s->opt_no_body) + /* in HTTP lingo, no body means using the HEAD request... */ + s->method = HTTPREQ_HEAD; + else if(s->method == HTTPREQ_HEAD) + s->method = HTTPREQ_GET; +#endif + break; + case CURLOPT_FAILONERROR: + /* + * Do not output the >=400 error code HTML-page, but instead only + * return error. + */ + s->http_fail_on_error = enabled; + break; + case CURLOPT_KEEP_SENDING_ON_ERROR: + s->http_keep_sending_on_error = enabled; + break; + case CURLOPT_UPLOAD: + case CURLOPT_PUT: + /* + * We want to send data to the remote host. If this is HTTP, that equals + * using the PUT request. + */ + if(enabled) { + /* If this is HTTP, PUT is what's needed to "upload" */ + s->method = HTTPREQ_PUT; + s->opt_no_body = FALSE; /* this is implied */ + } + else + /* In HTTP, the opposite of upload is GET (unless NOBODY is true as + then this can be changed to HEAD later on) */ + s->method = HTTPREQ_GET; + break; + case CURLOPT_FILETIME: + /* + * Try to get the file time of the remote document. The time will + * later (possibly) become available using curl_easy_getinfo(). + */ + s->get_filetime = enabled; + break; +#ifndef CURL_DISABLE_HTTP + case CURLOPT_HTTP09_ALLOWED: + s->http09_allowed = enabled; + break; +#ifndef CURL_DISABLE_COOKIES + case CURLOPT_COOKIESESSION: + /* + * Set this option to TRUE to start a new "cookie session". It will + * prevent the forthcoming read-cookies-from-file actions to accept + * cookies that are marked as being session cookies, as they belong to a + * previous session. + */ + s->cookiesession = enabled; + break; +#endif + case CURLOPT_AUTOREFERER: + /* + * Switch on automatic referer that gets set if curl follows locations. + */ + s->http_auto_referer = enabled; + break; + case CURLOPT_TRANSFER_ENCODING: + s->http_transfer_encoding = enabled; + break; + case CURLOPT_UNRESTRICTED_AUTH: + /* + * Send authentication (user+password) when following locations, even when + * hostname changed. + */ + s->allow_auth_to_other_hosts = enabled; + break; + case CURLOPT_HTTP_TRANSFER_DECODING: + /* + * disable libcurl transfer encoding is used + */ + s->http_te_skip = !enabled; /* reversed */ + break; + case CURLOPT_HTTP_CONTENT_DECODING: + /* + * raw data passed to the application when content encoding is used + */ + s->http_ce_skip = !enabled; /* reversed */ + break; + case CURLOPT_HTTPGET: + /* + * Set to force us do HTTP GET + */ + if(enabled) { + s->method = HTTPREQ_GET; + s->opt_no_body = FALSE; /* this is implied */ + } + break; + case CURLOPT_POST: + /* Does this option serve a purpose anymore? Yes it does, when + CURLOPT_POSTFIELDS is not used and the POST data is read off the + callback! */ + if(enabled) { + s->method = HTTPREQ_POST; + s->opt_no_body = FALSE; /* this is implied */ + } + else + s->method = HTTPREQ_GET; + break; +#endif /* !CURL_DISABLE_HTTP */ +#ifndef CURL_DISABLE_PROXY + case CURLOPT_HTTPPROXYTUNNEL: + /* + * Tunnel operations through the proxy instead of normal proxy use + */ + s->tunnel_thru_httpproxy = enabled; + break; + case CURLOPT_HAPROXYPROTOCOL: + /* + * Set to send the HAProxy Proxy Protocol header + */ + s->haproxyprotocol = enabled; + break; + case CURLOPT_PROXY_SSL_VERIFYPEER: + /* + * Enable peer SSL verifying for proxy. + */ + s->proxy_ssl.primary.verifypeer = enabled; + + /* Update the current connection proxy_ssl_config. */ + Curl_ssl_conn_config_update(data, TRUE); + break; + case CURLOPT_PROXY_SSL_VERIFYHOST: + /* + * Enable verification of the hostname in the peer certificate for proxy + */ + s->proxy_ssl.primary.verifyhost = enabled; + ok = 2; + /* Update the current connection proxy_ssl_config. */ + Curl_ssl_conn_config_update(data, TRUE); + break; + case CURLOPT_PROXY_TRANSFER_MODE: + /* + * set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy + */ + s->proxy_transfer_mode = enabled; + break; +#endif /* !CURL_DISABLE_PROXY */ +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + case CURLOPT_SOCKS5_GSSAPI_NEC: + /* + * Set flag for NEC SOCKS5 support + */ + s->socks5_gssapi_nec = enabled; + break; +#endif +#ifdef CURL_LIST_ONLY_PROTOCOL + case CURLOPT_DIRLISTONLY: + /* + * An option that changes the command to one that asks for a list only, no + * file info details. Used for FTP, POP3 and SFTP. + */ + s->list_only = enabled; + break; +#endif + case CURLOPT_APPEND: + /* + * We want to upload and append to an existing file. Used for FTP and + * SFTP. + */ + s->remote_append = enabled; + break; +#ifndef CURL_DISABLE_FTP + case CURLOPT_FTP_USE_EPRT: + s->ftp_use_eprt = enabled; + break; + case CURLOPT_FTP_USE_EPSV: + s->ftp_use_epsv = enabled; + break; + case CURLOPT_FTP_USE_PRET: + s->ftp_use_pret = enabled; + break; + case CURLOPT_FTP_SKIP_PASV_IP: + /* + * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the + * bypass of the IP address in PASV responses. + */ + s->ftp_skip_ip = enabled; + break; + case CURLOPT_WILDCARDMATCH: + s->wildcard_enabled = enabled; + break; +#endif + case CURLOPT_CRLF: + /* + * Kludgy option to enable CRLF conversions. Subject for removal. + */ + s->crlf = enabled; + break; +#ifndef CURL_DISABLE_TFTP + case CURLOPT_TFTP_NO_OPTIONS: + /* + * Option that prevents libcurl from sending TFTP option requests to the + * server. + */ + s->tftp_no_options = enabled; + break; +#endif /* !CURL_DISABLE_TFTP */ + case CURLOPT_TRANSFERTEXT: + /* + * This option was previously named 'FTPASCII'. Renamed to work with + * more protocols than merely FTP. + * + * Transfer using ASCII (instead of BINARY). + */ + s->prefer_ascii = enabled; + break; + case CURLOPT_SSL_VERIFYPEER: + /* + * Enable peer SSL verifying. + */ + s->ssl.primary.verifypeer = enabled; + + /* Update the current connection ssl_config. */ + Curl_ssl_conn_config_update(data, FALSE); + break; +#ifndef CURL_DISABLE_DOH + case CURLOPT_DOH_SSL_VERIFYPEER: + /* + * Enable peer SSL verifying for DoH. + */ + s->doh_verifypeer = enabled; + break; + case CURLOPT_DOH_SSL_VERIFYHOST: + /* + * Enable verification of the hostname in the peer certificate for DoH + */ + s->doh_verifyhost = enabled; + ok = 2; + break; + case CURLOPT_DOH_SSL_VERIFYSTATUS: + /* + * Enable certificate status verifying for DoH. + */ + if(!Curl_ssl_cert_status_request()) + return CURLE_NOT_BUILT_IN; + + s->doh_verifystatus = enabled; + ok = 2; + break; +#endif /* !CURL_DISABLE_DOH */ + case CURLOPT_SSL_VERIFYHOST: + /* + * Enable verification of the hostname in the peer certificate + */ + + /* Obviously people are not reading documentation and too many thought + this argument took a boolean when it was not and misused it. + Treat 1 and 2 the same */ + s->ssl.primary.verifyhost = enabled; + ok = 2; + + /* Update the current connection ssl_config. */ + Curl_ssl_conn_config_update(data, FALSE); + break; + case CURLOPT_SSL_VERIFYSTATUS: + /* + * Enable certificate status verifying. + */ + if(!Curl_ssl_cert_status_request()) + return CURLE_NOT_BUILT_IN; + + s->ssl.primary.verifystatus = enabled; + + /* Update the current connection ssl_config. */ + Curl_ssl_conn_config_update(data, FALSE); + break; + case CURLOPT_CERTINFO: +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_CERTINFO)) + s->ssl.certinfo = enabled; + else +#endif + return CURLE_NOT_BUILT_IN; + break; + case CURLOPT_NOSIGNAL: + /* + * The application asks not to set any signal() or alarm() handlers, + * even when using a timeout. + */ + s->no_signal = enabled; + break; + case CURLOPT_TCP_NODELAY: + /* + * Enable or disable TCP_NODELAY, which will disable/enable the Nagle + * algorithm + */ + s->tcp_nodelay = enabled; + break; + case CURLOPT_IGNORE_CONTENT_LENGTH: + s->ignorecl = enabled; + break; + case CURLOPT_SSL_SESSIONID_CACHE: + s->ssl.primary.cache_session = enabled; +#ifndef CURL_DISABLE_PROXY + s->proxy_ssl.primary.cache_session = s->ssl.primary.cache_session; +#endif + break; +#ifdef USE_SSH + case CURLOPT_SSH_COMPRESSION: + s->ssh_compression = enabled; + break; +#endif /* !USE_SSH */ +#ifndef CURL_DISABLE_SMTP + case CURLOPT_MAIL_RCPT_ALLOWFAILS: + /* allow RCPT TO command to fail for some recipients */ + s->mail_rcpt_allowfails = enabled; + break; +#endif /* !CURL_DISABLE_SMTP */ + case CURLOPT_SASL_IR: + /* Enable/disable SASL initial response */ + s->sasl_ir = enabled; + break; + case CURLOPT_TCP_KEEPALIVE: + s->tcp_keepalive = enabled; + break; + case CURLOPT_TCP_FASTOPEN: +#if defined(CONNECT_DATA_IDEMPOTENT) || defined(MSG_FASTOPEN) || \ + defined(TCP_FASTOPEN_CONNECT) + s->tcp_fastopen = enabled; + break; +#else + return CURLE_NOT_BUILT_IN; +#endif + case CURLOPT_SSL_ENABLE_ALPN: + s->ssl_enable_alpn = enabled; + break; + case CURLOPT_PATH_AS_IS: + s->path_as_is = enabled; + break; + case CURLOPT_PIPEWAIT: + s->pipewait = enabled; + break; + case CURLOPT_SUPPRESS_CONNECT_HEADERS: + s->suppress_connect_headers = enabled; + break; +#ifndef CURL_DISABLE_SHUFFLE_DNS + case CURLOPT_DNS_SHUFFLE_ADDRESSES: + s->dns_shuffle_addresses = enabled; + break; +#endif + case CURLOPT_DISALLOW_USERNAME_IN_URL: + s->disallow_username_in_url = enabled; + break; + case CURLOPT_QUICK_EXIT: + s->quick_exit = enabled; + break; + default: + return CURLE_UNKNOWN_OPTION; + } + if((arg > ok) || (arg < 0)) + /* reserve other values for future use */ + infof(data, "boolean setopt(%d) got unsupported argument %ld," + " treated as %d", (int)option, arg, enabled); + + return CURLE_OK; +} + +static CURLcode value_range(long *value, long below_error, long min, long max) +{ + if(*value < below_error) + return CURLE_BAD_FUNCTION_ARGUMENT; + else if(*value < min) + *value = min; + else if(*value > max) + *value = max; + return CURLE_OK; +} + +static CURLcode setopt_long_net(struct Curl_easy *data, CURLoption option, + long arg) +{ + CURLcode result = CURLE_OK; + struct UserDefined *s = &data->set; + + switch(option) { + case CURLOPT_DNS_CACHE_TIMEOUT: + if(arg != -1) + return setopt_set_timeout_sec(&s->dns_cache_timeout_ms, arg); + s->dns_cache_timeout_ms = -1; + break; + case CURLOPT_MAXCONNECTS: + result = value_range(&arg, 0, 0, INT_MAX); + if(!result) + s->maxconnects = arg ? (uint32_t)arg : DEFAULT_CONNCACHE_SIZE; + break; + case CURLOPT_SERVER_RESPONSE_TIMEOUT: + return setopt_set_timeout_sec(&s->server_response_timeout, arg); + case CURLOPT_SERVER_RESPONSE_TIMEOUT_MS: + return setopt_set_timeout_ms(&s->server_response_timeout, arg); + case CURLOPT_LOW_SPEED_LIMIT: + if(arg < 0) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else + s->low_speed_limit = arg; + break; + case CURLOPT_LOW_SPEED_TIME: + result = value_range(&arg, 0, 0, USHRT_MAX); + if(!result) + s->low_speed_time = (uint16_t)arg; + break; + case CURLOPT_PORT: + if((arg < 0) || (arg > 65535)) + return CURLE_BAD_FUNCTION_ARGUMENT; + s->use_port = (unsigned short)arg; + break; + case CURLOPT_TIMEOUT: + return setopt_set_timeout_sec(&s->timeout, arg); + case CURLOPT_TIMEOUT_MS: + return setopt_set_timeout_ms(&s->timeout, arg); + case CURLOPT_CONNECTTIMEOUT: + return setopt_set_timeout_sec(&s->connecttimeout, arg); + case CURLOPT_CONNECTTIMEOUT_MS: + return setopt_set_timeout_ms(&s->connecttimeout, arg); +#ifndef CURL_DISABLE_BINDLOCAL + case CURLOPT_LOCALPORT: + if((arg < 0) || (arg > 65535)) + return CURLE_BAD_FUNCTION_ARGUMENT; + s->localport = curlx_sltous(arg); + break; + case CURLOPT_LOCALPORTRANGE: + if((arg < 0) || (arg > 65535)) + return CURLE_BAD_FUNCTION_ARGUMENT; + s->localportrange = curlx_sltous(arg); + break; +#endif + case CURLOPT_BUFFERSIZE: + result = value_range(&arg, 0, READBUFFER_MIN, READBUFFER_MAX); + if(!result) + s->buffer_size = (unsigned int)arg; + break; + case CURLOPT_UPLOAD_BUFFERSIZE: + result = value_range(&arg, 0, UPLOADBUFFER_MIN, UPLOADBUFFER_MAX); + if(!result) + s->upload_buffer_size = (unsigned int)arg; + break; + case CURLOPT_MAXFILESIZE: + if(arg < 0) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else + s->max_filesize = arg; + break; + case CURLOPT_IPRESOLVE: + if((arg < CURL_IPRESOLVE_WHATEVER) || (arg > CURL_IPRESOLVE_V6)) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else + s->ipver = (unsigned char)arg; + break; + case CURLOPT_CONNECT_ONLY: + if(arg < 0 || arg > 2) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else { + s->connect_only = !!arg; + s->connect_only_ws = (arg == 2); + } + break; +#ifdef USE_IPV6 + case CURLOPT_ADDRESS_SCOPE: +#if SIZEOF_LONG > 4 + if((unsigned long)arg > UINT_MAX) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else +#endif + s->scope_id = (unsigned int)arg; + break; +#endif + case CURLOPT_TCP_KEEPIDLE: + result = value_range(&arg, 0, 0, INT_MAX); + if(!result) + s->tcp_keepidle = (int)arg; + break; + case CURLOPT_TCP_KEEPINTVL: + result = value_range(&arg, 0, 0, INT_MAX); + if(!result) + s->tcp_keepintvl = (int)arg; + break; + case CURLOPT_TCP_KEEPCNT: + result = value_range(&arg, 0, 0, INT_MAX); + if(!result) + s->tcp_keepcnt = (int)arg; + break; + case CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS: + return setopt_set_timeout_ms(&s->happy_eyeballs_timeout, arg); + case CURLOPT_UPKEEP_INTERVAL_MS: + return setopt_set_timeout_ms(&s->upkeep_interval_ms, arg); + case CURLOPT_MAXAGE_CONN: + return setopt_set_timeout_sec(&s->conn_max_idle_ms, arg); + case CURLOPT_MAXLIFETIME_CONN: + return setopt_set_timeout_sec(&s->conn_max_age_ms, arg); + case CURLOPT_DNS_USE_GLOBAL_CACHE: + /* deprecated */ + break; + default: + return CURLE_UNKNOWN_OPTION; + } + return result; +} + +static CURLcode setopt_long_ssl(struct Curl_easy *data, CURLoption option, + long arg) +{ +#ifdef USE_SSL + CURLcode result = CURLE_OK; + struct UserDefined *s = &data->set; + switch(option) { + case CURLOPT_CA_CACHE_TIMEOUT: + if(Curl_ssl_supports(data, SSLSUPP_CA_CACHE)) { + result = value_range(&arg, -1, -1, INT_MAX); + if(!result) + s->general_ssl.ca_cache_timeout = (int)arg; + } + else + result = CURLE_NOT_BUILT_IN; + break; + case CURLOPT_SSLVERSION: +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_SSLVERSION: +#endif + return Curl_setopt_SSLVERSION(data, option, arg); + case CURLOPT_SSL_FALSESTART: + result = CURLE_NOT_BUILT_IN; + break; + case CURLOPT_USE_SSL: + if((arg < CURLUSESSL_NONE) || (arg >= CURLUSESSL_LAST)) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else + s->use_ssl = (unsigned char)arg; + break; + case CURLOPT_SSL_OPTIONS: + s->ssl.primary.ssl_options = (unsigned char)(arg & 0xff); + break; +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_SSL_OPTIONS: + s->proxy_ssl.primary.ssl_options = (unsigned char)(arg & 0xff); + break; +#endif + case CURLOPT_SSL_ENABLE_NPN: + break; + case CURLOPT_SSLENGINE_DEFAULT: + CURL_EASY_STR_CLEAR(data, STRING_SSL_ENGINE); + result = Curl_ssl_set_engine_default(data); + break; + default: + return CURLE_UNKNOWN_OPTION; + } + return result; +#else /* USE_SSL */ + (void)data; + (void)option; + (void)arg; + return CURLE_UNKNOWN_OPTION; +#endif /* !USE_SSL */ +} + +#ifndef CURL_DISABLE_PROXY +static void changeproxy(struct Curl_easy *data) +{ + Curl_auth_digest_cleanup(&data->state.proxydigest); + memset(&data->state.authproxy, 0, sizeof(data->state.authproxy)); +} + +static CURLcode setopt_long_proxy(struct Curl_easy *data, CURLoption option, + long arg) +{ + struct UserDefined *s = &data->set; + + switch(option) { + case CURLOPT_PROXYPORT: + if((arg < 0) || (arg > UINT16_MAX)) + return CURLE_BAD_FUNCTION_ARGUMENT; + if(arg != s->proxyport) + changeproxy(data); + s->proxyport = (uint16_t)arg; + break; + case CURLOPT_PROXYAUTH: + return httpauth(data, TRUE, (unsigned long)arg); + case CURLOPT_PROXYTYPE: + if((arg < CURLPROXY_HTTP) || (arg > CURLPROXY_HTTPS3)) + return CURLE_BAD_FUNCTION_ARGUMENT; +#ifndef USE_PROXY_HTTP3 + if(arg == CURLPROXY_HTTPS3) + return CURLE_NOT_BUILT_IN; +#endif + s->proxytype = (unsigned char)arg; + break; + case CURLOPT_SOCKS5_AUTH: + if(arg & ~(CURLAUTH_BASIC | CURLAUTH_GSSAPI)) + return CURLE_NOT_BUILT_IN; + s->socks5auth = (unsigned char)arg; + break; + default: + return CURLE_UNKNOWN_OPTION; + } + return CURLE_OK; +} +#else +static CURLcode setopt_long_proxy(struct Curl_easy *data, CURLoption option, + long arg) +{ + (void)data; + (void)option; + (void)arg; + return CURLE_UNKNOWN_OPTION; +} +#endif + +static CURLcode setopt_long_http(struct Curl_easy *data, CURLoption option, + long arg) +{ +#ifndef CURL_DISABLE_HTTP + CURLcode result = CURLE_OK; + struct UserDefined *s = &data->set; + + switch(option) { + case CURLOPT_FOLLOWLOCATION: + if((unsigned long)arg > 3) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else + s->http_follow_mode = (unsigned char)arg; + break; + case CURLOPT_MAXREDIRS: + result = value_range(&arg, -1, -1, 0x7fff); + if(!result) + s->maxredirs = (short)arg; + break; + case CURLOPT_POSTREDIR: + if(arg < CURL_REDIR_GET_ALL) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else { + s->post301 = !!(arg & CURL_REDIR_POST_301); + s->post302 = !!(arg & CURL_REDIR_POST_302); + s->post303 = !!(arg & CURL_REDIR_POST_303); + } + break; + case CURLOPT_HEADEROPT: + s->sep_headers = !!(arg & CURLHEADER_SEPARATE); + break; + case CURLOPT_HTTPAUTH: + return httpauth(data, FALSE, (unsigned long)arg); + case CURLOPT_HTTP_VERSION: + return setopt_HTTP_VERSION(data, arg); + case CURLOPT_EXPECT_100_TIMEOUT_MS: + result = value_range(&arg, 0, 0, 0xffff); + if(!result) + s->expect_100_timeout = (unsigned short)arg; + break; + case CURLOPT_STREAM_WEIGHT: +#if defined(USE_HTTP2) || defined(USE_HTTP3) + if((arg >= 1) && (arg <= 256)) + s->weight = (int)arg; + break; +#else + result = CURLE_NOT_BUILT_IN; + break; +#endif +#ifndef CURL_DISABLE_HTTPSIG + case CURLOPT_HTTPSIG_ALGORITHM: + if(arg != CURLHTTPSIG_NONE && + arg != CURLHTTPSIG_ED25519 && + arg != CURLHTTPSIG_HMAC_SHA256) + return CURLE_BAD_FUNCTION_ARGUMENT; + s->httpsig_algorithm = (uint8_t)arg; + if(arg) + s->httpauth = (uint32_t)CURLAUTH_HTTPSIG; + else + s->httpauth &= ~(uint32_t)CURLAUTH_HTTPSIG; + break; +#endif + default: + return CURLE_UNKNOWN_OPTION; + } + return result; +#else + (void)data; + (void)option; + (void)arg; + return CURLE_UNKNOWN_OPTION; +#endif +} + +static CURLcode setopt_long_proto(struct Curl_easy *data, CURLoption option, + long arg) +{ + CURLcode result = CURLE_OK; + struct UserDefined *s = &data->set; + + switch(option) { +#ifndef CURL_DISABLE_TFTP + case CURLOPT_TFTP_BLKSIZE: + result = value_range(&arg, 0, TFTP_BLKSIZE_MIN, TFTP_BLKSIZE_MAX); + if(!result) + s->tftp_blksize = (unsigned short)arg; + break; +#endif +#ifndef CURL_DISABLE_NETRC + case CURLOPT_NETRC: + if((arg < CURL_NETRC_IGNORED) || (arg >= CURL_NETRC_LAST)) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else + s->use_netrc = (unsigned char)arg; + break; +#endif +#ifndef CURL_DISABLE_FTP + case CURLOPT_FTP_FILEMETHOD: + if((arg < CURLFTPMETHOD_DEFAULT) || (arg >= CURLFTPMETHOD_LAST)) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else + s->ftp_filemethod = (unsigned char)arg; + break; + case CURLOPT_FTP_SSL_CCC: + if((arg < CURLFTPSSL_CCC_NONE) || (arg >= CURLFTPSSL_CCC_LAST)) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else + s->ftp_ccc = (unsigned char)arg; + break; + case CURLOPT_FTPSSLAUTH: + if((arg < CURLFTPAUTH_DEFAULT) || (arg >= CURLFTPAUTH_LAST)) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else + s->ftpsslauth = (unsigned char)arg; + break; + case CURLOPT_ACCEPTTIMEOUT_MS: + return setopt_set_timeout_ms(&s->accepttimeout, arg); +#endif +#if !defined(CURL_DISABLE_FTP) || defined(USE_SSH) + case CURLOPT_FTP_CREATE_MISSING_DIRS: + if((arg < CURLFTP_CREATE_DIR_NONE) || (arg > CURLFTP_CREATE_DIR_RETRY)) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else + s->ftp_create_missing_dirs = (unsigned char)arg; + break; + case CURLOPT_NEW_FILE_PERMS: + if((arg < 0) || (arg > 0777)) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else + s->new_file_perms = (unsigned int)arg; + break; +#endif +#ifndef CURL_DISABLE_RTSP + case CURLOPT_RTSP_REQUEST: + return setopt_RTSP_REQUEST(data, arg); + case CURLOPT_RTSP_CLIENT_CSEQ: + result = value_range(&arg, 0, 0, INT_MAX); + if(!result) + data->state.rtsp_next_client_CSeq = (uint32_t)arg; + break; + case CURLOPT_RTSP_SERVER_CSEQ: + result = value_range(&arg, 0, 0, INT_MAX); + if(!result) + data->state.rtsp_next_server_CSeq = (uint32_t)arg; + break; +#endif +#ifdef USE_SSH + case CURLOPT_SSH_AUTH_TYPES: + s->ssh_auth_types = (uint32_t)arg; + break; + case CURLOPT_NEW_DIRECTORY_PERMS: + if((arg < 0) || (arg > 0777)) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else + s->new_directory_perms = (unsigned int)arg; + break; +#endif + case CURLOPT_PROTOCOLS: + s->allowed_protocols = (curl_prot_t)arg; + break; + case CURLOPT_REDIR_PROTOCOLS: + s->redir_protocols = (curl_prot_t)arg; + break; +#ifndef CURL_DISABLE_WEBSOCKETS + case CURLOPT_WS_OPTIONS: + s->ws_raw_mode = (bool)(arg & CURLWS_RAW_MODE); + s->ws_no_auto_pong = (bool)(arg & CURLWS_NOAUTOPONG); + break; +#endif + default: + return CURLE_UNKNOWN_OPTION; + } + return result; +} + +static CURLcode setopt_long_misc(struct Curl_easy *data, CURLoption option, + long arg) +{ + struct UserDefined *s = &data->set; + + switch(option) { + case CURLOPT_TIMECONDITION: + if((arg < CURL_TIMECOND_NONE) || (arg >= CURL_TIMECOND_LAST)) + return CURLE_BAD_FUNCTION_ARGUMENT; + s->timecondition = (unsigned char)arg; + break; + case CURLOPT_TIMEVALUE: + s->timevalue = (time_t)arg; + break; + case CURLOPT_POSTFIELDSIZE: + if(arg < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + if(s->postfieldsize < arg && s->str_copypostfields) { + curlx_safefree(s->str_copypostfields); + s->postfields = NULL; + } + s->postfieldsize = arg; + break; + case CURLOPT_INFILESIZE: + if(arg < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + s->filesize = arg; + break; + case CURLOPT_RESUME_FROM: + if(arg < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + s->set_resume_from = arg; + break; + case CURLOPT_UPLOAD_FLAGS: + s->upload_flags = (unsigned char)arg; + break; +#ifndef CURL_DISABLE_MIME + case CURLOPT_MIME_OPTIONS: + s->mime_formescape = !!(arg & CURLMIMEOPT_FORMESCAPE); + break; +#endif +#ifndef CURL_DISABLE_HSTS + case CURLOPT_HSTS_CTRL: + if(arg & CURLHSTS_ENABLE) { + if(!data->hsts) { + data->hsts = Curl_hsts_init(); + if(!data->hsts) + return CURLE_OUT_OF_MEMORY; + } + } + else if(!data->share || !data->share->hsts) { + /* throw away the HSTS cache unless shared */ + Curl_hsts_cleanup(&data->hsts); + /* flush all the entries */ + curl_slist_free_all(data->state.hstslist); + data->state.hstslist = NULL; + } + else + /* detach from shared HSTS cache without freeing it */ + data->hsts = NULL; + break; +#endif +#ifndef CURL_DISABLE_ALTSVC + case CURLOPT_ALTSVC_CTRL: + return Curl_altsvc_ctrl(data, arg); +#endif +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + case CURLOPT_GSSAPI_DELEGATION: + s->gssapi_delegation = (unsigned char)arg & + (CURLGSSAPI_DELEGATION_POLICY_FLAG | CURLGSSAPI_DELEGATION_FLAG); + break; +#endif + default: + return CURLE_UNKNOWN_OPTION; + } + return CURLE_OK; +} + +static CURLcode setopt_long(struct Curl_easy *data, CURLoption option, + long arg) +{ + typedef CURLcode (*setoptfunc)(struct Curl_easy *data, + CURLoption option, long arg); + static const setoptfunc setopt_call[] = { + setopt_long_bool, + setopt_long_net, + setopt_long_http, + setopt_long_proxy, + setopt_long_ssl, + setopt_long_proto, + setopt_long_misc + }; + size_t i; + + for(i = 0; i < CURL_ARRAYSIZE(setopt_call); i++) { + CURLcode result = setopt_call[i](data, option, arg); + if(result != CURLE_UNKNOWN_OPTION) + return result; + } + return CURLE_UNKNOWN_OPTION; +} + +static CURLcode setopt_slist(struct Curl_easy *data, CURLoption option, + struct curl_slist *slist) +{ + CURLcode result = CURLE_OK; + struct UserDefined *s = &data->set; + switch(option) { +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXYHEADER: + /* + * Set a list with proxy headers to use (or replace internals with) + * + * Since CURLOPT_HTTPHEADER was the only way to set HTTP headers for a + * long time we remain doing it this way until CURLOPT_PROXYHEADER is + * used. As soon as this option has been used, if set to anything but + * NULL, custom headers for proxies are only picked from this list. + * + * Set this option to NULL to restore the previous behavior. + */ + s->proxyheaders = slist; + break; +#endif +#ifndef CURL_DISABLE_HTTP + case CURLOPT_HTTP200ALIASES: + /* + * Set a list of aliases for HTTP 200 in response header + */ + s->http200aliases = slist; + break; +#endif +#if !defined(CURL_DISABLE_FTP) || defined(USE_SSH) + case CURLOPT_POSTQUOTE: + /* + * List of RAW FTP commands to use after a transfer + */ + s->postquote = slist; + break; + case CURLOPT_PREQUOTE: + /* + * List of RAW FTP commands to use prior to RETR (Wesley Laxton) + */ + s->prequote = slist; + break; + case CURLOPT_QUOTE: + /* + * List of RAW FTP commands to use before a transfer + */ + s->quote = slist; + break; +#endif + case CURLOPT_RESOLVE: + /* + * List of HOST:PORT:[addresses] strings to populate the DNS cache with + * Entries added this way will remain in the cache until explicitly + * removed or the handle is cleaned up. + * + * Prefix the HOST with plus sign (+) to have the entry expire like + * automatically added entries. + * + * Prefix the HOST with dash (-) to _remove_ the entry from the cache. + * + * This API can remove any entry from the DNS cache, but only entries + * that are not actually in use right now will be pruned immediately. + */ + s->resolve = slist; + data->state.resolve = s->resolve; + break; +#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_MIME) + case CURLOPT_HTTPHEADER: + /* + * Set a list with HTTP headers to use (or replace internals with) + */ + s->headers = slist; + break; +#endif +#ifndef CURL_DISABLE_TELNET + case CURLOPT_TELNETOPTIONS: + /* + * Set a linked list of telnet options + */ + s->telnet_options = slist; + break; +#endif +#ifndef CURL_DISABLE_SMTP + case CURLOPT_MAIL_RCPT: + /* Set the list of mail recipients */ + s->mail_rcpt = slist; + break; +#endif + case CURLOPT_CONNECT_TO: + s->connect_to = slist; + break; + default: + return CURLE_UNKNOWN_OPTION; + } + return result; +} + +#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_IMAP) +#ifndef CURL_DISABLE_MIME +static CURLcode setopt_mimepost(struct Curl_easy *data, curl_mime *mimep) +{ + /* + * Set to make us do MIME POST + */ + CURLcode result; + struct UserDefined *s = &data->set; + if(!s->mimepostp) { + s->mimepostp = curlx_malloc(sizeof(*s->mimepostp)); + if(!s->mimepostp) + return CURLE_OUT_OF_MEMORY; + Curl_mime_initpart(s->mimepostp); + } + + result = Curl_mime_set_subparts(s->mimepostp, mimep, FALSE); + if(!result) { + s->method = HTTPREQ_POST_MIME; + s->opt_no_body = FALSE; /* this is implied */ +#ifndef CURL_DISABLE_FORM_API + Curl_mime_cleanpart(data->state.formp); + curlx_safefree(data->state.formp); + data->state.mimepost = NULL; +#endif + } + return result; +} +#endif /* !CURL_DISABLE_MIME */ +#endif /* !CURL_DISABLE_HTTP || !CURL_DISABLE_SMTP || !CURL_DISABLE_IMAP */ + +static CURLcode setopt_share(struct Curl_easy *data, struct Curl_share *set) +{ + CURLcode result; + + if(data->conn) { + /* As this handle already has a connection attached, changing share now + would be complicated and error-prone */ + infof(data, "Cannot change share object while in use"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + } + else { + /* disconnect from old share, if any and possible */ + result = Curl_share_easy_unlink(data); + if(!result && GOOD_SHARE_HANDLE(set)) + /* use new share if it set */ + result = Curl_share_easy_link(data, set); + } + return result; +} + +/* assorted pointer type arguments */ +static CURLcode setopt_pointers(struct Curl_easy *data, CURLoption option, + va_list param) +{ + CURLcode result = CURLE_OK; + struct UserDefined *s = &data->set; + switch(option) { + case CURLOPT_CURLU: + /* + * pass CURLU to set URL + */ + Curl_bufref_free(&data->state.url); + CURL_EASY_STR_CLEAR(data, STRING_SET_URL); + s->uh = va_arg(param, CURLU *); + break; +#ifndef CURL_DISABLE_HTTP +#ifndef CURL_DISABLE_FORM_API + case CURLOPT_HTTPPOST: + /* + * Set to make us do HTTP POST. Legacy API-style. + */ + s->httppost = va_arg(param, struct curl_httppost *); + s->method = HTTPREQ_POST_FORM; + s->opt_no_body = FALSE; /* this is implied */ + Curl_mime_cleanpart(data->state.formp); + curlx_safefree(data->state.formp); + data->state.mimepost = NULL; + break; +#endif /* !CURL_DISABLE_FORM_API */ +#endif /* !CURL_DISABLE_HTTP */ +#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_IMAP) +#ifndef CURL_DISABLE_MIME + case CURLOPT_MIMEPOST: + result = setopt_mimepost(data, va_arg(param, curl_mime *)); + break; +#endif /* !CURL_DISABLE_MIME */ +#endif /* !CURL_DISABLE_HTTP || !CURL_DISABLE_SMTP || !CURL_DISABLE_IMAP */ + case CURLOPT_STDERR: + /* + * Set to a FILE * that should receive all error writes. This + * defaults to stderr for normal operations. + */ + s->err = va_arg(param, FILE *); + if(!s->err) + s->err = stderr; + break; + case CURLOPT_SHARE: + return setopt_share(data, va_arg(param, struct Curl_share *)); + + default: + return CURLE_UNKNOWN_OPTION; + } + return result; +} + +#ifndef CURL_DISABLE_COOKIES +static CURLcode cookielist(struct Curl_easy *data, const char *ptr) +{ + CURLcode result = CURLE_OK; + if(!ptr) + return CURLE_OK; + + if(curl_strequal(ptr, "ALL")) { + /* clear all cookies */ + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + Curl_cookie_clearall(data->cookies); + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); + } + else if(curl_strequal(ptr, "SESS")) { + /* clear session cookies */ + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + Curl_cookie_clearsess(data->cookies); + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); + } + else if(curl_strequal(ptr, "FLUSH")) { + /* flush cookies to file, takes care of the locking */ + Curl_flush_cookies(data, FALSE); + } + else if(curl_strequal(ptr, "RELOAD")) { + /* reload cookies from file */ + return Curl_cookie_loadfiles(data, COOKIE_NOPSL | + (data->set.cookiesession ? + COOKIE_NOSESSION : 0)); + } + else { + if(!data->cookies) { + /* if cookie engine was not running, activate it */ + data->cookies = Curl_cookie_init(); + if(!data->cookies) + return CURLE_OUT_OF_MEMORY; + data->state.cookie_engine = TRUE; + } + + /* general protection against mistakes and abuse */ + if(strlen(ptr) > CURL_MAX_INPUT_LENGTH) + return CURLE_BAD_FUNCTION_ARGUMENT; + + /* Adding these cookies without the PSL check, because the PSL is not + initialized until *perform() time, and this might be called before + that */ + Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); + if(checkprefix("Set-Cookie:", ptr)) + /* HTTP Header format line */ + result = Curl_cookie_add(data, data->cookies, ptr + 11, + NULL, NULL, + COOKIE_HTTPHEADER | COOKIE_SECURE | + COOKIE_NOPSL); + else + /* Netscape format line */ + result = Curl_cookie_add(data, data->cookies, ptr, NULL, + NULL, COOKIE_SECURE | COOKIE_NOPSL); + Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); + } + return result; +} + +static CURLcode cookiefile(struct Curl_easy *data, const char *ptr) +{ + /* + * Set cookie file to read and parse. Can be used multiple times. + */ + if(ptr) { + struct curl_slist *cl; + /* general protection against mistakes and abuse */ + if(strlen(ptr) > CURL_MAX_INPUT_LENGTH) + return CURLE_BAD_FUNCTION_ARGUMENT; + /* append the cookie filename to the list of filenames, and deal with + them later */ + cl = curl_slist_append(data->state.cookielist, ptr); + if(!cl) { + curl_slist_free_all(data->state.cookielist); + data->state.cookielist = NULL; + return CURLE_OUT_OF_MEMORY; + } + data->state.cookielist = cl; /* store the list for later use */ + } + else { + /* clear the list of cookie files */ + curl_slist_free_all(data->state.cookielist); + data->state.cookielist = NULL; + + if(!data->share || !data->share->cookies) { + /* throw away all existing cookies if this is not a shared cookie + container */ + Curl_cookie_clearall(data->cookies); + Curl_cookie_cleanup(data->cookies); + } + /* disable the cookie engine */ + data->cookies = NULL; + } + return CURLE_OK; +} +#endif + +#ifndef CURL_DISABLE_PROXY +static CURLcode setproxy(struct Curl_easy *data, const char *proxy) +{ + const char *str = CURL_EASY_STR(data, STRING_PROXY); + if(str && proxy && + /* there was one set, is this a new one? */ + !strcmp(str, proxy)) + return CURLE_OK; /* same one as before */ + + changeproxy(data); + return Curl_setstropt(data, STRING_PROXY, proxy); +} + +static CURLcode setopt_cptr_proxy(struct Curl_easy *data, CURLoption option, + char *ptr) +{ + CURLcode result = CURLE_OK; + struct UserDefined *s = &data->set; + switch(option) { + case CURLOPT_PROXYUSERPWD: { + /* + * user:password needed to use the proxy + */ + char *u = NULL; + char *p = NULL; + result = setstropt_userpwd(ptr, &u, &p); + + /* URL decode the components */ + if(!result) { + char *str = NULL; + CURL_EASY_STR_CLEAR(data, STRING_PROXYUSERNAME); + CURL_EASY_STR_CLEAR(data, STRING_PROXYPASSWORD); + if(u) { + result = Curl_urldecode(u, 0, &str, NULL, REJECT_ZERO); + if(!result) + result = Curl_u8_strset_setn(&s->strings, STRING_PROXYUSERNAME, str); + } + if(!result && p) { + str = NULL; + result = Curl_urldecode(p, 0, &str, NULL, REJECT_ZERO); + if(!result) + result = Curl_u8_strset_setn(&s->strings, STRING_PROXYPASSWORD, str); + } + } + curlx_free(u); + curlx_strzero(p); + curlx_free(p); + break; + } + case CURLOPT_PROXYUSERNAME: + /* + * authentication username to use in the operation + */ + return Curl_setstropt(data, STRING_PROXYUSERNAME, ptr); + + case CURLOPT_PROXYPASSWORD: + /* + * authentication password to use in the operation + */ + return Curl_setstropt(data, STRING_PROXYPASSWORD, ptr); + + case CURLOPT_NOPROXY: + /* + * proxy exception list + */ + return Curl_setstropt(data, STRING_NOPROXY, ptr); + case CURLOPT_PROXY_SSLCERT: + /* + * String that holds filename of the SSL certificate to use for proxy + */ + return Curl_setstropt(data, STRING_CERT_PROXY, ptr); + case CURLOPT_PROXY_SSLCERTTYPE: + /* + * String that holds file type of the SSL certificate to use for proxy + */ + return Curl_setstropt(data, STRING_CERT_TYPE_PROXY, ptr); + case CURLOPT_PROXY_SSLKEY: + /* + * String that holds filename of the SSL key to use for proxy + */ + return Curl_setstropt(data, STRING_KEY_PROXY, ptr); + case CURLOPT_PROXY_KEYPASSWD: + /* + * String that holds the SSL private key password for proxy. + */ + return Curl_setstropt(data, STRING_KEY_PASSWD_PROXY, ptr); + case CURLOPT_PROXY_SSLKEYTYPE: + /* + * String that holds file type of the SSL key to use for proxy + */ + return Curl_setstropt(data, STRING_KEY_TYPE_PROXY, ptr); + case CURLOPT_PROXY_SSL_CIPHER_LIST: + if(Curl_ssl_supports(data, SSLSUPP_CIPHER_LIST)) { + /* set a list of cipher we want to use in the SSL connection for proxy */ + return Curl_setstropt(data, STRING_SSL_CIPHER_LIST_PROXY, ptr); + } + else + return CURLE_NOT_BUILT_IN; + case CURLOPT_PROXY_TLS13_CIPHERS: + if(Curl_ssl_supports(data, SSLSUPP_TLS13_CIPHERSUITES)) + /* set preferred list of TLS 1.3 cipher suites for proxy */ + return Curl_setstropt(data, STRING_SSL_CIPHER13_LIST_PROXY, ptr); + else + return CURLE_NOT_BUILT_IN; + case CURLOPT_PROXY: + /* + * Set proxy server:port to use as proxy. + * + * If the proxy is set to "" (and CURLOPT_PRE_PROXY is set to "" or NULL) + * we explicitly say that we do not want to use a proxy (even though there + * might be environment variables saying so). + * + * Setting it to NULL, means no proxy but allows the environment variables + * to decide for us (if CURLOPT_PRE_PROXY setting it to NULL). + */ + return setproxy(data, ptr); + case CURLOPT_PRE_PROXY: + /* + * Set proxy server:port to use as SOCKS proxy. + * + * If the proxy is set to "" or NULL we explicitly say that we do not want + * to use the socks proxy. + */ + return Curl_setstropt(data, STRING_PRE_PROXY, ptr); + case CURLOPT_SOCKS5_GSSAPI_SERVICE: + case CURLOPT_PROXY_SERVICE_NAME: + /* + * Set proxy authentication service name for Kerberos 5 and SPNEGO + */ + return Curl_setstropt(data, STRING_PROXY_SERVICE_NAME, ptr); + case CURLOPT_PROXY_PINNEDPUBLICKEY: + /* + * Set pinned public key for SSL connection. + * Specify filename of the public key in DER format. + */ +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_PINNEDPUBKEY)) + return Curl_setstropt(data, STRING_SSL_PINNEDPUBLICKEY_PROXY, ptr); +#endif + return CURLE_NOT_BUILT_IN; + + case CURLOPT_HAPROXY_CLIENT_IP: + /* + * Set the client IP to send through HAProxy PROXY protocol + */ + result = Curl_setstropt(data, STRING_HAPROXY_CLIENT_IP, ptr); + + /* enable the HAProxy protocol if an IP is provided */ + s->haproxyprotocol = !!CURL_EASY_STR(data, STRING_HAPROXY_CLIENT_IP); + break; + case CURLOPT_PROXY_CAINFO: + /* + * Set CA info SSL connection for proxy. Specify filename of the + * CA certificate + */ + result = Curl_setstropt(data, STRING_SSL_CAFILE_PROXY, ptr); + s->proxy_ssl.custom_cafile = + !!CURL_EASY_STR(data, STRING_SSL_CAFILE_PROXY); + return result; + case CURLOPT_PROXY_CRLFILE: + /* + * Set CRL file info for SSL connection for proxy. Specify filename of the + * CRL to check certificates revocation + */ + if(Curl_ssl_supports(data, SSLSUPP_CRLFILE)) + return Curl_setstropt(data, STRING_SSL_CRLFILE_PROXY, ptr); + return CURLE_NOT_BUILT_IN; + case CURLOPT_PROXY_ISSUERCERT: + /* + * Set Issuer certificate file to check certificates issuer + */ + if(Curl_ssl_supports(data, SSLSUPP_ISSUERCERT)) + return Curl_setstropt(data, STRING_SSL_ISSUERCERT_PROXY, ptr); + return CURLE_NOT_BUILT_IN; + case CURLOPT_PROXY_CAPATH: + /* + * Set CA path info for SSL connection proxy. Specify directory name of the + * CA certificates which have been prepared using openssl c_rehash utility. + */ +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_CA_PATH)) { + /* This does not work on Windows. */ + result = Curl_setstropt(data, STRING_SSL_CAPATH_PROXY, ptr); + s->proxy_ssl.custom_capath = + !!CURL_EASY_STR(data, STRING_SSL_CAPATH_PROXY); + return result; + } +#endif + return CURLE_NOT_BUILT_IN; + default: + return CURLE_UNKNOWN_OPTION; + } + return result; +} +#endif + +#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_MQTT) +/* + * A string with POST data. Makes curl HTTP POST. Even if it is NULL. If + * needed, CURLOPT_POSTFIELDSIZE must have been set prior to + * CURLOPT_COPYPOSTFIELDS and not altered later. + */ +static CURLcode setopt_copypostfields(const char *ptr, struct UserDefined *s) +{ + CURLcode result = CURLE_OK; + if(s->postfieldsize < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + if(!ptr || s->postfieldsize == -1) { + if(ptr && (strlen(ptr) > CURL_MAX_INPUT_LENGTH)) + return CURLE_BAD_FUNCTION_ARGUMENT; + curlx_safefree(s->str_copypostfields); + if(ptr) { + s->str_copypostfields = curlx_strdup(ptr); + if(!s->str_copypostfields) + return CURLE_OUT_OF_MEMORY; + } + } + else { + size_t pflen = curlx_sotouz_range(s->postfieldsize, 0, SIZE_MAX); + if(pflen == SIZE_MAX) + return CURLE_OUT_OF_MEMORY; + else { + /* Allocate even when size == 0. This satisfies the need of possible + later address compare to detect the COPYPOSTFIELDS mode, and to mark + that postfields is used rather than read function or form data. */ + char *p = curlx_memdup0(ptr, pflen); + if(!p) + return CURLE_OUT_OF_MEMORY; + else { + curlx_free(s->str_copypostfields); + s->str_copypostfields = p; + } + } + } + + s->postfields = s->str_copypostfields; + s->method = HTTPREQ_POST; + return result; +} +#endif + +#ifdef USE_ECH +static CURLcode setopt_ech(struct Curl_easy *data, const char *ptr) +{ + struct UserDefined *s = &data->set; + CURLcode result = CURLE_OK; + + if(!ptr || !strcmp(ptr, "false")) + s->tls_ech = CURLECH_DISABLE; + else { + size_t plen = strlen(ptr); + if(plen > CURL_MAX_INPUT_LENGTH) + result = CURLE_BAD_FUNCTION_ARGUMENT; + else { + if(!strcmp(ptr, "grease")) + s->tls_ech = CURLECH_GREASE; + else if(!strcmp(ptr, "true")) + s->tls_ech = CURLECH_ENABLE; + else if(!strcmp(ptr, "hard")) + s->tls_ech = CURLECH_HARD; + else if(plen > 4 && !strncmp(ptr, "ecl:", 4)) { + if(!s->tls_ech) + s->tls_ech = CURLECH_HARD; + result = Curl_setstropt(data, STRING_ECH_CONFIG, ptr + 4); + } + else if(plen > 3 && !strncmp(ptr, "pn:", 3)) { + if(!s->tls_ech) + s->tls_ech = CURLECH_HARD; + result = Curl_setstropt(data, STRING_ECH_PUBLIC, ptr + 3); + } + else + result = CURLE_BAD_FUNCTION_ARGUMENT; + } + } + return result; +} +#else +#define setopt_ech(x, y) CURLE_NOT_BUILT_IN +#endif + +#if defined(USE_SSL) || defined(USE_SSH) +/* One of the options is used for both TLS and SSH */ +static CURLcode setopt_cptr_ssl(struct Curl_easy *data, CURLoption option, + char *ptr) +{ + CURLcode result = CURLE_OK; + + switch(option) { + case CURLOPT_KEYPASSWD: + /* + * String that holds the SSL or SSH private key password. + */ + result = Curl_setstropt(data, STRING_KEY_PASSWD, ptr); + break; +#ifdef USE_SSL + case CURLOPT_CAINFO: + /* + * Set CA info for SSL connection. Specify filename of the CA certificate + */ + result = Curl_setstropt(data, STRING_SSL_CAFILE, ptr); + data->set.ssl.custom_cafile = !!CURL_EASY_STR(data, STRING_SSL_CAFILE); + return result; + case CURLOPT_CAPATH: + /* + * Set CA path info for SSL connection. Specify directory name of the CA + * certificates which have been prepared using openssl c_rehash utility. + */ + if(Curl_ssl_supports(data, SSLSUPP_CA_PATH)) { + /* This does not work on Windows. */ + result = Curl_setstropt(data, STRING_SSL_CAPATH, ptr); + data->set.ssl.custom_capath = !!CURL_EASY_STR(data, STRING_SSL_CAPATH); + return result; + } + return CURLE_NOT_BUILT_IN; + case CURLOPT_CRLFILE: + /* + * Set CRL file info for SSL connection. Specify filename of the CRL + * to check certificates revocation + */ + if(Curl_ssl_supports(data, SSLSUPP_CRLFILE)) + return Curl_setstropt(data, STRING_SSL_CRLFILE, ptr); + return CURLE_NOT_BUILT_IN; + case CURLOPT_SSL_CIPHER_LIST: + if(Curl_ssl_supports(data, SSLSUPP_CIPHER_LIST)) + /* set a list of cipher we want to use in the SSL connection */ + return Curl_setstropt(data, STRING_SSL_CIPHER_LIST, ptr); + else + return CURLE_NOT_BUILT_IN; + case CURLOPT_TLS13_CIPHERS: + if(Curl_ssl_supports(data, SSLSUPP_TLS13_CIPHERSUITES)) + /* set preferred list of TLS 1.3 cipher suites */ + return Curl_setstropt(data, STRING_SSL_CIPHER13_LIST, ptr); + else + return CURLE_NOT_BUILT_IN; + case CURLOPT_RANDOM_FILE: + break; + case CURLOPT_EGDSOCKET: + break; + case CURLOPT_SSL_CTX_DATA: + /* + * Set an SSL_CTX callback parameter pointer + */ + if(Curl_ssl_supports(data, SSLSUPP_SSL_CTX)) { + data->set.ssl.fsslctxp = ptr; + break; + } + else + return CURLE_NOT_BUILT_IN; + case CURLOPT_SSLCERT: + /* + * String that holds filename of the SSL certificate to use + */ + return Curl_setstropt(data, STRING_CERT, ptr); + case CURLOPT_SSLCERTTYPE: + /* + * String that holds file type of the SSL certificate to use + */ + return Curl_setstropt(data, STRING_CERT_TYPE, ptr); + case CURLOPT_SSLKEY: + /* + * String that holds filename of the SSL key to use + */ + return Curl_setstropt(data, STRING_KEY, ptr); + case CURLOPT_SSLKEYTYPE: + /* + * String that holds file type of the SSL key to use + */ + return Curl_setstropt(data, STRING_KEY_TYPE, ptr); + case CURLOPT_SSLENGINE: + /* + * String that holds the SSL crypto engine. + */ + if(ptr && ptr[0]) { + result = Curl_setstropt(data, STRING_SSL_ENGINE, ptr); + if(!result) { + result = Curl_ssl_set_engine(data, ptr); + } + } + break; + case CURLOPT_ISSUERCERT: + /* + * Set Issuer certificate file + * to check certificates issuer + */ + if(Curl_ssl_supports(data, SSLSUPP_ISSUERCERT)) + return Curl_setstropt(data, STRING_SSL_ISSUERCERT, ptr); + return CURLE_NOT_BUILT_IN; + case CURLOPT_SSL_EC_CURVES: + /* + * Set accepted curves in SSL connection setup. + * Specify colon-delimited list of curve algorithm names. + */ + if(Curl_ssl_supports(data, SSLSUPP_SSL_EC_CURVES)) + return Curl_setstropt(data, STRING_SSL_EC_CURVES, ptr); + return CURLE_NOT_BUILT_IN; + case CURLOPT_SSL_SIGNATURE_ALGORITHMS: + /* + * Set accepted signature algorithms. + * Specify colon-delimited list of signature scheme names. + */ + if(Curl_ssl_supports(data, SSLSUPP_SIGNATURE_ALGORITHMS)) + return Curl_setstropt(data, STRING_SSL_SIGNATURE_ALGORITHMS, ptr); + return CURLE_NOT_BUILT_IN; + case CURLOPT_PINNEDPUBLICKEY: + /* + * Set pinned public key for SSL connection. + * Specify filename of the public key in DER format. + */ + if(Curl_ssl_supports(data, SSLSUPP_PINNEDPUBKEY)) + return Curl_setstropt(data, STRING_SSL_PINNEDPUBLICKEY, ptr); + return CURLE_NOT_BUILT_IN; + case CURLOPT_ECH: + return setopt_ech(data, ptr); +#endif + default: + return CURLE_UNKNOWN_OPTION; + } + return result; +} +#endif + +#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_MQTT) +static CURLcode setopt_cptr_http_mqtt(struct Curl_easy *data, + CURLoption option, char *ptr) +{ + CURLcode result = CURLE_OK; + struct UserDefined *s = &data->set; + + switch(option) { + case CURLOPT_COPYPOSTFIELDS: + return setopt_copypostfields(ptr, s); + + case CURLOPT_POSTFIELDS: + /* + * Like above, but use static data instead of copying it. + */ + s->postfields = ptr; + /* Release old copied data. */ + curlx_safefree(s->str_copypostfields); + s->method = HTTPREQ_POST; + break; + +#ifndef CURL_DISABLE_HTTP + case CURLOPT_TRAILERDATA: + s->trailer_data = ptr; + break; + case CURLOPT_ACCEPT_ENCODING: + /* + * String to use at the value of Accept-Encoding header. + * + * If the encoding is set to "" we use an Accept-Encoding header that + * encompasses all the encodings we support. + * If the encoding is set to NULL we do not send an Accept-Encoding header + * and ignore any received Content-Encoding header. + * + */ + if(ptr && !*ptr) { + ptr = Curl_get_content_encodings(); + if(ptr) + result = CURL_EASY_STR_SETN(data, STRING_ENCODING, ptr); + else + result = CURLE_OUT_OF_MEMORY; + return result; + } + return Curl_setstropt(data, STRING_ENCODING, ptr); + +#ifndef CURL_DISABLE_AWS + case CURLOPT_AWS_SIGV4: + /* + * String that is merged to some authentication + * parameters are used by the algorithm. + */ + result = Curl_setstropt(data, STRING_AWS_SIGV4, ptr); + /* + * Basic has been set by default; it needs to be unset here. + */ + if(CURL_EASY_STR(data, STRING_AWS_SIGV4)) + s->httpauth = CURLAUTH_AWS_SIGV4; + else + s->httpauth &= ~(uint32_t)CURLAUTH_AWS_SIGV4; + break; +#endif +#ifndef CURL_DISABLE_HTTPSIG + case CURLOPT_HTTPSIG_KEY: + result = Curl_setstropt(data, STRING_HTTPSIG_KEY, ptr); + break; + case CURLOPT_HTTPSIG_KEYID: + result = Curl_setstropt(data, STRING_HTTPSIG_KEYID, ptr); + break; + case CURLOPT_HTTPSIG_HEADERS: + result = Curl_setstropt(data, STRING_HTTPSIG_HEADERS, ptr); + break; +#endif + case CURLOPT_REFERER: { + /* + * String to set in the HTTP Referer: field. + */ + struct bufref *oldref = &data->state.referer; + /* free the old after the storing the new in case the input is actually + pointing back to this */ + result = Curl_setstropt(data, STRING_SET_REFERER, ptr); + Curl_bufref_free(oldref); + break; + } + + case CURLOPT_USERAGENT: + /* + * String to use in the HTTP User-Agent field + */ + return Curl_setstropt(data, STRING_USERAGENT, ptr); + +#ifndef CURL_DISABLE_COOKIES + case CURLOPT_COOKIE: + /* + * Cookie string to send to the remote server in the request. + */ + return Curl_setstropt(data, STRING_COOKIE, ptr); + + case CURLOPT_COOKIEFILE: + return cookiefile(data, ptr); + + case CURLOPT_COOKIEJAR: + /* + * Set cookie filename to dump all cookies to when we are done. + */ + result = Curl_setstropt(data, STRING_COOKIEJAR, ptr); + if(!result) { + /* + * Activate the cookie parser. This may or may not already + * have been made. + */ + if(!data->cookies) + data->cookies = Curl_cookie_init(); + if(!data->cookies) + result = CURLE_OUT_OF_MEMORY; + else + data->state.cookie_engine = TRUE; + } + break; + + case CURLOPT_COOKIELIST: + return cookielist(data, ptr); +#endif /* !CURL_DISABLE_COOKIES */ + +#endif /* !CURL_DISABLE_HTTP */ + default: + return CURLE_UNKNOWN_OPTION; + } + return result; +} +#endif /* !CURL_DISABLE_HTTP || !CURL_DISABLE_MQTT */ + +#ifdef USE_SSH +static CURLcode setopt_cptr_ssh(struct Curl_easy *data, CURLoption option, + char *ptr) +{ + struct UserDefined *s = &data->set; + switch(option) { + case CURLOPT_SSH_PUBLIC_KEYFILE: + /* + * Use this file instead of the $HOME/.ssh/id_dsa.pub file + */ + return Curl_setstropt(data, STRING_SSH_PUBLIC_KEY, ptr); + case CURLOPT_SSH_PRIVATE_KEYFILE: + /* + * Use this file instead of the $HOME/.ssh/id_dsa file + */ + return Curl_setstropt(data, STRING_SSH_PRIVATE_KEY, ptr); + case CURLOPT_SSH_KEYDATA: + /* + * Custom client data to pass to the SSH keyfunc callback + */ + s->ssh_keyfunc_userp = ptr; + break; + case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5: + /* + * Option to allow for the MD5 of the host public key to be checked + * for validation purposes. + */ + return Curl_setstropt(data, STRING_SSH_HOST_PUBLIC_KEY_MD5, ptr); + case CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256: + /* + * Option to allow for the SHA256 of the host public key to be checked + * for validation purposes. + */ + return Curl_setstropt(data, STRING_SSH_HOST_PUBLIC_KEY_SHA256, ptr); + case CURLOPT_SSH_KNOWNHOSTS: + /* + * Store the filename to read known hosts from. + */ + return Curl_setstropt(data, STRING_SSH_KNOWNHOSTS, ptr); +#ifdef USE_LIBSSH2 + case CURLOPT_SSH_HOSTKEYDATA: + /* + * Custom client data to pass to the SSH keyfunc callback + */ + s->ssh_hostkeyfunc_userp = ptr; + break; +#endif /* USE_LIBSSH2 */ + default: + return CURLE_UNKNOWN_OPTION; + } + return CURLE_OK; +} +#endif /* USE_SSH */ + +#ifndef CURL_DISABLE_FTP +static CURLcode setopt_cptr_ftp(struct Curl_easy *data, CURLoption option, + char *ptr) +{ + CURLcode result = CURLE_OK; + struct UserDefined *s = &data->set; + switch(option) { + case CURLOPT_FTPPORT: + /* + * Use FTP PORT, this also specifies which IP address to use + */ + result = Curl_setstropt(data, STRING_FTPPORT, ptr); + s->ftp_use_port = !!CURL_EASY_STR(data, STRING_FTPPORT); + break; + + case CURLOPT_FTP_ACCOUNT: + return Curl_setstropt(data, STRING_FTP_ACCOUNT, ptr); + + case CURLOPT_FTP_ALTERNATIVE_TO_USER: + return Curl_setstropt(data, STRING_FTP_ALTERNATIVE_TO_USER, ptr); + + case CURLOPT_KRBLEVEL: + return CURLE_NOT_BUILT_IN; /* removed in 8.17.0 */ + case CURLOPT_CHUNK_DATA: + s->wildcardptr = ptr; + break; + case CURLOPT_FNMATCH_DATA: + s->fnmatch_data = ptr; + break; + default: + return CURLE_UNKNOWN_OPTION; + } + return result; +} +#endif /* !CURL_DISABLE_FTP */ + +static CURLcode setopt_cptr_net(struct Curl_easy *data, CURLoption option, + char *ptr) +{ + switch(option) { + case CURLOPT_INTERFACE: + /* + * Set what interface or address/hostname to bind the socket to when + * performing an operation and thus what from-IP your connection will use. + */ + return setstropt_interface(data, ptr); + +#ifdef USE_RESOLV_ARES + case CURLOPT_DNS_SERVERS: + return Curl_setstropt(data, STRING_DNS_SERVERS, ptr); + + case CURLOPT_DNS_INTERFACE: + return Curl_setstropt(data, STRING_DNS_INTERFACE, ptr); + + case CURLOPT_DNS_LOCAL_IP4: + return Curl_setstropt(data, STRING_DNS_LOCAL_IP4, ptr); + + case CURLOPT_DNS_LOCAL_IP6: + return Curl_setstropt(data, STRING_DNS_LOCAL_IP6, ptr); +#endif +#ifdef USE_UNIX_SOCKETS + case CURLOPT_UNIX_SOCKET_PATH: + data->set.abstract_unix_socket = FALSE; + return Curl_setstropt(data, STRING_UNIX_SOCKET_PATH, ptr); + + case CURLOPT_ABSTRACT_UNIX_SOCKET: + data->set.abstract_unix_socket = TRUE; + return Curl_setstropt(data, STRING_UNIX_SOCKET_PATH, ptr); +#endif +#ifndef CURL_DISABLE_DOH + case CURLOPT_DOH_URL: + { + CURLcode result = Curl_setstropt(data, STRING_DOH, ptr); + data->set.doh = !!CURL_EASY_STR(data, STRING_DOH); + return result; + } +#endif + default: + return CURLE_UNKNOWN_OPTION; + } +} + +static CURLcode setopt_cptr_misc(struct Curl_easy *data, CURLoption option, + char *ptr) +{ + CURLcode result = CURLE_OK; + struct UserDefined *s = &data->set; + + switch(option) { + case CURLOPT_REQUEST_TARGET: + return Curl_setstropt(data, STRING_TARGET, ptr); +#ifndef CURL_DISABLE_NETRC + case CURLOPT_NETRC_FILE: + return Curl_setstropt(data, STRING_NETRC_FILE, ptr); +#endif + case CURLOPT_CUSTOMREQUEST: + return Curl_setstropt(data, STRING_CUSTOMREQUEST, ptr); + + /* we do not set s->method = HTTPREQ_CUSTOM; here, we continue as if we + were using the already set type and this changes the actual request + keyword */ + case CURLOPT_SERVICE_NAME: + return Curl_setstropt(data, STRING_SERVICE_NAME, ptr); + + case CURLOPT_HEADERDATA: + s->writeheader = ptr; + break; + case CURLOPT_READDATA: + s->in_set = ptr; + break; + case CURLOPT_WRITEDATA: + s->out = ptr; + break; + case CURLOPT_DEBUGDATA: + s->debugdata = ptr; + break; + case CURLOPT_PROGRESSDATA: + s->progress_client = ptr; + break; + case CURLOPT_SEEKDATA: + s->seek_client = ptr; + break; + case CURLOPT_IOCTLDATA: + s->ioctl_client = ptr; + break; + case CURLOPT_SOCKOPTDATA: + s->sockopt_client = ptr; + break; + case CURLOPT_OPENSOCKETDATA: + s->opensocket_client = ptr; + break; + case CURLOPT_RESOLVER_START_DATA: + s->resolver_start_client = ptr; + break; + case CURLOPT_CLOSESOCKETDATA: + s->closesocket_client = ptr; + break; + case CURLOPT_PREREQDATA: + s->prereq_userp = ptr; + break; + case CURLOPT_ERRORBUFFER: + s->errorbuffer = ptr; + break; + case CURLOPT_URL: + result = Curl_setstropt(data, STRING_SET_URL, ptr); + Curl_bufref_set(&data->state.url, + CURL_EASY_STR(data, STRING_SET_URL), 0, NULL); + break; + + case CURLOPT_USERPWD: { + char *u = NULL, *p = NULL; + result = setstropt_userpwd(ptr, &u, &p); + if(!result) { + result = CURL_EASY_STR_SETN(data, STRING_USERNAME, u); + u = NULL; + } + if(!result) { + result = CURL_EASY_STR_SETN(data, STRING_PASSWORD, p); + p = NULL; + } + curlx_free(u); + curlx_free(p); + return result; + } + + case CURLOPT_USERNAME: + return Curl_setstropt(data, STRING_USERNAME, ptr); + + case CURLOPT_PASSWORD: + return Curl_setstropt(data, STRING_PASSWORD, ptr); + + case CURLOPT_LOGIN_OPTIONS: + return Curl_setstropt(data, STRING_OPTIONS, ptr); + + case CURLOPT_XOAUTH2_BEARER: + return Curl_setstropt(data, STRING_BEARER, ptr); + case CURLOPT_RANGE: + return Curl_setstropt(data, STRING_SET_RANGE, ptr); + case CURLOPT_PRIVATE: + s->private_data = ptr; + break; + case CURLOPT_PROTOCOLS_STR: + if(ptr) { + curl_prot_t protos; + result = protocol2num(ptr, &protos); + if(!result) + s->allowed_protocols = protos; + } + else + /* make a NULL argument reset to default */ + s->allowed_protocols = (curl_prot_t)CURLPROTO_64ALL; + break; + case CURLOPT_REDIR_PROTOCOLS_STR: + if(ptr) { + curl_prot_t protos; + result = protocol2num(ptr, &protos); + if(!result) + s->redir_protocols = protos; + } + else + /* make a NULL argument reset to default */ + s->redir_protocols = (curl_prot_t)CURLPROTO_REDIR; + break; + case CURLOPT_DEFAULT_PROTOCOL: + /* Set the protocol to use when the URL does not include any protocol */ + return Curl_setstropt(data, STRING_DEFAULT_PROTOCOL, ptr); +#ifndef CURL_DISABLE_SMTP + case CURLOPT_MAIL_FROM: + /* Set the SMTP mail originator */ + return Curl_setstropt(data, STRING_MAIL_FROM, ptr); + case CURLOPT_MAIL_AUTH: + /* Set the SMTP auth originator */ + return Curl_setstropt(data, STRING_MAIL_AUTH, ptr); +#endif + case CURLOPT_SASL_AUTHZID: + /* Authorization identity (identity to act as) */ + return Curl_setstropt(data, STRING_SASL_AUTHZID, ptr); +#ifndef CURL_DISABLE_RTSP + case CURLOPT_RTSP_SESSION_ID: + return Curl_setstropt(data, STRING_RTSP_SESSION_ID, ptr); + case CURLOPT_RTSP_STREAM_URI: + return Curl_setstropt(data, STRING_RTSP_STREAM_URI, ptr); + case CURLOPT_RTSP_TRANSPORT: + return Curl_setstropt(data, STRING_RTSP_TRANSPORT, ptr); + case CURLOPT_INTERLEAVEDATA: + s->rtp_out = ptr; + break; +#endif /* !CURL_DISABLE_RTSP */ + case CURLOPT_TLSAUTH_USERNAME: + case CURLOPT_TLSAUTH_PASSWORD: + case CURLOPT_TLSAUTH_TYPE: + case CURLOPT_PROXY_TLSAUTH_USERNAME: + case CURLOPT_PROXY_TLSAUTH_PASSWORD: + case CURLOPT_PROXY_TLSAUTH_TYPE: + return CURLE_NOT_BUILT_IN; +#ifndef CURL_DISABLE_HSTS + case CURLOPT_HSTSREADDATA: + s->hsts_read_userp = ptr; + break; + case CURLOPT_HSTSWRITEDATA: + s->hsts_write_userp = ptr; + break; + case CURLOPT_HSTS: { + struct curl_slist *h; + if(!data->hsts) { + data->hsts = Curl_hsts_init(); + if(!data->hsts) + return CURLE_OUT_OF_MEMORY; + } + if(ptr) { + result = Curl_setstropt(data, STRING_HSTS, ptr); + if(result) + return result; + /* this needs to build a list of filenames to read from, so that it can + read them later, as we might get a shared HSTS handle to load them + into */ + h = curl_slist_append(data->state.hstslist, ptr); + if(!h) { + curl_slist_free_all(data->state.hstslist); + data->state.hstslist = NULL; + return CURLE_OUT_OF_MEMORY; + } + data->state.hstslist = h; /* store the list for later use */ + } + else { + /* clear the list of HSTS files */ + curl_slist_free_all(data->state.hstslist); + data->state.hstslist = NULL; + if(!data->share || !data->share->hsts) + /* throw away the HSTS cache unless shared */ + Curl_hsts_cleanup(&data->hsts); + } + break; + } +#endif /* !CURL_DISABLE_HSTS */ +#ifndef CURL_DISABLE_ALTSVC + case CURLOPT_ALTSVC: + if(!data->asi) { + data->asi = Curl_altsvc_init(); + if(!data->asi) + return CURLE_OUT_OF_MEMORY; + } + result = Curl_setstropt(data, STRING_ALTSVC, ptr); + if(result) + break; + if(ptr) + return Curl_altsvc_load(data->asi, ptr); + break; +#endif /* !CURL_DISABLE_ALTSVC */ + case CURLOPT_ECH: + return setopt_ech(data, ptr); + default: + return CURLE_UNKNOWN_OPTION; + } + return result; +} + +static CURLcode setopt_cptr(struct Curl_easy *data, CURLoption option, + char *ptr) +{ + typedef CURLcode (*ptrfunc)(struct Curl_easy *data, CURLoption option, + char *ptr); + /* Order by likeliness */ + static const ptrfunc setopt_call[] = { + setopt_cptr_misc, +#if defined(USE_SSL) || defined(USE_SSH) + setopt_cptr_ssl, +#endif +#ifndef CURL_DISABLE_PROXY + setopt_cptr_proxy, +#endif + setopt_cptr_net, +#ifndef CURL_DISABLE_FTP + setopt_cptr_ftp, +#endif +#ifdef USE_SSH + setopt_cptr_ssh, +#endif +#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_MQTT) + setopt_cptr_http_mqtt, +#endif + }; + size_t i; + + for(i = 0; i < CURL_ARRAYSIZE(setopt_call); i++) { + CURLcode result = setopt_call[i](data, option, ptr); + if(result != CURLE_UNKNOWN_OPTION) + return result; + } + return CURLE_UNKNOWN_OPTION; +} + +static CURLcode setopt_func(struct Curl_easy *data, CURLoption option, + va_list param) +{ + struct UserDefined *s = &data->set; + switch(option) { + case CURLOPT_PROGRESSFUNCTION: + /* + * Progress callback function + */ + s->fprogress = va_arg(param, curl_progress_callback); + if(s->fprogress) + data->progress.callback = TRUE; /* no longer internal */ + else + data->progress.callback = FALSE; /* NULL enforces internal */ + break; + + case CURLOPT_XFERINFOFUNCTION: + /* + * Transfer info callback function + */ + s->fxferinfo = va_arg(param, curl_xferinfo_callback); + if(s->fxferinfo) + data->progress.callback = TRUE; /* no longer internal */ + else + data->progress.callback = FALSE; /* NULL enforces internal */ + + break; + case CURLOPT_DEBUGFUNCTION: + /* + * stderr write callback. + */ + s->fdebug = va_arg(param, curl_debug_callback); + /* + * if the callback provided is NULL, it will use the default callback + */ + break; + case CURLOPT_HEADERFUNCTION: + /* + * Set header write callback + */ + s->fwrite_header = va_arg(param, curl_write_callback); + break; + case CURLOPT_WRITEFUNCTION: + /* + * Set data write callback + */ + s->fwrite_func = va_arg(param, curl_write_callback); + if(!s->fwrite_func) +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcast-function-type-strict" +#endif + /* When set to NULL, reset to our internal default function */ + s->fwrite_func = (curl_write_callback)fwrite; +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic pop +#endif + break; + case CURLOPT_READFUNCTION: + /* + * Read data callback + */ + s->fread_func_set = va_arg(param, curl_read_callback); + if(!s->fread_func_set) { + s->is_fread_set = 0; +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcast-function-type-strict" +#endif + /* When set to NULL, reset to our internal default function */ + s->fread_func_set = (curl_read_callback)fread; +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic pop +#endif + } + else + s->is_fread_set = 1; + break; + case CURLOPT_SEEKFUNCTION: + /* + * Seek callback. Might be NULL. + */ + s->seek_func = va_arg(param, curl_seek_callback); + break; + case CURLOPT_IOCTLFUNCTION: + /* + * I/O control callback. Might be NULL. + */ + s->ioctl_func = va_arg(param, curl_ioctl_callback); + break; + case CURLOPT_SSL_CTX_FUNCTION: + /* + * Set an SSL_CTX callback + */ +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_SSL_CTX)) { + s->ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback); + break; + } + else +#endif + return CURLE_NOT_BUILT_IN; + + case CURLOPT_SOCKOPTFUNCTION: + /* + * socket callback function: called after socket() but before connect() + */ + s->fsockopt = va_arg(param, curl_sockopt_callback); + break; + + case CURLOPT_OPENSOCKETFUNCTION: + /* + * open/create socket callback function: called instead of socket(), + * before connect() + */ + s->fopensocket = va_arg(param, curl_opensocket_callback); + break; + + case CURLOPT_CLOSESOCKETFUNCTION: + /* + * close socket callback function: called instead of close() + * when shutting down a connection + */ + s->fclosesocket = va_arg(param, curl_closesocket_callback); + break; + + case CURLOPT_RESOLVER_START_FUNCTION: + /* + * resolver start callback function: called before a new resolver request + * is started + */ + s->resolver_start = va_arg(param, curl_resolver_start_callback); + break; + +#ifdef USE_SSH +#ifdef USE_LIBSSH2 + case CURLOPT_SSH_HOSTKEYFUNCTION: + /* the callback to check the hostkey without the knownhost file */ + s->ssh_hostkeyfunc = va_arg(param, curl_sshhostkeycallback); + break; +#endif + + case CURLOPT_SSH_KEYFUNCTION: + /* setting to NULL is fine since the ssh.c functions themselves will + then revert to use the internal default */ + s->ssh_keyfunc = va_arg(param, curl_sshkeycallback); + break; + +#endif /* USE_SSH */ + +#ifndef CURL_DISABLE_RTSP + case CURLOPT_INTERLEAVEFUNCTION: + /* Set the user defined RTP write function */ + s->fwrite_rtp = va_arg(param, curl_write_callback); + break; +#endif +#ifndef CURL_DISABLE_FTP + case CURLOPT_CHUNK_BGN_FUNCTION: + s->chunk_bgn = va_arg(param, curl_chunk_bgn_callback); + break; + case CURLOPT_CHUNK_END_FUNCTION: + s->chunk_end = va_arg(param, curl_chunk_end_callback); + break; + case CURLOPT_FNMATCH_FUNCTION: + s->fnmatch = va_arg(param, curl_fnmatch_callback); + break; +#endif +#ifndef CURL_DISABLE_HTTP + case CURLOPT_TRAILERFUNCTION: + s->trailer_callback = va_arg(param, curl_trailer_callback); + break; +#endif +#ifndef CURL_DISABLE_HSTS + case CURLOPT_HSTSREADFUNCTION: + s->hsts_read = va_arg(param, curl_hstsread_callback); + break; + case CURLOPT_HSTSWRITEFUNCTION: + s->hsts_write = va_arg(param, curl_hstswrite_callback); + break; +#endif + case CURLOPT_PREREQFUNCTION: + s->fprereq = va_arg(param, curl_prereq_callback); + break; + default: + return CURLE_UNKNOWN_OPTION; + } + return CURLE_OK; +} + +static CURLcode setopt_offt(struct Curl_easy *data, CURLoption option, + curl_off_t offt) +{ + struct UserDefined *s = &data->set; + switch(option) { + case CURLOPT_TIMEVALUE_LARGE: + /* + * This is the value to compare with the remote document with the + * method set with CURLOPT_TIMECONDITION + */ + s->timevalue = (time_t)offt; + break; + + /* MQTT "borrows" some of the HTTP options */ + case CURLOPT_POSTFIELDSIZE_LARGE: + /* + * The size of the POSTFIELD data to prevent libcurl to do strlen() to + * figure it out. Enables binary posts. + */ + if(offt < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(s->postfieldsize < offt && s->str_copypostfields) { + /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */ + curlx_safefree(s->str_copypostfields); + s->postfields = NULL; + } + s->postfieldsize = offt; + break; + case CURLOPT_INFILESIZE_LARGE: + /* + * If known, this should inform curl about the file size of the + * to-be-uploaded file. + */ + if(offt < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + s->filesize = offt; + break; + case CURLOPT_MAX_SEND_SPEED_LARGE: + /* + * When transfer uploads are faster than CURLOPT_MAX_SEND_SPEED_LARGE + * bytes per second the transfer is throttled.. + */ + if(offt < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + s->max_send_speed = offt; + /* use minimal burst rate of 32k. some protocol batch IO */ + Curl_rlimit_init(&data->progress.ul.rlimit, offt, + CURLMAX(offt, (32 * 1024)), + Curl_pgrs_now(data)); + break; + case CURLOPT_MAX_RECV_SPEED_LARGE: + /* + * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per + * second the transfer is throttled.. + */ + if(offt < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + s->max_recv_speed = offt; + /* use minimal burst rate of 32k. some protocol batch IO */ + Curl_rlimit_init(&data->progress.dl.rlimit, offt, + CURLMAX(offt, (32 * 1024)), + Curl_pgrs_now(data)); + break; + case CURLOPT_RESUME_FROM_LARGE: + /* + * Resume transfer at the given file position + */ + if(offt < -1) + return CURLE_BAD_FUNCTION_ARGUMENT; + s->set_resume_from = offt; + break; + case CURLOPT_MAXFILESIZE_LARGE: + /* + * Set the maximum size of a file to download. + */ + if(offt < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + s->max_filesize = offt; + break; + + default: + return CURLE_UNKNOWN_OPTION; + } + return CURLE_OK; +} + +static CURLcode setopt_blob(struct Curl_easy *data, CURLoption option, + struct curl_blob *blob) +{ + struct UserDefined *s = &data->set; + switch(option) { + case CURLOPT_SSLCERT_BLOB: + /* + * Blob that holds file content of the SSL certificate to use + */ + return Curl_setblobopt(&s->blobs[BLOB_CERT], blob); +#ifndef CURL_DISABLE_PROXY + case CURLOPT_PROXY_SSLCERT_BLOB: + /* + * Blob that holds file content of the SSL certificate to use for proxy + */ + return Curl_setblobopt(&s->blobs[BLOB_CERT_PROXY], blob); + case CURLOPT_PROXY_SSLKEY_BLOB: + /* + * Blob that holds file content of the SSL key to use for proxy + */ + return Curl_setblobopt(&s->blobs[BLOB_KEY_PROXY], blob); + case CURLOPT_PROXY_CAINFO_BLOB: + /* + * Blob that holds CA info for SSL connection proxy. + * Specify entire PEM of the CA certificate + */ +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_CAINFO_BLOB)) { + CURLcode result = Curl_setblobopt(&s->blobs[BLOB_CAINFO_PROXY], blob); + s->proxy_ssl.custom_cablob = !!s->blobs[BLOB_CAINFO_PROXY]; + return result; + } +#endif + return CURLE_NOT_BUILT_IN; + case CURLOPT_PROXY_ISSUERCERT_BLOB: + /* + * Blob that holds Issuer certificate to check certificates issuer + */ + if(Curl_ssl_supports(data, SSLSUPP_ISSUERCERT_BLOB)) + return Curl_setblobopt(&s->blobs[BLOB_SSL_ISSUERCERT_PROXY], blob); + return CURLE_NOT_BUILT_IN; +#endif + case CURLOPT_SSLKEY_BLOB: + /* + * Blob that holds file content of the SSL key to use + */ + return Curl_setblobopt(&s->blobs[BLOB_KEY], blob); + case CURLOPT_CAINFO_BLOB: + /* + * Blob that holds CA info for SSL connection. + * Specify entire PEM of the CA certificate + */ +#ifdef USE_SSL + if(Curl_ssl_supports(data, SSLSUPP_CAINFO_BLOB)) { + CURLcode result = Curl_setblobopt(&s->blobs[BLOB_CAINFO], blob); + s->ssl.custom_cablob = !!s->blobs[BLOB_CAINFO]; + return result; + } +#endif + return CURLE_NOT_BUILT_IN; + case CURLOPT_ISSUERCERT_BLOB: + /* + * Blob that holds Issuer certificate to check certificates issuer + */ + if(Curl_ssl_supports(data, SSLSUPP_ISSUERCERT_BLOB)) + return Curl_setblobopt(&s->blobs[BLOB_SSL_ISSUERCERT], blob); + return CURLE_NOT_BUILT_IN; + + default: + return CURLE_UNKNOWN_OPTION; + } + /* unreachable */ +} + +/* + * Do not make Curl_vsetopt() static: it is called from + * projects/OS400/ccsidcurl.c. + */ +CURLcode Curl_vsetopt(struct Curl_easy *data, CURLoption option, va_list param) +{ + if(option < CURLOPTTYPE_OBJECTPOINT) + return setopt_long(data, option, va_arg(param, long)); + else if(option < CURLOPTTYPE_FUNCTIONPOINT) { + /* unfortunately, different pointer types cannot be identified any other + way than being listed explicitly */ + switch(option) { + case CURLOPT_HTTPHEADER: + case CURLOPT_QUOTE: + case CURLOPT_POSTQUOTE: + case CURLOPT_TELNETOPTIONS: + case CURLOPT_PREQUOTE: + case CURLOPT_HTTP200ALIASES: + case CURLOPT_MAIL_RCPT: + case CURLOPT_RESOLVE: + case CURLOPT_PROXYHEADER: + case CURLOPT_CONNECT_TO: + return setopt_slist(data, option, va_arg(param, struct curl_slist *)); + case CURLOPT_HTTPPOST: /* curl_httppost * */ + case CURLOPT_MIMEPOST: /* curl_mime * */ + case CURLOPT_STDERR: /* FILE * */ + case CURLOPT_SHARE: /* CURLSH * */ + case CURLOPT_CURLU: /* CURLU * */ + return setopt_pointers(data, option, param); + case CURLOPT_STREAM_DEPENDS: /* CURL * */ + case CURLOPT_STREAM_DEPENDS_E: /* CURL * */ + return CURLE_OK; + default: + break; + } + /* the char pointer options */ + return setopt_cptr(data, option, va_arg(param, char *)); + } + else if(option < CURLOPTTYPE_OFF_T) + return setopt_func(data, option, param); + else if(option < CURLOPTTYPE_BLOB) + return setopt_offt(data, option, va_arg(param, curl_off_t)); + return setopt_blob(data, option, va_arg(param, struct curl_blob *)); +} + +/* + * curl_easy_setopt() is the external interface for setting options on an + * easy handle. + * + * NOTE: This is one of few API functions that are allowed to be called from + * within a callback. + */ +#undef curl_easy_setopt +CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...) +{ + struct Curl_eapi_guard guard; + CURLcode result; + + if(CURL_EAPI_ENTER(&guard, curl, easy_setopt, &result)) { + struct Curl_easy *data = curl; + va_list arg; + + va_start(arg, option); + + result = Curl_vsetopt(data, option, arg); + + va_end(arg); + if(result == CURLE_BAD_FUNCTION_ARGUMENT) + failf(data, "setopt 0x%x got bad argument", (unsigned int)option); + } + CURL_EAPI_LEAVE(&guard); + return result; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/setopt.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/setopt.h new file mode 100644 index 0000000000..e386262f88 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/setopt.h @@ -0,0 +1,41 @@ +#ifndef HEADER_CURL_SETOPT_H +#define HEADER_CURL_SETOPT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifdef USE_SSL +CURLcode Curl_setopt_SSLVERSION(struct Curl_easy *data, CURLoption option, + long arg); +#else +#define Curl_setopt_SSLVERSION(a, b, c) CURLE_NOT_BUILT_IN +#endif + +CURLcode Curl_setstropt(struct Curl_easy *data, + enum dupstring id, const char *s) WARN_UNUSED_RESULT; +CURLcode Curl_setblobopt(struct curl_blob **blobp, + const struct curl_blob *blob) WARN_UNUSED_RESULT; +CURLcode Curl_vsetopt(struct Curl_easy *data, CURLoption option, va_list param) + WARN_UNUSED_RESULT; + +#endif /* HEADER_CURL_SETOPT_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/setup-os400.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/setup-os400.h new file mode 100644 index 0000000000..b5bd733672 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/setup-os400.h @@ -0,0 +1,147 @@ +#ifndef HEADER_CURL_SETUP_OS400_H +#define HEADER_CURL_SETUP_OS400_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* OS/400 netdb.h does not define NI_MAXHOST. */ +#define NI_MAXHOST 1025 + +/* OS/400 netdb.h does not define NI_MAXSERV. */ +#define NI_MAXSERV 32 + +/* OS/400 has no idea of a tty! */ +#define isatty(fd) 0 + +/* Workaround bug in IBM QADRT runtime library: + * function puts() does not output the implicit trailing newline. + */ + +#include <stdio.h> /* Be sure it is loaded. */ +#undef puts +#define puts(s) (fputs(s, stdout) == EOF ? EOF : putchar('\n')) + +/* System API wrapper prototypes & definitions to support ASCII parameters. */ + +#include <sys/socket.h> +#include <netdb.h> +#include <gskssl.h> +#include <qsoasync.h> +#include <gssapi.h> + +#ifdef BUILDING_LIBCURL + +extern int Curl_getaddrinfo_a(const char *nodename, + const char *servname, + const struct addrinfo *hints, + struct addrinfo **res); +#define getaddrinfo Curl_getaddrinfo_a + +/* Note socklen_t must be used as this is declared before curl_socklen_t */ +extern int Curl_getnameinfo_a(const struct sockaddr *sa, + socklen_t salen, + char *nodename, socklen_t nodenamelen, + char *servname, socklen_t servnamelen, + int flags); +#define getnameinfo Curl_getnameinfo_a + +/* GSSAPI wrappers. */ + +extern OM_uint32 Curl_gss_import_name_a(OM_uint32 *minor_status, + gss_buffer_t in_name, + gss_OID in_name_type, + gss_name_t *out_name); +#define gss_import_name Curl_gss_import_name_a + +extern OM_uint32 Curl_gss_display_status_a(OM_uint32 *minor_status, + OM_uint32 status_value, + int status_type, gss_OID mech_type, + gss_msg_ctx_t *message_context, + gss_buffer_t status_string); +#define gss_display_status Curl_gss_display_status_a + +extern OM_uint32 Curl_gss_init_sec_context_a(OM_uint32 *minor_status, + gss_cred_id_t cred_handle, + gss_ctx_id_t *context_handle, + gss_name_t target_name, + gss_OID mech_type, + gss_flags_t req_flags, + OM_uint32 time_req, + gss_channel_bindings_t + input_chan_bindings, + gss_buffer_t input_token, + gss_OID *actual_mech_type, + gss_buffer_t output_token, + gss_flags_t *ret_flags, + OM_uint32 *time_rec); +#define gss_init_sec_context Curl_gss_init_sec_context_a + +extern OM_uint32 Curl_gss_delete_sec_context_a(OM_uint32 *minor_status, + gss_ctx_id_t *context_handle, + gss_buffer_t output_token); +#define gss_delete_sec_context Curl_gss_delete_sec_context_a + +/* LDAP wrappers. */ + +#define BerValue struct berval + +#define ldap_url_parse ldap_url_parse_utf8 +#define ldap_init Curl_ldap_init_a +#define ldap_simple_bind_s Curl_ldap_simple_bind_s_a +#define ldap_search_s Curl_ldap_search_s_a +#define ldap_get_values_len Curl_ldap_get_values_len_a +#define ldap_err2string Curl_ldap_err2string_a +#define ldap_get_dn Curl_ldap_get_dn_a +#define ldap_first_attribute Curl_ldap_first_attribute_a +#define ldap_next_attribute Curl_ldap_next_attribute_a + +/* Some socket functions must be wrapped to process textual addresses + like AF_UNIX. */ + +extern int Curl_os400_connect(int sd, struct sockaddr *destaddr, int addrlen); +extern int Curl_os400_bind(int sd, struct sockaddr *localaddr, int addrlen); +extern int Curl_os400_sendto(int sd, char *buffer, int buflen, int flags, + const struct sockaddr *dstaddr, int addrlen); +extern int Curl_os400_recvfrom(int sd, char *buffer, int buflen, int flags, + struct sockaddr *fromaddr, int *addrlen); +extern int Curl_os400_getpeername(int sd, struct sockaddr *addr, int *addrlen); +extern int Curl_os400_getsockname(int sd, struct sockaddr *addr, int *addrlen); + +#define connect Curl_os400_connect +#define bind Curl_os400_bind +#define sendto Curl_os400_sendto +#define recvfrom Curl_os400_recvfrom +#define getpeername Curl_os400_getpeername +#define getsockname Curl_os400_getsockname + +#ifdef HAVE_LIBZ +#define zlibVersion Curl_os400_zlibVersion +#define inflateInit_ Curl_os400_inflateInit_ +#define inflateInit2_ Curl_os400_inflateInit2_ +#define inflate Curl_os400_inflate +#define inflateEnd Curl_os400_inflateEnd +#endif + +#endif /* BUILDING_LIBCURL */ + +#endif /* HEADER_CURL_SETUP_OS400_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/setup-vms.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/setup-vms.h new file mode 100644 index 0000000000..35d12f0b42 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/setup-vms.h @@ -0,0 +1,396 @@ +#ifndef HEADER_CURL_SETUP_VMS_H +#define HEADER_CURL_SETUP_VMS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* JEM, 2012-12-30, VMS now generates config.h, so only define wrappers for */ +/* getenv(), getpwuid() and provide is_vms_shell() */ +/* Also need upper case symbols for system services, and */ +/* OpenSSL, and some Kerberos image */ + +#ifdef __DECC +#pragma message save +#pragma message disable dollarid +#endif + +/* Hide the stuff we are overriding */ +#define getenv decc_getenv +#ifdef __DECC +# if __INITIAL_POINTER_SIZE != 64 +# define getpwuid decc_getpwuid +# endif +#endif +#include <stdlib.h> +char *decc$getenv(const char *__name); +#include <pwd.h> + +#include <string.h> +#include <unixlib.h> + +#undef getenv +#undef getpwuid +#define getenv vms_getenv +#define getpwuid vms_getpwuid + +/* VAX needs these in upper case when compiling exact case */ +#define sys$assign SYS$ASSIGN +#define sys$dassgn SYS$DASSGN +#define sys$qiow SYS$QIOW + +#ifdef __DECC +# if __INITIAL_POINTER_SIZE +# pragma __pointer_size __save +# endif +#endif + +#if __USE_LONG_GID_T +# define decc_getpwuid DECC$__LONG_GID_GETPWUID +#else +# if __INITIAL_POINTER_SIZE +# define decc_getpwuid decc$__32_getpwuid +# else +# define decc_getpwuid decc$getpwuid +# endif +#endif + +struct passwd *decc_getpwuid(uid_t uid); + +#ifdef __DECC +# if __INITIAL_POINTER_SIZE == 32 +/* Translate the path, but only if the path is a VMS file specification */ +/* The translation is usually only needed for older versions of VMS */ +static char *vms_translate_path(const char *path) +{ + char *unix_path; + char *test_str; + + /* See if the result is in VMS format, if not, we are done */ + /* Assume that this is a PATH, not some data */ + test_str = strpbrk(path, ":[<^"); + if(!test_str) { + return (char *)path; + } + + unix_path = decc$translate_vms(path); + + if((int)unix_path <= 0) { + /* We can not translate it, so return the original string */ + return (char *)path; + } +} +# else + /* VMS translate path is actually not needed on the current 64-bit */ + /* VMS platforms, so instead of figuring out the pointer settings */ + /* Change it to a noop */ +# define vms_translate_path(__path) __path +# endif +#endif + +#ifdef __DECC +# if __INITIAL_POINTER_SIZE +# pragma __pointer_size __restore +# endif +#endif + +static char *vms_getenv(const char *envvar) +{ + char *result; + char *vms_path; + + /* first use the DECC getenv() function */ + result = decc$getenv(envvar); + if(!result) { + return result; + } + + vms_path = result; + result = vms_translate_path(vms_path); + + /* note that if you backport this to use VAX C RTL, that the VAX C RTL */ + /* may do a malloc(2048) for each call to getenv(), so you will need */ + /* to add a free(vms_path) */ + /* Do not do a free() for DEC C RTL builds, which should be used for */ + /* VMS 5.5-2 and later, even if using GCC */ + + return result; +} + +static struct passwd vms_passwd_cache; + +static struct passwd *vms_getpwuid(uid_t uid) +{ + struct passwd *my_passwd; + +/* Hack needed to support 64-bit builds, decc_getpwnam is 32-bit only */ +#ifdef __DECC +# if __INITIAL_POINTER_SIZE + __char_ptr32 unix_path; +# else + char *unix_path; +# endif +#else + char *unix_path; +#endif + + my_passwd = decc_getpwuid(uid); + if(!my_passwd) { + return my_passwd; + } + + unix_path = vms_translate_path(my_passwd->pw_dir); + + if((long)unix_path <= 0) { + /* We can not translate it, so return the original string */ + return my_passwd; + } + + /* If no changes needed, return it */ + if(unix_path == my_passwd->pw_dir) { + return my_passwd; + } + + /* Need to copy the structure returned */ + /* Since curl is only using pw_dir, no need to fix up */ + /* the pw_shell when running under Bash */ + vms_passwd_cache.pw_name = my_passwd->pw_name; + vms_passwd_cache.pw_uid = my_passwd->pw_uid; + vms_passwd_cache.pw_gid = my_passwd->pw_uid; + vms_passwd_cache.pw_dir = unix_path; + vms_passwd_cache.pw_shell = my_passwd->pw_shell; + + return &vms_passwd_cache; +} + +#ifdef __DECC +#pragma message restore +#endif + +/* Bug - VMS OpenSSL and Kerberos universal symbols are in uppercase only */ +/* VMS libraries should have universal symbols in exact and uppercase */ + +#define ASN1_INTEGER_get ASN1_INTEGER_GET +#define ASN1_STRING_data ASN1_STRING_DATA +#define ASN1_STRING_length ASN1_STRING_LENGTH +#define ASN1_STRING_print ASN1_STRING_PRINT +#define ASN1_STRING_to_UTF8 ASN1_STRING_TO_UTF8 +#define ASN1_STRING_type ASN1_STRING_TYPE +#define BIO_ctrl BIO_CTRL +#define BIO_free BIO_FREE +#define BIO_new BIO_NEW +#define BIO_s_mem BIO_S_MEM +#define BN_bn2bin BN_BN2BIN +#define BN_num_bits BN_NUM_BITS +#define CRYPTO_cleanup_all_ex_data CRYPTO_CLEANUP_ALL_EX_DATA +#define CRYPTO_free CRYPTO_FREE +#define CRYPTO_malloc CRYPTO_MALLOC +#define CONF_modules_load_file CONF_MODULES_LOAD_FILE +#ifdef __VAX +# ifdef VMS_OLD_SSL + /* Ancient OpenSSL on VAX/VMS missing this constant */ +# define CONF_MFLAGS_IGNORE_MISSING_FILE 0x10 +# undef CONF_modules_load_file +static int CONF_modules_load_file(const char *filename, + const char *appname, + unsigned long flags) { + return 1; +} +# endif +#endif +#define DES_ecb_encrypt DES_ECB_ENCRYPT +#define DES_set_key DES_SET_KEY +#define DES_set_odd_parity DES_SET_ODD_PARITY +#define ENGINE_ctrl ENGINE_CTRL +#define ENGINE_ctrl_cmd ENGINE_CTRL_CMD +#define ENGINE_finish ENGINE_FINISH +#define ENGINE_free ENGINE_FREE +#define ENGINE_get_first ENGINE_GET_FIRST +#define ENGINE_get_id ENGINE_GET_ID +#define ENGINE_get_next ENGINE_GET_NEXT +#define ENGINE_init ENGINE_INIT +#define ENGINE_load_builtin_engines ENGINE_LOAD_BUILTIN_ENGINES +#define ENGINE_load_private_key ENGINE_LOAD_PRIVATE_KEY +#define ENGINE_set_default ENGINE_SET_DEFAULT +#define ERR_clear_error ERR_CLEAR_ERROR +#define ERR_error_string ERR_ERROR_STRING +#define ERR_error_string_n ERR_ERROR_STRING_N +#define ERR_free_strings ERR_FREE_STRINGS +#define ERR_get_error ERR_GET_ERROR +#define ERR_peek_error ERR_PEEK_ERROR +#define ERR_remove_state ERR_REMOVE_STATE +#define EVP_PKEY_copy_parameters EVP_PKEY_COPY_PARAMETERS +#define EVP_PKEY_free EVP_PKEY_FREE +#define EVP_cleanup EVP_CLEANUP +#define GENERAL_NAMES_free GENERAL_NAMES_FREE +#define i2d_X509_PUBKEY I2D_X509_PUBKEY +#define MD4_Final MD4_FINAL +#define MD4_Init MD4_INIT +#define MD4_Update MD4_UPDATE +#define MD5_Final MD5_FINAL +#define MD5_Init MD5_INIT +#define MD5_Update MD5_UPDATE +#define OPENSSL_add_all_algo_noconf OPENSSL_ADD_ALL_ALGO_NOCONF +#ifndef __VAX +#define OPENSSL_load_builtin_modules OPENSSL_LOAD_BUILTIN_MODULES +#endif +#define PEM_read_X509 PEM_READ_X509 +#define PEM_write_bio_X509 PEM_WRITE_BIO_X509 +#define PKCS12_free PKCS12_FREE +#define PKCS12_parse PKCS12_PARSE +#define RAND_add RAND_ADD +#define RAND_bytes RAND_BYTES +#define RAND_file_name RAND_FILE_NAME +#define RAND_load_file RAND_LOAD_FILE +#define RAND_status RAND_STATUS +#define SSL_CIPHER_get_name SSL_CIPHER_GET_NAME +#define SSL_CTX_add_client_CA SSL_CTX_ADD_CLIENT_CA +#define SSL_CTX_callback_ctrl SSL_CTX_CALLBACK_CTRL +#define SSL_CTX_check_private_key SSL_CTX_CHECK_PRIVATE_KEY +#define SSL_CTX_ctrl SSL_CTX_CTRL +#define SSL_CTX_free SSL_CTX_FREE +#define SSL_CTX_get_cert_store SSL_CTX_GET_CERT_STORE +#define SSL_CTX_load_verify_locations SSL_CTX_LOAD_VERIFY_LOCATIONS +#define SSL_CTX_new SSL_CTX_NEW +#define SSL_CTX_set_cipher_list SSL_CTX_SET_CIPHER_LIST +#define SSL_CTX_set_def_passwd_cb_ud SSL_CTX_SET_DEF_PASSWD_CB_UD +#define SSL_CTX_set_default_passwd_cb SSL_CTX_SET_DEFAULT_PASSWD_CB +#define SSL_CTX_set_msg_callback SSL_CTX_SET_MSG_CALLBACK +#define SSL_CTX_set_verify SSL_CTX_SET_VERIFY +#define SSL_CTX_use_PrivateKey SSL_CTX_USE_PRIVATEKEY +#define SSL_CTX_use_PrivateKey_file SSL_CTX_USE_PRIVATEKEY_FILE +#define SSL_CTX_use_cert_chain_file SSL_CTX_USE_CERT_CHAIN_FILE +#define SSL_CTX_use_certificate SSL_CTX_USE_CERTIFICATE +#define SSL_CTX_use_certificate_file SSL_CTX_USE_CERTIFICATE_FILE +#define SSL_SESSION_free SSL_SESSION_FREE +#define SSL_connect SSL_CONNECT +#define SSL_free SSL_FREE +#define SSL_get1_session SSL_GET1_SESSION +#define SSL_get_certificate SSL_GET_CERTIFICATE +#define SSL_get_current_cipher SSL_GET_CURRENT_CIPHER +#define SSL_get_error SSL_GET_ERROR +#define SSL_get_peer_cert_chain SSL_GET_PEER_CERT_CHAIN +#define SSL_get_peer_certificate SSL_GET_PEER_CERTIFICATE +#define SSL_get_privatekey SSL_GET_PRIVATEKEY +#define SSL_get_session SSL_GET_SESSION +#define SSL_get_shutdown SSL_GET_SHUTDOWN +#define SSL_get_verify_result SSL_GET_VERIFY_RESULT +#define SSL_library_init SSL_LIBRARY_INIT +#define SSL_load_error_strings SSL_LOAD_ERROR_STRINGS +#define SSL_new SSL_NEW +#define SSL_peek SSL_PEEK +#define SSL_pending SSL_PENDING +#define SSL_read SSL_READ +#define SSL_set_connect_state SSL_SET_CONNECT_STATE +#define SSL_set_fd SSL_SET_FD +#define SSL_set_session SSL_SET_SESSION +#define SSL_shutdown SSL_SHUTDOWN +#define SSL_version SSL_VERSION +#define SSL_write SSL_WRITE +#define SSLeay SSLEAY +#define SSLv23_client_method SSLV23_CLIENT_METHOD +#define SSLv3_client_method SSLV3_CLIENT_METHOD +#define TLSv1_client_method TLSV1_CLIENT_METHOD +#define UI_create_method UI_CREATE_METHOD +#define UI_destroy_method UI_DESTROY_METHOD +#define UI_get0_user_data UI_GET0_USER_DATA +#define UI_get_input_flags UI_GET_INPUT_FLAGS +#define UI_get_string_type UI_GET_STRING_TYPE +#define UI_create_method UI_CREATE_METHOD +#define UI_destroy_method UI_DESTROY_METHOD +#define UI_method_get_closer UI_METHOD_GET_CLOSER +#define UI_method_get_opener UI_METHOD_GET_OPENER +#define UI_method_get_reader UI_METHOD_GET_READER +#define UI_method_get_writer UI_METHOD_GET_WRITER +#define UI_method_set_closer UI_METHOD_SET_CLOSER +#define UI_method_set_opener UI_METHOD_SET_OPENER +#define UI_method_set_reader UI_METHOD_SET_READER +#define UI_method_set_writer UI_METHOD_SET_WRITER +#define UI_OpenSSL UI_OPENSSL +#define UI_set_result UI_SET_RESULT +#define X509V3_EXT_print X509V3_EXT_PRINT +#define X509_EXTENSION_get_critical X509_EXTENSION_GET_CRITICAL +#define X509_EXTENSION_get_data X509_EXTENSION_GET_DATA +#define X509_EXTENSION_get_object X509_EXTENSION_GET_OBJECT +#define X509_LOOKUP_file X509_LOOKUP_FILE +#define X509_NAME_ENTRY_get_data X509_NAME_ENTRY_GET_DATA +#define X509_NAME_get_entry X509_NAME_GET_ENTRY +#define X509_NAME_get_index_by_NID X509_NAME_GET_INDEX_BY_NID +#define X509_NAME_print_ex X509_NAME_PRINT_EX +#define X509_STORE_CTX_get_current_cert X509_STORE_CTX_GET_CURRENT_CERT +#define X509_STORE_add_lookup X509_STORE_ADD_LOOKUP +#define X509_STORE_set_flags X509_STORE_SET_FLAGS +#define X509_check_issued X509_CHECK_ISSUED +#define X509_free X509_FREE +#define X509_get_ext_d2i X509_GET_EXT_D2I +#define X509_get_issuer_name X509_GET_ISSUER_NAME +#define X509_get_pubkey X509_GET_PUBKEY +#define X509_get_serialNumber X509_GET_SERIALNUMBER +#define X509_get_subject_name X509_GET_SUBJECT_NAME +#define X509_load_crl_file X509_LOAD_CRL_FILE +#define X509_verify_cert_error_string X509_VERIFY_CERT_ERROR_STRING +#define d2i_PKCS12_fp D2I_PKCS12_FP +#define i2t_ASN1_OBJECT I2T_ASN1_OBJECT +#define sk_num SK_NUM +#define sk_pop SK_POP +#define sk_pop_free SK_POP_FREE +#define sk_value SK_VALUE +#define SHA256_Final SHA256_FINAL +#define SHA256_Init SHA256_INIT +#define SHA256_Update SHA256_UPDATE + +#define USE_UPPERCASE_GSSAPI 1 +#define gss_seal GSS_SEAL +#define gss_unseal GSS_UNSEAL + +#define USE_UPPERCASE_KRBAPI 1 + +/* AI_NUMERICHOST needed for IP V6 support in curl */ +#ifdef HAVE_NETDB_H +#include <netdb.h> +#ifndef AI_NUMERICHOST +#undef USE_IPV6 +#endif +#endif + +/* VAX symbols are always in uppercase */ +#ifdef __VAX +#define inflate INFLATE +#define inflateEnd INFLATEEND +#define inflateInit2_ INFLATEINIT2_ +#define inflateInit_ INFLATEINIT_ +#define zlibVersion ZLIBVERSION +#endif + +/* Older VAX OpenSSL port defines these as Macros */ +/* Need to include the headers first and then redefine */ +/* that way a newer port will also work if some one has one */ +#ifdef __VAX + +# include <openssl/evp.h> +# ifndef OpenSSL_add_all_algorithms +# define OpenSSL_add_all_algorithms OPENSSL_ADD_ALL_ALGORITHMS + void OPENSSL_ADD_ALL_ALGORITHMS(void); +# endif +#endif + +#endif /* HEADER_CURL_SETUP_VMS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/setup-win32.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/setup-win32.h new file mode 100644 index 0000000000..6a89b966de --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/setup-win32.h @@ -0,0 +1,110 @@ +#ifndef HEADER_CURL_SETUP_WIN32_H +#define HEADER_CURL_SETUP_WIN32_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#undef USE_WINSOCK +/* ---------------------------------------------------------------- */ +/* Watt-32 TCP/IP SPECIFIC */ +/* ---------------------------------------------------------------- */ +#ifdef USE_WATT32 +# include <tcp.h> +# include <sys/socket.h> +# undef byte +# undef word +# define HAVE_SYS_IOCTL_H +# define HAVE_NETINET_IN_H +# define HAVE_NETDB_H +# define HAVE_ARPA_INET_H +# define SOCKET int +/* ---------------------------------------------------------------- */ +/* BSD-style lwIP TCP/IP stack SPECIFIC */ +/* ---------------------------------------------------------------- */ +#elif defined(USE_LWIPSOCK) + /* Define to use BSD-style lwIP TCP/IP stack. */ + /* #define USE_LWIPSOCK 1 */ +# undef HAVE_GETHOSTNAME +# define HAVE_GETHOSTBYNAME_R +# define HAVE_GETHOSTBYNAME_R_6 +# undef LWIP_POSIX_SOCKETS_IO_NAMES +# define LWIP_POSIX_SOCKETS_IO_NAMES 0 +# undef RECV_TYPE_ARG1 +# define RECV_TYPE_ARG1 int +# undef RECV_TYPE_ARG3 +# define RECV_TYPE_ARG3 size_t +# undef SEND_TYPE_ARG1 +# define SEND_TYPE_ARG1 int +# undef SEND_TYPE_ARG3 +# define SEND_TYPE_ARG3 size_t +#elif defined(_WIN32) +# define USE_WINSOCK 2 +# include <winsock2.h> +# include <ws2tcpip.h> +#endif + +/* + * Include header files for Windows builds before redefining anything. Use + * this preprocessor block only to include or exclude windows.h, winsock2.h or + * ws2tcpip.h. Any other Windows thing belongs to any other further and + * independent block. Under Cygwin things work as under Linux (e.g. + * <sys/socket.h>) and the Winsock headers should never be included when + * __CYGWIN__ is defined. + */ +#ifdef _WIN32 +# if defined(UNICODE) && !defined(_UNICODE) +# error "UNICODE is defined but _UNICODE is not defined" +# endif +# if defined(_UNICODE) && !defined(UNICODE) +# error "_UNICODE is defined but UNICODE is not defined" +# endif +# include <windows.h> +# include <winerror.h> +# include <tchar.h> +#endif + +/* + * Define _WIN32_WINNT_[OS] symbols because not all Windows build systems have + * those symbols to compare against, and even those that do may be missing + * newer symbols. + */ +#ifndef _WIN32_WINNT_VISTA +#define _WIN32_WINNT_VISTA 0x0600 /* Windows Vista */ +#endif +#ifndef _WIN32_WINNT_WS08 +#define _WIN32_WINNT_WS08 0x0600 /* Windows Server 2008 */ +#endif +#ifndef _WIN32_WINNT_WIN7 +#define _WIN32_WINNT_WIN7 0x0601 /* Windows 7 */ +#endif +#ifndef _WIN32_WINNT_WIN8 +#define _WIN32_WINNT_WIN8 0x0602 /* Windows 8 */ +#endif +#ifndef _WIN32_WINNT_WINBLUE +#define _WIN32_WINNT_WINBLUE 0x0603 /* Windows 8.1 */ +#endif +#ifndef _WIN32_WINNT_WIN10 +#define _WIN32_WINNT_WIN10 0x0A00 /* Windows 10 */ +#endif + +#endif /* HEADER_CURL_SETUP_WIN32_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/sha256.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/sha256.c new file mode 100644 index 0000000000..89b96017bd --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/sha256.c @@ -0,0 +1,512 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Florin Petriuc, <petriuc.florin@gmail.com> + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_AWS) || !defined(CURL_DISABLE_DIGEST_AUTH) || \ + defined(USE_LIBSSH2) || defined(USE_SSL) + +#include "curl_sha256.h" + +#ifdef USE_MBEDTLS +#include <mbedtls/version.h> +#if MBEDTLS_VERSION_NUMBER < 0x03020000 +#error "mbedTLS 3.2.0 or greater required" +#endif +#include <psa/crypto_config.h> +#endif + +/* Please keep the SSL backend-specific #if branches in this order: + * + * 1. USE_OPENSSL + * 2. USE_WOLFSSL + * 3. USE_GNUTLS + * 4. USE_MBEDTLS + * 5. USE_WIN32_CRYPTO + * 6. USE_COMMON_CRYPTO + * + * This ensures that the same SSL branch gets activated throughout this source + * file even if multiple backends are enabled at the same time. + */ + +#ifdef USE_OPENSSL +#include <openssl/evp.h> + +struct ossl_sha256_ctx { + EVP_MD_CTX *openssl_ctx; +}; +typedef struct ossl_sha256_ctx my_sha256_ctx; + +static CURLcode my_sha256_init(void *in) +{ + my_sha256_ctx *ctx = (my_sha256_ctx *)in; + ctx->openssl_ctx = EVP_MD_CTX_new(); + if(!ctx->openssl_ctx) + return CURLE_OUT_OF_MEMORY; + + if(!EVP_DigestInit_ex(ctx->openssl_ctx, EVP_sha256(), NULL)) { + EVP_MD_CTX_free(ctx->openssl_ctx); + return CURLE_FAILED_INIT; + } + return CURLE_OK; +} + +static void my_sha256_update(void *in, + const unsigned char *data, + unsigned int length) +{ + my_sha256_ctx *ctx = (my_sha256_ctx *)in; + EVP_DigestUpdate(ctx->openssl_ctx, data, length); +} + +static void my_sha256_final(unsigned char *digest, void *in) +{ + my_sha256_ctx *ctx = (my_sha256_ctx *)in; + EVP_DigestFinal_ex(ctx->openssl_ctx, digest, NULL); + EVP_MD_CTX_free(ctx->openssl_ctx); +} + +#elif defined(USE_WOLFSSL) +#include <wolfssl/options.h> +#include <wolfssl/wolfcrypt/sha256.h> + +typedef struct wc_Sha256 my_sha256_ctx; + +static CURLcode my_sha256_init(void *in) +{ + if(wc_InitSha256(in)) + return CURLE_FAILED_INIT; + return CURLE_OK; +} + +static void my_sha256_update(void *in, + const unsigned char *data, + unsigned int length) +{ + (void)wc_Sha256Update(in, data, (word32)length); +} + +static void my_sha256_final(unsigned char *digest, void *in) +{ + (void)wc_Sha256Final(in, digest); +} + +#elif defined(USE_GNUTLS) +#include <nettle/sha2.h> +#include <nettle/version.h> + +typedef struct sha256_ctx my_sha256_ctx; + +static CURLcode my_sha256_init(void *ctx) +{ + sha256_init(ctx); + return CURLE_OK; +} + +static void my_sha256_update(void *ctx, + const unsigned char *data, + unsigned int length) +{ + sha256_update(ctx, length, data); +} + +static void my_sha256_final(unsigned char *digest, void *ctx) +{ +#if NETTLE_VERSION_MAJOR >= 4 + sha256_digest(ctx, digest); +#else + sha256_digest(ctx, SHA256_DIGEST_SIZE, digest); +#endif +} + +#elif defined(USE_MBEDTLS) && \ + defined(PSA_WANT_ALG_SHA_256) && PSA_WANT_ALG_SHA_256 +#include <psa/crypto.h> + +typedef psa_hash_operation_t my_sha256_ctx; + +static CURLcode my_sha256_init(void *ctx) +{ + psa_hash_operation_t *pctx = (psa_hash_operation_t *)ctx; + *pctx = psa_hash_operation_init(); + if(psa_hash_setup(pctx, PSA_ALG_SHA_256) != PSA_SUCCESS) + return CURLE_OUT_OF_MEMORY; + return CURLE_OK; +} + +static void my_sha256_update(void *ctx, + const unsigned char *data, + unsigned int length) +{ + (void)psa_hash_update(ctx, data, length); +} + +static void my_sha256_final(unsigned char *digest, void *ctx) +{ + size_t actual_length; + (void)psa_hash_finish(ctx, digest, CURL_SHA256_DIGEST_LENGTH, + &actual_length); +} + +#elif (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \ + (__MAC_OS_X_VERSION_MAX_ALLOWED >= 1040)) || \ + (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ + (__IPHONE_OS_VERSION_MAX_ALLOWED >= 20000)) +#include <CommonCrypto/CommonDigest.h> + +typedef CC_SHA256_CTX my_sha256_ctx; + +static CURLcode my_sha256_init(void *ctx) +{ + (void)CC_SHA256_Init(ctx); + return CURLE_OK; +} + +static void my_sha256_update(void *ctx, + const unsigned char *data, + unsigned int length) +{ + (void)CC_SHA256_Update(ctx, data, length); +} + +static void my_sha256_final(unsigned char *digest, void *ctx) +{ + (void)CC_SHA256_Final(digest, ctx); +} + +#elif defined(USE_WIN32_CRYPTO) +#include <wincrypt.h> + +struct sha256_ctx { + HCRYPTPROV hCryptProv; + HCRYPTHASH hHash; +}; +typedef struct sha256_ctx my_sha256_ctx; + +static CURLcode my_sha256_init(void *in) +{ + my_sha256_ctx *ctx = (my_sha256_ctx *)in; + if(!CryptAcquireContext(&ctx->hCryptProv, NULL, NULL, PROV_RSA_AES, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + return CURLE_OUT_OF_MEMORY; + + if(!CryptCreateHash(ctx->hCryptProv, CALG_SHA_256, 0, 0, &ctx->hHash)) { + CryptReleaseContext(ctx->hCryptProv, 0); + ctx->hCryptProv = 0; + return CURLE_FAILED_INIT; + } + + return CURLE_OK; +} + +static void my_sha256_update(void *in, + const unsigned char *data, + unsigned int length) +{ + my_sha256_ctx *ctx = (my_sha256_ctx *)in; + CryptHashData(ctx->hHash, (const BYTE *)data, length, 0); +} + +static void my_sha256_final(unsigned char *digest, void *in) +{ + my_sha256_ctx *ctx = (my_sha256_ctx *)in; + unsigned long length = 0; + + CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0); + if(length == CURL_SHA256_DIGEST_LENGTH) + CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &length, 0); + + if(ctx->hHash) + CryptDestroyHash(ctx->hHash); + + if(ctx->hCryptProv) + CryptReleaseContext(ctx->hCryptProv, 0); +} + +#else + +/* When no other crypto library is available we use this code segment */ + +/* This is based on the SHA256 implementation in LibTomCrypt that was released + * into public domain. */ + +#define WPA_GET_BE32(a) \ + ((((unsigned long)(a)[0]) << 24) | \ + (((unsigned long)(a)[1]) << 16) | \ + (((unsigned long)(a)[2]) << 8) | \ + ((unsigned long)(a)[3])) +#define WPA_PUT_BE32(a, val) \ + do { \ + (a)[0] = (unsigned char)((((unsigned long)(val)) >> 24) & 0xff); \ + (a)[1] = (unsigned char)((((unsigned long)(val)) >> 16) & 0xff); \ + (a)[2] = (unsigned char)((((unsigned long)(val)) >> 8) & 0xff); \ + (a)[3] = (unsigned char)(((unsigned long)(val)) & 0xff); \ + } while(0) + +#define WPA_PUT_BE64(a, val) \ + do { \ + (a)[0] = (unsigned char)(((uint64_t)(val)) >> 56); \ + (a)[1] = (unsigned char)(((uint64_t)(val)) >> 48); \ + (a)[2] = (unsigned char)(((uint64_t)(val)) >> 40); \ + (a)[3] = (unsigned char)(((uint64_t)(val)) >> 32); \ + (a)[4] = (unsigned char)(((uint64_t)(val)) >> 24); \ + (a)[5] = (unsigned char)(((uint64_t)(val)) >> 16); \ + (a)[6] = (unsigned char)(((uint64_t)(val)) >> 8); \ + (a)[7] = (unsigned char)(((uint64_t)(val)) & 0xff); \ + } while(0) + +struct sha256_state { + uint64_t length; + unsigned long state[8], curlen; + unsigned char buf[64]; +}; +typedef struct sha256_state my_sha256_ctx; + +/* The K array */ +static const unsigned long K[64] = { + 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, + 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL, + 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, + 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, + 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL, + 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, + 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, + 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, + 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, + 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL, + 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, + 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, + 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL +}; + +/* Various logical functions */ +#define RORc(x, y) \ + (((((unsigned long)(x) & 0xFFFFFFFFUL) >> (unsigned long)((y) & 31)) | \ + ((unsigned long)(x) << (unsigned long)(32 - ((y) & 31)))) & 0xFFFFFFFFUL) + +#define Sha256_Ch(x, y, z) (z ^ (x & (y ^ z))) +#define Sha256_Maj(x, y, z) (((x | y) & z) | (x & y)) +#define Sha256_S(x, n) RORc(x, n) +#define Sha256_R(x, n) (((x) & 0xFFFFFFFFUL) >> (n)) + +#define Sigma0(x) (Sha256_S(x, 2) ^ Sha256_S(x, 13) ^ Sha256_S(x, 22)) +#define Sigma1(x) (Sha256_S(x, 6) ^ Sha256_S(x, 11) ^ Sha256_S(x, 25)) +#define Gamma0(x) (Sha256_S(x, 7) ^ Sha256_S(x, 18) ^ Sha256_R(x, 3)) +#define Gamma1(x) (Sha256_S(x, 17) ^ Sha256_S(x, 19) ^ Sha256_R(x, 10)) + +/* Compress 512 bits */ +static int sha256_compress(struct sha256_state *md, const unsigned char *buf) +{ + unsigned long S[8], W[64]; + int i; + + /* Copy state into S */ + for(i = 0; i < 8; i++) { + S[i] = md->state[i]; + } + /* copy the state into 512 bits into W[0..15] */ + for(i = 0; i < 16; i++) + W[i] = WPA_GET_BE32(buf + (4 * i)); + /* fill W[16..63] */ + for(i = 16; i < 64; i++) { + W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; + } + + /* Compress */ +#define RND(a, b, c, d, e, f, g, h, i) \ + do { \ + unsigned long t0 = h + Sigma1(e) + Sha256_Ch(e, f, g) + K[i] + W[i]; \ + unsigned long t1 = Sigma0(a) + Sha256_Maj(a, b, c); \ + d += t0; \ + h = t0 + t1; \ + } while(0) + + for(i = 0; i < 64; ++i) { + unsigned long t; + RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], i); + t = S[7]; + S[7] = S[6]; + S[6] = S[5]; + S[5] = S[4]; + S[4] = S[3]; + S[3] = S[2]; + S[2] = S[1]; + S[1] = S[0]; + S[0] = t; + } + + /* Feedback */ + for(i = 0; i < 8; i++) { + md->state[i] = md->state[i] + S[i]; + } + + return 0; +} + +/* Initialize the hash state */ +static CURLcode my_sha256_init(void *in) +{ + struct sha256_state *md = (struct sha256_state *)in; + md->curlen = 0; + md->length = 0; + md->state[0] = 0x6A09E667UL; + md->state[1] = 0xBB67AE85UL; + md->state[2] = 0x3C6EF372UL; + md->state[3] = 0xA54FF53AUL; + md->state[4] = 0x510E527FUL; + md->state[5] = 0x9B05688CUL; + md->state[6] = 0x1F83D9ABUL; + md->state[7] = 0x5BE0CD19UL; + + return CURLE_OK; +} + +/* Process a block of memory though the hash + @param md The hash state + @param in The data to hash + @param inlen The length of the data (octets) + */ +static void my_sha256_update(void *ctx, + const unsigned char *in, + unsigned int len) +{ + unsigned long inlen = len; + unsigned long n; + struct sha256_state *md = (struct sha256_state *)ctx; +#define CURL_SHA256_BLOCK_SIZE 64 + if(md->curlen > sizeof(md->buf)) + return; + while(inlen > 0) { + if(md->curlen == 0 && inlen >= CURL_SHA256_BLOCK_SIZE) { + if(sha256_compress(md, in) < 0) + return; + md->length += CURL_SHA256_BLOCK_SIZE * 8; + in += CURL_SHA256_BLOCK_SIZE; + inlen -= CURL_SHA256_BLOCK_SIZE; + } + else { + n = CURLMIN(inlen, (CURL_SHA256_BLOCK_SIZE - md->curlen)); + memcpy(md->buf + md->curlen, in, n); + md->curlen += n; + in += n; + inlen -= n; + if(md->curlen == CURL_SHA256_BLOCK_SIZE) { + if(sha256_compress(md, md->buf) < 0) + return; + md->length += 8 * CURL_SHA256_BLOCK_SIZE; + md->curlen = 0; + } + } + } +} + +/* Terminate the hash to get the digest + @param md The hash state + @param out [out] The destination of the hash (32 bytes) + @return 0 if successful + */ +static void my_sha256_final(unsigned char *out, void *ctx) +{ + struct sha256_state *md = ctx; + int i; + + if(md->curlen >= sizeof(md->buf)) + return; + + /* Increase the length of the message */ + md->length += md->curlen * 8; + + /* Append the '1' bit */ + md->buf[md->curlen++] = (unsigned char)0x80; + + /* If the length is currently above 56 bytes we append zeros + * then compress. Then we can fall back to padding zeros and length + * encoding like normal. + */ + if(md->curlen > 56) { + while(md->curlen < 64) { + md->buf[md->curlen++] = 0; + } + sha256_compress(md, md->buf); + md->curlen = 0; + } + + /* Pad up to 56 bytes of zeroes */ + while(md->curlen < 56) { + md->buf[md->curlen++] = 0; + } + + /* Store length */ + WPA_PUT_BE64(md->buf + 56, md->length); + sha256_compress(md, md->buf); + + /* Copy output */ + for(i = 0; i < 8; i++) + WPA_PUT_BE32(out + (4 * i), md->state[i]); +} + +#endif /* CRYPTO LIBS */ + +/* + * Curl_sha256it() + * + * Generates a SHA256 hash for the given input data. + * + * Parameters: + * + * output [in/out] - The output buffer. + * input [in] - The input data. + * length [in] - The input length. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_sha256it(unsigned char *output, const unsigned char *input, + size_t len) +{ + CURLcode result; + my_sha256_ctx ctx; + + result = my_sha256_init(&ctx); + if(!result) { + do { + unsigned int ilen = (unsigned int)CURLMIN(len, UINT_MAX); + my_sha256_update(&ctx, input, ilen); + len -= ilen; + input += ilen; + } while(len); + my_sha256_final(output, &ctx); + } + return result; +} + +const struct HMAC_params Curl_HMAC_SHA256 = { + my_sha256_init, /* Hash initialization function. */ + my_sha256_update, /* Hash update function. */ + my_sha256_final, /* Hash computation end function. */ + sizeof(my_sha256_ctx), /* Size of hash context structure. */ + 64, /* Maximum key length. */ + 32 /* Result size. */ +}; + +#endif /* AWS, DIGEST, or libssh2 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/sigpipe.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/sigpipe.h new file mode 100644 index 0000000000..b489796953 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/sigpipe.h @@ -0,0 +1,102 @@ +#ifndef HEADER_CURL_SIGPIPE_H +#define HEADER_CURL_SIGPIPE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(HAVE_SIGACTION) && !defined(USE_SO_NOSIGPIPE) +#include <signal.h> + +struct Curl_sigpipe_ctx { + struct sigaction old_pipe_act; + BIT(no_signal); +}; + +static CURL_INLINE void sigpipe_init(struct Curl_sigpipe_ctx *ig) +{ + memset(ig, 0, sizeof(*ig)); + ig->no_signal = TRUE; +} + +/* + * sigpipe_ignore() makes sure we ignore SIGPIPE while running libcurl + * internals, and then sigpipe_restore() will restore the situation when we + * return from libcurl again. + */ +static CURL_INLINE void sigpipe_ignore(struct Curl_easy *data, + struct Curl_sigpipe_ctx *ig) +{ + /* get a local copy of no_signal because the Curl_easy might not be + around when we restore */ + ig->no_signal = data->set.no_signal; + if(!data->set.no_signal) { + struct sigaction action; + /* first, extract the existing situation */ + sigaction(SIGPIPE, NULL, &ig->old_pipe_act); + action = ig->old_pipe_act; + /* ignore this signal */ + action.sa_handler = SIG_IGN; +#ifdef SA_SIGINFO + /* clear SA_SIGINFO flag since we are using sa_handler */ + action.sa_flags &= ~SA_SIGINFO; +#endif + sigaction(SIGPIPE, &action, NULL); + } +} + +/* + * sigpipe_restore() puts back the outside world's opinion of signal handler + * and SIGPIPE handling. It MUST only be called after a corresponding + * sigpipe_ignore() was used. + */ +static CURL_INLINE void sigpipe_restore(struct Curl_sigpipe_ctx *ig) +{ + if(!ig->no_signal) + /* restore the outside state */ + sigaction(SIGPIPE, &ig->old_pipe_act, NULL); +} + +static CURL_INLINE void sigpipe_apply(struct Curl_easy *data, + struct Curl_sigpipe_ctx *ig) +{ + if(data && (data->set.no_signal != ig->no_signal)) { + sigpipe_restore(ig); + sigpipe_ignore(data, ig); + } +} + +#else /* !HAVE_SIGACTION || USE_SO_NOSIGPIPE */ +/* for systems without sigaction or where SO_NOSIGPIPE is used. */ +#define sigpipe_ignore(x, y) do { (void)(x); (void)(y); } while(0) +#define sigpipe_apply(x, y) do { (void)(x); (void)(y); } while(0) +#define sigpipe_init(x) do { (void)(x); } while(0) +#define sigpipe_restore(x) do { (void)(x); } while(0) + +struct Curl_sigpipe_ctx { + bool dummy; +}; + +#endif /* else HAVE_SIGACTION && !USE_SO_NOSIGPIPE */ + +#endif /* HEADER_CURL_SIGPIPE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/slist.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/slist.c new file mode 100644 index 0000000000..83fd2918c6 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/slist.c @@ -0,0 +1,139 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "slist.h" + +/* returns last node in linked list */ +static struct curl_slist *slist_get_last(struct curl_slist *list) +{ + struct curl_slist *item; + + /* if caller passed us a NULL, return now */ + if(!list) + return NULL; + + /* loop through to find the last item */ + item = list; + while(item->next) { + item = item->next; + } + return item; +} + +/* + * Curl_slist_append_nodup() appends a string to the linked list. Rather than + * copying the string in dynamic storage, it takes its ownership. The string + * should have been malloc()ated. Curl_slist_append_nodup always returns + * the address of the first record, so that you can use this function as an + * initialization function as well as an append function. + * If an error occurs, NULL is returned and the string argument is NOT + * released. + */ +struct curl_slist *Curl_slist_append_nodup(struct curl_slist *list, + const char *data) +{ + struct curl_slist *last; + struct curl_slist *new_item; + + DEBUGASSERT(data); + + new_item = curlx_malloc(sizeof(struct curl_slist)); + if(!new_item) + return NULL; + + new_item->next = NULL; + new_item->data = CURL_UNCONST(data); + + /* if this is the first item, then new_item *is* the list */ + if(!list) + return new_item; + + last = slist_get_last(list); + last->next = new_item; + return list; +} + +/* + * curl_slist_append() appends a string to the linked list. It always returns + * the address of the first record, so that you can use this function as an + * initialization function as well as an append function. If you find this + * bothersome, then create a separate _init function and call it + * appropriately from within the program. + */ +struct curl_slist *curl_slist_append(struct curl_slist *list, const char *data) +{ + char *dupdata = curlx_strdup(data); + + if(!dupdata) + return NULL; + + list = Curl_slist_append_nodup(list, dupdata); + if(!list) + curlx_free(dupdata); + + return list; +} + +/* + * Curl_slist_duplicate() duplicates a linked list. It always returns the + * address of the first record of the cloned list or NULL in case of an + * error (or if the input list was NULL). + */ +struct curl_slist *Curl_slist_duplicate(struct curl_slist *inlist) +{ + struct curl_slist *outlist = NULL; + struct curl_slist *tmp; + + while(inlist) { + tmp = curl_slist_append(outlist, inlist->data); + + if(!tmp) { + curl_slist_free_all(outlist); + return NULL; + } + + outlist = tmp; + inlist = inlist->next; + } + return outlist; +} + +/* be nice and clean up resources */ +void curl_slist_free_all(struct curl_slist *list) +{ + struct curl_slist *next; + struct curl_slist *item; + + if(!list) + return; + + item = list; + do { + next = item->next; + curlx_safefree(item->data); + curlx_free(item); + item = next; + } while(next); +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/slist.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/slist.h new file mode 100644 index 0000000000..47a30824db --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/slist.h @@ -0,0 +1,41 @@ +#ifndef HEADER_CURL_SLIST_H +#define HEADER_CURL_SLIST_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Curl_slist_duplicate() duplicates a linked list. It always returns the + * address of the first record of the cloned list or NULL in case of an + * error (or if the input list was NULL). + */ +struct curl_slist *Curl_slist_duplicate(struct curl_slist *inlist); + +/* + * Curl_slist_append_nodup() takes ownership of the given string and appends + * it to the list. + */ +struct curl_slist *Curl_slist_append_nodup(struct curl_slist *list, + const char *data); + +#endif /* HEADER_CURL_SLIST_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/smb.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/smb.c new file mode 100644 index 0000000000..4299190ff5 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/smb.c @@ -0,0 +1,1243 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) Bill Nagel <wnagel@tycoint.com>, Exacq Technologies + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" + +#if defined(CURL_ENABLE_SMB) && defined(USE_CURL_NTLM_CORE) + +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> /* for htons() */ +#endif + +#include "smb.h" +#include "url.h" +#include "sendf.h" +#include "curl_trc.h" +#include "cfilters.h" +#include "connect.h" +#include "progress.h" +#include "transfer.h" +#include "select.h" +#include "curl_ntlm_core.h" +#include "escape.h" +#include "curl_endian.h" +#include "curlx/strcopy.h" + +/* meta key for storing protocol meta at easy handle */ +#define CURL_META_SMB_EASY "meta:proto:smb:easy" +/* meta key for storing protocol meta at connection */ +#define CURL_META_SMB_CONN "meta:proto:smb:conn" + +enum smb_conn_state { + SMB_NOT_CONNECTED = 0, + SMB_CONNECTING, + SMB_NEGOTIATE, + SMB_SETUP, + SMB_CONNECTED +}; + +/* SMB connection data, kept at connection */ +struct smb_conn { + enum smb_conn_state state; + const char *user; + char *domain; + char *share; + unsigned char challenge[8]; + unsigned int session_key; + unsigned short uid; + char *recv_buf; + char *send_buf; + size_t upload_size; + size_t send_size; + size_t sent; + size_t got; +}; + +/* SMB request state */ +enum smb_req_state { + SMB_REQUESTING, + SMB_TREE_CONNECT, + SMB_OPEN, + SMB_DOWNLOAD, + SMB_UPLOAD, + SMB_CLOSE, + SMB_TREE_DISCONNECT, + SMB_DONE +}; + +/* SMB request data, kept at easy handle */ +struct smb_request { + enum smb_req_state state; + char *path; + unsigned short tid; /* Even if we connect to the same tree as another */ + unsigned short fid; /* request, the tid will be different */ + CURLcode result; +}; + +/* + * Definitions for SMB protocol data structures + */ +#if defined(_MSC_VER) || defined(__ILEC400__) +# define PACK +# pragma pack(push) +# pragma pack(1) +#elif defined(__GNUC__) +# define PACK __attribute__((packed)) +#else +# define PACK +#endif + +#define SMB_COM_CLOSE 0x04 +#define SMB_COM_READ_ANDX 0x2e +#define SMB_COM_WRITE_ANDX 0x2f +#define SMB_COM_TREE_DISCONNECT 0x71 +#define SMB_COM_NEGOTIATE 0x72 +#define SMB_COM_SETUP_ANDX 0x73 +#define SMB_COM_TREE_CONNECT_ANDX 0x75 +#define SMB_COM_NT_CREATE_ANDX 0xa2 +#define SMB_COM_NO_ANDX_COMMAND 0xff + +#define SMB_WC_CLOSE 0x03 +#define SMB_WC_READ_ANDX 0x0c +#define SMB_WC_WRITE_ANDX 0x0e +#define SMB_WC_SETUP_ANDX 0x0d +#define SMB_WC_TREE_CONNECT_ANDX 0x04 +#define SMB_WC_NT_CREATE_ANDX 0x18 + +#define SMB_FLAGS_CANONICAL_PATHNAMES 0x10 +#define SMB_FLAGS_CASELESS_PATHNAMES 0x08 +/* #define SMB_FLAGS2_UNICODE_STRINGS 0x8000 */ +#define SMB_FLAGS2_IS_LONG_NAME 0x0040 +#define SMB_FLAGS2_KNOWS_LONG_NAME 0x0001 + +#define SMB_CAP_LARGE_FILES 0x08 +#define SMB_GENERIC_WRITE 0x40000000 +#define SMB_GENERIC_READ 0x80000000 +#define SMB_FILE_SHARE_ALL 0x07 +#define SMB_FILE_OPEN 0x01 +#define SMB_FILE_OVERWRITE_IF 0x05 + +#define SMB_ERR_NOACCESS 0x00050001 + +struct smb_header { + unsigned char nbt_type; + unsigned char nbt_flags; + unsigned short nbt_length; + unsigned char magic[4]; + unsigned char command; + unsigned int status; + unsigned char flags; + unsigned short flags2; + unsigned short pid_high; + unsigned char signature[8]; + unsigned short pad; + unsigned short tid; + unsigned short pid; + unsigned short uid; + unsigned short mid; +} PACK; + +struct smb_negotiate_response { + struct smb_header h; + unsigned char word_count; + unsigned short dialect_index; + unsigned char security_mode; + unsigned short max_mpx_count; + unsigned short max_number_vcs; + unsigned int max_buffer_size; + unsigned int max_raw_size; + unsigned int session_key; + unsigned int capabilities; + unsigned int system_time_low; + unsigned int system_time_high; + unsigned short server_time_zone; + unsigned char encryption_key_length; + unsigned short byte_count; + char bytes[1]; +} PACK; + +struct andx { + unsigned char command; + unsigned char pad; + unsigned short offset; +} PACK; + +struct smb_setup { + unsigned char word_count; + struct andx andx; + unsigned short max_buffer_size; + unsigned short max_mpx_count; + unsigned short vc_number; + unsigned int session_key; + unsigned short lengths[2]; + unsigned int pad; + unsigned int capabilities; + unsigned short byte_count; + char bytes[1024]; +} PACK; + +struct smb_tree_connect { + unsigned char word_count; + struct andx andx; + unsigned short flags; + unsigned short pw_len; + unsigned short byte_count; + char bytes[1024]; +} PACK; + +struct smb_nt_create { + unsigned char word_count; + struct andx andx; + unsigned char pad; + unsigned short name_length; + unsigned int flags; + unsigned int root_fid; + unsigned int access; + curl_off_t allocation_size; + unsigned int ext_file_attributes; + unsigned int share_access; + unsigned int create_disposition; + unsigned int create_options; + unsigned int impersonation_level; + unsigned char security_flags; + unsigned short byte_count; + char bytes[1024]; +} PACK; + +struct smb_nt_create_response { + struct smb_header h; + unsigned char word_count; + struct andx andx; + unsigned char op_lock_level; + unsigned short fid; + unsigned int create_disposition; + + curl_off_t create_time; + curl_off_t last_access_time; + curl_off_t last_write_time; + curl_off_t last_change_time; + unsigned int ext_file_attributes; + curl_off_t allocation_size; + curl_off_t end_of_file; +} PACK; + +struct smb_read { + unsigned char word_count; + struct andx andx; + unsigned short fid; + unsigned int offset; + unsigned short max_bytes; + unsigned short min_bytes; + unsigned int timeout; + unsigned short remaining; + unsigned int offset_high; + unsigned short byte_count; +} PACK; + +struct smb_write { + struct smb_header h; + unsigned char word_count; + struct andx andx; + unsigned short fid; + unsigned int offset; + unsigned int timeout; + unsigned short write_mode; + unsigned short remaining; + unsigned short pad; + unsigned short data_length; + unsigned short data_offset; + unsigned int offset_high; + unsigned short byte_count; + unsigned char pad2; +} PACK; + +struct smb_close { + unsigned char word_count; + unsigned short fid; + unsigned int last_mtime; + unsigned short byte_count; +} PACK; + +struct smb_tree_disconnect { + unsigned char word_count; + unsigned short byte_count; +} PACK; + +#if defined(_MSC_VER) || defined(__ILEC400__) +# pragma pack(pop) +#endif + +#define MAX_PAYLOAD_SIZE 0x8000 +#define MAX_MESSAGE_SIZE (MAX_PAYLOAD_SIZE + 0x1000) +#define CLIENTNAME "curl" +#define SERVICENAME "?????" + +/* SMB is mostly little endian */ +#if (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) || \ + defined(__OS400__) +static unsigned short smb_swap16(unsigned short x) +{ + return (unsigned short)((x << 8) | ((x >> 8) & 0xff)); +} + +static unsigned int smb_swap32(unsigned int x) +{ + return (x << 24) | ((x << 8) & 0xff0000) | ((x >> 8) & 0xff00) | + ((x >> 24) & 0xff); +} + +static curl_off_t smb_swap64(curl_off_t x) +{ + return ((curl_off_t)smb_swap32((unsigned int)x) << 32) | + smb_swap32((unsigned int)(x >> 32)); +} + +#else +# define smb_swap16(x) (x) +# define smb_swap32(x) (x) +# define smb_swap64(x) (x) +#endif + +static void conn_state(struct Curl_easy *data, struct smb_conn *smbc, + enum smb_conn_state newstate) +{ +#if defined(DEBUGBUILD) && defined(CURLVERBOSE) + /* For debug purposes */ + static const char * const names[] = { + "SMB_NOT_CONNECTED", + "SMB_CONNECTING", + "SMB_NEGOTIATE", + "SMB_SETUP", + "SMB_CONNECTED", + /* LAST */ + }; + + if(smbc->state != newstate) + infof(data, "SMB conn %p state change from %s to %s", + (void *)smbc, names[smbc->state], names[newstate]); +#else + (void)data; +#endif + smbc->state = newstate; +} + +static void request_state(struct Curl_easy *data, + enum smb_req_state newstate) +{ + struct smb_request *req = Curl_meta_get(data, CURL_META_SMB_EASY); + if(req) { +#if defined(DEBUGBUILD) && defined(CURLVERBOSE) + /* For debug purposes */ + static const char * const names[] = { + "SMB_REQUESTING", + "SMB_TREE_CONNECT", + "SMB_OPEN", + "SMB_DOWNLOAD", + "SMB_UPLOAD", + "SMB_CLOSE", + "SMB_TREE_DISCONNECT", + "SMB_DONE", + /* LAST */ + }; + + if(req->state != newstate) + infof(data, "SMB request %p state change from %s to %s", + (void *)req, names[req->state], names[newstate]); +#endif + + req->state = newstate; + } +} + +static void smb_easy_dtor(void *key, size_t klen, void *entry) +{ + struct smb_request *req = entry; + (void)key; + (void)klen; + curlx_safefree(req->path); + curlx_free(req); +} + +static void smb_conn_dtor(void *key, size_t klen, void *entry) +{ + struct smb_conn *smbc = entry; + (void)key; + (void)klen; + curlx_safefree(smbc->share); + curlx_safefree(smbc->domain); + curlx_safefree(smbc->recv_buf); + curlx_safefree(smbc->send_buf); + curlx_free(smbc); +} + +static CURLcode smb_parse_url_path(struct Curl_easy *data, + struct smb_conn *smbc, + struct smb_request *req) +{ + char *path; + char *slash, *s; + CURLcode result; + + /* URL decode the path */ + result = Curl_urldecode(data->state.up.path, 0, &path, NULL, REJECT_CTRL); + if(result) + return result; + + /* Parse the path for the share */ + curlx_safefree(smbc->share); + smbc->share = curlx_strdup((*path == '/' || *path == '\\') + ? path + 1 : path); + curlx_free(path); + if(!smbc->share) + return CURLE_OUT_OF_MEMORY; + + slash = strchr(smbc->share, '/'); + if(!slash) + slash = strchr(smbc->share, '\\'); + + /* The share must be present */ + if(!slash) { + curlx_safefree(smbc->share); + failf(data, "missing share in URL path for SMB"); + return CURLE_URL_MALFORMAT; + } + + /* Parse the path for the file path converting any forward slashes into + backslashes */ + *slash++ = 0; + for(s = slash; *s; s++) { + if(*s == '/') + *s = '\\'; + } + /* keep a copy at easy struct to not share this with connection state */ + req->path = curlx_strdup(slash); + if(!req->path) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +/* this should setup things in the connection, not in the easy + handle */ +static CURLcode smb_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + struct smb_conn *smbc; + struct smb_request *req; + + /* Initialize the connection state */ + smbc = curlx_calloc(1, sizeof(*smbc)); + if(!smbc || + Curl_conn_meta_set(conn, CURL_META_SMB_CONN, smbc, smb_conn_dtor)) + return CURLE_OUT_OF_MEMORY; + + /* Initialize the request state */ + req = curlx_calloc(1, sizeof(*req)); + if(!req || + Curl_meta_set(data, CURL_META_SMB_EASY, req, smb_easy_dtor)) + return CURLE_OUT_OF_MEMORY; + + /* Parse the URL path */ + return smb_parse_url_path(data, smbc, req); +} + +static CURLcode smb_connect(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = Curl_conn_meta_get(conn, CURL_META_SMB_CONN); + const char *slash; + const char *user = Curl_creds_user(conn->creds); + + (void)done; + if(!smbc) + return CURLE_FAILED_INIT; + + /* Check we have a username and password to authenticate with */ + if(!Curl_creds_has_user(data->state.creds)) + return CURLE_LOGIN_DENIED; + + /* Initialize the connection state */ + smbc->state = SMB_CONNECTING; + smbc->recv_buf = curlx_malloc(MAX_MESSAGE_SIZE); + if(!smbc->recv_buf) + return CURLE_OUT_OF_MEMORY; + smbc->send_buf = curlx_malloc(MAX_MESSAGE_SIZE); + if(!smbc->send_buf) + return CURLE_OUT_OF_MEMORY; + + /* Parse the username, domain, and password */ + slash = strchr(user, '/'); + if(!slash) + slash = strchr(user, '\\'); + + if(slash) { + smbc->user = slash + 1; + smbc->domain = curlx_strdup(user); + if(!smbc->domain) + return CURLE_OUT_OF_MEMORY; + smbc->domain[slash - user] = 0; + } + else { + smbc->user = user; + smbc->domain = curlx_strdup(conn->origin->hostname); + if(!smbc->domain) + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +static CURLcode smb_recv_message(struct Curl_easy *data, + struct smb_conn *smbc, + void **msg) +{ + char *buf = smbc->recv_buf; + size_t bytes_read; + size_t nbt_size; + size_t msg_size = sizeof(struct smb_header); + size_t len = MAX_MESSAGE_SIZE - smbc->got; + CURLcode result; + + result = Curl_xfer_recv(data, buf + smbc->got, len, &bytes_read); + if(result) + return result; + + if(!bytes_read) + return CURLE_OK; + + smbc->got += bytes_read; + + /* Check for a 32-bit nbt header */ + if(smbc->got < sizeof(unsigned int)) + return CURLE_OK; + + nbt_size = Curl_read16_be((const unsigned char *) + (buf + sizeof(unsigned short))) + + sizeof(unsigned int); + if(nbt_size > MAX_MESSAGE_SIZE) { + failf(data, "too large NetBIOS frame size %zu", nbt_size); + return CURLE_RECV_ERROR; + } + else if(nbt_size < msg_size) { + /* Each SMB message must be at least this large, e.g. 32 bytes */ + failf(data, "too small NetBIOS frame size %zu", nbt_size); + return CURLE_RECV_ERROR; + } + + if(smbc->got < nbt_size) + return CURLE_OK; + + if(nbt_size >= msg_size + 1) { + /* Add the word count */ + msg_size += 1 + (((unsigned char)buf[msg_size]) * sizeof(unsigned short)); + if(nbt_size >= msg_size + sizeof(unsigned short)) { + /* Add the byte count */ + msg_size += sizeof(unsigned short) + + Curl_read16_le((const unsigned char *)&buf[msg_size]); + if(nbt_size < msg_size) + return CURLE_RECV_ERROR; + } + } + + *msg = buf; + + return CURLE_OK; +} + +static void smb_pop_message(struct smb_conn *smbc) +{ + smbc->got = 0; +} + +static void smb_format_message(struct smb_conn *smbc, + struct smb_request *req, + struct smb_header *h, + unsigned char cmd, size_t len) +{ + const unsigned int pid = 0xbad71d; /* made up */ + + memset(h, 0, sizeof(*h)); + h->nbt_length = htons((unsigned short)(sizeof(*h) - sizeof(unsigned int) + + len)); + memcpy((char *)h->magic, "\xffSMB", 4); + h->command = cmd; + h->flags = SMB_FLAGS_CANONICAL_PATHNAMES | SMB_FLAGS_CASELESS_PATHNAMES; + h->flags2 = smb_swap16(SMB_FLAGS2_IS_LONG_NAME | SMB_FLAGS2_KNOWS_LONG_NAME); + h->uid = smb_swap16(smbc->uid); + h->tid = smb_swap16(req->tid); + h->pid_high = smb_swap16((unsigned short)(pid >> 16)); + h->pid = smb_swap16((unsigned short)pid); +} + +static CURLcode smb_send(struct Curl_easy *data, struct smb_conn *smbc, + size_t len, size_t upload_size) +{ + size_t bytes_written; + CURLcode result; + + result = Curl_xfer_send(data, smbc->send_buf, len, FALSE, &bytes_written); + if(result) + return result; + + if(bytes_written != len) { + smbc->send_size = len; + smbc->sent = bytes_written; + } + + smbc->upload_size = upload_size; + + return CURLE_OK; +} + +static CURLcode smb_flush(struct Curl_easy *data, struct smb_conn *smbc) +{ + size_t bytes_written; + size_t len = smbc->send_size - smbc->sent; + CURLcode result; + + if(!smbc->send_size) + return CURLE_OK; + + result = Curl_xfer_send(data, smbc->send_buf + smbc->sent, len, FALSE, + &bytes_written); + if(result) + return result; + + if(bytes_written != len) + smbc->sent += bytes_written; + else + smbc->send_size = 0; + + return CURLE_OK; +} + +static CURLcode smb_send_message(struct Curl_easy *data, + struct smb_conn *smbc, + struct smb_request *req, + unsigned char cmd, + const void *msg, size_t msg_len) +{ + if((MAX_MESSAGE_SIZE - sizeof(struct smb_header)) < msg_len) { + DEBUGASSERT(0); + return CURLE_SEND_ERROR; + } + smb_format_message(smbc, req, (struct smb_header *)smbc->send_buf, + cmd, msg_len); + memcpy(smbc->send_buf + sizeof(struct smb_header), msg, msg_len); + + return smb_send(data, smbc, sizeof(struct smb_header) + msg_len, 0); +} + +static CURLcode smb_send_negotiate(struct Curl_easy *data, + struct smb_conn *smbc, + struct smb_request *req) +{ + static const char msg[] = "\x00\x0c\x00\x02NT LM 0.12"; + + return smb_send_message(data, smbc, req, SMB_COM_NEGOTIATE, msg, + sizeof(msg)); +} + +static CURLcode smb_send_setup(struct Curl_easy *data) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = Curl_conn_meta_get(conn, CURL_META_SMB_CONN); + struct smb_request *req = Curl_meta_get(data, CURL_META_SMB_EASY); + struct smb_setup msg; + char *p = msg.bytes; + unsigned char lm_hash[21]; + unsigned char lm[24]; + unsigned char nt_hash[21]; + unsigned char nt[24]; + size_t byte_count; + const char *passwd = Curl_creds_passwd(conn->creds); + + if(!smbc || !req) + return CURLE_FAILED_INIT; + + byte_count = sizeof(lm) + sizeof(nt) + + strlen(smbc->user) + strlen(smbc->domain) + + CURL_CSTRLEN(CURL_OS) + CURL_CSTRLEN(CLIENTNAME) + 4; /* 4 null chars */ + if(byte_count > sizeof(msg.bytes)) + return CURLE_FILESIZE_EXCEEDED; + + Curl_ntlm_core_mk_lm_hash(passwd, lm_hash); + Curl_ntlm_core_lm_resp(lm_hash, smbc->challenge, lm); + Curl_ntlm_core_mk_nt_hash(passwd, nt_hash); + Curl_ntlm_core_lm_resp(nt_hash, smbc->challenge, nt); + + memset(&msg, 0, sizeof(msg) - sizeof(msg.bytes)); + msg.word_count = SMB_WC_SETUP_ANDX; + msg.andx.command = SMB_COM_NO_ANDX_COMMAND; + msg.max_buffer_size = smb_swap16(MAX_MESSAGE_SIZE); + msg.max_mpx_count = smb_swap16(1); + msg.vc_number = smb_swap16(1); + msg.session_key = smb_swap32(smbc->session_key); + msg.capabilities = smb_swap32(SMB_CAP_LARGE_FILES); + msg.lengths[0] = smb_swap16(sizeof(lm)); + msg.lengths[1] = smb_swap16(sizeof(nt)); + memcpy(p, lm, sizeof(lm)); + p += sizeof(lm); + memcpy(p, nt, sizeof(nt)); + p += sizeof(nt); + p += curl_msnprintf(p, byte_count - sizeof(nt) - sizeof(lm), + "%s%c" /* user */ + "%s%c" /* domain */ + "%s%c" /* OS */ + "%s", /* client name */ + smbc->user, 0, smbc->domain, 0, CURL_OS, 0, CLIENTNAME); + p++; /* count the final null-termination */ + DEBUGASSERT(byte_count == (size_t)(p - msg.bytes)); + msg.byte_count = smb_swap16((unsigned short)byte_count); + + return smb_send_message(data, smbc, req, SMB_COM_SETUP_ANDX, &msg, + sizeof(msg) - sizeof(msg.bytes) + byte_count); +} + +static CURLcode smb_send_tree_connect(struct Curl_easy *data, + struct smb_conn *smbc, + struct smb_request *req) +{ + struct smb_tree_connect msg; + struct connectdata *conn = data->conn; + char *p = msg.bytes; + const size_t byte_count = strlen(conn->origin->hostname) + + strlen(smbc->share) + + CURL_CSTRLEN(SERVICENAME) + 5; /* 2 nulls and 3 backslashes */ + + if(byte_count > sizeof(msg.bytes)) + return CURLE_FILESIZE_EXCEEDED; + + memset(&msg, 0, sizeof(msg) - sizeof(msg.bytes)); + msg.word_count = SMB_WC_TREE_CONNECT_ANDX; + msg.andx.command = SMB_COM_NO_ANDX_COMMAND; + msg.pw_len = 0; + + p += curl_msnprintf(p, byte_count, + "\\\\%s\\" /* hostname */ + "%s%c" /* share */ + "%s", /* service */ + conn->origin->hostname, smbc->share, 0, SERVICENAME); + p++; /* count the final null-termination */ + DEBUGASSERT(byte_count == (size_t)(p - msg.bytes)); + msg.byte_count = smb_swap16((unsigned short)byte_count); + + return smb_send_message(data, smbc, req, SMB_COM_TREE_CONNECT_ANDX, &msg, + sizeof(msg) - sizeof(msg.bytes) + byte_count); +} + +static CURLcode smb_send_open(struct Curl_easy *data, + struct smb_conn *smbc, + struct smb_request *req) +{ + struct smb_nt_create msg; + const size_t byte_count = strlen(req->path) + 1; + + if(byte_count > sizeof(msg.bytes)) + return CURLE_FILESIZE_EXCEEDED; + + memset(&msg, 0, sizeof(msg) - sizeof(msg.bytes)); + msg.word_count = SMB_WC_NT_CREATE_ANDX; + msg.andx.command = SMB_COM_NO_ANDX_COMMAND; + msg.name_length = smb_swap16((unsigned short)(byte_count - 1)); + msg.share_access = smb_swap32(SMB_FILE_SHARE_ALL); + if(data->state.upload) { + msg.access = smb_swap32(SMB_GENERIC_READ | SMB_GENERIC_WRITE); + msg.create_disposition = smb_swap32(SMB_FILE_OVERWRITE_IF); + } + else { + msg.access = smb_swap32(SMB_GENERIC_READ); + msg.create_disposition = smb_swap32(SMB_FILE_OPEN); + } + msg.byte_count = smb_swap16((unsigned short)byte_count); + curlx_strcopy(msg.bytes, sizeof(msg.bytes), req->path, byte_count - 1); + + return smb_send_message(data, smbc, req, SMB_COM_NT_CREATE_ANDX, &msg, + sizeof(msg) - sizeof(msg.bytes) + byte_count); +} + +static CURLcode smb_send_close(struct Curl_easy *data, + struct smb_conn *smbc, + struct smb_request *req) +{ + struct smb_close msg; + + memset(&msg, 0, sizeof(msg)); + msg.word_count = SMB_WC_CLOSE; + msg.fid = smb_swap16(req->fid); + + return smb_send_message(data, smbc, req, SMB_COM_CLOSE, &msg, sizeof(msg)); +} + +static CURLcode smb_send_tree_disconnect(struct Curl_easy *data, + struct smb_conn *smbc, + struct smb_request *req) +{ + struct smb_tree_disconnect msg; + memset(&msg, 0, sizeof(msg)); + return smb_send_message(data, smbc, req, SMB_COM_TREE_DISCONNECT, + &msg, sizeof(msg)); +} + +static CURLcode smb_send_read(struct Curl_easy *data, + struct smb_conn *smbc, + struct smb_request *req) +{ + curl_off_t offset = data->req.offset; + struct smb_read msg; + + memset(&msg, 0, sizeof(msg)); + msg.word_count = SMB_WC_READ_ANDX; + msg.andx.command = SMB_COM_NO_ANDX_COMMAND; + msg.fid = smb_swap16(req->fid); + msg.offset = smb_swap32((unsigned int)offset); + msg.offset_high = smb_swap32((unsigned int)(offset >> 32)); + msg.min_bytes = smb_swap16(MAX_PAYLOAD_SIZE); + msg.max_bytes = smb_swap16(MAX_PAYLOAD_SIZE); + + return smb_send_message(data, smbc, req, SMB_COM_READ_ANDX, + &msg, sizeof(msg)); +} + +static CURLcode smb_send_write(struct Curl_easy *data, + struct smb_conn *smbc, + struct smb_request *req) +{ + struct smb_write *msg; + curl_off_t offset = data->req.offset; + curl_off_t upload_size = data->req.size - data->req.bytecount; + + msg = (struct smb_write *)smbc->send_buf; + if(upload_size >= MAX_PAYLOAD_SIZE - 1) /* There is one byte of padding */ + upload_size = MAX_PAYLOAD_SIZE - 1; + + memset(msg, 0, sizeof(*msg)); + msg->word_count = SMB_WC_WRITE_ANDX; + msg->andx.command = SMB_COM_NO_ANDX_COMMAND; + msg->fid = smb_swap16(req->fid); + msg->offset = smb_swap32((unsigned int)offset); + msg->offset_high = smb_swap32((unsigned int)(offset >> 32)); + msg->data_length = smb_swap16((unsigned short)upload_size); + msg->data_offset = smb_swap16(sizeof(*msg) - sizeof(unsigned int)); + msg->byte_count = smb_swap16((unsigned short)(upload_size + 1)); + + smb_format_message(smbc, req, &msg->h, SMB_COM_WRITE_ANDX, + sizeof(*msg) - sizeof(msg->h) + (size_t)upload_size); + + return smb_send(data, smbc, sizeof(*msg), (size_t)upload_size); +} + +static CURLcode smb_send_and_recv(struct Curl_easy *data, + struct smb_conn *smbc, void **msg) +{ + CURLcode result; + *msg = NULL; /* if it returns early */ + + /* Check if there is data in the transfer buffer */ + if(!smbc->send_size && smbc->upload_size) { + size_t nread = smbc->upload_size > (size_t)MAX_MESSAGE_SIZE ? + (size_t)MAX_MESSAGE_SIZE : smbc->upload_size; + bool eos; + + result = Curl_client_read(data, smbc->send_buf, nread, &nread, &eos); + if(result && result != CURLE_AGAIN) + return result; + if(!nread) + return CURLE_OK; + + smbc->upload_size -= nread; + smbc->send_size = nread; + smbc->sent = 0; + } + + /* Check if there is data to send */ + if(smbc->send_size) { + result = smb_flush(data, smbc); + if(result) + return result; + } + + /* Check if there is still data to be sent */ + if(smbc->send_size || smbc->upload_size) + return CURLE_AGAIN; + + return smb_recv_message(data, smbc, msg); +} + +static CURLcode smb_connection_state(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = Curl_conn_meta_get(conn, CURL_META_SMB_CONN); + struct smb_request *req = Curl_meta_get(data, CURL_META_SMB_EASY); + struct smb_negotiate_response *nrsp; + struct smb_header *h; + CURLcode result; + void *msg = NULL; + + if(!smbc || !req) + return CURLE_FAILED_INIT; + + if(smbc->state == SMB_CONNECTING) { +#ifdef USE_SSL + if(Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + bool ssl_done = FALSE; + result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssl_done); + if(result && result != CURLE_AGAIN) + return result; + if(!ssl_done) + return CURLE_OK; + } +#endif + + result = smb_send_negotiate(data, smbc, req); + if(result) { + CURL_TRC_M(data, "SMB: failed to send negotiate message"); + connclose(conn); + return result; + } + + conn_state(data, smbc, SMB_NEGOTIATE); + } + + /* Send the previous message and check for a response */ + result = smb_send_and_recv(data, smbc, &msg); + if(result && result != CURLE_AGAIN) { + CURL_TRC_M(data, "SMB: failed to communicate"); + connclose(conn); + return result; + } + + if(!msg) + return CURLE_OK; + + h = msg; + + switch(smbc->state) { + case SMB_NEGOTIATE: + if((smbc->got < sizeof(*nrsp) + sizeof(smbc->challenge) - 1) || + h->status) { + CURL_TRC_M(data, "SMB: negotiation failed"); + connclose(conn); + return CURLE_COULDNT_CONNECT; + } + nrsp = msg; +#if defined(__GNUC__) && __GNUC__ >= 13 +#pragma GCC diagnostic push +/* error: 'memcpy' offset [74, 80] from the object at '<unknown>' is out of + the bounds of referenced subobject 'bytes' with type 'char[1]' */ +#pragma GCC diagnostic ignored "-Warray-bounds" +#endif + memcpy(smbc->challenge, nrsp->bytes, sizeof(smbc->challenge)); +#if defined(__GNUC__) && __GNUC__ >= 13 +#pragma GCC diagnostic pop +#endif + smbc->session_key = smb_swap32(nrsp->session_key); + result = smb_send_setup(data); + if(result) { + CURL_TRC_M(data, "SMB: failed to send setup message"); + connclose(conn); + return result; + } + conn_state(data, smbc, SMB_SETUP); + break; + + case SMB_SETUP: + if(h->status) { + CURL_TRC_M(data, "SMB: authentication failed"); + connclose(conn); + return CURLE_LOGIN_DENIED; + } + smbc->uid = smb_swap16(h->uid); + conn_state(data, smbc, SMB_CONNECTED); + *done = TRUE; + break; + + default: + smb_pop_message(smbc); + return CURLE_OK; /* ignore */ + } + + smb_pop_message(smbc); + + return CURLE_OK; +} + +/* + * Convert a timestamp from the Windows world (100 nsec units from 1 Jan 1601) + * to POSIX time. Cap the output to fit within a time_t. + */ +static void get_posix_time(time_t *out, curl_off_t timestamp) +{ + if(timestamp >= (curl_off_t)116444736000000000) { + timestamp -= (curl_off_t)116444736000000000; + timestamp /= 10000000; +#if SIZEOF_TIME_T < SIZEOF_CURL_OFF_T + if(timestamp > TIME_T_MAX) + *out = TIME_T_MAX; + else if(timestamp < TIME_T_MIN) + *out = TIME_T_MIN; + else +#endif + *out = (time_t)timestamp; + } + else + *out = 0; +} + +static CURLcode smb_request_state(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = Curl_conn_meta_get(conn, CURL_META_SMB_CONN); + struct smb_request *req = Curl_meta_get(data, CURL_META_SMB_EASY); + struct smb_header *h; + enum smb_req_state next_state = SMB_DONE; + size_t len; + size_t off; + CURLcode result; + void *msg = NULL; + const struct smb_nt_create_response *smb_m; + + if(!smbc || !req) + return CURLE_FAILED_INIT; + + if(data->state.upload && (data->state.infilesize < 0)) { + failf(data, "SMB upload needs to know the size up front"); + return CURLE_SEND_ERROR; + } + + /* Start the request */ + if(req->state == SMB_REQUESTING) { + result = smb_send_tree_connect(data, smbc, req); + if(result) { + CURL_TRC_M(data, "SMB: failed to send tree connect message"); + connclose(conn); + return result; + } + + request_state(data, SMB_TREE_CONNECT); + } + + /* Send the previous message and check for a response */ + result = smb_send_and_recv(data, smbc, &msg); + if(result && result != CURLE_AGAIN) { + CURL_TRC_M(data, "SMB: failed to communicate"); + connclose(conn); + return result; + } + + if(!msg) + return CURLE_OK; + + h = msg; + + switch(req->state) { + case SMB_TREE_CONNECT: + if(h->status) { + req->result = CURLE_REMOTE_FILE_NOT_FOUND; + if(h->status == smb_swap32(SMB_ERR_NOACCESS)) + req->result = CURLE_REMOTE_ACCESS_DENIED; + break; + } + req->tid = smb_swap16(h->tid); + next_state = SMB_OPEN; + break; + + case SMB_OPEN: + if(h->status || smbc->got < sizeof(struct smb_nt_create_response)) { + req->result = CURLE_REMOTE_FILE_NOT_FOUND; + if(h->status == smb_swap32(SMB_ERR_NOACCESS)) + req->result = CURLE_REMOTE_ACCESS_DENIED; + next_state = SMB_TREE_DISCONNECT; + break; + } + smb_m = (const struct smb_nt_create_response *)msg; + req->fid = smb_swap16(smb_m->fid); + data->req.offset = 0; + if(data->state.upload) { + data->req.size = data->state.infilesize; + Curl_pgrsSetUploadSize(data, data->req.size); + next_state = SMB_UPLOAD; + } + else { + data->req.size = smb_swap64(smb_m->end_of_file); + if(data->req.size < 0) { + req->result = CURLE_WEIRD_SERVER_REPLY; + next_state = SMB_CLOSE; + } + else { + Curl_pgrsSetDownloadSize(data, data->req.size); + if(data->set.get_filetime) + get_posix_time(&data->info.filetime, smb_m->last_change_time); + next_state = SMB_DOWNLOAD; + } + } + break; + + case SMB_DOWNLOAD: + if(h->status || smbc->got < sizeof(struct smb_header) + 15) { + req->result = CURLE_RECV_ERROR; + next_state = SMB_CLOSE; + break; + } + len = Curl_read16_le((const unsigned char *)msg + + sizeof(struct smb_header) + 11); + off = Curl_read16_le((const unsigned char *)msg + + sizeof(struct smb_header) + 13); + if(len > 0) { + if(off + sizeof(unsigned int) + len > smbc->got) { + failf(data, "Invalid input packet"); + result = CURLE_RECV_ERROR; + } + else + result = Curl_client_write(data, CLIENTWRITE_BODY, + (char *)msg + off + sizeof(unsigned int), + len); + if(result) { + req->result = result; + next_state = SMB_CLOSE; + break; + } + } + data->req.offset += len; + next_state = (len < MAX_PAYLOAD_SIZE) ? SMB_CLOSE : SMB_DOWNLOAD; + break; + + case SMB_UPLOAD: + if(h->status || smbc->got < sizeof(struct smb_header) + 7) { + req->result = CURLE_UPLOAD_FAILED; + next_state = SMB_CLOSE; + break; + } + len = Curl_read16_le((const unsigned char *)msg + + sizeof(struct smb_header) + 5); + data->req.bytecount += len; + data->req.offset += len; + Curl_pgrs_upload_inc(data, len); + if(data->req.bytecount >= data->req.size) + next_state = SMB_CLOSE; + else + next_state = SMB_UPLOAD; + break; + + case SMB_CLOSE: + /* We do not care if the close failed, proceed to tree disconnect anyway */ + next_state = SMB_TREE_DISCONNECT; + break; + + case SMB_TREE_DISCONNECT: + next_state = SMB_DONE; + break; + + default: + smb_pop_message(smbc); + return CURLE_OK; /* ignore */ + } + + smb_pop_message(smbc); + + switch(next_state) { + case SMB_OPEN: + result = smb_send_open(data, smbc, req); + break; + + case SMB_DOWNLOAD: + result = smb_send_read(data, smbc, req); + break; + + case SMB_UPLOAD: + result = smb_send_write(data, smbc, req); + break; + + case SMB_CLOSE: + result = smb_send_close(data, smbc, req); + break; + + case SMB_TREE_DISCONNECT: + result = smb_send_tree_disconnect(data, smbc, req); + break; + + case SMB_DONE: + result = req->result; + *done = TRUE; + break; + + default: + break; + } + + if(result) { + CURL_TRC_M(data, "SMB: failed to send message"); + connclose(conn); + return result; + } + + request_state(data, next_state); + + return CURLE_OK; +} + +static CURLcode smb_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + return Curl_pollset_add_inout(data, ps, data->conn->sock[FIRSTSOCKET]); +} + +static CURLcode smb_do(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct smb_conn *smbc = Curl_conn_meta_get(conn, CURL_META_SMB_CONN); + + *done = FALSE; + if(!smbc) + return CURLE_FAILED_INIT; + if(smbc->share) + return CURLE_OK; + return CURLE_URL_MALFORMAT; +} + +/* + * SMB handler interface + */ +const struct Curl_protocol Curl_protocol_smb = { + smb_setup_connection, /* setup_connection */ + smb_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + smb_connect, /* connect_it */ + smb_connection_state, /* connecting */ + smb_request_state, /* doing */ + smb_pollset, /* proto_pollset */ + smb_pollset, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#endif /* CURL_ENABLE_SMB && USE_CURL_NTLM_CORE */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/smb.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/smb.h new file mode 100644 index 0000000000..5a92ad13db --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/smb.h @@ -0,0 +1,31 @@ +#ifndef HEADER_CURL_SMB_H +#define HEADER_CURL_SMB_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Bill Nagel <wnagel@tycoint.com>, Exacq Technologies + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#if defined(CURL_ENABLE_SMB) && defined(USE_CURL_NTLM_CORE) +extern const struct Curl_protocol Curl_protocol_smb; +#endif + +#endif /* HEADER_CURL_SMB_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/smtp.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/smtp.c new file mode 100644 index 0000000000..50e2af400a --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/smtp.c @@ -0,0 +1,2021 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC1870 SMTP Service Extension for Message Size + * RFC2195 CRAM-MD5 authentication + * RFC2831 DIGEST-MD5 authentication + * RFC3207 SMTP over TLS + * RFC4422 Simple Authentication and Security Layer (SASL) + * RFC4616 PLAIN authentication + * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism + * RFC4954 SMTP Authentication + * RFC5321 SMTP protocol + * RFC5890 Internationalized Domain Names for Applications (IDNA) + * RFC6531 SMTP Extension for Internationalized Email + * RFC6532 Internationalized Email Headers + * RFC6749 OAuth 2.0 Authorization Framework + * RFC8314 Use of TLS for Email Submission and Access + * Draft SMTP URL Interface <draft-earhart-url-smtp-00.txt> + * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt> + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" +#include "smtp.h" + +#ifndef CURL_DISABLE_SMTP + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include "sendf.h" +#include "curl_trc.h" +#include "progress.h" +#include "transfer.h" +#include "escape.h" +#include "pingpong.h" +#include "mime.h" +#include "vtls/vtls.h" +#include "cfilters.h" +#include "connect.h" +#include "select.h" +#include "url.h" +#include "curl_gethostname.h" +#include "bufref.h" +#include "curl_sasl.h" +#include "idn.h" +#include "curlx/strparse.h" + +/* meta key for storing protocol meta at easy handle */ +#define CURL_META_SMTP_EASY "meta:proto:smtp:easy" +/* meta key for storing protocol meta at connection */ +#define CURL_META_SMTP_CONN "meta:proto:smtp:conn" + +/**************************************************************************** + * SMTP unique setup + ***************************************************************************/ +typedef enum { + SMTP_STOP, /* do nothing state, stops the state machine */ + SMTP_SERVERGREET, /* waiting for the initial greeting immediately after + a connect */ + SMTP_EHLO, + SMTP_HELO, + SMTP_STARTTLS, + SMTP_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS + (multi mode only) */ + SMTP_AUTH, + SMTP_COMMAND, /* VRFY, EXPN, NOOP, RSET and HELP */ + SMTP_MAIL, /* MAIL FROM */ + SMTP_RCPT, /* RCPT TO */ + SMTP_DATA, + SMTP_POSTDATA, + SMTP_QUIT, + SMTP_LAST /* never used */ +} smtpstate; + +/* smtp_conn is used for struct connection-oriented data in the connectdata + struct */ +struct smtp_conn { + struct pingpong pp; + struct SASL sasl; /* SASL-related storage */ + smtpstate state; /* Always use smtp.c:state() to change state! */ + char *domain; /* Client address/name to send in the EHLO */ + BIT(ssldone); /* Is connect() over SSL done? */ + BIT(tls_supported); /* StartTLS capability supported by server */ + BIT(size_supported); /* If server supports SIZE extension according to + RFC 1870 */ + BIT(utf8_supported); /* If server supports SMTPUTF8 extension according + to RFC 6531 */ + BIT(auth_supported); /* AUTH capability supported by server */ +}; + +/* This SMTP struct is used in the Curl_easy. All SMTP data that is + connection-oriented must be in smtp_conn to properly deal with the fact that + perhaps the Curl_easy is changed between the times the connection is + used. */ +struct SMTP { + curl_pp_transfer transfer; + char *custom; /* Custom Request */ + struct curl_slist *rcpt; /* Recipient list */ + int rcpt_last_error; /* The last error received for RCPT TO command */ + size_t eob; /* Number of bytes of the EOB (End Of Body) that + have been received so far */ + BIT(rcpt_had_ok); /* Whether any of RCPT TO commands (depends on + total number of recipients) succeeded so far */ + BIT(trailing_crlf); /* Specifies if the trailing CRLF is present */ +}; + +/*********************************************************************** + * + * smtp_parse_url_options() + * + * Parse the URL login options. + */ +static CURLcode smtp_parse_url_options(struct connectdata *conn, + struct smtp_conn *smtpc) +{ + CURLcode result = CURLE_OK; + const char *ptr = conn->options; + + while(!result && ptr && *ptr) { + const char *key = ptr; + const char *value; + + while(*ptr && *ptr != '=') + ptr++; + + value = ptr + 1; + + while(*ptr && *ptr != ';') + ptr++; + + if(curl_strnequal(key, "AUTH=", 5)) + result = Curl_sasl_parse_url_auth_option(&smtpc->sasl, + value, ptr - value); + else + result = CURLE_URL_MALFORMAT; + + if(*ptr == ';') + ptr++; + } + + return result; +} + +/*********************************************************************** + * + * smtp_parse_url_path() + * + * Parse the URL path into separate path components. + */ +static CURLcode smtp_parse_url_path(struct Curl_easy *data, + struct smtp_conn *smtpc) +{ + /* The SMTP struct is already initialized in smtp_connect() */ + const char *path = &data->state.up.path[1]; /* skip leading path */ + char localhost[HOSTNAME_MAX + 1]; + + /* Calculate the path if necessary */ + if(!*path) { + if(!Curl_gethostname(localhost, sizeof(localhost))) + path = localhost; + else + path = "localhost"; + } + + /* URL decode the path and use it as the domain in our EHLO */ + return Curl_urldecode(path, 0, &smtpc->domain, NULL, REJECT_CTRL); +} + +/*********************************************************************** + * + * smtp_parse_custom_request() + * + * Parse the custom request. + */ +static CURLcode smtp_parse_custom_request(struct Curl_easy *data, + struct SMTP *smtp) +{ + CURLcode result = CURLE_OK; + const char *custom = CURL_EASY_STR(data, STRING_CUSTOMREQUEST); + + /* URL decode the custom request */ + if(custom) + result = Curl_urldecode(custom, 0, &smtp->custom, NULL, REJECT_CTRL); + + return result; +} + +/*********************************************************************** + * + * smtp_parse_address() + * + * Parse the fully qualified mailbox address into a local address part and the + * hostname, converting the hostname to an IDN A-label, as per RFC-5890, if + * necessary. + * + * Parameters: + * + * fqma [in] - The fully qualified mailbox address (which may or + * may not contain UTF-8 characters). + * address [in/out] - A new allocated buffer which holds the local + * address part of the mailbox. This buffer must be + * free'ed by the caller. + * host [in/out] - The hostname structure that holds the original, + * and optionally encoded, hostname. + * Curl_free_idnconverted_hostname() must be called + * once the caller has finished with the structure. + * + * Returns CURLE_OK on success. + * + * Notes: + * + * Should a UTF-8 hostname require conversion to IDN ACE and we cannot honor + * that conversion then we shall return success. This allow the caller to send + * the data to the server as a U-label (as per RFC-6531 sect. 3.2). + * + * If an mailbox '@' separator cannot be located then the mailbox is considered + * to be either a local mailbox or an invalid mailbox (depending on what the + * calling function deems it to be) then the input will be returned in + * the address part with the hostname being NULL. + */ +static CURLcode smtp_parse_address(struct Curl_easy *data, const char *fqma, + char **address, struct hostname *host, + const char **suffix) +{ + CURLcode result = CURLE_OK; + size_t length; + char *addressend; + char *dup; + + /* A CR or LF in the address ends up verbatim in the MAIL FROM/RCPT TO + command line, so a crafted address could smuggle further SMTP commands + onto the wire. Reject it before the command is built. */ + if(strpbrk(fqma, "\r\n")) { + failf(data, "Refusing to send email address with a CR or LF"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + /* Duplicate the fully qualified email address so we can manipulate it, + ensuring it does not contain the delimiters if specified */ + dup = curlx_strdup(fqma[0] == '<' ? fqma + 1 : fqma); + if(!dup) + return CURLE_OUT_OF_MEMORY; + + if(fqma[0] != '<') { + length = strlen(dup); + if(length) { + if(dup[length - 1] == '>') + dup[length - 1] = '\0'; + } + } + else { + addressend = strrchr(dup, '>'); + if(addressend) { + *addressend = '\0'; + *suffix = addressend + 1; + } + } + + /* Extract the hostname from the address (if we can) */ + host->name = strpbrk(dup, "@"); + if(host->name) { + *host->name = '\0'; + host->name = host->name + 1; + + /* Attempt to convert the hostname to IDN ACE */ + (void)Curl_idnconvert_hostname(host); + + /* If Curl_idnconvert_hostname() fails then we shall attempt to continue + and send the hostname using UTF-8 rather than as 7-bit ACE (which is + our preference) */ + } + + /* Extract the local address from the mailbox */ + *address = dup; + + return result; +} + +struct cr_eob_ctx { + struct Curl_creader super; + struct bufq buf; + size_t n_eob; /* how many EOB bytes we matched so far */ + size_t eob; /* Number of bytes of the EOB (End Of Body) that + have been received so far */ + BIT(read_eos); /* we read an EOS from the next reader */ + BIT(processed_eos); /* we read and processed an EOS */ + BIT(eos); /* we have returned an EOS */ +}; + +static CURLcode cr_eob_init(struct Curl_easy *data, + struct Curl_creader *reader) +{ + struct cr_eob_ctx *ctx = reader->ctx; + (void)data; + /* The first char we read is the first on a line, as if we had + * read CRLF before */ + ctx->n_eob = 2; + Curl_bufq_init2(&ctx->buf, (16 * 1024), 1, BUFQ_OPT_SOFT_LIMIT); + return CURLE_OK; +} + +static void cr_eob_close(struct Curl_easy *data, struct Curl_creader *reader) +{ + struct cr_eob_ctx *ctx = reader->ctx; + (void)data; + Curl_bufq_free(&ctx->buf); +} + +/* this is the 5-bytes End-Of-Body marker for SMTP */ +#define SMTP_EOB "\r\n.\r\n" +#define SMTP_EOB_FIND_LEN 3 + +/* client reader doing SMTP End-Of-Body escaping. */ +static CURLcode cr_eob_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + struct cr_eob_ctx *ctx = reader->ctx; + CURLcode result = CURLE_OK; + size_t nread, i, start, n; + bool eos; + + if(!ctx->read_eos && Curl_bufq_is_empty(&ctx->buf)) { + /* Get more and convert it when needed */ + result = Curl_creader_read(data, reader->next, buf, blen, &nread, &eos); + CURL_TRC_SMTP(data, "cr_eob_read, next_read(len=%zu) -> %d, %zu eos=%d", + blen, (int)result, nread, eos); + if(result) + return result; + + ctx->read_eos = eos; + if(nread) { + if(!ctx->n_eob && !memchr(buf, SMTP_EOB[0], nread)) { + /* not in the middle of a match, no EOB start found, pass */ + *pnread = nread; + *peos = FALSE; + return CURLE_OK; + } + /* scan for EOB (continuation) and convert */ + for(i = start = 0; i < nread; ++i) { + if(ctx->n_eob >= SMTP_EOB_FIND_LEN) { + /* matched the EOB prefix and seeing additional char, add '.' */ + result = Curl_bufq_cwrite(&ctx->buf, buf + start, i - start, &n); + if(result) + return result; + result = Curl_bufq_cwrite(&ctx->buf, ".", 1, &n); + if(result) + return result; + ctx->n_eob = 0; + start = i; + if(data->state.infilesize > 0) + data->state.infilesize++; + } + + if(buf[i] != SMTP_EOB[ctx->n_eob]) + ctx->n_eob = 0; + + if(buf[i] == SMTP_EOB[ctx->n_eob]) { + /* matching another char of the EOB */ + ++ctx->n_eob; + } + } + + /* add any remainder to buf */ + if(start < nread) { + result = Curl_bufq_cwrite(&ctx->buf, buf + start, nread - start, &n); + if(result) + return result; + } + } + } + + *peos = FALSE; + + if(ctx->read_eos && !ctx->processed_eos) { + /* if we last matched a CRLF or if the data was empty, add ".\r\n" + * to end the body. If we sent something and it did not end with "\r\n", + * add "\r\n.\r\n" to end the body */ + const char *eob = SMTP_EOB; + CURL_TRC_SMTP(data, "auto-ending mail body with '\\r\\n.\\r\\n'"); + switch(ctx->n_eob) { + case 2: + /* seen a CRLF at the end, add the remainder */ + eob = &SMTP_EOB[2]; + break; + case 3: + /* ended with '\r\n.', we should escape the last '.' */ + eob = "." SMTP_EOB; + break; + default: + break; + } + result = Curl_bufq_cwrite(&ctx->buf, eob, strlen(eob), &n); + if(result) + return result; + ctx->processed_eos = TRUE; + } + + if(!Curl_bufq_is_empty(&ctx->buf)) { + result = Curl_bufq_cread(&ctx->buf, buf, blen, pnread); + } + else + *pnread = 0; + + if(ctx->read_eos && Curl_bufq_is_empty(&ctx->buf)) { + /* no more data, read all, done. */ + CURL_TRC_SMTP(data, "mail body complete, returning EOS"); + ctx->eos = TRUE; + } + *peos = (bool)ctx->eos; + DEBUGF(infof(data, "cr_eob_read(%zu) -> %d, %zu, %d", + blen, (int)result, *pnread, *peos)); + return result; +} + +static curl_off_t cr_eob_total_length(struct Curl_easy *data, + struct Curl_creader *reader) +{ + /* this reader changes length depending on input */ + (void)data; + (void)reader; + return -1; +} + +static const struct Curl_crtype cr_eob = { + "cr-smtp-eob", + cr_eob_init, + cr_eob_read, + cr_eob_close, + Curl_creader_def_needs_rewind, + cr_eob_total_length, + Curl_creader_def_resume_from, + Curl_creader_def_cntrl, + Curl_creader_def_is_paused, + Curl_creader_def_done, + sizeof(struct cr_eob_ctx) +}; + +static CURLcode cr_eob_add(struct Curl_easy *data) +{ + struct Curl_creader *reader = NULL; + CURLcode result; + + result = Curl_creader_create(&reader, data, &cr_eob, CURL_CR_CONTENT_ENCODE); + if(!result) + result = Curl_creader_add(data, reader); + + if(result && reader) + Curl_creader_free(data, reader); + return result; +} + +/*********************************************************************** + * + * smtp_endofresp() + * + * Checks for an ending SMTP status code at the start of the given string, but + * also detects various capabilities from the EHLO response including the + * supported authentication mechanisms. + */ +static bool smtp_endofresp(struct Curl_easy *data, struct connectdata *conn, + const char *line, size_t len, int *resp) +{ + struct smtp_conn *smtpc = Curl_conn_meta_get(conn, CURL_META_SMTP_CONN); + bool end = FALSE; + (void)data; + + DEBUGASSERT(smtpc); + if(!smtpc) + return FALSE; + + /* Nothing for us */ + if(len < 4 || !ISDIGIT(line[0]) || !ISDIGIT(line[1]) || !ISDIGIT(line[2])) + return FALSE; + + /* Do we have a command response? This should be the response code followed + by a space and optionally some text as per RFC-5321 and as outlined in + Section 4. Examples of RFC-4954 but some email servers ignore this and + only send the response code instead as per Section 4.2. */ + if(line[3] == ' ' || len == 5) { + char tmpline[6]; + curl_off_t code; + const char *p = tmpline; + end = TRUE; + memcpy(tmpline, line, (len == 5 ? 5 : 3)); + tmpline[len == 5 ? 5 : 3] = 0; + if(curlx_str_number(&p, &code, len == 5 ? 99999 : 999)) + return FALSE; + *resp = (int)code; + + /* Make sure real server never sends internal value */ + if(*resp == 1) + *resp = 0; + } + /* Do we have a multiline (continuation) response? */ + else if(line[3] == '-' && + (smtpc->state == SMTP_EHLO || smtpc->state == SMTP_COMMAND)) { + end = TRUE; + *resp = 1; /* Internal response code */ + } + + return end; +} + +/*********************************************************************** + * + * smtp_get_message() + * + * Gets the authentication message from the response buffer. + */ +static CURLcode smtp_get_message(struct Curl_easy *data, struct bufref *out) +{ + struct smtp_conn *smtpc = + Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN); + char *message; + size_t len; + + if(!smtpc) + return CURLE_FAILED_INIT; + + message = curlx_dyn_ptr(&smtpc->pp.recvbuf); + len = smtpc->pp.nfinal; + if(len > 4) { + /* Find the start of the message */ + len -= 4; + for(message += 4; ISBLANK(*message); message++, len--) + ; + + /* Find the end of the message */ + while(len--) + if(!ISNEWLINE(message[len]) && !ISBLANK(message[len])) + break; + + /* Terminate the message */ + message[++len] = '\0'; + Curl_bufref_set(out, message, len, NULL); + } + else + /* junk input => zero length output */ + Curl_bufref_set(out, "", 0, NULL); + + return CURLE_OK; +} + +/*********************************************************************** + * + * smtp_state() + * + * This is the ONLY way to change SMTP state! + */ +static void smtp_state(struct Curl_easy *data, + struct smtp_conn *smtpc, + smtpstate newstate) +{ +#ifdef CURLVERBOSE + /* for debug purposes */ + static const char * const names[] = { + "STOP", + "SERVERGREET", + "EHLO", + "HELO", + "STARTTLS", + "UPGRADETLS", + "AUTH", + "COMMAND", + "MAIL", + "RCPT", + "DATA", + "POSTDATA", + "QUIT", + /* LAST */ + }; + + if(smtpc->state != newstate) + CURL_TRC_SMTP(data, "state change from %s to %s", + names[smtpc->state], names[newstate]); +#else + (void)data; +#endif + + smtpc->state = newstate; +} + +/*********************************************************************** + * + * smtp_perform_ehlo() + * + * Sends the EHLO command to not only initialize communication with the ESMTP + * server but to also obtain a list of server side supported capabilities. + */ +static CURLcode smtp_perform_ehlo(struct Curl_easy *data, + struct smtp_conn *smtpc) +{ + CURLcode result = CURLE_OK; + + smtpc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanism yet */ + smtpc->sasl.authused = SASL_AUTH_NONE; /* Clear the authentication mechanism + used for esmtp connections */ + smtpc->tls_supported = FALSE; /* Clear the TLS capability */ + smtpc->auth_supported = FALSE; /* Clear the AUTH capability */ + + /* Send the EHLO command */ + result = Curl_pp_sendf(data, &smtpc->pp, "EHLO %s", smtpc->domain); + + if(!result) + smtp_state(data, smtpc, SMTP_EHLO); + + return result; +} + +/*********************************************************************** + * + * smtp_perform_helo() + * + * Sends the HELO command to initialize communication with the SMTP server. + */ +static CURLcode smtp_perform_helo(struct Curl_easy *data, + struct smtp_conn *smtpc) +{ + CURLcode result = CURLE_OK; + + smtpc->sasl.authused = SASL_AUTH_NONE; /* No authentication mechanism used + in smtp connections */ + + /* Send the HELO command */ + result = Curl_pp_sendf(data, &smtpc->pp, "HELO %s", smtpc->domain); + + if(!result) + smtp_state(data, smtpc, SMTP_HELO); + + return result; +} + +/*********************************************************************** + * + * smtp_perform_starttls() + * + * Sends the STLS command to start the upgrade to TLS. + */ +static CURLcode smtp_perform_starttls(struct Curl_easy *data, + struct smtp_conn *smtpc) +{ + /* Send the STARTTLS command */ + CURLcode result = Curl_pp_sendf(data, &smtpc->pp, "%s", "STARTTLS"); + + if(!result) + smtp_state(data, smtpc, SMTP_STARTTLS); + + return result; +} + +/*********************************************************************** + * + * smtp_perform_upgrade_tls() + * + * Performs the upgrade to TLS. + */ +static CURLcode smtp_perform_upgrade_tls(struct Curl_easy *data, + struct smtp_conn *smtpc) +{ +#ifdef USE_SSL + /* Start the SSL connection */ + struct connectdata *conn = data->conn; + CURLcode result; + bool ssldone = FALSE; + + DEBUGASSERT(smtpc->state == SMTP_UPGRADETLS); + if(!Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + result = Curl_ssl_cfilter_add( + data, Curl_conn_get_origin(conn, FIRSTSOCKET), conn, FIRSTSOCKET); + if(result) + goto out; + /* Change the connection handler and SMTP state */ + conn->scheme = &Curl_scheme_smtps; + } + + DEBUGASSERT(!smtpc->ssldone); + result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssldone); + DEBUGF(infof(data, "smtp_perform_upgrade_tls, connect -> %d, %d", + (int)result, ssldone)); + if(!result && ssldone) { + smtpc->ssldone = ssldone; + /* perform EHLO now, changes smtp->state out of SMTP_UPGRADETLS */ + result = smtp_perform_ehlo(data, smtpc); + } +out: + return result; +#else + (void)data; + (void)smtpc; + return CURLE_NOT_BUILT_IN; +#endif +} + +/*********************************************************************** + * + * smtp_perform_auth() + * + * Sends an AUTH command allowing the client to login with the given SASL + * authentication mechanism. + */ +static CURLcode smtp_perform_auth(struct Curl_easy *data, + const char *mech, + const struct bufref *initresp) +{ + CURLcode result = CURLE_OK; + struct smtp_conn *smtpc = + Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN); + const char *ir = Curl_bufref_ptr(initresp); + + if(!smtpc) + return CURLE_FAILED_INIT; + + if(ir) { /* AUTH <mech> ...<crlf> */ + /* Send the AUTH command with the initial response */ + result = Curl_pp_sendf(data, &smtpc->pp, "AUTH %s %s", + mech, *ir ? ir : "="); + } + else { + /* Send the AUTH command */ + result = Curl_pp_sendf(data, &smtpc->pp, "AUTH %s", mech); + } + + return result; +} + +/*********************************************************************** + * + * smtp_continue_auth() + * + * Sends SASL continuation data. + */ +static CURLcode smtp_continue_auth(struct Curl_easy *data, + const char *mech, + const struct bufref *resp) +{ + struct smtp_conn *smtpc = + Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN); + + (void)mech; + if(!smtpc) + return CURLE_FAILED_INIT; + return Curl_pp_sendf(data, &smtpc->pp, "%s", Curl_bufref_ptr(resp)); +} + +/*********************************************************************** + * + * smtp_cancel_auth() + * + * Sends SASL cancellation. + */ +static CURLcode smtp_cancel_auth(struct Curl_easy *data, const char *mech) +{ + struct smtp_conn *smtpc = + Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN); + + (void)mech; + if(!smtpc) + return CURLE_FAILED_INIT; + return Curl_pp_sendf(data, &smtpc->pp, "*"); +} + +/*********************************************************************** + * + * smtp_perform_authentication() + * + * Initiates the authentication sequence, with the appropriate SASL + * authentication mechanism. + */ +static CURLcode smtp_perform_authentication(struct Curl_easy *data, + struct smtp_conn *smtpc) +{ + CURLcode result = CURLE_OK; + saslprogress progress; + + /* Check we have enough data to authenticate with, and the + server supports authentication, and end the connect phase if not */ + if(!smtpc->auth_supported || + !Curl_sasl_can_authenticate(&smtpc->sasl, data)) { + smtp_state(data, smtpc, SMTP_STOP); + return result; + } + + /* Calculate the SASL login details */ + result = Curl_sasl_start(&smtpc->sasl, data, FALSE, &progress); + + if(!result) { + if(progress == SASL_INPROGRESS) + smtp_state(data, smtpc, SMTP_AUTH); + else + result = Curl_sasl_is_blocked(&smtpc->sasl, data); + } + + return result; +} + +/*********************************************************************** + * + * smtp_perform_command() + * + * Sends an SMTP based command. + */ +static CURLcode smtp_perform_command(struct Curl_easy *data, + struct smtp_conn *smtpc, + struct SMTP *smtp) +{ + CURLcode result = CURLE_OK; + + if(smtp->rcpt) { + /* We notify the server we are sending UTF-8 data if a) it supports the + SMTPUTF8 extension and b) The mailbox contains UTF-8 characters, in + either the local address or hostname parts. This is regardless of + whether the hostname is encoded using IDN ACE */ + bool utf8 = FALSE; + + if(!smtp->custom || !smtp->custom[0]) { + char *address = NULL; + struct hostname host = { NULL, NULL, NULL, NULL }; + const char *suffix = ""; + + /* Parse the mailbox to verify into the local address and hostname + parts, converting the hostname to an IDN A-label if necessary */ + result = smtp_parse_address(data, smtp->rcpt->data, + &address, &host, &suffix); + if(result) + return result; + + /* Establish whether we should report SMTPUTF8 to the server for this + mailbox as per RFC-6531 sect. 3.1 point 6 */ + utf8 = smtpc->utf8_supported && + (host.encalloc || + !Curl_is_ASCII_name(address) || + !Curl_is_ASCII_name(host.name)); + + /* Send the VRFY command (Note: The hostname part may be absent when the + host is a local system) */ + result = Curl_pp_sendf(data, &smtpc->pp, "VRFY %s%s%s%s", + address, + host.name ? "@" : "", + host.name ? host.name : "", + utf8 ? " SMTPUTF8" : ""); + + Curl_free_idnconverted_hostname(&host); + curlx_free(address); + } + else { + /* Establish whether we should report that we support SMTPUTF8 for EXPN + commands to the server as per RFC-6531 sect. 3.1 point 6 */ + utf8 = smtpc->utf8_supported && !strcmp(smtp->custom, "EXPN"); + + /* Send the custom recipient based command such as the EXPN command */ + result = Curl_pp_sendf(data, &smtpc->pp, + "%s %s%s", smtp->custom, + smtp->rcpt->data, + utf8 ? " SMTPUTF8" : ""); + } + } + else + /* Send the non-recipient based command such as HELP */ + result = Curl_pp_sendf(data, &smtpc->pp, "%s", + smtp->custom && smtp->custom[0] != '\0' ? + smtp->custom : "HELP"); + + if(!result) + smtp_state(data, smtpc, SMTP_COMMAND); + + return result; +} + +/*********************************************************************** + * + * smtp_perform_mail() + * + * Sends an MAIL command to initiate the upload of a message. + */ +static CURLcode smtp_perform_mail(struct Curl_easy *data, + struct smtp_conn *smtpc, + struct SMTP *smtp) +{ + char *from = NULL; + char *auth = NULL; + char *size = NULL; + const char *str; + CURLcode result = CURLE_OK; + + /* We notify the server we are sending UTF-8 data if a) it supports the + SMTPUTF8 extension and b) The mailbox contains UTF-8 characters, in + either the local address or hostname parts. This is regardless of + whether the hostname is encoded using IDN ACE */ + bool utf8 = FALSE; + + /* Calculate the FROM parameter */ + str = CURL_EASY_STR(data, STRING_MAIL_FROM); + if(str) { + char *address = NULL; + struct hostname host = { NULL, NULL, NULL, NULL }; + const char *suffix = ""; + + /* Parse the FROM mailbox into the local address and hostname parts, + converting the hostname to an IDN A-label if necessary */ + result = smtp_parse_address(data, str, &address, &host, &suffix); + if(result) + goto out; + + /* Establish whether we should report SMTPUTF8 to the server for this + mailbox as per RFC-6531 sect. 3.1 point 4 and sect. 3.4 */ + utf8 = smtpc->utf8_supported && + (host.encalloc || + !Curl_is_ASCII_name(address) || + !Curl_is_ASCII_name(host.name)); + + if(host.name) { + from = curl_maprintf("<%s@%s>%s", address, host.name, suffix); + + Curl_free_idnconverted_hostname(&host); + } + else + /* An invalid mailbox was provided but we let the server worry + about that and reply with a 501 error */ + from = curl_maprintf("<%s>%s", address, suffix); + + curlx_free(address); + } + else + /* Null reverse-path, RFC-5321, sect. 3.6.3 */ + from = curlx_strdup("<>"); + + if(!from) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + /* Calculate the optional AUTH parameter */ + str = CURL_EASY_STR(data, STRING_MAIL_AUTH); + if(str && smtpc->sasl.authused) { + if(str[0] != '\0') { + char *address = NULL; + struct hostname host = { NULL, NULL, NULL, NULL }; + const char *suffix = ""; + + /* Parse the AUTH mailbox into the local address and hostname parts, + converting the hostname to an IDN A-label if necessary */ + result = smtp_parse_address(data, str, &address, &host, &suffix); + if(result) + goto out; + + /* Establish whether we should report SMTPUTF8 to the server for this + mailbox as per RFC-6531 sect. 3.1 point 4 and sect. 3.4 */ + if(!utf8 && smtpc->utf8_supported && + (host.encalloc || + !Curl_is_ASCII_name(address) || + !Curl_is_ASCII_name(host.name))) + utf8 = TRUE; + + if(host.name) { + auth = curl_maprintf("<%s@%s>%s", address, host.name, suffix); + + Curl_free_idnconverted_hostname(&host); + } + else + /* An invalid mailbox was provided but we let the server worry + about it */ + auth = curl_maprintf("<%s>%s", address, suffix); + curlx_free(address); + } + else + /* Empty AUTH, RFC-2554, sect. 5 */ + auth = curlx_strdup("<>"); + + if(!auth) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + +#ifndef CURL_DISABLE_MIME + /* Prepare the mime data if some. */ + if(IS_MIME_POST(data)) { + curl_mimepart *postp = data->set.mimepostp; + + /* Use the whole structure as data. */ + postp->flags &= ~(unsigned int)MIME_BODY_ONLY; + + /* Add external headers and mime version. */ + curl_mime_headers(postp, data->set.headers, 0); + result = Curl_mime_prepare_headers(data, postp, NULL, + NULL, MIMESTRATEGY_MAIL); + + if(!result) + if(!Curl_checkheaders(data, STRCONST("Mime-Version"))) + result = Curl_mime_add_header(&postp->curlheaders, + "Mime-Version: 1.0"); + + if(!result) + result = Curl_creader_set_mime(data, postp); + if(result) + goto out; + data->state.infilesize = Curl_creader_total_length(data); + } + else +#endif + { + result = Curl_creader_set_fread(data, data->state.infilesize); + if(result) + goto out; + } + + /* Calculate the optional SIZE parameter */ + if(smtpc->size_supported && data->state.infilesize > 0) { + size = curl_maprintf("%" FMT_OFF_T, data->state.infilesize); + + if(!size) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + + /* If the mailboxes in the FROM and AUTH parameters do not include a UTF-8 + based address then quickly scan through the recipient list and check if + any there do, as we need to correctly identify our support for SMTPUTF8 + in the envelope, as per RFC-6531 sect. 3.4 */ + if(smtpc->utf8_supported && !utf8) { + struct curl_slist *rcpt = smtp->rcpt; + + while(rcpt && !utf8) { + /* Does the hostname contain non-ASCII characters? */ + if(!Curl_is_ASCII_name(rcpt->data)) + utf8 = TRUE; + + rcpt = rcpt->next; + } + } + + /* Add the client reader doing STMP EOB escaping */ + result = cr_eob_add(data); + if(result) + goto out; + + /* Send the MAIL command */ + result = Curl_pp_sendf(data, &smtpc->pp, + "MAIL FROM:%s%s%s%s%s%s", + from, /* Mandatory */ + auth ? " AUTH=" : "", /* Optional on AUTH support */ + auth ? auth : "", + size ? " SIZE=" : "", /* Optional on SIZE support */ + size ? size : "", + utf8 ? " SMTPUTF8" /* Internationalised mailbox */ + : ""); /* included in our envelope */ + +out: + curlx_free(from); + curlx_free(auth); + curlx_free(size); + + if(!result) + smtp_state(data, smtpc, SMTP_MAIL); + + return result; +} + +/*********************************************************************** + * + * smtp_perform_rcpt_to() + * + * Sends a RCPT TO command for a given recipient as part of the message upload + * process. + */ +static CURLcode smtp_perform_rcpt_to(struct Curl_easy *data, + struct smtp_conn *smtpc, + struct SMTP *smtp) +{ + CURLcode result = CURLE_OK; + char *address = NULL; + struct hostname host = { NULL, NULL, NULL, NULL }; + const char *suffix = ""; + + /* Parse the recipient mailbox into the local address and hostname parts, + converting the hostname to an IDN A-label if necessary */ + result = smtp_parse_address(data, smtp->rcpt->data, + &address, &host, &suffix); + if(result) + return result; + + /* Send the RCPT TO command */ + if(host.name) + result = Curl_pp_sendf(data, &smtpc->pp, "RCPT TO:<%s@%s>%s", + address, host.name, suffix); + else + /* An invalid mailbox was provided but we let the server worry about + that and reply with a 501 error */ + result = Curl_pp_sendf(data, &smtpc->pp, "RCPT TO:<%s>%s", + address, suffix); + + Curl_free_idnconverted_hostname(&host); + curlx_free(address); + + if(!result) + smtp_state(data, smtpc, SMTP_RCPT); + + return result; +} + +/*********************************************************************** + * + * smtp_perform_quit() + * + * Performs the quit action prior to sclose() being called. + */ +static CURLcode smtp_perform_quit(struct Curl_easy *data, + struct smtp_conn *smtpc) +{ + /* Send the QUIT command */ + CURLcode result = Curl_pp_sendf(data, &smtpc->pp, "%s", "QUIT"); + + if(!result) + smtp_state(data, smtpc, SMTP_QUIT); + + return result; +} + +/* For the initial server greeting */ +static CURLcode smtp_state_servergreet_resp(struct Curl_easy *data, + struct smtp_conn *smtpc, + int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; + + if(smtpcode / 100 != 2) { + failf(data, "Got unexpected smtp-server response: %d", smtpcode); + result = CURLE_WEIRD_SERVER_REPLY; + } + else + result = smtp_perform_ehlo(data, smtpc); + + return result; +} + +/* For STARTTLS responses */ +static CURLcode smtp_state_starttls_resp(struct Curl_easy *data, + struct smtp_conn *smtpc, + int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; + + /* Pipelining in response is forbidden. */ + if(smtpc->pp.overflow) + return CURLE_WEIRD_SERVER_REPLY; + + if(smtpcode != 220) { + if(data->set.use_ssl != CURLUSESSL_TRY) { + failf(data, "STARTTLS denied, code %d", smtpcode); + result = CURLE_USE_SSL_FAILED; + } + else + result = smtp_perform_authentication(data, smtpc); + } + else + smtp_state(data, smtpc, SMTP_UPGRADETLS); + + return result; +} + +/* For EHLO responses */ +static CURLcode smtp_state_ehlo_resp(struct Curl_easy *data, + struct smtp_conn *smtpc, + int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + const char *line = curlx_dyn_ptr(&smtpc->pp.recvbuf); + size_t len = smtpc->pp.nfinal; + + (void)instate; + + if(smtpcode / 100 != 2 && smtpcode != 1) { + if(data->set.use_ssl <= CURLUSESSL_TRY || + Curl_conn_is_ssl(data->conn, FIRSTSOCKET)) + result = smtp_perform_helo(data, smtpc); + else { + failf(data, "Remote access denied: %d", smtpcode); + result = CURLE_REMOTE_ACCESS_DENIED; + } + } + else if(len >= 4) { + line += 4; + len -= 4; + + /* Does the server support the STARTTLS capability? */ + if(len >= 8 && curl_strnequal(line, "STARTTLS", 8)) + smtpc->tls_supported = TRUE; + + /* Does the server support the SIZE capability? */ + else if(len >= 4 && curl_strnequal(line, "SIZE", 4)) + smtpc->size_supported = TRUE; + + /* Does the server support the UTF-8 capability? */ + else if(len >= 8 && curl_strnequal(line, "SMTPUTF8", 8)) + smtpc->utf8_supported = TRUE; + + /* Does the server support authentication? */ + else if(len >= 5 && curl_strnequal(line, "AUTH ", 5)) { + smtpc->auth_supported = TRUE; + + /* Advance past the AUTH keyword */ + line += 5; + len -= 5; + + /* Loop through the data line */ + for(;;) { + size_t llen; + size_t wordlen; + unsigned short mechbit; + + while(len && (ISBLANK(*line) || ISNEWLINE(*line))) { + line++; + len--; + } + + if(!len) + break; + + /* Extract the word */ + for(wordlen = 0; wordlen < len && !ISBLANK(line[wordlen]) && + !ISNEWLINE(line[wordlen]);) + wordlen++; + + /* Test the word for a matching authentication mechanism */ + mechbit = Curl_sasl_decode_mech(line, wordlen, &llen); + if(mechbit && llen == wordlen) + smtpc->sasl.authmechs |= mechbit; + + line += wordlen; + len -= wordlen; + } + } + + if(smtpcode != 1) { + if(data->set.use_ssl && !Curl_conn_is_ssl(data->conn, FIRSTSOCKET)) { + /* We do not have an SSL/TLS connection yet, but SSL is requested */ + if(smtpc->tls_supported) + /* Switch to TLS connection now */ + result = smtp_perform_starttls(data, smtpc); + else if(data->set.use_ssl == CURLUSESSL_TRY) + /* Fallback and carry on with authentication */ + result = smtp_perform_authentication(data, smtpc); + else { + failf(data, "STARTTLS not supported."); + result = CURLE_USE_SSL_FAILED; + } + } + else + result = smtp_perform_authentication(data, smtpc); + } + } + else { + failf(data, "Unexpectedly short EHLO response"); + result = CURLE_WEIRD_SERVER_REPLY; + } + + return result; +} + +/* For HELO responses */ +static CURLcode smtp_state_helo_resp(struct Curl_easy *data, + struct smtp_conn *smtpc, + int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; + + if(smtpcode / 100 != 2) { + failf(data, "Remote access denied: %d", smtpcode); + result = CURLE_REMOTE_ACCESS_DENIED; + } + else + /* End of connect phase */ + smtp_state(data, smtpc, SMTP_STOP); + + return result; +} + +/* For SASL authentication responses */ +static CURLcode smtp_state_auth_resp(struct Curl_easy *data, + struct smtp_conn *smtpc, + int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + saslprogress progress; + + (void)instate; + + result = Curl_sasl_continue(&smtpc->sasl, data, smtpcode, &progress); + if(!result) + switch(progress) { + case SASL_DONE: + smtp_state(data, smtpc, SMTP_STOP); /* Authenticated */ + break; + case SASL_IDLE: /* No mechanism left after cancellation */ + failf(data, "Authentication cancelled"); + result = CURLE_LOGIN_DENIED; + break; + default: + break; + } + + return result; +} + +/* For command responses */ +static CURLcode smtp_state_command_resp(struct Curl_easy *data, + struct smtp_conn *smtpc, + struct SMTP *smtp, + int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + const char *line = curlx_dyn_ptr(&smtpc->pp.recvbuf); + size_t len = smtpc->pp.nfinal; + + (void)instate; + + if((smtp->rcpt && smtpcode / 100 != 2 && smtpcode != 553 && smtpcode != 1) || + (!smtp->rcpt && smtpcode / 100 != 2 && smtpcode != 1)) { + failf(data, "Command failed: %d", smtpcode); + result = CURLE_WEIRD_SERVER_REPLY; + } + else { + if(!data->req.no_body) + result = Curl_client_write(data, CLIENTWRITE_BODY, line, len); + + if(!result && (smtpcode != 1)) { + if(smtp->rcpt) { + smtp->rcpt = smtp->rcpt->next; + + if(smtp->rcpt) { + /* Send the next command */ + result = smtp_perform_command(data, smtpc, smtp); + } + else + /* End of DO phase */ + smtp_state(data, smtpc, SMTP_STOP); + } + else + /* End of DO phase */ + smtp_state(data, smtpc, SMTP_STOP); + } + } + + return result; +} + +/* For MAIL responses */ +static CURLcode smtp_state_mail_resp(struct Curl_easy *data, + struct smtp_conn *smtpc, + struct SMTP *smtp, + int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; + + if(smtpcode / 100 != 2) { + failf(data, "MAIL failed: %d", smtpcode); + result = CURLE_SEND_ERROR; + } + else + /* Start the RCPT TO command */ + result = smtp_perform_rcpt_to(data, smtpc, smtp); + + return result; +} + +/* For RCPT responses */ +static CURLcode smtp_state_rcpt_resp(struct Curl_easy *data, + struct smtp_conn *smtpc, + struct SMTP *smtp, + int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + bool is_smtp_err = FALSE; + bool is_smtp_blocking_err = FALSE; + + (void)instate; + + is_smtp_err = (smtpcode / 100 != 2); + + /* If there are multiple RCPT TO commands to issue, it is possible to + ignore errors and proceed with only the valid addresses. */ + is_smtp_blocking_err = (is_smtp_err && !data->set.mail_rcpt_allowfails); + + if(is_smtp_err) { + /* Remembering the last failure which we can report if all "RCPT TO" have + failed and we cannot proceed. */ + smtp->rcpt_last_error = smtpcode; + + if(is_smtp_blocking_err) { + failf(data, "RCPT failed: %d", smtpcode); + result = CURLE_SEND_ERROR; + } + } + else { + /* Some RCPT TO commands have succeeded. */ + smtp->rcpt_had_ok = TRUE; + } + + if(!is_smtp_blocking_err) { + smtp->rcpt = smtp->rcpt->next; + + if(smtp->rcpt) + /* Send the next RCPT TO command */ + result = smtp_perform_rcpt_to(data, smtpc, smtp); + else { + /* We were not able to issue a successful RCPT TO command while going + over recipients (potentially multiple). Sending back last error. */ + if(!smtp->rcpt_had_ok) { + failf(data, "RCPT failed: %d (last error)", smtp->rcpt_last_error); + result = CURLE_SEND_ERROR; + } + else { + /* Send the DATA command */ + result = Curl_pp_sendf(data, &smtpc->pp, "%s", "DATA"); + + if(!result) + smtp_state(data, smtpc, SMTP_DATA); + } + } + } + + return result; +} + +/* For DATA response */ +static CURLcode smtp_state_data_resp(struct Curl_easy *data, + struct smtp_conn *smtpc, + int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + (void)instate; + + if(smtpcode != 354) { + failf(data, "DATA failed: %d", smtpcode); + result = CURLE_SEND_ERROR; + } + else { + /* Set the progress upload size */ + Curl_pgrsSetUploadSize(data, data->state.infilesize); + + /* SMTP upload */ + Curl_xfer_setup_send(data, FIRSTSOCKET); + + /* End of DO phase */ + smtp_state(data, smtpc, SMTP_STOP); + } + + return result; +} + +/* For POSTDATA responses, which are received after the entire DATA + part has been sent to the server */ +static CURLcode smtp_state_postdata_resp(struct Curl_easy *data, + struct smtp_conn *smtpc, + int smtpcode, + smtpstate instate) +{ + CURLcode result = CURLE_OK; + + (void)instate; + + if(smtpcode != 250) + result = CURLE_WEIRD_SERVER_REPLY; + + /* End of DONE phase */ + smtp_state(data, smtpc, SMTP_STOP); + + return result; +} + +static CURLcode smtp_pp_statemachine(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + int smtpcode; + struct smtp_conn *smtpc = Curl_conn_meta_get(conn, CURL_META_SMTP_CONN); + struct SMTP *smtp = Curl_meta_get(data, CURL_META_SMTP_EASY); + size_t nread = 0; + + if(!smtpc || !smtp) + return CURLE_FAILED_INIT; + + /* Busy upgrading the connection; right now all I/O is SSL/TLS, not SMTP */ +upgrade_tls: + if(smtpc->state == SMTP_UPGRADETLS) { + result = smtp_perform_upgrade_tls(data, smtpc); + if(result || (smtpc->state == SMTP_UPGRADETLS)) + return result; + } + + /* Flush any data that needs to be sent */ + if(smtpc->pp.sendleft) + return Curl_pp_flushsend(data, &smtpc->pp); + + do { + /* Read the response from the server */ + result = Curl_pp_readresp(data, FIRSTSOCKET, &smtpc->pp, + &smtpcode, &nread); + if(result) + return result; + + /* Store the latest response for later retrieval if necessary */ + if(smtpc->state != SMTP_QUIT && smtpcode != 1) + data->info.httpcode = smtpcode; + + if(!smtpcode) + break; + + /* We have now received a full SMTP server response */ + switch(smtpc->state) { + case SMTP_SERVERGREET: + result = smtp_state_servergreet_resp(data, smtpc, + smtpcode, smtpc->state); + break; + + case SMTP_EHLO: + result = smtp_state_ehlo_resp(data, smtpc, smtpcode, smtpc->state); + break; + + case SMTP_HELO: + result = smtp_state_helo_resp(data, smtpc, smtpcode, smtpc->state); + break; + + case SMTP_STARTTLS: + result = smtp_state_starttls_resp(data, smtpc, smtpcode, smtpc->state); + /* During UPGRADETLS, leave the read loop as we need to connect + * (e.g. TLS handshake) before we continue sending/receiving. */ + if(!result && (smtpc->state == SMTP_UPGRADETLS)) + goto upgrade_tls; + break; + + case SMTP_AUTH: + result = smtp_state_auth_resp(data, smtpc, smtpcode, smtpc->state); + break; + + case SMTP_COMMAND: + result = smtp_state_command_resp(data, smtpc, smtp, + smtpcode, smtpc->state); + break; + + case SMTP_MAIL: + result = smtp_state_mail_resp(data, smtpc, smtp, smtpcode, smtpc->state); + break; + + case SMTP_RCPT: + result = smtp_state_rcpt_resp(data, smtpc, smtp, smtpcode, smtpc->state); + break; + + case SMTP_DATA: + result = smtp_state_data_resp(data, smtpc, smtpcode, smtpc->state); + break; + + case SMTP_POSTDATA: + result = smtp_state_postdata_resp(data, smtpc, smtpcode, smtpc->state); + break; + + case SMTP_QUIT: + default: + /* internal error */ + smtp_state(data, smtpc, SMTP_STOP); + break; + } + } while(!result && smtpc->state != SMTP_STOP && + Curl_pp_moredata(&smtpc->pp)); + + return result; +} + +/* Called repeatedly until done from multi.c */ +static CURLcode smtp_multi_statemach(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct smtp_conn *smtpc = + Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN); + + *done = FALSE; + if(!smtpc) + return CURLE_FAILED_INIT; + + result = Curl_pp_statemach(data, &smtpc->pp, FALSE, FALSE); + *done = (smtpc->state == SMTP_STOP); + return result; +} + +static CURLcode smtp_block_statemach(struct Curl_easy *data, + struct smtp_conn *smtpc, + bool disconnecting) +{ + CURLcode result = CURLE_OK; + + while(smtpc->state != SMTP_STOP && !result) + result = Curl_pp_statemach(data, &smtpc->pp, TRUE, disconnecting); + + return result; +} + +/* For the SMTP "protocol connect" and "doing" phases only */ +static CURLcode smtp_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct smtp_conn *smtpc = + Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN); + return smtpc ? Curl_pp_pollset(data, &smtpc->pp, ps) : CURLE_OK; +} + +/* SASL parameters for the smtp protocol */ +static const struct SASLproto saslsmtp = { + "smtp", /* The service name */ + smtp_perform_auth, /* Send authentication command */ + smtp_continue_auth, /* Send authentication continuation */ + smtp_cancel_auth, /* Cancel authentication */ + smtp_get_message, /* Get SASL response message */ + 512 - 8, /* Max line len - strlen("AUTH ") - 1 space - CRLF */ + 334, /* Code received when continuation is expected */ + 235, /* Code to receive upon authentication success */ + SASL_AUTH_DEFAULT, /* Default mechanisms */ + SASL_FLAG_BASE64 /* Configuration flags */ +}; + +/*********************************************************************** + * + * smtp_connect() + * + * This function should do everything that is to be considered a part of + * the connection phase. + * + * The variable pointed to by 'done' will be TRUE if the protocol-layer + * connect phase is done when this function returns, or FALSE if not. + */ +static CURLcode smtp_connect(struct Curl_easy *data, bool *done) +{ + struct smtp_conn *smtpc = + Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN); + CURLcode result = CURLE_OK; + + *done = FALSE; /* default to not done yet */ + if(!smtpc) + return CURLE_FAILED_INIT; + + PINGPONG_SETUP(&smtpc->pp, smtp_pp_statemachine, smtp_endofresp); + + /* Initialize the SASL storage */ + Curl_sasl_init(&smtpc->sasl, data, &saslsmtp); + + /* Initialize the pingpong layer */ + Curl_pp_init(&smtpc->pp, Curl_pgrs_now(data)); + + /* Parse the URL options */ + result = smtp_parse_url_options(data->conn, smtpc); + if(result) + return result; + + /* Parse the URL path */ + result = smtp_parse_url_path(data, smtpc); + if(result) + return result; + + /* Start off waiting for the server greeting response */ + smtp_state(data, smtpc, SMTP_SERVERGREET); + + result = smtp_multi_statemach(data, done); + + return result; +} + +/*********************************************************************** + * + * smtp_done() + * + * The DONE function. This does what needs to be done after a single DO has + * performed. + * + * Input argument is already checked for validity. + */ +static CURLcode smtp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + struct smtp_conn *smtpc = + Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN); + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct SMTP *smtp = Curl_meta_get(data, CURL_META_SMTP_EASY); + + (void)premature; + + if(!smtpc) + return CURLE_FAILED_INIT; + if(!smtp) + return CURLE_OK; + + /* Cleanup our per-request based variables */ + curlx_safefree(smtp->custom); + + if(status) { + CURL_TRC_M(data, "SMTP done with bad status"); + connclose(conn); /* marked for closure */ + result = status; /* use the already set error code */ + } + else if(!data->set.connect_only && data->set.mail_rcpt && + (data->state.upload || IS_MIME_POST(data))) { + + smtp_state(data, smtpc, SMTP_POSTDATA); + + /* Run the state-machine */ + result = smtp_block_statemach(data, smtpc, FALSE); + } + + /* Clear the transfer mode for the next request */ + smtp->transfer = PPTRANSFER_BODY; + CURL_TRC_SMTP(data, "smtp_done(status=%d, premature=%d) -> %d", + (int)status, premature, (int)result); + return result; +} + +/*********************************************************************** + * + * smtp_perform() + * + * This is the actual DO function for SMTP. Transfer a mail, send a command + * or get some data according to the options previously setup. + */ +static CURLcode smtp_perform(struct Curl_easy *data, + struct smtp_conn *smtpc, + struct SMTP *smtp, + bool *connected, + bool *dophase_done) +{ + /* This is SMTP and no proxy */ + CURLcode result = CURLE_OK; + + CURL_TRC_SMTP(data, "smtp_perform(), start"); + + if(data->req.no_body) { + /* Requested no body means no transfer */ + smtp->transfer = PPTRANSFER_INFO; + } + + *dophase_done = FALSE; /* not done yet */ + + /* Store the first recipient (or NULL if not specified) */ + smtp->rcpt = data->set.mail_rcpt; + + /* Track of whether we have successfully sent at least one RCPT TO command */ + smtp->rcpt_had_ok = FALSE; + + /* Track of the last error we have received by sending RCPT TO command */ + smtp->rcpt_last_error = 0; + + /* Initial data character is the first character in line: it is implicitly + preceded by a virtual CRLF. */ + smtp->trailing_crlf = TRUE; + smtp->eob = 2; + + /* Start the first command in the DO phase */ + if((data->state.upload || IS_MIME_POST(data)) && data->set.mail_rcpt) + /* MAIL transfer */ + result = smtp_perform_mail(data, smtpc, smtp); + else + /* SMTP based command (VRFY, EXPN, NOOP, RSET or HELP) */ + result = smtp_perform_command(data, smtpc, smtp); + + if(result) + goto out; + + /* Run the state-machine */ + result = smtp_multi_statemach(data, dophase_done); + + *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET); + +out: + CURL_TRC_SMTP(data, "smtp_perform() -> %d, connected=%d, done=%d", + (int)result, *connected, *dophase_done); + return result; +} + +/* Call this when the DO phase has completed */ +static CURLcode smtp_dophase_done(struct Curl_easy *data, + struct SMTP *smtp, + bool connected) +{ + (void)connected; + + if(smtp->transfer != PPTRANSFER_BODY) + /* no data to transfer */ + Curl_xfer_setup_nop(data); + + return CURLE_OK; +} + +/*********************************************************************** + * + * smtp_regular_transfer() + * + * The input argument is already checked for validity. + * + * Performs all commands done before a regular transfer between a local and a + * remote host. + */ +static CURLcode smtp_regular_transfer(struct Curl_easy *data, + struct smtp_conn *smtpc, + struct SMTP *smtp, + bool *dophase_done) +{ + CURLcode result = CURLE_OK; + bool connected = FALSE; + + /* Make sure size is unknown at this point */ + data->req.size = -1; + + /* Set the progress data */ + Curl_pgrsReset(data); + + /* Carry out the perform */ + result = smtp_perform(data, smtpc, smtp, &connected, dophase_done); + + /* Perform post DO phase operations if necessary */ + if(!result && *dophase_done) + result = smtp_dophase_done(data, smtp, connected); + + CURL_TRC_SMTP(data, "smtp_regular_transfer() -> %d, done=%d", + (int)result, *dophase_done); + return result; +} + +/*********************************************************************** + * + * smtp_do() + * + * This function is registered as 'curl_do' function. It decodes the path + * parts etc as a wrapper to the actual DO function (smtp_perform). + * + * The input argument is already checked for validity. + */ +static CURLcode smtp_do(struct Curl_easy *data, bool *done) +{ + struct smtp_conn *smtpc = + Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN); + struct SMTP *smtp = Curl_meta_get(data, CURL_META_SMTP_EASY); + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + *done = FALSE; /* default to false */ + if(!smtpc || !smtp) + return CURLE_FAILED_INIT; + + /* Parse the custom request */ + result = smtp_parse_custom_request(data, smtp); + if(result) + return result; + + result = smtp_regular_transfer(data, smtpc, smtp, done); + CURL_TRC_SMTP(data, "smtp_do() -> %d, done=%d", (int)result, *done); + return result; +} + +/*********************************************************************** + * + * smtp_disconnect() + * + * Disconnect from an SMTP server. Cleanup protocol-specific per-connection + * resources. BLOCKING. + */ +static CURLcode smtp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + struct smtp_conn *smtpc = Curl_conn_meta_get(conn, CURL_META_SMTP_CONN); + + if(!smtpc) + return CURLE_FAILED_INIT; + + /* We cannot send quit unconditionally. If this connection is stale or + bad in any way, sending quit and waiting around here will make the + disconnect wait in vain and cause more problems than we need to. */ + + if(!dead_connection && conn->bits.protoconnstart && + !Curl_pp_needs_flush(data, &smtpc->pp)) { + if(!smtp_perform_quit(data, smtpc)) + (void)smtp_block_statemach(data, smtpc, TRUE); /* ignore on QUIT */ + } + + CURL_TRC_SMTP(data, "smtp_disconnect(), finished"); + return CURLE_OK; +} + +/* Called from multi.c while DOing */ +static CURLcode smtp_doing(struct Curl_easy *data, bool *dophase_done) +{ + struct SMTP *smtp = Curl_meta_get(data, CURL_META_SMTP_EASY); + CURLcode result; + + if(!smtp) + return CURLE_FAILED_INIT; + result = smtp_multi_statemach(data, dophase_done); + if(result) + DEBUGF(infof(data, "DO phase failed")); + else if(*dophase_done) { + result = smtp_dophase_done(data, smtp, FALSE /* not connected */); + + DEBUGF(infof(data, "DO phase is complete")); + } + + CURL_TRC_SMTP(data, "smtp_doing() -> %d, done=%d", (int)result, + *dophase_done); + return result; +} + +static void smtp_easy_dtor(void *key, size_t klen, void *entry) +{ + struct SMTP *smtp = entry; + (void)key; + (void)klen; + curlx_free(smtp); +} + +static void smtp_conn_dtor(void *key, size_t klen, void *entry) +{ + struct smtp_conn *smtpc = entry; + (void)key; + (void)klen; + Curl_pp_disconnect(&smtpc->pp); + curlx_safefree(smtpc->domain); + curlx_free(smtpc); +} + +static CURLcode smtp_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + struct smtp_conn *smtpc; + struct SMTP *smtp; + CURLcode result = CURLE_OK; + + smtpc = curlx_calloc(1, sizeof(*smtpc)); + if(!smtpc || + Curl_conn_meta_set(conn, CURL_META_SMTP_CONN, smtpc, smtp_conn_dtor)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + smtp = curlx_calloc(1, sizeof(*smtp)); + if(!smtp || + Curl_meta_set(data, CURL_META_SMTP_EASY, smtp, smtp_easy_dtor)) + result = CURLE_OUT_OF_MEMORY; + +out: + CURL_TRC_SMTP(data, "smtp_setup_connection() -> %d", (int)result); + return result; +} + +/* + * SMTP protocol handler. + */ +const struct Curl_protocol Curl_protocol_smtp = { + smtp_setup_connection, /* setup_connection */ + smtp_do, /* do_it */ + smtp_done, /* done */ + ZERO_NULL, /* do_more */ + smtp_connect, /* connect_it */ + smtp_multi_statemach, /* connecting */ + smtp_doing, /* doing */ + smtp_pollset, /* proto_pollset */ + smtp_pollset, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + smtp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#endif /* CURL_DISABLE_SMTP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/smtp.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/smtp.h new file mode 100644 index 0000000000..75b81979c2 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/smtp.h @@ -0,0 +1,30 @@ +#ifndef HEADER_CURL_SMTP_H +#define HEADER_CURL_SMTP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_SMTP +extern const struct Curl_protocol Curl_protocol_smtp; +#endif + +#endif /* HEADER_CURL_SMTP_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/sockaddr.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/sockaddr.h new file mode 100644 index 0000000000..916360d089 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/sockaddr.h @@ -0,0 +1,61 @@ +#ifndef HEADER_CURL_SOCKADDR_H +#define HEADER_CURL_SOCKADDR_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct Curl_sockaddr_storage { + union { + struct sockaddr sa; + struct sockaddr_in sa_in; +#ifdef USE_IPV6 + struct sockaddr_in6 sa_in6; +#endif +#ifdef HAVE_STRUCT_SOCKADDR_STORAGE + struct sockaddr_storage sa_stor; +#else + char cbuf[256]; /* this should be big enough to fit a lot */ +#endif + } buffer; +}; + +/* + * The Curl_sockaddr_ex structure is libcurl's external API curl_sockaddr + * structure with enough space available to directly hold any + * protocol-specific address structures. The variable declared here will be + * used to pass / receive data to/from the fopensocket callback if this has + * been set, before that, it is initialized from parameters. + */ +struct Curl_sockaddr_ex { + int family; + int socktype; + int protocol; + unsigned int addrlen; + union { + struct sockaddr sa; + struct Curl_sockaddr_storage buf; + } addr; +}; + +#endif /* HEADER_CURL_SOCKADDR_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/socketpair.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/socketpair.c new file mode 100644 index 0000000000..d4ac66e95e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/socketpair.c @@ -0,0 +1,364 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "socketpair.h" +#include "urldata.h" +#include "rand.h" +#include "curlx/nonblock.h" + +#ifndef CURL_DISABLE_SOCKETPAIR + +/* choose implementation */ +#ifdef USE_EVENTFD + +#include <sys/eventfd.h> + +static int wakeup_eventfd(curl_socket_t socks[2], bool nonblocking) +{ + int efd = eventfd(0, nonblocking ? EFD_CLOEXEC | EFD_NONBLOCK : EFD_CLOEXEC); + if(efd == -1) { + socks[0] = socks[1] = CURL_SOCKET_BAD; + return -1; + } + socks[0] = socks[1] = efd; + return 0; +} + +#elif defined(HAVE_PIPE) + +#ifdef HAVE_FCNTL +#include <fcntl.h> +#endif + +static int wakeup_pipe(curl_socket_t socks[2], bool nonblocking) +{ +#ifdef HAVE_PIPE2 + int flags = nonblocking ? O_NONBLOCK | O_CLOEXEC : O_CLOEXEC; + if(pipe2(socks, flags)) + return -1; +#else + if(pipe(socks)) + return -1; +#ifdef HAVE_FCNTL + if(fcntl(socks[0], F_SETFD, FD_CLOEXEC) || + fcntl(socks[1], F_SETFD, FD_CLOEXEC)) { + sclose(socks[0]); + sclose(socks[1]); + socks[0] = socks[1] = CURL_SOCKET_BAD; + return -1; + } +#endif + if(nonblocking) { + if(curlx_nonblock(socks[0], TRUE) < 0 || + curlx_nonblock(socks[1], TRUE) < 0) { + sclose(socks[0]); + sclose(socks[1]); + socks[0] = socks[1] = CURL_SOCKET_BAD; + return -1; + } + } +#endif + + return 0; +} + +#elif defined(HAVE_SOCKETPAIR) /* !USE_EVENTFD && !HAVE_PIPE */ + +#ifndef USE_UNIX_SOCKETS +#error "unsupported Unix domain and socketpair build combo" +#endif + +static int wakeup_socketpair(curl_socket_t socks[2], bool nonblocking) +{ + int type = SOCK_STREAM; +#ifdef SOCK_CLOEXEC + type |= SOCK_CLOEXEC; +#endif +#ifdef CURL_USE_SOCK_NONBLOCK + if(nonblocking) + type |= SOCK_NONBLOCK; +#endif + + if(CURL_SOCKETPAIR(AF_UNIX, type, 0, socks)) + return -1; +#ifndef CURL_USE_SOCK_NONBLOCK + if(nonblocking) { + if(curlx_nonblock(socks[0], TRUE) < 0 || + curlx_nonblock(socks[1], TRUE) < 0) { + sclose(socks[0]); + sclose(socks[1]); + socks[0] = socks[1] = CURL_SOCKET_BAD; + return -1; + } + } +#endif +#ifdef USE_SO_NOSIGPIPE + if(Curl_sock_nosigpipe(socks[1]) < 0) { + sclose(socks[0]); + sclose(socks[1]); + socks[0] = socks[1] = CURL_SOCKET_BAD; + return -1; + } +#endif /* USE_SO_NOSIGPIPE */ + + return 0; +} + +#else /* !USE_EVENTFD && !HAVE_PIPE && !HAVE_SOCKETPAIR */ + +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> /* for IPPROTO_TCP */ +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif + +#ifndef INADDR_LOOPBACK +#define INADDR_LOOPBACK 0x7f000001 +#endif + +#include "select.h" /* for Curl_poll */ + +static int wakeup_inet(curl_socket_t socks[2], bool nonblocking) +{ + union { + struct sockaddr_in inaddr; + struct sockaddr addr; + } a; + curl_socket_t listener; + curl_socklen_t addrlen = sizeof(a.inaddr); + int reuse = 1; + struct pollfd pfd[1]; + + listener = CURL_SOCKET(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if(listener == CURL_SOCKET_BAD) + return -1; + + memset(&a, 0, sizeof(a)); + a.inaddr.sin_family = AF_INET; + a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + a.inaddr.sin_port = 0; + + socks[0] = socks[1] = CURL_SOCKET_BAD; + +#if defined(_WIN32) || defined(__CYGWIN__) + /* do not set SO_REUSEADDR on Windows */ + (void)reuse; +#ifdef SO_EXCLUSIVEADDRUSE + { + int exclusive = 1; + if(setsockopt(listener, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, + (char *)&exclusive, (curl_socklen_t)sizeof(exclusive)) == -1) + goto error; + } +#endif +#else + if(setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, + (char *)&reuse, (curl_socklen_t)sizeof(reuse)) == -1) + goto error; +#endif + if(bind(listener, &a.addr, sizeof(a.inaddr)) == -1) + goto error; + if(getsockname(listener, &a.addr, &addrlen) == -1 || + addrlen < (int)sizeof(a.inaddr)) + goto error; + if(listen(listener, 1) == -1) + goto error; + socks[0] = CURL_SOCKET(AF_INET, SOCK_STREAM, 0); + if(socks[0] == CURL_SOCKET_BAD) + goto error; + if(connect(socks[0], &a.addr, sizeof(a.inaddr)) == -1) + goto error; + + /* use non-blocking accept to make sure we do not block forever */ + if(curlx_nonblock(listener, TRUE) < 0) + goto error; + pfd[0].fd = listener; + pfd[0].events = POLLIN; + pfd[0].revents = 0; + (void)Curl_poll(pfd, 1, 1000); /* one second */ + socks[1] = CURL_ACCEPT(listener, NULL, NULL); + if(socks[1] == CURL_SOCKET_BAD) + goto error; + else { + struct curltime start = curlx_now(); + char rnd[9]; + char check[sizeof(rnd)]; + char *p = &check[0]; + size_t s = sizeof(check); + + if(Curl_rand(NULL, (unsigned char *)rnd, sizeof(rnd))) + goto error; + + /* write data to the socket */ + swrite(socks[0], rnd, sizeof(rnd)); + /* verify that we read the correct data */ + do { + ssize_t nread; + + pfd[0].fd = socks[1]; + pfd[0].events = POLLIN; + pfd[0].revents = 0; + (void)Curl_poll(pfd, 1, 1000); /* one second */ + + nread = sread(socks[1], p, s); + if(nread == -1) { + int sockerr = SOCKERRNO; + /* Do not block forever */ + if(curlx_timediff_ms(curlx_now(), start) > (60 * 1000)) + goto error; + if(SOCK_EAGAIN(sockerr) +#ifndef USE_WINSOCK + || (sockerr == SOCKEINTR) || (sockerr == SOCKEINPROGRESS) +#endif + ) { + continue; + } + goto error; + } + s -= nread; + if(s) { + p += nread; + continue; + } + if(memcmp(rnd, check, sizeof(check))) + goto error; + break; + } while(1); + } + + if(nonblocking) + if(curlx_nonblock(socks[0], TRUE) < 0 || + curlx_nonblock(socks[1], TRUE) < 0) + goto error; +#ifdef USE_SO_NOSIGPIPE + if(Curl_sock_nosigpipe(socks[1]) < 0) + goto error; +#endif + sclose(listener); + return 0; + +error: + sclose(listener); + sclose(socks[0]); + sclose(socks[1]); + socks[0] = socks[1] = CURL_SOCKET_BAD; + return -1; +} + +#endif /* choose implementation */ + +int Curl_wakeup_init(curl_socket_t socks[2], bool nonblocking) +{ +#ifdef USE_EVENTFD + return wakeup_eventfd(socks, nonblocking); +#elif defined(HAVE_PIPE) + return wakeup_pipe(socks, nonblocking); +#elif defined(HAVE_SOCKETPAIR) + return wakeup_socketpair(socks, nonblocking); +#else + return wakeup_inet(socks, nonblocking); +#endif +} + +#if defined(USE_EVENTFD) || defined(HAVE_PIPE) + +#define wakeup_write write +#define wakeup_read read +#define wakeup_close close + +#else /* !USE_EVENTFD && !HAVE_PIPE */ + +#define wakeup_write swrite +#define wakeup_read sread +#define wakeup_close sclose + +#endif + +int Curl_wakeup_signal(curl_socket_t socks[2]) +{ + int sockerr = 0; +#ifdef USE_EVENTFD + const uint64_t buf[1] = { 1 }; +#else + const char buf[1] = { 1 }; +#endif + + while(1) { + sockerr = 0; + if(wakeup_write(socks[1], buf, sizeof(buf)) < 0) { + sockerr = SOCKERRNO; +#ifndef USE_WINSOCK + if(sockerr == SOCKEINTR) + continue; +#endif + if(SOCK_EAGAIN(sockerr)) + sockerr = 0; /* wakeup is already ongoing */ + } + break; + } + return sockerr; +} + +CURLcode Curl_wakeup_consume(curl_socket_t socks[2], bool all) +{ + char buf[64]; + ssize_t rc; + CURLcode result = CURLE_OK; + + do { + rc = wakeup_read(socks[0], buf, sizeof(buf)); + if(!rc) + break; + else if(rc < 0) { + int sockerr = SOCKERRNO; +#ifndef USE_WINSOCK + if(sockerr == SOCKEINTR) + continue; +#endif + if(SOCK_EAGAIN(sockerr)) + break; + result = CURLE_READ_ERROR; + break; + } + } while(all); + return result; +} + +void Curl_wakeup_destroy(curl_socket_t socks[2]) +{ +#ifndef USE_EVENTFD + if(socks[1] != CURL_SOCKET_BAD) + wakeup_close(socks[1]); +#endif + if(socks[0] != CURL_SOCKET_BAD) + wakeup_close(socks[0]); + socks[0] = socks[1] = CURL_SOCKET_BAD; +} + +#endif /* !CURL_DISABLE_SOCKETPAIR */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/socketpair.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/socketpair.h new file mode 100644 index 0000000000..fd08c879da --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/socketpair.h @@ -0,0 +1,43 @@ +#ifndef HEADER_CURL_SOCKETPAIR_H +#define HEADER_CURL_SOCKETPAIR_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_SOCKETPAIR + +/* return < 0 for failure to initialize */ +int Curl_wakeup_init(curl_socket_t socks[2], bool nonblocking); +void Curl_wakeup_destroy(curl_socket_t socks[2]); + +/* return 0 on success or errno on failure */ +int Curl_wakeup_signal(curl_socket_t socks[2]); + +CURLcode Curl_wakeup_consume(curl_socket_t socks[2], bool all); + +#else +#define Curl_wakeup_destroy(x) Curl_nop_stmt +#endif + +#endif /* HEADER_CURL_SOCKETPAIR_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/socks.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/socks.c new file mode 100644 index 0000000000..949f20c135 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/socks.c @@ -0,0 +1,1373 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_PROXY + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif + +#include "urldata.h" +#include "bufq.h" +#include "curl_addrinfo.h" +#include "curl_trc.h" +#include "select.h" +#include "cfilters.h" +#include "connect.h" +#include "socks.h" +#include "vdns/cf-dns.h" +#include "curlx/inet_pton.h" + +/* for the (SOCKS) connect state machine */ +enum socks_state_t { + SOCKS_ST_INIT, + /* SOCKS Version 4 states */ + SOCKS4_ST_START, + SOCKS4_ST_RESOLVING, + SOCKS4_ST_SEND, + SOCKS4_ST_RECV, + /* SOCKS Version 5 states */ + SOCKS5_ST_START, + SOCKS5_ST_REQ0_SEND, + SOCKS5_ST_RESP0_RECV, /* set up read */ + SOCKS5_ST_GSSAPI_INIT, + SOCKS5_ST_AUTH_INIT, /* setup outgoing auth buffer */ + SOCKS5_ST_AUTH_SEND, /* send auth */ + SOCKS5_ST_AUTH_RECV, /* read auth response */ + SOCKS5_ST_REQ1_INIT, /* init SOCKS "request" */ + SOCKS5_ST_RESOLVING, + SOCKS5_ST_REQ1_SEND, + SOCKS5_ST_RESP1_RECV, + /* Terminal states, all SOCKS versions */ + SOCKS_ST_SUCCESS, + SOCKS_ST_FAILED +}; + +#if defined(DEBUGBUILD) && defined(CURLVERBOSE) +static const char * const cf_socks_statename[] = { + "SOCKS_INIT", + "SOCKS4_START", + "SOCKS4_RESOLVING", + "SOCKS4_SEND", + "SOCKS4_RECV", + "SOCKS5_START", + "SOCKS5_REQ0_SEND", + "SOCKS5_RESP0_RECV", + "SOCKS5_GSSAPI_INIT", + "SOCKS5_AUTH_INIT", + "SOCKS5_AUTH_SEND", + "SOCKS5_AUTH_RECV", + "SOCKS5_REQ1_INIT", + "SOCKS5_RESOLVING", + "SOCKS5_REQ1_SEND", + "SOCKS5_RESP1_RECV", + "SOCKS_SUCCESS", + "SOCKS_FAILED" +}; +#endif + +#define SOCKS_CHUNK_SIZE 1024 +#define SOCKS_CHUNKS 1 + +struct socks_ctx { + enum socks_state_t state; + struct bufq iobuf; + struct Curl_peer *dest; + struct Curl_creds *creds; + CURLproxycode presult; + uint32_t resolv_id; + uint8_t ip_version; + uint8_t proxy_type; + unsigned char version; + BIT(resolve_local); + BIT(socks4a); +}; + +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) +/* + * Helper read-from-socket functions. Does the same as Curl_read() but it + * blocks until all bytes amount of buffersize will be read. No more, no less. + * + * This is STUPID BLOCKING behavior. Only used by the SOCKS GSSAPI functions. + */ +CURLcode Curl_blockread_all(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, /* store read data here */ + size_t blen, /* space in buf */ + size_t *pnread) /* amount bytes read */ +{ + size_t nread = 0; + CURLcode result; + + *pnread = 0; + for(;;) { + timediff_t timeout_ms = Curl_timeleft_ms(data); + curl_socket_t sock = Curl_conn_cf_get_socket(cf, data); + + if(timeout_ms < 0) { + /* we already got the timeout */ + return CURLE_OPERATION_TIMEDOUT; + } + if(!timeout_ms) + timeout_ms = TIMEDIFF_T_MAX; + if(SOCKET_READABLE(sock, timeout_ms) <= 0) + return CURLE_OPERATION_TIMEDOUT; + result = Curl_conn_cf_recv(cf->next, data, buf, blen, &nread); + if(result == CURLE_AGAIN) + continue; + else if(result) + return result; + + if(blen == nread) { + *pnread += nread; + return CURLE_OK; + } + if(!nread) /* EOF */ + return CURLE_RECV_ERROR; + + buf += nread; + blen -= nread; + *pnread += nread; + } +} +#endif + +#if defined(DEBUGBUILD) && defined(CURLVERBOSE) +#define sxstate(x, c, d, y) socksstate(x, c, d, y, __LINE__) +#else +#define sxstate(x, c, d, y) socksstate(x, c, d, y) +#endif + +/* always use this function to change state, to make debugging easier */ +static void socksstate(struct socks_ctx *sx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + enum socks_state_t state +#if defined(DEBUGBUILD) && defined(CURLVERBOSE) + , int lineno +#endif +) +{ + enum socks_state_t oldstate = sx->state; + + if(oldstate == state) + /* do not bother when the new state is the same as the old state */ + return; + + sx->state = state; + +#if defined(DEBUGBUILD) && defined(CURLVERBOSE) + CURL_TRC_CF(data, cf, "[%s] -> [%s] (line %d)", + cf_socks_statename[oldstate], + cf_socks_statename[sx->state], lineno); +#else + (void)cf; + (void)data; +#endif +} + +static CURLproxycode socks_failed(struct socks_ctx *sx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + CURLproxycode presult) +{ + sxstate(sx, cf, data, SOCKS_ST_FAILED); + sx->presult = presult; + return presult; +} + +static CURLproxycode socks_flush(struct socks_ctx *sx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + CURLcode result; + size_t nwritten; + + *done = FALSE; + while(!Curl_bufq_is_empty(&sx->iobuf)) { + result = Curl_cf_send_bufq(cf->next, data, &sx->iobuf, NULL, 0, + &nwritten); + if(result == CURLE_AGAIN) + return CURLPX_OK; + else if(result) { + failf(data, "Failed to send SOCKS request: %s", + curl_easy_strerror(result)); + return socks_failed(sx, cf, data, CURLPX_SEND_CONNECT); + } + } + *done = TRUE; + return CURLPX_OK; +} + +static CURLproxycode socks_recv(struct socks_ctx *sx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + size_t min_bytes, + bool *done) +{ + CURLcode result; + size_t nread; + + *done = FALSE; + while(Curl_bufq_len(&sx->iobuf) < min_bytes) { + result = Curl_cf_recv_bufq(cf->next, data, &sx->iobuf, + min_bytes - Curl_bufq_len(&sx->iobuf), + &nread); + if(result == CURLE_AGAIN) + return CURLPX_OK; + else if(result) { + failf(data, "Failed to receive SOCKS response: %s", + curl_easy_strerror(result)); + return CURLPX_RECV_CONNECT; + } + else if(!nread) { /* EOF */ + if(Curl_bufq_len(&sx->iobuf) < min_bytes) { + failf(data, "Failed to receive SOCKS response, " + "proxy closed connection"); + return CURLPX_RECV_CONNECT; + } + break; + } + } + *done = TRUE; + return CURLPX_OK; +} + +static CURLproxycode socks4_req_add_hd(struct socks_ctx *sx, + struct Curl_easy *data) +{ + unsigned char buf[4]; + size_t nwritten; + CURLcode result; + + (void)data; + buf[0] = 4; /* version (SOCKS4) */ + buf[1] = 1; /* connect */ + buf[2] = (unsigned char)((sx->dest->port >> 8) & 0xffU); /* MSB */ + buf[3] = (unsigned char)(sx->dest->port & 0xffU); /* LSB */ + + result = Curl_bufq_write(&sx->iobuf, buf, 4, &nwritten); + if(result || (nwritten != 4)) + return CURLPX_SEND_REQUEST; + return CURLPX_OK; +} + +static CURLproxycode socks4_req_add_user(struct socks_ctx *sx, + struct Curl_easy *data) +{ + CURLcode result; + size_t nwritten; + + if(sx->creds) { + size_t plen = strlen(sx->creds->user); + if(plen > 255) { + /* there is no real size limit to this field in the protocol, but + SOCKS5 limits the proxy user field to 255 bytes and it seems likely + that a longer field is either a mistake or malicious input */ + failf(data, "Too long SOCKS proxy username"); + return CURLPX_LONG_USER; + } + /* add proxy name WITH trailing zero */ + result = Curl_bufq_cwrite(&sx->iobuf, sx->creds->user, plen + 1, + &nwritten); + if(result || (nwritten != (plen + 1))) + return CURLPX_SEND_REQUEST; + } + else { + /* empty username */ + unsigned char b = 0; + result = Curl_bufq_write(&sx->iobuf, &b, 1, &nwritten); + if(result || (nwritten != 1)) + return CURLPX_SEND_REQUEST; + } + return CURLPX_OK; +} + +static CURLproxycode socks4_resolving(struct socks_ctx *sx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + const struct Curl_addrinfo *ai = NULL; + CURLcode result; + size_t nwritten; + + *done = FALSE; + result = Curl_conn_dns_addr_result(cf->conn, cf->sockindex, sx->dest); + if(result) { + if(result != CURLE_AGAIN) { + failf(data, "error %d resolving SOCKS destination %s:%u", + (int)result, sx->dest->hostname, sx->dest->port); + return CURLPX_RESOLVE_HOST; + } + return CURLPX_OK; + } + + ai = Curl_conn_dns_get_ai(data, sx->dest, cf->sockindex, AF_INET, 0); + if(ai) { + struct sockaddr_in *saddr_in; + char ipbuf[64]; + + Curl_printable_address(ai, ipbuf, sizeof(ipbuf)); + CURL_TRC_CF(data, cf, "SOCKS4 connect to IPv4 %s (locally resolved)", + ipbuf); + + saddr_in = (struct sockaddr_in *)(void *)ai->ai_addr; + result = Curl_bufq_write(&sx->iobuf, + (unsigned char *)&saddr_in->sin_addr.s_addr, 4, + &nwritten); + + if(result || (nwritten != 4)) + return CURLPX_SEND_REQUEST; + } + else { + /* No IPv4 address resolved */ + failf(data, "SOCKS4 connection to %s not supported", sx->dest->hostname); + return CURLPX_RESOLVE_HOST; + } + + *done = TRUE; + return CURLPX_OK; +} + +static CURLproxycode socks4_check_resp(struct socks_ctx *sx, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + const unsigned char *resp; + size_t rlen; + + if(!Curl_bufq_peek(&sx->iobuf, &resp, &rlen) || rlen < 8) { + failf(data, "SOCKS4 reply is incomplete."); + return CURLPX_RECV_CONNECT; + } + + DEBUGASSERT(rlen == 8); + /* + * Response format + * + * +----+----+----+----+----+----+----+----+ + * | VN | CD | DSTPORT | DSTIP | + * +----+----+----+----+----+----+----+----+ + * # of bytes: 1 1 2 4 + * + * VN is the version of the reply code and should be 0. CD is the result + * code with one of the following values: + * + * 90: request granted + * 91: request rejected or failed + * 92: request rejected because SOCKS server cannot connect to + * identd on the client + * 93: request rejected because the client program and identd + * report different user-ids + */ + + /* wrong version ? */ + if(resp[0]) { + failf(data, "SOCKS4 reply has wrong version, version should be 0."); + return CURLPX_BAD_VERSION; + } + + /* Result */ + switch(resp[1]) { + case 90: + CURL_TRC_CF(data, cf, "SOCKS4%s request granted.", sx->socks4a ? "a" : ""); + Curl_bufq_skip(&sx->iobuf, 8); + return CURLPX_OK; + case 91: + failf(data, + "[SOCKS] cannot complete SOCKS4 connection to %u.%u.%u.%u:%u. (%u)" + ", request rejected or failed.", + resp[4], resp[5], resp[6], resp[7], + (unsigned int)((resp[2] << 8) | resp[3]), resp[1]); + return CURLPX_REQUEST_FAILED; + case 92: + failf(data, + "[SOCKS] cannot complete SOCKS4 connection to %u.%u.%u.%u:%u. (%u)" + ", request rejected because SOCKS server cannot connect to " + "identd on the client.", + resp[4], resp[5], resp[6], resp[7], + (unsigned int)((resp[2] << 8) | resp[3]), resp[1]); + return CURLPX_IDENTD; + case 93: + failf(data, + "[SOCKS] cannot complete SOCKS4 connection to %u.%u.%u.%u:%u. (%u)" + ", request rejected because the client program and identd " + "report different user-ids.", + resp[4], resp[5], resp[6], resp[7], + (unsigned int)((resp[2] << 8) | resp[3]), resp[1]); + return CURLPX_IDENTD_DIFFER; + default: + failf(data, + "[SOCKS] cannot complete SOCKS4 connection to %u.%u.%u.%u:%u. (%u)" + ", Unknown.", + resp[4], resp[5], resp[6], resp[7], + (unsigned int)((resp[2] << 8) | resp[3]), resp[1]); + return CURLPX_UNKNOWN_FAIL; + } +} + +/* + * This function logs in to a SOCKS4 proxy and sends the specifics to the final + * destination server. + * + * Reference : + * https://www.openssh.com/txt/socks4.protocol + * + * Note : + * Set protocol4a=true for "SOCKS 4A (Simple Extension to SOCKS 4 Protocol)" + * Nonsupport "Identification Protocol (RFC1413)" + */ +static CURLproxycode socks4_connect(struct Curl_cfilter *cf, + struct socks_ctx *sx, + struct Curl_easy *data) +{ + size_t nwritten; + CURLproxycode presult; + CURLcode result; + bool done; + +process_state: + switch(sx->state) { + case SOCKS_ST_INIT: + sx->version = 4; + sxstate(sx, cf, data, SOCKS4_ST_START); + FALLTHROUGH(); + + case SOCKS4_ST_START: + Curl_bufq_reset(&sx->iobuf); + sx->socks4a = (sx->proxy_type == CURLPROXY_SOCKS4A); + sx->presult = CURLPX_OK; + + /* SOCKS4 can only do IPv4, insist! */ + sx->ip_version = CURL_IPRESOLVE_V4; + CURL_TRC_CF(data, cf, "SOCKS4%s connecting to %s:%u", + sx->socks4a ? "a" : "", + sx->dest->hostname, sx->dest->port); + + /* + * Compose socks4 request + * + * Request format + * + * +----+----+----+----+----+----+----+----+----+----+....+----+ + * | VN | CD | DSTPORT | DSTIP | USERID |NULL| + * +----+----+----+----+----+----+----+----+----+----+....+----+ + * # of bytes: 1 1 2 4 variable 1 + */ + presult = socks4_req_add_hd(sx, data); + if(presult) + return socks_failed(sx, cf, data, presult); + + /* DNS resolve only for SOCKS4, not SOCKS4a */ + if(!sx->resolve_local) { + /* socks4a, not resolving locally, sends the hostname. + * add an invalid address + user + hostname */ + unsigned char buf[4] = { 0, 0, 0, 1 }; + size_t hlen = strlen(sx->dest->hostname) + 1; /* including NUL */ + + if(hlen > 255) { + failf(data, "SOCKS4: too long hostname"); + return socks_failed(sx, cf, data, CURLPX_LONG_HOSTNAME); + } + result = Curl_bufq_write(&sx->iobuf, buf, 4, &nwritten); + if(result || (nwritten != 4)) + return socks_failed(sx, cf, data, CURLPX_SEND_REQUEST); + presult = socks4_req_add_user(sx, data); + if(presult) + return socks_failed(sx, cf, data, presult); + result = Curl_bufq_cwrite(&sx->iobuf, sx->dest->hostname, hlen, + &nwritten); + if(result || (nwritten != hlen)) + return socks_failed(sx, cf, data, CURLPX_SEND_REQUEST); + /* request complete */ + sxstate(sx, cf, data, SOCKS4_ST_SEND); + goto process_state; + } + sxstate(sx, cf, data, SOCKS4_ST_RESOLVING); + FALLTHROUGH(); + + case SOCKS4_ST_RESOLVING: + presult = socks4_resolving(sx, cf, data, &done); + if(presult) + return socks_failed(sx, cf, data, presult); + if(!done) + return CURLPX_OK; + /* append user */ + presult = socks4_req_add_user(sx, data); + if(presult) + return socks_failed(sx, cf, data, presult); + sxstate(sx, cf, data, SOCKS4_ST_SEND); + FALLTHROUGH(); + + case SOCKS4_ST_SEND: + presult = socks_flush(sx, cf, data, &done); + if(presult) + return socks_failed(sx, cf, data, presult); + else if(!done) + return CURLPX_OK; + sxstate(sx, cf, data, SOCKS4_ST_RECV); + FALLTHROUGH(); + + case SOCKS4_ST_RECV: + /* Receive 8-byte response */ + presult = socks_recv(sx, cf, data, 8, &done); + if(presult) + return socks_failed(sx, cf, data, presult); + else if(!done) + return CURLPX_OK; + presult = socks4_check_resp(sx, cf, data); + if(presult) + return socks_failed(sx, cf, data, presult); + sxstate(sx, cf, data, SOCKS_ST_SUCCESS); + FALLTHROUGH(); + + case SOCKS_ST_SUCCESS: + return CURLPX_OK; + + case SOCKS_ST_FAILED: + DEBUGASSERT(sx->presult); + return sx->presult; + + default: + DEBUGASSERT(0); + return socks_failed(sx, cf, data, CURLPX_SEND_REQUEST); + } +} + +static CURLproxycode socks5_req0_init(struct Curl_cfilter *cf, + struct socks_ctx *sx, + struct Curl_easy *data) +{ + const unsigned char auth = data->set.socks5auth; + unsigned char req[5]; /* version + len + 3 possible auth methods */ + unsigned char nauths; + size_t req_len, nwritten; + CURLcode result; + + (void)cf; + /* RFC1928 chapter 5 specifies max 255 chars for domain name in packet */ + if(!sx->resolve_local && strlen(sx->dest->hostname) > 255) { + failf(data, "SOCKS5: the destination hostname is too long to be " + "resolved remotely by the proxy."); + return CURLPX_LONG_HOSTNAME; + } + + if(auth & ~(CURLAUTH_BASIC | CURLAUTH_GSSAPI)) + infof(data, "warning: unsupported value passed to " + "CURLOPT_SOCKS5_AUTH: %u", auth); + if(!(auth & CURLAUTH_BASIC)) + /* disable username/password auth */ + Curl_creds_unlink(&sx->creds); + + req[0] = 5; /* version */ + nauths = 1; + req[1 + nauths] = 0; /* 1. no authentication */ +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + if(auth & CURLAUTH_GSSAPI) { + ++nauths; + req[1 + nauths] = 1; /* GSS-API */ + } +#endif + if(sx->creds) { + ++nauths; + req[1 + nauths] = 2; /* username/password */ + } + req[1] = nauths; + req_len = 2 + nauths; + + result = Curl_bufq_write(&sx->iobuf, req, req_len, &nwritten); + if(result || (nwritten != req_len)) + return CURLPX_SEND_REQUEST; + return CURLPX_OK; +} + +static CURLproxycode socks5_check_resp0(struct socks_ctx *sx, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + const unsigned char *resp; + unsigned char auth_mode; + size_t rlen; + + if(!Curl_bufq_peek(&sx->iobuf, &resp, &rlen) || rlen < 2) { + failf(data, "SOCKS5 initial reply is incomplete."); + return CURLPX_RECV_CONNECT; + } + + if(resp[0] != 5) { + failf(data, "Received invalid version in initial SOCKS5 response."); + return CURLPX_BAD_VERSION; + } + + auth_mode = resp[1]; + Curl_bufq_skip(&sx->iobuf, 2); + + switch(auth_mode) { + case 0: + /* DONE! No authentication needed. Send request. */ + sxstate(sx, cf, data, SOCKS5_ST_REQ1_INIT); + return CURLPX_OK; + case 1: + if(data->set.socks5auth & CURLAUTH_GSSAPI) { + sxstate(sx, cf, data, SOCKS5_ST_GSSAPI_INIT); + return CURLPX_OK; + } + failf(data, "SOCKS5 GSSAPI per-message authentication is not enabled."); + return CURLPX_GSSAPI_PERMSG; + case 2: + /* regular name + password authentication */ + if(data->set.socks5auth & CURLAUTH_BASIC) { + sxstate(sx, cf, data, SOCKS5_ST_AUTH_INIT); + return CURLPX_OK; + } + failf(data, "BASIC authentication proposed but not enabled."); + return CURLPX_NO_AUTH; + case 255: + failf(data, "No authentication method was acceptable."); + return CURLPX_NO_AUTH; + default: + failf(data, "Unknown SOCKS5 mode attempted to be used by server."); + return CURLPX_UNKNOWN_MODE; + } +} + +static CURLproxycode socks5_auth_init(struct Curl_cfilter *cf, + struct socks_ctx *sx, + struct Curl_easy *data) +{ + /* Needs username and password */ + size_t ulen = 0, plen = 0, nwritten; + unsigned char buf[2]; + CURLcode result; + + if(sx->creds) { + ulen = strlen(sx->creds->user); + plen = strlen(sx->creds->passwd); + /* the lengths must fit in a single byte */ + if(ulen > 255) { + failf(data, "Excessive username length for proxy auth"); + return CURLPX_LONG_USER; + } + if(plen > 255) { + failf(data, "Excessive password length for proxy auth"); + return CURLPX_LONG_PASSWD; + } + } + + /* username/password request looks like + * +----+------+----------+------+----------+ + * |VER | ULEN | UNAME | PLEN | PASSWD | + * +----+------+----------+------+----------+ + * | 1 | 1 | 1 to 255 | 1 | 1 to 255 | + * +----+------+----------+------+----------+ + */ + buf[0] = 1; /* username/pw subnegotiation version */ + buf[1] = (unsigned char)ulen; + result = Curl_bufq_write(&sx->iobuf, buf, 2, &nwritten); + if(result || (nwritten != 2)) + return CURLPX_SEND_REQUEST; + if(ulen) { + result = Curl_bufq_cwrite(&sx->iobuf, sx->creds->user, ulen, &nwritten); + if(result || (nwritten != ulen)) + return CURLPX_SEND_REQUEST; + } + buf[0] = (unsigned char)plen; + result = Curl_bufq_write(&sx->iobuf, buf, 1, &nwritten); + if(result || (nwritten != 1)) + return CURLPX_SEND_REQUEST; + if(plen) { + result = Curl_bufq_cwrite(&sx->iobuf, sx->creds->passwd, plen, &nwritten); + if(result || (nwritten != plen)) + return CURLPX_SEND_REQUEST; + } + sxstate(sx, cf, data, SOCKS5_ST_AUTH_SEND); + return CURLPX_OK; +} + +static CURLproxycode socks5_check_auth_resp(struct socks_ctx *sx, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + const unsigned char *resp; + unsigned char auth_status; + size_t rlen; + + (void)cf; + if(!Curl_bufq_peek(&sx->iobuf, &resp, &rlen) || rlen < 2) { + failf(data, "SOCKS5 sub-negotiation response incomplete."); + return CURLPX_RECV_CONNECT; + } + + /* ignore the first (VER) byte */ + auth_status = resp[1]; + if(auth_status) { + failf(data, "User was rejected by the SOCKS5 server (%d %d).", + resp[0], resp[1]); + return CURLPX_USER_REJECTED; + } + Curl_bufq_skip(&sx->iobuf, 2); + return CURLPX_OK; +} + +static CURLproxycode socks5_req1_init(struct socks_ctx *sx, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + unsigned char req[5]; + unsigned char ipbuf[16]; + const unsigned char *destination; + unsigned char desttype, destlen, hdlen; + size_t nwritten; + CURLcode result; + + req[0] = 5; /* version (SOCKS5) */ + req[1] = 1; /* connect */ + req[2] = 0; /* must be zero */ + if(sx->resolve_local) { + /* rest of request is added after resolving */ + result = Curl_bufq_write(&sx->iobuf, req, 3, &nwritten); + if(result || (nwritten != 3)) + return CURLPX_SEND_REQUEST; + return CURLPX_OK; + } + + /* remote resolving, send what type+addr/string to resolve */ +#ifdef USE_IPV6 + if(strchr(sx->dest->hostname, ':')) { + desttype = 4; + destination = ipbuf; + destlen = 16; + if(curlx_inet_pton(AF_INET6, sx->dest->hostname, ipbuf) != 1) + return CURLPX_BAD_ADDRESS_TYPE; + } + else +#endif + if(curlx_inet_pton(AF_INET, sx->dest->hostname, ipbuf) == 1) { + desttype = 1; + destination = ipbuf; + destlen = 4; + } + else { + const size_t hostname_len = strlen(sx->dest->hostname); + /* socks5_req0_init() already rejects hostnames longer than 255 bytes, so + this cast to unsigned char is safe. Assert to guard against future + refactoring that might remove or reorder that earlier check. */ + DEBUGASSERT(hostname_len <= 255); + desttype = 3; + destination = (const unsigned char *)sx->dest->hostname; + destlen = (unsigned char)hostname_len; /* 1-byte length */ + } + + req[3] = desttype; + req[4] = destlen; + hdlen = (desttype == 3) ? 5 : 4; /* no length byte for ip addresses */ + result = Curl_bufq_write(&sx->iobuf, req, hdlen, &nwritten); + if(result || (nwritten != hdlen)) + return CURLPX_SEND_REQUEST; + result = Curl_bufq_write(&sx->iobuf, destination, destlen, &nwritten); + if(result || (nwritten != destlen)) + return CURLPX_SEND_REQUEST; + /* PORT MSB+LSB */ + req[0] = (unsigned char)((sx->dest->port >> 8) & 0xff); + req[1] = (unsigned char)(sx->dest->port & 0xff); + result = Curl_bufq_write(&sx->iobuf, req, 2, &nwritten); + if(result || (nwritten != 2)) + return CURLPX_SEND_REQUEST; + CURL_TRC_CF(data, cf, "SOCKS5 connect to %s:%u (remotely resolved)", + sx->dest->hostname, sx->dest->port); + return CURLPX_OK; +} + +static CURLproxycode socks5_resolving(struct socks_ctx *sx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + const struct Curl_addrinfo *ai = NULL; + char dest[MAX_IPADR_LEN]; /* printable address */ + const unsigned char *destination = NULL; + unsigned char desttype = 1, destlen = 4; + unsigned char req[2]; + CURLcode result; + CURLproxycode presult = CURLPX_OK; + size_t nwritten; + + *done = FALSE; + result = Curl_conn_dns_addr_result(cf->conn, cf->sockindex, sx->dest); + if(result) { + if(result != CURLE_AGAIN) { + failf(data, "error %d resolving SOCKS destination %s:%u", + (int)result, sx->dest->hostname, sx->dest->port); + return CURLPX_RESOLVE_HOST; + } + return CURLPX_OK; + } + +#ifdef USE_IPV6 + if(data->set.ipver != CURL_IPRESOLVE_V4) + ai = Curl_conn_dns_get_ai(data, sx->dest, cf->sockindex, AF_INET6, 0); +#endif + if(!ai) + ai = Curl_conn_dns_get_ai(data, sx->dest, cf->sockindex, AF_INET, 0); + + if(!ai) { + failf(data, "Failed to resolve \"%s\" for SOCKS5 connect.", + sx->dest->hostname); + presult = CURLPX_RESOLVE_HOST; + goto out; + } + + Curl_printable_address(ai, dest, sizeof(dest)); + + if(ai->ai_family == AF_INET) { + struct sockaddr_in *saddr_in; + desttype = 1; /* ATYP: IPv4 = 1 */ + destlen = 4; + saddr_in = (struct sockaddr_in *)(void *)ai->ai_addr; + destination = (const unsigned char *)&saddr_in->sin_addr.s_addr; + CURL_TRC_CF(data, cf, "SOCKS5 connect to %s:%u (locally resolved)", + dest, sx->dest->port); + } +#ifdef USE_IPV6 + else if(ai->ai_family == AF_INET6) { + struct sockaddr_in6 *saddr_in6; + desttype = 4; /* ATYP: IPv6 = 4 */ + destlen = 16; + saddr_in6 = (struct sockaddr_in6 *)(void *)ai->ai_addr; + destination = (const unsigned char *)&saddr_in6->sin6_addr.s6_addr; + CURL_TRC_CF(data, cf, "SOCKS5 connect to [%s]:%u (locally resolved)", + dest, sx->dest->port); + } +#endif + + if(!destination) { + failf(data, "SOCKS5 connection to %s not supported", dest); + presult = CURLPX_RESOLVE_HOST; + goto out; + } + + req[0] = desttype; + result = Curl_bufq_write(&sx->iobuf, req, 1, &nwritten); + if(result || (nwritten != 1)) { + presult = CURLPX_SEND_REQUEST; + goto out; + } + result = Curl_bufq_write(&sx->iobuf, destination, destlen, &nwritten); + if(result || (nwritten != destlen)) { + presult = CURLPX_SEND_REQUEST; + goto out; + } + /* PORT MSB+LSB */ + req[0] = (unsigned char)((sx->dest->port >> 8) & 0xffU); + req[1] = (unsigned char)(sx->dest->port & 0xffU); + result = Curl_bufq_write(&sx->iobuf, req, 2, &nwritten); + if(result || (nwritten != 2)) { + presult = CURLPX_SEND_REQUEST; + goto out; + } + +out: + *done = (presult == CURLPX_OK); + return presult; +} + +static CURLproxycode socks5_recv_resp1(struct socks_ctx *sx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + const unsigned char *resp; + size_t rlen, resp_len = 8; /* minimum response length */ + CURLproxycode presult; + + presult = socks_recv(sx, cf, data, resp_len, done); + if(presult) + return presult; + else if(!*done) + return CURLPX_OK; + + if(!Curl_bufq_peek(&sx->iobuf, &resp, &rlen) || rlen < resp_len) { + failf(data, "SOCKS5 response is incomplete."); + return CURLPX_RECV_CONNECT; + } + + /* Response packet includes BND.ADDR is variable length parameter by RFC + 1928, so the response packet MUST be read until the end to avoid errors + at subsequent protocol level. + + +----+-----+-------+------+----------+----------+ + |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | + +----+-----+-------+------+----------+----------+ + | 1 | 1 | 0x00 | 1 | Variable | 2 | + +----+-----+-------+------+----------+----------+ + + ATYP: + o IPv4 address: 0x01, BND.ADDR = 4-byte + o domain name: 0x03, BND.ADDR = [ 1-byte length, string ] + o IPv6 address: 0x04, BND.ADDR = 16-byte + */ + if(resp[0] != 5) { /* version */ + failf(data, "SOCKS5 reply has wrong version, version should be 5."); + return CURLPX_BAD_VERSION; + } + else if(resp[1]) { /* Anything besides 0 is an error */ + CURLproxycode rc = CURLPX_REPLY_UNASSIGNED; + int code = resp[1]; + failf(data, "cannot complete SOCKS5 connection to %s. (%d)", + sx->dest->hostname, code); + if(code < 9) { + /* RFC 1928 section 6 lists: */ + static const CURLproxycode lookup[] = { + CURLPX_OK, + CURLPX_REPLY_GENERAL_SERVER_FAILURE, + CURLPX_REPLY_NOT_ALLOWED, + CURLPX_REPLY_NETWORK_UNREACHABLE, + CURLPX_REPLY_HOST_UNREACHABLE, + CURLPX_REPLY_CONNECTION_REFUSED, + CURLPX_REPLY_TTL_EXPIRED, + CURLPX_REPLY_COMMAND_NOT_SUPPORTED, + CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED, + }; + rc = lookup[code]; + } + return rc; + } + + /* Calculate real packet size */ + switch(resp[3]) { + case 1: /* IPv4 */ + resp_len = 4 + 4 + 2; + break; + case 3: /* domain name */ + resp_len = 4 + 1 + resp[4] + 2; /* header, var length, var bytes, port */ + break; + case 4: /* IPv6 */ + resp_len = 4 + 16 + 2; + break; + default: + failf(data, "SOCKS5 reply has wrong address type."); + return CURLPX_BAD_ADDRESS_TYPE; + } + + /* receive the rest of the response */ + presult = socks_recv(sx, cf, data, resp_len, done); + if(presult) + return presult; + else if(!*done) + return CURLPX_OK; + + if(!Curl_bufq_peek(&sx->iobuf, &resp, &rlen) || rlen < resp_len) { + failf(data, "SOCKS5 response is incomplete."); + return CURLPX_RECV_CONNECT; + } + /* got it all */ + *done = TRUE; + return CURLPX_OK; +} + +/* + * This function logs in to a SOCKS5 proxy and sends the specifics to the final + * destination server. + */ +static CURLproxycode socks5_connect(struct Curl_cfilter *cf, + struct socks_ctx *sx, + struct Curl_easy *data) +{ + CURLproxycode presult; + bool done; + +process_state: + switch(sx->state) { + case SOCKS_ST_INIT: + sx->version = 5; + sxstate(sx, cf, data, SOCKS5_ST_START); + FALLTHROUGH(); + + case SOCKS5_ST_START: + CURL_TRC_CF(data, cf, "SOCKS5: connecting to %s:%u", + sx->dest->hostname, sx->dest->port); + presult = socks5_req0_init(cf, sx, data); + if(presult) + return socks_failed(sx, cf, data, presult); + sxstate(sx, cf, data, SOCKS5_ST_REQ0_SEND); + FALLTHROUGH(); + + case SOCKS5_ST_REQ0_SEND: + presult = socks_flush(sx, cf, data, &done); + if(presult) + return socks_failed(sx, cf, data, presult); + else if(!done) + return CURLPX_OK; + /* done sending! */ + sxstate(sx, cf, data, SOCKS5_ST_RESP0_RECV); + FALLTHROUGH(); + + case SOCKS5_ST_RESP0_RECV: + presult = socks_recv(sx, cf, data, 2, &done); + if(presult) + return socks_failed(sx, cf, data, presult); + else if(!done) + return CURLPX_OK; + presult = socks5_check_resp0(sx, cf, data); + if(presult) + return socks_failed(sx, cf, data, presult); + /* socks5_check_resp0() sets next socks state */ + goto process_state; + + case SOCKS5_ST_GSSAPI_INIT: { +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + /* GSSAPI stuff done non-blocking */ + CURLcode result = Curl_SOCKS5_gssapi_negotiate(cf, data, sx->creds); + if(result) { + failf(data, "Unable to negotiate SOCKS5 GSS-API context."); + return CURLPX_GSSAPI; + } + sxstate(sx, cf, data, SOCKS5_ST_REQ1_INIT); + goto process_state; +#else + failf(data, "SOCKS5 GSSAPI per-message authentication is not supported."); + return socks_failed(sx, cf, data, CURLPX_GSSAPI_PERMSG); +#endif + } + + case SOCKS5_ST_AUTH_INIT: + presult = socks5_auth_init(cf, sx, data); + if(presult) + return socks_failed(sx, cf, data, presult); + sxstate(sx, cf, data, SOCKS5_ST_AUTH_SEND); + FALLTHROUGH(); + + case SOCKS5_ST_AUTH_SEND: + presult = socks_flush(sx, cf, data, &done); + if(presult) + return socks_failed(sx, cf, data, presult); + else if(!done) + return CURLPX_OK; + sxstate(sx, cf, data, SOCKS5_ST_AUTH_RECV); + FALLTHROUGH(); + + case SOCKS5_ST_AUTH_RECV: + presult = socks_recv(sx, cf, data, 2, &done); + if(presult) + return socks_failed(sx, cf, data, presult); + else if(!done) + return CURLPX_OK; + presult = socks5_check_auth_resp(sx, cf, data); + if(presult) + return socks_failed(sx, cf, data, presult); + /* Everything is good so far, user was authenticated! */ + sxstate(sx, cf, data, SOCKS5_ST_REQ1_INIT); + FALLTHROUGH(); + + case SOCKS5_ST_REQ1_INIT: + presult = socks5_req1_init(sx, cf, data); + if(presult) + return socks_failed(sx, cf, data, presult); + if(!sx->resolve_local) { + /* we do not resolve, request is complete */ + sxstate(sx, cf, data, SOCKS5_ST_REQ1_SEND); + goto process_state; + } + sxstate(sx, cf, data, SOCKS5_ST_RESOLVING); + FALLTHROUGH(); + + case SOCKS5_ST_RESOLVING: + presult = socks5_resolving(sx, cf, data, &done); + if(presult) + return socks_failed(sx, cf, data, presult); + if(!done) + return CURLPX_OK; + sxstate(sx, cf, data, SOCKS5_ST_REQ1_SEND); + FALLTHROUGH(); + + case SOCKS5_ST_REQ1_SEND: + presult = socks_flush(sx, cf, data, &done); + if(presult) + return socks_failed(sx, cf, data, presult); + else if(!done) + return CURLPX_OK; +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + if(cf->conn->socks5_gssapi_enctype) { + failf(data, "SOCKS5 GSS-API protection not yet implemented."); + return CURLPX_GSSAPI_PROTECTION; + } +#endif + sxstate(sx, cf, data, SOCKS5_ST_RESP1_RECV); + FALLTHROUGH(); + + case SOCKS5_ST_RESP1_RECV: + presult = socks5_recv_resp1(sx, cf, data, &done); + if(presult) + return socks_failed(sx, cf, data, presult); + if(!done) + return CURLPX_OK; + CURL_TRC_CF(data, cf, "SOCKS5 request granted."); + sxstate(sx, cf, data, SOCKS_ST_SUCCESS); + FALLTHROUGH(); + + case SOCKS_ST_SUCCESS: + return CURLPX_OK; + + case SOCKS_ST_FAILED: + DEBUGASSERT(sx->presult); + return sx->presult; + + default: + DEBUGASSERT(0); + return socks_failed(sx, cf, data, CURLPX_SEND_REQUEST); + } +} + +static void socks_proxy_ctx_free(struct socks_ctx *ctx) +{ + if(ctx) { + Curl_peer_unlink(&ctx->dest); + Curl_creds_unlink(&ctx->creds); + Curl_bufq_free(&ctx->iobuf); + curlx_free(ctx); + } +} + +/* After a TCP connection to the proxy has been verified, this function does + the next magic steps. If 'done' is not set TRUE, it is not done yet and + must be called again. + + Note: this function's sub-functions call failf() */ +static CURLcode socks_proxy_cf_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct socks_ctx *ctx = cf->ctx; + CURLproxycode pxresult = CURLPX_OK; + CURLcode result; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + result = cf->next->cft->do_connect(cf->next, data, done); + if(result || !*done) + return result; + + switch(ctx->proxy_type) { + case CURLPROXY_SOCKS5: + case CURLPROXY_SOCKS5_HOSTNAME: + pxresult = socks5_connect(cf, ctx, data); + break; + + case CURLPROXY_SOCKS4: + case CURLPROXY_SOCKS4A: + pxresult = socks4_connect(cf, ctx, data); + break; + + default: + DEBUGASSERT(0); /* should not come here, checked it at creation time */ + result = CURLE_COULDNT_CONNECT; + goto out; + } + + if(pxresult) { + result = CURLE_PROXY; + data->info.pxcode = (uint8_t)pxresult; + goto out; + } + else if(ctx->state != SOCKS_ST_SUCCESS) + goto out; + +#ifdef CURLVERBOSE + if(Curl_trc_is_verbose(data)) { + struct ip_quadruple ipquad; + bool is_ipv6; + if(!Curl_conn_cf_get_ip_info(cf->next, data, &is_ipv6, &ipquad)) + infof(data, "Opened %sSOCKS connection from %s port %d to %s port %d " + "(via %s port %u)", + (cf->sockindex == SECONDARYSOCKET) ? "2nd " : "", + ipquad.local_ip, ipquad.local_port, + ctx->dest->hostname, ctx->dest->port, + ipquad.remote_ip, ipquad.remote_port); + else + infof(data, "Opened %sSOCKS connection", + (cf->sockindex == SECONDARYSOCKET) ? "2nd " : ""); + } +#endif + cf->connected = TRUE; + +out: + *done = (bool)cf->connected; + if(*done || result) + Curl_creds_unlink(&ctx->creds); + return result; +} + +static CURLcode socks_cf_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct socks_ctx *sx = cf->ctx; + CURLcode result = CURLE_OK; + + if(!cf->connected && sx) { + /* If we are not connected, the filter below is and has nothing + * to wait on, we determine what to wait for. */ + curl_socket_t sock = Curl_conn_cf_get_socket(cf, data); + switch(sx->state) { + case SOCKS4_ST_SEND: + case SOCKS5_ST_REQ0_SEND: + case SOCKS5_ST_AUTH_SEND: + case SOCKS5_ST_REQ1_SEND: + CURL_TRC_CF(data, cf, "adjust pollset out (%d)", (int)sx->state); + result = Curl_pollset_set_out_only(data, ps, sock); + break; + default: + CURL_TRC_CF(data, cf, "adjust pollset in (%d)", (int)sx->state); + result = Curl_pollset_set_in_only(data, ps, sock); + break; + } + } + return result; +} + +static void socks_proxy_cf_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + (void)data; + socks_proxy_ctx_free(cf->ctx); + cf->ctx = NULL; +} + +static CURLcode socks_cf_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct socks_ctx *sx = cf->ctx; + + switch(query) { + case CF_QUERY_HOST_PORT: + if(sx) { + *pres1 = sx->dest->port; + *((const char **)pres2) = sx->dest->hostname; + return CURLE_OK; + } + break; + case CF_QUERY_ALPN_NEGOTIATED: { + const char **palpn = pres2; + DEBUGASSERT(palpn); + *palpn = NULL; + return CURLE_OK; + } + default: + break; + } + return cf->next ? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +struct Curl_cftype Curl_cft_socks_proxy = { + "SOCKS", + CF_TYPE_IP_CONNECT | CF_TYPE_PROXY, + 0, + socks_proxy_cf_destroy, + socks_proxy_cf_connect, + Curl_cf_def_shutdown, + socks_cf_adjust_pollset, + Curl_cf_def_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + socks_cf_query, +}; + +CURLcode Curl_cf_socks_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *dest, + uint8_t ip_version, + uint8_t proxy_type, + struct Curl_creds *creds) +{ + struct Curl_cfilter *cf; + struct socks_ctx *ctx; + bool resolve_local = FALSE; + uint8_t dns_queries = Curl_resolv_dns_queries(data, ip_version); + CURLcode result; + + if(!dest) + return CURLE_FAILED_INIT; + + switch(proxy_type) { + case CURLPROXY_SOCKS5: + resolve_local = TRUE; + break; + case CURLPROXY_SOCKS5_HOSTNAME: + break; + case CURLPROXY_SOCKS4: + resolve_local = TRUE; + dns_queries = (uint8_t)(dns_queries & ~CURL_DNSQ_AAAA); + break; + case CURLPROXY_SOCKS4A: + break; + default: + failf(data, "unknown proxytype %d option given", proxy_type); + return CURLE_COULDNT_CONNECT; + } + + /* NUL byte already part of struct size */ + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + return CURLE_OUT_OF_MEMORY; + } + + Curl_peer_link(&ctx->dest, dest); + ctx->ip_version = ip_version; + ctx->proxy_type = proxy_type; + ctx->resolve_local = resolve_local; + Curl_creds_link(&ctx->creds, creds); + Curl_bufq_init2(&ctx->iobuf, SOCKS_CHUNK_SIZE, SOCKS_CHUNKS, + BUFQ_OPT_SOFT_LIMIT); + + result = Curl_cf_create(&cf, &Curl_cft_socks_proxy, ctx); + if(!result) { + Curl_conn_cf_insert_after(cf_at, cf); + if(ctx->resolve_local) { + result = Curl_conn_dns_add_addr_resolve(data, cf_at->conn, + cf_at->sockindex, + ctx->dest, dns_queries, + TRNSPRT_TCP); + } + } + else + socks_proxy_ctx_free(ctx); + return result; +} + +#endif /* CURL_DISABLE_PROXY */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/socks.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/socks.h new file mode 100644 index 0000000000..d8e77c7f13 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/socks.h @@ -0,0 +1,69 @@ +#ifndef HEADER_CURL_SOCKS_H +#define HEADER_CURL_SOCKS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_PROXY + +struct Curl_peer; +struct Curl_creds; + +/* + * Helper read-from-socket functions. Does the same as Curl_read() but it + * blocks until all bytes amount of buffersize will be read. No more, no less. + * + * This is STUPID BLOCKING behavior + */ +CURLcode Curl_blockread_all(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, + size_t blen, + size_t *pnread); + +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) +/* + * This function handles the SOCKS5 GSS-API negotiation and initialization + */ +CURLcode Curl_SOCKS5_gssapi_negotiate(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct Curl_creds *creds); +#endif + +/* Insert a SOCKS filter after `cf_at` for connecting to `dest`. + * Credentials are optional and NOT duplicated and are + * expected to exist during connect phase. + */ +CURLcode Curl_cf_socks_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *dest, + uint8_t ip_version, + uint8_t proxy_type, + struct Curl_creds *creds); + +extern struct Curl_cftype Curl_cft_socks_proxy; + +#endif /* !CURL_DISABLE_PROXY */ + +#endif /* HEADER_CURL_SOCKS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/socks_gssapi.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/socks_gssapi.c new file mode 100644 index 0000000000..c1cfba5b71 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/socks_gssapi.c @@ -0,0 +1,601 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) Markus Moeller, <markus_moeller@compuserve.com> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(HAVE_GSSAPI) && !defined(CURL_DISABLE_PROXY) + +#include "curl_gssapi.h" +#include "urldata.h" +#include "curl_trc.h" +#include "cfilters.h" +#include "connect.h" +#include "curlx/nonblock.h" +#include "socks.h" +#include "curlx/strdup.h" + +#if defined(CURL_HAVE_DIAG) && defined(__APPLE__) && !defined(HAVE_GSSAPPLE) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + +#define MAX_GSS_LEN 1024 + +/* + * Helper GSS-API error functions. + */ +static int check_gss_err(struct Curl_easy *data, + OM_uint32 major_status, + OM_uint32 minor_status, + const char *function) +{ + if(GSS_ERROR(major_status)) { + OM_uint32 maj_stat, min_stat; + OM_uint32 msg_ctx = 0; + gss_buffer_desc status_string = GSS_C_EMPTY_BUFFER; + struct dynbuf dbuf; + + curlx_dyn_init(&dbuf, MAX_GSS_LEN); + msg_ctx = 0; + while(!msg_ctx) { + /* convert major status code (GSS-API error) to text */ + maj_stat = gss_display_status(&min_stat, major_status, + GSS_C_GSS_CODE, + GSS_C_NULL_OID, + &msg_ctx, &status_string); + if(maj_stat == GSS_S_COMPLETE) { + if(curlx_dyn_addn(&dbuf, status_string.value, status_string.length)) + return 1; /* error */ + gss_release_buffer(&min_stat, &status_string); + break; + } + gss_release_buffer(&min_stat, &status_string); + } + if(curlx_dyn_addn(&dbuf, ".\n", 2)) + return 1; /* error */ + msg_ctx = 0; + while(!msg_ctx) { + /* convert minor status code (underlying routine error) to text */ + maj_stat = gss_display_status(&min_stat, minor_status, + GSS_C_MECH_CODE, + GSS_C_NULL_OID, + &msg_ctx, &status_string); + if(maj_stat == GSS_S_COMPLETE) { + if(curlx_dyn_addn(&dbuf, status_string.value, status_string.length)) + return 1; /* error */ + gss_release_buffer(&min_stat, &status_string); + break; + } + gss_release_buffer(&min_stat, &status_string); + } + failf(data, "GSS-API error: %s failed: %s", function, + curlx_dyn_ptr(&dbuf)); + curlx_dyn_free(&dbuf); + return 1; + } + + return 0; +} + +static CURLcode socks5_gss_create_service_name(struct Curl_easy *data, + struct connectdata *conn, + const char *serviceptr, + gss_name_t *server) +{ + OM_uint32 gss_major_status, gss_minor_status, gss_status; + gss_buffer_desc service = GSS_C_EMPTY_BUFFER; + + /* prepare service name */ + if(strchr(serviceptr, '/')) { + service.length = strlen(serviceptr); + service.value = curlx_memdup(serviceptr, service.length); + if(!service.value) + return CURLE_OUT_OF_MEMORY; + + gss_major_status = gss_import_name(&gss_minor_status, &service, + (gss_OID)GSS_C_NULL_OID, server); + } + else { + service.value = curl_maprintf("%s@%s", serviceptr, + conn->socks_proxy.peer->hostname); + if(!service.value) + return CURLE_OUT_OF_MEMORY; + service.length = strlen(service.value); + + gss_major_status = gss_import_name(&gss_minor_status, &service, + GSS_C_NT_HOSTBASED_SERVICE, server); + } + + curlx_safefree(service.value); + service.length = 0; + + if(check_gss_err(data, gss_major_status, + gss_minor_status, "gss_import_name()")) { + failf(data, "Failed to create service name."); + gss_release_name(&gss_status, server); + return CURLE_COULDNT_CONNECT; + } + + return CURLE_OK; +} + +static CURLcode socks5_gss_auth_loop(struct Curl_cfilter *cf, + struct Curl_easy *data, + gss_name_t *server_ptr, + gss_ctx_id_t *gss_context, + OM_uint32 *gss_ret_flags) +{ + OM_uint32 gss_major_status, gss_minor_status, gss_status; + gss_buffer_desc gss_send_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc gss_recv_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc *gss_token = GSS_C_NO_BUFFER; + unsigned short us_length; + unsigned char socksreq[4]; + size_t actualread; + size_t nwritten; + CURLcode result; + + /* GSS-API request looks like + * +----+------+-----+----------------+ + * |VER | MTYP | LEN | TOKEN | + * +----+------+----------------------+ + * | 1 | 1 | 2 | up to 2^16 - 1 | + * +----+------+-----+----------------+ + */ + + /* As long as we need to keep sending some context info, and there is no + * errors, keep sending it... */ + for(;;) { + gss_major_status = Curl_gss_init_sec_context(data, + &gss_minor_status, + gss_context, + *server_ptr, + &Curl_krb5_mech_oid, + NULL, + gss_token, + &gss_send_token, + TRUE, + gss_ret_flags, + GSS_C_NO_CREDENTIAL); + + if(gss_token != GSS_C_NO_BUFFER) { + curlx_safefree(gss_recv_token.value); + gss_recv_token.length = 0; + } + if(check_gss_err(data, gss_major_status, + gss_minor_status, "gss_init_sec_context") || + /* the size needs to fit in a 16-bit field */ + (gss_send_token.length > 0xffff)) { + gss_release_name(&gss_status, server_ptr); + gss_release_buffer(&gss_status, &gss_send_token); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + failf(data, "Failed to initialize GSS-API token."); + return CURLE_COULDNT_CONNECT; + } + + if(gss_send_token.length) { + socksreq[0] = 1; /* GSS-API subnegotiation version */ + socksreq[1] = 1; /* authentication message type */ + us_length = htons((unsigned short)gss_send_token.length); + memcpy(socksreq + 2, &us_length, sizeof(short)); + + result = Curl_conn_cf_send(cf->next, data, socksreq, 4, FALSE, + &nwritten); + if(result || (nwritten != 4)) { + failf(data, "Failed to send GSS-API authentication request."); + gss_release_name(&gss_status, server_ptr); + gss_release_buffer(&gss_status, &gss_send_token); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + result = Curl_conn_cf_send(cf->next, data, + gss_send_token.value, + gss_send_token.length, FALSE, &nwritten); + if(result || (gss_send_token.length != nwritten)) { + failf(data, "Failed to send GSS-API authentication token."); + gss_release_name(&gss_status, server_ptr); + gss_release_buffer(&gss_status, &gss_send_token); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + } + + gss_release_buffer(&gss_status, &gss_send_token); + if(gss_major_status != GSS_S_CONTINUE_NEEDED) + break; + + /* analyze response */ + + /* GSS-API response looks like + * +----+------+-----+----------------+ + * |VER | MTYP | LEN | TOKEN | + * +----+------+----------------------+ + * | 1 | 1 | 2 | up to 2^16 - 1 | + * +----+------+-----+----------------+ + */ + + result = Curl_blockread_all(cf, data, (char *)socksreq, 4, &actualread); + if(result || (actualread != 4)) { + failf(data, "Failed to receive GSS-API authentication response."); + gss_release_name(&gss_status, server_ptr); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + /* ignore the first (VER) byte */ + if(socksreq[1] == 255) { /* status / message type */ + failf(data, "User was rejected by the SOCKS5 server (%d %d).", + socksreq[0], socksreq[1]); + gss_release_name(&gss_status, server_ptr); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + if(socksreq[1] != 1) { /* status / message type */ + failf(data, "Invalid GSS-API authentication response type (%d %d).", + socksreq[0], socksreq[1]); + gss_release_name(&gss_status, server_ptr); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + memcpy(&us_length, socksreq + 2, sizeof(short)); + us_length = ntohs(us_length); + + if(!us_length) { + failf(data, "Invalid zero-length GSS-API authentication token."); + gss_release_name(&gss_status, server_ptr); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + gss_recv_token.length = us_length; + gss_recv_token.value = curlx_malloc(gss_recv_token.length); + if(!gss_recv_token.value) { + failf(data, + "Could not allocate memory for GSS-API authentication " + "response token."); + gss_release_name(&gss_status, server_ptr); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_OUT_OF_MEMORY; + } + + result = Curl_blockread_all(cf, data, (char *)gss_recv_token.value, + gss_recv_token.length, &actualread); + + if(result || (actualread != us_length)) { + failf(data, "Failed to receive GSS-API authentication token."); + gss_release_name(&gss_status, server_ptr); + curlx_safefree(gss_recv_token.value); + gss_recv_token.length = 0; + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + gss_token = &gss_recv_token; + } + + gss_release_name(&gss_status, server_ptr); + return CURLE_OK; +} + +static CURLcode socks5_gss_auth_verify(struct Curl_easy *data, + gss_ctx_id_t *gss_context) +{ + OM_uint32 gss_major_status, gss_minor_status, gss_status; + gss_name_t gss_client_name = GSS_C_NO_NAME; + gss_buffer_desc gss_send_token = GSS_C_EMPTY_BUFFER; + + /* Everything is good so far, user was authenticated! */ + gss_major_status = gss_inquire_context(&gss_minor_status, *gss_context, + &gss_client_name, NULL, NULL, NULL, + NULL, NULL, NULL); + if(check_gss_err(data, gss_major_status, + gss_minor_status, "gss_inquire_context")) { + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + gss_release_name(&gss_status, &gss_client_name); + failf(data, "Failed to determine username."); + return CURLE_COULDNT_CONNECT; + } + gss_major_status = gss_display_name(&gss_minor_status, gss_client_name, + &gss_send_token, NULL); + if(check_gss_err(data, gss_major_status, + gss_minor_status, "gss_display_name")) { + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + gss_release_name(&gss_status, &gss_client_name); + gss_release_buffer(&gss_status, &gss_send_token); + failf(data, "Failed to determine username."); + return CURLE_COULDNT_CONNECT; + } + + infof(data, "SOCKS5 server authenticated user %.*s with GSS-API.", + (int)gss_send_token.length, (const char *)gss_send_token.value); + + gss_release_name(&gss_status, &gss_client_name); + gss_release_buffer(&gss_status, &gss_send_token); + + return CURLE_OK; +} + +static CURLcode socks5_gss_negotiate_enc(struct Curl_cfilter *cf, + struct Curl_easy *data, + gss_ctx_id_t *gss_context, + OM_uint32 gss_ret_flags) +{ + struct connectdata *conn = cf->conn; + OM_uint32 gss_major_status, gss_minor_status, gss_status; + gss_buffer_desc gss_send_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc gss_recv_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc gss_w_token = GSS_C_EMPTY_BUFFER; + unsigned short us_length; + unsigned char socksreq[4]; + size_t actualread; + size_t nwritten; + CURLcode result; + int gss_enc; + + /* Do encryption */ + socksreq[0] = 1; /* GSS-API subnegotiation version */ + socksreq[1] = 2; /* encryption message type */ + + gss_enc = 0; /* no data protection */ + /* do confidentiality protection if supported */ + if(gss_ret_flags & GSS_C_CONF_FLAG) + gss_enc = 2; + /* else do integrity protection */ + else if(gss_ret_flags & GSS_C_INTEG_FLAG) + gss_enc = 1; + + infof(data, "SOCKS5 server supports GSS-API %s data protection.", + (gss_enc == 0) ? "no" : + ((gss_enc == 1) ? "integrity" : "confidentiality")); + + /* + * Sending the encryption type in clear seems wrong. It should be + * protected with gss_seal()/gss_wrap(). See RFC1961 extract below + * The NEC reference implementations on which this is based is + * therefore at fault + * + * +------+------+------+.......................+ + * + ver | mtyp | len | token | + * +------+------+------+.......................+ + * + 0x01 | 0x02 | 0x02 | up to 2^16 - 1 octets | + * +------+------+------+.......................+ + * + * Where: + * + * - "ver" is the protocol version number, here 1 to represent the + * first version of the SOCKS/GSS-API protocol + * + * - "mtyp" is the message type, here 2 to represent a protection + * -level negotiation message + * + * - "len" is the length of the "token" field in octets + * + * - "token" is the GSS-API encapsulated protection level + * + * The token is produced by encapsulating an octet containing the + * required protection level using gss_seal()/gss_wrap() with conf_req + * set to FALSE. The token is verified using gss_unseal()/ + * gss_unwrap(). + * + */ + if(data->set.socks5_gssapi_nec) { + us_length = htons((short)1); + memcpy(socksreq + 2, &us_length, sizeof(short)); + } + else { + gss_send_token.length = 1; + gss_send_token.value = curlx_memdup(&gss_enc, gss_send_token.length); + if(!gss_send_token.value) { + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_OUT_OF_MEMORY; + } + + gss_major_status = gss_wrap(&gss_minor_status, *gss_context, 0, + GSS_C_QOP_DEFAULT, &gss_send_token, + NULL, &gss_w_token); + + if(check_gss_err(data, gss_major_status, gss_minor_status, "gss_wrap")) { + curlx_safefree(gss_send_token.value); + gss_send_token.length = 0; + gss_release_buffer(&gss_status, &gss_w_token); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + failf(data, "Failed to wrap GSS-API encryption value into token."); + return CURLE_COULDNT_CONNECT; + } + curlx_safefree(gss_send_token.value); + gss_send_token.length = 0; + + us_length = htons((unsigned short)gss_w_token.length); + memcpy(socksreq + 2, &us_length, sizeof(short)); + } + + result = Curl_conn_cf_send(cf->next, data, socksreq, 4, FALSE, &nwritten); + if(result || (nwritten != 4)) { + failf(data, "Failed to send GSS-API encryption request."); + gss_release_buffer(&gss_status, &gss_w_token); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + if(data->set.socks5_gssapi_nec) { + memcpy(socksreq, &gss_enc, 1); + result = Curl_conn_cf_send(cf->next, data, socksreq, 1, FALSE, &nwritten); + if(result || (nwritten != 1)) { + failf(data, "Failed to send GSS-API encryption type."); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + } + else { + result = Curl_conn_cf_send(cf->next, data, gss_w_token.value, + gss_w_token.length, FALSE, &nwritten); + if(result || (gss_w_token.length != nwritten)) { + failf(data, "Failed to send GSS-API encryption type."); + gss_release_buffer(&gss_status, &gss_w_token); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + gss_release_buffer(&gss_status, &gss_w_token); + } + + result = Curl_blockread_all(cf, data, (char *)socksreq, 4, &actualread); + if(result || (actualread != 4)) { + failf(data, "Failed to receive GSS-API encryption response."); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + /* ignore the first (VER) byte */ + if(socksreq[1] == 255) { /* status / message type */ + failf(data, "User was rejected by the SOCKS5 server (%d %d).", + socksreq[0], socksreq[1]); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + if(socksreq[1] != 2) { /* status / message type */ + failf(data, "Invalid GSS-API encryption response type (%d %d).", + socksreq[0], socksreq[1]); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + memcpy(&us_length, socksreq + 2, sizeof(short)); + us_length = ntohs(us_length); + + if(!us_length) { + failf(data, "Invalid zero-length GSS-API encryption token."); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + gss_recv_token.length = us_length; + gss_recv_token.value = curlx_malloc(gss_recv_token.length); + if(!gss_recv_token.value) { + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_OUT_OF_MEMORY; + } + result = Curl_blockread_all(cf, data, (char *)gss_recv_token.value, + gss_recv_token.length, &actualread); + + if(result || (actualread != us_length)) { + failf(data, "Failed to receive GSS-API encryption type."); + curlx_safefree(gss_recv_token.value); + gss_recv_token.length = 0; + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + if(!data->set.socks5_gssapi_nec) { + gss_major_status = gss_unwrap(&gss_minor_status, *gss_context, + &gss_recv_token, &gss_w_token, + NULL, NULL); + + if(check_gss_err(data, gss_major_status, gss_minor_status, "gss_unwrap")) { + curlx_safefree(gss_recv_token.value); + gss_recv_token.length = 0; + gss_release_buffer(&gss_status, &gss_w_token); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + failf(data, "Failed to unwrap GSS-API encryption value into token."); + return CURLE_COULDNT_CONNECT; + } + curlx_safefree(gss_recv_token.value); + gss_recv_token.length = 0; + + if(gss_w_token.length != 1) { + failf(data, "Invalid GSS-API encryption response length (%zu).", + gss_w_token.length); + gss_release_buffer(&gss_status, &gss_w_token); + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + memcpy(socksreq, gss_w_token.value, gss_w_token.length); + gss_release_buffer(&gss_status, &gss_w_token); + } + else { + if(gss_recv_token.length != 1) { + failf(data, "Invalid GSS-API encryption response length (%zu).", + gss_recv_token.length); + curlx_safefree(gss_recv_token.value); + gss_recv_token.length = 0; + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + return CURLE_COULDNT_CONNECT; + } + + memcpy(socksreq, gss_recv_token.value, gss_recv_token.length); + curlx_safefree(gss_recv_token.value); + gss_recv_token.length = 0; + } + + infof(data, "SOCKS5 access %s protection granted.", + (socksreq[0] == 0) ? "without GSS-API data" : + ((socksreq[0] == 1) ? "with GSS-API integrity" : + "with GSS-API confidentiality")); + + conn->socks5_gssapi_enctype = socksreq[0]; + if(socksreq[0] == 0) + Curl_gss_delete_sec_context(&gss_status, gss_context, NULL); + + return CURLE_OK; +} + +CURLcode Curl_SOCKS5_gssapi_negotiate(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct Curl_creds *creds) +{ + struct connectdata *conn = cf->conn; + curl_socket_t sock = conn->sock[cf->sockindex]; + CURLcode result; + OM_uint32 gss_ret_flags = 0; + gss_name_t server = GSS_C_NO_NAME; + const char *service = Curl_creds_has_sasl_service(creds) ? + Curl_creds_sasl_service(creds) : "rcmd"; + gss_ctx_id_t gss_context = GSS_C_NO_CONTEXT; + + result = socks5_gss_create_service_name(data, conn, service, &server); + if(!result) { + (void)curlx_nonblock(sock, FALSE); + result = socks5_gss_auth_loop(cf, data, &server, &gss_context, + &gss_ret_flags); + } + if(!result) + result = socks5_gss_auth_verify(data, &gss_context); + if(!result) + result = socks5_gss_negotiate_enc(cf, data, &gss_context, gss_ret_flags); + + /* unconditionally put it back to non-blocking */ + (void)curlx_nonblock(sock, TRUE); + + return result; +} + +#if defined(CURL_HAVE_DIAG) && defined(__APPLE__) && !defined(HAVE_GSSAPPLE) +#pragma GCC diagnostic pop +#endif + +#endif /* HAVE_GSSAPI && !CURL_DISABLE_PROXY */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/socks_sspi.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/socks_sspi.c new file mode 100644 index 0000000000..576d6aef5b --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/socks_sspi.c @@ -0,0 +1,536 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) Markus Moeller, <markus_moeller@compuserve.com> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_WINDOWS_SSPI) && !defined(CURL_DISABLE_PROXY) + +#include "urldata.h" +#include "curl_trc.h" +#include "cfilters.h" +#include "connect.h" +#include "strerror.h" +#include "curlx/nonblock.h" +#include "socks.h" +#include "curl_sspi.h" +#include "curlx/multibyte.h" + +/* + * Helper SSPI error functions. + */ +static int check_sspi_err(struct Curl_easy *data, + SECURITY_STATUS status, + const char *function) +{ + if(status != SEC_E_OK && + status != SEC_I_COMPLETE_AND_CONTINUE && + status != SEC_I_COMPLETE_NEEDED && + status != SEC_I_CONTINUE_NEEDED) { + char buffer[STRERROR_LEN]; + failf(data, "SSPI error: %s failed: %s", function, + Curl_sspi_strerror(status, buffer, sizeof(buffer))); + return 1; + } + return 0; +} + +/* This is the SSPI-using version of this function */ +static CURLcode socks5_sspi_setup(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct Curl_creds *creds, + CredHandle *cred_handle, + char **service_namep) +{ + struct connectdata *conn = cf->conn; + const char *service = Curl_creds_has_sasl_service(creds) ? + Curl_creds_sasl_service(creds) : "rcmd"; + SECURITY_STATUS status; + + /* prepare service name */ + if(strchr(service, '/')) + *service_namep = curlx_strdup(service); + else + *service_namep = curl_maprintf("%s/%s", + service, conn->socks_proxy.peer->hostname); + if(!*service_namep) + return CURLE_OUT_OF_MEMORY; + + status = + Curl_pSecFn->AcquireCredentialsHandle(NULL, CURL_UNCONST(TEXT("Kerberos")), + SECPKG_CRED_OUTBOUND, + NULL, NULL, NULL, NULL, + cred_handle, NULL); + + if(check_sspi_err(data, status, "AcquireCredentialsHandle")) { + failf(data, "Failed to acquire credentials."); + return CURLE_COULDNT_CONNECT; + } + + return CURLE_OK; +} + +static CURLcode socks5_free_token(SecBuffer *send_token, + CURLcode result) +{ + if(send_token->pvBuffer) { + Curl_pSecFn->FreeContextBuffer(send_token->pvBuffer); + send_token->pvBuffer = NULL; + } + return result; +} + +static CURLcode socks5_sspi_loop(struct Curl_cfilter *cf, + struct Curl_easy *data, + CredHandle *cred_handle, + CtxtHandle *sspi_context, + char *service_name, + unsigned long *sspi_ret_flagsp) +{ + struct connectdata *conn = cf->conn; + curl_socket_t sock = conn->sock[cf->sockindex]; + CURLcode result = CURLE_OK; + CURLcode code; + SECURITY_STATUS status; + SecBuffer sspi_send_token, sspi_recv_token; + SecBufferDesc input_desc, output_desc; + PCtxtHandle context_handle = NULL; + unsigned short us_length; + size_t actualread; + size_t written; + unsigned char socksreq[4]; + + input_desc.cBuffers = 1; + input_desc.pBuffers = &sspi_recv_token; + input_desc.ulVersion = SECBUFFER_VERSION; + + sspi_recv_token.BufferType = SECBUFFER_TOKEN; + sspi_recv_token.cbBuffer = 0; + sspi_recv_token.pvBuffer = NULL; + + output_desc.cBuffers = 1; + output_desc.pBuffers = &sspi_send_token; + output_desc.ulVersion = SECBUFFER_VERSION; + + sspi_send_token.BufferType = SECBUFFER_TOKEN; + sspi_send_token.cbBuffer = 0; + sspi_send_token.pvBuffer = NULL; + + (void)curlx_nonblock(sock, FALSE); + + for(;;) { + TCHAR *sname = curlx_convert_UTF8_to_tchar(service_name); + if(!sname) { + curlx_free(sspi_recv_token.pvBuffer); + return socks5_free_token(&sspi_send_token, CURLE_OUT_OF_MEMORY); + } + + status = + Curl_pSecFn->InitializeSecurityContext(cred_handle, context_handle, + sname, + ISC_REQ_MUTUAL_AUTH | + ISC_REQ_ALLOCATE_MEMORY | + ISC_REQ_CONFIDENTIALITY | + ISC_REQ_REPLAY_DETECT, + 0, SECURITY_NATIVE_DREP, + &input_desc, 0, + sspi_context, + &output_desc, + sspi_ret_flagsp, NULL); + + curlx_free(sname); + curlx_safefree(sspi_recv_token.pvBuffer); + sspi_recv_token.cbBuffer = 0; + + if(check_sspi_err(data, status, "InitializeSecurityContext")) { + failf(data, "Failed to initialize security context."); + return socks5_free_token(&sspi_send_token, CURLE_COULDNT_CONNECT); + } + + if(sspi_send_token.cbBuffer) { + socksreq[0] = 1; /* GSS-API subnegotiation version */ + socksreq[1] = 1; /* authentication message type */ + if(sspi_send_token.cbBuffer > 0xffff) { + /* needs to fit in an unsigned 16-bit field */ + return socks5_free_token(&sspi_send_token, CURLE_COULDNT_CONNECT); + } + us_length = htons((unsigned short)sspi_send_token.cbBuffer); + memcpy(socksreq + 2, &us_length, sizeof(short)); + + code = Curl_conn_cf_send(cf->next, data, socksreq, 4, FALSE, &written); + if(code || (written != 4)) { + failf(data, "Failed to send SSPI authentication request."); + return socks5_free_token(&sspi_send_token, CURLE_COULDNT_CONNECT); + } + + code = Curl_conn_cf_send(cf->next, data, + sspi_send_token.pvBuffer, + sspi_send_token.cbBuffer, FALSE, &written); + if(code || (sspi_send_token.cbBuffer != written)) { + failf(data, "Failed to send SSPI authentication token."); + return socks5_free_token(&sspi_send_token, CURLE_COULDNT_CONNECT); + } + } + + if(sspi_send_token.pvBuffer) + socks5_free_token(&sspi_send_token, CURLE_OK); + sspi_send_token.cbBuffer = 0; + + curlx_safefree(sspi_recv_token.pvBuffer); + sspi_recv_token.cbBuffer = 0; + + if(status != SEC_I_CONTINUE_NEEDED) + break; + + result = Curl_blockread_all(cf, data, (char *)socksreq, 4, &actualread); + if(result || (actualread != 4)) { + failf(data, "Failed to receive SSPI authentication response."); + return result ? result : CURLE_COULDNT_CONNECT; + } + + if(socksreq[1] == 255) { + failf(data, "User was rejected by the SOCKS5 server (%u %u).", + (unsigned int)socksreq[0], (unsigned int)socksreq[1]); + return CURLE_COULDNT_CONNECT; + } + + if(socksreq[1] != 1) { + failf(data, "Invalid SSPI authentication response type (%u %u).", + (unsigned int)socksreq[0], (unsigned int)socksreq[1]); + return CURLE_COULDNT_CONNECT; + } + + memcpy(&us_length, socksreq + 2, sizeof(short)); + us_length = ntohs(us_length); + + if(!us_length) { + failf(data, "Invalid zero-length SSPI authentication token."); + return CURLE_COULDNT_CONNECT; + } + + sspi_recv_token.cbBuffer = us_length; + sspi_recv_token.pvBuffer = curlx_malloc(us_length); + + if(!sspi_recv_token.pvBuffer) + return CURLE_OUT_OF_MEMORY; + + result = Curl_blockread_all(cf, data, (char *)sspi_recv_token.pvBuffer, + sspi_recv_token.cbBuffer, &actualread); + + if(result || (actualread != us_length)) { + failf(data, "Failed to receive SSPI authentication token."); + curlx_free(sspi_recv_token.pvBuffer); + return result ? result : CURLE_COULDNT_CONNECT; + } + + context_handle = sspi_context; + } + + return CURLE_OK; +} + +static CURLcode socks5_free(SecBuffer *sspi_w_token, + CURLcode result) +{ + curlx_safefree(sspi_w_token[0].pvBuffer); + curlx_safefree(sspi_w_token[1].pvBuffer); + curlx_safefree(sspi_w_token[2].pvBuffer); + return result; +} + +static CURLcode socks5_sspi_encrypt(struct Curl_cfilter *cf, + struct Curl_easy *data, + CtxtHandle *sspi_context, + unsigned long sspi_ret_flags) +{ + CURLcode result = CURLE_OK; + CURLcode code; + SECURITY_STATUS status; + unsigned char gss_enc; + SecBuffer sspi_w_token[3]; + SecBufferDesc wrap_desc; + SecPkgContext_Sizes sspi_sizes; + unsigned short us_length; + unsigned long qop; + unsigned char socksreq[4]; + uint8_t *etbuf = NULL; + size_t etbuf_size = 0; + size_t actualread; + size_t written; + + gss_enc = 0; + if(sspi_ret_flags & ISC_REQ_CONFIDENTIALITY) + gss_enc = 2; + else if(sspi_ret_flags & ISC_REQ_INTEGRITY) + gss_enc = 1; + + infof(data, "SOCKS5 server supports GSS-API %s data protection.", + (gss_enc == 0) ? "no" : + ((gss_enc == 1) ? "integrity" : "confidentiality")); + + sspi_w_token[0].pvBuffer = + sspi_w_token[1].pvBuffer = + sspi_w_token[2].pvBuffer = NULL; + + wrap_desc.cBuffers = 3; + wrap_desc.pBuffers = sspi_w_token; + wrap_desc.ulVersion = SECBUFFER_VERSION; + + socksreq[0] = 1; + socksreq[1] = 2; + + if(data->set.socks5_gssapi_nec) { + us_length = htons((unsigned short)1); + memcpy(socksreq + 2, &us_length, sizeof(short)); + } + else { + status = Curl_pSecFn->QueryContextAttributes(sspi_context, + SECPKG_ATTR_SIZES, + &sspi_sizes); + if(check_sspi_err(data, status, "QueryContextAttributes")) { + failf(data, "Failed to query security context attributes."); + return CURLE_COULDNT_CONNECT; + } + + sspi_w_token[0].cbBuffer = sspi_sizes.cbSecurityTrailer; + sspi_w_token[0].BufferType = SECBUFFER_TOKEN; + sspi_w_token[0].pvBuffer = curlx_malloc(sspi_sizes.cbSecurityTrailer); + + if(!sspi_w_token[0].pvBuffer) + return CURLE_OUT_OF_MEMORY; + + sspi_w_token[1].cbBuffer = 1; + sspi_w_token[1].BufferType = SECBUFFER_DATA; + sspi_w_token[1].pvBuffer = curlx_malloc(1); + if(!sspi_w_token[1].pvBuffer) + return socks5_free(sspi_w_token, CURLE_OUT_OF_MEMORY); + + memcpy(sspi_w_token[1].pvBuffer, &gss_enc, 1); + sspi_w_token[2].BufferType = SECBUFFER_PADDING; + sspi_w_token[2].cbBuffer = sspi_sizes.cbBlockSize; + sspi_w_token[2].pvBuffer = curlx_malloc(sspi_sizes.cbBlockSize); + if(!sspi_w_token[2].pvBuffer) + return socks5_free(sspi_w_token, CURLE_OUT_OF_MEMORY); + + status = Curl_pSecFn->EncryptMessage(sspi_context, + KERB_WRAP_NO_ENCRYPT, + &wrap_desc, 0); + if(check_sspi_err(data, status, "EncryptMessage")) + return socks5_free(sspi_w_token, CURLE_COULDNT_CONNECT); + + etbuf_size = sspi_w_token[0].cbBuffer + sspi_w_token[1].cbBuffer + + sspi_w_token[2].cbBuffer; + if(etbuf_size > 0xffff) + return socks5_free(sspi_w_token, CURLE_COULDNT_CONNECT); + + etbuf = curlx_malloc(etbuf_size); + if(!etbuf) + return socks5_free(sspi_w_token, CURLE_OUT_OF_MEMORY); + + memcpy(etbuf, sspi_w_token[0].pvBuffer, sspi_w_token[0].cbBuffer); + memcpy(etbuf + sspi_w_token[0].cbBuffer, + sspi_w_token[1].pvBuffer, sspi_w_token[1].cbBuffer); + memcpy(etbuf + sspi_w_token[0].cbBuffer + sspi_w_token[1].cbBuffer, + sspi_w_token[2].pvBuffer, sspi_w_token[2].cbBuffer); + + (void)socks5_free(sspi_w_token, CURLE_OK); + + us_length = htons((unsigned short)etbuf_size); + memcpy(socksreq + 2, &us_length, sizeof(short)); + } + + code = Curl_conn_cf_send(cf->next, data, socksreq, 4, FALSE, &written); + if(code || (written != 4)) { + failf(data, "Failed to send SSPI encryption request."); + curlx_free(etbuf); + return CURLE_COULDNT_CONNECT; + } + + if(data->set.socks5_gssapi_nec) { + memcpy(socksreq, &gss_enc, 1); + code = Curl_conn_cf_send(cf->next, data, socksreq, 1, FALSE, &written); + if(code || (written != 1)) { + failf(data, "Failed to send SSPI encryption type."); + return CURLE_COULDNT_CONNECT; + } + } + else { + code = Curl_conn_cf_send(cf->next, data, etbuf, etbuf_size, FALSE, + &written); + curlx_free(etbuf); + if(code || (etbuf_size != written)) { + failf(data, "Failed to send SSPI encryption type."); + return CURLE_COULDNT_CONNECT; + } + } + + result = Curl_blockread_all(cf, data, (char *)socksreq, 4, &actualread); + if(result || (actualread != 4)) { + failf(data, "Failed to receive SSPI encryption response."); + return result ? result : CURLE_COULDNT_CONNECT; + } + + if(socksreq[1] == 255) { + failf(data, "User was rejected by the SOCKS5 server (%u %u).", + (unsigned int)socksreq[0], (unsigned int)socksreq[1]); + return CURLE_COULDNT_CONNECT; + } + + if(socksreq[1] != 2) { + failf(data, "Invalid SSPI encryption response type (%u %u).", + (unsigned int)socksreq[0], (unsigned int)socksreq[1]); + return CURLE_COULDNT_CONNECT; + } + + memcpy(&us_length, socksreq + 2, sizeof(short)); + us_length = ntohs(us_length); + + if(!us_length) { + failf(data, "Invalid zero-length SSPI encryption token."); + return CURLE_COULDNT_CONNECT; + } + + sspi_w_token[0].cbBuffer = us_length; + sspi_w_token[0].pvBuffer = curlx_malloc(us_length); + if(!sspi_w_token[0].pvBuffer) + return CURLE_OUT_OF_MEMORY; + + result = Curl_blockread_all(cf, data, (char *)sspi_w_token[0].pvBuffer, + sspi_w_token[0].cbBuffer, &actualread); + + if(result || (actualread != us_length)) { + failf(data, "Failed to receive SSPI encryption type."); + goto fail; + } + + if(!data->set.socks5_gssapi_nec) { + wrap_desc.cBuffers = 2; + sspi_w_token[0].BufferType = SECBUFFER_STREAM; + sspi_w_token[1].BufferType = SECBUFFER_DATA; + sspi_w_token[1].cbBuffer = 0; + sspi_w_token[1].pvBuffer = NULL; + + /* At least one of the descriptors must be of type SECBUFFER_DATA. The + message is decrypted in place so the SECBUFFER_DATA receives a pointer + to the message in SECBUFFER_STREAM. */ + status = Curl_pSecFn->DecryptMessage(sspi_context, &wrap_desc, 0, &qop); + + if(check_sspi_err(data, status, "DecryptMessage")) + goto fail; + + if(sspi_w_token[1].cbBuffer != 1) { + failf(data, "Invalid SSPI encryption response length (%lu).", + (unsigned long)sspi_w_token[1].cbBuffer); + goto fail; + } + + memcpy(socksreq, sspi_w_token[1].pvBuffer, sspi_w_token[1].cbBuffer); + } + else { + if(sspi_w_token[0].cbBuffer != 1) { + failf(data, "Invalid SSPI encryption response length (%lu).", + (unsigned long)sspi_w_token[0].cbBuffer); + goto fail; + } + memcpy(socksreq, sspi_w_token[0].pvBuffer, sspi_w_token[0].cbBuffer); + } + curlx_free(sspi_w_token[0].pvBuffer); + + infof(data, "SOCKS5 access %s protection granted BUT NOT USED.", + (socksreq[0] == 0) ? "without GSS-API data" : + ((socksreq[0] == 1) ? "with GSS-API integrity" : + "with GSS-API confidentiality")); + + cf->conn->socks5_gssapi_enctype = socksreq[0]; + return CURLE_OK; + +fail: + curlx_free(sspi_w_token[0].pvBuffer); + return CURLE_COULDNT_CONNECT; +} + +CURLcode Curl_SOCKS5_gssapi_negotiate(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct Curl_creds *creds) +{ + struct connectdata *conn = cf->conn; + curl_socket_t sock = conn->sock[cf->sockindex]; + CURLcode result; + SECURITY_STATUS status; + CredHandle cred_handle; + CtxtHandle sspi_context; + SecPkgCredentials_Names names; + char *service_name = NULL; + unsigned long sspi_ret_flags = 0; + + memset(&cred_handle, 0, sizeof(cred_handle)); + memset(&sspi_context, 0, sizeof(sspi_context)); + names.sUserName = NULL; + + result = socks5_sspi_setup(cf, data, creds, &cred_handle, &service_name); + if(result) + goto error; + + result = socks5_sspi_loop(cf, data, &cred_handle, &sspi_context, + service_name, &sspi_ret_flags); + if(result) + goto error; + + curlx_safefree(service_name); + + status = Curl_pSecFn->QueryCredentialsAttributes(&cred_handle, + SECPKG_CRED_ATTR_NAMES, + &names); + if(check_sspi_err(data, status, "QueryCredentialAttributes")) { + failf(data, "Failed to determine username."); + result = CURLE_COULDNT_CONNECT; + goto error; + } + else { + VERBOSE(char *user_utf8 = curlx_convert_tchar_to_UTF8(names.sUserName)); + infof(data, "SOCKS5 server authenticated user %s with GSS-API.", + (user_utf8 ? user_utf8 : "(unknown)")); + VERBOSE(curlx_free(user_utf8)); + Curl_pSecFn->FreeContextBuffer(names.sUserName); + names.sUserName = NULL; + } + + result = socks5_sspi_encrypt(cf, data, &sspi_context, sspi_ret_flags); + if(result) + goto error; + + (void)curlx_nonblock(sock, TRUE); + Curl_pSecFn->DeleteSecurityContext(&sspi_context); + Curl_pSecFn->FreeCredentialsHandle(&cred_handle); + return CURLE_OK; + +error: + (void)curlx_nonblock(sock, TRUE); + curlx_free(service_name); + Curl_pSecFn->DeleteSecurityContext(&sspi_context); + Curl_pSecFn->FreeCredentialsHandle(&cred_handle); + if(names.sUserName) + Curl_pSecFn->FreeContextBuffer(names.sUserName); + return result; +} +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/splay.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/splay.c new file mode 100644 index 0000000000..788da215ee --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/splay.c @@ -0,0 +1,377 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "splay.h" + + +void Curl_timeouts_init(struct Curl_timeouts *timeouts, + const struct curltime *ptime_base) +{ + timeouts->tree = NULL; + timeouts->time_base = ptime_base ? *ptime_base : curlx_now(); +} + +bool Curl_timeouts_has(struct Curl_easy *data) +{ + struct Curl_tree *node = data ? &data->state.timeouts.splaynode : NULL; + return node && node->registered; +} + +timediff_t Curl_timeouts_offset_us(struct Curl_timeouts *timeouts, + const struct curltime *pts) +{ + return curlx_ptimediff_us(pts, &timeouts->time_base); +} + +int Curl_timeouts_next_ms(struct Curl_timeouts *timeouts, + const struct curltime *pnow, + timediff_t *pexpire_offset_us, + uint32_t *pmid) +{ + if(timeouts->tree) { /* splay the lowest key to the root */ + timeouts->tree = Curl_splay(TIMEDIFF_T_MIN, timeouts->tree); + } + + if(timeouts->tree) { + timediff_t elapsed_us = Curl_timeouts_offset_us(timeouts, pnow); + timediff_t delta_us = timeouts->tree->key - elapsed_us; + if(pmid) + *pmid = timeouts->tree->id; + if(pexpire_offset_us) + *pexpire_offset_us = timeouts->tree->key; + if(delta_us > 0) { /* expires in the future */ + timediff_t ms = curlx_us_to_ceil_ms(delta_us); + return (ms > INT_MAX) ? INT_MAX : (int)ms; + } + else /* has expired */ + return 0; + } + if(pmid) + *pmid = UINT32_MAX; + if(pexpire_offset_us) + *pexpire_offset_us = 0; + return -1; +} + +bool Curl_timeouts_remove_expired(struct Curl_timeouts *timeouts, + const struct curltime *ts, + uint32_t *pmid) +{ + if(timeouts->tree) { + struct Curl_tree *t = NULL; + timediff_t elapsed_us = Curl_timeouts_offset_us(timeouts, ts); + timeouts->tree = Curl_splaygetbest(elapsed_us, timeouts->tree, &t); + if(t) { + *pmid = t->id; + return TRUE; + } + } + *pmid = UINT32_MAX; + return FALSE; +} + +void Curl_timeouts_add(struct Curl_timeouts *timeouts, + struct Curl_easy *data, + timediff_t offset_us) +{ + struct Curl_tree *node = &data->state.timeouts.splaynode; + DEBUGASSERT(!node->registered); + timeouts->tree = Curl_splayinsert(offset_us, timeouts->tree, + node, data->mid); +} + +bool Curl_timeouts_remove(struct Curl_timeouts *timeouts, + struct Curl_easy *data) +{ + struct Curl_tree *node = &data->state.timeouts.splaynode; + if(node->registered) { + int rc = Curl_splayremove(timeouts->tree, node, &timeouts->tree); +#ifdef DEBUGBUILD + if(rc) + curl_mfprintf(stderr, "Internal error removing splay node = %d\n", rc); +#else + (void)rc; +#endif + return TRUE; + } + return FALSE; +} + +/* + * Splay using the key i (which may or may not be in the tree). + * This rotates the tree, so: + * - root->smaller has all nodes smaller than `key` + * - root->larger has all nodes larger than `key` + * - root->key may equal `key` or not + * <https://en.wikipedia.org/wiki/Splay_tree> + */ +struct Curl_tree *Curl_splay(timediff_t key, + struct Curl_tree *root) +{ + struct Curl_tree N, *l, *r, *y; + + if(!root) + return NULL; + N.smaller = N.larger = NULL; + l = r = &N; + + for(;;) { + if(key < root->key) { + /* key is somewhere in root->smaller branch */ + if(!root->smaller) /* which is empty, done */ + break; + if(key < root->smaller->key) { + /* key is somewhere in root->smaller->smaller, make a "Zig step" */ + y = root->smaller; + root->smaller = y->larger; + y->larger = root; + root = y; + if(!root->smaller) + break; + } + /* Making root->smaller the new root, the old root is no longer + * referenced. Remember it in the N tree's `r`ight/larger side. + * Everything in old root is smaller than what the right side + * of N already has, so it gets added to r->smaller. */ + r->smaller = root; + r = root; + root = root->smaller; + } + else if(key > root->key) { + /* key is somewhere in root->larger branch */ + if(!root->larger) /* which is empty, done */ + break; + if(key > root->larger->key) { + /* key is somewhere in root->larger->larger, make a "Zig step" */ + y = root->larger; + root->larger = y->smaller; + y->smaller = root; + root = y; + if(!root->larger) + break; + } + /* Making root->larger the new root, the old root is no longer + * referenced. Remember it in the N tree's `l`eft/smaller side. + * Everything in old root is larger than what the left side + * of N already has, so it gets added to l->larger. */ + l->larger = root; + l = root; + root = root->larger; + } + else /* exact match, root is key, done */ + break; + } + + /* Put it all together again. + * root->smaller has everything larger than current `l`. + * root->larger has everything smaller than current `r`. */ + l->larger = root->smaller; + r->smaller = root->larger; + root->smaller = N.larger; + root->larger = N.smaller; + + return root; +} + +/* Insert key i into the tree t. Return a pointer to the resulting tree or + * NULL if something went wrong. + * + * @unittest: 1309 + */ +struct Curl_tree *Curl_splayinsert(timediff_t key, + struct Curl_tree *root, + struct Curl_tree *node, + uint32_t id) +{ + DEBUGASSERT(node); + + node->key = key; + node->id = id; + node->same = NULL; + node->registered = TRUE; + if(root) { + root = Curl_splay(key, root); + DEBUGASSERT(root); + if(key == root->key) { + /* There already exists a node in the tree with the same key. + Append the new node to the `same` list. */ + struct Curl_tree **panchor = &root->same; + while(*panchor) + panchor = &(*panchor)->same; + *panchor = node; + return root; /* the root node always stays the same */ + } + } + + /* node becomes the new root. Insert old root as sub-branch. */ + if(!root) { + node->smaller = node->larger = NULL; + } + else if(key < root->key) { + node->smaller = root->smaller; + node->larger = root; + root->smaller = NULL; + } + else { + node->larger = root->larger; + node->smaller = root; + root->larger = NULL; + } + + return node; +} + +/* Finds and deletes the best-fit node from the tree. Return a pointer to the + resulting tree. best-fit means the smallest node if it is not larger than + the key */ +struct Curl_tree *Curl_splaygetbest(timediff_t key, + struct Curl_tree *root, + struct Curl_tree **removed) +{ + struct Curl_tree *x; + + if(!root) { + *removed = NULL; /* none removed since there was no root */ + return NULL; + } + + /* find smallest */ + root = Curl_splay(TIMEDIFF_T_MIN, root); + DEBUGASSERT(root); + if(key < root->key) { + /* even the smallest is too big */ + *removed = NULL; + return root; + } + + /* FIRST! Check if there is a list with identical keys */ + if(root->same) { + x = root->same; + DEBUGASSERT(x->key == root->key); + /* 'x' becomes the new root node */ + x->larger = root->larger; + x->smaller = root->smaller; + root->same = NULL; + root->registered = FALSE; + *removed = root; + return x; /* new root */ + } + + /* we splayed the tree to the smallest element, there is no smaller */ + x = root->larger; + root->registered = FALSE; + *removed = root; + + return x; +} + +/* Deletes the node we point out from the tree if it is there. Stores a + * pointer to the new resulting tree in 'newroot'. + * + * Returns zero on success and non-zero on errors! + * When returning error, it does not touch the 'newroot' pointer. + * + * NOTE: when the last node of the tree is removed, there is no tree left so + * 'newroot' will be made to point to NULL. + * + * @unittest: 1309 + */ +int Curl_splayremove(struct Curl_tree *root, + struct Curl_tree *removenode, + struct Curl_tree **newroot) +{ + struct Curl_tree *x; + + if(!root) + return 1; + + DEBUGASSERT(removenode); + if(!removenode->registered) + return 2; + + root = Curl_splay(removenode->key, root); + DEBUGASSERT(root); + + /* First make sure that we got the same root key as the one we want + to remove, as otherwise we might be trying to remove a node that + is not actually in the tree. */ + if(root->key != removenode->key) { + DEBUGASSERT(0); + return 2; + } + + if(root != removenode) { + /* Should be in the root->same list then */ + struct Curl_tree **panchor; + for(panchor = &root->same; *panchor; panchor = &(*panchor)->same) { + if(*panchor == removenode) { + *panchor = removenode->same; + removenode->same = NULL; + removenode->registered = FALSE; + *newroot = root; + return 0; + } + } + /* not found in same list, error */ + DEBUGASSERT(0); + return 2; + } + /* removing the root node */ + if(root->same) { + /* 'x' is the new root node, we make it use the root node's + smaller/larger links */ + x = root->same; + x->larger = root->larger; + x->smaller = root->smaller; + root->same = NULL; + } + else { + /* Remove the root node */ + if(!root->smaller) + x = root->larger; + else { + x = Curl_splay(removenode->key, root->smaller); + DEBUGASSERT(x); + x->larger = root->larger; + } + } + removenode->registered = FALSE; + *newroot = x; /* return new root */ + return 0; +} + +/* set and get the custom payload for this tree node */ +void Curl_splayset(struct Curl_tree *node, uint32_t id) +{ + DEBUGASSERT(node); + node->id = id; +} + +uint32_t Curl_splayget(struct Curl_tree *node) +{ + DEBUGASSERT(node); + return node->id; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/splay.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/splay.h new file mode 100644 index 0000000000..3f9e66297c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/splay.h @@ -0,0 +1,92 @@ +#ifndef HEADER_CURL_SPLAY_H +#define HEADER_CURL_SPLAY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "curlx/timeval.h" + +struct Curl_easy; + +/* only use function calls to access this struct */ +struct Curl_tree { + struct Curl_tree *smaller; /* smaller node */ + struct Curl_tree *larger; /* larger node */ + struct Curl_tree *same; /* points to the next node with identical key */ + timediff_t key; /* this node's "sort" key */ + uint32_t id; /* provided id for this node */ + BIT(registered); /* node is registered in splay tree */ +}; + +struct Curl_timeouts { + struct Curl_tree *tree; + struct curltime time_base; +}; + +void Curl_timeouts_init(struct Curl_timeouts *timeouts, + const struct curltime *ptime_base); + +bool Curl_timeouts_has(struct Curl_easy *data); + +timediff_t Curl_timeouts_offset_us(struct Curl_timeouts *timeouts, + const struct curltime *pts); + +int Curl_timeouts_next_ms(struct Curl_timeouts *timeouts, + const struct curltime *pnow, + timediff_t *pexpire_offset_us, + uint32_t *pmid); + +bool Curl_timeouts_remove_expired(struct Curl_timeouts *timeouts, + const struct curltime *ts, + uint32_t *pmid); + +void Curl_timeouts_add(struct Curl_timeouts *timeouts, + struct Curl_easy *data, + timediff_t offset_us); + +/* Returns TRUE if data was registered in timeouts before */ +bool Curl_timeouts_remove(struct Curl_timeouts *timeouts, + struct Curl_easy *data); + +struct Curl_tree *Curl_splay(timediff_t key, + struct Curl_tree *root); + +struct Curl_tree *Curl_splayinsert(timediff_t key, + struct Curl_tree *root, + struct Curl_tree *node, + uint32_t id); + +struct Curl_tree *Curl_splaygetbest(timediff_t key, + struct Curl_tree *root, + struct Curl_tree **removed); + +int Curl_splayremove(struct Curl_tree *root, + struct Curl_tree *removenode, + struct Curl_tree **newroot); + +/* set and get the custom payload for this tree node */ +void Curl_splayset(struct Curl_tree *node, uint32_t id); +uint32_t Curl_splayget(struct Curl_tree *node); + +#endif /* HEADER_CURL_SPLAY_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/strcase.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/strcase.c new file mode 100644 index 0000000000..6c3597cc37 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/strcase.c @@ -0,0 +1,132 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "strcase.h" + +/* Mapping table to go from lowercase to uppercase for plain ASCII.*/ +const unsigned char Curl_touppermap[256] = { + 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, 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, 52, 53, 54, 55, 56, 57, 58, 59, + 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, + 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, + 90, 91, 92, 93, 94, 95, 96, 65, 66, 67, 68, 69, 70, 71, 72, + 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, + 88, 89, 90, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, + 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, + 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, + 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, + 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, + 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, + 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, + 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, + 255 +}; + +/* Mapping table to go from uppercase to lowercase for plain ASCII.*/ +const unsigned char Curl_tolowermap[256] = { + 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, 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, 52, 53, 54, 55, 56, 57, 58, 59, + 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, + 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, + 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, + 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, + 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, + 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, + 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, + 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, + 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, + 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, + 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, + 255 +}; + +/* Copy an upper case version of the string from src to dest. The + * strings may overlap. No more than n characters of the string are copied + * (including any NUL) and the destination string will NOT be + * null-terminated if that limit is reached. + */ +void Curl_strntoupper(char *dest, const char *src, size_t n) +{ + if(n < 1) + return; + + do { + *dest++ = Curl_raw_toupper(*src); + } while(*src++ && --n); +} + +/* Copy a lower case version of the string from src to dest. The + * strings may overlap. No more than n characters of the string are copied + * (including any NUL) and the destination string will NOT be + * null-terminated if that limit is reached. + */ +void Curl_strntolower(char *dest, const char *src, size_t n) +{ + if(n < 1) + return; + + do { + *dest++ = Curl_raw_tolower(*src); + } while(*src++ && --n); +} + +/* Compare case-sensitive null-terminated strings, taking care of possible + * null pointers. Return true if arguments match. + */ +bool Curl_safecmp(const char *a, const char *b) +{ + if(a && b) + return !strcmp(a, b); + return !a && !b; +} + +/* + * Curl_timestrcmp() returns 0 if the two strings are identical. The time this + * function spends is a function of the shortest string, not of the contents. + */ +int Curl_timestrcmp(const char *a, const char *b) +{ + int match = 0; + int i = 0; + + if(a && b) { + while(1) { + match |= a[i] ^ b[i]; + if(!a[i] || !b[i]) + break; + i++; + } + } + else + return a || b; + return match; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/strcase.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/strcase.h new file mode 100644 index 0000000000..559db875bd --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/strcase.h @@ -0,0 +1,57 @@ +#ifndef HEADER_CURL_STRCASE_H +#define HEADER_CURL_STRCASE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* Mapping tables for plain ASCII case conversion, defined in strcase.c. + Declared here so the conversions below inline at every call site without + relying on LTO or a unity build: casecompare() invokes one of them twice + per byte compared, where the call costs more than the lookup itself. */ +extern const unsigned char Curl_touppermap[256]; +extern const unsigned char Curl_tolowermap[256]; + +/* Portable, consistent toupper/tolower. Do not use toupper()/tolower() from + <ctype.h>, whose behavior is altered by the current locale. */ +static CURL_INLINE char Curl_raw_toupper(char in) +{ + return (char)Curl_touppermap[(unsigned char)in]; +} + +static CURL_INLINE char Curl_raw_tolower(char in) +{ + return (char)Curl_tolowermap[(unsigned char)in]; +} + +/* checkprefix() is a shorter version of the above, used when the first + argument is the string literal */ +#define checkprefix(a, b) curl_strnequal(b, STRCONST(a)) + +void Curl_strntoupper(char *dest, const char *src, size_t n); +void Curl_strntolower(char *dest, const char *src, size_t n); + +bool Curl_safecmp(const char *a, const char *b); +int Curl_timestrcmp(const char *a, const char *b); + +#endif /* HEADER_CURL_STRCASE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/strequal.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/strequal.c new file mode 100644 index 0000000000..a352fda70b --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/strequal.c @@ -0,0 +1,95 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "strcase.h" + +/* + * curl_strequal() is for doing "raw" case insensitive strings. This is meant + * to be locale independent and only compare strings we know are safe for + * this. See https://daniel.haxx.se/blog/2008/10/15/strcasecmp-in-turkish/ for + * further explanations as to why this function is necessary. + */ + +static int casecompare(const char *first, const char *second) +{ + while(*first) { + if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) + /* get out of the loop as soon as they do not match */ + return 0; + first++; + second++; + } + /* If we are here either the strings are the same or the length is different. + We can test if the "current" character is non-zero for one and zero + for the other. Note that the characters may not be exactly the same even + if they match, we only want to compare zero-ness. */ + return !*first == !*second; +} + +static int ncasecompare(const char *first, const char *second, size_t max) +{ + while(*first && max) { + if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) + return 0; + max--; + first++; + second++; + } + if(max == 0) + return 1; /* they are equal this far */ + + return Curl_raw_toupper(*first) == Curl_raw_toupper(*second); +} + +/* + * Only "raw" case insensitive strings. This is meant to be locale independent + * and only compare strings we know are safe for this. + * + * The function is capable of comparing a-z case insensitively. + * + * Result is 1 if text matches and 0 if not. + */ + +/* --- public function --- */ +int curl_strequal(const char *s1, const char *s2) +{ + if(s1 && s2) + /* both pointers point to something then compare them */ + return casecompare(s1, s2); + + /* if both pointers are NULL then treat them as equal */ + return NULL == s1 && NULL == s2; +} + +/* --- public function --- */ +int curl_strnequal(const char *s1, const char *s2, size_t n) +{ + if(s1 && s2) + /* both pointers point to something then compare them */ + return ncasecompare(s1, s2, n); + + /* if both pointers are NULL then treat them as equal if max is non-zero */ + return NULL == s1 && NULL == s2 && n; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/strerror.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/strerror.c new file mode 100644 index 0000000000..6fc801dc61 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/strerror.c @@ -0,0 +1,680 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_WINDOWS_SSPI +#include "curl_sspi.h" +#endif + +#include "curlx/winapi.h" +#include "strerror.h" +#include "curlx/strcopy.h" + +const char *curl_easy_strerror(CURLcode error) +{ +#ifdef CURLVERBOSE + switch(error) { + case CURLE_OK: + return "No error"; + + case CURLE_UNSUPPORTED_PROTOCOL: + return "Unsupported protocol"; + + case CURLE_FAILED_INIT: + return "Failed initialization"; + + case CURLE_URL_MALFORMAT: + return "URL using bad/illegal format or missing URL"; + + case CURLE_NOT_BUILT_IN: + return "A requested feature, protocol or option was not found built-in in" + " this libcurl due to a build-time decision."; + + case CURLE_COULDNT_RESOLVE_PROXY: + return "Could not resolve proxy name"; + + case CURLE_COULDNT_RESOLVE_HOST: + return "Could not resolve hostname"; + + case CURLE_COULDNT_CONNECT: + return "Could not connect to server"; + + case CURLE_WEIRD_SERVER_REPLY: + return "Weird server reply"; + + case CURLE_REMOTE_ACCESS_DENIED: + return "Access denied to remote resource"; + + case CURLE_FTP_ACCEPT_FAILED: + return "FTP: The server failed to connect to data port"; + + case CURLE_FTP_ACCEPT_TIMEOUT: + return "FTP: Accepting server connect has timed out"; + + case CURLE_FTP_PRET_FAILED: + return "FTP: The server did not accept the PRET command."; + + case CURLE_FTP_WEIRD_PASS_REPLY: + return "FTP: unknown PASS reply"; + + case CURLE_FTP_WEIRD_PASV_REPLY: + return "FTP: unknown PASV reply"; + + case CURLE_FTP_WEIRD_227_FORMAT: + return "FTP: unknown 227 response format"; + + case CURLE_FTP_CANT_GET_HOST: + return "FTP: cannot figure out the host in the PASV response"; + + case CURLE_HTTP2: + return "Error in the HTTP2 framing layer"; + + case CURLE_FTP_COULDNT_SET_TYPE: + return "FTP: could not set file type"; + + case CURLE_PARTIAL_FILE: + return "Transferred a partial file"; + + case CURLE_FTP_COULDNT_RETR_FILE: + return "FTP: could not retrieve (RETR failed) the specified file"; + + case CURLE_QUOTE_ERROR: + return "Quote command returned error"; + + case CURLE_HTTP_RETURNED_ERROR: + return "HTTP response code said error"; + + case CURLE_WRITE_ERROR: + return "Failed writing received data to disk/application"; + + case CURLE_UPLOAD_FAILED: + return "Upload failed (at start/before it took off)"; + + case CURLE_READ_ERROR: + return "Failed to open/read local data from file/application"; + + case CURLE_OUT_OF_MEMORY: + return "Out of memory"; + + case CURLE_OPERATION_TIMEDOUT: + return "Timeout was reached"; + + case CURLE_FTP_PORT_FAILED: + return "FTP: command PORT failed"; + + case CURLE_FTP_COULDNT_USE_REST: + return "FTP: command REST failed"; + + case CURLE_RANGE_ERROR: + return "Requested range was not delivered by the server"; + + case CURLE_SSL_CONNECT_ERROR: + return "SSL connect error"; + + case CURLE_BAD_DOWNLOAD_RESUME: + return "Could not resume download"; + + case CURLE_FILE_COULDNT_READ_FILE: + return "Could not read a file:// file"; + + case CURLE_LDAP_CANNOT_BIND: + return "LDAP: cannot bind"; + + case CURLE_LDAP_SEARCH_FAILED: + return "LDAP: search failed"; + + case CURLE_ABORTED_BY_CALLBACK: + return "Operation was aborted by an application callback"; + + case CURLE_BAD_FUNCTION_ARGUMENT: + return "A libcurl function was given a bad argument"; + + case CURLE_INTERFACE_FAILED: + return "Failed binding local connection end"; + + case CURLE_TOO_MANY_REDIRECTS: + return "Number of redirects hit maximum amount"; + + case CURLE_UNKNOWN_OPTION: + return "An unknown option was passed in to libcurl"; + + case CURLE_SETOPT_OPTION_SYNTAX: + return "Malformed option provided in a setopt"; + + case CURLE_GOT_NOTHING: + return "Server returned nothing (no headers, no data)"; + + case CURLE_SSL_ENGINE_NOTFOUND: + return "SSL crypto engine not found"; + + case CURLE_SSL_ENGINE_SETFAILED: + return "Can not set SSL crypto engine as default"; + + case CURLE_SSL_ENGINE_INITFAILED: + return "Failed to initialize SSL crypto engine"; + + case CURLE_SEND_ERROR: + return "Failed sending data to the peer"; + + case CURLE_RECV_ERROR: + return "Failure when receiving data from the peer"; + + case CURLE_SSL_CERTPROBLEM: + return "Problem with the local SSL certificate"; + + case CURLE_SSL_CIPHER: + return "Could not use specified SSL cipher"; + + case CURLE_PEER_FAILED_VERIFICATION: + return "SSL peer certificate or SSH remote key was not OK"; + + case CURLE_SSL_CACERT_BADFILE: + return "Problem with the SSL CA cert (path? access rights?)"; + + case CURLE_BAD_CONTENT_ENCODING: + return "Unrecognized or bad HTTP Content or Transfer-Encoding"; + + case CURLE_FILESIZE_EXCEEDED: + return "Maximum file size exceeded"; + + case CURLE_USE_SSL_FAILED: + return "Requested SSL level failed"; + + case CURLE_SSL_SHUTDOWN_FAILED: + return "Failed to shut down the SSL connection"; + + case CURLE_SSL_CRL_BADFILE: + return "Failed to load CRL file (path? access rights?, format?)"; + + case CURLE_SSL_ISSUER_ERROR: + return "Issuer check against peer certificate failed"; + + case CURLE_SEND_FAIL_REWIND: + return "Send failed since rewinding of the data stream failed"; + + case CURLE_LOGIN_DENIED: + return "Login denied"; + + case CURLE_TFTP_NOTFOUND: + return "TFTP: File Not Found"; + + case CURLE_TFTP_PERM: + return "TFTP: Access Violation"; + + case CURLE_REMOTE_DISK_FULL: + return "Disk full or allocation exceeded"; + + case CURLE_TFTP_ILLEGAL: + return "TFTP: Illegal operation"; + + case CURLE_TFTP_UNKNOWNID: + return "TFTP: Unknown transfer ID"; + + case CURLE_REMOTE_FILE_EXISTS: + return "Remote file already exists"; + + case CURLE_TFTP_NOSUCHUSER: + return "TFTP: No such user"; + + case CURLE_REMOTE_FILE_NOT_FOUND: + return "Remote file not found"; + + case CURLE_SSH: + return "Error in the SSH layer"; + + case CURLE_AGAIN: + return "Socket not ready for send/recv"; + + case CURLE_RTSP_CSEQ_ERROR: + return "RTSP CSeq mismatch or invalid CSeq"; + + case CURLE_RTSP_SESSION_ERROR: + return "RTSP session error"; + + case CURLE_FTP_BAD_FILE_LIST: + return "Unable to parse FTP file list"; + + case CURLE_CHUNK_FAILED: + return "Chunk callback failed"; + + case CURLE_NO_CONNECTION_AVAILABLE: + return "The max connection limit is reached"; + + case CURLE_SSL_PINNEDPUBKEYNOTMATCH: + return "SSL public key does not match pinned public key"; + + case CURLE_SSL_INVALIDCERTSTATUS: + return "SSL server certificate status verification FAILED"; + + case CURLE_HTTP2_STREAM: + return "Stream error in the HTTP/2 framing layer"; + + case CURLE_RECURSIVE_API_CALL: + return "API function called from within callback"; + + case CURLE_AUTH_ERROR: + return "An authentication function returned an error"; + + case CURLE_HTTP3: + return "HTTP/3 error"; + + case CURLE_QUIC_CONNECT_ERROR: + return "QUIC connection error"; + + case CURLE_PROXY: + return "proxy handshake error"; + + case CURLE_SSL_CLIENTCERT: + return "SSL Client Certificate required"; + + case CURLE_UNRECOVERABLE_POLL: + return "Unrecoverable error in select/poll"; + + case CURLE_TOO_LARGE: + return "A value or data field grew larger than allowed"; + + case CURLE_ECH_REQUIRED: + return "ECH attempted but failed"; + + /* error codes not used by current libcurl */ + default: + break; + } + /* + * By using a switch, gcc -Wall will complain about enum values + * which do not appear, helping keep this function up-to-date. + * By using gcc -Wall -Werror, you cannot forget. + * + * A table would not have the same benefit. Most compilers will generate + * code similar to a table in any case, so there is little performance gain + * from a table. Something is broken for the user's application, anyways, so + * does it matter how fast it _does not_ work? + * + * The line number for the error will be near this comment, which is why it + * is here, and not at the start of the switch. + */ + return "Unknown error"; +#else + if(!error) + return "No error"; + else + return "Error"; +#endif +} + +const char *curl_multi_strerror(CURLMcode error) +{ +#ifdef CURLVERBOSE + switch(error) { + case CURLM_CALL_MULTI_PERFORM: + return "Please call curl_multi_perform() soon"; + + case CURLM_OK: + return "No error"; + + case CURLM_BAD_HANDLE: + return "Invalid multi handle"; + + case CURLM_BAD_EASY_HANDLE: + return "Invalid easy handle"; + + case CURLM_OUT_OF_MEMORY: + return "Out of memory"; + + case CURLM_INTERNAL_ERROR: + return "Internal error"; + + case CURLM_BAD_SOCKET: + return "Invalid socket argument"; + + case CURLM_UNKNOWN_OPTION: + return "Unknown option"; + + case CURLM_ADDED_ALREADY: + return "The easy handle is already added to a multi handle"; + + case CURLM_RECURSIVE_API_CALL: + return "API function called from within callback"; + + case CURLM_WAKEUP_FAILURE: + return "Wakeup is unavailable or failed"; + + case CURLM_BAD_FUNCTION_ARGUMENT: + return "A libcurl function was given a bad argument"; + + case CURLM_ABORTED_BY_CALLBACK: + return "Operation was aborted by an application callback"; + + case CURLM_UNRECOVERABLE_POLL: + return "Unrecoverable error in select/poll"; + + case CURLM_LAST: + break; + } + + return "Unknown error"; +#else + if(error == CURLM_OK) + return "No error"; + else + return "Error"; +#endif +} + +const char *curl_share_strerror(CURLSHcode error) +{ +#ifdef CURLVERBOSE + switch(error) { + case CURLSHE_OK: + return "No error"; + + case CURLSHE_BAD_OPTION: + return "Unknown share option"; + + case CURLSHE_IN_USE: + return "Share currently in use"; + + case CURLSHE_INVALID: + return "Invalid share handle"; + + case CURLSHE_NOMEM: + return "Out of memory"; + + case CURLSHE_NOT_BUILT_IN: + return "Feature not enabled in this library"; + + case CURLSHE_LAST: + break; + } + + return "CURLSHcode unknown"; +#else + if(error == CURLSHE_OK) + return "No error"; + else + return "Error"; +#endif +} + +const char *curl_url_strerror(CURLUcode error) +{ +#ifdef CURLVERBOSE + switch(error) { + case CURLUE_OK: + return "No error"; + + case CURLUE_BAD_HANDLE: + return "An invalid CURLU pointer was passed as argument"; + + case CURLUE_BAD_PARTPOINTER: + return "An invalid 'part' argument was passed as argument"; + + case CURLUE_MALFORMED_INPUT: + return "Malformed input to a URL function"; + + case CURLUE_BAD_PORT_NUMBER: + return "Port number was not a decimal number between 0 and 65535"; + + case CURLUE_UNSUPPORTED_SCHEME: + return "Unsupported URL scheme"; + + case CURLUE_URLDECODE: + return "URL decode error, most likely because of rubbish in the input"; + + case CURLUE_OUT_OF_MEMORY: + return "A memory function failed"; + + case CURLUE_USER_NOT_ALLOWED: + return "Credentials was passed in the URL when prohibited"; + + case CURLUE_UNKNOWN_PART: + return "An unknown part ID was passed to a URL API function"; + + case CURLUE_NO_SCHEME: + return "No scheme present"; + + case CURLUE_NO_USER: + return "No user present"; + + case CURLUE_NO_PASSWORD: + return "No password present"; + + case CURLUE_NO_OPTIONS: + return "No options present"; + + case CURLUE_NO_HOST: + return "No host present"; + + case CURLUE_NO_PORT: + return "No port number present"; + + case CURLUE_NO_QUERY: + return "No query present"; + + case CURLUE_NO_FRAGMENT: + return "No fragment present"; + + case CURLUE_NO_ZONEID: + return "No zoneid present"; + + case CURLUE_BAD_LOGIN: + return "Bad login"; + + case CURLUE_BAD_IPV6: + return "Bad IPv6 address"; + + case CURLUE_BAD_HOSTNAME: + return "Bad hostname"; + + case CURLUE_BAD_FILE_URL: + return "Bad file:// URL"; + + case CURLUE_BAD_SLASHES: + return "Unsupported number of slashes following scheme"; + + case CURLUE_BAD_SCHEME: + return "Bad scheme"; + + case CURLUE_BAD_PATH: + return "Bad path"; + + case CURLUE_BAD_FRAGMENT: + return "Bad fragment"; + + case CURLUE_BAD_QUERY: + return "Bad query"; + + case CURLUE_BAD_PASSWORD: + return "Bad password"; + + case CURLUE_BAD_USER: + return "Bad user"; + + case CURLUE_LACKS_IDN: + return "libcurl lacks IDN support"; + + case CURLUE_TOO_LARGE: + return "A value or data field is larger than allowed"; + + case CURLUE_BACKSLASH: + return "Found a backslash where a forward slash was expected"; + + case CURLUE_LAST: + break; + } + + return "CURLUcode unknown"; +#else + if(error == CURLUE_OK) + return "No error"; + else + return "Error"; +#endif +} + +#ifdef USE_WINDOWS_SSPI +/* + * Curl_sspi_strerror: + * Variant of curlx_strerror if the error code is definitely Windows SSPI. + */ +const char *Curl_sspi_strerror(SECURITY_STATUS err, char *buf, size_t buflen) +{ +#ifdef _WIN32 + DWORD old_win_err = GetLastError(); +#endif + int old_errno = errno; + VERBOSE(const char *txt); + + if(!buflen) + return NULL; + + *buf = '\0'; + +#ifdef CURLVERBOSE + switch(err) { + case SEC_E_OK: + txt = "No error"; + break; +#define SEC2TXT(sec) case sec: txt = #sec; break + SEC2TXT(CRYPT_E_REVOKED); + SEC2TXT(CRYPT_E_NO_REVOCATION_DLL); + SEC2TXT(CRYPT_E_NO_REVOCATION_CHECK); + SEC2TXT(CRYPT_E_REVOCATION_OFFLINE); + SEC2TXT(CRYPT_E_NOT_IN_REVOCATION_DATABASE); + SEC2TXT(SEC_E_ALGORITHM_MISMATCH); + SEC2TXT(SEC_E_BAD_BINDINGS); + SEC2TXT(SEC_E_BAD_PKGID); + SEC2TXT(SEC_E_BUFFER_TOO_SMALL); + SEC2TXT(SEC_E_CANNOT_INSTALL); + SEC2TXT(SEC_E_CANNOT_PACK); + SEC2TXT(SEC_E_CERT_EXPIRED); + SEC2TXT(SEC_E_CERT_UNKNOWN); + SEC2TXT(SEC_E_CERT_WRONG_USAGE); + SEC2TXT(SEC_E_CONTEXT_EXPIRED); + SEC2TXT(SEC_E_CROSSREALM_DELEGATION_FAILURE); + SEC2TXT(SEC_E_CRYPTO_SYSTEM_INVALID); + SEC2TXT(SEC_E_DECRYPT_FAILURE); + SEC2TXT(SEC_E_DELEGATION_POLICY); + SEC2TXT(SEC_E_DELEGATION_REQUIRED); + SEC2TXT(SEC_E_DOWNGRADE_DETECTED); + SEC2TXT(SEC_E_ENCRYPT_FAILURE); + SEC2TXT(SEC_E_ILLEGAL_MESSAGE); + SEC2TXT(SEC_E_INCOMPLETE_CREDENTIALS); + SEC2TXT(SEC_E_INCOMPLETE_MESSAGE); + SEC2TXT(SEC_E_INSUFFICIENT_MEMORY); + SEC2TXT(SEC_E_INTERNAL_ERROR); + SEC2TXT(SEC_E_INVALID_HANDLE); + SEC2TXT(SEC_E_INVALID_PARAMETER); + SEC2TXT(SEC_E_INVALID_TOKEN); + SEC2TXT(SEC_E_ISSUING_CA_UNTRUSTED); + SEC2TXT(SEC_E_ISSUING_CA_UNTRUSTED_KDC); + SEC2TXT(SEC_E_KDC_CERT_EXPIRED); + SEC2TXT(SEC_E_KDC_CERT_REVOKED); + SEC2TXT(SEC_E_KDC_INVALID_REQUEST); + SEC2TXT(SEC_E_KDC_UNABLE_TO_REFER); + SEC2TXT(SEC_E_KDC_UNKNOWN_ETYPE); + SEC2TXT(SEC_E_LOGON_DENIED); + SEC2TXT(SEC_E_MAX_REFERRALS_EXCEEDED); + SEC2TXT(SEC_E_MESSAGE_ALTERED); + SEC2TXT(SEC_E_MULTIPLE_ACCOUNTS); + SEC2TXT(SEC_E_MUST_BE_KDC); + SEC2TXT(SEC_E_NOT_OWNER); + SEC2TXT(SEC_E_NO_AUTHENTICATING_AUTHORITY); + SEC2TXT(SEC_E_NO_CREDENTIALS); + SEC2TXT(SEC_E_NO_IMPERSONATION); + SEC2TXT(SEC_E_NO_IP_ADDRESSES); + SEC2TXT(SEC_E_NO_KERB_KEY); + SEC2TXT(SEC_E_NO_PA_DATA); + SEC2TXT(SEC_E_NO_S4U_PROT_SUPPORT); + SEC2TXT(SEC_E_NO_TGT_REPLY); + SEC2TXT(SEC_E_OUT_OF_SEQUENCE); + SEC2TXT(SEC_E_PKINIT_CLIENT_FAILURE); + SEC2TXT(SEC_E_PKINIT_NAME_MISMATCH); + SEC2TXT(SEC_E_POLICY_NLTM_ONLY); + SEC2TXT(SEC_E_QOP_NOT_SUPPORTED); + SEC2TXT(SEC_E_REVOCATION_OFFLINE_C); + SEC2TXT(SEC_E_REVOCATION_OFFLINE_KDC); + SEC2TXT(SEC_E_SECPKG_NOT_FOUND); + SEC2TXT(SEC_E_SECURITY_QOS_FAILED); + SEC2TXT(SEC_E_SHUTDOWN_IN_PROGRESS); + SEC2TXT(SEC_E_SMARTCARD_CERT_EXPIRED); + SEC2TXT(SEC_E_SMARTCARD_CERT_REVOKED); + SEC2TXT(SEC_E_SMARTCARD_LOGON_REQUIRED); + SEC2TXT(SEC_E_STRONG_CRYPTO_NOT_SUPPORTED); + SEC2TXT(SEC_E_TARGET_UNKNOWN); + SEC2TXT(SEC_E_TIME_SKEW); + SEC2TXT(SEC_E_TOO_MANY_PRINCIPALS); + SEC2TXT(SEC_E_UNFINISHED_CONTEXT_DELETED); + SEC2TXT(SEC_E_UNKNOWN_CREDENTIALS); + SEC2TXT(SEC_E_UNSUPPORTED_FUNCTION); + SEC2TXT(SEC_E_UNSUPPORTED_PREAUTH); + SEC2TXT(SEC_E_UNTRUSTED_ROOT); + SEC2TXT(SEC_E_WRONG_CREDENTIAL_HANDLE); + SEC2TXT(SEC_E_WRONG_PRINCIPAL); + SEC2TXT(SEC_I_COMPLETE_AND_CONTINUE); + SEC2TXT(SEC_I_COMPLETE_NEEDED); + SEC2TXT(SEC_I_CONTEXT_EXPIRED); + SEC2TXT(SEC_I_CONTINUE_NEEDED); + SEC2TXT(SEC_I_INCOMPLETE_CREDENTIALS); + SEC2TXT(SEC_I_LOCAL_LOGON); + SEC2TXT(SEC_I_NO_LSA_CONTEXT); + SEC2TXT(SEC_I_RENEGOTIATE); + SEC2TXT(SEC_I_SIGNATURE_NEEDED); + default: + txt = "Unknown error"; + } + + if(err == SEC_E_ILLEGAL_MESSAGE) { + curl_msnprintf(buf, buflen, + "SEC_E_ILLEGAL_MESSAGE (0x%08lx) - This error usually " + "occurs when a fatal SSL/TLS alert is received (e.g. " + "handshake failed). More detail may be available in " + "the Windows System event log.", (unsigned long)err); + } + else { + char msgbuf[256]; + if(curlx_get_winapi_error((DWORD)err, msgbuf, sizeof(msgbuf))) + curl_msnprintf(buf, buflen, "%s (0x%08lx) - %s", txt, (unsigned long)err, + msgbuf); + else + curl_msnprintf(buf, buflen, "%s (0x%08lx)", txt, (unsigned long)err); + } +#else /* CURLVERBOSE */ + if(err == SEC_E_OK) + curlx_strcopy(buf, buflen, STRCONST("No error")); + else + curlx_strcopy(buf, buflen, STRCONST("Error")); +#endif + + if(errno != old_errno) + errno = old_errno; + +#ifdef _WIN32 + if(old_win_err != GetLastError()) + SetLastError(old_win_err); +#endif + + return buf; +} +#endif /* USE_WINDOWS_SSPI */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/strerror.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/strerror.h new file mode 100644 index 0000000000..4b9779ff2d --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/strerror.h @@ -0,0 +1,32 @@ +#ifndef HEADER_CURL_STRERROR_H +#define HEADER_CURL_STRERROR_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_WINDOWS_SSPI +const char *Curl_sspi_strerror(SECURITY_STATUS err, char *buf, size_t buflen); +#endif + +#endif /* HEADER_CURL_STRERROR_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/system_win32.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/system_win32.c new file mode 100644 index 0000000000..4cbc2c25e9 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/system_win32.c @@ -0,0 +1,76 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, <steve_holme@hotmail.com>. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef _WIN32 + +#include "system_win32.h" +#include "curl_sspi.h" +#include "curlx/timeval.h" +#include "curlx/version_win32.h" /* for curlx_verify_windows_init() */ + +/* Curl_win32_init() performs Win32 global initialization */ +CURLcode Curl_win32_init(long flags) +{ + /* CURL_GLOBAL_WIN32 controls the *optional* part of the initialization which + is for Winsock at the moment. Any required Win32 initialization + should take place after this block. */ + if(flags & CURL_GLOBAL_WIN32) { +#ifdef USE_WINSOCK + WSADATA wsa; + if(WSAStartup(MAKEWORD(2, 2), &wsa)) + return CURLE_FAILED_INIT; +#elif defined(USE_LWIPSOCK) + lwip_init(); +#endif + } /* CURL_GLOBAL_WIN32 */ + +#ifdef USE_WINDOWS_SSPI + { + CURLcode result = Curl_sspi_global_init(); + if(result) + return result; + } +#endif + + curlx_verify_windows_init(); + curlx_now_init(); + return CURLE_OK; +} + +/* Curl_win32_cleanup() is the opposite of Curl_win32_init() */ +void Curl_win32_cleanup(long init_flags) +{ +#ifdef USE_WINDOWS_SSPI + Curl_sspi_global_cleanup(); +#endif + + if(init_flags & CURL_GLOBAL_WIN32) { +#ifdef USE_WINSOCK + WSACleanup(); +#endif + } +} + +#endif /* _WIN32 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/system_win32.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/system_win32.h new file mode 100644 index 0000000000..d504b563db --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/system_win32.h @@ -0,0 +1,35 @@ +#ifndef HEADER_CURL_SYSTEM_WIN32_H +#define HEADER_CURL_SYSTEM_WIN32_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, <steve_holme@hotmail.com>. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef _WIN32 +CURLcode Curl_win32_init(long flags); +void Curl_win32_cleanup(long init_flags); +#else +#define Curl_win32_init(x) CURLE_OK +#endif /* _WIN32 */ + +#endif /* HEADER_CURL_SYSTEM_WIN32_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/telnet.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/telnet.c new file mode 100644 index 0000000000..735fa66156 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/telnet.c @@ -0,0 +1,1581 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" +#include "telnet.h" + +#ifndef CURL_DISABLE_TELNET + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NET_IF_H +#include <net/if.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif + +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif + +#include "url.h" +#include "transfer.h" +#include "sendf.h" +#include "curl_trc.h" +#include "progress.h" +#include "arpa_telnet.h" +#include "connect.h" +#include "select.h" +#include "curlx/strparse.h" + +#define SUBBUFSIZE 512 + +#define CURL_SB_CLEAR(x) (x)->subpointer = (x)->subbuffer +#define CURL_SB_TERM(x) \ + do { \ + (x)->subend = (x)->subpointer; \ + CURL_SB_CLEAR(x); \ + } while(0) +#define CURL_SB_ACCUM(x, c) \ + do { \ + if((x)->subpointer < ((x)->subbuffer + sizeof((x)->subbuffer))) \ + *(x)->subpointer++ = (c); \ + } while(0) + +#define CURL_SB_GET(x) ((*(x)->subpointer++) & 0xff) +#define CURL_SB_LEN(x) ((x)->subend - (x)->subpointer) + +/* For posterity: +#define CURL_SB_PEEK(x) (*(x)->subpointer & 0xff) +#define CURL_SB_EOF(x) ((x)->subpointer >= (x)->subend) */ + +/* For negotiation compliant to RFC 1143 */ +#define CURL_NO 0 +#define CURL_YES 1 +#define CURL_WANTYES 2 +#define CURL_WANTNO 3 + +#define CURL_EMPTY 0 +#define CURL_OPPOSITE 1 + +/* meta key for storing protocol meta at easy handle */ +#define CURL_META_TELNET_EASY "meta:proto:telnet:easy" + +/* + * Telnet receiver states for fsm + */ +typedef enum { + CURL_TS_DATA = 0, + CURL_TS_IAC, + CURL_TS_WILL, + CURL_TS_WONT, + CURL_TS_DO, + CURL_TS_DONT, + CURL_TS_CR, + CURL_TS_SB, /* sub-option collection */ + CURL_TS_SE /* looking for sub-option end */ +} TelnetReceive; + +struct TELNET { + int please_negotiate; + int already_negotiated; + int us[256]; + int usq[256]; + int us_preferred[256]; + int him[256]; + int himq[256]; + int him_preferred[256]; + int subnegotiation[256]; + const char *subopt_ttype; /* Set with suboption TTYPE */ + const char *subopt_xdisploc; /* Set with suboption XDISPLOC */ + unsigned short subopt_wsx; /* Set with suboption NAWS */ + unsigned short subopt_wsy; /* Set with suboption NAWS */ + TelnetReceive telrcv_state; + struct curl_slist *telnet_vars; /* Environment variables */ + struct dynbuf out; /* output buffer */ + + /* suboptions */ + unsigned char subbuffer[SUBBUFSIZE]; + unsigned char *subpointer, *subend; /* buffer for sub-options */ +}; + +#ifndef CURLVERBOSE +#define printoption(a, b, c, d) Curl_nop_stmt +#else +static void printoption(struct Curl_easy *data, + const char *direction, int cmd, int option) +{ + if(data->set.verbose) { + if(cmd == CURL_IAC) { + if(CURL_TELCMD_OK(option)) + infof(data, "%s IAC %s", direction, CURL_TELCMD(option)); + else + infof(data, "%s IAC %d", direction, option); + } + else { + const char *fmt = (cmd == CURL_WILL) ? "WILL" : + (cmd == CURL_WONT) ? "WONT" : + (cmd == CURL_DO) ? "DO" : + (cmd == CURL_DONT) ? "DONT" : 0; + if(fmt) { + const char *opt; + if(CURL_TELOPT_OK(option)) + opt = CURL_TELOPT(option); + else if(option == CURL_TELOPT_EXOPL) + opt = "EXOPL"; + else + opt = NULL; + + if(opt) + infof(data, "%s %s %s", direction, fmt, opt); + else + infof(data, "%s %s %d", direction, fmt, option); + } + else + infof(data, "%s %d %d", direction, cmd, option); + } + } +} +#endif /* !CURLVERBOSE */ + +static void telnet_easy_dtor(void *key, size_t klen, void *entry) +{ + struct TELNET *tn = entry; + (void)key; + (void)klen; + curl_slist_free_all(tn->telnet_vars); + curlx_dyn_free(&tn->out); + curlx_free(tn); +} + +static CURLcode init_telnet(struct Curl_easy *data) +{ + struct TELNET *tn; + + tn = curlx_calloc(1, sizeof(struct TELNET)); + if(!tn) + return CURLE_OUT_OF_MEMORY; + + curlx_dyn_init(&tn->out, 0xffff); + + tn->telrcv_state = CURL_TS_DATA; + + /* Init suboptions */ + CURL_SB_CLEAR(tn); + + /* Set the options we want by default */ + tn->us_preferred[CURL_TELOPT_SGA] = CURL_YES; + tn->him_preferred[CURL_TELOPT_SGA] = CURL_YES; + + /* To be compliant with previous releases of libcurl we enable this option + by default. This behavior can be changed with the "BINARY" option in + CURLOPT_TELNETOPTIONS */ + tn->us_preferred[CURL_TELOPT_BINARY] = CURL_YES; + tn->him_preferred[CURL_TELOPT_BINARY] = CURL_YES; + + /* We must allow the server to echo what we sent but it is not necessary + to request the server to do so (it might force the server to close + the connection). Hence, we ignore ECHO in the negotiate function */ + tn->him_preferred[CURL_TELOPT_ECHO] = CURL_YES; + + /* Set the subnegotiation fields to send information after negotiation + passed (do/will) + + Default values are (0,0) initialized by calloc. + According to the RFC1013 it is valid: + A value equal to zero is acceptable for the width (or height), and means + that no character width (or height) is being sent. In this case, the width + (or height) that will be assumed by the Telnet server is operating system + specific (it will probably be based upon the terminal type information + that may have been sent using the TERMINAL TYPE Telnet option). */ + tn->subnegotiation[CURL_TELOPT_NAWS] = CURL_YES; + + return Curl_meta_set(data, CURL_META_TELNET_EASY, tn, telnet_easy_dtor); +} + +static void send_negotiation(struct Curl_easy *data, int cmd, int option) +{ + unsigned char buf[3]; + ssize_t bytes_written; + struct connectdata *conn = data->conn; + + buf[0] = CURL_IAC; + buf[1] = (unsigned char)cmd; + buf[2] = (unsigned char)option; + + bytes_written = swrite(conn->sock[FIRSTSOCKET], buf, 3); + if(bytes_written < 0) + failf(data, "Sending data failed (%d)", SOCKERRNO); + + printoption(data, "SENT", cmd, option); +} + +static void set_remote_option(struct Curl_easy *data, struct TELNET *tn, + int option, int newstate) +{ + if(newstate == CURL_YES) { + switch(tn->him[option]) { + case CURL_NO: + tn->him[option] = CURL_WANTYES; + send_negotiation(data, CURL_DO, option); + break; + + case CURL_YES: + /* Already enabled */ + break; + + case CURL_WANTNO: + switch(tn->himq[option]) { + case CURL_EMPTY: + /* Already negotiating for CURL_YES, queue the request */ + tn->himq[option] = CURL_OPPOSITE; + break; + case CURL_OPPOSITE: + /* Error: already queued an enable request */ + break; + } + break; + + case CURL_WANTYES: + switch(tn->himq[option]) { + case CURL_EMPTY: + /* Error: already negotiating for enable */ + break; + case CURL_OPPOSITE: + tn->himq[option] = CURL_EMPTY; + break; + } + break; + } + } + else { /* NO */ + switch(tn->him[option]) { + case CURL_NO: + /* Already disabled */ + break; + + case CURL_YES: + tn->him[option] = CURL_WANTNO; + send_negotiation(data, CURL_DONT, option); + break; + + case CURL_WANTNO: + switch(tn->himq[option]) { + case CURL_EMPTY: + /* Already negotiating for NO */ + break; + case CURL_OPPOSITE: + tn->himq[option] = CURL_EMPTY; + break; + } + break; + + case CURL_WANTYES: + switch(tn->himq[option]) { + case CURL_EMPTY: + tn->himq[option] = CURL_OPPOSITE; + break; + case CURL_OPPOSITE: + break; + } + break; + } + } +} + +static void set_local_option(struct Curl_easy *data, struct TELNET *tn, + int option, int newstate) +{ + if(newstate == CURL_YES) { + switch(tn->us[option]) { + case CURL_NO: + tn->us[option] = CURL_WANTYES; + send_negotiation(data, CURL_WILL, option); + break; + + case CURL_YES: + /* Already enabled */ + break; + + case CURL_WANTNO: + switch(tn->usq[option]) { + case CURL_EMPTY: + /* Already negotiating for CURL_YES, queue the request */ + tn->usq[option] = CURL_OPPOSITE; + break; + case CURL_OPPOSITE: + /* Error: already queued an enable request */ + break; + } + break; + + case CURL_WANTYES: + switch(tn->usq[option]) { + case CURL_EMPTY: + /* Error: already negotiating for enable */ + break; + case CURL_OPPOSITE: + tn->usq[option] = CURL_EMPTY; + break; + } + break; + } + } + else { /* NO */ + switch(tn->us[option]) { + case CURL_NO: + /* Already disabled */ + break; + + case CURL_YES: + tn->us[option] = CURL_WANTNO; + send_negotiation(data, CURL_WONT, option); + break; + + case CURL_WANTNO: + switch(tn->usq[option]) { + case CURL_EMPTY: + /* Already negotiating for NO */ + break; + case CURL_OPPOSITE: + tn->usq[option] = CURL_EMPTY; + break; + } + break; + + case CURL_WANTYES: + switch(tn->usq[option]) { + case CURL_EMPTY: + tn->usq[option] = CURL_OPPOSITE; + break; + case CURL_OPPOSITE: + break; + } + break; + } + } +} + +static void telnet_negotiate(struct Curl_easy *data, struct TELNET *tn) +{ + int i; + + for(i = 0; i < CURL_NTELOPTS; i++) { + if(i == CURL_TELOPT_ECHO) + continue; + + if(tn->us_preferred[i] == CURL_YES) + set_local_option(data, tn, i, CURL_YES); + + if(tn->him_preferred[i] == CURL_YES) + set_remote_option(data, tn, i, CURL_YES); + } +} + +static void rec_will(struct Curl_easy *data, struct TELNET *tn, int option) +{ + switch(tn->him[option]) { + case CURL_NO: + if(tn->him_preferred[option] == CURL_YES) { + tn->him[option] = CURL_YES; + send_negotiation(data, CURL_DO, option); + } + else + send_negotiation(data, CURL_DONT, option); + + break; + + case CURL_YES: + /* Already enabled */ + break; + + case CURL_WANTNO: + switch(tn->himq[option]) { + case CURL_EMPTY: + /* Error: DONT answered by WILL */ + tn->him[option] = CURL_NO; + break; + case CURL_OPPOSITE: + /* Error: DONT answered by WILL */ + tn->him[option] = CURL_YES; + tn->himq[option] = CURL_EMPTY; + break; + } + break; + + case CURL_WANTYES: + switch(tn->himq[option]) { + case CURL_EMPTY: + tn->him[option] = CURL_YES; + break; + case CURL_OPPOSITE: + tn->him[option] = CURL_WANTNO; + tn->himq[option] = CURL_EMPTY; + send_negotiation(data, CURL_DONT, option); + break; + } + break; + } +} + +static void rec_wont(struct Curl_easy *data, struct TELNET *tn, int option) +{ + switch(tn->him[option]) { + case CURL_NO: + /* Already disabled */ + break; + + case CURL_YES: + tn->him[option] = CURL_NO; + send_negotiation(data, CURL_DONT, option); + break; + + case CURL_WANTNO: + switch(tn->himq[option]) { + case CURL_EMPTY: + tn->him[option] = CURL_NO; + break; + + case CURL_OPPOSITE: + tn->him[option] = CURL_WANTYES; + tn->himq[option] = CURL_EMPTY; + send_negotiation(data, CURL_DO, option); + break; + } + break; + + case CURL_WANTYES: + switch(tn->himq[option]) { + case CURL_EMPTY: + tn->him[option] = CURL_NO; + break; + case CURL_OPPOSITE: + tn->him[option] = CURL_NO; + tn->himq[option] = CURL_EMPTY; + break; + } + break; + } +} + +static void printsub(struct Curl_easy *data, + int direction, /* '<' or '>' */ + const unsigned char *pointer, /* ptr to suboption data */ + size_t length) /* suboption data length */ +{ + if(data->set.verbose) { + unsigned int i = 0; + if(direction) { + infof(data, "%s IAC SB ", (direction == '<') ? "RCVD" : "SENT"); + if(length >= 3) { + int j; + + i = pointer[length - 2]; + j = pointer[length - 1]; + + if(i != CURL_IAC || j != CURL_SE) { + infof(data, "(terminated by "); + if(CURL_TELOPT_OK(i)) + infof(data, "%s ", CURL_TELOPT(i)); + else if(CURL_TELCMD_OK(i)) + infof(data, "%s ", CURL_TELCMD(i)); + else + infof(data, "%u ", i); + if(CURL_TELOPT_OK(j)) + infof(data, "%s", CURL_TELOPT(j)); + else if(CURL_TELCMD_OK(j)) + infof(data, "%s", CURL_TELCMD(j)); + else + infof(data, "%d", j); + infof(data, ", not IAC SE) "); + } + } + if(length >= 2) + length -= 2; + else /* bad input */ + return; + } + if(length <= 1) { + infof(data, "(Empty suboption?)"); + return; + } + + if(CURL_TELOPT_OK(pointer[0])) { + switch(pointer[0]) { + case CURL_TELOPT_TTYPE: + case CURL_TELOPT_XDISPLOC: + case CURL_TELOPT_NEW_ENVIRON: + case CURL_TELOPT_NAWS: + infof(data, "%s", CURL_TELOPT(pointer[0])); + break; + default: + infof(data, "%s (unsupported)", CURL_TELOPT(pointer[0])); + break; + } + } + else + infof(data, "%d (unknown)", pointer[0]); + + switch(pointer[0]) { + case CURL_TELOPT_NAWS: + if(length > 4) + infof(data, "Width: %d ; Height: %d", (pointer[1] << 8) | pointer[2], + (pointer[3] << 8) | pointer[4]); + break; + default: + switch(pointer[1]) { + case CURL_TELQUAL_IS: + infof(data, " IS"); + break; + case CURL_TELQUAL_SEND: + infof(data, " SEND"); + break; + case CURL_TELQUAL_INFO: + infof(data, " INFO/REPLY"); + break; + case CURL_TELQUAL_NAME: + infof(data, " NAME"); + break; + } + + switch(pointer[0]) { + case CURL_TELOPT_TTYPE: + case CURL_TELOPT_XDISPLOC: + infof(data, " \"%.*s\"", + (int)((length > 2) ? (length - 2) : 0), &pointer[2]); + break; + case CURL_TELOPT_NEW_ENVIRON: + if(pointer[1] == CURL_TELQUAL_IS) { + infof(data, " "); + for(i = 3; i < length; i++) { + switch(pointer[i]) { + case CURL_NEW_ENV_VAR: + infof(data, ", "); + break; + case CURL_NEW_ENV_VALUE: + infof(data, " = "); + break; + default: + infof(data, "%c", pointer[i]); + break; + } + } + } + break; + default: + for(i = 2; i < length; i++) + infof(data, " %.2x", pointer[i]); + break; + } + } + } +} + +/* Escape and send a telnet data block */ +static CURLcode send_telnet_data(struct Curl_easy *data, + struct TELNET *tn, + const char *buffer, ssize_t nread) +{ + size_t i, outlen; + const unsigned char *outbuf; + CURLcode result = CURLE_OK; + size_t bytes_written; + size_t total_written = 0; + struct connectdata *conn = data->conn; + + DEBUGASSERT(tn); + DEBUGASSERT(nread > 0); + if(nread < 0) + return CURLE_TOO_LARGE; + + if(memchr(buffer, CURL_IAC, nread)) { + /* only use the escape buffer when necessary */ + curlx_dyn_reset(&tn->out); + + for(i = 0; i < (size_t)nread && !result; i++) { + result = curlx_dyn_addn(&tn->out, &buffer[i], 1); + if(!result && ((unsigned char)buffer[i] == CURL_IAC)) + /* IAC is FF in hex */ + result = curlx_dyn_addn(&tn->out, "\xff", 1); + } + + outlen = curlx_dyn_len(&tn->out); + outbuf = curlx_dyn_uptr(&tn->out); + } + else { + outlen = (size_t)nread; + outbuf = (const unsigned char *)buffer; + } + while(!result && total_written < outlen) { + /* Make sure socket is writable to avoid EWOULDBLOCK condition */ + struct pollfd pfd[1]; + timediff_t timeout_ms = Curl_timeleft_ms(data); + pfd[0].fd = conn->sock[FIRSTSOCKET]; + pfd[0].events = POLLOUT; + if(timeout_ms < 0) + return CURLE_OPERATION_TIMEDOUT; + /* 0 means no timeout configured; pass -1 to poll for infinite wait */ + switch(Curl_poll(pfd, 1, timeout_ms ? timeout_ms : -1)) { + case -1: /* error, abort writing */ + result = CURLE_SEND_ERROR; + break; + case 0: /* timeout */ + result = CURLE_OPERATION_TIMEDOUT; + break; + default: /* write! */ + bytes_written = 0; + result = Curl_xfer_send(data, outbuf + total_written, + outlen - total_written, FALSE, &bytes_written); + total_written += bytes_written; + break; + } + } + + return result; +} + +/* + * sendsuboption() + * + * Send suboption information to the server side. + */ +static void sendsuboption(struct Curl_easy *data, + struct TELNET *tn, int option) +{ + ssize_t bytes_written; + unsigned short x, y; + const unsigned char *uc1, *uc2; + struct connectdata *conn = data->conn; + + switch(option) { + case CURL_TELOPT_NAWS: + /* We prepare data to be sent */ + CURL_SB_CLEAR(tn); + CURL_SB_ACCUM(tn, CURL_IAC); + CURL_SB_ACCUM(tn, CURL_SB); + CURL_SB_ACCUM(tn, CURL_TELOPT_NAWS); + /* We must deal either with little or big endian processors */ + /* Window size must be sent according to the 'network order' */ + x = htons(tn->subopt_wsx); + y = htons(tn->subopt_wsy); + uc1 = (const unsigned char *)&x; + uc2 = (const unsigned char *)&y; + CURL_SB_ACCUM(tn, uc1[0]); + CURL_SB_ACCUM(tn, uc1[1]); + CURL_SB_ACCUM(tn, uc2[0]); + CURL_SB_ACCUM(tn, uc2[1]); + + CURL_SB_ACCUM(tn, CURL_IAC); + CURL_SB_ACCUM(tn, CURL_SE); + CURL_SB_TERM(tn); + /* data suboption is now ready */ + + printsub(data, '>', (const unsigned char *)tn->subbuffer + 2, + CURL_SB_LEN(tn) - 2); + + /* we send the header of the suboption... */ + bytes_written = swrite(conn->sock[FIRSTSOCKET], tn->subbuffer, 3); + if(bytes_written < 0) + failf(data, "Sending data failed (%d)", SOCKERRNO); + /* ... then the window size with the send_telnet_data() function + to deal with 0xFF cases ... */ + send_telnet_data(data, tn, (const char *)tn->subbuffer + 3, 4); + /* ... and the footer */ + bytes_written = swrite(conn->sock[FIRSTSOCKET], tn->subbuffer + 7, 2); + if(bytes_written < 0) + failf(data, "Sending data failed (%d)", SOCKERRNO); + break; + } +} + +static void rec_do(struct Curl_easy *data, struct TELNET *tn, int option) +{ + switch(tn->us[option]) { + case CURL_NO: + if(tn->us_preferred[option] == CURL_YES) { + tn->us[option] = CURL_YES; + send_negotiation(data, CURL_WILL, option); + if(tn->subnegotiation[option] == CURL_YES) + /* transmission of data option */ + sendsuboption(data, tn, option); + } + else if(tn->subnegotiation[option] == CURL_YES) { + /* send information to achieve this option */ + tn->us[option] = CURL_YES; + send_negotiation(data, CURL_WILL, option); + sendsuboption(data, tn, option); + } + else + send_negotiation(data, CURL_WONT, option); + break; + + case CURL_YES: + /* Already enabled */ + break; + + case CURL_WANTNO: + switch(tn->usq[option]) { + case CURL_EMPTY: + /* Error: DONT answered by WILL */ + tn->us[option] = CURL_NO; + break; + case CURL_OPPOSITE: + /* Error: DONT answered by WILL */ + tn->us[option] = CURL_YES; + tn->usq[option] = CURL_EMPTY; + break; + } + break; + + case CURL_WANTYES: + switch(tn->usq[option]) { + case CURL_EMPTY: + tn->us[option] = CURL_YES; + if(tn->subnegotiation[option] == CURL_YES) { + /* transmission of data option */ + sendsuboption(data, tn, option); + } + break; + case CURL_OPPOSITE: + tn->us[option] = CURL_WANTNO; + tn->usq[option] = CURL_EMPTY; + send_negotiation(data, CURL_WONT, option); + break; + } + break; + } +} + +static void rec_dont(struct Curl_easy *data, struct TELNET *tn, int option) +{ + switch(tn->us[option]) { + case CURL_NO: + /* Already disabled */ + break; + + case CURL_YES: + tn->us[option] = CURL_NO; + send_negotiation(data, CURL_WONT, option); + break; + + case CURL_WANTNO: + switch(tn->usq[option]) { + case CURL_EMPTY: + tn->us[option] = CURL_NO; + break; + + case CURL_OPPOSITE: + tn->us[option] = CURL_WANTYES; + tn->usq[option] = CURL_EMPTY; + send_negotiation(data, CURL_WILL, option); + break; + } + break; + + case CURL_WANTYES: + switch(tn->usq[option]) { + case CURL_EMPTY: + tn->us[option] = CURL_NO; + break; + case CURL_OPPOSITE: + tn->us[option] = CURL_NO; + tn->usq[option] = CURL_EMPTY; + break; + } + break; + } +} + +static bool str_is_nonascii(const char *str) +{ + char c; + while((c = *str++) != 0) + if(c & 0x80) + return TRUE; + + return FALSE; +} + +static CURLcode check_telnet_options(struct Curl_easy *data, + struct TELNET *tn) +{ + struct curl_slist *head; + struct curl_slist *beg; + CURLcode result = CURLE_OK; + + /* Add the username as an environment variable if it + was given on the command line */ + if(data->state.creds) { + char buffer[256]; + if(str_is_nonascii(Curl_creds_user(data->conn->creds))) { + DEBUGF(infof(data, "set a non ASCII username in telnet")); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + curl_msnprintf(buffer, sizeof(buffer), "USER,%s", + Curl_creds_user(data->conn->creds)); + beg = curl_slist_append(tn->telnet_vars, buffer); + if(!beg) { + curl_slist_free_all(tn->telnet_vars); + tn->telnet_vars = NULL; + return CURLE_OUT_OF_MEMORY; + } + tn->telnet_vars = beg; + tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES; + } + + for(head = data->set.telnet_options; head && !result; head = head->next) { + size_t olen; + const char *option = head->data; + const char *arg; + const char *sep = strchr(option, '='); + if(sep) { + olen = sep - option; + arg = ++sep; + if(str_is_nonascii(arg)) + continue; + switch(olen) { + case 5: + /* Terminal type */ + if(curl_strnequal(option, "TTYPE", 5)) { + tn->subopt_ttype = arg; + tn->us_preferred[CURL_TELOPT_TTYPE] = CURL_YES; + break; + } + result = CURLE_UNKNOWN_OPTION; + break; + + case 8: + /* Display variable */ + if(curl_strnequal(option, "XDISPLOC", 8)) { + tn->subopt_xdisploc = arg; + tn->us_preferred[CURL_TELOPT_XDISPLOC] = CURL_YES; + break; + } + result = CURLE_UNKNOWN_OPTION; + break; + + case 7: + /* Environment variable */ + if(curl_strnequal(option, "NEW_ENV", 7)) { + beg = curl_slist_append(tn->telnet_vars, arg); + if(!beg) { + result = CURLE_OUT_OF_MEMORY; + break; + } + tn->telnet_vars = beg; + tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES; + } + else + result = CURLE_UNKNOWN_OPTION; + break; + + case 2: + /* Window Size */ + if(curl_strnequal(option, "WS", 2)) { + const char *p = arg; + curl_off_t x = 0; + curl_off_t y = 0; + if(curlx_str_number(&p, &x, 0xffff) || + curlx_str_single(&p, 'x') || + curlx_str_number(&p, &y, 0xffff)) { + failf(data, "Syntax error in telnet option: %s", head->data); + result = CURLE_SETOPT_OPTION_SYNTAX; + } + else { + tn->subopt_wsx = (unsigned short)x; + tn->subopt_wsy = (unsigned short)y; + tn->us_preferred[CURL_TELOPT_NAWS] = CURL_YES; + } + } + else + result = CURLE_UNKNOWN_OPTION; + break; + + case 6: + /* To take care or not of the 8th bit in data exchange */ + if(curl_strnequal(option, "BINARY", 6)) { + const char *p = arg; + curl_off_t binary_option; + if(!curlx_str_number(&p, &binary_option, 1) && + (binary_option != 1)) { + tn->us_preferred[CURL_TELOPT_BINARY] = CURL_NO; + tn->him_preferred[CURL_TELOPT_BINARY] = CURL_NO; + } + } + else + result = CURLE_UNKNOWN_OPTION; + break; + default: + failf(data, "Unknown telnet option %s", head->data); + result = CURLE_UNKNOWN_OPTION; + break; + } + } + else { + failf(data, "Syntax error in telnet option: %s", head->data); + result = CURLE_SETOPT_OPTION_SYNTAX; + } + } + + if(result) { + curl_slist_free_all(tn->telnet_vars); + tn->telnet_vars = NULL; + } + + return result; +} + +/* if the option contains an IAC code, it should be escaped in the output, but + as we cannot think of any legit way to send that as part of the content we + rather ban its use instead */ +static bool bad_option(const char *data) +{ + return !data || !!strchr(data, CURL_IAC); +} + +/* + * suboption() + * + * Look at the sub-option buffer, and try to be helpful to the other + * side. + */ +static CURLcode suboption(struct Curl_easy *data, struct TELNET *tn) +{ + struct curl_slist *v; + unsigned char temp[2048]; + ssize_t bytes_written; + size_t len; + struct connectdata *conn = data->conn; + + if(!CURL_SB_LEN(tn)) /* ignore empty suboption */ + return CURLE_OK; + + printsub(data, '<', (const unsigned char *)tn->subbuffer, + CURL_SB_LEN(tn) + 2); + switch(CURL_SB_GET(tn)) { + case CURL_TELOPT_TTYPE: + if(bad_option(tn->subopt_ttype)) + return CURLE_BAD_FUNCTION_ARGUMENT; + if(strlen(tn->subopt_ttype) > 1000) { + failf(data, "Too long telnet TTYPE"); + return CURLE_SEND_ERROR; + } + len = curl_msnprintf((char *)temp, sizeof(temp), "%c%c%c%c%s%c%c", + CURL_IAC, CURL_SB, CURL_TELOPT_TTYPE, + CURL_TELQUAL_IS, tn->subopt_ttype, CURL_IAC, + CURL_SE); + bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len); + + if(bytes_written < 0) { + failf(data, "Sending data failed (%d)", SOCKERRNO); + return CURLE_SEND_ERROR; + } + printsub(data, '>', &temp[2], len-2); + break; + case CURL_TELOPT_XDISPLOC: + if(bad_option(tn->subopt_xdisploc)) + return CURLE_BAD_FUNCTION_ARGUMENT; + if(strlen(tn->subopt_xdisploc) > 1000) { + failf(data, "Too long telnet XDISPLOC"); + return CURLE_SEND_ERROR; + } + len = curl_msnprintf((char *)temp, sizeof(temp), "%c%c%c%c%s%c%c", + CURL_IAC, CURL_SB, CURL_TELOPT_XDISPLOC, + CURL_TELQUAL_IS, tn->subopt_xdisploc, CURL_IAC, + CURL_SE); + bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len); + if(bytes_written < 0) { + failf(data, "Sending data failed (%d)", SOCKERRNO); + return CURLE_SEND_ERROR; + } + printsub(data, '>', &temp[2], len - 2); + break; + case CURL_TELOPT_NEW_ENVIRON: + len = curl_msnprintf((char *)temp, sizeof(temp), "%c%c%c%c", + CURL_IAC, CURL_SB, CURL_TELOPT_NEW_ENVIRON, + CURL_TELQUAL_IS); + for(v = tn->telnet_vars; v; v = v->next) { + size_t tmplen = (strlen(v->data) + 1); + if(bad_option(v->data)) + return CURLE_BAD_FUNCTION_ARGUMENT; + /* Add the variable if it fits */ + if(len + tmplen < sizeof(temp) - 6) { + const char *s = strchr(v->data, ','); + if(!s) + len += curl_msnprintf((char *)&temp[len], sizeof(temp) - len, + "%c%s", CURL_NEW_ENV_VAR, v->data); + else { + size_t vlen = s - v->data; + len += curl_msnprintf((char *)&temp[len], sizeof(temp) - len, + "%c%.*s%c%s", CURL_NEW_ENV_VAR, + (int)vlen, v->data, CURL_NEW_ENV_VALUE, ++s); + } + } + } + curl_msnprintf((char *)&temp[len], sizeof(temp) - len, + "%c%c", CURL_IAC, CURL_SE); + len += 2; + bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len); + if(bytes_written < 0) + failf(data, "Sending data failed (%d)", SOCKERRNO); + printsub(data, '>', &temp[2], len - 2); + break; + } + return CURLE_OK; +} + +static CURLcode telrcv(struct Curl_easy *data, + struct TELNET *tn, + const unsigned char *inbuf, /* Data received from + socket */ + ssize_t count) /* Number of bytes + received */ +{ + unsigned char c; + CURLcode result; + int in = 0; + int startwrite = -1; + +#define startskipping() \ + if(startwrite >= 0) { \ + result = Curl_client_write(data, \ + CLIENTWRITE_BODY, \ + (const char *)&inbuf[startwrite], \ + in-startwrite); \ + if(result) \ + return result; \ + } \ + startwrite = -1 + +#define writebyte() \ + if(startwrite < 0) \ + startwrite = in + +#define bufferflush() startskipping() + + while(count--) { + c = inbuf[in]; + + switch(tn->telrcv_state) { + case CURL_TS_CR: + tn->telrcv_state = CURL_TS_DATA; + if(c == '\0') { + startskipping(); + break; /* Ignore \0 after CR */ + } + writebyte(); + break; + + case CURL_TS_DATA: + if(c == CURL_IAC) { + tn->telrcv_state = CURL_TS_IAC; + startskipping(); + break; + } + else if(c == '\r') + tn->telrcv_state = CURL_TS_CR; + writebyte(); + break; + + case CURL_TS_IAC: + DEBUGASSERT(startwrite < 0); + switch(c) { + case CURL_WILL: + tn->telrcv_state = CURL_TS_WILL; + break; + case CURL_WONT: + tn->telrcv_state = CURL_TS_WONT; + break; + case CURL_DO: + tn->telrcv_state = CURL_TS_DO; + break; + case CURL_DONT: + tn->telrcv_state = CURL_TS_DONT; + break; + case CURL_SB: + CURL_SB_CLEAR(tn); + tn->telrcv_state = CURL_TS_SB; + break; + case CURL_IAC: + tn->telrcv_state = CURL_TS_DATA; + writebyte(); + break; + case CURL_DM: + case CURL_NOP: + case CURL_GA: + default: + tn->telrcv_state = CURL_TS_DATA; + printoption(data, "RCVD", CURL_IAC, c); + break; + } + break; + + case CURL_TS_WILL: + printoption(data, "RCVD", CURL_WILL, c); + tn->please_negotiate = 1; + rec_will(data, tn, c); + tn->telrcv_state = CURL_TS_DATA; + break; + + case CURL_TS_WONT: + printoption(data, "RCVD", CURL_WONT, c); + tn->please_negotiate = 1; + rec_wont(data, tn, c); + tn->telrcv_state = CURL_TS_DATA; + break; + + case CURL_TS_DO: + printoption(data, "RCVD", CURL_DO, c); + tn->please_negotiate = 1; + rec_do(data, tn, c); + tn->telrcv_state = CURL_TS_DATA; + break; + + case CURL_TS_DONT: + printoption(data, "RCVD", CURL_DONT, c); + tn->please_negotiate = 1; + rec_dont(data, tn, c); + tn->telrcv_state = CURL_TS_DATA; + break; + + case CURL_TS_SB: + if(c == CURL_IAC) + tn->telrcv_state = CURL_TS_SE; + else + CURL_SB_ACCUM(tn, c); + break; + + case CURL_TS_SE: + if(c != CURL_SE) { + if(c != CURL_IAC) { + /* + * This is an error. We only expect to get "IAC IAC" or "IAC SE". + * Several things may have happened. An IAC was not doubled, the IAC + * SE was left off, or another option got inserted into the + * suboption are all possibilities. + */ + failf(data, "telnet: suboption error"); + return CURLE_RECV_ERROR; + } + CURL_SB_ACCUM(tn, c); + tn->telrcv_state = CURL_TS_SB; + } + else { + CURL_SB_ACCUM(tn, CURL_IAC); + CURL_SB_ACCUM(tn, CURL_SE); + tn->subpointer -= 2; + CURL_SB_TERM(tn); + result = suboption(data, tn); /* handle sub-option */ + if(result) + return result; + tn->telrcv_state = CURL_TS_DATA; + } + break; + } + ++in; + } + bufferflush(); + return CURLE_OK; +} + +static CURLcode telnet_done(struct Curl_easy *data, + CURLcode status, bool premature) +{ + (void)status; + (void)premature; + Curl_meta_remove(data, CURL_META_TELNET_EASY); + return CURLE_OK; +} + +static CURLcode telnet_do(struct Curl_easy *data, bool *done) +{ + CURLcode result; + struct connectdata *conn = data->conn; + curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; +#ifdef USE_WINSOCK + WSAEVENT event_handle; + WSANETWORKEVENTS events; + HANDLE stdin_handle; + HANDLE objs[2]; + DWORD obj_count; + DWORD wait_timeout; + DWORD readfile_read; +#else + timediff_t interval_ms; + struct pollfd pfd[2]; + int poll_cnt; + ssize_t snread; +#endif + bool keepon = TRUE; + char buffer[4 * 1024]; + struct TELNET *tn; + + *done = TRUE; /* unconditionally */ + + result = init_telnet(data); + if(result) + return result; + + tn = Curl_meta_get(data, CURL_META_TELNET_EASY); + if(!tn) + return CURLE_FAILED_INIT; + + result = check_telnet_options(data, tn); + if(result) + return result; + +#ifdef USE_WINSOCK + /* We want to wait for both stdin and the socket. Since + * the select() function in Winsock only works on sockets + * we have to use the WaitForMultipleObjects() call. + */ + + /* First, create a sockets event object */ + event_handle = WSACreateEvent(); + if(event_handle == WSA_INVALID_EVENT) { + failf(data, "WSACreateEvent failed (%d)", SOCKERRNO); + return CURLE_FAILED_INIT; + } + + /* Tell Winsock what events we want to listen to */ + if(WSAEventSelect(sockfd, event_handle, FD_READ | FD_CLOSE)) { + WSACloseEvent(event_handle); + return CURLE_RECV_ERROR; + } + + /* Then get the Windows file handle for stdin */ + stdin_handle = GetStdHandle(STD_INPUT_HANDLE); + + /* Create the list of objects to wait for */ + objs[0] = event_handle; + objs[1] = stdin_handle; + + /* If stdin_handle is a pipe, use PeekNamedPipe() method to check it, + else use the old WaitForMultipleObjects() way */ + if(GetFileType(stdin_handle) == FILE_TYPE_PIPE || data->set.is_fread_set) { + /* Do not wait for stdin_handle, wait for event_handle */ + obj_count = 1; + /* Check stdin_handle per 100 milliseconds */ + wait_timeout = 100; + } + else { + obj_count = 2; + wait_timeout = 1000; + } + + /* Keep on listening and act on events */ + while(keepon) { + const DWORD buf_size = (DWORD)sizeof(buffer); + DWORD waitret = WaitForMultipleObjects(obj_count, objs, + FALSE, wait_timeout); + switch(waitret) { + + case WAIT_TIMEOUT: { + for(;;) { + if(data->set.is_fread_set) { + size_t n; + /* read from user-supplied method */ + n = data->state.fread_func(buffer, 1, buf_size, data->state.in); + if(n == CURL_READFUNC_ABORT) { + keepon = FALSE; + result = CURLE_READ_ERROR; + break; + } + + if(n == CURL_READFUNC_PAUSE) + break; + + if(n == 0) /* no bytes */ + break; + + /* fall through with number of bytes read */ + readfile_read = (DWORD)n; + } + else { + /* read from stdin */ + if(!PeekNamedPipe(stdin_handle, NULL, 0, NULL, + &readfile_read, NULL)) { + keepon = FALSE; + result = CURLE_READ_ERROR; + break; + } + + if(!readfile_read) + break; + + if(!ReadFile(stdin_handle, buffer, buf_size, &readfile_read, NULL)) { + keepon = FALSE; + result = CURLE_READ_ERROR; + break; + } + } + + result = send_telnet_data(data, tn, buffer, readfile_read); + if(result) { + keepon = FALSE; + break; + } + } + } + break; + + case WAIT_OBJECT_0 + 1: { + if(!ReadFile(stdin_handle, buffer, buf_size, &readfile_read, NULL)) { + keepon = FALSE; + result = CURLE_READ_ERROR; + break; + } + + result = send_telnet_data(data, tn, buffer, readfile_read); + if(result) { + keepon = FALSE; + break; + } + } + break; + + case WAIT_OBJECT_0: { + events.lNetworkEvents = 0; + if(WSAEnumNetworkEvents(sockfd, event_handle, &events) != 0) { + int sockerr = SOCKERRNO; + if(sockerr != SOCKEINPROGRESS) { + infof(data, "WSAEnumNetworkEvents failed (%d)", sockerr); + keepon = FALSE; + result = CURLE_READ_ERROR; + } + break; + } + if(events.lNetworkEvents & FD_READ) { + /* read data from network */ + size_t nread; + result = Curl_xfer_recv(data, buffer, sizeof(buffer), &nread); + /* read would have blocked. Loop again */ + if(result == CURLE_AGAIN) + break; + /* returned not-zero, this an error */ + else if(result) { + keepon = FALSE; + break; + } + /* returned zero but actually received 0 or less here, + the server closed the connection and we bail out */ + else if(!nread) { + keepon = FALSE; + break; + } + + result = telrcv(data, tn, (unsigned char *)buffer, nread); + if(result) { + keepon = FALSE; + break; + } + + /* Negotiate if the peer has started negotiating, + otherwise do not. We do not want to speak telnet with + non-telnet servers, like POP or SMTP. */ + if(tn->please_negotiate && !tn->already_negotiated) { + telnet_negotiate(data, tn); + tn->already_negotiated = 1; + } + } + if(events.lNetworkEvents & FD_CLOSE) { + keepon = FALSE; + } + break; + } + } /* switch */ + + if(data->set.timeout) { + if(curlx_ptimediff_ms(Curl_pgrs_now(data), &conn->created) >= + data->set.timeout) { + failf(data, "Time-out"); + result = CURLE_OPERATION_TIMEDOUT; + keepon = FALSE; + } + } + } + + /* We called WSACreateEvent, so call WSACloseEvent */ + if(!WSACloseEvent(event_handle)) { + infof(data, "WSACloseEvent failed (%d)", SOCKERRNO); + } +#else + pfd[0].fd = sockfd; + pfd[0].events = POLLIN; + + if(data->set.is_fread_set) { + poll_cnt = 1; + interval_ms = 100; /* poll user-supplied read function */ + } + else { + /* really using fread, so infile is a FILE* */ + pfd[1].fd = fileno((FILE *)data->state.in); + pfd[1].events = POLLIN; + poll_cnt = 2; + interval_ms = 1 * 1000; + if(pfd[1].fd < 0) { + failf(data, "cannot read input"); + result = CURLE_RECV_ERROR; + keepon = FALSE; + } + } + + while(keepon) { + DEBUGF(infof(data, "telnet_do, poll %d fds", poll_cnt)); + switch(Curl_poll(pfd, (unsigned int)poll_cnt, interval_ms)) { + case -1: /* error, stop reading */ + keepon = FALSE; + continue; + case 0: /* timeout */ + pfd[0].revents = 0; + pfd[1].revents = 0; + FALLTHROUGH(); + default: /* read! */ + if(pfd[0].revents & POLLIN) { + /* read data from network */ + size_t nread; + result = Curl_xfer_recv(data, buffer, sizeof(buffer), &nread); + /* read would have blocked. Loop again */ + if(result == CURLE_AGAIN) + break; + /* returned not-zero, this an error */ + if(result) { + keepon = FALSE; + /* In test 1452, macOS sees a ECONNRESET sometimes? Is this the + * telnet test server not shutting down the socket in a clean way? + * Seems to be timing related, happens more on slow debug build */ + if(data->state.os_errno == SOCKECONNRESET) { + DEBUGF(infof(data, "telnet_do, unexpected ECONNRESET on recv")); + } + break; + } + /* returned zero but actually received 0 or less here, + the server closed the connection and we bail out */ + else if(!nread) { + keepon = FALSE; + break; + } + + Curl_pgrs_download_inc(data, nread); + result = telrcv(data, tn, (unsigned char *)buffer, nread); + if(result) { + keepon = FALSE; + break; + } + + /* Negotiate if the peer has started negotiating, + otherwise do not. We do not want to speak telnet with + non-telnet servers, like POP or SMTP. */ + if(tn->please_negotiate && !tn->already_negotiated) { + telnet_negotiate(data, tn); + tn->already_negotiated = 1; + } + } + + snread = 0; + if(poll_cnt == 2) { + if(pfd[1].revents & POLLIN) { /* read from in file */ + snread = read(pfd[1].fd, buffer, sizeof(buffer)); + } + } + else { + /* read from user-supplied method */ + snread = (int)data->state.fread_func(buffer, 1, sizeof(buffer), + data->state.in); + if(snread == CURL_READFUNC_ABORT) { + keepon = FALSE; + break; + } + if(snread == CURL_READFUNC_PAUSE) + break; + } + + if(snread > 0) { + result = send_telnet_data(data, tn, buffer, snread); + if(result) { + keepon = FALSE; + break; + } + Curl_pgrs_upload_inc(data, (size_t)snread); + } + else if(snread < 0) + keepon = FALSE; + + break; + } /* poll switch statement */ + + if(data->set.timeout) { + if(curlx_ptimediff_ms(Curl_pgrs_now(data), &conn->created) >= + data->set.timeout) { + failf(data, "Time-out"); + result = CURLE_OPERATION_TIMEDOUT; + keepon = FALSE; + } + } + + if(!result) { + result = Curl_pgrsUpdate(data); + if(result) + keepon = FALSE; + } + } +#endif + /* mark this as "no further transfer wanted" */ + Curl_xfer_setup_nop(data); + + return result; +} + +/* + * TELNET protocol handler. + */ +const struct Curl_protocol Curl_protocol_telnet = { + ZERO_NULL, /* setup_connection */ + telnet_do, /* do_it */ + telnet_done, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_pollset */ + ZERO_NULL, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#endif /* !CURL_DISABLE_TELNET */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/telnet.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/telnet.h new file mode 100644 index 0000000000..3848fff3ba --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/telnet.h @@ -0,0 +1,30 @@ +#ifndef HEADER_CURL_TELNET_H +#define HEADER_CURL_TELNET_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_TELNET +extern const struct Curl_protocol Curl_protocol_telnet; +#endif + +#endif /* HEADER_CURL_TELNET_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/tftp.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/tftp.c new file mode 100644 index 0000000000..d95da69dc3 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/tftp.c @@ -0,0 +1,1358 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" +#include "tftp.h" + +#ifndef CURL_DISABLE_TFTP + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NET_IF_H +#include <net/if.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif + +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif + +#include "cfilters.h" +#include "cf-socket.h" +#include "transfer.h" +#include "sendf.h" +#include "curl_trc.h" +#include "progress.h" +#include "connect.h" +#include "sockaddr.h" /* required for Curl_sockaddr_storage */ +#include "url.h" +#include "strcase.h" +#include "select.h" +#include "escape.h" +#include "curlx/strerr.h" +#include "curlx/strparse.h" +#include "curlx/strcopy.h" + +/* RFC2348 allows the block size to be negotiated */ +#define TFTP_BLKSIZE_DEFAULT 512 +#define TFTP_OPTION_BLKSIZE "blksize" + +/* from RFC2349: */ +#define TFTP_OPTION_TSIZE "tsize" +#define TFTP_OPTION_INTERVAL "timeout" + +typedef enum { + TFTP_MODE_NETASCII = 0, + TFTP_MODE_OCTET +} tftp_mode_t; + +typedef enum { + TFTP_STATE_START = 0, + TFTP_STATE_RX, + TFTP_STATE_TX, + TFTP_STATE_FIN +} tftp_state_t; + +typedef enum { + TFTP_EVENT_NONE = -1, + TFTP_EVENT_INIT = 0, + TFTP_EVENT_RRQ = 1, + TFTP_EVENT_WRQ = 2, + TFTP_EVENT_DATA = 3, + TFTP_EVENT_ACK = 4, + TFTP_EVENT_ERROR = 5, + TFTP_EVENT_OACK = 6, + TFTP_EVENT_TIMEOUT +} tftp_event_t; + +typedef enum { + TFTP_ERR_UNDEF = 0, + TFTP_ERR_NOTFOUND, + TFTP_ERR_PERM, + TFTP_ERR_DISKFULL, + TFTP_ERR_ILLEGAL, + TFTP_ERR_UNKNOWNID, + TFTP_ERR_EXISTS, + TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */ + + /* The remaining error codes are internal to curl */ + TFTP_ERR_NONE = -100, + TFTP_ERR_TIMEOUT, + TFTP_ERR_NORESPONSE +} tftp_error_t; + +struct tftp_packet { + unsigned char *data; +}; + +/* meta key for storing protocol meta at connection */ +#define CURL_META_TFTP_CONN "meta:proto:tftp:conn" + +struct tftp_conn { + struct Curl_sockaddr_storage local_addr; + struct Curl_sockaddr_storage remote_addr; + struct tftp_packet rpacket; + struct tftp_packet spacket; + tftp_state_t state; + tftp_mode_t mode; + tftp_error_t error; + tftp_event_t event; + struct Curl_easy *data; + curl_socket_t sockfd; + int retries; + int retry_time; + int retry_max; + time_t rx_time; + curl_socklen_t remote_addrlen; + int rbytes; + size_t sbytes; + unsigned int blksize; + unsigned int requested_blksize; + unsigned short block; + BIT(remote_pinned); +}; + +/********************************************************** + * + * tftp_set_timeouts - + * + * Set timeouts based on state machine state. + * Use user provided connect timeouts until DATA or ACK + * packet is received, then use user-provided transfer timeouts + * + * + **********************************************************/ +static CURLcode tftp_set_timeouts(struct tftp_conn *state) +{ + time_t timeout; + timediff_t timeout_ms; + + /* Compute drop-dead time */ + timeout_ms = Curl_timeleft_ms(state->data); + + if(timeout_ms < 0) { + /* time-out, bail out, go home */ + failf(state->data, "Connection time-out"); + return CURLE_OPERATION_TIMEDOUT; + } + + /* Set per-block timeout to total */ + if((timeout_ms > 0) && (timeout_ms < 3600000)) + /* do the calculation only if the timeout is "reasonable" */ + timeout = (time_t)(timeout_ms + 500) / 1000; + else + timeout = 15; + + /* Average reposting an ACK after 5 seconds */ + state->retry_max = (int)timeout / 5; + + /* Bound the total number */ + if(state->retry_max < 3) + state->retry_max = 3; + + if(state->retry_max > 50) + state->retry_max = 50; + + /* Compute the re-ACK interval to suit the timeout */ + state->retry_time = (int)(timeout / state->retry_max); + if(state->retry_time < 1) + state->retry_time = 1; + + infof(state->data, + "set timeouts for state %d; Total %" FMT_OFF_T ", retry %d maxtry %d", + (int)state->state, timeout_ms, state->retry_time, state->retry_max); + + /* init RX time */ + state->rx_time = time(NULL); + + return CURLE_OK; +} + +/********************************************************** + * + * tftp_set_send_first + * + * Event handler for the START state + * + **********************************************************/ + +static void setpacketevent(struct tftp_packet *packet, unsigned short num) +{ + packet->data[0] = (unsigned char)(num >> 8); + packet->data[1] = (unsigned char)(num & 0xff); +} + +static void setpacketblock(struct tftp_packet *packet, unsigned short num) +{ + packet->data[2] = (unsigned char)(num >> 8); + packet->data[3] = (unsigned char)(num & 0xff); +} + +static unsigned short getrpacketevent(const struct tftp_packet *packet) +{ + return (unsigned short)((packet->data[0] << 8) | packet->data[1]); +} + +static unsigned short getrpacketblock(const struct tftp_packet *packet) +{ + return (unsigned short)((packet->data[2] << 8) | packet->data[3]); +} + +static size_t tftp_strnlen(const char *string, size_t maxlen) +{ + const char *end = memchr(string, '\0', maxlen); + return end ? (size_t)(end - string) : maxlen; +} + +static const char *tftp_option_get(const char *buf, size_t len, + const char **option, const char **value) +{ + size_t loc; + + loc = tftp_strnlen(buf, len); + loc++; /* NULL term */ + + if(loc >= len) + return NULL; + *option = buf; + + loc += tftp_strnlen(buf + loc, len - loc); + loc++; /* NULL term */ + + if(loc > len) + return NULL; + *value = &buf[strlen(*option) + 1]; + + return &buf[loc]; +} + +static CURLcode tftp_parse_option_ack(struct tftp_conn *state, + const char *ptr, int len) +{ + const char *tmp = ptr; + struct Curl_easy *data = state->data; + + /* if OACK does not contain blksize option, the default (512) must be used */ + state->blksize = TFTP_BLKSIZE_DEFAULT; + + while(tmp < ptr + len) { + const char *option, *value; + size_t olen; + + tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value); + if(!tmp) { + failf(data, "Malformed ACK packet, rejecting"); + return CURLE_TFTP_ILLEGAL; + } + olen = strlen(option); + + infof(data, "got option=(%s) value=(%s)", option, value); + + if((CURL_CSTRLEN(TFTP_OPTION_BLKSIZE) == olen) && + checkprefix(TFTP_OPTION_BLKSIZE, option)) { + curl_off_t blksize; + if(curlx_str_number(&value, &blksize, TFTP_BLKSIZE_MAX)) { + failf(data, "%s (%d)", "blksize is larger than max supported", + TFTP_BLKSIZE_MAX); + return CURLE_TFTP_ILLEGAL; + } + if(!blksize) { + failf(data, "invalid blocksize value in OACK packet"); + return CURLE_TFTP_ILLEGAL; + } + else if(blksize < TFTP_BLKSIZE_MIN) { + failf(data, "%s (%d)", "blksize is smaller than min supported", + TFTP_BLKSIZE_MIN); + return CURLE_TFTP_ILLEGAL; + } + else if(blksize > state->requested_blksize) { + /* could realloc pkt buffers here, but the spec does not call out + * support for the server requesting a bigger blksize than the client + * requests */ + failf(data, "server requested blksize larger than allocated (%" + CURL_FORMAT_CURL_OFF_T ")", blksize); + return CURLE_TFTP_ILLEGAL; + } + + state->blksize = (unsigned int)blksize; + infof(data, "blksize parsed from OACK (%u) requested (%u)", + state->blksize, state->requested_blksize); + } + else if((CURL_CSTRLEN(TFTP_OPTION_TSIZE) == olen) && + checkprefix(TFTP_OPTION_TSIZE, option)) { + curl_off_t tsize = 0; + /* tsize should be ignored on upload: Who cares about the size of the + remote file? */ + if(!data->state.upload && + !curlx_str_number(&value, &tsize, CURL_OFF_T_MAX)) { + if(!tsize) { + failf(data, "invalid tsize -:%s:- value in OACK packet", value); + return CURLE_TFTP_ILLEGAL; + } + infof(data, "tsize parsed from OACK (%" CURL_FORMAT_CURL_OFF_T ")", + tsize); + Curl_pgrsSetDownloadSize(data, tsize); + } + } + } + + return CURLE_OK; +} + +static CURLcode tftp_option_add(struct tftp_conn *state, size_t *csize, + size_t index, const char *option) +{ + char *buf = (char *)&state->spacket.data[index]; + size_t oplen = strlen(option); + size_t blen; + if((state->blksize <= index) || + (oplen + 1) > (size_t)(state->blksize - index)) + return CURLE_TFTP_ILLEGAL; + blen = state->blksize - index; + curlx_strcopy(buf, blen, option, oplen); + *csize += oplen + 1; + return CURLE_OK; +} + +/* the next blocknum is x + 1 but it needs to wrap at an unsigned 16-bit + boundary */ +#define NEXT_BLOCKNUM(x) (((x) + 1) & 0xffff) + +/********************************************************** + * + * tftp_tx + * + * Event handler for the TX state + * + **********************************************************/ +static CURLcode tftp_tx(struct tftp_conn *state, tftp_event_t event) +{ + struct Curl_easy *data = state->data; + ssize_t sbytes; + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + size_t cb; /* Bytes currently read */ + char buffer[STRERROR_LEN]; + char *bufptr; + bool eos; + + switch(event) { + + case TFTP_EVENT_ACK: + case TFTP_EVENT_OACK: + if(event == TFTP_EVENT_ACK) { + /* Ack the packet */ + int rblock = getrpacketblock(&state->rpacket); + + if(rblock != state->block && + /* There is a bug in tftpd-hpa that causes it to send us an ACK for + * 65535 when the block number wraps to 0. To handle it, when we are + * expecting 0, also accept 65535. See + * https://www.syslinux.org/archives/2010-September/015612.html + * */ + !(state->block == 0 && rblock == 65535)) { + /* This is not the expected block. Log it and up the retry counter */ + infof(data, "Received ACK for block %d, expecting %d", + rblock, state->block); + state->retries++; + /* Bail out if over the maximum */ + if(state->retries > state->retry_max) { + failf(data, "tftp_tx: giving up waiting for block %d ack", + state->block); + result = CURLE_SEND_ERROR; + } + else { + /* Re-send the data packet */ + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4 + (SEND_TYPE_ARG3)state->sbytes, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* Check all sbytes were sent */ + if(sbytes < 0) { + failf(data, "%s", + curlx_strerror(SOCKERRNO, buffer, sizeof(buffer))); + result = CURLE_SEND_ERROR; + } + } + + return result; + } + /* This is the expected packet. Reset the counters and send the next + block */ + state->rx_time = time(NULL); + state->block++; + } + else + state->block = 1; /* first data block is 1 when using OACK */ + + state->retries = 0; + setpacketevent(&state->spacket, TFTP_EVENT_DATA); + setpacketblock(&state->spacket, state->block); + if(state->block > 1 && state->sbytes < state->blksize) { + state->state = TFTP_STATE_FIN; + return CURLE_OK; + } + + /* TFTP considers data block size < 512 bytes as an end of session, so + * in some cases we must wait for additional data to build full (512 bytes) + * data block. + * */ + state->sbytes = 0; + bufptr = (char *)state->spacket.data + 4; + do { + result = Curl_client_read(data, bufptr, state->blksize - state->sbytes, + &cb, &eos); + if(result) + return result; + state->sbytes += cb; + bufptr += cb; + } while(state->sbytes < state->blksize && cb); + + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4 + (SEND_TYPE_ARG3)state->sbytes, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* Check all sbytes were sent */ + if(sbytes < 0) { + failf(data, "%s", curlx_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + /* Update the progress meter */ + k->writebytecount += state->sbytes; + Curl_pgrs_upload_inc(data, state->sbytes); + break; + + case TFTP_EVENT_TIMEOUT: + /* Increment the retry counter and log the timeout */ + state->retries++; + infof(data, "Timeout waiting for block %d ACK. " + "Retries = %d", NEXT_BLOCKNUM(state->block), state->retries); + /* Decide if we have had enough */ + if(state->retries > state->retry_max) { + state->error = TFTP_ERR_TIMEOUT; + state->state = TFTP_STATE_FIN; + } + else { + /* Re-send the data packet */ + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4 + (SEND_TYPE_ARG3)state->sbytes, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* Check all sbytes were sent */ + if(sbytes < 0) { + failf(data, "%s", curlx_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + /* since this was a re-send, we remain at the still byte position */ + Curl_pgrsSetUploadCounter(data, k->writebytecount); + } + break; + + case TFTP_EVENT_ERROR: + state->state = TFTP_STATE_FIN; + setpacketevent(&state->spacket, TFTP_EVENT_ERROR); + setpacketblock(&state->spacket, state->block); + (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* do not bother with the return code, but if the socket is still up we + * should be a good TFTP client and let the server know we are done */ + state->state = TFTP_STATE_FIN; + break; + + default: + failf(data, "tftp_tx: internal error, event: %d", (int)event); + break; + } + + return result; +} + +static CURLcode tftp_connect_for_tx(struct tftp_conn *state, + tftp_event_t event) +{ + CURLcode result; + + infof(state->data, "%s", "Connected for transmit"); + + state->state = TFTP_STATE_TX; + result = tftp_set_timeouts(state); + if(result) + return result; + return tftp_tx(state, event); +} + +/********************************************************** + * + * tftp_rx + * + * Event handler for the RX state + * + **********************************************************/ +static CURLcode tftp_rx(struct tftp_conn *state, tftp_event_t event) +{ + ssize_t sbytes; + int rblock; + struct Curl_easy *data = state->data; + char buffer[STRERROR_LEN]; + + switch(event) { + + case TFTP_EVENT_DATA: + /* Is this the block we expect? */ + rblock = getrpacketblock(&state->rpacket); + if(NEXT_BLOCKNUM(state->block) == rblock) { + /* This is the expected block. Reset counters and ACK it. */ + state->retries = 0; + } + else if(state->block == rblock) { + /* This is the last recently received block again. Log it and ACK it + again. */ + infof(data, "Received last DATA packet block %d again.", rblock); + } + else { + /* totally unexpected, log it */ + infof(data, + "Received unexpected DATA packet block %d, expecting block %d", + rblock, NEXT_BLOCKNUM(state->block)); + break; + } + + /* ACK this block. */ + state->block = (unsigned short)rblock; + setpacketevent(&state->spacket, TFTP_EVENT_ACK); + setpacketblock(&state->spacket, state->block); + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + if(sbytes < 0) { + failf(data, "%s", curlx_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + + /* Check if completed (That is, a less than full packet is received) */ + if(state->rbytes < (ssize_t)state->blksize + 4) { + state->state = TFTP_STATE_FIN; + } + else { + state->state = TFTP_STATE_RX; + } + state->rx_time = time(NULL); + break; + + case TFTP_EVENT_OACK: + /* ACK option acknowledgement so we can move on to data */ + state->block = 0; + state->retries = 0; + setpacketevent(&state->spacket, TFTP_EVENT_ACK); + setpacketblock(&state->spacket, state->block); + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + if(sbytes < 0) { + failf(data, "%s", curlx_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + + /* we are ready to RX data */ + state->state = TFTP_STATE_RX; + state->rx_time = time(NULL); + break; + + case TFTP_EVENT_TIMEOUT: + /* Increment the retry count and fail if over the limit */ + state->retries++; + infof(data, + "Timeout waiting for block %d ACK. Retries = %d", + NEXT_BLOCKNUM(state->block), state->retries); + if(state->retries > state->retry_max) { + state->error = TFTP_ERR_TIMEOUT; + state->state = TFTP_STATE_FIN; + } + else { + /* Resend the previous ACK */ + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + if(sbytes < 0) { + failf(data, "%s", curlx_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + } + break; + + case TFTP_EVENT_ERROR: + setpacketevent(&state->spacket, TFTP_EVENT_ERROR); + setpacketblock(&state->spacket, state->block); + (void)sendto(state->sockfd, (void *)state->spacket.data, + 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* do not bother with the return code, but if the socket is still up we + * should be a good TFTP client and let the server know we are done */ + state->state = TFTP_STATE_FIN; + break; + + default: + failf(data, "%s", "tftp_rx: internal error"); + return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for + this */ + } + return CURLE_OK; +} + +static CURLcode tftp_connect_for_rx(struct tftp_conn *state, + tftp_event_t event) +{ + CURLcode result; + + infof(state->data, "%s", "Connected for receive"); + + state->state = TFTP_STATE_RX; + result = tftp_set_timeouts(state); + if(result) + return result; + return tftp_rx(state, event); +} + +static CURLcode tftp_send_first(struct tftp_conn *state, + tftp_event_t event) +{ + size_t sbytes; + ssize_t senddata; + const char *mode = "octet"; + char *filename; + struct Curl_easy *data = state->data; + const struct Curl_sockaddr_ex *remote_addr = NULL; + CURLcode result = CURLE_OK; + + /* Set ASCII mode if -B flag was used */ + if(data->state.prefer_ascii) + mode = "netascii"; + + switch(event) { + + case TFTP_EVENT_INIT: /* Send the first packet out */ + case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */ + /* Increment the retry counter, quit if over the limit */ + state->retries++; + if(state->retries > state->retry_max) { + state->error = TFTP_ERR_NORESPONSE; + state->state = TFTP_STATE_FIN; + return result; + } + + if(data->state.upload) { + /* If we are uploading, send a WRQ */ + setpacketevent(&state->spacket, TFTP_EVENT_WRQ); + if(data->state.infilesize != -1) + Curl_pgrsSetUploadSize(data, data->state.infilesize); + } + else { + /* If we are downloading, send an RRQ */ + setpacketevent(&state->spacket, TFTP_EVENT_RRQ); + } + /* As RFC3617 describes the separator slash is not actually part of the + filename so we skip the always-present first letter of the path + string. */ + if(!state->data->state.up.path[1]) { + failf(data, "Missing filename"); + return CURLE_TFTP_ILLEGAL; + } + result = Curl_urldecode(&state->data->state.up.path[1], 0, + &filename, NULL, REJECT_ZERO); + if(result) + return result; + + if(strlen(filename) + strlen(mode) + 4 > state->blksize) { + failf(data, "TFTP filename too long"); + curlx_free(filename); + return CURLE_TFTP_ILLEGAL; /* too long filename field */ + } + + sbytes = 2 + + curl_msnprintf((char *)state->spacket.data + 2, + state->blksize, + "%s%c%s%c", filename, '\0', mode, '\0'); + curlx_free(filename); + + /* optional addition of TFTP options */ + if(!data->set.tftp_no_options) { + char buf[64]; + /* add tsize option */ + curl_msnprintf(buf, sizeof(buf), "%" FMT_OFF_T, + data->state.upload && (data->state.infilesize != -1) ? + data->state.infilesize : 0); + + result = tftp_option_add(state, &sbytes, sbytes, TFTP_OPTION_TSIZE); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, sbytes, buf); + + /* add blksize option */ + curl_msnprintf(buf, sizeof(buf), "%u", state->requested_blksize); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, sbytes, TFTP_OPTION_BLKSIZE); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, sbytes, buf); + + /* add timeout option */ + curl_msnprintf(buf, sizeof(buf), "%d", state->retry_time); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, sbytes, TFTP_OPTION_INTERVAL); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, sbytes, buf); + + if(result != CURLE_OK) { + failf(data, "TFTP buffer too small for options"); + return CURLE_TFTP_ILLEGAL; + } + } + + /* the typecast for the 3rd argument is mostly for systems that do + not have a size_t argument, like older unixes that want an 'int' */ +#ifdef __AMIGA__ +#define CURL_SENDTO_ARG5(x) CURL_UNCONST(x) +#else +#define CURL_SENDTO_ARG5(x) (x) +#endif + remote_addr = Curl_conn_get_remote_addr(data, FIRSTSOCKET); + if(!remote_addr) + return CURLE_FAILED_INIT; + + senddata = sendto(state->sockfd, (void *)state->spacket.data, + (SEND_TYPE_ARG3)sbytes, 0, + CURL_SENDTO_ARG5(&remote_addr->curl_sa_addr), + (curl_socklen_t)remote_addr->addrlen); + if(senddata != (ssize_t)sbytes) { + char buffer[STRERROR_LEN]; + failf(data, "%s", curlx_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + break; + + case TFTP_EVENT_OACK: + if(data->state.upload) { + result = tftp_connect_for_tx(state, event); + } + else { + result = tftp_connect_for_rx(state, event); + } + break; + + case TFTP_EVENT_ACK: /* Connected for transmit */ + result = tftp_connect_for_tx(state, event); + break; + + case TFTP_EVENT_DATA: /* Connected for receive */ + result = tftp_connect_for_rx(state, event); + break; + + case TFTP_EVENT_ERROR: + state->state = TFTP_STATE_FIN; + break; + + default: + failf(state->data, "tftp_send_first: internal error"); + return CURLE_TFTP_ILLEGAL; + } + + return result; +} + +/********************************************************** + * + * tftp_translate_code + * + * Translate internal error codes to CURL error codes + * + **********************************************************/ +static CURLcode tftp_translate_code(tftp_error_t error) +{ + CURLcode result = CURLE_OK; + + if(error != TFTP_ERR_NONE) { + switch(error) { + case TFTP_ERR_NOTFOUND: + result = CURLE_TFTP_NOTFOUND; + break; + case TFTP_ERR_PERM: + result = CURLE_TFTP_PERM; + break; + case TFTP_ERR_DISKFULL: + result = CURLE_REMOTE_DISK_FULL; + break; + case TFTP_ERR_UNDEF: + case TFTP_ERR_ILLEGAL: + result = CURLE_TFTP_ILLEGAL; + break; + case TFTP_ERR_UNKNOWNID: + result = CURLE_TFTP_UNKNOWNID; + break; + case TFTP_ERR_EXISTS: + result = CURLE_REMOTE_FILE_EXISTS; + break; + case TFTP_ERR_NOSUCHUSER: + result = CURLE_TFTP_NOSUCHUSER; + break; + case TFTP_ERR_TIMEOUT: + result = CURLE_OPERATION_TIMEDOUT; + break; + case TFTP_ERR_NORESPONSE: + result = CURLE_COULDNT_CONNECT; + break; + default: + result = CURLE_ABORTED_BY_CALLBACK; + break; + } + } + else + result = CURLE_OK; + + return result; +} + +/********************************************************** + * + * tftp_state_machine + * + * The tftp state machine event dispatcher + * + **********************************************************/ +static CURLcode tftp_state_machine(struct tftp_conn *state, + tftp_event_t event) +{ + CURLcode result = CURLE_OK; + struct Curl_easy *data = state->data; + + switch(state->state) { + case TFTP_STATE_START: + DEBUGF(infof(data, "TFTP_STATE_START")); + result = tftp_send_first(state, event); + break; + case TFTP_STATE_RX: + DEBUGF(infof(data, "TFTP_STATE_RX")); + result = tftp_rx(state, event); + break; + case TFTP_STATE_TX: + DEBUGF(infof(data, "TFTP_STATE_TX")); + result = tftp_tx(state, event); + break; + case TFTP_STATE_FIN: + infof(data, "%s", "TFTP finished"); + break; + default: + DEBUGF(infof(data, "STATE: %d", (int)state->state)); + failf(data, "%s", "Internal state machine error"); + result = CURLE_TFTP_ILLEGAL; + break; + } + + return result; +} + +static void tftp_conn_dtor(void *key, size_t klen, void *entry) +{ + struct tftp_conn *state = entry; + (void)key; + (void)klen; + curlx_safefree(state->rpacket.data); + curlx_safefree(state->spacket.data); + curlx_free(state); +} + +/********************************************************** + * + * tftp_connect + * + * The connect callback + * + **********************************************************/ +static CURLcode tftp_connect(struct Curl_easy *data, bool *done) +{ + struct tftp_conn *state; + int blksize; + int need_blksize; + struct connectdata *conn = data->conn; + const struct Curl_sockaddr_ex *remote_addr = NULL; + CURLcode result; + + blksize = TFTP_BLKSIZE_DEFAULT; + + state = curlx_calloc(1, sizeof(*state)); + if(!state || + Curl_conn_meta_set(conn, CURL_META_TFTP_CONN, state, tftp_conn_dtor)) + return CURLE_OUT_OF_MEMORY; + + /* alloc pkt buffers based on specified blksize */ + if(data->set.tftp_blksize) + /* range checked when set */ + blksize = (int)data->set.tftp_blksize; + + need_blksize = blksize; + /* default size is the fallback when no OACK is received */ + if(need_blksize < TFTP_BLKSIZE_DEFAULT) + need_blksize = TFTP_BLKSIZE_DEFAULT; + + if(!state->rpacket.data) { + state->rpacket.data = curlx_calloc(1, need_blksize + 2 + 2); + + if(!state->rpacket.data) + return CURLE_OUT_OF_MEMORY; + } + + if(!state->spacket.data) { + state->spacket.data = curlx_calloc(1, need_blksize + 2 + 2); + + if(!state->spacket.data) + return CURLE_OUT_OF_MEMORY; + } + + /* we do not keep TFTP connections up because there is none or little gain + * for UDP */ + connclose(conn); + + state->data = data; + state->sockfd = conn->sock[FIRSTSOCKET]; + state->state = TFTP_STATE_START; + state->error = TFTP_ERR_NONE; + state->blksize = TFTP_BLKSIZE_DEFAULT; /* Unless updated by OACK response */ + state->requested_blksize = blksize; + + remote_addr = Curl_conn_get_remote_addr(data, FIRSTSOCKET); + DEBUGASSERT(remote_addr); + if(!remote_addr) + return CURLE_FAILED_INIT; + + ((struct sockaddr *)&state->local_addr)->sa_family = + (CURL_SA_FAMILY_T)remote_addr->family; + + result = tftp_set_timeouts(state); + if(result) + return result; + + if(!conn->bits.bound) { + /* If not already bound, bind to any interface, random UDP port. If it is + * reused or a custom local port was desired, this has already been done! + * + * We once used the size of the local_addr struct as the third argument + * for bind() to better work with IPv6 or whatever size the struct could + * have, but we learned that at least Tru64, AIX and IRIX *requires* the + * size of that argument to match the exact size of a 'sockaddr_in' struct + * when running IPv4-only. + * + * Therefore we use the size from the address we connected to, which we + * assume uses the same IP version and thus hopefully this works for both + * IPv4 and IPv6... + */ + int rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr, + (curl_socklen_t)remote_addr->addrlen); + if(rc) { + char buffer[STRERROR_LEN]; + failf(data, "bind() failed; %s", + curlx_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_COULDNT_CONNECT; + } + conn->bits.bound = TRUE; + } + + *done = TRUE; + + return CURLE_OK; +} + +/********************************************************** + * + * tftp_done + * + * The done callback + * + **********************************************************/ +static CURLcode tftp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct tftp_conn *state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN); + + (void)status; + (void)premature; + + if(Curl_pgrsDone(data)) + return CURLE_ABORTED_BY_CALLBACK; + + /* If we have encountered an error */ + if(state) + result = tftp_translate_code(state->error); + + return result; +} + +static CURLcode tftp_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + return Curl_pollset_add_in(data, ps, data->conn->sock[FIRSTSOCKET]); +} + +/********************************************************** + * + * tftp_receive_packet + * + * Called once select fires and data is ready on the socket + * + **********************************************************/ +static CURLcode tftp_receive_packet(struct Curl_easy *data, + struct tftp_conn *state) +{ + CURLcode result = CURLE_OK; + struct Curl_sockaddr_storage remote_addr; + curl_socklen_t fromlen = sizeof(remote_addr); + + /* Receive the packet */ + state->rbytes = (int)recvfrom(state->sockfd, + (void *)state->rpacket.data, + (RECV_TYPE_ARG3)state->blksize + 4, + 0, + (struct sockaddr *)&remote_addr, + &fromlen); + if((state->rbytes >= 0) && fromlen) { + if(state->remote_pinned) { + /* pinned, verify that it comes from the same address */ + if((state->remote_addrlen != fromlen) || + memcmp(&remote_addr, &state->remote_addr, fromlen)) { + failf(data, "Data received from another address"); + return CURLE_RECV_ERROR; + } + } + else { + /* pin address on first use */ + state->remote_pinned = TRUE; + state->remote_addrlen = fromlen; + memcpy(&state->remote_addr, &remote_addr, fromlen); + } + } + + /* Sanity check packet length */ + if(state->rbytes < 4) { + failf(data, "Received too short packet"); + /* Not a timeout, but how best to handle it? */ + state->event = TFTP_EVENT_TIMEOUT; + } + else { + /* The event is given by the TFTP packet time */ + unsigned short event = getrpacketevent(&state->rpacket); + state->event = (tftp_event_t)event; + + switch(state->event) { + case TFTP_EVENT_DATA: + /* Do not pass to the client empty or retransmitted packets */ + if(state->rbytes > 4 && + (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) { + result = Curl_client_write(data, CLIENTWRITE_BODY, + (const char *)state->rpacket.data + 4, + state->rbytes - 4); + if(result) { + tftp_state_machine(state, TFTP_EVENT_ERROR); + return result; + } + } + break; + case TFTP_EVENT_ERROR: { + unsigned short error = getrpacketblock(&state->rpacket); + const char *str = (const char *)state->rpacket.data + 4; + size_t strn = state->rbytes - 4; + state->error = (tftp_error_t)error; + if(tftp_strnlen(str, strn) < strn) + infof(data, "TFTP error: %s", str); + break; + } + case TFTP_EVENT_ACK: + break; + case TFTP_EVENT_OACK: + result = tftp_parse_option_ack(state, + (const char *)state->rpacket.data + 2, + state->rbytes-2); + if(result) + return result; + break; + case TFTP_EVENT_RRQ: + case TFTP_EVENT_WRQ: + default: + failf(data, "%s", "Internal error: Unexpected packet"); + break; + } + + /* Update the progress meter */ + result = Curl_pgrsUpdate(data); + if(result) { + tftp_state_machine(state, TFTP_EVENT_ERROR); + return result; + } + } + return result; +} + +/********************************************************** + * + * tftp_state_timeout + * + * Check if timeouts have been reached + * + **********************************************************/ +static timediff_t tftp_state_timeout(struct tftp_conn *state, + tftp_event_t *event) +{ + time_t current; + timediff_t timeout_ms; + + if(event) + *event = TFTP_EVENT_NONE; + + timeout_ms = Curl_timeleft_ms(state->data); + if(timeout_ms < 0) { + state->error = TFTP_ERR_TIMEOUT; + state->state = TFTP_STATE_FIN; + return timeout_ms; + } + current = time(NULL); + if(current > state->rx_time + state->retry_time) { + if(event) + *event = TFTP_EVENT_TIMEOUT; + state->rx_time = time(NULL); /* update even though we received nothing */ + } + + return timeout_ms; +} + +/********************************************************** + * + * tftp_multi_statemach + * + * Handle single RX socket event and return + * + **********************************************************/ +static CURLcode tftp_multi_statemach(struct Curl_easy *data, bool *done) +{ + tftp_event_t event; + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct tftp_conn *state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN); + timediff_t timeout_ms; + + *done = FALSE; + if(!state) + return CURLE_FAILED_INIT; + + timeout_ms = tftp_state_timeout(state, &event); + if(timeout_ms < 0) { + failf(data, "TFTP response timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + if(event != TFTP_EVENT_NONE) { + result = tftp_state_machine(state, event); + if(result) + return result; + *done = (state->state == TFTP_STATE_FIN); + if(*done) + /* Tell curl we are done */ + Curl_xfer_setup_nop(data); + } + else { + /* no timeouts to handle, check our socket */ + int rc = SOCKET_READABLE(state->sockfd, 0); + + if(rc == -1) { + /* bail out */ + int sockerr = SOCKERRNO; + char buffer[STRERROR_LEN]; + failf(data, "%s", curlx_strerror(sockerr, buffer, sizeof(buffer))); + state->event = TFTP_EVENT_ERROR; + } + else if(rc) { + result = tftp_receive_packet(data, state); + if(result) + return result; + result = tftp_state_machine(state, state->event); + if(result) + return result; + *done = (state->state == TFTP_STATE_FIN); + if(*done) + /* Tell curl we are done */ + Curl_xfer_setup_nop(data); + } + /* if rc == 0, then select() timed out */ + } + + return result; +} + +/********************************************************** + * + * tftp_doing + * + * Called from multi.c while DOing + * + **********************************************************/ +static CURLcode tftp_doing(struct Curl_easy *data, bool *dophase_done) +{ + CURLcode result; + result = tftp_multi_statemach(data, dophase_done); + + if(*dophase_done) { + DEBUGF(infof(data, "DO phase is complete")); + } + else if(!result) { + /* The multi code does not have this logic for the DOING state so we + provide it for TFTP since it may do the entire transfer in this + state. */ + result = Curl_pgrsCheck(data); + } + return result; +} + +/********************************************************** + * + * tftp_perform + * + * Entry point for transfer from tftp_do, starts state mach + * + **********************************************************/ +static CURLcode tftp_perform(struct Curl_easy *data, bool *dophase_done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct tftp_conn *state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN); + + *dophase_done = FALSE; + if(!state) + return CURLE_FAILED_INIT; + + result = tftp_state_machine(state, TFTP_EVENT_INIT); + + if((state->state == TFTP_STATE_FIN) || result) + return result; + + result = tftp_multi_statemach(data, dophase_done); + + if(*dophase_done) + DEBUGF(infof(data, "DO phase is complete")); + + return result; +} + +/********************************************************** + * + * tftp_do + * + * The do callback + * + * This callback initiates the TFTP transfer + * + **********************************************************/ + +static CURLcode tftp_do(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct tftp_conn *state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN); + CURLcode result; + + *done = FALSE; + + if(!state) { + result = tftp_connect(data, done); + if(result) + return result; + + state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN); + if(!state) + return CURLE_TFTP_ILLEGAL; + } + + result = tftp_perform(data, done); + + /* If tftp_perform() returned an error, use that for return code. If it + was OK, see if tftp_translate_code() has an error. */ + if(!result) + /* If we have encountered an internal tftp error, translate it. */ + result = tftp_translate_code(state->error); + + return result; +} + +static CURLcode tftp_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + char *path = data->state.up.path; + size_t len = strlen(path); + + conn->transport_wanted = TRNSPRT_UDP; + + /* TFTP URLs support a trailing ";mode=netascii" or ";mode=octet" */ + if((len >= 14) && !memcmp(&path[len - 14], ";mode=netascii", 14)) { + data->state.prefer_ascii = TRUE; + path[len - 14] = 0; /* cut it there */ + } + else if((len >= 11) && !memcmp(&path[len - 11], ";mode=octet", 11)) { + data->state.prefer_ascii = FALSE; + path[len - 11] = 0; /* cut it there */ + } + + return CURLE_OK; +} + +/* + * TFTP protocol handler. + */ +const struct Curl_protocol Curl_protocol_tftp = { + tftp_setup_connection, /* setup_connection */ + tftp_do, /* do_it */ + tftp_done, /* done */ + ZERO_NULL, /* do_more */ + tftp_connect, /* connect_it */ + tftp_multi_statemach, /* connecting */ + tftp_doing, /* doing */ + tftp_pollset, /* proto_pollset */ + tftp_pollset, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + ZERO_NULL, /* perform_pollset */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/tftp.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/tftp.h new file mode 100644 index 0000000000..32310103b0 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/tftp.h @@ -0,0 +1,33 @@ +#ifndef HEADER_CURL_TFTP_H +#define HEADER_CURL_TFTP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_TFTP +extern const struct Curl_protocol Curl_protocol_tftp; +#endif + +#define TFTP_BLKSIZE_MIN 8 +#define TFTP_BLKSIZE_MAX 65464 + +#endif /* HEADER_CURL_TFTP_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/thrdpool.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/thrdpool.c new file mode 100644 index 0000000000..900fd1cfc0 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/thrdpool.c @@ -0,0 +1,502 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_THREADS + +#include "llist.h" +#include "curl_threads.h" +#include "curlx/timeval.h" +#include "curlx/strparse.h" +#include "thrdpool.h" +#ifdef CURLVERBOSE +#include "curl_trc.h" +#include "urldata.h" +#endif + + +struct thrdslot { + struct Curl_llist_node node; + struct curl_thrdpool *tpool; + curl_thread_t thread; + curl_cond_t await; + struct curltime starttime; + const char *work_description; + timediff_t work_timeout_ms; + uint32_t id; + BIT(running); + BIT(idle); +}; + +struct curl_thrdpool { + const char *name; + uint64_t refcount; + curl_mutex_t lock; + curl_cond_t await; + struct Curl_llist slots; + struct Curl_llist zombies; + Curl_thrdpool_take_item_cb *fn_take; + Curl_thrdpool_process_item_cb *fn_process; + Curl_thrdpool_return_item_cb *fn_return; + void *fn_user_data; + CURLcode fatal_err; + uint32_t min_threads; + uint32_t max_threads; + uint32_t idle_time_ms; + uint32_t next_id; +#ifdef DEBUGBUILD + int dbg_fail_starts; /* fail this many thread starts */ +#endif + BIT(aborted); + BIT(detached); +}; + +static void thrdpool_join_zombies(struct curl_thrdpool *tpool); +static bool thrdpool_unlink(struct curl_thrdpool *tpool, bool locked); + +static void thrdslot_destroy(struct thrdslot *tslot) +{ + DEBUGASSERT(tslot->thread == curl_thread_t_null); + DEBUGASSERT(!tslot->running); + Curl_cond_destroy(&tslot->await); + curlx_free(tslot); +} + +static void thrdslot_done(struct thrdslot *tslot) +{ + struct curl_thrdpool *tpool = tslot->tpool; + + DEBUGASSERT(Curl_node_llist(&tslot->node) == &tpool->slots); + Curl_node_remove(&tslot->node); + tslot->running = FALSE; + Curl_llist_append(&tpool->zombies, tslot, &tslot->node); + Curl_cond_signal(&tpool->await); +} + +static CURL_THREAD_RETURN_T CURL_STDCALL thrdslot_run(void *arg) +{ + struct thrdslot *tslot = arg; + struct curl_thrdpool *tpool = tslot->tpool; + void *item; + + Curl_mutex_acquire(&tpool->lock); + DEBUGASSERT(Curl_node_llist(&tslot->node) == &tpool->slots); + for(;;) { + while(!tpool->aborted) { + tslot->work_description = NULL; + tslot->work_timeout_ms = 0; + item = tpool->fn_take(tpool->fn_user_data, &tslot->work_description, + &tslot->work_timeout_ms); + if(!item) + break; + tslot->starttime = curlx_now(); + tslot->idle = FALSE; + Curl_mutex_release(&tpool->lock); + + tpool->fn_process(item); + + Curl_mutex_acquire(&tpool->lock); + tslot->work_description = NULL; + tpool->fn_return(item, tpool->aborted ? NULL : tpool->fn_user_data); + } + + if(tpool->aborted || + (Curl_llist_count(&tpool->slots) > tpool->max_threads)) + goto out; + + tslot->idle = TRUE; + tslot->starttime = curlx_now(); + thrdpool_join_zombies(tpool); + Curl_cond_signal(&tpool->await); + /* Only wait with idle timeout when we are above the minimum + * number of threads. Otherwise short idle timeouts will keep + * on activating threads that have no means to shut down. */ + if((tpool->idle_time_ms > 0) && + (Curl_llist_count(&tpool->slots) > tpool->min_threads)) { + CURLcode result = Curl_cond_timedwait(&tslot->await, &tpool->lock, + tpool->idle_time_ms); + if((result == CURLE_OPERATION_TIMEDOUT) && + (Curl_llist_count(&tpool->slots) > tpool->min_threads)) { + goto out; + } + } + else { + Curl_cond_wait(&tslot->await, &tpool->lock); + } + } + +out: + thrdslot_done(tslot); + if(!thrdpool_unlink(tslot->tpool, TRUE)) { + /* tpool not destroyed */ + Curl_mutex_release(&tpool->lock); + } + return 0; +} + +static CURLcode thrdslot_start(struct curl_thrdpool *tpool) +{ + struct thrdslot *tslot; + CURLcode result = CURLE_OUT_OF_MEMORY; + + tslot = curlx_calloc(1, sizeof(*tslot)); + if(!tslot) + goto out; + tslot->id = tpool->next_id++; + tslot->tpool = tpool; + tslot->thread = curl_thread_t_null; + Curl_cond_init(&tslot->await); + + tpool->refcount++; + tslot->running = TRUE; +#ifdef DEBUGBUILD + if(tpool->dbg_fail_starts > 0) { + --tpool->dbg_fail_starts; + tslot->thread = curl_thread_t_null; + } + else +#endif + tslot->thread = Curl_thread_create(thrdslot_run, tslot); + if(tslot->thread == curl_thread_t_null) { /* never started */ + tslot->running = FALSE; + thrdpool_unlink(tpool, TRUE); + result = CURLE_FAILED_INIT; + goto out; + } + + Curl_llist_append(&tpool->slots, tslot, &tslot->node); + tslot = NULL; + result = CURLE_OK; + +out: + if(tslot) + thrdslot_destroy(tslot); + return result; +} + +static void thrdpool_wake_all(struct curl_thrdpool *tpool) +{ + struct Curl_llist_node *e; + for(e = Curl_llist_head(&tpool->slots); e; e = Curl_node_next(e)) { + struct thrdslot *tslot = Curl_node_elem(e); + Curl_cond_signal(&tslot->await); + } +} + +static void thrdpool_join_zombies(struct curl_thrdpool *tpool) +{ + struct Curl_llist_node *e; + + for(e = Curl_llist_head(&tpool->zombies); e; + e = Curl_llist_head(&tpool->zombies)) { + struct thrdslot *tslot = Curl_node_elem(e); + + Curl_node_remove(&tslot->node); + if(tslot->thread != curl_thread_t_null) { + Curl_mutex_release(&tpool->lock); + Curl_thread_join(&tslot->thread); + Curl_mutex_acquire(&tpool->lock); + tslot->thread = curl_thread_t_null; + } + thrdslot_destroy(tslot); + } +} + +static bool thrdpool_unlink(struct curl_thrdpool *tpool, bool locked) +{ + DEBUGASSERT(tpool->refcount); + if(tpool->refcount) + tpool->refcount--; + if(tpool->refcount) + return FALSE; + + /* no more references, free */ + DEBUGASSERT(tpool->aborted); + thrdpool_join_zombies(tpool); + if(locked) + Curl_mutex_release(&tpool->lock); + Curl_cond_destroy(&tpool->await); + Curl_mutex_destroy(&tpool->lock); + curlx_free(tpool); + return TRUE; +} + +static CURLcode thrdpool_signal(struct curl_thrdpool *tpool, + uint32_t nthreads) +{ + struct Curl_llist_node *e, *n; + CURLcode result = CURLE_OK; + + DEBUGASSERT(!tpool->aborted); + thrdpool_join_zombies(tpool); + + for(e = Curl_llist_head(&tpool->slots); e && nthreads; e = n) { + struct thrdslot *tslot = Curl_node_elem(e); + n = Curl_node_next(e); + if(tslot->idle) { + Curl_cond_signal(&tslot->await); + --nthreads; + } + else if(!tslot->starttime.tv_sec && !tslot->starttime.tv_usec) { + /* starting thread, queries for work soon. */ + --nthreads; + } + } + + while(nthreads && !result && + Curl_llist_count(&tpool->slots) < tpool->max_threads) { + result = thrdslot_start(tpool); + if(result) + break; + --nthreads; + } + + return result; +} + +CURLcode Curl_thrdpool_set_props(struct curl_thrdpool *tpool, + uint32_t min_threads, + uint32_t max_threads, + uint32_t idle_time_ms) +{ + CURLcode result = CURLE_OK; + size_t running; + + if(!max_threads || (min_threads > max_threads)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + Curl_mutex_acquire(&tpool->lock); + tpool->min_threads = min_threads; + tpool->max_threads = max_threads; + tpool->idle_time_ms = idle_time_ms; + running = Curl_llist_count(&tpool->slots); + if(tpool->min_threads > running) { + result = thrdpool_signal(tpool, tpool->min_threads - (uint32_t)running); + } + Curl_mutex_release(&tpool->lock); + + return result; +} + +CURLcode Curl_thrdpool_create(struct curl_thrdpool **ptpool, + const char *name, + uint32_t min_threads, + uint32_t max_threads, + uint32_t idle_time_ms, + Curl_thrdpool_take_item_cb *fn_take, + Curl_thrdpool_process_item_cb *fn_process, + Curl_thrdpool_return_item_cb *fn_return, + void *user_data) +{ + struct curl_thrdpool *tpool; + CURLcode result = CURLE_OUT_OF_MEMORY; + DEBUGASSERT(name); + + tpool = curlx_calloc(1, sizeof(*tpool)); + if(!tpool) + goto out; + tpool->refcount = 1; + + Curl_mutex_init(&tpool->lock); + Curl_cond_init(&tpool->await); + Curl_llist_init(&tpool->slots, NULL); + Curl_llist_init(&tpool->zombies, NULL); + tpool->fn_take = fn_take; + tpool->fn_process = fn_process; + tpool->fn_return = fn_return; + tpool->fn_user_data = user_data; + + /* a const string that remains */ + tpool->name = name; + +#ifdef DEBUGBUILD + { + const char *p = getenv("CURL_DBG_THRDPOOL_FAIL_STARTS"); + if(p) { + curl_off_t l; + if(!curlx_str_number(&p, &l, INT_MAX)) + tpool->dbg_fail_starts = (int)l; + } + } +#endif + + result = Curl_thrdpool_set_props(tpool, min_threads, max_threads, + idle_time_ms); + +out: + if(result && tpool) { + tpool->aborted = TRUE; + thrdpool_unlink(tpool, FALSE); + tpool = NULL; + } + *ptpool = tpool; + return result; +} + +void Curl_thrdpool_destroy(struct curl_thrdpool *tpool, bool join) +{ + Curl_mutex_acquire(&tpool->lock); + + tpool->aborted = TRUE; + + while(join && Curl_llist_count(&tpool->slots)) { + thrdpool_wake_all(tpool); + Curl_cond_wait(&tpool->await, &tpool->lock); + } + + thrdpool_join_zombies(tpool); + + /* detach all still running threads */ + if(Curl_llist_count(&tpool->slots)) { + struct Curl_llist_node *e; + for(e = Curl_llist_head(&tpool->slots); e; e = Curl_node_next(e)) { + struct thrdslot *tslot = Curl_node_elem(e); + if(tslot->thread != curl_thread_t_null) + Curl_thread_destroy(&tslot->thread); + } + tpool->detached = TRUE; + } + + if(!thrdpool_unlink(tpool, TRUE)) { + /* tpool not destroyed */ + Curl_mutex_release(&tpool->lock); + } +} + +CURLcode Curl_thrdpool_signal(struct curl_thrdpool *tpool, uint32_t nthreads) +{ + CURLcode result; + + Curl_mutex_acquire(&tpool->lock); + result = thrdpool_signal(tpool, nthreads); + Curl_mutex_release(&tpool->lock); + return result; +} + +static bool thrdpool_all_idle(struct curl_thrdpool *tpool) +{ + struct Curl_llist_node *e; + for(e = Curl_llist_head(&tpool->slots); e; e = Curl_node_next(e)) { + struct thrdslot *tslot = Curl_node_elem(e); + if(!tslot->idle) + return FALSE; + } + return TRUE; +} + +CURLcode Curl_thrdpool_await_idle(struct curl_thrdpool *tpool, + uint32_t timeout_ms) +{ + CURLcode result = CURLE_OK; + struct curltime end = { 0 }; + + Curl_mutex_acquire(&tpool->lock); + DEBUGASSERT(!tpool->aborted); + if(tpool->aborted) { + result = CURLE_FAILED_INIT; + goto out; + } + + while(!thrdpool_all_idle(tpool)) { + if(timeout_ms) { + timediff_t remain_ms; + CURLcode r; + + if(!end.tv_sec && !end.tv_usec) { + end = curlx_now(); + end.tv_sec += (time_t)(timeout_ms / 1000); + end.tv_usec += (int)(timeout_ms % 1000) * 1000; + if(end.tv_usec >= 1000000) { + end.tv_sec++; + end.tv_usec -= 1000000; + } + } + remain_ms = curlx_timediff_ms(curlx_now(), end); + if(remain_ms <= 0) + r = CURLE_OPERATION_TIMEDOUT; + else + r = Curl_cond_timedwait(&tpool->await, &tpool->lock, + (uint32_t)remain_ms); + if(r == CURLE_OPERATION_TIMEDOUT) { + result = r; + break; + } + } + else { + Curl_cond_wait(&tpool->await, &tpool->lock); + } + } + +out: + thrdpool_join_zombies(tpool); + Curl_mutex_release(&tpool->lock); + return result; +} + +#ifdef CURLVERBOSE +void Curl_thrdpool_trace(struct curl_thrdpool *tpool, + struct Curl_easy *data) +{ + struct curl_trc_feat *feat = &Curl_trc_feat_threads; + if(Curl_trc_ft_is_verbose(data, feat)) { + struct Curl_llist_node *e; + struct curltime now = curlx_now(); + + Curl_mutex_acquire(&tpool->lock); + if(!Curl_llist_count(&tpool->slots)) { + Curl_trc_feat_infof(data, feat, "[TPOOL-%s] no threads running", + tpool->name); + } + for(e = Curl_llist_head(&tpool->slots); e; e = Curl_node_next(e)) { + struct thrdslot *tslot = Curl_node_elem(e); + timediff_t elapsed_ms = curlx_ptimediff_ms(&now, &tslot->starttime); + if(!tslot->running) { + Curl_trc_feat_infof(data, feat, "[TPOOL-%s] [%u]: not running", + tpool->name, tslot->id); + } + else if(!tslot->starttime.tv_sec && !tslot->starttime.tv_usec) { + Curl_trc_feat_infof(data, feat, "[TPOOL-%s] [%u]: starting...", + tpool->name, tslot->id); + } + else if(tslot->idle) { + Curl_trc_feat_infof(data, feat, "[TPOOL-%s] [%u]: idle for %" + FMT_TIMEDIFF_T "ms", + tpool->name, tslot->id, elapsed_ms); + } + else { + timediff_t remain_ms = tslot->work_timeout_ms ? + (tslot->work_timeout_ms - elapsed_ms) : 0; + Curl_trc_feat_infof(data, feat, "[TPOOL-%s] [%u]: busy %" + FMT_TIMEDIFF_T "ms, timeout in %" FMT_TIMEDIFF_T + "ms: %s", + tpool->name, tslot->id, elapsed_ms, remain_ms, + tslot->work_description); + } + } + Curl_mutex_release(&tpool->lock); + } +} +#endif + +#endif /* USE_THREADS */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/thrdpool.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/thrdpool.h new file mode 100644 index 0000000000..cc81fb6fcb --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/thrdpool.h @@ -0,0 +1,106 @@ +#ifndef HEADER_CURL_THRDPOOL_H +#define HEADER_CURL_THRDPOOL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "curlx/timediff.h" + +#ifdef USE_THREADS + +struct curl_thrdpool; +struct Curl_easy; + +/* Invoked under thread pool lock to get an "item" to work on. Must + * return NULL if there is nothing to do. + * Caller might return a descriptive string about the "item", where + * available. The string needs to have the same lifetime as the + * item itself. */ +typedef void *Curl_thrdpool_take_item_cb(void *user_data, + const char **pdescription, + timediff_t *ptimeout_ms); + +/* Invoked outside thread pool lock to process the item taken. */ +typedef void Curl_thrdpool_process_item_cb(void *item); + +/* Invoked under thread pool lock to return a processed item back + * to the producer. + * If the thread pool has been destroyed, `user_data` will be NULL + * and the callback is responsible to release all `item` resources. */ +typedef void Curl_thrdpool_return_item_cb(void *item, void *user_data); + +/* Create a new thread pool. + * @param name name of pool for tracing purposes + * @param min_threads minimum number of threads to have always running + * @param max_threads maximum number of threads running, ever. + * @param idle_time_ms maximum time a thread should wait for tasks to + * process before shutting down (unless the pool is + * already at minimum thread count), use 0 for + * infinite wait. + * @param fn_take take the next item to process + * @param fn_process process the item taken + * @param fn_return return the processed item + * @param user_data parameter passed to take/return callbacks + */ +CURLcode Curl_thrdpool_create(struct curl_thrdpool **ptpool, + const char *name, + uint32_t min_threads, + uint32_t max_threads, + uint32_t idle_time_ms, + Curl_thrdpool_take_item_cb *fn_take, + Curl_thrdpool_process_item_cb *fn_process, + Curl_thrdpool_return_item_cb *fn_return, + void *user_data); + +/* Destroy the thread pool, release its resources. + * With `join` being TRUE, the call will wait for all threads to finish + * processing before returning. On FALSE, it will detach all threads + * running. Ongoing item processing will continue to run and + * `fn_return` will be invoked with NULL user_data before the thread exits. + */ +void Curl_thrdpool_destroy(struct curl_thrdpool *tpool, bool join); + +/* Signal the pool to wake up `nthreads` idle worker threads, possible + * creating new threads up to the max limit. The number should reflect + * the items that can actually be taken for processing right away, e.g. + * the producers "queue" length of outstanding items. + */ +CURLcode Curl_thrdpool_signal(struct curl_thrdpool *tpool, uint32_t nthreads); + +CURLcode Curl_thrdpool_await_idle(struct curl_thrdpool *tpool, + uint32_t timeout_ms); + +/* Change the properties of a threadpool. */ +CURLcode Curl_thrdpool_set_props(struct curl_thrdpool *tpool, + uint32_t min_threads, + uint32_t max_threads, + uint32_t idle_time_ms); + +#ifdef CURLVERBOSE +void Curl_thrdpool_trace(struct curl_thrdpool *tpool, + struct Curl_easy *data); +#endif + +#endif /* USE_THREADS */ + +#endif /* HEADER_CURL_THRDPOOL_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/thrdqueue.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/thrdqueue.c new file mode 100644 index 0000000000..b009405905 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/thrdqueue.c @@ -0,0 +1,433 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_THREADS + +#include "llist.h" +#include "curl_threads.h" +#include "thrdpool.h" +#include "thrdqueue.h" +#include "curlx/timeval.h" +#ifdef CURLVERBOSE +#include "curl_trc.h" +#include "urldata.h" +#endif + + +struct curl_thrdq { + const char *name; + curl_mutex_t lock; + curl_cond_t await; + struct Curl_llist sendq; + struct Curl_llist recvq; + struct curl_thrdpool *tpool; + Curl_thrdq_item_free_cb *fn_free; + Curl_thrdq_item_process_cb *fn_process; + Curl_thrdq_ev_cb *fn_event; + void *fn_user_data; + BIT(aborted); +}; + +struct thrdq_item { + struct Curl_llist_node node; + Curl_thrdq_item_free_cb *fn_free; + Curl_thrdq_item_process_cb *fn_process; + void *item; + struct curltime start; + timediff_t timeout_ms; + const char *description; +}; + +static struct thrdq_item *thrdq_item_create(struct curl_thrdq *tqueue, + void *item, + const char *description, + timediff_t timeout_ms) +{ + struct thrdq_item *qitem; + + qitem = curlx_calloc(1, sizeof(*qitem)); + if(!qitem) + return NULL; + qitem->item = item; + qitem->description = description; + qitem->fn_free = tqueue->fn_free; + qitem->fn_process = tqueue->fn_process; + if(timeout_ms) { + qitem->start = curlx_now(); + qitem->timeout_ms = timeout_ms; + } + return qitem; +} + +static void thrdq_item_destroy(struct thrdq_item *qitem) +{ + if(qitem->item) + qitem->fn_free(qitem->item); + curlx_free(qitem); +} + +static void thrdq_item_list_dtor(void *user_data, void *elem) +{ + (void)user_data; + thrdq_item_destroy(elem); +} + +static void *thrdq_tpool_take(void *user_data, const char **pdescription, + timediff_t *ptimeout_ms) +{ + struct curl_thrdq *tqueue = user_data; + struct thrdq_item *qitem = NULL; + struct Curl_llist_node *e; + Curl_thrdq_ev_cb *fn_event = NULL; + void *fn_user_data = NULL; + + Curl_mutex_acquire(&tqueue->lock); + *pdescription = NULL; + *ptimeout_ms = 0; + if(!tqueue->aborted) { + e = Curl_llist_head(&tqueue->sendq); + if(e) { + struct curltime now = curlx_now(); + timediff_t timeout_ms; + while(e) { + qitem = Curl_node_take_elem(e); + timeout_ms = (!qitem->timeout_ms) ? 0 : + (qitem->timeout_ms - curlx_ptimediff_ms(&now, &qitem->start)); + if(timeout_ms < 0) { + /* timed out while queued, place on receive queue */ + Curl_llist_append(&tqueue->recvq, qitem, &qitem->node); + fn_event = tqueue->fn_event; + fn_user_data = tqueue->fn_user_data; + qitem = NULL; + e = Curl_llist_head(&tqueue->sendq); + continue; + } + else { + *pdescription = qitem->description; + *ptimeout_ms = timeout_ms; + break; + } + } + } + } + Curl_mutex_release(&tqueue->lock); + /* avoiding deadlocks */ + if(fn_event) + fn_event(tqueue, CURL_THRDQ_EV_ITEM_DONE, fn_user_data); + return qitem; +} + +static void thrdq_tpool_return(void *item, void *user_data) +{ + struct curl_thrdq *tqueue = user_data; + struct thrdq_item *qitem = item; + Curl_thrdq_ev_cb *fn_event = NULL; + void *fn_user_data = NULL; + + if(!tqueue) { + thrdq_item_destroy(item); + return; + } + + Curl_mutex_acquire(&tqueue->lock); + if(tqueue->aborted) { + thrdq_item_destroy(qitem); + } + else { + DEBUGASSERT(!Curl_node_llist(&qitem->node)); + Curl_llist_append(&tqueue->recvq, qitem, &qitem->node); + fn_event = tqueue->fn_event; + fn_user_data = tqueue->fn_user_data; + } + Curl_mutex_release(&tqueue->lock); + /* avoiding deadlocks */ + if(fn_event) + fn_event(tqueue, CURL_THRDQ_EV_ITEM_DONE, fn_user_data); +} + +static void thrdq_tpool_process(void *item) +{ + struct thrdq_item *qitem = item; + qitem->fn_process(qitem->item); +} + +static void thrdq_unlink(struct curl_thrdq *tqueue, bool locked, bool join) +{ + DEBUGASSERT(tqueue->aborted); + if(tqueue->tpool) { + if(locked) + Curl_mutex_release(&tqueue->lock); + Curl_thrdpool_destroy(tqueue->tpool, join); + tqueue->tpool = NULL; + if(locked) + Curl_mutex_acquire(&tqueue->lock); + } + + Curl_llist_destroy(&tqueue->sendq, NULL); + Curl_llist_destroy(&tqueue->recvq, NULL); + Curl_cond_destroy(&tqueue->await); + if(locked) + Curl_mutex_release(&tqueue->lock); + Curl_mutex_destroy(&tqueue->lock); + curlx_free(tqueue); +} + +CURLcode Curl_thrdq_create(struct curl_thrdq **ptqueue, + const char *name, + uint32_t min_threads, + uint32_t max_threads, + uint32_t idle_time_ms, + Curl_thrdq_item_free_cb *fn_free, + Curl_thrdq_item_process_cb *fn_process, + Curl_thrdq_ev_cb *fn_event, + void *user_data) +{ + struct curl_thrdq *tqueue; + CURLcode result = CURLE_OUT_OF_MEMORY; + DEBUGASSERT(name); + + tqueue = curlx_calloc(1, sizeof(*tqueue)); + if(!tqueue) + goto out; + + Curl_mutex_init(&tqueue->lock); + Curl_cond_init(&tqueue->await); + Curl_llist_init(&tqueue->sendq, thrdq_item_list_dtor); + Curl_llist_init(&tqueue->recvq, thrdq_item_list_dtor); + tqueue->fn_free = fn_free; + tqueue->fn_process = fn_process; + tqueue->fn_event = fn_event; + tqueue->fn_user_data = user_data; + + /* a const string that remains */ + tqueue->name = name; + + result = Curl_thrdpool_create(&tqueue->tpool, name, + min_threads, max_threads, idle_time_ms, + thrdq_tpool_take, + thrdq_tpool_process, + thrdq_tpool_return, + tqueue); + +out: + if(result && tqueue) { + tqueue->aborted = TRUE; + thrdq_unlink(tqueue, FALSE, TRUE); + tqueue = NULL; + } + *ptqueue = tqueue; + return result; +} + +void Curl_thrdq_destroy(struct curl_thrdq *tqueue, bool join) +{ + Curl_mutex_acquire(&tqueue->lock); + DEBUGASSERT(!tqueue->aborted); + tqueue->aborted = TRUE; + thrdq_unlink(tqueue, TRUE, join); +} + +static uint32_t thrdq_get_signals(struct curl_thrdq *tqueue) +{ + size_t qlen = Curl_llist_count(&tqueue->sendq); + return (qlen <= UINT32_MAX) ? (uint32_t)qlen : UINT32_MAX; +} + +CURLcode Curl_thrdq_send(struct curl_thrdq *tqueue, void *item, + const char *description, timediff_t timeout_ms) +{ + struct thrdq_item *qitem; + CURLcode result = CURLE_OK; + uint32_t signals = 0; + + Curl_mutex_acquire(&tqueue->lock); + if(tqueue->aborted) { + DEBUGASSERT(0); + result = CURLE_SEND_ERROR; + goto out; + } + if(timeout_ms < 0) { + result = CURLE_OPERATION_TIMEDOUT; + goto out; + } + + qitem = thrdq_item_create(tqueue, item, description, timeout_ms); + if(!qitem) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + Curl_llist_append(&tqueue->sendq, qitem, &qitem->node); + signals = thrdq_get_signals(tqueue); + +out: + Curl_mutex_release(&tqueue->lock); + /* Signal thread pool unlocked to avoid deadlocks. Since we added + * item to the queue already, it might have been taken for processing + * already. Any error in signalling the pool cannot be reported to + * the caller since it needs to give up ownership of item. */ + if(!result && signals) + (void)Curl_thrdpool_signal(tqueue->tpool, (uint32_t)signals); + return result; +} + +bool Curl_thrdq_check_started(struct curl_thrdq *tqueue) +{ + size_t unprocessed; + + Curl_mutex_acquire(&tqueue->lock); + unprocessed = tqueue->aborted ? 0 : Curl_llist_count(&tqueue->sendq); + Curl_mutex_release(&tqueue->lock); + return !unprocessed || + !Curl_thrdpool_signal(tqueue->tpool, (uint32_t)unprocessed); +} + +CURLcode Curl_thrdq_recv(struct curl_thrdq *tqueue, void **pitem) +{ + CURLcode result = CURLE_AGAIN; + struct Curl_llist_node *e; + uint32_t signals = 0; + + *pitem = NULL; + Curl_mutex_acquire(&tqueue->lock); + if(tqueue->aborted) { + DEBUGASSERT(0); + result = CURLE_RECV_ERROR; + goto out; + } + + e = Curl_llist_head(&tqueue->recvq); + if(e) { + struct thrdq_item *qitem = Curl_node_take_elem(e); + *pitem = qitem->item; + qitem->item = NULL; + thrdq_item_destroy(qitem); + result = CURLE_OK; + } + else + signals = thrdq_get_signals(tqueue); + +out: + Curl_mutex_release(&tqueue->lock); + /* Signal thread pool unlocked to avoid deadlocks. If items await + * processing while nothing was ready, make sure the pool has a + * thread to work on them. An earlier thread start may have failed, + * which `Curl_thrdq_send()` cannot report to its caller. Without + * this, such items would sit unprocessed until the next send. */ + if(signals) + (void)Curl_thrdpool_signal(tqueue->tpool, (uint32_t)signals); + return result; +} + +static void thrdq_llist_clean_matches(struct Curl_llist *llist, + Curl_thrdq_item_match_cb *fn_match, + void *match_data) +{ + struct Curl_llist_node *e, *n; + struct thrdq_item *qitem; + + for(e = Curl_llist_head(llist); e; e = n) { + n = Curl_node_next(e); + qitem = Curl_node_elem(e); + if(fn_match(qitem->item, match_data)) + Curl_node_remove(e); + } +} + +void Curl_thrdq_clear(struct curl_thrdq *tqueue, + Curl_thrdq_item_match_cb *fn_match, + void *match_data) +{ + Curl_mutex_acquire(&tqueue->lock); + if(tqueue->aborted) { + DEBUGASSERT(0); + goto out; + } + thrdq_llist_clean_matches(&tqueue->sendq, fn_match, match_data); + thrdq_llist_clean_matches(&tqueue->recvq, fn_match, match_data); +out: + Curl_mutex_release(&tqueue->lock); +} + +#ifdef UNITTESTS +/* @unittest 3301 */ +UNITTEST CURLcode thrdq_await_done(struct curl_thrdq *tqueue, + uint32_t timeout_ms); +UNITTEST CURLcode thrdq_await_done(struct curl_thrdq *tqueue, + uint32_t timeout_ms) +{ + return Curl_thrdpool_await_idle(tqueue->tpool, timeout_ms); +} +#endif + +CURLcode Curl_thrdq_set_props(struct curl_thrdq *tqueue, + uint32_t min_threads, + uint32_t max_threads, + uint32_t idle_time_ms) +{ + CURLcode result; + uint32_t signals; + + Curl_mutex_acquire(&tqueue->lock); + signals = thrdq_get_signals(tqueue); + Curl_mutex_release(&tqueue->lock); + + result = Curl_thrdpool_set_props(tqueue->tpool, min_threads, + max_threads, idle_time_ms); + if(!result && signals) + result = Curl_thrdpool_signal(tqueue->tpool, (uint32_t)signals); + return result; +} + +#ifdef CURLVERBOSE +void Curl_thrdq_trace(struct curl_thrdq *tqueue, + struct Curl_easy *data) +{ + struct curl_trc_feat *feat = &Curl_trc_feat_threads; + if(Curl_trc_ft_is_verbose(data, feat)) { + struct Curl_llist_node *e; + struct thrdq_item *qitem; + + Curl_thrdpool_trace(tqueue->tpool, data); + Curl_mutex_acquire(&tqueue->lock); + if(!Curl_llist_count(&tqueue->sendq) && + !Curl_llist_count(&tqueue->recvq)) { + Curl_trc_feat_infof(data, feat, "[TQUEUE-%s] empty", tqueue->name); + } + for(e = Curl_llist_head(&tqueue->sendq); e; e = Curl_node_next(e)) { + qitem = Curl_node_elem(e); + Curl_trc_feat_infof(data, feat, "[TQUEUE-%s] in: %s", + tqueue->name, qitem->description); + } + for(e = Curl_llist_head(&tqueue->recvq); e; e = Curl_node_next(e)) { + qitem = Curl_node_elem(e); + Curl_trc_feat_infof(data, feat, "[TQUEUE-%s] out: %s", + tqueue->name, qitem->description); + } + Curl_mutex_release(&tqueue->lock); + } +} +#endif + +#endif /* USE_THREADS */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/thrdqueue.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/thrdqueue.h new file mode 100644 index 0000000000..0d84f6f6f1 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/thrdqueue.h @@ -0,0 +1,127 @@ +#ifndef HEADER_CURL_THRDQUEUE_H +#define HEADER_CURL_THRDQUEUE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "curlx/timediff.h" + +struct curl_thrdq; + +#ifdef USE_THREADS + +struct Curl_easy; + +typedef enum { + CURL_THRDQ_EV_ITEM_DONE /* an item has been processed and is ready */ +} Curl_thrdq_event; + +/* Notification callback when "events" happen in the queue. May be called from + * any thread, queue is not locked. */ +typedef void Curl_thrdq_ev_cb(const struct curl_thrdq *tqueue, + Curl_thrdq_event ev, + void *user_data); + +/* Process a queued item. May be called from any thread. Queue is not + * locked. */ +typedef void Curl_thrdq_item_process_cb(void *item); + +/* Free an item. May be called from any thread at any time for an + * item that is in the queue (either before or after processing). */ +typedef void Curl_thrdq_item_free_cb(void *item); + +/* Create a new queue processing "items" by a thread pool. + */ +CURLcode Curl_thrdq_create(struct curl_thrdq **ptqueue, + const char *name, + uint32_t min_threads, + uint32_t max_threads, + uint32_t idle_time_ms, + Curl_thrdq_item_free_cb *fn_free, + Curl_thrdq_item_process_cb *fn_process, + Curl_thrdq_ev_cb *fn_event, /* optional */ + void *user_data); + +/* Destroy the queue, free all queued items unprocessed and destroy + * the thread pool used. + * @param join TRUE when thread pool shall be joined. FALSE for + * detaching any running threads. + */ +void Curl_thrdq_destroy(struct curl_thrdq *tqueue, bool join); + +/* Send "item" onto the queue. The caller needs to clear any reference + * to "item" on success, e.g. the queue takes ownership. + * `description` is an optional string describing the item for tracing + * purposes. It needs to have the same lifetime as `item`. + * + * With`timeout_ms` != 0, items that get stuck that long in the send + * queue are removed and added to the receive queue right away. + */ +CURLcode Curl_thrdq_send(struct curl_thrdq *tqueue, void *item, + const char *description, timediff_t timeout_ms); + +/* Receive the oldest, processed item from the queue again, if there is one. + * The caller takes ownership of the item received, e.g. the queue + * relinquishes all references to item. + * Returns CURLE_AGAIN when there is no processed item, setting `pitem` + * to NULL. When nothing has been processed while items await sending, + * the pool is signalled to make sure a worker thread exists: an + * earlier thread start may have failed. + */ +CURLcode Curl_thrdq_recv(struct curl_thrdq *tqueue, void **pitem); + +/* Check that items awaiting processing have a worker thread to run + * them, signalling the pool to start one when needed -- an earlier + * thread start may have failed. Returns TRUE when everything is ok: + * no items are waiting or the pool took the signal. FALSE when a + * thread start just failed again; callers may want to check again + * soon rather than wait indefinitely. + */ +bool Curl_thrdq_check_started(struct curl_thrdq *tqueue); + +/* Return TRUE if the passed "item" matches. */ +typedef bool Curl_thrdq_item_match_cb(void *item, void *match_data); + +/* Clear all scheduled/processed items that match from the queue. This + * will *not* be able to clear items that are being processed. + */ +void Curl_thrdq_clear(struct curl_thrdq *tqueue, + Curl_thrdq_item_match_cb *fn_match, + void *match_data); + +CURLcode Curl_thrdq_await_done(struct curl_thrdq *tqueue, + uint32_t timeout_ms); + +CURLcode Curl_thrdq_set_props(struct curl_thrdq *tqueue, + uint32_t min_threads, + uint32_t max_threads, + uint32_t idle_time_ms); + +#ifdef CURLVERBOSE +void Curl_thrdq_trace(struct curl_thrdq *tqueue, + struct Curl_easy *data); +#endif + +#endif /* USE_THREADS */ + +#endif /* HEADER_CURL_THRDQUEUE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/transfer.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/transfer.c new file mode 100644 index 0000000000..3b6c5c03dd --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/transfer.c @@ -0,0 +1,903 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NET_IF_H +#include <net/if.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif +#include <signal.h> + +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif + +#ifdef HAVE_SYS_SELECT_H +#include <sys/select.h> +#elif defined(HAVE_UNISTD_H) +#include <unistd.h> +#endif + +#ifndef HAVE_SOCKET +#error "We cannot compile without socket() support" +#endif + +#include "urldata.h" + +#include "cfilters.h" +#include "cw-out.h" +#include "transfer.h" +#include "sendf.h" +#include "curl_trc.h" +#include "progress.h" +#include "http.h" +#include "url.h" +#include "getinfo.h" +#include "multiif.h" +#include "connect.h" +#include "hsts.h" +#include "setopt.h" +#include "headers.h" +#include "bufref.h" +#include "rtsp.h" + +#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_IMAP) +/* + * checkheaders() checks the linked list of custom headers for a + * particular header (prefix). Provide the prefix without colon! + * + * Returns a pointer to the first matching header or NULL if none matched. + */ +char *Curl_checkheaders(const struct Curl_easy *data, + const char *thisheader, + const size_t thislen) +{ + struct curl_slist *head; + DEBUGASSERT(thislen); + DEBUGASSERT(thisheader[thislen - 1] != ':'); + + for(head = data->set.headers; head; head = head->next) { + if(curl_strnequal(head->data, thisheader, thislen) && + Curl_headersep(head->data[thislen])) + return head->data; + } + + return NULL; +} +#endif + +static int data_pending(struct Curl_easy *data, bool rcvd_eagain) +{ + struct connectdata *conn = data->conn; + + if(conn->scheme->protocol & PROTO_FAMILY_FTP) + return Curl_conn_data_pending(data, SECONDARYSOCKET); + + /* in the case of libssh2, we can never be really sure that we have emptied + its internal buffers so we MUST always try until we get EAGAIN back */ + return (!rcvd_eagain && + conn->scheme->protocol & (CURLPROTO_SCP | CURLPROTO_SFTP)) || + Curl_conn_data_pending(data, FIRSTSOCKET); +} + +/* + * Check to see if CURLOPT_TIMECONDITION was met by comparing the time of the + * remote document with the time provided by CURLOPT_TIMEVAL + */ +bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc) +{ + if((timeofdoc == 0) || (data->set.timevalue == 0)) + return TRUE; + + switch(data->set.timecondition) { + case CURL_TIMECOND_IFMODSINCE: + default: + if(timeofdoc <= data->set.timevalue) { + infof(data, "The requested document is not new enough"); + data->info.timecond = TRUE; + return FALSE; + } + break; + case CURL_TIMECOND_IFUNMODSINCE: + if(timeofdoc >= data->set.timevalue) { + infof(data, "The requested document is not old enough"); + data->info.timecond = TRUE; + return FALSE; + } + break; + } + + return TRUE; +} + +static CURLcode xfer_recv_shutdown(struct Curl_easy *data, bool *done) +{ + if(!data || !data->conn) + return CURLE_FAILED_INIT; + return Curl_conn_shutdown(data, data->conn->recv_idx, done); +} + +static bool xfer_recv_shutdown_started(struct Curl_easy *data) +{ + if(!data || !data->conn) + return FALSE; + return Curl_shutdown_started(data->conn, data->conn->recv_idx); +} + +CURLcode Curl_xfer_send_shutdown(struct Curl_easy *data, bool *done) +{ + if(!data || !data->conn) + return CURLE_FAILED_INIT; + return Curl_conn_shutdown(data, data->conn->send_idx, done); +} + +/** + * Receive raw response data for the transfer. + * @param data the transfer + * @param buf buffer to keep response data received + * @param blen length of `buf` + * @param eos_reliable if EOS detection in underlying connection is reliable + * @return number of bytes read or -1 for error + */ +static CURLcode xfer_recv_resp(struct Curl_easy *data, + char *buf, size_t blen, + bool eos_reliable, + size_t *pnread) +{ + CURLcode result; + + DEBUGASSERT(blen > 0); + *pnread = 0; + /* If we are reading BODY data and the connection does NOT handle EOF + * and we know the size of the BODY data, limit the read amount */ + if(!eos_reliable && !data->req.header && data->req.size != -1) { + blen = curlx_sotouz_range(data->req.size - data->req.bytecount, 0, blen); + } + else if(xfer_recv_shutdown_started(data)) { + /* we already received everything. Do not try more. */ + blen = 0; + } + + if(blen) { + result = Curl_xfer_recv(data, buf, blen, pnread); + if(result) + return result; + } + + if(*pnread == 0) { + if(data->req.shutdown) { + bool done; + result = xfer_recv_shutdown(data, &done); + if(result) + return result; + if(!done) { + return CURLE_AGAIN; + } + } + DEBUGF(infof(data, "sendrecv_dl: we are done")); + } + return CURLE_OK; +} + +/* + * Go ahead and do a read if we have a readable socket or if + * the stream was rewound (in which case we have data in a + * buffer) + */ +static CURLcode sendrecv_dl(struct Curl_easy *data, + struct SingleRequest *k) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + char *buf, *xfer_buf; + size_t blen, xfer_blen; + int maxloops = 10; + bool is_multiplex = FALSE; + bool rcvd_eagain = FALSE; + bool is_eos = FALSE, rate_limited = FALSE; + + result = Curl_multi_xfer_buf_borrow(data, &xfer_buf, &xfer_blen); + if(result) + goto out; + + /* This is where we loop until we have read everything there is to + read or we get a CURLE_AGAIN */ + do { + size_t bytestoread; + + if(!is_multiplex) { + /* Multiplexed connection have inherent handling of EOF and we do not + * have to carefully restrict the amount we try to read. + * Multiplexed changes only in one direction. */ + is_multiplex = Curl_conn_is_multiplex(conn, FIRSTSOCKET); + } + + buf = xfer_buf; + bytestoread = xfer_blen; + + if(bytestoread && Curl_rlimit_active(&data->progress.dl.rlimit)) { + curl_off_t dl_avail = Curl_rlimit_avail(&data->progress.dl.rlimit, NULL); +#if 0 + DEBUGF(infof(data, "dl_rlimit, available=%" FMT_OFF_T, dl_avail)); +#endif + /* In case of rate limited downloads: if this loop already got data and + * less than 16k is left in the limit, break out. We want to stutter a + * bit to keep in the limit, but too small receives will cost cpu + * unnecessarily. */ + if(dl_avail <= 0) { + rate_limited = TRUE; + break; + } + if(dl_avail < (curl_off_t)bytestoread) + bytestoread = (size_t)dl_avail; + } + + rcvd_eagain = FALSE; + result = xfer_recv_resp(data, buf, bytestoread, is_multiplex, &blen); + if(result) { + if(result != CURLE_AGAIN) + goto out; /* real error */ + rcvd_eagain = TRUE; + result = CURLE_OK; + if(data->req.download_done && data->req.no_body && + !data->req.resp_trailer) { + DEBUGF(infof(data, "EAGAIN, download done, no trailer announced, " + "not waiting for EOS")); + blen = 0; + /* continue as if we received the EOS */ + } + else + break; /* get out of loop */ + } + + /* We only get a 0-length receive at the end of the response */ + is_eos = (blen == 0); + + if(!blen) { + result = Curl_req_stop_send_recv(data); + if(result) + goto out; + if(k->eos_written) /* already did write this to client, leave */ + break; + } + + result = Curl_xfer_write_resp(data, buf, blen, is_eos); + if(result || data->req.done) + goto out; + + /* if we are done, we stop receiving. On multiplexed connections, + * we should read the EOS. Which may arrive as meta data after + * the bytes. Not taking it in might lead to RST of streams. */ + if((!is_multiplex && data->req.download_done) || is_eos) { + CURL_REQ_CLEAR_RECV(data); + } + /* if we stopped receiving, leave the loop */ + if(!CURL_REQ_WANT_RECV(data)) + break; + + } while(maxloops--); + + if(!is_eos && !rate_limited && CURL_REQ_WANT_RECV(data) && + (!rcvd_eagain || data_pending(data, rcvd_eagain))) { + /* Did not read until EAGAIN/EOS or there is still data pending + * in buffers. Mark as read-again via simulated SELECT results. */ + Curl_multi_mark_dirty(data); + CURL_TRC_M(data, "sendrecv_dl() no EAGAIN/pending data, mark as dirty"); + } + + if(!CURL_REQ_WANT_RECV(data) && CURL_REQ_WANT_SEND(data) && + (conn->bits.close || is_multiplex)) { + /* When we have read the entire thing and the close bit is set, the server + may now close the connection. If there is now any kind of sending going + on from our side, we need to stop that immediately. */ + infof(data, "we are done reading and this is set to close, stop send"); + Curl_req_abort_sending(data); + } + +out: + Curl_multi_xfer_buf_release(data, xfer_buf); + if(result) + DEBUGF(infof(data, "sendrecv_dl() -> %d", (int)result)); + return result; +} + +/* + * Send data to upload to the server, when the socket is writable. + */ +static CURLcode sendrecv_ul(struct Curl_easy *data) +{ + /* We should not get here when the sending is already done. */ + DEBUGASSERT(!Curl_req_done_sending(data)); + + if(!Curl_req_done_sending(data)) + return Curl_req_send_more(data); + return CURLE_OK; +} + +/* + * Curl_sendrecv() is the low-level function to be called when data is to + * be read and written to/from the connection. + */ +CURLcode Curl_sendrecv(struct Curl_easy *data) +{ + struct SingleRequest *k = &data->req; + const struct curltime *pnow = NULL; + CURLcode result = CURLE_OK; + + if(Curl_xfer_is_blocked(data)) { + result = CURLE_OK; + goto out; + } + + /* We go ahead and do a read if we have a readable socket or if the stream + was rewound (in which case we have data in a buffer) */ + if(CURL_REQ_WANT_RECV(data)) { + result = sendrecv_dl(data, k); + if(result || data->req.done) + goto out; + } + + /* If we still have writing to do, we check if we have a writable socket. */ + if(Curl_req_want_send(data)) { + result = sendrecv_ul(data); + if(result) + goto out; + } + + pnow = Curl_pgrs_now(data); + if(CURL_REQ_WANT_IO(data)) { + if(Curl_timeleft_now_ms(data, pnow) < 0) { + if(k->size != -1) { + failf(data, "Operation timed out after %" FMT_TIMEDIFF_T + " milliseconds with %" FMT_OFF_T " out of %" + FMT_OFF_T " bytes received", + Curl_pgrs_since_ms(data, NULL, TIMER_STARTSINGLE), + k->bytecount, k->size); + } + else { + failf(data, "Operation timed out after %" FMT_TIMEDIFF_T + " milliseconds with %" FMT_OFF_T " bytes received", + Curl_pgrs_since_ms(data, NULL, TIMER_STARTSINGLE), + k->bytecount); + } + result = CURLE_OPERATION_TIMEDOUT; + goto out; + } + } + else { + /* + * The transfer has been performed. Make some general checks before + * returning. + */ + if(!data->req.no_body && (k->size != -1) && + (k->bytecount != k->size) && !k->newurl) { + failf(data, "transfer closed with %" FMT_OFF_T + " bytes remaining to read", k->size - k->bytecount); + result = CURLE_PARTIAL_FILE; + goto out; + } + } + + /* If there is nothing more to send/recv, the request is done */ + if(!CURL_REQ_WANT_IO(data)) + data->req.done = TRUE; + + result = Curl_pgrsCheckX(data, pnow); + +out: + if(result) + DEBUGF(infof(data, "Curl_sendrecv() -> %d", (int)result)); + return result; +} + +/* Curl_init_CONNECT() gets called each time the handle switches to CONNECT + which means this gets called once for each subsequent redirect etc */ +void Curl_init_CONNECT(struct Curl_easy *data) +{ + data->state.fread_func = data->set.fread_func_set; + data->state.in = data->set.in_set; + data->state.upload = (data->state.httpreq == HTTPREQ_PUT); +} + +/* + * Curl_pretransfer() is called immediately before a transfer starts, and only + * once for one transfer no matter if it has redirects or do multi-pass + * authentication etc. + */ +CURLcode Curl_pretransfer(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + + /* Reset the retry count at the start of each request. + * If the retry count is not reset, when the connection drops, + * it will not enter the retry mechanism on CONN_MAX_RETRIES + 1 attempts + * and will immediately throw + * "Connection died, tried CONN_MAX_RETRIES times before giving up". + * By resetting it here, we ensure each new request starts fresh. */ + data->state.retrycount = 0; + + if(!CURL_EASY_STR(data, STRING_SET_URL) && !data->set.uh) { + /* we cannot do anything without URL */ + failf(data, "No URL set"); + return CURLE_URL_MALFORMAT; + } + + /* CURLOPT_CURLU overrides CURLOPT_URL and the contents of the CURLU handle + is allowed to be changed by the user between transfers */ + if(data->set.uh) { + char *url = NULL; + CURLUcode uc; + uc = curl_url_get(data->set.uh, CURLUPART_URL, &url, 0); + if(uc) { + /* clear the pointer to not point to freed memory anymore */ + Curl_bufref_set(&data->state.url, NULL, 0, NULL); + failf(data, "No URL set"); + return CURLE_URL_MALFORMAT; + } + result = CURL_EASY_STR_SETN(data, STRING_SET_URL, url); + if(result) + return result; + } + + Curl_bufref_set(&data->state.url, CURL_EASY_STR(data, STRING_SET_URL), + 0, NULL); + + if(data->set.postfields && data->set.set_resume_from) { + /* we cannot */ + failf(data, "cannot mix POSTFIELDS with RESUME_FROM"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + data->state.prefer_ascii = data->set.prefer_ascii; +#ifdef CURL_LIST_ONLY_PROTOCOL + data->state.list_only = data->set.list_only; +#endif + data->state.httpreq = data->set.method; + + /* initial transfer request coming up, forget the initial origin + * from a previous perform() on this handle. */ + Curl_peer_unlink(&data->state.initial_origin); + Curl_peer_unlink(&data->state.origin); + data->state.requests = 0; + data->state.followlocation = 0; /* reset the location-follow counter */ + data->state.this_is_a_follow = FALSE; /* reset this */ + data->state.http_ignorecustom = FALSE; /* use custom HTTP method */ + data->state.errorbuf = FALSE; /* no error has occurred */ +#ifndef CURL_DISABLE_HTTP + Curl_http_neg_init(data, &data->state.http_neg); +#endif + data->state.authproblem = FALSE; + data->state.authhost.want = data->set.httpauth; + data->state.authproxy.want = data->set.proxyauth; + curlx_safefree(data->info.wouldredirect); + Curl_data_priority_clear_state(data); + if(data->set.http_auto_referer) + Curl_bufref_free(&data->state.referer); + if(CURL_EASY_STR(data, STRING_SET_REFERER)) + Curl_bufref_set(&data->state.referer, + CURL_EASY_STR(data, STRING_SET_REFERER), 0, NULL); + else + Curl_bufref_free(&data->state.referer); + + if(data->state.httpreq == HTTPREQ_PUT) + data->state.infilesize = data->set.filesize; + else if((data->state.httpreq != HTTPREQ_GET) && + (data->state.httpreq != HTTPREQ_HEAD)) { + data->state.infilesize = data->set.postfieldsize; + if(data->set.postfields && (data->state.infilesize == -1)) + data->state.infilesize = (curl_off_t)strlen(data->set.postfields); + } + else + data->state.infilesize = 0; + + /* If there is a list of cookie files to read, do it now! */ + result = Curl_cookie_loadfiles(data, + data->set.cookiesession ? + COOKIE_NOSESSION : 0); + if(!result) + Curl_cookie_run(data); /* activate */ + + /* If there is a list of host pairs to deal with */ + if(!result && data->state.resolve) + result = Curl_loadhostpairs(data); + + if(!result) + /* If there is a list of hsts files to read */ + result = Curl_hsts_loadfiles(data); + + if(!result) { + /* Allow data->set.use_port to set which port to use. This needs to be + * disabled for example when we follow Location: headers to URLs using + * different ports! */ + data->state.allow_port = TRUE; + +#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(MSG_NOSIGNAL) + /************************************************************* + * Tell signal handler to ignore SIGPIPE + *************************************************************/ + if(!data->set.no_signal) + data->state.prev_signal = signal(SIGPIPE, SIG_IGN); +#endif + + Curl_initinfo(data); /* reset session-specific information "variables" */ + Curl_pgrsResetTransferSizes(data); + Curl_pgrsStart(data, NULL); + + /* In case the handle is reused and an authentication method was picked + in the session we need to make sure we only use the one(s) we now + consider to be fine */ + data->state.authhost.picked &= data->state.authhost.want; + data->state.authproxy.picked &= data->state.authproxy.want; + +#ifndef CURL_DISABLE_FTP + data->state.wildcardmatch = data->set.wildcard_enabled; + if(data->state.wildcardmatch) { + struct WildcardData *wc; + if(!data->wildcard) { + data->wildcard = curlx_calloc(1, sizeof(struct WildcardData)); + if(!data->wildcard) + return CURLE_OUT_OF_MEMORY; + } + wc = data->wildcard; + if(wc->state < CURLWC_INIT) { + if(wc->ftpwc) + wc->dtor(wc->ftpwc); + curlx_safefree(wc->pattern); + curlx_safefree(wc->path); + Curl_wildcard_init(wc); /* init wildcard structures */ + } + } +#endif + result = Curl_hsts_loadcb(data, data->hsts); + } + + data->req.headerbytecount = 0; + Curl_headers_cleanup(data); + return result; +} + +/* Returns CURLE_OK *and* sets '*url' if a request retry is wanted. + + NOTE: that the *url is curlx_malloc()ed. */ +CURLcode Curl_retry_request(struct Curl_easy *data, char **url) +{ + struct connectdata *conn = data->conn; + bool retry = FALSE; + *url = NULL; + + /* if we are talking upload, we cannot do the checks below, unless the + protocol is HTTP as when uploading over HTTP we will still get a + response */ + if(data->state.upload && + !(conn->scheme->protocol & (PROTO_FAMILY_HTTP | CURLPROTO_RTSP))) + return CURLE_OK; + + if(conn->bits.reuse && + (data->req.bytecount + data->req.headerbytecount == 0) && + ((!data->req.no_body && !data->req.done) || + (conn->scheme->protocol & PROTO_FAMILY_HTTP)) +#ifndef CURL_DISABLE_RTSP + && (data->set.rtspreq != RTSPREQ_RECEIVE) +#endif + ) + /* We got no data, we attempted to reuse a connection. For HTTP this + can be a retry so we try again regardless if we expected a body. + For other protocols we only try again only if we expected a body. + + This might happen if the connection was left alive when we were + done using it before, but that was closed when we wanted to read from + it again. Bad luck. Retry the same request on a fresh connect! */ + retry = TRUE; + else if(data->state.refused_stream && + (data->req.bytecount + data->req.headerbytecount == 0)) { + /* This was sent on a refused stream, safe to rerun. A refused stream + error can typically only happen on HTTP/2 level if the stream is safe + to issue again, but the nghttp2 API can deliver the message to other + streams as well, which is why this adds the check the data counters + too. */ + infof(data, "REFUSED_STREAM, retrying a fresh connect"); + data->state.refused_stream = FALSE; /* clear again */ + retry = TRUE; + } + if(retry) { +#define CONN_MAX_RETRIES 5 + if(data->state.retrycount++ >= CONN_MAX_RETRIES) { + failf(data, "Connection died, tried %d times before giving up", + CONN_MAX_RETRIES); + data->state.retrycount = 0; + return CURLE_SEND_ERROR; + } + infof(data, "Connection died, retrying a fresh connect (retry count: %d)", + data->state.retrycount); + *url = Curl_bufref_dup(&data->state.url); + if(!*url) + return CURLE_OUT_OF_MEMORY; + + connclose(conn); /* close this connection */ + conn->bits.retry = TRUE; /* mark this as a connection we are about to + retry. Marking it this way should prevent i.e + HTTP transfers to return error because nothing + has been transferred! */ + Curl_creader_set_rewind(data, TRUE); + } + return CURLE_OK; +} + +static void xfer_setup( + struct Curl_easy *data, /* transfer */ + int8_t send_idx, /* sockindex to send on or -1 */ + int8_t recv_idx, /* sockindex to receive on or -1 */ + curl_off_t recv_size /* how much to receive, -1 if unknown */ + ) +{ + struct SingleRequest *k = &data->req; + struct connectdata *conn = data->conn; + + DEBUGASSERT(conn); + /* indexes are in range */ + DEBUGASSERT((send_idx <= 1) && (send_idx >= -1)); + DEBUGASSERT((recv_idx <= 1) && (recv_idx >= -1)); + /* if request wants to send, switching off the send direction is wrong */ + DEBUGASSERT((send_idx >= 0) || !Curl_req_want_send(data)); + + conn->send_idx = send_idx; + conn->recv_idx = recv_idx; + + /* without receiving, there should be not recv_size */ + DEBUGASSERT((conn->recv_idx >= 0) || (recv_size == -1)); + k->size = recv_size; + k->header = !!conn->scheme->run->write_resp_hd; + /* by default, we do not shutdown at the end of the transfer */ + k->shutdown = FALSE; + k->shutdown_err_ignore = FALSE; + + /* The code sequence below is placed in this function because all necessary + input is not always known in do_complete() as this function may be called + after that */ + if(!k->header && (recv_size > 0)) + Curl_pgrsSetDownloadSize(data, recv_size); + + /* we want header and/or body, if neither then do not do this! */ + if(conn->scheme->run->write_resp_hd || !data->req.no_body) { + if(conn->recv_idx != -1) + CURL_REQ_SET_RECV(data); + if(conn->send_idx != -1) + CURL_REQ_SET_SEND(data); + } + CURL_TRC_M(data, "xfer_setup: recv_idx=%d, send_idx=%d", + conn->recv_idx, conn->send_idx); +} + +void Curl_xfer_setup_nop(struct Curl_easy *data) +{ + xfer_setup(data, -1, -1, -1); +} + +void Curl_xfer_setup_sendrecv(struct Curl_easy *data, + int8_t sockindex, + curl_off_t recv_size) +{ + xfer_setup(data, sockindex, sockindex, recv_size); +} + +void Curl_xfer_setup_send(struct Curl_easy *data, + int8_t sockindex) +{ + xfer_setup(data, sockindex, -1, -1); +} + +void Curl_xfer_setup_recv(struct Curl_easy *data, + int8_t sockindex, + curl_off_t recv_size) +{ + xfer_setup(data, -1, sockindex, recv_size); +} + +void Curl_xfer_set_shutdown(struct Curl_easy *data, + bool shutdown, + bool ignore_errors) +{ + /* Shutdown should only be set when the transfer only sends or receives. */ + DEBUGASSERT(!shutdown || + (data->conn->send_idx < 0) || (data->conn->recv_idx < 0)); + data->req.shutdown = shutdown; + data->req.shutdown_err_ignore = ignore_errors; +} + +CURLcode Curl_xfer_write_resp(struct Curl_easy *data, + const char *buf, size_t blen, + bool is_eos) +{ + CURLcode result = CURLE_OK; + + if(data->conn->scheme->run->write_resp) { + /* protocol handlers offering this function take full responsibility + * for writing all received download data to the client. */ + result = data->conn->scheme->run->write_resp(data, buf, blen, is_eos); + } + else { + /* No special handling by protocol handler, write all received data + * as BODY to the client. */ + if(blen || is_eos) { + int cwtype = CLIENTWRITE_BODY; + if(is_eos) + cwtype |= CLIENTWRITE_EOS; + result = Curl_client_write(data, cwtype, buf, blen); + } + } + + if(!result && is_eos) { + /* If we wrote the EOS, we are definitely done */ + data->req.eos_written = TRUE; + data->req.download_done = TRUE; + } + CURL_TRC_WRITE(data, "xfer_write_resp(len=%zu, eos=%d) -> %d", + blen, is_eos, (int)result); + return result; +} + +bool Curl_xfer_write_is_paused(struct Curl_easy *data) +{ + return Curl_cwriter_is_paused(data); +} + +CURLcode Curl_xfer_write_resp_hd(struct Curl_easy *data, + const char *hd0, size_t hdlen, bool is_eos) +{ + if(data->conn->scheme->run->write_resp_hd) { + DEBUGASSERT(!hd0[hdlen]); /* null-terminated */ + /* protocol handlers offering this function take full responsibility + * for writing all received download data to the client. */ + return data->conn->scheme->run->write_resp_hd(data, hd0, hdlen, is_eos); + } + /* No special handling by protocol handler, write as response bytes */ + return Curl_xfer_write_resp(data, hd0, hdlen, is_eos); +} + +CURLcode Curl_xfer_write_done(struct Curl_easy *data, bool premature) +{ + (void)premature; + return Curl_cw_out_done(data); +} + +bool Curl_xfer_needs_flush(struct Curl_easy *data) +{ + return Curl_conn_needs_flush(data, data->conn->send_idx); +} + +CURLcode Curl_xfer_flush(struct Curl_easy *data) +{ + return Curl_conn_flush(data, data->conn->send_idx); +} + +CURLcode Curl_xfer_send(struct Curl_easy *data, + const void *buf, size_t blen, bool eos, + size_t *pnwritten) +{ + CURLcode result; + + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + + result = Curl_conn_send(data, data->conn->send_idx, + buf, blen, eos, pnwritten); + if(result == CURLE_AGAIN) { + result = CURLE_OK; + *pnwritten = 0; + } + else if(!result && *pnwritten) + data->info.request_size += *pnwritten; + + DEBUGF(infof(data, "Curl_xfer_send(len=%zu, eos=%d) -> %d, %zu", + blen, eos, (int)result, *pnwritten)); + return result; +} + +CURLcode Curl_xfer_recv(struct Curl_easy *data, + char *buf, size_t blen, + size_t *pnrcvd) +{ + DEBUGASSERT(data); + DEBUGASSERT(data->conn); + DEBUGASSERT(data->set.buffer_size > 0); + + if(curlx_uitouz(data->set.buffer_size) < blen) + blen = curlx_uitouz(data->set.buffer_size); + return Curl_conn_recv(data, data->conn->recv_idx, buf, blen, pnrcvd); +} + +CURLcode Curl_xfer_send_close(struct Curl_easy *data) +{ + Curl_conn_ev_data_done_send(data); + return CURLE_OK; +} + +bool Curl_xfer_is_blocked(struct Curl_easy *data) +{ + bool want_send = CURL_REQ_WANT_SEND(data); + bool want_recv = CURL_REQ_WANT_RECV(data); + if(!want_send) + return want_recv && Curl_xfer_recv_is_paused(data); + else if(!want_recv) + return want_send && Curl_xfer_send_is_paused(data); + else + return Curl_xfer_recv_is_paused(data) && Curl_xfer_send_is_paused(data); +} + +bool Curl_xfer_send_is_paused(struct Curl_easy *data) +{ + return Curl_rlimit_is_blocked(&data->progress.ul.rlimit); +} + +bool Curl_xfer_recv_is_paused(struct Curl_easy *data) +{ + return Curl_rlimit_is_blocked(&data->progress.dl.rlimit); +} + +CURLcode Curl_xfer_pause_send(struct Curl_easy *data, bool enable) +{ + CURLcode result = CURLE_OK; + Curl_rlimit_block(&data->progress.ul.rlimit, enable, Curl_pgrs_now(data)); + if(!enable && Curl_creader_is_paused(data)) + result = Curl_creader_unpause(data); + Curl_pgrsSendPause(data, enable); + return result; +} + +CURLcode Curl_xfer_pause_recv(struct Curl_easy *data, bool enable) +{ + CURLcode result = CURLE_OK; + Curl_rlimit_block(&data->progress.dl.rlimit, enable, Curl_pgrs_now(data)); + if(!enable && Curl_cwriter_is_paused(data)) + result = Curl_cwriter_unpause(data); + Curl_conn_ev_data_pause(data, enable); + Curl_pgrsRecvPause(data, enable); + return result; +} + +bool Curl_xfer_is_secure(struct Curl_easy *data) +{ +#ifndef CURL_DISABLE_PROXY + if(data->conn && data->conn->bits.origin_is_proxy) { + /* talking to a forward proxy, not secure. we do not use + * a forward proxy for https: and other 's' URLs. Let's just check that + * this did not fail somewhere. */ + DEBUGASSERT(!(data->state.origin->scheme->flags & PROTOPT_SSL)); + return FALSE; + } +#endif + return (data->state.origin->scheme->flags & PROTOPT_SSL); +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/transfer.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/transfer.h new file mode 100644 index 0000000000..0ad0d549ed --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/transfer.h @@ -0,0 +1,154 @@ +#ifndef HEADER_CURL_TRANSFER_H +#define HEADER_CURL_TRANSFER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#define Curl_headersep(x) ((((x) == ':') || ((x) == ';'))) + +char *Curl_checkheaders(const struct Curl_easy *data, + const char *thisheader, + const size_t thislen); + +void Curl_init_CONNECT(struct Curl_easy *data); + +CURLcode Curl_pretransfer(struct Curl_easy *data); + +CURLcode Curl_sendrecv(struct Curl_easy *data); +CURLcode Curl_retry_request(struct Curl_easy *data, char **url); +bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc); + +/** + * Write the transfer raw response bytes, as received from the connection. + * Handle all passed bytes or return an error. By default, this writes + * the bytes as BODY to the client. Protocols may provide a + * "write_resp" callback in their handler to add specific treatment. E.g. + * HTTP parses response headers and passes them differently to the client. + * @param data the transfer + * @param buf the raw response bytes + * @param blen the amount of bytes in `buf` + * @param is_eos TRUE iff the connection indicates this to be the last + * bytes of the response + */ +CURLcode Curl_xfer_write_resp(struct Curl_easy *data, + const char *buf, size_t blen, + bool is_eos); + +bool Curl_xfer_write_is_paused(struct Curl_easy *data); + +/** + * Write a single "header" line from a server response. + * @param hd0 the null-terminated, single header line + * @param hdlen the length of the header line + * @param is_eos TRUE iff this is the end of the response + */ +CURLcode Curl_xfer_write_resp_hd(struct Curl_easy *data, + const char *hd0, size_t hdlen, bool is_eos); + +/* The transfer is neither receiving nor sending. */ +void Curl_xfer_setup_nop(struct Curl_easy *data); + +/* The transfer sends data on the given socket index */ +void Curl_xfer_setup_send(struct Curl_easy *data, + int8_t sockindex); + +/* The transfer receives data on the given socket index, the + * amount to receive (or -1 if unknown). */ +void Curl_xfer_setup_recv(struct Curl_easy *data, + int8_t sockindex, + curl_off_t recv_size); + +/* *After* Curl_xfer_setup_xxx(), tell the transfer to shutdown the + * connection at the end. Let the transfer either fail or ignore any + * errors during shutdown. */ +void Curl_xfer_set_shutdown(struct Curl_easy *data, + bool shutdown, + bool ignore_errors); + +/** + * The transfer will use socket 1 to send/recv. `recv_size` is + * the amount to receive or -1 if unknown. + */ +void Curl_xfer_setup_sendrecv(struct Curl_easy *data, + int8_t sockindex, + curl_off_t recv_size); + +/** + * Multi has set transfer to DONE. Last chance to trigger + * missing response things like writing an EOS to the client. + */ +CURLcode Curl_xfer_write_done(struct Curl_easy *data, bool premature); + +/** + * Return TRUE iff transfer has pending data to send. Checks involved + * connection filters. + */ +bool Curl_xfer_needs_flush(struct Curl_easy *data); + +/** + * Flush any pending send data on the transfer connection. + */ +CURLcode Curl_xfer_flush(struct Curl_easy *data); + +/** + * Send data on the socket/connection filter designated + * for transfer's outgoing data. + * Return CURLE_OK on blocking with (*pnwritten == 0). + */ +CURLcode Curl_xfer_send(struct Curl_easy *data, + const void *buf, size_t blen, bool eos, + size_t *pnwritten); + +/** + * Receive data on the socket/connection filter designated + * for transfer's incoming data. + * Return CURLE_AGAIN on blocking with (*pnrcvd == 0). + */ +CURLcode Curl_xfer_recv(struct Curl_easy *data, + char *buf, size_t blen, + size_t *pnrcvd); + +CURLcode Curl_xfer_send_close(struct Curl_easy *data); +CURLcode Curl_xfer_send_shutdown(struct Curl_easy *data, bool *done); + +/* Return TRUE if the transfer is not done, but further progress + * is blocked. For example when it is only receiving and its writer + * is PAUSED. */ +bool Curl_xfer_is_blocked(struct Curl_easy *data); + +/* Query if send/recv for transfer is paused. */ +bool Curl_xfer_send_is_paused(struct Curl_easy *data); +bool Curl_xfer_recv_is_paused(struct Curl_easy *data); + +/* Enable/Disable pausing of send/recv for the transfer. */ +CURLcode Curl_xfer_pause_send(struct Curl_easy *data, bool enable); +CURLcode Curl_xfer_pause_recv(struct Curl_easy *data, bool enable); + +/* TRUE if the transfer is secure, e.g. uses TLS and does not + * use a forward proxy. */ +bool Curl_xfer_is_secure(struct Curl_easy *data); + +/* Internal variant of the API function */ +CURLcode Curl_easy_recv(struct Curl_easy *data, + void *buffer, size_t buflen, size_t *n); + +#endif /* HEADER_CURL_TRANSFER_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-bset.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-bset.c new file mode 100644 index 0000000000..55aedb234b --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-bset.c @@ -0,0 +1,233 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "uint-bset.h" + +#ifdef DEBUGBUILD +#define CURL_UINT32_BSET_MAGIC 0x62757473 +#endif + +void Curl_uint32_bset_init(struct uint32_bset *bset) +{ + memset(bset, 0, sizeof(*bset)); +#ifdef DEBUGBUILD + bset->init = CURL_UINT32_BSET_MAGIC; +#endif +} + +CURLcode Curl_uint32_bset_resize(struct uint32_bset *bset, uint32_t nmax) +{ + uint32_t nslots = (nmax < (UINT32_MAX - 63)) ? + ((nmax + 63) / 64) : (UINT32_MAX / 64); + + DEBUGASSERT(bset->init == CURL_UINT32_BSET_MAGIC); + if(nslots != bset->nslots) { + uint64_t *slots = curlx_calloc(nslots, sizeof(uint64_t)); + if(!slots) + return CURLE_OUT_OF_MEMORY; + + if(bset->slots) { + memcpy(slots, bset->slots, + (CURLMIN(nslots, bset->nslots) * sizeof(uint64_t))); + curlx_free(bset->slots); + } + bset->slots = slots; + bset->nslots = nslots; + bset->first_slot_used = 0; + } + return CURLE_OK; +} + +void Curl_uint32_bset_destroy(struct uint32_bset *bset) +{ + DEBUGASSERT(bset->init == CURL_UINT32_BSET_MAGIC); + curlx_free(bset->slots); + memset(bset, 0, sizeof(*bset)); +} + +#ifdef UNITTESTS +/* @unittest 3211 */ +UNITTEST uint32_t uint32_bset_capacity(struct uint32_bset *bset); +UNITTEST uint32_t uint32_bset_capacity(struct uint32_bset *bset) +{ + return bset->nslots * 64; +} +#endif + +uint32_t Curl_uint32_bset_count(struct uint32_bset *bset) +{ + uint32_t i; + uint32_t n = 0; + for(i = 0; i < bset->nslots; ++i) { + if(bset->slots[i]) + n += CURL_POPCOUNT64(bset->slots[i]); + } + return n; +} + +bool Curl_uint32_bset_empty(struct uint32_bset *bset) +{ + uint32_t i; + for(i = bset->first_slot_used; i < bset->nslots; ++i) { + if(bset->slots[i]) + return FALSE; + } + return TRUE; +} + +void Curl_uint32_bset_clear(struct uint32_bset *bset) +{ + if(bset->nslots) { + memset(bset->slots, 0, bset->nslots * sizeof(uint64_t)); + bset->first_slot_used = UINT32_MAX; + } +} + +bool Curl_uint32_bset_add(struct uint32_bset *bset, uint32_t i) +{ + uint32_t islot = i / 64; + if(islot >= bset->nslots) + return FALSE; + bset->slots[islot] |= ((uint64_t)1 << (i % 64)); + if(islot < bset->first_slot_used) + bset->first_slot_used = islot; + return TRUE; +} + +void Curl_uint32_bset_remove(struct uint32_bset *bset, uint32_t i) +{ + size_t islot = i / 64; + if(islot < bset->nslots) + bset->slots[islot] &= ~((uint64_t)1 << (i % 64)); +} + +bool Curl_uint32_bset_contains(struct uint32_bset *bset, uint32_t i) +{ + uint32_t islot = i / 64; + if(islot >= bset->nslots) + return FALSE; + return (bset->slots[islot] & ((uint64_t)1 << (i % 64))) != 0; +} + +bool Curl_uint32_bset_first(struct uint32_bset *bset, uint32_t *pfirst) +{ + uint32_t i; + for(i = bset->first_slot_used; i < bset->nslots; ++i) { + if(bset->slots[i]) { + *pfirst = (i * 64) + CURL_CTZ64(bset->slots[i]); + bset->first_slot_used = i; + return TRUE; + } + } + bset->first_slot_used = *pfirst = UINT32_MAX; + return FALSE; +} + +bool Curl_uint32_bset_next(struct uint32_bset *bset, uint32_t last, + uint32_t *pnext) +{ + uint32_t islot; + uint64_t x; + + ++last; /* look for number one higher than last */ + islot = last / 64; /* the slot this would be in */ + if(islot < bset->nslots) { + /* shift away the bits we already iterated in this slot */ + x = (bset->slots[islot] >> (last % 64)); + if(x) { + /* more bits set, next is `last` + trailing 0s of the shifted slot */ + *pnext = last + CURL_CTZ64(x); + return TRUE; + } + /* no more bits set in the last slot, scan forward */ + for(islot = islot + 1; islot < bset->nslots; ++islot) { + if(bset->slots[islot]) { + *pnext = (islot * 64) + CURL_CTZ64(bset->slots[islot]); + return TRUE; + } + } + } + *pnext = UINT32_MAX; /* a value we cannot store */ + return FALSE; +} + +#ifdef CURL_POPCOUNT64_IMPLEMENT +uint32_t Curl_popcount64(uint64_t x) +{ + /* Compute the "Hamming Distance" between 'x' and 0, + * which is the number of set bits in 'x'. + * See: https://en.wikipedia.org/wiki/Hamming_weight */ + const uint64_t m1 = 0x5555555555555555LL; /* 0101+ */ + const uint64_t m2 = 0x3333333333333333LL; /* 00110011+ */ + const uint64_t m4 = 0x0f0f0f0f0f0f0f0fLL; /* 00001111+ */ + /* 1 + 256^1 + 256^2 + 256^3 + ... + 256^7 */ + const uint64_t h01 = 0x0101010101010101LL; + x -= (x >> 1) & m1; /* replace every 2 bits with bits present */ + x = (x & m2) + ((x >> 2) & m2); /* replace every nibble with bits present */ + x = (x + (x >> 4)) & m4; /* replace every byte with bits present */ + /* top 8 bits of x + (x << 8) + (x << 16) + (x << 24) + ... which makes the + * top byte the sum of all individual 8 bytes, throw away the rest */ + return (uint32_t)((x * h01) >> 56); +} +#endif /* CURL_POPCOUNT64_IMPLEMENT */ + +#ifdef CURL_CTZ64_IMPLEMENT +uint32_t Curl_ctz64(uint64_t x) +{ + /* count trailing zeros in a uint64_t. + * divide and conquer to find the number of lower 0 bits */ + const uint64_t ml32 = 0xFFFFFFFF; /* lower 32 bits */ + const uint64_t ml16 = 0x0000FFFF; /* lower 16 bits */ + const uint64_t ml8 = 0x000000FF; /* lower 8 bits */ + const uint64_t ml4 = 0x0000000F; /* lower 4 bits */ + const uint64_t ml2 = 0x00000003; /* lower 2 bits */ + uint32_t n; + + if(!x) + return 64; + n = 1; + if(!(x & ml32)) { + n = n + 32; + x = x >> 32; + } + if(!(x & ml16)) { + n = n + 16; + x = x >> 16; + } + if(!(x & ml8)) { + n = n + 8; + x = x >> 8; + } + if(!(x & ml4)) { + n = n + 4; + x = x >> 4; + } + if(!(x & ml2)) { + n = n + 2; + x = x >> 2; + } + return n - (uint32_t)(x & 1); +} +#endif /* CURL_CTZ64_IMPLEMENT */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-bset.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-bset.h new file mode 100644 index 0000000000..ce0450c53c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-bset.h @@ -0,0 +1,109 @@ +#ifndef HEADER_CURL_UINT_BSET_H +#define HEADER_CURL_UINT_BSET_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* A bitset for unsigned int values. + * It can hold the numbers from 0 - (nmax - 1), + * rounded to the next 64 multiple. + * + * Optimized for high efficiency in adding/removing numbers. + * Efficient storage when the set is (often) relatively full. + * + * If the set's cardinality is only expected to be a fraction of nmax, + * uint_spbset offers a "sparse" variant with more memory efficiency at + * the price of slightly slower operations. + */ + +struct uint32_bset { + uint64_t *slots; + uint32_t nslots; + uint32_t first_slot_used; +#ifdef DEBUGBUILD + int init; +#endif +}; + +/* Initialize the bitset with capacity 0. */ +void Curl_uint32_bset_init(struct uint32_bset *bset); + +/* Resize the bitset capacity to hold numbers from 0 to `nmax`, + * which rounds up `nmax` to the next multiple of 64. */ +CURLcode Curl_uint32_bset_resize(struct uint32_bset *bset, uint32_t nmax); + +/* Destroy the bitset, freeing all resources. */ +void Curl_uint32_bset_destroy(struct uint32_bset *bset); + +/* Get the cardinality of the bitset, e.g. numbers present in the set. */ +uint32_t Curl_uint32_bset_count(struct uint32_bset *bset); + +/* TRUE of bitset is empty */ +bool Curl_uint32_bset_empty(struct uint32_bset *bset); + +/* Clear the bitset, making it empty. */ +void Curl_uint32_bset_clear(struct uint32_bset *bset); + +/* Add the number `i` to the bitset. Return FALSE if the number is + * outside the set's capacity. + * Numbers can be added more than once, without making a difference. */ +bool Curl_uint32_bset_add(struct uint32_bset *bset, uint32_t i); + +/* Remove the number `i` from the bitset. */ +void Curl_uint32_bset_remove(struct uint32_bset *bset, uint32_t i); + +/* Return TRUE if the bitset contains number `i`. */ +bool Curl_uint32_bset_contains(struct uint32_bset *bset, uint32_t i); + +/* Get the first number in the bitset, e.g. the smallest. + * Returns FALSE when the bitset is empty. */ +bool Curl_uint32_bset_first(struct uint32_bset *bset, uint32_t *pfirst); + +/* Get the next number in the bitset, following `last` in natural order. + * Put another way, this is the smallest number greater than `last` in + * the bitset. `last` does not have to be present in the set. + * + * Returns FALSE when no such number is in the set. + * + * This allows to iterate the set while being modified: + * - added numbers higher than 'last' will be picked up by the iteration. + * - added numbers lower than 'last' will not show up. + * - removed numbers lower or equal to 'last' will not show up. + * - removed numbers higher than 'last' will not be visited. */ +bool Curl_uint32_bset_next(struct uint32_bset *bset, uint32_t last, + uint32_t *pnext); + +#ifndef CURL_POPCOUNT64 +#define CURL_POPCOUNT64(x) Curl_popcount64(x) +#define CURL_POPCOUNT64_IMPLEMENT +uint32_t Curl_popcount64(uint64_t x); +#endif /* !CURL_POPCOUNT64 */ + +#ifndef CURL_CTZ64 +#define CURL_CTZ64(x) Curl_ctz64(x) +#define CURL_CTZ64_IMPLEMENT +uint32_t Curl_ctz64(uint64_t x); +#endif /* !CURL_CTZ64 */ + +#endif /* HEADER_CURL_UINT_BSET_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-hash.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-hash.c new file mode 100644 index 0000000000..c37448fd11 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-hash.c @@ -0,0 +1,235 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "uint-hash.h" + +/* random patterns for API verification */ +#ifdef DEBUGBUILD +#define CURL_UINT32_HASHINIT 0x7117e779 +#endif + +static uint32_t uint32_hash_hash(uint32_t id, uint32_t slots) +{ + return (id % slots); +} + +struct uint_hash_entry { + struct uint_hash_entry *next; + void *value; + uint32_t id; +}; + +void Curl_uint32_hash_init(struct uint_hash *h, + uint32_t slots, + Curl_uint32_hash_dtor *dtor) +{ + DEBUGASSERT(h); + DEBUGASSERT(slots); + + h->table = NULL; + h->dtor = dtor; + h->size = 0; + h->slots = slots; +#ifdef DEBUGBUILD + h->init = CURL_UINT32_HASHINIT; +#endif +} + +static struct uint_hash_entry *uint32_hash_mk_entry(uint32_t id, void *value) +{ + struct uint_hash_entry *e; + + /* allocate the struct for the hash entry */ + e = curlx_malloc(sizeof(*e)); + if(e) { + e->id = id; + e->next = NULL; + e->value = value; + } + return e; +} + +static void uint32_hash_entry_clear(struct uint_hash *h, + struct uint_hash_entry *e) +{ + DEBUGASSERT(h); + DEBUGASSERT(e); + if(e->value) { + if(h->dtor) + h->dtor(e->id, e->value); + e->value = NULL; + } +} + +static void uint32_hash_entry_destroy(struct uint_hash *h, + struct uint_hash_entry *e) +{ + uint32_hash_entry_clear(h, e); + curlx_free(e); +} + +static void uint32_hash_entry_unlink(struct uint_hash *h, + struct uint_hash_entry **he_anchor, + struct uint_hash_entry *he) +{ + *he_anchor = he->next; + --h->size; +} + +static void uint32_hash_elem_link(struct uint_hash *h, + struct uint_hash_entry **he_anchor, + struct uint_hash_entry *he) +{ + he->next = *he_anchor; + *he_anchor = he; + ++h->size; +} + +#define CURL_UINT32_HASH_SLOT(h, id) h->table[uint32_hash_hash(id, (h)->slots)] +#define CURL_UINT32_HASH_SLOT_ADDR(h, id) &CURL_UINT32_HASH_SLOT(h, id) + +bool Curl_uint32_hash_set(struct uint_hash *h, uint32_t id, void *value) +{ + struct uint_hash_entry *he, **slot; + + DEBUGASSERT(h); + DEBUGASSERT(h->slots); + DEBUGASSERT(h->init == CURL_UINT32_HASHINIT); + if(!h->table) { + h->table = curlx_calloc(h->slots, sizeof(*he)); + if(!h->table) + return FALSE; /* OOM */ + } + + slot = CURL_UINT32_HASH_SLOT_ADDR(h, id); + for(he = *slot; he; he = he->next) { + if(he->id == id) { + /* existing key entry, overwrite by clearing old pointer */ + uint32_hash_entry_clear(h, he); + he->value = value; + return TRUE; + } + } + + he = uint32_hash_mk_entry(id, value); + if(!he) + return FALSE; /* OOM */ + + uint32_hash_elem_link(h, slot, he); + return TRUE; +} + +bool Curl_uint32_hash_remove(struct uint_hash *h, uint32_t id) +{ + DEBUGASSERT(h); + DEBUGASSERT(h->slots); + DEBUGASSERT(h->init == CURL_UINT32_HASHINIT); + if(h->table) { + struct uint_hash_entry *he, **he_anchor; + + he_anchor = CURL_UINT32_HASH_SLOT_ADDR(h, id); + while(*he_anchor) { + he = *he_anchor; + if(id == he->id) { + uint32_hash_entry_unlink(h, he_anchor, he); + uint32_hash_entry_destroy(h, he); + return TRUE; + } + he_anchor = &he->next; + } + } + return FALSE; +} + +void *Curl_uint32_hash_get(struct uint_hash *h, uint32_t id) +{ + DEBUGASSERT(h); + DEBUGASSERT(h->init == CURL_UINT32_HASHINIT); + if(h->table) { + struct uint_hash_entry *he; + DEBUGASSERT(h->slots); + he = CURL_UINT32_HASH_SLOT(h, id); + while(he) { + if(id == he->id) { + return he->value; + } + he = he->next; + } + } + return NULL; +} + +/* @unittest 1616 */ +UNITTEST void uint_hash_clear(struct uint_hash *h); +UNITTEST void uint_hash_clear(struct uint_hash *h) +{ + if(h && h->table) { + struct uint_hash_entry *he, **he_anchor; + size_t i; + DEBUGASSERT(h->init == CURL_UINT32_HASHINIT); + for(i = 0; i < h->slots; ++i) { + he_anchor = &h->table[i]; + while(*he_anchor) { + he = *he_anchor; + uint32_hash_entry_unlink(h, he_anchor, he); + uint32_hash_entry_destroy(h, he); + } + } + } +} + +void Curl_uint32_hash_destroy(struct uint_hash *h) +{ + DEBUGASSERT(h->init == CURL_UINT32_HASHINIT); + if(h->table) { + uint_hash_clear(h); + curlx_safefree(h->table); + } + DEBUGASSERT(h->size == 0); + h->slots = 0; +} + +uint32_t Curl_uint32_hash_count(struct uint_hash *h) +{ + DEBUGASSERT(h->init == CURL_UINT32_HASHINIT); + return h->size; +} + +void Curl_uint32_hash_visit(struct uint_hash *h, + Curl_uint32_hash_visit_cb *cb, + void *user_data) +{ + if(h && h->table && cb) { + struct uint_hash_entry *he; + size_t i; + DEBUGASSERT(h->init == CURL_UINT32_HASHINIT); + for(i = 0; i < h->slots; ++i) { + for(he = h->table[i]; he; he = he->next) { + if(!cb(he->id, he->value, user_data)) + return; + } + } + } +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-hash.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-hash.h new file mode 100644 index 0000000000..3cbcf8f8f1 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-hash.h @@ -0,0 +1,59 @@ +#ifndef HEADER_CURL_UINT_HASH_H +#define HEADER_CURL_UINT_HASH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* A version with uint32_t as key */ +typedef void Curl_uint32_hash_dtor(uint32_t id, void *value); +struct uint_hash_entry; + +/* Hash for `uint32_t` as key */ +struct uint_hash { + struct uint_hash_entry **table; + Curl_uint32_hash_dtor *dtor; + uint32_t slots; + uint32_t size; +#ifdef DEBUGBUILD + int init; +#endif +}; + +void Curl_uint32_hash_init(struct uint_hash *h, + uint32_t slots, + Curl_uint32_hash_dtor *dtor); +void Curl_uint32_hash_destroy(struct uint_hash *h); +bool Curl_uint32_hash_set(struct uint_hash *h, uint32_t id, void *value); +bool Curl_uint32_hash_remove(struct uint_hash *h, uint32_t id); +void *Curl_uint32_hash_get(struct uint_hash *h, uint32_t id); +uint32_t Curl_uint32_hash_count(struct uint_hash *h); + +typedef bool Curl_uint32_hash_visit_cb(uint32_t id, void *value, + void *user_data); + +void Curl_uint32_hash_visit(struct uint_hash *h, + Curl_uint32_hash_visit_cb *cb, + void *user_data); + +#endif /* HEADER_CURL_UINT_HASH_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-hashset.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-hashset.c new file mode 100644 index 0000000000..84e9e5ec7b --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-hashset.c @@ -0,0 +1,311 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "uint-hashset.h" +#include "curlx/strdup.h" + +/* random patterns for API verification */ +#ifdef DEBUGBUILD +#define CURL_U8_STRSET_MAGIC 0x7117e783 +#endif + +#define CURL_U8_STRSET_DEBUG 0 + +#define CURL_SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) + +static const uint8_t u8_smask[] = { + 0x00U, + 0x01U, + 0x03U, + 0x07U, + 0x0FU, + 0x1FU, + 0x3FU, + 0x7FU, + 0xFFU, +}; + +#define CURL_U8_SET_SLOT_IDX(s, i) (uint8_t)((i) & u8_smask[(s)->slotbits]) +#define CURL_U8_SLOT_CNT(i) ((uint16_t)u8_smask[(i)] + 1) +#define CURL_U8_SET_SLOT_CNT(s) CURL_U8_SLOT_CNT((s)->slotbits) + +/* A hashset for tuples (id, string) using Robin Hood Hashing. + * <https://www.cs.cornell.edu/courses/JavaAndDS/files/hashing_RobinHood.pdf> + * The basic idea here to handle collisions by robbing "rich" entries and + * giving to the "poor": + * - We have an array: (id, string) are ideally placed at index "id % size". + * - If slot at index is already occupied, we have a collision. + * - A simple collision strategy would look at the next index, and the + * next until finding an empty slot. + * - The drawback is that this may lead to many checks on lookups, as it + * will need to also look at subsequent slots until it finds the match. + * The amount of lookups is the "probe sequence length" (psl) and this + * may vary greatly between entries. + * - Robin Hood Hashing balances the 'psl's of all entries more evenly: + * - psl == 0 means an entry is in exactly the right slot + * - psl == 1 means it is in the slot right after. psl == 2 is the slot + * after that, etc. + * - when inserting a new entry, track its psl. Finding a slot where + * the existing entry has a lower psl makes a swap. Put the new entry + * and its psl there, take the previous entry and its psl and find + * the next best slot for the previous entry. */ +void Curl_u8_strset_init(struct u8_strset *set) +{ +#if defined(__GNUC__) && __GNUC__ >= 13 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Warray-bounds" +#endif + memset(set, 0, sizeof(*set)); +#if defined(__GNUC__) && __GNUC__ >= 13 +#pragma GCC diagnostic pop +#endif + set->data = set->sdata; + set->ids = set->sids; + set->psl = set->spsl; + set->slotbits = CURL_U8_STRSET_START_BITS; + set->count = 0; +#ifdef DEBUGBUILD + set->init = CURL_U8_STRSET_MAGIC; +#endif +} + +void Curl_u8_strset_clear(struct u8_strset *set) +{ + uint16_t i; + DEBUGASSERT(set->init == CURL_U8_STRSET_MAGIC); + for(i = 0; i < CURL_U8_SET_SLOT_CNT(set); ++i) + curlx_safefree(set->data[i]); + + if(set->data != set->sdata) + curlx_safefree(set->data); + Curl_u8_strset_init(set); +} + +static void u8_strset_addn(struct u8_strset *set, uint8_t id, char *val) +{ + uint8_t i = CURL_U8_SET_SLOT_IDX(set, id); + uint8_t psl = 0; + while(set->data[i]) { + if(psl > set->psl[i]) { /* SWAP */ + char *tmpdata; + tmpdata = set->data[i]; + set->data[i] = val; + val = tmpdata; + CURL_SWAP(set->psl[i], psl); + CURL_SWAP(set->ids[i], id); + } + i = CURL_U8_SET_SLOT_IDX(set, i + 1); + ++psl; + } + set->ids[i] = id; + set->data[i] = val; + set->psl[i] = psl; + ++set->count; +} + +static bool u8_strset_grow(struct u8_strset *set) +{ + uint8_t i, *prev_ids, nslotbits; + uint16_t prev_slots; + char **prev_data; + size_t nslots; + void *d; + + if(set->slotbits >= 8) + return FALSE; + nslotbits = (uint8_t)(set->slotbits + 1); +#if CURL_U8_STRSET_DEBUG + curl_mfprintf(stderr, "u8_strset_grow from %d to %d\n", + set->slotbits, nslotbits); +#endif + nslots = CURL_U8_SLOT_CNT(nslotbits); + d = curlx_calloc(1, (nslots * sizeof(char *)) + (2 * nslots)); + if(!d) + return FALSE; + + prev_data = set->data; + prev_ids = set->ids; + prev_slots = set->slotbits; +#if defined(__GNUC__) && __GNUC__ >= 13 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wanalyzer-allocation-size" +#endif + set->data = (char **)d; +#if defined(__GNUC__) && __GNUC__ >= 13 +#pragma GCC diagnostic pop +#endif + set->ids = (uint8_t *)d + (nslots * sizeof(char *)); + set->psl = set->ids + nslots; + set->slotbits = nslotbits; + set->count = 0; + /* re-add previous entries */ + for(i = 0; i < CURL_U8_SLOT_CNT(prev_slots); ++i) { + if(prev_data[i]) + u8_strset_addn(set, prev_ids[i], prev_data[i]); + } + if(prev_data != set->sdata) + curlx_free(prev_data); + return TRUE; +} + +static bool u8_strset_get_index(struct u8_strset *set, + uint8_t id, uint8_t *pindex) +{ + uint8_t i = CURL_U8_SET_SLOT_IDX(set, id); + uint8_t psl = 0; + while(set->data[i] && (psl <= set->psl[i])) { + if(set->ids[i] == id) { + *pindex = i; +#if CURL_U8_STRSET_DEBUG + curl_mfprintf(stderr, "u8_strset_index %d=%s\n", id, set->data[i]); +#endif + return TRUE; + } + i = CURL_U8_SET_SLOT_IDX(set, i + 1); + ++psl; + } +#if CURL_U8_STRSET_DEBUG + curl_mfprintf(stderr, "u8_strset_index %d not found\n", id); +#endif + *pindex = 0; + return FALSE; +} + +uint16_t Curl_u8_strset_count(struct u8_strset *set) +{ + return set->count; +} + +const char *Curl_u8_strset_get(struct u8_strset *set, uint8_t id) +{ + uint8_t i; + DEBUGASSERT(set->init == CURL_U8_STRSET_MAGIC); + if(u8_strset_get_index(set, id, &i)) + return set->data[i]; + return NULL; +} + +CURLcode Curl_u8_strset_setn(struct u8_strset *set, + uint8_t id, char *str) +{ + uint8_t i; + + DEBUGASSERT(set->init == CURL_U8_STRSET_MAGIC); +#if CURL_U8_STRSET_DEBUG + curl_mfprintf(stderr, "u8_strset_setn %d=%s\n", id, str); +#endif + if(!str) { + Curl_u8_strset_unset(set, id); + return CURLE_OK; + } + + if(u8_strset_get_index(set, id, &i)) { + /* `id` is in set, replace value */ + curlx_free(set->data[i]); + set->data[i] = str; + return CURLE_OK; + } + /* `id` not in set yet, grow if full */ + if((set->count >= CURL_U8_SET_SLOT_CNT(set)) && !u8_strset_grow(set)) { + curlx_free(str); + return CURLE_OUT_OF_MEMORY; + } + + u8_strset_addn(set, id, str); + return CURLE_OK; +} + +CURLcode Curl_u8_strset_setx(struct u8_strset *set, + uint8_t id, const char *str, size_t slen) +{ + char *val; + + DEBUGASSERT(set->init == CURL_U8_STRSET_MAGIC); + if(!str) { + Curl_u8_strset_unset(set, id); + return CURLE_OK; + } + + val = curlx_memdup0(str, slen); + if(!val) + return CURLE_OUT_OF_MEMORY; + return Curl_u8_strset_setn(set, id, val); +} + +CURLcode Curl_u8_strset_set(struct u8_strset *set, + uint8_t id, const char *str) +{ + return Curl_u8_strset_setx(set, id, str, str ? strlen(str) : 0); +} + +static void u8_strset_unset(struct u8_strset *set, uint8_t id, bool zero) +{ + uint8_t i, j; + + DEBUGASSERT(set->init == CURL_U8_STRSET_MAGIC); + if(u8_strset_get_index(set, id, &i)) { + /* `id` is in set */ + if(zero) + curlx_strzero(set->data[i]); + curlx_safefree(set->data[i]); + set->ids[i] = set->psl[i] = 0; + --set->count; + j = CURL_U8_SET_SLOT_IDX(set, i + 1); + /* shift all entries with positive psl "down" */ + while(set->data[j] && set->psl[j]) { + set->data[i] = set->data[j]; + set->ids[i] = set->ids[j]; + set->psl[i] = (uint8_t)(set->psl[j] - 1); + set->data[j] = NULL; + set->ids[j] = set->psl[j] = 0; + i = j; + j = CURL_U8_SET_SLOT_IDX(set, i + 1); + } + } +} + +void Curl_u8_strset_unset(struct u8_strset *set, uint8_t id) +{ + u8_strset_unset(set, id, FALSE); +} + +void Curl_u8_strset_unset0(struct u8_strset *set, uint8_t id) +{ + u8_strset_unset(set, id, TRUE); +} + +CURLcode Curl_u8_strset_copy(struct u8_strset *dest, struct u8_strset *src) +{ + CURLcode result = CURLE_OK; + uint16_t i; + + DEBUGASSERT(src->init == CURL_U8_STRSET_MAGIC); + Curl_u8_strset_clear(dest); + for(i = 0; !result && (i < CURL_U8_SET_SLOT_CNT(src)); ++i) { + if(src->data[i]) + result = Curl_u8_strset_set(dest, src->ids[i], src->data[i]); + } + return result; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-hashset.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-hashset.h new file mode 100644 index 0000000000..e5a1e02f00 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-hashset.h @@ -0,0 +1,82 @@ +#ifndef HEADER_CURL_UINT_HASHSET_H +#define HEADER_CURL_UINT_HASHSET_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* How large should the initial set be? + * Measuring our test suite with set growth force fail, gives + * BITS RESULT + * 1 1261 tests out of 1951 reported OK: 64% + * 2 1792 tests out of 1951 reported OK: 91% + * 3 1944 tests out of 1951 reported OK: 99% + * 4 1949 tests out of 1951 reported OK: 99% + * 5 single fail of 3211, unit test for u8_strset + * meaning 91% of our tests to not set more than 4 strings and + * 99% do not set more than 8. + */ +#define CURL_U8_STRSET_START_BITS 3 +#define CURL_U8_STRSET_START_DIM (1U << CURL_U8_STRSET_START_BITS) + +/* A set that can hold up to 256 strings identified by an `id'. + * Setting a string for an existing id replaces the previous one. + * Getting the string for an id not in the set returns NULL. + * Setting an id to NULL unsets the id. + */ +struct u8_strset { + char **data; /* #slots array of null-terminated strings */ + uint8_t *ids; /* #slots array of `id` values */ + uint8_t *psl; /* #slots array of "probe sequence length" values */ + char *sdata[CURL_U8_STRSET_START_DIM]; + uint8_t sids[CURL_U8_STRSET_START_DIM]; + uint8_t spsl[CURL_U8_STRSET_START_DIM]; + uint16_t count; + uint8_t slotbits; +#ifdef DEBUGBUILD + int32_t init; +#endif +}; + +void Curl_u8_strset_init(struct u8_strset *set); +void Curl_u8_strset_clear(struct u8_strset *set); + +uint16_t Curl_u8_strset_count(struct u8_strset *set); +const char *Curl_u8_strset_get(struct u8_strset *set, uint8_t id); + +/* Set string for id, makes a copy. */ +CURLcode Curl_u8_strset_set(struct u8_strset *set, + uint8_t id, const char *str); +CURLcode Curl_u8_strset_setx(struct u8_strset *set, + uint8_t id, const char *str, size_t slen); +/* Set string for id, takes ownership of `str` even on failure. */ +CURLcode Curl_u8_strset_setn(struct u8_strset *set, + uint8_t id, char *str); +void Curl_u8_strset_unset(struct u8_strset *set, uint8_t id); + +/* Remove the string if in the set and zero its memory */ +void Curl_u8_strset_unset0(struct u8_strset *set, uint8_t id); + +CURLcode Curl_u8_strset_copy(struct u8_strset *dest, struct u8_strset *src); + +#endif /* HEADER_CURL_UINT_HASHSET_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-spbset.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-spbset.c new file mode 100644 index 0000000000..66b0fcb670 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-spbset.c @@ -0,0 +1,305 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "uint-bset.h" +#include "uint-spbset.h" + +#ifdef DEBUGBUILD +#define CURL_UINT32_SPBSET_MAGIC 0x70737362 +#endif + +void Curl_uint32_spbset_init(struct uint32_spbset *bset) +{ + memset(bset, 0, sizeof(*bset)); +#ifdef DEBUGBUILD + bset->init = CURL_UINT32_SPBSET_MAGIC; +#endif +} + +/* Clear the bitset, making it empty. + + @unittest 3213 + */ +UNITTEST void uint32_spbset_clear(struct uint32_spbset *bset); +UNITTEST void uint32_spbset_clear(struct uint32_spbset *bset) +{ + struct uint32_spbset_chunk *next, *chunk; + + for(chunk = bset->head.next; chunk; chunk = next) { + next = chunk->next; + curlx_free(chunk); + } + memset(&bset->head, 0, sizeof(bset->head)); +} + +void Curl_uint32_spbset_destroy(struct uint32_spbset *bset) +{ + DEBUGASSERT(bset->init == CURL_UINT32_SPBSET_MAGIC); + uint32_spbset_clear(bset); +} + +uint32_t Curl_uint32_spbset_count(struct uint32_spbset *bset) +{ + struct uint32_spbset_chunk *chunk; + uint32_t i, n = 0; + + for(chunk = &bset->head; chunk; chunk = chunk->next) { + for(i = 0; i < CURL_UINT32_SPBSET_CH_SLOTS; ++i) { + if(chunk->slots[i]) + n += CURL_POPCOUNT64(chunk->slots[i]); + } + } + return n; +} + +static bool uint32_spbset_empty_chunk(struct uint32_spbset_chunk *chunk) +{ + uint32_t i; + for(i = 0; i < CURL_UINT32_SPBSET_CH_SLOTS; ++i) { + if(chunk->slots[i]) + return FALSE; + } + return TRUE; +} + +static struct uint32_spbset_chunk *uint32_spbset_unlink_empty( + struct uint32_spbset *bset, uint32_t for_offset) +{ + struct uint32_spbset_chunk *chunk, **panchor = NULL; + for(chunk = &bset->head; chunk; + panchor = &chunk->next, chunk = chunk->next) { + if(uint32_spbset_empty_chunk(chunk)) + break; + } + if(chunk) { + if(chunk == &bset->head) { /* head chunk is empty */ + if(!bset->head.next || (for_offset < bset->head.next->offset)) { + return &bset->head; + } + /* swap head and next, unlink */ + chunk = bset->head.next; + memcpy(&bset->head, chunk, sizeof(bset->head)); + memset(chunk, 0, sizeof(*chunk)); + } + else { + *panchor = chunk->next; /* unlink */ + memset(chunk, 0, sizeof(*chunk)); + } + } + return chunk; +} + +static struct uint32_spbset_chunk *uint32_spbset_insert_chunk( + struct uint32_spbset *bset, struct uint32_spbset_chunk *nchunk) +{ + struct uint32_spbset_chunk *chunk, **panchor; + + /* insert nchunk into set's ordered chunk list */ + if(nchunk->offset < bset->head.offset) { + /* swap chunk and head */ + uint32_t offset = nchunk->offset; + memcpy(nchunk, &bset->head, sizeof(*nchunk)); + memset(&bset->head, 0, sizeof(bset->head)); + bset->head.next = nchunk; + bset->head.offset = offset; + return &bset->head; + } + DEBUGASSERT(nchunk->offset > bset->head.offset); + panchor = &bset->head.next; + for(chunk = *panchor; chunk; + panchor = &chunk->next, chunk = chunk->next) { + if(chunk->offset > nchunk->offset) { /* insert before this chunk */ + nchunk->next = chunk; + *panchor = nchunk; + return nchunk; + } + } + /* no chunk with larger offset, append */ + *panchor = nchunk; + return nchunk; +} + +static struct uint32_spbset_chunk *uint32_spbset_get_chunk( + struct uint32_spbset *bset, uint32_t i, bool grow) +{ + struct uint32_spbset_chunk *chunk; + uint32_t i_offset = (i & ~CURL_UINT32_SPBSET_CH_MASK); + + if(!bset) + return NULL; + + for(chunk = &bset->head; chunk; chunk = chunk->next) { + if(chunk->offset == i_offset) + return chunk; + else if(chunk->offset > i_offset) + break; /* need new chunk here */ + } + if(!grow) /* just a check if the chunk exists */ + return NULL; + + /* Is there an empty chunk to reuse? */ + chunk = uint32_spbset_unlink_empty(bset, i_offset); + if(chunk) { + chunk->offset = i_offset; + if(chunk == &bset->head) /* head chunk is empty, stayed linked */ + return &bset->head; + /* was really unlinked, need to insert below */ + } + else { + /* need a new one */ + chunk = curlx_calloc(1, sizeof(*chunk)); + if(!chunk) + return NULL; + chunk->offset = i_offset; + } + + return uint32_spbset_insert_chunk(bset, chunk); +} + +bool Curl_uint32_spbset_add(struct uint32_spbset *bset, uint32_t i) +{ + struct uint32_spbset_chunk *chunk = uint32_spbset_get_chunk(bset, i, TRUE); + if(!chunk) + return FALSE; + + DEBUGASSERT(i >= chunk->offset); + i -= chunk->offset; + DEBUGASSERT(i < (CURL_UINT32_SPBSET_CH_SLOTS * 64)); + chunk->slots[(i / 64)] |= ((uint64_t)1 << (i % 64)); + return TRUE; +} + +void Curl_uint32_spbset_remove(struct uint32_spbset *bset, uint32_t i) +{ + struct uint32_spbset_chunk *chunk = uint32_spbset_get_chunk(bset, i, FALSE); + if(chunk) { + DEBUGASSERT(i >= chunk->offset); + i -= chunk->offset; + DEBUGASSERT(i < (CURL_UINT32_SPBSET_CH_SLOTS * 64)); + chunk->slots[(i / 64)] &= ~((uint64_t)1 << (i % 64)); + } +} + +bool Curl_uint32_spbset_contains(struct uint32_spbset *bset, uint32_t i) +{ + struct uint32_spbset_chunk *chunk = uint32_spbset_get_chunk(bset, i, FALSE); + if(chunk) { + DEBUGASSERT(i >= chunk->offset); + i -= chunk->offset; + DEBUGASSERT(i < (CURL_UINT32_SPBSET_CH_SLOTS * 64)); + return (chunk->slots[i / 64] & ((uint64_t)1 << (i % 64))) != 0; + } + return FALSE; +} + +bool Curl_uint32_spbset_first(struct uint32_spbset *bset, uint32_t *pfirst) +{ + struct uint32_spbset_chunk *chunk; + uint32_t i; + + for(chunk = &bset->head; chunk; chunk = chunk->next) { + for(i = 0; i < CURL_UINT32_SPBSET_CH_SLOTS; ++i) { + if(chunk->slots[i]) { + *pfirst = chunk->offset + ((i * 64) + CURL_CTZ64(chunk->slots[i])); + return TRUE; + } + } + } + *pfirst = 0; /* give it a defined value even if it should not be used */ + return FALSE; +} + +static bool uint32_spbset_chunk_first(struct uint32_spbset_chunk *chunk, + uint32_t *pfirst) +{ + uint32_t i; + for(i = 0; i < CURL_UINT32_SPBSET_CH_SLOTS; ++i) { + if(chunk->slots[i]) { + *pfirst = chunk->offset + ((i * 64) + CURL_CTZ64(chunk->slots[i])); + return TRUE; + } + } + *pfirst = UINT32_MAX; /* a value we cannot store */ + return FALSE; +} + +static bool uint32_spbset_chunk_next(struct uint32_spbset_chunk *chunk, + uint32_t last, + uint32_t *pnext) +{ + if(chunk->offset <= last) { + uint64_t x; + uint32_t i = ((last - chunk->offset) / 64); + if(i < CURL_UINT32_SPBSET_CH_SLOTS) { + x = (chunk->slots[i] >> (last % 64)); + if(x) { + /* more bits set, next is `last` + trailing 0s of the shifted slot */ + *pnext = last + CURL_CTZ64(x); + return TRUE; + } + /* no more bits set in the last slot, scan forward */ + for(i = i + 1; i < CURL_UINT32_SPBSET_CH_SLOTS; ++i) { + if(chunk->slots[i]) { + *pnext = chunk->offset + ((i * 64) + CURL_CTZ64(chunk->slots[i])); + return TRUE; + } + } + } + } + *pnext = UINT32_MAX; + return FALSE; +} + +bool Curl_uint32_spbset_next(struct uint32_spbset *bset, uint32_t last, + uint32_t *pnext) +{ + struct uint32_spbset_chunk *chunk; + uint32_t last_offset; + + ++last; /* look for the next higher number */ + last_offset = (last & ~CURL_UINT32_SPBSET_CH_MASK); + + for(chunk = &bset->head; chunk; chunk = chunk->next) { + if(chunk->offset >= last_offset) { + break; + } + } + + if(chunk && (chunk->offset == last_offset)) { + /* is there a number higher than last in this chunk? */ + if(uint32_spbset_chunk_next(chunk, last, pnext)) + return TRUE; + /* not in this chunk */ + chunk = chunk->next; + } + /* look for the first in the "higher" chunks, if there are any. */ + while(chunk) { + if(uint32_spbset_chunk_first(chunk, pnext)) + return TRUE; + chunk = chunk->next; + } + *pnext = UINT32_MAX; + return FALSE; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-spbset.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-spbset.h new file mode 100644 index 0000000000..4b105c02ed --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-spbset.h @@ -0,0 +1,91 @@ +#ifndef HEADER_CURL_UINT_SPBSET_H +#define HEADER_CURL_UINT_SPBSET_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* A "sparse" bitset for uint32_t values. + * It can hold any uint32_t value. + * + * Optimized for the case where only a small set of numbers need + * to be kept, especially when "close" together. Then storage space + * is most efficient, deteriorating when many number are far apart. + */ + +/* 4 slots = 256 bits, keep this a 2^n value. */ +#define CURL_UINT32_SPBSET_CH_SLOTS 4 +#define CURL_UINT32_SPBSET_CH_MASK ((CURL_UINT32_SPBSET_CH_SLOTS * 64) - 1) + +/* store the uint value from offset to + * (offset + (CURL_UINT32_SPBSET_CHUNK_SLOTS * 64) - 1 */ +struct uint32_spbset_chunk { + struct uint32_spbset_chunk *next; + uint64_t slots[CURL_UINT32_SPBSET_CH_SLOTS]; + uint32_t offset; +}; + +struct uint32_spbset { + struct uint32_spbset_chunk head; +#ifdef DEBUGBUILD + int init; +#endif +}; + +void Curl_uint32_spbset_init(struct uint32_spbset *bset); + +void Curl_uint32_spbset_destroy(struct uint32_spbset *bset); + +/* Get the cardinality of the bitset, e.g. numbers present in the set. */ +uint32_t Curl_uint32_spbset_count(struct uint32_spbset *bset); + +/* Add the number `i` to the bitset. + * Numbers can be added more than once, without making a difference. + * Returns FALSE if allocations failed. */ +bool Curl_uint32_spbset_add(struct uint32_spbset *bset, uint32_t i); + +/* Remove the number `i` from the bitset. */ +void Curl_uint32_spbset_remove(struct uint32_spbset *bset, uint32_t i); + +/* Return TRUE if the bitset contains number `i`. */ +bool Curl_uint32_spbset_contains(struct uint32_spbset *bset, uint32_t i); + +/* Get the first number in the bitset, e.g. the smallest. + * Returns FALSE when the bitset is empty. */ +bool Curl_uint32_spbset_first(struct uint32_spbset *bset, uint32_t *pfirst); + +/* Get the next number in the bitset, following `last` in natural order. + * Put another way, this is the smallest number greater than `last` in + * the bitset. `last` does not have to be present in the set. + * + * Returns FALSE when no such number is in the set. + * + * This allows to iterate the set while being modified: + * - added numbers higher than 'last' will be picked up by the iteration. + * - added numbers lower than 'last' will not show up. + * - removed numbers lower or equal to 'last' will not show up. + * - removed numbers higher than 'last' will not be visited. */ +bool Curl_uint32_spbset_next(struct uint32_spbset *bset, uint32_t last, + uint32_t *pnext); + +#endif /* HEADER_CURL_UINT_SPBSET_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-table.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-table.c new file mode 100644 index 0000000000..addd2c9cb2 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-table.c @@ -0,0 +1,202 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "uint-table.h" + +#ifdef DEBUGBUILD +#define CURL_UINT32_TBL_MAGIC 0x62757473 +#endif + +void Curl_uint32_tbl_init(struct uint32_tbl *tbl, + Curl_uint32_tbl_entry_dtor *entry_dtor) +{ + memset(tbl, 0, sizeof(*tbl)); + tbl->entry_dtor = entry_dtor; + tbl->last_key_added = UINT32_MAX; +#ifdef DEBUGBUILD + tbl->init = CURL_UINT32_TBL_MAGIC; +#endif +} + +static void uint32_tbl_clear_rows(struct uint32_tbl *tbl, + uint32_t from, + uint32_t upto_excluding) +{ + uint32_t i, end; + + end = CURLMIN(upto_excluding, tbl->nrows); + for(i = from; i < end; ++i) { + if(tbl->rows[i]) { + if(tbl->entry_dtor) + tbl->entry_dtor(i, tbl->rows[i]); + tbl->rows[i] = NULL; + tbl->nentries--; + } + } +} + +CURLcode Curl_uint32_tbl_resize(struct uint32_tbl *tbl, uint32_t nrows) +{ + /* we use `tbl->nrows + 1` during iteration, want that to work */ + DEBUGASSERT(tbl->init == CURL_UINT32_TBL_MAGIC); + if(!nrows) + return CURLE_BAD_FUNCTION_ARGUMENT; + if(nrows != tbl->nrows) { + void **rows = curlx_calloc(nrows, sizeof(void *)); + if(!rows) + return CURLE_OUT_OF_MEMORY; + if(tbl->rows) { + memcpy(rows, tbl->rows, (CURLMIN(nrows, tbl->nrows) * sizeof(void *))); + if(nrows < tbl->nrows) + uint32_tbl_clear_rows(tbl, nrows, tbl->nrows); + curlx_free(tbl->rows); + } + tbl->rows = rows; + tbl->nrows = nrows; + } + return CURLE_OK; +} + +/* Clear the table, making it empty. + + @unittest 3212 + */ +UNITTEST void uint32_tbl_clear(struct uint32_tbl *tbl); +UNITTEST void uint32_tbl_clear(struct uint32_tbl *tbl) +{ + DEBUGASSERT(tbl->init == CURL_UINT32_TBL_MAGIC); + uint32_tbl_clear_rows(tbl, 0, tbl->nrows); + DEBUGASSERT(!tbl->nentries); + tbl->last_key_added = UINT32_MAX; +} + +void Curl_uint32_tbl_destroy(struct uint32_tbl *tbl) +{ + DEBUGASSERT(tbl->init == CURL_UINT32_TBL_MAGIC); + uint32_tbl_clear(tbl); + curlx_free(tbl->rows); + memset(tbl, 0, sizeof(*tbl)); +} + +uint32_t Curl_uint32_tbl_capacity(struct uint32_tbl *tbl) +{ + return tbl->nrows; +} + +uint32_t Curl_uint32_tbl_count(struct uint32_tbl *tbl) +{ + return tbl->nentries; +} + +void *Curl_uint32_tbl_get(struct uint32_tbl *tbl, uint32_t key) +{ + return (key < tbl->nrows) ? tbl->rows[key] : NULL; +} + +bool Curl_uint32_tbl_add(struct uint32_tbl *tbl, void *entry, uint32_t *pkey) +{ + uint32_t key, start_pos; + + DEBUGASSERT(tbl->init == CURL_UINT32_TBL_MAGIC); + if(!entry || !pkey) + return FALSE; + *pkey = UINT32_MAX; + if(tbl->nentries == tbl->nrows) /* full */ + return FALSE; + + start_pos = CURLMIN(tbl->last_key_added, tbl->nrows) + 1; + for(key = start_pos; key < tbl->nrows; ++key) { + if(!tbl->rows[key]) { + tbl->rows[key] = entry; + tbl->nentries++; + tbl->last_key_added = key; + *pkey = key; + return TRUE; + } + } + /* no free entry at or above tbl->maybe_next_key, wrap around */ + for(key = 0; key < start_pos; ++key) { + if(!tbl->rows[key]) { + tbl->rows[key] = entry; + tbl->nentries++; + tbl->last_key_added = key; + *pkey = key; + return TRUE; + } + } + /* Did not find any free row? Should not happen */ + DEBUGASSERT(0); + return FALSE; +} + +void Curl_uint32_tbl_remove(struct uint32_tbl *tbl, uint32_t key) +{ + uint32_tbl_clear_rows(tbl, key, key + 1); +} + +bool Curl_uint32_tbl_contains(struct uint32_tbl *tbl, uint32_t key) +{ + return (key < tbl->nrows) ? !!tbl->rows[key] : FALSE; +} + +static bool uint32_tbl_next_at(struct uint32_tbl *tbl, uint32_t key, + uint32_t *pkey, void **pentry) +{ + for(; key < tbl->nrows; ++key) { + if(tbl->rows[key]) { + *pkey = key; + *pentry = tbl->rows[key]; + return TRUE; + } + } + *pkey = UINT32_MAX; /* always invalid */ + *pentry = NULL; + return FALSE; +} + +bool Curl_uint32_tbl_first(struct uint32_tbl *tbl, + uint32_t *pkey, void **pentry) +{ + if(!pkey || !pentry) + return FALSE; + if(tbl->nentries && uint32_tbl_next_at(tbl, 0, pkey, pentry)) + return TRUE; + DEBUGASSERT(!tbl->nentries); + *pkey = UINT32_MAX; /* always invalid */ + *pentry = NULL; + return FALSE; +} + +bool Curl_uint32_tbl_next(struct uint32_tbl *tbl, uint32_t last_key, + uint32_t *pkey, void **pentry) +{ + if(!pkey || !pentry) + return FALSE; + if(uint32_tbl_next_at(tbl, last_key + 1, pkey, pentry)) + return TRUE; + *pkey = UINT32_MAX; /* always invalid */ + *pentry = NULL; + return FALSE; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-table.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-table.h new file mode 100644 index 0000000000..398a26a648 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/uint-table.h @@ -0,0 +1,96 @@ +#ifndef HEADER_CURL_UINT_TABLE_H +#define HEADER_CURL_UINT_TABLE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* Destructor for a single table entry */ +typedef void Curl_uint32_tbl_entry_dtor(uint32_t key, void *entry); + +struct uint32_tbl { + void **rows; /* array of void* holding entries */ + Curl_uint32_tbl_entry_dtor *entry_dtor; + uint32_t nrows; /* length of `rows` array */ + uint32_t nentries; /* entries in table */ + uint32_t last_key_added; /* UINT_MAX or last key added */ +#ifdef DEBUGBUILD + int init; +#endif +}; + +/* Initialize the table with 0 capacity. + * The optional `entry_dtor` is called when a table entry is removed, + * Passing NULL means no action is taken on removal. */ +void Curl_uint32_tbl_init(struct uint32_tbl *tbl, + Curl_uint32_tbl_entry_dtor *entry_dtor); + +/* Resize the table to change capacity `nmax`. When `nmax` is reduced, + * all present entries with key equal or larger to `nmax` are removed. */ +CURLcode Curl_uint32_tbl_resize(struct uint32_tbl *tbl, uint32_t nrows); + +/* Destroy the table, freeing all entries. */ +void Curl_uint32_tbl_destroy(struct uint32_tbl *tbl); + +/* Get the table capacity. */ +uint32_t Curl_uint32_tbl_capacity(struct uint32_tbl *tbl); + +/* Get the number of entries in the table. */ +uint32_t Curl_uint32_tbl_count(struct uint32_tbl *tbl); + +/* Get the entry for key or NULL if not present */ +void *Curl_uint32_tbl_get(struct uint32_tbl *tbl, uint32_t key); + +/* Add a new entry to the table and assign it a free key. + * Returns FALSE if the table is full. + * + * Keys are assigned in a round-robin manner. + * No matter the capacity, UINT_MAX is never assigned. */ +bool Curl_uint32_tbl_add(struct uint32_tbl *tbl, void *entry, uint32_t *pkey); + +/* Remove the entry with `key`. */ +void Curl_uint32_tbl_remove(struct uint32_tbl *tbl, uint32_t key); + +/* Return TRUE if the table contains an tryn with that keys. */ +bool Curl_uint32_tbl_contains(struct uint32_tbl *tbl, uint32_t key); + +/* Get the first entry in the table (with the smallest `key`). + * Returns FALSE if the table is empty. */ +bool Curl_uint32_tbl_first(struct uint32_tbl *tbl, + uint32_t *pkey, void **pentry); + +/* Get the next key in the table, following `last_key` in natural order. + * Put another way, this is the smallest key greater than `last_key` in + * the table. `last_key` does not have to be present in the table. + * + * Returns FALSE when no such entry is in the table. + * + * This allows to iterate the table while being modified: + * - added keys higher than 'last_key' will be picked up by the iteration. + * - added keys lower than 'last_key' will not show up. + * - removed keys lower or equal to 'last_key' will not show up. + * - removed keys higher than 'last_key' will not be visited. */ +bool Curl_uint32_tbl_next(struct uint32_tbl *tbl, uint32_t last_key, + uint32_t *pkey, void **pentry); + +#endif /* HEADER_CURL_UINT_TABLE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/url.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/url.c new file mode 100644 index 0000000000..6eeae43d0d --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/url.c @@ -0,0 +1,2598 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NET_IF_H +#include <net/if.h> +#endif +#ifdef HAVE_IPHLPAPI_H +#include <Iphlpapi.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif + +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#ifdef HAVE_SYS_UN_H +#include <sys/un.h> +#endif + +#ifndef HAVE_SOCKET +#error "We cannot compile without socket() support" +#endif + +#if defined(HAVE_IF_NAMETOINDEX) && defined(USE_WINSOCK) +#if defined(__MINGW32__) && (__MINGW64_VERSION_MAJOR <= 5) +#include <wincrypt.h> /* workaround for old mingw-w64 missing to include it */ +#endif +#include <iphlpapi.h> +#endif + +#include "urldata.h" +#include "mime.h" +#include "bufref.h" +#include "vtls/vtls.h" +#include "vssh/vssh.h" +#include "transfer.h" +#include "curl_addrinfo.h" +#include "curl_trc.h" +#include "progress.h" +#include "cookie.h" +#include "strcase.h" +#include "escape.h" +#include "curl_share.h" +#include "http_digest.h" +#include "multiif.h" +#include "getinfo.h" +#include "pop3.h" +#include "urlapi-int.h" +#include "hsts.h" +#include "proxy.h" +#include "cfilters.h" +#include "idn.h" +#include "http_proxy.h" +#include "conncache.h" +#include "multihandle.h" +#include "curlx/strdup.h" +#include "setopt.h" +#include "altsvc.h" +#include "curlx/dynbuf.h" +#include "headers.h" +#include "curlx/strerr.h" +#include "curlx/strparse.h" +#include "peer.h" + +/* Now for the protocols */ +#include "ftp.h" +#include "dict.h" +#include "telnet.h" +#include "tftp.h" +#include "http.h" +#include "vauth/vauth.h" +#include "file.h" +#include "curl_ldap.h" +#include "vssh/ssh.h" +#include "imap.h" +#include "url.h" +#include "connect.h" +#include "gopher.h" +#include "mqtt.h" +#include "rtsp.h" +#include "smtp.h" +#include "ws.h" + +/* Some parts of the code (e.g. chunked encoding) assume this buffer has more + * than a few bytes to play with. Do not let it become too small or bad things + * will happen. + */ +#if READBUFFER_SIZE < READBUFFER_MIN +# error READBUFFER_SIZE is too small +#endif + +/* + * get_protocol_family() + * + * This is used to return the protocol family for a given protocol. + * + * Parameters: + * + * 's' [in] - struct Curl_scheme pointer. + * + * Returns the family as a single bit protocol identifier. + */ +static curl_prot_t get_protocol_family(const struct Curl_scheme *s) +{ + DEBUGASSERT(s); + DEBUGASSERT(s->family); + return s->family; +} + +void Curl_freeset(struct Curl_easy *data) +{ + /* Free all dynamic strings stored in the data->set substructure. */ + enum dupblob j; + + CURL_EASY_STR_CLEAR0(data, STRING_PASSWORD); + CURL_EASY_STR_CLEAR0(data, STRING_KEY_PASSWD); + CURL_EASY_STR_CLEAR0(data, STRING_BEARER); +#ifndef CURL_DISABLE_PROXY + CURL_EASY_STR_CLEAR0(data, STRING_PROXYPASSWORD); + CURL_EASY_STR_CLEAR0(data, STRING_KEY_PASSWD_PROXY); +#endif + Curl_u8_strset_clear(&data->set.strings); + curlx_safefree(data->set.str_copypostfields); + + for(j = (enum dupblob)0; j < BLOB_LAST; j++) { + curlx_safefree(data->set.blobs[j]); + } + + Curl_bufref_free(&data->state.referer); + Curl_bufref_free(&data->state.url); + +#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API) + Curl_mime_cleanpart(data->set.mimepostp); + curlx_safefree(data->set.mimepostp); +#endif + +#ifndef CURL_DISABLE_COOKIES + curl_slist_free_all(data->state.cookielist); + data->state.cookielist = NULL; +#endif +} + +/* free the URL pieces */ +static void up_free(struct Curl_easy *data) +{ + struct urlpieces *up = &data->state.up; + curlx_safefree(up->options); + curlx_safefree(up->path); + curlx_safefree(up->query); + curl_url_cleanup(data->state.uh); + data->state.uh = NULL; +} + +/* + * This is the internal function curl_easy_cleanup() calls. This should + * cleanup and free all resources associated with this Curl_easy. + * + * We ignore SIGPIPE when this is called from curl_easy_cleanup. + */ +CURLcode Curl_close(struct Curl_easy **datap) +{ + struct Curl_easy *data; + + if(!datap || !*datap) + return CURLE_OK; + + data = *datap; + *datap = NULL; + + if(!data->state.internal && data->multi) { + /* This handle is still part of a multi handle, take care of this first + and detach this handle from there. + This detaches the connection. */ + Curl_multi_remove_handle(data->multi, data); + } + else { + /* Detach connection if any is left. This should not be normal, but can be + the case for example with CONNECT_ONLY + recv/send (test 556) */ + Curl_detach_connection(data); + if(!data->state.internal && data->multi_easy) { + /* when curl_easy_perform() is used, it creates its own multi handle to + use and this is the one */ + curl_multi_cleanup(data->multi_easy); + data->multi_easy = NULL; + } + } + DEBUGASSERT(!data->conn || data->state.internal); + + Curl_expire_clear_all(data); /* shut off any timers left */ + + if(data->state.rangestringalloc) + curlx_free(data->state.range); + + /* release any resolve information this transfer kept */ + Curl_resolv_destroy_all(data); + + data->set.verbose = FALSE; /* no more calls to DEBUGFUNCTION */ + data->magic = 0; /* force a clear AFTER the possibly enforced removal from + * the multi handle and async dns shutdown. The multi + * handle might check the magic and so might any + * DEBUGFUNCTION invoked for tracing */ + + /* freed here in case DONE was not called */ + Curl_req_free(&data->req, data); + + /* Close down all open SSL info and sessions */ + Curl_ssl_close_all(data); + Curl_peer_unlink(&data->state.origin); + Curl_peer_unlink(&data->state.initial_origin); + Curl_ssl_free_certinfo(data); + + Curl_bufref_free(&data->state.referer); + + up_free(data); + curlx_dyn_free(&data->state.headerb); + Curl_flush_cookies(data, TRUE); +#ifndef CURL_DISABLE_ALTSVC + Curl_altsvc_save(data, data->asi, CURL_EASY_STR(data, STRING_ALTSVC)); + Curl_altsvc_cleanup(&data->asi); +#endif +#ifndef CURL_DISABLE_HSTS + Curl_hsts_save(data, data->hsts, CURL_EASY_STR(data, STRING_HSTS)); + if(!data->share || !data->share->hsts) + Curl_hsts_cleanup(&data->hsts); + curl_slist_free_all(data->state.hstslist); /* clean up list */ +#endif +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_DIGEST_AUTH) + Curl_http_auth_cleanup_digest(data); +#endif + curlx_safefree(data->state.most_recent_ftp_entrypath); + curlx_safefree(data->info.contenttype); + curlx_safefree(data->info.wouldredirect); + + /* No longer a dirty share, if it exists */ + if(Curl_share_easy_unlink(data)) + DEBUGASSERT(0); + + Curl_hash_destroy(&data->meta_hash); + Curl_creds_unlink(&data->state.creds); +#ifndef CURL_DISABLE_HTTP + curlx_safefree(data->state.rangeline); + curlx_safefree(data->state.http_host); +#endif +#ifndef CURL_DISABLE_COOKIES + curlx_safefree(data->req.cookiehost); +#endif + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_FORM_API) + Curl_mime_cleanpart(data->state.formp); + curlx_safefree(data->state.formp); +#endif + + /* destruct wildcard structures if it is needed */ + Curl_wildcard_dtor(&data->wildcard); + Curl_freeset(data); + Curl_headers_cleanup(data); + Curl_netrc_cleanup(&data->state.netrc); +#ifndef CURL_DISABLE_DIGEST_AUTH + curlx_free(data->state.envproxy); +#endif + Curl_ssl_config_cleanup(&data->set.ssl.primary); +#ifndef CURL_DISABLE_PROXY + Curl_ssl_config_cleanup(&data->set.proxy_ssl.primary); +#endif + curlx_memzero(data, sizeof(*data)); + curlx_free(data); + return CURLE_OK; +} + +/* + * Initialize the UserDefined fields within a Curl_easy. + * This may be safely called on a new or existing Curl_easy. + */ +void Curl_init_userdefined(struct Curl_easy *data) +{ + struct UserDefined *set = &data->set; + + set->out = stdout; /* default output to stdout */ + set->in_set = stdin; /* default input from stdin */ + set->err = stderr; /* default stderr to stderr */ + + Curl_u8_strset_init(&data->set.strings); + +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcast-function-type-strict" +#endif + /* use fwrite as default function to store output */ + set->fwrite_func = (curl_write_callback)fwrite; + + /* use fread as default function to read input */ + set->fread_func_set = (curl_read_callback)fread; +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic pop +#endif + set->is_fread_set = 0; + + set->seek_client = ZERO_NULL; + + set->filesize = -1; /* we do not know the size */ + set->postfieldsize = -1; /* unknown size */ + set->maxredirs = 30; /* sensible default */ + + set->method = HTTPREQ_GET; /* Default HTTP request */ +#ifndef CURL_DISABLE_RTSP + set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */ +#endif +#ifndef CURL_DISABLE_FTP + set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */ + set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */ + set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */ + set->ftp_filemethod = FTPFILE_MULTICWD; + set->ftp_skip_ip = TRUE; /* skip PASV IP by default */ +#endif + set->dns_cache_timeout_ms = 60000; /* Timeout every 60 seconds by default */ + + /* Timeout every 24 hours by default */ + set->general_ssl.ca_cache_timeout = 24 * 60 * 60; + + set->httpauth = CURLAUTH_BASIC; /* defaults to basic */ + + Curl_ssl_config_init(&data->set.ssl.primary); +#ifndef CURL_DISABLE_PROXY + Curl_ssl_config_init(&data->set.proxy_ssl.primary); + set->proxyport = 0; + set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */ + set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */ + /* SOCKS5 proxy auth defaults to username/password + GSS-API */ + set->socks5auth = CURLAUTH_BASIC | CURLAUTH_GSSAPI; +#endif + +#ifndef CURL_DISABLE_DOH + set->doh_verifyhost = TRUE; + set->doh_verifypeer = TRUE; +#endif +#ifdef USE_SSH + /* defaults to any auth type */ + set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; + set->new_directory_perms = 0755; /* Default permissions */ +#endif + + set->new_file_perms = 0644; /* Default permissions */ + set->allowed_protocols = (curl_prot_t)CURLPROTO_64ALL; + set->redir_protocols = CURLPROTO_REDIR; + +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + /* + * disallow unprotected protection negotiation NEC reference implementation + * seem not to follow rfc1961 section 4.3/4.4 + */ + set->socks5_gssapi_nec = FALSE; +#endif + + /* set default minimum TLS version */ +#ifdef USE_SSL + Curl_setopt_SSLVERSION(data, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT); +#ifndef CURL_DISABLE_PROXY + Curl_setopt_SSLVERSION(data, CURLOPT_PROXY_SSLVERSION, + CURL_SSLVERSION_DEFAULT); +#endif +#endif +#ifndef CURL_DISABLE_FTP + set->wildcard_enabled = FALSE; + set->chunk_bgn = ZERO_NULL; + set->chunk_end = ZERO_NULL; + set->fnmatch = ZERO_NULL; +#endif + set->tcp_keepalive = FALSE; + set->tcp_keepintvl = 60; + set->tcp_keepidle = 60; + set->tcp_keepcnt = 9; + set->tcp_fastopen = FALSE; + set->tcp_nodelay = TRUE; + set->ssl_enable_alpn = TRUE; + set->expect_100_timeout = 1000L; /* Wait for a second by default. */ + set->sep_headers = TRUE; /* separated header lists by default */ + set->buffer_size = READBUFFER_SIZE; + set->upload_buffer_size = UPLOADBUFFER_DEFAULT; + set->upload_flags = CURLULFLAG_SEEN; + set->happy_eyeballs_timeout = CURL_HET_DEFAULT; + set->upkeep_interval_ms = CURL_UPKEEP_INTERVAL_DEFAULT; + set->maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */ + set->conn_max_idle_ms = 118 * 1000; + set->conn_max_age_ms = 24 * 3600 * 1000; + set->http09_allowed = FALSE; + set->httpwant = CURL_HTTP_VERSION_NONE; +#if defined(USE_HTTP2) || defined(USE_HTTP3) + set->weight = 0; +#endif + set->quick_exit = 0L; +#ifndef CURL_DISABLE_WEBSOCKETS + set->ws_raw_mode = FALSE; + set->ws_no_auto_pong = FALSE; +#endif +} + +/* easy->meta_hash destructor. Should never be called as elements + * MUST be added with their own destructor */ +static void easy_meta_freeentry(void *p) +{ + (void)p; + /* Always FALSE. Cannot use a 0 assert here since compilers + * are not in agreement if they then want a NORETURN attribute or + * not. *sigh* */ + DEBUGASSERT(!p); +} + +/** + * Curl_open() + * + * @param curl is a pointer to a Curl_easy pointer that gets set by this + * function. + * @return CURLcode + */ +CURLcode Curl_open(struct Curl_easy **curl) +{ + struct Curl_easy *data; + + /* simple start-up: alloc the struct, init it with zeroes and return */ + data = curlx_calloc(1, sizeof(struct Curl_easy)); + if(!data) { + /* this is a serious error */ + DEBUGF(curl_mfprintf(stderr, "Error: calloc of Curl_easy failed\n")); + return CURLE_OUT_OF_MEMORY; + } + + data->magic = CURLEASY_MAGIC_NUMBER; + /* most recent connection is not yet defined */ + data->state.lastconnect_id = -1; + /* and not assigned an id yet */ + data->id = -1; + data->mid = UINT32_MAX; + data->master_mid = UINT32_MAX; + data->progress.hide = TRUE; + + Curl_hash_init(&data->meta_hash, 23, + Curl_hash_str, curlx_str_key_compare, easy_meta_freeentry); + DEBUGASSERT(STRING_LAST <= UINT8_MAX); + Curl_u8_strset_init(&data->set.strings); + curlx_dyn_init(&data->state.headerb, CURL_MAX_HTTP_HEADER); + Curl_bufref_init(&data->state.url); + Curl_bufref_init(&data->state.referer); + Curl_req_init(&data->req); + Curl_initinfo(data); +#ifndef CURL_DISABLE_HTTP + Curl_llist_init(&data->state.httphdrs, NULL); +#endif + Curl_netrc_init(&data->state.netrc); + Curl_init_userdefined(data); + + *curl = data; + return CURLE_OK; +} + +void Curl_conn_free(struct Curl_easy *data, struct connectdata *conn) +{ + int8_t i; + + DEBUGASSERT(conn); + + if(conn->scheme && conn->scheme->run->disconnect && + !conn->bits.shutdown_handler) + conn->scheme->run->disconnect(data, conn, TRUE); + + for(i = 0; i < (int8_t)CURL_ARRAYSIZE(conn->cfilter); ++i) { + Curl_conn_cf_discard_all(data, conn, i); + } + +#ifndef CURL_DISABLE_PROXY + Curl_peer_unlink(&conn->http_proxy.peer); + Curl_peer_unlink(&conn->socks_proxy.peer); + Curl_creds_unlink(&conn->http_proxy.creds); + Curl_creds_unlink(&conn->socks_proxy.creds); +#endif + Curl_creds_unlink(&conn->creds); + Curl_peer_unlink(&conn->creds_origin); + curlx_safefree(conn->options); + curlx_safefree(conn->localdev); + Curl_ssl_conn_config_cleanup(conn); + + curlx_safefree(conn->destination); + Curl_hash_destroy(&conn->meta_hash); + Curl_peer_unlink(&conn->origin); + Curl_peer_unlink(&conn->via_peer); + Curl_peer_unlink(&conn->origin2); + Curl_peer_unlink(&conn->via_peer2); + + curlx_free(conn); /* free all the connection oriented data */ +} + +/* + * xfer_may_multiplex() + * + * Return a TRUE, iff the transfer can be done over an (appropriate) + * multiplexed connection. + */ +static bool xfer_may_multiplex(const struct Curl_easy *data, + const struct connectdata *conn) +{ +#ifndef CURL_DISABLE_HTTP + /* If an HTTP protocol and multiplexing is enabled */ + if((conn->scheme->protocol & PROTO_FAMILY_HTTP) && + (!conn->bits.protoconnstart || !conn->bits.close)) { + + if(Curl_multiplex_wanted(data->multi) && + (data->state.http_neg.allowed & (CURL_HTTP_V2x | CURL_HTTP_V3x))) + /* allows HTTP/2 or newer */ + return TRUE; + } +#else + (void)data; + (void)conn; +#endif + return FALSE; +} + +#ifndef CURL_DISABLE_PROXY +static bool proxy_info_matches(const struct proxy_info *data, + const struct proxy_info *needle) +{ + if((data->proxytype == needle->proxytype) && + Curl_peer_same_destination(data->peer, needle->peer) && + Curl_creds_same(data->creds, needle->creds)) { + return TRUE; + } + return FALSE; +} +#endif + +#ifdef USE_SSH +static bool ssh_config_matches(struct connectdata *one, + struct connectdata *two) +{ + struct ssh_conn *sshc1, *sshc2; + + sshc1 = Curl_conn_meta_get(one, CURL_META_SSH_CONN); + sshc2 = Curl_conn_meta_get(two, CURL_META_SSH_CONN); + return sshc1 && sshc2 && Curl_safecmp(sshc1->priv_key, sshc2->priv_key) && + Curl_safecmp(sshc1->pub_key, sshc2->pub_key); +} +#endif + +struct url_conn_match { + struct connectdata *found; + struct Curl_easy *data; + struct connectdata *needle; + struct curltime now; + BIT(may_multiplex); + BIT(want_ntlm_http); + BIT(want_proxy_ntlm_http); + BIT(want_nego_http); + BIT(want_proxy_nego_http); + BIT(may_tls); /* May upgrade clear-text connection to TLS, can only reuse + * connections that have matching TLS configuration. + * Always TRUE if `req_tls` is TRUE. */ + BIT(require_tls); /* Requires TLS use from a clear-text start, can only + * reuse connections that have TLS. */ + BIT(wait_pipe); + BIT(force_reuse); + BIT(seen_pending_conn); + BIT(seen_single_use_conn); + BIT(seen_multiplex_conn); +}; + +static bool url_match_connect_config(struct connectdata *conn, + struct url_conn_match *m) +{ + /* connect-only or to-be-closed connections will not be reused */ + if(conn->bits.connect_only || conn->bits.close || conn->bits.no_reuse) + return FALSE; + + /* ip_version must match */ + if(m->data->set.ipver != CURL_IPRESOLVE_WHATEVER && + m->data->set.ipver != conn->ip_version) + return FALSE; + + if(m->needle->localdev || m->needle->localport) { + /* If we are bound to a specific local end (IP+port), we must not reuse a + random other one, although if we did not ask for a particular one we + can reuse one that was bound. + + This comparison is a bit rough and too strict. Since the input + parameters can be specified in numerous ways and still end up the same + it would take a lot of processing to make it really accurate. Instead, + this matching will assume that reuses of bound connections will most + likely also reuse the exact same binding parameters and missing out a + few edge cases should not hurt anyone much. */ + if((conn->localport != m->needle->localport) || + (conn->localportrange != m->needle->localportrange) || + (m->needle->localdev && + (!conn->localdev || strcmp(conn->localdev, m->needle->localdev)))) + return FALSE; + } + + if(!m->needle->via_peer != !conn->via_peer) + /* do not mix connections that use the "connect to host" feature and + * connections that do not use this feature */ + return FALSE; + + return TRUE; +} + +static bool url_match_fully_connected(struct connectdata *conn, + struct url_conn_match *m) +{ + if(!Curl_conn_is_connected(conn, FIRSTSOCKET) || + conn->bits.upgrade_in_progress) { + /* Not yet connected, or a protocol upgrade is in progress. The later + * happens for HTTP/2 Upgrade: requests that need a response. */ + if(m->may_multiplex) { + m->seen_pending_conn = TRUE; + /* Do not pick a connection that has not connected yet */ + infof(m->data, "Connection #%" FMT_OFF_T + " is not open enough, cannot reuse", conn->connection_id); + } + /* Do not pick a connection that has not connected yet */ + return FALSE; + } + return TRUE; +} + +static bool url_match_multi(struct connectdata *conn, + struct url_conn_match *m) +{ + if(CONN_INUSE(conn)) { + DEBUGASSERT(conn->attached_multi); + if(conn->attached_multi != m->data->multi) + return FALSE; + } + return TRUE; +} + +static bool url_match_multiplex_needs(struct connectdata *conn, + struct url_conn_match *m) +{ + if(CONN_INUSE(conn)) { + if(!conn->bits.multiplex) { + /* conn busy and conn cannot take more transfers */ + m->seen_single_use_conn = TRUE; + return FALSE; + } + m->seen_multiplex_conn = TRUE; + if(!m->may_multiplex || !url_match_multi(conn, m)) + /* conn busy and transfer cannot be multiplexed */ + return FALSE; + } + return TRUE; +} + +static bool url_match_multiplex_limits(struct connectdata *conn, + struct url_conn_match *m) +{ + if(CONN_INUSE(conn) && m->may_multiplex) { + DEBUGASSERT(conn->bits.multiplex); + /* If multiplexed, make sure we do not go over concurrency limit */ + if(conn->attached_xfers >= + Curl_multi_max_concurrent_streams(m->data->multi)) { + infof(m->data, "client side MAX_CONCURRENT_STREAMS reached" + ", skip (%u)", conn->attached_xfers); + return FALSE; + } + if(conn->attached_xfers >= + Curl_conn_get_max_concurrent(m->data, conn, FIRSTSOCKET)) { + infof(m->data, "MAX_CONCURRENT_STREAMS reached, skip (%u)", + conn->attached_xfers); + return FALSE; + } + /* When not multiplexed, we have a match here! */ + infof(m->data, "Multiplexed connection found"); + } + return TRUE; +} + +static bool url_match_ssl_use(struct connectdata *conn, + struct url_conn_match *m) +{ + if(m->needle->scheme->flags & PROTOPT_SSL) { + /* We are looking for SSL, if `conn` does not do it, not a match. */ + if(!Curl_conn_is_ssl(conn, FIRSTSOCKET)) + return FALSE; + } + else if(Curl_conn_is_ssl(conn, FIRSTSOCKET)) { + /* If the protocol does not allow reuse of SSL connections OR + is of another protocol family, not a match. */ + if(!(m->needle->scheme->flags & PROTOPT_SSL_REUSE) || + (get_protocol_family(conn->scheme) != m->needle->scheme->protocol)) + return FALSE; + /* We may reuse this as an auto-TLS upgrade, but only if the SSL + * config parameters match. */ + if(!Curl_ssl_conn_config_match(m->data, conn, FALSE)) + return FALSE; + } + else if(m->require_tls) + /* a clear-text STARTTLS protocol with required TLS */ + return FALSE; + return TRUE; +} + +#ifndef CURL_DISABLE_PROXY +static bool url_match_proxy_use(struct connectdata *conn, + struct url_conn_match *m) +{ + if(m->needle->bits.origin_is_proxy != conn->bits.origin_is_proxy) + return FALSE; + + if(!proxy_info_matches(&m->needle->socks_proxy, &conn->socks_proxy)) + return FALSE; + + if(!proxy_info_matches(&m->needle->http_proxy, &conn->http_proxy)) + return FALSE; + + if(CURL_PROXY_IS_HTTPS(m->needle->http_proxy.proxytype)) { + /* https proxies come in different types, http/1.1, h2, ... */ + /* match SSL config to proxy */ + if(!Curl_ssl_conn_config_match(m->data, conn, TRUE)) { + DEBUGF(infof(m->data, + "Connection #%" FMT_OFF_T + " has different SSL proxy parameters, cannot reuse", + conn->connection_id)); + return FALSE; + } + /* the SSL config to the server, which may apply here is checked + * further below */ + } + return TRUE; +} +#else +#define url_match_proxy_use(c, m) ((void)(c), (void)(m), TRUE) +#endif + +#ifndef CURL_DISABLE_HTTP +static bool url_match_http_multiplex(struct connectdata *conn, + struct url_conn_match *m) +{ + if(m->may_multiplex && + (m->data->state.http_neg.allowed & (CURL_HTTP_V2x | CURL_HTTP_V3x)) && + (m->needle->scheme->protocol & CURLPROTO_HTTP) && + !conn->httpversion_seen) { + if(m->data->set.pipewait) { + infof(m->data, "Server upgrade does not support multiplex yet, wait"); + m->found = NULL; + m->wait_pipe = TRUE; + return TRUE; /* stop searching, we want to wait */ + } + infof(m->data, "Server upgrade cannot be used"); + return FALSE; + } + return TRUE; +} + +static bool url_match_http_version(struct connectdata *conn, + struct url_conn_match *m) +{ + /* If looking for HTTP and the HTTP versions allowed do not include + * the HTTP version of conn, continue looking. */ + if((m->needle->scheme->protocol & PROTO_FAMILY_HTTP)) { + switch(Curl_conn_http_version(m->data, conn)) { + case 30: + if(!(m->data->state.http_neg.allowed & CURL_HTTP_V3x)) { + DEBUGF(infof(m->data, "not reusing conn #%" CURL_FORMAT_CURL_OFF_T + ", we do not want h3", conn->connection_id)); + return FALSE; + } + break; + case 20: + if(!(m->data->state.http_neg.allowed & CURL_HTTP_V2x)) { + DEBUGF(infof(m->data, "not reusing conn #%" CURL_FORMAT_CURL_OFF_T + ", we do not want h2", conn->connection_id)); + return FALSE; + } + break; + default: + if(!(m->data->state.http_neg.allowed & CURL_HTTP_V1x)) { + DEBUGF(infof(m->data, "not reusing conn #%" CURL_FORMAT_CURL_OFF_T + ", we do not want h1", conn->connection_id)); + return FALSE; + } + break; + } + } + return TRUE; +} +#else +#define url_match_http_multiplex(c, m) ((void)(c), (void)(m), TRUE) +#define url_match_http_version(c, m) ((void)(c), (void)(m), TRUE) +#endif + +static bool url_match_proto_config(struct connectdata *conn, + struct url_conn_match *m) +{ + if(!url_match_http_version(conn, m)) + return FALSE; + +#ifdef USE_SSH + if(get_protocol_family(m->needle->scheme) & PROTO_FAMILY_SSH) { + if(!ssh_config_matches(m->needle, conn)) + return FALSE; + } +#endif +#ifndef CURL_DISABLE_FTP + else if(get_protocol_family(m->needle->scheme) & PROTO_FAMILY_FTP) { + if(!Curl_ftp_conns_match(m->needle, conn)) + return FALSE; + } +#endif + return TRUE; +} + +static bool url_match_auth(struct connectdata *conn, + struct url_conn_match *m) +{ + if(!Curl_creds_same(m->needle->creds, conn->creds)) { + if(m->needle->creds) + return FALSE; + if(!Curl_creds_same(m->data->state.creds, conn->creds)) + return FALSE; + } +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + /* GSS delegation differences do not actually affect every connection and + auth method, but this check takes precaution before efficiency */ + if(m->needle->gssapi_delegation != conn->gssapi_delegation) + return FALSE; +#endif + + return TRUE; +} + +static bool url_match_destination(struct connectdata *conn, + struct url_conn_match *m) +{ + /* Different connect-to peers never match */ + if(!Curl_peer_same_destination(m->needle->via_peer, conn->via_peer)) + return FALSE; + + if(m->needle->origin->scheme != conn->origin->scheme) { + /* `needle` and `conn` not having the same scheme. + * This is allowed for the same family *if* conn is using TLS. + * - IMAP+STARTTLS works for IMAPS. + * - IMAPS works for IMAP. */ + if(get_protocol_family(conn->origin->scheme) != + m->needle->scheme->protocol) { + return FALSE; + } + } + /* Scheme mismatch is acceptable, compare hostname/port */ + return Curl_peer_same_destination(m->needle->origin, conn->origin); +} + +static bool url_match_ssl_config(struct connectdata *conn, + struct url_conn_match *m) +{ + /* If talking/upgrading to TLS, conn needs to use the same SSL options. */ + if(((m->needle->scheme->flags & PROTOPT_SSL) || m->may_tls) && + !Curl_ssl_conn_config_match(m->data, conn, FALSE)) { + DEBUGF(infof(m->data, "Connection #%" FMT_OFF_T + " has different SSL parameters, cannot reuse", + conn->connection_id)); + return FALSE; + } + return TRUE; +} + +#ifdef USE_NTLM +static bool url_match_auth_ntlm(struct connectdata *conn, + struct url_conn_match *m) +{ + if(conn->http_ntlm_state != NTLMSTATE_NONE) { + /* Connection is using NTLM. We cannot reuse if transfer + * has different Auth input parameters. */ + if(!m->want_ntlm_http || + !Curl_creds_same(conn->creds, m->data->state.creds) || + !Curl_peer_equal(conn->creds_origin, m->data->state.origin)) + return FALSE; + } + else if(m->want_ntlm_http) { + /* Transfer wants NTLM, connection is not using it. + * Do not reuse when connection has credentials and they differ. */ + if(conn->creds && + (!Curl_creds_same(conn->creds, m->data->state.creds) || + !Curl_peer_equal(conn->creds_origin, m->data->state.origin))) + return FALSE; + } + +#ifndef CURL_DISABLE_PROXY + /* Same for Proxy NTLM authentication */ + if(conn->proxy_ntlm_state != NTLMSTATE_NONE) { + if(!m->want_proxy_ntlm_http || + !Curl_creds_same(m->needle->http_proxy.creds, conn->http_proxy.creds)) + return FALSE; + } + else if(m->want_proxy_ntlm_http) { + if(conn->http_proxy.creds && + !Curl_creds_same(m->needle->http_proxy.creds, conn->http_proxy.creds)) + return FALSE; + } +#endif + if(m->want_ntlm_http || m->want_proxy_ntlm_http) { + /* Credentials are already checked, we may use this connection. + * With NTLM being weird as it is, we MUST use a + * connection where it has already been fully negotiated. + * If it has not, we keep on looking for a better one. */ + m->found = conn; + + if((m->want_ntlm_http && + (conn->http_ntlm_state != NTLMSTATE_NONE)) || + (m->want_proxy_ntlm_http && + (conn->proxy_ntlm_state != NTLMSTATE_NONE))) { + /* We must use this connection, no other */ + m->force_reuse = TRUE; + return TRUE; + } + /* Continue look up for a better connection */ + return FALSE; + } + return TRUE; +} +#else +#define url_match_auth_ntlm(c, m) ((void)(c), (void)(m), TRUE) +#endif + +#ifdef USE_SPNEGO +static bool url_match_auth_nego(struct connectdata *conn, + struct url_conn_match *m) +{ + if(conn->http_negotiate_state != GSS_AUTHNONE) { + /* Connection is using Negotiate. We cannot reuse if transfer + * has different Auth input parameters. */ + if(!m->want_nego_http || + !Curl_creds_same(conn->creds, m->data->state.creds) || + !Curl_peer_equal(conn->creds_origin, m->data->state.origin)) + return FALSE; + } + else if(m->want_nego_http) { + /* Transfer wants Negotiate, connection is not using it. + * Do not reuse when connection has credentials and they differ. */ + if(conn->creds && + (!Curl_creds_same(conn->creds, m->data->state.creds) || + !Curl_peer_equal(conn->creds_origin, m->data->state.origin))) + return FALSE; + } + +#ifndef CURL_DISABLE_PROXY + /* Same for Proxy Negotiate authentication */ + if(conn->proxy_negotiate_state != GSS_AUTHNONE) { + if(!m->want_proxy_nego_http || + !Curl_creds_same(m->needle->http_proxy.creds, conn->http_proxy.creds)) + return FALSE; + } + else if(m->want_proxy_nego_http) { + if(conn->http_proxy.creds && + !Curl_creds_same(m->needle->http_proxy.creds, conn->http_proxy.creds)) + return FALSE; + } +#endif + if(m->want_nego_http || m->want_proxy_nego_http) { + /* Credentials are already checked, we may use this connection. We MUST + * use a connection where it has already been fully negotiated. If it has + * not, we keep on looking for a better one. */ + m->found = conn; + if((m->want_nego_http && + (conn->http_negotiate_state != GSS_AUTHNONE)) || + (m->want_proxy_nego_http && + (conn->proxy_negotiate_state != GSS_AUTHNONE))) { + /* We must use this connection, no other */ + m->force_reuse = TRUE; + return TRUE; + } + return FALSE; /* get another */ + } + return TRUE; +} +#else +#define url_match_auth_nego(c, m) ((void)(c), (void)(m), TRUE) +#endif + +static bool url_match_conn(struct connectdata *conn, void *userdata) +{ + struct url_conn_match *m = userdata; + /* Check if `conn` can be used for transfer `m->data` */ + + /* general connect config setting match? */ + if(!url_match_connect_config(conn, m)) + return FALSE; + + /* match for destination and protocol? */ + if(!url_match_destination(conn, m)) + return FALSE; + + if(!url_match_fully_connected(conn, m)) + return FALSE; + + if(!url_match_multiplex_needs(conn, m)) + return FALSE; + + if(!url_match_ssl_use(conn, m)) + return FALSE; + + if(!url_match_proxy_use(conn, m)) + return FALSE; + if(!url_match_ssl_config(conn, m)) + return FALSE; + + if(!url_match_http_multiplex(conn, m)) + return FALSE; + else if(m->wait_pipe) + /* wait on multiplexing */ + return TRUE; + + if(!url_match_auth(conn, m)) + return FALSE; + + if(!url_match_proto_config(conn, m)) + return FALSE; + + if(!url_match_auth_ntlm(conn, m)) + return FALSE; + else if(m->force_reuse) + return TRUE; + + if(!url_match_auth_nego(conn, m)) + return FALSE; + else if(m->force_reuse) + return TRUE; + + if(!url_match_multiplex_limits(conn, m)) + return FALSE; + + if(m->data->set.conn_max_age_ms > 0) { + timediff_t age_ms = curlx_ptimediff_ms(&m->now, &conn->created); + if(age_ms > m->data->set.conn_max_age_ms) { + /* Transfer is looking for a younger connection. */ + if(!CONN_INUSE(conn)) + Curl_conn_close(m->data, conn, FALSE); + return FALSE; + } + } + + /* If we are going to pick an idle connection, do an extra + * health check before we reuse it. */ + if(!CONN_INUSE(conn) && + !Curl_cpool_conn_seems_healthy(conn, m->data, &m->now)) { + infof(m->data, "Connection %" FMT_OFF_T " seems to be dead, terminating", + conn->connection_id); + Curl_conn_close(m->data, conn, FALSE); + return FALSE; + } + + /* conn matches our needs. */ + m->found = conn; + return TRUE; +} + +static bool url_match_result(void *userdata) +{ + struct url_conn_match *match = userdata; + if(match->found) { + /* Attach it now while still under lock, so the connection does + * no longer appear idle and can be reaped. */ + Curl_attach_connection(match->data, match->found, TRUE); + return TRUE; + } + else if(match->seen_single_use_conn && !match->seen_multiplex_conn) { + /* We have seen a single-use, existing connection to the destination and + * no multiplexed one. It seems safe to assume that the server does + * not support multiplexing. */ + match->wait_pipe = FALSE; + } + else if(match->seen_pending_conn && match->data->set.pipewait) { + infof(match->data, + "Found pending candidate for reuse and CURLOPT_PIPEWAIT is set"); + match->wait_pipe = TRUE; + } + match->force_reuse = FALSE; + return FALSE; +} + +/* + * Given a transfer and a prototype connection (needle), + * find and attach an existing connection that matches. + * + * Return TRUE if an existing connection was attached. + * `waitpipe` is TRUE if no existing connection matched, but there + * might be suitable one in the near future (common cause: multiplexing + * capability has not been determined yet, e.g. ALPN handshake). + */ +static bool url_attach_existing(struct Curl_easy *data, + struct connectdata *needle, + bool *waitpipe) +{ + struct cpool *cpool = Curl_cpool_get_instance(data); + struct url_conn_match match; + bool success; + + DEBUGASSERT(!data->conn); + + memset(&match, 0, sizeof(match)); + match.data = data; + match.needle = needle; + match.now = *Curl_pgrs_now(data); + match.may_multiplex = xfer_may_multiplex(data, needle); + + Curl_cpool_prune_dead(cpool, data); + +#ifdef USE_NTLM + match.want_ntlm_http = + (data->state.authhost.want & CURLAUTH_NTLM) && + (needle->scheme->protocol & PROTO_FAMILY_HTTP); +#ifndef CURL_DISABLE_PROXY + match.want_proxy_ntlm_http = + needle->http_proxy.creds && + (data->state.authproxy.want & CURLAUTH_NTLM) && + (needle->scheme->protocol & PROTO_FAMILY_HTTP); +#endif +#endif + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO) + match.want_nego_http = + (data->state.authhost.want & CURLAUTH_NEGOTIATE) && + (needle->scheme->protocol & PROTO_FAMILY_HTTP); +#ifndef CURL_DISABLE_PROXY + match.want_proxy_nego_http = + needle->http_proxy.creds && + (data->state.authproxy.want & CURLAUTH_NEGOTIATE) && + (needle->scheme->protocol & PROTO_FAMILY_HTTP); +#endif +#endif + match.require_tls = data->set.use_ssl >= CURLUSESSL_CONTROL; + match.may_tls = data->set.use_ssl > CURLUSESSL_NONE; + + /* Find a connection in the pool that matches what "data + needle" + * requires. If a suitable candidate is found, it is attached to "data". */ + success = Curl_cpool_find(data, needle->destination, + url_match_conn, url_match_result, &match); + + /* wait_pipe is TRUE if we encounter a bundle that is undecided. There + * is no matching connection then, yet. */ + *waitpipe = (bool)match.wait_pipe; + return success; +} + +/* + * Allocate and initialize a new connectdata object. + */ +static struct connectdata *allocate_conn(struct Curl_easy *data) +{ + struct connectdata *conn = curlx_calloc(1, sizeof(struct connectdata)); + if(!conn) + return NULL; + + /* and we setup a few fields in case we end up actually using this struct */ + + conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */ + conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */ + conn->recv_idx = 0; /* default for receiving transfer data */ + conn->send_idx = 0; /* default for sending transfer data */ + conn->connection_id = -1; /* no ID */ + conn->attached_xfers = 0; + + /* Remember time this connection started */ + conn->lastused = conn->lastupkeep = conn->created = *Curl_pgrs_now(data); + +#ifndef CURL_DISABLE_FTP + conn->bits.ftp_use_epsv = data->set.ftp_use_epsv; + conn->bits.ftp_use_eprt = data->set.ftp_use_eprt; +#endif + conn->ip_version = data->set.ipver; + conn->bits.connect_only = (bool)data->set.connect_only; + conn->transport_wanted = TRNSPRT_TCP; /* most of them are TCP streams */ + + /* Store the local bind parameters that will be used for this connection */ + if(CURL_EASY_STR(data, STRING_DEVICE)) { + conn->localdev = curlx_strdup(CURL_EASY_STR(data, STRING_DEVICE)); + if(!conn->localdev) + goto error; + } +#ifndef CURL_DISABLE_BINDLOCAL + conn->localportrange = data->set.localportrange; + conn->localport = data->set.localport; +#endif + + /* the close socket stuff needs to be copied to the connection struct as + it may live on without (this specific) Curl_easy */ + conn->fclosesocket = data->set.fclosesocket; + conn->closesocket_client = data->set.closesocket_client; +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + conn->gssapi_delegation = data->set.gssapi_delegation; +#endif + return conn; +error: + + curlx_free(conn->localdev); + curlx_free(conn); + return NULL; +} + +static CURLcode url_set_conn_scheme(struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_scheme *scheme) +{ + /* URL scheme is usable for connection when it is + * - allowed + * - not from a redirect or an allowed redirect protocol */ + if(scheme->run && + (data->set.allowed_protocols & scheme->protocol) && + (!data->state.this_is_a_follow || + (data->set.redir_protocols & scheme->protocol))) { + conn->scheme = conn->given = scheme; + return CURLE_OK; + } + if(scheme->flags & PROTOPT_NO_TRANSFER) + failf(data, "Protocol \"%s\" is not for transfers", scheme->name); + else + failf(data, "Protocol \"%s\" is disabled%s", scheme->name, + data->state.this_is_a_follow ? " (in redirect)" : ""); + return CURLE_UNSUPPORTED_PROTOCOL; +} + +CURLcode Curl_uc_to_curlcode(CURLUcode uc) +{ + switch(uc) { + default: + return CURLE_URL_MALFORMAT; + case CURLUE_UNSUPPORTED_SCHEME: + return CURLE_UNSUPPORTED_PROTOCOL; + case CURLUE_OUT_OF_MEMORY: + return CURLE_OUT_OF_MEMORY; + case CURLUE_USER_NOT_ALLOWED: + return CURLE_LOGIN_DENIED; + } +} + +#ifndef CURL_DISABLE_HSTS +static CURLcode hsts_upgrade(struct Curl_easy *data, + CURLU *uh, + uint16_t port_override, + uint32_t scope_id) +{ + /* HSTS upgrade */ + if(data->hsts && (data->state.origin->scheme == &Curl_scheme_http) && + Curl_hsts_applies(data->hsts, data->state.origin)) { + char *url; + CURLUcode uc; + CURLcode result; + + uc = curl_url_set(uh, CURLUPART_SCHEME, "https", 0); + if(uc) + return Curl_uc_to_curlcode(uc); + Curl_bufref_free(&data->state.url); + /* after update, get the updated version */ + uc = curl_url_get(uh, CURLUPART_URL, &url, 0); + if(uc) + return Curl_uc_to_curlcode(uc); + Curl_bufref_set(&data->state.url, url, 0, curl_free); + + result = Curl_peer_from_url(uh, data, port_override, scope_id, + &data->state.origin); + if(result) + return result; + infof(data, "Switched from HTTP to HTTPS due to HSTS => %s", url); + } + return CURLE_OK; +} +#else +#define hsts_upgrade(x, y, z, a) CURLE_OK +#endif + +static bool str_has_ctrl(const char *input) +{ + if(input) { + const unsigned char *str = (const unsigned char *)input; + while(*str) { + if(*str < 0x20) + return TRUE; + str++; + } + } + return FALSE; +} + +#ifndef CURL_DISABLE_NETRC +/* + * Override the login details from the URL with that in the CURLOPT_USERPWD + * option or a .netrc file, if applicable. + */ +static CURLcode url_set_data_creds_netrc(struct Curl_easy *data, + struct Curl_creds **pcreds) +{ + struct Curl_creds *ncreds_out = NULL; + CURLcode result = CURLE_OK; + + if(data->set.use_netrc) { /* not CURL_NETRC_IGNORED */ + struct Curl_creds *ncreds_in = NULL; + bool scan_netrc = TRUE; + NETRCcode ret; + CURLUcode uc; + + if(*pcreds) { + switch((*pcreds)->source) { + case CREDS_OPTION: + /* we never override credentials set via CURLOPT_*, leave. */ + scan_netrc = FALSE; + break; + case CREDS_URL: /* only apply when netrc is not required */ + if(data->set.use_netrc == CURL_NETRC_REQUIRED) { + /* We ignore password from URL */ + ncreds_in = *pcreds; + } + else if(!Curl_creds_has_user(*pcreds) || + !Curl_creds_has_passwd(*pcreds)) { + /* We use netrc to complete what is missing */ + ncreds_in = *pcreds; + } + else + scan_netrc = FALSE; + break; + default: /* ignore credentials from other sources */ + break; + } + } + + if(!scan_netrc) + goto out; + + ret = Curl_netrc_scan(data, &data->state.netrc, + data->state.origin->hostname, + Curl_creds_user(ncreds_in), + CURL_EASY_STR(data, STRING_NETRC_FILE), + &ncreds_out); + DEBUGASSERT(!ret || !ncreds_out); + if(ret == NETRC_OUT_OF_MEMORY) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + else if(ret && ((ret == NETRC_NO_MATCH) || + (data->set.use_netrc == CURL_NETRC_OPTIONAL))) { + infof(data, "Could not find host %s in the %s file; using defaults", + data->state.origin->hostname, + (CURL_EASY_STR(data, STRING_NETRC_FILE) ? + CURL_EASY_STR(data, STRING_NETRC_FILE) : ".netrc")); + } + else if(ret) { + const char *m = Curl_netrc_strerror(ret); + failf(data, ".netrc error: %s", m); + result = CURLE_READ_ERROR; + goto out; + } + else if(ncreds_out) { + if(!(data->state.origin->scheme->flags & PROTOPT_USERPWDCTRL)) { + /* if the protocol cannot handle control codes in credentials, make + sure there are none */ + if(str_has_ctrl(ncreds_out->user) || + str_has_ctrl(ncreds_out->passwd)) { + failf(data, "control code detected in .netrc credentials"); + result = CURLE_READ_ERROR; + goto out; + } + } + CURL_TRC_M(data, "netrc: using credentials for %s as %s", + data->state.origin->hostname, ncreds_out->user); + result = Curl_creds_merge(ncreds_out->user, ncreds_out->passwd, + *pcreds, CREDS_NETRC, pcreds); + if(result) + goto out; + /* for updated strings, we update them in the URL */ + uc = curl_url_set(data->state.uh, CURLUPART_USER, + Curl_creds_user(*pcreds), CURLU_URLENCODE); + if(!uc) + uc = curl_url_set(data->state.uh, CURLUPART_PASSWORD, + Curl_creds_passwd(*pcreds), + CURLU_URLENCODE); + if(uc) + result = Curl_uc_to_curlcode(uc); + } + else + DEBUGASSERT(0); + } + +#ifdef CURLVERBOSE + Curl_creds_trace(data, data->state.creds, "transfer credentials"); +#endif + +out: + Curl_creds_unlink(&ncreds_out); + return result; +} +#endif /* CURL_DISABLE_NETRC */ + +static CURLcode url_set_data_creds(struct Curl_easy *data, CURLU *uh) +{ + struct Curl_creds *newcreds = NULL; + CURLcode result = CURLE_OK; + + if((CURL_EASY_STR(data, STRING_USERNAME) || + CURL_EASY_STR(data, STRING_PASSWORD) || + CURL_EASY_STR(data, STRING_BEARER) || + CURL_EASY_STR(data, STRING_SASL_AUTHZID) || + CURL_EASY_STR(data, STRING_SERVICE_NAME)) && + Curl_auth_allowed_to_origin(data, data->state.origin)) { + result = Curl_creds_create(CURL_EASY_STR(data, STRING_USERNAME), + CURL_EASY_STR(data, STRING_PASSWORD), + CURL_EASY_STR(data, STRING_BEARER), + CURL_EASY_STR(data, STRING_SASL_AUTHZID), + CURL_EASY_STR(data, STRING_SERVICE_NAME), + CREDS_OPTION, &newcreds); + if(result) + goto out; + if(newcreds && + !(data->state.origin->scheme->flags & PROTOPT_USERPWDCTRL) && + (str_has_ctrl(Curl_creds_user(newcreds)) || + str_has_ctrl(Curl_creds_passwd(newcreds)))) { + /* if the protocol cannot handle control codes in credentials, make + sure there are none */ + failf(data, "control code detected in credentials"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + } + + /* Extract credentials from the URL only if there are none OR + * if no CURLOPT_USER was set. */ + if(!newcreds || !Curl_creds_has_user(newcreds)) { + char *user = NULL; + char *passwd = NULL; + char *udecoded = NULL; + char *pdecoded = NULL; + CURLUcode uc; + + uc = curl_url_get(uh, CURLUPART_USER, &user, 0); + if(uc && (uc != CURLUE_NO_USER)) + result = Curl_uc_to_curlcode(uc); + if(!result) { + uc = curl_url_get(uh, CURLUPART_PASSWORD, &passwd, 0); + if(uc && (uc != CURLUE_NO_PASSWORD)) + result = Curl_uc_to_curlcode(uc); + } + if(!result && user) { + result = Curl_urldecode(user, 0, &udecoded, NULL, + (data->state.origin->scheme->flags & + PROTOPT_USERPWDCTRL) ? + REJECT_ZERO : REJECT_CTRL); + } + if(!result && passwd) { + result = Curl_urldecode(passwd, 0, &pdecoded, NULL, + (data->state.origin->scheme->flags & + PROTOPT_USERPWDCTRL) ? + REJECT_ZERO : REJECT_CTRL); + } + if(!result) + result = Curl_creds_merge(udecoded, pdecoded, newcreds, + CREDS_URL, &newcreds); + + curlx_free(udecoded); + curlx_free(pdecoded); + curlx_free(passwd); + curlx_free(user); + if(result) { + failf(data, "error extracting credentials from URL"); + goto out; + } + } + +#ifndef CURL_DISABLE_NETRC + /* Check for overridden login details and set them accordingly so that + they are known when protocol->setup_connection is called! */ + result = url_set_data_creds_netrc(data, &newcreds); +#endif /* CURL_DISABLE_NETRC */ + +out: + if(!result && !Curl_creds_equal(data->state.creds, newcreds)) { + /* Do we have more things to trigger on credentials change? */ + Curl_creds_link(&data->state.creds, newcreds); + } + Curl_creds_unlink(&newcreds); + return result; +} + +static CURLcode url_set_conn_origin_etc(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + + Curl_peer_link(&conn->origin, data->state.origin); + + /* set the connection scheme */ + result = url_set_conn_scheme(data, conn, conn->origin->scheme); + if(result) + goto out; + + /* set the connection options */ + if(CURL_EASY_STR(data, STRING_OPTIONS)) { + conn->options = curlx_strdup(CURL_EASY_STR(data, STRING_OPTIONS)); + if(!conn->options) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + else if(data->state.up.options) { + conn->options = curlx_strdup(data->state.up.options); + if(!conn->options) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + +out: + return result; +} + +/* + * If we are doing a resumed transfer, we need to setup our stuff + * properly. + */ +static CURLcode setup_range(struct Curl_easy *data) +{ + struct UrlState *s = &data->state; + s->resume_from = data->set.set_resume_from; + if(s->resume_from || CURL_EASY_STR(data, STRING_SET_RANGE)) { + if(s->rangestringalloc) + curlx_free(s->range); + + if(s->resume_from) + s->range = curl_maprintf("%" FMT_OFF_T "-", s->resume_from); + else + s->range = curlx_strdup(CURL_EASY_STR(data, STRING_SET_RANGE)); + + if(!s->range) + return CURLE_OUT_OF_MEMORY; + + s->rangestringalloc = TRUE; + + /* tell ourselves to fetch this range */ + s->use_range = TRUE; /* enable range download */ + } + else + s->use_range = FALSE; /* disable range download */ + + return CURLE_OK; +} + +/* + * setup_connection_internals() - + * + * Setup connection internals specific to the requested protocol in the + * Curl_easy. This is inited and setup before the connection is made but + * is about the particular protocol that is to be used. + * + * This MUST get called after proxy magic has been figured out. + */ +static CURLcode setup_connection_internals(struct Curl_easy *data, + struct connectdata *conn) +{ + struct Curl_peer *peer = NULL; + CURLcode result; + + if(conn->scheme->run->setup_connection) { + result = conn->scheme->run->setup_connection(data, conn); + if(result) + return result; + } + + /* Now create the destination name */ + peer = Curl_conn_get_destination(conn, FIRSTSOCKET); + if(!peer) + return CURLE_FAILED_INIT; + + /* IPv6 addresses with a scope_id (0 is default == global) have a + * printable representation with a '%<scope_id>' suffix. */ + if(peer->ipv6) + if(peer->scopeid) + conn->destination = curl_maprintf("[%s%%%u]:%u", + peer->hostname, peer->scopeid, peer->port); + else + conn->destination = curl_maprintf("[%s]:%u", + peer->hostname, peer->port); + else + conn->destination = curl_maprintf("%s:%u", peer->hostname, peer->port); + if(!conn->destination) + return CURLE_OUT_OF_MEMORY; + + Curl_strntolower(conn->destination, conn->destination, + strlen(conn->destination)); + +#ifdef USE_IPV6 + if(data->set.scope_id) + conn->scope_id = data->set.scope_id; + else { + struct Curl_peer *first = Curl_conn_get_first_peer(conn, FIRSTSOCKET); + if(!first) + return CURLE_FAILED_INIT; + conn->scope_id = first->scopeid; + } +#endif + + return CURLE_OK; +} + +/* + * Curl_parse_login_details() + * + * This is used to parse a login string for username, password and options in + * the following formats: + * + * user + * user:password + * user:password;options + * user;options + * user;options:password + * :password + * :password;options + * ;options + * ;options:password + * + * Parameters: + * + * login [in] - login string. + * len [in] - length of the login string. + * userp [in/out] - address where a pointer to newly allocated memory + * holding the user will be stored upon completion. + * passwdp [in/out] - address where a pointer to newly allocated memory + * holding the password will be stored upon completion. + * optionsp [in/out] - OPTIONAL address where a pointer to newly allocated + * memory holding the options will be stored upon + * completion. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_parse_login_details(const char *login, const size_t len, + char **userp, char **passwdp, + char **optionsp) +{ + char *ubuf = NULL; + char *pbuf = NULL; + const char *psep = NULL; + const char *osep = NULL; + size_t ulen; + size_t plen; + size_t olen; + + DEBUGASSERT(userp); + DEBUGASSERT(passwdp); + + /* Attempt to find the password separator */ + psep = memchr(login, ':', len); + + /* Attempt to find the options separator */ + if(optionsp) + osep = memchr(login, ';', len); + + /* Calculate the portion lengths */ + ulen = (psep ? + (size_t)(osep && psep > osep ? osep - login : psep - login) : + (osep ? (size_t)(osep - login) : len)); + plen = (psep ? + (osep && osep > psep ? (size_t)(osep - psep) : + (size_t)(login + len - psep)) - 1 : 0); + olen = (osep ? + (psep && psep > osep ? (size_t)(psep - osep) : + (size_t)(login + len - osep)) - 1 : 0); + + /* Clone the user portion buffer, which can be zero length */ + ubuf = curlx_memdup0(login, ulen); + if(!ubuf) + goto error; + + /* Clone the password portion buffer */ + if(psep) { + pbuf = curlx_memdup0(&psep[1], plen); + if(!pbuf) + goto error; + } + + /* Allocate the options portion buffer */ + if(optionsp) { + char *obuf = NULL; + if(olen) { + obuf = curlx_memdup0(&osep[1], olen); + if(!obuf) + goto error; + } + *optionsp = obuf; + } + *userp = ubuf; + *passwdp = pbuf; + return CURLE_OK; +error: + curlx_free(ubuf); + curlx_free(pbuf); + return CURLE_OUT_OF_MEMORY; +} + +/* + * Set the login details so they are available in the connection + */ +static CURLcode url_set_conn_login(struct Curl_easy *data, + struct connectdata *conn) +{ + /* If our protocol needs a password and we have none, use the defaults */ + if((conn->scheme->flags & PROTOPT_NEEDSPWD) && !conn->creds) { + Curl_peer_link(&conn->creds_origin, data->state.origin); + if(data->state.creds) + Curl_creds_link(&conn->creds, data->state.creds); + else + return Curl_creds_create(CURL_DEFAULT_USER, CURL_DEFAULT_PASSWORD, + NULL, NULL, NULL, CREDS_NONE, &conn->creds); + } + else if(!(conn->scheme->flags & PROTOPT_CREDSPERREQUEST)) { + /* for protocols that do not handle credentials per request, + * the connection credentials are set by the initial transfer. */ + Curl_peer_link(&conn->creds_origin, data->state.origin); + Curl_creds_link(&conn->creds, data->state.creds); + } + + return CURLE_OK; +} + +/* + * Parses one "connect to" string in the form: + * "HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT". + */ +static CURLcode parse_connect_to_string(struct Curl_easy *data, + const struct Curl_peer *dest, + const char *conn_to_line, + struct Curl_peer **pvia_dest) +{ + CURLcode result = CURLE_OK; + const char *ptr = conn_to_line; + bool host_match = FALSE; + bool port_match = FALSE; + + *pvia_dest = NULL; + + if(*ptr == ':') { + /* an empty hostname always matches */ + host_match = TRUE; + ptr++; + } + else { + /* check whether the URL's hostname matches. Use the URL hostname + * when it was an IPv6 address. Otherwise use the connection's hostname + * that has IDN conversion. */ + size_t hlen = strlen(dest->hostname); + host_match = curl_strnequal(ptr, dest->hostname, hlen); + if(!host_match && (dest->user_hostname != dest->hostname)) { + /* hostname was normalized, could be IPv6 or IDN */ + hlen = strlen(dest->user_hostname); + host_match = curl_strnequal(ptr, dest->user_hostname, hlen); + } + host_match = host_match && ptr[hlen] == ':'; + if(host_match) + ptr += hlen + 1; + } + + if(host_match) { + if(*ptr == ':') { + /* an empty port always matches */ + port_match = TRUE; + ptr++; + } + else { + /* check whether the URL's port matches */ + const char *ptr_next = strchr(ptr, ':'); + if(ptr_next) { + curl_off_t port_to_match; + if(!curlx_str_number(&ptr, &port_to_match, 0xffff) && + ((uint16_t)port_to_match == dest->port)) { + port_match = TRUE; + } + ptr = ptr_next + 1; + } + } + } + + if(host_match && port_match && ptr && *ptr) + result = Curl_peer_from_connect_to(data, dest, ptr, pvia_dest); + + return result; +} + +/* With `conn->origin` known, determine if we should talk to that + * directly or via another peer. This is the result of inspecting + * the "connect to" slist and "alt-svc" settings. */ +static CURLcode url_set_conn_peer(struct Curl_easy *data, + struct connectdata *conn) +{ + CURLcode result = CURLE_OK; + struct Curl_peer *origin = conn->origin; + struct Curl_peer *via_peer = NULL; + struct curl_slist *conn_to_entry = data->set.connect_to; + + DEBUGASSERT(!conn->via_peer); + Curl_peer_unlink(&conn->via_peer); + + while(conn_to_entry && !via_peer) { + result = parse_connect_to_string(data, origin, conn_to_entry->data, + &via_peer); + if(result) + return result; + conn_to_entry = conn_to_entry->next; + } + +#ifndef CURL_DISABLE_ALTSVC + if(data->asi && !via_peer && + ((conn->scheme->protocol == CURLPROTO_HTTPS) || +#ifdef DEBUGBUILD + /* allow debug builds to circumvent the HTTPS restriction */ + getenv("CURL_ALTSVC_HTTP") +#else + 0 +#endif + )) { + /* no connect_to match, try alt-svc! */ + enum alpnid srcalpnid = ALPN_none; + bool hit = FALSE; + struct altsvc *as = NULL; + int allowed_alpns = ALPN_none; + struct http_negotiation *neg = &data->state.http_neg; + bool same_dest = FALSE; + + DEBUGF(infof(data, "Alt-svc check wanted=%x, allowed=%x", + neg->wanted, neg->allowed)); +#ifdef USE_HTTP3 + if(neg->allowed & CURL_HTTP_V3x) + allowed_alpns |= ALPN_h3; +#endif +#ifdef USE_HTTP2 + if(neg->allowed & CURL_HTTP_V2x) + allowed_alpns |= ALPN_h2; +#endif + if(neg->allowed & CURL_HTTP_V1x) + allowed_alpns |= ALPN_h1; + allowed_alpns &= (int)data->asi->flags; + + DEBUGF(infof(data, "check Alt-Svc for host '%s'", origin->hostname)); +#ifdef USE_HTTP3 + if(!hit && (neg->wanted & CURL_HTTP_V3x)) { + srcalpnid = ALPN_h3; + hit = Curl_altsvc_lookup(data->asi, + origin, ALPN_h3, /* from */ + &as /* to */, + allowed_alpns, &same_dest); + } +#endif +#ifdef USE_HTTP2 + if(!hit && (neg->wanted & CURL_HTTP_V2x) && + !neg->h2_prior_knowledge) { + srcalpnid = ALPN_h2; + hit = Curl_altsvc_lookup(data->asi, + origin, ALPN_h2, /* from */ + &as /* to */, + allowed_alpns, &same_dest); + } +#endif + if(!hit && (neg->wanted & CURL_HTTP_V1x) && + !neg->only_10) { + srcalpnid = ALPN_h1; + hit = Curl_altsvc_lookup(data->asi, + origin, ALPN_h1, /* from */ + &as /* to */, + allowed_alpns, &same_dest); + } + + if(hit && same_dest) { + /* same destination, but more HTTPS version options */ + switch(as->dst.alpnid) { + case ALPN_h1: + neg->wanted |= CURL_HTTP_V1x; + neg->preferred = CURL_HTTP_V1x; + break; + case ALPN_h2: + neg->wanted |= CURL_HTTP_V2x; + neg->preferred = CURL_HTTP_V2x; + break; + case ALPN_h3: + neg->wanted |= CURL_HTTP_V3x; + neg->preferred = CURL_HTTP_V3x; + break; + default: /* should not be possible */ + break; + } + } + else if(hit) { + result = Curl_peer_create(data, conn->origin->scheme, + as->dst.host, as->dst.port, + &via_peer); + if(result) + return result; + infof(data, "Alt-svc connecting from [%s]%s:%u to [%s]%s:%u", + Curl_alpnid2str(srcalpnid), origin->hostname, origin->port, + Curl_alpnid2str(as->dst.alpnid), + via_peer->hostname, via_peer->port); + conn->bits.altused = TRUE; + if(srcalpnid != as->dst.alpnid) { + /* protocol version switch */ + switch(as->dst.alpnid) { + case ALPN_h1: + neg->wanted = neg->allowed = CURL_HTTP_V1x; + neg->only_10 = FALSE; + break; + case ALPN_h2: + neg->wanted = neg->allowed = CURL_HTTP_V2x; + break; + case ALPN_h3: + conn->transport_wanted = TRNSPRT_QUIC; + neg->wanted = neg->allowed = CURL_HTTP_V3x; + break; + default: /* should not be possible */ + break; + } + } + } + } +#endif + + if(via_peer) + conn->via_peer = via_peer; + + return result; +} + +/* + * Adjust reused connection settings to the transfer/needle. + */ +static void url_conn_reuse_adjust(struct Curl_easy *data, + struct connectdata *needle) +{ + struct connectdata *conn = data->conn; + + /* get the user+password information from the needle since it may + * be new for this request even when we reuse conn */ + if(needle->creds) { + /* use the new username and password though */ + Curl_creds_link(&conn->creds, needle->creds); + } + +#ifndef CURL_DISABLE_PROXY + /* use the new proxy username and proxy password though */ + Curl_creds_link(&conn->http_proxy.creds, needle->http_proxy.creds); + Curl_creds_link(&conn->socks_proxy.creds, needle->socks_proxy.creds); +#endif + + /* Finding a connection for reuse in the cpool matches, among other + * things on the "remote-relevant" hostname. This is not necessarily + * the authority of the URL, e.g. conn->origin. For example: + * - we use a proxy (not tunneling). we want to send all requests + * that use the same proxy on this connection. + * - we have a "connect-to" setting that may redirect the hostname of + * a new request to the same remote endpoint of an existing conn. + * We want to reuse an existing conn to the remote endpoint. + * Since connection reuse does not match on conn->origin necessarily, we + * switch conn to needle's host settings. + */ + Curl_peer_link(&conn->origin, needle->origin); + Curl_peer_link(&conn->via_peer, needle->via_peer); + Curl_peer_link(&conn->origin2, needle->origin2); + Curl_peer_link(&conn->via_peer2, needle->via_peer2); +} + +static void conn_meta_freeentry(void *p) +{ + (void)p; + /* Always FALSE. Cannot use a 0 assert here since compilers + * are not in agreement if they then want a NORETURN attribute or + * not. *sigh* */ + DEBUGASSERT(!p); +} + +static CURLcode url_create_needle(struct Curl_easy *data, + struct connectdata **pneedle) +{ + struct connectdata *needle = NULL; + CURLcode result = CURLE_OK; + bool network_scheme = TRUE; /* almost all are */ + + /* Allocate a temporary connection data struct (needle) and fill in for + comparison purposes. */ + needle = allocate_conn(data); + if(!needle) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + /* Do the unfailable inits first, before checks that may early return */ + Curl_hash_init(&needle->meta_hash, 23, + Curl_hash_str, curlx_str_key_compare, conn_meta_freeentry); + + /************************************************************* + * Determine `conn->origin` and populate `data->state.up` and + * other URL related properties. + *************************************************************/ + result = url_set_conn_origin_etc(data, needle); + if(result) + goto out; + + DEBUGASSERT(needle->origin); + network_scheme = !(needle->origin->scheme->flags & PROTOPT_NONETWORK); + +#ifdef USE_UNIX_SOCKETS + /************************************************************* + * Set UDS first. It overrides "via_peer" and proxy settings. + *************************************************************/ + if(network_scheme && CURL_EASY_STR(data, STRING_UNIX_SOCKET_PATH)) { + result = Curl_peer_uds_create( + needle->origin->scheme, CURL_EASY_STR(data, STRING_UNIX_SOCKET_PATH), + (bool)data->set.abstract_unix_socket, &needle->via_peer); + if(result) + goto out; + } +#endif /* USE_UNIX_SOCKETS */ + + if(network_scheme && !needle->via_peer) { + /************************************************************* + * If the `via_peer` is not already set (via UDS above), + * determine if we talk to `conn->origin` directly or use + * `conn->via_peer` using "connect to" and "alt-svc" properties. + *************************************************************/ + result = url_set_conn_peer(data, needle); + if(result) + goto out; + } + + /************************************************************* + * Check whether the host and the "connect to host" are equal. + * Do this after the hostnames have been IDN-converted and + * before initializing the proxy. + *************************************************************/ + if(Curl_peer_equal(needle->origin, needle->via_peer)) { + Curl_peer_unlink(&needle->via_peer); + } + +#ifndef CURL_DISABLE_PROXY + /* Going via a unix socket ignores any proxy settings */ + if(network_scheme && + (!needle->via_peer || !needle->via_peer->unix_socket)) { + result = Curl_proxy_init_conn(data, needle); + if(result) + goto out; + } +#endif /* CURL_DISABLE_PROXY */ + + result = url_set_conn_login(data, needle); /* default credentials */ + if(result) + goto out; + + /************************************************************* + * Setup internals depending on protocol. Needs to be done after + * we figured out what/if proxy to use. + *************************************************************/ + result = setup_connection_internals(data, needle); + if(result) + goto out; + + if(needle->scheme->flags & PROTOPT_ALPN) { + /* The protocol wants it, so set the bits if enabled in the easy handle + (default) */ + if(data->set.ssl_enable_alpn) + needle->bits.tls_enable_alpn = TRUE; + } + + if(network_scheme) { + /* Setup callbacks for network connections */ + needle->recv[FIRSTSOCKET] = Curl_cf_recv; + needle->send[FIRSTSOCKET] = Curl_cf_send; + needle->recv[SECONDARYSOCKET] = Curl_cf_recv; + needle->send[SECONDARYSOCKET] = Curl_cf_send; + needle->bits.tcp_fastopen = data->set.tcp_fastopen; +#ifdef USE_UNIX_SOCKETS + if(Curl_conn_get_first_peer(needle, FIRSTSOCKET)->unix_socket) + needle->transport_wanted = TRNSPRT_UNIX; +#endif + } + +out: + if(!result) { + DEBUGASSERT(needle); + DEBUGASSERT(needle->origin); + *pneedle = needle; + } + else { + *pneedle = NULL; + if(needle) + Curl_conn_free(data, needle); + } + return result; +} + +static CURLcode url_set_data_origin_and_creds(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + CURLU *uh; + CURLUcode uc; + bool use_set_uh = (data->set.uh && !data->state.this_is_a_follow); + uint16_t port_override = data->state.allow_port ? data->set.use_port : 0; + uint32_t scope_id = 0; + + /************************************************************* + * Check input data + *************************************************************/ + if(!Curl_bufref_ptr(&data->state.url)) { + result = CURLE_URL_MALFORMAT; + goto out; + } + + up_free(data); /* cleanup previous leftovers first */ + + /* parse the URL */ + if(use_set_uh) + uh = data->state.uh = curl_url_dup(data->set.uh); + else + uh = data->state.uh = curl_url(); + if(!uh) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + /* Calculate the *real* URL this transfer uses, applying defaults + * where information is missing. */ + if(CURL_EASY_STR(data, STRING_DEFAULT_PROTOCOL) && + !Curl_is_absolute_url(Curl_bufref_ptr(&data->state.url), NULL, 0, TRUE)) { + char *url = curl_maprintf("%s://%s", + CURL_EASY_STR(data, STRING_DEFAULT_PROTOCOL), + Curl_bufref_ptr(&data->state.url)); + if(!url) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + Curl_bufref_set(&data->state.url, url, 0, curl_free); + } + + if(!use_set_uh) { + char *newurl; + uc = curl_url_set(uh, CURLUPART_URL, Curl_bufref_ptr(&data->state.url), + (unsigned int)(CURLU_GUESS_SCHEME | + CURLU_NON_SUPPORT_SCHEME | + (data->set.disallow_username_in_url ? + CURLU_DISALLOW_USER : 0) | + (data->set.path_as_is ? CURLU_PATH_AS_IS : 0))); + if(uc) { + failf(data, "URL rejected: %s", curl_url_strerror(uc)); + result = Curl_uc_to_curlcode(uc); + goto out; + } + + /* after it was parsed, get the generated normalized version */ + uc = curl_url_get(uh, CURLUPART_URL, &newurl, CURLU_GET_EMPTY); + if(uc) { + result = Curl_uc_to_curlcode(uc); + goto out; + } + Curl_bufref_set(&data->state.url, newurl, 0, curl_free); + } + +#ifdef USE_IPV6 + scope_id = data->set.scope_id; +#endif + + /* `uh` is now as the connection should use it, probably. */ + result = Curl_peer_from_url(uh, data, port_override, scope_id, + &data->state.origin); + if(result) + goto out; + /* The origin might get changed when HSTS applies */ + result = hsts_upgrade(data, uh, port_override, scope_id); + if(result) + goto out; + + /* When the transfers initial_origin is not set, this is the initial + * request. Remember this starting point. */ + if(!data->state.initial_origin) + Curl_peer_link(&data->state.initial_origin, data->state.origin); + + uc = curl_url_get(uh, CURLUPART_PATH, &data->state.up.path, CURLU_URLENCODE); + if(uc) { + result = Curl_uc_to_curlcode(uc); + goto out; + } + uc = curl_url_get(uh, CURLUPART_QUERY, &data->state.up.query, + CURLU_GET_EMPTY); + if(uc && (uc != CURLUE_NO_QUERY)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + uc = curl_url_get(uh, CURLUPART_OPTIONS, &data->state.up.options, + CURLU_URLDECODE); + if(uc && (uc != CURLUE_NO_OPTIONS)) { + result = Curl_uc_to_curlcode(uc); + goto out; + } + + result = url_set_data_creds(data, uh); + if(result) + goto out; + +out: + return result; +} + +/** + * Find an existing connection for the transfer or create a new one. + * Returns + * - CURLE_OK on success with a connection attached to data + * - CURLE_NO_CONNECTION_AVAILABLE when connection limits apply or when + * a suitable connection has not determined its multiplex capability. + * - a fatal error + */ +static CURLcode url_find_or_create_conn(struct Curl_easy *data) +{ + struct connectdata *needle = NULL; + bool waitpipe = FALSE; + CURLcode result; + + /* create the template connection for transfer data. Use this needle to + * find an existing connection or, if none exists, convert needle + * to a full connection and attach it to data. */ + result = url_create_needle(data, &needle); + if(result) + goto out; + DEBUGASSERT(needle); + + /*********************************************************************** + * file: is a special case in that it does not need a network connection + ***********************************************************************/ +#ifndef CURL_DISABLE_FILE + if(needle->scheme->flags & PROTOPT_NONETWORK) { + bool done; + /* this is supposed to be the connect function so we better at least check + that the file is present here! */ + DEBUGASSERT(needle->scheme->run->connect_it); + data->info.conn_scheme = needle->scheme->name; + /* conn_protocol can only provide "old" protocols */ + data->info.conn_protocol = needle->scheme->protocol & CURLPROTO_MASK; + result = needle->scheme->run->connect_it(data, &done); + if(result) + goto out; + + /* Setup a "faked" transfer that will do nothing */ + result = Curl_cpool_add(data, needle); + Curl_attach_connection(data, needle, TRUE); + needle = NULL; + if(!result) { + /* Setup whatever necessary for a resumed transfer */ + result = setup_range(data); + if(!result) { + Curl_xfer_setup_nop(data); + result = Curl_init_transfer(data, data->conn); + } + } + + if(result) { + DEBUGASSERT(data->conn->scheme->run->done); + /* we ignore the return code for the protocol-specific DONE */ + (void)data->conn->scheme->run->done(data, result, FALSE); + } + goto out; + } +#endif + + /* Complete the easy's SSL configuration for connection cache matching */ + result = Curl_ssl_easy_config_complete(data, needle->origin); + if(result) + goto out; + + /************************************************************* + * Reuse of existing connection is not allowed when + * - connect_only is set or + * - reuse_fresh is set and this is not a follow-up request + * (like with HTTP followlocation) + *************************************************************/ + if((!data->set.reuse_fresh || data->state.followlocation) && + !data->set.connect_only) { + /* Ok, try to find and attach an existing one */ + url_attach_existing(data, needle, &waitpipe); + } + + if(data->conn) { + /* We attached an existing connection for this transfer. Copy + * over transfer specific properties over from needle. */ + struct connectdata *conn = data->conn; + VERBOSE(bool tls_upgraded = (!(needle->given->flags & PROTOPT_SSL) && + Curl_conn_is_ssl(conn, FIRSTSOCKET))); + + conn->bits.reuse = TRUE; + url_conn_reuse_adjust(data, needle); + +#ifndef CURL_DISABLE_PROXY + infof(data, "Reusing existing %s: connection%s with %s %s", + conn->given->name, + tls_upgraded ? " (upgraded to SSL)" : "", + (conn->socks_proxy.peer || conn->http_proxy.peer) ? "proxy" : "host", + conn->socks_proxy.peer ? conn->socks_proxy.peer->user_hostname : + conn->http_proxy.peer ? conn->http_proxy.peer->user_hostname : + conn->origin->hostname); +#else + infof(data, "Reusing existing %s: connection%s with host %s", + conn->given->name, + tls_upgraded ? " (upgraded to SSL)" : "", + conn->origin->hostname); +#endif + } + else { + /* We have decided that we want a new connection. We may not be able to do + that if we have reached the limit of how many connections we are + allowed to open. */ + + if(waitpipe) { + /* There is a connection that *might* become usable for multiplexing + "soon", and we wait for that */ + infof(data, "Waiting on connection to negotiate possible multiplexing."); + result = CURLE_NO_CONNECTION_AVAILABLE; + goto out; + } + else { + switch(Curl_cpool_check_limits(data, needle, &needle->created)) { + case CPOOL_LIMIT_DEST: + infof(data, "No more connections allowed to host"); + result = CURLE_NO_CONNECTION_AVAILABLE; + goto out; + case CPOOL_LIMIT_TOTAL: + if(data->master_mid != UINT32_MAX) + CURL_TRC_M(data, "Allowing sub-requests (like DoH) to override " + "max connection limit"); + else { + infof(data, "No connections available, total of %zu reached.", + data->multi->max_total_connections); + result = CURLE_NO_CONNECTION_AVAILABLE; + goto out; + } + break; + default: + break; + } + } + + /* Convert needle into a full connection by filling in all the + * remaining parts like the cloned SSL configuration. */ + result = Curl_ssl_conn_config_init(data, needle); + if(result) { + DEBUGF(curl_mfprintf(stderr, "Error: init connection SSL config\n")); + goto out; + } + + /* Add needle to conn pool, which assigns the connection id. + * Attach regardless of result, for correct handling. */ + result = Curl_cpool_add(data, needle); + Curl_attach_connection(data, needle, TRUE); + needle = NULL; + if(result) + goto out; + +#ifdef USE_NTLM + /* If NTLM is requested in a part of this connection, make sure we do not + assume the state is fine as this is a fresh connection and NTLM is + connection based. */ + if((data->state.authhost.picked & CURLAUTH_NTLM) && + data->state.authhost.done) { + infof(data, "NTLM picked AND auth done set, clear picked"); + data->state.authhost.picked = CURLAUTH_NONE; + data->state.authhost.done = FALSE; + } + + if((data->state.authproxy.picked & CURLAUTH_NTLM) && + data->state.authproxy.done) { + infof(data, "NTLM-proxy picked AND auth done set, clear picked"); + data->state.authproxy.picked = CURLAUTH_NONE; + data->state.authproxy.done = FALSE; + } +#endif + } + + /* Setup and init stuff before DO starts, in preparing for the transfer. */ + result = Curl_init_transfer(data, data->conn); + if(result) + goto out; + + /* Setup whatever necessary for a resumed transfer */ + result = setup_range(data); + if(result) + goto out; + + /* persist the scheme and handler the transfer is using */ + data->info.conn_scheme = data->conn->scheme->name; + /* conn_protocol can only provide "old" protocols */ + data->info.conn_protocol = data->conn->scheme->protocol & CURLPROTO_MASK; + data->info.used_proxy = +#ifdef CURL_DISABLE_PROXY + 0 +#else + (data->conn->socks_proxy.peer || data->conn->http_proxy.peer) +#endif + ; + + /* Lastly, inform connection filters that a new transfer is attached */ + result = Curl_conn_ev_data_setup(data); + +out: + if(needle) + Curl_conn_free(data, needle); + DEBUGASSERT(result || data->conn); + return result; +} + +CURLcode Curl_connect(struct Curl_easy *data, bool *pconnected) +{ + CURLcode result; + struct connectdata *conn = NULL; + + *pconnected = FALSE; + + /* Set the request to virgin state based on transfer settings */ + Curl_req_hard_reset(&data->req, data); + /* Determine the origin of the transfer and what credentials to use */ + result = url_set_data_origin_and_creds(data); + if(result) + goto out; + if(!data->state.origin) { /* just make really sure */ + DEBUGASSERT(0); + result = CURLE_FAILED_INIT; + goto out; + } + + /* Get or create a connection for the transfer. */ + result = url_find_or_create_conn(data); + conn = data->conn; + if(result) + goto out; + if(!data->conn) { /* just make really sure */ + DEBUGASSERT(0); + result = CURLE_FAILED_INIT; + goto out; + } + + Curl_pgrsTime(data, TIMER_POSTQUEUE); + if(conn->bits.reuse) { + if(conn->attached_xfers > 1) + /* multiplexed */ + *pconnected = TRUE; + } + else if(conn->scheme->flags & PROTOPT_NONETWORK) { + Curl_pgrsTime(data, TIMER_NAMELOOKUP); + *pconnected = TRUE; + } + else { + result = Curl_conn_setup(data, conn, FIRSTSOCKET, CURL_CF_SSL_DEFAULT); + if(!result) + result = Curl_headers_init(data); + CURL_TRC_M(data, "Curl_conn_setup() -> %d", (int)result); + } + +out: + if(result == CURLE_NO_CONNECTION_AVAILABLE) + DEBUGASSERT(!conn); + + if(result && conn) { + /* We are not allowed to return failure with memory left allocated in the + connectdata struct, free those here */ + Curl_detach_connection(data); + Curl_conn_close(data, conn, TRUE); + } + + return result; +} + +/* + * Curl_init_transfer() is called each time before the transfer starts - to + * prepare for a transfer, sometimes multiple times on the same Curl_easy. + * Make sure nothing in here depends on stuff that is setup dynamically for + * the transfer. + * + * Allow this function to get called with 'conn' set to NULL. + */ + +CURLcode Curl_init_transfer(struct Curl_easy *data, struct connectdata *conn) +{ + CURLcode result; + + if(conn) { + conn->bits.do_more = FALSE; /* by default there is no curl_do_more() to + use */ + /* if the protocol used does not support wildcards, switch it off */ + if(data->state.wildcardmatch && + !(conn->scheme->flags & PROTOPT_WILDCARD)) + data->state.wildcardmatch = FALSE; + } + + data->state.done = FALSE; /* *_done() is not called yet */ + + data->req.no_body = data->set.opt_no_body; + if(data->req.no_body) + /* in HTTP lingo, no body means using the HEAD request... */ + data->state.httpreq = HTTPREQ_HEAD; + + result = Curl_req_start(&data->req, data); + if(!result) { + Curl_pgrsReset(data); + } + return result; +} + +#if defined(USE_HTTP2) || defined(USE_HTTP3) + +void Curl_data_priority_clear_state(struct Curl_easy *data) +{ + data->state.weight = 0; +} + +#endif /* USE_HTTP2 || USE_HTTP3 */ + +CURLcode Curl_conn_meta_set(struct connectdata *conn, const char *key, + void *meta_data, Curl_meta_dtor *meta_dtor) +{ + if(!Curl_hash_add2(&conn->meta_hash, CURL_UNCONST(key), strlen(key) + 1, + meta_data, meta_dtor)) { + meta_dtor(CURL_UNCONST(key), strlen(key) + 1, meta_data); + return CURLE_OUT_OF_MEMORY; + } + return CURLE_OK; +} + +void Curl_conn_meta_remove(struct connectdata *conn, const char *key) +{ + Curl_hash_delete(&conn->meta_hash, CURL_UNCONST(key), strlen(key) + 1); +} + +void *Curl_conn_meta_get(struct connectdata *conn, const char *key) +{ + return Curl_hash_pick(&conn->meta_hash, CURL_UNCONST(key), strlen(key) + 1); +} + +struct Curl_easy *Curl_get_admin(struct Curl_easy *data) +{ + struct Curl_easy *admin; + + if(!data->mid) /* already an admin handle */ + admin = data; + else if(data->multi) + admin = data->multi->admin; + else if(data->multi_easy) + admin = data->multi_easy->admin; + else { + DEBUGASSERT(0); /* we do not want this. does it happen? */ + admin = data; + } + if(admin != data) { + admin->set.conn_max_idle_ms = data->set.conn_max_idle_ms; + admin->set.conn_max_age_ms = data->set.conn_max_age_ms; + admin->set.upkeep_interval_ms = data->set.upkeep_interval_ms; + admin->set.timeout = data->set.timeout; + admin->set.server_response_timeout = data->set.server_response_timeout; + admin->set.no_signal = data->set.no_signal; + } + return admin; +} + +CURLcode Curl_1st_fatal(CURLcode r1, CURLcode r2) +{ + if(r1 && (r1 != CURLE_AGAIN)) + return r1; + if(r2 && (r2 != CURLE_AGAIN)) + return r2; + return r1; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/url.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/url.h new file mode 100644 index 0000000000..43ee63cfc5 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/url.h @@ -0,0 +1,98 @@ +#ifndef HEADER_CURL_URL_H +#define HEADER_CURL_URL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* Reject URLs exceeding this length */ +#define MAX_URL_LEN 0xffff + +/* + * Prototypes for library-wide functions + */ + +CURLcode Curl_init_transfer(struct Curl_easy *data, struct connectdata *conn); +CURLcode Curl_open(struct Curl_easy **curl); +void Curl_init_userdefined(struct Curl_easy *data); + +void Curl_freeset(struct Curl_easy *data); +CURLcode Curl_uc_to_curlcode(CURLUcode uc); +CURLcode Curl_close(struct Curl_easy **datap); /* opposite of Curl_open() */ +CURLcode Curl_connect(struct Curl_easy *data, bool *pconnected); +void Curl_conn_free(struct Curl_easy *data, struct connectdata *conn); +CURLcode Curl_parse_login_details(const char *login, const size_t len, + char **userp, char **passwdp, + char **optionsp); + +/* Attach/Clear/Get meta data for an easy handle. Needs to provide + * a destructor, will be automatically called when the easy handle + * is reset or closed. */ +typedef void Curl_meta_dtor(void *key, size_t key_len, void *meta_data); + +/* Set the transfer meta data for the key. Any existing entry for that + * key will be destroyed. + * Takes ownership of `meta_data` and destroys it when the call fails. */ +CURLcode Curl_meta_set(struct Curl_easy *data, const char *key, + void *meta_data, Curl_meta_dtor *meta_dtor); +void Curl_meta_remove(struct Curl_easy *data, const char *key); +void *Curl_meta_get(struct Curl_easy *data, const char *key); +void Curl_meta_reset(struct Curl_easy *data); + +/* Set connection meta data for the key. Any existing entry for that + * key will be destroyed. + * Takes ownership of `meta_data` and destroys it when the call fails. */ +CURLcode Curl_conn_meta_set(struct connectdata *conn, const char *key, + void *meta_data, Curl_meta_dtor *meta_dtor); +void Curl_conn_meta_remove(struct connectdata *conn, const char *key); +void *Curl_conn_meta_get(struct connectdata *conn, const char *key); + +/* Get an admin handle for internal operations from the given + * easy handle, if possible. The admin handle inherits certain + * properties from `data`. If no admin handle is available (not multi + * or share attached), the easy handle itself is returned. */ +struct Curl_easy *Curl_get_admin(struct Curl_easy *data); + +#define CURL_DEFAULT_PROXY_PORT 1080 /* default proxy port unless specified */ +#define CURL_DEFAULT_HTTPS_PROXY_PORT 443 /* default https proxy port unless + specified */ + +/* Always eval all arguments, return the first + * result != (CURLE_OK | CURLE_AGAIN) or `r1`. */ +CURLcode Curl_1st_fatal(CURLcode r1, CURLcode r2); + +#if defined(USE_HTTP2) || defined(USE_HTTP3) +void Curl_data_priority_clear_state(struct Curl_easy *data); +#else +#define Curl_data_priority_clear_state(x) +#endif /* USE_HTTP2 || USE_HTTP3 */ + +#ifdef USE_NGHTTP2 +CURLcode Curl_data_priority_add_child(struct Curl_easy *parent, + struct Curl_easy *child, + bool exclusive); +#else +#define Curl_data_priority_add_child(x, y, z) CURLE_NOT_BUILT_IN +#endif + +#endif /* HEADER_CURL_URL_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/urlapi-int.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/urlapi-int.h new file mode 100644 index 0000000000..cf1fe6e7cc --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/urlapi-int.h @@ -0,0 +1,70 @@ +#ifndef HEADER_CURL_URLAPI_INT_H +#define HEADER_CURL_URLAPI_INT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include <curl/urlapi.h> + +/* Internal representation of CURLU. Point to URL-encoded strings. */ +struct Curl_URL { + char *scheme; + char *user; + char *password; + char *options; /* IMAP only? */ + char *host; + char *zoneid; /* for numerical IPv6 addresses */ + char *path; + char *query; + char *fragment; + uint16_t portnum; /* the numerical port if present */ + BIT(port_present); /* to support missing port */ + BIT(query_present); /* to support blank */ + BIT(fragment_present); /* to support blank */ + BIT(guessed_scheme); /* when a URL without scheme is parsed */ +}; + +#define HOST_ERROR (-1) /* out of memory */ +#define HOST_NAME 1 +#define HOST_IPV4 2 +#define HOST_IPV6 3 + +#define QUERY_NO 2 +#define QUERY_NOT_YET 3 /* allow to change to query */ +#define QUERY_YES 4 + +size_t Curl_is_absolute_url(const char *url, char *buf, size_t buflen, + bool guess_scheme); + +CURLUcode Curl_url_set_authority(CURLU *u, const char *authority); + +CURLUcode Curl_junkscan(const char *url, size_t *urllen, bool allowspace); + +#define U_CURLU_URLDECODE (unsigned int)CURLU_URLDECODE +#define U_CURLU_PATH_AS_IS (unsigned int)CURLU_PATH_AS_IS + +bool Curl_url_same_origin(CURLU *base, CURLU *href); + +CURLUcode Curl_url_get_port(CURLU *u, uint16_t *pport); + +#endif /* HEADER_CURL_URLAPI_INT_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/urlapi.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/urlapi.c new file mode 100644 index 0000000000..734efbc35e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/urlapi.c @@ -0,0 +1,2173 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "urlapi-int.h" +#include "strcase.h" +#include "url.h" +#include "escape.h" +#include "curlx/inet_pton.h" +#include "curlx/inet_ntop.h" +#include "curlx/strdup.h" +#include "idn.h" +#include "curlx/strparse.h" +#include "curl_memrchr.h" + +#ifdef _WIN32 +/* MS-DOS/Windows style drive prefix, eg c: in c:foo */ +#define STARTS_WITH_DRIVE_PREFIX(str) \ + ((('a' <= (str)[0] && (str)[0] <= 'z') || \ + ('A' <= (str)[0] && (str)[0] <= 'Z')) && \ + ((str)[1] == ':')) +#endif + +/* MS-DOS/Windows style drive prefix, optionally with + * a '|' instead of ':', followed by a slash or NUL */ +#define STARTS_WITH_URL_DRIVE_PREFIX(str) \ + ((('a' <= (str)[0] && (str)[0] <= 'z') || \ + ('A' <= (str)[0] && (str)[0] <= 'Z')) && \ + ((str)[1] == ':' || (str)[1] == '|') && \ + ((str)[2] == '/' || (str)[2] == '\\' || (str)[2] == 0)) + +/* scheme is not URL encoded, the longest libcurl supported ones are... */ +#define MAX_SCHEME_LEN 40 +#define MAX_ZONEID_LEN 16 + +/* characters not allowed in hostnames */ +#define HOSTNAME_INVALID_CHARS " \r\n\t/:#?!@{}[]\\$\'\"^`*<>=;,+&()%|" + +/* + * If USE_IPV6 is disabled, we still want to parse IPv6 addresses, so make + * sure we have _some_ value for AF_INET6 without polluting our fake value + * everywhere. + */ +#if !defined(USE_IPV6) && !defined(AF_INET6) +#define AF_INET6 (AF_INET + 1) +#endif + +#define DEFAULT_SCHEME "https" + +static void free_urlhandle(struct Curl_URL *u) +{ + curlx_free(u->scheme); + curlx_free(u->user); + curlx_strzero(u->password); + curlx_free(u->password); + curlx_free(u->options); + curlx_free(u->host); + curlx_free(u->zoneid); + curlx_free(u->path); + curlx_free(u->query); + curlx_free(u->fragment); +} + +/* + * Find the separator at the end of the hostname, or the '?' in cases like + * http://www.example.com?id=2380 + */ +static const char *find_host_sep(const char *url) +{ + /* Find the start of the hostname */ + const char *sep = strstr(url, "//"); + if(!sep) + sep = url; + else + sep += 2; + + /* Find first / or ? */ + while(*sep && *sep != '/' && *sep != '?') + sep++; + + return sep; +} + +/* convert CURLcode to CURLUcode */ +#define cc2cu(x) \ + ((x) == CURLE_TOO_LARGE ? CURLUE_TOO_LARGE : CURLUE_OUT_OF_MEMORY) + +/* urlencode_str() writes data into an output dynbuf and URL-encodes the + * spaces in the source URL accordingly. + * + * This function re-encodes the string, meaning that it leaves already encoded + * bytes as-is and works by encoding only what *has* to be encoded - unless it + * has to uppercase the hex to normalize. + * + * Illegal percent-encoding sequences are left as-is. + * + * URL encoding should be skipped for hostnames, otherwise IDN resolution + * will fail. + * + * 'query' tells if it is a query part or not, or if it is allowed to + * "transition" into a query part with a question mark. + * + * @unittest 1675 + */ +UNITTEST CURLUcode urlencode_str(struct dynbuf *o, const char *url, + size_t len, bool relative, + unsigned int query); +UNITTEST CURLUcode urlencode_str(struct dynbuf *o, const char *url, + size_t len, bool relative, + unsigned int query) +{ + /* we must add this with whitespace-replacing */ + const unsigned char *iptr; + const unsigned char *host_sep = (const unsigned char *)url; + CURLcode result = CURLE_OK; + + DEBUGASSERT((query >= QUERY_NO) && (query <= QUERY_YES)); + + if(!relative) { + size_t n; + host_sep = (const unsigned char *)find_host_sep(url); + + /* output the first piece as-is */ + n = (const char *)host_sep - url; + result = curlx_dyn_addn(o, url, n); + len -= n; + } + + for(iptr = host_sep; len && !result; iptr++, len--) { + if(*iptr == ' ') { + if(query != QUERY_YES) + result = curlx_dyn_addn(o, "%20", 3); + else + result = curlx_dyn_addn(o, "+", 1); + } + else if((*iptr < ' ') || (*iptr >= 0x7f)) { + unsigned char out[3] = { '%' }; + Curl_hexbyte(&out[1], *iptr); + result = curlx_dyn_addn(o, out, 3); + } + else if(*iptr == '%' && (len >= 3) && + ISXDIGIT(iptr[1]) && ISXDIGIT(iptr[2]) && + (ISLOWER(iptr[1]) || ISLOWER(iptr[2]))) { + /* uppercase it */ + unsigned char hex = (unsigned char)((curlx_hexval(iptr[1]) << 4) | + curlx_hexval(iptr[2])); + unsigned char out[3] = { '%' }; + Curl_hexbyte(&out[1], hex); + result = curlx_dyn_addn(o, out, 3); + iptr += 2; + len -= 2; + } + else { + result = curlx_dyn_addn(o, iptr, 1); + if(*iptr == '?' && (query == QUERY_NOT_YET)) + query = QUERY_YES; + } + } + + if(result) + return cc2cu(result); + return CURLUE_OK; +} + +/* + * Returns the length of the scheme if the given URL is absolute (as opposed + * to relative). Stores the scheme in the buffer if TRUE and 'buf' is + * non-NULL. The buflen must be larger than MAX_SCHEME_LEN if buf is set. + * + * If 'guess_scheme' is TRUE, it means the URL might be provided without + * scheme. + */ +size_t Curl_is_absolute_url(const char *url, char *buf, size_t buflen, + bool guess_scheme) +{ + size_t i = 0; + DEBUGASSERT(!buf || (buflen > MAX_SCHEME_LEN)); + (void)buflen; /* only used in debug-builds */ + if(buf) + buf[0] = 0; /* always leave a defined value in buf */ +#ifdef _WIN32 + if(guess_scheme && STARTS_WITH_DRIVE_PREFIX(url)) + return 0; +#endif + if(ISALPHA(url[0])) + for(i = 1; i < MAX_SCHEME_LEN; ++i) { + char s = url[i]; + if(s && (ISALNUM(s) || (s == '+') || (s == '-') || (s == '.'))) { + /* RFC 3986 3.1 explains: + scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + */ + } + else { + break; + } + } + if(i && (url[i] == ':') && ((url[i + 1] == '/') || !guess_scheme)) { + /* If this does not guess scheme, the scheme always ends with the colon so + that this also detects data: URLs etc. In guessing mode, data: could + be the hostname "data" with a specified port number. */ + + /* the length of the scheme is the name part only */ + size_t len = i; + if(buf) { + Curl_strntolower(buf, url, i); + buf[i] = 0; + } + return len; + } + return 0; +} + +/* scan for byte values <= 31, 127 and sometimes space */ +CURLUcode Curl_junkscan(const char *url, size_t *urllen, bool allowspace) +{ + size_t n = strlen(url); + size_t i; + unsigned char control; + const unsigned char *p = (const unsigned char *)url; + if(n > CURL_MAX_INPUT_LENGTH) + return CURLUE_MALFORMED_INPUT; + + control = allowspace ? 0x1f : 0x20; + for(i = 0; i < n; i++) { + if(p[i] <= control || p[i] == 127) + return CURLUE_MALFORMED_INPUT; + } + *urllen = n; + return CURLUE_OK; +} + +/* + * parse_hostname_login() + * + * Parse the login details (username, password and options) from the URL and + * strip them out of the hostname + * + * @unittest 1675 + */ +UNITTEST CURLUcode parse_hostname_login(struct Curl_URL *u, + const char *login, + size_t len, + unsigned int flags, + size_t *hostname_offset); +UNITTEST CURLUcode parse_hostname_login(struct Curl_URL *u, + const char *login, + size_t len, + unsigned int flags, + size_t *hostname_offset) +{ + CURLUcode ures = CURLUE_OK; + CURLcode result; + char *userp = NULL; + char *passwdp = NULL; + char *optionsp = NULL; + const struct Curl_scheme *h = NULL; + + /* At this point, we assume all the other special cases have been taken + * care of, so the host is at most + * + * [user[:password][;options]]@]hostname + * + * We need somewhere to put the embedded details, so do that first. + */ + const char *ptr; + + DEBUGASSERT(login); + + *hostname_offset = 0; + ptr = memchr(login, '@', len); + if(!ptr) + goto out; + + /* We will now try to extract the + * possible login information in a string like: + * ftp://user:password@ftp.site.example:8021/README */ + ptr++; + + /* if this is a known scheme, get some details */ + if(u->scheme) + h = Curl_get_scheme(u->scheme); + + /* We could use the login information in the URL so extract it. Only parse + options if the handler says we should. Note that 'h' might be NULL! */ + result = Curl_parse_login_details(login, ptr - login - 1, + &userp, &passwdp, + (h && (h->flags & PROTOPT_URLOPTIONS)) ? + &optionsp : NULL); + if(result) { + /* the only possible error from Curl_parse_login_details is out of + memory: */ + ures = CURLUE_OUT_OF_MEMORY; + goto out; + } + + if(userp) { + if(flags & CURLU_DISALLOW_USER) { + /* Option DISALLOW_USER is set and URL contains username. */ + ures = CURLUE_USER_NOT_ALLOWED; + goto out; + } + curlx_free(u->user); + u->user = userp; + } + + if(passwdp) { + curlx_strzero(u->password); + curlx_free(u->password); + u->password = passwdp; + } + + if(optionsp) { + curlx_free(u->options); + u->options = optionsp; + } + + /* the hostname starts at this offset */ + *hostname_offset = ptr - login; + return CURLUE_OK; + +out: + + curlx_free(userp); + curlx_strzero(passwdp); + curlx_free(passwdp); + curlx_free(optionsp); + curlx_safefree(u->user); + curlx_strzero(u->password); + curlx_safefree(u->password); + curlx_safefree(u->options); + + return ures; +} + +/* @unittest 1653 */ +UNITTEST CURLUcode parse_port(struct Curl_URL *u, struct dynbuf *host, + bool has_scheme); +UNITTEST CURLUcode parse_port(struct Curl_URL *u, struct dynbuf *host, + bool has_scheme) +{ + const char *portptr; + const char *hostname = curlx_dyn_ptr(host); + /* + * Find the end of an IPv6 address on the ']' ending bracket. + */ + u->portnum = 0; + u->port_present = FALSE; + if(hostname[0] == '[') { + portptr = strchr(hostname, ']'); + if(!portptr) + return CURLUE_BAD_IPV6; + portptr++; + /* this is a RFC2732-style specified IP-address */ + if(*portptr) { + if(*portptr != ':') + return CURLUE_BAD_PORT_NUMBER; + } + else + portptr = NULL; + } + else + portptr = strchr(hostname, ':'); + + if(portptr) { + curl_off_t port; + size_t keep = portptr - hostname; + int rc; + + /* Browser behavior adaptation. If there is a colon with no digits after, + cut off the name there which makes us ignore the colon and use the + default port. Firefox, Chrome and Safari all do that. + + Do not do it if the URL has no scheme, to make something that looks like + a scheme not work! */ + curlx_dyn_setlen(host, keep); + portptr++; + if(!*portptr) + return has_scheme ? CURLUE_OK : CURLUE_BAD_PORT_NUMBER; + if(*portptr == '\\') + return CURLUE_BACKSLASH; + rc = curlx_str_number(&portptr, &port, 0xffff); + if(rc) + return CURLUE_BAD_PORT_NUMBER; + else if(*portptr == '\\') + return CURLUE_BACKSLASH; + else if(*portptr) + return CURLUE_BAD_PORT_NUMBER; + + u->portnum = (uint16_t)port; + u->port_present = TRUE; + } + + return CURLUE_OK; +} + +/* This function assumes 'hostname' now starts with [. It trims 'hostname' in + * place and it sets u->zoneid if present. + * + * @unittest 1675 + */ +UNITTEST CURLUcode ipv6_parse(struct Curl_URL *u, char *hostname, + size_t hlen); +UNITTEST CURLUcode ipv6_parse(struct Curl_URL *u, char *hostname, + size_t hlen) /* length of hostname */ +{ + size_t len; + DEBUGASSERT(*hostname == '['); + if(hlen < 4) /* '[::]' is the shortest possible valid string */ + return CURLUE_BAD_IPV6; + hostname++; + hlen -= 2; + + /* only valid IPv6 letters are ok */ + len = strspn(hostname, "0123456789abcdefABCDEF:."); + + if(hlen != len) { + hlen = len; + if(hostname[len] == '%') { + /* this could now be '%[zone id]' */ + char zoneid[MAX_ZONEID_LEN]; + int i = 0; + char *h = &hostname[len + 1]; + /* pass '25' if present and is a URL encoded percent sign */ + if(!strncmp(h, "25", 2) && h[2] && (h[2] != ']')) + h += 2; + while(*h && (*h != ']') && (i < (MAX_ZONEID_LEN - 1))) + zoneid[i++] = *h++; + if(!i || (']' != *h)) + return CURLUE_BAD_IPV6; + zoneid[i] = 0; + u->zoneid = curlx_strdup(zoneid); + if(!u->zoneid) + return CURLUE_OUT_OF_MEMORY; + hostname[len] = ']'; /* insert end bracket */ + hostname[len + 1] = 0; /* terminate the hostname */ + } + else + return CURLUE_BAD_IPV6; + /* hostname is fine */ + } + + /* Normalize the IPv6 address */ + { + char dest[16]; /* fits a binary IPv6 address */ + hostname[hlen] = 0; /* end the address there */ + if(curlx_inet_pton(AF_INET6, hostname, dest) != 1) + return CURLUE_BAD_IPV6; + if(!curlx_inet_ntop(AF_INET6, dest, hostname, hlen + 1)) { + hlen = strlen(hostname); /* might be shorter now */ + hostname[hlen + 1] = 0; + } + hostname[hlen] = ']'; /* restore ending bracket */ + } + return CURLUE_OK; +} + +static CURLUcode hostname_check(struct Curl_URL *u, char *hostname, + size_t hlen) /* length of hostname */ +{ + size_t len; + DEBUGASSERT(hostname); + + if(!hlen) + return CURLUE_NO_HOST; + else if(hostname[0] == '[') + return ipv6_parse(u, hostname, hlen); + else { + /* letters from the second string are not ok */ + len = strcspn(hostname, HOSTNAME_INVALID_CHARS); + if(hlen != len) + /* hostname with bad content */ + return CURLUE_BAD_HOSTNAME; + else if((hlen >= 2) && + (hostname[hlen - 1] == '.') && (hostname[hlen - 2] == '.')) + /* more than one trailing dot is not allowed */ + return CURLUE_BAD_HOSTNAME; + else if((hlen == 1) && (hostname[0] == '.')) + /* a single dot alone is not allowed */ + return CURLUE_BAD_HOSTNAME; + } + return CURLUE_OK; +} + +/* + * Handle partial IPv4 numerical addresses and different bases, like + * '16843009', '0x7f', '0x7f.1' '0177.1.1.1' etc. + * + * If the given input string is syntactically wrong IPv4 or any part for + * example is too big, this function returns HOST_NAME. + * + * Output the "normalized" version of that input string in plain quad decimal + * integers. + * + * A single dot following the numerical address is accepted and "swallowed" as + * if it was never there. + * + * Returns the host type. + * + * @unittest 1675 + */ +UNITTEST int ipv4_normalize(struct dynbuf *host); +UNITTEST int ipv4_normalize(struct dynbuf *host) +{ + bool done = FALSE; + int n = 0; + const char *c = curlx_dyn_ptr(host); + unsigned int parts[4] = { 0, 0, 0, 0 }; + CURLcode result = CURLE_OK; + + if(*c == '[') + return HOST_IPV6; + + while(!done) { + int rc; + curl_off_t l; + if(*c == '0') { + if(Curl_raw_tolower(c[1]) == 'x') { + c += 2; /* skip the prefix */ + rc = curlx_str_hex(&c, &l, UINT_MAX); + if(rc) + return HOST_NAME; + } + else + rc = curlx_str_octal(&c, &l, UINT_MAX); + } + else + rc = curlx_str_number(&c, &l, UINT_MAX); + + if(rc) { + if(!n || (rc != STRE_NO_NUM) || *c) + return HOST_NAME; + n--; + } + else + parts[n] = (unsigned int)l; + + switch(*c) { + case '.': + if(n == 3) { + if(c[1]) + /* something follows this dot */ + return HOST_NAME; + done = TRUE; + } + else { + n++; + c++; + } + break; + + case '\0': + done = TRUE; + break; + + default: + return HOST_NAME; + } + } + + switch(n) { + case 0: /* a -- 32 bits */ + curlx_dyn_reset(host); + + result = curlx_dyn_addf(host, "%u.%u.%u.%u", + (parts[0] >> 24), + ((parts[0] >> 16) & 0xff), + ((parts[0] >> 8) & 0xff), + (parts[0] & 0xff)); + break; + case 1: /* a.b -- 8.24 bits */ + if((parts[0] > 0xff) || (parts[1] > 0xffffff)) + return HOST_NAME; + curlx_dyn_reset(host); + result = curlx_dyn_addf(host, "%u.%u.%u.%u", + parts[0], + ((parts[1] >> 16) & 0xff), + ((parts[1] >> 8) & 0xff), + (parts[1] & 0xff)); + break; + case 2: /* a.b.c -- 8.8.16 bits */ + if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xffff)) + return HOST_NAME; + curlx_dyn_reset(host); + result = curlx_dyn_addf(host, "%u.%u.%u.%u", + parts[0], + parts[1], + ((parts[2] >> 8) & 0xff), + (parts[2] & 0xff)); + break; + case 3: /* a.b.c.d -- 8.8.8.8 bits */ + if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff) || + (parts[3] > 0xff)) + return HOST_NAME; + curlx_dyn_reset(host); + result = curlx_dyn_addf(host, "%u.%u.%u.%u", + parts[0], + parts[1], + parts[2], + parts[3]); + break; + } + if(result) + return HOST_ERROR; + return HOST_IPV4; +} + +/* if necessary, replace the host content with a URL decoded version */ +static CURLUcode urldecode_host(struct dynbuf *host) +{ + const char *per; + const char *hostname = curlx_dyn_ptr(host); + per = strchr(hostname, '%'); + if(!per) + /* nothing to decode */ + return CURLUE_OK; + else { + /* encoded */ + size_t dlen; + char *decoded; + CURLcode result = Curl_urldecode(hostname, 0, &decoded, &dlen, + REJECT_CTRL); + if(result) + return CURLUE_BAD_HOSTNAME; + curlx_dyn_reset(host); + result = curlx_dyn_addn(host, decoded, dlen); + curlx_free(decoded); + if(result) + return cc2cu(result); + } + + return CURLUE_OK; +} + +static CURLUcode parse_authority(struct Curl_URL *u, + const char *auth, size_t authlen, + unsigned int flags, + struct dynbuf *host, + bool has_scheme) +{ + size_t offset; + CURLUcode uc; + CURLcode result; + + /* + * Parse the login details and strip them out of the hostname. + */ + uc = parse_hostname_login(u, auth, authlen, flags, &offset); + if(uc) + return uc; + + result = curlx_dyn_addn(host, auth + offset, authlen - offset); + if(result) { + uc = cc2cu(result); + return uc; + } + + uc = parse_port(u, host, has_scheme); + + if(!curlx_dyn_len(host)) + /* this makes no-host errors override port number problems */ + uc = CURLUE_NO_HOST; + if(!uc) + uc = urldecode_host(host); + if(uc) + return uc; + + switch(ipv4_normalize(host)) { + case HOST_IPV4: + break; + case HOST_IPV6: + uc = ipv6_parse(u, curlx_dyn_ptr(host), curlx_dyn_len(host)); + break; + case HOST_NAME: + uc = hostname_check(u, curlx_dyn_ptr(host), curlx_dyn_len(host)); + break; + case HOST_ERROR: + uc = CURLUE_OUT_OF_MEMORY; + break; + default: + uc = CURLUE_BAD_HOSTNAME; /* Bad IPv4 address even */ + break; + } + + return uc; +} + +/* used for HTTP/2 server push */ +CURLUcode Curl_url_set_authority(CURLU *u, const char *authority) +{ + CURLUcode ures; + struct dynbuf host; + + DEBUGASSERT(authority); + curlx_dyn_init(&host, CURL_MAX_INPUT_LENGTH); + + ures = parse_authority(u, authority, strlen(authority), + CURLU_DISALLOW_USER, &host, !!u->scheme); + if(ures) + curlx_dyn_free(&host); + else { + curlx_free(u->host); + u->host = curlx_dyn_ptr(&host); + } + return ures; +} + +/* + * "Remove Dot Segments" + * https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 + */ + +static bool is_dot(const char **str, size_t *clen) +{ + const char *p = *str; + if(*p == '.') { + (*str)++; + (*clen)--; + return TRUE; + } + else if((*clen >= 3) && + (p[0] == '%') && (p[1] == '2') && ((p[2] | 0x20) == 'e')) { + *str += 3; + *clen -= 3; + return TRUE; + } + return FALSE; +} + +#define ISSLASH(x) ((x) == '/') + +/* prescan the string to see if it needs work */ +static bool needs_dedotdot(const char *p, size_t pn) +{ + /* a single byte path cannot be cleaned up */ + if(pn < 2) + return FALSE; + while(pn) { + if(is_dot(&p, &pn)) { + /* "./" or dot before end of string */ + if(!pn || ISSLASH(*p)) + return TRUE; + /* "../" or ".." before end of string */ + else if(is_dot(&p, &pn) && (!pn || ISSLASH(*p))) + return TRUE; + } + else { + p++; + pn--; + } + } + return FALSE; +} + +/* + * dedotdotify() + * + * This function gets a null-terminated path with dot and dotdot sequences + * passed in and strips them off according to the rules in RFC 3986 section + * 5.2.4. + * + * The function handles a path. It should not contain the query nor fragment. + * + * RETURNS + * + * Zero for success and 'out' set to an allocated string (or NULL if there's + * nothing to do). + * + * @unittest 1395 + */ +UNITTEST int dedotdotify(const char *input, size_t clen, char **outp); +UNITTEST int dedotdotify(const char *input, size_t clen, char **outp) +{ + struct dynbuf out; + CURLcode result = CURLE_OK; + + /* variables for leading dot checks */ + const char *dinput = input; + size_t dlen = clen; + + *outp = NULL; + if(!needs_dedotdot(input, clen)) + return 0; + + curlx_dyn_init(&out, clen + 1); + + /* if the input buffer begins with a prefix of "../" or "./", then remove + that prefix from the input buffer; otherwise, */ + if(is_dot(&dinput, &dlen)) { + if(ISSLASH(*dinput)) { + /* one dot followed by a slash */ + input = dinput + 1; + clen = dlen - 1; + } + + /* if the input buffer consists only of "." or "..", then remove + that from the input buffer; otherwise, */ + else if(is_dot(&dinput, &dlen)) { + if(!dlen) + /* .. [end] */ + goto end; + else if(ISSLASH(*dinput)) { + /* ../ */ + input = dinput + 1; + clen = dlen - 1; + } + } + } + + while(clen && !result) { /* until end of path content */ + if(ISSLASH(*input)) { + const char *p = &input[1]; + size_t blen = clen - 1; + /* if the input buffer begins with a prefix of "/./" or "/.", where "." + is a complete path segment, then replace that prefix with "/" in the + input buffer; otherwise, */ + if(is_dot(&p, &blen)) { + if(!blen) { /* /. */ + result = curlx_dyn_addn(&out, "/", 1); + break; + } + else if(ISSLASH(*p)) { /* /./ */ + input = p; + clen = blen; + continue; + } + + /* if the input buffer begins with a prefix of "/../" or "/..", where + ".." is a complete path segment, then replace that prefix with "/" + in the input buffer and remove the last segment and its preceding + "/" (if any) from the output buffer; otherwise, */ + else if(is_dot(&p, &blen) && (ISSLASH(*p) || !blen)) { + /* remove the last segment from the output buffer */ + size_t len = curlx_dyn_len(&out); + if(len) { + const char *ptr = curlx_dyn_ptr(&out); + const char *last = memrchr(ptr, '/', len); + if(last) + /* trim the output at the slash */ + curlx_dyn_setlen(&out, last - ptr); + } + + if(blen) { /* /../ */ + input = p; + clen = blen; + continue; + } + result = curlx_dyn_addn(&out, "/", 1); + break; + } + } + } + + /* move the first path segment in the input buffer to the end of the + output buffer, including the initial "/" character (if any) and any + subsequent characters up to, but not including, the next "/" character + or the end of the input buffer. */ + + result = curlx_dyn_addn(&out, input, 1); + input++; + clen--; + } +end: + if(!result) { + if(curlx_dyn_len(&out)) + *outp = curlx_dyn_ptr(&out); + else { + *outp = curlx_strdup(""); + if(!*outp) + return 1; + } + } + return result ? 1 : 0; /* success */ +} + +/* + * @unittest 1675 + */ +UNITTEST CURLUcode parse_file(const char *url, size_t urllen, CURLU *u, + const char **pathp, size_t *pathlenp); +UNITTEST CURLUcode parse_file(const char *url, size_t urllen, CURLU *u, + const char **pathp, size_t *pathlenp) +{ + const char *path; + size_t pathlen; + + *pathp = NULL; + *pathlenp = 0; + if(urllen <= 6) + /* file:/ is not enough to actually be a complete file: URL */ + return CURLUE_BAD_FILE_URL; + + /* path has been allocated large enough to hold this */ + path = &url[5]; + pathlen = urllen - 5; + + /* RFC 8089: file-hier-part = ( "//" auth-path ) / local-path, where + local-path also starts with a "/". So reject anything that does not + start with at least one "/" */ + if(path[0] != '/') + return CURLUE_BAD_FILE_URL; + + /* Extra handling URLs with an authority component (i.e. that start with + * "file://") + * + * We allow omitted hostname (e.g. file:/<path>) -- valid according to + * RFC 8089, but not the (current) WHAT-WG URL spec. + */ + if(path[1] == '/') { + /* swallow the two slashes */ + const char *ptr = &path[2]; + + /* + * According to RFC 8089, a file: URL can be reliably dereferenced if: + * + * o it has no/blank hostname, or + * + * o the hostname matches "localhost" (case-insensitively), or + * + * o the hostname is a FQDN that resolves to this machine, or + * + * For brevity, we only consider URLs with empty, "localhost", or + * "127.0.0.1" hostnames as local, otherwise as an UNC String. + * + * Additionally, there is an exception for URLs with a Windows drive + * letter in the authority (which was accidentally omitted from RFC 8089 + * Appendix E, but believe me, it was meant to be there. --MK) + */ + if(ptr[0] != '/' && !STARTS_WITH_URL_DRIVE_PREFIX(ptr)) { + /* the URL includes a hostname, it must match "localhost" or + "127.0.0.1" to be valid */ + if(checkprefix("localhost/", ptr) || + checkprefix("127.0.0.1/", ptr)) { + ptr += 9; /* now points to the slash after the host */ + } + else + /* Invalid file://hostname/, expected localhost or 127.0.0.1 or + none */ + return CURLUE_BAD_FILE_URL; + } + + path = ptr; + pathlen = urllen - (ptr - url); + } + +#if !defined(_WIN32) && !defined(MSDOS) && !defined(__CYGWIN__) + /* Do not allow Windows drive letters when not in Windows. + * This catches both "file:/c:" and "file:c:" */ + if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) || + STARTS_WITH_URL_DRIVE_PREFIX(path)) { + /* File drive letters are only accepted in MS-DOS/Windows */ + return CURLUE_BAD_FILE_URL; + } +#else + /* If the path starts with a slash and a drive letter, ditch the slash */ + if('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) { + /* This cannot be done with strcpy, as the memory chunks overlap! */ + path++; + pathlen--; + } +#endif + u->scheme = curlx_strdup("file"); + if(!u->scheme) + return CURLUE_OUT_OF_MEMORY; + + *pathp = path; + *pathlenp = pathlen; + return CURLUE_OK; +} + +static CURLUcode parse_scheme(const char *url, CURLU *u, char *schemebuf, + size_t schemelen, unsigned int flags, + const char **hostpp) +{ + /* clear path */ + const char *schemep = NULL; + + if(schemelen) { + int num_slashes = 0; + const char *p = &url[schemelen + 1]; + if(!Curl_get_scheme(schemebuf) && !(flags & CURLU_NON_SUPPORT_SCHEME)) + return CURLUE_UNSUPPORTED_SCHEME; + + if(!ISSLASH(*p)) + /* less than one */ + return CURLUE_BAD_SLASHES; + if((flags & CURLU_NO_AUTHORITY)) { + while(ISSLASH(*p) && (num_slashes < 2)) { + p++; + num_slashes++; + } + } + else { + while(ISSLASH(*p) && (num_slashes < 4)) { + p++; + num_slashes++; + } + if(num_slashes > 3) + return CURLUE_BAD_SLASHES; + } + + schemep = schemebuf; + *hostpp = p; /* hostname starts here */ + } + else { + /* no scheme! */ + + if(!(flags & (CURLU_DEFAULT_SCHEME | CURLU_GUESS_SCHEME))) + return CURLUE_BAD_SCHEME; + + if(flags & CURLU_DEFAULT_SCHEME) + schemep = DEFAULT_SCHEME; + + /* + * The URL was badly formatted, let's try without scheme specified. + */ + *hostpp = url; + } + + if(schemep) { + u->scheme = curlx_strdup(schemep); + if(!u->scheme) + return CURLUE_OUT_OF_MEMORY; + } + return CURLUE_OK; +} + +static CURLUcode guess_scheme(CURLU *u, struct dynbuf *host) +{ + const char *hostname = curlx_dyn_ptr(host); + const char *schemep = NULL; + /* legacy curl-style guess based on hostname */ + if(checkprefix("ftp.", hostname)) + schemep = "ftp"; + else if(checkprefix("dict.", hostname)) + schemep = "dict"; + else if(checkprefix("ldap.", hostname)) + schemep = "ldap"; + else if(checkprefix("imap.", hostname)) + schemep = "imap"; + else if(checkprefix("smtp.", hostname)) + schemep = "smtp"; + else if(checkprefix("pop3.", hostname)) + schemep = "pop3"; + else + schemep = "http"; + + u->scheme = curlx_strdup(schemep); + if(!u->scheme) + return CURLUE_OUT_OF_MEMORY; + + u->guessed_scheme = TRUE; + return CURLUE_OK; +} + +static CURLUcode handle_fragment(CURLU *u, const char *fragment, + size_t fraglen, unsigned int flags) +{ + CURLUcode ures; + u->fragment_present = TRUE; + if(fraglen > 1) { + /* skip the leading '#' in the copy but include the null-terminator */ + if(flags & CURLU_URLENCODE) { + struct dynbuf enc; + curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + ures = urlencode_str(&enc, fragment + 1, fraglen - 1, TRUE, QUERY_NO); + if(ures) + return ures; + u->fragment = curlx_dyn_ptr(&enc); + } + else { + u->fragment = curlx_memdup0(fragment + 1, fraglen - 1); + if(!u->fragment) + return CURLUE_OUT_OF_MEMORY; + } + } + return CURLUE_OK; +} + +static CURLUcode handle_query(CURLU *u, const char *query, + size_t qlen, unsigned int flags) +{ + u->query_present = TRUE; + if(qlen > 1) { + if(flags & CURLU_URLENCODE) { + struct dynbuf enc; + CURLUcode ures; + curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + /* skip the leading question mark */ + ures = urlencode_str(&enc, query + 1, qlen - 1, TRUE, QUERY_YES); + if(ures) + return ures; + u->query = curlx_dyn_ptr(&enc); + } + else { + u->query = curlx_memdup0(query + 1, qlen - 1); + if(!u->query) + return CURLUE_OUT_OF_MEMORY; + } + } + else { + /* single byte query */ + u->query = curlx_strdup(""); + if(!u->query) + return CURLUE_OUT_OF_MEMORY; + } + return CURLUE_OK; +} + +static CURLUcode handle_path(CURLU *u, const char *path, + size_t pathlen, unsigned int flags, + bool is_file) +{ + CURLUcode ures; + if(pathlen && (flags & CURLU_URLENCODE)) { + struct dynbuf enc; + curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + ures = urlencode_str(&enc, path, pathlen, TRUE, QUERY_NO); + if(ures) + return ures; + pathlen = curlx_dyn_len(&enc); + path = u->path = curlx_dyn_ptr(&enc); + } + + if(pathlen >= (size_t)(1 + !is_file)) { + /* paths for file:// scheme can be one byte, others need to be two */ + if(!u->path) { + u->path = curlx_memdup0(path, pathlen); + if(!u->path) + return CURLUE_OUT_OF_MEMORY; + path = u->path; + } + else if(flags & CURLU_URLENCODE) + /* it might have encoded more than the path so cut it */ + u->path[pathlen] = 0; + + if(!(flags & CURLU_PATH_AS_IS)) { + /* remove ../ and ./ sequences according to RFC3986 */ + char *dedot; + int err = dedotdotify(path, pathlen, &dedot); + if(err) + return CURLUE_OUT_OF_MEMORY; + if(dedot) { + curlx_free(u->path); + u->path = dedot; + } + } + } + return CURLUE_OK; +} + +static CURLUcode parseurl(const char *url, CURLU *u, unsigned int flags) +{ + const char *path; + size_t pathlen; + char schemebuf[MAX_SCHEME_LEN + 1]; + size_t schemelen = 0; + size_t urllen; + CURLUcode ures = CURLUE_OK; + struct dynbuf host; + bool is_file = FALSE; + + DEBUGASSERT(url); + + curlx_dyn_init(&host, CURL_MAX_INPUT_LENGTH); + + ures = Curl_junkscan(url, &urllen, !!(flags & CURLU_ALLOW_SPACE)); + if(ures) + goto fail; + + schemelen = Curl_is_absolute_url(url, schemebuf, sizeof(schemebuf), + flags & (CURLU_GUESS_SCHEME | + CURLU_DEFAULT_SCHEME)); + + /* handle the file: scheme */ + if(schemelen && !strcmp(schemebuf, "file")) { + is_file = TRUE; + ures = parse_file(url, urllen, u, &path, &pathlen); + } + else { + const char *hostp = NULL; + size_t hostlen; + ures = parse_scheme(url, u, schemebuf, schemelen, flags, &hostp); + if(ures) + goto fail; + + /* find the end of the hostname + port number */ + hostlen = strcspn(hostp, "/?#"); + path = &hostp[hostlen]; + + /* this pathlen also contains the query and the fragment */ + pathlen = urllen - (path - url); + if(hostlen) { + ures = parse_authority(u, hostp, hostlen, flags, &host, !!u->scheme); + if(!ures && (flags & CURLU_GUESS_SCHEME) && !u->scheme) + ures = guess_scheme(u, &host); + } + else if(flags & CURLU_NO_AUTHORITY) { + /* allowed to be empty. */ + if(curlx_dyn_add(&host, "")) + ures = CURLUE_OUT_OF_MEMORY; + } + else + ures = CURLUE_NO_HOST; + } + if(!ures) { + /* The path might at this point contain a fragment and/or a query to + handle */ + const char *fragment = strchr(path, '#'); + if(fragment) { + size_t fraglen = pathlen - (fragment - path); + ures = handle_fragment(u, fragment, fraglen, flags); + /* after this, pathlen still contains the query */ + pathlen -= fraglen; + } + } + if(!ures) { + const char *query = memchr(path, '?', pathlen); + if(query) { + size_t qlen = pathlen - (query - path); + ures = handle_query(u, query, qlen, flags); + pathlen -= qlen; + } + } + if(!ures) + /* the fragment and query parts are trimmed off from the path */ + ures = handle_path(u, path, pathlen, flags, is_file); + if(!ures) { + u->host = curlx_dyn_ptr(&host); + return CURLUE_OK; + } +fail: + curlx_dyn_free(&host); + free_urlhandle(u); + return ures; +} + +/* + * Parse the URL and, if successful, replace everything in the Curl_URL struct. + */ +static CURLUcode parseurl_and_replace(const char *url, CURLU *u, + unsigned int flags) +{ + CURLUcode ures; + CURLU tmpurl; + memset(&tmpurl, 0, sizeof(tmpurl)); + ures = parseurl(url, &tmpurl, flags); + if(!ures) { + free_urlhandle(u); + *u = tmpurl; + } + return ures; +} + +/* + * Concatenate a relative URL onto a base URL making it absolute. + */ +static CURLUcode redirect_url(const char *base, const char *relurl, + CURLU *u, unsigned int flags) +{ + struct dynbuf urlbuf; + bool host_changed = FALSE; + const char *useurl = relurl; + const char *cutoff = NULL; + size_t prelen; + CURLUcode uc; + /* this can get here with a NULL u->scheme only if asked to use the default + scheme, so allow fallback to that */ + const char *scheme = u->scheme ? u->scheme : DEFAULT_SCHEME; + + /* protsep points to the start of the hostname, after [scheme]:// */ + const char *protsep = base + strlen(scheme) + 3; + DEBUGASSERT(base && relurl && u); /* all set here */ + if(!base) + return CURLUE_MALFORMED_INPUT; /* should never happen */ + + /* handle different relative URL types */ + switch(relurl[0]) { + case '/': + if(relurl[1] == '/') { + /* protocol-relative URL: //example.com/path */ + cutoff = protsep; + useurl = &relurl[2]; + host_changed = TRUE; + } + else + /* absolute /path */ + cutoff = strchr(protsep, '/'); + break; + + case '#': + /* fragment-only change */ + if(u->fragment_present) + cutoff = strchr(protsep, '#'); + break; + + default: + /* path or query-only change */ + if(u->query_present) + /* remove existing query */ + cutoff = strchr(protsep, '?'); + else if(u->fragment_present) + /* Remove existing fragment */ + cutoff = strchr(protsep, '#'); + + if(relurl[0] != '?') { + /* append a relative path after the last slash */ + cutoff = memrchr(protsep, '/', + cutoff ? (size_t)(cutoff - protsep) : strlen(protsep)); + if(cutoff) + cutoff++; /* truncate after last slash */ + } + break; + } + + prelen = cutoff ? (size_t)(cutoff - base) : strlen(base); + + /* build new URL */ + curlx_dyn_init(&urlbuf, CURL_MAX_INPUT_LENGTH); + + if(!curlx_dyn_addn(&urlbuf, base, prelen) && + !urlencode_str(&urlbuf, useurl, strlen(useurl), !host_changed, + QUERY_NOT_YET)) { + uc = parseurl_and_replace(curlx_dyn_ptr(&urlbuf), u, + flags & ~U_CURLU_PATH_AS_IS); + } + else + uc = CURLUE_OUT_OF_MEMORY; + + curlx_dyn_free(&urlbuf); + return uc; +} + +/* + */ +CURLU *curl_url(void) +{ + return curlx_calloc(1, sizeof(struct Curl_URL)); +} + +void curl_url_cleanup(CURLU *u) +{ + if(u) { + free_urlhandle(u); + curlx_free(u); + } +} + +#define DUP(dest, src, name) \ + do { \ + if((src)->name) { \ + (dest)->name = curlx_strdup((src)->name); \ + if(!(dest)->name) \ + goto fail; \ + } \ + } while(0) + +CURLU *curl_url_dup(const CURLU *in) +{ + struct Curl_URL *u = curlx_calloc(1, sizeof(struct Curl_URL)); + if(u) { + DUP(u, in, scheme); + DUP(u, in, user); + DUP(u, in, password); + DUP(u, in, options); + DUP(u, in, host); + DUP(u, in, path); + DUP(u, in, query); + DUP(u, in, fragment); + DUP(u, in, zoneid); + u->portnum = in->portnum; + u->port_present = in->port_present; + u->fragment_present = in->fragment_present; + u->query_present = in->query_present; + } + return u; +fail: + curl_url_cleanup(u); + return NULL; +} + +#ifndef USE_IDN +#define host_decode(x, y) CURLUE_LACKS_IDN +#define host_encode(x, y) CURLUE_LACKS_IDN +#else +static CURLUcode host_decode(const char *host, char **allochost) +{ + CURLcode result = Curl_idn_decode(host, allochost); + if(result) + return (result == CURLE_OUT_OF_MEMORY) ? + CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME; + return CURLUE_OK; +} + +static CURLUcode host_encode(const char *host, char **allochost) +{ + CURLcode result = Curl_idn_encode(host, allochost); + if(result) + return (result == CURLE_OUT_OF_MEMORY) ? + CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME; + return CURLUE_OK; +} +#endif + +static CURLUcode urlget_format(const CURLU *u, CURLUPart what, + const char *ptr, char **partp, + bool plusdecode, unsigned int flags) +{ + CURLUcode uc = CURLUE_OK; + size_t partlen = strlen(ptr); + bool urldecode = (flags & CURLU_URLDECODE) ? 1 : 0; + bool urlencode = (flags & CURLU_URLENCODE) ? 1 : 0; + bool punycode = (flags & CURLU_PUNYCODE) && (what == CURLUPART_HOST); + bool depunyfy = (flags & CURLU_PUNY2IDN) && (what == CURLUPART_HOST); + char *part = curlx_memdup0(ptr, partlen); + *partp = NULL; + if(!part) + return CURLUE_OUT_OF_MEMORY; + if(plusdecode) { + /* convert + to space */ + char *plus = part; + size_t i = 0; + for(i = 0; i < partlen; ++plus, i++) { + if(*plus == '+') + *plus = ' '; + } + } + if(urldecode) { + char *decoded; + size_t dlen; + /* this unconditional rejection of control bytes is documented API + behavior */ + CURLcode result = Curl_urldecode(part, partlen, &decoded, &dlen, + REJECT_CTRL); + curlx_free(part); + if(result) + return CURLUE_URLDECODE; + part = decoded; + partlen = dlen; + } + if(urlencode) { + struct dynbuf enc; + curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + uc = urlencode_str(&enc, part, partlen, TRUE, what == CURLUPART_QUERY ? + QUERY_YES : QUERY_NO); + curlx_free(part); + if(uc) + return uc; + part = curlx_dyn_ptr(&enc); + } + else if(punycode) { + if(!Curl_is_ASCII_name(u->host)) { + char *punyversion = NULL; + uc = host_decode(part, &punyversion); + curlx_free(part); + if(uc) + return uc; + part = punyversion; + } + } + else if(depunyfy) { + if(Curl_is_ASCII_name(u->host)) { + char *unpunified = NULL; + uc = host_encode(part, &unpunified); + curlx_free(part); + if(uc) + return uc; + part = unpunified; + } + } + *partp = part; + return CURLUE_OK; +} + +static CURLUcode file_url(const CURLU *u, char **part, + const char *fragmentsep, + const char *querysep) +{ + char *url = curl_maprintf("file://%s%s%s%s%s", + u->path, querysep, u->query ? u->query : "", + fragmentsep, u->fragment ? u->fragment : ""); + if(!url) + return CURLUE_OUT_OF_MEMORY; + + *part = url; + return CURLUE_OK; +} + +static CURLUcode urlget_url(const CURLU *u, char **part, unsigned int flags) +{ + char *url; + char *allochost = NULL; + const char *fragmentsep = + (u->fragment || (u->fragment_present && flags & CURLU_GET_EMPTY)) ? + "#" : ""; + const char *querysep = ((u->query && u->query[0]) || + (u->query_present && flags & CURLU_GET_EMPTY)) ? + "?" : ""; + char portbuf[7]; + if(curl_strequal("file", u->scheme)) + return file_url(u, part, fragmentsep, querysep); + else if(!u->host) + return CURLUE_NO_HOST; + else { + const char *scheme; + char *options = u->options; + char *port = NULL; + const struct Curl_scheme *h = NULL; + char schemebuf[MAX_SCHEME_LEN + 5]; + if(u->scheme) + scheme = u->scheme; + else if(flags & CURLU_DEFAULT_SCHEME) + scheme = DEFAULT_SCHEME; + else + return CURLUE_NO_SCHEME; + + if(u->port_present) { + curl_msnprintf(portbuf, sizeof(portbuf), "%u", u->portnum); + port = portbuf; + } + + h = Curl_get_scheme(scheme); + if(h) { + if(!u->port_present && (flags & CURLU_DEFAULT_PORT)) { + /* there is no stored port number, but asked to deliver a default one + for the scheme */ + curl_msnprintf(portbuf, sizeof(portbuf), "%u", h->defport); + port = portbuf; + } + else if(u->port_present && (h->defport == u->portnum) && + (flags & CURLU_NO_DEFAULT_PORT)) { + /* there is a stored port number, but asked to inhibit if it matches + the default port for the scheme */ + port = NULL; + } + + if(!(h->flags & PROTOPT_URLOPTIONS)) + options = NULL; + } + + if(u->host[0] == '[') { + if(u->zoneid) { + /* make it '[ host %25 zoneid ]' */ + struct dynbuf enc; + size_t hostlen = strlen(u->host); + curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + if(curlx_dyn_addf(&enc, "%.*s%%25%s]", (int)hostlen - 1, u->host, + u->zoneid)) + return CURLUE_OUT_OF_MEMORY; + allochost = curlx_dyn_ptr(&enc); + } + } + else if(flags & CURLU_URLENCODE) { + allochost = curl_easy_escape(NULL, u->host, 0); + if(!allochost) + return CURLUE_OUT_OF_MEMORY; + } + else if(flags & CURLU_PUNYCODE) { + if(!Curl_is_ASCII_name(u->host)) { + CURLUcode ret = host_decode(u->host, &allochost); + if(ret) + return ret; + } + } + else if(flags & CURLU_PUNY2IDN) { + if(Curl_is_ASCII_name(u->host)) { + CURLUcode ret = host_encode(u->host, &allochost); + if(ret) + return ret; + } + } + + if(!(flags & CURLU_NO_GUESS_SCHEME) || !u->guessed_scheme) + curl_msnprintf(schemebuf, sizeof(schemebuf), "%s://", scheme); + else + schemebuf[0] = 0; + + url = curl_maprintf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", + schemebuf, + u->user ? u->user : "", + u->password ? ":" : "", + u->password ? u->password : "", + options ? ";" : "", + options ? options : "", + (u->user || u->password || options) ? "@" : "", + allochost ? allochost : u->host, + port ? ":" : "", + port ? port : "", + u->path ? u->path : "/", + querysep, + u->query ? u->query : "", + fragmentsep, + u->fragment ? u->fragment : ""); + curlx_free(allochost); + } + if(!url) + return CURLUE_OUT_OF_MEMORY; + *part = url; + return CURLUE_OK; +} + +CURLUcode curl_url_get(const CURLU *u, CURLUPart what, + char **part, unsigned int flags) +{ + const char *ptr; + CURLUcode ifmissing = CURLUE_UNKNOWN_PART; + char portbuf[7]; + bool plusdecode = FALSE; + if(!u) + return CURLUE_BAD_HANDLE; + if(!part) + return CURLUE_BAD_PARTPOINTER; + *part = NULL; + + switch(what) { + case CURLUPART_SCHEME: + ptr = u->scheme; + ifmissing = CURLUE_NO_SCHEME; + flags &= ~U_CURLU_URLDECODE; /* never for schemes */ + if((flags & CURLU_NO_GUESS_SCHEME) && u->guessed_scheme) + return CURLUE_NO_SCHEME; + break; + case CURLUPART_USER: + ptr = u->user; + ifmissing = CURLUE_NO_USER; + break; + case CURLUPART_PASSWORD: + ptr = u->password; + ifmissing = CURLUE_NO_PASSWORD; + break; + case CURLUPART_OPTIONS: + ptr = u->options; + ifmissing = CURLUE_NO_OPTIONS; + break; + case CURLUPART_HOST: + ptr = u->host; + ifmissing = CURLUE_NO_HOST; + break; + case CURLUPART_ZONEID: + ptr = u->zoneid; + ifmissing = CURLUE_NO_ZONEID; + break; + case CURLUPART_PORT: + ptr = NULL; + ifmissing = CURLUE_NO_PORT; + flags &= ~U_CURLU_URLDECODE; /* never for port */ + if(u->port_present) { + const struct Curl_scheme *h = u->scheme ? + Curl_get_scheme(u->scheme) : NULL; + /* there is a stored port number, but ask to inhibit if + it matches the default one for the scheme */ + if(h && (h->defport == u->portnum) && + (flags & CURLU_NO_DEFAULT_PORT)) { + ptr = NULL; + } + else { + curl_msnprintf(portbuf, sizeof(portbuf), "%u", u->portnum); + ptr = portbuf; + } + } + else if((flags & CURLU_DEFAULT_PORT) && u->scheme) { + /* there is no stored port number, but asked to deliver + a default one for the scheme */ + const struct Curl_scheme *h = Curl_get_scheme(u->scheme); + if(h) { + curl_msnprintf(portbuf, sizeof(portbuf), "%u", h->defport); + ptr = portbuf; + } + } + break; + case CURLUPART_PATH: + ptr = u->path; + if(!ptr) + ptr = "/"; + break; + case CURLUPART_QUERY: + ptr = u->query; + ifmissing = CURLUE_NO_QUERY; + plusdecode = flags & CURLU_URLDECODE; + if(ptr && !ptr[0] && !(flags & CURLU_GET_EMPTY)) + /* there was a blank query and the user does not ask for it */ + ptr = NULL; + break; + case CURLUPART_FRAGMENT: + ptr = u->fragment; + ifmissing = CURLUE_NO_FRAGMENT; + if(!ptr && u->fragment_present && flags & CURLU_GET_EMPTY) + /* there was a blank fragment and the user asks for it */ + ptr = ""; + break; + case CURLUPART_URL: + return urlget_url(u, part, flags); + default: + ptr = NULL; + break; + } + if(ptr) + return urlget_format(u, what, ptr, part, plusdecode, flags); + + return ifmissing; +} + +static CURLUcode set_url_scheme(CURLU *u, const char *scheme, + unsigned int flags) +{ + size_t plen = strlen(scheme); + const struct Curl_scheme *h = NULL; + if((plen > MAX_SCHEME_LEN) || (plen < 1)) + /* too long or too short */ + return CURLUE_BAD_SCHEME; + /* verify that it is a fine scheme */ + h = Curl_get_scheme(scheme); + if(!(flags & CURLU_NON_SUPPORT_SCHEME) && (!h || !h->run)) + return CURLUE_UNSUPPORTED_SCHEME; + if(!h) { + const char *s = scheme; + if(ISALPHA(*s)) { + /* ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */ + s++; + while(--plen) { + if(ISALNUM(*s) || (*s == '+') || (*s == '-') || (*s == '.')) + s++; /* fine */ + else + return CURLUE_BAD_SCHEME; + } + } + else + return CURLUE_BAD_SCHEME; + } + u->guessed_scheme = FALSE; + return CURLUE_OK; +} + +static CURLUcode set_url_port(CURLU *u, const char *provided_port) +{ + curl_off_t port; + if(!ISDIGIT(provided_port[0])) + /* not a number */ + return CURLUE_BAD_PORT_NUMBER; + if(curlx_str_number(&provided_port, &port, 0xffff) || *provided_port) + /* weirdly provided number, not good! */ + return CURLUE_BAD_PORT_NUMBER; + u->portnum = (uint16_t)port; + u->port_present = TRUE; + return CURLUE_OK; +} + +static CURLUcode set_url(CURLU *u, const char *url, size_t part_size, + unsigned int flags) +{ + /* + * Allow a new URL to replace the existing (if any) contents. + * + * If the existing contents is enough for a URL, allow a relative URL to + * replace it. + */ + CURLUcode uc; + char *oldurl = NULL; + + if(!part_size) { + /* a blank URL is not a valid URL unless we already have a complete one + and this is a redirect */ + uc = curl_url_get(u, CURLUPART_URL, &oldurl, flags); + if(!uc) { + /* success, meaning the "" is a fine relative URL, and the new URL + inherits scheme/authority/path/query, but not fragment, from the + existing URL (RFC 3986 section 5.2.2) */ + curlx_safefree(u->fragment); + u->fragment_present = FALSE; + curlx_free(oldurl); + return CURLUE_OK; + } + if(uc == CURLUE_OUT_OF_MEMORY) + return uc; + return CURLUE_MALFORMED_INPUT; + } + + /* if the new URL is absolute replace the existing with the new. */ + if(Curl_is_absolute_url(url, NULL, 0, + flags & (CURLU_GUESS_SCHEME | CURLU_DEFAULT_SCHEME))) + return parseurl_and_replace(url, u, flags); + + /* if the old URL is incomplete (we cannot get an absolute URL in + 'oldurl'), replace the existing with the new. + Always include "scheme://" to make the URL "complete" */ + /* Preserve empty query/fragment separators: they affect where relative + references splice into the base URL. */ + uc = curl_url_get(u, CURLUPART_URL, &oldurl, + (flags & ~CURLU_NO_GUESS_SCHEME) | CURLU_GET_EMPTY); + if(uc == CURLUE_OUT_OF_MEMORY) + return uc; + else if(uc) + return parseurl_and_replace(url, u, flags); + + DEBUGASSERT(oldurl); /* it is set here */ + /* apply the relative part to create a new URL */ + uc = redirect_url(oldurl, url, u, flags); + curlx_free(oldurl); + return uc; +} + +static CURLUcode urlset_clear(CURLU *u, CURLUPart what) +{ + switch(what) { + case CURLUPART_URL: + free_urlhandle(u); + memset(u, 0, sizeof(struct Curl_URL)); + break; + case CURLUPART_SCHEME: + curlx_safefree(u->scheme); + u->guessed_scheme = FALSE; + break; + case CURLUPART_USER: + curlx_safefree(u->user); + break; + case CURLUPART_PASSWORD: + curlx_strzero(u->password); + curlx_safefree(u->password); + break; + case CURLUPART_OPTIONS: + curlx_safefree(u->options); + break; + case CURLUPART_HOST: + curlx_safefree(u->host); + break; + case CURLUPART_ZONEID: + curlx_safefree(u->zoneid); + break; + case CURLUPART_PORT: + u->portnum = 0; + u->port_present = FALSE; + break; + case CURLUPART_PATH: + curlx_safefree(u->path); + break; + case CURLUPART_QUERY: + curlx_safefree(u->query); + u->query_present = FALSE; + break; + case CURLUPART_FRAGMENT: + curlx_safefree(u->fragment); + u->fragment_present = FALSE; + break; + default: + return CURLUE_UNKNOWN_PART; + } + return CURLUE_OK; +} + +static bool allowed_in_path(unsigned char x) +{ + switch(x) { + case '!': + case '$': + case '&': + case '\'': + case '(': + case ')': + case '{': + case '}': + case '[': + case ']': + case '*': + case '+': + case ',': + case ';': + case '=': + case ':': + case '@': + case '/': + return TRUE; + } + return FALSE; +} + +static CURLUcode url_encode_part(struct dynbuf *encp, + const char *part, + bool plusencode, + bool pathmode, + bool equalsencode) +{ + const unsigned char *i; + + for(i = (const unsigned char *)part; *i; i++) { + CURLcode result; + if((*i == ' ') && plusencode) + result = curlx_dyn_addn(encp, "+", 1); + else if(ISUNRESERVED(*i) || + (pathmode && allowed_in_path(*i)) || + ((*i == '=') && equalsencode)) { + if((*i == '=') && equalsencode) + /* only skip the first equals sign */ + equalsencode = FALSE; + result = curlx_dyn_addn(encp, i, 1); + } + else { + unsigned char out[3] = { '%' }; + Curl_hexbyte(&out[1], *i); + result = curlx_dyn_addn(encp, out, 3); + } + if(result) + return cc2cu(result); + } + return CURLUE_OK; +} + +static CURLUcode url_uppercasehex_part(struct dynbuf *encp, + const char *part) +{ + char *p; + CURLcode result = curlx_dyn_add(encp, part); + if(result) + return cc2cu(result); + p = curlx_dyn_ptr(encp); + while(*p) { + /* make sure percent encoded are upper case */ + if((*p == '%') && ISXDIGIT(p[1]) && ISXDIGIT(p[2]) && + (ISLOWER(p[1]) || ISLOWER(p[2]))) { + p[1] = Curl_raw_toupper(p[1]); + p[2] = Curl_raw_toupper(p[2]); + p += 3; + } + else + p++; + } + return CURLUE_OK; +} + +static CURLUcode url_append_query(CURLU *u, struct dynbuf *encp) +{ + /* Append the 'encp' string onto the old query. Add a '&' separator if none + is already present at the end of the existing query */ + + size_t querylen = u->query ? strlen(u->query) : 0; + bool addamperand = querylen && (u->query[querylen - 1] != '&'); + if(querylen) { + struct dynbuf qbuf; + CURLcode result; + const char *newp = curlx_dyn_ptr(encp); + curlx_dyn_init(&qbuf, CURL_MAX_INPUT_LENGTH); + + /* add original query */ + result = curlx_dyn_addn(&qbuf, u->query, querylen); + if(!result && addamperand) + /* add ampersand */ + result = curlx_dyn_addn(&qbuf, "&", 1); + if(!result) + /* add new query part */ + result = curlx_dyn_add(&qbuf, newp); + if(result) + goto nomem; + curlx_dyn_free(encp); + curlx_free(u->query); + u->query = curlx_dyn_ptr(&qbuf); + return CURLUE_OK; +nomem: + curlx_dyn_free(encp); + return cc2cu(result); + } + else { + curlx_free(u->query); + u->query = curlx_dyn_ptr(encp); + } + return CURLUE_OK; +} + +static CURLUcode url_sethost(CURLU *u, struct dynbuf *encp, + bool urlencode, + unsigned int flags) +{ + size_t n = curlx_dyn_len(encp); + bool bad = FALSE; + char *newp = curlx_dyn_ptr(encp); + if(!n) + /* an empty hostname is okay if told so */ + bad = (flags & CURLU_NO_AUTHORITY) ? FALSE : TRUE; + else if(!urlencode) { + /* if the hostname part was not URL encoded here, it was set already URL + encoded so we need to decode it to check */ + size_t dlen; + char *decoded = NULL; + CURLcode result = Curl_urldecode(newp, n, &decoded, &dlen, REJECT_CTRL); + if(result || hostname_check(u, decoded, dlen)) + bad = TRUE; + curlx_free(decoded); + } + else if(hostname_check(u, newp, n)) + bad = TRUE; + if(bad) { + curlx_dyn_free(encp); + return CURLUE_BAD_HOSTNAME; + } + return CURLUE_OK; +} + +CURLUcode curl_url_set(CURLU *u, CURLUPart what, + const char *part, unsigned int flags) +{ + char **storep = NULL; + bool urlencode = (flags & CURLU_URLENCODE) ? 1 : 0; + bool plusencode = FALSE; + bool pathmode = FALSE; + bool leadingslash = FALSE; + bool appendquery = FALSE; + bool equalsencode = FALSE; + size_t nalloc; + + if(!u) + return CURLUE_BAD_HANDLE; + if(!part) + /* setting a part to NULL clears it */ + return urlset_clear(u, what); + + nalloc = strlen(part); + if(nalloc > CURL_MAX_INPUT_LENGTH) + /* excessive input length */ + return CURLUE_MALFORMED_INPUT; + + switch(what) { + case CURLUPART_SCHEME: { + CURLUcode status = set_url_scheme(u, part, flags); + if(status) + return status; + storep = &u->scheme; + urlencode = FALSE; /* never */ + break; + } + case CURLUPART_USER: + storep = &u->user; + break; + case CURLUPART_PASSWORD: + storep = &u->password; + break; + case CURLUPART_OPTIONS: + storep = &u->options; + break; + case CURLUPART_HOST: + storep = &u->host; + curlx_safefree(u->zoneid); + break; + case CURLUPART_ZONEID: + storep = &u->zoneid; + break; + case CURLUPART_PORT: + return set_url_port(u, part); + case CURLUPART_PATH: + pathmode = TRUE; + leadingslash = TRUE; /* enforce */ + storep = &u->path; + break; + case CURLUPART_QUERY: + plusencode = urlencode; + appendquery = (flags & CURLU_APPENDQUERY) ? 1 : 0; + equalsencode = appendquery; + storep = &u->query; + u->query_present = TRUE; + break; + case CURLUPART_FRAGMENT: + storep = &u->fragment; + u->fragment_present = TRUE; + break; + case CURLUPART_URL: + return set_url(u, part, nalloc, flags); + default: + return CURLUE_UNKNOWN_PART; + } + DEBUGASSERT(storep); + { + const char *newp = NULL; + struct dynbuf enc; + CURLUcode status; + curlx_dyn_init(&enc, (nalloc * 3) + 1 + leadingslash); + + if(leadingslash && (part[0] != '/')) { + CURLcode result = curlx_dyn_addn(&enc, "/", 1); + if(result) + return cc2cu(result); + } + if(urlencode) + status = url_encode_part(&enc, part, plusencode, pathmode, equalsencode); + else + status = url_uppercasehex_part(&enc, part); + if(!status) { + newp = curlx_dyn_ptr(&enc); + + if(appendquery && newp) + return url_append_query(u, &enc); + else if(what == CURLUPART_HOST) + status = url_sethost(u, &enc, urlencode, flags); + } + if(status) + return status; + + if(what == CURLUPART_PASSWORD) + curlx_strzero(*storep); + curlx_free(*storep); + *storep = (char *)CURL_UNCONST(newp); + } + return CURLUE_OK; +} + +bool Curl_url_same_origin(CURLU *base, CURLU *href) +{ + const struct Curl_scheme *s = NULL; + + /* base must be an absolute URL */ + if(!base->scheme || !base->host) + return FALSE; + if(href->scheme && !curl_strequal(base->scheme, href->scheme)) + return FALSE; + if(href->host) { + if(!curl_strequal(base->host, href->host)) + return FALSE; + + if(base->port_present != href->port_present) { + /* one is present, one is not */ + s = Curl_get_scheme(base->scheme); + if(!s) /* Cannot match default port for unknown scheme */ + return FALSE; + /* to match, the present one must be the default port */ + if((base->port_present && (base->portnum != s->defport)) || + (href->port_present && (href->portnum != s->defport))) + return FALSE; + } + else if(base->portnum != href->portnum) /* both present or missing */ + return FALSE; + + if(!curl_strequal(base->zoneid ? base->zoneid : "", + href->zoneid ? href->zoneid : "")) + return FALSE; + } + else if(href->port_present) /* no host in href, then there must be no port */ + return FALSE; + return TRUE; +} + +CURLUcode Curl_url_get_port(CURLU *u, uint16_t *pport) +{ + if(u->port_present) { + *pport = u->portnum; + return CURLUE_OK; + } + else if(u->scheme) { + const struct Curl_scheme *s = Curl_get_scheme(u->scheme); + if(s && s->defport) { + *pport = s->defport; + return CURLUE_OK; + } + } + *pport = 0; + return CURLUE_NO_PORT; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/urldata.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/urldata.h new file mode 100644 index 0000000000..1c0101847b --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/urldata.h @@ -0,0 +1,1240 @@ +#ifndef HEADER_CURL_URLDATA_H +#define HEADER_CURL_URLDATA_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* This file is for lib internal stuff */ +#include "curl_setup.h" + +#define CURL_DEFAULT_USER "anonymous" +#define CURL_DEFAULT_PASSWORD "ftp@example.com" + +#if !defined(_WIN32) && !defined(MSDOS) +/* do FTP line-end CRLF => LF conversions on platforms that prefer LF-only. It + also means: keep CRLF line endings on the CRLF platforms */ +#define CURL_PREFER_LF_LINEENDS +#endif + +#define DEFAULT_CONNCACHE_SIZE 5 + +/* length of longest IPv6 address string including the null-terminator */ +#define MAX_IPADR_LEN sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255") + +/* Max string input length is a precaution against abuse and to detect junk + input easier and better. */ +#define CURL_MAX_INPUT_LENGTH 8000000 + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETINET_IN6_H +#include <netinet/in6.h> +#endif + +#include "curlx/timeval.h" + +#include "api.h" +#include "cookie.h" +#include "creds.h" +#include "psl.h" +#include "formdata.h" +#include "http_chunks.h" /* for the structs and enum stuff */ +#include "hash.h" +#include "peer.h" +#include "proxy.h" +#include "splay.h" +#include "curlx/dynbuf.h" +#include "bufref.h" +#include "dynhds.h" +#include "request.h" +#include "ratelimit.h" +#include "netrc.h" +#include "uint-hashset.h" +#include "vdns/asyn.h" +#include "vdns/hostip.h" +#include "vtls/vtls_config.h" + +/* On error return, the value of `pnwritten` has no meaning */ +typedef CURLcode (Curl_send)(struct Curl_easy *data, /* transfer */ + int8_t sockindex, /* socketindex */ + const uint8_t *buf, /* data to write */ + size_t len, /* amount to send */ + bool eos, /* last chunk */ + size_t *pnwritten); /* how much sent */ + +/* On error return, the value of `pnread` has no meaning */ +typedef CURLcode (Curl_recv)(struct Curl_easy *data, /* transfer */ + int8_t sockindex, /* socketindex */ + char *buf, /* store data here */ + size_t len, /* max amount to read */ + size_t *pnread); /* how much received */ + +#include "mime.h" +#include "protocol.h" +#include "ftp.h" +#include "http.h" +#include "smb.h" +#include "mqtt.h" +#include "ftplistparser.h" +#include "multihandle.h" +#include "cf-socket.h" + +#ifdef HAVE_GSSAPI +# ifdef HAVE_GSSAPPLE +# include <GSS/gssapi.h> +# include <GSS/gssapi_oid.h> +# elif defined(HAVE_GSSGNU) +# include <gss.h> +# elif defined(HAVE_GSSAPI_H) +# include <gssapi.h> +# else /* MIT Kerberos */ +# include <gssapi/gssapi.h> +# include <gssapi/gssapi_krb5.h> /* for GSS_C_CHANNEL_BOUND_FLAG in 1.19+ */ +# endif +#endif + +#ifdef USE_LIBSSH2 +#include <libssh2.h> +#include <libssh2_sftp.h> +#endif /* USE_LIBSSH2 */ + +#define READBUFFER_SIZE CURL_MAX_WRITE_SIZE +#define READBUFFER_MAX CURL_MAX_READ_SIZE +#define READBUFFER_MIN 1024 + +/* The default upload buffer size, should not be smaller than + CURL_MAX_WRITE_SIZE, as it needs to hold a full buffer as could be sent in + a write callback. + + The size was 16KB for many years but was bumped to 64KB because it makes + libcurl able to do significantly faster uploads in some circumstances. Even + larger buffers can help further, but this is deemed a fair memory/speed + compromise. */ +#define UPLOADBUFFER_DEFAULT 65536 +#define UPLOADBUFFER_MAX (2 * 1024 * 1024) +#define UPLOADBUFFER_MIN CURL_MAX_WRITE_SIZE + +#ifdef USE_WINDOWS_SSPI +#include "curl_sspi.h" +#endif + +#ifndef CURL_DISABLE_DIGEST_AUTH +/* Struct used for Digest challenge-response authentication */ +struct digestdata { + struct Curl_creds *creds; + struct Curl_peer *origin; +#ifdef USE_WINDOWS_SSPI + BYTE *input_token; + size_t input_token_len; + CtxtHandle *http_context; +#else + char *nonce; + char *cnonce; + char *realm; + char *opaque; + char *qop; + char *algorithm; + int nc; /* nonce count */ + uint8_t algo; + BIT(stale); /* set true for re-negotiation */ + BIT(userhash); +#endif +}; +#endif + +typedef enum { + NTLMSTATE_NONE, + NTLMSTATE_TYPE1, + NTLMSTATE_TYPE2, + NTLMSTATE_TYPE3, + NTLMSTATE_LAST +} curlntlm; + +typedef enum { + GSS_AUTHNONE, + GSS_AUTHRECV, + GSS_AUTHSENT, + GSS_AUTHDONE, + GSS_AUTHSUCC +} curlnegotiate; + +/* + * Boolean values that concerns this connection. + */ +struct ConnectBits { + BIT(connect_only); +#ifndef CURL_DISABLE_PROXY + BIT(origin_is_proxy); /* if set, the connection's origin is a proxy */ +#endif + /* always modify bits.close with the connclose() and connkeep() macros! */ + BIT(close); /* if set, we close the connection after this request */ + BIT(reuse); /* if set, this is a reused connection */ + BIT(altused); /* this is an alt-svc "redirect" */ + BIT(ipv6); /* we communicate with a site using an IPv6 address */ + BIT(do_more); /* this is set TRUE if the ->curl_do_more() function is + supposed to be called, after ->curl_do() */ + BIT(protoconnstart);/* the protocol layer has STARTED its operation after + the TCP layer connect */ + BIT(retry); /* this connection is about to get closed and then + re-attempted at another connection. */ +#ifndef CURL_DISABLE_FTP + BIT(ftp_use_epsv); /* As set with CURLOPT_FTP_USE_EPSV, but if we find out + EPSV does not work we disable it for the forthcoming + requests */ + BIT(ftp_use_eprt); /* As set with CURLOPT_FTP_USE_EPRT, but if we find out + EPRT does not work we disable it for the forthcoming + requests */ + BIT(ftp_use_data_ssl); /* Enabled SSL for the data connection */ +#endif + BIT(bound); /* set true if bind() has already been done on this socket/ + connection */ + BIT(upgrade_in_progress); /* protocol upgrade is in progress */ + BIT(multiplex); /* connection is multiplexed */ + BIT(tcp_fastopen); /* use TCP Fast Open */ + BIT(tls_enable_alpn); /* TLS ALPN extension? */ + BIT(sock_accepted); /* TRUE if the SECONDARYSOCKET was created with + accept() */ + BIT(parallel_connect); /* set TRUE when a parallel connect attempt has + started (happy eyeballs) */ + BIT(aborted); /* connection was aborted, e.g. in unclean state */ + BIT(no_reuse); /* connection should not be reused */ + BIT(shutdown_handler); /* connection shutdown: handler shut down */ + BIT(shutdown_filters); /* connection shutdown: filters shut down */ + BIT(in_cpool); /* connection is kept in a connection pool */ + BIT(dns_resolved); /* DNS records for connection were resolved */ +}; + +struct hostname { + char *rawalloc; /* allocated "raw" version of the name */ + char *encalloc; /* allocated IDN-encoded version of the name */ + char *name; /* name to use internally, might be encoded, might be raw */ + const char *dispname; /* name to display, as 'name' might be encoded */ +}; + +#define FIRSTSOCKET 0 +#define SECONDARYSOCKET 1 + +#define TRNSPRT_NONE 0 +#define TRNSPRT_TCP 3 +#define TRNSPRT_UDP 4 +#define TRNSPRT_QUIC 5 +#define TRNSPRT_UNIX 6 + +#define TRNSPRT_IS_DGRAM(x) (((x) == TRNSPRT_UDP) || ((x) == TRNSPRT_QUIC)) + +struct ip_quadruple { + char remote_ip[MAX_IPADR_LEN]; + char local_ip[MAX_IPADR_LEN]; + uint16_t remote_port; + uint16_t local_port; + uint8_t transport; +}; + +#define CUR_IP_QUAD_HAS_PORTS(x) \ + (((x)->transport == TRNSPRT_TCP) || \ + ((x)->transport == TRNSPRT_UDP) || \ + ((x)->transport == TRNSPRT_QUIC)) + +/* + * The connectdata struct contains all fields and variables that should be + * unique for an entire connection. + */ +struct connectdata { + curl_off_t connection_id; /* Contains a unique number to make it easier to + track the connections in the log output */ + + /* A connection cache from a SHARE might be used in several multi handles. + * We MUST not reuse connections that are running in another multi, + * for concurrency reasons. That multi might run in another thread. + * `attached_multi` is set by the first transfer attached and cleared + * when the last one is detached. + * NEVER call anything on this multi, check for equality. */ + struct Curl_multi *attached_multi; + + /* Who the connection is talking to, ultimately */ + struct Curl_peer *origin; /* connection ultimately talks to this */ + struct Curl_peer *via_peer; /* if set, connection really talks to this */ + struct Curl_peer *origin2; /* origin of SECONDARYSOCKET */ + struct Curl_peer *via_peer2; /* peer of SECONDARYSOCKET */ + struct Curl_creds *creds; /* When connection itself is tied to credentials */ + struct Curl_peer *creds_origin; /* origin tied credentials are for */ + const struct Curl_scheme *scheme; /* Connection's real protocol handler */ + const struct Curl_scheme *given; /* The protocol first given */ + + /* `meta_hash` is a general key-value store for implementations + * with the lifetime of the connection. + * Elements need to be added with their own destructor to be invoked when + * the connection is cleaned up (see Curl_hash_add2()).*/ + struct Curl_hash meta_hash; + + struct Curl_llist_node cpool_node; /* conncache lists */ + struct Curl_llist_node cshutdn_node; /* cshutdn list */ + char *destination; /* hostname+port, used in conncache */ + + struct curltime created; /* creation time */ + struct curltime lastused; /* when returned to the connection pool as idle */ + struct curltime lastchecked; /* when last checked alive status */ + struct curltime lastupkeep; /* when last done conn_upkeep */ + +#ifndef CURL_DISABLE_PROXY + struct proxy_info socks_proxy; + struct proxy_info http_proxy; +#endif + + struct Curl_cfilter *cfilter[2]; /* connection filters */ + Curl_recv *recv[2]; + Curl_send *send[2]; + /* A connection can have one or two sockets and connection filters. + * The protocol using the 2nd one is FTP for CONTROL+DATA sockets */ + curl_socket_t sock[2]; + +#define CONN_SOCK_IDX_VALID(i) (((i) >= 0) && ((i) < 2)) + + struct { + struct curltime start[2]; /* when filter shutdown started */ + timediff_t timeout_ms; /* 0 means no timeout */ + } shutdown; + + curl_closesocket_callback fclosesocket; /* function closing the socket(s) */ + void *closesocket_client; + + struct ssl_primary_config ssl_config; +#ifndef CURL_DISABLE_PROXY + struct ssl_primary_config proxy_ssl_config; +#endif + char *options; /* options string, allocated */ + + /*************** Request - specific items ************/ +#ifdef USE_WINDOWS_SSPI + CtxtHandle *sslContext; +#endif + +#ifdef USE_NTLM + curlntlm http_ntlm_state; + curlntlm proxy_ntlm_state; +#endif + +#ifdef USE_SPNEGO + curlnegotiate http_negotiate_state; + curlnegotiate proxy_negotiate_state; +#endif + + /* When this connection is created, store the conditions for the local end + bind. This is stored before the actual bind and before any connection is + made and will serve the purpose of being used for comparison reasons so + that subsequent bound-requested connections are not accidentally reusing + wrong connections. */ + char *localdev; + struct ConnectBits bits; /* various state-flags for this connection */ +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + int socks5_gssapi_enctype; +#endif + + /* This is used by the connection pool logic. If this returns TRUE, this + handle is still used by one or more easy handles and can only used by any + other easy handle without careful consideration (== only for + multiplexing) and it cannot be used by another multi handle! */ +#define CONN_INUSE(c) (!!(c)->attached_xfers) + uint32_t attached_xfers; /* # of attached easy handles */ + +#ifdef USE_IPV6 + uint32_t scope_id; /* Scope id for IPv6 */ +#endif + uint16_t localportrange; + uint16_t localport; + int8_t recv_idx; /* on which socket index to receive, default 0 */ + int8_t send_idx; /* on which socket index to send, default 0 */ + uint8_t transport_wanted; /* one of the TRNSPRT_* defines. Not necessarily + the transport the connection ends using due to Alt-Svc and happy + eyeballing. Use Curl_conn_get_transport() for actual value once the + connection is set up. */ + uint8_t ip_version; /* copied from the Curl_easy at creation time */ + /* HTTP version last responded with by the server or negotiated via ALPN. + * 0 at start, then one of 09, 10, 11, etc. */ + uint8_t httpversion_seen; + uint8_t gssapi_delegation; /* inherited from set.gssapi_delegation */ + +}; + +#ifndef CURL_DISABLE_PROXY +#define CURL_CONN_HOST_DISPNAME(c) \ + ((c)->socks_proxy.peer ? (c)->socks_proxy.peer->user_hostname : \ + (c)->http_proxy.peer ? (c)->http_proxy.peer->user_hostname : \ + (c)->via_peer ? (c)->via_peer->user_hostname : \ + (c)->origin->user_hostname) +#else +#define CURL_CONN_HOST_DISPNAME(c) \ + ((c)->via_peer ? (c)->via_peer->user_hostname : (c)->origin->user_hostname) +#endif + +/* The end of connectdata. */ + +/* + * Struct to keep statistical and informational data. + * All variables in this struct must be initialized/reset in Curl_initinfo(). + */ +struct PureInfo { + /* PureInfo primary ip_quadruple is copied over from the connectdata + struct in order to allow curl_easy_getinfo() to return this information + even when the session handle is no longer associated with a connection, + and also allow curl_easy_reset() to clear this information from the + session handle without disturbing information which is still alive, and + that might be reused, in the connection pool. */ + struct ip_quadruple primary; + struct curl_certinfo certs; /* info about the certs. Asked for with + CURLOPT_CERTINFO / CURLINFO_CERTINFO */ + time_t filetime; /* If requested, this is might get set. Set to -1 if the + time was unretrievable. */ + curl_off_t request_size; /* the amount of bytes sent in the request(s) */ + curl_off_t numconnects; /* how many new connections libcurl created */ + char *contenttype; /* the content type of the object */ + char *wouldredirect; /* URL this would have been redirected to if asked to */ + curl_off_t retry_after; /* info from Retry-After: header */ + const char *conn_scheme; + int httpcode; /* Recent HTTP, FTP, RTSP or SMTP response code */ + int httpproxycode; /* response code from proxy when received separate */ + int httpversion; /* the http version number X.Y = X*10+Y */ + uint32_t conn_protocol; + uint32_t proxyauthavail; /* what proxy auth types were announced */ + uint32_t httpauthavail; /* what host auth types were announced */ + uint32_t proxyauthpicked; /* selected proxy auth type */ + uint32_t httpauthpicked; /* selected host auth type */ + uint32_t header_size; /* size of read header(s) in bytes */ + uint8_t pxcode; /* holds a CURLproxycode */ + BIT(timecond); /* set to TRUE if the time condition did not match, which + thus made the document NOT get fetched */ + BIT(used_proxy); /* the transfer used a proxy */ +}; + +struct pgrs_dir { + curl_off_t total_size; /* total expected bytes */ + curl_off_t cur_size; /* transferred bytes so far */ + curl_off_t speed; /* bytes per second transferred */ + struct Curl_rlimit rlimit; /* speed limiting / pausing */ +}; + +struct Progress { + struct curltime now; /* current time of processing */ + struct curltime start; /* when transfer was initialized, set once */ + + struct pgrs_dir ul; + struct pgrs_dir dl; + curl_off_t deliver; /* amount of data delivered to application */ + curl_off_t current_speed; /* uses the currently fastest transfer */ + curl_off_t earlydata_sent; + + struct { + timediff_t startop_us; /* since start when operations started */ + timediff_t startsingle_us; /* since start when last request started */ + timediff_t startqueue_us; /* since start when last entered queueing */ + timediff_t startredirect_us; /* since start when last redirected */ + timediff_t lastshow_us; /* since start when last progress shown */ + } delta; + struct { + timediff_t spent_us; /* all time spent since start */ + timediff_t queued_us; /* time spent since startsingle's for queueing */ + timediff_t nslookup_us; /* same for name resolves */ + timediff_t connect_us; /* same for connects */ + timediff_t appconnect_us; /* same for application connects, e.g. TLS */ + timediff_t pretransfer_us; /* same until requests were sent */ + timediff_t starttransfer_us; /* same until responses started */ + timediff_t posttransfer_us; /* same until responses ended */ + } total; + +#define CURL_SPEED_RECORDS (5 + 1) /* 6 entries for 5 seconds */ + + curl_off_t speed_amount[CURL_SPEED_RECORDS]; + timediff_t speed_time[CURL_SPEED_RECORDS]; + uint32_t speeder_c; + BIT(hide); + BIT(ul_size_known); + BIT(dl_size_known); + BIT(headers_out); /* when the headers have been written */ + BIT(callback); /* set when progress callback is used */ + BIT(startransfer_added); +}; + +struct auth { + uint32_t want; /* Bitmask set to the authentication methods wanted by app + (with CURLOPT_HTTPAUTH or CURLOPT_PROXYAUTH). */ + uint32_t picked; + uint32_t avail; /* Bitmask for what the server reports to support for this + resource */ + BIT(done); /* TRUE when the auth phase is done and ready to do the + actual request */ + BIT(multipass); /* TRUE if this is not yet authenticated but within the + auth multipass negotiation */ +}; + +#ifdef USE_NGHTTP2 +struct Curl_data_prio_node { + struct Curl_data_prio_node *next; + struct Curl_easy *data; +}; +#endif + +/* Timers */ +typedef enum { + EXPIRE_100_TIMEOUT, + EXPIRE_ASYNC_NAME, + EXPIRE_CONNECTTIMEOUT, + EXPIRE_HAPPY_EYEBALLS, + EXPIRE_MULTI_PENDING, + EXPIRE_SPEEDCHECK, + EXPIRE_TIMEOUT, + EXPIRE_TOOFAST, + EXPIRE_QUIC, + EXPIRE_FTP_ACCEPT, + EXPIRE_ALPN_EYEBALLS, + EXPIRE_SHUTDOWN, + EXPIRE_LAST /* not an actual timer, used as a marker only */ +} expire_id; + +struct expire_timers { + struct Curl_tree splaynode; /* for the splay stuff */ + /* microsecond offset from Curl_timeouts base timestamp */ + timediff_t offset_us[EXPIRE_LAST]; + uint8_t next[EXPIRE_LAST]; + uint8_t first; +}; + +/* individual pieces of the URL */ +struct urlpieces { + char *options; + char *path; + char *query; +}; + +struct UrlState { + curl_off_t lastconnect_id; /* The last assigned connection or -1 */ + /* Origin of the initial (e.g. not followed) request of a transfer. + Credentials from CURLOPT_* are only valid for this origin. + Always set once a transfer starts searching for connections. */ + struct Curl_peer *initial_origin; + /* Current origin of the transfer, changes to origin of follow + * requests. */ + struct Curl_peer *origin; + + struct curltime keeps_speed; /* for the progress meter really */ + struct dynbuf headerb; /* buffer to store headers in */ +#ifndef CURL_DISABLE_HSTS + struct curl_slist *hstslist; /* list of HSTS files set by + curl_easy_setopt(HSTS) calls */ +#endif + + int os_errno; /* filled in with errno whenever an error occurs */ + int requests; /* request counter: redirects + authentication retakes */ +#ifdef HAVE_SIGNAL + /* storage for the previous bag^H^H^HSIGPIPE signal handler :-) */ + void (*prev_signal)(int sig); +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + char *envproxy; /* last proxy string used for proxy-related state */ + struct digestdata digest; /* state data for host Digest auth */ + struct digestdata proxydigest; /* state data for proxy Digest auth */ +#endif + struct auth authhost; /* auth details for host */ + struct auth authproxy; /* auth details for proxy */ + +#ifdef USE_CURL_ASYNC + struct Curl_resolv_async *async; /* asynchronous name resolver data */ +#endif + +#ifdef USE_OPENSSL + /* void instead of ENGINE to avoid bleeding OpenSSL into this header */ + void *engine; + /* void instead of OSSL_PROVIDER */ + void *provider; + void *baseprov; + void *libctx; + char *propq; /* for a provider */ +#endif /* USE_OPENSSL */ + struct expire_timers timeouts; /* expire timeouts */ + + /* a place to store the most recently set (S)FTP entrypath */ + char *most_recent_ftp_entrypath; + char *range; /* range, if used. See README for detailed specification on + this syntax. */ + curl_off_t resume_from; /* continue [ftp] transfer from here */ + curl_off_t infilesize; /* size of file to upload, -1 means unknown. + Copied from set.filesize at start of operation */ + curl_read_callback fread_func; /* read callback/function */ + void *in; /* CURLOPT_READDATA */ + CURLU *uh; /* URL handle for the current parsed URL */ + struct urlpieces up; + struct bufref url; /* work URL, initially copied from UserDefined */ + struct bufref referer; /* referer string */ + struct curl_slist *resolve; /* set to point to the set.resolve list when + this should be dealt with in pretransfer */ +#ifndef CURL_DISABLE_HTTP + curl_mimepart *mimepost; +#ifndef CURL_DISABLE_FORM_API + curl_mimepart *formp; /* storage for old API form-posting, allocated on + demand */ +#endif + struct Curl_llist httphdrs; /* received headers */ + struct curl_header headerout[2]; /* for external purposes */ +#endif +#ifndef CURL_DISABLE_COOKIES + struct curl_slist *cookielist; /* list of cookie files set by + curl_easy_setopt(COOKIEFILE) calls */ +#endif + +#ifdef CURLVERBOSE + struct curl_trc_feat *feat; /* opt. trace feature transfer is part of */ +#endif + +#ifndef CURL_DISABLE_NETRC + struct store_netrc netrc; +#endif + + struct Curl_creds *creds; /* Credentials for the origin only */ + +#ifndef CURL_DISABLE_HTTP + char *rangeline; /* allocated */ + char *http_host; /* allocated */ + struct http_negotiation http_neg; +#endif +#ifndef CURL_DISABLE_RTSP + /* This RTSP state information survives requests and connections */ + uint8_t rtp_channel_mask[32]; /* for the correctness checking of the + interleaved data */ + uint32_t rtsp_next_client_CSeq; /* the session's next client CSeq */ + uint32_t rtsp_next_server_CSeq; /* the session's next server CSeq */ + uint32_t rtsp_CSeq_recv; /* most recent CSeq received */ +#endif +#if defined(USE_HTTP2) || defined(USE_HTTP3) + int weight; /* shallow copy of data->set */ +#endif + uint16_t followlocation; /* redirect counter */ + uint8_t retrycount; /* number of retries on a new connection, up to + CONN_MAX_RETRIES */ + uint8_t httpreq; /* Curl_HttpReq; what kind of HTTP request (if any) + is this */ + +#ifdef USE_OPENSSL + BIT(provider_loaded); +#endif /* USE_OPENSSL */ + BIT(really_alive); /* transfer is really alive in multi, passed INIT */ + BIT(this_is_a_follow); /* this is a followed Location: request */ + BIT(refused_stream); /* this was refused, try again */ + BIT(errorbuf); /* Set to TRUE if the error buffer is already filled in. + This must be set to FALSE every time _easy_perform() is + called. */ + BIT(allow_port); /* Is set.use_port allowed to take effect or not. This + is always set TRUE when curl_easy_perform() is called. */ + BIT(authproblem); /* TRUE if there is some problem authenticating */ + /* set after initial USER failure, to prevent an authentication loop */ + BIT(wildcardmatch); /* enable wildcard matching */ + BIT(disableexpect); /* TRUE if Expect: is disabled due to a previous + 417 response */ + BIT(use_range); + BIT(rangestringalloc); /* the range string is malloc()'ed */ + BIT(done); /* set to FALSE when Curl_init_transfer() is called and set to + TRUE when multi_done() is called, to prevent multi_done() from + being invoked twice. */ +#ifndef CURL_DISABLE_COOKIES + BIT(cookie_engine); +#endif + BIT(prefer_ascii); /* ASCII rather than binary */ +#ifdef CURL_LIST_ONLY_PROTOCOL + BIT(list_only); /* list directory contents */ +#endif + BIT(wildcard_resolve); /* Set to true if any resolve change is a wildcard */ + BIT(upload); /* upload request */ + BIT(internal); /* internal: true if this easy handle was created for + internal use and the user does not have ownership of the + handle. */ + BIT(http_ignorecustom); /* ignore custom method from now */ +#ifndef CURL_DISABLE_HTTP + BIT(http_hd_te); /* Added HTTP header TE: */ + BIT(http_hd_upgrade); /* Added HTTP header Upgrade: */ + BIT(http_hd_h2_settings); /* Added HTTP header H2Settings: */ + BIT(maybe_folded); + BIT(leading_unfold); /* unfold started, this is the leading bytes */ +#endif +}; + +/* + * This 'UserDefined' struct must only contain data that is set once to go + * for many (perhaps) independent connections. Values that are generated or + * calculated internally for the "session handle" MUST be defined within the + * 'struct UrlState' instead. The only exceptions MUST note the changes in + * the 'DynamicStatic' struct. + * Character pointer fields point to dynamic storage, unless otherwise stated. + */ + +struct Curl_multi; /* declared in multihandle.c */ + +enum dupstring { + STRING_CERT, /* client certificate filename */ + STRING_CERT_TYPE, /* format for certificate (default: PEM)*/ + STRING_KEY, /* private key filename */ + STRING_KEY_PASSWD, /* plain text private key password */ + STRING_KEY_TYPE, /* format for private key (default: PEM) */ + STRING_SSL_CAPATH, /* CA directory name (does not work on Windows) */ + STRING_SSL_CAFILE, /* certificate file to verify peer against */ + STRING_SSL_PINNEDPUBLICKEY, /* public key file to verify peer against */ + STRING_SSL_CIPHER_LIST, /* list of ciphers to use */ + STRING_SSL_CIPHER13_LIST, /* list of TLS 1.3 ciphers to use */ + STRING_SSL_CRLFILE, /* CRL file to check certificate */ + STRING_SSL_ISSUERCERT, /* issuer cert file to check certificate */ + STRING_SERVICE_NAME, /* Service name */ +#ifndef CURL_DISABLE_PROXY + STRING_CERT_PROXY, /* client certificate filename */ + STRING_CERT_TYPE_PROXY, /* format for certificate (default: PEM)*/ + STRING_KEY_PROXY, /* private key filename */ + STRING_KEY_PASSWD_PROXY, /* plain text private key password */ + STRING_KEY_TYPE_PROXY, /* format for private key (default: PEM) */ + STRING_SSL_CAPATH_PROXY, /* CA directory name (does not work on Windows) */ + STRING_SSL_CAFILE_PROXY, /* certificate file to verify peer against */ + STRING_SSL_PINNEDPUBLICKEY_PROXY, /* public key file to verify proxy */ + STRING_SSL_CIPHER_LIST_PROXY, /* list of ciphers to use */ + STRING_SSL_CIPHER13_LIST_PROXY, /* list of TLS 1.3 ciphers to use */ + STRING_SSL_CRLFILE_PROXY, /* CRL file to check certificate */ + STRING_SSL_ISSUERCERT_PROXY, /* issuer cert file to check certificate */ + STRING_PROXY_SERVICE_NAME, /* Proxy service name */ +#endif +#ifndef CURL_DISABLE_COOKIES + STRING_COOKIE, /* HTTP cookie string to send */ + STRING_COOKIEJAR, /* dump all cookies to this file */ +#endif + STRING_CUSTOMREQUEST, /* HTTP/FTP/RTSP request/method to use */ + STRING_DEFAULT_PROTOCOL, /* Protocol to use when the URL does not specify */ + STRING_DEVICE, /* local network interface/address to use */ + STRING_INTERFACE, /* local network interface to use */ + STRING_BINDHOST, /* local address to use */ + STRING_ENCODING, /* Accept-Encoding string */ +#ifndef CURL_DISABLE_FTP + STRING_FTP_ACCOUNT, /* ftp account data */ + STRING_FTP_ALTERNATIVE_TO_USER, /* command to send if USER/PASS fails */ + STRING_FTPPORT, /* port to send with the FTP PORT command */ +#endif +#ifndef CURL_DISABLE_NETRC + STRING_NETRC_FILE, /* if not NULL, use this instead of trying to find + $HOME/.netrc */ +#endif +#ifndef CURL_DISABLE_PROXY + STRING_PROXY, /* proxy to use */ + STRING_PRE_PROXY, /* pre socks proxy to use */ +#endif + STRING_SET_RANGE, /* range, if used */ + STRING_SET_REFERER, /* custom string for the HTTP referer field */ + STRING_SET_URL, /* what original URL to work on */ + STRING_USERAGENT, /* User-Agent string */ + STRING_SSL_ENGINE, /* name of SSL engine */ + STRING_USERNAME, /* <username>, if used */ + STRING_PASSWORD, /* <password>, if used */ + STRING_OPTIONS, /* <options>, if used */ +#ifndef CURL_DISABLE_PROXY + STRING_PROXYUSERNAME, /* Proxy <username>, if used */ + STRING_PROXYPASSWORD, /* Proxy <password>, if used */ + STRING_NOPROXY, /* List of hosts which should not use the proxy, if + used */ +#endif +#ifndef CURL_DISABLE_RTSP + STRING_RTSP_SESSION_ID, /* Session ID to use */ + STRING_RTSP_STREAM_URI, /* Stream URI for this request */ + STRING_RTSP_TRANSPORT, /* Transport for this session */ +#endif +#ifdef USE_SSH + STRING_SSH_PRIVATE_KEY, /* path to the private key file for auth */ + STRING_SSH_PUBLIC_KEY, /* path to the public key file for auth */ + STRING_SSH_HOST_PUBLIC_KEY_MD5, /* md5 of host public key in ASCII hex */ + STRING_SSH_HOST_PUBLIC_KEY_SHA256, /* sha256 of host public key in base64 */ + STRING_SSH_KNOWNHOSTS, /* filename of knownhosts file */ +#endif +#ifndef CURL_DISABLE_SMTP + STRING_MAIL_FROM, + STRING_MAIL_AUTH, +#endif + STRING_BEARER, /* <bearer>, if used */ +#ifdef USE_UNIX_SOCKETS + STRING_UNIX_SOCKET_PATH, /* path to Unix socket, if used */ +#endif + STRING_TARGET, /* CURLOPT_REQUEST_TARGET */ +#ifndef CURL_DISABLE_DOH + STRING_DOH, /* CURLOPT_DOH_URL */ +#endif +#ifndef CURL_DISABLE_ALTSVC + STRING_ALTSVC, /* CURLOPT_ALTSVC */ +#endif +#ifndef CURL_DISABLE_HSTS + STRING_HSTS, /* CURLOPT_HSTS */ +#endif + STRING_SASL_AUTHZID, /* CURLOPT_SASL_AUTHZID */ +#ifdef USE_ARES + STRING_DNS_SERVERS, + STRING_DNS_INTERFACE, + STRING_DNS_LOCAL_IP4, + STRING_DNS_LOCAL_IP6, +#endif + STRING_SSL_EC_CURVES, +#ifndef CURL_DISABLE_AWS + STRING_AWS_SIGV4, /* Parameters for V4 signature */ +#endif +#ifndef CURL_DISABLE_HTTPSIG + STRING_HTTPSIG_KEY, /* hex-encoded key data */ + STRING_HTTPSIG_KEYID, /* key identifier */ + STRING_HTTPSIG_HEADERS, /* space-separated components to sign */ +#endif +#ifndef CURL_DISABLE_PROXY + STRING_HAPROXY_CLIENT_IP, /* CURLOPT_HAPROXY_CLIENT_IP */ +#endif + STRING_ECH_CONFIG, /* CURLOPT_ECH_CONFIG */ + STRING_ECH_PUBLIC, /* CURLOPT_ECH_PUBLIC */ + STRING_SSL_SIGNATURE_ALGORITHMS, /* CURLOPT_SSL_SIGNATURE_ALGORITHMS */ + + STRING_LAST /* not used, an end-of-list marker */ +}; + +enum dupblob { + BLOB_CERT, + BLOB_KEY, + BLOB_SSL_ISSUERCERT, + BLOB_CAINFO, +#ifndef CURL_DISABLE_PROXY + BLOB_CERT_PROXY, + BLOB_KEY_PROXY, + BLOB_SSL_ISSUERCERT_PROXY, + BLOB_CAINFO_PROXY, +#endif + BLOB_LAST +}; + +struct UserDefined { + FILE *err; /* the stderr user data goes here */ + void *debugdata; /* the data that will be passed to fdebug */ + char *errorbuffer; /* (Static) store failure messages in here */ + void *out; /* CURLOPT_WRITEDATA */ + void *in_set; /* CURLOPT_READDATA */ + void *writeheader; /* write the header to this if non-NULL */ + uint32_t httpauth; /* kind of HTTP authentication to use (bitmask) */ + uint32_t proxyauth; /* kind of proxy authentication to use (bitmask) */ + void *postfields; /* if POST, set the fields' values here */ + char *str_copypostfields; /* CURLOPT_COPYPOSTFIELDS value */ + curl_seek_callback seek_func; /* function that seeks the input */ + curl_off_t postfieldsize; /* if POST, this might have a size to use instead + of strlen(), and then the data *may* be binary + (contain zero bytes) */ + curl_write_callback fwrite_func; /* function that stores the output */ + curl_write_callback fwrite_header; /* function that stores headers */ + curl_write_callback fwrite_rtp; /* function that stores interleaved RTP */ + curl_read_callback fread_func_set; /* function that reads the input */ + curl_progress_callback fprogress; /* OLD and deprecated progress callback */ + curl_xferinfo_callback fxferinfo; /* progress callback */ + curl_debug_callback fdebug; /* function that write informational data */ + curl_ioctl_callback ioctl_func; /* function for I/O control */ + curl_sockopt_callback fsockopt; /* function for setting socket options */ + void *sockopt_client; /* pointer to pass to the socket options callback */ + curl_opensocket_callback fopensocket; /* function for checking/translating + the address and opening the + socket */ + void *opensocket_client; + curl_closesocket_callback fclosesocket; /* function for closing the + socket */ + void *closesocket_client; + curl_prereq_callback fprereq; /* pre-initial request callback */ + void *prereq_userp; /* pre-initial request user data */ + + void *seek_client; /* pointer to pass to the seek callback */ +#ifndef CURL_DISABLE_HSTS + curl_hstsread_callback hsts_read; + void *hsts_read_userp; + curl_hstswrite_callback hsts_write; + void *hsts_write_userp; +#endif + void *progress_client; /* pointer to pass to the progress callback */ + void *ioctl_client; /* pointer to pass to the ioctl callback */ + timediff_t conn_max_idle_ms; /* max idle time to allow a connection that + is to be reused */ + timediff_t conn_max_age_ms; /* max time since creation to allow a + connection that is to be reused */ + curl_off_t filesize; /* size of file to upload, -1 means unknown */ + curl_off_t low_speed_limit; /* bytes/second */ + curl_off_t max_send_speed; /* high speed limit in bytes/second for upload */ + curl_off_t max_recv_speed; /* high speed limit in bytes/second for + download */ + curl_off_t set_resume_from; /* continue [ftp] transfer from here */ + struct curl_slist *headers; /* linked list of extra headers */ + struct curl_httppost *httppost; /* linked list of old POST data */ +#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API) + curl_mimepart *mimepostp; /* MIME/POST data. */ +#endif +#ifndef CURL_DISABLE_TELNET + struct curl_slist *telnet_options; /* linked list of telnet options */ +#endif + struct curl_slist *resolve; /* list of names to add/remove from + DNS cache */ + struct curl_slist *connect_to; /* list of host:port mappings to override + the hostname and port to connect to */ + time_t timevalue; /* what time to compare with */ + struct ssl_config_data ssl; /* user defined SSL stuff */ +#ifndef CURL_DISABLE_PROXY + struct ssl_config_data proxy_ssl; /* user defined SSL stuff for proxy */ + struct curl_slist *proxyheaders; /* linked list of extra CONNECT headers */ + uint16_t proxyport; /* If non-zero, use this port number by + default. If the proxy string features a + ":[port]" that one will override this. */ + uint8_t proxytype; /* what kind of proxy */ + uint8_t socks5auth;/* kind of SOCKS5 authentication to use (bitmask) */ +#endif + struct ssl_general_config general_ssl; /* general user defined SSL stuff */ + timediff_t dns_cache_timeout_ms; /* DNS cache timeout (milliseconds) */ + uint32_t buffer_size; /* size of receive buffer to use */ + uint32_t upload_buffer_size; /* size of upload buffer to use, keep it >= + CURL_MAX_WRITE_SIZE */ + void *private_data; /* application-private data */ +#ifndef CURL_DISABLE_HTTP + struct curl_slist *http200aliases; /* linked list of aliases for http200 */ +#endif + curl_off_t max_filesize; /* Maximum file size to download */ +#ifndef CURL_DISABLE_FTP + timediff_t accepttimeout; /* in milliseconds, 0 means no timeout */ +#endif +#if !defined(CURL_DISABLE_FTP) || defined(USE_SSH) + struct curl_slist *quote; /* after connection is established */ + struct curl_slist *postquote; /* after the transfer */ + struct curl_slist *prequote; /* before the transfer, after type */ +#endif +#ifdef USE_LIBSSH2 + curl_sshhostkeycallback ssh_hostkeyfunc; /* hostkey check callback */ + void *ssh_hostkeyfunc_userp; /* custom pointer to callback */ +#endif +#ifdef USE_SSH + curl_sshkeycallback ssh_keyfunc; /* key matching callback */ + void *ssh_keyfunc_userp; /* custom pointer to callback */ + uint32_t ssh_auth_types; /* allowed SSH auth types */ + uint32_t new_directory_perms; /* when creating remote dirs */ +#endif + struct u8_strset strings; + struct curl_blob *blobs[BLOB_LAST]; + uint32_t new_file_perms; /* when creating remote files */ +#ifdef USE_IPV6 + uint32_t scope_id; /* Scope id for IPv6 */ +#endif + curl_prot_t allowed_protocols; + curl_prot_t redir_protocols; +#ifndef CURL_DISABLE_RTSP + void *rtp_out; /* write RTP to this if non-NULL */ +#endif +#ifndef CURL_DISABLE_FTP + curl_chunk_bgn_callback chunk_bgn; /* called before part of transfer + starts */ + curl_chunk_end_callback chunk_end; /* called after part transferring + stopped */ + curl_fnmatch_callback fnmatch; /* callback to decide which file corresponds + to pattern (e.g. if WILDCARDMATCH is on) */ + void *fnmatch_data; + void *wildcardptr; +#endif + + timediff_t timeout; /* ms, 0 means no timeout */ + timediff_t connecttimeout; /* ms, 0 means default timeout */ + timediff_t happy_eyeballs_timeout; /* ms, 0 is a valid value */ + timediff_t server_response_timeout; /* ms, 0 means no timeout */ + timediff_t shutdowntimeout; /* ms, 0 means default timeout */ + curl_resolver_start_callback resolver_start; /* optional callback called + before resolver start */ + void *resolver_start_client; /* pointer to pass to resolver start callback */ + timediff_t upkeep_interval_ms; /* Time between calls for connection + upkeep. */ + CURLU *uh; /* URL handle for the current parsed URL */ +#ifndef CURL_DISABLE_HTTP + void *trailer_data; /* pointer to pass to trailer data callback */ + curl_trailer_callback trailer_callback; /* trailing data callback */ +#endif +#ifndef CURL_DISABLE_SMTP + struct curl_slist *mail_rcpt; /* linked list of mail recipients */ +#endif + int tcp_keepidle; /* seconds in idle before sending keepalive probe */ + int tcp_keepintvl; /* seconds between TCP keepalive probes */ + int tcp_keepcnt; /* maximum number of keepalive probes */ + + uint32_t maxconnects; /* Max idle connections in the connection cache */ +#if defined(USE_HTTP2) || defined(USE_HTTP3) + /* Priority information for an easy handle in relation to others on the same + connection. */ + int weight; +#endif + short maxredirs; /* maximum no. of http(s) redirects to follow, + set to -1 for infinity */ + uint16_t expect_100_timeout; /* in milliseconds */ + uint16_t use_port; /* which port to use (when not using default) */ + uint16_t low_speed_time; /* number of seconds */ +#ifndef CURL_DISABLE_BINDLOCAL + uint16_t localport; /* local port number to bind to */ + uint16_t localportrange; /* number of additional port numbers to test + in case the 'localport' one cannot be + bind()ed */ +#endif +#ifndef CURL_DISABLE_TFTP + uint16_t tftp_blksize; /* in bytes, 0 means use default */ +#endif +#ifndef CURL_DISABLE_RTSP + uint8_t rtspreq; /* RTSP request type */ +#endif +#ifdef USE_ECH + uint8_t tls_ech; /* TLS ECH configuration */ +#endif +#ifndef CURL_DISABLE_NETRC + uint8_t use_netrc; /* enum CURL_NETRC_OPTION values */ +#endif +#if !defined(CURL_DISABLE_FTP) || defined(USE_SSH) + /* Despite the name, ftp_create_missing_dirs is for FTP(S) and SFTP + 1 - create directories that do not exist + 2 - the same but also allow MKD to fail once + */ + uint8_t ftp_create_missing_dirs; +#endif +#ifndef CURL_DISABLE_FTP + uint8_t ftp_filemethod; /* how to get to a file: curl_ftpfile */ + uint8_t ftpsslauth; /* what AUTH XXX to try: curl_ftpauth */ + uint8_t ftp_ccc; /* FTP CCC options: curl_ftpccc */ +#endif + uint8_t httpsig_algorithm; /* CURLHTTPSIG_* algorithm for RFC 9421 */ + uint8_t use_ssl; /* if AUTH TLS is to be attempted etc, for FTP or IMAP or + POP3 or others! (type: curl_usessl)*/ + uint8_t timecondition; /* kind of time comparison: curl_TimeCond */ + uint8_t method; /* what kind of HTTP request: Curl_HttpReq */ + uint8_t httpwant; /* when non-zero, a specific HTTP version requested + to be used in the library's request(s) */ + uint8_t ipver; /* the CURL_IPRESOLVE_* defines in the public header + file 0 - whatever, 1 - v2, 2 - v6 */ + uint8_t upload_flags; /* flags set by CURLOPT_UPLOAD_FLAGS */ +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + /* GSS-API/SSPI credential delegation, see CURLOPT_GSSAPI_DELEGATION */ + uint8_t gssapi_delegation; +#endif + uint8_t http_follow_mode; /* follow HTTP redirects */ + BIT(connect_only); /* make connection/request, then let application use the + socket */ + BIT(connect_only_ws); /* special websocket connect-only level */ +#ifndef CURL_DISABLE_SMTP + BIT(mail_rcpt_allowfails); /* allow RCPT TO command to fail for some + recipients */ +#endif +#ifndef CURL_DISABLE_MIME + BIT(mime_formescape); +#endif + BIT(is_fread_set); /* has read callback been set to non-NULL? */ +#ifndef CURL_DISABLE_TFTP + BIT(tftp_no_options); /* do not send TFTP options requests */ +#endif + BIT(sep_headers); /* handle host and proxy headers separately */ +#ifndef CURL_DISABLE_COOKIES + BIT(cookiesession); /* new cookie session? */ +#endif + BIT(crlf); /* convert crlf on ftp upload(?) */ +#ifdef USE_SSH + BIT(ssh_compression); /* enable SSH compression */ +#endif + +/* Here follows boolean settings that define how to behave during + this session. They are STATIC, set by libcurl users or at least initially + and they do not change during operations. */ + BIT(quick_exit); /* set 1L when it is okay to leak things (like + threads), as we are about to exit() anyway and + do not want lengthy cleanups to delay termination, + e.g. after a DNS timeout */ + BIT(get_filetime); /* get the time and get of the remote file */ +#ifndef CURL_DISABLE_PROXY + BIT(tunnel_thru_httpproxy); /* use CONNECT through an HTTP proxy */ +#endif + BIT(prefer_ascii); /* ASCII rather than binary */ + BIT(remote_append); /* append, not overwrite, on upload */ +#ifdef CURL_LIST_ONLY_PROTOCOL + BIT(list_only); /* list directory */ +#endif +#ifndef CURL_DISABLE_FTP + BIT(ftp_use_port); /* use the FTP PORT command */ + BIT(ftp_use_epsv); /* if EPSV is to be attempted or not */ + BIT(ftp_use_eprt); /* if EPRT is to be attempted or not */ + BIT(ftp_use_pret); /* if PRET is to be used before PASV or not */ + BIT(ftp_skip_ip); /* skip the IP address the FTP server passes on to + us */ + BIT(wildcard_enabled); /* enable wildcard matching */ +#endif + BIT(http_fail_on_error); /* fail on HTTP error codes >= 400 */ + BIT(http_keep_sending_on_error); /* for HTTP status codes >= 300 */ + BIT(http_transfer_encoding); /* request compressed HTTP transfer-encoding */ + BIT(allow_auth_to_other_hosts); + BIT(include_header); /* include received protocol headers in data output */ + BIT(http_set_referer); /* is a custom referer used */ + BIT(http_auto_referer); /* set "correct" referer when following + location: */ + BIT(opt_no_body); /* as set with CURLOPT_NOBODY */ + BIT(verbose); /* output verbosity */ + BIT(reuse_forbid); /* forbidden to be reused, close after use */ + BIT(reuse_fresh); /* do not reuse an existing connection */ + BIT(no_signal); /* do not use any signal/alarm handler */ + BIT(tcp_nodelay); /* whether to enable TCP_NODELAY or not */ + BIT(ignorecl); /* ignore content length */ + BIT(http_te_skip); /* pass the raw body data to the user, even when + transfer-encoded (chunked, compressed) */ + BIT(http_ce_skip); /* pass the raw body data to the user, even when + content-encoded (chunked, compressed) */ + BIT(proxy_transfer_mode); /* set transfer mode (;type=<a|i>) when doing + FTP via an HTTP proxy */ +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + BIT(socks5_gssapi_nec); /* Flag to support NEC SOCKS5 server */ +#endif + BIT(sasl_ir); /* Enable/disable SASL initial response */ + BIT(tcp_keepalive); /* use TCP keepalives */ + BIT(tcp_fastopen); /* use TCP Fast Open */ + BIT(ssl_enable_alpn);/* TLS ALPN extension? */ + BIT(path_as_is); /* allow dotdots? */ + BIT(pipewait); /* wait for multiplex status before starting a new + connection */ + BIT(suppress_connect_headers); /* suppress proxy CONNECT response headers + from user callbacks */ + BIT(dns_shuffle_addresses); /* whether to shuffle addresses before use */ +#ifndef CURL_DISABLE_PROXY + BIT(haproxyprotocol); /* whether to send HAProxy PROXY protocol v1 + header */ +#endif +#ifdef USE_UNIX_SOCKETS + BIT(abstract_unix_socket); +#endif + BIT(disallow_username_in_url); /* disallow username in URL */ +#ifndef CURL_DISABLE_DOH + BIT(doh); /* DNS-over-HTTPS enabled */ + BIT(doh_verifypeer); /* DoH certificate peer verification */ + BIT(doh_verifyhost); /* DoH certificate hostname verification */ + BIT(doh_verifystatus); /* DoH certificate status verification */ +#endif + BIT(http09_allowed); /* allow HTTP/0.9 responses */ +#ifndef CURL_DISABLE_WEBSOCKETS + BIT(ws_raw_mode); + BIT(ws_no_auto_pong); +#endif + BIT(post301); /* keep POSTs as POSTs after a 301 request */ + BIT(post302); /* keep POSTs as POSTs after a 302 request */ + BIT(post303); /* keep POSTs as POSTs after a 303 request */ +}; + +#ifndef CURL_DISABLE_MIME +#define IS_MIME_POST(a) \ + ((a)->set.mimepostp && ((a)->set.mimepostp->kind != MIMEKIND_NONE)) +#else +#define IS_MIME_POST(a) FALSE +#endif + +/* callback that gets called when the transfer `data` is done and + * `data->master_mid` is set to an existing easy handle. */ +typedef void multi_sub_xfer_done_cb(struct Curl_easy *data, + struct Curl_easy *master, + CURLcode result); + +/* + * The 'connectdata' struct MUST have all the connection oriented stuff as we + * may have several simultaneous connections and connection structs in memory. + * + * The 'struct UserDefined' must only contain data that is set once to go for + * many (perhaps) independent connections. Values that are generated or + * calculated internally for the "session handle" must be defined within the + * 'struct UrlState' instead. + */ + +struct Curl_easy { + /* First a simple identifier to more easily detect if a user mixes up this + easy handle with a multi handle. Set this to CURLEASY_MAGIC_NUMBER */ + uint32_t magic; + /* once an easy handle is added to a multi, either explicitly by the + * libcurl application or implicitly during `curl_easy_perform()`, + * a unique identifier inside this one multi instance. */ + uint32_t mid; + CURLMstate mstate; /* the handle's state */ + CURLcode result; /* previous result */ + + struct connectdata *conn; + struct Curl_multi *multi; /* if non-NULL, points to the multi handle + struct to which this "belongs" when used by + the multi interface */ + struct Curl_eapi_stack callstack; /* easy api calls ongoing */ + + struct Curl_share *share; /* Share, handles global variable mutexing */ + + struct Curl_multi *multi_easy; /* if non-NULL, points to the multi handle + struct to which this "belongs" when used + by the easy interface */ + struct Curl_message msg; /* A single posted message. */ + + /* once an easy handle is tied to a connection pool a non-negative number to + distinguish this transfer from other using the same pool. For easier + tracking in log output. This may wrap around after CURL_OFF_T_MAX to 0 + again, so it has no uniqueness guarantee for large processings. Note: it + has no uniqueness either IFF more than one connection pool is used by the + libcurl application. */ + curl_off_t id; + uint32_t master_mid; /* if set, this transfer belongs to a master */ + multi_sub_xfer_done_cb *sub_xfer_done; + + /* `meta_hash` is a general key-value store for implementations + * with the lifetime of the easy handle. + * Elements need to be added with their own destructor to be invoked when + * the easy handle is cleaned up (see Curl_hash_add2()).*/ + struct Curl_hash meta_hash; + +#ifdef USE_LIBPSL + struct PslCache *psl; /* The associated PSL cache. */ +#endif + struct SingleRequest req; /* Request-specific data */ + struct UserDefined set; /* values set by the libcurl user */ +#ifndef CURL_DISABLE_COOKIES + struct CookieInfo *cookies; /* the cookies, read from files and servers. + NOTE that the 'cookie' field in the + UserDefined struct defines if the "engine" + is to be used or not. */ +#endif +#ifndef CURL_DISABLE_HSTS + struct hsts *hsts; +#endif +#ifndef CURL_DISABLE_ALTSVC + struct altsvcinfo *asi; /* the alt-svc cache */ +#endif + struct Progress progress; /* for all the progress meter data */ + struct UrlState state; /* struct for fields used for state info and + other dynamic purposes */ +#ifndef CURL_DISABLE_FTP + struct WildcardData *wildcard; /* wildcard download state info */ +#endif + struct PureInfo info; /* stats, reports and info data */ + struct curl_tlssessioninfo tsi; /* Information about the TLS session, only + valid after a client has asked for it */ +}; + +#define CURL_EASY_STR(d, id) \ + Curl_u8_strset_get(&(d)->set.strings, (uint8_t)(id)) +#define CURL_EASY_STR_SET(d, id, s, slen) \ + Curl_u8_strset_setx(&(d)->set.strings, (uint8_t)(id), (s), (slen)) +#define CURL_EASY_STR_SETN(d, id, s) \ + Curl_u8_strset_setn(&(d)->set.strings, (uint8_t)(id), (s)) +#define CURL_EASY_STR_CLEAR(d, id) \ + Curl_u8_strset_unset(&(d)->set.strings, (uint8_t)(id)) +#define CURL_EASY_STR_CLEAR0(d, id) \ + Curl_u8_strset_unset0(&(d)->set.strings, (uint8_t)(id)) + +#define LIBCURL_NAME "libcurl" + +#endif /* HEADER_CURL_URLDATA_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/cleartext.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/cleartext.c new file mode 100644 index 0000000000..ca0c9967ff --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/cleartext.c @@ -0,0 +1,112 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC4616 PLAIN authentication + * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt> + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_POP3) || \ + (!defined(CURL_DISABLE_LDAP) && defined(USE_OPENLDAP)) + +#include "vauth/vauth.h" + +/* + * Curl_auth_create_plain_message() + * + * This is used to generate an already encoded PLAIN message ready + * for sending to the recipient. + * + * Parameters: + * + * creds [in] - The credentials. + * passwd [in] - The password. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_plain_message(struct Curl_creds *creds, + struct bufref *out) +{ + size_t len; + char *auth; + + size_t zlen = strlen(Curl_creds_sasl_authzid(creds)); + size_t clen = strlen(Curl_creds_user(creds)); + size_t plen = strlen(Curl_creds_passwd(creds)); + + if((zlen > CURL_MAX_INPUT_LENGTH) || (clen > CURL_MAX_INPUT_LENGTH) || + (plen > CURL_MAX_INPUT_LENGTH)) + return CURLE_TOO_LARGE; + + len = zlen + clen + plen + 2; + + auth = curl_maprintf("%s%c%s%c%s", + Curl_creds_sasl_authzid(creds), '\0', + Curl_creds_user(creds), '\0', + Curl_creds_passwd(creds)); + if(!auth) + return CURLE_OUT_OF_MEMORY; + Curl_bufref_set(out, auth, len, curl_free); + return CURLE_OK; +} + +/* + * Curl_auth_create_login_message() + * + * This is used to generate an already encoded LOGIN message containing the + * username or password ready for sending to the recipient. + * + * Parameters: + * + * value [in] - The username or user's password. + * out [out] - The result storage. + * + * Returns void. + */ +void Curl_auth_create_login_message(const char *value, struct bufref *out) +{ + Curl_bufref_set(out, value, strlen(value), NULL); +} + +/* + * Curl_auth_create_external_message() + * + * This is used to generate an already encoded EXTERNAL message containing + * the username ready for sending to the recipient. + * + * Parameters: + * + * user [in] - The username. + * out [out] - The result storage. + * + * Returns void. + */ +void Curl_auth_create_external_message(const char *user, struct bufref *out) +{ + /* This is the same formatting as the login message */ + Curl_auth_create_login_message(user, out); +} + +#endif /* if no users */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/cram.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/cram.c new file mode 100644 index 0000000000..023c31b58b --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/cram.c @@ -0,0 +1,87 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC2195 CRAM-MD5 authentication + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_DIGEST_AUTH + +#include "vauth/vauth.h" +#include "curl_hmac.h" +#include "curl_md5.h" + +/* + * Curl_auth_create_cram_md5_message() + * + * This is used to generate a CRAM-MD5 response message ready for sending to + * the recipient. + * + * Parameters: + * + * chlg [in] - The challenge. + * userp [in] - The username. + * passwdp [in] - The user's password. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_cram_md5_message(const struct bufref *chlg, + struct Curl_creds *creds, + struct bufref *out) +{ + struct HMAC_context *ctxt; + unsigned char digest[MD5_DIGEST_LEN]; + char *response; + const char *user = Curl_creds_user(creds); + const char *passwd = Curl_creds_passwd(creds); + + /* Compute the digest using the password as the key */ + ctxt = Curl_HMAC_init(&Curl_HMAC_MD5, + (const unsigned char *)passwd, + curlx_uztoui(strlen(passwd))); + if(!ctxt) + return CURLE_OUT_OF_MEMORY; + + /* Update the digest with the given challenge */ + if(Curl_bufref_len(chlg)) + Curl_HMAC_update(ctxt, Curl_bufref_uptr(chlg), + curlx_uztoui(Curl_bufref_len(chlg))); + + /* Finalise the digest */ + Curl_HMAC_final(ctxt, digest); + + /* Generate the response */ + response = curl_maprintf( + "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", + user, digest[0], digest[1], digest[2], digest[3], digest[4], + digest[5], digest[6], digest[7], digest[8], digest[9], digest[10], + digest[11], digest[12], digest[13], digest[14], digest[15]); + if(!response) + return CURLE_OUT_OF_MEMORY; + + Curl_bufref_set(out, response, strlen(response), curl_free); + return CURLE_OK; +} + +#endif /* !CURL_DISABLE_DIGEST_AUTH */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/digest.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/digest.c new file mode 100644 index 0000000000..748c0d8347 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/digest.c @@ -0,0 +1,1057 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC2831 DIGEST-MD5 authentication + * RFC7616 DIGEST-SHA256, DIGEST-SHA512-256 authentication + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_DIGEST_AUTH + +#include "vauth/vauth.h" +#include "vauth/digest.h" +#include "curlx/base64.h" +#include "curl_md5.h" +#include "curl_sha256.h" +#include "curl_sha512_256.h" +#include "curlx/strparse.h" +#include "rand.h" +#include "escape.h" + +#ifndef USE_WINDOWS_SSPI +#define SESSION_ALGO 1 /* for algos with this bit set */ + +#define ALGO_MD5 0 +#define ALGO_MD5SESS (ALGO_MD5 | SESSION_ALGO) +#define ALGO_SHA256 2 +#define ALGO_SHA256SESS (ALGO_SHA256 | SESSION_ALGO) +#define ALGO_SHA512_256 4 +#define ALGO_SHA512_256SESS (ALGO_SHA512_256 | SESSION_ALGO) + +#define DIGEST_QOP_VALUE_AUTH (1 << 0) +#define DIGEST_QOP_VALUE_AUTH_INT (1 << 1) +#define DIGEST_QOP_VALUE_AUTH_CONF (1 << 2) + +#define DIGEST_QOP_VALUE_STRING_AUTH "auth" +#define DIGEST_QOP_VALUE_STRING_AUTH_INT "auth-int" +#define DIGEST_QOP_VALUE_STRING_AUTH_CONF "auth-conf" +#endif + +bool Curl_auth_digest_get_pair(const char *str, char *value, char *content, + const char **endptr) +{ + int c; + bool starts_with_quote = FALSE; + bool escape = FALSE; + + for(c = DIGEST_MAX_VALUE_LENGTH - 1; (*str && (*str != '=') && c--);) + *value++ = *str++; + *value = 0; + + if('=' != *str++) + /* eek, no match */ + return FALSE; + + if('\"' == *str) { + /* This starts with a quote so it must end with one as well! */ + str++; + starts_with_quote = TRUE; + } + + for(c = DIGEST_MAX_CONTENT_LENGTH - 1; *str && c--; str++) { + if(!escape) { + switch(*str) { + case '\\': + if(starts_with_quote) { + /* the start of an escaped quote */ + escape = TRUE; + continue; + } + break; + + case ',': + if(!starts_with_quote) { + /* This signals the end of the content if we did not get a starting + quote and then we do "sloppy" parsing */ + c = 0; /* the end */ + continue; + } + break; + + case '\r': + case '\n': + /* end of string */ + if(starts_with_quote) + return FALSE; /* No closing quote */ + c = 0; + continue; + + case '\"': + if(starts_with_quote) { + /* end of string */ + c = 0; + continue; + } + else + return FALSE; + } + } + + escape = FALSE; + *content++ = *str; + } + if(escape) + return FALSE; /* No character after backslash */ + + *content = 0; + *endptr = str; + + return TRUE; +} + +#ifndef USE_WINDOWS_SSPI +/* Convert MD5 chunk to RFC2617 (section 3.1.3) -suitable ASCII string */ +static void auth_digest_md5_to_ascii( + const unsigned char *source, /* 16 bytes */ + unsigned char *dest) /* 33 bytes */ +{ + int i; + for(i = 0; i < 16; i++) + curl_msnprintf((char *)&dest[i * 2], 3, "%02x", source[i]); +} + +/* Convert sha256 or SHA-512/256 chunk to RFC7616 -suitable ASCII string */ +static void auth_digest_sha256_to_ascii( + const unsigned char *source, /* 32 bytes */ + unsigned char *dest) /* 65 bytes */ +{ + int i; + for(i = 0; i < 32; i++) + curl_msnprintf((char *)&dest[i * 2], 3, "%02x", source[i]); +} + +/* Perform quoted-string escaping as described in RFC2616 and its errata */ +static char *auth_digest_string_quoted(const char *s) +{ + struct dynbuf out; + curlx_dyn_init(&out, 2048); + if(!*s) /* for zero length input, make sure we return an empty string */ + return curlx_strdup(""); + while(*s) { + CURLcode result; + if(*s == '"' || *s == '\\') { + result = curlx_dyn_addn(&out, "\\", 1); + if(!result) + result = curlx_dyn_addn(&out, s, 1); + } + else if((*s < ' ') || (*s > 0x7e)) { + unsigned char buf[3] = { '%' }; + Curl_hexbyte(&buf[1], (unsigned char)*s); + result = curlx_dyn_addn(&out, buf, 3); + } + else + result = curlx_dyn_addn(&out, s, 1); + if(result) + return NULL; + s++; + } + return curlx_dyn_ptr(&out); +} + +/* Retrieves the value for a corresponding key from the challenge string + * returns TRUE if the key could be found, FALSE if it does not exist + */ +static bool auth_digest_get_key_value(const char *chlg, const char *key, + char *buf, size_t buflen) +{ + /* keyword=[value],keyword2=[value] + The values may or may not be quoted. + */ + + do { + struct Curl_str data; + struct Curl_str name; + + curlx_str_passblanks(&chlg); + + if(!curlx_str_until(&chlg, &name, 64, '=') && + !curlx_str_single(&chlg, '=')) { + /* this is the key, get the value, possibly quoted */ + int rc = curlx_str_quotedword(&chlg, &data, 256); + if(rc == STRE_BEGQUOTE) + /* try unquoted until comma */ + rc = curlx_str_until(&chlg, &data, 256, ','); + if(rc) + return FALSE; /* weird */ + + if(curlx_str_cmp(&name, key)) { + /* if this is our key, return the value */ + size_t len = curlx_strlen(&data); + const char *src = curlx_str(&data); + size_t i; + size_t outlen = 0; + + if(len >= buflen) + /* does not fit */ + return FALSE; + + for(i = 0; i < len; i++) { + if(src[i] == '\\' && i + 1 < len) { + i++; /* skip backslash */ + } + buf[outlen++] = src[i]; + } + buf[outlen] = 0; + return TRUE; + } + if(curlx_str_single(&chlg, ',')) + return FALSE; + } + else /* odd syntax */ + break; + } while(1); + + return FALSE; +} + +static void auth_digest_get_qop_values(const char *options, int *value) +{ + struct Curl_str out; + /* Initialize the output */ + *value = 0; + + while(!curlx_str_until(&options, &out, 32, ',')) { + if(curlx_str_casecompare(&out, DIGEST_QOP_VALUE_STRING_AUTH)) + *value |= DIGEST_QOP_VALUE_AUTH; + else if(curlx_str_casecompare(&out, DIGEST_QOP_VALUE_STRING_AUTH_INT)) + *value |= DIGEST_QOP_VALUE_AUTH_INT; + else if(curlx_str_casecompare(&out, DIGEST_QOP_VALUE_STRING_AUTH_CONF)) + *value |= DIGEST_QOP_VALUE_AUTH_CONF; + if(curlx_str_single(&options, ',')) + break; + } +} + +/* + * auth_decode_digest_md5_message() + * + * This is used internally to decode an already encoded DIGEST-MD5 challenge + * message into the separate attributes. + * + * Parameters: + * + * chlgref [in] - The challenge message. + * nonce [in/out] - The buffer where the nonce is stored. + * nlen [in] - The length of the nonce buffer. + * realm [in/out] - The buffer where the realm is stored. + * rlen [in] - The length of the realm buffer. + * alg [in/out] - The buffer where the algorithm is stored. + * alen [in] - The length of the algorithm buffer. + * qop [in/out] - The buffer where the qop-options is stored. + * qlen [in] - The length of the qop buffer. + * + * Returns CURLE_OK on success. + */ +static CURLcode auth_decode_digest_md5_message(const struct bufref *chlgref, + char *nonce, size_t nlen, + char *realm, size_t rlen, + char *alg, size_t alen, + char *qop, size_t qlen) +{ + const char *chlg = Curl_bufref_ptr(chlgref); + + /* Ensure we have a valid challenge message */ + if(!Curl_bufref_len(chlgref)) + return CURLE_BAD_CONTENT_ENCODING; + + /* Retrieve nonce string from the challenge */ + if(!auth_digest_get_key_value(chlg, "nonce", nonce, nlen)) + return CURLE_BAD_CONTENT_ENCODING; + + /* Retrieve realm string from the challenge */ + if(!auth_digest_get_key_value(chlg, "realm", realm, rlen)) { + /* Challenge does not have a realm, set empty string [RFC2831] page 6 */ + *realm = '\0'; + } + + /* Retrieve algorithm string from the challenge */ + if(!auth_digest_get_key_value(chlg, "algorithm", alg, alen)) + return CURLE_BAD_CONTENT_ENCODING; + + /* Retrieve qop-options string from the challenge */ + if(!auth_digest_get_key_value(chlg, "qop", qop, qlen)) + return CURLE_BAD_CONTENT_ENCODING; + + return CURLE_OK; +} + +/* + * Curl_auth_is_digest_supported() + * + * This is used to evaluate if DIGEST is supported. + * + * Parameters: None + * + * Returns TRUE as DIGEST as handled by libcurl. + */ +bool Curl_auth_is_digest_supported(void) +{ + return TRUE; +} + +/* + * Curl_auth_create_digest_md5_message() + * + * This is used to generate an already encoded DIGEST-MD5 response message + * ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * chlg [in] - The challenge message. + * userp [in] - The username. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data, + const struct bufref *chlg, + struct Curl_creds *creds, + const char *default_service, + struct bufref *out) +{ + const char *service = Curl_creds_has_sasl_service(creds) ? + Curl_creds_sasl_service(creds) : default_service; + size_t i; + struct MD5_context *ctxt; + const char *userp = Curl_creds_user(creds); + const char *passwdp = Curl_creds_passwd(creds); + char *response = NULL; + unsigned char digest[MD5_DIGEST_LEN]; + char HA1_hex[(2 * MD5_DIGEST_LEN) + 1]; + char HA2_hex[(2 * MD5_DIGEST_LEN) + 1]; + char resp_hash_hex[(2 * MD5_DIGEST_LEN) + 1]; + char nonce[64]; + char realm[128]; + char algorithm[64]; + char qop_options[64]; + int qop_values; + char cnonce[33]; + char nonceCount[] = "00000001"; + char method[] = "AUTHENTICATE"; + char qop[] = DIGEST_QOP_VALUE_STRING_AUTH; + char *spn = NULL; + char *qrealm; + char *qnonce; + char *quserp; + + /* Decode the challenge message */ + CURLcode result = auth_decode_digest_md5_message(chlg, + nonce, sizeof(nonce), + realm, sizeof(realm), + algorithm, + sizeof(algorithm), + qop_options, + sizeof(qop_options)); + if(result) + return result; + + /* We only support md5 sessions */ + if(strcmp(algorithm, "md5-sess")) + return CURLE_BAD_CONTENT_ENCODING; + + /* Get the qop-values from the qop-options */ + auth_digest_get_qop_values(qop_options, &qop_values); + + /* We only support auth quality-of-protection */ + if(!(qop_values & DIGEST_QOP_VALUE_AUTH)) + return CURLE_BAD_CONTENT_ENCODING; + + /* Generate 32 random hex chars, 32 bytes + 1 null-termination */ + result = Curl_rand_hex(data, (unsigned char *)cnonce, sizeof(cnonce)); + if(result) + return result; + + /* Good so far, now calculate A1 and H(A1) according to RFC 2831 */ + ctxt = Curl_MD5_init(&Curl_DIGEST_MD5); + if(!ctxt) + return CURLE_OUT_OF_MEMORY; + + Curl_MD5_update(ctxt, (const unsigned char *)userp, + curlx_uztoui(strlen(userp))); + Curl_MD5_update(ctxt, (const unsigned char *)":", 1); + Curl_MD5_update(ctxt, (const unsigned char *)realm, + curlx_uztoui(strlen(realm))); + Curl_MD5_update(ctxt, (const unsigned char *)":", 1); + Curl_MD5_update(ctxt, (const unsigned char *)passwdp, + curlx_uztoui(strlen(passwdp))); + Curl_MD5_final(ctxt, digest); + + ctxt = Curl_MD5_init(&Curl_DIGEST_MD5); + if(!ctxt) + return CURLE_OUT_OF_MEMORY; + + Curl_MD5_update(ctxt, (const unsigned char *)digest, MD5_DIGEST_LEN); + Curl_MD5_update(ctxt, (const unsigned char *)":", 1); + Curl_MD5_update(ctxt, (const unsigned char *)nonce, + curlx_uztoui(strlen(nonce))); + Curl_MD5_update(ctxt, (const unsigned char *)":", 1); + Curl_MD5_update(ctxt, (const unsigned char *)cnonce, + curlx_uztoui(strlen(cnonce))); + Curl_MD5_final(ctxt, digest); + + /* Convert calculated 16 octet hex into 32 bytes string */ + for(i = 0; i < MD5_DIGEST_LEN; i++) + curl_msnprintf(&HA1_hex[2 * i], 3, "%02x", digest[i]); + + /* Generate our SPN */ + spn = Curl_auth_build_spn(service, data->state.origin->hostname, NULL); + if(!spn) + return CURLE_OUT_OF_MEMORY; + + /* Calculate H(A2) */ + ctxt = Curl_MD5_init(&Curl_DIGEST_MD5); + if(!ctxt) { + curlx_free(spn); + + return CURLE_OUT_OF_MEMORY; + } + + Curl_MD5_update(ctxt, (const unsigned char *)method, + curlx_uztoui(strlen(method))); + Curl_MD5_update(ctxt, (const unsigned char *)":", 1); + Curl_MD5_update(ctxt, (const unsigned char *)spn, + curlx_uztoui(strlen(spn))); + Curl_MD5_final(ctxt, digest); + + for(i = 0; i < MD5_DIGEST_LEN; i++) + curl_msnprintf(&HA2_hex[2 * i], 3, "%02x", digest[i]); + + /* Now calculate the response hash */ + ctxt = Curl_MD5_init(&Curl_DIGEST_MD5); + if(!ctxt) { + curlx_free(spn); + + return CURLE_OUT_OF_MEMORY; + } + + Curl_MD5_update(ctxt, (const unsigned char *)HA1_hex, 2 * MD5_DIGEST_LEN); + Curl_MD5_update(ctxt, (const unsigned char *)":", 1); + Curl_MD5_update(ctxt, (const unsigned char *)nonce, + curlx_uztoui(strlen(nonce))); + Curl_MD5_update(ctxt, (const unsigned char *)":", 1); + + Curl_MD5_update(ctxt, (const unsigned char *)nonceCount, + curlx_uztoui(strlen(nonceCount))); + Curl_MD5_update(ctxt, (const unsigned char *)":", 1); + Curl_MD5_update(ctxt, (const unsigned char *)cnonce, + curlx_uztoui(strlen(cnonce))); + Curl_MD5_update(ctxt, (const unsigned char *)":", 1); + Curl_MD5_update(ctxt, (const unsigned char *)qop, + curlx_uztoui(strlen(qop))); + Curl_MD5_update(ctxt, (const unsigned char *)":", 1); + + Curl_MD5_update(ctxt, (const unsigned char *)HA2_hex, 2 * MD5_DIGEST_LEN); + Curl_MD5_final(ctxt, digest); + + for(i = 0; i < MD5_DIGEST_LEN; i++) + curl_msnprintf(&resp_hash_hex[2 * i], 3, "%02x", digest[i]); + + /* escape double quotes and backslashes in the username, realm and nonce as + necessary */ + qrealm = auth_digest_string_quoted(realm); + qnonce = auth_digest_string_quoted(nonce); + quserp = auth_digest_string_quoted(userp); + if(qrealm && qnonce && quserp) + /* Generate the response */ + response = curl_maprintf("username=\"%s\",realm=\"%s\",nonce=\"%s\"," + "cnonce=\"%s\",nc=\"%s\",digest-uri=\"%s\"," + "response=%s,qop=%s", + quserp, qrealm, qnonce, + cnonce, nonceCount, spn, resp_hash_hex, qop); + + curlx_free(qrealm); + curlx_free(qnonce); + curlx_free(quserp); + curlx_free(spn); + if(!response) + return CURLE_OUT_OF_MEMORY; + + /* Return the response. */ + Curl_bufref_set(out, response, strlen(response), curl_free); + return result; +} + +/* + * Curl_auth_decode_digest_http_message() + * + * This is used to decode an HTTP DIGEST challenge message into the separate + * attributes. + * + * Parameters: + * + * chlg [in] - The challenge message. + * digest [in/out] - The digest data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_digest_http_message(const char *chlg, + struct digestdata *digest) +{ + bool before = FALSE; /* got a nonce before */ + + /* If we already have received a nonce, keep that in mind */ + if(digest->nonce) + before = TRUE; + + /* Clean up any former leftovers and initialize to defaults */ + Curl_auth_digest_cleanup(digest); + + for(;;) { + char value[DIGEST_MAX_VALUE_LENGTH]; + char content[DIGEST_MAX_CONTENT_LENGTH]; + + /* Pass all additional spaces here */ + while(*chlg && ISBLANK(*chlg)) + chlg++; + + /* Extract a value=content pair */ + if(Curl_auth_digest_get_pair(chlg, value, content, &chlg)) { + if(curl_strequal(value, "nonce")) { + curlx_free(digest->nonce); + digest->nonce = curlx_strdup(content); + if(!digest->nonce) + return CURLE_OUT_OF_MEMORY; + } + else if(curl_strequal(value, "stale")) { + if(curl_strequal(content, "true")) { + digest->stale = TRUE; + digest->nc = 1; /* we make a new nonce now */ + } + } + else if(curl_strequal(value, "realm")) { + curlx_free(digest->realm); + digest->realm = curlx_strdup(content); + if(!digest->realm) + return CURLE_OUT_OF_MEMORY; + } + else if(curl_strequal(value, "opaque")) { + curlx_free(digest->opaque); + digest->opaque = curlx_strdup(content); + if(!digest->opaque) + return CURLE_OUT_OF_MEMORY; + } + else if(curl_strequal(value, "qop")) { + const char *token = content; + struct Curl_str out; + bool foundAuth = FALSE; + bool foundAuthInt = FALSE; + /* Pass leading spaces */ + while(*token && ISBLANK(*token)) + token++; + while(!curlx_str_until(&token, &out, 32, ',')) { + if(curlx_str_casecompare(&out, DIGEST_QOP_VALUE_STRING_AUTH)) + foundAuth = TRUE; + else if(curlx_str_casecompare(&out, + DIGEST_QOP_VALUE_STRING_AUTH_INT)) + foundAuthInt = TRUE; + if(curlx_str_single(&token, ',')) + break; + while(*token && ISBLANK(*token)) + token++; + } + + /* Select only auth or auth-int. Otherwise, ignore */ + if(foundAuth) { + curlx_free(digest->qop); + digest->qop = curlx_strdup(DIGEST_QOP_VALUE_STRING_AUTH); + if(!digest->qop) + return CURLE_OUT_OF_MEMORY; + } + else if(foundAuthInt) { + curlx_free(digest->qop); + digest->qop = curlx_strdup(DIGEST_QOP_VALUE_STRING_AUTH_INT); + if(!digest->qop) + return CURLE_OUT_OF_MEMORY; + } + } + else if(curl_strequal(value, "algorithm")) { + curlx_free(digest->algorithm); + digest->algorithm = curlx_strdup(content); + if(!digest->algorithm) + return CURLE_OUT_OF_MEMORY; + + if(curl_strequal(content, "MD5-sess")) + digest->algo = ALGO_MD5SESS; + else if(curl_strequal(content, "MD5")) + digest->algo = ALGO_MD5; + else if(curl_strequal(content, "SHA-256")) + digest->algo = ALGO_SHA256; + else if(curl_strequal(content, "SHA-256-SESS")) + digest->algo = ALGO_SHA256SESS; + else if(curl_strequal(content, "SHA-512-256")) { +#ifdef CURL_HAVE_SHA512_256 + digest->algo = ALGO_SHA512_256; +#else /* !CURL_HAVE_SHA512_256 */ + return CURLE_NOT_BUILT_IN; +#endif /* CURL_HAVE_SHA512_256 */ + } + else if(curl_strequal(content, "SHA-512-256-SESS")) { +#ifdef CURL_HAVE_SHA512_256 + digest->algo = ALGO_SHA512_256SESS; +#else /* !CURL_HAVE_SHA512_256 */ + return CURLE_NOT_BUILT_IN; +#endif /* CURL_HAVE_SHA512_256 */ + } + else + return CURLE_BAD_CONTENT_ENCODING; + } + else if(curl_strequal(value, "userhash")) { + if(curl_strequal(content, "true")) { + digest->userhash = TRUE; + } + } + else { + /* Unknown specifier, ignore it! */ + } + } + else + break; /* We are done here */ + + /* Pass all additional spaces here */ + while(*chlg && ISBLANK(*chlg)) + chlg++; + + /* Allow the list to be comma-separated */ + if(',' == *chlg) + chlg++; + } + + /* We had a nonce since before, and we got another one now without + 'stale=true'. This means we provided bad credentials in the previous + request */ + if(before && !digest->stale) + return CURLE_BAD_CONTENT_ENCODING; + + /* We got this header without a nonce, that is a bad Digest line! */ + if(!digest->nonce) + return CURLE_BAD_CONTENT_ENCODING; + + /* "<algo>-sess" protocol versions require "auth" or "auth-int" qop */ + if(!digest->qop && (digest->algo & SESSION_ALGO)) + return CURLE_BAD_CONTENT_ENCODING; + + return CURLE_OK; +} + +/* + * auth_create_digest_http_message() + * + * This is used to generate an HTTP DIGEST response message ready for sending + * to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * creds [in] - The credentials + * request [in] - The HTTP request. + * uripath [in] - The path of the HTTP uri. + * digest [in/out] - The digest data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result is stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +static CURLcode auth_create_digest_http_message( + struct Curl_easy *data, + struct Curl_creds *creds, + const unsigned char *request, + const unsigned char *uripath, + struct digestdata *digest, + char **outptr, size_t *outlen, + void (*convert_to_ascii)(const unsigned char *, unsigned char *), + CURLcode (*hash)(unsigned char *, const unsigned char *, const size_t)) +{ + CURLcode result; + const char *userp = Curl_creds_user(creds); + const char *passwdp = Curl_creds_passwd(creds); + unsigned char hashbuf[32]; /* 32 bytes/256 bits */ + unsigned char request_digest[65]; + unsigned char ha1[65]; /* 64 digits and 1 zero byte */ + unsigned char ha2[65]; /* 64 digits and 1 zero byte */ + char userh[65]; + char *cnonce = NULL; + size_t cnonce_sz = 0; + char *userp_quoted = NULL; + char *realm_quoted = NULL; + char *nonce_quoted = NULL; + char *hashthis = NULL; + char *uri_quoted = NULL; + struct dynbuf response; + *outptr = NULL; + + curlx_dyn_init(&response, 4096); /* arbitrary max */ + + memset(hashbuf, 0, sizeof(hashbuf)); + if(!digest->nc) + digest->nc = 1; + + if(!digest->cnonce) { + char cnoncebuf[12]; + result = Curl_rand_bytes(data, +#ifdef DEBUGBUILD + TRUE, +#endif + (unsigned char *)cnoncebuf, + sizeof(cnoncebuf)); + if(!result) + result = curlx_base64_encode((uint8_t *)cnoncebuf, sizeof(cnoncebuf), + &cnonce, &cnonce_sz); + if(result) + goto oom; + + digest->cnonce = cnonce; + } + + if(digest->userhash) { + char *hasht = curl_maprintf("%s:%s", userp, + digest->realm ? digest->realm : ""); + if(!hasht) { + result = CURLE_OUT_OF_MEMORY; + goto oom; + } + + result = hash(hashbuf, (unsigned char *)hasht, strlen(hasht)); + curlx_free(hasht); + if(result) + goto oom; + convert_to_ascii(hashbuf, (unsigned char *)userh); + } + + /* If the algorithm is "MD5" or unspecified (which then defaults to MD5): + + A1 = unq(username-value) ":" unq(realm-value) ":" passwd + + If the algorithm is "MD5-sess" then: + + A1 = H(unq(username-value) ":" unq(realm-value) ":" passwd) ":" + unq(nonce-value) ":" unq(cnonce-value) + */ + + hashthis = curl_maprintf("%s:%s:%s", userp, digest->realm ? + digest->realm : "", passwdp); + if(!hashthis) { + result = CURLE_OUT_OF_MEMORY; + goto oom; + } + + result = hash(hashbuf, (unsigned char *)hashthis, strlen(hashthis)); + curlx_free(hashthis); + if(result) + goto oom; + convert_to_ascii(hashbuf, ha1); + + if(digest->algo & SESSION_ALGO) { + /* nonce and cnonce are OUTSIDE the hash */ + char *tmp = curl_maprintf("%s:%s:%s", ha1, digest->nonce, digest->cnonce); + if(!tmp) { + result = CURLE_OUT_OF_MEMORY; + goto oom; + } + + result = hash(hashbuf, (unsigned char *)tmp, strlen(tmp)); + curlx_free(tmp); + if(result) + goto oom; + convert_to_ascii(hashbuf, ha1); + } + + /* If the "qop" directive's value is "auth" or is unspecified, then A2 is: + + A2 = Method ":" digest-uri-value + + If the "qop" value is "auth-int", then A2 is: + + A2 = Method ":" digest-uri-value ":" H(entity-body) + + (The "Method" value is the HTTP request method as specified in section + 5.1.1 of RFC 2616) + */ + + uri_quoted = auth_digest_string_quoted((const char *)uripath); + if(!uri_quoted) { + result = CURLE_OUT_OF_MEMORY; + goto oom; + } + + hashthis = curl_maprintf("%s:%s", request, uripath); + if(!hashthis) { + result = CURLE_OUT_OF_MEMORY; + goto oom; + } + + if(digest->qop && curl_strequal(digest->qop, "auth-int")) { + /* We do not support auth-int for PUT or POST */ + char hashed[65]; + char *hashthis2; + + result = hash(hashbuf, (const unsigned char *)"", 0); + if(result) { + curlx_free(hashthis); + goto oom; + } + convert_to_ascii(hashbuf, (unsigned char *)hashed); + + hashthis2 = curl_maprintf("%s:%s", hashthis, hashed); + curlx_free(hashthis); + hashthis = hashthis2; + if(!hashthis) { + result = CURLE_OUT_OF_MEMORY; + goto oom; + } + } + + result = hash(hashbuf, (unsigned char *)hashthis, strlen(hashthis)); + curlx_free(hashthis); + if(result) + goto oom; + convert_to_ascii(hashbuf, ha2); + + if(digest->qop) + hashthis = curl_maprintf("%s:%s:%08x:%s:%s:%s", ha1, digest->nonce, + (unsigned int)digest->nc, digest->cnonce, + digest->qop, ha2); + else + hashthis = curl_maprintf("%s:%s:%s", ha1, digest->nonce, ha2); + + if(!hashthis) { + result = CURLE_OUT_OF_MEMORY; + goto oom; + } + + result = hash(hashbuf, (unsigned char *)hashthis, strlen(hashthis)); + curlx_free(hashthis); + if(result) + goto oom; + convert_to_ascii(hashbuf, request_digest); + + /* For test case 64 (snooped from a Mozilla 1.3a request) + + Authorization: Digest username="testuser", realm="testrealm", \ + nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca" + + Digest parameters are all quoted strings. Username which is provided by + the user needs double quotes and backslashes within it escaped. + realm, nonce, and opaque needs backslashes as well as they were + de-escaped when copied from request header. cnonce is generated with + web-safe characters. uri is already percent encoded. nc is 8 hex + characters. algorithm and qop with standard values only contain web-safe + characters. + */ + userp_quoted = auth_digest_string_quoted(digest->userhash ? userh : userp); + if(!userp_quoted) { + result = CURLE_OUT_OF_MEMORY; + goto oom; + } + if(digest->realm) + realm_quoted = auth_digest_string_quoted(digest->realm); + else { + realm_quoted = curlx_malloc(1); + if(realm_quoted) + realm_quoted[0] = 0; + } + if(!realm_quoted) { + result = CURLE_OUT_OF_MEMORY; + goto oom; + } + + nonce_quoted = auth_digest_string_quoted(digest->nonce); + if(!nonce_quoted) { + result = CURLE_OUT_OF_MEMORY; + goto oom; + } + + if(digest->qop) { + result = curlx_dyn_addf(&response, "username=\"%s\", " + "realm=\"%s\", " + "nonce=\"%s\", " + "uri=\"%s\", " + "cnonce=\"%s\", " + "nc=%08x, " + "qop=%s, " + "response=\"%s\"", + userp_quoted, + realm_quoted, + nonce_quoted, + uri_quoted, + digest->cnonce, + (unsigned int)digest->nc, + digest->qop, + request_digest); + + /* Increment nonce-count to use another nc value for the next request */ + digest->nc++; + } + else { + result = curlx_dyn_addf(&response, "username=\"%s\", " + "realm=\"%s\", " + "nonce=\"%s\", " + "uri=\"%s\", " + "response=\"%s\"", + userp_quoted, + realm_quoted, + nonce_quoted, + uri_quoted, + request_digest); + } + if(result) + goto oom; + + /* Add the optional fields */ + if(digest->opaque) { + /* Append the opaque */ + char *opaque_quoted = auth_digest_string_quoted(digest->opaque); + if(!opaque_quoted) { + result = CURLE_OUT_OF_MEMORY; + goto oom; + } + result = curlx_dyn_addf(&response, ", opaque=\"%s\"", opaque_quoted); + curlx_free(opaque_quoted); + if(result) + goto oom; + } + + if(digest->algorithm) { + /* Append the algorithm */ + result = curlx_dyn_addf(&response, ", algorithm=%s", digest->algorithm); + if(result) + goto oom; + } + + if(digest->userhash) { + /* Append the userhash */ + result = curlx_dyn_add(&response, ", userhash=true"); + if(result) + goto oom; + } + + /* Return the output */ + *outptr = curlx_dyn_ptr(&response); + *outlen = curlx_dyn_len(&response); + result = CURLE_OK; + +oom: + curlx_free(nonce_quoted); + curlx_free(realm_quoted); + curlx_free(uri_quoted); + curlx_free(userp_quoted); + if(result) + curlx_dyn_free(&response); + return result; +} + +/* + * Curl_auth_create_digest_http_message() + * + * This is used to generate an HTTP DIGEST response message ready for sending + * to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The username. + * passwdp [in] - The user's password. + * request [in] - The HTTP request. + * uripath [in] - The path of the HTTP uri. + * digest [in/out] - The digest data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result is stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data, + struct Curl_creds *creds, + const unsigned char *request, + const unsigned char *uripath, + struct digestdata *digest, + char **outptr, size_t *outlen) +{ + if(digest->algo <= ALGO_MD5SESS) + return auth_create_digest_http_message(data, creds, + request, uripath, digest, + outptr, outlen, + auth_digest_md5_to_ascii, + Curl_md5it); + + if(digest->algo <= ALGO_SHA256SESS) + return auth_create_digest_http_message(data, creds, + request, uripath, digest, + outptr, outlen, + auth_digest_sha256_to_ascii, + Curl_sha256it); +#ifdef CURL_HAVE_SHA512_256 + if(digest->algo <= ALGO_SHA512_256SESS) + return auth_create_digest_http_message(data, creds, + request, uripath, digest, + outptr, outlen, + auth_digest_sha256_to_ascii, + Curl_sha512_256it); +#endif /* CURL_HAVE_SHA512_256 */ + + /* Should be unreachable */ + return CURLE_BAD_CONTENT_ENCODING; +} + +/* + * Curl_auth_digest_cleanup() + * + * This is used to clean up the digest specific data. + * + * Parameters: + * + * digest [in/out] - The digest data struct being cleaned up. + * + */ +void Curl_auth_digest_cleanup(struct digestdata *digest) +{ + Curl_peer_unlink(&digest->origin); + Curl_creds_unlink(&digest->creds); + curlx_safefree(digest->nonce); + curlx_safefree(digest->cnonce); + curlx_safefree(digest->realm); + curlx_safefree(digest->opaque); + curlx_safefree(digest->qop); + curlx_safefree(digest->algorithm); + + digest->nc = 0; + digest->algo = ALGO_MD5; /* default algorithm */ + digest->stale = FALSE; /* default means normal, not stale */ + digest->userhash = FALSE; +} +#endif /* !USE_WINDOWS_SSPI */ + +#endif /* !CURL_DISABLE_DIGEST_AUTH */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/digest.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/digest.h new file mode 100644 index 0000000000..5b8f3ae767 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/digest.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_DIGEST_H +#define HEADER_CURL_DIGEST_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_DIGEST_AUTH + +#define DIGEST_MAX_VALUE_LENGTH 256 +#define DIGEST_MAX_CONTENT_LENGTH 1024 + +/* This is used to extract the realm from a challenge message */ +bool Curl_auth_digest_get_pair(const char *str, char *value, char *content, + const char **endptr); + +#endif + +#endif /* HEADER_CURL_DIGEST_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/digest_sspi.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/digest_sspi.c new file mode 100644 index 0000000000..e3648e37b8 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/digest_sspi.c @@ -0,0 +1,637 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, <steve_holme@hotmail.com>. + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC2831 DIGEST-MD5 authentication + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_WINDOWS_SSPI) && !defined(CURL_DISABLE_DIGEST_AUTH) + +#include "creds.h" +#include "vauth/vauth.h" +#include "vauth/digest.h" +#include "curlx/multibyte.h" +#include "curl_trc.h" +#include "curlx/strdup.h" +#include "strcase.h" +#include "strerror.h" + +/* + * Curl_auth_is_digest_supported() + * + * This is used to evaluate if DIGEST is supported. + * + * Parameters: None + * + * Returns TRUE if DIGEST is supported by Windows SSPI. + */ +bool Curl_auth_is_digest_supported(void) +{ + PSecPkgInfo SecurityPackage; + SECURITY_STATUS status; + + /* Query the security package for Digest */ + status = + Curl_pSecFn->QuerySecurityPackageInfo( + CURL_UNCONST(TEXT(SP_NAME_DIGEST)), + &SecurityPackage); + + /* Release the package buffer as it is not required anymore */ + if(status == SEC_E_OK) { + Curl_pSecFn->FreeContextBuffer(SecurityPackage); + } + + return status == SEC_E_OK; +} + +/* + * Curl_auth_create_digest_md5_message() + * + * This is used to generate an already encoded DIGEST-MD5 response message + * ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * chlg [in] - The challenge message. + * userp [in] - The username in the format User or Domain\User. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data, + const struct bufref *chlg, + struct Curl_creds *creds, + const char *default_service, + struct bufref *out) +{ + CURLcode result = CURLE_OK; + TCHAR *spn = NULL; + size_t token_max = 0; + unsigned char *output_token = NULL; + CredHandle credentials; + CtxtHandle context; + PSecPkgInfo SecurityPackage; + SEC_WINNT_AUTH_IDENTITY_EX identity; + SEC_WINNT_AUTH_IDENTITY_EX *p_identity; + SecBuffer chlg_buf; + SecBuffer resp_buf; + SecBufferDesc chlg_desc; + SecBufferDesc resp_desc; + SECURITY_STATUS status; + unsigned long attrs; + const char *service = Curl_creds_has_sasl_service(creds) ? + Curl_creds_sasl_service(creds) : default_service; + + /* Ensure we have a valid challenge message */ + if(!Curl_bufref_len(chlg)) { + infof(data, "DIGEST-MD5 handshake failure (empty challenge message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Query the security package for DigestSSP */ + status = + Curl_pSecFn->QuerySecurityPackageInfo( + CURL_UNCONST(TEXT(SP_NAME_DIGEST)), + &SecurityPackage); + if(status != SEC_E_OK) { + failf(data, "SSPI: could not get auth info"); + return CURLE_AUTH_ERROR; + } + + token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + Curl_pSecFn->FreeContextBuffer(SecurityPackage); + + /* Allocate our response buffer */ + output_token = curlx_malloc(token_max); + if(!output_token) + return CURLE_OUT_OF_MEMORY; + + /* Generate our SPN */ + spn = Curl_auth_build_spn(service, data->state.origin->hostname, NULL); + if(!spn) { + curlx_free(output_token); + return CURLE_OUT_OF_MEMORY; + } + + if(Curl_creds_has_user(creds)) { + /* Populate our identity structure */ + result = Curl_create_sspi_identity(creds->user, creds->passwd, + &identity); + if(result) { + curlx_free(spn); + curlx_free(output_token); + return result; + } + + /* Allow proper cleanup of the identity structure */ + p_identity = &identity; + } + else + /* Use the current Windows user */ + p_identity = NULL; + + /* Acquire our credentials handle */ + status = Curl_pSecFn->AcquireCredentialsHandle(NULL, + CURL_UNCONST(TEXT(SP_NAME_DIGEST)), + SECPKG_CRED_OUTBOUND, NULL, + p_identity, NULL, NULL, + &credentials, NULL); + + if(status != SEC_E_OK) { + Curl_sspi_free_identity(p_identity); + curlx_free(spn); + curlx_free(output_token); + return CURLE_LOGIN_DENIED; + } + + /* Setup the challenge "input" security buffer */ + chlg_desc.ulVersion = SECBUFFER_VERSION; + chlg_desc.cBuffers = 1; + chlg_desc.pBuffers = &chlg_buf; + chlg_buf.BufferType = SECBUFFER_TOKEN; + chlg_buf.pvBuffer = CURL_UNCONST(Curl_bufref_ptr(chlg)); + chlg_buf.cbBuffer = curlx_uztoul(Curl_bufref_len(chlg)); + + /* Setup the response "output" security buffer */ + resp_desc.ulVersion = SECBUFFER_VERSION; + resp_desc.cBuffers = 1; + resp_desc.pBuffers = &resp_buf; + resp_buf.BufferType = SECBUFFER_TOKEN; + resp_buf.pvBuffer = output_token; + resp_buf.cbBuffer = curlx_uztoul(token_max); + + /* Generate our response message */ + status = Curl_pSecFn->InitializeSecurityContext(&credentials, NULL, spn, + 0, 0, 0, &chlg_desc, 0, + &context, &resp_desc, &attrs, + NULL); + + if(status == SEC_I_COMPLETE_NEEDED || + status == SEC_I_COMPLETE_AND_CONTINUE) + Curl_pSecFn->CompleteAuthToken(&credentials, &resp_desc); + else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) { + VERBOSE(char buffer[STRERROR_LEN]); + + Curl_pSecFn->FreeCredentialsHandle(&credentials); + Curl_sspi_free_identity(p_identity); + curlx_free(spn); + curlx_free(output_token); + + if(status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + + infof(data, "schannel: InitializeSecurityContext failed: %s", + Curl_sspi_strerror(status, buffer, sizeof(buffer))); + + return CURLE_AUTH_ERROR; + } + + /* Return the response. */ + Curl_bufref_set(out, output_token, resp_buf.cbBuffer, curl_free); + + /* Free our handles */ + Curl_pSecFn->DeleteSecurityContext(&context); + Curl_pSecFn->FreeCredentialsHandle(&credentials); + + /* Free the identity structure */ + Curl_sspi_free_identity(p_identity); + + /* Free the SPN */ + curlx_free(spn); + + return result; +} + +/* + * Curl_override_sspi_http_realm() + * + * This is used to populate the domain in an SSPI identity structure + * The realm is extracted from the challenge message and used as the + * domain if it is not already explicitly set. + * + * Parameters: + * + * chlg [in] - The challenge message. + * identity [in/out] - The identity structure. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_override_sspi_http_realm(const char *chlg, + SEC_WINNT_AUTH_IDENTITY_EX *identity) +{ + xcharp_u domain, dup_domain; + + /* If domain is blank or unset, check challenge message for realm */ + if(!identity->Domain || !identity->DomainLength) { + for(;;) { + char value[DIGEST_MAX_VALUE_LENGTH]; + char content[DIGEST_MAX_CONTENT_LENGTH]; + + /* Pass all additional spaces here */ + while(*chlg && ISBLANK(*chlg)) + chlg++; + + /* Extract a value=content pair */ + if(Curl_auth_digest_get_pair(chlg, value, content, &chlg)) { + if(curl_strequal(value, "realm")) { + + /* Setup identity's domain and length */ + domain.tchar_ptr = curlx_convert_UTF8_to_tchar(content); + if(!domain.tchar_ptr) + return CURLE_OUT_OF_MEMORY; + + dup_domain.tchar_ptr = curlx_tcsdup(domain.tchar_ptr); + if(!dup_domain.tchar_ptr) { + curlx_free(domain.tchar_ptr); + return CURLE_OUT_OF_MEMORY; + } + + curlx_free(identity->Domain); + identity->Domain = dup_domain.tbyte_ptr; + identity->DomainLength = curlx_uztoul(_tcslen(dup_domain.tchar_ptr)); + dup_domain.tchar_ptr = NULL; + + curlx_free(domain.tchar_ptr); + } + else { + /* Unknown specifier, ignore it! */ + } + } + else + break; /* We are done here */ + + /* Pass all additional spaces here */ + while(*chlg && ISBLANK(*chlg)) + chlg++; + + /* Allow the list to be comma-separated */ + if(',' == *chlg) + chlg++; + } + } + + return CURLE_OK; +} + +/* + * Curl_auth_decode_digest_http_message() + * + * This is used to decode an HTTP DIGEST challenge message into the separate + * attributes. + * + * Parameters: + * + * chlg [in] - The challenge message. + * digest [in/out] - The digest data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_digest_http_message(const char *chlg, + struct digestdata *digest) +{ + size_t chlglen = strlen(chlg); + + /* We had an input token before so if there is another one now that means we + provided bad credentials in the previous request or it is stale. */ + if(digest->input_token) { + bool stale = FALSE; + const char *p = chlg; + + /* Check for the 'stale' directive */ + for(;;) { + char value[DIGEST_MAX_VALUE_LENGTH]; + char content[DIGEST_MAX_CONTENT_LENGTH]; + + while(*p && ISBLANK(*p)) + p++; + + if(!Curl_auth_digest_get_pair(p, value, content, &p)) + break; + + if(curl_strequal(value, "stale") && + curl_strequal(content, "true")) { + stale = TRUE; + break; + } + + while(*p && ISBLANK(*p)) + p++; + + if(',' == *p) + p++; + } + + if(stale) + Curl_auth_digest_cleanup(digest); + else + return CURLE_LOGIN_DENIED; + } + + /* Store the challenge for use later */ + digest->input_token = (BYTE *)curlx_memdup(chlg, chlglen + 1); + if(!digest->input_token) + return CURLE_OUT_OF_MEMORY; + + digest->input_token_len = chlglen; + + return CURLE_OK; +} + +/* + * Curl_auth_create_digest_http_message() + * + * This is used to generate an HTTP DIGEST response message ready for sending + * to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The username in the format User or Domain\User. + * passwdp [in] - The user's password. + * request [in] - The HTTP request. + * uripath [in] - The path of the HTTP uri. + * digest [in/out] - The digest data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result is stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data, + struct Curl_creds *creds, + const unsigned char *request, + const unsigned char *uripath, + struct digestdata *digest, + char **outptr, size_t *outlen) +{ + size_t token_max; + char *resp; + BYTE *output_token; + size_t output_token_len = 0; + PSecPkgInfo SecurityPackage; + SecBuffer chlg_buf[5]; + SecBufferDesc chlg_desc; + SECURITY_STATUS status; + + /* Query the security package for DigestSSP */ + status = + Curl_pSecFn->QuerySecurityPackageInfo( + CURL_UNCONST(TEXT(SP_NAME_DIGEST)), + &SecurityPackage); + if(status != SEC_E_OK) { + failf(data, "SSPI: could not get auth info"); + return CURLE_AUTH_ERROR; + } + + token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + Curl_pSecFn->FreeContextBuffer(SecurityPackage); + + /* Allocate the output buffer according to the max token size as indicated + by the security package */ + output_token = curlx_malloc(token_max); + if(!output_token) { + return CURLE_OUT_OF_MEMORY; + } + + /* If the user/passwd that was used to make the identity for http_context + has changed then delete that context. */ + if(!Curl_creds_same(creds, digest->creds)) { + if(digest->http_context) { + Curl_pSecFn->DeleteSecurityContext(digest->http_context); + curlx_safefree(digest->http_context); + } + Curl_creds_unlink(&digest->creds); + } + + if(digest->http_context) { + chlg_desc.ulVersion = SECBUFFER_VERSION; + chlg_desc.cBuffers = 5; + chlg_desc.pBuffers = chlg_buf; + chlg_buf[0].BufferType = SECBUFFER_TOKEN; + chlg_buf[0].pvBuffer = NULL; + chlg_buf[0].cbBuffer = 0; + chlg_buf[1].BufferType = SECBUFFER_PKG_PARAMS; + chlg_buf[1].pvBuffer = CURL_UNCONST(request); + chlg_buf[1].cbBuffer = curlx_uztoul(strlen((const char *)request)); + chlg_buf[2].BufferType = SECBUFFER_PKG_PARAMS; + chlg_buf[2].pvBuffer = CURL_UNCONST(uripath); + chlg_buf[2].cbBuffer = curlx_uztoul(strlen((const char *)uripath)); + chlg_buf[3].BufferType = SECBUFFER_PKG_PARAMS; + chlg_buf[3].pvBuffer = NULL; + chlg_buf[3].cbBuffer = 0; + chlg_buf[4].BufferType = SECBUFFER_PADDING; + chlg_buf[4].pvBuffer = output_token; + chlg_buf[4].cbBuffer = curlx_uztoul(token_max); + + status = Curl_pSecFn->MakeSignature(digest->http_context, 0, &chlg_desc, + 0); + if(status == SEC_E_OK) + output_token_len = chlg_buf[4].cbBuffer; + else { /* delete the context so a new one can be made */ + infof(data, "digest_sspi: MakeSignature failed, error 0x%08lx", + (unsigned long)status); + Curl_pSecFn->DeleteSecurityContext(digest->http_context); + curlx_safefree(digest->http_context); + } + } + + if(!digest->http_context) { + CredHandle credentials; + SEC_WINNT_AUTH_IDENTITY_EX identity; + SEC_WINNT_AUTH_IDENTITY_EX *p_identity; + SecBuffer resp_buf; + SecBufferDesc resp_desc; + unsigned long attrs; + TCHAR *spn; + + /* free the credentials used to make the previous identity */ + Curl_creds_unlink(&digest->creds); + + if(Curl_creds_has_user(creds)) { + /* Populate our identity structure */ + if(Curl_create_sspi_identity(creds->user, creds->passwd, &identity)) { + curlx_free(output_token); + return CURLE_OUT_OF_MEMORY; + } + + /* Populate our identity domain */ + if(Curl_override_sspi_http_realm((const char *)digest->input_token, + &identity)) { + Curl_sspi_free_identity(&identity); + curlx_free(output_token); + return CURLE_OUT_OF_MEMORY; + } + + /* Allow proper cleanup of the identity structure */ + p_identity = &identity; + } + else + /* Use the current Windows user */ + p_identity = NULL; + + if(creds) + Curl_creds_link(&digest->creds, creds); + + /* Acquire our credentials handle */ + status = Curl_pSecFn->AcquireCredentialsHandle(NULL, + CURL_UNCONST(TEXT(SP_NAME_DIGEST)), + SECPKG_CRED_OUTBOUND, NULL, + p_identity, NULL, NULL, + &credentials, NULL); + if(status != SEC_E_OK) { + Curl_sspi_free_identity(p_identity); + curlx_free(output_token); + + return CURLE_LOGIN_DENIED; + } + + /* Setup the challenge "input" security buffer if present */ + chlg_desc.ulVersion = SECBUFFER_VERSION; + chlg_desc.cBuffers = 3; + chlg_desc.pBuffers = chlg_buf; + chlg_buf[0].BufferType = SECBUFFER_TOKEN; + chlg_buf[0].pvBuffer = digest->input_token; + chlg_buf[0].cbBuffer = curlx_uztoul(digest->input_token_len); + chlg_buf[1].BufferType = SECBUFFER_PKG_PARAMS; + chlg_buf[1].pvBuffer = CURL_UNCONST(request); + chlg_buf[1].cbBuffer = curlx_uztoul(strlen((const char *)request)); + chlg_buf[2].BufferType = SECBUFFER_PKG_PARAMS; + chlg_buf[2].pvBuffer = NULL; + chlg_buf[2].cbBuffer = 0; + + /* Setup the response "output" security buffer */ + resp_desc.ulVersion = SECBUFFER_VERSION; + resp_desc.cBuffers = 1; + resp_desc.pBuffers = &resp_buf; + resp_buf.BufferType = SECBUFFER_TOKEN; + resp_buf.pvBuffer = output_token; + resp_buf.cbBuffer = curlx_uztoul(token_max); + + spn = curlx_convert_UTF8_to_tchar((const char *)uripath); + if(!spn) { + Curl_pSecFn->FreeCredentialsHandle(&credentials); + + Curl_sspi_free_identity(p_identity); + curlx_free(output_token); + + return CURLE_OUT_OF_MEMORY; + } + + /* Allocate our new context handle */ + digest->http_context = curlx_calloc(1, sizeof(CtxtHandle)); + if(!digest->http_context) { + Curl_pSecFn->FreeCredentialsHandle(&credentials); + curlx_free(spn); + Curl_sspi_free_identity(p_identity); + curlx_free(output_token); + return CURLE_OUT_OF_MEMORY; + } + + /* Generate our response message */ + status = Curl_pSecFn->InitializeSecurityContext(&credentials, NULL, + spn, + ISC_REQ_USE_HTTP_STYLE, + 0, 0, + &chlg_desc, 0, + digest->http_context, + &resp_desc, &attrs, NULL); + curlx_free(spn); + + if(status == SEC_I_COMPLETE_NEEDED || + status == SEC_I_COMPLETE_AND_CONTINUE) + Curl_pSecFn->CompleteAuthToken(&credentials, &resp_desc); + else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) { + VERBOSE(char buffer[STRERROR_LEN]); + + Curl_pSecFn->FreeCredentialsHandle(&credentials); + + Curl_sspi_free_identity(p_identity); + curlx_free(output_token); + + curlx_safefree(digest->http_context); + + if(status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + + infof(data, "schannel: InitializeSecurityContext failed: %s", + Curl_sspi_strerror(status, buffer, sizeof(buffer))); + + return CURLE_AUTH_ERROR; + } + + output_token_len = resp_buf.cbBuffer; + + Curl_pSecFn->FreeCredentialsHandle(&credentials); + Curl_sspi_free_identity(p_identity); + } + + resp = curlx_memdup0((const char *)output_token, output_token_len); + curlx_free(output_token); + if(!resp) { + return CURLE_OUT_OF_MEMORY; + } + + /* Return the response */ + *outptr = resp; + *outlen = output_token_len; + return CURLE_OK; +} + +/* + * Curl_auth_digest_cleanup() + * + * This is used to clean up the digest specific data. + * + * Parameters: + * + * digest [in/out] - The digest data struct being cleaned up. + * + */ +void Curl_auth_digest_cleanup(struct digestdata *digest) +{ + /* Free the input token */ + curlx_safefree(digest->input_token); + + /* Reset any variables */ + digest->input_token_len = 0; + + /* Delete security context */ + if(digest->http_context) { + Curl_pSecFn->DeleteSecurityContext(digest->http_context); + curlx_safefree(digest->http_context); + } + + /* Free the copy of user/passwd used to make the identity for http_context */ + Curl_creds_unlink(&digest->creds); + Curl_peer_unlink(&digest->origin); +} + +#endif /* USE_WINDOWS_SSPI && !CURL_DISABLE_DIGEST_AUTH */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/gsasl.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/gsasl.c new file mode 100644 index 0000000000..37adba593d --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/gsasl.c @@ -0,0 +1,121 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Simon Josefsson, <simon@josefsson.org>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC5802 SCRAM-SHA-1 authentication + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_GSASL + +#include "vauth/vauth.h" +#include "curl_trc.h" + +#include <gsasl.h> + +#if GSASL_VERSION_NUMBER < 0x010600 +#error "libgsasl 1.6.0 or greater required" +#endif + +bool Curl_auth_gsasl_is_supported(struct Curl_easy *data, + const char *mech, + struct gsasldata *gsasl) +{ + int res; + + res = gsasl_init(&gsasl->ctx); + if(res != GSASL_OK) { + failf(data, "gsasl init: %s", gsasl_strerror(res)); + return FALSE; + } + + res = gsasl_client_start(gsasl->ctx, mech, &gsasl->client); + if(res != GSASL_OK) { + gsasl_done(gsasl->ctx); + gsasl->ctx = NULL; + return FALSE; + } + + return TRUE; +} + +CURLcode Curl_auth_gsasl_start(struct Curl_easy *data, + struct Curl_creds *creds, + struct gsasldata *gsasl) +{ +#if GSASL_VERSION_NUMBER >= 0x010b00 + int res; + res = +#endif + gsasl_property_set(gsasl->client, GSASL_AUTHID, creds->user); +#if GSASL_VERSION_NUMBER >= 0x010b00 + if(res != GSASL_OK) { + failf(data, "setting AUTHID failed: %s", gsasl_strerror(res)); + return CURLE_OUT_OF_MEMORY; + } +#endif + +#if GSASL_VERSION_NUMBER >= 0x010b00 + res = +#endif + gsasl_property_set(gsasl->client, GSASL_PASSWORD, creds->passwd); +#if GSASL_VERSION_NUMBER >= 0x010b00 + if(res != GSASL_OK) { + failf(data, "setting PASSWORD failed: %s", gsasl_strerror(res)); + return CURLE_OUT_OF_MEMORY; + } +#endif + + (void)data; + + return CURLE_OK; +} + +CURLcode Curl_auth_gsasl_token(struct Curl_easy *data, + const struct bufref *chlg, + struct gsasldata *gsasl, + struct bufref *out) +{ + int res; + char *response; + size_t outlen; + + res = gsasl_step(gsasl->client, Curl_bufref_ptr(chlg), Curl_bufref_len(chlg), + &response, &outlen); + if(res != GSASL_OK && res != GSASL_NEEDS_MORE) { + failf(data, "GSASL step: %s", gsasl_strerror(res)); + return CURLE_BAD_CONTENT_ENCODING; + } + + Curl_bufref_set(out, response, outlen, gsasl_free); + return CURLE_OK; +} + +void Curl_auth_gsasl_cleanup(struct gsasldata *gsasl) +{ + gsasl_finish(gsasl->client); + gsasl->client = NULL; + + gsasl_done(gsasl->ctx); + gsasl->ctx = NULL; +} +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/krb5_gssapi.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/krb5_gssapi.c new file mode 100644 index 0000000000..6d9a125177 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/krb5_gssapi.c @@ -0,0 +1,326 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, <steve_holme@hotmail.com>. + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(HAVE_GSSAPI) && defined(USE_KERBEROS5) + +#include "vauth/vauth.h" +#include "curl_sasl.h" +#include "curl_gssapi.h" +#include "curl_trc.h" + +#if defined(CURL_HAVE_DIAG) && defined(__APPLE__) && !defined(HAVE_GSSAPPLE) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + +/* + * Curl_auth_is_gssapi_supported() + * + * This is used to evaluate if GSSAPI (Kerberos V5) is supported. + * + * Parameters: None + * + * Returns TRUE if Kerberos V5 is supported by the GSS-API library. + */ +bool Curl_auth_is_gssapi_supported(void) +{ + return TRUE; +} + +/* + * Curl_auth_create_gssapi_user_message() + * + * This is used to generate an already encoded GSSAPI (Kerberos V5) user token + * message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The username. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in[ - The hostname. + * mutual_auth [in] - Flag specifying whether or not mutual authentication + * is enabled. + * chlg [in] - Optional challenge message. + * krb5 [in/out] - The Kerberos 5 data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_gssapi_user_message(struct Curl_easy *data, + struct Curl_creds *creds, + const char *default_service, + const char *host, + const bool mutual_auth, + const struct bufref *chlg, + struct kerberos5data *krb5, + struct bufref *out) +{ + CURLcode result = CURLE_OK; + OM_uint32 major_status; + OM_uint32 minor_status; + OM_uint32 unused_status; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + const char *service = Curl_creds_has_sasl_service(creds) ? + Curl_creds_sasl_service(creds) : default_service; + + if(!krb5->spn) { + gss_buffer_desc spn_token = GSS_C_EMPTY_BUFFER; + + /* Generate our SPN */ + char *spn = Curl_auth_build_spn(service, NULL, host); + if(!spn) + return CURLE_OUT_OF_MEMORY; + + /* Populate the SPN structure */ + spn_token.value = spn; + spn_token.length = strlen(spn); + + /* Import the SPN */ + major_status = gss_import_name(&minor_status, &spn_token, + GSS_C_NT_HOSTBASED_SERVICE, &krb5->spn); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_import_name() failed: ", + major_status, minor_status); + + curlx_free(spn); + + return CURLE_AUTH_ERROR; + } + + curlx_free(spn); + } + + if(chlg) { + if(!Curl_bufref_len(chlg)) { + infof(data, "GSSAPI handshake failure (empty challenge message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + input_token.value = CURL_UNCONST(Curl_bufref_ptr(chlg)); + input_token.length = Curl_bufref_len(chlg); + } + + major_status = Curl_gss_init_sec_context(data, + &minor_status, + &krb5->context, + krb5->spn, + &Curl_krb5_mech_oid, + GSS_C_NO_CHANNEL_BINDINGS, + &input_token, + &output_token, + mutual_auth, + NULL, + GSS_C_NO_CREDENTIAL); + + if(GSS_ERROR(major_status)) { + if(output_token.value) + gss_release_buffer(&unused_status, &output_token); + + Curl_gss_log_error(data, "gss_init_sec_context() failed: ", + major_status, minor_status); + + return CURLE_AUTH_ERROR; + } + + if(output_token.value && output_token.length) { + result = Curl_bufref_memdup0(out, output_token.value, output_token.length); + gss_release_buffer(&unused_status, &output_token); + } + else + Curl_bufref_set(out, mutual_auth ? "" : NULL, 0, NULL); + + return result; +} + +/* + * Curl_auth_create_gssapi_security_message() + * + * This is used to generate an already encoded GSSAPI (Kerberos V5) security + * token message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * authzid [in] - The authorization identity if some. + * chlg [in] - Optional challenge message. + * krb5 [in/out] - The Kerberos 5 data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_gssapi_security_message(struct Curl_easy *data, + const char *authzid, + const struct bufref *chlg, + struct kerberos5data *krb5, + struct bufref *out) +{ + CURLcode result = CURLE_OK; + size_t messagelen = 0; + unsigned char *message = NULL; + OM_uint32 major_status; + OM_uint32 minor_status; + OM_uint32 unused_status; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + unsigned char *indata; + gss_qop_t qop = GSS_C_QOP_DEFAULT; + unsigned int sec_layer = 0; + unsigned int max_size = 0; + + /* Ensure we have a valid challenge message */ + if(!Curl_bufref_len(chlg)) { + infof(data, "GSSAPI handshake failure (empty security message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Setup the challenge "input" security buffer */ + input_token.value = CURL_UNCONST(Curl_bufref_ptr(chlg)); + input_token.length = Curl_bufref_len(chlg); + + /* Decrypt the inbound challenge and obtain the qop */ + major_status = gss_unwrap(&minor_status, krb5->context, &input_token, + &output_token, NULL, &qop); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_unwrap() failed: ", + major_status, minor_status); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Not 4 octets long so fail as per RFC4752 Section 3.1 */ + if(output_token.length != 4) { + infof(data, "GSSAPI handshake failure (invalid security data)"); + gss_release_buffer(&unused_status, &output_token); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Extract the security layer and the maximum message size */ + indata = output_token.value; + sec_layer = indata[0]; + max_size = ((unsigned int)indata[1] << 16) | + ((unsigned int)indata[2] << 8) | indata[3]; + + /* Free the challenge as it is not required anymore */ + gss_release_buffer(&unused_status, &output_token); + + /* Process the security layer */ + if(!(sec_layer & GSSAUTH_P_NONE)) { + infof(data, "GSSAPI handshake failure (invalid security layer)"); + + return CURLE_BAD_CONTENT_ENCODING; + } + sec_layer &= GSSAUTH_P_NONE; /* We do not support a security layer */ + + /* Process the maximum message size the server can receive */ + if(max_size > 0) { + /* The server has told us it supports a maximum receive buffer, but as we + do not require one unless we are encrypting data, we tell the server + our receive buffer is zero. */ + max_size = 0; + } + + /* Allocate our message */ + messagelen = 4; + if(authzid) + messagelen += strlen(authzid); + message = curlx_malloc(messagelen); + if(!message) + return CURLE_OUT_OF_MEMORY; + + /* Populate the message with the security layer and client supported receive + message size. */ + message[0] = sec_layer & 0xFF; + message[1] = (max_size >> 16) & 0xFF; + message[2] = (max_size >> 8) & 0xFF; + message[3] = max_size & 0xFF; + + /* If given, append the authorization identity. */ + + if(authzid && *authzid) + memcpy(message + 4, authzid, messagelen - 4); + + /* Setup the "authentication data" security buffer */ + input_token.value = message; + input_token.length = messagelen; + + /* Encrypt the data */ + major_status = gss_wrap(&minor_status, krb5->context, 0, + GSS_C_QOP_DEFAULT, &input_token, NULL, + &output_token); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_wrap() failed: ", + major_status, minor_status); + curlx_free(message); + return CURLE_AUTH_ERROR; + } + + /* Return the response. */ + result = Curl_bufref_memdup0(out, output_token.value, output_token.length); + /* Free the output buffer */ + gss_release_buffer(&unused_status, &output_token); + + /* Free the message buffer */ + curlx_free(message); + + return result; +} + +/* + * Curl_auth_cleanup_gssapi() + * + * This is used to clean up the GSSAPI (Kerberos V5) specific data. + * + * Parameters: + * + * krb5 [in/out] - The Kerberos 5 data struct being cleaned up. + * + */ +void Curl_auth_cleanup_gssapi(struct kerberos5data *krb5) +{ + OM_uint32 minor_status; + + /* Free our security context */ + if(krb5->context != GSS_C_NO_CONTEXT) { + Curl_gss_delete_sec_context(&minor_status, &krb5->context, + GSS_C_NO_BUFFER); + krb5->context = GSS_C_NO_CONTEXT; + } + + /* Free the SPN */ + if(krb5->spn != GSS_C_NO_NAME) { + gss_release_name(&minor_status, &krb5->spn); + krb5->spn = GSS_C_NO_NAME; + } +} + +#if defined(CURL_HAVE_DIAG) && defined(__APPLE__) && !defined(HAVE_GSSAPPLE) +#pragma GCC diagnostic pop +#endif + +#endif /* HAVE_GSSAPI && USE_KERBEROS5 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/krb5_sspi.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/krb5_sspi.c new file mode 100644 index 0000000000..24d2421be6 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/krb5_sspi.c @@ -0,0 +1,456 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, <steve_holme@hotmail.com>. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_WINDOWS_SSPI) && defined(USE_KERBEROS5) + +#include "vauth/vauth.h" +#include "curl_trc.h" + +/* + * Curl_auth_is_gssapi_supported() + * + * This is used to evaluate if GSSAPI (Kerberos V5) is supported. + * + * Parameters: None + * + * Returns TRUE if Kerberos V5 is supported by Windows SSPI. + */ +bool Curl_auth_is_gssapi_supported(void) +{ + PSecPkgInfo SecurityPackage; + SECURITY_STATUS status; + + /* Query the security package for Kerberos */ + status = Curl_pSecFn->QuerySecurityPackageInfo( + CURL_UNCONST(TEXT(SP_NAME_KERBEROS)), + &SecurityPackage); + + /* Release the package buffer as it is not required anymore */ + if(status == SEC_E_OK) { + Curl_pSecFn->FreeContextBuffer(SecurityPackage); + } + + return status == SEC_E_OK; +} + +/* + * Curl_auth_create_gssapi_user_message() + * + * This is used to generate an already encoded GSSAPI (Kerberos V5) user token + * message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The username in the format User or Domain\User. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The hostname. + * mutual_auth [in] - Flag specifying whether or not mutual authentication + * is enabled. + * chlg [in] - Optional challenge message. + * krb5 [in/out] - The Kerberos 5 data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_gssapi_user_message(struct Curl_easy *data, + struct Curl_creds *creds, + const char *default_service, + const char *host, + const bool mutual_auth, + const struct bufref *chlg, + struct kerberos5data *krb5, + struct bufref *out) +{ + CURLcode result = CURLE_OK; + CtxtHandle context; + PSecPkgInfo SecurityPackage; + SecBuffer chlg_buf; + SecBuffer resp_buf; + SecBufferDesc chlg_desc; + SecBufferDesc resp_desc; + SECURITY_STATUS status; + unsigned long attrs; + const char *service = Curl_creds_has_sasl_service(creds) ? + Curl_creds_sasl_service(creds) : default_service; + + if(!krb5->spn) { + /* Generate our SPN */ + krb5->spn = Curl_auth_build_spn(service, host, NULL); + if(!krb5->spn) + return CURLE_OUT_OF_MEMORY; + } + + if(!krb5->output_token) { + /* Query the security package for Kerberos */ + status = Curl_pSecFn->QuerySecurityPackageInfo( + CURL_UNCONST(TEXT(SP_NAME_KERBEROS)), + &SecurityPackage); + if(status != SEC_E_OK) { + failf(data, "SSPI: could not get auth info"); + return CURLE_AUTH_ERROR; + } + + krb5->token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + Curl_pSecFn->FreeContextBuffer(SecurityPackage); + + /* Allocate our response buffer */ + krb5->output_token = curlx_malloc(krb5->token_max); + if(!krb5->output_token) + return CURLE_OUT_OF_MEMORY; + } + + if(!krb5->credentials) { + /* Do we have credentials to use or are we using single sign-on? */ + if(Curl_creds_has_user(creds)) { + /* Populate our identity structure */ + result = Curl_create_sspi_identity( + creds->user, creds->passwd, &krb5->identity); + if(result) + return result; + + /* Allow proper cleanup of the identity structure */ + krb5->p_identity = &krb5->identity; + } + else + /* Use the current Windows user */ + krb5->p_identity = NULL; + + /* Allocate our credentials handle */ + krb5->credentials = curlx_calloc(1, sizeof(CredHandle)); + if(!krb5->credentials) + return CURLE_OUT_OF_MEMORY; + + /* Acquire our credentials handle */ + status = Curl_pSecFn->AcquireCredentialsHandle(NULL, + CURL_UNCONST(TEXT(SP_NAME_KERBEROS)), + SECPKG_CRED_OUTBOUND, NULL, + krb5->p_identity, NULL, NULL, + krb5->credentials, NULL); + if(status != SEC_E_OK) { + curlx_safefree(krb5->credentials); + return CURLE_LOGIN_DENIED; + } + + /* Allocate our new context handle */ + krb5->context = curlx_calloc(1, sizeof(CtxtHandle)); + if(!krb5->context) + return CURLE_OUT_OF_MEMORY; + } + + if(chlg) { + if(!Curl_bufref_len(chlg)) { + infof(data, "GSSAPI handshake failure (empty challenge message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Setup the challenge "input" security buffer */ + chlg_desc.ulVersion = SECBUFFER_VERSION; + chlg_desc.cBuffers = 1; + chlg_desc.pBuffers = &chlg_buf; + chlg_buf.BufferType = SECBUFFER_TOKEN; + chlg_buf.pvBuffer = CURL_UNCONST(Curl_bufref_ptr(chlg)); + chlg_buf.cbBuffer = curlx_uztoul(Curl_bufref_len(chlg)); + } + + /* Setup the response "output" security buffer */ + resp_desc.ulVersion = SECBUFFER_VERSION; + resp_desc.cBuffers = 1; + resp_desc.pBuffers = &resp_buf; + resp_buf.BufferType = SECBUFFER_TOKEN; + resp_buf.pvBuffer = krb5->output_token; + resp_buf.cbBuffer = curlx_uztoul(krb5->token_max); + + /* Generate our challenge-response message */ + status = Curl_pSecFn->InitializeSecurityContext(krb5->credentials, + chlg ? krb5->context : NULL, + krb5->spn, + (mutual_auth ? + ISC_REQ_MUTUAL_AUTH : 0), + 0, SECURITY_NATIVE_DREP, + chlg ? &chlg_desc : NULL, 0, + &context, + &resp_desc, &attrs, NULL); + + if(status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + + if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) + return CURLE_AUTH_ERROR; + + if(memcmp(&context, krb5->context, sizeof(context))) { + Curl_pSecFn->DeleteSecurityContext(krb5->context); + + memcpy(krb5->context, &context, sizeof(context)); + } + + if(resp_buf.cbBuffer) { + result = Curl_bufref_memdup0(out, resp_buf.pvBuffer, resp_buf.cbBuffer); + } + else if(mutual_auth) + Curl_bufref_set(out, "", 0, NULL); + else + Curl_bufref_set(out, NULL, 0, NULL); + + return result; +} + +/* + * Curl_auth_create_gssapi_security_message() + * + * This is used to generate an already encoded GSSAPI (Kerberos V5) security + * token message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * authzid [in] - The authorization identity if some. + * chlg [in] - The challenge message. + * krb5 [in/out] - The Kerberos 5 data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_gssapi_security_message(struct Curl_easy *data, + const char *authzid, + const struct bufref *chlg, + struct kerberos5data *krb5, + struct bufref *out) +{ + CURLcode result = CURLE_OK; + size_t offset = 0; + size_t messagelen = 0; + size_t appdatalen = 0; + unsigned char *trailer = NULL; + unsigned char *message = NULL; + unsigned char *padding = NULL; + unsigned char *appdata = NULL; + SecBuffer input_buf[2]; + SecBuffer wrap_buf[3]; + SecBufferDesc input_desc; + SecBufferDesc wrap_desc; + unsigned char *indata; + unsigned long qop = 0; + unsigned long sec_layer = 0; + unsigned long max_size = 0; + SecPkgContext_Sizes sizes; + SECURITY_STATUS status; + + /* Ensure we have a valid challenge message */ + DEBUGASSERT(chlg); + if(!Curl_bufref_len(chlg)) { + infof(data, "GSSAPI handshake failure (empty security message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Get our response size information */ + status = Curl_pSecFn->QueryContextAttributes(krb5->context, + SECPKG_ATTR_SIZES, &sizes); + + if(status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + + if(status != SEC_E_OK) + return CURLE_AUTH_ERROR; + + /* Setup the "input" security buffer */ + input_desc.ulVersion = SECBUFFER_VERSION; + input_desc.cBuffers = 2; + input_desc.pBuffers = input_buf; + input_buf[0].BufferType = SECBUFFER_STREAM; + input_buf[0].pvBuffer = CURL_UNCONST(Curl_bufref_ptr(chlg)); + input_buf[0].cbBuffer = curlx_uztoul(Curl_bufref_len(chlg)); + input_buf[1].BufferType = SECBUFFER_DATA; + input_buf[1].pvBuffer = NULL; + input_buf[1].cbBuffer = 0; + + /* Decrypt the inbound challenge and obtain the qop. The encrypted message + is decrypted in place, overwriting the original contents of its buffer. + The SECBUFFER_DATA receives a pointer to the message in + SECBUFFER_STREAM. */ + status = Curl_pSecFn->DecryptMessage(krb5->context, &input_desc, 0, &qop); + if(status != SEC_E_OK) { + infof(data, "GSSAPI handshake failure (decryption failed)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Not 4 octets long so fail as per RFC4752 Section 3.1 */ + if(input_buf[1].cbBuffer != 4) { + infof(data, "GSSAPI handshake failure (invalid security data)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Extract the security layer and the maximum message size */ + indata = input_buf[1].pvBuffer; + sec_layer = indata[0]; + max_size = ((unsigned long)indata[1] << 16) | + ((unsigned long)indata[2] << 8) | indata[3]; + + /* Process the security layer */ + if(!(sec_layer & KERB_WRAP_NO_ENCRYPT)) { + infof(data, "GSSAPI handshake failure (invalid security layer)"); + return CURLE_BAD_CONTENT_ENCODING; + } + sec_layer &= KERB_WRAP_NO_ENCRYPT; /* We do not support a security layer */ + + /* Process the maximum message size the server can receive */ + if(max_size > 0) { + /* The server has told us it supports a maximum receive buffer, but as we + do not require one unless we are encrypting data, we tell the server + our receive buffer is zero. */ + max_size = 0; + } + + /* Allocate the trailer */ + trailer = curlx_malloc(sizes.cbSecurityTrailer); + if(!trailer) + return CURLE_OUT_OF_MEMORY; + + /* Allocate our message */ + messagelen = 4; + if(authzid) + messagelen += strlen(authzid); + message = curlx_malloc(messagelen); + if(!message) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + /* Populate the message with the security layer and client supported receive + message size. */ + message[0] = sec_layer & 0xFF; + message[1] = (max_size >> 16) & 0xFF; + message[2] = (max_size >> 8) & 0xFF; + message[3] = max_size & 0xFF; + + /* If given, append the authorization identity. */ + + if(authzid && *authzid) + memcpy(message + 4, authzid, messagelen - 4); + + /* Allocate the padding */ + padding = curlx_malloc(sizes.cbBlockSize); + if(!padding) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + /* Setup the "authentication data" security buffer */ + wrap_desc.ulVersion = SECBUFFER_VERSION; + wrap_desc.cBuffers = 3; + wrap_desc.pBuffers = wrap_buf; + wrap_buf[0].BufferType = SECBUFFER_TOKEN; + wrap_buf[0].pvBuffer = trailer; + wrap_buf[0].cbBuffer = sizes.cbSecurityTrailer; + wrap_buf[1].BufferType = SECBUFFER_DATA; + wrap_buf[1].pvBuffer = message; + wrap_buf[1].cbBuffer = curlx_uztoul(messagelen); + wrap_buf[2].BufferType = SECBUFFER_PADDING; + wrap_buf[2].pvBuffer = padding; + wrap_buf[2].cbBuffer = sizes.cbBlockSize; + + /* Encrypt the data */ + status = Curl_pSecFn->EncryptMessage(krb5->context, KERB_WRAP_NO_ENCRYPT, + &wrap_desc, 0); + if(status != SEC_E_OK) { + if(status == SEC_E_INSUFFICIENT_MEMORY) + result = CURLE_OUT_OF_MEMORY; + else + result = CURLE_AUTH_ERROR; + goto out; + } + + /* Allocate the encryption (wrap) buffer */ + appdatalen = wrap_buf[0].cbBuffer + wrap_buf[1].cbBuffer + + wrap_buf[2].cbBuffer; + appdata = curlx_malloc(appdatalen); + if(!appdata) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + /* Populate the encryption buffer */ + memcpy(appdata, wrap_buf[0].pvBuffer, wrap_buf[0].cbBuffer); + offset += wrap_buf[0].cbBuffer; + memcpy(appdata + offset, wrap_buf[1].pvBuffer, wrap_buf[1].cbBuffer); + offset += wrap_buf[1].cbBuffer; + memcpy(appdata + offset, wrap_buf[2].pvBuffer, wrap_buf[2].cbBuffer); + +out: + /* Free all of our local buffers */ + curlx_free(padding); + curlx_free(message); + curlx_free(trailer); + + if(result) + return result; + + /* Return the response. */ + Curl_bufref_set(out, appdata, appdatalen, curl_free); + return CURLE_OK; +} + +/* + * Curl_auth_cleanup_gssapi() + * + * This is used to clean up the GSSAPI (Kerberos V5) specific data. + * + * Parameters: + * + * krb5 [in/out] - The Kerberos 5 data struct being cleaned up. + * + */ +void Curl_auth_cleanup_gssapi(struct kerberos5data *krb5) +{ + /* Free our security context */ + if(krb5->context) { + Curl_pSecFn->DeleteSecurityContext(krb5->context); + curlx_safefree(krb5->context); + } + + /* Free our credentials handle */ + if(krb5->credentials) { + Curl_pSecFn->FreeCredentialsHandle(krb5->credentials); + curlx_safefree(krb5->credentials); + } + + /* Free our identity */ + Curl_sspi_free_identity(krb5->p_identity); + krb5->p_identity = NULL; + + /* Free the SPN and output token */ + curlx_safefree(krb5->spn); + curlx_safefree(krb5->output_token); + + /* Reset any variables */ + krb5->token_max = 0; +} + +#endif /* USE_WINDOWS_SSPI && USE_KERBEROS5 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/ntlm.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/ntlm.c new file mode 100644 index 0000000000..3f1ffb50ce --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/ntlm.c @@ -0,0 +1,860 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_NTLM) && !defined(USE_WINDOWS_SSPI) + +/* + * NTLM details: + * + * https://davenport.sourceforge.net/ntlm.html + * https://www.innovation.ch/java/ntlm.html + */ + +#define DEBUG_ME 0 + +#include "vauth/vauth.h" +#include "curl_trc.h" +#include "curl_ntlm_core.h" +#include "rand.h" +#include "curlx/strdup.h" +#include "curl_endian.h" + +/* "NTLMSSP" signature is always in ASCII regardless of the platform */ +#define NTLMSSP_SIGNATURE "\x4e\x54\x4c\x4d\x53\x53\x50" + +/* NTLM buffer fixed size, large enough for long user + host + domain */ +#define NTLM_BUFSIZE 1024 + +/* Flag bits definitions based on + https://davenport.sourceforge.net/ntlm.html */ + +#define NTLMFLAG_NEGOTIATE_UNICODE (1 << 0) +/* Indicates that Unicode strings are supported for use in security buffer + data. */ + +#define NTLMFLAG_NEGOTIATE_OEM (1 << 1) +/* Indicates that OEM strings are supported for use in security buffer data. */ + +#define NTLMFLAG_REQUEST_TARGET (1 << 2) +/* Requests that the server's authentication realm be included in the Type 2 + message. */ + +#if DEBUG_ME +/* unknown (1 << 3) */ +#define NTLMFLAG_NEGOTIATE_SIGN (1 << 4) +/* Specifies that authenticated communication between the client and server + should carry a digital signature (message integrity). */ + +#define NTLMFLAG_NEGOTIATE_SEAL (1 << 5) +/* Specifies that authenticated communication between the client and server + should be encrypted (message confidentiality). */ + +#define NTLMFLAG_NEGOTIATE_DATAGRAM_STYLE (1 << 6) +/* Indicates that datagram authentication is being used. */ + +#define NTLMFLAG_NEGOTIATE_LM_KEY (1 << 7) +/* Indicates that the LAN Manager session key should be used for signing and + sealing authenticated communications. */ +#endif + +#define NTLMFLAG_NEGOTIATE_NTLM_KEY (1 << 9) +/* Indicates that NTLM authentication is being used. */ + +#if DEBUG_ME +/* unknown (1 << 10) */ + +#define NTLMFLAG_NEGOTIATE_ANONYMOUS (1 << 11) +/* Sent by the client in the Type 3 message to indicate that an anonymous + context has been established. This also affects the response fields. */ + +#define NTLMFLAG_NEGOTIATE_DOMAIN_SUPPLIED (1 << 12) +/* Sent by the client in the Type 1 message to indicate that a desired + authentication realm is included in the message. */ + +#define NTLMFLAG_NEGOTIATE_WORKSTATION_SUPPLIED (1 << 13) +/* Sent by the client in the Type 1 message to indicate that the client + workstation's name is included in the message. */ + +#define NTLMFLAG_NEGOTIATE_LOCAL_CALL (1 << 14) +/* Sent by the server to indicate that the server and client are on the same + machine. Implies that the client may use a pre-established local security + context rather than responding to the challenge. */ +#endif + +#define NTLMFLAG_NEGOTIATE_ALWAYS_SIGN (1 << 15) +/* Indicates that authenticated communication between the client and server + should be signed with a "dummy" signature. */ + +#if DEBUG_ME +#define NTLMFLAG_TARGET_TYPE_DOMAIN (1 << 16) +/* Sent by the server in the Type 2 message to indicate that the target + authentication realm is a domain. */ + +#define NTLMFLAG_TARGET_TYPE_SERVER (1 << 17) +/* Sent by the server in the Type 2 message to indicate that the target + authentication realm is a server. */ + +#define NTLMFLAG_TARGET_TYPE_SHARE (1 << 18) +/* Sent by the server in the Type 2 message to indicate that the target + authentication realm is a share. Presumably, this is for share-level + authentication. Usage is unclear. */ +#endif + +#define NTLMFLAG_NEGOTIATE_NTLM2_KEY (1 << 19) +/* Indicates that the NTLM2 signing and sealing scheme should be used for + protecting authenticated communications. */ + +#if DEBUG_ME +#define NTLMFLAG_REQUEST_INIT_RESPONSE (1 << 20) +/* unknown purpose */ + +#define NTLMFLAG_REQUEST_ACCEPT_RESPONSE (1 << 21) +/* unknown purpose */ + +#define NTLMFLAG_REQUEST_NONNT_SESSION_KEY (1 << 22) +/* unknown purpose */ +#endif + +#define NTLMFLAG_NEGOTIATE_TARGET_INFO (1 << 23) +/* Sent by the server in the Type 2 message to indicate that it is including a + Target Information block in the message. */ + +#if DEBUG_ME +/* unknown (1<24) */ +/* unknown (1<25) */ +/* unknown (1<26) */ +/* unknown (1<27) */ +/* unknown (1<28) */ + +#define NTLMFLAG_NEGOTIATE_128 (1 << 29) +/* Indicates that 128-bit encryption is supported. */ + +#define NTLMFLAG_NEGOTIATE_KEY_EXCHANGE (1 << 30) +/* Indicates that the client provides an encrypted master key in + the "Session Key" field of the Type 3 message. */ + +#define NTLMFLAG_NEGOTIATE_56 (1 << 31) +/* Indicates that 56-bit encryption is supported. */ + +#define DEBUG_OUT(x) x +static void ntlm_print_flags(FILE *handle, unsigned long flags) +{ + if(flags & NTLMFLAG_NEGOTIATE_UNICODE) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_UNICODE "); + if(flags & NTLMFLAG_NEGOTIATE_OEM) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_OEM "); + if(flags & NTLMFLAG_REQUEST_TARGET) + curl_mfprintf(handle, "NTLMFLAG_REQUEST_TARGET "); + if(flags & (1 << 3)) + curl_mfprintf(handle, "NTLMFLAG_UNKNOWN_3 "); + if(flags & NTLMFLAG_NEGOTIATE_SIGN) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_SIGN "); + if(flags & NTLMFLAG_NEGOTIATE_SEAL) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_SEAL "); + if(flags & NTLMFLAG_NEGOTIATE_DATAGRAM_STYLE) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_DATAGRAM_STYLE "); + if(flags & NTLMFLAG_NEGOTIATE_LM_KEY) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_LM_KEY "); + if(flags & NTLMFLAG_NEGOTIATE_NTLM_KEY) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_NTLM_KEY "); + if(flags & (1 << 10)) + curl_mfprintf(handle, "NTLMFLAG_UNKNOWN_10 "); + if(flags & NTLMFLAG_NEGOTIATE_ANONYMOUS) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_ANONYMOUS "); + if(flags & NTLMFLAG_NEGOTIATE_DOMAIN_SUPPLIED) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_DOMAIN_SUPPLIED "); + if(flags & NTLMFLAG_NEGOTIATE_WORKSTATION_SUPPLIED) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_WORKSTATION_SUPPLIED "); + if(flags & NTLMFLAG_NEGOTIATE_LOCAL_CALL) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_LOCAL_CALL "); + if(flags & NTLMFLAG_NEGOTIATE_ALWAYS_SIGN) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_ALWAYS_SIGN "); + if(flags & NTLMFLAG_TARGET_TYPE_DOMAIN) + curl_mfprintf(handle, "NTLMFLAG_TARGET_TYPE_DOMAIN "); + if(flags & NTLMFLAG_TARGET_TYPE_SERVER) + curl_mfprintf(handle, "NTLMFLAG_TARGET_TYPE_SERVER "); + if(flags & NTLMFLAG_TARGET_TYPE_SHARE) + curl_mfprintf(handle, "NTLMFLAG_TARGET_TYPE_SHARE "); + if(flags & NTLMFLAG_NEGOTIATE_NTLM2_KEY) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_NTLM2_KEY "); + if(flags & NTLMFLAG_REQUEST_INIT_RESPONSE) + curl_mfprintf(handle, "NTLMFLAG_REQUEST_INIT_RESPONSE "); + if(flags & NTLMFLAG_REQUEST_ACCEPT_RESPONSE) + curl_mfprintf(handle, "NTLMFLAG_REQUEST_ACCEPT_RESPONSE "); + if(flags & NTLMFLAG_REQUEST_NONNT_SESSION_KEY) + curl_mfprintf(handle, "NTLMFLAG_REQUEST_NONNT_SESSION_KEY "); + if(flags & NTLMFLAG_NEGOTIATE_TARGET_INFO) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_TARGET_INFO "); + if(flags & (1 << 24)) + curl_mfprintf(handle, "NTLMFLAG_UNKNOWN_24 "); + if(flags & (1 << 25)) + curl_mfprintf(handle, "NTLMFLAG_UNKNOWN_25 "); + if(flags & (1 << 26)) + curl_mfprintf(handle, "NTLMFLAG_UNKNOWN_26 "); + if(flags & (1 << 27)) + curl_mfprintf(handle, "NTLMFLAG_UNKNOWN_27 "); + if(flags & (1 << 28)) + curl_mfprintf(handle, "NTLMFLAG_UNKNOWN_28 "); + if(flags & NTLMFLAG_NEGOTIATE_128) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_128 "); + if(flags & NTLMFLAG_NEGOTIATE_KEY_EXCHANGE) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_KEY_EXCHANGE "); + if(flags & NTLMFLAG_NEGOTIATE_56) + curl_mfprintf(handle, "NTLMFLAG_NEGOTIATE_56 "); +} + +static void ntlm_print_hex(FILE *handle, const char *buf, size_t len) +{ + const char *p = buf; + + (void)handle; + + curl_mfprintf(stderr, "0x"); + while(len-- > 0) + curl_mfprintf(stderr, "%02.2x", (unsigned int)*p++); +} +#else +#define DEBUG_OUT(x) Curl_nop_stmt +#endif + +/* + * ntlm_decode_type2_target() + * + * This is used to decode the "target info" in the NTLM type-2 message + * received. + * + * Parameters: + * + * data [in] - The session handle. + * type2ref [in] - The type-2 message. + * ntlm [in/out] - The NTLM data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +static CURLcode ntlm_decode_type2_target(struct Curl_easy *data, + const struct bufref *type2ref, + struct ntlmdata *ntlm) +{ + unsigned short target_info_len = 0; + unsigned int target_info_offset = 0; + const unsigned char *type2 = Curl_bufref_uptr(type2ref); + size_t type2len = Curl_bufref_len(type2ref); + + if(type2len >= 48) { + target_info_len = Curl_read16_le(&type2[40]); + target_info_offset = Curl_read32_le(&type2[44]); + if(target_info_len > 0) { + if((target_info_offset > type2len) || + (target_info_offset + target_info_len) > type2len || + target_info_offset < 48) { + infof(data, "NTLM handshake failure (bad type-2 message). " + "Target Info Offset Len is set incorrect by the peer"); + return CURLE_BAD_CONTENT_ENCODING; + } + + curlx_free(ntlm->target_info); /* replace any previous data */ + ntlm->target_info = curlx_memdup(&type2[target_info_offset], + target_info_len); + if(!ntlm->target_info) + return CURLE_OUT_OF_MEMORY; + } + } + + ntlm->target_info_len = target_info_len; + + return CURLE_OK; +} + +/* + NTLM message structure notes: + + A 'short' is a 'network short', a little-endian 16-bit unsigned value. + + A 'long' is a 'network long', a little-endian, 32-bit unsigned value. + + A 'security buffer' represents a triplet used to point to a buffer, + consisting of two shorts and one long: + + 1. A 'short' containing the length of the buffer content in bytes. + 2. A 'short' containing the allocated space for the buffer in bytes. + 3. A 'long' containing the offset to the start of the buffer in bytes, + from the beginning of the NTLM message. + */ + +/* + * Curl_auth_is_ntlm_supported() + * + * This is used to evaluate if NTLM is supported. + * + * Parameters: None + * + * Returns TRUE as NTLM as handled by libcurl. + */ +bool Curl_auth_is_ntlm_supported(void) +{ + return TRUE; +} + +/* + * Curl_auth_decode_ntlm_type2_message() + * + * This is used to decode an NTLM type-2 message. The raw NTLM message is + * checked * for validity before the appropriate data for creating a type-3 + * message is * written to the given NTLM data structure. + * + * Parameters: + * + * data [in] - The session handle. + * type2ref [in] - The type-2 message. + * ntlm [in/out] - The NTLM data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_ntlm_type2_message(struct Curl_easy *data, + const struct bufref *type2ref, + struct ntlmdata *ntlm) +{ + static const char type2_marker[] = { 0x02, 0x00, 0x00, 0x00 }; + + /* NTLM type-2 message structure: + + Index Description Content + 0 NTLMSSP Signature null-terminated ASCII "NTLMSSP" + (0x4e544c4d53535000) + 8 NTLM Message Type long (0x02000000) + 12 Target Name security buffer + 20 Flags long + 24 Challenge 8 bytes + (32) Context 8 bytes (two consecutive longs) (*) + (40) Target Information security buffer (*) + (48) OS Version Structure 8 bytes (*) + 32 (48) (56) Start of data block (*) + (*) -> Optional + */ + + CURLcode result = CURLE_OK; + const unsigned char *type2 = Curl_bufref_uptr(type2ref); + size_t type2len = Curl_bufref_len(type2ref); + + ntlm->flags = 0; + + if((type2len < 32) || + memcmp(type2, NTLMSSP_SIGNATURE, 8) || + memcmp(type2 + 8, type2_marker, sizeof(type2_marker))) { + /* This was not a good enough type-2 message */ + infof(data, "NTLM handshake failure (bad type-2 message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + ntlm->flags = Curl_read32_le(&type2[20]); + memcpy(ntlm->nonce, &type2[24], 8); + + if(ntlm->flags & NTLMFLAG_NEGOTIATE_TARGET_INFO) { + result = ntlm_decode_type2_target(data, type2ref, ntlm); + if(result) { + infof(data, "NTLM handshake failure (bad type-2 message)"); + return result; + } + } + + DEBUG_OUT({ + curl_mfprintf(stderr, "**** TYPE2 header flags=0x%08.8lx ", ntlm->flags); + ntlm_print_flags(stderr, ntlm->flags); + curl_mfprintf(stderr, "\n nonce="); + ntlm_print_hex(stderr, (char *)ntlm->nonce, 8); + curl_mfprintf(stderr, "\n****\n"); + curl_mfprintf(stderr, "**** Header %s\n ", header); + }); + + return result; +} + +/* copy the source to the destination and fill in zeroes in every + other destination byte! */ +static void unicodecpy(unsigned char *dest, const char *src, size_t length) +{ + size_t i; + for(i = 0; i < length; i++) { + dest[2 * i] = (unsigned char)src[i]; + dest[(2 * i) + 1] = '\0'; + } +} + +/* + * Curl_auth_create_ntlm_type1_message() + * + * This is used to generate an NTLM type-1 message ready for sending to the + * recipient using the appropriate compile time crypto API. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The username in the format User or Domain\User. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The hostname. + * ntlm [in/out] - The NTLM data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_ntlm_type1_message(struct Curl_easy *data, + struct Curl_creds *creds, + const char *default_service, + const char *host, + struct ntlmdata *ntlm, + struct bufref *out) +{ + /* NTLM type-1 message structure: + + Index Description Content + 0 NTLMSSP Signature null-terminated ASCII "NTLMSSP" + (0x4e544c4d53535000) + 8 NTLM Message Type long (0x01000000) + 12 Flags long + (16) Supplied Domain security buffer (*) + (24) Supplied Workstation security buffer (*) + (32) OS Version Structure 8 bytes (*) + (32) (40) Start of data block (*) + (*) -> Optional + */ + + const char *service = Curl_creds_has_sasl_service(creds) ? + Curl_creds_sasl_service(creds) : default_service; + size_t size; + + char *ntlmbuf; + const char *hostname = ""; /* empty */ + const char *domain = ""; /* empty */ + size_t hostlen = 0; + size_t domlen = 0; + size_t hostoff = 0; + size_t domoff = hostoff + hostlen; /* This is 0: remember that host and + domain are empty */ + (void)data; + (void)creds; + (void)service; + (void)host; + + /* Clean up any former leftovers and initialize to defaults */ + Curl_auth_cleanup_ntlm(ntlm); + + ntlmbuf = curl_maprintf(NTLMSSP_SIGNATURE "%c" + "\x01%c%c%c" /* 32-bit type = 1 */ + "%c%c%c%c" /* 32-bit NTLM flag field */ + "%c%c" /* domain length */ + "%c%c" /* domain allocated space */ + "%c%c" /* domain name offset */ + "%c%c" /* 2 zeroes */ + "%c%c" /* host length */ + "%c%c" /* host allocated space */ + "%c%c" /* hostname offset */ + "%c%c" /* 2 zeroes */ + "%s" /* hostname */ + "%s", /* domain string */ + 0, /* trailing zero */ + 0, 0, 0, /* part of type-1 long */ + + LONGQUARTET(NTLMFLAG_NEGOTIATE_OEM | + NTLMFLAG_REQUEST_TARGET | + NTLMFLAG_NEGOTIATE_NTLM_KEY | + NTLMFLAG_NEGOTIATE_NTLM2_KEY | + NTLMFLAG_NEGOTIATE_ALWAYS_SIGN), + SHORTPAIR(domlen), + SHORTPAIR(domlen), + SHORTPAIR(domoff), + 0, 0, + SHORTPAIR(hostlen), + SHORTPAIR(hostlen), + SHORTPAIR(hostoff), + 0, 0, + hostname, /* this is empty */ + domain /* this is empty */); + + if(!ntlmbuf) + return CURLE_OUT_OF_MEMORY; + + /* Initial packet length */ + size = 32 + hostlen + domlen; + + DEBUG_OUT({ + curl_mfprintf(stderr, "* TYPE1 header flags=0x%02.2x%02.2x%02.2x%02.2x " + "0x%08.8x ", + LONGQUARTET(NTLMFLAG_NEGOTIATE_OEM | + NTLMFLAG_REQUEST_TARGET | + NTLMFLAG_NEGOTIATE_NTLM_KEY | + NTLMFLAG_NEGOTIATE_NTLM2_KEY | + NTLMFLAG_NEGOTIATE_ALWAYS_SIGN), + NTLMFLAG_NEGOTIATE_OEM | + NTLMFLAG_REQUEST_TARGET | + NTLMFLAG_NEGOTIATE_NTLM_KEY | + NTLMFLAG_NEGOTIATE_NTLM2_KEY | + NTLMFLAG_NEGOTIATE_ALWAYS_SIGN); + ntlm_print_flags(stderr, + NTLMFLAG_NEGOTIATE_OEM | + NTLMFLAG_REQUEST_TARGET | + NTLMFLAG_NEGOTIATE_NTLM_KEY | + NTLMFLAG_NEGOTIATE_NTLM2_KEY | + NTLMFLAG_NEGOTIATE_ALWAYS_SIGN); + curl_mfprintf(stderr, "\n****\n"); + }); + + Curl_bufref_set(out, ntlmbuf, size, curl_free); + return CURLE_OK; +} + +/* + * Curl_auth_create_ntlm_type3_message() + * + * This is used to generate an already encoded NTLM type-3 message ready for + * sending to the recipient using the appropriate compile time crypto API. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The username in the format User or Domain\User. + * passwdp [in] - The user's password. + * ntlm [in/out] - The NTLM data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_ntlm_type3_message(struct Curl_easy *data, + struct Curl_creds *creds, + struct ntlmdata *ntlm, + struct bufref *out) +{ + /* NTLM type-3 message structure: + + Index Description Content + 0 NTLMSSP Signature null-terminated ASCII "NTLMSSP" + (0x4e544c4d53535000) + 8 NTLM Message Type long (0x03000000) + 12 LM/LMv2 Response security buffer + 20 NTLM/NTLMv2 Response security buffer + 28 Target Name security buffer + 36 Username security buffer + 44 Workstation Name security buffer + (52) Session Key security buffer (*) + (60) Flags long (*) + (64) OS Version Structure 8 bytes (*) + 52 (64) (72) Start of data block + (*) -> Optional + */ + + CURLcode result = CURLE_OK; + size_t size; + unsigned char ntlmbuf[NTLM_BUFSIZE]; + unsigned int lmrespoff; + unsigned char lmresp[24]; /* fixed-size */ + unsigned int ntrespoff; + unsigned int ntresplen = 24; + unsigned char ntresp[24]; /* fixed-size */ + const unsigned char *ptr_ntresp = &ntresp[0]; + unsigned char *ntlmv2resp = NULL; + bool unicode = (ntlm->flags & NTLMFLAG_NEGOTIATE_UNICODE); + /* The fixed hostname we provide, in order to not leak our real local host + name. Copy the name used by Firefox. */ + static const char host[] = "WORKSTATION"; + const char *userp = Curl_creds_user(creds); + const char *passwdp = Curl_creds_passwd(creds); + const char *user; + const char *domain = ""; + size_t hostoff = 0; + size_t useroff = 0; + size_t domoff = 0; + size_t hostlen = 0; + size_t userlen = 0; + size_t domlen = 0; + + memset(lmresp, 0, sizeof(lmresp)); + memset(ntresp, 0, sizeof(ntresp)); + user = strchr(userp, '\\'); + if(!user) + user = strchr(userp, '/'); + + if(user) { + domain = userp; + domlen = (user - domain); + user++; + } + else + user = userp; + + userlen = strlen(user); + hostlen = sizeof(host) - 1; + + if(ntlm->flags & NTLMFLAG_NEGOTIATE_NTLM2_KEY) { + unsigned char ntbuffer[0x18]; + unsigned char entropy[8]; + unsigned char ntlmv2hash[0x18]; + + /* Full NTLM version 2 + Although this cannot be negotiated, it is used here if available, as + servers featuring extended security are likely supporting also + NTLMv2. */ + result = Curl_rand(data, entropy, 8); + if(result) + return result; + + result = Curl_ntlm_core_mk_nt_hash(passwdp, ntbuffer); + if(result) + return result; + + result = Curl_ntlm_core_mk_ntlmv2_hash(user, userlen, domain, domlen, + ntbuffer, ntlmv2hash); + if(result) + return result; + + /* LMv2 response */ + result = Curl_ntlm_core_mk_lmv2_resp(ntlmv2hash, entropy, + &ntlm->nonce[0], lmresp); + if(result) + return result; + + /* NTLMv2 response */ + result = Curl_ntlm_core_mk_ntlmv2_resp(ntlmv2hash, entropy, + ntlm, &ntlmv2resp, &ntresplen); + if(result) + return result; + + ptr_ntresp = ntlmv2resp; + } + else { + + unsigned char ntbuffer[0x18]; + unsigned char lmbuffer[0x18]; + + /* NTLM version 1 */ + + result = Curl_ntlm_core_mk_nt_hash(passwdp, ntbuffer); + if(result) + return result; + + Curl_ntlm_core_lm_resp(ntbuffer, &ntlm->nonce[0], ntresp); + + result = Curl_ntlm_core_mk_lm_hash(passwdp, lmbuffer); + if(result) + return result; + + Curl_ntlm_core_lm_resp(lmbuffer, &ntlm->nonce[0], lmresp); + ntlm->flags &= ~(unsigned int)NTLMFLAG_NEGOTIATE_NTLM2_KEY; + + /* A safer but less compatible alternative is: + * Curl_ntlm_core_lm_resp(ntbuffer, &ntlm->nonce[0], lmresp); + * See https://davenport.sourceforge.net/ntlm.html#ntlmVersion2 */ + } + + if(unicode) { + domlen = domlen * 2; + userlen = userlen * 2; + hostlen = hostlen * 2; + } + + lmrespoff = 64; /* size of the message header */ + ntrespoff = lmrespoff + 0x18; + domoff = ntrespoff + ntresplen; + useroff = domoff + domlen; + hostoff = useroff + userlen; + + /* Create the big type-3 message binary blob */ + size = curl_msnprintf((char *)ntlmbuf, NTLM_BUFSIZE, + NTLMSSP_SIGNATURE "%c" + "\x03%c%c%c" /* 32-bit type = 3 */ + + "%c%c" /* LanManager length */ + "%c%c" /* LanManager allocated space */ + "%c%c" /* LanManager offset */ + "%c%c" /* 2 zeroes */ + + "%c%c" /* NT-response length */ + "%c%c" /* NT-response allocated space */ + "%c%c" /* NT-response offset */ + "%c%c" /* 2 zeroes */ + + "%c%c" /* domain length */ + "%c%c" /* domain allocated space */ + "%c%c" /* domain name offset */ + "%c%c" /* 2 zeroes */ + + "%c%c" /* user length */ + "%c%c" /* user allocated space */ + "%c%c" /* user offset */ + "%c%c" /* 2 zeroes */ + + "%c%c" /* host length */ + "%c%c" /* host allocated space */ + "%c%c" /* host offset */ + "%c%c" /* 2 zeroes */ + + "%c%c" /* session key length (unknown purpose) */ + "%c%c" /* session key allocated space + (unknown purpose) */ + "%c%c" /* session key offset (unknown purpose) */ + "%c%c" /* 2 zeroes */ + + "%c%c%c%c", /* flags */ + + /* domain string */ + /* user string */ + /* host string */ + /* LanManager response */ + /* NT response */ + + 0, /* null-termination */ + 0, 0, 0, /* type-3 long, the 24 upper bits */ + + SHORTPAIR(0x18), /* LanManager response length, + twice */ + SHORTPAIR(0x18), + SHORTPAIR(lmrespoff), + 0x0, 0x0, + + SHORTPAIR(ntresplen), /* NT-response length, twice */ + SHORTPAIR(ntresplen), + SHORTPAIR(ntrespoff), + 0x0, 0x0, + + SHORTPAIR(domlen), + SHORTPAIR(domlen), + SHORTPAIR(domoff), + 0x0, 0x0, + + SHORTPAIR(userlen), + SHORTPAIR(userlen), + SHORTPAIR(useroff), + 0x0, 0x0, + + SHORTPAIR(hostlen), + SHORTPAIR(hostlen), + SHORTPAIR(hostoff), + 0x0, 0x0, + + 0x0, 0x0, + 0x0, 0x0, + 0x0, 0x0, + 0x0, 0x0, + + LONGQUARTET(ntlm->flags)); + + DEBUGASSERT(size == 64); + DEBUGASSERT(size == (size_t)lmrespoff); + + /* We append the binary hashes */ + if(size < (NTLM_BUFSIZE - 0x18)) { + memcpy(&ntlmbuf[size], lmresp, 0x18); + size += 0x18; + } + + DEBUG_OUT({ + curl_mfprintf(stderr, "**** TYPE3 header lmresp="); + ntlm_print_hex(stderr, (char *)&ntlmbuf[lmrespoff], 0x18); + }); + + /* ntresplen + size should not be risking an integer overflow here */ + if(ntresplen + size > sizeof(ntlmbuf)) { + failf(data, "incoming NTLM message too big"); + result = CURLE_TOO_LARGE; + goto error; + } + DEBUGASSERT(size == (size_t)ntrespoff); + memcpy(&ntlmbuf[size], ptr_ntresp, ntresplen); + size += ntresplen; + + DEBUG_OUT({ + curl_mfprintf(stderr, "\n ntresp="); + ntlm_print_hex(stderr, (char *)&ntlmbuf[ntrespoff], ntresplen); + }); + + DEBUG_OUT({ + curl_mfprintf(stderr, "\n flags=0x%02.2x%02.2x%02.2x%02.2x 0x%08.8x ", + LONGQUARTET(ntlm->flags), ntlm->flags); + ntlm_print_flags(stderr, ntlm->flags); + curl_mfprintf(stderr, "\n****\n"); + }); + + /* Make sure that the domain, user and host strings fit in the + buffer before we copy them there. */ + if(size + userlen + domlen + hostlen >= NTLM_BUFSIZE) { + failf(data, "user + domain + hostname too big for NTLM"); + result = CURLE_TOO_LARGE; + goto error; + } + + DEBUGASSERT(size == domoff); + if(unicode) + unicodecpy(&ntlmbuf[size], domain, domlen / 2); + else + memcpy(&ntlmbuf[size], domain, domlen); + + size += domlen; + + DEBUGASSERT(size == useroff); + if(unicode) + unicodecpy(&ntlmbuf[size], user, userlen / 2); + else + memcpy(&ntlmbuf[size], user, userlen); + + size += userlen; + + DEBUGASSERT(size == hostoff); + if(unicode) + unicodecpy(&ntlmbuf[size], host, hostlen / 2); + else + memcpy(&ntlmbuf[size], host, hostlen); + + size += hostlen; + + /* Return the binary blob. */ + result = Curl_bufref_memdup0(out, ntlmbuf, size); + +error: + curlx_free(ntlmv2resp); /* Free the dynamic buffer allocated for NTLMv2 */ + + Curl_auth_cleanup_ntlm(ntlm); + + return result; +} + +/* + * Curl_auth_cleanup_ntlm() + * + * This is used to clean up the NTLM specific data. + * + * Parameters: + * + * ntlm [in/out] - The NTLM data struct being cleaned up. + * + */ +void Curl_auth_cleanup_ntlm(struct ntlmdata *ntlm) +{ + /* Free the target info */ + curlx_safefree(ntlm->target_info); + + /* Reset any variables */ + ntlm->target_info_len = 0; +} + +#endif /* USE_NTLM && !USE_WINDOWS_SSPI */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/ntlm_sspi.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/ntlm_sspi.c new file mode 100644 index 0000000000..85c7256025 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/ntlm_sspi.c @@ -0,0 +1,353 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_WINDOWS_SSPI) && defined(USE_NTLM) + +#include "vauth/vauth.h" +#include "curl_ntlm_core.h" +#include "curl_trc.h" +#include "curlx/strdup.h" + +/* + * Curl_auth_is_ntlm_supported() + * + * This is used to evaluate if NTLM is supported. + * + * Parameters: None + * + * Returns TRUE if NTLM is supported by Windows SSPI. + */ +bool Curl_auth_is_ntlm_supported(void) +{ + PSecPkgInfo SecurityPackage; + SECURITY_STATUS status; + + /* Query the security package for NTLM */ + status = Curl_pSecFn->QuerySecurityPackageInfo( + CURL_UNCONST(TEXT(SP_NAME_NTLM)), + &SecurityPackage); + + /* Release the package buffer as it is not required anymore */ + if(status == SEC_E_OK) { + Curl_pSecFn->FreeContextBuffer(SecurityPackage); + } + + return status == SEC_E_OK; +} + +/* + * Curl_auth_create_ntlm_type1_message() + * + * This is used to generate an already encoded NTLM type-1 message ready for + * sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The username in the format User or Domain\User. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The hostname. + * ntlm [in/out] - The NTLM data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_ntlm_type1_message(struct Curl_easy *data, + struct Curl_creds *creds, + const char *default_service, + const char *host, + struct ntlmdata *ntlm, + struct bufref *out) +{ + PSecPkgInfo SecurityPackage; + SecBuffer type_1_buf; + SecBufferDesc type_1_desc; + SECURITY_STATUS status; + unsigned long attrs; + const char *service = Curl_creds_has_sasl_service(creds) ? + Curl_creds_sasl_service(creds) : default_service; + + /* Clean up any former leftovers and initialize to defaults */ + Curl_auth_cleanup_ntlm(ntlm); + + /* Query the security package for NTLM */ + status = Curl_pSecFn->QuerySecurityPackageInfo( + CURL_UNCONST(TEXT(SP_NAME_NTLM)), + &SecurityPackage); + if(status != SEC_E_OK) { + failf(data, "SSPI: could not get auth info"); + return CURLE_AUTH_ERROR; + } + + ntlm->token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + Curl_pSecFn->FreeContextBuffer(SecurityPackage); + + /* Allocate our output buffer */ + ntlm->output_token = curlx_malloc(ntlm->token_max); + if(!ntlm->output_token) + return CURLE_OUT_OF_MEMORY; + + if(Curl_creds_has_user(creds)) { + CURLcode result; + + /* Populate our identity structure */ + result = Curl_create_sspi_identity( + creds->user, creds->passwd, &ntlm->identity); + if(result) + return result; + + /* Allow proper cleanup of the identity structure */ + ntlm->p_identity = &ntlm->identity; + } + else + /* Use the current Windows user */ + ntlm->p_identity = NULL; + + /* Allocate our credentials handle */ + ntlm->credentials = curlx_calloc(1, sizeof(CredHandle)); + if(!ntlm->credentials) + return CURLE_OUT_OF_MEMORY; + + /* Acquire our credentials handle */ + status = Curl_pSecFn->AcquireCredentialsHandle(NULL, + CURL_UNCONST(TEXT(SP_NAME_NTLM)), + SECPKG_CRED_OUTBOUND, NULL, + ntlm->p_identity, NULL, NULL, + ntlm->credentials, NULL); + if(status != SEC_E_OK) { + curlx_safefree(ntlm->credentials); + return CURLE_LOGIN_DENIED; + } + + /* Allocate our new context handle */ + ntlm->context = curlx_calloc(1, sizeof(CtxtHandle)); + if(!ntlm->context) + return CURLE_OUT_OF_MEMORY; + + ntlm->spn = Curl_auth_build_spn(service, host, NULL); + if(!ntlm->spn) + return CURLE_OUT_OF_MEMORY; + + /* Setup the type-1 "output" security buffer */ + type_1_desc.ulVersion = SECBUFFER_VERSION; + type_1_desc.cBuffers = 1; + type_1_desc.pBuffers = &type_1_buf; + type_1_buf.BufferType = SECBUFFER_TOKEN; + type_1_buf.pvBuffer = ntlm->output_token; + type_1_buf.cbBuffer = curlx_uztoul(ntlm->token_max); + + /* Generate our type-1 message */ + status = Curl_pSecFn->InitializeSecurityContext(ntlm->credentials, NULL, + ntlm->spn, + 0, 0, SECURITY_NETWORK_DREP, + NULL, 0, + ntlm->context, &type_1_desc, + &attrs, NULL); + if(status == SEC_I_COMPLETE_NEEDED || + status == SEC_I_COMPLETE_AND_CONTINUE) + Curl_pSecFn->CompleteAuthToken(ntlm->context, &type_1_desc); + else if(status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) + return CURLE_AUTH_ERROR; + + /* Return the response. */ + Curl_bufref_set(out, ntlm->output_token, type_1_buf.cbBuffer, NULL); + return CURLE_OK; +} + +/* + * Curl_auth_decode_ntlm_type2_message() + * + * This is used to decode an already encoded NTLM type-2 message. + * + * Parameters: + * + * data [in] - The session handle. + * type2 [in] - The type-2 message. + * ntlm [in/out] - The NTLM data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_ntlm_type2_message(struct Curl_easy *data, + const struct bufref *type2ref, + struct ntlmdata *ntlm) +{ + /* Ensure we have a valid type-2 message */ + if(!Curl_bufref_len(type2ref)) { + infof(data, "NTLM handshake failure (empty type-2 message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Store the challenge for later use */ + ntlm->input_token = curlx_memdup0(Curl_bufref_ptr(type2ref), + Curl_bufref_len(type2ref)); + if(!ntlm->input_token) + return CURLE_OUT_OF_MEMORY; + ntlm->input_token_len = Curl_bufref_len(type2ref); + + return CURLE_OK; +} + +/* + * Curl_auth_create_ntlm_type3_message() + * + * This is used to generate an already encoded NTLM type-3 message ready for + * sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The username in the format User or Domain\User. + * passwdp [in] - The user's password. + * ntlm [in/out] - The NTLM data struct being used and modified. + * out [out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_ntlm_type3_message(struct Curl_easy *data, + struct Curl_creds *creds, + struct ntlmdata *ntlm, + struct bufref *out) +{ + CURLcode result = CURLE_OK; + SecBuffer type_2_bufs[2]; + SecBuffer type_3_buf; + SecBufferDesc type_2_desc; + SecBufferDesc type_3_desc; + SECURITY_STATUS status; + unsigned long attrs; + SecPkgContext_Bindings pkgBindings = { 0, NULL }; + + (void)creds; + + /* Setup the type-2 "input" security buffer */ + type_2_desc.ulVersion = SECBUFFER_VERSION; + type_2_desc.cBuffers = 1; + type_2_desc.pBuffers = &type_2_bufs[0]; + type_2_bufs[0].BufferType = SECBUFFER_TOKEN; + type_2_bufs[0].pvBuffer = ntlm->input_token; + type_2_bufs[0].cbBuffer = curlx_uztoul(ntlm->input_token_len); + + /* SSL context comes from schannel. + * When extended protection is used in IIS server, + * we have to pass a second SecBuffer to the SecBufferDesc + * otherwise IIS does not pass the authentication (401 response). + * Minimum supported version is Windows 7. + * https://learn.microsoft.com/security-updates/SecurityAdvisories/2009/973811 + */ + if(ntlm->sslContext) { + status = Curl_pSecFn->QueryContextAttributes( + ntlm->sslContext, + SECPKG_ATTR_ENDPOINT_BINDINGS, + &pkgBindings + ); + if(status == SEC_E_OK) { + type_2_desc.cBuffers++; + type_2_bufs[1].BufferType = SECBUFFER_CHANNEL_BINDINGS; + type_2_bufs[1].cbBuffer = pkgBindings.BindingsLength; + type_2_bufs[1].pvBuffer = pkgBindings.Bindings; + } + } + + /* Setup the type-3 "output" security buffer */ + type_3_desc.ulVersion = SECBUFFER_VERSION; + type_3_desc.cBuffers = 1; + type_3_desc.pBuffers = &type_3_buf; + type_3_buf.BufferType = SECBUFFER_TOKEN; + type_3_buf.pvBuffer = ntlm->output_token; + type_3_buf.cbBuffer = curlx_uztoul(ntlm->token_max); + + /* Generate our type-3 message */ + status = Curl_pSecFn->InitializeSecurityContext(ntlm->credentials, + ntlm->context, + ntlm->spn, + 0, 0, SECURITY_NETWORK_DREP, + &type_2_desc, + 0, ntlm->context, + &type_3_desc, + &attrs, NULL); + + if(pkgBindings.Bindings) + Curl_pSecFn->FreeContextBuffer(pkgBindings.Bindings); + + if(status != SEC_E_OK) { + infof(data, "NTLM handshake failure (type-3 message): Status=0x%08lx", + (unsigned long)status); + + if(status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + + return CURLE_AUTH_ERROR; + } + + /* Return the response. */ + result = Curl_bufref_memdup0(out, ntlm->output_token, type_3_buf.cbBuffer); + Curl_auth_cleanup_ntlm(ntlm); + return result; +} + +/* + * Curl_auth_cleanup_ntlm() + * + * This is used to clean up the NTLM specific data. + * + * Parameters: + * + * ntlm [in/out] - The NTLM data struct being cleaned up. + * + */ +void Curl_auth_cleanup_ntlm(struct ntlmdata *ntlm) +{ + /* Free our security context */ + if(ntlm->context) { + Curl_pSecFn->DeleteSecurityContext(ntlm->context); + curlx_safefree(ntlm->context); + } + + /* Free our credentials handle */ + if(ntlm->credentials) { + Curl_pSecFn->FreeCredentialsHandle(ntlm->credentials); + curlx_safefree(ntlm->credentials); + } + + /* Free our identity */ + Curl_sspi_free_identity(ntlm->p_identity); + ntlm->p_identity = NULL; + + /* Free the input and output tokens */ + curlx_safefree(ntlm->input_token); + curlx_safefree(ntlm->output_token); + + /* Reset any variables */ + ntlm->token_max = 0; + + curlx_safefree(ntlm->spn); +} + +#endif /* USE_WINDOWS_SSPI && USE_NTLM */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/oauth2.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/oauth2.c new file mode 100644 index 0000000000..f597114638 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/oauth2.c @@ -0,0 +1,100 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC6749 OAuth 2.0 Authorization Framework + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_POP3) || \ + (!defined(CURL_DISABLE_LDAP) && defined(USE_OPENLDAP)) + +#include "vauth/vauth.h" + +/* + * Curl_auth_create_oauth_bearer_message() + * + * This is used to generate an OAuth 2.0 message ready for sending to the + * recipient. + * + * Parameters: + * + * user[in] - The username. + * host[in] - The hostname. + * port[in] - The port(when not Port 80). + * bearer[in] - The bearer token. + * out[out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_oauth_bearer_message(struct Curl_creds *creds, + const char *host, + const long port, + struct bufref *out) +{ + char *oauth; + + /* Generate the message */ + if(port == 0 || port == 80) + oauth = curl_maprintf("n,a=%s,\1host=%s\1auth=Bearer %s\1\1", + Curl_creds_user(creds), host, + Curl_creds_oauth_bearer(creds)); + else + oauth = curl_maprintf("n,a=%s,\1host=%s\1port=%ld\1auth=Bearer %s\1\1", + Curl_creds_user(creds), host, port, + Curl_creds_oauth_bearer(creds)); + if(!oauth) + return CURLE_OUT_OF_MEMORY; + + Curl_bufref_set(out, oauth, strlen(oauth), curl_free); + return CURLE_OK; +} + +/* + * Curl_auth_create_xoauth_bearer_message() + * + * This is used to generate a XOAuth 2.0 message ready for * sending to the + * recipient. + * + * Parameters: + * + * user[in] - The username. + * bearer[in] - The bearer token. + * out[out] - The result storage. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_xoauth_bearer_message(struct Curl_creds *creds, + struct bufref *out) +{ + /* Generate the message */ + char *xoauth = curl_maprintf("user=%s\1auth=Bearer %s\1\1", + Curl_creds_user(creds), + Curl_creds_oauth_bearer(creds)); + if(!xoauth) + return CURLE_OUT_OF_MEMORY; + + Curl_bufref_set(out, xoauth, strlen(xoauth), curl_free); + return CURLE_OK; +} +#endif /* disabled, no users */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/spnego_gssapi.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/spnego_gssapi.c new file mode 100644 index 0000000000..b2bc28fb3f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/spnego_gssapi.c @@ -0,0 +1,376 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC4178 Simple and Protected GSS-API Negotiation Mechanism + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(HAVE_GSSAPI) && defined(USE_SPNEGO) + +#include "vauth/vauth.h" +#include "curlx/base64.h" +#include "curl_gssapi.h" +#include "curl_trc.h" + +#if defined(CURL_HAVE_DIAG) && defined(__APPLE__) && !defined(HAVE_GSSAPPLE) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + +/* + * Curl_auth_is_spnego_supported() + * + * This is used to evaluate if SPNEGO (Negotiate) is supported. + * + * Parameters: None + * + * Returns TRUE if Negotiate supported by the GSS-API library. + */ +bool Curl_auth_is_spnego_supported(void) +{ + return TRUE; +} + +/* + * Curl_auth_decode_spnego_message() + * + * This is used to decode an already encoded SPNEGO (Negotiate) challenge + * message. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The username in the format User or Domain\User. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The hostname. + * chlg64 [in] - The optional base64 encoded challenge message. + * nego [in/out] - The Negotiate data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data, + struct Curl_creds *creds, + const char *default_service, + const char *host, + const char *chlg64, + struct negotiatedata *nego) +{ + CURLcode result = CURLE_OK; + size_t chlglen = 0; + unsigned char *chlg = NULL; + OM_uint32 major_status; + OM_uint32 minor_status; + OM_uint32 unused_status; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + gss_channel_bindings_t chan_bindings = GSS_C_NO_CHANNEL_BINDINGS; +#ifdef GSS_C_CHANNEL_BOUND_FLAG + struct gss_channel_bindings_struct chan; +#endif + + (void)creds; + + if(nego->context && nego->status == GSS_S_COMPLETE) { + /* We finished successfully our part of authentication, but server + * rejected it (since we are again here). Exit with an error since we + * cannot invent anything better */ + Curl_auth_cleanup_spnego(nego); + return CURLE_LOGIN_DENIED; + } + + if(!nego->spn) { + gss_buffer_desc spn_token = GSS_C_EMPTY_BUFFER; + + /* Generate our SPN */ + const char *service = Curl_creds_has_sasl_service(creds) ? + Curl_creds_sasl_service(creds) : default_service; + char *spn = Curl_auth_build_spn(service, NULL, host); + if(!spn) + return CURLE_OUT_OF_MEMORY; + + /* Populate the SPN structure */ + spn_token.value = spn; + spn_token.length = strlen(spn); + + /* Import the SPN */ + major_status = gss_import_name(&minor_status, &spn_token, + GSS_C_NT_HOSTBASED_SERVICE, + &nego->spn); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_import_name() failed: ", + major_status, minor_status); + + curlx_free(spn); + + return CURLE_AUTH_ERROR; + } + + curlx_free(spn); + } + + if(chlg64 && *chlg64) { + /* Decode the base-64 encoded challenge message */ + if(*chlg64 != '=') { + result = curlx_base64_decode(chlg64, &chlg, &chlglen); + if(result) + return result; + } + + /* Ensure we have a valid challenge message */ + if(!chlg) { + infof(data, "SPNEGO handshake failure (empty challenge message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Setup the challenge "input" security buffer */ + input_token.value = chlg; + input_token.length = chlglen; + } + + /* Set channel binding data if available */ +#ifdef GSS_C_CHANNEL_BOUND_FLAG + if(curlx_dyn_len(&nego->channel_binding_data)) { + memset(&chan, 0, sizeof(struct gss_channel_bindings_struct)); + chan.application_data.length = curlx_dyn_len(&nego->channel_binding_data); + chan.application_data.value = curlx_dyn_ptr(&nego->channel_binding_data); + chan_bindings = &chan; + } +#endif + +#ifdef HAVE_GSS_SET_NEG_MECHS + /* Acquire explicit credentials and restrict SPNEGO sub-mechanisms to + * exclude NTLM. We enumerate all available mechanisms and filter out + * the NTLMSSP OID, matching SSPI's "!ntlm". */ + if(nego->cred == GSS_C_NO_CREDENTIAL) { + /* OID 1.3.6.1.4.1.311.2.2.10 (NTLMSSP) */ + static const gss_OID_desc ntlmssp_oid = { + 10, CURL_UNCONST("\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a") + }; + gss_OID_set available_mechs = GSS_C_NO_OID_SET; + gss_OID_set filtered_mechs = GSS_C_NO_OID_SET; + + /* Acquire default credentials for SPNEGO */ + major_status = Curl_gss_acquire_cred(&minor_status, GSS_C_NO_NAME, + GSS_C_INDEFINITE, GSS_C_NO_OID_SET, + GSS_C_INITIATE, &nego->cred, NULL, NULL); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_acquire_cred() failed: ", + major_status, minor_status); + curlx_safefree(input_token.value); + return CURLE_AUTH_ERROR; + } + + /* Get all available mechanisms */ + major_status = Curl_gss_indicate_mechs(&minor_status, &available_mechs); + if(!GSS_ERROR(major_status)) { + /* Build a set excluding NTLMSSP */ + major_status = gss_create_empty_oid_set(&minor_status, &filtered_mechs); + if(!GSS_ERROR(major_status)) { + size_t i; + for(i = 0; i < available_mechs->count; i++) { + gss_OID oid = &available_mechs->elements[i]; + if(oid->length != ntlmssp_oid.length || + memcmp(oid->elements, ntlmssp_oid.elements, oid->length)) { + gss_add_oid_set_member(&minor_status, oid, &filtered_mechs); + } + } + /* Restrict SPNEGO to only use non-NTLM mechanisms */ + major_status = Curl_gss_set_neg_mechs(&minor_status, nego->cred, + filtered_mechs); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_set_neg_mechs() failed: ", + major_status, minor_status); + } + gss_release_oid_set(&minor_status, &filtered_mechs); + } + gss_release_oid_set(&minor_status, &available_mechs); + } + } +#endif /* HAVE_GSS_SET_NEG_MECHS */ + + /* Generate our challenge-response message */ + major_status = Curl_gss_init_sec_context(data, + &minor_status, + &nego->context, + nego->spn, + &Curl_spnego_mech_oid, + chan_bindings, + &input_token, + &output_token, + TRUE, + NULL, + nego->cred); + + /* Free the decoded challenge as it is not required anymore */ + curlx_safefree(input_token.value); + + nego->status = major_status; + if(GSS_ERROR(major_status)) { + if(output_token.value) + gss_release_buffer(&unused_status, &output_token); + + Curl_gss_log_error(data, "gss_init_sec_context() failed: ", + major_status, minor_status); + + return CURLE_AUTH_ERROR; + } + + if(!output_token.value || !output_token.length) { + if(output_token.value) + gss_release_buffer(&unused_status, &output_token); + + return CURLE_AUTH_ERROR; + } + + /* Check if NTLM was selected and is disallowed */ + if(nego->context != GSS_C_NO_CONTEXT) { + /* OID 1.3.6.1.4.1.311.2.2.10 (NTLMSSP) */ + static const gss_OID_desc ntlmssp_oid = { + 10, CURL_UNCONST("\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a") + }; + OM_uint32 inquire_major, inquire_minor; + gss_OID mech_type = GSS_C_NO_OID; + + inquire_major = Curl_gss_inquire_context(&inquire_minor, + nego->context, + &mech_type); + if(!GSS_ERROR(inquire_major) && mech_type && + mech_type->length == ntlmssp_oid.length && + !memcmp(mech_type->elements, ntlmssp_oid.elements, + ntlmssp_oid.length)) { + infof(data, "SPNEGO chose NTLM, but NTLM is not allowed"); + gss_release_buffer(&unused_status, &output_token); + Curl_auth_cleanup_spnego(nego); + return CURLE_AUTH_ERROR; + } + } + + /* Free previous token */ + if(nego->output_token.length && nego->output_token.value) + gss_release_buffer(&unused_status, &nego->output_token); + + nego->output_token = output_token; + + return CURLE_OK; +} + +/* + * Curl_auth_create_spnego_message() + * + * This is used to generate an already encoded SPNEGO (Negotiate) response + * message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * nego [in/out] - The Negotiate data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result is stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_spnego_message(struct negotiatedata *nego, + char **outptr, size_t *outlen) +{ + CURLcode result; + OM_uint32 minor_status; + + /* Base64 encode the already generated response */ + result = curlx_base64_encode(nego->output_token.value, + nego->output_token.length, + outptr, outlen); + + if(result) { + gss_release_buffer(&minor_status, &nego->output_token); + nego->output_token.value = NULL; + nego->output_token.length = 0; + + return result; + } + + if(!*outptr || !*outlen) { + gss_release_buffer(&minor_status, &nego->output_token); + nego->output_token.value = NULL; + nego->output_token.length = 0; + + return CURLE_REMOTE_ACCESS_DENIED; + } + + return CURLE_OK; +} + +/* + * Curl_auth_cleanup_spnego() + * + * This is used to clean up the SPNEGO (Negotiate) specific data. + * + * Parameters: + * + * nego [in/out] - The Negotiate data struct being cleaned up. + * + */ +void Curl_auth_cleanup_spnego(struct negotiatedata *nego) +{ + OM_uint32 minor_status; + + /* Free our security context */ + if(nego->context != GSS_C_NO_CONTEXT) { + Curl_gss_delete_sec_context(&minor_status, &nego->context, + GSS_C_NO_BUFFER); + nego->context = GSS_C_NO_CONTEXT; + } + + /* Free the output token */ + if(nego->output_token.value) { + gss_release_buffer(&minor_status, &nego->output_token); + nego->output_token.value = NULL; + nego->output_token.length = 0; + } + + /* Free the SPN */ + if(nego->spn != GSS_C_NO_NAME) { + gss_release_name(&minor_status, &nego->spn); + nego->spn = GSS_C_NO_NAME; + } + + /* Free our credentials */ + if(nego->cred != GSS_C_NO_CREDENTIAL) { + Curl_gss_release_cred(&minor_status, &nego->cred); + nego->cred = GSS_C_NO_CREDENTIAL; + } + + /* Reset any variables */ + nego->status = 0; + nego->noauthpersist = FALSE; + nego->havenoauthpersist = FALSE; + nego->havenegdata = FALSE; + nego->havemultiplerequests = FALSE; +} + +#if defined(CURL_HAVE_DIAG) && defined(__APPLE__) && !defined(HAVE_GSSAPPLE) +#pragma GCC diagnostic pop +#endif + +#endif /* HAVE_GSSAPI && USE_SPNEGO */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/spnego_sspi.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/spnego_sspi.c new file mode 100644 index 0000000000..4babd4510d --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/spnego_sspi.c @@ -0,0 +1,368 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC4178 Simple and Protected GSS-API Negotiation Mechanism + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_WINDOWS_SSPI) && defined(USE_SPNEGO) + +#include "vauth/vauth.h" +#include "curlx/base64.h" +#include "curl_trc.h" +#include "strerror.h" + +/* + * Curl_auth_is_spnego_supported() + * + * This is used to evaluate if SPNEGO (Negotiate) is supported. + * + * Parameters: None + * + * Returns TRUE if Negotiate is supported by Windows SSPI. + */ +bool Curl_auth_is_spnego_supported(void) +{ + PSecPkgInfo SecurityPackage; + SECURITY_STATUS status; + + /* Query the security package for Negotiate */ + status = Curl_pSecFn->QuerySecurityPackageInfo( + CURL_UNCONST(TEXT(SP_NAME_NEGOTIATE)), + &SecurityPackage); + + /* Release the package buffer as it is not required anymore */ + if(status == SEC_E_OK) { + Curl_pSecFn->FreeContextBuffer(SecurityPackage); + } + + return status == SEC_E_OK; +} + +/* + * Curl_auth_decode_spnego_message() + * + * This is used to decode an already encoded SPNEGO (Negotiate) challenge + * message. + * + * Parameters: + * + * data [in] - The session handle. + * user [in] - The username in the format User or Domain\User. + * password [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The hostname. + * chlg64 [in] - The optional base64 encoded challenge message. + * nego [in/out] - The Negotiate data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data, + struct Curl_creds *creds, + const char *default_service, + const char *host, + const char *chlg64, + struct negotiatedata *nego) +{ + CURLcode result = CURLE_OK; + size_t chlglen = 0; + unsigned char *chlg = NULL; + PSecPkgInfo SecurityPackage; + SecBuffer chlg_buf[2]; + SecBuffer resp_buf; + SecBufferDesc chlg_desc; + SecBufferDesc resp_desc; + unsigned long attrs; + SecPkgContext_Bindings pkgBindings = { 0, NULL }; + + if(nego->context && nego->status == SEC_E_OK) { + /* We finished successfully our part of authentication, but server + * rejected it (since we are again here). Exit with an error since we + * cannot invent anything better */ + Curl_auth_cleanup_spnego(nego); + return CURLE_LOGIN_DENIED; + } + + if(!nego->spn) { + /* Generate our SPN */ + const char *service = Curl_creds_has_sasl_service(creds) ? + Curl_creds_sasl_service(creds) : default_service; + nego->spn = Curl_auth_build_spn(service, host, NULL); + if(!nego->spn) + return CURLE_OUT_OF_MEMORY; + } + + if(!nego->output_token) { + /* Query the security package for Negotiate */ + nego->status = Curl_pSecFn->QuerySecurityPackageInfo( + CURL_UNCONST(TEXT(SP_NAME_NEGOTIATE)), + &SecurityPackage); + if(nego->status != SEC_E_OK) { + failf(data, "SSPI: could not get auth info"); + return CURLE_AUTH_ERROR; + } + + nego->token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + Curl_pSecFn->FreeContextBuffer(SecurityPackage); + + /* Allocate our output buffer */ + nego->output_token = curlx_malloc(nego->token_max); + if(!nego->output_token) + return CURLE_OUT_OF_MEMORY; + } + + if(!nego->credentials) { + /* Do we have credentials to use or are we using single sign-on? */ + if(Curl_creds_has_user(creds)) { + /* Populate our identity structure */ + result = Curl_create_sspi_identity(creds->user, creds->passwd, + &nego->identity); + if(result) + return result; + + /* Allow proper cleanup of the identity structure */ + nego->p_identity = &nego->identity; + } + else + /* Use the current Windows user */ + nego->p_identity = NULL; + + /* Exclude NTLM from SPNEGO negotiation via the PackageList field */ + if(!nego->p_identity) { + memset(&nego->identity, 0, sizeof(nego->identity)); + nego->identity.Version = SEC_WINNT_AUTH_IDENTITY_VERSION; + nego->identity.Length = sizeof(nego->identity); + nego->identity.Flags = CURL_SEC_WINNT_AUTH_IDENTITY; + nego->p_identity = &nego->identity; + } + + /* Use the special name "!ntlm" to prevent NTLM from being used: + * https://learn.microsoft.com/windows/win32/api/sspi/ns-sspi-sec_winnt_auth_identity_exa + */ + nego->identity.PackageList = CURL_UNCONST(TEXT("!ntlm")); + nego->identity.PackageListLength = 5; + + /* Allocate our credentials handle */ + nego->credentials = curlx_calloc(1, sizeof(CredHandle)); + if(!nego->credentials) + return CURLE_OUT_OF_MEMORY; + + /* Acquire our credentials handle */ + nego->status = Curl_pSecFn->AcquireCredentialsHandle(NULL, + CURL_UNCONST(TEXT(SP_NAME_NEGOTIATE)), + SECPKG_CRED_OUTBOUND, NULL, + nego->p_identity, NULL, NULL, + nego->credentials, NULL); + if(nego->status != SEC_E_OK) { + curlx_safefree(nego->credentials); + return CURLE_AUTH_ERROR; + } + + /* Allocate our new context handle */ + nego->context = curlx_calloc(1, sizeof(CtxtHandle)); + if(!nego->context) + return CURLE_OUT_OF_MEMORY; + } + + chlg_desc.ulVersion = SECBUFFER_VERSION; + chlg_desc.cBuffers = 0; + chlg_desc.pBuffers = chlg_buf; + + if(chlg64 && *chlg64) { + /* Decode the base-64 encoded challenge message */ + if(*chlg64 != '=') { + result = curlx_base64_decode(chlg64, &chlg, &chlglen); + if(result) + return result; + } + + /* Ensure we have a valid challenge message */ + if(!chlg) { + infof(data, "SPNEGO handshake failure (empty challenge message)"); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Setup the challenge "input" security buffer */ + chlg_desc.cBuffers = 1; + chlg_buf[0].BufferType = SECBUFFER_TOKEN; + chlg_buf[0].pvBuffer = chlg; + chlg_buf[0].cbBuffer = curlx_uztoul(chlglen); + } + + /* SSL context comes from Schannel. + * When extended protection is used in IIS server, pass its channel + * bindings on the initial call too. HTTP Negotiate can create and send a + * Kerberos token before receiving a challenge from the server. + * Minimum supported version is Windows 7. + * https://learn.microsoft.com/security-updates/SecurityAdvisories/2009/973811 + */ + if(nego->sslContext) { + nego->status = Curl_pSecFn->QueryContextAttributes( + nego->sslContext, + SECPKG_ATTR_ENDPOINT_BINDINGS, + &pkgBindings); + if(nego->status == SEC_E_OK) { + SecBuffer *binding_buf = &chlg_buf[chlg_desc.cBuffers++]; + binding_buf->BufferType = SECBUFFER_CHANNEL_BINDINGS; + binding_buf->cbBuffer = pkgBindings.BindingsLength; + binding_buf->pvBuffer = pkgBindings.Bindings; + } + } + + /* Setup the response "output" security buffer */ + resp_desc.ulVersion = SECBUFFER_VERSION; + resp_desc.cBuffers = 1; + resp_desc.pBuffers = &resp_buf; + resp_buf.BufferType = SECBUFFER_TOKEN; + resp_buf.pvBuffer = nego->output_token; + resp_buf.cbBuffer = curlx_uztoul(nego->token_max); + + /* Generate our challenge-response message */ + { + DWORD sspi_flags = ISC_REQ_CONFIDENTIALITY; + if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_FLAG) + sspi_flags |= ISC_REQ_DELEGATE | ISC_REQ_MUTUAL_AUTH; + nego->status = + Curl_pSecFn->InitializeSecurityContext(nego->credentials, + chlg ? nego->context : NULL, + nego->spn, + sspi_flags, + 0, SECURITY_NATIVE_DREP, + chlg_desc.cBuffers ? + &chlg_desc : NULL, + 0, nego->context, + &resp_desc, &attrs, NULL); + } + + if(pkgBindings.Bindings) + Curl_pSecFn->FreeContextBuffer(pkgBindings.Bindings); + + /* Free the decoded challenge as it is not required anymore */ + curlx_free(chlg); + + if(GSS_ERROR(nego->status)) { + char buffer[STRERROR_LEN]; + failf(data, "InitializeSecurityContext failed: %s", + Curl_sspi_strerror(nego->status, buffer, sizeof(buffer))); + + if(nego->status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + + return CURLE_AUTH_ERROR; + } + + if(nego->status == SEC_I_COMPLETE_NEEDED || + nego->status == SEC_I_COMPLETE_AND_CONTINUE) { + nego->status = Curl_pSecFn->CompleteAuthToken(nego->context, &resp_desc); + if(GSS_ERROR(nego->status)) { + char buffer[STRERROR_LEN]; + failf(data, "CompleteAuthToken failed: %s", + Curl_sspi_strerror(nego->status, buffer, sizeof(buffer))); + + if(nego->status == SEC_E_INSUFFICIENT_MEMORY) + return CURLE_OUT_OF_MEMORY; + + return CURLE_AUTH_ERROR; + } + } + + nego->output_token_length = resp_buf.cbBuffer; + + return result; +} + +/* + * Curl_auth_create_spnego_message() + * + * This is used to generate an already encoded SPNEGO (Negotiate) response + * message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * nego [in/out] - The Negotiate data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result is stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_spnego_message(struct negotiatedata *nego, + char **outptr, size_t *outlen) +{ + /* Base64 encode the already generated response */ + CURLcode result = curlx_base64_encode(nego->output_token, + nego->output_token_length, outptr, + outlen); + if(!result && (!*outptr || !*outlen)) { + curlx_free(*outptr); + result = CURLE_REMOTE_ACCESS_DENIED; + } + + return result; +} + +/* + * Curl_auth_cleanup_spnego() + * + * This is used to clean up the SPNEGO (Negotiate) specific data. + * + * Parameters: + * + * nego [in/out] - The Negotiate data struct being cleaned up. + * + */ +void Curl_auth_cleanup_spnego(struct negotiatedata *nego) +{ + /* Free our security context */ + if(nego->context) { + Curl_pSecFn->DeleteSecurityContext(nego->context); + curlx_safefree(nego->context); + } + + /* Free our credentials handle */ + if(nego->credentials) { + Curl_pSecFn->FreeCredentialsHandle(nego->credentials); + curlx_safefree(nego->credentials); + } + + /* Free our identity */ + Curl_sspi_free_identity(nego->p_identity); + nego->p_identity = NULL; + + /* Free the SPN and output token */ + curlx_safefree(nego->spn); + curlx_safefree(nego->output_token); + + /* Reset any variables */ + nego->status = 0; + nego->token_max = 0; + nego->noauthpersist = FALSE; + nego->havenoauthpersist = FALSE; + nego->havenegdata = FALSE; + nego->havemultiplerequests = FALSE; +} + +#endif /* USE_WINDOWS_SSPI && USE_SPNEGO */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/vauth.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/vauth.c new file mode 100644 index 0000000000..3259556e5f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/vauth.c @@ -0,0 +1,252 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, <steve_holme@hotmail.com>. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "vauth/vauth.h" +#include "creds.h" +#include "curlx/multibyte.h" +#include "url.h" + +/* + * Curl_auth_build_spn() + * + * This is used to build an SPN string in the following formats: + * + * service/host@realm (Not currently used) + * service/host (Not used by GSS-API) + * service@realm (Not used by Windows SSPI) + * + * Parameters: + * + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The hostname. + * realm [in] - The realm. + * + * Returns a pointer to the newly allocated SPN. + */ +#ifndef USE_WINDOWS_SSPI +char *Curl_auth_build_spn(const char *service, const char *host, + const char *realm) +{ + char *spn = NULL; + + /* Generate our SPN */ + if(host && realm) + spn = curl_maprintf("%s/%s@%s", service, host, realm); + else if(host) + spn = curl_maprintf("%s/%s", service, host); + else if(realm) + spn = curl_maprintf("%s@%s", service, realm); + + /* Return our newly allocated SPN */ + return spn; +} +#else +TCHAR *Curl_auth_build_spn(const char *service, const char *host, + const char *realm) +{ + char *utf8_spn = NULL; + TCHAR *tchar_spn = NULL; + + (void)realm; + + /* Note: We could use DsMakeSPN() or DsClientMakeSpnForTargetServer() rather + than doing this ourselves but the first is only available in Windows XP + and Windows Server 2003 and the latter is only available in Windows 2000 + but not Windows95/98/ME or Windows NT4.0 unless the Active Directory + Client Extensions are installed. As such it is far simpler for us to + formulate the SPN instead. */ + + /* Generate our UTF8 based SPN */ + utf8_spn = curl_maprintf("%s/%s", service, host); + if(!utf8_spn) + return NULL; + + /* Allocate and return a TCHAR based SPN. */ + tchar_spn = curlx_convert_UTF8_to_tchar(utf8_spn); + curlx_free(utf8_spn); + + return tchar_spn; +} +#endif /* USE_WINDOWS_SSPI */ + +/* + * Curl_auth_user_contains_domain() + * + * This is used to test if the specified user contains a Windows domain name as + * follows: + * + * Domain\User (Down-level Logon Name) + * Domain/User (curl Down-level format - for compatibility with existing code) + * User@Domain (User Principal Name) + * + * Note: The username may be empty when using a GSS-API library or Windows + * SSPI as the user and domain are either obtained from the credentials cache + * when using GSS-API or via the currently logged in user's credentials when + * using Windows SSPI. + * + * Parameters: + * + * user [in] - The username. + * + * Returns TRUE on success; otherwise FALSE. + */ +bool Curl_auth_user_contains_domain(struct Curl_creds *creds) +{ + bool valid = FALSE; + + if(Curl_creds_has_user(creds)) { + /* Check we have a domain name or UPN present */ + const char *p = strpbrk(creds->user, "\\/@"); + + valid = p && (p > creds->user) && + (p < (creds->user + strlen(creds->user) - 1)); + } +#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) + else + /* User and domain are obtained from the GSS-API credentials cache or the + currently logged in user from Windows */ + valid = TRUE; +#endif + + return valid; +} + +/* + * Curl_auth_allowed_to_host() tells if authentication, cookies or other + * "sensitive data" can be sent to the connection's origin. + */ +bool Curl_auth_allowed_to_host(struct Curl_easy *data) +{ + return Curl_auth_allowed_to_origin(data, data->state.origin); +} + +bool Curl_auth_allowed_to_origin(struct Curl_easy *data, + struct Curl_peer *origin) +{ + return data->set.allow_auth_to_other_hosts || + Curl_peer_equal(data->state.initial_origin, origin); +} + +#ifdef USE_NTLM +static void ntlm_conn_dtor(void *key, size_t klen, void *entry) +{ + struct ntlmdata *ntlm = entry; + (void)key; + (void)klen; + DEBUGASSERT(ntlm); + Curl_auth_cleanup_ntlm(ntlm); + curlx_free(ntlm); +} + +struct ntlmdata *Curl_auth_ntlm_get(struct connectdata *conn, bool proxy) +{ + const char *key = proxy ? CURL_META_NTLM_PROXY_CONN : CURL_META_NTLM_CONN; + struct ntlmdata *ntlm = Curl_conn_meta_get(conn, key); + if(!ntlm) { + ntlm = curlx_calloc(1, sizeof(*ntlm)); + if(!ntlm || Curl_conn_meta_set(conn, key, ntlm, ntlm_conn_dtor)) + return NULL; + } + return ntlm; +} + +void Curl_auth_ntlm_remove(struct connectdata *conn, bool proxy) +{ + Curl_conn_meta_remove(conn, proxy ? CURL_META_NTLM_PROXY_CONN + : CURL_META_NTLM_CONN); +} +#endif /* USE_NTLM */ + +#ifdef USE_KERBEROS5 +static void krb5_conn_dtor(void *key, size_t klen, void *entry) +{ + struct kerberos5data *krb5 = entry; + (void)key; + (void)klen; + DEBUGASSERT(krb5); + Curl_auth_cleanup_gssapi(krb5); + curlx_free(krb5); +} + +struct kerberos5data *Curl_auth_krb5_get(struct connectdata *conn) +{ + struct kerberos5data *krb5 = Curl_conn_meta_get(conn, CURL_META_KRB5_CONN); + if(!krb5) { + krb5 = curlx_calloc(1, sizeof(*krb5)); + if(!krb5 || + Curl_conn_meta_set(conn, CURL_META_KRB5_CONN, krb5, krb5_conn_dtor)) + return NULL; + } + return krb5; +} +#endif /* USE_KERBEROS5 */ + +#ifdef USE_GSASL +static void gsasl_conn_dtor(void *key, size_t klen, void *entry) +{ + struct gsasldata *gsasl = entry; + (void)key; + (void)klen; + DEBUGASSERT(gsasl); + Curl_auth_gsasl_cleanup(gsasl); + curlx_free(gsasl); +} + +struct gsasldata *Curl_auth_gsasl_get(struct connectdata *conn) +{ + struct gsasldata *gsasl = Curl_conn_meta_get(conn, CURL_META_GSASL_CONN); + if(!gsasl) { + gsasl = curlx_calloc(1, sizeof(*gsasl)); + if(!gsasl || + Curl_conn_meta_set(conn, CURL_META_GSASL_CONN, gsasl, gsasl_conn_dtor)) + return NULL; + } + return gsasl; +} +#endif /* USE_GSASL */ + +#ifdef USE_SPNEGO +static void nego_conn_dtor(void *key, size_t klen, void *entry) +{ + struct negotiatedata *nego = entry; + (void)key; + (void)klen; + DEBUGASSERT(nego); + Curl_auth_cleanup_spnego(nego); + curlx_free(nego); +} + +struct negotiatedata *Curl_auth_nego_get(struct connectdata *conn, bool proxy) +{ + const char *key = proxy ? CURL_META_NEGO_PROXY_CONN : CURL_META_NEGO_CONN; + struct negotiatedata *nego = Curl_conn_meta_get(conn, key); + if(!nego) { + nego = curlx_calloc(1, sizeof(*nego)); + if(!nego || Curl_conn_meta_set(conn, key, nego, nego_conn_dtor)) + return NULL; + } + return nego; +} +#endif /* USE_SPNEGO */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/vauth.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/vauth.h new file mode 100644 index 0000000000..bddd55f8d5 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vauth/vauth.h @@ -0,0 +1,338 @@ +#ifndef HEADER_CURL_VAUTH_H +#define HEADER_CURL_VAUTH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, <steve_holme@hotmail.com>. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "bufref.h" +#include "curlx/dynbuf.h" +#include "urldata.h" + +struct Curl_easy; +struct Curl_creds; +struct connectdata; +struct Curl_peer; + +#ifndef CURL_DISABLE_DIGEST_AUTH +struct digestdata; +#endif + +#ifdef USE_NTLM +struct ntlmdata; +#endif + +#if (defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)) && defined(USE_SPNEGO) +struct negotiatedata; +#endif + +#ifdef USE_GSASL +struct gsasldata; +#endif + +#ifdef USE_WINDOWS_SSPI +#include "curl_sspi.h" +#define GSS_ERROR(status) ((status) & 0x80000000) +#endif + +/* + * Curl_auth_allowed_to_host() tells if authentication, cookies or other + * "sensitive data" can (still) be sent to this host. + */ +bool Curl_auth_allowed_to_host(struct Curl_easy *data); +bool Curl_auth_allowed_to_origin(struct Curl_easy *data, + struct Curl_peer *origin); + +/* This is used to build an SPN string */ +#ifndef USE_WINDOWS_SSPI +char *Curl_auth_build_spn(const char *service, const char *host, + const char *realm); +#else +TCHAR *Curl_auth_build_spn(const char *service, const char *host, + const char *realm); +#endif + +/* This is used to test if the user contains a Windows domain name */ +bool Curl_auth_user_contains_domain(struct Curl_creds *creds); + +/* This is used to generate a PLAIN cleartext message */ +CURLcode Curl_auth_create_plain_message(struct Curl_creds *creds, + struct bufref *out); + +/* This is used to generate a LOGIN cleartext message */ +void Curl_auth_create_login_message(const char *value, struct bufref *out); + +/* This is used to generate an EXTERNAL cleartext message */ +void Curl_auth_create_external_message(const char *user, struct bufref *out); + +#ifndef CURL_DISABLE_DIGEST_AUTH +/* This is used to generate a CRAM-MD5 response message */ +CURLcode Curl_auth_create_cram_md5_message(const struct bufref *chlg, + struct Curl_creds *creds, + struct bufref *out); + +/* This is used to evaluate if DIGEST is supported */ +bool Curl_auth_is_digest_supported(void); + +/* This is used to generate a base64 encoded DIGEST-MD5 response message */ +CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data, + const struct bufref *chlg, + struct Curl_creds *creds, + const char *default_service, + struct bufref *out); + +/* This is used to decode an HTTP DIGEST challenge message */ +CURLcode Curl_auth_decode_digest_http_message(const char *chlg, + struct digestdata *digest); + +/* This is used to generate an HTTP DIGEST response message */ +CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data, + struct Curl_creds *creds, + const unsigned char *request, + const unsigned char *uripath, + struct digestdata *digest, + char **outptr, size_t *outlen); + +/* This is used to clean up the digest specific data */ +void Curl_auth_digest_cleanup(struct digestdata *digest); +#else +#define Curl_auth_digest_cleanup(x) +#define Curl_auth_is_digest_supported() FALSE +#endif /* !CURL_DISABLE_DIGEST_AUTH */ + +#ifdef USE_GSASL + +/* meta key for storing GSASL meta at connection */ +#define CURL_META_GSASL_CONN "meta:auth:gsasl:conn" + +#include <gsasl.h> +struct gsasldata { + Gsasl *ctx; + Gsasl_session *client; +}; + +struct gsasldata *Curl_auth_gsasl_get(struct connectdata *conn); + +/* This is used to evaluate if MECH is supported by gsasl */ +bool Curl_auth_gsasl_is_supported(struct Curl_easy *data, + const char *mech, + struct gsasldata *gsasl); +/* This is used to start a gsasl method */ +CURLcode Curl_auth_gsasl_start(struct Curl_easy *data, + struct Curl_creds *creds, + struct gsasldata *gsasl); + +/* This is used to process and generate a new SASL token */ +CURLcode Curl_auth_gsasl_token(struct Curl_easy *data, + const struct bufref *chlg, + struct gsasldata *gsasl, + struct bufref *out); + +/* This is used to clean up the gsasl specific data */ +void Curl_auth_gsasl_cleanup(struct gsasldata *gsasl); +#endif + +#ifdef USE_NTLM + +/* meta key for storing NTML meta at connection */ +#define CURL_META_NTLM_CONN "meta:auth:ntml:conn" +/* meta key for storing NTML-PROXY meta at connection */ +#define CURL_META_NTLM_PROXY_CONN "meta:auth:ntml-proxy:conn" + +struct ntlmdata { +#ifdef USE_WINDOWS_SSPI +/* The sslContext is used for the Schannel bindings. The + * api is available on the Windows 7 SDK and later. + */ + CtxtHandle *sslContext; + CredHandle *credentials; + CtxtHandle *context; + SEC_WINNT_AUTH_IDENTITY_EX identity; + SEC_WINNT_AUTH_IDENTITY_EX *p_identity; + size_t token_max; + BYTE *output_token; + BYTE *input_token; + size_t input_token_len; + TCHAR *spn; +#else + unsigned int flags; + unsigned char nonce[8]; + unsigned int target_info_len; + void *target_info; /* TargetInfo received in the NTLM type-2 message */ +#endif +}; + +/* This is used to evaluate if NTLM is supported */ +bool Curl_auth_is_ntlm_supported(void); + +struct ntlmdata *Curl_auth_ntlm_get(struct connectdata *conn, bool proxy); +void Curl_auth_ntlm_remove(struct connectdata *conn, bool proxy); + +/* This is used to clean up the NTLM specific data */ +void Curl_auth_cleanup_ntlm(struct ntlmdata *ntlm); + +/* This is used to generate a base64 encoded NTLM type-1 message */ +CURLcode Curl_auth_create_ntlm_type1_message(struct Curl_easy *data, + struct Curl_creds *creds, + const char *default_service, + const char *host, + struct ntlmdata *ntlm, + struct bufref *out); + +/* This is used to decode a base64 encoded NTLM type-2 message */ +CURLcode Curl_auth_decode_ntlm_type2_message(struct Curl_easy *data, + const struct bufref *type2ref, + struct ntlmdata *ntlm); + +/* This is used to generate a base64 encoded NTLM type-3 message */ +CURLcode Curl_auth_create_ntlm_type3_message(struct Curl_easy *data, + struct Curl_creds *creds, + struct ntlmdata *ntlm, + struct bufref *out); + +#else +#define Curl_auth_is_ntlm_supported() FALSE +#endif /* USE_NTLM */ + +/* This is used to generate a base64 encoded OAuth 2.0 message */ +CURLcode Curl_auth_create_oauth_bearer_message(struct Curl_creds *creds, + const char *host, + const long port, + struct bufref *out); + +/* This is used to generate a base64 encoded XOAuth 2.0 message */ +CURLcode Curl_auth_create_xoauth_bearer_message(struct Curl_creds *creds, + struct bufref *out); + +#ifdef USE_KERBEROS5 + +/* meta key for storing KRB5 meta at connection */ +#define CURL_META_KRB5_CONN "meta:auth:krb5:conn" + +struct kerberos5data { +#ifdef USE_WINDOWS_SSPI + CredHandle *credentials; + CtxtHandle *context; + TCHAR *spn; + SEC_WINNT_AUTH_IDENTITY_EX identity; + SEC_WINNT_AUTH_IDENTITY_EX *p_identity; + size_t token_max; + BYTE *output_token; +#else + gss_ctx_id_t context; + gss_name_t spn; +#endif +}; + +struct kerberos5data *Curl_auth_krb5_get(struct connectdata *conn); + +/* This is used to evaluate if GSSAPI (Kerberos V5) is supported */ +bool Curl_auth_is_gssapi_supported(void); + +/* This is used to generate a base64 encoded GSSAPI (Kerberos V5) user token + message */ +CURLcode Curl_auth_create_gssapi_user_message(struct Curl_easy *data, + struct Curl_creds *creds, + const char *default_service, + const char *host, + const bool mutual_auth, + const struct bufref *chlg, + struct kerberos5data *krb5, + struct bufref *out); + +/* This is used to generate a base64 encoded GSSAPI (Kerberos V5) security + token message */ +CURLcode Curl_auth_create_gssapi_security_message(struct Curl_easy *data, + const char *authzid, + const struct bufref *chlg, + struct kerberos5data *krb5, + struct bufref *out); + +/* This is used to clean up the GSSAPI specific data */ +void Curl_auth_cleanup_gssapi(struct kerberos5data *krb5); +#else +#define Curl_auth_is_gssapi_supported() FALSE +#endif /* USE_KERBEROS5 */ + +#ifdef USE_SPNEGO + +bool Curl_auth_is_spnego_supported(void); + +/* meta key for storing NEGO meta at connection */ +#define CURL_META_NEGO_CONN "meta:auth:nego:conn" +/* meta key for storing NEGO PROXY meta at connection */ +#define CURL_META_NEGO_PROXY_CONN "meta:auth:nego-proxy:conn" + +/* Struct used for Negotiate (SPNEGO) authentication */ +struct negotiatedata { +#ifdef HAVE_GSSAPI + OM_uint32 status; + gss_ctx_id_t context; + gss_name_t spn; + gss_cred_id_t cred; + gss_buffer_desc output_token; +#ifdef GSS_C_CHANNEL_BOUND_FLAG + struct dynbuf channel_binding_data; +#endif +#else +#ifdef USE_WINDOWS_SSPI + CtxtHandle *sslContext; + SECURITY_STATUS status; + CredHandle *credentials; + CtxtHandle *context; + SEC_WINNT_AUTH_IDENTITY_EX identity; + SEC_WINNT_AUTH_IDENTITY_EX *p_identity; + TCHAR *spn; + size_t token_max; + BYTE *output_token; + size_t output_token_length; +#endif +#endif + BIT(noauthpersist); + BIT(havenoauthpersist); + BIT(havenegdata); + BIT(havemultiplerequests); +}; + +struct negotiatedata *Curl_auth_nego_get(struct connectdata *conn, bool proxy); + +/* This is used to decode a base64 encoded SPNEGO (Negotiate) challenge + message */ +CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data, + struct Curl_creds *creds, + const char *default_service, + const char *host, + const char *chlg64, + struct negotiatedata *nego); + +/* This is used to generate a base64 encoded SPNEGO (Negotiate) response + message */ +CURLcode Curl_auth_create_spnego_message(struct negotiatedata *nego, + char **outptr, size_t *outlen); + +/* This is used to clean up the SPNEGO specific data */ +void Curl_auth_cleanup_spnego(struct negotiatedata *nego); + +#endif /* USE_SPNEGO */ + +#endif /* HEADER_CURL_VAUTH_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/asyn-ares.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/asyn-ares.c new file mode 100644 index 0000000000..dfb0875995 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/asyn-ares.c @@ -0,0 +1,766 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_RESOLV_ARES + +/*********************************************************************** + * Only for ares-enabled builds and only for functions that fulfill + * the asynch resolver backend API as defined in asyn.h, + * nothing else belongs in this file! + **********************************************************************/ + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include "urldata.h" +#include "cfilters.h" +#include "curl_addrinfo.h" +#include "curl_trc.h" +#include "url.h" +#include "multiif.h" +#include "curlx/inet_pton.h" +#include "connect.h" +#include "select.h" +#include "progress.h" +#include "curlx/timediff.h" +#include "vdns/hostip.h" +#include "vdns/httpsrr.h" +#include <ares.h> + +#if ARES_VERSION < 0x011000 +#error "c-ares 1.16.0 or greater required" +#endif + +#ifdef USE_HTTPSRR +#if ARES_VERSION < 0x011c00 +#error "c-ares 1.28.0 or greater required for HTTPSRR" +#endif +#define HTTPSRR_WORKS +#endif + +#define CARES_TIMEOUT_PER_ATTEMPT 2000 + +static int ares_ver = 0; + +static CURLcode async_ares_set_dns_servers(struct Curl_easy *data, + struct Curl_resolv_async *async); +static CURLcode async_ares_set_dns_interface(struct Curl_easy *data, + struct Curl_resolv_async *async); +static CURLcode async_ares_set_dns_local_ip4(struct Curl_easy *data, + struct Curl_resolv_async *async); +static CURLcode async_ares_set_dns_local_ip6(struct Curl_easy *data, + struct Curl_resolv_async *async); + +/* + * Curl_async_global_init() - the generic low-level asynchronous name + * resolve API. Called from curl_global_init() to initialize global resolver + * environment. Initializes ares library. + */ +int Curl_async_global_init(void) +{ +#ifdef CARES_HAVE_ARES_LIBRARY_INIT + if(ares_library_init(ARES_LIB_INIT_ALL)) { + return CURLE_FAILED_INIT; + } +#endif + ares_version(&ares_ver); + return CURLE_OK; +} + +/* + * Curl_async_global_cleanup() + * + * Called from curl_global_cleanup() to destroy global resolver environment. + * Deinitializes ares library. + */ +void Curl_async_global_cleanup(void) +{ +#ifdef CARES_HAVE_ARES_LIBRARY_CLEANUP + ares_library_cleanup(); +#endif +} + +static void sock_state_cb(void *data, ares_socket_t socket_fd, + int readable, int writable) +{ + struct Curl_easy *easy = data; + if(!readable && !writable) { + DEBUGASSERT(easy); + Curl_multi_will_close(easy, socket_fd); + } +} + +static CURLcode async_ares_init(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + struct async_ares_ctx *ares = &async->ares; + int status; + struct ares_options options; + int optmask = ARES_OPT_SOCK_STATE_CB; + CURLcode result = CURLE_OK; + + /* initial status - failed */ + ares->ares_status = ARES_ENOTFOUND; + async->queries_ongoing = 0; + + options.sock_state_cb = sock_state_cb; + options.sock_state_cb_data = data; + + DEBUGASSERT(!ares->channel); + /* + if c ares < 1.20.0: curl set timeout to CARES_TIMEOUT_PER_ATTEMPT (2s) + + if c-ares >= 1.20.0 it already has the timeout to 2s, curl does not need + to set the timeout value; + + if c-ares >= 1.24.0, user can set the timeout via /etc/resolv.conf to + overwrite c-ares' timeout. + */ + DEBUGASSERT(ares_ver); + if(ares_ver < 0x011400) { + options.timeout = CARES_TIMEOUT_PER_ATTEMPT; + optmask |= ARES_OPT_TIMEOUTMS; + } + + status = ares_init_options(&ares->channel, &options, optmask); + if(status != ARES_SUCCESS) { + ares->channel = NULL; + result = (status == ARES_ENOMEM) ? CURLE_OUT_OF_MEMORY : CURLE_FAILED_INIT; + goto out; + } + + result = async_ares_set_dns_servers(data, async); + if(result && result != CURLE_NOT_BUILT_IN) + goto out; + + result = async_ares_set_dns_interface(data, async); + if(result && result != CURLE_NOT_BUILT_IN) + goto out; + + result = async_ares_set_dns_local_ip4(data, async); + if(result && result != CURLE_NOT_BUILT_IN) + goto out; + + result = async_ares_set_dns_local_ip6(data, async); + if(result && result != CURLE_NOT_BUILT_IN) + goto out; + + result = CURLE_OK; + +out: + if(result && ares->channel) { + ares_destroy(ares->channel); + ares->channel = NULL; + } + return result; +} + +void Curl_async_ares_shutdown(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + /* c-ares has a method to "cancel" operations on a channel, but + * as reported in #18216, this does not totally reset the channel + * and ares may get stuck. + * We need to destroy the channel and on demand create a new + * one to avoid that. */ + Curl_async_ares_destroy(data, async); +} + +void Curl_async_ares_destroy(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + struct async_ares_ctx *ares = &async->ares; + (void)data; + if(ares->channel) { + ares_destroy(ares->channel); + ares->channel = NULL; + } +} + +CURLcode Curl_async_pollset(struct Curl_easy *data, + struct Curl_resolv_async *async, + struct easy_pollset *ps) +{ + struct async_ares_ctx *ares = &async->ares; + CURLcode result = CURLE_OK; + + if(ares->channel) { + result = Curl_ares_pollset(data, ares->channel, ps); + if(!result) { + timediff_t ms = Curl_ares_timeout_ms(data, async, ares->channel); + Curl_expire(data, ms, EXPIRE_ASYNC_NAME); + } + } + return result; +} + +/* + * Curl_async_take_result() is called repeatedly to check if a previous + * name resolve request has completed. It should also make sure to time-out if + * the operation seems to take too long. + * + * Returns normal CURLcode errors. + */ +CURLcode Curl_async_take_result(struct Curl_easy *data, + struct Curl_resolv_async *async, + struct Curl_dns_entry **pdns) +{ + struct async_ares_ctx *ares = &async->ares; + struct Curl_dns_entry *dns = NULL; + CURLcode result = CURLE_OK; + + DEBUGASSERT(pdns); + *pdns = NULL; + if(!ares) + return CURLE_FAILED_INIT; + + if(Curl_ares_perform(ares->channel, 0) < 0) { + result = CURLE_UNRECOVERABLE_POLL; + goto out; + } + + if(async->queries_ongoing) { + result = CURLE_AGAIN; + goto out; + } + + /* all c-ares operations done, what is the result to report? */ + result = ares->result; + if(ares->ares_status == ARES_SUCCESS && !result) { + + if(CURL_DNSQ_IS_ADDR(async->dns_queries)) { + dns = Curl_dnsc_mk_addr2(data, async->dns_queries, + &async->ai_AAAA, &async->ai_A, + async->peer); + if(!dns) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + +#ifdef HTTPSRR_WORKS + if(!dns && (async->dns_queries & CURL_DNSQ_HTTPS)) { + dns = Curl_dnsc_mk_https(data, &async->httpsrr, async->peer); + if(!dns) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } +#endif + } + /* if we have not found anything, report the proper + * CURLE_COULDNT_RESOLVE_* code */ + if(!result && !dns) { + const char *msg = NULL; + /* only an authoritative "does not exist" answer from every query + may be cached as a negative entry, not transient failures like + timeouts or server troubles */ + async->negative_answer = !ares->transient_err && + ((ares->ares_status == ARES_ENOTFOUND) || + (ares->ares_status == ARES_ENODATA)); + if(ares->ares_status != ARES_SUCCESS) + msg = ares_strerror(ares->ares_status); + result = Curl_async_failed(data, async, msg); + } + + CURL_TRC_DNS(data, "[%s] ares_take_result, result=%d, ares_result=%d, " + "ares_status=%d, dns=%sfound", + Curl_resolv_query_str(async->dns_queries), + (int)result, (int)ares->result, ares->ares_status, + dns ? "" : "not "); + +out: + if(result != CURLE_AGAIN) + ares->result = result; + *pdns = result ? NULL : dns; + return result; +} + +static timediff_t async_ares_poll_timeout(struct async_ares_ctx *ares, + timediff_t timeout_ms) +{ + struct timeval *ares_calced, time_buf, max_timeout; + int itimeout_ms; + +#if TIMEDIFF_T_MAX > INT_MAX + itimeout_ms = (timeout_ms > INT_MAX) ? INT_MAX : + ((timeout_ms < 0) ? -1 : (int)timeout_ms); +#else + itimeout_ms = (int)timeout_ms; +#endif + max_timeout.tv_sec = itimeout_ms / 1000; + max_timeout.tv_usec = (itimeout_ms % 1000) * 1000; + + /* c-ares tells us the shortest timeout of any operation on channel */ + ares_calced = ares_timeout(ares->channel, &max_timeout, &time_buf); + /* use the timeout period ares returned to us above if less than one + second is left, otherwise use 1000ms to make sure the progress callback + gets called frequent enough */ + if(!ares_calced->tv_sec) + return (timediff_t)(ares_calced->tv_usec / 1000); + else + return 1000; +} + +/* + * Curl_async_await() + * + * Waits for a resolve to finish. This function should be avoided since using + * this risk getting the multi interface to "hang". + * + * 'pdns' MUST be non-NULL. + * + * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, + * CURLE_OPERATION_TIMEDOUT if a time-out occurred, or other errors. + */ +CURLcode Curl_async_await(struct Curl_easy *data, uint32_t resolv_id, + struct Curl_dns_entry **pdns) +{ + struct Curl_resolv_async *async = Curl_async_get(data, resolv_id); + struct async_ares_ctx *ares = async ? &async->ares : NULL; + struct curltime start = *Curl_pgrs_now(data); + CURLcode result = CURLE_OK; + + DEBUGASSERT(pdns); + *pdns = NULL; /* clear on entry */ + + if(!ares) + return CURLE_FAILED_INIT; + + /* Wait for the name resolve query to complete or time out. */ + while(!result) { + timediff_t timeout_ms; + + timeout_ms = Curl_timeleft_ms(data); + if(!timeout_ms) { /* no applicable timeout from `data`*/ + timediff_t elapsed_ms = curlx_ptimediff_ms(Curl_pgrs_now(data), &start); + if(elapsed_ms < CURL_TIMEOUT_RESOLVE_MS) + timeout_ms = CURL_TIMEOUT_RESOLVE_MS - elapsed_ms; + else + timeout_ms = -1; + } + + if(timeout_ms < 0) { + result = CURLE_OPERATION_TIMEDOUT; + break; + } + + if(Curl_ares_perform(ares->channel, + async_ares_poll_timeout(ares, timeout_ms)) < 0) { + result = CURLE_UNRECOVERABLE_POLL; + break; + } + + result = Curl_async_take_result(data, async, pdns); + if(result == CURLE_AGAIN) + result = CURLE_OK; + else if(result || *pdns) + break; + + if(Curl_pgrsUpdate(data)) { + result = CURLE_ABORTED_BY_CALLBACK; + break; + } + } + + if(result) + ares_cancel(ares->channel); + return result; +} + +/* + * async_ares_node2addr() converts an address list provided by c-ares + * to an internal libcurl compatible list. + */ +static struct Curl_addrinfo *async_ares_node2addr( + struct ares_addrinfo_node *node) +{ + /* traverse the ares_addrinfo_node list */ + struct ares_addrinfo_node *ai; + struct Curl_addrinfo *cafirst = NULL; + struct Curl_addrinfo *calast = NULL; + int error = 0; + + for(ai = node; ai; ai = ai->ai_next) { + size_t ss_size; + struct Curl_addrinfo *ca; + /* ignore elements with unsupported address family, + settle family-specific sockaddr structure size. */ + if(ai->ai_family == AF_INET) + ss_size = sizeof(struct sockaddr_in); +#ifdef USE_IPV6 + else if(ai->ai_family == AF_INET6) + ss_size = sizeof(struct sockaddr_in6); +#endif + else + continue; + + /* ignore elements without required address info */ + if(!ai->ai_addr || !(ai->ai_addrlen > 0)) + continue; + + /* ignore elements with bogus address size */ + if((size_t)ai->ai_addrlen < ss_size) + continue; + + ca = curlx_malloc(sizeof(struct Curl_addrinfo) + ss_size); + if(!ca) { + error = EAI_MEMORY; + break; + } + + /* copy each structure member individually, member ordering, + size, or padding might be different for each platform. */ + + ca->ai_flags = ai->ai_flags; + ca->ai_family = ai->ai_family; + ca->ai_socktype = ai->ai_socktype; + ca->ai_protocol = ai->ai_protocol; + ca->ai_addrlen = (curl_socklen_t)ss_size; + ca->ai_addr = NULL; + ca->ai_canonname = NULL; + ca->ai_next = NULL; + + ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo)); + memcpy(ca->ai_addr, ai->ai_addr, ss_size); + + /* if the return list is empty, this becomes the first element */ + if(!cafirst) + cafirst = ca; + + /* add this element last in the return list */ + if(calast) + calast->ai_next = ca; + calast = ca; + } + + /* if we failed, destroy the Curl_addrinfo list */ + if(error) { + Curl_freeaddrinfo(cafirst); + cafirst = NULL; + } + + return cafirst; +} + +static void async_ares_A_cb(void *user_data, int status, int timeouts, + struct ares_addrinfo *ares_ai) +{ + struct Curl_resolv_async *async = user_data; + struct async_ares_ctx *ares = async ? &async->ares : NULL; + + (void)timeouts; + if(!async) + return; + + async->dns_responses |= CURL_DNSQ_A; + async->queries_ongoing--; + async->done = !async->queries_ongoing; + if(status == ARES_SUCCESS) { + ares->ares_status = ARES_SUCCESS; + async->ai_A = async_ares_node2addr(ares_ai->nodes); + ares_freeaddrinfo(ares_ai); + } + else { + if((status != ARES_ENOTFOUND) && (status != ARES_ENODATA)) + ares->transient_err = TRUE; + if(ares->ares_status != ARES_SUCCESS) /* do not overwrite success */ + ares->ares_status = status; + } +} + +#ifdef CURLRES_IPV6 +static void async_ares_AAAA_cb(void *user_data, int status, int timeouts, + struct ares_addrinfo *ares_ai) +{ + struct Curl_resolv_async *async = user_data; + struct async_ares_ctx *ares = async ? &async->ares : NULL; + + (void)timeouts; + if(!async) + return; + + async->dns_responses |= CURL_DNSQ_AAAA; + async->queries_ongoing--; + async->done = !async->queries_ongoing; + if(status == ARES_SUCCESS) { + ares->ares_status = ARES_SUCCESS; + async->ai_AAAA = async_ares_node2addr(ares_ai->nodes); + ares_freeaddrinfo(ares_ai); + } + else { + if((status != ARES_ENOTFOUND) && (status != ARES_ENODATA)) + ares->transient_err = TRUE; + if(ares->ares_status != ARES_SUCCESS) /* do not overwrite success */ + ares->ares_status = status; + } +} +#endif /* CURLRES_IPV6 */ + +#ifdef USE_HTTPSRR +static void async_ares_rr_done(void *user_data, ares_status_t status, + size_t timeouts, + const ares_dns_record_t *dnsrec) +{ + struct Curl_resolv_async *async = user_data; + struct async_ares_ctx *ares = async ? &async->ares : NULL; + + if(!async) + return; + + (void)timeouts; + async->dns_responses |= CURL_DNSQ_HTTPS; + async->queries_ongoing--; + async->done = !async->queries_ongoing; + ares->ares_status = status; + if((status != ARES_ENOTFOUND) && (status != ARES_ENODATA)) + ares->transient_err = TRUE; + if((ARES_SUCCESS != status) || !dnsrec) + return; + ares->result = Curl_httpsrr_from_ares(dnsrec, &async->httpsrr); +} +#endif /* USE_HTTPSRR */ + +/* + * Curl_async_getaddrinfo() - when using ares + * + * Starts a name resolve for the given hostname and port number. + */ +CURLcode Curl_async_getaddrinfo(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + struct async_ares_ctx *ares = &async->ares; + char service[12]; + int socktype; + CURLcode result = CURLE_OK; + + if(ares->channel) { + DEBUGASSERT(0); + result = CURLE_FAILED_INIT; + goto out; + } + + result = async_ares_init(data, async); + if(result) + goto out; + + result = Curl_resolv_announce_start(data, ares->channel); + if(result) + goto out; + +#if defined(CURLVERBOSE) && ARES_VERSION >= 0x011800 /* >= v1.24.0 */ + if(CURL_TRC_DNS_is_verbose(data)) { + char *csv = ares_get_servers_csv(ares->channel); + CURL_TRC_DNS(data, "ares: servers=%s", csv); + ares_free_string(csv); + } +#endif + + curl_msnprintf(service, sizeof(service), "%d", async->peer->port); + socktype = + (Curl_conn_get_transport(data, data->conn) == TRNSPRT_TCP) ? + SOCK_STREAM : SOCK_DGRAM; + +#ifdef CURLRES_IPV6 + if(async->dns_queries & CURL_DNSQ_AAAA) { + struct ares_addrinfo_hints hints; + + memset(&hints, 0, sizeof(hints)); + CURL_TRC_DNS(data, "[AAAA] ares: query records for %s", + async->peer->hostname); + hints.ai_family = PF_INET6; + hints.ai_socktype = socktype; + hints.ai_flags = ARES_AI_NUMERICSERV; + async->queries_ongoing++; + ares_getaddrinfo(ares->channel, async->peer->hostname, + service, &hints, async_ares_AAAA_cb, async); + } +#endif /* CURLRES_IPV6 */ + + if(async->dns_queries & CURL_DNSQ_A) { + struct ares_addrinfo_hints hints; + + memset(&hints, 0, sizeof(hints)); + CURL_TRC_DNS(data, "[A] ares: query records for %s", + async->peer->hostname); + hints.ai_family = PF_INET; + hints.ai_socktype = socktype; + hints.ai_flags = ARES_AI_NUMERICSERV; + async->queries_ongoing++; + ares_getaddrinfo(ares->channel, async->peer->hostname, + service, &hints, async_ares_A_cb, async); + } + +#ifdef USE_HTTPSRR + if(async->dns_queries & CURL_DNSQ_HTTPS) { + char *https_name = NULL; + if(async->peer->port != 443) { + https_name = curl_maprintf("_%u._https.%s", + async->peer->port, async->peer->hostname); + if(!https_name) + return CURLE_OUT_OF_MEMORY; + } + CURL_TRC_DNS(data, "[HTTPS] ares: query records for %s", + https_name ? https_name : async->peer->hostname); + async->queries_ongoing++; + ares_query_dnsrec(ares->channel, + https_name ? https_name : async->peer->hostname, + ARES_CLASS_IN, ARES_REC_TYPE_HTTPS, + async_ares_rr_done, async, NULL); + curlx_free(https_name); + } +#endif /* USE_HTTPSRR */ + +out: + ares->result = result; + return result ? result : (async->queries_ongoing ? CURLE_AGAIN : CURLE_OK); +} + +/* Set what DNS server are is to use. This is called in 2 situations: + * 1. when the application does 'CURLOPT_DNS_SERVERS' and passing NULL + * means any previous set value should be unset. Which means + * we need to destroy and create the are channel anew, if there is one. + * 2. When we lazy init the ares channel and NULL means that there + * are no preferences and we do not reset any existing channel. */ +static CURLcode async_ares_set_dns_servers(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + struct async_ares_ctx *ares = async ? &async->ares : NULL; + CURLcode result = CURLE_NOT_BUILT_IN; + const char *servers = CURL_EASY_STR(data, STRING_DNS_SERVERS); + int ares_result = ARES_SUCCESS; + +#ifdef DEBUGBUILD + if(getenv("CURL_DNS_SERVER")) + servers = getenv("CURL_DNS_SERVER"); +#endif + + if(!servers) + return CURLE_OK; + + /* if channel is not there, this is a parameter check */ + if(ares && ares->channel) + ares_result = ares_set_servers_ports_csv(ares->channel, servers); + switch(ares_result) { + case ARES_SUCCESS: + result = CURLE_OK; + break; + case ARES_ENOMEM: + result = CURLE_OUT_OF_MEMORY; + break; + case ARES_ENOTINITIALIZED: + case ARES_ENODATA: + case ARES_EBADSTR: + default: + DEBUGF(infof(data, "bad servers set")); + result = CURLE_BAD_FUNCTION_ARGUMENT; + break; + } + return result; +} + +static CURLcode async_ares_set_dns_interface(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + struct async_ares_ctx *ares = async ? &async->ares : NULL; + const char *interf = CURL_EASY_STR(data, STRING_DNS_INTERFACE); + + if(!interf) + interf = ""; + + /* if channel is not there, this is a parameter check */ + if(ares && ares->channel) + ares_set_local_dev(ares->channel, interf); + + return CURLE_OK; +} + +static CURLcode async_ares_set_dns_local_ip4(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + struct async_ares_ctx *ares = async ? &async->ares : NULL; + struct in_addr a4; + const char *local_ip4 = CURL_EASY_STR(data, STRING_DNS_LOCAL_IP4); + + if(!local_ip4 || (local_ip4[0] == 0)) { + a4.s_addr = 0; /* disabled: do not bind to a specific address */ + } + else { + if(curlx_inet_pton(AF_INET, local_ip4, &a4) != 1) { + DEBUGF(infof(data, "bad DNS IPv4 address")); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + } + + /* if channel is not there yet, this is a parameter check */ + if(ares && ares->channel) + ares_set_local_ip4(ares->channel, ntohl(a4.s_addr)); + + return CURLE_OK; +} + +static CURLcode async_ares_set_dns_local_ip6(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ +#ifdef USE_IPV6 + struct async_ares_ctx *ares = async ? &async->ares : NULL; + unsigned char a6[INET6_ADDRSTRLEN]; + const char *local_ip6 = CURL_EASY_STR(data, STRING_DNS_LOCAL_IP6); + + if(!local_ip6 || (local_ip6[0] == 0)) { + /* disabled: do not bind to a specific address */ + memset(a6, 0, sizeof(a6)); + } + else { + if(curlx_inet_pton(AF_INET6, local_ip6, a6) != 1) { + DEBUGF(infof(data, "bad DNS IPv6 address")); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + } + + /* if channel is not there, this is a parameter check */ + if(ares && ares->channel) + ares_set_local_ip6(ares->channel, a6); + + return CURLE_OK; +#else /* no IPv6 support */ + (void)data; + (void)async; + return CURLE_NOT_BUILT_IN; +#endif +} + +#endif /* USE_RESOLV_ARES */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/asyn-base.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/asyn-base.c new file mode 100644 index 0000000000..f3db691c8c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/asyn-base.c @@ -0,0 +1,276 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#ifdef USE_ARES +#include <ares.h> +#endif + +#include "urldata.h" +#include "connect.h" +#include "curl_addrinfo.h" +#include "curl_trc.h" +#include "multiif.h" +#include "progress.h" +#include "select.h" +#include "url.h" +#include "vdns/hostip.h" +#include "vdns/httpsrr.h" + +/*********************************************************************** + * Only for builds using asynchronous name resolves + **********************************************************************/ +#ifdef CURLRES_ASYNCH + +timediff_t Curl_async_timeleft_ms(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + if(async->timeout_ms) { + timediff_t elapsed_ms = + curlx_ptimediff_ms(Curl_pgrs_now(data), &async->start); + return async->timeout_ms - elapsed_ms; + } + return Curl_timeleft_ms(data); +} + +#ifdef USE_ARES + +#if ARES_VERSION < 0x011000 +#error "c-ares 1.16.0 or greater required" +#endif + +/* + * Curl_ares_pollset() is called when the outside world (using + * curl_multi_fdset()) wants to get our fd_set setup and we are talking with + * ares. The caller must make sure that this function is only called when we + * have a working ares channel. + * + * Returns: sockets-in-use-bitmap + */ +CURLcode Curl_ares_pollset(struct Curl_easy *data, + ares_channel channel, + struct easy_pollset *ps) +{ + curl_socket_t sockets[16]; /* ARES documented limit */ + unsigned int bitmap, i; + CURLcode result = CURLE_OK; + + DEBUGASSERT(channel); + if(!channel) + return CURLE_FAILED_INIT; + + bitmap = ares_getsock(channel, (ares_socket_t *)sockets, + CURL_ARRAYSIZE(sockets)); + for(i = 0; i < CURL_ARRAYSIZE(sockets); ++i) { + int flags = 0; + if(ARES_GETSOCK_READABLE(bitmap, i)) + flags |= CURL_POLL_IN; + if(ARES_GETSOCK_WRITABLE(bitmap, i)) + flags |= CURL_POLL_OUT; + if(!flags) + break; + result = Curl_pollset_change(data, ps, sockets[i], flags, 0); + if(result) + return result; + } + return result; +} + +timediff_t Curl_ares_timeout_ms(struct Curl_easy *data, + struct Curl_resolv_async *async, + ares_channel channel) +{ + timediff_t async_timeout_ms; + + DEBUGASSERT(channel); + if(!channel) + return -1; + + async_timeout_ms = Curl_async_timeleft_ms(data, async); + if((async_timeout_ms > 0) && (async_timeout_ms < INT_MAX)) { + struct timeval timebuf; + struct timeval *timeout; + struct timeval end = { (int)async_timeout_ms / 1000, + ((int)async_timeout_ms % 1000) * 1000 }; + + timeout = ares_timeout(channel, &end, &timebuf); + if(timeout) + return curlx_tvtoms(timeout); + } + return async_timeout_ms; +} + +/* + * Curl_ares_perform() + * + * 1) Ask ares what sockets it currently plays with, then + * 2) wait for the timeout period to check for action on ares' sockets. + * 3) tell ares to act on all the sockets marked as "with action" + * + * return number of sockets it worked on, or -1 on error + */ +int Curl_ares_perform(ares_channel channel, timediff_t timeout_ms) +{ + int nfds; + int bitmask; + ares_socket_t socks[ARES_GETSOCK_MAXNUM]; + struct pollfd pfd[ARES_GETSOCK_MAXNUM]; + int i; + int num = 0; + + if(!channel) + return 0; + + bitmask = ares_getsock(channel, socks, ARES_GETSOCK_MAXNUM); + + for(i = 0; i < ARES_GETSOCK_MAXNUM; i++) { + pfd[i].events = 0; + pfd[i].revents = 0; + if(ARES_GETSOCK_READABLE(bitmask, i)) { + pfd[i].fd = socks[i]; + pfd[i].events |= POLLRDNORM | POLLIN; + } + if(ARES_GETSOCK_WRITABLE(bitmask, i)) { + pfd[i].fd = socks[i]; + pfd[i].events |= POLLWRNORM | POLLOUT; + } + if(pfd[i].events) + num++; + else + break; + } + + if(num) { + nfds = Curl_poll(pfd, (unsigned int)num, timeout_ms); + if(nfds < 0) + return -1; + } + else + nfds = 0; + + if(!nfds) + /* Call ares_process() unconditionally here, even if we timed out + above, as otherwise the ares name resolve will not timeout! */ + ares_process_fd(channel, ARES_SOCKET_BAD, ARES_SOCKET_BAD); + else { + /* move through the descriptors and ask for processing on them */ + for(i = 0; i < num; i++) + ares_process_fd(channel, + (pfd[i].revents & (POLLRDNORM | POLLIN)) ? + pfd[i].fd : ARES_SOCKET_BAD, + (pfd[i].revents & (POLLWRNORM | POLLOUT)) ? + pfd[i].fd : ARES_SOCKET_BAD); + } + return nfds; +} + +#endif /* USE_ARES */ + +#endif /* CURLRES_ASYNCH */ + +#ifdef USE_CURL_ASYNC + +#include "doh.h" + +void Curl_async_shutdown(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + if(async) { + CURL_TRC_DNS(data, "[%u] shutdown async", async->id); + async->shutdown = TRUE; +#ifdef USE_RESOLV_ARES + Curl_async_ares_shutdown(data, async); +#endif +#ifdef USE_RESOLV_THREADED + Curl_async_thrdd_shutdown(data, async); +#endif +#ifndef CURL_DISABLE_DOH + Curl_doh_cleanup(data, async); +#endif + } +} + +void Curl_async_destroy(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + if(async) { + CURL_TRC_DNS(data, "[%u] destroy async", async->id); + async->shutdown = TRUE; +#ifdef USE_RESOLV_ARES + Curl_async_ares_destroy(data, async); +#endif +#ifdef USE_RESOLV_THREADED + Curl_async_thrdd_destroy(data, async); +#endif +#ifndef CURL_DISABLE_DOH + Curl_doh_cleanup(data, async); +#endif + if(async->ai_A) + Curl_freeaddrinfo(async->ai_A); + if(async->ai_AAAA) + Curl_freeaddrinfo(async->ai_AAAA); +#ifdef USE_HTTPSRR + Curl_httpsrr_destroy(async->httpsrr); +#endif + Curl_peer_unlink(&async->peer); + curlx_safefree(async); + } +} + +CURLcode Curl_async_failed(struct Curl_easy *data, + struct Curl_resolv_async *async, + const char *detail) +{ + const char *host_or_proxy = "host"; + CURLcode result = CURLE_COULDNT_RESOLVE_HOST; + +#ifndef CURL_DISABLE_PROXY + if(async->for_proxy) { + host_or_proxy = "proxy"; + result = CURLE_COULDNT_RESOLVE_PROXY; + } +#endif + + if(async->dns_queries & (CURL_DNSQ_A | CURL_DNSQ_AAAA)) + failf(data, "Could not resolve %s: %s%s%s%s", + host_or_proxy, async->peer->hostname, + detail ? " (" : "", detail ? detail : "", detail ? ")" : ""); + return result; +} + +#endif /* USE_CURL_ASYNC */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/asyn-thrdd.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/asyn-thrdd.c new file mode 100644 index 0000000000..1ca217a79e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/asyn-thrdd.c @@ -0,0 +1,932 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/*********************************************************************** + * Only for threaded name resolves builds + **********************************************************************/ +#ifdef USE_RESOLV_THREADED + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#ifdef HAVE_GETADDRINFO +#define RESOLVER_ENOMEM EAI_MEMORY /* = WSA_NOT_ENOUGH_MEMORY on Windows */ +#else +#define RESOLVER_ENOMEM SOCKENOMEM +#endif + +#include "urldata.h" +#include "cfilters.h" +#include "curl_addrinfo.h" +#include "curl_trc.h" +#include "url.h" +#include "multiif.h" +#include "curl_threads.h" +#include "progress.h" +#include "rand.h" +#include "select.h" +#include "thrdqueue.h" +#include "vdns/hostip.h" +#include "vdns/httpsrr.h" +#include "curlx/strparse.h" +#include "curlx/wait.h" + +#ifdef USE_ARES +#include <ares.h> +#ifdef USE_HTTPSRR +#define USE_HTTPSRR_ARES /* the combo */ +#endif +#endif + + +/* + * Curl_async_global_init() + * Called from curl_global_init() to initialize global resolver environment. + * Does nothing here. + */ +int Curl_async_global_init(void) +{ +#if defined(USE_ARES) && defined(CARES_HAVE_ARES_LIBRARY_INIT) + if(ares_library_init(ARES_LIB_INIT_ALL)) { + return CURLE_FAILED_INIT; + } +#endif + return CURLE_OK; +} + +/* + * Curl_async_global_cleanup() + * Called from curl_global_cleanup() to destroy global resolver environment. + * Does nothing here. + */ +void Curl_async_global_cleanup(void) +{ +#if defined(USE_ARES) && defined(CARES_HAVE_ARES_LIBRARY_INIT) + ares_library_cleanup(); +#endif +} + +#ifdef CURLVERBOSE +#define CURL_ASYN_ITEM_DESC_LEN 64 +#define async_item_description(x) (x)->description +#else +#define async_item_description(x) NULL +#endif + +struct async_thrdd_item { + struct Curl_addrinfo *res; +#ifdef CURLVERBOSE + char description[CURL_ASYN_ITEM_DESC_LEN]; +#endif + int sockerr; + uint32_t mid; + uint32_t resolv_id; + uint16_t port; + uint8_t transport; + uint8_t dns_queries; + BIT(negative); /* resolver answered that the name does not exist */ +#ifdef DEBUGBUILD + uint32_t delay_ms; + uint32_t delay_fail_ms; + BIT(dbg_negative); +#endif + char hostname[1]; +}; + +/* Give up reference to add_ctx */ +static void async_thrdd_item_destroy(struct async_thrdd_item *item) +{ + if(item) { + if(item->res) + Curl_freeaddrinfo(item->res); + curlx_free(item); + } +} + +/* Initialize context for threaded resolver */ +static struct async_thrdd_item *async_thrdd_item_create( + struct Curl_easy *data, + uint32_t resolv_id, uint8_t dns_queries, + const char *hostname, uint16_t port, + uint8_t transport) +{ + size_t hostlen = strlen(hostname); + struct async_thrdd_item *item; + + item = curlx_calloc(1, sizeof(*item) + hostlen); + if(!item) + return NULL; + + if(hostlen) /* NUL byte of name already in struct size */ + memcpy(item->hostname, hostname, hostlen); + item->mid = data->mid; + item->resolv_id = resolv_id; + item->dns_queries = dns_queries; + item->port = port; + item->transport = transport; + +#ifdef CURLVERBOSE + curl_msnprintf(item->description, sizeof(item->description), + "[%" FMT_OFF_T "/%u] %s %s:%u", + data->id, item->resolv_id, + Curl_resolv_query_str(dns_queries), + item->hostname, item->port); +#endif + +#ifdef DEBUGBUILD + { + const char *p = getenv("CURL_DBG_RESOLV_DELAY"); + if(p) { + curl_off_t l; + if(!curlx_str_number(&p, &l, UINT32_MAX)) { + item->delay_ms = (uint32_t)l; + } + } + p = getenv("CURL_DBG_RESOLV_FAIL_DELAY"); + if(p) { + curl_off_t l; + if(!curlx_str_number(&p, &l, UINT32_MAX)) { + unsigned char c = 0; + Curl_rand_bytes(data, FALSE, &c, 1); + item->delay_fail_ms = (uint32_t)l + c; + } + } + if(getenv("CURL_DBG_RESOLV_FAIL_NEGATIVE")) + item->dbg_negative = TRUE; + } +#endif + + return item; +} + +#ifdef USE_HTTPSRR_ARES + +static void async_thrdd_rr_done(void *user_data, ares_status_t status, + size_t timeouts, + const ares_dns_record_t *dnsrec) +{ + struct Curl_resolv_async *async = user_data; + struct async_thrdd_ctx *thrdd = async ? &async->thrdd : NULL; + + (void)timeouts; + if(!thrdd) + return; + + async->dns_responses |= CURL_DNSQ_HTTPS; + async->queries_ongoing--; + async->done = !async->queries_ongoing; + if((ARES_SUCCESS == status) && dnsrec) + async->result = Curl_httpsrr_from_ares(dnsrec, &async->httpsrr); +} + +static CURLcode async_rr_start(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + struct async_thrdd_ctx *thrdd = &async->thrdd; + char *https_name = NULL; + int status; + CURLcode result = CURLE_OK; + + DEBUGASSERT(!thrdd->rr.channel); + if(async->peer->port != 443) { + https_name = curl_maprintf("_%u._https.%s", + async->peer->port, async->peer->hostname); + if(!https_name) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + status = ares_init_options(&thrdd->rr.channel, NULL, 0); + if(status != ARES_SUCCESS) { + thrdd->rr.channel = NULL; + result = CURLE_FAILED_INIT; + goto out; + } +#ifdef DEBUGBUILD + if(getenv("CURL_DNS_SERVER")) { + const char *servers = getenv("CURL_DNS_SERVER"); + status = ares_set_servers_ports_csv(thrdd->rr.channel, servers); + if(status) { + result = CURLE_FAILED_INIT; + goto out; + } + } +#endif + + async->queries_ongoing++; + ares_query_dnsrec(thrdd->rr.channel, + https_name ? https_name : async->peer->hostname, + ARES_CLASS_IN, ARES_REC_TYPE_HTTPS, + async_thrdd_rr_done, async, NULL); + CURL_TRC_DNS(data, "[HTTPS] query records for %s", + https_name ? https_name : async->peer->hostname); + +out: + curlx_free(https_name); + return result; +} +#endif + +void Curl_async_thrdd_shutdown(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + Curl_async_thrdd_destroy(data, async); +} + +struct async_thrdd_match_ctx { + uint32_t mid; + uint32_t resolv_id; +}; + +static bool async_thrdd_match_item(void *qitem, void *match_data) +{ + const struct async_thrdd_match_ctx *ctx = match_data; + struct async_thrdd_item *item = qitem; + return (item->mid == ctx->mid) && (item->resolv_id == ctx->resolv_id); +} + +void Curl_async_thrdd_destroy(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + (void)data; + if(async->queries_ongoing && !async->done && + data->multi && data->multi->resolv_thrdq) { + /* Remove any resolve items still queued */ + struct async_thrdd_match_ctx mctx; + mctx.mid = data->mid; + mctx.resolv_id = async->id; + Curl_thrdq_clear(data->multi->resolv_thrdq, + async_thrdd_match_item, &mctx); + } +#ifdef USE_HTTPSRR_ARES + if(async->thrdd.rr.channel) { + ares_destroy(async->thrdd.rr.channel); + async->thrdd.rr.channel = NULL; + } +#endif + async_thrdd_item_destroy(async->thrdd.res_A); + async->thrdd.res_A = NULL; + async_thrdd_item_destroy(async->thrdd.res_AAAA); + async->thrdd.res_AAAA = NULL; +} + +/* + * Waits for a resolve to finish. This function should be avoided since using + * this risk getting the multi interface to "hang". + */ +CURLcode Curl_async_await(struct Curl_easy *data, uint32_t resolv_id, + struct Curl_dns_entry **pdns) +{ + struct Curl_resolv_async *async = Curl_async_get(data, resolv_id); + struct async_thrdd_ctx *thrdd = async ? &async->thrdd : NULL; + timediff_t milli, ms; + CURLcode result = CURLE_AGAIN; + + if(!thrdd) + return CURLE_FAILED_INIT; + + while(result == CURLE_AGAIN) { + while(async->queries_ongoing && !async->done) { + Curl_async_thrdd_multi_process(data->multi); + if(async->done) + break; + + ms = curlx_ptimediff_ms(Curl_pgrs_now(data), &async->start); + if(ms < 3) + milli = 0; + else if(ms <= 50) + milli = ms / 3; + else if(ms <= 250) + milli = 50; + else + milli = 200; + CURL_TRC_DNS(data, "await, waiting %" FMT_TIMEDIFF_T "ms", milli); + curlx_wait_ms(milli); + } + result = Curl_async_take_result(data, async, pdns); + } + return result; +} + +#ifdef HAVE_GETADDRINFO + +/* Was the getaddrinfo() failure an authoritative negative answer, + i.e. the resolver responded that the name (or its data) does not + exist? Transient failures like EAI_AGAIN and local troubles must + not count as negative answers. */ +static bool gai_negative(int rc) +{ + switch(rc) { +#ifdef EAI_NONAME + case EAI_NONAME: +#endif +#if defined(EAI_NODATA) && \ + (!defined(EAI_NONAME) || (EAI_NODATA != EAI_NONAME)) + case EAI_NODATA: +#endif + return TRUE; + default: + return FALSE; + } +} + +/* Process the item, using Curl_getaddrinfo_ex() */ +static void async_thrdd_item_process(void *arg) +{ + struct async_thrdd_item *item = arg; + struct addrinfo hints; + char service[12]; + int pf = PF_INET; + int rc; + +#ifdef DEBUGBUILD + if(item->delay_ms) { + curlx_wait_ms(item->delay_ms); + } + if(item->delay_fail_ms) { + curlx_wait_ms(item->delay_fail_ms); + item->negative = item->dbg_negative; + return; + } +#endif + + memset(&hints, 0, sizeof(hints)); +#ifdef CURLRES_IPV6 + if(item->dns_queries & CURL_DNSQ_AAAA) { + pf = (item->dns_queries & CURL_DNSQ_A) ? PF_UNSPEC : PF_INET6; + } +#endif + hints.ai_family = pf; + hints.ai_socktype = Curl_socktype_for_transport(item->transport); + hints.ai_protocol = Curl_protocol_for_transport(item->transport); +#ifdef __APPLE__ + /* If we leave `ai_flags == 0` then macOS is looking for IPV4MAPPED + * when doing AAAA queries. We do not want this "help". */ + hints.ai_flags = AI_ADDRCONFIG; +#endif + + curl_msnprintf(service, sizeof(service), "%u", item->port); +#ifdef AI_NUMERICSERV + hints.ai_flags |= AI_NUMERICSERV; +#endif + + rc = Curl_getaddrinfo_ex(item->hostname, service, &hints, &item->res); + if(rc) { + item->sockerr = SOCKERRNO ? SOCKERRNO : rc; + if(item->sockerr == 0) + item->sockerr = RESOLVER_ENOMEM; + item->negative = gai_negative(rc); + } + else { + Curl_addrinfo_set_port(item->res, item->port); + } +} + +#else /* HAVE_GETADDRINFO */ + +/* Process the item, using Curl_ipv4_resolve_r() */ +static void async_thrdd_item_process(void *arg) +{ + struct async_thrdd_item *item = arg; + +#ifdef DEBUGBUILD + if(item->delay_ms) { + curlx_wait_ms(item->delay_ms); + } + if(item->delay_fail_ms) { + curlx_wait_ms(item->delay_fail_ms); + item->negative = item->dbg_negative; + return; + } +#endif + item->res = Curl_ipv4_resolve_r(item->hostname, item->port); + if(!item->res) { + item->sockerr = SOCKERRNO; + if(item->sockerr == 0) + item->sockerr = RESOLVER_ENOMEM; + /* this resolver cannot tell a transient failure from an + authoritative negative answer, treat it as before */ + item->negative = TRUE; + } +} + +#endif /* HAVE_GETADDRINFO */ + +#ifdef ENABLE_INTERNAL_WAKEUP +static void async_thrdd_event(const struct curl_thrdq *tqueue, + Curl_thrdq_event ev, + void *user_data) +{ + struct Curl_multi *multi = user_data; + (void)tqueue; + switch(ev) { + case CURL_THRDQ_EV_ITEM_DONE: + Curl_multi_wakeup_internal(multi); + break; + default: + break; + } +} +#else +#define async_thrdd_event NULL +#endif + +static void async_thrdd_item_free(void *item) +{ + async_thrdd_item_destroy(item); +} + +/* Create a thread queue for processing resolv items */ +CURLcode Curl_async_thrdd_multi_init(struct Curl_multi *multi, + uint32_t min_threads, + uint32_t max_threads, + uint32_t idle_time_ms) +{ + CURLcode result; + DEBUGASSERT(!multi->resolv_thrdq); + result = Curl_thrdq_create(&multi->resolv_thrdq, "DNS", + min_threads, max_threads, idle_time_ms, + async_thrdd_item_free, + async_thrdd_item_process, + async_thrdd_event, + multi); +#ifdef DEBUGBUILD + if(!result) { + const char *p = getenv("CURL_DBG_RESOLV_MAX_THREADS"); + if(p) { + curl_off_t l; + if(!curlx_str_number(&p, &l, UINT32_MAX)) { + result = Curl_async_thrdd_multi_set_props( + multi, min_threads, (uint32_t)l, idle_time_ms); + } + } + } +#endif + return result; +} + +/* Tear down the thread queue, joining active threads or detaching them */ +void Curl_async_thrdd_multi_destroy(struct Curl_multi *multi, bool join) +{ + if(multi->resolv_thrdq) { +#ifdef CURLVERBOSE + CURL_TRC_DNS(multi->admin, "destroy thread queue+pool, join=%d", join); + Curl_thrdq_trace(multi->resolv_thrdq, multi->admin); +#endif + Curl_thrdq_destroy(multi->resolv_thrdq, join); + multi->resolv_thrdq = NULL; + } +} + +#ifdef CURLVERBOSE +static void async_thrdd_report_item(struct Curl_easy *data, + struct async_thrdd_item *item) +{ + char buf[MAX_IPADR_LEN]; + struct dynbuf tmp; + const char *sep = ""; + const struct Curl_addrinfo *ai = item->res; + CURLcode result; + int ai_family; +#ifdef USE_IPV6 + ai_family = (item->dns_queries & CURL_DNSQ_AAAA) ? AF_INET6 : AF_INET; +#else + ai_family = AF_INET; +#endif + + if(!CURL_TRC_DNS_is_verbose(data)) + return; + + curlx_dyn_init(&tmp, 1024); + for(; ai; ai = ai->ai_next) { + if(ai->ai_family == ai_family) { + Curl_printable_address(ai, buf, sizeof(buf)); + result = curlx_dyn_addf(&tmp, "%s%s", sep, buf); + if(result) { + CURL_TRC_DNS(data, "too many IP, cannot show"); + goto out; + } + sep = ", "; + } + } + + CURL_TRC_DNS(data, "Host %s:%u resolved IPv%c: %s", + item->hostname, item->port, + (item->dns_queries & CURL_DNSQ_AAAA) ? '6' : '4', + (curlx_dyn_len(&tmp) ? curlx_dyn_ptr(&tmp) : "(none)")); +out: + curlx_dyn_free(&tmp); +} +#endif /* CURLVERBOSE */ + +/* Process the receiving end of the thread queue, dispatching + * processed items to their transfer when it can still be found + * and has an `async` state present. Otherwise, destroy the item. */ +void Curl_async_thrdd_multi_process(struct Curl_multi *multi) +{ + struct Curl_easy *data; + void *qitem; + + while(!Curl_thrdq_recv(multi->resolv_thrdq, &qitem)) { + /* dispatch resolve result */ + struct async_thrdd_item *item = qitem; + struct Curl_resolv_async *async = NULL; + + data = Curl_multi_get_easy(multi, item->mid); + if(data) + async = Curl_async_get(data, item->resolv_id); + if(async) { + struct async_thrdd_item **pdest = &async->thrdd.res_A; + +#ifdef CURLRES_IPV6 + if(item->dns_queries & CURL_DNSQ_AAAA) + pdest = &async->thrdd.res_AAAA; +#endif + if(!*pdest) { + *pdest = item; + item = NULL; + } + else + DEBUGASSERT(0); /* should not receive duplicates here */ + + --async->queries_ongoing; + Curl_multi_mark_dirty(data); + } + async_thrdd_item_free(item); + } + VERBOSE(Curl_thrdq_trace(multi->resolv_thrdq, multi->admin)); +} + +CURLcode Curl_async_thrdd_multi_set_props(struct Curl_multi *multi, + uint32_t min_threads, + uint32_t max_threads, + uint32_t idle_time_ms) +{ + return Curl_thrdq_set_props(multi->resolv_thrdq, + min_threads, max_threads, idle_time_ms); +} + +static CURLcode async_thrdd_query(struct Curl_easy *data, + struct Curl_resolv_async *async, + uint8_t dns_queries) +{ + struct async_thrdd_item *item; + CURLcode result; + + item = async_thrdd_item_create(data, async->id, dns_queries, + async->peer->hostname, async->peer->port, + async->transport); + if(!item) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + CURL_TRC_DNS(data, "queueing query %s", item->description); + result = Curl_thrdq_send(data->multi->resolv_thrdq, item, + async_item_description(item), async->timeout_ms); + if(result) + goto out; + item = NULL; + async->queries_ongoing++; + +out: + if(item) + async_thrdd_item_free(item); + return result; +} + +CURLcode Curl_async_getaddrinfo(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + CURLcode result = CURLE_FAILED_INIT; + void *resolver = NULL; + + if(async->queries_ongoing || async->done) + return CURLE_FAILED_INIT; + +#ifdef USE_HTTPSRR_ARES + DEBUGASSERT(!async->thrdd.rr.channel); + if((async->dns_queries & CURL_DNSQ_HTTPS) && !async->is_ipaddr) { + result = async_rr_start(data, async); + if(result) + goto out; + resolver = async->thrdd.rr.channel; + } +#endif + + result = Curl_resolv_announce_start(data, resolver); + if(result) + return result; + +#ifdef CURLRES_IPV6 + /* Do not start an AAAA query for an IPv4 address when + * we will start an A query for it. */ + if((async->dns_queries & CURL_DNSQ_AAAA) && + !(async->is_ipv4addr && (async->dns_queries & CURL_DNSQ_A))) { + result = async_thrdd_query(data, async, CURL_DNSQ_AAAA); + if(result) + goto out; + } +#endif + if(async->dns_queries & CURL_DNSQ_A) { + result = async_thrdd_query(data, async, CURL_DNSQ_A); + if(result) + goto out; + } + +#ifdef CURLVERBOSE + Curl_thrdq_trace(data->multi->resolv_thrdq, data); +#endif + +out: + if(!async->queries_ongoing) + async->done = TRUE; + + if(result) + CURL_TRC_DNS(data, "error queueing query %s:%d -> %d", + async->peer->hostname, async->peer->port, (int)result); + return result; +} + +CURLcode Curl_async_pollset(struct Curl_easy *data, + struct Curl_resolv_async *async, + struct easy_pollset *ps) +{ + timediff_t timeout_ms; + + timeout_ms = Curl_async_timeleft_ms(data, async); +#ifdef USE_HTTPSRR_ARES + if(async->thrdd.rr.channel) { + CURLcode result = Curl_ares_pollset(data, async->thrdd.rr.channel, ps); + if(result) + return result; + timeout_ms = Curl_ares_timeout_ms(data, async, async->thrdd.rr.channel); + } +#else + (void)ps; +#endif + + if(!async->done) { + const struct curltime *pnow = Curl_pgrs_now(data); +#ifndef ENABLE_INTERNAL_WAKEUP + timediff_t stutter_ms, elapsed_ms; + elapsed_ms = curlx_ptimediff_ms(pnow, &async->start); + if(elapsed_ms < 3) + stutter_ms = 1; + else if(elapsed_ms <= 50) + stutter_ms = elapsed_ms / 3; + else if(elapsed_ms <= 250) + stutter_ms = 50; + else + stutter_ms = 200; + timeout_ms = CURLMIN(stutter_ms, timeout_ms); +#else + if(async->queries_ongoing && + !Curl_thrdq_check_started(data->multi->resolv_thrdq)) { + /* The queue has items but starting a worker thread to process + them just failed again; expire soon to check once more, + instead of sleeping on the full resolve timeout. */ + CURL_TRC_DNS(data, "resolver thread start failed again, retrying"); + timeout_ms = CURLMIN(100, timeout_ms); + } +#endif + Curl_expire_set(data, EXPIRE_ASYNC_NAME, timeout_ms, pnow); + } + return CURLE_OK; +} + +#if defined(USE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID) +static bool async_thrdd_item_missing_scope(struct Curl_easy *data, + struct async_thrdd_item *item) +{ + const struct Curl_addrinfo *ai; + + /* scope id already globally set */ + if(data->conn && data->conn->scope_id) + return FALSE; + + for(ai = item->res; ai; ai = ai->ai_next) { + if(ai->ai_family == AF_INET6) { + struct sockaddr_in6 *sa6 = (void *)ai->ai_addr; + if(IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr) && !sa6->sin6_scope_id) + return TRUE; + } + } + return FALSE; +} + +static void async_thrdd_item_strip_results(struct async_thrdd_item *item, + int ai_family) +{ + struct Curl_addrinfo *ai = item->res, **panchor = &item->res; + while(ai) { + if(ai->ai_family == ai_family) { + *panchor = ai->ai_next; + ai->ai_next = NULL; + Curl_freeaddrinfo(ai); + ai = *panchor; + } + else { + panchor = &ai->ai_next; + ai = ai->ai_next; + } + } +} + +#endif /* USE_IPV6 && HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID */ + +static CURLcode async_thrdd_check_done(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + struct async_thrdd_ctx *thrdd = &async->thrdd; + + (void)data; + if(thrdd->res_A && !thrdd->processed_A) { + VERBOSE(async_thrdd_report_item(data, thrdd->res_A)); + /* move addrinfos to the async result member */ + async->dns_responses |= thrdd->res_A->dns_queries; + async->ai_A = thrdd->res_A->res; + thrdd->res_A->res = NULL; + thrdd->processed_A = TRUE; + } + + if(thrdd->res_AAAA && !thrdd->processed_AAAA) { +#if defined(USE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID) + /* do we accept the incoming AAAA response? */ + if(!(thrdd->res_AAAA->dns_queries & CURL_DNSQ_A) && + async_thrdd_item_missing_scope(data, thrdd->res_AAAA)) { + /* We queried "only" AF_INET6. This may be problematic when the + * result has ipv6 link-local addresses and did not give + * any scope id for it. glibc has a long outstanding bug + * <https://sourceware.org/bugzilla/show_bug.cgi?id=14413> + * that gives scope ids only on AF_UNSPEC queries. */ + struct async_thrdd_item *item = thrdd->res_AAAA; + CURLcode result; + + /* Reuse the item and queue it again, this time with added + * CURL_DNSQ_A which resolves using AF_UNSPEC. */ + thrdd->res_AAAA = NULL; + item->dns_queries |= CURL_DNSQ_A; + if(item->res) { + Curl_freeaddrinfo(item->res); + item->res = NULL; + } + + CURL_TRC_DNS(data, "re-queueing query %s for AF_UNSPEC resolve", + item->description); + result = Curl_thrdq_send(data->multi->resolv_thrdq, item, + async_item_description(item), + async->timeout_ms); + if(result) { + async_thrdd_item_free(item); + return result; + } + async->queries_ongoing++; + return CURLE_AGAIN; + } + /* accepting the AAAA result, strip it of any AF_INET entries, + * as we might have resolved it with AF_UNSPEC. */ + async_thrdd_item_strip_results(thrdd->res_AAAA, AF_INET); +#endif /* USE_IPV6 && HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID */ + VERBOSE(async_thrdd_report_item(data, thrdd->res_AAAA)); + /* move addrinfos to the async result member */ + async->dns_responses |= thrdd->res_AAAA->dns_queries; + async->ai_AAAA = thrdd->res_AAAA->res; + thrdd->res_AAAA->res = NULL; + thrdd->processed_AAAA = TRUE; + } + + if(async->queries_ongoing) + return CURLE_AGAIN; + async->done = TRUE; + return CURLE_OK; +} + +/* + * Curl_async_take_result() is called repeatedly to check if a previous + * name resolve request has completed. It should also make sure to time-out if + * the operation seems to take too long. + */ +CURLcode Curl_async_take_result(struct Curl_easy *data, + struct Curl_resolv_async *async, + struct Curl_dns_entry **pdns) +{ + struct async_thrdd_ctx *thrdd = &async->thrdd; + struct Curl_dns_entry *dns = NULL; + CURLcode result = CURLE_OK; + + DEBUGASSERT(pdns); + *pdns = NULL; + +#ifdef USE_HTTPSRR_ARES + /* best effort, ignore errors */ + if(thrdd->rr.channel) + (void)Curl_ares_perform(thrdd->rr.channel, 0); +#endif +#ifndef ENABLE_INTERNAL_WAKEUP + Curl_async_thrdd_multi_process(data->multi); +#endif + + result = async_thrdd_check_done(data, async); + if(result) + return result; + + Curl_expire_clear(data, EXPIRE_ASYNC_NAME); + + /* A failure is an authoritative negative answer, eligible for + negative caching, only when every A/AAAA query performed came + back answering that the name does not exist. A query that + failed transiently or never returned is not an answer. */ + { + const uint8_t ip_queries = + async->dns_queries & (CURL_DNSQ_A | CURL_DNSQ_AAAA); + bool negative = (async->dns_responses & ip_queries) == ip_queries; + if(thrdd->res_A && (async->ai_A || !thrdd->res_A->negative)) + negative = FALSE; + if(thrdd->res_AAAA && (async->ai_AAAA || !thrdd->res_AAAA->negative)) + negative = FALSE; + if(!thrdd->res_A && !thrdd->res_AAAA) + negative = FALSE; + async->negative_answer = negative; + } + + if(async->result) { + result = async->result; + goto out; + } + + if(async->ai_A || async->ai_AAAA) { + dns = Curl_dnsc_mk_addr2( + data, async->dns_queries, &async->ai_A, &async->ai_AAAA, async->peer); + if(!dns) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + +#ifdef USE_HTTPSRR_ARES + if(!dns && thrdd->rr.channel) { + Curl_httpsrr_trace(data, async->httpsrr); + dns = Curl_dnsc_mk_https(data, &async->httpsrr, async->peer); + if(!dns) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } +#endif + + if(dns) { + *pdns = dns; + dns = NULL; + } +#ifdef CURLVERBOSE + Curl_thrdq_trace(data->multi->resolv_thrdq, data); +#endif + +out: + Curl_dns_entry_unlink(data, &dns); + Curl_async_thrdd_shutdown(data, async); + if(!result && !*pdns) + result = Curl_async_failed(data, async, NULL); + if(result && + (result != CURLE_COULDNT_RESOLVE_HOST) && + (result != CURLE_COULDNT_RESOLVE_PROXY)) { + CURL_TRC_DNS(data, "Error %d resolving %s:%d", + (int)result, async->peer->hostname, async->peer->port); + } + return result; +} + +#endif /* USE_RESOLV_THREADED */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/asyn.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/asyn.h new file mode 100644 index 0000000000..7eade656a5 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/asyn.h @@ -0,0 +1,271 @@ +#ifndef HEADER_CURL_ASYN_H +#define HEADER_CURL_ASYN_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_HTTPSRR) && defined(USE_ARES) +#include "vdns/httpsrr.h" +#endif + +struct Curl_easy; +struct Curl_dns_entry; +struct Curl_resolv_async; +struct Curl_multi; +struct easy_pollset; + +#ifdef CURLRES_ASYNCH + +#include "curl_addrinfo.h" + +struct hostent; +struct connectdata; +struct easy_pollset; + +#if defined(USE_RESOLV_ARES) && defined(USE_RESOLV_THREADED) +#error cannot have both USE_RESOLV_ARES and USE_RESOLV_THREADED defined +#endif + +/* + * This header defines all functions in the internal asynch resolver interface. + * All asynch resolvers need to provide these functions. + * asyn-ares.c and asyn-thread.c are the current implementations of asynch + * resolver backends. + */ + +/* + * Curl_async_global_init() + * + * Called from curl_global_init() to initialize global resolver environment. + * Returning anything else than CURLE_OK fails curl_global_init(). + */ +int Curl_async_global_init(void); + +/* + * Curl_async_global_cleanup() + * Called from curl_global_cleanup() to destroy global resolver environment. + */ +void Curl_async_global_cleanup(void); + +/* + * Curl_async_getaddrinfo() - when using this resolver + * + * Returns name information about the given hostname and port number. If + * successful, the 'hostent' is returned and the fourth argument will point to + * memory we need to free after use. That memory *MUST* be freed with + * Curl_freeaddrinfo(), nothing else. + * + * Each resolver backend must of course make sure to return data in the + * correct format to comply with this. + */ +CURLcode Curl_async_getaddrinfo(struct Curl_easy *data, + struct Curl_resolv_async *async); + +#ifdef USE_HTTPSRR +bool Curl_async_knows_https(struct Curl_easy *data, + struct Curl_resolv_async *async); +#endif /* USE_HTTPSRR */ + +#ifdef USE_ARES +/* common functions for c-ares and threaded resolver with HTTPSRR */ +#include <ares.h> + +CURLcode Curl_ares_pollset(struct Curl_easy *data, + ares_channel channel, + struct easy_pollset *ps); + +timediff_t Curl_ares_timeout_ms(struct Curl_easy *data, + struct Curl_resolv_async *async, + ares_channel channel); + +int Curl_ares_perform(ares_channel channel, timediff_t timeout_ms); +#endif + +#ifdef USE_RESOLV_ARES +/* async resolving implementation using c-ares alone */ +struct async_ares_ctx { + ares_channel channel; + int ares_status; /* ARES_SUCCESS, ARES_ENOTFOUND, etc. */ + CURLcode result; /* CURLE_OK or error handling response */ + BIT(transient_err); /* an A/AAAA query failed without the resolver + answering that the name does not exist */ +}; + +void Curl_async_ares_shutdown(struct Curl_easy *data, + struct Curl_resolv_async *async); +void Curl_async_ares_destroy(struct Curl_easy *data, + struct Curl_resolv_async *async); + +#endif /* USE_RESOLV_ARES */ + +#ifdef USE_RESOLV_THREADED + +struct async_thrdd_item; + +/* Context for threaded resolver */ +struct async_thrdd_ctx { + struct async_thrdd_item *res_A; /* IPv4 final result */ + struct async_thrdd_item *res_AAAA; /* IPv6 final result */ +#if defined(USE_HTTPSRR) && defined(USE_ARES) + struct { + ares_channel channel; + } rr; +#endif + BIT(processed_A); + BIT(processed_AAAA); +}; + +void Curl_async_thrdd_shutdown(struct Curl_easy *data, + struct Curl_resolv_async *async); +void Curl_async_thrdd_destroy(struct Curl_easy *data, + struct Curl_resolv_async *async); + +CURLcode Curl_async_thrdd_multi_init(struct Curl_multi *multi, + uint32_t min_threads, + uint32_t max_threads, + uint32_t idle_time_ms); +void Curl_async_thrdd_multi_destroy(struct Curl_multi *multi, bool join); +void Curl_async_thrdd_multi_process(struct Curl_multi *multi); + +CURLcode Curl_async_thrdd_multi_set_props(struct Curl_multi *multi, + uint32_t min_threads, + uint32_t max_threads, + uint32_t idle_time_ms); + +#endif /* USE_RESOLV_THREADED */ + +#ifndef CURL_DISABLE_DOH +struct doh_probes; +#endif + +/* + * Curl_async_await() + * + * Waits for a resolve to finish. This function should be avoided since using + * this risk getting the multi interface to "hang". + * + * On return 'dns' is assigned the resolved dns (CURLE_OK or NULL otherwise. + * + * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, + * CURLE_OPERATION_TIMEDOUT if a time-out occurred, or other errors. + */ +CURLcode Curl_async_await(struct Curl_easy *data, uint32_t resolv_id, + struct Curl_dns_entry **pdns); + +/* + * Take the result of an async resolve operation. + * Returns CURLE_OK with `*pdns` != NULL, CURLE_AGAIN while still + * ongoing or an error code for a failed resolve. + */ +CURLcode Curl_async_take_result(struct Curl_easy *data, + struct Curl_resolv_async *async, + struct Curl_dns_entry **pdns); + +/* Curl_async_pollset() + * + * This function is called from the Curl_multi_pollset() function. 'sock' is a + * pointer to an array to hold the file descriptors, with 'numsock' being the + * size of that array (in number of entries). This function is supposed to + * return bitmask indicating what file descriptors (referring to array indexes + * in the 'sock' array) to wait for, read/write. + */ +CURLcode Curl_async_pollset(struct Curl_easy *data, + struct Curl_resolv_async *async, + struct easy_pollset *ps); + +#else /* CURLRES_ASYNCH */ + +/* convert these functions if an asynch resolver is not used */ +#define Curl_async_global_init() CURLE_OK +#define Curl_async_global_cleanup() Curl_nop_stmt +#define Curl_async_await(a, b, c) CURLE_COULDNT_RESOLVE_HOST +#define Curl_async_take_result(x, y, z) CURLE_COULDNT_RESOLVE_HOST +#define Curl_async_pollset(x, y, z) CURLE_OK +#define Curl_async_knows_https(x, y) TRUE +#endif /* !CURLRES_ASYNCH */ + +#if defined(CURLRES_ASYNCH) || !defined(CURL_DISABLE_DOH) +#define USE_CURL_ASYNC +#endif + +#ifdef USE_CURL_ASYNC + +struct Curl_resolv_async { + struct Curl_resolv_async *next; + struct Curl_peer *peer; + struct Curl_addrinfo *ai_A; + struct Curl_addrinfo *ai_AAAA; +#ifdef USE_HTTPSRR + struct Curl_https_rrinfo *httpsrr; +#endif +#ifdef USE_RESOLV_ARES + struct async_ares_ctx ares; +#elif defined(USE_RESOLV_THREADED) + struct async_thrdd_ctx thrdd; +#endif +#ifndef CURL_DISABLE_DOH + struct doh_probes *doh; /* DoH specific data for this request */ +#endif + struct curltime start; + timediff_t interval_end; + timediff_t timeout_ms; + CURLcode result; + uint32_t poll_interval; + uint32_t id; /* unique id per easy handle of the resolve operation */ + uint8_t dns_queries; /* what queries are being performed */ + uint8_t dns_responses; /* what queries had responses so far. */ + uint8_t transport; + uint8_t queries_ongoing; + BIT(is_ipaddr); + BIT(is_ipv4addr); + BIT(for_proxy); + BIT(done); + BIT(shutdown); + BIT(negative_answer); /* resolver answered that the name does not + exist. Only such failures may be cached as + negative entries, not transient or local + resolver failures. */ +}; + +timediff_t Curl_async_timeleft_ms(struct Curl_easy *data, + struct Curl_resolv_async *async); + +/* Shut down the given async resolve. */ +void Curl_async_shutdown(struct Curl_easy *data, + struct Curl_resolv_async *async); + +/* Frees the resources of the given async resolve and the struct itself. */ +void Curl_async_destroy(struct Curl_easy *data, + struct Curl_resolv_async *async); + +CURLcode Curl_async_failed(struct Curl_easy *data, + struct Curl_resolv_async *async, + const char *detail); + +#else /* !USE_CURL_ASYNC */ +#define Curl_async_shutdown(x, y) Curl_nop_stmt +#endif /* USE_CURL_ASYNC */ + +/********** end of generic resolver interface functions *****************/ +#endif /* HEADER_CURL_ASYN_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/cf-dns.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/cf-dns.c new file mode 100644 index 0000000000..8a08912d93 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/cf-dns.c @@ -0,0 +1,691 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "urldata.h" +#include "curl_addrinfo.h" +#include "cfilters.h" +#include "connect.h" +#include "curl_trc.h" +#include "multiif.h" +#include "progress.h" +#include "url.h" +#include "vdns/cf-dns.h" +#include "vdns/dnscache.h" +#include "vdns/httpsrr.h" +#include "curlx/strparse.h" + +/* Max time to wait for AAAA before connecting sub-filters, e.g. + * letting cf-ip-happy.c do its work. */ +#define CURL_HE_AAAA_AWAIT_MS 25 + +struct cf_dns_ctx { + struct Curl_dns_entry *dns; + struct Curl_peer *peer; + CURLcode resolv_result; + timediff_t he_aaaa_await_ms; + uint32_t resolv_id; + uint8_t dns_queries; + uint8_t transport; + BIT(started); + BIT(announced); + BIT(for_proxy); +}; + +static struct cf_dns_ctx *cf_dns_ctx_create(struct Curl_easy *data, + struct Curl_peer *peer, + uint8_t dns_queries, + uint8_t transport, + bool for_proxy) +{ + struct cf_dns_ctx *ctx; + + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) + return NULL; + + Curl_peer_link(&ctx->peer, peer); + ctx->dns_queries = dns_queries; + ctx->transport = transport; + ctx->for_proxy = for_proxy; + ctx->he_aaaa_await_ms = CURL_HE_AAAA_AWAIT_MS; +#ifdef DEBUGBUILD + { + const char *p = getenv("CURL_DBG_HE_AAAA_AWAIT_MS"); + if(p) { + curl_off_t l; + if(!curlx_str_number(&p, &l, UINT32_MAX)) { + ctx->he_aaaa_await_ms = (uint32_t)l; + } + } + } +#endif + + CURL_TRC_DNS(data, "[%s] created DNS filter for %s:%u, transport=%x", + Curl_resolv_query_str(ctx->dns_queries), + peer->hostname, peer->port, ctx->transport); + return ctx; +} + +static void cf_dns_ctx_destroy(struct Curl_easy *data, + struct cf_dns_ctx *ctx) +{ + if(ctx) { + Curl_peer_unlink(&ctx->peer); + Curl_dns_entry_unlink(data, &ctx->dns); + curlx_free(ctx); + } +} + +#ifdef CURLVERBOSE +static void cf_dns_report_addr(struct Curl_easy *data, + struct dynbuf *tmp, + const char *label, + int ai_family, + const struct Curl_addrinfo *ai) +{ + char buf[MAX_IPADR_LEN]; + const char *sep = ""; + CURLcode result; + + curlx_dyn_reset(tmp); + for(; ai; ai = ai->ai_next) { + if(ai->ai_family == ai_family) { + Curl_printable_address(ai, buf, sizeof(buf)); + result = curlx_dyn_addf(tmp, "%s%s", sep, buf); + if(result) { + infof(data, "too many IP, cannot show"); + return; + } + sep = ", "; + } + } + + infof(data, "%s%s", label, + (curlx_dyn_len(tmp) ? curlx_dyn_ptr(tmp) : "(none)")); +} + +static void cf_dns_report(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct Curl_dns_entry *dns) +{ + struct cf_dns_ctx *ctx = cf->ctx; + struct dynbuf tmp; + + if(!Curl_trc_is_verbose(data) || + /* ignore no name or numerical IP addresses */ + !dns->hostname[0] || Curl_host_is_ipnum(dns->hostname)) + return; + + if(ctx->peer->unix_socket) { +#ifdef USE_UNIX_SOCKETS + CURL_TRC_CF(data, cf, "resolved unix://%s", ctx->peer->hostname); +#else + DEBUGASSERT(0); +#endif + } + else { + curlx_dyn_init(&tmp, 1024); + if(CURL_DNSQ_IS_ADDR(ctx->dns_queries)) { + infof(data, "Host %s:%u was resolved.", dns->hostname, dns->port); +#ifdef CURLRES_IPV6 + cf_dns_report_addr(data, &tmp, "IPv6: ", AF_INET6, dns->addr); +#endif + cf_dns_report_addr(data, &tmp, "IPv4: ", AF_INET, dns->addr); + } +#ifdef USE_HTTPSRR + else if(ctx->dns_queries & CURL_DNSQ_HTTPS) { + if(!dns->hinfo) + infof(data, "HTTPS-RR %s:%u: -", dns->hostname, dns->port); + else if(!Curl_httpsrr_applicable(data, dns->hinfo)) + infof(data, "HTTPS-RR %s:%u: not applicable", + dns->hostname, dns->port); + else { + CURLcode result = Curl_httpsrr_print(&tmp, dns->hinfo); + if(!result) + infof(data, "HTTPS-RR %s:%u: %s", + dns->hostname, dns->port, curlx_dyn_ptr(&tmp)); + else + infof(data, "Error printing HTTPS-RR information"); + } + } +#endif + curlx_dyn_free(&tmp); + } +} +#else +#define cf_dns_report(x, y, z) Curl_nop_stmt +#endif + +/************************************************************* + * Resolve the address of the server or proxy + *************************************************************/ +static CURLcode cf_dns_start(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct Curl_dns_entry **pdns) +{ + struct cf_dns_ctx *ctx = cf->ctx; + timediff_t timeout_ms = Curl_timeleft_ms(data); + CURLcode result = CURLE_OK; + + *pdns = NULL; + + CURL_TRC_CF(data, cf, "[%s] cf_dns_start %s %s:%u", + Curl_resolv_query_str(ctx->dns_queries), + ctx->peer->unix_socket ? "unix-domain-socket" : "host", + ctx->peer->hostname, ctx->peer->port); + if(ctx->peer->unix_socket) + ctx->dns_queries = CURL_DNSQ_A; /* treat it like an A resolve */ + + if(CURL_DNSQ_IS_ADDR(ctx->dns_queries)) { + if(Curl_is_ipv4addr(ctx->peer->hostname)) + ctx->dns_queries |= CURL_DNSQ_A; +#ifdef USE_IPV6 + else if(ctx->peer->ipv6) + ctx->dns_queries |= CURL_DNSQ_AAAA; +#endif + + result = Curl_resolv(data, ctx->peer, ctx->dns_queries, ctx->transport, + (bool)ctx->for_proxy, timeout_ms, + &ctx->resolv_id, pdns); + } +#ifdef USE_HTTPSRR + else if(ctx->dns_queries == CURL_DNSQ_HTTPS) { + result = Curl_resolv_https(data, ctx->peer, (bool)ctx->for_proxy, + timeout_ms, &ctx->resolv_id, pdns); + } +#endif + else { + failf(data, "unsupported DNS queries %x", ctx->dns_queries); + return CURLE_FAILED_INIT; + } + + DEBUGASSERT(!result || !*pdns); + if(!result) { /* resolved right away, either sync or from dnscache */ + DEBUGASSERT(*pdns); + return CURLE_OK; + } + else if(result == CURLE_AGAIN) { /* async resolv in progress */ + return CURLE_OK; + } + else if(result == CURLE_OPERATION_TIMEDOUT) { /* took too long */ + failf(data, "Failed to resolve '%s' with timeout after %" + FMT_TIMEDIFF_T " ms", ctx->peer->hostname, + Curl_pgrs_since_ms(data, NULL, TIMER_STARTSINGLE)); + return CURLE_OPERATION_TIMEDOUT; + } + else { + DEBUGASSERT(result); + if(ctx->dns_queries & (CURL_DNSQ_A | CURL_DNSQ_AAAA)) + failf(data, "Could not resolve: %s", ctx->peer->hostname); + return result; + } +} + +static bool cf_dns_ready_to_connect(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_dns_ctx *ctx = cf->ctx; + + if(ctx->resolv_result) + return TRUE; + else if(ctx->dns) + return TRUE; +#ifdef USE_CURL_ASYNC + else if(CURL_DNSQ_IS_ADDR(ctx->dns_queries)) { + const struct curltime *pnow; + timediff_t remain_ms; + /* For Happy Eyeballing, we can start on either A or AAAA resolves, + * but AAAA is preferred. We enforce a small delay for missing + * AAAA to arrive, then we let the connect continue. + * Note: if AAAA was never started (-4), it is considered to have + * an answer (e.g. a negative one). */ + if(Curl_resolv_has_answers(data, ctx->resolv_id, CURL_DNSQ_AAAA)) + return TRUE; + pnow = Curl_pgrs_now(data); + remain_ms = ctx->he_aaaa_await_ms - + Curl_resolv_elapsed_ms(data, ctx->resolv_id, pnow); + if(remain_ms <= 0) + return TRUE; + CURL_TRC_CF(data, cf, "[%s] still waiting %" FMT_TIMEDIFF_T + "ms for AAAA result", + Curl_resolv_query_str(ctx->dns_queries), remain_ms); + Curl_expire_set(data, EXPIRE_HAPPY_EYEBALLS, remain_ms, pnow); + return FALSE; + } + else { + return TRUE; + } +#else + (void)data; + DEBUGASSERT(0); /* We should not come here */ + return FALSE; +#endif /* USE_CURL_ASYNC */ +} + +static CURLcode cf_dns_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_dns_ctx *ctx = cf->ctx; + bool ip_query = (ctx->dns_queries & (CURL_DNSQ_A | CURL_DNSQ_AAAA)); + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; + if(!ctx->started) { + ctx->started = TRUE; + ctx->resolv_result = cf_dns_start(cf, data, &ctx->dns); + } + + if(!ctx->dns && !ctx->resolv_result) { + ctx->resolv_result = + Curl_resolv_take_result(data, ctx->resolv_id, &ctx->dns); + } + + if(ctx->resolv_result && ip_query) { + /* failing A|AAAA resolves is a hard failure. */ + CURL_TRC_CF(data, cf, "[%s] error resolving: %d", + Curl_resolv_query_str(ctx->dns_queries), + (int)ctx->resolv_result); + return ctx->resolv_result; + } + + if(ctx->dns && !ctx->announced) { + ctx->announced = TRUE; + if((cf->sockindex == FIRSTSOCKET) && ip_query) { + cf->conn->bits.dns_resolved = TRUE; + Curl_pgrsTime(data, TIMER_NAMELOOKUP); + } + cf_dns_report(cf, data, ctx->dns); + } + + /* Delay connection sub-filters when we are still waiting for AAAA */ + if(!cf_dns_ready_to_connect(cf, data)) { + return CURLE_OK; + } + + if(cf->next && !cf->next->connected) { + bool sub_done; + CURLcode result = Curl_conn_cf_connect(cf->next, data, &sub_done); + if(result || !sub_done) + return result; + DEBUGASSERT(sub_done); + } + + /* sub filter chain is connected, this means the filter has done + * its work and is connected as well, if it has results or not. */ + CURL_TRC_CF(data, cf, "connected filter chain below"); + *done = TRUE; + cf->connected = TRUE; + Curl_resolv_destroy(data, ctx->resolv_id); + return CURLE_OK; +} + +static void cf_dns_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_dns_ctx *ctx = cf->ctx; + + CURL_TRC_CF(data, cf, "destroy"); + cf_dns_ctx_destroy(data, ctx); +} + +static CURLcode cf_dns_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ +#ifdef USE_CURL_ASYNC + if(!cf->connected) { + /* The pollset only works when we have started the resolving. + * Otherwise we might wait on the WAKEUP socketpair forever. + * Since DNS filters can be added in the middle of a connect + * attempt, they are not always started that way. */ + struct cf_dns_ctx *ctx = cf->ctx; + if(!ctx->started) { + CURL_TRC_CF(data, cf, "adjust_pollset, starting %s:%u queries=%s", + ctx->peer->hostname, ctx->peer->port, + Curl_resolv_query_str(ctx->dns_queries)); + ctx->started = TRUE; + ctx->resolv_result = cf_dns_start(cf, data, &ctx->dns); + if(ctx->resolv_result || ctx->dns) { + Curl_multi_mark_dirty(data); + } + } + return Curl_resolv_pollset(data, ps); + } +#else + (void)cf; + (void)data; + (void)ps; +#endif + return CURLE_OK; +} + +static CURLcode cf_dns_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + struct cf_dns_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + (void)arg1; + (void)arg2; + switch(event) { + case CF_CTRL_DATA_DONE: + if(ctx->dns) { + /* Should only come here when the connect attempt failed and + * `data` is giving up on it. On a successful connect, we already + * unlinked the DNS entry. */ + Curl_dns_entry_unlink(data, &ctx->dns); + } + break; + default: + break; + } + return result; +} + +struct Curl_cftype Curl_cft_dns = { + "DNS", + CF_TYPE_SETUP | CF_TYPE_DNS, + CURL_LOG_LVL_NONE, + cf_dns_destroy, + cf_dns_connect, + Curl_cf_def_shutdown, + cf_dns_adjust_pollset, + Curl_cf_def_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + cf_dns_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + Curl_cf_def_query, +}; + +static CURLcode cf_dns_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *peer, + uint8_t dns_queries, + uint8_t transport, + bool for_proxy) +{ + struct Curl_cfilter *cf = NULL; + struct cf_dns_ctx *ctx; + CURLcode result = CURLE_OK; + + (void)data; + ctx = cf_dns_ctx_create(data, peer, dns_queries, transport, for_proxy); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + result = Curl_cf_create(&cf, &Curl_cft_dns, ctx); + +out: + *pcf = result ? NULL : cf; + if(result) + cf_dns_ctx_destroy(data, ctx); + return result; +} + +/* Adds a "resolv" filter at the top of the connection's filter chain. + * The filter will resolve the peer on the first connect attempt. */ +static CURLcode cf_dns_add(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + struct Curl_peer *peer, + uint8_t dns_queries, + uint8_t transport) +{ + struct Curl_cfilter *cf = NULL; + bool for_proxy = FALSE; + CURLcode result; + + if(!peer) + return CURLE_FAILED_INIT; +#ifndef CURL_DISABLE_PROXY + for_proxy = (peer == conn->socks_proxy.peer) || + (peer == conn->http_proxy.peer); +#endif + + result = cf_dns_create(&cf, data, peer, dns_queries, transport, for_proxy); + if(result) + goto out; + Curl_conn_cf_add(data, conn, sockindex, cf); +out: + return result; +} + +/* Insert a new "resolv" filter directly after `cf`. It will + * start a DNS resolve for the given peer on the + * first connect attempt. + * See socks.c on how this is used to make a non-blocking DNS + * resolve during connect. + */ +static CURLcode cf_dns_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *peer, + uint8_t dns_queries, + uint8_t transport) +{ + struct Curl_cfilter *cf; + CURLcode result; + + result = cf_dns_create(&cf, data, peer, dns_queries, transport, FALSE); + if(result) + return result; + + Curl_conn_cf_insert_after(cf_at, cf); + return CURLE_OK; +} + +static CURLcode cf_dns_add_resolve(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + struct Curl_peer *peer, + uint8_t dns_queries, + uint8_t transport) +{ + struct Curl_cfilter *cf = data->conn->cfilter[sockindex]; + struct Curl_cfilter *cf_dns = NULL; + bool is_addr = CURL_DNSQ_IS_ADDR(dns_queries); + + if((dns_queries & CURL_DNSQ_HTTPS) && + Curl_is_ipaddr(peer->hostname)) { + dns_queries = (uint8_t)(dns_queries & ~CURL_DNSQ_HTTPS); + } + + for(; cf && dns_queries; cf = cf->next) { + if(cf->cft == &Curl_cft_dns) { + struct cf_dns_ctx *ctx = cf->ctx; + cf_dns = cf; + if(Curl_peer_same_destination(ctx->peer, peer)) { + /* subtract queries already being scheduled/ongoing */ + dns_queries = (uint8_t)(~ctx->dns_queries & dns_queries); + if(!dns_queries) { /* already there */ + return CURLE_OK; + } + else if(is_addr && !ctx->started && + CURL_DNSQ_IS_ADDR(ctx->dns_queries)) { + ctx->dns_queries |= dns_queries; + CURL_TRC_DNS(data, "[%s] added queries=%s for %s:%u", + Curl_resolv_query_str(ctx->dns_queries), + Curl_resolv_query_str(dns_queries), + peer->hostname, peer->port); + return CURLE_OK; + } + } + } + } + + if(dns_queries) { + /* No existing filter is handling these, add a new DNS filter + * (after the last one if there was one already. FCFS. */ + if(cf_dns) + return cf_dns_insert_after(cf_dns, data, peer, dns_queries, transport); + else + return cf_dns_add(data, conn, sockindex, peer, dns_queries, transport); + } + return CURLE_OK; +} + +CURLcode Curl_conn_dns_add_addr_resolve(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + struct Curl_peer *peer, + uint8_t dns_queries, + uint8_t transport) +{ + /* should only have address query bits */ + DEBUGASSERT(!(dns_queries & ~CURL_DNSQ_ADDR)); + return cf_dns_add_resolve(data, conn, sockindex, peer, + (dns_queries & CURL_DNSQ_ADDR), transport); +} + +/* Return the result of the DNS address resolution for peer. + * Searches for a DNS filter from the top of the filter chain down. Returns + * - CURLE_AGAIN when not done yet + * - CURLE_OK when DNS was successfully resolved + * - CURLR_FAILED_INIT when no resolv filter was found + * - error returned by the DNS resolv + */ +CURLcode Curl_conn_dns_addr_result(struct connectdata *conn, + int8_t sockindex, + struct Curl_peer *peer) +{ + struct Curl_cfilter *cf = conn->cfilter[sockindex]; + for(; cf; cf = cf->next) { + if(cf->cft == &Curl_cft_dns) { + struct cf_dns_ctx *ctx = cf->ctx; + if(Curl_peer_same_destination(ctx->peer, peer) && + (ctx->dns_queries & (CURL_DNSQ_A | CURL_DNSQ_AAAA))) { + if(ctx->dns || ctx->resolv_result) + return ctx->resolv_result; + return CURLE_AGAIN; + } + } + } + return CURLE_FAILED_INIT; /* no one is resolving */ +} + +/* Return the addrinfo at `index` for the given `family` from the + * first "resolve" filter at the connection. If the DNS resolving is + * not done yet or if no address for the family exists, returns NULL. + */ +const struct Curl_addrinfo *Curl_conn_dns_get_ai(struct Curl_easy *data, + struct Curl_peer *peer, + int8_t sockindex, + int ai_family, + unsigned int index) +{ + struct connectdata *conn = data->conn; + struct Curl_cfilter *cf = conn->cfilter[sockindex]; + + for(; cf; cf = cf->next) { + if(cf->cft == &Curl_cft_dns) { + struct cf_dns_ctx *ctx = cf->ctx; + if(Curl_peer_same_destination(ctx->peer, peer) && + (ctx->dns_queries & (CURL_DNSQ_A | CURL_DNSQ_AAAA))) { + CURL_TRC_CF(data, cf, "get %uth result for %s:%u, family=%d, dns=%d", + index, peer->hostname, peer->port, ai_family, !!ctx->dns); + if(ctx->resolv_result) + return NULL; + else if(ctx->dns) { + /* A cached DNS entry may contain address families that we + * here never queried for. We want to give no results for those. */ + if((ai_family == AF_INET) && !(ctx->dns_queries & CURL_DNSQ_A)) + return NULL; +#ifdef USE_IPV6 + if((ai_family == AF_INET6) && !(ctx->dns_queries & CURL_DNSQ_AAAA)) + return NULL; +#endif + return Curl_addrinfo_get(ctx->dns->addr, ai_family, index); + } + else + return Curl_resolv_get_ai(data, ctx->resolv_id, ai_family, index); + } + } + } + return NULL; +} + +#ifdef USE_HTTPSRR +CURLcode Curl_conn_dns_add_https_resolve(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + struct Curl_peer *peer) +{ + return cf_dns_add_resolve(data, conn, sockindex, peer, + CURL_DNSQ_HTTPS, conn->transport_wanted); +} + +/* Return the HTTPS-RR info from the first "resolve" filter at the + * connection. If the DNS resolving is not done yet or if there + * is no HTTPS-RR info, returns NULL. + */ +const struct Curl_https_rrinfo *Curl_conn_dns_get_https(struct Curl_easy *data, + int8_t sockindex, + struct Curl_peer *peer) +{ + struct Curl_cfilter *cf = data->conn->cfilter[sockindex]; + for(; cf; cf = cf->next) { + if(cf->cft == &Curl_cft_dns) { + struct cf_dns_ctx *ctx = cf->ctx; + if(Curl_peer_same_destination(ctx->peer, peer) && + (ctx->dns_queries & CURL_DNSQ_HTTPS)) { + if(ctx->dns) + return ctx->dns->hinfo; + else + return Curl_resolv_get_https(data, ctx->resolv_id); + } + } + } + return NULL; +} + +bool Curl_conn_dns_resolved_https(struct Curl_easy *data, + int8_t sockindex, + struct Curl_peer *peer) +{ + struct Curl_cfilter *cf = data->conn->cfilter[sockindex]; + for(; cf; cf = cf->next) { + if(cf->cft == &Curl_cft_dns) { + struct cf_dns_ctx *ctx = cf->ctx; + if(Curl_peer_same_destination(ctx->peer, peer) && + (ctx->dns_queries & CURL_DNSQ_HTTPS)) { + if(ctx->dns) + return TRUE; + else + return Curl_resolv_knows_https(data, ctx->resolv_id); + } + } + } + return TRUE; +} + +#endif /* USE_HTTPSRR */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/cf-dns.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/cf-dns.h new file mode 100644 index 0000000000..6226d2161a --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/cf-dns.h @@ -0,0 +1,71 @@ +#ifndef HEADER_CURL_CF_DNS_H +#define HEADER_CURL_CF_DNS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct Curl_easy; +struct connectdata; +struct Curl_dns_entry; +struct Curl_addrinfo; +struct Curl_peer; + +CURLcode Curl_conn_dns_add_addr_resolve(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + struct Curl_peer *peer, + uint8_t dns_queries, + uint8_t transport); + +CURLcode Curl_conn_dns_addr_result(struct connectdata *conn, + int8_t sockindex, + struct Curl_peer *peer); + +const struct Curl_addrinfo *Curl_conn_dns_get_ai(struct Curl_easy *data, + struct Curl_peer *peer, + int8_t sockindex, + int ai_family, + unsigned int index); + +#ifdef USE_HTTPSRR +CURLcode Curl_conn_dns_add_https_resolve(struct Curl_easy *data, + struct connectdata *conn, + int8_t sockindex, + struct Curl_peer *peer); + +const struct Curl_https_rrinfo * +Curl_conn_dns_get_https(struct Curl_easy *data, + int8_t sockindex, + struct Curl_peer *peer); +bool Curl_conn_dns_resolved_https(struct Curl_easy *data, + int8_t sockindex, + struct Curl_peer *peer); +#else +#define Curl_conn_dns_get_https(a, b, c) NULL +#define Curl_conn_dns_resolved_https(a, b, c) TRUE +#endif + +extern struct Curl_cftype Curl_cft_dns; + +#endif /* HEADER_CURL_CF_DNS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/dnscache.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/dnscache.c new file mode 100644 index 0000000000..bfd935ed47 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/dnscache.c @@ -0,0 +1,1008 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETINET_IN6_H +#include <netinet/in6.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include "urldata.h" +#include "curl_addrinfo.h" +#include "curl_share.h" +#include "curl_trc.h" +#include "hash.h" +#include "progress.h" +#include "rand.h" +#include "strcase.h" +#include "vdns/dnscache.h" +#include "vdns/hostip.h" +#include "vdns/httpsrr.h" +#include "curlx/inet_ntop.h" +#include "curlx/inet_pton.h" +#include "curlx/strcopy.h" +#include "curlx/strparse.h" + +#define MAX_HOSTCACHE_LEN (255 + 7) /* max FQDN + colon + port number + zero */ + +#define MAX_DNS_CACHE_SIZE 29999 + +struct dnsc_id { + struct Curl_str name; + uint16_t port; + char type; +}; + +static void dnsc_peer2id(struct dnsc_id *pid, char type, + struct Curl_peer *peer) +{ + curlx_str_assign(&pid->name, peer->hostname, strlen(peer->hostname)); + pid->port = peer->port; + pid->type = type; +} + +static void dnsc_str2id(struct dnsc_id *pid, char type, + struct Curl_str *name, uint16_t port) +{ + pid->name = *name; + pid->port = port; + pid->type = type; +} + +struct dnsc_key { + char data[MAX_HOSTCACHE_LEN]; + size_t len; +}; + +/* + * Create a hostcache id string for the provided host + port, to be used by + * the DNS caching. Without alloc. Return length of the id string. + */ +static void dnsc_id2key(struct dnsc_key *key, struct dnsc_id *id) +{ + size_t namelen = curlx_strlen(&id->name); + if(namelen > (sizeof(key->data) - 8)) + namelen = sizeof(key->data) - 8; + /* store and lower case the name */ + key->data[0] = id->type; + Curl_strntolower(key->data + 1, curlx_str(&id->name), namelen); + /* include the terminating 0 in key length */ + key->len = namelen + 2 + + curl_msnprintf(&key->data[namelen + 1], 7, ":%u", id->port); +} + +static void dnscache_entry_free(struct Curl_dns_entry *dns) +{ + Curl_freeaddrinfo(dns->addr); +#ifdef USE_HTTPSRR + Curl_httpsrr_destroy(dns->hinfo); +#endif + curlx_free(dns); +} + +struct dnscache_prune_data { + struct curltime now; + timediff_t oldest_ms; /* oldest time in cache not pruned. */ + timediff_t max_age_ms; +}; + +/* + * This function is set as a callback to be called for every entry in the DNS + * cache when we want to prune old unused entries. + * + * Returning non-zero means remove the entry, return 0 to keep it in the + * cache. + */ +static int dnscache_entry_is_stale(void *datap, void *hc) +{ + struct dnscache_prune_data *prune = (struct dnscache_prune_data *)datap; + struct Curl_dns_entry *dns = (struct Curl_dns_entry *)hc; + + if(dns->timestamp.tv_sec || dns->timestamp.tv_usec) { + /* get age in milliseconds */ + timediff_t age = curlx_ptimediff_ms(&prune->now, &dns->timestamp); + if(!dns->addr) + age *= 2; /* negative entries age twice as fast */ + if(age >= prune->max_age_ms) + return TRUE; + if(age > prune->oldest_ms) + prune->oldest_ms = age; + } + return FALSE; +} + +/* + * Prune the DNS cache. This assumes that a lock has already been taken. + * Returns the 'age' of the oldest still kept entry - in milliseconds. + */ +static timediff_t dnscache_prune(struct Curl_hash *hostcache, + timediff_t cache_timeout_ms, + struct curltime now) +{ + struct dnscache_prune_data user; + + user.max_age_ms = cache_timeout_ms; + user.now = now; + user.oldest_ms = 0; + + Curl_hash_clean_with_criterium(hostcache, + (void *)&user, + dnscache_entry_is_stale); + + return user.oldest_ms; +} + +static struct Curl_dnscache *dnscache_get(struct Curl_easy *data) +{ + if(data->share && data->share->specifier & (1 << CURL_LOCK_DATA_DNS)) + return &data->share->dnscache; + if(data->multi) + return &data->multi->dnscache; + return NULL; +} + +static void dnscache_lock(struct Curl_easy *data, + struct Curl_dnscache *dnscache) +{ + if(data->share && dnscache == &data->share->dnscache) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); +} + +static void dnscache_unlock(struct Curl_easy *data, + struct Curl_dnscache *dnscache) +{ + if(data->share && dnscache == &data->share->dnscache) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); +} + +/* + * Library-wide function for pruning the DNS cache. This function takes and + * returns the appropriate locks. + */ +void Curl_dnscache_prune(struct Curl_easy *data) +{ + struct Curl_dnscache *dnscache = dnscache_get(data); + /* the timeout may be set -1 (forever) */ + timediff_t timeout_ms = data->set.dns_cache_timeout_ms; + + if(!dnscache || (timeout_ms == -1)) + /* NULL hostcache means we cannot do it */ + return; + + dnscache_lock(data, dnscache); + + do { + /* Remove outdated and unused entries from the hostcache */ + timediff_t oldest_ms = + dnscache_prune(&dnscache->entries, timeout_ms, *Curl_pgrs_now(data)); + + if(Curl_hash_count(&dnscache->entries) > MAX_DNS_CACHE_SIZE) + /* prune the ones over half this age */ + timeout_ms = oldest_ms / 2; + else + break; + + /* if the cache size is still too big, use the oldest age as new prune + limit */ + } while(timeout_ms); + + dnscache_unlock(data, dnscache); +} + +void Curl_dnscache_clear(struct Curl_easy *data) +{ + struct Curl_dnscache *dnscache = dnscache_get(data); + if(dnscache) { + dnscache_lock(data, dnscache); + Curl_hash_clean(&dnscache->entries); + dnscache_unlock(data, dnscache); + } +} + +/* lookup address, returns entry if found and not stale */ +static CURLcode fetch_addr(struct Curl_easy *data, + struct Curl_dnscache *dnscache, + uint8_t dns_queries, + struct Curl_peer *peer, + struct Curl_dns_entry **pdns) +{ + struct Curl_dns_entry *dns = NULL; + struct dnsc_id id; + struct dnsc_key key; + char type = CURL_DNSQ_IS_ADDR(dns_queries) ? + CURL_DNST_ADDR : CURL_DNST_HTTPS; + CURLcode result = CURLE_OK; + + *pdns = NULL; + if(!dnscache) + return CURLE_OK; + + dnsc_peer2id(&id, type, peer); + dnsc_id2key(&key, &id); + + /* See if it is already in our dns cache */ + dns = Curl_hash_pick(&dnscache->entries, key.data, key.len); + + /* No entry found in cache, check if we might have a wildcard entry */ + if(!dns && (type == CURL_DNST_ADDR) && data->state.wildcard_resolve) { + struct Curl_str wildname; + + curlx_str_assign(&wildname, "*", 1); + dnsc_str2id(&id, CURL_DNST_ADDR, &wildname, peer->port); + dnsc_id2key(&key, &id); + + /* See if it is already in our dns cache */ + dns = Curl_hash_pick(&dnscache->entries, key.data, key.len); + } + + if(dns && (data->set.dns_cache_timeout_ms != -1)) { + /* See whether the returned entry is stale. Done before we release lock */ + struct dnscache_prune_data user; + + user.now = *Curl_pgrs_now(data); + user.max_age_ms = data->set.dns_cache_timeout_ms; + user.oldest_ms = 0; + + if(dnscache_entry_is_stale(&user, dns)) { + infof(data, "Hostname in DNS cache was stale, zapped"); + dns = NULL; /* the memory deallocation is being handled by the hash */ + Curl_hash_delete(&dnscache->entries, key.data, key.len); + } + } + + /* We need to cache address information and HTTPS-RR separately. */ + if(dns && CURL_DNSQ_IS_ADDR(dns_queries)) { + if((uint8_t)(dns->dns_queries & dns_queries) != + (uint8_t)(dns_queries & CURL_DNSQ_ADDR)) { + /* The entry does not cover all wanted address queries, a miss. */ + dns = NULL; + } + else if(!(dns->dns_responses & dns_queries)) { + /* The entry has no responses for the wanted DNS queries. */ + CURL_TRC_DNS(data, "cache entry does not have type=%s addresses", + Curl_resolv_query_str(dns_queries)); + dns = NULL; + result = CURLE_COULDNT_RESOLVE_HOST; + } + else if(dns && !dns->addr) { /* negative entry */ + dns = NULL; + result = CURLE_COULDNT_RESOLVE_HOST; + } + } + + *pdns = dns; + return result; +} + +/* + * Curl_dnscache_get() fetches a 'Curl_dns_entry' already in the DNS cache. + * + * Curl_resolv() checks initially and multi_runsingle() checks each time + * it discovers the handle in the state WAITRESOLVE whether the hostname + * has already been resolved and the address has already been stored in + * the DNS cache. This short circuits waiting for a lot of pending + * lookups for the same hostname requested by different handles. + * + * Returns the Curl_dns_entry entry pointer or NULL if not in the cache. + * + * The returned data *MUST* be "released" with Curl_dns_entry_unlink() after + * use, or we will leak memory! + */ +CURLcode Curl_dnscache_get(struct Curl_easy *data, + uint8_t dns_queries, + struct Curl_peer *peer, + struct Curl_dns_entry **pentry) +{ + struct Curl_dnscache *dnscache = dnscache_get(data); + struct Curl_dns_entry *dns = NULL; + CURLcode result = CURLE_OK; + + dnscache_lock(data, dnscache); + result = fetch_addr(data, dnscache, dns_queries, peer, &dns); + if(!result && dns) + dns->refcount++; /* we pass out a reference */ + else if(result) { + DEBUGASSERT(!dns); + dns = NULL; + } + dnscache_unlock(data, dnscache); + + CURL_TRC_DNS(data, "cache lookup %s:%u queries=%s -> %d %sfound", + peer->hostname, peer->port, Curl_resolv_query_str(dns_queries), + (int)result, dns ? "" : "not "); + *pentry = dns; + return result; +} + +#ifndef CURL_DISABLE_SHUFFLE_DNS +/* + * Return # of addresses in a Curl_addrinfo struct + */ +static int num_addresses(const struct Curl_addrinfo *addr) +{ + int i = 0; + while(addr) { + addr = addr->ai_next; + i++; + } + return i; +} + +/* + * dns_shuffle_addr() shuffles the order of addresses in a 'Curl_addrinfo' + * struct by re-linking its linked list. + * + * The addr argument should be the address of a pointer to the head node of a + * `Curl_addrinfo` list and it will be modified to point to the new head after + * shuffling. + * + * Not declared static only to make it easy to use in a unit test! + * + * @unittest 1608 + */ +UNITTEST CURLcode dns_shuffle_addr(struct Curl_easy *data, + struct Curl_addrinfo **addr); +UNITTEST CURLcode dns_shuffle_addr(struct Curl_easy *data, + struct Curl_addrinfo **addr) +{ + CURLcode result = CURLE_OK; + const int num_addrs = num_addresses(*addr); + + if(num_addrs > 1) { + struct Curl_addrinfo **nodes; + CURL_TRC_DNS(data, "Shuffling %d addresses", num_addrs); + + nodes = curlx_malloc(num_addrs * sizeof(*nodes)); + if(nodes) { + int i; + unsigned int *rnd; + const size_t rnd_size = num_addrs * sizeof(*rnd); + + /* build a plain array of Curl_addrinfo pointers */ + nodes[0] = *addr; + for(i = 1; i < num_addrs; i++) { + nodes[i] = nodes[i - 1]->ai_next; + } + + rnd = curlx_malloc(rnd_size); + if(rnd) { + /* Fisher-Yates shuffle */ + if(Curl_rand(data, (unsigned char *)rnd, rnd_size) == CURLE_OK) { + struct Curl_addrinfo *swap_tmp; + for(i = num_addrs - 1; i > 0; i--) { + swap_tmp = nodes[rnd[i] % (unsigned int)(i + 1)]; + nodes[rnd[i] % (unsigned int)(i + 1)] = nodes[i]; + nodes[i] = swap_tmp; + } + + /* relink list in the new order */ + for(i = 1; i < num_addrs; i++) { + nodes[i - 1]->ai_next = nodes[i]; + } + + nodes[num_addrs - 1]->ai_next = NULL; + *addr = nodes[0]; + } + curlx_free(rnd); + } + else + result = CURLE_OUT_OF_MEMORY; + curlx_free(nodes); + } + else + result = CURLE_OUT_OF_MEMORY; + } + return result; +} +#endif + +static bool dnscache_ai_has_family(struct Curl_addrinfo *ai, int ai_family) +{ + for(; ai; ai = ai->ai_next) { + if(ai->ai_family == ai_family) + return TRUE; + } + return FALSE; +} + +static struct Curl_dns_entry *dnsc_entry_create(struct Curl_easy *data, + struct dnsc_id *pid, + bool permanent) +{ + struct Curl_dns_entry *dns = NULL; + + /* Create a new cache entry, struct already has the hostname NUL */ + dns = curlx_calloc(1, sizeof(struct Curl_dns_entry) + + curlx_strlen(&pid->name)); + if(!dns) + goto out; + + dns->refcount = 1; /* the cache has the first reference */ + dns->hostlen = curlx_strlen(&pid->name); + dns->port = pid->port; + if(dns->hostlen) + memcpy(dns->hostname, curlx_str(&pid->name), dns->hostlen); + + if(permanent) { + dns->timestamp.tv_sec = 0; /* an entry that never goes stale */ + dns->timestamp.tv_usec = 0; /* an entry that never goes stale */ + } + else { + dns->timestamp = *Curl_pgrs_now(data); + } + +out: + return dns; +} + +static struct Curl_dns_entry *dnsc_entry_assign_addr( + struct Curl_easy *data, + struct Curl_dns_entry *dns, + uint8_t dns_queries, + struct Curl_addrinfo **paddr1, + struct Curl_addrinfo **paddr2) +{ + if(!dns) + goto out; + /* only do this when this is the only reference */ + DEBUGASSERT(dns->refcount == 1); + DEBUGASSERT(dns->type == CURL_DNST_INIT); + + dns->type = CURL_DNST_ADDR; + /* queries should only be about addresses */ + DEBUGASSERT(!(dns_queries & ~CURL_DNSQ_ADDR)); + dns->dns_queries = (dns_queries & CURL_DNSQ_ADDR); + + /* Take the given address lists into the entry */ + if(paddr1 && *paddr1) { + dns->addr = *paddr1; + *paddr1 = NULL; + } + if(paddr2 && *paddr2) { + struct Curl_addrinfo **phead = &dns->addr; + while(*phead) + phead = &(*phead)->ai_next; + *phead = *paddr2; + *paddr2 = NULL; + } + + if((dns_queries & CURL_DNSQ_A) && + dnscache_ai_has_family(dns->addr, PF_INET)) + dns->dns_responses |= CURL_DNSQ_A; + +#ifdef USE_IPV6 + if((dns_queries & CURL_DNSQ_AAAA) && + dnscache_ai_has_family(dns->addr, PF_INET6)) + dns->dns_responses |= CURL_DNSQ_AAAA; +#endif /* USE_IPV6 */ + +#ifndef CURL_DISABLE_SHUFFLE_DNS + /* shuffle addresses if requested */ + if(data->set.dns_shuffle_addresses && dns->addr) { + CURLcode result = dns_shuffle_addr(data, &dns->addr); + if(result) { + /* free without lock, we are the sole owner */ + dnscache_entry_free(dns); + dns = NULL; + goto out; + } + } +#else + (void)data; +#endif + +out: + if(paddr1 && *paddr1) { + Curl_freeaddrinfo(*paddr1); + *paddr1 = NULL; + } + if(paddr2 && *paddr2) { + Curl_freeaddrinfo(*paddr2); + *paddr2 = NULL; + } + return dns; +} + +struct Curl_dns_entry *Curl_dnsc_mk_addr(struct Curl_easy *data, + uint8_t dns_queries, + struct Curl_addrinfo **paddr, + struct Curl_peer *peer) +{ + struct dnsc_id id; + struct Curl_dns_entry *dns; + + dnsc_peer2id(&id, CURL_DNST_ADDR, peer); + dns = dnsc_entry_create(data, &id, FALSE); + dns = dnsc_entry_assign_addr(data, dns, dns_queries, paddr, NULL); + return dns; +} + +struct Curl_dns_entry *Curl_dnsc_mk_addr2(struct Curl_easy *data, + uint8_t dns_queries, + struct Curl_addrinfo **paddr1, + struct Curl_addrinfo **paddr2, + struct Curl_peer *peer) +{ + struct dnsc_id id; + struct Curl_dns_entry *dns; + + dnsc_peer2id(&id, CURL_DNST_ADDR, peer); + dns = dnsc_entry_create(data, &id, FALSE); + dns = dnsc_entry_assign_addr(data, dns, dns_queries, paddr1, paddr2); + return dns; +} + +#ifdef USE_HTTPSRR +static struct Curl_dns_entry *dnsc_entry_assign_https( + struct Curl_dns_entry *dns, + struct Curl_https_rrinfo **phinfo) +{ + if(!dns) + goto out; + /* only do this when this is the only reference */ + DEBUGASSERT(dns->refcount == 1); + DEBUGASSERT(dns->type == CURL_DNST_INIT); + + if(dns->hinfo) { + Curl_httpsrr_destroy(dns->hinfo); + dns->hinfo = NULL; + } + dns->type = CURL_DNST_HTTPS; + dns->dns_responses = dns->dns_queries = CURL_DNSQ_HTTPS; + if(phinfo) { + dns->hinfo = *phinfo; + *phinfo = NULL; + } +out: + if(phinfo && *phinfo) { + Curl_httpsrr_destroy(*phinfo); + *phinfo = NULL; + } + return dns; +} + +struct Curl_dns_entry *Curl_dnsc_mk_https(struct Curl_easy *data, + struct Curl_https_rrinfo **phinfo, + struct Curl_peer *peer) +{ + struct dnsc_id id; + struct Curl_dns_entry *dns; + + dnsc_peer2id(&id, CURL_DNST_HTTPS, peer); + dns = dnsc_entry_create(data, &id, FALSE); + dns = dnsc_entry_assign_https(dns, phinfo); + return dns; +} + +static struct Curl_dns_entry *dnsc_add_https(struct Curl_easy *data, + struct Curl_dnscache *dnscache, + struct Curl_https_rrinfo **phinfo, + struct dnsc_id *id, + bool permanent) +{ + struct Curl_dns_entry *dns, *dns2; + struct dnsc_key key; + + dns = dnsc_entry_create(data, id, permanent); + dns = dnsc_entry_assign_https(dns, phinfo); + if(!dns) + return NULL; + + /* Store the resolved data in our DNS cache. */ + dnsc_id2key(&key, id); + dns2 = Curl_hash_add(&dnscache->entries, key.data, key.len, (void *)dns); + if(!dns2) { + dnscache_entry_free(dns); + return NULL; + } + + dns = dns2; + dns->refcount++; /* mark entry as in-use */ + return dns; +} +#endif /* USE_HTTPSRR */ + +static struct Curl_dns_entry *dnsc_add_addr(struct Curl_easy *data, + struct Curl_dnscache *dnscache, + uint8_t dns_queries, + struct Curl_addrinfo **paddr, + struct dnsc_id *id, + struct dnsc_key *key, + bool permanent) +{ + struct Curl_dns_entry *dns; + struct Curl_dns_entry *dns2; + + dns = dnsc_entry_create(data, id, permanent); + dns = dnsc_entry_assign_addr(data, dns, dns_queries, paddr, NULL); + if(!dns) + return NULL; + + /* Store the resolved data in our DNS cache. */ + dns2 = Curl_hash_add(&dnscache->entries, key->data, key->len, (void *)dns); + if(!dns2) { + dnscache_entry_free(dns); + return NULL; + } + + dns = dns2; + dns->refcount++; /* mark entry as in-use */ + return dns; +} + +static struct Curl_dns_entry *dnsc_add_peer_addr( + struct Curl_easy *data, + struct Curl_dnscache *dnscache, + uint8_t dns_queries, + struct Curl_addrinfo **paddr, + struct dnsc_id *id, + bool permanent) +{ + struct Curl_dns_entry *dns; + struct Curl_dns_entry *dns2; + struct dnsc_key key; + + dns = dnsc_entry_create(data, id, permanent); + dns = dnsc_entry_assign_addr(data, dns, dns_queries, paddr, NULL); + if(!dns) + return NULL; + + /* Store the resolved data in our DNS cache. */ + dnsc_id2key(&key, id); + dns2 = Curl_hash_add(&dnscache->entries, key.data, key.len, (void *)dns); + if(!dns2) { + dnscache_entry_free(dns); + return NULL; + } + + dns = dns2; + dns->refcount++; /* mark entry as in-use */ + return dns; +} + +CURLcode Curl_dnscache_add(struct Curl_easy *data, + struct Curl_dns_entry *entry) +{ + struct Curl_dnscache *dnscache = dnscache_get(data); + struct Curl_str name; + struct dnsc_id id; + struct dnsc_key key; + + if(!dnscache) + return CURLE_FAILED_INIT; + if(!entry || (entry->type == CURL_DNST_INIT)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + curlx_str_assign(&name, entry->hostname, entry->hostlen); + dnsc_str2id(&id, entry->type, &name, entry->port); + dnsc_id2key(&key, &id); + + /* Store the resolved data in our DNS cache and up ref count */ + dnscache_lock(data, dnscache); + if(!Curl_hash_add(&dnscache->entries, key.data, key.len, (void *)entry)) { + dnscache_unlock(data, dnscache); + return CURLE_OUT_OF_MEMORY; + } + entry->refcount++; + dnscache_unlock(data, dnscache); + CURL_TRC_DNS(data, "cached entry for %s:%u queries=%s", + entry->hostname, entry->port, + Curl_resolv_query_str(entry->dns_queries)); + return CURLE_OK; +} + +CURLcode Curl_dnscache_add_negative(struct Curl_easy *data, + uint8_t dns_queries, + struct Curl_peer *peer) +{ + struct Curl_dnscache *dnscache = dnscache_get(data); + struct Curl_dns_entry *dns = NULL; + struct dnsc_id id; + CURLcode result = CURLE_OK; + + DEBUGASSERT(dnscache); + if(!dnscache) + return CURLE_FAILED_INIT; + + dnscache_lock(data, dnscache); + + if(dns_queries & CURL_DNSQ_ADDR) { + /* put this new host in the cache */ + dnsc_peer2id(&id, CURL_DNST_ADDR, peer); + dns = dnsc_add_peer_addr(data, dnscache, dns_queries, NULL, &id, FALSE); + if(!dns) + result = CURLE_OUT_OF_MEMORY; + } +#ifdef USE_HTTPSRR + else if(dns_queries == CURL_DNSQ_HTTPS) { + dnsc_peer2id(&id, CURL_DNST_HTTPS, peer); + dns = dnsc_add_https(data, dnscache, NULL, &id, FALSE); + if(!dns) + result = CURLE_OUT_OF_MEMORY; + } +#endif + else { + /* a query we do not know, just cache nothing */ + DEBUGASSERT(0); + } + + if(dns) { + /* release the returned reference; the cache itself will keep the + * entry alive: */ + dns->refcount--; + CURL_TRC_DNS(data, "cache negative name resolve for %s:%d type=%s", + peer->hostname, peer->port, + Curl_resolv_query_str(dns_queries)); + } + dnscache_unlock(data, dnscache); + return result; +} + +/* + * Curl_dns_entry_unlink() releases a reference to the given cached DNS entry. + * When the reference count reaches 0, the entry is destroyed. It is important + * that only one unlink is made for each Curl_resolv() call. + * + * May be called with 'data' == NULL for global cache. + */ +void Curl_dns_entry_unlink(struct Curl_easy *data, + struct Curl_dns_entry **pdns) +{ + if(*pdns) { + struct Curl_dnscache *dnscache = dnscache_get(data); + struct Curl_dns_entry *dns = *pdns; + *pdns = NULL; + dnscache_lock(data, dnscache); + dns->refcount--; + if(dns->refcount == 0) + dnscache_entry_free(dns); + dnscache_unlock(data, dnscache); + } +} + +static void dnscache_entry_dtor(void *entry) +{ + struct Curl_dns_entry *dns = (struct Curl_dns_entry *)entry; + DEBUGASSERT(dns && (dns->refcount > 0)); + dns->refcount--; + if(dns->refcount == 0) + dnscache_entry_free(dns); +} + +/* + * Curl_dnscache_init() inits a new DNS cache. + */ +void Curl_dnscache_init(struct Curl_dnscache *dns, size_t size) +{ + Curl_hash_init(&dns->entries, size, Curl_hash_str, curlx_str_key_compare, + dnscache_entry_dtor); +} + +void Curl_dnscache_destroy(struct Curl_dnscache *dns) +{ + Curl_hash_destroy(&dns->entries); +} + +CURLcode Curl_loadhostpairs(struct Curl_easy *data) +{ + struct Curl_dnscache *dnscache = dnscache_get(data); + struct curl_slist *hostp; + struct dnsc_id id; + struct dnsc_key key; + + if(!dnscache) + return CURLE_FAILED_INIT; + + /* Default is no wildcard found */ + data->state.wildcard_resolve = FALSE; + + for(hostp = data->state.resolve; hostp; hostp = hostp->next) { + const char *host = hostp->data; + struct Curl_str source; + if(!host) + continue; + if(*host == '-') { + curl_off_t num = 0; + host++; + if(!curlx_str_single(&host, '[')) { + if(curlx_str_until(&host, &source, MAX_IPADR_LEN, ']') || + curlx_str_single(&host, ']') || + curlx_str_single(&host, ':')) + continue; + } + else { + if(curlx_str_until(&host, &source, 4096, ':') || + curlx_str_single(&host, ':')) { + continue; + } + } + + if(!curlx_str_number(&host, &num, 0xffff)) { + /* Create an entry id, based upon the hostname and port */ + dnsc_str2id(&id, CURL_DNST_ADDR, &source, (uint16_t)num); + dnsc_id2key(&key, &id); + dnscache_lock(data, dnscache); + /* delete entry, ignore if it did not exist */ + Curl_hash_delete(&dnscache->entries, key.data, key.len); + dnscache_unlock(data, dnscache); + } + } + else { + struct Curl_dns_entry *dns; + struct Curl_addrinfo *head = NULL, *tail = NULL; + char address[64]; + curl_off_t tmpofft = 0; + uint16_t port = 0; + bool permanent = TRUE; + bool error = TRUE; + VERBOSE(const char *addresses = NULL); + + if(*host == '+') { + host++; + permanent = FALSE; + } + if(!curlx_str_single(&host, '[')) { + if(curlx_str_until(&host, &source, MAX_IPADR_LEN, ']') || + curlx_str_single(&host, ']')) + continue; + } + else { + if(curlx_str_until(&host, &source, 4096, ':')) + continue; + } + if(curlx_str_single(&host, ':') || + curlx_str_number(&host, &tmpofft, 0xffff) || + curlx_str_single(&host, ':')) + goto err; + port = (uint16_t)tmpofft; + + VERBOSE(addresses = host); + + /* start the address section */ + while(*host) { + struct Curl_str target; + struct Curl_addrinfo *ai; + CURLcode result; + + if(!curlx_str_single(&host, '[')) { + if(curlx_str_until(&host, &target, MAX_IPADR_LEN, ']') || + curlx_str_single(&host, ']')) + goto err; + } + else { + if(curlx_str_until(&host, &target, 4096, ',')) { + if(curlx_str_single(&host, ',')) + goto err; + /* survive nothing but a comma */ + continue; + } + } +#ifndef USE_IPV6 + if(memchr(curlx_str(&target), ':', curlx_strlen(&target))) { + infof(data, "Ignoring resolve address '%.*s', missing IPv6 support.", + (int)curlx_strlen(&target), curlx_str(&target)); + if(curlx_str_single(&host, ',')) + goto err; + continue; + } +#endif + + if(curlx_strlen(&target) >= sizeof(address)) + goto err; + + memcpy(address, curlx_str(&target), curlx_strlen(&target)); + address[curlx_strlen(&target)] = '\0'; + + result = Curl_str2addr(address, port, &ai); + if(result) { + infof(data, "Resolve IP address '%s' found is illegal", address); + goto err; + } + + if(tail) { + tail->ai_next = ai; + tail = tail->ai_next; + } + else { + head = tail = ai; + } + if(curlx_str_single(&host, ',')) + break; + } + + if(!head) + goto err; + + error = FALSE; +err: + if(error) { + failf(data, "Could not parse CURLOPT_RESOLVE entry '%s'", hostp->data); + Curl_freeaddrinfo(head); + return CURLE_SETOPT_OPTION_SYNTAX; + } + + dnsc_str2id(&id, CURL_DNST_ADDR, &source, port); + dnsc_id2key(&key, &id); + dnscache_lock(data, dnscache); + + /* See if it is already in our dns cache */ + dns = Curl_hash_pick(&dnscache->entries, key.data, key.len); + + if(dns) { + infof(data, "RESOLVE %.*s:%u - old addresses discarded", + (int)curlx_strlen(&source), curlx_str(&source), port); + /* delete old entry, there are two reasons for this + 1. old entry may have different addresses. + 2. even if entry with correct addresses is already in the cache, + but if it is close to expire, then by the time next http + request is made, it can get expired and pruned because old + entry is not necessarily marked as permanent. + 3. when adding a non-permanent entry, we want it to remove and + replace an existing permanent entry. + 4. when adding a non-permanent entry, we want it to get a "fresh" + timeout that starts _now_. */ + + Curl_hash_delete(&dnscache->entries, key.data, key.len); + } + + /* put this new host in the cache, override all address queries */ + dns = dnsc_add_addr(data, dnscache, CURL_DNSQ_ADDR, &head, + &id, &key, permanent); + if(dns) + /* release the returned reference; the cache itself will keep the + * entry alive: */ + dns->refcount--; + + dnscache_unlock(data, dnscache); + + if(!dns) + return CURLE_OUT_OF_MEMORY; + + infof(data, "[DNS] added %.*s:%u:%s to cache%s", + (int)curlx_strlen(&id.name), curlx_str(&id.name), id.port, + addresses, permanent ? "" : " (non-permanent)"); + + /* Wildcard hostname */ + if(curlx_str_casecompare(&source, "*")) { + infof(data, "RESOLVE *:%u using wildcard", port); + data->state.wildcard_resolve = TRUE; + } + } + } + data->state.resolve = NULL; /* dealt with now */ + + return CURLE_OK; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/dnscache.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/dnscache.h new file mode 100644 index 0000000000..73dcff60d7 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/dnscache.h @@ -0,0 +1,142 @@ +#ifndef HEADER_CURL_DNSCACHE_H +#define HEADER_CURL_DNSCACHE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "hash.h" +#include "curlx/timeval.h" + +struct addrinfo; +struct hostent; +struct Curl_easy; +struct connectdata; +struct easy_pollset; +struct Curl_https_rrinfo; +struct Curl_multi; +struct Curl_peer; + +#define CURL_DNST_INIT '\0' +#define CURL_DNST_ADDR 'A' +#define CURL_DNST_HTTPS 'H' + +struct Curl_dns_entry { + struct Curl_addrinfo *addr; +#ifdef USE_HTTPSRR + struct Curl_https_rrinfo *hinfo; +#endif + /* timestamp == 0 -- permanent CURLOPT_RESOLVE entry (does not time out) */ + struct curltime timestamp; + size_t hostlen; + /* reference counter, entry is freed on reaching 0 */ + uint32_t refcount; + /* hostname port number that resolved to addr. */ + uint16_t port; + char type; /* CURL_DNST_ADDR or CURL_DNST_HTTPS */ + uint8_t dns_queries; /* CURL_DNSQ_* type of queries performed for this */ + uint8_t dns_responses; /* CURL_DNSQ_* type this entry has responses for */ + /* hostname that resolved to addr. may be NULL (Unix domain sockets). */ + char hostname[1]; +}; + +/* + * Create a `Curl_dns_entry` with a reference count of 1. + * Use `Curl_dns_entry_unlink()` to release your hold on it. + * + * The call takes ownership of `paddr`, even in case of failure, and always + * clears `*paddr`. It makes a copy of `hostname`. + * + * Returns entry or NULL on OOM. + */ +struct Curl_dns_entry *Curl_dnsc_mk_addr(struct Curl_easy *data, + uint8_t dns_queries, + struct Curl_addrinfo **paddr, + struct Curl_peer *peer); + +struct Curl_dns_entry *Curl_dnsc_mk_addr2(struct Curl_easy *data, + uint8_t dns_queries, + struct Curl_addrinfo **paddr1, + struct Curl_addrinfo **paddr2, + struct Curl_peer *peer); + +#ifdef USE_HTTPSRR +struct Curl_dns_entry *Curl_dnsc_mk_https(struct Curl_easy *data, + struct Curl_https_rrinfo **phinfo, + struct Curl_peer *peer); +#endif /* USE_HTTPSRR */ + +/* unlink a dns entry, frees all resources if it was the last reference. + * Always clears `*pdns`` */ +void Curl_dns_entry_unlink(struct Curl_easy *data, + struct Curl_dns_entry **pdns); + +struct Curl_dnscache { + struct Curl_hash entries; +}; + +/* init a new dns cache */ +void Curl_dnscache_init(struct Curl_dnscache *dns, size_t size); + +void Curl_dnscache_destroy(struct Curl_dnscache *dns); + +/* prune old entries from the DNS cache */ +void Curl_dnscache_prune(struct Curl_easy *data); + +/* clear the DNS cache */ +void Curl_dnscache_clear(struct Curl_easy *data); + +/* + * Curl_dnscache_get() fetches a 'Curl_dns_entry' already in the DNS cache. + * + * Returns the Curl_dns_entry entry pointer or NULL if not in the cache. + * + * The returned data *MUST* be "released" with Curl_dns_entry_unlink() after + * use, or we will leak memory! + * Returns CURLE_OK or CURLE_COULDNT_RESOLVE_HOST when a negative + * entry was in the cache. + */ +CURLcode Curl_dnscache_get(struct Curl_easy *data, + uint8_t dns_queries, + struct Curl_peer *peer, + struct Curl_dns_entry **pentry); + +/* + * Curl_dnscache_addr() adds `entry` to the cache, increasing its + * reference count on success. + */ +CURLcode Curl_dnscache_add(struct Curl_easy *data, + struct Curl_dns_entry *entry); + +/* Store a "negative" entry for host:port, e.g. remember that + * it could not be resolved. */ +CURLcode Curl_dnscache_add_negative(struct Curl_easy *data, + uint8_t dns_queries, + struct Curl_peer *peer); + +/* + * Populate the cache with specified entries from CURLOPT_RESOLVE. + */ +CURLcode Curl_loadhostpairs(struct Curl_easy *data); + +#endif /* HEADER_CURL_DNSCACHE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/doh.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/doh.c new file mode 100644 index 0000000000..3b52ed92f3 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/doh.c @@ -0,0 +1,1265 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_DOH + +#include "urldata.h" +#include "curl_addrinfo.h" +#include "curl_trc.h" +#include "multiif.h" +#include "url.h" +#include "connect.h" +#include "vdns/doh.h" +#include "vdns/httpsrr.h" +#include "curlx/strdup.h" +#include "curlx/dynbuf.h" +#include "escape.h" /* for Curl_hexencode() */ +#include "urlapi-int.h" + +#define DNS_CLASS_IN 0x01 + +static void doh_close(struct Curl_easy *data, + struct Curl_resolv_async *async); + +#ifdef CURLVERBOSE +static const char * const doh_code_str[] = { + "", + "Bad label", + "Out of range", + "Label loop", + "Too small", + "Out of memory", + "RDATA length", + "Malformat", + "Bad RCODE", + "Unexpected TYPE", + "Unexpected CLASS", + "No content", + "Bad ID", + "Name too long", + "No such name", + "Transport failed", + "Out Of Memory" +}; + +static const char *doh_strerror(DOHcode code) +{ + if((size_t)code < CURL_ARRAYSIZE(doh_code_str)) + return doh_code_str[code]; + return "bad error code"; +} + +static const char *doh_type2name(DNStype dnstype) +{ + switch(dnstype) { + case CURL_DNS_TYPE_A: + return "A"; + case CURL_DNS_TYPE_AAAA: + return "AAAA"; +#ifdef USE_HTTPSRR + case CURL_DNS_TYPE_HTTPS: + return "HTTPS"; +#endif + default: + return "unknown"; + } +} + +#endif /* CURLVERBOSE */ + +/* @unittest 1655 + */ +UNITTEST DOHcode doh_req_encode(const char *host, + DNStype dnstype, + unsigned char *dnsp, /* buffer */ + size_t len, /* buffer size */ + size_t *olen); /* output length */ +UNITTEST DOHcode doh_req_encode(const char *host, + DNStype dnstype, + unsigned char *dnsp, /* buffer */ + size_t len, /* buffer size */ + size_t *olen) /* output length */ +{ + const size_t hostlen = strlen(host); + unsigned char *orig = dnsp; + const char *hostp = host; + + /* The expected output length is 16 bytes more than the length of + * the QNAME-encoding of the hostname. + * + * A valid DNS name may not contain a zero-length label, except at + * the end. For this reason, a name beginning with a dot, or + * containing a sequence of two or more consecutive dots, is invalid + * and cannot be encoded as a QNAME. + * + * If the hostname ends with a trailing dot, the corresponding + * QNAME-encoding is one byte longer than the hostname. If (as is + * also valid) the hostname is shortened by the omission of the + * trailing dot, then its QNAME-encoding will be two bytes longer + * than the hostname. + * + * Each [ label, dot ] pair is encoded as [ length, label ], + * preserving overall length. A final [ label ] without a dot is + * also encoded as [ length, label ], increasing overall length + * by one. The encoding is completed by appending a zero byte, + * representing the zero-length root label, again increasing + * the overall length by one. + */ + + size_t expected_len; + DEBUGASSERT(hostlen); + expected_len = 12 + 1 + hostlen + 4; + if(host[hostlen - 1] != '.') + expected_len++; + + if(expected_len > DOH_MAX_DNSREQ_SIZE) + return DOH_DNS_NAME_TOO_LONG; + + if(len < expected_len) + return DOH_TOO_SMALL_BUFFER; + + *dnsp++ = 0; /* 16-bit id */ + *dnsp++ = 0; + *dnsp++ = 0x01; /* |QR| Opcode |AA|TC|RD| Set the RD bit */ + *dnsp++ = '\0'; /* |RA| Z | RCODE | */ + *dnsp++ = '\0'; + *dnsp++ = 1; /* QDCOUNT (number of entries in the question section) */ + *dnsp++ = '\0'; + *dnsp++ = '\0'; /* ANCOUNT */ + *dnsp++ = '\0'; + *dnsp++ = '\0'; /* NSCOUNT */ + *dnsp++ = '\0'; + *dnsp++ = '\0'; /* ARCOUNT */ + + /* encode each label and store it in the QNAME */ + while(*hostp) { + size_t labellen; + const char *dot = strchr(hostp, '.'); + if(dot) + labellen = dot - hostp; + else + labellen = strlen(hostp); + if((labellen > 63) || (!labellen)) { + /* label is too long or too short, error out */ + *olen = 0; + return DOH_DNS_BAD_LABEL; + } + /* label is non-empty, process it */ + *dnsp++ = (unsigned char)labellen; + memcpy(dnsp, hostp, labellen); + dnsp += labellen; + hostp += labellen; + /* advance past dot, but only if there is one */ + if(dot) + hostp++; + } /* next label */ + + *dnsp++ = 0; /* append zero-length label for root */ + + /* There are assigned TYPE codes beyond 255: use range [1..65535] */ + *dnsp++ = (unsigned char)(255 & (dnstype >> 8)); /* upper 8-bit TYPE */ + *dnsp++ = (unsigned char)(255 & dnstype); /* lower 8-bit TYPE */ + + *dnsp++ = '\0'; /* upper 8-bit CLASS */ + *dnsp++ = DNS_CLASS_IN; /* IN - "the Internet" */ + + *olen = dnsp - orig; + + /* verify that our estimation of length is valid, since + * this has led to buffer overflows in this function */ + DEBUGASSERT(*olen == expected_len); + return DOH_OK; +} + +static size_t doh_probe_write_cb(char *contents, size_t size, size_t nmemb, + void *userp) +{ + size_t realsize = size * nmemb; + struct Curl_easy *data = userp; + struct doh_request *doh_req = Curl_meta_get(data, CURL_EZM_DOH_PROBE); + if(!doh_req) + return CURL_WRITEFUNC_ERROR; + + if(curlx_dyn_addn(&doh_req->resp_body, contents, realsize)) + return 0; + + return realsize; +} + +static void doh_probe_done(struct Curl_easy *doh, + struct Curl_easy *master, CURLcode result); +static void doh_probe_dtor(void *key, size_t klen, void *e) +{ + (void)key; + (void)klen; + if(e) { + struct doh_request *doh_req = e; + curl_slist_free_all(doh_req->req_hds); + curlx_dyn_free(&doh_req->resp_body); + curlx_free(e); + } +} + +#define ERROR_CHECK_SETOPT(x, y) \ + do { \ + result = curl_easy_setopt((CURL *)doh, x, y); \ + if(result && \ + result != CURLE_NOT_BUILT_IN && \ + result != CURLE_UNKNOWN_OPTION) \ + goto error; \ + } while(0) + +static CURLcode doh_probe_run(struct Curl_easy *data, + DNStype dnstype, + const char *host, + const char *url, CURLM *multi, + uint32_t resolv_id, + uint32_t *pmid) +{ + struct Curl_easy *doh = NULL; + CURLcode result = CURLE_OK; + timediff_t timeout_ms; + struct doh_request *doh_req; + DOHcode d; + bool maybe_https = !curl_strnequal(url, STRCONST("http:")); + + *pmid = UINT32_MAX; + + doh_req = curlx_calloc(1, sizeof(*doh_req)); + if(!doh_req) + return CURLE_OUT_OF_MEMORY; + doh_req->resolv_id = resolv_id; + doh_req->dnstype = dnstype; + curlx_dyn_init(&doh_req->resp_body, DYN_DOH_RESPONSE); + + d = doh_req_encode(host, dnstype, doh_req->req_body, + sizeof(doh_req->req_body), + &doh_req->req_body_len); + if(d) { + failf(data, "Failed to encode DoH packet [%d]", (int)d); + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + timeout_ms = Curl_timeleft_ms(data); + if(timeout_ms < 0) { + result = CURLE_OPERATION_TIMEDOUT; + goto error; + } + + doh_req->req_hds = + curl_slist_append(NULL, "Content-Type: application/dns-message"); + if(!doh_req->req_hds) { + result = CURLE_OUT_OF_MEMORY; + goto error; + } + + /* Curl_open() is the internal version of curl_easy_init() */ + result = Curl_open(&doh); + if(result) + goto error; + + /* pass in the struct pointer via a local variable to please coverity and + the gcc typecheck helpers */ + VERBOSE(doh->state.feat = &Curl_trc_feat_doh); + ERROR_CHECK_SETOPT(CURLOPT_URL, url); + ERROR_CHECK_SETOPT(CURLOPT_DEFAULT_PROTOCOL, "https"); + ERROR_CHECK_SETOPT(CURLOPT_WRITEFUNCTION, doh_probe_write_cb); + ERROR_CHECK_SETOPT(CURLOPT_WRITEDATA, doh); + ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDS, doh_req->req_body); + ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDSIZE, (long)doh_req->req_body_len); + ERROR_CHECK_SETOPT(CURLOPT_HTTPHEADER, doh_req->req_hds); +#ifdef USE_HTTP2 + if(maybe_https) { + ERROR_CHECK_SETOPT(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS); + ERROR_CHECK_SETOPT(CURLOPT_PIPEWAIT, 1L); + } +#endif +#ifndef DEBUGBUILD + /* enforce HTTPS if not debug */ + ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTPS); +#else + /* in debug mode, also allow http */ + ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); +#endif + ERROR_CHECK_SETOPT(CURLOPT_TIMEOUT_MS, (long)timeout_ms); + ERROR_CHECK_SETOPT(CURLOPT_SHARE, (CURLSH *)data->share); + if(data->set.err && data->set.err != stderr) + ERROR_CHECK_SETOPT(CURLOPT_STDERR, data->set.err); + if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_doh)) + ERROR_CHECK_SETOPT(CURLOPT_VERBOSE, 1L); + if(data->set.no_signal) + ERROR_CHECK_SETOPT(CURLOPT_NOSIGNAL, 1L); + if(data->set.fdebug) + ERROR_CHECK_SETOPT(CURLOPT_DEBUGFUNCTION, data->set.fdebug); + if(data->set.debugdata) + ERROR_CHECK_SETOPT(CURLOPT_DEBUGDATA, data->set.debugdata); + + if(maybe_https) { + ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYHOST, + data->set.doh_verifyhost ? 2L : 0L); + ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYPEER, + data->set.doh_verifypeer ? 1L : 0L); + ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYSTATUS, + data->set.doh_verifystatus ? 1L : 0L); + + /* Inherit *some* SSL options from the user's transfer. This is a + best-guess as to which options are needed for compatibility. #3661 + + Note DoH does not inherit the user's proxy server so proxy SSL settings + have no effect and are not inherited. If that changes then two new + options should be added to check doh proxy insecure separately, + CURLOPT_DOH_PROXY_SSL_VERIFYHOST and CURLOPT_DOH_PROXY_SSL_VERIFYPEER. + */ + doh->set.ssl.custom_cafile = data->set.ssl.custom_cafile; + doh->set.ssl.custom_capath = data->set.ssl.custom_capath; + doh->set.ssl.custom_cablob = data->set.ssl.custom_cablob; + if(CURL_EASY_STR(data, STRING_SSL_CAFILE)) { + ERROR_CHECK_SETOPT(CURLOPT_CAINFO, + CURL_EASY_STR(data, STRING_SSL_CAFILE)); + } + if(data->set.blobs[BLOB_CAINFO]) { + ERROR_CHECK_SETOPT(CURLOPT_CAINFO_BLOB, data->set.blobs[BLOB_CAINFO]); + } + if(CURL_EASY_STR(data, STRING_SSL_CAPATH)) { + ERROR_CHECK_SETOPT(CURLOPT_CAPATH, + CURL_EASY_STR(data, STRING_SSL_CAPATH)); + } + if(CURL_EASY_STR(data, STRING_SSL_CRLFILE)) { + ERROR_CHECK_SETOPT(CURLOPT_CRLFILE, + CURL_EASY_STR(data, STRING_SSL_CRLFILE)); + } + if(data->set.ssl.certinfo) + ERROR_CHECK_SETOPT(CURLOPT_CERTINFO, 1L); + if(data->set.ssl.fsslctx) + ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_FUNCTION, data->set.ssl.fsslctx); + if(data->set.ssl.fsslctxp) + ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_DATA, data->set.ssl.fsslctxp); + if(CURL_EASY_STR(data, STRING_SSL_EC_CURVES)) { + ERROR_CHECK_SETOPT(CURLOPT_SSL_EC_CURVES, + CURL_EASY_STR(data, STRING_SSL_EC_CURVES)); + } + + (void)curl_easy_setopt(doh, CURLOPT_SSL_OPTIONS, + ((long)data->set.ssl.primary.ssl_options & + ~CURLSSLOPT_AUTO_CLIENT_CERT)); + } + + doh->state.internal = TRUE; + doh->master_mid = data->mid; /* master transfer of this one */ + doh->sub_xfer_done = doh_probe_done; + + result = Curl_meta_set(doh, CURL_EZM_DOH_PROBE, doh_req, doh_probe_dtor); + doh_req = NULL; /* call took ownership */ + if(result) + goto error; + + /* DoH handles must not inherit private_data. The handles may be passed to + the user via callbacks and the user will be able to identify them as + internal handles because private data is not set. The user can then set + private_data via CURLOPT_PRIVATE if they so choose. */ + DEBUGASSERT(!doh->set.private_data); + + if(Curl_multi_add_handle(multi, doh)) + goto error; + + *pmid = doh->mid; + return CURLE_OK; + +error: + Curl_close(&doh); + if(doh_req) + doh_probe_dtor(NULL, 0, doh_req); + return result; +} + +/* + * Curl_doh() starts a name resolve using DoH. It resolves a name and returns + * a 'Curl_addrinfo *' with the address information. + */ + +CURLcode Curl_doh(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + CURLcode result = CURLE_OK; + struct doh_probes *dohp = NULL; + size_t i; + + DEBUGASSERT(!async->doh); + DEBUGASSERT(async->peer->hostname[0]); + if(async->doh) { + DEBUGASSERT(0); /* should not happen */ + Curl_doh_cleanup(data, async); + } + + if(!async->dns_queries) + return CURLE_BAD_FUNCTION_ARGUMENT; +#ifdef USE_HTTPSRR + if(CURL_DNSQ_IS_ADDR(async->dns_queries) && + (async->dns_queries & CURL_DNSQ_HTTPS)) { + /* Can't mix those in the same async resolve */ + DEBUGASSERT(0); + return CURLE_BAD_FUNCTION_ARGUMENT; + } +#else + if(async->dns_queries & CURL_DNSQ_HTTPS) { + DEBUGASSERT(0); + return CURLE_NOT_BUILT_IN; + } +#endif + + /* start clean, consider allocating this struct on demand */ + async->doh = dohp = curlx_calloc(1, sizeof(struct doh_probes)); + if(!dohp) + return CURLE_OUT_OF_MEMORY; + + for(i = 0; i < DOH_SLOT_COUNT; ++i) { + dohp->probe_rc[i] = DOH_OK; + dohp->probe_mid[i] = UINT32_MAX; + } + +#ifdef USE_IPV6 + /* AAAA results have preference in happy eyeballing, trigger first */ + if(async->dns_queries & CURL_DNSQ_AAAA) { + /* create IPv6 DoH request */ + result = doh_probe_run(data, CURL_DNS_TYPE_AAAA, + async->peer->hostname, + CURL_EASY_STR(data, STRING_DOH), + data->multi, async->id, + &dohp->probe_mid[DOH_SLOT_IPV6]); + if(result) + goto error; + async->queries_ongoing++; + } +#endif + + /* create IPv4 DoH request */ + if(async->dns_queries & CURL_DNSQ_A) { + result = doh_probe_run(data, CURL_DNS_TYPE_A, + async->peer->hostname, + CURL_EASY_STR(data, STRING_DOH), + data->multi, async->id, + &dohp->probe_mid[DOH_SLOT_IPV4]); + if(result) + goto error; + async->queries_ongoing++; + } + +#ifdef USE_HTTPSRR + if(async->dns_queries & CURL_DNSQ_HTTPS) { + char *qname = NULL; + if(async->peer->port != PORT_HTTPS) { + qname = curl_maprintf("_%u._https.%s", + async->peer->port, async->peer->hostname); + if(!qname) + goto error; + } + result = doh_probe_run(data, CURL_DNS_TYPE_HTTPS, + qname ? qname : async->peer->hostname, + CURL_EASY_STR(data, STRING_DOH), data->multi, + async->id, + &dohp->probe_mid[DOH_SLOT_HTTPS_RR]); + curlx_free(qname); + if(result) + goto error; + async->queries_ongoing++; + } +#endif + return CURLE_OK; + +error: + Curl_doh_cleanup(data, async); + return result; +} + +static DOHcode doh_skipqname(const unsigned char *doh, size_t dohlen, + unsigned int *indexp) +{ + unsigned char length; + do { + if(dohlen < (*indexp + 1)) + return DOH_DNS_OUT_OF_RANGE; + length = doh[*indexp]; + if((length & 0xc0) == 0xc0) { + /* name pointer, advance over it and be done */ + if(dohlen < (*indexp + 2)) + return DOH_DNS_OUT_OF_RANGE; + *indexp += 2; + break; + } + if(length & 0xc0) + return DOH_DNS_BAD_LABEL; + if(dohlen < (*indexp + 1 + length)) + return DOH_DNS_OUT_OF_RANGE; + *indexp += (unsigned int)(1 + length); + } while(length); + return DOH_OK; +} + +static unsigned short doh_get16bit(const unsigned char *doh, + unsigned int index) +{ + return (unsigned short)((doh[index] << 8) | doh[index + 1]); +} + +static unsigned int doh_get32bit(const unsigned char *doh, unsigned int index) +{ + /* make clang and gcc optimize this to bswap by incrementing + the pointer first. */ + doh += index; + + /* avoid undefined behavior by casting to unsigned before shifting + 24 bits, possibly into the sign bit. codegen is same, but + ub sanitizer will not be upset */ + return ((unsigned)doh[0] << 24) | ((unsigned)doh[1] << 16) | + ((unsigned)doh[2] << 8) | doh[3]; +} + +static void doh_store_a(const unsigned char *doh, int index, + struct dohentry *d) +{ + /* silently ignore addresses over the limit */ + if(d->numaddr < DOH_MAX_ADDR) { + struct dohaddr *a = &d->addr[d->numaddr]; + a->type = CURL_DNS_TYPE_A; + memcpy(&a->ip.v4, &doh[index], 4); + d->numaddr++; + } +} + +static void doh_store_aaaa(const unsigned char *doh, int index, + struct dohentry *d) +{ + /* silently ignore addresses over the limit */ + if(d->numaddr < DOH_MAX_ADDR) { + struct dohaddr *a = &d->addr[d->numaddr]; + a->type = CURL_DNS_TYPE_AAAA; + memcpy(&a->ip.v6, &doh[index], 16); + d->numaddr++; + } +} + +#ifdef USE_HTTPSRR +static DOHcode doh_store_https(const unsigned char *doh, int index, + struct dohentry *d, uint16_t len) +{ + /* silently ignore RRs over the limit */ + if(d->numhttps_rrs < DOH_MAX_HTTPS) { + struct dohhttps_rr *h = &d->https_rrs[d->numhttps_rrs]; + h->val = curlx_memdup(&doh[index], len); + if(!h->val) + return DOH_OUT_OF_MEM; + h->len = len; + d->numhttps_rrs++; + } + return DOH_OK; +} +#endif + +static DOHcode doh_rdata(const unsigned char *doh, + unsigned short rdlength, + unsigned short type, + int index, + struct dohentry *d) +{ + /* RDATA + - A (TYPE 1): 4 bytes + - AAAA (TYPE 28): 16 bytes + - HTTPS (TYPE 65): N bytes */ + switch(type) { + case CURL_DNS_TYPE_A: + if(rdlength != 4) + return DOH_DNS_RDATA_LEN; + doh_store_a(doh, index, d); + break; + case CURL_DNS_TYPE_AAAA: + if(rdlength != 16) + return DOH_DNS_RDATA_LEN; + doh_store_aaaa(doh, index, d); + break; +#ifdef USE_HTTPSRR + case CURL_DNS_TYPE_HTTPS: { + DOHcode rc = doh_store_https(doh, index, d, rdlength); + if(rc) + return rc; + break; + } +#endif + default: + /* unsupported type, or type we do not store, skip it */ + break; + } + return DOH_OK; +} + +/* @unittest 1655 */ +UNITTEST void de_init(struct dohentry *de); +UNITTEST void de_init(struct dohentry *de) +{ + memset(de, 0, sizeof(*de)); + de->ttl = INT_MAX; +} + +/* TTL value cap */ +#define MAX_DNS_TTL 86400U /* 24 hours */ +/* @unittest 1650 */ +UNITTEST DOHcode doh_resp_decode(const unsigned char *doh, + size_t dohlen, + DNStype dnstype, + struct dohentry *d); +UNITTEST DOHcode doh_resp_decode(const unsigned char *doh, + size_t dohlen, + DNStype dnstype, + struct dohentry *d) +{ + unsigned char rcode; + unsigned short qdcount; + unsigned short ancount; + unsigned short type = 0; + unsigned short rdlength; + unsigned short nscount; + unsigned short arcount; + unsigned int index = 12; + DOHcode rc; + + if(dohlen < 12) + return DOH_TOO_SMALL_BUFFER; /* too small */ + if(!doh || doh[0] || doh[1]) + return DOH_DNS_BAD_ID; /* bad ID */ + rcode = doh[3] & 0x0f; + if(rcode == 3) + return DOH_DNS_NXDOMAIN; /* name does not exist */ + if(rcode) + return DOH_DNS_BAD_RCODE; /* bad rcode */ + + qdcount = doh_get16bit(doh, 4); + while(qdcount) { + rc = doh_skipqname(doh, dohlen, &index); + if(rc) + return rc; /* bad qname */ + if(dohlen < (index + 4)) + return DOH_DNS_OUT_OF_RANGE; + index += 4; /* skip question's type and class */ + qdcount--; + } + + ancount = doh_get16bit(doh, 6); + while(ancount) { + unsigned short dnsclass; + unsigned int ttl; + + rc = doh_skipqname(doh, dohlen, &index); + if(rc) + return rc; /* bad qname */ + + if(dohlen < (index + 2)) + return DOH_DNS_OUT_OF_RANGE; + + type = doh_get16bit(doh, index); + if((type != CURL_DNS_TYPE_CNAME) && /* may be synthesized from DNAME */ + (type != CURL_DNS_TYPE_DNAME) && /* if present, accept and ignore */ + (type != dnstype)) + /* Not the same type as was asked for, nor CNAME nor DNAME */ + return DOH_DNS_UNEXPECTED_TYPE; + index += 2; + + if(dohlen < (index + 2)) + return DOH_DNS_OUT_OF_RANGE; + dnsclass = doh_get16bit(doh, index); + if(DNS_CLASS_IN != dnsclass) + return DOH_DNS_UNEXPECTED_CLASS; /* unsupported */ + index += 2; + + if(dohlen < (index + 4)) + return DOH_DNS_OUT_OF_RANGE; + + ttl = doh_get32bit(doh, index); + if(ttl > MAX_DNS_TTL) + ttl = MAX_DNS_TTL; + if(ttl < d->ttl) + d->ttl = ttl; + index += 4; + + if(dohlen < (index + 2)) + return DOH_DNS_OUT_OF_RANGE; + + rdlength = doh_get16bit(doh, index); + index += 2; + if(dohlen < (index + rdlength)) + return DOH_DNS_OUT_OF_RANGE; + + rc = doh_rdata(doh, rdlength, type, (int)index, d); + if(rc) + return rc; + index += rdlength; + ancount--; + } + + nscount = doh_get16bit(doh, 8); + while(nscount) { + rc = doh_skipqname(doh, dohlen, &index); + if(rc) + return rc; /* bad qname */ + + if(dohlen < (index + 8)) + return DOH_DNS_OUT_OF_RANGE; + + index += 2 + 2 + 4; /* type, dnsclass and ttl */ + + if(dohlen < (index + 2)) + return DOH_DNS_OUT_OF_RANGE; + + rdlength = doh_get16bit(doh, index); + index += 2; + if(dohlen < (index + rdlength)) + return DOH_DNS_OUT_OF_RANGE; + index += rdlength; + nscount--; + } + + arcount = doh_get16bit(doh, 10); + while(arcount) { + rc = doh_skipqname(doh, dohlen, &index); + if(rc) + return rc; /* bad qname */ + + if(dohlen < (index + 8)) + return DOH_DNS_OUT_OF_RANGE; + + index += 2 + 2 + 4; /* type, dnsclass and ttl */ + + if(dohlen < (index + 2)) + return DOH_DNS_OUT_OF_RANGE; + + rdlength = doh_get16bit(doh, index); + index += 2; + if(dohlen < (index + rdlength)) + return DOH_DNS_OUT_OF_RANGE; + index += rdlength; + arcount--; + } + + if(index != dohlen) + return DOH_DNS_MALFORMAT; /* something is wrong */ + + return DOH_OK; /* ok */ +} + +/* + * This function returns a pointer to the first element of a newly allocated + * Curl_addrinfo struct linked list filled with the data from a set of DoH + * lookups. Curl_addrinfo is meant to work like the addrinfo struct does for + * an IPv6 stack, but usable also for IPv4, all hosts and environments. + * + * The memory allocated by this function *MUST* be free'd later on calling + * Curl_freeaddrinfo(). For each successful call to this function there + * must be an associated call later to Curl_freeaddrinfo(). + */ +static CURLcode doh2ai(const struct dohentry *de, const char *hostname, + int port, struct Curl_addrinfo **aip) +{ + struct Curl_addrinfo *ai; + struct Curl_addrinfo *prevai = NULL; + struct Curl_addrinfo *firstai = NULL; + struct sockaddr_in *addr; +#ifdef USE_IPV6 + struct sockaddr_in6 *addr6; +#endif + size_t hostlen = strlen(hostname) + 1; /* include null-terminator */ + CURLcode result = CURLE_OK; + int i; + + for(i = 0; i < de->numaddr; i++) { + size_t ss_size; + CURL_SA_FAMILY_T addrtype; + if(de->addr[i].type == CURL_DNS_TYPE_AAAA) { +#ifndef USE_IPV6 + /* we cannot handle IPv6 addresses */ + continue; +#else + ss_size = sizeof(struct sockaddr_in6); + addrtype = AF_INET6; +#endif + } + else { + ss_size = sizeof(struct sockaddr_in); + addrtype = AF_INET; + } + + ai = curlx_calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen); + if(!ai) { + result = CURLE_OUT_OF_MEMORY; + break; + } + ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo)); + ai->ai_canonname = (void *)((char *)ai->ai_addr + ss_size); + memcpy(ai->ai_canonname, hostname, hostlen); + + if(!firstai) + /* store the pointer we want to return from this function */ + firstai = ai; + + if(prevai) + /* make the previous entry point to this */ + prevai->ai_next = ai; + + ai->ai_family = addrtype; + + /* we return all names as STREAM, so when using this address for TFTP + the type must be ignored and conn->socktype be used instead! */ + ai->ai_socktype = SOCK_STREAM; + + ai->ai_addrlen = (curl_socklen_t)ss_size; + + /* leave the rest of the struct filled with zero */ + + switch(ai->ai_family) { + case AF_INET: + addr = (void *)ai->ai_addr; /* storage area for this info */ + DEBUGASSERT(sizeof(struct in_addr) == sizeof(de->addr[i].ip.v4)); + memcpy(&addr->sin_addr, &de->addr[i].ip.v4, sizeof(struct in_addr)); + addr->sin_family = addrtype; + addr->sin_port = htons((unsigned short)port); + break; + +#ifdef USE_IPV6 + case AF_INET6: + addr6 = (void *)ai->ai_addr; /* storage area for this info */ + DEBUGASSERT(sizeof(struct in6_addr) == sizeof(de->addr[i].ip.v6)); + memcpy(&addr6->sin6_addr, &de->addr[i].ip.v6, sizeof(struct in6_addr)); + addr6->sin6_family = addrtype; + addr6->sin6_port = htons((unsigned short)port); + break; +#endif + } + + prevai = ai; + } + + if(result) { + Curl_freeaddrinfo(firstai); + firstai = NULL; + } + *aip = firstai; + + return result; +} + +/* @unittest 1655 */ +UNITTEST void de_cleanup(struct dohentry *d); +UNITTEST void de_cleanup(struct dohentry *d) +{ +#ifdef USE_HTTPSRR + int i = 0; + for(i = 0; i < d->numhttps_rrs; i++) + curlx_safefree(d->https_rrs[i].val); +#else + (void)d; +#endif +} + +#ifdef USE_HTTPSRR + +/* + * @brief decode the DNS name in a binary RRData + * @param buf points to the buffer (in/out) + * @param remaining points to the remaining buffer length (in/out) + * @param dnsname returns the string form name on success + * @return is 1 for success, error otherwise + * + * The encoding here is defined in + * https://datatracker.ietf.org/doc/html/rfc1035#section-3.1 + * + * The input buffer pointer will be modified so it points to after the end of + * the DNS name encoding on output. (that is why it is an "unsigned char + * **" :-) + */ +static CURLcode doh_decode_rdata_name(const unsigned char **buf, + size_t *remaining, char **dnsname) +{ + const unsigned char *cp = NULL; + size_t rem = 0; + unsigned char clen = 0; /* chunk len */ + struct dynbuf thename; + + DEBUGASSERT(buf && remaining && dnsname); + if(!buf || !remaining || !dnsname || !*remaining) + return CURLE_OUT_OF_MEMORY; + curlx_dyn_init(&thename, CURL_MAXLEN_HOST_NAME); + rem = *remaining; + cp = *buf; + clen = *cp++; + /* RFC 9460 says it must be uncompressed */ + if(clen > 63) + return CURLE_WEIRD_SERVER_REPLY; + + if(clen == 0) { + /* special case - return "." as name */ + if(curlx_dyn_addn(&thename, ".", 1)) + return CURLE_OUT_OF_MEMORY; + } + while(clen) { + if(clen >= rem) { + curlx_dyn_free(&thename); + return CURLE_OUT_OF_MEMORY; + } + if(curlx_dyn_addn(&thename, cp, clen) || + curlx_dyn_addn(&thename, ".", 1)) + return CURLE_TOO_LARGE; + + cp += clen; + rem -= (clen + 1); + if(rem <= 0) { + curlx_dyn_free(&thename); + return CURLE_OUT_OF_MEMORY; + } + clen = *cp++; + if(clen > 63) { + /* invalid format */ + curlx_dyn_free(&thename); + return CURLE_WEIRD_SERVER_REPLY; + } + } + *buf = cp; + *remaining = rem - 1; + *dnsname = curlx_dyn_ptr(&thename); + return CURLE_OK; +} + +/* @unittest 1658 */ +UNITTEST CURLcode doh_resp_decode_httpsrr(struct Curl_easy *data, + const unsigned char *cp, size_t len, + struct Curl_https_rrinfo **hrr); +UNITTEST CURLcode doh_resp_decode_httpsrr(struct Curl_easy *data, + const unsigned char *cp, size_t len, + struct Curl_https_rrinfo **hrr) +{ + uint16_t pcode = 0, plen = 0; + uint32_t expected_min_pcode = 0; + struct Curl_https_rrinfo *lhrr = NULL; + char *dnsname = NULL; + CURLcode result = CURLE_OUT_OF_MEMORY; + size_t olen; + + (void)data; + *hrr = NULL; + if(len <= 2) + return CURLE_BAD_FUNCTION_ARGUMENT; + lhrr = curlx_calloc(1, sizeof(struct Curl_https_rrinfo)); + if(!lhrr) + return CURLE_OUT_OF_MEMORY; + lhrr->priority = doh_get16bit(cp, 0); + cp += 2; + len -= 2; + if(doh_decode_rdata_name(&cp, &len, &dnsname) != CURLE_OK) + goto err; + lhrr->target = dnsname; + if(Curl_junkscan(dnsname, &olen, FALSE)) { + /* unacceptable hostname content */ + result = CURLE_WEIRD_SERVER_REPLY; + goto err; + } + while(len >= 4) { + pcode = doh_get16bit(cp, 0); + plen = doh_get16bit(cp, 2); + cp += 4; + len -= 4; + if(pcode < expected_min_pcode || plen > len) { + result = CURLE_WEIRD_SERVER_REPLY; + goto err; + } + result = Curl_httpsrr_set(lhrr, pcode, cp, plen); + if(result) + goto err; + Curl_httpsrr_trace(data, lhrr); + cp += plen; + len -= plen; + expected_min_pcode = pcode + 1; + } + *hrr = lhrr; + return CURLE_OK; +err: + Curl_httpsrr_destroy(lhrr); + return result; +} + +#endif /* USE_HTTPSRR */ + +/* called from multi when a sub transfer, e.g. doh probe, is done. + * Parse the response and set the results in the `async` context + * of master, using the id from the probe's CURL_EZM_DOH_PROBE + * meta data. */ +static void doh_probe_done(struct Curl_easy *doh, + struct Curl_easy *master, CURLcode result) +{ + struct Curl_resolv_async *async = NULL; + struct doh_probes *dohp = NULL; + struct doh_request *doh_req = NULL; + struct Curl_addrinfo **pdest_ai; + struct dohentry de; + int slot, httpcode; + + de_init(&de); + doh_req = Curl_meta_get(doh, CURL_EZM_DOH_PROBE); + if(!doh_req) { + /* transfer `doh` is not a DoH probe. */ + DEBUGASSERT(0); + goto out; + } + + async = Curl_async_get(master, doh_req->resolv_id); + if(!async) { + CURL_TRC_DNS(master, "[%u] ignoring outdated DoH response", + doh_req->resolv_id); + goto out; + } + dohp = async->doh; + + for(slot = 0; slot < DOH_SLOT_COUNT; ++slot) { + if(dohp->probe_mid[slot] == doh->mid) + break; + } + /* We really should have found the slot where to store the response */ + if(slot >= DOH_SLOT_COUNT) { + failf(master, "DoH: unknown sub request done"); + DEBUGASSERT(0); + goto out; + } + + async->queries_ongoing--; + dohp = async->doh; + httpcode = doh->info.httpcode; + switch(slot) { + case DOH_SLOT_IPV4: + async->dns_responses |= CURL_DNSQ_A; + break; +#ifdef USE_IPV6 + case DOH_SLOT_IPV6: + async->dns_responses |= CURL_DNSQ_AAAA; + break; +#endif +#ifdef USE_HTTPSRR + case DOH_SLOT_HTTPS_RR: + async->dns_responses |= CURL_DNSQ_HTTPS; + break; +#endif + default: + DEBUGASSERT(0); + break; + } + + if(result) { + dohp->probe_rc[slot] = DOH_HTTP_FAILED; + infof(doh, "[DoH] [%s] error: %s", + doh_type2name(doh_req->dnstype), curl_easy_strerror(result)); + goto out; + } + else if((httpcode < 200) || (httpcode >= 300)) { + dohp->probe_rc[slot] = DOH_HTTP_FAILED; + infof(doh, "[DoH] [%s] error: HTTP status %d", + doh_type2name(doh_req->dnstype), httpcode); + goto out; + } + + dohp->probe_rc[slot] = doh_resp_decode(curlx_dyn_uptr(&doh_req->resp_body), + curlx_dyn_len(&doh_req->resp_body), + doh_req->dnstype, &de); + if(dohp->probe_rc[slot]) { +#ifdef USE_HTTPSRR + if((dohp->probe_rc[slot] == DOH_NO_CONTENT) && + (doh_req->dnstype == CURL_DNS_TYPE_HTTPS)) { + dohp->probe_rc[slot] = DOH_DNS_NXDOMAIN; + } +#endif + infof(doh, "[DoH] [%s] error decoding response: %s", + doh_type2name(doh_req->dnstype), + doh_strerror(dohp->probe_rc[slot])); + goto out; + } + + if(doh_req->dnstype == CURL_DNS_TYPE_A) + pdest_ai = &async->ai_A; + else if(doh_req->dnstype == CURL_DNS_TYPE_AAAA) + pdest_ai = &async->ai_AAAA; + else + pdest_ai = NULL; + + if(pdest_ai && de.numaddr) { + if(*pdest_ai) { + Curl_freeaddrinfo(*pdest_ai); + *pdest_ai = NULL; + } + result = doh2ai(&de, async->peer->hostname, async->peer->port, pdest_ai); + if(result) { /* hard failure on our side, fail completely */ + infof(doh, "[DoH] [%s] error creating addrinfo: %s", + doh_type2name(doh_req->dnstype), curl_easy_strerror(result)); + dohp->probe_rc[slot] = DOH_OOM; + async->result = result; + } + } +#ifdef USE_HTTPSRR + else if((doh_req->dnstype == CURL_DNS_TYPE_HTTPS) && de.numhttps_rrs) { + CURL_TRC_DNS(doh, "[HTTPS] got %d records", de.numhttps_rrs); + result = doh_resp_decode_httpsrr(doh, de.https_rrs->val, + de.https_rrs->len, &async->httpsrr); + if(result) { + dohp->probe_rc[slot] = DOH_HTTP_FAILED; + infof(doh, "[DoH] error decoding HTTPS RR: %s", + curl_easy_strerror(result)); + goto out; + } + } +#endif /* USE_HTTPSRR */ + + /* DoH request complete, run master to act on results */ + infof(doh, "DoH request complete, %u to go", async->queries_ongoing); + +out: + Curl_multi_mark_dirty(master); + de_cleanup(&de); + Curl_meta_remove(doh, CURL_EZM_DOH_PROBE); +} + +CURLcode Curl_doh_take_result(struct Curl_easy *data, + struct Curl_resolv_async *async, + struct Curl_dns_entry **pdns) +{ + struct doh_probes *dohp = async->doh; + CURLcode result = CURLE_OK; + + *pdns = NULL; /* defaults to no response */ + if(!dohp) + return CURLE_OUT_OF_MEMORY; + + async->negative_answer = FALSE; + if(async->result) { + result = async->result; + goto out; + } + + if(CURL_DNSQ_IS_ADDR(async->dns_queries) && + dohp->probe_mid[DOH_SLOT_IPV4] == UINT32_MAX && + dohp->probe_mid[DOH_SLOT_IPV6] == UINT32_MAX) { + failf(data, "Could not DoH-resolve: %s", async->peer->hostname); + return async->for_proxy ? + CURLE_COULDNT_RESOLVE_PROXY : CURLE_COULDNT_RESOLVE_HOST; + } + else if(!async->queries_ongoing) { + struct Curl_dns_entry *dns = NULL; + bool negative = TRUE; + int slot; + + /* remove DoH handles from multi handle and close them */ + doh_close(data, async); + /* parse the responses, create the struct and return it! */ + for(slot = 0; slot < DOH_SLOT_COUNT; slot++) { + /* Failing without an NXDOMAIN answer - a SERVFAIL-class rcode or + an undecodable response - says nothing about the name. Such a + failure must not be cached as a negative entry. */ + if(dohp->probe_rc[slot] && (dohp->probe_rc[slot] != DOH_DNS_NXDOMAIN)) + negative = FALSE; + } /* next slot */ + + if(async->ai_A || async->ai_AAAA) { + dns = Curl_dnsc_mk_addr2( + data, async->dns_queries, &async->ai_A, &async->ai_AAAA, async->peer); + if(!dns) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } +#ifdef USE_HTTPSRR + else if((async->dns_queries & CURL_DNSQ_HTTPS) && + !dohp->probe_rc[DOH_SLOT_HTTPS_RR]) { + Curl_httpsrr_trace(data, async->httpsrr); + dns = Curl_dnsc_mk_https(data, &async->httpsrr, async->peer); + if(!dns) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } +#endif /* USE_HTTPSRR */ + else { + /* every query failed. Only NXDOMAIN answers for all of them + make this a negative answer, eligible for caching. */ + async->negative_answer = negative; + result = async->for_proxy ? + CURLE_COULDNT_RESOLVE_PROXY : CURLE_COULDNT_RESOLVE_HOST; + } + + /* and add the entry to the cache */ + if(dns) + result = Curl_dnscache_add(data, dns); + *pdns = dns; + } /* !async->queries_ongoing */ + else + /* wait for pending DoH transactions to complete */ + return CURLE_AGAIN; + +out: + Curl_doh_cleanup(data, async); + return result; +} + +static void doh_close(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + struct doh_probes *doh = async ? async->doh : NULL; + if(doh && data->multi) { + struct Curl_easy *probe_data; + uint32_t mid; + size_t slot; + for(slot = 0; slot < DOH_SLOT_COUNT; slot++) { + mid = doh->probe_mid[slot]; + if(mid == UINT32_MAX) + continue; + doh->probe_mid[slot] = UINT32_MAX; + /* should have been called before data is removed from multi handle */ + DEBUGASSERT(data->multi); + probe_data = data->multi ? Curl_multi_get_easy(data->multi, mid) : NULL; + if(!probe_data) { + DEBUGF(infof(data, "Curl_doh_close: xfer for mid=%u not found!", mid)); + continue; + } + probe_data->sub_xfer_done = NULL; /* No longer interested in result */ + /* data->multi might already be reset at this time */ + Curl_multi_remove_handle(data->multi, probe_data); + Curl_close(&probe_data); + } + CURL_TRC_DNS(data, "[DoH] probe done"); + } +} + +void Curl_doh_cleanup(struct Curl_easy *data, + struct Curl_resolv_async *async) +{ + struct doh_probes *dohp = async->doh; + if(dohp) { + doh_close(data, async); + curlx_safefree(async->doh); + } +} + +#endif /* CURL_DISABLE_DOH */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/doh.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/doh.h new file mode 100644 index 0000000000..a6358027a7 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/doh.h @@ -0,0 +1,168 @@ +#ifndef HEADER_CURL_DOH_H +#define HEADER_CURL_DOH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "urldata.h" + +/* enums outside of the #ifdef to make the types work in unitprotos.h even on + builds without DoH support */ + +struct Curl_resolv_async; + +typedef enum { + DOH_OK, + DOH_DNS_BAD_LABEL, /* 1 */ + DOH_DNS_OUT_OF_RANGE, /* 2 */ + DOH_DNS_LABEL_LOOP, /* 3 */ + DOH_TOO_SMALL_BUFFER, /* 4 */ + DOH_OUT_OF_MEM, /* 5 */ + DOH_DNS_RDATA_LEN, /* 6 */ + DOH_DNS_MALFORMAT, /* 7 */ + DOH_DNS_BAD_RCODE, /* 8 - unsuccessful rcode, not NXDOMAIN */ + DOH_DNS_UNEXPECTED_TYPE, /* 9 */ + DOH_DNS_UNEXPECTED_CLASS, /* 10 */ + DOH_NO_CONTENT, /* 11 */ + DOH_DNS_BAD_ID, /* 12 */ + DOH_DNS_NAME_TOO_LONG, /* 13 */ + DOH_DNS_NXDOMAIN, /* 14 - no such name */ + DOH_HTTP_FAILED, /* failure at the HTTP level */ + DOH_OOM, /* out of memory */ + DOH_CODE_LAST /* Not used, limit */ +} DOHcode; + +typedef enum { + CURL_DNS_TYPE_A = 1, + CURL_DNS_TYPE_NS = 2, + CURL_DNS_TYPE_CNAME = 5, + CURL_DNS_TYPE_AAAA = 28, + CURL_DNS_TYPE_DNAME = 39, /* RFC6672 */ + CURL_DNS_TYPE_HTTPS = 65 +} DNStype; + +struct dohentry; /* forward-declare for non-DoH builds */ + +#ifndef CURL_DISABLE_DOH + +enum doh_slot_num { + /* Explicit values for first two symbols so as to match hard-coded + * constants in existing code + */ + DOH_SLOT_IPV4 = 0, /* make 'V4' stand out for readability */ + DOH_SLOT_IPV6 = 1, /* 'V6' likewise */ + + /* Space here for (possibly build-specific) additional slot definitions */ +#ifdef USE_HTTPSRR + DOH_SLOT_HTTPS_RR = 2, /* for HTTPS RR */ +#endif + + /* for example */ + /* #ifdef WANT_DOH_FOOBAR_TXT */ + /* DOH_PROBE_SLOT_FOOBAR_TXT, */ + /* #endif */ + + /* AFTER all slot definitions, establish how many we have */ + DOH_SLOT_COUNT +}; + +#define CURL_EZM_DOH_PROBE "ezm:doh-p" + +/* the largest one we can make, based on RFCs 1034, 1035 */ +#define DOH_MAX_DNSREQ_SIZE (256 + 16) + +/* each DoH probe request has this + * as easy meta for CURL_EZM_DOH_PROBE */ +struct doh_request { + unsigned char req_body[DOH_MAX_DNSREQ_SIZE]; + struct curl_slist *req_hds; + struct dynbuf resp_body; + size_t req_body_len; + uint32_t resolv_id; /* id of the resolve operation */ + DNStype dnstype; +}; + +/* each transfer firing off DoH requests has this + * as easy meta for CURL_EZM_DOH_MASTER */ +struct doh_probes { + uint32_t probe_mid[DOH_SLOT_COUNT]; + DOHcode probe_rc[DOH_SLOT_COUNT]; +}; + +/* + * Curl_doh() starts a name resolve using DoH (DNS-over-HTTPS). It resolves a + * name and returns a 'Curl_addrinfo *' with the address information. + */ +CURLcode Curl_doh(struct Curl_easy *data, + struct Curl_resolv_async *async); + +CURLcode Curl_doh_take_result(struct Curl_easy *data, + struct Curl_resolv_async *async, + struct Curl_dns_entry **pdns); + +#define DOH_MAX_ADDR 24 +#define DOH_MAX_HTTPS 4 + +struct dohaddr { + int type; + union { + unsigned char v4[4]; /* network byte order */ + unsigned char v6[16]; + } ip; +}; + +#ifdef USE_HTTPSRR + +/* + * These may need escaping when found within an ALPN string + * value. + */ +#define COMMA_CHAR ',' +#define BACKSLASH_CHAR '\\' + +struct dohhttps_rr { + uint16_t len; /* raw encoded length */ + unsigned char *val; /* raw encoded octets */ +}; +#endif + +struct dohentry { + struct dohaddr addr[DOH_MAX_ADDR]; + int numaddr; + unsigned int ttl; +#ifdef USE_HTTPSRR + struct dohhttps_rr https_rrs[DOH_MAX_HTTPS]; + int numhttps_rrs; +#endif +}; + +void Curl_doh_cleanup(struct Curl_easy *data, + struct Curl_resolv_async *async); +#define Curl_doh_wanted(d) (!!(d)->set.doh) + +#else /* CURL_DISABLE_DOH */ +#define Curl_doh(a, b) NULL +#define Curl_doh_take_result(x, y, z) CURLE_COULDNT_RESOLVE_HOST +#define Curl_doh_wanted(d) FALSE +#endif /* !CURL_DISABLE_DOH */ + +#endif /* HEADER_CURL_DOH_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/hostip.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/hostip.c new file mode 100644 index 0000000000..8464bd2917 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/hostip.c @@ -0,0 +1,1183 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETINET_IN6_H +#include <netinet/in6.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include <setjmp.h> /* for sigjmp_buf, sigsetjmp() */ +#include <signal.h> + +#include "urldata.h" +#include "curl_addrinfo.h" +#include "curl_trc.h" +#include "url.h" +#include "multiif.h" +#include "progress.h" +#include "select.h" +#include "strcase.h" +#include "easy_lock.h" +#include "vdns/dnscache.h" +#include "vdns/doh.h" +#include "vdns/hostip.h" +#include "vdns/httpsrr.h" +#include "curlx/inet_ntop.h" +#include "curlx/inet_pton.h" +#include "curlx/strcopy.h" +#include "curlx/strparse.h" + +#if defined(CURLRES_SYNCH) && \ + defined(HAVE_ALARM) && \ + defined(SIGALRM) && \ + defined(HAVE_SIGSETJMP) && \ + defined(GLOBAL_INIT_IS_THREADSAFE) +/* alarm-based timeouts can only be used with all the dependencies satisfied */ +#define USE_ALARM_TIMEOUT +#endif + +#define RESOLV_FAIL(for_proxy) \ + ((for_proxy) ? CURLE_COULDNT_RESOLVE_PROXY : CURLE_COULDNT_RESOLVE_HOST) + +#define IS_RESOLV_FAIL(result) \ + (((result) == CURLE_COULDNT_RESOLVE_HOST) || \ + ((result) == CURLE_COULDNT_RESOLVE_PROXY)) +/* + * ipv6works() returns TRUE if IPv6 seems to work. + */ +#ifdef USE_IPV6 +static bool ipv6works(struct Curl_easy *data); +#else +#define ipv6works(x) FALSE +#endif + +/* + * hostip.c explained + * ================== + * + * The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c + * source file are these: + * + * CURLRES_IPV6 - this host has getaddrinfo() and family, and thus we use + * that. The host may not be able to resolve IPv6, but we do not really have to + * take that into account. Hosts that are not IPv6-enabled have CURLRES_IPV4 + * defined. + * + * USE_RESOLV_ARES - is defined if libcurl is built to use c-ares for + * asynchronous name resolves. This can be Windows or *nix. + * + * USE_RESOLV_THREADED - is defined if libcurl is built to run under (native) + * Windows, and then the name resolve will be done in a new thread, and the + * supported API will be the same as for ares-builds. + * + * If any of the two previous are defined, CURLRES_ASYNCH is defined too. If + * libcurl is not built to use an asynchronous resolver, CURLRES_SYNCH is + * defined. + * + * The host*.c sources files are split up like this: + * + * hostip.c - method-independent resolver functions and utility functions + * hostip4.c - IPv4 specific functions + * hostip6.c - IPv6 specific functions + * asyn.h - common functions for all async resolvers + * The two asynchronous name resolver backends are implemented in: + * asyn-ares.c - async resolver using c-ares + * asyn-thread.c - async resolver using POSIX threads + * + * The hostip.h is the united header file for all this. It defines the + * CURLRES_* defines based on the config*.h and curl_setup.h defines. + */ + +uint8_t Curl_resolv_dns_queries(struct Curl_easy *data, uint8_t ip_version) +{ + (void)data; + switch(ip_version) { + case CURL_IPRESOLVE_V6: + return CURL_DNSQ_AAAA; + case CURL_IPRESOLVE_V4: + return CURL_DNSQ_A; + default: + if(ipv6works(data)) + return (CURL_DNSQ_A | CURL_DNSQ_AAAA); + else + return CURL_DNSQ_A; + } +} + +#ifdef CURLVERBOSE +const char *Curl_resolv_query_str(uint8_t dns_queries) +{ + switch(dns_queries) { + case (CURL_DNSQ_A | CURL_DNSQ_AAAA | CURL_DNSQ_HTTPS): + return "A+AAAA+HTTPS"; + case (CURL_DNSQ_A | CURL_DNSQ_AAAA): + return "A+AAAA"; + case (CURL_DNSQ_AAAA | CURL_DNSQ_HTTPS): + return "AAAA+HTTPS"; + case (CURL_DNSQ_AAAA): + return "AAAA"; + case (CURL_DNSQ_A | CURL_DNSQ_HTTPS): + return "A+HTTPS"; + case (CURL_DNSQ_A): + return "A"; + case (CURL_DNSQ_HTTPS): + return "HTTPS"; + case 0: + return "-"; + default: + DEBUGASSERT(0); + return "???"; + } +} +#endif + +/* + * Curl_printable_address() stores a printable version of the 1st address + * given in the 'ai' argument. The result will be stored in the buf that is + * bufsize bytes big. + * + * If the conversion fails, the target buffer is empty. + */ +void Curl_printable_address(const struct Curl_addrinfo *ai, char *buf, + size_t bufsize) +{ + DEBUGASSERT(bufsize); + buf[0] = 0; + + switch(ai->ai_family) { + case AF_INET: { + const struct sockaddr_in *sa4 = (const void *)ai->ai_addr; + const struct in_addr *ipaddr4 = &sa4->sin_addr; + (void)curlx_inet_ntop(ai->ai_family, (const void *)ipaddr4, buf, bufsize); + break; + } +#ifdef USE_IPV6 + case AF_INET6: { + const struct sockaddr_in6 *sa6 = (const void *)ai->ai_addr; + const struct in6_addr *ipaddr6 = &sa6->sin6_addr; + (void)curlx_inet_ntop(ai->ai_family, (const void *)ipaddr6, buf, bufsize); + break; + } +#endif + default: + break; + } +} + +#ifdef USE_ALARM_TIMEOUT +/* Beware this is a global and unique instance. This is used to store the + return address that we can jump back to from inside a signal handler. This + is not thread-safe stuff. */ +static sigjmp_buf curl_jmpenv; +static curl_simple_lock curl_jmpenv_lock = CURL_SIMPLE_LOCK_INIT; +#endif + +#ifdef USE_IPV6 +/* return a static IPv6 ::1 for the name */ +static struct Curl_addrinfo *get_localhost6(uint16_t port, const char *name) +{ + struct Curl_addrinfo *ca; + const size_t ss_size = sizeof(struct sockaddr_in6); + const size_t hostlen = strlen(name); + struct sockaddr_in6 sa6; + unsigned char ipv6[16]; + unsigned short port16 = (unsigned short)(port & 0xffff); + ca = curlx_calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen + 1); + if(!ca) + return NULL; + + memset(&sa6, 0, sizeof(sa6)); + sa6.sin6_family = AF_INET6; + sa6.sin6_port = htons(port16); + + (void)curlx_inet_pton(AF_INET6, "::1", ipv6); + memcpy(&sa6.sin6_addr, ipv6, sizeof(ipv6)); + + ca->ai_flags = 0; + ca->ai_family = AF_INET6; + ca->ai_socktype = SOCK_STREAM; + ca->ai_protocol = IPPROTO_TCP; + ca->ai_addrlen = (curl_socklen_t)ss_size; + ca->ai_next = NULL; + ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo)); + memcpy(ca->ai_addr, &sa6, ss_size); + ca->ai_canonname = (char *)ca->ai_addr + ss_size; + curlx_strcopy(ca->ai_canonname, hostlen + 1, name, hostlen); + return ca; +} +#else +#define get_localhost6(x, y) NULL +#endif + +/* return a static IPv4 127.0.0.1 for the given name */ +static struct Curl_addrinfo *get_localhost(uint16_t port, const char *name) +{ + struct Curl_addrinfo *ca; + struct Curl_addrinfo *ca6; + const size_t ss_size = sizeof(struct sockaddr_in); + const size_t hostlen = strlen(name); + struct sockaddr_in sa; + unsigned int ipv4; + unsigned short port16 = (unsigned short)(port & 0xffff); + + /* memset to clear the sa.sin_zero field */ + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_port = htons(port16); + if(curlx_inet_pton(AF_INET, "127.0.0.1", (char *)&ipv4) < 1) + return NULL; + memcpy(&sa.sin_addr, &ipv4, sizeof(ipv4)); + + ca = curlx_calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen + 1); + if(!ca) + return NULL; + ca->ai_flags = 0; + ca->ai_family = AF_INET; + ca->ai_socktype = SOCK_STREAM; + ca->ai_protocol = IPPROTO_TCP; + ca->ai_addrlen = (curl_socklen_t)ss_size; + ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo)); + memcpy(ca->ai_addr, &sa, ss_size); + ca->ai_canonname = (char *)ca->ai_addr + ss_size; + curlx_strcopy(ca->ai_canonname, hostlen + 1, name, hostlen); + + ca6 = get_localhost6(port, name); + if(!ca6) + return ca; + ca6->ai_next = ca; + return ca6; +} + +#ifdef USE_IPV6 +/* the nature of most systems is that IPv6 status does not come and go during a + program's lifetime so we only probe the first time and then we have the + info kept for fast reuse */ +CURLcode Curl_probeipv6(struct Curl_multi *multi) +{ + /* probe to see if we have a working IPv6 stack */ + curl_socket_t s = CURL_SOCKET(PF_INET6, SOCK_DGRAM, 0); + multi->ipv6_works = FALSE; + if(s == CURL_SOCKET_BAD) { + if(SOCKERRNO == SOCKENOMEM) + return CURLE_OUT_OF_MEMORY; + } + else { + multi->ipv6_works = TRUE; + sclose(s); + } + return CURLE_OK; +} + +/* + * ipv6works() returns TRUE if IPv6 seems to work. + */ +static bool ipv6works(struct Curl_easy *data) +{ + DEBUGASSERT(data); + DEBUGASSERT(data->multi); + return data ? data->multi->ipv6_works : FALSE; +} +#endif /* USE_IPV6 */ + +/* + * Curl_host_is_ipnum() returns TRUE if the given string is a numerical IPv4 + * (or IPv6 if supported) address. + */ +bool Curl_host_is_ipnum(const char *hostname) +{ + struct in_addr in; +#ifdef USE_IPV6 + struct in6_addr in6; +#endif + if(curlx_inet_pton(AF_INET, hostname, &in) > 0 +#ifdef USE_IPV6 + || curlx_inet_pton(AF_INET6, hostname, &in6) > 0 +#endif + ) + return TRUE; + return FALSE; +} + +/* return TRUE if 'part' is a case insensitive tail of 'full' */ +static bool tailmatch(const char *full, size_t flen, + const char *part, size_t plen) +{ + if(plen > flen) + return FALSE; + return curl_strnequal(part, &full[flen - plen], plen); +} + +static CURLcode hostip_resolv_failed(struct Curl_easy *data, + struct Curl_peer *peer, + bool for_proxy) +{ + failf(data, "Could not resolve %s: %s", + for_proxy ? "proxy" : "host", peer->hostname); + return RESOLV_FAIL(for_proxy); +} + +static bool can_resolve_dns_queries(struct Curl_easy *data, + uint8_t dns_queries) +{ + (void)data; + if((CURL_DNSQ_IS_ADDR(dns_queries) == CURL_DNSQ_AAAA) && !ipv6works(data)) + return FALSE; + return TRUE; +} + +CURLcode Curl_resolv_announce_start(struct Curl_easy *data, + void *resolver) +{ + if(data->set.resolver_start) { + struct Curl_mapi_guard guard; + int rc; + + CURL_TRC_DNS(data, "announcing resolve to application"); + CURL_CBAPI_START(&guard, data, easy_resolver_start); + rc = data->set.resolver_start(resolver, NULL, + data->set.resolver_start_client); + CURL_CBAPI_END(&guard); + if(rc) { + CURL_TRC_DNS(data, "application aborted resolve"); + return CURLE_ABORTED_BY_CALLBACK; + } + } + return CURLE_OK; +} + +#ifdef USE_CURL_ASYNC + +static struct Curl_resolv_async *hostip_async_new(struct Curl_easy *data, + uint8_t dns_queries, + struct Curl_peer *peer, + uint8_t transport, + bool for_proxy, + timediff_t timeout_ms) +{ + struct Curl_resolv_async *async; + + if(!data->multi) { + DEBUGASSERT(0); + return NULL; + } + + /* struct size already includes the NUL for hostname */ + async = curlx_calloc(1, sizeof(*async)); + if(!async) + return NULL; + + /* Give every async resolve operation a "unique" id. This may + * wrap around after a long time, making collisions highly unlikely. + * As we keep the async structs at the easy handle, chances of + * easy `mid plus resolv->id` colliding should be astronomical. + * `resolv_id == 0` is never used. */ + if(data->multi->last_resolv_id == UINT32_MAX) + data->multi->last_resolv_id = 1; /* wrap around */ + else + data->multi->last_resolv_id++; + async->id = data->multi->last_resolv_id; + Curl_peer_link(&async->peer, peer); + async->dns_queries = dns_queries; + async->transport = transport; + async->for_proxy = for_proxy; + async->start = *Curl_pgrs_now(data); + async->timeout_ms = timeout_ms; + async->is_ipaddr = Curl_is_ipaddr(peer->hostname); + if(async->is_ipaddr) + async->is_ipv4addr = Curl_is_ipv4addr(peer->hostname); + + return async; +} + +static CURLcode hostip_resolv_take_result(struct Curl_easy *data, + struct Curl_resolv_async *async, + struct Curl_dns_entry **pdns) +{ + CURLcode result; + + /* If async resolving is ongoing, this must be set */ + if(!async) + return CURLE_FAILED_INIT; + +#ifndef CURL_DISABLE_DOH + if(async->doh) + result = Curl_doh_take_result(data, async, pdns); + else +#endif + result = Curl_async_take_result(data, async, pdns); + + if(result == CURLE_AGAIN) { + CURL_TRC_DNS(data, "[%s] resolve incomplete, responses=%s, " + "ongoing=%d for %s:%d", + Curl_resolv_query_str(async->dns_queries), + Curl_resolv_query_str(async->dns_responses), + async->queries_ongoing, + async->peer->hostname, async->peer->port); + result = CURLE_OK; + } + else if(IS_RESOLV_FAIL(result)) { + result = Curl_async_failed(data, async, NULL); + } + else if(result) { + /* a local failure, not a resolve answer. Keep the error as it + is so it does not get treated as one. */ + CURL_TRC_DNS(data, "[%s] resolve error %d for %s:%u", + Curl_resolv_query_str(async->dns_queries), + (int)result, async->peer->hostname, async->peer->port); + } + else { + CURL_TRC_DNS(data, "[%s] resolve complete for %s:%u", + Curl_resolv_query_str(async->dns_queries), + async->peer->hostname, async->peer->port); + DEBUGASSERT(*pdns); + } + + return result; +} + +timediff_t Curl_resolv_elapsed_ms(struct Curl_easy *data, + uint32_t resolv_id, + const struct curltime *pnow) +{ + struct Curl_resolv_async *async = Curl_async_get(data, resolv_id); + if(!async) + return CURL_TIMEOUT_RESOLVE_MS; + return curlx_ptimediff_ms(pnow, &async->start); +} + +bool Curl_resolv_has_answers(struct Curl_easy *data, + uint32_t resolv_id, uint8_t dns_queries) +{ + struct Curl_resolv_async *async = Curl_async_get(data, resolv_id); + uint8_t check_queries; + /* a no longer existing/running resolve has all answers. */ + if(!async || async->done) + return TRUE; + /* Relevant are only queries undertaken. Others are considered answered. */ + check_queries = (dns_queries & async->dns_queries); + if((check_queries & async->dns_responses) != check_queries) { + return FALSE; + } + return TRUE; +} + +const struct Curl_addrinfo *Curl_resolv_get_ai(struct Curl_easy *data, + uint32_t resolv_id, + int ai_family, + unsigned int index) +{ + struct Curl_resolv_async *async = Curl_async_get(data, resolv_id); + if(!async || !CURL_DNSQ_IS_ADDR(async->dns_queries)) + return NULL; + switch(ai_family) { + case AF_INET: + return Curl_addrinfo_get(async->ai_A, ai_family, index); +#ifdef USE_IPV6 + case AF_INET6: + return Curl_addrinfo_get(async->ai_AAAA, ai_family, index); +#endif + default: + return NULL; + } +} + +#ifdef USE_HTTPSRR + +CURLcode Curl_resolv_https(struct Curl_easy *data, + struct Curl_peer *peer, + bool for_proxy, + timediff_t timeout_ms, + uint32_t *presolv_id, + struct Curl_dns_entry **pdns) +{ + return Curl_resolv(data, peer, CURL_DNSQ_HTTPS, TRNSPRT_TCP, + for_proxy, timeout_ms, presolv_id, pdns); +} + +const struct Curl_https_rrinfo * +Curl_resolv_get_https(struct Curl_easy *data, uint32_t resolv_id) +{ + struct Curl_resolv_async *async; + if(!Curl_resolv_knows_https(data, resolv_id)) + return NULL; + async = Curl_async_get(data, resolv_id); + return async ? async->httpsrr : NULL; +} + +bool Curl_resolv_knows_https(struct Curl_easy *data, uint32_t resolv_id) +{ + struct Curl_resolv_async *async = Curl_async_get(data, resolv_id); + if(async && (async->dns_queries & CURL_DNSQ_HTTPS)) + return ((async->dns_responses & CURL_DNSQ_HTTPS) || + !async->queries_ongoing); + return TRUE; /* we know it will never come */ +} + +#endif /* USE_HTTPSRR */ + +#endif /* USE_CURL_ASYNC */ + +/* Start resolving. `*pnegative` is only meaningful when this returns + a CURLE_COULDNT_RESOLVE_* failure: TRUE when the resolver answered + that the name does not exist, FALSE on transient or local failures + that must not be cached as negative entries. */ +static CURLcode hostip_resolv_start(struct Curl_easy *data, + uint8_t dns_queries, + struct Curl_peer *peer, + uint8_t transport, + bool for_proxy, + timediff_t timeout_ms, + bool allowDOH, + uint32_t *presolv_id, + struct Curl_dns_entry **pdns, + bool *pnegative) +{ +#ifdef USE_CURL_ASYNC + struct Curl_resolv_async *async = NULL; +#endif + struct Curl_addrinfo *addr = NULL; + size_t hostname_len; + bool addr_queries = (dns_queries & (CURL_DNSQ_A | CURL_DNSQ_AAAA)); + CURLcode result = CURLE_OK; + + *pnegative = FALSE; + + (void)timeout_ms; /* not in all ifdefs */ + *presolv_id = 0; + *pdns = NULL; + + /* Check for "known" things to resolve ourselves. */ + if(addr_queries) { +#ifndef USE_RESOLVE_ON_IPS + if(Curl_is_ipaddr(peer->hostname)) { + /* test655 verifies that the announce is done, even though there + * is no real resolving. So, keep doing this. */ + result = Curl_resolv_announce_start(data, NULL); + if(result) + goto out; + /* shortcut literal IP addresses, if we are not told to resolve them. */ + result = Curl_str2addr(peer->hostname, peer->port, &addr); + goto out; + } +#endif + + hostname_len = strlen(peer->hostname); + if(curl_strequal(peer->hostname, "localhost") || + curl_strequal(peer->hostname, "localhost.") || + tailmatch(peer->hostname, hostname_len, STRCONST(".localhost")) || + tailmatch(peer->hostname, hostname_len, STRCONST(".localhost."))) { + result = Curl_resolv_announce_start(data, NULL); + if(result) + goto out; + addr = get_localhost(peer->port, peer->hostname); + if(!addr) + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } +#ifndef CURL_DISABLE_DOH + if(!Curl_is_ipaddr(peer->hostname) && allowDOH && data->set.doh) { + result = Curl_resolv_announce_start(data, NULL); + if(result) + goto out; + if(!async) { + async = hostip_async_new(data, dns_queries, peer, transport, + for_proxy, timeout_ms); + if(!async) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + result = Curl_doh(data, async); + goto out; + } +#else + (void)allowDOH; +#endif + + /* Can we provide the requested IP specifics in resolving? */ + if(!can_resolve_dns_queries(data, dns_queries)) { + result = RESOLV_FAIL(for_proxy); + goto out; + } + +#ifdef CURLRES_ASYNCH + (void)addr; + if(!async) { + async = hostip_async_new(data, dns_queries, peer, transport, + for_proxy, timeout_ms); + if(!async) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + result = Curl_async_getaddrinfo(data, async); + if(result == CURLE_AGAIN) { + /* the answer might be there already. Check. */ + CURLcode r2 = hostip_resolv_take_result(data, async, pdns); + if(r2) + result = r2; + else if(*pdns) + result = CURLE_OK; + } +#else + result = Curl_resolv_announce_start(data, NULL); + if(result) + goto out; + addr = Curl_sync_getaddrinfo(data, dns_queries, peer->hostname, peer->port, + transport); + if(!addr) { + result = RESOLV_FAIL(for_proxy); + /* the synchronous resolvers do not tell a transient failure from + an authoritative negative answer, treat it as before */ + *pnegative = TRUE; + } +#endif + +out: + if(!result) { + if(addr) { + /* we got a response, create a dns entry, add to cache, return */ + DEBUGASSERT(!*pdns); + *pdns = Curl_dnsc_mk_addr(data, dns_queries, &addr, peer); + if(!*pdns) + result = CURLE_OUT_OF_MEMORY; + } + else if(!*pdns) + result = CURLE_AGAIN; + } + else if(*pdns) + Curl_dns_entry_unlink(data, pdns); + else if(addr) + Curl_freeaddrinfo(addr); + +#ifdef USE_CURL_ASYNC + if(async) { + if(result == CURLE_AGAIN) { /* still need it, link, return id. */ + *presolv_id = async->id; + async->next = data->state.async; + data->state.async = async; + } + else { + *pnegative = !!async->negative_answer; + Curl_async_destroy(data, async); + } + } +#endif + return result; +} + +static CURLcode hostip_resolv(struct Curl_easy *data, + uint8_t dns_queries, + struct Curl_peer *peer, + uint8_t transport, + bool for_proxy, + timediff_t timeout_ms, + bool allowDOH, + uint32_t *presolv_id, + struct Curl_dns_entry **pdns) +{ + size_t hostname_len; + CURLcode result = RESOLV_FAIL(for_proxy); + bool cache_dns = FALSE; + bool negative = FALSE; + + (void)timeout_ms; /* not used in all ifdefs */ + *presolv_id = 0; + *pdns = NULL; + +#ifdef CURL_DISABLE_DOH + (void)allowDOH; +#endif + + /* We should intentionally error and not resolve .onion TLDs */ + hostname_len = strlen(peer->hostname); + DEBUGASSERT(hostname_len); + if(hostname_len >= 7 && + (curl_strequal(&peer->hostname[hostname_len - 6], ".onion") || + curl_strequal(&peer->hostname[hostname_len - 7], ".onion."))) { + failf(data, "Not resolving .onion address (RFC 7686)"); + goto out; + } + +#ifdef DEBUGBUILD + CURL_TRC_DNS(data, "[%s] hostip_resolv(%s:%u)", + Curl_resolv_query_str(dns_queries), peer->hostname, peer->port); + if((CURL_DNSQ_IS_ADDR(dns_queries) == CURL_DNSQ_AAAA) && + getenv("CURL_DBG_RESOLV_FAIL_IPV6")) { + infof(data, "DEBUG fail ipv6 resolve"); + result = hostip_resolv_failed(data, peer, for_proxy); + goto out; + } +#endif + /* Let's check our DNS cache first */ + result = Curl_dnscache_get(data, dns_queries, peer, pdns); + if(*pdns) { + infof(data, "Hostname %s was found in DNS cache", peer->hostname); + result = CURLE_OK; + } + else if(result) { + infof(data, "Negative DNS entry"); + result = hostip_resolv_failed(data, peer, for_proxy); + } + else { + /* No luck, we need to start resolving. */ + cache_dns = TRUE; + result = hostip_resolv_start(data, dns_queries, peer, transport, + for_proxy, timeout_ms, allowDOH, + presolv_id, pdns, &negative); + CURL_TRC_DNS(data, "[%s] hostip_resolv started -> %d", + Curl_resolv_query_str(dns_queries), (int)result); + } + +out: + if(result && (result != CURLE_AGAIN)) { + Curl_dns_entry_unlink(data, pdns); + if(IS_RESOLV_FAIL(result)) { + if(cache_dns && negative) + Curl_dnscache_add_negative(data, dns_queries, peer); + if(dns_queries & (CURL_DNSQ_A | CURL_DNSQ_AAAA)) + failf(data, "Could not resolve: %s:%u", peer->hostname, peer->port); + } + else { + failf(data, "Error %d resolving %s:%u", + (int)result, peer->hostname, peer->port); + } + } + else if(cache_dns && *pdns) { + result = Curl_dnscache_add(data, *pdns); + if(result) + Curl_dns_entry_unlink(data, pdns); + } + + return result; +} + +CURLcode Curl_resolv_blocking(struct Curl_easy *data, + uint8_t dns_queries, + const char *hostname, + uint16_t port, + uint8_t transport, + struct Curl_dns_entry **pdns) +{ + struct Curl_peer *peer = NULL; + CURLcode result; + uint32_t resolv_id; + + DEBUGASSERT(hostname && *hostname); + *pdns = NULL; + + result = Curl_peer_create(data, data->conn->scheme, hostname, port, &peer); + if(result) + goto out; + + /* We cannot do a blocking resolve using DoH currently */ + result = hostip_resolv(data, dns_queries, peer, transport, FALSE, 0, FALSE, + &resolv_id, pdns); + switch(result) { + case CURLE_OK: + DEBUGASSERT(*pdns); + break; +#ifdef USE_CURL_ASYNC + case CURLE_AGAIN: + DEBUGASSERT(!*pdns); + result = Curl_async_await(data, resolv_id, pdns); + Curl_resolv_destroy(data, resolv_id); + break; +#endif + default: + break; + } + +out: + Curl_peer_unlink(&peer); + return result; +} + +#ifdef USE_ALARM_TIMEOUT +/* + * This signal handler jumps back into the main libcurl code and continues + * execution. This effectively causes the remainder of the application to run + * within a signal handler which is nonportable and could lead to problems. + */ +CURL_NORETURN static void alarmfunc(int sig) +{ + (void)sig; + siglongjmp(curl_jmpenv, 1); +} + +static CURLcode resolv_alarm_timeout(struct Curl_easy *data, + uint8_t dns_queries, + struct Curl_peer *peer, + uint8_t transport, + bool for_proxy, + timediff_t timeout_ms, + uint32_t *presolv_id, + struct Curl_dns_entry **entry) +{ +#ifdef HAVE_SIGACTION + struct sigaction keep_sigact; /* store the old struct here */ + volatile bool keep_copysig = FALSE; /* whether old sigact has been saved */ + struct sigaction sigact; +#else +#ifdef HAVE_SIGNAL + void (*keep_sigact)(int); /* store the old handler here */ +#endif /* HAVE_SIGNAL */ +#endif /* HAVE_SIGACTION */ + volatile long timeout; + volatile unsigned int prev_alarm = 0; + CURLcode result; + + DEBUGASSERT(peer->hostname && *peer->hostname); + DEBUGASSERT(timeout_ms > 0); + DEBUGASSERT(!data->set.no_signal); +#ifndef CURL_DISABLE_DOH + DEBUGASSERT(!data->set.doh); +#endif + + *entry = NULL; + timeout = (timeout_ms > LONG_MAX) ? LONG_MAX : (long)timeout_ms; + if(timeout < 1000) { + /* The alarm() function only provides integer second resolution, so if + we want to wait less than one second we must bail out already now. */ + failf(data, + "remaining timeout of %ld too small to resolve via SIGALRM method", + timeout); + return CURLE_OPERATION_TIMEDOUT; + } + /* This allows us to time-out from the name resolver, as the timeout + will generate a signal and we will siglongjmp() from that here. + This technique has problems (see alarmfunc). + This should be the last thing we do before calling Curl_resolv(), + as otherwise we would have to worry about variables that get modified + before we invoke Curl_resolv() (and thus use "volatile"). */ + curl_simple_lock_lock(&curl_jmpenv_lock); + + if(sigsetjmp(curl_jmpenv, 1)) { + /* this is coming from a siglongjmp() after an alarm signal */ + failf(data, "name lookup timed out"); + result = CURLE_OPERATION_TIMEDOUT; + goto clean_up; + } + else { + /************************************************************* + * Set signal handler to catch SIGALRM + * Store the old value to be able to set it back later! + *************************************************************/ +#ifdef HAVE_SIGACTION + sigaction(SIGALRM, NULL, &sigact); + keep_sigact = sigact; + keep_copysig = TRUE; /* yes, we have a copy */ + sigact.sa_handler = alarmfunc; +#ifdef SA_RESTART + /* HP-UX does not have SA_RESTART but defaults to that behavior! */ + sigact.sa_flags &= ~SA_RESTART; +#endif + /* now set the new struct */ + sigaction(SIGALRM, &sigact, NULL); +#else /* HAVE_SIGACTION */ + /* no sigaction(), revert to the much lamer signal() */ +#ifdef HAVE_SIGNAL + keep_sigact = signal(SIGALRM, alarmfunc); +#endif +#endif /* HAVE_SIGACTION */ + + /* alarm() makes a signal get sent when the timeout fires off, and that + will abort system calls */ + prev_alarm = alarm(curlx_sltoui(timeout / 1000L)); + } + + /* Perform the actual name resolution. This might be interrupted by an + * alarm if it takes too long. */ + result = hostip_resolv(data, dns_queries, peer, transport, + for_proxy, timeout_ms, FALSE, presolv_id, entry); + +clean_up: + if(!prev_alarm) + /* deactivate a possibly active alarm before uninstalling the handler */ + alarm(0); + +#ifdef HAVE_SIGACTION + if(keep_copysig) { + /* we got a struct as it looked before, now put that one back nice + and clean */ + sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */ + } +#else +#ifdef HAVE_SIGNAL + /* restore the previous SIGALRM handler */ + signal(SIGALRM, keep_sigact); +#endif +#endif /* HAVE_SIGACTION */ + + curl_simple_lock_unlock(&curl_jmpenv_lock); + + /* switch back the alarm() to either zero or to what it was before minus + the time we spent until now! */ + if(prev_alarm) { + /* there was an alarm() set before us, now put it back */ + timediff_t elapsed_secs = curlx_ptimediff_ms(Curl_pgrs_now(data), + &data->conn->created) / 1000; + + /* the alarm period is counted in even number of seconds */ + unsigned long alarm_set = (unsigned long)(prev_alarm - elapsed_secs); + + if(!alarm_set || + ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000))) { + /* if the alarm time-left reached zero or turned "negative" (counted + with unsigned values), we should fire off a SIGALRM here, but we + will not, and zero would be to switch it off so we never set it to + less than 1! */ + alarm(1); + result = CURLE_OPERATION_TIMEDOUT; + failf(data, "Previous alarm fired off"); + } + else + alarm((unsigned int)alarm_set); + } + + return result; +} + +#endif /* USE_ALARM_TIMEOUT */ + +#ifdef USE_UNIX_SOCKETS +static CURLcode resolv_unix(struct Curl_easy *data, + struct Curl_peer *peer, + struct Curl_dns_entry **pdns) +{ + struct Curl_addrinfo *addr; + CURLcode result; + + DEBUGASSERT(peer->unix_socket); + *pdns = NULL; + + result = Curl_unix2addr(peer->hostname, (bool)peer->abstract_uds, &addr); + if(result) { + if(result == CURLE_TOO_LARGE) { + /* Long paths are not supported for now */ + failf(data, "Unix socket path too long: '%s'", peer->hostname); + result = CURLE_COULDNT_RESOLVE_HOST; + } + return result; + } + + *pdns = Curl_dnsc_mk_addr(data, 0, &addr, peer); + return *pdns ? CURLE_OK : CURLE_OUT_OF_MEMORY; +} +#endif /* USE_UNIX_SOCKETS */ + +/* + * Curl_resolv() is the main name resolve function within libcurl. It resolves + * a name and returns a pointer to the entry in the 'entry' argument. This + * function might return immediately if we are using asynch resolves. See the + * return codes. + * + * The cache entry we return will get its 'inuse' counter increased when this + * function is used. You MUST call Curl_dns_entry_unlink() later (when you are + * done using this struct) to decrease the reference counter again. + * + * If built with a synchronous resolver and use of signals is not + * disabled by the application, then a nonzero timeout will cause a + * timeout after the specified number of milliseconds. Otherwise, timeout + * is ignored. + * + * Return codes: + * CURLE_OK = success, *pdns set to non-NULL + * CURLE_AGAIN = resolving in progress, *pdns == NULL + * any other CURLcode error, *pdns == NULL + */ +CURLcode Curl_resolv(struct Curl_easy *data, + struct Curl_peer *peer, + uint8_t dns_queries, + uint8_t transport, + bool for_proxy, + timediff_t timeout_ms, + uint32_t *presolv_id, + struct Curl_dns_entry **pdns) +{ + *presolv_id = 0; + *pdns = NULL; + + if(timeout_ms < 0) + /* got an already expired timeout */ + return CURLE_OPERATION_TIMEDOUT; + else if(!timeout_ms) + timeout_ms = CURL_TIMEOUT_RESOLVE_MS; + +#ifdef USE_UNIX_SOCKETS + if((dns_queries & CURL_DNSQ_ADDR) && peer->unix_socket) + return resolv_unix(data, peer, pdns); +#else + if(peer->unix_socket) + return hostip_resolv_failed(data, peer, for_proxy); +#endif + +#ifdef USE_ALARM_TIMEOUT + if(dns_queries & CURL_DNSQ_ADDR) { + if(timeout_ms && data->set.no_signal) { + /* Cannot use ALARM when signals are disabled */ + timeout_ms = 0; + } + if(timeout_ms && !Curl_doh_wanted(data)) { + return resolv_alarm_timeout(data, dns_queries, peer, transport, + for_proxy, timeout_ms, presolv_id, pdns); + } + } +#endif /* !USE_ALARM_TIMEOUT */ + +#ifndef CURLRES_ASYNCH + if(timeout_ms) + infof(data, "timeout on name lookup is not supported"); +#endif + + return hostip_resolv(data, dns_queries, peer, transport, + for_proxy, timeout_ms, TRUE, presolv_id, pdns); +} + +#ifdef USE_CURL_ASYNC + +struct Curl_resolv_async *Curl_async_get(struct Curl_easy *data, + uint32_t resolv_id) +{ + struct Curl_resolv_async *async = data->state.async; + for(; async; async = async->next) { + if(async->id == resolv_id) + return async; + } + return NULL; +} + +CURLcode Curl_resolv_take_result(struct Curl_easy *data, uint32_t resolv_id, + struct Curl_dns_entry **pdns) +{ + struct Curl_resolv_async *async = Curl_async_get(data, resolv_id); + CURLcode result; + + /* If async resolving is ongoing, this must be set */ + if(!async) + return CURLE_FAILED_INIT; + + /* check if we have the name resolved by now (from someone else) */ + result = Curl_dnscache_get(data, async->dns_queries, async->peer, pdns); + if(*pdns) { + /* Tell a possibly async resolver we no longer need the results. */ + infof(data, "Hostname '%s' was found in DNS cache", async->peer->hostname); + Curl_async_shutdown(data, async); + return CURLE_OK; + } + else if(result) { + Curl_async_shutdown(data, async); + return Curl_async_failed(data, async, NULL); + } + + result = hostip_resolv_take_result(data, async, pdns); + + if(*pdns) { + /* Add to cache */ + result = Curl_dnscache_add(data, *pdns); + if(result) + Curl_dns_entry_unlink(data, pdns); + } + else if(IS_RESOLV_FAIL(result)) { + /* Only cache the failure when the resolver answered that the + name does not exist. Transient failures, e.g. an unreachable + or overloaded DNS server or local resource shortages, say + nothing about the name and would poison the cache for every + transfer using it. */ + if(async->negative_answer) + Curl_dnscache_add_negative(data, async->dns_queries, async->peer); + if(async->dns_queries & (CURL_DNSQ_A | CURL_DNSQ_AAAA)) + failf(data, "Could not resolve: %s:%u", + async->peer->hostname, async->peer->port); + } + else if(result) { + failf(data, "Error %d resolving %s:%u", + (int)result, async->peer->hostname, async->peer->port); + } + return result; +} + +CURLcode Curl_resolv_pollset(struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct Curl_resolv_async *async = data->state.async; + CURLcode result = CURLE_OK; + + (void)ps; + for(; async && !result; async = async->next) { +#ifndef CURL_DISABLE_DOH + if(async->doh) /* DoH has nothing for the pollset */ + continue; +#endif + result = Curl_async_pollset(data, async, ps); + } + return result; +} + +void Curl_resolv_destroy(struct Curl_easy *data, uint32_t resolv_id) +{ + struct Curl_resolv_async **panchor = &data->state.async; + + for(; *panchor; panchor = &(*panchor)->next) { + struct Curl_resolv_async *async = *panchor; + if(async->id == resolv_id) { + *panchor = async->next; + Curl_async_destroy(data, async); + break; + } + } +} + +void Curl_resolv_shutdown_all(struct Curl_easy *data) +{ + struct Curl_resolv_async *async = data->state.async; + for(; async; async = async->next) { + Curl_async_shutdown(data, async); + } +} + +void Curl_resolv_destroy_all(struct Curl_easy *data) +{ + while(data->state.async) { + struct Curl_resolv_async *async = data->state.async; + data->state.async = async->next; + Curl_async_destroy(data, async); + } +} + +#endif /* USE_CURL_ASYNC */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/hostip.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/hostip.h new file mode 100644 index 0000000000..43172101f2 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/hostip.h @@ -0,0 +1,204 @@ +#ifndef HEADER_CURL_HOSTIP_H +#define HEADER_CURL_HOSTIP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#include "hash.h" +#include "curlx/timeval.h" /* for curltime, timediff_t */ + +/* Allocate enough memory to hold the full name information structs and + * everything. OSF1 is known to require at least 8872 bytes. The buffer + * required for storing all possible aliases and IP numbers is according to + * Stevens' Unix Network Programming 2nd edition, p. 304: 8192 bytes! + */ +#define CURL_HOSTENT_SIZE 9000 + +#define CURL_TIMEOUT_RESOLVE_MS (300 * 1000) + +struct addrinfo; +struct hostent; +struct Curl_easy; +struct connectdata; +struct easy_pollset; +struct Curl_https_rrinfo; +struct Curl_multi; +struct Curl_dns_entry; +struct Curl_peer; + +/* DNS query types */ +#define CURL_DNSQ_A (1U << 0) +#define CURL_DNSQ_AAAA (1U << 1) +#define CURL_DNSQ_HTTPS (1U << 2) + +#define CURL_DNSQ_ADDR (uint8_t)(CURL_DNSQ_A | CURL_DNSQ_AAAA) +#define CURL_DNSQ_IS_ADDR(x) (uint8_t)((x)&(CURL_DNSQ_ADDR)) + +#ifdef CURLVERBOSE +const char *Curl_resolv_query_str(uint8_t dns_queries); +#endif + +/* Return CURL_DNSQ_* bits for the transfer and ip_version. */ +uint8_t Curl_resolv_dns_queries(struct Curl_easy *data, uint8_t ip_version); + +enum alpnid { + ALPN_none = 0, + ALPN_h1 = CURLALTSVC_H1, + ALPN_h2 = CURLALTSVC_H2, + ALPN_h3 = CURLALTSVC_H3 +}; + +bool Curl_host_is_ipnum(const char *hostname); + +#ifdef USE_IPV6 +/* probe if it seems to work */ +CURLcode Curl_probeipv6(struct Curl_multi *multi); +#else +#define Curl_probeipv6(x) CURLE_OK +#endif + +/* IPv4 thread-safe resolve function used for synch and asynch builds */ +struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname, uint16_t port); + +/* + * Curl_printable_address() returns a printable version of the 1st address + * given in the 'ai' argument. The result will be stored in the buf that is + * bufsize bytes big. + */ +void Curl_printable_address(const struct Curl_addrinfo *ai, + char *buf, size_t bufsize); + +/* Start DNS resolving for the given parameters. Returns + * - CURLE_OK: `*pdns` is the resolved DNS entry (needs to be unlinked). + * `*presolv_id` is 0. + * - CURLE_AGAIN: resolve is asynchronous and not finished yet. + * `presolv_id` is the identifier for querying results later. + * - other: the operation failed, `*pdns` is NULL, `*presolv_id` is 0. + */ +CURLcode Curl_resolv(struct Curl_easy *data, + struct Curl_peer *peer, + uint8_t dns_queries, + uint8_t transport, + bool for_proxy, + timediff_t timeout_ms, + uint32_t *presolv_id, + struct Curl_dns_entry **pdns); + +CURLcode Curl_resolv_blocking(struct Curl_easy *data, + uint8_t dns_queries, + const char *hostname, + uint16_t port, + uint8_t transport, + struct Curl_dns_entry **pdns); + +/* Announce start of a resolve operation to application callback, + * passing the resolver implementation (maybe NULL). */ +CURLcode Curl_resolv_announce_start(struct Curl_easy *data, + void *resolver); + +#ifdef USE_CURL_ASYNC + +CURLcode Curl_resolv_pollset(struct Curl_easy *data, + struct easy_pollset *ps); + +/* Get the `async` struct for the given `resolv_id`, if it exists. */ +struct Curl_resolv_async *Curl_async_get(struct Curl_easy *data, + uint32_t resolv_id); + +/* Shut down all resolves of the given easy handle. */ +void Curl_resolv_shutdown_all(struct Curl_easy *data); + +/* Destroy all resolve resources of the given easy handle. */ +void Curl_resolv_destroy_all(struct Curl_easy *data); + +CURLcode Curl_resolv_take_result(struct Curl_easy *data, uint32_t resolv_id, + struct Curl_dns_entry **pdns); + +void Curl_resolv_destroy(struct Curl_easy *data, uint32_t resolv_id); + +/* How much time has gone by since start of resolve. + * Returns CURL_TIMEOUT_RESOLVE_MS if `resolv_id` is no longer valid. */ +timediff_t Curl_resolv_elapsed_ms(struct Curl_easy *data, + uint32_t resolv_id, + const struct curltime *pnow); + +/* Return TRUE if `resolv_id` has answers (positive or negative) to + * all queries in `dns_queries`. + * Queries not requested are considered answered. */ +bool Curl_resolv_has_answers(struct Curl_easy *data, + uint32_t resolv_id, uint8_t dns_queries); + +const struct Curl_addrinfo *Curl_resolv_get_ai(struct Curl_easy *data, + uint32_t resolv_id, + int ai_family, + unsigned int index); +#ifdef USE_HTTPSRR + +/* Start DNS resolving for HTTPS records. Returns + * - CURLE_OK: `*pdns` is the resolved DNS entry (needs to be unlinked). + * `*presolv_id` is 0. + * - CURLE_AGAIN: resolve is asynchronous and not finished yet. + * `presolv_id` is the identifier for querying results later. + * - other: the operation failed, `*pdns` is NULL, `*presolv_id` is 0. + */ +CURLcode Curl_resolv_https(struct Curl_easy *data, + struct Curl_peer *peer, + bool for_proxy, + timediff_t timeout_ms, + uint32_t *presolv_id, + struct Curl_dns_entry **pdns); + + +const struct Curl_https_rrinfo *Curl_resolv_get_https(struct Curl_easy *data, + uint32_t resolv_id); +bool Curl_resolv_knows_https(struct Curl_easy *data, uint32_t resolv_id); +#endif /* USE_HTTPSRR */ + +#else /* !USE_CURL_ASYNC */ +#define Curl_resolv_shutdown_all(x) Curl_nop_stmt +#define Curl_resolv_destroy_all(x) Curl_nop_stmt +#define Curl_resolv_take_result(x, y, z) CURLE_NOT_BUILT_IN +#define Curl_resolv_elapsed_ms(x, y, z) CURL_TIMEOUT_RESOLVE_MS +#define Curl_resolv_has_answers(x, y, z) TRUE +#define Curl_resolv_get_ai(x, y, z, a) NULL +#define Curl_resolv_get_https(x, y) NULL +#define Curl_resolv_knows_https(x, y) TRUE +#define Curl_resolv_pollset(x, y) CURLE_OK +#define Curl_resolv_destroy(x, y) Curl_nop_stmt +#endif /* USE_CURL_ASYNC */ + +#ifdef CURLRES_SYNCH +/* + * Curl_sync_getaddrinfo() is the non-async low-level name resolve API. + * There are several versions of this function - depending on IPV6 + * support and platform. + */ +struct Curl_addrinfo *Curl_sync_getaddrinfo(struct Curl_easy *data, + uint8_t dns_queries, + const char *hostname, + uint16_t port, + uint8_t transport); +#endif + +#endif /* HEADER_CURL_HOSTIP_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/hostip4.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/hostip4.c new file mode 100644 index 0000000000..83896a82b2 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/hostip4.c @@ -0,0 +1,283 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/*********************************************************************** + * Only for plain IPv4 builds + **********************************************************************/ +#ifdef CURLRES_IPV4 /* plain IPv4 code coming up */ + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include "urldata.h" +#include "curl_addrinfo.h" +#include "curl_trc.h" +#include "vdns/hostip.h" +#include "url.h" + + +#ifdef CURLRES_SYNCH + +/* + * Curl_sync_getaddrinfo() - the IPv4 synchronous version. + * + * The original code to this function was from the Dancer source code, written + * by Bjorn Reese, it has since been patched and modified considerably. + * + * gethostbyname_r() is the thread-safe version of the gethostbyname() + * function. When we build for plain IPv4, we attempt to use this + * function. There are _three_ different gethostbyname_r() versions, and we + * detect which one this platform supports in the configure script and set up + * the HAVE_GETHOSTBYNAME_R_3, HAVE_GETHOSTBYNAME_R_5 or + * HAVE_GETHOSTBYNAME_R_6 defines accordingly. Note that HAVE_GETADDRBYNAME + * has the corresponding rules. This is primarily on *nix. Note that some Unix + * flavors have thread-safe versions of the plain gethostbyname() etc. + * + */ +struct Curl_addrinfo *Curl_sync_getaddrinfo(struct Curl_easy *data, + uint8_t dns_queries, + const char *hostname, + uint16_t port, + uint8_t transport) +{ + struct Curl_addrinfo *ai = NULL; + + (void)dns_queries; + (void)transport; + + ai = Curl_ipv4_resolve_r(hostname, port); + if(!ai) + infof(data, "Curl_ipv4_resolve_r failed for %s", hostname); + + return ai; +} +#endif /* CURLRES_SYNCH */ +#endif /* CURLRES_IPV4 */ + +#if defined(CURLRES_IPV4) && !defined(USE_RESOLV_ARES) && \ + !defined(CURLRES_AMIGA) + +/* + * Curl_ipv4_resolve_r() - IPv4 thread-safe resolver function. + * + * This is used for both synchronous and asynchronous resolver builds, + * implying that only thread-safe code and function calls may be used. + * + */ +struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname, + uint16_t port) +{ +#if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETADDRINFO_THREADSAFE)) && \ + defined(HAVE_GETHOSTBYNAME_R_3) + int res; +#endif + struct Curl_addrinfo *ai = NULL; +#if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETADDRINFO_THREADSAFE)) + struct hostent *h = NULL; + struct hostent *buf = NULL; +#endif + +#if defined(HAVE_GETADDRINFO) && defined(HAVE_GETADDRINFO_THREADSAFE) + struct addrinfo hints; + char sbuf[12]; + char *sbufptr = NULL; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = PF_INET; + hints.ai_socktype = SOCK_STREAM; + if(port) { + curl_msnprintf(sbuf, sizeof(sbuf), "%d", port); + sbufptr = sbuf; + } + + (void)Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &ai); + +#elif defined(HAVE_GETHOSTBYNAME_R) + /* + * gethostbyname_r() is the preferred resolve function for many platforms. + * Since there are three different versions of it, the following code is + * somewhat #ifdef-ridden. + */ + int h_errnop; + + buf = curlx_calloc(1, CURL_HOSTENT_SIZE); + if(!buf) + return NULL; /* major failure */ + /* + * The clearing of the buffer is a workaround for a gethostbyname_r bug in + * QNX Neutrino and it is also _required_ for some of these functions on some + * platforms. + */ + +#ifdef HAVE_GETHOSTBYNAME_R_5 + /* Solaris, IRIX and more */ + h = gethostbyname_r(hostname, + (struct hostent *)buf, + (char *)buf + sizeof(struct hostent), + CURL_HOSTENT_SIZE - sizeof(struct hostent), + &h_errnop); + + /* If the buffer is too small, it returns NULL and sets errno to + * ERANGE. The errno is thread-safe if this is compiled with + * -D_REENTRANT as then the 'errno' variable is a macro defined to get + * used properly for threads. + */ + + if(h) { + ; + } + else +#elif defined(HAVE_GETHOSTBYNAME_R_6) + /* Linux */ + + (void)gethostbyname_r(hostname, + (struct hostent *)buf, + (char *)buf + sizeof(struct hostent), + CURL_HOSTENT_SIZE - sizeof(struct hostent), + &h, /* DIFFERENCE */ + &h_errnop); + /* Redhat 8, using glibc 2.2.93 changed the behavior. Now all of a + * sudden this function returns EAGAIN if the given buffer size is too + * small. Previous versions are known to return ERANGE for the same + * problem. + * + * This would not be such a big problem if older versions would not + * sometimes return EAGAIN on a common failure case. Alas, we cannot + * assume that EAGAIN *or* ERANGE means ERANGE for any given version of + * glibc. + * + * For now, we do that and thus we may call the function repeatedly and + * fail for older glibc versions that return EAGAIN, until we run out of + * buffer size (step_size grows beyond CURL_HOSTENT_SIZE). + * + * If anyone has a better fix, please tell us! + * + * ------------------------------------------------------------------- + * + * On October 23rd 2003, Dan C dug up more details on the mysteries of + * gethostbyname_r() in glibc: + * + * In glibc 2.2.5 the interface is different (this has also been + * discovered in glibc 2.1.1-6 as shipped by Redhat 6). What I cannot + * explain, is that tests performed on glibc 2.2.4-34 and 2.2.4-32 + * (shipped/upgraded by Redhat 7.2) do not show this behavior! + * + * In this "buggy" version, the return code is -1 on error and 'errno' + * is set to the ERANGE or EAGAIN code. Note that 'errno' is not a + * thread-safe variable. + */ + + if(!h) /* failure */ +#elif defined(HAVE_GETHOSTBYNAME_R_3) + /* AIX, Digital UNIX/Tru64, HP-UX 10, more? */ + + /* For AIX 4.3 or later, we do not use gethostbyname_r() at all, because of + * the plain fact that it does not return unique full buffers on each + * call, but instead several of the pointers in the hostent structs will + * point to the same actual data! This have the unfortunate down-side that + * our caching system breaks down horribly. Luckily for us though, AIX 4.3 + * and more recent versions have a "completely thread-safe"[*] libc where + * all the data is stored in thread-specific memory areas making calls to + * the plain old gethostbyname() work fine even for multi-threaded + * programs. + * + * This AIX 4.3 or later detection is all made in the configure script. + * + * Troels Walsted Hansen helped us work this out on March 3rd, 2003. + * + * [*] = much later we have found out that it is not at all "completely + * thread-safe", but at least the gethostbyname() function is. + */ + + if(CURL_HOSTENT_SIZE >= + (sizeof(struct hostent) + sizeof(struct hostent_data))) { + + /* August 22nd, 2000: Albert Chin-A-Young brought an updated version + * that should work! September 20: Richard Prescott worked on the buffer + * size dilemma. + */ + + res = gethostbyname_r(hostname, + (struct hostent *)buf, + (struct hostent_data *)((char *)buf + + sizeof(struct hostent))); + h_errnop = SOCKERRNO; /* we do not deal with this, but set it anyway */ + } + else + res = -1; /* failure, too smallish buffer size */ + + if(!res) { /* success */ + + h = buf; /* result expected in h */ + + /* This is the worst kind of the different gethostbyname_r() interfaces. + * Since we do not know how big buffer this particular lookup required, + * we cannot realloc down the huge alloc without doing closer analysis of + * the returned data. Thus, we always use CURL_HOSTENT_SIZE for every + * name lookup. Fixing this would require an extra allocation and then + * calling Curl_addrinfo_copy() that subsequent reallocation down the new + * memory area to the actually used amount. + */ + } + else +#endif /* HAVE_...BYNAME_R_5 || HAVE_...BYNAME_R_6 || HAVE_...BYNAME_R_3 */ + { + h = NULL; /* set return code to NULL */ + curlx_free(buf); + } +#else /* (HAVE_GETADDRINFO && HAVE_GETADDRINFO_THREADSAFE) || + HAVE_GETHOSTBYNAME_R */ + /* + * Here is code for platforms that do not have a thread-safe + * getaddrinfo() nor gethostbyname_r() function or for which + * gethostbyname() is the preferred one. + */ + h = gethostbyname(CURL_UNCONST(hostname)); +#endif /* (HAVE_GETADDRINFO && HAVE_GETADDRINFO_THREADSAFE) || + HAVE_GETHOSTBYNAME_R */ + +#if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETADDRINFO_THREADSAFE)) + if(h) { + ai = Curl_he2ai(h, port); + + if(buf) /* used a *_r() function */ + curlx_free(buf); + } +#endif + + return ai; +} +#endif /* CURLRES_IPV4 && !USE_RESOLV_ARES && !CURLRES_AMIGA */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/hostip6.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/hostip6.c new file mode 100644 index 0000000000..e33a154d2f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/hostip6.c @@ -0,0 +1,120 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/*********************************************************************** + * Only for IPv6-enabled builds + **********************************************************************/ +#ifdef CURLRES_IPV6 + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include "urldata.h" +#include "cfilters.h" +#include "curl_addrinfo.h" +#include "curl_trc.h" +#include "url.h" +#include "vdns/hostip.h" +#include "curlx/inet_pton.h" +#include "connect.h" + +#ifdef CURLRES_SYNCH + +/* + * Curl_sync_getaddrinfo() when built IPv6-enabled (non-threading and + * non-ares version). + * + * Returns name information about the given hostname and port number. If + * successful, the 'addrinfo' is returned and the fourth argument will point + * to memory we need to free after use. That memory *MUST* be freed with + * Curl_freeaddrinfo(), nothing else. + */ +struct Curl_addrinfo *Curl_sync_getaddrinfo(struct Curl_easy *data, + uint8_t dns_queries, + const char *hostname, + uint16_t port, + uint8_t transport) +{ + struct addrinfo hints; + struct Curl_addrinfo *res; + int error; + char sbuf[12]; + char *sbufptr = NULL; +#ifndef USE_RESOLVE_ON_IPS + char addrbuf[128]; +#endif + int pf = PF_INET; + + if(dns_queries & CURL_DNSQ_AAAA) + pf = PF_UNSPEC; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = pf; + hints.ai_socktype = (transport == TRNSPRT_TCP) ? + SOCK_STREAM : SOCK_DGRAM; + +#ifndef USE_RESOLVE_ON_IPS + /* + * The AI_NUMERICHOST must not be set to get synthesized IPv6 address from + * an IPv4 address on iOS and macOS. + */ + if((curlx_inet_pton(AF_INET, hostname, addrbuf) == 1) || + (curlx_inet_pton(AF_INET6, hostname, addrbuf) == 1)) { + /* the given address is numerical only, prevent a reverse lookup */ + hints.ai_flags = AI_NUMERICHOST; + } +#endif + + if(port) { + curl_msnprintf(sbuf, sizeof(sbuf), "%d", port); + sbufptr = sbuf; + } + + error = Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &res); + if(error) { + infof(data, "getaddrinfo(3) failed for %s:%d", hostname, port); + return NULL; + } + + if(port) { + Curl_addrinfo_set_port(res, port); + } + + return res; +} +#endif /* CURLRES_SYNCH */ + +#endif /* CURLRES_IPV6 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/httpsrr.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/httpsrr.c new file mode 100644 index 0000000000..98a3c89496 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/httpsrr.c @@ -0,0 +1,316 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_HTTPSRR + +#include "urldata.h" +#include "connect.h" +#include "curl_trc.h" +#include "vdns/httpsrr.h" +#include "curlx/strdup.h" +#include "curlx/inet_ntop.h" + +static CURLcode httpsrr_decode_alpn(const uint8_t *cp, size_t len, + unsigned char *alpns) +{ + /* + * The wire-format value for "alpn" consists of at least one alpn-id + * prefixed by its length as a single octet, and these length-value pairs + * are concatenated to form the SvcParamValue. These pairs MUST exactly fill + * the SvcParamValue; otherwise, the SvcParamValue is malformed. + */ + int idnum = 0; + + while(len > 0) { + size_t tlen = *cp++; + enum alpnid id; + len--; + if(tlen > len) + return CURLE_BAD_CONTENT_ENCODING; + + /* we only store ALPN ids we know about */ + id = Curl_alpn2alpnid(cp, tlen); + if(id != ALPN_none) { + if(idnum == MAX_HTTPSRR_ALPNS) + break; + if(idnum && memchr(alpns, id, idnum)) + /* this ALPN id is already stored */ + ; + else + alpns[idnum++] = (unsigned char)id; + } + cp += tlen; + len -= tlen; + } + if(idnum < MAX_HTTPSRR_ALPNS) + alpns[idnum] = ALPN_none; /* terminate the list */ + return CURLE_OK; +} + +#ifdef CURLVERBOSE + +static CURLcode httpsrr_print_addr(struct dynbuf *dyn, + int ai_family, + const uint8_t *addr, + size_t total_len) +{ + char buf[MAX_IPADR_LEN]; + size_t i, alen = (ai_family == AF_INET6) ? 16 : 4; + const char *sep = ""; + CURLcode result = CURLE_OK; + + for(i = 0; (i < (total_len / alen)) && !result; ++i) { + if(curlx_inet_ntop(ai_family, addr + (i * alen), buf, sizeof(buf))) + result = curlx_dyn_add(dyn, "<error parsing address>"); + else + result = curlx_dyn_addf(dyn, "%s%s", sep, buf); + sep = ","; + } + return result; +} + +void Curl_httpsrr_trace(struct Curl_easy *data, + struct Curl_https_rrinfo *rr) +{ + struct dynbuf tmp; + CURLcode result; + + if(!rr) { + CURL_TRC_DNS(data, "[HTTPS] no record available"); + return; + } + curlx_dyn_init(&tmp, 1024); + result = Curl_httpsrr_print(&tmp, rr); + if(!result) + CURL_TRC_DNS(data, "[HTTPS] record: %s", curlx_dyn_ptr(&tmp)); + else + CURL_TRC_DNS(data, "[HTTPS] error printing information"); + curlx_dyn_free(&tmp); +} + +CURLcode Curl_httpsrr_print(struct dynbuf *tmp, + struct Curl_https_rrinfo *rr) +{ + CURLcode result; + int i; + + curlx_dyn_reset(tmp); + result = curlx_dyn_addf(tmp, "%u %s", rr->priority, + rr->target ? rr->target : "."); + if(!result && rr->mandatory) + result = curlx_dyn_add(tmp, " mandatory-keys(ignored)"); + if(!result && rr->alpns[0]) { + const char *sep = "", *name; + result = curlx_dyn_add(tmp, " alpn="); + for(i = 0; !result && (i < 4); ++i) { + switch(rr->alpns[i]) { + case ALPN_h1: + name = "http/1.1"; + break; + case ALPN_h2: + name = "h2"; + break; + case ALPN_h3: + name = "h3"; + break; + default: + name = NULL; + } + if(name) { + result = curlx_dyn_addf(tmp, "%s%s", sep, name); + sep = ","; + } + } + } + if(!result && rr->port_set) { + result = curlx_dyn_addf(tmp, " port=%u", rr->port); + } + if(!result && rr->no_def_alpn) + result = curlx_dyn_add(tmp, " no-default-alpn"); + if(!result && rr->ipv6hints_len) { + result = curlx_dyn_add(tmp, " ipv6hint="); + if(!result) + result = httpsrr_print_addr( + tmp, AF_INET6, rr->ipv6hints, rr->ipv6hints_len); + } + if(!result && rr->ipv4hints_len) { + result = curlx_dyn_add(tmp, " ipv4hint="); + if(!result) + result = httpsrr_print_addr( + tmp, AF_INET, rr->ipv4hints, rr->ipv4hints_len); + } + if(!result && rr->echconfiglist_len) + result = curlx_dyn_addf(tmp, " ech=<%zu bytes>", rr->echconfiglist_len); + + return result; +} + +#endif /* CURLVERBOSE */ + +CURLcode Curl_httpsrr_set(struct Curl_https_rrinfo *rr, + uint16_t rrkey, const uint8_t *val, size_t vlen) +{ + CURLcode result = CURLE_OK; + switch(rrkey) { + case HTTPS_RR_CODE_MANDATORY: + rr->mandatory = TRUE; + break; + case HTTPS_RR_CODE_ALPN: /* str_list */ + result = httpsrr_decode_alpn(val, vlen, rr->alpns); + break; + case HTTPS_RR_CODE_NO_DEF_ALPN: + if(vlen) /* no data */ + return CURLE_BAD_FUNCTION_ARGUMENT; + rr->no_def_alpn = TRUE; + break; + case HTTPS_RR_CODE_IPV4: /* addr4 list */ + if(!vlen || (vlen & 3)) /* the size must be 4-byte aligned */ + return CURLE_BAD_FUNCTION_ARGUMENT; + curlx_free(rr->ipv4hints); + rr->ipv4hints = curlx_memdup(val, vlen); + if(!rr->ipv4hints) + return CURLE_OUT_OF_MEMORY; + rr->ipv4hints_len = vlen; + break; + case HTTPS_RR_CODE_ECH: + if(!vlen) + return CURLE_BAD_FUNCTION_ARGUMENT; + curlx_free(rr->echconfiglist); + rr->echconfiglist = curlx_memdup(val, vlen); + if(!rr->echconfiglist) + return CURLE_OUT_OF_MEMORY; + rr->echconfiglist_len = vlen; + break; + case HTTPS_RR_CODE_IPV6: /* addr6 list */ + if(!vlen || (vlen & 15)) /* the size must be 16-byte aligned */ + return CURLE_BAD_FUNCTION_ARGUMENT; + curlx_free(rr->ipv6hints); + rr->ipv6hints = curlx_memdup(val, vlen); + if(!rr->ipv6hints) + return CURLE_OUT_OF_MEMORY; + rr->ipv6hints_len = vlen; + break; + case HTTPS_RR_CODE_PORT: + if(vlen != 2) + return CURLE_BAD_FUNCTION_ARGUMENT; + rr->port = (uint16_t)((val[0] << 8) | val[1]); + rr->port_set = TRUE; + break; + default: + /* unknown code */ + break; + } + return result; +} + +void Curl_httpsrr_destroy(struct Curl_https_rrinfo *rrinfo) +{ + if(rrinfo) { + curlx_free(rrinfo->target); + curlx_free(rrinfo->echconfiglist); + curlx_free(rrinfo->ipv4hints); + curlx_free(rrinfo->ipv6hints); + curlx_free(rrinfo); + } +} + +bool Curl_httpsrr_applicable(struct Curl_easy *data, + const struct Curl_https_rrinfo *rr) +{ + if(!data->conn || !rr) + return FALSE; + return (!rr->target || !rr->target[0] || + (rr->target[0] == '.' && !rr->target[1])) && + (!rr->port_set || rr->port == data->conn->origin->port); +} + +#ifdef USE_ARES + +static CURLcode httpsrr_opt(const ares_dns_rr_t *rr, + ares_dns_rr_key_t key, size_t idx, + struct Curl_https_rrinfo *hinfo) +{ + const unsigned char *val = NULL; + unsigned short code; + size_t len = 0; + + code = ares_dns_rr_get_opt(rr, key, idx, &val, &len); + return Curl_httpsrr_set(hinfo, code, val, len); +} + +CURLcode Curl_httpsrr_from_ares(const ares_dns_record_t *dnsrec, + struct Curl_https_rrinfo **phinfo) +{ + struct Curl_https_rrinfo *hinfo = NULL; + CURLcode result = CURLE_OUT_OF_MEMORY; + size_t i; + + hinfo = curlx_calloc(1, sizeof(*hinfo)); + if(!hinfo) + goto out; + + for(i = 0; i < ares_dns_record_rr_cnt(dnsrec, ARES_SECTION_ANSWER); i++) { + const char *target; + size_t opt; + const ares_dns_rr_t *rr = + ares_dns_record_rr_get_const(dnsrec, ARES_SECTION_ANSWER, i); + if(ares_dns_rr_get_type(rr) != ARES_REC_TYPE_HTTPS) + continue; + /* When SvcPriority is 0, the SVCB record is in AliasMode. Otherwise, it + is in ServiceMode */ + target = ares_dns_rr_get_str(rr, ARES_RR_HTTPS_TARGET); + if(target && target[0]) { + curlx_free(hinfo->target); + hinfo->target = curlx_strdup(target); + if(!hinfo->target) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + hinfo->priority = ares_dns_rr_get_u16(rr, ARES_RR_HTTPS_PRIORITY); + for(opt = 0; opt < ares_dns_rr_get_opt_cnt(rr, ARES_RR_HTTPS_PARAMS); + opt++) { + result = httpsrr_opt(rr, ARES_RR_HTTPS_PARAMS, opt, hinfo); + if(result) + goto out; + } + } + result = CURLE_OK; + +out: + if(result) { + *phinfo = NULL; + Curl_httpsrr_destroy(hinfo); + } + else { + DEBUGASSERT(hinfo); + *phinfo = hinfo; + } + return result; +} + +#endif /* USE_ARES */ + +#endif /* USE_HTTPSRR */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/httpsrr.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/httpsrr.h new file mode 100644 index 0000000000..8d6eed1c93 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vdns/httpsrr.h @@ -0,0 +1,97 @@ +#ifndef HEADER_CURL_HTTPSRR_H +#define HEADER_CURL_HTTPSRR_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_ARES +#include <ares.h> +#endif + +#ifdef USE_HTTPSRR + +#define CURL_MAXLEN_HOST_NAME 253 +#define MAX_HTTPSRR_ALPNS 4 + +struct Curl_easy; +struct dynbuf; + +struct Curl_https_rrinfo { + /* + * Fields from HTTPS RR. The only mandatory fields are priority and target. + * See https://datatracker.ietf.org/doc/html/rfc9460#section-14.3.2 + */ + char *target; + unsigned char *ipv4hints; /* keytag = 4 */ + size_t ipv4hints_len; + unsigned char *echconfiglist; /* keytag = 5 */ + size_t echconfiglist_len; + unsigned char *ipv6hints; /* keytag = 6 */ + size_t ipv6hints_len; + unsigned char alpns[MAX_HTTPSRR_ALPNS]; /* keytag = 1 */ + /* store parsed alpnid entries in the array, end with ALPN_none */ + uint16_t port; + uint16_t priority; + BIT(no_def_alpn); /* keytag = 2 */ + BIT(mandatory); /* keytag = 0 */ + BIT(port_set); /* port value has been assigned */ +}; + +CURLcode Curl_httpsrr_set(struct Curl_https_rrinfo *rr, + uint16_t rrkey, const uint8_t *val, size_t vlen); + +void Curl_httpsrr_destroy(struct Curl_https_rrinfo *rrinfo); + +/* TRUE if the record is applicable to the transfer and its connection. */ +bool Curl_httpsrr_applicable(struct Curl_easy *data, + const struct Curl_https_rrinfo *rr); + +/* + * Code points for DNS wire format SvcParams as per RFC 9460 + */ +#define HTTPS_RR_CODE_MANDATORY 0x00 +#define HTTPS_RR_CODE_ALPN 0x01 +#define HTTPS_RR_CODE_NO_DEF_ALPN 0x02 +#define HTTPS_RR_CODE_PORT 0x03 +#define HTTPS_RR_CODE_IPV4 0x04 +#define HTTPS_RR_CODE_ECH 0x05 +#define HTTPS_RR_CODE_IPV6 0x06 + +#ifdef USE_ARES +CURLcode Curl_httpsrr_from_ares(const ares_dns_record_t *dnsrec, + struct Curl_https_rrinfo **phinfo); +#endif /* USE_ARES */ + +#ifdef CURLVERBOSE +CURLcode Curl_httpsrr_print(struct dynbuf *tmp, + struct Curl_https_rrinfo *rr); +void Curl_httpsrr_trace(struct Curl_easy *data, + struct Curl_https_rrinfo *rr); +#else +#define Curl_httpsrr_trace(a, b) Curl_nop_stmt +#endif + +#endif /* USE_HTTPSRR */ + +#endif /* HEADER_CURL_HTTPSRR_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/version.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/version.c new file mode 100644 index 0000000000..c4cdde6377 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/version.c @@ -0,0 +1,681 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_NGHTTP2 +#include <nghttp2/nghttp2.h> +#endif + +#include "urldata.h" +#include "vtls/vtls.h" +#include "http2.h" +#include "vssh/ssh.h" +#include "vquic/vquic.h" +#include "easy_lock.h" + +#ifdef USE_ARES +# include <ares.h> +#endif + +#ifdef USE_LIBIDN2 +#include <idn2.h> +#endif + +#ifdef USE_LIBPSL +#include <libpsl.h> +#endif + +#ifdef HAVE_LIBZ +#include <zlib.h> +#endif + +#ifdef HAVE_BROTLI +#ifdef CURL_HAVE_DIAG +/* Ignore -Wvla warnings in brotli headers */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wvla" +#endif +#include <brotli/decode.h> +#ifdef CURL_HAVE_DIAG +#pragma GCC diagnostic pop +#endif +#endif + +#ifdef HAVE_ZSTD +#include <zstd.h> +#endif + +#ifdef USE_GSASL +#include <gsasl.h> +#endif + +#ifndef CURL_DISABLE_LDAP +#include "curl_ldap.h" +#endif + +#ifdef HAVE_BROTLI +static void brotli_version(char *buf, size_t bufsz) +{ + uint32_t brotli_version = BrotliDecoderVersion(); + unsigned int major = brotli_version >> 24; + unsigned int minor = (brotli_version & 0x00FFFFFF) >> 12; + unsigned int patch = brotli_version & 0x00000FFF; + (void)curl_msnprintf(buf, bufsz, "brotli/%u.%u.%u", major, minor, patch); +} +#endif + +#ifdef HAVE_ZSTD +static void zstd_version(char *buf, size_t bufsz) +{ + unsigned int version = ZSTD_versionNumber(); + unsigned int major = version / (100 * 100); + unsigned int minor = (version - (major * 100 * 100)) / 100; + unsigned int patch = version - (major * 100 * 100) - (minor * 100); + (void)curl_msnprintf(buf, bufsz, "zstd/%u.%u.%u", major, minor, patch); +} +#endif + +#ifdef USE_LIBPSL +static void psl_version(char *buf, size_t bufsz) +{ +#if defined(PSL_VERSION_MAJOR) && (PSL_VERSION_MAJOR > 0 || \ + PSL_VERSION_MINOR >= 11) + int num = psl_check_version_number(0); + curl_msnprintf(buf, bufsz, "libpsl/%d.%d.%d", + num >> 16, (num >> 8) & 0xff, num & 0xff); +#else + curl_msnprintf(buf, bufsz, "libpsl/%s", psl_get_version()); +#endif +} +#endif + +#if defined(USE_LIBIDN2) || defined(USE_WIN32_IDN) || defined(USE_APPLE_IDN) +#define USE_IDN +#endif + +#ifdef USE_IDN +static void idn_version(char *buf, size_t bufsz) +{ +#ifdef USE_LIBIDN2 + curl_msnprintf(buf, bufsz, "libidn2/%s", idn2_check_version(NULL)); +#elif defined(USE_WIN32_IDN) + curl_msnprintf(buf, bufsz, "WinIDN"); +#elif defined(USE_APPLE_IDN) + curl_msnprintf(buf, bufsz, "AppleIDN"); +#endif +} +#endif + +/* + * curl_version() returns a pointer to a static buffer. + * + * It is implemented to work multi-threaded by making sure repeated invokes + * generate the exact same string and never write any temporary data like + * zeros in the data. + */ + +#define VERSION_PARTS 16 /* number of substrings we can concatenate */ + +char *curl_version(void) +{ + static char out[300]; + char *outp; + size_t outlen; + const char *src[VERSION_PARTS]; +#ifdef USE_SSL + char ssl_version[200]; +#endif +#ifdef HAVE_LIBZ + char z_version[30]; +#endif +#ifdef HAVE_BROTLI + char br_version[30]; +#endif +#ifdef HAVE_ZSTD + char zstd_ver[30]; +#endif +#ifdef USE_ARES + char cares_version[30]; +#endif +#ifdef USE_IDN + char idn_ver[30]; +#endif +#ifdef USE_LIBPSL + char psl_ver[30]; +#endif +#ifdef USE_SSH + char ssh_version[30]; +#endif +#if !defined(CURL_DISABLE_HTTP) && defined(USE_NGHTTP2) + char h2_version[30]; +#endif +#if !defined(CURL_DISABLE_HTTP) && defined(USE_HTTP3) + char h3_version[30]; +#endif +#ifdef USE_GSASL + char gsasl_buf[30]; +#endif +#ifdef HAVE_GSSAPI + char gss_buf[40]; +#endif +#ifndef CURL_DISABLE_LDAP + char ldap_buf[30]; +#endif + int i = 0; + int j; + +#ifdef DEBUGBUILD + /* Override version string when environment variable CURL_VERSION is set */ + const char *debugversion = getenv("CURL_VERSION"); + if(debugversion) { + curl_msnprintf(out, sizeof(out), "%s", debugversion); + return out; + } +#endif + + src[i++] = LIBCURL_NAME "/" LIBCURL_VERSION; +#ifdef USE_SSL + Curl_ssl_version(ssl_version, sizeof(ssl_version)); + src[i++] = ssl_version; +#endif +#ifdef HAVE_LIBZ + curl_msnprintf(z_version, sizeof(z_version), "zlib/%s", zlibVersion()); + src[i++] = z_version; +#endif +#ifdef HAVE_BROTLI + brotli_version(br_version, sizeof(br_version)); + src[i++] = br_version; +#endif +#ifdef HAVE_ZSTD + zstd_version(zstd_ver, sizeof(zstd_ver)); + src[i++] = zstd_ver; +#endif +#ifdef USE_ARES + curl_msnprintf(cares_version, sizeof(cares_version), + "c-ares/%s", ares_version(NULL)); + src[i++] = cares_version; +#endif +#ifdef USE_IDN + idn_version(idn_ver, sizeof(idn_ver)); + src[i++] = idn_ver; +#endif +#ifdef USE_LIBPSL + psl_version(psl_ver, sizeof(psl_ver)); + src[i++] = psl_ver; +#endif +#ifdef USE_SSH + Curl_ssh_version(ssh_version, sizeof(ssh_version)); + src[i++] = ssh_version; +#endif +#if !defined(CURL_DISABLE_HTTP) && defined(USE_NGHTTP2) + Curl_http2_ver(h2_version, sizeof(h2_version)); + src[i++] = h2_version; +#endif +#if !defined(CURL_DISABLE_HTTP) && defined(USE_HTTP3) + Curl_quic_ver(h3_version, sizeof(h3_version)); + src[i++] = h3_version; +#endif +#ifdef USE_GSASL + curl_msnprintf(gsasl_buf, sizeof(gsasl_buf), "libgsasl/%s", + gsasl_check_version(NULL)); + src[i++] = gsasl_buf; +#endif +#ifdef HAVE_GSSAPI +#ifdef HAVE_GSSAPPLE + curl_msnprintf(gss_buf, sizeof(gss_buf), "AppleGSS"); +#elif defined(HAVE_GSSGNU) + curl_msnprintf(gss_buf, sizeof(gss_buf), "libgss/%s", GSS_VERSION); +#elif defined(CURL_KRB5_VERSION) + curl_msnprintf(gss_buf, sizeof(gss_buf), "mit-krb5/%s", CURL_KRB5_VERSION); +#else + curl_msnprintf(gss_buf, sizeof(gss_buf), "mit-krb5"); +#endif + src[i++] = gss_buf; +#endif /* HAVE_GSSAPI */ +#ifndef CURL_DISABLE_LDAP + Curl_ldap_version(ldap_buf, sizeof(ldap_buf)); + src[i++] = ldap_buf; +#endif + + DEBUGASSERT(i <= VERSION_PARTS); + + outp = &out[0]; + outlen = sizeof(out); + for(j = 0; j < i; j++) { + size_t n = strlen(src[j]); + /* we need room for a space, the string and the final zero */ + if(outlen <= (n + 2)) + break; + if(j) { + /* prepend a space if not the first */ + *outp++ = ' '; + outlen--; + } + memcpy(outp, src[j], n); + outp += n; + outlen -= n; + } + *outp = 0; + + return out; +} + +/* data for curl_version_info + + Keep the list sorted alphabetically. It is also written so that each + protocol line has its own #if line to make things easier on the eye. + */ + +static const char * const supported_protocols[] = { +#ifndef CURL_DISABLE_DICT + "dict", +#endif +#ifndef CURL_DISABLE_FILE + "file", +#endif +#ifndef CURL_DISABLE_FTP + "ftp", +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_FTP) + "ftps", +#endif +#ifndef CURL_DISABLE_GOPHER + "gopher", +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_GOPHER) + "gophers", +#endif +#ifndef CURL_DISABLE_HTTP + "http", +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP) + "https", +#endif +#ifndef CURL_DISABLE_IMAP + "imap", +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_IMAP) + "imaps", +#endif +#ifndef CURL_DISABLE_LDAP + "ldap", +#if !defined(CURL_DISABLE_LDAPS) && \ + ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \ + (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL))) + "ldaps", +#endif +#endif +#ifndef CURL_DISABLE_MQTT + "mqtt", +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_MQTT) + "mqtts", +#endif +#ifndef CURL_DISABLE_POP3 + "pop3", +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_POP3) + "pop3s", +#endif +#ifndef CURL_DISABLE_RTSP + "rtsp", +#endif +#ifdef USE_SSH + "scp", + "sftp", +#endif +#if defined(CURL_ENABLE_SMB) && defined(USE_CURL_NTLM_CORE) + "smb", +# ifdef USE_SSL + "smbs", +# endif +#endif +#ifndef CURL_DISABLE_SMTP + "smtp", +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_SMTP) + "smtps", +#endif +#ifndef CURL_DISABLE_TELNET + "telnet", +#endif +#ifndef CURL_DISABLE_TFTP + "tftp", +#endif +#ifndef CURL_DISABLE_HTTP + /* WebSocket support relies on HTTP */ +#ifndef CURL_DISABLE_WEBSOCKETS + "ws", +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_WEBSOCKETS) + "wss", +#endif +#endif + + NULL +}; + +/* + * Feature presence runtime check functions. + * + * Warning: the value returned by these should not change between + * curl_global_init() and curl_global_cleanup() calls. + */ + +#if defined(USE_LIBIDN2) || defined(USE_WIN32_IDN) || defined(USE_APPLE_IDN) +static int idn_present(curl_version_info_data *info) +{ +#if defined(USE_WIN32_IDN) || defined(USE_APPLE_IDN) + (void)info; + return TRUE; +#else + return !!info->libidn; +#endif +} +#endif + +#if defined(USE_SSL) && !defined(CURL_DISABLE_PROXY) && \ + !defined(CURL_DISABLE_HTTP) +static int https_proxy_present(curl_version_info_data *info) +{ + (void)info; + return Curl_ssl_supports(NULL, SSLSUPP_HTTPS_PROXY); +} +#endif + +#if defined(USE_SSL) && defined(USE_ECH) +static int ech_present(curl_version_info_data *info) +{ + (void)info; + return Curl_ssl_supports(NULL, SSLSUPP_ECH); +} +#endif + +/* + * Features table. + * + * Keep the features alphabetically sorted. + * Use FEATURE() macro to define an entry: this allows documentation check. + */ + +#define FEATURE(name, present, bitmask) { (name), (present), (bitmask) } + +struct feat { + const char *name; + int (*present)(curl_version_info_data *info); + int bitmask; +}; + +static const struct feat features_table[] = { +#ifndef CURL_DISABLE_ALTSVC + FEATURE("alt-svc", NULL, CURL_VERSION_ALTSVC), +#endif +#if defined(USE_ARES) && defined(USE_RESOLV_THREADED) && defined(USE_HTTPSRR) + FEATURE("asyn-rr", NULL, 0), +#endif +#ifdef CURLRES_ASYNCH + FEATURE("AsynchDNS", NULL, CURL_VERSION_ASYNCHDNS), +#endif +#ifdef HAVE_BROTLI + FEATURE("brotli", NULL, CURL_VERSION_BROTLI), +#endif +#ifdef DEBUGBUILD + FEATURE("Debug", NULL, CURL_VERSION_DEBUG), +#endif +#if defined(USE_SSL) && defined(USE_ECH) + FEATURE("ECH", ech_present, 0), + +#ifndef USE_HTTPSRR +#error "ECH enabled but not HTTPSRR, must be a config error" +#endif +#endif +#ifdef USE_GSASL + FEATURE("gsasl", NULL, CURL_VERSION_GSASL), +#endif +#ifdef HAVE_GSSAPI + FEATURE("GSS-API", NULL, CURL_VERSION_GSSAPI), +#endif +#ifndef CURL_DISABLE_HSTS + FEATURE("HSTS", NULL, CURL_VERSION_HSTS), +#endif +#if !defined(CURL_DISABLE_HTTP) && defined(USE_NGHTTP2) + FEATURE("HTTP2", NULL, CURL_VERSION_HTTP2), +#endif +#if !defined(CURL_DISABLE_HTTP) && defined(USE_HTTP3) + FEATURE("HTTP3", NULL, CURL_VERSION_HTTP3), +#endif +#if defined(USE_SSL) && !defined(CURL_DISABLE_PROXY) && \ + !defined(CURL_DISABLE_HTTP) + FEATURE("HTTPS-proxy", https_proxy_present, CURL_VERSION_HTTPS_PROXY), +#endif +#ifndef CURL_DISABLE_HTTPSIG + FEATURE("HTTPSIG", NULL, 0), +#endif +#ifdef USE_HTTPSRR + FEATURE("HTTPSRR", NULL, 0), +#endif +#if defined(USE_LIBIDN2) || defined(USE_WIN32_IDN) || defined(USE_APPLE_IDN) + FEATURE("IDN", idn_present, CURL_VERSION_IDN), +#endif +#ifdef USE_IPV6 + FEATURE("IPv6", NULL, CURL_VERSION_IPV6), +#endif +#ifdef USE_KERBEROS5 + FEATURE("Kerberos", NULL, CURL_VERSION_KERBEROS5), +#endif +#if (SIZEOF_CURL_OFF_T > 4) && ((SIZEOF_OFF_T > 4) || defined(_WIN32)) + FEATURE("Largefile", NULL, CURL_VERSION_LARGEFILE), +#endif +#ifdef HAVE_LIBZ + FEATURE("libz", NULL, CURL_VERSION_LIBZ), +#endif +#ifdef CURL_WITH_MULTI_SSL + FEATURE("MultiSSL", NULL, CURL_VERSION_MULTI_SSL), +#endif +#ifdef USE_NTLM + FEATURE("NTLM", NULL, CURL_VERSION_NTLM), +#endif +#ifdef USE_PROXY_HTTP3 + FEATURE("proxy-HTTP3", NULL, 0), +#endif +#ifdef USE_LIBPSL + FEATURE("PSL", NULL, CURL_VERSION_PSL), +#endif +#ifdef USE_SSL +#ifdef USE_APPLE_SECTRUST + FEATURE("AppleSecTrust", NULL, 0), +#elif defined(CURL_CA_NATIVE) + FEATURE("NativeCA", NULL, 0), +#endif +#endif /* USE_SSL */ +#ifdef USE_SPNEGO + FEATURE("SPNEGO", NULL, CURL_VERSION_SPNEGO), +#endif +#ifdef USE_SSL + FEATURE("SSL", NULL, CURL_VERSION_SSL), +#endif +#ifdef USE_SSLS_EXPORT + FEATURE("SSLS-EXPORT", NULL, 0), +#endif +#ifdef USE_WINDOWS_SSPI + FEATURE("SSPI", NULL, CURL_VERSION_SSPI), +#endif +#ifdef GLOBAL_INIT_IS_THREADSAFE + FEATURE("threadsafe", NULL, CURL_VERSION_THREADSAFE), +#endif +#if defined(_WIN32) && defined(UNICODE) && defined(_UNICODE) + FEATURE("Unicode", NULL, CURL_VERSION_UNICODE), +#endif +#ifdef USE_UNIX_SOCKETS + FEATURE("UnixSockets", NULL, CURL_VERSION_UNIX_SOCKETS), +#endif +#ifdef HAVE_ZSTD + FEATURE("zstd", NULL, CURL_VERSION_ZSTD), +#endif + {NULL, NULL, 0} +}; + +static const char *feature_names[CURL_ARRAYSIZE(features_table)] = { NULL }; + +static curl_version_info_data version_info = { + CURLVERSION_NOW, + LIBCURL_VERSION, + LIBCURL_VERSION_NUM, + CURL_OS, /* as found by configure or set by hand at build-time */ + 0, /* features bitmask is built at runtime */ + NULL, /* ssl_version */ + 0, /* ssl_version_num, this is kept at zero */ + NULL, /* zlib_version */ + supported_protocols, + NULL, /* c-ares version */ + 0, /* c-ares version numerical */ + NULL, /* libidn version */ + 0, /* iconv version */ + NULL, /* ssh lib version */ + 0, /* brotli_ver_num */ + NULL, /* brotli version */ + 0, /* nghttp2 version number */ + NULL, /* nghttp2 version string */ + NULL, /* quic library string */ +#ifdef CURL_CA_BUNDLE + CURL_CA_BUNDLE, /* cainfo */ +#else + NULL, +#endif +#ifdef CURL_CA_PATH + CURL_CA_PATH, /* capath */ +#else + NULL, +#endif + 0, /* zstd_ver_num */ + NULL, /* zstd version */ + NULL, /* Hyper version */ + NULL, /* gsasl version */ + feature_names, + NULL /* rtmp version */ +}; + +curl_version_info_data *curl_version_info(CURLversion stamp) +{ + size_t n; + const struct feat *p; + int features = 0; + +#ifdef USE_SSH + static char ssh_buf[80]; /* 'ssh_buffer' clashes with libssh/libssh.h */ +#endif +#ifdef USE_SSL +#ifdef CURL_WITH_MULTI_SSL + static char ssl_buffer[200]; +#else + static char ssl_buffer[80]; +#endif +#endif +#ifdef HAVE_BROTLI + static char brotli_buffer[80]; +#endif +#ifdef HAVE_ZSTD + static char zstd_buffer[80]; +#endif + + (void)stamp; + +#ifdef USE_SSL + Curl_ssl_version(ssl_buffer, sizeof(ssl_buffer)); + version_info.ssl_version = ssl_buffer; +#endif + +#ifdef HAVE_LIBZ + version_info.libz_version = zlibVersion(); + /* libz left NULL if non-existing */ +#endif +#ifdef USE_ARES + { + int aresnum; + version_info.ares = ares_version(&aresnum); + version_info.ares_num = aresnum; + } +#endif +#ifdef USE_LIBIDN2 + /* This returns a version string if we use the given version or later, + otherwise it returns NULL */ + version_info.libidn = idn2_check_version(IDN2_VERSION); +#endif + +#ifdef USE_SSH + Curl_ssh_version(ssh_buf, sizeof(ssh_buf)); + version_info.libssh_version = ssh_buf; +#endif + +#ifdef HAVE_BROTLI + version_info.brotli_ver_num = BrotliDecoderVersion(); + brotli_version(brotli_buffer, sizeof(brotli_buffer)); + version_info.brotli_version = brotli_buffer; +#endif + +#ifdef HAVE_ZSTD + version_info.zstd_ver_num = ZSTD_versionNumber(); + zstd_version(zstd_buffer, sizeof(zstd_buffer)); + version_info.zstd_version = zstd_buffer; +#endif + +#ifdef USE_NGHTTP2 + { + nghttp2_info *h2 = nghttp2_version(0); + version_info.nghttp2_ver_num = (unsigned int)h2->version_num; + version_info.nghttp2_version = h2->version_str; + } +#endif + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_HTTP3) + { + static char quicbuffer[80]; + Curl_quic_ver(quicbuffer, sizeof(quicbuffer)); + version_info.quic_version = quicbuffer; + } +#endif + +#ifdef USE_GSASL + { + version_info.gsasl_version = gsasl_check_version(NULL); + } +#endif + + /* Get available features, build bitmask and names array. */ + n = 0; + for(p = features_table; p->name; p++) + if(!p->present || p->present(&version_info)) { + features |= p->bitmask; + feature_names[n++] = p->name; + } + +#ifdef DEBUGBUILD + features |= CURL_VERSION_CURLDEBUG; /* for compatibility */ +#endif + + feature_names[n] = NULL; /* Terminate array. */ + version_info.features = features; + + return &version_info; +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/capsule.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/capsule.c new file mode 100644 index 0000000000..4bbdae3ace --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/capsule.c @@ -0,0 +1,301 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP) + +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> /* for htons() */ +#endif + +#include <curl/curl.h> +#include "urldata.h" +#include "curlx/dynbuf.h" +#include "cfilters.h" +#include "curl_trc.h" +#include "bufq.h" +#include "vquic/capsule.h" + + +/** + * Convert 64-bit value from network byte order to host byte order + */ +static uint64_t capsule_ntohll(uint64_t value) +{ +#if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) + return value; +#elif (defined(__GNUC__) || defined(__clang__)) && \ + defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) + return __builtin_bswap64(value); +#else + union { + uint64_t u64; + uint32_t u32[2]; + } src, dst; + + src.u64 = value; + dst.u32[0] = ntohl(src.u32[1]); + dst.u32[1] = ntohl(src.u32[0]); + return dst.u64; +#endif +} + +/** + * Encode a variable-length integer into a plain buffer. + * @param buf Output buffer (must have at least 8 bytes) + * @param value Value to encode (must be <= 0x3FFFFFFFFFFFFFFF) + * @return Number of bytes written + */ +static size_t capsule_encode_varint_buf(uint8_t *buf, uint64_t value) +{ + DEBUGASSERT(value <= 0x3FFFFFFFFFFFFFFF); + + if(value <= 0x3F) { + buf[0] = (uint8_t)value; + return 1; + } + else if(value <= 0x3FFF) { + uint16_t encoded = (uint16_t)value & 0x3FFF; + encoded = ntohs(encoded | 0x4000); + memcpy(buf, &encoded, 2); + return 2; + } + else if(value <= 0x3FFFFFFF) { + uint32_t encoded = (uint32_t)value & 0x3FFFFFFF; + encoded = ntohl(encoded | 0x80000000); + memcpy(buf, &encoded, 4); + return 4; + } + else { + uint64_t encoded = (uint64_t)value & 0x3FFFFFFFFFFFFFFF; + encoded = capsule_ntohll(encoded | 0xC000000000000000); + memcpy(buf, &encoded, 8); + return 8; + } +} + +static CURLcode capsule_peek_u8(struct bufq *recvbufq, + size_t offset, + uint8_t *pbyte) +{ + const unsigned char *peek = NULL; + size_t peeklen = 0; + + if(!Curl_bufq_peek_at(recvbufq, offset, &peek, &peeklen) || !peeklen) + return CURLE_AGAIN; + *pbyte = peek[0]; + return CURLE_OK; +} + +static CURLcode capsule_decode_varint_at(struct bufq *recvbufq, + size_t offset, + uint64_t *pvalue, + size_t *pconsumed) +{ + uint8_t first_byte, byte; + uint64_t value; + size_t nbytes; + size_t i; + CURLcode result; + + result = capsule_peek_u8(recvbufq, offset, &first_byte); + if(result) + return result; + + nbytes = (size_t)1 << (first_byte >> 6); /* 1, 2, 4 or 8 bytes */ + value = first_byte & 0x3F; + + for(i = 1; i < nbytes; ++i) { + result = capsule_peek_u8(recvbufq, offset + i, &byte); + if(result) + return result; + value = (value << 8) | byte; + } + + *pvalue = value; + *pconsumed = nbytes; + return CURLE_OK; +} + +/** + * Write the capsule header (type + varint length + context ID) into `hdr`. + * @param hdr Output buffer (must be >= HTTP_CAPSULE_HEADER_MAX_SIZE) + * @param hdrlen Size of `hdr` in bytes + * @param payload_len Length of the UDP payload that follows + * @return Number of header bytes written, or 0 on error + * + * @unittest 3400 + */ +UNITTEST size_t capsule_encap_udp_hdr(uint8_t *hdr, size_t hdrlen, + size_t payload_len); +UNITTEST size_t capsule_encap_udp_hdr(uint8_t *hdr, size_t hdrlen, + size_t payload_len) +{ + size_t off = 0; + DEBUGASSERT(hdrlen >= HTTP_CAPSULE_HEADER_MAX_SIZE); + if(hdrlen < HTTP_CAPSULE_HEADER_MAX_SIZE) + return 0; + hdr[off++] = 0; /* capsule type: HTTP Datagram */ + off += capsule_encode_varint_buf(hdr + off, (uint64_t)payload_len + 1); + hdr[off++] = 0; /* context ID */ + return off; +} + +CURLcode Curl_capsule_encap_udp_datagram(struct bufq *q, + const void *buf, size_t blen) +{ + CURLcode result; + uint8_t hdr[HTTP_CAPSULE_HEADER_MAX_SIZE]; + size_t hdr_len, nwritten; + + hdr_len = capsule_encap_udp_hdr(hdr, sizeof(hdr), blen); + DEBUGASSERT(hdr_len); + if(!hdr_len) + return CURLE_FAILED_INIT; + + result = Curl_bufq_write(q, hdr, hdr_len, &nwritten); + if(!result && (nwritten != hdr_len)) + return CURLE_WRITE_ERROR; + if(!result) { + result = Curl_bufq_write(q, buf, blen, &nwritten); + if(!result && (nwritten != blen)) + return CURLE_WRITE_ERROR; + } + if(result == CURLE_AGAIN) + return CURLE_WRITE_ERROR; + return result; +} + +size_t Curl_capsule_process_udp_raw(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct bufq *recvbufq, + unsigned char *buf, size_t len, + CURLcode *err) +{ + const unsigned char *context_id, *capsule_type; + size_t read_size, varint_len; + uint64_t capsule_length; + size_t offset, payload_len; + size_t bytes_read = 0; + CURLcode result = CURLE_OK; + + if(!len) { + *err = CURLE_BAD_FUNCTION_ARGUMENT; + return 0; + } + + if(Curl_bufq_is_empty(recvbufq)) { + *err = CURLE_AGAIN; + return 0; + } + + if(!Curl_bufq_peek(recvbufq, &capsule_type, &read_size) || !read_size) { + *err = CURLE_AGAIN; + return 0; + } + + if(capsule_type[0]) { + infof(data, "Error! Invalid capsule type: %d", capsule_type[0]); + Curl_bufq_skip(recvbufq, 1); + *err = CURLE_RECV_ERROR; + return 0; + } + + offset = 1; + result = capsule_decode_varint_at(recvbufq, offset, &capsule_length, + &varint_len); + if(result == CURLE_AGAIN) { + *err = CURLE_AGAIN; + return 0; + } + else if(result) { + *err = CURLE_RECV_ERROR; + return 0; + } + offset += varint_len; + + if(!Curl_bufq_peek_at(recvbufq, offset, &context_id, &read_size) || + !read_size) { + *err = CURLE_AGAIN; + return 0; + } + + if(*context_id) { + infof(data, "Error! Invalid context ID: %02x", *context_id); + Curl_bufq_skip(recvbufq, offset + 1); + *err = CURLE_RECV_ERROR; + return 0; + } + offset += 1; + + if(!capsule_length) { + infof(data, "Error! Invalid capsule length: 0"); + Curl_bufq_skip(recvbufq, offset); + *err = CURLE_RECV_ERROR; + return 0; + } + if(capsule_length - 1 >= (uint64_t)SIZE_MAX) { + infof(data, "Error! Capsule length too large: %" CURL_FORMAT_CURL_OFF_T, + (curl_off_t)capsule_length); + *err = CURLE_RECV_ERROR; + return 0; + } + payload_len = (size_t)(capsule_length - 1); + + if(Curl_bufq_len(recvbufq) < offset + payload_len) { + *err = CURLE_AGAIN; + return 0; + } + + if(payload_len > len) { + infof(data, "UDP payload does not fit destination buffer: %zu > %zu", + payload_len, len); + Curl_bufq_skip(recvbufq, offset + payload_len); + *err = CURLE_RECV_ERROR; + return 0; + } + + Curl_bufq_skip(recvbufq, offset); + if(!payload_len) { + *err = CURLE_OK; + return 0; + } + result = Curl_bufq_read(recvbufq, buf, payload_len, &bytes_read); + if(result || (bytes_read != payload_len)) { + infof(data, "Error! Read less than expected %zu %zu", + payload_len, bytes_read); + *err = CURLE_RECV_ERROR; + return 0; + } + + if(cf && data) { + CURL_TRC_CF(data, cf, "Processed UDP capsule raw: size=%zu " + "length_left %zu", payload_len, Curl_bufq_len(recvbufq)); + } + *err = CURLE_OK; + return bytes_read; +} + +#endif /* !CURL_DISABLE_PROXY && !CURL_DISABLE_HTTP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/capsule.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/capsule.h new file mode 100644 index 0000000000..7861e6fd73 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/capsule.h @@ -0,0 +1,70 @@ +#ifndef HEADER_CURL_CAPSULE_H +#define HEADER_CURL_CAPSULE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP) + +#include "curlx/dynbuf.h" +#include "bufq.h" + +/* HTTP Capsule constants */ +#define HTTP_CAPSULE_HEADER_MAX_SIZE 10 + +/* HTTP Capsule function prototypes */ + +/** + * Encapsulate UDP payload into HTTP Datagram capsule format + * @param q the bufq to write the capsule to + * @param buf Payload buffer + * @param blen Payload buffer length + * @return CURLE_OK on success, error code on failure + */ +CURLcode Curl_capsule_encap_udp_datagram(struct bufq *q, + const void *buf, size_t blen); + +struct Curl_easy; +struct Curl_cfilter; + +/** + * Process one UDP capsule from buffer into raw datagram payload bytes. + * @param cf Connection filter + * @param data Easy handle + * @param recvbufq Buffer queue containing capsule data + * @param buf Output buffer for one datagram payload + * @param len Size of output buffer in bytes + * @param err Error code output + * @return Number of payload bytes written. Check `err` for status. + */ +size_t Curl_capsule_process_udp_raw(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct bufq *recvbufq, + unsigned char *buf, size_t len, + CURLcode *err); + +#endif /* !CURL_DISABLE_PROXY && !CURL_DISABLE_HTTP */ + +#endif /* HEADER_CURL_CAPSULE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-capsule.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-capsule.c new file mode 100644 index 0000000000..3ff7827bba --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-capsule.c @@ -0,0 +1,306 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP) + +#include "urldata.h" +#include "cfilters.h" +#include "curl_trc.h" +#include "bufq.h" +#include "select.h" +#include "vquic/capsule.h" +#include "vquic/cf-capsule.h" + +/* send/recv buffer: 4 chunks of 16KB = 64KB, enough for large datagrams */ +#define CAPSULE_RECV_CHUNKS 4 +#define CAPSULE_SEND_CHUNKS 4 +#define CAPSULE_CHUNK_SIZE (16 * 1024) + +struct cf_capsule_ctx { + struct bufq recvbuf; + struct bufq sendbuf; +}; + +static void cf_capsule_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_capsule_ctx *ctx = cf->ctx; + (void)data; + if(ctx) { + Curl_bufq_free(&ctx->recvbuf); + Curl_bufq_free(&ctx->sendbuf); + curlx_safefree(ctx); + } +} + +static CURLcode cf_capsule_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + if(cf->next) { + CURLcode result = cf->next->cft->do_connect(cf->next, data, done); + if(!result && *done) + cf->connected = TRUE; + return result; + } + *done = FALSE; + return CURLE_OK; +} + +static CURLcode cf_capsule_flush(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_capsule_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + size_t nwritten; + + if(Curl_bufq_is_empty(&ctx->sendbuf)) + return CURLE_OK; + + result = Curl_cf_send_bufq(cf->next, data, &ctx->sendbuf, NULL, 0, + &nwritten); + if(result) { + if(result == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "flush send buffer(%zu) -> EAGAIN", + Curl_bufq_len(&ctx->sendbuf)); + } + return result; + } + return Curl_bufq_is_empty(&ctx->sendbuf) ? CURLE_OK : CURLE_AGAIN; +} + +static CURLcode cf_capsule_send(struct Curl_cfilter *cf, + struct Curl_easy *data, + const uint8_t *buf, size_t len, + bool eos, size_t *pnwritten) +{ + struct cf_capsule_ctx *ctx = cf->ctx; + CURLcode result; + + (void)eos; + *pnwritten = 0; + + if(Curl_bufq_is_full(&ctx->sendbuf)) { + result = cf_capsule_flush(cf, data); + if(result) + return result; + } + + /* encapsulate new payload into a capsule */ + result = Curl_capsule_encap_udp_datagram(&ctx->sendbuf, buf, len); + if(result) + return result; + + result = cf_capsule_flush(cf, data); + if(result == CURLE_AGAIN) { + /* Could not send it (or all), report success nevertheless as we + * have the payload buffered now and will flush it later. */ + result = CURLE_OK; + } + + if(!result) + *pnwritten = len; + return result; +} + +static CURLcode cf_capsule_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, size_t len, + size_t *pnread) +{ + struct cf_capsule_ctx *ctx = cf->ctx; + CURLcode result; + size_t nread; + + *pnread = 0; + + /* fill our receive buffer from the filter below */ + while(!Curl_bufq_is_full(&ctx->recvbuf)) { + result = Curl_cf_recv_bufq(cf->next, data, &ctx->recvbuf, 0, &nread); + if(result == CURLE_AGAIN) + break; + if(result) + return result; + if(!nread) + break; + } + + /* try to extract a complete capsule datagram */ + *pnread = Curl_capsule_process_udp_raw(cf, data, &ctx->recvbuf, + (unsigned char *)buf, len, + &result); + return result; +} + +static bool cf_capsule_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_capsule_ctx *ctx = cf->ctx; + + if(ctx && !Curl_bufq_is_empty(&ctx->recvbuf)) + return TRUE; + return cf->next ? cf->next->cft->has_data_pending(cf->next, data) : FALSE; +} + +static CURLcode cf_capsule_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + CURLcode result = CURLE_OK; + + (void)arg1; + (void)arg2; + switch(event) { + case CF_CTRL_FLUSH: + result = cf_capsule_flush(cf, data); + break; + default: + break; + } + return result; +} + +static CURLcode cf_capsule_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_capsule_ctx *ctx = cf->ctx; + + (void)pres2; + switch(query) { + case CF_QUERY_NEED_FLUSH: { + if(!Curl_bufq_is_empty(&ctx->sendbuf)) { + *pres1 = TRUE; + return CURLE_OK; + } + break; + } + default: + break; + } + return cf->next ? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +static CURLcode cf_capsule_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_capsule_ctx *ctx = cf->ctx; + + if(!Curl_bufq_is_empty(&ctx->sendbuf)) { + curl_socket_t sock = Curl_conn_cf_get_socket(cf, data); + if(sock != CURL_SOCKET_BAD) + return Curl_pollset_add_out(data, ps, sock); + } + return CURLE_OK; +} + +static CURLcode cf_capsule_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + + if(!cf->connected || cf->shutdown) { + *done = TRUE; + } + else { + result = cf_capsule_flush(cf, data); + *done = !result; + if(result == CURLE_AGAIN) + result = CURLE_OK; + } + return result; +} + +struct Curl_cftype Curl_cft_capsule = { + "CAPSULE", + 0, + 0, + cf_capsule_destroy, + cf_capsule_connect, + cf_capsule_shutdown, + cf_capsule_adjust_pollset, + cf_capsule_data_pending, + cf_capsule_send, + cf_capsule_recv, + cf_capsule_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_capsule_query, +}; + +static CURLcode cf_capsule_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn) +{ + struct Curl_cfilter *cf = NULL; + struct cf_capsule_ctx *ctx; + CURLcode result; + + (void)data; + (void)conn; + *pcf = NULL; + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + Curl_bufq_init2(&ctx->recvbuf, CAPSULE_CHUNK_SIZE, CAPSULE_RECV_CHUNKS, + BUFQ_OPT_SOFT_LIMIT); + Curl_bufq_init2(&ctx->sendbuf, CAPSULE_CHUNK_SIZE, CAPSULE_SEND_CHUNKS, + BUFQ_OPT_SOFT_LIMIT); + + result = Curl_cf_create(&cf, &Curl_cft_capsule, ctx); + +out: + *pcf = (!result) ? cf : NULL; + if(result && ctx) { + Curl_bufq_free(&ctx->recvbuf); + Curl_bufq_free(&ctx->sendbuf); + curlx_free(ctx); + } + return result; +} + +CURLcode Curl_cf_capsule_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data) +{ + struct Curl_cfilter *cf; + CURLcode result; + + result = cf_capsule_create(&cf, data, cf_at->conn); + if(!result) + Curl_conn_cf_insert_after(cf_at, cf); + return result; +} + +#endif /* !CURL_DISABLE_PROXY && !CURL_DISABLE_HTTP */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-capsule.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-capsule.h new file mode 100644 index 0000000000..437c9681b6 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-capsule.h @@ -0,0 +1,40 @@ +#ifndef HEADER_CURL_CF_CAPSULE_H +#define HEADER_CURL_CF_CAPSULE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP) + +/* Insert a capsule protocol filter after `cf_at` in the filter chain. + * The capsule filter encapsulates/decapsulates UDP datagrams using + * the HTTP Datagram capsule format (RFC 9297). */ +CURLcode Curl_cf_capsule_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data); + +extern struct Curl_cftype Curl_cft_capsule; + +#endif /* !CURL_DISABLE_PROXY && !CURL_DISABLE_HTTP */ + +#endif /* HEADER_CURL_CF_CAPSULE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2-cmn.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2-cmn.c new file mode 100644 index 0000000000..b1cfb68cbd --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2-cmn.c @@ -0,0 +1,2098 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_NGTCP2) && defined(USE_NGHTTP3) + +#include <ngtcp2/ngtcp2.h> + +#ifdef USE_OPENSSL +#include <openssl/err.h> +#if defined(OPENSSL_IS_AWSLC) || defined(OPENSSL_IS_BORINGSSL) +#include <ngtcp2/ngtcp2_crypto_boringssl.h> +#elif defined(OPENSSL_QUIC_API2) +#include <ngtcp2/ngtcp2_crypto_ossl.h> +#else +#include <ngtcp2/ngtcp2_crypto_quictls.h> +#endif +#include "vtls/openssl.h" +#elif defined(USE_GNUTLS) +#include <ngtcp2/ngtcp2_crypto_gnutls.h> +#include "vtls/gtls.h" +#elif defined(USE_WOLFSSL) +#include <ngtcp2/ngtcp2_crypto_wolfssl.h> +#include "vtls/wolfssl.h" +#endif + +#include <nghttp3/nghttp3.h> + +#include "urldata.h" +#include "url.h" +#include "uint-hash.h" +#include "curl_trc.h" +#include "rand.h" +#include "multiif.h" +#include "cfilters.h" +#include "cf-socket.h" +#include "connect.h" +#include "progress.h" +#include "curlx/fopen.h" +#include "curlx/dynbuf.h" +#include "http1.h" +#include "select.h" +#include "sockaddr.h" +#include "transfer.h" +#include "bufref.h" +#include "vdns/cf-dns.h" +#include "vquic/vquic.h" +#include "vquic/vquic_int.h" +#include "vquic/vquic-tls.h" +#include "vtls/vtls.h" +#include "vtls/vtls_scache.h" +#include "vquic/cf-ngtcp2-cmn.h" + +/* + * Store ngtcp2 version info in this buffer. + */ +void Curl_ngtcp2_ver(char *p, size_t len) +{ + const ngtcp2_info *ng2 = ngtcp2_version(0); + const nghttp3_info *ht3 = nghttp3_version(0); + (void)curl_msnprintf(p, len, "ngtcp2/%s nghttp3/%s", + ng2->version_str, ht3->version_str); +} + +void Curl_cf_ngtcp2_h3_stream_ctx_free(struct h3_stream_ctx *stream) +{ + Curl_bufq_free(&stream->sendbuf); + Curl_h1_req_parse_free(&stream->h1); + curlx_free(stream); +} + +static void h3_stream_hash_free(unsigned int id, void *stream) +{ + (void)id; + DEBUGASSERT(stream); + Curl_cf_ngtcp2_h3_stream_ctx_free((struct h3_stream_ctx *)stream); +} + +static bool cf_ngtcp2_h3_err_is_fatal(int code) +{ + return (NGHTTP3_ERR_FATAL >= code) || + (NGHTTP3_ERR_H3_CLOSED_CRITICAL_STREAM == code); +} + +void Curl_cf_ngtcp2_h3_err_set(struct Curl_cfilter *cf, + struct Curl_easy *data, int code) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + if(!ctx->last_error.error_code) { + ngtcp2_ccerr_set_application_error(&ctx->last_error, + nghttp3_err_infer_quic_app_error_code(code), NULL, 0); + } + if(cf_ngtcp2_h3_err_is_fatal(code)) + Curl_cf_ngtcp2_cmn_conn_close(cf, data); +} + +CURLcode Curl_cf_ngtcp2_ctx_init(struct cf_ngtcp2_ctx *ctx, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct ssl_primary_config *sslc, + cf_ngtcp2_init_h3_conn *init_h3_conn_cb) +{ + DEBUGASSERT(!ctx->initialized); + ctx->qlogfd = -1; + ctx->tunnel_inbuf = NULL; + ctx->tunnel_inbuf_len = 0; + ctx->version = NGTCP2_PROTO_VER_MAX; + Curl_bufcp_init(&ctx->stream_bufcp, H3_STREAM_CHUNK_SIZE, + H3_STREAM_POOL_SPARES); + curlx_dyn_init(&ctx->scratch, CURL_MAX_HTTP_HEADER); + Curl_uint32_hash_init(&ctx->streams, 63, h3_stream_hash_free); + ctx->init_h3_conn_cb = init_h3_conn_cb; + ctx->initialized = TRUE; + return Curl_vquic_tls_peer_init(origin, peer, sslc, &ctx->ssl_peer); +} + +void Curl_cf_ngtcp2_ctx_cleanup(struct cf_ngtcp2_ctx *ctx) +{ + if(ctx && ctx->initialized) { + Curl_vquic_tls_cleanup(&ctx->tls); + Curl_vquic_ctx_free(&ctx->q); + Curl_bufcp_free(&ctx->stream_bufcp); + curlx_dyn_free(&ctx->scratch); + Curl_uint32_hash_destroy(&ctx->streams); + Curl_ssl_peer_cleanup(&ctx->ssl_peer); + curlx_safefree(ctx->tunnel_inbuf); + ctx->tunnel_inbuf_len = 0; + if(ctx->qlogfd != -1) { + curlx_close(ctx->qlogfd); + ctx->qlogfd = -1; + } + } +} + +static ngtcp2_conn *get_conn(ngtcp2_crypto_conn_ref *conn_ref) +{ + struct Curl_cfilter *cf = conn_ref->user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + return ctx->qconn; +} + +#ifdef DEBUG_NGTCP2 +static void quic_printf(void *user_data, const char *fmt, ...) +{ + va_list ap; + (void)user_data; + va_start(ap, fmt); + curl_mvfprintf(stderr, fmt, ap); + va_end(ap); + curl_mfprintf(stderr, "\n"); +} +#endif + +static void qlog_callback(void *user_data, uint32_t flags, + const void *data, size_t datalen) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + (void)flags; + if(ctx->qlogfd != -1) { + ssize_t rc = write(ctx->qlogfd, data, datalen); + if(rc == -1) { + /* on write error, stop further write attempts */ + curlx_close(ctx->qlogfd); + ctx->qlogfd = -1; + } + } +} + +static void quic_settings(struct cf_ngtcp2_ctx *ctx, + struct Curl_easy *data, + struct cf_ngtcp2_io_ctx *pktx) +{ + ngtcp2_settings *s = &ctx->settings; + ngtcp2_transport_params *t = &ctx->transport_params; + + ngtcp2_settings_default(s); + ngtcp2_transport_params_default(t); +#ifdef DEBUG_NGTCP2 + s->log_printf = quic_printf; +#else + s->log_printf = NULL; +#endif + + s->initial_ts = pktx->ts; + s->handshake_timeout = (data->set.connecttimeout > 0) ? + data->set.connecttimeout * NGTCP2_MILLISECONDS : QUIC_HANDSHAKE_TIMEOUT; + s->max_window = H3_CONN_WINDOW_SIZE_MAX; + s->max_stream_window = 0; /* disable ngtcp2 auto-tuning of window */ + s->no_pmtud = FALSE; +#ifdef NGTCP2_SETTINGS_V3 + /* try ten times the ngtcp2 defaults here for problems with Caddy */ + s->glitch_ratelim_burst = 1000 * 10; + s->glitch_ratelim_rate = 33 * 10; +#endif + t->initial_max_data = s->max_window; + t->initial_max_stream_data_bidi_local = H3_STREAM_WINDOW_SIZE_INITIAL; + t->initial_max_stream_data_bidi_remote = H3_STREAM_WINDOW_SIZE_INITIAL; + t->initial_max_stream_data_uni = t->initial_max_data; + t->initial_max_streams_bidi = QUIC_MAX_STREAMS; + t->initial_max_streams_uni = QUIC_MAX_STREAMS; + t->max_idle_timeout = 0; /* no idle timeout from our side */ + if(ctx->qlogfd != -1) { + s->qlog_write = qlog_callback; + } +} + +#if defined(_MSC_VER) && defined(_DLL) +#pragma warning(push) +#pragma warning(disable:4232) /* MSVC extension, dllimport identity */ +#endif + +static int cb_ngtcp2_handshake_completed(ngtcp2_conn *tconn, void *user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf ? cf->ctx : NULL; + struct Curl_easy *data; + + (void)tconn; + DEBUGASSERT(ctx); + data = CF_DATA_CURRENT(cf); + DEBUGASSERT(data); + if(!ctx || !data) + return NGTCP2_ERR_CALLBACK_FAILURE; + + ctx->handshake_at = *Curl_pgrs_now(data); + ctx->tls_handshake_complete = TRUE; + Curl_vquic_report_handshake(&ctx->tls, cf, data); + + ctx->tls_vrfy_result = Curl_vquic_tls_verify_peer(&ctx->tls, cf, + data, &ctx->ssl_peer); + if(ctx->tls_vrfy_result) + return NGTCP2_ERR_CALLBACK_FAILURE; + +#ifdef CURLVERBOSE + if(Curl_trc_is_verbose(data)) { + const ngtcp2_transport_params *rp; + rp = ngtcp2_conn_get_remote_transport_params(ctx->qconn); + CURL_TRC_CF(data, cf, "handshake complete after %" FMT_TIMEDIFF_T + "ms, remote transport[max_udp_payload=%" PRIu64 + ", initial_max_data=%" PRIu64 "]", + curlx_ptimediff_ms(&ctx->handshake_at, &ctx->started_at), + rp->max_udp_payload_size, rp->initial_max_data); + } +#endif + + /* In case of earlydata, where we simulate being connected, update + * the handshake time when we really did connect */ + if(ctx->use_earlydata && !ctx->stats_reported && + !(cf->cft->flags & CF_TYPE_PROXY)) { + Curl_pgrsTimeWas(data, TIMER_APPCONNECT, ctx->handshake_at); + ctx->stats_reported = TRUE; + } + if(ctx->use_earlydata) { +#if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_EARLYDATA) + /* Check for bug that OpenSSL did not even send the early data. */ + if(SSL_get_early_data_status(ctx->tls.ossl.ssl) == SSL_EARLY_DATA_NOT_SENT) + CURL_TRC_CF(data, cf, "OpenSSL did not send early data"); +#endif + +#if NGTCP2_VERSION_NUM >= 0x011700 + ctx->earlydata_accepted = + !ngtcp2_conn_get_tls_early_data_rejected2(ctx->qconn); +#else /* older NGTCP2 */ +#if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_EARLYDATA) + int ossl_early_status = SSL_get_early_data_status(ctx->tls.ossl.ssl); + if(ossl_early_status == SSL_EARLY_DATA_NOT_SENT) + CURL_TRC_CF(data, cf, "OpenSSL did not send early data"); + ctx->earlydata_accepted = (ossl_early_status == SSL_EARLY_DATA_ACCEPTED); +#elif defined(USE_GNUTLS) + int flags = gnutls_session_get_flags(ctx->tls.gtls.session); + ctx->earlydata_accepted = !!(flags & GNUTLS_SFLAGS_EARLY_DATA); +#elif defined(USE_WOLFSSL) +#ifdef WOLFSSL_EARLY_DATA + ctx->earlydata_accepted = + (wolfSSL_get_early_data_status(ctx->tls.wssl.ssl) != + WOLFSSL_EARLY_DATA_REJECTED); +#else + DEBUGASSERT(0); /* should not come here if ED is disabled. */ + ctx->earlydata_accepted = FALSE; +#endif /* WOLFSSL_EARLY_DATA */ +#endif /* OPENSSL or GNUTLS or WOLFSSL */ +#endif /* older NGTCP2 */ + CURL_TRC_CF(data, cf, "server did%s accept %zu bytes of early data", + ctx->earlydata_accepted ? "" : " not", ctx->earlydata_skip); + Curl_pgrsEarlyData(data, ctx->earlydata_accepted ? + (curl_off_t)ctx->earlydata_skip : + -(curl_off_t)ctx->earlydata_skip); + } + return 0; +} + +static int cb_recv_stream_data(ngtcp2_conn *tconn, uint32_t flags, + int64_t stream_id, uint64_t offset, + const uint8_t *buf, size_t buflen, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + nghttp3_ssize rc; + uint64_t nconsumed; + int fin = (flags & NGTCP2_STREAM_DATA_FLAG_FIN) ? 1 : 0; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + (void)offset; + + rc = nghttp3_conn_read_stream(ctx->h3conn, stream_id, buf, buflen, fin); + if(rc < 0) { + if(data && stream) { + CURL_TRC_CF(data, cf, "[%" PRId64 "] error on known stream, " + "reset=%d, closed=%d", + stream_id, stream->reset, stream->closed); + } + return NGTCP2_ERR_CALLBACK_FAILURE; + } + nconsumed = (uint64_t)rc; + if(nconsumed) { + /* number of bytes inside buflen which consists of framing overhead + * including QPACK HEADERS. In other words, it does not consume payload of + * DATA frame. */ + ngtcp2_conn_extend_max_stream_offset(tconn, stream_id, nconsumed); + ngtcp2_conn_extend_max_offset(tconn, nconsumed); + if(stream) { + stream->rx_offset += nconsumed; + stream->rx_offset_max += nconsumed; + } + } + return 0; +} + +static int cb_acked_stream_data_offset(ngtcp2_conn *tconn, int64_t stream_id, + uint64_t offset, uint64_t datalen, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + int rv; + (void)stream_id; + (void)tconn; + (void)offset; + (void)datalen; + (void)stream_user_data; + + rv = nghttp3_conn_add_ack_offset(ctx->h3conn, stream_id, datalen); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + return NGTCP2_ERR_CALLBACK_FAILURE; + } + + return 0; +} + +static int cb_stream_close(ngtcp2_conn *tconn, uint32_t flags, + int64_t stream_id, uint64_t app_error_code, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + int rv; + + (void)tconn; + /* stream is closed... */ + if(!data) + data = CF_DATA_CURRENT(cf); + if(!data) + return NGTCP2_ERR_CALLBACK_FAILURE; + + if(!(flags & NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET)) { + app_error_code = NGHTTP3_H3_NO_ERROR; + } + + rv = nghttp3_conn_close_stream(ctx->h3conn, stream_id, app_error_code); + CURL_TRC_CF(data, cf, "[%" PRId64 "] quic close(app_error=%" + PRIu64 ") -> %d", stream_id, app_error_code, rv); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + Curl_cf_ngtcp2_h3_err_set(cf, data, rv); + return NGTCP2_ERR_CALLBACK_FAILURE; + } + + return 0; +} + +#ifdef NGTCP2_CALLBACKS_V5 /* ngtcp2 v1.25.0+ */ +static int cb_stream_close2(ngtcp2_conn *tconn, uint32_t flags, + int64_t stream_id, + uint64_t rx_app_error_code, + uint64_t tx_app_error_code, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + uint64_t h3_app_error_code = NGHTTP3_H3_NO_ERROR; + int rv; + + (void)tconn; + (void)tx_app_error_code; + /* stream is closed... */ + if(!data) + data = CF_DATA_CURRENT(cf); + if(!data) + return NGTCP2_ERR_CALLBACK_FAILURE; + + if(flags & NGTCP2_STREAM_CLOSE2_FLAG_RX_APP_ERROR_CODE_SET) + h3_app_error_code = rx_app_error_code; + + rv = nghttp3_conn_close_stream(ctx->h3conn, stream_id, h3_app_error_code); + CURL_TRC_CF(data, cf, "[%" PRId64 "] quic close(app_error=%" + PRIu64 ") -> %d", stream_id, h3_app_error_code, rv); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + Curl_cf_ngtcp2_h3_err_set(cf, data, rv); + return NGTCP2_ERR_CALLBACK_FAILURE; + } + + return 0; +} +#endif + +static int cb_stream_reset(ngtcp2_conn *tconn, int64_t stream_id, + uint64_t final_size, uint64_t app_error_code, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + int rv; + (void)tconn; + (void)final_size; + (void)app_error_code; + + rv = nghttp3_conn_shutdown_stream_read(ctx->h3conn, stream_id); + CURL_TRC_CF(data, cf, "[%" PRId64 "] reset -> %d", stream_id, rv); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + return NGTCP2_ERR_CALLBACK_FAILURE; + } + + return 0; +} + +static int cb_stream_stop_sending(ngtcp2_conn *tconn, int64_t stream_id, + uint64_t app_error_code, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + int rv; + (void)tconn; + (void)app_error_code; + (void)stream_user_data; + + rv = nghttp3_conn_shutdown_stream_read(ctx->h3conn, stream_id); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + return NGTCP2_ERR_CALLBACK_FAILURE; + } + + return 0; +} + +static int cb_extend_max_local_streams_bidi(ngtcp2_conn *tconn, + uint64_t max_streams, + void *user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + + (void)tconn; + ctx->max_bidi_streams = max_streams; + if(data) + CURL_TRC_CF(data, cf, "max bidi streams now %" PRIu64 ", used %" PRIu64, + ctx->max_bidi_streams, ctx->used_bidi_streams); + return 0; +} + +static int cb_extend_max_stream_data(ngtcp2_conn *tconn, int64_t stream_id, + uint64_t max_data, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *s_data = stream_user_data; + struct h3_stream_ctx *stream; + int rv; + (void)tconn; + (void)max_data; + + rv = nghttp3_conn_unblock_stream(ctx->h3conn, stream_id); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + return NGTCP2_ERR_CALLBACK_FAILURE; + } + stream = H3_STREAM_CTX(ctx, s_data); + if(stream && stream->quic_flow_blocked) { + CURL_TRC_CF(s_data, cf, "[%" PRId64 "] unblock quic flow", stream_id); + stream->quic_flow_blocked = FALSE; + Curl_multi_mark_dirty(s_data); + } + return 0; +} + +static void cb_rand(uint8_t *dest, size_t destlen, + const ngtcp2_rand_ctx *rand_ctx) +{ + CURLcode result; + (void)rand_ctx; + + result = Curl_rand(NULL, dest, destlen); + if(result) { + /* cb_rand is only used for non-cryptographic context. If Curl_rand + failed, fill 0 and call it *random*. */ + memset(dest, 0, destlen); + } +} + +/* for ngtcp2 <v1.22.0 */ +static int cb_get_new_connection_id(ngtcp2_conn *tconn, ngtcp2_cid *cid, + uint8_t *token, size_t cidlen, + void *user_data) +{ + CURLcode result; + (void)tconn; + (void)user_data; + + result = Curl_rand(NULL, cid->data, cidlen); + if(result) + return NGTCP2_ERR_CALLBACK_FAILURE; + cid->datalen = cidlen; + + result = Curl_rand(NULL, token, NGTCP2_STATELESS_RESET_TOKENLEN); + if(result) + return NGTCP2_ERR_CALLBACK_FAILURE; + + return 0; +} + +#ifdef NGTCP2_CALLBACKS_V3 /* ngtcp2 v1.22.0+ */ +static int cb_get_new_connection_id2( + ngtcp2_conn *tconn, ngtcp2_cid *cid, + struct ngtcp2_stateless_reset_token *token, size_t cidlen, void *user_data) +{ + CURLcode result; + (void)tconn; + (void)user_data; + + result = Curl_rand(NULL, cid->data, cidlen); + if(result) + return NGTCP2_ERR_CALLBACK_FAILURE; + cid->datalen = cidlen; + + result = Curl_rand(NULL, token->data, sizeof(token->data)); + if(result) + return NGTCP2_ERR_CALLBACK_FAILURE; + + return 0; +} +#endif + +static int cb_recv_rx_key(ngtcp2_conn *tconn, ngtcp2_encryption_level level, + void *user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf ? cf->ctx : NULL; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + (void)tconn; + + if(level != NGTCP2_ENCRYPTION_LEVEL_1RTT) + return 0; + + DEBUGASSERT(ctx); + DEBUGASSERT(data); + if(ctx && data && !ctx->h3conn && ctx->init_h3_conn_cb) { + if(ctx->init_h3_conn_cb(cf, data, ctx)) + return NGTCP2_ERR_CALLBACK_FAILURE; + } + return 0; +} + +#ifdef CURL_HAVE_DIAG +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif +static ngtcp2_callbacks ng_callbacks = { + ngtcp2_crypto_client_initial_cb, + NULL, /* recv_client_initial */ + ngtcp2_crypto_recv_crypto_data_cb, + cb_ngtcp2_handshake_completed, + NULL, /* recv_version_negotiation */ + ngtcp2_crypto_encrypt_cb, + ngtcp2_crypto_decrypt_cb, + ngtcp2_crypto_hp_mask_cb, + cb_recv_stream_data, + cb_acked_stream_data_offset, + NULL, /* stream_open */ + cb_stream_close, + NULL, /* recv_stateless_reset */ + ngtcp2_crypto_recv_retry_cb, + cb_extend_max_local_streams_bidi, + NULL, /* extend_max_local_streams_uni */ + cb_rand, + cb_get_new_connection_id, /* for ngtcp2 <v1.22.0 */ + NULL, /* remove_connection_id */ + ngtcp2_crypto_update_key_cb, /* update_key */ + NULL, /* path_validation */ + NULL, /* select_preferred_addr */ + cb_stream_reset, + NULL, /* extend_max_remote_streams_bidi */ + NULL, /* extend_max_remote_streams_uni */ + cb_extend_max_stream_data, + NULL, /* dcid_status */ + NULL, /* handshake_confirmed */ + NULL, /* recv_new_token */ + ngtcp2_crypto_delete_crypto_aead_ctx_cb, + ngtcp2_crypto_delete_crypto_cipher_ctx_cb, + NULL, /* recv_datagram */ + NULL, /* ack_datagram */ + NULL, /* lost_datagram */ + ngtcp2_crypto_get_path_challenge_data_cb, + cb_stream_stop_sending, + NULL, /* version_negotiation */ + cb_recv_rx_key, + NULL, /* recv_tx_key */ + NULL, /* early_data_rejected */ +#ifdef NGTCP2_CALLBACKS_V2 /* ngtcp2 v1.14.0+ */ + NULL, /* begin_path_validation */ +#endif +#ifdef NGTCP2_CALLBACKS_V3 /* ngtcp2 v1.22.0+ */ + NULL, /* recv_stateless_reset2 */ + cb_get_new_connection_id2, /* get_new_connection_id2 */ + NULL, /* dcid_status2 */ + ngtcp2_crypto_get_path_challenge_data2_cb, /* get_path_challenge_data2 */ +#endif +#ifdef NGTCP2_CALLBACKS_V4 /* ngtcp2 v1.24.0+ */ + NULL, /* recv_stop_sending */ +#endif +#ifdef NGTCP2_CALLBACKS_V5 /* ngtcp2 v1.25.0+ */ + cb_stream_close2, /* is called instead of cb_stream_close when set */ +#endif +}; +#ifdef CURL_HAVE_DIAG +#pragma GCC diagnostic pop +#endif + +#if defined(_MSC_VER) && defined(_DLL) +#pragma warning(pop) +#endif + +static bool cf_ngtcp2_need_httpsrr(struct Curl_easy *data) +{ +#ifdef USE_OPENSSL + return Curl_ossl_need_httpsrr(data); +#elif defined(USE_WOLFSSL) + return Curl_wssl_need_httpsrr(data); +#else + (void)data; + return FALSE; +#endif +} + +#ifdef USE_OPENSSL +/* The "new session" callback must return zero if the session can be removed + * or non-zero if the session has been put into the session cache. + */ +static int quic_ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid) +{ + struct Curl_cfilter *cf; + struct cf_ngtcp2_ctx *ctx; + struct Curl_easy *data; + ngtcp2_crypto_conn_ref *cref; + + cref = (ngtcp2_crypto_conn_ref *)SSL_get_app_data(ssl); + cf = cref ? cref->user_data : NULL; + ctx = cf ? cf->ctx : NULL; + data = cf ? CF_DATA_CURRENT(cf) : NULL; + if(cf && data && ctx) { + unsigned char *quic_tp = NULL; + size_t quic_tp_len = 0; +#ifdef HAVE_OPENSSL_EARLYDATA + ngtcp2_ssize tplen; + uint8_t tpbuf[256]; + + tplen = ngtcp2_conn_encode_0rtt_transport_params(ctx->qconn, tpbuf, + sizeof(tpbuf)); + if(tplen < 0) + CURL_TRC_CF(data, cf, "error encoding 0RTT transport data: %s", + ngtcp2_strerror((int)tplen)); + else { + quic_tp = (unsigned char *)tpbuf; + quic_tp_len = (size_t)tplen; + } +#endif + Curl_ossl_add_session(cf, data, &ctx->tls.ossl, ctx->ssl_peer.scache_key, + ssl_sessionid, "h3", quic_tp, quic_tp_len, NULL); + } + return 0; +} +#endif /* USE_OPENSSL */ + +#ifdef USE_GNUTLS + +#ifdef CURLVERBOSE +static const char *gtls_hs_msg_name(int mtype) +{ + switch(mtype) { + case 1: + return "ClientHello"; + case 2: + return "ServerHello"; + case 4: + return "SessionTicket"; + case 8: + return "EncryptedExtensions"; + case 11: + return "Certificate"; + case 13: + return "CertificateRequest"; + case 15: + return "CertificateVerify"; + case 20: + return "Finished"; + case 24: + return "KeyUpdate"; + case 254: + return "MessageHash"; + } + return "Unknown"; +} +#endif + +static int quic_gtls_handshake_cb(gnutls_session_t session, unsigned int htype, + unsigned when, unsigned int incoming, + const gnutls_datum_t *msg) +{ + ngtcp2_crypto_conn_ref *conn_ref = gnutls_session_get_ptr(session); + struct Curl_cfilter *cf = conn_ref ? conn_ref->user_data : NULL; + struct cf_ngtcp2_ctx *ctx = cf ? cf->ctx : NULL; + + (void)msg; + (void)incoming; + if(when && cf && ctx) { /* after message has been processed */ + struct Curl_easy *data = CF_DATA_CURRENT(cf); + DEBUGASSERT(data); + if(!data) + return 0; + CURL_TRC_CF(data, cf, "SSL message: %s %s [%u]", + incoming ? "<-" : "->", gtls_hs_msg_name(htype), htype); + switch(htype) { + case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET: { + ngtcp2_ssize tplen; + uint8_t tpbuf[256]; + unsigned char *quic_tp = NULL; + size_t quic_tp_len = 0; + + tplen = ngtcp2_conn_encode_0rtt_transport_params(ctx->qconn, tpbuf, + sizeof(tpbuf)); + if(tplen < 0) + CURL_TRC_CF(data, cf, "error encoding 0RTT transport data: %s", + ngtcp2_strerror((int)tplen)); + else { + quic_tp = (unsigned char *)tpbuf; + quic_tp_len = (size_t)tplen; + } + (void)Curl_gtls_cache_session(cf, data, ctx->ssl_peer.scache_key, + session, 0, "h3", quic_tp, quic_tp_len, + NULL); + break; + } + default: + break; + } + } + return 0; +} +#endif /* USE_GNUTLS */ + +#ifdef USE_WOLFSSL +static int wssl_quic_new_session_cb(WOLFSSL *ssl, WOLFSSL_SESSION *session) +{ + ngtcp2_crypto_conn_ref *conn_ref = wolfSSL_get_app_data(ssl); + struct Curl_cfilter *cf = conn_ref ? conn_ref->user_data : NULL; + + DEBUGASSERT(cf); + if(cf && session) { + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + DEBUGASSERT(data); + if(data && ctx) { + ngtcp2_ssize tplen; + uint8_t tpbuf[256]; + unsigned char *quic_tp = NULL; + size_t quic_tp_len = 0; + + tplen = ngtcp2_conn_encode_0rtt_transport_params(ctx->qconn, tpbuf, + sizeof(tpbuf)); + if(tplen < 0) + CURL_TRC_CF(data, cf, "error encoding 0RTT transport data: %s", + ngtcp2_strerror((int)tplen)); + else { + quic_tp = (unsigned char *)tpbuf; + quic_tp_len = (size_t)tplen; + } + (void)Curl_wssl_cache_session(cf, data, ctx->ssl_peer.scache_key, + session, wolfSSL_version(ssl), + "h3", quic_tp, quic_tp_len, NULL); + } + } + return 0; +} +#endif /* USE_WOLFSSL */ + +static CURLcode cf_ngtcp2_tls_ctx_setup(struct Curl_cfilter *cf, + struct Curl_easy *data, + void *user_data) +{ + struct curl_tls_ctx *ctx = user_data; + +#ifdef USE_OPENSSL +#if defined(OPENSSL_IS_AWSLC) || defined(OPENSSL_IS_BORINGSSL) + if(ngtcp2_crypto_boringssl_configure_client_context(ctx->ossl.ssl_ctx) + != 0) { + failf(data, "ngtcp2_crypto_boringssl_configure_client_context failed"); + return CURLE_FAILED_INIT; + } +#elif defined(OPENSSL_QUIC_API2) + /* nothing to do */ +#else + if(ngtcp2_crypto_quictls_configure_client_context(ctx->ossl.ssl_ctx) != 0) { + failf(data, "ngtcp2_crypto_quictls_configure_client_context failed"); + return CURLE_FAILED_INIT; + } +#endif /* !OPENSSL_IS_AWSLC && !OPENSSL_IS_BORINGSSL */ + if(Curl_ssl_scache_use(cf, data)) { + /* Enable the session cache because it is a prerequisite for the + * "new session" callback. Use the "external storage" mode to prevent + * OpenSSL from creating an internal session cache. + */ + SSL_CTX_set_session_cache_mode(ctx->ossl.ssl_ctx, + SSL_SESS_CACHE_CLIENT | + SSL_SESS_CACHE_NO_INTERNAL); + SSL_CTX_sess_set_new_cb(ctx->ossl.ssl_ctx, quic_ossl_new_session_cb); + } + +#elif defined(USE_GNUTLS) + if(ngtcp2_crypto_gnutls_configure_client_session(ctx->gtls.session) != 0) { + failf(data, "ngtcp2_crypto_gnutls_configure_client_session failed"); + return CURLE_FAILED_INIT; + } + if(Curl_ssl_scache_use(cf, data)) { + gnutls_handshake_set_hook_function(ctx->gtls.session, + GNUTLS_HANDSHAKE_ANY, GNUTLS_HOOK_POST, + quic_gtls_handshake_cb); + } + +#elif defined(USE_WOLFSSL) + if(ngtcp2_crypto_wolfssl_configure_client_context(ctx->wssl.ssl_ctx) != 0) { + failf(data, "ngtcp2_crypto_wolfssl_configure_client_context failed"); + return CURLE_FAILED_INIT; + } + if(Curl_ssl_scache_use(cf, data)) { + /* Register to get notified when a new session is received */ + wolfSSL_CTX_sess_set_new_cb(ctx->wssl.ssl_ctx, wssl_quic_new_session_cb); + } +#endif + return CURLE_OK; +} + +static CURLcode cf_ngtcp2_on_session_reuse(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct alpn_spec *alpns, + struct Curl_ssl_session *scs, + bool *do_early_data) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + *do_early_data = FALSE; +#if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_EARLYDATA) + ctx->earlydata_max = scs->earlydata_max; +#endif +#ifdef USE_GNUTLS + ctx->earlydata_max = + gnutls_record_get_max_early_data_size(ctx->tls.gtls.session); +#endif +#ifdef USE_WOLFSSL +#ifdef WOLFSSL_EARLY_DATA + ctx->earlydata_max = scs->earlydata_max; +#else + ctx->earlydata_max = 0; +#endif /* WOLFSSL_EARLY_DATA */ +#endif +#if defined(USE_GNUTLS) || defined(USE_WOLFSSL) || \ + (defined(USE_OPENSSL) && defined(HAVE_OPENSSL_EARLYDATA)) + if(!ctx->earlydata_max) { + CURL_TRC_CF(data, cf, "SSL session does not allow earlydata"); + } + else if(!Curl_alpn_contains_proto(alpns, scs->alpn)) { + CURL_TRC_CF(data, cf, "SSL session from different ALPN, no early data"); + } + else if(!scs->quic_tp || !scs->quic_tp_len) { + CURL_TRC_CF(data, cf, "no 0RTT transport parameters, no early data"); + } + else { + int rv; + rv = ngtcp2_conn_decode_and_set_0rtt_transport_params( + ctx->qconn, (const uint8_t *)scs->quic_tp, scs->quic_tp_len); + if(rv) + CURL_TRC_CF(data, cf, "no early data, failed to set 0RTT transport " + "parameters: %s", ngtcp2_strerror(rv)); + else if(ctx->init_h3_conn_cb) { + infof(data, "SSL session allows %zu bytes of early data, " + "reusing ALPN '%s'", ctx->earlydata_max, scs->alpn); + result = ctx->init_h3_conn_cb(cf, data, ctx); + if(!result) { + ctx->use_earlydata = TRUE; + cf->connected = TRUE; + *do_early_data = TRUE; + } + } + else { /* init_h3_conn_cb not set, assume done */ + ctx->use_earlydata = TRUE; + cf->connected = TRUE; + *do_early_data = TRUE; + } + } +#else /* not supported in the TLS backend */ + (void)data; + (void)ctx; + (void)scs; + (void)alpns; +#endif + return result; +} + +/* + * Might be called twice for happy eyeballs. + */ +static CURLcode cf_connect_start(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_ngtcp2_io_ctx *pktx) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + int rc; + int rv; + CURLcode result; + const struct Curl_sockaddr_ex *sockaddr = NULL; + int qfd; + static const struct alpn_spec ALPN_SPEC_H3 = { { "h3", "h3-29" }, 2 }; + + DEBUGASSERT(ctx->initialized); + ctx->dcid.datalen = NGTCP2_MAX_CIDLEN; + result = Curl_rand(data, ctx->dcid.data, NGTCP2_MAX_CIDLEN); + if(result) + return result; + + ctx->scid.datalen = NGTCP2_MAX_CIDLEN; + result = Curl_rand(data, ctx->scid.data, NGTCP2_MAX_CIDLEN); + if(result) + return result; + + (void)Curl_qlogdir(data, ctx->scid.data, NGTCP2_MAX_CIDLEN, &qfd); + ctx->qlogfd = qfd; /* -1 if failure above */ + quic_settings(ctx, data, pktx); + + result = Curl_vquic_ctx_init(data, &ctx->q); + if(result) + return result; + + /* Query socket and remote address from sub-chain */ + if(Curl_cf_socket_peek(cf->next, data, &ctx->q.sockfd, &sockaddr, NULL)) { + /* No direct socket - must be tunneled QUIC (CONNECT-UDP through proxy) */ + ctx->q.sockfd = CURL_SOCKET_BAD; + } + + if(ctx->q.sockfd != CURL_SOCKET_BAD) { + /* Direct UDP socket - get local address for ngtcp2 */ + ctx->q.local_addrlen = sizeof(ctx->q.local_addr); + rv = getsockname(ctx->q.sockfd, (struct sockaddr *)&ctx->q.local_addr, + &ctx->q.local_addrlen); + if(rv == -1) + return CURLE_QUIC_CONNECT_ERROR; + + ngtcp2_addr_init(&ctx->connected_path.local, + (struct sockaddr *)&ctx->q.local_addr, + ctx->q.local_addrlen); + ngtcp2_addr_init(&ctx->connected_path.remote, + &sockaddr->curl_sa_addr, (socklen_t)sockaddr->addrlen); + } + else { + /* Tunneled QUIC (e.g. CONNECT-UDP): get remote address + from the connected filter below */ + const struct Curl_sockaddr_ex *remote = NULL; + if(cf->next->cft->query(cf->next, data, CF_QUERY_REMOTE_ADDR, NULL, + CURL_UNCONST(&remote))) + return CURLE_QUIC_CONNECT_ERROR; + if(!remote) + return CURLE_QUIC_CONNECT_ERROR; + + memset(&ctx->q.local_addr, 0, sizeof(ctx->q.local_addr)); + switch(remote->family) { + case AF_INET: + ((struct sockaddr_in *)&ctx->q.local_addr)->sin_family = AF_INET; + ctx->q.local_addrlen = sizeof(struct sockaddr_in); + break; +#ifdef USE_IPV6 + case AF_INET6: + ((struct sockaddr_in6 *)&ctx->q.local_addr)->sin6_family = AF_INET6; + ctx->q.local_addrlen = sizeof(struct sockaddr_in6); + break; +#endif + default: + return CURLE_QUIC_CONNECT_ERROR; + } + + ngtcp2_addr_init(&ctx->connected_path.local, + (struct sockaddr *)&ctx->q.local_addr, + ctx->q.local_addrlen); + ngtcp2_addr_init(&ctx->connected_path.remote, + &remote->curl_sa_addr, + (socklen_t)remote->addrlen); + } + + rc = ngtcp2_conn_client_new(&ctx->qconn, &ctx->dcid, &ctx->scid, + &ctx->connected_path, + NGTCP2_PROTO_VER_V1, &ng_callbacks, + &ctx->settings, &ctx->transport_params, + Curl_ngtcp2_mem(), cf); + if(rc) + return CURLE_QUIC_CONNECT_ERROR; + + ctx->conn_ref.get_conn = get_conn; + ctx->conn_ref.user_data = cf; + + result = Curl_vquic_tls_init(&ctx->tls, cf, data, + &ctx->ssl_peer, &ALPN_SPEC_H3, + cf_ngtcp2_tls_ctx_setup, &ctx->tls, + &ctx->conn_ref, + cf_ngtcp2_on_session_reuse); + if(result) + return result; + +#if defined(USE_OPENSSL) && defined(OPENSSL_QUIC_API2) + if(ngtcp2_crypto_ossl_ctx_new(&ctx->ossl_ctx, ctx->tls.ossl.ssl) != 0) { + failf(data, "ngtcp2_crypto_ossl_ctx_new failed"); + return CURLE_FAILED_INIT; + } + ngtcp2_conn_set_tls_native_handle(ctx->qconn, ctx->ossl_ctx); + if(ngtcp2_crypto_ossl_configure_client_session(ctx->tls.ossl.ssl) != 0) { + failf(data, "ngtcp2_crypto_ossl_configure_client_session failed"); + return CURLE_FAILED_INIT; + } +#elif defined(USE_OPENSSL) + SSL_set_quic_use_legacy_codepoint(ctx->tls.ossl.ssl, 0); + ngtcp2_conn_set_tls_native_handle(ctx->qconn, ctx->tls.ossl.ssl); +#elif defined(USE_GNUTLS) + ngtcp2_conn_set_tls_native_handle(ctx->qconn, ctx->tls.gtls.session); +#elif defined(USE_WOLFSSL) + ngtcp2_conn_set_tls_native_handle(ctx->qconn, ctx->tls.wssl.ssl); +#else +#error "ngtcp2 TLS backend not defined" +#endif + +#if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_EARLYDATA) && \ + defined(OPENSSL_QUIC_API2) + /* We need to tell OpenSSL to *really* use Early Data for QUIC and + * this only works *after* ngtcp2 has tweaked all SSL parameters, + * otherwise OpenSSL does not accept it. */ + if(ctx->use_earlydata && + !SSL_set_quic_tls_early_data_enabled(ctx->tls.ossl.ssl, 1)) { + CURL_TRC_CF(data, cf, "OpenSSL refused to use early data"); + ctx->use_earlydata = FALSE; + cf->connected = FALSE; + } +#endif + ngtcp2_ccerr_default(&ctx->last_error); + + return CURLE_OK; +} + +CURLcode Curl_cf_ngtcp2_cmn_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + struct cf_call_data save; + struct cf_ngtcp2_io_ctx pktx; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* Connect the sub-chain */ + if(cf->next && !cf->next->connected) { + result = Curl_conn_cf_connect(cf->next, data, done); + if(result || !*done) + return result; + } + + *done = FALSE; + + if(cf_ngtcp2_need_httpsrr(data) && + !Curl_conn_dns_resolved_https(data, cf->sockindex, ctx->ssl_peer.peer)) { + CURL_TRC_CF(data, cf, "need HTTPS-RR, delaying connect"); + return CURLE_OK; + } + + Curl_cf_ngtcp2_io_ctx_init(&pktx, cf, data); + CF_DATA_SAVE(save, cf, data); + + if(!ctx->qconn) { + ctx->started_at = *Curl_pgrs_now(data); + result = cf_connect_start(cf, data, &pktx); + if(result) + goto out; + if(cf->connected) { + *done = TRUE; + goto out; + } + result = Curl_cf_ngtcp2_progress_egress(cf, data, &pktx); + /* we do not expect to be able to recv anything yet */ + goto out; + } + + result = Curl_cf_ngtcp2_progress_ingress(cf, data, &pktx); + if(result) + goto out; + + result = Curl_cf_ngtcp2_progress_egress(cf, data, &pktx); + if(result) + goto out; + + if(ngtcp2_conn_get_handshake_completed(ctx->qconn)) { + result = ctx->tls_vrfy_result; + if(!result) { + CURL_TRC_CF(data, cf, "peer verified"); + cf->connected = TRUE; + *done = TRUE; + } + } + +out: + if(ctx->tls_vrfy_result) + result = ctx->tls_vrfy_result; + if(ctx->qconn && + ((result == CURLE_RECV_ERROR) || (result == CURLE_SEND_ERROR)) && + ngtcp2_conn_in_draining_period(ctx->qconn)) { + const ngtcp2_ccerr *cerr = ngtcp2_conn_get_ccerr(ctx->qconn); + + result = CURLE_COULDNT_CONNECT; + if(cerr) { + CURL_TRC_CF(data, cf, "connect error, type=%d, code=%" PRIu64, + (int)cerr->type, cerr->error_code); + switch(cerr->type) { + case NGTCP2_CCERR_TYPE_VERSION_NEGOTIATION: + CURL_TRC_CF(data, cf, "error in version negotiation"); + break; + default: + if(cerr->error_code >= NGTCP2_CRYPTO_ERROR) { + CURL_TRC_CF(data, cf, "crypto error, tls alert=%u", + (unsigned int)(cerr->error_code & 0xffU)); + } + else if(cerr->error_code == NGTCP2_CONNECTION_REFUSED) { + CURL_TRC_CF(data, cf, "connection refused by server"); + /* When a QUIC server instance is shutting down, it may send us a + * CONNECTION_CLOSE with this code right away. We want + * to keep on trying in this case. */ + result = CURLE_WEIRD_SERVER_REPLY; + } + } + } + } + +#ifdef CURLVERBOSE + if(result) { + if(ctx->q.sockfd != CURL_SOCKET_BAD) { + /* Direct UDP socket - get IP info for error reporting */ + struct ip_quadruple ip; + + if(!Curl_cf_socket_peek(cf->next, data, NULL, NULL, &ip)) + infof(data, "QUIC connect to %s port %u failed: %s", + ip.remote_ip, ip.remote_port, curl_easy_strerror(result)); + } + } +#endif + if(!result && ctx->qconn) { + result = Curl_cf_ngtcp2_cmn_set_expiry(cf, data, &pktx); + } + if(result || *done) + CURL_TRC_CF(data, cf, "connect -> %d, done=%d", (int)result, *done); + CF_DATA_RESTORE(cf, save); + return result; +} + +CURLcode Curl_cf_ngtcp2_cmn_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct cf_call_data save; + struct cf_ngtcp2_io_ctx pktx; + CURLcode result = CURLE_OK; + + if(cf->shutdown || !ctx->qconn) { + *done = TRUE; + return CURLE_OK; + } + + if(!cf->next) { + Curl_bufq_reset(&ctx->q.sendbuf); + *done = TRUE; + return CURLE_OK; + } + + CF_DATA_SAVE(save, cf, data); + *done = FALSE; + Curl_cf_ngtcp2_io_ctx_init(&pktx, cf, data); + + if(!ctx->shutdown_started) { + char buffer[NGTCP2_MAX_UDP_PAYLOAD_SIZE]; + ngtcp2_ssize nwritten; + + if(!Curl_bufq_is_empty(&ctx->q.sendbuf)) { + CURL_TRC_CF(data, cf, "shutdown, flushing sendbuf"); + result = Curl_cf_ngtcp2_progress_egress(cf, data, &pktx); + if(!Curl_bufq_is_empty(&ctx->q.sendbuf)) { + CURL_TRC_CF(data, cf, "sending shutdown packets blocked"); + result = CURLE_OK; + goto out; + } + else if(result) { + CURL_TRC_CF(data, cf, "shutdown, error %d flushing sendbuf", + (int)result); + *done = TRUE; + goto out; + } + } + + DEBUGASSERT(Curl_bufq_is_empty(&ctx->q.sendbuf)); + ctx->shutdown_started = TRUE; + nwritten = ngtcp2_conn_write_connection_close( + ctx->qconn, NULL, /* path */ + NULL, /* pkt_info */ + (uint8_t *)buffer, sizeof(buffer), + &ctx->last_error, pktx.ts); + CURL_TRC_CF(data, cf, "start shutdown(err_type=%d, err_code=%" + PRIu64 ") -> %zd", (int)ctx->last_error.type, + ctx->last_error.error_code, (ssize_t)nwritten); + /* there are cases listed in ngtcp2 documentation where this call + * may fail. Since we are doing a connection shutdown as graceful + * as we can, such an error is ignored here. */ + if(nwritten > 0) { + /* Ignore amount written. sendbuf was empty and has always room for + * NGTCP2_MAX_UDP_PAYLOAD_SIZE. It can only completely fail, in which + * case `result` is set non zero. */ + size_t n; + result = Curl_bufq_write(&ctx->q.sendbuf, (const unsigned char *)buffer, + (size_t)nwritten, &n); + if(result) { + CURL_TRC_CF(data, cf, "error %d adding shutdown packets to sendbuf, " + "aborting shutdown", (int)result); + goto out; + } + + ctx->q.no_gso = TRUE; + ctx->q.gsolen = (size_t)nwritten; + ctx->q.split_len = 0; + } + } + + if(!Curl_bufq_is_empty(&ctx->q.sendbuf)) { + CURL_TRC_CF(data, cf, "shutdown, flushing egress"); + result = Curl_vquic_flush(cf, data, &ctx->q); + if(result == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "sending shutdown packets blocked"); + result = CURLE_OK; + goto out; + } + else if(result) { + CURL_TRC_CF(data, cf, "shutdown, error %d flushing sendbuf", + (int)result); + *done = TRUE; + goto out; + } + } + + if(Curl_bufq_is_empty(&ctx->q.sendbuf)) { + /* Sent everything off. ngtcp2 seems to have no support for graceful + * shutdowns. We are done. */ + CURL_TRC_CF(data, cf, "shutdown completely sent off, done"); + *done = TRUE; + result = CURLE_OK; + } +out: + CF_DATA_RESTORE(cf, save); + return result; +} + +void Curl_cf_ngtcp2_cmn_conn_close(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + bool done; + Curl_cf_ngtcp2_cmn_shutdown(cf, data, &done); +} + +static bool cf_ngtcp2_err_is_fatal(int code) +{ + return (NGTCP2_ERR_FATAL >= code) || + (NGTCP2_ERR_DROP_CONN == code) || + (NGTCP2_ERR_IDLE_CLOSE == code); +} + +void Curl_cf_ngtcp2_cmn_err_set(struct Curl_cfilter *cf, + struct Curl_easy *data, int code) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + if(!ctx->last_error.error_code) { + if(NGTCP2_ERR_CRYPTO == code) { + ngtcp2_ccerr_set_tls_alert(&ctx->last_error, + ngtcp2_conn_get_tls_alert(ctx->qconn), + NULL, 0); + } + else { + ngtcp2_ccerr_set_liberr(&ctx->last_error, code, NULL, 0); + } + } + if(cf_ngtcp2_err_is_fatal(code)) + Curl_cf_ngtcp2_cmn_conn_close(cf, data); +} + +void Curl_cf_ngtcp2_io_ctx_init(struct cf_ngtcp2_io_ctx *io_ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + + io_ctx->cf = cf; + io_ctx->data = data; + io_ctx->now = *Curl_pgrs_now(data); + ngtcp2_path_storage_zero(&io_ctx->ps); + Curl_vquic_ctx_set_time(&ctx->q, &io_ctx->now); + io_ctx->ts = ((ngtcp2_tstamp)io_ctx->now.tv_sec * NGTCP2_SECONDS) + + ((ngtcp2_tstamp)io_ctx->now.tv_usec * NGTCP2_MICROSECONDS); +} + +void Curl_cf_ngtcp2_io_ctx_update_time(struct Curl_easy *data, + struct cf_ngtcp2_io_ctx *io_ctx, + struct Curl_cfilter *cf) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + + io_ctx->now = *Curl_pgrs_now(data); + Curl_vquic_ctx_update_time(&ctx->q, &io_ctx->now); + io_ctx->ts = ((ngtcp2_tstamp)io_ctx->now.tv_sec * NGTCP2_SECONDS) + + ((ngtcp2_tstamp)io_ctx->now.tv_usec * NGTCP2_MICROSECONDS); +} + +#if NGTCP2_VERSION_NUM < 0x011100 +struct cf_ngtcp2_sfind_ctx { + int64_t stream_id; + struct h3_stream_ctx *stream; + uint32_t mid; +}; + +static bool cf_ngtcp2_sfind(uint32_t mid, void *value, void *user_data) +{ + struct cf_ngtcp2_sfind_ctx *fctx = user_data; + struct h3_stream_ctx *stream = value; + + if(fctx->stream_id == stream->id) { + fctx->mid = mid; + fctx->stream = stream; + return FALSE; + } + return TRUE; /* continue */ +} + +static struct h3_stream_ctx *cf_ngtcp2_get_stream(struct cf_ngtcp2_ctx *ctx, + int64_t stream_id) +{ + struct cf_ngtcp2_sfind_ctx fctx; + fctx.stream_id = stream_id; + fctx.stream = NULL; + Curl_uint32_hash_visit(&ctx->streams, cf_ngtcp2_sfind, &fctx); + return fctx.stream; +} +#else +static struct h3_stream_ctx *cf_ngtcp2_get_stream(struct cf_ngtcp2_ctx *ctx, + int64_t stream_id) +{ + struct Curl_easy *data = + ngtcp2_conn_get_stream_user_data(ctx->qconn, stream_id); + + if(!data) { + return NULL; + } + + return H3_STREAM_CTX(ctx, data); +} +#endif + +/** + * Read a network packet to send from ngtcp2 into `buf`. + * Return number of bytes written or -1 with *err set. + */ +static CURLcode read_pkt_to_send(void *userp, + unsigned char *buf, size_t buflen, + size_t *pnread) +{ + struct cf_ngtcp2_io_ctx *x = userp; + struct cf_ngtcp2_ctx *ctx = x->cf->ctx; + nghttp3_vec vec[16]; + nghttp3_ssize veccnt; + ngtcp2_ssize ndatalen; + uint32_t flags; + int64_t stream_id; + int fin; + ssize_t n; + + *pnread = 0; + veccnt = 0; + stream_id = -1; + fin = 0; + + /* ngtcp2 may want to put several frames from different streams into + * this packet. `NGTCP2_WRITE_STREAM_FLAG_MORE` tells it to do so. + * When `NGTCP2_ERR_WRITE_MORE` is returned, we *need* to make + * another iteration. + * When ngtcp2 is happy (because it has no other frame that would fit + * or it has nothing more to send), it returns the total length + * of the assembled packet. This may be 0 if there was nothing to send. */ + for(;;) { + + if(ctx->h3conn && ngtcp2_conn_get_max_data_left(ctx->qconn)) { + veccnt = nghttp3_conn_writev_stream(ctx->h3conn, &stream_id, &fin, vec, + CURL_ARRAYSIZE(vec)); + if(veccnt < 0) { + failf(x->data, "nghttp3_conn_writev_stream returned error: %s", + nghttp3_strerror((int)veccnt)); + Curl_cf_ngtcp2_h3_err_set(x->cf, x->data, (int)veccnt); + return CURLE_SEND_ERROR; + } + } + + flags = NGTCP2_WRITE_STREAM_FLAG_MORE | + (fin ? NGTCP2_WRITE_STREAM_FLAG_FIN : 0); + n = ngtcp2_conn_writev_stream(ctx->qconn, &x->ps.path, + NULL, buf, buflen, + &ndatalen, flags, stream_id, + (const ngtcp2_vec *)vec, veccnt, x->ts); + if(n == 0) { + /* nothing to send */ + return CURLE_AGAIN; + } + else if(n < 0) { + switch(n) { + case NGTCP2_ERR_STREAM_DATA_BLOCKED: { + struct h3_stream_ctx *stream; + DEBUGASSERT(ndatalen == -1); + nghttp3_conn_block_stream(ctx->h3conn, stream_id); + CURL_TRC_CF(x->data, x->cf, "[%" PRId64 "] block quic flow", + stream_id); + stream = cf_ngtcp2_get_stream(ctx, stream_id); + if(stream) /* it might be not one of our h3 streams? */ + stream->quic_flow_blocked = TRUE; + n = 0; + break; + } + case NGTCP2_ERR_STREAM_SHUT_WR: + DEBUGASSERT(ndatalen == -1); + nghttp3_conn_shutdown_stream_write(ctx->h3conn, stream_id); + n = 0; + break; + case NGTCP2_ERR_WRITE_MORE: + /* ngtcp2 wants to send more. update the flow of the stream whose data + * is in the buffer and continue */ + DEBUGASSERT(ndatalen >= 0); + n = 0; + break; + default: + DEBUGASSERT(ndatalen == -1); + failf(x->data, "ngtcp2_conn_writev_stream returned error: %s", + ngtcp2_strerror((int)n)); + Curl_cf_ngtcp2_cmn_err_set(x->cf, x->data, (int)n); + return CURLE_SEND_ERROR; + } + } + + if(ndatalen >= 0) { + /* we add the amount of data bytes to the flow windows */ + int rv = nghttp3_conn_add_write_offset(ctx->h3conn, stream_id, ndatalen); + if(rv) { + failf(x->data, "nghttp3_conn_add_write_offset returned error: %s", + nghttp3_strerror(rv)); + return CURLE_SEND_ERROR; + } + } + + if(n > 0) { + /* packet assembled, leave */ + *pnread = (size_t)n; + return CURLE_OK; + } + } +} + +CURLcode Curl_cf_ngtcp2_progress_egress(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_ngtcp2_io_ctx *pktx) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + size_t nread; + size_t max_payload_size, path_max_payload_size; + size_t pktcnt = 0; + size_t gsolen = 0; /* this disables gso until we have a clue */ + size_t send_quantum; + CURLcode result; + struct cf_ngtcp2_io_ctx local_pktx; + + if(!pktx) { + Curl_cf_ngtcp2_io_ctx_init(&local_pktx, cf, data); + pktx = &local_pktx; + } + else { + Curl_cf_ngtcp2_io_ctx_update_time(data, pktx, cf); + ngtcp2_path_storage_zero(&pktx->ps); + } + + result = Curl_vquic_flush(cf, data, &ctx->q); + if(result) { + if(result == CURLE_AGAIN) { + Curl_expire_set(data, EXPIRE_QUIC, 1, &pktx->now); + return CURLE_OK; + } + return result; + } + + /* In UDP, there is a maximum theoretical packet payload length and + * a minimum payload length that is "guaranteed" to work. + * To detect if this minimum payload can be increased, ngtcp2 sends + * now and then a packet payload larger than the minimum. It that + * is ACKed by the peer, both parties know that it works and + * the subsequent packets can use a larger one. + * This is called PMTUD (Path Maximum Transmission Unit Discovery). + * Since a PMTUD might be rejected right on send, we do not want it + * be followed by other packets of lesser size. Because those would + * also fail then. If we detect a PMTUD while buffering, we flush. + */ + max_payload_size = ngtcp2_conn_get_max_tx_udp_payload_size(ctx->qconn); + path_max_payload_size = + ngtcp2_conn_get_path_max_tx_udp_payload_size(ctx->qconn); + send_quantum = ngtcp2_conn_get_send_quantum(ctx->qconn); + CURL_TRC_CF(data, cf, "egress, collect and send packets, quantum=%zu", + send_quantum); + for(;;) { + /* add the next packet to send, if any, to our buffer */ + result = Curl_bufq_sipn(&ctx->q.sendbuf, max_payload_size, + read_pkt_to_send, pktx, &nread); + if(result == CURLE_AGAIN) + break; + else if(result) + return result; + else { + size_t buflen = Curl_bufq_len(&ctx->q.sendbuf); + if((buflen >= send_quantum) || + ((buflen + gsolen) >= ctx->q.sendbuf.chunk_size)) + break; + DEBUGASSERT(nread > 0); + ++pktcnt; + if(pktcnt == 1) { + /* first packet in buffer. This is either of a known, "good" + * payload size or it is a PMTUD. We shall see. */ + gsolen = nread; + } + else if(nread > gsolen || + (gsolen > path_max_payload_size && nread != gsolen)) { + /* The added packet is a PMTUD *or* the one(s) before the added were + * PMTUD and the last one is smaller. Flush the buffer before the last + * add. */ + result = Curl_vquic_send_tail_split(cf, data, &ctx->q, + gsolen, nread, nread); + if(result) { + if(result == CURLE_AGAIN) { + Curl_expire_set(data, EXPIRE_QUIC, 1, &pktx->now); + return CURLE_OK; + } + return result; + } + pktcnt = 0; + } + else if(nread < gsolen) { + /* Reached capacity of our buffer *or* + * last add was shorter than the previous ones, flush */ + break; + } + } + } + + if(!Curl_bufq_is_empty(&ctx->q.sendbuf)) { + /* time to send */ + CURL_TRC_CF(data, cf, "egress, send collected %zu packets in %zu bytes", + pktcnt, Curl_bufq_len(&ctx->q.sendbuf)); + result = Curl_vquic_send(cf, data, &ctx->q, gsolen); + if(result) { + if(result == CURLE_AGAIN) { + Curl_expire_set(data, EXPIRE_QUIC, 1, &pktx->now); + return CURLE_OK; + } + return result; + } + Curl_cf_ngtcp2_io_ctx_update_time(data, pktx, cf); + ngtcp2_conn_update_pkt_tx_time(ctx->qconn, pktx->ts); + } + return CURLE_OK; +} + +struct cf_ngtcp2_recv_ctx { + struct cf_ngtcp2_io_ctx *pktx; + size_t pkt_count; +}; + +static CURLcode cf_ngtcp2_recv_pkts(const unsigned char *buf, size_t buflen, + size_t gso_size, + struct sockaddr_storage *remote_addr, + socklen_t remote_addrlen, uint8_t ecn, + void *userp) +{ + struct cf_ngtcp2_recv_ctx *rctx = userp; + struct cf_ngtcp2_io_ctx *pktx = rctx->pktx; + struct cf_ngtcp2_ctx *ctx = pktx->cf->ctx; + ngtcp2_pkt_info pi; + ngtcp2_path path; + size_t offset, pktlen; + int rv; + + if(!rctx->pkt_count) { + Curl_cf_ngtcp2_io_ctx_update_time(pktx->data, pktx, pktx->cf); + ngtcp2_path_storage_zero(&pktx->ps); + } + + if(ecn) + CURL_TRC_CF(pktx->data, pktx->cf, "vquic_recv(len=%zu, gso=%zu, ecn=%x)", + buflen, gso_size, (unsigned)ecn); + ngtcp2_addr_init(&path.local, (struct sockaddr *)&ctx->q.local_addr, + ctx->q.local_addrlen); + ngtcp2_addr_init(&path.remote, (struct sockaddr *)remote_addr, + remote_addrlen); + pi.ecn = (uint8_t)ecn; + + for(offset = 0; offset < buflen; offset += gso_size) { + rctx->pkt_count++; + pktlen = ((offset + gso_size) <= buflen) ? gso_size : (buflen - offset); + rv = ngtcp2_conn_read_pkt(ctx->qconn, &path, &pi, + buf + offset, pktlen, pktx->ts); + if(rv) { + CURL_TRC_CF(pktx->data, pktx->cf, "ingress, read_pkt -> %s (%d)", + ngtcp2_strerror(rv), rv); + Curl_cf_ngtcp2_cmn_err_set(pktx->cf, pktx->data, rv); + + if(rv == NGTCP2_ERR_CRYPTO) + /* this is a "TLS problem", but a failed certificate verification + is a common reason for this */ + return CURLE_PEER_FAILED_VERIFICATION; + return CURLE_RECV_ERROR; + } + } + return CURLE_OK; +} + +CURLcode Curl_cf_ngtcp2_progress_ingress(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_ngtcp2_io_ctx *pktx) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct cf_ngtcp2_io_ctx local_pktx; + struct cf_ngtcp2_recv_ctx rctx; + CURLcode result = CURLE_OK; + + if(!pktx) { + Curl_cf_ngtcp2_io_ctx_init(&local_pktx, cf, data); + pktx = &local_pktx; + } + + result = Curl_vquic_tls_before_recv(&ctx->tls, cf, data); + if(result) + return result; + + rctx.pktx = pktx; + rctx.pkt_count = 0; + + if(ctx->q.sockfd != CURL_SOCKET_BAD) { + /* Direct UDP socket (via happy eyeballs) */ + CURL_TRC_CF(data, cf, "progress_ingress(socket)"); + return Curl_vquic_recv_packets(cf, data, &ctx->q, 1000, + cf_ngtcp2_recv_pkts, &rctx); + } + else { + /* Tunneled QUIC (CONNECT-UDP through proxy) */ + unsigned char *buf; + size_t max_udp_payload = QUIC_TUNNEL_INBUF_SIZE; + size_t pkt_limit = QUIC_TUNNEL_INGRESS_PKT_LIMIT; + size_t nread; + struct sockaddr_storage remote_addr; + socklen_t remote_addrlen; + + CURL_TRC_CF(data, cf, "progress_ingress(sub-filters)"); + if(ctx->qconn) { + size_t max_path_payload; + max_path_payload = + ngtcp2_conn_get_path_max_tx_udp_payload_size(ctx->qconn); + if(max_path_payload > max_udp_payload) + max_udp_payload = max_path_payload; + } + + if(ctx->tunnel_inbuf_len < max_udp_payload) { + unsigned char *newbuf = curlx_realloc(ctx->tunnel_inbuf, + max_udp_payload); + if(!newbuf) + return CURLE_OUT_OF_MEMORY; + ctx->tunnel_inbuf = newbuf; + ctx->tunnel_inbuf_len = max_udp_payload; + } + buf = ctx->tunnel_inbuf; + + while(pkt_limit--) { + result = Curl_conn_cf_recv(cf->next, data, (char *)buf, + ctx->tunnel_inbuf_len, &nread); + if(result == CURLE_AGAIN) { + /* no more data available at the moment */ + return CURLE_OK; + } + if(result) { + CURL_TRC_CF(data, cf, "ingress, recv from tunnel failed: %d", + (int)result); + return result; + } + if(nread == 0) { + /* tunnel closed */ + return CURLE_OK; + } + + memcpy(&remote_addr, ctx->connected_path.remote.addr, + ctx->connected_path.remote.addrlen); + remote_addrlen = (socklen_t)ctx->connected_path.remote.addrlen; + result = cf_ngtcp2_recv_pkts(buf, nread, nread, &remote_addr, + remote_addrlen, 0, &rctx); + if(result) + return result; + + if(!ctx->q.got_first_byte) { + ctx->q.got_first_byte = TRUE; + ctx->q.first_byte_at = ctx->q.last_op; + } + ctx->q.last_io = ctx->q.last_op; + } + return CURLE_OK; + } +} + +/** + * Connection maintenance like timeouts on packet ACKs etc. are done by us, not + * the OS like for TCP. POLL events on the socket therefore are not + * sufficient. + * ngtcp2 tells us when it wants to be invoked again. We handle that via + * the `Curl_expire()` mechanisms. + */ +CURLcode Curl_cf_ngtcp2_cmn_set_expiry(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_ngtcp2_io_ctx *pktx) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct cf_ngtcp2_io_ctx local_pktx; + ngtcp2_tstamp expiry; + + if(!pktx) { + Curl_cf_ngtcp2_io_ctx_init(&local_pktx, cf, data); + pktx = &local_pktx; + } + else { + Curl_cf_ngtcp2_io_ctx_update_time(data, pktx, cf); + } + + expiry = ngtcp2_conn_get_expiry(ctx->qconn); + if(expiry != UINT64_MAX) { + if(expiry <= pktx->ts) { + CURLcode result; + int rv = ngtcp2_conn_handle_expiry(ctx->qconn, pktx->ts); + if(rv) { + failf(data, "ngtcp2_conn_handle_expiry returned error: %s", + ngtcp2_strerror(rv)); + Curl_cf_ngtcp2_cmn_err_set(cf, data, rv); + return CURLE_SEND_ERROR; + } + result = Curl_cf_ngtcp2_progress_ingress(cf, data, pktx); + if(!result) + result = Curl_cf_ngtcp2_progress_egress(cf, data, pktx); + if(result) { + /* a verify failure during ingress must win over generic errors */ + if(ctx->tls_vrfy_result) + result = ctx->tls_vrfy_result; + return result; + } + /* ask again, things might have changed */ + expiry = ngtcp2_conn_get_expiry(ctx->qconn); + } + + if(expiry > pktx->ts) { + ngtcp2_duration timeout = expiry - pktx->ts; + if(timeout % NGTCP2_MILLISECONDS) { + timeout += NGTCP2_MILLISECONDS; + } + Curl_expire_set(data, EXPIRE_QUIC, + (timediff_t)(timeout / NGTCP2_MILLISECONDS), + &pktx->now); + } + } + return CURLE_OK; +} + +static void cf_ngtcp2_setup_keep_alive(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + const ngtcp2_transport_params *rp; + /* Peer should have sent us its transport parameters. If it + * announces a positive `max_idle_timeout` it closes the + * connection when it does not hear from us for that time. + * + * Some servers use this as a keep-alive timer at a rather low + * value. We are doing HTTP/3 here and waiting for the response + * to a request may take a considerable amount of time. We need + * to prevent the peer's QUIC stack from closing in this case. + */ + if(!ctx->qconn) + return; + + rp = ngtcp2_conn_get_remote_transport_params(ctx->qconn); + if(!rp || !rp->max_idle_timeout) { + ngtcp2_conn_set_keep_alive_timeout(ctx->qconn, UINT64_MAX); + CURL_TRC_CF(data, cf, "no peer idle timeout, unset keep-alive"); + } + else if(!Curl_uint32_hash_count(&ctx->streams)) { + ngtcp2_conn_set_keep_alive_timeout(ctx->qconn, UINT64_MAX); + CURL_TRC_CF(data, cf, "no active streams, unset keep-alive"); + } + else { + ngtcp2_duration keep_ns; + keep_ns = (rp->max_idle_timeout > 1) ? (rp->max_idle_timeout / 2) : 1; + ngtcp2_conn_set_keep_alive_timeout(ctx->qconn, keep_ns); + CURL_TRC_CF(data, cf, "peer idle timeout is %" PRIu64 "ms, " + "set keep-alive to %" PRIu64 " ms.", + (rp->max_idle_timeout / NGTCP2_MILLISECONDS), + (keep_ns / NGTCP2_MILLISECONDS)); + } +} + +CURLcode Curl_cf_ngtcp2_h3_stream_setup(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + if(!data) + return CURLE_FAILED_INIT; + + if(stream) + return CURLE_OK; + + stream = curlx_calloc(1, sizeof(*stream)); + if(!stream) + return CURLE_OUT_OF_MEMORY; + + stream->id = -1; + stream->rx_offset = 0; + stream->rx_offset_max = H3_STREAM_WINDOW_SIZE_INITIAL; + stream->tx_in_flight_ideal = H3_STREAM_SEND_BUF_INITIAL; + + /* on send, we control how much we put into the buffer */ + Curl_bufq_initp(&stream->sendbuf, &ctx->stream_bufcp, + H3_STREAM_SEND_CHUNKS, BUFQ_OPT_NONE); + stream->tx_in_flight_size = 0; + stream->window_size_max = H3_STREAM_WINDOW_SIZE_INITIAL; + Curl_h1_req_parse_init(&stream->h1, H1_PARSE_DEFAULT_MAX_LINE_LEN); + + if(!Curl_uint32_hash_set(&ctx->streams, data->mid, stream)) { + Curl_cf_ngtcp2_h3_stream_ctx_free(stream); + return CURLE_OUT_OF_MEMORY; + } + + if(Curl_uint32_hash_count(&ctx->streams) == 1) + cf_ngtcp2_setup_keep_alive(cf, data); + + return CURLE_OK; +} + +void Curl_cf_ngtcp2_h3_stream_close(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + DEBUGASSERT(data); + DEBUGASSERT(stream); + if(!stream->closed && ctx->qconn && ctx->h3conn) { + CURLcode result; + + nghttp3_conn_set_stream_user_data(ctx->h3conn, stream->id, NULL); + ngtcp2_conn_set_stream_user_data(ctx->qconn, stream->id, NULL); + stream->closed = TRUE; + (void)ngtcp2_conn_shutdown_stream(ctx->qconn, 0, stream->id, + NGHTTP3_H3_REQUEST_CANCELLED); + result = Curl_cf_ngtcp2_progress_egress(cf, data, NULL); + if(result) + CURL_TRC_CF(data, cf, "[%" PRId64 "] cancel stream -> %d", + stream->id, (int)result); + } +} + +void Curl_cf_ngtcp2_h3_stream_done(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + (void)cf; + if(stream) { + CURL_TRC_CF(data, cf, "[%" PRId64 "] easy handle is done", stream->id); + Curl_cf_ngtcp2_h3_stream_close(cf, data, stream); + Curl_uint32_hash_remove(&ctx->streams, data->mid); + if(!Curl_uint32_hash_count(&ctx->streams)) + cf_ngtcp2_setup_keep_alive(cf, data); + } +} + +bool Curl_cf_ngtcp2_cmn_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + bool alive = FALSE; + const ngtcp2_transport_params *rp; + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + *input_pending = FALSE; + if(!ctx->qconn || ctx->shutdown_started) + goto out; + + /* We do not announce a max idle timeout, but when the peer does + * it closes the connection when it expires. */ + rp = ngtcp2_conn_get_remote_transport_params(ctx->qconn); + if(rp && rp->max_idle_timeout) { + timediff_t idletime_ms = + curlx_ptimediff_ms(Curl_pgrs_now(data), &ctx->q.last_io); + if(idletime_ms > 0) { + uint64_t max_idle_ms = + (uint64_t)(rp->max_idle_timeout / NGTCP2_MILLISECONDS); + if((uint64_t)idletime_ms > max_idle_ms) + goto out; + } + } + + if(!cf->next || !cf->next->cft->is_alive(cf->next, data, input_pending)) + goto out; + + alive = TRUE; + if(*input_pending) { + CURLcode result; + /* This happens before we have sent off a request and the connection is + not in use by any other transfer, there should not be any data here, + only "protocol frames" */ + *input_pending = FALSE; + result = Curl_cf_ngtcp2_progress_ingress(cf, data, NULL); + CURL_TRC_CF(data, cf, "is_alive, progress ingress -> %d", (int)result); + alive = result ? FALSE : TRUE; + } + +out: + CF_DATA_RESTORE(cf, save); + return alive; +} + +CURLcode Curl_cf_ngtcp2_h3_init_ctrls(struct cf_ngtcp2_ctx *ctx, + struct Curl_easy *data) +{ + int64_t ctrl_stream_id, qpack_enc_stream_id, qpack_dec_stream_id; + int rc; + + rc = ngtcp2_conn_open_uni_stream(ctx->qconn, &ctrl_stream_id, NULL); + if(rc) { + failf(data, "error creating HTTP/3 control stream: %s", + ngtcp2_strerror(rc)); + return CURLE_QUIC_CONNECT_ERROR; + } + rc = nghttp3_conn_bind_control_stream(ctx->h3conn, ctrl_stream_id); + if(rc) { + failf(data, "error binding HTTP/3 control stream: %s", + ngtcp2_strerror(rc)); + return CURLE_QUIC_CONNECT_ERROR; + } + rc = ngtcp2_conn_open_uni_stream(ctx->qconn, &qpack_enc_stream_id, NULL); + if(rc) { + failf(data, "error creating HTTP/3 qpack encoding stream: %s", + ngtcp2_strerror(rc)); + return CURLE_QUIC_CONNECT_ERROR; + } + rc = ngtcp2_conn_open_uni_stream(ctx->qconn, &qpack_dec_stream_id, NULL); + if(rc) { + failf(data, "error creating HTTP/3 qpack decoding stream: %s", + ngtcp2_strerror(rc)); + return CURLE_QUIC_CONNECT_ERROR; + } + rc = nghttp3_conn_bind_qpack_streams(ctx->h3conn, qpack_enc_stream_id, + qpack_dec_stream_id); + if(rc) { + failf(data, "error binding HTTP/3 qpack streams: %s", ngtcp2_strerror(rc)); + return CURLE_QUIC_CONNECT_ERROR; + } + return CURLE_OK; +} + +CURLcode Curl_cf_ngtcp2_cmn_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + + switch(query) { + case CF_QUERY_CONNECT_REPLY_MS: + if((ctx->q.sockfd != CURL_SOCKET_BAD) && ctx->q.got_first_byte) { + timediff_t ms = curlx_ptimediff_ms(&ctx->q.first_byte_at, + &ctx->started_at); + *pres1 = (ms < INT_MAX) ? (int)ms : INT_MAX; + return CURLE_OK; + } + break; + case CF_QUERY_REALLY_CONNECTED: + if(ctx->q.sockfd != CURL_SOCKET_BAD) { + *pres1 = ctx->q.got_first_byte; + return CURLE_OK; + } + break; + default: + break; + } + return cf->next ? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +CURLcode Curl_cf_ngtcp2_cmn_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + (void)arg1; + (void)arg2; + switch(event) { + case CF_CTRL_REPORT_STATS: + if(cf->connected && !ctx->stats_reported) { + if((cf->cft->flags & CF_TYPE_PROXY) && + (ctx->q.sockfd != CURL_SOCKET_BAD) && ctx->q.got_first_byte) { + Curl_pgrsTimeWas(data, TIMER_CONNECT, ctx->q.first_byte_at); + ctx->stats_reported = TRUE; + } + else if(ctx->handshake_at.tv_sec || ctx->handshake_at.tv_usec) { + if(ctx->q.sockfd != CURL_SOCKET_BAD) + Curl_pgrsTimeWas(data, TIMER_CONNECT, ctx->q.first_byte_at); + Curl_pgrsTimeWas(data, TIMER_APPCONNECT, ctx->handshake_at); + ctx->stats_reported = TRUE; + } + } + break; + default: + break; + } + return result; +} + +#endif /* !CURL_DISABLE_HTTP && USE_NGTCP2 && USE_NGHTTP3 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2-cmn.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2-cmn.h new file mode 100644 index 0000000000..e0c27a95f7 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2-cmn.h @@ -0,0 +1,253 @@ +#ifndef HEADER_CURL_VQUIC_CF_NGTCP2_CMN_H +#define HEADER_CURL_VQUIC_CF_NGTCP2_CMN_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_NGTCP2) && defined(USE_NGHTTP3) + +#include <ngtcp2/ngtcp2.h> +#include <ngtcp2/ngtcp2_crypto.h> + +#ifdef USE_OPENSSL +#include <openssl/err.h> +#if defined(OPENSSL_IS_AWSLC) || defined(OPENSSL_IS_BORINGSSL) +#include <ngtcp2/ngtcp2_crypto_boringssl.h> +#elif defined(OPENSSL_QUIC_API2) +#include <ngtcp2/ngtcp2_crypto_ossl.h> +#else +#include <ngtcp2/ngtcp2_crypto_quictls.h> +#endif +#include "vtls/openssl.h" +#elif defined(USE_GNUTLS) +#include <ngtcp2/ngtcp2_crypto_gnutls.h> +#include "vtls/gtls.h" +#elif defined(USE_WOLFSSL) +#include <wolfssl/options.h> +#include <wolfssl/ssl.h> +#include <wolfssl/quic.h> +#include <ngtcp2/ngtcp2_crypto_wolfssl.h> +#include "vtls/wolfssl.h" +#endif + +#ifdef HAVE_NETINET_UDP_H +#include <netinet/udp.h> +#endif + +#include <nghttp3/nghttp3.h> + +#include "http1.h" +#include "uint-hash.h" +#include "vtls/vtls.h" +#include "vquic/vquic_int.h" +#include "vquic/vquic-tls.h" + +struct Curl_cfilter; +struct Curl_easy; +struct cf_ngtcp2_ctx; +struct cf_quic_ctx; + +#define QUIC_MAX_STREAMS (256 * 1024) +#define QUIC_HANDSHAKE_TIMEOUT (10 * NGTCP2_SECONDS) +#define QUIC_TUNNEL_INBUF_SIZE (64 * 1024) + +/* We announce a small window size in transport param to the server, + * and grow that immediately to max when no rate limit is in place. + * We need to start small as we are not able to decrease it. */ +#define H3_STREAM_WINDOW_SIZE_INITIAL (32 * 1024) +#define H3_STREAM_WINDOW_SIZE_MAX (10 * 1024 * 1024) +#define H3_CONN_WINDOW_SIZE_MAX (100 * H3_STREAM_WINDOW_SIZE_MAX) + +#define H3_STREAM_CHUNK_SIZE (64 * 1024) +#if H3_STREAM_CHUNK_SIZE < NGTCP2_MAX_UDP_PAYLOAD_SIZE +#error H3_STREAM_CHUNK_SIZE smaller than NGTCP2_MAX_UDP_PAYLOAD_SIZE +#endif +/* The pool keeps spares around and half of a full stream window + * seems good. More does not seem to improve performance. + * The benefit of the pool is that stream buffers do not keep + * spares. Memory consumption goes down when streams run empty, + * have a large upload done, etc. */ +#define H3_STREAM_POOL_SPARES 2 +/* The max amount of un-acked upload data we keep around per stream */ +#define H3_STREAM_SEND_BUFFER_MAX (10 * 1024 * 1024) +#define H3_STREAM_SEND_CHUNKS \ + (H3_STREAM_SEND_BUFFER_MAX / H3_STREAM_CHUNK_SIZE) +/* How much data we initially want to buffer un-acked */ +#define H3_STREAM_SEND_BUF_INITIAL (32 * 1024) + +#define QUIC_TUNNEL_INGRESS_PKT_LIMIT 1000 + + +void Curl_ngtcp2_ver(char *p, size_t len); + +typedef CURLcode cf_ngtcp2_init_h3_conn(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_ngtcp2_ctx *ctx); + +struct cf_ngtcp2_ctx { + struct cf_quic_ctx q; + struct ssl_peer ssl_peer; + struct curl_tls_ctx tls; +#ifdef OPENSSL_QUIC_API2 + ngtcp2_crypto_ossl_ctx *ossl_ctx; +#endif + ngtcp2_path connected_path; + ngtcp2_conn *qconn; + ngtcp2_cid dcid; + ngtcp2_cid scid; + uint32_t version; + ngtcp2_settings settings; + ngtcp2_transport_params transport_params; + ngtcp2_ccerr last_error; + ngtcp2_crypto_conn_ref conn_ref; + struct cf_call_data call_data; + cf_ngtcp2_init_h3_conn *init_h3_conn_cb; + nghttp3_conn *h3conn; + nghttp3_settings h3settings; + struct curltime started_at; /* time the current attempt started */ + struct curltime handshake_at; /* time connect handshake finished */ + struct bufc_pool stream_bufcp; /* chunk pool for streams */ + struct dynbuf scratch; /* temp buffer for header construction */ + struct uint_hash streams; /* hash data->mid to h3_stream_ctx */ + uint64_t used_bidi_streams; /* bidi streams we have opened */ + uint64_t max_bidi_streams; /* max bidi streams we can open */ + size_t earlydata_max; /* max amount of early data supported by + server on session reuse */ + size_t earlydata_skip; /* sending bytes to skip when earlydata + is accepted by peer */ + CURLcode tls_vrfy_result; /* result of TLS peer verification */ + int qlogfd; + unsigned char *tunnel_inbuf; /* ingress buffer for tunneled packets */ + size_t tunnel_inbuf_len; + BIT(initialized); + BIT(tls_handshake_complete); /* TLS handshake is done */ + BIT(use_earlydata); /* Using 0RTT data */ + BIT(earlydata_accepted); /* 0RTT was accepted by server */ + BIT(shutdown_started); /* queued shutdown packets */ + BIT(stats_reported); /* connect statistics reported */ +}; + +/* How to access `call_data` from a cf_ngtcp2 filter */ +#undef CF_CTX_CALL_DATA +#define CF_CTX_CALL_DATA(cf) ((struct cf_ngtcp2_ctx *)(cf)->ctx)->call_data + +CURLcode Curl_cf_ngtcp2_ctx_init(struct cf_ngtcp2_ctx *ctx, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct ssl_primary_config *sslc, + cf_ngtcp2_init_h3_conn *init_h3_conn_cb); +void Curl_cf_ngtcp2_ctx_cleanup(struct cf_ngtcp2_ctx *ctx); +void Curl_cf_ngtcp2_cmn_err_set(struct Curl_cfilter *cf, + struct Curl_easy *data, int code); + +/** + * All about the H3 internals of a stream + */ +struct h3_stream_ctx { + int64_t id; /* HTTP/3 stream identifier */ + struct bufq sendbuf; /* h3 request body */ + struct h1_req_parser h1; /* h1 request parsing */ + uint64_t error3; /* HTTP/3 stream error code */ + curl_off_t upload_left; /* number of request bytes left to upload */ + curl_off_t rx_total; /* total number of bytes received */ + uint64_t rx_offset; /* current receive offset */ + uint64_t rx_offset_max; /* allowed receive offset */ + uint64_t window_size_max; /* max flow control window set for stream */ + size_t tx_in_flight_size; /* sendbuf data "in flight" */ + size_t tx_in_flight_ideal; /* ideal amount of un-acked send data */ + int status_code; /* HTTP status code */ + CURLcode xfer_result; /* result from xfer_resp_write(_hd) */ + BIT(resp_hds_complete); /* we have a complete, final response */ + BIT(closed); /* TRUE on stream close */ + BIT(reset); /* TRUE on stream reset */ + BIT(send_closed); /* stream is local closed */ + BIT(quic_flow_blocked); /* stream is blocked by QUIC flow control */ +}; + +void Curl_cf_ngtcp2_h3_stream_ctx_free(struct h3_stream_ctx *stream); +void Curl_cf_ngtcp2_h3_err_set(struct Curl_cfilter *cf, + struct Curl_easy *data, int code); + +CURLcode Curl_cf_ngtcp2_h3_init_ctrls(struct cf_ngtcp2_ctx *ctx, + struct Curl_easy *data); + +CURLcode Curl_cf_ngtcp2_cmn_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done); + +CURLcode Curl_cf_ngtcp2_cmn_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done); +void Curl_cf_ngtcp2_cmn_conn_close(struct Curl_cfilter *cf, + struct Curl_easy *data); + +struct cf_ngtcp2_io_ctx { + struct Curl_cfilter *cf; + struct Curl_easy *data; + struct curltime now; + ngtcp2_tstamp ts; + ngtcp2_path_storage ps; +}; + +void Curl_cf_ngtcp2_io_ctx_init(struct cf_ngtcp2_io_ctx *io_ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data); +void Curl_cf_ngtcp2_io_ctx_update_time(struct Curl_easy *data, + struct cf_ngtcp2_io_ctx *io_ctx, + struct Curl_cfilter *cf); + +CURLcode Curl_cf_ngtcp2_progress_egress(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_ngtcp2_io_ctx *pktx); + +CURLcode Curl_cf_ngtcp2_progress_ingress(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_ngtcp2_io_ctx *pktx); + +CURLcode Curl_cf_ngtcp2_cmn_set_expiry(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_ngtcp2_io_ctx *pktx); + +CURLcode Curl_cf_ngtcp2_h3_stream_setup(struct Curl_cfilter *cf, + struct Curl_easy *data); +void Curl_cf_ngtcp2_h3_stream_close(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream); +void Curl_cf_ngtcp2_h3_stream_done(struct Curl_cfilter *cf, + struct Curl_easy *data); + +bool Curl_cf_ngtcp2_cmn_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending); + +CURLcode Curl_cf_ngtcp2_cmn_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2); + +CURLcode Curl_cf_ngtcp2_cmn_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2); + +#endif /* !CURL_DISABLE_HTTP && USE_NGTCP2 && USE_NGHTTP3 */ + +#endif /* HEADER_CURL_VQUIC_CF_NGTCP2_CMN_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2-proxy.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2-proxy.c new file mode 100644 index 0000000000..89bf19cc27 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2-proxy.c @@ -0,0 +1,1329 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_PROXY) && \ + defined(USE_PROXY_HTTP3) && defined(USE_NGHTTP3) && \ + defined(USE_NGTCP2) && defined(USE_OPENSSL) + +#include "urldata.h" +#include "url.h" +#include "curl_trc.h" +#include "sendf.h" +#include "multiif.h" +#include "cfilters.h" +#include "connect.h" +#include "progress.h" +#include "curlx/dynbuf.h" +#include "http_proxy.h" +#include "vquic/vquic.h" +#include "vquic/cf-ngtcp2-cmn.h" +#include "vquic/cf-ngtcp2-proxy.h" +#include "capsule.h" + +/* A stream window is the maximum amount we need to buffer for + * each active transfer. We use HTTP/3 flow control and only ACK + * when we take things out of the buffer. + * Chunk size is large enough to take a full DATA frame */ +#define PROXY_H3_STREAM_RECV_CHUNKS ((512 * 1024) / H3_STREAM_CHUNK_SIZE) + +typedef enum { + H3_TUNNEL_INIT, /* init/default/no tunnel state */ + H3_TUNNEL_CONNECT, /* CONNECT request is being sent */ + H3_TUNNEL_RESPONSE, /* CONNECT response received completely */ + H3_TUNNEL_ESTABLISHED, + H3_TUNNEL_FAILED +} h3_tunnel_state; + +struct h3_tunnel_stream { + struct Curl_peer *peer; /* where the tunnel goes to */ + struct http_resp *resp; + struct bufq recvbuf; + char *authority; + struct h3_stream_ctx *stream; + h3_tunnel_state state; + BIT(udp); + BIT(has_final_response); + BIT(closed); +}; + +static CURLcode h3_tunnel_stream_init(struct h3_tunnel_stream *ts, + struct Curl_peer *peer, + bool udp) +{ + ts->state = H3_TUNNEL_INIT; + Curl_peer_link(&ts->peer, peer); + Curl_bufq_init2(&ts->recvbuf, H3_STREAM_CHUNK_SIZE, + PROXY_H3_STREAM_RECV_CHUNKS, BUFQ_OPT_SOFT_LIMIT); + ts->udp = udp; + /* host:port with IPv6 support */ + ts->authority = curl_maprintf("%s%s%s:%u", peer->ipv6 ? "[" : "", + peer->hostname, + peer->ipv6 ? "]" : "", + peer->port); + if(!ts->authority) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static void h3_tunnel_stream_reset(struct h3_tunnel_stream *ts) +{ + Curl_bufq_reset(&ts->recvbuf); + Curl_http_resp_free(ts->resp); + ts->resp = NULL; + ts->stream = NULL; + ts->has_final_response = FALSE; + ts->closed = FALSE; + ts->state = H3_TUNNEL_INIT; +} + +static void h3_tunnel_stream_cleanup(struct h3_tunnel_stream *ts) +{ + Curl_peer_unlink(&ts->peer); + Curl_bufq_free(&ts->recvbuf); + Curl_http_resp_free(ts->resp); + curlx_safefree(ts->authority); + ts->state = H3_TUNNEL_INIT; +} + +static void h3_tunnel_go_state(struct Curl_cfilter *cf, + struct h3_tunnel_stream *ts, + h3_tunnel_state new_state, + struct Curl_easy *data) +{ + VERBOSE(int64_t stream_id = ts->stream ? ts->stream->id : -1); + (void)cf; + + if(ts->state == new_state) + return; + + /* leaving this one */ + switch(ts->state) { + case H3_TUNNEL_CONNECT: + data->req.ignorebody = FALSE; + break; + default: + break; + } + + /* entering this one */ + switch(new_state) { + case H3_TUNNEL_INIT: + CURL_TRC_CF(data, cf, "[%" PRId64 "] -> [init]", stream_id); + h3_tunnel_stream_reset(ts); + break; + case H3_TUNNEL_CONNECT: + CURL_TRC_CF(data, cf, "[%" PRId64 "] -> [connect]", stream_id); + ts->state = H3_TUNNEL_CONNECT; + break; + case H3_TUNNEL_RESPONSE: + CURL_TRC_CF(data, cf, "[%" PRId64 "] -> [response]", stream_id); + ts->state = H3_TUNNEL_RESPONSE; + break; + case H3_TUNNEL_ESTABLISHED: + CURL_TRC_CF(data, cf, "[%" PRId64 "] -> [established]", stream_id); + infof(data, "CONNECT%s phase completed for HTTP/3 proxy", + ts->udp ? "-UDP" : ""); + data->state.authproxy.done = TRUE; + data->state.authproxy.multipass = FALSE; + ts->state = new_state; + curlx_safefree(data->req.hd_proxy_auth); + break; + case H3_TUNNEL_FAILED: + CURL_TRC_CF(data, cf, "[%" PRId64 "] -> [failed]", stream_id); + ts->state = new_state; + /* If a proxy-authorization header was used for the proxy, then we should + make sure that it is not accidentally used for the document request + after we have connected. So let's free and clear it here. */ + curlx_safefree(data->req.hd_proxy_auth); + break; + } +} + +struct cf_h3_proxy_ctx { + struct cf_ngtcp2_ctx ngtcp2_ctx; + struct h3_tunnel_stream tunnel; /* our tunnel CONNECT stream */ + BIT(connected); +}; + +static CURLcode cf_ngtcp2_proxy_h3_init(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_ngtcp2_ctx *ctx); + +static CURLcode cf_h3_proxy_ctx_init(struct cf_h3_proxy_ctx *ctx, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct ssl_primary_config *sslc, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport) +{ + CURLcode result; + result = Curl_cf_ngtcp2_ctx_init(&ctx->ngtcp2_ctx, origin, peer, + sslc, cf_ngtcp2_proxy_h3_init); + if(!result) + result = h3_tunnel_stream_init(&ctx->tunnel, tunnel_peer, + TRNSPRT_IS_DGRAM(tunnel_transport)); + return result; +} + +static void cf_h3_proxy_ctx_free(struct cf_h3_proxy_ctx *ctx) +{ + if(ctx) { + Curl_cf_ngtcp2_ctx_cleanup(&ctx->ngtcp2_ctx); + h3_tunnel_stream_cleanup(&ctx->tunnel); + curlx_free(ctx); + } +} + +static int cb_h3_proxy_acked_req_body(nghttp3_conn *conn, int64_t stream_id, + uint64_t datalen, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_h3_proxy_ctx *pctx = cf->ctx; + struct h3_stream_ctx *stream; + size_t skiplen; + (void)stream_user_data; + + stream = pctx->tunnel.stream; + if(!stream || (stream->id != stream_id)) + return 0; + + /* The server acknowledged `datalen` of bytes from our request body. + * This is a delta. We have kept this data in `sendbuf` for + * re-transmissions and can free it now. */ + if(datalen >= (uint64_t)stream->tx_in_flight_size) + skiplen = stream->tx_in_flight_size; + else + skiplen = (size_t)datalen; + Curl_bufq_skip(&stream->sendbuf, skiplen); + stream->tx_in_flight_size -= skiplen; + + /* Resume upload processing if we have more data to send */ + if(stream->tx_in_flight_size < Curl_bufq_len(&stream->sendbuf)) { + int rv = nghttp3_conn_resume_stream(conn, stream_id); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + return NGHTTP3_ERR_CALLBACK_FAILURE; + } + } + return 0; +} + +static int cb_h3_proxy_stream_close(nghttp3_conn *conn, int64_t stream_id, + uint64_t app_error_code, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_h3_proxy_ctx *pctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + struct h3_stream_ctx *stream; + + (void)conn; + (void)stream_user_data; + if(!data) + return NGHTTP3_ERR_CALLBACK_FAILURE; + + stream = pctx->tunnel.stream; + if(!stream || (stream->id != stream_id)) + return 0; + + stream->closed = TRUE; + stream->error3 = app_error_code; + if(stream->error3 != NGHTTP3_H3_NO_ERROR) { + stream->reset = TRUE; + stream->send_closed = TRUE; + CURL_TRC_CF(data, cf, "[%" PRId64 "] RESET: error %" PRIu64, + stream->id, stream->error3); + } + else + CURL_TRC_CF(data, cf, "[%" PRId64 "] CLOSED", stream->id); + pctx->tunnel.stream = NULL; + pctx->tunnel.closed = TRUE; + Curl_multi_mark_dirty(data); + return 0; +} + +static void cf_h3_proxy_upd_rx_win(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream) +{ + struct cf_h3_proxy_ctx *pctx = cf->ctx; + struct cf_ngtcp2_ctx *ctx = &pctx->ngtcp2_ctx; + uint64_t cur_win, wanted_win = H3_STREAM_WINDOW_SIZE_MAX; + + /* how much does rate limiting allow us to acknowledge? */ + if(Curl_rlimit_active(&data->progress.dl.rlimit)) { + int64_t avail; + + /* start rate limit updates only after first bytes arrived */ + if(!stream->rx_offset) + return; + + avail = Curl_rlimit_avail(&data->progress.dl.rlimit, NULL); + if(avail <= 0) { + /* nothing available, do not extend the rx offset */ + CURL_TRC_CF(data, cf, "[%" PRId64 "] dl rate limit exhausted (%" PRId64 + " tokens)", stream->id, avail); + return; + } + wanted_win = CURLMIN((uint64_t)avail, H3_STREAM_WINDOW_SIZE_MAX); + } + + if(stream->rx_offset_max < stream->rx_offset) { + DEBUGASSERT(0); + return; + } + cur_win = stream->rx_offset_max - stream->rx_offset; + if(cur_win < wanted_win) { + /* We have exhausted the credit we gave the QUIC peer for DATA. + * We extend it with the amount we can give (rate limit) */ + uint64_t ext = wanted_win - cur_win; + + ngtcp2_conn_extend_max_stream_offset(ctx->qconn, stream->id, ext); + ngtcp2_conn_extend_max_offset(ctx->qconn, ext); + stream->rx_offset_max += ext; + if(stream->rx_offset_max > stream->window_size_max) { + stream->window_size_max = stream->rx_offset_max; + CURL_TRC_CF(data, cf, "[%" PRId64 "] max window now -> %" PRIu64, + stream->id, stream->window_size_max); + } + CURL_TRC_CF(data, cf, "[%" PRId64 "] rx_offset_max -> %" PRIu64 + " (ext %" PRIu64 ", win %" PRIu64 ")", + stream->id, stream->rx_offset_max, ext, wanted_win); + } +} + +static int cb_h3_proxy_recv_data(nghttp3_conn *conn, int64_t stream3_id, + const uint8_t *buf, size_t buflen, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_h3_proxy_ctx *pctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + struct h3_stream_ctx *stream; + size_t nwritten; + CURLcode result = CURLE_OK; + (void)conn; + (void)stream3_id; + (void)stream_user_data; + + stream = pctx->tunnel.stream; + if(!data || !stream || (stream->id != stream3_id)) { + return NGHTTP3_ERR_CALLBACK_FAILURE; + } + + stream->rx_total += (curl_off_t)buflen; + CURL_TRC_CF(data, cf, "[cb_h3_proxy_recv_data] " + "[%" PRId64 "] DATA len=%zu, total=%" FMT_OFF_T, + stream->id, buflen, stream->rx_total); + + result = Curl_bufq_write(&pctx->tunnel.recvbuf, buf, buflen, &nwritten); + if(result || (nwritten < buflen)) { + return NGHTTP3_ERR_CALLBACK_FAILURE; + } + + /* DATA has been moved into our local recv buffer. Update stream offsets + * and give QUIC read credit back so long transfers over proxy tunnels + * do not stall on stream/connection flow-control limits. */ + stream->rx_offset += buflen; + if(stream->rx_offset_max < stream->rx_offset) + stream->rx_offset_max = stream->rx_offset; + + CURL_TRC_CF(data, cf, "[%" PRId64 "] DATA len=%zu, rx win=%" PRIu64, + stream->id, buflen, stream->rx_offset_max - stream->rx_offset); + cf_h3_proxy_upd_rx_win(cf, data, stream); + + Curl_multi_mark_dirty(data); + return 0; +} + +static int cb_h3_proxy_deferred_consume(nghttp3_conn *conn, int64_t stream_id, + size_t consumed, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_h3_proxy_ctx *pctx = cf->ctx; + struct cf_ngtcp2_ctx *ctx = &pctx->ngtcp2_ctx; + (void)conn; + (void)stream_user_data; + + if(!ctx) + return 0; + + /* nghttp3 has consumed bytes on the QUIC stream and we need to + * tell the QUIC connection to increase its flow control */ + ngtcp2_conn_extend_max_stream_offset(ctx->qconn, stream_id, consumed); + ngtcp2_conn_extend_max_offset(ctx->qconn, consumed); + + return 0; +} + +static int cb_h3_proxy_recv_header(nghttp3_conn *conn, int64_t stream_id, + int32_t token, nghttp3_rcbuf *name, + nghttp3_rcbuf *value, uint8_t flags, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_h3_proxy_ctx *pctx = cf->ctx; + nghttp3_vec h3name = nghttp3_rcbuf_get_buf(name); + nghttp3_vec h3val = nghttp3_rcbuf_get_buf(value); + struct Curl_easy *data = CF_DATA_CURRENT(cf); + struct h3_stream_ctx *stream; + CURLcode result = CURLE_OK; + int http_status; + struct http_resp *resp; + (void)conn; + (void)stream_id; + (void)token; + (void)flags; + (void)stream_user_data; + + /* stream_user_data might be NULL for control streams */ + if(!data) + return NGHTTP3_ERR_CALLBACK_FAILURE; + + stream = pctx->tunnel.stream; + if(!stream || (stream->id != stream_id)) { + CURL_TRC_CF(data, cf, "[%" PRId64 "] recv_header: stream lookup " + "failed for data=%p mid=%u", + stream_id, (void *)data, data ? data->mid : 0); + return 0; + } + + if(pctx->tunnel.has_final_response) { + /* we do not do anything with trailers for tunnel streams */ + return 0; + } + + if(token == NGHTTP3_QPACK_TOKEN__STATUS) { + result = Curl_http_decode_status(&stream->status_code, + (const char *)h3val.base, h3val.len); + if(result) + return NGHTTP3_ERR_CALLBACK_FAILURE; + http_status = stream->status_code; + result = Curl_http_resp_make(&resp, http_status, NULL); + if(result) + return NGHTTP3_ERR_CALLBACK_FAILURE; + if(pctx->tunnel.resp) + Curl_http_resp_free(pctx->tunnel.resp); + pctx->tunnel.resp = resp; + } + else { + if(!pctx->tunnel.resp) { + return NGHTTP3_ERR_CALLBACK_FAILURE; + } + /* store as an HTTP1-style header */ + CURL_TRC_CF(data, cf, "[%" PRId64 "] header: %.*s: %.*s", stream_id, + (int)h3name.len, h3name.base, (int)h3val.len, h3val.base); + result = Curl_dynhds_add(&pctx->tunnel.resp->headers, + (const char *)h3name.base, h3name.len, + (const char *)h3val.base, h3val.len); + if(result) { + return NGHTTP3_ERR_CALLBACK_FAILURE; + } + } + return 0; +} + +static int cb_h3_proxy_end_headers(nghttp3_conn *conn, int64_t stream_id, + int fin, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_h3_proxy_ctx *pctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + struct h3_stream_ctx *stream; + (void)conn; + (void)stream_id; + (void)fin; + (void)stream_user_data; + + if(!data) + return NGHTTP3_ERR_CALLBACK_FAILURE; + + stream = pctx->tunnel.stream; + if(!stream || (stream->id != stream_id)) { + CURL_TRC_CF(data, cf, "[%" PRId64 "] end_headers: stream lookup " + "failed for data=%p mid=%u", + stream_id, (void *)data, data ? data->mid : 0); + return 0; + } + + CURL_TRC_CF(data, cf, "[%" PRId64 "] end_headers, status=%d", stream_id, + stream->status_code); + + if(!pctx->tunnel.has_final_response) { + if(stream->status_code / 100 != 1) { + pctx->tunnel.has_final_response = TRUE; + } + } + + if(stream->status_code / 100 != 1) { + stream->resp_hds_complete = TRUE; + } + + Curl_multi_mark_dirty(data); + return 0; +} + +static int cb_h3_proxy_stop_sending(nghttp3_conn *conn, int64_t stream_id, + uint64_t app_error_code, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_h3_proxy_ctx *pctx = cf->ctx; + struct cf_ngtcp2_ctx *ctx = &pctx->ngtcp2_ctx; + (void)conn; + (void)stream_user_data; + + if(ctx) { + int rv = ngtcp2_conn_shutdown_stream_read(ctx->qconn, 0, stream_id, + app_error_code); + + if(rv && rv != NGTCP2_ERR_STREAM_NOT_FOUND) { + return NGHTTP3_ERR_CALLBACK_FAILURE; + } + } + + return 0; +} + +static int cb_h3_proxy_reset_stream(nghttp3_conn *conn, int64_t stream_id, + uint64_t app_error_code, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_h3_proxy_ctx *pctx = cf->ctx; + struct cf_ngtcp2_ctx *ctx = &pctx->ngtcp2_ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + int rv; + + (void)conn; + (void)stream_user_data; + if(!data) + return NGHTTP3_ERR_CALLBACK_FAILURE; + + if(!pctx->tunnel.stream || + (stream_id != pctx->tunnel.stream->id)) + return 0; + + rv = ngtcp2_conn_shutdown_stream_write(ctx->qconn, 0, stream_id, + app_error_code); + CURL_TRC_CF(data, cf, "[%" PRId64 "] reset -> %d", stream_id, rv); + pctx->tunnel.stream = NULL; + pctx->tunnel.closed = TRUE; + if(rv && rv != NGTCP2_ERR_STREAM_NOT_FOUND) { + return NGHTTP3_ERR_CALLBACK_FAILURE; + } + return 0; +} + +static nghttp3_ssize cb_h3_tunnel_read_data(nghttp3_conn *conn, + int64_t stream_id, + nghttp3_vec *vec, + size_t veccnt, + uint32_t *pflags, + void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_h3_proxy_ctx *pctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + struct h3_stream_ctx *stream; + size_t nwritten = 0; + size_t nvecs = 0; + const unsigned char *buf_base; + + (void)conn; + (void)stream_id; + (void)veccnt; + (void)stream_user_data; + (void)pflags; + + stream = pctx->tunnel.stream; + if(!data || !stream || (stream->id != stream_id)) + return NGHTTP3_ERR_CALLBACK_FAILURE; + + /* nghttp3 keeps references to the sendbuf data until it is ACKed + * by the server (see `cb_h3_proxy_acked_req_body()` for updates). + * `tx_in_flight_size` is the amount of bytes in `sendbuf` + * that we have already passed to nghttp3, but which have not been + * ACKed yet. + * Any amount beyond `tx_in_flight_size` we need still to pass + * to nghttp3. Do that now, if we can. */ + if(stream->tx_in_flight_size < Curl_bufq_len(&stream->sendbuf)) { + nvecs = 0; + while(nvecs < veccnt) { + if(!Curl_bufq_peek_at(&stream->sendbuf, + stream->tx_in_flight_size, + &buf_base, + &vec[nvecs].len)) + break; + vec[nvecs].base = (uint8_t *)(uintptr_t)buf_base; + stream->tx_in_flight_size += vec[nvecs].len; + nwritten += vec[nvecs].len; + ++nvecs; + } + DEBUGASSERT(nvecs > 0); /* we SHOULD have been able to peek */ + } + + if(!nwritten) { + /* Not EOF, and nothing to give, we signal WOULDBLOCK. */ + CURL_TRC_CF(data, cf, "[%" PRId64 "] read req body -> AGAIN", + stream->id); + return NGHTTP3_ERR_WOULDBLOCK; + } + + CURL_TRC_CF(data, cf, "[%" PRId64 "] read req body -> " + "%zu vecs%s with %zu (buffered=%zu)", + stream->id, nvecs, + *pflags == NGHTTP3_DATA_FLAG_EOF ? " EOF" : "", + nwritten, Curl_bufq_len(&stream->sendbuf)); + return (nghttp3_ssize)nvecs; +} + +#ifdef CURL_HAVE_DIAG +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif +static nghttp3_callbacks ngh3_proxy_callbacks = { + cb_h3_proxy_acked_req_body, /* acked_stream_data */ + cb_h3_proxy_stream_close, + cb_h3_proxy_recv_data, + cb_h3_proxy_deferred_consume, + NULL, /* begin_headers */ + cb_h3_proxy_recv_header, + cb_h3_proxy_end_headers, + NULL, /* begin_trailers */ + cb_h3_proxy_recv_header, + NULL, /* end_trailers */ + cb_h3_proxy_stop_sending, + NULL, /* end_stream */ + cb_h3_proxy_reset_stream, + NULL, /* shutdown */ + NULL, /* recv_settings (deprecated) */ +#ifdef NGHTTP3_CALLBACKS_V2 /* nghttp3 v1.11.0+ */ + NULL, /* recv_origin */ + NULL, /* end_origin */ + NULL, /* rand */ +#endif +#ifdef NGHTTP3_CALLBACKS_V3 /* nghttp3 v1.14.0+ */ + NULL, /* recv_settings2 */ +#endif +#ifdef NGHTTP3_CALLBACKS_V4 /* nghttp3 v1.18.0+ */ + NULL, /* stream_close2 */ +#endif +}; +#ifdef CURL_HAVE_DIAG +#pragma GCC diagnostic pop +#endif + +static CURLcode cf_ngtcp2_proxy_h3_init(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_ngtcp2_ctx *ctx) +{ + int rc; + + if(ngtcp2_conn_get_streams_uni_left(ctx->qconn) < 3) { + failf(data, "QUIC connection lacks 3 uni streams to run HTTP/3"); + return CURLE_QUIC_CONNECT_ERROR; + } + + nghttp3_settings_default(&ctx->h3settings); + + rc = nghttp3_conn_client_new(&ctx->h3conn, + &ngh3_proxy_callbacks, + &ctx->h3settings, + Curl_nghttp3_mem(), + cf); + if(rc) { + failf(data, "error creating nghttp3 connection instance"); + return CURLE_OUT_OF_MEMORY; + } + + return Curl_cf_ngtcp2_h3_init_ctrls(ctx, data); +} + +static ssize_t cf_h3_proxy_recv_closed_stream(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream, + CURLcode *err) +{ + ssize_t nread = -1; + *err = CURLE_OK; + + if(stream->reset) { + if(stream->error3 == CURL_H3_ERR_REQUEST_REJECTED) { + infof(data, "HTTP/3 stream %" PRId64 " refused by server, try again " + "on a new connection", stream->id); + connclose(cf->conn); + data->state.refused_stream = TRUE; + *err = CURLE_RECV_ERROR; + goto out; + } + else if(stream->resp_hds_complete && data->req.no_body) { + CURL_TRC_CF(data, cf, "[%" PRId64 "] error after response headers, " + "but we did not want a body anyway, ignore error 0x%" + PRIx64 " %s", stream->id, stream->error3, + Curl_vquic_h3_err_str(stream->error3)); + nread = 0; + goto out; + } + failf(data, "HTTP/3 stream %" PRId64 " reset by server (error 0x%" PRIx64 + " %s)", stream->id, stream->error3, + Curl_vquic_h3_err_str(stream->error3)); + *err = data->req.bytecount ? CURLE_PARTIAL_FILE : CURLE_HTTP3; + goto out; + } + else if(!stream->resp_hds_complete) { + failf(data, + "HTTP/3 stream %" PRId64 " was closed cleanly, but before " + "getting all response header fields, treated as error", + stream->id); + *err = CURLE_HTTP3; + goto out; + } + nread = 0; + +out: + return nread; +} + +static CURLcode cf_h3_proxy_sendbuf_add(struct Curl_easy *data, + struct h3_stream_ctx *stream, + const uint8_t *buf, size_t len, + size_t *pnwritten) +{ + CURLcode result; + *pnwritten = 0; + (void)data; + + result = Curl_bufq_write(&stream->sendbuf, buf, len, pnwritten); + return result; +} + +static CURLcode cf_h3_proxy_send(struct Curl_cfilter *cf, + struct Curl_easy *data, + const uint8_t *buf, size_t len, + bool eos, size_t *pnwritten) +{ + struct cf_h3_proxy_ctx *pctx = cf->ctx; + struct cf_ngtcp2_ctx *ctx = &pctx->ngtcp2_ctx; + struct h3_stream_ctx *stream = NULL; + struct cf_call_data save; + struct cf_ngtcp2_io_ctx pktx; + CURLcode result = CURLE_OK; + + CF_DATA_SAVE(save, cf, data); + DEBUGASSERT(cf->connected); + DEBUGASSERT(ctx->qconn); + DEBUGASSERT(ctx->h3conn); + Curl_cf_ngtcp2_io_ctx_init(&pktx, cf, data); + *pnwritten = 0; + + /* handshake verification failed in callback, do not send anything */ + if(ctx->tls_vrfy_result) { + result = ctx->tls_vrfy_result; + goto denied; + } + + (void)eos; /* use for stream EOF and block handling */ + result = Curl_cf_ngtcp2_progress_ingress(cf, data, &pktx); + if(result) + goto out; + + if(pctx->tunnel.closed) { + result = CURLE_SEND_ERROR; + goto denied; + } + + stream = pctx->tunnel.stream; + if(!stream) { + result = CURLE_SEND_ERROR; + goto denied; + } + + if(stream->closed) { + if(stream->resp_hds_complete) { + /* Server decided to close the stream after having sent us a final + * response. This is valid if it is not interested in the request + * body. This happens on 30x or 40x responses. + * We silently discard the data sent, since this is not a transport + * error situation. */ + CURL_TRC_CF(data, cf, "[%" PRId64 "] discarding data" + "on closed stream with response", stream->id); + result = CURLE_OK; + *pnwritten = len; + goto out; + } + CURL_TRC_CF(data, cf, "[%" PRId64 "] send_body(len=%zu) " + "-> stream closed", stream->id, len); + result = CURLE_HTTP3; + goto out; + } + else { + result = cf_h3_proxy_sendbuf_add(data, stream, buf, len, pnwritten); + CURL_TRC_CF(data, cf, "[%" PRId64 "] cf_send, add to " + "sendbuf(len=%zu) -> %d, %zu", + stream->id, len, (int)result, *pnwritten); + if(result) + goto out; + (void)nghttp3_conn_resume_stream(ctx->h3conn, stream->id); + } + + if(*pnwritten > 0 && !ctx->tls_handshake_complete && ctx->use_earlydata) + ctx->earlydata_skip += *pnwritten; + + DEBUGASSERT(!result); + result = Curl_cf_ngtcp2_progress_egress(cf, data, &pktx); + +out: + result = Curl_1st_fatal(result, + Curl_cf_ngtcp2_cmn_set_expiry(cf, data, &pktx)); +denied: + CURL_TRC_CF(data, cf, "[%" PRId64 "] cf_send(len=%zu) -> %d, %zu", + stream ? stream->id : -1, len, (int)result, *pnwritten); + CF_DATA_RESTORE(cf, save); + return result; +} + +/* incoming data frames on the h3 stream */ +static CURLcode cf_h3_proxy_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, size_t len, size_t *pnread) +{ + struct cf_h3_proxy_ctx *pctx = cf->ctx; + struct cf_ngtcp2_ctx *ctx = &pctx->ngtcp2_ctx; + struct h3_stream_ctx *stream = pctx->tunnel.stream; + struct cf_call_data save; + struct cf_ngtcp2_io_ctx pktx; + CURLcode result = CURLE_OK; + + CF_DATA_SAVE(save, cf, data); + DEBUGASSERT(cf->connected); + DEBUGASSERT(ctx); + DEBUGASSERT(ctx->qconn); + DEBUGASSERT(ctx->h3conn); + *pnread = 0; + + /* handshake verification failed in callback, do not recv anything */ + if(ctx->tls_vrfy_result) { + result = ctx->tls_vrfy_result; + goto denied; + } + + Curl_cf_ngtcp2_io_ctx_init(&pktx, cf, data); + + if(!stream || ctx->shutdown_started) { + result = CURLE_RECV_ERROR; + goto out; + } + + if(!Curl_bufq_is_empty(&pctx->tunnel.recvbuf)) { + result = Curl_bufq_cread(&pctx->tunnel.recvbuf, buf, len, pnread); + if(result) + goto out; + } + + result = Curl_cf_ngtcp2_progress_ingress(cf, data, &pktx); + if(result) + goto out; + + /* inbufq had nothing before, maybe after progressing ingress? */ + if(!*pnread && !Curl_bufq_is_empty(&pctx->tunnel.recvbuf)) { + result = Curl_bufq_cread(&pctx->tunnel.recvbuf, buf, len, pnread); + if(result) { + CURL_TRC_CF(data, cf, "[%" PRId64 "] read inbufq(len=%zu) -> %zu, %d", + stream->id, len, *pnread, (int)result); + goto out; + } + } + + if(*pnread) { + Curl_multi_mark_dirty(data); + } + else { + if(stream->xfer_result) { + CURL_TRC_CF(data, cf, "[%" PRId64 "] xfer write failed", stream->id); + Curl_cf_ngtcp2_h3_stream_close(cf, data, stream); + result = stream->xfer_result; + goto out; + } + else if(stream->closed) { + ssize_t nread = + cf_h3_proxy_recv_closed_stream(cf, data, stream, &result); + if(nread > 0) + *pnread = (size_t)nread; + goto out; + } + result = CURLE_AGAIN; + } + +out: + result = Curl_1st_fatal(result, + Curl_cf_ngtcp2_progress_egress(cf, data, &pktx)); + result = Curl_1st_fatal(result, + Curl_cf_ngtcp2_cmn_set_expiry(cf, data, &pktx)); +denied: + CURL_TRC_CF(data, cf, "[%" PRId64 "] cf_recv(len=%zu) -> %d, %zu", + stream ? stream->id : -1, len, (int)result, *pnread); + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode cf_h3_proxy_submit(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_tunnel_stream *ts, + struct httpreq *req) +{ + struct cf_h3_proxy_ctx *pctx = cf->ctx; + struct cf_ngtcp2_ctx *ctx = &pctx->ngtcp2_ctx; + struct h3_stream_ctx *stream = NULL; + struct dynhds h2_headers; + nghttp3_nv *nva = NULL; + size_t nheader; + int rc = 0; + unsigned int i; + nghttp3_data_reader reader; + nghttp3_data_reader *preader = NULL; + CURLcode result; + + Curl_dynhds_init(&h2_headers, 0, DYN_HTTP_REQUEST); + result = Curl_http_req_to_h2(&h2_headers, req, data); + if(result) + goto out; + + result = Curl_cf_ngtcp2_h3_stream_setup(cf, data); + if(result) + goto out; + stream = H3_STREAM_CTX(ctx, data); + DEBUGASSERT(stream); + if(!stream) { + result = CURLE_FAILED_INIT; + goto out; + } + + nheader = Curl_dynhds_count(&h2_headers); + nva = curlx_malloc(sizeof(nghttp3_nv) * nheader); + if(!nva) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + for(i = 0; i < nheader; ++i) { + struct dynhds_entry *e = Curl_dynhds_getn(&h2_headers, i); + nva[i].name = (unsigned char *)e->name; + nva[i].namelen = e->namelen; + nva[i].value = (unsigned char *)e->value; + nva[i].valuelen = e->valuelen; + nva[i].flags = NGHTTP3_NV_FLAG_NONE; + } + + /* Open a bidirectional stream */ + { + int64_t sid; + int rv; + + DEBUGASSERT(stream->id == -1); + /* Do NOT set `data` as stream user data. The transfer `data` may + * get cleaned up long before the tunnel goes down. */ + rv = ngtcp2_conn_open_bidi_stream(ctx->qconn, &sid, NULL); + if(rv) { + failf(data, "cannot get bidi streams: %s", ngtcp2_strerror(rv)); + result = CURLE_SEND_ERROR; + goto out; + } + stream->id = sid; + ts->stream = stream; + ++ctx->used_bidi_streams; + CURL_TRC_CF(data, cf, "[%" PRId64 "] opened bidi stream", sid); + } + + /* CONNECT-UDP request stream remains open for capsules, no fixed EOF. */ + stream->send_closed = 0; + reader.read_data = cb_h3_tunnel_read_data; + preader = &reader; + + rc = nghttp3_conn_submit_request(ctx->h3conn, stream->id, + nva, nheader, preader, data); + + if(rc) { + switch(rc) { + case NGHTTP3_ERR_CONN_CLOSING: + CURL_TRC_CF(data, cf, "h3sid[%" PRId64 "] failed to send, " + "connection is closing", stream->id); + break; + default: + CURL_TRC_CF(data, cf, "h3sid[%" PRId64 "] failed to send -> %d (%s)", + stream->id, rc, nghttp3_strerror(rc)); + break; + } + result = CURLE_SEND_ERROR; + goto out; + } + + if(Curl_trc_is_verbose(data)) { + CURL_TRC_CF(data, cf, "[H3-PROXY] [%" PRId64 "] OPENED stream " + "for %s", stream->id, + Curl_bufref_ptr(&data->state.url)); + } + +out: + curlx_free(nva); + Curl_dynhds_free(&h2_headers); + return result; +} + +static CURLcode cf_h3_proxy_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_h3_proxy_ctx *pctx = cf->ctx; + struct cf_ngtcp2_ctx *ctx = &pctx->ngtcp2_ctx; + bool want_recv, want_send; + CURLcode result = CURLE_OK; + curl_socket_t sock = (ctx->q.sockfd != CURL_SOCKET_BAD) ? + ctx->q.sockfd : Curl_conn_cf_get_socket(cf, data); + + if(!ctx->qconn || !pctx->tunnel.stream || (sock == CURL_SOCKET_BAD)) + return CURLE_OK; + + Curl_pollset_check(data, ps, sock, &want_recv, &want_send); + + if(want_recv || want_send || !Curl_bufq_is_empty(&ctx->q.sendbuf)) { + struct h3_stream_ctx *stream = pctx->tunnel.stream; + bool c_exhaust, s_exhaust; + + c_exhaust = want_send && + (!ngtcp2_conn_get_cwnd_left(ctx->qconn) || + !ngtcp2_conn_get_max_data_left(ctx->qconn)); + s_exhaust = want_send && stream && stream->id >= 0 && + stream->quic_flow_blocked; + want_recv = (want_recv || c_exhaust || s_exhaust); + want_send = (!s_exhaust && want_send) || + !Curl_bufq_is_empty(&ctx->q.sendbuf); + + result = Curl_pollset_set(data, ps, sock, want_recv, want_send); + } + return result; +} + +static bool cf_h3_proxy_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct cf_h3_proxy_ctx *pctx = cf->ctx; + if(!Curl_bufq_is_empty(&pctx->tunnel.recvbuf)) + return TRUE; + return cf->next ? + cf->next->cft->has_data_pending(cf->next, data) : FALSE; +} + +static CURLcode cf_h3_proxy_submit_CONNECT(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_tunnel_stream *ts) +{ + CURLcode result; + struct httpreq *req = NULL; + + result = Curl_http_proxy_create_tunnel_request(&req, cf, data, + ts->peer, + PROXY_HTTP_V3, + (bool)ts->udp); + if(!result) + result = Curl_creader_set_null(data); + if(!result) + result = cf_h3_proxy_submit(cf, data, ts, req); + + if(req) + Curl_http_req_free(req); + if(result) + failf(data, "Failed sending CONNECT to proxy"); + return result; +} + +static CURLcode cf_h3_proxy_inspect_response(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_tunnel_stream *ts) +{ + struct cf_h3_proxy_ctx *pctx = cf->ctx; + proxy_inspect_result res; + CURLcode result; + + result = Curl_http_proxy_inspect_tunnel_response( + cf, data, ts->resp, (bool)pctx->tunnel.udp, &res); + if(result) + return result; + switch(res) { + case PROXY_INSPECT_OK: + h3_tunnel_go_state(cf, ts, H3_TUNNEL_ESTABLISHED, data); + break; + case PROXY_INSPECT_FAILED: + h3_tunnel_go_state(cf, ts, H3_TUNNEL_FAILED, data); + result = CURLE_COULDNT_CONNECT; + break; + case PROXY_INSPECT_AUTH_RETRY: + h3_tunnel_go_state(cf, ts, H3_TUNNEL_INIT, data); + break; + } + return result; +} + +static CURLcode cf_h3_proxy_tunnel(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_tunnel_stream *ts, + bool *pdone) +{ + struct cf_h3_proxy_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + DEBUGASSERT(ts); + DEBUGASSERT(ts->authority); + *pdone = FALSE; + do { + switch(ts->state) { + case H3_TUNNEL_INIT: + CURL_TRC_CF(data, cf, "[0] CONNECT start for %s", ts->authority); + result = cf_h3_proxy_submit_CONNECT(cf, data, ts); + if(result) + goto out; + h3_tunnel_go_state(cf, ts, H3_TUNNEL_CONNECT, data); + + result = Curl_cf_ngtcp2_progress_egress(cf, data, NULL); + if(result) + goto out; + FALLTHROUGH(); + + case H3_TUNNEL_CONNECT: + /* Non-blocking: call ingress/egress once and return. + * The multi interface will call us again when ready. */ + result = Curl_cf_ngtcp2_progress_ingress(cf, data, NULL); + if(result) + goto out; + result = Curl_cf_ngtcp2_progress_egress(cf, data, NULL); + if(result && result != CURLE_AGAIN) { + h3_tunnel_go_state(cf, ts, H3_TUNNEL_FAILED, data); + goto out; + } + + if(ts->has_final_response) { + h3_tunnel_go_state(cf, ts, H3_TUNNEL_RESPONSE, data); + } + else { + /* Not done yet, return and let multi interface call us again */ + result = CURLE_OK; + goto out; + } + FALLTHROUGH(); + + case H3_TUNNEL_RESPONSE: + DEBUGASSERT(ts->has_final_response); + result = cf_h3_proxy_inspect_response(cf, data, ts); + if(result) + goto out; + ctx->connected = TRUE; + break; + + case H3_TUNNEL_ESTABLISHED: + *pdone = TRUE; + return CURLE_OK; + + case H3_TUNNEL_FAILED: + return CURLE_RECV_ERROR; + + default: + break; + } + + } while(ts->state == H3_TUNNEL_INIT); + +out: + if((result && (result != CURLE_AGAIN)) || ctx->tunnel.closed) + h3_tunnel_go_state(cf, ts, H3_TUNNEL_FAILED, data); + return result; +} + +static CURLcode cf_h3_proxy_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + struct cf_h3_proxy_ctx *pctx = cf->ctx; + struct cf_call_data save = { 0 }; + CURLcode result = CURLE_OK; + struct h3_tunnel_stream *ts = &pctx->tunnel; + bool data_saved = FALSE; + + result = Curl_cf_ngtcp2_cmn_connect(cf, data, done); + if(result || !*done) + goto out; + + CF_DATA_SAVE(save, cf, data); + data_saved = TRUE; + + /* At this point the QUIC is connected, but the proxy is not connected */ + result = cf_h3_proxy_tunnel(cf, data, ts, done); + +out: + if(*done) { + cf->connected = TRUE; + /* The real request will follow the CONNECT, reset request partially */ + Curl_req_soft_reset(&data->req, data); + Curl_client_reset(data); + } + + if(data_saved) + CF_DATA_RESTORE(cf, save); + return result; +} + +static void cf_h3_proxy_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_h3_proxy_ctx *ctx = cf->ctx; + + (void)data; + if(ctx) { + CURL_TRC_CF(data, cf, "cf_h3_proxy_destroy()"); + cf_h3_proxy_ctx_free(ctx); + cf->ctx = NULL; + } +} + +static CURLcode cf_h3_proxy_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + return Curl_cf_ngtcp2_cmn_shutdown(cf, data, done); +} + +struct Curl_cftype Curl_cft_h3_proxy = { + "H3-PROXY", + CF_TYPE_IP_CONNECT | CF_TYPE_PROXY | CF_TYPE_SSL, + CURL_LOG_LVL_NONE, + cf_h3_proxy_destroy, + cf_h3_proxy_connect, + cf_h3_proxy_shutdown, + cf_h3_proxy_adjust_pollset, + cf_h3_proxy_data_pending, + cf_h3_proxy_send, + cf_h3_proxy_recv, + Curl_cf_def_cntrl, + Curl_cf_ngtcp2_cmn_conn_is_alive, + Curl_cf_def_conn_keep_alive, + Curl_cf_ngtcp2_cmn_query, +}; + +CURLcode Curl_cf_ngtcp2_proxy_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport) +{ + struct Curl_cfilter *cf = NULL; + struct cf_h3_proxy_ctx *ctx; + CURLcode result = CURLE_OUT_OF_MEMORY; + + if(!tunnel_peer) + return CURLE_FAILED_INIT; + if((transport_peer != TRNSPRT_QUIC) || (!conn->http_proxy.peer)) + return CURLE_FAILED_INIT; + + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + result = cf_h3_proxy_ctx_init(ctx, origin, peer, &conn->proxy_ssl_config, + tunnel_peer, tunnel_transport); + if(result) + goto out; + + result = Curl_cf_create(&cf, &Curl_cft_h3_proxy, ctx); + if(result) + goto out; + cf->conn = conn; + + result = Curl_cf_udp_create(&cf->next, data, origin, peer, TRNSPRT_QUIC, + conn, addr, NULL, TRNSPRT_QUIC); + if(result) + goto out; + cf->next->conn = cf->conn; + cf->next->sockindex = cf->sockindex; + +out: + *pcf = (!result) ? cf : NULL; + if(result) { + if(cf) + Curl_conn_cf_discard_chain(&cf, data); + else if(ctx) + cf_h3_proxy_ctx_free(ctx); + } + else + CURL_TRC_CF(data, cf, "created, udp_tunnel=%d", ctx->tunnel.udp); + return result; +} + +CURLcode Curl_cf_ngtcp2_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport) +{ + struct Curl_cfilter *cf = NULL; + struct cf_h3_proxy_ctx *ctx; + CURLcode result = CURLE_OUT_OF_MEMORY; + (void)data; + + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) + goto out; + result = cf_h3_proxy_ctx_init(ctx, origin, peer, + &cf_at->conn->proxy_ssl_config, + tunnel_peer, tunnel_transport); + if(result) + goto out; + + result = Curl_cf_create(&cf, &Curl_cft_h3_proxy, ctx); + if(result) + goto out; + + /* H3-PROXY uses the UDP socket created by happy eyeballs below it. + Curl_conn_cf_insert_after chains the existing sub-filters, i.e. + "HAPPY-EYEBALLS -> UDP" as cf->next of H3-PROXY. */ + Curl_conn_cf_insert_after(cf_at, cf); + +out: + if(result) { + if(cf) + Curl_conn_cf_discard_chain(&cf, data); + else if(ctx) + cf_h3_proxy_ctx_free(ctx); + } + return result; +} + +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2-proxy.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2-proxy.h new file mode 100644 index 0000000000..acdee0e463 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2-proxy.h @@ -0,0 +1,52 @@ +#ifndef HEADER_CURL_VQUIC_CF_NGTCP2_PROXY_H +#define HEADER_CURL_VQUIC_CF_NGTCP2_PROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_PROXY) && \ + defined(USE_PROXY_HTTP3) && defined(USE_NGHTTP3) && \ + defined(USE_NGTCP2) && defined(USE_OPENSSL) + +CURLcode Curl_cf_ngtcp2_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport); + +CURLcode Curl_cf_ngtcp2_proxy_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport); + +#endif + +#endif /* HEADER_CURL_VQUIC_CF_NGTCP2_PROXY_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2.c new file mode 100644 index 0000000000..e3bca8774e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2.c @@ -0,0 +1,1179 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_NGTCP2) && defined(USE_NGHTTP3) + +#include "urldata.h" +#include "url.h" +#include "uint-hash.h" +#include "curl_trc.h" +#include "rand.h" +#include "multiif.h" +#include "cfilters.h" +#include "cf-socket.h" +#include "connect.h" +#include "progress.h" +#include "curlx/fopen.h" +#include "curlx/dynbuf.h" +#include "http1.h" +#include "select.h" +#include "transfer.h" +#include "bufref.h" +#include "vdns/cf-dns.h" +#include "vquic/vquic.h" +#include "vquic/vquic_int.h" +#include "vquic/cf-ngtcp2-cmn.h" +#include "vquic/cf-ngtcp2.h" + + +static int cb_h3_acked_req_body(nghttp3_conn *conn, int64_t stream_id, + uint64_t datalen, void *user_data, + void *stream_user_data); + +static CURLcode cf_ngtcp2_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + bool want_recv, want_send; + CURLcode result = CURLE_OK; + curl_socket_t sock = (ctx->q.sockfd != CURL_SOCKET_BAD) ? + ctx->q.sockfd : Curl_conn_cf_get_socket(cf, data); + + if(!ctx->qconn || (sock == CURL_SOCKET_BAD)) + return CURLE_OK; + + Curl_pollset_check(data, ps, sock, &want_recv, &want_send); + if(!want_send && !Curl_bufq_is_empty(&ctx->q.sendbuf)) + want_send = TRUE; + + if(want_recv || want_send) { + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + struct cf_call_data save; + bool c_exhaust, s_exhaust; + + CF_DATA_SAVE(save, cf, data); + c_exhaust = want_send && (!ngtcp2_conn_get_cwnd_left(ctx->qconn) || + !ngtcp2_conn_get_max_data_left(ctx->qconn)); + s_exhaust = want_send && stream && stream->id >= 0 && + (stream->quic_flow_blocked || + stream->tx_in_flight_size >= stream->tx_in_flight_ideal); + want_recv = (want_recv || c_exhaust || s_exhaust); + want_send = (!s_exhaust && want_send) || + !Curl_bufq_is_empty(&ctx->q.sendbuf); + + result = Curl_pollset_set(data, ps, sock, want_recv, want_send); + CF_DATA_RESTORE(cf, save); + } + return result; +} + +static int cb_h3_stream_close(nghttp3_conn *conn, int64_t stream_id, + uint64_t app_error_code, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + (void)conn; + (void)stream_id; + + /* we might be called by nghttp3 after we already cleaned up */ + if(!stream) + return 0; + + stream->closed = TRUE; + stream->error3 = app_error_code; + if(stream->error3 != NGHTTP3_H3_NO_ERROR) { + stream->reset = TRUE; + stream->send_closed = TRUE; + CURL_TRC_CF(data, cf, "[%" PRId64 "] RESET: error %" PRIu64, + stream->id, stream->error3); + } + else { + CURL_TRC_CF(data, cf, "[%" PRId64 "] CLOSED", stream->id); + } + Curl_multi_mark_dirty(data); + return 0; +} + +static void h3_xfer_write_resp_hd(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream, + const char *buf, size_t buflen, bool eos) +{ + /* This function returns no error intentionally, but records + * the result at the stream, skipping further writes once the + * `result` of the transfer is known. + * The stream is subsequently cancelled "higher up" in the filter's + * send/recv callbacks. Closing the stream here leads to SEND/RECV + * errors in other places that then overwrite the transfer's result. */ + if(!stream->xfer_result) { + stream->xfer_result = Curl_xfer_write_resp_hd(data, buf, buflen, eos); + if(stream->xfer_result) + CURL_TRC_CF(data, cf, "[%" PRId64 "] error %d writing %zu " + "bytes of headers", stream->id, (int)stream->xfer_result, + buflen); + } +} + +static void h3_xfer_write_resp(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream, + const char *buf, size_t buflen, bool eos) +{ + /* This function returns no error intentionally, but records + * the result at the stream, skipping further writes once the + * `result` of the transfer is known. + * The stream is subsequently cancelled "higher up" in the filter's + * send/recv callbacks. Closing the stream here leads to SEND/RECV + * errors in other places that then overwrite the transfer's result. */ + if(!stream->xfer_result) { + stream->xfer_result = Curl_xfer_write_resp(data, buf, buflen, eos); + /* If the transfer write is errored, we do not want any more data */ + if(stream->xfer_result) { + CURL_TRC_CF(data, cf, "[%" PRId64 "] error %d writing %zu bytes of data", + stream->id, (int)stream->xfer_result, buflen); + } + } +} + +static void cf_ngtcp2_upd_rx_win(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + uint64_t cur_win, wanted_win = H3_STREAM_WINDOW_SIZE_MAX; + + /* how much does rate limiting allow us to acknowledge? */ + if(Curl_rlimit_active(&data->progress.dl.rlimit)) { + int64_t avail; + + /* start rate limit updates only after first bytes arrived */ + if(!stream->rx_offset) + return; + + avail = Curl_rlimit_avail(&data->progress.dl.rlimit, NULL); + if(avail <= 0) { + /* nothing available, do not extend the rx offset */ + CURL_TRC_CF(data, cf, "[%" PRId64 "] dl rate limit exhausted (%" PRId64 + " tokens)", stream->id, avail); + return; + } + wanted_win = CURLMIN((uint64_t)avail, H3_STREAM_WINDOW_SIZE_MAX); + } + + if(stream->rx_offset_max < stream->rx_offset) { + DEBUGASSERT(0); + return; + } + cur_win = stream->rx_offset_max - stream->rx_offset; + + if(wanted_win > cur_win) { + uint64_t delta = wanted_win - cur_win; + + if(UINT64_MAX - delta < stream->rx_offset_max) + delta = UINT64_MAX - stream->rx_offset_max; + if(delta) { + CURL_TRC_CF(data, cf, "[%" PRId64 "] rx window, extend by %" PRIu64 + " bytes", stream->id, delta); + stream->rx_offset_max += delta; + ngtcp2_conn_extend_max_stream_offset(ctx->qconn, stream->id, delta); + } + } +} + +static int cb_h3_recv_data(nghttp3_conn *conn, int64_t stream3_id, + const uint8_t *buf, size_t buflen, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + (void)conn; + (void)stream3_id; + + if(!stream) + return NGHTTP3_ERR_CALLBACK_FAILURE; + + h3_xfer_write_resp(cf, data, stream, (const char *)buf, buflen, FALSE); + + ngtcp2_conn_extend_max_offset(ctx->qconn, buflen); + stream->rx_offset += buflen; + if(stream->rx_offset_max < stream->rx_offset) + stream->rx_offset_max = stream->rx_offset; + + CURL_TRC_CF(data, cf, "[%" PRId64 "] DATA len=%zu, rx win=%" PRIu64, + stream->id, buflen, stream->rx_offset_max - stream->rx_offset); + cf_ngtcp2_upd_rx_win(cf, data, stream); + return 0; +} + +static int cb_h3_deferred_consume(nghttp3_conn *conn, int64_t stream3_id, + size_t consumed, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + (void)conn; + + /* nghttp3 has consumed bytes on the QUIC stream and we need to + * tell the QUIC connection to increase its flow control */ + ngtcp2_conn_extend_max_stream_offset(ctx->qconn, stream3_id, consumed); + ngtcp2_conn_extend_max_offset(ctx->qconn, consumed); + if(stream) { + stream->rx_offset += consumed; + stream->rx_offset_max += consumed; + } + return 0; +} + +static int cb_h3_end_headers(nghttp3_conn *conn, int64_t stream_id, + int fin, void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + (void)conn; + (void)stream_id; + (void)fin; + (void)cf; + + if(!stream) + return 0; + /* add a CRLF only if we have received some headers */ + h3_xfer_write_resp_hd(cf, data, stream, STRCONST("\r\n"), + (bool)stream->closed); + + CURL_TRC_CF(data, cf, "[%" PRId64 "] end_headers, status=%d", + stream_id, stream->status_code); + if(stream->status_code / 100 != 1) { + stream->resp_hds_complete = TRUE; + } + Curl_multi_mark_dirty(data); + return 0; +} + +static int cb_h3_recv_header(nghttp3_conn *conn, int64_t stream_id, + int32_t token, nghttp3_rcbuf *name, + nghttp3_rcbuf *value, uint8_t flags, + void *user_data, void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + nghttp3_vec h3name = nghttp3_rcbuf_get_buf(name); + nghttp3_vec h3val = nghttp3_rcbuf_get_buf(value); + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result = CURLE_OK; + (void)conn; + (void)stream_id; + (void)token; + (void)flags; + (void)cf; + + /* we might have cleaned up this transfer already */ + if(!stream) + return 0; + + if(token == NGHTTP3_QPACK_TOKEN__STATUS) { + + result = Curl_http_decode_status(&stream->status_code, + (const char *)h3val.base, h3val.len); + if(result) + return NGHTTP3_ERR_CALLBACK_FAILURE; + curlx_dyn_reset(&ctx->scratch); + result = curlx_dyn_addn(&ctx->scratch, STRCONST("HTTP/3 ")); + if(!result) + result = curlx_dyn_addn(&ctx->scratch, + (const char *)h3val.base, h3val.len); + if(!result) + result = curlx_dyn_addn(&ctx->scratch, STRCONST(" \r\n")); + if(!result) + h3_xfer_write_resp_hd(cf, data, stream, curlx_dyn_ptr(&ctx->scratch), + curlx_dyn_len(&ctx->scratch), FALSE); + CURL_TRC_CF(data, cf, "[%" PRId64 "] status: %s", + stream_id, curlx_dyn_ptr(&ctx->scratch)); + if(result) { + return NGHTTP3_ERR_CALLBACK_FAILURE; + } + } + else { + /* store as an HTTP1-style header */ + CURL_TRC_CF(data, cf, "[%" PRId64 "] header: %.*s: %.*s", + stream_id, (int)h3name.len, h3name.base, + (int)h3val.len, h3val.base); + curlx_dyn_reset(&ctx->scratch); + result = curlx_dyn_addn(&ctx->scratch, + (const char *)h3name.base, h3name.len); + if(!result) + result = curlx_dyn_addn(&ctx->scratch, STRCONST(": ")); + if(!result) + result = curlx_dyn_addn(&ctx->scratch, + (const char *)h3val.base, h3val.len); + if(!result) + result = curlx_dyn_addn(&ctx->scratch, STRCONST("\r\n")); + if(!result) + h3_xfer_write_resp_hd(cf, data, stream, curlx_dyn_ptr(&ctx->scratch), + curlx_dyn_len(&ctx->scratch), FALSE); + } + return 0; +} + +static int cb_h3_stop_sending(nghttp3_conn *conn, int64_t stream_id, + uint64_t app_error_code, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + int rv; + (void)conn; + (void)stream_user_data; + + rv = ngtcp2_conn_shutdown_stream_read(ctx->qconn, 0, stream_id, + app_error_code); + if(rv && rv != NGTCP2_ERR_STREAM_NOT_FOUND) { + return NGHTTP3_ERR_CALLBACK_FAILURE; + } + + return 0; +} + +static int cb_h3_reset_stream(nghttp3_conn *conn, int64_t stream_id, + uint64_t app_error_code, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + int rv; + (void)conn; + + rv = ngtcp2_conn_shutdown_stream_write(ctx->qconn, 0, stream_id, + app_error_code); + CURL_TRC_CF(data, cf, "[%" PRId64 "] reset -> %d", stream_id, rv); + if(rv && rv != NGTCP2_ERR_STREAM_NOT_FOUND) { + return NGHTTP3_ERR_CALLBACK_FAILURE; + } + + return 0; +} + +#ifdef CURL_HAVE_DIAG +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif +static nghttp3_callbacks ngh3_callbacks = { + cb_h3_acked_req_body, /* acked_stream_data */ + cb_h3_stream_close, + cb_h3_recv_data, + cb_h3_deferred_consume, + NULL, /* begin_headers */ + cb_h3_recv_header, + cb_h3_end_headers, + NULL, /* begin_trailers */ + cb_h3_recv_header, + NULL, /* end_trailers */ + cb_h3_stop_sending, + NULL, /* end_stream */ + cb_h3_reset_stream, + NULL, /* shutdown */ + NULL, /* recv_settings (deprecated) */ +#ifdef NGHTTP3_CALLBACKS_V2 /* nghttp3 v1.11.0+ */ + NULL, /* recv_origin */ + NULL, /* end_origin */ + NULL, /* rand */ +#endif +#ifdef NGHTTP3_CALLBACKS_V3 /* nghttp3 v1.14.0+ */ + NULL, /* recv_settings2 */ +#endif +#ifdef NGHTTP3_CALLBACKS_V4 /* nghttp3 v1.18.0+ */ + NULL, /* stream_close2 */ +#endif +}; +#ifdef CURL_HAVE_DIAG +#pragma GCC diagnostic pop +#endif + +static CURLcode init_ngh3_conn(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_ngtcp2_ctx *ctx) +{ + int rc; + + if(ngtcp2_conn_get_streams_uni_left(ctx->qconn) < 3) { + failf(data, "QUIC connection lacks 3 uni streams to run HTTP/3"); + return CURLE_QUIC_CONNECT_ERROR; + } + + nghttp3_settings_default(&ctx->h3settings); + + rc = nghttp3_conn_client_new(&ctx->h3conn, + &ngh3_callbacks, + &ctx->h3settings, + Curl_nghttp3_mem(), + cf); + if(rc) { + failf(data, "error creating nghttp3 connection instance"); + return CURLE_OUT_OF_MEMORY; + } + + return Curl_cf_ngtcp2_h3_init_ctrls(ctx, data); +} + +static CURLcode recv_closed_stream(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream, + size_t *pnread) +{ + (void)cf; + *pnread = 0; + if(stream->reset) { + if(stream->error3 == CURL_H3_ERR_REQUEST_REJECTED) { + infof(data, "HTTP/3 stream %" PRId64 " refused by server, try again " + "on a new connection", stream->id); + connclose(cf->conn); /* do not use this anymore */ + data->state.refused_stream = TRUE; + return CURLE_RECV_ERROR; /* trigger Curl_retry_request() later */ + } + else if(stream->resp_hds_complete && data->req.no_body) { + CURL_TRC_CF(data, cf, "[%" PRId64 "] error after response headers, " + "but we did not want a body anyway, ignore error 0x%" + PRIx64 " %s", stream->id, stream->error3, + Curl_vquic_h3_err_str(stream->error3)); + return CURLE_OK; + } + failf(data, "HTTP/3 stream %" PRId64 " reset by server (error 0x%" PRIx64 + " %s)", stream->id, stream->error3, + Curl_vquic_h3_err_str(stream->error3)); + return data->req.bytecount ? CURLE_PARTIAL_FILE : CURLE_HTTP3; + } + else if(!stream->resp_hds_complete) { + failf(data, + "HTTP/3 stream %" PRId64 " was closed cleanly, but before " + "getting all response header fields, treated as error", + stream->id); + return CURLE_HTTP3; + } + return CURLE_OK; +} + +/* incoming data frames on the h3 stream */ +static CURLcode cf_ngtcp2_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t buflen, size_t *pnread) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + struct cf_call_data save; + struct cf_ngtcp2_io_ctx pktx; + CURLcode result = CURLE_OK; + int i; + + (void)ctx; + (void)buf; + NOVERBOSE((void)buflen); + + CF_DATA_SAVE(save, cf, data); + DEBUGASSERT(cf->connected); + DEBUGASSERT(ctx); + DEBUGASSERT(ctx->qconn); + DEBUGASSERT(ctx->h3conn); + *pnread = 0; + + /* handshake verification failed in callback, do not recv anything */ + if(ctx->tls_vrfy_result) { + result = ctx->tls_vrfy_result; + goto denied; + } + + Curl_cf_ngtcp2_io_ctx_init(&pktx, cf, data); + + if(!stream || ctx->shutdown_started) { + result = CURLE_RECV_ERROR; + goto out; + } + + cf_ngtcp2_upd_rx_win(cf, data, stream); + + /* first check for results/closed already known without touching + * the connection. For an already failed/closed stream, errors on + * the connection do not count. + * Then handle incoming data and check for failed/closed again. + */ + for(i = 0; i < 2; ++i) { + if(stream->xfer_result) { + CURL_TRC_CF(data, cf, "[%" PRId64 "] xfer write failed", stream->id); + Curl_cf_ngtcp2_h3_stream_close(cf, data, stream); + result = stream->xfer_result; + goto out; + } + else if(stream->closed) { + result = recv_closed_stream(cf, data, stream, pnread); + goto out; + } + + if(!i && Curl_cf_ngtcp2_progress_ingress(cf, data, &pktx)) { + result = CURLE_RECV_ERROR; + goto out; + } + } + + result = CURLE_AGAIN; + +out: + result = Curl_1st_fatal(result, + Curl_cf_ngtcp2_progress_egress(cf, data, &pktx)); + result = Curl_1st_fatal(result, + Curl_cf_ngtcp2_cmn_set_expiry(cf, data, &pktx)); + if(ctx->tls_vrfy_result) + result = ctx->tls_vrfy_result; +denied: + CURL_TRC_CF(data, cf, "[%" PRId64 "] cf_recv(buflen=%zu) -> %d, %zu", + stream ? stream->id : -1, buflen, (int)result, *pnread); + CF_DATA_RESTORE(cf, save); + return result; +} + +static int cb_h3_acked_req_body(nghttp3_conn *conn, int64_t stream_id, + uint64_t datalen, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + size_t skiplen; + + (void)cf; + if(!stream) + return 0; + /* The server acknowledged `datalen` of bytes from our request body. + * This is a delta. We have kept this data in `sendbuf` for + * re-transmissions and can free it now. */ + if(datalen >= (uint64_t)stream->tx_in_flight_size) + skiplen = stream->tx_in_flight_size; + else + skiplen = (size_t)datalen; + Curl_bufq_skip(&stream->sendbuf, skiplen); + stream->tx_in_flight_size -= skiplen; + + /* Resume upload processing if we have more data to send */ + if(stream->tx_in_flight_size < Curl_bufq_len(&stream->sendbuf)) { + int rv = nghttp3_conn_resume_stream(conn, stream_id); + if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) { + return NGHTTP3_ERR_CALLBACK_FAILURE; + } + } + return 0; +} + +static nghttp3_ssize cb_h3_read_req_body(nghttp3_conn *conn, int64_t stream_id, + nghttp3_vec *vec, size_t veccnt, + uint32_t *pflags, void *user_data, + void *stream_user_data) +{ + struct Curl_cfilter *cf = user_data; + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = stream_user_data; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + size_t nwritten = 0; + size_t nvecs = 0; + (void)cf; + (void)conn; + (void)stream_id; + (void)user_data; + (void)veccnt; + + if(!stream) + return NGHTTP3_ERR_CALLBACK_FAILURE; + /* nghttp3 keeps references to the sendbuf data until it is ACKed + * by the server (see `cb_h3_acked_req_body()` for updates). + * `tx_in_flight_size` is the amount of bytes in `sendbuf` + * that we have already passed to nghttp3, but which have not been + * ACKed yet. + * Any amount beyond `tx_in_flight_size` we need still to pass + * to nghttp3. Do that now, if we can. */ + if(stream->tx_in_flight_size < Curl_bufq_len(&stream->sendbuf)) { + nvecs = 0; + while(nvecs < veccnt && + Curl_bufq_peek_at(&stream->sendbuf, + stream->tx_in_flight_size, + CURL_UNCONST(&vec[nvecs].base), + &vec[nvecs].len)) { + stream->tx_in_flight_size += vec[nvecs].len; + nwritten += vec[nvecs].len; + ++nvecs; + } + DEBUGASSERT(nvecs > 0); /* we SHOULD have been be able to peek */ + } + + if(nwritten > 0 && stream->upload_left != -1) + stream->upload_left -= nwritten; + + /* When we stopped sending and everything in `sendbuf` is "in flight", + * we are at the end of the request body. */ + if(stream->upload_left == 0) { + *pflags = NGHTTP3_DATA_FLAG_EOF; + stream->send_closed = TRUE; + } + else if(!nwritten) { + /* Not EOF, and nothing to give, we signal WOULDBLOCK. */ + CURL_TRC_CF(data, cf, "[%" PRId64 "] read req body -> AGAIN", stream->id); + return NGHTTP3_ERR_WOULDBLOCK; + } + + CURL_TRC_CF(data, cf, "[%" PRId64 "] read req body -> " + "%zu vecs%s with %zu (buffered=%zu, left=%" FMT_OFF_T ")", + stream->id, nvecs, + *pflags == NGHTTP3_DATA_FLAG_EOF ? " EOF" : "", + nwritten, Curl_bufq_len(&stream->sendbuf), + stream->upload_left); + return (nghttp3_ssize)nvecs; +} + +static CURLcode h3_stream_open(struct Curl_cfilter *cf, + struct Curl_easy *data, + const uint8_t *buf, size_t len, + size_t *pnwritten) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = NULL; + int64_t sid; + struct dynhds h2_headers; + size_t nheader; + nghttp3_nv *nva = NULL; + int rc = 0; + unsigned int i; + nghttp3_data_reader reader; + nghttp3_data_reader *preader = NULL; + CURLcode result; + + *pnwritten = 0; + Curl_dynhds_init(&h2_headers, 0, DYN_HTTP_REQUEST); + + result = Curl_cf_ngtcp2_h3_stream_setup(cf, data); + if(result) + goto out; + stream = H3_STREAM_CTX(ctx, data); + DEBUGASSERT(stream); + if(!stream) { + result = CURLE_FAILED_INIT; + goto out; + } + + result = Curl_h1_req_parse_read(&stream->h1, buf, len, NULL, + !data->state.http_ignorecustom ? + CURL_EASY_STR(data, STRING_CUSTOMREQUEST) : NULL, + 0, pnwritten); + if(result) + goto out; + if(!stream->h1.done) { + /* need more data */ + goto out; + } + DEBUGASSERT(stream->h1.req); + + result = Curl_http_req_to_h2(&h2_headers, stream->h1.req, data); + if(result) + goto out; + + /* no longer needed */ + Curl_h1_req_parse_free(&stream->h1); + + nheader = Curl_dynhds_count(&h2_headers); + nva = curlx_malloc(sizeof(nghttp3_nv) * nheader); + if(!nva) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + for(i = 0; i < nheader; ++i) { + struct dynhds_entry *e = Curl_dynhds_getn(&h2_headers, i); + nva[i].name = (unsigned char *)e->name; + nva[i].namelen = e->namelen; + nva[i].value = (unsigned char *)e->value; + nva[i].valuelen = e->valuelen; + nva[i].flags = NGHTTP3_NV_FLAG_NONE; + } + + rc = ngtcp2_conn_open_bidi_stream(ctx->qconn, &sid, data); + if(rc) { + failf(data, "cannot open bidi streams"); + result = CURLE_SEND_ERROR; + goto out; + } + stream->id = sid; + ++ctx->used_bidi_streams; + + switch(data->state.httpreq) { + case HTTPREQ_POST: + case HTTPREQ_POST_FORM: + case HTTPREQ_POST_MIME: + case HTTPREQ_PUT: + /* known request body size or -1 */ + if(data->state.infilesize != -1) + stream->upload_left = data->state.infilesize; + else + /* data sending without specifying the data amount up front */ + stream->upload_left = -1; /* unknown */ + break; + default: + /* there is no request body */ + stream->upload_left = 0; /* no request body */ + break; + } + + stream->send_closed = (stream->upload_left == 0); + if(!stream->send_closed) { + reader.read_data = cb_h3_read_req_body; + preader = &reader; + } + + rc = nghttp3_conn_submit_request(ctx->h3conn, stream->id, + nva, nheader, preader, data); + if(rc) { + switch(rc) { + case NGHTTP3_ERR_CONN_CLOSING: + CURL_TRC_CF(data, cf, "h3sid[%" PRId64 "] failed to send, " + "connection is closing", stream->id); + break; + default: + CURL_TRC_CF(data, cf, "h3sid[%" PRId64 "] failed to send -> " + "%d (%s)", stream->id, rc, nghttp3_strerror(rc)); + break; + } + Curl_cf_ngtcp2_h3_stream_close(cf, data, stream); + result = CURLE_SEND_ERROR; + goto out; + } + + cf_ngtcp2_upd_rx_win(cf, data, stream); + + if(Curl_trc_is_verbose(data)) { + infof(data, "[HTTP/3] [%" PRId64 "] OPENED stream for %s", + stream->id, Curl_bufref_ptr(&data->state.url)); + for(i = 0; i < nheader; ++i) { + infof(data, "[HTTP/3] [%" PRId64 "] [%.*s: %.*s]", stream->id, + (int)nva[i].namelen, nva[i].name, + (int)nva[i].valuelen, nva[i].value); + } + } + +out: + curlx_free(nva); + Curl_dynhds_free(&h2_headers); + return result; +} + +static CURLcode cf_ngtcp2_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const uint8_t *buf, size_t len, bool eos, + size_t *pnwritten) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + struct cf_call_data save; + struct cf_ngtcp2_io_ctx pktx; + CURLcode result = CURLE_OK; + + CF_DATA_SAVE(save, cf, data); + DEBUGASSERT(cf->connected); + DEBUGASSERT(ctx->qconn); + DEBUGASSERT(ctx->h3conn); + Curl_cf_ngtcp2_io_ctx_init(&pktx, cf, data); + *pnwritten = 0; + + /* handshake verification failed in callback, do not send anything */ + if(ctx->tls_vrfy_result) { + result = ctx->tls_vrfy_result; + goto denied; + } + + (void)eos; /* use for stream EOF and block handling */ + result = Curl_cf_ngtcp2_progress_ingress(cf, data, &pktx); + if(result) + goto out; + + if(!stream || stream->id < 0) { + if(ctx->shutdown_started) { + CURL_TRC_CF(data, cf, "cannot open stream on closed connection"); + result = CURLE_SEND_ERROR; + goto out; + } + result = h3_stream_open(cf, data, buf, len, pnwritten); + if(result) { + CURL_TRC_CF(data, cf, "failed to open stream -> %d", (int)result); + goto out; + } + stream = H3_STREAM_CTX(ctx, data); + } + else if(stream->xfer_result) { + CURL_TRC_CF(data, cf, "[%" PRId64 "] xfer write failed", stream->id); + Curl_cf_ngtcp2_h3_stream_close(cf, data, stream); + result = stream->xfer_result; + goto out; + } + else if(stream->closed) { + if(stream->resp_hds_complete) { + /* Server decided to close the stream after having sent us a final + * response. This is valid if it is not interested in the request + * body. This happens on 30x or 40x responses. + * We silently discard the data sent, since this is not a transport + * error situation. */ + CURL_TRC_CF(data, cf, "[%" PRId64 "] discarding data" + "on closed stream with response", stream->id); + result = CURLE_OK; + *pnwritten = len; + goto out; + } + CURL_TRC_CF(data, cf, "[%" PRId64 "] send_body(len=%zu) " + "-> stream closed", stream->id, len); + result = CURLE_HTTP3; + goto out; + } + else if(ctx->shutdown_started) { + CURL_TRC_CF(data, cf, "cannot send on closed connection"); + result = CURLE_SEND_ERROR; + goto out; + } + else if(stream->tx_in_flight_size >= stream->tx_in_flight_ideal) { + result = CURLE_AGAIN; + goto out; + } + else { + result = Curl_bufq_write(&stream->sendbuf, buf, len, pnwritten); + CURL_TRC_CF(data, cf, "[%" PRId64 "] cf_send, add to " + "sendbuf(len=%zu) -> %d, %zu", + stream->id, len, (int)result, *pnwritten); + if(result) + goto out; + (void)nghttp3_conn_resume_stream(ctx->h3conn, stream->id); + } + + if(*pnwritten > 0 && !ctx->tls_handshake_complete && ctx->use_earlydata) + ctx->earlydata_skip += *pnwritten; + + DEBUGASSERT(!result); + result = Curl_cf_ngtcp2_progress_egress(cf, data, &pktx); + + if(*pnwritten > 0) { + const size_t delta = (2 * 1024); + if(stream->tx_in_flight_size > (stream->tx_in_flight_ideal + delta)) { + /* ngtcp2 keeps more in flight than we try to provide for, + * increase our "ideal" tx buffer length */ + stream->tx_in_flight_ideal += delta; + CURL_TRC_CF(data, cf, "[%" PRId64 "] cf_send(%zu), added %zu, " + "inflight=%zu, increase tx_win=%zu", + stream->id, len, *pnwritten, + stream->tx_in_flight_size, stream->tx_in_flight_ideal); + } + else if((stream->tx_in_flight_size + delta) < stream->tx_in_flight_ideal) { + /* ngtcp2 keeps less in flight than we try to provide for, + * decrease our "ideal" tx buffer length */ + stream->tx_in_flight_ideal -= delta; + CURL_TRC_CF(data, cf, "[%" PRId64 "] cf_send(%zu), added %zu, " + "inflight=%zu, reduce tx_win=%zu", + stream->id, len, *pnwritten, + stream->tx_in_flight_size, stream->tx_in_flight_ideal); + } + } + +out: + result = Curl_1st_fatal(result, + Curl_cf_ngtcp2_cmn_set_expiry(cf, data, &pktx)); + if(ctx->tls_vrfy_result) + result = ctx->tls_vrfy_result; +denied: + CURL_TRC_CF(data, cf, "[%" PRId64 "] cf_send(len=%zu) -> %d, %zu", + stream ? stream->id : -1, len, (int)result, *pnwritten); + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode h3_data_pause(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool pause) +{ + /* There seems to exist no API in ngtcp2 to shrink/enlarge the streams + * windows. As we do in HTTP/2. */ + (void)cf; + if(!pause) + Curl_multi_mark_dirty(data); + return CURLE_OK; +} + +static CURLcode cf_ngtcp2_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + switch(event) { + case CF_CTRL_DATA_SETUP: + break; + case CF_CTRL_DATA_PAUSE: + result = h3_data_pause(cf, data, (arg1 != 0)); + break; + case CF_CTRL_DATA_DONE: + Curl_cf_ngtcp2_h3_stream_done(cf, data); + break; + case CF_CTRL_DATA_DONE_SEND: { + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + if(stream && !stream->send_closed) { + stream->send_closed = TRUE; + stream->upload_left = Curl_bufq_len(&stream->sendbuf) - + stream->tx_in_flight_size; + (void)nghttp3_conn_resume_stream(ctx->h3conn, stream->id); + } + break; + } + case CF_CTRL_CONN_INFO_UPDATE: + if(!cf->sockindex && cf->connected) { + cf->conn->httpversion_seen = 30; + Curl_conn_set_multiplex(cf->conn); + } + break; + default: + result = Curl_cf_ngtcp2_cmn_cntrl(cf, data, event, arg1, arg2); + break; + } + CF_DATA_RESTORE(cf, save); + return result; +} + +static void cf_ngtcp2_ctx_close(struct cf_ngtcp2_ctx *ctx) +{ + struct cf_call_data save = ctx->call_data; + + if(!ctx->initialized) + return; + if(ctx->qlogfd != -1) { + curlx_close(ctx->qlogfd); + } + ctx->qlogfd = -1; + Curl_vquic_tls_cleanup(&ctx->tls); + Curl_ssl_peer_cleanup(&ctx->ssl_peer); + Curl_vquic_ctx_free(&ctx->q); + if(ctx->h3conn) { + nghttp3_conn_del(ctx->h3conn); + ctx->h3conn = NULL; + } + if(ctx->qconn) { + ngtcp2_conn_del(ctx->qconn); + ctx->qconn = NULL; + } +#ifdef OPENSSL_QUIC_API2 + if(ctx->ossl_ctx) { + ngtcp2_crypto_ossl_ctx_del(ctx->ossl_ctx); + ctx->ossl_ctx = NULL; + } +#endif + ctx->call_data = save; +} + +static void cf_ngtcp2_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + + CURL_TRC_CF(data, cf, "destroy"); + if(ctx) { + if(ctx->qconn) { + struct cf_call_data save; + CF_DATA_SAVE(save, cf, data); + Curl_cf_ngtcp2_cmn_conn_close(cf, data); + cf_ngtcp2_ctx_close(ctx); + CF_DATA_RESTORE(cf, save); + } + Curl_cf_ngtcp2_ctx_cleanup(ctx); + curlx_free(ctx); + cf->ctx = NULL; + } +} + +static CURLcode cf_ngtcp2_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + return Curl_cf_ngtcp2_cmn_connect(cf, data, done); +} + +static CURLcode cf_ngtcp2_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct cf_call_data save; + + switch(query) { + case CF_QUERY_MAX_CONCURRENT: { + DEBUGASSERT(pres1); + CF_DATA_SAVE(save, cf, data); + /* Set after transport params arrived and continually updated + * by callback. QUIC counts the number over the lifetime of the + * connection, ever increasing. + * We count the *open* transfers plus the budget for new ones. */ + if(!ctx->qconn || ctx->shutdown_started) { + *pres1 = 0; + } + else if(ctx->max_bidi_streams) { + uint64_t avail_bidi_streams = 0; + uint64_t max_streams = cf->conn->attached_xfers; + if(ctx->max_bidi_streams > ctx->used_bidi_streams) + avail_bidi_streams = ctx->max_bidi_streams - ctx->used_bidi_streams; + max_streams += avail_bidi_streams; + *pres1 = (max_streams > INT_MAX) ? INT_MAX : (int)max_streams; + } + else /* transport params not arrived yet? take our default. */ + *pres1 = (int)Curl_multi_max_concurrent_streams(data->multi); + CURL_TRC_CF(data, cf, "query conn[%" FMT_OFF_T "]: " + "MAX_CONCURRENT -> %d (%u in use)", + cf->conn->connection_id, *pres1, cf->conn->attached_xfers); + CF_DATA_RESTORE(cf, save); + return CURLE_OK; + } + case CF_QUERY_HTTP_VERSION: + *pres1 = 30; + return CURLE_OK; + case CF_QUERY_SSL_INFO: + case CF_QUERY_SSL_CTX_INFO: { + struct curl_tlssessioninfo *info = pres2; + if(Curl_vquic_tls_get_ssl_info(&ctx->tls, + (query == CF_QUERY_SSL_CTX_INFO), info)) + return CURLE_OK; + break; + } + case CF_QUERY_ALPN_NEGOTIATED: { + const char **palpn = pres2; + DEBUGASSERT(palpn); + *palpn = cf->connected ? "h3" : NULL; + return CURLE_OK; + } + default: + break; + } + return Curl_cf_ngtcp2_cmn_query(cf, data, query, pres1, pres2); +} + +struct Curl_cftype Curl_cft_http3 = { + "HTTP/3", + CF_TYPE_IP_CONNECT | CF_TYPE_SSL | CF_TYPE_MULTIPLEX | CF_TYPE_HTTP, + 0, + cf_ngtcp2_destroy, + cf_ngtcp2_connect, + Curl_cf_ngtcp2_cmn_shutdown, + cf_ngtcp2_adjust_pollset, + Curl_cf_def_data_pending, + cf_ngtcp2_send, + cf_ngtcp2_recv, + cf_ngtcp2_cntrl, + Curl_cf_ngtcp2_cmn_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_ngtcp2_query, +}; + +CURLcode Curl_cf_ngtcp2_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr) +{ + struct cf_ngtcp2_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL; + CURLcode result; + + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + result = Curl_cf_ngtcp2_ctx_init(ctx, origin, peer, + &conn->ssl_config, init_ngh3_conn); + if(!result) + result = Curl_cf_create(&cf, &Curl_cft_http3, ctx); + if(result) + goto out; + cf->conn = conn; + + result = Curl_cf_udp_create(&cf->next, data, origin, peer, TRNSPRT_QUIC, + conn, addr, NULL, TRNSPRT_QUIC); + if(result) + goto out; + cf->next->conn = cf->conn; + cf->next->sockindex = cf->sockindex; + +out: + *pcf = (!result) ? cf : NULL; + if(result) { + if(cf) + Curl_conn_cf_discard_chain(&cf, data); + else if(ctx) { + Curl_cf_ngtcp2_ctx_cleanup(ctx); + curlx_free(ctx); + } + } + return result; +} + +CURLcode Curl_cf_ngtcp2_insert_after(struct Curl_cfilter *cf_at, + struct Curl_peer *origin, + struct Curl_peer *peer) +{ + struct cf_ngtcp2_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL; + CURLcode result; + + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + result = Curl_cf_ngtcp2_ctx_init(ctx, origin, peer, + &cf_at->conn->ssl_config, init_ngh3_conn); + if(!result) + result = Curl_cf_create(&cf, &Curl_cft_http3, ctx); + if(result) + goto out; + Curl_conn_cf_insert_after(cf_at, cf); +out: + if(result) { + curlx_safefree(cf); + if(ctx) { + Curl_cf_ngtcp2_ctx_cleanup(ctx); + curlx_free(ctx); + } + } + return result; +} + +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2.h new file mode 100644 index 0000000000..601efc8224 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-ngtcp2.h @@ -0,0 +1,63 @@ +#ifndef HEADER_CURL_VQUIC_CF_NGTCP2_H +#define HEADER_CURL_VQUIC_CF_NGTCP2_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_NGTCP2) && defined(USE_NGHTTP3) + +#ifdef HAVE_NETINET_UDP_H +#include <netinet/udp.h> +#endif + +#include <ngtcp2/ngtcp2_crypto.h> +#ifdef OPENSSL_QUIC_API2 +#include <ngtcp2/ngtcp2_crypto_ossl.h> +#endif +#include <nghttp3/nghttp3.h> +#ifdef USE_OPENSSL +#include <openssl/ssl.h> +#elif defined(USE_WOLFSSL) +#include <wolfssl/options.h> +#include <wolfssl/ssl.h> +#include <wolfssl/quic.h> +#endif + +struct Curl_cfilter; + +#include "urldata.h" + +CURLcode Curl_cf_ngtcp2_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr); + +CURLcode Curl_cf_ngtcp2_insert_after(struct Curl_cfilter *cf_at, + struct Curl_peer *origin, + struct Curl_peer *peer); +#endif + +#endif /* HEADER_CURL_VQUIC_CF_NGTCP2_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-quiche.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-quiche.c new file mode 100644 index 0000000000..934a56cada --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-quiche.c @@ -0,0 +1,1713 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_QUICHE) +#include <quiche.h> +#include <openssl/err.h> +#include <openssl/ssl.h> + +#include "bufq.h" +#include "uint-hash.h" +#include "urldata.h" +#include "cfilters.h" +#include "cf-socket.h" +#include "curl_trc.h" +#include "rand.h" +#include "multiif.h" +#include "connect.h" +#include "progress.h" +#include "select.h" +#include "http.h" +#include "http1.h" +#include "sockaddr.h" +#include "vdns/cf-dns.h" +#include "vquic/vquic.h" +#include "vquic/vquic_int.h" +#include "vquic/vquic-tls.h" +#include "vquic/cf-quiche.h" +#include "transfer.h" +#include "url.h" +#include "bufref.h" +#include "vtls/openssl.h" +#include "vtls/vtls.h" + +/* HTTP/3 error values defined in RFC 9114, ch. 8.1 */ +#define CURL_H3_NO_ERROR 0x0100 + +#define MAX_PKT_BURST 10 + +#define QUIC_MAX_STREAMS 100 + +#define H3_STREAM_WINDOW_SIZE (1024 * 128) +#define H3_STREAM_CHUNK_SIZE (1024 * 16) +/* Receive and Send max number of chunks follows from the + * chunk size and window size */ +#define H3_STREAM_RECV_CHUNKS \ + (H3_STREAM_WINDOW_SIZE / H3_STREAM_CHUNK_SIZE) + +/* + * Store quiche version info in this buffer. + */ +void Curl_quiche_ver(char *p, size_t len) +{ + (void)curl_msnprintf(p, len, "quiche/%s", quiche_version()); +} + +struct cf_quiche_ctx { + struct cf_quic_ctx q; + struct ssl_peer ssl_peer; + struct curl_tls_ctx tls; + quiche_conn *qconn; + quiche_config *cfg; + quiche_h3_conn *h3c; + quiche_h3_config *h3config; + uint8_t scid[QUICHE_MAX_CONN_ID_LEN]; + struct curltime started_at; /* time the current attempt started */ + struct curltime handshake_at; /* time connect handshake finished */ + struct uint_hash streams; /* hash `data->mid` to `stream_ctx` */ + struct dynbuf h1hdr; /* temp buffer for header construction */ + struct bufq writebuf; /* temp buffer for writing bodies */ + curl_off_t data_recvd; + BIT(initialized); + BIT(goaway); /* got GOAWAY from server */ + BIT(x509_store_setup); /* if x509 store has been set up */ + BIT(shutdown_started); /* queued shutdown packets */ + BIT(stats_reported); /* connect statistics reported */ +}; + +#ifdef DEBUG_QUICHE +/* initialize debug log callback only once */ +static int debug_log_init = 0; +static void quiche_debug_log(const char *line, void *argp) +{ + (void)argp; + curl_mfprintf(stderr, "%s\n", line); +} +#endif + +static void h3_stream_hash_free(unsigned int id, void *stream); + +static CURLcode cf_quiche_ctx_init(struct cf_quiche_ctx *ctx, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct ssl_primary_config *sslc) +{ + DEBUGASSERT(!ctx->initialized); +#ifdef DEBUG_QUICHE + if(!debug_log_init) { + quiche_enable_debug_logging(quiche_debug_log, NULL); + debug_log_init = 1; + } +#endif + curlx_dyn_init(&ctx->h1hdr, CURL_MAX_HTTP_HEADER); + Curl_uint32_hash_init(&ctx->streams, 63, h3_stream_hash_free); + Curl_bufq_init2(&ctx->writebuf, H3_STREAM_CHUNK_SIZE, H3_STREAM_RECV_CHUNKS, + BUFQ_OPT_SOFT_LIMIT); + ctx->data_recvd = 0; + ctx->initialized = TRUE; + return Curl_vquic_tls_peer_init(origin, peer, sslc, &ctx->ssl_peer); +} + +static void cf_quiche_ctx_free(struct cf_quiche_ctx *ctx) +{ + if(ctx && ctx->initialized) { + /* quiche freed it */ + ctx->tls.ossl.ssl = NULL; + Curl_vquic_tls_cleanup(&ctx->tls); + Curl_ssl_peer_cleanup(&ctx->ssl_peer); + Curl_vquic_ctx_free(&ctx->q); + Curl_uint32_hash_destroy(&ctx->streams); + curlx_dyn_free(&ctx->h1hdr); + Curl_bufq_free(&ctx->writebuf); + } + curlx_free(ctx); +} + +static void cf_quiche_ctx_close(struct cf_quiche_ctx *ctx) +{ + if(ctx->h3c) { + quiche_h3_conn_free(ctx->h3c); + ctx->h3c = NULL; + } + if(ctx->h3config) { + quiche_h3_config_free(ctx->h3config); + ctx->h3config = NULL; + } + if(ctx->qconn) { + quiche_conn_free(ctx->qconn); + ctx->qconn = NULL; + } + if(ctx->cfg) { + quiche_config_free(ctx->cfg); + ctx->cfg = NULL; + } + Curl_ssl_peer_cleanup(&ctx->ssl_peer); +} + +static CURLcode cf_flush_egress(struct Curl_cfilter *cf, + struct Curl_easy *data); + +/** + * All about the H3 internals of a stream + */ +struct h3_stream_ctx { + uint64_t id; /* HTTP/3 protocol stream identifier */ + struct h1_req_parser h1; /* h1 request parsing */ + uint64_t error3; /* HTTP/3 stream error code */ + int status_code; /* HTTP status code */ + CURLcode xfer_result; /* result from cf_quiche_write_(hd/body) */ + BIT(opened); /* TRUE after stream has been opened */ + BIT(closed); /* TRUE on stream close */ + BIT(reset); /* TRUE on stream reset */ + BIT(send_closed); /* stream is locally closed */ + BIT(resp_hds_complete); /* final response has been received */ + BIT(resp_got_header); /* TRUE when h3 stream has recvd some HEADER */ + BIT(quic_flow_blocked); /* stream is blocked by QUIC flow control */ +}; + +static void h3_stream_ctx_free(struct h3_stream_ctx *stream) +{ + Curl_h1_req_parse_free(&stream->h1); + curlx_free(stream); +} + +static void h3_stream_hash_free(unsigned int id, void *stream) +{ + (void)id; + DEBUGASSERT(stream); + h3_stream_ctx_free((struct h3_stream_ctx *)stream); +} + +typedef bool cf_quiche_svisit(struct Curl_cfilter *cf, + struct Curl_easy *sdata, + struct h3_stream_ctx *stream, + void *user_data); + +struct cf_quiche_visit_ctx { + struct Curl_cfilter *cf; + struct Curl_multi *multi; + cf_quiche_svisit *cb; + void *user_data; +}; + +static bool cf_quiche_stream_do(uint32_t mid, void *val, void *user_data) +{ + struct cf_quiche_visit_ctx *vctx = user_data; + struct h3_stream_ctx *stream = val; + struct Curl_easy *sdata = Curl_multi_get_easy(vctx->multi, mid); + if(sdata) + return vctx->cb(vctx->cf, sdata, stream, vctx->user_data); + return TRUE; +} + +static void cf_quiche_for_all_streams(struct Curl_cfilter *cf, + struct Curl_multi *multi, + cf_quiche_svisit *do_cb, + void *user_data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct cf_quiche_visit_ctx vctx; + vctx.cf = cf; + vctx.multi = multi; + vctx.cb = do_cb; + vctx.user_data = user_data; + Curl_uint32_hash_visit(&ctx->streams, cf_quiche_stream_do, &vctx); +} + +static bool cf_quiche_do_resume(struct Curl_cfilter *cf, + struct Curl_easy *sdata, + struct h3_stream_ctx *stream, + void *user_data) +{ + (void)user_data; + if(stream->quic_flow_blocked) { + stream->quic_flow_blocked = FALSE; + Curl_multi_mark_dirty(sdata); + CURL_TRC_CF(sdata, cf, "[%" PRIu64 "] unblock", stream->id); + } + return TRUE; +} + +static bool cf_quiche_do_expire(struct Curl_cfilter *cf, + struct Curl_easy *sdata, + struct h3_stream_ctx *stream, + void *user_data) +{ + (void)user_data; + CURL_TRC_CF(sdata, cf, "conn closed, mark as dirty"); + stream->xfer_result = CURLE_SEND_ERROR; + Curl_multi_mark_dirty(sdata); + return TRUE; +} + +static CURLcode h3_data_setup(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + if(stream) + return CURLE_OK; + + stream = curlx_calloc(1, sizeof(*stream)); + if(!stream) + return CURLE_OUT_OF_MEMORY; + + stream->id = -1; + Curl_h1_req_parse_init(&stream->h1, H1_PARSE_DEFAULT_MAX_LINE_LEN); + + if(!Curl_uint32_hash_set(&ctx->streams, data->mid, stream)) { + h3_stream_ctx_free(stream); + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} + +static void cf_quiche_stream_close(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + CURLcode result; + + if(ctx->qconn && !stream->closed) { + quiche_conn_stream_shutdown(ctx->qconn, stream->id, + QUICHE_SHUTDOWN_READ, CURL_H3_NO_ERROR); + if(!stream->send_closed) { + quiche_conn_stream_shutdown(ctx->qconn, stream->id, + QUICHE_SHUTDOWN_WRITE, CURL_H3_NO_ERROR); + stream->send_closed = TRUE; + } + stream->closed = TRUE; + result = cf_flush_egress(cf, data); + if(result) + CURL_TRC_CF(data, cf, "[%" PRIu64 "] stream close, flush egress -> %d", + stream->id, (int)result); + } +} + +static void h3_data_done(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + (void)cf; + if(stream) { + CURL_TRC_CF(data, cf, "[%" PRIu64 "] easy handle is done", stream->id); + cf_quiche_stream_close(cf, data, stream); + Curl_uint32_hash_remove(&ctx->streams, data->mid); + } +} + +static void cf_quiche_expire_conn_closed(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + DEBUGASSERT(data->multi); + CURL_TRC_CF(data, cf, "conn closed, expire all transfers"); + cf_quiche_for_all_streams(cf, data->multi, cf_quiche_do_expire, NULL); +} + +static void cf_quiche_write_hd(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream, + const char *buf, size_t blen, bool eos) +{ + /* This function returns no error intentionally, but records + * the result at the stream, skipping further writes once the + * `result` of the transfer is known. + * The stream is subsequently cancelled "higher up" in the filter's + * send/recv callbacks. Closing the stream here leads to SEND/RECV + * errors in other places that then overwrite the transfer's result. */ + if(!stream->xfer_result) { + stream->xfer_result = Curl_xfer_write_resp_hd(data, buf, blen, eos); + if(stream->xfer_result) + CURL_TRC_CF(data, cf, "[%" PRIu64 "] error %d writing %zu " + "bytes of headers", stream->id, (int)stream->xfer_result, + blen); + } +} + +struct cb_ctx { + struct Curl_cfilter *cf; + struct Curl_easy *data; + struct h3_stream_ctx *stream; +}; + +static bool is_valid_h3_header(const uint8_t *hdr, size_t hlen) +{ + while(hlen--) { + switch(*hdr++) { + case '\n': + case '\r': + case '\0': + return FALSE; + } + } + return TRUE; +} + +static int cb_each_header(uint8_t *name, size_t name_len, + uint8_t *value, size_t value_len, + void *argp) +{ + struct cb_ctx *x = argp; + struct Curl_cfilter *cf = x->cf; + struct Curl_easy *data = x->data; + struct h3_stream_ctx *stream = x->stream; + struct cf_quiche_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(!stream || stream->xfer_result) + return 1; /* abort iteration */ + + if((name_len == 7) && !strncmp(HTTP_PSEUDO_STATUS, (char *)name, 7) && + is_valid_h3_header(value, value_len)) { + curlx_dyn_reset(&ctx->h1hdr); + result = Curl_http_decode_status(&stream->status_code, + (const char *)value, value_len); + if(!result) + result = curlx_dyn_addn(&ctx->h1hdr, STRCONST("HTTP/3 ")); + if(!result) + result = curlx_dyn_addn(&ctx->h1hdr, (const char *)value, value_len); + if(!result) + result = curlx_dyn_addn(&ctx->h1hdr, STRCONST(" \r\n")); + if(!result) + cf_quiche_write_hd(cf, data, stream, curlx_dyn_ptr(&ctx->h1hdr), + curlx_dyn_len(&ctx->h1hdr), FALSE); + CURL_TRC_CF(data, cf, "[%" PRIu64 "] status: %s", + stream->id, curlx_dyn_ptr(&ctx->h1hdr)); + } + else { + if(is_valid_h3_header(value, value_len) && + is_valid_h3_header(name, name_len)) { + /* store as an HTTP1-style header */ + CURL_TRC_CF(data, cf, "[%" PRIu64 "] header: %.*s: %.*s", + stream->id, (int)name_len, name, + (int)value_len, value); + curlx_dyn_reset(&ctx->h1hdr); + result = curlx_dyn_addn(&ctx->h1hdr, (const char *)name, name_len); + if(!result) + result = curlx_dyn_addn(&ctx->h1hdr, STRCONST(": ")); + if(!result) + result = curlx_dyn_addn(&ctx->h1hdr, (const char *)value, value_len); + if(!result) + result = curlx_dyn_addn(&ctx->h1hdr, STRCONST("\r\n")); + if(!result) + cf_quiche_write_hd(cf, data, stream, curlx_dyn_ptr(&ctx->h1hdr), + curlx_dyn_len(&ctx->h1hdr), FALSE); + } + else + CURL_TRC_CF(x->data, x->cf, "[%" PRIu64 "] ignore %zu bytes bad header", + stream->id, value_len + name_len); + } + + if(result) { + CURL_TRC_CF(x->data, x->cf, "[%" PRIu64 "] on header error %d", + stream->id, (int)result); + if(!stream->xfer_result) + stream->xfer_result = result; + } + return stream->xfer_result ? 1 : 0; +} + +static CURLcode stream_resp_read(void *reader_ctx, + unsigned char *buf, size_t len, + size_t *pnread) +{ + struct cb_ctx *x = reader_ctx; + struct cf_quiche_ctx *ctx = x->cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, x->data); + ssize_t nread; + + *pnread = 0; + if(!stream) + return CURLE_RECV_ERROR; + + nread = quiche_h3_recv_body(ctx->h3c, ctx->qconn, stream->id, buf, len); + if(!curlx_sztouz(nread, pnread)) + return CURLE_AGAIN; + return CURLE_OK; +} + +static void cf_quiche_flush_body(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + const uint8_t *buf; + size_t blen; + + while(stream && !stream->xfer_result) { + if(Curl_bufq_peek(&ctx->writebuf, &buf, &blen)) { + stream->xfer_result = Curl_xfer_write_resp( + data, (const char *)buf, blen, FALSE); + Curl_bufq_skip(&ctx->writebuf, blen); + if(stream->xfer_result) { + CURL_TRC_CF(data, cf, "[%" PRIu64 "] error %d writing %zu bytes" + " of data", stream->id, (int)stream->xfer_result, blen); + } + } + else + break; + } + Curl_bufq_reset(&ctx->writebuf); +} + +static void cf_quiche_recv_body(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + size_t nread; + struct cb_ctx cb_ctx; + CURLcode result = CURLE_OK; + + if(!stream) + return; + + /* Even when the transfer has already errored, we need to receive + * the data from quiche, as quiche otherwise gets stuck and + * raise events to receive over and over again. */ + cb_ctx.cf = cf; + cb_ctx.data = data; + cb_ctx.stream = stream; + Curl_bufq_reset(&ctx->writebuf); + while(!result) { + result = Curl_bufq_slurp(&ctx->writebuf, + stream_resp_read, &cb_ctx, &nread); + if(!result) + cf_quiche_flush_body(cf, data, stream); + else if(result == CURLE_AGAIN) + break; + else if(result) { + CURL_TRC_CF(data, cf, "[%" PRIu64 "] recv_body error %d", + stream->id, (int)result); + failf(data, "[%" PRIu64 "] Error %d in HTTP/3 response body for stream", + stream->id, (int)result); + stream->closed = TRUE; + stream->reset = TRUE; + stream->send_closed = TRUE; + if(!stream->xfer_result) + stream->xfer_result = result; + } + } + cf_quiche_flush_body(cf, data, stream); +} + +static void cf_quiche_process_ev(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream, + quiche_h3_event *ev) +{ + enum quiche_h3_event_type type; + + if(!stream) + return; + + type = quiche_h3_event_type(ev); + + switch(type) { + case QUICHE_H3_EVENT_HEADERS: { + struct cb_ctx cb_ctx; + stream->resp_got_header = TRUE; + cb_ctx.cf = cf; + cb_ctx.data = data; + cb_ctx.stream = stream; + quiche_h3_event_for_each_header(ev, cb_each_header, &cb_ctx); + CURL_TRC_CF(data, cf, "[%" PRIu64 "] <- [HEADERS]", stream->id); + Curl_multi_mark_dirty(data); + break; + } + case QUICHE_H3_EVENT_DATA: + if(!stream->resp_hds_complete) { + stream->resp_hds_complete = TRUE; + cf_quiche_write_hd(cf, data, stream, "\r\n", 2, FALSE); + } + cf_quiche_recv_body(cf, data, stream); + CURL_TRC_CF(data, cf, "[%" PRIu64 "] <- [DATA]", stream->id); + Curl_multi_mark_dirty(data); + break; + + case QUICHE_H3_EVENT_RESET: + CURL_TRC_CF(data, cf, "[%" PRIu64 "] RESET", stream->id); + stream->closed = TRUE; + stream->reset = TRUE; + stream->send_closed = TRUE; + Curl_multi_mark_dirty(data); + break; + + case QUICHE_H3_EVENT_FINISHED: + CURL_TRC_CF(data, cf, "[%" PRIu64 "] CLOSED", stream->id); + if(!stream->resp_hds_complete) { + stream->resp_hds_complete = TRUE; + cf_quiche_write_hd(cf, data, stream, "\r\n", 2, TRUE); + } + stream->closed = TRUE; + Curl_multi_mark_dirty(data); + break; + + case QUICHE_H3_EVENT_GOAWAY: + CURL_TRC_CF(data, cf, "[%" PRIu64 "] <- [GOAWAY]", stream->id); + break; + + default: + CURL_TRC_CF(data, cf, "[%" PRIu64 "] recv, unhandled event %d", + stream->id, (int)type); + break; + } +} + +struct cf_quiche_disp_ctx { + uint64_t stream_id; + struct Curl_cfilter *cf; + struct Curl_multi *multi; + quiche_h3_event *ev; +}; + +static bool cf_quiche_disp_event(uint32_t mid, void *val, void *user_data) +{ + struct cf_quiche_disp_ctx *dctx = user_data; + struct h3_stream_ctx *stream = val; + + if(stream->id == dctx->stream_id) { + struct Curl_easy *sdata = Curl_multi_get_easy(dctx->multi, mid); + if(sdata) + cf_quiche_process_ev(dctx->cf, sdata, stream, dctx->ev); + return FALSE; /* stop iterating */ + } + return TRUE; +} + +static CURLcode cf_poll_events(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = NULL; + quiche_h3_event *ev; + + /* Take in the events and distribute them to the transfers. */ + while(ctx->h3c) { + int64_t rv = quiche_h3_conn_poll(ctx->h3c, ctx->qconn, &ev); + if(rv == QUICHE_H3_ERR_DONE) { + break; + } + else if(rv < 0) { + CURL_TRC_CF(data, cf, "error poll: %" PRId64, rv); + return CURLE_HTTP3; + } + else { + stream = H3_STREAM_CTX(ctx, data); + if(stream && stream->id == (uint64_t)rv) { + /* event for calling transfer */ + cf_quiche_process_ev(cf, data, stream, ev); + quiche_h3_event_free(ev); + if(stream->xfer_result) + return stream->xfer_result; + } + else { + /* another transfer, do not return errors, as they are not for + * the calling transfer */ + struct cf_quiche_disp_ctx dctx; + dctx.stream_id = (uint64_t)rv; + dctx.cf = cf; + dctx.multi = data->multi; + dctx.ev = ev; + Curl_uint32_hash_visit(&ctx->streams, cf_quiche_disp_event, &dctx); + quiche_h3_event_free(ev); + } + } + } + return CURLE_OK; +} + +struct recv_ctx { + struct Curl_cfilter *cf; + struct Curl_easy *data; + int pkts; +}; + +static CURLcode cf_quiche_recv_pkts(const unsigned char *buf, size_t buflen, + size_t gso_size, + struct sockaddr_storage *remote_addr, + socklen_t remote_addrlen, uint8_t ecn, + void *userp) +{ + struct recv_ctx *r = userp; + struct cf_quiche_ctx *ctx = r->cf->ctx; + quiche_recv_info recv_info; + size_t pktlen, offset, nread; + ssize_t rv; + + (void)ecn; + + recv_info.to = (struct sockaddr *)&ctx->q.local_addr; + recv_info.to_len = ctx->q.local_addrlen; + recv_info.from = (struct sockaddr *)remote_addr; + recv_info.from_len = remote_addrlen; + + for(offset = 0; offset < buflen; offset += gso_size) { + pktlen = ((offset + gso_size) <= buflen) ? gso_size : (buflen - offset); + rv = quiche_conn_recv(ctx->qconn, + (unsigned char *)CURL_UNCONST(buf + offset), + pktlen, &recv_info); + if(!curlx_sztouz(rv, &nread)) { + if(QUICHE_ERR_DONE == rv) { + if(quiche_conn_is_draining(ctx->qconn)) { + CURL_TRC_CF(r->data, r->cf, "ingress, connection is draining"); + return CURLE_RECV_ERROR; + } + if(quiche_conn_is_closed(ctx->qconn)) { + CURL_TRC_CF(r->data, r->cf, "ingress, connection is closed"); + return CURLE_RECV_ERROR; + } + CURL_TRC_CF(r->data, r->cf, "ingress, quiche is DONE"); + return CURLE_OK; + } + else if(QUICHE_ERR_TLS_FAIL == rv) { + long verify_ok = SSL_get_verify_result(ctx->tls.ossl.ssl); + if(verify_ok != X509_V_OK) { + failf(r->data, "SSL certificate problem: %s", + X509_verify_cert_error_string(verify_ok)); + return CURLE_PEER_FAILED_VERIFICATION; + } + failf(r->data, "ingress, quiche reports TLS fail"); + return CURLE_RECV_ERROR; + } + else { + failf(r->data, "quiche reports error %zd on receive", rv); + return CURLE_RECV_ERROR; + } + } + else if(nread < pktlen) { + CURL_TRC_CF(r->data, r->cf, "ingress, quiche only read %zu/%zu bytes", + nread, pktlen); + } + ++r->pkts; + } + + return CURLE_OK; +} + +static CURLcode cf_process_ingress(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct recv_ctx rctx; + CURLcode result; + + DEBUGASSERT(ctx->qconn); + result = Curl_vquic_tls_before_recv(&ctx->tls, cf, data); + if(result) + return result; + + rctx.cf = cf; + rctx.data = data; + rctx.pkts = 0; + + result = Curl_vquic_recv_packets(cf, data, &ctx->q, 1000, + cf_quiche_recv_pkts, &rctx); + if(result) + return result; + + if(rctx.pkts > 0) { + /* quiche digested ingress packets. It might have opened flow control + * windows again. */ + DEBUGASSERT(data->multi); + cf_quiche_for_all_streams(cf, data->multi, cf_quiche_do_resume, NULL); + } + return cf_poll_events(cf, data); +} + +struct read_ctx { + struct Curl_cfilter *cf; + struct Curl_easy *data; + quiche_send_info send_info; +}; + +static CURLcode read_pkt_to_send(void *userp, + unsigned char *buf, size_t buflen, + size_t *pnread) +{ + struct read_ctx *x = userp; + struct cf_quiche_ctx *ctx = x->cf->ctx; + ssize_t rv; + + *pnread = 0; + rv = quiche_conn_send(ctx->qconn, buf, buflen, &x->send_info); + if(rv == QUICHE_ERR_DONE) + return CURLE_AGAIN; + + if(!curlx_sztouz(rv, pnread)) { + failf(x->data, "quiche_conn_send returned %zd", rv); + return CURLE_SEND_ERROR; + } + return CURLE_OK; +} + +/* + * flush_egress drains the buffers and sends off data. + * Calls failf() on errors. + */ +static CURLcode cf_flush_egress(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + size_t nread; + CURLcode result; + int64_t expiry_ns; + int64_t timeout_ns; + struct read_ctx readx; + size_t pkt_count, gsolen; + + expiry_ns = quiche_conn_timeout_as_nanos(ctx->qconn); + if(!expiry_ns) { + quiche_conn_on_timeout(ctx->qconn); + if(quiche_conn_is_closed(ctx->qconn)) { + if(quiche_conn_is_timed_out(ctx->qconn)) + failf(data, "connection closed by idle timeout"); + else + failf(data, "connection closed by server"); + /* Connection timed out, expire all transfers belonging to it + * as it does not get any more POLL events here. */ + cf_quiche_expire_conn_closed(cf, data); + return CURLE_SEND_ERROR; + } + } + + result = Curl_vquic_flush(cf, data, &ctx->q); + if(result) { + if(result == CURLE_AGAIN) { + Curl_expire(data, 1, EXPIRE_QUIC); + return CURLE_OK; + } + return result; + } + + readx.cf = cf; + readx.data = data; + memset(&readx.send_info, 0, sizeof(readx.send_info)); + pkt_count = 0; + gsolen = quiche_conn_max_send_udp_payload_size(ctx->qconn); + for(;;) { + /* add the next packet to send, if any, to our buffer */ + result = Curl_bufq_sipn(&ctx->q.sendbuf, 0, + read_pkt_to_send, &readx, &nread); + if(result) { + if(result != CURLE_AGAIN) + return result; + /* Nothing more to add, flush and leave */ + result = Curl_vquic_send(cf, data, &ctx->q, gsolen); + if(result) { + if(result == CURLE_AGAIN) { + Curl_expire(data, 1, EXPIRE_QUIC); + return CURLE_OK; + } + return result; + } + goto out; + } + + ++pkt_count; + if(nread < gsolen || pkt_count >= MAX_PKT_BURST) { + result = Curl_vquic_send(cf, data, &ctx->q, gsolen); + if(result) { + if(result == CURLE_AGAIN) { + Curl_expire(data, 1, EXPIRE_QUIC); + return CURLE_OK; + } + goto out; + } + pkt_count = 0; + } + } + +out: + timeout_ns = quiche_conn_timeout_as_nanos(ctx->qconn); + if(timeout_ns % 1000000) + timeout_ns += 1000000; + /* expire resolution is milliseconds */ + Curl_expire(data, (timeout_ns / 1000000), EXPIRE_QUIC); + return result; +} + +static CURLcode recv_closed_stream(struct Curl_cfilter *cf, + struct Curl_easy *data, + size_t *pnread) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result = CURLE_OK; + + DEBUGASSERT(stream); + *pnread = 0; + if(stream->reset) { + if(stream->error3 == CURL_H3_ERR_REQUEST_REJECTED) { + infof(data, "HTTP/3 stream %" PRIu64 " refused by server, try again " + "on a new connection", stream->id); + connclose(cf->conn); /* do not use this anymore */ + data->state.refused_stream = TRUE; + return CURLE_RECV_ERROR; /* trigger Curl_retry_request() later */ + } + else if(stream->resp_hds_complete && data->req.no_body) { + CURL_TRC_CF(data, cf, "[%" PRIu64 "] error after response headers, " + "but we did not want a body anyway, ignore error 0x%" + PRIx64 " %s", stream->id, stream->error3, + Curl_vquic_h3_err_str(stream->error3)); + return CURLE_OK; + } + failf(data, "HTTP/3 stream %" PRIu64 " reset by server (error 0x%" PRIx64 + " %s)", stream->id, stream->error3, + Curl_vquic_h3_err_str(stream->error3)); + result = data->req.bytecount ? CURLE_PARTIAL_FILE : CURLE_HTTP3; + CURL_TRC_CF(data, cf, "[%" PRIu64 "] cf_recv, was reset -> %d", + stream->id, (int)result); + } + else if(!stream->resp_got_header) { + failf(data, "HTTP/3 stream %" PRIu64 " was closed cleanly, but before " + "getting all response header fields, treated as error", + stream->id); + result = CURLE_HTTP3; + } + return result; +} + +static CURLcode cf_quiche_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t blen, size_t *pnread) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result = CURLE_OK; + + *pnread = 0; + (void)buf; + (void)blen; + Curl_vquic_ctx_update_time(&ctx->q, Curl_pgrs_now(data)); + + if(!stream) + return CURLE_RECV_ERROR; + + result = cf_process_ingress(cf, data); + if(result) { + CURL_TRC_CF(data, cf, "cf_recv, error on ingress"); + goto out; + } + + if(stream->xfer_result) { + cf_quiche_stream_close(cf, data, stream); + result = stream->xfer_result; + goto out; + } + else if(stream->closed) + result = recv_closed_stream(cf, data, pnread); + else if(quiche_conn_is_draining(ctx->qconn)) { + failf(data, "QUIC connection is draining"); + result = CURLE_HTTP3; + } + else + result = CURLE_AGAIN; + +out: + result = Curl_1st_fatal(result, cf_flush_egress(cf, data)); + if(*pnread > 0) + ctx->data_recvd += *pnread; + CURL_TRC_CF(data, cf, "[%" PRIu64 "] cf_recv(len=%zu) -> %d, %zu, total=%" + FMT_OFF_T, stream->id, blen, (int)result, *pnread, + ctx->data_recvd); + return result; +} + +static CURLcode cf_quiche_send_body(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct h3_stream_ctx *stream, + const uint8_t *buf, size_t len, bool eos, + size_t *pnwritten) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + ssize_t rv; + + *pnwritten = 0; + rv = quiche_h3_send_body(ctx->h3c, ctx->qconn, stream->id, + (uint8_t *)CURL_UNCONST(buf), len, eos); + if(rv == QUICHE_H3_ERR_DONE || (rv == 0 && len > 0)) { + /* Blocked on flow control and should HOLD sending. + When do we open again? */ + if(!quiche_conn_stream_writable(ctx->qconn, stream->id, len)) { + CURL_TRC_CF(data, cf, "[%" PRIu64 "] send_body(len=%zu) " + "-> window exhausted", stream->id, len); + stream->quic_flow_blocked = TRUE; + } + return CURLE_AGAIN; + } + else if(rv == QUICHE_H3_TRANSPORT_ERR_INVALID_STREAM_STATE) { + CURL_TRC_CF(data, cf, "[%" PRIu64 "] send_body(len=%zu) " + "-> invalid stream state", stream->id, len); + return CURLE_HTTP3; + } + else if(rv == QUICHE_H3_TRANSPORT_ERR_FINAL_SIZE) { + CURL_TRC_CF(data, cf, "[%" PRIu64 "] send_body(len=%zu) -> exceeds size", + stream->id, len); + return CURLE_SEND_ERROR; + } + else if(!curlx_sztouz(rv, pnwritten)) { + CURL_TRC_CF(data, cf, "[%" PRIu64 "] send_body(len=%zu) -> quiche err %zd", + stream->id, len, rv); + return CURLE_SEND_ERROR; + } + else { + if(eos && (len == *pnwritten)) + stream->send_closed = TRUE; + CURL_TRC_CF(data, cf, "[%" PRIu64 "] send body(len=%zu, eos=%d) -> %zu", + stream->id, len, stream->send_closed, *pnwritten); + return CURLE_OK; + } +} + +static CURLcode h3_open_stream(struct Curl_cfilter *cf, + struct Curl_easy *data, + const uint8_t *buf, size_t blen, bool eos, + size_t *pnwritten) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + size_t nheader, i; + int64_t rv; + struct dynhds h2_headers; + quiche_h3_header *nva = NULL; + CURLcode result = CURLE_OK; + + *pnwritten = 0; + if(!stream) { + result = h3_data_setup(cf, data); + if(result) + return result; + stream = H3_STREAM_CTX(ctx, data); + DEBUGASSERT(stream); + } + + Curl_dynhds_init(&h2_headers, 0, DYN_HTTP_REQUEST); + + DEBUGASSERT(stream); + + result = Curl_h1_req_parse_read(&stream->h1, buf, blen, NULL, + !data->state.http_ignorecustom ? + CURL_EASY_STR(data, STRING_CUSTOMREQUEST) : NULL, + 0, pnwritten); + if(result) + goto out; + if(!stream->h1.done) { + /* need more data */ + goto out; + } + DEBUGASSERT(stream->h1.req); + + result = Curl_http_req_to_h2(&h2_headers, stream->h1.req, data); + if(result) + goto out; + + /* no longer needed */ + Curl_h1_req_parse_free(&stream->h1); + + nheader = Curl_dynhds_count(&h2_headers); + nva = curlx_malloc(sizeof(quiche_h3_header) * nheader); + if(!nva) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + for(i = 0; i < nheader; ++i) { + struct dynhds_entry *e = Curl_dynhds_getn(&h2_headers, i); + nva[i].name = (unsigned char *)e->name; + nva[i].name_len = e->namelen; + nva[i].value = (unsigned char *)e->value; + nva[i].value_len = e->valuelen; + } + + buf += *pnwritten; + blen -= *pnwritten; + + if(eos && !blen) + stream->send_closed = TRUE; + + rv = quiche_h3_send_request(ctx->h3c, ctx->qconn, nva, nheader, + stream->send_closed); + CURL_TRC_CF(data, cf, "quiche_send_request() -> %" PRId64, rv); + if(rv < 0) { + if(QUICHE_H3_ERR_STREAM_BLOCKED == rv) { + /* quiche seems to report this error if the connection window is + * exhausted. Which happens frequently and intermittent. */ + CURL_TRC_CF(data, cf, "[%" PRIu64 "] blocked", stream->id); + stream->quic_flow_blocked = TRUE; + result = CURLE_AGAIN; + goto out; + } + else { + CURL_TRC_CF(data, cf, "send_request(%s) -> %" PRId64, + Curl_bufref_ptr(&data->state.url), rv); + } + result = CURLE_SEND_ERROR; + goto out; + } + + DEBUGASSERT(!stream->opened); + stream->id = (uint64_t)rv; + stream->opened = TRUE; + stream->closed = FALSE; + stream->reset = FALSE; + + if(Curl_trc_is_verbose(data)) { + infof(data, "[HTTP/3] [%" PRIu64 "] OPENED stream for %s", + stream->id, Curl_bufref_ptr(&data->state.url)); + for(i = 0; i < nheader; ++i) { + infof(data, "[HTTP/3] [%" PRIu64 "] [%.*s: %.*s]", stream->id, + (int)nva[i].name_len, nva[i].name, + (int)nva[i].value_len, nva[i].value); + } + } + + if(blen) { /* after the headers, there was request BODY data */ + size_t nwritten; + CURLcode r2 = CURLE_OK; + + r2 = cf_quiche_send_body(cf, data, stream, buf, blen, eos, &nwritten); + if(r2 && (r2 != CURLE_AGAIN)) { /* real error, fail */ + result = r2; + } + else if(nwritten > 0) { + *pnwritten += nwritten; + } + } + +out: + curlx_free(nva); + Curl_dynhds_free(&h2_headers); + return result; +} + +static CURLcode cf_quiche_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const uint8_t *buf, size_t len, bool eos, + size_t *pnwritten) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + CURLcode result; + + *pnwritten = 0; + Curl_vquic_ctx_update_time(&ctx->q, Curl_pgrs_now(data)); + + result = cf_process_ingress(cf, data); + if(result) + goto out; + + if(!stream || !stream->opened) { + result = h3_open_stream(cf, data, buf, len, eos, pnwritten); + if(result) + goto out; + stream = H3_STREAM_CTX(ctx, data); + } + else if(stream->xfer_result) { + cf_quiche_stream_close(cf, data, stream); + result = stream->xfer_result; + } + else if(stream->closed) { + if(stream->resp_hds_complete) { + /* sending request body on a stream that has been closed by the + * server. If the server has send us a final response, we should + * silently discard the send data. + * This happens for example on redirects where the server, instead + * of reading the full request body closed the stream after + * sending the 30x response. + * This is sort of a race: had the transfer loop called recv first, + * it would see the response and stop/discard sending on its own- */ + CURL_TRC_CF(data, cf, "[%" PRIu64 "] discarding data " + "on closed stream with response", stream->id); + result = CURLE_OK; + *pnwritten = len; + goto out; + } + CURL_TRC_CF(data, cf, "[%" PRIu64 "] send_body(len=%zu) " + "-> stream closed", stream->id, len); + result = CURLE_HTTP3; + goto out; + } + else { + result = cf_quiche_send_body(cf, data, stream, buf, len, eos, pnwritten); + } + +out: + result = Curl_1st_fatal(result, cf_flush_egress(cf, data)); + + CURL_TRC_CF(data, cf, "[%" PRIu64 "] cf_send(len=%zu) -> %d, %zu", + stream ? stream->id : (uint64_t)~0, len, + (int)result, *pnwritten); + return result; +} + +static bool stream_is_writable(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + + return stream && (quiche_conn_stream_writable( + ctx->qconn, stream->id, 1) > 0); +} + +static CURLcode cf_quiche_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + bool want_recv, want_send; + CURLcode result = CURLE_OK; + + if(!ctx->qconn) + return CURLE_OK; + + Curl_pollset_check(data, ps, ctx->q.sockfd, &want_recv, &want_send); + if(want_recv || want_send) { + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + bool c_exhaust, s_exhaust; + + c_exhaust = FALSE; /* Have not found any call in quiche that tells + us if the connection itself is blocked */ + s_exhaust = want_send && stream && stream->opened && + (stream->quic_flow_blocked || !stream_is_writable(cf, data)); + want_recv = (want_recv || c_exhaust || s_exhaust); + want_send = (!s_exhaust && want_send) || + !Curl_bufq_is_empty(&ctx->q.sendbuf); + + result = Curl_pollset_set(data, ps, ctx->q.sockfd, want_recv, want_send); + } + return result; +} + +static CURLcode h3_data_pause(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool pause) +{ + /* There seems to exist no API in quiche to shrink/enlarge the streams + * windows. As we do in HTTP/2. */ + (void)cf; + if(!pause) { + Curl_multi_mark_dirty(data); + } + return CURLE_OK; +} + +static CURLcode cf_quiche_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + (void)arg1; + (void)arg2; + switch(event) { + case CF_CTRL_DATA_SETUP: + break; + case CF_CTRL_DATA_PAUSE: + result = h3_data_pause(cf, data, (arg1 != 0)); + break; + case CF_CTRL_DATA_DONE: + h3_data_done(cf, data); + break; + case CF_CTRL_DATA_DONE_SEND: { + struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data); + if(stream && !stream->send_closed) { + unsigned char body[1]; + size_t sent; + + stream->send_closed = TRUE; + body[0] = 'X'; + result = cf_quiche_send(cf, data, body, 0, TRUE, &sent); + CURL_TRC_CF(data, cf, "[%" PRIu64 "] DONE_SEND -> %d, %zu", + stream->id, (int)result, sent); + } + break; + } + case CF_CTRL_CONN_INFO_UPDATE: + if(!cf->sockindex && cf->connected) { + cf->conn->httpversion_seen = 30; + Curl_conn_set_multiplex(cf->conn); + } + break; + case CF_CTRL_REPORT_STATS: + if(cf->connected && !ctx->stats_reported && + (ctx->handshake_at.tv_sec || ctx->handshake_at.tv_usec)) { + Curl_pgrsTimeWas(data, TIMER_CONNECT, ctx->q.first_byte_at); + Curl_pgrsTimeWas(data, TIMER_APPCONNECT, ctx->handshake_at); + ctx->stats_reported = TRUE; + } + break; + default: + break; + } + return result; +} + +static CURLcode cf_quiche_ctx_open(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + int rv; + CURLcode result; + const struct Curl_sockaddr_ex *sockaddr; + static const struct alpn_spec ALPN_SPEC_H3 = { { "h3" }, 1 }; + + DEBUGASSERT(ctx->q.sockfd != CURL_SOCKET_BAD); + DEBUGASSERT(ctx->initialized); + + result = Curl_vquic_ctx_init(data, &ctx->q); + if(result) + return result; + + ctx->cfg = quiche_config_new(QUICHE_PROTOCOL_VERSION); + if(!ctx->cfg) { + failf(data, "cannot create quiche config"); + return CURLE_FAILED_INIT; + } + quiche_config_enable_pacing(ctx->cfg, FALSE); + quiche_config_set_initial_max_data(ctx->cfg, (1 * 1024 * 1024) + /* (QUIC_MAX_STREAMS/2) * H3_STREAM_WINDOW_SIZE */); + quiche_config_set_initial_max_streams_bidi(ctx->cfg, QUIC_MAX_STREAMS); + quiche_config_set_initial_max_streams_uni(ctx->cfg, QUIC_MAX_STREAMS); + quiche_config_set_initial_max_stream_data_bidi_local(ctx->cfg, + H3_STREAM_WINDOW_SIZE); + quiche_config_set_initial_max_stream_data_bidi_remote(ctx->cfg, + H3_STREAM_WINDOW_SIZE); + quiche_config_set_initial_max_stream_data_uni(ctx->cfg, + H3_STREAM_WINDOW_SIZE); + quiche_config_set_disable_active_migration(ctx->cfg, TRUE); + + quiche_config_set_max_connection_window(ctx->cfg, + 10 * QUIC_MAX_STREAMS * H3_STREAM_WINDOW_SIZE); + quiche_config_set_max_stream_window(ctx->cfg, 10 * H3_STREAM_WINDOW_SIZE); + quiche_config_set_application_protos(ctx->cfg, + (uint8_t *)CURL_UNCONST(QUICHE_H3_APPLICATION_PROTOCOL), + CURL_CSTRLEN(QUICHE_H3_APPLICATION_PROTOCOL)); + + result = Curl_vquic_tls_init(&ctx->tls, cf, data, &ctx->ssl_peer, + &ALPN_SPEC_H3, NULL, NULL, cf, NULL); + if(result) + return result; + + result = Curl_rand(data, ctx->scid, sizeof(ctx->scid)); + if(result) + return result; + + if(Curl_cf_socket_peek(cf->next, data, &ctx->q.sockfd, &sockaddr, NULL)) + return CURLE_QUIC_CONNECT_ERROR; + + ctx->q.local_addrlen = sizeof(ctx->q.local_addr); + rv = getsockname(ctx->q.sockfd, (struct sockaddr *)&ctx->q.local_addr, + &ctx->q.local_addrlen); + if(rv == -1) + return CURLE_QUIC_CONNECT_ERROR; + + ctx->qconn = quiche_conn_new_with_tls((const uint8_t *)ctx->scid, + sizeof(ctx->scid), NULL, 0, + (struct sockaddr *)&ctx->q.local_addr, + ctx->q.local_addrlen, + &sockaddr->curl_sa_addr, + sockaddr->addrlen, + ctx->cfg, ctx->tls.ossl.ssl, FALSE); + if(!ctx->qconn) { + failf(data, "cannot create quiche connection"); + return CURLE_OUT_OF_MEMORY; + } + + /* Known to not work on Windows */ +#if !defined(_WIN32) && defined(HAVE_QUICHE_CONN_SET_QLOG_FD) + { + int qfd; + (void)Curl_qlogdir(data, ctx->scid, sizeof(ctx->scid), &qfd); + if(qfd != -1) + quiche_conn_set_qlog_fd(ctx->qconn, qfd, "qlog title", "curl qlog"); + } +#endif + + result = cf_flush_egress(cf, data); + if(result) + return result; + + { + unsigned char alpn_protocols[] = QUICHE_H3_APPLICATION_PROTOCOL; + unsigned alpn_len, offset = 0; + + /* Replace each ALPN length prefix by a comma. */ + while(offset < CURL_CSTRLEN(alpn_protocols)) { + alpn_len = alpn_protocols[offset]; + alpn_protocols[offset] = ','; + offset += 1 + alpn_len; + } + + CURL_TRC_CF(data, cf, "Sent QUIC client Initial, ALPN: %s", + alpn_protocols + 1); + } + + return CURLE_OK; +} + +static CURLcode cf_quiche_verify_peer(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + return Curl_vquic_tls_verify_peer(&ctx->tls, cf, data, &ctx->ssl_peer); +} + +static CURLcode cf_quiche_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + /* Connect the UDP filter first */ + if(!cf->next->connected) { + result = Curl_conn_cf_connect(cf->next, data, done); + if(result || !*done) + return result; + } + + *done = FALSE; + if(Curl_ossl_need_httpsrr(data) && + !Curl_conn_dns_resolved_https(data, cf->sockindex, ctx->ssl_peer.peer)) { + CURL_TRC_CF(data, cf, "need HTTPS-RR, delaying connect"); + return CURLE_OK; + } + + Curl_vquic_ctx_update_time(&ctx->q, Curl_pgrs_now(data)); + + if(!ctx->qconn) { + result = cf_quiche_ctx_open(cf, data); + if(result) + goto out; + ctx->started_at = ctx->q.last_op; + result = cf_flush_egress(cf, data); + /* we do not expect to be able to recv anything yet */ + goto out; + } + + result = cf_process_ingress(cf, data); + if(result) + goto out; + + result = cf_flush_egress(cf, data); + if(result) + goto out; + + if(quiche_conn_is_established(ctx->qconn)) { + ctx->handshake_at = ctx->q.last_op; + CURL_TRC_CF(data, cf, "handshake complete after %" FMT_TIMEDIFF_T "ms", + curlx_ptimediff_ms(&ctx->handshake_at, &ctx->started_at)); + result = cf_quiche_verify_peer(cf, data); + if(!result) { + CURL_TRC_CF(data, cf, "peer verified"); + ctx->h3config = quiche_h3_config_new(); + if(!ctx->h3config) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + /* quiche 0.29.3+ rejects response headers larger than 32 KiB by + default. Allow as much as curl itself accepts. */ + quiche_h3_config_set_max_field_section_size(ctx->h3config, + MAX_HTTP_RESP_HEADER_SIZE); + + /* Create a new HTTP/3 connection on the QUIC connection. */ + ctx->h3c = quiche_h3_conn_new_with_transport(ctx->qconn, ctx->h3config); + if(!ctx->h3c) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + cf->connected = TRUE; + *done = TRUE; + } + } + else if(quiche_conn_is_draining(ctx->qconn)) { + /* When a QUIC server instance is shutting down, it may send us a + * CONNECTION_CLOSE right away. Our connection then enters the DRAINING + * state. The CONNECT may work in the near future again. Indicate + * that as a "weird" reply. */ + result = CURLE_WEIRD_SERVER_REPLY; + } + +out: +#ifdef CURLVERBOSE + if(result && result != CURLE_AGAIN) { + struct ip_quadruple ip; + + if(!Curl_cf_socket_peek(cf->next, data, NULL, NULL, &ip)) + infof(data, "connect to %s port %u failed: %s", + ip.remote_ip, ip.remote_port, curl_easy_strerror(result)); + else + infof(data, "connect failed: %s", curl_easy_strerror(result)); + } +#endif + return result; +} + +static CURLcode cf_quiche_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(cf->shutdown || !ctx || !ctx->qconn) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; + if(!ctx->shutdown_started) { + int err; + + ctx->shutdown_started = TRUE; + Curl_vquic_ctx_update_time(&ctx->q, Curl_pgrs_now(data)); + err = quiche_conn_close(ctx->qconn, TRUE, 0, NULL, 0); + if(err) { + CURL_TRC_CF(data, cf, "error %d adding shutdown packet, " + "aborting shutdown", err); + result = CURLE_SEND_ERROR; + goto out; + } + } + + if(!Curl_bufq_is_empty(&ctx->q.sendbuf)) { + CURL_TRC_CF(data, cf, "shutdown, flushing sendbuf"); + result = cf_flush_egress(cf, data); + if(result) + goto out; + } + + if(Curl_bufq_is_empty(&ctx->q.sendbuf)) { + /* sent everything, quiche does not seem to support a graceful shutdown + * waiting for a reply, so we are done. */ + CURL_TRC_CF(data, cf, "shutdown completely sent off, done"); + *done = TRUE; + } + else { + CURL_TRC_CF(data, cf, "shutdown sending blocked"); + } + +out: + return result; +} + +static void cf_quiche_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + (void)data; + if(cf->ctx) { + cf_quiche_ctx_close(cf->ctx); + cf_quiche_ctx_free(cf->ctx); + cf->ctx = NULL; + } +} + +static CURLcode cf_quiche_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + + switch(query) { + case CF_QUERY_MAX_CONCURRENT: { + uint64_t max_streams = cf->conn->attached_xfers; + if(!ctx->goaway && ctx->qconn) { + max_streams += quiche_conn_peer_streams_left_bidi(ctx->qconn); + } + *pres1 = (max_streams > INT_MAX) ? INT_MAX : (int)max_streams; + CURL_TRC_CF(data, cf, "query conn[%" FMT_OFF_T "]: " + "MAX_CONCURRENT -> %d (%u in use)", + cf->conn->connection_id, *pres1, cf->conn->attached_xfers); + return CURLE_OK; + } + case CF_QUERY_CONNECT_REPLY_MS: + if(ctx->q.got_first_byte) { + timediff_t ms = curlx_ptimediff_ms(&ctx->q.first_byte_at, + &ctx->started_at); + *pres1 = (ms < INT_MAX) ? (int)ms : INT_MAX; + } + else + *pres1 = -1; + return CURLE_OK; + case CF_QUERY_HTTP_VERSION: + *pres1 = 30; + return CURLE_OK; + case CF_QUERY_SSL_INFO: + case CF_QUERY_SSL_CTX_INFO: { + struct curl_tlssessioninfo *info = pres2; + if(Curl_vquic_tls_get_ssl_info(&ctx->tls, + (query == CF_QUERY_SSL_CTX_INFO), info)) + return CURLE_OK; + break; + } + case CF_QUERY_ALPN_NEGOTIATED: { + const char **palpn = pres2; + DEBUGASSERT(palpn); + *palpn = cf->connected ? "h3" : NULL; + return CURLE_OK; + } + default: + break; + } + return cf->next ? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +static bool cf_quiche_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + bool alive = TRUE; + + *input_pending = FALSE; + if(!ctx->qconn) + return FALSE; + + if(quiche_conn_is_closed(ctx->qconn)) { + if(quiche_conn_is_timed_out(ctx->qconn)) + CURL_TRC_CF(data, cf, "connection was closed due to idle timeout"); + else + CURL_TRC_CF(data, cf, "connection is closed"); + return FALSE; + } + + if(!cf->next || !cf->next->cft->is_alive(cf->next, data, input_pending)) + return FALSE; + + if(*input_pending) { + /* This happens before we have sent off a request and the connection is + not in use by any other transfer, there should not be any data here, + only "protocol frames" */ + *input_pending = FALSE; + if(cf_process_ingress(cf, data)) + alive = FALSE; + else { + alive = TRUE; + } + } + + return alive; +} + +struct Curl_cftype Curl_cft_http3 = { + "HTTP/3", + CF_TYPE_IP_CONNECT | CF_TYPE_SSL | CF_TYPE_MULTIPLEX | CF_TYPE_HTTP, + 0, + cf_quiche_destroy, + cf_quiche_connect, + cf_quiche_shutdown, + cf_quiche_adjust_pollset, + Curl_cf_def_data_pending, + cf_quiche_send, + cf_quiche_recv, + cf_quiche_cntrl, + cf_quiche_conn_is_alive, + Curl_cf_def_conn_keep_alive, + cf_quiche_query, +}; + +CURLcode Curl_cf_quiche_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr) +{ + struct cf_quiche_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL; + CURLcode result; + + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + result = cf_quiche_ctx_init(ctx, origin, peer, &conn->ssl_config); + if(!result) + result = Curl_cf_create(&cf, &Curl_cft_http3, ctx); + if(result) + goto out; + cf->conn = conn; + + result = Curl_cf_udp_create(&cf->next, data, origin, peer, TRNSPRT_QUIC, + conn, addr, NULL, TRNSPRT_QUIC); + if(result) + goto out; + cf->next->conn = cf->conn; + cf->next->sockindex = cf->sockindex; + +out: + *pcf = (!result) ? cf : NULL; + if(result) { + if(cf) + Curl_conn_cf_discard_chain(&cf, data); + else if(ctx) + cf_quiche_ctx_free(ctx); + } + + return result; +} + +CURLcode Curl_cf_quiche_insert_after(struct Curl_cfilter *cf_at, + struct Curl_peer *origin, + struct Curl_peer *peer) +{ + struct cf_quiche_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL; + CURLcode result; + + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + result = cf_quiche_ctx_init(ctx, origin, peer, &cf_at->conn->ssl_config); + if(!result) + result = Curl_cf_create(&cf, &Curl_cft_http3, ctx); + if(result) + goto out; + Curl_conn_cf_insert_after(cf_at, cf); + +out: + if(result) { + curlx_safefree(cf); + if(ctx) + cf_quiche_ctx_free(ctx); + } + + return result; +} + +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-quiche.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-quiche.h new file mode 100644 index 0000000000..88d9161dd7 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/cf-quiche.h @@ -0,0 +1,50 @@ +#ifndef HEADER_CURL_VQUIC_CF_QUICHE_H +#define HEADER_CURL_VQUIC_CF_QUICHE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_QUICHE) + +#include <quiche.h> +#include <openssl/ssl.h> + +struct Curl_cfilter; +struct Curl_easy; + +void Curl_quiche_ver(char *p, size_t len); + +CURLcode Curl_cf_quiche_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr); +CURLcode Curl_cf_quiche_insert_after(struct Curl_cfilter *cf_at, + struct Curl_peer *origin, + struct Curl_peer *peer); + +#endif + +#endif /* HEADER_CURL_VQUIC_CF_QUICHE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic-tls.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic-tls.c new file mode 100644 index 0000000000..75e2f4e1e2 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic-tls.c @@ -0,0 +1,241 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_HTTP3) && \ + (defined(USE_OPENSSL) || defined(USE_GNUTLS) || defined(USE_WOLFSSL)) + +#ifdef USE_OPENSSL +#include <openssl/err.h> +#include "vtls/openssl.h" +#elif defined(USE_GNUTLS) +#include <gnutls/abstract.h> +#include <gnutls/gnutls.h> +#include <gnutls/x509.h> +#include <gnutls/crypto.h> +#include <nettle/sha2.h> +#include "vtls/gtls.h" +#elif defined(USE_WOLFSSL) +#include <wolfssl/options.h> +#include <wolfssl/ssl.h> +#include <wolfssl/quic.h> +#include "vtls/wolfssl.h" +#endif + +#include "urldata.h" +#include "cfilters.h" +#include "vtls/vtls.h" +#include "vtls/vtls_scache.h" +#include "vquic/vquic-tls.h" + +CURLcode Curl_vquic_tls_peer_init(struct Curl_peer *origin, + struct Curl_peer *peer, + struct ssl_primary_config *sslc, + struct ssl_peer *ssl_peer) +{ + char tls_id[80]; + +#ifdef USE_OPENSSL + Curl_ossl_version(tls_id, sizeof(tls_id)); +#elif defined(USE_GNUTLS) + Curl_gtls_version(tls_id, sizeof(tls_id)); +#elif defined(USE_WOLFSSL) + Curl_wssl_version(tls_id, sizeof(tls_id)); +#else +#error "no TLS lib in used, should not happen" + return CURLE_FAILED_INIT; +#endif + if(ssl_peer->origin || ssl_peer->peer) + Curl_ssl_peer_cleanup(ssl_peer); + return Curl_ssl_peer_init(ssl_peer, origin, peer, sslc, + tls_id, TRNSPRT_QUIC); +} + +CURLcode Curl_vquic_tls_init(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *ssl_peer, + const struct alpn_spec *alpns, + Curl_vquic_tls_ctx_setup *cb_setup, + void *cb_user_data, void *ssl_user_data, + Curl_vquic_session_reuse_cb *session_reuse_cb) +{ +#ifdef USE_OPENSSL + return Curl_ossl_ctx_init(&ctx->ossl, cf, data, ssl_peer, alpns, + cb_setup, cb_user_data, NULL, ssl_user_data, + session_reuse_cb); +#elif defined(USE_GNUTLS) + return Curl_gtls_ctx_init(&ctx->gtls, cf, data, ssl_peer, alpns, + cb_setup, cb_user_data, ssl_user_data, + session_reuse_cb); +#elif defined(USE_WOLFSSL) + return Curl_wssl_ctx_init(&ctx->wssl, cf, data, ssl_peer, alpns, + cb_setup, cb_user_data, + ssl_user_data, session_reuse_cb); +#else +#error "no TLS lib in used, should not happen" + return CURLE_FAILED_INIT; +#endif +} + +void Curl_vquic_tls_cleanup(struct curl_tls_ctx *ctx) +{ +#ifdef USE_OPENSSL + if(ctx->ossl.ssl) + SSL_free(ctx->ossl.ssl); + if(ctx->ossl.ssl_ctx) + SSL_CTX_free(ctx->ossl.ssl_ctx); +#elif defined(USE_GNUTLS) + if(ctx->gtls.session) + gnutls_deinit(ctx->gtls.session); + Curl_gtls_shared_creds_free(&ctx->gtls.shared_creds); +#elif defined(USE_WOLFSSL) + if(ctx->wssl.ssl) + wolfSSL_free(ctx->wssl.ssl); + if(ctx->wssl.ssl_ctx) + wolfSSL_CTX_free(ctx->wssl.ssl_ctx); +#endif + memset(ctx, 0, sizeof(*ctx)); +} + +CURLcode Curl_vquic_tls_before_recv(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ +#ifdef USE_OPENSSL + if(!ctx->ossl.x509_store_setup) { + CURLcode result = Curl_ssl_setup_x509_store(cf, data, &ctx->ossl); + if(result) + return result; + ctx->ossl.x509_store_setup = TRUE; + } +#elif defined(USE_WOLFSSL) + if(!ctx->wssl.x509_store_setup) { + CURLcode result = Curl_wssl_setup_x509_store(cf, data, &ctx->wssl); + if(result) + return result; + } +#elif defined(USE_GNUTLS) + if(!ctx->gtls.shared_creds->trust_setup) { + CURLcode result = Curl_gtls_client_trust_setup(cf, data, &ctx->gtls); + if(result) + return result; + } +#else + (void)ctx; + (void)cf; + (void)data; +#endif + return CURLE_OK; +} + +CURLcode Curl_vquic_tls_verify_peer(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer) +{ + struct ssl_primary_config *conn_config; + CURLcode result = CURLE_OK; + + conn_config = Curl_ssl_cf_get_primary_config(cf); + if(!conn_config) + return CURLE_FAILED_INIT; + +#ifdef USE_OPENSSL + (void)conn_config; + result = Curl_ossl_check_peer_cert(cf, data, &ctx->ossl, peer); +#elif defined(USE_GNUTLS) + result = Curl_gtls_verifyserver( + cf, data, ctx->gtls.session, conn_config, &data->set.ssl, peer, + CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY)); + if(result) + return result; +#elif defined(USE_WOLFSSL) + (void)data; + if(conn_config->verifyhost) { + WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(ctx->wssl.ssl); + if(!cert) + result = CURLE_OUT_OF_MEMORY; + else if(peer->sni && + (wolfSSL_X509_check_host(cert, peer->sni, strlen(peer->sni), 0, + NULL) == WOLFSSL_FAILURE)) + result = CURLE_PEER_FAILED_VERIFICATION; + else if(!peer->sni && + (wolfSSL_X509_check_ip_asc(cert, peer->origin->hostname, + 0) == WOLFSSL_FAILURE)) + result = CURLE_PEER_FAILED_VERIFICATION; + wolfSSL_X509_free(cert); + } + if(!result) + result = Curl_wssl_verify_pinned(cf, data, &ctx->wssl); +#endif + /* on error, remove any session we might have in the pool */ + if(result) + Curl_ssl_scache_remove_all(cf, data, peer->scache_key); + return result; +} + +bool Curl_vquic_tls_get_ssl_info(struct curl_tls_ctx *ctx, + bool give_ssl_ctx, + struct curl_tlssessioninfo *info) +{ +#ifdef USE_OPENSSL + info->backend = CURLSSLBACKEND_OPENSSL; + info->internals = give_ssl_ctx ? + (void *)ctx->ossl.ssl_ctx : (void *)ctx->ossl.ssl; + return TRUE; +#elif defined(USE_GNUTLS) + (void)give_ssl_ctx; /* gnutls always returns its session */ + info->backend = CURLSSLBACKEND_GNUTLS; + info->internals = ctx->gtls.session; + return TRUE; +#elif defined(USE_WOLFSSL) + info->backend = CURLSSLBACKEND_WOLFSSL; + info->internals = give_ssl_ctx ? + (void *)ctx->wssl.ssl_ctx : (void *)ctx->wssl.ssl; + return TRUE; +#else + return FALSE; +#endif +} + +void Curl_vquic_report_handshake(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + (void)cf; +#ifdef USE_OPENSSL + (void)cf; + Curl_ossl_report_handshake(data, &ctx->ossl); +#elif defined(USE_GNUTLS) + Curl_gtls_report_handshake(data, &ctx->gtls); +#elif defined(USE_WOLFSSL) + Curl_wssl_report_handshake(data, &ctx->wssl); +#else + (void)data; + (void)ctx; +#endif +} + +#endif /* !USE_HTTP3 && (USE_OPENSSL || USE_GNUTLS || USE_WOLFSSL) */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic-tls.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic-tls.h new file mode 100644 index 0000000000..e8d2418b06 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic-tls.h @@ -0,0 +1,125 @@ +#ifndef HEADER_CURL_VQUIC_TLS_H +#define HEADER_CURL_VQUIC_TLS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_HTTP3) && \ + (defined(USE_OPENSSL) || defined(USE_GNUTLS) || defined(USE_WOLFSSL)) + +#include "bufq.h" +#include "vtls/vtls.h" +#include "vtls/vtls_int.h" + +#include "vtls/openssl.h" +#include "vtls/wolfssl.h" + +struct ssl_peer; +struct Curl_ssl_session; +struct curl_tlssessioninfo; + +struct curl_tls_ctx { +#ifdef USE_OPENSSL + struct ossl_ctx ossl; +#elif defined(USE_GNUTLS) + struct gtls_ctx gtls; +#elif defined(USE_WOLFSSL) + struct wssl_ctx wssl; +#endif +}; + +/** + * Callback passed to `Curl_vquic_tls_init()` that can + * do early initializations on the not otherwise configured TLS + * instances created. This varies by TLS backend: + * - openssl/wolfssl: SSL_CTX* has been created + * - gnutls: gtls_client_init() has run + */ +typedef CURLcode Curl_vquic_tls_ctx_setup(struct Curl_cfilter *cf, + struct Curl_easy *data, + void *cb_user_data); + +typedef CURLcode Curl_vquic_session_reuse_cb(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct alpn_spec *alpns, + struct Curl_ssl_session *scs, + bool *do_early_data); + +CURLcode Curl_vquic_tls_peer_init(struct Curl_peer *origin, + struct Curl_peer *peer, + struct ssl_primary_config *sslc, + struct ssl_peer *ssl_peer); + +/** + * Initialize the QUIC TLS instances based of the SSL configurations + * for the connection filter, transfer and peer. + * @param ctx the TLS context to initialize + * @param cf the connection filter involved + * @param data the transfer involved + * @param ssl_peer the SSL peer to be connected to + * @param alpns the ALPN specifications to negotiate, may be NULL + * @param cb_setup optional callback for early TLS config + * @param cb_user_data user_data param for callback + * @param ssl_user_data optional pointer to set in TLS application context + * @param session_reuse_cb callback to handle session reuse, signal early data + */ +CURLcode Curl_vquic_tls_init(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *ssl_peer, + const struct alpn_spec *alpns, + Curl_vquic_tls_ctx_setup *cb_setup, + void *cb_user_data, + void *ssl_user_data, + Curl_vquic_session_reuse_cb *session_reuse_cb); + +/** + * Cleanup all data that has been initialized. + */ +void Curl_vquic_tls_cleanup(struct curl_tls_ctx *ctx); + +CURLcode Curl_vquic_tls_before_recv(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data); + +/** + * After the QUIC basic handshake has been, verify that the peer + * (and its certificate) fulfill our requirements. + */ +CURLcode Curl_vquic_tls_verify_peer(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer); + +bool Curl_vquic_tls_get_ssl_info(struct curl_tls_ctx *ctx, + bool give_ssl_ctx, + struct curl_tlssessioninfo *info); + +void Curl_vquic_report_handshake(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data); + +#endif /* !USE_HTTP3 && (USE_OPENSSL || USE_GNUTLS || USE_WOLFSSL) */ + +#endif /* HEADER_CURL_VQUIC_TLS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic.c new file mode 100644 index 0000000000..bbc5777eac --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic.c @@ -0,0 +1,1334 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" +#include "vquic/vquic.h" +#include "vtls/vtls.h" + +#include "curl_trc.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_HTTP3) + +#ifdef HAVE_NETINET_UDP_H +#include <netinet/udp.h> +#endif +#ifdef HAVE_NETINET_IP_H +#include <netinet/ip.h> +#endif + +#ifdef USE_NGHTTP3 +#include <nghttp3/nghttp3.h> +#endif + +#if defined(USE_APPLE_FAST_UDP) && defined(__APPLE__) +#include <sys/syscall.h> +#if defined(SYS_recvmsg_x) && defined(SYS_sendmsg_x) +#define HAVE_APPLE_MSG_X +#endif +#endif + +#include "bufq.h" +#include "curlx/dynbuf.h" +#include "curlx/fopen.h" +#include "cfilters.h" +#include "vdns/cf-dns.h" +#include "vquic/cf-ngtcp2.h" +#include "vquic/cf-ngtcp2-cmn.h" +#include "vquic/cf-ngtcp2-proxy.h" +#include "vquic/cf-quiche.h" +#include "multiif.h" +#include "progress.h" +#include "rand.h" +#include "vquic/vquic_int.h" +#include "curlx/strerr.h" +#include "curlx/strparse.h" + + +#define NW_CHUNK_SIZE (64 * 1024) +#define NW_SEND_CHUNKS 1 + +#ifdef HAVE_APPLE_MSG_X + +/* this is `struct msghdr` with an additional field at the end */ +struct msghdr_x { + void *msg_name; /* optional address */ + socklen_t msg_namelen; /* size of address */ + struct iovec *msg_iov; /* scatter/gather array */ + int msg_iovlen; /* # elements in msg_iov */ + void *msg_control; /* ancillary data, see below */ + socklen_t msg_controllen; /* ancillary data buffer len */ + int msg_flags; /* flags on received message */ + size_t msg_datalen; /* byte length of buffer in msg_iov */ +}; +#endif + +#ifdef CURLVERBOSE +#ifdef HAVE_APPLE_MSG_X +#define VQUIC_SEND_METHOD "sendmsg_x" +#elif defined(HAVE_SENDMSG) +#define VQUIC_SEND_METHOD "sendmsg" +#else +#define VQUIC_SEND_METHOD "send" +#endif +#endif + +int Curl_vquic_init(void) +{ +#if defined(USE_NGTCP2) && defined(OPENSSL_QUIC_API2) + if(ngtcp2_crypto_ossl_init()) + return 0; +#endif + + return 1; +} + +void Curl_vquic_cleanup(void) +{ +#if defined(USE_NGTCP2) && defined(OPENSSL_QUIC_API2) && \ + (NGTCP2_VERSION_NUM >= 0x011800) + ngtcp2_crypto_ossl_free(); +#endif +} + +void Curl_quic_ver(char *p, size_t len) +{ +#if defined(USE_NGTCP2) && defined(USE_NGHTTP3) + Curl_ngtcp2_ver(p, len); +#elif defined(USE_QUICHE) + Curl_quiche_ver(p, len); +#endif +} + +CURLcode Curl_vquic_ctx_init(struct Curl_easy *data, + struct cf_quic_ctx *qctx) +{ + Curl_bufq_init2(&qctx->sendbuf, NW_CHUNK_SIZE, NW_SEND_CHUNKS, + BUFQ_OPT_SOFT_LIMIT); +#if defined(__linux__) && defined(UDP_SEGMENT) && defined(HAVE_SENDMSG) + qctx->no_gso = FALSE; +#elif defined(HAVE_APPLE_MSG_X) + qctx->no_gso = FALSE; +#else + qctx->no_gso = TRUE; +#endif +#ifdef DEBUGBUILD + { + const char *p = getenv("CURL_DBG_QUIC_WBLOCK"); + if(p) { + curl_off_t l; + if(!curlx_str_number(&p, &l, 100)) + qctx->wblock_percent = (int)l; + } + } +#endif + Curl_vquic_ctx_set_time(qctx, Curl_pgrs_now(data)); + + return CURLE_OK; +} + +void Curl_vquic_ctx_free(struct cf_quic_ctx *qctx) +{ + Curl_bufq_free(&qctx->sendbuf); +} + +void Curl_vquic_ctx_set_time(struct cf_quic_ctx *qctx, + const struct curltime *pnow) +{ + qctx->last_op = *pnow; +} + +void Curl_vquic_ctx_update_time(struct cf_quic_ctx *qctx, + const struct curltime *pnow) +{ + qctx->last_op = *pnow; +} + +#ifdef HAVE_APPLE_MSG_X +static CURLcode do_sendmsg(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + const uint8_t *pkt, size_t pktlen, size_t gsolen, + size_t *psent) +{ +#define MSG_X_SNUM 64 + struct iovec msg_iov[MSG_X_SNUM]; + struct msghdr_x mmsg[MSG_X_SNUM]; + char errstr[STRERROR_LEN]; + size_t n, i = 0, sent = 0; + int rc; + CURLcode result = CURLE_OK; + VERBOSE(size_t calls = 0); + + *psent = 0; + if(!pktlen) + return CURLE_OK; + if(!gsolen || (pktlen < gsolen)) + gsolen = pktlen; + n = (pktlen + gsolen - 1) / gsolen; + while(i < n) { + size_t j, batch = CURLMIN(n - i, MSG_X_SNUM), pkts_sent = 0; + + for(j = 0; j < batch; ++j) { + const size_t offset = (i + j) * gsolen; + msg_iov[j].iov_base = CURL_UNCONST(pkt + offset); + msg_iov[j].iov_len = CURLMIN(gsolen, pktlen - offset); + memset(&mmsg[j], 0, sizeof(mmsg[j])); + mmsg[j].msg_iov = &msg_iov[j]; + mmsg[j].msg_iovlen = 1; + mmsg[j].msg_datalen = msg_iov[j].iov_len; + } + +#if defined(CURL_HAVE_DIAG) && defined(__APPLE__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + while((rc = syscall(SYS_sendmsg_x, qctx->sockfd, &mmsg, batch, 0)) == -1 && + (SOCKERRNO == SOCKEINTR)) + ; +#if defined(CURL_HAVE_DIAG) && defined(__APPLE__) +#pragma GCC diagnostic pop +#endif + + if(rc < 0) { + if(SOCK_EAGAIN(SOCKERRNO)) { + CURL_TRC_CF(data, cf, "egress, sendmsg_x -> EAGAIN"); + result = sent ? CURLE_OK : CURLE_AGAIN; + goto out; + } + if(SOCKERRNO != SOCKEMSGSIZE) { + curlx_strerror(SOCKERRNO, errstr, sizeof(errstr)); + failf(data, "QUIC: sendmsg_x() returned %d (errno=%d; %s)", + rc, SOCKERRNO, errstr); + result = CURLE_SEND_ERROR; + goto out; + } + /* Error was SOCKEMSGSIZE. Network stack does not accept the packet + * length(s). This might be a PMTUD. Just drop it into the void + * and fall through to the success handling. */ + pkts_sent = batch; + } + else + pkts_sent = CURLMIN((size_t)rc, batch); + + VERBOSE(++calls); + if(!pkts_sent) { /* no packets of the current batch were sent */ + result = sent ? CURLE_OK : CURLE_AGAIN; + goto out; + } + i += pkts_sent; /* Some have been sent */ + for(j = 0; j < pkts_sent; ++j) + sent += msg_iov[j].iov_len; + if(pkts_sent < batch) + goto out; /* but not all of them */ + } + +out: + *psent = sent; + if(sent || result) + CURL_TRC_CF(data, cf, + "vquic_sendmsg_x(len=%zu, gso=%zu, packets=%zu, " + "calls=%zu) -> %d", + sent, gsolen, n, calls, (int)result); + return result; +} + +#else /* HAVE_APPLE_MSG_X */ + +static CURLcode send_packet_no_gso(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + const uint8_t *pkt, size_t pktlen, + size_t gsolen, size_t *psent); + +static CURLcode do_sendmsg(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + const uint8_t *pkt, size_t pktlen, size_t gsolen, + size_t *psent) +{ + CURLcode result = CURLE_OK; +#ifdef HAVE_SENDMSG + struct iovec msg_iov; + struct msghdr msg = { 0 }; + ssize_t rv; +#if defined(__linux__) && defined(UDP_SEGMENT) + uint8_t msg_ctrl[32]; + struct cmsghdr *cm; +#endif + + *psent = 0; + msg_iov.iov_base = (uint8_t *)CURL_UNCONST(pkt); + msg_iov.iov_len = pktlen; + msg.msg_iov = &msg_iov; + msg.msg_iovlen = 1; + +#if defined(__linux__) && defined(UDP_SEGMENT) + if(pktlen > gsolen) { + /* Only set this, when we need it. macOS, for example, + * does not seem to like a msg_control of length 0. */ + memset(msg_ctrl, 0, sizeof(msg_ctrl)); + msg.msg_control = msg_ctrl; + DEBUGASSERT(sizeof(msg_ctrl) >= CMSG_SPACE(sizeof(int))); + msg.msg_controllen = CMSG_SPACE(sizeof(int)); + cm = CMSG_FIRSTHDR(&msg); + cm->cmsg_level = SOL_UDP; + cm->cmsg_type = UDP_SEGMENT; + cm->cmsg_len = CMSG_LEN(sizeof(uint16_t)); + *(uint16_t *)(void *)CMSG_DATA(cm) = gsolen & 0xffff; + } +#endif + + while((rv = sendmsg(qctx->sockfd, &msg, 0)) == -1 && SOCKERRNO == SOCKEINTR) + ; + + if(!curlx_sztouz(rv, psent)) { + int sockerr = SOCKERRNO; + if(SOCK_EAGAIN(sockerr)) + return CURLE_AGAIN; + switch(sockerr) { + case SOCKEMSGSIZE: + /* UDP datagram is too large; caused by PMTUD. Let it be lost. */ + *psent = pktlen; + break; + case EIO: + if(pktlen > gsolen) { + /* GSO failure */ + infof(data, "sendmsg() returned %zd (errno %d); disable GSO", rv, + sockerr); + qctx->no_gso = TRUE; + return send_packet_no_gso(cf, data, qctx, pkt, pktlen, gsolen, psent); + } + FALLTHROUGH(); + default: + failf(data, "sendmsg() returned %zd (errno %d)", rv, sockerr); + result = CURLE_SEND_ERROR; + goto out; + } + } + else if(pktlen != *psent) { + failf(data, "sendmsg() sent only %zu/%zu bytes", *psent, pktlen); + result = CURLE_SEND_ERROR; + goto out; + } +#else + ssize_t rv; + (void)gsolen; + + *psent = 0; + + while((rv = swrite(qctx->sockfd, pkt, pktlen)) == -1 && + SOCKERRNO == SOCKEINTR) + ; + + if(!curlx_sztouz(rv, psent)) { + if(SOCK_EAGAIN(SOCKERRNO)) { + result = CURLE_AGAIN; + goto out; + } + else { + if(SOCKERRNO != SOCKEMSGSIZE) { + failf(data, "send() returned %zd (errno %d)", rv, SOCKERRNO); + result = CURLE_SEND_ERROR; + goto out; + } + /* UDP datagram is too large; caused by PMTUD. Let it be lost. */ + *psent = pktlen; + } + } +#endif + (void)cf; + +out: + CURL_TRC_CF(data, cf, + "vquic_%s(len=%zu, gso=%zu, calls=1) -> %d, sent=%zu", + VQUIC_SEND_METHOD, pktlen, gsolen, (int)result, *psent); + return result; +} + +#endif /* !HAVE_APPLE_MSG_X */ + +static CURLcode send_packet_no_gso(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + const uint8_t *pkt, size_t pktlen, + size_t gsolen, size_t *psent) +{ + const uint8_t *p, *end = pkt + pktlen; + size_t sent, len; + CURLcode result = CURLE_OK; + VERBOSE(size_t calls = 0); + + *psent = 0; + + for(p = pkt; p < end; p += gsolen) { + len = CURLMIN(gsolen, (size_t)(end - p)); + result = do_sendmsg(cf, data, qctx, p, len, len, &sent); + if(result) + goto out; + *psent += sent; + VERBOSE(++calls); + } +out: + CURL_TRC_CF(data, cf, + "vquic_%s(len=%zu, gso=%zu, calls=%zu) -> %d, sent=%zu", + VQUIC_SEND_METHOD, pktlen, gsolen, calls, (int)result, *psent); + return result; +} + +/* Split QUIC payload by datagram (gso) boundaries when sending over a + * non-UDP lower filter (for example CONNECT-UDP proxy tunnel). */ +static CURLcode send_packet_no_gso_cf(struct Curl_cfilter *cf, + struct Curl_easy *data, + const uint8_t *pkt, size_t pktlen, + size_t gsolen, size_t *psent) +{ + const uint8_t *p, *end = pkt + pktlen; + size_t sent, len; + CURLcode result = CURLE_OK; + VERBOSE(size_t calls = 0); + + *psent = 0; + + /* Send one datagram-sized chunk per call into the lower filter. */ + for(p = pkt; p < end; p += len) { + len = CURLMIN(gsolen, (size_t)(end - p)); + result = Curl_conn_cf_send(cf->next, data, p, len, FALSE, &sent); + /* Report forward progress even if we return CURLE_AGAIN later. */ + VERBOSE(++calls); + /* Preserve lower-filter errors (including CURLE_AGAIN). */ + if(result) + goto out; + + if(sent != len) { + /* We can only send the complete datagram, not parts. */ + result = CURLE_SEND_ERROR; + goto out; + } + *psent += sent; + } + +out: + CURL_TRC_CF(data, cf, + "vquic_cf_send(len=%zu, gso=%zu, calls=%zu) -> %d, sent=%zu", + pktlen, gsolen, calls, (int)result, *psent); + return result; +} + +static CURLcode vquic_send_packets(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + const uint8_t *pkt, size_t pktlen, + size_t gsolen, size_t *psent) +{ + CURLcode result; +#ifdef DEBUGBUILD + /* simulate network blocking/partial writes */ + if(qctx->wblock_percent > 0) { + unsigned char c; + *psent = 0; + Curl_rand(data, &c, 1); + if(c >= ((100 - qctx->wblock_percent) * 256 / 100)) { + CURL_TRC_CF(data, cf, "vquic_flush() simulate EWOULDBLOCK"); + return CURLE_AGAIN; + } + } +#endif + if(qctx->no_gso && pktlen > gsolen) { + result = send_packet_no_gso(cf, data, qctx, pkt, pktlen, gsolen, psent); + } + else { + result = do_sendmsg(cf, data, qctx, pkt, pktlen, gsolen, psent); + } + if(!result) + qctx->last_io = qctx->last_op; + return result; +} + +CURLcode Curl_vquic_flush(struct Curl_cfilter *cf, struct Curl_easy *data, + struct cf_quic_ctx *qctx) +{ + const unsigned char *buf; + size_t blen, sent; + CURLcode result; + size_t gsolen; + + while(Curl_bufq_peek(&qctx->sendbuf, &buf, &blen)) { + gsolen = qctx->gsolen; + if(qctx->split_len) { + gsolen = qctx->split_gsolen; + if(blen > qctx->split_len) + blen = qctx->split_len; + } + + if(qctx->sockfd != CURL_SOCKET_BAD) { + /* Direct UDP socket (via happy eyeballs) */ + result = vquic_send_packets(cf, data, qctx, buf, blen, gsolen, &sent); + } + else { + /* Tunneled QUIC (CONNECT-UDP through proxy) */ + if(gsolen && (blen > gsolen)) { + /* Send one datagram at a time to preserve packet boundaries. */ + result = send_packet_no_gso_cf(cf, data, buf, blen, gsolen, &sent); + } + else { + /* No GSO aggregate to split, regular lower-filter send is enough. */ + result = Curl_conn_cf_send(cf->next, data, buf, blen, FALSE, &sent); + } + } + + if(result) { + if(result == CURLE_AGAIN) { + Curl_bufq_skip(&qctx->sendbuf, sent); + if(qctx->split_len) + qctx->split_len -= sent; + } + return result; + } + Curl_bufq_skip(&qctx->sendbuf, sent); + if(qctx->split_len) + qctx->split_len -= sent; + } + return CURLE_OK; +} + +CURLcode Curl_vquic_send(struct Curl_cfilter *cf, struct Curl_easy *data, + struct cf_quic_ctx *qctx, size_t gsolen) +{ + qctx->gsolen = gsolen; + return Curl_vquic_flush(cf, data, qctx); +} + +CURLcode Curl_vquic_send_tail_split(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, size_t gsolen, + size_t tail_len, size_t tail_gsolen) +{ + DEBUGASSERT(Curl_bufq_len(&qctx->sendbuf) > tail_len); + qctx->split_len = Curl_bufq_len(&qctx->sendbuf) - tail_len; + qctx->split_gsolen = gsolen; + qctx->gsolen = tail_gsolen; + CURL_TRC_CF(data, cf, "vquic_send_tail_split: [%zu gso=%zu][%zu gso=%zu]", + qctx->split_len, qctx->split_gsolen, tail_len, qctx->gsolen); + return Curl_vquic_flush(cf, data, qctx); +} + +#if (defined(HAVE_SENDMMSG) || defined(HAVE_SENDMSG)) && \ + !defined(HAVE_APPLE_MSG_X) +static size_t vquic_msghdr_get_udp_gro(struct msghdr *msg) +{ + int gso_size = 0; +#if defined(__linux__) && defined(UDP_GRO) + struct cmsghdr *cmsg; + + /* Workaround musl CMSG_NXTHDR issue */ +#if defined(__clang__) && !defined(__GLIBC__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-compare" +#pragma clang diagnostic ignored "-Wcast-align" +#endif + for(cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) { +#if defined(__clang__) && !defined(__GLIBC__) +#pragma clang diagnostic pop +#endif + if(cmsg->cmsg_level == SOL_UDP && cmsg->cmsg_type == UDP_GRO) { + memcpy(&gso_size, CMSG_DATA(cmsg), sizeof(gso_size)); + + break; + } + } +#endif /* linux && UDP_GRO */ + (void)msg; + + return (size_t)gso_size; +} +#endif /* (HAVE_SENDMMSG || HAVE_SENDMSG) && !HAVE_APPLE_MSG_X */ + +#if (defined(HAVE_SENDMMSG) || defined(HAVE_SENDMSG) || \ + defined(HAVE_APPLE_MSG_X)) && \ + (defined(IP_RECVTOS) || defined(IP_TOS)) && defined(IPTOS_ECN_MASK) +static uint8_t vquic_msghdr_get_ecn(struct msghdr *msg, int family) +{ + struct cmsghdr *cmsg; + switch(family) { + case AF_INET: + /* Workaround musl CMSG_NXTHDR issue */ +#if defined(__clang__) && !defined(__GLIBC__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-compare" +#pragma clang diagnostic ignored "-Wcast-align" +#endif + for(cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) { +#if defined(__clang__) && !defined(__GLIBC__) +#pragma clang diagnostic pop +#endif + if(cmsg->cmsg_level == IPPROTO_IP && +#ifdef __APPLE__ + cmsg->cmsg_type == IP_RECVTOS +#else + cmsg->cmsg_type == IP_TOS +#endif + && cmsg->cmsg_len) { + return *(uint8_t *)(CMSG_DATA(cmsg)) & IPTOS_ECN_MASK; + } + } + break; + case AF_INET6: + /* Workaround musl CMSG_NXTHDR issue */ +#if defined(__clang__) && !defined(__GLIBC__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-compare" +#pragma clang diagnostic ignored "-Wcast-align" +#endif + for(cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) { +#if defined(__clang__) && !defined(__GLIBC__) +#pragma clang diagnostic pop +#endif + if(cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_TCLASS && + cmsg->cmsg_len) { + unsigned int tos; + + memcpy(&tos, CMSG_DATA(cmsg), sizeof(int)); + + return (uint8_t)(tos & IPTOS_ECN_MASK); + } + } + break; + } + return 0; +} +#else +#define vquic_msghdr_get_ecn(a, b) 0 +#endif /* HAVE_SENDMMSG || HAVE_SENDMSG || HAVE_APPLE_MSG_X ... */ + +#ifdef HAVE_SENDMMSG + +static CURLcode recvmmsg_packets(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + size_t max_pkts, + Curl_vquic_recv_pkts_cb *recv_cb, void *userp) +{ +#if defined(__linux__) && defined(UDP_GRO) +#define MMSG_NUM 16 +#define UDP_GRO_CNT_MAX 64 +#define CMSG_PER_MSG_SIZE (2 * CMSG_SPACE(sizeof(int))) +#else +#define MMSG_NUM 64 +#define UDP_GRO_CNT_MAX 1 +#define CMSG_PER_MSG_SIZE CMSG_SPACE(sizeof(int)) +#endif +#define MSG_BUF_SIZE (UDP_GRO_CNT_MAX * 1500) + struct iovec msg_iov[MMSG_NUM]; + struct mmsghdr mmsg[MMSG_NUM]; + uint8_t msg_ctrl[MMSG_NUM * CMSG_PER_MSG_SIZE]; + struct sockaddr_storage remote_addr[MMSG_NUM]; + size_t total_nread = 0, pkts = 0; +#ifdef CURLVERBOSE + size_t calls = 0; +#endif + int mcount, i, n; + char errstr[STRERROR_LEN]; + CURLcode result = CURLE_OK; + size_t gso_size; + char *sockbuf = NULL; + uint8_t (*bufs)[MSG_BUF_SIZE] = NULL; + uint8_t ecn = 0; + + DEBUGASSERT(max_pkts > 0); + result = Curl_multi_xfer_sockbuf_borrow(data, MMSG_NUM * MSG_BUF_SIZE, + &sockbuf); + if(result) + goto out; + bufs = (uint8_t (*)[MSG_BUF_SIZE])sockbuf; + + total_nread = 0; + while(pkts < max_pkts) { + n = (int)CURLMIN(CURLMIN(MMSG_NUM, IOV_MAX), max_pkts); + memset(&mmsg, 0, sizeof(mmsg)); + for(i = 0; i < n; ++i) { + msg_iov[i].iov_base = bufs[i]; + msg_iov[i].iov_len = sizeof(bufs[i]); + mmsg[i].msg_hdr.msg_iov = &msg_iov[i]; + mmsg[i].msg_hdr.msg_iovlen = 1; + mmsg[i].msg_hdr.msg_name = &remote_addr[i]; + mmsg[i].msg_hdr.msg_namelen = sizeof(remote_addr[i]); + mmsg[i].msg_hdr.msg_control = &msg_ctrl[i * CMSG_PER_MSG_SIZE]; + mmsg[i].msg_hdr.msg_controllen = CMSG_PER_MSG_SIZE; + } + + while((mcount = recvmmsg(qctx->sockfd, mmsg, n, 0, NULL)) == -1 && + (SOCKERRNO == SOCKEINTR || SOCKERRNO == SOCKEMSGSIZE)) + ; + if(mcount == -1) { + if(SOCK_EAGAIN(SOCKERRNO)) { + CURL_TRC_CF(data, cf, "ingress, recvmmsg -> EAGAIN"); + goto out; + } + if(!cf->connected && SOCKERRNO == SOCKECONNREFUSED) { + struct ip_quadruple ip; + if(!Curl_cf_socket_peek(cf->next, data, NULL, NULL, &ip)) + failf(data, "QUIC: connection to %s port %u refused", + ip.remote_ip, ip.remote_port); + result = CURLE_COULDNT_CONNECT; + goto out; + } + curlx_strerror(SOCKERRNO, errstr, sizeof(errstr)); + failf(data, "QUIC: recvmmsg() unexpectedly returned %d (errno=%d; %s)", + mcount, SOCKERRNO, errstr); + result = CURLE_RECV_ERROR; + goto out; + } + + VERBOSE(++calls); + for(i = 0; i < mcount; ++i) { + /* A zero-length UDP packet is no QUIC packet. Ignore. */ + if(!mmsg[i].msg_len) { + ++pkts; + continue; + } + total_nread += mmsg[i].msg_len; + + ecn = vquic_msghdr_get_ecn(&mmsg[i].msg_hdr, remote_addr[i].ss_family); + gso_size = vquic_msghdr_get_udp_gro(&mmsg[i].msg_hdr); + if(gso_size == 0) + gso_size = mmsg[i].msg_len; + + result = recv_cb(bufs[i], mmsg[i].msg_len, gso_size, + mmsg[i].msg_hdr.msg_name, + mmsg[i].msg_hdr.msg_namelen, ecn, userp); + if(result) + goto out; + pkts += (mmsg[i].msg_len + gso_size - 1) / gso_size; + } + } + +out: + if(total_nread || result) + CURL_TRC_CF(data, cf, + "vquic_recvmmsg(len=%zu, packets=%zu, calls=%zu) -> %d", + total_nread, pkts, calls, (int)result); + Curl_multi_xfer_sockbuf_release(data, sockbuf); + return result; +} + +#elif defined(HAVE_APPLE_MSG_X) + +static CURLcode recvmsg_x_packets(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + size_t max_pkts, + Curl_vquic_recv_pkts_cb *recv_cb, + void *userp) +{ +#define MSG_X_NUM 64 +#define MSG_BUF_SIZE (2048) +#define CMSG_PER_MSG_SIZE CMSG_SPACE(sizeof(int)) + struct iovec msg_iov[MSG_X_NUM]; + struct msghdr_x mmsg[MSG_X_NUM]; + uint8_t msg_ctrl[MSG_X_NUM * CMSG_PER_MSG_SIZE]; + struct sockaddr_storage remote_addr[MSG_X_NUM]; + size_t total_nread = 0, pkts = 0; +#ifdef CURLVERBOSE + size_t calls = 0; +#endif + int mcount, i; + char errstr[STRERROR_LEN]; + CURLcode result = CURLE_OK; + size_t gso_size; + char *sockbuf = NULL; + uint8_t (*bufs)[MSG_BUF_SIZE] = NULL; + uint8_t ecn = 0; + + DEBUGASSERT(max_pkts > 0); + result = Curl_multi_xfer_sockbuf_borrow(data, MSG_X_NUM * MSG_BUF_SIZE, + &sockbuf); + if(result) + goto out; + bufs = (uint8_t (*)[MSG_BUF_SIZE])sockbuf; + + total_nread = 0; + while(pkts < max_pkts) { + int n = (int)CURLMIN(CURLMIN(MSG_X_NUM, IOV_MAX), max_pkts); + memset(&mmsg, 0, sizeof(mmsg)); + for(i = 0; i < n; ++i) { + msg_iov[i].iov_base = bufs[i]; + msg_iov[i].iov_len = sizeof(bufs[i]); + mmsg[i].msg_iov = &msg_iov[i]; + mmsg[i].msg_iovlen = 1; + mmsg[i].msg_name = &remote_addr[i]; + mmsg[i].msg_namelen = sizeof(remote_addr[i]); + mmsg[i].msg_control = &msg_ctrl[i * CMSG_PER_MSG_SIZE]; + mmsg[i].msg_controllen = CMSG_PER_MSG_SIZE; + } + +#if defined(CURL_HAVE_DIAG) && defined(__APPLE__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + while((mcount = syscall(SYS_recvmsg_x, qctx->sockfd, mmsg, n, 0)) == -1 && + (SOCKERRNO == SOCKEINTR || SOCKERRNO == SOCKEMSGSIZE)) + ; +#if defined(CURL_HAVE_DIAG) && defined(__APPLE__) +#pragma GCC diagnostic pop +#endif + if(mcount == -1) { + if(SOCK_EAGAIN(SOCKERRNO)) { + CURL_TRC_CF(data, cf, "ingress, recvmsg_x -> EAGAIN"); + goto out; + } + if(!cf->connected && SOCKERRNO == SOCKECONNREFUSED) { + struct ip_quadruple ip; + if(!Curl_cf_socket_peek(cf->next, data, NULL, NULL, &ip)) + failf(data, "QUIC: connection to %s port %u refused", + ip.remote_ip, ip.remote_port); + result = CURLE_COULDNT_CONNECT; + goto out; + } + curlx_strerror(SOCKERRNO, errstr, sizeof(errstr)); + failf(data, "QUIC: recvmsg_x() unexpectedly returned %d (errno=%d; %s)", + mcount, SOCKERRNO, errstr); + result = CURLE_RECV_ERROR; + goto out; + } + + VERBOSE(++calls); + for(i = 0; i < mcount; ++i) { + /* A zero-length UDP packet is no QUIC packet. Ignore. */ + if(!mmsg[i].msg_datalen) { + ++pkts; + continue; + } + total_nread += mmsg[i].msg_datalen; + ecn = vquic_msghdr_get_ecn((struct msghdr *)&mmsg[i], + remote_addr[i].ss_family); + gso_size = mmsg[i].msg_datalen; + + result = recv_cb(bufs[i], mmsg[i].msg_datalen, gso_size, + mmsg[i].msg_name, + mmsg[i].msg_namelen, ecn, userp); + if(result) + goto out; + pkts += (mmsg[i].msg_datalen + gso_size - 1) / gso_size; + } + } + +out: + if(total_nread || result) + CURL_TRC_CF(data, cf, + "vquic_recvmsg_x(len=%zu, packets=%zu, calls=%zu) -> %d", + total_nread, pkts, calls, (int)result); + Curl_multi_xfer_sockbuf_release(data, sockbuf); + return result; +} + +#elif defined(HAVE_SENDMSG) +static CURLcode recvmsg_packets(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + size_t max_pkts, + Curl_vquic_recv_pkts_cb *recv_cb, void *userp) +{ +#define CMSG_PER_MSG_SIZE CMSG_SPACE(sizeof(int)) + struct iovec msg_iov; + struct msghdr msg; + uint8_t buf[64 * 1024]; + struct sockaddr_storage remote_addr; + size_t total_nread, pkts, calls; + ssize_t rc; + size_t nread; + char errstr[STRERROR_LEN]; + CURLcode result = CURLE_OK; + uint8_t msg_ctrl[CMSG_PER_MSG_SIZE]; + size_t gso_size; + uint8_t ecn = 0; + + DEBUGASSERT(max_pkts > 0); + for(pkts = 0, total_nread = 0, calls = 0; pkts < max_pkts;) { + /* fully initialize this on each call to `recvmsg()`. There seem to + * operating systems out there that mess with `msg_iov.iov_len`. */ + memset(&msg, 0, sizeof(msg)); + msg_iov.iov_base = buf; + msg_iov.iov_len = sizeof(buf); + msg.msg_iov = &msg_iov; + msg.msg_iovlen = 1; + msg.msg_control = msg_ctrl; + msg.msg_name = &remote_addr; + msg.msg_namelen = sizeof(remote_addr); + msg.msg_controllen = CMSG_PER_MSG_SIZE; + + while((rc = recvmsg(qctx->sockfd, &msg, 0)) == -1 && + (SOCKERRNO == SOCKEINTR || SOCKERRNO == SOCKEMSGSIZE)) + ; + if(!curlx_sztouz(rc, &nread)) { + if(SOCK_EAGAIN(SOCKERRNO)) { + goto out; + } + if(!cf->connected && SOCKERRNO == SOCKECONNREFUSED) { + struct ip_quadruple ip; + if(!Curl_cf_socket_peek(cf->next, data, NULL, NULL, &ip)) + failf(data, "QUIC: connection to %s port %u refused", + ip.remote_ip, ip.remote_port); + result = CURLE_COULDNT_CONNECT; + goto out; + } + curlx_strerror(SOCKERRNO, errstr, sizeof(errstr)); + failf(data, "QUIC: recvmsg() unexpectedly returned %zd (errno=%d; %s)", + rc, SOCKERRNO, errstr); + result = CURLE_RECV_ERROR; + goto out; + } + + total_nread += nread; + ++calls; + + /* A 0-length UDP packet is no QUIC packet */ + if(!nread) { + ++pkts; + continue; + } + + ecn = vquic_msghdr_get_ecn(&msg, remote_addr.ss_family); + gso_size = vquic_msghdr_get_udp_gro(&msg); + if(gso_size == 0) + gso_size = nread; + + result = recv_cb(buf, nread, gso_size, + msg.msg_name, msg.msg_namelen, ecn, userp); + if(result) + goto out; + pkts += (nread + gso_size - 1) / gso_size; + } + +out: + if(total_nread || result) + CURL_TRC_CF(data, cf, + "vquic_recvmsg(len=%zu, packets=%zu, calls=%zu) -> %d", + total_nread, pkts, calls, (int)result); + return result; +} + +#else /* HAVE_SENDMMSG || HAVE_SENDMSG */ +static CURLcode recvfrom_packets(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + size_t max_pkts, + Curl_vquic_recv_pkts_cb *recv_cb, void *userp) +{ + uint8_t buf[64 * 1024]; + int bufsize = (int)sizeof(buf); + struct sockaddr_storage remote_addr; + socklen_t remote_addrlen = sizeof(remote_addr); + size_t total_nread, pkts, calls = 0, nread; + ssize_t rv; + char errstr[STRERROR_LEN]; + CURLcode result = CURLE_OK; + + DEBUGASSERT(max_pkts > 0); + for(pkts = 0, total_nread = 0; pkts < max_pkts;) { + while((rv = recvfrom(qctx->sockfd, (char *)buf, bufsize, 0, + (struct sockaddr *)&remote_addr, + &remote_addrlen)) == -1 && + (SOCKERRNO == SOCKEINTR || SOCKERRNO == SOCKEMSGSIZE)) + ; + if(!curlx_sztouz(rv, &nread)) { + if(SOCK_EAGAIN(SOCKERRNO)) { + CURL_TRC_CF(data, cf, "ingress, recvfrom -> EAGAIN"); + goto out; + } + if(!cf->connected && SOCKERRNO == SOCKECONNREFUSED) { + struct ip_quadruple ip; + if(!Curl_cf_socket_peek(cf->next, data, NULL, NULL, &ip)) + failf(data, "QUIC: connection to %s port %u refused", + ip.remote_ip, ip.remote_port); + result = CURLE_COULDNT_CONNECT; + goto out; + } + curlx_strerror(SOCKERRNO, errstr, sizeof(errstr)); + failf(data, "QUIC: recvfrom() unexpectedly returned %zd (errno=%d; %s)", + rv, SOCKERRNO, errstr); + result = CURLE_RECV_ERROR; + goto out; + } + + ++pkts; + ++calls; + + /* A 0-length UDP packet is no QUIC packet */ + if(!nread) + continue; + + total_nread += nread; + result = recv_cb(buf, nread, nread, &remote_addr, remote_addrlen, + 0, userp); + if(result) + goto out; + } + +out: + if(total_nread || result) + CURL_TRC_CF(data, cf, + "vquic_recvfrom(len=%zu, packets=%zu, calls=%zu) -> %d", + total_nread, pkts, calls, (int)result); + return result; +} +#endif /* !HAVE_SENDMMSG && !HAVE_SENDMSG */ + +CURLcode Curl_vquic_recv_packets(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + size_t max_pkts, + Curl_vquic_recv_pkts_cb *recv_cb, void *userp) +{ + CURLcode result; +#ifdef HAVE_SENDMMSG + result = recvmmsg_packets(cf, data, qctx, max_pkts, recv_cb, userp); +#elif defined(HAVE_APPLE_MSG_X) + result = recvmsg_x_packets(cf, data, qctx, max_pkts, recv_cb, userp); +#elif defined(HAVE_SENDMSG) + result = recvmsg_packets(cf, data, qctx, max_pkts, recv_cb, userp); +#else + result = recvfrom_packets(cf, data, qctx, max_pkts, recv_cb, userp); +#endif + if(!result) { + if(!qctx->got_first_byte) { + qctx->got_first_byte = TRUE; + qctx->first_byte_at = qctx->last_op; + } + qctx->last_io = qctx->last_op; + } + return result; +} + +/* + * If the QLOGDIR environment variable is set, open and return a file + * descriptor to write the log to. + * + * This function returns error if something failed outside of failing to + * create the file. Open file success is deemed by seeing if the returned fd + * is != -1. + */ +CURLcode Curl_qlogdir(struct Curl_easy *data, + unsigned char *scid, + size_t scidlen, + int *qlogfdp) +{ + char *qlog_dir = curl_getenv("QLOGDIR"); + *qlogfdp = -1; + if(qlog_dir) { + struct dynbuf fname; + CURLcode result; + unsigned int i; + curlx_dyn_init(&fname, DYN_QLOG_NAME); + result = curlx_dyn_add(&fname, qlog_dir); + if(!result) + result = curlx_dyn_add(&fname, "/"); + for(i = 0; (i < scidlen) && !result; i++) { + char hex[3]; + curl_msnprintf(hex, 3, "%02x", scid[i]); + result = curlx_dyn_add(&fname, hex); + } + if(!result) + result = curlx_dyn_add(&fname, ".sqlog"); + + if(!result) { + int qlogfd = curlx_open(curlx_dyn_ptr(&fname), + O_WRONLY | O_CREAT | CURL_O_BINARY, + data->set.new_file_perms +#ifdef _WIN32 + & (_S_IREAD | _S_IWRITE) +#endif + ); + if(qlogfd != -1) + *qlogfdp = qlogfd; + } + curlx_dyn_free(&fname); + curlx_free(qlog_dir); + if(result) + return result; + } + + return CURLE_OK; +} + +CURLcode Curl_cf_quic_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer) +{ + CURLcode result; + + (void)data; /* not used in all cases and compilers are stupid */ +#if defined(USE_NGTCP2) && defined(USE_NGHTTP3) + result = Curl_cf_ngtcp2_insert_after(cf_at, origin, peer); +#elif defined(USE_QUICHE) + result = Curl_cf_quiche_insert_after(cf_at, origin, peer); +#else + (void)cf_at; + (void)origin; + (void)peer; + result = CURLE_NOT_BUILT_IN; +#endif + +#if defined(USE_HTTPSRR) && defined(USE_ECH) + /* When using ECH, kick off the HTTPS-RR resolve */ + if(!result && (origin->scheme->family == CURLPROTO_HTTP) && + CURLECH_ENABLED(data) && + Curl_ssl_supports(data, SSLSUPP_ECH) && + (data->set.tls_ech != CURLECH_GREASE) && + !CURL_EASY_STR(data, STRING_ECH_CONFIG)) { + result = Curl_conn_dns_add_https_resolve(data, cf_at->conn, + cf_at->sockindex, origin); + } +#endif /* USE_HTTPSRR && USE_ECH */ + return result; +} + +CURLcode Curl_cf_quic_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport) +{ + (void)transport_peer; + (void)tunnel_transport; + (void)tunnel_peer; + DEBUGASSERT(transport_peer == TRNSPRT_QUIC); +#if defined(USE_NGTCP2) && defined(USE_NGHTTP3) + return Curl_cf_ngtcp2_create(pcf, data, origin, peer, conn, addr); +#elif defined(USE_QUICHE) + return Curl_cf_quiche_create(pcf, data, origin, peer, conn, addr); +#else + *pcf = NULL; + (void)data; + (void)origin; + (void)peer; + (void)conn; + (void)addr; + (void)tunnel_peer; + (void)tunnel_transport; + return CURLE_NOT_BUILT_IN; +#endif +} + +#if !defined(CURL_DISABLE_PROXY) && defined(USE_PROXY_HTTP3) + +CURLcode Curl_cf_h3_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport) +{ +#if defined(USE_NGTCP2) && defined(USE_NGHTTP3) + return Curl_cf_ngtcp2_proxy_insert_after(cf_at, data, origin, peer, + tunnel_peer, tunnel_transport); +#else + (void)cf_at; + (void)data; + (void)origin; + (void)peer; + (void)tunnel_peer; + (void)tunnel_transport; + return CURLE_NOT_BUILT_IN; +#endif +} + +CURLcode Curl_cf_h3_proxy_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport) +{ + DEBUGASSERT(transport_peer == TRNSPRT_QUIC); +#if defined(USE_NGTCP2) && defined(USE_NGHTTP3) + return Curl_cf_ngtcp2_proxy_create(pcf, data, origin, peer, transport_peer, + conn, addr, + tunnel_peer, tunnel_transport); +#else + *pcf = NULL; + (void)data; + (void)conn; + (void)addr; + (void)peer; + (void)transport_peer; + (void)tunnel_peer; + (void)tunnel_transport; + return CURLE_NOT_BUILT_IN; +#endif +} + +#endif /* !CURL_DISABLE_PROXY && USE_PROXY_HTTP3 */ + +CURLcode Curl_conn_may_http3(struct Curl_easy *data, + const struct connectdata *conn, + unsigned char transport) +{ + if(transport == TRNSPRT_UNIX) { + failf(data, "HTTP/3 cannot be used over UNIX domain sockets"); + return CURLE_QUIC_CONNECT_ERROR; + } + if(!(data->state.origin->scheme->flags & PROTOPT_SSL)) { + failf(data, "HTTP/3 requested for non-HTTPS URL"); + return CURLE_URL_MALFORMAT; + } +#ifndef CURL_DISABLE_PROXY + if(conn->socks_proxy.peer) { + failf(data, "HTTP/3 is not supported over a SOCKS proxy"); + return CURLE_URL_MALFORMAT; + } +#else + (void)conn; +#endif + + return CURLE_OK; +} + +#ifdef CURLVERBOSE +const char *Curl_vquic_h3_err_str(uint64_t error_code) +{ + if(error_code <= UINT_MAX) { + switch((unsigned int)error_code) { + case CURL_H3_ERR_NO_ERROR: + return "NO_ERROR"; + case CURL_H3_ERR_GENERAL_PROTOCOL_ERROR: + return "GENERAL_PROTOCOL_ERROR"; + case CURL_H3_ERR_INTERNAL_ERROR: + return "INTERNAL_ERROR"; + case CURL_H3_ERR_STREAM_CREATION_ERROR: + return "STREAM_CREATION_ERROR"; + case CURL_H3_ERR_CLOSED_CRITICAL_STREAM: + return "CLOSED_CRITICAL_STREAM"; + case CURL_H3_ERR_FRAME_UNEXPECTED: + return "FRAME_UNEXPECTED"; + case CURL_H3_ERR_FRAME_ERROR: + return "FRAME_ERROR"; + case CURL_H3_ERR_EXCESSIVE_LOAD: + return "EXCESSIVE_LOAD"; + case CURL_H3_ERR_ID_ERROR: + return "ID_ERROR"; + case CURL_H3_ERR_SETTINGS_ERROR: + return "SETTINGS_ERROR"; + case CURL_H3_ERR_MISSING_SETTINGS: + return "MISSING_SETTINGS"; + case CURL_H3_ERR_REQUEST_REJECTED: + return "REQUEST_REJECTED"; + case CURL_H3_ERR_REQUEST_CANCELLED: + return "REQUEST_CANCELLED"; + case CURL_H3_ERR_REQUEST_INCOMPLETE: + return "REQUEST_INCOMPLETE"; + case CURL_H3_ERR_MESSAGE_ERROR: + return "MESSAGE_ERROR"; + case CURL_H3_ERR_CONNECT_ERROR: + return "CONNECT_ERROR"; + case CURL_H3_ERR_VERSION_FALLBACK: + return "VERSION_FALLBACK"; + default: + break; + } + } + /* RFC 9114 ch. 8.1 + 9, reserved future error codes that are NO_ERROR */ + if((error_code >= 0x21) && !((error_code - 0x21) % 0x1f)) + return "NO_ERROR"; + return "unknown"; +} +#endif /* CURLVERBOSE */ + +#if defined(USE_NGTCP2) || defined(USE_NGHTTP3) + +static void *vquic_ngtcp2_malloc(size_t size, void *user_data) +{ + (void)user_data; + return Curl_cmalloc(size); +} + +static void vquic_ngtcp2_free(void *ptr, void *user_data) +{ + (void)user_data; + Curl_cfree(ptr); +} + +static void *vquic_ngtcp2_calloc(size_t nmemb, size_t size, void *user_data) +{ + (void)user_data; + return Curl_ccalloc(nmemb, size); +} + +static void *vquic_ngtcp2_realloc(void *ptr, size_t size, void *user_data) +{ + (void)user_data; + return Curl_crealloc(ptr, size); +} + +#ifdef USE_NGTCP2 +static struct ngtcp2_mem vquic_ngtcp2_mem = { + NULL, + vquic_ngtcp2_malloc, + vquic_ngtcp2_free, + vquic_ngtcp2_calloc, + vquic_ngtcp2_realloc +}; +struct ngtcp2_mem *Curl_ngtcp2_mem(void) +{ + return &vquic_ngtcp2_mem; +} +#endif + +#ifdef USE_NGHTTP3 +static struct nghttp3_mem vquic_nghttp3_mem = { + NULL, + vquic_ngtcp2_malloc, + vquic_ngtcp2_free, + vquic_ngtcp2_calloc, + vquic_ngtcp2_realloc +}; +struct nghttp3_mem *Curl_nghttp3_mem(void) +{ + return &vquic_nghttp3_mem; +} +#endif + +#endif /* USE_NGTCP2 || USE_NGHTTP3 */ + +#else /* CURL_DISABLE_HTTP || !USE_HTTP3 */ + +CURLcode Curl_conn_may_http3(struct Curl_easy *data, + const struct connectdata *conn, + unsigned char transport) +{ + (void)data; + (void)conn; + (void)transport; + DEBUGF(infof(data, "QUIC is not supported in this build")); + return CURLE_NOT_BUILT_IN; +} + +#endif /* !CURL_DISABLE_HTTP && USE_HTTP3 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic.h new file mode 100644 index 0000000000..f1363e2c0a --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic.h @@ -0,0 +1,92 @@ +#ifndef HEADER_CURL_VQUIC_QUIC_H +#define HEADER_CURL_VQUIC_QUIC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_HTTP3) +struct Curl_cfilter; +struct Curl_easy; +struct connectdata; +struct Curl_addrinfo; + +void Curl_quic_ver(char *p, size_t len); +int Curl_vquic_init(void); +void Curl_vquic_cleanup(void); + +CURLcode Curl_qlogdir(struct Curl_easy *data, + unsigned char *scid, + size_t scidlen, + int *qlogfdp); + +CURLcode Curl_cf_quic_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer); + +CURLcode Curl_cf_quic_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport); + +extern struct Curl_cftype Curl_cft_http3; + +#if !defined(CURL_DISABLE_PROXY) && defined(USE_PROXY_HTTP3) + +CURLcode Curl_cf_h3_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport); + +CURLcode Curl_cf_h3_proxy_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer, + uint8_t transport_peer, + struct connectdata *conn, + struct Curl_sockaddr_ex *addr, + struct Curl_peer *tunnel_peer, + uint8_t tunnel_transport); + +extern struct Curl_cftype Curl_cft_h3_proxy; + +#endif /* !CURL_DISABLE_PROXY && USE_PROXY_HTTP3 */ + +#else +#define Curl_vquic_init() 1 +#define Curl_vquic_cleanup() +#endif /* !CURL_DISABLE_HTTP && USE_HTTP3 */ + +CURLcode Curl_conn_may_http3(struct Curl_easy *data, + const struct connectdata *conn, + unsigned char transport); + +#endif /* HEADER_CURL_VQUIC_QUIC_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic_int.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic_int.h new file mode 100644 index 0000000000..23e1102eb0 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vquic/vquic_int.h @@ -0,0 +1,129 @@ +#ifndef HEADER_CURL_VQUIC_QUIC_INT_H +#define HEADER_CURL_VQUIC_QUIC_INT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_HTTP3 + +#include "bufq.h" + +#define MAX_UDP_PAYLOAD_SIZE 1452 + +/* definitions from RFC 9114, ch 8.1 */ +typedef enum { + CURL_H3_ERR_NO_ERROR = 0x0100, + CURL_H3_ERR_GENERAL_PROTOCOL_ERROR = 0x0101, + CURL_H3_ERR_INTERNAL_ERROR = 0x0102, + CURL_H3_ERR_STREAM_CREATION_ERROR = 0x0103, + CURL_H3_ERR_CLOSED_CRITICAL_STREAM = 0x0104, + CURL_H3_ERR_FRAME_UNEXPECTED = 0x0105, + CURL_H3_ERR_FRAME_ERROR = 0x0106, + CURL_H3_ERR_EXCESSIVE_LOAD = 0x0107, + CURL_H3_ERR_ID_ERROR = 0x0108, + CURL_H3_ERR_SETTINGS_ERROR = 0x0109, + CURL_H3_ERR_MISSING_SETTINGS = 0x010a, + CURL_H3_ERR_REQUEST_REJECTED = 0x010b, + CURL_H3_ERR_REQUEST_CANCELLED = 0x010c, + CURL_H3_ERR_REQUEST_INCOMPLETE = 0x010d, + CURL_H3_ERR_MESSAGE_ERROR = 0x010e, + CURL_H3_ERR_CONNECT_ERROR = 0x010f, + CURL_H3_ERR_VERSION_FALLBACK = 0x0110, +} vquic_h3_error; + +#ifdef CURLVERBOSE +const char *Curl_vquic_h3_err_str(uint64_t error_code); +#else +#define Curl_vquic_h3_err_str(x) "" +#endif /* CURLVERBOSE */ + +struct cf_quic_ctx { + curl_socket_t sockfd; /* connected UDP socket */ + struct sockaddr_storage local_addr; /* address socket is bound to */ + socklen_t local_addrlen; /* length of local address */ + + struct bufq sendbuf; /* buffer for sending one or more packets */ + struct curltime first_byte_at; /* when first byte was recvd */ + struct curltime last_op; /* last (attempted) send/recv operation */ + struct curltime last_io; /* last successful socket IO */ + size_t gsolen; /* length of individual packets in send buf */ + size_t split_len; /* if != 0, buffer length after which GSO differs */ + size_t split_gsolen; /* length of individual packets after split_len */ +#ifdef DEBUGBUILD + int wblock_percent; /* percent of writes doing EAGAIN */ +#endif + BIT(got_first_byte); /* if first byte was received */ + BIT(no_gso); /* do not use gso on sending */ +}; + +#define H3_STREAM_CTX(ctx, data) \ + ((data) ? Curl_uint32_hash_get(&(ctx)->streams, (data)->mid) : NULL) + +CURLcode Curl_vquic_ctx_init(struct Curl_easy *data, + struct cf_quic_ctx *qctx); +void Curl_vquic_ctx_free(struct cf_quic_ctx *qctx); + +void Curl_vquic_ctx_set_time(struct cf_quic_ctx *qctx, + const struct curltime *pnow); + +void Curl_vquic_ctx_update_time(struct cf_quic_ctx *qctx, + const struct curltime *pnow); + +CURLcode Curl_vquic_send(struct Curl_cfilter *cf, struct Curl_easy *data, + struct cf_quic_ctx *qctx, size_t gsolen); + +CURLcode Curl_vquic_send_tail_split(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, size_t gsolen, + size_t tail_len, size_t tail_gsolen); + +CURLcode Curl_vquic_flush(struct Curl_cfilter *cf, struct Curl_easy *data, + struct cf_quic_ctx *qctx); + +typedef CURLcode Curl_vquic_recv_pkts_cb(const unsigned char *buf, + size_t buflen, + size_t gso_size, + struct sockaddr_storage *remote_addr, + socklen_t remote_addrlen, uint8_t ecn, + void *userp); + +CURLcode Curl_vquic_recv_packets(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct cf_quic_ctx *qctx, + size_t max_pkts, + Curl_vquic_recv_pkts_cb *recv_cb, + void *userp); + +#ifdef USE_NGTCP2 +struct ngtcp2_mem; +struct ngtcp2_mem *Curl_ngtcp2_mem(void); +#endif +#ifdef USE_NGHTTP3 +struct nghttp3_mem; +struct nghttp3_mem *Curl_nghttp3_mem(void); +#endif + +#endif /* !USE_HTTP3 */ + +#endif /* HEADER_CURL_VQUIC_QUIC_INT_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/libssh.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/libssh.c new file mode 100644 index 0000000000..03a84d218b --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/libssh.c @@ -0,0 +1,3178 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Red Hat, Inc. + * + * Authors: Nikos Mavrogiannopoulos, Tomas Mraz, Stanislav Zidek, + * Robert Kolcun, Andreas Schneider + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_LIBSSH + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include "urldata.h" +#include "sendf.h" +#include "curl_trc.h" +#include "progress.h" +#include "transfer.h" +#include "vssh/ssh.h" +#include "url.h" +#include "cfilters.h" +#include "connect.h" +#include "parsedate.h" /* for the week day and month names */ +#include "curlx/strparse.h" +#include "multiif.h" +#include "select.h" +#include "vssh/vssh.h" +#include "curlx/base64.h" /* for curlx_base64_encode() */ + +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif + +/* A recent macro provided by libssh. Or make our own. */ +#ifndef SSH_STRING_FREE_CHAR +#define SSH_STRING_FREE_CHAR(x) \ + do { \ + if(x) { \ + ssh_string_free_char(x); \ + x = NULL; \ + } \ + } while(0) +#endif + +/* These stat values may not be the same as the user's S_IFMT / S_IFLNK */ +#ifndef SSH_S_IFMT +#define SSH_S_IFMT 00170000 +#endif +#ifndef SSH_S_IFLNK +#define SSH_S_IFLNK 0120000 +#endif + +static CURLcode sftp_error_to_CURLE(int err) +{ + switch(err) { + case SSH_FX_OK: + return CURLE_OK; + + case SSH_FX_NO_SUCH_FILE: + case SSH_FX_NO_SUCH_PATH: + return CURLE_REMOTE_FILE_NOT_FOUND; + + case SSH_FX_PERMISSION_DENIED: + case SSH_FX_WRITE_PROTECT: + return CURLE_REMOTE_ACCESS_DENIED; + + case SSH_FX_FILE_ALREADY_EXISTS: + return CURLE_REMOTE_FILE_EXISTS; + + default: + break; + } + + return CURLE_SSH; +} + +/* Multiple options: + * 1. CURL_EASY_STR(data, STRING_SSH_HOST_PUBLIC_KEY_SHA256) is set + * with a SHA256 hash. + * 2. CURL_EASY_STR(data, STRING_SSH_HOST_PUBLIC_KEY_MD5) is set + * with an MD5 hash (90s style auth, not sure we should have it here) + * 3. data->set.ssh_keyfunc callback is set. Then we do trust on first + * use. We even save on knownhosts if CURLKHSTAT_FINE_ADD_TO_FILE + * is returned by it. + * 4. none of the above. We only accept if it is present on known hosts. + * + * Returns SSH_OK or SSH_ERROR. + */ +static int myssh_is_known(struct Curl_easy *data, struct ssh_conn *sshc) +{ + int rc; + ssh_key pubkey; + unsigned char *hash_sha256 = NULL; + size_t hlen_sha256; + unsigned char *hash_md5 = NULL; + size_t hlen_md5; + char *found_base64 = NULL; + char *known_base64 = NULL; + int vstate; + enum curl_khmatch keymatch; + struct curl_khkey foundkey; + struct curl_khkey *knownkeyp = NULL; + curl_sshkeycallback func = data->set.ssh_keyfunc; + struct ssh_knownhosts_entry *knownhostsentry = NULL; + struct curl_khkey knownkey; + + rc = ssh_get_server_publickey(sshc->ssh_session, &pubkey); + + if(rc != SSH_OK) + return rc; + + if(CURL_EASY_STR(data, STRING_SSH_HOST_PUBLIC_KEY_SHA256)) { + const char *pubkey_sha256 = + CURL_EASY_STR(data, STRING_SSH_HOST_PUBLIC_KEY_SHA256); + char *fingerprint_b64 = NULL; + size_t fingerprint_b64_len; + size_t pub_pos = 0; + size_t b64_pos = 0; + + rc = ssh_get_publickey_hash(pubkey, SSH_PUBLICKEY_HASH_SHA256, + &hash_sha256, &hlen_sha256); + if(rc != SSH_OK || hlen_sha256 != 32) { + failf(data, "Denied establishing ssh session: " + "SHA256 fingerprint not available"); + goto cleanup; + } + + if(curlx_base64_encode((const uint8_t *)hash_sha256, 32, &fingerprint_b64, + &fingerprint_b64_len) != CURLE_OK) { + rc = SSH_ERROR; + goto cleanup; + } + + infof(data, "SSH SHA256 fingerprint: %s", fingerprint_b64); + + /* Find the position of any = padding characters in the public key */ + while((pubkey_sha256[pub_pos] != '=') && pubkey_sha256[pub_pos]) { + pub_pos++; + } + + /* Find the position of any = padding characters in the base64 coded + * hostkey fingerprint */ + while((fingerprint_b64[b64_pos] != '=') && fingerprint_b64[b64_pos]) { + b64_pos++; + } + + /* Before we authenticate we check the hostkey's SHA256 fingerprint + * against a known fingerprint, if available. + */ + if((pub_pos != b64_pos) || + strncmp(fingerprint_b64, pubkey_sha256, pub_pos)) { + failf(data, + "Denied establishing ssh session: mismatch SHA256 fingerprint. " + "Remote %s is not equal to %s", fingerprint_b64, pubkey_sha256); + curlx_free(fingerprint_b64); + rc = SSH_ERROR; + goto cleanup; + } + + curlx_free(fingerprint_b64); + + rc = SSH_OK; + goto cleanup; + } + + if(CURL_EASY_STR(data, STRING_SSH_HOST_PUBLIC_KEY_MD5)) { + const char *pubkey_md5 = + CURL_EASY_STR(data, STRING_SSH_HOST_PUBLIC_KEY_MD5); + char md5buffer[33]; + int i; + + rc = ssh_get_publickey_hash(pubkey, SSH_PUBLICKEY_HASH_MD5, + &hash_md5, &hlen_md5); + if(rc != SSH_OK || hlen_md5 != 16) { + failf(data, + "Denied establishing ssh session: MD5 fingerprint not available"); + goto cleanup; + } + + for(i = 0; i < 16; i++) + curl_msnprintf(&md5buffer[i * 2], 3, "%02x", hash_md5[i]); + + infof(data, "SSH MD5 fingerprint: %s", md5buffer); + + if(!curl_strequal(md5buffer, pubkey_md5)) { + failf(data, + "Denied establishing ssh session: mismatch MD5 fingerprint. " + "Remote %s is not equal to %s", md5buffer, pubkey_md5); + rc = SSH_ERROR; + goto cleanup; + } + + rc = SSH_OK; + goto cleanup; + } + + if(CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS)) { + + /* Get the known_key from the known hosts file */ + vstate = ssh_session_get_known_hosts_entry(sshc->ssh_session, + &knownhostsentry); + + /* Case an entry was found in a known hosts file */ + if(knownhostsentry) { + if(knownhostsentry->publickey) { + rc = ssh_pki_export_pubkey_base64(knownhostsentry->publickey, + &known_base64); + if(rc != SSH_OK) { + goto cleanup; + } + knownkey.key = known_base64; + knownkey.len = strlen(known_base64); + + switch(ssh_key_type(knownhostsentry->publickey)) { + case SSH_KEYTYPE_RSA: + knownkey.keytype = CURLKHTYPE_RSA; + break; + case SSH_KEYTYPE_RSA1: + knownkey.keytype = CURLKHTYPE_RSA1; + break; + case SSH_KEYTYPE_ECDSA: + case SSH_KEYTYPE_ECDSA_P256: + case SSH_KEYTYPE_ECDSA_P384: + case SSH_KEYTYPE_ECDSA_P521: + knownkey.keytype = CURLKHTYPE_ECDSA; + break; + case SSH_KEYTYPE_ED25519: + knownkey.keytype = CURLKHTYPE_ED25519; + break; + case SSH_KEYTYPE_DSS: + knownkey.keytype = CURLKHTYPE_DSS; + break; + default: + rc = SSH_ERROR; + goto cleanup; + } + knownkeyp = &knownkey; + } + } + + switch(vstate) { + case SSH_KNOWN_HOSTS_OK: + keymatch = CURLKHMATCH_OK; + break; + case SSH_KNOWN_HOSTS_OTHER: + keymatch = CURLKHMATCH_MISMATCH; + break; + case SSH_KNOWN_HOSTS_NOT_FOUND: + case SSH_KNOWN_HOSTS_UNKNOWN: + case SSH_KNOWN_HOSTS_ERROR: + keymatch = CURLKHMATCH_MISSING; + break; + default: + keymatch = CURLKHMATCH_MISMATCH; + break; + } + + if(func) { /* use callback to determine action */ + struct Curl_mapi_guard guard; + + rc = ssh_pki_export_pubkey_base64(pubkey, &found_base64); + if(rc != SSH_OK) + goto cleanup; + + foundkey.key = found_base64; + foundkey.len = strlen(found_base64); + + switch(ssh_key_type(pubkey)) { + case SSH_KEYTYPE_RSA: + foundkey.keytype = CURLKHTYPE_RSA; + break; + case SSH_KEYTYPE_RSA1: + foundkey.keytype = CURLKHTYPE_RSA1; + break; + case SSH_KEYTYPE_ECDSA: + case SSH_KEYTYPE_ECDSA_P256: + case SSH_KEYTYPE_ECDSA_P384: + case SSH_KEYTYPE_ECDSA_P521: + foundkey.keytype = CURLKHTYPE_ECDSA; + break; + case SSH_KEYTYPE_ED25519: + foundkey.keytype = CURLKHTYPE_ED25519; + break; + case SSH_KEYTYPE_DSS: + foundkey.keytype = CURLKHTYPE_DSS; + break; + default: + rc = SSH_ERROR; + goto cleanup; + } + + CURL_CBAPI_START(&guard, data, easy_ssh_keyfunc); + rc = func(data, knownkeyp, /* from the knownhosts file */ + &foundkey, /* from the remote host */ + keymatch, data->set.ssh_keyfunc_userp); + CURL_CBAPI_END(&guard); + + switch(rc) { + case CURLKHSTAT_FINE_ADD_TO_FILE: + rc = ssh_session_update_known_hosts(sshc->ssh_session); + if(rc != SSH_OK) { + goto cleanup; + } + break; + case CURLKHSTAT_FINE: + break; + default: /* REJECT/DEFER */ + rc = SSH_ERROR; + goto cleanup; + } + } + else { + if(keymatch != CURLKHMATCH_OK) { + rc = SSH_ERROR; + goto cleanup; + } + } + } + rc = SSH_OK; + +cleanup: + if(found_base64) { + /* !checksrc! disable BANNEDFUNC 1 */ + free(found_base64); /* allocated by libssh, deallocate with system free */ + } + if(known_base64) { + /* !checksrc! disable BANNEDFUNC 1 */ + free(known_base64); /* allocated by libssh, deallocate with system free */ + } + if(hash_sha256) + ssh_clean_pubkey_hash(&hash_sha256); + if(hash_md5) + ssh_clean_pubkey_hash(&hash_md5); + ssh_key_free(pubkey); + if(knownhostsentry) { + ssh_knownhosts_entry_free(knownhostsentry); + } + return rc; +} + +static int myssh_to_ERROR(struct Curl_easy *data, + struct ssh_conn *sshc, + CURLcode result) +{ + myssh_to(data, sshc, SSH_SESSION_DISCONNECT); + sshc->actualcode = result; + return SSH_ERROR; +} + +static int myssh_to_SFTP_CLOSE(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->actualcode = sftp_error_to_CURLE(sftp_get_error(sshc->sftp_session)); + return SSH_ERROR; +} + +static int myssh_to_PASSWD_AUTH(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(sshc->auth_methods & SSH_AUTH_METHOD_PASSWORD) { + myssh_to(data, sshc, SSH_AUTH_PASS_INIT); + return SSH_OK; + } + return myssh_to_ERROR(data, sshc, CURLE_LOGIN_DENIED); +} + +static int myssh_to_KEY_AUTH(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(sshc->auth_methods & SSH_AUTH_METHOD_INTERACTIVE) { + myssh_to(data, sshc, SSH_AUTH_KEY_INIT); + return SSH_OK; + } + return myssh_to_PASSWD_AUTH(data, sshc); +} + +static int myssh_to_GSSAPI_AUTH(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(sshc->auth_methods & SSH_AUTH_METHOD_GSSAPI_MIC) { + myssh_to(data, sshc, SSH_AUTH_GSSAPI); + return SSH_OK; + } + return myssh_to_KEY_AUTH(data, sshc); +} + +static int myssh_in_SFTP_READDIR_INIT(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + if(!sshp) + return myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + Curl_pgrsSetDownloadSize(data, -1); + if(data->req.no_body) { + myssh_to(data, sshc, SSH_STOP); + return SSH_NO_ERROR; + } + + /* + * This is a directory that we are trying to get, so produce a directory + * listing + */ + sshc->sftp_dir = sftp_opendir(sshc->sftp_session, + sshp->path); + if(!sshc->sftp_dir) { + failf(data, "Could not open directory for reading: %s", + ssh_get_error(sshc->ssh_session)); + return myssh_to_SFTP_CLOSE(data, sshc); + } + myssh_to(data, sshc, SSH_SFTP_READDIR); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_READDIR(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + CURLcode result = CURLE_OK; + + if(!sshp) + return myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + curlx_dyn_reset(&sshc->readdir_buf); + if(sshc->readdir_attrs) + sftp_attributes_free(sshc->readdir_attrs); + + sshc->readdir_attrs = sftp_readdir(sshc->sftp_session, sshc->sftp_dir); + if(sshc->readdir_attrs) { + sshc->readdir_filename = sshc->readdir_attrs->name; + sshc->readdir_longentry = sshc->readdir_attrs->longname; + sshc->readdir_len = strlen(sshc->readdir_filename); + + if(data->set.list_only) { + char *tmpLine; + + tmpLine = curl_maprintf("%s\n", sshc->readdir_filename); + if(!tmpLine) { + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->actualcode = CURLE_OUT_OF_MEMORY; + return SSH_ERROR; + } + result = Curl_client_write(data, CLIENTWRITE_BODY, + tmpLine, sshc->readdir_len + 1); + curlx_free(tmpLine); + + if(result) { + myssh_to(data, sshc, SSH_STOP); + sshc->actualcode = result; + return SSH_NO_ERROR; + } + } + else { + if(curlx_dyn_add(&sshc->readdir_buf, sshc->readdir_longentry)) { + sshc->actualcode = CURLE_OUT_OF_MEMORY; + myssh_to(data, sshc, SSH_STOP); + return SSH_ERROR; + } + + if((sshc->readdir_attrs->flags & SSH_FILEXFER_ATTR_PERMISSIONS) && + ((sshc->readdir_attrs->permissions & SSH_S_IFMT) == + SSH_S_IFLNK)) { + sshc->readdir_linkPath = curl_maprintf("%s%s", sshp->path, + sshc->readdir_filename); + + if(!sshc->readdir_linkPath) { + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->actualcode = CURLE_OUT_OF_MEMORY; + return SSH_ERROR; + } + + myssh_to(data, sshc, SSH_SFTP_READDIR_LINK); + return SSH_NO_ERROR; + } + myssh_to(data, sshc, SSH_SFTP_READDIR_BOTTOM); + return SSH_NO_ERROR; + } + } + else if(sftp_dir_eof(sshc->sftp_dir)) { + myssh_to(data, sshc, SSH_SFTP_READDIR_DONE); + } + else { + failf(data, "Could not open remote directory for reading: %s", + ssh_get_error(sshc->ssh_session)); + return myssh_to_SFTP_CLOSE(data, sshc); + } + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_READDIR_LINK(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(sshc->readdir_link_attrs) + sftp_attributes_free(sshc->readdir_link_attrs); + + sshc->readdir_link_attrs = sftp_lstat(sshc->sftp_session, + sshc->readdir_linkPath); + if(!sshc->readdir_link_attrs) { + failf(data, "Could not read symlink for reading: %s", + ssh_get_error(sshc->ssh_session)); + return myssh_to_SFTP_CLOSE(data, sshc); + } + + if(!sshc->readdir_link_attrs->name) { + sshc->readdir_tmp = sftp_readlink(sshc->sftp_session, + sshc->readdir_linkPath); + if(!sshc->readdir_tmp) + sshc->readdir_len = 0; + else + sshc->readdir_len = strlen(sshc->readdir_tmp); + sshc->readdir_longentry = NULL; + sshc->readdir_filename = sshc->readdir_tmp; + } + else { + sshc->readdir_len = strlen(sshc->readdir_link_attrs->name); + sshc->readdir_filename = sshc->readdir_link_attrs->name; + sshc->readdir_longentry = sshc->readdir_link_attrs->longname; + } + + curlx_safefree(sshc->readdir_linkPath); + + if(curlx_dyn_addf(&sshc->readdir_buf, " -> %s", sshc->readdir_filename)) { + /* Not using: + * return myssh_to_SFTP_CLOSE(data, sshc); + * + * as that assumes an sftp related error while + * assigning sshc->actualcode whereas the current + * error is curlx_dyn_addf() related. + */ + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->actualcode = CURLE_OUT_OF_MEMORY; + return SSH_ERROR; + } + + sftp_attributes_free(sshc->readdir_link_attrs); + sshc->readdir_link_attrs = NULL; + sshc->readdir_filename = NULL; + sshc->readdir_longentry = NULL; + + myssh_to(data, sshc, SSH_SFTP_READDIR_BOTTOM); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_READDIR_BOTTOM(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + CURLcode result; + + if(curlx_dyn_addn(&sshc->readdir_buf, "\n", 1)) + result = CURLE_OUT_OF_MEMORY; + else + result = Curl_client_write(data, CLIENTWRITE_BODY, + curlx_dyn_ptr(&sshc->readdir_buf), + curlx_dyn_len(&sshc->readdir_buf)); + + ssh_string_free_char(sshc->readdir_tmp); + sshc->readdir_tmp = NULL; + + if(result) { + myssh_to(data, sshc, SSH_STOP); + sshc->actualcode = result; + } + else + myssh_to(data, sshc, SSH_SFTP_READDIR); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_READDIR_DONE(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + sftp_closedir(sshc->sftp_dir); + sshc->sftp_dir = NULL; + + /* no data to transfer */ + Curl_xfer_setup_nop(data); + myssh_to(data, sshc, SSH_STOP); + return SSH_NO_ERROR; +} + +static void myssh_quote_error(struct Curl_easy *data, struct ssh_conn *sshc, + const char *cmd) +{ + if(cmd) + failf(data, "%s command failed: %s", cmd, + ssh_get_error(sshc->ssh_session)); + curlx_safefree(sshc->quote_path1); + curlx_safefree(sshc->quote_path2); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; +} + +static int myssh_in_SFTP_QUOTE_STATVFS(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + sftp_statvfs_t statvfs; + + statvfs = sftp_statvfs(sshc->sftp_session, sshc->quote_path1); + if(!statvfs && !sshc->acceptfail) { + myssh_quote_error(data, sshc, "statvfs"); + return SSH_OK; + } + else if(statvfs) { +#ifdef _MSC_VER +#define CURL_LIBSSH_VFS_SIZE_MASK "I64u" +#elif defined(__MINGW32__) && (__MINGW64_VERSION_MAJOR <= 6) +#define CURL_LIBSSH_VFS_SIZE_MASK "llu" +#else +#define CURL_LIBSSH_VFS_SIZE_MASK PRIu64 +#endif + CURLcode result = CURLE_OK; + char *tmp = curl_maprintf("statvfs:\n" + "f_bsize: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_frsize: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_blocks: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_bfree: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_bavail: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_files: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_ffree: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_favail: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_fsid: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_flag: %" CURL_LIBSSH_VFS_SIZE_MASK "\n" + "f_namemax: %" CURL_LIBSSH_VFS_SIZE_MASK "\n", + statvfs->f_bsize, statvfs->f_frsize, + statvfs->f_blocks, statvfs->f_bfree, + statvfs->f_bavail, statvfs->f_files, + statvfs->f_ffree, statvfs->f_favail, + statvfs->f_fsid, statvfs->f_flag, + statvfs->f_namemax); + sftp_statvfs_free(statvfs); + + if(!tmp) + result = CURLE_OUT_OF_MEMORY; + + if(!result) { + result = Curl_client_write(data, CLIENTWRITE_HEADER, tmp, strlen(tmp)); + curlx_free(tmp); + } + if(result) { + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + } + } + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return SSH_OK; +} + +static int myssh_auth_interactive(struct connectdata *conn, + struct ssh_conn *sshc) +{ + int rc; + int nprompts; + +restart: + switch(sshc->kbd_state) { + case 0: + rc = ssh_userauth_kbdint(sshc->ssh_session, NULL, NULL); + if(rc == SSH_AUTH_AGAIN) + return SSH_AGAIN; + + if(rc != SSH_AUTH_INFO) + return SSH_ERROR; + + nprompts = ssh_userauth_kbdint_getnprompts(sshc->ssh_session); + if(nprompts != 1) + return SSH_ERROR; + + rc = ssh_userauth_kbdint_setanswer(sshc->ssh_session, 0, + Curl_creds_passwd(conn->creds)); + if(rc < 0) + return SSH_ERROR; + + FALLTHROUGH(); + case 1: + sshc->kbd_state = 1; + + rc = ssh_userauth_kbdint(sshc->ssh_session, NULL, NULL); + if(rc == SSH_AUTH_AGAIN) + return SSH_AGAIN; + else if(rc == SSH_AUTH_SUCCESS) + rc = SSH_OK; + else if(rc == SSH_AUTH_INFO) { + nprompts = ssh_userauth_kbdint_getnprompts(sshc->ssh_session); + if(nprompts) + return SSH_ERROR; + + sshc->kbd_state = 2; + goto restart; + } + else + rc = SSH_ERROR; + break; + case 2: + sshc->kbd_state = 2; + + rc = ssh_userauth_kbdint(sshc->ssh_session, NULL, NULL); + if(rc == SSH_AUTH_AGAIN) + return SSH_AGAIN; + else if(rc == SSH_AUTH_SUCCESS) + rc = SSH_OK; + else + rc = SSH_ERROR; + + break; + default: + return SSH_ERROR; + } + + sshc->kbd_state = 0; + return rc; +} + +static void myssh_state_init(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + sshc->secondCreateDirs = 0; + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_OK; + +#if 0 + ssh_set_log_level(SSH_LOG_PROTOCOL); +#endif + + /* Set libssh to non-blocking, since everything internally is + non-blocking */ + ssh_set_blocking(sshc->ssh_session, 0); + + myssh_to(data, sshc, SSH_S_STARTUP); +} + +static void myssh_block2waitfor(struct connectdata *conn, + struct ssh_conn *sshc, + bool block) +{ + (void)conn; + if(block) { + int dir = ssh_get_poll_flags(sshc->ssh_session); + /* translate the libssh define bits into our own bit defines */ + sshc->waitfor = + ((dir & SSH_READ_PENDING) ? REQ_IO_RECV : 0) | + ((dir & SSH_WRITE_PENDING) ? REQ_IO_SEND : 0); + } + else + sshc->waitfor = 0; +} + +static int myssh_in_S_STARTUP(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + struct connectdata *conn = data->conn; + int rc = ssh_connect(sshc->ssh_session); + + myssh_block2waitfor(conn, sshc, (rc == SSH_AGAIN)); + if(rc == SSH_AGAIN) { + CURL_TRC_SSH(data, "connect -> EAGAIN"); + } + else if(rc != SSH_OK) { + failf(data, "Failure establishing ssh session"); + rc = myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + } + else + myssh_to(data, sshc, SSH_HOSTKEY); + + return rc; +} + +static int myssh_in_AUTHLIST(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc; + sshc->authed = FALSE; + + rc = ssh_userauth_none(sshc->ssh_session, NULL); + if(rc == SSH_AUTH_AGAIN) + return SSH_AGAIN; + + if(rc == SSH_AUTH_SUCCESS) { + sshc->authed = TRUE; + infof(data, "Authenticated with none"); + myssh_to(data, sshc, SSH_AUTH_DONE); + return rc; + } + else if(rc == SSH_AUTH_ERROR) { + rc = myssh_to_ERROR(data, sshc, CURLE_LOGIN_DENIED); + return rc; + } + + sshc->auth_methods = + (unsigned int)ssh_userauth_list(sshc->ssh_session, NULL); + if(sshc->auth_methods) + infof(data, "SSH authentication methods available: %s%s%s%s", + sshc->auth_methods & SSH_AUTH_METHOD_PUBLICKEY ? + "public key, " : "", + sshc->auth_methods & SSH_AUTH_METHOD_GSSAPI_MIC ? + "GSSAPI, " : "", + sshc->auth_methods & SSH_AUTH_METHOD_INTERACTIVE ? + "keyboard-interactive, " : "", + sshc->auth_methods & SSH_AUTH_METHOD_PASSWORD ? + "password" : ""); + /* For public key auth we need either the private key or + CURLSSH_AUTH_AGENT. */ + if((sshc->auth_methods & SSH_AUTH_METHOD_PUBLICKEY) && + (sshc->priv_key || (data->set.ssh_auth_types & CURLSSH_AUTH_AGENT))) { + myssh_to(data, sshc, SSH_AUTH_PKEY_INIT); + infof(data, "Authentication using SSH public key file"); + } + else if(sshc->auth_methods & SSH_AUTH_METHOD_GSSAPI_MIC) { + myssh_to(data, sshc, SSH_AUTH_GSSAPI); + } + else if(sshc->auth_methods & SSH_AUTH_METHOD_INTERACTIVE) { + myssh_to(data, sshc, SSH_AUTH_KEY_INIT); + } + else if(sshc->auth_methods & SSH_AUTH_METHOD_PASSWORD) { + myssh_to(data, sshc, SSH_AUTH_PASS_INIT); + } + else { /* unsupported authentication method */ + rc = myssh_to_ERROR(data, sshc, CURLE_LOGIN_DENIED); + } + return rc; +} + +static int myssh_in_AUTH_PKEY_INIT(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc; + if(!(data->set.ssh_auth_types & CURLSSH_AUTH_PUBLICKEY)) { + rc = myssh_to_GSSAPI_AUTH(data, sshc); + return rc; + } + + /* Two choices, (1) private key was given on CMD, + * (2) use the "default" keys. */ + if(sshc->priv_key) { + if(sshc->pubkey && !data->set.ssl.primary.key_passwd) { + rc = ssh_userauth_try_publickey(sshc->ssh_session, NULL, sshc->pubkey); + if(rc == SSH_AUTH_AGAIN) + return SSH_AGAIN; + + if(rc != SSH_OK) { + rc = myssh_to_GSSAPI_AUTH(data, sshc); + return rc; + } + } + + rc = ssh_pki_import_privkey_file(sshc->priv_key, + data->set.ssl.primary.key_passwd, NULL, + NULL, &sshc->privkey); + if(rc != SSH_OK) { + failf(data, "Could not load private key file %s", sshc->priv_key); + rc = myssh_to_ERROR(data, sshc, CURLE_LOGIN_DENIED); + return rc; + } + + myssh_to(data, sshc, SSH_AUTH_PKEY); + } + else { + rc = ssh_userauth_publickey_auto(sshc->ssh_session, NULL, + data->set.ssl.primary.key_passwd); + if(rc == SSH_AUTH_AGAIN) + return SSH_AGAIN; + + if(rc == SSH_AUTH_SUCCESS) { + rc = SSH_OK; + sshc->authed = TRUE; + infof(data, "Completed public key authentication"); + myssh_to(data, sshc, SSH_AUTH_DONE); + return rc; + } + + rc = myssh_to_GSSAPI_AUTH(data, sshc); + } + return rc; +} + +static int myssh_in_AUTH_PKEY(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = ssh_userauth_publickey(sshc->ssh_session, NULL, sshc->privkey); + if(rc == SSH_AUTH_AGAIN) + return SSH_AGAIN; + else if(rc == SSH_AUTH_SUCCESS) { + sshc->authed = TRUE; + infof(data, "Completed public key authentication"); + myssh_to(data, sshc, SSH_AUTH_DONE); + return SSH_OK; + } + else { + infof(data, "Failed public key authentication (rc: %d)", rc); + return myssh_to_GSSAPI_AUTH(data, sshc); + } +} + +static int myssh_in_AUTH_GSSAPI(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc; + if(!(data->set.ssh_auth_types & CURLSSH_AUTH_GSSAPI)) + return myssh_to_KEY_AUTH(data, sshc); + + rc = ssh_userauth_gssapi(sshc->ssh_session); + if(rc == SSH_AUTH_AGAIN) + return SSH_AGAIN; + + if(rc == SSH_AUTH_SUCCESS) { + sshc->authed = TRUE; + infof(data, "Completed gssapi authentication"); + myssh_to(data, sshc, SSH_AUTH_DONE); + return SSH_OK; + } + + return myssh_to_KEY_AUTH(data, sshc); +} + +static int myssh_in_AUTH_KEY_INIT(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(data->set.ssh_auth_types & CURLSSH_AUTH_KEYBOARD) { + myssh_to(data, sshc, SSH_AUTH_KEY); + return SSH_NO_ERROR; + } + return myssh_to_PASSWD_AUTH(data, sshc); +} + +static int myssh_in_AUTH_KEY(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + /* keyboard-interactive authentication */ + int rc = myssh_auth_interactive(data->conn, sshc); + if(rc == SSH_AGAIN) + return rc; + else if(rc == SSH_OK) { + sshc->authed = TRUE; + infof(data, "completed keyboard interactive authentication"); + myssh_to(data, sshc, SSH_AUTH_DONE); + return SSH_NO_ERROR; + } + else + return myssh_to_PASSWD_AUTH(data, sshc); +} + +static int myssh_in_AUTH_PASS_INIT(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(!(data->set.ssh_auth_types & CURLSSH_AUTH_PASSWORD)) + return myssh_to_ERROR(data, sshc, CURLE_LOGIN_DENIED); + myssh_to(data, sshc, SSH_AUTH_PASS); + return SSH_NO_ERROR; +} + +static int myssh_in_AUTH_PASS(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = ssh_userauth_password(sshc->ssh_session, NULL, + Curl_creds_passwd(data->conn->creds)); + if(rc == SSH_AUTH_AGAIN) + return SSH_AGAIN; + else if(rc == SSH_AUTH_SUCCESS) { + sshc->authed = TRUE; + infof(data, "Completed password authentication"); + myssh_to(data, sshc, SSH_AUTH_DONE); + return SSH_NO_ERROR; + } + return myssh_to_ERROR(data, sshc, CURLE_LOGIN_DENIED); +} + +static int myssh_in_AUTH_DONE(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + struct connectdata *conn = data->conn; + if(!sshc->authed) { + failf(data, "Authentication failure"); + return myssh_to_ERROR(data, sshc, CURLE_LOGIN_DENIED); + } + + /* At this point we have an authenticated ssh session. */ + infof(data, "Authentication complete"); + Curl_pgrsTime(data, TIMER_APPCONNECT); /* SSH is connected */ + conn->recv_idx = FIRSTSOCKET; + conn->send_idx = -1; + + if(conn->scheme->protocol == CURLPROTO_SFTP) { + myssh_to(data, sshc, SSH_SFTP_INIT); + return SSH_NO_ERROR; + } + infof(data, "SSH CONNECT phase done"); + myssh_to(data, sshc, SSH_STOP); + return SSH_NO_ERROR; +} + +static int myssh_in_UPLOAD_INIT(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + int flags; + int rc = 0; + + if(!sshp) + return myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + + if(data->state.resume_from) { + sftp_attributes attrs; + + if(data->state.resume_from < 0) { + attrs = sftp_stat(sshc->sftp_session, sshp->path); + if(attrs) { + curl_off_t size = attrs->size; + sftp_attributes_free(attrs); + if(size < 0) { + failf(data, "Bad file size (%" FMT_OFF_T ")", size); + rc = myssh_to_ERROR(data, sshc, CURLE_BAD_DOWNLOAD_RESUME); + return rc; + } + data->state.resume_from = size; + } + else { + data->state.resume_from = 0; + } + } + } + + if(data->set.remote_append) { + /* True append mode: create if nonexisting */ + flags = O_WRONLY | O_CREAT | O_APPEND; + } + else if(data->state.resume_from > 0) { + /* + * Resume MUST NOT use O_APPEND. Many SFTP servers/impls force all + * writes to EOF when O_APPEND is set, ignoring a prior seek(). + * Open write-only and seek to the resume offset instead. + */ + flags = O_WRONLY; + } + else + /* Clear file before writing (normal behavior) */ + flags = O_WRONLY | O_CREAT | O_TRUNC; + + if(sshc->sftp_file) + sftp_close(sshc->sftp_file); + sshc->sftp_file = + sftp_open(sshc->sftp_session, sshp->path, + flags, (mode_t)data->set.new_file_perms); + if(!sshc->sftp_file) { + int err = sftp_get_error(sshc->sftp_session); + + if((err == SSH_FX_NO_SUCH_FILE || + err == SSH_FX_FAILURE || + err == SSH_FX_NO_SUCH_PATH) && + data->set.ftp_create_missing_dirs && + (strlen(sshp->path) > 1)) { + /* try to create the path remotely */ + rc = 0; + sshc->secondCreateDirs = 1; + myssh_to(data, sshc, SSH_SFTP_CREATE_DIRS_INIT); + return rc; + } + else { + rc = myssh_to_SFTP_CLOSE(data, sshc); + return rc; + } + } + + /* If we have a restart point then we need to seek to the correct + position. Skip if in explicit remote append mode. */ + if(data->state.resume_from > 0 && !data->set.remote_append) { + int seekerr = CURL_SEEKFUNC_OK; + /* Let's read off the proper amount of bytes from the input. */ + if(data->set.seek_func) { + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_seek_func); + seekerr = data->set.seek_func(data->set.seek_client, + data->state.resume_from, SEEK_SET); + CURL_CBAPI_END(&guard); + } + + if(seekerr != CURL_SEEKFUNC_OK) { + curl_off_t passed = 0; + + if(seekerr != CURL_SEEKFUNC_CANTSEEK) { + failf(data, "Could not seek stream"); + rc = myssh_to_ERROR(data, sshc, CURLE_FTP_COULDNT_USE_REST); + return rc; + } + /* seekerr == CURL_SEEKFUNC_CANTSEEK (cannot seek to offset) */ + do { + char scratch[4 * 1024]; + size_t readthisamountnow = + (data->state.resume_from - passed > + (curl_off_t)sizeof(scratch)) ? + sizeof(scratch) : curlx_sotouz(data->state.resume_from - passed); + + size_t actuallyread = + data->state.fread_func(scratch, 1, + readthisamountnow, data->state.in); + + passed += actuallyread; + if((actuallyread == 0) || (actuallyread > readthisamountnow)) { + /* this checks for greater-than only to make sure that the + CURL_READFUNC_ABORT return code still aborts */ + failf(data, "Failed to read data"); + rc = myssh_to_ERROR(data, sshc, CURLE_FTP_COULDNT_USE_REST); + return rc; + } + } while(passed < data->state.resume_from); + } + + /* now, decrease the size of the read */ + if(data->state.infilesize > 0) { + if(data->state.resume_from > data->state.infilesize) { + failf(data, "Resume point beyond size"); + return myssh_to_ERROR(data, sshc, CURLE_BAD_FUNCTION_ARGUMENT); + } + data->state.infilesize -= data->state.resume_from; + data->req.size = data->state.infilesize; + Curl_pgrsSetUploadSize(data, data->state.infilesize); + } + + rc = sftp_seek64(sshc->sftp_file, data->state.resume_from); + if(rc) { + rc = myssh_to_SFTP_CLOSE(data, sshc); + return rc; + } + } + if(data->state.infilesize > 0) { + data->req.size = data->state.infilesize; + Curl_pgrsSetUploadSize(data, data->state.infilesize); + } + /* upload data */ + Curl_xfer_setup_send(data, FIRSTSOCKET); + + /* not set by Curl_xfer_setup to preserve io_flags */ + data->conn->recv_idx = FIRSTSOCKET; + + /* since we do not really wait for anything at this point, we want the + state machine to move on as soon as possible so we mark this as dirty */ + Curl_multi_mark_dirty(data); +#if LIBSSH_VERSION_INT > SSH_VERSION_INT(0, 11, 0) + sshc->sftp_send_state = 0; +#endif + myssh_to(data, sshc, SSH_STOP); + return rc; +} + +static int myssh_in_SFTP_DOWNLOAD_INIT(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + if(!sshp) + return myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + /* Work on getting the specified file */ + if(sshc->sftp_file) + sftp_close(sshc->sftp_file); + + sshc->sftp_file = sftp_open(sshc->sftp_session, sshp->path, + O_RDONLY, (mode_t)data->set.new_file_perms); + if(!sshc->sftp_file) { + failf(data, "Could not open remote file for reading: %s", + ssh_get_error(sshc->ssh_session)); + + return myssh_to_SFTP_CLOSE(data, sshc); + } + sftp_file_set_nonblocking(sshc->sftp_file); + myssh_to(data, sshc, SSH_SFTP_DOWNLOAD_STAT); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_DOWNLOAD_STAT(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + curl_off_t size; + int rc = 0; + sftp_attributes attrs = sftp_fstat(sshc->sftp_file); + if(!attrs || + !(attrs->flags & SSH_FILEXFER_ATTR_SIZE) || + (attrs->size == 0)) { + /* + * sftp_fstat did not return an error, so maybe the server + * does not support stat() + * OR the server does not return a file size with a stat() + * OR file size is 0 + */ + data->req.size = -1; + data->req.maxdownload = -1; + Curl_pgrsSetDownloadSize(data, -1); + size = 0; + if(attrs) + sftp_attributes_free(attrs); + } + else { + size = attrs->size; + + sftp_attributes_free(attrs); + + if(size < 0) { + failf(data, "Bad file size (%" FMT_OFF_T ")", size); + return myssh_to_ERROR(data, sshc, CURLE_BAD_DOWNLOAD_RESUME); + } + if(data->state.use_range) { + curl_off_t from; + CURLcode result = Curl_ssh_range(data, data->state.range, size, + &from, &size); + if(result) + return myssh_to_ERROR(data, sshc, result); + + rc = sftp_seek64(sshc->sftp_file, from); + if(rc) + return myssh_to_SFTP_CLOSE(data, sshc); + } + data->req.size = size; + data->req.maxdownload = size; + Curl_pgrsSetDownloadSize(data, size); + } + + /* We can resume if we can seek to the resume position */ + if(data->state.resume_from) { + if(data->state.resume_from < 0) { + /* We are supposed to download the last abs(from) bytes */ + if(size < -data->state.resume_from) { + failf(data, "Offset (%" FMT_OFF_T ") was beyond file size (%" + FMT_OFF_T ")", data->state.resume_from, size); + return myssh_to_ERROR(data, sshc, CURLE_BAD_DOWNLOAD_RESUME); + } + /* download from where? */ + data->state.resume_from += size; + } + else { + if(size < data->state.resume_from) { + failf(data, "Offset (%" FMT_OFF_T + ") was beyond file size (%" FMT_OFF_T ")", + data->state.resume_from, size); + return myssh_to_ERROR(data, sshc, CURLE_BAD_DOWNLOAD_RESUME); + } + } + /* Now store the number of bytes we are expected to download */ + data->req.size = size - data->state.resume_from; + data->req.maxdownload = size - data->state.resume_from; + Curl_pgrsSetDownloadSize(data, size - data->state.resume_from); + + rc = sftp_seek64(sshc->sftp_file, data->state.resume_from); + if(rc) + return myssh_to_SFTP_CLOSE(data, sshc); + } + + /* Setup the actual download */ + if(data->req.size == 0) { + /* no data to transfer */ + Curl_xfer_setup_nop(data); + infof(data, "File already completely downloaded"); + myssh_to(data, sshc, SSH_STOP); + return rc; + } + Curl_xfer_setup_recv(data, FIRSTSOCKET, data->req.size); + + /* not set by Curl_xfer_setup to preserve io_flags */ + data->conn->send_idx = 0; + + sshc->sftp_recv_state = 0; + myssh_to(data, sshc, SSH_STOP); + + return rc; +} + +static int myssh_in_SFTP_CLOSE(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + if(!sshp) + return myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + if(sshc->sftp_file) { + sftp_close(sshc->sftp_file); + sshc->sftp_file = NULL; + } + curlx_safefree(sshp->path); + + CURL_TRC_SSH(data, "SFTP DONE done"); + + /* Check if nextstate is set and move .nextstate could be POSTQUOTE_INIT + After nextstate is executed, the control should come back to + SSH_SFTP_CLOSE to pass the correct result back */ + if(sshc->nextstate != SSH_NO_STATE && + sshc->nextstate != SSH_SFTP_CLOSE) { + myssh_to(data, sshc, sshc->nextstate); + sshc->nextstate = SSH_SFTP_CLOSE; + } + else { + myssh_to(data, sshc, SSH_STOP); + } + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_SHUTDOWN(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + /* during times we get here due to a broken transfer and then the + sftp_handle might not have been taken down so make sure that is done + before we proceed */ + ssh_set_blocking(sshc->ssh_session, 0); +#if LIBSSH_VERSION_INT > SSH_VERSION_INT(0, 11, 0) + SFTP_AIO_FREE(sshc->sftp_send_aio); + SFTP_AIO_FREE(sshc->sftp_recv_aio); +#endif + + if(sshc->sftp_file) { + sftp_close(sshc->sftp_file); + sshc->sftp_file = NULL; + } + + if(sshc->sftp_session) { + sftp_free(sshc->sftp_session); + sshc->sftp_session = NULL; + } + + SSH_STRING_FREE_CHAR(sshc->homedir); + + myssh_to(data, sshc, SSH_SESSION_DISCONNECT); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_INIT(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc; + ssh_set_blocking(sshc->ssh_session, 1); + + sshc->sftp_session = sftp_new(sshc->ssh_session); + if(!sshc->sftp_session) { + failf(data, "Failure initializing sftp session: %s", + ssh_get_error(sshc->ssh_session)); + return myssh_to_ERROR(data, sshc, CURLE_COULDNT_CONNECT); + } + + rc = sftp_init(sshc->sftp_session); + if(rc != SSH_OK) { + failf(data, "Failure initializing sftp session: %s", + ssh_get_error(sshc->ssh_session)); + return myssh_to_ERROR(data, sshc, sftp_error_to_CURLE(SSH_FX_FAILURE)); + } + myssh_to(data, sshc, SSH_SFTP_REALPATH); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_REALPATH(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + /* Get the "home" directory */ + sshc->homedir = sftp_canonicalize_path(sshc->sftp_session, "."); + if(!sshc->homedir) + return myssh_to_ERROR(data, sshc, CURLE_COULDNT_CONNECT); + + curlx_free(data->state.most_recent_ftp_entrypath); + data->state.most_recent_ftp_entrypath = curlx_strdup(sshc->homedir); + if(!data->state.most_recent_ftp_entrypath) + return myssh_to_ERROR(data, sshc, CURLE_OUT_OF_MEMORY); + + /* This is the last step in the SFTP connect phase. Do note that while + we get the homedir here, we get the "workingpath" in the DO action + since the homedir remains the same between request but the + working path does not. */ + CURL_TRC_SSH(data, "CONNECT phase done"); + myssh_to(data, sshc, SSH_STOP); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_QUOTE_INIT(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + CURLcode result; + + if(!sshp) + return myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + + result = Curl_getworkingpath(data, sshc->homedir, &sshp->path); + if(result) { + sshc->actualcode = result; + myssh_to(data, sshc, SSH_STOP); + } + else if(data->set.quote) { + infof(data, "Sending quote commands"); + sshc->quote_item = data->set.quote; + myssh_to(data, sshc, SSH_SFTP_QUOTE); + } + else + myssh_to(data, sshc, SSH_SFTP_GETINFO); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_POSTQUOTE_INIT(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(data->set.postquote) { + infof(data, "Sending quote commands"); + sshc->quote_item = data->set.postquote; + myssh_to(data, sshc, SSH_SFTP_QUOTE); + } + else { + myssh_to(data, sshc, SSH_STOP); + } + return SSH_NO_ERROR; +} + +static int quote_error(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + failf(data, "Suspicious data after the command line"); + curlx_safefree(sshc->quote_path1); + curlx_safefree(sshc->quote_path2); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_QUOTE(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + const char *cp; + CURLcode result; + + /* + * Support some of the "FTP" commands + */ + const char *cmd = sshc->quote_item->data; + sshc->acceptfail = FALSE; + + if(!sshp) + return myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + + /* if a command starts with an asterisk, which a legal SFTP command never + can, the command is allowed to fail without it causing any + aborts or cancels etc. It causes libcurl to act as if the command + is successful, whatever the server responds. */ + + if(cmd[0] == '*') { + cmd++; + sshc->acceptfail = TRUE; + } + + if(curl_strequal("pwd", cmd)) { + /* output debug output if that is requested */ + char *tmp = curl_maprintf("257 \"%s\" is current directory.\n", + sshp->path); + if(!tmp) { + sshc->actualcode = CURLE_OUT_OF_MEMORY; + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + return SSH_NO_ERROR; + } + Curl_debug(data, CURLINFO_HEADER_OUT, "PWD\n", 4); + Curl_debug(data, CURLINFO_HEADER_IN, tmp, strlen(tmp)); + + /* this sends an FTP-like "header" to the header callback so that + the current directory can be read similar to how it is read when + using ordinary FTP. */ + result = Curl_client_write(data, CLIENTWRITE_HEADER, tmp, strlen(tmp)); + curlx_free(tmp); + if(result) { + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + } + else + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return SSH_NO_ERROR; + } + + /* + * the arguments following the command must be separated from the + * command with a space so we can check for it unconditionally + */ + cp = strchr(cmd, ' '); + if(!cp) { + failf(data, "Syntax error in SFTP command. Supply parameter(s)"); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + return SSH_NO_ERROR; + } + + /* + * also, every command takes at least one argument so we get that + * first argument right now + */ + result = Curl_get_pathname(&cp, &sshc->quote_path1, sshc->homedir); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + failf(data, "Out of memory"); + else + failf(data, "Syntax error: Bad first parameter"); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + return SSH_NO_ERROR; + } + + /* + * SFTP is a binary protocol, so we do not send text commands + * to the server. Instead, we scan for commands used by + * OpenSSH's sftp program and call the appropriate libssh + * functions. + */ + if(!strncmp(cmd, "chgrp ", 6) || + !strncmp(cmd, "chmod ", 6) || + !strncmp(cmd, "chown ", 6) || + !strncmp(cmd, "atime ", 6) || + !strncmp(cmd, "mtime ", 6)) { + /* attribute change */ + + /* sshc->quote_path1 contains the mode to set */ + /* get the destination */ + result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + failf(data, "Out of memory"); + else + failf(data, "Syntax error in chgrp/chmod/chown/atime/mtime: " + "Bad second parameter"); + curlx_safefree(sshc->quote_path1); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + return SSH_NO_ERROR; + } + if(*cp) + return quote_error(data, sshc); + sshc->quote_attrs = NULL; + myssh_to(data, sshc, SSH_SFTP_QUOTE_STAT); + return SSH_NO_ERROR; + } + if(!strncmp(cmd, "ln ", 3) || + !strncmp(cmd, "symlink ", 8)) { + /* symbolic linking */ + /* sshc->quote_path1 is the source */ + /* get the destination */ + result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + failf(data, "Out of memory"); + else + failf(data, "Syntax error in ln/symlink: Bad second parameter"); + curlx_safefree(sshc->quote_path1); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + return SSH_NO_ERROR; + } + if(*cp) + return quote_error(data, sshc); + myssh_to(data, sshc, SSH_SFTP_QUOTE_SYMLINK); + return SSH_NO_ERROR; + } + else if(!strncmp(cmd, "mkdir ", 6)) { + if(*cp) + return quote_error(data, sshc); + /* create directory */ + myssh_to(data, sshc, SSH_SFTP_QUOTE_MKDIR); + return SSH_NO_ERROR; + } + else if(!strncmp(cmd, "rename ", 7)) { + /* rename file */ + /* first param is the source path */ + /* second param is the dest. path */ + result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); + if(result) { + if(result == CURLE_OUT_OF_MEMORY) + failf(data, "Out of memory"); + else + failf(data, "Syntax error in rename: Bad second parameter"); + curlx_safefree(sshc->quote_path1); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + return SSH_NO_ERROR; + } + if(*cp) + return quote_error(data, sshc); + myssh_to(data, sshc, SSH_SFTP_QUOTE_RENAME); + return SSH_NO_ERROR; + } + else if(!strncmp(cmd, "rmdir ", 6)) { + /* delete directory */ + if(*cp) + return quote_error(data, sshc); + myssh_to(data, sshc, SSH_SFTP_QUOTE_RMDIR); + return SSH_NO_ERROR; + } + else if(!strncmp(cmd, "rm ", 3)) { + if(*cp) + return quote_error(data, sshc); + myssh_to(data, sshc, SSH_SFTP_QUOTE_UNLINK); + return SSH_NO_ERROR; + } +#ifdef HAS_STATVFS_SUPPORT + else if(!strncmp(cmd, "statvfs ", 8)) { + if(*cp) + return quote_error(data, sshc); + myssh_to(data, sshc, SSH_SFTP_QUOTE_STATVFS); + return SSH_NO_ERROR; + } +#endif + + failf(data, "Unknown SFTP command"); + curlx_safefree(sshc->quote_path1); + curlx_safefree(sshc->quote_path2); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_NEXT_QUOTE(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + curlx_safefree(sshc->quote_path1); + curlx_safefree(sshc->quote_path2); + + sshc->quote_item = sshc->quote_item->next; + + if(sshc->quote_item) { + myssh_to(data, sshc, SSH_SFTP_QUOTE); + } + else { + if(sshc->nextstate != SSH_NO_STATE) { + myssh_to(data, sshc, sshc->nextstate); + sshc->nextstate = SSH_NO_STATE; + } + else { + myssh_to(data, sshc, SSH_SFTP_GETINFO); + } + } + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_QUOTE_STAT(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + const char *cmd = sshc->quote_item->data; + sshc->acceptfail = FALSE; + + /* if a command starts with an asterisk, which a legal SFTP command never + can, the command is allowed to fail without it causing any + aborts or cancels etc. It causes libcurl to act as if the command + is successful, whatever the server responds. */ + + if(cmd[0] == '*') { + cmd++; + sshc->acceptfail = TRUE; + } + + /* We read the file attributes, store them in sshc->quote_attrs + * and modify them accordingly to command. Then we switch to + * QUOTE_SETSTAT state to write new ones. + */ + + if(sshc->quote_attrs) + sftp_attributes_free(sshc->quote_attrs); + sshc->quote_attrs = sftp_stat(sshc->sftp_session, sshc->quote_path2); + if(!sshc->quote_attrs) { + failf(data, "Attempt to get SFTP stats failed: %d", + sftp_get_error(sshc->sftp_session)); + myssh_quote_error(data, sshc, NULL); + return SSH_NO_ERROR; + } + + /* Now set the new attributes... */ + if(!strncmp(cmd, "chgrp", 5)) { + const char *p = sshc->quote_path1; + curl_off_t gid; + if(curlx_str_number(&p, &gid, UINT_MAX)) { + failf(data, "Syntax error: chgrp gid not a number"); + myssh_quote_error(data, sshc, NULL); + return SSH_NO_ERROR; + } + sshc->quote_attrs->gid = (uint32_t)gid; + sshc->quote_attrs->flags |= SSH_FILEXFER_ATTR_UIDGID; + } + else if(!strncmp(cmd, "chmod", 5)) { + curl_off_t perms; + const char *p = sshc->quote_path1; + if(curlx_str_octal(&p, &perms, 07777)) { + failf(data, "Syntax error: chmod permissions not a number"); + myssh_quote_error(data, sshc, NULL); + return SSH_NO_ERROR; + } + sshc->quote_attrs->permissions = (mode_t)perms; + sshc->quote_attrs->flags |= SSH_FILEXFER_ATTR_PERMISSIONS; + } + else if(!strncmp(cmd, "chown", 5)) { + const char *p = sshc->quote_path1; + curl_off_t uid; + if(curlx_str_number(&p, &uid, UINT_MAX)) { + failf(data, "Syntax error: chown uid not a number"); + myssh_quote_error(data, sshc, NULL); + return SSH_NO_ERROR; + } + sshc->quote_attrs->uid = (uint32_t)uid; + sshc->quote_attrs->flags |= SSH_FILEXFER_ATTR_UIDGID; + } + else if(!strncmp(cmd, "atime", 5) || + !strncmp(cmd, "mtime", 5)) { + time_t date; + bool fail = FALSE; + if(Curl_getdate_capped(sshc->quote_path1, &date)) { + failf(data, "incorrect date format for %.*s", 5, cmd); + fail = TRUE; + } +#if SIZEOF_TIME_T > 4 + else if(date > 0xffffffff) { + failf(data, "date overflow"); + fail = TRUE; /* avoid setting a capped time */ + } +#endif + if(fail) { + myssh_quote_error(data, sshc, NULL); + return SSH_NO_ERROR; + } + if(!strncmp(cmd, "atime", 5)) + sshc->quote_attrs->atime = (uint32_t)date; + else /* mtime */ + sshc->quote_attrs->mtime = (uint32_t)date; + + sshc->quote_attrs->flags |= SSH_FILEXFER_ATTR_ACMODTIME; + } + + /* Now send the completed structure... */ + myssh_to(data, sshc, SSH_SFTP_QUOTE_SETSTAT); + return SSH_NO_ERROR; +} + +static void conn_forget_socket(struct Curl_easy *data, int8_t sockindex) +{ + struct connectdata *conn = data->conn; + if(conn && CONN_SOCK_IDX_VALID(sockindex)) { + struct Curl_cfilter *cf = conn->cfilter[sockindex]; + if(cf) + (void)Curl_conn_cf_cntrl(cf, data, TRUE, CF_CTRL_FORGET_SOCKET, 0, NULL); + fake_sclose(conn->sock[sockindex]); + conn->sock[sockindex] = CURL_SOCKET_BAD; + } +} + +static void myssh_SESSION_DISCONNECT(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + /* during weird times when we have been prematurely aborted, the channel + is still alive when we reach this state and we MUST kill the channel + properly first */ + if(sshc->scp_session) { + ssh_scp_free(sshc->scp_session); + sshc->scp_session = NULL; + } + + if(sshc->sftp_file) { + sftp_close(sshc->sftp_file); + sshc->sftp_file = NULL; + } + if(sshc->sftp_session) { + sftp_free(sshc->sftp_session); + sshc->sftp_session = NULL; + } + + ssh_disconnect(sshc->ssh_session); + if(!ssh_version(SSH_VERSION_INT(0, 10, 0))) { + /* conn->sock[FIRSTSOCKET] is closed by ssh_disconnect behind our back, + tell the connection to forget about it. This libssh + bug is fixed in 0.10.0. */ + conn_forget_socket(data, FIRSTSOCKET); + } + + SSH_STRING_FREE_CHAR(sshc->homedir); + + myssh_to(data, sshc, SSH_SESSION_FREE); +} + +static int myssh_SSH_SCP_DOWNLOAD(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + curl_off_t bytecount; + int rc = ssh_scp_pull_request(sshc->scp_session); + if(rc != SSH_SCP_REQUEST_NEWFILE) { + const char *err_msg = ssh_get_error(sshc->ssh_session); + failf(data, "%s", err_msg); + return myssh_to_ERROR(data, sshc, CURLE_REMOTE_FILE_NOT_FOUND); + } + + /* download data */ + bytecount = ssh_scp_request_get_size(sshc->scp_session); + data->req.maxdownload = bytecount; + Curl_xfer_setup_recv(data, FIRSTSOCKET, bytecount); + + /* not set by Curl_xfer_setup to preserve io_flags */ + data->conn->send_idx = 0; + + myssh_to(data, sshc, SSH_STOP); + return 0; +} + +static int myssh_in_TRANS_INIT(struct Curl_easy *data, struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + CURLcode result; + int rc = 0; + if(!sshp) + return myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + + result = Curl_getworkingpath(data, sshc->homedir, &sshp->path); + if(result) { + sshc->actualcode = result; + myssh_to(data, sshc, SSH_STOP); + return 0; + } + + /* Functions from the SCP subsystem cannot handle/return SSH_AGAIN */ + ssh_set_blocking(sshc->ssh_session, 1); + + if(data->state.upload) { + if(data->state.infilesize < 0) { + failf(data, "SCP requires a known file size for upload"); + return myssh_to_ERROR(data, sshc, CURLE_UPLOAD_FAILED); + } + + sshc->scp_session = + ssh_scp_new(sshc->ssh_session, SSH_SCP_WRITE, sshp->path); + myssh_to(data, sshc, SSH_SCP_UPLOAD_INIT); + } + else { + sshc->scp_session = + ssh_scp_new(sshc->ssh_session, SSH_SCP_READ, sshp->path); + myssh_to(data, sshc, SSH_SCP_DOWNLOAD_INIT); + } + + if(!sshc->scp_session) { + const char *err_msg = ssh_get_error(sshc->ssh_session); + failf(data, "%s", err_msg); + rc = myssh_to_ERROR(data, sshc, CURLE_UPLOAD_FAILED); + } + return rc; +} + +static void sshc_cleanup(struct ssh_conn *sshc) +{ + if(sshc->initialized) { + if(sshc->sftp_file) { + sftp_close(sshc->sftp_file); + sshc->sftp_file = NULL; + } + if(sshc->sftp_session) { + sftp_free(sshc->sftp_session); + sshc->sftp_session = NULL; + } + if(sshc->ssh_session) { + ssh_free(sshc->ssh_session); + sshc->ssh_session = NULL; + } + + /* worst-case scenario cleanup */ + DEBUGASSERT(!sshc->ssh_session); + DEBUGASSERT(!sshc->scp_session); + + if(sshc->readdir_tmp) { + ssh_string_free_char(sshc->readdir_tmp); + sshc->readdir_tmp = NULL; + } + if(sshc->quote_attrs) { + sftp_attributes_free(sshc->quote_attrs); + sshc->quote_attrs = NULL; + } + if(sshc->readdir_attrs) { + sftp_attributes_free(sshc->readdir_attrs); + sshc->readdir_attrs = NULL; + } + if(sshc->readdir_link_attrs) { + sftp_attributes_free(sshc->readdir_link_attrs); + sshc->readdir_link_attrs = NULL; + } + if(sshc->privkey) { + ssh_key_free(sshc->privkey); + sshc->privkey = NULL; + } + if(sshc->pubkey) { + ssh_key_free(sshc->pubkey); + sshc->pubkey = NULL; + } + + curlx_safefree(sshc->pub_key); + curlx_safefree(sshc->priv_key); + curlx_safefree(sshc->quote_path1); + curlx_safefree(sshc->quote_path2); + curlx_dyn_free(&sshc->readdir_buf); + curlx_safefree(sshc->readdir_linkPath); + SSH_STRING_FREE_CHAR(sshc->homedir); + sshc->initialized = FALSE; + } +} + +static int myssh_in_SFTP_QUOTE_SETSTAT(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = sftp_setstat(sshc->sftp_session, sshc->quote_path2, + sshc->quote_attrs); + if(rc == SSH_AGAIN) + return rc; + if(rc && !sshc->acceptfail) { + myssh_quote_error(data, sshc, "setstat"); + return rc; + } + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_QUOTE_SYMLINK(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = sftp_symlink(sshc->sftp_session, sshc->quote_path2, + sshc->quote_path1); + if(rc == SSH_AGAIN) + return rc; + if(rc && !sshc->acceptfail) { + myssh_quote_error(data, sshc, "symlink"); + return rc; + } + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_QUOTE_MKDIR(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = sftp_mkdir(sshc->sftp_session, sshc->quote_path1, + (mode_t)data->set.new_directory_perms); + if(rc == SSH_AGAIN) + return rc; + if(rc && !sshc->acceptfail) { + myssh_quote_error(data, sshc, "mkdir"); + return rc; + } + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_QUOTE_RENAME(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = sftp_rename(sshc->sftp_session, sshc->quote_path1, + sshc->quote_path2); + if(rc == SSH_AGAIN) + return rc; + if(rc && !sshc->acceptfail) { + myssh_quote_error(data, sshc, "rename"); + return rc; + } + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_QUOTE_RMDIR(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = sftp_rmdir(sshc->sftp_session, sshc->quote_path1); + if(rc == SSH_AGAIN) + return rc; + if(rc && !sshc->acceptfail) { + myssh_quote_error(data, sshc, "rmdir"); + return rc; + } + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_QUOTE_UNLINK(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = sftp_unlink(sshc->sftp_session, sshc->quote_path1); + if(rc == SSH_AGAIN) + return rc; + if(rc && !sshc->acceptfail) { + myssh_quote_error(data, sshc, "rm"); + return rc; + } + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_GETINFO(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(data->set.get_filetime) + myssh_to(data, sshc, SSH_SFTP_FILETIME); + else + myssh_to(data, sshc, SSH_SFTP_TRANS_INIT); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_FILETIME(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + sftp_attributes attrs; + if(!sshp) + return myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + + attrs = sftp_stat(sshc->sftp_session, sshp->path); + if(attrs) { + data->info.filetime = attrs->mtime; + sftp_attributes_free(attrs); + } + + myssh_to(data, sshc, SSH_SFTP_TRANS_INIT); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_TRANS_INIT(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + if(!sshp) + return myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + if(data->state.upload) + myssh_to(data, sshc, SSH_SFTP_UPLOAD_INIT); + else { + size_t path_len = strlen(sshp->path); + + if(path_len && sshp->path[path_len - 1] == '/') + myssh_to(data, sshc, SSH_SFTP_READDIR_INIT); + else + myssh_to(data, sshc, SSH_SFTP_DOWNLOAD_INIT); + } + + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_CREATE_DIRS_INIT(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + if(!sshp) + return myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + + if(strlen(sshp->path) > 1) { + sshc->slash_pos = sshp->path + 1; /* ignore the leading '/' */ + myssh_to(data, sshc, SSH_SFTP_CREATE_DIRS); + } + else { + myssh_to(data, sshc, SSH_SFTP_UPLOAD_INIT); + } + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_CREATE_DIRS(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + if(!sshp) + return myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + + sshc->slash_pos = strchr(sshc->slash_pos, '/'); + if(sshc->slash_pos) { + *sshc->slash_pos = 0; + + infof(data, "Creating directory '%s'", sshp->path); + myssh_to(data, sshc, SSH_SFTP_CREATE_DIRS_MKDIR); + return SSH_NO_ERROR; + } + myssh_to(data, sshc, SSH_SFTP_UPLOAD_INIT); + return SSH_NO_ERROR; +} + +static int myssh_in_SFTP_CREATE_DIRS_MKDIR(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + int rc; + int err; + /* 'mode' - parameter is preliminary - default to 0644 */ + if(!sshp) + return myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + + rc = sftp_mkdir(sshc->sftp_session, sshp->path, + (mode_t)data->set.new_directory_perms); + if(rc == SSH_AGAIN) + return rc; + *sshc->slash_pos = '/'; + ++sshc->slash_pos; + if(rc < 0) { + /* + * Abort if failure was not that the directory already + * exists or the permission was denied (creation might + * succeed further down the path) - retry on unspecific + * FAILURE also + */ + err = sftp_get_error(sshc->sftp_session); + if((err != SSH_FX_FILE_ALREADY_EXISTS) && + (err != SSH_FX_FAILURE) && + (err != SSH_FX_PERMISSION_DENIED)) { + return myssh_to_SFTP_CLOSE(data, sshc); + } + rc = 0; /* clear rc and continue */ + } + myssh_to(data, sshc, SSH_SFTP_CREATE_DIRS); + return rc; +} + +static int myssh_in_SCP_UPLOAD_INIT(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + int rc; + if(!sshp) + return myssh_to_ERROR(data, sshc, CURLE_FAILED_INIT); + + rc = ssh_scp_init(sshc->scp_session); + if(rc != SSH_OK) { + const char *err_msg = ssh_get_error(sshc->ssh_session); + failf(data, "%s", err_msg); + return myssh_to_ERROR(data, sshc, CURLE_UPLOAD_FAILED); + } + + rc = ssh_scp_push_file64(sshc->scp_session, sshp->path, + (uint64_t)data->state.infilesize, + (int)data->set.new_file_perms); + + if(rc != SSH_OK) { + const char *err_msg = ssh_get_error(sshc->ssh_session); + failf(data, "%s", err_msg); + return myssh_to_ERROR(data, sshc, CURLE_UPLOAD_FAILED); + } + + /* upload data */ + Curl_xfer_setup_send(data, FIRSTSOCKET); + + /* not set by Curl_xfer_setup to preserve io_flags */ + data->conn->recv_idx = FIRSTSOCKET; + + myssh_to(data, sshc, SSH_STOP); + return SSH_NO_ERROR; +} + +static int myssh_in_SCP_DOWNLOAD_INIT(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = ssh_scp_init(sshc->scp_session); + if(rc != SSH_OK) { + const char *err_msg = ssh_get_error(sshc->ssh_session); + failf(data, "%s", err_msg); + return myssh_to_ERROR(data, sshc, + CURLE_COULDNT_CONNECT); + } + myssh_to(data, sshc, SSH_SCP_DOWNLOAD); + return SSH_NO_ERROR; +} + +static int myssh_in_SCP_DONE(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(data->state.upload) + myssh_to(data, sshc, SSH_SCP_SEND_EOF); + else + myssh_to(data, sshc, SSH_SCP_CHANNEL_FREE); + return SSH_NO_ERROR; +} + +static int myssh_in_SCP_SEND_EOF(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(sshc->scp_session) { + int rc = ssh_scp_close(sshc->scp_session); + if(rc == SSH_AGAIN) { + /* Currently the ssh_scp_close handles waiting for + * EOF in blocking way. + */ + return SSH_AGAIN; + } + if(rc != SSH_OK) { + infof(data, + "Failed to close libssh scp channel: %s", + ssh_get_error(sshc->ssh_session)); + } + } + + myssh_to(data, sshc, SSH_SCP_CHANNEL_FREE); + return SSH_NO_ERROR; +} + +static int myssh_in_SCP_CHANNEL_FREE(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(sshc->scp_session) { + ssh_scp_free(sshc->scp_session); + sshc->scp_session = NULL; + } + CURL_TRC_SSH(data, "SCP DONE phase complete"); + + ssh_set_blocking(sshc->ssh_session, 0); + + myssh_to(data, sshc, SSH_SESSION_DISCONNECT); + return SSH_NO_ERROR; +} + +static CURLcode myssh_in_SESSION_FREE(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + CURLcode result; + sshc_cleanup(sshc); + /* the code we are about to return */ + result = sshc->actualcode; + memset(sshc, 0, sizeof(struct ssh_conn)); + connclose(data->conn); + sshc->state = SSH_SESSION_FREE; /* current */ + sshc->nextstate = SSH_NO_STATE; + myssh_to(data, sshc, SSH_STOP); + return result; +} + +/* + * myssh_statemachine() runs the SSH state machine as far as it can without + * blocking and without reaching the end. The data the pointer 'block' points + * to is set to TRUE if the libssh function returns SSH_AGAIN + * meaning it wants to be called again when the socket is ready + */ +static CURLcode myssh_statemachine(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool *block) +{ + CURLcode result = CURLE_OK; + int rc = SSH_NO_ERROR; + + *block = FALSE; /* we are not blocking by default */ + do { + + switch(sshc->state) { + case SSH_INIT: + myssh_state_init(data, sshc); + FALLTHROUGH(); + case SSH_S_STARTUP: + rc = myssh_in_S_STARTUP(data, sshc); + if(rc) + break; + FALLTHROUGH(); + case SSH_HOSTKEY: + rc = myssh_is_known(data, sshc); + if(rc != SSH_OK) { + rc = myssh_to_ERROR(data, sshc, CURLE_PEER_FAILED_VERIFICATION); + break; + } + myssh_to(data, sshc, SSH_AUTHLIST); + FALLTHROUGH(); + case SSH_AUTHLIST: + rc = myssh_in_AUTHLIST(data, sshc); + break; + case SSH_AUTH_PKEY_INIT: + rc = myssh_in_AUTH_PKEY_INIT(data, sshc); + break; + case SSH_AUTH_PKEY: + rc = myssh_in_AUTH_PKEY(data, sshc); + break; + case SSH_AUTH_GSSAPI: + rc = myssh_in_AUTH_GSSAPI(data, sshc); + break; + case SSH_AUTH_KEY_INIT: + rc = myssh_in_AUTH_KEY_INIT(data, sshc); + break; + case SSH_AUTH_KEY: + rc = myssh_in_AUTH_KEY(data, sshc); + break; + case SSH_AUTH_PASS_INIT: + rc = myssh_in_AUTH_PASS_INIT(data, sshc); + break; + case SSH_AUTH_PASS: + rc = myssh_in_AUTH_PASS(data, sshc); + break; + case SSH_AUTH_DONE: + rc = myssh_in_AUTH_DONE(data, sshc); + break; + case SSH_SFTP_INIT: + rc = myssh_in_SFTP_INIT(data, sshc); + break; + case SSH_SFTP_REALPATH: + rc = myssh_in_SFTP_REALPATH(data, sshc); + break; + case SSH_SFTP_QUOTE_INIT: + rc = myssh_in_SFTP_QUOTE_INIT(data, sshc, sshp); + break; + case SSH_SFTP_POSTQUOTE_INIT: + rc = myssh_in_SFTP_POSTQUOTE_INIT(data, sshc); + break; + case SSH_SFTP_QUOTE: + rc = myssh_in_SFTP_QUOTE(data, sshc, sshp); + break; + case SSH_SFTP_NEXT_QUOTE: + rc = myssh_in_SFTP_NEXT_QUOTE(data, sshc); + break; + case SSH_SFTP_QUOTE_STAT: + rc = myssh_in_SFTP_QUOTE_STAT(data, sshc); + break; + case SSH_SFTP_QUOTE_SETSTAT: + rc = myssh_in_SFTP_QUOTE_SETSTAT(data, sshc); + break; + case SSH_SFTP_QUOTE_SYMLINK: + rc = myssh_in_SFTP_QUOTE_SYMLINK(data, sshc); + break; + case SSH_SFTP_QUOTE_MKDIR: + rc = myssh_in_SFTP_QUOTE_MKDIR(data, sshc); + break; + case SSH_SFTP_QUOTE_RENAME: + rc = myssh_in_SFTP_QUOTE_RENAME(data, sshc); + break; + case SSH_SFTP_QUOTE_RMDIR: + rc = myssh_in_SFTP_QUOTE_RMDIR(data, sshc); + break; + case SSH_SFTP_QUOTE_UNLINK: + rc = myssh_in_SFTP_QUOTE_UNLINK(data, sshc); + break; + case SSH_SFTP_QUOTE_STATVFS: + rc = myssh_in_SFTP_QUOTE_STATVFS(data, sshc); + break; + case SSH_SFTP_GETINFO: + rc = myssh_in_SFTP_GETINFO(data, sshc); + break; + case SSH_SFTP_FILETIME: + rc = myssh_in_SFTP_FILETIME(data, sshc, sshp); + break; + case SSH_SFTP_TRANS_INIT: + rc = myssh_in_SFTP_TRANS_INIT(data, sshc, sshp); + break; + case SSH_SFTP_UPLOAD_INIT: + rc = myssh_in_UPLOAD_INIT(data, sshc, sshp); + break; + case SSH_SFTP_CREATE_DIRS_INIT: + rc = myssh_in_SFTP_CREATE_DIRS_INIT(data, sshc, sshp); + break; + case SSH_SFTP_CREATE_DIRS: + rc = myssh_in_SFTP_CREATE_DIRS(data, sshc, sshp); + break; + case SSH_SFTP_CREATE_DIRS_MKDIR: + rc = myssh_in_SFTP_CREATE_DIRS_MKDIR(data, sshc, sshp); + break; + case SSH_SFTP_READDIR_INIT: + rc = myssh_in_SFTP_READDIR_INIT(data, sshc, sshp); + break; + case SSH_SFTP_READDIR: + rc = myssh_in_SFTP_READDIR(data, sshc, sshp); + break; + case SSH_SFTP_READDIR_LINK: + rc = myssh_in_SFTP_READDIR_LINK(data, sshc); + break; + case SSH_SFTP_READDIR_BOTTOM: + rc = myssh_in_SFTP_READDIR_BOTTOM(data, sshc); + break; + case SSH_SFTP_READDIR_DONE: + rc = myssh_in_SFTP_READDIR_DONE(data, sshc); + break; + case SSH_SFTP_DOWNLOAD_INIT: + rc = myssh_in_SFTP_DOWNLOAD_INIT(data, sshc, sshp); + break; + case SSH_SFTP_DOWNLOAD_STAT: + rc = myssh_in_SFTP_DOWNLOAD_STAT(data, sshc); + break; + case SSH_SFTP_CLOSE: + rc = myssh_in_SFTP_CLOSE(data, sshc, sshp); + break; + case SSH_SFTP_SHUTDOWN: + rc = myssh_in_SFTP_SHUTDOWN(data, sshc); + break; + case SSH_SCP_TRANS_INIT: + rc = myssh_in_TRANS_INIT(data, sshc, sshp); + break; + case SSH_SCP_UPLOAD_INIT: + rc = myssh_in_SCP_UPLOAD_INIT(data, sshc, sshp); + break; + case SSH_SCP_DOWNLOAD_INIT: + rc = myssh_in_SCP_DOWNLOAD_INIT(data, sshc); + if(rc) + break; + FALLTHROUGH(); + case SSH_SCP_DOWNLOAD: + rc = myssh_SSH_SCP_DOWNLOAD(data, sshc); + break; + case SSH_SCP_DONE: + rc = myssh_in_SCP_DONE(data, sshc); + break; + case SSH_SCP_SEND_EOF: + rc = myssh_in_SCP_SEND_EOF(data, sshc); + break; + case SSH_SCP_CHANNEL_FREE: + myssh_in_SCP_CHANNEL_FREE(data, sshc); + FALLTHROUGH(); + case SSH_SESSION_DISCONNECT: + myssh_SESSION_DISCONNECT(data, sshc); + FALLTHROUGH(); + case SSH_SESSION_FREE: + result = myssh_in_SESSION_FREE(data, sshc); + break; + case SSH_QUIT: + default: + /* internal error */ + sshc->nextstate = SSH_NO_STATE; + myssh_to(data, sshc, SSH_STOP); + break; + } + /* break the loop only on STOP or SSH_AGAIN. If `rc` is some + * other error code, we will have progressed the state accordingly. */ + } while((rc != SSH_AGAIN) && (sshc->state != SSH_STOP)); + + if(rc == SSH_AGAIN) { + /* we would block, we need to wait for the socket to be ready (in the + right direction too)! */ + *block = TRUE; + } + if(!result && (sshc->state == SSH_STOP)) + result = sshc->actualcode; + CURL_TRC_SSH(data, "[%s] statemachine() -> %d, block=%d", + Curl_ssh_statename(sshc->state), (int)result, *block); + return result; +} + +/* called repeatedly until done from multi.c */ +static CURLcode myssh_multi_statemach(struct Curl_easy *data, + bool *done) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + struct SSHPROTO *sshp = Curl_meta_get(data, CURL_META_SSH_EASY); + bool block; /* we store the status and use that to provide + a Curl_ssh_pollset() implementation */ + CURLcode result; + + if(!sshc || !sshp) + return CURLE_FAILED_INIT; + result = myssh_statemachine(data, sshc, sshp, &block); + *done = (sshc->state == SSH_STOP); + myssh_block2waitfor(conn, sshc, block); + + return result; +} + +static CURLcode myssh_block_statemach(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool disconnect) +{ + struct connectdata *conn = data->conn; + CURLcode result = CURLE_OK; + + while((sshc->state != SSH_STOP) && !result) { + bool block; + timediff_t left_ms = 1000; + + result = myssh_statemachine(data, sshc, sshp, &block); + if(result) + break; + + if(!disconnect) { + result = Curl_pgrsCheck(data); + if(result) + break; + + left_ms = Curl_timeleft_ms(data); + if(left_ms < 0) { + failf(data, "Operation timed out"); + return CURLE_OPERATION_TIMEDOUT; + } + } + + if(block) { + curl_socket_t fd_read = conn->sock[FIRSTSOCKET]; + /* wait for the socket to become ready */ + (void)SOCKET_READABLE(fd_read, left_ms > 1000 ? 1000 : left_ms); + } + } + + return result; +} + +static void myssh_easy_dtor(void *key, size_t klen, void *entry) +{ + struct SSHPROTO *sshp = entry; + (void)key; + (void)klen; + curlx_safefree(sshp->path); + curlx_free(sshp); +} + +static void myssh_conn_dtor(void *key, size_t klen, void *entry) +{ + struct ssh_conn *sshc = entry; + (void)key; + (void)klen; + sshc_cleanup(sshc); + curlx_free(sshc); +} + +/* + * SSH setup connection + */ +static CURLcode myssh_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + struct SSHPROTO *sshp; + struct ssh_conn *sshc; + + sshc = curlx_calloc(1, sizeof(*sshc)); + if(!sshc) + return CURLE_OUT_OF_MEMORY; + + curlx_dyn_init(&sshc->readdir_buf, CURL_PATH_MAX * 2); + sshc->initialized = TRUE; + if(Curl_conn_meta_set(conn, CURL_META_SSH_CONN, sshc, myssh_conn_dtor)) + return CURLE_OUT_OF_MEMORY; + + sshp = curlx_calloc(1, sizeof(*sshp)); + if(!sshp || + Curl_meta_set(data, CURL_META_SSH_EASY, sshp, myssh_easy_dtor)) + return CURLE_OUT_OF_MEMORY; + + return Curl_ssh_setup_pkey(data, sshc); +} + +static Curl_recv scp_recv, sftp_recv; +static Curl_send scp_send, sftp_send; + +/* + * Curl_ssh_connect() gets called from Curl_protocol_connect() to allow us to + * do protocol-specific actions at connect-time. + */ +static CURLcode myssh_connect(struct Curl_easy *data, bool *done) +{ + CURLcode result; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + struct SSHPROTO *ssh = Curl_meta_get(data, CURL_META_SSH_EASY); + curl_socket_t sock = conn->sock[FIRSTSOCKET]; + int rc; + + if(!sshc || !ssh) + return CURLE_FAILED_INIT; + + CURL_TRC_SSH(data, "myssh_connect"); + if(conn->scheme->protocol & CURLPROTO_SCP) { + conn->recv[FIRSTSOCKET] = scp_recv; + conn->send[FIRSTSOCKET] = scp_send; + } + else { + conn->recv[FIRSTSOCKET] = sftp_recv; + conn->send[FIRSTSOCKET] = sftp_send; + } + + sshc->ssh_session = ssh_new(); + if(!sshc->ssh_session) { + failf(data, "Failure initializing ssh session"); + return CURLE_FAILED_INIT; + } + + /* For IPv6 origins, use the `user_hostname` that has the "[]" enclosure. + * Otherwise, use `hostname` that is IDN converted. */ + rc = ssh_options_set(sshc->ssh_session, SSH_OPTIONS_HOST, + conn->origin->ipv6 ? + conn->origin->user_hostname : conn->origin->hostname); + + if(rc != SSH_OK) { + failf(data, "Could not set remote host"); + return CURLE_FAILED_INIT; + } + + rc = ssh_options_parse_config(sshc->ssh_session, NULL); + if(rc != SSH_OK) { + infof(data, "Could not parse SSH configuration files"); + /* ignore */ + } + + CURL_TRC_SSH(data, "myssh_connect, set socket=%" FMT_SOCKET_T, sock); + rc = ssh_options_set(sshc->ssh_session, SSH_OPTIONS_FD, &sock); + if(rc != SSH_OK) { + failf(data, "Could not set socket"); + return CURLE_FAILED_INIT; + } + + if(Curl_creds_has_user(conn->creds)) { + infof(data, "User: %s", conn->creds->user); + rc = ssh_options_set(sshc->ssh_session, SSH_OPTIONS_USER, + conn->creds->user); + if(rc != SSH_OK) { + failf(data, "Could not set user"); + return CURLE_FAILED_INIT; + } + } + + if(CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS)) { + infof(data, "Known hosts: %s", + CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS)); + rc = ssh_options_set(sshc->ssh_session, SSH_OPTIONS_KNOWNHOSTS, + CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS)); + if(rc == SSH_OK) + /* libssh has two separate options for this. Set both to the same file + to avoid surprises */ + rc = ssh_options_set(sshc->ssh_session, SSH_OPTIONS_GLOBAL_KNOWNHOSTS, + CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS)); + if(rc != SSH_OK) { + failf(data, "Could not set known hosts file path"); + return CURLE_FAILED_INIT; + } + } + + if(conn->origin->port) { + rc = ssh_options_set(sshc->ssh_session, SSH_OPTIONS_PORT, + &conn->origin->port); + if(rc != SSH_OK) { + failf(data, "Could not set remote port"); + return CURLE_FAILED_INIT; + } + } + + if(data->set.ssh_compression) { + rc = ssh_options_set(sshc->ssh_session, SSH_OPTIONS_COMPRESSION, + "zlib,zlib@openssh.com,none"); + if(rc != SSH_OK) { + failf(data, "Could not set compression"); + return CURLE_FAILED_INIT; + } + } + + sshc->privkey = NULL; + sshc->pubkey = NULL; + + if(sshc->pub_key) { + rc = ssh_pki_import_pubkey_file(sshc->pub_key, &sshc->pubkey); + if(rc != SSH_OK) { + failf(data, "Could not load public key file"); + return CURLE_FAILED_INIT; + } + } + + /* we do not verify here, we do it at the state machine, + * after connection */ + + myssh_to(data, sshc, SSH_INIT); + + result = myssh_multi_statemach(data, done); + + return result; +} + +/* called from multi.c while DOing */ +static CURLcode scp_doing(struct Curl_easy *data, bool *dophase_done) +{ + CURLcode result; + + result = myssh_multi_statemach(data, dophase_done); + + if(*dophase_done) { + CURL_TRC_SSH(data, "DO phase is complete"); + } + return result; +} + +/* + *********************************************************************** + * + * scp_perform() + * + * This is the actual DO function for SCP. Get a file according to + * the options previously setup. + */ + +static CURLcode scp_perform(struct Curl_easy *data, + bool *connected, bool *dophase_done) +{ + CURLcode result = CURLE_OK; + struct ssh_conn *sshc = Curl_conn_meta_get(data->conn, CURL_META_SSH_CONN); + + CURL_TRC_SSH(data, "DO phase starts"); + + *dophase_done = FALSE; /* not done yet */ + if(!sshc) + return CURLE_FAILED_INIT; + + /* start the first command in the DO phase */ + myssh_to(data, sshc, SSH_SCP_TRANS_INIT); + + result = myssh_multi_statemach(data, dophase_done); + + *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET); + + if(*dophase_done) { + CURL_TRC_SSH(data, "DO phase is complete"); + } + + return result; +} + +/* BLOCKING, but the function is using the state machine so the only reason + this is still blocking is that the multi interface code has no support for + disconnecting operations that takes a while */ +static CURLcode scp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + CURLcode result = CURLE_OK; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + struct SSHPROTO *sshp = Curl_meta_get(data, CURL_META_SSH_EASY); + (void)dead_connection; + + if(sshc && sshc->ssh_session) { + /* only if there is a session still around to use! */ + myssh_to(data, sshc, SSH_SESSION_DISCONNECT); + result = myssh_block_statemach(data, sshc, sshp, TRUE); + } + + return result; +} + +/* generic done function for both SCP and SFTP called from their specific + done functions */ +static CURLcode myssh_done(struct Curl_easy *data, + struct ssh_conn *sshc, + CURLcode status) +{ + CURLcode result = CURLE_OK; + struct SSHPROTO *sshp = Curl_meta_get(data, CURL_META_SSH_EASY); + + if(!status && sshp) { + /* run the state-machine */ + result = myssh_block_statemach(data, sshc, sshp, FALSE); + } + else + result = status; + + if(Curl_pgrsDone(data)) + return CURLE_ABORTED_BY_CALLBACK; + + CURL_REQ_CLEAR_IO(data); + return result; +} + +static CURLcode scp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + struct ssh_conn *sshc = Curl_conn_meta_get(data->conn, CURL_META_SSH_CONN); + (void)premature; + + if(!sshc) + return CURLE_FAILED_INIT; + if(!status) + myssh_to(data, sshc, SSH_SCP_DONE); + + return myssh_done(data, sshc, status); +} + +static CURLcode scp_send(struct Curl_easy *data, int8_t sockindex, + const uint8_t *mem, size_t len, bool eos, + size_t *pnwritten) +{ + int rc; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + + (void)sockindex; /* we only support SCP on the fixed known primary socket */ + (void)eos; + *pnwritten = 0; + + if(!sshc) + return CURLE_FAILED_INIT; + + rc = ssh_scp_write(sshc->scp_session, mem, len); + +#if 0 + /* The following code is misleading, mostly added as wishful thinking + * that libssh at some point would implement non-blocking ssh_scp_write/read. + * Currently rc can only be number of bytes read or SSH_ERROR. */ + myssh_block2waitfor(conn, sshc, (rc == SSH_AGAIN)); + + if(rc == SSH_AGAIN) + return CURLE_AGAIN; + else +#endif + if(rc != SSH_OK) + return CURLE_SSH; + + *pnwritten = len; + return CURLE_OK; +} + +static CURLcode scp_recv(struct Curl_easy *data, int8_t sockindex, + char *mem, size_t len, size_t *pnread) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + int nread; + + (void)sockindex; /* we only support SCP on the fixed known primary socket */ + *pnread = 0; + + if(!sshc) + return CURLE_FAILED_INIT; + + /* libssh returns int */ + nread = ssh_scp_read(sshc->scp_session, mem, len); + if(nread == SSH_ERROR) + return CURLE_SSH; +#if 0 + /* The following code is misleading, mostly added as wishful thinking + * that libssh at some point would implement non-blocking ssh_scp_write/read. + * Currently rc can only be SSH_OK or SSH_ERROR. */ + + myssh_block2waitfor(conn, sshc, (nread == SSH_AGAIN)); + if(nread == SSH_AGAIN) + return CURLE_AGAIN; +#endif + *pnread = (size_t)nread; + return CURLE_OK; +} + +/* + * =============== SFTP =============== + */ + +/* + *********************************************************************** + * + * sftp_perform() + * + * This is the actual DO function for SFTP. Get a file/directory according to + * the options previously setup. + */ + +static CURLcode sftp_perform(struct Curl_easy *data, + bool *connected, + bool *dophase_done) +{ + struct ssh_conn *sshc = Curl_conn_meta_get(data->conn, CURL_META_SSH_CONN); + CURLcode result = CURLE_OK; + + CURL_TRC_SSH(data, "DO phase starts"); + + *dophase_done = FALSE; /* not done yet */ + if(!sshc) + return CURLE_FAILED_INIT; + + /* start the first command in the DO phase */ + myssh_to(data, sshc, SSH_SFTP_QUOTE_INIT); + + /* run the state-machine */ + result = myssh_multi_statemach(data, dophase_done); + + *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET); + + if(*dophase_done) { + CURL_TRC_SSH(data, "DO phase is complete"); + } + + return result; +} + +/* called from multi.c while DOing */ +static CURLcode sftp_doing(struct Curl_easy *data, + bool *dophase_done) +{ + CURLcode result = myssh_multi_statemach(data, dophase_done); + if(*dophase_done) { + CURL_TRC_SSH(data, "DO phase is complete"); + } + return result; +} + +/* BLOCKING, but the function is using the state machine so the only reason + this is still blocking is that the multi interface code has no support for + disconnecting operations that takes a while */ +static CURLcode sftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + struct SSHPROTO *sshp = Curl_meta_get(data, CURL_META_SSH_EASY); + CURLcode result = CURLE_OK; + (void)dead_connection; + + CURL_TRC_SSH(data, "DISCONNECT starts now"); + + if(sshc && sshc->ssh_session) { + /* only if there is a session still around to use! */ + myssh_to(data, sshc, SSH_SFTP_SHUTDOWN); + result = myssh_block_statemach(data, sshc, sshp, TRUE); + } + + CURL_TRC_SSH(data, "DISCONNECT is done"); + return result; +} + +static CURLcode sftp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + + if(!sshc) + return CURLE_FAILED_INIT; + if(!status) { + /* Post quote commands are executed after the SFTP_CLOSE state to avoid + errors that could happen due to open file handles during POSTQUOTE + operation */ + if(!premature && data->set.postquote && !conn->bits.retry) + sshc->nextstate = SSH_SFTP_POSTQUOTE_INIT; + myssh_to(data, sshc, SSH_SFTP_CLOSE); + } + return myssh_done(data, sshc, status); +} + +/* return number of sent bytes */ +static CURLcode sftp_send(struct Curl_easy *data, int8_t sockindex, + const uint8_t *mem, size_t len, bool eos, + size_t *pnwritten) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + ssize_t nwrite; + + (void)sockindex; + (void)eos; + *pnwritten = 0; + + if(!sshc) + return CURLE_FAILED_INIT; + +#if LIBSSH_VERSION_INT > SSH_VERSION_INT(0, 11, 0) + switch(sshc->sftp_send_state) { + case 0: + sftp_file_set_nonblocking(sshc->sftp_file); + if(sftp_aio_begin_write(sshc->sftp_file, mem, len, + &sshc->sftp_send_aio) == SSH_ERROR) { + return CURLE_SEND_ERROR; + } + sshc->sftp_send_state = 1; + FALLTHROUGH(); + case 1: + nwrite = sftp_aio_wait_write(&sshc->sftp_send_aio); + myssh_block2waitfor(conn, sshc, (nwrite == SSH_AGAIN) ? TRUE : FALSE); + if(nwrite == SSH_AGAIN) + return CURLE_AGAIN; + else if(nwrite < 0) + return CURLE_SEND_ERROR; + + /* + * sftp_aio_wait_write() would free sftp_send_aio and + * assign it NULL in all cases except when it returns + * SSH_AGAIN. + */ + + sshc->sftp_send_state = 0; + *pnwritten = (size_t)nwrite; + return CURLE_OK; + default: + /* we never reach here */ + return CURLE_SEND_ERROR; + } +#else + /* + * limit the writes to the maximum specified in Section 3 of + * https://datatracker.ietf.org/doc/html/draft-ietf-secsh-filexfer-02 + * + * libssh started applying appropriate read/write length limits + * internally since version 0.11.0, hence such an operation is + * not needed for versions after (and including) 0.11.0. + */ + if(len > 32768) + len = 32768; + + nwrite = sftp_write(sshc->sftp_file, mem, len); + + myssh_block2waitfor(conn, sshc, FALSE); + +#if 0 /* not returned by libssh on write */ + if(nwrite == SSH_AGAIN) { + *err = CURLE_AGAIN; + nwrite = 0; + } + else +#endif + if(nwrite < 0) + return CURLE_SSH; + + *pnwritten = (size_t)nwrite; + return CURLE_OK; +#endif +} + +/* + * Return number of received (decrypted) bytes + * or <0 on error + */ +static CURLcode sftp_recv(struct Curl_easy *data, int8_t sockindex, + char *mem, size_t len, size_t *pnread) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + ssize_t nread; + + (void)sockindex; + *pnread = 0; + + DEBUGASSERT(len < CURL_MAX_READ_SIZE); + if(!sshc) + return CURLE_FAILED_INIT; + + switch(sshc->sftp_recv_state) { + case 0: +#if LIBSSH_VERSION_INT > SSH_VERSION_INT(0, 11, 0) + if(sftp_aio_begin_read(sshc->sftp_file, len, + &sshc->sftp_recv_aio) == SSH_ERROR) { + return CURLE_RECV_ERROR; + } +#else + sshc->sftp_file_index = + sftp_async_read_begin(sshc->sftp_file, (uint32_t)len); + if(sshc->sftp_file_index < 0) + return CURLE_RECV_ERROR; +#endif + + FALLTHROUGH(); + case 1: + sshc->sftp_recv_state = 1; + +#if LIBSSH_VERSION_INT > SSH_VERSION_INT(0, 11, 0) + nread = sftp_aio_wait_read(&sshc->sftp_recv_aio, mem, len); +#else + nread = sftp_async_read(sshc->sftp_file, mem, (uint32_t)len, + (uint32_t)sshc->sftp_file_index); +#endif + + myssh_block2waitfor(conn, sshc, (nread == SSH_AGAIN)); + + if(nread == SSH_AGAIN) + return CURLE_AGAIN; + else if(nread < 0) + return CURLE_RECV_ERROR; + + /* + * sftp_aio_wait_read() would free sftp_recv_aio and + * assign it NULL in all cases except when it returns + * SSH_AGAIN. + */ + + sshc->sftp_recv_state = 0; + *pnread = (size_t)nread; + return CURLE_OK; + + default: + /* we never reach here */ + return CURLE_RECV_ERROR; + } +} + +static CURLcode myssh_do_it(struct Curl_easy *data, bool *done) +{ + CURLcode result; + bool connected = FALSE; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + + *done = FALSE; /* default to false */ + if(!sshc) + return CURLE_FAILED_INIT; + + data->req.size = -1; /* make sure this is unknown at this point */ + + sshc->actualcode = CURLE_OK; /* reset error code */ + sshc->secondCreateDirs = 0; /* reset the create directory attempt state + variable */ + + Curl_pgrsReset(data); + + if(conn->scheme->protocol & CURLPROTO_SCP) + result = scp_perform(data, &connected, done); + else + result = sftp_perform(data, &connected, done); + + return result; +} + +CURLcode Curl_ssh_init(void) +{ + if(ssh_init()) { + DEBUGF(curl_mfprintf(stderr, "Error: libssh_init failed\n")); + return CURLE_FAILED_INIT; + } + return CURLE_OK; +} + +void Curl_ssh_cleanup(void) +{ + (void)ssh_finalize(); +} + +void Curl_ssh_version(char *buffer, size_t buflen) +{ + (void)curl_msnprintf(buffer, buflen, "libssh/%s", ssh_version(0)); +} + +/* + * SCP. + */ +const struct Curl_protocol Curl_protocol_scp = { + myssh_setup_connection, /* setup_connection */ + myssh_do_it, /* do_it */ + scp_done, /* done */ + ZERO_NULL, /* do_more */ + myssh_connect, /* connect_it */ + myssh_multi_statemach, /* connecting */ + scp_doing, /* doing */ + Curl_ssh_pollset, /* proto_pollset */ + Curl_ssh_pollset, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + Curl_ssh_pollset, /* perform_pollset */ + scp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +/* + * SFTP. + */ +const struct Curl_protocol Curl_protocol_sftp = { + myssh_setup_connection, /* setup_connection */ + myssh_do_it, /* do_it */ + sftp_done, /* done */ + ZERO_NULL, /* do_more */ + myssh_connect, /* connect_it */ + myssh_multi_statemach, /* connecting */ + sftp_doing, /* doing */ + Curl_ssh_pollset, /* proto_pollset */ + Curl_ssh_pollset, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + Curl_ssh_pollset, /* perform_pollset */ + sftp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + ZERO_NULL, /* follow */ +}; + +#endif /* USE_LIBSSH */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/libssh2.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/libssh2.c new file mode 100644 index 0000000000..24a651d30e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/libssh2.c @@ -0,0 +1,3949 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_LIBSSH2 + +/* #define CURL_LIBSSH2_DEBUG */ + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef __VMS +#include <in.h> +#include <inet.h> +#endif + +#include "urldata.h" +#include "sendf.h" +#include "curl_trc.h" +#include "progress.h" +#include "transfer.h" +#include "vssh/ssh.h" +#include "url.h" +#include "cfilters.h" +#include "connect.h" +#include "parsedate.h" /* for the week day and month names */ +#include "multiif.h" +#include "select.h" +#include "curlx/fopen.h" +#include "vssh/vssh.h" +#include "curlx/strparse.h" +#include "curlx/base64.h" /* for curlx_base64_encode() */ + +static const char *sftp_libssh2_strerror(unsigned long err) +{ + switch(err) { + case LIBSSH2_FX_NO_SUCH_FILE: + return "No such file or directory"; + + case LIBSSH2_FX_PERMISSION_DENIED: + return "Permission denied"; + + case LIBSSH2_FX_FAILURE: + return "Operation failed"; + + case LIBSSH2_FX_BAD_MESSAGE: + return "Bad message from SFTP server"; + + case LIBSSH2_FX_NO_CONNECTION: + return "Not connected to SFTP server"; + + case LIBSSH2_FX_CONNECTION_LOST: + return "Connection to SFTP server lost"; + + case LIBSSH2_FX_OP_UNSUPPORTED: + return "Operation not supported by SFTP server"; + + case LIBSSH2_FX_INVALID_HANDLE: + return "Invalid handle"; + + case LIBSSH2_FX_NO_SUCH_PATH: + return "No such file or directory"; + + case LIBSSH2_FX_FILE_ALREADY_EXISTS: + return "File already exists"; + + case LIBSSH2_FX_WRITE_PROTECT: + return "File is write protected"; + + case LIBSSH2_FX_NO_MEDIA: + return "No media"; + + case LIBSSH2_FX_NO_SPACE_ON_FILESYSTEM: + return "Disk full"; + + case LIBSSH2_FX_QUOTA_EXCEEDED: + return "User quota exceeded"; + + case LIBSSH2_FX_UNKNOWN_PRINCIPAL: + return "Unknown principal"; + + case LIBSSH2_FX_LOCK_CONFLICT: + return "File lock conflict"; + + case LIBSSH2_FX_DIR_NOT_EMPTY: + return "Directory not empty"; + + case LIBSSH2_FX_NOT_A_DIRECTORY: + return "Not a directory"; + + case LIBSSH2_FX_INVALID_FILENAME: + return "Invalid filename"; + + case LIBSSH2_FX_LINK_LOOP: + return "Link points to itself"; + } + return "Unknown error in libssh2"; +} + +static void kbd_callback(const char *name, int name_len, + const char *instruction, int instruction_len, + int num_prompts, + const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts, + LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses, + void **abstract) +{ + struct Curl_easy *data = (struct Curl_easy *)*abstract; + +#ifdef CURL_LIBSSH2_DEBUG + curl_mfprintf(stderr, "name=%s\n", name); + curl_mfprintf(stderr, "name_len=%d\n", name_len); + curl_mfprintf(stderr, "instruction=%s\n", instruction); + curl_mfprintf(stderr, "instruction_len=%d\n", instruction_len); + curl_mfprintf(stderr, "num_prompts=%d\n", num_prompts); +#else + (void)name; + (void)name_len; + (void)instruction; + (void)instruction_len; +#endif /* CURL_LIBSSH2_DEBUG */ + if(num_prompts == 1) { + struct connectdata *conn = data->conn; + const char *passwd = Curl_creds_passwd(conn->creds); + /* this function must allocate memory that can be freed by libssh2, which + uses the LIBSSH2_FREE_FUNC callback */ + responses[0].text = Curl_cstrdup(passwd); + responses[0].length = responses[0].text ? curlx_uztoui(strlen(passwd)) : 0; + } + (void)prompts; +} /* kbd_callback */ + +static CURLcode sftp_libssh2_error_to_CURLE(unsigned long err) +{ + switch(err) { + case LIBSSH2_FX_OK: + return CURLE_OK; + + case LIBSSH2_FX_NO_SUCH_FILE: + case LIBSSH2_FX_NO_SUCH_PATH: + return CURLE_REMOTE_FILE_NOT_FOUND; + + case LIBSSH2_FX_PERMISSION_DENIED: + case LIBSSH2_FX_WRITE_PROTECT: + case LIBSSH2_FX_LOCK_CONFLICT: + return CURLE_REMOTE_ACCESS_DENIED; + + case LIBSSH2_FX_NO_SPACE_ON_FILESYSTEM: + case LIBSSH2_FX_QUOTA_EXCEEDED: + return CURLE_REMOTE_DISK_FULL; + + case LIBSSH2_FX_FILE_ALREADY_EXISTS: + return CURLE_REMOTE_FILE_EXISTS; + + case LIBSSH2_FX_DIR_NOT_EMPTY: + return CURLE_QUOTE_ERROR; + + default: + break; + } + + return CURLE_SSH; +} + +static CURLcode libssh2_session_error_to_CURLE(int err) +{ + switch(err) { + /* Ordered by order of appearance in libssh2.h */ + case LIBSSH2_ERROR_NONE: + return CURLE_OK; + + /* This is the error returned by libssh2_scp_recv2 + * on unknown file */ + case LIBSSH2_ERROR_SCP_PROTOCOL: + return CURLE_REMOTE_FILE_NOT_FOUND; + + case LIBSSH2_ERROR_SOCKET_NONE: + return CURLE_COULDNT_CONNECT; + + case LIBSSH2_ERROR_ALLOC: + return CURLE_OUT_OF_MEMORY; + + case LIBSSH2_ERROR_SOCKET_SEND: + return CURLE_SEND_ERROR; + + case LIBSSH2_ERROR_HOSTKEY_INIT: + case LIBSSH2_ERROR_HOSTKEY_SIGN: + case LIBSSH2_ERROR_PUBLICKEY_UNRECOGNIZED: + case LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED: + return CURLE_PEER_FAILED_VERIFICATION; + + case LIBSSH2_ERROR_PASSWORD_EXPIRED: + return CURLE_LOGIN_DENIED; + + case LIBSSH2_ERROR_SOCKET_TIMEOUT: + case LIBSSH2_ERROR_TIMEOUT: + return CURLE_OPERATION_TIMEDOUT; + + case LIBSSH2_ERROR_EAGAIN: + return CURLE_AGAIN; + } + + return CURLE_SSH; +} + +/* These functions are made to use the libcurl memory functions - NOT the + debugmem functions, as that leads us to trigger on libssh2 memory leaks + that are not ours to care for */ + +static LIBSSH2_ALLOC_FUNC(my_libssh2_malloc) +{ + (void)abstract; + return Curl_cmalloc(count); +} + +static LIBSSH2_REALLOC_FUNC(my_libssh2_realloc) +{ + (void)abstract; + return Curl_crealloc(ptr, count); +} + +static LIBSSH2_FREE_FUNC(my_libssh2_free) +{ + (void)abstract; + if(ptr) /* ssh2 agent sometimes call free with null ptr */ + Curl_cfree(ptr); +} + +static int sshkeycallback(CURL *easy, + const struct curl_khkey *knownkey, /* known */ + const struct curl_khkey *foundkey, /* found */ + enum curl_khmatch match, + void *clientp) +{ + (void)easy; + (void)knownkey; + (void)foundkey; + (void)clientp; + + /* we only allow perfect matches, and we reject everything else */ + return (match != CURLKHMATCH_OK) ? CURLKHSTAT_REJECT : CURLKHSTAT_FINE; +} + +static enum curl_khtype convert_ssh2_keytype(int sshkeytype) +{ + enum curl_khtype keytype = CURLKHTYPE_UNKNOWN; + switch(sshkeytype) { + case LIBSSH2_HOSTKEY_TYPE_RSA: + keytype = CURLKHTYPE_RSA; + break; +#ifdef LIBSSH2_HOSTKEY_TYPE_DSS + case LIBSSH2_HOSTKEY_TYPE_DSS: /* deprecated upstream */ + keytype = CURLKHTYPE_DSS; + break; +#endif +#ifdef LIBSSH2_HOSTKEY_TYPE_ECDSA_256 + case LIBSSH2_HOSTKEY_TYPE_ECDSA_256: + keytype = CURLKHTYPE_ECDSA; + break; +#endif +#ifdef LIBSSH2_HOSTKEY_TYPE_ECDSA_384 + case LIBSSH2_HOSTKEY_TYPE_ECDSA_384: + keytype = CURLKHTYPE_ECDSA; + break; +#endif +#ifdef LIBSSH2_HOSTKEY_TYPE_ECDSA_521 + case LIBSSH2_HOSTKEY_TYPE_ECDSA_521: + keytype = CURLKHTYPE_ECDSA; + break; +#endif +#ifdef LIBSSH2_HOSTKEY_TYPE_ED25519 + case LIBSSH2_HOSTKEY_TYPE_ED25519: + keytype = CURLKHTYPE_ED25519; + break; +#endif + } + return keytype; +} + +static CURLcode ssh_knownhost(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + struct connectdata *conn = data->conn; + struct libssh2_knownhost *host = NULL; + const char *remotekey = NULL; + int keycheck = LIBSSH2_KNOWNHOST_CHECK_FAILURE; + int keybit = 0; + int sshkeytype = 0; + size_t keylen = 0; + int rc = 0; + CURLcode result = CURLE_OK; + + if(!CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS)) { + infof(data, "SSH: no knownhosts file configured"); + return CURLE_OK; + } + + remotekey = libssh2_session_hostkey(sshc->ssh_session, + &keylen, &sshkeytype); + if(remotekey) { + /* + * A subject to figure out is what hostname we need to pass in here. + * What hostname does OpenSSH store in its file if an IDN name is + * used? + */ + struct Curl_mapi_guard guard; + enum curl_khmatch keymatch; + curl_sshkeycallback func = + data->set.ssh_keyfunc ? data->set.ssh_keyfunc : sshkeycallback; + struct curl_khkey knownkey; + struct curl_khkey *knownkeyp = NULL; + struct curl_khkey foundkey; + + switch(sshkeytype) { + case LIBSSH2_HOSTKEY_TYPE_RSA: + keybit = LIBSSH2_KNOWNHOST_KEY_SSHRSA; + break; +#ifdef LIBSSH2_HOSTKEY_TYPE_DSS + case LIBSSH2_HOSTKEY_TYPE_DSS: /* deprecated upstream */ + keybit = LIBSSH2_KNOWNHOST_KEY_SSHDSS; + break; +#endif + case LIBSSH2_HOSTKEY_TYPE_ECDSA_256: + keybit = LIBSSH2_KNOWNHOST_KEY_ECDSA_256; + break; + case LIBSSH2_HOSTKEY_TYPE_ECDSA_384: + keybit = LIBSSH2_KNOWNHOST_KEY_ECDSA_384; + break; + case LIBSSH2_HOSTKEY_TYPE_ECDSA_521: + keybit = LIBSSH2_KNOWNHOST_KEY_ECDSA_521; + break; + case LIBSSH2_HOSTKEY_TYPE_ED25519: + keybit = LIBSSH2_KNOWNHOST_KEY_ED25519; + break; + default: + infof(data, "SSH: unsupported host key type for knownhosts check"); + keybit = 0; + break; + } + if(!keybit) + /* no check means failure! */ + rc = CURLKHSTAT_REJECT; + else { + keycheck = libssh2_knownhost_checkp(sshc->kh, + conn->origin->hostname, + (conn->origin->port != PORT_SSH) ? + conn->origin->port : -1, + remotekey, keylen, + LIBSSH2_KNOWNHOST_TYPE_PLAIN | + LIBSSH2_KNOWNHOST_KEYENC_RAW | + keybit, + &host); + + infof(data, "SSH: host check %d, key: %s", keycheck, + (keycheck <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH) ? + host->key : "<none>"); + + /* setup 'knownkey' */ + if(keycheck <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH) { + knownkey.key = host->key; + knownkey.len = 0; + knownkey.keytype = convert_ssh2_keytype(sshkeytype); + knownkeyp = &knownkey; + } + + /* setup 'foundkey' */ + foundkey.key = remotekey; + foundkey.len = keylen; + foundkey.keytype = convert_ssh2_keytype(sshkeytype); + + /* + * if any of the LIBSSH2_KNOWNHOST_CHECK_* defines and the + * curl_khmatch enum are ever modified, we need to introduce a + * translation table here! + */ + keymatch = (enum curl_khmatch)keycheck; + + /* Ask the callback how to behave */ + CURL_CBAPI_START(&guard, data, easy_ssh_keyfunc); + rc = func(data, knownkeyp, /* from the knownhosts file */ + &foundkey, /* from the remote host */ + keymatch, data->set.ssh_keyfunc_userp); + CURL_CBAPI_END(&guard); + } + } + else { + /* no remotekey means failure! */ + infof(data, "SSH: host offers no public key"); + rc = CURLKHSTAT_REJECT; + } + + switch(rc) { + default: /* unknown return codes is the same as reject */ + case CURLKHSTAT_REJECT: + infof(data, "SSH: knownhost check failed"); + myssh_to(data, sshc, SSH_SESSION_FREE); + FALLTHROUGH(); + case CURLKHSTAT_DEFER: + /* DEFER means bail out but keep the SSH_HOSTKEY state */ + result = CURLE_PEER_FAILED_VERIFICATION; + break; + case CURLKHSTAT_FINE_REPLACE: + /* remove old host+key that does not match */ + if(host) + libssh2_knownhost_del(sshc->kh, host); + FALLTHROUGH(); + case CURLKHSTAT_FINE: + case CURLKHSTAT_FINE_ADD_TO_FILE: + /* proceed */ + if(keycheck != LIBSSH2_KNOWNHOST_CHECK_MATCH) { + int addrc; + const char *hostbuf; + char *hostport = NULL; + if(conn->origin->port != PORT_SSH) { + hostbuf = hostport = curl_maprintf("[%s]:%u", conn->origin->hostname, + conn->origin->port); + if(!hostbuf) + infof(data, "WARNING: failed allocating buffer for [host]:port"); + } + else + hostbuf = conn->origin->hostname; + if(hostbuf) { + /* the found host+key did not match but has been told to be fine + anyway so we add it in memory */ + addrc = libssh2_knownhost_addc(sshc->kh, hostbuf, NULL, + remotekey, keylen, NULL, 0, + LIBSSH2_KNOWNHOST_TYPE_PLAIN | + LIBSSH2_KNOWNHOST_KEYENC_RAW | + keybit, NULL); + if(addrc) + infof(data, "WARNING: adding the known host %s failed", hostbuf); + else if(rc == CURLKHSTAT_FINE_ADD_TO_FILE || + rc == CURLKHSTAT_FINE_REPLACE) { + /* now we write the entire in-memory list of known hosts to the + known_hosts file */ + int wrc = + libssh2_knownhost_writefile( + sshc->kh, CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS), + LIBSSH2_KNOWNHOST_FILE_OPENSSH); + if(wrc) { + infof(data, "WARNING: writing %s failed", + CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS)); + } + } + } + curlx_free(hostport); + } + else + infof(data, "SSH: knownhost entry matches host key"); + break; + } + return result; +} + +static CURLcode ssh_check_fingerprint(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + const char *pubkey_md5 = + CURL_EASY_STR(data, STRING_SSH_HOST_PUBLIC_KEY_MD5); + const char *pubkey_sha256 = + CURL_EASY_STR(data, STRING_SSH_HOST_PUBLIC_KEY_SHA256); + + if(pubkey_sha256) { + const char *fingerprint = NULL; + char *fingerprint_b64 = NULL; + size_t fingerprint_b64_len; + size_t pub_pos = 0; + size_t b64_pos = 0; + + infof(data, "SSH: SHA256 public key '%s'", pubkey_sha256); + /* The fingerprint points to static storage (!), do not free() it. */ + fingerprint = libssh2_hostkey_hash(sshc->ssh_session, + LIBSSH2_HOSTKEY_HASH_SHA256); + if(!fingerprint) { + failf(data, + "Denied establishing ssh session: SHA256 fingerprint " + "not available"); + myssh_to(data, sshc, SSH_SESSION_FREE); + return CURLE_PEER_FAILED_VERIFICATION; + } + + /* The length of fingerprint is 32 bytes for SHA256. + * See libssh2_hostkey_hash documentation. */ + if(curlx_base64_encode((const uint8_t *)fingerprint, 32, &fingerprint_b64, + &fingerprint_b64_len) != CURLE_OK) { + myssh_to(data, sshc, SSH_SESSION_FREE); + return CURLE_PEER_FAILED_VERIFICATION; + } + + if(!fingerprint_b64) { + failf(data, "SHA256 fingerprint could not be encoded"); + myssh_to(data, sshc, SSH_SESSION_FREE); + return CURLE_PEER_FAILED_VERIFICATION; + } + + infof(data, "SSH: SHA256 fingerprint '%s'", fingerprint_b64); + + /* Find the position of any = padding characters in the public key */ + while((pubkey_sha256[pub_pos] != '=') && pubkey_sha256[pub_pos]) { + pub_pos++; + } + + /* Find the position of any = padding characters in the base64 coded + * hostkey fingerprint */ + while((fingerprint_b64[b64_pos] != '=') && fingerprint_b64[b64_pos]) { + b64_pos++; + } + + /* Before we authenticate we check the hostkey's SHA256 fingerprint + * against a known fingerprint, if available. + */ + if((pub_pos != b64_pos) || + strncmp(fingerprint_b64, pubkey_sha256, pub_pos)) { + failf(data, + "Denied establishing ssh session: mismatch SHA256 fingerprint. " + "Remote %s is not equal to %s", fingerprint_b64, pubkey_sha256); + curlx_free(fingerprint_b64); + myssh_to(data, sshc, SSH_SESSION_FREE); + return CURLE_PEER_FAILED_VERIFICATION; + } + + curlx_free(fingerprint_b64); + + infof(data, "SSH: SHA256 checksum match"); + } + + if(pubkey_md5) { + char md5buffer[33]; + const char *fingerprint; + + infof(data, "SSH: MD5 public key '%s'", pubkey_md5); + fingerprint = libssh2_hostkey_hash(sshc->ssh_session, + LIBSSH2_HOSTKEY_HASH_MD5); + + if(fingerprint) { + /* The fingerprint points to static storage (!), do not free() it. */ + int i; + for(i = 0; i < 16; i++) { + curl_msnprintf(&md5buffer[i * 2], 3, "%02x", + (unsigned char)fingerprint[i]); + } + + infof(data, "SSH: MD5 fingerprint '%s'", md5buffer); + } + + /* This does NOT verify the length of 'pubkey_md5' separately, which + makes the comparison below fail unless it is exactly 32 characters */ + if(!fingerprint || !curl_strequal(md5buffer, pubkey_md5)) { + if(fingerprint) { + failf(data, + "Denied establishing ssh session: mismatch MD5 fingerprint. " + "Remote %s is not equal to %s", md5buffer, pubkey_md5); + } + else { + failf(data, + "Denied establishing ssh session: MD5 fingerprint " + "not available"); + } + myssh_to(data, sshc, SSH_SESSION_FREE); + return CURLE_PEER_FAILED_VERIFICATION; + } + infof(data, "SSH: MD5 checksum match"); + } + + if(!pubkey_md5 && !pubkey_sha256) { + if(data->set.ssh_hostkeyfunc) { + size_t keylen = 0; + int sshkeytype = 0; + int rc = 0; + /* we handle the process to the callback */ + const char *remotekey = libssh2_session_hostkey(sshc->ssh_session, + &keylen, &sshkeytype); + if(remotekey) { + struct Curl_mapi_guard guard; + enum curl_khtype keytype = convert_ssh2_keytype(sshkeytype); + CURL_CBAPI_START(&guard, data, easy_ssh_hostkeyfunc); + rc = data->set.ssh_hostkeyfunc(data->set.ssh_hostkeyfunc_userp, + (int)keytype, remotekey, keylen); + CURL_CBAPI_END(&guard); + if(rc != CURLKHMATCH_OK) { + myssh_to(data, sshc, SSH_SESSION_FREE); + failf(data, "SSH: callback failed host public key verification"); + return CURLE_PEER_FAILED_VERIFICATION; + } + infof(data, "SSH: verified public key via callback"); + } + else { + myssh_to(data, sshc, SSH_SESSION_FREE); + return CURLE_PEER_FAILED_VERIFICATION; + } + return CURLE_OK; + } + else { + CURL_TRC_SSH(data, "no host key checksum given, checking knownhosts"); + return ssh_knownhost(data, sshc); + } + } + else { + /* as we already matched, we skip the check for known hosts */ + return CURLE_OK; + } +} + +/* + * ssh_force_knownhost_key_type() checks the known hosts file and try to + * force a specific public key type from the server if an entry is found. + */ +static CURLcode ssh_force_knownhost_key_type(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + CURLcode result = CURLE_OK; + + static const char hostkey_method_ssh_ed25519[] = "ssh-ed25519"; + static const char hostkey_method_ssh_ecdsa_521[] = "ecdsa-sha2-nistp521"; + static const char hostkey_method_ssh_ecdsa_384[] = "ecdsa-sha2-nistp384"; + static const char hostkey_method_ssh_ecdsa_256[] = "ecdsa-sha2-nistp256"; + static const char hostkey_method_ssh_rsa_all[] = + "rsa-sha2-256,rsa-sha2-512,ssh-rsa"; +#ifdef LIBSSH2_KNOWNHOST_KEY_SSHDSS + static const char hostkey_method_ssh_dss[] = "ssh-dss"; +#endif + bool found = FALSE; + + if(sshc->kh && + !CURL_EASY_STR(data, STRING_SSH_HOST_PUBLIC_KEY_MD5) && + !CURL_EASY_STR(data, STRING_SSH_HOST_PUBLIC_KEY_SHA256)) { + struct libssh2_knownhost *store = NULL; + struct connectdata *conn = data->conn; + /* lets try to find our host in the known hosts file */ + while(!libssh2_knownhost_get(sshc->kh, &store, store)) { + /* For non-standard ports, the name is enclosed in */ + /* square brackets, followed by a colon and the port */ + if(store) { + if(store->name) { + if(store->name[0] == '[') { + curl_off_t port; + size_t kh_name_size = 0; + const char *p; + const char *kh_name_end = strstr(store->name, "]:"); + if(!kh_name_end) { + infof(data, "SSH: invalid host pattern %s in %s", + store->name, + CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS)); + continue; + } + p = kh_name_end + 2; /* start of port number */ + if(!curlx_str_number(&p, &port, 0xffff) && + (kh_name_end && (port == conn->origin->port))) { + kh_name_size = strlen(store->name) - 1 - strlen(kh_name_end); + if(!strncmp(store->name + 1, conn->origin->hostname, + kh_name_size)) { + found = TRUE; + break; + } + } + } + else if(!strcmp(store->name, conn->origin->hostname)) { + found = TRUE; + break; + } + } + else { + found = TRUE; + break; + } + } + } + + if(found) { + int rc; + const char *hostkey_method = NULL; + infof(data, "SSH: found host '%s' in '%s'", + conn->origin->hostname, + CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS)); + + switch(store->typemask & LIBSSH2_KNOWNHOST_KEY_MASK) { + case LIBSSH2_KNOWNHOST_KEY_ED25519: + hostkey_method = hostkey_method_ssh_ed25519; + break; + case LIBSSH2_KNOWNHOST_KEY_ECDSA_521: + hostkey_method = hostkey_method_ssh_ecdsa_521; + break; + case LIBSSH2_KNOWNHOST_KEY_ECDSA_384: + hostkey_method = hostkey_method_ssh_ecdsa_384; + break; + case LIBSSH2_KNOWNHOST_KEY_ECDSA_256: + hostkey_method = hostkey_method_ssh_ecdsa_256; + break; + case LIBSSH2_KNOWNHOST_KEY_SSHRSA: + hostkey_method = hostkey_method_ssh_rsa_all; + break; +#ifdef LIBSSH2_KNOWNHOST_KEY_SSHDSS + case LIBSSH2_KNOWNHOST_KEY_SSHDSS: /* deprecated upstream */ + hostkey_method = hostkey_method_ssh_dss; + break; +#endif + case LIBSSH2_KNOWNHOST_KEY_RSA1: + failf(data, "Found host key type RSA1 which is not supported"); + return CURLE_SSH; + default: + failf(data, "Unknown host key type: %d", + (store->typemask & LIBSSH2_KNOWNHOST_KEY_MASK)); + return CURLE_SSH; + } + + infof(data, "SSH: set '%s' as hostkey type", hostkey_method); + rc = libssh2_session_method_pref(sshc->ssh_session, + LIBSSH2_METHOD_HOSTKEY, hostkey_method); + if(rc) { + char *err_msg = NULL; + int errlen; + libssh2_session_last_error(sshc->ssh_session, &err_msg, &errlen, 0); + failf(data, "libssh2 method '%s' failed: %s", hostkey_method, err_msg); + result = libssh2_session_error_to_CURLE(rc); + } + } + else { + infof(data, "SSH: did not find host '%s' in '%s'", + conn->origin->hostname, + CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS)); + } + } + + return result; +} + +static CURLcode quote_error(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + failf(data, "Suspicious data after the command line"); + curlx_safefree(sshc->quote_path1); + curlx_safefree(sshc->quote_path2); + return CURLE_QUOTE_ERROR; +} + +static CURLcode sftp_quote(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + const char *cp; + CURLcode result = CURLE_OK; + + /* + * Support some of the "FTP" commands + * + * 'sshc->quote_item' is already verified to be non-NULL before it + * switched to this state. + */ + const char *cmd = sshc->quote_item->data; + sshc->acceptfail = FALSE; + + /* if a command starts with an asterisk, which a legal SFTP command never + can, the command is allowed to fail without it causing any + aborts or cancels etc. It causes libcurl to act as if the command + is successful, whatever the server responds. */ + + if(cmd[0] == '*') { + cmd++; + sshc->acceptfail = TRUE; + } + + if(curl_strequal("pwd", cmd)) { + /* output debug output if that is requested */ + char *tmp = curl_maprintf("257 \"%s\" is current directory.\n", + sshp->path); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + Curl_debug(data, CURLINFO_HEADER_OUT, "PWD\n", 4); + Curl_debug(data, CURLINFO_HEADER_IN, tmp, strlen(tmp)); + + /* this sends an FTP-like "header" to the header callback so that + the current directory can be read similar to how it is read when + using ordinary FTP. */ + result = Curl_client_write(data, CLIENTWRITE_HEADER, tmp, strlen(tmp)); + curlx_free(tmp); + if(!result) + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return result; + } + + /* + * the arguments following the command must be separated from the + * command with a space so we can check for it unconditionally + */ + cp = strchr(cmd, ' '); + if(!cp) { + failf(data, "Syntax error command '%s', missing parameter", cmd); + return CURLE_QUOTE_ERROR; + } + + /* + * also, every command takes at least one argument so we get that + * first argument right now + */ + result = Curl_get_pathname(&cp, &sshc->quote_path1, sshc->homedir); + if(result) { + if(result != CURLE_OUT_OF_MEMORY) + failf(data, "Syntax error: Bad first parameter to '%s'", cmd); + return result; + } + + /* + * SFTP is a binary protocol, so we do not send text commands to the server. + * Instead, we scan for commands used by OpenSSH's sftp program and call the + * appropriate libssh2 functions. + */ + if(!strncmp(cmd, "chgrp ", 6) || + !strncmp(cmd, "chmod ", 6) || + !strncmp(cmd, "chown ", 6) || + !strncmp(cmd, "atime ", 6) || + !strncmp(cmd, "mtime ", 6)) { + /* attribute change */ + + /* sshc->quote_path1 contains the mode to set */ + /* get the destination */ + result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); + if(result) { + if(result != CURLE_OUT_OF_MEMORY) + failf(data, "Syntax error in %s: Bad second parameter", cmd); + curlx_safefree(sshc->quote_path1); + return result; + } + if(*cp) + return quote_error(data, sshc); + + memset(&sshp->quote_attrs, 0, sizeof(LIBSSH2_SFTP_ATTRIBUTES)); + myssh_to(data, sshc, SSH_SFTP_QUOTE_STAT); + return result; + } + if(!strncmp(cmd, "ln ", 3) || + !strncmp(cmd, "symlink ", 8)) { + /* symbolic linking */ + /* sshc->quote_path1 is the source */ + /* get the destination */ + result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); + if(result) { + if(result != CURLE_OUT_OF_MEMORY) + failf(data, "Syntax error in ln/symlink: Bad second parameter"); + curlx_safefree(sshc->quote_path1); + return result; + } + if(*cp) + return quote_error(data, sshc); + myssh_to(data, sshc, SSH_SFTP_QUOTE_SYMLINK); + return result; + } + else if(!strncmp(cmd, "mkdir ", 6)) { + if(*cp) + return quote_error(data, sshc); + /* create directory */ + myssh_to(data, sshc, SSH_SFTP_QUOTE_MKDIR); + return result; + } + else if(!strncmp(cmd, "rename ", 7)) { + /* rename file */ + /* first param is the source path */ + /* second param is the dest. path */ + result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); + if(result) { + if(result != CURLE_OUT_OF_MEMORY) + failf(data, "Syntax error in rename: Bad second parameter"); + curlx_safefree(sshc->quote_path1); + return result; + } + if(*cp) + return quote_error(data, sshc); + myssh_to(data, sshc, SSH_SFTP_QUOTE_RENAME); + return result; + } + else if(!strncmp(cmd, "rmdir ", 6)) { + if(*cp) + return quote_error(data, sshc); + /* delete directory */ + myssh_to(data, sshc, SSH_SFTP_QUOTE_RMDIR); + return result; + } + else if(!strncmp(cmd, "rm ", 3)) { + if(*cp) + return quote_error(data, sshc); + myssh_to(data, sshc, SSH_SFTP_QUOTE_UNLINK); + return result; + } + else if(!strncmp(cmd, "statvfs ", 8)) { + if(*cp) + return quote_error(data, sshc); + myssh_to(data, sshc, SSH_SFTP_QUOTE_STATVFS); + return result; + } + + failf(data, "Unknown SFTP command"); + curlx_safefree(sshc->quote_path1); + curlx_safefree(sshc->quote_path2); + return CURLE_QUOTE_ERROR; +} + +static CURLcode sftp_upload_init(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool *blockp) +{ + unsigned long flags; + + /* + * NOTE!!! libssh2 requires that the destination path is a full path + * that includes the destination file and name OR ends in a "/" + * If this is not done the destination file is named the + * same name as the last directory in the path. + */ + + if(data->state.resume_from) { + LIBSSH2_SFTP_ATTRIBUTES attrs; + if(data->state.resume_from < 0) { + int rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + LIBSSH2_SFTP_STAT, &attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) { + *blockp = TRUE; + return CURLE_OK; + } + if(rc) { + data->state.resume_from = 0; + } + else { + curl_off_t size = attrs.filesize; + if(size < 0) { + failf(data, "Bad file size (%" FMT_OFF_T ")", size); + return CURLE_BAD_DOWNLOAD_RESUME; + } + data->state.resume_from = attrs.filesize; + } + } + } + + if(data->set.remote_append) { + /* True append mode: create if nonexisting */ + flags = LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT | LIBSSH2_FXF_APPEND; + } + else if(data->state.resume_from > 0) { + /* + * Resume MUST NOT use APPEND; some servers force writes to EOF when + * APPEND is set, ignoring a prior seek(). + */ + flags = LIBSSH2_FXF_WRITE; + } + else { + /* Clear file before writing (normal behavior) */ + flags = LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT | LIBSSH2_FXF_TRUNC; + } + + sshc->sftp_handle = + libssh2_sftp_open_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + flags, (long)data->set.new_file_perms, + LIBSSH2_SFTP_OPENFILE); + + if(!sshc->sftp_handle) { + CURLcode result; + unsigned long sftperr; + int rc = libssh2_session_last_errno(sshc->ssh_session); + + if(LIBSSH2_ERROR_EAGAIN == rc) { + *blockp = TRUE; + return CURLE_OK; + } + + if(LIBSSH2_ERROR_SFTP_PROTOCOL == rc) + /* only when there was an SFTP protocol error can we extract + the sftp error! */ + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + else + sftperr = LIBSSH2_FX_OK; /* not an sftp error at all */ + + if(sshc->secondCreateDirs) { + myssh_to(data, sshc, SSH_SFTP_CLOSE); + failf(data, "Creating the dir/file failed: %s", + sftp_libssh2_strerror(sftperr)); + return sftp_libssh2_error_to_CURLE(sftperr); + } + if((sftperr == LIBSSH2_FX_NO_SUCH_FILE || + sftperr == LIBSSH2_FX_FAILURE || + sftperr == LIBSSH2_FX_NO_SUCH_PATH) && + data->set.ftp_create_missing_dirs && + (strlen(sshp->path) > 1)) { + /* try to create the path remotely */ + sshc->secondCreateDirs = 1; + myssh_to(data, sshc, SSH_SFTP_CREATE_DIRS_INIT); + return CURLE_OK; + } + myssh_to(data, sshc, SSH_SFTP_CLOSE); + result = sftp_libssh2_error_to_CURLE(sftperr); + if(!result) { + /* Sometimes, for some reason libssh2_sftp_last_error() returns zero + even though libssh2_sftp_open() failed previously! We need to + work around that! */ + result = CURLE_SSH; + sftperr = LIBSSH2_FX_OK; + } + failf(data, "Upload failed: %s (%lu/%d)", + sftperr != LIBSSH2_FX_OK ? + sftp_libssh2_strerror(sftperr) : "ssh error", + sftperr, rc); + return result; + } + + /* If we have a restart point then we need to seek to the correct + Skip if in explicit remote append mode. */ + if(data->state.resume_from > 0 && !data->set.remote_append) { + int seekerr = CURL_SEEKFUNC_OK; + /* Let's read off the proper amount of bytes from the input. */ + if(data->set.seek_func) { + struct Curl_mapi_guard guard; + CURL_CBAPI_START(&guard, data, easy_seek_func); + seekerr = data->set.seek_func(data->set.seek_client, + data->state.resume_from, SEEK_SET); + CURL_CBAPI_END(&guard); + } + + if(seekerr != CURL_SEEKFUNC_OK) { + curl_off_t passed = 0; + + if(seekerr != CURL_SEEKFUNC_CANTSEEK) { + failf(data, "Could not seek stream"); + return CURLE_FTP_COULDNT_USE_REST; + } + /* seekerr == CURL_SEEKFUNC_CANTSEEK (cannot seek to offset) */ + do { + struct Curl_mapi_guard guard; + char scratch[4 * 1024]; + size_t readthisamountnow = + (data->state.resume_from - passed > + (curl_off_t)sizeof(scratch)) ? + sizeof(scratch) : curlx_sotouz(data->state.resume_from - passed); + + size_t actuallyread; + CURL_CBAPI_START(&guard, data, easy_fread_func); + actuallyread = data->state.fread_func(scratch, 1, + readthisamountnow, + data->state.in); + CURL_CBAPI_END(&guard); + + passed += actuallyread; + if((actuallyread == 0) || (actuallyread > readthisamountnow)) { + /* this checks for greater-than only to make sure that the + CURL_READFUNC_ABORT return code still aborts */ + failf(data, "Failed to read data"); + return CURLE_FTP_COULDNT_USE_REST; + } + } while(passed < data->state.resume_from); + } + + /* now, decrease the size of the read */ + if(data->state.infilesize > 0) { + data->state.infilesize -= data->state.resume_from; + data->req.size = data->state.infilesize; + Curl_pgrsSetUploadSize(data, data->state.infilesize); + } + + libssh2_sftp_seek64(sshc->sftp_handle, + (libssh2_uint64_t)data->state.resume_from); + } + if(data->state.infilesize > 0) { + data->req.size = data->state.infilesize; + Curl_pgrsSetUploadSize(data, data->state.infilesize); + } + /* upload data */ + Curl_xfer_setup_send(data, FIRSTSOCKET); + + /* not set by Curl_xfer_setup to preserve io_flags */ + data->conn->recv_idx = FIRSTSOCKET; + + /* since we do not really wait for anything at this point, we want the + state machine to move on as soon as possible so mark this as dirty */ + Curl_multi_mark_dirty(data); + + myssh_to(data, sshc, SSH_STOP); + return CURLE_OK; +} + +static void ssh_state_pkey_init(struct Curl_easy *data, struct ssh_conn *sshc) +{ + /* + * Check the supported auth types in the order I feel is most secure + * with the requested type of authentication + */ + sshc->authed = FALSE; + + if((data->set.ssh_auth_types & CURLSSH_AUTH_PUBLICKEY) && + strstr(sshc->authlist, "publickey")) { + if(sshc->pub_key) + infof(data, "SSH: trying public key file '%s'", sshc->pub_key); + infof(data, "SSH: trying private key file '%s'", sshc->priv_key); + myssh_to(data, sshc, SSH_AUTH_PKEY); + } + else + myssh_to(data, sshc, SSH_AUTH_PASS_INIT); +} + +static CURLcode sftp_quote_stat(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool *blockp) +{ + const char *cmd = sshc->quote_item->data; + sshc->acceptfail = FALSE; + + /* if a command starts with an asterisk, which a legal SFTP command never + can, the command is allowed to fail without it causing any aborts or + cancels etc. It causes libcurl to act as if the command is + successful, whatever the server responds. */ + + if(cmd[0] == '*') { + cmd++; + sshc->acceptfail = TRUE; + } + + if(strncmp(cmd, "chmod", 5)) { + /* Since chown and chgrp only set owner OR group but libssh2 wants to set + * them both at once, we need to obtain the current ownership first. This + * takes an extra protocol round trip. + */ + int rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshc->quote_path2, + curlx_uztoui(strlen(sshc->quote_path2)), + LIBSSH2_SFTP_STAT, + &sshp->quote_attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) { + *blockp = TRUE; + return CURLE_OK; + } + if(rc && !sshc->acceptfail) { /* get those attributes */ + unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session); + failf(data, "Attempt to get SFTP stats failed: %s", + sftp_libssh2_strerror(sftperr)); + goto fail; + } + } + + /* Now set the new attributes... */ + if(!strncmp(cmd, "chgrp", 5)) { + const char *p = sshc->quote_path1; + curl_off_t gid; + if(!curlx_str_number(&p, &gid, ULONG_MAX)) { + sshp->quote_attrs.gid = (unsigned long)gid; + sshp->quote_attrs.flags = LIBSSH2_SFTP_ATTR_UIDGID; + } + else if(!sshc->acceptfail) { + failf(data, "Syntax error: chgrp gid not a number"); + goto fail; + } + } + else if(!strncmp(cmd, "chmod", 5)) { + curl_off_t perms; + const char *p = sshc->quote_path1; + /* permissions are octal */ + if(curlx_str_octal(&p, &perms, 07777)) { + failf(data, "Syntax error: chmod permissions not a number"); + goto fail; + } + + sshp->quote_attrs.permissions = (unsigned long)perms; + sshp->quote_attrs.flags = LIBSSH2_SFTP_ATTR_PERMISSIONS; + } + else if(!strncmp(cmd, "chown", 5)) { + const char *p = sshc->quote_path1; + curl_off_t uid; + if(!curlx_str_number(&p, &uid, ULONG_MAX)) { + sshp->quote_attrs.uid = (unsigned long)uid; + sshp->quote_attrs.flags = LIBSSH2_SFTP_ATTR_UIDGID; + } + else if(!sshc->acceptfail) { + failf(data, "Syntax error: chown uid not a number"); + goto fail; + } + } + else if(!strncmp(cmd, "atime", 5) || + !strncmp(cmd, "mtime", 5)) { + time_t date; + bool fail = FALSE; + + if(Curl_getdate_capped(sshc->quote_path1, &date)) { + failf(data, "incorrect date format for %.*s", 5, cmd); + fail = TRUE; + } +#if SIZEOF_TIME_T > SIZEOF_LONG + if(date > 0xffffffff) { + /* if 'long' cannot hold >32-bit, this date cannot be sent */ + failf(data, "date overflow"); + fail = TRUE; + } +#endif + if(fail) + goto fail; + if(!strncmp(cmd, "atime", 5)) + sshp->quote_attrs.atime = (unsigned long)date; + else /* mtime */ + sshp->quote_attrs.mtime = (unsigned long)date; + + sshp->quote_attrs.flags = LIBSSH2_SFTP_ATTR_ACMODTIME; + } + + /* Now send the completed structure... */ + myssh_to(data, sshc, SSH_SFTP_QUOTE_SETSTAT); + return CURLE_OK; +fail: + curlx_safefree(sshc->quote_path1); + curlx_safefree(sshc->quote_path2); + return CURLE_QUOTE_ERROR; +} + +static CURLcode sftp_download_stat(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool *blockp) +{ + LIBSSH2_SFTP_ATTRIBUTES attrs; + int rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + LIBSSH2_SFTP_STAT, &attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) { + *blockp = TRUE; + return CURLE_OK; + } + if(rc || + !(attrs.flags & LIBSSH2_SFTP_ATTR_SIZE) || + (attrs.filesize == 0)) { + /* + * libssh2_sftp_open() did not return an error, so maybe the server + * does not support stat() + * OR the server does not return a file size with a stat() + * OR file size is 0 + */ + data->req.size = -1; + data->req.maxdownload = -1; + Curl_pgrsSetDownloadSize(data, -1); + attrs.filesize = 0; /* might be uninitialized but is read below */ + } + else { + curl_off_t size = attrs.filesize; + + if(size < 0) { + failf(data, "Bad file size (%" FMT_OFF_T ")", size); + return CURLE_BAD_DOWNLOAD_RESUME; + } + if(data->state.use_range) { + curl_off_t from; + CURLcode result = Curl_ssh_range(data, data->state.range, size, + &from, &size); + if(result) + return result; + + libssh2_sftp_seek64(sshc->sftp_handle, (libssh2_uint64_t)from); + } + data->req.size = size; + data->req.maxdownload = size; + Curl_pgrsSetDownloadSize(data, size); + } + + /* We can resume if we can seek to the resume position */ + if(data->state.resume_from) { + if(data->state.resume_from < 0) { + /* We are supposed to download the last abs(from) bytes */ + if((curl_off_t)attrs.filesize < -data->state.resume_from) { + failf(data, "Offset (%" FMT_OFF_T ") was beyond file size (%" + FMT_OFF_T ")", + data->state.resume_from, (curl_off_t)attrs.filesize); + return CURLE_BAD_DOWNLOAD_RESUME; + } + /* download from where? */ + data->state.resume_from += attrs.filesize; + } + else { + if((curl_off_t)attrs.filesize < data->state.resume_from) { + failf(data, "Offset (%" FMT_OFF_T + ") was beyond file size (%" FMT_OFF_T ")", + data->state.resume_from, (curl_off_t)attrs.filesize); + return CURLE_BAD_DOWNLOAD_RESUME; + } + } + /* Now store the number of bytes we are expected to download */ + data->req.size = attrs.filesize - data->state.resume_from; + data->req.maxdownload = attrs.filesize - data->state.resume_from; + Curl_pgrsSetDownloadSize(data, attrs.filesize - data->state.resume_from); + libssh2_sftp_seek64(sshc->sftp_handle, + (libssh2_uint64_t)data->state.resume_from); + } + + /* Setup the actual download */ + if(data->req.size == 0) { + /* no data to transfer */ + Curl_xfer_setup_nop(data); + infof(data, "SSH: file already completely downloaded"); + myssh_to(data, sshc, SSH_STOP); + return CURLE_OK; + } + Curl_xfer_setup_recv(data, FIRSTSOCKET, data->req.size); + + /* not set by Curl_xfer_setup to preserve io_flags */ + data->conn->send_idx = 0; + + myssh_to(data, sshc, SSH_STOP); + + return CURLE_OK; +} + +static CURLcode sftp_readdir(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool *blockp) +{ + CURLcode result = CURLE_OK; + int rc = libssh2_sftp_readdir_ex(sshc->sftp_handle, + sshp->readdir_filename, CURL_PATH_MAX, + sshp->readdir_longentry, CURL_PATH_MAX, + &sshp->readdir_attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) { + *blockp = TRUE; + return result; + } + if(rc > 0) { + size_t readdir_len = (size_t)rc; + sshp->readdir_filename[readdir_len] = '\0'; + + if(data->set.list_only) { + result = Curl_client_write(data, CLIENTWRITE_BODY, + sshp->readdir_filename, + readdir_len); + if(!result) + result = Curl_client_write(data, CLIENTWRITE_BODY, "\n", 1); + if(result) + return result; + } + else { + result = curlx_dyn_add(&sshp->readdir, sshp->readdir_longentry); + + if(!result) { + if((sshp->readdir_attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) && + ((sshp->readdir_attrs.permissions & LIBSSH2_SFTP_S_IFMT) == + LIBSSH2_SFTP_S_IFLNK)) { + result = curlx_dyn_addf(&sshp->readdir_link, "%s%s", sshp->path, + sshp->readdir_filename); + myssh_to(data, sshc, SSH_SFTP_READDIR_LINK); + } + else { + myssh_to(data, sshc, SSH_SFTP_READDIR_BOTTOM); + } + } + return result; + } + } + else if(!rc) { + myssh_to(data, sshc, SSH_SFTP_READDIR_DONE); + } + else { + unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session); + result = sftperr ? sftp_libssh2_error_to_CURLE(sftperr) : CURLE_SSH; + failf(data, "Could not open remote file for reading: %s :: %d", + sftp_libssh2_strerror(sftperr), + libssh2_session_last_errno(sshc->ssh_session)); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + } + return result; +} + +static CURLcode ssh_state_init(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + CURLcode result; + sshc->secondCreateDirs = 0; + sshc->nextstate = SSH_NO_STATE; + + /* Set libssh2 to non-blocking, since everything internally is + non-blocking */ + libssh2_session_set_blocking(sshc->ssh_session, 0); + + result = ssh_force_knownhost_key_type(data, sshc); + if(result) + myssh_to(data, sshc, SSH_SESSION_FREE); + else + myssh_to(data, sshc, SSH_S_STARTUP); + return result; +} + +static CURLcode ssh_state_startup(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + struct connectdata *conn = data->conn; + int rc = libssh2_session_handshake(sshc->ssh_session, + conn->sock[FIRSTSOCKET]); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + failf(data, "Failure establishing ssh session: %d, %s", rc, err_msg); + + myssh_to(data, sshc, SSH_SESSION_FREE); + return CURLE_FAILED_INIT; + } + + myssh_to(data, sshc, SSH_HOSTKEY); + return CURLE_OK; +} + +static CURLcode ssh_state_hostkey(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + /* + * Before we authenticate we should check the hostkey's fingerprint + * against our known hosts. How that is handled (reading from file, + * whatever) is up to us. + */ + CURLcode result = ssh_check_fingerprint(data, sshc); + if(!result) + myssh_to(data, sshc, SSH_AUTHLIST); + return result; +} + +static CURLcode ssh_state_authlist(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + /* + * Figure out authentication methods + * NB: As soon as we have provided a username to an openssh server we + * must never change it later. Thus, always specify the correct username + * here, even though the libssh2 docs kind of indicate that it should be + * possible to get a 'generic' list (not user-specific) of authentication + * methods, presumably with a blank username. That does not work in my + * experience. + * Therefore always specify it here. + */ + struct connectdata *conn = data->conn; + const char *user = Curl_creds_user(conn->creds); + sshc->authlist = libssh2_userauth_list(sshc->ssh_session, + user, curlx_uztoui(strlen(user))); + + if(!sshc->authlist) { + int rc; + if(libssh2_userauth_authenticated(sshc->ssh_session)) { + sshc->authed = TRUE; + infof(data, "SSH: user accepted with no authentication"); + myssh_to(data, sshc, SSH_AUTH_DONE); + return CURLE_OK; + } + rc = libssh2_session_last_errno(sshc->ssh_session); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + myssh_to(data, sshc, SSH_SESSION_FREE); + return libssh2_session_error_to_CURLE(rc); + } + infof(data, "SSH: host offers authentication via: %s", sshc->authlist); + + myssh_to(data, sshc, SSH_AUTH_PKEY_INIT); + return CURLE_OK; +} + +static CURLcode ssh_state_auth_pkey(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + /* The function below checks if the files exists, no need to stat() here. + */ + struct connectdata *conn = data->conn; + const char *user = Curl_creds_user(conn->creds); + int rc = + libssh2_userauth_publickey_fromfile_ex(sshc->ssh_session, + user, + curlx_uztoui(strlen(user)), + sshc->pub_key, + sshc->priv_key, sshc->passphrase); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc == 0) { + sshc->authed = TRUE; + infof(data, "SSH: authenticated via publickey"); + myssh_to(data, sshc, SSH_AUTH_DONE); + } + else { + char *err_msg = NULL; + char unknown[] = "Reason unknown (-1)"; + if(rc == -1) { + /* No error message has been set and the last set error message, if + any, is from a previous error so ignore it. #11837 */ + err_msg = unknown; + } + else { + (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + } + infof(data, "SSH: publickey authentication denied: %s", err_msg); + myssh_to(data, sshc, SSH_AUTH_PASS_INIT); + } + return CURLE_OK; +} + +static CURLcode ssh_state_auth_pass_init(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if((data->set.ssh_auth_types & CURLSSH_AUTH_PASSWORD) && + strstr(sshc->authlist, "password")) { + myssh_to(data, sshc, SSH_AUTH_PASS); + } + else { + myssh_to(data, sshc, SSH_AUTH_HOST_INIT); + } + return CURLE_OK; +} + +static CURLcode ssh_state_auth_pass(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + struct connectdata *conn = data->conn; + const char *user = Curl_creds_user(conn->creds); + const char *passwd = Curl_creds_passwd(conn->creds); + int rc = + libssh2_userauth_password_ex(sshc->ssh_session, user, + curlx_uztoui(strlen(user)), + passwd, + curlx_uztoui(strlen(passwd)), + NULL); + if(rc == LIBSSH2_ERROR_EAGAIN) { + return CURLE_AGAIN; + } + if(rc == 0) { + sshc->authed = TRUE; + infof(data, "SSH: initialized password authentication"); + myssh_to(data, sshc, SSH_AUTH_DONE); + } + else { + myssh_to(data, sshc, SSH_AUTH_HOST_INIT); + } + return CURLE_OK; +} + +static CURLcode ssh_state_auth_host_init(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if((data->set.ssh_auth_types & CURLSSH_AUTH_HOST) && + strstr(sshc->authlist, "hostbased")) { + myssh_to(data, sshc, SSH_AUTH_HOST); + } + else { + myssh_to(data, sshc, SSH_AUTH_AGENT_INIT); + } + return CURLE_OK; +} + +static CURLcode ssh_state_auth_agent_init(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = 0; + if((data->set.ssh_auth_types & CURLSSH_AUTH_AGENT) && + strstr(sshc->authlist, "publickey")) { + + infof(data, "SSH: trying publickey authentication via agent"); + /* Connect to the ssh-agent */ + /* The agent could be shared by a curl thread i believe + but nothing obvious as keys can be added/removed at any time */ + if(!sshc->ssh_agent) { + sshc->ssh_agent = libssh2_agent_init(sshc->ssh_session); + if(!sshc->ssh_agent) { + infof(data, "SSH: could not create agent object"); + + myssh_to(data, sshc, SSH_AUTH_KEY_INIT); + return CURLE_OK; + } + } + + rc = libssh2_agent_connect(sshc->ssh_agent); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + if(rc < 0) { + infof(data, "SSH: failure connecting to agent"); + myssh_to(data, sshc, SSH_AUTH_KEY_INIT); + } + else { + myssh_to(data, sshc, SSH_AUTH_AGENT_LIST); + } + } + else + myssh_to(data, sshc, SSH_AUTH_KEY_INIT); + return CURLE_OK; +} + +static CURLcode ssh_state_auth_agent_list(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = libssh2_agent_list_identities(sshc->ssh_agent); + + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + if(rc < 0) { + infof(data, "SSH: failure requesting identities to agent"); + myssh_to(data, sshc, SSH_AUTH_KEY_INIT); + } + else { + myssh_to(data, sshc, SSH_AUTH_AGENT); + sshc->sshagent_prev_identity = NULL; + } + return CURLE_OK; +} + +static CURLcode ssh_state_auth_agent(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + /* as prev_identity evolves only after an identity user auth finished we + can safely request it again as long as EAGAIN is returned here or by + libssh2_agent_userauth */ + int rc = libssh2_agent_get_identity(sshc->ssh_agent, + &sshc->sshagent_identity, + sshc->sshagent_prev_identity); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc == 0) { + CURL_TRC_SSH(data, "[SSH_AUTH_AGENT_LIST] auth user '%s' for key '%s'", + Curl_creds_user(data->conn->creds), + sshc->sshagent_identity->comment); + rc = libssh2_agent_userauth(sshc->ssh_agent, + Curl_creds_user(data->conn->creds), + sshc->sshagent_identity); + + if(rc < 0) { + if(rc != LIBSSH2_ERROR_EAGAIN) { + /* tried and failed? go to next identity */ + sshc->sshagent_prev_identity = sshc->sshagent_identity; + return CURLE_OK; + } + return CURLE_AGAIN; + } + } + + if(rc < 0) + infof(data, "SSH: failure requesting identities to agent"); + else if(rc == 1) + infof(data, "SSH: no agent identity would match"); + + if(rc == LIBSSH2_ERROR_NONE) { + sshc->authed = TRUE; + infof(data, "SSH: agent authenticated user '%s' with key '%s'", + Curl_creds_user(data->conn->creds), + sshc->sshagent_identity->comment); + myssh_to(data, sshc, SSH_AUTH_DONE); + } + else { + myssh_to(data, sshc, SSH_AUTH_KEY_INIT); + } + return CURLE_OK; +} + +static CURLcode ssh_state_auth_key_init(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if((data->set.ssh_auth_types & CURLSSH_AUTH_KEYBOARD) && + strstr(sshc->authlist, "keyboard-interactive")) { + myssh_to(data, sshc, SSH_AUTH_KEY); + } + else { + myssh_to(data, sshc, SSH_AUTH_DONE); + } + return CURLE_OK; +} + +static CURLcode ssh_state_auth_key(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + /* Authentication failed. Continue with keyboard-interactive now. */ + struct connectdata *conn = data->conn; + const char *user = Curl_creds_user(conn->creds); + int rc = + libssh2_userauth_keyboard_interactive_ex(sshc->ssh_session, + user, curlx_uztoui(strlen(user)), + &kbd_callback); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc == 0) { + sshc->authed = TRUE; + infof(data, "SSH: initialized keyboard interactive authentication"); + myssh_to(data, sshc, SSH_AUTH_DONE); + return CURLE_OK; + } + return CURLE_LOGIN_DENIED; +} + +static CURLcode ssh_state_auth_done(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + struct connectdata *conn = data->conn; + if(!sshc->authed) { + failf(data, "Authentication failure"); + myssh_to(data, sshc, SSH_SESSION_FREE); + return CURLE_LOGIN_DENIED; + } + + /* + * At this point we have an authenticated ssh session. + */ + infof(data, "SSH: authentication complete"); + + Curl_pgrsTime(data, TIMER_APPCONNECT); /* SSH is connected */ + + data->conn->recv_idx = FIRSTSOCKET; + conn->send_idx = -1; + + if(conn->scheme->protocol == CURLPROTO_SFTP) { + myssh_to(data, sshc, SSH_SFTP_INIT); + return CURLE_OK; + } + infof(data, "SSH: connection established"); + myssh_to(data, sshc, SSH_STOP); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_init(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + /* + * Start the libssh2 sftp session + */ + sshc->sftp_session = libssh2_sftp_init(sshc->ssh_session); + if(!sshc->sftp_session) { + char *err_msg = NULL; + if(libssh2_session_last_errno(sshc->ssh_session) == + LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + failf(data, "Failure initializing sftp session: %s", err_msg); + myssh_to(data, sshc, SSH_SESSION_FREE); + return CURLE_FAILED_INIT; + } + myssh_to(data, sshc, SSH_SFTP_REALPATH); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_realpath(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + /* + * Get the "home" directory + */ + int rc; + + if(!sshp) + return CURLE_FAILED_INIT; + + rc = libssh2_sftp_symlink_ex(sshc->sftp_session, ".", + curlx_uztoui(CURL_CSTRLEN(".")), + sshp->readdir_filename, CURL_PATH_MAX, + LIBSSH2_SFTP_REALPATH); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + myssh_to(data, sshc, SSH_STOP); + if(rc > 0) { + curlx_free(sshc->homedir); + sshc->homedir = curlx_strdup(sshp->readdir_filename); + if(!sshc->homedir) + return CURLE_OUT_OF_MEMORY; + curlx_free(data->state.most_recent_ftp_entrypath); + data->state.most_recent_ftp_entrypath = curlx_strdup(sshc->homedir); + if(!data->state.most_recent_ftp_entrypath) + return CURLE_OUT_OF_MEMORY; + } + else { + /* Return the error type */ + unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session); + CURLcode result; + if(sftperr) + result = sftp_libssh2_error_to_CURLE(sftperr); + else + /* in this case, the error was not in the SFTP level but for example a + time-out or similar */ + result = CURLE_SSH; + CURL_TRC_SSH(data, "error = %lu makes libcurl = %d", sftperr, (int)result); + return result; + } + + /* This is the last step in the SFTP connect phase. Do note that while we + get the homedir here, we get the "workingpath" in the DO action since the + homedir remains the same between request but the working path does not. */ + CURL_TRC_SSH(data, "CONNECT phase done"); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_quote_init(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + CURLcode result; + + if(!sshp) + return CURLE_FAILED_INIT; + + result = Curl_getworkingpath(data, sshc->homedir, &sshp->path); + if(result) { + myssh_to(data, sshc, SSH_STOP); + return result; + } + + if(data->set.quote) { + infof(data, "SSH: sending quote commands"); + sshc->quote_item = data->set.quote; + myssh_to(data, sshc, SSH_SFTP_QUOTE); + } + else { + myssh_to(data, sshc, SSH_SFTP_GETINFO); + } + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_postquote_init(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(data->set.postquote) { + infof(data, "SSH: sending quote commands"); + sshc->quote_item = data->set.postquote; + myssh_to(data, sshc, SSH_SFTP_QUOTE); + } + else { + myssh_to(data, sshc, SSH_STOP); + } + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_quote(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + /* Send quote commands */ + CURLcode result; + + if(!sshp) + return CURLE_FAILED_INIT; + + result = sftp_quote(data, sshc, sshp); + if(result) { + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + } + return result; +} + +static CURLcode ssh_state_sftp_next_quote(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + curlx_safefree(sshc->quote_path1); + curlx_safefree(sshc->quote_path2); + + sshc->quote_item = sshc->quote_item->next; + + if(sshc->quote_item) { + myssh_to(data, sshc, SSH_SFTP_QUOTE); + } + else { + if(sshc->nextstate != SSH_NO_STATE) { + myssh_to(data, sshc, sshc->nextstate); + sshc->nextstate = SSH_NO_STATE; + } + else { + myssh_to(data, sshc, SSH_SFTP_GETINFO); + } + } + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_quote_stat(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool *blockp) +{ + CURLcode result; + + if(!sshp) + return CURLE_FAILED_INIT; + + result = sftp_quote_stat(data, sshc, sshp, blockp); + if(result) { + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + } + return result; +} + +static CURLcode ssh_state_sftp_quote_setstat(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + int rc; + + if(!sshp) + return CURLE_FAILED_INIT; + + rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshc->quote_path2, + curlx_uztoui(strlen(sshc->quote_path2)), + LIBSSH2_SFTP_SETSTAT, + &sshp->quote_attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc && !sshc->acceptfail) { + unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session); + failf(data, "Attempt to set SFTP stats for \"%s\" failed: %s", + sshc->quote_path2, sftp_libssh2_strerror(sftperr)); + curlx_safefree(sshc->quote_path1); + curlx_safefree(sshc->quote_path2); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + return CURLE_QUOTE_ERROR; + } + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_quote_symlink(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = + libssh2_sftp_symlink_ex(sshc->sftp_session, sshc->quote_path1, + curlx_uztoui(strlen(sshc->quote_path1)), + sshc->quote_path2, + curlx_uztoui(strlen(sshc->quote_path2)), + LIBSSH2_SFTP_SYMLINK); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc && !sshc->acceptfail) { + unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session); + failf(data, "symlink \"%s\" to \"%s\" failed: %s", + sshc->quote_path1, sshc->quote_path2, + sftp_libssh2_strerror(sftperr)); + curlx_safefree(sshc->quote_path1); + curlx_safefree(sshc->quote_path2); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + return CURLE_QUOTE_ERROR; + } + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_quote_mkdir(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = libssh2_sftp_mkdir_ex(sshc->sftp_session, sshc->quote_path1, + curlx_uztoui(strlen(sshc->quote_path1)), + (long)data->set.new_directory_perms); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc && !sshc->acceptfail) { + unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session); + failf(data, "mkdir \"%s\" failed: %s", + sshc->quote_path1, sftp_libssh2_strerror(sftperr)); + curlx_safefree(sshc->quote_path1); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + return CURLE_QUOTE_ERROR; + } + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_quote_rename(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = + libssh2_sftp_rename_ex(sshc->sftp_session, sshc->quote_path1, + curlx_uztoui(strlen(sshc->quote_path1)), + sshc->quote_path2, + curlx_uztoui(strlen(sshc->quote_path2)), + LIBSSH2_SFTP_RENAME_OVERWRITE | + LIBSSH2_SFTP_RENAME_ATOMIC | + LIBSSH2_SFTP_RENAME_NATIVE); + + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc && !sshc->acceptfail) { + unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session); + failf(data, "rename \"%s\" to \"%s\" failed: %s", + sshc->quote_path1, sshc->quote_path2, + sftp_libssh2_strerror(sftperr)); + curlx_safefree(sshc->quote_path1); + curlx_safefree(sshc->quote_path2); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + return CURLE_QUOTE_ERROR; + } + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_quote_rmdir(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = libssh2_sftp_rmdir_ex(sshc->sftp_session, sshc->quote_path1, + curlx_uztoui(strlen(sshc->quote_path1))); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc && !sshc->acceptfail) { + unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session); + failf(data, "rmdir \"%s\" failed: %s", + sshc->quote_path1, sftp_libssh2_strerror(sftperr)); + curlx_safefree(sshc->quote_path1); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + return CURLE_QUOTE_ERROR; + } + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_quote_unlink(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + int rc = libssh2_sftp_unlink_ex(sshc->sftp_session, sshc->quote_path1, + curlx_uztoui(strlen(sshc->quote_path1))); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc && !sshc->acceptfail) { + unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session); + failf(data, "rm \"%s\" failed: %s", + sshc->quote_path1, sftp_libssh2_strerror(sftperr)); + curlx_safefree(sshc->quote_path1); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + return CURLE_QUOTE_ERROR; + } + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_quote_statvfs(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + LIBSSH2_SFTP_STATVFS statvfs; + int rc = libssh2_sftp_statvfs(sshc->sftp_session, sshc->quote_path1, + curlx_uztoui(strlen(sshc->quote_path1)), + &statvfs); + + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc && !sshc->acceptfail) { + unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session); + failf(data, "statvfs \"%s\" failed: %s", + sshc->quote_path1, sftp_libssh2_strerror(sftperr)); + curlx_safefree(sshc->quote_path1); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + return CURLE_QUOTE_ERROR; + } + else if(rc == 0) { +#ifdef _MSC_VER +#define CURL_LIBSSH2_VFS_SIZE_MASK "I64u" +#else +#define CURL_LIBSSH2_VFS_SIZE_MASK "llu" +#endif + CURLcode result; + char *tmp = curl_maprintf("statvfs:\n" + "f_bsize: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_frsize: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_blocks: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_bfree: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_bavail: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_files: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_ffree: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_favail: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_fsid: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_flag: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n" + "f_namemax: %" CURL_LIBSSH2_VFS_SIZE_MASK "\n", + statvfs.f_bsize, statvfs.f_frsize, + statvfs.f_blocks, statvfs.f_bfree, + statvfs.f_bavail, statvfs.f_files, + statvfs.f_ffree, statvfs.f_favail, + statvfs.f_fsid, statvfs.f_flag, + statvfs.f_namemax); + if(!tmp) { + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + return CURLE_OUT_OF_MEMORY; + } + + result = Curl_client_write(data, CLIENTWRITE_HEADER, tmp, strlen(tmp)); + curlx_free(tmp); + if(result) { + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + return result; + } + } + myssh_to(data, sshc, SSH_SFTP_NEXT_QUOTE); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_create_dirs_mkdir(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + /* 'mode' - parameter is preliminary - default to 0644 */ + int rc; + + if(!sshp) + return CURLE_FAILED_INIT; + + rc = libssh2_sftp_mkdir_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + (long)data->set.new_directory_perms); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + *sshc->slash_pos = '/'; + ++sshc->slash_pos; + if(rc < 0) { + /* + * Abort if failure was not that the directory already exists or + * the permission was denied (creation might succeed further down + * the path) - retry on unspecific FAILURE also + */ + unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session); + if((sftperr != LIBSSH2_FX_FILE_ALREADY_EXISTS) && + (sftperr != LIBSSH2_FX_FAILURE) && + (sftperr != LIBSSH2_FX_PERMISSION_DENIED)) { + myssh_to(data, sshc, SSH_SFTP_CLOSE); + return sftp_libssh2_error_to_CURLE(sftperr); + } + } + myssh_to(data, sshc, SSH_SFTP_CREATE_DIRS); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_readdir_init(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + if(!sshp) + return CURLE_FAILED_INIT; + + Curl_pgrsSetDownloadSize(data, -1); + if(data->req.no_body) { + myssh_to(data, sshc, SSH_STOP); + return CURLE_OK; + } + + /* + * This is a directory that we are trying to get, so produce a directory + * listing + */ + sshc->sftp_handle = + libssh2_sftp_open_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + 0, 0, LIBSSH2_SFTP_OPENDIR); + if(!sshc->sftp_handle) { + unsigned long sftperr; + if(libssh2_session_last_errno(sshc->ssh_session) == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + failf(data, "Could not open directory for reading: %s", + sftp_libssh2_strerror(sftperr)); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + return sftp_libssh2_error_to_CURLE(sftperr); + } + myssh_to(data, sshc, SSH_SFTP_READDIR); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_readdir_link(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + CURLcode result; + int rc; + if(!sshp) + return CURLE_FAILED_INIT; + + rc = libssh2_sftp_symlink_ex(sshc->sftp_session, + curlx_dyn_ptr(&sshp->readdir_link), + (unsigned int) + curlx_dyn_len(&sshp->readdir_link), + sshp->readdir_filename, + CURL_PATH_MAX, LIBSSH2_SFTP_READLINK); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + curlx_dyn_free(&sshp->readdir_link); + + if(rc < 0) + return CURLE_OUT_OF_MEMORY; + + /* append filename and extra output */ + result = curlx_dyn_addf(&sshp->readdir, " -> %s", sshp->readdir_filename); + if(result) + myssh_to(data, sshc, SSH_SFTP_CLOSE); + else + myssh_to(data, sshc, SSH_SFTP_READDIR_BOTTOM); + return result; +} + +static CURLcode ssh_state_scp_download_init(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + curl_off_t bytecount; + libssh2_struct_stat sb; + + if(!sshp) + return CURLE_FAILED_INIT; + /* + * We must check the remote file; if it is a directory no values are + * be set in sb + */ + + /* + * If support for >2GB files exists, use it. + */ + + /* get a fresh new channel from the ssh layer */ + memset(&sb, 0, sizeof(libssh2_struct_stat)); + sshc->ssh_channel = libssh2_scp_recv2(sshc->ssh_session, sshp->path, &sb); + if(!sshc->ssh_channel) { + int ssh_err; + char *err_msg = NULL; + + if(libssh2_session_last_errno(sshc->ssh_session) == + LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + ssh_err = libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + failf(data, "%s", err_msg); + myssh_to(data, sshc, SSH_SCP_CHANNEL_FREE); + return libssh2_session_error_to_CURLE(ssh_err); + } + + /* download data */ + bytecount = (curl_off_t)sb.st_size; + data->req.maxdownload = (curl_off_t)sb.st_size; + Curl_xfer_setup_recv(data, FIRSTSOCKET, bytecount); + + /* not set by Curl_xfer_setup to preserve io_flags */ + data->conn->send_idx = 0; + + myssh_to(data, sshc, SSH_STOP); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_close(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + int rc = 0; + if(!sshp) + return CURLE_FAILED_INIT; + if(sshc->sftp_handle) { + rc = libssh2_sftp_close(sshc->sftp_handle); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc < 0) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + infof(data, "Failed to close libssh2 file: %d %s", rc, err_msg); + } + sshc->sftp_handle = NULL; + } + + curlx_safefree(sshp->path); + + CURL_TRC_SSH(data, "SFTP DONE done"); + + /* Check if nextstate is set and move .nextstate could be POSTQUOTE_INIT + After nextstate is executed, the control should come back to + SSH_SFTP_CLOSE to pass the correct result back */ + if(sshc->nextstate != SSH_NO_STATE && + sshc->nextstate != SSH_SFTP_CLOSE) { + myssh_to(data, sshc, sshc->nextstate); + sshc->nextstate = SSH_SFTP_CLOSE; + } + else + myssh_to(data, sshc, SSH_STOP); + + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_shutdown(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + /* during times we get here due to a broken transfer and then the + sftp_handle might not have been taken down so make sure that is done + before we proceed */ + int rc = 0; + if(sshc->sftp_handle) { + rc = libssh2_sftp_close(sshc->sftp_handle); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc < 0) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + infof(data, "Failed to close libssh2 file: %d %s", rc, err_msg); + } + sshc->sftp_handle = NULL; + } + if(sshc->sftp_session) { + rc = libssh2_sftp_shutdown(sshc->sftp_session); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc < 0) { + infof(data, "Failed to stop libssh2 sftp subsystem"); + } + sshc->sftp_session = NULL; + } + + curlx_safefree(sshc->homedir); + + myssh_to(data, sshc, SSH_SESSION_DISCONNECT); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_download_init(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + if(!sshp) + return CURLE_FAILED_INIT; + /* + * Work on getting the specified file + */ + sshc->sftp_handle = + libssh2_sftp_open_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + LIBSSH2_FXF_READ, (long)data->set.new_file_perms, + LIBSSH2_SFTP_OPENFILE); + if(!sshc->sftp_handle) { + unsigned long sftperr; + if(libssh2_session_last_errno(sshc->ssh_session) == + LIBSSH2_ERROR_EAGAIN) { + return CURLE_AGAIN; + } + sftperr = libssh2_sftp_last_error(sshc->sftp_session); + failf(data, "Could not open remote file for reading: %s", + sftp_libssh2_strerror(sftperr)); + myssh_to(data, sshc, SSH_SFTP_CLOSE); + return sftp_libssh2_error_to_CURLE(sftperr); + } + myssh_to(data, sshc, SSH_SFTP_DOWNLOAD_STAT); + return CURLE_OK; +} + +static CURLcode ssh_state_scp_upload_init(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + if(!sshp) + return CURLE_FAILED_INIT; + /* + * libssh2 requires that the destination path is a full path that + * includes the destination file and name OR ends in a "/" . If this is + * not done the destination file is named the same name as the last + * directory in the path. + */ + sshc->ssh_channel = + libssh2_scp_send64(sshc->ssh_session, sshp->path, + (int)data->set.new_file_perms, + (libssh2_int64_t)data->state.infilesize, 0, 0); + if(!sshc->ssh_channel) { + int ssh_err; + char *err_msg = NULL; + CURLcode result; + if(libssh2_session_last_errno(sshc->ssh_session) == + LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + ssh_err = libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + failf(data, "%s", err_msg); + myssh_to(data, sshc, SSH_SCP_CHANNEL_FREE); + result = libssh2_session_error_to_CURLE(ssh_err); + + /* Map generic errors to upload failed */ + if(result == CURLE_SSH || + result == CURLE_REMOTE_FILE_NOT_FOUND) + result = CURLE_UPLOAD_FAILED; + return result; + } + + /* upload data */ + data->req.size = data->state.infilesize; + Curl_pgrsSetUploadSize(data, data->state.infilesize); + Curl_xfer_setup_send(data, FIRSTSOCKET); + + /* not set by Curl_xfer_setup to preserve io_flags */ + data->conn->recv_idx = FIRSTSOCKET; + + myssh_to(data, sshc, SSH_STOP); + + return CURLE_OK; +} + +static CURLcode ssh_state_session_disconnect(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + /* during weird times when we have been prematurely aborted, the channel + is still alive when we reach this state and we MUST kill the channel + properly first */ + int rc = 0; + if(sshc->ssh_channel) { + rc = libssh2_channel_free(sshc->ssh_channel); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc < 0) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + infof(data, "Failed to free libssh2 scp subsystem: %d %s", rc, err_msg); + } + sshc->ssh_channel = NULL; + } + + if(sshc->ssh_session) { + rc = libssh2_session_disconnect(sshc->ssh_session, "Shutdown"); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc < 0) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + infof(data, "Failed to disconnect libssh2 session: %d %s", rc, err_msg); + } + } + + curlx_safefree(sshc->homedir); + + myssh_to(data, sshc, SSH_SESSION_FREE); + return CURLE_OK; +} + +static CURLcode sshc_cleanup(struct ssh_conn *sshc, struct Curl_easy *data, + bool block) +{ + int rc; + + if(sshc->kh) { + libssh2_knownhost_free(sshc->kh); + sshc->kh = NULL; + } + + if(sshc->ssh_agent) { + rc = libssh2_agent_disconnect(sshc->ssh_agent); + if((rc < 0) && data) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + infof(data, "Failed to disconnect from libssh2 agent: %d %s", + rc, err_msg); + } + if(!block && (rc == LIBSSH2_ERROR_EAGAIN)) + return CURLE_AGAIN; + + libssh2_agent_free(sshc->ssh_agent); + sshc->ssh_agent = NULL; + + /* NB: there is no need to free identities, they are part of internal + agent stuff */ + sshc->sshagent_identity = NULL; + sshc->sshagent_prev_identity = NULL; + } + + if(sshc->sftp_handle) { + rc = libssh2_sftp_close(sshc->sftp_handle); + if((rc < 0) && data) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + infof(data, "Failed to close libssh2 file: %d %s", rc, err_msg); + } + if(!block && (rc == LIBSSH2_ERROR_EAGAIN)) + return CURLE_AGAIN; + + sshc->sftp_handle = NULL; + } + + if(sshc->ssh_channel) { + rc = libssh2_channel_free(sshc->ssh_channel); + if((rc < 0) && data) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + infof(data, "Failed to free libssh2 scp subsystem: %d %s", rc, err_msg); + } + if(!block && (rc == LIBSSH2_ERROR_EAGAIN)) + return CURLE_AGAIN; + + sshc->ssh_channel = NULL; + } + + if(sshc->sftp_session) { + rc = libssh2_sftp_shutdown(sshc->sftp_session); + if((rc < 0) && data) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + infof(data, "Failed to stop libssh2 sftp subsystem: %d %s", rc, err_msg); + } + if(!block && (rc == LIBSSH2_ERROR_EAGAIN)) + return CURLE_AGAIN; + + sshc->sftp_session = NULL; + } + + if(sshc->ssh_session) { + rc = libssh2_session_free(sshc->ssh_session); + if((rc < 0) && data) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); + infof(data, "Failed to free libssh2 session: %d %s", rc, err_msg); + } + if(!block && (rc == LIBSSH2_ERROR_EAGAIN)) + return CURLE_AGAIN; + + sshc->ssh_session = NULL; + } + + /* worst-case scenario cleanup */ + DEBUGASSERT(!sshc->ssh_session); + DEBUGASSERT(!sshc->ssh_channel); + DEBUGASSERT(!sshc->sftp_session); + DEBUGASSERT(!sshc->sftp_handle); + DEBUGASSERT(!sshc->kh); + DEBUGASSERT(!sshc->ssh_agent); + + curlx_safefree(sshc->pub_key); + curlx_safefree(sshc->priv_key); + curlx_safefree(sshc->quote_path1); + curlx_safefree(sshc->quote_path2); + curlx_safefree(sshc->homedir); + + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_getinfo(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(data->set.get_filetime) + myssh_to(data, sshc, SSH_SFTP_FILETIME); + else + myssh_to(data, sshc, SSH_SFTP_TRANS_INIT); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_filetime(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + LIBSSH2_SFTP_ATTRIBUTES attrs; + int rc; + + if(!sshp) + return CURLE_FAILED_INIT; + + rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + LIBSSH2_SFTP_STAT, &attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + if(rc == 0) + data->info.filetime = (time_t)attrs.mtime; + + myssh_to(data, sshc, SSH_SFTP_TRANS_INIT); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_trans_init(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + if(data->state.upload) + myssh_to(data, sshc, SSH_SFTP_UPLOAD_INIT); + else if(sshp) { + size_t plen = strlen(sshp->path); + if(plen && (sshp->path[plen - 1] == '/')) + myssh_to(data, sshc, SSH_SFTP_READDIR_INIT); + else + myssh_to(data, sshc, SSH_SFTP_DOWNLOAD_INIT); + } + else + return CURLE_FAILED_INIT; + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_upload_init(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool *block) +{ + CURLcode result; + if(!sshp) + return CURLE_FAILED_INIT; + result = sftp_upload_init(data, sshc, sshp, block); + if(result) { + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + } + return result; +} + +static CURLcode ssh_state_sftp_create_dirs_init(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + if(!sshp) + return CURLE_FAILED_INIT; + if(strlen(sshp->path) > 1) { + sshc->slash_pos = sshp->path + 1; /* ignore the leading '/' */ + myssh_to(data, sshc, SSH_SFTP_CREATE_DIRS); + } + else + myssh_to(data, sshc, SSH_SFTP_UPLOAD_INIT); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_create_dirs(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + if(!sshp) + return CURLE_FAILED_INIT; + sshc->slash_pos = strchr(sshc->slash_pos, '/'); + if(sshc->slash_pos) { + *sshc->slash_pos = 0; + infof(data, "SFTP: creating directory '%s'", sshp->path); + myssh_to(data, sshc, SSH_SFTP_CREATE_DIRS_MKDIR); + return CURLE_OK; + } + myssh_to(data, sshc, SSH_SFTP_UPLOAD_INIT); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_readdir(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool *block) +{ + CURLcode result; + if(!sshp) + return CURLE_FAILED_INIT; + result = sftp_readdir(data, sshc, sshp, block); + if(result) + myssh_to(data, sshc, SSH_SFTP_CLOSE); + return result; +} + +static CURLcode ssh_state_sftp_readdir_bottom(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + CURLcode result; + if(!sshp) + return CURLE_FAILED_INIT; + + result = curlx_dyn_addn(&sshp->readdir, "\n", 1); + if(!result) + result = Curl_client_write(data, CLIENTWRITE_BODY, + curlx_dyn_ptr(&sshp->readdir), + curlx_dyn_len(&sshp->readdir)); + if(result) { + curlx_dyn_free(&sshp->readdir); + myssh_to(data, sshc, SSH_STOP); + } + else { + curlx_dyn_reset(&sshp->readdir); + myssh_to(data, sshc, SSH_SFTP_READDIR); + } + return result; +} + +static CURLcode ssh_state_sftp_readdir_done(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(libssh2_sftp_closedir(sshc->sftp_handle) == + LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + + sshc->sftp_handle = NULL; + + /* no data to transfer */ + Curl_xfer_setup_nop(data); + myssh_to(data, sshc, SSH_STOP); + return CURLE_OK; +} + +static CURLcode ssh_state_sftp_download_stat(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool *block) +{ + CURLcode result; + if(!sshp) + return CURLE_FAILED_INIT; + result = sftp_download_stat(data, sshc, sshp, block); + if(result) { + myssh_to(data, sshc, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + } + return result; +} + +static CURLcode ssh_state_scp_trans_init(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + CURLcode result; + if(!sshp) + return CURLE_FAILED_INIT; + result = Curl_getworkingpath(data, sshc->homedir, + &sshp->path); + if(result) { + myssh_to(data, sshc, SSH_STOP); + return result; + } + + if(data->state.upload) { + if(data->state.infilesize < 0) { + failf(data, "SCP requires a known file size for upload"); + myssh_to(data, sshc, SSH_SCP_CHANNEL_FREE); + return CURLE_UPLOAD_FAILED; + } + myssh_to(data, sshc, SSH_SCP_UPLOAD_INIT); + } + else + myssh_to(data, sshc, SSH_SCP_DOWNLOAD_INIT); + return CURLE_OK; +} + +static CURLcode ssh_state_scp_done(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(data->state.upload) + myssh_to(data, sshc, SSH_SCP_SEND_EOF); + else + myssh_to(data, sshc, SSH_SCP_CHANNEL_FREE); + return CURLE_OK; +} + +static CURLcode ssh_state_scp_send_eof(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(sshc->ssh_channel) { + int rc = libssh2_channel_send_eof(sshc->ssh_channel); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + if(rc) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + infof(data, "Failed to send libssh2 channel EOF: %d %s", + rc, err_msg); + } + } + myssh_to(data, sshc, SSH_SCP_WAIT_EOF); + return CURLE_OK; +} + +static CURLcode ssh_state_scp_wait_eof(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(sshc->ssh_channel) { + int rc = libssh2_channel_wait_eof(sshc->ssh_channel); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + if(rc) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + infof(data, "Failed to get channel EOF: %d %s", rc, err_msg); + } + } + myssh_to(data, sshc, SSH_SCP_WAIT_CLOSE); + return CURLE_OK; +} + +static CURLcode ssh_state_scp_wait_close(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(sshc->ssh_channel) { + int rc = + libssh2_channel_wait_closed(sshc->ssh_channel); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + if(rc) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + infof(data, "Channel failed to close: %d %s", rc, err_msg); + } + } + myssh_to(data, sshc, SSH_SCP_CHANNEL_FREE); + return CURLE_OK; +} + +static CURLcode ssh_state_scp_channel_free( + struct Curl_easy *data, + struct ssh_conn *sshc) +{ + if(sshc->ssh_channel) { + int rc = libssh2_channel_free(sshc->ssh_channel); + if(rc == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + if(rc < 0) { + char *err_msg = NULL; + (void)libssh2_session_last_error(sshc->ssh_session, + &err_msg, NULL, 0); + infof(data, "Failed to free libssh2 scp subsystem: %d %s", rc, err_msg); + } + sshc->ssh_channel = NULL; + } + CURL_TRC_SSH(data, "SCP DONE phase complete"); + myssh_to(data, sshc, SSH_STOP); + return CURLE_OK; +} + +static CURLcode ssh_state_session_free(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + CURLcode result = sshc_cleanup(sshc, data, FALSE); + struct connectdata *conn = data->conn; + if(result) + return result; + memset(sshc, 0, sizeof(struct ssh_conn)); + connclose(conn); + sshc->state = SSH_SESSION_FREE; /* current */ + myssh_to(data, sshc, SSH_STOP); + return CURLE_OK; +} + +/* + * ssh_statemachine() runs the SSH state machine as far as it can without + * blocking and without reaching the end. The data the pointer 'block' points + * to is set to TRUE if the libssh2 function returns LIBSSH2_ERROR_EAGAIN + * meaning it wants to be called again when the socket is ready + */ +static CURLcode ssh_statemachine(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool *block) +{ + CURLcode result = CURLE_OK; + *block = 0; /* we are not blocking by default */ + + do { + switch(sshc->state) { + case SSH_INIT: + result = ssh_state_init(data, sshc); + if(result) + break; + FALLTHROUGH(); + + case SSH_S_STARTUP: + result = ssh_state_startup(data, sshc); + if(result) + break; + FALLTHROUGH(); + + case SSH_HOSTKEY: + result = ssh_state_hostkey(data, sshc); + break; + + case SSH_AUTHLIST: + result = ssh_state_authlist(data, sshc); + break; + + case SSH_AUTH_PKEY_INIT: + ssh_state_pkey_init(data, sshc); + break; + + case SSH_AUTH_PKEY: + result = ssh_state_auth_pkey(data, sshc); + break; + + case SSH_AUTH_PASS_INIT: + result = ssh_state_auth_pass_init(data, sshc); + break; + + case SSH_AUTH_PASS: + result = ssh_state_auth_pass(data, sshc); + break; + + case SSH_AUTH_HOST_INIT: + result = ssh_state_auth_host_init(data, sshc); + break; + + case SSH_AUTH_HOST: + myssh_to(data, sshc, SSH_AUTH_AGENT_INIT); + break; + + case SSH_AUTH_AGENT_INIT: + result = ssh_state_auth_agent_init(data, sshc); + break; + + case SSH_AUTH_AGENT_LIST: + result = ssh_state_auth_agent_list(data, sshc); + break; + + case SSH_AUTH_AGENT: + result = ssh_state_auth_agent(data, sshc); + break; + + case SSH_AUTH_KEY_INIT: + result = ssh_state_auth_key_init(data, sshc); + break; + + case SSH_AUTH_KEY: + result = ssh_state_auth_key(data, sshc); + break; + + case SSH_AUTH_DONE: + result = ssh_state_auth_done(data, sshc); + break; + + case SSH_SFTP_INIT: + result = ssh_state_sftp_init(data, sshc); + break; + + case SSH_SFTP_REALPATH: + result = ssh_state_sftp_realpath(data, sshc, sshp); + break; + + case SSH_SFTP_QUOTE_INIT: + result = ssh_state_sftp_quote_init(data, sshc, sshp); + break; + + case SSH_SFTP_POSTQUOTE_INIT: + result = ssh_state_sftp_postquote_init(data, sshc); + break; + + case SSH_SFTP_QUOTE: + result = ssh_state_sftp_quote(data, sshc, sshp); + break; + + case SSH_SFTP_NEXT_QUOTE: + result = ssh_state_sftp_next_quote(data, sshc); + break; + + case SSH_SFTP_QUOTE_STAT: + result = ssh_state_sftp_quote_stat(data, sshc, sshp, block); + break; + + case SSH_SFTP_QUOTE_SETSTAT: + result = ssh_state_sftp_quote_setstat(data, sshc, sshp); + break; + + case SSH_SFTP_QUOTE_SYMLINK: + result = ssh_state_sftp_quote_symlink(data, sshc); + break; + + case SSH_SFTP_QUOTE_MKDIR: + result = ssh_state_sftp_quote_mkdir(data, sshc); + break; + + case SSH_SFTP_QUOTE_RENAME: + result = ssh_state_sftp_quote_rename(data, sshc); + break; + + case SSH_SFTP_QUOTE_RMDIR: + result = ssh_state_sftp_quote_rmdir(data, sshc); + break; + + case SSH_SFTP_QUOTE_UNLINK: + result = ssh_state_sftp_quote_unlink(data, sshc); + break; + + case SSH_SFTP_QUOTE_STATVFS: + result = ssh_state_sftp_quote_statvfs(data, sshc); + break; + + case SSH_SFTP_GETINFO: + result = ssh_state_sftp_getinfo(data, sshc); + break; + + case SSH_SFTP_FILETIME: + result = ssh_state_sftp_filetime(data, sshc, sshp); + break; + + case SSH_SFTP_TRANS_INIT: + result = ssh_state_sftp_trans_init(data, sshc, sshp); + break; + + case SSH_SFTP_UPLOAD_INIT: + result = ssh_state_sftp_upload_init(data, sshc, sshp, block); + break; + + case SSH_SFTP_CREATE_DIRS_INIT: + result = ssh_state_sftp_create_dirs_init(data, sshc, sshp); + break; + + case SSH_SFTP_CREATE_DIRS: + result = ssh_state_sftp_create_dirs(data, sshc, sshp); + break; + + case SSH_SFTP_CREATE_DIRS_MKDIR: + result = ssh_state_sftp_create_dirs_mkdir(data, sshc, sshp); + break; + + case SSH_SFTP_READDIR_INIT: + result = ssh_state_sftp_readdir_init(data, sshc, sshp); + break; + + case SSH_SFTP_READDIR: + result = ssh_state_sftp_readdir(data, sshc, sshp, block); + break; + + case SSH_SFTP_READDIR_LINK: + result = ssh_state_sftp_readdir_link(data, sshc, sshp); + break; + + case SSH_SFTP_READDIR_BOTTOM: + result = ssh_state_sftp_readdir_bottom(data, sshc, sshp); + break; + + case SSH_SFTP_READDIR_DONE: + result = ssh_state_sftp_readdir_done(data, sshc); + break; + + case SSH_SFTP_DOWNLOAD_INIT: + result = ssh_state_sftp_download_init(data, sshc, sshp); + break; + + case SSH_SFTP_DOWNLOAD_STAT: + result = ssh_state_sftp_download_stat(data, sshc, sshp, block); + break; + + case SSH_SFTP_CLOSE: + result = ssh_state_sftp_close(data, sshc, sshp); + break; + + case SSH_SFTP_SHUTDOWN: + result = ssh_state_sftp_shutdown(data, sshc); + break; + + case SSH_SCP_TRANS_INIT: + result = ssh_state_scp_trans_init(data, sshc, sshp); + break; + + case SSH_SCP_UPLOAD_INIT: + result = ssh_state_scp_upload_init(data, sshc, sshp); + break; + + case SSH_SCP_DOWNLOAD_INIT: + result = ssh_state_scp_download_init(data, sshc, sshp); + break; + + case SSH_SCP_DONE: + result = ssh_state_scp_done(data, sshc); + break; + + case SSH_SCP_SEND_EOF: + result = ssh_state_scp_send_eof(data, sshc); + break; + + case SSH_SCP_WAIT_EOF: + result = ssh_state_scp_wait_eof(data, sshc); + break; + + case SSH_SCP_WAIT_CLOSE: + result = ssh_state_scp_wait_close(data, sshc); + break; + + case SSH_SCP_CHANNEL_FREE: + result = ssh_state_scp_channel_free(data, sshc); + break; + + case SSH_SESSION_DISCONNECT: + result = ssh_state_session_disconnect(data, sshc); + break; + + case SSH_SESSION_FREE: + result = ssh_state_session_free(data, sshc); + break; + + case SSH_QUIT: + default: + /* internal error */ + myssh_to(data, sshc, SSH_STOP); + break; + } + + } while(!result && (sshc->state != SSH_STOP) && !*block); + + if(result == CURLE_AGAIN) { + /* we would block, we need to wait for the socket to be ready (in the + right direction too)! */ + *block = TRUE; + result = CURLE_OK; + } + CURL_TRC_SSH(data, "[%s] statemachine() -> %d, block=%d", + Curl_ssh_statename(sshc->state), (int)result, *block); + + return result; +} + +/* + * When one of the libssh2 functions has returned LIBSSH2_ERROR_EAGAIN this + * function is used to figure out in what direction and stores this info so + * that the multi interface can take advantage of it. Make sure to call this + * function in all cases so that when it _does not_ return EAGAIN we can + * restore the default wait bits. + */ +static void ssh_block2waitfor(struct Curl_easy *data, + struct ssh_conn *sshc, + bool block) +{ + int dir = 0; + (void)data; + if(block) { + dir = libssh2_session_block_directions(sshc->ssh_session); + if(dir) { + /* translate the libssh2 define bits into our own bit defines */ + sshc->waitfor = + ((dir & LIBSSH2_SESSION_BLOCK_INBOUND) ? REQ_IO_RECV : 0) | + ((dir & LIBSSH2_SESSION_BLOCK_OUTBOUND) ? REQ_IO_SEND : 0); + } + } + if(!dir) + sshc->waitfor = 0; +} + +/* called repeatedly until done from multi.c */ +static CURLcode ssh_multi_statemach(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + struct SSHPROTO *sshp = Curl_meta_get(data, CURL_META_SSH_EASY); + CURLcode result = CURLE_OK; + bool block; /* we store the status and use that to provide + a Curl_ssh_pollset() implementation */ + if(!sshc || !sshp) + return CURLE_FAILED_INIT; + + do { + result = ssh_statemachine(data, sshc, sshp, &block); + *done = (sshc->state == SSH_STOP); + /* if there is no error, it is not done and it did not EWOULDBLOCK, then + try again */ + } while(!result && !*done && !block); + ssh_block2waitfor(data, sshc, block); + + return result; +} + +static CURLcode ssh_block_statemach(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool disconnect) +{ + CURLcode result = CURLE_OK; + struct curltime start = *Curl_pgrs_now(data); + + while((sshc->state != SSH_STOP) && !result) { + bool block; + timediff_t left_ms = 1000; + + result = ssh_statemachine(data, sshc, sshp, &block); + if(result) + break; + + if(!disconnect) { + result = Curl_pgrsCheck(data); + if(result) + break; + + left_ms = Curl_timeleft_ms(data); + if(left_ms < 0) { + failf(data, "Operation timed out"); + return CURLE_OPERATION_TIMEDOUT; + } + } + else if(curlx_ptimediff_ms(Curl_pgrs_now(data), &start) > 1000) { + /* disconnect timeout */ + failf(data, "Disconnect timed out"); + result = CURLE_OK; + break; + } + + if(block) { + int dir = libssh2_session_block_directions(sshc->ssh_session); + curl_socket_t sock = data->conn->sock[FIRSTSOCKET]; + curl_socket_t fd_read = CURL_SOCKET_BAD; + curl_socket_t fd_write = CURL_SOCKET_BAD; + if(LIBSSH2_SESSION_BLOCK_INBOUND & dir) + fd_read = sock; + if(LIBSSH2_SESSION_BLOCK_OUTBOUND & dir) + fd_write = sock; + /* wait for the socket to become ready */ + (void)Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write, + left_ms > 1000 ? 1000 : left_ms); + } + } + + return result; +} + +static void myssh_easy_dtor(void *key, size_t klen, void *entry) +{ + struct SSHPROTO *sshp = entry; + (void)key; + (void)klen; + curlx_safefree(sshp->path); + curlx_dyn_free(&sshp->readdir); + curlx_dyn_free(&sshp->readdir_link); + curlx_free(sshp); +} + +static void myssh_conn_dtor(void *key, size_t klen, void *entry) +{ + struct ssh_conn *sshc = entry; + (void)key; + (void)klen; + sshc_cleanup(sshc, NULL, TRUE); + curlx_free(sshc); +} + +/* + * SSH setup and connection + */ +static CURLcode ssh_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + struct ssh_conn *sshc; + struct SSHPROTO *sshp; + (void)conn; + + sshc = curlx_calloc(1, sizeof(*sshc)); + if(!sshc) + return CURLE_OUT_OF_MEMORY; + + if(Curl_conn_meta_set(conn, CURL_META_SSH_CONN, sshc, myssh_conn_dtor)) + return CURLE_OUT_OF_MEMORY; + + sshp = curlx_calloc(1, sizeof(*sshp)); + if(!sshp) + return CURLE_OUT_OF_MEMORY; + + curlx_dyn_init(&sshp->readdir, CURL_PATH_MAX * 2); + curlx_dyn_init(&sshp->readdir_link, CURL_PATH_MAX); + if(Curl_meta_set(data, CURL_META_SSH_EASY, sshp, myssh_easy_dtor)) + return CURLE_OUT_OF_MEMORY; + + return Curl_ssh_setup_pkey(data, sshc); +} + +static Curl_recv scp_recv, sftp_recv; +static Curl_send scp_send, sftp_send; + +#ifndef CURL_DISABLE_PROXY +static ssize_t ssh_tls_recv(libssh2_socket_t sock, void *buffer, + size_t length, int flags, void **abstract) +{ + struct Curl_easy *data = (struct Curl_easy *)*abstract; + int8_t sockindex = Curl_conn_sockindex(data, sock); + size_t nread; + CURLcode result; + struct connectdata *conn = data->conn; + Curl_recv *backup = conn->recv[sockindex]; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + (void)flags; + + if(!sshc) + return -1; + + /* swap in the TLS reader function for this call only, and then swap back + the SSH one again */ + conn->recv[sockindex] = sshc->tls_recv; + result = Curl_conn_recv(data, sockindex, buffer, length, &nread); + conn->recv[sockindex] = backup; + if(result == CURLE_AGAIN) + return -EAGAIN; /* magic return code for libssh2 */ + else if(result) + return -1; /* generic error */ + Curl_debug(data, CURLINFO_DATA_IN, (const char *)buffer, nread); + return (ssize_t)nread; +} + +static ssize_t ssh_tls_send(libssh2_socket_t sock, const void *buffer, + size_t length, int flags, void **abstract) +{ + struct Curl_easy *data = (struct Curl_easy *)*abstract; + int8_t sockindex = Curl_conn_sockindex(data, sock); + size_t nwrite; + CURLcode result; + struct connectdata *conn = data->conn; + Curl_send *backup = conn->send[sockindex]; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + (void)flags; + + if(!sshc) + return -1; + + /* swap in the TLS writer function for this call only, and then swap back + the SSH one again */ + conn->send[sockindex] = sshc->tls_send; + result = Curl_conn_send(data, sockindex, buffer, length, FALSE, &nwrite); + conn->send[sockindex] = backup; + if(result == CURLE_AGAIN) + return -EAGAIN; /* magic return code for libssh2 */ + else if(result) + return -1; /* error */ + Curl_debug(data, CURLINFO_DATA_OUT, (const char *)buffer, nwrite); + return (ssize_t)nwrite; +} +#endif + +/* + * Curl_ssh_connect() gets called from Curl_protocol_connect() to allow us to + * do protocol-specific actions at connect-time. + */ +static CURLcode ssh_connect(struct Curl_easy *data, bool *done) +{ +#ifdef CURL_LIBSSH2_DEBUG + curl_socket_t sock; +#endif + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + CURLcode result; + +#if LIBSSH2_VERSION_NUM >= 0x010b00 + { + const char *crypto_str; + switch(libssh2_crypto_engine()) { + case libssh2_gcrypt: + crypto_str = "libgcrypt"; + break; + case libssh2_mbedtls: + crypto_str = "mbedTLS"; + break; + case libssh2_openssl: + crypto_str = "openssl compatible"; + break; + case libssh2_os400qc3: + crypto_str = "OS400QC3"; + break; + case libssh2_wincng: + crypto_str = "WinCNG"; + break; + default: + crypto_str = NULL; + break; + } + if(crypto_str) + infof(data, "SSH: libssh2 cryptography backend: %s", crypto_str); + } +#endif + + if(!sshc) + return CURLE_FAILED_INIT; + + infof(data, "SSH: user '%s'", Curl_creds_user(conn->creds)); +#ifdef CURL_LIBSSH2_DEBUG + infof(data, "SSH: password %s", Curl_creds_passwd(conn->creds)); + sock = conn->sock[FIRSTSOCKET]; +#endif /* CURL_LIBSSH2_DEBUG */ + + /* libcurl MUST set custom memory functions so that the kbd_callback + function's memory allocations can be properly freed */ + sshc->ssh_session = libssh2_session_init_ex(my_libssh2_malloc, + my_libssh2_free, + my_libssh2_realloc, data); + + if(!sshc->ssh_session) { + failf(data, "Failure initializing ssh session"); + return CURLE_FAILED_INIT; + } + + /* Set the packet read timeout if the libssh2 version supports it */ +#if LIBSSH2_VERSION_NUM >= 0x010B00 + if(data->set.server_response_timeout > 0) { + libssh2_session_set_read_timeout(sshc->ssh_session, + (long)(data->set.server_response_timeout / 1000)); + } +#endif + +#ifndef CURL_DISABLE_PROXY + if(conn->http_proxy.proxytype == CURLPROXY_HTTPS) { + /* Setup libssh2 callbacks to make it read/write TLS from the socket. + + ssize_t + recvcb(libssh2_socket_t sock, void *buffer, size_t length, + int flags, void **abstract); + + ssize_t + sendcb(libssh2_socket_t sock, const void *buffer, size_t length, + int flags, void **abstract); + */ +#if LIBSSH2_VERSION_NUM >= 0x010b01 + infof(data, "SSH: using HTTPS proxy"); +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcast-function-type-strict" +#endif + libssh2_session_callback_set2(sshc->ssh_session, + LIBSSH2_CALLBACK_RECV, + (libssh2_cb_generic *)ssh_tls_recv); + libssh2_session_callback_set2(sshc->ssh_session, + LIBSSH2_CALLBACK_SEND, + (libssh2_cb_generic *)ssh_tls_send); +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic pop +#endif +#else + /* + * This crazy union dance is here to avoid assigning a void pointer a + * function pointer as it is invalid C. The problem is of course that + * libssh2 has such an API... + */ + union receive { + void *recvp; + ssize_t (*recvptr)(libssh2_socket_t, void *, size_t, int, void **); + }; + union transfer { + void *sendp; + ssize_t (*sendptr)(libssh2_socket_t, const void *, size_t, int, void **); + }; + union receive sshrecv; + union transfer sshsend; + + sshrecv.recvptr = ssh_tls_recv; + sshsend.sendptr = ssh_tls_send; + + infof(data, "SSH: using HTTPS proxy"); + libssh2_session_callback_set(sshc->ssh_session, + LIBSSH2_CALLBACK_RECV, sshrecv.recvp); + libssh2_session_callback_set(sshc->ssh_session, + LIBSSH2_CALLBACK_SEND, sshsend.sendp); +#endif + + /* Store the underlying TLS recv/send function pointers to be used when + reading from the proxy */ + sshc->tls_recv = conn->recv[FIRSTSOCKET]; + sshc->tls_send = conn->send[FIRSTSOCKET]; + } + +#endif /* CURL_DISABLE_PROXY */ + if(conn->scheme->protocol & CURLPROTO_SCP) { + conn->recv[FIRSTSOCKET] = scp_recv; + conn->send[FIRSTSOCKET] = scp_send; + } + else { + conn->recv[FIRSTSOCKET] = sftp_recv; + conn->send[FIRSTSOCKET] = sftp_send; + } + + if(data->set.ssh_compression && + libssh2_session_flag(sshc->ssh_session, LIBSSH2_FLAG_COMPRESS, 1) < 0) { + infof(data, "SSH: failed to enable compression for session"); + } + + if(CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS)) { + int rc; + sshc->kh = libssh2_knownhost_init(sshc->ssh_session); + if(!sshc->kh) { + libssh2_session_free(sshc->ssh_session); + sshc->ssh_session = NULL; + return CURLE_FAILED_INIT; + } + + /* read all known hosts from there */ + rc = libssh2_knownhost_readfile( + sshc->kh, CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS), + LIBSSH2_KNOWNHOST_FILE_OPENSSH); + if(rc < 0) + infof(data, "SSH: failed to read known hosts from %s", + CURL_EASY_STR(data, STRING_SSH_KNOWNHOSTS)); + } + +#ifdef CURL_LIBSSH2_DEBUG + libssh2_trace(sshc->ssh_session, ~0); + infof(data, "SSH: socket %d", (int)sock); +#endif + + myssh_to(data, sshc, SSH_INIT); + + result = ssh_multi_statemach(data, done); + + return result; +} + +/* + *********************************************************************** + * + * scp_perform() + * + * This is the actual DO function for SCP. Get a file according to + * the options previously setup. + */ + +static CURLcode scp_perform(struct Curl_easy *data, + bool *connected, + bool *dophase_done) +{ + struct ssh_conn *sshc = Curl_conn_meta_get(data->conn, CURL_META_SSH_CONN); + CURLcode result = CURLE_OK; + + CURL_TRC_SSH(data, "DO phase starts"); + + *dophase_done = FALSE; /* not done yet */ + if(!sshc) + return CURLE_FAILED_INIT; + + /* start the first command in the DO phase */ + myssh_to(data, sshc, SSH_SCP_TRANS_INIT); + + /* run the state-machine */ + result = ssh_multi_statemach(data, dophase_done); + + *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET); + + if(*dophase_done) { + CURL_TRC_SSH(data, "DO phase is complete"); + } + + return result; +} + +/* called from multi.c while DOing */ +static CURLcode scp_doing(struct Curl_easy *data, + bool *dophase_done) +{ + CURLcode result; + result = ssh_multi_statemach(data, dophase_done); + + if(*dophase_done) { + CURL_TRC_SSH(data, "DO phase is complete"); + } + return result; +} + +/* BLOCKING, but the function is using the state machine so the only reason + this is still blocking is that the multi interface code has no support for + disconnecting operations that takes a while */ +static CURLcode scp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + CURLcode result = CURLE_OK; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + struct SSHPROTO *sshp = Curl_meta_get(data, CURL_META_SSH_EASY); + (void)dead_connection; + + if(sshc && sshc->ssh_session) { + /* only if there is a session still around to use! */ + myssh_to(data, sshc, SSH_SESSION_DISCONNECT); + result = ssh_block_statemach(data, sshc, sshp, TRUE); + } + + if(sshc) + return sshc_cleanup(sshc, data, TRUE); + return result; +} + +/* generic done function for both SCP and SFTP called from their specific + done functions */ +static CURLcode ssh_done(struct Curl_easy *data, CURLcode status) +{ + struct ssh_conn *sshc = Curl_conn_meta_get(data->conn, CURL_META_SSH_CONN); + struct SSHPROTO *sshp = Curl_meta_get(data, CURL_META_SSH_EASY); + CURLcode result = CURLE_OK; + + if(!sshc || !sshp) + return CURLE_FAILED_INIT; + + if(!status) + /* run the state-machine */ + result = ssh_block_statemach(data, sshc, sshp, FALSE); + else + result = status; + + if(Curl_pgrsDone(data)) + return CURLE_ABORTED_BY_CALLBACK; + + CURL_REQ_CLEAR_IO(data); + return result; +} + +static CURLcode scp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + struct ssh_conn *sshc = Curl_conn_meta_get(data->conn, CURL_META_SSH_CONN); + (void)premature; + + if(sshc && !status) + myssh_to(data, sshc, SSH_SCP_DONE); + + return ssh_done(data, status); +} + +static CURLcode scp_send(struct Curl_easy *data, int8_t sockindex, + const uint8_t *mem, size_t len, bool eos, + size_t *pnwritten) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + CURLcode result = CURLE_OK; + ssize_t nwritten; + + (void)sockindex; /* we only support SCP on the fixed known primary socket */ + (void)eos; + *pnwritten = 0; + + if(!sshc) + return CURLE_FAILED_INIT; + + /* libssh2_channel_write() returns int! */ + nwritten = (ssize_t)libssh2_channel_write(sshc->ssh_channel, + (const char *)mem, len); + + ssh_block2waitfor(data, sshc, (nwritten == LIBSSH2_ERROR_EAGAIN)); + + if(nwritten == LIBSSH2_ERROR_EAGAIN) + result = CURLE_AGAIN; + else if(nwritten < LIBSSH2_ERROR_NONE) + result = libssh2_session_error_to_CURLE((int)nwritten); + else + *pnwritten = (size_t)nwritten; + + return result; +} + +static CURLcode scp_recv(struct Curl_easy *data, int8_t sockindex, + char *mem, size_t len, size_t *pnread) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + CURLcode result = CURLE_OK; + ssize_t nread; + + (void)sockindex; /* we only support SCP on the fixed known primary socket */ + *pnread = 0; + + if(!sshc) + return CURLE_FAILED_INIT; + + /* libssh2_channel_read() returns int */ + nread = (ssize_t)libssh2_channel_read(sshc->ssh_channel, mem, len); + + ssh_block2waitfor(data, sshc, (nread == LIBSSH2_ERROR_EAGAIN)); + if(nread == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + else if(nread < LIBSSH2_ERROR_NONE) + result = libssh2_session_error_to_CURLE((int)nread); + else + *pnread = (size_t)nread; + + return result; +} + +/* + * =============== SFTP =============== + */ + +/* + *********************************************************************** + * + * sftp_perform() + * + * This is the actual DO function for SFTP. Get a file/directory according to + * the options previously setup. + */ + +static CURLcode sftp_perform(struct Curl_easy *data, + bool *connected, + bool *dophase_done) +{ + struct ssh_conn *sshc = Curl_conn_meta_get(data->conn, CURL_META_SSH_CONN); + CURLcode result = CURLE_OK; + + CURL_TRC_SSH(data, "DO phase starts"); + + *dophase_done = FALSE; /* not done yet */ + if(!sshc) + return CURLE_FAILED_INIT; + + /* start the first command in the DO phase */ + myssh_to(data, sshc, SSH_SFTP_QUOTE_INIT); + + /* run the state-machine */ + result = ssh_multi_statemach(data, dophase_done); + + *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET); + + if(*dophase_done) { + CURL_TRC_SSH(data, "DO phase is complete"); + } + + return result; +} + +/* called from multi.c while DOing */ +static CURLcode sftp_doing(struct Curl_easy *data, + bool *dophase_done) +{ + CURLcode result = ssh_multi_statemach(data, dophase_done); + + if(*dophase_done) { + CURL_TRC_SSH(data, "DO phase is complete"); + } + return result; +} + +/* BLOCKING, but the function is using the state machine so the only reason + this is still blocking is that the multi interface code has no support for + disconnecting operations that takes a while */ +static CURLcode sftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead_connection) +{ + CURLcode result = CURLE_OK; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + struct SSHPROTO *sshp = Curl_meta_get(data, CURL_META_SSH_EASY); + (void)dead_connection; + + if(sshc) { + if(sshc->ssh_session) { + /* only if there is a session still around to use! */ + CURL_TRC_SSH(data, "DISCONNECT starts now"); + myssh_to(data, sshc, SSH_SFTP_SHUTDOWN); + result = ssh_block_statemach(data, sshc, sshp, TRUE); + CURL_TRC_SSH(data, "DISCONNECT is done -> %d", (int)result); + } + sshc_cleanup(sshc, data, TRUE); + } + return result; +} + +static CURLcode sftp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + + if(!sshc) + return CURLE_FAILED_INIT; + + if(!status) { + /* Post quote commands are executed after the SFTP_CLOSE state to avoid + errors that could happen due to open file handles during POSTQUOTE + operation */ + if(!premature && data->set.postquote && !conn->bits.retry) + sshc->nextstate = SSH_SFTP_POSTQUOTE_INIT; + myssh_to(data, sshc, SSH_SFTP_CLOSE); + } + return ssh_done(data, status); +} + +/* return number of sent bytes */ +static CURLcode sftp_send(struct Curl_easy *data, int8_t sockindex, + const uint8_t *mem, size_t len, bool eos, + size_t *pnwritten) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + ssize_t nwrite; + + (void)sockindex; + (void)eos; + *pnwritten = 0; + + if(!sshc) + return CURLE_FAILED_INIT; + + nwrite = libssh2_sftp_write(sshc->sftp_handle, (const char *)mem, len); + + ssh_block2waitfor(data, sshc, (nwrite == LIBSSH2_ERROR_EAGAIN)); + + if(nwrite == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + else if(nwrite < LIBSSH2_ERROR_NONE) + return libssh2_session_error_to_CURLE((int)nwrite); + *pnwritten = (size_t)nwrite; + return CURLE_OK; +} + +/* + * Return number of received (decrypted) bytes + * or <0 on error + */ +static CURLcode sftp_recv(struct Curl_easy *data, int8_t sockindex, + char *mem, size_t len, size_t *pnread) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + ssize_t nread; + + (void)sockindex; + *pnread = 0; + + if(!sshc) + return CURLE_FAILED_INIT; + + nread = libssh2_sftp_read(sshc->sftp_handle, mem, len); + + ssh_block2waitfor(data, sshc, (nread == LIBSSH2_ERROR_EAGAIN)); + + if(nread == LIBSSH2_ERROR_EAGAIN) + return CURLE_AGAIN; + else if(nread < 0) + return libssh2_session_error_to_CURLE((int)nread); + + *pnread = (size_t)nread; + return CURLE_OK; +} + +/* + * The DO function is generic for both protocols. There was previously two + * separate ones but this way means less duplicated code. + */ +static CURLcode ssh_do(struct Curl_easy *data, bool *done) +{ + CURLcode result; + bool connected = FALSE; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + + *done = FALSE; /* default to false */ + if(!sshc) + return CURLE_FAILED_INIT; + + data->req.size = -1; /* make sure this is unknown at this point */ + sshc->secondCreateDirs = 0; /* reset the create directory attempt state + variable */ + + Curl_pgrsReset(data); + + if(conn->scheme->protocol & CURLPROTO_SCP) + result = scp_perform(data, &connected, done); + else + result = sftp_perform(data, &connected, done); + + return result; +} + +CURLcode Curl_ssh_init(void) +{ + if(libssh2_init(0)) { + DEBUGF(curl_mfprintf(stderr, "Error: libssh2_init failed\n")); + return CURLE_FAILED_INIT; + } + return CURLE_OK; +} + +void Curl_ssh_cleanup(void) +{ + libssh2_exit(); +} + +void Curl_ssh_version(char *buffer, size_t buflen) +{ + (void)curl_msnprintf(buffer, buflen, "libssh2/%s", libssh2_version(0)); +} + +/* The SSH session is associated with the *CONNECTION* but the callback user + * pointer is an easy handle pointer. This function allows us to reassign the + * user pointer to the *CURRENT* (new) easy handle. + */ +static void ssh_attach(struct Curl_easy *data, struct connectdata *conn) +{ + DEBUGASSERT(data); + DEBUGASSERT(conn); + if(conn->scheme->protocol & PROTO_FAMILY_SSH) { + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + if(sshc && sshc->ssh_session) { + /* only re-attach if the session already exists */ + void **abstract = libssh2_session_abstract(sshc->ssh_session); + *abstract = data; + } + } +} + +/* + * SCP protocol handler. + */ +const struct Curl_protocol Curl_protocol_scp = { + ssh_setup_connection, /* setup_connection */ + ssh_do, /* do_it */ + scp_done, /* done */ + ZERO_NULL, /* do_more */ + ssh_connect, /* connect_it */ + ssh_multi_statemach, /* connecting */ + scp_doing, /* doing */ + Curl_ssh_pollset, /* proto_pollset */ + Curl_ssh_pollset, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + Curl_ssh_pollset, /* perform_pollset */ + scp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ssh_attach, /* attach */ + ZERO_NULL, /* follow */ +}; + +/* + * SFTP protocol handler. + */ +const struct Curl_protocol Curl_protocol_sftp = { + ssh_setup_connection, /* setup_connection */ + ssh_do, /* do_it */ + sftp_done, /* done */ + ZERO_NULL, /* do_more */ + ssh_connect, /* connect_it */ + ssh_multi_statemach, /* connecting */ + sftp_doing, /* doing */ + Curl_ssh_pollset, /* proto_pollset */ + Curl_ssh_pollset, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + Curl_ssh_pollset, /* perform_pollset */ + sftp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ssh_attach, /* attach */ + ZERO_NULL, /* follow */ +}; + +#endif /* USE_LIBSSH2 */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/ssh.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/ssh.h new file mode 100644 index 0000000000..52bc139990 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/ssh.h @@ -0,0 +1,262 @@ +#ifndef HEADER_CURL_VSSH_SSH_H +#define HEADER_CURL_VSSH_SSH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" + +extern const struct Curl_protocol Curl_protocol_sftp; +extern const struct Curl_protocol Curl_protocol_scp; + +#ifdef USE_SSH + +#ifdef USE_LIBSSH2 +#include <libssh2.h> +#include <libssh2_sftp.h> +#elif defined(USE_LIBSSH) +/* in 0.10.0 or later, ignore deprecated warnings */ +#define SSH_SUPPRESS_DEPRECATED +#include <libssh/libssh.h> +#include <libssh/sftp.h> +#endif + +/* meta key for storing protocol meta at easy handle */ +#define CURL_META_SSH_EASY "meta:proto:ssh:easy" +/* meta key for storing protocol meta at connection */ +#define CURL_META_SSH_CONN "meta:proto:ssh:conn" + +/**************************************************************************** + * SSH unique setup + ***************************************************************************/ +typedef enum { + SSH_NO_STATE = -1, /* Used for "nextState" so say there is none */ + SSH_STOP = 0, /* do nothing state, stops the state machine */ + + SSH_INIT, /* First state in SSH-CONNECT */ + SSH_S_STARTUP, /* Session startup */ + SSH_HOSTKEY, /* verify hostkey */ + SSH_AUTHLIST, + SSH_AUTH_PKEY_INIT, + SSH_AUTH_PKEY, + SSH_AUTH_PASS_INIT, + SSH_AUTH_PASS, + SSH_AUTH_AGENT_INIT, /* initialize then wait for connection to agent */ + SSH_AUTH_AGENT_LIST, /* ask for list then wait for entire list to come */ + SSH_AUTH_AGENT, /* attempt one key at a time */ + SSH_AUTH_HOST_INIT, + SSH_AUTH_HOST, + SSH_AUTH_KEY_INIT, + SSH_AUTH_KEY, + SSH_AUTH_GSSAPI, + SSH_AUTH_DONE, + SSH_SFTP_INIT, + SSH_SFTP_REALPATH, /* Last state in SSH-CONNECT */ + + SSH_SFTP_QUOTE_INIT, /* First state in SFTP-DO */ + SSH_SFTP_POSTQUOTE_INIT, /* (Possibly) First state in SFTP-DONE */ + SSH_SFTP_QUOTE, + SSH_SFTP_NEXT_QUOTE, + SSH_SFTP_QUOTE_STAT, + SSH_SFTP_QUOTE_SETSTAT, + SSH_SFTP_QUOTE_SYMLINK, + SSH_SFTP_QUOTE_MKDIR, + SSH_SFTP_QUOTE_RENAME, + SSH_SFTP_QUOTE_RMDIR, + SSH_SFTP_QUOTE_UNLINK, + SSH_SFTP_QUOTE_STATVFS, + SSH_SFTP_GETINFO, + SSH_SFTP_FILETIME, + SSH_SFTP_TRANS_INIT, + SSH_SFTP_UPLOAD_INIT, + SSH_SFTP_CREATE_DIRS_INIT, + SSH_SFTP_CREATE_DIRS, + SSH_SFTP_CREATE_DIRS_MKDIR, + SSH_SFTP_READDIR_INIT, + SSH_SFTP_READDIR, + SSH_SFTP_READDIR_LINK, + SSH_SFTP_READDIR_BOTTOM, + SSH_SFTP_READDIR_DONE, + SSH_SFTP_DOWNLOAD_INIT, + SSH_SFTP_DOWNLOAD_STAT, /* Last state in SFTP-DO */ + SSH_SFTP_CLOSE, /* Last state in SFTP-DONE */ + SSH_SFTP_SHUTDOWN, /* First state in SFTP-DISCONNECT */ + SSH_SCP_TRANS_INIT, /* First state in SCP-DO */ + SSH_SCP_UPLOAD_INIT, + SSH_SCP_DOWNLOAD_INIT, + SSH_SCP_DOWNLOAD, + SSH_SCP_DONE, + SSH_SCP_SEND_EOF, + SSH_SCP_WAIT_EOF, + SSH_SCP_WAIT_CLOSE, + SSH_SCP_CHANNEL_FREE, /* Last state in SCP-DONE */ + SSH_SESSION_DISCONNECT, /* First state in SCP-DISCONNECT */ + SSH_SESSION_FREE, /* Last state in SCP/SFTP-DISCONNECT */ + SSH_QUIT, + SSH_LAST /* never used */ +} sshstate; + +#define CURL_PATH_MAX 1024 + +/* this struct is used in the HandleData struct which is part of the + Curl_easy, which means this is used on a per-easy handle basis. + Everything that is strictly related to a connection is banned from this + struct. */ +struct SSHPROTO { + char *path; /* the path we operate on, at least one byte long */ +#ifdef USE_LIBSSH2 + struct dynbuf readdir_link; + struct dynbuf readdir; + char readdir_filename[CURL_PATH_MAX + 1]; + char readdir_longentry[CURL_PATH_MAX + 1]; + + LIBSSH2_SFTP_ATTRIBUTES quote_attrs; /* used by the SFTP_QUOTE state */ + + /* Here's a set of struct members used by the SFTP_READDIR state */ + LIBSSH2_SFTP_ATTRIBUTES readdir_attrs; +#endif +}; + +/* ssh_conn is used for struct connection-oriented data in the connectdata + struct */ +struct ssh_conn { + const char *authlist; /* List of auth. methods, managed by libssh2 */ + + /* common */ + const char *passphrase; /* pass-phrase to use */ + char *pub_key; /* strdup'ed public key file */ + char *priv_key; /* strdup'ed private key file */ + sshstate state; /* always use ssh.c:state() to change state! */ + sshstate nextstate; /* the state to goto after stopping */ + struct curl_slist *quote_item; /* for the quote option */ + char *quote_path1; /* two generic pointers for the QUOTE stuff */ + char *quote_path2; + + char *homedir; /* when doing SFTP we figure out home directory + in the connect phase */ + /* end of READDIR stuff */ + + int secondCreateDirs; /* counter use by the code to see if the + second attempt has been made to change + to/create a directory */ + int waitfor; /* REQ_IO_RECV/REQ_IO_SEND bits overriding + pollset given flags */ + char *slash_pos; /* used by the SFTP_CREATE_DIRS state */ + +#ifdef USE_LIBSSH + CURLcode actualcode; /* the actual error code */ + char *readdir_linkPath; + size_t readdir_len; + struct dynbuf readdir_buf; +/* our variables */ + unsigned kbd_state; /* 0 or 1 */ + ssh_key privkey; + ssh_key pubkey; + unsigned int auth_methods; + ssh_session ssh_session; + ssh_scp scp_session; + sftp_session sftp_session; + sftp_file sftp_file; + sftp_dir sftp_dir; + + unsigned sftp_recv_state; /* 0 or 1 */ +#if LIBSSH_VERSION_INT > SSH_VERSION_INT(0, 11, 0) + sftp_aio sftp_recv_aio; + + sftp_aio sftp_send_aio; + unsigned sftp_send_state; /* 0 or 1 */ +#else + int sftp_file_index; /* for async read */ +#endif + sftp_attributes readdir_attrs; /* used by the SFTP readdir actions */ + sftp_attributes readdir_link_attrs; /* used by the SFTP readdir actions */ + sftp_attributes quote_attrs; /* used by the SFTP_QUOTE state */ + + const char *readdir_filename; /* points within readdir_attrs */ + const char *readdir_longentry; + char *readdir_tmp; + BIT(initialized); +#elif defined(USE_LIBSSH2) + LIBSSH2_SESSION *ssh_session; /* Secure Shell session */ + LIBSSH2_CHANNEL *ssh_channel; /* Secure Shell channel handle */ + LIBSSH2_SFTP *sftp_session; /* SFTP handle */ + LIBSSH2_SFTP_HANDLE *sftp_handle; + +#ifndef CURL_DISABLE_PROXY + /* for HTTPS proxy storage */ + Curl_recv *tls_recv; + Curl_send *tls_send; +#endif + + LIBSSH2_AGENT *ssh_agent; /* proxy to ssh-agent/pageant */ + struct libssh2_agent_publickey *sshagent_identity; + struct libssh2_agent_publickey *sshagent_prev_identity; + LIBSSH2_KNOWNHOSTS *kh; +#endif /* USE_LIBSSH */ + BIT(authed); /* the connection has been authenticated fine */ + BIT(acceptfail); /* used by the SFTP_QUOTE (continue if + quote command fails) */ +}; + +#ifdef USE_LIBSSH +#if LIBSSH_VERSION_INT < SSH_VERSION_INT(0, 9, 0) +#error "SCP/SFTP protocols require libssh 0.9.0 or greater" +#endif +#endif + +#ifdef USE_LIBSSH2 + +/* Feature detection based on version numbers to better work with + non-configure platforms */ + +#if !defined(LIBSSH2_VERSION_NUM) || (LIBSSH2_VERSION_NUM < 0x010900) +#error "SCP/SFTP protocols require libssh2 1.9.0 or greater" +/* 1.9.0 was released on June 20 2019 */ +#endif + +#endif /* USE_LIBSSH2 */ + +#ifdef CURLVERBOSE +const char *Curl_ssh_statename(sshstate state); +#else +#define Curl_ssh_statename(x) "" +#endif +void Curl_ssh_set_state(struct Curl_easy *data, + struct ssh_conn *sshc, + sshstate nowstate); + +#define myssh_to(x, y, z) Curl_ssh_set_state(x, y, z) + +/* generic SSH backend functions */ +CURLcode Curl_ssh_init(void); +void Curl_ssh_cleanup(void); +void Curl_ssh_version(char *buffer, size_t buflen); +void Curl_ssh_attach(struct Curl_easy *data, + struct connectdata *conn); +#else /* !USE_SSH */ +#define Curl_ssh_cleanup() +#define Curl_ssh_attach(x, y) +#define Curl_ssh_init() 0 +#endif /* USE_SSH */ + +#endif /* HEADER_CURL_SSH_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/vssh.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/vssh.c new file mode 100644 index 0000000000..9834546987 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/vssh.c @@ -0,0 +1,450 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl AND ISC + * + ***************************************************************************/ +#include "curl_setup.h" +#include "vssh/ssh.h" + +#ifdef USE_SSH + +#include "vssh/vssh.h" +#include "curlx/strparse.h" +#include "curl_trc.h" +#include "escape.h" +#include "select.h" /* for Curl_pollset_change() */ +#include "url.h" /* for Curl_conn_meta_get() */ +#include "curlx/fopen.h" + +#ifdef CURLVERBOSE +const char *Curl_ssh_statename(sshstate state) +{ + static const char * const names[] = { + "SSH_STOP", + "SSH_INIT", + "SSH_S_STARTUP", + "SSH_HOSTKEY", + "SSH_AUTHLIST", + "SSH_AUTH_PKEY_INIT", + "SSH_AUTH_PKEY", + "SSH_AUTH_PASS_INIT", + "SSH_AUTH_PASS", + "SSH_AUTH_AGENT_INIT", + "SSH_AUTH_AGENT_LIST", + "SSH_AUTH_AGENT", + "SSH_AUTH_HOST_INIT", + "SSH_AUTH_HOST", + "SSH_AUTH_KEY_INIT", + "SSH_AUTH_KEY", + "SSH_AUTH_GSSAPI", + "SSH_AUTH_DONE", + "SSH_SFTP_INIT", + "SSH_SFTP_REALPATH", + "SSH_SFTP_QUOTE_INIT", + "SSH_SFTP_POSTQUOTE_INIT", + "SSH_SFTP_QUOTE", + "SSH_SFTP_NEXT_QUOTE", + "SSH_SFTP_QUOTE_STAT", + "SSH_SFTP_QUOTE_SETSTAT", + "SSH_SFTP_QUOTE_SYMLINK", + "SSH_SFTP_QUOTE_MKDIR", + "SSH_SFTP_QUOTE_RENAME", + "SSH_SFTP_QUOTE_RMDIR", + "SSH_SFTP_QUOTE_UNLINK", + "SSH_SFTP_QUOTE_STATVFS", + "SSH_SFTP_GETINFO", + "SSH_SFTP_FILETIME", + "SSH_SFTP_TRANS_INIT", + "SSH_SFTP_UPLOAD_INIT", + "SSH_SFTP_CREATE_DIRS_INIT", + "SSH_SFTP_CREATE_DIRS", + "SSH_SFTP_CREATE_DIRS_MKDIR", + "SSH_SFTP_READDIR_INIT", + "SSH_SFTP_READDIR", + "SSH_SFTP_READDIR_LINK", + "SSH_SFTP_READDIR_BOTTOM", + "SSH_SFTP_READDIR_DONE", + "SSH_SFTP_DOWNLOAD_INIT", + "SSH_SFTP_DOWNLOAD_STAT", + "SSH_SFTP_CLOSE", + "SSH_SFTP_SHUTDOWN", + "SSH_SCP_TRANS_INIT", + "SSH_SCP_UPLOAD_INIT", + "SSH_SCP_DOWNLOAD_INIT", + "SSH_SCP_DOWNLOAD", + "SSH_SCP_DONE", + "SSH_SCP_SEND_EOF", + "SSH_SCP_WAIT_EOF", + "SSH_SCP_WAIT_CLOSE", + "SSH_SCP_CHANNEL_FREE", + "SSH_SESSION_DISCONNECT", + "SSH_SESSION_FREE", + "QUIT" + }; + /* a precaution to make sure the lists are in sync */ + DEBUGASSERT(CURL_ARRAYSIZE(names) == SSH_LAST); + return ((size_t)state < CURL_ARRAYSIZE(names)) ? names[state] : ""; +} +#endif /* CURLVERBOSE */ + +/* + * SSH State machine related code + */ +/* This is the ONLY way to change SSH state! */ +void Curl_ssh_set_state(struct Curl_easy *data, + struct ssh_conn *sshc, + sshstate nowstate) +{ +#ifdef CURLVERBOSE + if(sshc->state != nowstate) { + CURL_TRC_SSH(data, "[%s] -> [%s]", + Curl_ssh_statename(sshc->state), + Curl_ssh_statename(nowstate)); + } +#else + (void)data; +#endif + sshc->state = nowstate; +} + +#define MAX_SSHPATH_LEN 100000 /* arbitrary */ + +/* figure out the path to work with in this particular request */ +CURLcode Curl_getworkingpath(struct Curl_easy *data, + const char *homedir, /* when SFTP is used */ + char **path) /* returns the allocated + real path to work with */ +{ + char *working_path; + size_t working_path_len; + struct dynbuf npath; + CURLcode result = + Curl_urldecode(data->state.up.path, 0, &working_path, + &working_path_len, REJECT_ZERO); + if(result) + return result; + + /* new path to switch to in case we need to */ + curlx_dyn_init(&npath, MAX_SSHPATH_LEN); + + /* Check for /~/, indicating relative to the user's home directory */ + if((data->conn->scheme->protocol & CURLPROTO_SCP) && + (working_path_len > 3) && (!memcmp(working_path, "/~/", 3))) { + /* It is referenced to the home directory, so strip the leading '/~/' */ + if(curlx_dyn_addn(&npath, &working_path[3], working_path_len - 3)) { + curlx_free(working_path); + return CURLE_OUT_OF_MEMORY; + } + } + else if((data->conn->scheme->protocol & CURLPROTO_SFTP) && + (!strcmp("/~", working_path) || + ((working_path_len > 2) && !memcmp(working_path, "/~/", 3)))) { + if(curlx_dyn_add(&npath, homedir)) { + curlx_free(working_path); + return CURLE_OUT_OF_MEMORY; + } + if(working_path_len > 2) { + size_t len; + const char *p; + int copyfrom = 3; + /* Copy a separating '/' if homedir does not end with one */ + len = curlx_dyn_len(&npath); + p = curlx_dyn_ptr(&npath); + if(len && (p[len - 1] != '/')) + copyfrom = 2; + + if(curlx_dyn_addn(&npath, &working_path[copyfrom], + working_path_len - copyfrom)) { + curlx_free(working_path); + return CURLE_OUT_OF_MEMORY; + } + } + else { + if(curlx_dyn_add(&npath, "/")) { + curlx_free(working_path); + return CURLE_OUT_OF_MEMORY; + } + } + } + + if(curlx_dyn_len(&npath)) { + curlx_free(working_path); + + /* store the pointer for the caller to receive */ + *path = curlx_dyn_ptr(&npath); + } + else + *path = working_path; + DEBUGASSERT(*path && (*path)[0]); + + return CURLE_OK; +} + +#define MAX_PATHLENGTH 65535 /* arbitrary long */ + +CURLcode Curl_get_pathname(const char **cpp, char **path, const char *homedir) +{ + const char *cp = *cpp; + struct dynbuf out; + CURLcode result; + + DEBUGASSERT(homedir); + *path = NULL; + *cpp = NULL; + if(!*cp || !homedir) + return CURLE_QUOTE_ERROR; + + curlx_dyn_init(&out, MAX_PATHLENGTH); + + /* Ignore leading whitespace */ + curlx_str_passblanks(&cp); + + /* Check for quoted filenames */ + if(*cp == '\"' || *cp == '\'') { + char quot = *cp++; + + /* Search for terminating quote, unescape some chars */ + while(*cp != quot) { + if(!*cp) /* End of string */ + goto fail; + + if(*cp == '\\') { /* Escaped characters */ + cp++; + if(*cp != '\'' && *cp != '\"' && *cp != '\\') + goto fail; + } + result = curlx_dyn_addn(&out, cp, 1); + if(result) + return result; + cp++; + } + cp++; /* pass the end quote */ + + if(!curlx_dyn_len(&out)) + goto fail; + } + else { + struct Curl_str word; + bool content = FALSE; + int rc; + /* Handling for relative path - prepend home directory */ + if(cp[0] == '/' && cp[1] == '~' && cp[2] == '/') { + result = curlx_dyn_add(&out, homedir); + if(!result) + result = curlx_dyn_addn(&out, "/", 1); + if(result) + return result; + cp += 3; + content = TRUE; + } + /* Read to end of filename - either to whitespace or terminator */ + rc = curlx_str_word(&cp, &word, MAX_PATHLENGTH); + if(rc) { + if(rc == STRE_BIG) { + curlx_dyn_free(&out); + return CURLE_TOO_LARGE; + } + else if(!content) + /* no path, no word, this is incorrect */ + goto fail; + } + else { + /* append the word */ + result = curlx_dyn_addn(&out, curlx_str(&word), curlx_strlen(&word)); + if(result) + return result; + } + } + /* skip whitespace */ + curlx_str_passblanks(&cp); + + /* return pointer to second parameter if it exists */ + *cpp = cp; + + *path = curlx_dyn_ptr(&out); + return CURLE_OK; + +fail: + curlx_dyn_free(&out); + return CURLE_QUOTE_ERROR; +} + +CURLcode Curl_ssh_range(struct Curl_easy *data, + const char *range, curl_off_t filesize, + curl_off_t *startp, curl_off_t *sizep) +{ + curl_off_t from, to; + int to_t; + int from_t = curlx_str_number(&range, &from, CURL_OFF_T_MAX); + if(from_t == STRE_OVERFLOW) + return CURLE_RANGE_ERROR; + curlx_str_passblanks(&range); + (void)curlx_str_single(&range, '-'); + + to_t = curlx_str_numblanks(&range, &to); + if((to_t == STRE_OVERFLOW) || (to_t && from_t) || *range) + return CURLE_RANGE_ERROR; + + if(from_t) { + /* no start point given, set from relative to end of file */ + if(!to) + /* "-0" is not a fine range */ + return CURLE_RANGE_ERROR; + else if(to > filesize) + to = filesize; + from = filesize - to; + to = filesize - 1; + } + else if(from > filesize) { + failf(data, "Offset (%" FMT_OFF_T ") was beyond file size (%" + FMT_OFF_T ")", from, filesize); + return CURLE_RANGE_ERROR; + } + else if((to_t == STRE_NO_NUM) || (to >= filesize)) + to = filesize - 1; + + if(from > to) { + failf(data, "Bad range: start offset larger than end offset"); + return CURLE_RANGE_ERROR; + } + if((to - from) == CURL_OFF_T_MAX) + return CURLE_RANGE_ERROR; + + *startp = from; + *sizep = to - from + 1; + return CURLE_OK; +} + +/* called by the multi interface to figure out what socket(s) to wait for and + for what actions in the DO_DONE, PERFORM and WAITPERFORM states */ +CURLcode Curl_ssh_pollset(struct Curl_easy *data, struct easy_pollset *ps) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = Curl_conn_meta_get(conn, CURL_META_SSH_CONN); + curl_socket_t sock = conn->sock[FIRSTSOCKET]; + int waitfor; + + if(!sshc || (sock == CURL_SOCKET_BAD)) + return CURLE_FAILED_INIT; + + waitfor = sshc->waitfor ? sshc->waitfor : data->req.io_flags; + if(waitfor) { + int flags = 0; + if(waitfor & REQ_IO_RECV) + flags |= CURL_POLL_IN; + if(waitfor & REQ_IO_SEND) + flags |= CURL_POLL_OUT; + DEBUGASSERT(flags); + CURL_TRC_SSH(data, "pollset, flags=%x", (unsigned int)flags); + return Curl_pollset_change(data, ps, sock, flags, 0); + } + /* While we still have a session, we listen incoming data. */ + if(sshc->ssh_session) + return Curl_pollset_change(data, ps, sock, CURL_POLL_IN, 0); + return CURLE_OK; +} + +CURLcode Curl_ssh_setup_pkey(struct Curl_easy *data, struct ssh_conn *sshc) +{ + char *home = NULL; + if(data->set.ssh_auth_types & CURLSSH_AUTH_PUBLICKEY) { + const char *str; + + sshc->pub_key = sshc->priv_key = NULL; + + if(CURL_EASY_STR(data, STRING_SSH_PRIVATE_KEY)) { + sshc->priv_key = curlx_strdup( + CURL_EASY_STR(data, STRING_SSH_PRIVATE_KEY)); + if(!sshc->priv_key) + goto fail; + } + else { + /* To ponder about: should really the lib be messing about with the HOME + environment variable etc? */ + curlx_struct_stat sbuf; + home = curl_getenv("HOME"); + + /* If no private key file is specified, try some common paths. */ + if(home) { + /* Try ~/.ssh first. */ + sshc->priv_key = curl_maprintf("%s/.ssh/id_rsa", home); + if(!sshc->priv_key) + goto fail; + else if(curlx_stat(sshc->priv_key, &sbuf)) { + curlx_free(sshc->priv_key); + sshc->priv_key = curl_maprintf("%s/.ssh/id_dsa", home); + if(!sshc->priv_key) + goto fail; + else if(curlx_stat(sshc->priv_key, &sbuf)) { + curlx_safefree(sshc->priv_key); + } + } + curlx_safefree(home); + } + if(!sshc->priv_key) { + /* Nothing found; try the current dir. */ + sshc->priv_key = curlx_strdup("id_rsa"); + if(sshc->priv_key && curlx_stat(sshc->priv_key, &sbuf)) { + curlx_free(sshc->priv_key); + sshc->priv_key = curlx_strdup("id_dsa"); + if(sshc->priv_key && curlx_stat(sshc->priv_key, &sbuf)) { + curlx_free(sshc->priv_key); + /* Out of guesses. Set to the empty string to avoid + * surprising info messages. */ + sshc->priv_key = curlx_strdup(""); + } + } + } + } + + /* + * Unless the user explicitly specifies a public key file, let the SSH + * library extract the public key from the private key file. This is done + * by passing sshc->pub_key = NULL. + */ + str = CURL_EASY_STR(data, STRING_SSH_PUBLIC_KEY); + if(str && *str) { /* treat empty string the same way as NULL */ + sshc->pub_key = curlx_strdup(str); + if(!sshc->pub_key) + goto fail; + } + + sshc->passphrase = data->set.ssl.primary.key_passwd; + if(!sshc->passphrase) + sshc->passphrase = ""; + + if(sshc->pub_key) + infof(data, "SSH: public key file '%s'", sshc->pub_key); + if(sshc->priv_key) + infof(data, "SSH: private key file '%s'", sshc->priv_key); + else + infof(data, "SSH: public key auth without private key set!"); + } + return CURLE_OK; + +fail: + curlx_safefree(home); + curlx_safefree(sshc->priv_key); + curlx_safefree(sshc->pub_key); + return CURLE_OUT_OF_MEMORY; +} + +#endif /* USE_SSH */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/vssh.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/vssh.h new file mode 100644 index 0000000000..4c505c453a --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vssh/vssh.h @@ -0,0 +1,48 @@ +#ifndef HEADER_CURL_VSSH_VSSH_H +#define HEADER_CURL_VSSH_VSSH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_SSH + +#include "urldata.h" + +struct ssh_conn; + +CURLcode Curl_getworkingpath(struct Curl_easy *data, + const char *homedir, + char **path); + +CURLcode Curl_get_pathname(const char **cpp, char **path, const char *homedir); + +CURLcode Curl_ssh_range(struct Curl_easy *data, + const char *range, curl_off_t filesize, + curl_off_t *startp, curl_off_t *sizep); + +CURLcode Curl_ssh_pollset(struct Curl_easy *data, struct easy_pollset *ps); +CURLcode Curl_ssh_setup_pkey(struct Curl_easy *data, struct ssh_conn *sshc); + +#endif /* USE_SSH */ +#endif /* HEADER_CURL_VSSH_VSSH_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/apple.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/apple.c new file mode 100644 index 0000000000..ce7f0c5e1c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/apple.c @@ -0,0 +1,296 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* This file is for implementing all "generic" SSL functions that all libcurl + internals should use. It is then responsible for calling the proper + "backend" function. + + SSL-functions in libcurl should call functions in this source file, and not + to any specific SSL-layer. + + Curl_ssl_ - prefix for generic ones + + Note that this source code uses the functions of the configured SSL + backend via the global Curl_ssl instance. + + "SSL/TLS Strong Encryption: An Introduction" + https://httpd.apache.org/docs/2.0/ssl/ssl_intro.html + */ + +#include "curl_setup.h" + +#ifdef USE_APPLE_SECTRUST + +#include "urldata.h" +#include "cfilters.h" +#include "curl_trc.h" +#include "vtls/vtls.h" +#include "vtls/apple.h" + +#include <Security/Security.h> + +#if (defined(MAC_OS_X_VERSION_MAX_ALLOWED) && \ + MAC_OS_X_VERSION_MAX_ALLOWED >= 101400) || \ + (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ + __IPHONE_OS_VERSION_MAX_ALLOWED >= 120000) +#define SUPPORTS_SecTrustEvaluateWithError 1 +#endif + +#if defined(SUPPORTS_SecTrustEvaluateWithError) && \ + ((defined(MAC_OS_X_VERSION_MIN_REQUIRED) && \ + MAC_OS_X_VERSION_MIN_REQUIRED >= 101400) || \ + (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && \ + __IPHONE_OS_VERSION_MIN_REQUIRED >= 120000)) +#define REQUIRES_SecTrustEvaluateWithError 1 +#endif + +#if defined(SUPPORTS_SecTrustEvaluateWithError) && \ + !defined(HAVE_BUILTIN_AVAILABLE) && \ + !defined(REQUIRES_SecTrustEvaluateWithError) +#undef SUPPORTS_SecTrustEvaluateWithError +#endif + +#if (defined(MAC_OS_X_VERSION_MAX_ALLOWED) && \ + MAC_OS_X_VERSION_MAX_ALLOWED >= 100900) || \ + (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ + __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) +#define SUPPORTS_SecOCSP 1 +#endif + +CURLcode Curl_vtls_apple_verify(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + size_t num_certs, + Curl_vtls_get_cert_der *der_cb, + void *cb_user_data, + const unsigned char *ocsp_buf, + size_t ocsp_len) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + CURLcode result = CURLE_OK; + SecTrustRef trust = NULL; + SecPolicyRef policy = NULL; + CFMutableArrayRef policies = NULL; + CFMutableArrayRef cert_array = NULL; + CFStringRef host_str = NULL; + CFErrorRef error = NULL; + OSStatus status = noErr; + CFStringRef error_ref = NULL; + char *err_desc = NULL; + size_t i; + + if(conn_config->verifyhost) { + host_str = CFStringCreateWithCString(NULL, + peer->sni ? peer->sni : peer->origin->hostname, kCFStringEncodingUTF8); + if(!host_str) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + + policies = CFArrayCreateMutable(NULL, 2, &kCFTypeArrayCallBacks); + if(!policies) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + policy = SecPolicyCreateSSL(true, host_str); + if(!policy) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + CFArrayAppendValue(policies, policy); + CFRelease(policy); + policy = NULL; + +#if defined(HAVE_BUILTIN_AVAILABLE) && defined(SUPPORTS_SecOCSP) + { + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + if(!ssl_config->no_revoke) { + if(__builtin_available(macOS 10.9, iOS 7, tvOS 9, watchOS 2, *)) { + /* Even without this set, validation seemingly-unavoidably fails + * for certificates that trustd already knows to be revoked. + * This policy further allows trustd to consult CRLs and OCSP data + * to determine revocation status (which it may then cache). */ + CFOptionFlags revocation_flags = kSecRevocationUseAnyAvailableMethod; +#if 0 + /* `revoke_best_effort` is off by default in libcurl. When we + * add `kSecRevocationRequirePositiveResponse` to the Apple + * Trust policies, it interprets this as it NEEDs a confirmation + * of a cert being NOT REVOKED. Which not in general available for + * certificates on the Internet. + * It seems that applications using this policy are expected to PIN + * their certificate public keys or verification fails. + * This does not seem to be what we want here. */ + if(!ssl_config->revoke_best_effort) { + revocation_flags |= kSecRevocationRequirePositiveResponse; + } +#endif + policy = SecPolicyCreateRevocation(revocation_flags); + if(!policy) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + CFArrayAppendValue(policies, policy); + } + } + } +#endif + + cert_array = CFArrayCreateMutable(NULL, num_certs, &kCFTypeArrayCallBacks); + if(!cert_array) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + for(i = 0; i < num_certs; i++) { + SecCertificateRef cert; + CFDataRef certdata; + unsigned char *der; + size_t der_len; + + result = der_cb(cf, data, cb_user_data, i, &der, &der_len); + if(result) + goto out; + + certdata = CFDataCreate(NULL, der, (CFIndex)der_len); + if(!certdata) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + cert = SecCertificateCreateWithData(NULL, certdata); + CFRelease(certdata); + if(!cert) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + CFArrayAppendValue(cert_array, cert); + CFRelease(cert); + } + + status = SecTrustCreateWithCertificates(cert_array, policies, &trust); + if(status != noErr || !trust) { + failf(data, "Apple SecTrust: failed to create validation trust"); + result = CURLE_PEER_FAILED_VERIFICATION; + goto out; + } + + if(ocsp_len > 0) { + bool checked = FALSE; +#if defined(HAVE_BUILTIN_AVAILABLE) && defined(SUPPORTS_SecOCSP) + if(__builtin_available(macOS 10.9, iOS 7, tvOS 9, watchOS 2, *)) { + CFDataRef ocspdata = CFDataCreate(NULL, ocsp_buf, (CFIndex)ocsp_len); + + status = SecTrustSetOCSPResponse(trust, ocspdata); + CFRelease(ocspdata); + if(status != noErr) { + failf(data, "Apple SecTrust: failed to set OCSP response: %d", + (int)status); + result = CURLE_PEER_FAILED_VERIFICATION; + goto out; + } + checked = TRUE; + } +#endif + if(!checked) { + (void)ocsp_buf; + failf(data, "Apple SecTrust: OCSP verification not supported"); + result = CURLE_NOT_BUILT_IN; + goto out; + } + } + +#ifdef SUPPORTS_SecTrustEvaluateWithError +#ifdef HAVE_BUILTIN_AVAILABLE + if(__builtin_available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *)) { +#else + if(1) { +#endif + result = SecTrustEvaluateWithError(trust, &error) ? + CURLE_OK : CURLE_PEER_FAILED_VERIFICATION; + if(error) { + VERBOSE(CFIndex code = CFErrorGetCode(error)); + error_ref = CFErrorCopyDescription(error); + + if(error_ref) { + CFIndex size = CFStringGetMaximumSizeForEncoding( + CFStringGetLength(error_ref), kCFStringEncodingUTF8); + err_desc = curlx_malloc(size + 1); + if(err_desc) { + if(!CFStringGetCString(error_ref, err_desc, size, + kCFStringEncodingUTF8)) + curlx_safefree(err_desc); + } + } + infof(data, "Apple SecTrust failure %ld%s%s", code, + err_desc ? ": " : "", err_desc ? err_desc : ""); + } + } + else +#endif /* SUPPORTS_SecTrustEvaluateWithError */ + { +#ifndef REQUIRES_SecTrustEvaluateWithError + SecTrustResultType sec_result; + status = SecTrustEvaluate(trust, &sec_result); + + if(status != noErr) { + failf(data, "Apple SecTrust verification failed: error %d", (int)status); + result = CURLE_PEER_FAILED_VERIFICATION; + } + else if((sec_result == kSecTrustResultUnspecified) || + (sec_result == kSecTrustResultProceed)) { + /* "unspecified" means system-trusted with no explicit user setting */ + result = CURLE_OK; + } + else { + /* Any other trust result is a verification failure in this context */ + result = CURLE_PEER_FAILED_VERIFICATION; + } +#endif /* REQUIRES_SecTrustEvaluateWithError */ + } + +out: + curlx_free(err_desc); + if(error_ref) + CFRelease(error_ref); + if(error) + CFRelease(error); + if(host_str) + CFRelease(host_str); + if(policies) + CFRelease(policies); + if(policy) + CFRelease(policy); + if(cert_array) + CFRelease(cert_array); + if(trust) + CFRelease(trust); + return result; +} + +#endif /* USE_APPLE_SECTRUST */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/apple.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/apple.h new file mode 100644 index 0000000000..d86a56b1f9 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/apple.h @@ -0,0 +1,54 @@ +#ifndef HEADER_CURL_VTLS_APPLE_H +#define HEADER_CURL_VTLS_APPLE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Jan Venekamp, <jan@venekamp.net> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_APPLE_SECTRUST +struct Curl_cfilter; +struct Curl_easy; +struct ssl_peer; + +/* Get the DER encoded i-th certificate in the server handshake */ +typedef CURLcode Curl_vtls_get_cert_der(struct Curl_cfilter *cf, + struct Curl_easy *data, + void *user_data, + size_t i, + unsigned char **pder, + size_t *pder_len); + +/* Ask Apple's Security framework to verify the certificate chain + * send by the peer. On CURLE_OK it has been verified. + */ +CURLcode Curl_vtls_apple_verify(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + size_t num_certs, + Curl_vtls_get_cert_der *der_cb, + void *cb_user_data, + const unsigned char *ocsp_buf, + size_t ocsp_len); +#endif /* USE_APPLE_SECTRUST */ + +#endif /* HEADER_CURL_VTLS_APPLE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/cipher_suite.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/cipher_suite.c new file mode 100644 index 0000000000..2c6a0c02d0 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/cipher_suite.c @@ -0,0 +1,702 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Jan Venekamp, <jan@venekamp.net> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_MBEDTLS) || defined(USE_RUSTLS) + +#include "vtls/cipher_suite.h" + +/* + * To support the CURLOPT_SSL_CIPHER_LIST option on SSL backends + * that do not support it natively, but do support setting a list of + * IANA ids, we need a list of all supported cipher suite names + * (OpenSSL and IANA) to be able to look up the IANA ids. + * + * To keep the binary size of this list down we compress each entry + * down to 2 + 6 bytes using the C preprocessor. + */ + +/* + * mbedTLS NOTE: mbedTLS has mbedtls_ssl_get_ciphersuite_id() to + * convert a string representation to an IANA id, we do not use that + * because it does not support "standard" OpenSSL cipher suite + * names, nor IANA names. + */ + +/* NOTE: also see tests/unit/unit3205.c */ + +/* Text for cipher suite parts (max 64 entries), + keep indexes below in sync with this! */ +static const char cs_txt[] = + "\0" + "TLS" "\0" + "WITH" "\0" + "128" "\0" + "256" "\0" + "3DES" "\0" + "8" "\0" + "AES" "\0" + "AES128" "\0" + "AES256" "\0" + "CBC" "\0" + "CBC3" "\0" + "CCM" "\0" + "CCM8" "\0" + "CHACHA20" "\0" + "DES" "\0" + "DHE" "\0" + "ECDH" "\0" + "ECDHE" "\0" + "ECDSA" "\0" + "EDE" "\0" /* spellchecker:disable-line */ + "GCM" "\0" + "MD5" "\0" + "NULL" "\0" + "POLY1305" "\0" + "PSK" "\0" + "RSA" "\0" + "SHA" "\0" + "SHA256" "\0" + "SHA384" "\0" +#ifdef USE_MBEDTLS + "ARIA" "\0" + "ARIA128" "\0" + "ARIA256" "\0" + "CAMELLIA" "\0" + "CAMELLIA128" "\0" + "CAMELLIA256" "\0" +#endif +; +/* Indexes of above cs_txt */ +enum { + CS_TXT_IDX_, + CS_TXT_IDX_TLS, + CS_TXT_IDX_WITH, + CS_TXT_IDX_128, + CS_TXT_IDX_256, + CS_TXT_IDX_3DES, + CS_TXT_IDX_8, + CS_TXT_IDX_AES, + CS_TXT_IDX_AES128, + CS_TXT_IDX_AES256, + CS_TXT_IDX_CBC, + CS_TXT_IDX_CBC3, + CS_TXT_IDX_CCM, + CS_TXT_IDX_CCM8, + CS_TXT_IDX_CHACHA20, + CS_TXT_IDX_DES, + CS_TXT_IDX_DHE, + CS_TXT_IDX_ECDH, + CS_TXT_IDX_ECDHE, + CS_TXT_IDX_ECDSA, + CS_TXT_IDX_EDE, /* spellchecker:disable-line */ + CS_TXT_IDX_GCM, + CS_TXT_IDX_MD5, + CS_TXT_IDX_NULL, + CS_TXT_IDX_POLY1305, + CS_TXT_IDX_PSK, + CS_TXT_IDX_RSA, + CS_TXT_IDX_SHA, + CS_TXT_IDX_SHA256, + CS_TXT_IDX_SHA384, +#ifdef USE_MBEDTLS + CS_TXT_IDX_ARIA, + CS_TXT_IDX_ARIA128, + CS_TXT_IDX_ARIA256, + CS_TXT_IDX_CAMELLIA, + CS_TXT_IDX_CAMELLIA128, + CS_TXT_IDX_CAMELLIA256, +#endif + CS_TXT_LEN, +}; + +#define CS_ZIP_IDX(a, b, c, d, e, f, g, h) \ +{ \ + (uint8_t)((((a) << 2) & 0xFF) | ((b) & 0x3F) >> 4), \ + (uint8_t)((((b) << 4) & 0xFF) | ((c) & 0x3F) >> 2), \ + (uint8_t)((((c) << 6) & 0xFF) | ((d) & 0x3F)), \ + (uint8_t)((((e) << 2) & 0xFF) | ((f) & 0x3F) >> 4), \ + (uint8_t)((((f) << 4) & 0xFF) | ((g) & 0x3F) >> 2), \ + (uint8_t)((((g) << 6) & 0xFF) | ((h) & 0x3F)) \ +} +#define CS_ENTRY(id, a, b, c, d, e, f, g, h) \ +{ \ + id, \ + CS_ZIP_IDX( \ + CS_TXT_IDX_ ## a, CS_TXT_IDX_ ## b, \ + CS_TXT_IDX_ ## c, CS_TXT_IDX_ ## d, \ + CS_TXT_IDX_ ## e, CS_TXT_IDX_ ## f, \ + CS_TXT_IDX_ ## g, CS_TXT_IDX_ ## h \ + ) \ +} + +struct cs_entry { + uint16_t id; + uint8_t zip[6]; +}; + +/* !checksrc! disable COMMANOSPACE all */ +static const struct cs_entry cs_list[] = { + /* TLS 1.3 ciphers */ + CS_ENTRY(0x1301, TLS,AES,128,GCM,SHA256,,,), + CS_ENTRY(0x1302, TLS,AES,256,GCM,SHA384,,,), + CS_ENTRY(0x1303, TLS,CHACHA20,POLY1305,SHA256,,,,), + CS_ENTRY(0x1304, TLS,AES,128,CCM,SHA256,,,), + CS_ENTRY(0x1305, TLS,AES,128,CCM,8,SHA256,,), + /* TLS 1.2 ciphers */ + CS_ENTRY(0xC02B, TLS,ECDHE,ECDSA,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0xC02B, ECDHE,ECDSA,AES128,GCM,SHA256,,,), + CS_ENTRY(0xC02C, TLS,ECDHE,ECDSA,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0xC02C, ECDHE,ECDSA,AES256,GCM,SHA384,,,), + CS_ENTRY(0xC02F, TLS,ECDHE,RSA,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0xC02F, ECDHE,RSA,AES128,GCM,SHA256,,,), + CS_ENTRY(0xC030, TLS,ECDHE,RSA,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0xC030, ECDHE,RSA,AES256,GCM,SHA384,,,), + CS_ENTRY(0xCCA8, TLS,ECDHE,RSA,WITH,CHACHA20,POLY1305,SHA256,), + CS_ENTRY(0xCCA8, ECDHE,RSA,CHACHA20,POLY1305,,,,), + CS_ENTRY(0xCCA9, TLS,ECDHE,ECDSA,WITH,CHACHA20,POLY1305,SHA256,), + CS_ENTRY(0xCCA9, ECDHE,ECDSA,CHACHA20,POLY1305,,,,), +#ifdef USE_MBEDTLS + CS_ENTRY(0x002F, TLS,RSA,WITH,AES,128,CBC,SHA,), + CS_ENTRY(0x002F, AES128,SHA,,,,,,), + CS_ENTRY(0x0035, TLS,RSA,WITH,AES,256,CBC,SHA,), + CS_ENTRY(0x0035, AES256,SHA,,,,,,), + CS_ENTRY(0x003C, TLS,RSA,WITH,AES,128,CBC,SHA256,), + CS_ENTRY(0x003C, AES128,SHA256,,,,,,), + CS_ENTRY(0x003D, TLS,RSA,WITH,AES,256,CBC,SHA256,), + CS_ENTRY(0x003D, AES256,SHA256,,,,,,), + CS_ENTRY(0x009C, TLS,RSA,WITH,AES,128,GCM,SHA256,), + CS_ENTRY(0x009C, AES128,GCM,SHA256,,,,,), + CS_ENTRY(0x009D, TLS,RSA,WITH,AES,256,GCM,SHA384,), + CS_ENTRY(0x009D, AES256,GCM,SHA384,,,,,), + CS_ENTRY(0xC004, TLS,ECDH,ECDSA,WITH,AES,128,CBC,SHA), + CS_ENTRY(0xC004, ECDH,ECDSA,AES128,SHA,,,,), + CS_ENTRY(0xC005, TLS,ECDH,ECDSA,WITH,AES,256,CBC,SHA), + CS_ENTRY(0xC005, ECDH,ECDSA,AES256,SHA,,,,), + CS_ENTRY(0xC009, TLS,ECDHE,ECDSA,WITH,AES,128,CBC,SHA), + CS_ENTRY(0xC009, ECDHE,ECDSA,AES128,SHA,,,,), + CS_ENTRY(0xC00A, TLS,ECDHE,ECDSA,WITH,AES,256,CBC,SHA), + CS_ENTRY(0xC00A, ECDHE,ECDSA,AES256,SHA,,,,), + CS_ENTRY(0xC00E, TLS,ECDH,RSA,WITH,AES,128,CBC,SHA), + CS_ENTRY(0xC00E, ECDH,RSA,AES128,SHA,,,,), + CS_ENTRY(0xC00F, TLS,ECDH,RSA,WITH,AES,256,CBC,SHA), + CS_ENTRY(0xC00F, ECDH,RSA,AES256,SHA,,,,), + CS_ENTRY(0xC013, TLS,ECDHE,RSA,WITH,AES,128,CBC,SHA), + CS_ENTRY(0xC013, ECDHE,RSA,AES128,SHA,,,,), + CS_ENTRY(0xC014, TLS,ECDHE,RSA,WITH,AES,256,CBC,SHA), + CS_ENTRY(0xC014, ECDHE,RSA,AES256,SHA,,,,), + CS_ENTRY(0xC023, TLS,ECDHE,ECDSA,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0xC023, ECDHE,ECDSA,AES128,SHA256,,,,), + CS_ENTRY(0xC024, TLS,ECDHE,ECDSA,WITH,AES,256,CBC,SHA384), + CS_ENTRY(0xC024, ECDHE,ECDSA,AES256,SHA384,,,,), + CS_ENTRY(0xC025, TLS,ECDH,ECDSA,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0xC025, ECDH,ECDSA,AES128,SHA256,,,,), + CS_ENTRY(0xC026, TLS,ECDH,ECDSA,WITH,AES,256,CBC,SHA384), + CS_ENTRY(0xC026, ECDH,ECDSA,AES256,SHA384,,,,), + CS_ENTRY(0xC027, TLS,ECDHE,RSA,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0xC027, ECDHE,RSA,AES128,SHA256,,,,), + CS_ENTRY(0xC028, TLS,ECDHE,RSA,WITH,AES,256,CBC,SHA384), + CS_ENTRY(0xC028, ECDHE,RSA,AES256,SHA384,,,,), + CS_ENTRY(0xC029, TLS,ECDH,RSA,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0xC029, ECDH,RSA,AES128,SHA256,,,,), + CS_ENTRY(0xC02A, TLS,ECDH,RSA,WITH,AES,256,CBC,SHA384), + CS_ENTRY(0xC02A, ECDH,RSA,AES256,SHA384,,,,), + CS_ENTRY(0xC02D, TLS,ECDH,ECDSA,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0xC02D, ECDH,ECDSA,AES128,GCM,SHA256,,,), + CS_ENTRY(0xC02E, TLS,ECDH,ECDSA,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0xC02E, ECDH,ECDSA,AES256,GCM,SHA384,,,), + CS_ENTRY(0xC031, TLS,ECDH,RSA,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0xC031, ECDH,RSA,AES128,GCM,SHA256,,,), + CS_ENTRY(0xC032, TLS,ECDH,RSA,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0xC032, ECDH,RSA,AES256,GCM,SHA384,,,), + CS_ENTRY(0x0001, TLS,RSA,WITH,NULL,MD5,,,), + CS_ENTRY(0x0001, NULL,MD5,,,,,,), + CS_ENTRY(0x0002, TLS,RSA,WITH,NULL,SHA,,,), + CS_ENTRY(0x0002, NULL,SHA,,,,,,), + CS_ENTRY(0x002C, TLS,PSK,WITH,NULL,SHA,,,), + CS_ENTRY(0x002C, PSK,NULL,SHA,,,,,), + CS_ENTRY(0x002D, TLS,DHE,PSK,WITH,NULL,SHA,,), + CS_ENTRY(0x002D, DHE,PSK,NULL,SHA,,,,), + CS_ENTRY(0x002E, TLS,RSA,PSK,WITH,NULL,SHA,,), + CS_ENTRY(0x002E, RSA,PSK,NULL,SHA,,,,), + CS_ENTRY(0x0033, TLS,DHE,RSA,WITH,AES,128,CBC,SHA), + CS_ENTRY(0x0033, DHE,RSA,AES128,SHA,,,,), + CS_ENTRY(0x0039, TLS,DHE,RSA,WITH,AES,256,CBC,SHA), + CS_ENTRY(0x0039, DHE,RSA,AES256,SHA,,,,), + CS_ENTRY(0x003B, TLS,RSA,WITH,NULL,SHA256,,,), + CS_ENTRY(0x003B, NULL,SHA256,,,,,,), + CS_ENTRY(0x0067, TLS,DHE,RSA,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0x0067, DHE,RSA,AES128,SHA256,,,,), + CS_ENTRY(0x006B, TLS,DHE,RSA,WITH,AES,256,CBC,SHA256), + CS_ENTRY(0x006B, DHE,RSA,AES256,SHA256,,,,), + CS_ENTRY(0x008C, TLS,PSK,WITH,AES,128,CBC,SHA,), + CS_ENTRY(0x008C, PSK,AES128,CBC,SHA,,,,), + CS_ENTRY(0x008D, TLS,PSK,WITH,AES,256,CBC,SHA,), + CS_ENTRY(0x008D, PSK,AES256,CBC,SHA,,,,), + CS_ENTRY(0x0090, TLS,DHE,PSK,WITH,AES,128,CBC,SHA), + CS_ENTRY(0x0090, DHE,PSK,AES128,CBC,SHA,,,), + CS_ENTRY(0x0091, TLS,DHE,PSK,WITH,AES,256,CBC,SHA), + CS_ENTRY(0x0091, DHE,PSK,AES256,CBC,SHA,,,), + CS_ENTRY(0x0094, TLS,RSA,PSK,WITH,AES,128,CBC,SHA), + CS_ENTRY(0x0094, RSA,PSK,AES128,CBC,SHA,,,), + CS_ENTRY(0x0095, TLS,RSA,PSK,WITH,AES,256,CBC,SHA), + CS_ENTRY(0x0095, RSA,PSK,AES256,CBC,SHA,,,), + CS_ENTRY(0x009E, TLS,DHE,RSA,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0x009E, DHE,RSA,AES128,GCM,SHA256,,,), + CS_ENTRY(0x009F, TLS,DHE,RSA,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0x009F, DHE,RSA,AES256,GCM,SHA384,,,), + CS_ENTRY(0x00A8, TLS,PSK,WITH,AES,128,GCM,SHA256,), + CS_ENTRY(0x00A8, PSK,AES128,GCM,SHA256,,,,), + CS_ENTRY(0x00A9, TLS,PSK,WITH,AES,256,GCM,SHA384,), + CS_ENTRY(0x00A9, PSK,AES256,GCM,SHA384,,,,), + CS_ENTRY(0x00AA, TLS,DHE,PSK,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0x00AA, DHE,PSK,AES128,GCM,SHA256,,,), + CS_ENTRY(0x00AB, TLS,DHE,PSK,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0x00AB, DHE,PSK,AES256,GCM,SHA384,,,), + CS_ENTRY(0x00AC, TLS,RSA,PSK,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0x00AC, RSA,PSK,AES128,GCM,SHA256,,,), + CS_ENTRY(0x00AD, TLS,RSA,PSK,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0x00AD, RSA,PSK,AES256,GCM,SHA384,,,), + CS_ENTRY(0x00AE, TLS,PSK,WITH,AES,128,CBC,SHA256,), + CS_ENTRY(0x00AE, PSK,AES128,CBC,SHA256,,,,), + CS_ENTRY(0x00AF, TLS,PSK,WITH,AES,256,CBC,SHA384,), + CS_ENTRY(0x00AF, PSK,AES256,CBC,SHA384,,,,), + CS_ENTRY(0x00B0, TLS,PSK,WITH,NULL,SHA256,,,), + CS_ENTRY(0x00B0, PSK,NULL,SHA256,,,,,), + CS_ENTRY(0x00B1, TLS,PSK,WITH,NULL,SHA384,,,), + CS_ENTRY(0x00B1, PSK,NULL,SHA384,,,,,), + CS_ENTRY(0x00B2, TLS,DHE,PSK,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0x00B2, DHE,PSK,AES128,CBC,SHA256,,,), + CS_ENTRY(0x00B3, TLS,DHE,PSK,WITH,AES,256,CBC,SHA384), + CS_ENTRY(0x00B3, DHE,PSK,AES256,CBC,SHA384,,,), + CS_ENTRY(0x00B4, TLS,DHE,PSK,WITH,NULL,SHA256,,), + CS_ENTRY(0x00B4, DHE,PSK,NULL,SHA256,,,,), + CS_ENTRY(0x00B5, TLS,DHE,PSK,WITH,NULL,SHA384,,), + CS_ENTRY(0x00B5, DHE,PSK,NULL,SHA384,,,,), + CS_ENTRY(0x00B6, TLS,RSA,PSK,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0x00B6, RSA,PSK,AES128,CBC,SHA256,,,), + CS_ENTRY(0x00B7, TLS,RSA,PSK,WITH,AES,256,CBC,SHA384), + CS_ENTRY(0x00B7, RSA,PSK,AES256,CBC,SHA384,,,), + CS_ENTRY(0x00B8, TLS,RSA,PSK,WITH,NULL,SHA256,,), + CS_ENTRY(0x00B8, RSA,PSK,NULL,SHA256,,,,), + CS_ENTRY(0x00B9, TLS,RSA,PSK,WITH,NULL,SHA384,,), + CS_ENTRY(0x00B9, RSA,PSK,NULL,SHA384,,,,), + CS_ENTRY(0xC001, TLS,ECDH,ECDSA,WITH,NULL,SHA,,), + CS_ENTRY(0xC001, ECDH,ECDSA,NULL,SHA,,,,), + CS_ENTRY(0xC006, TLS,ECDHE,ECDSA,WITH,NULL,SHA,,), + CS_ENTRY(0xC006, ECDHE,ECDSA,NULL,SHA,,,,), + CS_ENTRY(0xC00B, TLS,ECDH,RSA,WITH,NULL,SHA,,), + CS_ENTRY(0xC00B, ECDH,RSA,NULL,SHA,,,,), + CS_ENTRY(0xC010, TLS,ECDHE,RSA,WITH,NULL,SHA,,), + CS_ENTRY(0xC010, ECDHE,RSA,NULL,SHA,,,,), + CS_ENTRY(0xC035, TLS,ECDHE,PSK,WITH,AES,128,CBC,SHA), + CS_ENTRY(0xC035, ECDHE,PSK,AES128,CBC,SHA,,,), + CS_ENTRY(0xC036, TLS,ECDHE,PSK,WITH,AES,256,CBC,SHA), + CS_ENTRY(0xC036, ECDHE,PSK,AES256,CBC,SHA,,,), + CS_ENTRY(0xCCAB, TLS,PSK,WITH,CHACHA20,POLY1305,SHA256,,), + CS_ENTRY(0xCCAB, PSK,CHACHA20,POLY1305,,,,,), + CS_ENTRY(0xC09C, TLS,RSA,WITH,AES,128,CCM,,), + CS_ENTRY(0xC09C, AES128,CCM,,,,,,), + CS_ENTRY(0xC09D, TLS,RSA,WITH,AES,256,CCM,,), + CS_ENTRY(0xC09D, AES256,CCM,,,,,,), + CS_ENTRY(0xC0A0, TLS,RSA,WITH,AES,128,CCM,8,), + CS_ENTRY(0xC0A0, AES128,CCM8,,,,,,), + CS_ENTRY(0xC0A1, TLS,RSA,WITH,AES,256,CCM,8,), + CS_ENTRY(0xC0A1, AES256,CCM8,,,,,,), + CS_ENTRY(0xC0AC, TLS,ECDHE,ECDSA,WITH,AES,128,CCM,), + CS_ENTRY(0xC0AC, ECDHE,ECDSA,AES128,CCM,,,,), + CS_ENTRY(0xC0AD, TLS,ECDHE,ECDSA,WITH,AES,256,CCM,), + CS_ENTRY(0xC0AD, ECDHE,ECDSA,AES256,CCM,,,,), + CS_ENTRY(0xC0AE, TLS,ECDHE,ECDSA,WITH,AES,128,CCM,8), + CS_ENTRY(0xC0AE, ECDHE,ECDSA,AES128,CCM8,,,,), + CS_ENTRY(0xC0AF, TLS,ECDHE,ECDSA,WITH,AES,256,CCM,8), + CS_ENTRY(0xC0AF, ECDHE,ECDSA,AES256,CCM8,,,,), + /* entries marked ns are "non-standard", they are not in OpenSSL */ + CS_ENTRY(0x0041, TLS,RSA,WITH,CAMELLIA,128,CBC,SHA,), + CS_ENTRY(0x0041, CAMELLIA128,SHA,,,,,,), + CS_ENTRY(0x0045, TLS,DHE,RSA,WITH,CAMELLIA,128,CBC,SHA), + CS_ENTRY(0x0045, DHE,RSA,CAMELLIA128,SHA,,,,), + CS_ENTRY(0x0084, TLS,RSA,WITH,CAMELLIA,256,CBC,SHA,), + CS_ENTRY(0x0084, CAMELLIA256,SHA,,,,,,), + CS_ENTRY(0x0088, TLS,DHE,RSA,WITH,CAMELLIA,256,CBC,SHA), + CS_ENTRY(0x0088, DHE,RSA,CAMELLIA256,SHA,,,,), + CS_ENTRY(0x00BA, TLS,RSA,WITH,CAMELLIA,128,CBC,SHA256,), + CS_ENTRY(0x00BA, CAMELLIA128,SHA256,,,,,,), + CS_ENTRY(0x00BE, TLS,DHE,RSA,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0x00BE, DHE,RSA,CAMELLIA128,SHA256,,,,), + CS_ENTRY(0x00C0, TLS,RSA,WITH,CAMELLIA,256,CBC,SHA256,), + CS_ENTRY(0x00C0, CAMELLIA256,SHA256,,,,,,), + CS_ENTRY(0x00C4, TLS,DHE,RSA,WITH,CAMELLIA,256,CBC,SHA256), + CS_ENTRY(0x00C4, DHE,RSA,CAMELLIA256,SHA256,,,,), + CS_ENTRY(0xC037, TLS,ECDHE,PSK,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0xC037, ECDHE,PSK,AES128,CBC,SHA256,,,), + CS_ENTRY(0xC038, TLS,ECDHE,PSK,WITH,AES,256,CBC,SHA384), + CS_ENTRY(0xC038, ECDHE,PSK,AES256,CBC,SHA384,,,), + CS_ENTRY(0xC039, TLS,ECDHE,PSK,WITH,NULL,SHA,,), + CS_ENTRY(0xC039, ECDHE,PSK,NULL,SHA,,,,), + CS_ENTRY(0xC03A, TLS,ECDHE,PSK,WITH,NULL,SHA256,,), + CS_ENTRY(0xC03A, ECDHE,PSK,NULL,SHA256,,,,), + CS_ENTRY(0xC03B, TLS,ECDHE,PSK,WITH,NULL,SHA384,,), + CS_ENTRY(0xC03B, ECDHE,PSK,NULL,SHA384,,,,), + CS_ENTRY(0xC03C, TLS,RSA,WITH,ARIA,128,CBC,SHA256,), + CS_ENTRY(0xC03C, ARIA128,SHA256,,,,,,), /* ns */ + CS_ENTRY(0xC03D, TLS,RSA,WITH,ARIA,256,CBC,SHA384,), + CS_ENTRY(0xC03D, ARIA256,SHA384,,,,,,), /* ns */ + CS_ENTRY(0xC044, TLS,DHE,RSA,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC044, DHE,RSA,ARIA128,SHA256,,,,), /* ns */ + CS_ENTRY(0xC045, TLS,DHE,RSA,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC045, DHE,RSA,ARIA256,SHA384,,,,), /* ns */ + CS_ENTRY(0xC048, TLS,ECDHE,ECDSA,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC048, ECDHE,ECDSA,ARIA128,SHA256,,,,), /* ns */ + CS_ENTRY(0xC049, TLS,ECDHE,ECDSA,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC049, ECDHE,ECDSA,ARIA256,SHA384,,,,), /* ns */ + CS_ENTRY(0xC04A, TLS,ECDH,ECDSA,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC04A, ECDH,ECDSA,ARIA128,SHA256,,,,), /* ns */ + CS_ENTRY(0xC04B, TLS,ECDH,ECDSA,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC04B, ECDH,ECDSA,ARIA256,SHA384,,,,), /* ns */ + CS_ENTRY(0xC04C, TLS,ECDHE,RSA,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC04C, ECDHE,ARIA128,SHA256,,,,,), /* ns */ + CS_ENTRY(0xC04D, TLS,ECDHE,RSA,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC04D, ECDHE,ARIA256,SHA384,,,,,), /* ns */ + CS_ENTRY(0xC04E, TLS,ECDH,RSA,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC04E, ECDH,ARIA128,SHA256,,,,,), /* ns */ + CS_ENTRY(0xC04F, TLS,ECDH,RSA,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC04F, ECDH,ARIA256,SHA384,,,,,), /* ns */ + CS_ENTRY(0xC050, TLS,RSA,WITH,ARIA,128,GCM,SHA256,), + CS_ENTRY(0xC050, ARIA128,GCM,SHA256,,,,,), + CS_ENTRY(0xC051, TLS,RSA,WITH,ARIA,256,GCM,SHA384,), + CS_ENTRY(0xC051, ARIA256,GCM,SHA384,,,,,), + CS_ENTRY(0xC052, TLS,DHE,RSA,WITH,ARIA,128,GCM,SHA256), + CS_ENTRY(0xC052, DHE,RSA,ARIA128,GCM,SHA256,,,), + CS_ENTRY(0xC053, TLS,DHE,RSA,WITH,ARIA,256,GCM,SHA384), + CS_ENTRY(0xC053, DHE,RSA,ARIA256,GCM,SHA384,,,), + CS_ENTRY(0xC05C, TLS,ECDHE,ECDSA,WITH,ARIA,128,GCM,SHA256), + CS_ENTRY(0xC05C, ECDHE,ECDSA,ARIA128,GCM,SHA256,,,), + CS_ENTRY(0xC05D, TLS,ECDHE,ECDSA,WITH,ARIA,256,GCM,SHA384), + CS_ENTRY(0xC05D, ECDHE,ECDSA,ARIA256,GCM,SHA384,,,), + CS_ENTRY(0xC05E, TLS,ECDH,ECDSA,WITH,ARIA,128,GCM,SHA256), + CS_ENTRY(0xC05E, ECDH,ECDSA,ARIA128,GCM,SHA256,,,), /* ns */ + CS_ENTRY(0xC05F, TLS,ECDH,ECDSA,WITH,ARIA,256,GCM,SHA384), + CS_ENTRY(0xC05F, ECDH,ECDSA,ARIA256,GCM,SHA384,,,), /* ns */ + CS_ENTRY(0xC060, TLS,ECDHE,RSA,WITH,ARIA,128,GCM,SHA256), + CS_ENTRY(0xC060, ECDHE,ARIA128,GCM,SHA256,,,,), + CS_ENTRY(0xC061, TLS,ECDHE,RSA,WITH,ARIA,256,GCM,SHA384), + CS_ENTRY(0xC061, ECDHE,ARIA256,GCM,SHA384,,,,), + CS_ENTRY(0xC062, TLS,ECDH,RSA,WITH,ARIA,128,GCM,SHA256), + CS_ENTRY(0xC062, ECDH,ARIA128,GCM,SHA256,,,,), /* ns */ + CS_ENTRY(0xC063, TLS,ECDH,RSA,WITH,ARIA,256,GCM,SHA384), + CS_ENTRY(0xC063, ECDH,ARIA256,GCM,SHA384,,,,), /* ns */ + CS_ENTRY(0xC064, TLS,PSK,WITH,ARIA,128,CBC,SHA256,), + CS_ENTRY(0xC064, PSK,ARIA128,SHA256,,,,,), /* ns */ + CS_ENTRY(0xC065, TLS,PSK,WITH,ARIA,256,CBC,SHA384,), + CS_ENTRY(0xC065, PSK,ARIA256,SHA384,,,,,), /* ns */ + CS_ENTRY(0xC066, TLS,DHE,PSK,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC066, DHE,PSK,ARIA128,SHA256,,,,), /* ns */ + CS_ENTRY(0xC067, TLS,DHE,PSK,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC067, DHE,PSK,ARIA256,SHA384,,,,), /* ns */ + CS_ENTRY(0xC068, TLS,RSA,PSK,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC068, RSA,PSK,ARIA128,SHA256,,,,), /* ns */ + CS_ENTRY(0xC069, TLS,RSA,PSK,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC069, RSA,PSK,ARIA256,SHA384,,,,), /* ns */ + CS_ENTRY(0xC06A, TLS,PSK,WITH,ARIA,128,GCM,SHA256,), + CS_ENTRY(0xC06A, PSK,ARIA128,GCM,SHA256,,,,), + CS_ENTRY(0xC06B, TLS,PSK,WITH,ARIA,256,GCM,SHA384,), + CS_ENTRY(0xC06B, PSK,ARIA256,GCM,SHA384,,,,), + CS_ENTRY(0xC06C, TLS,DHE,PSK,WITH,ARIA,128,GCM,SHA256), + CS_ENTRY(0xC06C, DHE,PSK,ARIA128,GCM,SHA256,,,), + CS_ENTRY(0xC06D, TLS,DHE,PSK,WITH,ARIA,256,GCM,SHA384), + CS_ENTRY(0xC06D, DHE,PSK,ARIA256,GCM,SHA384,,,), + CS_ENTRY(0xC06E, TLS,RSA,PSK,WITH,ARIA,128,GCM,SHA256), + CS_ENTRY(0xC06E, RSA,PSK,ARIA128,GCM,SHA256,,,), + CS_ENTRY(0xC06F, TLS,RSA,PSK,WITH,ARIA,256,GCM,SHA384), + CS_ENTRY(0xC06F, RSA,PSK,ARIA256,GCM,SHA384,,,), + CS_ENTRY(0xC070, TLS,ECDHE,PSK,WITH,ARIA,128,CBC,SHA256), + CS_ENTRY(0xC070, ECDHE,PSK,ARIA128,SHA256,,,,), /* ns */ + CS_ENTRY(0xC071, TLS,ECDHE,PSK,WITH,ARIA,256,CBC,SHA384), + CS_ENTRY(0xC071, ECDHE,PSK,ARIA256,SHA384,,,,), /* ns */ + CS_ENTRY(0xC072, TLS,ECDHE,ECDSA,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0xC072, ECDHE,ECDSA,CAMELLIA128,SHA256,,,,), + CS_ENTRY(0xC073, TLS,ECDHE,ECDSA,WITH,CAMELLIA,256,CBC,SHA384), + CS_ENTRY(0xC073, ECDHE,ECDSA,CAMELLIA256,SHA384,,,,), + CS_ENTRY(0xC074, TLS,ECDH,ECDSA,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0xC074, ECDH,ECDSA,CAMELLIA128,SHA256,,,,), /* ns */ + CS_ENTRY(0xC075, TLS,ECDH,ECDSA,WITH,CAMELLIA,256,CBC,SHA384), + CS_ENTRY(0xC075, ECDH,ECDSA,CAMELLIA256,SHA384,,,,), /* ns */ + CS_ENTRY(0xC076, TLS,ECDHE,RSA,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0xC076, ECDHE,RSA,CAMELLIA128,SHA256,,,,), + CS_ENTRY(0xC077, TLS,ECDHE,RSA,WITH,CAMELLIA,256,CBC,SHA384), + CS_ENTRY(0xC077, ECDHE,RSA,CAMELLIA256,SHA384,,,,), + CS_ENTRY(0xC078, TLS,ECDH,RSA,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0xC078, ECDH,CAMELLIA128,SHA256,,,,,), /* ns */ + CS_ENTRY(0xC079, TLS,ECDH,RSA,WITH,CAMELLIA,256,CBC,SHA384), + CS_ENTRY(0xC079, ECDH,CAMELLIA256,SHA384,,,,,), /* ns */ + CS_ENTRY(0xC07A, TLS,RSA,WITH,CAMELLIA,128,GCM,SHA256,), + CS_ENTRY(0xC07A, CAMELLIA128,GCM,SHA256,,,,,), /* ns */ + CS_ENTRY(0xC07B, TLS,RSA,WITH,CAMELLIA,256,GCM,SHA384,), + CS_ENTRY(0xC07B, CAMELLIA256,GCM,SHA384,,,,,), /* ns */ + CS_ENTRY(0xC07C, TLS,DHE,RSA,WITH,CAMELLIA,128,GCM,SHA256), + CS_ENTRY(0xC07C, DHE,RSA,CAMELLIA128,GCM,SHA256,,,), /* ns */ + CS_ENTRY(0xC07D, TLS,DHE,RSA,WITH,CAMELLIA,256,GCM,SHA384), + CS_ENTRY(0xC07D, DHE,RSA,CAMELLIA256,GCM,SHA384,,,), /* ns */ + CS_ENTRY(0xC086, TLS,ECDHE,ECDSA,WITH,CAMELLIA,128,GCM,SHA256), + CS_ENTRY(0xC086, ECDHE,ECDSA,CAMELLIA128,GCM,SHA256,,,), /* ns */ + CS_ENTRY(0xC087, TLS,ECDHE,ECDSA,WITH,CAMELLIA,256,GCM,SHA384), + CS_ENTRY(0xC087, ECDHE,ECDSA,CAMELLIA256,GCM,SHA384,,,), /* ns */ + CS_ENTRY(0xC088, TLS,ECDH,ECDSA,WITH,CAMELLIA,128,GCM,SHA256), + CS_ENTRY(0xC088, ECDH,ECDSA,CAMELLIA128,GCM,SHA256,,,), /* ns */ + CS_ENTRY(0xC089, TLS,ECDH,ECDSA,WITH,CAMELLIA,256,GCM,SHA384), + CS_ENTRY(0xC089, ECDH,ECDSA,CAMELLIA256,GCM,SHA384,,,), /* ns */ + CS_ENTRY(0xC08A, TLS,ECDHE,RSA,WITH,CAMELLIA,128,GCM,SHA256), + CS_ENTRY(0xC08A, ECDHE,CAMELLIA128,GCM,SHA256,,,,), /* ns */ + CS_ENTRY(0xC08B, TLS,ECDHE,RSA,WITH,CAMELLIA,256,GCM,SHA384), + CS_ENTRY(0xC08B, ECDHE,CAMELLIA256,GCM,SHA384,,,,), /* ns */ + CS_ENTRY(0xC08C, TLS,ECDH,RSA,WITH,CAMELLIA,128,GCM,SHA256), + CS_ENTRY(0xC08C, ECDH,CAMELLIA128,GCM,SHA256,,,,), /* ns */ + CS_ENTRY(0xC08D, TLS,ECDH,RSA,WITH,CAMELLIA,256,GCM,SHA384), + CS_ENTRY(0xC08D, ECDH,CAMELLIA256,GCM,SHA384,,,,), /* ns */ + CS_ENTRY(0xC08E, TLS,PSK,WITH,CAMELLIA,128,GCM,SHA256,), + CS_ENTRY(0xC08E, PSK,CAMELLIA128,GCM,SHA256,,,,), /* ns */ + CS_ENTRY(0xC08F, TLS,PSK,WITH,CAMELLIA,256,GCM,SHA384,), + CS_ENTRY(0xC08F, PSK,CAMELLIA256,GCM,SHA384,,,,), /* ns */ + CS_ENTRY(0xC090, TLS,DHE,PSK,WITH,CAMELLIA,128,GCM,SHA256), + CS_ENTRY(0xC090, DHE,PSK,CAMELLIA128,GCM,SHA256,,,), /* ns */ + CS_ENTRY(0xC091, TLS,DHE,PSK,WITH,CAMELLIA,256,GCM,SHA384), + CS_ENTRY(0xC091, DHE,PSK,CAMELLIA256,GCM,SHA384,,,), /* ns */ + CS_ENTRY(0xC092, TLS,RSA,PSK,WITH,CAMELLIA,128,GCM,SHA256), + CS_ENTRY(0xC092, RSA,PSK,CAMELLIA128,GCM,SHA256,,,), /* ns */ + CS_ENTRY(0xC093, TLS,RSA,PSK,WITH,CAMELLIA,256,GCM,SHA384), + CS_ENTRY(0xC093, RSA,PSK,CAMELLIA256,GCM,SHA384,,,), /* ns */ + CS_ENTRY(0xC094, TLS,PSK,WITH,CAMELLIA,128,CBC,SHA256,), + CS_ENTRY(0xC094, PSK,CAMELLIA128,SHA256,,,,,), + CS_ENTRY(0xC095, TLS,PSK,WITH,CAMELLIA,256,CBC,SHA384,), + CS_ENTRY(0xC095, PSK,CAMELLIA256,SHA384,,,,,), + CS_ENTRY(0xC096, TLS,DHE,PSK,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0xC096, DHE,PSK,CAMELLIA128,SHA256,,,,), + CS_ENTRY(0xC097, TLS,DHE,PSK,WITH,CAMELLIA,256,CBC,SHA384), + CS_ENTRY(0xC097, DHE,PSK,CAMELLIA256,SHA384,,,,), + CS_ENTRY(0xC098, TLS,RSA,PSK,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0xC098, RSA,PSK,CAMELLIA128,SHA256,,,,), + CS_ENTRY(0xC099, TLS,RSA,PSK,WITH,CAMELLIA,256,CBC,SHA384), + CS_ENTRY(0xC099, RSA,PSK,CAMELLIA256,SHA384,,,,), + CS_ENTRY(0xC09A, TLS,ECDHE,PSK,WITH,CAMELLIA,128,CBC,SHA256), + CS_ENTRY(0xC09A, ECDHE,PSK,CAMELLIA128,SHA256,,,,), + CS_ENTRY(0xC09B, TLS,ECDHE,PSK,WITH,CAMELLIA,256,CBC,SHA384), + CS_ENTRY(0xC09B, ECDHE,PSK,CAMELLIA256,SHA384,,,,), + CS_ENTRY(0xC09E, TLS,DHE,RSA,WITH,AES,128,CCM,), + CS_ENTRY(0xC09E, DHE,RSA,AES128,CCM,,,,), + CS_ENTRY(0xC09F, TLS,DHE,RSA,WITH,AES,256,CCM,), + CS_ENTRY(0xC09F, DHE,RSA,AES256,CCM,,,,), + CS_ENTRY(0xC0A2, TLS,DHE,RSA,WITH,AES,128,CCM,8), + CS_ENTRY(0xC0A2, DHE,RSA,AES128,CCM8,,,,), + CS_ENTRY(0xC0A3, TLS,DHE,RSA,WITH,AES,256,CCM,8), + CS_ENTRY(0xC0A3, DHE,RSA,AES256,CCM8,,,,), + CS_ENTRY(0xC0A4, TLS,PSK,WITH,AES,128,CCM,,), + CS_ENTRY(0xC0A4, PSK,AES128,CCM,,,,,), + CS_ENTRY(0xC0A5, TLS,PSK,WITH,AES,256,CCM,,), + CS_ENTRY(0xC0A5, PSK,AES256,CCM,,,,,), + CS_ENTRY(0xC0A6, TLS,DHE,PSK,WITH,AES,128,CCM,), + CS_ENTRY(0xC0A6, DHE,PSK,AES128,CCM,,,,), + CS_ENTRY(0xC0A7, TLS,DHE,PSK,WITH,AES,256,CCM,), + CS_ENTRY(0xC0A7, DHE,PSK,AES256,CCM,,,,), + CS_ENTRY(0xC0A8, TLS,PSK,WITH,AES,128,CCM,8,), + CS_ENTRY(0xC0A8, PSK,AES128,CCM8,,,,,), + CS_ENTRY(0xC0A9, TLS,PSK,WITH,AES,256,CCM,8,), + CS_ENTRY(0xC0A9, PSK,AES256,CCM8,,,,,), + CS_ENTRY(0xC0AA, TLS,PSK,DHE,WITH,AES,128,CCM,8), + CS_ENTRY(0xC0AA, DHE,PSK,AES128,CCM8,,,,), + CS_ENTRY(0xC0AB, TLS,PSK,DHE,WITH,AES,256,CCM,8), + CS_ENTRY(0xC0AB, DHE,PSK,AES256,CCM8,,,,), + CS_ENTRY(0xCCAA, TLS,DHE,RSA,WITH,CHACHA20,POLY1305,SHA256,), + CS_ENTRY(0xCCAA, DHE,RSA,CHACHA20,POLY1305,,,,), + CS_ENTRY(0xCCAC, TLS,ECDHE,PSK,WITH,CHACHA20,POLY1305,SHA256,), + CS_ENTRY(0xCCAC, ECDHE,PSK,CHACHA20,POLY1305,,,,), + CS_ENTRY(0xCCAD, TLS,DHE,PSK,WITH,CHACHA20,POLY1305,SHA256,), + CS_ENTRY(0xCCAD, DHE,PSK,CHACHA20,POLY1305,,,,), + CS_ENTRY(0xCCAE, TLS,RSA,PSK,WITH,CHACHA20,POLY1305,SHA256,), + CS_ENTRY(0xCCAE, RSA,PSK,CHACHA20,POLY1305,,,,), +#endif +}; +#define CS_LIST_LEN CURL_ARRAYSIZE(cs_list) + +static int cs_str_to_zip(const char *cs_str, size_t cs_len, uint8_t zip[6]) +{ + uint8_t indexes[8] = { 0 }; + const char *entry, *cur; + const char *nxt = cs_str; + const char *end = cs_str + cs_len; + char separator = '-'; + int idx, i = 0; + size_t len; + + /* split the cipher string by '-' or '_' */ + if(curl_strnequal(cs_str, "TLS", 3)) + separator = '_'; + + do { + if(i == 8) + return -1; + + /* determine the length of the part */ + cur = nxt; + for(; nxt < end && *nxt != '\0' && *nxt != separator; nxt++) + ; + len = nxt - cur; + + /* lookup index for the part (skip empty string at 0) */ + for(idx = 1, entry = cs_txt + 1; idx < CS_TXT_LEN; idx++) { + size_t elen = strlen(entry); + if(elen == len && curl_strnequal(entry, cur, len)) + break; + entry += elen + 1; + } + if(idx == CS_TXT_LEN) + return -1; + + indexes[i++] = (uint8_t)idx; + } while(nxt < end && *(nxt++) != '\0'); + + /* zip the 8 indexes into 48 bits */ + zip[0] = (uint8_t)(indexes[0] << 2 | (indexes[1] & 0x3F) >> 4); + zip[1] = (uint8_t)(indexes[1] << 4 | (indexes[2] & 0x3F) >> 2); + zip[2] = (uint8_t)(indexes[2] << 6 | (indexes[3] & 0x3F)); + zip[3] = (uint8_t)(indexes[4] << 2 | (indexes[5] & 0x3F) >> 4); + zip[4] = (uint8_t)(indexes[5] << 4 | (indexes[6] & 0x3F) >> 2); + zip[5] = (uint8_t)(indexes[6] << 6 | (indexes[7] & 0x3F)); + + return 0; +} + +static int cs_zip_to_str(const uint8_t zip[6], char *buf, size_t buf_size) +{ + uint8_t indexes[8] = { 0 }; + const char *entry; + char separator = '-'; + int idx, i, r; + size_t len = 0; + + /* unzip the 8 indexes */ + indexes[0] = zip[0] >> 2; + indexes[1] = (uint8_t)(((zip[0] << 4) & 0x3F) | zip[1] >> 4); + indexes[2] = (uint8_t)(((zip[1] << 2) & 0x3F) | zip[2] >> 6); + indexes[3] = ((zip[2] << 0) & 0x3F); + indexes[4] = zip[3] >> 2; + indexes[5] = (uint8_t)(((zip[3] << 4) & 0x3F) | zip[4] >> 4); + indexes[6] = (uint8_t)(((zip[4] << 2) & 0x3F) | zip[5] >> 6); + indexes[7] = ((zip[5] << 0) & 0x3F); + + if(indexes[0] == CS_TXT_IDX_TLS) + separator = '_'; + + for(i = 0; i < 8 && indexes[i] != 0 && len < buf_size; i++) { + if(indexes[i] >= CS_TXT_LEN) + return -1; + + /* lookup the part string for the index (skip empty string at 0) */ + for(idx = 1, entry = cs_txt + 1; idx < indexes[i]; idx++) { + size_t elen = strlen(entry); + entry += elen + 1; + } + + /* append the part string to the buffer */ + if(i > 0) + r = curl_msnprintf(&buf[len], buf_size - len, "%c%s", separator, entry); + else + r = curl_msnprintf(&buf[len], buf_size - len, "%s", entry); + + if(r < 0) + return -1; + len += r; + } + + return 0; +} + +uint16_t Curl_cipher_suite_lookup_id(const char *cs_str, size_t cs_len) +{ + size_t i; + uint8_t zip[6]; + + if(cs_len > 0 && cs_str_to_zip(cs_str, cs_len, zip) == 0) { + for(i = 0; i < CS_LIST_LEN; i++) { + if(!memcmp(cs_list[i].zip, zip, sizeof(zip))) + return cs_list[i].id; + } + } + + return 0; +} + +static bool cs_is_separator(char c) +{ + switch(c) { + case ' ': + case '\t': + case ':': + case ',': + case ';': + return TRUE; + } + return FALSE; +} + +uint16_t Curl_cipher_suite_walk_str(const char **str, const char **end) +{ + /* move string pointer to first non-separator or end of string */ + for(; cs_is_separator(*str[0]); (*str)++) + ; + + /* move end pointer to next separator or end of string */ + for(*end = *str; *end[0] != '\0' && !cs_is_separator(*end[0]); (*end)++) + ; + + return Curl_cipher_suite_lookup_id(*str, *end - *str); +} + +int Curl_cipher_suite_get_str(uint16_t id, char *buf, size_t buf_size, + bool prefer_rfc) +{ + size_t i, j = CS_LIST_LEN; + int r = -1; + + for(i = 0; i < CS_LIST_LEN; i++) { + if(cs_list[i].id != id) + continue; + if((cs_list[i].zip[0] >> 2 != CS_TXT_IDX_TLS) == !prefer_rfc) { + j = i; + break; + } + if(j == CS_LIST_LEN) + j = i; + } + + if(j < CS_LIST_LEN) + r = cs_zip_to_str(cs_list[j].zip, buf, buf_size); + + if(r < 0) + curl_msnprintf(buf, buf_size, "TLS_UNKNOWN_0x%04x", id); + + return r; +} + +#endif /* defined(USE_MBEDTLS) || defined(USE_RUSTLS) */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/cipher_suite.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/cipher_suite.h new file mode 100644 index 0000000000..0e185e351e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/cipher_suite.h @@ -0,0 +1,44 @@ +#ifndef HEADER_CURL_CIPHER_SUITE_H +#define HEADER_CURL_CIPHER_SUITE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Jan Venekamp, <jan@venekamp.net> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_MBEDTLS) || defined(USE_RUSTLS) + +/* Lookup IANA id for cipher suite string, returns 0 if not recognized */ +uint16_t Curl_cipher_suite_lookup_id(const char *cs_str, size_t cs_len); + +/* Walk over cipher suite string, update str and end pointers to next + cipher suite in string, returns IANA id of that suite if recognized */ +uint16_t Curl_cipher_suite_walk_str(const char **str, const char **end); + +/* Copy openssl or RFC name for cipher suite in supplied buffer. + Caller is responsible to supply sufficiently large buffer (size + of 64 should suffice), excess bytes are silently truncated. */ +int Curl_cipher_suite_get_str(uint16_t id, char *buf, size_t buf_size, + bool prefer_rfc); + +#endif /* defined(USE_MBEDTLS) || defined(USE_RUSTLS) */ +#endif /* HEADER_CURL_CIPHER_SUITE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/gtls.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/gtls.c new file mode 100644 index 0000000000..9d17573dc5 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/gtls.c @@ -0,0 +1,2344 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Source file for all GnuTLS-specific code for the TLS/SSL layer. No code + * but vtls.c should ever call or use these functions. + * + * Note: do not use the GnuTLS' *_t variable type names in this source code, + * since they were not present in 1.0.x. + */ +#include "curl_setup.h" + +#ifdef USE_GNUTLS + +#include <gnutls/abstract.h> +#include <gnutls/gnutls.h> +#include <gnutls/x509.h> +#include <gnutls/crypto.h> +#include <nettle/sha2.h> +#include <nettle/version.h> + +#include "urldata.h" +#include "curl_trc.h" +#include "vtls/keylog.h" +#include "vtls/gtls.h" +#include "vtls/vtls.h" +#include "vtls/vtls_int.h" +#include "vtls/vtls_scache.h" +#include "vtls/apple.h" +#include "vauth/vauth.h" +#include "parsedate.h" +#include "connect.h" /* for the connect timeout */ +#include "progress.h" +#include "curlx/strdup.h" +#include "curlx/fopen.h" +#include "vtls/x509asn1.h" + +/* Enable GnuTLS debugging by defining GTLSDEBUG */ +#if 0 +#define GTLSDEBUG +#endif + +#ifdef GTLSDEBUG +static void tls_log_func(int level, const char *str) +{ + curl_mfprintf(stderr, "|<%d>| %s", level, str); +} +#endif + +#if !defined(GNUTLS_VERSION_NUMBER) || (GNUTLS_VERSION_NUMBER < 0x030605) +#error "too old GnuTLS version" +#endif + +#undef CURL_GNUTLS_EARLY_DATA +#if GNUTLS_VERSION_NUMBER >= 0x030702 +#define CURL_GNUTLS_EARLY_DATA +#endif + +#include <gnutls/ocsp.h> + +struct gtls_ssl_backend_data { + struct gtls_ctx gtls; +}; + +static ssize_t gtls_push(void *s, const void *buf, size_t blen) +{ + struct Curl_cfilter *cf = s; + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + size_t nwritten; + CURLcode result; + + DEBUGASSERT(data); + result = Curl_conn_cf_send(cf->next, data, buf, blen, FALSE, &nwritten); + CURL_TRC_CF(data, cf, "gtls_push(len=%zu) -> %d, %zu", + blen, (int)result, nwritten); + backend->gtls.io_result = result; + if(result) { + /* !checksrc! disable ERRNOVAR 1 */ + gnutls_transport_set_errno(backend->gtls.session, + (result == CURLE_AGAIN) ? EAGAIN : EINVAL); + return -1; + } + return (ssize_t)nwritten; +} + +static ssize_t gtls_pull(void *s, void *buf, size_t blen) +{ + struct Curl_cfilter *cf = s; + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + size_t nread; + CURLcode result; + + DEBUGASSERT(data); + if(!backend->gtls.shared_creds->trust_setup) { + result = Curl_gtls_client_trust_setup(cf, data, &backend->gtls); + if(result) { + /* !checksrc! disable ERRNOVAR 1 */ + gnutls_transport_set_errno(backend->gtls.session, EINVAL); + backend->gtls.io_result = result; + return -1; + } + } + + result = Curl_conn_cf_recv(cf->next, data, buf, blen, &nread); + CURL_TRC_CF(data, cf, "gtls_pull(len=%zu) -> %d, %zu", blen, (int)result, + nread); + backend->gtls.io_result = result; + if(result) { + /* !checksrc! disable ERRNOVAR 1 */ + gnutls_transport_set_errno(backend->gtls.session, + (result == CURLE_AGAIN) ? EAGAIN : EINVAL); + return -1; + } + else if(nread == 0) + connssl->peer_closed = TRUE; + return (ssize_t)nread; +} + +/** + * gtls_init() + * + * Global GnuTLS init, called from Curl_ssl_init(). This calls functions that + * are not thread-safe (It is thread-safe since GnuTLS 3.3.0) and thus this + * function itself is not thread-safe and must only be called from within + * curl_global_init() to keep the thread situation under control! + * + * @retval 0 error initializing SSL + * @retval 1 SSL initialized successfully + */ +static int gtls_init(void) +{ + int ret = 1; + ret = gnutls_global_init() ? 0 : 1; +#ifdef GTLSDEBUG + gnutls_global_set_log_function(tls_log_func); + gnutls_global_set_log_level(2); +#endif + return ret; +} + +static void gtls_cleanup(void) +{ + gnutls_global_deinit(); + Curl_tls_keylog_close(); +} + +#ifdef CURLVERBOSE +static void showtime(struct Curl_easy *data, const char *text, time_t stamp) +{ + struct tm buffer; + const struct tm *tm = &buffer; + char str[96]; + CURLcode result = curlx_gmtime(stamp, &buffer); + if(result) + return; + + curl_msnprintf(str, + sizeof(str), + " %s: %s, %02d %s %4d %02d:%02d:%02d GMT", + text, + Curl_wkday[tm->tm_wday ? tm->tm_wday-1 : 6], + tm->tm_mday, + Curl_month[tm->tm_mon], + tm->tm_year + 1900, + tm->tm_hour, + tm->tm_min, + tm->tm_sec); + infof(data, "%s", str); +} +#endif + +static gnutls_datum_t load_file(const char *file) +{ + FILE *f; + gnutls_datum_t loaded_file = { NULL, 0 }; + long filelen; + void *ptr; + + f = curlx_fopen(file, "rb"); + if(!f) + return loaded_file; + if(fseek(f, 0, SEEK_END)) + goto out; + filelen = ftell(f); + if(filelen < 0 || filelen > CURL_MAX_INPUT_LENGTH) + goto out; + if(fseek(f, 0, SEEK_SET)) + goto out; + ptr = curlx_malloc((size_t)filelen); + if(!ptr) + goto out; + if(fread(ptr, 1, (size_t)filelen, f) < (size_t)filelen) { + curlx_free(ptr); + goto out; + } + + loaded_file.data = ptr; + loaded_file.size = (unsigned int)filelen; +out: + curlx_fclose(f); + return loaded_file; +} + +static void unload_file(gnutls_datum_t data) +{ + curlx_free(data.data); +} + +/* this function does an SSL/TLS (re-)handshake */ +static CURLcode cf_gtls_handshake(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + gnutls_session_t session; + int rc; + + DEBUGASSERT(backend); + session = backend->gtls.session; + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + backend->gtls.io_result = CURLE_OK; + rc = gnutls_handshake(session); + + if(!backend->gtls.shared_creds->trust_setup) { + /* After having send off the ClientHello, we prepare the trust + * store to verify the coming certificate from the server */ + CURLcode result = Curl_gtls_client_trust_setup(cf, data, &backend->gtls); + if(result) + return result; + } + + if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) { + connssl->io_need = + gnutls_record_get_direction(session) ? + CURL_SSL_IO_NEED_SEND : CURL_SSL_IO_NEED_RECV; + return CURLE_AGAIN; + } + else if((rc < 0) && !gnutls_error_is_fatal(rc)) { +#ifdef CURLVERBOSE + const char *strerr = NULL; + + if(rc == GNUTLS_E_WARNING_ALERT_RECEIVED) { + gnutls_alert_description_t alert = gnutls_alert_get(session); + strerr = gnutls_alert_get_name(alert); + } + + if(!strerr) + strerr = gnutls_strerror(rc); + + infof(data, "gnutls_handshake() warning: %s", strerr); +#endif + return CURLE_AGAIN; + } + else if((rc < 0) && backend->gtls.io_result) { + return backend->gtls.io_result; + } + else if(rc < 0) { + const char *strerr = NULL; + + if(rc == GNUTLS_E_FATAL_ALERT_RECEIVED) { + gnutls_alert_description_t alert = gnutls_alert_get(session); + strerr = gnutls_alert_get_name(alert); + } + + if(!strerr) + strerr = gnutls_strerror(rc); + + failf(data, "GnuTLS, handshake failed: %s", strerr); + return CURLE_SSL_CONNECT_ERROR; + } + + return CURLE_OK; +} + +static gnutls_x509_crt_fmt_t gnutls_do_file_type(const char *type) +{ + if(!type || !type[0]) + return GNUTLS_X509_FMT_PEM; + if(curl_strequal(type, "PEM")) + return GNUTLS_X509_FMT_PEM; + if(curl_strequal(type, "DER")) + return GNUTLS_X509_FMT_DER; + return GNUTLS_X509_FMT_PEM; /* default to PEM */ +} + +#define GNUTLS_CIPHERS "NORMAL:%PROFILE_MEDIUM:-ARCFOUR-128:" \ + "-CTYPE-ALL:+CTYPE-X509" + +#define QUIC_PRIORITY \ + "NORMAL:%PROFILE_MEDIUM:-VERS-ALL:+VERS-TLS1.3:-CIPHER-ALL:+AES-128-GCM:" \ + "+AES-256-GCM:+CHACHA20-POLY1305:+AES-128-CCM:-GROUP-ALL:" \ + "+GROUP-SECP256R1:+GROUP-X25519:+GROUP-SECP384R1:+GROUP-SECP521R1:" \ + "%DISABLE_TLS13_COMPAT_MODE" + +static CURLcode gnutls_set_ssl_version_min_max( + struct Curl_easy *data, + struct ssl_peer *peer, + struct ssl_primary_config *conn_config, + const char **prioritylist, + bool tls13support) +{ + long ssl_version = conn_config->version; + long ssl_version_max = conn_config->version_max; + + DEBUGASSERT(ssl_version != CURL_SSLVERSION_DEFAULT); + if(ssl_version <= CURL_SSLVERSION_TLSv1) + ssl_version = CURL_SSLVERSION_TLSv1_0; + if((ssl_version_max == CURL_SSLVERSION_MAX_NONE) || + (ssl_version_max == CURL_SSLVERSION_MAX_DEFAULT)) + ssl_version_max = tls13support ? + CURL_SSLVERSION_MAX_TLSv1_3 : CURL_SSLVERSION_MAX_TLSv1_2; + + if(peer->transport == TRNSPRT_QUIC) { + if(ssl_version_max < CURL_SSLVERSION_MAX_TLSv1_3) { + failf(data, "QUIC needs at least TLS version 1.3"); + return CURLE_SSL_CONNECT_ERROR; + } + *prioritylist = QUIC_PRIORITY; + return CURLE_OK; + } + + switch(ssl_version | ssl_version_max) { + case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_0: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.0"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_1: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.1:+VERS-TLS1.0"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_2: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.2:+VERS-TLS1.1:+VERS-TLS1.0"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_TLSv1_1: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.1"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_TLSv1_2: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.2:+VERS-TLS1.1"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_2 | CURL_SSLVERSION_MAX_TLSv1_2: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.2"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_3 | CURL_SSLVERSION_MAX_TLSv1_3: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.3"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_3: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_TLSv1_3: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.3:+VERS-TLS1.2:+VERS-TLS1.1"; + return CURLE_OK; + case CURL_SSLVERSION_TLSv1_2 | CURL_SSLVERSION_MAX_TLSv1_3: + *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" + "+VERS-TLS1.3:+VERS-TLS1.2"; + return CURLE_OK; + } + + failf(data, "GnuTLS: cannot set TLS protocol"); + return CURLE_SSL_CONNECT_ERROR; +} + +CURLcode Curl_gtls_shared_creds_create(struct Curl_easy *data, + struct gtls_shared_creds **pcreds) +{ + struct gtls_shared_creds *shared; + int rc; + + *pcreds = NULL; + shared = curlx_calloc(1, sizeof(*shared)); + if(!shared) + return CURLE_OUT_OF_MEMORY; + + rc = gnutls_certificate_allocate_credentials(&shared->creds); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "gnutls_certificate_allocate_credentials() failed: %s", + gnutls_strerror(rc)); + curlx_free(shared); + return CURLE_SSL_CONNECT_ERROR; + } + + shared->refcount = 1; + shared->time = *Curl_pgrs_now(data); + *pcreds = shared; + return CURLE_OK; +} + +CURLcode Curl_gtls_shared_creds_up_ref(struct gtls_shared_creds *creds) +{ + DEBUGASSERT(creds); + if(creds->refcount < SIZE_MAX) { + ++creds->refcount; + return CURLE_OK; + } + return CURLE_BAD_FUNCTION_ARGUMENT; +} + +void Curl_gtls_shared_creds_free(struct gtls_shared_creds **pcreds) +{ + struct gtls_shared_creds *shared = *pcreds; + *pcreds = NULL; + if(shared) { + --shared->refcount; + if(!shared->refcount) { + gnutls_certificate_free_credentials(shared->creds); + curlx_free(shared->CAfile); + curlx_free(shared); + } + } +} + +static CURLcode gtls_populate_creds(struct Curl_cfilter *cf, + struct Curl_easy *data, + gnutls_certificate_credentials_t creds) +{ + struct ssl_primary_config *config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + bool creds_are_empty = TRUE; + int rc; + + if(!config->verifypeer) { + infof(data, "SSL Trust: peer verification disabled"); + return CURLE_OK; + } + + infof(data, "SSL Trust Anchors:"); + if(config->native_ca_store) { +#ifdef USE_APPLE_SECTRUST + infof(data, " Native: Apple SecTrust"); + creds_are_empty = FALSE; +#else + rc = gnutls_certificate_set_x509_system_trust(creds); + if(rc < 0) + infof(data, "error reading native CA store (%s), continuing anyway", + gnutls_strerror(rc)); + else { + infof(data, " Native: %d certificates from system trust", rc); + if(rc > 0) + creds_are_empty = FALSE; + } +#endif + } + + if(config->ca_info_blob) { + gnutls_datum_t ca_info_datum; + if(config->ca_info_blob->len > (size_t)UINT_MAX) { + failf(data, "certificate blob too long: %zu bytes", + config->ca_info_blob->len); + return CURLE_SSL_CACERT_BADFILE; + } + ca_info_datum.data = config->ca_info_blob->data; + ca_info_datum.size = (unsigned int)config->ca_info_blob->len; + rc = gnutls_certificate_set_x509_trust_mem(creds, &ca_info_datum, + GNUTLS_X509_FMT_PEM); + creds_are_empty = creds_are_empty && (rc <= 0); + if(rc < 0) { + infof(data, "error reading CA cert blob (%s)%s", gnutls_strerror(rc), + (creds_are_empty ? "" : ", continuing anyway")); + if(creds_are_empty) { + ssl_config->certverifyresult = rc; + return CURLE_SSL_CACERT_BADFILE; + } + } + else + infof(data, " CA Blob: %d certificates", rc); + } + /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */ + else if(config->CAfile) { + /* set the trusted CA cert bundle file */ + gnutls_certificate_set_verify_flags(creds, + GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT); + + rc = gnutls_certificate_set_x509_trust_file(creds, + config->CAfile, + GNUTLS_X509_FMT_PEM); + creds_are_empty = creds_are_empty && (rc <= 0); + if(rc < 0) { + infof(data, "error reading CA cert file %s (%s)%s", + config->CAfile, gnutls_strerror(rc), + (creds_are_empty ? "" : ", continuing anyway")); + if(creds_are_empty) { + ssl_config->certverifyresult = rc; + return CURLE_SSL_CACERT_BADFILE; + } + } + else + infof(data, " CAfile: %d certificates in %s", rc, config->CAfile); + } + + if(config->CApath) { + /* set the trusted CA cert directory */ + rc = gnutls_certificate_set_x509_trust_dir(creds, config->CApath, + GNUTLS_X509_FMT_PEM); + creds_are_empty = creds_are_empty && (rc <= 0); + if(rc < 0) { + infof(data, "error reading CA cert file %s (%s)%s", + config->CApath, gnutls_strerror(rc), + (creds_are_empty ? "" : ", continuing anyway")); + if(creds_are_empty) { + ssl_config->certverifyresult = rc; + return CURLE_SSL_CACERT_BADFILE; + } + } + else + infof(data, " CApath: %d certificates in %s", rc, config->CApath); + } + + if(creds_are_empty) + infof(data, " no trust anchors configured"); + + if(config->CRLfile) { + /* set the CRL list file */ + rc = gnutls_certificate_set_x509_crl_file(creds, config->CRLfile, + GNUTLS_X509_FMT_PEM); + if(rc < 0) { + failf(data, "error reading CRL file %s (%s)", + config->CRLfile, gnutls_strerror(rc)); + return CURLE_SSL_CRL_BADFILE; + } + else + infof(data, " CRLfile: %d CRL in %s", rc, config->CRLfile); + } + + return CURLE_OK; +} + +/* key to use at `multi->proto_hash` */ +#define MPROTO_GTLS_X509_KEY "tls:gtls:x509:share" + +static bool gtls_shared_creds_expired(struct Curl_easy *data, + const struct gtls_shared_creds *sc) +{ + const struct ssl_general_config *cfg = &data->set.general_ssl; + timediff_t elapsed_ms = curlx_ptimediff_ms(Curl_pgrs_now(data), &sc->time); + timediff_t timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000; + + if(timeout_ms < 0) + return FALSE; + + return elapsed_ms >= timeout_ms; +} + +static bool gtls_shared_creds_different(struct Curl_cfilter *cf, + const struct gtls_shared_creds *sc) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + if(!sc->CAfile || !conn_config->CAfile) + return sc->CAfile != conn_config->CAfile; + + return strcmp(sc->CAfile, conn_config->CAfile); +} + +static struct gtls_shared_creds *gtls_get_cached_creds(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct gtls_shared_creds *shared_creds; + + if(data->multi) { + shared_creds = Curl_hash_pick(&data->multi->proto_hash, + CURL_UNCONST(MPROTO_GTLS_X509_KEY), + CURL_CSTRLEN(MPROTO_GTLS_X509_KEY)); + if(shared_creds && shared_creds->creds && + !gtls_shared_creds_expired(data, shared_creds) && + !gtls_shared_creds_different(cf, shared_creds)) { + return shared_creds; + } + } + return NULL; +} + +static void gtls_shared_creds_hash_free(void *key, size_t key_len, void *p) +{ + struct gtls_shared_creds *sc = p; + DEBUGASSERT(key_len == CURL_CSTRLEN(MPROTO_GTLS_X509_KEY)); + DEBUGASSERT(!memcmp(MPROTO_GTLS_X509_KEY, key, key_len)); + (void)key; + (void)key_len; + Curl_gtls_shared_creds_free(&sc); /* down reference */ +} + +static void gtls_set_cached_creds(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct gtls_shared_creds *sc) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + + DEBUGASSERT(sc); + DEBUGASSERT(sc->creds); + DEBUGASSERT(!sc->CAfile); + DEBUGASSERT(sc->refcount == 1); + if(!data->multi) + return; + + if(conn_config->CAfile) { + sc->CAfile = curlx_strdup(conn_config->CAfile); + if(!sc->CAfile) + return; + } + + if(Curl_gtls_shared_creds_up_ref(sc)) + return; + + if(!Curl_hash_add2(&data->multi->proto_hash, + CURL_UNCONST(MPROTO_GTLS_X509_KEY), + CURL_CSTRLEN(MPROTO_GTLS_X509_KEY), + sc, gtls_shared_creds_hash_free)) { + Curl_gtls_shared_creds_free(&sc); /* down reference again */ + return; + } +} + +CURLcode Curl_gtls_client_trust_setup(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct gtls_ctx *gtls) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + struct gtls_shared_creds *cached_creds = NULL; + bool cache_criteria_met; + CURLcode result; + int rc; + + /* Consider the X509 store cacheable if it comes exclusively from a CAfile, + or no source is provided and we are falling back to OpenSSL's built-in + default. */ + cache_criteria_met = (data->set.general_ssl.ca_cache_timeout != 0) && + conn_config->verifypeer && + !conn_config->CApath && + !conn_config->ca_info_blob && + !ssl_config->primary.CRLfile && + !conn_config->native_ca_store && + !conn_config->clientcert; /* GnuTLS adds client cert to its credentials! */ + + if(cache_criteria_met) + cached_creds = gtls_get_cached_creds(cf, data); + + if(cached_creds && !Curl_gtls_shared_creds_up_ref(cached_creds)) { + CURL_TRC_CF(data, cf, "using shared trust anchors and CRLs"); + Curl_gtls_shared_creds_free(>ls->shared_creds); + gtls->shared_creds = cached_creds; + rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_CERTIFICATE, + gtls->shared_creds->creds); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc)); + return CURLE_SSL_CONNECT_ERROR; + } + } + else { + CURL_TRC_CF(data, cf, "loading trust anchors and CRLs"); + result = gtls_populate_creds(cf, data, gtls->shared_creds->creds); + if(result) + return result; + gtls->shared_creds->trust_setup = TRUE; + if(cache_criteria_met) + gtls_set_cached_creds(cf, data, gtls->shared_creds); + } + return CURLE_OK; +} + +#ifdef CURL_GNUTLS_EARLY_DATA +static int gtls_get_ietf_proto(gnutls_session_t session) +{ + switch(gnutls_protocol_get_version(session)) { + case GNUTLS_SSL3: + return CURL_IETF_PROTO_SSL3; + case GNUTLS_TLS1_0: + return CURL_IETF_PROTO_TLS1; + case GNUTLS_TLS1_1: + return CURL_IETF_PROTO_TLS1_1; + case GNUTLS_TLS1_2: + return CURL_IETF_PROTO_TLS1_2; + case GNUTLS_TLS1_3: + return CURL_IETF_PROTO_TLS1_3; + default: + return CURL_IETF_PROTO_UNKNOWN; + } +} + +CURLcode Curl_gtls_cache_session(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key, + gnutls_session_t session, + curl_off_t valid_until, + const char *alpn, + unsigned char *quic_tp, + size_t quic_tp_len, + struct Curl_ssl_session **psession) +{ + struct Curl_ssl_session *sc_session = NULL, *sc_dup = NULL; + unsigned char *sdata, *qtp_clone = NULL; + size_t sdata_len = 0; + size_t earlydata_max = 0; + CURLcode result = CURLE_OK; + + if(psession) + *psession = NULL; + if(!Curl_ssl_scache_use(cf, data)) + return CURLE_OK; + + /* we always unconditionally get the session id here, as even if we + already got it from the cache and asked to use it in the connection, it + might have been rejected and then a new one is in use now and we need to + detect that. */ + + /* get the session ID data size */ + gnutls_session_get_data(session, NULL, &sdata_len); + if(!sdata_len) /* GnuTLS does this for some version combinations */ + return CURLE_OK; + + sdata = curlx_malloc(sdata_len); /* get a buffer for it */ + if(!sdata) + return CURLE_OUT_OF_MEMORY; + + /* extract session ID to the allocated buffer */ + gnutls_session_get_data(session, sdata, &sdata_len); + earlydata_max = gnutls_record_get_max_early_data_size(session); + + CURL_TRC_CF(data, cf, "get session id (len=%zu, alpn=%s, earlymax=%zu) " + "and store in cache", sdata_len, alpn ? alpn : "-", + earlydata_max); + if(quic_tp && quic_tp_len) { + qtp_clone = curlx_memdup0((const char *)quic_tp, quic_tp_len); + if(!qtp_clone) { + curlx_free(sdata); + return CURLE_OUT_OF_MEMORY; + } + } + + result = Curl_ssl_session_create2(sdata, sdata_len, + gtls_get_ietf_proto(session), + alpn, valid_until, earlydata_max, + qtp_clone, quic_tp_len, + &sc_session); + /* call took ownership of `sdata` and `qtp_clone` */ + if(!result && psession && /* return a duplicate if asked for and FTP */ + (cf->conn->scheme->family == CURLPROTO_FTP)) + result = Curl_ssl_session_dup(sc_session, &sc_dup); + if(!result) { + result = Curl_ssl_scache_put(cf, data, ssl_peer_key, sc_session); + /* took ownership of `sc_session` */ + sc_session = NULL; + } + if(!result && psession) { + *psession = sc_dup; + sc_dup = NULL; + } + Curl_ssl_session_destroy(sc_session); + Curl_ssl_session_destroy(sc_dup); + return result; +} +#endif + +#ifdef CURL_GNUTLS_EARLY_DATA +static CURLcode cf_gtls_update_session_id(struct Curl_cfilter *cf, + struct Curl_easy *data, + gnutls_session_t session) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct Curl_ssl_session *scs = NULL; + CURLcode result; + + result = Curl_gtls_cache_session(cf, data, connssl->peer.scache_key, + session, 0, connssl->negotiated.alpn, + NULL, 0, &scs); + if(!result) { + Curl_ssl_session_destroy(connssl->session); + connssl->session = scs; + } + return result; +} + +static int gtls_handshake_cb(gnutls_session_t session, unsigned int htype, + unsigned when, unsigned int incoming, + const gnutls_datum_t *msg) +{ + struct Curl_cfilter *cf = gnutls_session_get_ptr(session); + + (void)msg; + (void)incoming; + if(when) { /* after message has been processed */ + struct Curl_easy *data = CF_DATA_CURRENT(cf); + if(data) { + CURL_TRC_CF(data, cf, "handshake: %s message type %u", + incoming ? "incoming" : "outgoing", htype); + switch(htype) { + case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET: { + cf_gtls_update_session_id(cf, data, session); + break; + } + default: + break; + } + } + } + return 0; +} +#endif + +static CURLcode gtls_set_priority(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct gtls_ctx *gtls, + const char *priority) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct dynbuf buf; + const char *err = NULL; + CURLcode result = CURLE_OK; + int rc; + + curlx_dyn_init(&buf, 4096); + + if(conn_config->cipher_list) { + if((conn_config->cipher_list[0] == '+') || + (conn_config->cipher_list[0] == '-') || + (conn_config->cipher_list[0] == '!')) { + /* add it to our own */ + if(!curlx_dyn_len(&buf)) { /* not added yet */ + result = curlx_dyn_add(&buf, priority); + if(result) + goto out; + } + result = curlx_dyn_addf(&buf, ":%s", conn_config->cipher_list); + if(result) + goto out; + priority = curlx_dyn_ptr(&buf); + } + else /* replace our own completely */ + priority = conn_config->cipher_list; + } + + infof(data, "GnuTLS priority: %s", priority); + rc = gnutls_priority_set_direct(gtls->session, priority, &err); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "Error %d setting GnuTLS priority: %s", rc, err); + result = CURLE_SSL_CONNECT_ERROR; + } + +out: + curlx_dyn_free(&buf); + return result; +} + +static CURLcode gtls_client_init(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + size_t earlydata_max, + struct gtls_ctx *gtls) +{ + struct ssl_primary_config *config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + unsigned int init_flags; + int rc; + const char *prioritylist; + bool tls13support; + CURLcode result; + + if(config->version == CURL_SSLVERSION_SSLv2 || + config->version == CURL_SSLVERSION_SSLv3) { + failf(data, "GnuTLS does not support SSLv2 or SSLv3"); + return CURLE_SSL_CONNECT_ERROR; + } + + /* allocate a shared creds struct */ + result = Curl_gtls_shared_creds_create(data, >ls->shared_creds); + if(result) + return result; + + ssl_config->certverifyresult = 0; + + /* Initialize TLS session as a client */ + init_flags = GNUTLS_CLIENT; +#ifdef CURL_GNUTLS_EARLY_DATA + if(peer->transport == TRNSPRT_QUIC && earlydata_max > 0) + init_flags |= GNUTLS_ENABLE_EARLY_DATA | GNUTLS_NO_END_OF_EARLY_DATA; + else if(earlydata_max > 0 && earlydata_max != 0xFFFFFFFFUL) + /* See https://gitlab.com/gnutls/gnutls/-/issues/1619 + * We cannot differentiate between a session announcing no earldata + * and one announcing 0xFFFFFFFFUL. On TCP+TLS, this is unlikely, but + * on QUIC this is common. */ + init_flags |= GNUTLS_ENABLE_EARLY_DATA; +#endif + +#ifdef GNUTLS_FORCE_CLIENT_CERT + init_flags |= GNUTLS_FORCE_CLIENT_CERT; +#endif + +#ifdef GNUTLS_NO_TICKETS_TLS12 + init_flags |= GNUTLS_NO_TICKETS_TLS12; +#endif + +#ifdef GNUTLS_NO_STATUS_REQUEST + if(!config->verifystatus) + /* Disable the "status_request" TLS extension, enabled by default since + GnuTLS 3.8.0. */ + init_flags |= GNUTLS_NO_STATUS_REQUEST; +#endif + + CURL_TRC_CF(data, cf, "gnutls_init(flags=%x), earlydata=%zu", + init_flags, earlydata_max); + rc = gnutls_init(>ls->session, init_flags); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "gnutls_init() failed: %d", rc); + return CURLE_SSL_CONNECT_ERROR; + } + + if(peer->sni) { + if(gnutls_server_name_set(gtls->session, GNUTLS_NAME_DNS, + peer->sni, strlen(peer->sni)) < 0) { + failf(data, "Failed to set SNI"); + return CURLE_SSL_CONNECT_ERROR; + } + } + + /* Use default priorities */ + rc = gnutls_set_default_priority(gtls->session); + if(rc != GNUTLS_E_SUCCESS) + return CURLE_SSL_CONNECT_ERROR; + + /* "In GnuTLS 3.6.5, TLS 1.3 is enabled by default" */ + tls13support = !!gnutls_check_version("3.6.5"); + + if(config->version == CURL_SSLVERSION_TLSv1_3) { + if(!tls13support) { + failf(data, "This GnuTLS installation does not support TLS 1.3"); + return CURLE_SSL_CONNECT_ERROR; + } + } + + /* At this point we know we have a supported TLS version, so set it */ + result = gnutls_set_ssl_version_min_max(data, peer, + config, &prioritylist, tls13support); + if(result) + return result; + + result = gtls_set_priority(cf, data, gtls, prioritylist); + if(result) + return result; + + if(config->clientcert) { + if(!gtls->shared_creds->trust_setup) { + result = Curl_gtls_client_trust_setup(cf, data, gtls); + if(result) + return result; + } + if(ssl_config->primary.cert_type && + curl_strequal(ssl_config->primary.cert_type, "P12")) { + rc = gnutls_certificate_set_x509_simple_pkcs12_file( + gtls->shared_creds->creds, config->clientcert, GNUTLS_X509_FMT_DER, + ssl_config->primary.key_passwd ? ssl_config->primary.key_passwd : ""); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, + "error reading X.509 potentially-encrypted key or certificate " + "file: %s", + gnutls_strerror(rc)); + return CURLE_SSL_CONNECT_ERROR; + } + } + else { + const unsigned int supported_key_encryption_algorithms = + GNUTLS_PKCS_USE_PKCS12_3DES | GNUTLS_PKCS_USE_PKCS12_ARCFOUR | + GNUTLS_PKCS_USE_PKCS12_RC2_40 | GNUTLS_PKCS_USE_PBES2_3DES | + GNUTLS_PKCS_USE_PBES2_AES_128 | GNUTLS_PKCS_USE_PBES2_AES_192 | + GNUTLS_PKCS_USE_PBES2_AES_256; + rc = gnutls_certificate_set_x509_key_file2( + gtls->shared_creds->creds, + config->clientcert, + ssl_config->primary.key ? ssl_config->primary.key : + config->clientcert, + gnutls_do_file_type(ssl_config->primary.cert_type), + ssl_config->primary.key_passwd, + supported_key_encryption_algorithms); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, + "error reading X.509 %skey file: %s", + ssl_config->primary.key_passwd ? "potentially-encrypted " : "", + gnutls_strerror(rc)); + return CURLE_SSL_CONNECT_ERROR; + } + } + } + + rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_CERTIFICATE, + gtls->shared_creds->creds); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc)); + return CURLE_SSL_CONNECT_ERROR; + } + + if(config->verifystatus) { + rc = gnutls_ocsp_status_request_enable_client(gtls->session, + NULL, 0, NULL); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "gnutls_ocsp_status_request_enable_client() failed: %d", rc); + return CURLE_SSL_CONNECT_ERROR; + } + } + + return CURLE_OK; +} + +#ifdef CURL_GNUTLS_EARLY_DATA +static int keylog_callback(gnutls_session_t session, const char *label, + const gnutls_datum_t *secret) +{ + gnutls_datum_t crandom; + gnutls_datum_t srandom; + + gnutls_session_get_random(session, &crandom, &srandom); + if(crandom.size != 32) { + return -1; + } + + Curl_tls_keylog_write(label, crandom.data, crandom.size, + secret->data, secret->size); + return 0; +} + +static CURLcode gtls_on_session_reuse(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct alpn_spec *alpns, + struct Curl_ssl_session *scs, + bool *do_early_data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + + connssl->earlydata_max = + gnutls_record_get_max_early_data_size(backend->gtls.session); + + /* Seems to be no GnuTLS way to signal no EarlyData in session */ + return Curl_on_session_reuse(cf, data, alpns, scs, do_early_data, + connssl->earlydata_max && + connssl->earlydata_max != 0xFFFFFFFFUL); +} +#endif + +static CURLcode gtls_apply_session( + struct gtls_ctx *gctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + struct alpn_spec *alpns, + Curl_gtls_init_session_reuse_cb *sess_reuse_cb, + struct Curl_ssl_session *scs, + bool *pwas_setup) +{ + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + CURLcode result = CURLE_OK; + int rc; + + if(scs && scs->sdata && scs->sdata_len && + (!scs->alpn || Curl_alpn_contains_proto(alpns, scs->alpn))) { + /* we got a cached session, use it! */ + + result = gtls_client_init(cf, data, peer, scs->earlydata_max, gctx); + if(result) + goto out; + *pwas_setup = TRUE; + + rc = gnutls_session_set_data(gctx->session, scs->sdata, scs->sdata_len); + if(rc < 0) + infof(data, "SSL session not accepted by GnuTLS, continuing without"); + else { + infof(data, "SSL reusing session with ALPN '%s'", + scs->alpn ? scs->alpn : "-"); + if(ssl_config->earlydata && scs->alpn && + !cf->conn->bits.connect_only) { + bool do_early_data = FALSE; + if(sess_reuse_cb) { + result = sess_reuse_cb(cf, data, alpns, scs, &do_early_data); + if(result) + goto out; + } + if(do_early_data) { + /* We only try the ALPN protocol the session used before, + * otherwise we might send early data for the wrong protocol */ + Curl_alpn_restrict_to(alpns, scs->alpn); + } + } + } + } +out: + return result; +} + +CURLcode Curl_gtls_ctx_init(struct gtls_ctx *gctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + const struct alpn_spec *alpns_requested, + Curl_gtls_ctx_setup_cb *cb_setup, + void *cb_user_data, + void *ssl_user_data, + Curl_gtls_init_session_reuse_cb *sess_reuse_cb) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_ssl_session *scs = NULL; + gnutls_datum_t gtls_alpns[ALPN_ENTRIES_MAX]; + size_t gtls_alpns_count = 0; + bool gtls_session_setup = FALSE; + struct alpn_spec alpns; + CURLcode result = CURLE_OK; + + DEBUGASSERT(gctx); + Curl_alpn_copy(&alpns, alpns_requested); + + if((cf->sockindex == SECONDARYSOCKET) && !(cf->cft->flags & CF_TYPE_PROXY)) { + /* FTP is a bitch. On TLS secured transfers, it is a common server + * option to require the client to use the SAME TLS session as on + * the control connection or it fails the request. See #22225. */ + scs = Curl_ssl_get_cf_session(data, cf->cft, FIRSTSOCKET); + if(scs) { + result = gtls_apply_session(gctx, cf, data, peer, &alpns, + sess_reuse_cb, scs, >ls_session_setup); + scs = NULL; + if(!result && gtls_session_setup) { + CURL_TRC_CF(data, cf, "applied SSL session from control connection"); + } + } + } + /* This might be a reconnect, so we check for a session ID in the cache + to speed up things. We need to do this before constructing the GnuTLS + session since we need to set flags depending on the kind of reuse. */ + if(!gtls_session_setup && conn_config->cache_session && + !conn_config->verifystatus) { + result = Curl_ssl_scache_take(cf, data, peer->scache_key, &scs); + if(result) + goto out; + result = gtls_apply_session(gctx, cf, data, peer, &alpns, + sess_reuse_cb, scs, >ls_session_setup); + } + + if(!gtls_session_setup) { + result = gtls_client_init(cf, data, peer, 0, gctx); + if(result) + goto out; + } + + gnutls_session_set_ptr(gctx->session, ssl_user_data); + + if(cb_setup) { + result = cb_setup(cf, data, cb_user_data); + if(result) + goto out; + } + +#ifdef CURL_GNUTLS_EARLY_DATA + /* Open the file if a TLS or QUIC backend has not done this before. */ + Curl_tls_keylog_open(); + if(Curl_tls_keylog_enabled()) { + gnutls_session_set_keylog_function(gctx->session, keylog_callback); + } +#endif + + /* convert the ALPN string from our arguments to a list of strings that + * GnuTLS wants and does convert internally back to this string for sending + * to the server. nice. */ + if(!gtls_alpns_count && alpns.count) { + size_t i; + DEBUGASSERT(CURL_ARRAYSIZE(gtls_alpns) >= alpns.count); + for(i = 0; i < alpns.count; ++i) { + gtls_alpns[i].data = (unsigned char *)alpns.entries[i]; + gtls_alpns[i].size = (unsigned int)strlen(alpns.entries[i]); + } + gtls_alpns_count = alpns.count; + } + + if(gtls_alpns_count && + gnutls_alpn_set_protocols(gctx->session, + gtls_alpns, (unsigned int)gtls_alpns_count, + GNUTLS_ALPN_MANDATORY)) { + failf(data, "failed setting ALPN"); + result = CURLE_SSL_CONNECT_ERROR; + } + +out: + Curl_ssl_scache_return(cf, data, peer->scache_key, scs); + return result; +} + +static CURLcode gtls_connect_step1(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + CURLcode result; + + DEBUGASSERT(backend); + + if(connssl->state == ssl_connection_complete) + /* to make us tolerant against being called more than once for the + same connection */ + return CURLE_OK; + + result = Curl_gtls_ctx_init(&backend->gtls, cf, data, &connssl->peer, + connssl->alpn, NULL, NULL, cf, +#ifdef CURL_GNUTLS_EARLY_DATA + gtls_on_session_reuse +#else + NULL +#endif + ); + + if(result) + return result; + + if(connssl->alpn && (connssl->state != ssl_connection_deferred)) { + struct alpn_proto_buf proto; + memset(&proto, 0, sizeof(proto)); + Curl_alpn_to_proto_str(&proto, connssl->alpn); + infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); + } + +#ifdef CURL_GNUTLS_EARLY_DATA + gnutls_handshake_set_hook_function(backend->gtls.session, + GNUTLS_HANDSHAKE_ANY, GNUTLS_HOOK_POST, + gtls_handshake_cb); +#endif + + /* register callback functions and handle to send and receive data. */ + gnutls_transport_set_ptr(backend->gtls.session, cf); + gnutls_transport_set_push_function(backend->gtls.session, gtls_push); + gnutls_transport_set_pull_function(backend->gtls.session, gtls_pull); + + return CURLE_OK; +} + +static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, + gnutls_x509_crt_t cert, + const char *pinnedpubkey) +{ + /* Scratch */ + size_t len1 = 0, len2 = 0; + unsigned char *buff1 = NULL; + + gnutls_pubkey_t key = NULL; + + /* Result is returned to caller */ + CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; + + /* if a path was not specified, do not pin */ + if(!pinnedpubkey) + return CURLE_OK; + + if(!cert) + return result; + + do { + int ret; + + /* Begin Gyrations to get the public key */ + ret = gnutls_pubkey_init(&key); + if(ret < 0) + break; /* failed */ + + ret = gnutls_pubkey_import_x509(key, cert, 0); + if(ret < 0) + break; /* failed */ + + ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, NULL, &len1); + if(ret != GNUTLS_E_SHORT_MEMORY_BUFFER || len1 == 0) + break; /* failed */ + + buff1 = curlx_malloc(len1); + if(!buff1) + break; /* failed */ + + len2 = len1; + + ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, buff1, &len2); + if(ret < 0 || len1 != len2) + break; /* failed */ + + /* End Gyrations */ + + /* The one good exit point */ + result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1); + } while(0); + + if(key) + gnutls_pubkey_deinit(key); + + curlx_safefree(buff1); + + return result; +} + +void Curl_gtls_report_handshake(struct Curl_easy *data, struct gtls_ctx *gctx) +{ +#ifdef CURLVERBOSE + if(Curl_trc_is_verbose(data)) { + const char *ptr; + gnutls_protocol_t version = gnutls_protocol_get_version(gctx->session); + + /* the name of the cipher suite used, e.g. ECDHE_RSA_AES_256_GCM_SHA384. */ + ptr = gnutls_cipher_suite_get_name(gnutls_kx_get(gctx->session), + gnutls_cipher_get(gctx->session), + gnutls_mac_get(gctx->session)); + + infof(data, "SSL connection using %s / %s", + gnutls_protocol_get_name(version), ptr); + } +#else + (void)data; + (void)gctx; +#endif +} + +static void gtls_msg_verify_result(struct Curl_easy *data, + struct ssl_peer *peer, + gnutls_x509_crt_t x509_cert, + bool was_verified, + bool needs_verified) +{ + char certname[65] = ""; /* limited to 64 chars by ASN.1 */ + size_t size = sizeof(certname); + int rc; + + rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME, + 0, /* the first and only one */ + FALSE, certname, &size); + if(rc) { + infof(data, "error fetching CN from cert:%s", gnutls_strerror(rc)); + certname[0] = 0; + } + + if(!was_verified) { + if(needs_verified) { + failf(data, "SSL: certificate subject name (%s) does not match " + "target hostname '%s'", certname, + peer->origin->user_hostname); + } + else + infof(data, " common name: %s (does not match '%s')", + certname, peer->origin->user_hostname); + } + else + infof(data, " common name: %s (matched)", certname); +} + +static void gtls_infof_cert(struct Curl_easy *data, + gnutls_x509_crt_t x509_cert) +{ +#ifdef CURLVERBOSE + if(Curl_trc_is_verbose(data)) { + gnutls_datum_t certfields; + int rc, algo; + time_t tstamp; + unsigned int bits; + + /* public key algorithm's parameters */ + algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits); + infof(data, " certificate public key: %s", + gnutls_pk_algorithm_get_name((gnutls_pk_algorithm_t)algo)); + + /* version of the X.509 certificate. */ + infof(data, " certificate version: #%d", + gnutls_x509_crt_get_version(x509_cert)); + + rc = gnutls_x509_crt_get_dn2(x509_cert, &certfields); + if(rc) + infof(data, "Failed to get certificate name"); + else { + infof(data, " subject: %s", certfields.data); + + tstamp = gnutls_x509_crt_get_activation_time(x509_cert); + showtime(data, "start date", tstamp); + + tstamp = gnutls_x509_crt_get_expiration_time(x509_cert); + showtime(data, "expire date", tstamp); + + gnutls_free(certfields.data); + } + + rc = gnutls_x509_crt_get_issuer_dn2(x509_cert, &certfields); + if(rc) + infof(data, "Failed to get certificate issuer"); + else { + infof(data, " issuer: %s", certfields.data); + + gnutls_free(certfields.data); + } + } +#else + (void)data; + (void)x509_cert; +#endif +} + +static CURLcode gtls_verify_ocsp_status(struct Curl_easy *data, + gnutls_session_t session) +{ + gnutls_ocsp_resp_t ocsp_resp = NULL; + gnutls_datum_t status_request; + gnutls_certificate_credentials_t creds = NULL; + gnutls_x509_trust_list_t tlist = NULL; + unsigned int verify_status = 0; + gnutls_ocsp_cert_status_t status = GNUTLS_OCSP_CERT_UNKNOWN; + gnutls_x509_crl_reason_t reason; + CURLcode result = CURLE_OK; + int rc; + + rc = gnutls_ocsp_status_request_get(session, &status_request); + + if(rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) { + failf(data, "No OCSP response received"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto out; + } + else if(rc < 0) { + failf(data, "Invalid OCSP response received"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto out; + } + + rc = gnutls_ocsp_resp_init(&ocsp_resp); + if(rc < 0) { + failf(data, "Failed to initialize OCSP response object"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto out; + } + + rc = gnutls_ocsp_resp_import(ocsp_resp, &status_request); + if(rc < 0) { + failf(data, "Invalid OCSP response received"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto out; + } + + if(!gnutls_credentials_get(session, GNUTLS_CRD_CERTIFICATE, (void **)&creds)) + gnutls_certificate_get_trust_list(creds, &tlist); + if(!tlist) { + failf(data, "OCSP response signature verification failed"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto out; + } + rc = gnutls_ocsp_resp_verify(ocsp_resp, tlist, &verify_status, 0); + if(rc < 0 || verify_status) { + failf(data, "OCSP response signature verification failed"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto out; + } + + (void)gnutls_ocsp_resp_get_single(ocsp_resp, 0, NULL, NULL, NULL, NULL, + &status, NULL, NULL, NULL, &reason); + + switch(status) { + case GNUTLS_OCSP_CERT_GOOD: + break; + + case GNUTLS_OCSP_CERT_REVOKED: { + const char *crl_reason; + + switch(reason) { + default: + case GNUTLS_X509_CRLREASON_UNSPECIFIED: + crl_reason = "unspecified reason"; + break; + + case GNUTLS_X509_CRLREASON_KEYCOMPROMISE: + crl_reason = "private key compromised"; + break; + + case GNUTLS_X509_CRLREASON_CACOMPROMISE: + crl_reason = "CA compromised"; + break; + + case GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED: + crl_reason = "affiliation has changed"; + break; + + case GNUTLS_X509_CRLREASON_SUPERSEDED: + crl_reason = "certificate superseded"; + break; + + case GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION: + crl_reason = "operation has ceased"; + break; + + case GNUTLS_X509_CRLREASON_CERTIFICATEHOLD: + crl_reason = "certificate is on hold"; + break; + + case GNUTLS_X509_CRLREASON_REMOVEFROMCRL: + crl_reason = "will be removed from delta CRL"; + break; + + case GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN: + crl_reason = "privilege withdrawn"; + break; + + case GNUTLS_X509_CRLREASON_AACOMPROMISE: + crl_reason = "AA compromised"; + break; + } + + failf(data, "Server certificate was revoked: %s", crl_reason); + break; + } + + default: + case GNUTLS_OCSP_CERT_UNKNOWN: + failf(data, "Server certificate status is unknown"); + break; + } + + result = (status != GNUTLS_OCSP_CERT_GOOD) ? + CURLE_SSL_INVALIDCERTSTATUS : CURLE_OK; + +out: + if(ocsp_resp) + gnutls_ocsp_resp_deinit(ocsp_resp); + return result; +} + +struct gtls_cert_chain { + const gnutls_datum_t *certs; + unsigned int num_certs; +}; + +#ifdef USE_APPLE_SECTRUST +static CURLcode gtls_chain_get_der(struct Curl_cfilter *cf, + struct Curl_easy *data, + void *user_data, + size_t i, + unsigned char **pder, + size_t *pder_len) +{ + struct gtls_cert_chain *chain = user_data; + + (void)cf; + (void)data; + *pder_len = 0; + *pder = NULL; + + if(i >= chain->num_certs) + return CURLE_TOO_LARGE; + *pder = chain->certs[i].data; + *pder_len = (size_t)chain->certs[i].size; + return CURLE_OK; +} +#endif /* USE_APPLE_SECTRUST */ + +/* This function verifies the peer's certificate and returns CURLE_OK on + success or an appropriate CURLcode on error. The certificate verification + status bitmask (trusted, invalid etc.) is stored in + ssl_config->certverifyresult as one or more gnutls_certificate_status_t + enumerated elements bitwise or'd. */ +static CURLcode gtls_verify_cert(struct Curl_easy *data, + struct ssl_primary_config *config, + struct ssl_config_data *ssl_config, + gnutls_session_t session, + struct Curl_cfilter *cf, + struct ssl_peer *peer, + struct gtls_cert_chain *chain) +{ + bool verified = FALSE; + unsigned int verify_status = 0; + long * const certverifyresult = &ssl_config->certverifyresult; + int rc = gnutls_certificate_verify_peers2(session, &verify_status); + if(rc < 0) { + failf(data, "server cert verify failed: %d", rc); + *certverifyresult = rc; + return CURLE_SSL_CONNECT_ERROR; + } + *certverifyresult = verify_status; + verified = !(verify_status & GNUTLS_CERT_INVALID); + if(verified) + infof(data, " SSL certificate verified by GnuTLS"); + +#ifdef USE_APPLE_SECTRUST + if(!verified && config->native_ca_store) { + CURLcode result = + Curl_vtls_apple_verify(cf, data, peer, chain->num_certs, + gtls_chain_get_der, chain, NULL, 0); + if(result && (result != CURLE_PEER_FAILED_VERIFICATION)) + return result; /* unexpected error */ + verified = !result; + if(verified) { + infof(data, "SSL certificate verified via Apple SecTrust."); + *certverifyresult = 0; + } + } +#else + (void)cf; + (void)peer; + (void)chain; +#endif + + if(!verified) { + /* verify_status is a bitmask of gnutls_certificate_status bits */ + const char *cause = "certificate error, no details available"; + if(verify_status & GNUTLS_CERT_EXPIRED) + cause = "certificate has expired"; + else if(verify_status & GNUTLS_CERT_SIGNER_NOT_FOUND) + cause = "certificate signer not trusted"; + else if(verify_status & GNUTLS_CERT_INSECURE_ALGORITHM) + cause = "certificate uses insecure algorithm"; + else if(verify_status & GNUTLS_CERT_INVALID_OCSP_STATUS) + cause = "attached OCSP status response is invalid"; + failf(data, "SSL certificate verification failed: %s. (CAfile: %s " + "CRLfile: %s)", cause, + config->CAfile ? config->CAfile : "none", + ssl_config->primary.CRLfile ? + ssl_config->primary.CRLfile : "none"); + + return CURLE_PEER_FAILED_VERIFICATION; + } + return CURLE_OK; +} + +CURLcode Curl_gtls_verifyserver(struct Curl_cfilter *cf, + struct Curl_easy *data, + gnutls_session_t session, + struct ssl_primary_config *config, + struct ssl_config_data *ssl_config, + struct ssl_peer *peer, + const char *pinned_key) +{ + struct gtls_cert_chain chain; + gnutls_x509_crt_t x509_cert = NULL, x509_issuer = NULL; + time_t certclock; + int rc; + CURLcode result = CURLE_OK; + long * const certverifyresult = &ssl_config->certverifyresult; + + (void)cf; + /* This function returns the peer's raw certificate (chain) as sent by + the peer. These certificates are in raw format (DER encoded for + X.509). In case of a X.509 then a certificate list may be present. The + first certificate in the list is the peer's certificate, following the + issuer's certificate, then the issuer's issuer etc. */ + + chain.certs = gnutls_certificate_get_peers(session, &chain.num_certs); + if(!chain.certs) { + if(config->verifypeer || + config->verifyhost || + config->issuercert) { + failf(data, "failed to get server cert"); + *certverifyresult = GNUTLS_E_NO_CERTIFICATE_FOUND; + result = CURLE_PEER_FAILED_VERIFICATION; + goto out; + } + infof(data, " common name: WARNING could not obtain"); + } + + if(data->set.ssl.certinfo && chain.certs) { + if(chain.num_certs > MAX_ALLOWED_CERT_AMOUNT) { + failf(data, "%u certificates is more than allowed (%d)", + chain.num_certs, MAX_ALLOWED_CERT_AMOUNT); + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + else { + unsigned int i; + + result = Curl_ssl_init_certinfo(data, (int)chain.num_certs); + if(result) + goto out; + + for(i = 0; i < chain.num_certs; i++) { + const char *beg = (const char *)chain.certs[i].data; + const char *end = beg + chain.certs[i].size; + + result = Curl_extract_certinfo(data, (int)i, beg, end); + if(result) + goto out; + } + } + } + + if(config->verifypeer) { + result = gtls_verify_cert(data, config, ssl_config, session, + cf, peer, &chain); + if(result) + goto out; + } + else + infof(data, " SSL certificate verification SKIPPED"); + + /* initialize an X.509 certificate structure. */ + if(gnutls_x509_crt_init(&x509_cert)) { + failf(data, "failed to init GnuTLS x509_crt"); + *certverifyresult = GNUTLS_E_NO_CERTIFICATE_FOUND; + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + + if(chain.certs) { + /* convert the given DER or PEM encoded Certificate to the native + gnutls_x509_crt_t format */ + rc = gnutls_x509_crt_import(x509_cert, chain.certs, GNUTLS_X509_FMT_DER); + if(rc) { + failf(data, "error parsing server's certificate chain"); + *certverifyresult = GNUTLS_E_NO_CERTIFICATE_FOUND; + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + } + + /* Check for time-based validity */ + certclock = gnutls_x509_crt_get_expiration_time(x509_cert); + + if(certclock == (time_t)-1) { + if(config->verifypeer) { + failf(data, "server cert expiration date verify failed"); + *certverifyresult = GNUTLS_CERT_EXPIRED; + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + else + infof(data, " SSL certificate expiration date verify FAILED"); + } + else { + if(certclock < time(NULL)) { + if(config->verifypeer) { + failf(data, "server certificate expiration date has passed."); + *certverifyresult = GNUTLS_CERT_EXPIRED; + result = CURLE_PEER_FAILED_VERIFICATION; + goto out; + } + else + infof(data, " SSL certificate expiration date FAILED"); + } + else + infof(data, " SSL certificate expiration date OK"); + } + + certclock = gnutls_x509_crt_get_activation_time(x509_cert); + + if(certclock == (time_t)-1) { + if(config->verifypeer) { + failf(data, "server cert activation date verify failed"); + *certverifyresult = GNUTLS_CERT_NOT_ACTIVATED; + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + else + infof(data, " SSL certificate activation date verify FAILED"); + } + else { + if(certclock > time(NULL)) { + if(config->verifypeer) { + failf(data, "server certificate not activated yet."); + *certverifyresult = GNUTLS_CERT_NOT_ACTIVATED; + result = CURLE_PEER_FAILED_VERIFICATION; + goto out; + } + else + infof(data, " SSL certificate activation date FAILED"); + } + else + infof(data, " SSL certificate activation date OK"); + } + + if(config->verifystatus) { + result = gtls_verify_ocsp_status(data, session); + if(result) + goto out; + } + else + infof(data, " SSL certificate status verification SKIPPED"); + + if(config->issuercert) { + gnutls_datum_t issuerp; + if(gnutls_x509_crt_init(&x509_issuer)) { + failf(data, "failed to init GnuTLS x509_crt for issuer"); + result = CURLE_SSL_ISSUER_ERROR; + goto out; + } + issuerp = load_file(config->issuercert); + rc = gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM); + unload_file(issuerp); + if(rc) { + failf(data, "failed to import issuer certificate (%s) (Issuer Cert: %s)", + gnutls_strerror(rc), config->issuercert); + result = CURLE_SSL_ISSUER_ERROR; + goto out; + } + rc = (int)gnutls_x509_crt_check_issuer(x509_cert, x509_issuer); + if(rc <= 0) { + failf(data, "server certificate issuer check failed (Issuer Cert: %s)", + config->issuercert); + result = CURLE_SSL_ISSUER_ERROR; + goto out; + } + infof(data, " SSL certificate issuer check OK (Issuer Cert: %s)", + config->issuercert); + } + + /* This function checks if the given certificate's subject matches the + given hostname. This is a basic implementation of the matching described + in RFC2818 (HTTPS), which takes into account wildcards, and the subject + alternative name PKIX extension. Returns non zero on success, and zero on + failure. */ + + /* This function does not handle trailing dots, so if we have an SNI name + use that and fallback to the hostname only if there is no SNI (like for + IP addresses) */ + rc = (int)gnutls_x509_crt_check_hostname(x509_cert, + peer->sni ? peer->sni : + peer->origin->hostname); + result = (!rc && config->verifyhost) ? + CURLE_PEER_FAILED_VERIFICATION : CURLE_OK; + gtls_msg_verify_result(data, peer, x509_cert, rc, config->verifyhost); + if(result) + goto out; + + if(pinned_key) { + result = pkp_pin_peer_pubkey(data, x509_cert, pinned_key); + if(result != CURLE_OK) { + failf(data, "SSL: public key does not match pinned public key"); + goto out; + } + } + + gtls_infof_cert(data, x509_cert); + +out: + if(x509_issuer) + gnutls_x509_crt_deinit(x509_issuer); + if(x509_cert) + gnutls_x509_crt_deinit(x509_cert); + return result; +} + +static CURLcode gtls_verifyserver(struct Curl_cfilter *cf, + struct Curl_easy *data, + gnutls_session_t session) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); +#ifndef CURL_DISABLE_PROXY + const char *pinned_key = Curl_ssl_cf_is_proxy(cf) ? + CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY_PROXY) : + CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY); +#else + const char *pinned_key = CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY); +#endif + CURLcode result; + + result = Curl_gtls_verifyserver(cf, data, session, conn_config, ssl_config, + &connssl->peer, pinned_key); + if(result) + goto out; + +#ifdef CURL_GNUTLS_EARLY_DATA + /* Only on TLSv1.2 or lower do we have the session id now. For + * TLSv1.3 we get it via a SESSION_TICKET message that arrives later. */ + if(gnutls_protocol_get_version(session) < GNUTLS_TLS1_3) + result = cf_gtls_update_session_id(cf, data, session); +#endif + +out: + return result; +} + +#ifdef CURL_GNUTLS_EARLY_DATA +static CURLcode gtls_send_earlydata(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + CURLcode result = CURLE_OK; + const unsigned char *buf; + size_t blen; + ssize_t n; + + DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sending); + backend->gtls.io_result = CURLE_OK; + while(Curl_bufq_peek(&connssl->earlydata, &buf, &blen)) { + n = gnutls_record_send_early_data(backend->gtls.session, buf, blen); + CURL_TRC_CF(data, cf, "gtls_send_earlydata(len=%zu) -> %zd", blen, n); + if(n < 0) { + if(n == GNUTLS_E_AGAIN) + result = CURLE_AGAIN; + else + result = backend->gtls.io_result ? + backend->gtls.io_result : CURLE_SEND_ERROR; + goto out; + } + else if(!n) { + /* GnuTLS is buggy, it *SHOULD* return the amount of bytes it took in. + * Instead it returns 0 if everything was written. */ + n = (ssize_t)blen; + } + + Curl_bufq_skip(&connssl->earlydata, (size_t)n); + } + /* sent everything there was */ + infof(data, "SSL sending %zu bytes of early data", connssl->earlydata_skip); +out: + return result; +} +#endif + +/* + * This function is called after the TCP connect has completed. Setup the TLS + * layer and do all necessary magic. + */ +/* We use connssl->connecting_state to keep track of the connection status; + there are three states: 'ssl_connect_1' (not started yet or complete), + 'ssl_connect_2' (doing handshake with the server), and + 'ssl_connect_3' (verifying and getting stats). + */ +static CURLcode gtls_connect_common(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + CURLcode result = CURLE_OK; + + DEBUGASSERT(backend); + /* check if the connection has already been established */ + if(ssl_connection_complete == connssl->state) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; + + /* Initiate the connection, if not already done */ + if(connssl->connecting_state == ssl_connect_1) { + result = gtls_connect_step1(cf, data); + if(result) + goto out; + connssl->connecting_state = ssl_connect_2; + } + + if(connssl->connecting_state == ssl_connect_2) { +#ifdef CURL_GNUTLS_EARLY_DATA + if(connssl->earlydata_state == ssl_earlydata_await) { + goto out; + } + else if(connssl->earlydata_state == ssl_earlydata_sending) { + result = gtls_send_earlydata(cf, data); + if(result) + goto out; + connssl->earlydata_state = ssl_earlydata_sent; + } + DEBUGASSERT((connssl->earlydata_state == ssl_earlydata_none) || + (connssl->earlydata_state == ssl_earlydata_sent)); +#endif + result = cf_gtls_handshake(cf, data); + if(result) + goto out; + connssl->connecting_state = ssl_connect_3; + } + + /* Finish connecting once the handshake is done */ + if(connssl->connecting_state == ssl_connect_3) { + gnutls_datum_t proto; + int rc; + + Curl_gtls_report_handshake(data, &backend->gtls); + + result = gtls_verifyserver(cf, data, backend->gtls.session); + if(result) + goto out; + + connssl->state = ssl_connection_complete; + + rc = gnutls_alpn_get_selected_protocol(backend->gtls.session, &proto); + if(rc) { /* No ALPN from server */ + proto.data = NULL; + proto.size = 0; + } + + result = Curl_alpn_set_negotiated(cf, data, connssl, + proto.data, proto.size); + if(result) + goto out; + +#ifdef CURL_GNUTLS_EARLY_DATA + if(connssl->earlydata_state > ssl_earlydata_none) { + /* We should be in this state by now */ + DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sent); + connssl->earlydata_state = + (gnutls_session_get_flags(backend->gtls.session) & + GNUTLS_SFLAGS_EARLY_DATA) ? + ssl_earlydata_accepted : ssl_earlydata_rejected; + } +#endif + connssl->connecting_state = ssl_connect_done; + } + + if(connssl->connecting_state == ssl_connect_done) + DEBUGASSERT(connssl->state == ssl_connection_complete); + +out: + if(result == CURLE_AGAIN) { + *done = FALSE; + return CURLE_OK; + } + *done = ((connssl->state == ssl_connection_complete) || + (connssl->state == ssl_connection_deferred)); + CURL_TRC_CF(data, cf, "gtls_connect_common() -> %d, done=%d", (int)result, + *done); + return result; +} + +static CURLcode gtls_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ +#ifdef CURL_GNUTLS_EARLY_DATA + struct ssl_connect_data *connssl = cf->ctx; + if((connssl->state == ssl_connection_deferred) && + (connssl->earlydata_state == ssl_earlydata_await)) { + /* We refuse to be pushed, we are waiting for someone to send/recv. */ + *done = TRUE; + return CURLE_OK; + } +#endif + return gtls_connect_common(cf, data, done); +} + +static bool gtls_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct ssl_connect_data *ctx = cf->ctx; + struct gtls_ssl_backend_data *backend; + + (void)data; + DEBUGASSERT(ctx && ctx->backend); + backend = (struct gtls_ssl_backend_data *)ctx->backend; + if(backend->gtls.session && + gnutls_record_check_pending(backend->gtls.session) != 0) + return TRUE; + return FALSE; +} + +static CURLcode gtls_send(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *buf, + size_t blen, + size_t *pnwritten) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + CURLcode result = CURLE_OK; + ssize_t nwritten; + size_t remain = blen; + + DEBUGASSERT(backend); + *pnwritten = 0; + + while(remain) { + backend->gtls.io_result = CURLE_OK; + nwritten = gnutls_record_send(backend->gtls.session, buf, remain); + + if(nwritten >= 0) { + *pnwritten += (size_t)nwritten; + DEBUGASSERT((size_t)nwritten <= remain); + buf = (char *)CURL_UNCONST(buf) + (size_t)nwritten; + remain -= (size_t)nwritten; + } + else { + if(*pnwritten && (nwritten == GNUTLS_E_AGAIN)) { + result = CURLE_OK; + goto out; + } + result = (nwritten == GNUTLS_E_AGAIN) ? + CURLE_AGAIN : + (backend->gtls.io_result ? backend->gtls.io_result : CURLE_SEND_ERROR); + goto out; + } + } + +out: + CURL_TRC_CF(data, cf, "gtls_send(len=%zu) -> %d, %zu", + blen, (int)result, *pnwritten); + return result; +} + +/* + * This function is called to shut down the SSL layer but keep the + * socket open (CCC - Clear Command Channel) + */ +static CURLcode gtls_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + char buf[1024]; + CURLcode result = CURLE_OK; + ssize_t nread = 0; + size_t i; + + DEBUGASSERT(backend); + /* If we have no handshaked connection or already shut down */ + if(!backend->gtls.session || cf->shutdown || + connssl->state != ssl_connection_complete) { + *done = TRUE; + goto out; + } + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + *done = FALSE; + + if(!backend->gtls.sent_shutdown) { + /* do this only once */ + backend->gtls.sent_shutdown = TRUE; + if(send_shutdown) { + int ret = gnutls_bye(backend->gtls.session, GNUTLS_SHUT_RDWR); + if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) { + CURL_TRC_CF(data, cf, "SSL shutdown, gnutls_bye EAGAIN"); + connssl->io_need = gnutls_record_get_direction(backend->gtls.session) ? + CURL_SSL_IO_NEED_SEND : CURL_SSL_IO_NEED_RECV; + backend->gtls.sent_shutdown = FALSE; + result = CURLE_OK; + goto out; + } + if(ret != GNUTLS_E_SUCCESS) { + CURL_TRC_CF(data, cf, "SSL shutdown, gnutls_bye error: '%s'(%d)", + gnutls_strerror((int)ret), (int)ret); + result = CURLE_RECV_ERROR; + goto out; + } + } + } + + /* SSL should now have started the shutdown from our side. Since it + * was not complete, we are lacking the close notify from the server. */ + for(i = 0; i < 10; ++i) { + nread = gnutls_record_recv(backend->gtls.session, buf, sizeof(buf)); + if(nread <= 0) + break; + } + if(nread > 0) { + /* still data coming in? */ + } + else if(nread == 0) { + /* We got the close notify alert and are done. */ + *done = TRUE; + } + else if((nread == GNUTLS_E_AGAIN) || (nread == GNUTLS_E_INTERRUPTED)) { + connssl->io_need = gnutls_record_get_direction(backend->gtls.session) ? + CURL_SSL_IO_NEED_SEND : CURL_SSL_IO_NEED_RECV; + } + else { + CURL_TRC_CF(data, cf, "SSL shutdown, error: '%s'(%d)", + gnutls_strerror((int)nread), (int)nread); + result = CURLE_RECV_ERROR; + } + +out: + cf->shutdown = (result || *done); + return result; +} + +static void gtls_close(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + + DEBUGASSERT(backend); + CURL_TRC_CF(data, cf, "close"); + if(backend->gtls.session) { + gnutls_deinit(backend->gtls.session); + backend->gtls.session = NULL; + } + if(backend->gtls.shared_creds) { + Curl_gtls_shared_creds_free(&backend->gtls.shared_creds); + } +} + +static CURLcode gtls_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, size_t blen, + size_t *pnread) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + CURLcode result = CURLE_OK; + ssize_t nread; + + DEBUGASSERT(backend); + + nread = gnutls_record_recv(backend->gtls.session, buf, blen); + + if(nread >= 0) + *pnread = (size_t)nread; + else { + if((nread == GNUTLS_E_AGAIN) || (nread == GNUTLS_E_INTERRUPTED)) { + result = CURLE_AGAIN; + goto out; + } + else if(nread == GNUTLS_E_REHANDSHAKE) { + /* Either TLSv1.2 renegotiate or a TLSv1.3 session key update. */ + result = cf_gtls_handshake(cf, data); + if(!result) + result = CURLE_AGAIN; /* make us get called again. */ + goto out; + } + else { + failf(data, "GnuTLS recv error (%d): %s", + (int)nread, gnutls_strerror((int)nread)); + result = backend->gtls.io_result ? + backend->gtls.io_result : CURLE_RECV_ERROR; + goto out; + } + } + +out: + CURL_TRC_CF(data, cf, "gtls_recv(len=%zu) -> %d, %zd", blen, + (int)result, nread); + return result; +} + +size_t Curl_gtls_version(char *buffer, size_t size) +{ + return curl_msnprintf(buffer, size, "GnuTLS/%s", gnutls_check_version(NULL)); +} + +/* data might be NULL! */ +static CURLcode gtls_random(struct Curl_easy *data, + unsigned char *entropy, size_t length) +{ + int rc; + (void)data; + rc = gnutls_rnd(GNUTLS_RND_RANDOM, entropy, length); + return rc ? CURLE_FAILED_INIT : CURLE_OK; +} + +static CURLcode gtls_sha256sum(const unsigned char *input, + size_t len, + unsigned char *sha256sum, /* output */ + size_t sha256len) +{ + struct sha256_ctx SHA256pw; + sha256_init(&SHA256pw); + do { + unsigned int ilen = (unsigned int)CURLMIN(len, UINT_MAX); + sha256_update(&SHA256pw, ilen, input); + len -= ilen; + input += ilen; + } while(len); +#if NETTLE_VERSION_MAJOR >= 4 + (void)sha256len; + sha256_digest(&SHA256pw, sha256sum); +#else + sha256_digest(&SHA256pw, (unsigned int)sha256len, sha256sum); +#endif + return CURLE_OK; +} + +static bool gtls_cert_status_request(void) +{ + return TRUE; +} + +static void *gtls_get_internals(struct ssl_connect_data *connssl, + CURLINFO info) +{ + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + (void)info; + DEBUGASSERT(backend); + return backend->gtls.session; +} + +const struct Curl_ssl Curl_ssl_gnutls = { + { CURLSSLBACKEND_GNUTLS, "gnutls" }, /* info */ + + SSLSUPP_CA_PATH | + SSLSUPP_CERTINFO | + SSLSUPP_PINNEDPUBKEY | + SSLSUPP_HTTPS_PROXY | + SSLSUPP_CAINFO_BLOB | + SSLSUPP_CIPHER_LIST | + SSLSUPP_CA_CACHE | + SSLSUPP_ISSUERCERT | + SSLSUPP_CRLFILE, + + sizeof(struct gtls_ssl_backend_data), + + gtls_init, /* init */ + gtls_cleanup, /* cleanup */ + Curl_gtls_version, /* version */ + gtls_shutdown, /* shutdown */ + gtls_data_pending, /* data_pending */ + gtls_random, /* random */ + gtls_cert_status_request, /* cert_status_request */ + gtls_connect, /* connect */ + Curl_ssl_adjust_pollset, /* adjust_pollset */ + gtls_get_internals, /* get_internals */ + gtls_close, /* close_one */ + NULL, /* close_all */ + NULL, /* set_engine */ + NULL, /* set_engine_default */ + NULL, /* engines_list */ + gtls_sha256sum, /* sha256sum */ + gtls_recv, /* recv decrypted data */ + gtls_send, /* send data to encrypt */ + NULL, /* get_channel_binding */ +}; + +#endif /* USE_GNUTLS */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/gtls.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/gtls.h new file mode 100644 index 0000000000..0ad9a7e68c --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/gtls.h @@ -0,0 +1,115 @@ +#ifndef HEADER_CURL_GTLS_H +#define HEADER_CURL_GTLS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_GNUTLS + +#include <gnutls/gnutls.h> + +#include "curlx/timeval.h" + +struct Curl_easy; +struct Curl_cfilter; +struct alpn_spec; +struct ssl_primary_config; +struct ssl_config_data; +struct ssl_peer; +struct ssl_connect_data; +struct Curl_ssl_session; + +struct gtls_shared_creds { + gnutls_certificate_credentials_t creds; + char *CAfile; /* CAfile path used to generate X509 store */ + struct curltime time; /* when the shared creds was created */ + size_t refcount; + BIT(trust_setup); /* x509 anchors + CRLs have been set up */ +}; + +CURLcode Curl_gtls_shared_creds_create(struct Curl_easy *data, + struct gtls_shared_creds **pcreds); +CURLcode Curl_gtls_shared_creds_up_ref(struct gtls_shared_creds *creds); +void Curl_gtls_shared_creds_free(struct gtls_shared_creds **pcreds); + +struct gtls_ctx { + gnutls_session_t session; + struct gtls_shared_creds *shared_creds; + CURLcode io_result; /* result of last IO cfilter operation */ + BIT(sent_shutdown); +}; + +size_t Curl_gtls_version(char *buffer, size_t size); + +typedef CURLcode Curl_gtls_ctx_setup_cb(struct Curl_cfilter *cf, + struct Curl_easy *data, + void *user_data); + +typedef CURLcode Curl_gtls_init_session_reuse_cb(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct alpn_spec *alpns, + struct Curl_ssl_session *scs, + bool *do_early_data); + +CURLcode Curl_gtls_ctx_init(struct gtls_ctx *gctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + const struct alpn_spec *alpns_requested, + Curl_gtls_ctx_setup_cb *cb_setup, + void *cb_user_data, + void *ssl_user_data, + Curl_gtls_init_session_reuse_cb *sess_reuse_cb); + +CURLcode Curl_gtls_client_trust_setup(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct gtls_ctx *gtls); + +CURLcode Curl_gtls_verifyserver(struct Curl_cfilter *cf, + struct Curl_easy *data, + gnutls_session_t session, + struct ssl_primary_config *config, + struct ssl_config_data *ssl_config, + struct ssl_peer *peer, + const char *pinned_key); + +/* Extract TLS session and place in cache, if configured. Return + * a copy of the session if desired. */ +CURLcode Curl_gtls_cache_session(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key, + gnutls_session_t session, + curl_off_t valid_until, + const char *alpn, + unsigned char *quic_tp, + size_t quic_tp_len, + struct Curl_ssl_session **psession); + +/* Report properties of a successful handshake */ +void Curl_gtls_report_handshake(struct Curl_easy *data, struct gtls_ctx *gctx); + +extern const struct Curl_ssl Curl_ssl_gnutls; + +#endif /* USE_GNUTLS */ +#endif /* HEADER_CURL_GTLS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/hostcheck.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/hostcheck.c new file mode 100644 index 0000000000..0af540993f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/hostcheck.c @@ -0,0 +1,128 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_OPENSSL) || defined(USE_SCHANNEL) +/* these backends use functions from this file */ + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETINET_IN6_H +#include <netinet/in6.h> +#endif + +#include "curl_memrchr.h" +#include "vdns/hostip.h" +#include "vtls/hostcheck.h" + +/* check the two input strings with given length, but do not + assume they end in nul-bytes */ +static bool pmatch(const char *hostname, size_t hostlen, + const char *pattern, size_t patternlen) +{ + if(hostlen != patternlen) + return FALSE; + return curl_strnequal(hostname, pattern, hostlen); +} + +/* + * Match a hostname against a wildcard pattern. + * E.g. + * "foo.host.com" matches "*.host.com". + * + * We use the matching rule described in RFC6125, section 6.4.3. + * https://datatracker.ietf.org/doc/html/rfc6125#section-6.4.3 + * + * In addition: ignore trailing dots in the hostnames and wildcards, so that + * the names are used normalized. This is what the browsers do. + * + * Do not allow wildcard matching on IP numbers. There are apparently + * certificates being used with an IP address in the CN field, thus making no + * apparent distinction between a name and an IP. We need to detect the use of + * an IP address and not wildcard match on such names. + * + * Only match on "*" being used for the leftmost label, not "a*", "a*b" nor + * "*b". + * + * Return TRUE on a match. FALSE if not. + * + * @unittest: 1397 + */ + +static bool hostmatch(const char *hostname, + size_t hostlen, + const char *pattern, + size_t patternlen) +{ + const char *pattern_label_end; + + DEBUGASSERT(pattern); + DEBUGASSERT(patternlen); + DEBUGASSERT(hostname); + DEBUGASSERT(hostlen); + + /* normalize pattern and hostname by stripping off trailing dots */ + if(hostname[hostlen - 1] == '.') + hostlen--; + if(pattern[patternlen - 1] == '.') + patternlen--; + + if(strncmp(pattern, "*.", 2)) + return pmatch(hostname, hostlen, pattern, patternlen); + + /* detect host as IP address or starting with a dot and fail if so */ + else if(Curl_host_is_ipnum(hostname) || (hostname[0] == '.')) + return FALSE; + + /* We require at least 2 dots in the pattern to avoid too wide wildcard + match. */ + pattern_label_end = memchr(pattern, '.', patternlen); + if(!pattern_label_end || + (memrchr(pattern, '.', patternlen) == pattern_label_end)) + return pmatch(hostname, hostlen, pattern, patternlen); + else { + const char *hostname_label_end = memchr(hostname, '.', hostlen); + if(hostname_label_end) { + size_t skiphost = hostname_label_end - hostname; + size_t skiplen = pattern_label_end - pattern; + return pmatch(hostname_label_end, hostlen - skiphost, + pattern_label_end, patternlen - skiplen); + } + } + return FALSE; +} + +/* + * Curl_cert_hostcheck() returns TRUE if a match and FALSE if not. + */ +bool Curl_cert_hostcheck(const char *match, size_t matchlen, + const char *hostname, size_t hostlen) +{ + if(match && *match && hostname && *hostname) + return hostmatch(hostname, hostlen, match, matchlen); + return FALSE; +} + +#endif /* USE_OPENSSL || USE_SCHANNEL */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/hostcheck.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/hostcheck.h new file mode 100644 index 0000000000..d8e1a52377 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/hostcheck.h @@ -0,0 +1,36 @@ +#ifndef HEADER_CURL_HOSTCHECK_H +#define HEADER_CURL_HOSTCHECK_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_OPENSSL) || defined(USE_SCHANNEL) + +/* returns TRUE if there is a match */ +bool Curl_cert_hostcheck(const char *match, size_t matchlen, + const char *hostname, size_t hostlen); + +#endif + +#endif /* HEADER_CURL_HOSTCHECK_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/keylog.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/keylog.c new file mode 100644 index 0000000000..ac9649a41f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/keylog.c @@ -0,0 +1,162 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "vtls/keylog.h" + +#if defined(USE_OPENSSL) || defined(USE_GNUTLS) || defined(USE_WOLFSSL) || \ + defined(USE_RUSTLS) + +#include "escape.h" +#include "curlx/fopen.h" + +/* The fp for the open SSLKEYLOGFILE, or NULL if not open */ +static FILE *keylog_file_fp; +/* Used for verbose logging */ +static char *keylog_file_name; + +void Curl_tls_keylog_open(void) +{ + if(!keylog_file_fp) { + keylog_file_name = getenv("SSLKEYLOGFILE"); + if(keylog_file_name) { + keylog_file_fp = curlx_fopen(keylog_file_name, FOPEN_APPENDTEXT); + if(keylog_file_fp) { +#ifdef _WIN32 + if(setvbuf(keylog_file_fp, NULL, _IONBF, 0)) +#else + if(setvbuf(keylog_file_fp, NULL, _IOLBF, 4096)) +#endif + { + curlx_fclose(keylog_file_fp); + keylog_file_fp = NULL; + } + } + } + } +} + +void Curl_tls_keylog_close(void) +{ + if(keylog_file_fp) { + curlx_fclose(keylog_file_fp); + keylog_file_fp = NULL; + } +} + +bool Curl_tls_keylog_enabled(void) +{ + return !!keylog_file_fp; +} + +const char *Curl_tls_keylog_file_name(void) +{ + return keylog_file_name; +} + +bool Curl_tls_keylog_write_line(const char *line) +{ + /* The current maximum valid keylog line length LF and NUL is 195. */ + size_t linelen; + char buf[256]; + + if(!keylog_file_fp || !line) { + return FALSE; + } + + linelen = strlen(line); + if(linelen == 0 || linelen > sizeof(buf) - 2) { + /* Empty line or too big to fit in an LF and NUL. */ + return FALSE; + } + + memcpy(buf, line, linelen); + if(line[linelen - 1] != '\n') { + buf[linelen++] = '\n'; + } + buf[linelen] = '\0'; + + /* Using fputs here instead of fprintf since libcurl's fprintf replacement + may not be thread-safe. */ + fputs(buf, keylog_file_fp); + return TRUE; +} + +bool Curl_tls_keylog_write(const char *label, + const unsigned char *client_random, + size_t random_size, + const unsigned char *secret, size_t secretlen) +{ + size_t pos, i; + unsigned char line[KEYLOG_LABEL_MAXLEN + 1 + + (2 * CLIENT_RANDOM_SIZE) + 1 + + (2 * SECRET_MAXLEN) + 1 + 1]; + DEBUGASSERT(random_size >= CLIENT_RANDOM_SIZE); + if(random_size < CLIENT_RANDOM_SIZE) + return FALSE; + if(!keylog_file_fp) + return FALSE; + + pos = strlen(label); + if(pos > KEYLOG_LABEL_MAXLEN || !secretlen || secretlen > SECRET_MAXLEN) { + /* Should never happen - sanity check anyway. */ + return FALSE; + } + + memcpy(line, label, pos); + line[pos++] = ' '; + + /* Client Random */ + for(i = 0; i < CLIENT_RANDOM_SIZE; i++) { + Curl_hexbyte(&line[pos], client_random[i]); + pos += 2; + } + line[pos++] = ' '; + + /* Secret */ + for(i = 0; i < secretlen; i++) { + Curl_hexbyte(&line[pos], secret[i]); + pos += 2; + } + line[pos++] = '\n'; + line[pos] = '\0'; + + /* Using fputs here instead of fprintf since libcurl's fprintf replacement + may not be thread-safe. */ + fputs((char *)line, keylog_file_fp); + return TRUE; +} + +#else /* TLS backend */ + +bool Curl_tls_keylog_enabled(void) +{ + return FALSE; +} + +const char *Curl_tls_keylog_file_name(void) +{ + return NULL; +} + +#endif /* TLS backend */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/keylog.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/keylog.h new file mode 100644 index 0000000000..d489eb6360 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/keylog.h @@ -0,0 +1,75 @@ +#ifndef HEADER_CURL_KEYLOG_H +#define HEADER_CURL_KEYLOG_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#define KEYLOG_LABEL_MAXLEN CURL_CSTRLEN("CLIENT_HANDSHAKE_TRAFFIC_SECRET") + +#define CLIENT_RANDOM_SIZE 32 + +/* + * The master secret in TLS 1.2 and before is always 48 bytes. In TLS 1.3, the + * secret size depends on the cipher suite's hash function which is 32 bytes + * for SHA-256 and 48 bytes for SHA-384. + */ +#define SECRET_MAXLEN 48 + +/* + * Opens the TLS key log file if requested by the user. The SSLKEYLOGFILE + * environment variable specifies the output file. + */ +void Curl_tls_keylog_open(void); + +/* + * Closes the TLS key log file if not already. + */ +void Curl_tls_keylog_close(void); + +/* + * Returns true if the user successfully enabled the TLS key log file. + */ +bool Curl_tls_keylog_enabled(void); + +/* + * Returns a pointer to the filename keys are being written to, if enabled. + */ +const char *Curl_tls_keylog_file_name(void); + +/* + * Appends a key log file entry. + * Returns true iff the key log file is open and a valid entry was provided. + */ +bool Curl_tls_keylog_write(const char *label, + const unsigned char *client_random, + size_t random_size, + const unsigned char *secret, size_t secretlen); + +/* + * Appends a line to the key log file, ensure it is terminated by an LF. + * Returns true iff the key log file is open and a valid line was provided. + */ +bool Curl_tls_keylog_write_line(const char *line); + +#endif /* HEADER_CURL_KEYLOG_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/mbedtls.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/mbedtls.c new file mode 100644 index 0000000000..dbee473d7d --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/mbedtls.c @@ -0,0 +1,1697 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) Hoi-Ho Chan, <hoiho.chan@gmail.com> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Source file for all mbedTLS-specific code for the TLS/SSL layer. No code + * but vtls.c should ever call or use these functions. + * + */ +#include "curl_setup.h" + +#ifdef USE_MBEDTLS + +/* Define this to enable lots of debugging for mbedTLS */ +/* #define MBEDTLS_DEBUG */ + +#include <mbedtls/version.h> +#if MBEDTLS_VERSION_NUMBER < 0x03020000 +#error "mbedTLS 3.2.0 or greater required" +#endif +#include <psa/crypto_config.h> +#include <mbedtls/net_sockets.h> +#include <mbedtls/ssl.h> +#include <mbedtls/x509.h> +#include <mbedtls/psa_util.h> + +#if MBEDTLS_VERSION_NUMBER < 0x04000000 && !defined(MBEDTLS_CTR_DRBG_C) +#error "MBEDTLS_CTR_DRBG_C is required for mbedTLS 3.x." +#endif + +#include <mbedtls/error.h> +#if MBEDTLS_VERSION_NUMBER < 0x04000000 +#include <mbedtls/entropy.h> +#include <mbedtls/ctr_drbg.h> +#endif +#ifdef MBEDTLS_DEBUG +#include <mbedtls/debug.h> +#endif + +#include "vtls/cipher_suite.h" +#include "urldata.h" +#include "curl_trc.h" +#include "vtls/mbedtls.h" +#include "vtls/vtls.h" +#include "vtls/vtls_int.h" +#include "vtls/vtls_scache.h" +#include "vtls/x509asn1.h" +#include "connect.h" /* for the connect timeout */ +#include "curlx/strdup.h" +#include "curl_sha256.h" + +/* ALPN for http2 */ +#if defined(USE_HTTP2) && defined(MBEDTLS_SSL_ALPN) +#define HAS_ALPN_MBEDTLS +#endif + +struct mbed_ssl_backend_data { + mbedtls_ssl_context ssl; + mbedtls_x509_crt cacert; + mbedtls_x509_crt clicert; +#ifdef MBEDTLS_X509_CRL_PARSE_C + mbedtls_x509_crl crl; +#endif + mbedtls_pk_context pk; + mbedtls_ssl_config config; +#ifdef HAS_ALPN_MBEDTLS + const char *protocols[3]; +#endif + int *ciphersuites; + size_t send_blocked_len; + BIT(initialized); /* mbedtls_ssl_context is initialized */ + BIT(sent_shutdown); + BIT(send_blocked); +}; + +/** A context for random number generation (RNG). + */ +#if MBEDTLS_VERSION_NUMBER < 0x04000000 +struct rng_context_t { + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context drbg; +}; + +static struct rng_context_t rng; +#endif + +#ifndef MBEDTLS_ERROR_C +#define mbedtls_strerror(a, b, c) b[0] = 0 +#endif + +#ifdef MBEDTLS_DEBUG +static void mbed_debug(void *context, int level, const char *f_name, + int line_nb, const char *line) +{ + struct Curl_easy *data = (struct Curl_easy *)context; + (void)level; + (void)line_nb; + (void)f_name; + + if(data) { + size_t len = strlen(line); + if(len && (line[len - 1] == '\n')) + /* discount any trailing newline */ + len--; + infof(data, "%.*s", (int)len, line); + } +} +#endif + +static int mbedtls_bio_cf_write(void *bio, + const unsigned char *buf, size_t blen) +{ + struct Curl_cfilter *cf = bio; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + size_t nwritten; + CURLcode result; + + DEBUGASSERT(data); + if(!data) + return 0; + + result = Curl_conn_cf_send(cf->next, data, buf, blen, FALSE, &nwritten); + CURL_TRC_CF(data, cf, "mbedtls_bio_cf_out_write(len=%zu) -> %d, %zu", + blen, (int)result, nwritten); + if(result == CURLE_AGAIN) + return MBEDTLS_ERR_SSL_WANT_WRITE; + return result ? -1 : (int)nwritten; +} + +static int mbedtls_bio_cf_read(void *bio, unsigned char *buf, size_t blen) +{ + struct Curl_cfilter *cf = bio; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + size_t nread = 0; + CURLcode result; + + DEBUGASSERT(data); + if(!data) + return 0; + /* OpenSSL catches this case, so should we. */ + if(!buf) + return 0; + + result = Curl_conn_cf_recv(cf->next, data, (char *)buf, blen, &nread); + CURL_TRC_CF(data, cf, "mbedtls_bio_cf_in_read(len=%zu) -> %d, %zu", + blen, (int)result, nread); + if(result == CURLE_AGAIN) + return MBEDTLS_ERR_SSL_WANT_READ; + /* nread is never larger than int here */ + return result ? -1 : (int)nread; +} + +/* See: + * https://web.archive.org/web/20200921194007/tls.mbed.org/discussions/generic/howto-determine-exact-buffer-len-for-mbedtls_pk_write_pubkey_der + */ +#define RSA_PUB_DER_MAX_BYTES (38 + (2 * MBEDTLS_MPI_MAX_SIZE)) +#define ECP_PUB_DER_MAX_BYTES (30 + (2 * MBEDTLS_ECP_MAX_BYTES)) + +#define PUB_DER_MAX_BYTES (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \ + RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES) + +static CURLcode mbed_set_ssl_version_min_max( + struct Curl_easy *data, + struct mbed_ssl_backend_data *backend, + struct ssl_primary_config *conn_config) +{ + mbedtls_ssl_protocol_version ver_min = +#ifdef MBEDTLS_SSL_PROTO_TLS1_2 + MBEDTLS_SSL_VERSION_TLS1_2 +#else + MBEDTLS_SSL_VERSION_TLS1_3 +#endif + ; + mbedtls_ssl_protocol_version ver_max = +#ifdef MBEDTLS_SSL_PROTO_TLS1_3 + MBEDTLS_SSL_VERSION_TLS1_3 +#else + MBEDTLS_SSL_VERSION_TLS1_2 +#endif + ; + + DEBUGASSERT(conn_config->version != CURL_SSLVERSION_DEFAULT); + switch(conn_config->version) { + case CURL_SSLVERSION_TLSv1: + case CURL_SSLVERSION_TLSv1_0: + case CURL_SSLVERSION_TLSv1_1: + case CURL_SSLVERSION_TLSv1_2: +#ifdef MBEDTLS_SSL_PROTO_TLS1_2 + ver_min = MBEDTLS_SSL_VERSION_TLS1_2; + break; +#endif + case CURL_SSLVERSION_TLSv1_3: +#ifdef MBEDTLS_SSL_PROTO_TLS1_3 + ver_min = MBEDTLS_SSL_VERSION_TLS1_3; + break; +#endif + default: + failf(data, "mbedTLS: unsupported minimum TLS version value: %x", + conn_config->version); + return CURLE_SSL_CONNECT_ERROR; + } + + switch(conn_config->version_max) { + case CURL_SSLVERSION_MAX_DEFAULT: + case CURL_SSLVERSION_MAX_NONE: + case CURL_SSLVERSION_MAX_TLSv1_3: +#ifdef MBEDTLS_SSL_PROTO_TLS1_3 + ver_max = MBEDTLS_SSL_VERSION_TLS1_3; + break; +#endif +#ifdef MBEDTLS_SSL_PROTO_TLS1_2 + case CURL_SSLVERSION_MAX_TLSv1_2: + ver_max = MBEDTLS_SSL_VERSION_TLS1_2; + break; +#endif + case CURL_SSLVERSION_MAX_TLSv1_1: + case CURL_SSLVERSION_MAX_TLSv1_0: + default: + failf(data, "mbedTLS: unsupported maximum TLS version value"); + return CURLE_SSL_CONNECT_ERROR; + } + + mbedtls_ssl_conf_min_tls_version(&backend->config, ver_min); + mbedtls_ssl_conf_max_tls_version(&backend->config, ver_max); + + return CURLE_OK; +} + +/* TLS_ECJPAKE_WITH_AES_128_CCM_8 (0xC0FF) is marked experimental in mbedTLS. + The number is not reserved by IANA nor is the cipher suite present in other + SSL implementations. Provide provisional support for specifying the cipher + suite here. */ +#ifdef MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 +static int mbed_cipher_suite_get_str(uint16_t id, char *buf, size_t buf_size, + bool prefer_rfc) +{ + if(id == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8) + curl_msnprintf(buf, buf_size, "%s", "TLS_ECJPAKE_WITH_AES_128_CCM_8"); + else + return Curl_cipher_suite_get_str(id, buf, buf_size, prefer_rfc); + return 0; +} + +static uint16_t mbed_cipher_suite_walk_str(const char **str, const char **end) +{ + uint16_t id = Curl_cipher_suite_walk_str(str, end); + size_t len = *end - *str; + static const char ecjpake_suite[] = "TLS_ECJPAKE_WITH_AES_128_CCM_8"; + + if(!id) { + if((len == CURL_CSTRLEN(ecjpake_suite)) && + curl_strnequal(ecjpake_suite, *str, len)) + id = MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8; + } + return id; +} +#else +#define mbed_cipher_suite_get_str Curl_cipher_suite_get_str +#define mbed_cipher_suite_walk_str Curl_cipher_suite_walk_str +#endif + +static CURLcode mbed_set_selected_ciphers( + struct Curl_easy *data, + struct mbed_ssl_backend_data *backend, + const char *ciphers12, + const char *ciphers13) +{ + const char *ciphers = ciphers12; + const int *supported; + int *selected; + size_t supported_len, count = 0, default13_count = 0, i, j; + const char *ptr, *end; + + supported = mbedtls_ssl_list_ciphersuites(); + for(i = 0; supported[i] != 0; i++) + ; + supported_len = i; + + selected = curlx_malloc(sizeof(int) * (supported_len + 1)); + if(!selected) + return CURLE_OUT_OF_MEMORY; + +#ifndef MBEDTLS_SSL_PROTO_TLS1_3 + (void)ciphers13, (void)j; +#else + if(!ciphers13) { + /* Add default TLSv1.3 ciphers to selection */ + for(j = 0; j < supported_len; j++) { + uint16_t id = (uint16_t)supported[j]; + if(strncmp(mbedtls_ssl_get_ciphersuite_name(id), "TLS1-3", 6)) + continue; + + selected[count++] = id; + } + + default13_count = count; + } + else + ciphers = ciphers13; + +add_ciphers: +#endif + for(ptr = ciphers; ptr[0] != '\0' && count < supported_len; ptr = end) { + uint16_t id = mbed_cipher_suite_walk_str(&ptr, &end); + + /* Check if cipher is supported */ + if(id) { + for(i = 0; i < supported_len && supported[i] != id; i++) + ; + if(i == supported_len) + id = 0; + } + if(!id) { + if(ptr[0] != '\0') + infof(data, "mbedTLS: unknown cipher in list: \"%.*s\"", + (int)(end - ptr), ptr); + continue; + } + + /* No duplicates allowed (so selected cannot overflow) */ + for(i = 0; i < count && selected[i] != id; i++) + ; + if(i < count) { + if(i >= default13_count) + infof(data, "mbedTLS: duplicate cipher in list: \"%.*s\"", + (int)(end - ptr), ptr); + continue; + } + + selected[count++] = id; + } + +#ifdef MBEDTLS_SSL_PROTO_TLS1_3 + if(ciphers == ciphers13 && ciphers12) { + ciphers = ciphers12; + goto add_ciphers; + } + + if(!ciphers12) { + /* Add default TLSv1.2 ciphers to selection */ + for(j = 0; j < supported_len; j++) { + uint16_t id = (uint16_t)supported[j]; + if(!strncmp(mbedtls_ssl_get_ciphersuite_name(id), "TLS1-3", 6)) + continue; + + /* No duplicates allowed (so selected cannot overflow) */ + for(i = 0; i < count && selected[i] != id; i++) + ; + if(i < count) + continue; + + selected[count++] = id; + } + } +#endif + + selected[count] = 0; + + if(count == 0) { + curlx_free(selected); + failf(data, "mbedTLS: no supported cipher in list"); + return CURLE_SSL_CIPHER; + } + + /* mbedtls_ssl_conf_ciphersuites(): The ciphersuites array is not copied. + It must remain valid for the lifetime of the SSL configuration */ + backend->ciphersuites = selected; + mbedtls_ssl_conf_ciphersuites(&backend->config, backend->ciphersuites); + return CURLE_OK; +} + +static void mbed_dump_cert_info(struct Curl_easy *data, + const mbedtls_x509_crt *crt) +{ +#if !defined(CURLVERBOSE) || defined(MBEDTLS_X509_REMOVE_INFO) + (void)data, (void)crt; +#else + const size_t bufsize = 16384; + char *p, *buffer = curlx_malloc(bufsize); + + if(buffer && mbedtls_x509_crt_info(buffer, bufsize, " ", crt) > 0) { + infof(data, "Server certificate:"); + for(p = buffer; *p; p += *p != '\0') { + size_t s = strcspn(p, "\n"); + infof(data, "%.*s", (int)s, p); + p += s; + } + } + else + infof(data, "Unable to dump certificate information"); + + curlx_free(buffer); +#endif +} + +static void mbed_extract_certinfo(struct Curl_easy *data, + const mbedtls_x509_crt *crt) +{ + CURLcode result; + const mbedtls_x509_crt *cur; + int cert_count = 0; + int i; + + for(cur = crt; cur && cert_count <= MAX_ALLOWED_CERT_AMOUNT; cur = cur->next) + cert_count++; + + if(cert_count > MAX_ALLOWED_CERT_AMOUNT) { + infof(data, "More certificates than allowed (%d), skipping certinfo", + MAX_ALLOWED_CERT_AMOUNT); + return; + } + + result = Curl_ssl_init_certinfo(data, cert_count); + + for(i = 0, cur = crt; result == CURLE_OK && cur; ++i, cur = cur->next) { + const char *beg = (const char *)cur->raw.p; + const char *end = beg + cur->raw.len; + result = Curl_extract_certinfo(data, i, beg, end); + } +} + +static int mbed_verify_cb(void *ptr, mbedtls_x509_crt *crt, + int depth, uint32_t *flags) +{ + struct Curl_cfilter *cf = (struct Curl_cfilter *)ptr; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_easy *data = CF_DATA_CURRENT(cf); + + if(depth == 0) { + if(data->set.verbose) + mbed_dump_cert_info(data, crt); + if(data->set.ssl.certinfo) + mbed_extract_certinfo(data, crt); + } + + /* `verifypeer` and `verifyhost` are independent, so clear the flags of a + disabled check only. The name mismatch belongs to `verifyhost`. */ + if(!conn_config->verifypeer) + *flags &= MBEDTLS_X509_BADCERT_CN_MISMATCH; + if(!conn_config->verifyhost) + *flags &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH; + + if(*flags) { +#ifndef MBEDTLS_X509_REMOVE_INFO + char buf[128]; + mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", *flags); + failf(data, "mbedTLS: %s", buf); +#else + failf(data, "mbedTLS: certificate verification error 0x%08x", + (unsigned int)*flags); +#endif + } + + return 0; +} + +static CURLcode mbed_load_cacert(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; + const char * const ssl_cafile = + /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */ + (ca_info_blob ? NULL : conn_config->CAfile); + const bool verifypeer = conn_config->verifypeer; + const char * const ssl_capath = conn_config->CApath; +#ifdef MBEDTLS_PEM_PARSE_C + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + const char * const ssl_cert_type = ssl_config->primary.cert_type; +#endif + int ret = -1; + char errorbuf[128]; + + mbedtls_x509_crt_init(&backend->cacert); + + if(ca_info_blob && verifypeer) { +#ifdef MBEDTLS_PEM_PARSE_C + /* if DER or a null-terminated PEM process using + mbedtls_x509_crt_parse(). */ + if((ssl_cert_type && curl_strequal(ssl_cert_type, "DER")) || + ((char *)(ca_info_blob->data))[ca_info_blob->len - 1] == '\0') { + ret = mbedtls_x509_crt_parse(&backend->cacert, ca_info_blob->data, + ca_info_blob->len); + } + else { /* they say it is PEM and it is not null-terminated */ + + /* Unfortunately, mbedtls_x509_crt_parse() requires the data to be + null-terminated if the data is PEM encoded (even when provided the + exact length). The function accepts PEM or DER formats, but we cannot + assume if the user passed in a PEM format cert that it is + null-terminated. */ + unsigned char *newblob = curlx_memdup0(ca_info_blob->data, + ca_info_blob->len); + if(!newblob) + return CURLE_OUT_OF_MEMORY; + + ret = mbedtls_x509_crt_parse(&backend->cacert, newblob, + ca_info_blob->len + 1); + curlx_free(newblob); + } +#else + /* DER encoded certs do not need to be null-terminated because it is a + binary format. Thus, if we are not compiling with PEM_PARSE we can avoid + the extra memory copies altogether. */ + ret = mbedtls_x509_crt_parse_der(&backend->cacert, ca_info_blob->data, + ca_info_blob->len); +#endif + + if(ret < 0) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "mbedTLS: error importing CA cert blob: (-0x%04X) %s", + (unsigned int)-ret, errorbuf); + return CURLE_SSL_CERTPROBLEM; + } + } + + if(ssl_cafile && verifypeer) { +#ifdef MBEDTLS_FS_IO + ret = mbedtls_x509_crt_parse_file(&backend->cacert, ssl_cafile); + + if(ret < 0) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "mbedTLS: error reading CA cert file %s: (-0x%04X) %s", + ssl_cafile, (unsigned int)-ret, errorbuf); + return CURLE_SSL_CACERT_BADFILE; + } +#else + failf(data, "mbedTLS: functions that use the file system not built in"); + return CURLE_NOT_BUILT_IN; +#endif + } + + if(ssl_capath) { +#ifdef MBEDTLS_FS_IO + ret = mbedtls_x509_crt_parse_path(&backend->cacert, ssl_capath); + + if(ret < 0) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "mbedTLS: error reading CA cert path %s: (-0x%04X) %s", + ssl_capath, (unsigned int)-ret, errorbuf); + + if(verifypeer) + return CURLE_SSL_CACERT_BADFILE; + } +#else + failf(data, "mbedTLS: functions that use the file system not built in"); + return CURLE_NOT_BUILT_IN; +#endif + } + + return CURLE_OK; +} + +static CURLcode mbed_load_clicert(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + char * const ssl_cert = ssl_config->primary.clientcert; + const struct curl_blob *ssl_cert_blob = ssl_config->primary.cert_blob; +#ifdef MBEDTLS_PEM_PARSE_C + const char * const ssl_cert_type = ssl_config->primary.cert_type; +#endif + int ret = -1; + char errorbuf[128]; + + mbedtls_x509_crt_init(&backend->clicert); + + if(ssl_cert) { +#ifdef MBEDTLS_FS_IO + ret = mbedtls_x509_crt_parse_file(&backend->clicert, ssl_cert); + + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "mbedTLS: error reading client cert file %s: (-0x%04X) %s", + ssl_cert, (unsigned int)-ret, errorbuf); + + return CURLE_SSL_CERTPROBLEM; + } +#else + failf(data, "mbedTLS: functions that use the file system not built in"); + return CURLE_NOT_BUILT_IN; +#endif + } + + if(ssl_cert_blob) { +#ifdef MBEDTLS_PEM_PARSE_C + /* if DER or a null-terminated PEM process using + mbedtls_x509_crt_parse(). */ + if((ssl_cert_type && curl_strequal(ssl_cert_type, "DER")) || + ((char *)(ssl_cert_blob->data))[ssl_cert_blob->len - 1] == '\0') { + + ret = mbedtls_x509_crt_parse(&backend->clicert, + ssl_cert_blob->data, + ssl_cert_blob->len); + } + else { /* they say it is PEM and it is not null-terminated */ + + /* Unfortunately, mbedtls_x509_crt_parse() requires the data to be + null-terminated if the data is PEM encoded (even when provided the + exact length). The function accepts PEM or DER formats, but we cannot + assume if the user passed in a PEM format cert that it is + null-terminated. */ + unsigned char *newblob = curlx_memdup0(ssl_cert_blob->data, + ssl_cert_blob->len); + if(!newblob) + return CURLE_OUT_OF_MEMORY; + ret = mbedtls_x509_crt_parse(&backend->clicert, newblob, + ssl_cert_blob->len + 1); + curlx_free(newblob); + } +#else + /* DER encoded certs do not need to be null-terminated because it is a + binary format. Thus, if we are not compiling with PEM_PARSE we can avoid + the extra memory copies altogether. */ + ret = mbedtls_x509_crt_parse_der(&backend->clicert, ssl_cert_blob->data, + ssl_cert_blob->len); +#endif + + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "mbedTLS: error reading client cert blob: (-0x%04X) %s", + (unsigned int)-ret, errorbuf); + return CURLE_SSL_CERTPROBLEM; + } + } + + return CURLE_OK; +} + +static CURLcode mbed_load_privkey(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + int ret = -1; + char errorbuf[128]; + + mbedtls_pk_init(&backend->pk); + + if(ssl_config->primary.key || ssl_config->primary.key_blob) { + if(ssl_config->primary.key) { +#ifdef MBEDTLS_FS_IO +#if MBEDTLS_VERSION_NUMBER >= 0x04000000 + ret = mbedtls_pk_parse_keyfile(&backend->pk, ssl_config->primary.key, + ssl_config->primary.key_passwd); + if(ret == 0 && + !(mbedtls_pk_can_do_psa(&backend->pk, + PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_ANY_HASH), + PSA_KEY_USAGE_SIGN_HASH) || + mbedtls_pk_can_do_psa(&backend->pk, + MBEDTLS_PK_ALG_ECDSA(PSA_ALG_ANY_HASH), + PSA_KEY_USAGE_SIGN_HASH))) + ret = MBEDTLS_ERR_PK_TYPE_MISMATCH; +#else + ret = mbedtls_pk_parse_keyfile(&backend->pk, ssl_config->primary.key, + ssl_config->primary.key_passwd, + mbedtls_ctr_drbg_random, + &rng.drbg); + if(ret == 0 && !(mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_RSA) || + mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_ECKEY))) + ret = MBEDTLS_ERR_PK_TYPE_MISMATCH; +#endif + + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "mbedTLS: error reading private key %s: (-0x%04X) %s", + ssl_config->primary.key, (unsigned int)-ret, errorbuf); + return CURLE_SSL_CERTPROBLEM; + } +#else + failf(data, "mbedTLS: functions that use the file system not built in"); + return CURLE_NOT_BUILT_IN; +#endif + } + else { + const struct curl_blob *ssl_key_blob = ssl_config->primary.key_blob; + const char *passwd = ssl_config->primary.key_passwd; + /* Unfortunately, mbedtls_pk_parse_key() requires the data to be + null-terminated if the data is PEM encoded (even when provided the + exact length). */ + unsigned char *newblob = curlx_memdup0(ssl_key_blob->data, + ssl_key_blob->len); + if(!newblob) + return CURLE_OUT_OF_MEMORY; + +#if MBEDTLS_VERSION_NUMBER >= 0x04000000 + ret = mbedtls_pk_parse_key(&backend->pk, newblob, ssl_key_blob->len, + (const unsigned char *)passwd, + passwd ? strlen(passwd) : 0); + if(ret == 0 && + !(mbedtls_pk_can_do_psa(&backend->pk, + PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_ANY_HASH), + PSA_KEY_USAGE_SIGN_HASH) || + mbedtls_pk_can_do_psa(&backend->pk, + MBEDTLS_PK_ALG_ECDSA(PSA_ALG_ANY_HASH), + PSA_KEY_USAGE_SIGN_HASH))) + ret = MBEDTLS_ERR_PK_TYPE_MISMATCH; +#else + ret = mbedtls_pk_parse_key(&backend->pk, newblob, ssl_key_blob->len, + (const unsigned char *)passwd, + passwd ? strlen(passwd) : 0, + mbedtls_ctr_drbg_random, + &rng.drbg); + if(ret == 0 && !(mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_RSA) || + mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_ECKEY))) + ret = MBEDTLS_ERR_PK_TYPE_MISMATCH; +#endif + curlx_free(newblob); + + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "mbedTLS: error parsing private key: (-0x%04X) %s", + (unsigned int)-ret, errorbuf); + return CURLE_SSL_CERTPROBLEM; + } + } + } + + return CURLE_OK; +} + +static CURLcode mbed_load_crl(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + const char * const ssl_crlfile = ssl_config->primary.CRLfile; + +#ifdef MBEDTLS_X509_CRL_PARSE_C + mbedtls_x509_crl_init(&backend->crl); + + if(ssl_crlfile) { + char errorbuf[128]; +#ifdef MBEDTLS_FS_IO + int ret = mbedtls_x509_crl_parse_file(&backend->crl, ssl_crlfile); + + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "mbedTLS: error reading CRL file %s: (-0x%04X) %s", + ssl_crlfile, (unsigned int)-ret, errorbuf); + + return CURLE_SSL_CRL_BADFILE; + } +#else + (void)errorbuf; + failf(data, "mbedTLS: functions that use the file system not built in"); + return CURLE_NOT_BUILT_IN; +#endif + } +#else + (void)backend; + if(ssl_crlfile) { + failf(data, "mbedTLS: CRL support not built in"); + return CURLE_NOT_BUILT_IN; + } +#endif + + return CURLE_OK; +} + +static bool mbed_apply_session(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct Curl_ssl_session *sc_session) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + + if(sc_session && sc_session->sdata && sc_session->sdata_len) { + mbedtls_ssl_session session; + int ret; + + mbedtls_ssl_session_init(&session); + ret = mbedtls_ssl_session_load(&session, sc_session->sdata, + sc_session->sdata_len); + if(ret) { + failf(data, "SSL session error loading: -0x%x", (unsigned int)-ret); + } + else { + ret = mbedtls_ssl_set_session(&backend->ssl, &session); + if(ret) + failf(data, "SSL session error setting: -0x%x", (unsigned int)-ret); + } + mbedtls_ssl_session_free(&session); + if(!ret) { + infof(data, "SSL reusing session ID"); + return TRUE; + } + } + return FALSE; +} + +static CURLcode mbed_configure_ssl(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + int ret; + bool session_applied = FALSE; + CURLcode result; + char errorbuf[128]; + + infof(data, "mbedTLS: Connecting to %s:%d", + connssl->peer.origin->hostname, connssl->peer.origin->port); + + mbedtls_ssl_config_init(&backend->config); + ret = mbedtls_ssl_config_defaults(&backend->config, + MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT); + if(ret) { + failf(data, "mbedTLS: ssl_config failed"); + return CURLE_SSL_CONNECT_ERROR; + } + +#ifdef MBEDTLS_DEBUG + /* In order to make that work in mbedtls MBEDTLS_DEBUG_C must be defined. */ + mbedtls_ssl_conf_dbg(&backend->config, mbed_debug, data); + /* - 0 No debug + * - 1 Error + * - 2 State change + * - 3 Informational + * - 4 Verbose + */ + mbedtls_debug_set_threshold(4); +#endif + +#if defined(MBEDTLS_SSL_SESSION_TICKETS) && \ + defined(MBEDTLS_SSL_PROTO_TLS1_3) && \ + MBEDTLS_VERSION_NUMBER >= 0x03060100 && \ + MBEDTLS_VERSION_NUMBER < 0x04000000 + /* New in mbedTLS 3.6.1, need to enable, default is now disabled. 4.0.0 + enabled it by default for TLSv1.3. */ + mbedtls_ssl_conf_tls13_enable_signal_new_session_tickets( + &backend->config, MBEDTLS_SSL_TLS1_3_SIGNAL_NEW_SESSION_TICKETS_ENABLED); +#endif + + /* Always let mbedTLS verify certificates, if verifypeer or verifyhost are + * disabled we clear the corresponding error flags in the verify callback + * function. That is also where we log verification errors. */ + mbedtls_ssl_conf_verify(&backend->config, mbed_verify_cb, cf); + mbedtls_ssl_conf_authmode(&backend->config, MBEDTLS_SSL_VERIFY_REQUIRED); + + mbedtls_ssl_init(&backend->ssl); + backend->initialized = TRUE; + + /* use the default secure profile baked into mbedTLS */ + mbedtls_ssl_conf_cert_profile(&backend->config, + &mbedtls_x509_crt_profile_next); + + result = mbed_set_ssl_version_min_max(data, backend, conn_config); + if(result) + return result; + +#if MBEDTLS_VERSION_NUMBER < 0x04000000 + mbedtls_ssl_conf_rng(&backend->config, mbedtls_ctr_drbg_random, + &rng.drbg); +#endif + + ret = mbedtls_ssl_setup(&backend->ssl, + &backend->config); + if(ret) { + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "mbedTLS: ssl_setup failed: " + "(-0x%04X) %s", (unsigned int)-ret, errorbuf); + return CURLE_SSL_CONNECT_ERROR; + } + + mbedtls_ssl_set_bio(&backend->ssl, cf, + mbedtls_bio_cf_write, + mbedtls_bio_cf_read, + NULL /* rev_timeout() */); + +#ifndef MBEDTLS_SSL_PROTO_TLS1_3 + if(conn_config->cipher_list) { + result = mbed_set_selected_ciphers(data, backend, + conn_config->cipher_list, NULL); +#else + if(conn_config->cipher_list || conn_config->cipher_list13) { + result = mbed_set_selected_ciphers(data, backend, + conn_config->cipher_list, + conn_config->cipher_list13); +#endif + if(result) { + failf(data, "mbedTLS: failed to set cipher suites"); + return result; + } + } + else { + mbedtls_ssl_conf_ciphersuites(&backend->config, + mbedtls_ssl_list_ciphersuites()); + } + +#ifdef MBEDTLS_SSL_RENEGOTIATION + mbedtls_ssl_conf_renegotiation(&backend->config, + MBEDTLS_SSL_RENEGOTIATION_ENABLED); +#endif + +#ifdef MBEDTLS_SSL_SESSION_TICKETS + mbedtls_ssl_conf_session_tickets(&backend->config, + MBEDTLS_SSL_SESSION_TICKETS_DISABLED); +#endif + + if((cf->sockindex == SECONDARYSOCKET) && !(cf->cft->flags & CF_TYPE_PROXY)) { + /* FTP is a bitch. On TLS secured transfers, it is a common server + * option to require the client to use the SAME TLS session as on + * the control connection or it fails the request. See #22225. */ + struct Curl_ssl_session *scs = + Curl_ssl_get_cf_session(data, cf->cft, FIRSTSOCKET); + if(scs) { + if(mbed_apply_session(cf, data, scs)) { + CURL_TRC_CF(data, cf, "applied SSL session from control connection"); + session_applied = TRUE; + } + } + } + + /* Check if there is a cached ID we can/should use here! */ + if(!session_applied && Curl_ssl_scache_use(cf, data)) { + struct Curl_ssl_session *sc_session = NULL; + CURLcode sresult = Curl_ssl_scache_take(cf, data, connssl->peer.scache_key, + &sc_session); + if(!sresult && sc_session && sc_session->sdata && sc_session->sdata_len) { + mbedtls_ssl_session session; + + mbedtls_ssl_session_init(&session); + ret = mbedtls_ssl_session_load(&session, sc_session->sdata, + sc_session->sdata_len); + if(ret) { + failf(data, "SSL session error loading: -0x%x", (unsigned int)-ret); + } + else { + ret = mbedtls_ssl_set_session(&backend->ssl, &session); + if(ret) + failf(data, "SSL session error setting: -0x%x", (unsigned int)-ret); + else + infof(data, "SSL reusing session ID"); + } + mbedtls_ssl_session_free(&session); + } + Curl_ssl_scache_return(cf, data, connssl->peer.scache_key, + sc_session); + } + + mbedtls_ssl_conf_ca_chain(&backend->config, &backend->cacert, +#ifdef MBEDTLS_X509_CRL_PARSE_C + &backend->crl +#else + NULL +#endif + ); + + if(ssl_config->primary.key || ssl_config->primary.key_blob) { + mbedtls_ssl_conf_own_cert(&backend->config, &backend->clicert, + &backend->pk); + } + + if(mbedtls_ssl_set_hostname(&backend->ssl, connssl->peer.sni ? + connssl->peer.sni : + connssl->peer.origin->hostname)) { + /* mbedtls_ssl_set_hostname() sets the name to use in CN/SAN checks and + the name to set in the SNI extension. Thus even if curl connects to + a host specified as an IP address, this function must be used. */ + failf(data, "Failed to set SNI"); + return CURLE_SSL_CONNECT_ERROR; + } + +#ifdef HAS_ALPN_MBEDTLS + if(connssl->alpn) { + struct alpn_proto_buf proto; + size_t i; + + for(i = 0; i < connssl->alpn->count; ++i) { + backend->protocols[i] = connssl->alpn->entries[i]; + } + /* this function does not clone the protocols array, which is why we need + to keep it around */ + if(mbedtls_ssl_conf_alpn_protocols(&backend->config, + &backend->protocols[0])) { + failf(data, "Failed setting ALPN protocols"); + return CURLE_SSL_CONNECT_ERROR; + } + Curl_alpn_to_proto_str(&proto, connssl->alpn); + infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); + } +#endif + + /* give application a chance to interfere with mbedTLS set up. */ + if(data->set.ssl.fsslctx) { + result = (*data->set.ssl.fsslctx)(data, &backend->config, + data->set.ssl.fsslctxp); + if(result) + failf(data, "error signaled by SSL ctx callback"); + } + + return result; +} + +static CURLcode mbed_connect_step1(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + CURLcode result; + + if((conn_config->version == CURL_SSLVERSION_SSLv2) || + (conn_config->version == CURL_SSLVERSION_SSLv3)) { + failf(data, "Not supported SSL version"); + return CURLE_NOT_BUILT_IN; + } + + result = mbed_load_cacert(cf, data); + if(!result) + result = mbed_load_clicert(cf, data); + if(!result) + result = mbed_load_privkey(cf, data); + if(!result) + result = mbed_load_crl(cf, data); + if(!result) + result = mbed_configure_ssl(cf, data); + if(result) + return result; + + connssl->connecting_state = ssl_connect_2; + return CURLE_OK; +} + +#if defined(MBEDTLS_PK_WRITE_C) && defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) +#define HAVE_PINNED_PUBKEY +#endif + +static CURLcode mbed_connect_step2(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ +#if defined(HAVE_PINNED_PUBKEY) || defined(HAS_ALPN_MBEDTLS) + CURLcode result; +#endif + int ret; + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; +#ifdef HAVE_PINNED_PUBKEY +#ifndef CURL_DISABLE_PROXY + const char * const pinnedpubkey = Curl_ssl_cf_is_proxy(cf) ? + CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY_PROXY) : + CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY); +#else + const char * const pinnedpubkey = + CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY); +#endif +#endif + + DEBUGASSERT(backend); + + ret = mbedtls_ssl_handshake(&backend->ssl); + + if(ret == MBEDTLS_ERR_SSL_WANT_READ) { + connssl->io_need = CURL_SSL_IO_NEED_RECV; + return CURLE_OK; + } + else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) { + connssl->io_need = CURL_SSL_IO_NEED_SEND; + return CURLE_OK; + } + else if(ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) { + failf(data, "peer certificate could not be verified"); + return CURLE_PEER_FAILED_VERIFICATION; + } + else if(ret) { + char errorbuf[128]; + CURL_TRC_CF(data, cf, "TLS version %04X", + mbedtls_ssl_get_version_number(&backend->ssl)); + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "ssl_handshake returned: (-0x%04X) %s", + (unsigned int)-ret, errorbuf); + return CURLE_SSL_CONNECT_ERROR; + } + + { + char cipher_str[64]; + uint16_t cipher_id; + cipher_id = + (uint16_t)mbedtls_ssl_get_ciphersuite_id_from_ssl(&backend->ssl); + mbed_cipher_suite_get_str(cipher_id, cipher_str, sizeof(cipher_str), TRUE); + infof(data, "mbedTLS: %s Handshake complete, cipher is %s", + mbedtls_ssl_get_version(&backend->ssl), cipher_str); + } + +#ifdef HAVE_PINNED_PUBKEY + if(pinnedpubkey) { + int size; + const mbedtls_x509_crt *peercert; + mbedtls_x509_crt *p = NULL; + unsigned char *pubkey = NULL; + + peercert = mbedtls_ssl_get_peer_cert(&backend->ssl); + if(!peercert || !peercert->raw.p || !peercert->raw.len) { + failf(data, "Failed due to missing peer certificate"); + return CURLE_SSL_PINNEDPUBKEYNOTMATCH; + } + + p = curlx_calloc(1, sizeof(*p)); + + if(!p) + return CURLE_OUT_OF_MEMORY; + + pubkey = curlx_malloc(PUB_DER_MAX_BYTES); + + if(!pubkey) { + result = CURLE_OUT_OF_MEMORY; + goto pinnedpubkey_error; + } + + mbedtls_x509_crt_init(p); + + /* Make a copy of our const peercert because mbedtls_pk_write_pubkey_der + needs a non-const key, for now. + https://github.com/Mbed-TLS/mbedtls/issues/396 */ + if(mbedtls_x509_crt_parse_der(p, peercert->raw.p, peercert->raw.len)) { + failf(data, "Failed copying peer certificate"); + result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; + goto pinnedpubkey_error; + } + + size = mbedtls_pk_write_pubkey_der(&p->pk, pubkey, PUB_DER_MAX_BYTES); + + if(size <= 0) { + failf(data, "Failed copying public key from peer certificate"); + result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; + goto pinnedpubkey_error; + } + + /* mbedtls_pk_write_pubkey_der writes data at the end of the buffer. */ + result = Curl_pin_peer_pubkey(data, + pinnedpubkey, + &pubkey[PUB_DER_MAX_BYTES - size], size); +pinnedpubkey_error: + mbedtls_x509_crt_free(p); + curlx_free(p); + curlx_free(pubkey); + if(result) + return result; + } +#endif + +#ifdef HAS_ALPN_MBEDTLS + if(connssl->alpn) { + const char *proto = mbedtls_ssl_get_alpn_protocol(&backend->ssl); + + result = Curl_alpn_set_negotiated(cf, data, connssl, + (const unsigned char *)proto, + proto ? strlen(proto) : 0); + if(result) + return result; + } +#endif + + connssl->connecting_state = ssl_connect_3; + infof(data, "SSL connected"); + + return CURLE_OK; +} + +static CURLcode mbed_new_session(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + mbedtls_ssl_session session; + bool msession_alloced = FALSE; + struct Curl_ssl_session *sc_session = NULL; + unsigned char *sdata = NULL; + size_t slen = 0; + int ietf_tls_id; + CURLcode result = CURLE_OK; + int ret; + + DEBUGASSERT(backend); + if(!Curl_ssl_scache_use(cf, data)) + return CURLE_OK; + + mbedtls_ssl_session_init(&session); + ret = mbedtls_ssl_get_session(&backend->ssl, &session); + msession_alloced = (ret != MBEDTLS_ERR_SSL_ALLOC_FAILED); + if(ret) { + failf(data, "mbedtls_ssl_get_session returned -0x%x", (unsigned int)-ret); + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + + mbedtls_ssl_session_save(&session, NULL, 0, &slen); + if(!slen) { + failf(data, "failed to serialize session: length is 0"); + goto out; + } + + sdata = curlx_malloc(slen); + if(!sdata) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + ret = mbedtls_ssl_session_save(&session, sdata, slen, &slen); + if(ret) { + failf(data, "failed to serialize session: -0x%x", (unsigned int)-ret); + goto out; + } + + ietf_tls_id = mbedtls_ssl_get_version_number(&backend->ssl); + result = Curl_ssl_session_create(sdata, slen, + ietf_tls_id, + connssl->negotiated.alpn, 0, 0, + &sc_session); + sdata = NULL; /* call took ownership */ + if(!result && /* return a duplicate if asked for and FTP */ + (cf->conn->scheme->family == CURLPROTO_FTP)) { + Curl_ssl_session_destroy(connssl->session); + result = Curl_ssl_session_dup(sc_session, &connssl->session); + } + + if(!result) { + result = Curl_ssl_scache_put(cf, data, connssl->peer.scache_key, + sc_session); + sc_session = NULL; + } + +out: + if(msession_alloced) + mbedtls_ssl_session_free(&session); + Curl_ssl_session_destroy(sc_session); + curlx_free(sdata); + return result; +} + +static CURLcode mbed_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *mem, size_t len, size_t *pnwritten) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + CURLcode result = CURLE_OK; + int nwritten; + + DEBUGASSERT(backend); + *pnwritten = 0; + connssl->io_need = CURL_SSL_IO_NEED_NONE; + /* mbedTLS is picky when a mbedtls_ssl_write() was previously blocked. + * It requires to be called with the same amount of bytes again, or it + * loses bytes, e.g. reporting all was sent but they were not. + * Remember the blocked length and use that when set. */ + if(backend->send_blocked) { + DEBUGASSERT(backend->send_blocked_len <= len); + CURL_TRC_CF(data, cf, "mbedtls_ssl_write(len=%zu) -> previously blocked " + "on %zu bytes", len, backend->send_blocked_len); + len = backend->send_blocked_len; + } + + nwritten = mbedtls_ssl_write(&backend->ssl, (const unsigned char *)mem, len); + + if(nwritten >= 0) { + *pnwritten = (size_t)nwritten; + backend->send_blocked = FALSE; + } + else { + CURL_TRC_CF(data, cf, "mbedtls_ssl_write(len=%zu) -> -0x%04X", + len, (unsigned int)-nwritten); + switch(nwritten) { +#ifdef MBEDTLS_SSL_PROTO_TLS1_3 + case MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET: +#endif + case MBEDTLS_ERR_SSL_WANT_READ: + connssl->io_need = CURL_SSL_IO_NEED_RECV; + result = CURLE_AGAIN; + break; + case MBEDTLS_ERR_SSL_WANT_WRITE: + connssl->io_need = CURL_SSL_IO_NEED_SEND; + result = CURLE_AGAIN; + break; + default: + result = CURLE_SEND_ERROR; + break; + } + if((result == CURLE_AGAIN) && !backend->send_blocked) { + backend->send_blocked = TRUE; + backend->send_blocked_len = len; + } + } + + CURL_TRC_CF(data, cf, "mbedtls_ssl_write(len=%zu) -> %d, %zu", + len, (int)result, *pnwritten); + return result; +} + +static CURLcode mbedtls_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + unsigned char buf[1024]; + CURLcode result = CURLE_OK; + int ret = 0; + size_t i; + + DEBUGASSERT(backend); + + if(!backend->initialized || cf->shutdown) { + *done = TRUE; + return CURLE_OK; + } + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + *done = FALSE; + + if(!backend->sent_shutdown) { + /* do this only once */ + backend->sent_shutdown = TRUE; + if(send_shutdown) { + ret = mbedtls_ssl_close_notify(&backend->ssl); + switch(ret) { + case 0: /* we sent it, receive from the server */ + break; + case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY: /* server also closed */ + *done = TRUE; + goto out; + case MBEDTLS_ERR_SSL_WANT_READ: + connssl->io_need = CURL_SSL_IO_NEED_RECV; + goto out; + case MBEDTLS_ERR_SSL_WANT_WRITE: + connssl->io_need = CURL_SSL_IO_NEED_SEND; + goto out; + default: + CURL_TRC_CF(data, cf, "mbedtls_shutdown error -0x%04X", + (unsigned int)-ret); + result = CURLE_RECV_ERROR; + goto out; + } + } + } + + /* SSL should now have started the shutdown from our side. Since it + * was not complete, we are lacking the close notify from the server. */ + for(i = 0; i < 10; ++i) { + ret = mbedtls_ssl_read(&backend->ssl, buf, sizeof(buf)); + /* This seems to be a bug in mbedTLS TLSv1.3 where it reports + * WANT_READ, but has not encountered an EAGAIN. */ + if(ret == MBEDTLS_ERR_SSL_WANT_READ) + ret = mbedtls_ssl_read(&backend->ssl, buf, sizeof(buf)); +#ifdef MBEDTLS_SSL_PROTO_TLS1_3 + if(ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET) + continue; +#endif + if(ret <= 0) + break; + } + + if(ret > 0) { + /* still data coming in? */ + CURL_TRC_CF(data, cf, "mbedtls_shutdown, still getting data"); + } + else if(ret == 0 || (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)) { + /* We got the close notify alert and are done. */ + CURL_TRC_CF(data, cf, "mbedtls_shutdown done"); + *done = TRUE; + } + else if(ret == MBEDTLS_ERR_SSL_WANT_READ) { + CURL_TRC_CF(data, cf, "mbedtls_shutdown, need RECV"); + connssl->io_need = CURL_SSL_IO_NEED_RECV; + } + else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) { + CURL_TRC_CF(data, cf, "mbedtls_shutdown, need SEND"); + connssl->io_need = CURL_SSL_IO_NEED_SEND; + } + else { + CURL_TRC_CF(data, cf, "mbedtls_shutdown error -0x%04X", + (unsigned int)-ret); + result = CURLE_RECV_ERROR; + } + +out: + cf->shutdown = (result || *done); + return result; +} + +static void mbedtls_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + + (void)data; + DEBUGASSERT(backend); + mbedtls_pk_free(&backend->pk); + mbedtls_x509_crt_free(&backend->clicert); + mbedtls_x509_crt_free(&backend->cacert); +#ifdef MBEDTLS_X509_CRL_PARSE_C + mbedtls_x509_crl_free(&backend->crl); +#endif + curlx_safefree(backend->ciphersuites); + mbedtls_ssl_config_free(&backend->config); + if(backend->initialized) { + mbedtls_ssl_free(&backend->ssl); + backend->initialized = FALSE; + } +} + +static CURLcode mbed_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t buffersize, size_t *pnread) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + CURLcode result = CURLE_OK; + int nread; + + DEBUGASSERT(backend); + *pnread = 0; + connssl->io_need = CURL_SSL_IO_NEED_NONE; + + nread = mbedtls_ssl_read(&backend->ssl, (unsigned char *)buf, buffersize); + if(nread > 0) + *pnread = (size_t)nread; + else { + char errorbuf[128]; + CURL_TRC_CF(data, cf, "mbedtls_ssl_read(len=%zu) -> -0x%04X", + buffersize, (unsigned int)-nread); + switch(nread) { +#ifdef MBEDTLS_SSL_SESSION_TICKETS + case MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET: + mbed_new_session(cf, data); + FALLTHROUGH(); +#endif + case MBEDTLS_ERR_SSL_WANT_READ: + connssl->io_need = CURL_SSL_IO_NEED_RECV; + result = CURLE_AGAIN; + break; + case MBEDTLS_ERR_SSL_WANT_WRITE: + connssl->io_need = CURL_SSL_IO_NEED_SEND; + result = CURLE_AGAIN; + break; + case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY: + result = CURLE_OK; + break; + default: + mbedtls_strerror(nread, errorbuf, sizeof(errorbuf)); + failf(data, "ssl_read returned: (-0x%04X) %s", (unsigned int)-nread, + errorbuf); + result = CURLE_RECV_ERROR; + break; + } + } + return result; +} + +static size_t mbedtls_version(char *buffer, size_t size) +{ +#ifdef MBEDTLS_VERSION_C + /* if mbedtls_version_get_number() is available it is better */ + unsigned int version = mbedtls_version_get_number(); + return curl_msnprintf(buffer, size, "mbedTLS/%u.%u.%u", version >> 24, + (version >> 16) & 0xff, (version >> 8) & 0xff); +#else + return curl_msnprintf(buffer, size, "mbedTLS/%s", MBEDTLS_VERSION_STRING); +#endif +} + +/* 'data' might be NULL */ +static CURLcode mbedtls_random(struct Curl_easy *data, + unsigned char *entropy, size_t length) +{ + psa_status_t status; + (void)data; + + status = psa_generate_random(entropy, length); + + return status == PSA_SUCCESS ? CURLE_OK : CURLE_FAILED_INIT; +} + +static CURLcode mbedtls_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + CURLcode result; + struct ssl_connect_data *connssl = cf->ctx; + + /* check if the connection has already been established */ + if(ssl_connection_complete == connssl->state) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; + connssl->io_need = CURL_SSL_IO_NEED_NONE; + + if(connssl->connecting_state == ssl_connect_1) { + result = mbed_connect_step1(cf, data); + if(result) + return result; + } + + if(connssl->connecting_state == ssl_connect_2) { + result = mbed_connect_step2(cf, data); + if(result) + return result; + } + + if(connssl->connecting_state == ssl_connect_3) { + /* For tls1.3 we get notified about new sessions */ + struct ssl_connect_data *ctx = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)ctx->backend; + + if(mbedtls_ssl_get_version_number(&backend->ssl) <= + MBEDTLS_SSL_VERSION_TLS1_2) { + result = mbed_new_session(cf, data); + if(result) + return result; + } + connssl->connecting_state = ssl_connect_done; + } + + if(connssl->connecting_state == ssl_connect_done) { + connssl->state = ssl_connection_complete; + *done = TRUE; + } + + return CURLE_OK; +} + +/* + * return 0 error initializing SSL + * return 1 SSL initialized successfully + */ +static int mbedtls_init(void) +{ +#if MBEDTLS_VERSION_NUMBER < 0x04000000 + int ret = 0; +#endif + psa_status_t status; + status = psa_crypto_init(); + + if(status != PSA_SUCCESS) + return 0; + +#if MBEDTLS_VERSION_NUMBER < 0x04000000 + mbedtls_ctr_drbg_init(&rng.drbg); + mbedtls_entropy_init(&rng.entropy); + + ret = mbedtls_ctr_drbg_seed(&rng.drbg, mbedtls_entropy_func, &rng.entropy, + NULL, 0); + + if(ret) + /* mbedtls_ctr_drbg_seed returned error */ + return 0; + + /* To prevent an adversary from reading your random data, + you can enable prediction resistance. + + Entropy is gathered before each mbedtls_ctr_drbg_random() call. + Only use this if you have ample supply of good entropy.*/ + mbedtls_ctr_drbg_set_prediction_resistance(&rng.drbg, + MBEDTLS_CTR_DRBG_PR_ON); +#endif + return 1; +} + +static void mbedtls_cleanup(void) +{ + mbedtls_psa_crypto_free(); + +#if MBEDTLS_VERSION_NUMBER < 0x04000000 + mbedtls_ctr_drbg_free(&rng.drbg); + mbedtls_entropy_free(&rng.entropy); +#endif +} + +static bool mbedtls_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct ssl_connect_data *ctx = cf->ctx; + struct mbed_ssl_backend_data *backend; + + (void)data; + DEBUGASSERT(ctx && ctx->backend); + backend = (struct mbed_ssl_backend_data *)ctx->backend; + return mbedtls_ssl_get_bytes_avail(&backend->ssl) != 0; +} + +static CURLcode mbedtls_sha256sum(const unsigned char *input, + size_t inputlen, + unsigned char *sha256sum, + size_t sha256len) +{ +#if defined(PSA_WANT_ALG_SHA_256) && PSA_WANT_ALG_SHA_256 + psa_status_t status; + size_t sha256len_actual; + status = psa_hash_compute(PSA_ALG_SHA_256, input, inputlen, + sha256sum, sha256len, + &sha256len_actual); + if(status != PSA_SUCCESS) + return CURLE_BAD_FUNCTION_ARGUMENT; + return CURLE_OK; +#else + (void)sha256len; + return Curl_sha256it(sha256sum, input, inputlen); +#endif +} + +static void *mbedtls_get_internals(struct ssl_connect_data *connssl, + CURLINFO info) +{ + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + (void)info; + DEBUGASSERT(backend); + return &backend->ssl; +} + +const struct Curl_ssl Curl_ssl_mbedtls = { + { CURLSSLBACKEND_MBEDTLS, "mbedtls" }, /* info */ + + SSLSUPP_CA_PATH | + SSLSUPP_CAINFO_BLOB | + SSLSUPP_CERTINFO | +#ifdef HAVE_PINNED_PUBKEY + SSLSUPP_PINNEDPUBKEY | +#endif + SSLSUPP_SSL_CTX | +#ifdef MBEDTLS_SSL_PROTO_TLS1_3 /* requires mbedTLS 3.6.0+ */ + SSLSUPP_TLS13_CIPHERSUITES | +#endif + SSLSUPP_HTTPS_PROXY | + SSLSUPP_CIPHER_LIST | +#ifdef MBEDTLS_X509_CRL_PARSE_C + SSLSUPP_CRLFILE | +#endif + 0, + + sizeof(struct mbed_ssl_backend_data), + + mbedtls_init, /* init */ + mbedtls_cleanup, /* cleanup */ + mbedtls_version, /* version */ + mbedtls_shutdown, /* shutdown */ + mbedtls_data_pending, /* data_pending */ + mbedtls_random, /* random */ + NULL, /* cert_status_request */ + mbedtls_connect, /* connect */ + Curl_ssl_adjust_pollset, /* adjust_pollset */ + mbedtls_get_internals, /* get_internals */ + mbedtls_close, /* close_one */ + NULL, /* close_all */ + NULL, /* set_engine */ + NULL, /* set_engine_default */ + NULL, /* engines_list */ + mbedtls_sha256sum, /* sha256sum */ + mbed_recv, /* recv decrypted data */ + mbed_send, /* send data to encrypt */ + NULL, /* get_channel_binding */ +}; + +#endif /* USE_MBEDTLS */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/mbedtls.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/mbedtls.h new file mode 100644 index 0000000000..d8a0a06eb6 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/mbedtls.h @@ -0,0 +1,34 @@ +#ifndef HEADER_CURL_MBEDTLS_H +#define HEADER_CURL_MBEDTLS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) Hoi-Ho Chan, <hoiho.chan@gmail.com> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_MBEDTLS + +extern const struct Curl_ssl Curl_ssl_mbedtls; + +#endif /* USE_MBEDTLS */ +#endif /* HEADER_CURL_MBEDTLS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/openssl.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/openssl.c new file mode 100644 index 0000000000..dedd8f3e70 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/openssl.c @@ -0,0 +1,5571 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code + * but vtls.c should ever call or use these functions. + */ +#include "curl_setup.h" + +#ifdef USE_OPENSSL + +#include "urldata.h" +#include "curl_trc.h" +#include "formdata.h" /* for the boundary function */ +#include "url.h" /* for the SSL config check function */ +#include "curlx/inet_pton.h" +#include "vtls/openssl.h" +#include "connect.h" +#include "progress.h" +#include "vtls/vtls.h" +#include "vtls/vtls_int.h" +#include "vtls/vtls_scache.h" +#include "vauth/vauth.h" +#include "vtls/keylog.h" +#include "vtls/hostcheck.h" +#include "transfer.h" +#include "multiif.h" +#include "curlx/strerr.h" +#include "curlx/strparse.h" +#include "curlx/strcopy.h" +#include "curlx/strdup.h" +#include "vdns/cf-dns.h" +#include "vdns/httpsrr.h" +#include "vtls/apple.h" +#ifdef USE_ECH +#include "curlx/base64.h" +#endif + +#include <openssl/rand.h> +#include <openssl/x509v3.h> +#ifndef OPENSSL_NO_DSA +#include <openssl/dsa.h> +#endif +#include <openssl/dh.h> +#include <openssl/err.h> +#include <openssl/conf.h> +#include <openssl/bn.h> +#include <openssl/rsa.h> +#include <openssl/bio.h> +#include <openssl/pkcs12.h> +#include <openssl/tls1.h> +#include <openssl/evp.h> + +#if defined(HAVE_SSL_SET1_ECH_CONFIG_LIST) && !defined(HAVE_BORINGSSL_LIKE) +#include <openssl/ech.h> +#endif + +#ifndef OPENSSL_NO_OCSP +#include <openssl/ocsp.h> +#endif + +#if !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_UI_CONSOLE) +#define USE_OPENSSL_ENGINE +#include <openssl/engine.h> +#endif + +#ifdef LIBRESSL_VERSION_NUMBER +/* As of LibreSSL 2.0.0-4.0.0: OPENSSL_VERSION_NUMBER == 0x20000000L */ +# if LIBRESSL_VERSION_NUMBER < 0x2090100fL /* 2019-04-13 */ +# error "LibreSSL 2.9.1 or greater required" +# endif +#elif !defined(HAVE_BORINGSSL_LIKE) +# ifndef HAVE_OPENSSL3 /* 2021-09-07 */ +# error "OpenSSL 3.0.0 or greater required" +# endif +#endif + +#if defined(HAVE_OPENSSL3) && !defined(OPENSSL_NO_UI_CONSOLE) +#include <openssl/provider.h> +#include <openssl/store.h> +/* this is used in the following conditions to make them easier to read */ +#define OPENSSL_HAS_PROVIDERS +#endif + +/* AWS-LC fixed a bug with large buffers in v1.61.0 which also introduced + * X509_V_ERR_EC_KEY_EXPLICIT_PARAMS. */ +#if !defined(LIBRESSL_VERSION_NUMBER) && !defined(OPENSSL_IS_BORINGSSL) && \ + (!defined(OPENSSL_IS_AWSLC) || defined(X509_V_ERR_EC_KEY_EXPLICIT_PARAMS)) +#define HAVE_SSL_CTX_SET_DEFAULT_READ_BUFFER_LEN 1 +#endif + +#if defined(USE_OPENSSL_ENGINE) || defined(OPENSSL_HAS_PROVIDERS) +#include <openssl/ui.h> +#endif + +#ifdef HAVE_OPENSSL3 +#define HAVE_EVP_PKEY_GET_PARAMS 1 +#endif + +#ifdef HAVE_EVP_PKEY_GET_PARAMS +#include <openssl/core_names.h> +#define DECLARE_PKEY_PARAM_BIGNUM(name) BIGNUM *name = NULL +#define FREE_PKEY_PARAM_BIGNUM(name) BN_clear_free(name) +#else +#define DECLARE_PKEY_PARAM_BIGNUM(name) const BIGNUM *name +#define FREE_PKEY_PARAM_BIGNUM(name) +#endif + +/* Whether SSL_CTX_set_ciphersuites is available. + * BoringSSL: no + * LibreSSL: supported since 3.4.1 (released 2021-10-14) + * OpenSSL: supported since 1.1.1 (commit a53b5be6a05) + */ +#if (!defined(LIBRESSL_VERSION_NUMBER) || \ + (defined(LIBRESSL_VERSION_NUMBER) && \ + LIBRESSL_VERSION_NUMBER >= 0x3040100fL)) && \ + !defined(OPENSSL_IS_BORINGSSL) +# define HAVE_SSL_CTX_SET_CIPHERSUITES +# ifndef OPENSSL_IS_AWSLC +# define HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH +# endif +#endif + +/* Whether SSL_CTX_set1_sigalgs_list is available + * BoringSSL: supported since 0.20240913.0 (commit 826ce15) + * LibreSSL: no + * OpenSSL: supported since 1.0.2 (commit 0b362de5f575) + */ +#ifndef LIBRESSL_VERSION_NUMBER +#define HAVE_SSL_CTX_SET1_SIGALGS +#endif + +#ifdef LIBRESSL_VERSION_NUMBER +#define OSSL_PACKAGE "LibreSSL" +#elif defined(OPENSSL_IS_AWSLC) +#define OSSL_PACKAGE "AWS-LC" +#elif defined(OPENSSL_IS_BORINGSSL) +#define OSSL_PACKAGE "BoringSSL" +#elif defined(USE_NGTCP2) && defined(USE_NGHTTP3) && \ + !defined(OPENSSL_QUIC_API2) +#define OSSL_PACKAGE "quictls" +#else +#define OSSL_PACKAGE "OpenSSL" +#endif + +#ifdef HAVE_BORINGSSL_LIKE +typedef size_t numcert_t; +typedef uint32_t sslerr_t; +#else +typedef int numcert_t; +typedef unsigned long sslerr_t; +#endif +#define ossl_valsize_t numcert_t + +static CURLcode push_certinfo(struct Curl_easy *data, + BIO *mem, const char *label, int num) + WARN_UNUSED_RESULT; + +static CURLcode push_certinfo(struct Curl_easy *data, + BIO *mem, const char *label, int num) +{ + char *ptr; + long len = BIO_get_mem_data(mem, &ptr); + CURLcode result = Curl_ssl_push_certinfo_len(data, num, label, ptr, len); + (void)BIO_reset(mem); + return result; +} + +static CURLcode pubkey_show(struct Curl_easy *data, + BIO *mem, + int num, + const char *type, + const char *name, + const BIGNUM *bn) WARN_UNUSED_RESULT; + +static CURLcode pubkey_show(struct Curl_easy *data, + BIO *mem, + int num, + const char *type, + const char *name, + const BIGNUM *bn) +{ + char namebuf[32]; + + curl_msnprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name); + + if(bn) + BN_print(mem, bn); + return push_certinfo(data, mem, namebuf, num); +} + +#define print_pubkey_BN(_type, _name, _num) \ + pubkey_show(data, mem, _num, #_type, #_name, _name) + +static int asn1_object_dump(const ASN1_OBJECT *a, char *buf, size_t len) +{ + int i = i2t_ASN1_OBJECT(buf, (int)len, a); + return (i >= (int)len); /* buffer too small */ +} + +static CURLcode X509V3_ext(struct Curl_easy *data, + int certnum, + const STACK_OF(X509_EXTENSION) *extsarg) +{ + int i; + CURLcode result = CURLE_OK; +#ifdef LIBRESSL_VERSION_NUMBER + STACK_OF(X509_EXTENSION) *exts = CURL_UNCONST(extsarg); +#else + const STACK_OF(X509_EXTENSION) *exts = extsarg; +#endif + + if((int)sk_X509_EXTENSION_num(exts) <= 0) + /* no extensions, bail out */ + return result; + + for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) { + const ASN1_OBJECT *obj; + X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, (ossl_valsize_t)i); + BUF_MEM *biomem; + char namebuf[128]; + BIO *bio_out = BIO_new(BIO_s_mem()); + + if(!bio_out) + return result; + + obj = X509_EXTENSION_get_object(ext); + + if(asn1_object_dump(obj, namebuf, sizeof(namebuf))) + /* make sure the name is null-terminated */ + namebuf[CURL_CSTRLEN(namebuf)] = 0; + + if(!X509V3_EXT_print(bio_out, ext, 0, 0)) + ASN1_STRING_print(bio_out, + (const ASN1_STRING *)X509_EXTENSION_get_data(ext)); + + BIO_get_mem_ptr(bio_out, &biomem); + result = Curl_ssl_push_certinfo_len(data, certnum, namebuf, biomem->data, + biomem->length); + BIO_free(bio_out); + if(result) + break; + } + return result; +} + +static CURLcode get_pkey_rsa(struct Curl_easy *data, + EVP_PKEY *pubkey, BIO *mem, int i) +{ + CURLcode result = CURLE_OK; +#ifndef HAVE_EVP_PKEY_GET_PARAMS + RSA *rsa = EVP_PKEY_get0_RSA(pubkey); +#endif /* !HAVE_EVP_PKEY_GET_PARAMS */ + DECLARE_PKEY_PARAM_BIGNUM(n); + DECLARE_PKEY_PARAM_BIGNUM(e); +#ifdef HAVE_EVP_PKEY_GET_PARAMS + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_RSA_N, &n); + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_RSA_E, &e); +#else + RSA_get0_key(rsa, &n, &e, NULL); +#endif /* HAVE_EVP_PKEY_GET_PARAMS */ + BIO_printf(mem, "%d", (int)(n ? BN_num_bits(n) : 0)); + result = push_certinfo(data, mem, "RSA Public Key", i); + if(!result) { + result = print_pubkey_BN(rsa, n, i); + if(!result) + result = print_pubkey_BN(rsa, e, i); + } + FREE_PKEY_PARAM_BIGNUM(n); + FREE_PKEY_PARAM_BIGNUM(e); + return result; +} + +#ifndef OPENSSL_NO_DSA +static CURLcode get_pkey_dsa(struct Curl_easy *data, + EVP_PKEY *pubkey, BIO *mem, int i) +{ + CURLcode result = CURLE_OK; +#ifndef HAVE_EVP_PKEY_GET_PARAMS + DSA *dsa = EVP_PKEY_get0_DSA(pubkey); +#endif /* !HAVE_EVP_PKEY_GET_PARAMS */ + DECLARE_PKEY_PARAM_BIGNUM(p); + DECLARE_PKEY_PARAM_BIGNUM(q); + DECLARE_PKEY_PARAM_BIGNUM(g); + DECLARE_PKEY_PARAM_BIGNUM(pub_key); +#ifdef HAVE_EVP_PKEY_GET_PARAMS + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_P, &p); + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_Q, &q); + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_G, &g); + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_PUB_KEY, &pub_key); +#else + DSA_get0_pqg(dsa, &p, &q, &g); + DSA_get0_key(dsa, &pub_key, NULL); +#endif /* HAVE_EVP_PKEY_GET_PARAMS */ + result = print_pubkey_BN(dsa, p, i); + if(!result) + result = print_pubkey_BN(dsa, q, i); + if(!result) + result = print_pubkey_BN(dsa, g, i); + if(!result) + result = print_pubkey_BN(dsa, pub_key, i); + FREE_PKEY_PARAM_BIGNUM(p); + FREE_PKEY_PARAM_BIGNUM(q); + FREE_PKEY_PARAM_BIGNUM(g); + FREE_PKEY_PARAM_BIGNUM(pub_key); + return result; +} +#endif /* !OPENSSL_NO_DSA */ + +static CURLcode get_pkey_dh(struct Curl_easy *data, + EVP_PKEY *pubkey, BIO *mem, int i) +{ + CURLcode result; +#ifndef HAVE_EVP_PKEY_GET_PARAMS + DH *dh = EVP_PKEY_get0_DH(pubkey); +#endif /* !HAVE_EVP_PKEY_GET_PARAMS */ + DECLARE_PKEY_PARAM_BIGNUM(p); + DECLARE_PKEY_PARAM_BIGNUM(q); + DECLARE_PKEY_PARAM_BIGNUM(g); + DECLARE_PKEY_PARAM_BIGNUM(pub_key); +#ifdef HAVE_EVP_PKEY_GET_PARAMS + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_P, &p); + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_Q, &q); + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_G, &g); + EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_PUB_KEY, &pub_key); +#else + DH_get0_pqg(dh, &p, &q, &g); + DH_get0_key(dh, &pub_key, NULL); +#endif /* HAVE_EVP_PKEY_GET_PARAMS */ + result = print_pubkey_BN(dh, p, i); + if(!result) + result = print_pubkey_BN(dh, q, i); + if(!result) + result = print_pubkey_BN(dh, g, i); + if(!result) + result = print_pubkey_BN(dh, pub_key, i); + FREE_PKEY_PARAM_BIGNUM(p); + FREE_PKEY_PARAM_BIGNUM(q); + FREE_PKEY_PARAM_BIGNUM(g); + FREE_PKEY_PARAM_BIGNUM(pub_key); + return result; +} + +#ifdef HAVE_OPENSSL3 +/* from OpenSSL commit fc756e594ed5a27af378 */ +typedef const X509_PUBKEY pubkeytype_t; +#else +typedef X509_PUBKEY pubkeytype_t; +#endif + +static CURLcode ossl_certchain(struct Curl_easy *data, SSL *ssl) +{ + CURLcode result; + STACK_OF(X509) *sk; + int i; + numcert_t numcerts; + BIO *mem; + + DEBUGASSERT(ssl); + + sk = SSL_get_peer_cert_chain(ssl); + if(!sk) + return CURLE_SSL_CONNECT_ERROR; + + numcerts = sk_X509_num(sk); + if(numcerts > MAX_ALLOWED_CERT_AMOUNT) { + failf(data, "%d certificates is more than allowed (%d)", (int)numcerts, + MAX_ALLOWED_CERT_AMOUNT); + return CURLE_SSL_CONNECT_ERROR; + } + + result = Curl_ssl_init_certinfo(data, (int)numcerts); + if(result) + return result; + + mem = BIO_new(BIO_s_mem()); + if(!mem) + result = CURLE_OUT_OF_MEMORY; + + for(i = 0; !result && (i < (int)numcerts); i++) { + ASN1_INTEGER *num; + const unsigned char *numdata; + X509 *x = sk_X509_value(sk, (ossl_valsize_t)i); + EVP_PKEY *pubkey = NULL; + int j; + const ASN1_BIT_STRING *psig = NULL; + + X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE); + result = push_certinfo(data, mem, "Subject", i); + if(result) + break; + + X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE); + result = push_certinfo(data, mem, "Issuer", i); + if(result) + break; + + BIO_printf(mem, "%lx", (unsigned long)X509_get_version(x)); + result = push_certinfo(data, mem, "Version", i); + if(result) + break; + + num = X509_get_serialNumber(x); + if(ASN1_STRING_type(num) == V_ASN1_NEG_INTEGER) + BIO_puts(mem, "-"); + numdata = ASN1_STRING_get0_data(num); + for(j = 0; j < ASN1_STRING_length(num); j++) + BIO_printf(mem, "%02x", numdata[j]); + result = push_certinfo(data, mem, "Serial Number", i); + if(result) + break; + + { + const X509_ALGOR *sigalg = NULL; + pubkeytype_t *xpubkey = NULL; + ASN1_OBJECT *pubkeyoid = NULL; + + X509_get0_signature(&psig, &sigalg, x); + if(sigalg) { + const ASN1_OBJECT *sigalgoid = NULL; + X509_ALGOR_get0(&sigalgoid, NULL, NULL, sigalg); + i2a_ASN1_OBJECT(mem, sigalgoid); + result = push_certinfo(data, mem, "Signature Algorithm", i); + if(result) + break; + } + + xpubkey = X509_get_X509_PUBKEY(x); + if(xpubkey) { + X509_PUBKEY_get0_param(&pubkeyoid, NULL, NULL, NULL, xpubkey); + if(pubkeyoid) { + i2a_ASN1_OBJECT(mem, pubkeyoid); + result = push_certinfo(data, mem, "Public Key Algorithm", i); + if(result) + break; + } + } + + result = X509V3_ext(data, i, X509_get0_extensions(x)); + if(result) + break; + } + + ASN1_TIME_print(mem, X509_get0_notBefore(x)); + result = push_certinfo(data, mem, "Start date", i); + if(result) + break; + + ASN1_TIME_print(mem, X509_get0_notAfter(x)); + result = push_certinfo(data, mem, "Expire date", i); + if(result) + break; + + pubkey = X509_get_pubkey(x); + if(!pubkey) + infof(data, " Unable to load public key"); + else { + switch(EVP_PKEY_id(pubkey)) { + case EVP_PKEY_RSA: + result = get_pkey_rsa(data, pubkey, mem, i); + break; + +#ifndef OPENSSL_NO_DSA + case EVP_PKEY_DSA: + result = get_pkey_dsa(data, pubkey, mem, i); + break; +#endif + + case EVP_PKEY_DH: + result = get_pkey_dh(data, pubkey, mem, i); + break; + } + EVP_PKEY_free(pubkey); + } + + if(!result && psig) { + const unsigned char *psigdata = ASN1_STRING_get0_data(psig); + for(j = 0; j < ASN1_STRING_length(psig); j++) + BIO_printf(mem, "%02x:", psigdata[j]); + result = push_certinfo(data, mem, "Signature", i); + } + + if(!result) { + PEM_write_bio_X509(mem, x); + result = push_certinfo(data, mem, "Cert", i); + } + } + + BIO_free(mem); + + if(result) + /* cleanup all leftovers */ + Curl_ssl_free_certinfo(data); + + return result; +} + +static int ossl_bio_cf_create(BIO *bio) +{ + BIO_set_shutdown(bio, 1); + BIO_set_init(bio, 1); + BIO_set_data(bio, NULL); + return 1; +} + +static int ossl_bio_cf_destroy(BIO *bio) +{ + if(!bio) + return 0; + return 1; +} + +static long ossl_bio_cf_ctrl(BIO *bio, int cmd, long num, void *ptr) +{ + struct Curl_cfilter *cf = BIO_get_data(bio); + long ret = 1; + + (void)cf; + (void)ptr; + switch(cmd) { + case BIO_CTRL_GET_CLOSE: + ret = (long)BIO_get_shutdown(bio); + break; + case BIO_CTRL_SET_CLOSE: + BIO_set_shutdown(bio, (int)num); + break; + case BIO_CTRL_FLUSH: + /* we do no delayed writes, but if we ever would, this + * needs to trigger it. */ + ret = 1; + break; + case BIO_CTRL_DUP: + ret = 1; + break; + case BIO_CTRL_EOF: { + /* EOF has been reached on input? */ + struct ssl_connect_data *connssl = cf->ctx; + return connssl->peer_closed; + } + default: + ret = 0; + break; + } + return ret; +} + +static int ossl_bio_cf_out_write(BIO *bio, const char *buf, int blen) +{ + struct Curl_cfilter *cf = BIO_get_data(bio); + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + size_t nwritten; + CURLcode result; + + DEBUGASSERT(data); + if(blen < 0) + return 0; + + result = Curl_conn_cf_send(cf->next, data, + (const uint8_t *)buf, (size_t)blen, FALSE, + &nwritten); + CURL_TRC_CF(data, cf, "ossl_bio_cf_out_write(len=%d) -> %d, %zu", + blen, (int)result, nwritten); + BIO_clear_retry_flags(bio); + octx->io_result = result; + if(result) { + if(result == CURLE_AGAIN) + BIO_set_retry_write(bio); + return -1; + } + return (int)nwritten; +} + +static int ossl_bio_cf_in_read(BIO *bio, char *buf, int blen) +{ + struct Curl_cfilter *cf = BIO_get_data(bio); + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + size_t nread; + CURLcode result, r2; + + DEBUGASSERT(data); + /* OpenSSL catches this case, so should we. */ + if(!buf) + return 0; + if(blen < 0) + return 0; + + result = Curl_conn_cf_recv(cf->next, data, buf, (size_t)blen, &nread); + CURL_TRC_CF(data, cf, "ossl_bio_cf_in_read(len=%d) -> %d, %zu", + blen, (int)result, nread); + BIO_clear_retry_flags(bio); + octx->io_result = result; + if(result) { + if(result == CURLE_AGAIN) + BIO_set_retry_read(bio); + } + else { + /* feeding data to OpenSSL means SSL_read() might succeed */ + connssl->input_pending = TRUE; + if(nread == 0) + connssl->peer_closed = TRUE; + } + + /* Before returning server replies to the SSL instance, we need + * to have setup the x509 store or verification fails. */ + if(!octx->x509_store_setup) { + r2 = Curl_ssl_setup_x509_store(cf, data, octx); + if(r2) { + BIO_clear_retry_flags(bio); + octx->io_result = r2; + return -1; + } + octx->x509_store_setup = TRUE; + } + return result ? -1 : (int)nread; +} + +static BIO_METHOD *ossl_bio_cf_method_create(void) +{ + BIO_METHOD *m = BIO_meth_new(BIO_TYPE_MEM, "OpenSSL CF BIO"); + if(m) { + BIO_meth_set_write(m, &ossl_bio_cf_out_write); + BIO_meth_set_read(m, &ossl_bio_cf_in_read); + BIO_meth_set_ctrl(m, &ossl_bio_cf_ctrl); + BIO_meth_set_create(m, &ossl_bio_cf_create); + BIO_meth_set_destroy(m, &ossl_bio_cf_destroy); + } + return m; +} + +static void ossl_bio_cf_method_free(BIO_METHOD *m) +{ + if(m) + BIO_meth_free(m); +} + +#ifndef HAVE_KEYLOG_UPSTREAM +#ifdef HAVE_KEYLOG_CALLBACK +static void ossl_keylog_callback(const SSL *ssl, const char *line) +{ + (void)ssl; + + Curl_tls_keylog_write_line(line); +} +#else +/* + * ossl_log_tls12_secret is called by libcurl to make the CLIENT_RANDOMs if the + * OpenSSL being used does not have native support for doing that. + */ +static void ossl_log_tls12_secret(const SSL *ssl, bool *keylog_done) +{ + const SSL_SESSION *session; + unsigned char client_random[SSL3_RANDOM_SIZE]; + unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH]; + int master_key_length = 0; + + ERR_set_mark(); + + session = SSL_get_session(ssl); + + if(!session || *keylog_done) { + ERR_pop_to_mark(); + return; + } + + SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE); + master_key_length = (int) + SSL_SESSION_get_master_key(session, master_key, SSL_MAX_MASTER_KEY_LENGTH); + + ERR_pop_to_mark(); + + /* The handshake has not progressed sufficiently yet, or this is a TLS 1.3 + * session (when curl was built with older OpenSSL headers and running with + * newer OpenSSL runtime libraries). */ + if(master_key_length <= 0) + return; + + *keylog_done = TRUE; + Curl_tls_keylog_write("CLIENT_RANDOM", client_random, + sizeof(client_random), + master_key, master_key_length); +} +#endif /* !HAVE_KEYLOG_CALLBACK */ +#endif /* HAVE_KEYLOG_UPSTREAM */ + +static const char *SSL_ERROR_to_str(int err) +{ + switch(err) { + case SSL_ERROR_NONE: + return "SSL_ERROR_NONE"; + case SSL_ERROR_SSL: + return "SSL_ERROR_SSL"; + case SSL_ERROR_WANT_READ: + return "SSL_ERROR_WANT_READ"; + case SSL_ERROR_WANT_WRITE: + return "SSL_ERROR_WANT_WRITE"; + case SSL_ERROR_WANT_X509_LOOKUP: + return "SSL_ERROR_WANT_X509_LOOKUP"; + case SSL_ERROR_SYSCALL: + return "SSL_ERROR_SYSCALL"; + case SSL_ERROR_ZERO_RETURN: + return "SSL_ERROR_ZERO_RETURN"; + case SSL_ERROR_WANT_CONNECT: + return "SSL_ERROR_WANT_CONNECT"; + case SSL_ERROR_WANT_ACCEPT: + return "SSL_ERROR_WANT_ACCEPT"; +#ifdef SSL_ERROR_WANT_ASYNC /* OpenSSL 1.1.0+, LibreSSL 3.6.0+ */ + case SSL_ERROR_WANT_ASYNC: + return "SSL_ERROR_WANT_ASYNC"; +#endif +#ifdef SSL_ERROR_WANT_ASYNC_JOB /* OpenSSL 1.1.0+, LibreSSL 3.6.0+ */ + case SSL_ERROR_WANT_ASYNC_JOB: + return "SSL_ERROR_WANT_ASYNC_JOB"; +#endif +#ifdef SSL_ERROR_WANT_CLIENT_HELLO_CB /* OpenSSL 1.1.1, LibreSSL 3.6.0+ */ + case SSL_ERROR_WANT_CLIENT_HELLO_CB: + return "SSL_ERROR_WANT_CLIENT_HELLO_CB"; +#endif + default: + return "SSL_ERROR unknown"; + } +} + +/* Return error string for last OpenSSL error + */ +static char *ossl_strerror(unsigned long error, char *buf, size_t size) +{ + size_t len; + DEBUGASSERT(size); + *buf = '\0'; + + len = Curl_ossl_version(buf, size); + DEBUGASSERT(len < (size - 2)); + if(len < (size - 2)) { + buf += len; + size -= (len + 2); + *buf++ = ':'; + *buf++ = ' '; + *buf = '\0'; + } + +#ifdef HAVE_BORINGSSL_LIKE + ERR_error_string_n((uint32_t)error, buf, size); +#else + ERR_error_string_n(error, buf, size); +#endif + + if(!*buf) { + const char *msg = error ? "Unknown error" : "No error"; + curlx_strcopy(buf, size, msg, strlen(msg)); + } + + return buf; +} + +static int passwd_callback(char *buf, int num, int encrypting, void *password) +{ + DEBUGASSERT(encrypting == 0); + + if(!encrypting && num >= 0 && password) { + int klen = curlx_uztosi(strlen((char *)password)); + if(num > klen) { + memcpy(buf, password, klen + 1); + return klen; + } + } + return 0; +} + +/* + * rand_enough() returns TRUE if we have seeded the random engine properly. + */ +static bool rand_enough(void) +{ + return RAND_status() != 0; +} + +static CURLcode ossl_seed(struct Curl_easy *data) +{ + /* This might get called before it has been added to a multi handle */ + if(data->multi && data->multi->ssl_seeded) + return CURLE_OK; + + if(rand_enough()) { + /* OpenSSL 1.1.0+ should return here */ + if(data->multi) + data->multi->ssl_seeded = TRUE; + return CURLE_OK; + } + failf(data, "Insufficient randomness"); + return CURLE_SSL_CONNECT_ERROR; +} + +#ifndef SSL_FILETYPE_ENGINE +#define SSL_FILETYPE_ENGINE 42 +#endif +#ifndef SSL_FILETYPE_PKCS12 +#define SSL_FILETYPE_PKCS12 43 +#endif +#ifndef SSL_FILETYPE_PROVIDER +#define SSL_FILETYPE_PROVIDER 44 +#endif +static int ossl_do_file_type(const char *type) +{ + if(!type || !type[0]) + return SSL_FILETYPE_PEM; + if(curl_strequal(type, "PEM")) + return SSL_FILETYPE_PEM; + if(curl_strequal(type, "DER")) + return SSL_FILETYPE_ASN1; + if(curl_strequal(type, "PROV")) + return SSL_FILETYPE_PROVIDER; + if(curl_strequal(type, "ENG")) + return SSL_FILETYPE_ENGINE; + if(curl_strequal(type, "P12")) + return SSL_FILETYPE_PKCS12; + return -1; +} + +#if defined(USE_OPENSSL_ENGINE) || defined(OPENSSL_HAS_PROVIDERS) +/* + * Supply default password to the engine user interface conversation. + * The password is passed by OpenSSL engine from ENGINE_load_private_key() + * last argument to the ui and can be obtained by UI_get0_user_data(ui) here. + */ +static int ssl_ui_reader(UI *ui, UI_STRING *uis) +{ + const char *password; + switch(UI_get_string_type(uis)) { + case UIT_PROMPT: + case UIT_VERIFY: + password = (const char *)UI_get0_user_data(ui); + if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) { + UI_set_result(ui, uis, password); + return 1; + } + FALLTHROUGH(); + default: + break; + } + return UI_method_get_reader(UI_OpenSSL())(ui, uis); +} + +/* + * Suppress interactive request for a default password if available. + */ +static int ssl_ui_writer(UI *ui, UI_STRING *uis) +{ + switch(UI_get_string_type(uis)) { + case UIT_PROMPT: + case UIT_VERIFY: + if(UI_get0_user_data(ui) && + (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) { + return 1; + } + FALLTHROUGH(); + default: + break; + } + return UI_method_get_writer(UI_OpenSSL())(ui, uis); +} + +/* + * Check if a given string is a PKCS#11 URI + */ +static bool is_pkcs11_uri(const char *string) +{ + return string && curl_strnequal(string, "pkcs11:", 7); +} + +#endif + +static CURLcode ossl_set_engine(struct Curl_easy *data, const char *name); +#ifdef OPENSSL_HAS_PROVIDERS +static CURLcode ossl_set_provider(struct Curl_easy *data, const char *iname); +#endif + +static int use_certificate_blob(SSL_CTX *ctx, const struct curl_blob *blob, + int type, const char *key_passwd) +{ + int ret = 0; + X509 *x = NULL; + /* the typecast of blob->len is fine since it is guaranteed to never be + larger than CURL_MAX_INPUT_LENGTH */ + BIO *in = BIO_new_mem_buf(blob->data, (int)blob->len); + if(!in) + return CURLE_OUT_OF_MEMORY; + + if(type == SSL_FILETYPE_ASN1) { + /* j = ERR_R_ASN1_LIB; */ + x = d2i_X509_bio(in, NULL); + } + else if(type == SSL_FILETYPE_PEM) { + /* ERR_R_PEM_LIB; */ + x = PEM_read_bio_X509(in, NULL, passwd_callback, CURL_UNCONST(key_passwd)); + } + else { + ret = 0; + goto end; + } + + if(!x) { + ret = 0; + goto end; + } + + ret = SSL_CTX_use_certificate(ctx, x); +end: + X509_free(x); + BIO_free(in); + return ret; +} + +static int use_privatekey_blob(SSL_CTX *ctx, const struct curl_blob *blob, + int type, const char *key_passwd) +{ + int ret = 0; + EVP_PKEY *pkey = NULL; + BIO *in = BIO_new_mem_buf(blob->data, (int)blob->len); + if(!in) + return CURLE_OUT_OF_MEMORY; + + if(type == SSL_FILETYPE_PEM) + pkey = PEM_read_bio_PrivateKey(in, NULL, passwd_callback, + CURL_UNCONST(key_passwd)); + else if(type == SSL_FILETYPE_ASN1) + pkey = d2i_PrivateKey_bio(in, NULL); + else + goto end; + + if(!pkey) + goto end; + + ret = SSL_CTX_use_PrivateKey(ctx, pkey); + EVP_PKEY_free(pkey); +end: + BIO_free(in); + return ret; +} + +static int use_certificate_chain_blob(SSL_CTX *ctx, + const struct curl_blob *blob, + const char *key_passwd) +{ + int ret = 0; + X509 *x = NULL; + BIO *in = BIO_new_mem_buf(blob->data, (int)blob->len); + if(!in) + return CURLE_OUT_OF_MEMORY; + + ERR_clear_error(); + + x = PEM_read_bio_X509_AUX(in, NULL, + passwd_callback, CURL_UNCONST(key_passwd)); + if(!x) + goto end; + + ret = SSL_CTX_use_certificate(ctx, x); + + if(ERR_peek_error() != 0) + ret = 0; + + if(ret) { + X509 *ca; + sslerr_t err; + + if(!SSL_CTX_clear_chain_certs(ctx)) { + ret = 0; + goto end; + } + + while((ca = PEM_read_bio_X509(in, NULL, passwd_callback, + CURL_UNCONST(key_passwd))) != NULL) { + + if(!SSL_CTX_add0_chain_cert(ctx, ca)) { + X509_free(ca); + ret = 0; + goto end; + } + } + + err = ERR_peek_last_error(); + if((ERR_GET_LIB(err) == ERR_LIB_PEM) && + (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) + ERR_clear_error(); + else + ret = 0; + } + +end: + X509_free(x); + BIO_free(in); + return ret; +} + +static int enginecheck(struct Curl_easy *data, + SSL_CTX* ctx, + const char *key_file, + const char *key_passwd) +{ +#ifdef USE_OPENSSL_ENGINE + EVP_PKEY *priv_key = NULL; + + /* Implicitly use pkcs11 engine if none was provided and the + * key_file is a PKCS#11 URI */ + if(!data->state.engine) { + if(is_pkcs11_uri(key_file)) { + if(ossl_set_engine(data, "pkcs11") != CURLE_OK) { + return 0; + } + } + } + + if(data->state.engine) { + UI_METHOD *ui_method = UI_create_method("curl user interface"); + if(!ui_method) { + failf(data, "unable to create " OSSL_PACKAGE " user-interface method"); + return 0; + } + UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL())); + UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL())); + UI_method_set_reader(ui_method, ssl_ui_reader); + UI_method_set_writer(ui_method, ssl_ui_writer); + priv_key = ENGINE_load_private_key(data->state.engine, key_file, + ui_method, + CURL_UNCONST(key_passwd)); + UI_destroy_method(ui_method); + if(!priv_key) { + failf(data, "failed to load private key from crypto engine"); + return 0; + } + if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) { + failf(data, "unable to set private key"); + EVP_PKEY_free(priv_key); + return 0; + } + EVP_PKEY_free(priv_key); /* we do not need the handle any more... */ + } + else { + failf(data, "crypto engine not set, cannot load private key"); + return 0; + } + return 1; +#else + (void)ctx; + (void)key_file; + (void)key_passwd; + failf(data, "SSL_FILETYPE_ENGINE not supported for private key"); + return 0; +#endif +} + +static int providercheck(struct Curl_easy *data, + SSL_CTX* ctx, + const char *key_file) +{ +#ifdef OPENSSL_HAS_PROVIDERS + char error_buffer[256]; + /* Implicitly use pkcs11 provider if none was provided and the + * key_file is a PKCS#11 URI */ + if(!data->state.provider_loaded) { + if(is_pkcs11_uri(key_file)) { + if(ossl_set_provider(data, "pkcs11") != CURLE_OK) { + return 0; + } + } + } + + if(data->state.provider_loaded) { + /* Load the private key from the provider */ + EVP_PKEY *priv_key = NULL; + OSSL_STORE_CTX *store = NULL; + OSSL_STORE_INFO *info = NULL; + UI_METHOD *ui_method = UI_create_method("curl user interface"); + if(!ui_method) { + failf(data, "unable to create " OSSL_PACKAGE " user-interface method"); + return 0; + } + UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL())); + UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL())); + UI_method_set_reader(ui_method, ssl_ui_reader); + UI_method_set_writer(ui_method, ssl_ui_writer); + + store = OSSL_STORE_open_ex(key_file, data->state.libctx, + data->state.propq, ui_method, NULL, NULL, + NULL, NULL); + if(!store) { + failf(data, "Failed to open OpenSSL store: %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + UI_destroy_method(ui_method); + return 0; + } + if(OSSL_STORE_expect(store, OSSL_STORE_INFO_PKEY) != 1) { + failf(data, "Failed to set store preference. Ignoring the error: %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + } + + info = OSSL_STORE_load(store); + if(info) { + int ossl_type = OSSL_STORE_INFO_get_type(info); + + if(ossl_type == OSSL_STORE_INFO_PKEY) + priv_key = OSSL_STORE_INFO_get1_PKEY(info); + OSSL_STORE_INFO_free(info); + } + OSSL_STORE_close(store); + UI_destroy_method(ui_method); + if(!priv_key) { + failf(data, "No private key found in the openssl store: %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + return 0; + } + + if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) { + failf(data, "unable to set private key [%s]", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + EVP_PKEY_free(priv_key); + return 0; + } + EVP_PKEY_free(priv_key); /* we do not need the handle any more... */ + } + else { + failf(data, "crypto provider not set, cannot load private key"); + return 0; + } + return 1; +#else + (void)ctx; + (void)key_file; + failf(data, "SSL_FILETYPE_PROVIDER not supported for private key"); + return 0; +#endif +} + +static int engineload(struct Curl_easy *data, + SSL_CTX* ctx, + const char *cert_file) +{ +/* ENGINE_CTRL_GET_CMD_FROM_NAME supported by OpenSSL, LibreSSL <=3.8.3 */ +#if defined(USE_OPENSSL_ENGINE) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME) + char error_buffer[256]; + /* Implicitly use pkcs11 engine if none was provided and the + * cert_file is a PKCS#11 URI */ + if(!data->state.engine) { + if(is_pkcs11_uri(cert_file)) { + if(ossl_set_engine(data, "pkcs11") != CURLE_OK) { + return 0; + } + } + } + + if(data->state.engine) { + static const char cmd_name[] = "LOAD_CERT_CTRL"; + struct { + const char *cert_id; + X509 *cert; + } params; + + params.cert_id = cert_file; + params.cert = NULL; + + /* Does the engine supports LOAD_CERT_CTRL ? */ + if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME, + 0, CURL_UNCONST(cmd_name), NULL)) { + failf(data, "SSL engine does not support loading certificates"); + return 0; + } + + /* Load the certificate from the engine */ + if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name, 0, ¶ms, NULL, 1)) { + failf(data, "SSL engine cannot load client cert with id '%s' [%s]", + cert_file, + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + return 0; + } + + if(!params.cert) { + failf(data, "SSL engine did not initialize the certificate properly."); + return 0; + } + + if(SSL_CTX_use_certificate(ctx, params.cert) != 1) { + failf(data, "unable to set client certificate [%s]", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + X509_free(params.cert); + return 0; + } + X509_free(params.cert); /* we do not need the handle any more... */ + } + else { + failf(data, "crypto engine not set, cannot load certificate"); + return 0; + } + return 1; +#else + (void)ctx; + (void)cert_file; + failf(data, "SSL_FILETYPE_ENGINE not supported for certificate"); + return 0; +#endif +} + +static int providerload(struct Curl_easy *data, + SSL_CTX* ctx, + const char *cert_file) +{ +#ifdef OPENSSL_HAS_PROVIDERS + char error_buffer[256]; + /* Implicitly use pkcs11 provider if none was provided and the + * cert_file is a PKCS#11 URI */ + if(!data->state.provider_loaded) { + if(is_pkcs11_uri(cert_file)) { + if(ossl_set_provider(data, "pkcs11") != CURLE_OK) { + return 0; + } + } + } + + if(data->state.provider_loaded) { + /* Load the certificate from the provider */ + OSSL_STORE_INFO *info = NULL; + X509 *cert = NULL; + OSSL_STORE_CTX *store = + OSSL_STORE_open_ex(cert_file, data->state.libctx, + NULL, NULL, NULL, NULL, NULL, NULL); + int rc; + + if(!store) { + failf(data, "Failed to open OpenSSL store: %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + return 0; + } + if(OSSL_STORE_expect(store, OSSL_STORE_INFO_CERT) != 1) { + failf(data, "Failed to set store preference. Ignoring the error: %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + } + + info = OSSL_STORE_load(store); + if(info) { + int ossl_type = OSSL_STORE_INFO_get_type(info); + + if(ossl_type == OSSL_STORE_INFO_CERT) + cert = OSSL_STORE_INFO_get1_CERT(info); + OSSL_STORE_INFO_free(info); + } + OSSL_STORE_close(store); + if(!cert) { + failf(data, "No cert found in the openssl store: %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + return 0; + } + + rc = SSL_CTX_use_certificate(ctx, cert); + X509_free(cert); /* we do not need the handle any more... */ + + if(rc != 1) { + failf(data, "unable to set client certificate [%s]", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + return 0; + } + } + else { + failf(data, "crypto provider not set, cannot load certificate"); + return 0; + } + return 1; +#else + (void)ctx; + (void)cert_file; + failf(data, "SSL_FILETYPE_PROVIDER not supported for certificate"); + return 0; +#endif +} + +static int pkcs12load(struct Curl_easy *data, + SSL_CTX* ctx, + const struct curl_blob *cert_blob, + const char *cert_file, + const char *key_passwd) +{ + char error_buffer[256]; + BIO *cert_bio = NULL; + PKCS12 *p12 = NULL; + EVP_PKEY *pri; + X509 *x509; + int cert_done = 0; + STACK_OF(X509) *ca = NULL; + if(cert_blob) { + cert_bio = BIO_new_mem_buf(cert_blob->data, (int)cert_blob->len); + if(!cert_bio) { + failf(data, "BIO_new_mem_buf NULL, " OSSL_PACKAGE " error %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + return 0; + } + } + else { + cert_bio = BIO_new(BIO_s_file()); + if(!cert_bio) { + failf(data, "BIO_new return NULL, " OSSL_PACKAGE " error %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + return 0; + } + + if(BIO_read_filename(cert_bio, CURL_UNCONST(cert_file)) <= 0) { + failf(data, "could not open PKCS12 file '%s'", cert_file); + BIO_free(cert_bio); + return 0; + } + } + + p12 = d2i_PKCS12_bio(cert_bio, NULL); + BIO_free(cert_bio); + + if(!p12) { + failf(data, "error reading PKCS12 file '%s'", + cert_blob ? "(memory blob)" : cert_file); + return 0; + } + + if(!PKCS12_parse(p12, key_passwd, &pri, &x509, &ca)) { + failf(data, "could not parse PKCS12 file, check password, " OSSL_PACKAGE + " error %s", + ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer))); + PKCS12_free(p12); + return 0; + } + + PKCS12_free(p12); + + if(SSL_CTX_use_certificate(ctx, x509) != 1) { + failf(data, "could not load PKCS12 client certificate, " OSSL_PACKAGE + " error %s", + ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer))); + goto fail; + } + + if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) { + failf(data, "unable to use private key from PKCS12 file '%s'", cert_file); + goto fail; + } + + if(!SSL_CTX_check_private_key(ctx)) { + failf(data, "private key from PKCS12 file '%s' " + "does not match certificate in same file", cert_file); + goto fail; + } + /* Set Certificate Verification chain */ + if(ca) { + while(sk_X509_num(ca)) { + /* + * Note that sk_X509_pop() is used below to make sure the cert is + * removed from the stack properly before getting passed to + * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously + * we used sk_X509_value() instead, but then we would clean it in the + * subsequent sk_X509_pop_free() call. + */ + X509 *x = sk_X509_pop(ca); + if(!SSL_CTX_add_client_CA(ctx, x)) { + X509_free(x); + failf(data, "cannot add certificate to client CA list"); + goto fail; + } + if(!SSL_CTX_add_extra_chain_cert(ctx, x)) { + X509_free(x); + failf(data, "cannot add certificate to certificate chain"); + goto fail; + } + } + } + + cert_done = 1; +fail: + EVP_PKEY_free(pri); + X509_free(x509); +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcast-function-type-strict" +#endif + sk_X509_pop_free(ca, X509_free); +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic pop +#endif + if(!cert_done) + return 0; /* failure! */ + return 1; +} + +static CURLcode client_cert(struct Curl_easy *data, + SSL_CTX* ctx, + char *cert_file, + const struct curl_blob *cert_blob, + const char *cert_type, + char *key_file, + const struct curl_blob *key_blob, + const char *key_type, + char *key_passwd) +{ + char error_buffer[256]; + bool check_privkey = TRUE; + int file_type = ossl_do_file_type(cert_type); + + if(cert_file || cert_blob || (file_type == SSL_FILETYPE_ENGINE) || + (file_type == SSL_FILETYPE_PROVIDER)) { + SSL *ssl; + X509 *x509; + bool pcks12_done = FALSE; + int cert_use_result; + + if(key_passwd) { + /* set the password in the callback userdata */ + SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd); + /* Set passwd callback: */ + SSL_CTX_set_default_passwd_cb(ctx, passwd_callback); + } + + switch(file_type) { + case SSL_FILETYPE_PEM: + /* SSL_CTX_use_certificate_chain_file() only works on PEM files */ + cert_use_result = cert_blob ? + use_certificate_chain_blob(ctx, cert_blob, key_passwd) : + SSL_CTX_use_certificate_chain_file(ctx, cert_file); + if(cert_use_result != 1) { + failf(data, + "could not load PEM client certificate from %s, " OSSL_PACKAGE + " error %s, " + "(no key found, wrong passphrase, or wrong file format?)", + (cert_blob ? "CURLOPT_SSLCERT_BLOB" : cert_file), + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + return CURLE_SSL_CERTPROBLEM; + } + break; + + case SSL_FILETYPE_ASN1: + /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but + we use the case above for PEM so this can only be performed with + ASN1 files. */ + + cert_use_result = cert_blob ? + use_certificate_blob(ctx, cert_blob, file_type, key_passwd) : + SSL_CTX_use_certificate_file(ctx, cert_file, file_type); + if(cert_use_result != 1) { + failf(data, + "could not load ASN1 client certificate from %s, " OSSL_PACKAGE + " error %s, " + "(no key found, wrong passphrase, or wrong file format?)", + (cert_blob ? "CURLOPT_SSLCERT_BLOB" : cert_file), + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + return CURLE_SSL_CERTPROBLEM; + } + break; + + case SSL_FILETYPE_ENGINE: + if(!cert_file || !engineload(data, ctx, cert_file)) + return CURLE_SSL_CERTPROBLEM; + break; + + case SSL_FILETYPE_PROVIDER: + if(!cert_file || !providerload(data, ctx, cert_file)) + return CURLE_SSL_CERTPROBLEM; + break; + + case SSL_FILETYPE_PKCS12: + if(!pkcs12load(data, ctx, cert_blob, cert_file, key_passwd)) + return CURLE_SSL_CERTPROBLEM; + pcks12_done = TRUE; + break; + + default: + failf(data, "not supported file type '%s' for certificate", cert_type); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + if(!key_file && !key_blob) { + key_file = cert_file; + key_blob = cert_blob; + } + else + file_type = ossl_do_file_type(key_type); + + switch(file_type) { + case SSL_FILETYPE_PEM: + case SSL_FILETYPE_ASN1: + cert_use_result = key_blob ? + use_privatekey_blob(ctx, key_blob, file_type, key_passwd) : + SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type); + if(cert_use_result != 1) { + failf(data, "unable to set private key file: '%s' type %s", + key_file ? key_file : "(memory blob)", + key_type ? key_type : "PEM"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + break; + case SSL_FILETYPE_ENGINE: + if(!enginecheck(data, ctx, key_file, key_passwd)) + return CURLE_SSL_CERTPROBLEM; + break; + + case SSL_FILETYPE_PROVIDER: + if(!providercheck(data, ctx, key_file)) + return CURLE_SSL_CERTPROBLEM; + break; + + case SSL_FILETYPE_PKCS12: + if(!pcks12_done) { + failf(data, "file type P12 for private key not supported"); + return CURLE_SSL_CERTPROBLEM; + } + break; + default: + failf(data, "not supported file type for private key"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + ssl = SSL_new(ctx); + if(!ssl) { + failf(data, "unable to create an SSL structure"); + return CURLE_OUT_OF_MEMORY; + } + + x509 = SSL_get_certificate(ssl); + + if(x509) { + EVP_PKEY *pktmp = X509_get_pubkey(x509); + EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl)); + EVP_PKEY_free(pktmp); + } + +#if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DEPRECATED_3_0) + { + /* If RSA is used, do not check the private key if its flags indicate + * it does not support it. */ + EVP_PKEY *priv_key = SSL_get_privatekey(ssl); + if(EVP_PKEY_id(priv_key) == EVP_PKEY_RSA) { + RSA *rsa = EVP_PKEY_get1_RSA(priv_key); + if(RSA_flags(rsa) & RSA_METHOD_FLAG_NO_CHECK) + check_privkey = FALSE; + RSA_free(rsa); /* Decrement reference count */ + } + } +#endif + + SSL_free(ssl); + + /* If we are using DSA, we can copy the parameters from + * the private key */ + + if(check_privkey == TRUE) { + /* Now we know that a key and cert have been set against + * the SSL context */ + if(!SSL_CTX_check_private_key(ctx)) { + failf(data, "Private key does not match the certificate public key"); + return CURLE_SSL_CERTPROBLEM; + } + } + } + return CURLE_OK; +} + +#ifdef CURLVERBOSE +/* returns non-zero on failure */ +static CURLcode x509_name_oneline(const X509_NAME *a, struct dynbuf *d) +{ + BIO *bio_out = BIO_new(BIO_s_mem()); + BUF_MEM *biomem; + int rc; + CURLcode result = CURLE_OUT_OF_MEMORY; + + if(bio_out) { + unsigned long flags = XN_FLAG_SEP_SPLUS_SPC | + (XN_FLAG_ONELINE & ~ASN1_STRFLGS_ESC_MSB & ~XN_FLAG_SPC_EQ); + curlx_dyn_reset(d); + rc = X509_NAME_print_ex(bio_out, a, 0, flags); + if(rc != -1) { + BIO_get_mem_ptr(bio_out, &biomem); + result = curlx_dyn_addn(d, biomem->data, biomem->length); + } + BIO_free(bio_out); + } + return result; +} +#endif + +/** + * Global SSL init + * + * @retval 0 error initializing SSL + * @retval 1 SSL initialized successfully + */ +static int ossl_init(void) +{ + const uint64_t flags = +#ifdef OPENSSL_INIT_ENGINE_ALL_BUILTIN + /* not present in BoringSSL */ + OPENSSL_INIT_ENGINE_ALL_BUILTIN | +#endif +#ifdef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG + OPENSSL_INIT_NO_LOAD_CONFIG | +#else + OPENSSL_INIT_LOAD_CONFIG | +#endif + 0; + OPENSSL_init_ssl(flags, NULL); + +#ifndef HAVE_KEYLOG_UPSTREAM + Curl_tls_keylog_open(); +#endif + + return 1; +} + +/* Global cleanup */ +static void ossl_cleanup(void) +{ +#ifndef HAVE_KEYLOG_UPSTREAM + Curl_tls_keylog_close(); +#endif +} + +/* Selects an OpenSSL crypto engine or provider. + */ +static CURLcode ossl_set_engine(struct Curl_easy *data, const char *name) +{ +#ifdef USE_OPENSSL_ENGINE + CURLcode result = CURLE_SSL_ENGINE_NOTFOUND; + ENGINE *e = ENGINE_by_id(name); + + if(e) { + + if(data->state.engine) { + ENGINE_finish(data->state.engine); + ENGINE_free(data->state.engine); + data->state.engine = NULL; + } + if(!ENGINE_init(e)) { + char buf[256]; + + ENGINE_free(e); + failf(data, "Failed to initialize SSL Engine '%s': %s", + name, ossl_strerror(ERR_get_error(), buf, sizeof(buf))); + result = CURLE_SSL_ENGINE_INITFAILED; + e = NULL; + } + else { + result = CURLE_OK; + } + data->state.engine = e; + return result; + } +#endif +#ifdef OPENSSL_HAS_PROVIDERS + return ossl_set_provider(data, name); +#else + (void)name; + failf(data, "OpenSSL engine not found"); + return CURLE_SSL_ENGINE_NOTFOUND; +#endif +} + +/* Sets engine as default for all SSL operations + */ +static CURLcode ossl_set_engine_default(struct Curl_easy *data) +{ +#ifdef USE_OPENSSL_ENGINE + if(data->state.engine) { + if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) { + infof(data, "set default crypto engine '%s'", + ENGINE_get_id(data->state.engine)); + } + else { + failf(data, "set default crypto engine '%s' failed", + ENGINE_get_id(data->state.engine)); + return CURLE_SSL_ENGINE_SETFAILED; + } + } +#else + (void)data; +#endif + return CURLE_OK; +} + +/* Return list of OpenSSL crypto engine names. + */ +static struct curl_slist *ossl_engines_list(struct Curl_easy *data) +{ + struct curl_slist *list = NULL; +#ifdef USE_OPENSSL_ENGINE + struct curl_slist *beg; + ENGINE *e; + + for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) { + beg = curl_slist_append(list, ENGINE_get_id(e)); + if(!beg) { + curl_slist_free_all(list); + return NULL; + } + list = beg; + } +#endif + (void)data; + return list; +} + +#ifdef OPENSSL_HAS_PROVIDERS + +static void ossl_provider_cleanup(struct Curl_easy *data) +{ + if(data->state.baseprov) { + OSSL_PROVIDER_unload(data->state.baseprov); + data->state.baseprov = NULL; + } + if(data->state.provider) { + OSSL_PROVIDER_unload(data->state.provider); + data->state.provider = NULL; + } + OSSL_LIB_CTX_free(data->state.libctx); + data->state.libctx = NULL; + curlx_safefree(data->state.propq); + data->state.provider_loaded = FALSE; +} + +#define MAX_PROVIDER_LEN 128 /* reasonable */ + +/* Selects an OpenSSL crypto provider. + * + * A provider might need an associated property, a string passed on to + * OpenSSL. Specify this as [PROVIDER][:PROPERTY]: separate the name and the + * property with a colon. No colon means no property is set. + * + * An example provider + property looks like "tpm2:?provider=tpm2". + */ +static CURLcode ossl_set_provider(struct Curl_easy *data, const char *iname) +{ + char name[MAX_PROVIDER_LEN + 1]; + struct Curl_str prov; + const char *propq = NULL; + + if(!iname) { + /* clear and cleanup provider use */ + ossl_provider_cleanup(data); + return CURLE_OK; + } + if(curlx_str_until(&iname, &prov, MAX_PROVIDER_LEN, ':')) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(!curlx_str_single(&iname, ':')) + /* there was a colon, get the propq until the end of string */ + propq = iname; + + /* we need the name in a buffer, null-terminated */ + memcpy(name, curlx_str(&prov), curlx_strlen(&prov)); + name[curlx_strlen(&prov)] = 0; + + if(!data->state.libctx) { + OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new(); + if(!libctx) + return CURLE_OUT_OF_MEMORY; + if(propq) { + data->state.propq = curlx_strdup(propq); + if(!data->state.propq) { + OSSL_LIB_CTX_free(libctx); + return CURLE_OUT_OF_MEMORY; + } + } + data->state.libctx = libctx; + } + +#ifndef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG + /* load the configuration file into the library context before checking the + * provider availability */ + if(!OSSL_LIB_CTX_load_config(data->state.libctx, NULL)) { + infof(data, "Failed to load default openssl config. Proceeding."); + } +#endif + + if(OSSL_PROVIDER_available(data->state.libctx, name)) { + /* already loaded through the configuration - no action needed */ + data->state.provider_loaded = TRUE; + return CURLE_OK; + } + + data->state.provider = OSSL_PROVIDER_try_load(data->state.libctx, name, 1); + if(!data->state.provider) { + char error_buffer[256]; + failf(data, "Failed to initialize provider: %s", + ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer))); + ossl_provider_cleanup(data); + return CURLE_SSL_ENGINE_NOTFOUND; + } + + /* load the base provider as well */ + data->state.baseprov = OSSL_PROVIDER_try_load(data->state.libctx, "base", 1); + if(!data->state.baseprov) { + ossl_provider_cleanup(data); + failf(data, "Failed to load base"); + return CURLE_SSL_ENGINE_NOTFOUND; + } + else + data->state.provider_loaded = TRUE; + return CURLE_OK; +} +#endif + +static CURLcode ossl_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + CURLcode result = CURLE_OK; + char buf[1024]; + int nread = -1, err; + size_t i; + + DEBUGASSERT(octx); + if(!octx->ssl || cf->shutdown) { + *done = TRUE; + goto out; + } + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + *done = FALSE; + if(!(SSL_get_shutdown(octx->ssl) & SSL_SENT_SHUTDOWN)) { + /* We have not started the shutdown from our side yet. Check + * if the server already sent us one. */ + ERR_clear_error(); + for(i = 0; i < 10; ++i) { + nread = SSL_read(octx->ssl, buf, (int)sizeof(buf)); + CURL_TRC_CF(data, cf, "SSL shutdown not sent, read -> %d", nread); + if(nread <= 0) + break; + } + err = SSL_get_error(octx->ssl, nread); + if(!nread && err == SSL_ERROR_ZERO_RETURN) { + bool input_pending; + /* Yes, it did. */ + if(!send_shutdown) { + CURL_TRC_CF(data, cf, "SSL shutdown received, not sending"); + *done = TRUE; + goto out; + } + else if(!cf->next->cft->is_alive(cf->next, data, &input_pending)) { + /* Server closed the connection after its closy notify. It + * seems not interested to see our close notify, so do not + * send it. We are done. */ + connssl->peer_closed = TRUE; + CURL_TRC_CF(data, cf, "peer closed connection"); + *done = TRUE; + goto out; + } + } + } + + /* SSL should now have started the shutdown from our side. Since it + * was not complete, we are lacking the close notify from the server. */ + if(send_shutdown && !(SSL_get_shutdown(octx->ssl) & SSL_SENT_SHUTDOWN)) { + int rc; + ERR_clear_error(); + CURL_TRC_CF(data, cf, "send SSL close notify"); + rc = SSL_shutdown(octx->ssl); + if(rc == 1) { + CURL_TRC_CF(data, cf, "SSL shutdown finished"); + *done = TRUE; + goto out; + } + if(SSL_get_error(octx->ssl, rc) == SSL_ERROR_WANT_WRITE) { + CURL_TRC_CF(data, cf, "SSL shutdown still wants to send"); + connssl->io_need = CURL_SSL_IO_NEED_SEND; + goto out; + } + /* Having sent the close notify, we use SSL_read() to get the + * missing close notify from the server. */ + } + + for(i = 0; i < 10; ++i) { + ERR_clear_error(); + nread = SSL_read(octx->ssl, buf, (int)sizeof(buf)); + CURL_TRC_CF(data, cf, "SSL shutdown read -> %d", nread); + if(nread <= 0) + break; + } + err = SSL_get_error(octx->ssl, nread); + switch(err) { + case SSL_ERROR_ZERO_RETURN: /* no more data */ + if(SSL_shutdown(octx->ssl) == 1) + CURL_TRC_CF(data, cf, "SSL shutdown finished"); + else + CURL_TRC_CF(data, cf, "SSL shutdown not received, but closed"); + *done = TRUE; + break; + case SSL_ERROR_NONE: /* did not get anything */ + case SSL_ERROR_WANT_READ: + /* SSL has sent its notify and now wants to read the reply + * from the server. We are not really interested in that. */ + CURL_TRC_CF(data, cf, "SSL shutdown sent, want receive"); + connssl->io_need = CURL_SSL_IO_NEED_RECV; + break; + case SSL_ERROR_WANT_WRITE: + CURL_TRC_CF(data, cf, "SSL shutdown send blocked"); + connssl->io_need = CURL_SSL_IO_NEED_SEND; + break; + default: + /* Server seems to have closed the connection without sending us + * a close notify. */ + { + VERBOSE(unsigned long sslerr = ERR_get_error()); + CURL_TRC_CF(data, cf, "SSL shutdown, ignore recv error: '%s', errno %d", + (sslerr ? + ossl_strerror(sslerr, buf, sizeof(buf)) : + SSL_ERROR_to_str(err)), + SOCKERRNO); + } + *done = TRUE; + result = CURLE_OK; + break; + } + +out: + cf->shutdown = (result || *done); + if(cf->shutdown || (connssl->io_need != CURL_SSL_IO_NEED_NONE)) + connssl->input_pending = FALSE; + return result; +} + +static void ossl_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + + (void)data; + DEBUGASSERT(octx); + + connssl->input_pending = FALSE; + if(octx->ssl) { + SSL_free(octx->ssl); + octx->ssl = NULL; + } + if(octx->ssl_ctx) { + SSL_CTX_free(octx->ssl_ctx); + octx->ssl_ctx = NULL; + octx->x509_store_setup = FALSE; + } + if(octx->bio_method) { + ossl_bio_cf_method_free(octx->bio_method); + octx->bio_method = NULL; + } +} + +/* + * This function is called when the 'data' struct is going away. Close + * down everything and free all resources! + */ +static void ossl_close_all(struct Curl_easy *data) +{ +#ifdef USE_OPENSSL_ENGINE + if(data->state.engine) { + ENGINE_finish(data->state.engine); + ENGINE_free(data->state.engine); + data->state.engine = NULL; + } +#else + (void)data; +#endif +#ifdef OPENSSL_HAS_PROVIDERS + ossl_provider_cleanup(data); +#endif +} + +/* ====================================================== */ + +/* Quote from RFC2818 section 3.1 "Server Identity" + + If a subjectAltName extension of type dNSName is present, that MUST + be used as the identity. Otherwise, the (most specific) Common Name + field in the Subject field of the certificate MUST be used. Although + the use of the Common Name is existing practice, it is deprecated and + Certification Authorities are encouraged to use the dNSName instead. + + Matching is performed using the matching rules specified by + [RFC2459]. If more than one identity of a given type is present in + the certificate (e.g., more than one dNSName name, a match in any one + of the set is considered acceptable.) Names may contain the wildcard + character * which is considered to match any single domain name + component or component fragment. E.g., *.a.com matches foo.a.com but + not bar.foo.a.com. f*.com matches foo.com but not bar.com. + + In some cases, the URI is specified as an IP address rather than a + hostname. In this case, the iPAddress subjectAltName must be present + in the certificate and must exactly match the IP in the URI. + + This function is now used from ngtcp2 (QUIC) as well. + */ +static CURLcode ossl_verifyhost(struct Curl_easy *data, + struct connectdata *conn, + struct ssl_peer *peer, + X509 *server_cert) +{ + bool matched = FALSE; + int target; /* target type, GEN_DNS or GEN_IPADD */ + size_t addrlen = 0; + STACK_OF(GENERAL_NAME) *altnames; +#ifdef USE_IPV6 + struct in6_addr addr; +#else + struct in_addr addr; +#endif + CURLcode result = CURLE_OK; + bool dNSName = FALSE; /* if a dNSName field exists in the cert */ + bool iPAddress = FALSE; /* if an iPAddress field exists in the cert */ + size_t hostlen = strlen(peer->origin->hostname); + + (void)conn; + switch(peer->type) { + case CURL_SSL_PEER_IPV4: + if(!curlx_inet_pton(AF_INET, peer->origin->hostname, &addr)) + return CURLE_PEER_FAILED_VERIFICATION; + target = GEN_IPADD; + addrlen = sizeof(struct in_addr); + break; +#ifdef USE_IPV6 + case CURL_SSL_PEER_IPV6: + if(!curlx_inet_pton(AF_INET6, peer->origin->hostname, &addr)) + return CURLE_PEER_FAILED_VERIFICATION; + target = GEN_IPADD; + addrlen = sizeof(struct in6_addr); + break; +#endif + case CURL_SSL_PEER_DNS: + target = GEN_DNS; + break; + default: + DEBUGASSERT(0); + failf(data, "unexpected SSL peer type: %d", (int)peer->type); + return CURLE_PEER_FAILED_VERIFICATION; + } + + /* get a "list" of alternative names */ + altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL); + + if(altnames) { +#ifdef HAVE_BORINGSSL_LIKE + size_t numalts; + size_t i; +#else + int numalts; + int i; +#endif + + /* get amount of alternatives, RFC2459 claims there MUST be at least + one, but we do not depend on it... */ + numalts = sk_GENERAL_NAME_num(altnames); + + /* loop through all alternatives - until a dnsmatch */ + for(i = 0; (i < numalts) && !matched; i++) { + /* get a handle to alternative name number i */ + const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i); + + if(check->type == GEN_DNS) + dNSName = TRUE; + else if(check->type == GEN_IPADD) + iPAddress = TRUE; + + /* only check alternatives of the same type the target is */ + if(check->type == target) { + /* get data and length */ + const char *altptr = (const char *)ASN1_STRING_get0_data(check->d.ia5); + size_t altlen = (size_t)ASN1_STRING_length(check->d.ia5); + + switch(target) { + case GEN_DNS: /* name/pattern comparison */ + if(!memchr(altptr, '\0', altlen) && + Curl_cert_hostcheck(altptr, altlen, + peer->origin->hostname, hostlen)) { + matched = TRUE; + infof(data, " subjectAltName: \"%s\" matches cert's \"%.*s\"", + peer->origin->user_hostname, (int)altlen, altptr); + } + break; + + case GEN_IPADD: /* IP address comparison */ + /* compare alternative IP address if the data chunk is the same size + our server IP address is */ + if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) { + matched = TRUE; + infof(data, " subjectAltName: \"%s\" matches cert's IP address!", + peer->origin->user_hostname); + } + break; + } + } + } + GENERAL_NAMES_free(altnames); + } + + if(matched) + /* an alternative name matched */ + ; + else if(dNSName || iPAddress) { + const char *tname = (peer->type == CURL_SSL_PEER_DNS) ? "hostname" : + (peer->type == CURL_SSL_PEER_IPV4) ? + "IPv4 address" : "IPv6 address"; + infof(data, " subjectAltName does not match %s %s", tname, + peer->origin->user_hostname); + failf(data, "SSL: no alternative certificate subject name matches " + "target %s '%s'", tname, peer->origin->user_hostname); + result = CURLE_PEER_FAILED_VERIFICATION; + } + else { + /* we have to look to the last occurrence of a commonName in the + distinguished one to get the most significant one. */ + int i = -1; + unsigned char *cn = NULL; + int cnlen = 0; + bool free_cn = FALSE; + + /* The following is done because of a bug in 0.9.6b */ + const X509_NAME *name = X509_get_subject_name(server_cert); + if(name) { + int j; + while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0) + i = j; + } + + /* we have the name entry and we now convert this to a string + that we can use for comparison. Doing this we support BMPstring, + UTF8, etc. */ + + if(i >= 0) { + const ASN1_STRING *tmp = + X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i)); + + /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input + is already UTF-8 encoded. We check for this case and copy the raw + string manually to avoid the problem. This code can be made + conditional in the future when OpenSSL has been fixed. */ + if(tmp) { + if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) { + cnlen = ASN1_STRING_length(tmp); + cn = (unsigned char *)CURL_UNCONST(ASN1_STRING_get0_data(tmp)); + } + else { /* not a UTF8 name */ + cnlen = ASN1_STRING_to_UTF8(&cn, tmp); + free_cn = TRUE; + } + + if((cnlen <= 0) || !cn) + result = CURLE_OUT_OF_MEMORY; + else if((size_t)cnlen != strlen((char *)cn)) { + /* there was a null-terminator before the end of string, this + cannot match and we return failure! */ + failf(data, "SSL: illegal cert name field"); + result = CURLE_PEER_FAILED_VERIFICATION; + } + } + } + + if(result) + /* error already detected, pass through */ + ; + else if(!cn) { + failf(data, "SSL: unable to obtain common name from peer certificate"); + result = CURLE_PEER_FAILED_VERIFICATION; + } + else if(!Curl_cert_hostcheck((const char *)cn, cnlen, + peer->origin->hostname, hostlen)) { + failf(data, "SSL: certificate subject name '%s' does not match " + "target hostname '%s'", cn, peer->origin->user_hostname); + result = CURLE_PEER_FAILED_VERIFICATION; + } + else { + infof(data, " common name: %s (matched)", cn); + } + if(free_cn) + OPENSSL_free(cn); + } + + return result; +} + +#ifndef OPENSSL_NO_OCSP +static CURLcode verifystatus(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ossl_ctx *octx) +{ + int i, ocsp_status; +#ifdef HAVE_BORINGSSL_LIKE + const uint8_t *status; +#else + unsigned char *status; +#endif + const unsigned char *p; + CURLcode result = CURLE_OK; + OCSP_RESPONSE *rsp = NULL; + OCSP_BASICRESP *br = NULL; + X509_STORE *st = NULL; + STACK_OF(X509) *ch = NULL; + X509 *cert; + OCSP_CERTID *id = NULL; + int cert_status, crl_reason; + ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd; + int ret; + long len; + + (void)cf; + DEBUGASSERT(octx); + + len = (long)SSL_get_tlsext_status_ocsp_resp(octx->ssl, &status); + + if(!status) { + failf(data, "No OCSP response received"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + p = status; + rsp = d2i_OCSP_RESPONSE(NULL, &p, len); + if(!rsp) { + failf(data, "Invalid OCSP response"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + ocsp_status = OCSP_response_status(rsp); + if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) { + failf(data, "Invalid OCSP response status: %s (%d)", + OCSP_response_status_str(ocsp_status), ocsp_status); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + br = OCSP_response_get1_basic(rsp); + if(!br) { + failf(data, "Invalid OCSP response"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + ch = SSL_get_peer_cert_chain(octx->ssl); + if(!ch) { + failf(data, "Could not get peer certificate chain"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + st = SSL_CTX_get_cert_store(octx->ssl_ctx); + + if(OCSP_basic_verify(br, ch, st, 0) <= 0) { + failf(data, "OCSP response verification failed"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + /* Compute the certificate's ID */ + cert = SSL_get1_peer_certificate(octx->ssl); + if(!cert) { + failf(data, "Error getting peer certificate"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + for(i = 0; i < (int)sk_X509_num(ch); i++) { + X509 *issuer = sk_X509_value(ch, (ossl_valsize_t)i); + if(X509_check_issued(issuer, cert) == X509_V_OK) { + /* Note to analysis tools: using SHA1 here is fine. The `id` + * generated is used as a hash lookup key, not as a verifier + * of the OCSP data itself. This all according to RFC 5019. */ + id = OCSP_cert_to_id(EVP_sha1(), cert, issuer); + break; + } + } + X509_free(cert); + + if(!id) { + failf(data, "Error computing OCSP ID"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + /* Find the single OCSP response corresponding to the certificate ID */ + ret = OCSP_resp_find_status(br, id, &cert_status, &crl_reason, &rev, + &thisupd, &nextupd); + OCSP_CERTID_free(id); + if(ret != 1) { + failf(data, "Could not find certificate ID in OCSP response"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + /* Validate the OCSP response issuing and update times. + * - `thisupd` is the time the OCSP response was issued + * - `nextupd` is the time the OCSP response should be updated + * (valid life time assigned by the OCSP responder) + * - 3rd param: how many seconds of clock skew we allow between + * our clock and the instance that issued the OCSP response + * - 4th param: how many seconds in the past `thisupd` may be, with + * -1 meaning there is no limit. */ + if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) { + failf(data, "OCSP response has expired"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + + infof(data, "SSL certificate status: %s (%d)", + OCSP_cert_status_str(cert_status), cert_status); + + switch(cert_status) { + case V_OCSP_CERTSTATUS_GOOD: + break; + + case V_OCSP_CERTSTATUS_REVOKED: + result = CURLE_SSL_INVALIDCERTSTATUS; + failf(data, "SSL certificate revocation reason: %s (%d)", + OCSP_crl_reason_str(crl_reason), crl_reason); + goto end; + + case V_OCSP_CERTSTATUS_UNKNOWN: + default: + result = CURLE_SSL_INVALIDCERTSTATUS; + goto end; + } + +end: + if(br) + OCSP_BASICRESP_free(br); + OCSP_RESPONSE_free(rsp); + + return result; +} +#endif + +static const char *ssl_msg_type(int ssl_ver, int msg) +{ + if(ssl_ver == SSL3_VERSION_MAJOR) { + switch(msg) { + case SSL3_MT_HELLO_REQUEST: + return "Hello request"; + case SSL3_MT_CLIENT_HELLO: + return "Client hello"; + case SSL3_MT_SERVER_HELLO: + return "Server hello"; +#ifdef SSL3_MT_NEWSESSION_TICKET + case SSL3_MT_NEWSESSION_TICKET: + return "Newsession Ticket"; +#endif + case SSL3_MT_CERTIFICATE: + return "Certificate"; + case SSL3_MT_SERVER_KEY_EXCHANGE: + return "Server key exchange"; + case SSL3_MT_CLIENT_KEY_EXCHANGE: + return "Client key exchange"; + case SSL3_MT_CERTIFICATE_REQUEST: + return "Request CERT"; + case SSL3_MT_SERVER_DONE: + return "Server finished"; + case SSL3_MT_CERTIFICATE_VERIFY: + return "CERT verify"; + case SSL3_MT_FINISHED: + return "Finished"; +#ifdef SSL3_MT_CERTIFICATE_STATUS + case SSL3_MT_CERTIFICATE_STATUS: + return "Certificate Status"; +#endif +#ifdef SSL3_MT_ENCRYPTED_EXTENSIONS + case SSL3_MT_ENCRYPTED_EXTENSIONS: + return "Encrypted Extensions"; +#endif +#ifdef SSL3_MT_SUPPLEMENTAL_DATA + case SSL3_MT_SUPPLEMENTAL_DATA: + return "Supplemental data"; +#endif +#ifdef SSL3_MT_END_OF_EARLY_DATA + case SSL3_MT_END_OF_EARLY_DATA: + return "End of early data"; +#endif +#ifdef SSL3_MT_KEY_UPDATE + case SSL3_MT_KEY_UPDATE: + return "Key update"; +#endif +#ifdef SSL3_MT_NEXT_PROTO + case SSL3_MT_NEXT_PROTO: + return "Next protocol"; +#endif +#ifdef SSL3_MT_MESSAGE_HASH + case SSL3_MT_MESSAGE_HASH: + return "Message hash"; +#endif + } + } + return "Unknown"; +} + +static const char *tls_rt_type(int type) +{ + switch(type) { +#ifdef SSL3_RT_HEADER + case SSL3_RT_HEADER: + return "TLS header"; +#endif + case SSL3_RT_CHANGE_CIPHER_SPEC: + return "TLS change cipher"; + case SSL3_RT_ALERT: + return "TLS alert"; + case SSL3_RT_HANDSHAKE: + return "TLS handshake"; + case SSL3_RT_APPLICATION_DATA: + return "TLS app data"; + default: + return "TLS Unknown"; + } +} + +/* + * Our callback from the SSL/TLS layers. + */ +static void ossl_trace(int direction, int ssl_ver, int content_type, + const void *buf, size_t len, SSL *ssl, + void *userp) +{ + const char *verstr; + struct Curl_cfilter *cf = userp; + struct Curl_easy *data = NULL; + char unknown[32]; + + if(!cf) + return; + data = CF_DATA_CURRENT(cf); + if(!data || !data->set.fdebug || (direction && direction != 1)) + return; + + switch(ssl_ver) { +#ifdef SSL3_VERSION + case SSL3_VERSION: + verstr = "SSLv3"; + break; +#endif + case TLS1_VERSION: + verstr = "TLSv1.0"; + break; +#ifdef TLS1_1_VERSION + case TLS1_1_VERSION: + verstr = "TLSv1.1"; + break; +#endif +#ifdef TLS1_2_VERSION + case TLS1_2_VERSION: + verstr = "TLSv1.2"; + break; +#endif + case TLS1_3_VERSION: + verstr = "TLSv1.3"; + break; + default: + curl_msnprintf(unknown, sizeof(unknown), "(%x)", (unsigned int)ssl_ver); + verstr = unknown; + break; + } + + /* Log progress for interesting records only (like Handshake or Alert), skip + * all raw record headers (content_type == SSL3_RT_HEADER or ssl_ver == 0). + * For TLS 1.3, skip notification of the decrypted inner Content-Type. + */ + if(ssl_ver +#ifdef SSL3_RT_HEADER + && content_type != SSL3_RT_HEADER +#endif +#ifdef SSL3_RT_INNER_CONTENT_TYPE + && content_type != SSL3_RT_INNER_CONTENT_TYPE +#endif + ) { + const char *msg_name = "Truncated message"; + const char *tls_rt_name; + char ssl_buf[1024]; + int msg_type = 0; + int txt_len; + + /* the info given when the version is zero is not that useful for us */ + + ssl_ver >>= 8; /* check the upper 8 bits only below */ + + /* SSLv2 does not seem to have TLS record-type headers, so OpenSSL + * always pass-up content-type as 0, but the interesting message-type + * is at 'buf[0]'. + */ + if(ssl_ver == SSL3_VERSION_MAJOR && content_type) + tls_rt_name = tls_rt_type(content_type); + else + tls_rt_name = ""; + + if(content_type == SSL3_RT_CHANGE_CIPHER_SPEC) { + if(len) { + msg_type = *(const unsigned char *)buf; + msg_name = "Change cipher spec"; + } + } + else if(content_type == SSL3_RT_ALERT) { + if(len >= 2) { + msg_type = + (((const unsigned char *)buf)[0] << 8) + + ((const unsigned char *)buf)[1]; + msg_name = SSL_alert_desc_string_long(msg_type); + } + } + else if(len) { + msg_type = *(const unsigned char *)buf; + msg_name = ssl_msg_type(ssl_ver, msg_type); + } + + txt_len = curl_msnprintf(ssl_buf, sizeof(ssl_buf), + "%s (%s), %s, %s (%d):\n", + verstr, direction ? "OUT" : "IN", + tls_rt_name, msg_name, msg_type); + Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len); + } + + Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT : + CURLINFO_SSL_DATA_IN, (const char *)buf, len); + (void)ssl; +} + +static CURLcode ossl_set_ssl_version_min_max(struct Curl_cfilter *cf, + SSL_CTX *ctx, + unsigned int ssl_version_min) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + /* first, TLS min version... */ + long curl_ssl_version_min = (long)ssl_version_min; + long curl_ssl_version_max; + + /* convert curl min SSL version option to OpenSSL constant */ +#if defined(HAVE_BORINGSSL_LIKE) || defined(LIBRESSL_VERSION_NUMBER) + uint16_t ossl_ssl_version_min = 0; + uint16_t ossl_ssl_version_max = 0; +#else + long ossl_ssl_version_min = 0; + long ossl_ssl_version_max = 0; +#endif + /* it cannot be default here */ + DEBUGASSERT(curl_ssl_version_min != CURL_SSLVERSION_DEFAULT); + switch(curl_ssl_version_min) { + case CURL_SSLVERSION_TLSv1: /* TLS 1.x */ + case CURL_SSLVERSION_TLSv1_0: + ossl_ssl_version_min = TLS1_VERSION; + break; + case CURL_SSLVERSION_TLSv1_1: + ossl_ssl_version_min = TLS1_1_VERSION; + break; + case CURL_SSLVERSION_TLSv1_2: + ossl_ssl_version_min = TLS1_2_VERSION; + break; + case CURL_SSLVERSION_TLSv1_3: + ossl_ssl_version_min = TLS1_3_VERSION; + break; + } + + /* ... then, TLS max version */ + curl_ssl_version_max = (long)conn_config->version_max; + + /* convert curl max SSL version option to OpenSSL constant */ + switch(curl_ssl_version_max) { + case CURL_SSLVERSION_MAX_TLSv1_0: + ossl_ssl_version_max = TLS1_VERSION; + break; + case CURL_SSLVERSION_MAX_TLSv1_1: + ossl_ssl_version_max = TLS1_1_VERSION; + break; + case CURL_SSLVERSION_MAX_TLSv1_2: + ossl_ssl_version_max = TLS1_2_VERSION; + break; + case CURL_SSLVERSION_MAX_TLSv1_3: + ossl_ssl_version_max = TLS1_3_VERSION; + break; + case CURL_SSLVERSION_MAX_NONE: /* none selected */ + case CURL_SSLVERSION_MAX_DEFAULT: /* max selected */ + default: + /* SSL_CTX_set_max_proto_version states that: setting the maximum to 0 + enables protocol versions up to the highest version supported by + the library */ + ossl_ssl_version_max = 0; + break; + } + + if(!SSL_CTX_set_min_proto_version(ctx, ossl_ssl_version_min) || + !SSL_CTX_set_max_proto_version(ctx, ossl_ssl_version_max)) + return CURLE_SSL_CONNECT_ERROR; + + return CURLE_OK; +} + +CURLcode Curl_ossl_add_session(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ossl_ctx *octx, + const char *ssl_peer_key, + SSL_SESSION *session, + const char *alpn, + unsigned char *quic_tp, + size_t quic_tp_len, + struct Curl_ssl_session **psession) +{ + struct Curl_ssl_session *sc_session = NULL, *sc_dup = NULL; + unsigned char *der_session_buf = NULL; + unsigned char *qtp_clone = NULL; + CURLcode result = CURLE_OK; + + if(psession) + *psession = NULL; + if(!cf || !data) + goto out; + + if(Curl_ssl_scache_use(cf, data)) { + size_t der_session_size; + unsigned char *der_session_ptr; + size_t earlydata_max = 0; + int ietf_tls_id = SSL_version(octx->ssl); + + der_session_size = i2d_SSL_SESSION(session, NULL); + if(der_session_size == 0) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + der_session_buf = der_session_ptr = curlx_malloc(der_session_size); + if(!der_session_buf) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + der_session_size = i2d_SSL_SESSION(session, &der_session_ptr); + if(der_session_size == 0) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + +#ifdef HAVE_OPENSSL_EARLYDATA + earlydata_max = SSL_SESSION_get_max_early_data(session); +#endif + if(quic_tp && quic_tp_len) { + qtp_clone = curlx_memdup0((const char *)quic_tp, quic_tp_len); + if(!qtp_clone) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + + result = Curl_ssl_session_create2(der_session_buf, der_session_size, + ietf_tls_id, alpn, + (curl_off_t)time(NULL) + + SSL_SESSION_get_timeout(session), + earlydata_max, qtp_clone, quic_tp_len, + &sc_session); + der_session_buf = NULL; /* took ownership of sdata */ +#ifdef USE_APPLE_SECTRUST + if(!result) + sc_session->sectrust_verified = octx->sectrust_verified; +#endif + if(!result && psession && /* return a duplicate if asked for and FTP */ + (cf->conn->scheme->family == CURLPROTO_FTP)) { + result = Curl_ssl_session_dup(sc_session, &sc_dup); + } + if(!result) { + result = Curl_ssl_scache_put(cf, data, ssl_peer_key, sc_session); + /* took ownership of `sc_session` */ + sc_session = NULL; + } + } + +out: + curlx_free(der_session_buf); + if(!result && psession) { + *psession = sc_dup; + sc_dup = NULL; + } + Curl_ssl_session_destroy(sc_session); + Curl_ssl_session_destroy(sc_dup); + return result; +} + +/* The "new session" callback must return zero if the session can be removed + * or non-zero if the session has been put into the session cache. + */ +static int ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid) +{ + struct Curl_cfilter *cf = (struct Curl_cfilter *)SSL_get_app_data(ssl); + if(cf) { + struct Curl_easy *data = CF_DATA_CURRENT(cf); + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + struct Curl_ssl_session *session = NULL; + Curl_ossl_add_session(cf, data, octx, connssl->peer.scache_key, + ssl_sessionid, connssl->negotiated.alpn, NULL, + 0, &session); + if(session) { /* remember current TLS session */ + Curl_ssl_session_destroy(connssl->session); + connssl->session = session; + } + } + return 0; +} + +static CURLcode load_cacert_from_memory(X509_STORE *store, + const struct curl_blob *ca_info_blob) +{ + /* these need to be freed at the end */ + BIO *cbio = NULL; + STACK_OF(X509_INFO) *inf = NULL; + + /* everything else is a reference */ + int i, count = 0; + X509_INFO *itmp = NULL; + + if(ca_info_blob->len > (size_t)INT_MAX) + return CURLE_SSL_CACERT_BADFILE; + + cbio = BIO_new_mem_buf(ca_info_blob->data, (int)ca_info_blob->len); + if(!cbio) + return CURLE_OUT_OF_MEMORY; + + inf = PEM_X509_INFO_read_bio(cbio, NULL, NULL, NULL); + if(!inf) { + BIO_free(cbio); + return CURLE_SSL_CACERT_BADFILE; + } + + /* add each entry from PEM file to x509_store */ + for(i = 0; i < (int)sk_X509_INFO_num(inf); ++i) { + itmp = sk_X509_INFO_value(inf, (ossl_valsize_t)i); + if(itmp->x509) { + if(X509_STORE_add_cert(store, itmp->x509)) { + ++count; + } + else { + /* set count to 0 to return an error */ + count = 0; + break; + } + } + if(itmp->crl) { + if(X509_STORE_add_crl(store, itmp->crl)) { + ++count; + } + else { + /* set count to 0 to return an error */ + count = 0; + break; + } + } + } + +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcast-function-type-strict" +#endif + sk_X509_INFO_pop_free(inf, X509_INFO_free); +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic pop +#endif + BIO_free(cbio); + + /* if we did not end up importing anything, treat that as an error */ + return (count > 0) ? CURLE_OK : CURLE_SSL_CACERT_BADFILE; +} + +#ifdef USE_WIN32_CRYPTO +static CURLcode ossl_win_load_store(struct Curl_easy *data, + struct Curl_cfilter *cf, + const char *win_store, + X509_STORE *store, + bool *padded) +{ + CURLcode result = CURLE_OK; + HCERTSTORE hStore; + + *padded = FALSE; + + hStore = CertOpenSystemStoreA(0, win_store); + if(hStore) { + PCCERT_CONTEXT pContext = NULL; + /* The array of enhanced key usage OIDs varies per certificate and + is declared outside of the loop so that rather than malloc/free each + iteration we can grow it with realloc, when necessary. */ + CERT_ENHKEY_USAGE *enhkey_usage = NULL; + DWORD enhkey_usage_size = 0; + VERBOSE(size_t total = 0); + VERBOSE(size_t imported = 0); + + /* This loop makes a best effort to import all valid certificates from + the MS root store. If a certificate cannot be imported it is + skipped. 'result' is used to store only hard-fail conditions (such + as out of memory) that cause an early break. */ + result = CURLE_OK; + for(;;) { + X509 *x509; + FILETIME now; + BYTE key_usage[2]; + DWORD req_size; + const unsigned char *encoded_cert; + pContext = CertEnumCertificatesInStore(hStore, pContext); + if(!pContext) + break; + + VERBOSE(++total); + +#if defined(DEBUGBUILD) && defined(CURLVERBOSE) + { + char cert_name[256]; + if(!CertGetNameStringA(pContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, + NULL, cert_name, sizeof(cert_name))) + infof(data, "SSL: unknown cert name"); + else + infof(data, "SSL: Checking cert \"%s\"", cert_name); + } +#endif + encoded_cert = (const unsigned char *)pContext->pbCertEncoded; + if(!encoded_cert) + continue; + + GetSystemTimeAsFileTime(&now); + if(CompareFileTime(&pContext->pCertInfo->NotBefore, &now) > 0 || + CompareFileTime(&now, &pContext->pCertInfo->NotAfter) > 0) + continue; + + /* If key usage exists check for signing attribute */ + if(CertGetIntendedKeyUsage(pContext->dwCertEncodingType, + pContext->pCertInfo, + key_usage, sizeof(key_usage))) { + if(!(key_usage[0] & CERT_KEY_CERT_SIGN_KEY_USAGE)) + continue; + } + else if(GetLastError()) + continue; + + /* If enhanced key usage exists check for server auth attribute. + * + * Note "In a Microsoft environment, a certificate might also have + * EKU extended properties that specify valid uses for the + * certificate." The call below checks both, and behavior varies + * depending on what is found. For more details see + * CertGetEnhancedKeyUsage doc. + */ + if(CertGetEnhancedKeyUsage(pContext, 0, NULL, &req_size) && req_size) { + if(req_size > enhkey_usage_size) { + void *tmp = curlx_realloc(enhkey_usage, req_size); + + if(!tmp) { + failf(data, "SSL: Out of memory allocating for OID list"); + result = CURLE_OUT_OF_MEMORY; + break; + } + + enhkey_usage = (CERT_ENHKEY_USAGE *)tmp; + enhkey_usage_size = req_size; + } + + if(CertGetEnhancedKeyUsage(pContext, 0, enhkey_usage, &req_size)) { + if(!enhkey_usage->cUsageIdentifier) { + /* "If GetLastError returns CRYPT_E_NOT_FOUND, the certificate + is good for all uses. If it returns zero, the certificate + has no valid uses." */ + if((HRESULT)GetLastError() != CRYPT_E_NOT_FOUND) + continue; + } + else { + DWORD i; + bool found = FALSE; + + for(i = 0; i < enhkey_usage->cUsageIdentifier; ++i) { + if(!strcmp("1.3.6.1.5.5.7.3.1" /* OID server auth */, + enhkey_usage->rgpszUsageIdentifier[i])) { + found = TRUE; + break; + } + } + + if(!found) + continue; + } + } + else + continue; + } + else + continue; + + x509 = d2i_X509(NULL, &encoded_cert, (long)pContext->cbCertEncoded); + if(!x509) + continue; + + /* Try to import the certificate. This may fail for legitimate reasons + such as duplicate certificate, which is allowed by MS but not + OpenSSL. */ + if(X509_STORE_add_cert(store, x509) == 1) { + VERBOSE(++imported); +#ifdef DEBUGBUILD + infof(data, "SSL: Imported cert"); +#endif + *padded = TRUE; + } + X509_free(x509); + } + + curlx_free(enhkey_usage); + CertFreeCertificateContext(pContext); + CertCloseStore(hStore, 0); + + CURL_TRC_CF(data, cf, + "ossl_win_load_store() found: %zu imported: %zu certs in %s.", + total, imported, win_store); + + if(result) + return result; + } + + return result; +} + +static CURLcode ossl_windows_load_anchors(struct Curl_cfilter *cf, + struct Curl_easy *data, + X509_STORE *store, + bool *padded) +{ + /* Import certificates from the Windows root certificate store if + requested. + https://stackoverflow.com/questions/9507184/ + https://github.com/d3x0r/SACK/blob/ff15424d3c581b86d40f818532e5a400c516d39d/src/netlib/ssl_layer.c#L1410 + https://datatracker.ietf.org/doc/html/rfc5280 */ + static const char * const win_stores[] = { + "ROOT", /* Trusted Root Certification Authorities */ + "CA" /* Intermediate Certification Authorities */ + }; + size_t i; + CURLcode result = CURLE_OK; + + *padded = FALSE; + for(i = 0; i < CURL_ARRAYSIZE(win_stores); ++i) { + bool store_added = FALSE; + result = ossl_win_load_store(data, cf, win_stores[i], store, &store_added); + if(result) + return result; + if(store_added) { + CURL_TRC_CF(data, cf, "added trust anchors from Windows %s store", + win_stores[i]); + *padded = TRUE; + } + else + infof(data, "error importing Windows %s store, continuing anyway", + win_stores[i]); + } + return result; +} + +#endif /* USE_WIN32_CRYPTO */ + +static CURLcode ossl_load_trust_anchors(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ossl_ctx *octx, + X509_STORE *store) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + CURLcode result = CURLE_OK; + const char * const ssl_cafile = + /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */ + (conn_config->ca_info_blob ? NULL : conn_config->CAfile); + const char * const ssl_capath = conn_config->CApath; + bool have_native_check = FALSE; + + octx->store_is_empty = TRUE; + if(conn_config->native_ca_store) { +#ifdef USE_WIN32_CRYPTO + bool added = FALSE; + result = ossl_windows_load_anchors(cf, data, store, &added); + if(result) + return result; + if(added) { + infof(data, " Native: Windows System Stores ROOT+CA"); + octx->store_is_empty = FALSE; + } +#elif defined(USE_APPLE_SECTRUST) + infof(data, " Native: Apple SecTrust"); + have_native_check = TRUE; +#endif + } + + if(conn_config->ca_info_blob) { + result = load_cacert_from_memory(store, conn_config->ca_info_blob); + if(result) { + failf(data, "error adding trust anchors from certificate blob: %d", + (int)result); + return result; + } + infof(data, " CA Blob from configuration"); + octx->store_is_empty = FALSE; + } + + if(ssl_cafile || ssl_capath) { +#ifdef HAVE_OPENSSL3 + /* OpenSSL 3.0.0 has deprecated SSL_CTX_load_verify_locations */ + if(ssl_cafile) { + if(!X509_STORE_load_file(store, ssl_cafile)) { + if(octx->store_is_empty && !have_native_check) { + /* Fail if we insist on successfully verifying the server. */ + failf(data, "error adding trust anchors from file: %s", ssl_cafile); + return CURLE_SSL_CACERT_BADFILE; + } + else + infof(data, "error setting certificate file, continuing anyway"); + } + infof(data, " CAfile: %s", ssl_cafile); + octx->store_is_empty = FALSE; + } + if(ssl_capath) { + if(!X509_STORE_load_path(store, ssl_capath)) { + if(octx->store_is_empty && !have_native_check) { + /* Fail if we insist on successfully verifying the server. */ + failf(data, "error adding trust anchors from path: %s", ssl_capath); + return CURLE_SSL_CACERT_BADFILE; + } + else + infof(data, "error setting certificate path, continuing anyway"); + } + infof(data, " CApath: %s", ssl_capath); + octx->store_is_empty = FALSE; + } +#else + /* tell OpenSSL where to find CA certificates that are used to verify the + server's certificate. */ + if(!X509_STORE_load_locations(store, ssl_cafile, ssl_capath)) { + if(octx->store_is_empty && !have_native_check) { + /* Fail if we insist on successfully verifying the server. */ + failf(data, "error adding trust anchors from locations:" + " CAfile: %s CApath: %s", + ssl_cafile ? ssl_cafile : "none", + ssl_capath ? ssl_capath : "none"); + return CURLE_SSL_CACERT_BADFILE; + } + else { + infof(data, "error setting certificate verify locations," + " continuing anyway"); + } + } + if(ssl_cafile) + infof(data, " CAfile: %s", ssl_cafile); + if(ssl_capath) + infof(data, " CApath: %s", ssl_capath); + octx->store_is_empty = FALSE; +#endif + } + +#ifdef CURL_CA_FALLBACK + if(octx->store_is_empty) { + /* verifying the peer without any CA certificates does not + work so use OpenSSL's built-in default as fallback */ + X509_STORE_set_default_paths(store); + infof(data, " OpenSSL default paths (fallback)"); + octx->store_is_empty = FALSE; + } +#endif + if(octx->store_is_empty && !have_native_check) + infof(data, " no trust anchors configured"); + + return result; +} + +static CURLcode ossl_populate_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ossl_ctx *octx, + X509_STORE *store) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + CURLcode result = CURLE_OK; + X509_LOOKUP *lookup = NULL; + const char * const ssl_crlfile = ssl_config->primary.CRLfile; + unsigned long x509flags = 0; + + CURL_TRC_CF(data, cf, "configuring OpenSSL's x509 trust store"); + if(!store) + return CURLE_OUT_OF_MEMORY; + + if(!conn_config->verifypeer) { + infof(data, "SSL Trust: peer verification disabled"); + return CURLE_OK; + } + + infof(data, "SSL Trust Anchors:"); + result = ossl_load_trust_anchors(cf, data, octx, store); + if(result) + return result; + + /* Does not make sense to load a CRL file without peer verification */ + if(ssl_crlfile) { + /* tell OpenSSL where to find CRL file that is used to check certificate + * revocation */ + lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); + if(!lookup || + (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM))) { + failf(data, "error loading CRL file: %s", ssl_crlfile); + return CURLE_SSL_CRL_BADFILE; + } + x509flags = X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL; + infof(data, " CRLfile: %s", ssl_crlfile); + } + + /* Try building a chain using issuers in the trusted store first to avoid + problems with server-sent legacy intermediates. Newer versions of + OpenSSL do alternate chain checking by default but we do not know how to + determine that in a reliable manner. + https://web.archive.org/web/20190422050538/rt.openssl.org/Ticket/Display.html?id=3621 + */ + x509flags |= X509_V_FLAG_TRUSTED_FIRST; + + if(!ssl_config->no_partialchain && !ssl_crlfile) { + /* Have intermediate certificates in the trust store be treated as + trust-anchors, in the same way as self-signed root CA certificates are. + This allows users to verify servers using the intermediate cert only, + instead of needing the whole chain. + + Due to OpenSSL bug https://github.com/openssl/openssl/issues/5081 we + cannot do partial chains with a CRL check. */ + x509flags |= X509_V_FLAG_PARTIAL_CHAIN; + } + (void)X509_STORE_set_flags(store, x509flags); + + return result; +} + +/* key to use at `multi->proto_hash` */ +#define MPROTO_OSSL_X509_KEY "tls:ossl:x509:share" + +struct ossl_x509_share { + char *CAfile; /* CAfile path used to generate X509 store */ + X509_STORE *store; /* cached X509 store or NULL if none */ + struct curltime time; /* when the cached store was created */ + BIT(store_is_empty); /* no certs/paths/blobs are in the store */ + BIT(no_partialchain); /* keep partial chain state */ +}; + +static void oss_x509_share_free(void *key, size_t key_len, void *p) +{ + struct ossl_x509_share *share = p; + DEBUGASSERT(key_len == CURL_CSTRLEN(MPROTO_OSSL_X509_KEY)); + DEBUGASSERT(!memcmp(MPROTO_OSSL_X509_KEY, key, key_len)); + (void)key; + (void)key_len; + if(share->store) { + X509_STORE_free(share->store); + } + curlx_free(share->CAfile); + curlx_free(share); +} + +static bool ossl_cached_x509_store_expired(struct Curl_easy *data, + const struct ossl_x509_share *mb) +{ + const struct ssl_general_config *cfg = &data->set.general_ssl; + if(cfg->ca_cache_timeout < 0) + return FALSE; + else { + timediff_t elapsed_ms = curlx_ptimediff_ms(Curl_pgrs_now(data), &mb->time); + timediff_t timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000; + + return elapsed_ms >= timeout_ms; + } +} + +static bool ossl_cached_x509_store_different(struct Curl_cfilter *cf, + const struct Curl_easy *data, + const struct ossl_x509_share *mb) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = + Curl_ssl_cf_get_config(cf, CURL_UNCONST(data)); + if(mb->no_partialchain != ssl_config->no_partialchain) + return TRUE; + if(!mb->CAfile || !conn_config->CAfile) + return mb->CAfile != conn_config->CAfile; + return strcmp(mb->CAfile, conn_config->CAfile); +} + +static X509_STORE *ossl_get_cached_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *pempty) +{ + struct Curl_multi *multi = data->multi; + struct ossl_x509_share *share; + X509_STORE *store = NULL; + + DEBUGASSERT(multi); + *pempty = TRUE; + share = multi ? Curl_hash_pick(&multi->proto_hash, + CURL_UNCONST(MPROTO_OSSL_X509_KEY), + CURL_CSTRLEN(MPROTO_OSSL_X509_KEY)) : NULL; + if(share && share->store && + !ossl_cached_x509_store_expired(data, share) && + !ossl_cached_x509_store_different(cf, data, share)) { + store = share->store; + *pempty = (bool)share->store_is_empty; + } + + return store; +} + +static void ossl_set_cached_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + X509_STORE *store, + bool is_empty) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_multi *multi = data->multi; + struct ossl_x509_share *share; + + DEBUGASSERT(multi); + if(!multi) + return; + share = Curl_hash_pick(&multi->proto_hash, + CURL_UNCONST(MPROTO_OSSL_X509_KEY), + CURL_CSTRLEN(MPROTO_OSSL_X509_KEY)); + + if(!share) { + share = curlx_calloc(1, sizeof(*share)); + if(!share) + return; + if(!Curl_hash_add2(&multi->proto_hash, + CURL_UNCONST(MPROTO_OSSL_X509_KEY), + CURL_CSTRLEN(MPROTO_OSSL_X509_KEY), + share, oss_x509_share_free)) { + curlx_free(share); + return; + } + } + + if(X509_STORE_up_ref(store)) { + char *CAfile = NULL; + struct ssl_config_data *ssl_config = + Curl_ssl_cf_get_config(cf, CURL_UNCONST(data)); + + if(conn_config->CAfile) { + CAfile = curlx_strdup(conn_config->CAfile); + if(!CAfile) { + X509_STORE_free(store); + return; + } + } + + if(share->store) { + X509_STORE_free(share->store); + curlx_free(share->CAfile); + } + + share->time = *Curl_pgrs_now(data); + share->store = store; + share->store_is_empty = is_empty; + share->CAfile = CAfile; + share->no_partialchain = ssl_config->no_partialchain; + } +} + +CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ossl_ctx *octx) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + CURLcode result = CURLE_OK; + X509_STORE *cached_store; + bool cache_criteria_met, is_empty; + + /* Consider the X509 store cacheable if it comes exclusively from a CAfile, + or no source is provided and we are falling back to OpenSSL's built-in + default. */ + cache_criteria_met = (data->set.general_ssl.ca_cache_timeout != 0) && + conn_config->verifypeer && + !conn_config->CApath && + !conn_config->ca_info_blob && + !ssl_config->primary.CRLfile && + !conn_config->native_ca_store; + + ERR_set_mark(); + + cached_store = ossl_get_cached_x509_store(cf, data, &is_empty); + if(cached_store && cache_criteria_met && X509_STORE_up_ref(cached_store)) { + SSL_CTX_set_cert_store(octx->ssl_ctx, cached_store); + octx->store_is_empty = is_empty; + } + else { + X509_STORE *store = SSL_CTX_get_cert_store(octx->ssl_ctx); + + result = ossl_populate_x509_store(cf, data, octx, store); + if(result == CURLE_OK && cache_criteria_met) { + ossl_set_cached_x509_store(cf, data, store, (bool)octx->store_is_empty); + } + } + + ERR_pop_to_mark(); + + return result; +} + +static bool ossl_apply_session( + struct ossl_ctx *octx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct alpn_spec *alpns, + Curl_ossl_init_session_reuse_cb *sess_reuse_cb, + struct Curl_ssl_session *scs) +{ + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + struct ssl_primary_config *conn_cfg = Curl_ssl_cf_get_primary_config(cf); + const unsigned char *der_sessionid = scs->sdata; + size_t der_sessionid_size = scs->sdata_len; + SSL_SESSION *ssl_session = NULL; + + /* If OpenSSL does not accept the session from the cache, this + * is not an error. We continue without it. */ + ssl_session = d2i_SSL_SESSION(NULL, &der_sessionid, + (long)der_sessionid_size); + if(ssl_session) { + if(!SSL_set_session(octx->ssl, ssl_session)) { + VERBOSE(char error_buffer[256]); + infof(data, "SSL: SSL_set_session not accepted, " + "continuing without: %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + } + else { + if(conn_cfg->verifypeer && + (SSL_get_verify_result(octx->ssl) != X509_V_OK) +#ifdef USE_APPLE_SECTRUST + /* if sectrust is used and verified the session before */ + && (!conn_cfg->native_ca_store || !scs->sectrust_verified) +#endif + ) { + /* Session was from unverified connection, cannot reuse here */ + SSL_set_session(octx->ssl, NULL); + infof(data, "SSL session not peer verified, not reusing"); + } + else { + infof(data, "SSL reusing session with ALPN '%s'", + scs->alpn ? scs->alpn : "-"); + octx->reused_session = TRUE; +#ifdef USE_APPLE_SECTRUST + octx->sectrust_session = scs->sectrust_verified; +#endif + infof(data, "SSL verify result: %lx", + (unsigned long)SSL_get_verify_result(octx->ssl)); +#ifdef HAVE_OPENSSL_EARLYDATA + if(ssl_config->earlydata && scs->alpn && + SSL_SESSION_get_max_early_data(ssl_session) && + !cf->conn->bits.connect_only && + (SSL_version(octx->ssl) == TLS1_3_VERSION)) { + bool do_early_data = FALSE; + if(sess_reuse_cb) + (void)sess_reuse_cb(cf, data, alpns, scs, &do_early_data); + if(do_early_data) { + /* We only try the ALPN protocol the session used before, + * otherwise we might send early data for the wrong protocol */ + Curl_alpn_restrict_to(alpns, scs->alpn); + } + } +#else + (void)alpns; + (void)ssl_config; + (void)sess_reuse_cb; +#endif + } + } + SSL_SESSION_free(ssl_session); + } + else { + infof(data, "SSL session not accepted by OpenSSL, continuing without"); + } + return (bool)octx->reused_session; +} + +static CURLcode ossl_init_session_and_alpns( + struct ossl_ctx *octx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + const struct alpn_spec *alpns_requested, + Curl_ossl_init_session_reuse_cb *sess_reuse_cb) +{ + struct ssl_primary_config *conn_cfg = Curl_ssl_cf_get_primary_config(cf); + struct alpn_spec alpns; + CURLcode result; + + Curl_alpn_copy(&alpns, alpns_requested); + + octx->reused_session = FALSE; + + if((cf->sockindex == SECONDARYSOCKET) && !(cf->cft->flags & CF_TYPE_PROXY)) { + /* FTP is a bitch. On TLS secured transfers, it is a common server + * option to require the client to use the SAME TLS session as on + * the control connection or it fails the request. See #22225. */ + struct Curl_ssl_session *scs = + Curl_ssl_get_cf_session(data, cf->cft, FIRSTSOCKET); + if(scs) { + if(ossl_apply_session(octx, cf, data, &alpns, sess_reuse_cb, scs)) + CURL_TRC_CF(data, cf, "applied SSL session from control connection"); + } + } + + if(!octx->reused_session && + Curl_ssl_scache_use(cf, data) && !conn_cfg->verifystatus) { + struct Curl_ssl_session *scs = NULL; + + result = Curl_ssl_scache_take(cf, data, peer->scache_key, &scs); + if(!result && scs && scs->sdata && scs->sdata_len) { + (void)ossl_apply_session(octx, cf, data, &alpns, sess_reuse_cb, scs); + } + Curl_ssl_scache_return(cf, data, peer->scache_key, scs); + } + + if(alpns.count) { + struct alpn_proto_buf proto; + memset(&proto, 0, sizeof(proto)); + result = Curl_alpn_to_proto_buf(&proto, &alpns); + if(result) { + failf(data, "Error determining ALPN"); + return CURLE_SSL_CONNECT_ERROR; + } + if(SSL_set_alpn_protos(octx->ssl, proto.data, proto.len)) { + failf(data, "Error setting ALPN"); + return CURLE_SSL_CONNECT_ERROR; + } + } + + return CURLE_OK; +} + +#ifdef HAVE_SSL_SET1_ECH_CONFIG_LIST +bool Curl_ossl_need_httpsrr(struct Curl_easy *data) +{ + if(!CURLECH_ENABLED(data)) + return FALSE; + if((data->set.tls_ech == CURLECH_GREASE) || + CURL_EASY_STR(data, STRING_ECH_CONFIG)) + return FALSE; + return TRUE; +} + +static CURLcode ossl_init_ech(struct ossl_ctx *octx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer) +{ + const char *outername = CURL_EASY_STR(data, STRING_ECH_PUBLIC); + int trying_ech_now = 0; + + if(!CURLECH_ENABLED(data)) + return CURLE_OK; + + if(data->set.tls_ech == CURLECH_GREASE) { + infof(data, "ECH: will GREASE ClientHello"); +#ifdef HAVE_BORINGSSL_LIKE + SSL_set_enable_ech_grease(octx->ssl, 1); +#else + SSL_set_options(octx->ssl, SSL_OP_ECH_GREASE); +#endif + } + else if(data->set.tls_ech && CURL_EASY_STR(data, STRING_ECH_CONFIG)) { +#ifdef HAVE_BORINGSSL_LIKE + /* have to do base64 decode here for BoringSSL */ + const char *b64 = CURL_EASY_STR(data, STRING_ECH_CONFIG); + uint8_t *ech_config; + size_t ech_config_len = 0; + CURLcode result; + + if(!b64) { + infof(data, "ECH: ECHConfig from command line empty"); + return CURLE_SSL_CONNECT_ERROR; + } + ech_config_len = 2 * strlen(b64); + result = curlx_base64_decode(b64, &ech_config, &ech_config_len); + if(result || !ech_config) { + infof(data, "ECH: cannot base64 decode ECHConfig from command line"); + if(data->set.tls_ech == CURLECH_HARD) + return result; + } + if(SSL_set1_ech_config_list(octx->ssl, ech_config, ech_config_len) != 1) { + infof(data, "ECH: SSL_ECH_set1_ech_config_list failed"); + if(data->set.tls_ech == CURLECH_HARD) { + curlx_free(ech_config); + return CURLE_SSL_CONNECT_ERROR; + } + } + curlx_free(ech_config); + trying_ech_now = 1; +#else + const char *ech_config = CURL_EASY_STR(data, STRING_ECH_CONFIG); + size_t ech_config_len = 0; + if(!ech_config) { + infof(data, "ECH: ECHConfig from command line empty"); + return CURLE_SSL_CONNECT_ERROR; + } + ech_config_len = strlen(ech_config); + if(SSL_set1_ech_config_list(octx->ssl, + (const uint8_t *)ech_config, + ech_config_len) != 1) { + infof(data, "ECH: SSL_ECH_set1_ech_config_list failed"); + if(data->set.tls_ech == CURLECH_HARD) + return CURLE_SSL_CONNECT_ERROR; + } + else + trying_ech_now = 1; +#endif /* HAVE_BORINGSSL_LIKE */ + infof(data, "ECH: ECHConfig from command line"); + } + else { + const struct Curl_https_rrinfo *rinfo = + Curl_conn_dns_get_https(data, cf->sockindex, peer->origin); + + if(rinfo && rinfo->echconfiglist) { + const unsigned char *ecl = rinfo->echconfiglist; + size_t elen = rinfo->echconfiglist_len; + + infof(data, "ECH: ECHConfig from HTTPS RR"); + if(SSL_set1_ech_config_list(octx->ssl, ecl, elen) != 1) { + infof(data, "ECH: SSL_set1_ech_config_list failed"); + if(data->set.tls_ech == CURLECH_HARD) + return CURLE_SSL_CONNECT_ERROR; + } + else { + trying_ech_now = 1; + infof(data, "ECH: imported ECHConfigList of length %zu", elen); + } + } + else { + infof(data, "ECH: requested but no ECHConfig available"); + if(data->set.tls_ech == CURLECH_HARD) + return CURLE_SSL_CONNECT_ERROR; + } + } +#ifdef HAVE_BORINGSSL_LIKE + (void)peer; + if(trying_ech_now && outername) { + infof(data, "ECH: setting public_name not supported with BoringSSL"); + return CURLE_SSL_CONNECT_ERROR; + } +#else + if(trying_ech_now && outername) { + int ret; + infof(data, "ECH: inner: '%s', outer: '%s'", + peer->origin->hostname ? peer->origin->hostname : "NULL", outername); + ret = SSL_ech_set1_server_names(octx->ssl, + peer->origin->hostname, outername, + 0 /* do send outer */); + if(ret != 1) { + infof(data, "ECH: rv failed to set server name(s) %d [ERROR]", ret); + return CURLE_SSL_CONNECT_ERROR; + } + } +#endif /* HAVE_BORINGSSL_LIKE */ + if(trying_ech_now && + SSL_set_min_proto_version(octx->ssl, TLS1_3_VERSION) != 1) { + infof(data, "ECH: cannot force TLSv1.3 [ERROR]"); + return CURLE_SSL_CONNECT_ERROR; + } + + return CURLE_OK; +} +#else /* HAVE_SSL_SET1_ECH_CONFIG_LIST */ +bool Curl_ossl_need_httpsrr(struct Curl_easy *data) +{ + (void)data; + return FALSE; +} +#endif /* else HAVE_SSL_SET1_ECH_CONFIG_LIST */ + +static CURLcode ossl_init_ssl(struct ossl_ctx *octx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + const struct alpn_spec *alpns_requested, + void *ssl_user_data, + Curl_ossl_init_session_reuse_cb *sess_reuse_cb) +{ + /* Let's make an SSL structure */ + if(octx->ssl) + SSL_free(octx->ssl); + octx->ssl = SSL_new(octx->ssl_ctx); + if(!octx->ssl) { + failf(data, "SSL: could not create a context (handle)"); + return CURLE_OUT_OF_MEMORY; + } + + SSL_set_app_data(octx->ssl, ssl_user_data); + +#ifndef OPENSSL_NO_OCSP + if(Curl_ssl_cf_get_primary_config(cf)->verifystatus) + SSL_set_tlsext_status_type(octx->ssl, TLSEXT_STATUSTYPE_ocsp); +#endif + + SSL_set_connect_state(octx->ssl); + + if(peer->sni) { + if(!SSL_set_tlsext_host_name(octx->ssl, peer->sni)) { + failf(data, "Failed set SNI"); + return CURLE_SSL_CONNECT_ERROR; + } + } + +#ifdef HAVE_SSL_SET1_ECH_CONFIG_LIST + { + CURLcode result = ossl_init_ech(octx, cf, data, peer); + if(result) + return result; + } +#endif /* HAVE_SSL_SET1_ECH_CONFIG_LIST */ + + return ossl_init_session_and_alpns(octx, cf, data, peer, + alpns_requested, sess_reuse_cb); +} + +static CURLcode ossl_init_method(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + const SSL_METHOD **pmethod, + unsigned int *pssl_version_min) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + + *pmethod = NULL; + *pssl_version_min = conn_config->version; + DEBUGASSERT(conn_config->version != CURL_SSLVERSION_DEFAULT); + switch(peer->transport) { + case TRNSPRT_TCP: + /* check to see if we have been told to use an explicit SSL/TLS version */ + switch(*pssl_version_min) { + case CURL_SSLVERSION_TLSv1: + case CURL_SSLVERSION_TLSv1_0: + case CURL_SSLVERSION_TLSv1_1: + case CURL_SSLVERSION_TLSv1_2: + case CURL_SSLVERSION_TLSv1_3: + /* it is handled later with the context options */ + *pmethod = TLS_client_method(); + break; + case CURL_SSLVERSION_SSLv2: + failf(data, "No SSLv2 support"); + return CURLE_NOT_BUILT_IN; + case CURL_SSLVERSION_SSLv3: + failf(data, "No SSLv3 support"); + return CURLE_NOT_BUILT_IN; + default: + failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); + return CURLE_SSL_CONNECT_ERROR; + } + break; + case TRNSPRT_QUIC: + *pssl_version_min = CURL_SSLVERSION_TLSv1_3; + if(conn_config->version_max && + (conn_config->version_max != CURL_SSLVERSION_MAX_DEFAULT) && + (conn_config->version_max != CURL_SSLVERSION_MAX_TLSv1_3)) { + failf(data, "QUIC needs at least TLS version 1.3"); + return CURLE_SSL_CONNECT_ERROR; + } + + *pmethod = TLS_method(); + break; + default: + failf(data, "unsupported transport %d in SSL init", peer->transport); + return CURLE_SSL_CONNECT_ERROR; + } + + return *pmethod ? CURLE_OK : CURLE_SSL_CONNECT_ERROR; +} + +CURLcode Curl_ossl_ctx_init(struct ossl_ctx *octx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + const struct alpn_spec *alpns_requested, + Curl_ossl_ctx_setup_cb *cb_setup, + void *cb_user_data, + Curl_ossl_new_session_cb *cb_new_session, + void *ssl_user_data, + Curl_ossl_init_session_reuse_cb *sess_reuse_cb) +{ + CURLcode result = CURLE_OK; + const char *ciphers; + const SSL_METHOD *req_method = NULL; + ctx_option_t ctx_options = 0; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + char * const ssl_cert = ssl_config->primary.clientcert; + const struct curl_blob *ssl_cert_blob = ssl_config->primary.cert_blob; + const char * const ssl_cert_type = ssl_config->primary.cert_type; + unsigned int ssl_version_min; + char error_buffer[256]; + + /* Make funny stuff to get random input */ + result = ossl_seed(data); + if(result) + return result; + + ssl_config->certverifyresult = !X509_V_OK; + + result = ossl_init_method(cf, data, peer, &req_method, &ssl_version_min); + if(result) + return result; + DEBUGASSERT(req_method); + + DEBUGASSERT(!octx->ssl_ctx); + octx->ssl_ctx = +#ifdef OPENSSL_HAS_PROVIDERS + data->state.libctx ? + SSL_CTX_new_ex(data->state.libctx, data->state.propq, req_method): +#endif + SSL_CTX_new(req_method); + + if(!octx->ssl_ctx) { + failf(data, "SSL: could not create a context: %s", + ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer))); + return CURLE_OUT_OF_MEMORY; + } +#ifdef OPENSSL_HAS_PROVIDERS + if(data->state.libctx) + /* forbid connection reuse with provider/engine use */ + connclose(data->conn); +#endif + + if(cb_setup) { + result = cb_setup(cf, data, cb_user_data); + if(result) + return result; + } + + if(data->set.fdebug && data->set.verbose && + (peer->transport != TRNSPRT_QUIC)) { + /* the SSL trace callback is only used for verbose logging; + * QUIC connections use a different TLS record format that + * ossl_trace cannot handle */ + SSL_CTX_set_msg_callback(octx->ssl_ctx, ossl_trace); + SSL_CTX_set_msg_callback_arg(octx->ssl_ctx, cf); + } + + /* OpenSSL contains code to work around lots of bugs and flaws in various + SSL-implementations. SSL_CTX_set_options() is used to enable those + workarounds. The man page for this option states that SSL_OP_ALL enables + all the workarounds and that "It is usually safe to use SSL_OP_ALL to + enable the bug workaround options if compatibility with somewhat broken + implementations is desired." + + The "-no_ticket" option was introduced in OpenSSL 0.9.8j. it is a flag to + disable "rfc4507bis session ticket support". rfc4507bis was later turned + into the proper RFC5077: https://datatracker.ietf.org/doc/html/rfc5077 + + The enabled extension concerns the session management. I wonder how often + libcurl stops a connection and then resumes a TLS session. Also, sending + the session data is some overhead. I suggest that you use your proposed + patch (which explicitly disables TICKET). + + If someone writes an application with libcurl and OpenSSL who wants to + enable the feature, one can do this in the SSL callback. + + SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper + interoperability with web server Netscape Enterprise Server 2.0.1 which + was released back in 1996. + + Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has + become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate + CVE-2010-4180 when using previous OpenSSL versions we no longer enable + this option regardless of OpenSSL version and SSL_OP_ALL definition. + + OpenSSL added a workaround for an SSL 3.0/TLS 1.0 CBC vulnerability: + https://web.archive.org/web/20240114184648/openssl.org/~bodo/tls-cbc.txt. + In 0.9.6e they added a bit to SSL_OP_ALL that _disables_ that workaround + despite the fact that SSL_OP_ALL is documented to do "rather harmless" + workarounds. In order to keep the secure workaround, the + SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit must not be set. */ + + ctx_options = SSL_OP_ALL | SSL_OP_NO_TICKET | SSL_OP_NO_COMPRESSION; + + /* mitigate CVE-2010-4180 */ + ctx_options &= ~(ctx_option_t)SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; + + /* unless the user explicitly asks to allow the protocol vulnerability we + use the workaround */ + if(!ssl_config->enable_beast) + ctx_options &= ~(ctx_option_t)SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; + + DEBUGASSERT(ssl_version_min != CURL_SSLVERSION_DEFAULT); + switch(ssl_version_min) { + case CURL_SSLVERSION_SSLv2: + case CURL_SSLVERSION_SSLv3: + return CURLE_NOT_BUILT_IN; + + /* "--tlsv<x.y>" options mean TLS >= version <x.y> */ + case CURL_SSLVERSION_TLSv1: /* TLS >= version 1.0 */ + case CURL_SSLVERSION_TLSv1_0: /* TLS >= version 1.0 */ + case CURL_SSLVERSION_TLSv1_1: /* TLS >= version 1.1 */ + case CURL_SSLVERSION_TLSv1_2: /* TLS >= version 1.2 */ + case CURL_SSLVERSION_TLSv1_3: /* TLS >= version 1.3 */ + /* asking for any TLS version as the minimum, means no SSL versions + allowed */ + ctx_options |= SSL_OP_NO_SSLv2; + ctx_options |= SSL_OP_NO_SSLv3; + + result = ossl_set_ssl_version_min_max(cf, octx->ssl_ctx, ssl_version_min); + if(result) + return result; + break; + + default: + failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); + return CURLE_SSL_CONNECT_ERROR; + } + + SSL_CTX_set_options(octx->ssl_ctx, ctx_options); + SSL_CTX_set_read_ahead(octx->ssl_ctx, 1); + + /* Max TLS1.2 record size 0x4000 + 0x800. + OpenSSL supports processing "jumbo TLS record" (8 TLS records) in one go + for some algorithms, so match that here. + Experimentation shows that a slightly larger buffer is needed + to avoid short reads. + + However using a large buffer (8 packets) actually decreases performance. + 4 packets is better. + */ +#ifdef HAVE_SSL_CTX_SET_DEFAULT_READ_BUFFER_LEN + SSL_CTX_set_default_read_buffer_len(octx->ssl_ctx, 0x401e * 4); +#endif + + /* We do retry writes sometimes from another buffer address */ + SSL_CTX_set_mode(octx->ssl_ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); + + ciphers = conn_config->cipher_list; + if(!ciphers && (peer->transport != TRNSPRT_QUIC)) + ciphers = NULL; + if(ciphers && (ssl_version_min < CURL_SSLVERSION_TLSv1_3)) { + if(!SSL_CTX_set_cipher_list(octx->ssl_ctx, ciphers)) { + failf(data, "failed setting cipher list: %s", ciphers); + return CURLE_SSL_CIPHER; + } + infof(data, "Cipher selection: %s", ciphers); + } + +#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES + { + const char *ciphers13 = conn_config->cipher_list13; + if(ciphers13 && + (!conn_config->version_max || + (conn_config->version_max == CURL_SSLVERSION_MAX_DEFAULT) || + (conn_config->version_max >= CURL_SSLVERSION_MAX_TLSv1_3))) { + if(!SSL_CTX_set_ciphersuites(octx->ssl_ctx, ciphers13)) { + failf(data, "failed setting TLS 1.3 cipher suite: %s", ciphers13); + return CURLE_SSL_CIPHER; + } + infof(data, "TLS 1.3 cipher selection: %s", ciphers13); + } + } +#endif + + if(ssl_cert || ssl_cert_blob || ssl_cert_type) { + result = client_cert(data, octx->ssl_ctx, + ssl_cert, ssl_cert_blob, ssl_cert_type, + ssl_config->primary.key, ssl_config->primary.key_blob, + ssl_config->primary.key_type, + ssl_config->primary.key_passwd); + if(result) + /* failf() is already done in client_cert() */ + return result; + } + +#ifdef HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH + /* OpenSSL 1.1.1 requires clients to opt-in for PHA */ + SSL_CTX_set_post_handshake_auth(octx->ssl_ctx, 1); +#endif + + { + const char *curves = conn_config->curves; + if(curves) { +#ifdef HAVE_BORINGSSL_LIKE +#define OSSL_CURVE_CAST(x) (x) +#else +#define OSSL_CURVE_CAST(x) (char *)CURL_UNCONST(x) +#endif + if(!SSL_CTX_set1_curves_list(octx->ssl_ctx, OSSL_CURVE_CAST(curves))) { + failf(data, "failed setting curves list: '%s'", curves); + return CURLE_SSL_CIPHER; + } + } + } + +#ifdef HAVE_SSL_CTX_SET1_SIGALGS +#define OSSL_SIGALG_CAST(x) OSSL_CURVE_CAST(x) + { + const char *signature_algorithms = conn_config->signature_algorithms; + if(signature_algorithms) { + if(!SSL_CTX_set1_sigalgs_list(octx->ssl_ctx, + OSSL_SIGALG_CAST(signature_algorithms))) { + failf(data, "failed setting signature algorithms: '%s'", + signature_algorithms); + return CURLE_SSL_CIPHER; + } + } + } +#endif + + /* OpenSSL always tries to verify the peer. By setting the failure mode + * to NONE, we allow the connect to complete, regardless of the outcome. + * We then explicitly check the result and may try alternatives like + * Apple's SecTrust for verification. */ + SSL_CTX_set_verify(octx->ssl_ctx, SSL_VERIFY_NONE, NULL); + + /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */ +#if !defined(HAVE_KEYLOG_UPSTREAM) && defined(HAVE_KEYLOG_CALLBACK) + if(Curl_tls_keylog_enabled()) { + SSL_CTX_set_keylog_callback(octx->ssl_ctx, ossl_keylog_callback); + } +#endif + + if(cb_new_session) { + /* Enable the session cache because it is a prerequisite for the + * "new session" callback. Use the "external storage" mode to prevent + * OpenSSL from creating an internal session cache. + */ + SSL_CTX_set_session_cache_mode(octx->ssl_ctx, + SSL_SESS_CACHE_CLIENT | + SSL_SESS_CACHE_NO_INTERNAL); + SSL_CTX_sess_set_new_cb(octx->ssl_ctx, cb_new_session); + } + + /* give application a chance to interfere with SSL set up. */ + if(data->set.ssl.fsslctx) { + struct Curl_mapi_guard guard; + /* When a user callback is installed to modify the SSL_CTX, + * we need to do the full initialization before calling it. + * See: #11800 */ + if(!octx->x509_store_setup) { + result = Curl_ssl_setup_x509_store(cf, data, octx); + if(result) + return result; + octx->x509_store_setup = TRUE; + } + CURL_CBAPI_START(&guard, data, easy_fsslctx); + result = (*data->set.ssl.fsslctx)(data, octx->ssl_ctx, + data->set.ssl.fsslctxp); + CURL_CBAPI_END(&guard); + if(result) { + failf(data, "error signaled by SSL ctx callback"); + return result; + } + } + + return ossl_init_ssl(octx, cf, data, peer, alpns_requested, + ssl_user_data, sess_reuse_cb); +} + +static CURLcode ossl_on_session_reuse(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct alpn_spec *alpns, + struct Curl_ssl_session *scs, + bool *do_early_data) +{ + struct ssl_connect_data *connssl = cf->ctx; + + connssl->earlydata_max = scs->earlydata_max; + + return Curl_on_session_reuse(cf, data, alpns, scs, do_early_data, + connssl->earlydata_max); +} + +void Curl_ossl_report_handshake(struct Curl_easy *data, struct ossl_ctx *octx) +{ +#ifdef CURLVERBOSE + if(Curl_trc_is_verbose(data)) { + int psigtype_nid = NID_undef; + const char *negotiated_group_name = NULL; + +#ifdef HAVE_OPENSSL3 + SSL_get_peer_signature_type_nid(octx->ssl, &psigtype_nid); +#if OPENSSL_VERSION_NUMBER >= 0x30200000L + negotiated_group_name = SSL_get0_group_name(octx->ssl); +#else + negotiated_group_name = + OBJ_nid2sn(SSL_get_negotiated_group(octx->ssl) & 0x0000FFFF); +#endif +#endif + + /* Informational message */ + infof(data, "SSL connection using %s / %s / %s / %s", + SSL_get_version(octx->ssl), + SSL_get_cipher(octx->ssl), + negotiated_group_name ? negotiated_group_name : "[blank]", + OBJ_nid2sn(psigtype_nid)); + } +#else + (void)data; + (void)octx; +#endif /* CURLVERBOSE */ +} + +static CURLcode ossl_connect_step1(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + BIO *bio; + CURLcode result; + + DEBUGASSERT(connssl->connecting_state == ssl_connect_1); + DEBUGASSERT(octx); + DEBUGASSERT(connssl->peer.origin); + + result = Curl_ossl_ctx_init(octx, cf, data, &connssl->peer, + connssl->alpn, NULL, NULL, + ossl_new_session_cb, cf, + ossl_on_session_reuse); + if(result) + return result; + + octx->bio_method = ossl_bio_cf_method_create(); + if(!octx->bio_method) + return CURLE_OUT_OF_MEMORY; + bio = BIO_new(octx->bio_method); + if(!bio) + return CURLE_OUT_OF_MEMORY; + + BIO_set_data(bio, cf); +#ifdef HAVE_SSL_SET0_WBIO + /* with OpenSSL v1.1.1 we get an alternative to SSL_set_bio() that works + * without backward compat quirks. Every call takes one reference, so we + * up it and pass. SSL* then owns and frees it. + * We check on the function in configure, since LibreSSL and friends + * each have their own versions to add support for this. */ + BIO_up_ref(bio); + SSL_set0_rbio(octx->ssl, bio); + SSL_set0_wbio(octx->ssl, bio); +#else + SSL_set_bio(octx->ssl, bio, bio); +#endif + + if(connssl->alpn && (connssl->state != ssl_connection_deferred)) { + struct alpn_proto_buf proto; + memset(&proto, 0, sizeof(proto)); + Curl_alpn_to_proto_str(&proto, connssl->alpn); + infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); + } + + connssl->connecting_state = ssl_connect_2; + return CURLE_OK; +} + +#ifdef HAVE_SSL_SET1_ECH_CONFIG_LIST +/* If we have retry configs, then trace those out */ +static int ossl_trace_ech_retry_configs(struct Curl_easy *data, SSL *ssl, + int reason) +{ + CURLcode result = CURLE_OK; + size_t rcl = 0; + int rv = 1; +#ifndef HAVE_BORINGSSL_LIKE + char *inner = NULL; + uint8_t *rcs = NULL; + char *outer = NULL; +#else + const char *inner = NULL; + const uint8_t *rcs = NULL; + const char *outer = NULL; + size_t out_name_len = 0; + int servername_type = 0; +#endif + NOVERBOSE((void)reason); + + /* nothing to trace if not doing ECH */ + if(!CURLECH_ENABLED(data)) + return rv; +#ifndef HAVE_BORINGSSL_LIKE + rv = SSL_ech_get1_retry_config(ssl, &rcs, &rcl); +#else + SSL_get0_ech_retry_configs(ssl, &rcs, &rcl); + rv = (int)rcl; +#endif + + if(rv && rcs) { + char *b64str = NULL; + size_t blen = 0; + + result = curlx_base64_encode(rcs, rcl, &b64str, &blen); + if(!result && b64str) { + infof(data, "ECH: retry_configs %s", b64str); + curlx_free(b64str); +#ifndef HAVE_BORINGSSL_LIKE + rv = SSL_ech_get1_status(ssl, &inner, &outer); + infof(data, "ECH: retry_configs for %s from %s, %d %d", + inner ? inner : "NULL", outer ? outer : "NULL", reason, rv); +#else + rv = SSL_ech_accepted(ssl); + servername_type = SSL_get_servername_type(ssl); + inner = SSL_get_servername(ssl, servername_type); + SSL_get0_ech_name_override(ssl, &outer, &out_name_len); + infof(data, "ECH: retry_configs for %s from %s, %d %d", + inner ? inner : "NULL", outer ? outer : "NULL", reason, rv); +#endif + } + } + else + infof(data, "ECH: no retry_configs (rv = %d)", rv); +#ifndef HAVE_BORINGSSL_LIKE + OPENSSL_free(inner); + OPENSSL_free(rcs); + OPENSSL_free(outer); +#endif + return rv; +} + +#endif + +static CURLcode ossl_connect_step2(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + int err; + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + DEBUGASSERT(connssl->connecting_state == ssl_connect_2); + DEBUGASSERT(octx); + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + ERR_clear_error(); + + err = SSL_connect(octx->ssl); + + if(!octx->x509_store_setup) { + /* After having send off the ClientHello, we prepare the x509 + * store to verify the coming certificate from the server */ + CURLcode result = Curl_ssl_setup_x509_store(cf, data, octx); + if(result) + return result; + octx->x509_store_setup = TRUE; + } + +#if !defined(HAVE_KEYLOG_UPSTREAM) && !defined(HAVE_KEYLOG_CALLBACK) + /* If key logging is enabled, wait for the handshake to complete and then + * proceed with logging secrets (for TLS 1.2 or older). + */ + if(Curl_tls_keylog_enabled() && !octx->keylog_done) + ossl_log_tls12_secret(octx->ssl, &octx->keylog_done); +#endif + + /* 1 is fine + 0 is "not successful but was shut down controlled" + <0 is "handshake was not successful, because a fatal error occurred" */ + if(err != 1) { + int detail = SSL_get_error(octx->ssl, err); + CURL_TRC_CF(data, cf, "SSL_connect() -> err=%d, detail=%d", err, detail); + + if(detail == SSL_ERROR_WANT_READ) { + CURL_TRC_CF(data, cf, "SSL_connect() -> want recv"); + connssl->io_need = CURL_SSL_IO_NEED_RECV; + return CURLE_AGAIN; + } + if(detail == SSL_ERROR_WANT_WRITE) { + CURL_TRC_CF(data, cf, "SSL_connect() -> want send"); + connssl->io_need = CURL_SSL_IO_NEED_SEND; + return CURLE_AGAIN; + } +#ifdef SSL_ERROR_WANT_ASYNC + if(detail == SSL_ERROR_WANT_ASYNC) { + CURL_TRC_CF(data, cf, "SSL_connect() -> want async"); + connssl->io_need = CURL_SSL_IO_NEED_RECV; + return CURLE_AGAIN; + } +#endif +#ifdef SSL_ERROR_WANT_RETRY_VERIFY + if(detail == SSL_ERROR_WANT_RETRY_VERIFY) { + CURL_TRC_CF(data, cf, "SSL_connect() -> want retry_verify"); + Curl_xfer_pause_recv(data, TRUE); + return CURLE_AGAIN; + } +#endif + else { + /* untreated error */ + sslerr_t errdetail; + char error_buffer[256] = ""; + CURLcode result; + long lerr; + int lib; + int reason; + + /* the connection failed, we are not waiting for anything else. */ + connssl->connecting_state = ssl_connect_2; + + /* Get the earliest error code from the thread's error queue and remove + the entry. */ + errdetail = ERR_get_error(); + + /* Extract which lib and reason */ + lib = ERR_GET_LIB(errdetail); + reason = ERR_GET_REASON(errdetail); + + if((lib == ERR_LIB_SSL) && + ((reason == SSL_R_CERTIFICATE_VERIFY_FAILED) +/* Missing from OpenSSL 4+ OPENSSL_NO_DEPRECATED_3_0 builds */ +#ifdef SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED + || (reason == SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED) +#endif + )) { + result = CURLE_PEER_FAILED_VERIFICATION; + + lerr = SSL_get_verify_result(octx->ssl); + if(lerr != X509_V_OK) { + ssl_config->certverifyresult = lerr; + failf(data, "SSL certificate problem: %s", + X509_verify_cert_error_string(lerr)); + } + else + failf(data, "%s", "SSL certificate verification failed"); + } +#ifdef SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED + /* SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED is only available on + OpenSSL version above v1.1.1, not AWS-LC, BoringSSL, or LibreSSL */ + else if((lib == ERR_LIB_SSL) && + (reason == SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED)) { + /* If client certificate is required, communicate the + error to client */ + result = CURLE_SSL_CLIENTCERT; + failf(data, "TLS cert problem: %s", + ossl_strerror(errdetail, error_buffer, sizeof(error_buffer))); + } +#endif +#ifdef HAVE_SSL_SET1_ECH_CONFIG_LIST + else if((lib == ERR_LIB_SSL) && +#ifndef HAVE_BORINGSSL_LIKE + (reason == SSL_R_ECH_REQUIRED)) { +#else + (reason == SSL_R_ECH_REJECTED)) { +#endif /* HAVE_BORINGSSL_LIKE */ + + /* trace retry_configs if we got some */ + ossl_trace_ech_retry_configs(data, octx->ssl, reason); + + result = CURLE_ECH_REQUIRED; + failf(data, "ECH required: %s", + ossl_strerror(errdetail, error_buffer, sizeof(error_buffer))); + } +#endif + else { + result = CURLE_SSL_CONNECT_ERROR; + failf(data, "TLS connect error: %s", + ossl_strerror(errdetail, error_buffer, sizeof(error_buffer))); + } + + /* detail is already set to the SSL error above */ + + /* If we e.g. use SSLv2 request-method and the server does not like us + * (RST connection, etc.), OpenSSL gives no explanation whatsoever and + * the SO_ERROR is also lost. + */ + if(result == CURLE_SSL_CONNECT_ERROR && errdetail == 0) { + char extramsg[80] = ""; + int sockerr = SOCKERRNO; + + if(sockerr && detail == SSL_ERROR_SYSCALL) + curlx_strerror(sockerr, extramsg, sizeof(extramsg)); + failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%d ", + extramsg[0] ? extramsg : SSL_ERROR_to_str(detail), + connssl->peer.origin->hostname, connssl->peer.origin->port); + } + + return result; + } + } + else { + /* we connected fine, we are not waiting for anything else. */ + connssl->connecting_state = ssl_connect_3; + Curl_ossl_report_handshake(data, octx); + +#if defined(HAVE_SSL_SET1_ECH_CONFIG_LIST) && !defined(HAVE_BORINGSSL_LIKE) + if(CURLECH_ENABLED(data)) { + char *inner = NULL, *outer = NULL; + int rv; + VERBOSE(const char *status); + + rv = SSL_ech_get1_status(octx->ssl, &inner, &outer); + switch(rv) { + case SSL_ECH_STATUS_SUCCESS: + VERBOSE(status = "succeeded"); + break; + case SSL_ECH_STATUS_GREASE_ECH: + VERBOSE(status = "sent GREASE, got retry-configs"); + break; + case SSL_ECH_STATUS_GREASE: + VERBOSE(status = "sent GREASE"); + break; + case SSL_ECH_STATUS_NOT_TRIED: + VERBOSE(status = "not attempted"); + break; + case SSL_ECH_STATUS_NOT_CONFIGURED: + VERBOSE(status = "not configured"); + break; + case SSL_ECH_STATUS_BACKEND: + VERBOSE(status = "backend (unexpected)"); + break; + case SSL_ECH_STATUS_FAILED: + VERBOSE(status = "failed"); + break; + case SSL_ECH_STATUS_BAD_CALL: + VERBOSE(status = "bad call (unexpected)"); + break; + case SSL_ECH_STATUS_BAD_NAME: { + struct ssl_primary_config *conn_config = + Curl_ssl_cf_get_primary_config(cf); + if(!conn_config->verifypeer && !conn_config->verifyhost && + inner && !strcmp(inner, connssl->peer.origin->hostname)) { + VERBOSE(status = "bad name (tolerated without peer verification)"); + rv = SSL_ECH_STATUS_SUCCESS; + } + else { + VERBOSE(status = "bad name (unexpected)"); + } + break; + } + default: + VERBOSE(status = "unexpected status"); + infof(data, "ECH: unexpected status %d", rv); + } + infof(data, "ECH: result: status is %s, inner is %s, outer is %s", + (status ? status : "NULL"), + (inner ? inner : "NULL"), + (outer ? outer : "NULL")); + OPENSSL_free(inner); + OPENSSL_free(outer); + if(rv == SSL_ECH_STATUS_GREASE_ECH) { + /* trace retry_configs if we got some */ + ossl_trace_ech_retry_configs(data, octx->ssl, 0); + } + if(rv != SSL_ECH_STATUS_SUCCESS && (data->set.tls_ech == CURLECH_HARD)) { + infof(data, "ECH: ech-hard failed"); + return CURLE_SSL_CONNECT_ERROR; + } + } + else { + infof(data, "ECH: result: status is not attempted"); + } +#endif /* HAVE_SSL_SET1_ECH_CONFIG_LIST && !HAVE_BORINGSSL_LIKE */ + + /* Sets data and len to negotiated protocol, len is 0 if no protocol was + * negotiated + */ + if(connssl->alpn) { + const unsigned char *neg_protocol; + unsigned int len; + SSL_get0_alpn_selected(octx->ssl, &neg_protocol, &len); + + return Curl_alpn_set_negotiated(cf, data, connssl, neg_protocol, len); + } + + return CURLE_OK; + } +} + +/* + * Heavily modified from: + * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL + */ +static CURLcode ossl_pkp_pin_peer_pubkey(struct Curl_easy *data, X509 *cert, + const char *pinnedpubkey) +{ + /* Scratch */ + int len1 = 0, len2 = 0; + unsigned char *buff1 = NULL, *temp = NULL; + + /* Result is returned to caller */ + CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; + + /* if a path was not specified, do not pin */ + if(!pinnedpubkey) + return CURLE_OK; + + if(!cert) + return result; + + do { + /* Get the subjectPublicKeyInfo */ + /* https://groups.google.com/group/mailing.openssl.users/browse_thread/thread/d61858dae102c6c7 */ + len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL); + if(len1 < 1) + break; /* failed */ + + buff1 = temp = curlx_malloc(len1); + if(!buff1) + break; /* failed */ + + /* https://docs.openssl.org/master/man3/d2i_X509/ */ + len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp); + + /* + * These checks are verifying we got back the same values as when we + * sized the buffer. it is pretty weak since they should always be the + * same, but it gives us something to test. + */ + if((len1 != len2) || !temp || ((temp - buff1) != len1)) + break; /* failed */ + + /* End Gyrations */ + + /* The one good exit point */ + result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1); + } while(0); + + if(buff1) + curlx_free(buff1); + + return result; +} + +#ifdef CURLVERBOSE +#if !defined(HAVE_BORINGSSL_LIKE) && \ + !(defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x3060000fL) +static void infof_certstack(struct Curl_easy *data, const SSL *ssl) +{ + STACK_OF(X509) *certstack; + long verify_result; + int num_cert_levels; + int cert_level; + + if(!Curl_trc_is_verbose(data)) + return; + + verify_result = SSL_get_verify_result(ssl); + if(verify_result != X509_V_OK) + certstack = SSL_get_peer_cert_chain(ssl); + else + certstack = SSL_get0_verified_chain(ssl); + if(!certstack) + return; + num_cert_levels = sk_X509_num(certstack); + + for(cert_level = 0; cert_level < num_cert_levels; cert_level++) { + char cert_algorithm[80] = ""; + char group_name_final[80] = ""; + const X509_ALGOR *palg_cert = NULL; + const ASN1_OBJECT *paobj_cert = NULL; + X509 *current_cert; + EVP_PKEY *current_pkey; + int key_bits; + int key_sec_bits; + int get_group_name; + const char *type_name; + + current_cert = sk_X509_value(certstack, cert_level); + if(!current_cert) + continue; + + current_pkey = X509_get0_pubkey(current_cert); + if(!current_pkey) + continue; + + X509_get0_signature(NULL, &palg_cert, current_cert); + X509_ALGOR_get0(&paobj_cert, NULL, NULL, palg_cert); + OBJ_obj2txt(cert_algorithm, sizeof(cert_algorithm), paobj_cert, 0); + + key_bits = EVP_PKEY_bits(current_pkey); +#ifndef HAVE_OPENSSL3 +#define EVP_PKEY_get_security_bits EVP_PKEY_security_bits +#endif + key_sec_bits = EVP_PKEY_get_security_bits(current_pkey); +#ifdef HAVE_OPENSSL3 + { + char group_name[80] = ""; + get_group_name = EVP_PKEY_get_group_name(current_pkey, group_name, + sizeof(group_name), NULL); + curl_msnprintf(group_name_final, sizeof(group_name_final), "/%s", + group_name); + } + type_name = EVP_PKEY_get0_type_name(current_pkey); +#else + get_group_name = 0; + type_name = NULL; +#endif + + infof(data, " Certificate level %d: " + "Public key type %s%s (%d/%d Bits/secBits), signed using %s", + cert_level, type_name ? type_name : "?", + get_group_name == 0 ? "" : group_name_final, + key_bits, key_sec_bits, cert_algorithm); + } +} +#else +#define infof_certstack(data, ssl) +#endif +#endif /* CURLVERBOSE */ + +static CURLcode ossl_check_issuer(struct Curl_cfilter *cf, + struct Curl_easy *data, + X509 *server_cert) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + X509 *issuer = NULL; + BIO *fp = NULL; + char err_buf[256] = ""; + bool verify_enabled = (conn_config->verifypeer || conn_config->verifyhost); + CURLcode result = CURLE_OK; + + /* e.g. match issuer name with provided issuer certificate */ + if(conn_config->issuercert_blob) { + fp = BIO_new_mem_buf(conn_config->issuercert_blob->data, + (int)conn_config->issuercert_blob->len); + if(!fp) { + failf(data, "BIO_new_mem_buf NULL, " OSSL_PACKAGE " error %s", + ossl_strerror(ERR_get_error(), err_buf, sizeof(err_buf))); + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + else if(conn_config->issuercert) { + fp = BIO_new(BIO_s_file()); + if(!fp) { + failf(data, "BIO_new return NULL, " OSSL_PACKAGE " error %s", + ossl_strerror(ERR_get_error(), err_buf, sizeof(err_buf))); + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + if(BIO_read_filename(fp, conn_config->issuercert) <= 0) { + if(verify_enabled) + failf(data, "SSL: Unable to open issuer cert (%s)", + conn_config->issuercert); + result = CURLE_SSL_ISSUER_ERROR; + goto out; + } + } + + if(fp) { + issuer = PEM_read_bio_X509(fp, NULL, ZERO_NULL, NULL); + if(!issuer) { + if(verify_enabled) + failf(data, "SSL: Unable to read issuer cert (%s)", + conn_config->issuercert); + result = CURLE_SSL_ISSUER_ERROR; + goto out; + } + + if(X509_check_issued(issuer, server_cert) != X509_V_OK) { + if(verify_enabled) + failf(data, "SSL: Certificate issuer check failed (%s)", + conn_config->issuercert); + result = CURLE_SSL_ISSUER_ERROR; + goto out; + } + + infof(data, " SSL certificate issuer check ok (%s)", + conn_config->issuercert); + } + +out: + if(fp) + BIO_free(fp); + if(issuer) + X509_free(issuer); + return result; +} + +static const char *pinned(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + (void)cf; + return +#ifndef CURL_DISABLE_PROXY + Curl_ssl_cf_is_proxy(cf) ? + CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY_PROXY) : +#endif + CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY); +} + +static CURLcode ossl_check_pinned_key(struct Curl_cfilter *cf, + struct Curl_easy *data, + X509 *server_cert) +{ + CURLcode result = CURLE_OK; + const char *ptr = pinned(cf, data); + if(ptr) { + result = ossl_pkp_pin_peer_pubkey(data, server_cert, ptr); + if(result) + failf(data, "SSL: public key does not match pinned public key"); + } + return result; +} + +#ifdef CURLVERBOSE +#define MAX_CERT_NAME_LENGTH 2048 +static CURLcode ossl_infof_cert(struct Curl_cfilter *cf, + struct Curl_easy *data, + X509 *server_cert) +{ + BIO *mem = NULL; + struct dynbuf dname; + char err_buf[256] = ""; + char *buf; + long len; + CURLcode result = CURLE_OK; + + if(!Curl_trc_is_verbose(data)) + return CURLE_OK; + + curlx_dyn_init(&dname, MAX_CERT_NAME_LENGTH); + mem = BIO_new(BIO_s_mem()); + if(!mem) { + failf(data, "BIO_new return NULL, " OSSL_PACKAGE " error %s", + ossl_strerror(ERR_get_error(), err_buf, sizeof(err_buf))); + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + infof(data, "%s certificate:", Curl_ssl_cf_is_proxy(cf) ? + "Proxy" : "Server"); + + result = x509_name_oneline(X509_get_subject_name(server_cert), &dname); + infof(data, " subject: %s", result ? "[NONE]" : curlx_dyn_ptr(&dname)); + + ASN1_TIME_print(mem, X509_get0_notBefore(server_cert)); + len = BIO_get_mem_data(mem, (char **)&buf); + infof(data, " start date: %.*s", (int)len, buf); + (void)BIO_reset(mem); + + ASN1_TIME_print(mem, X509_get0_notAfter(server_cert)); + len = BIO_get_mem_data(mem, (char **)&buf); + infof(data, " expire date: %.*s", (int)len, buf); + (void)BIO_reset(mem); + + result = x509_name_oneline(X509_get_issuer_name(server_cert), &dname); + if(result) /* should be only fatal stuff like OOM */ + goto out; + infof(data, " issuer: %s", curlx_dyn_ptr(&dname)); + +out: + BIO_free(mem); + curlx_dyn_free(&dname); + return result; +} +#endif /* CURLVERBOSE */ + +#ifdef USE_APPLE_SECTRUST +struct ossl_certs_ctx { + STACK_OF(X509) *sk; + size_t num_certs; + unsigned char *last_der; +}; + +static CURLcode ossl_chain_get_der(struct Curl_cfilter *cf, + struct Curl_easy *data, + void *user_data, + size_t i, + unsigned char **pder, + size_t *pder_len) +{ + struct ossl_certs_ctx *chain = user_data; + X509 *cert; + int der_len; + + OPENSSL_free(chain->last_der); + chain->last_der = NULL; + + (void)cf; + (void)data; + *pder_len = 0; + *pder = NULL; + + if(i >= chain->num_certs) + return CURLE_TOO_LARGE; + cert = sk_X509_value(chain->sk, (int)i); + if(!cert) + return CURLE_FAILED_INIT; + der_len = i2d_X509(cert, pder); + if(der_len < 0) + return CURLE_FAILED_INIT; + chain->last_der = *pder; + *pder_len = (size_t)der_len; + return CURLE_OK; +} + +static CURLcode ossl_apple_verify(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ossl_ctx *octx, + struct ssl_peer *peer) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ossl_certs_ctx chain; + CURLcode result; + + octx->sectrust_verified = FALSE; + memset(&chain, 0, sizeof(chain)); + chain.sk = SSL_get_peer_cert_chain(octx->ssl); + chain.num_certs = chain.sk ? sk_X509_num(chain.sk) : 0; + + if(!chain.num_certs && + (conn_config->verifypeer || conn_config->verifyhost)) { + if(!octx->reused_session) { + failf(data, "SSL: could not get peer certificate chain"); + result = CURLE_PEER_FAILED_VERIFICATION; + } + else { + /* When session was reused, there is no peer cert chain. + * We trust it if it came from a SecTrust verified TLS. */ + CURL_TRC_CF(data, cf, "session reused, sectrust_session=%d", + octx->sectrust_session); + octx->sectrust_verified = (bool)octx->sectrust_session; + return CURLE_OK; + } + } + else { +#ifdef HAVE_BORINGSSL_LIKE + const uint8_t *ocsp_data = NULL; +#else + unsigned char *ocsp_data = NULL; +#endif + long ocsp_len = 0; + bool ocsp_missing = FALSE; + if(conn_config->verifystatus && !octx->reused_session) + ocsp_len = (long)SSL_get_tlsext_status_ocsp_resp(octx->ssl, &ocsp_data); + + /* SSL_get_tlsext_status_ocsp_resp() returns the length of the OCSP + response data or -1 if there is no OCSP response data. + AWS-LC breaks the API and returns 0 when there is no data. */ + if(ocsp_len <= 0) { + ocsp_len = 0; /* no data available */ + ocsp_missing = TRUE; + } + result = Curl_vtls_apple_verify(cf, data, peer, chain.num_certs, + ossl_chain_get_der, &chain, + ocsp_data, ocsp_len); + OPENSSL_free(chain.last_der); + chain.last_der = NULL; + if(!result && ocsp_missing && conn_config->verifystatus && + !octx->reused_session) { + /* verified, but OCSP stapling is required and server sent none */ + octx->sectrust_verified = TRUE; + failf(data, "No OCSP response received"); + return CURLE_SSL_INVALIDCERTSTATUS; + } + } + octx->sectrust_verified = !result; + return result; +} +#endif /* USE_APPLE_SECTRUST */ + +CURLcode Curl_ossl_check_peer_cert(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ossl_ctx *octx, + struct ssl_peer *peer) +{ + struct connectdata *conn = cf->conn; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + CURLcode result = CURLE_OK; + long ossl_verify; + X509 *server_cert; + bool verified = FALSE; + + if(data->set.ssl.certinfo && !octx->reused_session) { + /* asked to gather certificate info. Reused sessions do not have cert + chains */ + result = ossl_certchain(data, octx->ssl); + if(result) + return result; + } + + server_cert = SSL_get1_peer_certificate(octx->ssl); + if(!server_cert) { + /* no verification at all, this maybe acceptable */ + if(!(conn_config->verifypeer || conn_config->verifyhost) && + !pinned(cf, data)) + goto out; + + failf(data, "SSL: could not get peer certificate"); + result = CURLE_PEER_FAILED_VERIFICATION; + goto out; + } + +#ifdef CURLVERBOSE + result = ossl_infof_cert(cf, data, server_cert); + if(result) + goto out; + infof_certstack(data, octx->ssl); +#endif + + if(conn_config->verifyhost) { + result = ossl_verifyhost(data, conn, peer, server_cert); + if(result) + goto out; + } + /* `verifyhost` is either OK or not requested from here on */ + + ossl_verify = SSL_get_verify_result(octx->ssl); + ssl_config->certverifyresult = ossl_verify; + infof(data, "OpenSSL verify result: %lx", (unsigned long)ossl_verify); + + verified = (ossl_verify == X509_V_OK); + if(verified) + infof(data, "SSL certificate verified via OpenSSL."); + +#ifdef USE_APPLE_SECTRUST + if(!verified && conn_config->verifypeer && conn_config->native_ca_store) { + /* we verify using Apple SecTrust *unless* OpenSSL already verified. + * This may happen if the application intercepted the OpenSSL callback + * and installed its own. */ + result = ossl_apple_verify(cf, data, octx, peer); + if(result && (result != CURLE_PEER_FAILED_VERIFICATION)) + goto out; /* unexpected error */ + if(octx->sectrust_verified) { + infof(data, "SSL certificate verified via Apple SecTrust."); + ssl_config->certverifyresult = X509_V_OK; + verified = TRUE; + } + } +#endif + + if(!verified) { + /* no trust established, report the OpenSSL status */ + if(conn_config->verifypeer) { + failf(data, "SSL certificate OpenSSL verify result: %s (%ld)", + X509_verify_cert_error_string(ossl_verify), ossl_verify); + result = CURLE_PEER_FAILED_VERIFICATION; + goto out; + } + infof(data, " SSL certificate verification failed, continuing anyway!"); + } + +#ifndef OPENSSL_NO_OCSP + if(conn_config->verifystatus && +#ifdef USE_APPLE_SECTRUST + !octx->sectrust_verified && /* already verified via sectrust, cannot + * verifystate via OpenSSL in that case as it + * does not have the trust anchors */ +#endif + !octx->reused_session) { + /* do not do this after Session ID reuse */ + result = verifystatus(cf, data, octx); + if(result) + goto out; + } +#endif + + result = ossl_check_issuer(cf, data, server_cert); + if(result) + goto out; + + result = ossl_check_pinned_key(cf, data, server_cert); + +out: + X509_free(server_cert); + return result; +} + +static CURLcode ossl_connect_step3(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + + DEBUGASSERT(connssl->connecting_state == ssl_connect_3); + + /* + * We check certificates to authenticate the server; otherwise we risk + * man-in-the-middle attack; NEVERTHELESS, if we are told explicitly not to + * verify the peer, ignore faults and failures from the server cert + * operations. + */ + + result = Curl_ossl_check_peer_cert(cf, data, octx, &connssl->peer); + if(result) + /* on error, remove sessions we might have in the pool */ + Curl_ssl_scache_remove_all(cf, data, connssl->peer.scache_key); + + return result; +} + +#ifdef HAVE_OPENSSL_EARLYDATA +static CURLcode ossl_send_earlydata(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + CURLcode result = CURLE_OK; + const unsigned char *buf; + size_t blen, nwritten; + int rc; + + DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sending); + octx->io_result = CURLE_OK; + while(Curl_bufq_peek(&connssl->earlydata, &buf, &blen)) { + nwritten = 0; + rc = SSL_write_early_data(octx->ssl, buf, blen, &nwritten); + CURL_TRC_CF(data, cf, "SSL_write_early_data(len=%zu) -> %d, %zu", + blen, rc, nwritten); + if(rc <= 0) { + long sslerror; + char error_buffer[256]; + int err = SSL_get_error(octx->ssl, rc); + + switch(err) { + case SSL_ERROR_WANT_READ: + connssl->io_need = CURL_SSL_IO_NEED_RECV; + result = CURLE_AGAIN; + goto out; + case SSL_ERROR_WANT_WRITE: + connssl->io_need = CURL_SSL_IO_NEED_SEND; + result = CURLE_AGAIN; + goto out; + case SSL_ERROR_SYSCALL: { + int sockerr = SOCKERRNO; + + if(octx->io_result == CURLE_AGAIN) { + result = CURLE_AGAIN; + goto out; + } + sslerror = ERR_get_error(); + if(sslerror) + ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)); + else if(sockerr) + curlx_strerror(sockerr, error_buffer, sizeof(error_buffer)); + else + curl_msnprintf(error_buffer, sizeof(error_buffer), "%s", + SSL_ERROR_to_str(err)); + + failf(data, OSSL_PACKAGE " SSL_write:early_data: %s, errno %d", + error_buffer, sockerr); + result = CURLE_SEND_ERROR; + goto out; + } + case SSL_ERROR_SSL: { + /* A failure in the SSL library occurred, usually a protocol error. + The OpenSSL error queue contains more information on the error. */ + sslerror = ERR_get_error(); + failf(data, "SSL_write_early_data() error: %s", + ossl_strerror(sslerror, error_buffer, sizeof(error_buffer))); + result = CURLE_SEND_ERROR; + goto out; + } + default: + /* a true error */ + failf(data, OSSL_PACKAGE " SSL_write_early_data: %s, errno %d", + SSL_ERROR_to_str(err), SOCKERRNO); + result = CURLE_SEND_ERROR; + goto out; + } + } + Curl_bufq_skip(&connssl->earlydata, nwritten); + } + /* sent everything there was */ + infof(data, "SSL sending %zu bytes of early data", connssl->earlydata_skip); +out: + return result; +} +#endif /* HAVE_OPENSSL_EARLYDATA */ + +static CURLcode ossl_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + CURLcode result = CURLE_OK; + struct ssl_connect_data *connssl = cf->ctx; + + /* check if the connection has already been established */ + if(ssl_connection_complete == connssl->state) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; + connssl->io_need = CURL_SSL_IO_NEED_NONE; + + if(connssl->connecting_state == ssl_connect_1) { + if(Curl_ossl_need_httpsrr(data) && + !Curl_conn_dns_resolved_https(data, cf->sockindex, + connssl->peer.peer)) { + CURL_TRC_CF(data, cf, "need HTTPS-RR, delaying connect"); + return CURLE_OK; + } + CURL_TRC_CF(data, cf, "ossl_connect, step1"); + result = ossl_connect_step1(cf, data); + if(result) + goto out; + } + + if(connssl->connecting_state == ssl_connect_2) { + CURL_TRC_CF(data, cf, "ossl_connect, step2"); +#ifdef HAVE_OPENSSL_EARLYDATA + if(connssl->earlydata_state == ssl_earlydata_await) { + goto out; + } + else if(connssl->earlydata_state == ssl_earlydata_sending) { + result = ossl_send_earlydata(cf, data); + if(result) + goto out; + connssl->earlydata_state = ssl_earlydata_sent; + } +#endif + DEBUGASSERT((connssl->earlydata_state == ssl_earlydata_none) || + (connssl->earlydata_state == ssl_earlydata_sent)); + + result = ossl_connect_step2(cf, data); + if(result) + goto out; + } + + if(connssl->connecting_state == ssl_connect_3) { + CURL_TRC_CF(data, cf, "ossl_connect, step3"); + result = ossl_connect_step3(cf, data); + if(result) + goto out; + connssl->connecting_state = ssl_connect_done; +#ifdef HAVE_OPENSSL_EARLYDATA + if(connssl->earlydata_state > ssl_earlydata_none) { + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + /* We should be in this state by now */ + DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sent); + connssl->earlydata_state = + (SSL_get_early_data_status(octx->ssl) == SSL_EARLY_DATA_ACCEPTED) ? + ssl_earlydata_accepted : ssl_earlydata_rejected; + } +#endif + } + + if(connssl->connecting_state == ssl_connect_done) { + CURL_TRC_CF(data, cf, "ossl_connect, done"); + connssl->state = ssl_connection_complete; + } + +out: + if(result == CURLE_AGAIN) { + *done = FALSE; + return CURLE_OK; + } + *done = ((connssl->state == ssl_connection_complete) || + (connssl->state == ssl_connection_deferred)); + return result; +} + +static bool ossl_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + (void)data; + return (bool)connssl->input_pending; +} + +static CURLcode ossl_send(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *mem, + size_t len, + size_t *pnwritten) +{ + /* SSL_write() is said to return 'int' while write() and send() returns + 'size_t' */ + int err; + char error_buffer[256]; + sslerr_t sslerror; + int memlen; + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + CURLcode result = CURLE_OK; + int nwritten; + + DEBUGASSERT(octx); + *pnwritten = 0; + ERR_clear_error(); + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len; + if(octx->blocked_ssl_write_len && (octx->blocked_ssl_write_len != memlen)) { + /* The previous SSL_write() call was blocked, using that length. + * We need to use that again or OpenSSL freaks out. A shorter + * length should not happen and is a bug in libcurl. */ + if(octx->blocked_ssl_write_len > memlen) { + DEBUGASSERT(0); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + memlen = octx->blocked_ssl_write_len; + } + octx->blocked_ssl_write_len = 0; + nwritten = SSL_write(octx->ssl, mem, memlen); + + if(nwritten > 0) + *pnwritten = (size_t)nwritten; + else { + err = SSL_get_error(octx->ssl, nwritten); + + switch(err) { + case SSL_ERROR_WANT_READ: + connssl->io_need = CURL_SSL_IO_NEED_RECV; + octx->blocked_ssl_write_len = memlen; + result = CURLE_AGAIN; + goto out; + case SSL_ERROR_WANT_WRITE: + result = CURLE_AGAIN; + octx->blocked_ssl_write_len = memlen; + goto out; + case SSL_ERROR_SYSCALL: { + int sockerr = SOCKERRNO; + + if(octx->io_result == CURLE_AGAIN) { + octx->blocked_ssl_write_len = memlen; + result = CURLE_AGAIN; + goto out; + } + sslerror = ERR_get_error(); + if(sslerror) + ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)); + else if(sockerr) + curlx_strerror(sockerr, error_buffer, sizeof(error_buffer)); + else + curl_msnprintf(error_buffer, sizeof(error_buffer), "%s", + SSL_ERROR_to_str(err)); + + failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d", + error_buffer, sockerr); + result = CURLE_SEND_ERROR; + goto out; + } + case SSL_ERROR_SSL: { + /* A failure in the SSL library occurred, usually a protocol error. + The OpenSSL error queue contains more information on the error. */ + sslerror = ERR_get_error(); + failf(data, "SSL_write() error: %s", + ossl_strerror(sslerror, error_buffer, sizeof(error_buffer))); + result = CURLE_SEND_ERROR; + goto out; + } + default: + /* a true error */ + failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d", + SSL_ERROR_to_str(err), SOCKERRNO); + result = CURLE_SEND_ERROR; + goto out; + } + } + +out: + return result; +} + +static CURLcode ossl_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, /* transfer */ + char *buf, /* store read data here */ + size_t buffersize, /* max amount to read */ + size_t *pnread) +{ + char error_buffer[256]; + unsigned long sslerror; + int buffsize; + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + CURLcode result = CURLE_OK; + int nread; + + DEBUGASSERT(octx); + + *pnread = 0; + ERR_clear_error(); + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize; + nread = SSL_read(octx->ssl, buf, buffsize); + + if(nread > 0) + *pnread = (size_t)nread; + else { + /* failed SSL_read */ + int err = SSL_get_error(octx->ssl, nread); + + switch(err) { + case SSL_ERROR_NONE: /* this is not an error */ + break; + case SSL_ERROR_ZERO_RETURN: /* no more data */ + /* close_notify alert */ + if(cf->sockindex == FIRSTSOCKET) + /* mark the connection for close if it is indeed the control + connection */ + CURL_TRC_CF(data, cf, "TLS close_notify"); + break; + case SSL_ERROR_WANT_READ: + connssl->io_need = CURL_SSL_IO_NEED_RECV; + result = CURLE_AGAIN; + goto out; + case SSL_ERROR_WANT_WRITE: + connssl->io_need = CURL_SSL_IO_NEED_SEND; + result = CURLE_AGAIN; + goto out; + default: + /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return + value/errno" */ + /* https://docs.openssl.org/master/man3/ERR_get_error/ */ + if(octx->io_result == CURLE_AGAIN) { + result = CURLE_AGAIN; + goto out; + } + sslerror = ERR_get_error(); + if((nread < 0) || sslerror) { + /* If the return code was negative or there actually is an error in the + queue */ + int sockerr = SOCKERRNO; + if(sslerror) + ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)); + else if(sockerr && err == SSL_ERROR_SYSCALL) + curlx_strerror(sockerr, error_buffer, sizeof(error_buffer)); + else + curl_msnprintf(error_buffer, sizeof(error_buffer), "%s", + SSL_ERROR_to_str(err)); + failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d", + error_buffer, sockerr); + result = CURLE_RECV_ERROR; + goto out; + } + else if(err == SSL_ERROR_SYSCALL) { + if(octx->io_result) { + /* logging handling in underlying filter already */ + result = octx->io_result; + } + else if(connssl->peer_closed) { + failf(data, "Connection closed abruptly"); + result = CURLE_RECV_ERROR; + } + else { + /* We should no longer get here nowadays, but handle + * the error in case of some weirdness in the OSSL stack */ + int sockerr = SOCKERRNO; + if(sockerr) + curlx_strerror(sockerr, error_buffer, sizeof(error_buffer)); + else { + curl_msnprintf(error_buffer, sizeof(error_buffer), + "Connection closed abruptly"); + } + failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d", + error_buffer, sockerr); + result = CURLE_RECV_ERROR; + } + goto out; + } + } + } + +out: + if((!result && !*pnread) || (result == CURLE_AGAIN)) { + /* This happens when: + * - we read an EOF + * - OpenSSLs buffers are empty, there is no more data + * - OpenSSL read is blocked on writing something first + * - an incomplete TLS packet is buffered that cannot be read + * until more data arrives */ + connssl->input_pending = FALSE; + } + CURL_TRC_CF(data, cf, "ossl_recv(len=%zu) -> %d, %zu (in_pending=%d)", + buffersize, (int)result, *pnread, connssl->input_pending); + return result; +} + +static CURLcode ossl_get_channel_binding(struct Curl_easy *data, + int8_t sockindex, + struct dynbuf *binding) +{ + X509 *cert; + int mdnid; + bool no_digest_acceptable = FALSE; + const EVP_MD *algo_type = NULL; + const char *algo_name = NULL; + unsigned int length; + unsigned char buf[EVP_MAX_MD_SIZE]; + + static const char prefix[] = "tls-server-end-point:"; + struct connectdata *conn = data->conn; + struct Curl_cfilter *cf = conn->cfilter[sockindex]; + struct ossl_ctx *octx = NULL; + CURLcode result = CURLE_OK; + + do { + const struct Curl_cftype *cft = cf->cft; + struct ssl_connect_data *connssl = cf->ctx; + + if(cft->name && !strcmp(cft->name, "SSL")) { + octx = (struct ossl_ctx *)connssl->backend; + break; + } + + cf = cf->next; + } while(cf); + + if(!octx) { + failf(data, "Failed to find the SSL filter"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + cert = SSL_get1_peer_certificate(octx->ssl); + if(!cert) + /* No server certificate, do not do channel binding */ + return CURLE_OK; + +#ifdef HAVE_OPENSSL3 + { + int pknid, secbits; + uint32_t flags; + EVP_PKEY *pkey = X509_get0_pubkey(cert); + + if(!X509_get_signature_info(cert, &mdnid, &pknid, &secbits, &flags)) { + failf(data, "certificate signature algorithm not recognized"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto out; + } + + if(mdnid != NID_undef) { + if(mdnid == NID_md5 || mdnid == NID_sha1) { + algo_type = EVP_sha256(); + } + else + algo_type = EVP_get_digestbynid(mdnid); + } + else if(pkey && !EVP_PKEY_is_a(pkey, OBJ_nid2sn(pknid))) { + /* The cert's pkey is different from the algorithm used to sign + * the certificate. Since the reported `mdnid` is undefined, there + * is no digest algorithm available here. This happens in PQC + * and is accepted, resulting in no addition to the binding. */ + no_digest_acceptable = TRUE; + } + else if(pkey) { + /* cert's pkey type is the same as the cert signer (or same family). + * Ask for the mandatory/advisory digest algorithm for the pkey. + */ + char mdname[128] = ""; + int rc = EVP_PKEY_get_default_digest_name(pkey, mdname, sizeof(mdname)); + bool md_is_undef = !strcmp(mdname, "UNDEF"); + + if(rc == 2 && md_is_undef) { + /* OpenSSL declares "undef" the *mandatory* digest for this key. + * This is some PQC shit, accept it, no addition to binding. */ + no_digest_acceptable = TRUE; + } + else if(rc > 0 && mdname[0] != '\0' && !md_is_undef) { + infof(data, "Digest algorithm : %s%s (derived from public key)" + ", but unavailable", + mdname, rc == 2 ? " [mandatory]" : " [advisory]"); + } + } + } +#else /* HAVE_OPENSSL3 */ + + if(!OBJ_find_sigid_algs(X509_get_signature_nid(cert), &mdnid, NULL)) { + failf(data, + "Unable to find digest NID for certificate signature algorithm"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto out; + } + + /* https://datatracker.ietf.org/doc/html/rfc5929#section-4.1 */ + if(mdnid == NID_md5 || mdnid == NID_sha1) { + algo_type = EVP_sha256(); + } + else { + algo_type = EVP_get_digestbynid(mdnid); + if(!algo_type) { + algo_name = OBJ_nid2sn(mdnid); + failf(data, "Could not find digest algorithm %s (NID %d)", + algo_name ? algo_name : "(null)", mdnid); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto out; + } + } + +#endif /* HAVE_OPENSSL3, else */ + + if(!algo_type) { + if(no_digest_acceptable) { + infof(data, "certificate exposes no signing digest algorithm, " + "nothing to add to channel binding"); + result = CURLE_OK; + goto out; + } + /* unacceptable, something is wrong, fail */ + algo_name = OBJ_nid2sn(mdnid); + failf(data, "Unable to find digest algorithm %s (NID %d) " + "for channel binding", algo_name ? algo_name : "(null)", mdnid); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto out; + } + + if(!X509_digest(cert, algo_type, buf, &length)) { + failf(data, "X509_digest() failed for channel binding"); + result = CURLE_SSL_INVALIDCERTSTATUS; + goto out; + } + + /* Append "tls-server-end-point:" */ + result = curlx_dyn_addn(binding, prefix, CURL_CSTRLEN(prefix)); + if(result) + goto out; + + /* Append digest */ + result = curlx_dyn_addn(binding, buf, length); + +out: + X509_free(cert); + return result; +} + +size_t Curl_ossl_version(char *buffer, size_t size) +{ +#ifdef LIBRESSL_VERSION_NUMBER + char *p; + size_t count; + const char *ver = OpenSSL_version(OPENSSL_VERSION); + static const char expected[] = OSSL_PACKAGE " "; /* ie "LibreSSL " */ + if(curl_strnequal(ver, expected, CURL_CSTRLEN(expected))) { + ver += CURL_CSTRLEN(expected); + } + count = curl_msnprintf(buffer, size, "%s/%s", OSSL_PACKAGE, ver); + for(p = buffer; *p; ++p) { + if(ISBLANK(*p)) + *p = '_'; + } + return count; +#elif defined(OPENSSL_IS_AWSLC) + return curl_msnprintf(buffer, size, "%s/%s", + OSSL_PACKAGE, AWSLC_VERSION_NUMBER_STRING); +#elif defined(OPENSSL_IS_BORINGSSL) +#ifdef CURL_BORINGSSL_VERSION + return curl_msnprintf(buffer, size, "%s/%s", + OSSL_PACKAGE, CURL_BORINGSSL_VERSION); +#else + return curl_msnprintf(buffer, size, OSSL_PACKAGE); +#endif +#else /* OpenSSL 3+ */ + return curl_msnprintf(buffer, size, "%s/%s", + OSSL_PACKAGE, OpenSSL_version(OPENSSL_VERSION_STRING)); +#endif +} + +/* can be called with data == NULL */ +static CURLcode ossl_random(struct Curl_easy *data, + unsigned char *entropy, size_t length) +{ + int rc; + if(data) { + if(ossl_seed(data)) /* Initiate the seed if not already done */ + return CURLE_FAILED_INIT; /* could not seed for some reason */ + } + else { + if(!rand_enough()) + return CURLE_FAILED_INIT; + } + /* RAND_bytes() returns 1 on success, 0 otherwise. */ + rc = RAND_bytes(entropy, (ossl_valsize_t)curlx_uztosi(length)); + return rc == 1 ? CURLE_OK : CURLE_FAILED_INIT; +} + +static CURLcode ossl_sha256sum(const unsigned char *input, + size_t len, + unsigned char *sha256sum /* output */, + size_t unused) +{ + CURLcode result = CURLE_OK; + EVP_MD_CTX *mdctx; + (void)unused; + + mdctx = EVP_MD_CTX_new(); + if(!mdctx) + return CURLE_OUT_OF_MEMORY; + if(!EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL)) { + result = CURLE_FAILED_INIT; + goto out; + } + if(!EVP_DigestUpdate(mdctx, input, len) || + !EVP_DigestFinal_ex(mdctx, sha256sum, NULL)) + result = CURLE_BAD_FUNCTION_ARGUMENT; +out: + EVP_MD_CTX_free(mdctx); + return result; +} + +static bool ossl_cert_status_request(void) +{ +#ifndef OPENSSL_NO_OCSP + return TRUE; +#else + return FALSE; +#endif +} + +static void *ossl_get_internals(struct ssl_connect_data *connssl, + CURLINFO info) +{ + /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */ + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + DEBUGASSERT(octx); + return info == CURLINFO_TLS_SESSION ? + (void *)octx->ssl_ctx : (void *)octx->ssl; +} + +const struct Curl_ssl Curl_ssl_openssl = { + { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */ + + SSLSUPP_CA_PATH | + SSLSUPP_CAINFO_BLOB | + SSLSUPP_CERTINFO | + SSLSUPP_PINNEDPUBKEY | + SSLSUPP_SSL_CTX | +#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES + SSLSUPP_TLS13_CIPHERSUITES | +#endif +#ifdef HAVE_SSL_CTX_SET1_SIGALGS + SSLSUPP_SIGNATURE_ALGORITHMS | +#endif +#ifdef HAVE_SSL_SET1_ECH_CONFIG_LIST + SSLSUPP_ECH | +#endif + SSLSUPP_CA_CACHE | + SSLSUPP_HTTPS_PROXY | + SSLSUPP_CIPHER_LIST | + SSLSUPP_ISSUERCERT | + SSLSUPP_ISSUERCERT_BLOB | + SSLSUPP_SSL_EC_CURVES | + SSLSUPP_CRLFILE, + + sizeof(struct ossl_ctx), + + ossl_init, /* init */ + ossl_cleanup, /* cleanup */ + Curl_ossl_version, /* version */ + ossl_shutdown, /* shutdown */ + ossl_data_pending, /* data_pending */ + ossl_random, /* random */ + ossl_cert_status_request, /* cert_status_request */ + ossl_connect, /* connect */ + Curl_ssl_adjust_pollset, /* adjust_pollset */ + ossl_get_internals, /* get_internals */ + ossl_close, /* close_one */ + ossl_close_all, /* close_all */ + ossl_set_engine, /* set_engine or provider */ + ossl_set_engine_default, /* set_engine_default */ + ossl_engines_list, /* engines_list */ + ossl_sha256sum, /* sha256sum */ + ossl_recv, /* recv decrypted data */ + ossl_send, /* send data to encrypt */ + ossl_get_channel_binding /* get_channel_binding */ +}; + +#endif /* USE_OPENSSL */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/openssl.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/openssl.h new file mode 100644 index 0000000000..dfac78c21e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/openssl.h @@ -0,0 +1,211 @@ +#ifndef HEADER_CURL_SSLUSE_H +#define HEADER_CURL_SSLUSE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_OPENSSL + +#ifdef USE_WIN32_CRYPTO +#include <wincrypt.h> +/* If <wincrypt.h> is included directly, or indirectly via <schannel.h>, + * <winldap.h>, <iphlpapi.h>, or something else, <wincrypt.h> does this: + * #define X509_NAME ((LPCSTR)7) + * + * In AWS-LC/BoringSSL's <openssl/base.h> there is: + * typedef struct X509_name_st X509_NAME; + * etc. + * + * The redefined symbols break these OpenSSL headers when included after + * <wincrypt.h>. + * The workaround is to undefine those defines here (and only here). + * + * For unity builds it may need to be repeated elsewhere too, e.g. in ldap.c, + * to apply to other sources using OpenSSL includes. Each compilation unit + * needs undefine them between the first <wincrypt.h> include and the first + * OpenSSL include. + * + * OpenSSL does this in <openssl/ssl.h> and <openssl/x509v3.h>, but it + * also does the #undef by including <openssl/ossl_typ.h>. <3.1.0 only does + * it on the first include. + * + * LibreSSL automatically undefines these symbols before using them. + */ +#undef X509_NAME +#undef X509_EXTENSIONS +#undef PKCS7_ISSUER_AND_SERIAL +#undef PKCS7_SIGNER_INFO +#undef OCSP_REQUEST +#undef OCSP_RESPONSE +#endif /* USE_WIN32_CRYPTO */ + +/* + * This header should only be needed to get included by vtls.c, openssl.c + * and ngtcp2.c + */ +#include <openssl/opensslv.h> +#include <openssl/ossl_typ.h> +#include <openssl/ssl.h> + +#include "urldata.h" + +#if OPENSSL_VERSION_NUMBER >= 0x30000000L +#define HAVE_OPENSSL3 /* non-fork OpenSSL 3.x or later */ +#endif + +#if defined(OPENSSL_IS_AWSLC) || defined(OPENSSL_IS_BORINGSSL) +#define HAVE_BORINGSSL_LIKE +#endif + +/* OpenSSL 3.5.0+ has built-in 'SSLKEYLOGFILE' support if built with + 'enable-sslkeylog' */ +#if OPENSSL_VERSION_NUMBER >= 0x30500000L && !defined(OPENSSL_NO_SSLKEYLOG) +#define HAVE_KEYLOG_UPSTREAM +#endif + +/* + * Whether SSL_CTX_set_keylog_callback is available. + * BoringSSL: supported since d28f59c27bac (committed 2015-11-19) + * LibreSSL: not supported. 3.5.0+ has a stub function that does nothing. + * OpenSSL: supported since 1.1.1 https://github.com/openssl/openssl/pull/2287 + */ +#ifndef LIBRESSL_VERSION_NUMBER +#define HAVE_KEYLOG_CALLBACK +#endif + +/* Check for OpenSSL 1.1.1 which has early data support. */ +#undef HAVE_OPENSSL_EARLYDATA +#if defined(TLS1_3_VERSION) && !defined(HAVE_BORINGSSL_LIKE) +#define HAVE_OPENSSL_EARLYDATA +#endif + +#ifdef LIBRESSL_VERSION_NUMBER +typedef long ctx_option_t; +#elif defined(HAVE_BORINGSSL_LIKE) +typedef uint32_t ctx_option_t; +#else +typedef uint64_t ctx_option_t; +#endif + +struct alpn_spec; +struct ssl_peer; +struct Curl_ssl_session; + +/* Struct to hold a curl OpenSSL instance */ +struct ossl_ctx { + /* these ones requires specific SSL-types */ + SSL_CTX *ssl_ctx; + SSL *ssl; + BIO_METHOD *bio_method; + CURLcode io_result; /* result of last BIO cfilter operation */ + /* blocked writes need to retry with same length, remember it */ + int blocked_ssl_write_len; +#if !defined(HAVE_KEYLOG_UPSTREAM) && !defined(HAVE_KEYLOG_CALLBACK) + /* Set to true once a valid keylog entry has been created to avoid dupes. + This is a bool and not a bitfield because it is passed by address. */ + bool keylog_done; +#endif + BIT(x509_store_setup); /* x509 store has been set up */ + BIT(store_is_empty); /* no certs/paths/blobs in x509 store */ + BIT(reused_session); /* session-ID was reused for this */ +#ifdef USE_APPLE_SECTRUST + BIT(sectrust_verified); /* peer was verified by sectrust */ + BIT(sectrust_session); /* session from sectrust verified peer */ +#endif +}; + +size_t Curl_ossl_version(char *buffer, size_t size); + +typedef CURLcode Curl_ossl_ctx_setup_cb(struct Curl_cfilter *cf, + struct Curl_easy *data, + void *user_data); + +typedef int Curl_ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid); +typedef CURLcode Curl_ossl_init_session_reuse_cb(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct alpn_spec *alpns, + struct Curl_ssl_session *scs, + bool *do_early_data); + +CURLcode Curl_ossl_ctx_init(struct ossl_ctx *octx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + const struct alpn_spec *alpns_requested, + Curl_ossl_ctx_setup_cb *cb_setup, + void *cb_user_data, + Curl_ossl_new_session_cb *cb_new_session, + void *ssl_user_data, + Curl_ossl_init_session_reuse_cb *sess_reuse_cb); + +/* Is a resolved HTTPS-RR needed for initializing OpenSSL? */ +bool Curl_ossl_need_httpsrr(struct Curl_easy *data); + +#ifndef HAVE_OPENSSL3 +#define SSL_get1_peer_certificate SSL_get_peer_certificate +#endif + +extern const struct Curl_ssl Curl_ssl_openssl; + +/** + * Setup the OpenSSL X509_STORE in `ssl_ctx` for the cfilter `cf` and + * easy handle `data`. Allows reuse of a shared cache if suitable + * and configured. + */ +CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ossl_ctx *octx); + +CURLcode Curl_ossl_ctx_configure(struct Curl_cfilter *cf, + struct Curl_easy *data, + SSL_CTX *ssl_ctx); + +/* + * Add a new session to the cache. Takes ownership of the session. + */ +CURLcode Curl_ossl_add_session(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ossl_ctx *octx, + const char *ssl_peer_key, + SSL_SESSION *session, + const char *alpn, + unsigned char *quic_tp, + size_t quic_tp_len, + struct Curl_ssl_session **psession); + +/* + * Get the server cert, verify it and show it, etc., only call failf() if + * SSL config verifypeer or -host is set. Otherwise all this is for + * informational purposes only! + */ +CURLcode Curl_ossl_check_peer_cert(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ossl_ctx *octx, + struct ssl_peer *peer); + +/* Report properties of a successful handshake */ +void Curl_ossl_report_handshake(struct Curl_easy *data, struct ossl_ctx *octx); + +#endif /* USE_OPENSSL */ +#endif /* HEADER_CURL_SSLUSE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/rustls.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/rustls.c new file mode 100644 index 0000000000..9c0b0d7be3 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/rustls.c @@ -0,0 +1,1468 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Jacob Hoffman-Andrews, <github@hoffman-andrews.com> + * Copyright (C) kpcyrd, <kpcyrd@archlinux.org> + * Copyright (C) Daniel McCarney, <daniel@binaryparadox.net> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_RUSTLS + +#include <rustls.h> + +#include "curlx/fopen.h" +#include "curlx/strerr.h" +#include "urldata.h" +#include "curl_trc.h" +#include "vdns/cf-dns.h" +#include "vdns/httpsrr.h" +#include "vtls/vtls.h" +#include "vtls/vtls_int.h" +#include "vtls/rustls.h" +#include "vtls/keylog.h" +#include "vtls/cipher_suite.h" +#include "vtls/x509asn1.h" +#ifdef USE_ECH +#include "curlx/base64.h" +#endif + +#if EAGAIN != EWOULDBLOCK +#define RAW_EAGAIN(e) ((e) == EWOULDBLOCK || (e) == EAGAIN) +#else +#define RAW_EAGAIN(e) ((e) == EWOULDBLOCK) +#endif + +struct rustls_ssl_backend_data { + const struct rustls_client_config *config; + struct rustls_connection *conn; + size_t plain_out_buffered; + BIT(data_in_pending); + BIT(sent_shutdown); +}; + +/* For a given rustls_result error code, return the best-matching CURLcode. */ +static CURLcode map_error(const rustls_result r) +{ + if(rustls_result_is_cert_error(r)) { + return CURLE_PEER_FAILED_VERIFICATION; + } + switch(r) { + case RUSTLS_RESULT_OK: + return CURLE_OK; + case RUSTLS_RESULT_NULL_PARAMETER: + return CURLE_BAD_FUNCTION_ARGUMENT; + default: + return CURLE_RECV_ERROR; + } +} + +static void rustls_failf(struct Curl_easy *data, const rustls_result rr, + const char *msg) +{ + char errorbuf[STRERROR_LEN]; + size_t errorlen; + rustls_error(rr, errorbuf, sizeof(errorbuf), &errorlen); + failf(data, "%s: %.*s", msg, (int)errorlen, errorbuf); +} + +static bool cr_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + const struct ssl_connect_data *ctx = cf->ctx; + struct rustls_ssl_backend_data *backend; + + (void)data; + DEBUGASSERT(ctx && ctx->backend); + backend = (struct rustls_ssl_backend_data *)ctx->backend; + return (bool)backend->data_in_pending; +} + +struct io_ctx { + struct Curl_cfilter *cf; + struct Curl_easy *data; +}; + +static int read_cb(void *userdata, uint8_t *buf, uintptr_t len, + uintptr_t *out_n) +{ + const struct io_ctx *io_ctx = userdata; + struct ssl_connect_data * const connssl = io_ctx->cf->ctx; + CURLcode result; + int ret = 0; + size_t nread; + + result = Curl_conn_cf_recv(io_ctx->cf->next, io_ctx->data, + (char *)buf, len, &nread); + if(result) { + nread = 0; + /* !checksrc! disable ERRNOVAR 4 */ + if(result == CURLE_AGAIN) + ret = EAGAIN; + else + ret = EINVAL; + } + else if(nread == 0) + connssl->peer_closed = TRUE; + *out_n = (uintptr_t)nread; + CURL_TRC_CF(io_ctx->data, io_ctx->cf, "cf->next recv(len=%zu) -> %d, %zu", + (size_t)len, (int)result, nread); + return ret; +} + +static int write_cb(void *userdata, const uint8_t *buf, uintptr_t len, + uintptr_t *out_n) +{ + const struct io_ctx *io_ctx = userdata; + CURLcode result; + int ret = 0; + size_t nwritten; + + result = Curl_conn_cf_send(io_ctx->cf->next, io_ctx->data, + buf, len, FALSE, &nwritten); + if(result) { + nwritten = 0; + if(result == CURLE_AGAIN) + ret = EAGAIN; + else + ret = EINVAL; + } + *out_n = (uintptr_t)nwritten; + CURL_TRC_CF(io_ctx->data, io_ctx->cf, "cf->next send(len=%zu) -> %d, %zu", + len, (int)result, nwritten); + return ret; +} + +static ssize_t tls_recv_more(struct Curl_cfilter *cf, + struct Curl_easy *data, CURLcode *err) +{ + const struct ssl_connect_data * const connssl = cf->ctx; + struct rustls_ssl_backend_data * const backend = + (struct rustls_ssl_backend_data *)connssl->backend; + struct io_ctx io_ctx; + size_t tls_bytes_read = 0; + rustls_io_result io_error; + rustls_result rresult = 0; + + io_ctx.cf = cf; + io_ctx.data = data; + io_error = rustls_connection_read_tls(backend->conn, read_cb, &io_ctx, + &tls_bytes_read); + if(RAW_EAGAIN(io_error)) { + *err = CURLE_AGAIN; + return -1; + } + else if(io_error) { + char buffer[STRERROR_LEN]; + failf(data, "reading from socket: %s", + curlx_strerror(io_error, buffer, sizeof(buffer))); + *err = CURLE_RECV_ERROR; + return -1; + } + + rresult = rustls_connection_process_new_packets(backend->conn); + if(rresult != RUSTLS_RESULT_OK) { + rustls_failf(data, rresult, "rustls_connection_process_new_packets"); + *err = map_error(rresult); + return -1; + } + + backend->data_in_pending = TRUE; + *err = CURLE_OK; + return (ssize_t)tls_bytes_read; +} + +/* + * Filter receive method implementation. `plainbuf` and `plainlen` + * are always not NULL/0. + */ +static CURLcode cr_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *plainbuf, size_t plainlen, size_t *pnread) +{ + const struct ssl_connect_data * const connssl = cf->ctx; + struct rustls_ssl_backend_data * const backend = + (struct rustls_ssl_backend_data *)connssl->backend; + struct rustls_connection *rconn = NULL; + CURLcode result = CURLE_OK; + size_t n = 0; + rustls_result rresult = 0; + bool eof = FALSE; + + DEBUGASSERT(backend); + *pnread = 0; + rconn = backend->conn; + + while(*pnread < plainlen) { + if(!backend->data_in_pending) { + if(tls_recv_more(cf, data, &result) < 0) { + if(result != CURLE_AGAIN) { + goto out; + } + result = CURLE_OK; + break; + } + } + + rresult = rustls_connection_read(rconn, + (uint8_t *)plainbuf + *pnread, + plainlen - *pnread, + &n); + if(rresult == RUSTLS_RESULT_PLAINTEXT_EMPTY) { + backend->data_in_pending = FALSE; + } + else if(rresult == RUSTLS_RESULT_UNEXPECTED_EOF) { + failf(data, "rustls: peer closed TCP connection " + "without first closing TLS connection"); + result = CURLE_RECV_ERROR; + goto out; + } + else if(rresult != RUSTLS_RESULT_OK) { + /* n always equals 0 in this case, do not need to check it */ + rustls_failf(data, rresult, "rustls_connection_read"); + result = CURLE_RECV_ERROR; + goto out; + } + else if(n == 0) { + /* n == 0 indicates clean EOF, but we may have read some other + plaintext bytes before we reached this. Break out of the loop + so we can figure out whether to return success or EOF. */ + eof = TRUE; + break; + } + else { + *pnread += n; + } + } + + if(!eof && !*pnread) { + result = CURLE_AGAIN; + } + +out: + CURL_TRC_CF(data, cf, "rustls_recv(len=%zu) -> %d, %zu", + plainlen, (int)result, *pnread); + return result; +} + +static CURLcode cr_flush_out(struct Curl_cfilter *cf, struct Curl_easy *data, + struct rustls_connection *rconn) +{ + struct io_ctx io_ctx; + rustls_io_result io_error; + size_t tlswritten = 0; + size_t tlswritten_total = 0; + + io_ctx.cf = cf; + io_ctx.data = data; + + while(rustls_connection_wants_write(rconn)) { + io_error = rustls_connection_write_tls(rconn, write_cb, &io_ctx, + &tlswritten); + if(RAW_EAGAIN(io_error)) { + CURL_TRC_CF(data, cf, "cf_send: EAGAIN after %zu bytes", + tlswritten_total); + return CURLE_AGAIN; + } + else if(io_error) { + char buffer[STRERROR_LEN]; + failf(data, "writing to socket: %s", + curlx_strerror(io_error, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + if(tlswritten == 0) { + failf(data, "EOF in swrite"); + return CURLE_SEND_ERROR; + } + CURL_TRC_CF(data, cf, "cf_send: wrote %zu TLS bytes", tlswritten); + tlswritten_total += tlswritten; + } + return CURLE_OK; +} + +/* + * On each call: + * - Copy `plainlen` bytes into Rustls' plaintext input buffer (if > 0). + * - Fully drain Rustls' plaintext output buffer into the socket until + * we get either an error or EAGAIN/EWOULDBLOCK. + * + * it is okay to call this function with plainbuf == NULL and plainlen == 0. + * In that case, it does not read anything into Rustls' plaintext input buffer. + * It only drains Rustls' plaintext output buffer into the socket. + */ +static CURLcode cr_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *plainbuf, size_t plainlen, + size_t *pnwritten) +{ + const struct ssl_connect_data * const connssl = cf->ctx; + struct rustls_ssl_backend_data * const backend = + (struct rustls_ssl_backend_data *)connssl->backend; + struct rustls_connection *rconn = NULL; + size_t plainwritten = 0; + const unsigned char *buf = plainbuf; + CURLcode result = CURLE_OK; + size_t blen = plainlen; + + DEBUGASSERT(backend); + *pnwritten = 0; + rconn = backend->conn; + DEBUGASSERT(rconn); + + CURL_TRC_CF(data, cf, "cf_send(len=%zu)", plainlen); + + /* If a previous send blocked, we already added its plain bytes + * to rustsls and must not do that again. Flush the TLS bytes and, + * if successful, deduct the previous plain bytes from the current + * send. */ + if(backend->plain_out_buffered) { + result = cr_flush_out(cf, data, rconn); + CURL_TRC_CF(data, cf, "cf_send: flushing %zu previously added bytes -> %d", + backend->plain_out_buffered, (int)result); + if(result) + return result; + if(blen > backend->plain_out_buffered) { + blen -= backend->plain_out_buffered; + buf += backend->plain_out_buffered; + } + else + blen = 0; + *pnwritten += backend->plain_out_buffered; + backend->plain_out_buffered = 0; + } + + if(blen > 0) { + rustls_result rresult; + CURL_TRC_CF(data, cf, "cf_send: adding %zu plain bytes to Rustls", blen); + rresult = rustls_connection_write(rconn, buf, blen, &plainwritten); + if(rresult != RUSTLS_RESULT_OK) { + rustls_failf(data, rresult, "rustls_connection_write"); + result = CURLE_WRITE_ERROR; + goto out; + } + else if(plainwritten == 0) { + failf(data, "rustls_connection_write: EOF"); + result = CURLE_WRITE_ERROR; + goto out; + } + } + + result = cr_flush_out(cf, data, rconn); + if(result) { + if(result == CURLE_AGAIN) { + /* The TLS bytes may have been partially written, but we fail the + * complete send() and remember how much we already added to Rustls. */ + backend->plain_out_buffered = plainwritten; + if(*pnwritten) { + result = CURLE_OK; + } + } + goto out; + } + else + *pnwritten += plainwritten; + +out: + CURL_TRC_CF(data, cf, "rustls_send(len=%zu) -> %d, %zu", + plainlen, (int)result, *pnwritten); + return result; +} + +/* A server certificate verify callback for Rustls that always returns + RUSTLS_RESULT_OK, or in other words disable certificate verification. */ +static uint32_t cr_verify_none(void *userdata, + const rustls_verify_server_cert_params *params) +{ + (void)userdata; + (void)params; + return RUSTLS_RESULT_OK; +} + +static int read_file_into(const char *filename, struct dynbuf *out) +{ + FILE *f = curlx_fopen(filename, FOPEN_READTEXT); + if(!f) { + return 0; + } + + for(;;) { + uint8_t buf[256]; + const size_t rr = fread(buf, 1, sizeof(buf), f); + if((!rr && !feof(f)) || + curlx_dyn_addn(out, buf, rr)) { + curlx_fclose(f); + return 0; + } + if(rr < sizeof(buf)) + break; + } + + return curlx_fclose(f) == 0; +} + +static void +cr_get_selected_ciphers(struct Curl_easy *data, + const char *ciphers12, + const char *ciphers13, + const struct rustls_supported_ciphersuite **selected, + size_t *selected_size) +{ + const size_t supported_len = *selected_size; + const size_t default_len = rustls_default_crypto_provider_ciphersuites_len(); + const struct rustls_supported_ciphersuite *entry = NULL; + const char *ciphers = ciphers12; + size_t count = 0, default13_count = 0, i, j; + const char *ptr, *end; + + DEBUGASSERT(default_len <= supported_len); + + if(!ciphers13) { + /* Add default TLSv1.3 ciphers to selection */ + for(j = 0; j < default_len; j++) { + entry = rustls_default_crypto_provider_ciphersuites_get(j); + if(rustls_supported_ciphersuite_protocol_version(entry) != + RUSTLS_TLS_VERSION_TLSV1_3) + continue; + + selected[count++] = entry; + } + + default13_count = count; + + if(!ciphers) + ciphers = ""; + } + else + ciphers = ciphers13; + +add_ciphers: + for(ptr = ciphers; ptr[0] != '\0' && count < supported_len; ptr = end) { + uint16_t id = Curl_cipher_suite_walk_str(&ptr, &end); + + /* Check if cipher is supported */ + if(id) { + for(i = 0; i < supported_len; i++) { + entry = rustls_default_crypto_provider_ciphersuites_get(i); + if(rustls_supported_ciphersuite_get_suite(entry) == id) + break; + } + if(i == supported_len) + id = 0; + } + if(!id) { + if(ptr[0] != '\0') + infof(data, "rustls: unknown cipher in list: \"%.*s\"", + (int)(end - ptr), ptr); + continue; + } + + /* No duplicates allowed (so selected cannot overflow) */ + for(i = 0; i < count && selected[i] != entry; i++) + ; + if(i < count) { + if(i >= default13_count) + infof(data, "rustls: duplicate cipher in list: \"%.*s\"", + (int)(end - ptr), ptr); + continue; + } + + selected[count++] = entry; + } + + if(ciphers == ciphers13 && ciphers12) { + ciphers = ciphers12; + goto add_ciphers; + } + + if(!ciphers12) { + /* Add default TLSv1.2 ciphers to selection */ + for(j = 0; j < default_len; j++) { + entry = rustls_default_crypto_provider_ciphersuites_get(j); + if(rustls_supported_ciphersuite_protocol_version(entry) == + RUSTLS_TLS_VERSION_TLSV1_3) + continue; + + /* No duplicates allowed (so selected cannot overflow) */ + for(i = 0; i < count && selected[i] != entry; i++) + ; + if(i < count) + continue; + + selected[count++] = entry; + } + } + + *selected_size = count; +} + +static void cr_keylog_log_cb(struct rustls_str label, + const uint8_t *client_random, + size_t client_random_len, const uint8_t *secret, + size_t secret_len) +{ + char clabel[KEYLOG_LABEL_MAXLEN]; + DEBUGASSERT(client_random_len == CLIENT_RANDOM_SIZE); + /* Turning a "rustls_str" into a null delimited "c" string */ + curl_msnprintf(clabel, sizeof(clabel), "%.*s", (int)label.len, label.data); + Curl_tls_keylog_write(clabel, client_random, client_random_len, + secret, secret_len); +} + +static CURLcode +init_config_builder(struct Curl_easy *data, + const struct ssl_primary_config *conn_config, + struct rustls_client_config_builder **config_builder) +{ + const struct rustls_supported_ciphersuite **cipher_suites = NULL; + struct rustls_crypto_provider_builder *custom_provider_builder = NULL; + const struct rustls_crypto_provider *custom_provider = NULL; + + uint16_t tls_versions[2] = { + RUSTLS_TLS_VERSION_TLSV1_2, + RUSTLS_TLS_VERSION_TLSV1_3, + }; + size_t tls_versions_len = 2; + size_t cipher_suites_len = rustls_default_crypto_provider_ciphersuites_len(); + + CURLcode result = CURLE_OK; + rustls_result rr; + + DEBUGASSERT(conn_config->version != CURL_SSLVERSION_DEFAULT); + switch(conn_config->version) { + case CURL_SSLVERSION_TLSv1: + case CURL_SSLVERSION_TLSv1_0: + case CURL_SSLVERSION_TLSv1_1: + case CURL_SSLVERSION_TLSv1_2: + break; + case CURL_SSLVERSION_TLSv1_3: + tls_versions[0] = RUSTLS_TLS_VERSION_TLSV1_3; + tls_versions_len = 1; + break; + default: + failf(data, "rustls: unsupported minimum TLS version value"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto cleanup; + } + + switch(conn_config->version_max) { + case CURL_SSLVERSION_MAX_DEFAULT: + case CURL_SSLVERSION_MAX_NONE: + case CURL_SSLVERSION_MAX_TLSv1_3: + break; + case CURL_SSLVERSION_MAX_TLSv1_2: + if(tls_versions[0] == RUSTLS_TLS_VERSION_TLSV1_2) { + tls_versions_len = 1; + break; + } + FALLTHROUGH(); + case CURL_SSLVERSION_MAX_TLSv1_1: + case CURL_SSLVERSION_MAX_TLSv1_0: + default: + failf(data, "rustls: unsupported maximum TLS version value"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto cleanup; + } + +#ifdef USE_ECH + if(CURLECH_ENABLED(data)) { + tls_versions[0] = RUSTLS_TLS_VERSION_TLSV1_3; + tls_versions_len = 1; + infof(data, "rustls: ECH enabled, forcing TLSv1.3"); + } +#endif /* USE_ECH */ + + cipher_suites = curlx_malloc(sizeof(*cipher_suites) * cipher_suites_len); + if(!cipher_suites) { + result = CURLE_OUT_OF_MEMORY; + goto cleanup; + } + + cr_get_selected_ciphers(data, + conn_config->cipher_list, + conn_config->cipher_list13, + cipher_suites, &cipher_suites_len); + if(cipher_suites_len == 0) { + failf(data, "rustls: no supported cipher in list"); + result = CURLE_SSL_CIPHER; + goto cleanup; + } + + rr = rustls_crypto_provider_builder_new_from_default( + &custom_provider_builder); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, + "failed to create crypto provider builder from default"); + result = CURLE_SSL_CIPHER; + goto cleanup; + } + + rr = + rustls_crypto_provider_builder_set_cipher_suites( + custom_provider_builder, + cipher_suites, + cipher_suites_len); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, + "failed to set ciphersuites for crypto provider builder"); + result = CURLE_SSL_CIPHER; + goto cleanup; + } + + rr = rustls_crypto_provider_builder_build(custom_provider_builder, + &custom_provider); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "failed to build custom crypto provider"); + result = CURLE_SSL_CIPHER; + goto cleanup; + } + + rr = rustls_client_config_builder_new_custom(custom_provider, + tls_versions, + tls_versions_len, + config_builder); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "failed to create client config builder"); + result = CURLE_SSL_CIPHER; + goto cleanup; + } + +cleanup: + if(cipher_suites) { + curlx_free(cipher_suites); + } + if(custom_provider_builder) { + rustls_crypto_provider_builder_free(custom_provider_builder); + } + if(custom_provider) { + rustls_crypto_provider_free(custom_provider); + } + return result; +} + +static void +init_config_builder_alpn(struct Curl_easy *data, + const struct ssl_connect_data *connssl, + struct rustls_client_config_builder *config_builder) +{ + struct alpn_proto_buf proto; + rustls_slice_bytes alpn[ALPN_ENTRIES_MAX]; + size_t i; + + for(i = 0; i < connssl->alpn->count; ++i) { + alpn[i].data = (const uint8_t *)connssl->alpn->entries[i]; + alpn[i].len = strlen(connssl->alpn->entries[i]); + } + rustls_client_config_builder_set_alpn_protocols(config_builder, alpn, + connssl->alpn->count); + Curl_alpn_to_proto_str(&proto, connssl->alpn); + infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); +} + +static CURLcode init_config_builder_verifier_crl( + struct Curl_easy *data, + const struct ssl_primary_config *conn_config, + struct rustls_web_pki_server_cert_verifier_builder *builder) +{ + CURLcode result = CURLE_OK; + struct dynbuf crl_contents; + rustls_result rr; + + curlx_dyn_init(&crl_contents, DYN_CRLFILE_SIZE); + if(!read_file_into(conn_config->CRLfile, &crl_contents)) { + failf(data, "rustls: failed to read revocation list file"); + result = CURLE_SSL_CRL_BADFILE; + goto cleanup; + } + + rr = rustls_web_pki_server_cert_verifier_builder_add_crl( + builder, + curlx_dyn_uptr(&crl_contents), + curlx_dyn_len(&crl_contents)); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "failed to parse revocation list"); + result = CURLE_SSL_CRL_BADFILE; + goto cleanup; + } + +cleanup: + curlx_dyn_free(&crl_contents); + return result; +} + +static CURLcode +init_config_builder_verifier(struct Curl_easy *data, + struct rustls_client_config_builder *builder, + const struct ssl_primary_config *conn_config, + const struct curl_blob *ca_info_blob, + const char * const ssl_cafile) +{ + const struct rustls_root_cert_store *roots = NULL; + struct rustls_root_cert_store_builder *roots_builder = NULL; + struct rustls_web_pki_server_cert_verifier_builder *verifier_builder = NULL; + struct rustls_server_cert_verifier *server_cert_verifier = NULL; + rustls_result rr = RUSTLS_RESULT_OK; + CURLcode result = CURLE_OK; + + roots_builder = rustls_root_cert_store_builder_new(); + if(ca_info_blob) { + rr = rustls_root_cert_store_builder_add_pem(roots_builder, + ca_info_blob->data, + ca_info_blob->len, + 1); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "failed to parse trusted certificates from blob"); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + } + else if(ssl_cafile) { + rr = rustls_root_cert_store_builder_load_roots_from_file(roots_builder, + ssl_cafile, + 1); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "failed to load trusted certificates"); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + } + + rr = rustls_root_cert_store_builder_build(roots_builder, &roots); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "failed to build trusted root certificate store"); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + + verifier_builder = rustls_web_pki_server_cert_verifier_builder_new(roots); + if(!verifier_builder) { + result = CURLE_OUT_OF_MEMORY; + goto cleanup; + } + + if(conn_config->CRLfile) { + result = init_config_builder_verifier_crl(data, + conn_config, + verifier_builder); + if(result) { + goto cleanup; + } + } + + rr = rustls_web_pki_server_cert_verifier_builder_build( + verifier_builder, &server_cert_verifier); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "failed to build certificate verifier"); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + + rustls_client_config_builder_set_server_verifier(builder, + server_cert_verifier); +cleanup: + if(roots_builder) { + rustls_root_cert_store_builder_free(roots_builder); + } + if(roots) { + rustls_root_cert_store_free(roots); + } + if(verifier_builder) { + rustls_web_pki_server_cert_verifier_builder_free(verifier_builder); + } + if(server_cert_verifier) { + rustls_server_cert_verifier_free(server_cert_verifier); + } + + return result; +} + +static CURLcode init_config_builder_platform_verifier( + struct Curl_easy *data, + struct rustls_client_config_builder *builder) +{ + struct rustls_server_cert_verifier *server_cert_verifier = NULL; + CURLcode result = CURLE_OK; + rustls_result rr; + + rr = rustls_platform_server_cert_verifier(&server_cert_verifier); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "failed to create platform certificate verifier"); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + + rustls_client_config_builder_set_server_verifier(builder, + server_cert_verifier); + +cleanup: + if(server_cert_verifier) { + rustls_server_cert_verifier_free(server_cert_verifier); + } + return result; +} + +static CURLcode +init_config_builder_keylog(struct Curl_easy *data, + struct rustls_client_config_builder *builder) +{ + rustls_result rr; + + Curl_tls_keylog_open(); + if(!Curl_tls_keylog_enabled()) { + return CURLE_OK; + } + + rr = rustls_client_config_builder_set_key_log(builder, + cr_keylog_log_cb, + NULL); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "rustls_client_config_builder_set_key_log"); + Curl_tls_keylog_close(); + return map_error(rr); + } + + return CURLE_OK; +} + +static CURLcode +init_config_builder_client_auth(struct Curl_easy *data, + const struct ssl_primary_config *conn_config, + const struct ssl_config_data *ssl_config, + struct rustls_client_config_builder *builder) +{ + struct dynbuf cert_contents; + struct dynbuf key_contents; + rustls_result rr; + const struct rustls_certified_key *certified_key = NULL; + CURLcode result = CURLE_OK; + + if(conn_config->clientcert && !ssl_config->primary.key) { + failf(data, "rustls: must provide key with certificate '%s'", + conn_config->clientcert); + return CURLE_SSL_CERTPROBLEM; + } + else if(!conn_config->clientcert && ssl_config->primary.key) { + failf(data, "rustls: must provide certificate with key '%s'", + ssl_config->primary.key); + return CURLE_SSL_CERTPROBLEM; + } + + curlx_dyn_init(&cert_contents, DYN_CERTFILE_SIZE); + curlx_dyn_init(&key_contents, DYN_KEYFILE_SIZE); + + if(!read_file_into(conn_config->clientcert, &cert_contents)) { + failf(data, "rustls: failed to read client certificate file: '%s'", + conn_config->clientcert); + result = CURLE_SSL_CERTPROBLEM; + goto cleanup; + } + + if(!read_file_into(ssl_config->primary.key, &key_contents)) { + failf(data, "rustls: failed to read key file: '%s'", + ssl_config->primary.key); + result = CURLE_SSL_CERTPROBLEM; + goto cleanup; + } + + rr = rustls_certified_key_build(curlx_dyn_uptr(&cert_contents), + curlx_dyn_len(&cert_contents), + curlx_dyn_uptr(&key_contents), + curlx_dyn_len(&key_contents), + &certified_key); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "rustls: failed to build certified key"); + result = CURLE_SSL_CERTPROBLEM; + goto cleanup; + } + + rr = rustls_certified_key_keys_match(certified_key); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, + "rustls: client certificate and keypair files do not match:"); + result = CURLE_SSL_CERTPROBLEM; + goto cleanup; + } + + rr = rustls_client_config_builder_set_certified_key(builder, + &certified_key, + 1); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "rustls: failed to set certified key"); + result = CURLE_SSL_CERTPROBLEM; + goto cleanup; + } + +cleanup: + curlx_dyn_free(&cert_contents); + curlx_dyn_free(&key_contents); + if(certified_key) { + rustls_certified_key_free(certified_key); + } + return result; +} + +#ifdef USE_ECH + +static bool cr_ech_need_httpsrr(struct Curl_easy *data) +{ + if(!CURLECH_ENABLED(data)) + return FALSE; + if((data->set.tls_ech == CURLECH_GREASE) || + CURL_EASY_STR(data, STRING_ECH_CONFIG)) + return FALSE; + return TRUE; +} + +static CURLcode +init_config_builder_ech(struct Curl_easy *data, + struct Curl_cfilter *cf, + struct rustls_client_config_builder *builder) +{ + const rustls_hpke *hpke = rustls_supported_hpke(); + unsigned char *ech_config = NULL; + size_t ech_config_len = 0; + struct Curl_dns_entry *dns = NULL; + CURLcode result = CURLE_OK; + rustls_result rr; + + if(!hpke) { + failf(data, + "rustls: ECH unavailable, rustls-ffi built without " + "HPKE compatible crypto provider"); + result = CURLE_SSL_CONNECT_ERROR; + goto cleanup; + } + + if(CURL_EASY_STR(data, STRING_ECH_PUBLIC)) { + failf(data, "rustls: ECH outername not supported"); + result = CURLE_SSL_CONNECT_ERROR; + goto cleanup; + } + + if(data->set.tls_ech == CURLECH_GREASE) { + rr = rustls_client_config_builder_enable_ech_grease(builder, hpke); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "rustls: failed to configure ECH GREASE"); + result = CURLE_SSL_CONNECT_ERROR; + goto cleanup; + } + return CURLE_OK; + } + + if(data->set.tls_ech && CURL_EASY_STR(data, STRING_ECH_CONFIG)) { + const char *b64 = CURL_EASY_STR(data, STRING_ECH_CONFIG); + size_t decode_result; + if(!b64) { + infof(data, "rustls: ECHConfig from command line empty"); + result = CURLE_SSL_CONNECT_ERROR; + goto cleanup; + } + /* rustls-ffi expects the raw TLS encoded ECHConfigList bytes */ + decode_result = curlx_base64_decode(b64, &ech_config, &ech_config_len); + if(decode_result || !ech_config) { + infof(data, "rustls: cannot base64 decode ECHConfig from command line"); + result = CURLE_SSL_CONNECT_ERROR; + goto cleanup; + } + } + else { + const struct ssl_connect_data *connssl = cf->ctx; + const struct Curl_https_rrinfo *rinfo = + Curl_conn_dns_get_https(data, cf->sockindex, connssl->peer.origin); + + if(!rinfo || !rinfo->echconfiglist) { + failf(data, "rustls: ECH requested but no ECHConfig available"); + result = CURLE_SSL_CONNECT_ERROR; + goto cleanup; + } + ech_config = rinfo->echconfiglist; + ech_config_len = rinfo->echconfiglist_len; + } + + rr = rustls_client_config_builder_enable_ech(builder, + ech_config, + ech_config_len, + hpke); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "rustls: failed to configure ECH"); + result = CURLE_SSL_CONNECT_ERROR; + goto cleanup; + } +cleanup: + /* if we base64 decoded, we can free now */ + if(data->set.tls_ech && CURL_EASY_STR(data, STRING_ECH_CONFIG)) { + curlx_free(ech_config); + } + if(dns) { + Curl_dns_entry_unlink(data, &dns); + } + return result; +} +#endif /* USE_ECH */ + +static CURLcode cr_init_backend(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct rustls_ssl_backend_data * const backend) +{ + const struct ssl_connect_data *connssl = cf->ctx; + const struct ssl_primary_config *conn_config = + Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + struct rustls_connection *rconn = NULL; + struct rustls_client_config_builder *config_builder = NULL; + + const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; + const char * const ssl_cafile = + /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */ + (ca_info_blob ? NULL : conn_config->CAfile); + CURLcode result = CURLE_OK; + rustls_result rr; + + DEBUGASSERT(backend); + rconn = backend->conn; + + result = init_config_builder(data, conn_config, &config_builder); + if(result != CURLE_OK) { + return result; + } + + if(connssl->alpn) { + init_config_builder_alpn(data, connssl, config_builder); + } + + if(!conn_config->verifypeer) { + rustls_client_config_builder_dangerous_set_certificate_verifier( + config_builder, cr_verify_none); + } + else if(conn_config->native_ca_store) { + if(conn_config->CRLfile) { + failf(data, "rustls: CRL file not supported with native CA store; " + "the platform verifier has no CRL attachment API"); + rustls_client_config_builder_free(config_builder); + return CURLE_NOT_BUILT_IN; + } + result = init_config_builder_platform_verifier(data, config_builder); + if(result != CURLE_OK) { + rustls_client_config_builder_free(config_builder); + return result; + } + } + else if(ca_info_blob || ssl_cafile) { + result = init_config_builder_verifier(data, + config_builder, + conn_config, + ca_info_blob, + ssl_cafile); + if(result != CURLE_OK) { + rustls_client_config_builder_free(config_builder); + return result; + } + } + + if(conn_config->clientcert || ssl_config->primary.key) { + result = init_config_builder_client_auth(data, + conn_config, + ssl_config, + config_builder); + if(result != CURLE_OK) { + rustls_client_config_builder_free(config_builder); + return result; + } + } + +#ifdef USE_ECH + if(CURLECH_ENABLED(data)) { + result = init_config_builder_ech(data, cf, config_builder); + if((result != CURLE_OK) && (data->set.tls_ech == CURLECH_HARD)) { + rustls_client_config_builder_free(config_builder); + return result; + } + } +#endif /* USE_ECH */ + + result = init_config_builder_keylog(data, config_builder); + if(result != CURLE_OK) { + rustls_client_config_builder_free(config_builder); + return result; + } + + rr = rustls_client_config_builder_build(config_builder, &backend->config); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "failed to build client config"); + return CURLE_SSL_CONNECT_ERROR; + } + + DEBUGASSERT(!rconn); + rr = rustls_client_connection_new(backend->config, + connssl->peer.origin->hostname, + &rconn); + if(rr != RUSTLS_RESULT_OK) { + rustls_failf(data, rr, "rustls_client_connection_new"); + rustls_client_config_free(backend->config); + backend->config = NULL; + return CURLE_COULDNT_CONNECT; + } + DEBUGASSERT(rconn); + rustls_connection_set_userdata(rconn, backend); + backend->conn = rconn; + + return result; +} + +static void cr_set_negotiated_alpn(struct Curl_cfilter *cf, + struct Curl_easy *data, + const struct rustls_connection *rconn) +{ + struct ssl_connect_data * const connssl = cf->ctx; + const uint8_t *protocol = NULL; + size_t len = 0; + + rustls_connection_get_alpn_protocol(rconn, &protocol, &len); + Curl_alpn_set_negotiated(cf, data, connssl, protocol, len); +} + +/* Given an established network connection, do a TLS handshake. + * + * This function sets `*done` to true once the handshake is complete. + * This function never reads the value of `*done*`. + */ +static CURLcode cr_connect(struct Curl_cfilter *cf, struct Curl_easy *data, + bool *done) +{ + struct ssl_connect_data * const connssl = cf->ctx; + const struct rustls_ssl_backend_data * const backend = + (struct rustls_ssl_backend_data *)connssl->backend; + const struct rustls_connection *rconn = NULL; + CURLcode tmperr = CURLE_OK; + CURLcode result; + bool wants_read; + bool wants_write; + ssize_t nread; + + DEBUGASSERT(backend); + + CURL_TRC_CF(data, cf, "cr_connect, state=%d", (int)connssl->state); + *done = FALSE; + +#ifdef USE_ECH + /* if we do ECH and need the HTTPS-RR information for it, + * we delay the connect until it arrives or DNS resolve fails. */ + if(cr_ech_need_httpsrr(data) && + !Curl_conn_dns_resolved_https(data, cf->sockindex, + connssl->peer.peer)) { + CURL_TRC_CF(data, cf, "need HTTPS-RR for ECH, delaying connect"); + return CURLE_OK; + } +#endif /* USE_ECH */ + + if(!backend->conn) { + result = + cr_init_backend(cf, data, + (struct rustls_ssl_backend_data *)connssl->backend); + CURL_TRC_CF(data, cf, "cr_connect, init backend -> %d", (int)result); + if(result) + return result; + connssl->state = ssl_connection_negotiating; + } + rconn = backend->conn; + + /* Read/write data until the handshake is done or the socket would block. */ + for(;;) { + /* + * Connection has been established according to Rustls. Set send/recv + * handlers, and update the state machine. + */ + connssl->io_need = CURL_SSL_IO_NEED_NONE; + if(!rustls_connection_is_handshaking(rconn)) { + /* Rustls claims it is no longer handshaking *before* it has + * send its FINISHED message off. We attempt to let it write + * one more time. Oh my. + */ + size_t nwritten; + cr_set_negotiated_alpn(cf, data, rconn); + tmperr = cr_send(cf, data, NULL, 0, &nwritten); + if(tmperr == CURLE_AGAIN) { + connssl->io_need = CURL_SSL_IO_NEED_SEND; + return CURLE_OK; + } + else if(tmperr != CURLE_OK) { + return tmperr; + } + /* REALLY Done with the handshake. */ + { +#ifdef CURLVERBOSE + const uint16_t proto = rustls_connection_get_protocol_version(rconn); + const rustls_str ciphersuite_name = + rustls_connection_get_negotiated_ciphersuite_name(rconn); + const rustls_str kex_group_name = + rustls_connection_get_negotiated_key_exchange_group_name(rconn); + const char *ver = "TLS version unknown"; + if(proto == RUSTLS_TLS_VERSION_TLSV1_3) + ver = "TLSv1.3"; + if(proto == RUSTLS_TLS_VERSION_TLSV1_2) + ver = "TLSv1.2"; +#endif + infof(data, + "rustls: handshake complete, %s, ciphersuite: %.*s, " + "key exchange group: %.*s", + ver, + (int) ciphersuite_name.len, + ciphersuite_name.data, + (int) kex_group_name.len, + kex_group_name.data); + } + if(data->set.ssl.certinfo) { + size_t num_certs = 0; + size_t i; + while(rustls_connection_get_peer_certificate(rconn, num_certs)) { + num_certs++; + if(num_certs > MAX_ALLOWED_CERT_AMOUNT) { + failf(data, "%zu certificates is more than allowed (%d)", + num_certs, MAX_ALLOWED_CERT_AMOUNT); + return CURLE_SSL_CONNECT_ERROR; + } + } + result = Curl_ssl_init_certinfo(data, (int)num_certs); + if(result) + return result; + for(i = 0; i < num_certs; i++) { + const rustls_certificate *cert; + const unsigned char *der_data; + size_t der_len; + rustls_result rresult = RUSTLS_RESULT_OK; + cert = rustls_connection_get_peer_certificate(rconn, i); + DEBUGASSERT(cert); /* Should exist since we counted already */ + rresult = rustls_certificate_get_der(cert, &der_data, &der_len); + if(rresult != RUSTLS_RESULT_OK) { + char errorbuf[255]; + size_t errorlen; + rustls_error(rresult, errorbuf, sizeof(errorbuf), &errorlen); + failf(data, + "Failed getting DER of server certificate #%zu: %.*s", i, + (int)errorlen, errorbuf); + return map_error(rresult); + } + { + const char *beg; + const char *end; + beg = (const char *)der_data; + end = (const char *)(der_data + der_len); + result = Curl_extract_certinfo(data, (int)i, beg, end); + if(result) + return result; + } + } + } + + connssl->state = ssl_connection_complete; + *done = TRUE; + return CURLE_OK; + } + + connssl->connecting_state = ssl_connect_2; + wants_read = rustls_connection_wants_read(rconn); + wants_write = rustls_connection_wants_write(rconn) || + backend->plain_out_buffered; + DEBUGASSERT(wants_read || wants_write); + + if(wants_write) { + size_t nwritten; + CURL_TRC_CF(data, cf, "rustls_connection wants us to write_tls."); + tmperr = cr_send(cf, data, NULL, 0, &nwritten); + if(tmperr == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "writing would block"); + connssl->io_need = CURL_SSL_IO_NEED_SEND; + return CURLE_OK; + } + else if(tmperr != CURLE_OK) { + return tmperr; + } + } + + if(wants_read) { + CURL_TRC_CF(data, cf, "rustls_connection wants us to read_tls."); + nread = tls_recv_more(cf, data, &tmperr); + if(nread == 0) { + connssl->peer_closed = TRUE; + failf(data, "TLS connect error: Connection closed abruptly"); + return CURLE_SSL_CONNECT_ERROR; + } + if(nread < 0) { + if(tmperr == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "reading would block"); + connssl->io_need = CURL_SSL_IO_NEED_RECV; + return CURLE_OK; + } + else if(tmperr == CURLE_RECV_ERROR) { + return CURLE_SSL_CONNECT_ERROR; + } + else { + return tmperr; + } + } + } + } + + /* We should never fall through the loop. We should return either because + the handshake is done or because we cannot read/write without blocking. */ + DEBUGASSERT(FALSE); +} + +static void *cr_get_internals(struct ssl_connect_data *connssl, CURLINFO info) +{ + struct rustls_ssl_backend_data *backend = + (struct rustls_ssl_backend_data *)connssl->backend; + (void)info; + DEBUGASSERT(backend); + return backend->conn; +} + +static CURLcode cr_shutdown(struct Curl_cfilter *cf, struct Curl_easy *data, + const bool send_shutdown, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct rustls_ssl_backend_data *backend = + (struct rustls_ssl_backend_data *)connssl->backend; + CURLcode result = CURLE_OK; + size_t i, nread = 0, nwritten; + + DEBUGASSERT(backend); + if(!backend->conn || cf->shutdown) { + *done = TRUE; + goto out; + } + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + *done = FALSE; + + if(!backend->sent_shutdown) { + /* do this only once */ + backend->sent_shutdown = TRUE; + if(send_shutdown) { + rustls_connection_send_close_notify(backend->conn); + } + } + + result = cr_send(cf, data, NULL, 0, &nwritten); + if(result) { + if(result == CURLE_AGAIN) { + connssl->io_need = CURL_SSL_IO_NEED_SEND; + result = CURLE_OK; + goto out; + } + DEBUGASSERT(result); + CURL_TRC_CF(data, cf, "shutdown send failed: %d", (int)result); + goto out; + } + + for(i = 0; i < 10; ++i) { + char buf[1024]; + result = cr_recv(cf, data, buf, (int)sizeof(buf), &nread); + if(result) + break; + } + + if(result == CURLE_AGAIN) { + connssl->io_need = CURL_SSL_IO_NEED_RECV; + result = CURLE_OK; + } + else if(result) { + DEBUGASSERT(result); + CURL_TRC_CF(data, cf, "shutdown, error: %d", (int)result); + } + else if(nread == 0) { + /* We got the close notify alert and are done. */ + *done = TRUE; + } + +out: + cf->shutdown = (result || *done); + return result; +} + +static void cr_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + const struct ssl_connect_data *connssl = cf->ctx; + struct rustls_ssl_backend_data *backend = + (struct rustls_ssl_backend_data *)connssl->backend; + + (void)data; + DEBUGASSERT(backend); + if(backend->conn) { + rustls_connection_free(backend->conn); + backend->conn = NULL; + } + if(backend->config) { + rustls_client_config_free(backend->config); + backend->config = NULL; + } +} + +static size_t cr_version(char *buffer, size_t size) +{ + const struct rustls_str ver = rustls_version(); + return curl_msnprintf(buffer, size, "%.*s", (int)ver.len, ver.data); +} + +static CURLcode cr_random(struct Curl_easy *data, unsigned char *entropy, + size_t length) +{ + rustls_result rresult = 0; + (void)data; + rresult = rustls_default_crypto_provider_random(entropy, length); + return map_error(rresult); +} + +static void cr_cleanup(void) +{ + Curl_tls_keylog_close(); +} + +const struct Curl_ssl Curl_ssl_rustls = { + { CURLSSLBACKEND_RUSTLS, "rustls" }, + SSLSUPP_CAINFO_BLOB | /* supports */ + SSLSUPP_HTTPS_PROXY | + SSLSUPP_CIPHER_LIST | + SSLSUPP_TLS13_CIPHERSUITES | + SSLSUPP_CERTINFO | + SSLSUPP_ECH | + SSLSUPP_CRLFILE, + sizeof(struct rustls_ssl_backend_data), + + NULL, /* init */ + cr_cleanup, /* cleanup */ + cr_version, /* version */ + cr_shutdown, /* shutdown */ + cr_data_pending, /* data_pending */ + cr_random, /* random */ + NULL, /* cert_status_request */ + cr_connect, /* connect */ + Curl_ssl_adjust_pollset, /* adjust_pollset */ + cr_get_internals, /* get_internals */ + cr_close, /* close_one */ + NULL, /* close_all */ + NULL, /* set_engine */ + NULL, /* set_engine_default */ + NULL, /* engines_list */ + NULL, /* sha256sum */ + cr_recv, /* recv decrypted data */ + cr_send, /* send data to encrypt */ + NULL, /* get_channel_binding */ +}; + +#endif /* USE_RUSTLS */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/rustls.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/rustls.h new file mode 100644 index 0000000000..b6ddbd1b7e --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/rustls.h @@ -0,0 +1,33 @@ +#ifndef HEADER_CURL_RUSTLS_H +#define HEADER_CURL_RUSTLS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Jacob Hoffman-Andrews, <github@hoffman-andrews.com> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_RUSTLS + +extern const struct Curl_ssl Curl_ssl_rustls; + +#endif /* USE_RUSTLS */ +#endif /* HEADER_CURL_RUSTLS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/schannel.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/schannel.c new file mode 100644 index 0000000000..34c6e79f79 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/schannel.c @@ -0,0 +1,2901 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) Marc Hoersken, <info@marc-hoersken.de> + * Copyright (C) Mark Salisbury, <mark.salisbury@hp.com> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Source file for all Schannel-specific code for the TLS/SSL layer. No code + * but vtls.c should ever call or use these functions. + */ +#include "curl_setup.h" + +#ifdef USE_SCHANNEL + +#ifndef USE_WINDOWS_SSPI +#error "cannot compile Schannel support without SSPI." +#endif + +#include "vtls/schannel.h" +#include "vtls/schannel_int.h" +#include "vtls/vtls.h" +#include "vtls/vtls_int.h" +#include "vtls/vtls_scache.h" +#include "curl_trc.h" +#include "connect.h" /* for the connect timeout */ +#include "curlx/strdup.h" +#include "strerror.h" +#include "select.h" /* for the socket readiness */ +#include "curlx/fopen.h" +#include "curlx/multibyte.h" +#include "vtls/x509asn1.h" +#include "curlx/version_win32.h" +#include "curlx/winapi.h" +#include "curlx/strparse.h" +#include "progress.h" +#include "curl_sha256.h" + +/* Some verbose debug messages are wrapped by SCH_DEV() instead of DEBUGF() + * and only shown if CURL_SCHANNEL_DEV_DEBUG was defined at build time. These + * messages are extra verbose and intended for curl developers debugging + * Schannel recv decryption and renegotiation. + */ +#ifdef CURL_SCHANNEL_DEV_DEBUG +#define SCH_DEV(x) x +#define SCH_DEV_SHOWBOOL(x) \ + infof(data, "schannel: " #x " %s", (x) ? "TRUE" : "FALSE"); +#else +#define SCH_DEV(x) do {} while(0) +#define SCH_DEV_SHOWBOOL(x) do {} while(0) +#endif + +/* Offered by mingw-w64 v8+, MS SDK 7.0A/VS2010+ */ +#ifndef SP_PROT_TLS1_0_CLIENT +#define SP_PROT_TLS1_0_CLIENT SP_PROT_TLS1_CLIENT +#endif +#ifndef SP_PROT_TLS1_1_CLIENT +#define SP_PROT_TLS1_1_CLIENT 0x00000200 +#endif +#ifndef SP_PROT_TLS1_2_CLIENT +#define SP_PROT_TLS1_2_CLIENT 0x00000800 +#endif + +/* Offered by mingw-w64 v8+, MS SDK 10.0.15063.0/VS2017 15.1+ */ +#ifndef SP_PROT_TLS1_3_CLIENT +#define SP_PROT_TLS1_3_CLIENT 0x00002000 +#endif +/* Offered by mingw-w64 v8+, MS SDK 8.1/VS2013+ */ +#ifndef SCH_USE_STRONG_CRYPTO +#define SCH_USE_STRONG_CRYPTO 0x00400000 +#endif + +/* Offered by mingw-w64 v10+, MS SDK 7.0A/VS2010+ */ +#ifndef SECBUFFER_ALERT +#define SECBUFFER_ALERT 17 +#endif + +/* Both schannel buffer sizes must be > 0 */ +#define CURL_SCHANNEL_BUFFER_INIT_SIZE 4096 +#define CURL_SCHANNEL_BUFFER_FREE_SIZE 1024 + +#define CERT_THUMBPRINT_STR_LEN 40 +#define CERT_THUMBPRINT_DATA_LEN 20 + +/* Uncomment to force verbose output + * #define infof(x, y, ...) curl_mprintf(y, __VA_ARGS__) + * #define failf(x, y, ...) curl_mprintf(y, __VA_ARGS__) + */ + +/* Offered by mingw-w64 v4+, MS SDK 6.0A/VS2008+ */ +#ifndef PKCS12_NO_PERSIST_KEY +#define PKCS12_NO_PERSIST_KEY 0x00008000 +#endif + +/* Offered by mingw-w64 v4+, MS SDK 8.0/~VS2012+ */ +#ifndef CERT_FIND_HAS_PRIVATE_KEY +#define CERT_FIND_HAS_PRIVATE_KEY (21 << CERT_COMPARE_SHIFT) +#endif + +/* key to use at `multi->proto_hash` */ +#define MPROTO_SCHANNEL_CERT_SHARE_KEY "tls:schannel:cert:share" + +static bool s_win_has_alpn; + +/* Offered by mingw-w64 v9+, MS SDK 8.1/VS2013+ */ +#ifndef SECBUFFER_APPLICATION_PROTOCOLS +#define SECBUFFER_APPLICATION_PROTOCOLS 18 +#define SECPKG_ATTR_APPLICATION_PROTOCOL 35 + +typedef enum { + SecApplicationProtocolNegotiationExt_None, + SecApplicationProtocolNegotiationExt_NPN, + SecApplicationProtocolNegotiationExt_ALPN +} SEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT; + +typedef enum { + SecApplicationProtocolNegotiationStatus_None, + SecApplicationProtocolNegotiationStatus_Success, + SecApplicationProtocolNegotiationStatus_SelectedClientOnly +} SEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS; + +/* !checksrc! disable TYPEDEFSTRUCT 1 */ +typedef struct { + SEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS ProtoNegoStatus; + SEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT ProtoNegoExt; + unsigned char ProtocolIdSize; + unsigned char ProtocolId[0xff]; +} SecPkgContext_ApplicationProtocol; +#endif + +static void InitSecBuffer(SecBuffer *buffer, unsigned long BufType, + void *BufDataPtr, unsigned long BufByteSize) +{ + buffer->cbBuffer = BufByteSize; + buffer->BufferType = BufType; + buffer->pvBuffer = BufDataPtr; +} + +static void InitSecBufferDesc(SecBufferDesc *desc, SecBuffer *BufArr, + unsigned long NumArrElem) +{ + desc->ulVersion = SECBUFFER_VERSION; + desc->pBuffers = BufArr; + desc->cBuffers = NumArrElem; +} + +static CURLcode schannel_set_ssl_version_min_max(DWORD *enabled_protocols, + struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + long ssl_version = conn_config->version; + long ssl_version_max = (long)conn_config->version_max; + long i = ssl_version; + + switch(ssl_version_max) { + case CURL_SSLVERSION_MAX_NONE: + case CURL_SSLVERSION_MAX_DEFAULT: + + /* Windows Server 2022 and newer (including Windows 11) support TLS 1.3 + built-in. Previous builds of Windows 10 had broken TLS 1.3 + implementations that could be enabled via registry. */ + if(curlx_verify_windows_version(10, 0, 20348, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) { + ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_3; + } + else /* Windows 10 or older */ + ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2; + + break; + } + + for(; i <= (ssl_version_max >> 16); ++i) { + switch(i) { + case CURL_SSLVERSION_TLSv1_0: + *enabled_protocols |= SP_PROT_TLS1_0_CLIENT; + break; + case CURL_SSLVERSION_TLSv1_1: + *enabled_protocols |= SP_PROT_TLS1_1_CLIENT; + break; + case CURL_SSLVERSION_TLSv1_2: + *enabled_protocols |= SP_PROT_TLS1_2_CLIENT; + break; + case CURL_SSLVERSION_TLSv1_3: + + /* Windows Server 2022 or newer */ + if(curlx_verify_windows_version(10, 0, 20348, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) { + *enabled_protocols |= SP_PROT_TLS1_3_CLIENT; + break; + } + else { /* Windows 10 or older */ + failf(data, "schannel: TLS 1.3 not supported on Windows 10 or older"); + return CURLE_SSL_CONNECT_ERROR; + } + } + } + return CURLE_OK; +} + +#define CIPHEROPTION(x) { #x, x } + +struct algo { + const char *name; + int id; +}; + +static const struct algo algs[] = { + CIPHEROPTION(CALG_MD2), + CIPHEROPTION(CALG_MD4), + CIPHEROPTION(CALG_MD5), + CIPHEROPTION(CALG_SHA), + CIPHEROPTION(CALG_SHA1), + CIPHEROPTION(CALG_MAC), + CIPHEROPTION(CALG_RSA_SIGN), + CIPHEROPTION(CALG_DSS_SIGN), + CIPHEROPTION(CALG_NO_SIGN), + CIPHEROPTION(CALG_RSA_KEYX), + CIPHEROPTION(CALG_DES), + CIPHEROPTION(CALG_3DES_112), + CIPHEROPTION(CALG_3DES), + CIPHEROPTION(CALG_DESX), + CIPHEROPTION(CALG_RC2), + CIPHEROPTION(CALG_RC4), + CIPHEROPTION(CALG_SEAL), + CIPHEROPTION(CALG_DH_SF), + CIPHEROPTION(CALG_DH_EPHEM), + CIPHEROPTION(CALG_AGREEDKEY_ANY), + CIPHEROPTION(CALG_HUGHES_MD5), + CIPHEROPTION(CALG_SKIPJACK), + CIPHEROPTION(CALG_TEK), + CIPHEROPTION(CALG_CYLINK_MEK), /* spellchecker:disable-line */ + CIPHEROPTION(CALG_SSL3_SHAMD5), + CIPHEROPTION(CALG_SSL3_MASTER), + CIPHEROPTION(CALG_SCHANNEL_MASTER_HASH), + CIPHEROPTION(CALG_SCHANNEL_MAC_KEY), + CIPHEROPTION(CALG_SCHANNEL_ENC_KEY), + CIPHEROPTION(CALG_PCT1_MASTER), + CIPHEROPTION(CALG_SSL2_MASTER), + CIPHEROPTION(CALG_TLS1_MASTER), + CIPHEROPTION(CALG_RC5), + CIPHEROPTION(CALG_HMAC), + CIPHEROPTION(CALG_TLS1PRF), + CIPHEROPTION(CALG_HASH_REPLACE_OWF), + CIPHEROPTION(CALG_AES_128), + CIPHEROPTION(CALG_AES_192), + CIPHEROPTION(CALG_AES_256), + CIPHEROPTION(CALG_AES), + CIPHEROPTION(CALG_SHA_256), + CIPHEROPTION(CALG_SHA_384), + CIPHEROPTION(CALG_SHA_512), + CIPHEROPTION(CALG_ECDH), +/* Offered by mingw-w64 v4+, MS SDK 6.0A/VS2008+ */ +#ifdef CALG_ECMQV + CIPHEROPTION(CALG_ECMQV), +#endif + CIPHEROPTION(CALG_ECDSA), +/* Offered by mingw-w64 v7+, MS SDK 7.0A/VS2010+ */ +#ifdef CALG_ECDH_EPHEM + CIPHEROPTION(CALG_ECDH_EPHEM), +#endif + { NULL, 0 }, +}; + +static int get_alg_id_by_name(const char *name) +{ + const char *nameEnd = strchr(name, ':'); + size_t n = nameEnd ? (size_t)(nameEnd - name) : strlen(name); + int i; + + for(i = 0; algs[i].name; i++) { + if((n == strlen(algs[i].name) && !strncmp(algs[i].name, name, n))) + return algs[i].id; + } + return 0; /* not found */ +} + +#define NUM_CIPHERS 47 /* There are a maximum of 47 options listed above */ + +static CURLcode set_ssl_ciphers(SCHANNEL_CRED *schannel_cred, char *ciphers, + ALG_ID *algIds) +{ + const char *startCur = ciphers; + int algCount = 0; + while(startCur && *startCur && (algCount < NUM_CIPHERS)) { + curl_off_t alg; + if(curlx_str_number(&startCur, &alg, INT_MAX) || !alg) + alg = get_alg_id_by_name(startCur); + + if(alg) + algIds[algCount++] = (ALG_ID)alg; + else if(!strncmp(startCur, "USE_STRONG_CRYPTO", + CURL_CSTRLEN("USE_STRONG_CRYPTO")) || + !strncmp(startCur, "SCH_USE_STRONG_CRYPTO", + CURL_CSTRLEN("SCH_USE_STRONG_CRYPTO"))) + schannel_cred->dwFlags |= SCH_USE_STRONG_CRYPTO; + else + return CURLE_SSL_CIPHER; + startCur = strchr(startCur, ':'); + if(startCur) + startCur++; + } + schannel_cred->palgSupportedAlgs = algIds; + schannel_cred->cSupportedAlgs = (DWORD)algCount; + return CURLE_OK; +} + +/* Function allocates memory for store_path only if CURLE_OK is returned */ +static CURLcode get_cert_location(TCHAR *path, DWORD *store_name, + TCHAR **store_path, TCHAR **thumbprint) +{ + TCHAR *sep; + TCHAR *store_path_start; + size_t store_name_len; + + sep = _tcschr(path, _TEXT('\\')); + if(!sep) + return CURLE_SSL_CERTPROBLEM; + + store_name_len = sep - path; + + if(_tcsncmp(path, _TEXT("CurrentUser"), store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_CURRENT_USER; + else if(_tcsncmp(path, _TEXT("LocalMachine"), store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE; + else if(_tcsncmp(path, _TEXT("CurrentService"), store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_CURRENT_SERVICE; + else if(_tcsncmp(path, _TEXT("Services"), store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_SERVICES; + else if(_tcsncmp(path, _TEXT("Users"), store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_USERS; + else if(_tcsncmp(path, _TEXT("CurrentUserGroupPolicy"), store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY; + else if(_tcsncmp(path, _TEXT("LocalMachineGroupPolicy"), store_name_len) == + 0) + *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY; + else if(_tcsncmp(path, _TEXT("LocalMachineEnterprise"), store_name_len) == 0) + *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE; + else + return CURLE_SSL_CERTPROBLEM; + + store_path_start = sep + 1; + + sep = _tcschr(store_path_start, _TEXT('\\')); + if(!sep) + return CURLE_SSL_CERTPROBLEM; + + *thumbprint = sep + 1; + if(_tcslen(*thumbprint) != CERT_THUMBPRINT_STR_LEN) + return CURLE_SSL_CERTPROBLEM; + + *sep = _TEXT('\0'); + *store_path = curlx_tcsdup(store_path_start); + *sep = _TEXT('\\'); + if(!*store_path) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static CURLcode get_client_cert(struct Curl_cfilter *cf, + struct Curl_easy *data, + HCERTSTORE *out_cert_store, + PCCERT_CONTEXT *out_cert_context) +{ + struct ssl_primary_config *sslc = Curl_ssl_cf_get_primary_config(cf); + PCCERT_CONTEXT client_cert = NULL; + HCERTSTORE client_cert_store = NULL; + CURLcode result = CURLE_OK; + + if(sslc->clientcert || sslc->cert_blob) { + DWORD cert_store_name = 0; + TCHAR *cert_store_path = NULL; + TCHAR *cert_thumbprint_str = NULL; + TCHAR cert_thumbprint_buf[CERT_THUMBPRINT_STR_LEN + 1]; + CRYPT_HASH_BLOB cert_thumbprint; + BYTE cert_thumbprint_data[CERT_THUMBPRINT_DATA_LEN]; + HCERTSTORE cert_store = NULL; + FILE *fInCert = NULL; + void *certdata = NULL; + size_t certsize = 0; + bool blob = !!sslc->cert_blob; + + if(blob) { + certdata = sslc->cert_blob->data; + certsize = sslc->cert_blob->len; + } + else { + TCHAR *cert_path = + curlx_convert_UTF8_to_tchar(sslc->clientcert); + if(!cert_path) + return CURLE_OUT_OF_MEMORY; + + result = get_cert_location(cert_path, &cert_store_name, + &cert_store_path, &cert_thumbprint_str); + + /* 'cert_thumbprint_str' points in to the allocated 'cert_path', copy + the data. The string is verified to be CERT_THUMBPRINT_STR_LEN bytes + long within the get_cert_location() function. */ + if(!result && cert_thumbprint_str) { + memcpy(cert_thumbprint_buf, cert_thumbprint_str, + sizeof(cert_thumbprint_buf)); + cert_thumbprint_str = cert_thumbprint_buf; + } + + curlx_free(cert_path); + if(result && (sslc->clientcert[0] != '\0')) + fInCert = curlx_fopen(sslc->clientcert, "rb"); + + if(result && !fInCert) { + failf(data, "schannel: Failed to get certificate location" + " or file for %s", + sslc->clientcert); + return result; + } + } + + if((fInCert || blob) && sslc->cert_type && + !curl_strequal(sslc->cert_type, "P12")) { + failf(data, "schannel: certificate format compatibility error " + "for %s", + blob ? "(memory blob)" : sslc->clientcert); + curlx_free(cert_store_path); + if(fInCert) + curlx_fclose(fInCert); + return CURLE_SSL_CERTPROBLEM; + } + + if(fInCert || blob) { + /* Reading a .p12 or .pfx file, like the example at bottom of + https://learn.microsoft.com/archive/msdn-technet-forums/3e7bc95f-b21a-4bcd-bd2c-7f996718cae5 + */ + CRYPT_DATA_BLOB datablob; + WCHAR *pszPassword; + size_t pwd_len = 0; + int cert_find_flags; + const char *cert_showfilename_error = blob ? + "(memory blob)" : sslc->clientcert; + curlx_free(cert_store_path); + if(fInCert) { + long cert_tell = 0; + bool continue_reading = fseek(fInCert, 0, SEEK_END) == 0; + if(continue_reading) { + cert_tell = ftell(fInCert); + if(cert_tell < 0) + continue_reading = FALSE; + else + certsize = (size_t)cert_tell; + } + if(continue_reading) + continue_reading = fseek(fInCert, 0, SEEK_SET) == 0; + if(continue_reading && (certsize < CURL_MAX_INPUT_LENGTH)) + certdata = curlx_malloc(certsize + 1); + if(!certdata || ((int)fread(certdata, certsize, 1, fInCert) != 1)) + continue_reading = FALSE; + curlx_fclose(fInCert); + if(!continue_reading) { + failf(data, "schannel: Failed to read cert file %s", + sslc->clientcert); + curlx_free(certdata); + return CURLE_SSL_CERTPROBLEM; + } + } + + /* Convert key-pair data to the in-memory certificate store */ + datablob.pbData = (BYTE *)certdata; + datablob.cbData = (DWORD)certsize; + + if(sslc->key_passwd) + pwd_len = strlen(sslc->key_passwd); + pszPassword = curlx_malloc(sizeof(WCHAR) * (pwd_len + 1)); + if(pszPassword) { + int str_w_len = 0; + if(pwd_len > 0) + str_w_len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, + sslc->key_passwd, (int)pwd_len, + pszPassword, (int)(pwd_len + 1)); + + if((str_w_len >= 0) && (str_w_len <= (int)pwd_len)) + pszPassword[str_w_len] = 0; + else + pszPassword[0] = 0; + + cert_store = PFXImportCertStore(&datablob, pszPassword, + PKCS12_NO_PERSIST_KEY); + curlx_memzero(pszPassword, sizeof(WCHAR) * (pwd_len + 1)); + curlx_free(pszPassword); + } + if(!blob) + curlx_free(certdata); + if(!cert_store) { + DWORD errorcode = GetLastError(); + if(errorcode == ERROR_INVALID_PASSWORD) + failf(data, "schannel: Failed to import cert file %s, " + "password is bad", + cert_showfilename_error); + else + failf(data, "schannel: Failed to import cert file %s, " + "last error is 0x%08lx", + cert_showfilename_error, errorcode); + return CURLE_SSL_CERTPROBLEM; + } + + /* CERT_FIND_HAS_PRIVATE_KEY is only available in Windows 8 / Server + 2012, (NT 6.2). For older versions we use CURL_FIND_ANY. */ + if(curlx_verify_windows_version(6, 2, 0, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) + cert_find_flags = CERT_FIND_HAS_PRIVATE_KEY; + else + cert_find_flags = CERT_FIND_ANY; + + client_cert = + CertFindCertificateInStore(cert_store, + X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, + cert_find_flags, NULL, NULL); + + if(!client_cert) { + failf(data, "schannel: Failed to get certificate from file %s" + ", last error is 0x%08lx", + cert_showfilename_error, GetLastError()); + CertCloseStore(cert_store, 0); + return CURLE_SSL_CERTPROBLEM; + } + } + else { + cert_store = + CertOpenStore( +#ifdef UNICODE + CERT_STORE_PROV_SYSTEM_W, +#else + CERT_STORE_PROV_SYSTEM_A, +#endif + 0, + (HCRYPTPROV)NULL, + CERT_STORE_OPEN_EXISTING_FLAG | cert_store_name, + cert_store_path); + if(!cert_store) { + char *path_utf8 = + curlx_convert_tchar_to_UTF8(cert_store_path); + failf(data, "schannel: Failed to open cert store %lx %s, " + "last error is 0x%08lx", + cert_store_name, (path_utf8 ? path_utf8 : "(unknown)"), + GetLastError()); + curlx_free(cert_store_path); + curlx_free(path_utf8); + return CURLE_SSL_CERTPROBLEM; + } + curlx_free(cert_store_path); + + cert_thumbprint.pbData = cert_thumbprint_data; + cert_thumbprint.cbData = CERT_THUMBPRINT_DATA_LEN; + + if(!CryptStringToBinary(cert_thumbprint_str, + CERT_THUMBPRINT_STR_LEN, + CRYPT_STRING_HEX, + cert_thumbprint_data, + &cert_thumbprint.cbData, + NULL, NULL)) { + CertCloseStore(cert_store, 0); + return CURLE_SSL_CERTPROBLEM; + } + + client_cert = + CertFindCertificateInStore(cert_store, + X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, + CERT_FIND_HASH, &cert_thumbprint, NULL); + if(!client_cert) { + /* CRYPT_E_NOT_FOUND / E_INVALIDARG */ + CertCloseStore(cert_store, 0); + failf(data, "schannel: client cert not found in cert store"); + return CURLE_SSL_CERTPROBLEM; + } + } + client_cert_store = cert_store; + } + + *out_cert_store = client_cert_store; + *out_cert_context = client_cert; + + return CURLE_OK; +} + +static CURLcode acquire_sspi_handle(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct schannel_ssl_backend_data *backend, + PCCERT_CONTEXT client_cert, + DWORD flags, + DWORD enabled_protocols) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + SECURITY_STATUS sspi_status = SEC_E_OK; + CURLcode result; + + /* We support TLS 1.3 starting in Windows Server 2022 or later + * (OS build 20348) */ + if(!conn_config->cipher_list && + curlx_verify_windows_version(10, 0, 20348, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) { + + SCH_CREDENTIALS credentials = { 0 }; + TLS_PARAMETERS tls_parameters = { 0 }; + CRYPTO_SETTINGS crypto_settings[1]; + PCCERT_CONTEXT client_certs[1]; + + if(client_cert) + client_certs[0] = client_cert; + else + client_certs[0] = NULL; + + memset(crypto_settings, 0, sizeof(crypto_settings)); + + tls_parameters.pDisabledCrypto = crypto_settings; + + /* The number of blocked suites */ + tls_parameters.cDisabledCrypto = (DWORD)0; + credentials.pTlsParameters = &tls_parameters; + credentials.cTlsParameters = 1; + + credentials.dwVersion = SCH_CREDENTIALS_VERSION; + credentials.dwFlags = flags | SCH_USE_STRONG_CRYPTO; + + credentials.pTlsParameters->grbitDisabledProtocols = ~enabled_protocols; + + if(client_certs[0]) { + credentials.cCreds = 1; + credentials.paCred = client_certs; + } + + sspi_status = + Curl_pSecFn->AcquireCredentialsHandle(NULL, CURL_UNCONST(UNISP_NAME), + SECPKG_CRED_OUTBOUND, NULL, + &credentials, NULL, NULL, + &backend->cred->cred_handle, NULL); + } + else { + /* Pre-Windows 10 1809 or the user set a legacy algorithm list. + Schannel does not negotiate TLS 1.3 when SCHANNEL_CRED is used. */ + ALG_ID algIds[NUM_CIPHERS]; + char *ciphers = conn_config->cipher_list; + SCHANNEL_CRED schannel_cred = { 0 }; + PCCERT_CONTEXT client_certs[1]; + + if(client_cert) + client_certs[0] = client_cert; + else + client_certs[0] = NULL; + + schannel_cred.dwVersion = SCHANNEL_CRED_VERSION; + schannel_cred.dwFlags = flags; + schannel_cred.grbitEnabledProtocols = enabled_protocols; + + if(ciphers) { + if((enabled_protocols & SP_PROT_TLS1_3_CLIENT)) { + if(!(enabled_protocols & ~SP_PROT_TLS1_3_CLIENT)) { + failf(data, "schannel: TLS 1.3 is not supported with a cipher list; " + "remove the cipher list or allow a lower TLS version"); + return CURLE_SSL_CONNECT_ERROR; + } + infof(data, "schannel: WARNING: This version of Schannel " + "negotiates a less-secure TLS version than TLS 1.3 because the " + "user set an algorithm cipher list."); + } + result = set_ssl_ciphers(&schannel_cred, ciphers, algIds); + if(result) { + failf(data, "schannel: Failed setting algorithm cipher list"); + return result; + } + } + else { + schannel_cred.dwFlags = flags | SCH_USE_STRONG_CRYPTO; + } + + if(client_certs[0]) { + schannel_cred.cCreds = 1; + schannel_cred.paCred = client_certs; + } + + sspi_status = + Curl_pSecFn->AcquireCredentialsHandle(NULL, CURL_UNCONST(UNISP_NAME), + SECPKG_CRED_OUTBOUND, NULL, + &schannel_cred, NULL, NULL, + &backend->cred->cred_handle, NULL); + } + + if(sspi_status != SEC_E_OK) { + char buffer[STRERROR_LEN]; + failf(data, "schannel: AcquireCredentialsHandle failed: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + switch(sspi_status) { + case SEC_E_INSUFFICIENT_MEMORY: + return CURLE_OUT_OF_MEMORY; + case SEC_E_NO_CREDENTIALS: + case SEC_E_SECPKG_NOT_FOUND: + case SEC_E_NOT_OWNER: + case SEC_E_UNKNOWN_CREDENTIALS: + case SEC_E_INTERNAL_ERROR: + default: + return CURLE_SSL_CONNECT_ERROR; + } + } + + return CURLE_OK; +} + +static CURLcode schannel_acquire_credential_handle(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + + PCCERT_CONTEXT client_cert = NULL; + HCERTSTORE client_cert_store = NULL; + CURLcode result; + + /* setup Schannel API options */ + DWORD flags = 0; + DWORD enabled_protocols = 0; + + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + + DEBUGASSERT(backend); + + if(conn_config->verifypeer) { + if(backend->use_manual_cred_validation) + flags = SCH_CRED_MANUAL_CRED_VALIDATION; + else + flags = SCH_CRED_AUTO_CRED_VALIDATION; + + if(ssl_config->no_revoke) { + flags |= SCH_CRED_IGNORE_NO_REVOCATION_CHECK | + SCH_CRED_IGNORE_REVOCATION_OFFLINE; + + DEBUGF(infof(data, "schannel: disabled server certificate revocation " + "checks")); + } + else if(ssl_config->revoke_best_effort) { + flags |= SCH_CRED_IGNORE_NO_REVOCATION_CHECK | + SCH_CRED_IGNORE_REVOCATION_OFFLINE | + SCH_CRED_REVOCATION_CHECK_CHAIN; + + DEBUGF(infof(data, "schannel: ignore revocation offline errors")); + } + else { + flags |= SCH_CRED_REVOCATION_CHECK_CHAIN; + + DEBUGF(infof(data, "schannel: checking server certificate revocation")); + } + } + else { + flags = SCH_CRED_MANUAL_CRED_VALIDATION | + SCH_CRED_IGNORE_NO_REVOCATION_CHECK | + SCH_CRED_IGNORE_REVOCATION_OFFLINE; + DEBUGF(infof(data, "schannel: disabled server cert revocation checks")); + } + + if(!conn_config->verifyhost) { + flags |= SCH_CRED_NO_SERVERNAME_CHECK; + DEBUGF(infof(data, "schannel: verifyhost setting prevents Schannel from " + "comparing the supplied target name with the subject " + "names in server certificates.")); + } + + if(!ssl_config->auto_client_cert) { + flags &= ~(DWORD)SCH_CRED_USE_DEFAULT_CREDS; + flags |= SCH_CRED_NO_DEFAULT_CREDS; + infof(data, "schannel: disabled automatic use of client certificate"); + } + else + infof(data, "schannel: enabled automatic use of client certificate"); + + DEBUGASSERT(conn_config->version != CURL_SSLVERSION_DEFAULT); + switch(conn_config->version) { + case CURL_SSLVERSION_TLSv1: + case CURL_SSLVERSION_TLSv1_0: + case CURL_SSLVERSION_TLSv1_1: + case CURL_SSLVERSION_TLSv1_2: + case CURL_SSLVERSION_TLSv1_3: { + result = schannel_set_ssl_version_min_max(&enabled_protocols, cf, data); + if(result) + return result; + break; + } + case CURL_SSLVERSION_SSLv3: + case CURL_SSLVERSION_SSLv2: + failf(data, "SSL versions not supported"); + return CURLE_NOT_BUILT_IN; + default: + failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); + return CURLE_SSL_CONNECT_ERROR; + } + + result = get_client_cert(cf, data, &client_cert_store, &client_cert); + if(result) + return result; + + /* allocate memory for the reusable credential handle */ + backend->cred = (struct Curl_schannel_cred *) + curlx_calloc(1, sizeof(struct Curl_schannel_cred)); + if(!backend->cred) { + failf(data, "schannel: unable to allocate memory"); + + if(client_cert) + CertFreeCertificateContext(client_cert); + if(client_cert_store) + CertCloseStore(client_cert_store, 0); + + return CURLE_OUT_OF_MEMORY; + } + backend->cred->refcount = 1; + + /* Since we did not persist the key, we need to extend the store's + * lifetime until the end of the connection + */ + backend->cred->client_cert_store = client_cert_store; + + result = acquire_sspi_handle(cf, data, backend, client_cert, + flags, enabled_protocols); + + if(client_cert) + CertFreeCertificateContext(client_cert); + + return result; +} + +static CURLcode schannel_connect_step1(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + size_t written = 0; + struct ssl_connect_data *connssl = cf->ctx; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + SecBuffer outbuf; + SecBufferDesc outbuf_desc; + SecBuffer inbuf; + SecBufferDesc inbuf_desc; + unsigned char alpn_buffer[128]; + SECURITY_STATUS sspi_status = SEC_E_OK; + CURLcode result; + + DEBUGASSERT(backend); + DEBUGF(infof(data, "schannel: SSL/TLS connection with %s port %d (step 1/3)", + connssl->peer.origin->hostname, connssl->peer.origin->port)); + + backend->use_alpn = connssl->alpn && s_win_has_alpn; + + if(conn_config->CAfile || conn_config->ca_info_blob) { + if(curlx_verify_windows_version(6, 1, 0, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) { + backend->use_manual_cred_validation = TRUE; + } + else { + failf(data, "schannel: this version of Windows is too old to support " + "certificate verification via CA bundle file."); + return CURLE_SSL_CACERT_BADFILE; + } + } + else + backend->use_manual_cred_validation = FALSE; + + backend->cred = NULL; + + /* check for an existing reusable credential handle */ + if(Curl_ssl_scache_use(cf, data)) { + struct Curl_schannel_cred *old_cred; + Curl_ssl_scache_lock(data); + old_cred = Curl_ssl_scache_get_obj(cf, data, connssl->peer.scache_key); + if(old_cred) { + backend->cred = old_cred; + DEBUGF(infof(data, "schannel: reusing existing credential handle")); + + /* increment the reference counter of the credential/session handle */ + backend->cred->refcount++; + DEBUGF(infof(data, + "schannel: incremented credential handle refcount = %d", + backend->cred->refcount)); + } + Curl_ssl_scache_unlock(data); + } + + if(!backend->cred) { + char *snihost; + result = schannel_acquire_credential_handle(cf, data); + if(result || !backend->cred) + return result; + /* schannel_acquire_credential_handle() sets backend->cred accordingly or + it returns error otherwise. */ + + /* A hostname associated with the credential is needed by + InitializeSecurityContext for SNI and other reasons. */ + snihost = connssl->peer.sni ? + connssl->peer.sni : connssl->peer.origin->hostname; + backend->cred->sni_hostname = curlx_convert_UTF8_to_tchar(snihost); + if(!backend->cred->sni_hostname) + return CURLE_OUT_OF_MEMORY; + } + + /* Warn if SNI is disabled due to use of an IP address */ + if(connssl->peer.type != CURL_SSL_PEER_DNS) { + infof(data, "schannel: using IP address, SNI is not supported by OS."); + } + + if(backend->use_alpn) { + int cur = 0; + int list_start_index = 0; + unsigned int *extension_len = NULL; + unsigned short *list_len = NULL; + struct alpn_proto_buf proto; + + /* The first four bytes is an unsigned int indicating number + of bytes of data in the rest of the buffer. */ + extension_len = (unsigned int *)(void *)&alpn_buffer[cur]; + cur += (int)sizeof(unsigned int); + + /* The next four bytes are an indicator that this buffer contains + ALPN data, as opposed to NPN, for example. */ + *(unsigned int *)(void *)&alpn_buffer[cur] = + SecApplicationProtocolNegotiationExt_ALPN; + cur += (int)sizeof(unsigned int); + + /* The next two bytes is an unsigned short indicating the number + of bytes used to list the preferred protocols. */ + list_len = (unsigned short *)(void *)&alpn_buffer[cur]; + cur += (int)sizeof(unsigned short); + + list_start_index = cur; + + result = Curl_alpn_to_proto_buf(&proto, connssl->alpn); + if(result) { + failf(data, "Error setting ALPN"); + return CURLE_SSL_CONNECT_ERROR; + } + memcpy(&alpn_buffer[cur], proto.data, proto.len); + cur += proto.len; + + *list_len = curlx_uitous(cur - list_start_index); + *extension_len = (unsigned int)(*list_len + + sizeof(unsigned int) + sizeof(unsigned short)); + + InitSecBuffer(&inbuf, SECBUFFER_APPLICATION_PROTOCOLS, alpn_buffer, cur); + InitSecBufferDesc(&inbuf_desc, &inbuf, 1); + + Curl_alpn_to_proto_str(&proto, connssl->alpn); + infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); + } + else { + InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&inbuf_desc, &inbuf, 1); + } + + /* setup output buffer */ + InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&outbuf_desc, &outbuf, 1); + + /* security request flags */ + backend->req_flags = + ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | + ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY | + ISC_REQ_STREAM | + (!ssl_config->auto_client_cert ? ISC_REQ_USE_SUPPLIED_CREDS : 0); + + /* allocate memory for the security context handle */ + backend->ctxt = (struct Curl_schannel_ctxt *) + curlx_calloc(1, sizeof(struct Curl_schannel_ctxt)); + if(!backend->ctxt) { + failf(data, "schannel: unable to allocate memory"); + return CURLE_OUT_OF_MEMORY; + } + + /* Schannel InitializeSecurityContext: + https://learn.microsoft.com/windows/win32/api/sspi/nf-sspi-initializesecuritycontextw + + At the moment we do not pass inbuf unless we are using ALPN since we only + use it for that, and WINE (for which we currently disable ALPN) is giving + us problems with inbuf regardless. https://github.com/curl/curl/issues/983 + */ + sspi_status = Curl_pSecFn->InitializeSecurityContext( + &backend->cred->cred_handle, NULL, backend->cred->sni_hostname, + backend->req_flags, 0, 0, + (backend->use_alpn ? &inbuf_desc : NULL), + 0, &backend->ctxt->ctxt_handle, + &outbuf_desc, &backend->ret_flags, NULL); + + if(sspi_status != SEC_I_CONTINUE_NEEDED) { + char buffer[STRERROR_LEN]; + curlx_safefree(backend->ctxt); + switch(sspi_status) { + case SEC_E_INSUFFICIENT_MEMORY: + failf(data, "schannel: initial InitializeSecurityContext failed: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + return CURLE_OUT_OF_MEMORY; + case SEC_E_WRONG_PRINCIPAL: + failf(data, "schannel: SNI or certificate check failed: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + return CURLE_PEER_FAILED_VERIFICATION; +#if 0 + case SEC_E_INVALID_HANDLE: + case SEC_E_INVALID_TOKEN: + case SEC_E_LOGON_DENIED: + case SEC_E_TARGET_UNKNOWN: + case SEC_E_NO_AUTHENTICATING_AUTHORITY: + case SEC_E_INTERNAL_ERROR: + case SEC_E_NO_CREDENTIALS: + case SEC_E_UNSUPPORTED_FUNCTION: + case SEC_E_APPLICATION_PROTOCOL_MISMATCH: +#endif + default: + failf(data, "schannel: initial InitializeSecurityContext failed: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + return CURLE_SSL_CONNECT_ERROR; + } + } + + DEBUGF(infof(data, "schannel: sending initial handshake data: " + "sending %lu bytes.", outbuf.cbBuffer)); + + /* send initial handshake data which is now stored in output buffer */ + result = Curl_conn_cf_send(cf->next, data, + (const uint8_t *)outbuf.pvBuffer, + outbuf.cbBuffer, FALSE, + &written); + Curl_pSecFn->FreeContextBuffer(outbuf.pvBuffer); + if(result || (outbuf.cbBuffer != written)) { + failf(data, "schannel: failed to send initial handshake data: " + "sent %zu of %lu bytes", written, outbuf.cbBuffer); + return CURLE_SSL_CONNECT_ERROR; + } + + DEBUGF(infof(data, "schannel: sent initial handshake data: " + "sent %zu bytes", written)); + + backend->recv_unrecoverable_err = CURLE_OK; + backend->recv_sspi_close_notify = FALSE; + backend->recv_connection_closed = FALSE; + backend->recv_renegotiating = FALSE; + backend->renegotiate_state.started = FALSE; + backend->encdata_is_incomplete = FALSE; + + /* continue to second handshake step */ + connssl->connecting_state = ssl_connect_2; + + return CURLE_OK; +} + +static CURLcode schannel_error(struct Curl_easy *data, + SECURITY_STATUS sspi_status) +{ + char buffer[STRERROR_LEN]; + switch(sspi_status) { + case SEC_E_INSUFFICIENT_MEMORY: + failf(data, "schannel: next InitializeSecurityContext failed: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + return CURLE_OUT_OF_MEMORY; + case SEC_E_WRONG_PRINCIPAL: + failf(data, "schannel: SNI or certificate check failed: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + return CURLE_PEER_FAILED_VERIFICATION; + case SEC_E_UNTRUSTED_ROOT: + failf(data, "schannel: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + return CURLE_PEER_FAILED_VERIFICATION; +#if 0 + case SEC_E_INVALID_HANDLE: + case SEC_E_INVALID_TOKEN: + case SEC_E_LOGON_DENIED: + case SEC_E_TARGET_UNKNOWN: + case SEC_E_NO_AUTHENTICATING_AUTHORITY: + case SEC_E_INTERNAL_ERROR: + case SEC_E_NO_CREDENTIALS: + case SEC_E_UNSUPPORTED_FUNCTION: + case SEC_E_APPLICATION_PROTOCOL_MISMATCH: +#endif + default: + failf(data, "schannel: next InitializeSecurityContext failed: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + return CURLE_SSL_CONNECT_ERROR; + } +} + +static CURLcode schannel_pkp_pin_peer_pubkey(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *pinnedpubkey) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + CERT_CONTEXT *pCertContextServer = NULL; + + /* Result is returned to caller */ + CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; + + DEBUGASSERT(backend); + + /* if a path was not specified, do not pin */ + if(!pinnedpubkey) + return CURLE_OK; + + do { + SECURITY_STATUS sspi_status; + const char *x509_der; + DWORD x509_der_len; + struct Curl_X509certificate x509_parsed; + struct Curl_asn1Element *pubkey; + + sspi_status = + Curl_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle, + SECPKG_ATTR_REMOTE_CERT_CONTEXT, + &pCertContextServer); + + if((sspi_status != SEC_E_OK) || !pCertContextServer) { + char buffer[STRERROR_LEN]; + failf(data, "schannel: Failed to read remote certificate context: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + break; /* failed */ + } + + if(!(((pCertContextServer->dwCertEncodingType & X509_ASN_ENCODING) != 0) && + (pCertContextServer->cbCertEncoded > 0))) + break; + + x509_der = (const char *)pCertContextServer->pbCertEncoded; + x509_der_len = pCertContextServer->cbCertEncoded; + memset(&x509_parsed, 0, sizeof(x509_parsed)); + if(Curl_parseX509(&x509_parsed, x509_der, x509_der + x509_der_len)) + break; + + pubkey = &x509_parsed.subjectPublicKeyInfo; + if(!pubkey->header || pubkey->end <= pubkey->header) { + failf(data, "SSL: failed retrieving public key from server certificate"); + break; + } + + result = Curl_pin_peer_pubkey(data, + pinnedpubkey, + (const unsigned char *)pubkey->header, + (size_t)(pubkey->end - pubkey->header)); + if(result) { + failf(data, "SSL: public key does not match pinned public key"); + } + } while(0); + + if(pCertContextServer) + CertFreeCertificateContext(pCertContextServer); + + return result; +} + +static CURLcode ensure_encoding_size(struct Curl_easy *data, + struct sbuffer *encdata, + size_t min_length) +{ + size_t size; + DEBUGASSERT(encdata->length >= encdata->offset); + if(encdata->length < encdata->offset) + return CURLE_FAILED_INIT; + size = encdata->length - encdata->offset; + if(size < CURL_SCHANNEL_BUFFER_FREE_SIZE || encdata->length < min_length) { + unsigned char *buffer; + size_t length = encdata->offset + CURL_SCHANNEL_BUFFER_FREE_SIZE; + if(length < min_length) + length = min_length; + buffer = curlx_realloc(encdata->buffer, length); + if(!buffer) { + failf(data, "schannel: unable to re-allocate memory"); + return CURLE_OUT_OF_MEMORY; + } + + encdata->buffer = buffer; + encdata->length = length; + SCH_DEV(infof(data, "schannel: encdata.buffer resized %zu", + encdata->length)); + } + return CURLE_OK; +} + +static CURLcode ensure_decoding_size(struct Curl_easy *data, + struct sbuffer *decdata, + size_t nowsize, + size_t len) +{ + size_t size = nowsize > CURL_SCHANNEL_BUFFER_FREE_SIZE ? + nowsize : CURL_SCHANNEL_BUFFER_FREE_SIZE; + DEBUGASSERT(decdata->length >= decdata->offset); + if(decdata->length < decdata->offset) + return CURLE_FAILED_INIT; + else if(decdata->length - decdata->offset < size || + decdata->length < len) { + /* increase internal decrypted data buffer */ + size_t length = decdata->offset + size; + unsigned char *buffer; + /* make sure that the requested amount of data fits */ + if(length < len) + length = len; + + buffer = curlx_realloc(decdata->buffer, length); + if(!buffer) { + failf(data, "schannel: unable to re-allocate memory"); + return CURLE_OUT_OF_MEMORY; + } + decdata->buffer = buffer; + decdata->length = length; + } + return CURLE_OK; +} + +static CURLcode schannel_connect_step2(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + int i; + size_t nread = 0; + SecBuffer outbuf[3]; + SecBufferDesc outbuf_desc; + SecBuffer inbuf[2]; + SecBufferDesc inbuf_desc; + SECURITY_STATUS sspi_status = SEC_E_OK; + CURLcode result; + bool doread; + const char *pubkey_ptr; + + DEBUGASSERT(backend); + + doread = (connssl->io_need & CURL_SSL_IO_NEED_SEND) ? FALSE : TRUE; + connssl->io_need = CURL_SSL_IO_NEED_NONE; + + DEBUGF(infof(data, "schannel: SSL/TLS connection with %s port %d (step 2/3)", + connssl->peer.origin->hostname, connssl->peer.origin->port)); + + if(!backend->cred || !backend->ctxt) + return CURLE_SSL_CONNECT_ERROR; + + /* buffer to store previously received and decrypted data */ + if(!backend->decdata.buffer) { + backend->decdata.offset = 0; + backend->decdata.length = CURL_SCHANNEL_BUFFER_INIT_SIZE; + backend->decdata.buffer = curlx_malloc(backend->decdata.length); + if(!backend->decdata.buffer) { + failf(data, "schannel: unable to allocate memory"); + return CURLE_OUT_OF_MEMORY; + } + } + + /* buffer to store previously received and encrypted data */ + if(!backend->encdata.buffer) { + backend->encdata_is_incomplete = FALSE; + backend->encdata.offset = 0; + backend->encdata.length = CURL_SCHANNEL_BUFFER_INIT_SIZE; + backend->encdata.buffer = curlx_malloc(backend->encdata.length); + if(!backend->encdata.buffer) { + failf(data, "schannel: unable to allocate memory"); + return CURLE_OUT_OF_MEMORY; + } + } + + result = ensure_encoding_size(data, &backend->encdata, 0); + if(result) + return result; + + for(;;) { + if(doread) { + /* read encrypted handshake data from socket */ + result = Curl_conn_cf_recv(cf->next, data, + (char *)(backend->encdata.buffer + + backend->encdata.offset), + backend->encdata.length - + backend->encdata.offset, + &nread); + if(result == CURLE_AGAIN) { + if(!backend->encdata.offset || backend->encdata_is_incomplete) { + connssl->io_need = CURL_SSL_IO_NEED_RECV; + DEBUGF(infof(data, "schannel: failed to receive handshake, " + "need more data")); + return CURLE_OK; + } + else { + DEBUGF(infof(data, "schannel: no new handshake data received, " + "continuing to process existing handshake data")); + } + } + else if(result || (nread == 0)) { + failf(data, "schannel: failed to receive handshake, " + "SSL/TLS connection failed"); + return CURLE_SSL_CONNECT_ERROR; + } + else { + /* increase encrypted data buffer offset */ + backend->encdata.offset += nread; + backend->encdata_is_incomplete = FALSE; + SCH_DEV(infof(data, "schannel: encrypted data got %zu", nread)); + } + } + + SCH_DEV(infof(data, + "schannel: encrypted data buffer: offset %zu length %zu", + backend->encdata.offset, backend->encdata.length)); + + /* setup input buffers */ + InitSecBuffer(&inbuf[0], SECBUFFER_TOKEN, + curlx_malloc(backend->encdata.offset), + curlx_uztoul(backend->encdata.offset)); + InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&inbuf_desc, inbuf, 2); + + /* setup output buffers */ + InitSecBuffer(&outbuf[0], SECBUFFER_TOKEN, NULL, 0); + InitSecBuffer(&outbuf[1], SECBUFFER_ALERT, NULL, 0); + InitSecBuffer(&outbuf[2], SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&outbuf_desc, outbuf, 3); + + if(!inbuf[0].pvBuffer) { + failf(data, "schannel: unable to allocate memory"); + return CURLE_OUT_OF_MEMORY; + } + + /* copy received handshake data into input buffer */ + memcpy(inbuf[0].pvBuffer, backend->encdata.buffer, + backend->encdata.offset); + + /* The socket must be writable (or a poll error occurred) before we call + InitializeSecurityContext to continue processing the received TLS + records. This is because that function is not idempotent and we do not + support partial save/resume sending replies of handshake tokens. */ + if(!SOCKET_WRITABLE(Curl_conn_cf_get_socket(cf, data), 0)) { + SCH_DEV(infof(data, "schannel: handshake waiting for writable socket")); + connssl->io_need = CURL_SSL_IO_NEED_SEND; + curlx_free(inbuf[0].pvBuffer); + return CURLE_OK; + } + + sspi_status = Curl_pSecFn->InitializeSecurityContext( + &backend->cred->cred_handle, &backend->ctxt->ctxt_handle, + backend->cred->sni_hostname, backend->req_flags, + 0, 0, &inbuf_desc, 0, NULL, + &outbuf_desc, &backend->ret_flags, NULL); + + /* free buffer for received handshake data */ + curlx_safefree(inbuf[0].pvBuffer); + + /* check if the handshake was incomplete */ + switch(sspi_status) { + case SEC_E_INCOMPLETE_MESSAGE: + backend->encdata_is_incomplete = TRUE; + connssl->io_need = CURL_SSL_IO_NEED_RECV; + DEBUGF(infof(data, + "schannel: received incomplete message, need more data")); + return CURLE_OK; + + case SEC_I_CONTINUE_NEEDED: + case SEC_E_OK: + /* check if the handshake needs to be continued */ + result = CURLE_OK; + for(i = 0; i < 3; i++) { + /* search for handshake tokens that need to be sent */ + if(outbuf[i].BufferType == SECBUFFER_TOKEN && outbuf[i].cbBuffer > 0) { + size_t written = 0; + DEBUGF(infof(data, "schannel: sending next handshake data: " + "sending %lu bytes.", outbuf[i].cbBuffer)); + + /* send handshake token to server */ + result = Curl_conn_cf_send(cf->next, data, + (const uint8_t *)outbuf[i].pvBuffer, + outbuf[i].cbBuffer, + FALSE, &written); + if(result || (outbuf[i].cbBuffer != written)) { + failf(data, "schannel: failed to send next handshake data: " + "sent %zu of %lu bytes", written, outbuf[i].cbBuffer); + result = CURLE_SSL_CONNECT_ERROR; + } + } + } + for(i = 0; i < 3; i++) { + /* free obsolete buffer */ + if(outbuf[i].pvBuffer) + Curl_pSecFn->FreeContextBuffer(outbuf[i].pvBuffer); + } + if(result) + return result; + break; + + case SEC_I_INCOMPLETE_CREDENTIALS: + if(!(backend->req_flags & ISC_REQ_USE_SUPPLIED_CREDS)) { + /* If the server has requested a client certificate, attempt to + continue the handshake without one. This allows connections to + servers which request a client certificate but do not require + it. */ + backend->req_flags |= ISC_REQ_USE_SUPPLIED_CREDS; + connssl->io_need = CURL_SSL_IO_NEED_SEND; + DEBUGF(infof(data, + "schannel: a client certificate has been requested")); + return CURLE_OK; + } + FALLTHROUGH(); + + default: + return schannel_error(data, sspi_status); + } + + /* check if there was additional remaining encrypted data */ + if(inbuf[1].BufferType == SECBUFFER_EXTRA && inbuf[1].cbBuffer > 0) { + SCH_DEV(infof(data, "schannel: encrypted data length: %lu", + inbuf[1].cbBuffer)); + /* There are two cases where we could be getting extra data here: + 1. If we are renegotiating a connection and the handshake is already + complete (from the server perspective), it can encrypt app data + (not handshake data) in an extra buffer at this point. + 2. (sspi_status == SEC_I_CONTINUE_NEEDED) We are negotiating a + connection and this extra data is part of the handshake. + We should process the data immediately; waiting for the socket to + be ready may fail since the server is done sending handshake data. + */ + /* check if the remaining data is less than the total amount + and therefore begins after the already processed data */ + if(backend->encdata.offset > inbuf[1].cbBuffer) { + memmove(backend->encdata.buffer, + (backend->encdata.buffer + backend->encdata.offset) - + inbuf[1].cbBuffer, inbuf[1].cbBuffer); + backend->encdata.offset = inbuf[1].cbBuffer; + if(sspi_status == SEC_I_CONTINUE_NEEDED) { + doread = FALSE; + continue; + } + } + } + else { + backend->encdata.offset = 0; + } + break; + } + + /* check if the handshake needs to be continued */ + if(sspi_status == SEC_I_CONTINUE_NEEDED) { + connssl->io_need = CURL_SSL_IO_NEED_RECV; + return CURLE_OK; + } + + /* check if the handshake is complete */ + if(sspi_status == SEC_E_OK) { + connssl->connecting_state = ssl_connect_3; + DEBUGF(infof(data, "schannel: SSL/TLS handshake complete")); + } + +#ifndef CURL_DISABLE_PROXY + pubkey_ptr = Curl_ssl_cf_is_proxy(cf) ? + CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY_PROXY) : + CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY); +#else + pubkey_ptr = CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY); +#endif + if(pubkey_ptr) { + result = schannel_pkp_pin_peer_pubkey(cf, data, pubkey_ptr); + if(result) { + failf(data, "SSL: public key does not match pinned public key"); + return result; + } + } + + if(conn_config->verifypeer && backend->use_manual_cred_validation) { + /* Certificate verification also verifies the hostname if verifyhost */ + return Curl_verify_certificate(cf, data); + } + + /* Verify the hostname manually when certificate verification is disabled, + because in that case Schannel does not verify it. */ + if(!conn_config->verifypeer && conn_config->verifyhost) + return Curl_verify_host(cf, data); + + return CURLE_OK; +} + +static bool valid_cert_encoding(const CERT_CONTEXT *cert_context) +{ + return cert_context && + ((cert_context->dwCertEncodingType & X509_ASN_ENCODING) != 0) && + cert_context->pbCertEncoded && + (cert_context->cbCertEncoded > 0); +} + +typedef bool (*Read_crt_func)(const CERT_CONTEXT *ccert_context, + bool reverse_order, void *arg); + +static void traverse_cert_store(const CERT_CONTEXT *context, + Read_crt_func func, void *arg) +{ + const CERT_CONTEXT *current_context = NULL; + bool should_continue = TRUE; + bool first = TRUE; + bool reverse_order = FALSE; + while(should_continue && + (current_context = CertEnumCertificatesInStore( + context->hCertStore, + current_context)) != NULL) { + /* Windows 11 22H2 OS Build 22621.674 or higher enumerates certificates in + leaf-to-root order while all previous versions of Windows enumerate + certificates in root-to-leaf order. Determine the order of enumeration + by comparing SECPKG_ATTR_REMOTE_CERT_CONTEXT's pbCertContext with the + first certificate's pbCertContext. */ + if(first && context->pbCertEncoded != current_context->pbCertEncoded) + reverse_order = TRUE; + should_continue = func(current_context, reverse_order, arg); + first = FALSE; + } + + if(current_context) + CertFreeCertificateContext(current_context); +} + +static bool cert_counter_callback(const CERT_CONTEXT *ccert_context, + bool reverse_order, void *certs_count) +{ + (void)reverse_order; + if(valid_cert_encoding(ccert_context)) + (*(int *)certs_count)++; + if(*(int *)certs_count > MAX_ALLOWED_CERT_AMOUNT) + return FALSE; + return TRUE; +} + +struct Adder_args { + struct Curl_easy *data; + CURLcode result; + int idx; + int certs_count; +}; + +static bool add_cert_to_certinfo(const CERT_CONTEXT *ccert_context, + bool reverse_order, void *raw_arg) +{ + struct Adder_args *args = (struct Adder_args *)raw_arg; + args->result = CURLE_OK; + if(valid_cert_encoding(ccert_context)) { + const char *beg = (const char *)ccert_context->pbCertEncoded; + const char *end = beg + ccert_context->cbCertEncoded; + int insert_index = reverse_order ? (args->certs_count - 1) - args->idx : + args->idx; + args->result = Curl_extract_certinfo(args->data, insert_index, + beg, end); + args->idx++; + } + return args->result == CURLE_OK; +} + +static void schannel_session_free(void *sessionid) +{ + /* this is expected to be called under sessionid lock */ + struct Curl_schannel_cred *cred = sessionid; + + if(cred) { + cred->refcount--; + if(cred->refcount == 0) { + Curl_pSecFn->FreeCredentialsHandle(&cred->cred_handle); + curlx_free(cred->sni_hostname); + if(cred->client_cert_store) { + CertCloseStore(cred->client_cert_store, 0); + cred->client_cert_store = NULL; + } + curlx_safefree(cred); + } + } +} + +static CURLcode schannel_connect_step3(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + CURLcode result = CURLE_OK; + SECURITY_STATUS sspi_status = SEC_E_OK; + CERT_CONTEXT *ccert_context = NULL; + SecPkgContext_ApplicationProtocol alpn_result; + + DEBUGASSERT(connssl->connecting_state == ssl_connect_3); + DEBUGASSERT(backend); + + DEBUGF(infof(data, "schannel: SSL/TLS connection with %s port %d (step 3/3)", + connssl->peer.origin->hostname, connssl->peer.origin->port)); + + if(!backend->cred) + return CURLE_SSL_CONNECT_ERROR; + + /* check if the required context attributes are met */ + if(backend->ret_flags != backend->req_flags) { + if(!(backend->ret_flags & ISC_RET_SEQUENCE_DETECT)) + failf(data, "schannel: failed to setup sequence detection"); + if(!(backend->ret_flags & ISC_RET_REPLAY_DETECT)) + failf(data, "schannel: failed to setup replay detection"); + if(!(backend->ret_flags & ISC_RET_CONFIDENTIALITY)) + failf(data, "schannel: failed to setup confidentiality"); + if(!(backend->ret_flags & ISC_RET_ALLOCATED_MEMORY)) + failf(data, "schannel: failed to setup memory allocation"); + if(!(backend->ret_flags & ISC_RET_STREAM)) + failf(data, "schannel: failed to setup stream orientation"); + return CURLE_SSL_CONNECT_ERROR; + } + + if(backend->use_alpn) { + sspi_status = + Curl_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle, + SECPKG_ATTR_APPLICATION_PROTOCOL, + &alpn_result); + + if(sspi_status != SEC_E_OK) { + failf(data, "schannel: failed to retrieve ALPN result"); + return CURLE_SSL_CONNECT_ERROR; + } + + if(alpn_result.ProtoNegoStatus == + SecApplicationProtocolNegotiationStatus_Success) { + if(backend->recv_renegotiating && + connssl->negotiated.alpn && + strncmp(connssl->negotiated.alpn, + (const char *)alpn_result.ProtocolId, + alpn_result.ProtocolIdSize)) { + /* Renegotiation selected a different protocol now, we cannot + * deal with this */ + failf(data, "schannel: server selected an ALPN protocol too late"); + return CURLE_SSL_CONNECT_ERROR; + } + Curl_alpn_set_negotiated(cf, data, connssl, alpn_result.ProtocolId, + alpn_result.ProtocolIdSize); + } + else { + if(!backend->recv_renegotiating) + Curl_alpn_set_negotiated(cf, data, connssl, NULL, 0); + } + } + + /* save the current session data for possible reuse */ + if(Curl_ssl_scache_use(cf, data)) { + Curl_ssl_scache_lock(data); + /* Up ref count since call takes ownership */ + backend->cred->refcount++; + result = Curl_ssl_scache_add_obj(cf, data, connssl->peer.scache_key, + backend->cred, schannel_session_free); + Curl_ssl_scache_unlock(data); + if(result) + return result; + } + + if(ssl_config->certinfo) { + int certs_count = 0; + sspi_status = + Curl_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle, + SECPKG_ATTR_REMOTE_CERT_CONTEXT, + &ccert_context); + + if((sspi_status != SEC_E_OK) || !ccert_context) { + failf(data, "schannel: failed to retrieve remote cert context"); + return CURLE_PEER_FAILED_VERIFICATION; + } + + traverse_cert_store(ccert_context, cert_counter_callback, &certs_count); + if(certs_count > MAX_ALLOWED_CERT_AMOUNT) { + failf(data, "%d certificates is more than allowed (%d)", + certs_count, MAX_ALLOWED_CERT_AMOUNT); + CertFreeCertificateContext(ccert_context); + return CURLE_SSL_CONNECT_ERROR; + } + + result = Curl_ssl_init_certinfo(data, certs_count); + if(!result) { + struct Adder_args args; + args.data = data; + args.idx = 0; + args.certs_count = certs_count; + args.result = CURLE_OK; + traverse_cert_store(ccert_context, add_cert_to_certinfo, &args); + result = args.result; + } + CertFreeCertificateContext(ccert_context); + if(result) + return result; + } + + connssl->connecting_state = ssl_connect_done; + + return CURLE_OK; +} + +static CURLcode schannel_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + CURLcode result; + + /* check if the connection has already been established */ + if(ssl_connection_complete == connssl->state) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; + + if(connssl->connecting_state == ssl_connect_1) { + result = schannel_connect_step1(cf, data); + if(result) + return result; + } + + if(connssl->connecting_state == ssl_connect_2) { + result = schannel_connect_step2(cf, data); + if(result) + return result; + } + + if(connssl->connecting_state == ssl_connect_3) { + result = schannel_connect_step3(cf, data); + if(result) + return result; + } + + if(connssl->connecting_state == ssl_connect_done) { + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + DEBUGASSERT(backend); + + if(Curl_pSecFn->QueryContextAttributes( + &backend->ctxt->ctxt_handle, + SECPKG_ATTR_STREAM_SIZES, + &backend->stream_sizes)) { + failf(data, "schannel: failed getting stream sizes"); + return CURLE_SSL_CONNECT_ERROR; + } + + connssl->state = ssl_connection_complete; + + /* When SSPI is used in combination with Schannel + * we need the Schannel context to create the Schannel + * binding to pass the IIS extended protection checks. + * Available on Windows 7 or later. + */ + cf->conn->sslContext = &backend->ctxt->ctxt_handle; + + *done = TRUE; + } + + return CURLE_OK; +} + +enum schannel_renegotiate_caller_t { + SCH_RENEG_CALLER_IS_RECV, + SCH_RENEG_CALLER_IS_SEND +}; + +/* The maximum time we allow for Schannel renegotiation which may in some + rare cases block either due to libcurl (waiting on the socket) or Windows + (waiting on an interactive security prompt). Note Schannel "renegotiation" + is not necessarily literal TLS renegotiation, but means DecryptMessage + returned SEC_I_RENEGOTIATE which means at least the security context needs + to be re-established. */ +#define MAX_RENEG_BLOCK_TIME (60 * 1000) /* 60 seconds in milliseconds */ + +/* This function renegotiates the connection due to a server request received + by schannel_recv. This function returns CURLE_AGAIN if the renegotiation is + incomplete. In that case, we remain in the renegotiation (connecting) stage + and future calls to schannel_recv and schannel_send must call this function + first to complete the renegotiation. */ +static CURLcode schannel_recv_renegotiate( + struct Curl_cfilter *cf, struct Curl_easy *data, + enum schannel_renegotiate_caller_t caller) +{ + CURLcode result; + curl_socket_t sockfd; + struct ssl_connect_data *connssl = cf->ctx; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + struct schannel_renegotiate_state *rs = &backend->renegotiate_state; + + if(!backend || !backend->recv_renegotiating) { + failf(data, "schannel: unexpected call to schannel_recv_renegotiate"); + return CURLE_SSL_CONNECT_ERROR; + } + DEBUGASSERT(caller <= SCH_RENEG_CALLER_IS_SEND); + if(caller == SCH_RENEG_CALLER_IS_RECV) + SCH_DEV(infof(data, "schannel: renegotiation caller is schannel_recv")); + else + SCH_DEV(infof(data, "schannel: renegotiation caller is schannel_send")); + + sockfd = Curl_conn_cf_get_socket(cf, data); + + if(sockfd == CURL_SOCKET_BAD) { + failf(data, "schannel: renegotiation missing socket"); + return CURLE_SSL_CONNECT_ERROR; + } + + if(!rs->started) { /* new renegotiation */ + infof(data, "schannel: renegotiating SSL/TLS connection"); + DEBUGASSERT(connssl->state == ssl_connection_complete); + DEBUGASSERT(connssl->connecting_state == ssl_connect_done); + connssl->state = ssl_connection_negotiating; + connssl->connecting_state = ssl_connect_2; + memset(rs, 0, sizeof(*rs)); + rs->io_need = CURL_SSL_IO_NEED_SEND; + rs->start_time = *Curl_pgrs_now(data); + rs->started = TRUE; + } + + for(;;) { + bool block_read, block_write, blocking, done; + curl_socket_t readfd, writefd; + timediff_t elapsed; + + elapsed = curlx_ptimediff_ms(Curl_pgrs_now(data), &rs->start_time); + if(elapsed >= MAX_RENEG_BLOCK_TIME) { + failf(data, "schannel: renegotiation timeout"); + result = CURLE_SSL_CONNECT_ERROR; + break; + } + + /* the current io_need state may have been overwritten since the last time + this function was called. restore the io_need state needed to continue + the renegotiation. */ + + connssl->io_need = rs->io_need; + + result = schannel_connect(cf, data, &done); + + rs->io_need = connssl->io_need; + + if(!result && !done) + result = CURLE_AGAIN; + + if(result != CURLE_AGAIN) + break; + + readfd = (rs->io_need & CURL_SSL_IO_NEED_RECV) ? sockfd : CURL_SOCKET_BAD; + writefd = (rs->io_need & CURL_SSL_IO_NEED_SEND) ? sockfd : CURL_SOCKET_BAD; + + if(readfd == CURL_SOCKET_BAD && writefd == CURL_SOCKET_BAD) + continue; + + /* connect should not have requested io read and write together */ + DEBUGASSERT(readfd == CURL_SOCKET_BAD || writefd == CURL_SOCKET_BAD); + + /* This function is partially blocking to avoid a stoppage that would + * occur if the user is waiting on the socket only in one direction. + * + * For example, if the user has called recv then they may not be waiting + * for a writable socket and vice versa, so we block to avoid that. + * + * In practice a wait is unlikely to occur. For caller recv if handshake + * data needs to be sent then we block for a writable socket that should + * be writable immediately except for OS resource constraints. For caller + * send if handshake data needs to be received then we block for a readable + * socket, which could take some time, but it is more likely the user has + * called recv since they had called it prior (only recv can start + * renegotiation and probably the user is going to call it again to get + * more of their data before calling send). + */ + + block_read = (caller == SCH_RENEG_CALLER_IS_SEND) ? TRUE : FALSE; + block_write = (caller == SCH_RENEG_CALLER_IS_RECV) ? TRUE : FALSE; + + blocking = (block_read && (readfd != CURL_SOCKET_BAD)) || + (block_write && (writefd != CURL_SOCKET_BAD)); + + SCH_DEV_SHOWBOOL(block_read); + SCH_DEV_SHOWBOOL(block_write); + SCH_DEV_SHOWBOOL(blocking); + + for(;;) { + int what; + timediff_t timeout_ms, remaining; + + result = Curl_pgrsUpdate(data); + if(result) + break; + + elapsed = curlx_ptimediff_ms(Curl_pgrs_now(data), &rs->start_time); + if(elapsed >= MAX_RENEG_BLOCK_TIME) { + failf(data, "schannel: renegotiation timeout"); + result = CURLE_SSL_CONNECT_ERROR; + break; + } + remaining = MAX_RENEG_BLOCK_TIME - elapsed; + + if(blocking) { + timeout_ms = Curl_timeleft_ms(data); + + if(timeout_ms < 0) { + result = CURLE_OPERATION_TIMEDOUT; + break; + } + + /* the blocking is in intervals so that the progress function can be + called every second */ + if(!timeout_ms || timeout_ms > 1000) + timeout_ms = 1000; + + if(timeout_ms > remaining) + timeout_ms = remaining; + } + else + timeout_ms = 0; + + SCH_DEV(infof(data, "schannel: renegotiation wait until socket is" + "%s%s for up to %" FMT_TIMEDIFF_T " ms", + ((readfd != CURL_SOCKET_BAD) ? " readable" : ""), + ((writefd != CURL_SOCKET_BAD) ? " writable" : ""), + timeout_ms)); + + what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, timeout_ms); + + if(what > 0 && (what & (CURL_CSELECT_IN | CURL_CSELECT_OUT))) { + SCH_DEV(infof(data, "schannel: renegotiation socket %s%s", + ((what & CURL_CSELECT_IN) ? "CURL_CSELECT_IN " : ""), + ((what & CURL_CSELECT_OUT) ? "CURL_CSELECT_OUT " : ""))); + result = CURLE_AGAIN; + break; + } + else if(!what) { + SCH_DEV(infof(data, "schannel: renegotiation socket timeout")); + if(blocking) + continue; + else + return CURLE_AGAIN; + } + + failf(data, "schannel: socket error during renegotiation"); + result = CURLE_SSL_CONNECT_ERROR; + break; + } + if(result != CURLE_AGAIN) + break; + } + + DEBUGASSERT(result != CURLE_AGAIN); + + rs->started = FALSE; + backend->recv_renegotiating = FALSE; + connssl->io_need = CURL_SSL_IO_NEED_NONE; + + if(result) + failf(data, "schannel: renegotiation failed"); + else + infof(data, "schannel: SSL/TLS connection renegotiated"); + + return result; +} + +static CURLcode schannel_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, size_t *pnwritten) +{ + size_t data_len = 0; + unsigned char *ptr = NULL; + struct ssl_connect_data *connssl = cf->ctx; + SecBuffer outbuf[4]; + SecBufferDesc outbuf_desc; + SECURITY_STATUS sspi_status = SEC_E_OK; + CURLcode result = CURLE_OK; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + + DEBUGASSERT(backend); + *pnwritten = 0; + + if(backend->recv_renegotiating) { + result = schannel_recv_renegotiate(cf, data, SCH_RENEG_CALLER_IS_SEND); + if(result) + return result; + } + + /* check if the buffer is longer than the maximum message length */ + if(len > backend->stream_sizes.cbMaximumMessage) { + len = backend->stream_sizes.cbMaximumMessage; + } + + /* calculate the complete message length and prepare the send buffer */ + data_len = backend->stream_sizes.cbHeader + len + + backend->stream_sizes.cbTrailer; + if(data_len > backend->send_buffer_len) { + ptr = curlx_realloc(backend->send_buffer, data_len); + if(!ptr) + return CURLE_OUT_OF_MEMORY; + backend->send_buffer = ptr; + backend->send_buffer_len = data_len; + } + else + ptr = backend->send_buffer; + + /* setup output buffers (header, data, trailer, empty) */ + InitSecBuffer(&outbuf[0], SECBUFFER_STREAM_HEADER, + ptr, backend->stream_sizes.cbHeader); + InitSecBuffer(&outbuf[1], SECBUFFER_DATA, + ptr + backend->stream_sizes.cbHeader, curlx_uztoul(len)); + InitSecBuffer(&outbuf[2], SECBUFFER_STREAM_TRAILER, + ptr + backend->stream_sizes.cbHeader + len, + backend->stream_sizes.cbTrailer); + InitSecBuffer(&outbuf[3], SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&outbuf_desc, outbuf, 4); + + /* copy data into output buffer */ + memcpy(outbuf[1].pvBuffer, buf, len); + + /* https://learn.microsoft.com/windows/win32/api/sspi/nf-sspi-encryptmessage */ + sspi_status = Curl_pSecFn->EncryptMessage(&backend->ctxt->ctxt_handle, 0, + &outbuf_desc, 0); + + /* check if the message was encrypted */ + if(sspi_status == SEC_E_OK) { + + /* send the encrypted message including header, data and trailer */ + len = outbuf[0].cbBuffer + outbuf[1].cbBuffer + outbuf[2].cbBuffer; + + /* it is important to send the full message which includes the header, + encrypted payload, and trailer. Until the client receives all the + data a coherent message has not been delivered and the client + cannot read any of it. + + If we wanted to buffer the unwritten encrypted bytes, we would + tell the client that all data it has requested to be sent has been + sent. The unwritten encrypted bytes would be the first bytes to + send on the next invocation. + Here's the catch with this - if we tell the client that all the + bytes have been sent, does the client call this method again to + send the buffered data? Looking at who calls this function, it + seems the answer is NO. */ + + /* send entire message or fail */ + while(len > *pnwritten) { + size_t this_write = 0; + int what; + timediff_t timeout_ms = Curl_timeleft_ms(data); + if(timeout_ms < 0) { + /* we already got the timeout */ + failf(data, "schannel: timed out sending data (bytes sent: %zu)", + *pnwritten); + result = CURLE_OPERATION_TIMEDOUT; + break; + } + else if(!timeout_ms) + timeout_ms = TIMEDIFF_T_MAX; + what = SOCKET_WRITABLE(Curl_conn_cf_get_socket(cf, data), timeout_ms); + if(what < 0) { + /* fatal error */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + result = CURLE_SEND_ERROR; + break; + } + else if(what == 0) { + failf(data, "schannel: timed out sending data (bytes sent: %zu)", + *pnwritten); + result = CURLE_OPERATION_TIMEDOUT; + break; + } + /* socket is writable */ + + result = Curl_conn_cf_send(cf->next, data, + (const uint8_t *)ptr + *pnwritten, + len - *pnwritten, + FALSE, &this_write); + if(result == CURLE_AGAIN) + continue; + else if(result) { + break; + } + + *pnwritten += this_write; + } + } + else if(sspi_status == SEC_E_INSUFFICIENT_MEMORY) { + result = CURLE_OUT_OF_MEMORY; + } + else { + result = CURLE_SEND_ERROR; + } + + if(len == *pnwritten) + /* Encrypted message including header, data and trailer entirely sent. + The return value is the number of unencrypted bytes that were sent. */ + *pnwritten = outbuf[1].cbBuffer; + + return result; +} + +static CURLcode schannel_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, size_t *pnread) +{ + size_t size = 0; + size_t nread = 0; + struct ssl_connect_data *connssl = cf->ctx; + SecBuffer inbuf[4]; + SecBufferDesc inbuf_desc; + SECURITY_STATUS sspi_status = SEC_E_OK; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + CURLcode result = CURLE_OK; + + DEBUGASSERT(backend); + *pnread = 0; + + if(backend->recv_renegotiating) { + result = schannel_recv_renegotiate(cf, data, SCH_RENEG_CALLER_IS_RECV); + if(result) + return result; + } + + /**************************************************************************** + * Do not return or set backend->recv_unrecoverable_err unless in the + * cleanup. The pattern for return error is set *err, optional infof, goto + * cleanup. + * + * Some verbose debug messages are wrapped by SCH_DEV() instead of DEBUGF() + * and only shown if CURL_SCHANNEL_DEV_DEBUG was defined at build time. These + * messages are extra verbose and intended for curl developers debugging + * Schannel recv decryption. + * + * Our priority is to always return as much decrypted data to the caller as + * possible, even if an error occurs. The state of the decrypted buffer must + * always be valid. Transfer of decrypted data to the caller's buffer is + * handled in the cleanup. + */ + + SCH_DEV(infof(data, "schannel: client wants to read %zu bytes", len)); + + if(len && len <= backend->decdata.offset) { + SCH_DEV(infof(data, + "schannel: enough decrypted data is already available")); + goto cleanup; + } + else if(backend->recv_unrecoverable_err) { + result = backend->recv_unrecoverable_err; + infof(data, "schannel: an unrecoverable error occurred in a prior call"); + goto cleanup; + } + else if(backend->recv_sspi_close_notify) { + /* once a server has indicated shutdown there is no more encrypted data */ + infof(data, "schannel: server indicated shutdown in a prior call"); + goto cleanup; + } + /* it is debatable what to return when !len. Regardless we cannot return + immediately because there may be data to decrypt (in the case we want to + decrypt all encrypted cached data) so handle !len later in cleanup. */ + else if(len && !backend->recv_connection_closed) { + /* the encrypted buffer must be large enough to hold all the bytes + requested and some TLS record overhead. 'len' is a buffer size, so this + integer math cannot overflow. */ + const size_t min_encdata_length = len + CURL_SCHANNEL_BUFFER_FREE_SIZE; + + /* make sure encrypt buffer fits the requested amount of data */ + result = ensure_encoding_size(data, &backend->encdata, min_encdata_length); + if(result) + goto cleanup; + + SCH_DEV(infof(data, + "schannel: encrypted data buffer: offset %zu length %zu", + backend->encdata.offset, backend->encdata.length)); + + /* read encrypted data from socket */ + result = Curl_conn_cf_recv(cf->next, data, + (char *)(backend->encdata.buffer + + backend->encdata.offset), + backend->encdata.length - + backend->encdata.offset, + &nread); + if(result) { + if(result == CURLE_AGAIN) + SCH_DEV(infof(data, "schannel: recv returned CURLE_AGAIN")); + else { + infof(data, "schannel: recv returned error %d", (int)result); + backend->recv_unrecoverable_err = result; + } + } + else if(nread == 0) { + backend->recv_connection_closed = TRUE; + DEBUGF(infof(data, "schannel: server closed the connection")); + } + else { + backend->encdata.offset += nread; + backend->encdata_is_incomplete = FALSE; + SCH_DEV(infof(data, "schannel: encrypted data got %zu", nread)); + } + } + + SCH_DEV(infof(data, "schannel: encrypted data buffer: offset %zu length %zu", + backend->encdata.offset, backend->encdata.length)); + + /* decrypt loop */ + while(backend->encdata.offset > 0 && sspi_status == SEC_E_OK && + (!len || backend->decdata.offset < len || + backend->recv_connection_closed)) { + /* prepare data buffer for DecryptMessage call */ + InitSecBuffer(&inbuf[0], SECBUFFER_DATA, backend->encdata.buffer, + curlx_uztoul(backend->encdata.offset)); + + /* we need 3 more empty input buffers for possible output */ + InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0); + InitSecBuffer(&inbuf[2], SECBUFFER_EMPTY, NULL, 0); + InitSecBuffer(&inbuf[3], SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&inbuf_desc, inbuf, 4); + + /* https://learn.microsoft.com/windows/win32/api/sspi/nf-sspi-decryptmessage + */ + sspi_status = Curl_pSecFn->DecryptMessage(&backend->ctxt->ctxt_handle, + &inbuf_desc, 0, NULL); + + /* check if everything went fine (server may want to renegotiate + or shutdown the connection context) */ + if(sspi_status == SEC_E_OK || sspi_status == SEC_I_RENEGOTIATE || + sspi_status == SEC_I_CONTEXT_EXPIRED) { + /* check for successfully decrypted data, even before actual + renegotiation or shutdown of the connection context */ + if(inbuf[1].BufferType == SECBUFFER_DATA) { + SCH_DEV(infof(data, "schannel: decrypted data length: %lu", + inbuf[1].cbBuffer)); + + /* ensure the decode buffer fits the received amount of data */ + result = ensure_decoding_size(data, &backend->decdata, + inbuf[1].cbBuffer, len); + if(result) + goto cleanup; + + /* copy decrypted data to internal buffer */ + size = inbuf[1].cbBuffer; + if(size) { + memcpy(backend->decdata.buffer + backend->decdata.offset, + inbuf[1].pvBuffer, size); + backend->decdata.offset += size; + } + + SCH_DEV(infof(data, "schannel: decrypted data added: %zu", size)); + SCH_DEV(infof(data, + "schannel: decrypted cached: offset %zu length %zu", + backend->decdata.offset, backend->decdata.length)); + } + + /* check for remaining encrypted data */ + if(inbuf[3].BufferType == SECBUFFER_EXTRA && inbuf[3].cbBuffer > 0) { + SCH_DEV(infof(data, "schannel: encrypted data length: %lu", + inbuf[3].cbBuffer)); + + /* check if the remaining data is less than the total amount + * and therefore begins after the already processed data + */ + if(backend->encdata.offset > inbuf[3].cbBuffer) { + /* move remaining encrypted data forward to the beginning of + buffer */ + memmove(backend->encdata.buffer, + (backend->encdata.buffer + backend->encdata.offset) - + inbuf[3].cbBuffer, inbuf[3].cbBuffer); + backend->encdata.offset = inbuf[3].cbBuffer; + } + + SCH_DEV(infof(data, + "schannel: encrypted cached: offset %zu length %zu", + backend->encdata.offset, backend->encdata.length)); + } + else { + /* reset encrypted buffer offset, because there is no data remaining */ + backend->encdata.offset = 0; + } + + /* check if server wants to renegotiate the connection context */ + if(sspi_status == SEC_I_RENEGOTIATE) { + infof(data, "schannel: remote party requests renegotiation"); + if(result && result != CURLE_AGAIN) { + infof(data, "schannel: cannot renegotiate, an error is pending"); + goto cleanup; + } + + backend->recv_renegotiating = TRUE; + result = schannel_recv_renegotiate(cf, data, SCH_RENEG_CALLER_IS_RECV); + if(result) + goto cleanup; + + /* now retry receiving data */ + sspi_status = SEC_E_OK; + continue; + } + /* check if the server closed the connection */ + else if(sspi_status == SEC_I_CONTEXT_EXPIRED) { + /* In Windows 2000 SEC_I_CONTEXT_EXPIRED (close_notify) is not + returned so we have to work around that in cleanup. */ + backend->recv_sspi_close_notify = TRUE; + if(!backend->recv_connection_closed) + backend->recv_connection_closed = TRUE; + /* We received the close notify fine, any error we got + * from the lower filters afterwards (e.g. the socket), is not + * an error on the TLS data stream. That one ended here. */ + if(result == CURLE_RECV_ERROR) + result = CURLE_OK; + infof(data, + "schannel: server close notification received (close_notify)"); + goto cleanup; + } + } + else if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) { + backend->encdata_is_incomplete = TRUE; + if(!result) + result = CURLE_AGAIN; + SCH_DEV(infof(data, "schannel: failed to decrypt data, need more data")); + goto cleanup; + } + else { + char buffer[STRERROR_LEN]; + failf(data, "schannel: failed to read data from server: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + result = CURLE_RECV_ERROR; + goto cleanup; + } + } + + SCH_DEV(infof(data, "schannel: encrypted data buffer: offset %zu length %zu", + backend->encdata.offset, backend->encdata.length)); + + SCH_DEV(infof(data, "schannel: decrypted data buffer: offset %zu length %zu", + backend->decdata.offset, backend->decdata.length)); + +cleanup: + /* Warning- there is no guarantee the encdata state is valid at this point */ + SCH_DEV(infof(data, "schannel: schannel_recv cleanup")); + + /* Error if the connection has closed without a close_notify. + + The behavior here is a matter of debate. We do not want to be vulnerable + to a truncation attack however there is some browser precedent for + ignoring the close_notify for compatibility reasons. */ + if(len && !backend->decdata.offset && backend->recv_connection_closed && + !backend->recv_sspi_close_notify) { + result = CURLE_RECV_ERROR; + failf(data, "schannel: server closed abruptly (missing close_notify)"); + } + + /* Any error other than CURLE_AGAIN is an unrecoverable error. */ + if(result && result != CURLE_AGAIN) + backend->recv_unrecoverable_err = result; + + size = len < backend->decdata.offset ? len : backend->decdata.offset; + if(size) { + memcpy(buf, backend->decdata.buffer, size); + memmove(backend->decdata.buffer, backend->decdata.buffer + size, + backend->decdata.offset - size); + backend->decdata.offset -= size; + SCH_DEV(infof(data, "schannel: decrypted data returned %zu", size)); + SCH_DEV(infof(data, + "schannel: decrypted data buffer: offset %zu length %zu", + backend->decdata.offset, backend->decdata.length)); + *pnread = size; + return CURLE_OK; + } + + if(!result && !backend->recv_connection_closed) + result = CURLE_AGAIN; + + /* it is debatable what to return when !len. We could return whatever error + we got from decryption but instead we override here so the return is + consistent. */ + if(!len) + return CURLE_OK; + + return result; +} + +static bool schannel_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + const struct ssl_connect_data *connssl = cf->ctx; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + + (void)data; + DEBUGASSERT(backend); + + if(backend->ctxt) /* SSL/TLS is in use */ + return backend->decdata.offset > 0 || + (backend->encdata.offset > 0 && !backend->encdata_is_incomplete) || + backend->recv_connection_closed || + backend->recv_sspi_close_notify || + backend->recv_unrecoverable_err; + else + return FALSE; +} + +/* shut down the SSL connection and clean up related memory. + this function can be called multiple times on the same connection including + if the SSL connection failed (eg connection made but failed handshake). */ +static CURLcode schannel_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + /* See https://learn.microsoft.com/windows/win32/secauthn/shutting-down-an-schannel-connection + * Shutting Down an Schannel Connection + */ + struct ssl_connect_data *connssl = cf->ctx; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + CURLcode result = CURLE_OK; + + if(cf->shutdown) { + *done = TRUE; + return CURLE_OK; + } + + DEBUGASSERT(data); + DEBUGASSERT(backend); + + /* Not supported in schannel */ + (void)send_shutdown; + + *done = FALSE; + if(backend->ctxt) { + infof(data, "schannel: shutting down SSL/TLS connection with %s port %d", + connssl->peer.origin->hostname, connssl->peer.origin->port); + } + + if(!backend->ctxt || cf->shutdown) { + *done = TRUE; + goto out; + } + + if(backend->cred && backend->ctxt && !backend->sent_shutdown) { + SecBufferDesc BuffDesc; + SecBuffer Buffer; + SECURITY_STATUS sspi_status; + SecBuffer outbuf; + SecBufferDesc outbuf_desc; + DWORD dwshut = SCHANNEL_SHUTDOWN; + + InitSecBuffer(&Buffer, SECBUFFER_TOKEN, &dwshut, sizeof(dwshut)); + InitSecBufferDesc(&BuffDesc, &Buffer, 1); + + sspi_status = Curl_pSecFn->ApplyControlToken(&backend->ctxt->ctxt_handle, + &BuffDesc); + + if(sspi_status != SEC_E_OK) { + char buffer[STRERROR_LEN]; + failf(data, "schannel: ApplyControlToken failure: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + result = CURLE_SEND_ERROR; + goto out; + } + + /* setup output buffer */ + InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&outbuf_desc, &outbuf, 1); + + sspi_status = Curl_pSecFn->InitializeSecurityContext( + &backend->cred->cred_handle, + &backend->ctxt->ctxt_handle, + backend->cred->sni_hostname, + backend->req_flags, + 0, + 0, + NULL, + 0, + &backend->ctxt->ctxt_handle, + &outbuf_desc, + &backend->ret_flags, NULL); + + if((sspi_status == SEC_E_OK) || (sspi_status == SEC_I_CONTEXT_EXPIRED)) { + /* send close message which is in output buffer */ + size_t written; + + result = Curl_conn_cf_send(cf->next, data, + (const uint8_t *)outbuf.pvBuffer, + outbuf.cbBuffer, + FALSE, &written); + Curl_pSecFn->FreeContextBuffer(outbuf.pvBuffer); + if(!result) { + if(written < outbuf.cbBuffer) { + result = CURLE_SEND_ERROR; + failf(data, "schannel: failed to send close msg: %s" + " (bytes written: %zu)", curl_easy_strerror(result), written); + goto out; + } + backend->sent_shutdown = TRUE; + *done = TRUE; + } + else if(result == CURLE_AGAIN) { + connssl->io_need = CURL_SSL_IO_NEED_SEND; + result = CURLE_OK; + goto out; + } + else { + if(!backend->recv_connection_closed) { + result = CURLE_SEND_ERROR; + failf(data, "schannel: error sending close msg: %d", (int)result); + goto out; + } + /* Looks like server already closed the connection. + * An error to send our close notify is not a failure. */ + *done = TRUE; + result = CURLE_OK; + } + } + } + + /* If the connection seems open and we have not seen the close notify + * from the server yet, try to receive it. */ + if(backend->cred && backend->ctxt && + !backend->recv_sspi_close_notify && !backend->recv_connection_closed) { + char buffer[1024]; + size_t nread; + + result = schannel_recv(cf, data, buffer, sizeof(buffer), &nread); + if(result == CURLE_AGAIN) { + connssl->io_need = CURL_SSL_IO_NEED_RECV; + } + else if(result) { + CURL_TRC_CF(data, cf, "SSL shutdown, error %d", (int)result); + result = CURLE_RECV_ERROR; + } + else if(nread == 0) { + /* We got the close notify alert and are done. */ + backend->recv_connection_closed = TRUE; + *done = TRUE; + } + else { + /* still data coming in? */ + } + } + +out: + cf->shutdown = (result || *done); + return result; +} + +static void schannel_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + + DEBUGASSERT(data); + DEBUGASSERT(backend); + + /* free SSPI Schannel API security context handle */ + if(backend->ctxt) { + DEBUGF(infof(data, "schannel: clear security context handle")); + Curl_pSecFn->DeleteSecurityContext(&backend->ctxt->ctxt_handle); + curlx_safefree(backend->ctxt); + } + + /* free SSPI Schannel API credential handle */ + if(backend->cred) { + Curl_ssl_scache_lock(data); + schannel_session_free(backend->cred); + Curl_ssl_scache_unlock(data); + backend->cred = NULL; + } + + /* free the buffer used to encrypt outgoing data */ + curlx_safefree(backend->send_buffer); + backend->send_buffer_len = 0; + + /* free internal buffer for received encrypted data */ + if(backend->encdata.buffer) { + curlx_safefree(backend->encdata.buffer); + backend->encdata.length = 0; + backend->encdata.offset = 0; + backend->encdata_is_incomplete = FALSE; + } + + /* free internal buffer for received decrypted data */ + if(backend->decdata.buffer) { + curlx_safefree(backend->decdata.buffer); + backend->decdata.length = 0; + backend->decdata.offset = 0; + } +} + +static int schannel_init(void) +{ + typedef const char *(APIENTRY *WINE_GET_VERSION_FN)(void); +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcast-function-type-strict" +#endif + WINE_GET_VERSION_FN p_wine_get_version = + CURLX_FUNCTION_CAST(WINE_GET_VERSION_FN, + GetProcAddress(GetModuleHandle(TEXT("ntdll")), "wine_get_version")); +#if defined(__clang__) && __clang_major__ >= 16 +#pragma clang diagnostic pop +#endif + if(p_wine_get_version) { /* WINE detected */ + curl_off_t ver = 0; + const char *wine_version = p_wine_get_version(); /* e.g. "6.0.2" */ + /* Assume ALPN support with WINE 6.0 or greater */ + if(wine_version) + curlx_str_number(&wine_version, &ver, 20); + s_win_has_alpn = (ver >= 6); + } + else { + /* ALPN is supported on Windows 8.1 / Server 2012 R2 or newer. */ + s_win_has_alpn = curlx_verify_windows_version(6, 3, 0, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL); + } + + return Curl_sspi_global_init() == CURLE_OK ? 1 : 0; +} + +static void schannel_cleanup(void) +{ + Curl_sspi_global_cleanup(); +} + +static size_t schannel_version(char *buffer, size_t size) +{ + return curl_msnprintf(buffer, size, "Schannel"); +} + +static CURLcode schannel_random(struct Curl_easy *data, + unsigned char *entropy, size_t length) +{ + (void)data; + + return curlx_win32_random(entropy, length); +} + +static CURLcode schannel_checksum(const unsigned char *input, + size_t inputlen, + unsigned char *checksum, + size_t checksumlen, + DWORD provType, + const unsigned int algId) +{ + CURLcode result = CURLE_FAILED_INIT; + + HCRYPTPROV hProv = 0; + HCRYPTHASH hHash = 0; + + size_t off; + + DWORD cbHashSize; + DWORD dwHashSizeLen; + DWORD dwChecksumLen; + + /* since this can fail in multiple ways, zero memory first so we never + * return old data + */ + memset(checksum, 0, checksumlen); + + if(!CryptAcquireContext(&hProv, NULL, NULL, provType, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + goto out; + + if(!CryptCreateHash(hProv, algId, 0, 0, &hHash)) + goto out; + + result = CURLE_BAD_FUNCTION_ARGUMENT; + + off = 0; + while(off < inputlen) { + DWORD chunk = (DWORD)CURLMIN(inputlen - off, 0xffffffffUL); + if(!CryptHashData(hHash, input + off, chunk, 0)) + goto out; + off += chunk; + } + + /* get hash size */ + cbHashSize = 0; + dwHashSizeLen = (DWORD)sizeof(cbHashSize); + if(!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *)&cbHashSize, + &dwHashSizeLen, 0)) + goto out; + + /* check if hash fits into the return buffer */ + if(checksumlen < cbHashSize) + goto out; + + dwChecksumLen = (DWORD)checksumlen; + if(CryptGetHashParam(hHash, HP_HASHVAL, checksum, &dwChecksumLen, 0) && + dwChecksumLen == cbHashSize) + result = CURLE_OK; + +out: + if(hHash) + CryptDestroyHash(hHash); + + if(hProv) + CryptReleaseContext(hProv, 0); + + return result; +} + +static CURLcode schannel_sha256sum(const unsigned char *input, + size_t inputlen, + unsigned char *sha256sum, + size_t sha256len) +{ + return schannel_checksum(input, inputlen, sha256sum, sha256len, + PROV_RSA_AES, CALG_SHA_256); +} + +static void *schannel_get_internals(struct ssl_connect_data *connssl, + CURLINFO info) +{ + struct schannel_ssl_backend_data *backend = + (struct schannel_ssl_backend_data *)connssl->backend; + (void)info; + DEBUGASSERT(backend); + return &backend->ctxt->ctxt_handle; +} + +HCERTSTORE Curl_schannel_get_cached_cert_store(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_multi *multi = data->multi; + const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; + struct schannel_cert_share *share; + const struct ssl_general_config *cfg = &data->set.general_ssl; + timediff_t timeout_ms; + unsigned char info_blob_digest[CURL_SHA256_DIGEST_LENGTH]; + + DEBUGASSERT(multi); + + if(!multi) { + return NULL; + } + + share = Curl_hash_pick(&multi->proto_hash, + CURL_UNCONST(MPROTO_SCHANNEL_CERT_SHARE_KEY), + CURL_CSTRLEN(MPROTO_SCHANNEL_CERT_SHARE_KEY)); + if(!share || !share->cert_store) { + return NULL; + } + + /* zero ca_cache_timeout completely disables caching */ + if(!cfg->ca_cache_timeout) { + return NULL; + } + + /* check for cache timeout by using the cached_x509_store_expired timediff + calculation pattern from openssl.c. + negative timeout means retain forever. */ + timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000; + if(timeout_ms >= 0) { + timediff_t elapsed_ms = + curlx_ptimediff_ms(Curl_pgrs_now(data), &share->time); + if(elapsed_ms >= timeout_ms) { + return NULL; + } + } + + if(ca_info_blob) { + if(share->CAinfo_blob_size != ca_info_blob->len) { + return NULL; + } + if(schannel_sha256sum((const unsigned char *)ca_info_blob->data, + ca_info_blob->len, + info_blob_digest, + CURL_SHA256_DIGEST_LENGTH)) + return NULL; + if(memcmp(share->CAinfo_blob_digest, info_blob_digest, + CURL_SHA256_DIGEST_LENGTH)) { + return NULL; + } + } + else { + if(!conn_config->CAfile || !share->CAfile || + strcmp(share->CAfile, conn_config->CAfile)) { + return NULL; + } + } + + return share->cert_store; +} + +static void schannel_cert_share_free(void *key, size_t key_len, void *p) +{ + struct schannel_cert_share *share = p; + DEBUGASSERT(key_len == CURL_CSTRLEN(MPROTO_SCHANNEL_CERT_SHARE_KEY)); + DEBUGASSERT(!memcmp(MPROTO_SCHANNEL_CERT_SHARE_KEY, key, key_len)); + (void)key; + (void)key_len; + if(share->cert_store) { + CertCloseStore(share->cert_store, 0); + } + curlx_free(share->CAfile); + curlx_free(share); +} + +bool Curl_schannel_set_cached_cert_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + HCERTSTORE cert_store) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_multi *multi = data->multi; + const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; + struct schannel_cert_share *share; + unsigned char digest[CURL_SHA256_DIGEST_LENGTH]; + char *CAfile = NULL; + + DEBUGASSERT(multi); + + if(!multi) { + return FALSE; + } + + if(ca_info_blob) { + if(schannel_sha256sum((const unsigned char *)ca_info_blob->data, + ca_info_blob->len, digest, sizeof(digest))) { + return FALSE; + } + } + else if(conn_config->CAfile) { + CAfile = curlx_strdup(conn_config->CAfile); + if(!CAfile) { + return FALSE; + } + } + + share = Curl_hash_pick(&multi->proto_hash, + CURL_UNCONST(MPROTO_SCHANNEL_CERT_SHARE_KEY), + CURL_CSTRLEN(MPROTO_SCHANNEL_CERT_SHARE_KEY)); + if(!share) { + share = curlx_calloc(1, sizeof(*share)); + if(!share) { + curlx_free(CAfile); + return FALSE; + } + if(!Curl_hash_add2(&multi->proto_hash, + CURL_UNCONST(MPROTO_SCHANNEL_CERT_SHARE_KEY), + CURL_CSTRLEN(MPROTO_SCHANNEL_CERT_SHARE_KEY), + share, schannel_cert_share_free)) { + curlx_free(share); + curlx_free(CAfile); + return FALSE; + } + } + + /* free old cache data */ + if(share->cert_store) { + CertCloseStore(share->cert_store, 0); + } + curlx_free(share->CAfile); + + if(ca_info_blob) { + memcpy(share->CAinfo_blob_digest, digest, sizeof(digest)); + share->CAinfo_blob_size = ca_info_blob->len; + } + else + share->CAinfo_blob_size = 0; + + share->time = curlx_now(); + share->cert_store = cert_store; + share->CAfile = CAfile; + return TRUE; +} + +const struct Curl_ssl Curl_ssl_schannel = { + { CURLSSLBACKEND_SCHANNEL, "schannel" }, /* info */ + + SSLSUPP_CERTINFO | + SSLSUPP_CAINFO_BLOB | + SSLSUPP_PINNEDPUBKEY | + SSLSUPP_CA_CACHE | + SSLSUPP_HTTPS_PROXY | + SSLSUPP_CIPHER_LIST, + + sizeof(struct schannel_ssl_backend_data), + + schannel_init, /* init */ + schannel_cleanup, /* cleanup */ + schannel_version, /* version */ + schannel_shutdown, /* shutdown */ + schannel_data_pending, /* data_pending */ + schannel_random, /* random */ + NULL, /* cert_status_request */ + schannel_connect, /* connect */ + Curl_ssl_adjust_pollset, /* adjust_pollset */ + schannel_get_internals, /* get_internals */ + schannel_close, /* close_one */ + NULL, /* close_all */ + NULL, /* set_engine */ + NULL, /* set_engine_default */ + NULL, /* engines_list */ + schannel_sha256sum, /* sha256sum */ + schannel_recv, /* recv decrypted data */ + schannel_send, /* send data to encrypt */ + NULL, /* get_channel_binding */ +}; + +#endif /* USE_SCHANNEL */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/schannel.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/schannel.h new file mode 100644 index 0000000000..fe49e9a9d0 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/schannel.h @@ -0,0 +1,45 @@ +#ifndef HEADER_CURL_SCHANNEL_H +#define HEADER_CURL_SCHANNEL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Marc Hoersken, <info@marc-hoersken.de>, et al. + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_SCHANNEL + +#include <schannel.h> + +#include "curl_sspi.h" +#include "cfilters.h" +#include "urldata.h" + +extern const struct Curl_ssl Curl_ssl_schannel; + +CURLcode Curl_verify_host(struct Curl_cfilter *cf, struct Curl_easy *data); + +CURLcode Curl_verify_certificate(struct Curl_cfilter *cf, + struct Curl_easy *data); + +#endif /* USE_SCHANNEL */ +#endif /* HEADER_CURL_SCHANNEL_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/schannel_int.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/schannel_int.h new file mode 100644 index 0000000000..ccbb63d7e2 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/schannel_int.h @@ -0,0 +1,169 @@ +#ifndef HEADER_CURL_SCHANNEL_INT_H +#define HEADER_CURL_SCHANNEL_INT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Marc Hoersken, <info@marc-hoersken.de>, et al. + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_SCHANNEL + +#include "vtls/vtls.h" +#include "curl_sha256.h" + +#if defined(_MSC_VER) && (_MSC_VER < 1700) +/* Workaround for warning: + 'type cast' : conversion from 'int' to 'LPCSTR' of greater size */ +#undef CERT_STORE_PROV_MEMORY +#undef CERT_STORE_PROV_SYSTEM_A +#undef CERT_STORE_PROV_SYSTEM_W +#define CERT_STORE_PROV_MEMORY ((LPCSTR)(size_t)2) +#define CERT_STORE_PROV_SYSTEM_A ((LPCSTR)(size_t)9) +#define CERT_STORE_PROV_SYSTEM_W ((LPCSTR)(size_t)10) +#endif + +/* Offered by mingw-w64 v8+, MS SDK 10.0.17763.0/VS2017 15.8+ */ +#ifndef SCH_CREDENTIALS_VERSION +#define SCH_CREDENTIALS_VERSION 0x00000005 + +typedef enum _eTlsAlgorithmUsage { + TlsParametersCngAlgUsageKeyExchange, + TlsParametersCngAlgUsageSignature, + TlsParametersCngAlgUsageCipher, + TlsParametersCngAlgUsageDigest, + TlsParametersCngAlgUsageCertSig +} eTlsAlgorithmUsage; + +/* !checksrc! disable TYPEDEFSTRUCT 1 */ +typedef struct _CRYPTO_SETTINGS { + eTlsAlgorithmUsage eAlgorithmUsage; + UNICODE_STRING strCngAlgId; + DWORD cChainingModes; + PUNICODE_STRING rgstrChainingModes; /* spellchecker:disable-line */ + DWORD dwMinBitLength; + DWORD dwMaxBitLength; +} CRYPTO_SETTINGS, *PCRYPTO_SETTINGS; + +/* !checksrc! disable TYPEDEFSTRUCT 1 */ +typedef struct _TLS_PARAMETERS { + DWORD cAlpnIds; + PUNICODE_STRING rgstrAlpnIds; /* spellchecker:disable-line */ + DWORD grbitDisabledProtocols; + DWORD cDisabledCrypto; + PCRYPTO_SETTINGS pDisabledCrypto; + DWORD dwFlags; +} TLS_PARAMETERS, *PTLS_PARAMETERS; + +/* !checksrc! disable TYPEDEFSTRUCT 1 */ +typedef struct _SCH_CREDENTIALS { + DWORD dwVersion; + DWORD dwCredFormat; + DWORD cCreds; + PCCERT_CONTEXT *paCred; + HCERTSTORE hRootStore; + + DWORD cMappers; + struct _HMAPPER **aphMappers; + + DWORD dwSessionLifespan; + DWORD dwFlags; + DWORD cTlsParameters; + PTLS_PARAMETERS pTlsParameters; +} SCH_CREDENTIALS, *PSCH_CREDENTIALS; + +#endif /* !SCH_CREDENTIALS_VERSION */ + +struct Curl_schannel_cred { + CredHandle cred_handle; + TCHAR *sni_hostname; + HCERTSTORE client_cert_store; + int refcount; +}; + +struct Curl_schannel_ctxt { + CtxtHandle ctxt_handle; +}; + +/* handle encoding/decoding buffers */ +struct sbuffer { + size_t length; + size_t offset; + unsigned char *buffer; +}; + +struct schannel_ssl_backend_data { + unsigned char *send_buffer; + size_t send_buffer_len; + struct sbuffer encdata; + struct sbuffer decdata; + struct Curl_schannel_cred *cred; + struct Curl_schannel_ctxt *ctxt; + SecPkgContext_StreamSizes stream_sizes; + unsigned long req_flags, ret_flags; + CURLcode recv_unrecoverable_err; /* schannel_recv had an unrecoverable err */ + struct schannel_renegotiate_state { + bool started; + struct curltime start_time; + int io_need; + } renegotiate_state; + BIT(recv_sspi_close_notify); /* true if connection closed by close_notify */ + BIT(recv_connection_closed); /* true if connection closed, regardless how */ + BIT(recv_renegotiating); /* true if recv is doing renegotiation */ + BIT(use_alpn); /* true if ALPN is used for this connection */ + BIT(use_manual_cred_validation); /* true if manual cred validation is used */ + BIT(sent_shutdown); + /* encdata_is_incomplete: if encdata contains only a partial record that + cannot be decrypted without another recv() (that is, status is + SEC_E_INCOMPLETE_MESSAGE) then set this true. after recv() adds more + bytes into encdata then set this back to false. */ + BIT(encdata_is_incomplete); +}; + +struct schannel_cert_share { + unsigned char CAinfo_blob_digest[CURL_SHA256_DIGEST_LENGTH]; + size_t CAinfo_blob_size; /* CA info blob size */ + char *CAfile; /* CAfile path used to generate + certificate store */ + HCERTSTORE cert_store; /* cached certificate store or + NULL if none */ + struct curltime time; /* when the cached store was created */ +}; + +/* size of the structure: 20 bytes */ +struct num_ip_data { + DWORD size; /* 04 bytes */ + union { + struct in_addr ia; /* 04 bytes */ + struct in6_addr ia6; /* 16 bytes */ + } bData; +}; + +HCERTSTORE Curl_schannel_get_cached_cert_store(struct Curl_cfilter *cf, + struct Curl_easy *data); + +bool Curl_schannel_set_cached_cert_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + HCERTSTORE cert_store); + +#endif /* USE_SCHANNEL */ +#endif /* HEADER_CURL_SCHANNEL_INT_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/schannel_verify.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/schannel_verify.c new file mode 100644 index 0000000000..6e55c9b839 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/schannel_verify.c @@ -0,0 +1,835 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Marc Hoersken, <info@marc-hoersken.de> + * Copyright (C) Mark Salisbury, <mark.salisbury@hp.com> + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Source file for Schannel-specific certificate verification. This code should + * only be invoked by code in schannel.c. + */ +#include "curl_setup.h" + +#ifdef USE_SCHANNEL + +#ifndef USE_WINDOWS_SSPI +#error "cannot compile Schannel support without SSPI." +#endif + +#include "vtls/schannel.h" +#include "vtls/schannel_int.h" + +#include "vtls/hostcheck.h" +#include "vtls/vtls.h" +#include "vtls/vtls_int.h" +#include "curl_trc.h" +#include "strerror.h" +#include "curlx/fopen.h" +#include "curlx/inet_pton.h" +#include "curlx/multibyte.h" +#include "curlx/version_win32.h" +#include "curlx/winapi.h" + +#define BACKEND ((struct schannel_ssl_backend_data *)connssl->backend) + +#define MAX_CAFILE_SIZE (1024 * 1024) /* 1 MiB */ +#define BEGIN_CERT "-----BEGIN CERTIFICATE-----" +#define END_CERT "\n-----END CERTIFICATE-----" + +struct cert_chain_engine_config_win8 { + DWORD cbSize; + HCERTSTORE hRestrictedRoot; + HCERTSTORE hRestrictedTrust; + HCERTSTORE hRestrictedOther; + DWORD cAdditionalStore; + HCERTSTORE *rghAdditionalStore; + DWORD dwFlags; + DWORD dwUrlRetrievalTimeout; + DWORD MaximumCachedCertificates; + DWORD CycleDetectionModulus; + HCERTSTORE hExclusiveRoot; + HCERTSTORE hExclusiveTrustedPeople; + DWORD dwExclusiveFlags; +}; + +/* Offered by mingw-w64 v4+, MS SDK 8.0/~VS2012+ */ +#ifndef CERT_CHAIN_EXCLUSIVE_ENABLE_CA_FLAG +#define CERT_CHAIN_EXCLUSIVE_ENABLE_CA_FLAG 0x00000001 +#endif + +/* Legacy structure to supply size to Win7 clients */ +struct cert_chain_engine_config_win7 { + DWORD cbSize; + HCERTSTORE hRestrictedRoot; + HCERTSTORE hRestrictedTrust; + HCERTSTORE hRestrictedOther; + DWORD cAdditionalStore; + HCERTSTORE *rghAdditionalStore; + DWORD dwFlags; + DWORD dwUrlRetrievalTimeout; + DWORD MaximumCachedCertificates; + DWORD CycleDetectionModulus; + HCERTSTORE hExclusiveRoot; + HCERTSTORE hExclusiveTrustedPeople; +}; + +/* Search the substring needle,needlelen into string haystack,haystacklen + * Strings do not need to be terminated by a '\0'. + * Similar of macOS/Linux memmem (not available on Visual Studio). + * Return position of beginning of first occurrence or NULL if not found + */ +static const char *c_memmem(const void *haystack, size_t haystacklen, + const void *needle, size_t needlelen) +{ + const char *p; + char first; + const char *str_limit = (const char *)haystack + haystacklen; + if(!needlelen || needlelen > haystacklen) + return NULL; + first = *(const char *)needle; + for(p = (const char *)haystack; p <= (str_limit - needlelen); p++) + if((*p == first) && !memcmp(p, needle, needlelen)) + return p; + + return NULL; +} + +static CURLcode add_certs_data_to_store(HCERTSTORE trust_store, + const char *ca_buffer, + size_t ca_buffer_size, + const char *ca_file_text, + struct Curl_easy *data) +{ + const size_t begin_cert_len = CURL_CSTRLEN(BEGIN_CERT); + const size_t end_cert_len = CURL_CSTRLEN(END_CERT); + CURLcode result = CURLE_OK; + int num_certs = 0; + bool more_certs = 1; + const char *current_ca_file_ptr = ca_buffer; + const char *ca_buffer_limit = ca_buffer + ca_buffer_size; + + while(more_certs && (current_ca_file_ptr < ca_buffer_limit)) { + const char *begin_cert_ptr = c_memmem(current_ca_file_ptr, + ca_buffer_limit - + current_ca_file_ptr - 1, + BEGIN_CERT, + begin_cert_len); + if(!begin_cert_ptr || !ISNEWLINE(begin_cert_ptr[begin_cert_len])) { + more_certs = 0; + } + else { + const char *end_cert_ptr = c_memmem(begin_cert_ptr, + ca_buffer_limit-begin_cert_ptr, + END_CERT, + end_cert_len); + if(!end_cert_ptr) { + failf(data, + "schannel: CA file '%s' is not correctly formatted", + ca_file_text); + result = CURLE_SSL_CACERT_BADFILE; + more_certs = 0; + } + else { + CERT_BLOB cert_blob; + const CERT_CONTEXT *cert_context = NULL; + BOOL add_cert_result = FALSE; + DWORD cert_size = + (DWORD)((end_cert_ptr + end_cert_len) - begin_cert_ptr); + + cert_blob.pbData = (BYTE *)CURL_UNCONST(begin_cert_ptr); + cert_blob.cbData = cert_size; + /* Caution: CryptQueryObject() is deprecated */ + if(!CryptQueryObject(CERT_QUERY_OBJECT_BLOB, + &cert_blob, + CERT_QUERY_CONTENT_FLAG_CERT, + CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED, + 0, + NULL, + NULL, + NULL, + NULL, + NULL, + (const void **)&cert_context)) { + char buffer[WINAPI_ERROR_LEN]; + failf(data, + "schannel: failed to extract certificate from CA file " + "'%s': %s", + ca_file_text, + curlx_winapi_strerror(GetLastError(), buffer, sizeof(buffer))); + result = CURLE_SSL_CACERT_BADFILE; + more_certs = 0; + } + else { + current_ca_file_ptr = begin_cert_ptr + cert_size; + + add_cert_result = + CertAddCertificateContextToStore(trust_store, + cert_context, + CERT_STORE_ADD_ALWAYS, + NULL); + if(!add_cert_result) { + char buffer[WINAPI_ERROR_LEN]; + failf(data, + "schannel: failed to add certificate from CA file '%s' " + "to certificate store: %s", + ca_file_text, + curlx_winapi_strerror(GetLastError(), buffer, + sizeof(buffer))); + result = CURLE_SSL_CACERT_BADFILE; + more_certs = 0; + } + else { + num_certs++; + } + + CertFreeCertificateContext(cert_context); + } + } + } + } + + if(result == CURLE_OK) { + if(!num_certs) { + infof(data, "schannel: did not add any certificates from CA file '%s'", + ca_file_text); + } + else { + infof(data, "schannel: added %d certificate(s) from CA file '%s'", + num_certs, ca_file_text); + } + } + return result; +} + +static CURLcode add_certs_file_to_store(HCERTSTORE trust_store, + const char *ca_file, + struct Curl_easy *data) +{ + CURLcode result; + FILE *ca_file_handle; + char *ca_file_buffer = NULL; + long ca_file_bufsize = 0; + long total_bytes_read = 0; + + /* + * Read the CA file completely into memory before parsing it. This + * optimizes for the common case where the CA file is relatively + * small ( < 1 MiB ). + */ + ca_file_handle = curlx_fopen(ca_file, "rb"); + if(!ca_file_handle) { + failf(data, "schannel: failed to open CA file '%s'", ca_file); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + + if(curlx_fseek(ca_file_handle, 0, SEEK_END)) { + failf(data, "schannel: failed seeking to end of CA file '%s'", ca_file); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + + ca_file_bufsize = ftell(ca_file_handle); + + if(curlx_fseek(ca_file_handle, 0, SEEK_SET)) { + failf(data, "schannel: failed seeking to beginning of CA file '%s'", + ca_file); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + + if(ca_file_bufsize < 0) { + failf(data, "schannel: failed to get length of CA file '%s'", ca_file); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + + if(ca_file_bufsize > MAX_CAFILE_SIZE) { + failf(data, "schannel: CA file exceeds max size of %d bytes", + MAX_CAFILE_SIZE); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + + ca_file_buffer = curlx_malloc(ca_file_bufsize + 1); + if(!ca_file_buffer) { + result = CURLE_OUT_OF_MEMORY; + goto cleanup; + } + + while(total_bytes_read < ca_file_bufsize) { + size_t nread = fread(ca_file_buffer + total_bytes_read, 1, + ca_file_bufsize - total_bytes_read, ca_file_handle); + + if(ferror(ca_file_handle)) { + failf(data, "schannel: failed to read from CA file '%s'", ca_file); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + + if(nread == 0) { + /* Premature EOF -- adjust the bufsize to the new value */ + ca_file_bufsize = total_bytes_read; + } + else { + total_bytes_read += (long)nread; + } + } + + /* null-terminate the buffer */ + ca_file_buffer[ca_file_bufsize] = '\0'; + + result = add_certs_data_to_store(trust_store, + ca_file_buffer, ca_file_bufsize, + ca_file, + data); + +cleanup: + if(ca_file_handle) { + curlx_fclose(ca_file_handle); + } + curlx_safefree(ca_file_buffer); + + return result; +} + +/* + * Returns the number of characters necessary to populate all the host_names. + * If host_names is not NULL, populate it with all the hostnames. Each string + * in the host_names is null-terminated and the last string is double + * null-terminated. If no DNS names are found, a single null-terminated empty + * string is returned. + */ +static DWORD cert_get_name_string(struct Curl_easy *data, + CERT_CONTEXT *cert_context, + LPTSTR host_names, + DWORD length, + PCERT_ALT_NAME_INFO alt_name_info, + BOOL Win8_compat) +{ + DWORD actual_length = 0; + BOOL compute_content = FALSE; + LPTSTR current_pos = NULL; + DWORD i; + + /* CERT_NAME_SEARCH_ALL_NAMES_FLAG is available from Windows 8 onwards. */ + if(Win8_compat) { +/* Offered by mingw-w64 v4+, MS SDK 8.0/~VS2012+ */ +#ifndef CERT_NAME_SEARCH_ALL_NAMES_FLAG +#define CERT_NAME_SEARCH_ALL_NAMES_FLAG 0x2 +#endif + /* CertGetNameString provides the 8-bit character string without + * any decoding */ + DWORD name_flags = + CERT_NAME_DISABLE_IE4_UTF8_FLAG | CERT_NAME_SEARCH_ALL_NAMES_FLAG; + actual_length = CertGetNameString(cert_context, + CERT_NAME_DNS_TYPE, + name_flags, + NULL, + host_names, + length); + return actual_length; + } + + if(!alt_name_info) + return 0; + + compute_content = host_names && length != 0; + + /* Initialize default return values. */ + actual_length = 1; + if(compute_content) { + *host_names = '\0'; + } + + current_pos = host_names; + + /* Iterate over the alternate names and populate host_names. */ + for(i = 0; i < alt_name_info->cAltEntry; i++) { + const CERT_ALT_NAME_ENTRY *entry = &alt_name_info->rgAltEntry[i]; + wchar_t *dns_w = NULL; + size_t current_length = 0; + + if(entry->dwAltNameChoice != CERT_ALT_NAME_DNS_NAME) { + continue; + } + if(!entry->pwszDNSName) { + infof(data, "schannel: Empty DNS name."); + continue; + } + current_length = wcslen(entry->pwszDNSName) + 1; + if(!compute_content) { + actual_length += (DWORD)current_length; + continue; + } + /* Sanity check to prevent buffer overrun. */ + if((actual_length + current_length) > length) { + failf(data, "schannel: Not enough memory to list all hostnames."); + break; + } + dns_w = entry->pwszDNSName; + /* pwszDNSName is in ia5 string format and hence does not contain any + * non-ASCII characters. */ + while(*dns_w != '\0') { + *current_pos++ = (TCHAR)(*dns_w++); + } + *current_pos++ = '\0'; + actual_length += (DWORD)current_length; + } + if(compute_content) { + /* Last string has double null-terminator. */ + *current_pos = '\0'; + } + return actual_length; +} + +/* + * Returns TRUE if the hostname is a numeric IPv4/IPv6 Address, + * and populates the buffer with IPv4/IPv6 info. + */ + +static bool get_num_host_info(struct num_ip_data *ip_blob, LPCSTR hostname) +{ + struct in_addr ia; + int res = curlx_inet_pton(AF_INET, hostname, &ia); + if(res) { + ip_blob->size = sizeof(struct in_addr); + memcpy(&ip_blob->bData.ia, &ia, sizeof(struct in_addr)); + return TRUE; + } + else { + struct in6_addr ia6; + res = curlx_inet_pton(AF_INET6, hostname, &ia6); + if(res) { + ip_blob->size = sizeof(struct in6_addr); + memcpy(&ip_blob->bData.ia6, &ia6, sizeof(struct in6_addr)); + return TRUE; + } + } + return FALSE; +} + +static bool get_alt_name_info(struct Curl_easy *data, + PCCERT_CONTEXT ctx, + PCERT_ALT_NAME_INFO *alt_name_info, + LPDWORD alt_name_info_size) +{ + PCERT_INFO cert_info = NULL; + PCERT_EXTENSION extension = NULL; + CRYPT_DECODE_PARA decode_para = { sizeof(CRYPT_DECODE_PARA), NULL, NULL }; + + if(!ctx) { + failf(data, "schannel: Null certificate context."); + return FALSE; + } + + cert_info = ctx->pCertInfo; + if(!cert_info) { + failf(data, "schannel: Null certificate info."); + return FALSE; + } + + extension = CertFindExtension(szOID_SUBJECT_ALT_NAME2, + cert_info->cExtension, + cert_info->rgExtension); + if(!extension) { + failf(data, "schannel: CertFindExtension() returned no extension."); + return FALSE; + } + + if(!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, + szOID_SUBJECT_ALT_NAME2, + extension->Value.pbData, + extension->Value.cbData, + CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, + &decode_para, + alt_name_info, + alt_name_info_size)) { + failf(data, "schannel: CryptDecodeObjectEx() returned no alternate name " + "information."); + return FALSE; + } + return TRUE; +} + +/* Verify the server's hostname */ +CURLcode Curl_verify_host(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + CURLcode result = CURLE_PEER_FAILED_VERIFICATION; + struct ssl_connect_data *connssl = cf->ctx; + CERT_CONTEXT *pCertContextServer = NULL; + SECURITY_STATUS sspi_status; + TCHAR *cert_hostname_buff = NULL; + size_t cert_hostname_buff_index = 0; + const char *conn_hostname = connssl->peer.origin->hostname; + size_t hostlen = strlen(conn_hostname); + DWORD len = 0; + DWORD actual_len = 0; + PCERT_ALT_NAME_INFO alt_name_info = NULL; + DWORD alt_name_info_size = 0; + struct num_ip_data ip_blob = { 0 }; + bool Win8_compat; + struct num_ip_data *p = &ip_blob; + DWORD i; + + sspi_status = + Curl_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle, + SECPKG_ATTR_REMOTE_CERT_CONTEXT, + &pCertContextServer); + + if((sspi_status != SEC_E_OK) || !pCertContextServer) { + char buffer[WINAPI_ERROR_LEN]; + failf(data, "schannel: Failed to read remote certificate context: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + goto cleanup; + } + + Win8_compat = curlx_verify_windows_version(6, 2, 0, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL); + if(get_num_host_info(p, conn_hostname) || !Win8_compat) { + if(!get_alt_name_info(data, pCertContextServer, + &alt_name_info, &alt_name_info_size)) { + goto cleanup; + } + } + + if(p->size && alt_name_info) { + for(i = 0; i < alt_name_info->cAltEntry; ++i) { + PCERT_ALT_NAME_ENTRY entry = &alt_name_info->rgAltEntry[i]; + if(entry->dwAltNameChoice == CERT_ALT_NAME_IP_ADDRESS) { + if(entry->IPAddress.cbData == p->size) { + if(!memcmp(entry->IPAddress.pbData, &p->bData, + entry->IPAddress.cbData)) { + result = CURLE_OK; + infof(data, + "schannel: connection hostname (%s) matched cert's IP address!", + conn_hostname); + break; + } + } + } + } + } + else { + /* Determine the size of the string needed for the cert hostname */ + len = cert_get_name_string(data, pCertContextServer, + NULL, 0, alt_name_info, Win8_compat); + if(len == 0) { + failf(data, + "schannel: CertGetNameString() returned no " + "certificate name information"); + goto cleanup; + } + + /* CertGetNameString guarantees that the returned name does not contain + * embedded null bytes. This appears to be undocumented behavior. + */ + cert_hostname_buff = curlx_malloc(len * sizeof(TCHAR)); + if(!cert_hostname_buff) { + result = CURLE_OUT_OF_MEMORY; + goto cleanup; + } + actual_len = cert_get_name_string(data, pCertContextServer, + (LPTSTR)cert_hostname_buff, len, + alt_name_info, Win8_compat); + + /* Sanity check */ + if(actual_len != len) { + failf(data, + "schannel: CertGetNameString() returned certificate " + "name information of unexpected size"); + goto cleanup; + } + + /* cert_hostname_buff contains all DNS names, where each name is + * null-terminated and the last DNS name is double null-terminated. Due to + * this encoding, use the length of the buffer to iterate over all names. + */ + while(cert_hostname_buff_index < len && + cert_hostname_buff[cert_hostname_buff_index] != TEXT('\0') && + result == CURLE_PEER_FAILED_VERIFICATION) { + char *cert_hostname; + + /* Comparing the cert name and the connection hostname encoded as UTF-8 + * is acceptable since both values are assumed to use ASCII + * (or some equivalent) encoding + */ + cert_hostname = curlx_convert_tchar_to_UTF8( + &cert_hostname_buff[cert_hostname_buff_index]); + if(!cert_hostname) { + result = CURLE_OUT_OF_MEMORY; + } + else { + if(Curl_cert_hostcheck(cert_hostname, strlen(cert_hostname), + conn_hostname, hostlen)) { + infof(data, "schannel: connection hostname (%s) validated " + "against certificate name (%s)", + conn_hostname, cert_hostname); + result = CURLE_OK; + } + else { + size_t cert_hostname_len; + + infof(data, + "schannel: connection hostname (%s) did not match " + "against certificate name (%s)", + conn_hostname, cert_hostname); + + cert_hostname_len = + _tcslen(&cert_hostname_buff[cert_hostname_buff_index]); + + /* Move on to next cert name */ + cert_hostname_buff_index += cert_hostname_len + 1; + + result = CURLE_PEER_FAILED_VERIFICATION; + } + curlx_free(cert_hostname); + } + } + + if(result == CURLE_PEER_FAILED_VERIFICATION) { + failf(data, + "schannel: CertGetNameString() failed to match " + "connection hostname (%s) against server certificate names", + conn_hostname); + } + else if(result != CURLE_OK) + failf(data, "schannel: server certificate name verification failed"); + } + +cleanup: + LocalFree(alt_name_info); + curlx_safefree(cert_hostname_buff); + + if(pCertContextServer) + CertFreeCertificateContext(pCertContextServer); + + return result; +} + +/* Verify the server's certificate and hostname */ +CURLcode Curl_verify_certificate(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + SECURITY_STATUS sspi_status; + CURLcode result = CURLE_OK; + CERT_CONTEXT *pCertContextServer = NULL; + const CERT_CHAIN_CONTEXT *pChainContext = NULL; + HCERTCHAINENGINE cert_chain_engine = NULL; + HCERTSTORE trust_store = NULL; + HCERTSTORE own_trust_store = NULL; + + DEBUGASSERT(BACKEND); + + sspi_status = + Curl_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle, + SECPKG_ATTR_REMOTE_CERT_CONTEXT, + &pCertContextServer); + + if((sspi_status != SEC_E_OK) || !pCertContextServer) { + char buffer[WINAPI_ERROR_LEN]; + failf(data, "schannel: Failed to read remote certificate context: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); + result = CURLE_PEER_FAILED_VERIFICATION; + } + + if(result == CURLE_OK && + (conn_config->CAfile || conn_config->ca_info_blob) && + BACKEND->use_manual_cred_validation) { + /* + * Create a chain engine that uses the certificates in the CA file as + * trusted certificates. This is only supported on Windows 7+. + */ + + if(curlx_verify_windows_version(6, 1, 0, PLATFORM_WINNT, + VERSION_LESS_THAN)) { + failf(data, "schannel: this version of Windows is too old to support " + "certificate verification via CA bundle file."); + result = CURLE_SSL_CACERT_BADFILE; + } + else { + /* try cache */ + trust_store = Curl_schannel_get_cached_cert_store(cf, data); + + if(trust_store) { + infof(data, "schannel: reusing certificate store from cache"); + } + else { + /* Open the certificate store */ + trust_store = CertOpenStore(CERT_STORE_PROV_MEMORY, + 0, + (HCRYPTPROV)NULL, + CERT_STORE_CREATE_NEW_FLAG, + NULL); + if(!trust_store) { + char buffer[WINAPI_ERROR_LEN]; + failf(data, "schannel: failed to create certificate store: %s", + curlx_winapi_strerror(GetLastError(), buffer, sizeof(buffer))); + result = CURLE_SSL_CACERT_BADFILE; + } + else { + const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; + own_trust_store = trust_store; + + if(ca_info_blob) { + result = add_certs_data_to_store(trust_store, + (const char *)ca_info_blob->data, + ca_info_blob->len, + "(memory blob)", + data); + } + else { + result = add_certs_file_to_store(trust_store, + conn_config->CAfile, + data); + } + if(result == CURLE_OK) { + if(Curl_schannel_set_cached_cert_store(cf, data, trust_store)) { + own_trust_store = NULL; + } + } + } + } + } + + if(result == CURLE_OK) { + struct cert_chain_engine_config_win8 engine_config; + BOOL create_engine_result; + + memset(&engine_config, 0, sizeof(engine_config)); + engine_config.hExclusiveRoot = trust_store; + + /* Win8/Server2012 allows us to match partial chains */ + if(curlx_verify_windows_version(6, 2, 0, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL) && + !ssl_config->no_partialchain) { + engine_config.cbSize = sizeof(engine_config); + engine_config.dwExclusiveFlags = CERT_CHAIN_EXCLUSIVE_ENABLE_CA_FLAG; + } + else + engine_config.cbSize = sizeof(struct cert_chain_engine_config_win7); + + /* CertCreateCertificateChainEngine checks the expected size of the + * CERT_CHAIN_ENGINE_CONFIG structure and fail if the specified size + * does not match the expected size. When this occurs, it indicates that + * CAINFO is not supported on the version of Windows in use. + */ + create_engine_result = + CertCreateCertificateChainEngine( + (CERT_CHAIN_ENGINE_CONFIG *)&engine_config, &cert_chain_engine); + if(!create_engine_result) { + char buffer[WINAPI_ERROR_LEN]; + failf(data, + "schannel: failed to create certificate chain engine: %s", + curlx_winapi_strerror(GetLastError(), buffer, sizeof(buffer))); + result = CURLE_SSL_CACERT_BADFILE; + } + } + } + + if(result == CURLE_OK) { + CERT_CHAIN_PARA ChainPara; + LPSTR serverAuthOID = CURL_UNCONST(szOID_PKIX_KP_SERVER_AUTH); + + memset(&ChainPara, 0, sizeof(ChainPara)); + ChainPara.cbSize = sizeof(ChainPara); + ChainPara.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND; + ChainPara.RequestedUsage.Usage.cUsageIdentifier = 1; + ChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = &serverAuthOID; + + if(!CertGetCertificateChain(cert_chain_engine, + pCertContextServer, + NULL, + pCertContextServer->hCertStore, + &ChainPara, + (ssl_config->no_revoke ? 0 : + CERT_CHAIN_REVOCATION_CHECK_CHAIN), + NULL, + &pChainContext)) { + char buffer[WINAPI_ERROR_LEN]; + failf(data, "schannel: failed to get the certificate chain: %s", + curlx_winapi_strerror(GetLastError(), buffer, sizeof(buffer))); + pChainContext = NULL; + result = CURLE_PEER_FAILED_VERIFICATION; + } + + if(result == CURLE_OK) { + CERT_SIMPLE_CHAIN *pSimpleChain = pChainContext->rgpChain[0]; + DWORD dwTrustErrorMask = ~(DWORD)(CERT_TRUST_IS_NOT_TIME_NESTED); + dwTrustErrorMask &= pSimpleChain->TrustStatus.dwErrorStatus; + + if(ssl_config->revoke_best_effort) { + /* Ignore errors when root certificates are missing the revocation + * list URL, or when the list could not be downloaded because the + * server is currently unreachable. */ + dwTrustErrorMask &= ~(DWORD)(CERT_TRUST_REVOCATION_STATUS_UNKNOWN | + CERT_TRUST_IS_OFFLINE_REVOCATION); + } + + if(dwTrustErrorMask) { + if(dwTrustErrorMask & CERT_TRUST_IS_REVOKED) + failf(data, "schannel: trust for this certificate or one of " + "the certificates in the certificate chain has been revoked"); + else if(dwTrustErrorMask & CERT_TRUST_IS_PARTIAL_CHAIN) + failf(data, "schannel: the certificate chain is incomplete"); + else if(dwTrustErrorMask & CERT_TRUST_IS_UNTRUSTED_ROOT) + failf(data, "schannel: the certificate or certificate chain is " + "based on an untrusted root"); + else if(dwTrustErrorMask & CERT_TRUST_IS_NOT_TIME_VALID) + failf(data, "schannel: this certificate or one of the certificates " + "in the certificate chain is not time valid"); + else if(dwTrustErrorMask & CERT_TRUST_REVOCATION_STATUS_UNKNOWN) + failf(data, "schannel: the revocation status is unknown"); + else + failf(data, "schannel: error 0x%08lx", dwTrustErrorMask); + result = CURLE_PEER_FAILED_VERIFICATION; + } + } + } + + if(result == CURLE_OK) { + if(conn_config->verifyhost) { + result = Curl_verify_host(cf, data); + } + } + + if(cert_chain_engine) { + CertFreeCertificateChainEngine(cert_chain_engine); + } + + if(own_trust_store) { + CertCloseStore(own_trust_store, 0); + } + + if(pChainContext) + CertFreeCertificateChain(pChainContext); + + if(pCertContextServer) + CertFreeCertificateContext(pCertContextServer); + + return result; +} + +#endif /* USE_SCHANNEL */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls.c new file mode 100644 index 0000000000..f6cc370890 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls.c @@ -0,0 +1,1811 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* This file is for implementing all "generic" SSL functions that all libcurl + internals should use. It is then responsible for calling the proper + "backend" function. + + SSL-functions in libcurl should call functions in this source file, and not + to any specific SSL-layer. + + Curl_ssl_ - prefix for generic ones + + Note that this source code uses the functions of the configured SSL + backend via the global Curl_ssl instance. + + "SSL/TLS Strong Encryption: An Introduction" + https://httpd.apache.org/docs/2.0/ssl/ssl_intro.html + */ + +#include "curl_setup.h" + +#include "urldata.h" +#include "cfilters.h" + +#include "vtls/vtls.h" /* generic SSL protos etc */ +#include "vtls/vtls_int.h" +#include "vtls/vtls_scache.h" +#include "vtls/keylog.h" + +#include "vtls/openssl.h" /* OpenSSL versions */ +#include "vtls/gtls.h" /* GnuTLS versions */ +#include "vtls/wolfssl.h" /* wolfSSL versions */ +#include "vtls/schannel.h" /* Schannel SSPI version */ +#include "vtls/mbedtls.h" /* mbedTLS versions */ +#include "vtls/rustls.h" /* Rustls versions */ + +#include "slist.h" +#include "curl_trc.h" +#include "strcase.h" +#include "url.h" +#include "progress.h" +#include "curlx/fopen.h" +#include "curl_sha256.h" +#include "curlx/base64.h" +#include "curlx/inet_pton.h" +#include "connect.h" +#include "select.h" +#include "setopt.h" +#include "vdns/cf-dns.h" +#include "curlx/strdup.h" +#include "curlx/strcopy.h" + +#ifdef USE_APPLE_SECTRUST +#include <Security/Security.h> +#endif + +#ifdef USE_SSL +#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_PROXY) +static const struct alpn_spec ALPN_SPEC_H11 = { + { ALPN_HTTP_1_1 }, 1 +}; +static const struct alpn_spec ALPN_SPEC_H10_H11 = { + { ALPN_HTTP_1_0, ALPN_HTTP_1_1 }, 2 +}; +#ifdef USE_HTTP2 +static const struct alpn_spec ALPN_SPEC_H2 = { + { ALPN_H2 }, 1 +}; +static const struct alpn_spec ALPN_SPEC_H2_H11 = { + { ALPN_H2, ALPN_HTTP_1_1 }, 2 +}; +static const struct alpn_spec ALPN_SPEC_H11_H2 = { + { ALPN_HTTP_1_1, ALPN_H2 }, 2 +}; +#endif /* USE_HTTP2 */ + +static const struct alpn_spec *alpn_get_spec(http_majors wanted, + http_majors preferred, + bool only_http_10, + bool use_alpn) +{ + if(!use_alpn) + return NULL; + /* If HTTP/1.0 is the wanted protocol then use ALPN http/1.0 and http/1.1. + This is for compatibility reasons since some HTTP/1.0 servers with old + ALPN implementations understand ALPN http/1.1 but not http/1.0. */ + if(only_http_10 && (wanted & CURL_HTTP_V1x)) + return &ALPN_SPEC_H10_H11; +#ifdef USE_HTTP2 + if(wanted & CURL_HTTP_V2x) { + if(wanted & CURL_HTTP_V1x) + return (preferred == CURL_HTTP_V1x) ? + &ALPN_SPEC_H11_H2 : &ALPN_SPEC_H2_H11; + return &ALPN_SPEC_H2; + } +#else + (void)wanted; + (void)preferred; +#endif + return &ALPN_SPEC_H11; +} +#endif /* !CURL_DISABLE_HTTP || !CURL_DISABLE_PROXY */ +#endif /* USE_SSL */ + +#ifdef USE_SSL +static int multissl_setup(const struct Curl_ssl *backend); +#endif + +curl_sslbackend Curl_ssl_backend(void) +{ +#ifdef USE_SSL + multissl_setup(NULL); + return Curl_ssl->info.id; +#else + return CURLSSLBACKEND_NONE; +#endif +} + +#ifdef USE_SSL + +/* "global" init done? */ +static bool init_ssl = FALSE; + +/** + * Global SSL init + * + * @retval 0 error initializing SSL + * @retval 1 SSL initialized successfully + */ +int Curl_ssl_init(void) +{ + /* make sure this is only done once */ + if(init_ssl) + return 1; + init_ssl = TRUE; /* never again */ + + if(Curl_ssl->init) + return Curl_ssl->init(); + return 1; +} + +static bool ssl_prefs_check(struct Curl_easy *data) +{ + /* check for CURLOPT_SSLVERSION invalid parameter value */ + const unsigned char sslver = data->set.ssl.primary.version; + if(sslver >= CURL_SSLVERSION_LAST) { + failf(data, "Unrecognized parameter value passed via CURLOPT_SSLVERSION"); + return FALSE; + } + + switch(data->set.ssl.primary.version_max) { + case CURL_SSLVERSION_MAX_NONE: + case CURL_SSLVERSION_MAX_DEFAULT: + break; + + default: + if((data->set.ssl.primary.version_max >> 16) < sslver) { + failf(data, "CURL_SSLVERSION_MAX incompatible with CURL_SSLVERSION"); + return FALSE; + } + } + + return TRUE; +} + +static struct ssl_connect_data *cf_ctx_new(struct Curl_easy *data, + const struct alpn_spec *alpn) +{ + struct ssl_connect_data *ctx; + + (void)data; + ctx = curlx_calloc(1, sizeof(*ctx)); + if(!ctx) + return NULL; + + ctx->ssl_impl = Curl_ssl; + ctx->alpn = alpn; + Curl_bufq_init2(&ctx->earlydata, CURL_SSL_EARLY_MAX, 1, BUFQ_OPT_NO_SPARES); + ctx->backend = curlx_calloc(1, ctx->ssl_impl->sizeof_ssl_backend_data); + if(!ctx->backend) { + curlx_free(ctx); + return NULL; + } + return ctx; +} + +static void cf_ctx_free(struct ssl_connect_data *ctx) +{ + if(ctx) { + curlx_safefree(ctx->negotiated.alpn); + Curl_bufq_free(&ctx->earlydata); + curlx_free(ctx->backend); + curlx_free(ctx); + } +} + +CURLcode Curl_ssl_get_channel_binding(struct Curl_easy *data, int8_t sockindex, + struct dynbuf *binding) +{ + if(Curl_ssl->get_channel_binding) + return Curl_ssl->get_channel_binding(data, sockindex, binding); + return CURLE_OK; +} + +void Curl_ssl_close_all(struct Curl_easy *data) +{ + if(Curl_ssl->close_all) + Curl_ssl->close_all(data); +} + +CURLcode Curl_ssl_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct ssl_connect_data *connssl = cf->ctx; + + if(connssl->io_need) { + curl_socket_t sock = Curl_conn_cf_get_socket(cf->next, data); + CURLcode result = CURLE_OK; + if(sock != CURL_SOCKET_BAD) { + if(connssl->io_need & CURL_SSL_IO_NEED_SEND) { + result = Curl_pollset_set_out_only(data, ps, sock); + CURL_TRC_CF(data, cf, "adjust_pollset, POLLOUT fd=%" FMT_SOCKET_T, + sock); + } + else { + result = Curl_pollset_set_in_only(data, ps, sock); + CURL_TRC_CF(data, cf, "adjust_pollset, POLLIN fd=%" FMT_SOCKET_T, + sock); + } + } + return result; + } + return CURLE_OK; +} + +/* Selects an SSL crypto engine + */ +CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine) +{ + if(Curl_ssl->set_engine) + return Curl_ssl->set_engine(data, engine); + return CURLE_NOT_BUILT_IN; +} + +/* Selects the default SSL crypto engine + */ +CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data) +{ + if(Curl_ssl->set_engine_default) + return Curl_ssl->set_engine_default(data); + return CURLE_NOT_BUILT_IN; +} + +/* Return list of OpenSSL crypto engine names. */ +struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data) +{ + if(Curl_ssl->engines_list) + return Curl_ssl->engines_list(data); + return NULL; +} + +static size_t multissl_version(char *buffer, size_t size); + +void Curl_ssl_version(char *buffer, size_t size) +{ +#ifdef CURL_WITH_MULTI_SSL + (void)multissl_version(buffer, size); +#else + (void)Curl_ssl->version(buffer, size); +#endif +} + +void Curl_ssl_free_certinfo(struct Curl_easy *data) +{ + struct curl_certinfo *ci = &data->info.certs; + + if(ci->num_of_certs) { + /* free all individual lists used */ + int i; + for(i = 0; i < ci->num_of_certs; i++) { + curl_slist_free_all(ci->certinfo[i]); + ci->certinfo[i] = NULL; + } + + curlx_safefree(ci->certinfo); /* free the actual array too */ + ci->num_of_certs = 0; + } +} + +CURLcode Curl_ssl_init_certinfo(struct Curl_easy *data, int num) +{ + struct curl_certinfo *ci = &data->info.certs; + struct curl_slist **table; + + /* Free any previous certificate information structures */ + Curl_ssl_free_certinfo(data); + + /* Allocate the required certificate information structures */ + table = curlx_calloc((size_t)num, sizeof(struct curl_slist *)); + if(!table) + return CURLE_OUT_OF_MEMORY; + + ci->num_of_certs = num; + ci->certinfo = table; + + return CURLE_OK; +} + +/* + * 'value' is NOT a null-terminated string + */ +CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data, + int certnum, + const char *label, + const char *value, + size_t valuelen) +{ + struct curl_certinfo *ci = &data->info.certs; + struct curl_slist *nl; + CURLcode result = CURLE_OK; + struct dynbuf build; + + DEBUGASSERT(certnum < ci->num_of_certs); + + curlx_dyn_init(&build, CURL_X509_STR_MAX); + + if(curlx_dyn_add(&build, label) || + curlx_dyn_addn(&build, ":", 1) || + curlx_dyn_addn(&build, value, valuelen)) + return CURLE_OUT_OF_MEMORY; + + nl = Curl_slist_append_nodup(ci->certinfo[certnum], curlx_dyn_ptr(&build)); + if(!nl) { + curlx_dyn_free(&build); + curl_slist_free_all(ci->certinfo[certnum]); + result = CURLE_OUT_OF_MEMORY; + } + + ci->certinfo[certnum] = nl; + return result; +} + +/* get length bytes of randomness */ +CURLcode Curl_ssl_random(struct Curl_easy *data, + unsigned char *buffer, size_t length) +{ + DEBUGASSERT(length == sizeof(int)); + if(Curl_ssl->random) + return Curl_ssl->random(data, buffer, length); + else + return CURLE_NOT_BUILT_IN; +} + +/* + * Public key pem to der conversion + */ + +static CURLcode pubkey_pem_to_der(const char *pem, + unsigned char **der, size_t *der_len) +{ + const char *begin_pos, *end_pos; + size_t pem_count, pem_len; + CURLcode result; + struct dynbuf pbuf; + + /* if no pem, exit. */ + if(!pem) + return CURLE_BAD_CONTENT_ENCODING; + + curlx_dyn_init(&pbuf, MAX_PINNED_PUBKEY_SIZE); + + begin_pos = strstr(pem, "-----BEGIN PUBLIC KEY-----"); + if(!begin_pos) + return CURLE_BAD_CONTENT_ENCODING; + + pem_count = begin_pos - pem; + /* Invalid if not at beginning AND not directly following \n */ + if(pem_count && '\n' != pem[pem_count - 1]) + return CURLE_BAD_CONTENT_ENCODING; + + /* 26 is length of "-----BEGIN PUBLIC KEY-----" */ + pem_count += 26; + + /* Invalid if not directly following \n */ + end_pos = strstr(pem + pem_count, "\n-----END PUBLIC KEY-----"); + if(!end_pos) + return CURLE_BAD_CONTENT_ENCODING; + + pem_len = end_pos - pem; + + /* + * Here we loop through the pem array one character at a time between the + * correct indices, and place each character that is not '\n' or '\r' + * into the stripped_pem array, which should represent the raw base64 string + */ + while(pem_count < pem_len) { + if('\n' != pem[pem_count] && '\r' != pem[pem_count]) { + result = curlx_dyn_addn(&pbuf, &pem[pem_count], 1); + if(result) + return result; + } + ++pem_count; + } + + if(curlx_dyn_len(&pbuf)) { + result = curlx_base64_decode(curlx_dyn_ptr(&pbuf), der, der_len); + curlx_dyn_free(&pbuf); + } + else + result = CURLE_BAD_CONTENT_ENCODING; + + return result; +} + +/* + * Generic pinned public key check. + */ + +CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data, + const char *pinnedpubkey, + const unsigned char *pubkey, size_t pubkeylen) +{ + CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; + + /* if a path was not specified, do not pin */ + if(!pinnedpubkey) + return CURLE_OK; + if(!pubkey || !pubkeylen) + return result; + + /* only do this if pinnedpubkey starts with "sha256//", length 8 */ + if(!strncmp(pinnedpubkey, "sha256//", 8)) { + CURLcode encode; + char *cert_hash = NULL; + const char *pinned_hash, *end_pos; + size_t cert_hash_len = 0, pinned_hash_len; + unsigned char *sha256sumdigest; + + if(!Curl_ssl->sha256sum) { + /* without sha256 support, this cannot match */ + return result; + } + + /* compute sha256sum of public key */ + sha256sumdigest = curlx_malloc(CURL_SHA256_DIGEST_LENGTH); + if(!sha256sumdigest) + return CURLE_OUT_OF_MEMORY; + encode = Curl_ssl->sha256sum(pubkey, pubkeylen, + sha256sumdigest, CURL_SHA256_DIGEST_LENGTH); + + if(!encode) + encode = curlx_base64_encode(sha256sumdigest, + CURL_SHA256_DIGEST_LENGTH, + &cert_hash, &cert_hash_len); + curlx_safefree(sha256sumdigest); + + if(encode) + return encode; + + infof(data, " public key hash: sha256//%s", cert_hash); + + pinned_hash = pinnedpubkey; + while(pinned_hash && + !strncmp(pinned_hash, "sha256//", CURL_CSTRLEN("sha256//"))) { + pinned_hash = pinned_hash + CURL_CSTRLEN("sha256//"); + end_pos = strchr(pinned_hash, ';'); + pinned_hash_len = end_pos ? + (size_t)(end_pos - pinned_hash) : strlen(pinned_hash); + + /* compare base64 sha256 digests */ + if(cert_hash_len == pinned_hash_len && + !memcmp(cert_hash, pinned_hash, cert_hash_len)) { + DEBUGF(infof(data, "public key hash matches pinned value")); + result = CURLE_OK; + break; + } + + DEBUGF(infof(data, "public key hash does not match 'sha256//%.*s'", + (int)pinned_hash_len, pinned_hash)); + /* next one or we are at the end */ + pinned_hash = end_pos ? (end_pos + 1) : NULL; + } + curlx_safefree(cert_hash); + } + else { + long filesize; + size_t size, pem_len; + CURLcode pem_read; + struct dynbuf buf; + unsigned char *pem_ptr = NULL; + size_t left; + FILE *fp = curlx_fopen(pinnedpubkey, "rb"); + if(!fp) + return result; + + curlx_dyn_init(&buf, MAX_PINNED_PUBKEY_SIZE); + + /* Determine the file's size */ + if(fseek(fp, 0, SEEK_END)) + goto end; + filesize = ftell(fp); + if(fseek(fp, 0, SEEK_SET)) + goto end; + if(filesize < 0 || filesize > MAX_PINNED_PUBKEY_SIZE) + goto end; + + /* + * if the size of our certificate is bigger than the file + * size then it cannot match + */ + size = curlx_sotouz((curl_off_t)filesize); + if(pubkeylen > size) + goto end; + + /* + * Read the file into the dynbuf + */ + left = size; + do { + char buffer[1024]; + size_t want = left > sizeof(buffer) ? sizeof(buffer) : left; + if(fread(buffer, 1, want, fp) != want) + goto end; + if(curlx_dyn_addn(&buf, buffer, want)) + goto end; + left -= want; + } while(left); + + /* If the sizes are the same, it cannot be base64 encoded, must be der */ + if(pubkeylen == size) { + if(!memcmp(pubkey, curlx_dyn_ptr(&buf), pubkeylen)) + result = CURLE_OK; + goto end; + } + + /* + * Otherwise we assume it is PEM and try to decode it after placing + * null-terminator + */ + pem_read = pubkey_pem_to_der(curlx_dyn_ptr(&buf), &pem_ptr, &pem_len); + /* if it was not read successfully, exit */ + if(pem_read) + goto end; + + /* + * if the size of our certificate does not match the size of + * the decoded file, they cannot be the same, otherwise compare + */ + if(pubkeylen == pem_len && !memcmp(pubkey, pem_ptr, pubkeylen)) + result = CURLE_OK; +end: + curlx_dyn_free(&buf); + curlx_safefree(pem_ptr); + curlx_fclose(fp); + } + + return result; +} + +/* + * Check whether the SSL backend supports the status_request extension. + */ +bool Curl_ssl_cert_status_request(void) +{ + if(Curl_ssl->cert_status_request) + return Curl_ssl->cert_status_request(); + return FALSE; +} + +static int multissl_init(void) +{ + if(multissl_setup(NULL)) + return 1; + if(Curl_ssl->init) + return Curl_ssl->init(); + return 1; +} + +static CURLcode multissl_random(struct Curl_easy *data, + unsigned char *entropy, size_t length) +{ + if(multissl_setup(NULL)) + return CURLE_FAILED_INIT; + return Curl_ssl->random(data, entropy, length); +} + +static CURLcode multissl_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + if(multissl_setup(NULL)) + return CURLE_FAILED_INIT; + return Curl_ssl->do_connect(cf, data, done); +} + +static CURLcode multissl_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + if(multissl_setup(NULL)) + return CURLE_OK; + return Curl_ssl->adjust_pollset(cf, data, ps); +} + +static void *multissl_get_internals(struct ssl_connect_data *connssl, + CURLINFO info) +{ + if(multissl_setup(NULL)) + return NULL; + return Curl_ssl->get_internals(connssl, info); +} + +static void multissl_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + if(multissl_setup(NULL)) + return; + Curl_ssl->close(cf, data); +} + +static CURLcode multissl_recv_plain(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, size_t len, size_t *pnread) +{ + if(multissl_setup(NULL)) + return CURLE_FAILED_INIT; + return Curl_ssl->recv_plain(cf, data, buf, len, pnread); +} + +static CURLcode multissl_send_plain(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *mem, size_t len, + size_t *pnwritten) +{ + if(multissl_setup(NULL)) + return CURLE_FAILED_INIT; + return Curl_ssl->send_plain(cf, data, mem, len, pnwritten); +} + +static const struct Curl_ssl Curl_ssl_multi = { + { CURLSSLBACKEND_NONE, "multi" }, /* info */ + 0, /* supports nothing */ + (size_t)-1, /* something insanely large to be on the safe side */ + + multissl_init, /* init */ + NULL, /* cleanup */ + multissl_version, /* version */ + NULL, /* shutdown */ + NULL, /* data_pending */ + multissl_random, /* random */ + NULL, /* cert_status_request */ + multissl_connect, /* connect */ + multissl_adjust_pollset, /* adjust_pollset */ + multissl_get_internals, /* get_internals */ + multissl_close, /* close_one */ + NULL, /* close_all */ + NULL, /* set_engine */ + NULL, /* set_engine_default */ + NULL, /* engines_list */ + NULL, /* sha256sum */ + multissl_recv_plain, /* recv decrypted data */ + multissl_send_plain, /* send data to encrypt */ + NULL, /* get_channel_binding */ +}; + +const struct Curl_ssl *Curl_ssl = +#ifdef CURL_WITH_MULTI_SSL + &Curl_ssl_multi; +#elif defined(USE_WOLFSSL) + &Curl_ssl_wolfssl; +#elif defined(USE_GNUTLS) + &Curl_ssl_gnutls; +#elif defined(USE_MBEDTLS) + &Curl_ssl_mbedtls; +#elif defined(USE_RUSTLS) + &Curl_ssl_rustls; +#elif defined(USE_OPENSSL) + &Curl_ssl_openssl; +#elif defined(USE_SCHANNEL) + &Curl_ssl_schannel; +#else +#error "Missing struct Curl_ssl for selected SSL backend" +#endif + +static const struct Curl_ssl *available_backends[] = { +#ifdef USE_WOLFSSL + &Curl_ssl_wolfssl, +#endif +#ifdef USE_GNUTLS + &Curl_ssl_gnutls, +#endif +#ifdef USE_MBEDTLS + &Curl_ssl_mbedtls, +#endif +#ifdef USE_OPENSSL + &Curl_ssl_openssl, +#endif +#ifdef USE_SCHANNEL + &Curl_ssl_schannel, +#endif +#ifdef USE_RUSTLS + &Curl_ssl_rustls, +#endif + NULL +}; + +/* Global cleanup */ +void Curl_ssl_cleanup(void) +{ + if(init_ssl) { + /* only cleanup if we did a previous init */ + if(Curl_ssl->cleanup) + Curl_ssl->cleanup(); +#ifdef CURL_WITH_MULTI_SSL + Curl_ssl = &Curl_ssl_multi; +#endif + init_ssl = FALSE; + } +} + +static size_t multissl_version(char *buffer, size_t size) +{ + static const struct Curl_ssl *selected; + static char backends[200]; + static size_t backends_len; + const struct Curl_ssl *current; + + current = Curl_ssl == &Curl_ssl_multi ? available_backends[0] : Curl_ssl; + + if(current != selected) { + char *p = backends; + const char *end = backends + sizeof(backends); + int i; + + selected = current; + + backends[0] = '\0'; + + for(i = 0; available_backends[i]; ++i) { + char vb[200]; + bool paren = (selected != available_backends[i]); + + if(available_backends[i]->version(vb, sizeof(vb))) { + p += curl_msnprintf(p, end - p, "%s%s%s%s", (p != backends ? " " : ""), + (paren ? "(" : ""), vb, (paren ? ")" : "")); + } + } + + backends_len = p - backends; + } + + if(size) { + curlx_strcopy(buffer, size, backends, backends_len); + } + return 0; +} + +static int multissl_setup(const struct Curl_ssl *backend) +{ + int i; + char *env; + + if(Curl_ssl != &Curl_ssl_multi) + return 1; + + if(backend) { + Curl_ssl = backend; + return 0; + } + + if(!available_backends[0]) + return 1; + + env = curl_getenv("CURL_SSL_BACKEND"); + if(env) { + for(i = 0; available_backends[i]; i++) { + if(curl_strequal(env, available_backends[i]->info.name)) { + Curl_ssl = available_backends[i]; + curlx_free(env); + return 0; + } + } + } + +#ifdef CURL_DEFAULT_SSL_BACKEND + for(i = 0; available_backends[i]; i++) { + if(curl_strequal(CURL_DEFAULT_SSL_BACKEND, + available_backends[i]->info.name)) { + Curl_ssl = available_backends[i]; + curlx_free(env); + return 0; + } + } +#endif + + /* Fall back to first available backend */ + Curl_ssl = available_backends[0]; + curlx_free(env); + return 0; +} + +/* This function is used to select the SSL backend to use. It is called by + curl_global_sslset (easy.c) which uses the global init lock. */ +CURLsslset Curl_init_sslset_nolock(curl_sslbackend id, const char *name, + const curl_ssl_backend ***avail) +{ + int i; + + if(avail) + *avail = (const curl_ssl_backend **)&available_backends; + + if(Curl_ssl != &Curl_ssl_multi) + return id == Curl_ssl->info.id || + (name && curl_strequal(name, Curl_ssl->info.name)) ? + CURLSSLSET_OK : +#ifdef CURL_WITH_MULTI_SSL + CURLSSLSET_TOO_LATE; +#else + CURLSSLSET_UNKNOWN_BACKEND; +#endif + + for(i = 0; available_backends[i]; i++) { + if(available_backends[i]->info.id == id || + (name && curl_strequal(available_backends[i]->info.name, name))) { + multissl_setup(available_backends[i]); + return CURLSSLSET_OK; + } + } + + return CURLSSLSET_UNKNOWN_BACKEND; +} + +#else /* USE_SSL */ +CURLsslset Curl_init_sslset_nolock(curl_sslbackend id, const char *name, + const curl_ssl_backend ***avail) +{ + (void)id; + (void)name; + (void)avail; + return CURLSSLSET_NO_BACKENDS; +} + +#endif /* !USE_SSL */ + +#ifdef USE_SSL + +void Curl_ssl_peer_cleanup(struct ssl_peer *peer) +{ + Curl_peer_unlink(&peer->origin); + Curl_peer_unlink(&peer->peer); + curlx_safefree(peer->sni); + curlx_safefree(peer->scache_key); + peer->transport = TRNSPRT_NONE; + peer->type = CURL_SSL_PEER_DNS; +} + +static ssl_peer_type get_peer_type(const char *hostname) +{ + if(hostname && hostname[0]) { +#ifdef USE_IPV6 + struct in6_addr addr; +#else + struct in_addr addr; +#endif + if(curlx_inet_pton(AF_INET, hostname, &addr)) + return CURL_SSL_PEER_IPV4; +#ifdef USE_IPV6 + else if(curlx_inet_pton(AF_INET6, hostname, &addr)) { + return CURL_SSL_PEER_IPV6; + } +#endif + } + return CURL_SSL_PEER_DNS; +} + +CURLcode Curl_ssl_peer_init(struct ssl_peer *ssl_peer, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct ssl_primary_config *sslc, + const char *tls_id, + uint8_t transport) +{ + CURLcode result = CURLE_OUT_OF_MEMORY; + + /* We expect a clean struct, e.g. called only ONCE */ + if(!ssl_peer || !origin) { + DEBUGASSERT(0); + return CURLE_FAILED_INIT; + } + DEBUGASSERT(!ssl_peer->origin); + DEBUGASSERT(!ssl_peer->peer); + DEBUGASSERT(!ssl_peer->sni); + ssl_peer->transport = transport; + + Curl_peer_link(&ssl_peer->origin, origin); + Curl_peer_link(&ssl_peer->peer, peer); + ssl_peer->type = get_peer_type(origin->hostname); + if(ssl_peer->type == CURL_SSL_PEER_DNS) { + /* not an IP address, normalize according to RCC 6066 ch. 3, + * max len of SNI is 2^16-1, no trailing dot */ + size_t len = strlen(origin->hostname); + if(len && (origin->hostname[len - 1] == '.')) + len--; + if(len < USHRT_MAX) { + ssl_peer->sni = curlx_calloc(1, len + 1); + if(!ssl_peer->sni) + goto out; + Curl_strntolower(ssl_peer->sni, origin->hostname, len); + ssl_peer->sni[len] = 0; + } + } + + result = Curl_ssl_peer_key_make(ssl_peer, sslc, tls_id, + &ssl_peer->scache_key); + +out: + if(result) + Curl_ssl_peer_cleanup(ssl_peer); + return result; +} + +static void ssl_cf_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + if(connssl) { + connssl->ssl_impl->close(cf, data); + connssl->state = ssl_connection_none; + connssl->connecting_state = ssl_connect_1; + connssl->prefs_checked = FALSE; + Curl_ssl_peer_cleanup(&connssl->peer); + Curl_ssl_session_destroy(connssl->session); + cf_ctx_free(connssl); + cf->ctx = NULL; + } + cf->connected = FALSE; +} + +static CURLcode ssl_cf_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct cf_call_data save; + CURLcode result; + + if(cf->connected && (connssl->state != ssl_connection_deferred)) { + *done = TRUE; + return CURLE_OK; + } + + if(!cf->next || !connssl->peer.origin) { + *done = FALSE; + return CURLE_FAILED_INIT; + } + + if(!cf->next->connected) { + result = cf->next->cft->do_connect(cf->next, data, done); + if(result || !*done) + return result; + } + + CF_DATA_SAVE(save, cf, data); + CURL_TRC_CF(data, cf, "cf_connect()"); + DEBUGASSERT(connssl); + + *done = FALSE; + + if(!connssl->prefs_checked) { + if(!ssl_prefs_check(data)) { + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + connssl->prefs_checked = TRUE; + } + + result = connssl->ssl_impl->do_connect(cf, data, done); + + if(!result && *done) { + cf->connected = TRUE; + if(connssl->state == ssl_connection_complete) { + connssl->handshake_done = *Curl_pgrs_now(data); + } + if(Curl_tls_keylog_enabled()) { + infof(data, "SSLKEYLOGFILE set, all TLS secrets are logged to '%s'", + Curl_tls_keylog_file_name()); +#ifdef LIBRESSL_VERSION_NUMBER + infof(data, "Note LibreSSL only supports SSLKEYLOGFILE for TLS <= 1.2"); +#endif + } + /* Connection can be deferred when sending early data */ + DEBUGASSERT(connssl->state == ssl_connection_complete || + connssl->state == ssl_connection_deferred); + DEBUGASSERT(connssl->state != ssl_connection_deferred || + connssl->earlydata_state > ssl_earlydata_none); + } +out: + CURL_TRC_CF(data, cf, "cf_connect() -> %d, done=%d", (int)result, *done); + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode ssl_cf_set_earlydata(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *buf, size_t blen) +{ + struct ssl_connect_data *connssl = cf->ctx; + size_t nwritten = 0; + CURLcode result = CURLE_OK; + + DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_await); + DEBUGASSERT(Curl_bufq_is_empty(&connssl->earlydata)); + if(blen) { + if(blen > connssl->earlydata_max) + blen = connssl->earlydata_max; + result = Curl_bufq_write(&connssl->earlydata, buf, blen, &nwritten); + CURL_TRC_CF(data, cf, "ssl_cf_set_earlydata(len=%zu) -> %zu", + blen, nwritten); + if(result) + return result; + } + return CURLE_OK; +} + +static CURLcode ssl_cf_connect_deferred(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *buf, size_t blen, + bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + CURLcode result = CURLE_OK; + + DEBUGASSERT(connssl->state == ssl_connection_deferred); + *done = FALSE; + if(connssl->earlydata_state == ssl_earlydata_await) { + result = ssl_cf_set_earlydata(cf, data, buf, blen); + if(result) + return result; + /* we buffered any early data we would like to send. Actually + * do the connect now which sends it and performs the handshake. */ + connssl->earlydata_state = ssl_earlydata_sending; + connssl->earlydata_skip = Curl_bufq_len(&connssl->earlydata); + } + + result = ssl_cf_connect(cf, data, done); + + if(!result && *done) { + if(!connssl->stats_reported && (cf->cft == &Curl_cft_ssl)) { + Curl_pgrsTimeWas(data, TIMER_APPCONNECT, connssl->handshake_done); + connssl->stats_reported = TRUE; + } + switch(connssl->earlydata_state) { + case ssl_earlydata_none: + break; + case ssl_earlydata_accepted: + if(!Curl_ssl_cf_is_proxy(cf)) + Curl_pgrsEarlyData(data, (curl_off_t)connssl->earlydata_skip); + infof(data, "Server accepted %zu bytes of TLS early data.", + connssl->earlydata_skip); + break; + case ssl_earlydata_rejected: + if(!Curl_ssl_cf_is_proxy(cf)) + Curl_pgrsEarlyData(data, -(curl_off_t)connssl->earlydata_skip); + infof(data, "Server rejected TLS early data."); + connssl->earlydata_skip = 0; + break; + default: + /* This should not happen. Either we do not use early data or we + * should know if it was accepted or not. */ + DEBUGASSERT(NULL); + break; + } + } + return result; +} + +static bool ssl_cf_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct cf_call_data save; + bool pending; + + CF_DATA_SAVE(save, cf, data); + if(connssl->ssl_impl->data_pending && + connssl->ssl_impl->data_pending(cf, data)) + pending = TRUE; + else + pending = cf->next->cft->has_data_pending(cf->next, data); + CF_DATA_RESTORE(cf, save); + return pending; +} + +static CURLcode ssl_cf_send(struct Curl_cfilter *cf, + struct Curl_easy *data, + const uint8_t *buf, size_t blen, + bool eos, size_t *pnwritten) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct cf_call_data save; + CURLcode result = CURLE_OK; + + (void)eos; + *pnwritten = 0; + CF_DATA_SAVE(save, cf, data); + + if(connssl->state == ssl_connection_deferred) { + bool done = FALSE; + result = ssl_cf_connect_deferred(cf, data, buf, blen, &done); + if(result) + goto out; + else if(!done) { + result = CURLE_AGAIN; + goto out; + } + DEBUGASSERT(connssl->state == ssl_connection_complete); + } + + if(connssl->earlydata_skip) { + if(connssl->earlydata_skip >= blen) { + connssl->earlydata_skip -= blen; + result = CURLE_OK; + *pnwritten = blen; + goto out; + } + else { + *pnwritten = connssl->earlydata_skip; + buf = buf + connssl->earlydata_skip; + blen -= connssl->earlydata_skip; + connssl->earlydata_skip = 0; + } + } + + /* OpenSSL and maybe other TLS libs do not like 0-length writes. Skip. */ + if(blen > 0) { + size_t nwritten; + result = connssl->ssl_impl->send_plain(cf, data, buf, blen, &nwritten); + if(!result) + *pnwritten += nwritten; + } + +out: + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode ssl_cf_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, char *buf, size_t len, + size_t *pnread) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct cf_call_data save; + CURLcode result = CURLE_OK; + + CF_DATA_SAVE(save, cf, data); + *pnread = 0; + if(connssl->state == ssl_connection_deferred) { + bool done = FALSE; + result = ssl_cf_connect_deferred(cf, data, NULL, 0, &done); + if(result) + goto out; + else if(!done) { + result = CURLE_AGAIN; + goto out; + } + DEBUGASSERT(connssl->state == ssl_connection_complete); + } + + result = connssl->ssl_impl->recv_plain(cf, data, buf, len, pnread); + +out: + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode ssl_cf_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + CURLcode result = CURLE_OK; + + *done = TRUE; + /* If we have done the SSL handshake, shut down the connection cleanly */ + if(cf->connected && (connssl->state == ssl_connection_complete) && + !cf->shutdown && Curl_ssl->shut_down) { + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + result = connssl->ssl_impl->shut_down(cf, data, TRUE, done); + CURL_TRC_CF(data, cf, "cf_shutdown -> %d, done=%d", (int)result, *done); + CF_DATA_RESTORE(cf, save); + cf->shutdown = (result || *done); + } + return result; +} + +static CURLcode ssl_cf_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct cf_call_data save; + CURLcode result; + + CF_DATA_SAVE(save, cf, data); + result = connssl->ssl_impl->adjust_pollset(cf, data, ps); + CF_DATA_RESTORE(cf, save); + return result; +} + +static CURLcode ssl_cf_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2) +{ + struct ssl_connect_data *connssl = cf->ctx; + + switch(query) { + case CF_QUERY_SSL_INFO: + case CF_QUERY_SSL_CTX_INFO: + if(!Curl_ssl_cf_is_proxy(cf)) { + struct curl_tlssessioninfo *info = pres2; + struct cf_call_data save; + CF_DATA_SAVE(save, cf, data); + info->backend = Curl_ssl_backend(); + info->internals = connssl->ssl_impl->get_internals( + cf->ctx, (query == CF_QUERY_SSL_INFO) ? + CURLINFO_TLS_SSL_PTR : CURLINFO_TLS_SESSION); + CF_DATA_RESTORE(cf, save); + return CURLE_OK; + } + break; + case CF_QUERY_ALPN_NEGOTIATED: { + const char **palpn = pres2; + DEBUGASSERT(palpn); + *palpn = connssl->negotiated.alpn; + CURL_TRC_CF(data, cf, "query ALPN: returning '%s'", *palpn); + return CURLE_OK; + } + default: + break; + } + return cf->next ? + cf->next->cft->query(cf->next, data, query, pres1, pres2) : + CURLE_UNKNOWN_OPTION; +} + +static CURLcode ssl_cf_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2) +{ + struct ssl_connect_data *connssl = cf->ctx; + + (void)arg1; + (void)arg2; + (void)data; + switch(event) { + case CF_CTRL_CONN_INFO_UPDATE: + if(connssl->negotiated.alpn && !cf->sockindex) { + if(!strcmp("http/1.1", connssl->negotiated.alpn)) + cf->conn->httpversion_seen = 11; + else if(!strcmp("h2", connssl->negotiated.alpn)) + cf->conn->httpversion_seen = 20; + else if(!strcmp("h3", connssl->negotiated.alpn)) + cf->conn->httpversion_seen = 30; + } + break; + case CF_CTRL_REPORT_STATS: + if(cf->connected && !connssl->stats_reported && + (cf->cft == &Curl_cft_ssl) && + (connssl->handshake_done.tv_sec || connssl->handshake_done.tv_usec)) { + Curl_pgrsTimeWas(data, TIMER_APPCONNECT, connssl->handshake_done); + connssl->stats_reported = TRUE; + } + break; + } + return CURLE_OK; +} + +static bool cf_ssl_is_alive(struct Curl_cfilter *cf, struct Curl_easy *data, + bool *input_pending) +{ + /* + * This function tries to determine connection status. + */ + return cf->next ? + cf->next->cft->is_alive(cf->next, data, input_pending) : + FALSE; /* pessimistic in absence of data */ +} + +struct Curl_cftype Curl_cft_ssl = { + "SSL", + CF_TYPE_SSL, + CURL_LOG_LVL_NONE, + ssl_cf_destroy, + ssl_cf_connect, + ssl_cf_shutdown, + ssl_cf_adjust_pollset, + ssl_cf_data_pending, + ssl_cf_send, + ssl_cf_recv, + ssl_cf_cntrl, + cf_ssl_is_alive, + Curl_cf_def_conn_keep_alive, + ssl_cf_query, +}; + +#ifndef CURL_DISABLE_PROXY + +struct Curl_cftype Curl_cft_ssl_proxy = { + "SSL-PROXY", + CF_TYPE_SSL | CF_TYPE_PROXY, + CURL_LOG_LVL_NONE, + ssl_cf_destroy, + ssl_cf_connect, + ssl_cf_shutdown, + ssl_cf_adjust_pollset, + ssl_cf_data_pending, + ssl_cf_send, + ssl_cf_recv, + Curl_cf_def_cntrl, + cf_ssl_is_alive, + Curl_cf_def_conn_keep_alive, + ssl_cf_query, +}; + +#endif /* !CURL_DISABLE_PROXY */ + +static CURLcode cf_ssl_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn) +{ + struct Curl_cfilter *cf = NULL; + struct ssl_connect_data *ctx; + CURLcode result; + + DEBUGASSERT(data->conn); + +#ifdef CURL_DISABLE_HTTP + (void)conn; + /* We only support ALPN for HTTP so far. */ + DEBUGASSERT(!conn->bits.tls_enable_alpn); + ctx = cf_ctx_new(data, NULL); +#else + ctx = cf_ctx_new(data, alpn_get_spec(data->state.http_neg.wanted, + data->state.http_neg.preferred, + (bool)data->state.http_neg.only_10, + (bool)conn->bits.tls_enable_alpn)); +#endif + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + result = Curl_cf_create(&cf, &Curl_cft_ssl, ctx); + +out: + if(result) + cf_ctx_free(ctx); + *pcf = result ? NULL : cf; + return result; +} + +static CURLcode cf_ssl_peer_init(struct Curl_cfilter *cf, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct ssl_primary_config *sslc) +{ + struct ssl_connect_data *connssl = cf->ctx; + char tls_id[80]; + connssl->ssl_impl->version(tls_id, sizeof(tls_id) - 1); + return Curl_ssl_peer_init(&connssl->peer, origin, peer, sslc, + tls_id, TRNSPRT_TCP); +} + +CURLcode Curl_ssl_cfilter_add(struct Curl_easy *data, + struct Curl_peer *origin, + struct connectdata *conn, + int8_t sockindex) +{ + struct Curl_cfilter *cf; + struct Curl_peer *peer = (sockindex == SECONDARYSOCKET) ? + conn->via_peer2 : conn->via_peer; + CURLcode result; + + result = cf_ssl_create(&cf, data, conn); + if(!result) + result = cf_ssl_peer_init(cf, origin, peer, &conn->ssl_config); + if(!result) + Curl_conn_cf_add(data, conn, sockindex, cf); + else if(cf) + Curl_conn_cf_discard_chain(&cf, data); + return result; +} + +CURLcode Curl_cf_ssl_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer) +{ + struct Curl_cfilter *cf; + CURLcode result; + + result = cf_ssl_create(&cf, data, cf_at->conn); + if(!result) + result = cf_ssl_peer_init(cf, origin, peer, &cf_at->conn->ssl_config); + if(!result) { + Curl_conn_cf_insert_after(cf_at, cf); +#if defined(USE_HTTPSRR) && defined(USE_ECH) + /* When using ECH, kick off the HTTPS-RR resolve */ + if((origin->scheme->family == CURLPROTO_HTTP) && + CURLECH_ENABLED(data) && + Curl_ssl_supports(data, SSLSUPP_ECH) && + (data->set.tls_ech != CURLECH_GREASE) && + !CURL_EASY_STR(data, STRING_ECH_CONFIG)) { + result = Curl_conn_dns_add_https_resolve(data, cf->conn, cf->sockindex, + origin); + } +#endif /* USE_HTTPSRR && USE_ECH */ + } + else if(cf) + Curl_conn_cf_discard_chain(&cf, data); + return result; +} + +#ifndef CURL_DISABLE_PROXY + +static CURLcode cf_ssl_proxy_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn) +{ + struct Curl_cfilter *cf = NULL; + struct ssl_connect_data *ctx; + CURLcode result; + /* ALPN is default, but if user explicitly disables it, obey */ + bool use_alpn = (bool)data->set.ssl_enable_alpn; + http_majors wanted = CURL_HTTP_V1x; + + (void)conn; +#ifdef USE_HTTP2 + if(conn->http_proxy.proxytype == CURLPROXY_HTTPS2) { + use_alpn = TRUE; + wanted = (CURL_HTTP_V1x | CURL_HTTP_V2x); + } +#endif + + ctx = cf_ctx_new(data, alpn_get_spec(wanted, 0, FALSE, use_alpn)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + result = Curl_cf_create(&cf, &Curl_cft_ssl_proxy, ctx); + +out: + if(result) + cf_ctx_free(ctx); + *pcf = result ? NULL : cf; + return result; +} + +CURLcode Curl_cf_ssl_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *peer) +{ + struct Curl_cfilter *cf; + CURLcode result; + + result = cf_ssl_proxy_create(&cf, data, cf_at->conn); + if(!result) + result = cf_ssl_peer_init(cf, peer, NULL, &cf_at->conn->proxy_ssl_config); + if(!result) + Curl_conn_cf_insert_after(cf_at, cf); + else if(cf) + Curl_conn_cf_discard_chain(&cf, data); + return result; +} + +#endif /* !CURL_DISABLE_PROXY */ + +bool Curl_ssl_supports(struct Curl_easy *data, unsigned int ssl_option) +{ + (void)data; + return (Curl_ssl->supports & ssl_option); +} + +static CURLcode vtls_shutdown_blocking(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct cf_call_data save; + CURLcode result = CURLE_OK; + timediff_t timeout_ms; + int what, loop = 10; + + if(cf->shutdown) { + *done = TRUE; + return CURLE_OK; + } + CF_DATA_SAVE(save, cf, data); + + *done = FALSE; + while(!result && !*done && loop--) { + timeout_ms = Curl_shutdown_timeleft(data, cf->conn, cf->sockindex); + + if(timeout_ms < 0) { + /* no need to continue if time is already up */ + failf(data, "SSL shutdown timeout"); + result = CURLE_OPERATION_TIMEDOUT; + goto out; + } + + result = connssl->ssl_impl->shut_down(cf, data, send_shutdown, done); + if(result || *done) + goto out; + + if(connssl->io_need) { + what = Curl_conn_cf_poll(cf, data, timeout_ms); + if(what < 0) { + /* fatal error */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + result = CURLE_RECV_ERROR; + goto out; + } + else if(what == 0) { + /* timeout */ + failf(data, "SSL shutdown timeout"); + result = CURLE_OPERATION_TIMEDOUT; + goto out; + } + /* socket is readable or writable */ + } + } +out: + CF_DATA_RESTORE(cf, save); + cf->shutdown = (result || *done); + return result; +} + +CURLcode Curl_ssl_cfilter_remove(struct Curl_easy *data, + int8_t sockindex, bool send_shutdown) +{ + struct Curl_cfilter *cf, *head; + CURLcode result = CURLE_OK; + + head = data->conn ? data->conn->cfilter[sockindex] : NULL; + for(cf = head; cf; cf = cf->next) { + if(cf->cft == &Curl_cft_ssl) { + bool done; + CURL_TRC_CF(data, cf, "shutdown and remove SSL, start"); + Curl_shutdown_start(data, sockindex, 0); + result = vtls_shutdown_blocking(cf, data, send_shutdown, &done); + Curl_shutdown_clear(data, sockindex); + if(!result && !done) /* blocking failed? */ + result = CURLE_SSL_SHUTDOWN_FAILED; + Curl_conn_cf_discard(&cf, data); + CURL_TRC_CF(data, cf, "shutdown and remove SSL, done -> %d", + (int)result); + break; + } + } + return result; +} + +bool Curl_ssl_cf_is_proxy(struct Curl_cfilter *cf) +{ + return (cf->cft->flags & CF_TYPE_SSL) && (cf->cft->flags & CF_TYPE_PROXY); +} + +struct ssl_config_data *Curl_ssl_cf_get_config(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ +#ifdef CURL_DISABLE_PROXY + (void)cf; + return &data->set.ssl; +#else + return Curl_ssl_cf_is_proxy(cf) ? &data->set.proxy_ssl : &data->set.ssl; +#endif +} + +struct ssl_primary_config *Curl_ssl_cf_get_primary_config( + struct Curl_cfilter *cf) +{ +#ifdef CURL_DISABLE_PROXY + return &cf->conn->ssl_config; +#else + return Curl_ssl_cf_is_proxy(cf) ? + &cf->conn->proxy_ssl_config : &cf->conn->ssl_config; +#endif +} + +CURLcode Curl_alpn_to_proto_buf(struct alpn_proto_buf *buf, + const struct alpn_spec *spec) +{ + size_t i, len; + int off = 0; + unsigned char blen; + + memset(buf, 0, sizeof(*buf)); + for(i = 0; spec && i < spec->count; ++i) { + len = strlen(spec->entries[i]); + if(len >= ALPN_NAME_MAX) + return CURLE_FAILED_INIT; + blen = (unsigned char)len; + if(off + blen + 1 >= (int)sizeof(buf->data)) + return CURLE_FAILED_INIT; + buf->data[off++] = blen; + memcpy(buf->data + off, spec->entries[i], blen); + off += blen; + } + buf->len = off; + return CURLE_OK; +} + +CURLcode Curl_alpn_to_proto_str(struct alpn_proto_buf *buf, + const struct alpn_spec *spec) +{ + size_t i, len; + size_t off = 0; + + memset(buf, 0, sizeof(*buf)); + for(i = 0; spec && i < spec->count; ++i) { + len = strlen(spec->entries[i]); + if(len >= ALPN_NAME_MAX) + return CURLE_FAILED_INIT; + if(off + len + 2 >= sizeof(buf->data)) + return CURLE_FAILED_INIT; + if(off) + buf->data[off++] = ','; + memcpy(buf->data + off, spec->entries[i], len); + off += len; + } + buf->data[off] = '\0'; + buf->len = (int)off; + return CURLE_OK; +} + +bool Curl_alpn_contains_proto(const struct alpn_spec *spec, + const char *proto) +{ + size_t i, plen = proto ? strlen(proto) : 0; + for(i = 0; spec && plen && i < spec->count; ++i) { + size_t slen = strlen(spec->entries[i]); + if((slen == plen) && !memcmp(proto, spec->entries[i], plen)) + return TRUE; + } + return FALSE; +} + +void Curl_alpn_restrict_to(struct alpn_spec *spec, const char *proto) +{ + size_t plen = strlen(proto); + DEBUGASSERT(plen < sizeof(spec->entries[0])); + if(plen < sizeof(spec->entries[0])) { + memcpy(spec->entries[0], proto, plen + 1); + spec->count = 1; + } +} + +void Curl_alpn_copy(struct alpn_spec *dest, const struct alpn_spec *src) +{ + if(src) + memcpy(dest, src, sizeof(*dest)); + else + memset(dest, 0, sizeof(*dest)); +} + +CURLcode Curl_alpn_set_negotiated(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_connect_data *connssl, + const unsigned char *proto, + size_t proto_len) +{ + CURLcode result = CURLE_OK; + (void)cf; + + if(connssl->negotiated.alpn) { + /* When we ask for a specific ALPN protocol, we need the confirmation + * of it by the server, as we have installed protocol handler and + * connection filter chain for exactly this protocol. */ + if(!proto_len) { + failf(data, "ALPN: asked for '%s' from previous session, " + "but server did not confirm it. Refusing to continue.", + connssl->negotiated.alpn); + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + else if(!proto) { + DEBUGASSERT(0); /* with length, we need a pointer */ + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + else if((strlen(connssl->negotiated.alpn) != proto_len) || + memcmp(connssl->negotiated.alpn, proto, proto_len)) { + failf(data, "ALPN: asked for '%s' from previous session, but server " + "selected '%.*s'. Refusing to continue.", + connssl->negotiated.alpn, (int)proto_len, proto); + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + /* ALPN is exactly what we asked for, done. */ + infof(data, "ALPN: server confirmed to use '%s'", + connssl->negotiated.alpn); + goto out; + } + + if(proto && proto_len) { + if(memchr(proto, '\0', proto_len)) { + failf(data, "ALPN: server selected protocol contains NUL. " + "Refusing to continue."); + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + connssl->negotiated.alpn = curlx_memdup0((const char *)proto, proto_len); + if(!connssl->negotiated.alpn) + return CURLE_OUT_OF_MEMORY; + } + + if(proto && proto_len) { + if(connssl->state == ssl_connection_deferred) + infof(data, VTLS_INFOF_ALPN_DEFERRED, (int)proto_len, proto); + else + infof(data, VTLS_INFOF_ALPN_ACCEPTED, (int)proto_len, proto); + } + else { + if(connssl->state == ssl_connection_deferred) + infof(data, VTLS_INFOF_NO_ALPN_DEFERRED); + else + infof(data, VTLS_INFOF_NO_ALPN); + } + +out: + return result; +} + +CURLcode Curl_on_session_reuse(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct alpn_spec *alpns, + struct Curl_ssl_session *scs, + bool *do_early_data, bool early_data_allowed) +{ + struct ssl_connect_data *connssl = cf->ctx; + CURLcode result = CURLE_OK; + + *do_early_data = FALSE; + + if(!early_data_allowed) { + CURL_TRC_CF(data, cf, "SSL session does not allow earlydata"); + } + else if(!Curl_alpn_contains_proto(alpns, scs->alpn)) { + CURL_TRC_CF(data, cf, "SSL session has different ALPN, no early data"); + } + else { + infof(data, "SSL session allows %zu bytes of early data, " + "reusing ALPN '%s'", connssl->earlydata_max, scs->alpn); + connssl->earlydata_state = ssl_earlydata_await; + connssl->state = ssl_connection_deferred; + result = Curl_alpn_set_negotiated(cf, data, connssl, + (const unsigned char *)scs->alpn, + scs->alpn ? strlen(scs->alpn) : 0); + *do_early_data = !result; + } + return result; +} + +struct Curl_ssl_session *Curl_ssl_get_cf_session(struct Curl_easy *data, + const struct Curl_cftype *cft, + int8_t sockindex) +{ + if(data->conn && +#ifndef CURL_DISABLE_PROXY + ((cft == &Curl_cft_ssl) || (cft == &Curl_cft_ssl_proxy))) { +#else + (cft == &Curl_cft_ssl)) { +#endif + struct Curl_cfilter *cf1 = data->conn->cfilter[sockindex]; + for(; cf1; cf1 = cf1->next) { + /* A tunneling proxy does not offer end2end encryption, even if + * it does SSL itself (e.g. QUIC H3 proxy) */ + if(cf1->cft == cft) + break; + } + if(cf1) { + struct ssl_connect_data *connssl = cf1->ctx; + if(connssl) + return connssl->session; + } + } + return NULL; +} + +#endif /* USE_SSL */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls.h new file mode 100644 index 0000000000..8ee22c8d5a --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls.h @@ -0,0 +1,241 @@ +#ifndef HEADER_CURL_VTLS_H +#define HEADER_CURL_VTLS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct connectdata; +struct ssl_config_data; +struct ssl_primary_config; +struct Curl_cfilter; +struct Curl_easy; +struct dynbuf; + +#define SSLSUPP_CA_PATH (1 << 0) /* supports CAPATH */ +#define SSLSUPP_CERTINFO (1 << 1) /* supports CURLOPT_CERTINFO */ +#define SSLSUPP_PINNEDPUBKEY (1 << 2) /* supports CURLOPT_PINNEDPUBLICKEY */ +#define SSLSUPP_SSL_CTX (1 << 3) /* supports CURLOPT_SSL_CTX */ +#define SSLSUPP_HTTPS_PROXY (1 << 4) /* supports access via HTTPS proxies */ +#define SSLSUPP_TLS13_CIPHERSUITES (1 << 5) /* supports TLS 1.3 ciphersuites */ +#define SSLSUPP_CAINFO_BLOB (1 << 6) +#define SSLSUPP_ECH (1 << 7) +#define SSLSUPP_CA_CACHE (1 << 8) +#define SSLSUPP_CIPHER_LIST (1 << 9) /* supports TLS 1.0-1.2 ciphersuites */ +#define SSLSUPP_SIGNATURE_ALGORITHMS (1 << 10) /* supports TLS sigalgs */ +#define SSLSUPP_ISSUERCERT (1 << 11) /* supports CURLOPT_ISSUERCERT */ +#define SSLSUPP_SSL_EC_CURVES (1 << 12) /* supports CURLOPT_SSL_EC_CURVES */ +#define SSLSUPP_CRLFILE (1 << 13) /* supports CURLOPT_CRLFILE */ +#define SSLSUPP_ISSUERCERT_BLOB (1 << 14) /* CURLOPT_ISSUERCERT_BLOB */ + +#ifdef USE_ECH +/* CURLECH_ values for the tls_ech option */ +#define CURLECH_DISABLE 0 +#define CURLECH_GREASE 1 +#define CURLECH_ENABLE 2 +#define CURLECH_HARD 3 + +#define CURLECH_ENABLED(data) ((data)->set.tls_ech) +#endif /* USE_ECH */ + +#define ALPN_ACCEPTED "ALPN: server accepted " + +#define VTLS_INFOF_NO_ALPN \ + "ALPN: server did not agree on a protocol. Uses default." +#define VTLS_INFOF_ALPN_OFFER_1STR \ + "ALPN: curl offers %s" +#define VTLS_INFOF_ALPN_ACCEPTED \ + ALPN_ACCEPTED "%.*s" + +#define VTLS_INFOF_NO_ALPN_DEFERRED \ + "ALPN: deferred handshake for early data without specific protocol." +#define VTLS_INFOF_ALPN_DEFERRED \ + "ALPN: deferred handshake for early data using '%.*s'." + +/* IETF defined version numbers used in TLS protocol negotiation */ +#define CURL_IETF_PROTO_UNKNOWN 0x0 +#define CURL_IETF_PROTO_SSL3 0x0300 +#define CURL_IETF_PROTO_TLS1 0x0301 +#define CURL_IETF_PROTO_TLS1_1 0x0302 +#define CURL_IETF_PROTO_TLS1_2 0x0303 +#define CURL_IETF_PROTO_TLS1_3 0x0304 +#define CURL_IETF_PROTO_DTLS1 0xFEFF +#define CURL_IETF_PROTO_DTLS1_2 0xFEFD + +typedef enum { + CURL_SSL_PEER_DNS, + CURL_SSL_PEER_IPV4, + CURL_SSL_PEER_IPV6 +} ssl_peer_type; + +struct ssl_peer { + struct Curl_peer *origin; /* the authority we talk to */ + struct Curl_peer *peer; /* the machine we are connected to */ + char *sni; /* SNI version of hostname or NULL if not usable */ + char *scache_key; /* for lookups in session cache */ + ssl_peer_type type; /* type of the peer information */ + uint8_t transport; /* one of TRNSPRT_* defines */ +}; + +CURLsslset Curl_init_sslset_nolock(curl_sslbackend id, const char *name, + const curl_ssl_backend ***avail); + +#define MAX_PINNED_PUBKEY_SIZE (1024 * 1024) /* 1 MiB */ + +curl_sslbackend Curl_ssl_backend(void); + +/** + * Init SSL peer information for filter. Can be called repeatedly. + */ +CURLcode Curl_ssl_peer_init(struct ssl_peer *ssl_peer, + struct Curl_peer *origin, + struct Curl_peer *peer, + struct ssl_primary_config *sslc, + const char *tls_id, + uint8_t transport); +/** + * Free all allocated data and reset peer information. + */ +void Curl_ssl_peer_cleanup(struct ssl_peer *peer); + +#ifdef USE_SSL +int Curl_ssl_init(void); +void Curl_ssl_cleanup(void); +/* tell the SSL stuff to close down all open information regarding + connections (and thus session ID caching etc) */ +void Curl_ssl_close_all(struct Curl_easy *data); +CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine); +/* Sets engine as default for all SSL operations */ +CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data); +struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data); + +void Curl_ssl_version(char *buffer, size_t size); + +/* Certificate information list handling. */ +#define CURL_X509_STR_MAX 100000 +#define MAX_ALLOWED_CERT_AMOUNT 100 + +void Curl_ssl_free_certinfo(struct Curl_easy *data); +CURLcode Curl_ssl_init_certinfo(struct Curl_easy *data, int num); +CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data, int certnum, + const char *label, const char *value, + size_t valuelen); +CURLcode Curl_ssl_push_certinfo(struct Curl_easy *data, int certnum, + const char *label, const char *value); + +/* Functions to be used by SSL library adaptation functions */ + +/* get N random bytes into the buffer */ +CURLcode Curl_ssl_random(struct Curl_easy *data, + unsigned char *buffer, size_t length); +/* Check pinned public key. */ +CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data, + const char *pinnedpubkey, + const unsigned char *pubkey, size_t pubkeylen); + +bool Curl_ssl_cert_status_request(void); + +/* The maximum size of the SSL channel binding is 85 bytes, as defined in + * RFC 5929, Section 4.1. The 'tls-server-end-point:' prefix is 21 bytes, + * and SHA-512 is the longest supported hash algorithm, with a digest length of + * 64 bytes. + * The maximum size of the channel binding is therefore 21 + 64 = 85 bytes. + */ +#define SSL_CB_MAX_SIZE 85 + +/* Return the tls-server-end-point channel binding, including the + * 'tls-server-end-point:' prefix. + * If successful, the data is written to the dynbuf, and CURLE_OK is returned. + * The dynbuf MUST HAVE a minimum toobig size of SSL_CB_MAX_SIZE. + * If the dynbuf is too small, CURLE_OUT_OF_MEMORY is returned. + * If channel binding is not supported, binding stays empty and CURLE_OK is + * returned. + */ +CURLcode Curl_ssl_get_channel_binding(struct Curl_easy *data, int8_t sockindex, + struct dynbuf *binding); + +#define SSL_SHUTDOWN_TIMEOUT 10000 /* ms */ + +CURLcode Curl_ssl_cfilter_add(struct Curl_easy *data, + struct Curl_peer *origin, + struct connectdata *conn, + int8_t sockindex); + +CURLcode Curl_cf_ssl_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *origin, + struct Curl_peer *peer); + +CURLcode Curl_ssl_cfilter_remove(struct Curl_easy *data, + int8_t sockindex, bool send_shutdown); + +#ifndef CURL_DISABLE_PROXY +CURLcode Curl_cf_ssl_proxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + struct Curl_peer *peer); +#endif /* !CURL_DISABLE_PROXY */ + +/** + * True iff the underlying SSL implementation supports the option. + * Option is one of the defined SSLSUPP_* values. + * `data` maybe NULL for the features of the default implementation. + */ +bool Curl_ssl_supports(struct Curl_easy *data, unsigned int ssl_option); + +/** + * Get the ssl_config_data in `data` that is relevant for cfilter `cf`. + */ +struct ssl_config_data *Curl_ssl_cf_get_config(struct Curl_cfilter *cf, + struct Curl_easy *data); + +/** + * Get the primary config relevant for the filter from its connection. + */ +struct ssl_primary_config *Curl_ssl_cf_get_primary_config( + struct Curl_cfilter *cf); + +extern struct Curl_cftype Curl_cft_ssl; +#ifndef CURL_DISABLE_PROXY +extern struct Curl_cftype Curl_cft_ssl_proxy; +#endif + +#else /* if not USE_SSL */ + +/* When SSL support is not present, define away these function calls */ +#define Curl_ssl_init() 1 +#define Curl_ssl_cleanup() Curl_nop_stmt +#define Curl_ssl_close_all(x) Curl_nop_stmt +#define Curl_ssl_set_engine(x, y) CURLE_NOT_BUILT_IN +#define Curl_ssl_set_engine_default(x) CURLE_NOT_BUILT_IN +#define Curl_ssl_engines_list(x) NULL +#define Curl_ssl_free_certinfo(x) Curl_nop_stmt +#define Curl_ssl_random(x, y, z) ((void)(x), CURLE_NOT_BUILT_IN) +#define Curl_ssl_cert_status_request() FALSE +#define Curl_ssl_supports(a, b) FALSE +#define Curl_ssl_cfilter_add(a, b, c, d) CURLE_NOT_BUILT_IN +#define Curl_ssl_cfilter_remove(a, b, c) CURLE_OK +#define Curl_ssl_cf_get_config(a, b) NULL +#define Curl_ssl_cf_get_primary_config(a) NULL +#endif + +#endif /* HEADER_CURL_VTLS_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_config.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_config.c new file mode 100644 index 0000000000..080d513bb5 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_config.c @@ -0,0 +1,406 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* This file is for implementing all "generic" SSL functions that all libcurl + internals should use. It is then responsible for calling the proper + "backend" function. + + SSL-functions in libcurl should call functions in this source file, and not + to any specific SSL-layer. + + Curl_ssl_ - prefix for generic ones + + Note that this source code uses the functions of the configured SSL + backend via the global Curl_ssl instance. + + "SSL/TLS Strong Encryption: An Introduction" + https://httpd.apache.org/docs/2.0/ssl/ssl_intro.html + */ + +#include "curl_setup.h" + +#include "urldata.h" +#include "setopt.h" +#include "strcase.h" +#include "vtls/vtls.h" +#include "vtls/vtls_config.h" + + +#define CLONE_STRING(var) \ + do { \ + if(source->var) { \ + dest->var = curlx_strdup(source->var); \ + if(!dest->var) \ + return FALSE; \ + } \ + else \ + dest->var = NULL; \ + } while(0) + +#define CLONE_BLOB(var) \ + do { \ + if(blobdup(&dest->var, source->var)) \ + return FALSE; \ + } while(0) + +static CURLcode blobdup(struct curl_blob **dest, struct curl_blob *src) +{ + DEBUGASSERT(dest); + DEBUGASSERT(!*dest); + if(src) { + /* only if there is data to dupe! */ + struct curl_blob *d; + d = curlx_malloc(sizeof(struct curl_blob) + src->len); + if(!d) + return CURLE_OUT_OF_MEMORY; + d->len = src->len; + /* Always duplicate because the connection may survive longer than the + handle that passed in the blob. */ + d->flags = CURL_BLOB_COPY; + d->data = (void *)((char *)d + sizeof(struct curl_blob)); + memcpy(d->data, src->data, src->len); + *dest = d; + } + return CURLE_OK; +} + +/* returns TRUE if the blobs are identical */ +static bool blobcmp(struct curl_blob *first, struct curl_blob *second) +{ + if(!first && !second) /* both are NULL */ + return TRUE; + if(!first || !second) /* one is NULL */ + return FALSE; + if(first->len != second->len) /* different sizes */ + return FALSE; + return !memcmp(first->data, second->data, first->len); /* same data */ +} + +void Curl_ssl_config_init(struct ssl_primary_config *sslc) +{ + /* + * libcurl 7.10 introduced SSL verification *by default*! This needs to be + * switched off unless wanted. + */ + sslc->verifypeer = TRUE; + sslc->verifyhost = TRUE; + sslc->cache_session = TRUE; /* caching by default */ +} + +void Curl_ssl_config_cleanup(struct ssl_primary_config *sslc) +{ + if(sslc->deep_copy) { + curlx_safefree(sslc->CApath); + curlx_safefree(sslc->CAfile); + curlx_safefree(sslc->issuercert); + curlx_safefree(sslc->clientcert); + curlx_safefree(sslc->cipher_list); + curlx_safefree(sslc->cipher_list13); + curlx_safefree(sslc->pinned_key); + curlx_safefree(sslc->cert_blob); + curlx_safefree(sslc->ca_info_blob); + curlx_safefree(sslc->issuercert_blob); + curlx_safefree(sslc->key_blob); + curlx_safefree(sslc->curves); + curlx_safefree(sslc->signature_algorithms); + curlx_safefree(sslc->CRLfile); + curlx_safefree(sslc->cert_type); + curlx_safefree(sslc->key); + curlx_safefree(sslc->key_type); + curlx_safefree(sslc->key_passwd); + sslc->deep_copy = FALSE; + } +} + +static bool match_ssl_primary_config(struct Curl_easy *data, + struct ssl_primary_config *c1, + struct ssl_primary_config *c2) +{ + (void)data; + if((c1->version == c2->version) && + (c1->version_max == c2->version_max) && + (c1->ssl_options == c2->ssl_options) && + (c1->native_ca_store == c2->native_ca_store) && + (c1->verifypeer == c2->verifypeer) && + (c1->verifyhost == c2->verifyhost) && + (c1->verifystatus == c2->verifystatus) && + blobcmp(c1->cert_blob, c2->cert_blob) && + blobcmp(c1->ca_info_blob, c2->ca_info_blob) && + blobcmp(c1->issuercert_blob, c2->issuercert_blob) && + blobcmp(c1->key_blob, c2->key_blob) && + Curl_safecmp(c1->CApath, c2->CApath) && + Curl_safecmp(c1->CAfile, c2->CAfile) && + Curl_safecmp(c1->issuercert, c2->issuercert) && + Curl_safecmp(c1->clientcert, c2->clientcert) && + curl_strequal(c1->cipher_list, c2->cipher_list) && + curl_strequal(c1->cipher_list13, c2->cipher_list13) && + curl_strequal(c1->curves, c2->curves) && + curl_strequal(c1->signature_algorithms, c2->signature_algorithms) && + Curl_safecmp(c1->CRLfile, c2->CRLfile) && + Curl_safecmp(c1->pinned_key, c2->pinned_key) && + curl_strequal(c1->cert_type, c2->cert_type) && + Curl_safecmp(c1->key, c2->key) && + curl_strequal(c1->key_type, c2->key_type) && + !Curl_timestrcmp(c1->key_passwd, c2->key_passwd)) + return TRUE; + + return FALSE; +} + +bool Curl_ssl_conn_config_match(struct Curl_easy *data, + struct connectdata *candidate, + bool proxy) +{ +#ifndef CURL_DISABLE_PROXY + if(proxy) + return match_ssl_primary_config(data, &data->set.proxy_ssl.primary, + &candidate->proxy_ssl_config); +#else + (void)proxy; +#endif + return match_ssl_primary_config(data, &data->set.ssl.primary, + &candidate->ssl_config); +} + +static bool clone_ssl_primary_config(struct ssl_primary_config *source, + struct ssl_primary_config *dest) +{ + DEBUGASSERT(!dest->deep_copy); + dest->deep_copy = TRUE; + dest->version = source->version; + dest->version_max = source->version_max; + dest->verifypeer = source->verifypeer; + dest->verifyhost = source->verifyhost; + dest->verifystatus = source->verifystatus; + dest->native_ca_store = source->native_ca_store; + dest->cache_session = source->cache_session; + dest->ssl_options = source->ssl_options; + + CLONE_BLOB(cert_blob); + CLONE_BLOB(ca_info_blob); + CLONE_BLOB(issuercert_blob); + CLONE_STRING(CApath); + CLONE_STRING(CAfile); + CLONE_STRING(issuercert); + CLONE_STRING(cipher_list); + CLONE_STRING(cipher_list13); + CLONE_STRING(pinned_key); + CLONE_STRING(curves); + CLONE_STRING(signature_algorithms); + CLONE_STRING(CRLfile); + /* SSL credentials: client certificate */ + CLONE_STRING(clientcert); + CLONE_STRING(cert_type); + CLONE_STRING(key); + CLONE_STRING(key_type); + CLONE_STRING(key_passwd); + CLONE_BLOB(key_blob); + return TRUE; +} + +static void ssl_easy_config_compl_options(struct Curl_peer *origin, + struct Curl_peer *initial_origin, + struct ssl_config_data *sslc) +{ + uint8_t options = sslc->primary.ssl_options; + /* If set via CURLOPT_(PROXY_)SSL_OPTIONS, we definitely use it. + * If not, we switch it on for supported backends if no custom + * CA settings exist. */ + sslc->primary.native_ca_store = !!(options & CURLSSLOPT_NATIVE_CA); + sslc->enable_beast = !!(options & CURLSSLOPT_ALLOW_BEAST); + sslc->no_partialchain = !!(options & CURLSSLOPT_NO_PARTIALCHAIN); + sslc->no_revoke = !!(options & CURLSSLOPT_NO_REVOKE); + sslc->revoke_best_effort = !!(options & CURLSSLOPT_REVOKE_BEST_EFFORT); + sslc->earlydata = !!(options & CURLSSLOPT_EARLYDATA); + + sslc->auto_client_cert = Curl_peer_equal(origin, initial_origin) && + !!(options & CURLSSLOPT_AUTO_CLIENT_CERT); +} + +static char *ssl_easy_steal(struct Curl_easy *data, enum dupstring id) +{ + /* For connection matching, we borrow string references from data + * THIS IS NOT REALLY NICE. */ + return CURL_UNCONST(CURL_EASY_STR(data, id)); +} + +CURLcode Curl_ssl_easy_config_complete(struct Curl_easy *data, + struct Curl_peer *origin) +{ + struct ssl_config_data *sslc = &data->set.ssl; +#if defined(CURL_CA_PATH) || defined(CURL_CA_BUNDLE) + CURLcode result; +#endif + + ssl_easy_config_compl_options(origin, data->state.initial_origin, sslc); + + if(Curl_ssl_backend() != CURLSSLBACKEND_SCHANNEL) { +#if defined(USE_APPLE_SECTRUST) || defined(CURL_CA_NATIVE) + if(!sslc->custom_capath && !sslc->custom_cafile && !sslc->custom_cablob) + sslc->primary.native_ca_store = TRUE; +#endif +#ifdef CURL_CA_PATH + if(!sslc->custom_capath && !CURL_EASY_STR(data, STRING_SSL_CAPATH)) { + result = Curl_setstropt(data, STRING_SSL_CAPATH, CURL_CA_PATH); + if(result) + return result; + } +#endif +#ifdef CURL_CA_BUNDLE + if(!sslc->custom_cafile && !CURL_EASY_STR(data, STRING_SSL_CAFILE)) { + result = Curl_setstropt(data, STRING_SSL_CAFILE, CURL_CA_BUNDLE); + if(result) + return result; + } +#endif + } + sslc->primary.CAfile = ssl_easy_steal(data, STRING_SSL_CAFILE); + sslc->primary.CRLfile = ssl_easy_steal(data, STRING_SSL_CRLFILE); + sslc->primary.CApath = ssl_easy_steal(data, STRING_SSL_CAPATH); + sslc->primary.cipher_list = ssl_easy_steal(data, STRING_SSL_CIPHER_LIST); + sslc->primary.cipher_list13 = ssl_easy_steal(data, STRING_SSL_CIPHER13_LIST); + sslc->primary.signature_algorithms = + ssl_easy_steal(data, STRING_SSL_SIGNATURE_ALGORITHMS); + sslc->primary.ca_info_blob = data->set.blobs[BLOB_CAINFO]; + sslc->primary.curves = ssl_easy_steal(data, STRING_SSL_EC_CURVES); + /* Maybe these should not be used for another origin. But for + * backwards compatibility, keep them in. */ + sslc->primary.issuercert = ssl_easy_steal(data, STRING_SSL_ISSUERCERT); + sslc->primary.issuercert_blob = data->set.blobs[BLOB_SSL_ISSUERCERT]; + + if(Curl_peer_equal(data->state.initial_origin, origin)) { + sslc->primary.pinned_key = + ssl_easy_steal(data, STRING_SSL_PINNEDPUBLICKEY); + sslc->primary.cert_blob = data->set.blobs[BLOB_CERT]; + sslc->primary.cert_type = ssl_easy_steal(data, STRING_CERT_TYPE); + sslc->primary.key = ssl_easy_steal(data, STRING_KEY); + sslc->primary.key_type = ssl_easy_steal(data, STRING_KEY_TYPE); + sslc->primary.key_passwd = ssl_easy_steal(data, STRING_KEY_PASSWD); + sslc->primary.clientcert = ssl_easy_steal(data, STRING_CERT); + sslc->primary.key_blob = data->set.blobs[BLOB_KEY]; + } + else { + sslc->primary.pinned_key = NULL; + sslc->primary.cert_blob = NULL; + sslc->primary.cert_type = NULL; + sslc->primary.key = NULL; + sslc->primary.key_type = NULL; + sslc->primary.key_passwd = NULL; + sslc->primary.clientcert = NULL; + sslc->primary.key_blob = NULL; + } + +#ifndef CURL_DISABLE_PROXY + sslc = &data->set.proxy_ssl; + /* no initial origin for proxy, it is not changed for redirects */ + ssl_easy_config_compl_options(NULL, NULL, sslc); + + if(Curl_ssl_backend() != CURLSSLBACKEND_SCHANNEL) { +#if defined(USE_APPLE_SECTRUST) || defined(CURL_CA_NATIVE) + if(!sslc->custom_capath && !sslc->custom_cafile && !sslc->custom_cablob) + sslc->primary.native_ca_store = TRUE; +#endif +#ifdef CURL_CA_PATH + if(!sslc->custom_capath && + !CURL_EASY_STR(data, STRING_SSL_CAPATH_PROXY)) { + result = Curl_setstropt(data, STRING_SSL_CAPATH_PROXY, CURL_CA_PATH); + if(result) + return result; + } +#endif +#ifdef CURL_CA_BUNDLE + if(!sslc->custom_cafile && + !CURL_EASY_STR(data, STRING_SSL_CAFILE_PROXY)) { + result = Curl_setstropt(data, STRING_SSL_CAFILE_PROXY, CURL_CA_BUNDLE); + if(result) + return result; + } +#endif + } + sslc->primary.CAfile = ssl_easy_steal(data, STRING_SSL_CAFILE_PROXY); + sslc->primary.CApath = ssl_easy_steal(data, STRING_SSL_CAPATH_PROXY); + sslc->primary.cipher_list = + ssl_easy_steal(data, STRING_SSL_CIPHER_LIST_PROXY); + sslc->primary.cipher_list13 = + ssl_easy_steal(data, STRING_SSL_CIPHER13_LIST_PROXY); + sslc->primary.pinned_key = + ssl_easy_steal(data, STRING_SSL_PINNEDPUBLICKEY_PROXY); + sslc->primary.cert_blob = data->set.blobs[BLOB_CERT_PROXY]; + sslc->primary.ca_info_blob = data->set.blobs[BLOB_CAINFO_PROXY]; + sslc->primary.issuercert = ssl_easy_steal(data, STRING_SSL_ISSUERCERT_PROXY); + sslc->primary.issuercert_blob = data->set.blobs[BLOB_SSL_ISSUERCERT_PROXY]; + sslc->primary.CRLfile = ssl_easy_steal(data, STRING_SSL_CRLFILE_PROXY); + sslc->primary.cert_type = ssl_easy_steal(data, STRING_CERT_TYPE_PROXY); + sslc->primary.key = ssl_easy_steal(data, STRING_KEY_PROXY); + sslc->primary.key_type = ssl_easy_steal(data, STRING_KEY_TYPE_PROXY); + sslc->primary.key_passwd = ssl_easy_steal(data, STRING_KEY_PASSWD_PROXY); + sslc->primary.clientcert = ssl_easy_steal(data, STRING_CERT_PROXY); + sslc->primary.key_blob = data->set.blobs[BLOB_KEY_PROXY]; +#endif /* CURL_DISABLE_PROXY */ + + return CURLE_OK; +} + +CURLcode Curl_ssl_conn_config_init(struct Curl_easy *data, + struct connectdata *conn) +{ + /* Clone "primary" SSL configurations from the easy handle to + * the connection. They are used for connection cache matching and + * probably outlive the easy handle */ + if(!clone_ssl_primary_config(&data->set.ssl.primary, &conn->ssl_config)) + return CURLE_OUT_OF_MEMORY; +#ifndef CURL_DISABLE_PROXY + if(!clone_ssl_primary_config(&data->set.proxy_ssl.primary, + &conn->proxy_ssl_config)) + return CURLE_OUT_OF_MEMORY; +#endif + return CURLE_OK; +} + +void Curl_ssl_conn_config_cleanup(struct connectdata *conn) +{ + Curl_ssl_config_cleanup(&conn->ssl_config); +#ifndef CURL_DISABLE_PROXY + Curl_ssl_config_cleanup(&conn->proxy_ssl_config); +#endif +} + +void Curl_ssl_conn_config_update(struct Curl_easy *data, bool for_proxy) +{ + /* May be called on an easy that has no connection yet */ + if(data->conn) { + struct ssl_primary_config *src, *dest; +#ifndef CURL_DISABLE_PROXY + src = for_proxy ? &data->set.proxy_ssl.primary : &data->set.ssl.primary; + dest = for_proxy ? &data->conn->proxy_ssl_config : &data->conn->ssl_config; +#else + (void)for_proxy; + src = &data->set.ssl.primary; + dest = &data->conn->ssl_config; +#endif + dest->verifyhost = src->verifyhost; + dest->verifypeer = src->verifypeer; + dest->verifystatus = src->verifystatus; + } +} diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_config.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_config.h new file mode 100644 index 0000000000..8296604259 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_config.h @@ -0,0 +1,121 @@ +#ifndef HEADER_CURL_VTLS_CONFIG_H +#define HEADER_CURL_VTLS_CONFIG_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct Curl_easy; +struct connectdata; +struct Curl_peer; + +struct ssl_primary_config { + char *CApath; /* certificate directory (does not work on Windows) */ + char *CAfile; /* certificate to verify peer against */ + char *issuercert; /* optional issuer certificate filename */ + char *clientcert; + char *cipher_list; /* list of ciphers to use */ + char *cipher_list13; /* list of TLS 1.3 cipher suites to use */ + char *signature_algorithms; /* list of signature algorithms to use */ + char *pinned_key; + char *CRLfile; /* CRL to check certificate revocation */ + char *cert_type; /* format for certificate (default: PEM) */ + char *key; /* private key filename */ + char *key_type; /* format for private key (default: PEM) */ + char *key_passwd; /* plain text private key password */ + struct curl_blob *cert_blob; + struct curl_blob *ca_info_blob; + struct curl_blob *issuercert_blob; + struct curl_blob *key_blob; + char *curves; /* list of curves to use */ + uint32_t version_max; /* max supported version the client wants to use */ + uint8_t ssl_options; /* the CURLOPT_SSL_OPTIONS bitmask */ + uint8_t version; /* what version the client wants to use */ + BIT(verifypeer); /* set TRUE if this is desired */ + BIT(verifyhost); /* set TRUE if CN/SAN must match hostname */ + BIT(verifystatus); /* set TRUE if certificate status must be checked */ + BIT(native_ca_store); /* use the native CA store of operating system */ + BIT(cache_session); /* cache session or not */ + BIT(deep_copy); /* members are deep copies, eg. owned here */ +}; + +struct ssl_config_data { + struct ssl_primary_config primary; + long certverifyresult; /* result from the certificate verification */ + curl_ssl_ctx_callback fsslctx; /* function to initialize SSL ctx */ + void *fsslctxp; /* parameter for call back */ + BIT(certinfo); /* gather lots of certificate info */ + BIT(earlydata); /* use TLS 1.3 early data */ + BIT(enable_beast); /* allow this flaw for interoperability's sake */ + BIT(no_revoke); /* disable SSL certificate revocation checks */ + BIT(no_partialchain); /* do not accept partial certificate chains */ + BIT(revoke_best_effort); /* ignore SSL revocation offline/missing revocation + list errors */ + BIT(auto_client_cert); /* automatically locate and use a client + certificate for authentication (Schannel) */ + BIT(custom_cafile); /* application has set custom CA file */ + BIT(custom_capath); /* application has set custom CA path */ + BIT(custom_cablob); /* application has set custom CA blob */ +}; + +struct ssl_general_config { + int ca_cache_timeout; /* Certificate store cache timeout (seconds) */ +}; + +void Curl_ssl_config_init(struct ssl_primary_config *sslc); +void Curl_ssl_config_cleanup(struct ssl_primary_config *sslc); + +/** + * Init the `data->set.ssl` and `data->set.proxy_ssl` for + * connection matching use. + */ +CURLcode Curl_ssl_easy_config_complete(struct Curl_easy *data, + struct Curl_peer *origin); + +/** + * Init SSL configs (main + proxy) for a new connection from the easy handle. + */ +CURLcode Curl_ssl_conn_config_init(struct Curl_easy *data, + struct connectdata *conn); + +/** + * Free allocated resources in SSL configs (main + proxy) for + * the given connection. + */ +void Curl_ssl_conn_config_cleanup(struct connectdata *conn); + +/** + * Return TRUE iff SSL configuration from `data` is functionally the + * same as the one on `candidate`. + * @param proxy match the proxy SSL config or the main one + */ +bool Curl_ssl_conn_config_match(struct Curl_easy *data, + struct connectdata *candidate, + bool proxy); + +/* Update certain connection SSL config flags after they have + * been changed on the easy handle. Works for `verifypeer`, + * `verifyhost` and `verifystatus`. */ +void Curl_ssl_conn_config_update(struct Curl_easy *data, bool for_proxy); + +#endif /* HEADER_CURL_VTLS_CONFIG_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_int.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_int.h new file mode 100644 index 0000000000..7c1881b8d8 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_int.h @@ -0,0 +1,223 @@ +#ifndef HEADER_CURL_VTLS_INT_H +#define HEADER_CURL_VTLS_INT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_SSL + +#include "cfilters.h" +#include "select.h" +#include "urldata.h" +#include "vtls/vtls.h" + +struct Curl_ssl; +struct ssl_connect_data; +struct Curl_ssl_session; + +/* see https://www.iana.org/assignments/tls-extensiontype-values/ */ +#define ALPN_HTTP_1_0_LENGTH 8 +#define ALPN_HTTP_1_0 "http/1.0" +#define ALPN_HTTP_1_1_LENGTH 8 +#define ALPN_HTTP_1_1 "http/1.1" +#define ALPN_H2_LENGTH 2 +#define ALPN_H2 "h2" +#define ALPN_H3_LENGTH 2 +#define ALPN_H3 "h3" + +/* conservative sizes on the ALPN entries and count we are handling, + * we can increase these if we ever feel the need or have to accommodate + * ALPN strings from the "outside". */ +#define ALPN_NAME_MAX 10 +#define ALPN_ENTRIES_MAX 3 +#define ALPN_PROTO_BUF_MAX (ALPN_ENTRIES_MAX * (ALPN_NAME_MAX + 1)) + +struct alpn_spec { + char entries[ALPN_ENTRIES_MAX][ALPN_NAME_MAX]; + size_t count; /* number of entries */ +}; + +struct alpn_proto_buf { + unsigned char data[ALPN_PROTO_BUF_MAX]; + int len; +}; + +CURLcode Curl_alpn_to_proto_buf(struct alpn_proto_buf *buf, + const struct alpn_spec *spec); +CURLcode Curl_alpn_to_proto_str(struct alpn_proto_buf *buf, + const struct alpn_spec *spec); +void Curl_alpn_restrict_to(struct alpn_spec *spec, const char *proto); +void Curl_alpn_copy(struct alpn_spec *dest, const struct alpn_spec *src); + +CURLcode Curl_alpn_set_negotiated(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_connect_data *connssl, + const unsigned char *proto, + size_t proto_len); + +bool Curl_alpn_contains_proto(const struct alpn_spec *spec, const char *proto); + +/* enum for the nonblocking SSL connection state machine */ +typedef enum { + ssl_connect_1, + ssl_connect_2, + ssl_connect_3, + ssl_connect_done +} ssl_connect_state; + +typedef enum { + ssl_connection_none, + ssl_connection_deferred, + ssl_connection_negotiating, + ssl_connection_complete +} ssl_connection_state; + +typedef enum { + ssl_earlydata_none, + ssl_earlydata_await, + ssl_earlydata_sending, + ssl_earlydata_sent, + ssl_earlydata_accepted, + ssl_earlydata_rejected +} ssl_earlydata_state; + +#define CURL_SSL_IO_NEED_NONE 0 +#define CURL_SSL_IO_NEED_RECV (1 << 0) +#define CURL_SSL_IO_NEED_SEND (1 << 1) + +/* Max earlydata payload we want to send */ +#define CURL_SSL_EARLY_MAX (64 * 1024) + +/* Information in each SSL cfilter context: cf->ctx */ +struct ssl_connect_data { + const struct Curl_ssl *ssl_impl; /* TLS backend for this filter */ + struct ssl_peer peer; /* peer the filter talks to */ + const struct alpn_spec *alpn; /* ALPN to use or NULL for none */ + void *backend; /* vtls backend specific props */ + struct cf_call_data call_data; /* data handle used in current call */ + struct Curl_ssl_session *session; /* TLS session in use or NULL */ + struct curltime handshake_done; /* time when handshake finished */ + struct { + char *alpn; /* ALPN value or NULL */ + } negotiated; + struct bufq earlydata; /* earlydata to be send to peer */ + size_t earlydata_max; /* max earlydata allowed by peer */ + size_t earlydata_skip; /* sending bytes to skip when earlydata + * is accepted by peer */ + ssl_connection_state state; + ssl_connect_state connecting_state; + ssl_earlydata_state earlydata_state; + int io_need; /* TLS signals special SEND/RECV needs */ + BIT(peer_closed); /* peer has closed connection */ + BIT(prefs_checked); /* SSL preferences have been checked */ + BIT(input_pending); /* data for SSL_read() may be available */ + BIT(stats_reported); /* connect times have been reported */ +}; + +/* Definitions for SSL Implementations */ + +struct Curl_ssl { + /* + * This *must* be the first entry to allow returning the list of available + * backends in curl_global_sslset(). + */ + curl_ssl_backend info; + unsigned int supports; /* bitfield, see above */ + size_t sizeof_ssl_backend_data; + + int (*init)(void); + void (*cleanup)(void); + + size_t (*version)(char *buffer, size_t size); + CURLcode (*shut_down)(struct Curl_cfilter *cf, struct Curl_easy *data, + bool send_shutdown, bool *done); + + /* data_pending() shall return TRUE when it wants to get called again to + drain internal buffers and deliver data instead of waiting for the socket + to get readable */ + bool (*data_pending)(struct Curl_cfilter *cf, const struct Curl_easy *data); + + /* return 0 if a find random is filled in */ + CURLcode (*random)(struct Curl_easy *data, unsigned char *entropy, + size_t length); + bool (*cert_status_request)(void); + + CURLcode (*do_connect)(struct Curl_cfilter *cf, struct Curl_easy *data, + bool *done); + + /* During handshake/shutdown, adjust the pollset to include the socket + * for POLLOUT or POLLIN as needed. Mandatory. */ + CURLcode (*adjust_pollset)(struct Curl_cfilter *cf, struct Curl_easy *data, + struct easy_pollset *ps); + void *(*get_internals)(struct ssl_connect_data *connssl, CURLINFO info); + void (*close)(struct Curl_cfilter *cf, struct Curl_easy *data); + void (*close_all)(struct Curl_easy *data); + + CURLcode (*set_engine)(struct Curl_easy *data, const char *engine); + CURLcode (*set_engine_default)(struct Curl_easy *data); + struct curl_slist *(*engines_list)(struct Curl_easy *data); + + CURLcode (*sha256sum)(const unsigned char *input, size_t inputlen, + unsigned char *sha256sum, size_t sha256sumlen); + CURLcode (*recv_plain)(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, size_t *pnread); + CURLcode (*send_plain)(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *mem, size_t len, size_t *pnwritten); + + CURLcode (*get_channel_binding)(struct Curl_easy *data, int8_t sockindex, + struct dynbuf *binding); +}; + +extern const struct Curl_ssl *Curl_ssl; + +CURLcode Curl_ssl_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps); + +/** + * Get the SSL filter below the given one or NULL if there is none. + */ +bool Curl_ssl_cf_is_proxy(struct Curl_cfilter *cf); + +CURLcode Curl_on_session_reuse(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct alpn_spec *alpns, + struct Curl_ssl_session *scs, + bool *do_early_data, bool early_data_allowed); + +/* Retrieve the SSL session held at the filter of type `cft` at + * data's connection at `sockindex` or NULL if not found/available. */ +struct Curl_ssl_session *Curl_ssl_get_cf_session(struct Curl_easy *data, + const struct Curl_cftype *cft, + int8_t sockindex); + +#endif /* USE_SSL */ + +#endif /* HEADER_CURL_VTLS_INT_H */ + +#ifdef USE_SSL +/* Restore the default SSL filter call_data accessor for unity builds. */ +#undef CF_CTX_CALL_DATA +#define CF_CTX_CALL_DATA(cf) ((struct ssl_connect_data *)(cf)->ctx)->call_data +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_scache.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_scache.c new file mode 100644 index 0000000000..c703302be8 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_scache.c @@ -0,0 +1,1359 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_SSL + +#include "urldata.h" +#include "cfilters.h" + +#include "vtls/vtls.h" /* generic SSL protos etc */ +#include "vtls/vtls_int.h" +#include "vtls/vtls_scache.h" +#include "vtls/vtls_spack.h" + +#include "strcase.h" +#include "url.h" +#include "llist.h" +#include "curl_share.h" +#include "curl_threads.h" +#include "curl_trc.h" +#include "curl_sha256.h" +#include "rand.h" +#include "curlx/strdup.h" + +/* a peer+tls-config we cache sessions for */ +struct Curl_ssl_scache_peer { + char *ssl_peer_key; /* id for peer + relevant TLS configuration */ + char *clientcert; + char *key_passwd; + struct Curl_llist sessions; + void *sobj; /* object instance or NULL */ + Curl_ssl_scache_obj_dtor *sobj_free; /* free `sobj` callback */ + unsigned char key_salt[CURL_SHA256_DIGEST_LENGTH]; /* for entry export */ + unsigned char key_hmac[CURL_SHA256_DIGEST_LENGTH]; /* for entry export */ + size_t max_sessions; + long age; /* a number, the higher the more recent */ + BIT(hmac_set); /* if key_salt and key_hmac are present */ + BIT(exportable); /* sessions for this peer can be exported */ +}; + +#define CURL_SCACHE_MAGIC 0x000e1551 + +#define GOOD_SCACHE(x) ((x) && (x)->magic == CURL_SCACHE_MAGIC) + +static CURLcode cf_ssl_peer_key_add_path(struct dynbuf *buf, + const char *name, + const char *path, + bool *is_local) +{ + if(path && path[0]) { + /* We try to add absolute paths, so that the session key can stay valid + * when used in another process with different CWD. When a path does not + * exist, this does not work. Then, we add the path as is. */ +#ifdef _WIN32 + char *abspath = _fullpath(NULL, path, 0); + if(abspath) { + CURLcode result = curlx_dyn_addf(buf, ":%s-%s", name, abspath); + /* !checksrc! disable BANNEDFUNC 1 */ + free(abspath); /* allocated by CRT, use system free() */ + return result; + } + *is_local = TRUE; +#elif defined(HAVE_REALPATH) + if(path[0] != '/') { + char *abspath = realpath(path, NULL); + if(abspath) { + CURLcode result = curlx_dyn_addf(buf, ":%s-%s", name, abspath); + /* !checksrc! disable BANNEDFUNC 1 */ + free(abspath); /* allocated by libc, free without memdebug */ + return result; + } + *is_local = TRUE; + } +#endif + return curlx_dyn_addf(buf, ":%s-%s", name, path); + } + return CURLE_OK; +} + +static CURLcode cf_ssl_peer_key_add_hash(struct dynbuf *buf, + const char *name, + struct curl_blob *blob) +{ + CURLcode result = CURLE_OK; + if(blob && blob->len) { + unsigned char hash[CURL_SHA256_DIGEST_LENGTH]; + size_t i; + + result = curlx_dyn_addf(buf, ":%s-", name); + if(result) + goto out; + result = Curl_sha256it(hash, blob->data, blob->len); + if(result) + goto out; + for(i = 0; i < CURL_SHA256_DIGEST_LENGTH; ++i) { + result = curlx_dyn_addf(buf, "%02x", hash[i]); + if(result) + goto out; + } + } +out: + return result; +} + +static CURLcode cf_ssl_peer_key_add_mtls(struct dynbuf *buf, + struct ssl_primary_config *ssl, + bool *is_local) +{ + CURLcode result = CURLE_OK; + if(ssl->clientcert && ssl->clientcert[0]) { + result = cf_ssl_peer_key_add_path(buf, "CCERT", ssl->clientcert, is_local); + if(result) + goto out; + } + if(ssl->key && ssl->key[0]) { + result = cf_ssl_peer_key_add_path(buf, "KEY", ssl->key, is_local); + if(result) + goto out; + } + if(ssl->key_blob) { + result = cf_ssl_peer_key_add_hash(buf, "KEYBlob", ssl->key_blob); + if(result) + goto out; + } + if(ssl->cert_type && ssl->cert_type[0]) { + size_t i; + result = curlx_dyn_add(buf, ":CT-"); + for(i = 0; !result && ssl->cert_type[i]; i++) { + char c = Curl_raw_toupper(ssl->cert_type[i]); + result = curlx_dyn_addn(buf, &c, 1); + } + if(result) + goto out; + } + if(ssl->key_type && ssl->key_type[0]) { + size_t i; + result = curlx_dyn_add(buf, ":KT-"); + for(i = 0; !result && ssl->key_type[i]; i++) { + char c = Curl_raw_toupper(ssl->key_type[i]); + result = curlx_dyn_addn(buf, &c, 1); + } + } +out: + return result; +} + +#define CURL_SSLS_LOCAL_SUFFIX ":L" +#define CURL_SSLS_GLOBAL_SUFFIX ":G" + +static bool cf_ssl_peer_key_is_global(const char *peer_key) +{ + size_t len = peer_key ? strlen(peer_key) : 0; + return (len > 2) && + (peer_key[len - 1] == 'G') && + (peer_key[len - 2] == ':'); +} + +static CURLcode ssl_peer_key_add_transport(struct dynbuf *buf, + uint8_t transport) +{ + switch(transport) { + case TRNSPRT_TCP: + return CURLE_OK; + case TRNSPRT_UDP: + return curlx_dyn_add(buf, ":UDP"); + case TRNSPRT_QUIC: + return curlx_dyn_add(buf, ":QUIC"); + case TRNSPRT_UNIX: + return curlx_dyn_add(buf, ":UNIX"); + default: + return curlx_dyn_addf(buf, ":TRNSPRT-%d", transport); + } +} + +static CURLcode ssl_peer_key_add_vrfy(struct dynbuf *buf, + struct ssl_primary_config *ssl, + const struct ssl_peer *peer) +{ + CURLcode result; + + if(!ssl->verifypeer) { + result = curlx_dyn_add(buf, ":NO-VRFY-PEER"); + if(result) + return result; + } + if(!ssl->verifyhost) { + result = curlx_dyn_add(buf, ":NO-VRFY-HOST"); + if(result) + return result; + } + if(ssl->verifystatus) { + result = curlx_dyn_add(buf, ":VRFY-STATUS"); + if(result) + return result; + } + if((!ssl->verifypeer || !ssl->verifyhost) && + peer->peer && !Curl_peer_equal(peer->origin, peer->peer)) { + result = curlx_dyn_addf(buf, ":CHOST-%s:CPORT-%u", + peer->peer->hostname, + peer->peer->port); + if(result) + return result; + } + return CURLE_OK; +} + +static CURLcode ssl_peer_key_build(struct ssl_primary_config *ssl, + const struct ssl_peer *peer, + const char *tls_id, + char **ppeer_key) +{ + struct dynbuf buf; + size_t key_len; + bool is_local = FALSE; + CURLcode result; + + *ppeer_key = NULL; + curlx_dyn_init(&buf, 10 * 1024); + + result = curlx_dyn_addf(&buf, "%s:%d", + peer->origin->hostname, peer->origin->port); + if(result) + goto out; + result = ssl_peer_key_add_transport(&buf, peer->transport); + if(result) + goto out; + result = ssl_peer_key_add_vrfy(&buf, ssl, peer); + if(result) + goto out; + if(ssl->version || ssl->version_max) { + result = curlx_dyn_addf(&buf, ":TLSVER-%d-%u", ssl->version, + (ssl->version_max >> 16)); + if(result) + goto out; + } + if(ssl->ssl_options) { + result = curlx_dyn_addf(&buf, ":TLSOPT-%x", ssl->ssl_options); + if(result) + goto out; + } + if(ssl->cipher_list) { + result = curlx_dyn_addf(&buf, ":CIPHER-%s", ssl->cipher_list); + if(result) + goto out; + } + if(ssl->cipher_list13) { + result = curlx_dyn_addf(&buf, ":CIPHER13-%s", ssl->cipher_list13); + if(result) + goto out; + } + if(ssl->curves) { + result = curlx_dyn_addf(&buf, ":CURVES-%s", ssl->curves); + if(result) + goto out; + } + if(ssl->signature_algorithms) { + result = curlx_dyn_addf(&buf, ":SIGALGS-%s", + ssl->signature_algorithms); + if(result) + goto out; + } + if(ssl->verifypeer) { + result = cf_ssl_peer_key_add_path(&buf, "CA", ssl->CAfile, &is_local); + if(result) + goto out; + result = cf_ssl_peer_key_add_path(&buf, "CApath", ssl->CApath, &is_local); + if(result) + goto out; + result = cf_ssl_peer_key_add_path(&buf, "CRL", ssl->CRLfile, &is_local); + if(result) + goto out; + result = cf_ssl_peer_key_add_path(&buf, "Issuer", ssl->issuercert, + &is_local); + if(result) + goto out; + if(ssl->ca_info_blob) { + result = cf_ssl_peer_key_add_hash(&buf, "CAInfoBlob", ssl->ca_info_blob); + if(result) + goto out; + } + if(ssl->issuercert_blob) { + result = cf_ssl_peer_key_add_hash(&buf, "IssuerBlob", + ssl->issuercert_blob); + if(result) + goto out; + } + } + if(ssl->cert_blob) { + result = cf_ssl_peer_key_add_hash(&buf, "CertBlob", ssl->cert_blob); + if(result) + goto out; + } + if(ssl->pinned_key && ssl->pinned_key[0]) { + result = curlx_dyn_addf(&buf, ":Pinned-%s", ssl->pinned_key); + if(result) + goto out; + } + + result = cf_ssl_peer_key_add_mtls(&buf, ssl, &is_local); + if(result) + goto out; + + if(!tls_id || !tls_id[0]) { + result = CURLE_FAILED_INIT; + goto out; + } + result = curlx_dyn_addf(&buf, ":IMPL-%s", tls_id); + if(result) + goto out; + + result = curlx_dyn_addf(&buf, is_local ? + CURL_SSLS_LOCAL_SUFFIX : CURL_SSLS_GLOBAL_SUFFIX); + if(result) + goto out; + + *ppeer_key = curlx_dyn_take(&buf, &key_len); + /* we added printable char, and dynbuf always null-terminates, no need + * to track length */ + +out: + curlx_dyn_free(&buf); + return result; +} + +CURLcode Curl_ssl_peer_key_make(const struct ssl_peer *peer, + struct ssl_primary_config *sslc, + const char *tls_id, + char **ppeer_key) +{ + return ssl_peer_key_build(sslc, peer, tls_id, ppeer_key); +} + +struct Curl_ssl_scache { + unsigned int magic; + struct Curl_ssl_scache_peer *peers; + size_t peer_count; + int default_lifetime_secs; + long age; +#ifdef USE_MUTEX + curl_mutex_t mutex; + curl_thread_id_t locking_thread; +#endif + BIT(is_locked); +}; + +static struct Curl_ssl_scache *cf_ssl_scache_get(struct Curl_easy *data) +{ + struct Curl_ssl_scache *scache = NULL; + /* If a share is present, its ssl_scache has preference over the multi */ + if(data->share && data->share->ssl_scache) + scache = data->share->ssl_scache; + else if(data->multi && data->multi->ssl_scache) + scache = data->multi->ssl_scache; + if(scache && !GOOD_SCACHE(scache)) { + failf(data, "transfer would use an invalid scache at %p, denied", + (void *)scache); + DEBUGASSERT(0); + return NULL; + } + return scache; +} + +static void cf_ssl_scache_session_ldestroy(void *udata, void *obj) +{ + struct Curl_ssl_session *s = obj; + (void)udata; + curlx_free(s->sdata); + curlx_free(s->quic_tp); + curlx_free(s->alpn); + curlx_free(s); +} + +CURLcode Curl_ssl_session_create(void *sdata, size_t sdata_len, + int ietf_tls_id, const char *alpn, + curl_off_t valid_until, size_t earlydata_max, + struct Curl_ssl_session **psession) +{ + return Curl_ssl_session_create2(sdata, sdata_len, ietf_tls_id, alpn, + valid_until, earlydata_max, + NULL, 0, psession); +} + +CURLcode Curl_ssl_session_create2(void *sdata, size_t sdata_len, + int ietf_tls_id, const char *alpn, + curl_off_t valid_until, size_t earlydata_max, + unsigned char *quic_tp, size_t quic_tp_len, + struct Curl_ssl_session **psession) +{ + struct Curl_ssl_session *s; + + if(!sdata || !sdata_len) { + curlx_free(sdata); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + *psession = NULL; + s = curlx_calloc(1, sizeof(*s)); + if(!s) { + curlx_free(sdata); + curlx_free(quic_tp); + return CURLE_OUT_OF_MEMORY; + } + + s->ietf_tls_id = ietf_tls_id; + s->valid_until = valid_until; + s->earlydata_max = earlydata_max; + s->sdata = sdata; + s->sdata_len = sdata_len; + s->quic_tp = quic_tp; + s->quic_tp_len = quic_tp_len; + if(alpn) { + s->alpn = curlx_strdup(alpn); + if(!s->alpn) { + cf_ssl_scache_session_ldestroy(NULL, s); + return CURLE_OUT_OF_MEMORY; + } + } + *psession = s; + return CURLE_OK; +} + +void Curl_ssl_session_destroy(struct Curl_ssl_session *s) +{ + if(s) { + /* if in the list, the list destructor takes care of it */ + if(Curl_node_llist(&s->list)) + Curl_node_remove(&s->list); + else { + cf_ssl_scache_session_ldestroy(NULL, s); + } + } +} + +CURLcode Curl_ssl_session_dup(struct Curl_ssl_session *src, + struct Curl_ssl_session **pdest) +{ + struct Curl_ssl_session *dest = NULL; + CURLcode result = CURLE_OUT_OF_MEMORY; + + if(!src || !pdest) + return CURLE_BAD_FUNCTION_ARGUMENT; + *pdest = NULL; + + dest = curlx_calloc(1, sizeof(*dest)); + if(!dest) + goto out; + + dest->ietf_tls_id = src->ietf_tls_id; + dest->valid_until = src->valid_until; + dest->earlydata_max = src->earlydata_max; + dest->sectrust_verified = src->sectrust_verified; + if(src->sdata_len) { + dest->sdata = curlx_memdup(src->sdata, src->sdata_len); + if(!dest->sdata) + goto out; + dest->sdata_len = src->sdata_len; + } + if(src->quic_tp_len) { + dest->quic_tp = curlx_memdup(src->quic_tp, src->quic_tp_len); + if(!dest->quic_tp) + goto out; + dest->quic_tp_len = src->quic_tp_len; + } + if(src->alpn) { + dest->alpn = curlx_strdup(src->alpn); + if(!dest->alpn) + goto out; + } + result = CURLE_OK; + +out: + if(!result) + *pdest = dest; + else { + *pdest = NULL; + if(dest) + Curl_ssl_session_destroy(dest); + } + return result; +} + +static void cf_ssl_scache_clear_peer(struct Curl_ssl_scache_peer *peer) +{ + Curl_llist_destroy(&peer->sessions, NULL); + if(peer->sobj) { + DEBUGASSERT(peer->sobj_free); + if(peer->sobj_free) + peer->sobj_free(peer->sobj); + peer->sobj = NULL; + } + peer->sobj_free = NULL; + curlx_safefree(peer->clientcert); + curlx_safefree(peer->key_passwd); + curlx_safefree(peer->ssl_peer_key); + peer->age = 0; + peer->hmac_set = FALSE; +} + +static void cf_ssl_scache_peer_set_obj(struct Curl_ssl_scache_peer *peer, + void *sobj, + Curl_ssl_scache_obj_dtor *sobj_free) +{ + DEBUGASSERT(peer); + if(peer->sobj_free) { + peer->sobj_free(peer->sobj); + } + peer->sobj = sobj; + peer->sobj_free = sobj_free; +} + +static void cf_ssl_cache_peer_update(struct Curl_ssl_scache_peer *peer) +{ + /* The sessions of this peer are exportable if + * - it has no confidential information + * - its peer key is not yet known, because sessions were + * imported using only the salt+hmac + * - the peer key is global, e.g. carrying no relative paths */ + peer->exportable = (!peer->clientcert && !peer->key_passwd && + (!peer->ssl_peer_key || + cf_ssl_peer_key_is_global(peer->ssl_peer_key))); +} + +static CURLcode cf_ssl_scache_peer_init(struct Curl_ssl_scache_peer *peer, + const char *ssl_peer_key, + const char *clientcert, + const char *key_passwd, + const unsigned char *salt, + const unsigned char *hmac) +{ + CURLcode result = CURLE_OUT_OF_MEMORY; + + DEBUGASSERT(!peer->ssl_peer_key); + if(ssl_peer_key) { + peer->ssl_peer_key = curlx_strdup(ssl_peer_key); + if(!peer->ssl_peer_key) + goto out; + peer->hmac_set = FALSE; + } + else if(salt && hmac) { + memcpy(peer->key_salt, salt, sizeof(peer->key_salt)); + memcpy(peer->key_hmac, hmac, sizeof(peer->key_hmac)); + peer->hmac_set = TRUE; + } + else { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + if(clientcert) { + peer->clientcert = curlx_strdup(clientcert); + if(!peer->clientcert) + goto out; + } + if(key_passwd) { + peer->key_passwd = curlx_strdup(key_passwd); + if(!peer->key_passwd) + goto out; + } + cf_ssl_cache_peer_update(peer); + result = CURLE_OK; +out: + if(result) + cf_ssl_scache_clear_peer(peer); + return result; +} + +static void cf_scache_session_remove(struct Curl_ssl_scache_peer *peer, + struct Curl_ssl_session *s) +{ + (void)peer; + DEBUGASSERT(Curl_node_llist(&s->list) == &peer->sessions); + Curl_ssl_session_destroy(s); +} + +static bool cf_scache_session_expired(struct Curl_ssl_session *s, + curl_off_t now) +{ + return (s->valid_until > 0) && (s->valid_until < now); +} + +static void cf_scache_peer_remove_expired(struct Curl_ssl_scache_peer *peer, + curl_off_t now) +{ + struct Curl_llist_node *n = Curl_llist_head(&peer->sessions); + while(n) { + struct Curl_ssl_session *s = Curl_node_elem(n); + n = Curl_node_next(n); + if(cf_scache_session_expired(s, now)) + cf_scache_session_remove(peer, s); + } +} + +static void cf_scache_peer_remove_non13(struct Curl_ssl_scache_peer *peer) +{ + struct Curl_llist_node *n = Curl_llist_head(&peer->sessions); + while(n) { + struct Curl_ssl_session *s = Curl_node_elem(n); + n = Curl_node_next(n); + if(s->ietf_tls_id != CURL_IETF_PROTO_TLS1_3) + cf_scache_session_remove(peer, s); + } +} + +CURLcode Curl_ssl_scache_create(size_t max_peers, + size_t max_sessions_per_peer, + struct Curl_ssl_scache **pscache) +{ + struct Curl_ssl_scache *scache; + struct Curl_ssl_scache_peer *peers; + size_t i; + + *pscache = NULL; + peers = curlx_calloc(max_peers, sizeof(*peers)); + if(!peers) + return CURLE_OUT_OF_MEMORY; + + scache = curlx_calloc(1, sizeof(*scache)); + if(!scache) { + curlx_free(peers); + return CURLE_OUT_OF_MEMORY; + } + + scache->magic = CURL_SCACHE_MAGIC; + scache->default_lifetime_secs = (24 * 60 * 60); /* 1 day */ + scache->peer_count = max_peers; + scache->peers = peers; + scache->age = 1; + for(i = 0; i < scache->peer_count; ++i) { + scache->peers[i].max_sessions = max_sessions_per_peer; + Curl_llist_init(&scache->peers[i].sessions, + cf_ssl_scache_session_ldestroy); + } +#ifdef USE_MUTEX + Curl_mutex_init(&scache->mutex); +#endif + *pscache = scache; + return CURLE_OK; +} + +void Curl_ssl_scache_destroy(struct Curl_ssl_scache *scache) +{ + if(GOOD_SCACHE(scache)) { + size_t i; + scache->magic = 0; + for(i = 0; i < scache->peer_count; ++i) { + cf_ssl_scache_clear_peer(&scache->peers[i]); + } + curlx_free(scache->peers); +#ifdef USE_MUTEX + Curl_mutex_destroy(&scache->mutex); +#endif + curlx_free(scache); + } +} + +bool Curl_ssl_scache_use(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + if(cf_ssl_scache_get(data)) { + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + return ssl_config ? ssl_config->primary.cache_session : FALSE; + } + return FALSE; +} + +/* Lock shared SSL session data */ +void Curl_ssl_scache_lock(struct Curl_easy *data) +{ + struct Curl_ssl_scache *scache = cf_ssl_scache_get(data); + if(scache) { + if(CURL_SHARE_ssl_scache(data)) + Curl_share_lock(data, CURL_LOCK_DATA_SSL_SESSION, + CURL_LOCK_ACCESS_SINGLE); +#ifdef USE_MUTEX + Curl_mutex_acquire(&scache->mutex); + scache->locking_thread = Curl_thread_get_current_id(); + DEBUGASSERT(!scache->is_locked); + scache->is_locked = TRUE; + Curl_mutex_release(&scache->mutex); +#else + DEBUGASSERT(!scache->is_locked); + scache->is_locked = TRUE; +#endif + } +} + +/* Unlock shared SSL session data */ +void Curl_ssl_scache_unlock(struct Curl_easy *data) +{ + struct Curl_ssl_scache *scache = cf_ssl_scache_get(data); + if(scache) { +#ifdef USE_MUTEX + Curl_mutex_acquire(&scache->mutex); + scache->locking_thread = 0; + DEBUGASSERT(scache->is_locked); + scache->is_locked = FALSE; + Curl_mutex_release(&scache->mutex); +#else + DEBUGASSERT(scache->is_locked); + scache->is_locked = FALSE; +#endif + if(CURL_SHARE_ssl_scache(data)) + Curl_share_unlock(data, CURL_LOCK_DATA_SSL_SESSION); + } +} + +bool Curl_ssl_scache_is_locked_by_current_thread(struct Curl_easy *data) +{ + struct Curl_ssl_scache *scache = cf_ssl_scache_get(data); + bool locked = FALSE; + if(!scache) + return FALSE; +#ifdef USE_MUTEX + Curl_mutex_acquire(&scache->mutex); + locked = scache->is_locked && Curl_thread_is_current(scache->locking_thread); + Curl_mutex_release(&scache->mutex); +#else + locked = (bool)scache->is_locked; +#endif + return locked; +} + +static bool cf_ssl_scache_match_auth(struct Curl_ssl_scache_peer *peer, + struct ssl_primary_config *conn_config) +{ + if(!conn_config) { + if(peer->clientcert || peer->key_passwd) + return FALSE; + return TRUE; + } + else if(!Curl_safecmp(peer->clientcert, conn_config->clientcert)) + return FALSE; + if(Curl_timestrcmp(peer->key_passwd, conn_config->key_passwd)) + return FALSE; + return TRUE; +} + +static CURLcode cf_ssl_find_peer_by_key(struct Curl_easy *data, + struct Curl_ssl_scache *scache, + const char *ssl_peer_key, + struct ssl_primary_config *conn_config, + struct Curl_ssl_scache_peer **ppeer) +{ + size_t i, peer_key_len = 0; + CURLcode result = CURLE_OK; + + *ppeer = NULL; + if(!GOOD_SCACHE(scache)) { + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + CURL_TRC_SSLS(data, "find peer slot for %s among %zu slots", + ssl_peer_key, scache->peer_count); + + /* check for entries with known peer_key */ + for(i = 0; scache && i < scache->peer_count; i++) { + if(scache->peers[i].ssl_peer_key && + !strcmp(ssl_peer_key, scache->peers[i].ssl_peer_key) && + cf_ssl_scache_match_auth(&scache->peers[i], conn_config)) { + /* yes, we have a cached session for this! */ + *ppeer = &scache->peers[i]; + goto out; + } + } + /* check for entries with HMAC set but no known peer_key */ + for(i = 0; scache && i < scache->peer_count; i++) { + if(!scache->peers[i].ssl_peer_key && + scache->peers[i].hmac_set && + cf_ssl_scache_match_auth(&scache->peers[i], conn_config)) { + /* possible entry with unknown peer_key, check hmac */ + unsigned char my_hmac[CURL_SHA256_DIGEST_LENGTH]; + if(!peer_key_len) /* we are lazy */ + peer_key_len = strlen(ssl_peer_key); + result = Curl_hmacit(&Curl_HMAC_SHA256, + scache->peers[i].key_salt, + sizeof(scache->peers[i].key_salt), + (const unsigned char *)ssl_peer_key, + peer_key_len, + my_hmac); + if(result) + goto out; + if(!memcmp(scache->peers[i].key_hmac, my_hmac, sizeof(my_hmac))) { + /* remember peer_key for future lookups */ + CURL_TRC_SSLS(data, "peer entry %zu key recovered: %s", + i, ssl_peer_key); + scache->peers[i].ssl_peer_key = curlx_strdup(ssl_peer_key); + if(!scache->peers[i].ssl_peer_key) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + cf_ssl_cache_peer_update(&scache->peers[i]); + *ppeer = &scache->peers[i]; + goto out; + } + } + } + CURL_TRC_SSLS(data, "peer not found for %s", ssl_peer_key); +out: + return result; +} + +static struct Curl_ssl_scache_peer *cf_ssl_get_free_peer( + struct Curl_ssl_scache *scache) +{ + struct Curl_ssl_scache_peer *peer = NULL; + size_t i; + + /* find empty or oldest peer */ + for(i = 0; i < scache->peer_count; ++i) { + /* free peer entry? */ + if(!scache->peers[i].ssl_peer_key && !scache->peers[i].hmac_set) { + peer = &scache->peers[i]; + break; + } + /* peer without sessions and obj */ + if(!scache->peers[i].sobj && + !Curl_llist_count(&scache->peers[i].sessions)) { + peer = &scache->peers[i]; + break; + } + /* remember "oldest" peer */ + if(!peer || (scache->peers[i].age < peer->age)) { + peer = &scache->peers[i]; + } + } + DEBUGASSERT(peer); + if(peer) + cf_ssl_scache_clear_peer(peer); + return peer; +} + +static CURLcode cf_ssl_add_peer(struct Curl_easy *data, + struct Curl_ssl_scache *scache, + const char *ssl_peer_key, + struct ssl_primary_config *conn_config, + struct Curl_ssl_scache_peer **ppeer) +{ + struct Curl_ssl_scache_peer *peer = NULL; + CURLcode result = CURLE_OK; + + *ppeer = NULL; + if(ssl_peer_key) { + result = cf_ssl_find_peer_by_key(data, scache, ssl_peer_key, conn_config, + &peer); + if(result || !scache->peer_count) + return result; + } + + if(peer) { + *ppeer = peer; + return CURLE_OK; + } + + peer = cf_ssl_get_free_peer(scache); + if(peer) { + char buffer[64]; + const char *ccert = conn_config ? conn_config->clientcert : NULL; + const char *kpasswd = conn_config ? conn_config->key_passwd : NULL; + if(!ccert && conn_config && conn_config->cert_blob) { + /* when using a client cert blob, create a name for it */ + curl_msnprintf(buffer, sizeof(buffer), + "cert-%p", conn_config->cert_blob->data); + ccert = buffer; /* data is strduped by cf_ssl_scache_peer_init */ + } + result = cf_ssl_scache_peer_init(peer, ssl_peer_key, ccert, kpasswd, + NULL, NULL); + if(result) + goto out; + /* all ready */ + *ppeer = peer; + result = CURLE_OK; + } + +out: + if(result) { + cf_ssl_scache_clear_peer(peer); + } + return result; +} + +static void cf_scache_peer_add_session(struct Curl_ssl_scache_peer *peer, + struct Curl_ssl_session *s, + curl_off_t now) +{ + /* A session not from TLSv1.3 replaces all other. */ + if(s->ietf_tls_id != CURL_IETF_PROTO_TLS1_3) { + Curl_llist_destroy(&peer->sessions, NULL); + Curl_llist_append(&peer->sessions, s, &s->list); + } + else { + /* Expire existing, append, trim from head to obey max_sessions */ + cf_scache_peer_remove_expired(peer, now); + cf_scache_peer_remove_non13(peer); + Curl_llist_append(&peer->sessions, s, &s->list); + while(Curl_llist_count(&peer->sessions) > peer->max_sessions) { + Curl_node_remove(Curl_llist_head(&peer->sessions)); + } + } +} + +static CURLcode cf_scache_add_session(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct Curl_ssl_scache *scache, + const char *ssl_peer_key, + struct Curl_ssl_session *s) +{ + struct Curl_ssl_scache_peer *peer = NULL; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + CURLcode result = CURLE_OUT_OF_MEMORY; + curl_off_t now = (curl_off_t)time(NULL); + curl_off_t max_lifetime; + + if(!scache || !scache->peer_count) { + Curl_ssl_session_destroy(s); + return CURLE_OK; + } + + if(s->valid_until <= 0) + s->valid_until = now + scache->default_lifetime_secs; + + max_lifetime = (s->ietf_tls_id == CURL_IETF_PROTO_TLS1_3) ? + CURL_SCACHE_MAX_13_LIFETIME_SEC : + CURL_SCACHE_MAX_12_LIFETIME_SEC; + if(s->valid_until > (now + max_lifetime)) + s->valid_until = now + max_lifetime; + + if(cf_scache_session_expired(s, now)) { + CURL_TRC_SSLS(data, "add, session already expired"); + Curl_ssl_session_destroy(s); + return CURLE_OK; + } + + result = cf_ssl_add_peer(data, scache, ssl_peer_key, conn_config, &peer); + if(result || !peer) { + CURL_TRC_SSLS(data, "unable to add scache peer: %d", (int)result); + Curl_ssl_session_destroy(s); + goto out; + } + + cf_scache_peer_add_session(peer, s, now); + +out: + if(result) { + failf(data, "[SCACHE] failed to add session for %s, error=%d", + ssl_peer_key, (int)result); + } + else + CURL_TRC_SSLS(data, "added session for %s [proto=0x%x, " + "valid_secs=%" FMT_OFF_T ", alpn=%s, earlydata=%zu, " + "quic_tp=%s], peer has %zu sessions now", ssl_peer_key, + (unsigned int)s->ietf_tls_id, s->valid_until - now, + s->alpn, s->earlydata_max, s->quic_tp ? "yes" : "no", + peer ? Curl_llist_count(&peer->sessions) : 0); + return result; +} + +CURLcode Curl_ssl_scache_put(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key, + struct Curl_ssl_session *s) +{ + struct Curl_ssl_scache *scache = cf_ssl_scache_get(data); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + CURLcode result; + DEBUGASSERT(ssl_config); + + if(!scache || !ssl_config->primary.cache_session) { + Curl_ssl_session_destroy(s); + return CURLE_OK; + } + + Curl_ssl_scache_lock(data); + result = cf_scache_add_session(cf, data, scache, ssl_peer_key, s); + Curl_ssl_scache_unlock(data); + return result; +} + +void Curl_ssl_scache_return(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key, + struct Curl_ssl_session *s) +{ + /* See RFC 8446 C.4: + * "Clients SHOULD NOT reuse a ticket for multiple connections." */ + if(s && s->ietf_tls_id < 0x304) + (void)Curl_ssl_scache_put(cf, data, ssl_peer_key, s); + else + Curl_ssl_session_destroy(s); +} + +CURLcode Curl_ssl_scache_take(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key, + struct Curl_ssl_session **ps) +{ + struct Curl_ssl_scache *scache = cf_ssl_scache_get(data); + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_ssl_scache_peer *peer = NULL; + struct Curl_llist_node *n; + struct Curl_ssl_session *s = NULL; + CURLcode result; + + *ps = NULL; + if(!scache) + return CURLE_OK; + + Curl_ssl_scache_lock(data); + result = cf_ssl_find_peer_by_key(data, scache, ssl_peer_key, conn_config, + &peer); + if(!result && peer) { + cf_scache_peer_remove_expired(peer, (curl_off_t)time(NULL)); + n = Curl_llist_head(&peer->sessions); + if(n) { + s = Curl_node_take_elem(n); + scache->age++; /* increase general age */ + peer->age = scache->age; /* set this as used in this age */ + } + } + if(s) { + *ps = s; + CURL_TRC_SSLS(data, "took session for %s [proto=0x%x, " + "alpn=%s, earlydata=%zu, quic_tp=%s], %zu sessions remain", + ssl_peer_key, (unsigned int)s->ietf_tls_id, s->alpn, + s->earlydata_max, s->quic_tp ? "yes" : "no", + Curl_llist_count(&peer->sessions)); + } + else { + CURL_TRC_SSLS(data, "no cached session for %s", ssl_peer_key); + } + Curl_ssl_scache_unlock(data); + return result; +} + +CURLcode Curl_ssl_scache_add_obj(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key, + void *sobj, + Curl_ssl_scache_obj_dtor *sobj_dtor_cb) +{ + struct Curl_ssl_scache *scache = cf_ssl_scache_get(data); + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_ssl_scache_peer *peer = NULL; + CURLcode result; + + DEBUGASSERT(sobj); + DEBUGASSERT(sobj_dtor_cb); + + if(!scache) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + + result = cf_ssl_add_peer(data, scache, ssl_peer_key, conn_config, &peer); + if(result || !peer) { + CURL_TRC_SSLS(data, "unable to add scache peer: %d", (int)result); + goto out; + } + + cf_ssl_scache_peer_set_obj(peer, sobj, sobj_dtor_cb); + sobj = NULL; /* peer took ownership */ + +out: + if(sobj && sobj_dtor_cb) + sobj_dtor_cb(sobj); + return result; +} + +void *Curl_ssl_scache_get_obj(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key) +{ + struct Curl_ssl_scache *scache = cf_ssl_scache_get(data); + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_ssl_scache_peer *peer = NULL; + CURLcode result; + void *sobj; + + if(!scache) + return NULL; + + result = cf_ssl_find_peer_by_key(data, scache, ssl_peer_key, conn_config, + &peer); + if(result) + return NULL; + + sobj = peer ? peer->sobj : NULL; + + CURL_TRC_SSLS(data, "%s cached session for '%s'", + sobj ? "Found" : "No", ssl_peer_key); + return sobj; +} + +void Curl_ssl_scache_remove_all(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key) +{ + struct Curl_ssl_scache *scache = cf_ssl_scache_get(data); + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_ssl_scache_peer *peer = NULL; + CURLcode result; + + (void)cf; + if(!scache) + return; + + Curl_ssl_scache_lock(data); + result = cf_ssl_find_peer_by_key(data, scache, ssl_peer_key, conn_config, + &peer); + if(!result && peer) + cf_ssl_scache_clear_peer(peer); + Curl_ssl_scache_unlock(data); +} + +#ifdef USE_SSLS_EXPORT + +#define CURL_SSL_TICKET_MAX (16 * 1024) + +static CURLcode cf_ssl_scache_peer_set_hmac(struct Curl_ssl_scache_peer *peer) +{ + CURLcode result; + + DEBUGASSERT(peer); + if(!peer->ssl_peer_key) + return CURLE_BAD_FUNCTION_ARGUMENT; + + result = Curl_rand(NULL, peer->key_salt, sizeof(peer->key_salt)); + if(result) + return result; + + result = Curl_hmacit(&Curl_HMAC_SHA256, + peer->key_salt, sizeof(peer->key_salt), + (const unsigned char *)peer->ssl_peer_key, + strlen(peer->ssl_peer_key), + peer->key_hmac); + if(!result) + peer->hmac_set = TRUE; + return result; +} + +static CURLcode cf_ssl_find_peer_by_hmac(struct Curl_ssl_scache *scache, + const unsigned char *salt, + const unsigned char *hmac, + struct Curl_ssl_scache_peer **ppeer) +{ + size_t i; + CURLcode result = CURLE_OK; + + *ppeer = NULL; + if(!GOOD_SCACHE(scache)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + /* look for an entry that matches salt+hmac exactly or has a known + * ssl_peer_key which salt+hmac's to the same. */ + for(i = 0; scache && i < scache->peer_count; i++) { + struct Curl_ssl_scache_peer *peer = &scache->peers[i]; + if(!cf_ssl_scache_match_auth(peer, NULL)) + continue; + if(scache->peers[i].hmac_set && + !memcmp(peer->key_salt, salt, sizeof(peer->key_salt)) && + !memcmp(peer->key_hmac, hmac, sizeof(peer->key_hmac))) { + /* found exact match, return */ + *ppeer = peer; + goto out; + } + else if(peer->ssl_peer_key) { + unsigned char my_hmac[CURL_SHA256_DIGEST_LENGTH]; + /* compute hmac for the passed salt */ + result = Curl_hmacit(&Curl_HMAC_SHA256, + salt, sizeof(peer->key_salt), + (const unsigned char *)peer->ssl_peer_key, + strlen(peer->ssl_peer_key), + my_hmac); + if(result) + goto out; + if(!memcmp(my_hmac, hmac, sizeof(my_hmac))) { + /* cryptohash match, take over salt+hmac if no set and return */ + if(!peer->hmac_set) { + memcpy(peer->key_salt, salt, sizeof(peer->key_salt)); + memcpy(peer->key_hmac, hmac, sizeof(peer->key_hmac)); + peer->hmac_set = TRUE; + } + *ppeer = peer; + goto out; + } + } + } +out: + return result; +} + +CURLcode Curl_ssl_session_import(struct Curl_easy *data, + const char *ssl_peer_key, + const unsigned char *shmac, size_t shmac_len, + const void *sdata, size_t sdata_len) +{ + struct Curl_ssl_scache *scache = cf_ssl_scache_get(data); + struct Curl_ssl_scache_peer *peer = NULL; + struct Curl_ssl_session *s = NULL; + CURLcode result; + + if(!scache) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + if(!ssl_peer_key && (!shmac || !shmac_len)) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + + result = Curl_ssl_session_unpack(data, sdata, sdata_len, &s); + if(result) + goto out; + + Curl_ssl_scache_lock(data); + + if(ssl_peer_key) { + result = cf_ssl_add_peer(data, scache, ssl_peer_key, NULL, &peer); + if(result) + goto out; + } + else if(shmac_len != (sizeof(peer->key_salt) + sizeof(peer->key_hmac))) { + /* Either salt+hmac was garbled by caller or is from a curl version + * that does things differently */ + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + else { + const unsigned char *salt = shmac; + const unsigned char *hmac = shmac + sizeof(peer->key_salt); + + result = cf_ssl_find_peer_by_hmac(scache, salt, hmac, &peer); + if(result) + goto out; + if(!peer) { + peer = cf_ssl_get_free_peer(scache); + if(peer) { + result = cf_ssl_scache_peer_init(peer, ssl_peer_key, NULL, NULL, + salt, hmac); + if(result) + goto out; + } + } + } + + if(peer) { + cf_scache_peer_add_session(peer, s, time(NULL)); + s = NULL; /* peer is now owner */ + CURL_TRC_SSLS(data, "successfully imported ticket for peer %s, now " + "with %zu tickets", + peer->ssl_peer_key ? peer->ssl_peer_key : "without key", + Curl_llist_count(&peer->sessions)); + } + +out: + if(scache && scache->is_locked) + Curl_ssl_scache_unlock(data); + Curl_ssl_session_destroy(s); + return result; +} + +CURLcode Curl_ssl_session_export(struct Curl_easy *data, + curl_ssls_export_cb *export_fn, + void *userptr) +{ + struct Curl_ssl_scache *scache = cf_ssl_scache_get(data); + struct Curl_ssl_scache_peer *peer; + struct dynbuf sbuf, hbuf; + struct Curl_llist_node *n; + size_t i; + curl_off_t now = time(NULL); + CURLcode result = CURLE_OK; +#ifdef CURLVERBOSE + size_t npeers = 0, ntickets = 0; +#endif + + if(!export_fn) + return CURLE_BAD_FUNCTION_ARGUMENT; + + Curl_ssl_scache_lock(data); + + curlx_dyn_init(&hbuf, (CURL_SHA256_DIGEST_LENGTH * 2) + 1); + curlx_dyn_init(&sbuf, CURL_SSL_TICKET_MAX); + + for(i = 0; scache && i < scache->peer_count; i++) { + peer = &scache->peers[i]; + if(!peer->ssl_peer_key && !peer->hmac_set) + continue; /* skip free entry */ + if(!peer->exportable) + continue; + + curlx_dyn_reset(&hbuf); + cf_scache_peer_remove_expired(peer, now); + n = Curl_llist_head(&peer->sessions); + if(n) + VERBOSE(++npeers); + while(n) { + struct Curl_ssl_session *s = Curl_node_elem(n); + if(!peer->hmac_set) { + result = cf_ssl_scache_peer_set_hmac(peer); + if(result) + goto out; + } + if(!curlx_dyn_len(&hbuf)) { + result = curlx_dyn_addn(&hbuf, peer->key_salt, sizeof(peer->key_salt)); + if(result) + goto out; + result = curlx_dyn_addn(&hbuf, peer->key_hmac, sizeof(peer->key_hmac)); + if(result) + goto out; + } + curlx_dyn_reset(&sbuf); + result = Curl_ssl_session_pack(data, s, &sbuf); + if(result) + goto out; + + result = export_fn(data, userptr, peer->ssl_peer_key, + curlx_dyn_uptr(&hbuf), curlx_dyn_len(&hbuf), + curlx_dyn_uptr(&sbuf), curlx_dyn_len(&sbuf), + s->valid_until, s->ietf_tls_id, + s->alpn, s->earlydata_max); + if(result) + goto out; + VERBOSE(++ntickets); + n = Curl_node_next(n); + } + } + result = CURLE_OK; + CURL_TRC_SSLS(data, "exported %zu session tickets for %zu peers", + ntickets, npeers); + +out: + Curl_ssl_scache_unlock(data); + curlx_dyn_free(&hbuf); + curlx_dyn_free(&sbuf); + return result; +} + +#endif /* USE_SSLS_EXPORT */ + +#endif /* USE_SSL */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_scache.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_scache.h new file mode 100644 index 0000000000..c9f35e800f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_scache.h @@ -0,0 +1,221 @@ +#ifndef HEADER_CURL_VTLS_SCACHE_H +#define HEADER_CURL_VTLS_SCACHE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_SSL + +#include "cfilters.h" +#include "urldata.h" + +struct Curl_cfilter; +struct Curl_easy; +struct Curl_ssl_scache; +struct Curl_ssl_session; +struct ssl_peer; + +/* RFC 8446 (TLSv1.3) restrict lifetime to one week max, for + * other, less secure versions, we restrict it to a day */ +#define CURL_SCACHE_MAX_13_LIFETIME_SEC (60 * 60 * 24 * 7) +#define CURL_SCACHE_MAX_12_LIFETIME_SEC (60 * 60 * 24) + +/* Create a session cache for up to max_peers endpoints with a total + * of up to max_sessions SSL sessions per peer */ +CURLcode Curl_ssl_scache_create(size_t max_peers, + size_t max_sessions_per_peer, + struct Curl_ssl_scache **pscache); + +void Curl_ssl_scache_destroy(struct Curl_ssl_scache *scache); + +/* Create a key from peer and TLS configuration information that is + * unique for how the connection filter wants to establish a TLS + * connection to the peer. + * If the filter is a TLS proxy filter, it uses the proxy relevant + * information. + * @param peer the peer the filter wants to talk to + * @param sslc the relevant ssl configuration + * @param tls_id identifier of TLS implementation for sessions. Should + * include full version if session data from other versions + * is to be avoided. + * @param ppeer_key on successful return, the key generated + */ +CURLcode Curl_ssl_peer_key_make(const struct ssl_peer *peer, + struct ssl_primary_config *sslc, + const char *tls_id, + char **ppeer_key); + +/* Return if there is a session cache shall be used. + * An SSL session might not be configured or not available for + * "connect-only" transfers. + */ +bool Curl_ssl_scache_use(struct Curl_cfilter *cf, struct Curl_easy *data); + +/* Lock session cache mutex. + * Call this before calling other Curl_ssl_*session* functions + * Caller should unlock this mutex as soon as possible, as it may block + * other SSL connection from making progress. + * The purpose of explicitly locking SSL session cache data is to allow + * individual SSL engines to manage session lifetime in their specific way. + */ +void Curl_ssl_scache_lock(struct Curl_easy *data); + +/* Unlock session cache mutex */ +void Curl_ssl_scache_unlock(struct Curl_easy *data); + +/* Get TLS session object from the cache for the ssl_peer_key. + * scache mutex must be locked (see Curl_ssl_scache_lock). + * Caller must make sure that the ownership of returned session object + * is properly taken (e.g. its refcount is incremented + * under scache mutex). + * @param cf the connection filter wanting to use it + * @param data the transfer involved + * @param ssl_peer_key the key for lookup + * @retval sobj the object for the peer key or NULL + */ +void *Curl_ssl_scache_get_obj(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key); + +typedef void Curl_ssl_scache_obj_dtor(void *sobj); + +/* Add a TLS session related object to the cache. + * Replaces an existing object with the same peer_key. + * scache mutex must be locked (see Curl_ssl_scache_lock). + * Call takes ownership of `sobj`, using `sobj_dtor_cb` + * to deallocate it. Is called in all outcomes, either right away or + * later when the session cache is cleaned up. + * Caller must ensure that it has properly shared ownership of `sobj` + * with cache (e.g. incrementing refcount on success) + * @param cf the connection filter wanting to use it + * @param data the transfer involved + * @param ssl_peer_key the key for lookup + * @param sobj the TLS session object + * @param sobj_free_cb callback to free the session object + */ +CURLcode Curl_ssl_scache_add_obj(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key, + void *sobj, + Curl_ssl_scache_obj_dtor *sobj_dtor_cb); + +/* All about an SSL session ticket */ +struct Curl_ssl_session { + uint8_t *sdata; /* session ticket data, plain bytes */ + size_t sdata_len; /* number of bytes in sdata */ + curl_off_t valid_until; /* seconds since EPOCH until ticket expires */ + int ietf_tls_id; /* TLS protocol identifier negotiated */ + char *alpn; /* APLN TLS negotiated protocol string */ + size_t earlydata_max; /* max 0-RTT data supported by peer */ + uint8_t *quic_tp; /* Optional QUIC transport param bytes */ + size_t quic_tp_len; /* number of bytes in quic_tp */ + struct Curl_llist_node list; /* internal storage handling */ + BIT(sectrust_verified); /* session comes from sectrust verified TLS */ +}; + +/* Create a `session` instance. Does NOT need locking. + * Takes ownership of `sdata` and `sobj` regardless of return code. + * @param sdata bytes of SSL session data or NULL (sobj then required) + * @param sdata_len amount of session data bytes + * @param ietf_tls_id IETF protocol version, e.g. 0x304 for TLSv1.3 + * @param alpn ALPN protocol selected or NULL + * @param valid_until seconds since EPOCH when session expires, pass 0 + * in case this is not known. + * @param psession on return the scached session instance created + */ +CURLcode Curl_ssl_session_create(void *sdata, size_t sdata_len, + int ietf_tls_id, const char *alpn, + curl_off_t valid_until, size_t earlydata_max, + struct Curl_ssl_session **psession); + +/* Variation of session creation with quic transport parameter bytes, + * Takes ownership of `quic_tp` regardless of return code. */ +CURLcode Curl_ssl_session_create2(void *sdata, size_t sdata_len, + int ietf_tls_id, const char *alpn, + curl_off_t valid_until, size_t earlydata_max, + unsigned char *quic_tp, size_t quic_tp_len, + struct Curl_ssl_session **psession); + +/* Duplicate an ssl session */ +CURLcode Curl_ssl_session_dup(struct Curl_ssl_session *src, + struct Curl_ssl_session **pdest); + +/* Destroy a `session` instance. Can be called with NULL. + * Does NOT need locking. */ +void Curl_ssl_session_destroy(struct Curl_ssl_session *s); + +/* Put the scache session into the cache. Does NOT need locking. + * Call takes ownership of `s` in all outcomes. + * @param cf the connection filter wanting to use it + * @param data the transfer involved + * @param ssl_peer_key the key for lookup + * @param s the scache session object + */ +CURLcode Curl_ssl_scache_put(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key, + struct Curl_ssl_session *s); + +/* Take a matching scache session from the cache. Does NOT need locking. + * @param cf the connection filter wanting to use it + * @param data the transfer involved + * @param ssl_peer_key the key for lookup + * @param s on return, the scache session object or NULL + */ +CURLcode Curl_ssl_scache_take(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key, + struct Curl_ssl_session **ps); + +/* Return a taken scache session to the cache. Does NOT need locking. + * Depending on TLS version and other criteria, it may cache it again + * or destroy it. Maybe called with a NULL session. + */ +void Curl_ssl_scache_return(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key, + struct Curl_ssl_session *s); + +/* Remove all sessions and obj for the peer_key. Does NOT need locking. */ +void Curl_ssl_scache_remove_all(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key); + +bool Curl_ssl_scache_is_locked_by_current_thread(struct Curl_easy *data); + +#ifdef USE_SSLS_EXPORT + +CURLcode Curl_ssl_session_import(struct Curl_easy *data, + const char *ssl_peer_key, + const unsigned char *shmac, size_t shmac_len, + const void *sdata, size_t sdata_len); + +CURLcode Curl_ssl_session_export(struct Curl_easy *data, + curl_ssls_export_cb *export_fn, + void *userptr); + +#endif /* USE_SSLS_EXPORT */ +#endif /* USE_SSL */ + +#endif /* HEADER_CURL_VTLS_SCACHE_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_spack.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_spack.c new file mode 100644 index 0000000000..d8e51c4fd1 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_spack.c @@ -0,0 +1,335 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_SSL) && defined(USE_SSLS_EXPORT) + +#include "urldata.h" +#include "curl_trc.h" +#include "vtls/vtls_scache.h" +#include "vtls/vtls_spack.h" +#include "curlx/strdup.h" + +#define CURL_SPACK_VERSION 0x01 +#define CURL_SPACK_IETF_ID 0x02 +#define CURL_SPACK_VALID_UNTIL 0x03 +#define CURL_SPACK_TICKET 0x04 +#define CURL_SPACK_ALPN 0x05 +#define CURL_SPACK_EARLYDATA 0x06 +#define CURL_SPACK_QUICTP 0x07 +#define CURL_SPACK_SECTRUST 0x08 + +static CURLcode spack_enc8(struct dynbuf *buf, uint8_t b) +{ + return curlx_dyn_addn(buf, &b, 1); +} + +static CURLcode spack_dec8(uint8_t *val, const uint8_t **src, + const uint8_t *end) +{ + if(end - *src < 1) + return CURLE_READ_ERROR; + *val = **src; + *src += 1; + return CURLE_OK; +} + +static CURLcode spack_enc16(struct dynbuf *buf, uint16_t val) +{ + uint8_t nval[2]; + nval[0] = (uint8_t)(val >> 8); + nval[1] = (uint8_t)val; + return curlx_dyn_addn(buf, nval, sizeof(nval)); +} + +static CURLcode spack_dec16(uint16_t *val, const uint8_t **src, + const uint8_t *end) +{ + if(end - *src < 2) + return CURLE_READ_ERROR; + *val = (uint16_t)((*src)[0] << 8 | (*src)[1]); + *src += 2; + return CURLE_OK; +} + +static CURLcode spack_enc32(struct dynbuf *buf, uint32_t val) +{ + uint8_t nval[4]; + nval[0] = (uint8_t)(val >> 24); + nval[1] = (uint8_t)(val >> 16); + nval[2] = (uint8_t)(val >> 8); + nval[3] = (uint8_t)val; + return curlx_dyn_addn(buf, nval, sizeof(nval)); +} + +static CURLcode spack_dec32(uint32_t *val, const uint8_t **src, + const uint8_t *end) +{ + if(end - *src < 4) + return CURLE_READ_ERROR; + *val = (uint32_t)(*src)[0] << 24 | (uint32_t)(*src)[1] << 16 | + (uint32_t)(*src)[2] << 8 | (*src)[3]; + *src += 4; + return CURLE_OK; +} + +static CURLcode spack_enc64(struct dynbuf *buf, uint64_t val) +{ + uint8_t nval[8]; + nval[0] = (uint8_t)(val >> 56); + nval[1] = (uint8_t)(val >> 48); + nval[2] = (uint8_t)(val >> 40); + nval[3] = (uint8_t)(val >> 32); + nval[4] = (uint8_t)(val >> 24); + nval[5] = (uint8_t)(val >> 16); + nval[6] = (uint8_t)(val >> 8); + nval[7] = (uint8_t)val; + return curlx_dyn_addn(buf, nval, sizeof(nval)); +} + +static CURLcode spack_dec64(uint64_t *val, const uint8_t **src, + const uint8_t *end) +{ + if(end - *src < 8) + return CURLE_READ_ERROR; + *val = (uint64_t)(*src)[0] << 56 | (uint64_t)(*src)[1] << 48 | + (uint64_t)(*src)[2] << 40 | (uint64_t)(*src)[3] << 32 | + (uint64_t)(*src)[4] << 24 | (uint64_t)(*src)[5] << 16 | + (uint64_t)(*src)[6] << 8 | (*src)[7]; + *src += 8; + return CURLE_OK; +} + +static CURLcode spack_encstr16(struct dynbuf *buf, const char *s) +{ + size_t slen = strlen(s); + CURLcode result; + if(slen > UINT16_MAX) + return CURLE_BAD_FUNCTION_ARGUMENT; + result = spack_enc16(buf, (uint16_t)slen); + if(!result) { + result = curlx_dyn_addn(buf, s, slen); + } + return result; +} + +static CURLcode spack_decstr16(char **val, const uint8_t **src, + const uint8_t *end) +{ + uint16_t slen; + CURLcode result; + + *val = NULL; + result = spack_dec16(&slen, src, end); + if(result) + return result; + if(end - *src < slen) + return CURLE_READ_ERROR; + *val = curlx_memdup0((const char *)(*src), slen); + *src += slen; + return *val ? CURLE_OK : CURLE_OUT_OF_MEMORY; +} + +static CURLcode spack_encdata16(struct dynbuf *buf, const uint8_t *data, + size_t data_len) +{ + CURLcode result; + if(data_len > UINT16_MAX) + return CURLE_BAD_FUNCTION_ARGUMENT; + result = spack_enc16(buf, (uint16_t)data_len); + if(!result) { + result = curlx_dyn_addn(buf, data, data_len); + } + return result; +} + +static CURLcode spack_decdata16(uint8_t **val, size_t *val_len, + const uint8_t **src, const uint8_t *end) +{ + uint16_t data_len; + CURLcode result; + + *val = NULL; + result = spack_dec16(&data_len, src, end); + if(result) + return result; + if(end - *src < data_len) + return CURLE_READ_ERROR; + *val = curlx_memdup0((const char *)(*src), data_len); + *val_len = data_len; + *src += data_len; + return *val ? CURLE_OK : CURLE_OUT_OF_MEMORY; +} + +CURLcode Curl_ssl_session_pack(struct Curl_easy *data, + struct Curl_ssl_session *s, + struct dynbuf *buf) +{ + CURLcode result; + DEBUGASSERT(s->sdata); + DEBUGASSERT(s->sdata_len); + + if(s->valid_until < 0) + return CURLE_BAD_FUNCTION_ARGUMENT; + + result = spack_enc8(buf, CURL_SPACK_VERSION); + if(!result) + result = spack_enc8(buf, CURL_SPACK_TICKET); + if(!result) + result = spack_encdata16(buf, s->sdata, s->sdata_len); + if(!result) + result = spack_enc8(buf, CURL_SPACK_IETF_ID); + if(!result) + result = spack_enc16(buf, (uint16_t)s->ietf_tls_id); + if(!result) + result = spack_enc8(buf, CURL_SPACK_VALID_UNTIL); + if(!result) + result = spack_enc64(buf, (uint64_t)s->valid_until); + if(!result && s->alpn) { + result = spack_enc8(buf, CURL_SPACK_ALPN); + if(!result) + result = spack_encstr16(buf, s->alpn); + } + if(!result && s->earlydata_max) { + if(s->earlydata_max > UINT32_MAX) + result = CURLE_BAD_FUNCTION_ARGUMENT; + if(!result) + result = spack_enc8(buf, CURL_SPACK_EARLYDATA); + if(!result) + result = spack_enc32(buf, (uint32_t)s->earlydata_max); + } + if(!result && s->sectrust_verified) { + result = spack_enc8(buf, CURL_SPACK_SECTRUST); + } + if(!result && s->quic_tp && s->quic_tp_len) { + result = spack_enc8(buf, CURL_SPACK_QUICTP); + if(!result) + result = spack_encdata16(buf, s->quic_tp, s->quic_tp_len); + } + + if(result) + CURL_TRC_SSLS(data, "error packing data: %d", (int)result); + return result; +} + +CURLcode Curl_ssl_session_unpack(struct Curl_easy *data, + const void *bufv, size_t buflen, + struct Curl_ssl_session **ps) +{ + struct Curl_ssl_session *s = NULL; + const unsigned char *buf = (const unsigned char *)bufv; + const unsigned char *end = buf + buflen; + uint8_t val8, *pval8; + uint16_t val16; + uint32_t val32; + uint64_t val64; + size_t dlen; + CURLcode result; + + DEBUGASSERT(buf); + DEBUGASSERT(buflen); + *ps = NULL; + + result = spack_dec8(&val8, &buf, end); + if(result) + goto out; + if(val8 != CURL_SPACK_VERSION) { + result = CURLE_READ_ERROR; + goto out; + } + + s = curlx_calloc(1, sizeof(*s)); + if(!s) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + while(buf < end) { + result = spack_dec8(&val8, &buf, end); + if(result) + goto out; + + switch(val8) { + case CURL_SPACK_ALPN: + curlx_free(s->alpn); + result = spack_decstr16(&s->alpn, &buf, end); + if(result) + goto out; + break; + case CURL_SPACK_EARLYDATA: + result = spack_dec32(&val32, &buf, end); + if(result) + goto out; + s->earlydata_max = val32; + break; + case CURL_SPACK_IETF_ID: + result = spack_dec16(&val16, &buf, end); + if(result) + goto out; + s->ietf_tls_id = val16; + break; + case CURL_SPACK_QUICTP: { + result = spack_decdata16(&pval8, &dlen, &buf, end); + if(result) + goto out; + curlx_free(s->quic_tp); + s->quic_tp = pval8; + s->quic_tp_len = dlen; + break; + } + case CURL_SPACK_TICKET: { + result = spack_decdata16(&pval8, &dlen, &buf, end); + if(result) + goto out; + curlx_free(s->sdata); + s->sdata = pval8; + s->sdata_len = dlen; + break; + } + case CURL_SPACK_VALID_UNTIL: + result = spack_dec64(&val64, &buf, end); + if(result) + goto out; + s->valid_until = (curl_off_t)val64; + break; + case CURL_SPACK_SECTRUST: + s->sectrust_verified = TRUE; + break; + default: /* unknown tag */ + result = CURLE_READ_ERROR; + goto out; + } + } + +out: + if(result) { + CURL_TRC_SSLS(data, "error unpacking data: %d", (int)result); + Curl_ssl_session_destroy(s); + } + else + *ps = s; + return result; +} + +#endif /* USE_SSL && USE_SSLS_EXPORT */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_spack.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_spack.h new file mode 100644 index 0000000000..4479384de9 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/vtls_spack.h @@ -0,0 +1,43 @@ +#ifndef HEADER_CURL_VTLS_SPACK_H +#define HEADER_CURL_VTLS_SPACK_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_SSL) && defined(USE_SSLS_EXPORT) + +struct dynbuf; +struct Curl_ssl_session; + +CURLcode Curl_ssl_session_pack(struct Curl_easy *data, + struct Curl_ssl_session *s, + struct dynbuf *buf); + +CURLcode Curl_ssl_session_unpack(struct Curl_easy *data, + const void *bufv, size_t buflen, + struct Curl_ssl_session **ps); + +#endif /* USE_SSL && USE_SSLS_EXPORT */ + +#endif /* HEADER_CURL_VTLS_SPACK_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/wolfssl.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/wolfssl.c new file mode 100644 index 0000000000..4b9facadf0 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/wolfssl.c @@ -0,0 +1,2350 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Source file for all wolfSSL specific code for the TLS/SSL layer. No code + * but vtls.c should ever call or use these functions. + * + */ +#include "curl_setup.h" + +#ifdef USE_WOLFSSL + +#include <wolfssl/options.h> +#include <wolfssl/version.h> + +#if LIBWOLFSSL_VERSION_HEX < 0x05000000 /* wolfSSL 5.0.0 (2021-11-01) */ +#error "wolfSSL 5.0.0 or greater required" +#endif +#if defined(OPENSSL_COEXIST) && LIBWOLFSSL_VERSION_HEX < 0x05007006 +#error "wolfSSL 5.7.6 or greater required to coexist with OpenSSL" +#endif + +/* To determine what functions are available we rely on one or both of: + - the user's options.h generated by wolfSSL + - the symbols detected by curl's configure + Since they are markedly different from one another, and one or the other may + not be available, we do some checking below to bring things in sync. */ + +/* HAVE_ALPN is wolfSSL's build time symbol for enabling ALPN in options.h. */ +#ifndef HAVE_ALPN +#ifdef HAVE_WOLFSSL_USEALPN +#define HAVE_ALPN +#endif +#endif + +#include "urldata.h" +#include "curl_trc.h" +#include "vdns/cf-dns.h" +#include "vdns/httpsrr.h" +#include "vtls/vtls.h" +#include "vtls/vtls_int.h" +#include "vtls/vtls_scache.h" +#include "vtls/keylog.h" +#include "connect.h" /* for the connect timeout */ +#include "progress.h" +#include "curlx/strdup.h" +#include "curlx/strcopy.h" +#include "vtls/x509asn1.h" +#ifdef USE_ECH +#include "curlx/base64.h" +#endif + +#include <wolfssl/ssl.h> +#include <wolfssl/error-ssl.h> + +#include "vtls/wolfssl.h" + +/* KEEP_PEER_CERT is a product of the presence of build time symbol + OPENSSL_EXTRA without NO_CERTS, depending on the version. KEEP_PEER_CERT is + in wolfSSL's settings.h, and the latter two are build time symbols in + options.h. */ +#ifndef KEEP_PEER_CERT +#if defined(HAVE_WOLFSSL_GET_PEER_CERTIFICATE) || \ + (defined(OPENSSL_EXTRA) && !defined(NO_CERTS)) +#define KEEP_PEER_CERT +#endif +#endif + +#ifdef HAVE_WOLFSSL_BIO_NEW +#define USE_BIO_CHAIN +#ifdef HAVE_WOLFSSL_BIO_SET_SHUTDOWN +#define USE_FULL_BIO +#else /* HAVE_WOLFSSL_BIO_SET_SHUTDOWN */ +#undef USE_FULL_BIO +#endif +/* wolfSSL 5.7.4 and older do not have these symbols, but only the + * OpenSSL ones. */ +#ifndef WOLFSSL_BIO_CTRL_GET_CLOSE +#define WOLFSSL_BIO_CTRL_GET_CLOSE BIO_CTRL_GET_CLOSE +#define WOLFSSL_BIO_CTRL_SET_CLOSE BIO_CTRL_SET_CLOSE +#define WOLFSSL_BIO_CTRL_FLUSH BIO_CTRL_FLUSH +#define WOLFSSL_BIO_CTRL_DUP BIO_CTRL_DUP +#define wolfSSL_BIO_set_retry_write BIO_set_retry_write +#define wolfSSL_BIO_set_retry_read BIO_set_retry_read +#endif /* !WOLFSSL_BIO_CTRL_GET_CLOSE */ + +#else /* HAVE_WOLFSSL_BIO_NEW */ +#undef USE_BIO_CHAIN +#endif + +#ifdef OPENSSL_EXTRA +/* + * Availability note: + * The TLS 1.3 secret callback (wolfSSL_set_tls13_secret_cb) was added in + * wolfSSL 4.4.0, but requires the -DHAVE_SECRET_CALLBACK build option. If that + * option is not set, then TLS 1.3 is not logged. + * For TLS 1.2 and before, we use wolfSSL_get_keys(). + * wolfSSL_get_client_random and wolfSSL_get_keys require OPENSSL_EXTRA + * (--enable-opensslextra or --enable-all). + */ +#if defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13) +static int wssl_tls13_secret_callback(SSL *ssl, int id, + const unsigned char *secret, + int secretSz, void *ctx) +{ + const char *label; + unsigned char client_random[SSL3_RANDOM_SIZE]; + (void)ctx; + + if(!ssl || !Curl_tls_keylog_enabled()) { + return 0; + } + + switch(id) { + case CLIENT_EARLY_TRAFFIC_SECRET: + label = "CLIENT_EARLY_TRAFFIC_SECRET"; + break; + case CLIENT_HANDSHAKE_TRAFFIC_SECRET: + label = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"; + break; + case SERVER_HANDSHAKE_TRAFFIC_SECRET: + label = "SERVER_HANDSHAKE_TRAFFIC_SECRET"; + break; + case CLIENT_TRAFFIC_SECRET: + label = "CLIENT_TRAFFIC_SECRET_0"; + break; + case SERVER_TRAFFIC_SECRET: + label = "SERVER_TRAFFIC_SECRET_0"; + break; + case EARLY_EXPORTER_SECRET: + label = "EARLY_EXPORTER_SECRET"; + break; + case EXPORTER_SECRET: + label = "EXPORTER_SECRET"; + break; + default: + return 0; + } + + if(wolfSSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE) == 0) { + /* Should never happen as wolfSSL_KeepArrays() was called before. */ + return 0; + } + + Curl_tls_keylog_write(label, client_random, sizeof(client_random), + secret, secretSz); + return 0; +} +#endif /* HAVE_SECRET_CALLBACK && WOLFSSL_TLS13 */ + +static void wssl_log_tls12_secret(WOLFSSL *ssl) +{ + unsigned char *ms, *sr, *cr; + unsigned int msLen, srLen, crLen, i, x = 0; + + /* wolfSSL_GetVersion is available since 3.13, we use it instead of + * SSL_version since the latter relies on OPENSSL_ALL (--enable-opensslall or + * --enable-all). Failing to perform this check could result in an unusable + * key log line when TLS 1.3 is actually negotiated. */ + switch(wolfSSL_GetVersion(ssl)) { + case WOLFSSL_SSLV3: + case WOLFSSL_TLSV1: + case WOLFSSL_TLSV1_1: + case WOLFSSL_TLSV1_2: + break; + default: + /* TLS 1.3 does not use this mechanism, the "master secret" returned below + * is not directly usable. */ + return; + } + + if(wolfSSL_get_keys(ssl, &ms, &msLen, &sr, &srLen, &cr, &crLen) != + WOLFSSL_SUCCESS) { + return; + } + + /* Check for a missing master secret and skip logging. That can happen if + * curl rejects the server certificate and aborts the handshake. + */ + for(i = 0; i < msLen; i++) { + x |= ms[i]; + } + if(x == 0) { + return; + } + + Curl_tls_keylog_write("CLIENT_RANDOM", cr, crLen, ms, msLen); +} +#endif /* OPENSSL_EXTRA */ + +static int wssl_do_file_type(const char *type) +{ + if(!type || !type[0]) + return WOLFSSL_FILETYPE_PEM; + if(curl_strequal(type, "PEM")) + return WOLFSSL_FILETYPE_PEM; + if(curl_strequal(type, "DER")) + return WOLFSSL_FILETYPE_ASN1; + return -1; +} + +#ifdef USE_BIO_CHAIN + +static int wssl_bio_cf_create(WOLFSSL_BIO *bio) +{ +#ifdef USE_FULL_BIO + wolfSSL_BIO_set_shutdown(bio, 1); +#endif + wolfSSL_BIO_set_data(bio, NULL); + return 1; +} + +static int wssl_bio_cf_destroy(WOLFSSL_BIO *bio) +{ + if(!bio) + return 0; + return 1; +} + +static long wssl_bio_cf_ctrl(WOLFSSL_BIO *bio, int cmd, long num, void *ptr) +{ + struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio); + long ret = 1; + + (void)cf; + (void)ptr; + (void)num; + switch(cmd) { + case WOLFSSL_BIO_CTRL_GET_CLOSE: +#ifdef USE_FULL_BIO + ret = (long)wolfSSL_BIO_get_shutdown(bio); +#else + ret = 0; +#endif + break; + case WOLFSSL_BIO_CTRL_SET_CLOSE: +#ifdef USE_FULL_BIO + wolfSSL_BIO_set_shutdown(bio, (int)num); +#endif + break; + case WOLFSSL_BIO_CTRL_FLUSH: + /* we do no delayed writes, but if we ever would, this + * needs to trigger it. */ + ret = 1; + break; + case WOLFSSL_BIO_CTRL_DUP: + ret = 1; + break; +#ifdef WOLFSSL_BIO_CTRL_EOF + case WOLFSSL_BIO_CTRL_EOF: { + /* EOF has been reached on input? */ + struct ssl_connect_data *connssl = cf->ctx; + return connssl->peer_closed; + } +#endif + default: + ret = 0; + break; + } + return ret; +} + +static int wssl_bio_cf_out_write(WOLFSSL_BIO *bio, const char *buf, int blen) +{ + struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio); + struct ssl_connect_data *connssl = cf->ctx; + struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + size_t nwritten, skiplen = 0; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + if(wssl->shutting_down && wssl->io_send_blocked_len && + (wssl->io_send_blocked_len < blen)) { + /* bug in wolfSSL: <https://github.com/wolfSSL/wolfssl/issues/7784> + * It adds the close notify message again every time we retry + * sending during shutdown. */ + CURL_TRC_CF(data, cf, "bio_write, shutdown restrict send of %d" + " to %d bytes", blen, wssl->io_send_blocked_len); + skiplen = (size_t)(blen - wssl->io_send_blocked_len); + blen = wssl->io_send_blocked_len; + } + result = Curl_conn_cf_send(cf->next, data, + (const uint8_t *)buf, blen, FALSE, &nwritten); + wssl->io_result = result; + CURL_TRC_CF(data, cf, "bio_write(len=%d) -> %d, %zu", + blen, (int)result, nwritten); +#ifdef USE_FULL_BIO + wolfSSL_BIO_clear_retry_flags(bio); +#endif + if(result == CURLE_AGAIN) { + wolfSSL_BIO_set_retry_write(bio); + if(wssl->shutting_down && !wssl->io_send_blocked_len) + wssl->io_send_blocked_len = blen; + } + else if(!result && skiplen) + nwritten += skiplen; + return result ? -1 : (int)nwritten; +} + +static int wssl_bio_cf_in_read(WOLFSSL_BIO *bio, char *buf, int blen) +{ + struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio); + struct ssl_connect_data *connssl = cf->ctx; + struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + size_t nread = 0; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + if(!data || (blen < 0)) { + wssl->io_result = CURLE_FAILED_INIT; + return -1; + } + if(!buf || !blen) + return 0; + + if((connssl->connecting_state == ssl_connect_2) && + !wssl->x509_store_setup) { + /* During handshake, init the x509 store before receiving the + * server response. This allows sending of ClientHello without delay. */ + result = Curl_wssl_setup_x509_store(cf, data, wssl); + if(result) { + CURL_TRC_CF(data, cf, "Curl_wssl_setup_x509_store() -> %d", (int)result); + wssl->io_result = result; + return -1; + } + } + + result = Curl_conn_cf_recv(cf->next, data, buf, blen, &nread); + wssl->io_result = result; + CURL_TRC_CF(data, cf, "bio_read(len=%d) -> %d, %zu", blen, (int)result, + nread); +#ifdef USE_FULL_BIO + wolfSSL_BIO_clear_retry_flags(bio); +#endif + if(result == CURLE_AGAIN) + wolfSSL_BIO_set_retry_read(bio); + else if(nread == 0) + connssl->peer_closed = TRUE; + return result ? -1 : (int)nread; +} + +static WOLFSSL_BIO_METHOD *wssl_bio_cf_method = NULL; + +static int wssl_bio_cf_init_methods(void) +{ + wssl_bio_cf_method = wolfSSL_BIO_meth_new(WOLFSSL_BIO_MEMORY, + "wolfSSL CF BIO"); + if(!wssl_bio_cf_method) + return FALSE; /* error */ + wolfSSL_BIO_meth_set_write(wssl_bio_cf_method, &wssl_bio_cf_out_write); + wolfSSL_BIO_meth_set_read(wssl_bio_cf_method, &wssl_bio_cf_in_read); + wolfSSL_BIO_meth_set_ctrl(wssl_bio_cf_method, &wssl_bio_cf_ctrl); + wolfSSL_BIO_meth_set_create(wssl_bio_cf_method, &wssl_bio_cf_create); + wolfSSL_BIO_meth_set_destroy(wssl_bio_cf_method, &wssl_bio_cf_destroy); + return TRUE; /* fine */ +} + +static void wssl_bio_cf_free_methods(void) +{ + wolfSSL_BIO_meth_free(wssl_bio_cf_method); + wssl_bio_cf_method = NULL; +} + +#else /* USE_BIO_CHAIN */ + +#define wssl_bio_cf_init_methods() TRUE +#define wssl_bio_cf_free_methods() Curl_nop_stmt + +#endif /* !USE_BIO_CHAIN */ + +#ifdef HAVE_EX_DATA +CURLcode Curl_wssl_cache_session(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key, + WOLFSSL_SESSION *session, + int ietf_tls_id, + const char *alpn, + unsigned char *quic_tp, + size_t quic_tp_len, + struct Curl_ssl_session **pscs) +{ + CURLcode result = CURLE_OK; + struct Curl_ssl_session *sc_session = NULL, *sc_dup = NULL; + unsigned char *sdata = NULL, *sdata_ptr, *qtp_clone = NULL; + unsigned int sdata_len; + unsigned int earlydata_max = 0; + + if(pscs) + *pscs = NULL; + if(!session) + goto out; + + sdata_len = wolfSSL_i2d_SSL_SESSION(session, NULL); + if(sdata_len <= 0) { + CURL_TRC_CF(data, cf, "fail to assess session length: %u", sdata_len); + result = CURLE_FAILED_INIT; + goto out; + } + sdata = sdata_ptr = curlx_calloc(1, sdata_len); + if(!sdata) { + failf(data, "unable to allocate session buffer of %u bytes", sdata_len); + result = CURLE_OUT_OF_MEMORY; + goto out; + } + /* wolfSSL right now does not change the last parameter here, but it + * might one day decide to do so for OpenSSL compatibility. */ + sdata_len = wolfSSL_i2d_SSL_SESSION(session, &sdata_ptr); + if(sdata_len <= 0) { + CURL_TRC_CF(data, cf, "fail to serialize session: %u", sdata_len); + result = CURLE_FAILED_INIT; + goto out; + } + if(quic_tp && quic_tp_len) { + qtp_clone = curlx_memdup0((const char *)quic_tp, quic_tp_len); + if(!qtp_clone) { + curlx_free(sdata); + return CURLE_OUT_OF_MEMORY; + } + } +#ifdef WOLFSSL_EARLY_DATA + earlydata_max = wolfSSL_SESSION_get_max_early_data(session); +#endif + + result = Curl_ssl_session_create2(sdata, sdata_len, + ietf_tls_id, alpn, + (curl_off_t)time(NULL) + + wolfSSL_SESSION_get_timeout(session), + earlydata_max, qtp_clone, quic_tp_len, + &sc_session); + sdata = NULL; /* took ownership of sdata */ + if(!result && pscs && /* return a duplicate if asked for and FTP */ + (cf->conn->scheme->family == CURLPROTO_FTP)) + result = Curl_ssl_session_dup(sc_session, &sc_dup); + if(!result) { + result = Curl_ssl_scache_put(cf, data, ssl_peer_key, sc_session); + /* took ownership of `sc_session` */ + sc_session = NULL; + } + +out: + curlx_free(sdata); + if(!result && pscs) { + *pscs = sc_dup; + sc_dup = NULL; + } + Curl_ssl_session_destroy(sc_session); + Curl_ssl_session_destroy(sc_dup); + return result; +} + +static int wssl_vtls_new_session_cb(WOLFSSL *ssl, WOLFSSL_SESSION *session) +{ + struct Curl_cfilter *cf; + + cf = (struct Curl_cfilter *)wolfSSL_get_app_data(ssl); + DEBUGASSERT(cf); + if(cf && session) { + struct ssl_connect_data *connssl = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + struct Curl_ssl_session *scs = NULL; + DEBUGASSERT(connssl); + DEBUGASSERT(data); + if(connssl && data) { + (void)Curl_wssl_cache_session(cf, data, connssl->peer.scache_key, + session, wolfSSL_version(ssl), + connssl->negotiated.alpn, NULL, 0, &scs); + if(scs) { + Curl_ssl_session_destroy(connssl->session); + connssl->session = scs; + } + } + } + return 0; +} +#endif + +static CURLcode wssl_on_session_reuse(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct alpn_spec *alpns, + struct Curl_ssl_session *scs, + bool *do_early_data) +{ + struct ssl_connect_data *connssl = cf->ctx; +#ifdef WOLFSSL_EARLY_DATA + struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend; + + connssl->earlydata_max = wolfSSL_SESSION_get_max_early_data( + wolfSSL_get_session(wssl->ssl)); +#else + connssl->earlydata_max = 0; +#endif + + /* Seems to be no wolfSSL way to signal no EarlyData in session */ + return Curl_on_session_reuse(cf, data, alpns, scs, do_early_data, + connssl->earlydata_max); +} + +static bool wssl_apply_session( + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct wssl_ctx *wss, + struct alpn_spec *alpns, + Curl_wssl_init_session_reuse_cb *sess_reuse_cb, + struct Curl_ssl_session *scs) +{ + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + CURLcode result = CURLE_OK; + WOLFSSL_SESSION *session = NULL; + bool success = FALSE; + + if(scs && scs->sdata && scs->sdata_len && + (!scs->alpn || Curl_alpn_contains_proto(alpns, scs->alpn))) { + /* wolfSSL changes the passed pointer for whatever reasons, yikes */ + const unsigned char *sdata = scs->sdata; + session = wolfSSL_d2i_SSL_SESSION(NULL, &sdata, (long)scs->sdata_len); + if(session) { + int ret = wolfSSL_set_session(wss->ssl, session); + if(ret != WOLFSSL_SUCCESS) { + infof(data, "cached session not accepted (%d), " + "removing from cache", ret); + goto out; + } + else { + infof(data, "SSL reusing session with ALPN '%s'", + scs->alpn ? scs->alpn : "-"); + success = TRUE; + if(ssl_config->earlydata && + !cf->conn->bits.connect_only && + !strcmp("TLSv1.3", wolfSSL_get_version(wss->ssl))) { + bool do_early_data = FALSE; + if(sess_reuse_cb) { + result = sess_reuse_cb(cf, data, alpns, scs, &do_early_data); + if(result) { + goto out; + } + } +#ifdef WOLFSSL_EARLY_DATA + if(do_early_data) { + unsigned int edmax = (scs->earlydata_max < UINT_MAX) ? + (unsigned int)scs->earlydata_max : UINT_MAX; + /* We only try the ALPN protocol the session used before, + * otherwise we might send early data for the wrong protocol */ + Curl_alpn_restrict_to(alpns, scs->alpn); + wolfSSL_set_max_early_data(wss->ssl, edmax); + } +#else + /* Should never enable when not supported */ + DEBUGASSERT(!do_early_data); +#endif + } + } + } + else { + failf(data, "could not decode previous session"); + } + } +out: + wolfSSL_SESSION_free(session); + return success; +} + +static CURLcode wssl_populate_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + WOLFSSL_X509_STORE *store, + struct wssl_ctx *wssl) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; + const char * const ssl_cafile = + /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */ + (ca_info_blob ? NULL : conn_config->CAfile); + const char * const ssl_capath = conn_config->CApath; + bool imported_native_ca = FALSE; + bool imported_ca_info_blob = FALSE; + +#ifndef NO_FILESYSTEM + /* load native CA certificates */ + if(conn_config->native_ca_store) { +#ifdef WOLFSSL_SYS_CA_CERTS + if(wolfSSL_CTX_load_system_CA_certs(wssl->ssl_ctx) != WOLFSSL_SUCCESS) { + infof(data, "error importing native CA store, continuing anyway"); + } + else { + imported_native_ca = TRUE; + infof(data, "successfully imported native CA store"); + } +#else + infof(data, "ignoring native CA option because wolfSSL was built without " + "native CA support"); +#endif + } +#endif /* !NO_FILESYSTEM */ + + /* load certificate blob */ + if(ca_info_blob) { + if(wolfSSL_CTX_load_verify_buffer(wssl->ssl_ctx, ca_info_blob->data, + (long)ca_info_blob->len, + WOLFSSL_FILETYPE_PEM) != + WOLFSSL_SUCCESS) { + failf(data, "error importing CA certificate blob"); + return CURLE_SSL_CACERT_BADFILE; + } + else { + imported_ca_info_blob = TRUE; + infof(data, "successfully imported CA certificate blob"); + } + } + +#ifndef NO_FILESYSTEM + /* load trusted cacert from file if not blob */ + + CURL_TRC_CF(data, cf, "wssl_populate_x509_store, path=%s, blob=%d", + ssl_cafile ? ssl_cafile : "none", !!ca_info_blob); + if(!store) + return CURLE_OUT_OF_MEMORY; + + if(ssl_cafile || ssl_capath) { + int rc = + wolfSSL_CTX_load_verify_locations_ex(wssl->ssl_ctx, + ssl_cafile, + ssl_capath, + WOLFSSL_LOAD_FLAG_IGNORE_ERR); + if(rc != WOLFSSL_SUCCESS) { + if(conn_config->verifypeer && + !imported_native_ca && !imported_ca_info_blob) { + /* Fail if we insist on successfully verifying the server. */ + failf(data, "error setting certificate verify locations:" + " CAfile: %s CApath: %s", + ssl_cafile ? ssl_cafile : "none", + ssl_capath ? ssl_capath : "none"); + return CURLE_SSL_CACERT_BADFILE; + } + else { + /* continue with a warning if no strict certificate + verification is required. */ + infof(data, "error setting certificate verify locations," + " continuing anyway:"); + } + } + else { + /* Everything is fine. */ + infof(data, "successfully set certificate verify locations:"); + } + infof(data, " CAfile: %s", ssl_cafile ? ssl_cafile : "none"); + infof(data, " CApath: %s", ssl_capath ? ssl_capath : "none"); + } +#endif + (void)store; + return CURLE_OK; +} + +/* key to use at `multi->proto_hash` */ +#define MPROTO_WSSL_X509_KEY "tls:wssl:x509:share" + +struct wssl_x509_share { + char *CAfile; /* CAfile path used to generate X509 store */ + WOLFSSL_X509_STORE *store; /* cached X509 store or NULL if none */ + struct curltime time; /* when the cached store was created */ +}; + +static void wssl_x509_share_free(void *key, size_t key_len, void *p) +{ + struct wssl_x509_share *share = p; + DEBUGASSERT(key_len == CURL_CSTRLEN(MPROTO_WSSL_X509_KEY)); + DEBUGASSERT(!memcmp(MPROTO_WSSL_X509_KEY, key, key_len)); + (void)key; + (void)key_len; + if(share->store) { + wolfSSL_X509_STORE_free(share->store); + } + curlx_free(share->CAfile); + curlx_free(share); +} + +static bool wssl_cached_x509_store_expired(struct Curl_easy *data, + const struct wssl_x509_share *mb) +{ + const struct ssl_general_config *cfg = &data->set.general_ssl; + timediff_t elapsed_ms = curlx_ptimediff_ms(Curl_pgrs_now(data), &mb->time); + timediff_t timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000; + + if(timeout_ms < 0) + return FALSE; + + return elapsed_ms >= timeout_ms; +} + +static bool wssl_cached_x509_store_different(struct Curl_cfilter *cf, + const struct wssl_x509_share *mb) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + if(!mb->CAfile || !conn_config->CAfile) + return mb->CAfile != conn_config->CAfile; + + return strcmp(mb->CAfile, conn_config->CAfile); +} + +static WOLFSSL_X509_STORE *wssl_get_cached_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct Curl_multi *multi = data->multi; + struct wssl_x509_share *share; + WOLFSSL_X509_STORE *store = NULL; + + DEBUGASSERT(multi); + share = multi ? Curl_hash_pick(&multi->proto_hash, + CURL_UNCONST(MPROTO_WSSL_X509_KEY), + CURL_CSTRLEN(MPROTO_WSSL_X509_KEY)) : NULL; + if(share && share->store && + !wssl_cached_x509_store_expired(data, share) && + !wssl_cached_x509_store_different(cf, share)) { + store = share->store; + } + + return store; +} + +static void wssl_set_cached_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + WOLFSSL_X509_STORE *store) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_multi *multi = data->multi; + struct wssl_x509_share *share; + + DEBUGASSERT(multi); + if(!multi) + return; + share = Curl_hash_pick(&multi->proto_hash, + CURL_UNCONST(MPROTO_WSSL_X509_KEY), + CURL_CSTRLEN(MPROTO_WSSL_X509_KEY)); + + if(!share) { + share = curlx_calloc(1, sizeof(*share)); + if(!share) + return; + if(!Curl_hash_add2(&multi->proto_hash, + CURL_UNCONST(MPROTO_WSSL_X509_KEY), + CURL_CSTRLEN(MPROTO_WSSL_X509_KEY), + share, wssl_x509_share_free)) { + curlx_free(share); + return; + } + } + + if(wolfSSL_X509_STORE_up_ref(store)) { + char *CAfile = NULL; + + if(conn_config->CAfile) { + CAfile = curlx_strdup(conn_config->CAfile); + if(!CAfile) { + wolfSSL_X509_STORE_free(store); + return; + } + } + + if(share->store) { + wolfSSL_X509_STORE_free(share->store); + curlx_free(share->CAfile); + } + + share->time = *Curl_pgrs_now(data); + share->store = store; + share->CAfile = CAfile; + } +} + +CURLcode Curl_wssl_setup_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct wssl_ctx *wssl) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + CURLcode result = CURLE_OK; + WOLFSSL_X509_STORE *cached_store; + bool cache_criteria_met; + + /* We do not want to do this again, no matter the outcome */ + wssl->x509_store_setup = TRUE; + + /* Consider the X509 store cacheable if it comes exclusively from a CAfile, + or no source is provided and we are falling back to wolfSSL's built-in + default. */ + cache_criteria_met = (data->set.general_ssl.ca_cache_timeout != 0) && + conn_config->verifypeer && + !conn_config->CApath && + !conn_config->ca_info_blob && + !ssl_config->primary.CRLfile && + !conn_config->native_ca_store; + + cached_store = cache_criteria_met ? wssl_get_cached_x509_store(cf, data) + : NULL; + if(cached_store && + wolfSSL_CTX_get_cert_store(wssl->ssl_ctx) == cached_store) { + /* The cached store is already in use, do nothing. */ + } + else if(cached_store && wolfSSL_X509_STORE_up_ref(cached_store)) { + wolfSSL_CTX_set_cert_store(wssl->ssl_ctx, cached_store); + } + else if(cache_criteria_met) { + /* wolfSSL's initial store in CTX is not shareable by default. + * Make a new one, suitable for adding to the cache. See #14278 */ + WOLFSSL_X509_STORE *store = wolfSSL_X509_STORE_new(); + if(!store) { + failf(data, "SSL: could not create a X509 store"); + return CURLE_OUT_OF_MEMORY; + } + wolfSSL_CTX_set_cert_store(wssl->ssl_ctx, store); + + result = wssl_populate_x509_store(cf, data, store, wssl); + if(!result) { + wssl_set_cached_x509_store(cf, data, store); + } + } + else { + /* We never share the CTX's store, use it. */ + WOLFSSL_X509_STORE *store = wolfSSL_CTX_get_cert_store(wssl->ssl_ctx); + result = wssl_populate_x509_store(cf, data, store, wssl); + } + + return result; +} + +#ifdef WOLFSSL_TLS13 +static CURLcode wssl_add_default_ciphers(bool tls13, struct dynbuf *buf) +{ + int i; + char *str; + + for(i = 0; (str = wolfSSL_get_cipher_list(i)) != NULL; i++) { + size_t n; + if((!strncmp(str, "TLS13", 5)) != tls13) + continue; + + /* if there already is data in the string, add colon separator */ + if(curlx_dyn_len(buf)) { + CURLcode result = curlx_dyn_addn(buf, ":", 1); + if(result) + return result; + } + + n = strlen(str); + if(curlx_dyn_addn(buf, str, n)) + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} +#endif + +#ifndef OPENSSL_EXTRA +static int wssl_legacy_CTX_set_min_proto_version(WOLFSSL_CTX *ctx, int version) +{ + int res; + switch(version) { + default: + case TLS1_VERSION: + res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1); + if(res == WOLFSSL_SUCCESS) + return res; + FALLTHROUGH(); + case TLS1_1_VERSION: + res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_1); + if(res == WOLFSSL_SUCCESS) + return res; + FALLTHROUGH(); + case TLS1_2_VERSION: + res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_2); +#ifdef WOLFSSL_TLS13 + if(res == WOLFSSL_SUCCESS) + return res; + FALLTHROUGH(); + case TLS1_3_VERSION: + res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_3); +#endif + } + return res; +} + +static int wssl_legacy_CTX_set_max_proto_version(WOLFSSL_CTX *ctx, int version) +{ + (void)ctx, (void)version; + return WOLFSSL_NOT_IMPLEMENTED; +} +#define wolfSSL_CTX_set_min_proto_version wssl_legacy_CTX_set_min_proto_version +#define wolfSSL_CTX_set_max_proto_version wssl_legacy_CTX_set_max_proto_version +#endif /* OPENSSL_EXTRA */ + +static CURLcode wssl_client_cert(struct Curl_easy *data, + struct ssl_config_data *ssl_config, + struct wssl_ctx *wctx) +{ + /* Load the client certificate, and private key */ +#ifndef NO_FILESYSTEM + if(ssl_config->primary.cert_blob || ssl_config->primary.clientcert) { + const char *cert_file = ssl_config->primary.clientcert; + const char *key_file = ssl_config->primary.key; + const struct curl_blob *cert_blob = ssl_config->primary.cert_blob; + const struct curl_blob *key_blob = ssl_config->primary.key_blob; + int file_type = wssl_do_file_type(ssl_config->primary.cert_type); + int rc; + + switch(file_type) { + case WOLFSSL_FILETYPE_PEM: + rc = cert_blob ? + wolfSSL_CTX_use_certificate_chain_buffer(wctx->ssl_ctx, + cert_blob->data, + (long)cert_blob->len) : + wolfSSL_CTX_use_certificate_chain_file(wctx->ssl_ctx, cert_file); + break; + case WOLFSSL_FILETYPE_ASN1: + rc = cert_blob ? + wolfSSL_CTX_use_certificate_buffer(wctx->ssl_ctx, cert_blob->data, + (long)cert_blob->len, file_type) : + wolfSSL_CTX_use_certificate_file(wctx->ssl_ctx, cert_file, file_type); + break; + default: + failf(data, "unknown cert type"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if(rc != 1) { + failf(data, "unable to use client certificate"); + return CURLE_SSL_CONNECT_ERROR; + } + + if(!key_blob && !key_file) { + key_blob = cert_blob; + key_file = cert_file; + } + else + file_type = wssl_do_file_type(ssl_config->primary.key_type); + + rc = key_blob ? + wolfSSL_CTX_use_PrivateKey_buffer(wctx->ssl_ctx, key_blob->data, + (long)key_blob->len, file_type) : + wolfSSL_CTX_use_PrivateKey_file(wctx->ssl_ctx, key_file, file_type); + if(rc != 1) { + failf(data, "unable to set private key"); + return CURLE_SSL_CONNECT_ERROR; + } + } +#else /* NO_FILESYSTEM */ + if(ssl_config->primary.cert_blob) { + const struct curl_blob *cert_blob = ssl_config->primary.cert_blob; + const struct curl_blob *key_blob = ssl_config->primary.key_blob; + int file_type = wssl_do_file_type(ssl_config->primary.cert_type); + int rc; + + switch(file_type) { + case WOLFSSL_FILETYPE_PEM: + rc = wolfSSL_CTX_use_certificate_chain_buffer(wctx->ssl_ctx, + cert_blob->data, + (long)cert_blob->len); + break; + case WOLFSSL_FILETYPE_ASN1: + rc = wolfSSL_CTX_use_certificate_buffer(wctx->ssl_ctx, cert_blob->data, + (long)cert_blob->len, file_type); + break; + default: + failf(data, "unknown cert type"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if(rc != 1) { + failf(data, "unable to use client certificate"); + return CURLE_SSL_CONNECT_ERROR; + } + + if(!key_blob) + key_blob = cert_blob; + else + file_type = wssl_do_file_type(ssl_config->primary.key_type); + + if(wolfSSL_CTX_use_PrivateKey_buffer(wctx->ssl_ctx, key_blob->data, + (long)key_blob->len, + file_type) != 1) { + failf(data, "unable to set private key"); + return CURLE_SSL_CONNECT_ERROR; + } + } +#endif /* !NO_FILESYSTEM */ + return CURLE_OK; +} + +static CURLcode ssl_version(struct Curl_easy *data, + struct ssl_primary_config *conn_config, + struct wssl_ctx *wctx, + int *min_version, int *max_version) +{ + int res; + *min_version = *max_version = 0; + DEBUGASSERT(conn_config->version != CURL_SSLVERSION_DEFAULT); + + switch(conn_config->version) { + case CURL_SSLVERSION_TLSv1: + case CURL_SSLVERSION_TLSv1_0: + *min_version = TLS1_VERSION; + break; + case CURL_SSLVERSION_TLSv1_1: + *min_version = TLS1_1_VERSION; + break; + case CURL_SSLVERSION_TLSv1_2: + *min_version = TLS1_2_VERSION; + break; +#ifdef WOLFSSL_TLS13 + case CURL_SSLVERSION_TLSv1_3: + *min_version = TLS1_3_VERSION; + break; +#endif + default: + failf(data, "wolfSSL: unsupported minimum TLS version value"); + return CURLE_SSL_CONNECT_ERROR; + } + + switch(conn_config->version_max) { +#ifdef WOLFSSL_TLS13 + case CURL_SSLVERSION_MAX_TLSv1_3: + *max_version = TLS1_3_VERSION; + break; +#endif + case CURL_SSLVERSION_MAX_TLSv1_2: + *max_version = TLS1_2_VERSION; + break; + case CURL_SSLVERSION_MAX_TLSv1_1: + *max_version = TLS1_1_VERSION; + break; + case CURL_SSLVERSION_MAX_TLSv1_0: + *max_version = TLS1_VERSION; + break; + case CURL_SSLVERSION_MAX_DEFAULT: + case CURL_SSLVERSION_MAX_NONE: + break; + default: + failf(data, "wolfSSL: unsupported maximum TLS version value"); + return CURLE_SSL_CONNECT_ERROR; + } + + res = wolfSSL_CTX_set_min_proto_version(wctx->ssl_ctx, *min_version); + if(res != WOLFSSL_SUCCESS) { + failf(data, "wolfSSL: failed set the minimum TLS version"); + return CURLE_SSL_CONNECT_ERROR; + } + + if(*max_version) { + res = wolfSSL_CTX_set_max_proto_version(wctx->ssl_ctx, *max_version); + if(res != WOLFSSL_SUCCESS) { + failf(data, "wolfSSL: failed set the maximum TLS version"); + return CURLE_SSL_CONNECT_ERROR; + } + } + return CURLE_OK; +} + +#ifdef WOLFSSL_TLS13 +#define MAX_CIPHER_LEN 4096 +#endif + +static CURLcode wssl_init_ciphers(struct Curl_easy *data, + struct wssl_ctx *wctx, + struct ssl_primary_config *conn_config, + int tls_min, int tls_max) +{ +#ifndef WOLFSSL_TLS13 + const char *ciphers = conn_config->cipher_list; + (void)tls_min; + (void)tls_max; + if(ciphers) { + if(!SSL_CTX_set_cipher_list(wctx->ssl_ctx, ciphers)) { + failf(data, "failed setting cipher list: %s", ciphers); + return CURLE_SSL_CIPHER; + } + infof(data, "Cipher selection: %s", ciphers); + } + return CURLE_OK; +#else + CURLcode result = CURLE_OK; + if(conn_config->cipher_list || conn_config->cipher_list13) { + const char *ciphers12 = conn_config->cipher_list; + const char *ciphers13 = conn_config->cipher_list13; + struct dynbuf c; + curlx_dyn_init(&c, MAX_CIPHER_LEN); + + if(!tls_max || (tls_max >= TLS1_3_VERSION)) { + if(ciphers13) + result = curlx_dyn_add(&c, ciphers13); + else + result = wssl_add_default_ciphers(TRUE, &c); + } + + if(!result && (tls_min < TLS1_3_VERSION)) { + if(ciphers12) { + if(curlx_dyn_len(&c)) + result = curlx_dyn_addn(&c, ":", 1); + if(!result) + result = curlx_dyn_add(&c, ciphers12); + } + else + result = wssl_add_default_ciphers(FALSE, &c); + } + if(!result) { + if(!wolfSSL_CTX_set_cipher_list(wctx->ssl_ctx, curlx_dyn_ptr(&c))) { + failf(data, "failed setting cipher list: %s", curlx_dyn_ptr(&c)); + result = CURLE_SSL_CIPHER; + } + else + infof(data, "Cipher selection: %s", curlx_dyn_ptr(&c)); + } + curlx_dyn_free(&c); + } + return result; +#endif +} + +/* wolfSSL_CTX_set1_groups_list() accepts PQC/hybrid groups (e.g. + X25519MLKEM768) that wolfSSL_CTX_set1_curves_list() rejects. It needs + OPENSSL_EXTRA, which wolfSSL's --enable-curl sets but --enable-curl=tiny + does not. */ +#ifdef OPENSSL_EXTRA +#define wssl_CTX_set1_groups_list wolfSSL_CTX_set1_groups_list +#else +#define wssl_CTX_set1_groups_list wolfSSL_CTX_set1_curves_list +#endif + +static CURLcode wssl_init_curves(struct Curl_easy *data, + struct wssl_ctx *wctx, + struct ssl_primary_config *conn_config) +{ + char *curves = conn_config->curves; + /* Without an explicit list, leave the key share group selection to + wolfSSL's own default. */ + if(curves && !wssl_CTX_set1_groups_list(wctx->ssl_ctx, curves)) { + failf(data, "failed setting curves list: '%s'", curves); + return CURLE_SSL_CIPHER; + } + return CURLE_OK; +} + +static CURLcode wssl_init_ssl_handle( + struct wssl_ctx *wctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + struct alpn_spec *alpns, + void *ssl_user_data, + unsigned char transport, + Curl_wssl_init_session_reuse_cb *sess_reuse_cb) +{ + struct Curl_ssl_session *scs = NULL; + bool session_applied = FALSE; + + /* Let's make an SSL structure */ + wctx->ssl = wolfSSL_new(wctx->ssl_ctx); + if(!wctx->ssl) { + failf(data, "SSL: could not create a handle"); + return CURLE_OUT_OF_MEMORY; + } + +#ifdef HAVE_EX_DATA + wolfSSL_set_app_data(wctx->ssl, ssl_user_data); +#else + (void)ssl_user_data; +#endif +#ifdef WOLFSSL_QUIC + if(transport == TRNSPRT_QUIC) + wolfSSL_set_quic_use_legacy_codepoint(wctx->ssl, 0); +#else + (void)transport; +#endif + + if((cf->sockindex == SECONDARYSOCKET) && !(cf->cft->flags & CF_TYPE_PROXY)) { + /* FTP is a bitch. On TLS secured transfers, it is a common server + * option to require the client to use the SAME TLS session as on + * the control connection or it fails the request. See #22225. */ + scs = Curl_ssl_get_cf_session(data, cf->cft, FIRSTSOCKET); + if(scs) { + session_applied = wssl_apply_session(cf, data, wctx, alpns, + sess_reuse_cb, scs); + if(session_applied) + CURL_TRC_CF(data, cf, "applied SSL session from control connection"); + scs = NULL; + } + } + + /* Check if there is a cached ID we can/should use here! */ + if(!session_applied && Curl_ssl_scache_use(cf, data)) { + /* Set session from cache if there is one */ + CURLcode result = Curl_ssl_scache_take(cf, data, peer->scache_key, &scs); + if(!result && scs) { + if(wssl_apply_session(cf, data, wctx, alpns, sess_reuse_cb, scs)) + Curl_ssl_scache_return(cf, data, peer->scache_key, scs); + else + Curl_ssl_session_destroy(scs); + } + } + +#ifdef HAVE_ALPN + if(alpns->count) { + struct alpn_proto_buf proto; + memset(&proto, 0, sizeof(proto)); + Curl_alpn_to_proto_str(&proto, alpns); + + if(wolfSSL_UseALPN(wctx->ssl, (char *)proto.data, + (unsigned int)proto.len, + WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) + != WOLFSSL_SUCCESS) { + failf(data, "SSL: failed setting ALPN protocols"); + return CURLE_SSL_CONNECT_ERROR; + } + CURL_TRC_CF(data, cf, "set ALPN: %s", proto.data); + } +#endif /* HAVE_ALPN */ + +#ifdef OPENSSL_EXTRA + if(Curl_tls_keylog_enabled()) { + /* Ensure the Client Random is preserved. */ + wolfSSL_KeepArrays(wctx->ssl); +#if defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13) + wolfSSL_set_tls13_secret_cb(wctx->ssl, wssl_tls13_secret_callback, NULL); +#endif + } +#endif /* OPENSSL_EXTRA */ + +#ifdef HAVE_SECURE_RENEGOTIATION + if(wolfSSL_UseSecureRenegotiation(wctx->ssl) != SSL_SUCCESS) { + failf(data, "SSL: failed setting secure renegotiation"); + return CURLE_SSL_CONNECT_ERROR; + } +#endif /* HAVE_SECURE_RENEGOTIATION */ + + return CURLE_OK; +} + +#ifdef HAVE_WOLFSSL_CTX_GENERATEECHCONFIG +static CURLcode wssl_init_ech(struct wssl_ctx *wctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer) +{ + int trying_ech_now = 0; + + if(CURL_EASY_STR(data, STRING_ECH_PUBLIC)) { + infof(data, "ECH: outername not (yet) supported" + " with wolfSSL"); + return CURLE_SSL_CONNECT_ERROR; + } + if(data->set.tls_ech == CURLECH_GREASE) { + infof(data, "ECH: GREASE is done by default by" + " wolfSSL: no need to ask"); + } + if(data->set.tls_ech && CURL_EASY_STR(data, STRING_ECH_CONFIG)) { + const char *b64val = CURL_EASY_STR(data, STRING_ECH_CONFIG); + word32 b64len = 0; + + b64len = (word32)strlen(b64val); + if(b64len && wolfSSL_SetEchConfigsBase64(wctx->ssl, CURL_UNCONST(b64val), + b64len) != WOLFSSL_SUCCESS) { + if(data->set.tls_ech == CURLECH_HARD) + return CURLE_SSL_CONNECT_ERROR; + } + else { + trying_ech_now = 1; + infof(data, "ECH: ECHConfig from command line"); + } + } + else { + const struct Curl_https_rrinfo *rinfo = + Curl_conn_dns_get_https(data, cf->sockindex, peer->origin); + + if(rinfo && rinfo->echconfiglist) { + const unsigned char *ecl = rinfo->echconfiglist; + size_t elen = rinfo->echconfiglist_len; + + infof(data, "ECH: ECHConfig from HTTPS RR"); + if(wolfSSL_SetEchConfigs(wctx->ssl, ecl, (word32)elen) != + WOLFSSL_SUCCESS) { + infof(data, "ECH: wolfSSL_SetEchConfigs failed"); + if(data->set.tls_ech == CURLECH_HARD) { + return CURLE_SSL_CONNECT_ERROR; + } + } + else { + trying_ech_now = 1; + infof(data, "ECH: imported ECHConfigList of length %zu", elen); + } + } + else { + infof(data, "ECH: requested but no ECHConfig available"); + if(data->set.tls_ech == CURLECH_HARD) { + return CURLE_SSL_CONNECT_ERROR; + } + } + } + + if(trying_ech_now && + wolfSSL_set_min_proto_version(wctx->ssl, TLS1_3_VERSION) != 1) { + infof(data, "ECH: cannot force TLSv1.3 [ERROR]"); + return CURLE_SSL_CONNECT_ERROR; + } + return CURLE_OK; +} +#endif /* HAVE_WOLFSSL_CTX_GENERATEECHCONFIG */ + +CURLcode Curl_wssl_ctx_init(struct wssl_ctx *wctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + const struct alpn_spec *alpns_requested, + Curl_wssl_ctx_setup_cb *cb_setup, + void *cb_user_data, + void *ssl_user_data, + Curl_wssl_init_session_reuse_cb *sess_reuse_cb) +{ + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + struct ssl_primary_config *conn_config; + WOLFSSL_METHOD *req_method = NULL; + struct alpn_spec alpns; + CURLcode result = CURLE_FAILED_INIT; + unsigned char transport; + int tls_min, tls_max; + + DEBUGASSERT(!wctx->ssl_ctx); + DEBUGASSERT(!wctx->ssl); + conn_config = Curl_ssl_cf_get_primary_config(cf); + if(!conn_config) { + result = CURLE_FAILED_INIT; + goto out; + } + Curl_alpn_copy(&alpns, alpns_requested); + DEBUGASSERT(cf->next); + transport = Curl_conn_cf_get_transport(cf->next, data); + + req_method = wolfTLS_client_method(); + if(!req_method) { + failf(data, "wolfSSL: could not create a client method"); + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + if(wctx->ssl_ctx) + wolfSSL_CTX_free(wctx->ssl_ctx); + + wctx->ssl_ctx = wolfSSL_CTX_new(req_method); + if(!wctx->ssl_ctx) { + failf(data, "wolfSSL: could not create a context"); + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + result = ssl_version(data, conn_config, wctx, &tls_min, &tls_max); + if(result) + goto out; + + result = wssl_init_ciphers(data, wctx, conn_config, tls_min, tls_max); + if(result) + goto out; + + result = wssl_init_curves(data, wctx, conn_config); + if(result) + goto out; + + result = wssl_client_cert(data, ssl_config, wctx); + if(result) + goto out; + + /* SSL always tries to verify the peer, this only says whether it should + * fail to connect if the verification fails, or if it should continue + * anyway. In the latter case the result of the verification is checked with + * SSL_get_verify_result() below. */ + wolfSSL_CTX_set_verify(wctx->ssl_ctx, conn_config->verifypeer ? + WOLFSSL_VERIFY_PEER : WOLFSSL_VERIFY_NONE, NULL); + +#ifdef HAVE_SNI + if(peer->sni) { + size_t sni_len = strlen(peer->sni); + if((sni_len < USHRT_MAX)) { + if(wolfSSL_CTX_UseSNI(wctx->ssl_ctx, WOLFSSL_SNI_HOST_NAME, + peer->sni, (unsigned short)sni_len) != 1) { + failf(data, "Failed to set SNI"); + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + CURL_TRC_CF(data, cf, "set SNI '%s'", peer->sni); + } + } +#endif + +#ifdef HAVE_EX_DATA + if(Curl_ssl_scache_use(cf, data) && (transport != TRNSPRT_QUIC)) { + /* Register to get notified when a new session is received */ + wolfSSL_CTX_sess_set_new_cb(wctx->ssl_ctx, wssl_vtls_new_session_cb); + } +#endif + + if(cb_setup) { + result = cb_setup(cf, data, cb_user_data); + if(result) + goto out; + } + + /* give application a chance to interfere with SSL set up. */ + if(data->set.ssl.fsslctx) { + if(!wctx->x509_store_setup) { + result = Curl_wssl_setup_x509_store(cf, data, wctx); + if(result) + goto out; + } + result = (*data->set.ssl.fsslctx)(data, wctx->ssl_ctx, + data->set.ssl.fsslctxp); + if(result) { + failf(data, "error signaled by SSL ctx callback"); + goto out; + } + } +#ifdef NO_FILESYSTEM + else if(conn_config->verifypeer) { + failf(data, "SSL: Certificates cannot be loaded because wolfSSL was built" + " with no file system. Either disable peer verification" + " (insecure) or if you are building an application with libcurl you" + " can load certificates via CURLOPT_SSL_CTX_FUNCTION."); + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } +#endif + + result = wssl_init_ssl_handle(wctx, cf, data, peer, &alpns, ssl_user_data, + transport, sess_reuse_cb); + if(result) + goto out; + +#ifdef HAVE_WOLFSSL_CTX_GENERATEECHCONFIG + if(CURLECH_ENABLED(data)) { + result = wssl_init_ech(wctx, cf, data, peer); + if(result) + goto out; + } +#endif /* HAVE_WOLFSSL_CTX_GENERATEECHCONFIG */ + + result = CURLE_OK; + +out: + if(result && wctx->ssl) { + wolfSSL_free(wctx->ssl); + wctx->ssl = NULL; + } + if(result && wctx->ssl_ctx) { + wolfSSL_CTX_free(wctx->ssl_ctx); + wctx->ssl_ctx = NULL; + } + return result; +} + +bool Curl_wssl_need_httpsrr(struct Curl_easy *data) +{ +#ifdef HAVE_WOLFSSL_CTX_GENERATEECHCONFIG + if(!CURLECH_ENABLED(data)) + return FALSE; + if((data->set.tls_ech == CURLECH_GREASE) || + CURL_EASY_STR(data, STRING_ECH_CONFIG)) + return FALSE; + return TRUE; +#else + (void)data; + return FALSE; +#endif +} + +/* + * This function loads all the client/CA certificates and CRLs. Setup the TLS + * layer and do all necessary magic. + */ +static CURLcode wssl_connect_step1(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + CURLcode result; + + DEBUGASSERT(wssl); + + if(connssl->state == ssl_connection_complete) + return CURLE_OK; + + result = Curl_wssl_ctx_init(wssl, cf, data, &connssl->peer, connssl->alpn, + NULL, NULL, cf, wssl_on_session_reuse); + if(result) + return result; + +#ifdef HAVE_ALPN + if(connssl->alpn && (connssl->state != ssl_connection_deferred)) { + struct alpn_proto_buf proto; + memset(&proto, 0, sizeof(proto)); + Curl_alpn_to_proto_str(&proto, connssl->alpn); + infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); + } +#endif + + /* Enable RFC2818 checks on domain names. This cannot check + * IP addresses which we need to do extra after the handshake. */ + if(conn_config->verifyhost && connssl->peer.sni) { + if(wolfSSL_check_domain_name(wssl->ssl, connssl->peer.sni) != + WOLFSSL_SUCCESS) { + return CURLE_SSL_CONNECT_ERROR; + } + } + +#ifdef USE_BIO_CHAIN + { + WOLFSSL_BIO *bio; + + if(!wssl_bio_cf_method) + return CURLE_FAILED_INIT; + bio = wolfSSL_BIO_new(wssl_bio_cf_method); + if(!bio) + return CURLE_OUT_OF_MEMORY; + + wolfSSL_BIO_set_data(bio, cf); + wolfSSL_set_bio(wssl->ssl, bio, bio); + } +#else /* !USE_BIO_CHAIN */ + { + curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data); + if(sockfd > INT_MAX) { + failf(data, "SSL: socket value too large"); + return CURLE_SSL_CONNECT_ERROR; + } + /* pass the raw socket into the SSL layer */ + if(!wolfSSL_set_fd(wssl->ssl, (int)sockfd)) { + failf(data, "SSL: wolfSSL_set_fd failed"); + return CURLE_SSL_CONNECT_ERROR; + } + } +#endif /* USE_BIO_CHAIN */ + + return CURLE_OK; +} + +static char *wssl_strerror(unsigned long error, char *buf, unsigned long size) +{ + DEBUGASSERT(size > 40); + *buf = '\0'; + + wolfSSL_ERR_error_string_n(error, buf, size); + + if(!*buf) { + const char *msg = error ? "Unknown error" : "No error"; + curlx_strcopy(buf, size, msg, strlen(msg)); + } + + return buf; +} + +CURLcode Curl_wssl_verify_pinned(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct wssl_ctx *wssl) +{ + WOLFSSL_X509 *x509 = NULL; + CURLcode result = CURLE_OK; +#ifndef CURL_DISABLE_PROXY + const char * const pinnedpubkey = Curl_ssl_cf_is_proxy(cf) ? + CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY_PROXY) : + CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY); +#else + const char * const pinnedpubkey = + CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY); + (void)cf; +#endif + + if(pinnedpubkey) { +#ifdef KEEP_PEER_CERT + const char *x509_der; + int x509_der_len; + struct Curl_X509certificate x509_parsed; + struct Curl_asn1Element *pubkey; + + result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; + + x509 = wolfSSL_get_peer_certificate(wssl->ssl); + if(!x509) { + failf(data, "SSL: failed retrieving server certificate"); + goto end; + } + + x509_der = (const char *)wolfSSL_X509_get_der(x509, &x509_der_len); + if(!x509_der) { + failf(data, "SSL: failed retrieving ASN.1 server certificate"); + goto end; + } + + memset(&x509_parsed, 0, sizeof(x509_parsed)); + if(Curl_parseX509(&x509_parsed, x509_der, x509_der + x509_der_len)) + goto end; + + pubkey = &x509_parsed.subjectPublicKeyInfo; + if(!pubkey->header || pubkey->end <= pubkey->header) { + failf(data, "SSL: failed retrieving public key from server certificate"); + goto end; + } + + result = Curl_pin_peer_pubkey(data, pinnedpubkey, + (const unsigned char *)pubkey->header, + (size_t)(pubkey->end - pubkey->header)); + if(result) + failf(data, "SSL: public key does not match pinned public key"); +#else + failf(data, "Library lacks pinning support built-in"); + return CURLE_NOT_BUILT_IN; +#endif + } +end: + wolfSSL_FreeX509(x509); + return result; +} + +#ifdef WOLFSSL_EARLY_DATA +static CURLcode wssl_send_earlydata(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend; + const unsigned char *buf; + size_t blen; + + DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sending); + wssl->io_result = CURLE_OK; + while(Curl_bufq_peek(&connssl->earlydata, &buf, &blen)) { + int nwritten = 0, rc; + + wolfSSL_ERR_clear_error(); + rc = wolfSSL_write_early_data(wssl->ssl, buf, (int)blen, &nwritten); + CURL_TRC_CF(data, cf, "wolfSSL_write_early_data(len=%zu) -> %d, %d", + blen, rc, nwritten); + if(rc < 0) { + int err = wolfSSL_get_error(wssl->ssl, rc); + char error_buffer[256]; + switch(err) { + case WOLFSSL_ERROR_NONE: /* did not get anything */ + case WOLFSSL_ERROR_WANT_READ: + case WOLFSSL_ERROR_WANT_WRITE: + return CURLE_AGAIN; + } + CURL_TRC_CF(data, cf, "SSL send early data, error: '%s'(%d)", + wssl_strerror((unsigned long)err, error_buffer, + sizeof(error_buffer)), err); + return CURLE_SEND_ERROR; + } + + Curl_bufq_skip(&connssl->earlydata, (size_t)nwritten); + } + /* sent everything there was */ + connssl->earlydata_state = ssl_earlydata_sent; + if(!Curl_ssl_cf_is_proxy(cf)) + Curl_pgrsEarlyData(data, (curl_off_t)connssl->earlydata_skip); + infof(data, "SSL sending %zu bytes of early data", connssl->earlydata_skip); + return CURLE_OK; +} +#endif /* WOLFSSL_EARLY_DATA */ + +static CURLcode wssl_handshake(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + int ret = -1, detail; + CURLcode result; + + DEBUGASSERT(wssl); + connssl->io_need = CURL_SSL_IO_NEED_NONE; + +#ifdef WOLFSSL_EARLY_DATA + if(connssl->earlydata_state == ssl_earlydata_sending) { + result = wssl_send_earlydata(cf, data); + if(result) + return result; + } + DEBUGASSERT((connssl->earlydata_state == ssl_earlydata_none) || + (connssl->earlydata_state == ssl_earlydata_sent)); +#else + DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_none); +#endif /* WOLFSSL_EARLY_DATA */ + + wolfSSL_ERR_clear_error(); + ret = wolfSSL_connect(wssl->ssl); + + if(!wssl->x509_store_setup) { + /* After having send off the ClientHello, we prepare the x509 + * store to verify the coming certificate from the server */ + result = Curl_wssl_setup_x509_store(cf, data, wssl); + if(result) { + CURL_TRC_CF(data, cf, "Curl_wssl_setup_x509_store() -> %d", (int)result); + return result; + } + } + +#ifdef OPENSSL_EXTRA + if(Curl_tls_keylog_enabled()) { + /* If key logging is enabled, wait for the handshake to complete and then + * proceed with logging secrets (for TLS 1.2 or older). + * + * During the handshake (ret==-1), wolfSSL_want_read() is true as it waits + * for the server response. At that point the master secret is not yet + * available, so we must not try to read it. + * To log the secret on completion with a handshake failure, detect + * completion via the observation that there is nothing to read or write. + * Note that OpenSSL SSL_want_read() is always true here. If wolfSSL ever + * changes, the worst case is that no key is logged on error. + */ + if(ret == WOLFSSL_SUCCESS || + (!wolfSSL_want_read(wssl->ssl) && + !wolfSSL_want_write(wssl->ssl))) { + wssl_log_tls12_secret(wssl->ssl); + /* Client Random and master secrets are no longer needed, erase these. + * Ignored while the handshake is still in progress. */ + wolfSSL_FreeArrays(wssl->ssl); + } + } +#endif /* OPENSSL_EXTRA */ + + detail = wolfSSL_get_error(wssl->ssl, ret); + CURL_TRC_CF(data, cf, "wolfSSL_connect() -> %d, detail=%d", ret, detail); + + /* On a successful handshake with an IP address, do an extra check + * on the peer certificate */ + if(ret == WOLFSSL_SUCCESS && + conn_config->verifyhost && + !connssl->peer.sni) { + /* we have an IP address as hostname. */ + WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wssl->ssl); + if(!cert) { + failf(data, "unable to get peer certificate"); + return CURLE_PEER_FAILED_VERIFICATION; + } + ret = wolfSSL_X509_check_ip_asc(cert, connssl->peer.origin->hostname, 0); + CURL_TRC_CF(data, cf, "check peer certificate for IP match on %s -> %d", + connssl->peer.origin->hostname, ret); + if(ret != WOLFSSL_SUCCESS) + detail = DOMAIN_NAME_MISMATCH; + wolfSSL_X509_free(cert); + } + + if(ret == WOLFSSL_SUCCESS) { + return CURLE_OK; + } + else { + if(detail == WOLFSSL_ERROR_WANT_READ) { + connssl->io_need = CURL_SSL_IO_NEED_RECV; + return CURLE_AGAIN; + } + else if(detail == WOLFSSL_ERROR_WANT_WRITE) { + connssl->io_need = CURL_SSL_IO_NEED_SEND; + return CURLE_AGAIN; + } + else if(detail == DOMAIN_NAME_MISMATCH) { + /* There is no easy way to override only the CN matching. + * This enables the override of both mismatching SubjectAltNames + * as also mismatching CN fields */ + failf(data, " subject alt name(s) or common name do not match \"%s\"", + connssl->peer.origin->hostname); + return CURLE_PEER_FAILED_VERIFICATION; + } + else if(detail == ASN_NO_SIGNER_E) { + if(conn_config->verifypeer) { + failf(data, " CA signer not available for verification"); + return CURLE_SSL_CACERT_BADFILE; + } + /* Continue with a warning if no strict certificate + verification is required. */ + infof(data, "CA signer not available for verification, " + "continuing anyway"); + return CURLE_OK; + } + else if(detail == ASN_AFTER_DATE_E) { + failf(data, "server verification failed: certificate has expired."); + return CURLE_PEER_FAILED_VERIFICATION; + } + else if(detail == ASN_BEFORE_DATE_E) { + failf(data, "server verification failed: certificate not valid yet."); + return CURLE_PEER_FAILED_VERIFICATION; + } + else if(wssl->io_result) { + switch(wssl->io_result) { + case CURLE_SEND_ERROR: + case CURLE_RECV_ERROR: + return CURLE_SSL_CONNECT_ERROR; + default: + return wssl->io_result; + } + } +#ifdef HAVE_WOLFSSL_CTX_GENERATEECHCONFIG + else if(detail == -1) { + /* try access a retry_config ECHConfigList for tracing */ + byte echConfigs[1000]; + word32 echConfigsLen = 1000; + int rv = 0; + + /* this currently does not produce the retry_configs */ + rv = wolfSSL_GetEchConfigs(wssl->ssl, echConfigs, &echConfigsLen); + if(rv != WOLFSSL_SUCCESS) { + infof(data, "Failed to get ECHConfigs"); + } + else { + char *b64str = NULL; + size_t blen = 0; + + result = curlx_base64_encode(echConfigs, echConfigsLen, + &b64str, &blen); + if(!result && b64str) + infof(data, "ECH: (not yet) retry_configs %s", b64str); + curlx_free(b64str); + } + return CURLE_SSL_CONNECT_ERROR; + } +#endif + else { + char error_buffer[256]; + failf(data, "SSL_connect failed with error %d: %s", detail, + wssl_strerror((unsigned long)detail, error_buffer, + sizeof(error_buffer))); + return CURLE_SSL_CONNECT_ERROR; + } + } +} + +static CURLcode wssl_send(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *buf, size_t blen, + size_t *pnwritten) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend; + CURLcode result = CURLE_OK; + int nwritten; + + DEBUGASSERT(wssl); + *pnwritten = 0; + wolfSSL_ERR_clear_error(); + + if(blen) { + int memlen = (blen > (size_t)INT_MAX) ? INT_MAX : (int)blen; + + nwritten = wolfSSL_write(wssl->ssl, buf, memlen); + + if(nwritten > 0) + *pnwritten += (size_t)nwritten; + else { + int err = wolfSSL_get_error(wssl->ssl, nwritten); + + switch(err) { + case WOLFSSL_ERROR_WANT_READ: + case WOLFSSL_ERROR_WANT_WRITE: + /* there is data pending, re-invoke wolfSSL_write() */ + if(*pnwritten) { + result = CURLE_OK; + goto out; + } + result = CURLE_AGAIN; + goto out; + + default: + if(wssl->io_result == CURLE_AGAIN) { + if(*pnwritten) { + result = CURLE_OK; + goto out; + } + result = CURLE_AGAIN; + goto out; + } + { + char error_buffer[256]; + failf(data, "SSL write: %s, errno %d", + wssl_strerror((unsigned long)err, error_buffer, + sizeof(error_buffer)), + SOCKERRNO); + } + result = CURLE_SEND_ERROR; + goto out; + } + } + } + +out: + CURL_TRC_CF(data, cf, "wssl_send(len=%zu) -> %d, %zu", + blen, (int)result, *pnwritten); + return result; +} + +static CURLcode wssl_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct wssl_ctx *wctx = (struct wssl_ctx *)connssl->backend; + CURLcode result = CURLE_OK; + char buf[1024]; + int nread = -1, err; + size_t i; + VERBOSE(char error_buffer[256]); + + DEBUGASSERT(wctx); + if(!wctx->ssl || cf->shutdown) { + *done = TRUE; + goto out; + } + + wctx->shutting_down = TRUE; + connssl->io_need = CURL_SSL_IO_NEED_NONE; + *done = FALSE; + if(!(wolfSSL_get_shutdown(wctx->ssl) & WOLFSSL_SENT_SHUTDOWN)) { + /* We have not started the shutdown from our side yet. Check + * if the server already sent us one. */ + wolfSSL_ERR_clear_error(); + nread = wolfSSL_read(wctx->ssl, buf, (int)sizeof(buf)); + err = wolfSSL_get_error(wctx->ssl, nread); + CURL_TRC_CF(data, cf, "wolfSSL_read, nread=%d, err=%d", nread, err); + if(!nread && err == WOLFSSL_ERROR_ZERO_RETURN) { + bool input_pending; + /* Yes, it did. */ + if(!send_shutdown) { + CURL_TRC_CF(data, cf, "SSL shutdown received, not sending"); + *done = TRUE; + goto out; + } + else if(!cf->next->cft->is_alive(cf->next, data, &input_pending)) { + /* Server closed the connection after its closy notify. It + * seems not interested to see our close notify, so do not + * send it. We are done. */ + CURL_TRC_CF(data, cf, "peer closed connection"); + connssl->peer_closed = TRUE; + *done = TRUE; + goto out; + } + } + } + + /* wolfSSL should now have started the shutdown from our side. Since it + * was not complete, we are lacking the close notify from the server. */ + if(send_shutdown) { + wolfSSL_ERR_clear_error(); + nread = wolfSSL_shutdown(wctx->ssl); + if(nread == 1) { + CURL_TRC_CF(data, cf, "SSL shutdown finished"); + *done = TRUE; + goto out; + } + if(wolfSSL_get_error(wctx->ssl, nread) == WOLFSSL_ERROR_WANT_WRITE) { + CURL_TRC_CF(data, cf, "SSL shutdown still wants to send"); + connssl->io_need = CURL_SSL_IO_NEED_SEND; + goto out; + } + /* Having sent the close notify, we use wolfSSL_read() to get the + * missing close notify from the server. */ + } + + for(i = 0; i < 10; ++i) { + wolfSSL_ERR_clear_error(); + nread = wolfSSL_read(wctx->ssl, buf, (int)sizeof(buf)); + if(nread <= 0) + break; + } + err = wolfSSL_get_error(wctx->ssl, nread); + switch(err) { + case WOLFSSL_ERROR_ZERO_RETURN: /* no more data */ + CURL_TRC_CF(data, cf, "SSL shutdown received"); + *done = TRUE; + break; + case WOLFSSL_ERROR_NONE: /* did not get anything */ + case WOLFSSL_ERROR_WANT_READ: + /* wolfSSL has sent its notify and now wants to read the reply + * from the server. We are not really interested in that. */ + CURL_TRC_CF(data, cf, "SSL shutdown sent, want receive"); + connssl->io_need = CURL_SSL_IO_NEED_RECV; + break; + case WOLFSSL_ERROR_WANT_WRITE: + CURL_TRC_CF(data, cf, "SSL shutdown send blocked"); + connssl->io_need = CURL_SSL_IO_NEED_SEND; + break; + default: + CURL_TRC_CF(data, cf, "SSL shutdown, error: '%s'(%d)", + wssl_strerror((unsigned long)err, error_buffer, + sizeof(error_buffer)), + err); + result = CURLE_RECV_ERROR; + break; + } + +out: + cf->shutdown = (result || *done); + return result; +} + +static void wssl_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend; + + (void)data; + + DEBUGASSERT(wssl); + + if(wssl->ssl) { + wolfSSL_free(wssl->ssl); + wssl->ssl = NULL; + } + if(wssl->ssl_ctx) { + wolfSSL_CTX_free(wssl->ssl_ctx); + wssl->ssl_ctx = NULL; + } +} + +static CURLcode wssl_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, size_t blen, + size_t *pnread) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend; + int buffsize = (blen > (size_t)INT_MAX) ? INT_MAX : (int)blen; + int nread; + + DEBUGASSERT(wssl); + + *pnread = 0; + wolfSSL_ERR_clear_error(); + + nread = wolfSSL_read(wssl->ssl, buf, buffsize); + + if(nread > 0) + *pnread = (size_t)nread; + else { + int err = wolfSSL_get_error(wssl->ssl, nread); + + switch(err) { + case WOLFSSL_ERROR_ZERO_RETURN: /* no more data */ + CURL_TRC_CF(data, cf, "wssl_recv(len=%zu) -> CLOSED", blen); + return CURLE_OK; + case WOLFSSL_ERROR_NONE: + case WOLFSSL_ERROR_WANT_READ: + case WOLFSSL_ERROR_WANT_WRITE: + if(!wssl->io_result && !connssl->peer_closed) { + /* there is data pending, re-invoke wolfSSL_read() */ + CURL_TRC_CF(data, cf, "wssl_recv(len=%zu) -> AGAIN", blen); + return CURLE_AGAIN; + } + /* fall through to default error handling below */ + FALLTHROUGH(); + default: + if(wssl->io_result == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "wssl_recv(len=%zu) -> AGAIN", blen); + return CURLE_AGAIN; + } + else if(!wssl->io_result && connssl->peer_closed) { + CURL_TRC_CF(data, cf, "wssl_recv(len=%zu) -> CLOSED", blen); + failf(data, "Connection closed abruptly"); + } + else { + char error_buffer[256]; + failf(data, "SSL read: %s, errno %d", + wssl_strerror((unsigned long)err, error_buffer, + sizeof(error_buffer)), + SOCKERRNO); + } + return CURLE_RECV_ERROR; + } + } + + CURL_TRC_CF(data, cf, "wssl_recv(len=%zu) -> 0, %zu", blen, *pnread); + return CURLE_OK; +} + +size_t Curl_wssl_version(char *buffer, size_t size) +{ + return curl_msnprintf(buffer, size, "wolfSSL/%s", wolfSSL_lib_version()); +} + +static int wssl_init(void) +{ + int ret; + +#ifdef OPENSSL_EXTRA + Curl_tls_keylog_open(); +#endif + ret = (wolfSSL_Init() == WOLFSSL_SUCCESS); + if(ret) + ret = wssl_bio_cf_init_methods(); + return ret; +} + +static void wssl_cleanup(void) +{ + wssl_bio_cf_free_methods(); + wolfSSL_Cleanup(); +#ifdef OPENSSL_EXTRA + Curl_tls_keylog_close(); +#endif +} + +static bool wssl_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct ssl_connect_data *ctx = cf->ctx; + struct wssl_ctx *wssl; + + (void)data; + DEBUGASSERT(ctx && ctx->backend); + + wssl = (struct wssl_ctx *)ctx->backend; + if(wssl->ssl) /* wolfSSL is in use */ + return wolfSSL_pending(wssl->ssl); + else + return FALSE; +} + +void Curl_wssl_report_handshake(struct Curl_easy *data, struct wssl_ctx *wssl) +{ + (void)wssl; + infof(data, "SSL connection using %s / %s", + wolfSSL_get_version(wssl->ssl), + wolfSSL_get_cipher_name(wssl->ssl)); +} + +static CURLcode wssl_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend; + CURLcode result = CURLE_OK; + + /* check if the connection has already been established */ + if(ssl_connection_complete == connssl->state) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; + connssl->io_need = CURL_SSL_IO_NEED_NONE; + + if(connssl->connecting_state == ssl_connect_1) { +#ifdef HAVE_WOLFSSL_CTX_GENERATEECHCONFIG + /* if we do ECH and need the HTTPS-RR information for it, + * we delay the connect until it arrives or DNS resolve fails. */ + if(Curl_wssl_need_httpsrr(data) && + !Curl_conn_dns_resolved_https(data, cf->sockindex, + connssl->peer.peer)) { + CURL_TRC_CF(data, cf, "need HTTPS-RR for ECH, delaying connect"); + return CURLE_OK; + } +#endif /* HAVE_WOLFSSL_CTX_GENERATEECHCONFIG */ + result = wssl_connect_step1(cf, data); + if(result) + return result; + connssl->connecting_state = ssl_connect_2; + } + + if(connssl->connecting_state == ssl_connect_2) { + if(connssl->earlydata_state == ssl_earlydata_await) { + /* We defer the handshake until request data arrives. */ + DEBUGASSERT(connssl->state == ssl_connection_deferred); + goto out; + } + result = wssl_handshake(cf, data); + if(result == CURLE_AGAIN) + goto out; + wssl->hs_result = result; + connssl->connecting_state = ssl_connect_3; + } + + if(connssl->connecting_state == ssl_connect_3) { + /* Once the handshake has errored, it stays in that state and + * errors again on every call. */ + if(wssl->hs_result) { + result = wssl->hs_result; + goto out; + } + result = Curl_wssl_verify_pinned(cf, data, wssl); + if(result) { + wssl->hs_result = result; + goto out; + } + /* handshake was done without errors */ +#ifdef HAVE_ALPN + if(connssl->alpn) { + int rc; + char *protocol = NULL; + unsigned short protocol_len = 0; + + rc = wolfSSL_ALPN_GetProtocol(wssl->ssl, &protocol, &protocol_len); + + if(rc == WOLFSSL_SUCCESS) { + Curl_alpn_set_negotiated(cf, data, connssl, + (const unsigned char *)protocol, + protocol_len); + } + else if(rc == WOLFSSL_ALPN_NOT_FOUND) + Curl_alpn_set_negotiated(cf, data, connssl, NULL, 0); + else { + failf(data, "ALPN, failure getting protocol, error %d", rc); + wssl->hs_result = result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + } +#endif /* HAVE_ALPN */ + + connssl->connecting_state = ssl_connect_done; + connssl->state = ssl_connection_complete; + Curl_wssl_report_handshake(data, wssl); + +#ifdef WOLFSSL_EARLY_DATA + if(connssl->earlydata_state > ssl_earlydata_none) { + /* We should be in this state by now */ + DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sent); + connssl->earlydata_state = + (wolfSSL_get_early_data_status(wssl->ssl) == + WOLFSSL_EARLY_DATA_REJECTED) ? + ssl_earlydata_rejected : ssl_earlydata_accepted; + } +#endif /* WOLFSSL_EARLY_DATA */ + } + + if((connssl->connecting_state == ssl_connect_done) || + (connssl->state == ssl_connection_deferred)) { + *done = TRUE; + } + +out: + if(result) { + *done = FALSE; + if(result == CURLE_AGAIN) + return CURLE_OK; + } + else if((connssl->connecting_state == ssl_connect_done) || + (connssl->state == ssl_connection_deferred)) { + *done = TRUE; + } + return result; +} + +static CURLcode wssl_random(struct Curl_easy *data, + unsigned char *entropy, size_t length) +{ + WC_RNG rng; + (void)data; + if(wc_InitRng(&rng)) + return CURLE_FAILED_INIT; + if(length > UINT_MAX) + return CURLE_FAILED_INIT; + if(wc_RNG_GenerateBlock(&rng, entropy, (unsigned)length)) + return CURLE_FAILED_INIT; + if(wc_FreeRng(&rng)) + return CURLE_FAILED_INIT; + return CURLE_OK; +} + +static CURLcode wssl_sha256sum(const unsigned char *input, + size_t len, + unsigned char *sha256sum /* output */, + size_t unused) +{ + wc_Sha256 SHA256pw; + (void)unused; + if(wc_InitSha256(&SHA256pw)) + return CURLE_FAILED_INIT; + do { + word32 ilen = (word32)CURLMIN(len, UINT32_MAX); + if(wc_Sha256Update(&SHA256pw, input, ilen)) + return CURLE_BAD_FUNCTION_ARGUMENT; + len -= ilen; + input += ilen; + } while(len); + if(wc_Sha256Final(&SHA256pw, sha256sum)) + return CURLE_BAD_FUNCTION_ARGUMENT; + return CURLE_OK; +} + +static void *wssl_get_internals(struct ssl_connect_data *connssl, + CURLINFO info) +{ + struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend; + DEBUGASSERT(wssl); + return info == CURLINFO_TLS_SESSION ? + (void *)wssl->ssl_ctx : (void *)wssl->ssl; +} + +const struct Curl_ssl Curl_ssl_wolfssl = { + { CURLSSLBACKEND_WOLFSSL, "wolfssl" }, /* info */ + +#ifdef KEEP_PEER_CERT + SSLSUPP_PINNEDPUBKEY | +#endif +#ifdef USE_BIO_CHAIN + SSLSUPP_HTTPS_PROXY | +#endif + SSLSUPP_CA_PATH | + SSLSUPP_CAINFO_BLOB | +#ifdef HAVE_WOLFSSL_CTX_GENERATEECHCONFIG + SSLSUPP_ECH | +#endif + SSLSUPP_SSL_CTX | +#ifdef WOLFSSL_TLS13 + SSLSUPP_TLS13_CIPHERSUITES | +#endif + SSLSUPP_CA_CACHE | + SSLSUPP_CIPHER_LIST | + SSLSUPP_SSL_EC_CURVES, + + sizeof(struct wssl_ctx), + + wssl_init, /* init */ + wssl_cleanup, /* cleanup */ + Curl_wssl_version, /* version */ + wssl_shutdown, /* shutdown */ + wssl_data_pending, /* data_pending */ + wssl_random, /* random */ + NULL, /* cert_status_request */ + wssl_connect, /* connect */ + Curl_ssl_adjust_pollset, /* adjust_pollset */ + wssl_get_internals, /* get_internals */ + wssl_close, /* close_one */ + NULL, /* close_all */ + NULL, /* set_engine */ + NULL, /* set_engine_default */ + NULL, /* engines_list */ + wssl_sha256sum, /* sha256sum */ + wssl_recv, /* recv decrypted data */ + wssl_send, /* send data to encrypt */ + NULL, /* get_channel_binding */ +}; + +#endif diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/wolfssl.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/wolfssl.h new file mode 100644 index 0000000000..2016a0069f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/wolfssl.h @@ -0,0 +1,102 @@ +#ifndef HEADER_CURL_WOLFSSL_H +#define HEADER_CURL_WOLFSSL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_WOLFSSL + +#include "urldata.h" + +#include <wolfssl/options.h> + +struct alpn_spec; +struct ssl_peer; +struct Curl_ssl_session; + +struct WOLFSSL; +struct WOLFSSL_CTX; +struct WOLFSSL_SESSION; + +extern const struct Curl_ssl Curl_ssl_wolfssl; + +struct wssl_ctx { + struct WOLFSSL_CTX *ssl_ctx; + struct WOLFSSL *ssl; + CURLcode io_result; /* result of last BIO cfilter operation */ + CURLcode hs_result; /* result of handshake */ + int io_send_blocked_len; /* length of last BIO write that EAGAIN-ed */ + BIT(x509_store_setup); /* x509 store has been set up */ + BIT(shutting_down); /* TLS is being shut down */ +}; + +size_t Curl_wssl_version(char *buffer, size_t size); + +typedef CURLcode Curl_wssl_ctx_setup_cb(struct Curl_cfilter *cf, + struct Curl_easy *data, + void *user_data); + +typedef CURLcode Curl_wssl_init_session_reuse_cb(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct alpn_spec *alpns, + struct Curl_ssl_session *scs, + bool *do_early_data); + +CURLcode Curl_wssl_ctx_init(struct wssl_ctx *wctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + const struct alpn_spec *alpns_requested, + Curl_wssl_ctx_setup_cb *cb_setup, + void *cb_user_data, + void *ssl_user_data, + Curl_wssl_init_session_reuse_cb *sess_reuse_cb); + +/* Is a resolved HTTPS-RR needed for initializing wolfSSL? */ +bool Curl_wssl_need_httpsrr(struct Curl_easy *data); + +CURLcode Curl_wssl_setup_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct wssl_ctx *wssl); + +#ifdef HAVE_EX_DATA +CURLcode Curl_wssl_cache_session(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char *ssl_peer_key, + struct WOLFSSL_SESSION *session, + int ietf_tls_id, + const char *alpn, + unsigned char *quic_tp, + size_t quic_tp_len, + struct Curl_ssl_session **pscs); +#endif + +CURLcode Curl_wssl_verify_pinned(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct wssl_ctx *wssl); + +void Curl_wssl_report_handshake(struct Curl_easy *data, struct wssl_ctx *wssl); + +#endif /* USE_WOLFSSL */ +#endif /* HEADER_CURL_WOLFSSL_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/x509asn1.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/x509asn1.c new file mode 100644 index 0000000000..4c5dac3e8b --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/x509asn1.c @@ -0,0 +1,1271 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_GNUTLS) || defined(USE_WOLFSSL) || defined(USE_SCHANNEL) || \ + defined(USE_MBEDTLS) || defined(USE_RUSTLS) + +#if defined(USE_GNUTLS) || defined(USE_SCHANNEL) || defined(USE_MBEDTLS) || \ + defined(USE_WOLFSSL) || defined(USE_RUSTLS) +#define WANT_PARSEX509 /* uses Curl_parseX509() */ +#endif + +#if defined(USE_GNUTLS) || defined(USE_SCHANNEL) || defined(USE_MBEDTLS) || \ + defined(USE_RUSTLS) +#define WANT_EXTRACT_CERTINFO /* uses Curl_extract_certinfo() */ +#endif + +#include "urldata.h" +#include "vtls/vtls.h" +#include "curl_trc.h" +#include "curlx/base64.h" +#include "vtls/x509asn1.h" +#include "curlx/dynbuf.h" + +/* + * Constants. + */ + +/* Largest supported ASN.1 structure. */ +#define CURL_ASN1_MAX ((size_t)0x40000) /* 256K */ + +#ifdef WANT_EXTRACT_CERTINFO + +/* ASN.1 OID table entry. */ +struct Curl_OID { + const char *numoid; /* Dotted-numeric OID. */ + const char *textoid; /* OID name. */ +}; + +/* ASN.1 OIDs. */ +static const struct Curl_OID OIDtable[] = { + { "1.2.840.10040.4.1", "dsa" }, + { "1.2.840.10040.4.3", "dsa-with-sha1" }, + { "1.2.840.10045.2.1", "ecPublicKey" }, + { "1.2.840.10045.3.0.1", "c2pnb163v1" }, + { "1.2.840.10045.4.1", "ecdsa-with-SHA1" }, + { "1.2.840.10045.4.3.1", "ecdsa-with-SHA224" }, + { "1.2.840.10045.4.3.2", "ecdsa-with-SHA256" }, + { "1.2.840.10045.4.3.3", "ecdsa-with-SHA384" }, + { "1.2.840.10045.4.3.4", "ecdsa-with-SHA512" }, + { "1.2.840.10046.2.1", "dhpublicnumber" }, + { "1.2.840.113549.1.1.1", "rsaEncryption" }, + { "1.2.840.113549.1.1.2", "md2WithRSAEncryption" }, + { "1.2.840.113549.1.1.4", "md5WithRSAEncryption" }, + { "1.2.840.113549.1.1.5", "sha1WithRSAEncryption" }, + { "1.2.840.113549.1.1.10", "RSASSA-PSS" }, + { "1.2.840.113549.1.1.14", "sha224WithRSAEncryption" }, + { "1.2.840.113549.1.1.11", "sha256WithRSAEncryption" }, + { "1.2.840.113549.1.1.12", "sha384WithRSAEncryption" }, + { "1.2.840.113549.1.1.13", "sha512WithRSAEncryption" }, + { "1.2.840.113549.2.2", "md2" }, + { "1.2.840.113549.2.5", "md5" }, + { "1.3.14.3.2.26", "sha1" }, + { "2.5.4.3", "CN" }, + { "2.5.4.4", "SN" }, + { "2.5.4.5", "serialNumber" }, + { "2.5.4.6", "C" }, + { "2.5.4.7", "L" }, + { "2.5.4.8", "ST" }, + { "2.5.4.9", "streetAddress" }, + { "2.5.4.10", "O" }, + { "2.5.4.11", "OU" }, + { "2.5.4.12", "title" }, + { "2.5.4.13", "description" }, + { "2.5.4.17", "postalCode" }, + { "2.5.4.41", "name" }, + { "2.5.4.42", "givenName" }, + { "2.5.4.43", "initials" }, + { "2.5.4.44", "generationQualifier" }, + { "2.5.4.45", "X500UniqueIdentifier" }, + { "2.5.4.46", "dnQualifier" }, + { "2.5.4.65", "pseudonym" }, + { "1.2.840.113549.1.9.1", "emailAddress" }, + { "2.5.4.72", "role" }, + { "2.5.29.17", "subjectAltName" }, + { "2.5.29.18", "issuerAltName" }, + { "2.5.29.19", "basicConstraints" }, + { "2.16.840.1.101.3.4.2.4", "sha224" }, + { "2.16.840.1.101.3.4.2.1", "sha256" }, + { "2.16.840.1.101.3.4.2.2", "sha384" }, + { "2.16.840.1.101.3.4.2.3", "sha512" }, + { "1.2.840.113549.1.9.2", "unstructuredName" }, + { NULL, NULL } +}; + +#endif /* WANT_EXTRACT_CERTINFO */ + +/* + * Lightweight ASN.1 parser. + * In particular, it does not check for syntactic/lexical errors. + * It is intended to support certificate information gathering for SSL backends + * that offer a mean to get certificates as a whole, but do not supply + * entry points to get particular certificate sub-fields. + * Please note there is no pretension here to rewrite a full SSL library. + */ + +#define CURL_ASN1_MAX_RECURSIONS 16 + +static const char *getASN1Element_(struct Curl_asn1Element *elem, + const char *beg, const char *end, + size_t lvl) +{ + unsigned char b; + size_t len; + struct Curl_asn1Element lelem; + + /* Get a single ASN.1 element into `elem', parse ASN.1 string at `beg' + ending at `end'. + Returns a pointer in source string after the parsed element, or NULL + if an error occurs. */ + if(!beg || !end || beg >= end || !*beg || + ((size_t)(end - beg) > CURL_ASN1_MAX) || + lvl >= CURL_ASN1_MAX_RECURSIONS) + return NULL; + + /* Process header byte. */ + elem->header = beg; + b = (unsigned char)*beg++; + elem->constructed = (b & 0x20) != 0; + elem->eclass = (b >> 6) & 3; + b &= 0x1F; + if(b == 0x1F) + return NULL; /* Long tag values not supported here. */ + elem->tag = b; + + /* Process length. */ + if(beg >= end) + return NULL; + b = (unsigned char)*beg++; + if(!(b & 0x80)) + len = b; + else { + b &= 0x7F; + if(!b) { + /* Unspecified length. Since we have all the data, we can determine the + effective length by skipping element until an end element is found. */ + if(!elem->constructed) + return NULL; + elem->beg = beg; + while(beg < end && *beg) { + beg = getASN1Element_(&lelem, beg, end, lvl + 1); + if(!beg) + return NULL; + } + if(beg >= end) + return NULL; + elem->end = beg; + return beg + 1; + } + else if((unsigned)b > (size_t)(end - beg)) + return NULL; /* Does not fit in source. */ + else { + /* Get long length. */ + len = 0; + do { + if(len & 0xFF000000L) + return NULL; /* Lengths > 32 bits are not supported. */ + len = (len << 8) | (unsigned char) *beg++; + } while(--b); + } + } + if(len > (size_t)(end - beg)) + return NULL; /* Element data does not fit in source. */ + elem->beg = beg; + elem->end = beg + len; + return elem->end; +} + +/* + * @unittest 1657 + */ +UNITTEST const char *getASN1Element(struct Curl_asn1Element *elem, + const char *beg, const char *end); +UNITTEST const char *getASN1Element(struct Curl_asn1Element *elem, + const char *beg, const char *end) +{ + return getASN1Element_(elem, beg, end, 0); +} + +#ifdef WANT_EXTRACT_CERTINFO + +/* + * Search the null-terminated OID or OID identifier in local table. + * Return the table entry pointer or NULL if not found. + */ +static const struct Curl_OID *searchOID(const char *oid) +{ + const struct Curl_OID *op; + for(op = OIDtable; op->numoid; op++) + if(!strcmp(op->numoid, oid) || curl_strequal(op->textoid, oid)) + return op; + + return NULL; +} + +/* + * Convert an ASN.1 Boolean value into its string representation. + * + * Return error code. + */ + +static CURLcode bool2str(struct dynbuf *store, + const char *beg, const char *end) +{ + uint8_t val; + if(end - beg != 1) + return CURLE_BAD_FUNCTION_ARGUMENT; + val = (uint8_t)*beg; + if((val != 0xff) && (val != 0x00)) + return CURLE_BAD_FUNCTION_ARGUMENT; + return curlx_dyn_add(store, val ? "TRUE" : "FALSE"); +} + +/* + * Convert an ASN.1 octet string to a printable string. + * + * Return error code. + */ +static CURLcode octet2str(struct dynbuf *store, + const char *beg, const char *end) +{ + CURLcode result = CURLE_OK; + + while(!result && beg < end) + result = curlx_dyn_addf(store, "%02x:", (unsigned char)*beg++); + + return result; +} + +static CURLcode bit2str(struct dynbuf *store, const char *beg, const char *end) +{ + /* Convert an ASN.1 bit string to a printable string. */ + + if(beg < end) { + uint8_t unused_bits = (uint8_t)*beg++; + if(unused_bits > 7) + return CURLE_BAD_FUNCTION_ARGUMENT; + } + else + return CURLE_BAD_FUNCTION_ARGUMENT; + return octet2str(store, beg, end); +} + +/* + * Convert an ASN.1 integer value into its string representation. + * + * Returns error. + */ +static CURLcode int2str(struct dynbuf *store, const char *beg, const char *end) +{ + uint32_t uval = 0; + int32_t sval = 0; + size_t n = end - beg; + size_t i; + const unsigned char *p = (const unsigned char *)beg; + + if(!n) + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(n > 4) + return octet2str(store, beg, end); + + if(p[0] & 0x80) + uval = ~0U; + + for(i = 0; i < n; i++) + uval = (uval << 8) | p[i]; + + sval = (int32_t)uval; + + /* small values are easier to read as decimals */ + if(sval > -10000 && sval < 10000) + return curlx_dyn_addf(store, "%d", sval); + + /* represent larger values as hex */ + return curlx_dyn_addf(store, "0x%x", uval); +} + +/* + * Convert from an ASN.1 typed string to UTF8. + * + * The result is stored in a dynbuf that is inited by the user of this + * function. + * + * Returns error. + */ +static CURLcode utf8asn1str(struct dynbuf *to, int type, const char *from, + const char *end) +{ + size_t inlength = end - from; + int size = 1; + CURLcode result = CURLE_OK; + + switch(type) { + case CURL_ASN1_BMP_STRING: + size = 2; + break; + case CURL_ASN1_UNIVERSAL_STRING: + size = 4; + break; + case CURL_ASN1_NUMERIC_STRING: + case CURL_ASN1_PRINTABLE_STRING: + case CURL_ASN1_TELETEX_STRING: + case CURL_ASN1_IA5_STRING: + case CURL_ASN1_VISIBLE_STRING: + case CURL_ASN1_UTF8_STRING: + break; + default: + return CURLE_BAD_FUNCTION_ARGUMENT; /* Conversion not supported. */ + } + + if(inlength % size) + /* Length inconsistent with character size. */ + return CURLE_BAD_FUNCTION_ARGUMENT; + + if(type == CURL_ASN1_UTF8_STRING) { + /* copy. */ + if(inlength) + result = curlx_dyn_addn(to, from, inlength); + } + else { + while(!result && (from < end)) { + char buf[4]; /* decode buffer */ + size_t charsize = 1; + unsigned int wc = 0; + + switch(size) { + case 4: + wc = (wc << 8) | *(const unsigned char *)from++; + wc = (wc << 8) | *(const unsigned char *)from++; + FALLTHROUGH(); + case 2: + wc = (wc << 8) | *(const unsigned char *)from++; + FALLTHROUGH(); + default: /* case 1: */ + wc = (wc << 8) | *(const unsigned char *)from++; + } + if(wc >= 0x00000080) { + if(wc >= 0x00000800) { + if(wc >= 0x00010000) { + if(wc >= 0x00200000) { + /* Invalid char. size for target encoding. */ + return CURLE_WEIRD_SERVER_REPLY; + } + buf[3] = (char)(0x80 | (wc & 0x3F)); + wc = (wc >> 6) | 0x00010000; + charsize++; + } + buf[2] = (char)(0x80 | (wc & 0x3F)); + wc = (wc >> 6) | 0x00000800; + charsize++; + } + buf[1] = (char)(0x80 | (wc & 0x3F)); + wc = (wc >> 6) | 0x000000C0; + charsize++; + } + buf[0] = (char)wc; + result = curlx_dyn_addn(to, buf, charsize); + } + } + return result; +} + +/* + * Convert an ASN.1 OID into its dotted string representation. Each field is + * limited to unsigned 32-bit values. + * + * A minor limitation is in the second number, which can be no larger than 32 + * bits - 80 == 4294967215. + * + * Return error code. + * + * @unittest 1666 + */ +UNITTEST CURLcode encodeOID(struct dynbuf *store, + const char *beg, const char *end); +UNITTEST CURLcode encodeOID(struct dynbuf *store, + const char *beg, const char *end) +{ + uint32_t x; + uint32_t y; + CURLcode result = CURLE_OK; + + if(end <= beg) + return CURLE_BAD_FUNCTION_ARGUMENT; + + /* Process the first two numbers. The initial digit cannot be larger than + 2 */ + y = *(const unsigned char *)beg++; + if(y <= 80) + x = y / 40; + else + x = 2; + result = curlx_dyn_addf(store, "%u", x); + if(result) + return result; + + if(y & 0x80) { + uint32_t t = (y & 0x7f); /* the second number */ + if(!t) + /* reject leading 0x80 padding */ + return CURLE_BAD_FUNCTION_ARGUMENT; + do { + if((t & 0xFE000000) || (beg >= end)) + return CURLE_BAD_FUNCTION_ARGUMENT; + y = *(const unsigned char *)beg++; + t = (t << 7) | (y & 0x7F); + } while(y & 0x80); + y = t; + } + + result = curlx_dyn_addf(store, ".%u", y - (x * 40)); + if(result) + return result; + + /* Process the trailing numbers. */ + while((beg < end) && !result) { + x = 0; + y = 0; + do { + /* 0x80 as the first value is invalid since it only adds padding */ + if((y & 0x80) && !x) + return CURLE_BAD_FUNCTION_ARGUMENT; + else if((x & 0xFE000000) || (beg == end)) + return CURLE_BAD_FUNCTION_ARGUMENT; + y = *(const unsigned char *)beg++; + x = (x << 7) | (y & 0x7F); + } while(y & 0x80); + result = curlx_dyn_addf(store, ".%u", x); + } + return result; +} + +/* + * Convert an ASN.1 OID into its dotted or symbolic string representation. + * + * Return error code. + */ + +static CURLcode OID2str(struct dynbuf *store, + const char *beg, const char *end) +{ + CURLcode result = CURLE_OK; + if(beg < end) { + struct dynbuf buf; + curlx_dyn_init(&buf, CURL_X509_STR_MAX); + result = encodeOID(&buf, beg, end); + + if(!result) { + const struct Curl_OID *op = searchOID(curlx_dyn_ptr(&buf)); + if(op) + result = curlx_dyn_add(store, op->textoid); + else + result = curlx_dyn_add(store, curlx_dyn_ptr(&buf)); + } + curlx_dyn_free(&buf); + } + return result; +} + +/* + * @unittest 1656 + */ +UNITTEST CURLcode GTime2str(struct dynbuf *store, + const char *beg, const char *end); +UNITTEST CURLcode GTime2str(struct dynbuf *store, + const char *beg, const char *end) +{ + const char *tzp; + const char *fracp; + char sec1, sec2; + size_t fracl; + size_t tzl; + const char *sep = ""; + + /* Convert an ASN.1 Generalized time to a printable string. + Return the dynamically allocated string, or NULL if an error occurs. */ + + for(fracp = beg; fracp < end && ISDIGIT(*fracp); fracp++) + ; + + /* Get seconds digits. */ + sec1 = '0'; + switch(fracp - beg - 12) { + case 0: + sec2 = '0'; + break; + case 2: + sec1 = fracp[-2]; + FALLTHROUGH(); + case 1: + sec2 = fracp[-1]; + break; + default: + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + /* timezone follows optional fractional seconds. */ + tzp = fracp; + fracl = 0; /* no fractional seconds detected so far */ + if(fracp < end && (*fracp == '.' || *fracp == ',')) { + /* Have fractional seconds, e.g. "[.,]\d+". How many? */ + fracp++; /* should be a digit char or BAD ARGUMENT */ + tzp = fracp; + while(tzp < end && ISDIGIT(*tzp)) + tzp++; + if(tzp == fracp) /* never looped, no digit after [.,] */ + return CURLE_BAD_FUNCTION_ARGUMENT; + fracl = tzp - fracp; /* number of fractional sec digits */ + DEBUGASSERT(fracl > 0); + /* Strip trailing zeroes in fractional seconds. + * May reduce fracl to 0 if only '0's are present. */ + while(fracl && fracp[fracl - 1] == '0') + fracl--; + } + + /* Process timezone. */ + if(tzp >= end) { + tzp = ""; + tzl = 0; + } + else if(*tzp == 'Z') { + sep = " "; + tzp = "GMT"; + tzl = 3; + } + else if((*tzp == '+') || (*tzp == '-')) { + sep = " UTC"; + tzl = end - tzp; + } + else { + sep = " "; + tzl = end - tzp; + } + + return curlx_dyn_addf(store, + "%.4s-%.2s-%.2s %.2s:%.2s:%c%c%s%.*s%s%.*s", + beg, beg + 4, beg + 6, + beg + 8, beg + 10, sec1, sec2, + fracl ? "." : "", (int)fracl, fracp, + sep, (int)tzl, tzp); +} + +/* + * Convert an ASN.1 UTC time to a printable string. + * + * Return error code. + */ +static CURLcode UTime2str(struct dynbuf *store, + const char *beg, const char *end) +{ + const char *tzp; + size_t tzl; + const char *sec; + + for(tzp = beg; tzp < end && *tzp >= '0' && *tzp <= '9'; tzp++) + ; + /* Get the seconds. */ + sec = beg + 10; + switch(tzp - sec) { + case 0: + sec = "00"; + FALLTHROUGH(); + case 2: + break; + default: + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + /* Process timezone. */ + if(tzp >= end) + return CURLE_BAD_FUNCTION_ARGUMENT; + if(*tzp == 'Z') { + tzp = "GMT"; + end = tzp + 3; + } + + tzl = end - tzp; + return curlx_dyn_addf(store, "%d%.2s-%.2s-%.2s %.2s:%.2s:%.2s %.*s", + 20 - (*beg >= '5'), beg, beg + 2, beg + 4, + beg + 6, beg + 8, sec, + (int)tzl, tzp); +} + +/* + * Convert an ASN.1 element to a printable string. + * + * Return error + * + * @unittest 1667 + */ +UNITTEST CURLcode ASN1tostr(struct dynbuf *store, + struct Curl_asn1Element *elem); +UNITTEST CURLcode ASN1tostr(struct dynbuf *store, + struct Curl_asn1Element *elem) +{ + CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT; + int type = elem->tag; + if(elem->constructed) + return result; /* No conversion of structured elements. */ + + switch(type) { + case CURL_ASN1_BOOLEAN: + result = bool2str(store, elem->beg, elem->end); + break; + case CURL_ASN1_INTEGER: + case CURL_ASN1_ENUMERATED: + result = int2str(store, elem->beg, elem->end); + break; + case CURL_ASN1_BIT_STRING: + result = bit2str(store, elem->beg, elem->end); + break; + case CURL_ASN1_OCTET_STRING: + result = octet2str(store, elem->beg, elem->end); + break; + case CURL_ASN1_NULL: + result = curlx_dyn_addn(store, "", 1); + break; + case CURL_ASN1_OBJECT_IDENTIFIER: + result = OID2str(store, elem->beg, elem->end); + break; + case CURL_ASN1_UTC_TIME: + result = UTime2str(store, elem->beg, elem->end); + break; + case CURL_ASN1_GENERALIZED_TIME: + result = GTime2str(store, elem->beg, elem->end); + break; + case CURL_ASN1_UTF8_STRING: + case CURL_ASN1_NUMERIC_STRING: + case CURL_ASN1_PRINTABLE_STRING: + case CURL_ASN1_TELETEX_STRING: + case CURL_ASN1_IA5_STRING: + case CURL_ASN1_VISIBLE_STRING: + case CURL_ASN1_UNIVERSAL_STRING: + case CURL_ASN1_BMP_STRING: + result = utf8asn1str(store, type, elem->beg, elem->end); + break; + } + + return result; +} + +/* + * ASCII encode distinguished name at `dn' into the store dynbuf. + * + * Returns error. + */ +static CURLcode encodeDN(struct dynbuf *store, struct Curl_asn1Element *dn) +{ + struct Curl_asn1Element rdn; + struct Curl_asn1Element atv; + struct Curl_asn1Element oid; + struct Curl_asn1Element value; + const char *p1; + const char *p2; + const char *p3; + const char *str; + CURLcode result = CURLE_OK; + bool added = FALSE; + struct dynbuf temp; + curlx_dyn_init(&temp, CURL_X509_STR_MAX); + + for(p1 = dn->beg; p1 < dn->end;) { + p1 = getASN1Element(&rdn, p1, dn->end); + if(!p1) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto error; + } + for(p2 = rdn.beg; p2 < rdn.end;) { + p2 = getASN1Element(&atv, p2, rdn.end); + if(!p2) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto error; + } + p3 = getASN1Element(&oid, atv.beg, atv.end); + if(!p3) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto error; + } + if(!getASN1Element(&value, p3, atv.end)) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto error; + } + curlx_dyn_reset(&temp); + result = ASN1tostr(&temp, &oid); + if(result) + goto error; + + str = curlx_dyn_ptr(&temp); + + if(!str) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto error; + } + + /* Encode delimiter. + If attribute has a short uppercase name, delimiter is ", ". */ + for(p3 = str; ISUPPER(*p3); p3++) + ; + if(added) { + if(p3 - str > 2) + result = curlx_dyn_addn(store, "/", 1); + else + result = curlx_dyn_addn(store, ", ", 2); + if(result) + goto error; + } + + /* Encode attribute name. */ + result = curlx_dyn_add(store, str); + if(result) + goto error; + + /* Generate equal sign. */ + result = curlx_dyn_addn(store, "=", 1); + if(result) + goto error; + + /* Generate value. */ + result = ASN1tostr(store, &value); + if(result) + goto error; + curlx_dyn_reset(&temp); + added = TRUE; /* use separator for next */ + } + } +error: + curlx_dyn_free(&temp); + + return result; +} + +#endif /* WANT_EXTRACT_CERTINFO */ + +#ifdef WANT_PARSEX509 +/* + * ASN.1 parse an X509 certificate into structure subfields. + * Syntax is assumed to have already been checked by the SSL backend. + * See RFC 5280. + */ +int Curl_parseX509(struct Curl_X509certificate *cert, + const char *beg, const char *end) +{ + struct Curl_asn1Element elem; + struct Curl_asn1Element tbsCertificate; + const char *ccp; + static const char defaultVersion = 0; /* v1. */ + + cert->certificate.header = NULL; + cert->certificate.beg = beg; + cert->certificate.end = end; + + /* Get the sequence content. */ + if(!getASN1Element(&elem, beg, end)) + return -1; /* Invalid bounds/size. */ + beg = elem.beg; + end = elem.end; + + /* Get tbsCertificate. */ + beg = getASN1Element(&tbsCertificate, beg, end); + if(!beg) + return -1; + /* Skip the signatureAlgorithm. */ + beg = getASN1Element(&cert->signatureAlgorithm, beg, end); + if(!beg) + return -1; + /* Get the signatureValue. */ + if(!getASN1Element(&cert->signature, beg, end)) + return -1; + + /* Parse TBSCertificate. */ + beg = tbsCertificate.beg; + end = tbsCertificate.end; + /* Get optional version, get serialNumber. */ + cert->version.header = NULL; + cert->version.beg = &defaultVersion; + cert->version.end = &defaultVersion + sizeof(defaultVersion); + beg = getASN1Element(&elem, beg, end); + if(!beg) + return -1; + if(elem.tag == 0) { + if(!getASN1Element(&cert->version, elem.beg, elem.end)) + return -1; + beg = getASN1Element(&elem, beg, end); + if(!beg) + return -1; + } + cert->serialNumber = elem; + /* Get signature algorithm. */ + beg = getASN1Element(&cert->signatureAlgorithm, beg, end); + /* Get issuer. */ + beg = getASN1Element(&cert->issuer, beg, end); + if(!beg) + return -1; + /* Get notBefore and notAfter. */ + beg = getASN1Element(&elem, beg, end); + if(!beg) + return -1; + ccp = getASN1Element(&cert->notBefore, elem.beg, elem.end); + if(!ccp) + return -1; + if(!getASN1Element(&cert->notAfter, ccp, elem.end)) + return -1; + /* Get subject. */ + beg = getASN1Element(&cert->subject, beg, end); + if(!beg) + return -1; + /* Get subjectPublicKeyAlgorithm and subjectPublicKey. */ + beg = getASN1Element(&cert->subjectPublicKeyInfo, beg, end); + if(!beg) + return -1; + ccp = getASN1Element(&cert->subjectPublicKeyAlgorithm, + cert->subjectPublicKeyInfo.beg, + cert->subjectPublicKeyInfo.end); + if(!ccp) + return -1; + if(!getASN1Element(&cert->subjectPublicKey, ccp, + cert->subjectPublicKeyInfo.end)) + return -1; + /* Get optional issuerUniqueID, subjectUniqueID and extensions. */ + cert->issuerUniqueID.tag = cert->subjectUniqueID.tag = 0; + cert->extensions.tag = elem.tag = 0; + cert->issuerUniqueID.header = cert->subjectUniqueID.header = NULL; + cert->issuerUniqueID.beg = cert->issuerUniqueID.end = ""; + cert->subjectUniqueID.beg = cert->subjectUniqueID.end = ""; + cert->extensions.header = NULL; + cert->extensions.beg = cert->extensions.end = ""; + if(beg < end) { + beg = getASN1Element(&elem, beg, end); + if(!beg) + return -1; + } + if(elem.tag == 1) { + cert->issuerUniqueID = elem; + if(beg < end) { + beg = getASN1Element(&elem, beg, end); + if(!beg) + return -1; + } + } + if(elem.tag == 2) { + cert->subjectUniqueID = elem; + if(beg < end) { + beg = getASN1Element(&elem, beg, end); + if(!beg) + return -1; + } + } + if(elem.tag == 3) + if(!getASN1Element(&cert->extensions, elem.beg, elem.end)) + return -1; + return 0; +} + +#endif /* WANT_PARSEX509 */ + +#ifdef WANT_EXTRACT_CERTINFO + +static CURLcode dumpAlgo(struct dynbuf *store, + struct Curl_asn1Element *param, + const char *beg, const char *end) +{ + struct Curl_asn1Element oid; + + /* Get algorithm parameters and return algorithm name. */ + + beg = getASN1Element(&oid, beg, end); + if(!beg) + return CURLE_BAD_FUNCTION_ARGUMENT; + param->header = NULL; + param->tag = 0; + param->beg = param->end = end; + if(beg < end) { + const char *p = getASN1Element(param, beg, end); + if(!p) + return CURLE_BAD_FUNCTION_ARGUMENT; + } + return OID2str(store, oid.beg, oid.end); +} + +/* + * This is a convenience function for push_certinfo_len that takes a zero + * terminated value. + */ +static CURLcode ssl_push_certinfo(struct Curl_easy *data, + int certnum, + const char *label, + const char *value) +{ + size_t valuelen = strlen(value); + + return Curl_ssl_push_certinfo_len(data, certnum, label, value, valuelen); +} + +/* + * This is a convenience function for push_certinfo_len that takes a + * dynbuf value. + * + * It also does the verbose output if !certnum. + */ +static CURLcode ssl_push_certinfo_dyn(struct Curl_easy *data, + int certnum, + const char *label, + struct dynbuf *ptr) +{ + size_t valuelen = curlx_dyn_len(ptr); + const char *value = curlx_dyn_ptr(ptr); + + CURLcode result = Curl_ssl_push_certinfo_len(data, certnum, label, + value, valuelen); + + if(!certnum && !result) + infof(data, " %s: %s", label, value); + + return result; +} + +static CURLcode do_pubkey_field(struct Curl_easy *data, int certnum, + const char *label, + struct Curl_asn1Element *elem) +{ + CURLcode result; + struct dynbuf out; + + curlx_dyn_init(&out, CURL_X509_STR_MAX); + + /* Generate a certificate information record for the public key. */ + + result = ASN1tostr(&out, elem); + if(!result) { + if(data->set.ssl.certinfo) + result = ssl_push_certinfo_dyn(data, certnum, label, &out); + curlx_dyn_free(&out); + } + return result; +} + +/* return 0 on success, 1 on error */ +static int do_pubkey(struct Curl_easy *data, int certnum, const char *algo, + struct Curl_asn1Element *param, + struct Curl_asn1Element *pubkey) +{ + struct Curl_asn1Element elem; + struct Curl_asn1Element pk; + const char *p; + + /* Generate all information records for the public key. */ + + if(curl_strequal(algo, "ecPublicKey")) { + /* + * ECC public key is all the data, a value of type BIT STRING mapped to + * OCTET STRING and should not be parsed as an ASN.1 value. + */ + const size_t dlen = pubkey->end - pubkey->beg; + size_t len; + if(dlen < 2) + /* too small */ + return 1; + len = (dlen - 2) * 4; + if(!certnum) + infof(data, " ECC Public Key (%zu bits)", len); + if(data->set.ssl.certinfo) { + char q[(sizeof(len) * 8 / 3) + 1]; + (void)curl_msnprintf(q, sizeof(q), "%zu", len); + if(ssl_push_certinfo(data, certnum, "ECC Public Key", q)) + return 1; + } + return do_pubkey_field(data, certnum, "ecPublicKey", pubkey) == CURLE_OK + ? 0 : 1; + } + + /* Get the public key (single element). */ + if(!getASN1Element(&pk, pubkey->beg + 1, pubkey->end)) + return 1; + + if(curl_strequal(algo, "rsaEncryption")) { + const char *q; + size_t len; + + p = getASN1Element(&elem, pk.beg, pk.end); + if(!p) + return 1; + + /* Compute key length. */ + for(q = elem.beg; q < elem.end && !*q; q++) + ; + len = ((elem.end - q) * 8); + if(len) { + unsigned int i; + for(i = *(const unsigned char *)q; !(i & 0x80); i <<= 1) + len--; + } + if(len > 32) + elem.beg = q; /* Strip leading zero bytes. */ + if(!certnum) + infof(data, " RSA Public Key (%zu bits)", len); + if(data->set.ssl.certinfo) { + char r[(sizeof(len) * 8 / 3) + 1]; + curl_msnprintf(r, sizeof(r), "%zu", len); + if(ssl_push_certinfo(data, certnum, "RSA Public Key", r)) + return 1; + } + /* Generate coefficients. */ + if(do_pubkey_field(data, certnum, "rsa(n)", &elem)) + return 1; + if(!getASN1Element(&elem, p, pk.end)) + return 1; + if(do_pubkey_field(data, certnum, "rsa(e)", &elem)) + return 1; + } + else if(curl_strequal(algo, "dsa")) { + p = getASN1Element(&elem, param->beg, param->end); + if(p) { + if(do_pubkey_field(data, certnum, "dsa(p)", &elem)) + return 1; + p = getASN1Element(&elem, p, param->end); + if(p) { + if(do_pubkey_field(data, certnum, "dsa(q)", &elem)) + return 1; + if(getASN1Element(&elem, p, param->end)) { + if(do_pubkey_field(data, certnum, "dsa(g)", &elem)) + return 1; + if(do_pubkey_field(data, certnum, "dsa(pub_key)", &pk)) + return 1; + } + } + } + } + else if(curl_strequal(algo, "dhpublicnumber")) { + p = getASN1Element(&elem, param->beg, param->end); + if(p) { + if(do_pubkey_field(data, certnum, "dh(p)", &elem)) + return 1; + if(getASN1Element(&elem, p, param->end)) { + if(do_pubkey_field(data, certnum, "dh(g)", &elem)) + return 1; + if(do_pubkey_field(data, certnum, "dh(pub_key)", &pk)) + return 1; + } + } + } + return 0; +} + +/* + * Convert an ASN.1 distinguished name into a printable string. + * Return error. + */ +static CURLcode DNtostr(struct dynbuf *store, struct Curl_asn1Element *dn) +{ + return encodeDN(store, dn); +} + +CURLcode Curl_extract_certinfo(struct Curl_easy *data, + int certnum, + const char *beg, + const char *end) +{ + struct Curl_X509certificate cert; + struct Curl_asn1Element param; + char *certptr; + size_t clen; + struct dynbuf out; + CURLcode result = CURLE_OK; + unsigned int version; + const char *ptr; + int rc; + + if(!data->set.ssl.certinfo) + if(certnum) + return CURLE_OK; + + curlx_dyn_init(&out, CURL_X509_STR_MAX); + /* Prepare the certificate information for curl_easy_getinfo(). */ + + /* Extract the certificate ASN.1 elements. */ + if(Curl_parseX509(&cert, beg, end)) + return CURLE_PEER_FAILED_VERIFICATION; + + /* Subject. */ + result = DNtostr(&out, &cert.subject); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Subject", &out); + if(result) + goto done; + } + curlx_dyn_reset(&out); + + /* Issuer. */ + result = DNtostr(&out, &cert.issuer); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Issuer", &out); + if(result) + goto done; + } + curlx_dyn_reset(&out); + + /* Version (always fits in less than 32 bits). */ + version = 0; + for(ptr = cert.version.beg; ptr < cert.version.end; ptr++) + version = (version << 8) | *(const unsigned char *)ptr; + if(data->set.ssl.certinfo) { + result = curlx_dyn_addf(&out, "%x", version); + if(result) + goto done; + result = ssl_push_certinfo_dyn(data, certnum, "Version", &out); + if(result) + goto done; + curlx_dyn_reset(&out); + } + + /* Serial number. */ + result = ASN1tostr(&out, &cert.serialNumber); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Serial Number", &out); + if(result) + goto done; + } + curlx_dyn_reset(&out); + + /* Signature algorithm .*/ + result = dumpAlgo(&out, ¶m, cert.signatureAlgorithm.beg, + cert.signatureAlgorithm.end); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Signature Algorithm", &out); + if(result) + goto done; + } + curlx_dyn_reset(&out); + + /* Start Date. */ + result = ASN1tostr(&out, &cert.notBefore); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Start Date", &out); + if(result) + goto done; + } + curlx_dyn_reset(&out); + + /* Expire Date. */ + result = ASN1tostr(&out, &cert.notAfter); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Expire Date", &out); + if(result) + goto done; + } + curlx_dyn_reset(&out); + + /* Public Key Algorithm. */ + result = dumpAlgo(&out, ¶m, cert.subjectPublicKeyAlgorithm.beg, + cert.subjectPublicKeyAlgorithm.end); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Public Key Algorithm", + &out); + if(result) + goto done; + } + + rc = do_pubkey(data, certnum, curlx_dyn_ptr(&out), + ¶m, &cert.subjectPublicKey); + if(rc) { + result = CURLE_OUT_OF_MEMORY; /* the most likely error */ + goto done; + } + curlx_dyn_reset(&out); + + /* Signature. */ + result = ASN1tostr(&out, &cert.signature); + if(result) + goto done; + if(data->set.ssl.certinfo) { + result = ssl_push_certinfo_dyn(data, certnum, "Signature", &out); + if(result) + goto done; + } + curlx_dyn_reset(&out); + + /* Generate PEM certificate. */ + result = curlx_base64_encode((const uint8_t *)cert.certificate.beg, + cert.certificate.end - cert.certificate.beg, + &certptr, &clen); + if(result) + goto done; + + /* Generate the final output certificate string. Format is: + -----BEGIN CERTIFICATE-----\n + <max 64 base64 characters>\n + . + . + . + -----END CERTIFICATE-----\n + */ + + curlx_dyn_reset(&out); + + /* Build the certificate string. */ + result = curlx_dyn_add(&out, "-----BEGIN CERTIFICATE-----\n"); + if(!result) { + size_t j = 0; + + while(!result && (j < clen)) { + size_t chunksize = (clen - j) > 64 ? 64 : (clen - j); + result = curlx_dyn_addn(&out, &certptr[j], chunksize); + if(!result) + result = curlx_dyn_addn(&out, "\n", 1); + j += chunksize; + } + if(!result) + result = curlx_dyn_add(&out, "-----END CERTIFICATE-----\n"); + } + curlx_free(certptr); + if(!result) + if(data->set.ssl.certinfo) + result = ssl_push_certinfo_dyn(data, certnum, "Cert", &out); + +done: + if(result) + failf(data, "Failed extracting certificate chain"); + curlx_dyn_free(&out); + return result; +} + +#endif /* WANT_EXTRACT_CERTINFO */ + +#endif /* USE_GNUTLS || USE_WOLFSSL || USE_SCHANNEL || USE_MBEDTLS || + USE_RUSTLS */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/x509asn1.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/x509asn1.h new file mode 100644 index 0000000000..dda55ac77f --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/vtls/x509asn1.h @@ -0,0 +1,119 @@ +#ifndef HEADER_CURL_X509ASN1_H +#define HEADER_CURL_X509ASN1_H + +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +/* forward-declare to make it visible in all builds */ +struct Curl_asn1Element; + +#if defined(USE_GNUTLS) || defined(USE_WOLFSSL) || defined(USE_SCHANNEL) || \ + defined(USE_MBEDTLS) || defined(USE_RUSTLS) + +#include "cfilters.h" +#include "urldata.h" + +/* ASN.1 classes. */ +/* #define CURL_ASN1_UNIVERSAL 0 */ +/* #define CURL_ASN1_APPLICATION 1 */ +/* #define CURL_ASN1_CONTEXT_SPECIFIC 2 */ +/* #define CURL_ASN1_PRIVATE 3 */ + +/* ASN.1 types. */ +#define CURL_ASN1_BOOLEAN 1 +#define CURL_ASN1_INTEGER 2 +#define CURL_ASN1_BIT_STRING 3 +#define CURL_ASN1_OCTET_STRING 4 +#define CURL_ASN1_NULL 5 +#define CURL_ASN1_OBJECT_IDENTIFIER 6 +/* #define CURL_ASN1_OBJECT_DESCRIPTOR 7 */ +/* #define CURL_ASN1_INSTANCE_OF 8 */ +/* #define CURL_ASN1_REAL 9 */ +#define CURL_ASN1_ENUMERATED 10 +/* #define CURL_ASN1_EMBEDDED 11 */ +#define CURL_ASN1_UTF8_STRING 12 +/* #define CURL_ASN1_RELATIVE_OID 13 */ +/* #define CURL_ASN1_SEQUENCE 16 */ +/* #define CURL_ASN1_SET 17 */ +#define CURL_ASN1_NUMERIC_STRING 18 +#define CURL_ASN1_PRINTABLE_STRING 19 +#define CURL_ASN1_TELETEX_STRING 20 +/* #define CURL_ASN1_VIDEOTEX_STRING 21 */ +#define CURL_ASN1_IA5_STRING 22 +#define CURL_ASN1_UTC_TIME 23 +#define CURL_ASN1_GENERALIZED_TIME 24 +/* #define CURL_ASN1_GRAPHIC_STRING 25 */ +#define CURL_ASN1_VISIBLE_STRING 26 +/* #define CURL_ASN1_GENERAL_STRING 27 */ +#define CURL_ASN1_UNIVERSAL_STRING 28 +/* #define CURL_ASN1_CHARACTER_STRING 29 */ +#define CURL_ASN1_BMP_STRING 30 + +/* + * Types. + */ + +/* ASN.1 parsed element. */ +struct Curl_asn1Element { + const char *header; /* Pointer to header byte. */ + const char *beg; /* Pointer to element data. */ + const char *end; /* Pointer to 1st byte after element. */ + unsigned char eclass; /* ASN.1 element class. */ + unsigned char tag; /* ASN.1 element tag. */ + BIT(constructed); /* Element is constructed. */ +}; + +/* X509 certificate: RFC 5280. */ +struct Curl_X509certificate { + struct Curl_asn1Element certificate; + struct Curl_asn1Element version; + struct Curl_asn1Element serialNumber; + struct Curl_asn1Element signatureAlgorithm; + struct Curl_asn1Element signature; + struct Curl_asn1Element issuer; + struct Curl_asn1Element notBefore; + struct Curl_asn1Element notAfter; + struct Curl_asn1Element subject; + struct Curl_asn1Element subjectPublicKeyInfo; + struct Curl_asn1Element subjectPublicKeyAlgorithm; + struct Curl_asn1Element subjectPublicKey; + struct Curl_asn1Element issuerUniqueID; + struct Curl_asn1Element subjectUniqueID; + struct Curl_asn1Element extensions; +}; + +/* + * Prototypes. + */ + +int Curl_parseX509(struct Curl_X509certificate *cert, + const char *beg, const char *end); +CURLcode Curl_extract_certinfo(struct Curl_easy *data, int certnum, + const char *beg, const char *end); +CURLcode Curl_verifyhost(struct Curl_cfilter *cf, struct Curl_easy *data, + const char *beg, const char *end); +#endif /* USE_GNUTLS || USE_WOLFSSL || USE_SCHANNEL || USE_MBEDTLS || + USE_RUSTLS */ +#endif /* HEADER_CURL_X509ASN1_H */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/ws.c b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ws.c new file mode 100644 index 0000000000..a7653df678 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ws.c @@ -0,0 +1,2071 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "urldata.h" +#include "ws.h" + +#ifndef CURL_DISABLE_WEBSOCKETS + +#include "url.h" +#include "bufq.h" +#include "curlx/dynbuf.h" +#include "rand.h" +#include "curlx/base64.h" +#include "cf-recvbuf.h" +#include "connect.h" +#include "sendf.h" +#include "curl_trc.h" +#include "multiif.h" +#include "easyif.h" +#include "transfer.h" +#include "select.h" +#include "curlx/strparse.h" +#include "curlx/strcopy.h" + +/* RFC 6455 Section 5.2 + + 0 1 2 3 4 5 6 7 + +-+-+-+-+-------+ + |F|R|R|R| opcode| + |I|S|S|S| (4) | + |N|V|V|V| | + | |1|2|3| | + */ +#define WSBIT_FIN 0x80 +#define WSBIT_RSV1 0x40 +#define WSBIT_RSV2 0x20 +#define WSBIT_RSV3 0x10 +#define WSBIT_RSV_MASK (WSBIT_RSV1 | WSBIT_RSV2 | WSBIT_RSV3) +#define WSBIT_OPCODE_CONT 0x0 +#define WSBIT_OPCODE_TEXT 0x1 +#define WSBIT_OPCODE_BIN 0x2 +#define WSBIT_OPCODE_CLOSE 0x8 +#define WSBIT_OPCODE_PING 0x9 +#define WSBIT_OPCODE_PONG 0xa +#ifdef CURLVERBOSE +#define WSBIT_OPCODE_MASK 0xf +#endif + +#define WSBIT_MASK 0x80 + +/* buffer dimensioning */ +#define WS_CHUNK_SIZE 65535 +#define WS_CHUNK_COUNT 2 + +/* a client-side WS frame decoder, parsing frame headers and + * payload, keeping track of current position and stats */ +enum ws_dec_state { + WS_DEC_INIT, + WS_DEC_HEAD, + WS_DEC_PAYLOAD +}; + +struct ws_decoder { + int frame_age; /* zero */ + int frame_flags; /* See the CURLWS_* defines */ + curl_off_t payload_offset; /* the offset parsing is at */ + curl_off_t payload_len; + uint8_t head[10]; + int head_len, head_total; + enum ws_dec_state state; + int cont_flags; +}; + +/* a client-side WS frame encoder, generating frame headers and + * converting payloads, tracking remaining data in current frame */ +struct ws_encoder { + curl_off_t payload_len; /* payload length of current frame */ + curl_off_t payload_remain; /* remaining payload of current */ + unsigned int xori; /* xor index */ + uint8_t mask[4]; /* 32-bit mask for this connection */ + uint8_t firstbyte; /* first byte of frame we encode */ + BIT(contfragment); /* set TRUE if the previous fragment sent was not final */ +}; + +/* Control frames are allowed up to 125 characters, rfc6455, ch. 5.5 */ +#define WS_MAX_CNTRL_LEN 125 + +struct ws_cntrl_frame { + unsigned int type; + size_t payload_len; + uint8_t payload[WS_MAX_CNTRL_LEN]; +}; + +/* A websocket connection with en- and decoder that treat frames + * and keep track of boundaries. */ +struct websocket { + struct Curl_easy *data; /* used for write callback handling */ + struct ws_decoder dec; /* decode of ws frames */ + struct ws_encoder enc; /* encode of ws frames */ + struct bufq recvbuf; /* raw data from the server */ + struct bufq sendbuf; /* raw data to be sent to the server */ + struct curl_ws_frame recvframe; /* the current WS FRAME received */ + struct ws_cntrl_frame pending; /* a control frame pending to be sent */ + size_t sendbuf_payload; /* number of payload bytes in sendbuf */ +}; + +#ifdef CURLVERBOSE +static const char *ws_frame_name_of_op(uint8_t firstbyte) +{ + switch(firstbyte & WSBIT_OPCODE_MASK) { + case WSBIT_OPCODE_CONT: + return "CONT"; + case WSBIT_OPCODE_TEXT: + return "TEXT"; + case WSBIT_OPCODE_BIN: + return "BIN"; + case WSBIT_OPCODE_CLOSE: + return "CLOSE"; + case WSBIT_OPCODE_PING: + return "PING"; + case WSBIT_OPCODE_PONG: + return "PONG"; + default: + return "???"; + } +} +#endif + +static int ws_frame_firstbyte2flags(struct Curl_easy *data, + uint8_t firstbyte, int cont_flags) +{ + switch(firstbyte) { + /* 0x00 - intermediate TEXT/BINARY fragment */ + case WSBIT_OPCODE_CONT: + if(!(cont_flags & CURLWS_CONT)) { + failf(data, "[WS] no ongoing fragmented message to resume"); + return 0; + } + return cont_flags | CURLWS_CONT; + /* 0x80 - final TEXT/BIN fragment */ + case (WSBIT_OPCODE_CONT | WSBIT_FIN): + if(!(cont_flags & CURLWS_CONT)) { + failf(data, "[WS] no ongoing fragmented message to resume"); + return 0; + } + return cont_flags & ~CURLWS_CONT; + /* 0x01 - first TEXT fragment */ + case WSBIT_OPCODE_TEXT: + if(cont_flags & CURLWS_CONT) { + failf(data, "[WS] fragmented message interrupted by new TEXT msg"); + return 0; + } + return CURLWS_TEXT | CURLWS_CONT; + /* 0x81 - unfragmented TEXT msg */ + case (WSBIT_OPCODE_TEXT | WSBIT_FIN): + if(cont_flags & CURLWS_CONT) { + failf(data, "[WS] fragmented message interrupted by new TEXT msg"); + return 0; + } + return CURLWS_TEXT; + /* 0x02 - first BINARY fragment */ + case WSBIT_OPCODE_BIN: + if(cont_flags & CURLWS_CONT) { + failf(data, "[WS] fragmented message interrupted by new BINARY msg"); + return 0; + } + return CURLWS_BINARY | CURLWS_CONT; + /* 0x82 - unfragmented BINARY msg */ + case (WSBIT_OPCODE_BIN | WSBIT_FIN): + if(cont_flags & CURLWS_CONT) { + failf(data, "[WS] fragmented message interrupted by new BINARY msg"); + return 0; + } + return CURLWS_BINARY; + /* 0x08 - first CLOSE fragment */ + case WSBIT_OPCODE_CLOSE: + failf(data, "[WS] invalid fragmented CLOSE frame"); + return 0; + /* 0x88 - unfragmented CLOSE */ + case (WSBIT_OPCODE_CLOSE | WSBIT_FIN): + return CURLWS_CLOSE; + /* 0x09 - first PING fragment */ + case WSBIT_OPCODE_PING: + failf(data, "[WS] invalid fragmented PING frame"); + return 0; + /* 0x89 - unfragmented PING */ + case (WSBIT_OPCODE_PING | WSBIT_FIN): + return CURLWS_PING; + /* 0x0a - first PONG fragment */ + case WSBIT_OPCODE_PONG: + failf(data, "[WS] invalid fragmented PONG frame"); + return 0; + /* 0x8a - unfragmented PONG */ + case (WSBIT_OPCODE_PONG | WSBIT_FIN): + return CURLWS_PONG; + /* invalid first byte */ + default: + if(firstbyte & WSBIT_RSV_MASK) + /* any of the reserved bits 0x40/0x20/0x10 are set */ + failf(data, "[WS] invalid reserved bits: %02x", firstbyte); + else + /* any of the reserved opcodes 0x3-0x7 or 0xb-0xf is used */ + failf(data, "[WS] invalid opcode: %02x", firstbyte); + return 0; + } +} + +static CURLcode ws_frame_flags2firstbyte(struct Curl_easy *data, + unsigned int flags, + bool contfragment, + uint8_t *pfirstbyte) +{ + *pfirstbyte = 0; + switch(flags & ~CURLWS_OFFSET) { + case 0: + if(contfragment) { + CURL_TRC_WS(data, "no flags given; interpreting as continuation " + "fragment for compatibility"); + *pfirstbyte = (WSBIT_OPCODE_CONT | WSBIT_FIN); + return CURLE_OK; + } + failf(data, "[WS] no flags given"); + return CURLE_BAD_FUNCTION_ARGUMENT; + case CURLWS_CONT: + if(contfragment) { + infof(data, "[WS] setting CURLWS_CONT flag without message type is " + "supported for compatibility but highly discouraged"); + *pfirstbyte = WSBIT_OPCODE_CONT; + return CURLE_OK; + } + failf(data, "[WS] No ongoing fragmented message to continue"); + return CURLE_BAD_FUNCTION_ARGUMENT; + case CURLWS_TEXT: + *pfirstbyte = contfragment ? (WSBIT_OPCODE_CONT | WSBIT_FIN) + : (WSBIT_OPCODE_TEXT | WSBIT_FIN); + return CURLE_OK; + case (CURLWS_TEXT | CURLWS_CONT): + *pfirstbyte = contfragment ? WSBIT_OPCODE_CONT : WSBIT_OPCODE_TEXT; + return CURLE_OK; + case CURLWS_BINARY: + *pfirstbyte = contfragment ? (WSBIT_OPCODE_CONT | WSBIT_FIN) + : (WSBIT_OPCODE_BIN | WSBIT_FIN); + return CURLE_OK; + case (CURLWS_BINARY | CURLWS_CONT): + *pfirstbyte = contfragment ? WSBIT_OPCODE_CONT : WSBIT_OPCODE_BIN; + return CURLE_OK; + case CURLWS_CLOSE: + *pfirstbyte = WSBIT_OPCODE_CLOSE | WSBIT_FIN; + return CURLE_OK; + case (CURLWS_CLOSE | CURLWS_CONT): + failf(data, "[WS] CLOSE frame must not be fragmented"); + return CURLE_BAD_FUNCTION_ARGUMENT; + case CURLWS_PING: + *pfirstbyte = WSBIT_OPCODE_PING | WSBIT_FIN; + return CURLE_OK; + case (CURLWS_PING | CURLWS_CONT): + failf(data, "[WS] PING frame must not be fragmented"); + return CURLE_BAD_FUNCTION_ARGUMENT; + case CURLWS_PONG: + *pfirstbyte = WSBIT_OPCODE_PONG | WSBIT_FIN; + return CURLE_OK; + case (CURLWS_PONG | CURLWS_CONT): + failf(data, "[WS] PONG frame must not be fragmented"); + return CURLE_BAD_FUNCTION_ARGUMENT; + default: + failf(data, "[WS] unknown flags: %x", flags); + return CURLE_BAD_FUNCTION_ARGUMENT; + } +} + +static void ws_dec_info(struct ws_decoder *dec, struct Curl_easy *data, + const char *msg) +{ + NOVERBOSE((void)msg); + switch(dec->head_len) { + case 0: + break; + case 1: + CURL_TRC_WS(data, "decoded %s [%s%s]", msg, + ws_frame_name_of_op(dec->head[0]), + (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL"); + break; + default: + if(dec->head_len < dec->head_total) { + CURL_TRC_WS(data, "decoded %s [%s%s](%d/%d)", msg, + ws_frame_name_of_op(dec->head[0]), + (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL", + dec->head_len, dec->head_total); + } + else { + CURL_TRC_WS(data, "decoded %s [%s%s payload=%" + FMT_OFF_T "/%" FMT_OFF_T "]", + msg, ws_frame_name_of_op(dec->head[0]), + (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL", + dec->payload_offset, dec->payload_len); + } + break; + } +} + +static CURLcode ws_send_raw_blocking(struct Curl_easy *data, + struct websocket *ws, + const char *buffer, size_t buflen); + +typedef CURLcode ws_write_payload(const uint8_t *buf, size_t buflen, + int frame_age, int frame_flags, + curl_off_t payload_offset, + curl_off_t payload_len, + void *userp, + size_t *pnwritten); + +static void ws_dec_next_frame(struct ws_decoder *dec) +{ + dec->frame_age = 0; + dec->frame_flags = 0; + dec->payload_offset = 0; + dec->payload_len = 0; + dec->head_len = dec->head_total = 0; + dec->state = WS_DEC_INIT; + /* dec->cont_flags must be carried over to next frame */ +} + +static void ws_dec_reset(struct ws_decoder *dec) +{ + dec->frame_age = 0; + dec->frame_flags = 0; + dec->payload_offset = 0; + dec->payload_len = 0; + dec->head_len = dec->head_total = 0; + dec->state = WS_DEC_INIT; + dec->cont_flags = 0; +} + +static void ws_dec_init(struct ws_decoder *dec) +{ + ws_dec_reset(dec); +} + +static CURLcode ws_dec_read_head(struct ws_decoder *dec, + struct Curl_easy *data, + struct bufq *inraw) +{ + const uint8_t *inbuf; + size_t inlen; + + while(Curl_bufq_peek(inraw, &inbuf, &inlen)) { + if(dec->head_len == 0) { + dec->head[0] = *inbuf; + Curl_bufq_skip(inraw, 1); + + dec->frame_flags = ws_frame_firstbyte2flags(data, dec->head[0], + dec->cont_flags); + if(!dec->frame_flags) { + ws_dec_reset(dec); + return CURLE_RECV_ERROR; + } + + /* fragmentation only applies to data frames (text/binary); + * control frames (close/ping/pong) do not affect the CONT status */ + if(dec->frame_flags & (CURLWS_TEXT | CURLWS_BINARY)) { + dec->cont_flags = dec->frame_flags; + } + + dec->head_len = 1; +#if 0 + ws_dec_info(dec, data, "seeing opcode"); +#endif + continue; + } + else if(dec->head_len == 1) { + dec->head[1] = *inbuf; + Curl_bufq_skip(inraw, 1); + dec->head_len = 2; + + if(dec->head[1] & WSBIT_MASK) { + /* A client MUST close a connection if it detects a masked frame. */ + failf(data, "[WS] masked input frame"); + ws_dec_reset(dec); + return CURLE_RECV_ERROR; + } + if(dec->frame_flags & CURLWS_PING && dec->head[1] > WS_MAX_CNTRL_LEN) { + /* The maximum valid size of PING frames is 125 bytes. + Accepting overlong pings would mean sending equivalent pongs! */ + failf(data, "[WS] received PING frame is too big"); + ws_dec_reset(dec); + return CURLE_RECV_ERROR; + } + if(dec->frame_flags & CURLWS_PONG && dec->head[1] > WS_MAX_CNTRL_LEN) { + /* The maximum valid size of PONG frames is 125 bytes. */ + failf(data, "[WS] received PONG frame is too big"); + ws_dec_reset(dec); + return CURLE_RECV_ERROR; + } + if(dec->frame_flags & CURLWS_CLOSE && dec->head[1] > WS_MAX_CNTRL_LEN) { + failf(data, "[WS] received CLOSE frame is too big"); + ws_dec_reset(dec); + return CURLE_RECV_ERROR; + } + + /* How long is the frame head? */ + if(dec->head[1] == 126) { + dec->head_total = 4; + continue; + } + else if(dec->head[1] == 127) { + dec->head_total = 10; + continue; + } + else { + dec->head_total = 2; + } + } + + if(dec->head_len < dec->head_total) { + dec->head[dec->head_len] = *inbuf; + Curl_bufq_skip(inraw, 1); + ++dec->head_len; + if(dec->head_len < dec->head_total) { +#if 0 + ws_dec_info(dec, data, "decoding head"); +#endif + continue; + } + } + /* got the complete frame head */ + DEBUGASSERT(dec->head_len == dec->head_total); + switch(dec->head_total) { + case 2: + dec->payload_len = dec->head[1]; + break; + case 4: + dec->payload_len = (dec->head[2] << 8) | dec->head[3]; + break; + case 10: + if(dec->head[2] > 127) { + failf(data, "[WS] frame length longer than 63 bits not supported"); + return CURLE_RECV_ERROR; + } + dec->payload_len = + (curl_off_t)dec->head[2] << 56 | + (curl_off_t)dec->head[3] << 48 | + (curl_off_t)dec->head[4] << 40 | + (curl_off_t)dec->head[5] << 32 | + (curl_off_t)dec->head[6] << 24 | + (curl_off_t)dec->head[7] << 16 | + (curl_off_t)dec->head[8] << 8 | + dec->head[9]; + break; + default: + /* this should never happen */ + DEBUGASSERT(0); + failf(data, "[WS] unexpected frame header length"); + return CURLE_RECV_ERROR; + } + + dec->frame_age = 0; + dec->payload_offset = 0; + ws_dec_info(dec, data, "head"); + return CURLE_OK; + } + return CURLE_AGAIN; +} + +static CURLcode ws_dec_pass_payload(struct ws_decoder *dec, + struct Curl_easy *data, + struct bufq *inraw, + ws_write_payload *write_cb, + void *write_ctx) +{ + const uint8_t *inbuf; + size_t inlen; + size_t nwritten; + CURLcode result; + size_t remain = curlx_sotouz_range(dec->payload_len - dec->payload_offset, + 0, SIZE_MAX); + + while(remain && Curl_bufq_peek(inraw, &inbuf, &inlen) && + !Curl_cwriter_is_paused(data)) { + if(inlen > remain) + inlen = remain; + result = write_cb(inbuf, inlen, dec->frame_age, dec->frame_flags, + dec->payload_offset, dec->payload_len, + write_ctx, &nwritten); + if(result) + return result; + Curl_bufq_skip(inraw, nwritten); + dec->payload_offset += nwritten; + remain = curlx_sotouz_range(dec->payload_len - dec->payload_offset, + 0, SIZE_MAX); + CURL_TRC_WS(data, "passed %zu bytes payload, %zu remain", + nwritten, remain); + } + + return remain ? CURLE_AGAIN : CURLE_OK; +} + +static CURLcode ws_dec_pass(struct ws_decoder *dec, + struct Curl_easy *data, + struct bufq *inraw, + ws_write_payload *write_cb, + void *write_ctx) +{ + CURLcode result; + + if(Curl_bufq_is_empty(inraw)) + return CURLE_AGAIN; + + switch(dec->state) { + case WS_DEC_INIT: + ws_dec_next_frame(dec); + dec->state = WS_DEC_HEAD; + FALLTHROUGH(); + case WS_DEC_HEAD: + result = ws_dec_read_head(dec, data, inraw); + if(result) { + if(result != CURLE_AGAIN) { + failf(data, "[WS] decode frame error %d", (int)result); + break; /* real error */ + } + /* incomplete ws frame head */ + DEBUGASSERT(Curl_bufq_is_empty(inraw)); + break; + } + /* head parsing done */ + dec->state = WS_DEC_PAYLOAD; + if(dec->payload_len == 0) { + size_t nwritten; + const uint8_t tmp = '\0'; + /* special case of a 0 length frame, need to write once */ + result = write_cb(&tmp, 0, dec->frame_age, dec->frame_flags, + 0, 0, write_ctx, &nwritten); + if(result) + return result; + dec->state = WS_DEC_INIT; + break; + } + FALLTHROUGH(); + case WS_DEC_PAYLOAD: + result = ws_dec_pass_payload(dec, data, inraw, write_cb, write_ctx); + ws_dec_info(dec, data, "passing"); + if(result) + return result; + /* payload parsing done */ + dec->state = WS_DEC_INIT; + break; + default: + /* we covered all enums above, but some code analyzers are wimps */ + result = CURLE_FAILED_INIT; + } + return result; +} + +static void update_meta(struct websocket *ws, + int frame_age, int frame_flags, + curl_off_t payload_offset, + curl_off_t payload_len, + size_t cur_len) +{ + curl_off_t bytesleft = (payload_len - payload_offset - cur_len); + + ws->recvframe.age = frame_age; + ws->recvframe.flags = frame_flags; + ws->recvframe.offset = payload_offset; + ws->recvframe.len = cur_len; + ws->recvframe.bytesleft = bytesleft; +} + +/* WebSocket decoding client writer */ +struct ws_cw_ctx { + struct Curl_cwriter super; + struct bufq buf; +}; + +static CURLcode ws_cw_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct ws_cw_ctx *ctx = writer->ctx; + (void)data; + Curl_bufq_init2(&ctx->buf, WS_CHUNK_SIZE, 1, BUFQ_OPT_SOFT_LIMIT); + return CURLE_OK; +} + +static void ws_cw_close(struct Curl_easy *data, struct Curl_cwriter *writer) +{ + struct ws_cw_ctx *ctx = writer->ctx; + (void)data; + Curl_bufq_free(&ctx->buf); +} + +struct ws_cw_dec_ctx { + struct Curl_easy *data; + struct websocket *ws; + struct Curl_cwriter *next_writer; + int cw_type; +}; + +static CURLcode ws_flush(struct Curl_easy *data, struct websocket *ws, + bool blocking); +static CURLcode ws_enc_send(struct Curl_easy *data, + struct websocket *ws, + const uint8_t *buffer, + size_t buflen, + curl_off_t fragsize, + unsigned int flags, + size_t *pnsent); +static CURLcode ws_enc_add_pending(struct Curl_easy *data, + struct websocket *ws); + +static CURLcode ws_enc_add_cntrl(struct Curl_easy *data, + struct websocket *ws, + const uint8_t *payload, + size_t plen, + unsigned int frame_type) +{ + (void)data; + DEBUGASSERT(plen <= WS_MAX_CNTRL_LEN); + if(plen > WS_MAX_CNTRL_LEN) + return CURLE_BAD_FUNCTION_ARGUMENT; + + /* Overwrite any pending frame with the new one, we keep + * only one. */ + ws->pending.type = frame_type; + ws->pending.payload_len = plen; + memcpy(ws->pending.payload, payload, plen); + return CURLE_OK; +} + +static curl_off_t ws_payload_remain(curl_off_t payload_total, + curl_off_t payload_offset, + size_t payload_buffered) +{ + curl_off_t buffered, remain = payload_total - payload_offset; + if((payload_total < 0) || (payload_offset < 0) || (remain < 0)) + return -1; + buffered = curlx_uztoso(payload_buffered); + if(remain < buffered) + return -1; + return remain - buffered; +} + +static CURLcode ws_cw_dec_next(const uint8_t *buf, size_t buflen, + int frame_age, int frame_flags, + curl_off_t payload_offset, + curl_off_t payload_len, + void *user_data, + size_t *pnwritten) +{ + struct ws_cw_dec_ctx *ctx = user_data; + struct Curl_easy *data = ctx->data; + struct websocket *ws = ctx->ws; + bool auto_pong = !data->set.ws_no_auto_pong; + curl_off_t remain; + CURLcode result; + + (void)frame_age; + *pnwritten = 0; + remain = ws_payload_remain(payload_len, payload_offset, buflen); + if(remain < 0) { + DEBUGASSERT(0); /* parameter mismatch */ + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + if(auto_pong && (frame_flags & CURLWS_PING) && !remain) { + /* auto-respond to PINGs, only works for single-frame payloads atm */ + CURL_TRC_WS(data, "auto PONG to [PING payload=%" FMT_OFF_T + "/%" FMT_OFF_T "]", payload_offset, payload_len); + /* send back the exact same content as a PONG */ + result = ws_enc_add_cntrl(data, ws, buf, buflen, CURLWS_PONG); + if(result) + return result; + } + else if(buflen || !remain) { + /* forward the decoded frame to the next client writer. */ + update_meta(ws, frame_age, frame_flags, payload_offset, + payload_len, buflen); + + CURL_TRC_WRITE(data, "[WS] pass %zu decoded bytes", buflen); + result = Curl_cwriter_write(data, ctx->next_writer, + (ctx->cw_type | CLIENTWRITE_0LEN), + (const char *)buf, buflen); + if(result) + return result; + } + *pnwritten = buflen; + return CURLE_OK; +} + +static CURLcode ws_cw_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + struct ws_cw_ctx *ctx = writer->ctx; + struct websocket *ws; + CURLcode result = CURLE_OK; + + CURL_TRC_WRITE(data, "[WS] write(len=%zu, type=%d)", nbytes, type); + if(!(type & CLIENTWRITE_BODY) || data->set.ws_raw_mode) + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); + + ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN); + if(!ws) { + failf(data, "[WS] not a websocket transfer"); + return CURLE_FAILED_INIT; + } + + if(nbytes) { + size_t nwritten; + result = Curl_bufq_write(&ctx->buf, (const uint8_t *)buf, + nbytes, &nwritten); + if(result) { + infof(data, "[WS] error adding data to buffer %d", (int)result); + return result; + } + } + + result = Curl_cwriter_flush(data, writer->next); + if(result) + goto out; + + while(!Curl_bufq_is_empty(&ctx->buf) && !Curl_cwriter_is_paused(data)) { + struct ws_cw_dec_ctx pass_ctx; + pass_ctx.data = data; + pass_ctx.ws = ws; + pass_ctx.next_writer = writer->next; + pass_ctx.cw_type = type; + result = ws_dec_pass(&ws->dec, data, &ctx->buf, + ws_cw_dec_next, &pass_ctx); + if(result == CURLE_AGAIN) { + /* insufficient amount of data, keep it for later. + * we pretend to have written all since we have a copy */ + result = CURLE_OK; + goto out; + } + else if(result) { + failf(data, "[WS] decode payload error %d", (int)result); + Curl_bufq_reset(&ctx->buf); + goto out; + } + } + + if((type & CLIENTWRITE_EOS) && !Curl_bufq_is_empty(&ctx->buf)) { + failf(data, "[WS] decode ending with %zu frame bytes remaining", + Curl_bufq_len(&ctx->buf)); + result = CURLE_RECV_ERROR; + } + +out: + if(!result) { + result = ws_flush(data, ws, Curl_api_is_in_callback(data)); + if(result == CURLE_AGAIN) + result = CURLE_OK; + } + return result; +} + +static CURLcode ws_cw_flush(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + CURLcode result = CURLE_OK; + + CURL_TRC_WRITE(data, "[ws] flush"); + if(!data->set.ws_raw_mode) { + struct ws_cw_ctx *ctx = writer->ctx; + struct websocket *ws; + + /* Frames should be written one by one, else the meta data does + * not fit. Flush the next writer first, so it does not aggregate + * our flushed data with anything it might have buffered. */ + result = Curl_cwriter_flush(data, writer->next); + if(result) + goto out; + + ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN); + if(!ws) { + failf(data, "[WS] not a websocket transfer"); + return CURLE_FAILED_INIT; + } + + while(!Curl_bufq_is_empty(&ctx->buf) && !Curl_cwriter_is_paused(data)) { + struct ws_cw_dec_ctx pass_ctx; + pass_ctx.data = data; + pass_ctx.ws = ws; + pass_ctx.next_writer = writer->next; + pass_ctx.cw_type = CLIENTWRITE_BODY; + result = ws_dec_pass(&ws->dec, data, &ctx->buf, + ws_cw_dec_next, &pass_ctx); + if(result == CURLE_AGAIN) { + /* insufficient amount of data, keep it for later. + * we pretend to have written all since we have a copy */ + result = CURLE_OK; + goto out; + } + else if(result) { + failf(data, "[WS] decode payload error %d", (int)result); + Curl_bufq_reset(&ctx->buf); + goto out; + } + } + } + +out: + if(!result) + result = Curl_cwriter_flush(data, writer->next); + return result; +} + +/* WebSocket payload decoding client writer. */ +static const struct Curl_cwtype ws_cw_decode = { + "ws-decode", + NULL, + 0, + ws_cw_init, + ws_cw_write, + ws_cw_flush, + ws_cw_close, + sizeof(struct ws_cw_ctx) +}; + +static void ws_enc_info(struct ws_encoder *enc, struct Curl_easy *data, + const char *msg) +{ + NOVERBOSE((void)enc); + NOVERBOSE((void)msg); + CURL_TRC_WS(data, "WS-ENC: %s [%s%s payload=%" + FMT_OFF_T "/%" FMT_OFF_T "]", + msg, ws_frame_name_of_op(enc->firstbyte), + (enc->firstbyte & WSBIT_FIN) ? "" : " NON-FIN", + enc->payload_len - enc->payload_remain, enc->payload_len); +} + +static void ws_enc_reset(struct ws_encoder *enc) +{ + enc->payload_remain = 0; + enc->xori = 0; + enc->contfragment = FALSE; +} + +static void ws_enc_init(struct ws_encoder *enc) +{ + ws_enc_reset(enc); +} + +/* RFC 6455 Section 5.2 + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-------+-+-------------+-------------------------------+ + |F|R|R|R| opcode|M| Payload len | Extended payload length | + |I|S|S|S| (4) |A| (7) | (16/64) | + |N|V|V|V| |S| | (if payload len==126/127) | + | |1|2|3| |K| | | + +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + + | Extended payload length continued, if payload len == 127 | + + - - - - - - - - - - - - - - - +-------------------------------+ + | |Masking-key, if MASK set to 1 | + +-------------------------------+-------------------------------+ + | Masking-key (continued) | Payload Data | + +-------------------------------- - - - - - - - - - - - - - - - + + : Payload Data continued ... : + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + | Payload Data continued ... | + +---------------------------------------------------------------+ + */ + +static CURLcode ws_enc_add_frame(struct Curl_easy *data, + struct ws_encoder *enc, + unsigned int flags, + curl_off_t payload_len, + struct bufq *out) +{ + uint8_t firstb = 0; + uint8_t head[14]; + CURLcode result; + size_t hlen, nwritten; + + if(payload_len < 0) { + failf(data, "[WS] starting new frame with negative payload length %" + FMT_OFF_T, payload_len); + return CURLE_SEND_ERROR; + } + + if(enc->payload_remain > 0) { + /* trying to write a new frame before the previous one is finished */ + failf(data, "[WS] starting new frame with %" FMT_OFF_T " bytes " + "from last one remaining to be sent", enc->payload_remain); + return CURLE_SEND_ERROR; + } + + result = ws_frame_flags2firstbyte(data, flags, (bool)enc->contfragment, + &firstb); + if(result) + return result; + + /* fragmentation only applies to data frames (text/binary); + * control frames (close/ping/pong) do not affect the CONT status */ + if(flags & (CURLWS_TEXT | CURLWS_BINARY)) { + enc->contfragment = (curl_bit)((flags & CURLWS_CONT) ? TRUE : FALSE); + } + + if(flags & CURLWS_PING && payload_len > WS_MAX_CNTRL_LEN) { + failf(data, "[WS] given PING frame is too big"); + return CURLE_TOO_LARGE; + } + if(flags & CURLWS_PONG && payload_len > WS_MAX_CNTRL_LEN) { + failf(data, "[WS] given PONG frame is too big"); + return CURLE_TOO_LARGE; + } + if(flags & CURLWS_CLOSE && payload_len > WS_MAX_CNTRL_LEN) { + failf(data, "[WS] given CLOSE frame is too big"); + return CURLE_TOO_LARGE; + } + + head[0] = enc->firstbyte = firstb; + if(payload_len > 65535) { + head[1] = 127 | WSBIT_MASK; + head[2] = (uint8_t)((payload_len >> 56) & 0xff); + head[3] = (uint8_t)((payload_len >> 48) & 0xff); + head[4] = (uint8_t)((payload_len >> 40) & 0xff); + head[5] = (uint8_t)((payload_len >> 32) & 0xff); + head[6] = (uint8_t)((payload_len >> 24) & 0xff); + head[7] = (uint8_t)((payload_len >> 16) & 0xff); + head[8] = (uint8_t)((payload_len >> 8) & 0xff); + head[9] = (uint8_t)(payload_len & 0xff); + hlen = 10; + } + else if(payload_len >= 126) { + head[1] = 126 | WSBIT_MASK; + head[2] = (uint8_t)((payload_len >> 8) & 0xff); + head[3] = (uint8_t)(payload_len & 0xff); + hlen = 4; + } + else { + head[1] = (uint8_t)payload_len | WSBIT_MASK; + hlen = 2; + } + + enc->payload_remain = enc->payload_len = payload_len; + ws_enc_info(enc, data, "sending"); + + /* 4 bytes random */ + + result = Curl_rand(data, (uint8_t *)&enc->mask, sizeof(enc->mask)); + if(result) + return result; + +#ifdef DEBUGBUILD + if(getenv("CURL_WS_FORCE_ZERO_MASK")) + /* force the bit mask to 0x00000000, effectively disabling masking */ + memset(&enc->mask, 0, sizeof(enc->mask)); +#endif + + /* add 4 bytes mask */ + memcpy(&head[hlen], &enc->mask, 4); + hlen += 4; + /* reset for payload to come */ + enc->xori = 0; + + result = Curl_bufq_write(out, head, hlen, &nwritten); + if(result) + return result; + if(nwritten != hlen) { + /* We use a bufq with SOFT_LIMIT, writing should always succeed */ + DEBUGASSERT(0); + return CURLE_SEND_ERROR; + } + return CURLE_OK; +} + +static CURLcode ws_enc_write_head(struct Curl_easy *data, + struct websocket *ws, + struct ws_encoder *enc, + unsigned int flags, + curl_off_t payload_len, + struct bufq *out) +{ + /* starting a new frame, we want a clean sendbuf. + * Any pending control frame we can add now as part of the flush. */ + if(ws->pending.type) { + CURLcode result = ws_enc_add_pending(data, ws); + if(result) + return result; + } + return ws_enc_add_frame(data, enc, flags, payload_len, out); +} + +static CURLcode ws_enc_write_payload(struct ws_encoder *enc, + struct Curl_easy *data, + const uint8_t *buf, size_t buflen, + struct bufq *out, size_t *pnwritten) +{ + CURLcode result; + size_t i, len, n, remain; + + *pnwritten = 0; + if(Curl_bufq_is_full(out)) + return CURLE_AGAIN; + + /* not the most performant way to do this */ + len = buflen; + remain = curlx_sotouz_range(enc->payload_remain, 0, SIZE_MAX); + if(remain < len) + len = remain; + + for(i = 0; i < len; ++i) { + uint8_t c = buf[i] ^ enc->mask[enc->xori]; + result = Curl_bufq_write(out, &c, 1, &n); + if(result) { + if((result != CURLE_AGAIN) || !i) + return result; + break; + } + enc->xori++; + enc->xori &= 3; + } + *pnwritten = i; + enc->payload_remain -= (curl_off_t)i; + ws_enc_info(enc, data, "buffered"); + return CURLE_OK; +} + +static CURLcode ws_enc_add_pending(struct Curl_easy *data, + struct websocket *ws) +{ + CURLcode result; + size_t n; + + if(!ws->pending.type) /* no pending frame here */ + return CURLE_OK; + if(ws->enc.payload_remain) /* in the middle of another frame */ + return CURLE_AGAIN; + + result = ws_enc_add_frame(data, &ws->enc, ws->pending.type, + (curl_off_t)ws->pending.payload_len, + &ws->sendbuf); + if(result) { + CURL_TRC_WS(data, "ws_enc_cntrl(), error adding head: %d", + (int)result); + goto out; + } + result = ws_enc_write_payload(&ws->enc, data, ws->pending.payload, + ws->pending.payload_len, + &ws->sendbuf, &n); + if(result) { + CURL_TRC_WS(data, "ws_enc_cntrl(), error adding payload: %d", + (int)result); + goto out; + } + if(n != ws->pending.payload_len) { + DEBUGASSERT(0); /* buffer should always be able to take all */ + CURL_TRC_WS(data, "ws_enc_cntrl(), error added only %zu/%zu payload,", + n, ws->pending.payload_len); + result = CURLE_SEND_ERROR; + goto out; + } + /* the frame should be complete now */ + DEBUGASSERT(!ws->enc.payload_remain); + memset(&ws->pending, 0, sizeof(ws->pending)); + +out: + return result; +} + +static CURLcode ws_enc_send(struct Curl_easy *data, + struct websocket *ws, + const uint8_t *buffer, + size_t buflen, + curl_off_t fragsize, + unsigned int flags, + size_t *pnsent) +{ + size_t n; + CURLcode result = CURLE_OK; + + DEBUGASSERT(!data->set.ws_raw_mode); + *pnsent = 0; + + if(ws->enc.payload_remain || !Curl_bufq_is_empty(&ws->sendbuf)) { + /* a frame is ongoing with payload buffered or more payload + * that needs to be encoded into the buffer */ + if(buflen < ws->sendbuf_payload) { + /* We have been called with LESS buffer data than before. This + * is not how it is supposed too work. */ + failf(data, "[WS] curl_ws_send() called with smaller 'buflen' than " + "bytes already buffered in previous call, %zu vs %zu", + buflen, ws->sendbuf_payload); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if((curl_off_t)buflen > + (ws->enc.payload_remain + (curl_off_t)ws->sendbuf_payload)) { + /* too large buflen beyond payload length of frame */ + failf(data, "[WS] unaligned frame size (sending %zu instead of " + "%" FMT_OFF_T ")", buflen, + (curl_off_t)(ws->enc.payload_remain + ws->sendbuf_payload)); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + } + else { + result = ws_flush(data, ws, Curl_api_is_in_callback(data)); + if(result) + return result; + + result = ws_enc_write_head(data, ws, &ws->enc, flags, + (flags & CURLWS_OFFSET) ? + fragsize : (curl_off_t)buflen, + &ws->sendbuf); + if(result) { + CURL_TRC_WS(data, "curl_ws_send(), error writing frame head %d", + (int)result); + return result; + } + } + + /* While there is either sendbuf to flush OR more payload to encode... */ + while(!Curl_bufq_is_empty(&ws->sendbuf) || (buflen > ws->sendbuf_payload)) { + /* Try to add more payload to sendbuf */ + if(buflen > ws->sendbuf_payload) { + size_t prev_len = Curl_bufq_len(&ws->sendbuf); + result = ws_enc_write_payload(&ws->enc, data, + buffer + ws->sendbuf_payload, + buflen - ws->sendbuf_payload, + &ws->sendbuf, &n); + if(result && (result != CURLE_AGAIN)) + return result; + ws->sendbuf_payload += Curl_bufq_len(&ws->sendbuf) - prev_len; + if(!ws->sendbuf_payload) { + return CURLE_AGAIN; + } + } + + /* flush, blocking when in callback */ + result = ws_flush(data, ws, Curl_api_is_in_callback(data)); + if(!result && ws->sendbuf_payload > 0) { + *pnsent += ws->sendbuf_payload; + buffer += ws->sendbuf_payload; + buflen -= ws->sendbuf_payload; + ws->sendbuf_payload = 0; + } + else if(result == CURLE_AGAIN) { + if(ws->sendbuf_payload > Curl_bufq_len(&ws->sendbuf)) { + /* blocked, part of payload bytes remain, report length + * that we managed to send. */ + size_t flushed = (ws->sendbuf_payload - Curl_bufq_len(&ws->sendbuf)); + *pnsent += flushed; + ws->sendbuf_payload -= flushed; + return CURLE_OK; + } + else { + /* blocked before sending headers or 1st payload byte. We cannot report + * OK on 0-length send (caller counts only payload) and EAGAIN */ + CURL_TRC_WS(data, "EAGAIN flushing sendbuf, payload_encoded: %zu/%zu", + ws->sendbuf_payload, buflen); + DEBUGASSERT(*pnsent == 0); + return CURLE_AGAIN; + } + } + else + return result; /* real error sending the data */ + } + return CURLE_OK; +} + +struct cr_ws_ctx { + struct Curl_creader super; + BIT(read_eos); /* we read an EOS from the next reader */ + BIT(eos); /* we have returned an EOS */ +}; + +static CURLcode cr_ws_init(struct Curl_easy *data, struct Curl_creader *reader) +{ + (void)data; + (void)reader; + return CURLE_OK; +} + +static void cr_ws_close(struct Curl_easy *data, struct Curl_creader *reader) +{ + (void)data; + (void)reader; +} + +static CURLcode cr_ws_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *pnread, bool *peos) +{ + struct cr_ws_ctx *ctx = reader->ctx; + CURLcode result = CURLE_OK; + size_t nread, n; + struct websocket *ws; + bool eos; + + *pnread = 0; + if(ctx->eos) { + *peos = TRUE; + return CURLE_OK; + } + + ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN); + if(!ws) { + failf(data, "[WS] not a websocket transfer"); + return CURLE_FAILED_INIT; + } + + if(Curl_bufq_is_empty(&ws->sendbuf)) { + if(ctx->read_eos) { + ctx->eos = TRUE; + *peos = TRUE; + return CURLE_OK; + } + + if(ws->enc.payload_remain) { + CURL_TRC_WS(data, "current frame, %" FMT_OFF_T " remaining", + ws->enc.payload_remain); + blen = curlx_sotouz_range(ws->enc.payload_remain, 0, blen); + } + + result = Curl_creader_read(data, reader->next, buf, blen, &nread, &eos); + if(result) + return result; + ctx->read_eos = eos; + + if(!Curl_bufq_is_empty(&ws->sendbuf)) { + /* client_read started a new frame, we disregard any eos reported */ + ctx->read_eos = FALSE; + Curl_creader_clear_eos(data, reader->next); + } + else if(!nread) { + /* nothing to convert, return this right away */ + if(ctx->read_eos) + ctx->eos = TRUE; + *pnread = nread; + *peos = (bool)ctx->eos; + goto out; + } + + if(!ws->enc.payload_remain && Curl_bufq_is_empty(&ws->sendbuf)) { + /* encode the data as a new BINARY frame */ + result = ws_enc_write_head(data, ws, &ws->enc, CURLWS_BINARY, nread, + &ws->sendbuf); + if(result) + goto out; + } + + result = ws_enc_write_payload(&ws->enc, data, (uint8_t *)buf, + nread, &ws->sendbuf, &n); + if(result) + goto out; + CURL_TRC_READ(data, "cr_ws_read, added %zu payload, len=%zu", nread, n); + } + + DEBUGASSERT(!Curl_bufq_is_empty(&ws->sendbuf)); + *peos = FALSE; + result = Curl_bufq_cread(&ws->sendbuf, buf, blen, pnread); + if(!result && ctx->read_eos && Curl_bufq_is_empty(&ws->sendbuf)) { + /* no more data, read all, done. */ + ctx->eos = TRUE; + *peos = TRUE; + } + +out: + CURL_TRC_READ(data, "cr_ws_read(len=%zu) -> %d, nread=%zu, eos=%d", + blen, (int)result, *pnread, *peos); + return result; +} + +static const struct Curl_crtype ws_cr_encode = { + "ws-encode", + cr_ws_init, + cr_ws_read, + cr_ws_close, + Curl_creader_def_needs_rewind, + Curl_creader_def_total_length, + Curl_creader_def_resume_from, + Curl_creader_def_cntrl, + Curl_creader_def_is_paused, + Curl_creader_def_done, + sizeof(struct cr_ws_ctx) +}; + +struct wsfield { + const char *name; + const char *val; +}; + +CURLcode Curl_ws_request(struct Curl_easy *data, struct dynbuf *req) +{ + unsigned int i; + CURLcode result = CURLE_OK; + uint8_t rand[16]; + char *randstr; + size_t randlen; + char keyval[40]; + struct SingleRequest *k = &data->req; + struct wsfield heads[] = { + { + /* The request MUST contain an |Upgrade| header field whose value + MUST include the "websocket" keyword. */ + "Upgrade", "websocket" + }, + { + /* The request MUST include a header field with the name + |Sec-WebSocket-Version|. The value of this header field MUST be + 13. */ + "Sec-WebSocket-Version", "13", + }, + { + /* The request MUST include a header field with the name + |Sec-WebSocket-Key|. The value of this header field MUST be a nonce + consisting of a randomly selected 16-byte value that has been + base64-encoded (see Section 4 of [RFC4648]). The nonce MUST be + selected randomly for each connection. */ + "Sec-WebSocket-Key", NULL, + } + }; + heads[2].val = &keyval[0]; + + /* 16 bytes random */ + result = Curl_rand(data, rand, sizeof(rand)); + if(result) + return result; + result = curlx_base64_encode(rand, sizeof(rand), &randstr, &randlen); + if(result) + return result; + DEBUGASSERT(randlen < sizeof(keyval)); + if(randlen >= sizeof(keyval)) { + curlx_free(randstr); + return CURLE_FAILED_INIT; + } + curlx_strcopy(keyval, sizeof(keyval), randstr, randlen); + curlx_free(randstr); + for(i = 0; !result && (i < CURL_ARRAYSIZE(heads)); i++) { + if(!Curl_checkheaders(data, heads[i].name, strlen(heads[i].name))) { + result = curlx_dyn_addf(req, "%s: %s\r\n", heads[i].name, heads[i].val); + } + } + data->state.http_hd_upgrade = TRUE; + k->upgr101 = UPGR101_WS; + data->conn->bits.upgrade_in_progress = TRUE; + return result; +} + +static void ws_conn_dtor(void *key, size_t klen, void *entry) +{ + struct websocket *ws = entry; + (void)key; + (void)klen; + Curl_bufq_free(&ws->recvbuf); + Curl_bufq_free(&ws->sendbuf); + curlx_free(ws); +} + +/* + * 'nread' is number of bytes of websocket data already in the buffer at + * 'mem'. + */ +CURLcode Curl_ws_accept(struct Curl_easy *data, + const char *mem, size_t nread) +{ + struct SingleRequest *k = &data->req; + struct websocket *ws; + struct Curl_cwriter *ws_dec_writer = NULL; + struct Curl_creader *ws_enc_reader = NULL; + CURLcode result; + + DEBUGASSERT(data->conn); + ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN); + if(!ws) { + size_t chunk_size = WS_CHUNK_SIZE; + ws = curlx_calloc(1, sizeof(*ws)); + if(!ws) + return CURLE_OUT_OF_MEMORY; +#ifdef DEBUGBUILD + { + const char *p = getenv("CURL_WS_CHUNK_SIZE"); + if(p) { + curl_off_t l; + if(!curlx_str_number(&p, &l, 1 * 1024 * 1024)) + chunk_size = (size_t)l; + } + } +#endif + CURL_TRC_WS(data, "WS, using chunk size %zu", chunk_size); + Curl_bufq_init2(&ws->recvbuf, chunk_size, WS_CHUNK_COUNT, + BUFQ_OPT_SOFT_LIMIT); + Curl_bufq_init2(&ws->sendbuf, chunk_size, WS_CHUNK_COUNT, + BUFQ_OPT_SOFT_LIMIT); + ws_dec_init(&ws->dec); + ws_enc_init(&ws->enc); + result = Curl_conn_meta_set(data->conn, CURL_META_PROTO_WS_CONN, + ws, ws_conn_dtor); + if(result) + return result; + } + else { + Curl_bufq_reset(&ws->recvbuf); + ws_dec_reset(&ws->dec); + ws_enc_reset(&ws->enc); + } + /* Verify the Sec-WebSocket-Accept response. + + The sent value is the base64 encoded version of a SHA-1 hash done on the + |Sec-WebSocket-Key| header field concatenated with + the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11". */ + + /* If the response includes a |Sec-WebSocket-Extensions| header field and + this header field indicates the use of an extension that was not present + in the client's handshake (the server has indicated an extension not + requested by the client), the client MUST Fail the WebSocket Connection. + */ + + /* If the response includes a |Sec-WebSocket-Protocol| header field + and this header field indicates the use of a subprotocol that was + not present in the client's handshake (the server has indicated a + subprotocol not requested by the client), the client MUST Fail + the WebSocket Connection. */ + + infof(data, "[WS] Received 101, switch to WebSocket"); + + /* Install our client writer that decodes WS frames payload */ + result = Curl_cwriter_create(&ws_dec_writer, data, &ws_cw_decode, + CURL_CW_CONTENT_DECODE); + if(result) + goto out; + result = Curl_cwriter_add(data, ws_dec_writer); + if(result) + goto out; + ws_dec_writer = NULL; /* owned by transfer now */ + + k->header = FALSE; /* we will not get more response headers */ + + if(data->set.connect_only) { + /* In CONNECT_ONLY setup, the payloads from `mem` need to be received + * when using `curl_ws_recv/curl_easy_recv` later on, after this transfer + * is already marked as DONE. + * Since `curl_easy_recv()` is also supposed to work, we need + * to buffer the data at connection level. See #22107 */ + if(nread) { + result = Curl_cf_recvbuf_add(data, data->conn, FIRSTSOCKET, + (const uint8_t *)mem, nread); + if(result) + goto out; + } + CURL_REQ_CLEAR_RECV(data); /* read no more content */ + } + else { /* !connect_only */ + if(data->set.method == HTTPREQ_PUT) { + CURL_TRC_WS(data, "UPLOAD set, add ws-encode reader"); + result = Curl_creader_set_fread(data, -1); + if(result) + goto out; + + if(!data->set.ws_raw_mode) { + /* Add our client reader encoding WS BINARY frames */ + result = Curl_creader_create(&ws_enc_reader, data, &ws_cr_encode, + CURL_CR_CONTENT_ENCODE); + if(result) + goto out; + result = Curl_creader_add(data, ws_enc_reader); + if(result) + goto out; + ws_enc_reader = NULL; /* owned by transfer now */ + } + + /* start over with sending */ + data->req.eos_read = FALSE; + data->req.upload_done = FALSE; + CURL_REQ_SET_SEND(data); + } + + /* Then pass any additional data to the writers */ + if(nread) { + result = Curl_client_write(data, CLIENTWRITE_BODY, mem, nread); + if(result) + goto out; + } + } + + k->upgr101 = UPGR101_RECEIVED; + k->header = FALSE; /* we will not get more responses */ + +out: + if(ws_dec_writer) + Curl_cwriter_free(data, ws_dec_writer); + if(ws_enc_reader) + Curl_creader_free(data, ws_enc_reader); + if(result) + CURL_TRC_WS(data, "Curl_ws_accept() failed -> %d", (int)result); + else + CURL_TRC_WS(data, "websocket established, %s mode", + data->set.connect_only ? "connect-only" : "callback"); + return result; +} + +struct ws_collect { + struct Curl_easy *data; + struct websocket *ws; + uint8_t *buffer; + size_t buflen; + size_t bufidx; + int frame_age; + int frame_flags; + curl_off_t payload_offset; + curl_off_t payload_len; + bool written; +}; + +static CURLcode ws_client_collect(const uint8_t *buf, size_t buflen, + int frame_age, int frame_flags, + curl_off_t payload_offset, + curl_off_t payload_len, + void *userp, + size_t *pnwritten) +{ + struct ws_collect *ctx = userp; + struct Curl_easy *data = ctx->data; + bool auto_pong = !data->set.ws_no_auto_pong; + curl_off_t remain; + CURLcode result = CURLE_OK; + + *pnwritten = 0; + remain = ws_payload_remain(payload_len, payload_offset, buflen); + if(remain < 0) { + DEBUGASSERT(0); /* parameter mismatch */ + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + if(!ctx->bufidx) { + /* first write */ + ctx->frame_age = frame_age; + ctx->frame_flags = frame_flags; + ctx->payload_offset = payload_offset; + ctx->payload_len = payload_len; + } + + if(auto_pong && (frame_flags & CURLWS_PING) && !remain) { + /* auto-respond to PINGs, only works for single-frame payloads atm */ + CURL_TRC_WS(data, "auto PONG to [PING payload=%" FMT_OFF_T + "/%" FMT_OFF_T "]", payload_offset, payload_len); + /* send back the exact same content as a PONG */ + result = ws_enc_add_cntrl(ctx->data, ctx->ws, buf, buflen, CURLWS_PONG); + if(result) + return result; + *pnwritten = buflen; + } + else { + size_t write_len; + + ctx->written = TRUE; + DEBUGASSERT(ctx->buflen >= ctx->bufidx); + write_len = CURLMIN(buflen, ctx->buflen - ctx->bufidx); + if(!write_len) { + if(!buflen) /* 0 length write, we accept that */ + return CURLE_OK; + return CURLE_AGAIN; /* no more space */ + } + memcpy(ctx->buffer + ctx->bufidx, buf, write_len); + ctx->bufidx += write_len; + *pnwritten = write_len; + } + return result; +} + +static CURLcode nw_in_recv(void *reader_ctx, + uint8_t *buf, size_t buflen, + size_t *pnread) +{ + struct Curl_easy *data = reader_ctx; + return Curl_easy_recv(data, buf, buflen, pnread); +} + +CURLcode curl_ws_recv(CURL *curl, void *buffer, + size_t buflen, size_t *recv, + const struct curl_ws_frame **metap) +{ + struct Curl_eapi_guard guard; + CURLcode result = CURLE_OK; + + *recv = 0; + *metap = NULL; + if(CURL_EAPI_ENTER(&guard, curl, ws_recv, &result)) { + struct Curl_easy *data = curl; + struct connectdata *conn; + struct websocket *ws; + struct ws_collect ctx; + + if(buflen && !buffer) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + + conn = data->conn; + if(!conn) { + /* Unhappy hack with lifetimes of transfers and connection */ + if(!data->set.connect_only) { + failf(data, "[WS] CONNECT_ONLY is required"); + result = CURLE_UNSUPPORTED_PROTOCOL; + goto out; + } + + Curl_getconnectinfo(data, &conn); + if(!conn) { + failf(data, "[WS] connection not found"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + } + ws = Curl_conn_meta_get(conn, CURL_META_PROTO_WS_CONN); + if(!ws) { + failf(data, "[WS] connection is not setup for websocket"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + + memset(&ctx, 0, sizeof(ctx)); + ctx.data = data; + ctx.ws = ws; + ctx.buffer = buffer; + ctx.buflen = buflen; + + while(1) { + /* receive more when our buffer is empty */ + if(Curl_bufq_is_empty(&ws->recvbuf)) { + size_t n; + result = Curl_bufq_slurp(&ws->recvbuf, nw_in_recv, data, &n); + if(result) + goto out; + else if(n == 0) { + /* connection closed */ + infof(data, "[WS] connection expectedly closed?"); + result = CURLE_GOT_NOTHING; + goto out; + } + CURL_TRC_WS(data, "curl_ws_recv, added %zu bytes from network", + Curl_bufq_len(&ws->recvbuf)); + } + + result = ws_dec_pass(&ws->dec, data, &ws->recvbuf, + ws_client_collect, &ctx); + if(result == CURLE_AGAIN) { + if(!ctx.written) { + ws_dec_info(&ws->dec, data, "need more input"); + continue; /* nothing written, try more input */ + } + break; + } + else if(result) { + goto out; + } + else if(ctx.written) { + /* The decoded frame is passed back to our caller. + * There are frames like PING were we auto-respond to and + * that we do not return. For these `ctx.written` is not set. */ + break; + } + } + + /* update frame information to be passed back */ + update_meta(ws, ctx.frame_age, ctx.frame_flags, ctx.payload_offset, + ctx.payload_len, ctx.bufidx); + *metap = &ws->recvframe; + *recv = ws->recvframe.len; + CURL_TRC_WS(data, "curl_ws_recv(len=%zu) -> %zu bytes (frame at %" + FMT_OFF_T ", %" FMT_OFF_T " left)", + buflen, *recv, ws->recvframe.offset, + ws->recvframe.bytesleft); + /* all's well, try to send any pending control. we do not know + * when the application will call `curl_ws_send()` again. */ + if(!data->set.ws_raw_mode && ws->pending.type) { + CURLcode r2 = ws_enc_add_pending(data, ws); + if(!r2) + (void)ws_flush(data, ws, Curl_api_is_in_callback(data)); + } + result = CURLE_OK; + } +out: + CURL_EAPI_LEAVE(&guard); + return result; +} + +static CURLcode ws_flush(struct Curl_easy *data, struct websocket *ws, + bool blocking) +{ + CURLcode result; + + /* If there is space, add any pending control frame */ + if(Curl_bufq_len(&ws->sendbuf) < ws->sendbuf.chunk_size) { + result = ws_enc_add_pending(data, ws); + if(result && (result != CURLE_AGAIN)) + return result; + } + + if(!Curl_bufq_is_empty(&ws->sendbuf)) { + const uint8_t *out; + size_t outlen, n; +#ifdef DEBUGBUILD + /* Simulate a blocking send after this chunk has been sent */ + bool eagain_next = FALSE; + size_t chunk_egain = 0; + const char *p = getenv("CURL_WS_CHUNK_EAGAIN"); + if(p) { + curl_off_t l; + if(!curlx_str_number(&p, &l, 1 * 1024 * 1024)) + chunk_egain = (size_t)l; + } +#endif + + while(Curl_bufq_peek(&ws->sendbuf, &out, &outlen)) { +#ifdef DEBUGBUILD + if(eagain_next) + return CURLE_AGAIN; + if(chunk_egain && (outlen > chunk_egain)) { + outlen = chunk_egain; + eagain_next = TRUE; + } +#endif + if(blocking) { + result = ws_send_raw_blocking(data, ws, (const char *)out, outlen); + n = result ? 0 : outlen; + } + else if(data->set.connect_only || Curl_api_is_in_callback(data)) + result = Curl_senddata(data, out, outlen, &n); + else { + result = Curl_xfer_send(data, out, outlen, FALSE, &n); + if(!result && !n && outlen) + result = CURLE_AGAIN; + } + + if(result == CURLE_AGAIN) { + CURL_TRC_WS(data, "flush EAGAIN, %zu bytes remain in buffer", + Curl_bufq_len(&ws->sendbuf)); + return result; + } + else if(result) { + failf(data, "[WS] flush, write error %d", (int)result); + return result; + } + else { + CURL_TRC_WS(data, "flushed %zu bytes", n); + Curl_bufq_skip(&ws->sendbuf, n); + } + } + } + return CURLE_OK; +} + +static CURLcode ws_send_raw_blocking(struct Curl_easy *data, + struct websocket *ws, + const char *buffer, size_t buflen) +{ + CURLcode result = CURLE_OK; + size_t nwritten; + + if(!data) + return result; + + (void)ws; + while(buflen) { + result = Curl_xfer_send(data, buffer, buflen, FALSE, &nwritten); + if(result) + return result; + DEBUGASSERT(nwritten <= buflen); + buffer += nwritten; + buflen -= nwritten; + if(buflen) { + curl_socket_t sock = data->conn->sock[FIRSTSOCKET]; + timediff_t left_ms; + int ev; + + CURL_TRC_WS(data, "ws_send_raw_blocking() partial, %zu left to send", + buflen); + left_ms = Curl_timeleft_ms(data); + if(left_ms < 0) { + failf(data, "[WS] Timeout waiting for socket becoming writable"); + return CURLE_SEND_ERROR; + } + + /* POLLOUT socket */ + if(sock == CURL_SOCKET_BAD) + return CURLE_SEND_ERROR; + ev = SOCKET_WRITABLE(sock, left_ms ? left_ms : 500); + if(ev < 0) { + failf(data, "[WS] Error while waiting for socket becoming writable"); + return CURLE_SEND_ERROR; + } + } + } + return result; +} + +static CURLcode ws_send_raw(struct Curl_easy *data, const void *buffer, + size_t buflen, size_t *pnwritten) +{ + struct websocket *ws; + CURLcode result; + + ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN); + if(!ws) { + failf(data, "[WS] Not a websocket transfer"); + return CURLE_SEND_ERROR; + } + if(!buflen) + return CURLE_OK; + + if(Curl_api_is_in_callback(data)) { + /* When invoked from inside callbacks, we do a blocking send as the + * callback will probably not implement partial writes that may then + * mess up the ws framing subsequently. + * We need any pending data to be flushed before sending. */ + result = ws_flush(data, ws, TRUE); + if(result) + return result; + result = ws_send_raw_blocking(data, ws, buffer, buflen); + if(!result) + *pnwritten = buflen; + } + else { + /* We need any pending data to be sent or EAGAIN this call. */ + result = ws_flush(data, ws, FALSE); + if(result) + return result; + result = Curl_senddata(data, buffer, buflen, pnwritten); + } + + CURL_TRC_WS(data, "ws_send_raw(len=%zu) -> %d, %zu", + buflen, (int)result, *pnwritten); + return result; +} + +CURLcode curl_ws_send(CURL *curl, const void *buffer_arg, + size_t buflen, size_t *sent, + curl_off_t fragsize, + unsigned int flags) +{ + struct Curl_eapi_guard guard; + CURLcode result = CURLE_OK; + + if(CURL_EAPI_ENTER(&guard, curl, ws_send, &result)) { + struct websocket *ws; + const uint8_t *buffer = buffer_arg; + struct Curl_easy *data = curl; + size_t ndummy; + size_t *pnsent = sent ? sent : &ndummy; + + CURL_TRC_WS(data, "curl_ws_send(len=%zu, fragsize=%" FMT_OFF_T + ", flags=%x), raw=%d", + buflen, fragsize, flags, data->set.ws_raw_mode); + + *pnsent = 0; + + if(!buffer && buflen) { + failf(data, "[WS] buffer is NULL when buflen is not"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + + if(!data->conn && data->set.connect_only) { + result = Curl_connect_only_attach(data); + if(result) + goto out; + } + if(!data->conn) { + failf(data, "[WS] No associated connection"); + result = CURLE_SEND_ERROR; + goto out; + } + ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN); + if(!ws) { + failf(data, "[WS] Not a websocket transfer"); + result = CURLE_SEND_ERROR; + goto out; + } + + if(data->set.ws_raw_mode) { + /* In raw mode, we write directly to the connection */ + /* try flushing any content still waiting to be sent. */ + result = ws_flush(data, ws, FALSE); + if(result) + goto out; + + if(!buffer) { + failf(data, "[WS] buffer is NULL in raw mode"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + if(!sent) { + failf(data, "[WS] sent is NULL in raw mode"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + if(fragsize || flags) { + failf(data, "[WS] fragsize and flags must be zero in raw mode"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto out; + } + result = ws_send_raw(data, buffer, buflen, pnsent); + goto out; + } + + /* Not RAW mode, we do the frame encoding */ + result = ws_enc_send(data, ws, buffer, buflen, fragsize, flags, pnsent); + CURL_TRC_WS(data, "curl_ws_send(len=%zu, fragsize=%" FMT_OFF_T + ", flags=%x, raw=%d) -> %d, %zu", + buflen, fragsize, flags, data->set.ws_raw_mode, (int)result, + *pnsent); + } +out: + CURL_EAPI_LEAVE(&guard); + return result; +} + +static CURLcode ws_setup_conn(struct Curl_easy *data, + struct connectdata *conn) +{ + /* WebSocket is 1.1 only (for now) */ + data->state.http_neg.accept_09 = FALSE; + data->state.http_neg.only_10 = FALSE; + data->state.http_neg.wanted = CURL_HTTP_V1x; + data->state.http_neg.allowed = CURL_HTTP_V1x; + return Curl_http_setup_conn(data, conn); +} + +const struct curl_ws_frame *curl_ws_meta(CURL *curl) +{ + /* we only return something for websocket, called from within the callback + when not using raw mode */ + struct Curl_easy *data = curl; + if(GOOD_EASY_HANDLE(data) && Curl_api_is_in_callback(data) && + data->conn && !data->set.ws_raw_mode) { + struct websocket *ws; + ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN); + if(ws) + return &ws->recvframe; + } + return NULL; +} + +CURL_EXTERN CURLcode curl_ws_start_frame(CURL *curl, + unsigned int flags, + curl_off_t frame_len) +{ + struct Curl_eapi_guard guard; + CURLcode result = CURLE_OK; + + if(CURL_EAPI_ENTER(&guard, curl, ws_start_frame, &result)) { + struct Curl_easy *data = curl; + struct websocket *ws; + + if(data->set.ws_raw_mode) { + failf(data, "cannot curl_ws_start_frame() with CURLWS_RAW_MODE enabled"); + result = CURLE_FAILED_INIT; + goto out; + } + + CURL_TRC_WS(data, "curl_ws_start_frame(flags=%x, frame_len=%" FMT_OFF_T, + flags, frame_len); + + if(!data->conn) { + failf(data, "[WS] No associated connection"); + result = CURLE_SEND_ERROR; + goto out; + } + ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN); + if(!ws) { + failf(data, "[WS] Not a websocket transfer"); + result = CURLE_SEND_ERROR; + goto out; + } + + if(ws->enc.payload_remain) { + failf(data, "[WS] previous frame not finished"); + result = CURLE_SEND_ERROR; + goto out; + } + + result = ws_enc_write_head(data, ws, &ws->enc, flags, frame_len, + &ws->sendbuf); + if(result) + CURL_TRC_WS(data, "curl_start_frame(), error adding frame head %d", + (int)result); + } +out: + CURL_EAPI_LEAVE(&guard); + return result; +} + +const struct Curl_protocol Curl_protocol_ws = { + ws_setup_conn, /* setup_connection */ + Curl_http, /* do_it */ + Curl_http_done, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_pollset */ + Curl_http_doing_pollset, /* doing_pollset */ + ZERO_NULL, /* domore_pollset */ + Curl_http_perform_pollset, /* perform_pollset */ + ZERO_NULL, /* disconnect */ + Curl_http_write_resp, /* write_resp */ + Curl_http_write_resp_hd, /* write_resp_hd */ + ZERO_NULL, /* connection_is_dead */ + ZERO_NULL, /* attach connection */ + Curl_http_follow, /* follow */ +}; + +#else + +CURLcode curl_ws_recv(CURL *curl, void *buffer, size_t buflen, + size_t *recv, + const struct curl_ws_frame **metap) +{ + (void)curl; + (void)buffer; + (void)buflen; + (void)recv; + (void)metap; + return CURLE_NOT_BUILT_IN; +} + +CURLcode curl_ws_send(CURL *curl, const void *buffer, + size_t buflen, size_t *sent, + curl_off_t fragsize, + unsigned int flags) +{ + (void)curl; + (void)buffer; + (void)buflen; + (void)sent; + (void)fragsize; + (void)flags; + return CURLE_NOT_BUILT_IN; +} + +const struct curl_ws_frame *curl_ws_meta(CURL *data) +{ + (void)data; + return NULL; +} + +CURL_EXTERN CURLcode curl_ws_start_frame(CURL *curl, + unsigned int flags, + curl_off_t frame_len) +{ + (void)curl; + (void)flags; + (void)frame_len; + return CURLE_NOT_BUILT_IN; +} + +#endif /* !CURL_DISABLE_WEBSOCKETS */ diff --git a/platforms/ios/Packages/CCurl/Vendor/curl/lib/ws.h b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ws.h new file mode 100644 index 0000000000..71b5b3fff0 --- /dev/null +++ b/platforms/ios/Packages/CCurl/Vendor/curl/lib/ws.h @@ -0,0 +1,44 @@ +#ifndef HEADER_CURL_WS_H +#define HEADER_CURL_WS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP) + +extern const struct Curl_protocol Curl_protocol_ws; + +/* meta key for storing protocol meta at connection */ +#define CURL_META_PROTO_WS_CONN "meta:proto:ws:conn" + +CURLcode Curl_ws_request(struct Curl_easy *data, struct dynbuf *req); +CURLcode Curl_ws_accept(struct Curl_easy *data, + const char *mem, size_t nread); + +#else +#define Curl_ws_request(x, y) CURLE_OK +#define Curl_ws_free(x) Curl_nop_stmt +#endif + +#endif /* HEADER_CURL_WS_H */ diff --git a/platforms/ios/ads/AMBAdBase.swift b/platforms/ios/ads/AMBAdBase.swift new file mode 100644 index 0000000000..beb7bbb831 --- /dev/null +++ b/platforms/ios/ads/AMBAdBase.swift @@ -0,0 +1,102 @@ +import GoogleMobileAds +import UIKit + +class AMBAdBase: NSObject { + weak var plugin: AMBPlugin? + let id: String + private let configuredAdUnitId: String + var adUnitId: String { plugin?.adEnvironment.unitID(for: adFormat, configured: configuredAdUnitId) ?? configuredAdUnitId } + let adFormat: String + let adRequest: Request + private var loadID = UUID() + private var loading: AMBContext? + private(set) var destroyed = false + + init?(_ ctx: AMBContext) { + guard let id = ctx.optId(), let adUnitId = ctx.optAdUnitID() else { return nil } + self.id = id + configuredAdUnitId = adUnitId + let format = String(ctx.optString("cls", "").dropLast(2)) + adFormat = format.prefix(1).lowercased() + format.dropFirst() + adRequest = ctx.optGADRequest() + plugin = ctx.plugin + super.init() + } + + var isActive: Bool { !destroyed && plugin?.ads[id] === self } + var isPresenting: Bool { false } + func isLoaded() -> Bool { false } + func load(_ ctx: AMBContext) { ctx.reject("Ad format does not support load") } + func show(_ ctx: AMBContext) { ctx.reject("Ad format does not support show") } + func hide(_ ctx: AMBContext) { ctx.reject("Ad format does not support hide") } + + func destroy() { + destroyed = true + loading?.reject("Ad is destroyed") + loading = nil + loadID = UUID() + } + + func beginLoad(_ ctx: AMBContext) -> UUID { + loading?.reject("Ad load was replaced") + loading = ctx + loadID = UUID() + return loadID + } + + func acceptsLoad(_ token: UUID) -> Bool { isActive && loading != nil && loadID == token } + + func finishLoad(_ token: UUID, error: Error? = nil) { + guard acceptsLoad(token) else { return } + let ctx = loading + loading = nil + if let error { + emit(AMBEvents.adLoadFail, error) + ctx?.reject(error) + } else { + emit(AMBEvents.adLoad) + ctx?.resolve() + } + } + + func emit(_ event: String, _ data: [String: Any] = [:]) { + guard isActive else { return } + var payload = data + payload["adId"] = id + plugin?.emit(event, data: payload) + } + + func emit(_ event: String, _ error: Error) { + emit(event, ["message": error.localizedDescription, "code": (error as NSError).code]) + } + + func emit(_ event: String, _ reward: AdReward) { + emit(event, ["reward": ["amount": reward.amount, "type": reward.type]]) + } + + func emit(_ event: String, _ size: AdSize) { emit(event, sizeData(size)) } + + func sizeData(_ size: AdSize) -> [String: Any] { + let scale = plugin?.viewController?.view.window?.screen.scale ?? 1 + return ["size": ["width": size.size.width, "height": size.size.height, + "widthInPixels": round(size.size.width * scale), + "heightInPixels": round(size.size.height * scale)]] + } + + func emitPaid(_ value: AdValue, response: ResponseInfo?) { + var data: [String: Any] = ["adUnitId": adUnitId, "adFormat": adFormat, + "valueMicros": value.value.multiplying(by: 1_000_000).int64Value, + "currencyCode": value.currencyCode, "precision": value.precision.rawValue] + let source = response?.loadedAdNetworkResponseInfo + data["adSourceName"] = source?.adSourceName + data["adSourceId"] = source?.adSourceID + data["adSourceInstanceName"] = source?.adSourceInstanceName + data["adSourceInstanceId"] = source?.adSourceInstanceID + for (key, sourceKey) in [("mediationGroupName", "mediation_group_name"), + ("mediationABTestName", "mediation_ab_test_name"), + ("mediationABTestVariant", "mediation_ab_test_variant")] { + data[key] = response?.extras[sourceKey] as? String + } + emit(AMBEvents.adPaid, data) + } +} diff --git a/platforms/ios/ads/AMBAdEnvironment.swift b/platforms/ios/ads/AMBAdEnvironment.swift new file mode 100644 index 0000000000..93ce73bbe5 --- /dev/null +++ b/platforms/ios/ads/AMBAdEnvironment.swift @@ -0,0 +1,85 @@ +import StoreKit + +struct AMBAdEnvironment { + let verifiedEnvironment: AppStore.Environment? + @MainActor private static let cache = AMBAdEnvironmentCache() + + @MainActor + static func current() async -> AMBAdEnvironment { + #if DEBUG || targetEnvironment(simulator) + // Debug and simulator installs have no App Store app transaction. + return AMBAdEnvironment(verifiedEnvironment: nil) + #else + return await cache.current { + if case .verified(let transaction) = try await AppTransaction.shared { + return transaction.environment + } + return nil + } + #endif + } + + @MainActor + static func resolve(timeout: Duration = .seconds(3), + lookup: @escaping () async throws -> AppStore.Environment?) async -> AMBAdEnvironment { + // A task group would still wait for a StoreKit operation that ignores cancellation. + await withCheckedContinuation { continuation in + var pending: CheckedContinuation<AMBAdEnvironment, Never>? = continuation + var deadline: Task<Void, Never>? + let request = Task { @MainActor in + let environment = try? await lookup() + guard let completion = pending else { return } + pending = nil + deadline?.cancel() + completion.resume(returning: AMBAdEnvironment(verifiedEnvironment: environment)) + } + deadline = Task { @MainActor in + do { try await Task.sleep(for: timeout) } + catch { return } + guard let completion = pending else { return } + pending = nil + request.cancel() + completion.resume(returning: AMBAdEnvironment(verifiedEnvironment: nil)) + } + } + } + + func unitID(for format: String, configured: String) -> String { + guard verifiedEnvironment == .sandbox || verifiedEnvironment == .xcode else { return configured } + // Google's demo units are used only in Apple's verified testing environments. + let suffix: String + switch format { + case "appOpen": suffix = "5575463023" + case "banner": suffix = "2435281174" + case "interstitial": suffix = "4411468910" + case "rewarded": suffix = "1712485313" + case "rewardedInterstitial": suffix = "6978759866" + case "native": suffix = "3986624511" + default: return configured + } + return "ca-app-pub-3940256099942544/" + suffix + } +} + +@MainActor +final class AMBAdEnvironmentCache { + private var verified: AMBAdEnvironment? + private var pending: Task<AMBAdEnvironment, Never>? + private var retryAfter: ContinuousClock.Instant? + private let now: () -> ContinuousClock.Instant + + init(now: @escaping () -> ContinuousClock.Instant = { .now }) { self.now = now } + + func current(lookup: @escaping () async throws -> AppStore.Environment?) async -> AMBAdEnvironment { + if let verified { return verified } + if let pending { return await pending.value } + if let retryAfter, now() < retryAfter { return AMBAdEnvironment(verifiedEnvironment: nil) } + let request = Task { await AMBAdEnvironment.resolve(lookup: lookup) } + pending = request + let result = await request.value + pending = nil + if result.verifiedEnvironment != nil { verified = result } + else { retryAfter = now().advanced(by: .seconds(30)) } + return result + } +} diff --git a/platforms/ios/ads/AMBAppOpenAd.swift b/platforms/ios/ads/AMBAppOpenAd.swift new file mode 100644 index 0000000000..85d01fb577 --- /dev/null +++ b/platforms/ios/ads/AMBAppOpenAd.swift @@ -0,0 +1,45 @@ +import Foundation +import GoogleMobileAds + +class AMBAppOpenAd: AMBFullScreen { + + var mAd: AppOpenAd? + + override func isLoaded() -> Bool { + return mAd != nil && !presenting + } + + override func load(_ ctx: AMBContext) { + guard !presenting else { ctx.reject("Ad is presenting"); return } + clear() + let token = beginLoad(ctx) + + AppOpenAd.load( + with: self.adUnitId, + request: adRequest, + completionHandler: { [weak self] ad, error in + guard let self, self.acceptsLoad(token) else { return } + if let error { + self.finishLoad(token, error: error) + return + } + ad?.fullScreenContentDelegate = self + ad?.paidEventHandler = { [weak self, weak ad] value in self?.emitPaid(value, response: ad?.responseInfo) } + self.mAd = ad + + self.finishLoad(token) + }) + } + + override func show(_ ctx: AMBContext) { + guard let ad = mAd, let controller = preparePresentation(ctx) else { return } + ad.present(from: controller) + ctx.resolve(true) + } + + override func clear() { + mAd?.fullScreenContentDelegate = nil + mAd?.paidEventHandler = nil + mAd = nil + } +} diff --git a/platforms/ios/ads/AMBBanner.swift b/platforms/ios/ads/AMBBanner.swift new file mode 100644 index 0000000000..28925e4f5c --- /dev/null +++ b/platforms/ios/ads/AMBBanner.swift @@ -0,0 +1,105 @@ +import GoogleMobileAds +import UIKit + +final class AMBBanner: AMBAdBase, BannerViewDelegate, AdSizeDelegate { + var makeBanner: (AdSize) -> BannerView = { BannerView(adSize: $0) } + let options: AMBContext + let position: String + let offset: CGFloat? + private(set) var bannerView: BannerView? + private(set) var visible = false + private enum LoadState { case idle, loading, loaded } + private var loadState = LoadState.idle + + override init?(_ ctx: AMBContext) { + options = ctx + position = ctx.optPosition() + offset = ctx.optOffset() + super.init(ctx) + } + + override func isLoaded() -> Bool { loadState == .loaded } + + override func load(_ ctx: AMBContext) { + guard loadState == .idle else { ctx.resolve(); return } + if bannerView == nil { + let banner = makeBanner(options.optAdSize()) + banner.delegate = self + banner.adSizeDelegate = self + banner.rootViewController = plugin?.viewController + banner.adUnitID = adUnitId + banner.paidEventHandler = { [weak self, weak banner] value in + self?.emitPaid(value, response: banner?.responseInfo) + } + bannerView = banner + } + loadState = .loading + bannerView?.load(adRequest) + ctx.resolve() + } + + override func show(_ ctx: AMBContext) { + guard bannerView != nil, isActive else { ctx.resolve(false); return } + visible = true + plugin?.banners.show(self) + ctx.resolve(true) + } + + override func hide(_ ctx: AMBContext) { + removeView() + ctx.resolve() + } + + override func destroy() { + removeView() + bannerView?.delegate = nil + bannerView?.adSizeDelegate = nil + bannerView?.paidEventHandler = nil + bannerView?.rootViewController = nil + bannerView = nil + loadState = .idle + super.destroy() + } + + func updateSize() { + guard let bannerView, let size = options.opt("size") as? [String: Any], + size["adaptive"] != nil, size["width"] == nil else { return } + let newSize = options.optAdSize() + if !isAdSizeEqualToSize(size1: bannerView.adSize, size2: newSize) { + bannerView.adSize = newSize + } + } + + func bannerViewDidReceiveAd(_ bannerView: BannerView) { + guard isActive, self.bannerView === bannerView, loadState != .idle else { return } + loadState = .loaded + emit(AMBEvents.adLoad, sizeData(bannerView.adSize)) + emit(AMBEvents.bannerLoad) + emit(AMBEvents.bannerSize, bannerView.adSize) + plugin?.banners.layout() + } + + func bannerView(_ bannerView: BannerView, didFailToReceiveAdWithError error: Error) { + guard isActive, self.bannerView === bannerView else { return } + loadState = .idle + removeView() + emit(AMBEvents.adLoadFail, error) + } + + func bannerViewDidRecordImpression(_ bannerView: BannerView) { emit(AMBEvents.adImpression) } + func bannerViewDidRecordClick(_ bannerView: BannerView) { emit(AMBEvents.adClick) } + func bannerViewWillPresentScreen(_ bannerView: BannerView) { emit(AMBEvents.adShow) } + func bannerViewDidDismissScreen(_ bannerView: BannerView) { emit(AMBEvents.adDismiss) } + + func adView(_ bannerView: BannerView, willChangeAdSizeTo size: AdSize) { + emit(AMBEvents.bannerSize, size) + emit(AMBEvents.bannerSizeChange, size) + DispatchQueue.main.async { [weak self] in self?.plugin?.banners.layout() } + } + + private func removeView() { + visible = false + bannerView?.removeFromSuperview() + plugin?.banners.hide(self) + } +} diff --git a/platforms/ios/ads/AMBBannerLayout.swift b/platforms/ios/ads/AMBBannerLayout.swift new file mode 100644 index 0000000000..4811b117e2 --- /dev/null +++ b/platforms/ios/ads/AMBBannerLayout.swift @@ -0,0 +1,73 @@ +import GoogleMobileAds +import UIKit + +final class AMBBannerLayout { + private weak var plugin: AMBPlugin? + private var banners: [AMBBanner] = [] + private var marginTop: CGFloat = 0 + private var marginBottom: CGFloat = 0 + private var layingOut = false + + init(plugin: AMBPlugin) { self.plugin = plugin } + + func show(_ banner: AMBBanner) { + if !banners.contains(where: { $0 === banner }) { banners.append(banner) } + layout() + } + + func hide(_ banner: AMBBanner) { + banners.removeAll { $0 === banner } + layout() + } + + func reset() { + banners.removeAll() + marginTop = 0 + marginBottom = 0 + plugin?.viewController?.setContentInsets(top: 0, bottom: 0) + } + + func configure(_ ctx: AMBContext) { + if let color = ctx.optBackgroundColor() { plugin?.viewController?.view.backgroundColor = color } + if let margin = ctx.optMarginTop(), margin.isFinite { marginTop = max(0, margin) } + if let margin = ctx.optMarginBottom(), margin.isFinite { marginBottom = max(0, margin) } + layout() + ctx.resolve() + } + + func layout() { + guard !layingOut, let controller = plugin?.viewController else { return } + layingOut = true + defer { layingOut = false } + if controller.isFullscreenLayout { + for banner in banners { banner.bannerView?.isHidden = true } + return + } + let root = controller.view! + let safe = root.safeAreaLayoutGuide.layoutFrame + let bottom = min(safe.maxY, root.keyboardLayoutGuide.layoutFrame.minY) + var topHeight: CGFloat = 0 + var bottomHeight: CGFloat = 0 + for banner in banners where banner.visible && banner.isActive && banner.isLoaded() { + banner.updateSize() + guard let view = banner.bannerView else { continue } + if view.superview !== root { root.addSubview(view) } + view.isHidden = false + let size = view.adSize.size + var y: CGFloat + if let offset = banner.offset { + y = banner.position == "top" ? offset : root.bounds.height - offset - size.height + } else if banner.position == "top" { + if topHeight == 0 { topHeight = marginTop } + y = safe.minY + topHeight + topHeight += size.height + } else { + if bottomHeight == 0 { bottomHeight = marginBottom } + bottomHeight += size.height + y = bottom - bottomHeight + } + view.frame = CGRect(x: safe.midX - size.width / 2, y: y, width: size.width, height: size.height) + } + controller.setContentInsets(top: topHeight, bottom: bottomHeight) + } +} diff --git a/platforms/ios/ads/AMBContext.swift b/platforms/ios/ads/AMBContext.swift new file mode 100644 index 0000000000..0bd73d5367 --- /dev/null +++ b/platforms/ios/ads/AMBContext.swift @@ -0,0 +1,132 @@ +import GoogleMobileAds +import UIKit + +final class AMBContext: AMBCoreContext { + weak var plugin: AMBPlugin? + let args: [Any] + let opts: [String: Any] + let callback: Callback + let generation: UUID + private var settled = false + + init(_ plugin: AMBPlugin, _ args: [Any], _ callback: Callback) { + self.plugin = plugin + self.args = args + self.opts = args.first as? [String: Any] ?? [:] + self.callback = callback + generation = plugin.generation + } + + var isCurrent: Bool { plugin?.generation == generation } + func has(_ name: String) -> Bool { opts[name] != nil } + func opt(_ name: String) -> Any? { opts[name] } + func opt0() -> Any? { args.first } + func optBool(_ name: String) -> Bool? { opt(name) as? Bool } + func optFloat(_ name: String) -> Float? { (opt(name) as? NSNumber)?.floatValue } + func optInt(_ name: String) -> Int? { opt(name) as? Int } + func optString(_ name: String, _ fallback: String) -> String { opt(name) as? String ?? fallback } + func optStringArray(_ name: String) -> [String]? { opt(name) as? [String] } + + func resolve() { finish(nil) } + func resolve(_ value: Bool) { finish(value) } + func resolve(_ value: UInt) { finish(value) } + func resolve(_ value: [String: Any]) { finish(value) } + + func reject(_ message: String) { + guard !settled else { return } + settled = true + if isCurrent { callback.error(message) } + } + + private func finish(_ value: Any?) { + guard !settled else { return } + settled = true + if isCurrent { callback.success(value) } + } + + func optOffset() -> CGFloat? { + return opt("offset") as? CGFloat + } + + func optBackgroundColor() -> UIColor? { + if let bgColor = opt("backgroundColor") as? NSDictionary, + let r = bgColor["r"] as? CGFloat, + let g = bgColor["g"] as? CGFloat, + let b = bgColor["b"] as? CGFloat, + let a = bgColor["a"] as? CGFloat { + return UIColor(red: r / 255, green: g / 255, blue: b / 255, alpha: a / 255) + } + return nil + } + + func optMarginTop() -> CGFloat? { + return opt("marginTop") as? CGFloat + } + + func optMarginBottom() -> CGFloat? { + return opt("marginBottom") as? CGFloat + } + + // swiftlint:disable cyclomatic_complexity + func optAdSize() -> AdSize { + if let adSizeType = opt("size") as? Int { + switch adSizeType { + case 0: + return AdSizeBanner + case 1: + return AdSizeLargeBanner + case 2: + return AdSizeMediumRectangle + case 3: + return AdSizeFullBanner + case 4: + return AdSizeLeaderboard + default: break + } + } + if let adSizeDict = opt("size") as? NSDictionary { + if let adaptive = adSizeDict["adaptive"] as? String { + var width = plugin?.viewController?.view.safeAreaLayoutGuide.layoutFrame.width ?? 320 + if let w = adSizeDict["width"] as? CGFloat { + width = w + } + if adaptive == "inline", + let maxHeight = adSizeDict["maxHeight"] as? CGFloat { + return inlineAdaptiveBanner(width: width, maxHeight: maxHeight) + } else { + // Keep the compact anchored size; the newer large helpers increase editor insets. + switch adSizeDict["orientation"] as? String { + case "portrait": + return portraitAnchoredAdaptiveBanner(width: width) + case "landscape": + return landscapeAnchoredAdaptiveBanner(width: width) + default: + return currentOrientationAnchoredAdaptiveBanner(width: width) + } + } + } else if let width = adSizeDict["width"] as? Int, + let height = adSizeDict["height"] as? Int { + return adSizeFor(cgSize: CGSize(width: width, height: height)) + } + } + return AdSizeBanner + } + // swiftlint:enable cyclomatic_complexity + + func optGADServerSideVerificationOptions() -> ServerSideVerificationOptions? { + guard let ssv = opt("serverSideVerification") as? NSDictionary + else { + return nil + } + + let options = ServerSideVerificationOptions.init() + if let customData = ssv.value(forKey: "customData") as? String { + options.customRewardText = customData + } + if let userId = ssv.value(forKey: "userId") as? String { + options.userIdentifier = userId + } + return options + } + +} diff --git a/platforms/ios/ads/AMBCore.swift b/platforms/ios/ads/AMBCore.swift new file mode 100644 index 0000000000..4b36acf8b9 --- /dev/null +++ b/platforms/ios/ads/AMBCore.swift @@ -0,0 +1,152 @@ +import Foundation +import GoogleMobileAds + +protocol AMBCoreContext { + var plugin: AMBPlugin? { get } + func has(_ name: String) -> Bool + func optBool(_ name: String) -> Bool? + func optFloat(_ name: String) -> Float? + func optInt(_ name: String) -> Int? + func optString(_ name: String, _ defaultValue: String) -> String + func optStringArray(_ name: String) -> [String]? + + func resolve(_ data: [String: Any]) + func resolve(_ data: Bool) + + func reject(_ msg: String) +} + +extension AMBCoreContext { + func optString(_ name: String) -> String? { + if has(name) { + return optString(name, "") + } + return nil + } + + func optAppMuted() -> Bool? { + return optBool("appMuted") + } + + func optAppVolume() -> Float? { + return optFloat("appVolume") + } + + func optId() -> String? { + return optString("id") + } + + func optPosition() -> String { + return optString("position", "bottom") + } + + func optAdUnitID() -> String? { + return optString("adUnitId") + } + + func optAd() -> AMBAdBase? { + guard let id = optId(), + let ad = plugin?.ads[id] + else { + return nil + } + return ad + } + + func optAdOrError() -> AMBAdBase? { + if let ad = optAd() { + return ad + } else { + reject("Ad not found: \(optId() ?? "-")") + return nil + } + } + + func optGADMaxAdContentRating() -> GADMaxAdContentRating? { + switch optString("maxAdContentRating") { + case "G": + return GADMaxAdContentRating.general + case "MA": + return GADMaxAdContentRating.matureAudience + case "PG": + return GADMaxAdContentRating.parentalGuidance + case "T": + return GADMaxAdContentRating.teen + default: + return nil + } + } + + func optChildDirectedTreatmentTag() -> Bool? { + return optBool("tagForChildDirectedTreatment") + } + + func optUnderAgeOfConsentTag() -> Bool? { + return optBool("tagForUnderAgeOfConsent") + } + + func optTestDeviceIds() -> [String]? { + return optStringArray("testDeviceIds") + } + + func optGADRequest() -> Request { + let request = Request() + request.scene = plugin?.viewController?.view.window?.windowScene + if let contentURL = optString("contentUrl") { + request.contentURL = contentURL + } + if let keywords = optStringArray("keywords") { + request.keywords = keywords + } + let extras = Extras() + if let npa = optString("npa") { + extras.additionalParameters = ["npa": npa] + } + request.register(extras) + return request + } + + func resolve() { + resolve([:]) + } + + func resolve(_ data: Bool) { + resolve(["value": data]) + } + + func reject() { + return reject(NSError(domain: "AdMob", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid ad options"])) + } + + func reject(_ error: Error) { + reject(error.localizedDescription) + } + + @MainActor + func configure() { + if let muted = optAppMuted() { + MobileAds.shared.isApplicationMuted = muted + } + if let volume = optAppVolume() { + MobileAds.shared.applicationVolume = volume + } + + let requestConfiguration = MobileAds.shared.requestConfiguration + if let maxAdContentRating = optGADMaxAdContentRating() { + requestConfiguration.maxAdContentRating = maxAdContentRating + } + plugin?.configureAgeTreatment(childDirected: optChildDirectedTreatmentTag(), underAgeOfConsent: optUnderAgeOfConsentTag()) + if let testDevices = optTestDeviceIds() { + requestConfiguration.testDeviceIdentifiers = testDevices + } + if let sameAppKey = optBool("sameAppKey") { + requestConfiguration.setPublisherFirstPartyIDEnabled(sameAppKey) + } + if let + publisherFirstPartyIDEnabled = optBool("publisherFirstPartyIDEnabled") { + requestConfiguration.setPublisherFirstPartyIDEnabled(publisherFirstPartyIDEnabled) + } + + resolve() + } +} diff --git a/platforms/ios/ads/AMBFullScreen.swift b/platforms/ios/ads/AMBFullScreen.swift new file mode 100644 index 0000000000..e3f86e910a --- /dev/null +++ b/platforms/ios/ads/AMBFullScreen.swift @@ -0,0 +1,60 @@ +import GoogleMobileAds +import UIKit + +class AMBFullScreen: AMBAdBase, FullScreenContentDelegate { + private(set) var presenting = false + override var isPresenting: Bool { presenting } + + func preparePresentation(_ ctx: AMBContext) -> UIViewController? { + guard isActive, !presenting, let plugin, plugin.presentedAd == nil, + let controller = plugin.viewController, controller.view.window != nil, + controller.presentedViewController == nil, + controller.view.window?.windowScene?.activationState == .foregroundActive else { + ctx.resolve(false) + return nil + } + presenting = true + plugin.presentedAd = self + return controller + } + + @MainActor + func recoverPresentation() -> Bool { + guard isActive, plugin?.canRecoverPresentation == true else { return false } + // The JS dismissal event may have been lost even when the SDK cleared presenting. + didFinishPresentation() + return true + } + + func clear() {} + + override func destroy() { + if presenting { + plugin?.viewController?.dismiss(animated: false) + presenting = false + if plugin?.presentedAd === self { plugin?.presentedAd = nil } + } + clear() + super.destroy() + } + + func adDidRecordImpression(_ ad: FullScreenPresentingAd) { emit(AMBEvents.adImpression) } + func adDidRecordClick(_ ad: FullScreenPresentingAd) { emit(AMBEvents.adClick) } + func adWillPresentFullScreenContent(_ ad: FullScreenPresentingAd) { emit(AMBEvents.adShow) } + + func ad(_ ad: FullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) { + didFinishPresentation() + emit(AMBEvents.adShowFail, error) + } + + func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) { + didFinishPresentation() + emit(AMBEvents.adDismiss) + } + + private func didFinishPresentation() { + presenting = false + if plugin?.presentedAd === self { plugin?.presentedAd = nil } + clear() + } +} diff --git a/platforms/ios/ads/AMBGenerated.swift b/platforms/ios/ads/AMBGenerated.swift new file mode 100644 index 0000000000..0af738fd64 --- /dev/null +++ b/platforms/ios/ads/AMBGenerated.swift @@ -0,0 +1,45 @@ +struct AMBBannerPosition { + static let bottom = "bottom" + static let top = "top" +} + +struct AMBEvents { + static let adClick = "admob.ad.click" + static let adDismiss = "admob.ad.dismiss" + static let adImpression = "admob.ad.impression" + static let adLoad = "admob.ad.load" + static let adLoadFail = "admob.ad.loadfail" + static let adPaid = "admob.ad.paid" + static let adReward = "admob.ad.reward" + static let adShow = "admob.ad.show" + static let adShowFail = "admob.ad.showfail" + static let bannerClick = "admob.banner.click" + static let bannerClose = "admob.banner.close" + static let bannerImpression = "admob.banner.impression" + static let bannerLoad = "admob.banner.load" + static let bannerLoadFail = "admob.banner.loadfail" + static let bannerOpen = "admob.banner.open" + static let bannerSize = "admob.banner.size" + static let bannerSizeChange = "admob.banner.sizechange" + static let interstitialDismiss = "admob.interstitial.dismiss" + static let interstitialImpression = "admob.interstitial.impression" + static let interstitialLoad = "admob.interstitial.load" + static let interstitialLoadFail = "admob.interstitial.loadfail" + static let interstitialShow = "admob.interstitial.show" + static let interstitialShowFail = "admob.interstitial.showfail" + static let ready = "admob.ready" + static let rewardedDismiss = "admob.rewarded.dismiss" + static let rewardedImpression = "admob.rewarded.impression" + static let rewardedInterstitialDismiss = "admob.rewardedi.dismiss" + static let rewardedInterstitialImpression = "admob.rewardedi.impression" + static let rewardedInterstitialLoad = "admob.rewardedi.load" + static let rewardedInterstitialLoadFail = "admob.rewardedi.loadfail" + static let rewardedInterstitialReward = "admob.rewardedi.reward" + static let rewardedInterstitialShow = "admob.rewardedi.show" + static let rewardedInterstitialShowFail = "admob.rewardedi.showfail" + static let rewardedLoad = "admob.rewarded.load" + static let rewardedLoadFail = "admob.rewarded.loadfail" + static let rewardedReward = "admob.rewarded.reward" + static let rewardedShow = "admob.rewarded.show" + static let rewardedShowFail = "admob.rewarded.showfail" +} diff --git a/platforms/ios/ads/AMBInterstitial.swift b/platforms/ios/ads/AMBInterstitial.swift new file mode 100644 index 0000000000..8b4813963e --- /dev/null +++ b/platforms/ios/ads/AMBInterstitial.swift @@ -0,0 +1,44 @@ +import GoogleMobileAds + +class AMBInterstitial: AMBFullScreen { + var mAd: InterstitialAd? + + override func isLoaded() -> Bool { + return self.mAd != nil && !presenting + } + + override func load(_ ctx: AMBContext) { + guard !presenting else { ctx.reject("Ad is presenting"); return } + clear() + let token = beginLoad(ctx) + + InterstitialAd.load( + with: adUnitId, + request: adRequest, + completionHandler: { [weak self] ad, error in + guard let self, self.acceptsLoad(token) else { return } + if let error { + self.finishLoad(token, error: error) + return + } + + self.mAd = ad + ad?.fullScreenContentDelegate = self + ad?.paidEventHandler = { [weak self, weak ad] value in self?.emitPaid(value, response: ad?.responseInfo) } + + self.finishLoad(token) + }) + } + + override func show(_ ctx: AMBContext) { + guard let ad = mAd, let controller = preparePresentation(ctx) else { return } + ad.present(from: controller) + ctx.resolve(true) + } + + override func clear() { + mAd?.fullScreenContentDelegate = nil + mAd?.paidEventHandler = nil + mAd = nil + } +} diff --git a/platforms/ios/ads/AMBNativeAd.swift b/platforms/ios/ads/AMBNativeAd.swift new file mode 100644 index 0000000000..3e01e5d6e2 --- /dev/null +++ b/platforms/ios/ads/AMBNativeAd.swift @@ -0,0 +1,104 @@ +import Foundation +import GoogleMobileAds +import UIKit + +protocol AMBNativeAdViewProvider: NSObjectProtocol { + func createView(_ nativeAd: NativeAd) -> UIView? + func didShow(_ ad: AMBNativeAd) + func didHide(_ ad: AMBNativeAd) +} + +extension AMBNativeAdViewProvider { + func didShow(_ ad: AMBNativeAd) {} + func didHide(_ ad: AMBNativeAd) {} +} + +final class AMBNativeAd: AMBAdBase, NativeAdLoaderDelegate, NativeAdDelegate { + static var providers: [String: AMBNativeAdViewProvider] = ["default": AMNAdViewProvider()] + private let viewProvider: AMBNativeAdViewProvider + private var loader: AdLoader? + private var nativeAd: NativeAd? + private var loadToken: UUID? + private var nativeView: UIView? + + override init?(_ ctx: AMBContext) { + guard let provider = Self.providers[ctx.optString("view", "default")] else { return nil } + viewProvider = provider + super.init(ctx) + } + + override func load(_ ctx: AMBContext) { + clear() + loadToken = beginLoad(ctx) + let loader = AdLoader(adUnitID: adUnitId, rootViewController: plugin?.viewController, + adTypes: [.native], options: nil) + self.loader = loader + loader.delegate = self + loader.load(adRequest) + } + + override func isLoaded() -> Bool { nativeAd != nil } + + override func show(_ ctx: AMBContext) { + guard let ad = nativeAd, let root = plugin?.viewController?.view, + let webView = plugin?.webView else { ctx.resolve(false); return } + if nativeView == nil { nativeView = viewProvider.createView(ad) } + guard let view = nativeView else { ctx.reject("Native ad view is unavailable"); return } + if let x = ctx.opt("x") as? Double, let y = ctx.opt("y") as? Double, + let width = ctx.opt("width") as? Double, let height = ctx.opt("height") as? Double { + guard x.isFinite, y.isFinite, width.isFinite, height.isFinite, width > 0, height > 0 else { + ctx.reject("Invalid native ad frame"); return + } + let frame = CGRect(x: x, y: y, width: width, height: height) + view.frame = webView.convert(frame, to: root) + } + if view.superview !== root { root.addSubview(view) } + view.isHidden = false + viewProvider.didShow(self) + ctx.resolve(true) + } + + override func hide(_ ctx: AMBContext) { + nativeView?.isHidden = true + viewProvider.didHide(self) + ctx.resolve() + } + + override func destroy() { + clear() + super.destroy() + } + + func adLoader(_ adLoader: AdLoader, didReceive nativeAd: NativeAd) { + guard loader === adLoader, let token = loadToken, acceptsLoad(token) else { return } + self.nativeAd = nativeAd + nativeAd.delegate = self + nativeAd.paidEventHandler = { [weak self, weak nativeAd] value in + self?.emitPaid(value, response: nativeAd?.responseInfo) + } + finishLoad(token) + loadToken = nil + } + + func adLoader(_ adLoader: AdLoader, didFailToReceiveAdWithError error: Error) { + guard loader === adLoader, let token = loadToken else { return } + finishLoad(token, error: error) + loadToken = nil + } + + func nativeAdDidRecordImpression(_ nativeAd: NativeAd) { emit(AMBEvents.adImpression) } + func nativeAdDidRecordClick(_ nativeAd: NativeAd) { emit(AMBEvents.adClick) } + func nativeAdWillPresentScreen(_ nativeAd: NativeAd) { emit(AMBEvents.adShow) } + func nativeAdDidDismissScreen(_ nativeAd: NativeAd) { emit(AMBEvents.adDismiss) } + + private func clear() { + loader?.delegate = nil + loader = nil + nativeAd?.delegate = nil + nativeAd?.paidEventHandler = nil + nativeAd = nil + nativeView?.removeFromSuperview() + nativeView = nil + loadToken = nil + } +} diff --git a/platforms/ios/ads/AMBPlugin.swift b/platforms/ios/ads/AMBPlugin.swift new file mode 100644 index 0000000000..aa93db6d10 --- /dev/null +++ b/platforms/ios/ads/AMBPlugin.swift @@ -0,0 +1,216 @@ +import AppTrackingTransparency +import GoogleMobileAds +import UIKit +import WebKit + +final class AMBPlugin: BaseService { + var ads: [String: AMBAdBase] = [:] + private(set) var generation = UUID() + weak var presentedAd: AMBFullScreen? + private var readyCallback: Callback? + private var events: [[String: Any]] = [] + private var starting: [AMBContext] = [] + private var started = false + private var childDirected = false + private var underAgeOfConsent = false + @MainActor private lazy var tracking = AMBTrackingAuthorization() + private(set) var adEnvironment = AMBAdEnvironment(verifiedEnvironment: nil) + private weak var registeredWebView: WKWebView? + lazy var banners = AMBBannerLayout(plugin: self) + lazy var privacy = AMBPrivacy(plugin: self) + + override func exec(action: String, args: [Any], callback: Callback) { + DispatchQueue.main.async { [self] in + execute(action, AMBContext(self, args, callback)) + } + } + + override func reset() { + DispatchQueue.main.async { [self] in + clearAds() + privacy.resetPresentation() + starting.forEach { $0.reject("Ad initialization was cancelled") } + starting.removeAll() + readyCallback?.release() + readyCallback = nil + events.removeAll() + generation = UUID() + tracking.cancel() + } + } + + @MainActor + func configureAgeTreatment(childDirected: Bool?, underAgeOfConsent: Bool?) { + guard childDirected != nil || underAgeOfConsent != nil else { return } + if let childDirected { self.childDirected = childDirected } + if let underAgeOfConsent { self.underAgeOfConsent = underAgeOfConsent } + MobileAds.shared.requestConfiguration.ageRestrictedTreatment = self.childDirected || self.underAgeOfConsent ? .child : .unspecified + } + + @MainActor + var canRecoverPresentation: Bool { + guard UIApplication.shared.applicationState == .active, + let controller = viewController, + controller.view.window?.windowScene?.activationState == .foregroundActive, + controller.presentedViewController == nil, + controller.transitionCoordinator == nil else { return false } + return true + } + + @MainActor + func recoverPresentation(_ id: String) -> Bool { + guard let ad = ads[id] else { return canRecoverPresentation } + return (ad as? AMBFullScreen)?.recoverPresentation() ?? false + } + + func clearAds() { + for ad in ads.values { ad.destroy() } + ads.removeAll() + presentedAd = nil + banners.reset() + } + + func emit(_ event: String, data: Any = NSNull()) { + let payload: [String: Any] = ["type": event, "data": data] + if let readyCallback { readyCallback.success(payload, keep: true) } + else if events.count < 100 { events.append(payload) } + } + + @MainActor + private func execute(_ action: String, _ ctx: AMBContext) { + switch action { + case "ready": + readyCallback?.release() + readyCallback = ctx.callback + for event in events { ctx.callback.success(event, keep: true) } + events.removeAll() + emit(AMBEvents.ready, data: ["isRunningInTestLab": false]) + case "configure", "configRequest": ctx.configure() + case "start": start(ctx) + case "setAppMuted": + guard let muted = ctx.opt0() as? Bool else { ctx.reject("Expected a boolean"); return } + MobileAds.shared.isApplicationMuted = muted + ctx.resolve() + case "setAppVolume": + guard let volume = ctx.opt0() as? Float, volume.isFinite, (0...1).contains(volume) else { + ctx.reject("Expected a volume from 0 to 1"); return + } + MobileAds.shared.applicationVolume = volume + ctx.resolve() + case "requestTrackingAuthorization": + tracking.authorize { result in + switch result { + case .success(let status): ctx.resolve(status.rawValue) + case .failure(let error): ctx.reject(error) + } + } + case "privacyGetState": ctx.resolve(privacy.state) + case "privacyGatherConsent": privacy.gather(ctx) + case "privacyShowOptions": privacy.showOptions(ctx) + case "privacyResetForTesting": privacy.resetForTesting(ctx) + case "adCreate": create(ctx) + case "adDestroy": + guard let id = ctx.optId() else { ctx.reject("id is required"); return } + ads.removeValue(forKey: id)?.destroy() + ctx.resolve() + case "adIsLoaded": + if let ad = ctx.optAdOrError() { ctx.resolve(ad.isLoaded()) } + case "adLoad", "adShow": + guard privacy.canRequestAds else { ctx.reject("Gather ad consent before requesting ads"); return } + guard started else { ctx.reject("Initialize ads before requesting ads"); return } + guard let ad = ctx.optAdOrError() else { return } + if action == "adLoad" { ad.load(ctx) } + else if ad is AMBBanner || ad.isLoaded() { ad.show(ctx) } + else { ctx.resolve(false) } + case "adRecoverPresentation": + guard let id = ctx.optId() else { ctx.reject("id is required"); return } + ctx.resolve(recoverPresentation(id)) + case "adHide": ctx.optAdOrError()?.hide(ctx) + case "bannerConfig": banners.configure(ctx) + case "webviewGoto": + // Open the SDK integration page without granting it the app's native bridge. + guard let text = ctx.opt0() as? String, let url = URL(string: text), + ["https", "http"].contains(url.scheme?.lowercased() ?? "") else { + ctx.reject("Expected an HTTP or HTTPS URL"); return + } + let controller = AdsIntegrationViewController(url: url) + guard let host = viewController, host.presentedViewController == nil else { + ctx.reject("Another view is already presented"); return + } + host.present(controller, animated: true) + ctx.resolve() + default: ctx.reject("Unsupported AdMob action: \(action)") + } + } + + @MainActor + private func start(_ ctx: AMBContext) { + guard privacy.canRequestAds else { ctx.reject("Gather ad consent before requesting ads"); return } + if started { ctx.resolve(["version": string(for: MobileAds.shared.versionNumber)]); return } + starting.append(ctx) + guard starting.count == 1 else { return } + let token = generation + tracking.authorize { [weak self] result in + guard let self, self.generation == token else { return } + if case .failure(let error) = result { + let pending = self.starting + self.starting.removeAll() + pending.forEach { $0.reject(error) } + return + } + Task { @MainActor [weak self] in + let environment = await AMBAdEnvironment.current() + guard let self, self.generation == token else { return } + guard self.privacy.canRequestAds else { + let pending = self.starting + self.starting.removeAll() + pending.forEach { $0.reject("Gather ad consent before requesting ads") } + return + } + self.adEnvironment = environment + self.startSDK(token) + } + } + } + + @MainActor + private func startSDK(_ token: UUID) { + let didStart: @MainActor @Sendable () -> Void = { [weak self] in + guard let self, self.generation == token else { return } + self.started = true + if let webView = self.webView, self.registeredWebView !== webView { + MobileAds.shared.register(webView) + self.registeredWebView = webView + } + let pending = self.starting + self.starting.removeAll() + for request in pending { request.resolve(["version": string(for: MobileAds.shared.versionNumber)]) } + } + MobileAds.shared.start { _ in + DispatchQueue.main.async(execute: didStart) + } + } + + private func create(_ ctx: AMBContext) { + guard let id = ctx.optId(), let unit = ctx.optAdUnitID(), + ctx.optString("cls") == "WebViewAd" || (!id.isEmpty && !unit.isEmpty) else { + ctx.reject("id and adUnitId are required"); return + } + guard ads[id]?.isPresenting != true else { ctx.reject("Ad is presenting"); return } + let ad: AMBAdBase? + switch ctx.optString("cls") { + case "AppOpenAd": ad = AMBAppOpenAd(ctx) + case "BannerAd": ad = AMBBanner(ctx) + case "InterstitialAd": ad = AMBInterstitial(ctx) + case "NativeAd": ad = AMBNativeAd(ctx) + case "WebViewAd": ad = AMBWebViewAd(ctx) + case "RewardedAd": ad = AMBRewarded(ctx) + case "RewardedInterstitialAd": ad = AMBRewardedInterstitial(ctx) + default: ad = nil + } + guard let ad else { ctx.reject("Ad class or options are not supported"); return } + ads.removeValue(forKey: id)?.destroy() + ads[id] = ad + ctx.resolve() + } +} diff --git a/platforms/ios/ads/AMBPrivacy.swift b/platforms/ios/ads/AMBPrivacy.swift new file mode 100644 index 0000000000..96b24dcd09 --- /dev/null +++ b/platforms/ios/ads/AMBPrivacy.swift @@ -0,0 +1,111 @@ +import UserMessagingPlatform +import UIKit + +final class AMBPrivacy { + private weak var plugin: AMBPlugin? + private var busy = false + private var presenting = false + private let information: ConsentInformation + + init(plugin: AMBPlugin, information: ConsentInformation = .shared) { + self.plugin = plugin + self.information = information + } + + var canRequestAds: Bool { information.canRequestAds } + var state: [String: Any] { + let status: String + switch information.consentStatus { + case .required: status = "required" + case .notRequired: status = "notRequired" + case .obtained: status = "obtained" + default: status = "unknown" + } + return ["consentStatus": status, "canRequestAds": canRequestAds, + "privacyOptionsRequired": information.privacyOptionsRequirementStatus == .required] + } + + func gather(_ ctx: AMBContext) { + guard !busy else { ctx.reject("A consent request is already in progress"); return } + let parameters = RequestParameters() + if ctx.has("debugGeography") || ctx.has("testDeviceIds") { + #if DEBUG + let settings = DebugSettings() + switch ctx.optString("debugGeography", "disabled") { + case "disabled": settings.geography = .disabled + case "eea": settings.geography = .EEA + case "notEea": settings.geography = .other + default: ctx.reject("Unknown debug geography"); return + } + settings.testDeviceIdentifiers = ctx.optStringArray("testDeviceIds") + parameters.debugSettings = settings + #else + ctx.reject("Consent debug controls require a debug build"); return + #endif + } + busy = true + information.requestConsentInfoUpdate(with: parameters) { [weak self] error in + guard let self, ctx.isCurrent else { return } + if let error { self.finish(ctx, error); return } + guard self.information.consentStatus == .required else { self.finish(ctx, nil); return } + ConsentForm.load { [weak self] form, error in + guard let self, ctx.isCurrent else { return } + if let error { self.finish(ctx, error); return } + guard let form else { + self.busy = false + ctx.reject("Consent form is unavailable") + return + } + guard let controller = self.presenter(ctx) else { self.busy = false; return } + self.presenting = true + form.present(from: controller) { [weak self] error in self?.finish(ctx, error) } + } + } + } + + func showOptions(_ ctx: AMBContext) { + guard !busy else { ctx.reject("A consent request is already in progress"); return } + guard information.privacyOptionsRequirementStatus == .required else { ctx.resolve(state); return } + guard let controller = presenter(ctx) else { return } + busy = true + presenting = true + ConsentForm.presentPrivacyOptionsForm(from: controller) { [weak self] error in + self?.finish(ctx, error) + } + } + + func resetForTesting(_ ctx: AMBContext) { + #if DEBUG + guard !busy else { ctx.reject("A consent request is already in progress"); return } + information.reset() + plugin?.clearAds() + ctx.resolve(state) + #else + ctx.reject("Consent reset requires a debug build") + #endif + } + + func resetPresentation() { + if presenting { plugin?.viewController?.dismiss(animated: false) } + presenting = false + busy = false + } + + private func presenter(_ ctx: AMBContext) -> UIViewController? { + guard let controller = plugin?.viewController, controller.view.window != nil, + controller.presentedViewController == nil, + controller.view.window?.windowScene?.activationState == .foregroundActive else { + ctx.reject("Consent requires the foreground app"); return nil + } + return controller + } + + private func finish(_ ctx: AMBContext, _ error: Error?) { + guard ctx.isCurrent else { return } + busy = false + presenting = false + if !canRequestAds { plugin?.clearAds() } + if let error { ctx.reject(error) } + else { ctx.resolve(state) } + } +} diff --git a/platforms/ios/ads/AMBRewarded.swift b/platforms/ios/ads/AMBRewarded.swift new file mode 100644 index 0000000000..a50d597978 --- /dev/null +++ b/platforms/ios/ads/AMBRewarded.swift @@ -0,0 +1,46 @@ +import GoogleMobileAds + +class AMBRewarded: AMBFullScreen { + var mAd: RewardedAd? + + override func isLoaded() -> Bool { + return self.mAd != nil && !presenting + } + + override func load(_ ctx: AMBContext) { + guard !presenting else { ctx.reject("Ad is presenting"); return } + clear() + let token = beginLoad(ctx) + + RewardedAd.load(with: adUnitId, request: adRequest, completionHandler: { [weak self] ad, error in + guard let self, self.acceptsLoad(token) else { return } + if let error { + self.finishLoad(token, error: error) + + return + } + + self.mAd = ad + ad?.fullScreenContentDelegate = self + ad?.paidEventHandler = { [weak self, weak ad] value in self?.emitPaid(value, response: ad?.responseInfo) } + ad?.serverSideVerificationOptions = ctx.optGADServerSideVerificationOptions() + + self.finishLoad(token) + }) + } + + override func show(_ ctx: AMBContext) { + guard let ad = mAd, let controller = preparePresentation(ctx) else { return } + let reward = ad.adReward + ad.present(from: controller, userDidEarnRewardHandler: { [weak self] in + self?.emit(AMBEvents.adReward, reward) + }) + ctx.resolve(true) + } + + override func clear() { + mAd?.fullScreenContentDelegate = nil + mAd?.paidEventHandler = nil + mAd = nil + } +} diff --git a/platforms/ios/ads/AMBRewardedInterstitial.swift b/platforms/ios/ads/AMBRewardedInterstitial.swift new file mode 100644 index 0000000000..86ecdd2b9f --- /dev/null +++ b/platforms/ios/ads/AMBRewardedInterstitial.swift @@ -0,0 +1,46 @@ +import GoogleMobileAds + +class AMBRewardedInterstitial: AMBFullScreen { + var mAd: RewardedInterstitialAd? + + override func isLoaded() -> Bool { + return self.mAd != nil && !presenting + } + + override func load(_ ctx: AMBContext) { + guard !presenting else { ctx.reject("Ad is presenting"); return } + clear() + let token = beginLoad(ctx) + + RewardedInterstitialAd.load(with: adUnitId, request: adRequest, completionHandler: { [weak self] ad, error in + guard let self, self.acceptsLoad(token) else { return } + if let error { + self.finishLoad(token, error: error) + + return + } + + self.mAd = ad + ad?.fullScreenContentDelegate = self + ad?.paidEventHandler = { [weak self, weak ad] value in self?.emitPaid(value, response: ad?.responseInfo) } + ad?.serverSideVerificationOptions = ctx.optGADServerSideVerificationOptions() + + self.finishLoad(token) + }) + } + + override func show(_ ctx: AMBContext) { + guard let ad = mAd, let controller = preparePresentation(ctx) else { return } + let reward = ad.adReward + ad.present(from: controller, userDidEarnRewardHandler: { [weak self] in + self?.emit(AMBEvents.adReward, reward) + }) + ctx.resolve(true) + } + + override func clear() { + mAd?.fullScreenContentDelegate = nil + mAd?.paidEventHandler = nil + mAd = nil + } +} diff --git a/platforms/ios/ads/AMBTrackingAuthorization.swift b/platforms/ios/ads/AMBTrackingAuthorization.swift new file mode 100644 index 0000000000..b590589034 --- /dev/null +++ b/platforms/ios/ads/AMBTrackingAuthorization.swift @@ -0,0 +1,94 @@ +import AppTrackingTransparency +import UIKit + +@MainActor +final class AMBTrackingAuthorization { + typealias Completion = (Result<ATTrackingManager.AuthorizationStatus, Error>) -> Void + private let status: @MainActor () -> ATTrackingManager.AuthorizationStatus + private let isActive: @MainActor () -> Bool + private let request: (@escaping @Sendable (ATTrackingManager.AuthorizationStatus) -> Void) -> Void + private let notifications: NotificationCenter + private var observer: NSObjectProtocol? + private var pending: [Completion] = [] + private var requestID: UUID? + private var deadline: Task<Void, Never>? + private let timeout: Duration + + init(status: @escaping @MainActor () -> ATTrackingManager.AuthorizationStatus = { ATTrackingManager.trackingAuthorizationStatus }, + isActive: @escaping @MainActor () -> Bool = { UIApplication.shared.applicationState == .active }, + notifications: NotificationCenter = .default, + timeout: Duration = .seconds(30), + request: @escaping (@escaping @Sendable (ATTrackingManager.AuthorizationStatus) -> Void) -> Void = ATTrackingManager.requestTrackingAuthorization) { + self.status = status + self.isActive = isActive + self.notifications = notifications + self.timeout = timeout + self.request = request + observer = notifications.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in + DispatchQueue.main.async { self?.requestWhenActive() } + } + } + + deinit { + deadline?.cancel() + if let observer { notifications.removeObserver(observer) } + } + + func authorize(_ completion: @escaping Completion) { + pending.append(completion) + if deadline == nil { + deadline = Task { [weak self, timeout] in + do { try await Task.sleep(for: timeout) } + catch { return } + guard !Task.isCancelled, let self, !self.pending.isEmpty else { return } + if !self.finishIfDecided() { + self.finish(.failure(NSError(domain: "AcodeAds", code: 3, + userInfo: [NSLocalizedDescriptionKey: "Tracking authorization is still pending. Please try again."]))) + } + } + } + requestWhenActive() + } + + func cancel() { + finish(.failure(NSError(domain: "AcodeAds", code: 1, + userInfo: [NSLocalizedDescriptionKey: "Tracking authorization was cancelled"]))) + } + + private func requestWhenActive() { + guard !pending.isEmpty, !finishIfDecided(), requestID == nil, isActive() else { return } + let id = UUID() + requestID = id + request { [weak self] status in + DispatchQueue.main.async { + guard let self, self.requestID == id else { return } + self.requestID = nil + if self.finishIfDecided() { return } + if status != .notDetermined { self.finish(.success(status)) } + else if self.isActive() { + self.finish(.failure(NSError(domain: "AcodeAds", code: 2, + userInfo: [NSLocalizedDescriptionKey: "Tracking authorization could not be presented. Please try again."]))) + } + // An inactive app cannot display ATT. Retry on didBecomeActive. + } + } + } + + private func finishIfDecided() -> Bool { + let current = status() + guard current != .notDetermined else { return false } + requestID = nil + finish(.success(current)) + return true + } + + private func finish(_ result: Result<ATTrackingManager.AuthorizationStatus, Error>) { + deadline?.cancel() + deadline = nil + // Cancellation/timeout settles callers, not the OS request. Its ID remains + // until a callback or a determined OS status proves it is safe to retire. + let callbacks = pending + pending.removeAll() + callbacks.forEach { $0(result) } + } +} diff --git a/platforms/ios/ads/AMBWebViewAd.swift b/platforms/ios/ads/AMBWebViewAd.swift new file mode 100644 index 0000000000..127e6e0b0e --- /dev/null +++ b/platforms/ios/ads/AMBWebViewAd.swift @@ -0,0 +1,8 @@ +import Foundation + +// Web ad markup is owned by the existing JavaScript WebViewAd API. +final class AMBWebViewAd: AMBAdBase { + override func load(_ ctx: AMBContext) { ctx.resolve() } + override func show(_ ctx: AMBContext) { ctx.resolve() } + override func hide(_ ctx: AMBContext) { ctx.resolve() } +} diff --git a/platforms/ios/ads/AMNAdView.xcassets/stars_3_5.imageset/Contents.json b/platforms/ios/ads/AMNAdView.xcassets/stars_3_5.imageset/Contents.json new file mode 100644 index 0000000000..bc9047bf7f --- /dev/null +++ b/platforms/ios/ads/AMNAdView.xcassets/stars_3_5.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "stars_3_5.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/platforms/ios/ads/AMNAdView.xcassets/stars_3_5.imageset/stars_3_5.png b/platforms/ios/ads/AMNAdView.xcassets/stars_3_5.imageset/stars_3_5.png new file mode 100644 index 0000000000..7396dbee9a Binary files /dev/null and b/platforms/ios/ads/AMNAdView.xcassets/stars_3_5.imageset/stars_3_5.png differ diff --git a/platforms/ios/ads/AMNAdView.xcassets/stars_4.imageset/Contents.json b/platforms/ios/ads/AMNAdView.xcassets/stars_4.imageset/Contents.json new file mode 100644 index 0000000000..4da3cefe56 --- /dev/null +++ b/platforms/ios/ads/AMNAdView.xcassets/stars_4.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "stars_4.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/platforms/ios/ads/AMNAdView.xcassets/stars_4.imageset/stars_4.png b/platforms/ios/ads/AMNAdView.xcassets/stars_4.imageset/stars_4.png new file mode 100644 index 0000000000..016af12ad9 Binary files /dev/null and b/platforms/ios/ads/AMNAdView.xcassets/stars_4.imageset/stars_4.png differ diff --git a/platforms/ios/ads/AMNAdView.xcassets/stars_4_5.imageset/Contents.json b/platforms/ios/ads/AMNAdView.xcassets/stars_4_5.imageset/Contents.json new file mode 100644 index 0000000000..3a773813c6 --- /dev/null +++ b/platforms/ios/ads/AMNAdView.xcassets/stars_4_5.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "stars_4_5.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/platforms/ios/ads/AMNAdView.xcassets/stars_4_5.imageset/stars_4_5.png b/platforms/ios/ads/AMNAdView.xcassets/stars_4_5.imageset/stars_4_5.png new file mode 100644 index 0000000000..adf396f182 Binary files /dev/null and b/platforms/ios/ads/AMNAdView.xcassets/stars_4_5.imageset/stars_4_5.png differ diff --git a/platforms/ios/ads/AMNAdView.xcassets/stars_5.imageset/Contents.json b/platforms/ios/ads/AMNAdView.xcassets/stars_5.imageset/Contents.json new file mode 100644 index 0000000000..df8c4574f4 --- /dev/null +++ b/platforms/ios/ads/AMNAdView.xcassets/stars_5.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "stars_5.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/platforms/ios/ads/AMNAdView.xcassets/stars_5.imageset/stars_5.png b/platforms/ios/ads/AMNAdView.xcassets/stars_5.imageset/stars_5.png new file mode 100644 index 0000000000..301a6c64b5 Binary files /dev/null and b/platforms/ios/ads/AMNAdView.xcassets/stars_5.imageset/stars_5.png differ diff --git a/platforms/ios/ads/AMNAdView.xib b/platforms/ios/ads/AMNAdView.xib new file mode 100644 index 0000000000..75f9c673fe --- /dev/null +++ b/platforms/ios/ads/AMNAdView.xib @@ -0,0 +1,149 @@ +<?xml version="1.0" encoding="UTF-8"?> +<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="17156" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" colorMatched="YES"> + <device id="retina4_7" orientation="portrait" appearance="light"/> + <dependencies> + <deployment version="2048" identifier="iOS"/> + <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17125"/> + <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> + </dependencies> + <objects> + <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/> + <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/> + <view contentMode="scaleToFill" id="iN0-l3-epB" customClass="GADNativeAdView"> + <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> + <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> + <subviews> + <imageView userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="iNa-bH-h1m"> + <rect key="frame" x="15" y="15.5" width="40" height="40"/> + <constraints> + <constraint firstAttribute="height" constant="40" id="ICz-3W-FQf"/> + <constraint firstAttribute="width" constant="40" id="vY6-8D-xIn"/> + </constraints> + </imageView> + <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Advertiser" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="GTT-Yh-eSq"> + <rect key="frame" x="63" y="38.5" width="66.5" height="17"/> + <fontDescription key="fontDescription" type="system" pointSize="14"/> + <color key="textColor" systemColor="darkTextColor"/> + <nil key="highlightedColor"/> + </label> + <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" placeholderIntrinsicWidth="100" placeholderIntrinsicHeight="17" translatesAutoresizingMaskIntoConstraints="NO" id="2Of-AP-0h9"> + <rect key="frame" x="129.5" y="38.5" width="100" height="17"/> + <constraints> + <constraint firstAttribute="height" constant="17" id="jBW-Cz-Kyc"/> + <constraint firstAttribute="width" constant="100" id="sXk-zk-NI0"/> + </constraints> + </imageView> + <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" verticalCompressionResistancePriority="751" text="Body that is really really long and can take up to two lines or sometimes even more." textAlignment="justified" lineBreakMode="tailTruncation" numberOfLines="0" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="PEQ-D9-2Vv"> + <rect key="frame" x="15" y="63.5" width="350" height="33.5"/> + <fontDescription key="fontDescription" type="system" pointSize="14"/> + <color key="textColor" systemColor="darkTextColor"/> + <nil key="highlightedColor"/> + </label> + <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="E5w-YA-UY8"> + <rect key="frame" x="318" y="259.5" width="47" height="34"/> + <fontDescription key="fontDescription" type="system" pointSize="18"/> + <state key="normal" title="Install"> + <color key="titleShadowColor" red="0.5" green="0.5" blue="0.5" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> + </state> + </button> + <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Price" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Ysb-of-cat"> + <rect key="frame" x="230" y="268" width="33" height="17"/> + <fontDescription key="fontDescription" type="system" pointSize="14"/> + <color key="textColor" systemColor="darkTextColor"/> + <nil key="highlightedColor"/> + </label> + <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Store" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="hwF-UL-Q8H"> + <rect key="frame" x="273" y="268" width="35" height="17"/> + <fontDescription key="fontDescription" type="system" pointSize="14"/> + <color key="textColor" systemColor="darkTextColor"/> + <nil key="highlightedColor"/> + </label> + <label opaque="NO" userInteractionEnabled="NO" contentMode="left" verticalHuggingPriority="251" horizontalCompressionResistancePriority="751" text="Headline" textAlignment="justified" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="beR-eV-DX1"> + <rect key="frame" x="63" y="10" width="297" height="20.5"/> + <constraints> + <constraint firstAttribute="height" constant="20.5" id="6r8-Hu-d0y"/> + </constraints> + <fontDescription key="fontDescription" type="system" pointSize="17"/> + <color key="textColor" systemColor="darkTextColor"/> + <nil key="highlightedColor"/> + </label> + <view contentMode="scaleAspectFit" translatesAutoresizingMaskIntoConstraints="NO" id="fNp-yu-K4i" customClass="GADMediaView"> + <rect key="frame" x="62.5" y="102" width="250" height="150"/> + <constraints> + <constraint firstAttribute="height" priority="750" constant="150" id="71m-kn-7Ug"/> + <constraint firstAttribute="width" constant="250" id="e3T-fD-di4"/> + </constraints> + </view> + <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Ad" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="lp1-oz-XOs"> + <rect key="frame" x="0.0" y="0.0" width="15" height="15"/> + <color key="backgroundColor" red="1" green="0.80000001190000003" blue="0.40000000600000002" alpha="1" colorSpace="calibratedRGB"/> + <constraints> + <constraint firstAttribute="width" relation="greaterThanOrEqual" constant="15" id="Twa-Vk-uWQ"/> + <constraint firstAttribute="height" constant="15" id="k8m-kJ-CF5"/> + </constraints> + <fontDescription key="fontDescription" type="system" weight="semibold" pointSize="11"/> + <color key="textColor" white="1" alpha="1" colorSpace="calibratedWhite"/> + <nil key="highlightedColor"/> + </label> + </subviews> + <color key="backgroundColor" red="1" green="0.98303861469999998" blue="0.92887652860000003" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> + <constraints> + <constraint firstItem="GTT-Yh-eSq" firstAttribute="leading" secondItem="beR-eV-DX1" secondAttribute="leading" id="0sB-Mk-EU6"/> + <constraint firstItem="lp1-oz-XOs" firstAttribute="top" secondItem="iN0-l3-epB" secondAttribute="top" id="3lA-qv-Nkc"/> + <constraint firstItem="Ysb-of-cat" firstAttribute="leading" relation="greaterThanOrEqual" secondItem="iN0-l3-epB" secondAttribute="leading" constant="20" symbolic="YES" id="3pc-w6-uy1"/> + <constraint firstItem="PEQ-D9-2Vv" firstAttribute="top" relation="greaterThanOrEqual" secondItem="iNa-bH-h1m" secondAttribute="bottom" id="4S3-p0-z6A"/> + <constraint firstAttribute="trailing" secondItem="PEQ-D9-2Vv" secondAttribute="trailing" constant="10" id="8U0-Fb-3R7"/> + <constraint firstItem="iNa-bH-h1m" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" constant="15" id="9WK-zC-xET"/> + <constraint firstAttribute="trailing" secondItem="beR-eV-DX1" secondAttribute="trailing" constant="15" id="BcE-do-dNl"/> + <constraint firstItem="lp1-oz-XOs" firstAttribute="left" secondItem="iN0-l3-epB" secondAttribute="left" id="BpX-yC-PZG"/> + <constraint firstItem="PEQ-D9-2Vv" firstAttribute="top" secondItem="2Of-AP-0h9" secondAttribute="bottom" constant="8" symbolic="YES" id="CCg-xe-cKg"/> + <constraint firstItem="2Of-AP-0h9" firstAttribute="top" secondItem="beR-eV-DX1" secondAttribute="bottom" constant="8" symbolic="YES" id="ESC-Pe-TXR"/> + <constraint firstItem="iNa-bH-h1m" firstAttribute="bottom" secondItem="2Of-AP-0h9" secondAttribute="bottom" id="GwM-y0-1du"/> + <constraint firstItem="beR-eV-DX1" firstAttribute="leading" secondItem="iNa-bH-h1m" secondAttribute="trailing" constant="8" symbolic="YES" id="MRN-dd-Oip"/> + <constraint firstItem="2Of-AP-0h9" firstAttribute="leading" secondItem="GTT-Yh-eSq" secondAttribute="trailing" id="Med-Nd-wEo"/> + <constraint firstItem="beR-eV-DX1" firstAttribute="top" secondItem="iN0-l3-epB" secondAttribute="top" constant="10" id="Mvs-eV-Wzb"/> + <constraint firstItem="Ysb-of-cat" firstAttribute="centerY" secondItem="hwF-UL-Q8H" secondAttribute="centerY" id="Rud-i8-Myz"/> + <constraint firstItem="fNp-yu-K4i" firstAttribute="centerX" secondItem="iN0-l3-epB" secondAttribute="centerX" id="TYN-lq-3DK"/> + <constraint firstItem="fNp-yu-K4i" firstAttribute="top" secondItem="PEQ-D9-2Vv" secondAttribute="bottom" constant="5" id="V0m-hf-6NS"/> + <constraint firstItem="GTT-Yh-eSq" firstAttribute="centerY" secondItem="2Of-AP-0h9" secondAttribute="centerY" id="YgR-kp-age"/> + <constraint firstItem="hwF-UL-Q8H" firstAttribute="leading" secondItem="Ysb-of-cat" secondAttribute="trailing" constant="10" id="aLb-sm-wAb"/> + <constraint firstAttribute="right" relation="greaterThanOrEqual" secondItem="lp1-oz-XOs" secondAttribute="right" constant="20" symbolic="YES" id="czi-qD-IaJ"/> + <constraint firstAttribute="trailing" secondItem="E5w-YA-UY8" secondAttribute="trailing" constant="10" id="eNM-dN-tvx"/> + <constraint firstItem="E5w-YA-UY8" firstAttribute="leading" secondItem="hwF-UL-Q8H" secondAttribute="trailing" constant="10" id="f39-vH-KWq"/> + <constraint firstItem="iNa-bH-h1m" firstAttribute="leading" secondItem="PEQ-D9-2Vv" secondAttribute="leading" id="mof-5F-8vM"/> + <constraint firstItem="E5w-YA-UY8" firstAttribute="centerY" secondItem="hwF-UL-Q8H" secondAttribute="centerY" id="rNj-VY-YrO"/> + <constraint firstItem="E5w-YA-UY8" firstAttribute="top" secondItem="fNp-yu-K4i" secondAttribute="bottom" constant="7.5" id="rup-e7-1CR"/> + <constraint firstAttribute="bottom" relation="greaterThanOrEqual" secondItem="E5w-YA-UY8" secondAttribute="bottom" constant="20" symbolic="YES" id="uEI-XT-igi"/> + </constraints> + <connections> + <outlet property="advertiserView" destination="GTT-Yh-eSq" id="bY8-5O-6fF"/> + <outlet property="bodyView" destination="PEQ-D9-2Vv" id="Gpd-Q6-Byv"/> + <outlet property="callToActionView" destination="E5w-YA-UY8" id="RCf-yK-s1x"/> + <outlet property="headlineView" destination="beR-eV-DX1" id="d1E-ed-yel"/> + <outlet property="iconView" destination="iNa-bH-h1m" id="gIe-xy-iwm"/> + <outlet property="mediaView" destination="fNp-yu-K4i" id="624-ZP-L04"/> + <outlet property="priceView" destination="Ysb-of-cat" id="L6Q-hd-uaJ"/> + <outlet property="starRatingView" destination="2Of-AP-0h9" id="zCO-9D-S0V"/> + <outlet property="storeView" destination="hwF-UL-Q8H" id="hRl-23-ce1"/> + </connections> + <point key="canvasLocation" x="13.768115942028986" y="-5.6919642857142856"/> + </view> + </objects> + <resources> + <systemColor name="darkTextColor"> + <color white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/> + </systemColor> + <systemColor name="darkTextColor"> + <color white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/> + </systemColor> + <systemColor name="darkTextColor"> + <color white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/> + </systemColor> + <systemColor name="darkTextColor"> + <color white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/> + </systemColor> + <systemColor name="darkTextColor"> + <color white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/> + </systemColor> + </resources> +</document> diff --git a/platforms/ios/ads/AMNAdViewProvider.swift b/platforms/ios/ads/AMNAdViewProvider.swift new file mode 100644 index 0000000000..ad6abc1bb9 --- /dev/null +++ b/platforms/ios/ads/AMNAdViewProvider.swift @@ -0,0 +1,80 @@ +import GoogleMobileAds +import UIKit + +class AMNAdViewProvider: NSObject, AMBNativeAdViewProvider { + func createView(_ ad: NativeAd) -> UIView? { + let nativeAd = ad + let nibView = Bundle.main.loadNibNamed("AMNAdView", owner: nil, options: nil)?.first + guard let nativeAdView = nibView as? NativeAdView else { + return nil + } + + (nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline + nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent + + if let mediaView = nativeAdView.mediaView, nativeAd.mediaContent.aspectRatio > 0 { + let heightConstraint = NSLayoutConstraint( + item: mediaView, + attribute: .height, + relatedBy: .equal, + toItem: mediaView, + attribute: .width, + multiplier: CGFloat(1 / nativeAd.mediaContent.aspectRatio), + constant: 0) + heightConstraint.isActive = true + } + + // These assets are not guaranteed to be present. Check that they are before + // showing or hiding them. + (nativeAdView.bodyView as? UILabel)?.text = nativeAd.body + nativeAdView.bodyView?.isHidden = nativeAd.body == nil + + (nativeAdView.callToActionView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal) + nativeAdView.callToActionView?.isHidden = nativeAd.callToAction == nil + + (nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image + nativeAdView.iconView?.isHidden = nativeAd.icon == nil + + (nativeAdView.starRatingView as? UIImageView)?.image = imageOfStars( + starRating: nativeAd.starRating) + nativeAdView.starRatingView?.isHidden = nativeAd.starRating == nil + + (nativeAdView.storeView as? UILabel)?.text = nativeAd.store + nativeAdView.storeView?.isHidden = nativeAd.store == nil + + (nativeAdView.priceView as? UILabel)?.text = nativeAd.price + nativeAdView.priceView?.isHidden = nativeAd.price == nil + + (nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser + nativeAdView.advertiserView?.isHidden = nativeAd.advertiser == nil + + // In order for the SDK to process touch events properly, user interaction should be disabled. + nativeAdView.callToActionView?.isUserInteractionEnabled = false + + // Associate the native ad view with the native ad object. This is + // required to make the ad clickable. + // Note: this should always be done after populating the ad views. + nativeAdView.nativeAd = nativeAd + + return nativeAdView + } + + /// Returns a `UIImage` representing the number of stars from the given star rating; returns `nil` + /// if the star rating is less than 3.5 stars. + private func imageOfStars(starRating: NSDecimalNumber?) -> UIImage? { + guard let rating = starRating?.doubleValue else { + return nil + } + if rating >= 5 { + return UIImage(named: "stars_5") + } else if rating >= 4.5 { + return UIImage(named: "stars_4_5") + } else if rating >= 4 { + return UIImage(named: "stars_4") + } else if rating >= 3.5 { + return UIImage(named: "stars_3_5") + } else { + return nil + } + } +} diff --git a/platforms/ios/ads/AdMobPlus-LICENSE.txt b/platforms/ios/ads/AdMobPlus-LICENSE.txt new file mode 100644 index 0000000000..5b8d4fc5e5 --- /dev/null +++ b/platforms/ios/ads/AdMobPlus-LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Ratson + +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/platforms/ios/ads/AdsIntegrationViewController.swift b/platforms/ios/ads/AdsIntegrationViewController.swift new file mode 100644 index 0000000000..541d46e6ee --- /dev/null +++ b/platforms/ios/ads/AdsIntegrationViewController.swift @@ -0,0 +1,23 @@ +import GoogleMobileAds +import UIKit +import WebKit + +final class AdsIntegrationViewController: UIViewController { + private let url: URL + + init(url: URL) { + self.url = url + super.init(nibName: nil, bundle: nil) + } + + required init?(coder: NSCoder) { nil } + + override func viewDidLoad() { + super.viewDidLoad() + let webView = WKWebView(frame: view.bounds) + webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] + view.addSubview(webView) + MobileAds.shared.register(webView) + webView.load(URLRequest(url: url)) + } +} diff --git a/platforms/ios/runner.icon/Assets/acode.png b/platforms/ios/runner.icon/Assets/acode.png new file mode 100644 index 0000000000..eedbceffbe Binary files /dev/null and b/platforms/ios/runner.icon/Assets/acode.png differ diff --git a/platforms/ios/runner.icon/icon.json b/platforms/ios/runner.icon/icon.json new file mode 100644 index 0000000000..680f6446d4 --- /dev/null +++ b/platforms/ios/runner.icon/icon.json @@ -0,0 +1,49 @@ +{ + "fill-specializations" : [ + { + "value" : { + "solid" : "display-p3:0.22745,0.24314,0.32941,1.00000" + } + }, + { + "appearance" : "dark", + "value" : { + "solid" : "display-p3:0.22745,0.24314,0.32941,1.00000" + } + } + ], + "groups" : [ + { + "layers" : [ + { + "fill" : { + "solid" : "display-p3:1.00000,1.00000,1.00000,1.00000" + }, + "image-name" : "acode.png", + "name" : "acode", + "position" : { + "scale" : 1, + "translation-in-points" : [ + 0, + 0 + ] + } + } + ], + "shadow" : { + "kind" : "neutral", + "opacity" : 0 + }, + "translucency" : { + "enabled" : false, + "value" : 0.5 + } + } + ], + "supported-platforms" : { + "circles" : [ + "watchOS" + ], + "squares" : "shared" + } +} \ No newline at end of file diff --git a/platforms/ios/runner.xcodeproj/project.pbxproj b/platforms/ios/runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000000..4c35357847 --- /dev/null +++ b/platforms/ios/runner.xcodeproj/project.pbxproj @@ -0,0 +1,723 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 77; + objects = { + +/* Begin PBXBuildFile section */ + 122FC5962F9CEDE000BE113A /* DeviceKit in Frameworks */ = {isa = PBXBuildFile; productRef = 122FC5952F9CEDE000BE113A /* DeviceKit */; }; + 12D6D3972FFEE6770006230E /* runner.icon in Resources */ = {isa = PBXBuildFile; fileRef = 12D6D3962FFEE6770006230E /* runner.icon */; }; + AC0DE3000000000000000001 /* CSSH2 in Frameworks */ = {isa = PBXBuildFile; productRef = AC0DE3000000000000000003 /* CSSH2 */; }; + AC0DE4000000000000000001 /* AcodeCurl in Frameworks */ = {isa = PBXBuildFile; productRef = AC0DE4000000000000000003 /* AcodeCurl */; }; + AC0DE600000000000000000D /* runnerTests/Iap.storekit in Resources */ = {isa = PBXBuildFile; fileRef = AC0DE600000000000000000C /* runnerTests/Iap.storekit */; }; + AC0DEAD00000000000000012 /* GoogleMobileAds in Frameworks */ = {isa = PBXBuildFile; productRef = AC0DEAD00000000000000011 /* GoogleMobileAds */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + AC0DE2000000000000000005 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 12D2F2EB2F843F1F000D37BC /* Project object */; + proxyType = 1; + remoteGlobalIDString = 12D2F2F22F843F1F000D37BC; + remoteInfo = runner; + }; + AC0DE600000000000000000B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 12D2F2EB2F843F1F000D37BC /* Project object */; + proxyType = 1; + remoteGlobalIDString = 12D2F2F22F843F1F000D37BC; + remoteInfo = runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 1249911F30644EB800C84B4D /* runnerUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = runnerUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 12D2F2F32F843F1F000D37BC /* runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 12D6D3962FFEE6770006230E /* runner.icon */ = {isa = PBXFileReference; lastKnownFileType = folder.iconcomposer.icon; path = runner.icon; sourceTree = "<group>"; }; + AC0DE2000000000000000001 /* runnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = runnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + AC0DE600000000000000000C /* runnerTests/Iap.storekit */ = {isa = PBXFileReference; lastKnownFileType = text; path = runnerTests/Iap.storekit; sourceTree = SOURCE_ROOT; }; + DEADBEEF1234DEADBEEF1234 /* Config.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Config.xcconfig; sourceTree = SOURCE_ROOT; }; +/* End PBXFileReference section */ + +/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ + 12D2F2F62F843F1F000D37BC /* Exceptions for "runner" folder in "runner" target */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + Info.plist, + ); + target = 12D2F2F22F843F1F000D37BC /* runner */; + }; +/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ + +/* Begin PBXFileSystemSynchronizedRootGroup section */ + 12D2F2F52F843F1F000D37BC /* runner */ = { + isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + 12D2F2F62F843F1F000D37BC /* Exceptions for "runner" folder in "runner" target */, + ); + explicitFolders = ( + bundle, + ); + path = runner; + sourceTree = "<group>"; + }; + AC0DE2000000000000000002 /* runnerTests */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = runnerTests; + sourceTree = "<group>"; + }; + AC0DE6000000000000000003 /* runnerUITests */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = runnerUITests; + sourceTree = "<group>"; + }; + AC0DEAD0000000000000000E /* ads */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = ads; + sourceTree = "<group>"; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + +/* Begin PBXFrameworksBuildPhase section */ + 12D2F2F02F843F1F000D37BC /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 122FC5962F9CEDE000BE113A /* DeviceKit in Frameworks */, + AC0DE3000000000000000001 /* CSSH2 in Frameworks */, + AC0DE4000000000000000001 /* AcodeCurl in Frameworks */, + AC0DEAD00000000000000012 /* GoogleMobileAds in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AC0DE2000000000000000004 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AC0DE6000000000000000005 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 12D2F2EA2F843F1F000D37BC = { + isa = PBXGroup; + children = ( + 12D2F2F52F843F1F000D37BC /* runner */, + 12D2F2F42F843F1F000D37BC /* Products */, + AC0DE2000000000000000002 /* runnerTests */, + DEADBEEF1234DEADBEEF1234 /* Config.xcconfig */, + 12D6D3962FFEE6770006230E /* runner.icon */, + AC0DEAD0000000000000000E /* ads */, + AC0DE6000000000000000003 /* runnerUITests */, + 12D7C9A330654F8B007A5955 /* Recovered References */, + ); + sourceTree = "<group>"; + }; + 12D2F2F42F843F1F000D37BC /* Products */ = { + isa = PBXGroup; + children = ( + 12D2F2F32F843F1F000D37BC /* runner.app */, + AC0DE2000000000000000001 /* runnerTests.xctest */, + 1249911F30644EB800C84B4D /* runnerUITests.xctest */, + ); + name = Products; + sourceTree = "<group>"; + }; + 12D7C9A330654F8B007A5955 /* Recovered References */ = { + isa = PBXGroup; + children = ( + AC0DE600000000000000000C /* runnerTests/Iap.storekit */, + ); + name = "Recovered References"; + sourceTree = "<group>"; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 12D2F2F22F843F1F000D37BC /* runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 12D2F2FE2F843F20000D37BC /* Build configuration list for PBXNativeTarget "runner" */; + buildPhases = ( + AC0DE7000000000000000001 /* Build Alpine */, + 12D2F2EF2F843F1F000D37BC /* Sources */, + 12D2F2F02F843F1F000D37BC /* Frameworks */, + 12D2F2F12F843F1F000D37BC /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + 12D2F2F52F843F1F000D37BC /* runner */, + AC0DEAD0000000000000000E /* ads */, + ); + name = runner; + packageProductDependencies = ( + 122FC5952F9CEDE000BE113A /* DeviceKit */, + AC0DE3000000000000000003 /* CSSH2 */, + AC0DE4000000000000000003 /* AcodeCurl */, + AC0DEAD00000000000000011 /* GoogleMobileAds */, + ); + productName = runner; + productReference = 12D2F2F32F843F1F000D37BC /* runner.app */; + productType = "com.apple.product-type.application"; + }; + AC0DE2000000000000000007 /* runnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = AC0DE2000000000000000008 /* Build configuration list for PBXNativeTarget "runnerTests" */; + buildPhases = ( + AC0DE2000000000000000003 /* Sources */, + AC0DE2000000000000000004 /* Frameworks */, + AC0DE5000000000000000001 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + AC0DE2000000000000000006 /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + AC0DE2000000000000000002 /* runnerTests */, + ); + name = runnerTests; + productName = runnerTests; + productReference = AC0DE2000000000000000001 /* runnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + AC0DE6000000000000000001 /* runnerUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = AC0DE6000000000000000007 /* Build configuration list for PBXNativeTarget "runnerUITests" */; + buildPhases = ( + AC0DE6000000000000000004 /* Sources */, + AC0DE6000000000000000005 /* Frameworks */, + AC0DE6000000000000000006 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + AC0DE600000000000000000A /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + AC0DE6000000000000000003 /* runnerUITests */, + ); + name = runnerUITests; + productName = runnerUITests; + productReference = 1249911F30644EB800C84B4D /* runnerUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 12D2F2EB2F843F1F000D37BC /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 2630; + LastUpgradeCheck = 2640; + TargetAttributes = { + 12D2F2F22F843F1F000D37BC = { + CreatedOnToolsVersion = 26.3; + }; + }; + }; + buildConfigurationList = 12D2F2EE2F843F1F000D37BC /* Build configuration list for PBXProject "runner" */; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 12D2F2EA2F843F1F000D37BC; + minimizedProjectReferenceProxies = 1; + packageReferences = ( + 122FC5942F9CEDE000BE113A /* XCRemoteSwiftPackageReference "DeviceKit" */, + AC0DE3000000000000000002 /* XCRemoteSwiftPackageReference "libssh2-spm" */, + AC0DE4000000000000000002 /* XCLocalSwiftPackageReference "Packages/CCurl" */, + AC0DEAD00000000000000010 /* XCRemoteSwiftPackageReference "swift-package-manager-google-mobile-ads" */, + ); + preferredProjectObjectVersion = 77; + productRefGroup = 12D2F2F42F843F1F000D37BC /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 12D2F2F22F843F1F000D37BC /* runner */, + AC0DE2000000000000000007 /* runnerTests */, + AC0DE6000000000000000001 /* runnerUITests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 12D2F2F12F843F1F000D37BC /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 12D6D3972FFEE6770006230E /* runner.icon in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AC0DE5000000000000000001 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AC0DE6000000000000000006 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + AC0DE600000000000000000D /* runnerTests/Iap.storekit in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + AC0DE7000000000000000001 /* Build Alpine */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Build Alpine"; + outputPaths = ( + "$(DERIVED_FILE_DIR)/Alpine-$(PLATFORM_NAME)/libAcodeAlpine.a", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/bash; + shellScript = "\"$PROJECT_DIR/Alpine/build.sh\""; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 12D2F2EF2F843F1F000D37BC /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AC0DE2000000000000000003 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AC0DE6000000000000000004 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + AC0DE2000000000000000006 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 12D2F2F22F843F1F000D37BC /* runner */; + targetProxy = AC0DE2000000000000000005 /* PBXContainerItemProxy */; + }; + AC0DE600000000000000000A /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 12D2F2F22F843F1F000D37BC /* runner */; + targetProxy = AC0DE600000000000000000B /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 12D2F2FC2F843F20000D37BC /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DEADBEEF1234DEADBEEF1234 /* Config.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES = "ic_acode_pro ic_acode_midnight_circuit ic_acode_aurora_pulse ic_acode_terminal_glow ic_acode_solar_flare ic_acode_blueprint ic_acode_pixel_party ic_acode_prism ic_acode_porcelain ic_acode_tangerine ic_acode_tidal ic_acode_lilac ic_acode_volt ic_acode_cobalt ic_acode_glacier"; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1023; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.6; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = 1.13.6; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 12D2F2FD2F843F20000D37BC /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DEADBEEF1234DEADBEEF1234 /* Config.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES = "ic_acode_pro ic_acode_midnight_circuit ic_acode_aurora_pulse ic_acode_terminal_glow ic_acode_solar_flare ic_acode_blueprint ic_acode_pixel_party ic_acode_prism ic_acode_porcelain ic_acode_tangerine ic_acode_tidal ic_acode_lilac ic_acode_volt ic_acode_cobalt ic_acode_glacier"; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1023; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.6; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = 1.13.6; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_COMPILATION_MODE = wholemodule; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 12D2F2FF2F843F20000D37BC /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DEADBEEF1234DEADBEEF1234 /* Config.xcconfig */; + buildSettings = { + ALPINE_LDFLAGS = "-lAcodeAlpine -lsqlite3 -lz -lbz2 -llzma -liconv -lxml2"; + ARCHS = arm64; + ASSETCATALOG_COMPILER_APPICON_NAME = runner; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; + CODE_SIGN_STYLE = Automatic; + ENABLE_PREVIEWS = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "$(PROJECT_DIR)/../../.ios-build/App-Info.plist"; + INFOPLIST_KEY_CFBundleDisplayName = Acode; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools"; + IPHONEOS_DEPLOYMENT_TARGET = 18.6; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "$(DERIVED_FILE_DIR)/Alpine-$(PLATFORM_NAME)", + ); + OTHER_LDFLAGS = ( + "$(inherited)", + "-ObjC", + "$(ALPINE_LDFLAGS)", + ); + PRODUCT_BUNDLE_IDENTIFIER = app.acode; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_INCLUDE_PATHS = "$(inherited) $(PROJECT_DIR)/Alpine/include"; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 12D2F3002F843F20000D37BC /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DEADBEEF1234DEADBEEF1234 /* Config.xcconfig */; + buildSettings = { + ALPINE_LDFLAGS = "-lAcodeAlpine -lsqlite3 -lz -lbz2 -llzma -liconv -lxml2"; + ARCHS = arm64; + ASSETCATALOG_COMPILER_APPICON_NAME = runner; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; + CODE_SIGN_STYLE = Automatic; + ENABLE_PREVIEWS = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "$(PROJECT_DIR)/../../.ios-build/App-Info.plist"; + INFOPLIST_KEY_CFBundleDisplayName = Acode; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools"; + IPHONEOS_DEPLOYMENT_TARGET = 18.6; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "$(DERIVED_FILE_DIR)/Alpine-$(PLATFORM_NAME)", + ); + OTHER_LDFLAGS = ( + "$(inherited)", + "-ObjC", + "$(ALPINE_LDFLAGS)", + ); + PRODUCT_BUNDLE_IDENTIFIER = app.acode; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_INCLUDE_PATHS = "$(inherited) $(PROJECT_DIR)/Alpine/include"; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + AC0DE2000000000000000009 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.6; + PRODUCT_BUNDLE_IDENTIFIER = app.acode.tests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SWIFT_INCLUDE_PATHS = "$(inherited) $(PROJECT_DIR)/Alpine/include"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/runner"; + }; + name = Debug; + }; + AC0DE2000000000000000010 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.6; + PRODUCT_BUNDLE_IDENTIFIER = app.acode.tests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SWIFT_INCLUDE_PATHS = "$(inherited) $(PROJECT_DIR)/Alpine/include"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/runner"; + }; + name = Release; + }; + AC0DE6000000000000000008 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.6; + PRODUCT_BUNDLE_IDENTIFIER = "app.acode.ui-tests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_INCLUDE_PATHS = "$(inherited) $(PROJECT_DIR)/Alpine/include"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = runner; + }; + name = Debug; + }; + AC0DE6000000000000000009 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.6; + PRODUCT_BUNDLE_IDENTIFIER = "app.acode.ui-tests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_INCLUDE_PATHS = "$(inherited) $(PROJECT_DIR)/Alpine/include"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = runner; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 12D2F2EE2F843F1F000D37BC /* Build configuration list for PBXProject "runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 12D2F2FC2F843F20000D37BC /* Debug */, + 12D2F2FD2F843F20000D37BC /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 12D2F2FE2F843F20000D37BC /* Build configuration list for PBXNativeTarget "runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 12D2F2FF2F843F20000D37BC /* Debug */, + 12D2F3002F843F20000D37BC /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + AC0DE2000000000000000008 /* Build configuration list for PBXNativeTarget "runnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + AC0DE2000000000000000009 /* Debug */, + AC0DE2000000000000000010 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + AC0DE6000000000000000007 /* Build configuration list for PBXNativeTarget "runnerUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + AC0DE6000000000000000008 /* Debug */, + AC0DE6000000000000000009 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + AC0DE4000000000000000002 /* XCLocalSwiftPackageReference "Packages/CCurl" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Packages/CCurl; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 122FC5942F9CEDE000BE113A /* XCRemoteSwiftPackageReference "DeviceKit" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/devicekit/DeviceKit.git"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 5.8.0; + }; + }; + AC0DE3000000000000000002 /* XCRemoteSwiftPackageReference "libssh2-spm" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/Lakr233/libssh2-spm.git"; + requirement = { + kind = revision; + revision = d211fdf8587532cd952927d9f9f3f5167ce6a77f; + }; + }; + AC0DEAD00000000000000010 /* XCRemoteSwiftPackageReference "swift-package-manager-google-mobile-ads" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/googleads/swift-package-manager-google-mobile-ads.git"; + requirement = { + kind = exactVersion; + version = 13.10.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 122FC5952F9CEDE000BE113A /* DeviceKit */ = { + isa = XCSwiftPackageProductDependency; + package = 122FC5942F9CEDE000BE113A /* XCRemoteSwiftPackageReference "DeviceKit" */; + productName = DeviceKit; + }; + AC0DE3000000000000000003 /* CSSH2 */ = { + isa = XCSwiftPackageProductDependency; + package = AC0DE3000000000000000002 /* XCRemoteSwiftPackageReference "libssh2-spm" */; + productName = CSSH2; + }; + AC0DE4000000000000000003 /* AcodeCurl */ = { + isa = XCSwiftPackageProductDependency; + productName = AcodeCurl; + }; + AC0DEAD00000000000000011 /* GoogleMobileAds */ = { + isa = XCSwiftPackageProductDependency; + package = AC0DEAD00000000000000010 /* XCRemoteSwiftPackageReference "swift-package-manager-google-mobile-ads" */; + productName = GoogleMobileAds; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 12D2F2EB2F843F1F000D37BC /* Project object */; +} diff --git a/platforms/ios/runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/platforms/ios/runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000000..919434a625 --- /dev/null +++ b/platforms/ios/runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Workspace + version = "1.0"> + <FileRef + location = "self:"> + </FileRef> +</Workspace> diff --git a/platforms/ios/runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/platforms/ios/runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000000..84b13bb56a --- /dev/null +++ b/platforms/ios/runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,50 @@ +{ + "originHash" : "55786b149f82d29aa4ac80cb1d17e7780539138ee8768a87556c88feb0b90665", + "pins" : [ + { + "identity" : "devicekit", + "kind" : "remoteSourceControl", + "location" : "https://github.com/devicekit/DeviceKit.git", + "state" : { + "revision" : "56b997e8a61707218f9af09f32b2a1d1806fd792", + "version" : "5.8.0" + } + }, + { + "identity" : "libssh2-spm", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Lakr233/libssh2-spm.git", + "state" : { + "revision" : "d211fdf8587532cd952927d9f9f3f5167ce6a77f" + } + }, + { + "identity" : "openssl-spm", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Lakr233/openssl-spm.git", + "state" : { + "revision" : "9f3b525d960fe71e534482310e96cd9c4f2faa17", + "version" : "3.6.2" + } + }, + { + "identity" : "swift-package-manager-google-mobile-ads", + "kind" : "remoteSourceControl", + "location" : "https://github.com/googleads/swift-package-manager-google-mobile-ads.git", + "state" : { + "revision" : "12b7af0f844723a86fd3c0089b02f64b1e495605", + "version" : "13.10.0" + } + }, + { + "identity" : "swift-package-manager-google-user-messaging-platform", + "kind" : "remoteSourceControl", + "location" : "https://github.com/googleads/swift-package-manager-google-user-messaging-platform.git", + "state" : { + "revision" : "13b248eaa73b7826f0efb1bcf455e251d65ecb1b", + "version" : "3.1.0" + } + } + ], + "version" : 3 +} diff --git a/platforms/ios/runner.xcodeproj/xcshareddata/xcschemes/runner.xcscheme b/platforms/ios/runner.xcodeproj/xcshareddata/xcschemes/runner.xcscheme new file mode 100644 index 0000000000..e966429fa3 --- /dev/null +++ b/platforms/ios/runner.xcodeproj/xcshareddata/xcschemes/runner.xcscheme @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Scheme LastUpgradeVersion="2660" version="1.3"> + <BuildAction parallelizeBuildables="YES" buildImplicitDependencies="YES"> + <BuildActionEntries> + <BuildActionEntry buildForTesting="YES" buildForRunning="YES" buildForProfiling="YES" buildForArchiving="YES" buildForAnalyzing="YES"> + <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="12D2F2F22F843F1F000D37BC" BuildableName="runner.app" BlueprintName="runner" ReferencedContainer="container:runner.xcodeproj"/> + </BuildActionEntry> + </BuildActionEntries> + </BuildAction> + <TestAction customLLDBInitFile="$(SRCROOT)/Alpine/lldbinit" buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.IDEFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv="YES"> + <Testables><TestableReference skipped="NO"> + <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="AC0DE2000000000000000007" BuildableName="runnerTests.xctest" BlueprintName="runnerTests" ReferencedContainer="container:runner.xcodeproj"/> + </TestableReference><TestableReference skipped="NO"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="AC0DE6000000000000000001" BuildableName="runnerUITests.xctest" BlueprintName="runnerUITests" ReferencedContainer="container:runner.xcodeproj"/></TestableReference></Testables> + </TestAction> + <LaunchAction customLLDBInitFile="$(SRCROOT)/Alpine/lldbinit" buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.IDEFoundation.Launcher.LLDB" launchStyle="0" useCustomWorkingDirectory="NO" ignoresPersistentStateOnLaunch="NO" debugDocumentVersioning="YES" debugServiceExtension="internal" allowLocationSimulation="YES"> + <BuildableProductRunnable runnableDebuggingMode="0"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="12D2F2F22F843F1F000D37BC" BuildableName="runner.app" BlueprintName="runner" ReferencedContainer="container:runner.xcodeproj"/></BuildableProductRunnable> + </LaunchAction> + <ProfileAction buildConfiguration="Release" shouldUseLaunchSchemeArgsEnv="YES"/> + <AnalyzeAction buildConfiguration="Debug"/> + <ArchiveAction buildConfiguration="Release" revealArchiveInOrganizer="YES"/> +</Scheme> diff --git a/platforms/ios/runner/AcodeApp.swift b/platforms/ios/runner/AcodeApp.swift new file mode 100644 index 0000000000..fa0df2fa0e --- /dev/null +++ b/platforms/ios/runner/AcodeApp.swift @@ -0,0 +1,53 @@ +// +// AcodeApp.swift +// acode +// +// Created by Ajit Kumar on 07/04/26. +// + +import SwiftUI +import UserNotifications + +class AppDelegate: NSObject, UIApplicationDelegate { + static weak var shared: AppDelegate? + var fullscreenOrientation: UIInterfaceOrientationMask? + + func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil + ) -> Bool { + AppDelegate.shared = self + UNUserNotificationCenter.current().delegate = NotificationService.shared + return true + } + + @available(iOS, deprecated: 26.0, message: "Migrate to UIScene lifecycle when targeting iOS 26+") + func application( + _ app: UIApplication, + open url: URL, + options: [UIApplication.OpenURLOptionsKey: Any] = [:] + ) -> Bool { + IncomingLinks.shared.receive(url) + return true + } + + func application( + _ application: UIApplication, + supportedInterfaceOrientationsFor window: UIWindow? + ) -> UIInterfaceOrientationMask { + fullscreenOrientation ?? (UIDevice.current.userInterfaceIdiom == .pad ? .all : .allButUpsideDown) + } +} + +@main +struct AcodeApp: App { + @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate + + var body: some Scene { + WindowGroup { + ContentView() + .ignoresSafeArea() + .onOpenURL { IncomingLinks.shared.receive($0) } + } + } +} diff --git a/platforms/ios/runner/AppURLSchemeHandler.swift b/platforms/ios/runner/AppURLSchemeHandler.swift new file mode 100644 index 0000000000..6260427418 --- /dev/null +++ b/platforms/ios/runner/AppURLSchemeHandler.swift @@ -0,0 +1,48 @@ +import WebKit + +final class AppURLSchemeHandler: NSObject, WKURLSchemeHandler { + private var active = Set<ObjectIdentifier>() + private let api = AppAPIHandler() + + func webView(_ webView: WKWebView, start task: WKURLSchemeTask) { + if task.request.url?.path.hasPrefix("/__api__/") == true { api.start(task); return } + let id = ObjectIdentifier(task) + active.insert(id) + guard let url = task.request.url, url.host == "localhost" else { + active.remove(id) + task.didFailWithError(URLError(.badURL)); return + } + let head = task.request.httpMethod == "HEAD" + let files = AppFiles.shared + let resource = url.path.hasPrefix("/__cdvfile_") || url.path.hasPrefix("/__file__/") || url.path.hasPrefix("/__cache__/") + ? url.absoluteString + : files.application.appendingPathComponent("bundle").appendingPathComponent(url.path == "/" ? "index.html" : url.path).absoluteString + DispatchQueue.global(qos: .userInitiated).async { [weak self] in + let result = Result { () -> (Data, String) in + let fileURL = try files.resolve(resource) + return try files.coordinate(fileURL) { (try Data(contentsOf: $0), files.mimeType($0)) } + } + DispatchQueue.main.async { + guard self?.active.remove(id) != nil else { return } + switch result { + case .success(let (data, mime)): + let headers = ["Content-Type": mime, "Content-Length": String(data.count), "Cache-Control": "no-cache", "Access-Control-Allow-Origin": "*"] + guard let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: headers) else { task.didFailWithError(URLError(.badServerResponse)); return } + task.didReceive(response) + if !head { task.didReceive(data) } + task.didFinish() + case .failure(let error): + #if DEBUG + print("[scheme] failed \(url.absoluteString) -> \(resource) code=\(FileFailure.code(error))") + #endif + task.didFailWithError(error) + } + } + } + } + + func webView(_ webView: WKWebView, stop task: WKURLSchemeTask) { + api.stop(task) + active.remove(ObjectIdentifier(task)) + } +} diff --git a/platforms/ios/runner/AppWebView.swift b/platforms/ios/runner/AppWebView.swift new file mode 100644 index 0000000000..59b5ccad2a --- /dev/null +++ b/platforms/ios/runner/AppWebView.swift @@ -0,0 +1,16 @@ +import WebKit + +final class AppWebView: WKWebView { + var nativeContextMenuDisabled = false { + didSet { UIMenuSystem.context.setNeedsRebuild() } + } + + override var inputAccessoryView: UIView? { nil } + + override func buildMenu(with builder: UIMenuBuilder) { + super.buildMenu(with: builder) + if nativeContextMenuDisabled && builder.system === UIMenuSystem.context { + builder.replaceChildren(ofMenu: .root) { _ in [] } + } + } +} diff --git a/platforms/ios/runner/Assets.xcassets/AccentColor.colorset/Contents.json b/platforms/ios/runner/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 0000000000..eb87897008 --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/Contents.json b/platforms/ios/runner/Assets.xcassets/Contents.json new file mode 100644 index 0000000000..73c00596a7 --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/SplashBackground.colorset/Contents.json b/platforms/ios/runner/Assets.xcassets/SplashBackground.colorset/Contents.json new file mode 100644 index 0000000000..570a257054 --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/SplashBackground.colorset/Contents.json @@ -0,0 +1,20 @@ +{ + "colors": [ + { + "color": { + "color-space": "srgb", + "components": { + "alpha": "1.000", + "blue": "0x2C", + "green": "0x20", + "red": "0x20" + } + }, + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_aurora_pulse.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_aurora_pulse.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_aurora_pulse.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_aurora_pulse.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_aurora_pulse.appiconset/icon.png new file mode 100644 index 0000000000..23f8590ace Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_aurora_pulse.appiconset/icon.png differ diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_blueprint.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_blueprint.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_blueprint.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_blueprint.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_blueprint.appiconset/icon.png new file mode 100644 index 0000000000..44641296dd Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_blueprint.appiconset/icon.png differ diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_cobalt.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_cobalt.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_cobalt.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_cobalt.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_cobalt.appiconset/icon.png new file mode 100644 index 0000000000..026533fa98 Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_cobalt.appiconset/icon.png differ diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_glacier.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_glacier.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_glacier.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_glacier.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_glacier.appiconset/icon.png new file mode 100644 index 0000000000..2407c66590 Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_glacier.appiconset/icon.png differ diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_lilac.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_lilac.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_lilac.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_lilac.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_lilac.appiconset/icon.png new file mode 100644 index 0000000000..6ed352c1b4 Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_lilac.appiconset/icon.png differ diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_midnight_circuit.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_midnight_circuit.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_midnight_circuit.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_midnight_circuit.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_midnight_circuit.appiconset/icon.png new file mode 100644 index 0000000000..32db88f50c Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_midnight_circuit.appiconset/icon.png differ diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_pixel_party.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_pixel_party.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_pixel_party.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_pixel_party.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_pixel_party.appiconset/icon.png new file mode 100644 index 0000000000..4139890aad Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_pixel_party.appiconset/icon.png differ diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_porcelain.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_porcelain.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_porcelain.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_porcelain.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_porcelain.appiconset/icon.png new file mode 100644 index 0000000000..819a1169fe Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_porcelain.appiconset/icon.png differ diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_prism.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_prism.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_prism.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_prism.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_prism.appiconset/icon.png new file mode 100644 index 0000000000..5bdfa596f1 Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_prism.appiconset/icon.png differ diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_pro.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_pro.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_pro.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_pro.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_pro.appiconset/icon.png new file mode 100644 index 0000000000..29b9bf7577 Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_pro.appiconset/icon.png differ diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_solar_flare.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_solar_flare.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_solar_flare.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_solar_flare.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_solar_flare.appiconset/icon.png new file mode 100644 index 0000000000..ef43af210f Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_solar_flare.appiconset/icon.png differ diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_tangerine.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_tangerine.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_tangerine.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_tangerine.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_tangerine.appiconset/icon.png new file mode 100644 index 0000000000..c208bcc6dc Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_tangerine.appiconset/icon.png differ diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_terminal_glow.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_terminal_glow.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_terminal_glow.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_terminal_glow.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_terminal_glow.appiconset/icon.png new file mode 100644 index 0000000000..bf2caa4bf7 Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_terminal_glow.appiconset/icon.png differ diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_tidal.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_tidal.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_tidal.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_tidal.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_tidal.appiconset/icon.png new file mode 100644 index 0000000000..2b4066be43 Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_tidal.appiconset/icon.png differ diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_volt.appiconset/Contents.json b/platforms/ios/runner/Assets.xcassets/ic_acode_volt.appiconset/Contents.json new file mode 100644 index 0000000000..58ae324d7c --- /dev/null +++ b/platforms/ios/runner/Assets.xcassets/ic_acode_volt.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "icon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/platforms/ios/runner/Assets.xcassets/ic_acode_volt.appiconset/icon.png b/platforms/ios/runner/Assets.xcassets/ic_acode_volt.appiconset/icon.png new file mode 100644 index 0000000000..fa49870984 Binary files /dev/null and b/platforms/ios/runner/Assets.xcassets/ic_acode_volt.appiconset/icon.png differ diff --git a/platforms/ios/runner/Bridge.swift b/platforms/ios/runner/Bridge.swift new file mode 100644 index 0000000000..8d710843d0 --- /dev/null +++ b/platforms/ios/runner/Bridge.swift @@ -0,0 +1,91 @@ +import WebKit + +final class Bridge: NSObject, WKScriptMessageHandler { + private(set) weak var webView: WKWebView? + private(set) weak var viewController: WebViewController? + private var services: [String: ServiceProtocol] = [:] + private var serviceQueues: [String: DispatchQueue] = [:] + private var navigationID = UUID() + private(set) lazy var shareService = ShareService(bridge: self) + + func setup(webView: WKWebView, viewController: WebViewController) { + if !services.isEmpty { reset() } + _ = shareService + self.webView = webView + self.viewController = viewController + services = [ + "Native": NativeService(bridge: self), + "FileHandler": FileHandlerService(bridge: self), + "Device": DeviceService(bridge: self), + "Dialog": DialogService(bridge: self), + "Encryption": EncryptionService(bridge: self), + "Notification": NotificationService(bridge: self), + "Scanner": ScannerService(bridge: self), + "EmbeddedProxy": EmbeddedProxyService(bridge: self), + "File": FileService(bridge: self), + "BuildInfo": BuildInfoService(bridge: self), + "Clipboard": ClipboardService(bridge: self), + "App": AppService(bridge: self), + "SystemBarPlugin": SystemBarService(bridge: self), + "System": SystemService(bridge: self), + "SDcard": DocumentsService(bridge: self), + "NativeHttpPlugin": NativeHTTPService(bridge: self), + "WebSocketPlugin": WebSocketService(bridge: self), + "Tee": PluginContextService(bridge: self), + "Authenticator": AuthenticatorService(bridge: self), + "CustomTabs": SafariService(bridge: self), + "Server": ServerService(bridge: self), + "Browser": BrowserService(bridge: self), + "AcodeWebView": PluginWebViewService(bridge: self), + "Sftp": SFTPService(bridge: self), + "Ftp": FTPService(bridge: self), + "Iap": IapService(bridge: self), + "Alpine": AlpineService(bridge: self), + "Executor": ExecutorService(bridge: self), + "BackgroundExecutor": BackgroundExecutorService(bridge: self), + "AdMob": AMBPlugin(bridge: self), + ] + serviceQueues = services.mapValues { _ in DispatchQueue(label: "app.acode.service." + UUID().uuidString, qos: .userInitiated) } + } + + var adsService: AMBPlugin? { services["AdMob"] as? AMBPlugin } + + // Called on the main thread by WKWebView. + func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) { + guard message.name == "exec", + let body = message.body as? [String: Any], + let service = body["service"] as? String, + let action = body["action"] as? String, + let argsString = body["args"] as? String, + let id = body["id"] as? Int else { return } + + let currentNavigation = navigationID + let callback = Callback(id: id, webView: webView, isValid: { [weak self] in self?.navigationID == currentNavigation }) + guard message.frameInfo.isMainFrame, + let source = message.frameInfo.request.url, + source.scheme == "acode", source.host == "localhost" else { + callback.error("Native services are only available to the app"); return + } + guard let svc = services[service] else { + callback.error(["code": "UNSUPPORTED_SERVICE", "message": "\(service) is unavailable on iOS"]); return + } + + let args: [Any] + if let data = argsString.data(using: .utf8), + let arr = try? JSONSerialization.jsonObject(with: data) as? [Any] { + args = arr + } else { + args = [] + } + + serviceQueues[service]?.async { + svc.exec(action: action, args: args, callback: callback) + } + } + + func reset() { + navigationID = UUID() + shareService.reset() + for (name, service) in services { serviceQueues[name]?.async { service.reset() } } + } +} diff --git a/platforms/ios/runner/Callback.swift b/platforms/ios/runner/Callback.swift new file mode 100644 index 0000000000..422cf7eb13 --- /dev/null +++ b/platforms/ios/runner/Callback.swift @@ -0,0 +1,53 @@ +import WebKit + +final class Callback { + let id: Int + private weak var webView: WKWebView? + private let isValid: () -> Bool + + init(id: Int, webView: WKWebView?, isValid: @escaping () -> Bool = { true }) { + self.id = id + self.webView = webView + self.isValid = isValid + } + + func success(_ value: Any? = nil, keep: Bool = false) { + send(success: value, error: nil, keep: keep, isBinary: false, length: 0) + } + + func successBinary(_ data: Data, keep: Bool = false) { + success(["kind": "arrayBuffer", "data": data.base64EncodedString()], keep: keep) + } + + func error(_ message: Any, keep: Bool = false) { + send(success: nil, error: message, keep: keep, isBinary: false, length: 0) + } + + func release() { + send(success: nil, error: nil, keep: false, isBinary: false, length: 0, status: 0) + } + + private func send(success: Any?, error: Any?, keep: Bool, isBinary: Bool, length: Int, status: Int? = nil) { + var payload: [String: Any] = [ + "id": id, + "keep": keep, + "isBinary": isBinary, + "length": length, + ] + payload["status"] = status ?? (error == nil ? 1 : 9) + if let error = error { + payload["error"] = error + } else { + payload["success"] = success ?? NSNull() + } + + guard let data = try? JSONSerialization.data(withJSONObject: payload), + let json = String(data: data, encoding: .utf8) else { return } + + let js = "window.iOS&&window.iOS.callback(\(json))" + DispatchQueue.main.async { [weak webView, isValid] in + guard isValid() else { return } + webView?.evaluateJavaScript(js, completionHandler: nil) + } + } +} diff --git a/platforms/ios/runner/ContentView.swift b/platforms/ios/runner/ContentView.swift new file mode 100644 index 0000000000..a9a461d0a2 --- /dev/null +++ b/platforms/ios/runner/ContentView.swift @@ -0,0 +1,23 @@ +// +// ContentView.swift +// acode +// +// Created by Ajit Kumar on 07/04/26. +// + +import SwiftUI + +struct ContentView: View { + var body: some View { + WebViewControllerRepresentable() + .ignoresSafeArea() + } +} + +struct WebViewControllerRepresentable: UIViewControllerRepresentable { + func makeUIViewController(context: Context) -> WebViewController { + WebViewController() + } + + func updateUIViewController(_ uiViewController: WebViewController, context: Context) {} +} diff --git a/platforms/ios/runner/EmbeddedProxyServer.swift b/platforms/ios/runner/EmbeddedProxyServer.swift new file mode 100644 index 0000000000..0a84b7748b --- /dev/null +++ b/platforms/ios/runner/EmbeddedProxyServer.swift @@ -0,0 +1,90 @@ +import Foundation +import WebKit + +final class EmbeddedProxyServer { + static let shared = EmbeddedProxyServer() + private let queue = DispatchQueue(label: "acode.embeddedProxy", qos: .userInitiated) + private var listeners: [Int: LocalHTTPServer] = [:] + private var pending: [String: LocalHTTPConnection] = [:] + + func startServer(port: Int, webView: WKWebView) -> Bool { + queue.sync { () -> Bool in + if listeners[port] != nil { return true } + guard (1...65535).contains(port), let server = try? LocalHTTPServer(port: port, loopback: true, queue: queue) else { return false } + listeners[port] = server + server.onRequest = { [weak self, weak webView] request, client in + guard let self else { client.cancel(); return } + self.pending[client.id] = client + let cleanup = client.onClose + client.onClose = { [weak self, weak client] in + cleanup?() + if let client { self?.pending.removeValue(forKey: client.id) } + } + let headers = String(data: (try? JSONSerialization.data(withJSONObject: request.headers)) ?? Data(), encoding: .utf8) ?? "{}" + DispatchQueue.main.async { + guard let webView else { self.sendResponseError(requestId: client.id, errorMessage: "WebView closed"); return } + webView.callAsyncJavaScript("window.__acodeProxy.httpRequest(id,method,url,headers,body)", + arguments: ["id": client.id, "method": request.method, "url": request.target, + "headers": headers, "body": String(decoding: request.body, as: UTF8.self)], + in: nil, in: .page) { result in + if case .failure = result { self.sendResponseError(requestId: client.id, errorMessage: "Preview request handler unavailable") } + } + } + } + server.start { [weak self, weak server] result in + if case .failure = result, self?.listeners[port] === server { self?.listeners.removeValue(forKey: port) } + } + return true + } + } + + func stopServer(port: Int) { + queue.sync { listeners.removeValue(forKey: port)?.stop() } + } + + func stopAll() { + queue.sync { + let servers = Array(listeners.values) + listeners.removeAll() + for server in servers { server.stop() } + } + } + + func hasServer(port: Int) -> Bool { + queue.sync { listeners[port] != nil } + } + + func cancelAllPending() { + queue.sync { + let clients = Array(pending.values) + pending.removeAll() + for client in clients { client.cancel() } + } + } + + func sendResponseStart(requestId: String, status: Int, statusText: String, headersJson: String) { + queue.async { [weak self] in + guard let client = self?.pending[requestId], (200...599).contains(status) else { return } + let headers = (try? JSONSerialization.jsonObject(with: Data(headersJson.utf8))) as? [String: String] ?? [:] + let length = headers.first { $0.key.lowercased() == "content-length" }.flatMap { UInt64($0.value) } + client.startResponse(status: status, headers: headers, length: length) + } + } + + func sendResponseData(requestId: String, chunkBase64: String, index: Int) { + queue.async { [weak self] in + guard let client = self?.pending[requestId], let data = Data(base64Encoded: chunkBase64) else { return } + client.send(data) + } + } + + func sendResponseEnd(requestId: String) { + queue.async { [weak self] in self?.pending[requestId]?.end() } + } + + func sendResponseError(requestId: String, errorMessage: String) { + queue.async { [weak self] in + self?.pending[requestId]?.respond(status: 502, headers: ["Content-Type": "text/plain"], body: Data(errorMessage.utf8)) + } + } +} diff --git a/platforms/ios/runner/EmbeddedProxyService.swift b/platforms/ios/runner/EmbeddedProxyService.swift new file mode 100644 index 0000000000..1cbb7347bc --- /dev/null +++ b/platforms/ios/runner/EmbeddedProxyService.swift @@ -0,0 +1,88 @@ +final class EmbeddedProxyService: BaseService { + + private let server = EmbeddedProxyServer.shared + + override func exec(action: String, args: [Any], callback: Callback) { + switch action { + case "responseStart": + handleResponseStart(args: args, callback: callback) + case "responseData": + handleResponseData(args: args, callback: callback) + case "responseEnd": + handleResponseEnd(args: args, callback: callback) + case "responseError": + handleResponseError(args: args, callback: callback) + default: + callback.error("Unknown action: \(action)") + } + } + + override func reset() { cleanupAll() } + + // MARK: - Response Handlers + + private func handleResponseStart(args: [Any], callback: Callback) { + guard let requestId = args[safe: 0] as? String, + let status = args[safe: 1] as? Int, + let statusText = args[safe: 2] as? String, + let headersJson = args[safe: 3] as? String else { + callback.error("Invalid responseStart args") + return + } + + server.sendResponseStart(requestId: requestId, status: status, statusText: statusText, headersJson: headersJson) + callback.success() + } + + private func handleResponseData(args: [Any], callback: Callback) { + guard let requestId = args[safe: 0] as? String, + let chunk = args[safe: 1] as? String, + let index = args[safe: 2] as? Int else { + callback.error("Invalid responseData args") + return + } + + server.sendResponseData(requestId: requestId, chunkBase64: chunk, index: index) + callback.success() + } + + private func handleResponseEnd(args: [Any], callback: Callback) { + guard let requestId = args[safe: 0] as? String else { + callback.error("Invalid responseEnd args") + return + } + + server.sendResponseEnd(requestId: requestId) + callback.success() + } + + private func handleResponseError(args: [Any], callback: Callback) { + guard let requestId = args[safe: 0] as? String else { + callback.error("Invalid responseError args") + return + } + let errorMessage = args[safe: 1] as? String ?? "Unknown error" + server.sendResponseError(requestId: requestId, errorMessage: errorMessage) + callback.success() + } + + // MARK: - Server Lifecycle + + func ensureServer(port: Int) -> Bool { + guard let webView = bridge?.webView else { return false } + return server.startServer(port: port, webView: webView) + } + + func cleanupServer(port: Int) { + server.stopServer(port: port) + } + + func cleanupAll() { + server.cancelAllPending() + server.stopAll() + } + + func hasServer(port: Int) -> Bool { + return server.hasServer(port: port) + } +} diff --git a/platforms/ios/runner/FTP-Licenses.txt b/platforms/ios/runner/FTP-Licenses.txt new file mode 100644 index 0000000000..14b9325829 --- /dev/null +++ b/platforms/ios/runner/FTP-Licenses.txt @@ -0,0 +1,27 @@ +Acode iOS FTP transport: curl 8.22.0 +https://curl.se/ + +COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 1996 - 2026, Daniel Stenberg, <daniel@haxx.se>, and many +contributors, see the THANKS file. + +All rights reserved. + +Permission to use, copy, modify, and distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright +notice and this permission notice appear in all copies. + +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 OF THIRD PARTY RIGHTS. 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. + +Except as contained in this notice, the name of a copyright holder shall not +be used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization of the copyright holder. + +The shared OpenSSL dependency is covered in SSH-Licenses.txt. diff --git a/platforms/ios/runner/FullscreenBackControls.swift b/platforms/ios/runner/FullscreenBackControls.swift new file mode 100644 index 0000000000..02ad823ccb --- /dev/null +++ b/platforms/ios/runner/FullscreenBackControls.swift @@ -0,0 +1,105 @@ +import UIKit + +@MainActor +final class FullscreenBackControls: NSObject, UIGestureRecognizerDelegate { + private let button = UIButton(type: .system) + private let gesture = UIScreenEdgePanGestureRecognizer() + private let revealGesture = UIPanGestureRecognizer() + private let action: () -> Void + private var available = false + private var hideTask: Task<Void, Never>? + + init(controller: UIViewController, action: @escaping () -> Void) { + self.action = action + super.init() + var configuration = UIButton.Configuration.gray() + configuration.image = UIImage(systemName: "chevron.left") + configuration.baseForegroundColor = .label + configuration.background.backgroundColor = .secondarySystemBackground + configuration.cornerStyle = .capsule + button.configuration = configuration + button.accessibilityLabel = "Back" + button.accessibilityIdentifier = "fullscreen-back" + button.isHidden = true + button.addTarget(self, action: #selector(back), for: .touchUpInside) + controller.view.addSubview(button) + button.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + button.widthAnchor.constraint(equalToConstant: 44), + button.heightAnchor.constraint(equalToConstant: 44), + button.leadingAnchor.constraint(equalTo: controller.view.safeAreaLayoutGuide.leadingAnchor, constant: 8), + button.topAnchor.constraint(equalTo: controller.view.safeAreaLayoutGuide.topAnchor, constant: 8), + ]) + gesture.edges = .left + gesture.isEnabled = false + gesture.delegate = self + gesture.addTarget(self, action: #selector(swiped)) + controller.view.addGestureRecognizer(gesture) + revealGesture.isEnabled = false + revealGesture.delegate = self + revealGesture.maximumNumberOfTouches = 1 + revealGesture.addTarget(self, action: #selector(revealed)) + controller.view.addGestureRecognizer(revealGesture) + } + + func update(active: Bool, enabled: Bool, theme: String) { + available = active && enabled + if !available { hide() } + button.isEnabled = available + button.overrideUserInterfaceStyle = theme == "light" ? .light : .dark + gesture.isEnabled = available + revealGesture.isEnabled = available + } + + func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { + guard gestureRecognizer === revealGesture, let view = revealGesture.view else { return true } + return touch.location(in: view).y <= view.safeAreaInsets.top + 44 + } + + func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { + if gestureRecognizer === revealGesture { + let velocity = revealGesture.velocity(in: revealGesture.view) + return velocity.y > abs(velocity.x) + } + let velocity = gesture.velocity(in: gesture.view) + return velocity.x > abs(velocity.y) + } + + @objc private func back() { + show() + action() + } + + @objc private func revealed() { + let translation = revealGesture.translation(in: revealGesture.view) + if revealGesture.state == .ended, translation.y >= 40, translation.y > abs(translation.x) { + show() + } + } + + @objc private func swiped() { + let translation = gesture.translation(in: gesture.view) + if gesture.state == .ended, translation.x >= 60, translation.x > abs(translation.y) { + action() + } + } + + private func show() { + guard available else { return } + hideTask?.cancel() + button.isHidden = false + hideTask = Task { [weak self] in + do { try await Task.sleep(for: .seconds(3)) } catch { return } + guard !Task.isCancelled else { return } + self?.hide() + } + } + + private func hide() { + hideTask?.cancel() + hideTask = nil + button.isHidden = true + } + + deinit { hideTask?.cancel() } +} diff --git a/platforms/ios/runner/Info.plist b/platforms/ios/runner/Info.plist new file mode 100644 index 0000000000..c8aef1014a --- /dev/null +++ b/platforms/ios/runner/Info.plist @@ -0,0 +1,107 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>CFBundleDevelopmentRegion</key> + <string>$(DEVELOPMENT_LANGUAGE)</string> + <key>CFBundleDisplayName</key> + <string>Acode</string> + <key>CFBundleExecutable</key> + <string>$(EXECUTABLE_NAME)</string> + <key>CFBundleIconFile</key> + <string>runner</string> + <key>CFBundleIdentifier</key> + <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundleName</key> + <string>Acode</string> + <key>CFBundlePackageType</key> + <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string> + <key>CFBundleShortVersionString</key> + <string>$(MARKETING_VERSION)</string> + <key>CFBundleURLTypes</key> + <array> + <dict> + <key>CFBundleURLName</key> + <string>acode-deep-link</string> + <key>CFBundleURLSchemes</key> + <array> + <string>acode</string> + </array> + </dict> + </array> + <key>CFBundleVersion</key> + <string>$(CURRENT_PROJECT_VERSION)</string> + <key>UIFileSharingEnabled</key> + <true/> + <key>LSSupportsOpeningDocumentsInPlace</key> + <true/> + <key>CFBundleDocumentTypes</key> + <array> + <dict> + <key>CFBundleTypeName</key> + <string>Document</string> + <key>CFBundleTypeRole</key> + <string>Editor</string> + <key>LSHandlerRank</key> + <string>Alternate</string> + <key>LSItemContentTypes</key> + <array><string>public.data</string><string>public.content</string></array> + </dict> + </array> + <key>LSRequiresIPhoneOS</key> + <true/> + <key>LSApplicationQueriesSchemes</key> + <array> + <string>googlechrome</string> + <string>googlechromes</string> + <string>firefox</string> + </array> + <key>NSCameraUsageDescription</key> + <string>Used for QR code scanning and capturing photos.</string> + <key>NSLocalNetworkUsageDescription</key> + <string>Used for connecting to local network services and the development server.</string> + <key>NSAppTransportSecurity</key> + <dict> + <key>NSAllowsArbitraryLoads</key> + <true/> + </dict> + <key>NSMicrophoneUsageDescription</key> + <string>Used for recording audio.</string> + <key>NSPhotoLibraryAddUsageDescription</key> + <string>Used for saving files to your photo library.</string> + <key>NSPhotoLibraryUsageDescription</key> + <string>Used for accessing photos when capturing from camera.</string> + <key>UIApplicationSceneManifest</key> + <dict> + <key>UIApplicationSupportsMultipleScenes</key> + <false/> + + </dict> + <key>UIApplicationSupportsIndirectInputEvents</key> + <true/> + <key>UILaunchScreen</key> + <dict> + <key>UIColorName</key> + <string>SplashBackground</string> + </dict> + <key>UIStatusBarStyle</key> + <string>UIStatusBarStyleLightContent</string> + <key>UISupportedInterfaceOrientations</key> + <array> + <string>UIInterfaceOrientationPortrait</string> + <string>UIInterfaceOrientationLandscapeLeft</string> + <string>UIInterfaceOrientationLandscapeRight</string> + </array> + <key>UISupportedInterfaceOrientations~ipad</key> + <array> + <string>UIInterfaceOrientationPortrait</string> + <string>UIInterfaceOrientationLandscapeLeft</string> + <string>UIInterfaceOrientationLandscapeRight</string> + <string>UIInterfaceOrientationPortraitUpsideDown</string> + </array> + <key>UIViewControllerBasedStatusBarAppearance</key> + <true/> +</dict> +</plist> diff --git a/platforms/ios/runner/PrivacyInfo.xcprivacy b/platforms/ios/runner/PrivacyInfo.xcprivacy new file mode 100644 index 0000000000..fb4b44c165 --- /dev/null +++ b/platforms/ios/runner/PrivacyInfo.xcprivacy @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>NSPrivacyAccessedAPITypes</key> + <array> + <dict> + <key>NSPrivacyAccessedAPIType</key> + <string>NSPrivacyAccessedAPICategoryFileTimestamp</string> + <key>NSPrivacyAccessedAPITypeReasons</key> + <array> + <string>C617.1</string> + <string>3B52.1</string> + </array> + </dict> + <dict> + <key>NSPrivacyAccessedAPIType</key> + <string>NSPrivacyAccessedAPICategoryDiskSpace</string> + <key>NSPrivacyAccessedAPITypeReasons</key> + <array> + <string>E174.1</string> + </array> + </dict> + <dict> + <key>NSPrivacyAccessedAPIType</key> + <string>NSPrivacyAccessedAPICategoryUserDefaults</string> + <key>NSPrivacyAccessedAPITypeReasons</key> + <array> + <string>CA92.1</string> + </array> + </dict> + <dict> + <key>NSPrivacyAccessedAPIType</key> + <string>NSPrivacyAccessedAPICategorySystemBootTime</string> + <key>NSPrivacyAccessedAPITypeReasons</key> + <array> + <string>35F9.1</string> + </array> + </dict> + </array> +</dict> +</plist> diff --git a/platforms/ios/runner/SSH-Licenses.txt b/platforms/ios/runner/SSH-Licenses.txt new file mode 100644 index 0000000000..d3f357804f --- /dev/null +++ b/platforms/ios/runner/SSH-Licenses.txt @@ -0,0 +1,279 @@ +Third-party software used by Acode for iOS remote connections + +libssh2 (BSD) +============= +/* Copyright (C) 2004-2007 Sara Golemon <sarag@libssh2.org> + * Copyright (C) 2005,2006 Mikhail Gusarov <dottedmag@dottedmag.net> + * Copyright (C) 2006-2007 The Written Word, Inc. + * Copyright (C) 2007 Eli Fant <elifantu@mail.ru> + * Copyright (C) 2009-2023 Daniel Stenberg + * Copyright (C) 2008, 2009 Simon Josefsson + * Copyright (C) 2000 Markus Friedl + * Copyright (C) 2015 Microsoft Corp. + * All rights reserved. + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted provided + * that the following conditions are met: + * + * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * + * 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. + * + * Neither the name of the copyright holder nor the names + * of any other contributors may be used to endorse or + * promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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. + */ + + +libssh2 Swift package (MIT) +=========================== +MIT License + +Copyright (c) 2024 Lakr Aream + +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. + + +OpenSSL Swift package (MIT) +=========================== +MIT License + +Copyright (c) 2023 Lakr Aream + +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. + +OpenSSL 3.6.2 (Apache-2.0) +========================== + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + diff --git a/platforms/ios/runner/Service.swift b/platforms/ios/runner/Service.swift new file mode 100644 index 0000000000..24dba0ad14 --- /dev/null +++ b/platforms/ios/runner/Service.swift @@ -0,0 +1,53 @@ +import UIKit +import WebKit + +protocol ServiceProtocol: AnyObject { + func exec(action: String, args: [Any], callback: Callback) + func reset() +} + +class BaseService: NSObject, ServiceProtocol { + weak var bridge: Bridge? + + required init(bridge: Bridge) { + self.bridge = bridge + } + + var webView: WKWebView? { bridge?.webView } + var viewController: WebViewController? { bridge?.viewController } + + func exec(action: String, args: [Any], callback: Callback) { + callback.error("Action '\(action)' not implemented") + } + + func reset() {} +} + +// MARK: - Shared utilities + +extension Array { + subscript(safe index: Int) -> Element? { + indices.contains(index) ? self[index] : nil + } +} + +extension UIColor { + convenience init?(hexString: String) { + let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) + var int: UInt64 = 0 + Scanner(string: hex).scanHexInt64(&int) + let a, r, g, b: UInt64 + switch hex.count { + case 3: (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) + case 6: (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) + case 8: (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) + default: return nil + } + self.init( + red: Double(r) / 255, + green: Double(g) / 255, + blue: Double(b) / 255, + alpha: Double(a) / 255 + ) + } +} diff --git a/platforms/ios/runner/SimulatorTestSupport.swift b/platforms/ios/runner/SimulatorTestSupport.swift new file mode 100644 index 0000000000..59116c8b29 --- /dev/null +++ b/platforms/ios/runner/SimulatorTestSupport.swift @@ -0,0 +1,19 @@ +#if DEBUG +import WebKit + +@MainActor +enum SimulatorTestSupport { + static func disableConsent(in scripts: WKUserContentController) { + guard !scripts.userScripts.contains(where: { $0.source.contains("iosConsentFixture") }) else { return } + // Suppress network consent independently of the test's StoreKit entitlements. + scripts.addUserScript(WKUserScript(source: """ + Object.defineProperty(window,'admob',{configurable:true,set(value){ + value.privacy.gatherConsent=async function iosConsentFixture(){ + return {consentStatus:'unknown',canRequestAds:false,privacyOptionsRequired:false}; + }; + Object.defineProperty(window,'admob',{configurable:true,writable:true,value}); + }}); + """, injectionTime: .atDocumentStart, forMainFrameOnly: true)) + } +} +#endif diff --git a/platforms/ios/runner/WebContextMenu.swift b/platforms/ios/runner/WebContextMenu.swift new file mode 100644 index 0000000000..7f943d0b79 --- /dev/null +++ b/platforms/ios/runner/WebContextMenu.swift @@ -0,0 +1,126 @@ +import WebKit + +final class WebContextMenu: NSObject, UIGestureRecognizerDelegate { + private weak var webView: WKWebView? + let gesture: UILongPressGestureRecognizer + + init(webView: WKWebView) { + self.webView = webView + gesture = UILongPressGestureRecognizer() + super.init() + gesture.minimumPressDuration = 0.45 + gesture.allowableMovement = 10 + gesture.cancelsTouchesInView = false + gesture.delegate = self + gesture.addTarget(self, action: #selector(handlePress)) + webView.addGestureRecognizer(gesture) + webView.configuration.userContentController.addUserScript( + WKUserScript(source: Self.script, injectionTime: .atDocumentStart, forMainFrameOnly: false) + ) + } + + func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, + shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { + true + } + + @objc private func handlePress() { + guard gesture.state == .began else { return } + send() + } + + func send() { + webView?.evaluateJavaScript("window.acodeNativeContextMenu?.()", completionHandler: nil) + } + + static let script = """ + (() => { + let press, suppressed; + let shadowRoots = []; + const messageType = 'acode-native-contextmenu'; + const cancel = () => { + press = null; + for (const root of shadowRoots) root.removeEventListener('scroll', cancel, true); + shadowRoots = []; + }; + const reset = () => { cancel(); suppressed?.restoreCallout?.(); suppressed = null; }; + const receive = () => { + if (press && !suppressed && press.target.isConnected && + press.target.getAttribute('data-url') === press.url && + performance.now() - press.started >= 400) { + const {target, pointerId, clientX, clientY} = press; + const event = new MouseEvent('contextmenu', { + bubbles: true, cancelable: true, composed: true, + button: 2, buttons: 2, clientX, clientY + }); + suppressed = {target, pointerId, until: Infinity}; + target.dispatchEvent(event); + const link = target.closest('a, img'); + if (event.defaultPrevented && link) { + const value = link.style.getPropertyValue('-webkit-touch-callout'); + const priority = link.style.getPropertyPriority('-webkit-touch-callout'); + suppressed.restoreCallout = () => value + ? link.style.setProperty('-webkit-touch-callout', value, priority) + : link.style.removeProperty('-webkit-touch-callout'); + link.style.setProperty('-webkit-touch-callout', 'none'); + } + } + for (let i = 0; i < frames.length; i++) + frames[i].postMessage({type: messageType}, '*'); + }; + window.acodeNativeContextMenu = receive; + window.addEventListener('message', event => { + if (event.source === parent && event.data?.type === messageType) + receive(); + }); + document.addEventListener('pointerdown', event => { + reset(); + if (event.pointerType !== 'touch' || !event.isPrimary) return; + const target = event.composedPath()[0]; + if (!(target instanceof Element)) return; + const current = press = { + target, pointerId: event.pointerId, clientX: event.clientX, + clientY: event.clientY, started: performance.now(), url: target.getAttribute('data-url') + }; + shadowRoots = event.composedPath().filter(node => node instanceof ShadowRoot); + for (const root of shadowRoots) root.addEventListener('scroll', cancel, true); + queueMicrotask(() => { if (press === current && event.defaultPrevented) cancel(); }); + }, true); + document.addEventListener('touchstart', event => { + const current = press; + queueMicrotask(() => { if (press === current && event.defaultPrevented) cancel(); }); + }, {capture: true, passive: true}); + document.addEventListener('pointermove', event => { + if (event.pointerId === press?.pointerId && + Math.hypot(event.clientX - press.clientX, event.clientY - press.clientY) > 10) + cancel(); + }, true); + for (const type of ['pointerup', 'pointercancel']) + document.addEventListener(type, event => { + if (event.pointerId === press?.pointerId) cancel(); + if (event.pointerId === suppressed?.pointerId) suppressed.until = Date.now() + 700; + }, true); + document.addEventListener('contextmenu', event => { + if (!event.isTrusted) return; + if (suppressed && event.composedPath().includes(suppressed.target)) { + event.preventDefault(); + event.stopImmediatePropagation(); + } else if (press) { + suppressed = {target: press.target, pointerId: press.pointerId, until: Infinity}; + cancel(); + } + }, true); + document.addEventListener('click', event => { + if (!event.isTrusted) return; + if (event.detail && suppressed && Date.now() < suppressed.until) { + event.preventDefault(); + event.stopImmediatePropagation(); + } + reset(); + }, true); + document.addEventListener('scroll', cancel, true); + window.addEventListener('blur', reset); + window.addEventListener('pagehide', reset); + })(); + """ +} diff --git a/platforms/ios/runner/WebFullscreen.swift b/platforms/ios/runner/WebFullscreen.swift new file mode 100644 index 0000000000..fe26a3357c --- /dev/null +++ b/platforms/ios/runner/WebFullscreen.swift @@ -0,0 +1,163 @@ +import UIKit +import WebKit + +@MainActor +final class WebFullscreen: NSObject { + private weak var controller: WebViewController? + private weak var scene: UIWindowScene? + private var observation: NSKeyValueObservation? + private var task: Task<Void, Never>? + private var pending: Callback? + private var requestID = UUID() + private var foreground = true + private var controls: FullscreenBackControls! + private var hasBackHandler = false + var isFullscreen: Bool { + let state = controller?.webView.fullscreenState + return controller?.isFullscreenLayout == true || state == .inFullscreen || state == .enteringFullscreen + } + private(set) var requestedOrientation: UIInterfaceOrientationMask? + + init(controller: WebViewController) { + self.controller = controller + super.init() + controls = FullscreenBackControls(controller: controller) { [weak self] in self?.back() } + observation = controller.webView.observe(\.fullscreenState, options: [.new]) { [weak self] webView, _ in + MainActor.assumeIsolated { + guard let self, self.controller?.isFullscreenLayout != true else { return } + if webView.fullscreenState == .notInFullscreen || webView.fullscreenState == .exitingFullscreen { + self.hasBackHandler = false + self.reset() + } + } + } + NotificationCenter.default.addObserver(self, selector: #selector(pause), name: UIApplication.willResignActiveNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(resume), name: UIApplication.didBecomeActiveNotification, object: nil) + } + + func setActive(_ active: Bool, callback: Callback? = nil) { + guard !active || foreground else { callback?.error("Fullscreen requires the foreground app."); return } + if !active { hasBackHandler = false; reset() } + controller?.setFullscreenLayout(active) + callback?.success() + } + + func setBackHandler(_ enabled: Bool, callback: Callback) { + guard !enabled || (foreground && isFullscreen) else { + callback.error("Back handler requires foreground fullscreen."); return + } + hasBackHandler = enabled + callback.success() + } + + func updateControls() { + controls.update(active: controller?.isFullscreenLayout == true, enabled: foreground, theme: controller?.themeType ?? "dark") + } + + func back() { + guard foreground, isFullscreen else { return } + let script = hasBackHandler + ? "document.dispatchEvent(new Event('fullscreenbackbutton'));" + : "Promise.resolve(document.exitFullscreen()).catch(console.error);" + controller?.webView.evaluateJavaScript(script, completionHandler: nil) + } + + func setOrientation(_ value: Any?, callback: Callback) { + guard let value, !(value is NSNull) else { reset(); callback.success(); return } + let mask: UIInterfaceOrientationMask + switch value as? String { + case "landscape": mask = .landscape + case "portrait": mask = UIDevice.current.userInterfaceIdiom == .pad ? [.portrait, .portraitUpsideDown] : .portrait + default: callback.error("Orientation must be landscape or portrait."); return + } + guard foreground, isFullscreen, let scene = controller?.view.window?.windowScene, + scene.activationState == .foregroundActive else { + callback.error("Orientation requires foreground fullscreen."); return + } + self.scene = scene + cancelPending() + requestedOrientation = mask + pending = callback + apply(mask, scene: scene) + } + + func reset() { + cancelPending() + requestedOrientation = nil + restorePolicy() + } + + @objc private func pause() { + foreground = false + updateControls() + if pending != nil { reset() } + else { cancelPending(); restorePolicy() } + } + + @objc private func resume() { + foreground = true + updateControls() + if let mask = requestedOrientation, isFullscreen, let scene { apply(mask, scene: scene) } + } + + private func apply(_ mask: UIInterfaceOrientationMask, scene: UIWindowScene) { + let id = UUID() + requestID = id + AppDelegate.shared?.fullscreenOrientation = mask + updateControllers() + scene.requestGeometryUpdate(.iOS(interfaceOrientations: mask)) { [weak self] error in + self?.fail(error.localizedDescription, request: id) + } + task = Task { [weak self, weak scene] in + for _ in 0..<150 { + do { try await Task.sleep(for: .milliseconds(20)) } catch { return } + guard let self, let scene, self.requestID == id else { return } + guard self.foreground, self.isFullscreen, scene.activationState == .foregroundActive else { + self.fail("Fullscreen session changed.", request: id); return + } + let orientation = scene.effectiveGeometry.interfaceOrientation + if mask.contains(UIInterfaceOrientationMask(rawValue: 1 << orientation.rawValue)) { + let callback = self.pending; self.pending = nil + self.task = nil + callback?.success() + return + } + } + self?.fail("iOS could not apply this orientation.", request: id) + } + } + + private func fail(_ message: String, request: UUID) { + guard requestID == request else { return } + let callback = pending; pending = nil + reset() + callback?.error(message) + } + + private func cancelPending() { + requestID = UUID() + task?.cancel(); task = nil + pending?.error("Fullscreen orientation request cancelled."); pending = nil + } + + private func restorePolicy() { + guard AppDelegate.shared?.fullscreenOrientation != nil else { return } + AppDelegate.shared?.fullscreenOrientation = nil + updateControllers() + let normal: UIInterfaceOrientationMask = UIDevice.current.userInterfaceIdiom == .pad ? .all : .allButUpsideDown + scene?.requestGeometryUpdate(.iOS(interfaceOrientations: normal)) + } + + private func updateControllers() { + controller?.setNeedsUpdateOfSupportedInterfaceOrientations() + for window in scene?.windows ?? [] { + var current = window.rootViewController + while let controller = current { + controller.setNeedsUpdateOfSupportedInterfaceOrientations() + current = controller.presentedViewController + } + } + } + + deinit { NotificationCenter.default.removeObserver(self) } +} diff --git a/platforms/ios/runner/WebShadowCaret.swift b/platforms/ios/runner/WebShadowCaret.swift new file mode 100644 index 0000000000..8e975f448b --- /dev/null +++ b/platforms/ios/runner/WebShadowCaret.swift @@ -0,0 +1,28 @@ +import WebKit + +enum WebShadowCaret { + static let script = """ + (() => { + const nativeAddRange = Selection.prototype.addRange; + if (nativeAddRange.name === 'acodeShadowCaretAddRange') return; + Selection.prototype.addRange = function acodeShadowCaretAddRange(range) { + const result = nativeAddRange.call(this, range); + if (this.rangeCount || !range.collapsed) return result; + const node = range.startContainer; + const root = node.getRootNode(); + const editor = root instanceof ShadowRoot ? root.activeElement : null; + if (!node.isConnected || node.ownerDocument !== document || + this !== document.getSelection() || !editor?.isContentEditable || + !editor.contains(node)) return result; + // Document selections reject shadow-root Ranges in WebKit, even for a focused caret. + this.setBaseAndExtent(node, range.startOffset, node, range.startOffset); + return result; + }; + })(); + """ + + static func install(on controller: WKUserContentController) { + guard !controller.userScripts.contains(where: { $0.source == script }) else { return } + controller.addUserScript(WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false)) + } +} diff --git a/platforms/ios/runner/WebViewController.swift b/platforms/ios/runner/WebViewController.swift new file mode 100644 index 0000000000..1b353ab99a --- /dev/null +++ b/platforms/ios/runner/WebViewController.swift @@ -0,0 +1,224 @@ +import UIKit +import WebKit +import GameController + +final class WebViewController: UIViewController { + private(set) var webView: WKWebView! + let bridge = Bridge() + private(set) var isKeyboardVisible = false + private(set) var keyboardHeight: CGFloat = 0 + private(set) var fullscreen: WebFullscreen! + private var contentTop: NSLayoutConstraint! + private var contentBottom: NSLayoutConstraint! + private var normalLayout: [NSLayoutConstraint] = [] + private var fullscreenLayout: [NSLayoutConstraint] = [] + var isFullscreenLayout: Bool { fullscreenLayout.first?.isActive == true } + private var scrollObservation: NSKeyValueObservation? + private var contextMenu: WebContextMenu? + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = UIColor(named: "SplashBackground") + + let config = WKWebViewConfiguration() + config.setURLSchemeHandler(AppURLSchemeHandler(), forURLScheme: "acode") + + let contentController = WKUserContentController() + #if DEBUG && targetEnvironment(simulator) + if ProcessInfo.processInfo.arguments.contains("-acode-ui-testing") { + SimulatorTestSupport.disableConsent(in: contentController) + } + #endif + WebShadowCaret.install(on: contentController) + contentController.add(WeakScriptMessageHandler(bridge), name: "exec") + config.userContentController = contentController + config.preferences.javaScriptCanOpenWindowsAutomatically = true + config.preferences.isElementFullscreenEnabled = true + + config.allowsInlineMediaPlayback = true + webView = AppWebView(frame: .zero, configuration: config) + contextMenu = WebContextMenu(webView: webView) + webView.navigationDelegate = self + #if DEBUG + webView.isInspectable = true + #endif + webView.scrollView.bounces = false + webView.scrollView.contentInsetAdjustmentBehavior = .never + webView.scrollView.isScrollEnabled = false + webView.backgroundColor = view.backgroundColor + webView.isOpaque = false + + let content = UIView() + view.addSubview(content) + content.addSubview(webView) + content.translatesAutoresizingMaskIntoConstraints = false + webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] + contentTop = content.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor) + contentBottom = content.bottomAnchor.constraint(equalTo: view.keyboardLayoutGuide.topAnchor) + normalLayout = [ + contentTop, + content.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), + content.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), + contentBottom, + ] + fullscreenLayout = [ + content.topAnchor.constraint(equalTo: view.topAnchor), + content.leadingAnchor.constraint(equalTo: view.leadingAnchor), + content.trailingAnchor.constraint(equalTo: view.trailingAnchor), + content.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ] + NSLayoutConstraint.activate(normalLayout) + + // The keyboard layout guide resizes the editor; WebKit scrolling would shift it twice. + scrollObservation = webView.scrollView.observe(\.contentOffset, options: [.new]) { scrollView, _ in + if scrollView.contentOffset != .zero { + scrollView.contentOffset = .zero + } + } + + fullscreen = WebFullscreen(controller: self) + bridge.setup(webView: webView, viewController: self) + webView.load(URLRequest(url: URL(string: "acode://localhost/")!)) + observeKeyboard() + + NotificationCenter.default.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(appCameToForeground), name: UIApplication.willEnterForegroundNotification, object: nil) + } + + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + bridge.adsService?.banners.layout() + } + + func setContentInsets(top: CGFloat, bottom: CGFloat) { + guard contentTop.constant != top || contentBottom.constant != -bottom else { return } + contentTop.constant = top + contentBottom.constant = -bottom + view.layoutIfNeeded() + } + + func setFullscreenLayout(_ active: Bool) { + NSLayoutConstraint.deactivate(active ? normalLayout : fullscreenLayout) + NSLayoutConstraint.activate(active ? fullscreenLayout : normalLayout) + setThemeType(themeType) + setNeedsUpdateOfHomeIndicatorAutoHidden() + setNeedsUpdateOfScreenEdgesDeferringSystemGestures() + view.layoutIfNeeded() + bridge.adsService?.banners.layout() + } + + @objc func appMovedToBackground() { + let script = "document.dispatchEvent(new CustomEvent('pause'));" + webView.evaluateJavaScript(script, completionHandler: nil) + } + + @objc func appCameToForeground() { + let script = "document.dispatchEvent(new CustomEvent('resume'));" + webView.evaluateJavaScript(script, completionHandler: nil) + } + + private func observeKeyboard() { + NotificationCenter.default.addObserver( + self, selector: #selector(keyboardWillShow), + name: UIResponder.keyboardWillChangeFrameNotification, object: nil + ) + NotificationCenter.default.addObserver( + self, selector: #selector(keyboardWillHide), + name: UIResponder.keyboardWillHideNotification, object: nil + ) + } + + @objc private func keyboardWillShow(_ notification: Notification) { + guard let info = notification.userInfo, + let frame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return } + let localFrame = view.convert(frame, from: nil) + keyboardHeight = max(0, view.bounds.intersection(localFrame).height - view.safeAreaInsets.bottom) + isKeyboardVisible = keyboardHeight > 0 + webView.evaluateJavaScript("window.dispatchEvent(new CustomEvent('keyboardshow', { detail: { height: \(keyboardHeight) } }))", completionHandler: nil) + } + + @objc private func keyboardWillHide(_ notification: Notification) { + isKeyboardVisible = false + keyboardHeight = 0 + webView.evaluateJavaScript("window.dispatchEvent(new CustomEvent('keyboardhide'))", completionHandler: nil) + } + + private(set) var themeType: String = "dark" + + override var preferredStatusBarStyle: UIStatusBarStyle { + themeType == "light" ? .darkContent : .lightContent + } + + var statusBarHidden = false + override var prefersStatusBarHidden: Bool { statusBarHidden || isFullscreenLayout } + override var prefersHomeIndicatorAutoHidden: Bool { isFullscreenLayout } + override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge { isFullscreenLayout ? .all : [] } + + var systemConfiguration: [String: Any] { + let hardwareKeyboard = GCKeyboard.coalesced != nil + return ["hardKeyboardHidden": hardwareKeyboard ? 1 : 2, "keyboardHidden": isKeyboardVisible ? 1 : 2, + "keyboardHeight": keyboardHeight, "keyboard": hardwareKeyboard ? 2 : 1, + "orientation": view.bounds.width > view.bounds.height ? 2 : 1, + "navigation": 0, "navigationHidden": 2, "touchscreen": 3, + "locale": Locale.current.identifier.replacingOccurrences(of: "_", with: "-"), + "fontScale": UIFontMetrics.default.scaledValue(for: 17) / 17] + } + + func setThemeType(_ type: String) { + themeType = type + fullscreen?.updateControls() + setNeedsStatusBarAppearanceUpdate() + var vc: UIViewController? = parent + while let current = vc { + current.setNeedsStatusBarAppearanceUpdate() + vc = current.parent + } + } + + func setSystemBarColor(_ color: UIColor) { + view.backgroundColor = color + webView.backgroundColor = color + view.window?.backgroundColor = color + } + + deinit { + NotificationCenter.default.removeObserver(self) + } +} + +extension WebViewController: WKNavigationDelegate { + func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { + bridge.reset() + } + + func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction) async -> WKNavigationActionPolicy { + guard let url = navigationAction.request.url else { return .cancel } + if url.scheme == "acode" { return .allow } + #if DEBUG + if url.scheme == "http" || url.scheme == "https" { return .allow } + #endif + return .cancel + } + + func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { + print("[WebView] didFailProvisionalNavigation: \(error)") + } + + func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { + print("[WebView] didFail: \(error)") + } + + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + print("[WebView] didFinish loading: \(webView.url?.absoluteString ?? "nil")") + } +} + +// Prevents WKUserContentController from retaining the message handler (avoids memory leak). +final class WeakScriptMessageHandler: NSObject, WKScriptMessageHandler { + private weak var delegate: WKScriptMessageHandler? + init(_ delegate: WKScriptMessageHandler) { self.delegate = delegate } + + func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) { + delegate?.userContentController(controller, didReceive: message) + } +} diff --git a/platforms/ios/runner/lib/AppFiles.swift b/platforms/ios/runner/lib/AppFiles.swift new file mode 100644 index 0000000000..201749dc02 --- /dev/null +++ b/platforms/ios/runner/lib/AppFiles.swift @@ -0,0 +1,150 @@ +import Foundation +import UniformTypeIdentifiers + +final class AppFiles { + static let shared = AppFiles() + let manager = FileManager.default + let data: URL + let cache: URL + let documents: URL + let temporary: URL + let application = Bundle.main.bundleURL + private(set) var roots: [String: URL] + private let lock = NSRecursiveLock() + private let history = FileRootHistory() + + private init() { + data = manager.urls(for: .libraryDirectory, in: .userDomainMask)[0].appendingPathComponent("NoCloud", isDirectory: true) + cache = manager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + documents = manager.urls(for: .documentDirectory, in: .userDomainMask)[0] + temporary = manager.temporaryDirectory + roots = ["files": data, "cache": cache, "persistent": documents, "temporary": temporary, "application": application] + for url in [data, cache, documents, temporary] { try? manager.createDirectory(at: url, withIntermediateDirectories: true) } + var dataDirectory = data + var values = URLResourceValues() + values.isExcludedFromBackup = true + try? dataDirectory.setResourceValues(values) + for (name, bookmark) in UserDefaults.standard.dictionary(forKey: "acode.folderBookmarks") ?? [:] { + guard let bookmark = bookmark as? Data else { continue } + var stale = false + if let url = try? URL(resolvingBookmarkData: bookmark, options: [], bookmarkDataIsStale: &stale), url.startAccessingSecurityScopedResource() { + roots[name] = url + if stale { try? remember(url, name: name) } + } + } + history.update(roots) + } + + func remember(_ url: URL, name: String = UUID().uuidString) throws { + lock.lock(); defer { lock.unlock() } + let scoped = url.startAccessingSecurityScopedResource() + var retained = false + defer { if scoped && !retained { url.stopAccessingSecurityScopedResource() } } + let canonical = url.standardizedFileURL.resolvingSymlinksInPath() + if [data, cache, documents, temporary, application].contains(where: { contains($0, canonical) }) { return } + guard scoped else { + if (try? resolve(url.absoluteString)) != nil { return } + throw FileFailure(2) + } + let existing = roots.first { $0.value.standardizedFileURL.resolvingSymlinksInPath() == canonical } + let key = existing?.key ?? name + let bookmark = try url.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil) + var bookmarks = UserDefaults.standard.dictionary(forKey: "acode.folderBookmarks") ?? [:] + bookmarks[key] = bookmark + UserDefaults.standard.set(bookmarks, forKey: "acode.folderBookmarks") + roots[key] = url + history.update(roots) + retained = true + existing?.value.stopAccessingSecurityScopedResource() + } + + func resolve(_ path: String, followingFinalSymlink: Bool = true) throws -> URL { + lock.lock(); defer { lock.unlock() } + guard let parsed = URL(string: path) else { throw FileFailure(5) } + let url: URL + if parsed.scheme == "acode", parsed.host == "localhost", parsed.path.hasPrefix("/__cdvfile_") { + let component = parsed.pathComponents[1] + let name = String(component.dropFirst("__cdvfile_".count).dropLast(2)) + guard component.hasSuffix("__"), let root = roots[name] else { throw FileFailure(1) } + let relative = parsed.pathComponents.dropFirst(2).joined(separator: "/") + url = relative.isEmpty ? root : root.appendingPathComponent(relative) + } else if parsed.scheme == "acode", parsed.host == "localhost", ["__file__", "__cache__"].contains(parsed.pathComponents[safe: 1] ?? "") { + let root = parsed.pathComponents[1] == "__file__" ? documents : cache + url = root.appendingPathComponent(parsed.pathComponents.dropFirst(2).joined(separator: "/")) + } else if parsed.isFileURL { + url = parsed + } else if path.hasPrefix("/") { + url = URL(fileURLWithPath: path) + } else { throw FileFailure(5) } + let normalized = history.resolve(url, roots: roots).standardizedFileURL + let canonical = followingFinalSymlink ? normalized.resolvingSymlinksInPath() + : normalized.deletingLastPathComponent().resolvingSymlinksInPath().appendingPathComponent(normalized.lastPathComponent) + guard roots.values.contains(where: { contains($0, canonical) }) else { throw FileFailure(2) } + return canonical + } + + func entry(_ url: URL) throws -> [String: Any] { + lock.lock(); defer { lock.unlock() } + let info = try resolve(url.absoluteString).resourceValues(forKeys: [.isDirectoryKey]) + let location = try resolve(url.absoluteString, followingFinalSymlink: false) + guard let (name, root) = roots.sorted(by: { $0.value.path.count > $1.value.path.count }).first(where: { contains($0.value, location) }) else { throw FileFailure(2) } + let relative = String(location.path.dropFirst(root.standardizedFileURL.resolvingSymlinksInPath().path.count)) + return ["name": location.lastPathComponent, "fullPath": relative.isEmpty ? "/" : relative, "nativeURL": location.absoluteString, "filesystemName": name, "isDirectory": info.isDirectory == true, "isFile": info.isDirectory != true] + } + + func metadata(_ url: URL) throws -> [String: Any] { + let values = try resolve(url.absoluteString).resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey, .isDirectoryKey]) + return ["name": url.lastPathComponent, "size": values.fileSize ?? 0, "type": mimeType(url), "lastModifiedDate": (values.contentModificationDate ?? .distantPast).timeIntervalSince1970 * 1000, "isDirectory": values.isDirectory == true, "isFile": values.isDirectory != true, "url": url.absoluteString, "canRead": manager.isReadableFile(atPath: url.path), "canWrite": manager.isWritableFile(atPath: url.path)] + } + + func coordinate<T>(_ url: URL, writing: Bool = false, _ operation: (URL) throws -> T) throws -> T { + var coordinationError: NSError? + var result: Result<T, Error>? + let accessor: (URL) -> Void = { item in result = Result { try operation(item) } } + if writing { NSFileCoordinator().coordinate(writingItemAt: url, options: [], error: &coordinationError, byAccessor: accessor) } + else { NSFileCoordinator().coordinate(readingItemAt: url, options: [], error: &coordinationError, byAccessor: accessor) } + if let error = coordinationError { throw error } + guard let result else { throw FileFailure(4) } + return try result.get() + } + + func allRoots() -> [String: URL] { + lock.lock(); defer { lock.unlock() } + return roots + } + + func pathReplacements() -> [[String: String]] { + lock.lock(); defer { lock.unlock() } + return history.replacements(roots: roots) + } + + func mimeType(_ url: URL) -> String { + switch url.pathExtension.lowercased() { + case "js", "mjs": return "application/javascript" + case "wasm": return "application/wasm" + case "css": return "text/css" + default: return UTType(filenameExtension: url.pathExtension)?.preferredMIMEType ?? "application/octet-stream" + } + } + + private func contains(_ root: URL, _ url: URL) -> Bool { + let base = root.standardizedFileURL.resolvingSymlinksInPath().path + return url.path == base || url.path.hasPrefix(base + "/") + } +} + +struct FileFailure: Error { + let code: Int + init(_ code: Int) { self.code = code } + static func code(_ error: Error) -> Int { + if let error = error as? FileFailure { return error.code } + let error = error as NSError + switch error.code { + case NSFileNoSuchFileError, NSFileReadNoSuchFileError: return 1 + case NSFileWriteFileExistsError: return 12 + case NSFileReadNoPermissionError, NSFileWriteNoPermissionError: return 2 + case NSFileWriteOutOfSpaceError: return 10 + default: return 4 + } + } +} diff --git a/platforms/ios/runner/lib/AppIconService.swift b/platforms/ios/runner/lib/AppIconService.swift new file mode 100644 index 0000000000..3ef49d9a69 --- /dev/null +++ b/platforms/ios/runner/lib/AppIconService.swift @@ -0,0 +1,20 @@ +import UIKit + +enum AppIconService { + static func set(_ name: String, callback: Callback) { + DispatchQueue.main.async { + let application = UIApplication.shared + let key = name.lowercased() + let icon = key == "default" ? nil : "ic_acode_" + key + let icons = Bundle.main.object(forInfoDictionaryKey: "CFBundleIcons") as? [String: Any] + let alternatives = icons?["CFBundleAlternateIcons"] as? [String: Any] ?? [:] + if let icon, alternatives[icon] == nil { callback.error("Unknown app icon: " + name); return } + guard application.supportsAlternateIcons else { callback.error("Alternate app icons are unavailable on this device"); return } + if application.alternateIconName == icon { callback.success(); return } + application.setAlternateIconName(icon) { error in + if let error { callback.error(error.localizedDescription) } + else { callback.success() } + } + } + } +} diff --git a/platforms/ios/runner/lib/BrowserActivity.swift b/platforms/ios/runner/lib/BrowserActivity.swift new file mode 100644 index 0000000000..c3e8feb8ae --- /dev/null +++ b/platforms/ios/runner/lib/BrowserActivity.swift @@ -0,0 +1,43 @@ +import UIKit + +final class BrowserActivity: UIActivity { + let url: URL + private let name: String + private let identifier: String + + init(name: String, identifier: String, url: URL) { + self.name = name + self.identifier = identifier + self.url = url + super.init() + } + + override class var activityCategory: UIActivity.Category { .action } + override var activityType: UIActivity.ActivityType? { UIActivity.ActivityType("app.acode.browser.\(identifier)") } + override var activityTitle: String? { "Open in \(name)" } + override var activityImage: UIImage? { UIImage(systemName: "globe") } + + override func canPerform(withActivityItems activityItems: [Any]) -> Bool { true } + + override func perform() { + UIApplication.shared.open(url) { opened in self.activityDidFinish(opened) } + } + + static func available(for url: URL, canOpen: (URL) -> Bool) -> [BrowserActivity] { + guard let scheme = url.scheme?.lowercased(), ["http", "https"].contains(scheme), url.host != nil else { return [] } + var activities = [BrowserActivity(name: "Default Browser", identifier: "default", url: url)] + var chrome = URLComponents(url: url, resolvingAgainstBaseURL: false) + chrome?.scheme = scheme == "https" ? "googlechromes" : "googlechrome" + if let target = chrome?.url, canOpen(target) { + activities.append(BrowserActivity(name: "Chrome", identifier: "chrome", url: target)) + } + var firefox = URLComponents() + firefox.scheme = "firefox" + firefox.host = "open-url" + firefox.queryItems = [URLQueryItem(name: "url", value: url.absoluteString)] + if let target = firefox.url, canOpen(target) { + activities.append(BrowserActivity(name: "Firefox", identifier: "firefox", url: target)) + } + return activities + } +} diff --git a/platforms/ios/runner/lib/DeviceService.swift b/platforms/ios/runner/lib/DeviceService.swift new file mode 100644 index 0000000000..ffc37cc1c5 --- /dev/null +++ b/platforms/ios/runner/lib/DeviceService.swift @@ -0,0 +1,44 @@ +import UIKit +import Darwin + +final class DeviceService: BaseService { + + override func exec(action: String, args: [Any], callback: Callback) { + switch action { + case "getDeviceInfo": + DispatchQueue.main.async { + #if targetEnvironment(simulator) + let virtual = true + #else + let virtual = false + #endif + let device = UIDevice.current + callback.success(["platform": "iOS", "version": device.systemVersion, "uuid": device.identifierForVendor?.uuidString ?? "unknown", "model": device.model, "manufacturer": "Apple", "isVirtual": virtual, "serial": "unknown"]) + } + case "id": deviceId(callback: callback) + default: callback.error("Unknown action: \(action)") + } + } + + private func deviceId(callback: Callback) { + let device = UIDevice.current + let screen = UIScreen.main + let scale = screen.scale + let bounds = screen.bounds + let width = Int(bounds.width * scale) + let height = Int(bounds.height * scale) + let dpi = Int(160 * scale) + let vendorId = device.identifierForVendor?.uuidString ?? "unknown" + let modelId = hardwareModel() + let id = "Apple_\(modelId)_\(width)_\(height)_\(dpi)_\(vendorId)" + callback.success(id) + } + + private func hardwareModel() -> String { + var size: Int = 0 + sysctlbyname("hw.machine", nil, &size, nil, 0) + var machine = [CChar](repeating: 0, count: size) + sysctlbyname("hw.machine", &machine, &size, nil, 0) + return String(cString: machine) + } +} diff --git a/platforms/ios/runner/lib/DialogService.swift b/platforms/ios/runner/lib/DialogService.swift new file mode 100644 index 0000000000..2b51780828 --- /dev/null +++ b/platforms/ios/runner/lib/DialogService.swift @@ -0,0 +1,91 @@ +import UIKit + +final class DialogService: BaseService { + + override func exec(action: String, args: [Any], callback: Callback) { + switch action { + case "alert": alert(args: args, callback: callback) + case "confirm": confirm(args: args, callback: callback) + case "prompt": prompt(args: args, callback: callback) + default: callback.error("Unknown action: \(action)") + } + } + + // MARK: - alert + + private func alert(args: [Any], callback: Callback) { + let message = args[safe: 0] as? String ?? "" + let title = args[safe: 1] as? String ?? "" + + DispatchQueue.main.async { [weak self] in + guard let vc = self?.viewController else { + callback.error("No view controller"); return + } + let alert = UIAlertController( + title: title.isEmpty ? nil : title, + message: message, + preferredStyle: .alert + ) + alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in + callback.success() + }) + vc.present(alert, animated: true) + } + } + + // MARK: - confirm + + private func confirm(args: [Any], callback: Callback) { + let message = args[safe: 0] as? String ?? "" + let title = args[safe: 1] as? String ?? "" + + DispatchQueue.main.async { [weak self] in + guard let vc = self?.viewController else { + callback.error("No view controller"); return + } + let alert = UIAlertController( + title: title.isEmpty ? nil : title, + message: message, + preferredStyle: .alert + ) + alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in + callback.success(true) + }) + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in + callback.success(false) + }) + vc.present(alert, animated: true) + } + } + + // MARK: - prompt + + private func prompt(args: [Any], callback: Callback) { + let message = args[safe: 0] as? String ?? "" + let defaultValue = args[safe: 1] as? String ?? "" + let title = args[safe: 2] as? String ?? "" + + DispatchQueue.main.async { [weak self] in + guard let vc = self?.viewController else { + callback.error("No view controller"); return + } + let alert = UIAlertController( + title: title.isEmpty ? nil : title, + message: message, + preferredStyle: .alert + ) + alert.addTextField { textField in + textField.text = defaultValue + textField.autocorrectionType = .no + } + alert.addAction(UIAlertAction(title: "OK", style: .default) { [weak alert] _ in + let text = alert?.textFields?.first?.text ?? "" + callback.success(text) + }) + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in + callback.success(nil as String?) + }) + vc.present(alert, animated: true) + } + } +} diff --git a/platforms/ios/runner/lib/DocumentsService.swift b/platforms/ios/runner/lib/DocumentsService.swift new file mode 100644 index 0000000000..dd2513e325 --- /dev/null +++ b/platforms/ios/runner/lib/DocumentsService.swift @@ -0,0 +1,145 @@ +import UIKit +import UniformTypeIdentifiers + +final class DocumentsService: BaseService, UIDocumentPickerDelegate { + private let files = AppFiles.shared + private let workspace = WorkspaceIndex() + private var pickerCallback: Callback? + private var pickerReturnsURI = false + private weak var picker: UIDocumentPickerViewController? + private var watches: [String: FileWatch] = [:] + + override func reset() { + workspace.reset() + watches.values.forEach { $0.stop() } + watches.removeAll() + DispatchQueue.main.async { [weak self] in + guard let self else { return } + self.pickerCallback?.error("Operation cancelled") + self.pickerCallback = nil + self.picker?.delegate = nil + self.picker?.dismiss(animated: false) + self.picker = nil + } + } + + override func exec(action: String, args: [Any], callback: Callback) { + if action.hasPrefix("workspace ") { workspace.exec(action, args: args, callback: callback); return } + do { + switch action { + case "watch file": + let url = try files.resolve(args[safe: 0] as? String ?? "") + let id = args[safe: 1] as? String ?? "" + guard files.manager.fileExists(atPath: url.path), !id.isEmpty else { throw FileFailure(1) } + watches.removeValue(forKey: id)?.stop() + watches[id] = FileWatch(url: url, callback: callback) + case "unwatch file": + watches.removeValue(forKey: args[safe: 0] as? String ?? "")?.stop() + callback.success() + case "list volumes": + callback.success([["name": "Acode", "uuid": "ios-documents", "path": files.documents.path]]) + case "storage permission": + if args[safe: 0] as? String == "ios-documents" { callback.success("file://" + files.documents.path) } + else { pick(type: .folder, uriOnly: true, callback: callback) } + case "open document file", "get image": + let type = (args[safe: 0] as? String).flatMap { UTType(mimeType: $0) } ?? (action == "get image" ? .image : .item) + pick(type: type, uriOnly: action == "get image", callback: callback) + case "list encodings": callback.success(FileContents.availableEncodings()) + default: try operate(action, args: args, callback: callback) + } + } catch { callback.error(["code": FileFailure.code(error), "message": error.localizedDescription]) } + } + + private func operate(_ action: String, args: [Any], callback: Callback) throws { + let url = try files.resolve(args[safe: 0] as? String ?? "") + switch action { + case "stats": callback.success(try stats(url)) + case "exists": callback.success(files.manager.fileExists(atPath: url.path) ? "TRUE" : "FALSE") + case "format uri": callback.success(url.absoluteString) + case "get path": callback.success(try files.resolve(url.appendingPathComponent(args[safe: 1] as? String ?? "").absoluteString).path) + case "list directory": + callback.success(try files.coordinate(url) { try files.manager.contentsOfDirectory(at: $0, includingPropertiesForKeys: [.isDirectoryKey]).map { try stats($0) } }) + case "read": callback.successBinary(try files.coordinate(url) { try Data(contentsOf: $0) }) + case "readAsText": + callback.success(try files.coordinate(url) { try String(contentsOf: $0, encoding: FileContents.encoding(args[safe: 1] as? String ?? "UTF-8")) }) + case "write", "writeText": + let data: Data + if action == "write", args[safe: 2] as? Bool == true { + guard let bytes = Data(base64Encoded: args[safe: 1] as? String ?? "") else { throw FileFailure(5) } + data = bytes + } else { + let encoding = try FileContents.encoding(action == "writeText" ? args[safe: 2] as? String ?? "UTF-8" : "UTF-8") + guard let bytes = (args[safe: 1] as? String ?? "").data(using: encoding) else { throw FileFailure(5) } + data = bytes + } + try files.coordinate(url, writing: true) { try data.write(to: $0, options: .atomic) } + callback.success("OK") + case "create file", "create directory": + let target = try files.resolve(url.appendingPathComponent(args[safe: 1] as? String ?? "").absoluteString) + if files.manager.fileExists(atPath: target.path) { throw FileFailure(12) } + if action == "create directory" { try files.manager.createDirectory(at: target, withIntermediateDirectories: false) } + else { try Data().write(to: target, options: .withoutOverwriting) } + callback.success(target.absoluteString) + case "delete": try files.coordinate(url, writing: true) { try files.manager.removeItem(at: $0) }; callback.success("OK") + case "rename", "move", "copy": + let path = args[safe: 1] as? String ?? "" + let target = try files.resolve(action == "rename" ? url.deletingLastPathComponent().appendingPathComponent(path).absoluteString : path) + try files.coordinate(target, writing: true) { target in + if action == "copy" { try files.manager.copyItem(at: url, to: target) } + else { try files.manager.moveItem(at: url, to: target) } + } + callback.success(target.absoluteString) + default: callback.error("Unsupported Files action: \(action)") + } + } + + private func stats(_ url: URL) throws -> [String: Any] { + var result = try files.metadata(url) + result["uri"] = "file://" + url.path + result["filename"] = url.lastPathComponent + result["length"] = result["size"] + result["lastModified"] = result["lastModifiedDate"] + result["mime"] = result["type"] + result["exists"] = true + result["isVirtual"] = false + result["persistedUriPermission"] = true + return result + } + + private func pick(type: UTType, uriOnly: Bool, callback: Callback) { + DispatchQueue.main.async { [weak self] in + guard let self, let presenter = self.viewController else { callback.error("View unavailable"); return } + guard self.pickerCallback == nil else { callback.error("A document picker is already open"); return } + guard presenter.presentedViewController == nil, presenter.viewIfLoaded?.window != nil else { + callback.error("A document picker cannot be presented right now"); return + } + self.pickerCallback = callback + self.pickerReturnsURI = uriOnly + let picker = UIDocumentPickerViewController(forOpeningContentTypes: [type], asCopy: false) + picker.delegate = self + self.picker = picker + presenter.present(picker, animated: true) + } + } + + func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { + guard controller === picker else { return } + let callback = pickerCallback + pickerCallback = nil + picker = nil + guard let url = urls.first else { callback?.error("No file selected"); return } + do { + try files.remember(url) + callback?.success(pickerReturnsURI ? "file://" + url.path : try stats(url)) + } catch { + callback?.error(["code": FileFailure.code(error), "message": error.localizedDescription]) + } + } + + func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { + guard controller === picker else { return } + pickerCallback?.error("Operation cancelled") + pickerCallback = nil + picker = nil + } +} diff --git a/platforms/ios/runner/lib/EncryptionService.swift b/platforms/ios/runner/lib/EncryptionService.swift new file mode 100644 index 0000000000..06c3aed2c6 --- /dev/null +++ b/platforms/ios/runner/lib/EncryptionService.swift @@ -0,0 +1,41 @@ +import Foundation + +final class EncryptionService: BaseService { + + override func exec(action: String, args: [Any], callback: Callback) { + switch action { + case "encrypt": encrypt(args: args, callback: callback) + case "decrypt": decrypt(args: args, callback: callback) + default: callback.error("Unknown action: \(action)") + } + } + + // XOR cipher then Base64 — matches Android Encryption.java exactly. + + private func encrypt(args: [Any], callback: Callback) { + guard let message = args[safe: 0] as? String, + let password = args[safe: 1] as? String else { + callback.error("message and password required"); return + } + let msgBytes = Array(message.utf8) + let passBytes = Array(password.utf8) + guard !passBytes.isEmpty else { callback.error("password must not be empty"); return } + let xored = msgBytes.enumerated().map { i, b in b ^ passBytes[i % passBytes.count] } + callback.success(Data(xored).base64EncodedString()) + } + + private func decrypt(args: [Any], callback: Callback) { + guard let encoded = args[safe: 0] as? String, + let password = args[safe: 1] as? String, + let data = Data(base64Encoded: encoded) else { + callback.error("encoded string and password required"); return + } + let passBytes = Array(password.utf8) + guard !passBytes.isEmpty else { callback.error("password must not be empty"); return } + let xored = data.enumerated().map { i, b in b ^ passBytes[i % passBytes.count] } + guard let result = String(bytes: xored, encoding: .utf8) else { + callback.error("Decryption produced invalid UTF-8"); return + } + callback.success(result) + } +} diff --git a/platforms/ios/runner/lib/FileContents.swift b/platforms/ios/runner/lib/FileContents.swift new file mode 100644 index 0000000000..56a1d1f063 --- /dev/null +++ b/platforms/ios/runner/lib/FileContents.swift @@ -0,0 +1,69 @@ +import Foundation +import CoreFoundation + +struct FileContents { + static func encoding(_ name: String) throws -> String.Encoding { + let value = CFStringConvertIANACharSetNameToEncoding(name as CFString) + guard value != kCFStringEncodingInvalidId else { throw FileFailure(5) } + return String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(value)) + } + + static func availableEncodings() -> [String: Any] { + var result: [String: Any] = [:] + for value in String.availableStringEncodings { + let code = CFStringConvertNSStringEncodingToEncoding(value.rawValue) + guard let label = CFStringConvertEncodingToIANACharSetName(code) as String? else { continue } + let name = label.uppercased() + result[name] = ["name": name, "label": name, "aliases": [label]] + } + return result + } + + static func perform(_ action: String, url: URL, args: [Any], callback: Callback) throws { + let writing = action == "write" || action == "truncate" + try AppFiles.shared.coordinate(url, writing: writing) { url in + if action == "write" { + let data: Data + if args[safe: 3] as? Bool == true { + guard let value = args[safe: 1] as? String, let bytes = Data(base64Encoded: value) else { throw FileFailure(5) } + data = bytes + } else { data = Data((args[safe: 1] as? String ?? "").utf8) } + let handle = try FileHandle(forWritingTo: url) + defer { try? handle.close() } + let requested = max(0, args[safe: 2] as? Int ?? 0) + let offset = min(UInt64(requested), try handle.seekToEnd()) + try handle.seek(toOffset: offset) + try handle.write(contentsOf: data) + try handle.truncate(atOffset: offset + UInt64(data.count)) + callback.success(data.count) + } else if action == "truncate" { + let handle = try FileHandle(forWritingTo: url) + defer { try? handle.close() } + // Android reports UNKNOWN_ERR for negative truncate lengths. + guard let requested = args[safe: 1] as? Int, requested >= 0 else { throw FileFailure(1000) } + let size = try handle.seekToEnd() + let length = min(UInt64(requested), size) + try handle.truncate(atOffset: length) + callback.success(length) + } else { + let handle = try FileHandle(forReadingFrom: url) + defer { try? handle.close() } + let index = action == "readAsText" ? 2 : 1 + let size = Int(try handle.seekToEnd()) + let start = min(size, max(0, args[safe: index] as? Int ?? 0)) + let requestedEnd = args[safe: index + 1] as? Int ?? -1 + let end = requestedEnd < 0 ? size : min(size, requestedEnd) + try handle.seek(toOffset: UInt64(start)) + let bytes = try handle.read(upToCount: max(0, end - start)) ?? Data() + switch action { + case "readAsArrayBuffer": callback.successBinary(bytes) + case "readAsBinaryString": callback.success(String(bytes: bytes, encoding: .isoLatin1) ?? "") + case "readAsDataURL": callback.success("data:\(AppFiles.shared.mimeType(url));base64,\(bytes.base64EncodedString())") + default: + guard let value = String(data: bytes, encoding: try encoding(args[safe: 1] as? String ?? "UTF-8")) else { throw FileFailure(5) } + callback.success(value) + } + } + } + } +} diff --git a/platforms/ios/runner/lib/FileHandlerService.swift b/platforms/ios/runner/lib/FileHandlerService.swift new file mode 100644 index 0000000000..cca6ce25a1 --- /dev/null +++ b/platforms/ios/runner/lib/FileHandlerService.swift @@ -0,0 +1,347 @@ +import Foundation +import UIKit + +final class FileHandlerService: BaseService { + + private let homeURL = URL(fileURLWithPath: NSHomeDirectory()) + private let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + private let cachesURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] + + /// Mirrors Android's `resolvePath`: prepends the app's Documents directory to paths + /// that start with "/" but are not already absolute sandbox paths. + private func resolvePath(_ path: String) -> String { + let home = homeURL.path + let docs = documentsURL.path + if path.hasPrefix(home) { return path } + return path.hasPrefix("/") ? docs + path : docs + "/" + path + } + + override func exec(action: String, args: [Any], callback: Callback) { + switch action { + case "read": read(args: args, callback: callback) + case "write": write(args: args, callback: callback) + case "delete": delete(args: args, callback: callback) + case "move": move(args: args, callback: callback) + case "copy": copy(args: args, callback: callback) + case "list": list(args: args, callback: callback) + case "exists": exists(args: args, callback: callback) + case "isDirectory": isDirectory(args: args, callback: callback) + case "isFile": isFile(args: args, callback: callback) + case "createDirectory": createDirectory(args: args, callback: callback) + case "createFile": createFile(args: args, callback: callback) + case "getMetadata": getMetadata(args: args, callback: callback) + case "resolve": resolve(args: args, callback: callback) + case "toUrl": toUrl(args: args, callback: callback) + case "saveToDevice": saveToDevice(args: args, callback: callback) + case "download": download(args: args, callback: callback) + case "reveal": callback.error("reveal is not supported on iOS") + case "print": printFile(args: args, callback: callback) + default: callback.error("Unknown action: \(action)") + } + } + + // MARK: - read + + private func read(args: [Any], callback: Callback) { + guard let rawPath = args[safe: 0] as? String else { callback.error("path required"); return } + let path = resolvePath(rawPath) + do { + let data = try Data(contentsOf: URL(fileURLWithPath: path)) + callback.success(data.base64EncodedString()) + } catch { + callback.error(error.localizedDescription) + } + } + + // MARK: - write + + private func write(args: [Any], callback: Callback) { + guard let rawPath = args[safe: 0] as? String, + let content = args[safe: 1] as? String else { callback.error("path and content required"); return } + let path = resolvePath(rawPath) + let isBase64 = (args[safe: 2] as? Bool) == true || (args[safe: 2] as? Int) == 1 + let url = URL(fileURLWithPath: path) + do { + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + if isBase64, let data = Data(base64Encoded: content) { + try data.write(to: url) + } else { + try content.write(to: url, atomically: true, encoding: .utf8) + } + callback.success() + } catch { + callback.error(error.localizedDescription) + } + } + + // MARK: - delete + + private func delete(args: [Any], callback: Callback) { + guard let rawPath = args[safe: 0] as? String else { callback.error("path required"); return } + let path = resolvePath(rawPath) + do { + try FileManager.default.removeItem(atPath: path) + callback.success() + } catch { + callback.error(error.localizedDescription) + } + } + + // MARK: - move / copy + + private func move(args: [Any], callback: Callback) { + guard let rawFrom = args[safe: 0] as? String, + let rawTo = args[safe: 1] as? String else { callback.error("from and to required"); return } + let from = resolvePath(rawFrom) + let to = resolvePath(rawTo) + do { + let dest = URL(fileURLWithPath: to) + try FileManager.default.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.moveItem(atPath: from, toPath: to) + callback.success() + } catch { + callback.error(error.localizedDescription) + } + } + + private func copy(args: [Any], callback: Callback) { + guard let rawFrom = args[safe: 0] as? String, + let rawTo = args[safe: 1] as? String else { callback.error("from and to required"); return } + let from = resolvePath(rawFrom) + let to = resolvePath(rawTo) + do { + let dest = URL(fileURLWithPath: to) + try FileManager.default.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.copyItem(atPath: from, toPath: to) + callback.success() + } catch { + callback.error(error.localizedDescription) + } + } + + // MARK: - list + + private func list(args: [Any], callback: Callback) { + guard let rawPath = args[safe: 0] as? String else { callback.error("path required"); return } + let path = resolvePath(rawPath) + do { + let entries = try FileManager.default.contentsOfDirectory(atPath: path) + callback.success(entries) + } catch { + callback.error(error.localizedDescription) + } + } + + // MARK: - exists / isDirectory / isFile + + private func exists(args: [Any], callback: Callback) { + guard let rawPath = args[safe: 0] as? String else { callback.error("path required"); return } + callback.success(FileManager.default.fileExists(atPath: resolvePath(rawPath)) ? 1 : 0) + } + + private func isDirectory(args: [Any], callback: Callback) { + guard let rawPath = args[safe: 0] as? String else { callback.error("path required"); return } + var isDir: ObjCBool = false + let exists = FileManager.default.fileExists(atPath: resolvePath(rawPath), isDirectory: &isDir) + callback.success(exists && isDir.boolValue ? 1 : 0) + } + + private func isFile(args: [Any], callback: Callback) { + guard let rawPath = args[safe: 0] as? String else { callback.error("path required"); return } + var isDir: ObjCBool = false + let exists = FileManager.default.fileExists(atPath: resolvePath(rawPath), isDirectory: &isDir) + callback.success(exists && !isDir.boolValue ? 1 : 0) + } + + // MARK: - createDirectory / createFile + + private func createDirectory(args: [Any], callback: Callback) { + guard let rawPath = args[safe: 0] as? String else { callback.error("path required"); return } + let resolved = resolvePath(rawPath) + do { + try FileManager.default.createDirectory(atPath: resolved, withIntermediateDirectories: true) + callback.success() + } catch { + callback.error(error.localizedDescription) + } + } + + private func createFile(args: [Any], callback: Callback) { + guard let rawPath = args[safe: 0] as? String else { callback.error("path required"); return } + let url = URL(fileURLWithPath: resolvePath(rawPath)) + do { + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + FileManager.default.createFile(atPath: url.path, contents: nil) + callback.success() + } catch { + callback.error(error.localizedDescription) + } + } + + // MARK: - getMetadata + + private func getMetadata(args: [Any], callback: Callback) { + guard let rawPath = args[safe: 0] as? String else { callback.error("path required"); return } + let path = resolvePath(rawPath) + do { + let attrs = try FileManager.default.attributesOfItem(atPath: path) + var isDir: ObjCBool = false + FileManager.default.fileExists(atPath: path, isDirectory: &isDir) + let result: [String: Any] = [ + "name": URL(fileURLWithPath: path).lastPathComponent, + "path": path, + "size": (attrs[.size] as? Int) ?? 0, + "lastModified": Int((attrs[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0) * 1000, + "isDirectory": isDir.boolValue, + ] + callback.success(result) + } catch { + callback.error(error.localizedDescription) + } + } + + // MARK: - resolve + + private func resolve(args: [Any], callback: Callback) { + guard let path = args[safe: 0] as? String else { callback.error("path required"); return } + callback.success(resolvePath(path)) + } + + // MARK: - toUrl + + private func toUrl(args: [Any], callback: Callback) { + guard let rawPath = args[safe: 0] as? String else { callback.error("path required"); return } + let path = resolvePath(rawPath) + let homePath = homeURL.path + let docsPath = documentsURL.path + let cachesPath = cachesURL.path + if path.hasPrefix(docsPath) { + let rel = String(path.dropFirst(docsPath.count)).trimmingCharacters(in: CharacterSet(charactersIn: "/")) + callback.success("acode://localhost/__file__/\(rel)") + } else if path.hasPrefix(cachesPath) { + let rel = String(path.dropFirst(cachesPath.count)).trimmingCharacters(in: CharacterSet(charactersIn: "/")) + callback.success("acode://localhost/__cache__/\(rel)") + } else if path.hasPrefix(homePath) { + // Any other sandbox path — serve via __file__ relative to home + let rel = String(path.dropFirst(homePath.count)).trimmingCharacters(in: CharacterSet(charactersIn: "/")) + callback.success("acode://localhost/__file__/\(rel)") + } else { + callback.error("Path must be within the app sandbox") + } + } + + // MARK: - saveToDevice + + private func saveToDevice(args: [Any], callback: Callback) { + guard let rawPath = args[safe: 0] as? String else { callback.error("path required"); return } + let resolvedPath = resolvePath(rawPath) + DispatchQueue.main.async { [weak self] in + guard let vc = self?.viewController else { return } + let url = URL(fileURLWithPath: resolvedPath) + let picker = UIDocumentPickerViewController(forExporting: [url], asCopy: true) + picker.delegate = SaveToDeviceDelegate.shared + SaveToDeviceDelegate.shared.pendingCallback = callback + vc.present(picker, animated: true) + } + } + + // MARK: - download + + private func download(args: [Any], callback: Callback) { + guard let urlString = args[safe: 0] as? String, + let rawDest = args[safe: 1] as? String, + let url = URL(string: urlString) else { + callback.error("url and path required"); return + } + let destPath = resolvePath(rawDest) + let openAfter = (args[safe: 2] as? Bool) == true || (args[safe: 2] as? Int) == 1 + let delegate = DownloadDelegate(destPath: destPath, openAfter: openAfter, callback: callback) + delegate.start(url: url) + // Hold reference until done via the delegate's own retention + } + + // MARK: - print + + private func printFile(args: [Any], callback: Callback) { + guard let rawPath = args[safe: 0] as? String else { callback.error("path required"); return } + let path = resolvePath(rawPath) + DispatchQueue.main.async { [weak self] in + guard let vc = self?.viewController else { return } + let controller = UIPrintInteractionController.shared + let info = UIPrintInfo.printInfo() + info.outputType = .general + controller.printInfo = info + controller.printingItem = URL(fileURLWithPath: path) + controller.present(from: vc.view.frame, in: vc.view, animated: true) { _, completed, error in + if let error = error { callback.error(error.localizedDescription) } + else { callback.success(completed ? 1 : 0) } + } + } + } +} + +// MARK: - Download helper + +private final class DownloadDelegate: NSObject, URLSessionDownloadDelegate { + private let destPath: String + private let openAfter: Bool + private let callback: Callback + private var session: URLSession? + + init(destPath: String, openAfter: Bool, callback: Callback) { + self.destPath = destPath + self.openAfter = openAfter + self.callback = callback + } + + func start(url: URL) { + let config = URLSessionConfiguration.default + session = URLSession(configuration: config, delegate: self, delegateQueue: nil) + session?.downloadTask(with: url).resume() + } + + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + guard totalBytesExpectedToWrite > 0 else { return } + let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) + callback.success(["progress": progress], keep: true) + } + + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + let dest = URL(fileURLWithPath: destPath) + do { + try FileManager.default.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true) + if FileManager.default.fileExists(atPath: dest.path) { + try FileManager.default.removeItem(at: dest) + } + try FileManager.default.moveItem(at: location, to: dest) + callback.success(destPath, keep: false) + } catch { + callback.error(error.localizedDescription) + } + self.session = nil + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + if let error = error { + callback.error(error.localizedDescription) + self.session = nil + } + } +} + +// MARK: - saveToDevice delegate + +private final class SaveToDeviceDelegate: NSObject, UIDocumentPickerDelegate { + static let shared = SaveToDeviceDelegate() + var pendingCallback: Callback? + + func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { + pendingCallback?.success(urls.first?.path) + pendingCallback = nil + } + + func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { + pendingCallback?.error("Cancelled") + pendingCallback = nil + } +} diff --git a/platforms/ios/runner/lib/FileRootHistory.swift b/platforms/ios/runner/lib/FileRootHistory.swift new file mode 100644 index 0000000000..73fd30e2e8 --- /dev/null +++ b/platforms/ios/runner/lib/FileRootHistory.swift @@ -0,0 +1,53 @@ +import Foundation + +final class FileRootHistory { + private let defaults: UserDefaults + private let key = "acode.fileRootHistory" + private var paths: [String: String] + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + paths = defaults.dictionary(forKey: key) as? [String: String] ?? [:] + } + + func update(_ roots: [String: URL]) { + var changed = false + for (name, root) in roots { + for path in [root.standardizedFileURL.path, root.standardizedFileURL.resolvingSymlinksInPath().path] { + if paths[path] != name { paths[path] = name; changed = true } + } + } + if changed { defaults.set(paths, forKey: key) } + } + + func resolve(_ url: URL, roots: [String: URL]) -> URL { + let normalized = url.standardizedFileURL + let path = normalized.path + if roots.values.contains(where: { contains($0.standardizedFileURL.path, path) }) { return normalized } + for (previous, name) in paths.sorted(by: { $0.key.count > $1.key.count }) { + guard let root = roots[name], contains(previous, path) else { continue } + let relative = String(path.dropFirst(previous.count)).trimmingCharacters(in: CharacterSet(charactersIn: "/")) + return relative.isEmpty ? root : root.appendingPathComponent(relative) + } + return normalized + } + + func replacements(roots: [String: URL]) -> [[String: String]] { + var replacements: [String: String] = [:] + for (previous, name) in paths { + guard let root = roots[name] else { continue } + if roots.values.contains(where: { contains($0.standardizedFileURL.path, previous) }) { continue } + let current = root.standardizedFileURL + let old = URL(fileURLWithPath: previous, isDirectory: false) + if previous != current.path { + replacements[old.absoluteString] = URL(fileURLWithPath: current.path, isDirectory: false).absoluteString + replacements["file://" + previous] = "file://" + current.path + } + } + return replacements.sorted(by: { $0.key.count > $1.key.count }).map { ["from": $0.key, "to": $0.value] } + } + + private func contains(_ root: String, _ path: String) -> Bool { + path == root || path.hasPrefix(root + "/") + } +} diff --git a/platforms/ios/runner/lib/FileService.swift b/platforms/ios/runner/lib/FileService.swift new file mode 100644 index 0000000000..6dffc91ed9 --- /dev/null +++ b/platforms/ios/runner/lib/FileService.swift @@ -0,0 +1,121 @@ +import Foundation + +final class FileService: BaseService { + private let files = AppFiles.shared + + override func exec(action: String, args: [Any], callback: Callback) { + do { + if action == "requestAllPaths" { callback.success(paths()); return } + if action == "getPathReplacements" { callback.success(files.pathReplacements()); return } + if action == "requestAllFileSystems" { + callback.success(try files.allRoots().values.map { try files.entry($0) }); return + } + if action == "requestFileSystem" { + let type = args[safe: 0] as? Int ?? -1 + guard type == 0 || type == 1 else { throw FileFailure(8) } + let name = type == 0 ? "temporary" : "persistent" + let root = files.allRoots()[name]! + let required = args[safe: 1] as? Int ?? 0 + if required > 0 { + let attributes = try files.manager.attributesOfFileSystem(forPath: root.path) + let available = (attributes[.systemFreeSize] as? NSNumber)?.intValue ?? 0 + guard required <= available else { throw FileFailure(10) } + } + callback.success(["name": name, "root": try files.entry(root)]); return + } + guard let path = args[safe: 0] as? String else { throw FileFailure(8) } + let preserveLink = ["resolveLocalFileSystemURI", "getFileMetadata", "getParent", "remove", "removeRecursively", "moveTo"].contains(action) + let url = try files.resolve(path, followingFinalSymlink: !preserveLink) + switch action { + case "resolveLocalFileSystemURI": callback.success(try files.entry(url)) + case "getFileMetadata": callback.success(try files.coordinate(url) { try files.metadata($0) }) + case "getParent": + let root = files.allRoots().values.contains { $0.standardizedFileURL.resolvingSymlinksInPath().path == url.path } + let parent = root ? url : url.deletingLastPathComponent() + callback.success(try files.entry(files.resolve(parent.absoluteString))) + case "readEntries": + callback.success(try files.coordinate(url) { directory in + try files.manager.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.isDirectoryKey]).map { try files.entry($0) } + }) + case "getFile", "getDirectory": + callback.success(try child(url, args: args, directory: action == "getDirectory")) + case "remove", "removeRecursively": + try files.coordinate(url, writing: true) { item in + if action == "remove", (try item.resourceValues(forKeys: [.isDirectoryKey])).isDirectory == true, + !(try files.manager.contentsOfDirectory(atPath: item.path)).isEmpty { throw FileFailure(9) } + if files.allRoots().values.contains(where: { $0.standardizedFileURL == item.standardizedFileURL }) { throw FileFailure(6) } + try files.manager.removeItem(at: item) + } + callback.success() + case "moveTo", "copyTo": + guard let parent = args[safe: 1] as? String else { throw FileFailure(8) } + let name = args[safe: 2] as? String ?? url.lastPathComponent + guard !name.contains(":") else { throw FileFailure(5) } + let destination = try files.resolve(parent).appendingPathComponent(name) + let target = try files.resolve(destination.absoluteString, followingFinalSymlink: false) + if (try? files.manager.attributesOfItem(atPath: target.path)[.type]) as? FileAttributeType == .typeSymbolicLink { throw FileFailure(12) } + try FileTransfer.perform(url, to: target, moving: action == "moveTo") + callback.success(try files.entry(target)) + case "setMetadata": + var item = url + var values = URLResourceValues() + if let excluded = (args[safe: 1] as? [String: Any])?["com.apple.MobileBackup"] as? NSNumber { values.isExcludedFromBackup = excluded.boolValue } + try item.setResourceValues(values) + callback.success() + case "write", "truncate", "readAsText", "readAsArrayBuffer", "readAsBinaryString", "readAsDataURL": + try FileContents.perform(action, url: url, args: args, callback: callback) + default: callback.error("Unsupported File action: \(action)") + } + } catch { callback.error(FileFailure.code(error)) } + } + + private func child(_ parent: URL, args: [Any], directory: Bool) throws -> [String: Any] { + guard let name = args[safe: 1] as? String else { throw FileFailure(8) } + guard !name.contains(":") else { throw FileFailure(5) } + let options = args[safe: 2] as? [String: Bool] ?? [:] + let entry = try files.entry(parent) + guard let filesystem = entry["filesystemName"] as? String, + let root = files.allRoots()[filesystem], + let parentPath = entry["fullPath"] as? String else { throw FileFailure(2) } + let requested = name.hasPrefix("/") ? name : parentPath + "/" + name + var components: [Substring] = [] + for component in requested.split(separator: "/") { + if component == ".." { if !components.isEmpty { components.removeLast() } } + else if component != "." { components.append(component) } + } + let path = root.appendingPathComponent(components.joined(separator: "/")) + let url = try files.resolve(path.absoluteString) + return try files.coordinate(url, writing: options["create"] == true) { url in + var isDirectory: ObjCBool = false + let exists = files.manager.fileExists(atPath: url.path, isDirectory: &isDirectory) + if exists { + if options["create"] == true, options["exclusive"] == true { throw FileFailure(12) } + if isDirectory.boolValue != directory { throw FileFailure(11) } + } else { + guard options["create"] == true else { throw FileFailure(1) } + if directory { try files.manager.createDirectory(at: url, withIntermediateDirectories: false) } + else if !files.manager.createFile(atPath: url.path, contents: Data()) { throw FileFailure(6) } + } + return try files.entry(path) + } + } + + private func paths() -> [String: Any] { + ["applicationDirectory": directoryURL(files.application), + "applicationStorageDirectory": directoryURL(URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)), + "dataDirectory": directoryURL(files.data), + "cacheDirectory": directoryURL(files.cache), + "tempDirectory": directoryURL(files.temporary), + "documentsDirectory": directoryURL(files.documents), + "syncedDataDirectory": NSNull(), "sharedDirectory": NSNull(), + "externalApplicationStorageDirectory": NSNull(), "externalDataDirectory": NSNull(), + "externalCacheDirectory": NSNull(), "externalRootDirectory": NSNull()] + } + + // FileManager directory URLs already end in "/"; entries resolve to single-slash URLs, so the + // roots must too or JS prefix checks against them never match. + private func directoryURL(_ url: URL) -> String { + let string = url.absoluteString + return string.hasSuffix("/") ? string : string + "/" + } +} diff --git a/platforms/ios/runner/lib/FileTransfer.swift b/platforms/ios/runner/lib/FileTransfer.swift new file mode 100644 index 0000000000..0a3f75cd0d --- /dev/null +++ b/platforms/ios/runner/lib/FileTransfer.swift @@ -0,0 +1,55 @@ +import Foundation + +struct FileTransfer { + private static let files = AppFiles.shared + + static func perform(_ source: URL, to destination: URL, moving: Bool = false) throws { + var coordinationError: NSError? + var result: Result<Void, Error>? + let coordinator = NSFileCoordinator() + let accessor: (URL, URL) -> Void = { input, output in + result = Result { + try transfer(input, to: output, moving: moving) + if moving { coordinator.item(at: input, didMoveTo: output) } + } + } + if moving { + coordinator.coordinate(writingItemAt: source, options: .forMoving, writingItemAt: destination, options: .forReplacing, error: &coordinationError, byAccessor: accessor) + } else { + coordinator.coordinate(readingItemAt: source, options: [], writingItemAt: destination, options: .forReplacing, error: &coordinationError, byAccessor: accessor) + } + if let error = coordinationError { throw error } + guard let result else { throw FileFailure(4) } + try result.get() + } + + private static func transfer(_ source: URL, to destination: URL, moving: Bool) throws { + let sourceInfo = try files.manager.attributesOfItem(atPath: source.path) + let directory = sourceInfo[.type] as? FileAttributeType == .typeDirectory + guard source.path != destination.path, + !directory || !destination.path.hasPrefix(source.path + "/") else { throw FileFailure(9) } + let roots = files.allRoots().values.map { $0.standardizedFileURL.resolvingSymlinksInPath().path } + guard !roots.contains(destination.path), !moving || !roots.contains(source.path) else { throw FileFailure(6) } + let existing: [FileAttributeKey: Any]? + do { existing = try files.manager.attributesOfItem(atPath: destination.path) } + catch { + guard FileFailure.code(error) == 1 else { throw error } + existing = nil + } + if let existing { + let targetDirectory = existing[.type] as? FileAttributeType == .typeDirectory + guard directory == targetDirectory else { throw FileFailure(9) } + if targetDirectory, !(try files.manager.contentsOfDirectory(atPath: destination.path)).isEmpty { throw FileFailure(9) } + } + if moving, existing == nil { + try files.manager.moveItem(at: source, to: destination) + return + } + let temporary = destination.deletingLastPathComponent().appendingPathComponent(".acode-copy-" + UUID().uuidString) + defer { try? files.manager.removeItem(at: temporary) } + try files.manager.copyItem(at: source, to: temporary) + if existing != nil { _ = try files.manager.replaceItemAt(destination, withItemAt: temporary) } + else { try files.manager.moveItem(at: temporary, to: destination) } + if moving { try files.manager.removeItem(at: source) } + } +} diff --git a/platforms/ios/runner/lib/FileWatch.swift b/platforms/ios/runner/lib/FileWatch.swift new file mode 100644 index 0000000000..4555dd86b1 --- /dev/null +++ b/platforms/ios/runner/lib/FileWatch.swift @@ -0,0 +1,35 @@ +import Foundation + +final class FileWatch: NSObject, NSFilePresenter { + let presentedItemURL: URL? + let presentedItemOperationQueue: OperationQueue + private let callback: Callback + + init(url: URL, callback: Callback) { + presentedItemURL = url + self.callback = callback + presentedItemOperationQueue = OperationQueue() + presentedItemOperationQueue.maxConcurrentOperationCount = 1 + super.init() + NSFileCoordinator.addFilePresenter(self) + } + + func stop() { + NSFileCoordinator.removeFilePresenter(self) + callback.release() + } + + func presentedItemDidChange() { callback.success(keep: true) } + func presentedItemDidMove(to newURL: URL) { callback.success(keep: true) } + func presentedSubitemDidAppear(at url: URL) { callback.success(keep: true) } + func presentedSubitemDidChange(at url: URL) { callback.success(keep: true) } + func presentedSubitem(at oldURL: URL, didMoveTo newURL: URL) { callback.success(keep: true) } + func accommodatePresentedItemDeletion(completionHandler: @escaping (Error?) -> Void) { + callback.success(keep: true) + completionHandler(nil) + } + func accommodatePresentedSubitemDeletion(at url: URL, completionHandler: @escaping (Error?) -> Void) { + callback.success(keep: true) + completionHandler(nil) + } +} diff --git a/platforms/ios/runner/lib/IncomingLinks.swift b/platforms/ios/runner/lib/IncomingLinks.swift new file mode 100644 index 0000000000..695ff8c29c --- /dev/null +++ b/platforms/ios/runner/lib/IncomingLinks.swift @@ -0,0 +1,52 @@ +import Foundation + +@MainActor +final class IncomingLinks { + static let shared = IncomingLinks() + private var pending: [[String: Any]] = [] + private var listener: Callback? + private var pendingAuth: URL? + var authenticationHandler: ((URL) -> Void)? { + didSet { + if let pendingAuth, let authenticationHandler { + self.pendingAuth = nil + authenticationHandler(pendingAuth) + } + } + } + + func receive(_ url: URL) { + if url.scheme == "acode", url.host == "auth", url.path == "/callback" { + if let authenticationHandler { authenticationHandler(url) } + else { pendingAuth = url } + return + } + var intent: [String: Any] = ["action": "android.intent.action.VIEW", "data": url.absoluteString] + if url.isFileURL { + let files = AppFiles.shared + do { + if (try? files.resolve(url.absoluteString)) == nil { + try files.remember(url) + } + intent["data"] = "file://" + url.path + intent["fileUri"] = intent["data"] + intent["uris"] = [intent["data"]!] + } catch { intent["error"] = error.localizedDescription } + } + if let listener { listener.success(intent, keep: true) } + else { pending.append(intent) } + NotificationCenter.default.post(name: .acodeDeepLink, object: url) + } + + func listen(_ callback: Callback) { listener?.release(); listener = callback } + + func current(_ callback: Callback) { + callback.success(pending.isEmpty ? [:] : pending.removeFirst()) + if let listener { + for intent in pending { listener.success(intent, keep: true) } + pending.removeAll() + } + } + + func reset() { listener?.release(); listener = nil } +} diff --git a/platforms/ios/runner/lib/NativeService.swift b/platforms/ios/runner/lib/NativeService.swift new file mode 100644 index 0000000000..252f768edd --- /dev/null +++ b/platforms/ios/runner/lib/NativeService.swift @@ -0,0 +1,381 @@ +import UIKit +import SafariServices +import Photos +import AVFoundation +import CoreHaptics +import Darwin +import DeviceKit + +final class NativeService: BaseService { + + private var cameraCallback: Callback? + private var intentObserver: NSObjectProtocol? + private lazy var browser = SafariService(bridge: bridge!) + private lazy var hapticGenerator = UIImpactFeedbackGenerator(style: .medium) + private var hapticsEngine: CHHapticEngine? + private let supportsHaptics: Bool = { + if #available(iOS 13.0, *) { + return CHHapticEngine.capabilitiesForHardware().supportsHaptics + } else { + return false + } + }() + + override func exec(action: String, args: [Any], callback: Callback) { + switch action { + case "shareFile": shareFile(args: args, callback: callback) + case "shareText": shareText(args: args, callback: callback) + case "getAppInfo": getAppInfo(args: args, callback: callback) + case "getDeviceInfo": getDeviceInfo(args: args, callback: callback) + case "getVersionSdkInt": callback.success(0) + case "openInBrowser": openInBrowser(args: args, callback: callback) + case "setIntentHandler": setIntentHandler(args: args, callback: callback) + case "setTheme": setTheme(args: args, callback: callback) + case "setSystemBarColor": setSystemBarColor(args: args, callback: callback) + case "getConfiguration": getConfiguration(args: args, callback: callback) + case "requestPermission": requestPermission(args: args, callback: callback) + case "requestPermissions": requestPermissions(args: args, callback: callback) + case "hasPermission": hasPermission(args: args, callback: callback) + case "captureFromCamera": captureFromCamera(args: args, callback: callback) + case "getIpAddresses": getIpAddresses(args: args, callback: callback) + case "hideSplashScreen": callback.success() + case "haptic": haptic(callback: callback) + case "exitApp": exit(0) + case "restartApp": callback.error("Programmatic app restart is unavailable on iOS") + case "requestIgnoreBatteryOptimization": callback.success(1) + default: callback.error("Unknown action: \(action)") + } + } + + // MARK: - shareFile / shareText + + private func shareFile(args: [Any], callback: Callback) { + guard let share = bridge?.shareService else { callback.error("Native bridge unavailable"); return } + share.exec(action: "shareFile", args: args, callback: callback) + } + + private func shareText(args: [Any], callback: Callback) { + guard let share = bridge?.shareService else { callback.error("Native bridge unavailable"); return } + share.exec(action: "shareText", args: args, callback: callback) + } + + // MARK: - getAppInfo + + private func getAppInfo(args: [Any], callback: Callback) { + let info = Bundle.main.infoDictionary + let result: [String: Any] = [ + "label": info?["CFBundleDisplayName"] as? String ?? info?["CFBundleName"] as? String ?? "", + "packageName": Bundle.main.bundleIdentifier ?? "", + "versionName": info?["CFBundleShortVersionString"] as? String ?? "", + "versionCode": Int(info?["CFBundleVersion"] as? String ?? "0") ?? 0, + "firstInstallTime": 0, + "lastUpdateTime": 0, + ] + callback.success(result) + } + + // MARK: - getDeviceInfo + + private func getDeviceInfo(args: [Any], callback: Callback) { + let device = UIDevice.current + let result: [String: Any] = [ + "manufacturer": "Apple", + "model": Device.current.description, + "product": device.name, + "isEmulator": Device.current.isSimulator, + ] + callback.success(result) + } + + // MARK: - openInBrowser + + private func openInBrowser(args: [Any], callback: Callback) { + browser.exec(action: "open", args: args, callback: callback) + } + + // MARK: - setIntentHandler + + private func setIntentHandler(args: [Any], callback: Callback) { + if let existing = intentObserver { + NotificationCenter.default.removeObserver(existing) + } + intentObserver = NotificationCenter.default.addObserver( + forName: .acodeDeepLink, object: nil, queue: .main + ) { notification in + if let url = notification.object as? URL { + callback.success(url.absoluteString, keep: true) + } + } + callback.success(nil, keep: true) + } + + // MARK: - setTheme / setSystemBarColor + + private func setTheme(args: [Any], callback: Callback) { + let systemBarColor = args[safe: 0] as? String + guard let theme = parseTheme(args[safe: 1]) ?? parseTheme(args[safe: 0]) else { + callback.error("Invalid theme JSON"); return + } + DispatchQueue.main.async { [weak self] in + let backgroundHex = systemBarColor ?? theme["primaryColor"] as? String + if let backgroundHex, let color = UIColor(hexString: backgroundHex) { + self?.viewController?.setSystemBarColor(color) + } + if let type = theme["type"] as? String { + self?.viewController?.setThemeType(type) + } + callback.success() + } + } + + private func parseTheme(_ value: Any?) -> [String: Any]? { + if let dict = value as? [String: Any] { return dict } + if let themeStr = value as? String, let data = themeStr.data(using: .utf8) { + return try? JSONSerialization.jsonObject(with: data) as? [String: Any] + } + return nil + } + + private func setSystemBarColor(args: [Any], callback: Callback) { + DispatchQueue.main.async { [weak self] in + self?.viewController?.setNeedsStatusBarAppearanceUpdate() + } + callback.success() + } + + // MARK: - getConfiguration + + @available(iOS, deprecated: 26.0, message: "Migrate to effectiveGeometry.interfaceOrientation when targeting iOS 26+") + private func getConfiguration(args: [Any], callback: Callback) { + DispatchQueue.main.async { [weak self] in + guard let self, let vc = self.viewController else { callback.error("No view controller"); return } + let windowScene = UIApplication.shared.connectedScenes + .compactMap { $0 as? UIWindowScene }.first + let orientation = windowScene?.interfaceOrientation.isPortrait == true ? "portrait" : "landscape" + let locale = Locale.current.identifier.replacingOccurrences(of: "_", with: "-") + let result: [String: Any] = [ + "keyboard": vc.isKeyboardVisible, + "orientation": orientation, + "locale": locale, + "fontScale": self.fontScale(), + ] + callback.success(result) + } + } + + private func fontScale() -> Double { + switch UIApplication.shared.preferredContentSizeCategory { + case .extraSmall: return 0.80 + case .small: return 0.85 + case .medium: return 0.90 + case .large: return 1.00 + case .extraLarge: return 1.10 + case .extraExtraLarge: return 1.20 + case .extraExtraExtraLarge: return 1.30 + case .accessibilityMedium: return 1.40 + case .accessibilityLarge: return 1.50 + case .accessibilityExtraLarge: return 1.60 + case .accessibilityExtraExtraLarge: return 1.70 + case .accessibilityExtraExtraExtraLarge: return 2.00 + default: return 1.00 + } + } + + @available(iOS 13.0, *) + private func startHapticsEngineIfNeeded() { + guard supportsHaptics else { return } + if hapticsEngine == nil { + do { + hapticsEngine = try CHHapticEngine() + } catch { + // Leave engine nil on failure; we'll fall back to UIFeedbackGenerator. + return + } + } + do { + try hapticsEngine?.start() + } catch { + // Ignore start errors; fallback will be used. + } + } + + // MARK: - Permissions + + private enum PermissionKind { + case camera, microphone, notifications, photoLibrary, unsupported + } + + private func permissionKind(for name: String) -> PermissionKind { + let lo = name.lowercased() + if lo.contains("camera") { return .camera } + if lo.contains("record_audio") || lo.contains("microphone") { return .microphone } + if lo.contains("notification") { return .notifications } + if lo.contains("photo") { return .photoLibrary } + return .unsupported + } + + private func requestPermission(args: [Any], callback: Callback) { + guard let permission = args[safe: 0] as? String else { + callback.error("Permission name required"); return + } + requestSinglePermission(permissionKind(for: permission), callback: callback) + } + + private func requestPermissions(args: [Any], callback: Callback) { + guard let permissions = args[safe: 0] as? [String] else { + callback.error("Permissions array required"); return + } + requestNextPermission(Array(permissions), index: 0, callback: callback) + } + + private func requestNextPermission(_ permissions: [String], index: Int, callback: Callback) { + guard index < permissions.count else { callback.success(1); return } + requestSinglePermission(permissionKind(for: permissions[index])) { [weak self] _ in + self?.requestNextPermission(permissions, index: index + 1, callback: callback) + } + } + + private func requestSinglePermission(_ kind: PermissionKind, callback: Callback? = nil, completion: ((Bool) -> Void)? = nil) { + let done: (Bool) -> Void = { granted in + callback?.success(granted ? 1 : 0) + completion?(granted) + } + switch kind { + case .unsupported: + callback?.error("This permission is unavailable on iOS; use the Files picker for document access") + completion?(false) + case .camera: + AVCaptureDevice.requestAccess(for: .video) { done($0) } + case .microphone: + AVAudioApplication.requestRecordPermission { done($0) } + case .notifications: + UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, _ in done(granted) } + case .photoLibrary: + PHPhotoLibrary.requestAuthorization(for: .readWrite) { status in + done(status == .authorized || status == .limited) + } + } + } + + private func hasPermission(args: [Any], callback: Callback) { + guard let permission = args[safe: 0] as? String else { + callback.error("Permission name required"); return + } + switch permissionKind(for: permission) { + case .unsupported: + callback.success(0) + case .camera: + callback.success(AVCaptureDevice.authorizationStatus(for: .video) == .authorized ? 1 : 0) + case .microphone: + callback.success(AVAudioApplication.shared.recordPermission == .granted ? 1 : 0) + case .notifications: + UNUserNotificationCenter.current().getNotificationSettings { settings in + callback.success(settings.authorizationStatus == .authorized ? 1 : 0) + } + case .photoLibrary: + let status = PHPhotoLibrary.authorizationStatus(for: .readWrite) + callback.success(status == .authorized || status == .limited ? 1 : 0) + } + } + + // MARK: - captureFromCamera + + private func captureFromCamera(args: [Any], callback: Callback) { + DispatchQueue.main.async { [weak self] in + guard let self = self, let vc = self.viewController else { return } + guard UIImagePickerController.isSourceTypeAvailable(.camera) else { + callback.error("Camera not available"); return + } + self.cameraCallback = callback + let picker = UIImagePickerController() + picker.sourceType = .camera + picker.delegate = self + vc.present(picker, animated: true) + } + } + + // MARK: - getIpAddresses + + private func getIpAddresses(args: [Any], callback: Callback) { + var addresses = [String]() + var ifaddr: UnsafeMutablePointer<ifaddrs>? + guard getifaddrs(&ifaddr) == 0 else { callback.success(addresses); return } + defer { freeifaddrs(ifaddr) } + var ptr = ifaddr + while let ifa = ptr { + defer { ptr = ifa.pointee.ifa_next } + guard let addr = ifa.pointee.ifa_addr else { continue } + let family = addr.pointee.sa_family + guard family == UInt8(AF_INET) || family == UInt8(AF_INET6) else { continue } + guard Int32(ifa.pointee.ifa_flags) & IFF_LOOPBACK == 0 else { continue } + var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) + getnameinfo(addr, socklen_t(addr.pointee.sa_len), &hostname, socklen_t(NI_MAXHOST), nil, 0, NI_NUMERICHOST) + addresses.append(String(cString: hostname)) + } + callback.success(addresses) + } +} + +// MARK: - Camera delegate + +extension NativeService: UIImagePickerControllerDelegate, UINavigationControllerDelegate { + func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { + picker.dismiss(animated: true) + guard let image = info[.originalImage] as? UIImage, + let data = image.jpegData(compressionQuality: 0.9) else { + cameraCallback?.error("Failed to capture image") + cameraCallback = nil + return + } + let fileName = "capture_\(Int(Date().timeIntervalSince1970)).jpg" + let destURL = FileManager.default.temporaryDirectory.appendingPathComponent(fileName) + do { + try data.write(to: destURL) + cameraCallback?.success(destURL.path) + } catch { + cameraCallback?.error(error.localizedDescription) + } + cameraCallback = nil + } + + func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { + picker.dismiss(animated: true) + cameraCallback?.error("Cancelled") + cameraCallback = nil + } + + private func haptic(callback: Callback) { + DispatchQueue.main.async { + if #available(iOS 13.0, *), self.supportsHaptics { + self.startHapticsEngineIfNeeded() + if let engine = self.hapticsEngine { + do { + let intensity = CHHapticEventParameter(parameterID: .hapticIntensity, value: 1.0) + let sharpness = CHHapticEventParameter(parameterID: .hapticSharpness, value: 0.5) + let event = CHHapticEvent(eventType: .hapticTransient, parameters: [intensity, sharpness], relativeTime: 0) + let pattern = try CHHapticPattern(events: [event], parameters: []) + let player = try engine.makePlayer(with: pattern) + try player.start(atTime: 0) + callback.success() + return + } catch { + // Fall back to UIFeedbackGenerator below on any error. + } + } + } + // Fallback for devices without Core Haptics or if starting/playing the engine failed. + let generator = UIImpactFeedbackGenerator(style: .medium) + generator.prepare() + generator.impactOccurred() + callback.success() + } + } +} + +// MARK: - Notification name + +extension Notification.Name { + static let acodeDeepLink = Notification.Name("acodeDeepLink") +} + +import UserNotifications diff --git a/platforms/ios/runner/lib/NotificationService.swift b/platforms/ios/runner/lib/NotificationService.swift new file mode 100644 index 0000000000..f1fa4660eb --- /dev/null +++ b/platforms/ios/runner/lib/NotificationService.swift @@ -0,0 +1,122 @@ +import UserNotifications +import UIKit + +final class NotificationService: BaseService { + + // Shared instance used by AppDelegate's UNUserNotificationCenterDelegate. + static weak var shared: NotificationService? + + private struct NotificationEntry { + let content: UNMutableNotificationContent + var tapCallback: Callback? + } + + private var registry: [Int: NotificationEntry] = [:] + private var nextId = 1 + + required init(bridge: Bridge) { + super.init(bridge: bridge) + NotificationService.shared = self + } + + override func exec(action: String, args: [Any], callback: Callback) { + switch action { + case "create": create(args: args, callback: callback) + case "show": show(args: args, callback: callback) + case "hide": hide(args: args, callback: callback) + case "delete": deleteNotification(args: args, callback: callback) + case "addListener": addListener(args: args, callback: callback) + default: callback.error("Unknown action: \(action)") + } + } + + // MARK: - create + + private func create(args: [Any], callback: Callback) { + guard let title = args[safe: 0] as? String, + let message = args[safe: 1] as? String else { + callback.error("title and message required"); return + } + let content = UNMutableNotificationContent() + content.title = title + content.body = message + content.sound = .default + // Apply optional options (icon/vibrate ignored on iOS) + if let optStr = args[safe: 2] as? String, + let data = optStr.data(using: .utf8), + let opts = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { + if let badge = opts["badge"] as? Int { + content.badge = NSNumber(value: badge) + } + } + let id = nextId + nextId += 1 + registry[id] = NotificationEntry(content: content) + callback.success(id) + } + + // MARK: - show + + private func show(args: [Any], callback: Callback) { + guard let id = args[safe: 0] as? Int, + let entry = registry[id] else { + callback.error("Invalid notification id"); return + } + let request = UNNotificationRequest( + identifier: String(id), + content: entry.content, + trigger: nil + ) + UNUserNotificationCenter.current().add(request) { error in + if let error = error { callback.error(error.localizedDescription) } + else { callback.success() } + } + } + + // MARK: - hide + + private func hide(args: [Any], callback: Callback) { + guard let id = args[safe: 0] as? Int else { callback.error("id required"); return } + UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [String(id)]) + callback.success() + } + + // MARK: - deleteNotification + + private func deleteNotification(args: [Any], callback: Callback) { + guard let id = args[safe: 0] as? Int else { callback.error("id required"); return } + let strId = String(id) + UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [strId]) + UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [strId]) + registry.removeValue(forKey: id) + callback.success() + } + + // MARK: - addListener + + private func addListener(args: [Any], callback: Callback) { + guard let id = args[safe: 0] as? Int else { callback.error("id required"); return } + registry[id]?.tapCallback = callback + callback.success(nil, keep: true) + } + + // MARK: - Tap handler (called by AppDelegate's UNUserNotificationCenterDelegate) + + func handleNotificationTap(response: UNNotificationResponse) { + guard let id = Int(response.notification.request.identifier) else { return } + registry[id]?.tapCallback?.success(id, keep: true) + } +} + +// MARK: - UNUserNotificationCenterDelegate + +extension NotificationService: UNUserNotificationCenterDelegate { + func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { + handleNotificationTap(response: response) + completionHandler() + } + + func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { + completionHandler([.banner, .sound, .badge]) + } +} diff --git a/platforms/ios/runner/lib/PlatformServices.swift b/platforms/ios/runner/lib/PlatformServices.swift new file mode 100644 index 0000000000..b7021973be --- /dev/null +++ b/platforms/ios/runner/lib/PlatformServices.swift @@ -0,0 +1,71 @@ +import UIKit +import WebKit + +final class BuildInfoService: BaseService { + override func exec(action: String, args: [Any], callback: Callback) { + guard action == "init" else { callback.error("Unknown BuildInfo action: \(action)"); return } + let info = Bundle.main.infoDictionary ?? [:] + let id = Bundle.main.bundleIdentifier ?? "app.acode" + let name = info["CFBundleDisplayName"] as? String ?? "Acode" + #if DEBUG + let debug = true + let buildType = "debug" + #else + let debug = false + let buildType = "release" + #endif + let flavor = "free" + callback.success(["packageName": id, "basePackageName": id, "displayName": name, "name": name, + "version": info["CFBundleShortVersionString"] as? String ?? "", "versionCode": Int(info["CFBundleVersion"] as? String ?? "0") ?? 0, + "debug": debug, "buildType": buildType, "flavor": flavor]) + } +} + +final class ClipboardService: BaseService { + override func exec(action: String, args: [Any], callback: Callback) { + DispatchQueue.main.async { + switch action { + case "copy": UIPasteboard.general.string = args[safe: 0] as? String ?? ""; callback.success() + case "paste": callback.success(UIPasteboard.general.string ?? "") + case "clear": UIPasteboard.general.items = []; callback.success() + default: callback.error("Unknown Clipboard action: \(action)") + } + } + } +} + +final class AppService: BaseService { + override func exec(action: String, args: [Any], callback: Callback) { + DispatchQueue.main.async { [self] in + switch action { + case "backHistory": self.webView?.goBack(); callback.success() + case "clearCache", "clear-cache": + WKWebsiteDataStore.default().removeData(ofTypes: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache], modifiedSince: .distantPast) { + callback.success(action == "clear-cache" ? "Cache cleared" : nil) + } + case "exitApp": exit(0) + default: callback.error("\(action) is unavailable on iOS") + } + } + } +} + +final class SystemBarService: BaseService { + override func exec(action: String, args: [Any], callback: Callback) { + DispatchQueue.main.async { [weak self] in + guard let controller = self?.viewController else { callback.error("View unavailable"); return } + switch action { + case "setStatusBarVisible": + controller.statusBarHidden = !(args[safe: 0] as? Bool ?? true) + controller.setNeedsStatusBarAppearanceUpdate() + case "setStatusBarBackgroundColor": + if args.count >= 3 { + let color = UIColor(red: (args[0] as? Double ?? 0) / 255, green: (args[1] as? Double ?? 0) / 255, blue: (args[2] as? Double ?? 0) / 255, alpha: args[safe: 3] as? Double ?? 1) + controller.setSystemBarColor(color) + } + default: callback.error("Unknown SystemBar action: \(action)"); return + } + callback.success() + } + } +} diff --git a/platforms/ios/runner/lib/RewardPassManager.swift b/platforms/ios/runner/lib/RewardPassManager.swift new file mode 100644 index 0000000000..583ca776b1 --- /dev/null +++ b/platforms/ios/runner/lib/RewardPassManager.swift @@ -0,0 +1,93 @@ +import Foundation + +// Preserves earned passes from before new redemptions were discontinued. +final class RewardPassManager { + private static let hour: Int64 = 60 * 60 * 1000 + private static let maximumDuration = 10 * hour + private static let maximumRedemptions = 3 + private let store: SecretStore + private let now: () -> Date + + init(store: SecretStore = SecretStore(namespace: "ads"), now: @escaping () -> Date = Date.init) { + self.store = store + self.now = now + } + + func getRewardStatus() throws -> String { + let date = now() + let raw = try store.get("reward_state") + let values = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [String: Any] ?? [:] + var state = synchronizedState(values, date: date) + let status = status(state, date: date) + state.expiryNoticePendingUntil = 0 + try save(state, previous: values) + return try json(status) + } + + private func synchronizedState(_ values: [String: Any], date: Date) -> RewardPassState { + let today = day(date) + var state = RewardPassState(values, today: today) + if state.redemptionDay != today { + state.redemptionDay = today + state.redemptionsToday = 0 + } + if state.adFreeUntil > 0, state.adFreeUntil <= milliseconds(date) { + state.expiryNoticePendingUntil = state.adFreeUntil + state.lastExpiredRewardUntil = state.adFreeUntil + state.adFreeUntil = 0 + } + return state + } + + private func status(_ state: RewardPassState, date: Date) -> [String: Any] { + let time = milliseconds(date) + return ["adFreeUntil": state.adFreeUntil, "lastExpiredRewardUntil": state.lastExpiredRewardUntil, + "isActive": state.adFreeUntil > time, "remainingMs": max(0, state.adFreeUntil - time), + "redemptionsToday": state.redemptionsToday, + "remainingRedemptions": max(0, Self.maximumRedemptions - state.redemptionsToday), + "maxRedemptionsPerDay": Self.maximumRedemptions, "maxActivePassMs": Self.maximumDuration, + "hasPendingExpiryNotice": state.expiryNoticePendingUntil > 0, + "expiryNoticePendingUntil": state.expiryNoticePendingUntil, + "canRedeem": false, "redeemDisabledReason": "Ad-free passes are no longer available."] + } + + private func save(_ state: RewardPassState, previous: [String: Any]) throws { + let values: [String: Any] = [ + "adFreeUntil": state.adFreeUntil, "lastExpiredRewardUntil": state.lastExpiredRewardUntil, + "expiryNoticePendingUntil": state.expiryNoticePendingUntil, + "redemptionDay": state.redemptionDay, "redemptionsToday": state.redemptionsToday, + ] + if !NSDictionary(dictionary: values).isEqual(to: previous) { + try store.set("reward_state", value: json(values)) + } + } + + private func json(_ value: [String: Any]) throws -> String { + String(decoding: try JSONSerialization.data(withJSONObject: value), as: UTF8.self) + } + + private func milliseconds(_ date: Date) -> Int64 { Int64(date.timeIntervalSince1970 * 1000) } + + private func day(_ date: Date) -> String { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = .current + return String(format: "%04d-%02d-%02d", calendar.component(.year, from: date), + calendar.component(.month, from: date), calendar.component(.day, from: date)) + } +} + +private struct RewardPassState { + var adFreeUntil: Int64 + var lastExpiredRewardUntil: Int64 + var expiryNoticePendingUntil: Int64 + var redemptionDay: String + var redemptionsToday: Int + + init(_ values: [String: Any], today: String) { + adFreeUntil = (values["adFreeUntil"] as? NSNumber)?.int64Value ?? 0 + lastExpiredRewardUntil = (values["lastExpiredRewardUntil"] as? NSNumber)?.int64Value ?? 0 + expiryNoticePendingUntil = (values["expiryNoticePendingUntil"] as? NSNumber)?.int64Value ?? 0 + redemptionDay = values["redemptionDay"] as? String ?? today + redemptionsToday = (values["redemptionsToday"] as? NSNumber)?.intValue ?? 0 + } +} diff --git a/platforms/ios/runner/lib/SafariService.swift b/platforms/ios/runner/lib/SafariService.swift new file mode 100644 index 0000000000..750c340738 --- /dev/null +++ b/platforms/ios/runner/lib/SafariService.swift @@ -0,0 +1,105 @@ +import SafariServices + +final class SafariService: BaseService, SFSafariViewControllerDelegate { + private weak var browser: SFSafariViewController? + private var openCallback: Callback? + private var lifecycleCallback: Callback? + private var authTabId: String? + + override func reset() { + DispatchQueue.main.async { + self.browser?.dismiss(animated: false) + self.browser = nil + self.openCallback?.error("Browser presentation was cancelled") + self.openCallback = nil + self.lifecycleCallback?.release() + self.lifecycleCallback = nil + self.authTabId = nil + } + } + + override func exec(action: String, args: [Any], callback: Callback) { + if action == "close" { + DispatchQueue.main.async { + guard let id = args[safe: 0] as? String, id == self.authTabId, let browser = self.browser else { + callback.success(); return + } + browser.dismiss(animated: true) { + self.safariViewControllerDidFinish(browser) + callback.success() + } + } + return + } + guard let value = args[safe: 0] as? String, let inputURL = URL(string: value), let scheme = inputURL.scheme?.lowercased() else { + callback.error("Invalid browser URL"); return + } + let url = Self.websiteURL(inputURL) + if action == "external" { + guard !["javascript", "data", "file", "acode", "about"].contains(scheme) else { callback.error("Unsupported external URL"); return } + DispatchQueue.main.async { + UIApplication.shared.open(url) { opened in + if opened { callback.success() } + else { callback.error("No app can open this URL") } + } + } + return + } + guard action == "open", ["http", "https"].contains(scheme), url.host != nil else { + callback.error("Custom tabs require an HTTP or HTTPS URL"); return + } + let options = args[safe: 1] as? [String: Any] ?? [:] + DispatchQueue.main.async { + guard let presenter = self.viewController, presenter.presentedViewController == nil else { + callback.error("A browser cannot be presented right now"); return + } + let configuration = SFSafariViewController.Configuration() + configuration.barCollapsingEnabled = false + let browser = SFSafariViewController(url: url, configuration: configuration) + browser.delegate = self + browser.modalPresentationStyle = .fullScreen + browser.dismissButtonStyle = .close + if #unavailable(iOS 26), let color = options["toolbarColor"] as? String { browser.preferredBarTintColor = UIColor(hexString: color) } + self.browser = browser + self.openCallback = callback + self.authTabId = options["authTabId"] as? String + let reportLifecycle = options["reportLifecycle"] as? Bool == true + presenter.present(browser, animated: true) { + guard self.browser === browser else { return } + self.openCallback = nil + if reportLifecycle { + self.lifecycleCallback = callback + callback.success(["type": "opened"], keep: true) + } + else { callback.success() } + } + } + } + + func safariViewController(_ controller: SFSafariViewController, activityItemsFor url: URL, title: String?) -> [UIActivity] { + BrowserActivity.available(for: url, canOpen: UIApplication.shared.canOpenURL) + } + + func safariViewControllerDidFinish(_ controller: SFSafariViewController) { + guard browser === controller else { return } + browser = nil + authTabId = nil + openCallback?.error("Browser closed before presentation completed") + openCallback = nil + lifecycleCallback?.success(["type": "closed"]) + lifecycleCallback = nil + } + + static func websiteURL(_ url: URL) -> URL { + guard url.scheme?.lowercased() == "https", + ["acode.app", "dev.acode.app"].contains(url.host?.lowercased() ?? ""), + url.port == nil || url.port == 443, + url.user == nil, url.password == nil, + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return url } + var query = components.percentEncodedQuery?.components(separatedBy: "&") ?? [] + query.removeAll { $0.components(separatedBy: "=").first?.removingPercentEncoding == "src" } + query.append("src=ios") + components.percentEncodedQuery = query.joined(separator: "&") + return components.url ?? url + } +} diff --git a/platforms/ios/runner/lib/ShareService.swift b/platforms/ios/runner/lib/ShareService.swift new file mode 100644 index 0000000000..df2ea022e4 --- /dev/null +++ b/platforms/ios/runner/lib/ShareService.swift @@ -0,0 +1,69 @@ +import UIKit + +final class ShareService: BaseService { + private weak var sheet: UIActivityViewController? + private var exportDirectory: URL? + private var pendingCallback: Callback? + + override func reset() { + DispatchQueue.main.async { [weak self] in + let sheet = self?.sheet + self?.finish(error: "Operation cancelled") + sheet?.dismiss(animated: false) + } + } + + override func exec(action: String, args: [Any], callback: Callback) { + do { + let item: Any + var cleanup: URL? + if action == "shareText" { + item = args[safe: 0] as? String ?? "" + } else { + let source = try AppFiles.shared.resolve(args[safe: 0] as? String ?? "") + let requestedName = args[safe: 1] as? String ?? "" + let name = requestedName.isEmpty ? source.lastPathComponent : URL(fileURLWithPath: requestedName).lastPathComponent + guard !name.isEmpty, name != ".", name != ".." else { throw FileFailure(5) } + let directory = AppFiles.shared.temporary.appendingPathComponent("share-" + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + cleanup = directory + let target = directory.appendingPathComponent(name) + do { try AppFiles.shared.coordinate(source) { try FileManager.default.copyItem(at: $0, to: target) } } + catch { try? FileManager.default.removeItem(at: directory); throw error } + item = target + } + DispatchQueue.main.async { [weak self] in + guard let self, let presenter = self.viewController, presenter.presentedViewController == nil, + presenter.viewIfLoaded?.window != nil, self.pendingCallback == nil else { + if let cleanup { try? FileManager.default.removeItem(at: cleanup) } + callback.error("A share sheet cannot be presented right now"); return + } + let sheet = UIActivityViewController(activityItems: [item], applicationActivities: nil) + if let popover = sheet.popoverPresentationController { + popover.sourceView = presenter.view + popover.sourceRect = CGRect(x: presenter.view.bounds.midX, y: presenter.view.bounds.midY, width: 1, height: 1) + popover.permittedArrowDirections = [] + } + self.sheet = sheet + self.exportDirectory = cleanup + self.pendingCallback = callback + sheet.completionWithItemsHandler = { [weak self, weak sheet] _, _, _, error in + guard let self, let sheet, self.sheet === sheet else { return } + self.finish(error: error?.localizedDescription) + } + presenter.present(sheet, animated: true) + } + } catch { callback.error(error.localizedDescription) } + } + + private func finish(error: String?) { + let callback = pendingCallback + pendingCallback = nil + sheet?.completionWithItemsHandler = nil + sheet = nil + if let exportDirectory { try? FileManager.default.removeItem(at: exportDirectory) } + exportDirectory = nil + if let error { callback?.error(error) } + else { callback?.success() } + } +} diff --git a/platforms/ios/runner/lib/SystemFiles.swift b/platforms/ios/runner/lib/SystemFiles.swift new file mode 100644 index 0000000000..e48783a315 --- /dev/null +++ b/platforms/ios/runner/lib/SystemFiles.swift @@ -0,0 +1,76 @@ +import Foundation + +struct SystemFiles { + private static let files = AppFiles.shared + + static func perform(_ action: String, args: [Any]) throws -> Any? { + let path = args[safe: 0] as? String ?? "" + if action == "fileExists" { + let countLinks = (args[safe: 1] as? String)?.lowercased() == "true" + guard let url = try? files.resolve(path, followingFinalSymlink: !countLinks) else { return 0 } + let linkExists = countLinks && (try? files.manager.destinationOfSymbolicLink(atPath: url.path)) != nil + return linkExists || files.manager.fileExists(atPath: url.path) ? 1 : 0 + } + if action == "createSymlink" { return createSymlink(target: path, path: args[safe: 1] as? String ?? "") } + if action == "extractAsset" { + guard !path.isEmpty, !path.hasPrefix("/"), !path.split(separator: "/").contains("..") else { throw FileFailure(5) } + let source = try files.resolve(files.application.appendingPathComponent(path).absoluteString) + let destination = try files.resolve(args[safe: 1] as? String ?? "", followingFinalSymlink: false) + try copy(source, to: destination) + return nil + } + let url = try files.resolve(path, followingFinalSymlink: action != "deleteFile" && action != "getParentPath") + switch action { + case "getParentPath": return url.deletingLastPathComponent().path + case "listChildren": + return (try? files.coordinate(url) { directory in + try files.manager.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil).map(\.path) + }) ?? [] + case "mkdirs": + try files.coordinate(url, writing: true) { item in + guard !files.manager.fileExists(atPath: item.path) else { throw SecretFailure("mkdirs failed") } + try files.manager.createDirectory(at: item, withIntermediateDirectories: true) + } + case "writeText": + guard let content = args[safe: 1] as? String else { throw FileFailure(5) } + // Android writes a singleton line, including its terminating newline. + try files.coordinate(url, writing: true) { try (content + "\n").write(to: $0, atomically: true, encoding: .utf8) } + return "File written successfully" + case "deleteFile": + try files.coordinate(url, writing: true) { item in + guard !files.allRoots().values.contains(where: { $0.standardizedFileURL.resolvingSymlinksInPath() == item }) else { throw FileFailure(6) } + let info = try files.manager.attributesOfItem(atPath: item.path) + if info[.type] as? FileAttributeType == .typeDirectory, + !(try files.manager.contentsOfDirectory(atPath: item.path)).isEmpty { throw SecretFailure("delete failed") } + try files.manager.removeItem(at: item) + } + case "copyToUri": + let directory = try files.resolve(args[safe: 1] as? String ?? "") + let name = args[safe: 2] as? String ?? "" + guard !name.isEmpty, name != ".", name != "..", !name.contains("/"), !name.contains("\0") else { throw FileFailure(5) } + try files.coordinate(directory, writing: true) { + try files.manager.createDirectory(at: $0, withIntermediateDirectories: true) + } + let destination = try files.resolve(directory.appendingPathComponent(name).absoluteString, followingFinalSymlink: false) + try copy(url, to: destination) + default: throw FileFailure(9) + } + return nil + } + + private static func createSymlink(target: String, path: String) -> Int { + do { + guard !target.isEmpty else { return 0 } + let link = try files.resolve(path, followingFinalSymlink: false) + let destination = target.hasPrefix("/") ? target : link.deletingLastPathComponent().appendingPathComponent(target).path + _ = try files.resolve(destination) + try files.coordinate(link, writing: true) { try files.manager.createSymbolicLink(atPath: $0.path, withDestinationPath: target) } + return 1 + } catch { return 0 } + } + + private static func copy(_ source: URL, to destination: URL) throws { + guard (try source.resourceValues(forKeys: [.isRegularFileKey])).isRegularFile == true else { throw FileFailure(9) } + try FileTransfer.perform(source, to: destination) + } +} diff --git a/platforms/ios/runner/lib/SystemService.swift b/platforms/ios/runner/lib/SystemService.swift new file mode 100644 index 0000000000..aadf9a72dd --- /dev/null +++ b/platforms/ios/runner/lib/SystemService.swift @@ -0,0 +1,117 @@ +import CryptoKit +import UIKit +import WebKit + +final class SystemService: BaseService { + private lazy var native = NativeService(bridge: bridge!) + private let files = AppFiles.shared + private let streams = HTTPStreamService() + private let rewards = RewardPassManager() + private lazy var browser = SafariService(bridge: bridge!) + private lazy var preview = BrowserService(bridge: bridge!) + + override func reset() { + streams.reset() + browser.reset() + preview.reset() + DispatchQueue.main.async { [weak self] in + IncomingLinks.shared.reset() + self?.viewController?.fullscreen.setActive(false) + (self?.webView as? AppWebView)?.nativeContextMenuDisabled = false + } + } + + override func exec(action: String, args: [Any], callback: Callback) { + do { + switch action { + case "http-stream-start", "http-stream-cancel", "http-stream-ack": streams.exec(action: action, args: args, callback: callback) + case "get-available-encodings": callback.success(FileContents.availableEncodings()) + case "encode": + guard let text = args[safe: 0] as? String, let data = text.data(using: try FileContents.encoding(args[safe: 1] as? String ?? "UTF-8")) else { throw FileFailure(5) } + callback.successBinary(data) + case "decode": + guard let encoded = args[safe: 0] as? String, let data = Data(base64Encoded: encoded), let text = String(data: data, encoding: try FileContents.encoding(args[safe: 1] as? String ?? "UTF-8")) else { throw FileFailure(5) } + callback.success(text) + case "getInstaller": callback.success("appstore") + case "getRewardStatus": callback.success(try rewards.getRewardStatus()) + case "get-android-version": callback.success(0) + case "get-configuration": + DispatchQueue.main.async { [weak self] in callback.success(self?.viewController?.systemConfiguration ?? [:]) } + case "get-app-info": native.exec(action: "getAppInfo", args: args, callback: callback) + case "get-webkit-info": callback.success(["packageName": "com.apple.WebKit", "versionName": ProcessInfo.processInfo.operatingSystemVersionString]) + case "is-powersave-mode": callback.success(ProcessInfo.processInfo.isLowPowerModeEnabled) + case "getFilesDir": callback.success(files.data.path) + case "getArch": + #if arch(arm64) + callback.success("arm64-v8a") + #else + callback.success("x86_64") + #endif + case "shareText": + guard let share = bridge?.shareService else { callback.error("Native bridge unavailable"); return } + share.exec(action: action, args: args, callback: callback) + case "file-action": + let intent = args[safe: 2] as? String ?? "android.intent.action.VIEW" + guard ["android.intent.action.VIEW", "android.intent.action.SEND"].contains(intent) else { + callback.error(["code": "UNSUPPORTED_ACTION", "message": "File intent \(intent) is unavailable on iOS"]); return + } + guard let share = bridge?.shareService else { callback.error("Native bridge unavailable"); return } + share.exec(action: "shareFile", args: args, callback: callback) + case "open-in-browser": browser.exec(action: "external", args: args, callback: callback) + case "in-app-browser": preview.exec(action: action, args: args, callback: callback) + case "set-ui-theme": native.exec(action: "setTheme", args: [args[safe: 0] ?? "", args[safe: 1] ?? [:]], callback: callback) + case "set-app-icon": AppIconService.set(args[safe: 0] as? String ?? "default", callback: callback) + case "has-permission", "request-permission": + native.exec(action: action == "has-permission" ? "hasPermission" : "requestPermission", args: args, callback: callback) + case "request-permissions": native.exec(action: "requestPermissions", args: args, callback: callback) + case "isManageExternalStorageDeclared", "hasGrantedStorageManager", "is-external-storage-manager": callback.success(false) + case "clearCache", "clear-cache": AppService(bridge: bridge!).exec(action: action, args: [], callback: callback) + case "checksumText": + guard let text = args[safe: 0] as? String else { throw FileFailure(5) } + callback.success(SHA256.hash(data: Data(text.utf8)).map { String(format: "%02x", $0) }.joined()) + case "get-global-setting": + DispatchQueue.main.async { + if args[safe: 0] as? String == "animator_duration_scale" { callback.success(UIAccessibility.isReduceMotionEnabled ? 0 : 1) } + else { callback.error("System setting is unavailable on iOS") } + } + case "get-intent": DispatchQueue.main.async { IncomingLinks.shared.current(callback) } + case "set-intent-handler": DispatchQueue.main.async { IncomingLinks.shared.listen(callback) } + case "set-fullscreen": + DispatchQueue.main.async { [weak self] in + guard let fullscreen = self?.viewController?.fullscreen, + let active = args[safe: 0] as? Bool else { callback.error("Invalid fullscreen request"); return } + fullscreen.setActive(active, callback: callback) + } + case "set-fullscreen-orientation": + DispatchQueue.main.async { [weak self] in + guard let fullscreen = self?.viewController?.fullscreen else { callback.error("View unavailable"); return } + fullscreen.setOrientation(args[safe: 0], callback: callback) + } + case "set-fullscreen-back-handler": + DispatchQueue.main.async { [weak self] in + guard let fullscreen = self?.viewController?.fullscreen, + let enabled = args[safe: 0] as? Bool else { callback.error("Invalid Back handler request"); return } + fullscreen.setBackHandler(enabled, callback: callback) + } + case "set-native-context-menu-disabled": + DispatchQueue.main.async { [weak self] in + (self?.webView as? AppWebView)?.nativeContextMenuDisabled = (args[safe: 0] as? String == "true") + callback.success() + } + case "compare-texts": + let first = args[safe: 0] as? String ?? "" + let second = args[safe: 1] as? String ?? "" + callback.success(first.utf16.elementsEqual(second.utf16) ? 0 : 1) + case "compare-file-text": + let url = try files.resolve(args[safe: 0] as? String ?? "") + let encoding = args[safe: 1] as? String ?? "" + let text = try files.coordinate(url) { try String(contentsOf: $0, encoding: FileContents.encoding(encoding.isEmpty ? "UTF-8" : encoding)) } + let current = args[safe: 2] as? String ?? "" + callback.success(text.utf16.elementsEqual(current.utf16) ? 0 : 1) + case "fileExists", "getParentPath", "listChildren", "mkdirs", "writeText", "deleteFile", "createSymlink", "copyToUri", "extractAsset": + callback.success(try SystemFiles.perform(action, args: args)) + default: callback.error(["code": "UNSUPPORTED_ACTION", "message": "System.\(action) is unavailable on iOS"]) + } + } catch { callback.error(error.localizedDescription) } + } +} diff --git a/platforms/ios/runner/lib/ftp/FTPClient.swift b/platforms/ios/runner/lib/ftp/FTPClient.swift new file mode 100644 index 0000000000..42e6b2ba30 --- /dev/null +++ b/platforms/ios/runner/lib/ftp/FTPClient.swift @@ -0,0 +1,132 @@ +import Foundation +import AcodeCurl + +final class FTPClient { + static let initialized = curl_global_init(Int(CURL_GLOBAL_DEFAULT)) + let profile: FTPProfile + let cancellation = FTPCancellation() + let queue = DispatchQueue(label: "app.acode.ftp.client", qos: .userInitiated) + var directory = "/" + private let handle: UnsafeMutableRawPointer + private let certificate: Data? + private let connectTo: String? + private var started = false + + init(_ profile: FTPProfile, certificate: Data? = nil, connectTo: String? = nil) throws { + guard Self.initialized == CURLE_OK, let handle = curl_easy_init() else { throw FTPFailure("Cannot initialize FTP") } + self.profile = profile; self.handle = handle; self.certificate = certificate + self.connectTo = connectTo + } + + deinit { curl_easy_cleanup(handle) } + + func connect() throws { + if started { try command("NOOP"); return } + _ = try perform("", commands: ["NOOP"]) + if let home = acode_curl_directory(handle) { directory = String(cString: home) } + started = true + } + + func path(_ value: String) throws -> String { + try FTPProfile.validate(value) + return ((value.hasPrefix("/") ? value : directory + "/" + value) as NSString).standardizingPath + } + + @discardableResult + func command(_ value: String, allowFailure: Bool = false) throws -> String { + try FTPProfile.validate(value) + let verb = String(value.prefix { !$0.isWhitespace }).uppercased() + guard !verb.isEmpty else { throw FTPFailure("Command is required.") } + let changesDirectory = ["CWD", "CDUP", "XCWD", "XCUP"].contains(verb) + let request = try perform(directory + "/", commands: [(allowFailure ? "*" : "") + value] + (changesDirectory ? ["PWD"] : []), close: changesDirectory) + if changesDirectory, let response = request.replies["PWD"], let home = Self.workingDirectory(response) { directory = home } + return request.replies[verb] ?? "" + } + + @discardableResult + func perform(_ remote: String, commands: [String] = [], listing: Bool = false, upload: Bool = false, request supplied: FTPRequest? = nil, close: Bool = false) throws -> FTPRequest { + try cancellation.check() + curl_easy_reset(handle) + let request = supplied ?? FTPRequest(cancellation) + let context = Unmanaged.passUnretained(request).toOpaque() + defer { + set(CURLOPT_VERBOSE, 0) + acode_curl_debug(handle, nil); acode_curl_progress(handle, nil); acode_curl_chunk(handle, nil) + for option in [CURLOPT_DEBUGDATA, CURLOPT_XFERINFODATA, CURLOPT_CHUNK_DATA, CURLOPT_WRITEDATA, CURLOPT_READDATA] { + acode_curl_pointer(handle, option, nil) + } + } + let url = try profile.url(remote) + var destinations: UnsafeMutablePointer<curl_slist>? + defer { acode_curl_pointer(handle, CURLOPT_CONNECT_TO, nil); curl_slist_free_all(destinations) } + // Test listeners use ephemeral ports while preserving the profile's TLS mode and hostname. + if let connectTo { + destinations = curl_slist_append(nil, connectTo) + acode_curl_pointer(handle, CURLOPT_CONNECT_TO, destinations) + } + set(CURLOPT_URL, listing ? String(url.dropLast(3)) + "*" : url) + set(CURLOPT_USERNAME, profile.username); set(CURLOPT_PASSWORD, profile.password) + set(CURLOPT_PROTOCOLS_STR, "ftp,ftps") + set(CURLOPT_NOSIGNAL, 1); set(CURLOPT_CONNECTTIMEOUT, 30); set(CURLOPT_SERVER_RESPONSE_TIMEOUT, 30) + set(CURLOPT_TCP_KEEPALIVE, 1); set(CURLOPT_TCP_KEEPIDLE, 300) + set(CURLOPT_FTP_FILEMETHOD, Int(CURLFTPMETHOD_SINGLECWD)) + set(CURLOPT_SSL_VERIFYPEER, 1); set(CURLOPT_SSL_VERIFYHOST, 2) + set(CURLOPT_SSL_OPTIONS, Int(CURLSSLOPT_NATIVE_CA)) + if let certificate { + set(CURLOPT_SSL_OPTIONS, 0) + _ = certificate.withUnsafeBytes { acode_curl_ca(handle, $0.baseAddress, $0.count) } + } + if profile.secure { set(CURLOPT_USE_SSL, Int(CURLUSESSL_ALL)) } + if profile.active { set(CURLOPT_FTPPORT, "-") } + set(CURLOPT_FORBID_REUSE, close ? 1 : 0) + set(CURLOPT_NOBODY, !commands.isEmpty ? 1 : 0) + set(CURLOPT_UPLOAD, upload ? 1 : 0) + set(CURLOPT_WILDCARDMATCH, listing ? 1 : 0) + if listing { set(CURLOPT_CUSTOMREQUEST, "LIST -a") } + acode_curl_write(handle, CURLOPT_WRITEFUNCTION, ftpWrite) + acode_curl_pointer(handle, CURLOPT_WRITEDATA, context) + acode_curl_read(handle, ftpRead) + acode_curl_pointer(handle, CURLOPT_READDATA, context) + acode_curl_write(handle, CURLOPT_HEADERFUNCTION, { _, size, count, _ in size * count }) + acode_curl_debug(handle, { _, type, bytes, count, pointer in + if let bytes { ftpRequest(pointer).trace(type, bytes: bytes, count: count) } + return 0 + }) + acode_curl_pointer(handle, CURLOPT_DEBUGDATA, context); set(CURLOPT_VERBOSE, 1) + acode_curl_progress(handle, { pointer, _, _, _, _ in ftpRequest(pointer).cancellation.cancelled || ftpRequest(pointer).error != nil ? 1 : 0 }) + acode_curl_pointer(handle, CURLOPT_XFERINFODATA, context); set(CURLOPT_NOPROGRESS, 0) + acode_curl_chunk(handle, { info, pointer, _ in + if let info { ftpRequest(pointer).entries.append(FTPEntry(info.assumingMemoryBound(to: curl_fileinfo.self).pointee)) } + return Int(CURL_CHUNK_BGN_FUNC_SKIP) + }) + acode_curl_pointer(handle, CURLOPT_CHUNK_DATA, context) + var quotes: UnsafeMutablePointer<curl_slist>? + defer { curl_slist_free_all(quotes) } + for command in commands { quotes = curl_slist_append(quotes, command) } + acode_curl_pointer(handle, CURLOPT_POSTQUOTE, quotes) + let code = curl_easy_perform(handle) + if let error = request.error { throw error } + try cancellation.check() + let reply = Int(acode_curl_response(handle)) + if listing && code == CURLE_REMOTE_FILE_NOT_FOUND && request.replyCodes["LIST"] == 226 { return request } + guard code == CURLE_OK else { throw FTPFailure(String(cString: curl_easy_strerror(code)), replyCode: reply) } + return request + } + + private func set(_ option: CURLoption, _ value: Int) { acode_curl_long(handle, option, value) } + private func set(_ option: CURLoption, _ value: String) { acode_curl_string(handle, option, value) } + + private static func workingDirectory(_ response: String) -> String? { + guard let opening = response.firstIndex(of: "\"") else { return nil } + var value = "", index = response.index(after: opening) + while index < response.endIndex { + let character = response[index]; index = response.index(after: index) + if character == "\"" { + guard index < response.endIndex, response[index] == "\"" else { return value } + index = response.index(after: index) + } + value.append(character) + } + return nil + } +} diff --git a/platforms/ios/runner/lib/ftp/FTPEntry.swift b/platforms/ios/runner/lib/ftp/FTPEntry.swift new file mode 100644 index 0000000000..0056926eae --- /dev/null +++ b/platforms/ios/runner/lib/ftp/FTPEntry.swift @@ -0,0 +1,82 @@ +import Foundation +import AcodeCurl + +struct FTPEntry { + var name: String + var size: Int64 = 0 + var directory = false + var file = false + var link: String? + var user: String? + var group: String? + var links = 0 + var readable = true + var writable = true + var modified: Double = 0 + + init(_ info: curl_fileinfo) { + name = Self.string(info.filename) ?? "" + size = Int64(info.size) + directory = info.filetype == CURLFILETYPE_DIRECTORY + file = info.filetype == CURLFILETYPE_FILE + if info.filetype == CURLFILETYPE_SYMLINK { link = Self.string(info.strings.target) ?? "" } + user = Self.string(info.strings.user); group = Self.string(info.strings.group) + links = info.hardlinks + if info.flags & UInt32(CURLFINFOFLAG_KNOWN_PERM) != 0 { + readable = info.perm & 0o400 != 0; writable = info.perm & 0o200 != 0 + } + modified = Self.date(Self.string(info.strings.time) ?? "") + } + + init?(facts response: String, path: String) { + guard let line = response.components(separatedBy: .newlines).map({ $0.trimmingCharacters(in: .whitespacesAndNewlines) }).first(where: { $0.lowercased().hasPrefix("type=") || $0.lowercased().contains(";type=") }), + let separator = line.firstIndex(of: " ") else { return nil } + let facts = Dictionary(line[..<separator].split(separator: ";").compactMap { part -> (String, String)? in + let pair = part.split(separator: "=", maxSplits: 1) + return pair.count == 2 ? (pair[0].lowercased(), String(pair[1])) : nil + }, uniquingKeysWith: { _, last in last }) + name = (path as NSString).lastPathComponent + let type = facts["type"]?.lowercased() ?? "" + directory = ["dir", "cdir", "pdir"].contains(type); file = type == "file" + if type.hasPrefix("os.unix=slink") { link = facts["type"]?.split(separator: ":", maxSplits: 1).dropFirst().first.map(String.init) ?? "" } + size = Int64(facts["size"] ?? "") ?? 0 + user = facts["unix.owner"] ?? facts["unix.uid"]; group = facts["unix.group"] ?? facts["unix.gid"] + links = Int(facts["unix.nlink"] ?? "") ?? 0 + if let permissions = facts["perm"] { + readable = permissions.contains(directory ? "l" : "r") + writable = permissions.contains(directory ? "c" : "w") || permissions.contains("a") + } + if let mode = facts["unix.mode"], let bits = UInt32(mode, radix: 8) { readable = bits & 0o400 != 0; writable = bits & 0o200 != 0 } + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX"); formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyyMMddHHmmss" + if let timestamp = facts["modify"], let date = formatter.date(from: String(timestamp.prefix(14))) { modified = date.timeIntervalSince1970 * 1000 } + } + + func json(path: String, target: FTPEntry? = nil) -> [String: Any] { + ["name": name, "length": size, "url": path, "isFile": target?.file ?? file, + "isDirectory": target?.directory ?? directory, "isLink": link != nil, "link": link as Any? ?? NSNull(), + "isValid": true, "isUnknown": !file && !directory && link == nil, "linkCount": links, + "user": user as Any? ?? NSNull(), "group": group as Any? ?? NSNull(), + "canRead": readable, "canWrite": writable, "lastModified": modified] + } + + private static func string(_ pointer: UnsafeMutablePointer<CChar>?) -> String? { pointer.map { String(cString: $0) } } + + private static func date(_ value: String) -> Double { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + let normalized = value.split(whereSeparator: { $0.isWhitespace }).joined(separator: " ") + let recent = normalized.contains(":") && !normalized.contains("-") + let year = Calendar.current.component(.year, from: Date()) + let input = recent ? "\(year) " + normalized : normalized + for format in recent ? ["yyyy MMM d HH:mm", "yyyy MMM d HH:mm:ss"] : ["MMM d yyyy", "MM-dd-yy hh:mma", "MM-dd-yyyy hh:mma"] { + formatter.dateFormat = format + if var date = formatter.date(from: input) { + if recent && date.timeIntervalSinceNow > 86400 { date = Calendar.current.date(byAdding: .year, value: -1, to: date) ?? date } + return date.timeIntervalSince1970 * 1000 + } + } + return 0 + } +} diff --git a/platforms/ios/runner/lib/ftp/FTPFiles.swift b/platforms/ios/runner/lib/ftp/FTPFiles.swift new file mode 100644 index 0000000000..8655aadce3 --- /dev/null +++ b/platforms/ios/runner/lib/ftp/FTPFiles.swift @@ -0,0 +1,70 @@ +import Foundation + +extension FTPClient { + func entries(_ remote: String) throws -> [FTPEntry] { + let directory = try path(remote) + return try perform(directory == "/" ? "/*" : directory + "/*", listing: true).entries + } + + func list(_ remote: String) throws -> [[String: Any]] { + let parent = try path(remote) + return try entries(parent).filter { ![".", ".."].contains($0.name) }.map { entry in + let child = try path(parent + "/" + entry.name) + if let link = entry.link { + let target = try path(link.hasPrefix("/") ? link : parent + "/" + link) + if let metadata = try? stat(target) { return entry.json(path: target, target: metadata) } + return entry.json(path: child) + } + return entry.json(path: child) + } + } + + func stat(_ remote: String) throws -> FTPEntry { + let target = try path(remote) + let parent = (target as NSString).deletingLastPathComponent + if target != "/", let listing = try? entries(parent), let entry = listing.first(where: { $0.name == (target as NSString).lastPathComponent }) { return entry } + let response = try command("MLST " + target, allowFailure: true) + if response.hasPrefix("250"), let entry = FTPEntry(facts: response, path: target) { return entry } + if response.hasPrefix("550") { throw FTPFailure("File not found.", replyCode: 550) } + if target == "/", let entry = try entries(target).first(where: { $0.name == "." }) { return entry } + throw FTPFailure("File not found.", replyCode: 550) + } + + func removeDirectory(_ remote: String, depth: Int = 0) throws { + guard depth < 128 else { throw FTPFailure("FTP directory nesting is too deep") } + let parent = try path(remote) + guard parent != "/" else { throw FTPFailure("Cannot delete the FTP root") } + for entry in try entries(parent) where ![".", ".."].contains(entry.name) { + let child = try path(parent + "/" + entry.name) + if entry.directory && entry.link == nil { try removeDirectory(child, depth: depth + 1) } + else { try command("DELE " + child) } + } + try command("RMD " + parent) + } + + func rename(_ remote: String, to destination: String) throws { + try perform(directory + "/", commands: ["RNFR " + path(remote), "RNTO " + path(destination)]) + } + + func download(_ remote: String, to local: String) throws { + let url = try AppFiles.shared.resolve(local) + try AppFiles.shared.coordinate(url, writing: true) { url in + guard FileManager.default.fileExists(atPath: url.path) || FileManager.default.createFile(atPath: url.path, contents: nil) else { throw FileFailure(6) } + let output = try FileHandle(forWritingTo: url) + defer { try? output.close() } + try output.truncate(atOffset: 0) + let request = FTPRequest(cancellation); request.output = output + try perform(path(remote), request: request) + } + } + + func upload(_ local: String, to remote: String) throws { + let url = try AppFiles.shared.resolve(local) + try AppFiles.shared.coordinate(url) { url in + let input = try FileHandle(forReadingFrom: url) + defer { try? input.close() } + let request = FTPRequest(cancellation); request.input = input + try perform(path(remote), upload: true, request: request) + } + } +} diff --git a/platforms/ios/runner/lib/ftp/FTPProfile.swift b/platforms/ios/runner/lib/ftp/FTPProfile.swift new file mode 100644 index 0000000000..97c4d0af99 --- /dev/null +++ b/platforms/ios/runner/lib/ftp/FTPProfile.swift @@ -0,0 +1,56 @@ +import Foundation + +struct FTPProfile: Equatable { + let host: String + let port: Int + let username: String + let password: String + let active: Bool + let secure: Bool + var id: String { "\(username)@\(host):\(port)" } + + init(_ args: [Any]) throws { + host = args[safe: 0] as? String ?? "" + port = args[safe: 1] as? Int ?? 21 + username = args[safe: 2] as? String ?? "" + password = args[safe: 3] as? String ?? "" + let mode = args[safe: 4] as? String ?? "passive" + let security = args[safe: 5] as? String ?? "ftp" + active = mode == "active" + secure = security == "ftps" + guard !host.isEmpty, (1...65535).contains(port), ["active", "passive"].contains(mode), ["ftp", "ftps"].contains(security) else { + throw FTPFailure("Invalid FTP connection options") + } + try Self.validate(host); try Self.validate(username); try Self.validate(password) + } + + func url(_ path: String) throws -> String { + var url = URLComponents() + url.scheme = secure && port == 990 ? "ftps" : "ftp" + url.host = host; url.port = port + let allowed = CharacterSet(charactersIn: "/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") + guard let encoded = path.addingPercentEncoding(withAllowedCharacters: allowed) else { throw FTPFailure("Invalid FTP path") } + url.percentEncodedPath = "/" + encoded + guard let result = url.url else { throw FTPFailure("Invalid FTP host") } + return result.absoluteString + } + + static func validate(_ value: String) throws { + guard !value.contains("\0"), !value.contains("\r"), !value.contains("\n") else { throw FTPFailure("FTP commands and paths cannot contain line breaks or NUL") } + } +} + +struct FTPFailure: LocalizedError { + let message: String + let replyCode: Int + var errorDescription: String? { message } + init(_ message: String, replyCode: Int = 0) { self.message = message; self.replyCode = replyCode } +} + +final class FTPCancellation { + private let lock = NSLock() + private var stopped = false + var cancelled: Bool { lock.lock(); defer { lock.unlock() }; return stopped } + func cancel() { lock.lock(); stopped = true; lock.unlock() } + func check() throws { if cancelled { throw FTPFailure("FTP operation cancelled") } } +} diff --git a/platforms/ios/runner/lib/ftp/FTPRequest.swift b/platforms/ios/runner/lib/ftp/FTPRequest.swift new file mode 100644 index 0000000000..ee83de5747 --- /dev/null +++ b/platforms/ios/runner/lib/ftp/FTPRequest.swift @@ -0,0 +1,66 @@ +import Foundation +import AcodeCurl + +final class FTPRequest { + let cancellation: FTPCancellation + var entries: [FTPEntry] = [] + var replies: [String: String] = [:] + var replyCodes: [String: Int] = [:] + var input: FileHandle? + var output: FileHandle? + var error: Error? + private var verb = "" + private var pending = Data() + private var response = "" + private var multiline: String? + + init(_ cancellation: FTPCancellation) { self.cancellation = cancellation } + + func trace(_ type: curl_infotype, bytes: UnsafeMutablePointer<CChar>, count: Int) { + guard type == CURLINFO_HEADER_IN || type == CURLINFO_HEADER_OUT else { return } + let text = String(decoding: UnsafeRawBufferPointer(start: bytes, count: count), as: UTF8.self) + if type == CURLINFO_HEADER_OUT { + verb = String(text.prefix { !$0.isWhitespace }).uppercased() + response = ""; multiline = nil + return + } + guard verb != "USER", verb != "PASS" else { return } + pending.append(UnsafeBufferPointer(start: UnsafeRawPointer(bytes).assumingMemoryBound(to: UInt8.self), count: count)) + guard pending.count + response.utf8.count <= 1_048_576 else { error = FTPFailure("FTP reply is too large"); return } + while let newline = pending.firstIndex(of: 10) { + let end = pending.index(after: newline) + let line = String(decoding: pending[..<end], as: UTF8.self) + pending.removeSubrange(..<end) + response += line + let prefix = String(line.prefix(3)) + if Int(prefix) != nil, line.count >= 4 { + let marker = line[line.index(line.startIndex, offsetBy: 3)] + if multiline == nil && marker == "-" { multiline = prefix } + if marker == " " && (multiline == nil || multiline == prefix) { replies[verb] = response; replyCodes[verb] = Int(prefix); multiline = nil } + } + } + } +} + +func ftpRequest(_ pointer: UnsafeMutableRawPointer?) -> FTPRequest { + Unmanaged<FTPRequest>.fromOpaque(pointer!).takeUnretainedValue() +} + +func ftpWrite(_ bytes: UnsafeMutablePointer<CChar>?, _ size: Int, _ count: Int, _ context: UnsafeMutableRawPointer?) -> Int { + let request = ftpRequest(context) + do { + try request.cancellation.check() + if let output = request.output, let bytes { try output.write(contentsOf: Data(bytes: bytes, count: size * count)) } + return size * count + } catch { request.error = error; return 0 } +} + +func ftpRead(_ bytes: UnsafeMutablePointer<CChar>?, _ size: Int, _ count: Int, _ context: UnsafeMutableRawPointer?) -> Int { + let request = ftpRequest(context) + do { + try request.cancellation.check() + guard let input = request.input, let bytes, let data = try input.read(upToCount: min(size * count, 65536)) else { return 0 } + data.copyBytes(to: UnsafeMutableRawBufferPointer(start: bytes, count: data.count)) + return data.count + } catch { request.error = error; return Int(CURL_READFUNC_ABORT) } +} diff --git a/platforms/ios/runner/lib/ftp/FTPService.swift b/platforms/ios/runner/lib/ftp/FTPService.swift new file mode 100644 index 0000000000..41e6df9d20 --- /dev/null +++ b/platforms/ios/runner/lib/ftp/FTPService.swift @@ -0,0 +1,84 @@ +import Foundation + +final class FTPService: BaseService { + private let control = DispatchQueue(label: "app.acode.ftp.control") + private var clients: [String: FTPClient] = [:] + + override func exec(action: String, args: [Any], callback: Callback) { + control.async { + do { + if action == "connect" { try self.connect(args, callback: callback); return } + let id = args[safe: 0] as? String ?? "" + if action == "disconnect" { + let client = self.clients.removeValue(forKey: id) + client?.cancellation.cancel() + if let client { client.queue.async { callback.success() } } else { callback.success() } + return + } + guard let client = self.clients[id] else { throw FTPFailure("FTP client not found.") } + client.queue.async { + do { try self.perform(action, args: args, client: client, callback: callback) } + catch { callback.error(error.localizedDescription) } + } + } catch { callback.error(error.localizedDescription) } + } + } + + override func reset() { + control.async { + for client in self.clients.values { client.cancellation.cancel() } + self.clients.removeAll() + } + } + + private func connect(_ args: [Any], callback: Callback) throws { + let profile = try FTPProfile(args) + let client: FTPClient + if let existing = clients[profile.id], existing.profile == profile, !existing.cancellation.cancelled { client = existing } + else { + client = try FTPClient(profile) + clients.removeValue(forKey: profile.id)?.cancellation.cancel() + clients[profile.id] = client + } + client.queue.async { + do { try client.connect(); callback.success(profile.id) } + catch { + self.control.async { if self.clients[profile.id] === client { self.clients.removeValue(forKey: profile.id) } } + callback.error(error.localizedDescription) + } + } + } + + private func perform(_ action: String, args: [Any], client: FTPClient, callback: Callback) throws { + let value = args[safe: 1] as? String ?? "" + if action == "isConnected" { + callback.success((try? client.command("NOOP")) != nil ? 1 : 0) + return + } + try client.cancellation.check() + if ["downloadFile", "uploadFile", "createFile", "createDirectory", "deleteFile", "deleteDirectory", "rename", "changeDirectory", "getStat"].contains(action), value.isEmpty { + throw FTPFailure("Path is required.") + } + switch action { + case "listDirectory": callback.success(try client.list(value)) + case "getStat": callback.success(try client.stat(value).json(path: client.path(value))) + case "exists": + do { _ = try client.stat(value); callback.success(1) } + catch let error as FTPFailure where error.replyCode == 550 { callback.success(0) } + case "downloadFile": try client.download(value, to: args[safe: 2] as? String ?? ""); callback.success() + case "uploadFile": try client.upload(value, to: args[safe: 2] as? String ?? ""); callback.success() + case "createFile": try client.perform(client.path(value), upload: true); callback.success() + case "createDirectory": try client.command("MKD " + client.path(value)); callback.success() + case "deleteFile": try client.command("DELE " + client.path(value)); callback.success() + case "deleteDirectory": try client.removeDirectory(value); callback.success() + case "rename": try client.rename(value, to: args[safe: 2] as? String ?? ""); callback.success(args[safe: 2]) + case "changeDirectory": try client.command("CWD " + client.path(value)); callback.success() + case "changeToParentDirectory": try client.command("CDUP"); callback.success() + case "getWorkingDirectory": callback.success(client.directory) + case "getKeepAlive": callback.success(300) + case "sendNoOp": try client.command("NOOP"); callback.success() + case "execCommand": callback.success(try client.command(value, allowFailure: true)) + default: throw FTPFailure("FTP action is not available: " + action) + } + } +} diff --git a/platforms/ios/runner/lib/network/AppAPIHandler.swift b/platforms/ios/runner/lib/network/AppAPIHandler.swift new file mode 100644 index 0000000000..fa3dd39246 --- /dev/null +++ b/platforms/ios/runner/lib/network/AppAPIHandler.swift @@ -0,0 +1,106 @@ +import WebKit + +final class AppAPIHandler { + private let origin: URL + private let auth: AppAuthentication + private var requests: [ObjectIdentifier: HTTPTransport] = [:] + + init(origin: URL = URL(string: AppAuthentication.origin)!, auth: AppAuthentication = AppAuthentication()) { + self.origin = origin + self.auth = auth + } + + func start(_ task: WKURLSchemeTask) { + let id = ObjectIdentifier(task) + do { + let request = try request(for: task.request) + let source = task.request.url! + let url = request.url! + let credentials = task.request.value(forHTTPHeaderField: "X-Acode-Credentials") == "include" + let redirects = task.request.value(forHTTPHeaderField: "X-Acode-Redirect") ?? "follow" + let transport = HTTPTransport(request: request, followRedirects: redirects == "follow", connectTimeout: 30, readTimeout: 60, cookieStorage: .shared) + transport.allowRedirect = { next in next.scheme == url.scheme && next.host == url.host && next.port == url.port && next.user == nil && next.password == nil } + transport.onRedirect = { [auth] response, next in + Self.storeCookies(from: response, credentials: credentials) + try Self.applyCookies(to: &next, credentials: credentials, auth: auth) + } + transport.onResponse = { [weak self] response in + Self.storeCookies(from: response, credentials: credentials) + if redirects == "error", (300..<400).contains(response.statusCode) { throw URLError(.redirectToNonExistentLocation) } + var headers: [String: String] = [:] + for (key, value) in response.allHeaderFields { + let name = String(describing: key) + if !["set-cookie", "set-cookie2", "content-encoding", "content-length"].contains(name.lowercased()) { headers[name] = String(describing: value) } + } + headers["X-Acode-Response-URL"] = response.url?.absoluteString ?? url.absoluteString + // URLSession delivers decompressed bytes, so the original encoding and size no longer apply. + let result = HTTPURLResponse(url: source, statusCode: response.statusCode, httpVersion: "HTTP/1.1", headerFields: headers)! + DispatchQueue.main.async { [weak self] in if self?.requests[id] != nil { task.didReceive(result) } } + } + transport.onData = { [weak self] data in DispatchQueue.main.async { [weak self] in if self?.requests[id] != nil { task.didReceive(data) } } } + transport.onComplete = { [weak self] error in + DispatchQueue.main.async { [weak self] in + guard self?.requests.removeValue(forKey: id) != nil else { return } + if let error { task.didFailWithError(error) } + else { task.didFinish() } + } + } + requests[id] = transport + transport.start() + } catch { task.didFailWithError(error) } + } + + func stop(_ task: WKURLSchemeTask) { requests.removeValue(forKey: ObjectIdentifier(task))?.cancel() } + + func request(for incomingRequest: URLRequest) throws -> URLRequest { + guard let source = incomingRequest.url, source.scheme == "acode", source.host == "localhost", source.path.hasPrefix("/__api__/") else { throw URLError(.badURL) } + let origin = try incomingRequest.value(forHTTPHeaderField: "X-Acode-API-Origin").map(AppAuthentication.baseURL) ?? self.origin + var destination = URLComponents(url: origin, resolvingAgainstBaseURL: false)! + let incoming = URLComponents(url: source, resolvingAgainstBaseURL: false)! + destination.percentEncodedPath = "/api/" + incoming.percentEncodedPath.dropFirst("/__api__/".count) + destination.percentEncodedQuery = incoming.percentEncodedQuery + guard let url = destination.url else { throw URLError(.badURL) } + var request = incomingRequest + request.url = url + request.mainDocumentURL = origin + let credentials = request.value(forHTTPHeaderField: "X-Acode-Credentials") == "include" + for key in (request.allHTTPHeaderFields ?? [:]).keys where ["host", "origin", "referer", "cookie", "content-length"].contains(key.lowercased()) || key.lowercased().hasPrefix("x-acode-") || key.lowercased().hasPrefix("sec-") { + request.setValue(nil, forHTTPHeaderField: key) + } + request.setValue("https://localhost", forHTTPHeaderField: "Origin") + request.setValue("https://localhost/", forHTTPHeaderField: "Referer") + try Self.applyCookies(to: &request, credentials: credentials, auth: auth) + return request + } + + static func storeCookies(from response: HTTPURLResponse, credentials: Bool) { + guard credentials, let url = response.url, AppAuthentication.accepts(url), + let header = response.value(forHTTPHeaderField: "Set-Cookie") else { return } + let storage = HTTPCookieStorage.shared + guard storage.cookieAcceptPolicy != .never else { return } + for cookie in HTTPCookie.cookies(withResponseHeaderFields: ["Set-Cookie": header], for: url) where cookie.name != "token" { + let domain = cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: ".")) + guard AppAuthentication.hosts.contains(domain), url.host == domain || url.host!.hasSuffix("." + domain) else { continue } + // Foundation requires the stored HttpOnly object when replacing or deleting it. + for existing in storage.cookies ?? [] where existing.name == cookie.name && existing.domain == cookie.domain && existing.path == cookie.path { + storage.deleteCookie(existing) + } + if let expiry = cookie.expiresDate, expiry <= Date() { continue } + storage.setCookies([cookie], for: url, mainDocumentURL: url) + } + } + + private static func applyCookies(to request: inout URLRequest, credentials: Bool, auth: AppAuthentication) throws { + guard let url = request.url else { throw URLError(.badURL) } + let trusted = AppAuthentication.accepts(url) + request.httpShouldHandleCookies = credentials && !trusted + request.setValue(nil, forHTTPHeaderField: "Cookie") + if credentials, trusted { + // A parent-domain cookie must not override the token for the selected environment. + var cookies = (HTTPCookieStorage.shared.cookies(for: url) ?? []).filter { $0.name != "token" } + let token = try auth.token(for: url) + if !token.isEmpty, let cookie = HTTPCookie(properties: [.name: "token", .value: token, .domain: url.host!, .path: "/", .secure: "TRUE"]) { cookies.append(cookie) } + request.setValue(HTTPCookie.requestHeaderFields(with: cookies)["Cookie"], forHTTPHeaderField: "Cookie") + } + } +} diff --git a/platforms/ios/runner/lib/network/HTTPBody.swift b/platforms/ios/runner/lib/network/HTTPBody.swift new file mode 100644 index 0000000000..ab5d2d432d --- /dev/null +++ b/platforms/ios/runner/lib/network/HTTPBody.swift @@ -0,0 +1,63 @@ +import Foundation + +struct HTTPBody { + let data: Data + let type: String + + static func encode(_ value: Any?, serializer: String) throws -> HTTPBody { + let object = value as? [String: Any] ?? [:] + switch serializer { + case "json": + return HTTPBody(data: try JSONSerialization.data(withJSONObject: value ?? [:], options: [.fragmentsAllowed]), type: "application/json; charset=UTF-8") + case "utf8": return HTTPBody(data: Data((object["text"] as? String ?? "").utf8), type: "text/plain; charset=UTF-8") + case "raw": + guard let raw = value as? String, let data = Data(base64Encoded: raw) else { throw HTTPFailure(status: -1, message: "Invalid binary request body") } + return HTTPBody(data: data, type: "application/octet-stream") + case "urlencoded": + let body = object.sorted(by: { $0.key < $1.key }).map { "\(escape($0.key))=\(escape(String(describing: $0.value)))" }.joined(separator: "&") + return HTTPBody(data: Data(body.utf8), type: "application/x-www-form-urlencoded; charset=UTF-8") + case "multipart": + guard let buffers = object["buffers"] as? [String], let names = object["names"] as? [String], + let fileNames = object["fileNames"] as? [Any], let types = object["types"] as? [String], + buffers.count == names.count, names.count == fileNames.count, names.count == types.count else { + throw HTTPFailure(status: -1, message: "Invalid multipart body") + } + return try multipart(buffers.indices.map { index in + guard let data = Data(base64Encoded: buffers[index]) else { throw HTTPFailure(status: -1, message: "Invalid multipart data") } + return (names[index], fileNames[index] as? String, types[index], data) + }) + default: throw HTTPFailure(status: -1, message: "Unknown serializer: \(serializer)") + } + } + + static func files(paths: [String], names: [String]) throws -> HTTPBody { + guard !paths.isEmpty, names.count == paths.count else { throw HTTPFailure(status: -1, message: "File paths and field names must match") } + let files = AppFiles.shared + return try multipart(paths.indices.map { index in + let url = try files.resolve(paths[index]) + let data = try files.coordinate(url) { try Data(contentsOf: $0) } + return (names[index], url.lastPathComponent, files.mimeType(url), data) + }) + } + + private static func multipart(_ parts: [(String, String?, String, Data)]) -> HTTPBody { + let boundary = "Acode-" + UUID().uuidString + var data = Data() + for (name, filename, type, bytes) in parts { + var header = "--\(boundary)\r\nContent-Disposition: form-data; name=\"\(quote(name))\"" + if let filename { header += "; filename=\"\(quote(filename))\"" } + header += "\r\nContent-Type: \(type.replacingOccurrences(of: "\r", with: "").replacingOccurrences(of: "\n", with: ""))\r\n\r\n" + data.append(Data(header.utf8)); data.append(bytes); data.append(Data("\r\n".utf8)) + } + data.append(Data("--\(boundary)--\r\n".utf8)) + return HTTPBody(data: data, type: "multipart/form-data; boundary=\(boundary)") + } + + private static func quote(_ value: String) -> String { + value.replacingOccurrences(of: "\r", with: "%0D").replacingOccurrences(of: "\n", with: "%0A").replacingOccurrences(of: "\"", with: "%22") + } + + private static func escape(_ value: String) -> String { + value.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")) ?? "" + } +} diff --git a/platforms/ios/runner/lib/network/HTTPRequest.swift b/platforms/ios/runner/lib/network/HTTPRequest.swift new file mode 100644 index 0000000000..065f467924 --- /dev/null +++ b/platforms/ios/runner/lib/network/HTTPRequest.swift @@ -0,0 +1,68 @@ +import Foundation + +struct HTTPRequest { + let id: Int + var request: URLRequest + let followRedirects: Bool + let responseType: String + let destination: URL? + let connectTimeout: TimeInterval + let readTimeout: TimeInterval + + init(action: String, args: [Any]) throws { + guard let address = args[safe: 0] as? String, let url = URL(string: address), + ["http", "https"].contains(url.scheme?.lowercased() ?? ""), url.host != nil else { + throw HTTPFailure(status: -5, message: "Expected an HTTP or HTTPS URL") + } + let hasBody = ["post", "put", "patch"].contains(action) + let upload = action == "uploadFiles" + let download = action == "downloadFile" + guard hasBody || upload || download || ["get", "head", "delete", "options"].contains(action) else { + throw HTTPFailure(status: -1, message: "Unknown HTTP action: \(action)") + } + let offset = hasBody || upload ? 4 : download ? 3 : 2 + guard let id = args[safe: download ? 6 : offset + 4] as? Int else { + throw HTTPFailure(status: -1, message: "Request ID is required") + } + self.id = id + connectTimeout = args[safe: offset] as? Double ?? 60 + readTimeout = args[safe: offset + 1] as? Double ?? 60 + followRedirects = args[safe: offset + 2] as? Bool ?? true + responseType = download ? "text" : args[safe: offset + 3] as? String ?? "text" + destination = download ? try AppFiles.shared.resolve(args[safe: 2] as? String ?? "") : nil + request = URLRequest(url: url) + request.httpMethod = upload ? "POST" : download ? "GET" : action.uppercased() + request.allHTTPHeaderFields = args[safe: hasBody ? 3 : 1] as? [String: String] ?? [:] + request.httpShouldHandleCookies = false + if hasBody { + let body = try HTTPBody.encode(args[safe: 1], serializer: args[safe: 2] as? String ?? "urlencoded") + request.httpBody = body.data + if request.value(forHTTPHeaderField: "Content-Type") == nil { request.setValue(body.type, forHTTPHeaderField: "Content-Type") } + } else if upload { + let body = try HTTPBody.files(paths: args[safe: 2] as? [String] ?? [], names: args[safe: 3] as? [String] ?? []) + request.httpBody = body.data + request.setValue(body.type, forHTTPHeaderField: "Content-Type") + } + } +} + +struct HTTPFailure: LocalizedError { + let status: Int + let message: String + var errorDescription: String? { message } + static func status(_ error: Error) -> Int { + if let failure = error as? HTTPFailure { return failure.status } + switch (error as NSError).code { + case NSURLErrorCancelled: return -8 + case NSURLErrorTimedOut: return -4 + case NSURLErrorCannotFindHost, NSURLErrorDNSLookupFailed: return -3 + case NSURLErrorNotConnectedToInternet: return -6 + case NSURLErrorUnsupportedURL, NSURLErrorBadURL: return -5 + case NSURLErrorSecureConnectionFailed, NSURLErrorServerCertificateUntrusted, + NSURLErrorServerCertificateHasBadDate, NSURLErrorServerCertificateHasUnknownRoot, + NSURLErrorServerCertificateNotYetValid, NSURLErrorClientCertificateRejected, + NSURLErrorClientCertificateRequired: return -2 + default: return -1 + } + } +} diff --git a/platforms/ios/runner/lib/network/HTTPStreamService.swift b/platforms/ios/runner/lib/network/HTTPStreamService.swift new file mode 100644 index 0000000000..cb0548c042 --- /dev/null +++ b/platforms/ios/runner/lib/network/HTTPStreamService.swift @@ -0,0 +1,116 @@ +import Foundation + +final class HTTPStreamService { + private let queue = DispatchQueue(label: "app.acode.http.streams") + private var streams: [String: HTTPStream] = [:] + + func reset() { + queue.async { + self.streams.values.forEach { $0.cancel() } + self.streams.removeAll() + } + } + + func exec(action: String, args: [Any], callback: Callback) { + queue.async { [self] in + let id = args[safe: 0] as? String ?? "" + do { + switch action { + case "http-stream-start": + guard !id.isEmpty, self.streams[id] == nil else { throw HTTPFailure(status: -1, message: "Invalid stream ID") } + let stream = try HTTPStream(args: args, callback: callback) { [weak self] finished in + self?.queue.async { + if self?.streams[id] === finished { self?.streams.removeValue(forKey: id) } + } + } + self.streams[id] = stream + stream.transport.start() + case "http-stream-cancel": self.streams[id]?.cancel(); callback.success() + case "http-stream-ack": self.streams[id]?.acknowledge(args[safe: 1] as? Int ?? 0); callback.success() + default: callback.error("Unknown HTTP stream action") + } + } catch { callback.error(error.localizedDescription) } + } + } +} + +private final class HTTPStream { + let transport: HTTPTransport + private let callback: Callback + private let chunkSize: Int + private let onFinish: (HTTPStream) -> Void + private var pending = Data() + private var outstanding = 0 + private var complete = false + private var finished = false + + init(args: [Any], callback: Callback, onFinish: @escaping (HTTPStream) -> Void) throws { + guard let address = args[safe: 1] as? String, let url = URL(string: address), + ["http", "https"].contains(url.scheme?.lowercased() ?? ""), url.host != nil else { throw HTTPFailure(status: -5, message: "Expected an HTTP or HTTPS URL") } + let options = args[safe: 2] as? [String: Any] ?? [:] + var request = URLRequest(url: url) + request.httpMethod = (options["method"] as? String ?? "GET").uppercased() + request.allHTTPHeaderFields = options["headers"] as? [String: String] ?? [:] + request.httpShouldHandleCookies = false + if let body = options["body"] as? String { + if options["bodyIsBase64"] as? Bool == true { + guard let data = Data(base64Encoded: body) else { throw HTTPFailure(status: -1, message: "Invalid stream body") } + request.httpBody = data + } else { request.httpBody = Data(body.utf8) } + } + chunkSize = max(1024, min(65536, options["chunkSize"] as? Int ?? 32768)) + self.callback = callback + self.onFinish = onFinish + transport = HTTPTransport(request: request, followRedirects: options["followRedirects"] as? Bool ?? true, + connectTimeout: (options["connectTimeout"] as? Double ?? 30000) / 1000, + readTimeout: (options["readTimeout"] as? Double ?? 0) / 1000) + transport.onResponse = { response in + callback.success(["type": "headers", "status": response.statusCode, "statusText": HTTPURLResponse.localizedString(forStatusCode: response.statusCode), + "url": response.url?.absoluteString ?? address, + "headers": response.allHeaderFields.map { [String(describing: $0.key), String(describing: $0.value)] }], keep: true) + } + transport.onData = { [weak self] data in self?.pending.append(data); self?.drain() } + transport.onComplete = { [weak self] error in + guard let self, !self.finished else { return } + if let error { self.finish(error) } + else { self.complete = true; self.drain() } + } + } + + func acknowledge(_ bytes: Int) { + transport.queue.async { + guard bytes > 0, !self.finished else { return } + self.outstanding -= min(bytes, self.outstanding) + self.drain() + } + } + + func cancel() { + transport.queue.async { + self.finish(URLError(.cancelled)) + self.transport.cancel() + } + } + + private func drain() { + guard !finished else { return } + while !pending.isEmpty, outstanding < 65536 { + let count = min(chunkSize, min(pending.count, 65536 - outstanding)) + let chunk = pending.prefix(count) + callback.success(["type": "data", "chunk": chunk.base64EncodedString(), "b64": true], keep: true) + outstanding += count + pending.removeFirst(count) + } + transport.setPaused(outstanding >= 65536) + if complete, pending.isEmpty { finish(nil) } + } + + private func finish(_ error: Error?) { + guard !finished else { return } + finished = true + pending.removeAll() + if let error { callback.success(["type": "error", "message": error.localizedDescription]) } + else { callback.success(["type": "complete"]) } + onFinish(self) + } +} diff --git a/platforms/ios/runner/lib/network/HTTPTransport.swift b/platforms/ios/runner/lib/network/HTTPTransport.swift new file mode 100644 index 0000000000..474f638a75 --- /dev/null +++ b/platforms/ios/runner/lib/network/HTTPTransport.swift @@ -0,0 +1,132 @@ +import Foundation + +final class HTTPTransport: NSObject, URLSessionDataDelegate, @unchecked Sendable { + let queue = DispatchQueue(label: "app.acode.http." + UUID().uuidString) + var onResponse: (HTTPURLResponse) throws -> Void = { _ in } + var onData: (Data) throws -> Void = { _ in } + var onComplete: (Error?) -> Void = { _ in } + var allowRedirect: (URL) -> Bool = { _ in true } + var onRedirect: (HTTPURLResponse, inout URLRequest) throws -> Void = { _, _ in } + private let request: URLRequest + private let followRedirects: Bool + private let connectTimeout: TimeInterval + private let readTimeout: TimeInterval + private let trust: HTTPTrust + private let cookieStorage: HTTPCookieStorage? + private var session: URLSession? + private var task: URLSessionDataTask? + private var timer: DispatchSourceTimer? + private var failure: Error? + private var paused = false + private var finished = false + + init(request: URLRequest, followRedirects: Bool, connectTimeout: TimeInterval, readTimeout: TimeInterval, trust: HTTPTrust = HTTPTrust(), cookieStorage: HTTPCookieStorage? = nil) { + self.request = request + self.followRedirects = followRedirects + self.connectTimeout = connectTimeout + self.readTimeout = readTimeout + self.trust = trust + self.cookieStorage = cookieStorage + } + + func start() { + queue.async { + guard !self.finished else { return } + let configuration = URLSessionConfiguration.ephemeral + configuration.httpCookieStorage = self.cookieStorage + configuration.urlCache = nil + configuration.timeoutIntervalForRequest = 31536000 + configuration.timeoutIntervalForResource = 31536000 + let delegates = OperationQueue() + delegates.maxConcurrentOperationCount = 1 + delegates.underlyingQueue = self.queue + let session = URLSession(configuration: configuration, delegate: self, delegateQueue: delegates) + self.session = session + self.task = session.dataTask(with: self.request) + self.resetTimeout(self.connectTimeout) + self.task?.resume() + } + } + + func cancel() { + queue.async { + self.failure = URLError(.cancelled) + if let task = self.task { task.cancel() } + else { self.finish(self.failure) } + } + } + + func setPaused(_ value: Bool) { + guard value != paused, !finished else { return } + paused = value + if value { task?.suspend(); resetTimeout(0) } + else { resetTimeout(readTimeout); task?.resume() } + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + do { + if let failure { throw failure } + guard let response = response as? HTTPURLResponse else { throw HTTPFailure(status: -1, message: "Invalid HTTP response") } + resetTimeout(readTimeout) + try onResponse(response) + completionHandler(.allow) + } catch { failure = error; completionHandler(.cancel) } + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + guard failure == nil, !finished else { return } + do { resetTimeout(paused ? 0 : readTimeout); try onData(data) } + catch { failure = error; dataTask.cancel() } + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + finish(failure ?? error) + } + + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { + if followRedirects, let url = request.url, !allowRedirect(url) { + failure = URLError(.redirectToNonExistentLocation) + completionHandler(nil); return + } + var redirect = request + if followRedirects { + do { try onRedirect(response, &redirect) } + catch { failure = error; completionHandler(nil); return } + } + if request.url?.host != task.currentRequest?.url?.host || request.url?.scheme != task.currentRequest?.url?.scheme || request.url?.port != task.currentRequest?.url?.port { + for header in ["Authorization", "Cookie", "Proxy-Authorization"] { redirect.setValue(nil, forHTTPHeaderField: header) } + } + completionHandler(followRedirects ? redirect : nil) + } + + func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + trust.respond(challenge, completion: completionHandler) + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + trust.respond(challenge, completion: completionHandler) + } + + private func resetTimeout(_ seconds: TimeInterval) { + timer?.cancel(); timer = nil + guard seconds > 0 else { return } + let timer = DispatchSource.makeTimerSource(queue: queue) + timer.schedule(deadline: .now() + seconds) + timer.setEventHandler { [weak self] in + self?.failure = URLError(.timedOut) + self?.task?.cancel() + } + self.timer = timer + timer.resume() + } + + private func finish(_ error: Error?) { + guard !finished else { return } + finished = true + resetTimeout(0) + onComplete(error) + session?.finishTasksAndInvalidate() + session = nil; task = nil + onResponse = { _ in }; onData = { _ in }; onComplete = { _ in }; onRedirect = { _, _ in } + } +} diff --git a/platforms/ios/runner/lib/network/HTTPTrust.swift b/platforms/ios/runner/lib/network/HTTPTrust.swift new file mode 100644 index 0000000000..cc7425d92f --- /dev/null +++ b/platforms/ios/runner/lib/network/HTTPTrust.swift @@ -0,0 +1,61 @@ +import Foundation +import Security + +struct HTTPTrust { + var mode = "default" + var certificates: [SecCertificate] = [] + var credential: URLCredential? + + mutating func configureServer(_ mode: String) throws { + guard ["default", "legacy", "nocheck", "pinned"].contains(mode) else { throw HTTPFailure(status: -2, message: "Unknown server trust mode") } + var anchors: [SecCertificate] = [] + if mode == "pinned" { + let directory = Bundle.main.bundleURL.appendingPathComponent("bundle/certificates") + for url in (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? [] where ["cer", "der"].contains(url.pathExtension.lowercased()) { + if let certificate = SecCertificateCreateWithData(nil, try Data(contentsOf: url) as CFData) { anchors.append(certificate) } + } + guard !anchors.isEmpty else { throw HTTPFailure(status: -2, message: "No pinned certificates in bundle/certificates") } + } + self.mode = mode + certificates = anchors + } + + mutating func configureClient(_ args: [Any]) throws { + let mode = args[safe: 0] as? String ?? "none" + if mode == "none" { credential = nil; return } + let identity: SecIdentity + var chain: [SecCertificate]? + if mode == "buffer" { + guard let encoded = args[safe: 2] as? String, let data = Data(base64Encoded: encoded) else { throw HTTPFailure(status: -2, message: "Invalid PKCS12 buffer") } + var imported: CFArray? + let status = SecPKCS12Import(data as CFData, [kSecImportExportPassphrase: args[safe: 3] as? String ?? ""] as CFDictionary, &imported) + guard status == errSecSuccess, let item = (imported as? [[String: Any]])?.first, + let value = item[kSecImportItemIdentity as String] else { throw HTTPFailure(status: -2, message: "Cannot import client certificate (\(status))") } + identity = value as! SecIdentity + chain = item[kSecImportItemCertChain as String] as? [SecCertificate] + } else if mode == "systemstore" { + var query: [String: Any] = [kSecClass as String: kSecClassIdentity, kSecReturnRef as String: true, kSecMatchLimit as String: kSecMatchLimitOne] + if let alias = args[safe: 1] as? String { query[kSecAttrLabel as String] = alias } + var value: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &value) + guard status == errSecSuccess, let value else { throw HTTPFailure(status: -2, message: "Client identity is unavailable in this app's Keychain") } + identity = value as! SecIdentity + } else { throw HTTPFailure(status: -2, message: "Unknown client authentication mode") } + credential = URLCredential(identity: identity, certificates: chain, persistence: .forSession) + } + + func respond(_ challenge: URLAuthenticationChallenge, completion: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + guard challenge.previousFailureCount == 0 else { completion(.cancelAuthenticationChallenge, nil); return } + let method = challenge.protectionSpace.authenticationMethod + if method == NSURLAuthenticationMethodClientCertificate { + completion(credential == nil ? .performDefaultHandling : .useCredential, credential) + } else if method == NSURLAuthenticationMethodServerTrust, let trust = challenge.protectionSpace.serverTrust { + if mode == "nocheck" { completion(.useCredential, URLCredential(trust: trust)) } + else if mode == "pinned" { + SecTrustSetAnchorCertificates(trust, certificates as CFArray) + SecTrustSetAnchorCertificatesOnly(trust, true) + completion(SecTrustEvaluateWithError(trust, nil) ? .useCredential : .cancelAuthenticationChallenge, URLCredential(trust: trust)) + } else { completion(.performDefaultHandling, nil) } + } else { completion(.performDefaultHandling, nil) } + } +} diff --git a/platforms/ios/runner/lib/network/NativeHTTPService.swift b/platforms/ios/runner/lib/network/NativeHTTPService.swift new file mode 100644 index 0000000000..7429374e72 --- /dev/null +++ b/platforms/ios/runner/lib/network/NativeHTTPService.swift @@ -0,0 +1,109 @@ +import Foundation + +final class NativeHTTPService: BaseService { + private let queue = DispatchQueue(label: "app.acode.http.requests") + private var requests: [Int: HTTPTransport] = [:] + private var trust = HTTPTrust() + + override func reset() { + queue.async { + self.requests.values.forEach { $0.cancel() } + self.requests.removeAll() + self.trust = HTTPTrust() + } + } + + override func exec(action: String, args: [Any], callback: Callback) { + queue.async { [self] in + do { + switch action { + case "setServerTrustMode": + try self.trust.configureServer(args[safe: 0] as? String ?? "default") + callback.success() + case "setClientAuthMode": try self.trust.configureClient(args); callback.success() + case "abort": + let request = self.requests[args[safe: 0] as? Int ?? -1] + request?.cancel() + callback.success(["aborted": request != nil]) + default: + let spec = try HTTPRequest(action: action, args: args) + guard self.requests[spec.id] == nil else { throw HTTPFailure(status: -1, message: "Duplicate request ID") } + let result = HTTPResult(spec: spec, callback: callback) + let transport = HTTPTransport(request: spec.request, followRedirects: spec.followRedirects, connectTimeout: spec.connectTimeout, readTimeout: spec.readTimeout, trust: self.trust) + transport.onResponse = { try result.receive($0) } + transport.onData = { try result.receive($0) } + transport.onComplete = { [weak self, weak transport] error in + result.finish(error) + guard let transport else { return } + self?.queue.async { + if self?.requests[spec.id] === transport { self?.requests.removeValue(forKey: spec.id) } + } + } + self.requests[spec.id] = transport + transport.start() + } + } catch { callback.error(["status": HTTPFailure.status(error), "url": args[safe: 0] as? String ?? "", "headers": [:], "error": error.localizedDescription]) } + } + } +} + +private final class HTTPResult { + let spec: HTTPRequest + let callback: Callback + var response: HTTPURLResponse? + var data = Data() + var output: FileHandle? + var temporary: URL? + + init(spec: HTTPRequest, callback: Callback) { self.spec = spec; self.callback = callback } + + func receive(_ response: HTTPURLResponse) throws { + self.response = response + if let destination = spec.destination, (200..<300).contains(response.statusCode) { + let temporary = destination.deletingLastPathComponent().appendingPathComponent(".acode-download-" + UUID().uuidString) + try Data().write(to: temporary, options: .withoutOverwriting) + self.temporary = temporary + output = try FileHandle(forWritingTo: temporary) + } + } + + func receive(_ bytes: Data) throws { + if let output { try output.write(contentsOf: bytes) } + else { data.append(bytes) } + } + + func finish(_ failure: Error?) { + var result: [String: Any] = ["url": response?.url?.absoluteString ?? spec.request.url!.absoluteString, "status": response?.statusCode ?? -1, "headers": headers()] + defer { if let temporary { try? FileManager.default.removeItem(at: temporary) } } + do { + try output?.close(); output = nil + if let failure { throw failure } + guard let response else { throw HTTPFailure(status: -1, message: "Missing HTTP response") } + if !(200..<300).contains(response.statusCode) { + result["error"] = text(); callback.error(result); return + } + if let destination = spec.destination, let temporary { + let files = AppFiles.shared + try files.coordinate(destination, writing: true) { target in + if files.manager.fileExists(atPath: target.path) { _ = try files.manager.replaceItemAt(target, withItemAt: temporary) } + else { try files.manager.moveItem(at: temporary, to: target) } + } + result["file"] = try files.entry(destination) + } else { result["data"] = ["arraybuffer", "blob"].contains(spec.responseType) ? data.base64EncodedString() : text() } + callback.success(result) + } catch { + result["status"] = HTTPFailure.status(error) + result["error"] = error.localizedDescription + callback.error(result) + } + } + + private func headers() -> [String: String] { + Dictionary((response?.allHeaderFields ?? [:]).map { (String(describing: $0.key).lowercased(), String(describing: $0.value)) }, uniquingKeysWith: { first, second in first + ", " + second }) + } + + private func text() -> String { + let encoding = try? FileContents.encoding(response?.textEncodingName ?? "UTF-8") + return String(data: data, encoding: encoding ?? .utf8) ?? String(decoding: data, as: UTF8.self) + } +} diff --git a/platforms/ios/runner/lib/network/WebSocketService.swift b/platforms/ios/runner/lib/network/WebSocketService.swift new file mode 100644 index 0000000000..cce70e694a --- /dev/null +++ b/platforms/ios/runner/lib/network/WebSocketService.swift @@ -0,0 +1,150 @@ +import Foundation + +final class WebSocketService: BaseService { + private let queue = DispatchQueue(label: "app.acode.websockets") + private var sockets: [String: NativeSocket] = [:] + + override func reset() { + queue.async { + self.sockets.values.forEach { $0.stop() } + self.sockets.removeAll() + } + } + + override func exec(action: String, args: [Any], callback: Callback) { + queue.async { [self] in + do { + if action == "connect" { + let id = UUID().uuidString + let socket = try NativeSocket(args: args, queue: self.queue) { [weak self] in self?.sockets.removeValue(forKey: id) } + self.sockets[id] = socket + callback.success(id) + socket.task.resume() + return + } + if action == "listClients" { callback.success(Array(self.sockets.keys)); return } + guard let id = args[safe: 0] as? String, let socket = self.sockets[id] else { throw HTTPFailure(status: -1, message: "Invalid socket ID") } + switch action { + case "registerListener": socket.listen(callback) + case "setBinaryType": socket.binaryType = args[safe: 1] as? String ?? ""; callback.success() + case "send": + let text = args[safe: 1] as? String ?? "" + let message: URLSessionWebSocketTask.Message + if args[safe: 2] as? Bool == true { + guard let data = Data(base64Encoded: text) else { throw HTTPFailure(status: -1, message: "Invalid socket binary data") } + message = .data(data) + } else { message = .string(text) } + socket.task.send(message) { error in + if let error { callback.error(error.localizedDescription) } + else { callback.success() } + } + case "close": + let code = args[safe: 1] as? Int ?? 1000 + guard let closeCode = URLSessionWebSocketTask.CloseCode(rawValue: code), code == 1000 || (3000...4999).contains(code) else { throw HTTPFailure(status: -1, message: "Invalid socket close code") } + let reason = Data((args[safe: 2] as? String ?? "Normal closure").utf8) + guard reason.count <= 123 else { throw HTTPFailure(status: -1, message: "Socket close reason exceeds 123 bytes") } + socket.task.cancel(with: closeCode, reason: reason) + callback.success() + default: callback.error("Unknown WebSocket action: \(action)") + } + } catch { callback.error(error.localizedDescription) } + } + } +} + +private final class NativeSocket: NSObject, URLSessionWebSocketDelegate, @unchecked Sendable { + private(set) var task: URLSessionWebSocketTask! + var binaryType: String + private let queue: DispatchQueue + private let onFinish: () -> Void + private var session: URLSession! + private var listener: Callback? + private var pending: [[String: Any]] = [] + private var state = 0 + private var reading = false + + init(args: [Any], queue: DispatchQueue, onFinish: @escaping () -> Void) throws { + guard let address = args[safe: 0] as? String, let url = URL(string: address), + ["ws", "wss"].contains(url.scheme?.lowercased() ?? ""), url.host != nil else { throw HTTPFailure(status: -5, message: "Expected a WebSocket URL") } + self.queue = queue + self.onFinish = onFinish + binaryType = args[safe: 3] as? String ?? "" + super.init() + var request = URLRequest(url: url) + request.allHTTPHeaderFields = args[safe: 2] as? [String: String] ?? [:] + if let protocols = args[safe: 1] as? [String], !protocols.isEmpty { request.setValue(protocols.joined(separator: ","), forHTTPHeaderField: "Sec-WebSocket-Protocol") } + request.timeoutInterval = 10 + let delegates = OperationQueue() + delegates.maxConcurrentOperationCount = 1 + delegates.underlyingQueue = queue + let configuration = URLSessionConfiguration.ephemeral + configuration.httpCookieStorage = nil + session = URLSession(configuration: configuration, delegate: self, delegateQueue: delegates) + task = session.webSocketTask(with: request) + } + + func listen(_ callback: Callback) { + listener = callback + for event in pending { callback.success(event, keep: event["readyState"] as? Int != 3) } + pending.removeAll() + if state == 3 { onFinish() } + else { receive() } + } + + func stop() { + state = 3 + listener = nil + pending.removeAll() + session.invalidateAndCancel() + } + + func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) { + state = 1 + emit(["type": "open", "protocol": `protocol` ?? "", "extensions": ""]) + receive() + } + + func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { + guard state != 3 else { return } + state = 3 + emit(["type": "close", "data": ["code": closeCode.rawValue, "reason": reason.flatMap { String(data: $0, encoding: .utf8) } ?? ""]]) + session.finishTasksAndInvalidate() + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + guard let error, state != 3 else { return } + state = 3 + emit(["type": "error", "data": error.localizedDescription]) + session.finishTasksAndInvalidate() + } + + private func receive() { + guard listener != nil, state == 1, !reading else { return } + reading = true + task.receive { [weak self] result in + guard let self else { return } + self.queue.async { + self.reading = false + guard self.state == 1 else { return } + switch result { + case .success(.string(let text)): self.emit(["type": "message", "data": text, "isBinary": false]) + case .success(.data(let data)): + let asText = self.binaryType != "arraybuffer" + self.emit(["type": "message", "data": asText ? String(decoding: data, as: UTF8.self) : data.base64EncodedString(), "isBinary": true, "parseAsText": asText]) + case .failure: return + @unknown default: return + } + self.receive() + } + } + } + + private func emit(_ value: [String: Any]) { + var event = value + event["readyState"] = state + if let listener { + listener.success(event, keep: state != 3) + if state == 3 { self.listener = nil; onFinish() } + } else { pending.append(event) } + } +} diff --git a/platforms/ios/runner/lib/preview/BrowserService.swift b/platforms/ios/runner/lib/preview/BrowserService.swift new file mode 100644 index 0000000000..536b3c3c9b --- /dev/null +++ b/platforms/ios/runner/lib/preview/BrowserService.swift @@ -0,0 +1,31 @@ +import UIKit + +final class BrowserService: BaseService { + private weak var browser: PreviewViewController? + + override func reset() { + DispatchQueue.main.async { self.browser?.close() } + } + + override func exec(action: String, args: [Any], callback: Callback) { + guard ["open", "in-app-browser"].contains(action), let value = args[safe: 0] as? String, + let url = URL(string: value), ["http", "https"].contains(url.scheme?.lowercased() ?? ""), url.host != nil else { + callback.error("Preview requires an HTTP or HTTPS URL"); return + } + DispatchQueue.main.async { + guard let presenter = self.viewController, presenter.presentedViewController == nil else { + callback.error("A browser cannot be presented right now"); return + } + let browser = PreviewViewController(url: url, theme: args[safe: 1] as? [String: Any] ?? [:], console: action == "open" && args[safe: 2] as? Bool == true) + if action == "in-app-browser" { + browser.title = args[safe: 1] as? String + browser.showTools = args[safe: 2] as? Bool ?? true + browser.disableCache = args[safe: 3] as? Bool ?? false + browser.onExternal = { callback.success("onOpenExternalBrowser:" + $0.absoluteString, keep: true) } + browser.onClose = { callback.release() } + } + self.browser = browser + presenter.present(browser, animated: true) { if action == "open" { callback.success() } } + } + } +} diff --git a/platforms/ios/runner/lib/preview/LocalHTTPConnection.swift b/platforms/ios/runner/lib/preview/LocalHTTPConnection.swift new file mode 100644 index 0000000000..f1c009d934 --- /dev/null +++ b/platforms/ios/runner/lib/preview/LocalHTTPConnection.swift @@ -0,0 +1,132 @@ +import Foundation +import Network + +final class LocalHTTPConnection { + let id = UUID().uuidString + private let connection: NWConnection + private let queue: DispatchQueue + private var parser = LocalHTTPParser() + private var sentContinue = false + private var started = false + private var finished = false + private var headOnly = false + private var deadline: DispatchWorkItem? + var onClose: (() -> Void)? + var onRequest: ((LocalHTTPRequest) -> Void)? + + init(_ connection: NWConnection, queue: DispatchQueue) { + self.connection = connection + self.queue = queue + } + + func start() { + connection.stateUpdateHandler = { [weak self] state in + if case .failed = state { self?.cancel() } + if case .cancelled = state { self?.cancel() } + } + connection.start(queue: queue) + armTimeout() + receive() + } + + func cancel() { + guard !finished else { return } + finished = true + deadline?.cancel() + connection.cancel() + onClose?() + onClose = nil + onRequest = nil + } + + func startResponse(status: Int, headers: [String: String], length: UInt64? = nil) { + guard !started, !finished else { return } + started = true + var text = "HTTP/1.1 \(status) \(HTTPURLResponse.localizedString(forStatusCode: status))\r\n" + for (name, value) in headers where !["content-length", "connection", "transfer-encoding"].contains(name.lowercased()) { + guard LocalHTTPParser.isToken(name) else { continue } + let values = name.lowercased() == "set-cookie" ? value.components(separatedBy: "\n") : [value] + for item in values where !item.contains("\r") && !item.contains("\n") && !item.contains("\0") { text += "\(name): \(item)\r\n" } + } + if let length { text += "Content-Length: \(length)\r\n" } + text += "Connection: close\r\n\r\n" + connection.send(content: Data(text.utf8), completion: .contentProcessed { [weak self] error in if error != nil { self?.cancel() } }) + } + + func send(_ data: Data, completion: @escaping () -> Void = {}) { + guard started, !finished else { return } + if headOnly { completion(); return } + connection.send(content: data, completion: .contentProcessed { [weak self] error in + guard let self, !self.finished else { return } + if error != nil { self.cancel(); return } + self.armTimeout() + completion() + }) + } + + func end() { + guard !finished else { return } + connection.send(content: nil, contentContext: .finalMessage, isComplete: true, completion: .contentProcessed { [weak self] _ in self?.cancel() }) + } + + func respond(status: Int, headers: [String: String] = [:], body: Data = Data()) { + startResponse(status: status, headers: headers, length: UInt64(body.count)) + send(body) { [weak self] in self?.end() } + } + + /// Sends `101 Switching Protocols` and hands the socket to the new protocol, which owns it from then on. + func upgrade(headers: [String: String]) -> NWConnection? { + guard !started, !finished else { return nil } + started = true + finished = true + deadline?.cancel() + var text = "HTTP/1.1 101 Switching Protocols\r\n" + for (name, value) in headers { text += "\(name): \(value)\r\n" } + connection.send(content: Data((text + "\r\n").utf8), completion: .contentProcessed { _ in }) + connection.stateUpdateHandler = nil + onClose?() + onClose = nil + onRequest = nil + return connection + } + + func sendFile(_ file: FileHandle, count: UInt64) { + guard !finished, !headOnly, count > 0 else { try? file.close(); end(); return } + do { + let data = try file.read(upToCount: Int(min(count, 64 * 1024))) ?? Data() + guard !data.isEmpty else { try? file.close(); cancel(); return } + send(data) { [weak self] in + guard let self else { try? file.close(); return } + self.sendFile(file, count: count - UInt64(data.count)) + } + } catch { try? file.close(); cancel() } + } + + private func receive() { + connection.receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) { [weak self] data, _, complete, error in + guard let self, !self.finished else { return } + if error != nil { self.cancel(); return } + do { + if let request = try self.parser.append(data ?? Data()) { + self.headOnly = request.method == "HEAD" + self.armTimeout() + self.onRequest?(request) + return + } + if complete { self.respond(status: 400); return } + if self.parser.expectsContinue, !self.sentContinue { + self.sentContinue = true + self.connection.send(content: Data("HTTP/1.1 100 Continue\r\n\r\n".utf8), completion: .contentProcessed { _ in }) + } + self.receive() + } catch { self.respond(status: (error as? LocalHTTPError)?.status ?? 400) } + } + } + + private func armTimeout() { + deadline?.cancel() + let item = DispatchWorkItem { [weak self] in self?.cancel() } + deadline = item + queue.asyncAfter(deadline: .now() + 60, execute: item) + } +} diff --git a/platforms/ios/runner/lib/preview/LocalHTTPRequest.swift b/platforms/ios/runner/lib/preview/LocalHTTPRequest.swift new file mode 100644 index 0000000000..586e20d561 --- /dev/null +++ b/platforms/ios/runner/lib/preview/LocalHTTPRequest.swift @@ -0,0 +1,122 @@ +import Foundation + +struct LocalHTTPRequest { + let method: String + let target: String + let headers: [String: String] + let body: Data + + var payload: [String: Any] { + let parts = target.split(separator: "?", maxSplits: 1, omittingEmptySubsequences: false) + return ["method": method, "path": String(parts[0]).removingPercentEncoding ?? String(parts[0]), + "query": parts.count > 1 ? String(parts[1]) : "", "headers": headers, + "body": String(decoding: body, as: UTF8.self)] + } +} + +struct LocalHTTPParser { + static let headerLimit = 64 * 1024 + static let bodyLimit = 64 * 1024 * 1024 + private var buffer = Data() + private var head: (method: String, target: String, headers: [String: String])? + private var body = Data() + private var chunkSize: Int? + private var trailers = false + private(set) var expectsContinue = false + + mutating func append(_ data: Data) throws -> LocalHTTPRequest? { + buffer.append(data) + if head == nil { + guard let end = buffer.range(of: Data("\r\n\r\n".utf8)) else { + guard buffer.count <= Self.headerLimit else { throw LocalHTTPError(431) } + return nil + } + guard end.lowerBound - buffer.startIndex <= Self.headerLimit else { throw LocalHTTPError(431) } + try parseHead(Data(buffer[..<end.lowerBound])) + buffer = Data(buffer[end.upperBound...]) + } + guard let head else { return nil } + if head.headers["transfer-encoding"] != nil { + guard try readChunks() else { return nil } + } else { + let length = Int(head.headers["content-length"] ?? "0") ?? 0 + guard buffer.count >= length else { return nil } + body = Data(buffer.prefix(length)) + } + return LocalHTTPRequest(method: head.method, target: head.target, headers: head.headers, body: body) + } + + private mutating func parseHead(_ data: Data) throws { + let lines = String(decoding: data, as: UTF8.self).components(separatedBy: "\r\n") + let first = (lines.first ?? "").split(separator: " ", omittingEmptySubsequences: false) + guard first.count == 3, Self.isToken(String(first[0])), first[1].hasPrefix("/"), + ["HTTP/1.1", "HTTP/1.0"].contains(first[2]), + !first[1].contains(where: { $0.asciiValue.map { $0 < 33 || $0 == 127 } ?? false }) else { throw LocalHTTPError(400) } + var headers: [String: String] = [:] + for line in lines.dropFirst() { + guard let colon = line.firstIndex(of: ":") else { throw LocalHTTPError(400) } + let key = String(line[..<colon]).lowercased() + let value = String(line[line.index(after: colon)...]).trimmingCharacters(in: .whitespaces) + guard Self.isToken(key), !value.contains(where: { $0 == "\r" || $0 == "\n" || $0 == "\0" }) else { throw LocalHTTPError(400) } + if headers[key] != nil { + guard !["content-length", "transfer-encoding", "host"].contains(key) else { throw LocalHTTPError(400) } + headers[key]! += (key == "cookie" ? "; " : ", ") + value + } else { headers[key] = value } + } + if let encoding = headers["transfer-encoding"] { + guard encoding.lowercased() == "chunked", headers["content-length"] == nil else { throw LocalHTTPError(400) } + } + if let text = headers["content-length"] { + guard !text.isEmpty, text.allSatisfy({ $0.isASCII && $0.isNumber }), let length = Int(text), length >= 0 else { throw LocalHTTPError(400) } + guard length <= Self.bodyLimit else { throw LocalHTTPError(413) } + } + if let expectation = headers["expect"] { + guard expectation.lowercased() == "100-continue" else { throw LocalHTTPError(417) } + expectsContinue = true + } + head = (String(first[0]), String(first[1]), headers) + } + + private mutating func readChunks() throws -> Bool { + while true { + if trailers { + if buffer.starts(with: Data("\r\n".utf8)) { return true } + if let end = buffer.range(of: Data("\r\n\r\n".utf8)) { + guard end.upperBound - buffer.startIndex <= Self.headerLimit else { throw LocalHTTPError(431) } + return true + } + guard buffer.count <= Self.headerLimit else { throw LocalHTTPError(431) } + return false + } + if chunkSize == nil { + guard let end = buffer.range(of: Data("\r\n".utf8)) else { + guard buffer.count < Self.headerLimit else { throw LocalHTTPError(400) } + return false + } + let text = String(decoding: buffer[..<end.lowerBound], as: UTF8.self).split(separator: ";", maxSplits: 1)[safe: 0].map(String.init) ?? "" + guard !text.isEmpty, text.allSatisfy({ $0.isHexDigit }), let size = Int(text, radix: 16) else { throw LocalHTTPError(400) } + guard size <= Self.bodyLimit - body.count else { throw LocalHTTPError(413) } + buffer = Data(buffer[end.upperBound...]) + if size == 0 { trailers = true; continue } + chunkSize = size + } + guard let size = chunkSize, buffer.count >= size + 2 else { return false } + let end = buffer.startIndex + size + guard buffer[end] == 13, buffer[end + 1] == 10 else { throw LocalHTTPError(400) } + body.append(buffer.prefix(size)) + buffer = Data(buffer.dropFirst(size + 2)) + chunkSize = nil + } + } + + static func isToken(_ value: String) -> Bool { + !value.isEmpty && value.utf8.allSatisfy { byte in + (65...90).contains(byte) || (97...122).contains(byte) || (48...57).contains(byte) || "!#$%&'*+-.^_`|~".utf8.contains(byte) + } + } +} + +struct LocalHTTPError: Error { + let status: Int + init(_ status: Int) { self.status = status } +} diff --git a/platforms/ios/runner/lib/preview/LocalHTTPServer.swift b/platforms/ios/runner/lib/preview/LocalHTTPServer.swift new file mode 100644 index 0000000000..918277a546 --- /dev/null +++ b/platforms/ios/runner/lib/preview/LocalHTTPServer.swift @@ -0,0 +1,72 @@ +import Foundation +import Network + +final class LocalHTTPServer { + private let listener: NWListener + private let queue: DispatchQueue + private var connections: [String: LocalHTTPConnection] = [:] + private var ready: ((Result<Int, Error>) -> Void)? + private var stopped = false + private var stopCallbacks: [() -> Void] = [] + var onRequest: ((LocalHTTPRequest, LocalHTTPConnection) -> Void)? + + init(port: Int, loopback: Bool = false, queue: DispatchQueue) throws { + guard (0...65535).contains(port), let endpoint = NWEndpoint.Port(rawValue: UInt16(port)) else { throw LocalHTTPError(400) } + self.queue = queue + let parameters = NWParameters.tcp + parameters.allowLocalEndpointReuse = true + // A port passed to `on:` as well as in requiredLocalEndpoint fails with EINVAL. + if loopback { + parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: endpoint) + listener = try NWListener(using: parameters) + } else { + listener = try NWListener(using: parameters, on: endpoint) + } + listener.newConnectionLimit = 64 + } + + func start(_ completion: @escaping (Result<Int, Error>) -> Void) { + ready = completion + listener.stateUpdateHandler = { [weak self] state in + guard let self else { return } + switch state { + case .ready: + self.ready?(.success(Int(self.listener.port!.rawValue))) + self.ready = nil + case .failed(let error): + self.ready?(.failure(error)); self.ready = nil; self.stop() + default: break + } + } + listener.newConnectionHandler = { [weak self] transport in + guard let self, self.connections.count < 64 else { transport.cancel(); return } + let client = LocalHTTPConnection(transport, queue: self.queue) + self.connections[client.id] = client + client.onClose = { [weak self, weak client] in if let client { self?.connections.removeValue(forKey: client.id) } } + client.onRequest = { [weak self, weak client] request in + guard let client else { return } + self?.onRequest?(request, client) + } + client.start() + } + listener.start(queue: queue) + } + + func stop(_ completion: @escaping () -> Void = {}) { + if stopped { completion(); return } + stopCallbacks.append(completion) + ready?(.failure(URLError(.cancelled))); ready = nil + listener.stateUpdateHandler = { state in + guard case .cancelled = state else { return } + self.stopped = true + self.listener.stateUpdateHandler = nil + let callbacks = self.stopCallbacks + self.stopCallbacks.removeAll() + for callback in callbacks { callback() } + } + listener.cancel() + let active = Array(connections.values) + connections.removeAll() + for client in active { client.cancel() } + } +} diff --git a/platforms/ios/runner/lib/preview/LocalWebSocket.swift b/platforms/ios/runner/lib/preview/LocalWebSocket.swift new file mode 100644 index 0000000000..e720bd75c6 --- /dev/null +++ b/platforms/ios/runner/lib/preview/LocalWebSocket.swift @@ -0,0 +1,125 @@ +import CryptoKit +import Foundation +import Network + +/// Server side of RFC 6455 on a socket upgraded by `LocalHTTPConnection`. Not thread-safe; use its queue. +final class LocalWebSocket { + private static let maximumMessage = 16 * 1024 * 1024 + private let connection: NWConnection + private var buffer = Data() + private var message = Data() + private var messageIsText = false + private var closed = false + var onMessage: ((Data, Bool) -> Void)? + var onClose: (() -> Void)? + + static func accept(_ request: LocalHTTPRequest, client: LocalHTTPConnection) -> LocalWebSocket? { + guard request.method == "GET", request.headers["upgrade"]?.lowercased() == "websocket", + let key = request.headers["sec-websocket-key"], + let connection = client.upgrade(headers: ["Upgrade": "websocket", "Connection": "Upgrade", + "Sec-WebSocket-Accept": acceptKey(key)]) else { return nil } + return LocalWebSocket(connection) + } + + private init(_ connection: NWConnection) { + self.connection = connection + connection.stateUpdateHandler = { [weak self] state in + switch state { + case .failed, .cancelled: self?.close() + default: break + } + } + receive() + } + + func send(_ payload: Data, text: Bool = false, completion: @escaping () -> Void = {}) { + guard !closed else { return } + connection.send(content: Self.frame(text ? 0x1 : 0x2, payload), completion: .contentProcessed { [weak self] error in + if error != nil { self?.close(); return } + completion() + }) + } + + func close() { + guard !closed else { return } + closed = true + connection.send(content: Self.frame(0x8, Data([0x03, 0xE8])), completion: .contentProcessed { [connection] _ in + connection.cancel() + }) + let handler = onClose + onClose = nil + onMessage = nil + handler?() + } + + private func receive() { + connection.receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) { [weak self] data, _, complete, error in + guard let self, !self.closed else { return } + if let data { buffer.append(data) } + do { + while !closed, let frame = try nextFrame() { handle(frame) } + } catch { close(); return } + if error != nil || complete { close(); return } + if !closed { receive() } + } + } + + private func handle(_ frame: (opcode: UInt8, final: Bool, payload: Data)) { + switch frame.opcode { + case 0x0, 0x1, 0x2: + if frame.opcode != 0x0 { message = Data(); messageIsText = frame.opcode == 0x1 } + message.append(frame.payload) + guard message.count <= Self.maximumMessage else { close(); return } + if frame.final { onMessage?(message, messageIsText); message = Data() } + case 0x8: close() + case 0x9: connection.send(content: Self.frame(0xA, frame.payload), completion: .contentProcessed { _ in }) + default: break + } + } + + private func nextFrame() throws -> (opcode: UInt8, final: Bool, payload: Data)? { + let head = [UInt8](buffer.prefix(14)) + guard head.count >= 2 else { return nil } + var length = Int(head[1] & 0x7F) + var offset = 2 + if length == 126 { + guard head.count >= 4 else { return nil } + length = Int(head[2]) << 8 | Int(head[3]) + offset = 4 + } else if length == 127 { + guard head.count >= 10 else { return nil } + guard head[2] & 0x80 == 0 else { throw LocalHTTPError(400) } + length = head[2..<10].reduce(0) { $0 << 8 | Int($1) } + offset = 10 + } + guard length <= Self.maximumMessage else { throw LocalHTTPError(413) } + let masked = head[1] & 0x80 != 0 + let start = offset + (masked ? 4 : 0) + guard buffer.count >= start + length else { return nil } + var payload = [UInt8](buffer[(buffer.startIndex + start)..<(buffer.startIndex + start + length)]) + if masked { + let mask = [UInt8](buffer[(buffer.startIndex + offset)..<(buffer.startIndex + offset + 4)]) + for index in payload.indices { payload[index] ^= mask[index & 3] } + } + buffer = Data(buffer.dropFirst(start + length)) + return (head[0] & 0x0F, head[0] & 0x80 != 0, Data(payload)) + } + + private static func frame(_ opcode: UInt8, _ payload: Data) -> Data { + var frame = Data([0x80 | opcode]) + if payload.count < 126 { + frame.append(UInt8(payload.count)) + } else if payload.count <= 0xFFFF { + frame.append(contentsOf: [126, UInt8(payload.count >> 8), UInt8(payload.count & 0xFF)]) + } else { + frame.append(127) + for shift in stride(from: 56, through: 0, by: -8) { frame.append(UInt8((payload.count >> shift) & 0xFF)) } + } + frame.append(payload) + return frame + } + + private static func acceptKey(_ key: String) -> String { + Data(Insecure.SHA1.hash(data: Data((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").utf8))).base64EncodedString() + } +} diff --git a/platforms/ios/runner/lib/preview/PluginWebView.swift b/platforms/ios/runner/lib/preview/PluginWebView.swift new file mode 100644 index 0000000000..705f2e9e38 --- /dev/null +++ b/platforms/ios/runner/lib/preview/PluginWebView.swift @@ -0,0 +1,136 @@ +import WebKit + +@MainActor +final class PluginWebView: NSObject, WKScriptMessageHandler { + let id = "wv_" + UUID().uuidString.replacingOccurrences(of: "-", with: "").prefix(12) + let controller: PreviewViewController + let fullscreen: Bool + private let allowNavigation: Bool + private var ready: Bool + private var requestedURL: URL? + private var pendingHTML: String? + private var loadedHTML: String? + private var pendingURL: URL? + var emit: (([String: Any]) -> Void)? + + init(options: [String: Any]) { + fullscreen = options["mode"] as? String == "fullscreen" + ready = !fullscreen + allowNavigation = options["allowNavigation"] as? Bool ?? true + controller = PreviewViewController(url: URL(string: "about:blank")!, theme: [:], console: true) + super.init() + controller.consoleEnabled = false + controller.title = options["title"] as? String + controller.allowsDownloads = options["allowDownloads"] as? Bool ?? false + controller.externalSchemesAllowed = false + controller.navigationPolicy = { [weak self] action in self?.allow(action) ?? false } + controller.onPageFinished = { [weak self] in + guard let self else { return } + self.event("pageFinished", data: ["url": self.controller.webView.url?.absoluteString ?? "", "title": self.controller.webView.title ?? ""]) + } + controller.onTitleChanged = { [weak self] title in self?.event("titleChanged", data: ["title": title]) } + let content = controller.webView.configuration.userContentController + WebShadowCaret.install(on: content) + content.add(WeakScriptMessageHandler(self), name: "webviewMessage") + content.addUserScript(WKUserScript(source: Self.messagingScript, injectionTime: .atDocumentStart, forMainFrameOnly: true)) + if ready { controller.loadViewIfNeeded() } + } + + func show(from presenter: UIViewController, callback: Callback? = nil) { + guard fullscreen else { callback?.error("Hidden WebViews cannot be shown; use mode fullscreen"); return } + if controller.presentingViewController != nil { callback?.success(); return } + guard presenter.presentedViewController == nil else { callback?.error("A WebView cannot be presented right now"); return } + ready = true + controller.loadViewIfNeeded() + if let url = pendingURL { pendingURL = nil; load(url) } + else if let html = pendingHTML { pendingHTML = nil; loadHTML(html) } + presenter.present(controller, animated: true) { callback?.success() } + } + + func hide(callback: Callback) { + guard controller.presentingViewController != nil else { callback.success(); return } + controller.dismiss(animated: true) { callback.success() } + } + + func load(_ url: URL) { + guard ready else { pendingURL = url; pendingHTML = nil; return } + loadedHTML = nil + requestedURL = url + controller.load(url) + } + + func loadHTML(_ html: String) { + guard ready else { pendingHTML = html; pendingURL = nil; return } + loadedHTML = html + requestedURL = URL(string: "about:blank")! + controller.webView.loadHTMLString(html, baseURL: nil) + } + + func evaluate(_ code: String, callback: Callback) { + guard ready else { callback.error("WebView is not ready"); return } + controller.webView.evaluateJavaScript(code) { value, error in + if let error { callback.error((error as NSError).userInfo["WKJavaScriptExceptionMessage"] as? String ?? error.localizedDescription) } + else if value == nil || value is NSNull { callback.success() } + else if let value = value as? String { callback.success(value) } + else if let value, let data = try? JSONSerialization.data(withJSONObject: value, options: [.fragmentsAllowed]), let text = String(data: data, encoding: .utf8) { callback.success(text) } + else { callback.success() } + } + } + + func post(_ message: String, callback: Callback) { + guard ready else { callback.error("WebView is not ready"); return } + controller.webView.callAsyncJavaScript("let value;try{value=JSON.parse(message)}catch{value=message}window.webview?._dispatch(value)", arguments: ["message": message], in: nil, in: .page) { result in + switch result { + case .success: callback.success() + case .failure(let error): callback.error((error as NSError).userInfo["WKJavaScriptExceptionMessage"] as? String ?? error.localizedDescription) + } + } + } + + func reload(callback: Callback) { + guard ready else { callback.error("WebView is not ready"); return } + if let html = loadedHTML, controller.webView.url?.absoluteString == "about:blank" { + loadHTML(html); callback.success(); return + } + requestedURL = controller.webView.url + controller.webView.reload() + callback.success() + } + + func destroy(completion: @escaping () -> Void = {}) { + controller.onClose = completion + controller.close() + controller.webView.configuration.userContentController.removeScriptMessageHandler(forName: "webviewMessage") + emit = nil + } + + func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) { + guard message.frameInfo.isMainFrame, let text = message.body as? String else { return } + emit?(["id": id, "message": text]) + } + + func event(_ name: String, data: [String: Any] = [:]) { emit?(["id": id, "event": name, "data": data]) } + + private func allow(_ action: WKNavigationAction) -> Bool { + guard let url = action.request.url else { return false } + if action.targetFrame?.isMainFrame == true, let expected = requestedURL, expected == url { + requestedURL = nil + return true + } + return allowNavigation && ["http", "https"].contains(url.scheme?.lowercased() ?? "") + } + + private static let messagingScript = """ + (()=>{ + if(window.webview?.__acodeBridge)return; + let callbacks=[]; + window.webview={ + __acodeBridge:true, + onMessage:callback=>{if(typeof callback==='function')callbacks.push(callback)}, + offMessage:callback=>{callbacks=callbacks.filter(item=>item!==callback)}, + postMessage:message=>window.webkit.messageHandlers.webviewMessage.postMessage(typeof message==='string'?message:JSON.stringify(message)), + _dispatch:message=>callbacks.slice().forEach(callback=>{try{callback(message)}catch(error){console.error(error)}}) + }; + })(); + """ +} diff --git a/platforms/ios/runner/lib/preview/PluginWebViewService.swift b/platforms/ios/runner/lib/preview/PluginWebViewService.swift new file mode 100644 index 0000000000..a0de642a14 --- /dev/null +++ b/platforms/ios/runner/lib/preview/PluginWebViewService.swift @@ -0,0 +1,70 @@ +import WebKit + +final class PluginWebViewService: BaseService { + private var instances: [String: PluginWebView] = [:] + private var messageCallback: Callback? + + override func reset() { + DispatchQueue.main.async { + for instance in self.instances.values { instance.destroy() } + self.instances.removeAll() + self.messageCallback?.release(); self.messageCallback = nil + } + } + + override func exec(action: String, args: [Any], callback: Callback) { + DispatchQueue.main.async { [self] in + if action == "setMessageCallback" { + self.messageCallback?.release(); self.messageCallback = callback; return + } + if action == "create" { + let options = args[safe: 0] as? [String: Any] ?? [:] + guard ["hidden", "fullscreen"].contains(options["mode"] as? String ?? "hidden") else { callback.error("Unsupported WebView mode"); return } + let instance = PluginWebView(options: options) + instance.controller.auxiliaryPresenter = self.viewController + self.instances[instance.id] = instance + instance.emit = { [weak self] payload in self?.messageCallback?.success(payload, keep: true) } + instance.controller.onClose = { [weak self, weak instance] in + guard let instance else { return } + instance.event("closed") + self?.instances.removeValue(forKey: instance.id) + instance.destroy() + } + if instance.fullscreen, options["visible"] as? Bool ?? true { + guard let presenter = self.viewController, presenter.presentedViewController == nil else { + self.instances.removeValue(forKey: instance.id); instance.destroy(); callback.error("A WebView cannot be presented right now"); return + } + instance.show(from: presenter) + } + callback.success(instance.id) + return + } + guard let id = args[safe: 0] as? String, let instance = self.instances[id] else { callback.error("WebView not found"); return } + switch action { + case "loadURL": + guard let value = args[safe: 1] as? String, let url = self.sanitizedURL(value) else { callback.error("Only HTTP and HTTPS URLs are allowed"); return } + instance.load(url); callback.success() + case "loadHTML": instance.loadHTML(args[safe: 1] as? String ?? ""); callback.success() + case "evaluate": instance.evaluate(args[safe: 1] as? String ?? "", callback: callback) + case "postMessage": instance.post(args[safe: 1] as? String ?? "", callback: callback) + case "show": + guard let presenter = self.viewController else { callback.error("View unavailable"); return } + instance.show(from: presenter, callback: callback) + case "hide": instance.hide(callback: callback) + case "reload": instance.reload(callback: callback) + case "destroy": self.instances.removeValue(forKey: id); instance.destroy { callback.success() } + default: callback.error("Unknown WebView action: \(action)") + } + } + } + + private func sanitizedURL(_ value: String) -> URL? { + let value = value.trimmingCharacters(in: .whitespacesAndNewlines) + guard !value.isEmpty else { return nil } + let explicit = value.range(of: "^[a-zA-Z][a-zA-Z0-9+.-]*:", options: .regularExpression) != nil + let hostPort = value.range(of: "^[^/:]+:[0-9]+(?:/|$)", options: .regularExpression) != nil + let input = explicit && !hostPort ? value : "https://" + value + guard let url = URL(string: input), ["http", "https"].contains(url.scheme?.lowercased() ?? ""), url.host != nil else { return nil } + return url + } +} diff --git a/platforms/ios/runner/lib/preview/PreviewActions.swift b/platforms/ios/runner/lib/preview/PreviewActions.swift new file mode 100644 index 0000000000..4c6e31f710 --- /dev/null +++ b/platforms/ios/runner/lib/preview/PreviewActions.swift @@ -0,0 +1,69 @@ +import UIKit +import WebKit + +extension PreviewViewController { + @objc func goBack() { + if consoleVisible { setConsoleVisible(false) } + else { webView.goBack() } + } + + @objc func goForward() { webView.goForward() } + + @objc func refresh() { + prepareNavigation { [weak self] in + guard let self else { return } + if self.disableCache { self.webView.reloadFromOrigin() } + else { self.webView.reload() } + } + } + + func setConsoleVisible(_ visible: Bool) { + consoleVisible = visible + webView.evaluateJavaScript("document.dispatchEvent(new CustomEvent('\(visible ? "show" : "hide")console'))") + updateMenu() + } + + func updateMenu() { + var actions: [UIMenuElement] = [ + UIAction(title: "Devices", image: UIImage(systemName: "display"), state: viewport == nil ? .off : .on) { [weak self] _ in self?.showDevices() }, + UIAction(title: "Disable Cache", image: UIImage(systemName: "arrow.triangle.2.circlepath"), state: disableCache ? .on : .off) { [weak self] _ in + guard let self else { return }; self.disableCache.toggle(); self.updateMenu(); self.refresh() + }, + ] + if consoleAvailable, viewport == nil { + actions.append(UIAction(title: "Console", image: UIImage(systemName: "terminal"), state: consoleVisible ? .on : .off) { [weak self] _ in + guard let self else { return }; self.setConsoleVisible(!self.consoleVisible) + }) + } + actions.append(UIAction(title: "Open in Browser", image: UIImage(systemName: "safari")) { [weak self] _ in + guard let self, let url = self.webView.url, ["http", "https"].contains(url.scheme ?? "") else { return } + if let onExternal = self.onExternal { onExternal(url); self.close() } + else { UIApplication.shared.open(url) { [weak self] opened in if opened { self?.close() } } } + }) + actions.append(UIAction(title: "Exit", image: UIImage(systemName: "xmark")) { [weak self] _ in self?.close() }) + actions.append(UIMenu(options: .displayInline, children: [ + UIAction(title: "Back", image: UIImage(systemName: "chevron.left"), attributes: webView.canGoBack || consoleVisible ? [] : .disabled) { [weak self] _ in self?.goBack() }, + UIAction(title: "Forward", image: UIImage(systemName: "chevron.right"), attributes: webView.canGoForward ? [] : .disabled) { [weak self] _ in self?.goForward() }, + ])) + menuButton.menu = UIMenu(children: actions) + } + + func applyViewport(_ size: CGSize?, scale: CGFloat = 1) { + let modeChanged = (viewport == nil) != (size == nil) + viewport = size + viewportScale = scale + if size != nil { setConsoleVisible(false) } + webView.configuration.defaultWebpagePreferences.preferredContentMode = size == nil ? .mobile : .desktop + view.setNeedsLayout() + updateMenu() + if modeChanged { refresh() } + } + + private func showDevices() { + let devices = PreviewDevicesController(size: viewport ?? content.bounds.size, scale: viewportScale) + devices.onChange = { [weak self] size, scale in self?.applyViewport(size, scale: scale) } + let navigation = UINavigationController(rootViewController: devices) + navigation.sheetPresentationController?.detents = [.medium(), .large()] + present(navigation, animated: true) + } +} diff --git a/platforms/ios/runner/lib/preview/PreviewDevicesController.swift b/platforms/ios/runner/lib/preview/PreviewDevicesController.swift new file mode 100644 index 0000000000..671e1a66f5 --- /dev/null +++ b/platforms/ios/runner/lib/preview/PreviewDevicesController.swift @@ -0,0 +1,74 @@ +import UIKit + +@MainActor +final class PreviewDevicesController: UITableViewController { + private let presets: [(String, CGFloat, CGFloat)] = [ + ("iPhone SE", 320, 568), ("iPhone 8", 375, 667), ("iPhone 8+", 414, 736), ("iPhone X", 375, 812), + ("iPad", 768, 1024), ("iPad Pro", 1024, 1366), ("Galaxy S5", 360, 640), ("Pixel 2", 411, 731), + ("Pixel 2 XL", 411, 823), ("Nexus 5X", 411, 731), ("Nexus 6P", 411, 731), ("Nexus 7", 600, 960), + ("Nexus 10", 800, 1280), ("Laptop", 1280, 800), ("Laptop L", 1440, 900), ("Laptop XL", 1680, 1050), ("UHD 4k", 3840, 2160), + ] + private let width = UITextField() + private let height = UITextField() + private let scaleControl = UISlider() + var onChange: ((CGSize?, CGFloat) -> Void)? + + init(size: CGSize, scale: CGFloat) { + super.init(style: .insetGrouped) + width.text = String(Int(size.width)); height.text = String(Int(size.height)) + scaleControl.minimumValue = 0.1; scaleControl.maximumValue = 1; scaleControl.value = Float(scale) + } + + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + override func viewDidLoad() { + super.viewDidLoad() + title = "Devices" + navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done)) + for field in [width, height] { + field.keyboardType = .numberPad + field.borderStyle = .roundedRect + field.addTarget(self, action: #selector(update), for: .editingChanged) + } + width.accessibilityLabel = "Viewport width" + height.accessibilityLabel = "Viewport height" + scaleControl.accessibilityLabel = "Viewport scale" + scaleControl.addTarget(self, action: #selector(update), for: .valueChanged) + } + + override func numberOfSections(in tableView: UITableView) -> Int { 2 } + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { section == 0 ? 4 : presets.count } + override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { section == 0 ? "Custom" : "Presets" } + + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = UITableViewCell(style: .value1, reuseIdentifier: nil) + if indexPath.section == 1 { + let preset = presets[indexPath.row] + cell.textLabel?.text = preset.0 + cell.detailTextLabel?.text = "\(Int(preset.1)) × \(Int(preset.2))" + } else if indexPath.row == 3 { cell.textLabel?.text = "Reset to Device" } + else { + cell.textLabel?.text = ["Width", "Height", "Scale"][indexPath.row] + let control: UIView = [width, height, scaleControl][indexPath.row] + control.frame = CGRect(x: 0, y: 0, width: 150, height: 32) + cell.accessoryView = control + cell.selectionStyle = .none + } + return cell + } + + override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + if indexPath.section == 1 { + let preset = presets[indexPath.row] + width.text = String(Int(preset.1)); height.text = String(Int(preset.2)); scaleControl.value = 1 + update(); dismiss(animated: true) + } else if indexPath.row == 3 { onChange?(nil, 1); dismiss(animated: true) } + } + + @objc private func update() { + guard let w = Int(width.text ?? ""), let h = Int(height.text ?? ""), (100...7680).contains(w), (100...7680).contains(h) else { return } + onChange?(CGSize(width: w, height: h), CGFloat(scaleControl.value)) + } + + @objc private func done() { update(); dismiss(animated: true) } +} diff --git a/platforms/ios/runner/lib/preview/PreviewDownloadManager.swift b/platforms/ios/runner/lib/preview/PreviewDownloadManager.swift new file mode 100644 index 0000000000..ffd478ff52 --- /dev/null +++ b/platforms/ios/runner/lib/preview/PreviewDownloadManager.swift @@ -0,0 +1,57 @@ +import UIKit +import WebKit + +@MainActor +final class PreviewDownloadManager: NSObject, WKDownloadDelegate { + static let shared = PreviewDownloadManager() + private(set) var transfers: [WKDownload: Transfer] = [:] + + func accept(_ download: WKDownload, destination: URL, browser: PreviewViewController) { + transfers[download] = Transfer(file: destination, browser: browser) + download.delegate = self + } + + func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) { + completionHandler(transfers[download]?.file) + } + + func downloadDidFinish(_ download: WKDownload) { + guard let transfer = transfers.removeValue(forKey: download) else { return } + show("Download complete", message: "Saved to Acode/Downloads/" + transfer.file.lastPathComponent, transfer: transfer) + } + + func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) { + guard let transfer = transfers.removeValue(forKey: download) else { return } + try? FileManager.default.removeItem(at: transfer.file) + guard (error as NSError).code != NSURLErrorCancelled else { return } + show("Download failed", message: error.localizedDescription, transfer: transfer) + } + + private func show(_ title: String, message: String, transfer: Transfer) { + DispatchQueue.main.async { + guard let presenter = transfer.browser?.dialogPresenter ?? transfer.presenter, + presenter.isViewLoaded, presenter.view.window != nil else { return } + // A finished transfer can arrive while its confirmation or preview is dismissing. + if let transition = presenter.transitionCoordinator ?? presenter.presentedViewController?.transitionCoordinator, + transition.animate(alongsideTransition: nil, completion: { _ in self.show(title, message: message, transfer: transfer) }) { return } + guard presenter.presentedViewController == nil, !presenter.isBeingDismissed else { return } + let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + if transfer.browser?.isClosed == false { transfer.browser?.activeDialog = alert } + presenter.present(alert, animated: true) + } + } + + @MainActor final class Transfer { + let file: URL + weak var browser: PreviewViewController? + weak var presenter: UIViewController? + + init(file: URL, browser: PreviewViewController) { + self.file = file + self.browser = browser + let current = browser.dialogPresenter + presenter = current?.presentingViewController ?? current + } + } +} diff --git a/platforms/ios/runner/lib/preview/PreviewDownloads.swift b/platforms/ios/runner/lib/preview/PreviewDownloads.swift new file mode 100644 index 0000000000..33e519df2f --- /dev/null +++ b/platforms/ios/runner/lib/preview/PreviewDownloads.swift @@ -0,0 +1,44 @@ +import UIKit +import WebKit + +extension PreviewViewController: WKDownloadDelegate { + func webView(_ webView: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) { download.delegate = self } + func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) { download.delegate = self } + + func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) { + guard let presenter = dialogPresenter, presenter.presentedViewController == nil, pendingDialog == nil else { completionHandler(nil); return } + let name = URL(fileURLWithPath: suggestedFilename).lastPathComponent + let alert = UIAlertController(title: "Download file", message: name, preferredStyle: .alert) + var answered = false + let answer: (URL?) -> Void = { [weak self] destination in + guard !answered else { return } + answered = true; self?.pendingDialog = nil; completionHandler(destination) + } + pendingDialog = { answer(nil) } + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in answer(nil) }) + alert.addAction(UIAlertAction(title: "Download", style: .default) { [weak self] _ in + guard let self else { answer(nil); return } + do { + let directory = AppFiles.shared.documents.appendingPathComponent("Downloads", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let basename = ["", ".", "..", "/"].contains(name) ? "download" : name + var target = directory.appendingPathComponent(basename) + if FileManager.default.fileExists(atPath: target.path) { + target = directory.appendingPathComponent(UUID().uuidString + "-" + basename) + } + PreviewDownloadManager.shared.accept(download, destination: target, browser: self) + answer(target) + } catch { answer(nil) } + }) + activeDialog = alert + presenter.present(alert, animated: true) + } + + func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) { + guard (error as NSError).code != NSURLErrorCancelled, let presenter = dialogPresenter, presenter.presentedViewController == nil else { return } + let alert = UIAlertController(title: "Download failed", message: error.localizedDescription, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + activeDialog = alert + presenter.present(alert, animated: true) + } +} diff --git a/platforms/ios/runner/lib/preview/PreviewNavigation.swift b/platforms/ios/runner/lib/preview/PreviewNavigation.swift new file mode 100644 index 0000000000..8ef417c802 --- /dev/null +++ b/platforms/ios/runner/lib/preview/PreviewNavigation.swift @@ -0,0 +1,120 @@ +import UIKit +import WebKit + +extension PreviewViewController: WKNavigationDelegate, WKUIDelegate, UITextFieldDelegate { + func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { + guard !isClosed, let url = action.request.url else { decisionHandler(.cancel); return } + if navigationPolicy?(action) == false { decisionHandler(.cancel); return } + let scheme = url.scheme?.lowercased() ?? "" + if ["http", "https", "about", "blob", "data"].contains(scheme) { + decisionHandler(action.shouldPerformDownload ? (allowsDownloads ? .download : .cancel) : .allow) + } else { + decisionHandler(.cancel) + if externalSchemesAllowed, action.navigationType == .linkActivated, !["file", "acode", "javascript"].contains(scheme) { UIApplication.shared.open(url) } + } + } + + func webView(_ webView: WKWebView, decidePolicyFor response: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { + guard !isClosed else { decisionHandler(.cancel); return } + let disposition = (response.response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Content-Disposition") ?? "" + decisionHandler(!response.canShowMIMEType || disposition.lowercased().hasPrefix("attachment") ? (allowsDownloads ? .download : .cancel) : .allow) + } + + func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { + progress.startAnimating() + consoleAvailable = false + updateMenu() + } + + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + updateAddress() + progress.stopAnimating() + if consoleEnabled { prepareConsole() } + onPageFinished?() + } + + func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { navigationFailed(error) } + func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { navigationFailed(error) } + + func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { + if action.targetFrame == nil, navigationPolicy?(action) != false, let url = action.request.url { load(url) } + return nil + } + + func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { + showDialog(message, defaultText: nil, confirm: false) { _ in completionHandler() } + } + + func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { + showDialog(message, defaultText: nil, confirm: true) { completionHandler($0 != nil) } + } + + func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { + showDialog(prompt, defaultText: defaultText ?? "", confirm: true, completion: completionHandler) + } + + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.text = webView.url?.absoluteString ?? initialURL.absoluteString + } + + func textFieldDidEndEditing(_ textField: UITextField) { updateAddress() } + + func textFieldShouldReturn(_ textField: UITextField) -> Bool { + let value = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if let url = URL(string: value.contains("://") ? value : "http://" + value) { load(url) } + textField.resignFirstResponder() + return true + } + + private func showDialog(_ message: String, defaultText: String?, confirm: Bool, completion: @escaping (String?) -> Void) { + guard let presenter = dialogPresenter, presenter.presentedViewController == nil, pendingDialog == nil else { completion(nil); return } + let alert = UIAlertController(title: webView.url?.host, message: message, preferredStyle: .alert) + if let defaultText { alert.addTextField { $0.text = defaultText } } + var answered = false + let answer: (String?) -> Void = { [weak self] value in + guard !answered else { return } + answered = true; self?.pendingDialog = nil; completion(value) + } + pendingDialog = { answer(nil) } + if confirm { alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in answer(nil) }) } + alert.addAction(UIAlertAction(title: "OK", style: .default) { [weak alert] _ in answer(alert?.textFields?.first?.text ?? "") }) + activeDialog = alert + presenter.present(alert, animated: true) + } + + private func navigationFailed(_ error: Error) { + progress.stopAnimating() + guard (error as NSError).code != NSURLErrorCancelled, presentedViewController == nil else { return } + showDialog(error.localizedDescription, defaultText: nil, confirm: false) { _ in } + } + + private func prepareConsole() { + let url = webView.url + let inspect = "Boolean(sessionStorage.getItem('__console_available') || document.querySelector('c-toggler') || window.eruda)" + webView.evaluateJavaScript(inspect) { [weak self] result, _ in + guard let self, self.webView.url == url else { return } + if result as? Bool == true { self.consoleReady(); return } + guard !self.consoleOnly else { return } + let file = AppFiles.shared.data.appendingPathComponent("eruda.js") + DispatchQueue.global(qos: .userInitiated).async { + let source = try? String(contentsOf: file, encoding: .utf8) + DispatchQueue.main.async { + guard self.webView.url == url else { return } + if let source { self.installConsole(source) } + } + } + } + } + + private func installConsole(_ source: String) { + webView.evaluateJavaScript(source + "\n;if(window.eruda){eruda.init({theme:'dark'});eruda._shadowRoot.querySelector('.eruda-entry-btn').style.display='none';sessionStorage.setItem('__console_available',true);document.addEventListener('showconsole',()=>eruda.show());document.addEventListener('hideconsole',()=>eruda.hide());}") { [weak self] _, error in + if error == nil { self?.consoleReady() } + } + } + + private func consoleReady() { + consoleAvailable = true + setConsoleVisible(consoleVisible) + updateMenu() + } +} diff --git a/platforms/ios/runner/lib/preview/PreviewResponse.swift b/platforms/ios/runner/lib/preview/PreviewResponse.swift new file mode 100644 index 0000000000..4a7defc3a4 --- /dev/null +++ b/platforms/ios/runner/lib/preview/PreviewResponse.swift @@ -0,0 +1,64 @@ +import CryptoKit +import Foundation + +enum PreviewResponse { + static func send(_ value: [String: Any], request: LocalHTTPRequest, client: LocalHTTPConnection) throws { + var headers = value["headers"] as? [String: String] ?? [:] + if let path = value["path"] as? String { + let files = AppFiles.shared + let url = try files.resolve(path) + try files.coordinate(url) { item in + let attributes = try item.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey, .isRegularFileKey]) + guard attributes.isRegularFile == true else { throw FileFailure(2) } + let size = UInt64(attributes.fileSize ?? 0) + let signature = "\(item.absoluteString)|\(attributes.contentModificationDate?.timeIntervalSince1970 ?? 0)|\(size)" + let etag = "\"" + SHA256.hash(data: Data(signature.utf8)).map { String(format: "%02x", $0) }.joined() + "\"" + if !headers.keys.contains(where: { $0.lowercased() == "content-type" }) { headers["Content-Type"] = files.mimeType(item) } + headers["ETag"] = etag + headers["Accept-Ranges"] = "bytes" + let rangeAllowed = request.headers["if-range"].map { $0 == etag } ?? true + let range = rangeAllowed ? request.headers["range"] : nil + let slice: Range<UInt64> + do { slice = try byteRange(range, size: size) } + catch { + headers["Content-Range"] = "bytes */\(size)" + client.respond(status: 416, headers: headers); return + } + if let conditional = request.headers["if-none-match"], conditional == "*" || conditional.components(separatedBy: ",").contains(where: { $0.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: "W/", with: "") == etag }) { + client.respond(status: 304, headers: headers); return + } + let partial = range != nil && range!.hasPrefix("bytes=") && !range!.contains(",") + if partial { headers["Content-Range"] = "bytes \(slice.lowerBound)-\(slice.upperBound - 1)/\(size)" } + let file = try FileHandle(forReadingFrom: item) + try file.seek(toOffset: slice.lowerBound) + client.startResponse(status: partial ? 206 : 200, headers: headers, length: slice.upperBound - slice.lowerBound) + client.sendFile(file, count: slice.upperBound - slice.lowerBound) + } + } else { + let status = value["status"] as? Int ?? 200 + guard (200...599).contains(status) else { throw LocalHTTPError(500) } + if !headers.keys.contains(where: { $0.lowercased() == "content-type" }) { headers["Content-Type"] = "text/plain; charset=utf-8" } + if let name = headers.keys.first(where: { $0.lowercased() == "content-type" }), let type = headers[name], !type.lowercased().contains("charset=") { + headers[name] = type + "; charset=utf-8" + } + let body = [204, 304].contains(status) ? Data() : Data((value["body"] as? String ?? "").utf8) + client.respond(status: status, headers: headers, body: body) + } + } + + private static func byteRange(_ range: String?, size: UInt64) throws -> Range<UInt64> { + guard let range, range.hasPrefix("bytes="), !range.contains(",") else { return 0..<size } + let pair = range.dropFirst(6).split(separator: "-", maxSplits: 1, omittingEmptySubsequences: false) + guard pair.count == 2, size > 0 else { throw LocalHTTPError(416) } + if pair[0].isEmpty { + guard let suffix = UInt64(pair[1]), suffix > 0 else { throw LocalHTTPError(416) } + return (size - min(size, suffix))..<size + } + guard let start = UInt64(pair[0]), start < size else { throw LocalHTTPError(416) } + let end: UInt64 + if pair[1].isEmpty { end = size - 1 } + else if let requested = UInt64(pair[1]), requested >= start { end = min(requested, size - 1) } + else { throw LocalHTTPError(416) } + return start..<(end + 1) + } +} diff --git a/platforms/ios/runner/lib/preview/PreviewToolbar.swift b/platforms/ios/runner/lib/preview/PreviewToolbar.swift new file mode 100644 index 0000000000..22739bbf4e --- /dev/null +++ b/platforms/ios/runner/lib/preview/PreviewToolbar.swift @@ -0,0 +1,92 @@ +import CoreText +import UIKit +import WebKit + +extension PreviewViewController { + func configureToolbar(foreground: UIColor) { + toolbar.alignment = .center + toolbar.isLayoutMarginsRelativeArrangement = true + toolbar.layoutMargins = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) + let close = toolbarButton("\u{e965}", label: "Close preview", action: #selector(close)) + let icon = UIImageView(image: PreviewIcons.image("\u{ea0d}")) + icon.contentMode = .center + let indicator = UIView() + indicator.addSubview(icon) + indicator.addSubview(progress) + progress.color = foreground + for child in [icon, progress] { + child.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + child.centerXAnchor.constraint(equalTo: indicator.centerXAnchor), + child.centerYAnchor.constraint(equalTo: indicator.centerYAnchor), + ]) + } + indicator.widthAnchor.constraint(equalToConstant: 35).isActive = true + indicator.heightAnchor.constraint(equalToConstant: 35).isActive = true + address.delegate = self + address.textColor = foreground + address.font = .systemFont(ofSize: 16) + address.keyboardType = .URL + address.returnKeyType = .go + address.autocapitalizationType = .none + address.autocorrectionType = .no + address.clearButtonMode = .whileEditing + address.isEnabled = !consoleOnly + address.accessibilityLabel = consoleOnly ? "Console title" : "Preview address" + address.setContentHuggingPriority(.defaultLow, for: .horizontal) + address.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + address.heightAnchor.constraint(equalToConstant: 35).isActive = true + if !consoleOnly { + address.backgroundColor = foreground.withAlphaComponent(0.067) + address.layer.cornerRadius = 17.5 + address.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 17.5, height: 1)) + address.leftViewMode = .always + } + for child in [close, indicator, address] { toolbar.addArrangedSubview(child) } + if !consoleOnly || !consoleEnabled { + toolbar.addArrangedSubview(toolbarButton("\u{e9b3}", label: "Refresh", action: #selector(refresh))) + } + menuButton.setImage(PreviewIcons.image("\u{e9b2}"), for: .normal) + menuButton.accessibilityLabel = "Preview menu" + menuButton.showsMenuAsPrimaryAction = true + menuButton.widthAnchor.constraint(equalToConstant: 35).isActive = true + menuButton.heightAnchor.constraint(equalToConstant: 45).isActive = true + if !consoleOnly && showTools { toolbar.addArrangedSubview(menuButton) } + updateAddress() + } + + func updateAddress() { + guard !address.isFirstResponder else { return } + address.text = title ?? webView.title.flatMap { $0.isEmpty ? nil : $0 } + ?? (consoleOnly ? "Console" : webView.url?.absoluteString ?? initialURL.absoluteString) + } + + private func toolbarButton(_ glyph: String, label: String, action: Selector) -> UIButton { + let button = UIButton(type: .system) + button.setImage(PreviewIcons.image(glyph), for: .normal) + button.accessibilityLabel = label + button.addTarget(self, action: action, for: .touchUpInside) + button.widthAnchor.constraint(equalToConstant: 35).isActive = true + button.heightAnchor.constraint(equalToConstant: 45).isActive = true + return button + } +} + +@MainActor +private enum PreviewIcons { + static let font: UIFont? = { + let url = Bundle.main.bundleURL.appendingPathComponent("bundle/build/icons.ttf") + guard let provider = CGDataProvider(url: url as CFURL), let font = CGFont(provider), let name = font.postScriptName else { return nil } + CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil) + return UIFont(name: name as String, size: 21) + }() + + static func image(_ glyph: String) -> UIImage? { + guard let font else { return nil } + let text = NSAttributedString(string: glyph, attributes: [.font: font, .foregroundColor: UIColor.white]) + return UIGraphicsImageRenderer(size: CGSize(width: 24, height: 24)).image { _ in + let size = text.size() + text.draw(at: CGPoint(x: (24 - size.width) / 2, y: (24 - size.height) / 2)) + }.withRenderingMode(.alwaysTemplate) + } +} diff --git a/platforms/ios/runner/lib/preview/PreviewViewController.swift b/platforms/ios/runner/lib/preview/PreviewViewController.swift new file mode 100644 index 0000000000..63c316e56c --- /dev/null +++ b/platforms/ios/runner/lib/preview/PreviewViewController.swift @@ -0,0 +1,156 @@ +import UIKit +import WebKit + +@MainActor +final class PreviewViewController: UIViewController { + let webView: WKWebView + let initialURL: URL + let consoleOnly: Bool + let theme: [String: Any] + let address = UITextField() + let content = UIView() + let toolbar = UIStackView() + let progress = UIActivityIndicatorView(style: .medium) + let menuButton = UIButton(type: .system) + var consoleVisible = false + var consoleAvailable = false + var disableCache = false + var showTools = true + var allowsDownloads = true + var externalSchemesAllowed = true + var navigationPolicy: ((WKNavigationAction) -> Bool)? + var onPageFinished: (() -> Void)? + var onTitleChanged: ((String) -> Void)? + var consoleEnabled = true + var viewport: CGSize? + var viewportScale: CGFloat = 1 + var onExternal: ((URL) -> Void)? + var onClose: (() -> Void)? + var pendingDialog: (() -> Void)? + weak var auxiliaryPresenter: UIViewController? + weak var activeDialog: UIAlertController? + private(set) var isClosed = false + private var observations: [NSKeyValueObservation] = [] + private var contextMenu: WebContextMenu? + private var contentBottom: NSLayoutConstraint? + private var contentFollowsKeyboard = true + + init(url: URL, theme: [String: Any], console: Bool) { + initialURL = url + self.theme = theme + consoleOnly = console + let configuration = WKWebViewConfiguration() + configuration.websiteDataStore = WKWebsiteDataStore(forIdentifier: UUID(uuidString: "A0C0DE00-0000-4000-8000-000000000001")!) + configuration.allowsInlineMediaPlayback = true + configuration.preferences.isElementFullscreenEnabled = true + webView = WKWebView(frame: .zero, configuration: configuration) + super.init(nibName: nil, bundle: nil) + contextMenu = WebContextMenu(webView: webView) + modalPresentationStyle = .fullScreen + } + + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + override func viewDidLoad() { + super.viewDidLoad() + let background = (theme["primaryColor"] as? String).flatMap(UIColor.init(hexString:)) ?? .systemBackground + let foreground = (theme["primaryTextColor"] as? String).flatMap(UIColor.init(hexString:)) ?? .label + view.backgroundColor = background + if theme["type"] as? String == "dark" { overrideUserInterfaceStyle = .dark } + if theme["type"] as? String == "light" { overrideUserInterfaceStyle = .light } + view.tintColor = foreground + content.clipsToBounds = true + webView.navigationDelegate = self + webView.uiDelegate = self + webView.allowsBackForwardNavigationGestures = true + webView.scrollView.contentInsetAdjustmentBehavior = .never + #if DEBUG + webView.isInspectable = true + #endif + configureToolbar(foreground: foreground) + for child in [toolbar, content] { child.translatesAutoresizingMaskIntoConstraints = false; view.addSubview(child) } + content.addSubview(webView) + contentBottom = content.bottomAnchor.constraint(equalTo: view.keyboardLayoutGuide.topAnchor) + contentBottom?.isActive = true + NSLayoutConstraint.activate([ + toolbar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), + toolbar.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), + toolbar.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), toolbar.heightAnchor.constraint(equalToConstant: 45), + content.topAnchor.constraint(equalTo: toolbar.bottomAnchor), content.leadingAnchor.constraint(equalTo: toolbar.leadingAnchor), + content.trailingAnchor.constraint(equalTo: toolbar.trailingAnchor), + ]) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameChanged), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) + observations = [ + webView.observe(\.canGoBack, options: [.new]) { [weak self] _, _ in MainActor.assumeIsolated { self?.updateMenu() } }, + webView.observe(\.canGoForward, options: [.new]) { [weak self] _, _ in MainActor.assumeIsolated { self?.updateMenu() } }, + webView.observe(\.title, options: [.new]) { [weak self] view, _ in + MainActor.assumeIsolated { self?.updateAddress(); self?.onTitleChanged?(view.title ?? "") } + }, + webView.observe(\.fullscreenState, options: [.new]) { [weak self] view, _ in + MainActor.assumeIsolated { if view.fullscreenState == .notInFullscreen { self?.view.setNeedsLayout() } } + }, + ] + updateMenu() + load(initialURL) + } + + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + guard webView.superview === content else { return } + let size = viewport ?? content.bounds.size + let scale = viewport == nil ? 1 : min(content.bounds.width / max(size.width, 1), content.bounds.height / max(size.height, 1)) * viewportScale + webView.transform = .identity + webView.bounds = CGRect(origin: .zero, size: size) + webView.center = CGPoint(x: content.bounds.midX, y: content.bounds.midY) + webView.transform = CGAffineTransform(scaleX: scale, y: scale) + } + + func load(_ url: URL) { + guard ["http", "https"].contains(url.scheme?.lowercased() ?? "") else { return } + prepareNavigation { [weak self] in + guard let self else { return } + self.webView.load(URLRequest(url: url, cachePolicy: self.disableCache ? .reloadIgnoringLocalCacheData : .useProtocolCachePolicy)) + } + } + + func prepareNavigation(_ action: @escaping @MainActor @Sendable () -> Void) { + guard !isClosed else { return } + if disableCache { + webView.configuration.websiteDataStore.removeData(ofTypes: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache, WKWebsiteDataTypeFetchCache], modifiedSince: .distantPast) { [weak self] in + guard let self, !self.isClosed else { return } + action() + } + } else { action() } + } + + var dialogPresenter: UIViewController? { isClosed ? nil : (isViewLoaded && view.window != nil ? self : auxiliaryPresenter) } + + @objc private func keyboardFrameChanged(_ notification: Notification) { + guard !isClosed, let window = viewIfLoaded?.window, + let frame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return } + // iOS 26 can leave the keyboard guide above the safe area after dismissal. + let visible = view.bounds.intersection(view.convert(frame, from: window.screen.coordinateSpace)).height > 0 + guard visible != contentFollowsKeyboard else { return } + contentFollowsKeyboard = visible + let anchor = visible ? view.keyboardLayoutGuide.topAnchor : view.safeAreaLayoutGuide.bottomAnchor + contentBottom?.isActive = false + contentBottom = content.bottomAnchor.constraint(equalTo: anchor) + contentBottom?.isActive = true + let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double ?? 0 + let curve = notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt ?? 0 + UIView.animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions(rawValue: curve << 16)) { + self.view.layoutIfNeeded() + } + } + + @objc func close() { + isClosed = true + pendingDialog?(); pendingDialog = nil + let dialog = activeDialog; activeDialog = nil + webView.stopLoading() + let completion = onClose; onClose = nil + if let presenter = presentingViewController { presenter.dismiss(animated: true) { completion?() } } + else if let dialog, dialog.presentingViewController != nil { dialog.dismiss(animated: false) { completion?() } } + else { completion?() } + } +} diff --git a/platforms/ios/runner/lib/preview/ServerService.swift b/platforms/ios/runner/lib/preview/ServerService.swift new file mode 100644 index 0000000000..92775e32d4 --- /dev/null +++ b/platforms/ios/runner/lib/preview/ServerService.swift @@ -0,0 +1,111 @@ +import Foundation + +final class ServerService: BaseService { + private final class Server { + let transport: LocalHTTPServer + var handler: Callback? + var replacementHandler: Callback? + var pending: [String: (LocalHTTPRequest, LocalHTTPConnection)] = [:] + var starters: [Callback] = [] + var ready = false + init(_ transport: LocalHTTPServer) { self.transport = transport } + } + + private let queue = DispatchQueue(label: "app.acode.preview") + private var servers: [Int: Server] = [:] + private var stopping: [Int: Server] = [:] + + override func reset() { + queue.async { + let active = Array(self.servers.values) + self.servers.removeAll() + for server in active { server.handler?.release(); server.transport.stop() } + for server in self.stopping.values { + server.replacementHandler?.release(); server.replacementHandler = nil + for callback in server.starters { callback.error("Server stopped") } + server.starters.removeAll() + } + } + } + + override func exec(action: String, args: [Any], callback: Callback) { + queue.async { [self] in + guard let port = args[safe: 0] as? Int, (1...65535).contains(port) else { callback.error("Invalid server port"); return } + do { + switch action { + case "start": try self.start(port, callback: callback) + case "stop": + guard let server = self.servers.removeValue(forKey: port) else { callback.error("Server not started on port \(port)"); return } + server.handler?.release() + self.stopping[port] = server + server.transport.stop { [weak self] in + guard let self else { return } + self.stopping.removeValue(forKey: port) + callback.success() + let starters = server.starters; server.starters.removeAll() + for starter in starters { + do { try self.start(port, callback: starter) } + catch { starter.error(error.localizedDescription) } + } + if let replacement = self.servers[port] { replacement.handler = server.replacementHandler } + else { server.replacementHandler?.release() } + server.replacementHandler = nil + } + case "setOnRequestHandler": + if let server = self.servers[port] { + server.handler?.release(); server.handler = callback + } else if let server = self.stopping[port], !server.starters.isEmpty { + server.replacementHandler?.release(); server.replacementHandler = callback + } else { callback.error("Server not started on port \(port)") } + case "send": + guard let server = self.servers[port] else { callback.error("Server not running"); return } + guard let id = args[safe: 1] as? String, let (request, client) = server.pending.removeValue(forKey: id), + let response = args[safe: 2] as? [String: Any] else { callback.error("Invalid preview response"); return } + do { try PreviewResponse.send(response, request: request, client: client); callback.success() } + catch { + client.respond(status: FileFailure.code(error) == 1 ? 404 : 403) + callback.error(error.localizedDescription) + } + default: callback.error("Unknown Server action: \(action)") + } + } catch { callback.error(error.localizedDescription) } + } + } + + private func start(_ port: Int, callback: Callback) throws { + if let server = stopping[port] { server.starters.append(callback); return } + if let server = servers[port] { + if server.ready { callback.success("Server started on port \(port)") } + else { server.starters.append(callback) } + return + } + let server = Server(try LocalHTTPServer(port: port, queue: queue)) + servers[port] = server + server.starters.append(callback) + server.transport.onRequest = { [weak server] request, client in + guard let server, let handler = server.handler else { client.respond(status: 503); return } + server.pending[client.id] = (request, client) + let cleanup = client.onClose + client.onClose = { [weak server, weak client] in + cleanup?() + if let client { server?.pending.removeValue(forKey: client.id) } + } + var payload = request.payload + payload["requestId"] = client.id + handler.success(payload, keep: true) + } + server.transport.start { [weak self, weak server] result in + guard let server else { return } + let callbacks = server.starters + server.starters.removeAll() + switch result { + case .success: + server.ready = true + for callback in callbacks { callback.success("Server started on port \(port)") } + case .failure(let error): + if self?.servers[port] === server { self?.servers.removeValue(forKey: port); server.handler?.release() } + for callback in callbacks { callback.error(error.localizedDescription) } + } + } + } +} diff --git a/platforms/ios/runner/lib/purchases/IapPurchase.swift b/platforms/ios/runner/lib/purchases/IapPurchase.swift new file mode 100644 index 0000000000..92a9b1245e --- /dev/null +++ b/platforms/ios/runner/lib/purchases/IapPurchase.swift @@ -0,0 +1,76 @@ +import StoreKit + +struct IapPurchase { + let transaction: Transaction + let signedTransaction: String + var acknowledged = false + + init(_ result: VerificationResult<Transaction>) throws { + guard case .verified(let transaction) = result else { throw IapFailure(6) } + self.transaction = transaction + signedTransaction = result.jwsRepresentation + } + + var active: Bool { + transaction.revocationDate == nil && !transaction.isUpgraded && + (transaction.expirationDate.map { $0 > Date() } ?? true) && + [.consumable, .nonConsumable].contains(transaction.productType) + } + + var json: [String: Any] { + ["productIds": [transaction.productID], "orderId": String(transaction.id), + "purchaseTime": transaction.purchaseDate.timeIntervalSince1970 * 1000, + "purchaseToken": signedTransaction, "signature": String(signedTransaction.split(separator: ".").last ?? ""), + "purchaseState": active ? 1 : 0, "isAcknowledged": acknowledged, "developerPayload": "", + "store": "appstore", "transactionId": String(transaction.id), + "originalTransactionId": String(transaction.originalID), "environment": transaction.environment.rawValue, + "signedTransactionInfo": signedTransaction] + } + + static func product(_ product: Product) -> [String: Any] { + ["productId": product.id, "title": product.displayName, "description": product.description, + "price": product.displayPrice, "priceAmountMicros": NSDecimalNumber(decimal: product.price * 1_000_000).int64Value, + "priceCurrencyCode": product.priceFormatStyle.currencyCode, "type": "inapp", "store": "appstore"] + } + + static func reference(_ token: String) -> (id: UInt64, product: String, bundle: String)? { + let parts = token.split(separator: ".", omittingEmptySubsequences: false) + guard parts.count == 3, token.utf8.count <= 32_768 else { return nil } + var payload = String(parts[1]).replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") + payload += String(repeating: "=", count: (4 - payload.count % 4) % 4) + guard let bytes = Data(base64Encoded: payload), + let json = try? JSONSerialization.jsonObject(with: bytes) as? [String: Any], + let rawID = json["transactionId"] as? String, let id = UInt64(rawID), + let product = json["productId"] as? String, let bundle = json["bundleId"] as? String else { return nil } + // The token only selects a transaction. Ownership must come from verified StoreKit results. + // StoreKit can re-sign the same transaction between delivery and acknowledgement. + return (id, product, bundle) + } +} + +struct IapFailure: Error { + let code: Int + init(_ code: Int) { self.code = code } + + static func code(_ error: Error) -> Int { + if let error = error as? IapFailure { return error.code } + if error is CancellationError { return -1 } + if let error = error as? Product.PurchaseError { + switch error { + case .productUnavailable: return 4 + case .purchaseNotAllowed: return 3 + default: return 5 + } + } + if let error = error as? StoreKitError { + switch error { + case .userCancelled: return 1 + case .networkError: return 2 + case .notAvailableInStorefront, .notEntitled: return 3 + case .unsupported: return -2 + default: return 6 + } + } + return 6 + } +} diff --git a/platforms/ios/runner/lib/purchases/IapService.swift b/platforms/ios/runner/lib/purchases/IapService.swift new file mode 100644 index 0000000000..1f96f29fbc --- /dev/null +++ b/platforms/ios/runner/lib/purchases/IapService.swift @@ -0,0 +1,17 @@ +import StoreKit + +final class IapService: BaseService { + private var store: IapStore? + + override func exec(action: String, args: [Any], callback: Callback) { + DispatchQueue.main.async { [weak self] in + guard let self else { callback.error(-1); return } + if self.store == nil { self.store = IapStore() } + self.store?.exec(action: action, args: args, callback: callback, presenter: self.viewController) + } + } + + override func reset() { + DispatchQueue.main.async { [weak self] in self?.store?.reset(); self?.store = nil } + } +} diff --git a/platforms/ios/runner/lib/purchases/IapStore.swift b/platforms/ios/runner/lib/purchases/IapStore.swift new file mode 100644 index 0000000000..530fd695ee --- /dev/null +++ b/platforms/ios/runner/lib/purchases/IapStore.swift @@ -0,0 +1,127 @@ +import StoreKit +import UIKit + +@MainActor +final class IapStore { + private var listener: Callback? + private var updates: Task<Void, Never>? + private var operations: [UUID: Task<Void, Never>] = [:] + private var delivered = Set<String>() + private var purchasing = false + + func exec(action: String, args: [Any], callback: Callback, presenter: UIViewController?) { + if action == "setPurchaseUpdatedListener" { + listener?.release(); listener = callback; delivered.removeAll(); listen(); return + } + if action == "startConnection" { + if AppStore.canMakePayments { listen(); callback.success(0) } + else { callback.error(3) } + return + } + let id = UUID() + operations[id] = Task { [weak self] in + guard let self else { return } + defer { self.operations.removeValue(forKey: id) } + do { + switch action { + case "getProducts": + guard let ids = args[safe: 0] as? [String], ids.allSatisfy({ !$0.isEmpty }) else { throw IapFailure(5) } + let products = try await Product.products(for: ids).filter { [.consumable, .nonConsumable].contains($0.type) } + try Task.checkCancellation() + callback.success(products.map(IapPurchase.product)) + case "getPurchases": callback.success(try await purchases().map(\.json)) + case "restorePurchases": + try await AppStore.sync() + callback.success(try await purchases().map(\.json)) + case "consume", "acknowledgePurchase": + guard let token = args[safe: 0] as? String, + let reference = IapPurchase.reference(token), + let purchase = try await purchases().first(where: { + $0.transaction.id == reference.id && $0.transaction.productID == reference.product && + $0.transaction.appBundleID == reference.bundle + }) else { throw IapFailure(8) } + if action == "consume" && purchase.transaction.productType != .consumable { throw IapFailure(5) } + try Task.checkCancellation() + await purchase.transaction.finish() + callback.success(action == "consume" ? 0 : nil) + case "purchase": try await purchase(args[safe: 0] as? String, callback: callback, presenter: presenter) + default: throw IapFailure(5) + } + } catch { callback.error(IapFailure.code(error)) } + } + } + + func reset() { + updates?.cancel(); updates = nil + for operation in operations.values { operation.cancel() } + operations.removeAll() + listener?.release(); listener = nil + delivered.removeAll() + } + + private func listen() { + guard updates == nil else { return } + updates = Task { [weak self] in + for await result in Transaction.updates { + guard !Task.isCancelled else { return } + self?.receive(result) + } + } + } + + private func purchases() async throws -> [IapPurchase] { + var found: [UInt64: IapPurchase] = [:] + for await result in Transaction.currentEntitlements { + try Task.checkCancellation() + var purchase = try IapPurchase(result) + purchase.acknowledged = true + if purchase.active { found[purchase.transaction.id] = purchase } + } + for await result in Transaction.unfinished { + try Task.checkCancellation() + let purchase = try IapPurchase(result) + if purchase.active { found[purchase.transaction.id] = purchase } + } + return found.values.sorted { $0.transaction.purchaseDate > $1.transaction.purchaseDate } + } + + private func purchase(_ productID: String?, callback: Callback, presenter: UIViewController?) async throws { + guard AppStore.canMakePayments else { throw IapFailure(3) } + guard !purchasing, let productID, !productID.isEmpty else { throw IapFailure(5) } + guard let presenter, presenter.view.window?.windowScene?.activationState == .foregroundActive else { throw IapFailure(-1) } + purchasing = true + defer { purchasing = false } + guard let product = try await Product.products(for: [productID]).first, + [.consumable, .nonConsumable].contains(product.type) else { throw IapFailure(4) } + if product.type == .nonConsumable, try await purchases().contains(where: { $0.transaction.productID == productID }) { throw IapFailure(7) } + try Task.checkCancellation() + listen() + callback.success() + // The existing API acknowledges launching the flow separately from its outcome. + do { + let result = try await product.purchase(confirmIn: presenter) + try Task.checkCancellation() + switch result { + case .success(let verified): receive(verified) + case .userCancelled: listener?.error(1, keep: true) + case .pending: listener?.success([["productIds": [productID], "purchaseState": 2, "isAcknowledged": false, "purchaseToken": "", "store": "appstore"]], keep: true) + @unknown default: listener?.error(6, keep: true) + } + } catch { + if !Task.isCancelled { listener?.error(IapFailure.code(error), keep: true) } + } + } + + private func receive(_ result: VerificationResult<Transaction>) { + guard let listener else { return } + do { + let purchase = try IapPurchase(result) + let transaction = purchase.transaction + let key = "\(transaction.id):\(transaction.revocationDate?.timeIntervalSince1970 ?? 0):\(transaction.isUpgraded)" + guard delivered.insert(key).inserted else { return } + listener.success([purchase.json], keep: true) + } catch { listener.error(IapFailure.code(error), keep: true) } + } + + deinit { updates?.cancel(); for operation in operations.values { operation.cancel() } } +} diff --git a/platforms/ios/runner/lib/security/AppAuthentication.swift b/platforms/ios/runner/lib/security/AppAuthentication.swift new file mode 100644 index 0000000000..cf3a620b57 --- /dev/null +++ b/platforms/ios/runner/lib/security/AppAuthentication.swift @@ -0,0 +1,107 @@ +import CryptoKit +import Foundation +import WebKit + +struct AppAuthentication { + static let origin = "https://acode.app" + static let hosts = ["acode.app", "dev.acode.app"] + let secrets: SecretStore + + init(namespace: String = "acode_auth_secure") { secrets = SecretStore(namespace: namespace) } + + static func accepts(_ url: URL) -> Bool { + url.scheme == "https" && hosts.contains(url.host ?? "") && (url.port == nil || url.port == 443) && url.user == nil && url.password == nil + } + + func begin(baseURL: String, version: Int) throws -> URL { + let base = try Self.baseURL(baseURL) + let state = try SecureToken.generate(bytes: 24) + let verifier = try SecureToken.generate() + let challenge = SHA256.hash(data: Data(verifier.utf8)).map { String(format: "%02x", $0) }.joined() + let pending = try JSONSerialization.data(withJSONObject: ["state": state, "verifier": verifier, "origin": base.absoluteString]) + try secrets.set("pending_login", value: String(decoding: pending, as: UTF8.self)) + var url = URLComponents(url: base.appendingPathComponent("login"), resolvingAgainstBaseURL: false)! + url.queryItems = ["redirect": "app", "authFlow": "app-code", "state": state, "challenge": challenge, "appVersionCode": String(version), "src": "ios"].map { URLQueryItem(name: $0.key, value: $0.value) } + return url.url! + } + + func consume(_ url: URL) throws -> URLRequest { + guard url.scheme == "acode", url.host == "auth", url.path == "/callback", url.user == nil, url.port == nil, + let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems, + items.filter({ $0.name == "code" }).count == 1, items.filter({ $0.name == "state" }).count == 1, + let code = items.first(where: { $0.name == "code" })?.value, !code.isEmpty, + let state = items.first(where: { $0.name == "state" })?.value, !state.isEmpty, + let pending = try JSONSerialization.jsonObject(with: Data(secrets.get("pending_login").utf8)) as? [String: String], + SecureToken.matches(state, pending["state"]), let verifier = pending["verifier"], !verifier.isEmpty else { + throw SecretFailure("Invalid sign-in callback") + } + let base = try Self.baseURL(pending["origin"] ?? Self.origin) + try cancel() + var request = URLRequest(url: base.appendingPathComponent("api/user/app-token/exchange")) + request.httpMethod = "POST" + request.httpShouldHandleCookies = false + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.httpBody = try JSONSerialization.data(withJSONObject: ["code": code, "state": state, "verifier": verifier]) + return request + } + + func token(for url: URL) throws -> String { try secrets.get(Self.tokenKey(for: url)) } + + static func accountURL(baseURL: String) throws -> URL { + let base = try Self.baseURL(baseURL) + var url = URLComponents(url: base.appendingPathComponent("profile/edit"), resolvingAgainstBaseURL: false)! + url.queryItems = [URLQueryItem(name: "src", value: "ios")] + return url.url! + } + + func save(_ token: String, for url: URL = URL(string: Self.origin)!) throws { + guard !token.isEmpty, token.utf8.allSatisfy({ $0 == 0x21 || (0x23...0x2b).contains($0) || (0x2d...0x3a).contains($0) || (0x3c...0x5b).contains($0) || (0x5d...0x7e).contains($0) }) else { + throw SecretFailure("Invalid sign-in token") + } + try secrets.set(Self.tokenKey(for: url), value: token) + } + + func cancel() throws { try secrets.remove("pending_login") } + func logout() throws { try cancel(); try secrets.remove("auth_token"); try secrets.remove("auth_token_dev") } + + @MainActor + func synchronizeCookies(_ store: WKHTTPCookieStore) async throws { + for cookie in HTTPCookieStorage.shared.cookies ?? [] where cookie.name == "token" && Self.hosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { + HTTPCookieStorage.shared.deleteCookie(cookie) + } + for cookie in await store.allCookies() where cookie.name == "token" && Self.hosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { + await store.deleteCookie(cookie) + } + for host in Self.hosts { + let token = try token(for: URL(string: "https://" + host)!) + if !token.isEmpty, let cookie = HTTPCookie(properties: [.name: "token", .value: token, .domain: host, .path: "/", .secure: "TRUE", .expires: Date.distantFuture, HTTPCookiePropertyKey("HttpOnly"): "TRUE", HTTPCookiePropertyKey("SameSite"): "None"]) { + await store.setCookie(cookie) + HTTPCookieStorage.shared.setCookie(cookie) + } + } + } + + static func baseURL(_ value: String) throws -> URL { + guard let url = URL(string: value), accepts(url), ["", "/"].contains(url.path), url.query == nil, url.fragment == nil else { + throw SecretFailure("Unsupported sign-in URL") + } + return URL(string: "https://" + url.host!)! + } + + static func exchangeFailure(_ response: HTTPURLResponse) -> SecretFailure { + if response.statusCode == 429 { + if let seconds = Int(response.value(forHTTPHeaderField: "Retry-After") ?? ""), seconds > 0 { + let minutes = (min(seconds, 86400) + 59) / 60 + return SecretFailure("Too many sign-in attempts. Please wait \(minutes) minute(s) and try again.") + } + return SecretFailure("Too many sign-in attempts. Please wait before trying again.") + } + if [400, 401].contains(response.statusCode) { return SecretFailure("Sign-in expired. Please try again.") } + return SecretFailure("The sign-in service is unavailable. Please try again later.") + } + + private static func tokenKey(for url: URL) throws -> String { + guard accepts(url) else { throw SecretFailure("Unsupported sign-in URL") } + return url.host == "acode.app" ? "auth_token" : "auth_token_dev" + } +} diff --git a/platforms/ios/runner/lib/security/AuthenticatorService.swift b/platforms/ios/runner/lib/security/AuthenticatorService.swift new file mode 100644 index 0000000000..ce6c509c55 --- /dev/null +++ b/platforms/ios/runner/lib/security/AuthenticatorService.swift @@ -0,0 +1,135 @@ +import AuthenticationServices +import WebKit + +final class AuthenticatorService: BaseService { + private var coordinator: SignInCoordinator! + + required init(bridge: Bridge) { + super.init(bridge: bridge) + DispatchQueue.main.async { [self] in + self.coordinator = SignInCoordinator(bridge: bridge) + IncomingLinks.shared.authenticationHandler = { [weak self] in self?.coordinator.receive($0) } + } + } + + override func exec(action: String, args: [Any], callback: Callback) { + DispatchQueue.main.async { self.coordinator.exec(action: action, args: args, callback: callback) } + } + + override func reset() { DispatchQueue.main.async { self.coordinator?.cancel() } } +} + +@MainActor +private final class SignInCoordinator: NSObject, ASWebAuthenticationPresentationContextProviding { + private weak var bridge: Bridge? + private let auth = AppAuthentication() + private var session: ASWebAuthenticationSession? + private var exchange: HTTPTransport? + private var callback: Callback? + private var operation = UUID() + + init(bridge: Bridge) { + self.bridge = bridge + super.init() + Task { try? await auth.synchronizeCookies(bridge.webView!.configuration.websiteDataStore.httpCookieStore) } + } + + func exec(action: String, args: [Any], callback: Callback) { + switch action { + case "login", "openAccount": + cancel() + do { + let options = args[safe: 0] as? [String: Any] ?? [:] + let account = action == "openAccount" + let baseURL = options["baseUrl"] as? String ?? AppAuthentication.origin + let url = try account ? AppAuthentication.accountURL(baseURL: baseURL) : auth.begin(baseURL: baseURL, version: options["appVersionCode"] as? Int ?? 0) + self.callback = callback + let id = operation + let session = ASWebAuthenticationSession(url: url, callbackURLScheme: "acode") { [weak self] url, error in + Task { @MainActor in + guard let self, self.operation == id else { return } + if account { + if let error, (error as? ASWebAuthenticationSessionError)?.code != .canceledLogin { + self.fail(error.localizedDescription); return + } + self.callback = nil; self.session = nil + callback.success() + } + else if let url { self.receive(url) } + else if (error as? ASWebAuthenticationSessionError)?.code == .canceledLogin { + self.fail("Sign-in was cancelled. You can try again.") + } + else { self.fail(error?.localizedDescription ?? "Sign-in cancelled") } + } + } + session.presentationContextProvider = self + self.session = session + if !session.start() { fail(account ? "Unable to open account settings" : "Unable to open sign-in") } + } catch { self.callback = nil; callback.error(error.localizedDescription) } + case "saveToken", "logout": + cancel() + Task { + do { + if action == "logout" { try auth.logout() } + else { try auth.save(args[safe: 0] as? String ?? "") } + if let store = bridge?.webView?.configuration.websiteDataStore.httpCookieStore { try await auth.synchronizeCookies(store) } + callback.success() + } catch { callback.error(error.localizedDescription) } + } + default: callback.error("Unsupported Authenticator action: \(action)") + } + } + + func receive(_ url: URL) { + guard exchange == nil else { return } + do { + let request = try auth.consume(url) + let id = operation + let transport = HTTPTransport(request: request, followRedirects: false, connectTimeout: 15, readTimeout: 30) + var data = Data() + transport.onResponse = { response in + guard (200..<300).contains(response.statusCode) else { throw AppAuthentication.exchangeFailure(response) } + } + transport.onData = { bytes in + guard data.count + bytes.count <= 65536 else { throw SecretFailure("Invalid sign-in response") } + data.append(bytes) + } + transport.onComplete = { [weak self] error in + Task { @MainActor in + guard let self, self.operation == id else { return } + do { + if let error { throw error } + let response = try JSONSerialization.jsonObject(with: data) as? [String: Any] + try self.auth.save(response?["token"] as? String ?? "", for: request.url!) + if let store = self.bridge?.webView?.configuration.websiteDataStore.httpCookieStore { try await self.auth.synchronizeCookies(store) } + guard self.operation == id else { return } + let callback = self.callback + self.callback = nil; self.exchange = nil; self.session = nil + callback?.success() + } catch { + self.fail((error as? SecretFailure)?.message ?? "Sign-in could not be completed. Please check your connection and try again.") + } + } + } + exchange = transport + transport.start() + } catch { fail("Invalid sign-in callback") } + } + + func cancel() { + operation = UUID() + session?.cancel(); session = nil + exchange?.cancel(); exchange = nil + callback?.error("Sign-in cancelled"); callback = nil + try? auth.cancel() + } + + func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { + bridge?.viewController?.view.window ?? ASPresentationAnchor() + } + + private func fail(_ message: String) { + callback?.error(message); callback = nil + cancel() + } +} diff --git a/platforms/ios/runner/lib/security/PluginContextService.swift b/platforms/ios/runner/lib/security/PluginContextService.swift new file mode 100644 index 0000000000..9ef1a6d57d --- /dev/null +++ b/platforms/ios/runner/lib/security/PluginContextService.swift @@ -0,0 +1,31 @@ +import Foundation + +final class PluginContextService: BaseService { + private let sessions = PluginSessions() + + override func reset() { sessions.reset() } + + override func exec(action: String, args: [Any], callback: Callback) { + do { + let token = args[safe: 0] as? String ?? "" + switch action { + case "establishConnection": callback.success(try sessions.establish()) + case "requestToken": callback.success(try sessions.issue(session: token, pluginID: args[safe: 1] as? String ?? "", manifest: args[safe: 2] as? String ?? "")) + case "invalidate": try sessions.invalidate(token); callback.success() + case "grantedPermission": callback.success(try sessions.permissions(for: token).contains(args[safe: 1] as? String ?? "") ? 1 : 0) + case "listAllPermissions": callback.success(try sessions.permissions(for: token)) + case "get_secret", "set_secret", "delete_secret", "clear_all_secrets": + let pluginID = try sessions.plugin(for: token) + let store = SecretStore(namespace: "plugin." + Data(pluginID.utf8).base64EncodedString()) + let key = args[safe: 1] as? String ?? "" + switch action { + case "get_secret": callback.success(try store.get(key, default: args[safe: 2] as? String ?? "")) + case "set_secret": try store.set(key, value: args[safe: 2] as? String ?? ""); callback.success() + case "delete_secret": try store.remove(key); callback.success() + default: try store.clear(); callback.success() + } + default: callback.error("Unknown plugin context action: \(action)") + } + } catch { callback.error(error.localizedDescription) } + } +} diff --git a/platforms/ios/runner/lib/security/PluginSessions.swift b/platforms/ios/runner/lib/security/PluginSessions.swift new file mode 100644 index 0000000000..5d6d92e8c2 --- /dev/null +++ b/platforms/ios/runner/lib/security/PluginSessions.swift @@ -0,0 +1,36 @@ +import Foundation + +final class PluginSessions { + private var session: String? + private var plugins: [String: (token: String, permissions: [String])] = [:] + + func establish() throws -> String { + guard session == nil else { throw SecretFailure("CONNECTION_ALREADY_ESTABLISHED") } + let token = try SecureToken.generate() + session = token + return token + } + + func issue(session: String, pluginID: String, manifest: String) throws -> String { + guard SecureToken.matches(session, self.session) else { throw SecretFailure("INVALID_SESSION") } + guard !pluginID.isEmpty, let data = manifest.data(using: .utf8), + let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw SecretFailure("INVALID_PLUGIN_JSON") } + let permissions: [String] + if let requested = json["permissions"], !(requested is NSNull) { + guard let values = requested as? [String] else { throw SecretFailure("INVALID_PLUGIN_JSON") } + permissions = values + } else { permissions = [] } + let token = try plugins[pluginID]?.token ?? SecureToken.generate() + plugins[pluginID] = (token, permissions) + return token + } + + func plugin(for token: String) throws -> String { + guard let plugin = plugins.first(where: { SecureToken.matches($0.value.token, token) })?.key else { throw SecretFailure("INVALID_TOKEN") } + return plugin + } + + func permissions(for token: String) throws -> [String] { plugins[try plugin(for: token)]!.permissions } + func invalidate(_ token: String) throws { plugins.removeValue(forKey: try plugin(for: token)) } + func reset() { session = nil; plugins.removeAll() } +} diff --git a/platforms/ios/runner/lib/security/SecretStore.swift b/platforms/ios/runner/lib/security/SecretStore.swift new file mode 100644 index 0000000000..0b1e62183d --- /dev/null +++ b/platforms/ios/runner/lib/security/SecretStore.swift @@ -0,0 +1,73 @@ +import Foundation +import Security + +struct SecretStore { + let namespace: String + + func get(_ key: String, default fallback: String = "") throws -> String { + var query = query(key) + query[kSecReturnData as String] = true + query[kSecMatchLimit as String] = kSecMatchLimitOne + var result: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &result) + if status == errSecItemNotFound { return fallback } + try check(status) + guard let data = result as? Data, let value = String(data: data, encoding: .utf8) else { throw SecretFailure("Invalid stored secret") } + return value + } + + func set(_ key: String, value: String) throws { + let query = query(key) + let data = Data(value.utf8) + let status = SecItemUpdate(query as CFDictionary, [kSecValueData: data] as CFDictionary) + if status == errSecItemNotFound { + var item = query + item[kSecValueData as String] = data + item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly + try check(SecItemAdd(item as CFDictionary, nil)) + } else { try check(status) } + } + + func remove(_ key: String) throws { try delete(query(key)) } + func clear() throws { try delete(query(nil)) } + + private func query(_ key: String?) -> [String: Any] { + var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: (Bundle.main.bundleIdentifier ?? "app.acode") + "." + namespace, + kSecAttrSynchronizable as String: false] + if let key { query[kSecAttrAccount as String] = key } + return query + } + + private func delete(_ query: [String: Any]) throws { + let status = SecItemDelete(query as CFDictionary) + if status != errSecItemNotFound { try check(status) } + } + + private func check(_ status: OSStatus) throws { + if status != errSecSuccess { throw SecretFailure("Keychain operation failed (\(status))") } + } +} + +struct SecretFailure: LocalizedError { + let message: String + init(_ message: String) { self.message = message } + var errorDescription: String? { message } +} + +struct SecureToken { + static func generate(bytes: Int = 32) throws -> String { + var data = [UInt8](repeating: 0, count: bytes) + guard SecRandomCopyBytes(kSecRandomDefault, data.count, &data) == errSecSuccess else { throw SecretFailure("Cannot generate a secure token") } + return data.map { String(format: "%02x", $0) }.joined() + } + + static func matches(_ first: String?, _ second: String?) -> Bool { + guard let first, let second else { return false } + let a = Array(first.utf8), b = Array(second.utf8) + guard a.count == b.count else { return false } + var difference: UInt8 = 0 + for index in a.indices { difference |= a[index] ^ b[index] } + return difference == 0 + } +} diff --git a/platforms/ios/runner/lib/ssh/SFTPClient.swift b/platforms/ios/runner/lib/ssh/SFTPClient.swift new file mode 100644 index 0000000000..37689ee930 --- /dev/null +++ b/platforms/ios/runner/lib/ssh/SFTPClient.swift @@ -0,0 +1,152 @@ +import Foundation +import CSSH2 + +final class SFTPClient { + let connection: SSHConnection + let handle: OpaquePointer + let profileID: String + private(set) var directory = "" + + init(connection: SSHConnection, profileID: String) throws { + self.connection = connection; self.profileID = profileID + connection.begin() + handle = try connection.pointer { libssh2_sftp_init(connection.session) } + var buffer = [CChar](repeating: 0, count: 32768) + let count = try connection.integer { Int(libssh2_sftp_symlink_ex(handle, ".", 1, &buffer, UInt32(buffer.count), LIBSSH2_SFTP_REALPATH)) } + guard count > 0 else { throw connection.failure() } + directory = String(decoding: buffer.prefix(count).map { UInt8(bitPattern: $0) }, as: UTF8.self) + } + + deinit { connection.cleanup { libssh2_sftp_shutdown(handle) } } + + func path(_ value: String) throws -> String { + guard !value.contains("\0") else { throw SecretFailure("Invalid remote path") } + if value.hasPrefix("/") { return value } + return directory + (directory.hasSuffix("/") ? "" : "/") + value + } + + func attributes(_ path: String, follow: Bool = false) throws -> LIBSSH2_SFTP_ATTRIBUTES { + connection.begin() + var attributes = LIBSSH2_SFTP_ATTRIBUTES() + let result = try connection.integer { Int(libssh2_sftp_stat_ex(handle, path, UInt32(path.utf8.count), follow ? LIBSSH2_SFTP_STAT : LIBSSH2_SFTP_LSTAT, &attributes)) } + guard result == 0 else { throw failure() } + return attributes + } + + func list(_ path: String) throws -> [[String: Any]] { + connection.begin() + let folder = try connection.pointer { libssh2_sftp_open_ex(handle, path, UInt32(path.utf8.count), 0, 0, LIBSSH2_SFTP_OPENDIR) } + defer { close(folder) } + var entries: [[String: Any]] = [] + while true { + connection.begin() + var buffer = [CChar](repeating: 0, count: 32768), attributes = LIBSSH2_SFTP_ATTRIBUTES() + let count = try connection.integer { Int(libssh2_sftp_readdir_ex(folder, &buffer, buffer.count, nil, 0, &attributes)) } + if count == 0 { return entries } + guard count > 0 else { throw failure() } + let name = String(decoding: buffer.prefix(count).map { UInt8(bitPattern: $0) }, as: UTF8.self) + if name == "." || name == ".." { continue } + let child = path + (path.hasSuffix("/") ? "" : "/") + name + entries.append(try info(child, attributes: attributes)) + } + } + + func stat(_ path: String) throws -> [String: Any] { + do { return try info(path, attributes: attributes(path)) } + catch let error as SFTPFailure where error.code == LIBSSH2_FX_NO_SUCH_FILE || error.code == LIBSSH2_FX_NO_SUCH_PATH { + return ["exists": false, "url": path] + } + } + + func info(_ path: String, attributes: LIBSSH2_SFTP_ATTRIBUTES) throws -> [String: Any] { + let mode = attributes.permissions + let isLink = mode & 0o170000 == 0o120000 + var targetAttributes = attributes + var result: [String: Any] = ["name": (path as NSString).lastPathComponent, "url": path, "exists": true, + "canRead": mode & 0o400 != 0, "canWrite": mode & 0o200 != 0, "length": attributes.filesize, + "lastModified": attributes.mtime, "permissions": permissions(mode), "isLink": isLink] + if isLink { + var buffer = [CChar](repeating: 0, count: 32768) + let count = try connection.integer { Int(libssh2_sftp_symlink_ex(handle, path, UInt32(path.utf8.count), &buffer, UInt32(buffer.count), LIBSSH2_SFTP_READLINK)) } + if count > 0 { + result["linkTarget"] = String(decoding: buffer.prefix(count).map { UInt8(bitPattern: $0) }, as: UTF8.self) + } + do { targetAttributes = try self.attributes(path, follow: true) } + catch let error as SFTPFailure where error.code == LIBSSH2_FX_NO_SUCH_FILE || error.code == LIBSSH2_FX_NO_SUCH_PATH { + result["isFile"] = false; result["isDirectory"] = false; return result + } + } + result["isDirectory"] = targetAttributes.permissions & 0o170000 == 0o040000 + result["isFile"] = targetAttributes.permissions & 0o170000 == 0o100000 + return result + } + + func mkdir(_ path: String) throws { + connection.begin() + try check { libssh2_sftp_mkdir_ex(handle, path, UInt32(path.utf8.count), 0o755) } + } + + func rename(_ source: String, to destination: String) throws { + connection.begin() + try check { libssh2_sftp_rename_ex(handle, source, UInt32(source.utf8.count), destination, UInt32(destination.utf8.count), 0) } + } + + func remove(_ path: String, force: Bool, recursive: Bool) throws { + let attributes: LIBSSH2_SFTP_ATTRIBUTES + do { attributes = try self.attributes(path) } + catch let error as SFTPFailure where force && (error.code == LIBSSH2_FX_NO_SUCH_FILE || error.code == LIBSSH2_FX_NO_SUCH_PATH) { return } + if attributes.permissions & 0o170000 == 0o040000 { + if recursive { + for entry in try list(path) { try remove(entry["url"] as! String, force: force, recursive: true) } + } + connection.begin() + try check { libssh2_sftp_rmdir_ex(handle, path, UInt32(path.utf8.count)) } + } else { + connection.begin() + try check { libssh2_sftp_unlink_ex(handle, path, UInt32(path.utf8.count)) } + } + } + + func open(_ path: String, flags: Int32) throws -> OpaquePointer { + connection.begin() + return try connection.pointer { libssh2_sftp_open_ex(handle, path, UInt32(path.utf8.count), UInt(flags), 0o644, LIBSSH2_SFTP_OPENFILE) } + } + + @discardableResult + func close(_ file: OpaquePointer) -> Int32 { + connection.cleanup { libssh2_sftp_close_handle(file) } + } + + func withFile(_ path: String, flags: Int32, operation: (OpaquePointer) throws -> Void) throws { + let file = try open(path, flags: flags) + do { try operation(file) } + catch { close(file); throw error } + guard close(file) == 0 else { throw failure() } + } + + func check(_ operation: () -> Int32) throws { + if try connection.integer({ Int(operation()) }) < 0 { throw failure() } + } + + func failure() -> Error { + if libssh2_session_last_errno(connection.session) == LIBSSH2_ERROR_SFTP_PROTOCOL { + return SFTPFailure(code: libssh2_sftp_last_error(handle)) + } + return connection.failure() + } + + private func permissions(_ mode: UInt) -> String { + var value = mode & 0o170000 == 0o040000 ? "d" : mode & 0o170000 == 0o120000 ? "l" : "-" + for shift in [6, 3, 0] { + value += mode & (4 << shift) != 0 ? "r" : "-" + value += mode & (2 << shift) != 0 ? "w" : "-" + value += mode & (1 << shift) != 0 ? "x" : "-" + } + return value + } +} + +struct SFTPFailure: LocalizedError { + let code: UInt + var errorDescription: String? { [2: "Remote file was not found", 3: "Permission denied", 4: "Remote file operation failed", 11: "File already exists" ][Int(code)] ?? "SFTP error \(code)" } +} diff --git a/platforms/ios/runner/lib/ssh/SFTPConnections.swift b/platforms/ios/runner/lib/ssh/SFTPConnections.swift new file mode 100644 index 0000000000..82fb6ab2fd --- /dev/null +++ b/platforms/ios/runner/lib/ssh/SFTPConnections.swift @@ -0,0 +1,62 @@ +import Foundation + +extension SFTPService { + func connect(_ action: String, args: [Any], callback: Callback) throws { + let shell = action == "openShellUsingProfile" + let profileID = args[safe: 0] as? String ?? "" + let profile = try profiles.profile(profileID) + let suppliedID = !shell ? args[safe: 1] as? String ?? "" : "" + let requestID = suppliedID.isEmpty ? UUID().uuidString : suppliedID + guard attempts[requestID] == nil else { throw SecretFailure("An SFTP connection with this request ID is already running") } + let attempt = SSHAttempt(callback: callback, shell: shell) + if !shell { + for previous in attempts.values where !previous.shell { previous.cancel() } + generation = UUID() + } + let currentGeneration = generation + attempts[requestID] = attempt + let timeout = shell ? 10 : min(30, max(1, (args[safe: 2] as? Double ?? 10000) / 1000)) + DispatchQueue.global(qos: .userInitiated).async { [self] in + do { + let connection = try SSHConnection(cancellation: attempt.cancellation) + try connection.connect(profile, timeout: timeout) { [self] key, algorithm in + try self.profiles.verify(endpoint: profile.endpoint, key: key, algorithm: algorithm) { [self] fingerprint in + try SSHPrompts.confirm(title: "Unknown SSH host", message: "This is the first connection to \(profile.endpoint).\n\nKey type: \(algorithm)\nFingerprint: \(fingerprint)\n\nVerify this fingerprint before trusting the host.", button: "Trust and connect", presenter: { [weak self] in self?.viewController }, cancellation: attempt.cancellation) + } + } + if shell { + let terminal = try SSHShell(connection: connection, columns: SSHShell.dimension(args[safe: 1], default: 80), rows: SSHShell.dimension(args[safe: 2], default: 24), callback: callback) + self.control.async { [self, terminal] in + self.attempts.removeValue(forKey: requestID) + guard (try? attempt.cancellation.check()) != nil else { terminal.close(); return } + terminal.onClose = { [weak self, weak terminal] in + guard let self, let id = terminal?.id else { return } + self.control.async { self.shells.removeValue(forKey: id) } + } + self.shells[terminal.id] = terminal + attempt.finish { terminal.start() } + } + } else { + let client = try SFTPClient(connection: connection, profileID: profileID) + self.control.async { + guard self.generation == currentGeneration, (try? attempt.cancellation.check()) != nil else { + self.attempts.removeValue(forKey: requestID); attempt.cancel(); return + } + self.activeCancellation?.cancel() + self.activeCancellation = attempt.cancellation + self.operations.async { + defer { self.control.async { self.attempts.removeValue(forKey: requestID) } } + guard (try? attempt.cancellation.check()) != nil else { attempt.cancel(); return } + self.client = client + attempt.finish { callback.success(action == "testProfile" ? client.directory : nil) } + } + } + } + } catch { + if let failure = error as? SSHFailure { SSHPrompts.changed(failure, presenter: { [weak self] in self?.viewController }) } + self.control.async { self.attempts.removeValue(forKey: requestID) } + attempt.finish { SSHFailure.report(error, to: callback) } + } + } + } +} diff --git a/platforms/ios/runner/lib/ssh/SFTPService.swift b/platforms/ios/runner/lib/ssh/SFTPService.swift new file mode 100644 index 0000000000..690268a110 --- /dev/null +++ b/platforms/ios/runner/lib/ssh/SFTPService.swift @@ -0,0 +1,109 @@ +import Foundation + +final class SFTPService: BaseService { + let profiles = SSHProfileStore() + let control = DispatchQueue(label: "app.acode.sftp.control") + let operations = DispatchQueue(label: "app.acode.sftp.files", qos: .userInitiated) + var attempts: [String: SSHAttempt] = [:] + var shells: [String: SSHShell] = [:] + var activeCancellation: SSHCancellation? + var client: SFTPClient? + var generation = UUID() + + override func exec(action: String, args: [Any], callback: Callback) { + control.async { + do { + let id = args[safe: 0] as? String ?? "" + switch action { + case "saveProfile", "editProfile": + let (id, profile) = try self.profiles.save(args, legacy: action == "saveProfile") + callback.success(action == "saveProfile" ? id : profile.info(id: id)) + case "getProfileInfo": callback.success(try self.profiles.profile(id).info(id: id)) + case "deleteProfile": try self.deleteProfile(id, callback: callback) + case "connectUsingProfile", "testProfile", "openShellUsingProfile": try self.connect(action, args: args, callback: callback) + case "cancelConnection": self.attempts[id]?.cancel(); callback.success() + case "writeShell", "resizeShell": + guard let shell = self.shells[id] else { throw SecretFailure("SSH shell is not connected") } + shell.perform(action, args: args, callback: callback) + case "closeShell": self.shells.removeValue(forKey: id)?.close(); callback.success() + case "close": + self.generation = UUID() + self.activeCancellation?.cancel(); self.activeCancellation = nil + for attempt in self.attempts.values where !attempt.shell { attempt.cancel() } + self.operations.async { self.client = nil; callback.success() } + default: self.fileAction(action, args: args, callback: callback) + } + } catch { SSHFailure.report(error, to: callback) } + } + } + + override func reset() { + control.async { + self.generation = UUID() + for attempt in self.attempts.values { attempt.cancel() } + self.attempts.removeAll() + for shell in self.shells.values { shell.close() } + self.shells.removeAll() + self.activeCancellation?.cancel(); self.activeCancellation = nil + self.operations.async { self.client = nil } + } + } + + private func fileAction(_ action: String, args: [Any], callback: Callback) { + operations.async { + do { + if action == "isConnected" { + callback.success(self.client?.connection.isConnected == true ? self.client!.profileID as Any : 0) + return + } + guard let client = self.client, client.connection.isConnected else { throw SecretFailure("Not connected") } + let path = try client.path(args[safe: 0] as? String ?? "") + switch action { + case "pwd": callback.success(client.directory) + case "lsDir": callback.success(try client.list(path)) + case "stat": callback.success(try client.stat(path)) + case "mkdir": try client.mkdir(path); callback.success() + case "rm": try client.remove(path, force: args[safe: 1] as? Bool ?? false, recursive: args[safe: 2] as? Bool ?? false); callback.success() + case "rename": try client.rename(path, to: client.path(args[safe: 1] as? String ?? "")); callback.success() + case "createFile": try client.create(path, contents: args[safe: 1] as? String ?? ""); callback.success() + case "getFile": try client.download(path, to: args[safe: 1] as? String ?? ""); callback.success() + case "putFile": try client.upload(args[safe: 1] as? String ?? "", to: path); callback.success() + case "exec": callback.success(try SSHChannel(connection: client.connection).execute(args[safe: 0] as? String ?? "")) + default: throw SecretFailure("SFTP action is not available: " + action) + } + } catch { SSHFailure.report(error, to: callback) } + } + } + + private func deleteProfile(_ id: String, callback: Callback) throws { + let profile = try profiles.profile(id) + let attempt = SSHAttempt(callback: callback, shell: true) + let requestID = UUID().uuidString + attempts[requestID] = attempt + DispatchQueue.global(qos: .userInitiated).async { [self] in + defer { self.control.async { self.attempts.removeValue(forKey: requestID) } } + do { + guard try SSHPrompts.confirm(title: "Delete saved SSH credentials?", message: "Remove the encrypted SFTP/SSH profile for \(profile.username)@\(profile.hostname)?", button: "Delete", destructive: true, presenter: { [weak self] in self?.viewController }, cancellation: attempt.cancellation) else { + throw SecretFailure("Profile deletion was cancelled") + } + try self.profiles.remove(id) + attempt.finish { callback.success() } + } catch { attempt.finish { SSHFailure.report(error, to: callback) } } + } + } +} + +final class SSHAttempt { + let cancellation = SSHCancellation() + let callback: Callback + let shell: Bool + private let lock = NSLock() + private var completed = false + init(callback: Callback, shell: Bool) { self.callback = callback; self.shell = shell } + func finish(_ completion: () -> Void) { + lock.lock(); defer { lock.unlock() } + guard !completed else { return } + completed = true; completion() + } + func cancel() { cancellation.cancel(); finish { SSHFailure.report(SSHFailure.cancelled, to: callback) } } +} diff --git a/platforms/ios/runner/lib/ssh/SFTPTransfer.swift b/platforms/ios/runner/lib/ssh/SFTPTransfer.swift new file mode 100644 index 0000000000..aa67a2a674 --- /dev/null +++ b/platforms/ios/runner/lib/ssh/SFTPTransfer.swift @@ -0,0 +1,54 @@ +import Foundation +import CSSH2 + +extension SFTPClient { + func download(_ remote: String, to local: String) throws { + let url = try AppFiles.shared.resolve(local) + try AppFiles.shared.coordinate(url, writing: true) { url in + try withFile(remote, flags: LIBSSH2_FXF_READ) { file in + guard FileManager.default.fileExists(atPath: url.path) || FileManager.default.createFile(atPath: url.path, contents: nil) else { throw FileFailure(6) } + let output = try FileHandle(forWritingTo: url) + defer { try? output.close() } + try output.truncate(atOffset: 0) + var buffer = [CChar](repeating: 0, count: 32768) + while true { + connection.begin() + let count = try connection.integer { libssh2_sftp_read(file, &buffer, buffer.count) } + if count == 0 { break } + guard count > 0 else { throw failure() } + try buffer.withUnsafeBytes { try output.write(contentsOf: Data($0.prefix(count))) } + } + } + } + } + + func upload(_ local: String, to remote: String) throws { + let url = try AppFiles.shared.resolve(local) + try AppFiles.shared.coordinate(url) { url in + let input = try FileHandle(forReadingFrom: url) + defer { try? input.close() } + try withFile(remote, flags: LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT | LIBSSH2_FXF_TRUNC) { file in + while let data = try input.read(upToCount: 32768), !data.isEmpty { try write(data, to: file) } + } + } + } + + func create(_ remote: String, contents: String) throws { + try withFile(remote, flags: LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT | LIBSSH2_FXF_EXCL) { file in + try write(Data(contents.utf8), to: file) + } + } + + private func write(_ data: Data, to file: OpaquePointer) throws { + try data.withUnsafeBytes { bytes in + guard let buffer = bytes.bindMemory(to: CChar.self).baseAddress else { return } + var offset = 0 + while offset < data.count { + connection.begin() + let count = try connection.integer { libssh2_sftp_write(file, buffer + offset, min(32768, data.count - offset)) } + guard count > 0 else { throw failure() } + offset += count + } + } + } +} diff --git a/platforms/ios/runner/lib/ssh/SSHChannel.swift b/platforms/ios/runner/lib/ssh/SSHChannel.swift new file mode 100644 index 0000000000..386cc7d68f --- /dev/null +++ b/platforms/ios/runner/lib/ssh/SSHChannel.swift @@ -0,0 +1,93 @@ +import Foundation +import CSSH2 + +final class SSHChannel { + let connection: SSHConnection + let handle: OpaquePointer + private var decoder = SSHTextDecoder() + private(set) var readCount = 0 + + init(connection: SSHConnection) throws { + self.connection = connection + connection.begin() + handle = try connection.pointer { libssh2_channel_open_ex(connection.session, "session", 7, 2 * 1024 * 1024, 32768, nil, 0) } + try connection.check { libssh2_channel_handle_extended_data2(handle, LIBSSH2_CHANNEL_EXTENDED_DATA_MERGE) } + } + + deinit { connection.cleanup { libssh2_channel_free(handle) } } + + func execute(_ command: String) throws -> [String: Any] { + try connection.check { libssh2_channel_process_startup(handle, "exec", 4, command, UInt32(command.utf8.count)) } + connection.begin(timeout: nil) + var result = "" + while true { + let text = try read() + result += text + if readCount == 0 { + if ended { break } + try connection.wait() + } + } + result += decoder.finish() + try connection.check { libssh2_channel_close(handle) } + return ["code": Int(libssh2_channel_get_exit_status(handle)), "result": result] + } + + func shell(columns: Int, rows: Int) throws { + try connection.check { libssh2_channel_request_pty_ex(handle, "xterm-256color", 14, nil, 0, Int32(columns), Int32(rows), 0, 0) } + try connection.check { libssh2_channel_process_startup(handle, "shell", 5, nil, 0) } + } + + func resize(columns: Int, rows: Int) throws { + connection.begin() + try connection.check { libssh2_channel_request_pty_size_ex(handle, Int32(columns), Int32(rows), 0, 0) } + } + + func write(_ text: String) throws { + try Data(text.utf8).withUnsafeBytes { bytes in + guard let buffer = bytes.bindMemory(to: CChar.self).baseAddress else { return } + var offset = 0 + while offset < bytes.count { + connection.begin() + let count = try connection.integer { libssh2_channel_write_ex(handle, 0, buffer + offset, bytes.count - offset) } + guard count > 0 else { throw connection.failure() } + offset += count + } + } + } + + func read() throws -> String { + var buffer = [CChar](repeating: 0, count: 32768) + let count = libssh2_channel_read_ex(handle, 0, &buffer, buffer.count) + readCount = max(0, count) + if count == LIBSSH2_ERROR_EAGAIN { return "" } + guard count >= 0 else { throw connection.failure() } + return decoder.append(Data(buffer.prefix(count).map { UInt8(bitPattern: $0) })) + } + + var ended: Bool { libssh2_channel_eof(handle) != 0 } + var exitCode: Int { Int(libssh2_channel_get_exit_status(handle)) } + func remainingText() -> String { decoder.finish() } +} + +struct SSHTextDecoder { + private var pending = Data() + mutating func append(_ data: Data) -> String { + pending.append(data) + var length = pending.count + if length > 0 { + var start = length - 1 + while start > 0 && pending[start] & 0xc0 == 0x80 && length - start < 4 { start -= 1 } + let first = pending[start] + let expected = first & 0xf8 == 0xf0 ? 4 : first & 0xf0 == 0xe0 ? 3 : first & 0xe0 == 0xc0 ? 2 : 1 + if length - start < expected { length = start } + } + let text = String(decoding: pending.prefix(length), as: UTF8.self) + pending = Data(pending.dropFirst(length)) + return text + } + mutating func finish() -> String { + defer { pending.removeAll() } + return String(decoding: pending, as: UTF8.self) + } +} diff --git a/platforms/ios/runner/lib/ssh/SSHConnection.swift b/platforms/ios/runner/lib/ssh/SSHConnection.swift new file mode 100644 index 0000000000..88f5a08fc4 --- /dev/null +++ b/platforms/ios/runner/lib/ssh/SSHConnection.swift @@ -0,0 +1,171 @@ +import Foundation +import CSSH2 +import Darwin + +final class SSHCancellation { + private let lock = NSLock() + private var cancelled = false + func cancel() { lock.lock(); cancelled = true; lock.unlock() } + func check() throws { + lock.lock(); defer { lock.unlock() } + if cancelled { throw SSHFailure.cancelled } + } +} + +final class SSHConnection { + private static let initialized = libssh2_init(0) + let session: OpaquePointer + let cancellation: SSHCancellation + private var socket: Int32 = -1 + private var deadline = Date.distantFuture + private var closed = false + + init(cancellation: SSHCancellation) throws { + guard Self.initialized == 0, let session = libssh2_session_init_ex(nil, nil, nil, nil) else { throw SecretFailure("Could not initialize SSH") } + self.session = session + self.cancellation = cancellation + libssh2_session_set_blocking(session, 0) + } + + deinit { close() } + + func connect(_ profile: SSHProfile, timeout: TimeInterval, verify: (Data, String) throws -> Void) throws { + begin(timeout: timeout) + socket = try connectSocket(host: profile.hostname, port: profile.port) + try check { libssh2_session_handshake(session, socket) } + var length = 0, type: Int32 = 0 + guard let key = libssh2_session_hostkey(session, &length, &type), length > 0 else { throw SecretFailure("SSH server did not provide a host key") } + let algorithms = [1: "ssh-rsa", 2: "ssh-dss", 3: "ecdsa-sha2-nistp256", 4: "ecdsa-sha2-nistp384", 5: "ecdsa-sha2-nistp521", 6: "ssh-ed25519"] + try verify(Data(bytes: key, count: length), algorithms[Int(type)] ?? "unknown") + begin(timeout: timeout) + if profile.authType == "key" { + try profile.privateKey.withUnsafeBytes { bytes in + let key = bytes.bindMemory(to: CChar.self) + try check { libssh2_userauth_publickey_frommemory(session, profile.username, profile.username.utf8.count, nil, 0, key.baseAddress, key.count, profile.passphrase) } + } + } else { + try check { libssh2_userauth_password_ex(session, profile.username, UInt32(profile.username.utf8.count), profile.password, UInt32(profile.password.utf8.count), nil) } + } + } + + func begin(timeout: TimeInterval? = 30) { deadline = timeout.map { Date().addingTimeInterval($0) } ?? .distantFuture } + + var isConnected: Bool { + guard !closed, socket >= 0, (try? cancellation.check()) != nil else { return false } + var byte: UInt8 = 0 + let count = recv(socket, &byte, 1, MSG_PEEK | MSG_DONTWAIT) + return count > 0 || (count < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) + } + + func check(_ operation: () -> Int32) throws { + let result = try integer { Int(operation()) } + if result < 0 { throw failure() } + } + + func integer(_ operation: () -> Int) throws -> Int { + while true { + try cancellation.check() + let result = operation() + if result != LIBSSH2_ERROR_EAGAIN { return result } + try wait() + } + } + + func pointer(_ operation: () -> OpaquePointer?) throws -> OpaquePointer { + while true { + try cancellation.check() + if let result = operation() { return result } + guard libssh2_session_last_errno(session) == LIBSSH2_ERROR_EAGAIN else { throw failure() } + try wait() + } + } + + func wait() throws { + try cancellation.check() + guard Date() < deadline else { + invalidate() + throw SecretFailure("SSH operation timed out") + } + let directions = libssh2_session_block_directions(session) + var events: Int16 = 0 + if directions & LIBSSH2_SESSION_BLOCK_INBOUND != 0 { events |= Int16(POLLIN) } + if directions & LIBSSH2_SESSION_BLOCK_OUTBOUND != 0 { events |= Int16(POLLOUT) } + if events == 0 { events = Int16(POLLIN) } + var descriptor = pollfd(fd: socket, events: events, revents: 0) + let result = poll(&descriptor, 1, 50) + if (result < 0 && errno != EINTR) || descriptor.revents & Int16(POLLERR | POLLNVAL) != 0 { + invalidate(); throw SecretFailure("SSH connection was interrupted") + } + } + + func failure() -> Error { + var message: UnsafeMutablePointer<CChar>? + let code = libssh2_session_last_error(session, &message, nil, 0) + if [LIBSSH2_ERROR_SOCKET_SEND, LIBSSH2_ERROR_SOCKET_RECV, LIBSSH2_ERROR_SOCKET_DISCONNECT, + LIBSSH2_ERROR_CHANNEL_CLOSED, LIBSSH2_ERROR_PROTO, LIBSSH2_ERROR_DECRYPT, + LIBSSH2_ERROR_INVALID_MAC, LIBSSH2_ERROR_TIMEOUT].contains(code) { invalidate() } + return SecretFailure(message.map { String(cString: $0) } ?? "SSH operation failed") + } + + @discardableResult + func cleanup(_ operation: () -> Int32) -> Int32 { + begin(timeout: 2) + while true { + if (try? cancellation.check()) == nil, socket >= 0 { shutdown(socket, SHUT_RDWR) } + let result = operation() + if result != LIBSSH2_ERROR_EAGAIN { return result } + do { try wait() } + catch { if socket >= 0 { shutdown(socket, SHUT_RDWR) } } + } + } + + func close() { + guard !closed else { return } + closed = true + if socket >= 0 { shutdown(socket, SHUT_RDWR) } + cleanup { libssh2_session_free(session) } + if socket >= 0 { Darwin.close(socket); socket = -1 } + } + + private func invalidate() { + cancellation.cancel() + if socket >= 0 { shutdown(socket, SHUT_RDWR) } + } + + private func connectSocket(host: String, port: Int) throws -> Int32 { + var hints = addrinfo() + hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP + var addresses: UnsafeMutablePointer<addrinfo>? + let result = getaddrinfo(host, String(port), &hints, &addresses) + guard result == 0 else { throw SecretFailure(String(cString: gai_strerror(result))) } + defer { freeaddrinfo(addresses) } + var address = addresses + while let current = address { + try cancellation.check() + let info = current.pointee + address = info.ai_next + let descriptor = Darwin.socket(info.ai_family, info.ai_socktype, info.ai_protocol) + if descriptor < 0 { continue } + guard fcntl(descriptor, F_SETFL, O_NONBLOCK) == 0 else { Darwin.close(descriptor); continue } + var enabled: Int32 = 1 + setsockopt(descriptor, SOL_SOCKET, SO_NOSIGPIPE, &enabled, socklen_t(MemoryLayout<Int32>.size)) + let connected = Darwin.connect(descriptor, info.ai_addr, info.ai_addrlen) + if connected == 0 { return descriptor } + if errno == EINPROGRESS { + do { + while Date() < deadline { + try cancellation.check() + var poller = pollfd(fd: descriptor, events: Int16(POLLOUT), revents: 0) + if poll(&poller, 1, 50) <= 0 { continue } + var error: Int32 = 0, size = socklen_t(MemoryLayout<Int32>.size) + getsockopt(descriptor, SOL_SOCKET, SO_ERROR, &error, &size) + if error == 0 { return descriptor } + break + } + } catch { Darwin.close(descriptor); throw error } + } + Darwin.close(descriptor) + } + throw SecretFailure("Could not connect to SSH host") + } +} diff --git a/platforms/ios/runner/lib/ssh/SSHProfile.swift b/platforms/ios/runner/lib/ssh/SSHProfile.swift new file mode 100644 index 0000000000..c0d8613251 --- /dev/null +++ b/platforms/ios/runner/lib/ssh/SSHProfile.swift @@ -0,0 +1,103 @@ +import Foundation +import CryptoKit + +struct SSHProfile: Codable { + let hostname: String + let port: Int + let username: String + let authType: String + var password: String = "" + var privateKey: Data = Data() + var passphrase: String = "" + + var endpoint: String { "\(hostname):\(port)" } + + func info(id: String) -> [String: Any] { + ["profileId": id, "hostname": hostname, "port": port, "username": username, "authType": authType] + } +} + +final class SSHProfileStore { + private let profiles: SecretStore + private let hosts: SecretStore + private let lock = NSRecursiveLock() + private let hostLock = NSLock() + + init(namespace: String = "ssh") { + profiles = SecretStore(namespace: namespace + ".profiles") + hosts = SecretStore(namespace: namespace + ".knownHosts") + } + + func profile(_ id: String) throws -> SSHProfile { + guard id.hasPrefix("profile-") else { throw SecretFailure("Invalid SFTP profile ID") } + let value = try profiles.get(id) + guard !value.isEmpty else { throw SecretFailure("SFTP profile was not found") } + return try JSONDecoder().decode(SSHProfile.self, from: Data(value.utf8)) + } + + func save(_ args: [Any], legacy: Bool) throws -> (String, SSHProfile) { + lock.lock(); defer { lock.unlock() } + let requested = (args[safe: 0] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + let id = ["", "null", "undefined"].contains(requested.lowercased()) ? "profile-" + UUID().uuidString : requested + if legacy && id == requested { throw SecretFailure("Legacy profile import cannot replace a saved profile") } + let existing = id == requested ? try profile(id) : nil + let host = (args[safe: 1] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + let username = (args[safe: 3] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + let port = args[safe: 2] as? Int ?? 22 + let auth = args[safe: 4] as? String ?? "password" + guard !host.isEmpty, !host.contains("\0"), !username.isEmpty, !username.contains("\0") else { throw SecretFailure("Hostname and username are required") } + guard (1...65535).contains(port) else { throw SecretFailure("Port must be between 1 and 65535") } + guard ["password", "key"].contains(auth) else { throw SecretFailure("Invalid SSH authentication type") } + var value = SSHProfile(hostname: host, port: port, username: username, authType: auth) + if auth == "key" { + let path = args[safe: 6] as? String ?? "" + if !path.isEmpty { + let url = try AppFiles.shared.resolve(path) + value.privateKey = try AppFiles.shared.coordinate(url) { try Data(contentsOf: $0) } + value.passphrase = args[safe: 7] as? String ?? "" + } else if let existing, existing.authType == "key" { + value.privateKey = existing.privateKey; value.passphrase = existing.passphrase + } else { throw SecretFailure("Select a private key file") } + } else { + value.password = args[safe: 5] as? String ?? "" + if value.password.isEmpty, let existing, existing.authType == "password" { value.password = existing.password } + } + let encoded = try JSONEncoder().encode(value) + try profiles.set(id, value: String(decoding: encoded, as: UTF8.self)) + return (id, value) + } + + func remove(_ id: String) throws { try profiles.remove(id) } + + func verify(endpoint: String, key: Data, algorithm: String, confirm: (String) throws -> Bool) throws { + hostLock.lock(); defer { hostLock.unlock() } + let fingerprint = "SHA256:" + Data(SHA256.hash(data: key)).base64EncodedString().replacingOccurrences(of: "=", with: "") + let trusted = try hosts.get(endpoint) + if !trusted.isEmpty { + let saved = try JSONDecoder().decode(SSHHost.self, from: Data(trusted.utf8)) + guard saved.key == key else { + throw SSHFailure(["code": "HOST_KEY_CHANGED", "host": endpoint, "fingerprint": fingerprint, "expectedFingerprint": saved.fingerprint]) + } + } else { + guard try confirm(fingerprint) else { throw SSHFailure(["code": "HOST_KEY_REJECTED", "host": endpoint, "fingerprint": fingerprint]) } + let host = SSHHost(key: key, algorithm: algorithm, fingerprint: fingerprint) + try hosts.set(endpoint, value: String(decoding: JSONEncoder().encode(host), as: UTF8.self)) + } + } +} + +private struct SSHHost: Codable { + let key: Data + let algorithm: String + let fingerprint: String +} + +struct SSHFailure: LocalizedError { + let payload: [String: Any] + init(_ payload: [String: Any]) { self.payload = payload } + var errorDescription: String? { payload["message"] as? String ?? payload["code"] as? String } + static var cancelled: SSHFailure { SSHFailure(["code": "SFTP_CONNECT_CANCELLED", "message": "SFTP connection cancelled", "cancelled": true, "nonRetryable": true]) } + static func report(_ error: Error, to callback: Callback) { + callback.error((error as? SSHFailure)?.payload ?? ["message": error.localizedDescription]) + } +} diff --git a/platforms/ios/runner/lib/ssh/SSHPrompts.swift b/platforms/ios/runner/lib/ssh/SSHPrompts.swift new file mode 100644 index 0000000000..b8e8061654 --- /dev/null +++ b/platforms/ios/runner/lib/ssh/SSHPrompts.swift @@ -0,0 +1,41 @@ +import UIKit + +enum SSHPrompts { + static func confirm(title: String, message: String, button: String, destructive: Bool = false, presenter: @escaping () -> UIViewController?, cancellation: SSHCancellation) throws -> Bool { + let decision = SSHDecision() + DispatchQueue.main.async { + guard (try? cancellation.check()) != nil, let presenter = presenter(), presenter.presentedViewController == nil else { decision.complete(false); return } + let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) + decision.alert = alert + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in decision.complete(false) }) + alert.addAction(UIAlertAction(title: button, style: destructive ? .destructive : .default) { _ in decision.complete(true) }) + presenter.present(alert, animated: true) + } + do { + while decision.signal.wait(timeout: .now() + .milliseconds(50)) == .timedOut { try cancellation.check() } + try cancellation.check() + return decision.accepted + } catch { + DispatchQueue.main.async { decision.alert?.dismiss(animated: true) } + throw error + } + } + + static func changed(_ failure: SSHFailure, presenter: @escaping () -> UIViewController?) { + guard failure.payload["code"] as? String == "HOST_KEY_CHANGED" else { return } + DispatchQueue.main.async { + guard let presenter = presenter(), presenter.presentedViewController == nil else { return } + let message = "The identity of \(failure.payload["host"] ?? "") has changed. The connection was blocked.\n\nExpected: \(failure.payload["expectedFingerprint"] ?? "")\nReceived: \(failure.payload["fingerprint"] ?? "")" + let alert = UIAlertController(title: "SSH host key changed", message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "Close", style: .default)) + presenter.present(alert, animated: true) + } + } +} + +private final class SSHDecision { + let signal = DispatchSemaphore(value: 0) + var accepted = false + weak var alert: UIAlertController? + func complete(_ value: Bool) { accepted = value; signal.signal() } +} diff --git a/platforms/ios/runner/lib/ssh/SSHShell.swift b/platforms/ios/runner/lib/ssh/SSHShell.swift new file mode 100644 index 0000000000..66a71bd4a2 --- /dev/null +++ b/platforms/ios/runner/lib/ssh/SSHShell.swift @@ -0,0 +1,75 @@ +import Foundation +import CSSH2 + +final class SSHShell { + let id = UUID().uuidString + let cancellation: SSHCancellation + private let channel: SSHChannel + private let callback: Callback + private let queue = DispatchQueue(label: "app.acode.ssh.shell", qos: .userInitiated) + private var timer: DispatchSourceTimer? + private var finished = false + var onClose: (() -> Void)? + + init(connection: SSHConnection, columns: Int, rows: Int, callback: Callback) throws { + cancellation = connection.cancellation + channel = try SSHChannel(connection: connection) + self.callback = callback + try channel.shell(columns: columns, rows: rows) + libssh2_keepalive_config(connection.session, 1, 30) + } + + func start() { + queue.async { [self] in + self.callback.success(["type": "ready", "sessionId": self.id], keep: true) + let timer = DispatchSource.makeTimerSource(queue: self.queue) + timer.schedule(deadline: .now(), repeating: .milliseconds(20)) + timer.setEventHandler { [weak self] in self?.read() } + self.timer = timer + timer.resume() + } + } + + func perform(_ action: String, args: [Any], callback: Callback) { + queue.async { + guard !self.finished else { callback.error("SSH shell is not connected"); return } + do { + if action == "writeShell" { try self.channel.write(args[safe: 1] as? String ?? "") } + else { try self.channel.resize(columns: Self.dimension(args[safe: 1], default: 80), rows: Self.dimension(args[safe: 2], default: 24)) } + callback.success() + } catch { SSHFailure.report(error, to: callback); self.finish(error) } + } + } + + func close() { + cancellation.cancel() + queue.async { self.finish(nil) } + } + + static func dimension(_ value: Any?, default fallback: Int) -> Int { min(65535, max(1, value as? Int ?? fallback)) } + + private func read() { + guard !finished else { return } + do { + try cancellation.check() + let text = try channel.read() + if !text.isEmpty { callback.success(["type": "data", "sessionId": id, "data": text], keep: true) } + if channel.ended && channel.readCount == 0 { finish(nil); return } + var next: Int32 = 0 + let status = libssh2_keepalive_send(channel.connection.session, &next) + if status < 0 && status != LIBSSH2_ERROR_EAGAIN { throw channel.connection.failure() } + } catch { finish(error) } + } + + private func finish(_ error: Error?) { + guard !finished else { return } + finished = true + timer?.cancel(); timer = nil + let tail = channel.remainingText() + if !tail.isEmpty { callback.success(["type": "data", "sessionId": id, "data": tail], keep: true) } + if let error, (error as? SSHFailure)?.payload["cancelled"] as? Bool != true { + callback.success(["type": "error", "sessionId": id, "message": error.localizedDescription]) + } else { callback.success(["type": "exit", "sessionId": id, "exitCode": channel.exitCode]) } + onClose?() + } +} diff --git a/platforms/ios/runner/lib/terminal/AlpineMaintenance.swift b/platforms/ios/runner/lib/terminal/AlpineMaintenance.swift new file mode 100644 index 0000000000..f9df867712 --- /dev/null +++ b/platforms/ios/runner/lib/terminal/AlpineMaintenance.swift @@ -0,0 +1,67 @@ +import AcodeAlpine +import Foundation + +enum AlpineMaintenance { + static func perform(_ action: String, callback: Callback) throws { + let runtime = AlpineRuntime.shared + let backup = runtime.files.data.appendingPathComponent("aterm_backup.tar") + switch action { + case "clearBackup": + if FileManager.default.fileExists(atPath: backup.path) { try FileManager.default.removeItem(at: backup) } + callback.success() + case "backup": + guard runtime.installed else { throw terminalError("Alpine is not installed.") } + try runtime.start(""" + tar -cf /acode/aterm_backup.tar -C / \ + --exclude=./acode --exclude=./acode-assets --exclude=./public \ + --exclude=./home --exclude=./root --exclude=./dev --exclude=./proc \ + --exclude=./sys --exclude=./run --exclude=./tmp \ + --exclude=./Users --exclude=./private --exclude=./var/mobile . + """, completion: { status, _, errors in + if status == 0 { callback.success(backup.absoluteString) } + else { callback.error(errors) } + }) + case "restore": + guard FileManager.default.fileExists(atPath: backup.path) else { throw terminalError("Backup File does not exist") } + let staging = runtime.root.appendingPathExtension("restore") + try? FileManager.default.removeItem(at: staging) + var error = [CChar](repeating: 0, count: 1024) + guard alpine_import(backup.path, staging.path, &error, error.count) else { + try? FileManager.default.removeItem(at: staging) + throw terminalError(String(cString: error)) + } + guard FileManager.default.fileExists(atPath: staging.appendingPathComponent("data/bin/busybox").path) else { + try? FileManager.default.removeItem(at: staging) + throw terminalError("This is not an iOS Alpine backup") + } + runtime.unmount { error in + if let error { callback.error(error.localizedDescription); return } + do { + let previous = runtime.root.appendingPathExtension("previous") + try? FileManager.default.removeItem(at: previous) + let exists = FileManager.default.fileExists(atPath: runtime.root.path) + if exists { try FileManager.default.moveItem(at: runtime.root, to: previous) } + do { try FileManager.default.moveItem(at: staging, to: runtime.root) } + catch { + if exists { try? FileManager.default.moveItem(at: previous, to: runtime.root) } + throw error + } + try FileManager.default.createDirectory(at: runtime.files.data.appendingPathComponent(".configured"), withIntermediateDirectories: true) + try? FileManager.default.removeItem(at: previous) + callback.success("ok") + } catch { callback.error(error.localizedDescription) } + } + case "uninstall": + runtime.unmount { error in + if let error { callback.error(error.localizedDescription); return } + do { + if FileManager.default.fileExists(atPath: runtime.root.path) { try FileManager.default.removeItem(at: runtime.root) } + let marker = runtime.files.data.appendingPathComponent(".configured") + if FileManager.default.fileExists(atPath: marker.path) { try FileManager.default.removeItem(at: marker) } + callback.success("ok") + } catch { callback.error(error.localizedDescription) } + } + default: throw terminalError("Unknown maintenance action") + } + } +} diff --git a/platforms/ios/runner/lib/terminal/AlpineProcess.swift b/platforms/ios/runner/lib/terminal/AlpineProcess.swift new file mode 100644 index 0000000000..88f925e725 --- /dev/null +++ b/platforms/ios/runner/lib/terminal/AlpineProcess.swift @@ -0,0 +1,94 @@ +import Foundation + +final class AlpineProcess { + let id = UUID().uuidString + let command: String + let background: Bool + let startedAt = Date().timeIntervalSince1970 * 1000 + let input = Pipe() + let output = Pipe() + let errors = Pipe() + var pid: Int32 = 0 + var status: Int32? + var listener: ((String, String) -> Void)? + var rawOutput: ((Data) -> Void)? + var completion: ((Int32, String, String) -> Void)? + private var pending = ["stdout": Data(), "stderr": Data()] + private var collected = ["stdout": "", "stderr": ""] + private var closed = Set<String>() + + init(command: String, background: Bool) { + self.command = command + self.background = background + } + + var info: [String: Any] { + ["id": id, "pid": pid, "command": command, "alpine": true, + "startedAt": startedAt, "background": background] + } + + /// Line output and exit bookkeeping run on `queue`; raw stdout goes straight + /// from the pipe's reader thread so streaming never waits behind guest calls. + func observe(on queue: DispatchQueue) { + for (kind, pipe) in [("stdout", output), ("stderr", errors)] { + let raw = kind == "stdout" ? rawOutput : nil + pipe.fileHandleForReading.readabilityHandler = { [weak self] handle in + let data = handle.availableData + if let raw, !data.isEmpty { raw(data); return } + if data.isEmpty { handle.readabilityHandler = nil } + queue.async { self?.receive(data, kind: kind) } + } + } + } + + func didStart() { + try? input.fileHandleForReading.close() + try? output.fileHandleForWriting.close() + try? errors.fileHandleForWriting.close() + } + + func finish(_ code: Int32) { + status = code + completeIfDrained() + } + + func write(_ text: String) throws { + try input.fileHandleForWriting.write(contentsOf: Data((text + "\n").utf8)) + } + + private func receive(_ data: Data, kind: String) { + pending[kind, default: Data()].append(data) + // Executor uses lines on Android. Buffering also preserves split UTF-8 sequences. + while let end = pending[kind]!.firstIndex(of: 10) { + let line = pending[kind]!.prefix(upTo: end) + let text = String(decoding: line, as: UTF8.self) + pending[kind]!.removeSubrange(...end) + deliver(text, kind: kind) + } + if data.isEmpty { + if !pending[kind]!.isEmpty { + deliver(String(decoding: pending[kind]!, as: UTF8.self), kind: kind) + pending[kind]!.removeAll() + } + closed.insert(kind) + completeIfDrained() + } + } + + private func deliver(_ text: String, kind: String) { + listener?(kind, text) + if completion != nil { collected[kind, default: ""] += text + "\n" } + } + + private func completeIfDrained() { + guard let status, closed.count == 2 else { return } + listener?("exit", String(status)) + listener = nil + completion?(status, collected["stdout"]!.trimmingCharacters(in: .newlines), + collected["stderr"]!.trimmingCharacters(in: .newlines)) + completion = nil + try? input.fileHandleForWriting.close() + try? output.fileHandleForReading.close() + try? errors.fileHandleForReading.close() + } +} diff --git a/platforms/ios/runner/lib/terminal/AlpineRuntime.swift b/platforms/ios/runner/lib/terminal/AlpineRuntime.swift new file mode 100644 index 0000000000..89911ca9c3 --- /dev/null +++ b/platforms/ios/runner/lib/terminal/AlpineRuntime.swift @@ -0,0 +1,242 @@ +import AcodeAlpine +import Foundation +import UIKit + +final class AlpineRuntime { + static let shared = AlpineRuntime() + let queue = DispatchQueue(label: "app.acode.alpine", qos: .userInitiated) + let files = AppFiles.shared + private(set) var processes: [String: AlpineProcess] = [:] + private var terminals: [Int32: TerminalSession] = [:] + private var booted = false + private var prepared = false + private var preparing: [() -> Void]? + private var suspended = false + private(set) var maintaining = false + private var sharedPaths = Set<String>() + + // The guest root must sit outside every host bind mount. Otherwise the + // emulator resolves its own root through that mount and loses Linux metadata. + var root: URL { files.data.deletingLastPathComponent().appendingPathComponent("Alpine") } + var installed: Bool { FileManager.default.fileExists(atPath: files.data.appendingPathComponent(".configured").path) } + var assets: URL { Bundle.main.resourceURL!.appendingPathComponent("Alpine") } + // Bun FFI needs JIT; optimizing and concurrent workers are unsafe in this guest. + var environment: String { + ["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "HOME=/public", + "PREFIX=/acode", "ALPINE_ROOT=/", "TERM=xterm-256color", "SHELL=/bin/bash", + "ANDROID_TZ=\(TimeZone.current.identifier)", "GODEBUG=asyncpreemptoff=1", "GOMAXPROCS=2", + "PYTHONMALLOC=malloc", "PYTHONDONTWRITEBYTECODE=1", + "BUN_JSC_useDFGJIT=0", "BUN_JSC_useFTLJIT=0", "BUN_JSC_useConcurrentJIT=0", + "BUN_JSC_numberOfGCMarkers=1", "BUN_JSC_useConcurrentGC=0"].joined(separator: "\0") + "\0\0" + } + + private init() { + // Guest servers keep listening across suspension; iOS reclaims their host sockets meanwhile. + let center = NotificationCenter.default + center.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] _ in + self?.suspend() + } + center.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] _ in + self?.resume() + } + } + + func extract() throws { + guard !FileManager.default.fileExists(atPath: root.path) else { return } + let staging = root.appendingPathExtension("installing") + try? FileManager.default.removeItem(at: staging) + var message = [CChar](repeating: 0, count: 1024) + guard alpine_import(assets.appendingPathComponent("alpine.rootfs").path, staging.path, &message, message.count) else { + try? FileManager.default.removeItem(at: staging) + throw failure(String(cString: message)) + } + try FileManager.default.moveItem(at: staging, to: root) + } + + func boot() throws { + guard !booted else { return } + guard FileManager.default.fileExists(atPath: root.appendingPathComponent("meta.db").path) else { + throw failure("Terminal not installed. Please install terminal first.") + } + try check(alpine_boot(root.appendingPathComponent("data").path, { pid, status in + let runtime = AlpineRuntime.shared + runtime.queue.async { runtime.didExit(pid: pid, status: status) } + })) + let publicDirectory = files.data.appendingPathComponent("public") + try FileManager.default.createDirectory(at: publicDirectory, withIntermediateDirectories: true) + for guest in ["/public", "/home", "/root"] { try check(alpine_bind(guest, publicDirectory.path, false)) } + try check(alpine_bind("/acode", files.data.path, false)) + try check(alpine_bind("/acode-assets", assets.path, true)) + // Update the server binary on every app launch while preserving guest packages and user rc files. + for name in ["axs", "init-alpine.sh"] { + let destination = files.data.appendingPathComponent(name) + try? FileManager.default.removeItem(at: destination) + try FileManager.default.copyItem(at: assets.appendingPathComponent(name), to: destination) + } + try check(alpine_chmod("/acode/axs", 0o755)) + booted = true + try shareFiles() + } + + @discardableResult + func start(_ command: String, background: Bool = false, + listener: ((String, String) -> Void)? = nil, + rawOutput: ((Data) -> Void)? = nil, + completion: ((Int32, String, String) -> Void)? = nil) throws -> AlpineProcess { + try ready() + let process = AlpineProcess(command: command, background: background) + process.listener = listener + process.rawOutput = rawOutput + process.completion = completion + let pid = shellScript(command).withCString { script in + environment.withCString { env in + alpine_start(script, env, process.input.fileHandleForReading.fileDescriptor, + process.output.fileHandleForWriting.fileDescriptor, process.errors.fileHandleForWriting.fileDescriptor) + } + } + process.didStart() + try check(pid) + process.pid = pid + processes[process.id] = process + process.observe(on: queue) + return process + } + + /// Starts a command on a guest pseudo-terminal whose I/O runs on `terminalQueue`. + func startTerminal(_ command: String, rows: Int, cols: Int, queue terminalQueue: DispatchQueue, + scrollbackLimit: Int = TerminalSession.replayLimit) throws -> TerminalSession { + try ready() + let session = TerminalSession(queue: terminalQueue, scrollbackLimit: scrollbackLimit) + let context = Unmanaged.passRetained(session).toOpaque() + var handle: OpaquePointer? + let pid = shellScript(command).withCString { script in + environment.withCString { env in + alpine_terminal_start(script, env, Int32(rows), Int32(cols), context, terminalCallbacks, &handle) + } + } + try check(pid) + guard let handle else { throw failure("Could not open a terminal") } + session.started(pid: pid, handle: handle) + terminals[pid] = session + return session + } + + /// Kills a hung-up shell that ignored SIGHUP once it had a chance to exit. + func killTerminal(_ session: TerminalSession) { + queue.asyncAfter(deadline: .now() + 1) { [self] in + if terminals[session.pid] === session { _ = alpine_kill(session.pid) } + } + } + + /// Runs the shared setup script once per boot so each shell only has to start bash. + func prepare(_ completion: @escaping () -> Void) { + if prepared { completion(); return } + guard preparing == nil else { preparing?.append(completion); return } + preparing = [completion] + do { + try start("exec /bin/sh /acode/init-alpine.sh --prepare", completion: { [self] status, _, errors in + if status == 0 { prepared = true } + else { print("Alpine setup exited with status \(status): \(errors)") } + finishPreparing() + }) + } catch { + print("Alpine setup failed: \(error.localizedDescription)") + finishPreparing() + } + } + + func execute(_ command: String, callback: Callback) throws { + try start(command, completion: { status, output, errors in + if status == 0 { callback.success(output) } + else { callback.error(errors.isEmpty ? "Command exited with status \(status): \(output)" : errors) } + }) + } + + func stop(_ id: String) { + if let process = processes[id], process.status == nil { _ = alpine_kill(process.pid) } + } + + func stopAll(background: Bool) { + for process in processes.values where process.background == background { stop(process.id) } + } + + func unmount(completion: @escaping (Error?) -> Void) { + guard !maintaining else { completion(failure("Alpine maintenance is in progress")); return } + guard booted else { completion(nil); return } + maintaining = true + alpine_stop_all() + waitForShutdown(deadline: Date().addingTimeInterval(10), completion: completion) + } + + func shareFiles() throws { + guard booted else { return } + for (name, url) in files.allRoots() where name != "application" { + for path in Set([url.path, url.resolvingSymlinksInPath().path]) { + if sharedPaths.contains(path) { continue } + try check(alpine_bind(path, url.path, false)) + sharedPaths.insert(path) + } + } + } + + private func ready() throws { + guard !maintaining else { throw failure("Alpine maintenance is in progress") } + try boot() + try shareFiles() + } + + private func shellScript(_ command: String) -> String { + "cd /public; " + command + } + + private func finishPreparing() { + let waiting = preparing ?? [] + preparing = nil + for completion in waiting { completion() } + } + + private func waitForShutdown(deadline: Date, completion: @escaping (Error?) -> Void) { + if alpine_idle() { + do { + try check(alpine_unmount()) + booted = false + prepared = false + sharedPaths.removeAll() + maintaining = false + completion(nil) + } catch { maintaining = false; completion(error) } + } else if Date() >= deadline { + maintaining = false + completion(failure("Alpine processes are still stopping. Try again.")) + } else { + queue.asyncAfter(deadline: .now() + .milliseconds(50)) { self.waitForShutdown(deadline: deadline, completion: completion) } + } + } + + private func didExit(pid: Int32, status: Int32) { + terminals.removeValue(forKey: pid)?.finish(status) + if let process = processes.values.first(where: { $0.pid == pid }) { process.finish(status) } + alpine_reap() + processes = processes.filter { $0.value.status == nil || $0.value.completion != nil || $0.value.listener != nil } + } + + private func suspend() { + guard !suspended else { return } + suspended = true + alpine_suspend() + } + + private func resume() { + guard suspended else { return } + suspended = false + alpine_resume() + } + + private func check(_ result: Int32) throws { + if result < 0 { throw failure("Alpine runtime error \(result)") } + } + + private func failure(_ message: String) -> NSError { + NSError(domain: "AcodeAlpine", code: 1, userInfo: [NSLocalizedDescriptionKey: message]) + } +} diff --git a/platforms/ios/runner/lib/terminal/AlpineService.swift b/platforms/ios/runner/lib/terminal/AlpineService.swift new file mode 100644 index 0000000000..f91d56954a --- /dev/null +++ b/platforms/ios/runner/lib/terminal/AlpineService.swift @@ -0,0 +1,49 @@ +import Foundation + +final class AlpineService: BaseService { + private let runtime = AlpineRuntime.shared + + override func exec(action: String, args: [Any], callback: Callback) { + runtime.queue.async { [self] in + do { + switch action { + case "isSupported": callback.success(true) + case "isInstalled": callback.success(runtime.installed) + case "isAxsRunning": + try runtime.shareFiles() + callback.success(TerminalServer.shared.isRunning) + case "install": try install(callback) + case "backup", "restore", "uninstall", "clearBackup": try AlpineMaintenance.perform(action, callback: callback) + case "startAxs": + try runtime.shareFiles() + let failsafe = args[safe: 0] as? Bool == true + let start = { + TerminalServer.shared.start(shell: failsafe ? "exec sh" : "exec bash --rcfile /initrc -i") { error in + if let error { callback.error(error.localizedDescription) } else { callback.success() } + } + } + if failsafe { start() } else { runtime.prepare(start) } + case "stopAxs": + TerminalServer.shared.stop() + callback.success() + default: callback.error("Unknown Alpine action: \(action)") + } + } catch { callback.error(error.localizedDescription) } + } + } + + private func install(_ callback: Callback) throws { + try runtime.extract() + try runtime.boot() + let setup = """ + set -e + printf 'nameserver 8.8.8.8\nnameserver 1.1.1.1\n' > /etc/resolv.conf + chmod +x /acode/axs + ln -sf /acode/axs /usr/local/bin/axs + /bin/sh /acode/init-alpine.sh --installing + """ + try runtime.start(setup, listener: { kind, text in + callback.success(["type": kind, "data": text], keep: kind != "exit") + }) + } +} diff --git a/platforms/ios/runner/lib/terminal/AlpineStreamServer.swift b/platforms/ios/runner/lib/terminal/AlpineStreamServer.swift new file mode 100644 index 0000000000..9ef8bce82f --- /dev/null +++ b/platforms/ios/runner/lib/terminal/AlpineStreamServer.swift @@ -0,0 +1,105 @@ +import Foundation +import Network + +/// Raw WebSocket transport for `Executor.spawnStream` (language servers). Socket +/// I/O runs on its own queue; only process start and kill touch the runtime queue. +final class AlpineStreamServer { + private let runtime = AlpineRuntime.shared + private let queue = DispatchQueue(label: "app.acode.alpine.stream", qos: .userInitiated) + private let listener: NWListener + private let command: [String] + private let callback: Callback + private var connection: NWConnection? + private var process: AlpineProcess? + private var stopped = false + var onStop: (() -> Void)? + + init(command: [String], callback: Callback) throws { + self.command = command + self.callback = callback + let parameters = NWParameters.tcp + parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: .any) + let websocket = NWProtocolWebSocket.Options() + websocket.autoReplyPing = true + parameters.defaultProtocolStack.applicationProtocols.insert(websocket, at: 0) + listener = try NWListener(using: parameters) + } + + func start() { + listener.stateUpdateHandler = { [weak self] state in + guard let self else { return } + switch state { + case .ready: callback.success(Int(listener.port!.rawValue)) + case .failed(let error): callback.error(error.localizedDescription); shutdown() + default: break + } + } + listener.newConnectionHandler = { [weak self] connection in self?.accept(connection) } + listener.start(queue: queue) + } + + func stop() { + queue.async { self.shutdown() } + } + + private func shutdown() { + guard !stopped else { return } + stopped = true + listener.cancel() + connection?.cancel() + if let process { runtime.queue.async { [runtime] in runtime.stop(process.id) } } + process = nil + let handler = onStop + onStop = nil + handler?() + } + + private func accept(_ connection: NWConnection) { + guard self.connection == nil else { connection.cancel(); return } + self.connection = connection + connection.stateUpdateHandler = { [weak self] state in + guard let self else { return } + switch state { + case .ready: launch(on: connection) + case .failed, .cancelled: shutdown() + default: break + } + } + connection.start(queue: queue) + } + + private func launch(on connection: NWConnection) { + let script = "exec " + command.map(shellQuote).joined(separator: " ") + " 2>&1" + let send = { [weak self, connection] (data: Data) in + let metadata = NWProtocolWebSocket.Metadata(opcode: .binary) + let context = NWConnection.ContentContext(identifier: "stdout", metadata: [metadata]) + connection.send(content: data, contentContext: context, isComplete: true, completion: .contentProcessed { error in + if error != nil { self?.stop() } + }) + } + runtime.queue.async { [weak self, runtime] in + do { + let process = try runtime.start(script, listener: { kind, _ in if kind == "exit" { self?.stop() } }, rawOutput: send) + self?.queue.async { + guard let self, !self.stopped else { runtime.queue.async { runtime.stop(process.id) }; return } + self.process = process + self.receive() + } + } catch { self?.stop() } + } + } + + private func receive() { + connection?.receiveMessage { [weak self] data, context, _, error in + guard let self else { return } + let metadata = context?.protocolMetadata(definition: NWProtocolWebSocket.definition) as? NWProtocolWebSocket.Metadata + if error != nil || metadata?.opcode == .close { shutdown(); return } + if let data { try? process?.input.fileHandleForWriting.write(contentsOf: data) } + receive() + } + } +} + +func shellQuote(_ value: String) -> String { + "'" + value.replacingOccurrences(of: "'", with: "'\\''") + "'" +} diff --git a/platforms/ios/runner/lib/terminal/ExecutorService.swift b/platforms/ios/runner/lib/terminal/ExecutorService.swift new file mode 100644 index 0000000000..1ba0af0090 --- /dev/null +++ b/platforms/ios/runner/lib/terminal/ExecutorService.swift @@ -0,0 +1,79 @@ +import AcodeAlpine +import Foundation + +class ExecutorService: BaseService { + var background: Bool { false } + private let runtime = AlpineRuntime.shared + private var streams: [AlpineStreamServer] = [] + + override func exec(action: String, args: [Any], callback: Callback) { + runtime.queue.async { [self] in + do { + let value = args[safe: 0] as? String ?? "" + switch action { + case "start": + let process = try runtime.start(value, background: background) + callback.success(process.id, keep: true) + process.listener = { kind, text in callback.success("\(kind):\(text)", keep: kind != "exit") } + case "exec": try runtime.execute(value, callback: callback) + case "write": + guard let process = runtime.processes[value], process.status == nil else { throw terminalError("Process not running") } + try process.write(args[safe: 1] as? String ?? "") + callback.success() + case "stop": runtime.stop(value); callback.success() + case "isRunning": + callback.success(runtime.processes[value].map { alpine_running($0.pid) } == true ? "running" : "stopped") + case "listProcesses": callback.success(runtime.processes.values.filter { $0.background == background && $0.status == nil }.map(\.info)) + case "listAllProcesses": try listAllProcesses(callback) + case "killProcess": + guard let pid = args[safe: 0] as? Int, pid > 1 else { throw terminalError("Invalid process") } + guard alpine_kill(Int32(pid)) == 0 else { throw terminalError("Process not running") } + callback.success() + case "stopService": runtime.stopAll(background: background); callback.success() + case "setProotDebug", "moveToForeground", "moveToBackground": callback.success() + case "spawn": + guard let command = args[safe: 0] as? [String], !command.isEmpty else { throw terminalError("Command is required") } + let server = try AlpineStreamServer(command: command, callback: callback) + streams.append(server) + server.onStop = { [weak self, weak server] in + self?.runtime.queue.async { self?.streams.removeAll { $0 === server } } + } + server.start() + case "loadLibrary": throw terminalError("Loading native libraries directly from JavaScript is not supported.") + default: callback.error("Unknown Executor action: \(action)") + } + } catch { callback.error(error.localizedDescription) } + } + } + + override func reset() { + runtime.queue.async { [self] in + streams.forEach { $0.stop() } + streams.removeAll() + // AXS and its PTYs survive a WebView reload, as they do on Android. + for process in runtime.processes.values where process.background == background { process.listener = nil } + } + } + + private func listAllProcesses(_ callback: Callback) throws { + try runtime.start("busybox ps -o pid,ppid,comm,args", completion: { status, output, errors in + guard status == 0 else { callback.error(errors); return } + let rows: [[String: Any]] = output.split(separator: "\n").dropFirst().compactMap { line in + let fields = line.split(maxSplits: 3, whereSeparator: \.isWhitespace) + guard fields.count >= 3, let pid = Int(fields[0]), let parent = Int(fields[1]) else { return nil } + return ["pid": pid, "ppid": parent, "name": String(fields[2]), + "command": fields.count > 3 ? String(fields[3]) : String(fields[2]), + "state": "", "memory": 0, "isSelf": pid == 1] + } + callback.success(rows) + }) + } +} + +final class BackgroundExecutorService: ExecutorService { + override var background: Bool { true } +} + +func terminalError(_ message: String) -> NSError { + NSError(domain: "AcodeTerminal", code: 1, userInfo: [NSLocalizedDescriptionKey: message]) +} diff --git a/platforms/ios/runner/lib/terminal/TerminalServer.swift b/platforms/ios/runner/lib/terminal/TerminalServer.swift new file mode 100644 index 0000000000..d1ff08391c --- /dev/null +++ b/platforms/ios/runner/lib/terminal/TerminalServer.swift @@ -0,0 +1,204 @@ +import Foundation +import UIKit + +/// Serves the AXS HTTP/WebSocket API from the host so terminal traffic never +/// passes through emulated sockets. Guest shells are the only emulated part. +final class TerminalServer { + static let shared = TerminalServer() + private static let port = 8767 + private static let origins: Set = ["https://localhost", "acode://localhost"] + private static let captureLimit = 16 * 1024 * 1024 + private let queue = DispatchQueue(label: "app.acode.terminal", qos: .userInitiated) + private let runtime = AlpineRuntime.shared + private var server: LocalHTTPServer? + private var listening = false + private var shell = "" + private var sessions: [Int32: TerminalSession] = [:] + + private init() { + // iOS reclaims listening sockets of suspended apps; sessions outlive the listener. + NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil) { [weak self] _ in + self?.queue.async { self?.relisten() } + } + } + + var isRunning: Bool { queue.sync { listening } } + + func start(shell: String, completion: @escaping (Error?) -> Void) { + queue.async { [self] in + guard server == nil else { completion(nil); return } + self.shell = shell + listen(completion) + } + } + + func stop() { + queue.async { [self] in + for session in sessions.values { terminate(session) } + sessions.removeAll() + server?.stop() + server = nil + listening = false + } + } + + private func listen(_ completion: @escaping (Error?) -> Void = { _ in }) { + do { + let server = try LocalHTTPServer(port: Self.port, loopback: true, queue: queue) + self.server = server + server.onRequest = { [weak self] request, client in self?.route(request, client) } + server.start { [weak self, weak server] result in + guard let self, self.server === server else { return } + switch result { + case .success: + listening = true + completion(nil) + case .failure(let error): + self.server = nil + listening = false + completion(error) + } + } + } catch { completion(error) } + } + + private func relisten() { + guard let server else { return } + listening = false + server.stop { [weak self] in self?.queue.async { self?.listen() } } + } + + private func route(_ request: LocalHTTPRequest, _ client: LocalHTTPConnection) { + let path = request.target.split(separator: "?", maxSplits: 1).first.map(String.init) ?? "" + let parts = path.split(separator: "/").map(String.init) + let origin = request.headers["origin"].flatMap { Self.origins.contains($0) ? $0 : nil } + let respond = { (status: Int, body: Any) in Self.respond(client, status: status, body: body, origin: origin) } + // Browsers send cross-origin simple POSTs and WebSocket upgrades without a + // preflight, so preview or in-app browser pages could otherwise run commands. + guard Self.allows(origin: request.headers["origin"]) else { respond(403, ["error": "Origin not allowed"]); return } + let session = parts.count >= 2 && parts[0] == "terminals" ? Int32(parts[1]).flatMap { sessions[$0] } : nil + switch (request.method, parts.count) { + case ("OPTIONS", _): respond(204, "") + case ("GET", 0): respond(200, "Acode terminal server") + case ("GET", 1) where parts[0] == "status": respond(200, "OK") + case ("POST", 1) where parts[0] == "terminals": create(request, respond) + case ("POST", 1) where parts[0] == "execute-command": execute(request, respond) + case ("GET", 2) where parts[0] == "terminals": + guard let session else { respond(404, ["error": "Session not found"]); return } + guard let socket = LocalWebSocket.accept(request, client: client) else { respond(400, ["error": "WebSocket upgrade required"]); return } + session.attach(socket) + case ("POST", 3) where parts[0] == "terminals" && parts[2] == "resize": + guard let session else { respond(404, ["error": "Session not found"]); return } + guard let size = Self.size(request.body) else { respond(400, ["error": "Invalid terminal size"]); return } + session.resize(rows: size.rows, cols: size.cols) + respond(200, ["success": true]) + case ("POST", 3) where parts[0] == "terminals" && parts[2] == "terminate": + guard let session else { respond(404, ["error": "Session not found"]); return } + sessions.removeValue(forKey: session.pid) + terminate(session) + respond(200, ["success": true]) + default: respond(404, ["error": "Not found"]) + } + } + + private func create(_ request: LocalHTTPRequest, _ respond: @escaping (Int, Any) -> Void) { + guard let size = Self.size(request.body) else { respond(400, ["error": "Invalid terminal size"]); return } + let shell = shell + runtime.queue.async { [self] in + do { + let session = try runtime.startTerminal(shell, rows: size.rows, cols: size.cols, queue: queue) + queue.async { [self, session] in + sessions[session.pid] = session + session.onFinish = { [weak self, weak session] in + if let session { self?.sessions.removeValue(forKey: session.pid) } + } + respond(200, String(session.pid)) + } + } catch { + queue.async { respond(500, ["error": error.localizedDescription]) } + } + } + } + + /// Matches AXS: `sh -c` on an 80×24 PTY in `cwd` (default HOME), answered when the + /// shell exits or after 30 s. Pipe-based execution stays available as `Executor.execute`. + private func execute(_ request: LocalHTTPRequest, _ respond: @escaping (Int, Any) -> Void) { + let body = (try? JSONSerialization.jsonObject(with: request.body)) as? [String: Any] ?? [:] + guard let command = body["command"] as? String else { respond(400, ["output": "", "error": "Command is required"]); return } + let directory = (body["cwd"] as? String ?? body["u_cwd"] as? String).flatMap { $0.isEmpty ? nil : $0 } + let script = (directory.map { "cd \(shellQuote($0)); " } ?? "") + "exec sh -c \(shellQuote(command))" + var answered = false + let answer = { (status: Int, output: String, error: String?) in + guard !answered else { return } + answered = true + respond(status, ["output": Self.stripEscapes(output), "error": error.map { $0 as Any } ?? NSNull()]) + } + let run = { [self] in + do { + let session = try runtime.startTerminal(script, rows: 24, cols: 80, queue: queue, scrollbackLimit: Self.captureLimit) + queue.async { [self, session] in + session.onExit = { [weak session] _ in + answer(200, String(decoding: session?.capturedOutput ?? Data(), as: UTF8.self), nil) + } + // Background children can outlive the shell, so the deadline tracks the response. + queue.asyncAfter(deadline: .now() + 30) { [self] in + guard !answered else { return } + terminate(session) + answer(500, "", "Command execution timed out") + } + } + } catch { + queue.async { answer(500, "", error.localizedDescription) } + } + } + runtime.queue.async { [self] in + guard let directory else { run(); return } + do { + try runtime.start("test -d \(shellQuote(directory))", completion: { [self] status, _, _ in + if status == 0 { run() } else { queue.async { answer(400, "", "Working directory does not exist") } } + }) + } catch { + queue.async { answer(500, "", error.localizedDescription) } + } + } + } + + private func terminate(_ session: TerminalSession) { + session.terminate() + runtime.killTerminal(session) + } + + private static func size(_ body: Data) -> (rows: Int, cols: Int)? { + let json = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:] + let value = { (key: String) -> Int? in + let number = (json[key] as? NSNumber)?.intValue ?? (json[key] as? String).flatMap { Int($0) } + return number.flatMap { (1...Int(UInt16.max)).contains($0) ? $0 : nil } + } + guard let rows = value("rows"), let cols = value("cols") else { return nil } + return (rows, cols) + } + + /// Native callers and guest programs send no Origin; browser pages always do. + static func allows(origin: String?) -> Bool { + guard let origin else { return true } + return origins.contains(origin) + } + + private static func respond(_ client: LocalHTTPConnection, status: Int, body: Any, origin: String?) { + var headers = ["Access-Control-Allow-Methods": "*", "Access-Control-Allow-Headers": "*"] + if let origin { headers["Access-Control-Allow-Origin"] = origin } + let data: Data + if let text = body as? String { + data = Data(text.utf8) + headers["Content-Type"] = "text/plain; charset=utf-8" + } else { + data = (try? JSONSerialization.data(withJSONObject: body)) ?? Data() + headers["Content-Type"] = "application/json" + } + client.respond(status: status, headers: headers, body: data) + } + + private static func stripEscapes(_ text: String) -> String { + text.replacingOccurrences(of: "\u{1B}\\[[0-9;?]*[A-Za-z]", with: "", options: .regularExpression) + } +} diff --git a/platforms/ios/runner/lib/terminal/TerminalSession.swift b/platforms/ios/runner/lib/terminal/TerminalSession.swift new file mode 100644 index 0000000000..84380196c1 --- /dev/null +++ b/platforms/ios/runner/lib/terminal/TerminalSession.swift @@ -0,0 +1,196 @@ +import AcodeAlpine +import Foundation + +/// One command on a guest pseudo-terminal. Output arrives on guest threads; +/// everything else runs on the terminal server's queue. +final class TerminalSession { + static let replayLimit = 256 * 1024 + private static let unsentLimit = 1024 * 1024 + private static let frameSize = 8 * 1024 + private static let coalesceDelay = DispatchTimeInterval.milliseconds(8) + private let queue: DispatchQueue + private let scrollbackLimit: Int + private let output = NSLock() + private var scrollback = Data() + private var pending = Data() + private var unsent = 0 + private var attached = false + private var flushScheduled = false + private var socket: LocalWebSocket? + private var input = Data() + private var handle: OpaquePointer? + private var status: Int32? + private(set) var pid: Int32 = 0 + var onFinish: (() -> Void)? + var onExit: ((Int32) -> Void)? + + /// Keeps the last `scrollbackLimit` bytes for replay on reattach or for `capturedOutput`. + init(queue: DispatchQueue, scrollbackLimit: Int = replayLimit) { + self.queue = queue + self.scrollbackLimit = scrollbackLimit + } + + var capturedOutput: Data { + output.lock() + defer { output.unlock() } + return Data(scrollback.suffix(scrollbackLimit)) + } + + /// Queried by blocking guest writers, which wait while the client is behind. + var congested: Bool { + output.lock() + defer { output.unlock() } + return attached && unsent > Self.unsentLimit + } + + func started(pid: Int32, handle: OpaquePointer) { + self.pid = pid + self.handle = handle + } + + /// Replays recent output, then streams live output until the socket closes. + func attach(_ socket: LocalWebSocket) { + if let status { + socket.send(Self.exitMessage(status), text: true) { socket.close() } + onFinish?() + return + } + self.socket?.close() + output.lock() + let history = scrollback.suffix(Self.replayLimit) + pending.removeAll() + unsent = 0 + attached = true + output.unlock() + self.socket = socket + socket.onMessage = { [weak self] data, _ in self?.write(data) } + socket.onClose = { [weak self, weak socket] in + guard let self, self.socket === socket else { return } + self.detach() + } + if !history.isEmpty { socket.send(Data(history)) } + } + + func resize(rows: Int, cols: Int) { + guard let handle else { return } + alpine_terminal_resize(handle, Int32(rows), Int32(cols)) + } + + func terminate() { + socket?.close() + close() + } + + /// Called by the runtime when the shell exits. + func finish(_ code: Int32) { + queue.async { [self] in + guard status == nil else { return } + status = code + close() + flush() + onExit?(code) + onExit = nil + guard let socket else { return } + socket.send(Self.exitMessage(code), text: true) { socket.close() } + onFinish?() + } + } + + /// Runs on guest threads. + func receive(_ data: Data) { + output.lock() + scrollback.append(data) + if scrollback.count > scrollbackLimit * 2 { + scrollback = Data(scrollback.suffix(scrollbackLimit)) + } + guard attached else { output.unlock(); return } + pending.append(data) + unsent += data.count + let immediate = pending.count >= Self.frameSize + let schedule = !flushScheduled + flushScheduled = true + output.unlock() + if immediate { queue.async { self.flush() } } + else if schedule { queue.asyncAfter(deadline: .now() + Self.coalesceDelay) { self.flush() } } + } + + private func flush() { + output.lock() + let data = pending + pending.removeAll(keepingCapacity: true) + flushScheduled = false + output.unlock() + guard !data.isEmpty, let socket else { return } + socket.send(data) { [weak self] in self?.acknowledge(data.count) } + } + + private func acknowledge(_ count: Int) { + output.lock() + unsent = max(0, unsent - count) + output.unlock() + wakeWriters() + } + + private func detach() { + socket = nil + output.lock() + attached = false + pending.removeAll() + unsent = 0 + output.unlock() + wakeWriters() + } + + private func wakeWriters() { + guard let handle else { return } + alpine_terminal_drained(handle) + } + + private func write(_ data: Data) { + let idle = input.isEmpty + input.append(data) + if idle { drainInput() } + } + + // The guest line buffer holds 4 KiB, so large pastes are fed as the shell reads. + private func drainInput() { + guard let handle, !input.isEmpty else { input.removeAll(); return } + let written = input.withUnsafeBytes { bytes in + alpine_terminal_input(handle, bytes.bindMemory(to: CChar.self).baseAddress, bytes.count) + } + if written > 0 { input = Data(input.dropFirst(written)) } + guard !input.isEmpty else { return } + queue.asyncAfter(deadline: .now() + .milliseconds(10)) { [weak self] in self?.drainInput() } + } + + private func close() { + guard let handle else { return } + self.handle = nil + input.removeAll() + alpine_terminal_close(handle) + } + + private static func exitMessage(_ code: Int32) -> Data { + let message: [String: Any] = [ + "type": "exit", + "data": ["exit_code": code, "signal": NSNull(), + "message": code == 0 ? "Process exited successfully" : "Process exited with non-zero status"], + ] + return (try? JSONSerialization.data(withJSONObject: message)) ?? Data() + } +} + +let terminalCallbacks = AlpineTerminalCallbacks( + output: { context, data, length in + guard let context, let data else { return } + Unmanaged<TerminalSession>.fromOpaque(context).takeUnretainedValue().receive(Data(bytes: data, count: length)) + }, + congested: { context in + guard let context else { return false } + return Unmanaged<TerminalSession>.fromOpaque(context).takeUnretainedValue().congested + }, + release: { context in + guard let context else { return } + Unmanaged<TerminalSession>.fromOpaque(context).release() + } +) diff --git a/platforms/ios/runner/lib/workspace/WorkspaceContent.swift b/platforms/ios/runner/lib/workspace/WorkspaceContent.swift new file mode 100644 index 0000000000..487cb12661 --- /dev/null +++ b/platforms/ios/runner/lib/workspace/WorkspaceContent.swift @@ -0,0 +1,82 @@ +import Foundation + +struct WorkspaceContent { + let database: WorkspaceDatabase + static let indexedCharacters = 512 * 1024 + static let indexedBytes = indexedCharacters * 4 + static let binaryExtensions: Set<String> = Set("3gp 7z aab aac apk avi bin bmp class db dex dll doc docx eot exe flac gif gz heic ico jar jpeg jpg keystore m4a m4v mkv mov mp3 mp4 o odt ogg otf pdf png ppt pptx pyc rar so sqlite sqlite3 tar tgz ttf wav webm webp woff woff2 xls xlsx xz zip".split(separator: " ").map(String.init)) + static let textExtensions: Set<String> = Set("astro c cc cfg conf cpp cs css csv cxx dart env go graphql h hpp htm html java js json jsx kt kts less lua md mjs php properties py rb rs sass scss sh sql svg swift toml ts tsx txt vue xml yaml yml".split(separator: " ").map(String.init)) + static let binaryMime: Set<String> = Set("application/java-archive application/java-vm application/octet-stream application/pdf application/vnd.android.package-archive application/zip application/x-7z-compressed application/x-rar-compressed application/x-sqlite3 application/x-tar application/x-xz".split(separator: " ").map(String.init)) + static let textMime: Set<String> = Set("application/javascript application/json application/ld+json application/sql application/typescript application/x-javascript application/x-php application/x-sh application/x-yaml application/xhtml+xml application/xml image/svg+xml".split(separator: " ").map(String.init)) + + func get(_ entry: WorkspaceEntry, overlays: [String: String], encoding: String, useIndex: Bool, large: Bool, job: WorkspaceJob) throws -> String? { + _ = try AppFiles.shared.resolve(entry.url) + if let text = overlays[entry.url] { return text } + if useIndex, let cache = try database.rows("SELECT * FROM content WHERE url = ?", [entry.url]).first, + (entry.size == 0 || (cache["size"] as? NSNumber)?.int64Value == entry.size), + (entry.modified == 0 || (cache["modified_date"] as? NSNumber)?.doubleValue == entry.modified) { return cache["text"] as? String } + if useIndex && !large, let text = try index(entry, encoding: encoding, job: job) { return text } + let limit = (large ? 128 : 16) * 1024 * 1024 + return try read(entry, encoding: encoding, bytes: limit, characters: limit, job: job) + } + + func index(_ entry: WorkspaceEntry, encoding: String, job: WorkspaceJob) throws -> String? { + guard let text = try read(entry, encoding: encoding, bytes: Self.indexedBytes, characters: Self.indexedCharacters, job: job) else { return nil } + try database.execute("INSERT OR REPLACE INTO content VALUES (?, ?, ?, ?, ?)", [entry.url, entry.size, entry.modified, encoding, text]) + return text + } + + private func read(_ entry: WorkspaceEntry, encoding: String, bytes limit: Int, characters: Int, job: WorkspaceJob) throws -> String? { + guard !entry.directory, !Self.isBinary(entry), entry.size <= limit else { return nil } + let url = try AppFiles.shared.resolve(entry.url) + let bytes = try AppFiles.shared.coordinate(url) { url in + let input = try FileHandle(forReadingFrom: url) + defer { try? input.close() } + var data = Data() + while data.count <= limit { + try job.check() + guard let next = try input.read(upToCount: min(65536, limit + 1 - data.count)), !next.isEmpty else { break } + data.append(next) + } + return data + } + guard bytes.count <= limit else { return nil } + let detected = Self.encoding(bytes, fallback: encoding) + if detected != .utf16LittleEndian && detected != .utf16BigEndian && detected != .utf32 && detected != .utf32LittleEndian && detected != .utf32BigEndian && Self.looksBinary(bytes) { return nil } + let text = detected == .utf8 ? String(decoding: bytes, as: UTF8.self) : String(data: bytes, encoding: detected) + guard let text, text.utf16.count <= characters, !text.utf16.prefix(2048).contains(where: { $0 <= 8 || $0 == 11 || (14...31).contains($0) || $0 == 127 }) else { return nil } + return text + } + + static func isBinary(_ entry: WorkspaceEntry) -> Bool { + if entry.directory { return false } + let mime = entry.mime.lowercased().split(separator: ";").first.map(String.init)?.trimmingCharacters(in: .whitespaces) ?? "" + let parts = entry.name.lowercased().split(separator: ".", omittingEmptySubsequences: false) + if mime.hasPrefix("text/") || textMime.contains(mime) || (parts.count > 1 && textExtensions.contains(String(parts.last!))) { return false } + if ["audio/", "font/", "image/", "model/", "video/"].contains(where: { mime.hasPrefix($0) }) || binaryMime.contains(mime) { return true } + return parts.count > 1 && binaryExtensions.contains(String(parts.last!)) || parts.count > 2 && binaryExtensions.contains(parts.suffix(2).joined(separator: ".")) + } + + private static func encoding(_ bytes: Data, fallback: String) -> String.Encoding { + if bytes.starts(with: [0xef, 0xbb, 0xbf]) { return .utf8 } + if bytes.starts(with: [0xff, 0xfe]) { return .utf16LittleEndian } + if bytes.starts(with: [0xfe, 0xff]) { return .utf16BigEndian } + let sample = Array(bytes.prefix(8192)) + if sample.count >= 8 { + let pairs = sample.count / 2 + let even = stride(from: 0, to: pairs * 2, by: 2).filter { sample[$0] == 0 }.count + let odd = stride(from: 1, to: pairs * 2, by: 2).filter { sample[$0] == 0 }.count + if Double(odd) > Double(pairs) * 0.35 && Double(even) < Double(pairs) * 0.05 { return .utf16LittleEndian } + if Double(even) > Double(pairs) * 0.35 && Double(odd) < Double(pairs) * 0.05 { return .utf16BigEndian } + } + return (try? FileContents.encoding(fallback)) ?? .utf8 + } + + private static func looksBinary(_ bytes: Data) -> Bool { + let sample = bytes.prefix(8192) + if sample.contains(0) { return true } + let control = sample.filter { $0 < 32 && ![9, 10, 13, 12].contains($0) }.count + let high = sample.filter { $0 >= 128 }.count + return Double(control) > max(8, Double(sample.count) * 0.02) && Double(high) < Double(sample.count) * 0.5 + } +} diff --git a/platforms/ios/runner/lib/workspace/WorkspaceDatabase.swift b/platforms/ios/runner/lib/workspace/WorkspaceDatabase.swift new file mode 100644 index 0000000000..938c109dc2 --- /dev/null +++ b/platforms/ios/runner/lib/workspace/WorkspaceDatabase.swift @@ -0,0 +1,123 @@ +import Foundation +import SQLite3 + +final class WorkspaceDatabase { + private var connection: OpaquePointer? + private let lock = NSRecursiveLock() + private let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self) + + init(url: URL = AppFiles.shared.data.appendingPathComponent("workspace-index.sqlite")) throws { + guard sqlite3_open_v2(url.path, &connection, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, nil) == SQLITE_OK else { + let error = failure(); sqlite3_close(connection); connection = nil; throw error + } + sqlite3_busy_timeout(connection, 5000) + try execute("PRAGMA journal_mode=WAL") + try execute("CREATE TABLE IF NOT EXISTS workspaces (root_url TEXT PRIMARY KEY, title TEXT, indexed_at INTEGER)") + try execute("CREATE TABLE IF NOT EXISTS files (root_url TEXT, parent_url TEXT, url TEXT, name TEXT, path TEXT, mime TEXT, is_directory INTEGER, size INTEGER, modified_date INTEGER, PRIMARY KEY (root_url, url))") + try execute("CREATE TABLE IF NOT EXISTS content (url TEXT PRIMARY KEY, size INTEGER, modified_date INTEGER, encoding TEXT, text TEXT)") + try execute("CREATE INDEX IF NOT EXISTS idx_files_parent ON files(root_url, parent_url)") + } + + deinit { sqlite3_close(connection) } + + @discardableResult + func execute(_ sql: String, _ values: [Any] = []) throws -> Int { + lock.lock(); defer { lock.unlock() } + let statement = try prepare(sql, values) + defer { sqlite3_finalize(statement) } + var status = sqlite3_step(statement) + while status == SQLITE_ROW { status = sqlite3_step(statement) } + guard status == SQLITE_DONE else { throw failure() } + return Int(sqlite3_changes(connection)) + } + + func rows(_ sql: String, _ values: [Any] = []) throws -> [[String: Any]] { + lock.lock(); defer { lock.unlock() } + let statement = try prepare(sql, values) + defer { sqlite3_finalize(statement) } + var result: [[String: Any]] = [] + var status = sqlite3_step(statement) + while status == SQLITE_ROW { + var row: [String: Any] = [:] + for column in 0..<sqlite3_column_count(statement) { + let name = String(cString: sqlite3_column_name(statement, column)) + switch sqlite3_column_type(statement, column) { + case SQLITE_INTEGER: row[name] = sqlite3_column_int64(statement, column) + case SQLITE_FLOAT: row[name] = sqlite3_column_double(statement, column) + case SQLITE_TEXT: + if let bytes = sqlite3_column_text(statement, column) { + row[name] = String(decoding: UnsafeBufferPointer(start: bytes, count: Int(sqlite3_column_bytes(statement, column))), as: UTF8.self) + } + default: row[name] = NSNull() + } + } + result.append(row) + status = sqlite3_step(statement) + } + guard status == SQLITE_DONE else { throw failure() } + return result + } + + func transaction<T>(_ body: () throws -> T) throws -> T { + lock.lock(); defer { lock.unlock() } + try execute("BEGIN IMMEDIATE") + do { + let value = try body() + try execute("COMMIT") + return value + } catch { _ = try? execute("ROLLBACK"); throw error } + } + + func save(_ entry: WorkspaceEntry) throws { + try execute("INSERT OR REPLACE INTO files VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", entry.values) + } + + func removeSubtree(root: String, url: String) throws -> Int { + let condition = "root_url = ? AND (url = ? OR url LIKE ? ESCAPE '\\')" + let values = [root, url, Self.escapeLike(url.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/") + "%"] + try execute("DELETE FROM content WHERE url IN (SELECT url FROM files WHERE " + condition + ")", values) + return try execute("DELETE FROM files WHERE " + condition, values) + } + + func clear(_ roots: [String]) throws { + try transaction { + if roots.isEmpty { + try execute("DELETE FROM content"); try execute("DELETE FROM files"); try execute("DELETE FROM workspaces") + } else { + for root in roots { + try execute("DELETE FROM content WHERE url IN (SELECT url FROM files WHERE root_url = ?)", [root]) + try execute("DELETE FROM files WHERE root_url = ?", [root]) + try execute("DELETE FROM workspaces WHERE root_url = ?", [root]) + } + } + } + } + + private func prepare(_ sql: String, _ values: [Any]) throws -> OpaquePointer { + var statement: OpaquePointer? + guard sqlite3_prepare_v2(connection, sql, -1, &statement, nil) == SQLITE_OK, let statement else { throw failure() } + do { + for (offset, value) in values.enumerated() { + let index = Int32(offset + 1) + let status: Int32 + if let text = value as? String { status = text.withCString { sqlite3_bind_text(statement, index, $0, Int32(text.utf8.count), transient) } } + else if let number = value as? NSNumber { status = sqlite3_bind_double(statement, index, number.doubleValue) } + else { status = sqlite3_bind_null(statement, index) } + guard status == SQLITE_OK else { throw failure() } + } + return statement + } catch { sqlite3_finalize(statement); throw error } + } + + private func failure() -> WorkspaceFailure { WorkspaceFailure(String(cString: sqlite3_errmsg(connection))) } + + static func escapeLike(_ value: String) -> String { + value.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "%", with: "\\%").replacingOccurrences(of: "_", with: "\\_") + } +} + +struct WorkspaceFailure: LocalizedError { + let message: String + var errorDescription: String? { message } + init(_ message: String) { self.message = message } +} diff --git a/platforms/ios/runner/lib/workspace/WorkspaceEntry.swift b/platforms/ios/runner/lib/workspace/WorkspaceEntry.swift new file mode 100644 index 0000000000..1dece70a63 --- /dev/null +++ b/platforms/ios/runner/lib/workspace/WorkspaceEntry.swift @@ -0,0 +1,41 @@ +import Foundation + +struct WorkspaceEntry { + let root: String + let parent: String + let url: String + let name: String + let path: String + let mime: String + let directory: Bool + let size: Int64 + let modified: Double + var values: [Any] { [root, parent, url, name, path, mime, directory ? 1 : 0, size, modified] } + var json: [String: Any] { + ["rootUrl": root, "parent": parent, "parentUrl": parent, "url": url, "uri": url, + "name": name, "path": path, "mime": mime, "type": mime, "isDirectory": directory, + "isFile": !directory, "size": size, "modifiedDate": modified] + } + + init(url: URL, root: String, parent: String, parentPath: String) throws { + let safeURL = try AppFiles.shared.resolve(url.absoluteString) + let info = try safeURL.resourceValues(forKeys: [.isDirectoryKey, .fileSizeKey, .contentModificationDateKey]) + self.root = root; self.parent = parent + self.url = URL(fileURLWithPath: url.path, isDirectory: false).absoluteString + name = url.lastPathComponent; path = parentPath + "/" + name + directory = info.isDirectory == true + let detectedMime = AppFiles.shared.mimeType(url) + mime = directory ? "vnd.android.document/directory" : (detectedMime == "application/octet-stream" ? "" : detectedMime) + size = max(0, Int64(info.fileSize ?? 0)); modified = max(0, (info.contentModificationDate ?? .distantPast).timeIntervalSince1970 * 1000) + } + + init(_ row: [String: Any], database: Bool = false) { + root = row[database ? "root_url" : "rootUrl"] as? String ?? "" + parent = row[database ? "parent_url" : "parentUrl"] as? String ?? row["parent"] as? String ?? "" + url = row["url"] as? String ?? ""; name = row["name"] as? String ?? ""; path = row["path"] as? String ?? "" + mime = row["mime"] as? String ?? row["type"] as? String ?? "" + directory = (row[database ? "is_directory" : "isDirectory"] as? NSNumber)?.boolValue ?? false + size = max(0, (row["size"] as? NSNumber)?.int64Value ?? 0) + modified = max(0, (row[database ? "modified_date" : "modifiedDate"] as? NSNumber)?.doubleValue ?? (row["lastModified"] as? NSNumber)?.doubleValue ?? 0) + } +} diff --git a/platforms/ios/runner/lib/workspace/WorkspaceGlob.swift b/platforms/ios/runner/lib/workspace/WorkspaceGlob.swift new file mode 100644 index 0000000000..98c823d5fa --- /dev/null +++ b/platforms/ios/runner/lib/workspace/WorkspaceGlob.swift @@ -0,0 +1,39 @@ +import Foundation + +struct WorkspaceGlob { + static func skipsDirectory(_ path: String, options: [String: Any]) -> Bool { + let patterns = options["excludeFolders"] as? [String] ?? [] + return matches(path, patterns: patterns) || matches(path + "/", patterns: patterns) + } + + static func patterns(_ value: String?) -> [String] { + (value ?? "").split(separator: ",").map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty } + } + + static func matches(_ path: String, patterns: [String]) -> Bool { + patterns.contains { matches(path, pattern: $0) } + } + + private static func matches(_ path: String, pattern: String) -> Bool { + guard !pattern.isEmpty else { return false } + if pattern == "**" { return true } + let path = path.replacingOccurrences(of: "\\", with: "/") + let characters = Array(pattern.replacingOccurrences(of: "\\", with: "/")) + var expression = "^", index = 0 + while index < characters.count { + switch characters[index] { + case "*": + if index + 1 < characters.count && characters[index + 1] == "*" { + index += 1 + if index + 1 < characters.count && characters[index + 1] == "/" { expression += "(?:.*/)?"; index += 1 } + else { expression += ".*" } + } else { expression += "[^/]*" } + case "?": expression += "." + default: expression += NSRegularExpression.escapedPattern(for: String(characters[index])) + } + index += 1 + } + guard let regex = try? NSRegularExpression(pattern: expression + "$") else { return false } + return [path, (path as NSString).lastPathComponent].contains { regex.firstMatch(in: $0, range: NSRange(location: 0, length: ($0 as NSString).length)) != nil } + } +} diff --git a/platforms/ios/runner/lib/workspace/WorkspaceIndex.swift b/platforms/ios/runner/lib/workspace/WorkspaceIndex.swift new file mode 100644 index 0000000000..7dc04ffadc --- /dev/null +++ b/platforms/ios/runner/lib/workspace/WorkspaceIndex.swift @@ -0,0 +1,102 @@ +import Foundation + +final class WorkspaceIndex { + let database: Result<WorkspaceDatabase, Error> + private let control = DispatchQueue(label: "app.acode.workspace.control") + private let indexing = DispatchQueue(label: "app.acode.workspace.index", qos: .userInitiated) + private let searching: OperationQueue = { + let queue = OperationQueue(); queue.name = "app.acode.workspace.search"; queue.maxConcurrentOperationCount = 2; return queue + }() + private var jobs: [String: WorkspaceJob] = [:] + + init(database: Result<WorkspaceDatabase, Error>? = nil) { + self.database = database ?? Result { try WorkspaceDatabase() } + } + + func reset() { + control.async { self.jobs.values.forEach { $0.cancel() }; self.jobs.removeAll() } + } + + func exec(_ action: String, args: [Any], callback: Callback) { + control.async { + let options = args[safe: 0] as? [String: Any] ?? [:] + switch action { + case "workspace cancel": + self.jobs[args[safe: 0] as? String ?? ""]?.cancel(); callback.success("OK") + case "workspace scan", "workspace search": + let id = options["id"] as? String ?? UUID().uuidString + let job = WorkspaceJob(id: id) { type, payload, terminal in + callback.success(payload.merging(["id": id, "type": type, "action": type]) { _, value in value }, keep: !terminal) + } + self.jobs.removeValue(forKey: id)?.cancel(); self.jobs[id] = job + let work = { + defer { self.control.async { if self.jobs[id] === job { self.jobs.removeValue(forKey: id) } } } + do { + if action == "workspace scan" { try self.scan(options, job: job) } + else { try self.search(options, job: job) } + } catch { + if job.cancelled && action == "workspace scan" { job.emit("cancelled", [:], true) } + else { job.emit("error", ["error": error.localizedDescription], true) } + } + } + if action == "workspace scan" { self.indexing.async(execute: work) } + else { self.searching.addOperation(work) } + default: + let work = { + do { + let db = try self.database.get() + switch action { + case "workspace query": callback.success(try self.query(options)) + case "workspace update": callback.success(try self.update(options)) + case "workspace mark dirty": + for url in args[safe: 0] as? [String] ?? [] { try db.execute("DELETE FROM content WHERE url = ?", [url]) } + callback.success("OK") + case "workspace clear": try db.clear(args[safe: 0] as? [String] ?? []); callback.success("OK") + default: throw WorkspaceFailure("Unknown workspace action: " + action) + } + } catch { callback.error(error.localizedDescription) } + } + if action == "workspace query" { self.searching.addOperation(work) } + else { self.indexing.async(execute: work) } + } + } + } + + func query(_ options: [String: Any]) throws -> [String: Any] { + var values: [Any] = [] + var condition = "1 = 1" + rootsClause(options["roots"] as? [String] ?? [], values: &values) + if let url = options["url"] as? String, !url.isEmpty { condition += " AND url = ?"; values.append(url) } + if options["includeDirectories"] as? Bool != true { condition += " AND is_directory = 0" } + let text = (options["text"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + var order = "name COLLATE NOCASE, path COLLATE NOCASE" + if !text.isEmpty { + condition += " AND (name LIKE ? ESCAPE '\\' OR path LIKE ? ESCAPE '\\')" + values += Array(repeating: "%" + WorkspaceDatabase.escapeLike(text) + "%", count: 2) + order = "CASE WHEN name LIKE ? ESCAPE '\\' THEN 0 ELSE 1 END, " + order + values.append(WorkspaceDatabase.escapeLike(text) + "%") + } + let limit = max(1, min(1000, options["limit"] as? Int ?? 200)) + let cursor = max(0, options["cursor"] as? Int ?? options["offset"] as? Int ?? 0) + let rows = try database.get().rows("SELECT * FROM files WHERE " + condition + " ORDER BY " + order + " LIMIT ? OFFSET ?", values + [limit + 1, cursor]) + return ["entries": rows.prefix(limit).map { WorkspaceEntry($0, database: true).json }, "hasMore": rows.count > limit, "cursor": rows.count > limit ? cursor + limit as Any : NSNull()] + } + + func rootsClause(_ roots: [String], values: inout [Any]) -> String { + guard !roots.isEmpty else { return "" } + let nonempty = roots.filter { !$0.isEmpty } + guard !nonempty.isEmpty else { return " AND 0 = 1" } + values += nonempty + return " AND root_url IN (" + Array(repeating: "?", count: nonempty.count).joined(separator: ",") + ")" + } +} + +final class WorkspaceJob { + let id: String + let emit: (String, [String: Any], Bool) -> Void + private let lock = NSLock() + private var stopped = false + var cancelled: Bool { lock.lock(); defer { lock.unlock() }; return stopped } + init(id: String = UUID().uuidString, emit: @escaping (String, [String: Any], Bool) -> Void = { _, _, _ in }) { self.id = id; self.emit = emit } + func cancel() { lock.lock(); stopped = true; lock.unlock() } + func check() throws { if cancelled { throw WorkspaceFailure("Search cancelled") } } +} diff --git a/platforms/ios/runner/lib/workspace/WorkspaceMatches.swift b/platforms/ios/runner/lib/workspace/WorkspaceMatches.swift new file mode 100644 index 0000000000..230a2f22f6 --- /dev/null +++ b/platforms/ios/runner/lib/workspace/WorkspaceMatches.swift @@ -0,0 +1,86 @@ +import Foundation + +final class WorkspaceMatches { + let text: String + let source: NSString + let regex: NSRegularExpression + let job: WorkspaceJob + private var deadline = ProcessInfo.processInfo.systemUptime + 2 + + init(text: String, regex: NSRegularExpression, job: WorkspaceJob) { + self.text = text; source = text as NSString; self.regex = regex; self.job = job + } + + func search(_ emit: ([[String: Any]], Bool) -> Void) throws { + var batch: [[String: Any]] = [] + var count = 0, cursor = 0, row = 0, column = 0 + try enumerate { match in + let range = match.range + if count == 5000 { emit(batch, true); batch.removeAll(); return false } + let word = self.source.substring(with: NSRange(location: range.location, length: min(160, range.length))) + try self.advance(to: range.location, cursor: &cursor, row: &row, column: &column) + let start = ["row": row, "column": column] + try self.advance(to: NSMaxRange(range), cursor: &cursor, row: &row, column: &column) + batch.append(["match": word, "renderText": self.render(word), "line": self.surrounding(range), "position": ["start": start, "end": ["row": row, "column": column]]]) + count += 1 + if batch.count == 200 && count < 5000 { emit(batch, false); batch.removeAll(keepingCapacity: true); self.renew() } + return true + } + if !batch.isEmpty { emit(batch, false) } + } + + func replace(_ replacement: WorkspaceReplacement) throws -> String { + let result = NSMutableString(capacity: source.length) + var cursor = 0 + try enumerate { match in + result.append(self.source.substring(with: NSRange(location: cursor, length: match.range.location - cursor))) + result.append(replacement.expand(match, in: self.source)) + cursor = NSMaxRange(match.range) + return true + } + result.append(source.substring(from: cursor)) + return result as String + } + + private func enumerate(_ match: (NSTextCheckingResult) throws -> Bool) throws { + var failure: Error? + regex.enumerateMatches(in: text, options: [.reportProgress], range: NSRange(location: 0, length: source.length)) { result, flags, stop in + do { + try self.check() + if let result, try !match(result) { stop.pointee = true } + if flags.contains(.internalError) { throw WorkspaceFailure("Regular expression failed") } + } catch { failure = error; stop.pointee = true } + } + if let failure { throw failure } + try job.check() + } + + private func advance(to position: Int, cursor: inout Int, row: inout Int, column: inout Int) throws { + while cursor < position { + if cursor & 1023 == 0 { try check() } + if source.character(at: cursor) == 10 { row += 1; column = 0 } else { column += 1 } + cursor += 1 + } + } + + private func surrounding(_ range: NSRange) -> String { + let remaining = max(0, 160 - range.length) + var start = range.location, end = min(NSMaxRange(range), range.location + 160) + let left = max(0, start - remaining / 2) + while start > left && ![10, 13].contains(source.character(at: start - 1)) { start -= 1 } + let right = min(source.length, start + 160) + while end < right && ![10, 13].contains(source.character(at: end)) { end += 1 } + var line = source.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: .whitespacesAndNewlines) + if start > 0 && ![10, 13].contains(source.character(at: start - 1)) { line = "..." + line } + if end < source.length && ![10, 13].contains(source.character(at: end)) { line += "..." } + return render(line) + } + + private func render(_ value: String) -> String { value.replacingOccurrences(of: "[\\r\\n]+", with: " ⏎ ", options: .regularExpression) } + private func check() throws { + try job.check() + guard ProcessInfo.processInfo.systemUptime <= deadline else { throw WorkspaceFailure("Search timed out; simplify the expression") } + } + + private func renew() { deadline = ProcessInfo.processInfo.systemUptime + 2 } +} diff --git a/platforms/ios/runner/lib/workspace/WorkspaceReplacement.swift b/platforms/ios/runner/lib/workspace/WorkspaceReplacement.swift new file mode 100644 index 0000000000..33679bdcfc --- /dev/null +++ b/platforms/ios/runner/lib/workspace/WorkspaceReplacement.swift @@ -0,0 +1,116 @@ +import Foundation + +/// Expands a replacement the way JavaScript's String.prototype.replace does +/// ($$, $&, $`, $', $1..$99, $<name>), so native regex replacements match the +/// JS worker path. +struct WorkspaceReplacement { + let template: NSString + let groupNames: Set<String> + let literal: Bool + + init(_ template: String, pattern: String, regExp: Bool) { + self.template = template as NSString + literal = !regExp + groupNames = regExp ? Self.groupNames(in: pattern) : [] + } + + func expand(_ match: NSTextCheckingResult, in source: NSString) -> String { + if literal { return template as String } + let out = NSMutableString(capacity: template.length) + let groups = match.numberOfRanges - 1 + let dollar: unichar = 36 + var index = 0 + while index < template.length { + let char = template.character(at: index) + guard char == dollar, index + 1 < template.length else { + out.append(template.substring(with: NSRange(location: index, length: 1))) + index += 1 + continue + } + let next = template.character(at: index + 1) + switch next { + case dollar: + out.append("$"); index += 2 + case 38: // & + out.append(source.substring(with: match.range)); index += 2 + case 96: // ` + out.append(source.substring(to: match.range.location)); index += 2 + case 39: // ' + out.append(source.substring(from: NSMaxRange(match.range))); index += 2 + case 48...57: + var group = Int(next) - 48 + var consumed = 1 + if index + 2 < template.length, case 48...57 = template.character(at: index + 2) { + let twoDigit = group * 10 + Int(template.character(at: index + 2)) - 48 + if twoDigit >= 1 && twoDigit <= groups { group = twoDigit; consumed = 2 } + } + if group >= 1 && group <= groups { + append(match.range(at: group), from: source, to: out) + index += 1 + consumed + } else { + out.append("$"); index += 1 + } + case 60 where !groupNames.isEmpty: // < + let close = template.range(of: ">", range: NSRange(location: index + 2, length: template.length - index - 2)) + guard close.location != NSNotFound else { out.append("$"); index += 1; continue } + let name = template.substring(with: NSRange(location: index + 2, length: close.location - index - 2)) + // JS: an unknown name expands to nothing once the pattern has named groups. + if groupNames.contains(name) { append(match.range(withName: name), from: source, to: out) } + index = close.location + 1 + default: + out.append("$"); index += 1 + } + } + return out as String + } + + private func append(_ range: NSRange, from source: NSString, to out: NSMutableString) { + if range.location != NSNotFound { out.append(source.substring(with: range)) } + } + + /// Named capture groups declared by the pattern, ignoring escaped text, + /// \Q...\E quotes and character classes. + static func groupNames(in pattern: String) -> Set<String> { + let chars = Array(pattern.utf16) + var names = Set<String>() + var classDepth = 0 + var index = 0 + while index < chars.count { + let char = chars[index] + if char == 92 { // backslash + if index + 1 < chars.count && chars[index + 1] == 81 { // Q + guard let end = quoteEnd(chars, from: index + 2) else { return names } + index = end + 1 + } else { + index += 1 + } + } else if classDepth > 0 { + if char == 91 { classDepth += 1 } else if char == 93 { classDepth -= 1 } + } else if char == 91 { // [ + classDepth = 1 + if index + 1 < chars.count && chars[index + 1] == 94 { index += 1 } + if index + 1 < chars.count && chars[index + 1] == 93 { index += 1 } + } else if char == 40, index + 3 < chars.count, chars[index + 1] == 63, chars[index + 2] == 60, isLetter(chars[index + 3]) { + var end = index + 3 + while end < chars.count && chars[end] != 62 { end += 1 } + names.insert(String(decoding: chars[(index + 3)..<end], as: UTF16.self)) + index = end + } + index += 1 + } + return names + } + + private static func quoteEnd(_ chars: [UInt16], from start: Int) -> Int? { + var index = start + while index + 1 < chars.count { + if chars[index] == 92 && chars[index + 1] == 69 { return index } + index += 1 + } + return nil + } + + private static func isLetter(_ char: UInt16) -> Bool { + (65...90).contains(char) || (97...122).contains(char) + } +} diff --git a/platforms/ios/runner/lib/workspace/WorkspaceScan.swift b/platforms/ios/runner/lib/workspace/WorkspaceScan.swift new file mode 100644 index 0000000000..f1a3460719 --- /dev/null +++ b/platforms/ios/runner/lib/workspace/WorkspaceScan.swift @@ -0,0 +1,99 @@ +import Foundation + +extension WorkspaceIndex { + func scan(_ options: [String: Any], job: WorkspaceJob) throws { + try job.check() + let root = options["rootUrl"] as? String ?? "" + let url = try AppFiles.shared.resolve(root) + guard try url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true else { throw WorkspaceFailure("Workspace is not a directory") } + let title = options["title"] as? String ?? url.lastPathComponent + let db = try database.get() + job.emit("status", ["state": "scanning", "message": "Scanning project files", "progress": 0], false) + let stats = try db.transaction { + try db.execute("INSERT OR REPLACE INTO workspaces VALUES (?, ?, ?)", [root, title, Date().timeIntervalSince1970 * 1000]) + try db.execute("DELETE FROM files WHERE root_url = ?", [root]) + let result = try walk(url, root: root, parent: root, path: title, options: options, job: job) + try job.check() + return result + } + job.emit("done", stats, true) + } + + func update(_ options: [String: Any]) throws -> [String: Any] { + let root = options["rootUrl"] as? String ?? "" + let rootURL = try AppFiles.shared.resolve(root) + let db = try database.get() + let savedTitle = try db.rows("SELECT title FROM workspaces WHERE root_url = ?", [root]).first?["title"] as? String + let title = options["title"] as? String ?? savedTitle ?? rootURL.lastPathComponent + return try db.transaction { + var removed = 0, added = 0 + for value in options["removed"] as? [String] ?? [] where !value.isEmpty && value != root { + let url = try checkedChild(value, root: rootURL) + removed += try db.removeSubtree(root: root, url: URL(fileURLWithPath: url.path, isDirectory: false).absoluteString) + } + for change in options["added"] as? [[String: Any]] ?? [] { + guard let value = change["url"] as? String, !value.isEmpty, let parent = change["parentUrl"] as? String, !parent.isEmpty else { continue } + let url = try checkedChild(value, root: rootURL) + _ = try checkedChild(parent, root: rootURL, allowRoot: true) + let parentPath = parent == root || (try? AppFiles.shared.resolve(parent))?.path == rootURL.path ? title : (try db.rows("SELECT path FROM files WHERE root_url = ? AND url = ?", [root, parent]).first?["path"] as? String ?? title) + removed += try db.removeSubtree(root: root, url: URL(fileURLWithPath: url.path, isDirectory: false).absoluteString) + guard let entry = try? WorkspaceEntry(url: url, root: root, parent: parent, parentPath: parentPath) else { continue } + if options["showHiddenFiles"] as? Bool != true && entry.name.hasPrefix(".") { continue } + try db.save(entry); added += 1 + if entry.directory && !WorkspaceGlob.skipsDirectory(entry.path, options: options) { + var updatedOptions = options; updatedOptions["indexContent"] = false; updatedOptions["emitEntries"] = false + let stats = try walk(url, root: root, parent: entry.url, path: entry.path, options: updatedOptions, job: WorkspaceJob()) + added += (stats["files"] as? Int ?? 0) + (stats["dirs"] as? Int ?? 0) + } + } + try db.execute("INSERT OR REPLACE INTO workspaces VALUES (?, ?, ?)", [root, title, Date().timeIntervalSince1970 * 1000]) + return ["added": added, "removed": removed] + } + } + + private func walk(_ initial: URL, root: String, parent: String, path: String, options: [String: Any], job: WorkspaceJob) throws -> [String: Any] { + let db = try database.get() + var stack = [(initial, parent, path)] + var visited = Set<String>(), batch: [[String: Any]] = [] + let initialPath = initial.resolvingSymlinksInPath() + var ancestor = initialPath.deletingLastPathComponent() + while ancestor.path != initialPath.path { + try job.check() + guard visited.insert(ancestor.path).inserted, ancestor.path != "/" else { break } + let parent = ancestor.deletingLastPathComponent() + guard parent.path.count < ancestor.path.count else { break } + ancestor = parent + } + var files = 0, directories = 0, indexed = 0 + while let (directory, parent, parentPath) = stack.popLast() { + try job.check() + guard visited.insert(directory.resolvingSymlinksInPath().path).inserted else { continue } + guard let children = try? AppFiles.shared.coordinate(directory, { try FileManager.default.contentsOfDirectory(at: $0, includingPropertiesForKeys: [.isDirectoryKey, .fileSizeKey, .contentModificationDateKey]) }) else { continue } + for child in children { + try job.check() + if options["showHiddenFiles"] as? Bool != true && child.lastPathComponent.hasPrefix(".") { continue } + guard let entry = try? WorkspaceEntry(url: child, root: root, parent: parent, parentPath: parentPath) else { continue } + try db.save(entry) + if entry.directory { directories += 1 } else { files += 1 } + if options["emitEntries"] as? Bool != false { + batch.append(entry.json) + if batch.count == 200 { job.emit("batch", ["entries": batch], false); batch.removeAll(keepingCapacity: true) } + } + if entry.directory { + if !WorkspaceGlob.skipsDirectory(entry.path, options: options) { stack.append((child, entry.url, entry.path)) } + } else if options["indexContent"] as? Bool == true { + _ = try? WorkspaceContent(database: db).index(entry, encoding: options["defaultEncoding"] as? String ?? "UTF-8", job: job) + indexed += 1 + } + } + } + if !batch.isEmpty { job.emit("batch", ["entries": batch], false) } + return ["files": files, "dirs": directories, "indexed": indexed] + } + + private func checkedChild(_ value: String, root: URL, allowRoot: Bool = false) throws -> URL { + let url = try AppFiles.shared.resolve(value) + guard (allowRoot && root.path == url.path) || url.path.hasPrefix(root.path + "/") else { throw WorkspaceFailure("Entry is outside the workspace") } + return url + } +} diff --git a/platforms/ios/runner/lib/workspace/WorkspaceSearch.swift b/platforms/ios/runner/lib/workspace/WorkspaceSearch.swift new file mode 100644 index 0000000000..dcc2263efb --- /dev/null +++ b/platforms/ios/runner/lib/workspace/WorkspaceSearch.swift @@ -0,0 +1,68 @@ +import Foundation + +extension WorkspaceIndex { + func search(_ options: [String: Any], job: WorkspaceJob) throws { + try job.check() + let db = try database.get() + let settings = options["options"] as? [String: Any] ?? [:] + let replacing = options["mode"] as? String == "replace" + let search = options["search"] as? String ?? "" + var pattern = settings["regExp"] as? Bool == true ? search : NSRegularExpression.escapedPattern(for: search) + if settings["wholeWord"] as? Bool == true { pattern = "\\b" + pattern + "\\b" } + let flags: NSRegularExpression.Options = settings["caseSensitive"] as? Bool == true ? [.anchorsMatchLines] : [.anchorsMatchLines, .caseInsensitive] + let regex = try NSRegularExpression(pattern: pattern, options: flags) + let replacement = WorkspaceReplacement(options["replace"] as? String ?? "", pattern: pattern, regExp: settings["regExp"] as? Bool == true) + let files = try searchFiles(options) + let content = WorkspaceContent(database: db) + let overlays = options["overlays"] as? [String: String] ?? [:] + let includes = WorkspaceGlob.patterns(settings["include"] as? String) + let excludes = WorkspaceGlob.patterns(settings["exclude"] as? String) + var lastProgress = -1 + job.emit("status", ["state": "searching", "message": "Searching files", "progress": 0], false) + for (offset, file) in files.enumerated() { + try job.check() + let progress = offset * 100 / max(1, files.count) + if progress != lastProgress { job.emit("progress", ["data": progress], false); lastProgress = progress } + let entry = WorkspaceEntry(file) + guard entry.url.hasPrefix("file:"), !WorkspaceContent.isBinary(entry) else { continue } + if !entry.path.isEmpty && (WorkspaceGlob.matches(entry.path, patterns: excludes) || !WorkspaceGlob.matches(entry.path, patterns: includes.isEmpty ? ["**"] : includes)) { continue } + let text: String + do { + guard let value = try content.get(entry, overlays: overlays, encoding: options["defaultEncoding"] as? String ?? "UTF-8", useIndex: options["useIndex"] as? Bool == true, large: !includes.isEmpty && WorkspaceGlob.matches(entry.path, patterns: includes), job: job) else { continue } + text = value + } catch { try job.check(); continue } + let matches = WorkspaceMatches(text: text, regex: regex, job: job) + if replacing { + let text = try matches.replace(replacement) + job.emit("replace-result", ["file": file, "text": text], false) + } else { + try matches.search { results, limited in + let data: [String: Any] = ["file": file, "matches": results, "limited": limited] + let batched = options["batchResults"] as? Bool == true + job.emit(batched ? "search-results" : "search-result", ["data": batched ? [data] as Any : data], false) + } + } + } + try job.check() + job.emit("progress", ["data": 100], false) + job.emit(replacing ? "done-replacing" : "done-searching", [:], true) + } + + private func searchFiles(_ options: [String: Any]) throws -> [[String: Any]] { + var seen = Set<String>() + var result = (options["files"] as? [[String: Any]] ?? []).filter { + guard let url = $0["url"] as? String, !url.isEmpty else { return false } + return seen.insert(url).inserted + } + let roots = options["roots"] as? [String] ?? [] + if !roots.isEmpty { + var values: [Any] = [] + let condition = rootsClause(roots, values: &values) + for row in try database.get().rows("SELECT * FROM files WHERE is_directory = 0" + condition, values) { + let entry = WorkspaceEntry(row, database: true) + if seen.insert(entry.url).inserted { result.append(entry.json) } + } + } + return result + } +} diff --git a/platforms/ios/runner/scanner/ScannerService.swift b/platforms/ios/runner/scanner/ScannerService.swift new file mode 100644 index 0000000000..ec1b989191 --- /dev/null +++ b/platforms/ios/runner/scanner/ScannerService.swift @@ -0,0 +1,270 @@ +import UIKit +import AVFoundation + +final class ScannerService: BaseService { + + private var captureSession: AVCaptureSession? + private var previewLayer: AVCaptureVideoPreviewLayer? + private var overlayView: UIView? + private var metadataOutput: AVCaptureMetadataOutput? + + private var scanCallback: Callback? + private var scanOnce = false + private var onShowCallback: Callback? + private var onHideCallback: Callback? + private var overlayColor: UIColor = UIColor.black.withAlphaComponent(0.85) + private var cornerRadius: CGFloat = 16 + + override func exec(action: String, args: [Any], callback: Callback) { + switch action { + case "show": show(args: args, callback: callback) + case "hide": hide(args: args, callback: callback) + case "scan": scan(args: args, callback: callback) + case "update": update(args: args, callback: callback) + case "setTheme": setTheme(args: args, callback: callback) + case "setOnShowListener": onShowCallback = callback; callback.success(nil, keep: true) + case "setOnHideListener": onHideCallback = callback; callback.success(nil, keep: true) + default: callback.error("Unknown action: \(action)") + } + } + + // MARK: - show + + private func show(args: [Any], callback: Callback) { + DispatchQueue.main.async { [weak self] in + guard let self = self, let vc = self.viewController else { return } + + var x: CGFloat = 0 + var y: CGFloat = 0 + var w: CGFloat = vc.view.bounds.width + var h: CGFloat = vc.view.bounds.height + + if let dims = args[safe: 0] as? [String: Any] { + x = CGFloat((dims["x"] as? Double) ?? 0) + y = CGFloat((dims["y"] as? Double) ?? 0) + w = CGFloat((dims["w"] as? Double) ?? Double(w)) + h = CGFloat((dims["h"] as? Double) ?? Double(h)) + } + + let overlay = UIView(frame: CGRect(x: x, y: y, width: w, height: h)) + overlay.backgroundColor = self.overlayColor + overlay.layer.cornerRadius = self.cornerRadius + overlay.clipsToBounds = true + self.overlayView = overlay + vc.view.addSubview(overlay) + + self.startCamera(in: overlay) { success, reason in + if success { + callback.success() + self.onShowCallback?.success(nil, keep: true) + } else { + overlay.removeFromSuperview() + self.overlayView = nil + callback.error(reason ?? "Failed to start camera") + } + } + } + } + + // MARK: - update + + private func update(args: [Any], callback: Callback){ + DispatchQueue.main.async { [weak self] in + guard let self = self, let overlay = self.overlayView else { + callback.error("No active overlay") + return + } + + var x: CGFloat = overlay.frame.origin.x + var y: CGFloat = overlay.frame.origin.y + var w: CGFloat = overlay.frame.width + var h: CGFloat = overlay.frame.height + + if let dims = args[safe: 0] as? [String: Any] { + x = CGFloat((dims["x"] as? Double) ?? Double(x)) + y = CGFloat((dims["y"] as? Double) ?? Double(y)) + w = CGFloat((dims["w"] as? Double) ?? Double(w)) + h = CGFloat((dims["h"] as? Double) ?? Double(h)) + } + + overlay.frame = CGRect(x: x, y: y, width: w, height: h) + self.previewLayer?.frame = overlay.bounds + callback.success() + } + } + + // MARK: - hide + + private func hide(args: [Any], callback: Callback) { + DispatchQueue.main.async { [weak self] in + self?.stopCamera() + callback.success() + self?.onHideCallback?.success(nil, keep: true) + } + } + + // MARK: - scan + + private func scan(args: [Any], callback: Callback) { + scanOnce = (args[safe: 0] as? Bool) == true || (args[safe: 0] as? Int) == 1 + scanCallback = callback + // Match Android: keep the callback pending until a scan result is emitted. + } + + // MARK: - setTheme + + private func setTheme(args: [Any], callback: Callback) { + let theme: [String: Any]? + if let dict = args[safe: 0] as? [String: Any] { + theme = dict + } else if let themeStr = args[safe: 0] as? String, + let data = themeStr.data(using: .utf8) { + theme = try? JSONSerialization.jsonObject(with: data) as? [String: Any] + } else { + theme = nil + } + guard let theme else { + callback.error("Invalid theme JSON"); return + } + if let bg = theme["popupBackground"] as? String, let color = UIColor(hexString: bg) { + overlayColor = color + DispatchQueue.main.async { [weak self] in + self?.overlayView?.backgroundColor = color + } + } + if let radius = (theme["cornerRadius"] as? String).flatMap({ Double($0) }) { + cornerRadius = CGFloat(radius) + DispatchQueue.main.async { [weak self] in + self?.overlayView?.layer.cornerRadius = CGFloat(radius) + } + } + callback.success() + } + + // MARK: - Camera setup + + private func startCamera(in container: UIView, completion: @escaping (Bool, String?) -> Void) { + let status = AVCaptureDevice.authorizationStatus(for: .video) + switch status { + case .authorized: + startCameraSession(in: container, completion: completion) + case .notDetermined: + AVCaptureDevice.requestAccess(for: .video) { granted in + DispatchQueue.main.async { + if granted { + self.startCameraSession(in: container, completion: completion) + } else { + completion(false, "Camera permission denied") + } + } + } + case .denied, .restricted: + completion(false, "Camera permission denied — enable it in Settings") + @unknown default: + completion(false, "Camera permission unknown status") + } + } + + private func startCameraSession(in container: UIView, completion: @escaping (Bool, String?) -> Void) { + guard let device = AVCaptureDevice.default(for: .video) else { + completion(false, "No camera device available"); return + } + guard let input = try? AVCaptureDeviceInput(device: device) else { + completion(false, "Failed to create camera input"); return + } + + let session = AVCaptureSession() + session.beginConfiguration() + + guard session.canAddInput(input) else { completion(false, "Cannot add camera input to session"); return } + session.addInput(input) + + let output = AVCaptureMetadataOutput() + guard session.canAddOutput(output) else { completion(false, "Cannot add metadata output to session"); return } + session.addOutput(output) + + // QR codes only + output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) + output.metadataObjectTypes = [.qr] + session.commitConfiguration() + + let preview = AVCaptureVideoPreviewLayer(session: session) + preview.videoGravity = .resizeAspectFill + preview.frame = container.bounds + + // Non-deprecated rotation — requires iOS 17+ + if let connection = preview.connection, connection.isVideoRotationAngleSupported(90) { + connection.videoRotationAngle = currentVideoRotationAngle() + } + + container.layer.insertSublayer(preview, at: 0) + + self.captureSession = session + self.previewLayer = preview + self.metadataOutput = output + + DispatchQueue.global(qos: .userInitiated).async { + session.startRunning() + DispatchQueue.main.async { + if session.isRunning { + completion(true, nil) + } else { + completion(false, "Session failed to start running") + } + } + } + } + + private func stopCamera() { + captureSession?.stopRunning() + captureSession = nil + previewLayer?.removeFromSuperlayer() + previewLayer = nil + metadataOutput = nil + overlayView?.removeFromSuperview() + overlayView = nil + scanOnce = false + scanCallback = nil + } + + // MARK: - Rotation + + private func currentVideoRotationAngle() -> CGFloat { + let scene = UIApplication.shared.connectedScenes + .compactMap { $0 as? UIWindowScene }.first + switch scene?.interfaceOrientation { + case .landscapeRight: return 0 + case .landscapeLeft: return 180 + case .portraitUpsideDown: return 270 + default: return 90 // .portrait + } + } +} + +// MARK: - AVCaptureMetadataOutputObjectsDelegate + +extension ScannerService: AVCaptureMetadataOutputObjectsDelegate { + func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { + guard let scanCallback = scanCallback, !metadataObjects.isEmpty else { return } + + let results: [[String: Any]] = metadataObjects.compactMap { obj in + guard let readable = obj as? AVMetadataMachineReadableCodeObject else { return nil } + return [ + "rawValue": readable.stringValue ?? "", + "displayValue": readable.stringValue ?? "", + "format": "256", // FORMAT_QR_CODE numeric value + "valueType": "0", + ] + } + + guard !results.isEmpty else { return } + + if scanOnce { + self.scanCallback = nil + scanCallback.success(results, keep: false) + DispatchQueue.main.async { self.stopCamera() } + } else { + scanCallback.success(results, keep: true) + } + } +} diff --git a/platforms/ios/runnerTests/AdsBannerLifecycleTests.swift b/platforms/ios/runnerTests/AdsBannerLifecycleTests.swift new file mode 100644 index 0000000000..7dadebb924 --- /dev/null +++ b/platforms/ios/runnerTests/AdsBannerLifecycleTests.swift @@ -0,0 +1,80 @@ +import GoogleMobileAds +import XCTest +@testable import runner + +extension AdsBridgeTests { + func testBannerReservesSpaceOnlyAfterLoadAndClearsItOnFailure() async throws { + let (controller, plugin) = try await host() + controller.view.layoutIfNeeded() + let initial = controller.webView.frame.height + let ad = try banner(plugin, id: "pending-banner", position: "bottom", loaded: false) + let view = try XCTUnwrap(ad.bannerView) + defer { plugin.ads.removeValue(forKey: ad.id)?.destroy() } + + ad.show(context(plugin, id: ad.id)) + XCTAssertFalse(ad.isLoaded()) + XCTAssertNil(view.superview) + XCTAssertEqual(controller.webView.frame.height, initial, accuracy: 1) + + ad.bannerViewDidReceiveAd(view) + XCTAssertTrue(ad.isLoaded()) + XCTAssertNotNil(view.superview) + XCTAssertEqual(controller.webView.frame.height, initial - 50, accuracy: 1) + + ad.bannerView(view, didFailToReceiveAdWithError: NSError(domain: "AdMob", code: 1)) + XCTAssertFalse(ad.isLoaded()) + XCTAssertNil(view.superview) + XCTAssertEqual(controller.webView.frame.height, initial, accuracy: 1) + + ad.bannerViewDidReceiveAd(view) + XCTAssertFalse(ad.isLoaded()) + XCTAssertNil(view.superview) + XCTAssertEqual(controller.webView.frame.height, initial, accuracy: 1) + + ad.load(context(plugin, id: ad.id)) + ad.show(context(plugin, id: ad.id)) + XCTAssertEqual(controller.webView.frame.height, initial, accuracy: 1) + ad.bannerViewDidReceiveAd(view) + XCTAssertEqual(controller.webView.frame.height, initial - 50, accuracy: 1) + } + + func testHidingPendingBannerPreventsLateLoadFromRestoringSpace() async throws { + let (controller, plugin) = try await host() + controller.view.layoutIfNeeded() + let initial = controller.webView.frame.height + let ad = try banner(plugin, id: "hidden-banner", position: "bottom", loaded: false) + let view = try XCTUnwrap(ad.bannerView) + defer { plugin.ads.removeValue(forKey: ad.id)?.destroy() } + + ad.show(context(plugin, id: ad.id)) + ad.hide(context(plugin, id: ad.id)) + ad.bannerViewDidReceiveAd(view) + plugin.banners.layout() + XCTAssertTrue(ad.isLoaded()) + XCTAssertFalse(ad.visible) + XCTAssertNil(view.superview) + XCTAssertEqual(controller.webView.frame.height, initial, accuracy: 1) + + ad.show(context(plugin, id: ad.id)) + XCTAssertEqual(controller.webView.frame.height, initial - 50, accuracy: 1) + ad.hide(context(plugin, id: ad.id)) + XCTAssertEqual(controller.webView.frame.height, initial, accuracy: 1) + } + + func testDestroyedBannerIgnoresLateLoadAndFailureCallbacks() async throws { + let (controller, plugin) = try await host() + controller.view.layoutIfNeeded() + let initial = controller.webView.frame.height + let ad = try banner(plugin, id: "destroyed-banner", position: "bottom", loaded: false) + let view = try XCTUnwrap(ad.bannerView) + ad.show(context(plugin, id: ad.id)) + plugin.ads.removeValue(forKey: ad.id)?.destroy() + + ad.bannerViewDidReceiveAd(view) + ad.bannerView(view, didFailToReceiveAdWithError: NSError(domain: "AdMob", code: 1)) + plugin.banners.layout() + XCTAssertFalse(ad.isLoaded()) + XCTAssertNil(view.superview) + XCTAssertEqual(controller.webView.frame.height, initial, accuracy: 1) + } +} diff --git a/platforms/ios/runnerTests/AdsBridgeTests.swift b/platforms/ios/runnerTests/AdsBridgeTests.swift new file mode 100644 index 0000000000..10bc21c157 --- /dev/null +++ b/platforms/ios/runnerTests/AdsBridgeTests.swift @@ -0,0 +1,212 @@ +import GoogleMobileAds +import UserMessagingPlatform +import XCTest +import WebKit +@testable import runner + +@MainActor +final class AdsBridgeTests: BridgeTestCase { + func testFormatsAndConsentGateThroughJavaScriptBridge() async throws { + let webView = try await appWebView() + ConsentInformation.shared.reset() + let result = try await webView.callAsyncJavaScript(""" + const call=(action,args=[])=>new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'AdMob',action,args)); + const state=await call('privacyGetState'); + if(state.canRequestAds||state.consentStatus!=='unknown')throw Error('Consent reset did not take effect'); + for(const cls of ['AppOpenAd','BannerAd','InterstitialAd','NativeAd','RewardedAd','RewardedInterstitialAd']) { + const id='ios-test-'+cls; + await call('adCreate',[{id,cls,adUnitId:'ca-app-pub-3940256099942544/4411468910'}]); + if(await call('adIsLoaded',[{id}]))throw Error(cls+' reports loaded before load'); + try {await call('adLoad',[{id}]);throw Error('Consent bypass');} + catch(error) {if(!String(error).includes('consent'))throw error;} + if(cls==='NativeAd'||cls==='BannerAd')await call('adHide',[{id}]); + await call('adDestroy',[{id}]);await call('adDestroy',[{id}]); + try {await call('adIsLoaded',[{id}]);throw Error('Destroyed ad still exists');} + catch(error) {if(!String(error).includes('not found'))throw error;} + } + try {await admob.start();throw Error('Started before consent');} + catch(error) {if(!String(error).includes('consent'))throw error;} + return true; + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + func testDestroyAndReplacementInvalidatePendingLoadsAndEvents() async throws { + let (controller, plugin) = try await host() + let webView = controller.webView! + _ = try await webView.evaluateJavaScript("window.iosAdEvents=[];window.iosAdListener=e=>iosAdEvents.push(e.adId);document.addEventListener('admob.ad.load',iosAdListener)") + defer { + plugin.ads.removeValue(forKey: "lifecycle")?.destroy() + webView.evaluateJavaScript("document.removeEventListener('admob.ad.load',iosAdListener);delete window.iosAdEvents;delete window.iosAdListener") + } + let original = try XCTUnwrap(AMBAdBase(context(plugin, id: "lifecycle"))) + plugin.ads[original.id] = original + let pending = original.beginLoad(context(plugin, id: original.id)) + original.destroy() + let replacement = try XCTUnwrap(AMBAdBase(context(plugin, id: original.id))) + plugin.ads[replacement.id] = replacement + original.finishLoad(pending) + XCTAssertFalse(original.acceptsLoad(pending)) + XCTAssertTrue(plugin.ads[original.id] === replacement) + let stale = replacement.beginLoad(context(plugin, id: replacement.id)) + let current = replacement.beginLoad(context(plugin, id: replacement.id)) + XCTAssertFalse(replacement.acceptsLoad(stale)) + replacement.finishLoad(stale) + replacement.finishLoad(current) + try await Task.sleep(for: .milliseconds(100)) + let events = try await webView.evaluateJavaScript("iosAdEvents") as? [String] + XCTAssertEqual(events, ["lifecycle"]) + let beforeReload = context(plugin, id: "reload") + plugin.reset() + try await Task.sleep(for: .milliseconds(100)) + XCTAssertFalse(beforeReload.isCurrent) + XCTAssertTrue(replacement.destroyed) + XCTAssertTrue(plugin.ads.isEmpty) + _ = try await webView.evaluateJavaScript("Bridge.exec(e=>{const d=e.data;if(d?.adId)d.ad=window.admobAds?.[d.adId];Bridge.fireDocumentEvent(e.type,d)},console.error,'AdMob','ready',[])") + } + + func testAdRequestsUseThePresentingWindowScene() async throws { + let (controller, plugin) = try await host() + let scene = try XCTUnwrap(controller.view.window?.windowScene) + let webView = controller.webView! + let classes = ["AppOpenAd", "BannerAd", "InterstitialAd", "NativeAd", "RewardedAd", "RewardedInterstitialAd"] + defer { for name in classes { plugin.ads.removeValue(forKey: "scene-" + name)?.destroy() } } + _ = try await webView.callAsyncJavaScript(""" + for(const cls of classes) { + await new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'AdMob','adCreate',[{ + id:'scene-'+cls,cls,adUnitId:'ca-app-pub-3940256099942544/4411468910' + }])); + } + """, arguments: ["classes": classes], in: nil, contentWorld: .page) + for name in classes { + let ad = try XCTUnwrap(plugin.ads["scene-" + name]) + XCTAssertTrue(ad.adRequest.scene === scene, "\(name) must request an ad sized for the presenting window") + } + } + + func testBannersReserveSpaceStackHideAndRestoreEditorAfterDestroy() async throws { + let (controller, plugin) = try await host() + controller.view.layoutIfNeeded() + let initial = controller.webView.frame.height + let top = try banner(plugin, id: "top", position: "top") + let bottom = try banner(plugin, id: "bottom", position: "bottom") + defer { + for ad in [top, bottom] { plugin.ads.removeValue(forKey: ad.id)?.destroy() } + } + top.show(context(plugin, id: top.id)) + bottom.show(context(plugin, id: bottom.id)) + XCTAssertEqual(controller.webView.frame.height, initial - 100, accuracy: 1) + let topView = try XCTUnwrap(top.bannerView) + let bottomView = try XCTUnwrap(bottom.bannerView) + XCTAssertLessThan(topView.frame.minY, bottomView.frame.minY) + top.show(context(plugin, id: top.id)) + XCTAssertEqual(controller.webView.frame.height, initial - 100, accuracy: 1) + top.hide(context(plugin, id: top.id)) + XCTAssertEqual(controller.webView.frame.height, initial - 50, accuracy: 1) + bottom.destroy() + XCTAssertNil(bottomView.superview) + XCTAssertEqual(controller.webView.frame.height, initial, accuracy: 1) + XCTAssertNil(bottomView.delegate) + } + + func testNativeTemplateLoadsAndFullscreenAdsCannotCompete() async throws { + let (controller, plugin) = try await host() + XCTAssertNotNil(AMNAdViewProvider().createView(NativeAd())) + let first = try XCTUnwrap(AMBFullScreen(context(plugin, id: "fullscreen-1"))) + let second = try XCTUnwrap(AMBFullScreen(context(plugin, id: "fullscreen-2"))) + plugin.ads[first.id] = first + plugin.ads[second.id] = second + defer { for ad in [first, second] { plugin.ads.removeValue(forKey: ad.id)?.destroy() } } + XCTAssertTrue(first.preparePresentation(context(plugin, id: first.id)) === controller) + XCTAssertNil(second.preparePresentation(context(plugin, id: second.id))) + first.destroy() + XCTAssertTrue(second.preparePresentation(context(plugin, id: second.id)) === controller) + } + + func testPresentationRecoveryNeverDismissesAVisibleController() async throws { + let (controller, plugin) = try await host() + let ad = try XCTUnwrap(AMBFullScreen(context(plugin, id: "recovery"))) + plugin.ads[ad.id] = ad + defer { plugin.ads.removeValue(forKey: ad.id)?.destroy() } + XCTAssertNotNil(ad.preparePresentation(context(plugin, id: ad.id))) + let visible = UIViewController() + await withCheckedContinuation { continuation in + controller.present(visible, animated: false) { continuation.resume() } + } + XCTAssertFalse(ad.recoverPresentation()) + XCTAssertFalse(plugin.recoverPresentation("already-removed")) + XCTAssertTrue(ad.isPresenting) + XCTAssertTrue(controller.presentedViewController === visible) + await withCheckedContinuation { continuation in + visible.dismiss(animated: false) { continuation.resume() } + } + XCTAssertTrue(ad.recoverPresentation()) + XCTAssertFalse(ad.isPresenting) + XCTAssertNil(plugin.presentedAd) + // Recovery also handles the case where only the JS event was lost. + XCTAssertTrue(ad.recoverPresentation()) + ad.destroy() + XCTAssertFalse(ad.recoverPresentation()) + plugin.ads.removeValue(forKey: ad.id) + XCTAssertTrue(plugin.recoverPresentation(ad.id)) + } + + func testPaidImpressionPayloadPreservesFormatsAndCurrencyMicros() async throws { + let (controller, plugin) = try await host() + let webView = controller.webView! + _ = try await webView.evaluateJavaScript("window.iosPaidEvents=[];window.iosPaidListener=e=>iosPaidEvents.push({adId:e.adId,adFormat:e.adFormat,valueMicros:e.valueMicros,currencyCode:e.currencyCode,precision:e.precision});document.addEventListener('admob.ad.paid',iosPaidListener)") + defer { webView.evaluateJavaScript("document.removeEventListener('admob.ad.paid',iosPaidListener);delete window.iosPaidEvents;delete window.iosPaidListener") } + let formats = ["AppOpenAd": "appOpen", "BannerAd": "banner", "InterstitialAd": "interstitial", + "NativeAd": "native", "RewardedAd": "rewarded", "RewardedInterstitialAd": "rewardedInterstitial"] + for (name, _) in formats { + let ad = try XCTUnwrap(AMBAdBase(context(plugin, id: name, options: ["cls": name]))) + plugin.ads[ad.id] = ad + ad.emitPaid(FixtureAdValue(), response: nil) + plugin.ads.removeValue(forKey: ad.id)?.destroy() + } + try await Task.sleep(for: .milliseconds(100)) + let payload = try await webView.evaluateJavaScript("iosPaidEvents") + let values = try XCTUnwrap(payload as? [[String: Any]]) + XCTAssertEqual(values.count, formats.count) + for value in values { + XCTAssertEqual(value["adFormat"] as? String, formats[value["adId"] as? String ?? ""]) + XCTAssertEqual(value["valueMicros"] as? Int, 123456) + XCTAssertEqual(value["currencyCode"] as? String, "USD") + XCTAssertEqual(value["precision"] as? Int, 3) + } + } + + func host() async throws -> (WebViewController, AMBPlugin) { + let webView = try await appWebView() + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let controller = try XCTUnwrap(responder as? WebViewController) + return (controller, try XCTUnwrap(controller.bridge.adsService)) + } + + func context(_ plugin: AMBPlugin, id: String, options: [String: Any] = [:]) -> AMBContext { + var args: [String: Any] = ["id": id, "adUnitId": "ca-app-pub-3940256099942544/2934735716", "cls": "BannerAd"] + args.merge(options) { _, new in new } + return AMBContext(plugin, [args], Callback(id: 0, webView: nil)) + } + + func banner(_ plugin: AMBPlugin, id: String, position: String, loaded: Bool = true) throws -> AMBBanner { + let ctx = context(plugin, id: id, options: ["position": position, "size": 0]) + let ad = try XCTUnwrap(AMBBanner(ctx)) + ad.makeBanner = { OfflineBanner(adSize: $0) } + plugin.ads[id] = ad + ad.load(ctx) + if loaded { ad.bannerViewDidReceiveAd(try XCTUnwrap(ad.bannerView)) } + return ad + } +} + +private final class FixtureAdValue: AdValue { + override var value: NSDecimalNumber { NSDecimalNumber(string: "0.123456") } + override var currencyCode: String { "USD" } + override var precision: AdValuePrecision { .precise } +} + +private final class OfflineBanner: BannerView { + override func load(_ request: Request?) {} +} diff --git a/platforms/ios/runnerTests/AdsEditionTests.swift b/platforms/ios/runnerTests/AdsEditionTests.swift new file mode 100644 index 0000000000..490c25082e --- /dev/null +++ b/platforms/ios/runnerTests/AdsEditionTests.swift @@ -0,0 +1,19 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class AdsEditionTests: BridgeTestCase { + func testIOSIsFreeWithAdvertisingAndCanonicalBundleId() async throws { + XCTAssertEqual(Bundle.main.bundleIdentifier, "app.acode") + let webView = try await appWebView() + let included = try await webView.evaluateJavaScript("typeof window.admob !== 'undefined'") as? Bool + let flavor = try await webView.evaluateJavaScript("BuildInfo.flavor") as? String + XCTAssertEqual(included, true) + XCTAssertEqual(flavor, "free") + XCTAssertNotNil(NSClassFromString("GADMobileAds")) + XCTAssertNotNil(NSClassFromString("UMPConsentInformation")) + XCTAssertTrue((Bundle.main.object(forInfoDictionaryKey: "GADApplicationIdentifier") as? String)?.hasPrefix("ca-app-pub-") == true) + XCTAssertNotNil(Bundle.main.url(forResource: "AMNAdView", withExtension: "nib")) + } +} diff --git a/platforms/ios/runnerTests/AdsRequestTests.swift b/platforms/ios/runnerTests/AdsRequestTests.swift new file mode 100644 index 0000000000..df6291ef83 --- /dev/null +++ b/platforms/ios/runnerTests/AdsRequestTests.swift @@ -0,0 +1,93 @@ +import GoogleMobileAds +import UserMessagingPlatform +import WebKit +import XCTest +@testable import runner + +@MainActor +final class AdsRequestTests: XCTestCase { + func testAgeTreatmentPreservesRestrictionsAcrossPartialConfigurationUpdates() { + let bridge = Bridge() + let plugin = AMBPlugin(bridge: bridge) + let configuration = MobileAds.shared.requestConfiguration + let original = configuration.ageRestrictedTreatment + defer { configuration.ageRestrictedTreatment = original } + configure(["tagForChildDirectedTreatment": false, "tagForUnderAgeOfConsent": false]) + XCTAssertEqual(configuration.ageRestrictedTreatment, .unspecified) + configure(["tagForUnderAgeOfConsent": true]) + XCTAssertEqual(configuration.ageRestrictedTreatment, .child) + configure(["tagForChildDirectedTreatment": false]) + XCTAssertEqual(configuration.ageRestrictedTreatment, .child) + configure(["tagForChildDirectedTreatment": true, "tagForUnderAgeOfConsent": false]) + XCTAssertEqual(configuration.ageRestrictedTreatment, .child) + configure([:]) + XCTAssertEqual(configuration.ageRestrictedTreatment, .child) + configure(["tagForChildDirectedTreatment": false]) + XCTAssertEqual(configuration.ageRestrictedTreatment, .unspecified) + + func configure(_ options: [String: Any]) { + AMBContext(plugin, [options], Callback(id: 0, webView: nil)).configure() + } + } + + func testLoadAndShowRequireStartupEvenWithConsent() async throws { + let bridge = Bridge() + let plugin = AMBPlugin(bridge: bridge) + let information = RequestConsentFixture() + plugin.privacy = AMBPrivacy(plugin: plugin, information: information) + let receiver = RequestReplyReceiver(loaded: expectation(description: "Callback page loaded")) + let configuration = WKWebViewConfiguration() + configuration.userContentController.add(receiver, name: "reply") + let replies = WKWebView(frame: .zero, configuration: configuration) + replies.navigationDelegate = receiver + defer { configuration.userContentController.removeScriptMessageHandler(forName: "reply") } + replies.loadHTMLString("<script>window.iOS={callback:r=>webkit.messageHandlers.reply.postMessage(r)};</script>", baseURL: nil) + await fulfillment(of: [receiver.loaded], timeout: 5) + let ctx = AMBContext(plugin, [["id": "gate", "adUnitId": "fixture"]], Callback(id: 0, webView: nil)) + let ad = try XCTUnwrap(RequestAdFixture(ctx)) + plugin.ads[ad.id] = ad + for allowed in [false, true] { + information.allowed = allowed + for action in ["adLoad", "adShow"] { + let response = expectation(description: "\(action) rejected before startup") + receiver.onReply = { payload in + XCTAssertEqual(payload["status"] as? Int, 9) + XCTAssertEqual(payload["error"] as? String, allowed + ? "Initialize ads before requesting ads" : "Gather ad consent before requesting ads") + response.fulfill() + } + plugin.exec(action: action, args: [["id": ad.id]], callback: Callback(id: 1, webView: replies)) + await fulfillment(of: [response], timeout: 5) + } + } + XCTAssertEqual(ad.requests, 0) + XCTAssertFalse(ad.recoverPresentation()) + } +} + +private final class RequestConsentFixture: ConsentInformation { + var allowed = false + override var canRequestAds: Bool { allowed } +} + +private final class RequestAdFixture: AMBFullScreen { + var requests = 0 + override func isLoaded() -> Bool { true } + override func load(_ ctx: AMBContext) { requests += 1; ctx.resolve() } + override func show(_ ctx: AMBContext) { requests += 1; ctx.resolve(true) } +} + +@MainActor +private final class RequestReplyReceiver: NSObject, WKNavigationDelegate, WKScriptMessageHandler { + let loaded: XCTestExpectation + var onReply: ([String: Any]) -> Void = { _ in } + + init(loaded: XCTestExpectation) { self.loaded = loaded } + + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { loaded.fulfill() } + + func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) { + guard let payload = message.body as? [String: Any] else { XCTFail("Invalid callback payload"); return } + onReply(payload) + } +} diff --git a/platforms/ios/runnerTests/AdsStartupTests.swift b/platforms/ios/runnerTests/AdsStartupTests.swift new file mode 100644 index 0000000000..5b248a67cf --- /dev/null +++ b/platforms/ios/runnerTests/AdsStartupTests.swift @@ -0,0 +1,90 @@ +import StoreKit +import XCTest +@testable import runner + +@MainActor +final class AdsStartupTests: XCTestCase { + func testEnvironmentCacheCoalescesRequestsAndRetainsVerifiedResult() async { + let cache = AMBAdEnvironmentCache() + var complete: CheckedContinuation<AppStore.Environment?, Never>? + let started = expectation(description: "StoreKit lookup started") + let first = Task { @MainActor in + await cache.current { + await withCheckedContinuation { complete = $0; started.fulfill() } + } + } + await fulfillment(of: [started], timeout: 1) + let joined = expectation(description: "Second lookup joined") + let second = Task { @MainActor in + joined.fulfill() + return await cache.current { XCTFail("Concurrent lookup must be coalesced"); return .production } + } + await fulfillment(of: [joined], timeout: 1) + complete?.resume(returning: .sandbox) + let firstResult = await first.value + let secondResult = await second.value + XCTAssertEqual(firstResult.verifiedEnvironment, .sandbox) + XCTAssertEqual(secondResult.verifiedEnvironment, .sandbox) + let cached = await cache.current { XCTFail("Verified result must be reused"); return nil } + XCTAssertEqual(cached.verifiedEnvironment, .sandbox) + } + + func testEnvironmentCacheRetriesFailuresAndUnverifiedResultsAfterCooldown() async { + var instant = ContinuousClock.now + let cache = AMBAdEnvironmentCache(now: { instant }) + let failed = await cache.current { throw URLError(.notConnectedToInternet) } + XCTAssertNil(failed.verifiedEnvironment) + let cooled = await cache.current { XCTFail("Retry must be throttled"); return .sandbox } + XCTAssertNil(cooled.verifiedEnvironment) + instant = instant.advanced(by: .seconds(30)) + let unverified = await cache.current { nil } + XCTAssertNil(unverified.verifiedEnvironment) + instant = instant.advanced(by: .seconds(30)) + let recovered = await cache.current { .sandbox } + XCTAssertEqual(recovered.verifiedEnvironment, .sandbox) + } + + func testOnlyVerifiedTestingEnvironmentsReplaceConfiguredUnits() { + let formats = ["banner", "interstitial", "rewarded", "rewardedInterstitial", "appOpen", "native"] + for environment: AppStore.Environment? in [nil, .production, .sandbox, .xcode] { + let policy = AMBAdEnvironment(verifiedEnvironment: environment) + for format in formats { + let unit = policy.unitID(for: format, configured: "production-unit") + if environment == .sandbox || environment == .xcode { + XCTAssertTrue(unit.hasPrefix("ca-app-pub-3940256099942544/"), format) + } else { XCTAssertEqual(unit, "production-unit", format) } + } + XCTAssertEqual(policy.unitID(for: "webView", configured: "original"), "original") + } + XCTAssertEqual(AMBAdEnvironment(verifiedEnvironment: .sandbox).unitID(for: "rewarded", configured: "production"), + "ca-app-pub-3940256099942544/1712485313") + } + + func testEnvironmentLookupPreservesSuccessAndFallsBackOnFailure() async { + let verified = await AMBAdEnvironment.resolve { .sandbox } + XCTAssertEqual(verified.verifiedEnvironment, .sandbox) + let failed = await AMBAdEnvironment.resolve { throw URLError(.notConnectedToInternet) } + XCTAssertNil(failed.verifiedEnvironment) + } + + func testEnvironmentDeadlineDoesNotWaitForCancellationAndIgnoresLateResult() async { + var completeLookup: CheckedContinuation<AppStore.Environment?, Never>? + let started = expectation(description: "Lookup started") + let completed = expectation(description: "Deadline releases startup") + let request = Task { @MainActor in + let result = await AMBAdEnvironment.resolve(timeout: .milliseconds(25)) { + await withCheckedContinuation { + completeLookup = $0 + started.fulfill() + } + } + XCTAssertNil(result.verifiedEnvironment) + completed.fulfill() + return result + } + await fulfillment(of: [started, completed], timeout: 2) + completeLookup?.resume(returning: .sandbox) + let result = await request.value + XCTAssertEqual(result.unitID(for: "rewarded", configured: "production"), "production") + } +} diff --git a/platforms/ios/runnerTests/AlpineInteractionTests.swift b/platforms/ios/runnerTests/AlpineInteractionTests.swift new file mode 100644 index 0000000000..17a5f5fca0 --- /dev/null +++ b/platforms/ios/runnerTests/AlpineInteractionTests.swift @@ -0,0 +1,144 @@ +import XCTest +import WebKit + +@MainActor +final class AlpineInteractionTests: BridgeTestCase { + func testOrphanedTerminalProcessExitsAfterSessionLeader() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(#""" + if (!await Terminal.isInstalled() && !await Terminal.install()) throw new Error(Terminal.lastInstallError); + const manager = acode.require('terminal'); + const terminal = await manager.createServer({name:'Alpine orphan cleanup'}); + const parent = Number(terminal.component.pid); + let directory; + let child; + const content = () => { + const buffer = terminal.component.terminal.buffer.active; + return Array.from({length:buffer.length}, (_, i) => buffer.getLine(i)?.translateToString()).join('\n'); + }; + const waitFor = async check => { + for (let i = 0; i < 100; i++) { + if (await check()) return; + await new Promise(resolve => setTimeout(resolve, 50)); + } + throw new Error('Orphan cleanup timed out: '+content()); + }; + const childExited = async () => !(await Executor.listAllProcesses()).some(process => process.pid === child); + try { + directory = await Executor.execute('mktemp -d /tmp/acode-orphan-test.XXXXXX', true); + await waitFor(() => content().includes('root@localhost')); + terminal.component.terminal.input(`sh -c 'trap "" HUP; echo $$ > "$1/pid"; echo ORPHAN:$$; while [ ! -e "$1/release" ]; do sleep 0.1; done' sh "${directory}" & disown\r`); + await waitFor(() => /ORPHAN:(\d+)/.test(content())); + child = Number(content().match(/ORPHAN:(\d+)/)[1]); + terminal.component.terminal.input('exit\r'); + await waitFor(async () => { + const processes = await Executor.listAllProcesses(); + return !processes.some(process => process.pid === parent) && processes.some(process => process.pid === child); + }); + await Executor.execute(`touch "${directory}/release"`, true); + await waitFor(childExited); + return await Executor.execute('printf ORPHAN_CLEANUP_PASS', true); + } finally { + try { + if (directory) { + await Executor.execute(`touch "${directory}/release"`, true); + child ||= Number(await Executor.execute(`cat "${directory}/pid" 2>/dev/null || true`, true)); + if (child) { + try { await waitFor(childExited); } + catch { + await Executor.killProcess(child).catch(() => {}); + await waitFor(childExited); + } + } + } + } finally { + try { await manager.close(terminal.id); } + finally { + if (directory) await Executor.execute(`rm -rf "${directory}"`, true); + } + } + } + """#, arguments: [:], in: nil, contentWorld: .page) as? String + XCTAssertEqual(result, "ORPHAN_CLEANUP_PASS") + } + + func testExistingTerminalUIAndSessionIsolation() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(#""" + if (!await Terminal.isInstalled() && !await Terminal.install()) throw new Error(Terminal.lastInstallError); + const manager = acode.require('terminal'); + const first = await manager.createServer({name:'Alpine first'}); + const second = await manager.createServer({name:'Alpine second'}); + const content = instance => { + const buffer = instance.component.terminal.buffer.active; + return Array.from({length:buffer.length}, (_, i) => buffer.getLine(i)?.translateToString()).join('\n'); + }; + const wait = async (instance, text) => { + for (let i = 0; i < 100; i++) { + if (content(instance).includes(text)) return; + await new Promise(resolve => setTimeout(resolve, 100)); + } + throw new Error('Missing ' + text + ': ' + content(instance)); + }; + const input = (instance, text) => instance.component.terminal.input(text); + try { + input(first, 'cd /tmp; export ACODE_CHECK=first; printf "ONE:%s:%s\\n" "$PWD" "$ACODE_CHECK"\r'); + input(second, 'cd /etc; export ACODE_CHECK=second; printf "TWO:%s:%s\\n" "$PWD" "$ACODE_CHECK"\r'); + await wait(first, 'ONE:/tmp:first'); + await wait(second, 'TWO:/etc:second'); + const processes = await Executor.listAllProcesses(); + for (const terminal of [first, second]) { + if (!processes.some(process => process.pid === Number(terminal.component.pid))) throw new Error('Terminal missing from process list'); + } + await first.component.resizeTerminal(100, 40, true); + input(first, 'stty size\r'); + await wait(first, '40 100'); + input(first, 'sleep 30\r'); + let sleeping = false; + for (let i = 0; i < 50; i++) { + if ((await Executor.listAllProcesses()).some(process => process.name === 'sleep')) { sleeping = true; break; } + await new Promise(resolve => setTimeout(resolve, 100)); + } + if (!sleeping) throw new Error('Foreground sleep did not start'); + input(first, '\x03'); + input(first, 'printf "SIGNAL:%s\\n" "$?"\r'); + await wait(first, 'SIGNAL:130'); + input(second, 'printf "STILL:%s\\n" "$ACODE_CHECK"\r'); + await wait(second, 'STILL:second'); + input(first, 'read -p "READY:$((1+1))" value; printf "INPUT:%s\\n" "$value"\r'); + await wait(first, 'READY:2'); + input(first, 'hello\r'); + await wait(first, 'INPUT:hello'); + const dropped = second.component.websocket; + dropped.close(); + for (let i = 0; i < 100 && (second.component.websocket === dropped || !second.component.isConnected); i++) { + await new Promise(resolve => setTimeout(resolve, 100)); + } + if (!second.component.isConnected) throw new Error('Terminal did not reconnect'); + await wait(second, 'STILL:second'); + input(second, 'printf "BACK:%s\\n" "$ACODE_CHECK"\r'); + await wait(second, 'BACK:second'); + second.component.options.port = 9; + const lost = second.component.websocket; + lost.close(); + for (let i = 0; i < 100 && !second.component.disconnected; i++) { + await new Promise(resolve => setTimeout(resolve, 100)); + } + if (!second.component.disconnected || second.component.intentionalClose) throw new Error('Tab was not kept after reconnect failures'); + second.component.options.port = 8767; + document.dispatchEvent(new CustomEvent('resume')); + for (let i = 0; i < 100 && (second.component.websocket === lost || !second.component.isConnected); i++) { + await new Promise(resolve => setTimeout(resolve, 100)); + } + input(second, 'printf "AGAIN:%s\\n" "$ACODE_CHECK"\r'); + await wait(second, 'AGAIN:second'); + return {first:content(first), second:content(second)}; + } finally { + await manager.close(first.id); + await manager.close(second.id); + } + """#, arguments: [:], in: nil, contentWorld: .page) as? [String: String] + XCTAssertTrue(result?["first"]?.contains("SIGNAL:130") == true) + XCTAssertTrue(result?["second"]?.contains("AGAIN:second") == true) + } +} diff --git a/platforms/ios/runnerTests/AlpineLspTests.swift b/platforms/ios/runnerTests/AlpineLspTests.swift new file mode 100644 index 0000000000..4eecfb92bf --- /dev/null +++ b/platforms/ios/runnerTests/AlpineLspTests.swift @@ -0,0 +1,58 @@ +import XCTest +import WebKit + +@MainActor +final class AlpineLspTests: BridgeTestCase { + func testExistingJsonLanguageServerOverAlpine() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(#""" + if (!await Terminal.isInstalled() && !await Terminal.install()) throw new Error(Terminal.lastInstallError); + await Executor.execute('command -v vscode-json-language-server >/dev/null || { apk add --no-cache nodejs npm && npm install -g --no-audit --no-fund vscode-langservers-extracted@4.10.0; }', true); + const api = acode.require('lsp'); + const server = api.servers.get('json-stdio'); + const context = {serverId:'ios-json-test', uri:'alpine://localhost/tmp/acode-lsp.json', originalDocumentUri:'alpine://localhost/tmp/acode-lsp.json', rootUri:'alpine://localhost/tmp'}; + const provider = await api.runtimes.select(server, context); + if (provider?.id !== 'builtin-alpine') throw new Error('Alpine provider not selected'); + const paths = provider.resolveUris(server, context); + if (paths.documentUri !== 'file:///tmp/acode-lsp.json') throw new Error('Wrong guest URI'); + const connection = await provider.start(server, context); + const handle = connection.transport; + const messages = []; + handle.transport.subscribe(text => messages.push(JSON.parse(text))); + const send = message => handle.transport.send(JSON.stringify({jsonrpc:'2.0', ...message})); + const response = async id => { + for (let i = 0; i < 150; i++) { + const value = messages.find(message => message.id === id); + if (value) { + if (value.error) throw new Error(JSON.stringify(value.error)); + return value.result; + } + await new Promise(resolve => setTimeout(resolve, 100)); + } + throw new Error('No LSP response for ' + id); + }; + try { + await handle.ready; + send({id:1, method:'initialize', params:{processId:null, rootUri:paths.rootUri, capabilities:{}, initializationOptions:{provideFormatter:true}}}); + const initialized = await response(1); + if (!initialized.capabilities.documentFormattingProvider) throw new Error('Formatting unavailable'); + send({method:'initialized', params:{}}); + send({method:'textDocument/didOpen', params:{textDocument:{uri:paths.documentUri, languageId:'json', version:1, text:'{"hello":1}'}}}); + send({id:2, method:'textDocument/formatting', params:{textDocument:{uri:paths.documentUri}, options:{tabSize:2, insertSpaces:true}}}); + const edits = await response(2); + if (!edits.length) throw new Error('JSON server returned no formatting edits'); + send({id:3, method:'shutdown', params:null}); + await response(3); + send({method:'exit'}); + return {provider:provider.id, edits:edits.length}; + } finally { + await handle.dispose(); + for (const process of await Executor.listProcesses()) { + if (process.command.includes('ios-json-test')) await Executor.stop(process.id); + } + } + """#, arguments: [:], in: nil, contentWorld: .page) as? [String: Any] + XCTAssertEqual(result?["provider"] as? String, "builtin-alpine") + XCTAssertGreaterThan(result?["edits"] as? Int ?? 0, 0) + } +} diff --git a/platforms/ios/runnerTests/AlpinePackageTests.swift b/platforms/ios/runnerTests/AlpinePackageTests.swift new file mode 100644 index 0000000000..518d6a7fce --- /dev/null +++ b/platforms/ios/runnerTests/AlpinePackageTests.swift @@ -0,0 +1,110 @@ +import XCTest +import WebKit + +@MainActor +final class AlpinePackageTests: BridgeTestCase { + func testCompressedArchivePreservesPermissionsAndSymlinks() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(#""" + if (!await Terminal.isInstalled() && !await Terminal.install()) throw new Error(Terminal.lastInstallError); + return await Executor.execute(`set -eu + dir=$(mktemp -d /tmp/acode-archive-test.XXXXXX) + trap 'rm -rf "$dir"' EXIT + mkdir "$dir/source" "$dir/extracted" + printf archive-probe > "$dir/source/tool" + chmod 755 "$dir/source/tool" + ln -s tool "$dir/source/link" + tar -czf "$dir/archive.tar.gz" -C "$dir/source" . + tar -xzf "$dir/archive.tar.gz" -C "$dir/extracted" + test "$(cat "$dir/extracted/link")" = archive-probe + test "$(readlink "$dir/extracted/link")" = tool + test "$(stat -c %a "$dir/extracted/tool")" = 755 + printf invalid > "$dir/invalid.tar.gz" + if tar -xzf "$dir/invalid.tar.gz" -C "$dir/extracted" 2>/dev/null; then exit 1; fi + printf ARCHIVE_PASS`, true); + """#, arguments: [:], in: nil, contentWorld: .page) as? String + XCTAssertEqual(result, "ARCHIVE_PASS") + } + + func testLinuxProcessInspectionAndDirectoryRemoval() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(#""" + if (!await Terminal.isInstalled() && !await Terminal.install()) throw new Error(Terminal.lastInstallError); + await Executor.execute('apk add --no-cache nodejs procps-ng', true); + const code = ` + const assert = require('node:assert/strict'); + const fs = require('node:fs'); + const child = require('node:child_process'); + const stat = fs.readFileSync('/proc/self/stat', 'utf8'); + const start = Number(stat.slice(stat.lastIndexOf(')') + 1).trim().split(/\\s+/)[19]); + assert(start > 0); + const details = child.execFileSync('ps', ['-p', String(process.pid), '-o', 'stat=', '-o', 'lstart='], {encoding:'utf8'}); + assert.match(details, /^[A-Z+<NlSs]+\\s+\\w{3}\\s+\\w{3}\\s+\\d+\\s+\\d{2}:\\d{2}:\\d{2}\\s+\\d{4}/); + for (const root of ['/tmp/', '/public/']) { + const dir = fs.mkdtempSync(root + 'acode-fs-probe-'); + const link = dir + '.link'; + try { + assert.throws(() => fs.unlinkSync(dir), {code:'EISDIR'}); + fs.symlinkSync(dir, link); + fs.unlinkSync(link); + assert(fs.statSync(dir).isDirectory()); + fs.mkdirSync(dir + '/child'); + fs.writeFileSync(dir + '/child/file', 'probe'); + fs.rmSync(dir, {recursive:true}); + assert(!fs.existsSync(dir)); + } finally { + fs.rmSync(link, {force:true}); + fs.rmSync(dir, {recursive:true, force:true}); + } + } + console.log('LINUX_COMPAT_PASS');`; + return await Executor.execute('node -e ' + "'" + code.replaceAll("'", "'\\''") + "'", true); + """#, arguments: [:], in: nil, contentWorld: .page) as? String + XCTAssertEqual(result, "LINUX_COMPAT_PASS") + } + + func testNodeNpmAndLinuxSubprocesses() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(#""" + if (!await Terminal.isInstalled() && !await Terminal.install()) throw new Error(Terminal.lastInstallError); + await Executor.execute('apk add --no-cache nodejs npm', true); + const fs = acode.require('fs'); + const path = 'alpine://localhost/tmp/acode-node-probe.js'; + const code = ` + const assert = require('node:assert/strict'); + const fs = require('node:fs'); + const http = require('node:http'); + const child = require('node:child_process'); + const startup = child.spawnSync(process.execPath, ['-e', 'process.stdout.write(typeof WebAssembly)'], {encoding:'utf8'}); + assert.equal(startup.status, 0); + assert.equal(startup.stdout, 'undefined'); + assert.equal(startup.stderr, ''); + assert.equal(1 + 2, 3); + fs.writeFileSync('/tmp/acode-node-utf8', 'hello π'); + assert.equal(fs.readFileSync('/tmp/acode-node-utf8', 'utf8'), 'hello π'); + assert.equal(child.execFileSync('/bin/sh', ['-c', 'printf subprocess'], {encoding:'utf8'}), 'subprocess'); + const server = http.createServer((req, res) => res.end('loopback')); + server.listen(0, '127.0.0.1', () => { + http.get('http://127.0.0.1:' + server.address().port, res => { + let body = ''; + res.on('data', data => body += data); + res.on('end', () => { + assert.equal(body, 'loopback'); + server.close(() => console.log('NODE_PASS')); + }); + }); + });`; + if (await fs(path).exists()) await fs(path).delete(); + await fs('alpine://localhost/tmp').createFile('acode-node-probe.js', code); + const node = await Executor.execute('node /tmp/acode-node-probe.js', true); + if (node !== 'NODE_PASS') throw new Error('Node check: ' + node); + await Executor.execute('npm install --ignore-scripts --no-audit --no-fund --cache /tmp/acode-npm-cache --prefix /tmp/acode-npm-probe is-number@7.0.0', true); + const npm = await Executor.execute('node -p "require(\'/tmp/acode-npm-probe/node_modules/is-number\')(42)"', true); + if (npm !== 'true') throw new Error('npm package check: ' + npm); + await Executor.execute('rm -rf /tmp/acode-node-probe.js /tmp/acode-node-utf8 /tmp/acode-npm-probe /tmp/acode-npm-cache', true); + return {node, npm}; + """#, arguments: [:], in: nil, contentWorld: .page) as? [String: String] + XCTAssertEqual(result?["node"], "NODE_PASS") + XCTAssertEqual(result?["npm"], "true") + } +} diff --git a/platforms/ios/runnerTests/AlpineSignalTests.swift b/platforms/ios/runnerTests/AlpineSignalTests.swift new file mode 100644 index 0000000000..908fe2db8b --- /dev/null +++ b/platforms/ios/runnerTests/AlpineSignalTests.swift @@ -0,0 +1,26 @@ +import XCTest +import WebKit + +@MainActor +final class AlpineSignalTests: BridgeTestCase { + func testFaultSignalsAndQueuedSignals() async throws { + let fixture = try XCTUnwrap(Bundle(for: Self.self).url(forResource: "fault-signals", withExtension: "elf")) + let payload = try Data(contentsOf: fixture).base64EncodedString() + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(#""" + if (!await Terminal.isInstalled() && !await Terminal.install()) throw new Error(Terminal.lastInstallError); + return await Executor.execute(` + dir=$(mktemp -d /tmp/acode-signal-test.XXXXXX) || exit 1 + trap 'rm -rf "$dir"' EXIT + printf '%s' '${payload}' | base64 -d > "$dir/probe" || exit 1 + chmod 755 "$dir/probe" || exit 1 + for signal in s i; do + for mode in b i h q; do + timeout -s KILL 3 "$dir/probe" "$mode" "$signal" >/dev/null 2>&1 + printf '%s:%s:%s\\n' "$signal" "$mode" "$?" + done + done`, true); + """#, arguments: ["payload": payload], in: nil, contentWorld: .page) as? String + XCTAssertEqual(result, "s:b:139\ns:i:139\ns:h:42\ns:q:42\ni:b:132\ni:i:132\ni:h:42\ni:q:42") + } +} diff --git a/platforms/ios/runnerTests/AlpineSimdTests.swift b/platforms/ios/runnerTests/AlpineSimdTests.swift new file mode 100644 index 0000000000..15be57ffd6 --- /dev/null +++ b/platforms/ios/runnerTests/AlpineSimdTests.swift @@ -0,0 +1,21 @@ +import XCTest +import WebKit + +@MainActor +final class AlpineSimdTests: BridgeTestCase { + func testHalfwordLaneLoadsAndStores() async throws { + let fixture = try XCTUnwrap(Bundle(for: Self.self).url(forResource: "halfword-lanes", withExtension: "elf")) + let payload = try Data(contentsOf: fixture).base64EncodedString() + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(#""" + if (!await Terminal.isInstalled() && !await Terminal.install()) throw new Error(Terminal.lastInstallError); + return await Executor.execute(`set -eu + dir=$(mktemp -d /tmp/acode-simd-test.XXXXXX) + trap 'rm -rf "$dir"' EXIT + printf '%s' '${payload}' | base64 -d > "$dir/probe" + chmod 755 "$dir/probe" + "$dir/probe"`, true); + """#, arguments: ["payload": payload], in: nil, contentWorld: .page) as? String + XCTAssertEqual(result, "SIMD_PASS") + } +} diff --git a/platforms/ios/runnerTests/AlpineTerminalServerTests.swift b/platforms/ios/runnerTests/AlpineTerminalServerTests.swift new file mode 100644 index 0000000000..115c552ef8 --- /dev/null +++ b/platforms/ios/runnerTests/AlpineTerminalServerTests.swift @@ -0,0 +1,124 @@ +import Network +import XCTest +import WebKit + +@MainActor +final class AlpineTerminalServerTests: BridgeTestCase { + func testCongestedWriterStillReceivesSignals() async throws { + let webView = try await editorWebView() + let pid = try await webView.callAsyncJavaScript(Self.prelude + #""" + return (await request('/terminals', {cols:80, rows:24})).data.trim(); + """#, arguments: [:], in: nil, contentWorld: .page) as? String ?? "" + let socket = RawWebSocket() + try await socket.open("/terminals/\(pid)") + // The client stops reading, so `cat` fills the socket and must block in the guest. + try await socket.send("cat /dev/zero\r") + let running = try await webView.callAsyncJavaScript(Self.prelude + #""" + return await waitFor(async () => (await processes()).includes('cat'), 100); + """#, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(running, true) + try await Task.sleep(for: .seconds(2)) + try await socket.send("\u{03}") + let stopped = try await webView.callAsyncJavaScript(Self.prelude + #""" + return await waitFor(async () => !(await processes()).includes('cat'), 50); + """#, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(stopped, true, "Ctrl-C did not reach a writer blocked on a congested client") + socket.close() + _ = try await webView.callAsyncJavaScript(Self.prelude + #""" + await request('/terminals/' + pid + '/terminate', {}); + """#, arguments: ["pid": pid], in: nil, contentWorld: .page) + } + + func testExecuteCommandRunsOnPtyWithResponseDeadline() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(Self.prelude + #""" + const execute = async body => { + try { return JSON.parse((await request('/execute-command', body)).data); } + catch (error) { return {status: error.status, ...JSON.parse(error.error || '{}')}; } + }; + const tty = await execute({command: 'test -t 0 && stty size'}); + const missing = await execute({command: 'true', cwd: '/acode-missing-directory'}); + let started = Date.now(); + const background = await execute({command: 'sleep 60 & echo started'}); + const backgroundSeconds = (Date.now() - started) / 1000; + started = Date.now(); + const timeout = await execute({command: 'sleep 45'}); + const timeoutSeconds = (Date.now() - started) / 1000; + const sleepersKilled = await waitFor(async () => !(await processes()).includes('sleep'), 50); + return {tty: tty.output, missing, background: background.output, backgroundSeconds, + timeout: timeout.error, timeoutSeconds, sleepersKilled}; + """#, arguments: [:], in: nil, contentWorld: .page) as? [String: Any] + XCTAssertTrue((result?["tty"] as? String)?.contains("24 80") == true, "\(String(describing: result))") + XCTAssertEqual((result?["missing"] as? [String: Any])?["status"] as? Int, 400) + XCTAssertTrue((result?["background"] as? String)?.contains("started") == true) + XCTAssertLessThan(result?["backgroundSeconds"] as? Double ?? 99, 10) + XCTAssertEqual(result?["timeout"] as? String, "Command execution timed out") + XCTAssertLessThan(result?["timeoutSeconds"] as? Double ?? 99, 40) + XCTAssertEqual(result?["sleepersKilled"] as? Bool, true) + } + + private static let prelude = #""" + if (!await Terminal.isInstalled() && !await Terminal.install()) throw new Error(Terminal.lastInstallError); + await Terminal.startAxs(); + const request = (path, data) => new Promise((resolve, reject) => Bridge.http.sendRequest( + 'http://127.0.0.1:8767' + path, + {method:'POST', serializer:'json', responseType:'text', data}, + resolve, reject)); + const processes = async () => (await Executor.listAllProcesses()).map(process => process.name); + const waitFor = async (check, attempts) => { + for (let i = 0; i < attempts; i++) { + if (await check()) return true; + await new Promise(resolve => setTimeout(resolve, 100)); + } + return false; + }; + + """# +} + +/// A WebSocket client that only reads the handshake, so tests can stop draining output. +private final class RawWebSocket { + private let connection = NWConnection(host: "127.0.0.1", port: 8767, using: .tcp) + private let queue = DispatchQueue(label: "app.acode.tests.raw-websocket") + + func open(_ path: String) async throws { + connection.start(queue: queue) + let key = Data((0..<16).map { _ in UInt8.random(in: 0...255) }).base64EncodedString() + try await write(Data("GET \(path) HTTP/1.1\r\nHost: 127.0.0.1\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: \(key)\r\nSec-WebSocket-Version: 13\r\n\r\n".utf8)) + var head = Data() + while head.range(of: Data("\r\n\r\n".utf8)) == nil { head.append(try await read()) } + guard String(decoding: head, as: UTF8.self).hasPrefix("HTTP/1.1 101") else { + throw NSError(domain: "AcodeTests", code: 3, userInfo: [NSLocalizedDescriptionKey: "Upgrade failed"]) + } + } + + func send(_ text: String) async throws { + let payload = Array(text.utf8) + let mask = (0..<4).map { _ in UInt8.random(in: 0...255) } + var frame = Data([0x81, 0x80 | UInt8(payload.count)] + mask) + frame.append(contentsOf: payload.enumerated().map { $1 ^ mask[$0 & 3] }) + try await write(frame) + } + + func close() { + connection.cancel() + } + + private func write(_ data: Data) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in + connection.send(content: data, completion: .contentProcessed { error in + if let error { continuation.resume(throwing: error) } else { continuation.resume() } + }) + } + } + + private func read() async throws -> Data { + try await withCheckedThrowingContinuation { continuation in + connection.receive(minimumIncompleteLength: 1, maximumLength: 4096) { data, _, complete, error in + if let error { continuation.resume(throwing: error) } + else if complete, data?.isEmpty ?? true { continuation.resume(throwing: NWError.posix(.ECONNRESET)) } + else { continuation.resume(returning: data ?? Data()) } + } + } + } +} diff --git a/platforms/ios/runnerTests/AlpineTerminalTests.swift b/platforms/ios/runnerTests/AlpineTerminalTests.swift new file mode 100644 index 0000000000..5afddbefaa --- /dev/null +++ b/platforms/ios/runnerTests/AlpineTerminalTests.swift @@ -0,0 +1,107 @@ +import XCTest +import WebKit + +@MainActor +final class AlpineTerminalTests: BridgeTestCase { + func testAlpineInstallationExecutorAndInteractiveServer() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(#""" + const log = []; + if (!await Terminal.isInstalled()) { + if (!await Terminal.install(text => log.push(text), text => log.push(text))) { + throw new Error(Terminal.lastInstallError + '\n' + log.join('\n')); + } + } + const executor = await Executor.execute("printf 'EXEC:%s\\n' \"$((6*7))\"", true); + if (executor !== 'EXEC:42') throw new Error('Executor: ' + executor); + let failure = ''; + try { await Executor.execute('echo expected-error >&2; exit 7', true); } + catch (error) { failure = String(error); } + if (!failure.includes('expected-error')) throw new Error('Missing nonzero exit: ' + failure); + await Terminal.startAxs(); + const request = (path, data) => new Promise((resolve, reject) => Bridge.http.sendRequest( + 'http://127.0.0.1:8767' + path, + data ? {method:'POST', serializer:'json', responseType:'text', data} : {method:'GET', responseType:'text'}, + resolve, reject)); + let ready = false; + for (let i = 0; i < 100; i++) { + try { ready = (await request('/status')).data.trim() === 'OK'; } catch {} + if (ready) break; + await new Promise(resolve => setTimeout(resolve, 100)); + } + if (!ready) throw new Error('AXS not ready'); + const attach = pid => { + const socket = new WebSocket('ws://127.0.0.1:8767/terminals/' + pid); + socket.binaryType = 'arraybuffer'; + const decoder = new TextDecoder(); + const waiters = []; + let text = ''; + socket.onmessage = event => { + text += typeof event.data === 'string' ? event.data : decoder.decode(event.data, {stream: true}); + for (const waiter of waiters.filter(waiter => text.includes(waiter.token))) waiter.resolve(text); + }; + const opened = new Promise((resolve, reject) => { + socket.onopen = resolve; + socket.onerror = () => reject(new Error('PTY connection failed')); + }); + const expect = token => new Promise((resolve, reject) => { + if (text.includes(token)) { resolve(text); return; } + const timeout = setTimeout(() => reject(new Error('PTY timeout waiting for ' + token + ': ' + text)), 15000); + waiters.push({token, resolve: value => { clearTimeout(timeout); resolve(value); }}); + }); + return {socket, opened, expect}; + }; + const pid = (await request('/terminals', {cols:80, rows:24})).data.trim(); + const first = attach(pid); + await first.opened; + first.socket.send("printf 'PTY:%s\\n' \"$((7*8))\"\n"); + const output = await first.expect('PTY:56'); + await request('/terminals/' + pid + '/resize', {cols:100, rows:40}); + first.socket.send('stty size\n'); + await first.expect('40 100'); + first.socket.close(); + const second = attach(pid); + await second.opened; + await second.expect('PTY:56'); + second.socket.send('exit\n'); + await second.expect('"type":"exit"'); + const other = (await request('/terminals', {cols:80, rows:24})).data.trim(); + await request('/terminals/' + other + '/terminate', {}); + const fs = acode.require('fs'); + const directory = 'alpine://localhost/tmp/acode-files-test'; + await Executor.execute('mkdir -p /tmp/acode-files-test', true); + const file = await fs(directory).createFile('नमस्ते & file.txt', 'hello π\n'); + if (await fs(file).readFile('utf-8') !== 'hello π\n') throw new Error('Guest read/write mismatch'); + await fs(file).writeFile('updated\n'); + const entries = await fs(directory).lsDir(); + if (!entries.some(entry => entry.name === 'नमस्ते & file.txt')) throw new Error('Guest listing mismatch'); + await fs(directory).delete(); + const cached = Bridge.file.cacheDirectory + 'alpine-shared.txt'; + await fs(Bridge.file.cacheDirectory).createFile('alpine-shared.txt', 'shared'); + const quote = text => "'" + text.replaceAll("'", "'\\''") + "'"; + if (await Executor.execute('cat ' + quote(decodeURIComponent(new URL(cached).pathname)), true) !== 'shared') { + throw new Error('Host Files mapping mismatch'); + } + await fs(cached).delete(); + const stream = await new Promise((resolve, reject) => Executor.spawnStream(['/bin/cat'], resolve, reject)); + const echoed = new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(new Error('Process stream timeout')), 5000); + stream.onmessage = event => { clearTimeout(timeout); resolve(new TextDecoder().decode(event.data)); }; + }); + stream.send(new TextEncoder().encode('binary π\n')); + if (await echoed !== 'binary π\n') throw new Error('Raw process stream mismatch'); + stream.close(); + await Executor.execute('printf before > /etc/acode-backup-test', true); + await Terminal.backup(); + await Executor.execute('printf after > /etc/acode-backup-test', true); + await Terminal.restore(); + if (await Executor.execute('cat /etc/acode-backup-test', true) !== 'before') throw new Error('Backup did not restore'); + await Executor.execute('rm /etc/acode-backup-test', true); + await Terminal.clearBackup(); + return {executor, output, installed: await Terminal.isInstalled()}; + """#, arguments: [:], in: nil, contentWorld: .page) as? [String: Any] + XCTAssertEqual(result?["executor"] as? String, "EXEC:42") + XCTAssertEqual(result?["installed"] as? Bool, true) + XCTAssertTrue((result?["output"] as? String)?.contains("PTY:56") == true) + } +} diff --git a/platforms/ios/runnerTests/AppBridgeTests.swift b/platforms/ios/runnerTests/AppBridgeTests.swift new file mode 100644 index 0000000000..a827135833 --- /dev/null +++ b/platforms/ios/runnerTests/AppBridgeTests.swift @@ -0,0 +1,202 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class AppBridgeTests: BridgeTestCase { + func testStartupIntentsWaitForTheEditorAndWarmIntentsArriveImmediately() async throws { + let webView = try await editorWebView() + defer { IncomingLinks.shared.reset(); webView.reload() } + let url = try XCTUnwrap(URL(string: "acode://plugin/install/cold.start.fixture")) + IncomingLinks.shared.reset() + IncomingLinks.shared.receive(url) + let early = try await webView.callAsyncJavaScript(""" + document.body.classList.add('loading'); + window.startupIntents = []; + const receive = intent => startupIntents.push(intent.data); + system.setIntentHandler(receive, error => { throw Error(error); }); + system.getIntent(receive, error => { throw Error(error); }); + await new Promise((resolve, reject) => Bridge.exec(resolve, reject, 'System', 'getArch', [])); + await new Promise(resolve => setTimeout(resolve, 200)); + return startupIntents; + """, arguments: [:], in: nil, contentWorld: .page) as? [String] + XCTAssertEqual(early, []) + let cold = try await webView.callAsyncJavaScript(""" + document.body.classList.remove('loading'); + for (let n = 0; n < 50 && !startupIntents.length; n++) + await new Promise(resolve => setTimeout(resolve, 100)); + return startupIntents; + """, arguments: [:], in: nil, contentWorld: .page) as? [String] + XCTAssertEqual(cold, [url.absoluteString]) + IncomingLinks.shared.receive(url) + let warm = try await webView.callAsyncJavaScript(""" + for (let n = 0; n < 50 && startupIntents.length < 2; n++) + await new Promise(resolve => setTimeout(resolve, 100)); + return startupIntents; + """, arguments: [:], in: nil, contentWorld: .page) as? [String] + XCTAssertEqual(warm, [url.absoluteString, url.absoluteString]) + } + + func testUnsupportedAppActionsRejectForNativeAndLegacyPlugins() async throws { + let webView = try await editorWebView() + let errors = try await webView.callAsyncJavaScript(""" + const attempt = (api, service, action, args = []) => new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(Error(service + '.' + action + ' did not settle')), 3000); + api.exec(() => { clearTimeout(timer); resolve('unexpected success'); }, + error => { clearTimeout(timer); resolve(String(error)); }, service, action, args); + }); + return await Promise.all([ + attempt(Bridge, 'App', 'overrideButton', ['menubutton', true]), + attempt(Bridge, 'App', 'clearHistory'), + attempt(cordova, 'CoreAndroid', 'overrideBackbutton', [true]), + attempt(cordova, 'CoreAndroid', 'overrideButton', ['volumeup', true]), + attempt(cordova, 'CoreAndroid', 'clearHistory'), + ]); + """, arguments: [:], in: nil, contentWorld: .page) as? [String] + XCTAssertEqual(errors, [ + "overrideButton is unavailable on iOS", + "clearHistory is unavailable on iOS", + "overrideButton is unavailable on iOS", + "overrideButton is unavailable on iOS", + "clearHistory is unavailable on iOS", + ]) + } + + func testIncomingFileOpensInTheEditorWithItsOriginalName() async throws { + let webView = try await appWebView() + let name = "Incoming # 50% 日本語.txt" + let url = AppFiles.shared.cache.appendingPathComponent(name) + try Data("incoming file ✓".utf8).write(to: url) + defer { try? FileManager.default.removeItem(at: url) } + IncomingLinks.shared.receive(url) + let opened = try await webView.callAsyncJavaScript(""" + for(let n=0;n<100;n++) { + const file = window.editorManager?.getFile(uri,'uri'); + if(file) { + try { return file.filename === name && file.session.getValue() === 'incoming file ✓'; } + finally { await file.remove(true); } + } + await new Promise(resolve=>setTimeout(resolve,100)); + } + throw Error('Incoming file did not open'); + """, arguments: ["uri": "file://" + url.path, "name": name], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(opened, true) + } + + func testEditorAvoidsSystemSafeAreas() async throws { + let webView = try await appWebView() + let window = try XCTUnwrap(webView.window) + window.layoutIfNeeded() + let frame = webView.convert(webView.bounds, to: window) + XCTAssertGreaterThanOrEqual(frame.minY, window.safeAreaInsets.top) + XCTAssertLessThanOrEqual(frame.maxY, window.bounds.height - window.safeAreaInsets.bottom) + } + func testEditorReadsEditsAndSavesAFile() async throws { + let webView = try await appWebView() + let result = try await webView.callAsyncJavaScript(""" + for(let n=0; !window.editorManager && n<100; n++) await new Promise(r=>setTimeout(r,100)); + const fsOperation = acode.require('fsOperation'); + const EditorFile = acode.require('EditorFile'); + const name = 'ios editor # 50% ✓.txt'; + const root = fsOperation(Bridge.file.cacheDirectory); + let directoryError; + try { await root.writeFile('must not replace a directory'); } + catch(error) { directoryError = error.code; } + if(directoryError !== 11) throw Error('Expected directory type mismatch, got ' + directoryError); + const uri = await root.createFile(name, 'original'); + const fs = fsOperation(uri); + let file; + let stage = 'read'; + try { + if(await fs.readFile('utf-8') !== 'original') throw Error('File read failed'); + stage = 'editor'; + file = new EditorFile(name, {uri, text:'original', isUnsaved:false}); + file.makeActive(); + file.session.setValue('edited ✓'); + await file.save(); + if(await fs.readFile('utf-8') !== 'edited ✓') throw Error('Editor save failed'); + stage = 'watch'; + const entry = await new Promise((resolve,reject)=>resolveLocalFileSystemURL(uri,resolve,reject)); + const changed = new Promise((resolve,reject)=>{ + const watch=sdcard.watchFile(entry.nativeURL,()=>{clearTimeout(timer);watch.unwatch();resolve(true);},reject); + const timer=setTimeout(()=>{watch.unwatch();reject(Error('File watch timed out'));},5000); + }); + await fs.writeFile('external edit'); + await changed; + return true; + } catch(error) { throw Error(stage + ': ' + JSON.stringify(error) + ' ' + error?.message); + } finally { if(file) await file.remove(true); await fs.delete(); } + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + func testEditorWorkerLoadsFromFileURL() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(""" + await new Promise(resolve => document.addEventListener('deviceready', resolve)); + const call = (action,args)=>new Promise((resolve,reject)=>Bridge.exec(resolve,error=>reject(Error(action+': '+JSON.stringify(error))),'File',action,args)); + const entry = await call('getFile',[Bridge.file.cacheDirectory,'worker # ? 50% 日本語.js',{create:true}]); + await call('write',[entry.nativeURL,'postMessage({answer:42});',0,false]); + const file = await new Promise((resolve,reject)=>resolveLocalFileSystemURI(entry.nativeURL,resolve,error=>reject(Error('resolve '+entry.nativeURL+': '+JSON.stringify(error))))); + try { + return await new Promise((resolve,reject)=>{ + const worker = new Worker(file.toInternalURL()); + const timer = setTimeout(()=>{worker.terminate();reject(Error('Worker timed out'));},5000); + worker.onmessage = e=>{clearTimeout(timer);worker.terminate();resolve(e.data.answer);}; + worker.onerror = e=>{clearTimeout(timer);worker.terminate();reject(Error(e.message));}; + }); + } finally { await call('remove',[entry.nativeURL]); } + """, arguments: [:], in: nil, contentWorld: .page) as? Int + XCTAssertEqual(result, 42) + } + + + func testNativeStartupAndFileBridge() async throws { + let webView = try await appWebView() + let result = try await webView.callAsyncJavaScript(""" + await new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(Error('Native startup timed out')), 10000); + document.addEventListener('deviceready', () => { clearTimeout(timeout); resolve(); }); + }); + const call = (service, action, args = []) => new Promise((resolve, reject) => Bridge.exec(resolve, reject, service, action, args)); + const root = await call('File', 'resolveLocalFileSystemURI', [Bridge.file.cacheDirectory]); + const name = 'ios-bridge-' + Date.now() + '.txt'; + const entry = await call('File', 'getFile', [Bridge.file.cacheDirectory, name, {create:true, exclusive:true}]); + try { + const bytes = new Uint8Array([0, 127, 128, 159, 255]).buffer; + await call('File', 'write', [entry.nativeURL, bytes, 0, true]); + const read = await call('File', 'readAsArrayBuffer', [entry.nativeURL, 0, 5]); + const values = [...new Uint8Array(read)]; + if (values.join(',') !== '0,127,128,159,255') throw Error('Binary roundtrip: ' + values); + await call('File', 'write', [entry.nativeURL, 'Acode ✓', 0, false]); + const text = await call('File', 'readAsText', [entry.nativeURL, 'UTF-8', 0, 99]); + if (text !== 'Acode ✓') throw Error('Text roundtrip: ' + text); + const resolved = await new Promise((resolve, reject) => resolveLocalFileSystemURL(entry.nativeURL, resolve, reject)); + const response = await fetch(resolved.toInternalURL()); + if (await response.text() !== text) throw Error('Scheme URL does not match native file'); + let unavailable = false; + try { await call('MissingService', 'action'); } catch { unavailable = true; } + return {platform: Bridge.platformId, directory: root.isDirectory, unavailable, compatibility: cordova.file === Bridge.file}; + } finally { await call('File', 'remove', [entry.nativeURL]); } + """, arguments: [:], in: nil, contentWorld: .page) as? [String: Any] + XCTAssertEqual(result?["platform"] as? String, "ios") + XCTAssertEqual(result?["directory"] as? Bool, true) + XCTAssertEqual(result?["unavailable"] as? Bool, true) + XCTAssertEqual(result?["compatibility"] as? Bool, true) + } + + func testEditorFinishesStartup() async throws { + let webView = try await appWebView() + webView.configuration.userContentController.addUserScript(WKUserScript(source: "window.startupErrors=[]; addEventListener('error',e=>startupErrors.push(e.message+' '+e.filename+':'+e.lineno)); addEventListener('unhandledrejection',e=>startupErrors.push(JSON.stringify(e.reason)+' '+e.reason?.stack));", injectionTime: .atDocumentStart, forMainFrameOnly: true)) + webView.reload() + try await Task.sleep(for: .seconds(1)) + for _ in 0..<100 { + let ready = try await webView.evaluateJavaScript("!!window.editorManager && !document.body.classList.contains('loading')") as? Bool + if ready == true { return } + try await Task.sleep(for: .milliseconds(200)) + } + let state = try await webView.evaluateJavaScript("JSON.stringify({body:document.body.innerText.slice(0,1200),attributes:document.body.outerHTML.slice(0,1000),manager:typeof window.editorManager,acode:typeof window.acode,errors:window.startupErrors,scripts:[...document.scripts].map(s=>s.src)})") + XCTFail("Editor did not finish startup: \(String(describing: state))") + } + +} diff --git a/platforms/ios/runnerTests/AppIconTests.swift b/platforms/ios/runnerTests/AppIconTests.swift new file mode 100644 index 0000000000..3f72a544ab --- /dev/null +++ b/platforms/ios/runnerTests/AppIconTests.swift @@ -0,0 +1,55 @@ +import XCTest +@testable import runner + +@MainActor +final class AppIconTests: BridgeTestCase { + func testEveryPickerIconIsPackagedForIPhoneAndIPad() throws { + let previews = try FileManager.default.contentsOfDirectory(at: Bundle.main.bundleURL.appendingPathComponent("bundle/icons"), includingPropertiesForKeys: nil) + let expected = Set(previews.filter { $0.lastPathComponent.hasPrefix("ic_acode_") && $0.pathExtension == "svg" && $0.lastPathComponent != "ic_acode_default.svg" }.map { $0.deletingPathExtension().lastPathComponent }) + XCTAssertEqual(expected.count, 15) + let metadata = try XCTUnwrap(PropertyListSerialization.propertyList(from: Data(contentsOf: Bundle.main.bundleURL.appendingPathComponent("Info.plist")), format: nil) as? [String: Any]) + for key in ["CFBundleIcons", "CFBundleIcons~ipad"] { + let icons = try XCTUnwrap(metadata[key] as? [String: Any]) + let alternatives = try XCTUnwrap(icons["CFBundleAlternateIcons"] as? [String: Any]) + XCTAssertEqual(Set(alternatives.keys), expected) + XCTAssertNotNil(icons["CFBundlePrimaryIcon"]) + } + XCTAssertTrue(UIApplication.shared.supportsAlternateIcons) + } + + func testPublicIconNoOpAndUnknownIconRejection() async throws { + let webView = try await appWebView() + let current = UIApplication.shared.alternateIconName?.replacingOccurrences(of: "ic_acode_", with: "") ?? "default" + let result = try await webView.callAsyncJavaScript(""" + const call=id=>new Promise((resolve,reject)=>system.setAppIcon(id,resolve,reject)); + await call(current); + try{await call('unknown-icon');throw Error('Unknown icon accepted');} + catch(error){if(error!=='Unknown app icon: unknown-icon')throw error;} + return true; + """, arguments: ["current": current], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + func testPickerControlsHaveVisibleTouchTargets() async throws { + let webView = try await appWebView() + let result = try await webView.callAsyncJavaScript(""" + for(let n=0;app.classList.contains('loading')&&n<150;n++)await new Promise(r=>setTimeout(r,100)); + if(app.classList.contains('loading'))throw Error('App startup did not finish'); + await acode.exec('open','settings'); + document.querySelector('[data-key="appIcon"]').click(); + await new Promise(r=>setTimeout(r,300)); + const dialog=document.querySelector('.app-icon-dialog'); + try { + const buttons=[...dialog.querySelectorAll('[data-icon]')]; + const targets=buttons.map(button=>{ + const r=button.getBoundingClientRect(); + const element=document.elementFromPoint(r.x+r.width/2,r.y+r.height/2); + const hit=element?.closest('[data-icon]'); + return {id:button.dataset.icon,x:r.x,y:r.y,width:r.width,height:r.height,hit:hit?.dataset.icon,element:element?.outerHTML.slice(0,200)}; + }); + return {targets,correct:targets.length===16&&targets.every(t=>t.hit===t.id)}; + }finally{dialog.querySelector('.button-container button').click();} + """, arguments: [:], in: nil, contentWorld: .page) as? [String: Any] + XCTAssertEqual(result?["correct"] as? Bool, true, String(describing: result)) + } +} diff --git a/platforms/ios/runnerTests/ArchiveTests.swift b/platforms/ios/runnerTests/ArchiveTests.swift new file mode 100644 index 0000000000..bb493dc95e --- /dev/null +++ b/platforms/ios/runnerTests/ArchiveTests.swift @@ -0,0 +1,169 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class ArchiveTests: BridgeTestCase { + func testFileBrowserCompressesAndImportsBinaryUnicodeAndEmptyEntries() async throws { + let app = try await editorWebView() + let manager = FileManager.default + let directory = AppFiles.shared.documents.appendingPathComponent("Archive fixture " + UUID().uuidString) + let nested = directory.appendingPathComponent("日本語 # sample") + var bytes = Data(count: 32 * 1024 * 1024) + bytes.withUnsafeMutableBytes { (buffer: UnsafeMutableRawBufferPointer) in + for index in buffer.indices { buffer[index] = UInt8(truncatingIfNeeded: index * 31 + 7) } + } + try manager.createDirectory(at: nested.appendingPathComponent("empty"), withIntermediateDirectories: true) + try bytes.write(to: nested.appendingPathComponent("binary #.bin")) + try Data().write(to: nested.appendingPathComponent("blank.txt")) + try "Archive ✓".write(to: directory.appendingPathComponent("notes.txt"), atomically: true, encoding: .utf8) + defer { try? manager.removeItem(at: directory) } + do { + let uri = try await app.callAsyncJavaScript(""" + window.archiveFixture={storage:localStorage.storageList,state:localStorage.fileBrowserState}; + delete localStorage.storageList; + let stage='open browser'; + try { + const wait=async check=>{for(let n=0;n<200;n++){if(await check())return;await new Promise(r=>setTimeout(r,50));}throw Error('Archive interaction timed out');}; + acode.require('fileBrowser')('file','Archive fixture',false).catch(()=>{}); + await wait(()=>document.querySelector('#file-browser li[data-uuid="ios-documents"]')); + const browser=document.getElementById('file-browser'); + const page=browser.closest('wc-page'); + stage='open documents'; + browser.querySelector('li[data-uuid="ios-documents"]').click(); + await wait(()=>browser.querySelector('li[data-name="'+name+'"]')); + browser.querySelector('li[data-name="'+name+'"]').click(); + stage='select entries'; + await wait(()=>browser.querySelector('li[data-name="notes.txt"]')); + page.querySelector('[data-action="toggle-menu"]').click(); + document.querySelector('.context-menu [action="select-items"]').click(); + await wait(()=>!document.querySelector('.context-menu')); + browser.querySelector('li[data-name="日本語 # sample"]').click(); + browser.querySelector('li[data-name="notes.txt"]').click(); + page.querySelector('[data-action="toggle-menu"]').click(); + document.querySelector('.context-menu [action="compress"]').click(); + stage='read generated archive'; + let archive; + await wait(async()=>{ + const entries=await acode.require('fsOperation')(uri).lsDir(); + archive=entries.find(entry=>entry.name.startsWith('archive_')&&entry.name.endsWith('.zip')); + return archive && browser.querySelector('li[data-name="'+archive.name+'"]'); + }); + return archive.url; + }catch(error){throw Error(stage+': '+(error?.message||JSON.stringify(error)));} + """, arguments: ["name": directory.lastPathComponent, "uri": "file://" + directory.path], in: nil, contentWorld: .page) as? String + let archive = try AppFiles.shared.resolve(XCTUnwrap(uri)) + XCTAssertGreaterThan(try Data(contentsOf: archive).count, bytes.count) + let first = archive.deletingPathExtension() + try await importArchive(archive, app: app) + try await verifyImport(first, bytes: bytes) + try "First import retained".write(to: first.appendingPathComponent("notes.txt"), atomically: true, encoding: .utf8) + try await importArchive(archive, app: app) + var second: URL? + for _ in 0..<100 { + second = try manager.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil).first { + $0.lastPathComponent.hasPrefix(first.lastPathComponent + "_") + } + if second != nil { break } + try await Task.sleep(for: .milliseconds(50)) + } + try await verifyImport(XCTUnwrap(second), bytes: bytes) + try await cancelImport(archive, in: directory, app: app) + XCTAssertEqual(try String(contentsOf: first.appendingPathComponent("notes.txt"), encoding: .utf8), "First import retained") + } catch { + try? await cleanup(app) + throw error + } + try await cleanup(app) + } + + private func cancelImport(_ archive: URL, in directory: URL, app: WKWebView) async throws { + _ = try await app.callAsyncJavaScript(""" + const fs=acode.require('fsOperation')(uri); + const names=entries=>JSON.stringify(entries.map(entry=>entry.name).sort()); + const state=window.archiveCancellation={exec:Bridge.exec,release:null,held:false,fs,names,before:names(await fs.lsDir())}; + // Hold one real write's completion so the normal Cancel button can be exercised. + Bridge.exec=(success,error,service,action,args=[])=>{ + const size=args[1]?.byteLength||args[1]?.length||0; + if(!state.held&&service==='File'&&action==='write'&&String(args[0]).includes(marker)&&size>1024*1024) { + state.held=true; + return state.exec((...values)=>{state.release=()=>success?.(...values);},error,service,action,args); + } + return state.exec(success,error,service,action,args); + }; + """, arguments: ["uri": "file://" + directory.path, "marker": String(directory.lastPathComponent.suffix(36))], in: nil, contentWorld: .page) + try await importArchive(archive, app: app) + let cancelled = try await app.callAsyncJavaScript(""" + const state=window.archiveCancellation; + const wait=async check=>{for(let n=0;n<400;n++){if(await check())return;await new Promise(r=>setTimeout(r,50));}throw Error('Archive cancellation timed out');}; + try { + await wait(()=>state.release&&document.querySelector('#__loader button')); + if(state.names(await state.fs.lsDir())===state.before)throw Error('No partial import to cancel'); + document.querySelector('#__loader button').click(); + Bridge.exec=state.exec; + const release=state.release;state.release=null;release(); + await wait(async()=>state.names(await state.fs.lsDir())===state.before&&!document.getElementById('__loader')); + return true; + } finally { + Bridge.exec=state.exec;state.release?.();delete window.archiveCancellation; + } + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(cancelled, true) + } + + private func importArchive(_ archive: URL, app: WKWebView) async throws { + _ = try await app.evaluateJavaScript(""" + document.getElementById('file-browser').closest('wc-page').querySelector('[data-action="toggle-add-menu"]').click(); + document.querySelector('.context-menu [action="import-project-zip"]').click(); + """) + var responder: UIResponder? = app + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let host = try XCTUnwrap(responder as? WebViewController) + var picker: UIDocumentPickerViewController? + for _ in 0..<100 { + if let presented = host.presentedViewController as? UIDocumentPickerViewController, !presented.isBeingPresented { + picker = presented; break + } + try await Task.sleep(for: .milliseconds(50)) + } + let selected = try XCTUnwrap(picker) + // Simulated selection can finish before the remote document service disconnects. + addTeardownBlock { @MainActor in withExtendedLifetime(selected) {} } + selected.delegate?.documentPicker?(selected, didPickDocumentsAt: [archive]) + await withCheckedContinuation { continuation in selected.dismiss(animated: false) { continuation.resume() } } + } + + private func verifyImport(_ directory: URL, bytes: Data) async throws { + let notes = directory.appendingPathComponent("notes.txt") + for _ in 0..<200 { + if (try? String(contentsOf: notes, encoding: .utf8)) == "Archive ✓" { break } + try await Task.sleep(for: .milliseconds(50)) + } + let nested = directory.appendingPathComponent("日本語 # sample") + XCTAssertEqual(try String(contentsOf: notes, encoding: .utf8), "Archive ✓") + XCTAssertEqual(try Data(contentsOf: nested.appendingPathComponent("binary #.bin")), bytes) + XCTAssertEqual(try Data(contentsOf: nested.appendingPathComponent("blank.txt")), Data()) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: nested.appendingPathComponent("empty").path), []) + } + + private func cleanup(_ app: WKWebView) async throws { + _ = try await app.callAsyncJavaScript(""" + const cancellation=window.archiveCancellation; + if(cancellation){ + document.querySelector('#__loader button')?.click(); + Bridge.exec=cancellation.exec;cancellation.release?.();delete window.archiveCancellation; + } + const page=document.getElementById('file-browser')?.closest('wc-page'); + if(page?.querySelector('.selection-mode'))page.querySelector('[data-action="close"]').click(); + page?.querySelector('[data-action="close"]')?.click(); + for(let n=0;page?.isConnected&&n<100;n++)await new Promise(resolve=>setTimeout(resolve,20)); + if(page?.isConnected)throw Error('Archive browser did not close'); + const saved=window.archiveFixture; + if(saved){ + if(saved.storage===undefined)delete localStorage.storageList;else localStorage.storageList=saved.storage; + if(saved.state===undefined)delete localStorage.fileBrowserState;else localStorage.fileBrowserState=saved.state; + } + delete window.archiveFixture; + """, arguments: [:], in: nil, contentWorld: .page) + } +} diff --git a/platforms/ios/runnerTests/AuthenticationTests.swift b/platforms/ios/runnerTests/AuthenticationTests.swift new file mode 100644 index 0000000000..3ee015d858 --- /dev/null +++ b/platforms/ios/runnerTests/AuthenticationTests.swift @@ -0,0 +1,169 @@ +import CryptoKit +import WebKit +import XCTest +@testable import runner + +final class AuthenticationTests: XCTestCase { + private var auth: AppAuthentication! + + override func setUpWithError() throws { auth = AppAuthentication(namespace: "test-auth-" + UUID().uuidString) } + override func tearDownWithError() throws { try auth.secrets.clear() } + + @MainActor + func testAuthenticationLinksDoNotReachPluginIntentObservers() { + let links = IncomingLinks() + var received: URL? + links.authenticationHandler = { received = $0 } + let leaked = expectation(description: "Authentication URL reached plugin observers") + leaked.isInverted = true + let observer = NotificationCenter.default.addObserver(forName: .acodeDeepLink, object: nil, queue: nil) { _ in leaked.fulfill() } + defer { NotificationCenter.default.removeObserver(observer) } + let url = URL(string: "acode://auth/callback?code=fixture&state=fixture")! + links.receive(url) + XCTAssertEqual(received, url) + wait(for: [leaked], timeout: 0.01) + } + + func testLoginChallengeAndOneTimeExchangeMatchTheExistingServerProtocol() throws { + for origin in ["https://acode.app", "https://dev.acode.app"] { + let url = try auth.begin(baseURL: origin, version: 1011) + let items = try XCTUnwrap(URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems) + let values = Dictionary(uniqueKeysWithValues: items.map { ($0.name, $0.value!) }) + XCTAssertEqual(url.host, URL(string: origin)?.host) + XCTAssertEqual(url.path, "/login") + XCTAssertEqual(values["authFlow"], "app-code") + XCTAssertEqual(values["redirect"], "app") + XCTAssertEqual(values["src"], "ios") + XCTAssertEqual(values["appVersionCode"], "1011") + XCTAssertEqual(values["state"]?.count, 48) + let callback = URL(string: "acode://auth/callback?state=\(values["state"]!)&code=test-code")! + let request = try auth.consume(callback) + let payload = try XCTUnwrap(JSONSerialization.jsonObject(with: request.httpBody!) as? [String: String]) + XCTAssertEqual(request.url?.absoluteString, origin + "/api/user/app-token/exchange") + XCTAssertEqual(request.httpMethod, "POST") + XCTAssertEqual(payload["code"], "test-code") + XCTAssertEqual(payload["state"], values["state"]) + XCTAssertEqual(payload["verifier"]?.count, 64) + let digest = SHA256.hash(data: Data(payload["verifier"]!.utf8)).map { String(format: "%02x", $0) }.joined() + XCTAssertEqual(values["challenge"], digest) + XCTAssertThrowsError(try auth.consume(callback)) + XCTAssertEqual(try auth.secrets.get("pending_login"), "") + } + } + + func testRejectsForgedCallbacksUntrustedOriginsAndInvalidCookieTokens() throws { + for value in ["http://acode.app", "https://acode.app.evil.test", "https://acode.app:8443", "https://user@acode.app", "https://acode.app/path", "http://dev.acode.app", "https://dev.acode.app.evil.test", "https://dev.acode.app:8443", "https://dev.acode.app?next=other"] { + XCTAssertThrowsError(try auth.begin(baseURL: value, version: 1)) + } + let url = try auth.begin(baseURL: "https://acode.app", version: 1) + let state = URLComponents(url: url, resolvingAgainstBaseURL: false)!.queryItems!.first { $0.name == "state" }!.value! + for value in ["acode://auth/callback?state=wrong&code=test", "acode://auth/callback?state=\(state)&code=", "acode://plugin/callback?state=\(state)&code=test", "acode://auth/callback?state=\(state)&state=\(state)&code=test"] { + XCTAssertThrowsError(try auth.consume(URL(string: value)!)) + } + for token in ["", "x;other=y", "x\r\ny", "unicode✓", "a b"] { XCTAssertThrowsError(try auth.save(token)) } + try auth.save("fixture.token-123_value") + XCTAssertEqual(try auth.secrets.get("auth_token"), "fixture.token-123_value") + try auth.logout() + XCTAssertEqual(try auth.secrets.get("auth_token"), "") + XCTAssertEqual(try auth.secrets.get("pending_login"), "") + } + + @MainActor + func testAPIRoutingKeepsDevelopmentAndProductionCredentialsSeparate() async throws { + let production = URL(string: "https://acode.app")! + let development = URL(string: "https://dev.acode.app")! + let previous = (HTTPCookieStorage.shared.cookies ?? []).filter { $0.name == "token" && AppAuthentication.hosts.contains($0.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) } + let unrelated = HTTPCookie(properties: [.name: "review-fixture-" + UUID().uuidString, .value: "other", .domain: "acode.app", .path: "/"])! + HTTPCookieStorage.shared.setCookie(unrelated) + defer { + HTTPCookieStorage.shared.deleteCookie(unrelated) + for cookie in HTTPCookieStorage.shared.cookies ?? [] where cookie.name == "token" && AppAuthentication.hosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { + HTTPCookieStorage.shared.deleteCookie(cookie) + } + previous.forEach(HTTPCookieStorage.shared.setCookie) + } + try auth.save("production-token") + try auth.save("development-token", for: development) + let dataStore = WKWebsiteDataStore.nonPersistent() + try await auth.synchronizeCookies(dataStore.httpCookieStore) + let webCookies = await dataStore.httpCookieStore.allCookies().filter { $0.name == "token" } + XCTAssertEqual(Set(webCookies.map(\.domain)), Set(AppAuthentication.hosts)) + let api = AppAPIHandler(auth: auth) + var source = URLRequest(url: URL(string: "acode://localhost/__api__/login?test=one%20two")!) + source.setValue("include", forHTTPHeaderField: "X-Acode-Credentials") + source.setValue("token=untrusted", forHTTPHeaderField: "Cookie") + for (origin, token) in [(production, "production-token"), (development, "development-token")] { + XCTAssertEqual((HTTPCookieStorage.shared.cookies(for: origin) ?? []).filter { $0.name == "token" }.map(\.value), [token]) + source.setValue(origin.absoluteString, forHTTPHeaderField: "X-Acode-API-Origin") + let request = try api.request(for: source) + XCTAssertEqual(request.url?.absoluteString, origin.absoluteString + "/api/login?test=one%20two") + let tokens = (request.value(forHTTPHeaderField: "Cookie") ?? "").components(separatedBy: ";").map { $0.trimmingCharacters(in: .whitespaces) }.filter { $0.hasPrefix("token=") } + XCTAssertEqual(tokens, ["token=" + token]) + XCTAssertFalse(request.httpShouldHandleCookies) + XCTAssertNil(request.value(forHTTPHeaderField: "X-Acode-API-Origin")) + } + source.setValue("omit", forHTTPHeaderField: "X-Acode-Credentials") + XCTAssertNil(try api.request(for: source).value(forHTTPHeaderField: "Cookie")) + source.setValue("https://dev.acode.app.evil.test", forHTTPHeaderField: "X-Acode-API-Origin") + XCTAssertThrowsError(try api.request(for: source)) + source.setValue(nil, forHTTPHeaderField: "X-Acode-API-Origin") + XCTAssertEqual(try api.request(for: source).url?.host, production.host) + try auth.logout() + XCTAssertEqual(try auth.token(for: production), "") + XCTAssertEqual(try auth.token(for: development), "") + } + + func testExchangeErrorsExplainRetryTimingAndExpiredSignIn() { + let url = URL(string: "https://dev.acode.app/api/user/app-token/exchange")! + let limited = HTTPURLResponse(url: url, statusCode: 429, httpVersion: nil, headerFields: ["Retry-After": "61"])! + XCTAssertEqual(AppAuthentication.exchangeFailure(limited).message, "Too many sign-in attempts. Please wait 2 minute(s) and try again.") + let expired = HTTPURLResponse(url: url, statusCode: 400, httpVersion: nil, headerFields: nil)! + XCTAssertEqual(AppAuthentication.exchangeFailure(expired).message, "Sign-in expired. Please try again.") + } + + func testAPIResponseCookiesPersistUpdateAndExpireWithoutReplacingAccountTokens() throws { + let name = "response-fixture-" + UUID().uuidString + defer { + for cookie in HTTPCookieStorage.shared.cookies ?? [] where cookie.name == name { + HTTPCookieStorage.shared.deleteCookie(cookie) + } + } + for host in AppAuthentication.hosts { + let origin = URL(string: "https://" + host)! + let url = origin.appendingPathComponent("api/cookie") + try auth.save("account-token", for: origin) + var source = URLRequest(url: URL(string: "acode://localhost/__api__/cookie")!) + source.setValue(origin.absoluteString, forHTTPHeaderField: "X-Acode-API-Origin") + source.setValue("include", forHTTPHeaderField: "X-Acode-Credentials") + let api = AppAPIHandler(auth: auth) + for (status, value) in [(200, "first"), (302, "updated")] { + let response = HTTPURLResponse(url: url, statusCode: status, httpVersion: nil, headerFields: ["Set-Cookie": "\(name)=\(value); Path=/api; Secure; HttpOnly, token=response-token; Path=/; Secure"])! + let before = (HTTPCookieStorage.shared.cookies(for: url) ?? []).first { $0.name == name }?.value + AppAPIHandler.storeCookies(from: response, credentials: false) + XCTAssertEqual((HTTPCookieStorage.shared.cookies(for: url) ?? []).first { $0.name == name }?.value, before) + AppAPIHandler.storeCookies(from: response, credentials: true) + let cookie = (HTTPCookieStorage.shared.cookies(for: url) ?? []).first { $0.name == name } + XCTAssertEqual(cookie?.value, value) + XCTAssertEqual(cookie?.isHTTPOnly, true) + XCTAssertFalse((HTTPCookieStorage.shared.cookies(for: url) ?? []).contains { $0.name == "token" && $0.value == "response-token" }) + let header = try api.request(for: source).value(forHTTPHeaderField: "Cookie") ?? "" + XCTAssertTrue(header.contains("\(name)=\(value)")) + XCTAssertTrue(header.contains("token=account-token")) + } + for expiry in ["Max-Age=0", "Expires=Thu, 01 Jan 1970 00:00:00 GMT"] { + let renewed = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: ["Set-Cookie": "\(name)=renewed; Path=/api; Secure"])! + AppAPIHandler.storeCookies(from: renewed, credentials: true) + let expired = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: ["Set-Cookie": "\(name)=; Path=/api; \(expiry); Secure"])! + AppAPIHandler.storeCookies(from: expired, credentials: false) + XCTAssertEqual((HTTPCookieStorage.shared.cookies(for: url) ?? []).first { $0.name == name }?.value, "renewed") + AppAPIHandler.storeCookies(from: expired, credentials: true) + XCTAssertFalse((HTTPCookieStorage.shared.cookies(for: url) ?? []).contains { $0.name == name }) + } + XCTAssertEqual(try auth.token(for: origin), "account-token") + } + let foreign = URL(string: "https://untrusted.example/api/cookie")! + let response = HTTPURLResponse(url: foreign, statusCode: 200, httpVersion: nil, headerFields: ["Set-Cookie": "\(name)=foreign; Path=/"])! + AppAPIHandler.storeCookies(from: response, credentials: true) + XCTAssertFalse((HTTPCookieStorage.shared.cookies ?? []).contains { $0.name == name }) + } +} diff --git a/platforms/ios/runnerTests/BridgeTestCase.swift b/platforms/ios/runnerTests/BridgeTestCase.swift new file mode 100644 index 0000000000..55214909e5 --- /dev/null +++ b/platforms/ios/runnerTests/BridgeTestCase.swift @@ -0,0 +1,55 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +class BridgeTestCase: XCTestCase { + override func setUp() async throws { + let webView = try await appWebView() + let marker = "iosConsentFixture" + let scripts = webView.configuration.userContentController + guard !scripts.userScripts.contains(where: { $0.source.contains(marker) }) else { return } + SimulatorTestSupport.disableConsent(in: scripts) + try await reloadWebView(webView) + } + + func appWebView() async throws -> WKWebView { + for _ in 0..<100 { + for scene in UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }) { + for window in scene.windows { + if let webView = findWebView(window), webView.url?.scheme == "acode", !webView.isLoading, + (try? await webView.evaluateJavaScript("!!window.Bridge")) as? Bool == true { return webView } + } + } + try await Task.sleep(for: .milliseconds(100)) + } + throw NSError(domain: "AcodeTests", code: 1, userInfo: [NSLocalizedDescriptionKey: "App WebView not mounted"]) + } + + func editorWebView() async throws -> WKWebView { + let webView = try await appWebView() + for _ in 0..<150 { + if (try? await webView.evaluateJavaScript("!!window.acode && !!window.editorManager && !document.body.classList.contains('loading')")) as? Bool == true { return webView } + try await Task.sleep(for: .milliseconds(100)) + } + throw NSError(domain: "AcodeTests", code: 2, userInfo: [NSLocalizedDescriptionKey: "Editor startup did not finish"]) + } + + func reloadWebView(_ webView: WKWebView) async throws { + let marker = UUID().uuidString + _ = try await webView.evaluateJavaScript("window.iosTestReloadMarker='\(marker)'") + webView.reload() + for _ in 0..<150 { + if !webView.isLoading, + (try? await webView.evaluateJavaScript("window.iosTestReloadMarker!=='\(marker)' && !!window.Bridge")) as? Bool == true { return } + try await Task.sleep(for: .milliseconds(100)) + } + throw NSError(domain: "AcodeTests", code: 3, userInfo: [NSLocalizedDescriptionKey: "App WebView did not finish reloading"]) + } + + private func findWebView(_ view: UIView) -> WKWebView? { + if let webView = view as? WKWebView, webView.url?.scheme == "acode" { return webView } + for child in view.subviews { if let found = findWebView(child) { return found } } + return nil + } +} diff --git a/platforms/ios/runnerTests/BrowserBridgeTests.swift b/platforms/ios/runnerTests/BrowserBridgeTests.swift new file mode 100644 index 0000000000..ba8d50b069 --- /dev/null +++ b/platforms/ios/runnerTests/BrowserBridgeTests.swift @@ -0,0 +1,131 @@ +import SafariServices +import WebKit +import XCTest +@testable import runner + +@MainActor +final class BrowserBridgeTests: BridgeTestCase { + func testAcodeWebsiteLinksCarryIOSSourceWithoutLosingTheirDestination() throws { + for host in ["acode.app", "dev.acode.app"] { + for path in ["/", "/faqs", "/profile/edit"] { + let original = try XCTUnwrap(URL(string: "https://\(host)\(path)?state=a%26b&src=android&src=ios#details")) + let rewritten = SafariService.websiteURL(original) + let components = try XCTUnwrap(URLComponents(url: rewritten, resolvingAgainstBaseURL: false)) + XCTAssertEqual(components.host, host) + XCTAssertEqual(components.path, path) + XCTAssertEqual(components.fragment, "details") + XCTAssertEqual(components.queryItems?.filter { $0.name == "src" }, [URLQueryItem(name: "src", value: "ios")]) + XCTAssertEqual(components.queryItems?.first { $0.name == "state" }?.value, "a&b") + XCTAssertEqual(SafariService.websiteURL(rewritten), rewritten) + } + } + XCTAssertEqual(SafariService.websiteURL(URL(string: "https://acode.app")!).query, "src=ios") + let encoded = "https://acode.app/login?code=a%2Bb&redirect=https%3A%2F%2Facode.app%2Fx%3Fkey%3Da%2Bb&flag&src=android#done" + XCTAssertEqual(SafariService.websiteURL(URL(string: encoded)!).absoluteString, + encoded.replacingOccurrences(of: "src=android", with: "src=ios")) + } + + func testOtherBrowserDestinationsRemainUnchanged() throws { + for value in ["https://example.com/?src=android", "https://acode.app.example.com/", "https://docs.acode.app/", + "https://acode.app:8443/", "https://user@acode.app/", "http://acode.app/", "mailto:acode@foxdebug.com"] { + let url = try XCTUnwrap(URL(string: value)) + XCTAssertEqual(SafariService.websiteURL(url), url) + } + } + + func testResetSettlesOpenCallbacksDuringPresentation() async throws { + let webView = try await appWebView() + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let controller = try XCTUnwrap(responder as? WebViewController) + let replies = WKWebView() + replies.loadHTMLString("<script>window.replies=[];window.iOS={callback:reply=>replies.push(reply)}</script>", baseURL: nil) + for _ in 0..<100 { + if (try? await replies.evaluateJavaScript("!!window.iOS")) as? Bool == true { break } + try await Task.sleep(for: .milliseconds(20)) + } + let service = SafariService(bridge: controller.bridge) + defer { service.reset() } + for (id, lifecycle) in [false, true].enumerated() { + service.exec(action: "open", args: ["https://example.test", ["reportLifecycle": lifecycle]], + callback: Callback(id: id, webView: replies)) + for _ in 0..<100 { + if controller.presentedViewController != nil { break } + try await Task.sleep(for: .milliseconds(10)) + } + XCTAssertNotNil(controller.presentedViewController) + service.reset() + for _ in 0..<100 { + if controller.presentedViewController == nil, + (try? await replies.evaluateJavaScript("replies.length")) as? Int == id + 1 { break } + try await Task.sleep(for: .milliseconds(20)) + } + } + let callbacks = try await replies.evaluateJavaScript("replies") as? [[String: Any]] + XCTAssertEqual(callbacks?.compactMap { $0["status"] as? Int }, [9, 9]) + XCTAssertTrue(callbacks?.allSatisfy { $0["keep"] as? Bool == false } == true) + } + + func testCustomTabsPresentSafariAndRejectInvalidSchemes() async throws { + let webView = try await appWebView() + let invalid = try await webView.callAsyncJavaScript(""" + for(const url of ['javascript:alert(1)', 'file:///etc/passwd', 'not a URL']) { + let rejected=false; + try { await new Promise((resolve,reject)=>CustomTabs.open(url,{},resolve,reject)); } + catch { rejected=true; } + if(!rejected) return false; + } + return true; + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(invalid, true) + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let controller = try XCTUnwrap(responder as? WebViewController) + XCTAssertNil(controller.presentedViewController, "Presentation already active: \(String(describing: controller.presentedViewController))") + let fixture = try HTTPFixture() + try await fixture.start() + defer { fixture.stop() } + _ = try await webView.callAsyncJavaScript("window.browserEvents=[]; await new Promise((resolve,reject)=>CustomTabs.open(url,{toolbarColor:'#123456',reportLifecycle:true},event=>{browserEvents.push(event.type);resolve();},reject));", arguments: ["url": fixture.origin], in: nil, contentWorld: .page) + let browser = try XCTUnwrap(controller.presentedViewController as? SFSafariViewController) + if #unavailable(iOS 26) { XCTAssertEqual(browser.preferredBarTintColor, UIColor(hexString: "#123456")) } + XCTAssertEqual(browser.dismissButtonStyle, .close) + XCTAssertEqual(browser.modalPresentationStyle, .fullScreen) + XCTAssertFalse(browser.configuration.barCollapsingEnabled) + let redirected = try XCTUnwrap(URL(string: "https://example.test/sign-in?state=a%26b&code=c%2Bd#finish")) + let activities = try XCTUnwrap(browser.delegate?.safariViewController?(browser, activityItemsFor: redirected, title: nil)) + let external = try XCTUnwrap(activities.first as? BrowserActivity) + XCTAssertEqual(external.url, redirected) + XCTAssertEqual(webView.url?.absoluteString, "acode://localhost/") + browser.delegate?.safariViewControllerDidFinish?(browser) + browser.delegate?.safariViewControllerDidFinish?(browser) + await withCheckedContinuation { continuation in browser.dismiss(animated: false) { continuation.resume() } } + let events = try await webView.callAsyncJavaScript("return window.browserEvents;", arguments: [:], in: nil, contentWorld: .page) as? [String] + XCTAssertEqual(events, ["opened", "closed"]) + _ = try await webView.callAsyncJavaScript("await new Promise((resolve,reject)=>CustomTabs.open(url,{authTabId:'active-auth',reportLifecycle:true},resolve,reject));", arguments: ["url": fixture.origin], in: nil, contentWorld: .page) + let reopened = try XCTUnwrap(controller.presentedViewController as? SFSafariViewController) + _ = try await webView.callAsyncJavaScript("await new Promise((resolve,reject)=>cordova.exec(resolve,reject,'CustomTabs','close',['old-auth']));", arguments: [:], in: nil, contentWorld: .page) + XCTAssertTrue(controller.presentedViewController === reopened) + _ = try await webView.callAsyncJavaScript("await new Promise((resolve,reject)=>cordova.exec(resolve,reject,'CustomTabs','close',['active-auth']));", arguments: [:], in: nil, contentWorld: .page) + XCTAssertNil(controller.presentedViewController) + _ = try await webView.callAsyncJavaScript("await new Promise((resolve,reject)=>CustomTabs.open(url,{},resolve,reject)); await new Promise((resolve,reject)=>cordova.exec(resolve,reject,'CustomTabs','close',['active-auth']));", arguments: ["url": fixture.origin], in: nil, contentWorld: .page) + let reading = try XCTUnwrap(controller.presentedViewController as? SFSafariViewController) + await withCheckedContinuation { continuation in reading.dismiss(animated: false) { continuation.resume() } } + } + + func testBrowserActionsPreserveSignInURLAndOnlyOfferInstalledBrowsers() throws { + let url = try XCTUnwrap(URL(string: "https://example.test/path?q=a%26b&state=c%2Bd&redirect_uri=https%3A%2F%2Facode.app%2Fcallback#finish")) + let available = BrowserActivity.available(for: url, canOpen: { _ in true }) + XCTAssertEqual(available.map(\.activityTitle), ["Open in Default Browser", "Open in Chrome", "Open in Firefox"]) + XCTAssertEqual(available[0].url, url) + XCTAssertEqual(available[1].url.absoluteString, url.absoluteString.replacingOccurrences(of: "https://", with: "googlechromes://")) + let firefox = try XCTUnwrap(URLComponents(url: available[2].url, resolvingAgainstBaseURL: false)) + XCTAssertEqual(firefox.queryItems?.first?.value, url.absoluteString) + XCTAssertEqual(BrowserActivity.available(for: url, canOpen: { _ in false }).map(\.activityTitle), ["Open in Default Browser"]) + XCTAssertEqual(BrowserActivity.available(for: url, canOpen: { $0.scheme == "firefox" }).map(\.activityTitle), ["Open in Default Browser", "Open in Firefox"]) + let http = try XCTUnwrap(URL(string: "http://example.test/path")) + XCTAssertEqual(BrowserActivity.available(for: http, canOpen: { _ in true })[1].url.scheme, "googlechrome") + XCTAssertTrue(BrowserActivity.available(for: URL(string: "javascript:alert(1)")!, canOpen: { _ in true }).isEmpty) + let declared = Bundle.main.object(forInfoDictionaryKey: "LSApplicationQueriesSchemes") as? [String] + XCTAssertTrue(["googlechrome", "googlechromes", "firefox"].allSatisfy { declared?.contains($0) == true }) + } +} diff --git a/platforms/ios/runnerTests/ConsoleObjectTests.swift b/platforms/ios/runnerTests/ConsoleObjectTests.swift new file mode 100644 index 0000000000..bc9777268f --- /dev/null +++ b/platforms/ios/runnerTests/ConsoleObjectTests.swift @@ -0,0 +1,57 @@ +import XCTest +import WebKit +@testable import runner + +extension PreviewBrowserTests { + func testStandaloneConsoleInspectsObjectsAndRecoversAfterCancellation() async throws { + let app = try await editorWebView() + var responder: UIResponder? = app + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let controller = try XCTUnwrap(responder as? WebViewController) + _ = try await app.evaluateJavaScript("acode.exec('console')") + let browser = try await presentedBrowser(controller) + defer { browser.dismiss(animated: false) } + try await waitForPage(browser.webView, expression: "Boolean(document.querySelector('#__c-input'))") + let result = try await browser.webView.callAsyncJavaScript(""" + const input=document.querySelector('#__c-input'); + const wait=async check=>{for(let n=0;n<100;n++){if(check())return;await new Promise(r=>setTimeout(r,20));}throw Error('Console command did not finish');}; + const submit=async code=>{ + console.clear();input.value=code; + input.dispatchEvent(new KeyboardEvent('keydown',{key:'Enter',bubbles:true,cancelable:true})); + await wait(()=>!input.disabled&&document.querySelector('c-message[log-level="log"],c-message[log-level="error"]')); + }; + await submit('({count:42,nested:{enabled:true}})'); + document.querySelector('c-message[log-level="log"] c-type').click(); + const row=[...document.querySelectorAll('c-line')].find(row=>row.firstElementChild?.textContent==='count:'); + const key=row.querySelector('c-key').getBoundingClientRect(),value=row.querySelector('c-text').getBoundingClientRect(); + const inline=Math.abs(key.top-value.top)<2&&value.left>=key.right; + const nested=[...document.querySelectorAll('c-line')].find(row=>row.firstElementChild?.textContent==='nested:'); + nested.querySelector('c-type').click(); + const expanded=nested.textContent.includes('enabled:')&&nested.textContent.includes('true'); + const hasContextSelector=!!document.querySelector('.__c-context'); + input.value='while(true){}'; + input.dispatchEvent(new KeyboardEvent('keydown',{key:'Enter',bubbles:true,cancelable:true})); + const stop=document.querySelector('[aria-label="Stop JavaScript execution"]'); + await wait(()=>input.disabled&&!stop.hidden); + stop.click(); + await wait(()=>!input.disabled); + await submit('21*2'); + const workerRecovered=document.querySelector('c-message[log-level="log"] c-text')?.textContent==='42'; + await submit('typeof window'); + const windowType=document.querySelector('c-message[log-level="log"] c-text')?.textContent; + const error=document.querySelector('c-message[log-level="error"]')?.textContent; + input.blur(); + return {inline,expanded,error:error||'',windowType,hasContextSelector,workerRecovered}; + """, arguments: [:], in: nil, contentWorld: .page) as? [String: Any] + XCTAssertEqual(result?["inline"] as? Bool, true, "Property keys and values must share a line") + XCTAssertEqual(result?["expanded"] as? Bool, true) + XCTAssertEqual(result?["error"] as? String, "") + XCTAssertEqual(result?["windowType"] as? String, "undefined") + XCTAssertEqual(result?["hasContextSelector"] as? Bool, false) + XCTAssertEqual(result?["workerRecovered"] as? Bool, true) + try await Task.sleep(for: .milliseconds(300)) + _ = try await browser.webView.evaluateJavaScript("document.querySelector('c-output').scrollTop=0") + try await Task.sleep(for: .milliseconds(200)) + attachScreenshot(browser, name: "console-worker-object") + } +} diff --git a/platforms/ios/runnerTests/DocumentsPickerTests.swift b/platforms/ios/runnerTests/DocumentsPickerTests.swift new file mode 100644 index 0000000000..6ff5146ee4 --- /dev/null +++ b/platforms/ios/runnerTests/DocumentsPickerTests.swift @@ -0,0 +1,120 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class DocumentsPickerTests: BridgeTestCase { + func testImageDocumentAndFolderResultsPreserveTheirContracts() async throws { + let webView = try await appWebView() + let host = try controller(webView) + let files = AppFiles.shared + let directory = files.documents.appendingPathComponent("picker-test-" + UUID().uuidString) + try files.manager.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? files.manager.removeItem(at: directory) } + let image = directory.appendingPathComponent("picked # 日本語.png") + let bytes = UIGraphicsImageRenderer(size: CGSize(width: 4, height: 4)).pngData { context in + UIColor.blue.setFill(); context.fill(CGRect(x: 0, y: 0, width: 4, height: 4)) + } + try bytes.write(to: image) + let roots = Set(files.allRoots().keys) + let bookmarks = Set((UserDefaults.standard.dictionary(forKey: "acode.folderBookmarks") ?? [:]).keys) + for action in ["get image", "get image", "open document file", "storage permission"] { + try await begin(webView, action: action) + let picker = try await presentedPicker(host) + XCTAssertFalse(picker.allowsMultipleSelection) + XCTAssertEqual(picker.documentPickerMode, .open) + let selected = action == "storage permission" ? directory : image + picker.delegate?.documentPicker?(picker, didPickDocumentsAt: [selected]) + await dismiss(picker) + let result = try await result(webView) + XCTAssertEqual(result["state"] as? String, "success") + if action == "open document file" { + let value = try XCTUnwrap(result["value"] as? [String: Any]) + XCTAssertEqual(value["filename"] as? String, image.lastPathComponent) + XCTAssertEqual(value["uri"] as? String, "file://" + image.path) + XCTAssertEqual(value["type"] as? String, "image/png") + XCTAssertEqual(value["length"] as? Int, bytes.count) + XCTAssertEqual(value["persistedUriPermission"] as? Bool, true) + } else { XCTAssertEqual(result["value"] as? String, "file://" + selected.path) } + } + XCTAssertEqual(Set(files.allRoots().keys), roots) + XCTAssertEqual(Set((UserDefaults.standard.dictionary(forKey: "acode.folderBookmarks") ?? [:]).keys), bookmarks) + } + + func testBusyPresentationCancellationAndReloadDoNotLeavePendingPickers() async throws { + let webView = try await appWebView() + let host = try controller(webView) + let modal = UIAlertController(title: "Picker fixture", message: nil, preferredStyle: .alert) + modal.addAction(UIAlertAction(title: "OK", style: .default)) + await withCheckedContinuation { continuation in host.present(modal, animated: false) { continuation.resume() } } + try await begin(webView, action: "get image") + let busy = try await result(webView) + XCTAssertEqual(busy["value"] as? String, "A document picker cannot be presented right now") + await dismiss(modal) + + try await begin(webView, action: "get image") + let oldPicker = try await presentedPicker(host) + let oldDelegate = oldPicker.delegate + try await begin(webView, action: "open document file", key: "secondPickerResult") + let concurrent = try await result(webView, key: "secondPickerResult") + XCTAssertEqual(concurrent["value"] as? String, "A document picker is already open") + webView.reload() + for _ in 0..<100 { + if host.presentedViewController == nil { break } + try await Task.sleep(for: .milliseconds(50)) + } + XCTAssertNil(host.presentedViewController) + XCTAssertNil(oldPicker.delegate) + let reloaded = try await appWebView() + try await begin(reloaded, action: "open document file") + let picker = try await presentedPicker(host) + oldDelegate?.documentPicker?(oldPicker, didPickDocumentsAt: [AppFiles.shared.documents]) + let pending = try await reloaded.evaluateJavaScript("window.pickerResult.state") as? String + XCTAssertEqual(pending, "pending") + picker.delegate?.documentPickerWasCancelled?(picker) + await dismiss(picker) + let cancelled = try await result(reloaded) + XCTAssertEqual(cancelled["value"] as? String, "Operation cancelled") + try await begin(reloaded, action: "get image") + let next = try await presentedPicker(host) + next.delegate?.documentPickerWasCancelled?(next) + await dismiss(next) + let nextResult = try await result(reloaded) + XCTAssertEqual(nextResult["state"] as? String, "error") + } + + private func controller(_ webView: WKWebView) throws -> WebViewController { + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + return try XCTUnwrap(responder as? WebViewController) + } + + private func begin(_ webView: WKWebView, action: String, key: String = "pickerResult") async throws { + _ = try await webView.callAsyncJavaScript(""" + window[key]={state:'pending'}; + Bridge.exec(value=>window[key]={state:'success',value},value=>window[key]={state:'error',value},'SDcard',action,[]); + """, arguments: ["action": action, "key": key], in: nil, contentWorld: .page) + } + + private func result(_ webView: WKWebView, key: String = "pickerResult") async throws -> [String: Any] { + let value = try await webView.callAsyncJavaScript(""" + for(let n=0;window[key].state==='pending'&&n<100;n++)await new Promise(r=>setTimeout(r,50)); + return window[key]; + """, arguments: ["key": key], in: nil, contentWorld: .page) + let result = try XCTUnwrap(value as? [String: Any]) + XCTAssertNotEqual(result["state"] as? String, "pending") + return result + } + + private func presentedPicker(_ host: UIViewController) async throws -> UIDocumentPickerViewController { + for _ in 0..<100 { + if let picker = host.presentedViewController as? UIDocumentPickerViewController, !picker.isBeingPresented { return picker } + try await Task.sleep(for: .milliseconds(50)) + } + throw NSError(domain: "AcodeTests", code: 1, userInfo: [NSLocalizedDescriptionKey: "Document picker not presented"]) + } + + private func dismiss(_ controller: UIViewController) async { + await withCheckedContinuation { continuation in controller.dismiss(animated: false) { continuation.resume() } } + } +} diff --git a/platforms/ios/runnerTests/FTPBridgeTests.swift b/platforms/ios/runnerTests/FTPBridgeTests.swift new file mode 100644 index 0000000000..882d724c7e --- /dev/null +++ b/platforms/ios/runnerTests/FTPBridgeTests.swift @@ -0,0 +1,80 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class FTPBridgeTests: BridgeTestCase { + func testPassiveTransfersAndCommands() async throws { try await exercise(mode: "passive") } + func testActiveTransfersAndCommands() async throws { try await exercise(mode: "active") } + + private func exercise(mode: String) async throws { + let fixture = try await SSHTestFixture.configuration() + let webView = try await appWebView() + let result = try await webView.callAsyncJavaScript(""" + const call=(action,args=[])=>new Promise((resolve,reject)=>Bridge.exec(resolve,error=>reject(Error(action+': '+JSON.stringify(error))),'Ftp',action,args)); + const options=['127.0.0.1',port,'fixture','fixture-password',mode,'ftp','utf8']; + const id=await call('connect',options); + const folder='/acode-'+Date.now(), local=Bridge.file.cacheDirectory+'ftp-fixture.bin'; + const check=(value,message)=>{if(!value) throw Error(message);}; + try { + check(id==='fixture@127.0.0.1:'+port,'Connection ID changed'); + check(await call('isConnected',[id])===1,'Not connected'); + check(await call('getWorkingDirectory',[id])==='/','Wrong home'); + check(await call('getKeepAlive',[id])===300,'Keepalive changed'); + await call('sendNoOp',[id]); + check((await call('execCommand',[id,'PWD'])).startsWith('257 '),'PWD reply lost'); + check((await call('execCommand',[id,'UNSUPPORTED'])).startsWith('500 '),'Raw error reply lost'); + const root=await call('listDirectory',[id,'/']); + check(root.some(x=>x.name==='.hidden'),'Hidden file omitted'); + const link=root.find(x=>x.name==='relative-link'); + check(link?.isLink && link.isFile && link.url==='/target.txt' && link.link==='target.txt','Relative link changed '+JSON.stringify(link)); + const broken=root.find(x=>x.name==='broken-link'); + check(broken?.isLink && !broken.isFile && !broken.isDirectory && broken.url==='/broken-link','Broken link changed'); + check((await call('listDirectory',[id,'/empty'])).length===0,'Empty listing failed'); + check((await call('getStat',[id,'/empty'])).isDirectory,'Empty directory stat failed'); + check((await call('getStat',[id,'/'])).isDirectory,'Root stat failed'); + check((await call('getStat',[id,'/relative-link'])).isLink,'Stat lost symbolic link'); + check(await call('exists',[id,'/missing'])===0,'Missing file exists'); + await call('createDirectory',[id,folder]); + await call('changeDirectory',[id,folder]); + check(await call('getWorkingDirectory',[id])===folder,'CWD lost'); + check(await call('connect',options)===id,'Reused connection changed ID'); + check(await call('getWorkingDirectory',[id])===folder,'Reused connection lost CWD'); + check((await call('execCommand',[id,'PWD'])).includes(folder),'Native CWD lost'); + const name='Acode ✓ 日本語 + #% file.txt'; + await call('createFile',[id,name]); + const entries=await call('listDirectory',[id,folder]); + check(entries.length===1 && entries[0].name===name && entries[0].length===0 && entries[0].isFile && entries[0].lastModified>0,'Listing changed '+JSON.stringify(entries)); + const bytes=new Uint8Array(350003).map((_,i)=>i%256); + const cache=await new Promise((resolve,reject)=>window.resolveLocalFileSystemURL(Bridge.file.cacheDirectory,resolve,reject)); + const entry=await new Promise((resolve,reject)=>cache.getFile('ftp-fixture.bin',{create:true},resolve,reject)); + await new Promise((resolve,reject)=>entry.createWriter(writer=>{writer.onwriteend=resolve;writer.onerror=reject;writer.write(new Blob([bytes]));},reject)); + await call('uploadFile',[id,local,name]); + const stat=await call('getStat',[id,name]); + check(stat.length===bytes.length && stat.isFile && stat.canRead && stat.canWrite && stat.lastModified>0,'Stat changed '+JSON.stringify(stat)); + check(await call('rename',[id,name,folder+'/renamed.bin'])===folder+'/renamed.bin','Rename reply changed'); + await call('downloadFile',[id,'renamed.bin',local]); + const downloaded=new Uint8Array(await (await fetch(entry.toInternalURL())).arrayBuffer()); + check(downloaded.length===bytes.length && downloaded.every((b,i)=>b===i%256),'Binary transfer corrupted'); + await call('changeToParentDirectory',[id]); + check(await call('getWorkingDirectory',[id])==='/','Parent directory lost'); + await call('createDirectory',[id,folder+'/nested']); + await call('createFile',[id,folder+'/nested/child']); + await call('deleteFile',[id,folder+'/renamed.bin']); + await call('deleteDirectory',[id,folder]); + check(await call('exists',[id,folder])===0,'Recursive deletion failed'); + try { await call('createDirectory',[id,'/bad\\r\\nDELE /target.txt']); throw Error('Command injection accepted'); } + catch(error) { if(error.message==='Command injection accepted') throw error; } + check(await call('exists',[id,'/target.txt'])===1,'Command injection deleted target'); + await call('disconnect',[id]); + await call('connect',options); + check(await call('isConnected',[id])===1,'Reconnect failed'); + return true; + } finally { + await call('disconnect',[id]); + try { const entry=await new Promise((resolve,reject)=>window.resolveLocalFileSystemURL(local,resolve,reject)); await new Promise((resolve,reject)=>entry.remove(resolve,reject)); } catch {} + } + """, arguments: ["port": fixture["ftpPort"]!, "mode": mode], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } +} diff --git a/platforms/ios/runnerTests/FTPTransferTests.swift b/platforms/ios/runnerTests/FTPTransferTests.swift new file mode 100644 index 0000000000..e0f3ceacf0 --- /dev/null +++ b/platforms/ios/runnerTests/FTPTransferTests.swift @@ -0,0 +1,98 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class FTPTransferTests: BridgeTestCase { + func testDisconnectDuringDownloadSettlesAndAllowsReconnect() async throws { + let fixture = try await SSHTestFixture.configuration() + for mode in ["passive", "active"] { + try await disconnectTransfer(port: fixture["ftpPort"] as! Int, mode: mode) + } + } + + func testDroppedConnectionsRejectTransfersAndAllowRecovery() async throws { + let fixture = try await SSHTestFixture.configuration() + let certificate = Data((fixture["ftpCertificate"] as! String).utf8) + try await Task.detached { + for security in ["ftp", "ftps", "implicit"] { + let port = security == "implicit" ? 990 : fixture[security == "ftp" ? "ftpPort" : "ftpsPort"] as! Int + let route = security == "implicit" ? "localhost:990:127.0.0.1:\(fixture["implicitFtpsPort"] as! Int)" : nil + for mode in ["passive", "active"] { + let profile = try FTPProfile(["localhost", port, "fixture", "fixture-password", mode, security == "ftp" ? "ftp" : "ftps"]) + let client = try FTPClient(profile, certificate: certificate, connectTo: route) + try client.connect() + let local = AppFiles.shared.cache.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: local) } + XCTAssertThrowsError(try client.download("/broken-transfer.bin", to: local.absoluteString)) + let partial = try Data(contentsOf: local) + XCTAssertGreaterThan(partial.count, 0) + XCTAssertLessThan(partial.count, 8_388_608) + XCTAssertEqual(partial, Data((0..<partial.count).map { UInt8($0 % 256) })) + try client.download("/target.txt", to: local.absoluteString) + XCTAssertEqual(try String(contentsOf: local, encoding: .utf8), "target") + try Data(repeating: 0xA5, count: 8_388_608).write(to: local) + XCTAssertThrowsError(try client.upload(local.absoluteString, to: "/broken-upload.bin")) + let size = try client.stat("/broken-upload.bin").size + XCTAssertGreaterThan(size, 0) + XCTAssertLessThan(size, 8_388_608) + let recovered = "/recovered-upload-" + UUID().uuidString + let bytes = Data("Recovered upload ✓".utf8) + try bytes.write(to: local) + try client.upload(local.absoluteString, to: recovered) + try Data().write(to: local) + try client.download(recovered, to: local.absoluteString) + XCTAssertEqual(try Data(contentsOf: local), bytes) + try client.command("DELE " + recovered) + try client.command("DELE /broken-upload.bin") + } + } + }.value + } + + private func disconnectTransfer(port: Int, mode: String) async throws { + let local = AppFiles.shared.cache.appendingPathComponent("interrupted-ftp-" + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: local) } + let id = "fixture@127.0.0.1:\(port)" + let webView = try await editorWebView() + addTeardownBlock { @MainActor in + _ = try? await webView.callAsyncJavaScript(""" + await new Promise(resolve=>Bridge.exec(resolve,resolve,'Ftp','disconnect',[id])); + delete window.interruptedFTPTransfer; + """, arguments: ["id": id], in: nil, contentWorld: .page) + } + _ = try await webView.callAsyncJavaScript(""" + const call=(action,args=[])=>new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'Ftp',action,args)); + await call('disconnect',[id]); + await call('connect',['127.0.0.1',port,'fixture','fixture-password',mode]); + window.interruptedFTPTransfer=call('downloadFile',[id,'/slow-transfer.bin',uri]).then(()=>({success:true}),error=>({error})); + return true; + """, arguments: ["id": id, "port": port, "mode": mode, "uri": local.absoluteString], in: nil, contentWorld: .page) + var length: UInt64 = 0 + for _ in 0..<100 { + length = (try? FileManager.default.attributesOfItem(atPath: local.path)[.size] as? NSNumber)?.uint64Value ?? 0 + if length > 0 { break } + try await Task.sleep(for: .milliseconds(50)) + } + XCTAssertGreaterThan(length, 0) + XCTAssertLessThan(length, 8_388_608) + let result = try await webView.callAsyncJavaScript(""" + const call=(action,args=[])=>new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'Ftp',action,args)); + let timer; + try { + const stopped=await Promise.race([ + Promise.all([call('disconnect',[id]),window.interruptedFTPTransfer]), + new Promise((resolve,reject)=>{timer=setTimeout(()=>reject(Error('Transfer did not stop after disconnect')),5000);}) + ]); + if(stopped[1].error!=='FTP operation cancelled')throw Error('Interrupted transfer did not report cancellation: '+JSON.stringify(stopped[1])); + await call('connect',['127.0.0.1',port,'fixture','fixture-password',mode]); + if(await call('isConnected',[id])!==1)throw Error('Reconnect failed'); + await call('downloadFile',[id,'/target.txt',uri]); + await call('disconnect',[id]); + return true; + } finally {clearTimeout(timer);delete window.interruptedFTPTransfer;} + """, arguments: ["id": id, "port": port, "mode": mode, "uri": local.absoluteString], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + XCTAssertEqual(try String(contentsOf: local, encoding: .utf8), "target") + } +} diff --git a/platforms/ios/runnerTests/FTPTransportTests.swift b/platforms/ios/runnerTests/FTPTransportTests.swift new file mode 100644 index 0000000000..e4691df89e --- /dev/null +++ b/platforms/ios/runnerTests/FTPTransportTests.swift @@ -0,0 +1,67 @@ +import XCTest +@testable import runner + +final class FTPTransportTests: XCTestCase { + func testFTPSVerifiesCertificateAndEncryptsActiveAndPassiveData() async throws { + let fixture = try await SSHTestFixture.configuration() + let certificate = Data((fixture["ftpCertificate"] as! String).utf8) + try await Task.detached { + for implicit in [false, true] { + let port = implicit ? 990 : fixture["ftpsPort"] as! Int + let route = implicit ? "localhost:990:127.0.0.1:\(fixture["implicitFtpsPort"] as! Int)" : nil + for mode in ["passive", "active"] { + let profile = try FTPProfile(["localhost", port, "fixture", "fixture-password", mode, "ftps"]) + let client = try FTPClient(profile, certificate: certificate, connectTo: route) + try client.connect() + XCTAssertEqual(client.directory, "/") + XCTAssertTrue(try client.list("/").contains { $0["name"] as? String == ".hidden" }) + let local = AppFiles.shared.cache.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: local) } + let data = Data((0..<350003).map { UInt8($0 % 256) }) + try data.write(to: local) + let remote = "/tls-" + UUID().uuidString + try client.upload(local.absoluteString, to: remote) + try Data().write(to: local) + try client.download(remote, to: local.absoluteString) + XCTAssertEqual(try Data(contentsOf: local), data) + try client.command("DELE " + remote) + } + } + }.value + } + + func testFTPSRejectsUntrustedCertificateAndWrongHostname() async throws { + let fixture = try await SSHTestFixture.configuration() + let certificate = Data((fixture["ftpCertificate"] as! String).utf8) + try await Task.detached { + for implicit in [false, true] { + let port = implicit ? 990 : fixture["ftpsPort"] as! Int + let route = implicit ? ":990:127.0.0.1:\(fixture["implicitFtpsPort"] as! Int)" : nil + let untrusted = try FTPClient(FTPProfile(["localhost", port, "fixture", "fixture-password", "passive", "ftps"]), connectTo: route) + XCTAssertThrowsError(try untrusted.connect()) { error in + XCTAssertTrue(error.localizedDescription.lowercased().contains("certificate"), error.localizedDescription) + } + let mismatch = try FTPClient(FTPProfile(["127.0.0.1", port, "fixture", "fixture-password", "passive", "ftps"]), certificate: certificate, connectTo: route) + XCTAssertThrowsError(try mismatch.connect()) { error in + XCTAssertTrue(error.localizedDescription.lowercased().contains("certificate"), error.localizedDescription) + } + } + }.value + } + + func testCancelledHandshakeStopsAndInvalidPasswordFails() async throws { + let fixture = try await SSHTestFixture.configuration() + let port = fixture["ftpPort"] as! Int + let silentPort = fixture["silentPort"] as! Int + let client = try FTPClient(FTPProfile(["127.0.0.1", silentPort, "fixture", "fixture-password"])) + let pending = Task.detached { try client.connect() } + try await Task.sleep(for: .milliseconds(100)) + client.cancellation.cancel() + do { try await pending.value; XCTFail("Cancelled connection succeeded") } + catch { XCTAssertEqual(error.localizedDescription, "FTP operation cancelled") } + try await Task.detached { + let invalid = try FTPClient(FTPProfile(["127.0.0.1", port, "fixture", "wrong-password"])) + XCTAssertThrowsError(try invalid.connect()) + }.value + } +} diff --git a/platforms/ios/runnerTests/FileContentsTests.swift b/platforms/ios/runnerTests/FileContentsTests.swift new file mode 100644 index 0000000000..3bbcacaa83 --- /dev/null +++ b/platforms/ios/runnerTests/FileContentsTests.swift @@ -0,0 +1,93 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class FileContentsTests: BridgeTestCase { + func testNativeReadRangesAndBinaryRepresentationsMatchBytes() async throws { + let app = try await editorWebView() + let file = AppFiles.shared.cache.appendingPathComponent("ios-read-ranges-" + UUID().uuidString + ".bin") + try Data((0..<768).map { UInt8($0 % 256) }).write(to: file) + defer { try? FileManager.default.removeItem(at: file) } + let result = try await app.callAsyncJavaScript(""" + const call=(action,args)=>new Promise((resolve,reject)=>Bridge.exec(resolve,error=>reject(Error(action+': '+JSON.stringify(error))),'File',action,args)); + for(const [start,end] of [[0,-1],[3,-1],[3,9],[250,2147483647],[300,100],[900,1000]]) { + const expected=Array.from({length:768},(_,index)=>index%256).slice(start,end<0?768:Math.max(start,end)); + for(const action of ['readAsArrayBuffer','readAsBinaryString','readAsDataURL']) { + const value=await call(action,[uri,start,end]); + const bytes=action==='readAsArrayBuffer'?[...new Uint8Array(value)]:Array.from(action==='readAsDataURL'?atob(value.split(',')[1]):value,char=>char.charCodeAt(0)); + if(bytes.join(',')!==expected.join(','))throw Error(action+' range '+start+','+end+' changed bytes: '+bytes.length); + } + } + await call('write',[uri,'plain text',0,false]); + if(await call('readAsText',[uri,'UTF-8',6,-1])!=='text')throw Error('Open-ended text read failed'); + return true; + """, arguments: ["uri": file.absoluteString], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + func testPublicBinaryReadersPreserveSlicesAcrossNativeChunks() async throws { + let app = try await editorWebView() + let file = AppFiles.shared.cache.appendingPathComponent("ios-read-chunks-" + UUID().uuidString + ".bin") + let count = 524_291 + try Data((0..<count).map { UInt8($0 % 256) }).write(to: file) + defer { try? FileManager.default.removeItem(at: file) } + let result = try await app.callAsyncJavaScript(""" + const entry=await new Promise((resolve,reject)=>resolveLocalFileSystemURI(uri,resolve,reject)); + const file=await new Promise((resolve,reject)=>entry.file(resolve,reject)); + for(const action of ['readAsArrayBuffer','readAsBinaryString','readAsDataURL']) { + const reader=new FileReader(); + const value=await new Promise((resolve,reject)=>{ + reader.onload=()=>resolve(reader.result); + reader.onerror=()=>reject(Error(action+': '+reader.error?.code)); + reader[action](file.slice(1,-1)); + }); + const bytes=action==='readAsArrayBuffer'?new Uint8Array(value):Array.from(action==='readAsDataURL'?atob(value.split(',')[1]):value,char=>char.charCodeAt(0)); + if(bytes.length!==count-2||bytes.some((byte,index)=>byte!==(index+1)%256))throw Error(action+' changed chunked bytes'); + if(reader.readyState!==FileReader.DONE)throw Error('Reader did not finish'); + } + return true; + """, arguments: ["uri": file.absoluteString, "count": count], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + func testNegativeTruncateRejectsWithoutErasingTheFileAndWriterRecovers() async throws { + let app = try await editorWebView() + let file = AppFiles.shared.cache.appendingPathComponent("ios-truncate-" + UUID().uuidString + ".txt") + try Data("retain".utf8).write(to: file) + defer { try? FileManager.default.removeItem(at: file) } + let result = try await app.callAsyncJavaScript(""" + const entry=await new Promise((resolve,reject)=>resolveLocalFileSystemURI(uri,resolve,reject)); + const writer=await new Promise((resolve,reject)=>entry.createWriter(resolve,reject)); + const events=[]; + writer.onwritestart=()=>events.push('start');writer.onwrite=()=>events.push('write');writer.onerror=()=>events.push('error'); + await new Promise(resolve=>{writer.onwriteend=resolve;writer.truncate(-1);}); + if(writer.error?.code!==1000||events.join(',')!=='start,error'||writer.length!==6)throw Error('Negative truncate did not reject safely: '+JSON.stringify({events,error:writer.error,length:writer.length})); + const text=await new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'File','readAsText',[uri,'UTF-8',0,99])); + if(text!=='retain')throw Error('Negative truncate erased contents'); + await new Promise((resolve,reject)=>{writer.onwriteend=resolve;writer.onerror=reject;writer.truncate(3);}); + if(writer.length!==3||writer.readyState!==FileWriter.DONE)throw Error('Writer did not recover'); + return true; + """, arguments: ["uri": file.absoluteString], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + XCTAssertEqual(try String(contentsOf: file, encoding: .utf8), "ret") + } + + func testWriteOffsetsClampAtEndAndTruncationDoesNotGrowTheFile() async throws { + let app = try await editorWebView() + let file = AppFiles.shared.cache.appendingPathComponent("ios-write-offsets-" + UUID().uuidString + ".txt") + try Data("abc".utf8).write(to: file) + defer { try? FileManager.default.removeItem(at: file) } + let result = try await app.callAsyncJavaScript(""" + const call=(action,args)=>new Promise((resolve,reject)=>Bridge.exec(resolve,error=>reject(Error(action+': '+JSON.stringify(error))),'File',action,args)); + if(await call('write',[uri,'Z',100,false])!==1)throw Error('Write count changed'); + if(await call('readAsText',[uri,'UTF-8',0,999])!=='abcZ')throw Error('Write added a gap beyond EOF'); + if(await call('truncate',[uri,99])!==4)throw Error('Truncate grew the file'); + await call('write',[uri,'X',1,false]); + if(await call('readAsText',[uri,'UTF-8',0,999])!=='aX')throw Error('Write retained the old tail'); + return true; + """, arguments: ["uri": file.absoluteString], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + XCTAssertEqual(try String(contentsOf: file, encoding: .utf8), "aX") + } +} diff --git a/platforms/ios/runnerTests/FileEntryTests.swift b/platforms/ios/runnerTests/FileEntryTests.swift new file mode 100644 index 0000000000..ec858a81b1 --- /dev/null +++ b/platforms/ios/runnerTests/FileEntryTests.swift @@ -0,0 +1,87 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class FileEntryTests: BridgeTestCase { + func testFilesystemRequestsCheckCapacityAndRootsReturnThemselvesAsParent() async throws { + let app = try await editorWebView() + let result = try await app.callAsyncJavaScript(""" + const roots=[]; + for(const type of [0,1]) { + roots.push((await new Promise((resolve,reject)=>requestFileSystem(type,1,resolve,reject))).root); + const code=await new Promise(resolve=>requestFileSystem(type,Number.MAX_SAFE_INTEGER,()=>resolve(null),error=>resolve(error.code))); + if(code!==FileError.QUOTA_EXCEEDED_ERR)throw Error('Filesystem capacity request was ignored: '+code); + } + for(const key of ['applicationDirectory','dataDirectory','cacheDirectory']) roots.push(await new Promise((resolve,reject)=>resolveLocalFileSystemURI(Bridge.file[key],resolve,reject))); + for(const root of roots) { + const parent=await new Promise((resolve,reject)=>root.getParent(resolve,error=>reject(Error(root.filesystem.name+': '+error.code)))); + if(parent.fullPath!=='/'||parent.nativeURL!==root.nativeURL||!parent.isDirectory)throw Error('Filesystem root escaped to a parent: '+root.filesystem.name); + } + return true; + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + func testAbsoluteAndRelativeChildPathsStayWithinTheirFilesystem() async throws { + let app = try await editorWebView() + let directory = AppFiles.shared.cache.appendingPathComponent("ios-entry-paths-" + UUID().uuidString) + let nested = directory.appendingPathComponent("nested") + let file = directory.appendingPathComponent("target # ? 日本語.txt") + try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: true) + try Data("path content".utf8).write(to: file) + defer { try? FileManager.default.removeItem(at: directory) } + let result = try await app.callAsyncJavaScript(""" + const parent=await new Promise((resolve,reject)=>resolveLocalFileSystemURI(uri,resolve,reject)); + const get=(entry,action,path)=>new Promise((resolve,reject)=>entry[action](path,{},resolve,error=>reject(Error(action+' '+path+': '+error.code)))); + for(const path of ['/'+fixture+'/'+name,'../'+name,'./../'+name]) { + const entry=await get(parent,'getFile',path); + if(entry.name!==name||entry.nativeURL!==expected)throw Error('Wrong file entry: '+path); + if(await fetch(entry.toInternalURL()).then(response=>response.text())!=='path content')throw Error('Wrong internal URL: '+path); + } + const root=await get(parent,'getDirectory','/'); + for(const path of ['..','../../','/../']) { + const entry=await get(root,'getDirectory',path); + if(entry.fullPath!=='/'||entry.nativeURL!==root.nativeURL)throw Error('Parent traversal escaped the filesystem: '+path); + } + const current=await get(parent,'getDirectory','.'); + if(current.nativeURL!==parent.nativeURL)throw Error('Current directory changed'); + return true; + """, arguments: ["uri": nested.absoluteString, "fixture": directory.lastPathComponent, "name": file.lastPathComponent, "expected": file.absoluteString], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + func testCreationFlagsTypeChecksAndInvalidNamesPreserveExistingFiles() async throws { + let app = try await editorWebView() + let directory = AppFiles.shared.cache.appendingPathComponent("ios-entry-flags-" + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let file = directory.appendingPathComponent("retain.txt") + try Data("retain contents".utf8).write(to: file) + defer { try? FileManager.default.removeItem(at: directory) } + let result = try await app.callAsyncJavaScript(""" + const parent=await new Promise((resolve,reject)=>resolveLocalFileSystemURI(uri,resolve,reject)); + const get=(action,path,options)=>new Promise((resolve,reject)=>parent[action](path,options,resolve,reject)); + for(const [action,path,options,code] of [ + ['getFile','retain.txt',{create:true,exclusive:true},12], + ['getDirectory','retain.txt',{},11], + ['getFile','.',{},11], + ['getFile','missing.txt',{},1], + ['getFile','invalid:name.txt',{create:true},5] + ]) { + const error=await get(action,path,options).then(()=>null,error=>error.code); + if(error!==code)throw Error(action+' '+path+': expected '+code+', received '+error); + } + const file=await get('getFile','retain.txt',{create:false,exclusive:true}); + for(const action of ['copyTo','moveTo']) { + const code=await new Promise(resolve=>file[action](parent,'invalid:name.txt',()=>resolve(null),error=>resolve(error.code))); + if(code!==5)throw Error(action+' accepted an invalid name: '+code); + } + await get('getFile','created.txt',{create:true,exclusive:true}); + await get('getDirectory','created-folder',{create:true,exclusive:true}); + return true; + """, arguments: ["uri": directory.absoluteString], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + XCTAssertEqual(try String(contentsOf: file, encoding: .utf8), "retain contents") + XCTAssertEqual(Set(try FileManager.default.contentsOfDirectory(atPath: directory.path)), ["retain.txt", "created.txt", "created-folder"]) + } +} diff --git a/platforms/ios/runnerTests/FileRootHistoryTests.swift b/platforms/ios/runnerTests/FileRootHistoryTests.swift new file mode 100644 index 0000000000..bfb22bb356 --- /dev/null +++ b/platforms/ios/runnerTests/FileRootHistoryTests.swift @@ -0,0 +1,53 @@ +import XCTest +@testable import runner + +final class FileRootHistoryTests: XCTestCase { + func testOldPathsFollowTheirAuthorizedRootAcrossSeveralInstalls() throws { + let suite = "app.acode.file-roots-test." + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let original = URL(fileURLWithPath: "/previous-container/Documents") + let middle = URL(fileURLWithPath: "/next-container/Documents") + let current = AppFiles.shared.documents + let filename = "relocation-" + UUID().uuidString + " # 日本語.txt" + let file = current.appendingPathComponent(filename) + try Data([0, 128, 255]).write(to: file) + defer { try? FileManager.default.removeItem(at: file) } + FileRootHistory(defaults: defaults).update(["persistent": original]) + FileRootHistory(defaults: defaults).update(["persistent": middle]) + let history = FileRootHistory(defaults: defaults) + let roots = ["persistent": current] + history.update(roots) + for root in [original, middle, current] { + let resolved = history.resolve(root.appendingPathComponent(filename), roots: roots) + XCTAssertEqual(try Data(contentsOf: resolved), Data([0, 128, 255])) + } + let outside = URL(fileURLWithPath: original.path + "-other/private.txt") + XCTAssertEqual(history.resolve(outside, roots: roots), outside) + let traversal = original.appendingPathComponent("../../private.txt") + XCTAssertThrowsError(try AppFiles.shared.resolve(history.resolve(traversal, roots: roots).absoluteString)) + } + + func testRevokedRootsAreNotReauthorizedAndNestedRootsUseTheClosestGrant() throws { + let suite = "app.acode.file-roots-test." + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let parent = URL(fileURLWithPath: "/old-provider/projects") + let nested = parent.appendingPathComponent("nested") + let history = FileRootHistory(defaults: defaults) + history.update(["provider": parent, "nested": nested]) + let roots = ["provider": URL(fileURLWithPath: "/new-provider/projects"), + "nested": URL(fileURLWithPath: "/another-provider/nested")] + history.update(roots) + let old = nested.appendingPathComponent("index.html") + XCTAssertEqual(history.resolve(old, roots: roots), roots["nested"]!.appendingPathComponent("index.html")) + XCTAssertEqual(history.resolve(old, roots: [:]), old) + XCTAssertTrue(history.replacements(roots: [:]).isEmpty) + let pairs = history.replacements(roots: roots) + XCTAssertEqual(pairs.first?["from"], nested.absoluteString) + XCTAssertEqual(pairs.first?["to"], roots["nested"]?.absoluteString) + let stillAuthorized = ["provider": parent, "nested": roots["nested"]!] + XCTAssertEqual(history.resolve(old, roots: stillAuthorized), old) + XCTAssertFalse(history.replacements(roots: stillAuthorized).contains { $0["from"] == nested.absoluteString }) + } +} diff --git a/platforms/ios/runnerTests/FileServiceTests.swift b/platforms/ios/runnerTests/FileServiceTests.swift new file mode 100644 index 0000000000..07fedf527f --- /dev/null +++ b/platforms/ios/runnerTests/FileServiceTests.swift @@ -0,0 +1,50 @@ +import XCTest +@testable import runner + +final class FileServiceTests: XCTestCase { + private let files = AppFiles.shared + private var directory: URL! + + override func setUpWithError() throws { + directory = files.cache.appendingPathComponent("ios-port-test-" + UUID().uuidString, isDirectory: true) + try files.manager.createDirectory(at: directory, withIntermediateDirectories: true) + } + + override func tearDownWithError() throws { + if let directory { try files.manager.removeItem(at: directory) } + } + + func testFileURLsRoundTripSpacesUnicodeAndFragments() throws { + let url = directory.appendingPathComponent("test # 日本語.txt") + try Data("hello ✓".utf8).write(to: url) + let entry = try files.entry(url) + let name = try XCTUnwrap(entry["filesystemName"] as? String) + let path = try XCTUnwrap(entry["fullPath"] as? String) + var components = URLComponents() + components.scheme = "acode" + components.host = "localhost" + components.path = "/__cdvfile_\(name)__" + path + let resolved = try files.resolve(XCTUnwrap(components.url?.absoluteString)) + XCTAssertEqual(resolved, url.standardizedFileURL.resolvingSymlinksInPath()) + XCTAssertEqual(try files.coordinate(resolved) { try String(contentsOf: $0, encoding: .utf8) }, "hello ✓") + XCTAssertEqual(try files.metadata(resolved)["size"] as? Int, Data("hello ✓".utf8).count) + } + + func testTraversalAndSymlinksCannotReadOutsideAuthorizedRoots() throws { + XCTAssertThrowsError(try files.resolve("acode://localhost/__cdvfile_cache__/../../../../etc/passwd")) + let link = directory.appendingPathComponent("outside") + try files.manager.createSymbolicLink(at: link, withDestinationURL: URL(fileURLWithPath: "/etc")) + XCTAssertThrowsError(try files.resolve(link.appendingPathComponent("passwd").absoluteString)) + XCTAssertThrowsError(try files.resolve("https://example.com/file")) + } + + func testEncodingsRoundTripAndIncludeUTF8() throws { + XCTAssertNotNil(FileContents.availableEncodings()["UTF-8"]) + for name in ["UTF-8", "UTF-16LE", "UTF-16BE", "UTF-32"] { + let encoding = try FileContents.encoding(name) + let bytes = try XCTUnwrap("Acode 日本語 ✓".data(using: encoding)) + XCTAssertEqual(String(data: bytes, encoding: encoding), "Acode 日本語 ✓") + } + XCTAssertThrowsError(try FileContents.encoding("not-an-encoding")) + } +} diff --git a/platforms/ios/runnerTests/FileSymlinkTests.swift b/platforms/ios/runnerTests/FileSymlinkTests.swift new file mode 100644 index 0000000000..2ac910e74b --- /dev/null +++ b/platforms/ios/runnerTests/FileSymlinkTests.swift @@ -0,0 +1,118 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class FileSymlinkTests: BridgeTestCase { + func testRemovingLinksThroughNativeAndPublicFileAPIsPreservesTargets() async throws { + let app = try await editorWebView() + let files = AppFiles.shared + let directory = files.cache.appendingPathComponent("ios-links-" + UUID().uuidString) + try files.manager.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? files.manager.removeItem(at: directory) } + let target = directory.appendingPathComponent("target.txt") + let link = directory.appendingPathComponent("alias # 日本語.txt") + let bytes = Data("retain target contents".utf8) + for route in ["native", "resolve", "child", "listing"] { + try bytes.write(to: target) + try files.manager.createSymbolicLink(atPath: link.path, withDestinationPath: target.lastPathComponent) + _ = try await app.callAsyncJavaScript(""" + const call=(action,args)=>new Promise((resolve,reject)=>Bridge.exec(resolve,error=>reject(Error(action+': '+JSON.stringify(error))),'File',action,args)); + if(route==='native') return await call('remove',[uri]); + const resolve=uri=>new Promise((resolve,reject)=>resolveLocalFileSystemURI(uri,resolve,reject)); + const folder=await resolve(root); + let entry; + if(route==='resolve') entry=await resolve(uri); + else if(route==='child') entry=await new Promise((resolve,reject)=>folder.getFile(name,{},resolve,reject)); + else entry=(await new Promise((resolve,reject)=>folder.createReader().readEntries(resolve,reject))).find(entry=>entry.name===name); + if(!entry||entry.name!==name||entry.nativeURL!==uri)throw Error('Link identity changed: '+route); + if(!decodeURIComponent(new URL(entry.toInternalURL()).pathname).endsWith('/'+name))throw Error('Internal URL points at target: '+route); + const metadata=await new Promise((resolve,reject)=>entry.file(resolve,reject)); + if(metadata.name!==name||metadata.size!==22)throw Error('Link metadata changed: '+route); + const text=await fetch(entry.toInternalURL()).then(response=>response.text()); + if(text!=='retain target contents')throw Error('Link read failed: '+route); + await new Promise((resolve,reject)=>entry.remove(resolve,reject)); + return true; + """, arguments: ["route": route, "root": directory.absoluteString, "uri": link.absoluteString, "name": link.lastPathComponent], in: nil, contentWorld: .page) + XCTAssertEqual(try Data(contentsOf: target), bytes, route) + XCTAssertThrowsError(try files.manager.destinationOfSymbolicLink(atPath: link.path), route) + } + } + + func testMovingAndRecursivelyRemovingLinksLeaveTargetsIntact() async throws { + let app = try await editorWebView() + let files = AppFiles.shared + let directory = files.cache.appendingPathComponent("ios-link-moves-" + UUID().uuidString) + let target = directory.appendingPathComponent("target", isDirectory: true) + try files.manager.createDirectory(at: target, withIntermediateDirectories: true) + defer { try? files.manager.removeItem(at: directory) } + let content = target.appendingPathComponent("retain.txt") + try Data("retain directory contents".utf8).write(to: content) + let link = directory.appendingPathComponent("alias") + try files.manager.createSymbolicLink(atPath: link.path, withDestinationPath: target.lastPathComponent) + let moved = directory.appendingPathComponent("renamed") + _ = try await app.callAsyncJavaScript(""" + const call=(action,args)=>new Promise((resolve,reject)=>Bridge.exec(resolve,error=>reject(Error(action+': '+JSON.stringify(error))),'File',action,args)); + const entry=await call('moveTo',[uri,root,'renamed']); + if(entry.name!=='renamed')throw Error('Moved link name changed'); + return true; + """, arguments: ["root": directory.absoluteString, "uri": link.absoluteString], in: nil, contentWorld: .page) + XCTAssertEqual(try files.manager.destinationOfSymbolicLink(atPath: moved.path), target.lastPathComponent) + XCTAssertEqual(try String(contentsOf: content, encoding: .utf8), "retain directory contents") + let existing = directory.appendingPathComponent("existing") + try files.manager.createSymbolicLink(atPath: existing.path, withDestinationPath: target.lastPathComponent) + _ = try await app.callAsyncJavaScript(""" + for(const action of ['moveTo','copyTo']) { + const error=await new Promise(resolve=>Bridge.exec(()=>resolve(null),resolve,'File',action,[uri,root,'existing'])); + if(error!==12)throw Error('Destination link was not protected: '+action+' '+error); + } + return true; + """, arguments: ["root": directory.absoluteString, "uri": moved.absoluteString], in: nil, contentWorld: .page) + XCTAssertEqual(try files.manager.destinationOfSymbolicLink(atPath: moved.path), target.lastPathComponent) + XCTAssertEqual(try files.manager.destinationOfSymbolicLink(atPath: existing.path), target.lastPathComponent) + _ = try await app.callAsyncJavaScript(""" + return await new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'File','removeRecursively',[uri])); + """, arguments: ["uri": moved.absoluteString], in: nil, contentWorld: .page) + XCTAssertThrowsError(try files.manager.destinationOfSymbolicLink(atPath: moved.path)) + XCTAssertEqual(try String(contentsOf: content, encoding: .utf8), "retain directory contents") + let destination = directory.appendingPathComponent("destination", isDirectory: true) + try files.manager.createDirectory(at: destination, withIntermediateDirectories: false) + _ = try await app.callAsyncJavaScript(""" + const call=(action,args)=>new Promise((resolve,reject)=>Bridge.exec(resolve,error=>reject(Error(action+': '+JSON.stringify(error))),'File',action,args)); + const entry=await call('moveTo',[uri,root,'relative-link']); + if(entry.name!=='relative-link')throw Error('Moved relative link name changed'); + const listed=await call('readEntries',[root]); + if(listed.length!==1||listed[0].name!=='relative-link')throw Error('Dangling link disappeared from listing'); + await call('remove',[entry.nativeURL]); + return true; + """, arguments: ["root": destination.absoluteString, "uri": existing.absoluteString], in: nil, contentWorld: .page) + XCTAssertEqual(try files.manager.contentsOfDirectory(atPath: destination.path), []) + XCTAssertEqual(try String(contentsOf: content, encoding: .utf8), "retain directory contents") + } + + func testUnauthorizedLinkTargetsRemainUnreadableButTheLinkCanBeRemoved() async throws { + let app = try await editorWebView() + let files = AppFiles.shared + let identifier = UUID().uuidString + let target = files.data.deletingLastPathComponent().appendingPathComponent("ungranted-" + identifier) + let link = files.cache.appendingPathComponent("ungranted-link-" + identifier) + let bytes = Data("ungranted fixture".utf8) + try bytes.write(to: target) + defer { + try? files.manager.removeItem(at: link) + try? files.manager.removeItem(at: target) + } + try files.manager.createSymbolicLink(at: link, withDestinationURL: target) + XCTAssertThrowsError(try files.resolve(target.absoluteString)) + _ = try await app.callAsyncJavaScript(""" + for(const action of ['resolveLocalFileSystemURI','getFileMetadata','readAsText']) { + const error=await new Promise(resolve=>Bridge.exec(()=>resolve(null),resolve,'File',action,[uri,'UTF-8',0,100])); + if(error!==2)throw Error('Unauthorized link access: '+action+' '+error); + } + await new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'File','remove',[uri])); + return true; + """, arguments: ["uri": link.absoluteString], in: nil, contentWorld: .page) + XCTAssertThrowsError(try files.manager.destinationOfSymbolicLink(atPath: link.path)) + XCTAssertEqual(try Data(contentsOf: target), bytes) + } +} diff --git a/platforms/ios/runnerTests/FileTransferTests.swift b/platforms/ios/runnerTests/FileTransferTests.swift new file mode 100644 index 0000000000..7c7768e20a --- /dev/null +++ b/platforms/ios/runnerTests/FileTransferTests.swift @@ -0,0 +1,112 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class FileTransferTests: BridgeTestCase { + func testFileEntriesReplaceExistingFilesAndEmptyDirectories() async throws { + let app = try await editorWebView() + let manager = FileManager.default + let root = AppFiles.shared.cache.appendingPathComponent("ios-transfer-" + UUID().uuidString) + try manager.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? manager.removeItem(at: root) } + let bytes = Data((0..<2_000_000).map { UInt8($0 % 256) }) + for action in ["copyTo", "moveTo"] { + for directory in [false, true] { + let container = root.appendingPathComponent(action + (directory ? "-directory" : "-file")) + let source = container.appendingPathComponent("source/entry # 日本語") + let destination = container.appendingPathComponent("destination", isDirectory: true) + let target = destination.appendingPathComponent(source.lastPathComponent) + try manager.createDirectory(at: source.deletingLastPathComponent(), withIntermediateDirectories: true) + try manager.createDirectory(at: destination, withIntermediateDirectories: true) + if directory { + try manager.createDirectory(at: source.appendingPathComponent("empty"), withIntermediateDirectories: true) + try bytes.write(to: source.appendingPathComponent("bytes.bin")) + try manager.createDirectory(at: target, withIntermediateDirectories: false) + } else { + try bytes.write(to: source) + try Data("replace old contents".utf8).write(to: target) + } + let uri = try await app.callAsyncJavaScript(""" + let watch,timer; + const changed=action==='moveTo'?new Promise((resolve,reject)=>{ + watch=sdcard.watchFile(nativeSource,()=>resolve(),reject); + timer=setTimeout(()=>reject(Error('Move did not notify the file watcher')),5000); + }):Promise.resolve(); + try { + const resolve=uri=>new Promise((resolve,reject)=>resolveLocalFileSystemURI(uri,resolve,reject)); + const entry=await resolve(nativeSource), parent=await resolve(destination); + const result=await new Promise((resolve,reject)=>entry[action](parent,entry.name,resolve,reject)); + if(result.isDirectory!==directory)throw Error('Transfer result type changed'); + await changed;return result.nativeURL; + } + catch(error){throw Error(action+': '+JSON.stringify(error)+' '+error?.message);} + finally{clearTimeout(timer);watch?.unwatch();} + """, arguments: ["nativeSource": source.absoluteString, "destination": destination.absoluteString, "action": action, "directory": directory], in: nil, contentWorld: .page) as? String + XCTAssertEqual(URL(string: try XCTUnwrap(uri))?.path, target.path) + XCTAssertEqual(try Data(contentsOf: directory ? target.appendingPathComponent("bytes.bin") : target), bytes) + if directory { XCTAssertEqual(try manager.contentsOfDirectory(atPath: target.appendingPathComponent("empty").path), []) } + XCTAssertEqual(manager.fileExists(atPath: source.path), action == "copyTo") + XCTAssertEqual(try manager.contentsOfDirectory(atPath: destination.path), [source.lastPathComponent]) + } + } + } + + func testRejectedTransfersPreserveSourceAndDestinationContents() async throws { + let app = try await editorWebView() + let files = AppFiles.shared + let root = files.cache.appendingPathComponent("ios-transfer-failure-" + UUID().uuidString) + let source = root.appendingPathComponent("source") + let target = root.appendingPathComponent("target") + try files.manager.createDirectory(at: source, withIntermediateDirectories: true) + try files.manager.createDirectory(at: target, withIntermediateDirectories: true) + defer { try? files.manager.removeItem(at: root) } + let sourceFile = source.appendingPathComponent("retain.txt") + let targetFile = target.appendingPathComponent("retain.txt") + try Data("source retained".utf8).write(to: sourceFile) + try Data("target retained".utf8).write(to: targetFile) + _ = try await app.callAsyncJavaScript(""" + const reject=async(action,source,parent,name,code)=>{ + const error=await new Promise(resolve=>Bridge.exec(()=>resolve(null),resolve,'File',action,[source,parent,name])); + if(error!==code)throw Error(action+' '+name+': expected '+code+', received '+error); + }; + for(const action of ['copyTo','moveTo']) { + await reject(action,file,source,'retain.txt',9); + await reject(action,source,source,'nested',9); + await reject(action,source,root,'target',9); + await reject(action,file,root,'target',9); + await reject(action,source,target,'retain.txt',9); + await reject(action,missing,target,'retain.txt',1); + } + return true; + """, arguments: ["root": root.absoluteString, "source": source.absoluteString, "target": target.absoluteString, "file": sourceFile.absoluteString, "missing": root.appendingPathComponent("missing").absoluteString], in: nil, contentWorld: .page) + XCTAssertEqual(try String(contentsOf: sourceFile, encoding: .utf8), "source retained") + XCTAssertEqual(try String(contentsOf: targetFile, encoding: .utf8), "target retained") + XCTAssertEqual(try files.manager.contentsOfDirectory(atPath: source.path), ["retain.txt"]) + XCTAssertEqual(try files.manager.contentsOfDirectory(atPath: target.path), ["retain.txt"]) + } + + func testUnreadableSourceDoesNotTruncateAnExistingDestination() async throws { + let app = try await editorWebView() + let files = AppFiles.shared + let root = files.cache.appendingPathComponent("ios-transfer-permissions-" + UUID().uuidString) + try files.manager.createDirectory(at: root, withIntermediateDirectories: true) + let source = root.appendingPathComponent("source") + let target = root.appendingPathComponent("target") + try Data("source retained".utf8).write(to: source) + try Data("target retained".utf8).write(to: target) + defer { + try? files.manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: source.path) + try? files.manager.removeItem(at: root) + } + try files.manager.setAttributes([.posixPermissions: 0], ofItemAtPath: source.path) + let error = try await app.callAsyncJavaScript(""" + return await new Promise(resolve=>Bridge.exec(()=>resolve(null),resolve,'File','copyTo',[source,root,'target'])); + """, arguments: ["root": root.absoluteString, "source": source.absoluteString], in: nil, contentWorld: .page) as? Int + XCTAssertEqual(error, 2) + XCTAssertEqual(try String(contentsOf: target, encoding: .utf8), "target retained") + try files.manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: source.path) + XCTAssertEqual(try String(contentsOf: source, encoding: .utf8), "source retained") + XCTAssertEqual(Set(try files.manager.contentsOfDirectory(atPath: root.path)), ["source", "target"]) + } +} diff --git a/platforms/ios/runnerTests/FileURLTests.swift b/platforms/ios/runnerTests/FileURLTests.swift new file mode 100644 index 0000000000..a4af072811 --- /dev/null +++ b/platforms/ios/runnerTests/FileURLTests.swift @@ -0,0 +1,33 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class FileURLTests: BridgeTestCase { + func testReservedNamesRemainPathsInFileMetadataAndWebViewFetch() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(""" + const call=(action,args)=>new Promise((resolve,reject)=>Bridge.exec(resolve,error=>reject(Error(action+': '+JSON.stringify(error))),'File',action,args)); + const folder=await call('getDirectory',[Bridge.file.cacheDirectory,'url # ? %3F 日本語 '+Date.now(),{create:true,exclusive:true}]); + const bytes=new Uint8Array([0,127,128,159,255]); + const names=['plain.bin','hash # 50% 日本語.bin','question ?.bin','literal %3F %23.bin']; + try { + for(const name of names) { + const entry=await call('getFile',[folder.nativeURL,name,{create:true,exclusive:true}]); + await call('write',[entry.nativeURL,bytes.buffer,0,true]); + const file=await new Promise((resolve,reject)=>resolveLocalFileSystemURI(entry.nativeURL,resolve,error=>reject(Error('resolve '+entry.nativeURL+': '+JSON.stringify(error))))); + const url=file.toInternalURL(); + if(new URL(url).search||new URL(url).hash)throw Error('Filename became query or fragment: '+url); + const metadata=await new Promise((resolve,reject)=>file.file(resolve,reject)); + if(metadata.name!==name||metadata.size!==bytes.length)throw Error('Metadata mismatch: '+name); + const response=await fetch(url); + if(!response.ok)throw Error('File response: '+response.status+' '+name); + const read=new Uint8Array(await response.arrayBuffer()); + if(read.join(',')!==bytes.join(','))throw Error('File bytes changed: '+name); + } + return true; + } finally { await call('removeRecursively',[folder.nativeURL]); } + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } +} diff --git a/platforms/ios/runnerTests/FilesBrowserTests.swift b/platforms/ios/runnerTests/FilesBrowserTests.swift new file mode 100644 index 0000000000..203577acb2 --- /dev/null +++ b/platforms/ios/runnerTests/FilesBrowserTests.swift @@ -0,0 +1,62 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class FilesBrowserTests: BridgeTestCase { + func testLocalDocumentsCanBeBrowsedWithoutAndroidStorageEntries() async throws { + let app = try await appWebView() + let files = AppFiles.shared + let file = files.documents.appendingPathComponent("browser-fixture-" + UUID().uuidString + ".txt") + try "Files browser ✓".write(to: file, atomically: true, encoding: .utf8) + defer { try? files.manager.removeItem(at: file) } + let result = try await app.callAsyncJavaScript(""" + for(let n=0;(!window.editorManager||document.body.classList.contains('loading'))&&n<100;n++) + await new Promise(r=>setTimeout(r,100)); + const storageList=localStorage.storageList, state=localStorage.fileBrowserState; + const settings=acode.require('settings'), feedback=settings.value.vibrateOnTap; + try { + settings.value.vibrateOnTap=true; + delete localStorage.storageList; + let selection; + acode.require('fileBrowser')('file','Files fixture',false).then(value=>selection=value,()=>selection=false); + for(let n=0;!document.querySelector('#file-browser li[data-uuid="ios-documents"]')&&n<100;n++) + await new Promise(r=>setTimeout(r,50)); + const browser=document.getElementById('file-browser'); + const entries=[...browser.querySelectorAll('li[data-uuid]')].map(item=>item.dataset.uuid); + const documents=browser.querySelector('li[data-uuid="ios-documents"]'); + if(!documents)throw new Error('Missing Documents: '+JSON.stringify(await new Promise((resolve,reject)=>sdcard.listStorages(resolve,reject)))+'; '+browser.outerHTML); + documents.click(); + for(let n=0;!browser.querySelector(`li[data-name="${name}"]`)&&n<100;n++) + await new Promise(r=>setTimeout(r,50)); + const entry=browser.querySelector(`li[data-name="${name}"]`); + if(!entry)throw new Error('Documents did not open: '+browser.innerText); + for(let n=0;document.getElementById('__loader')&&n<100;n++)await new Promise(r=>setTimeout(r,50)); + if(document.getElementById('__loader'))throw Error('Files browser is still loading'); + entry.dispatchEvent(new MouseEvent('contextmenu',{bubbles:true,cancelable:true})); + for(let n=0;!document.querySelector('.prompt.select:not(.hide)')&&n<100;n++) + await new Promise(r=>setTimeout(r,50)); + const menu=document.querySelector('.prompt.select:not(.hide)'); + if(!menu?.textContent.includes(strings.rename))throw Error('File context menu did not open with tap feedback'); + await acode.require('actionStack').pop(); + for(let n=0;menu.isConnected&&n<100;n++)await new Promise(r=>setTimeout(r,50)); + if(menu.isConnected)throw Error('File context menu did not dismiss'); + entry.click(); + for(let n=0;selection===undefined&&n<100;n++)await new Promise(r=>setTimeout(r,50)); + return {entries,name:selection.name,text:await acode.require('fsOperation')(selection.url).readFile('utf-8')}; + } finally { + settings.value.vibrateOnTap=feedback; + document.querySelector('#file-browser')?.closest('wc-page')?.querySelector('[data-action="close"]')?.click(); + if(storageList===undefined)delete localStorage.storageList;else localStorage.storageList=storageList; + if(state===undefined)delete localStorage.fileBrowserState;else localStorage.fileBrowserState=state; + } + """, arguments: ["name": file.lastPathComponent], in: nil, contentWorld: .page) + let value = try XCTUnwrap(result as? [String: Any]) + let entries = try XCTUnwrap(value["entries"] as? [String]) + XCTAssertTrue(entries.contains("ios-documents")) + XCTAssertTrue(entries.contains("terminal-public")) + XCTAssertFalse(entries.contains("internal-storage")) + XCTAssertEqual(value["name"] as? String, file.lastPathComponent) + XCTAssertEqual(value["text"] as? String, "Files browser ✓") + } +} diff --git a/platforms/ios/runnerTests/Fixtures/README.md b/platforms/ios/runnerTests/Fixtures/README.md new file mode 100644 index 0000000000..fa18a1f7c2 --- /dev/null +++ b/platforms/ios/runnerTests/Fixtures/README.md @@ -0,0 +1,40 @@ +# Local fixtures + +`halfword-lanes.elf` checks all eight ARM64 halfword lanes for loads and stores +with ordinary, immediate post-indexed and register post-indexed addressing. +Rebuild it from the repository root with LLVM and LLD: + +```sh +clang --target=aarch64-linux-gnu -c platforms/ios/Alpine/Tests/halfword-lanes.S -o /tmp/halfword-lanes.o +ld.lld -static --strip-all -e _start /tmp/halfword-lanes.o -o platforms/ios/runnerTests/Fixtures/halfword-lanes.elf +``` + +`fault-signals.elf` checks blocked, ignored and handled synchronous `SIGSEGV` and +`SIGILL`, plus ordinary blocked signals remaining pending until unblocked. +Fatal faults must exit with the signal's status; handlers exit with status 42. +Rebuild it with: + +```sh +clang --target=aarch64-linux-gnu -c platforms/ios/Alpine/Tests/fault-signals.S -o /tmp/fault-signals.o +ld.lld -static --strip-all -e _start /tmp/fault-signals.o -o platforms/ios/runnerTests/Fixtures/fault-signals.elf +``` + +## Plugin fixture + +`install-plugin.zip` is a disposable plugin with ID `app.acode.ios-install-fixture`. +It contains its manifest, `main.js`, a short readme, Acode's existing generic plugin +icon, an empty directory and a five-byte binary file with a Unicode filename. +Inspect the readable entries with `unzip -p install-plugin.zip main.js` or +`unzip -p install-plugin.zip plugin.json`. + +Its initializer reads the packaged binary asset, calls the legacy Cordova System +checksum API and reads a missing key from its isolated plugin context. It records +results in `window.iosInstalledPlugin`; unmount removes that marker. It does not +make purchases, authenticate, execute remote code or write secrets. + +The integration test enters the local archive URL through the Plugins source +prompt, checks the Installed list and removes the plugin, cache and installation +state. It exercises the real installer and loader without exposing test hooks in +the app. A separate paid simulator UI check selected this fixture through Plugins +→ Local → Select document → the native Files picker and verified the same +installation results. Its temporary test and installed fixture were removed. diff --git a/platforms/ios/runnerTests/Fixtures/fault-signals.elf b/platforms/ios/runnerTests/Fixtures/fault-signals.elf new file mode 100755 index 0000000000..6bc08d62fc Binary files /dev/null and b/platforms/ios/runnerTests/Fixtures/fault-signals.elf differ diff --git a/platforms/ios/runnerTests/Fixtures/halfword-lanes.elf b/platforms/ios/runnerTests/Fixtures/halfword-lanes.elf new file mode 100755 index 0000000000..8c8ff37e95 Binary files /dev/null and b/platforms/ios/runnerTests/Fixtures/halfword-lanes.elf differ diff --git a/platforms/ios/runnerTests/Fixtures/install-plugin.zip b/platforms/ios/runnerTests/Fixtures/install-plugin.zip new file mode 100644 index 0000000000..971c6c5033 Binary files /dev/null and b/platforms/ios/runnerTests/Fixtures/install-plugin.zip differ diff --git a/platforms/ios/runnerTests/HTTPFixture.swift b/platforms/ios/runnerTests/HTTPFixture.swift new file mode 100644 index 0000000000..94c30d14d0 --- /dev/null +++ b/platforms/ios/runnerTests/HTTPFixture.swift @@ -0,0 +1,141 @@ +import Foundation +import Network + +final class HTTPFixture: @unchecked Sendable { + private let listener: NWListener + private let queue = DispatchQueue(label: "app.acode.tests.http") + private var connections: [NWConnection] = [] + private var stalledDownloads: [NWConnection] = [] + private let websocket: Bool + let downloadName = "acode-preview-" + UUID().uuidString + ".bin" + var origin: String { "http://127.0.0.1:\(listener.port!.rawValue)" } + + init(websocket: Bool = false) throws { + self.websocket = websocket + let parameters = NWParameters.tcp + if websocket { + let options = NWProtocolWebSocket.Options() + options.autoReplyPing = true + options.setClientRequestHandler(queue) { protocols, headers in + let authorized = headers.contains { $0.name.lowercased() == "x-acode-fixture" && $0.value == "test" } + return NWProtocolWebSocket.Response(status: authorized ? .accept : .reject, subprotocol: protocols.first) + } + parameters.defaultProtocolStack.applicationProtocols.insert(options, at: 0) + } + listener = try NWListener(using: parameters, on: .any) + } + + func start() async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in + listener.stateUpdateHandler = { [weak self] state in + switch state { + case .ready: self?.listener.stateUpdateHandler = nil; continuation.resume() + case .failed(let error): self?.listener.stateUpdateHandler = nil; continuation.resume(throwing: error) + default: break + } + } + listener.newConnectionHandler = { [weak self] connection in + guard let self else { connection.cancel(); return } + self.connections.append(connection) + connection.start(queue: self.queue) + if self.websocket { self.receiveSocket(connection) } + else { self.receive(connection, buffer: Data()) } + } + listener.start(queue: queue) + } + } + + func stop() { + queue.async { self.listener.cancel(); self.connections.forEach { $0.cancel() }; self.connections.removeAll() } + } + + func completeDownloads() { + queue.async { + let remainder = Data(repeating: 0, count: 16_777_216 - 262_144) + for connection in self.stalledDownloads { + connection.send(content: remainder, completion: .contentProcessed { _ in connection.cancel() }) + } + self.stalledDownloads.removeAll() + } + } + + private func receiveSocket(_ connection: NWConnection) { + connection.receiveMessage { [weak self] data, context, _, error in + guard let self, error == nil, let metadata = context?.protocolMetadata(definition: NWProtocolWebSocket.definition) as? NWProtocolWebSocket.Metadata else { connection.cancel(); return } + let reply = NWProtocolWebSocket.Metadata(opcode: metadata.opcode) + if metadata.opcode == .close { reply.closeCode = metadata.closeCode } + let context = NWConnection.ContentContext(identifier: "echo", metadata: [reply]) + connection.send(content: data, contentContext: context, isComplete: true, completion: .contentProcessed { _ in + if metadata.opcode == .close { connection.cancel() } + else { self.receiveSocket(connection) } + }) + } + } + + private func receive(_ connection: NWConnection, buffer: Data) { + connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] data, _, complete, error in + guard let self, let data, error == nil else { connection.cancel(); return } + var buffer = buffer; buffer.append(data) + if let range = buffer.range(of: Data("\r\n\r\n".utf8)) { + let head = String(decoding: buffer[..<range.lowerBound], as: UTF8.self) + let size = head.components(separatedBy: "\r\n").first(where: { $0.lowercased().hasPrefix("content-length:") }).flatMap { Int($0.split(separator: ":", maxSplits: 1)[1].trimmingCharacters(in: .whitespaces)) } ?? 0 + if buffer.count - range.upperBound >= size { + self.respond(connection, head: head, body: Data(buffer[range.upperBound...])); return + } + } + if complete { connection.cancel() } + else { self.receive(connection, buffer: buffer) } + } + } + + private func respond(_ connection: NWConnection, head: String, body: Data) { + let requestPath = head.split(separator: " ").dropFirst().first.map(String.init) ?? "/" + let path = requestPath.hasPrefix("/api/") ? String(requestPath.dropFirst(4)) : requestPath + if ["/stalled-download", "/broken-download"].contains(path) { + if path == "/stalled-download" { stalledDownloads.append(connection) } + let header = "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Disposition: attachment; filename=\"\(downloadName)\"\r\nContent-Length: 16777216\r\nConnection: close\r\n\r\n" + let prefix = Data((0..<262144).map { UInt8($0 % 256) }) + connection.send(content: Data(header.utf8) + prefix, completion: .contentProcessed { _ in + if path == "/broken-download" { self.queue.asyncAfter(deadline: .now() + 0.5) { connection.cancel() } } + }) + return + } + var status = "200 OK" + var headers = "Content-Type: application/octet-stream\r\n" + var data = Data([0, 127, 128, 159, 255]) + switch path { + case "/preview-transfers": + headers = "Content-Type: text/html; charset=utf-8\r\n" + data = Data(""" + <!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"> + <title>Preview transfers

Preview transfers

+

Download fixture

+

+
No file selected
+ + """.utf8) + case "/download": headers += "Content-Disposition: attachment; filename=\"\(downloadName)\"\r\n" + case "/cached-preview": + headers = "Content-Type: text/html; charset=utf-8\r\nCache-Control: max-age=3600\r\n" + data = Data("Cached fixture \(UUID().uuidString)".utf8) + case "/page": headers = "Content-Type: text/html; charset=utf-8\r\n"; data = Data("HTTP fixture

Page ✓

".utf8) + case "/echo": data = body + case "/redirect": status = "302 Found"; headers += "Location: /bytes\r\n"; data = Data() + case "/external-redirect": status = "302 Found"; headers += "Location: http://localhost:1/\r\n"; data = Data() + case "/empty": status = "204 No Content"; data = Data() + case "/error": status = "422 Unprocessable Entity"; data = Data("invalid request".utf8) + case "/cookie": headers += "Set-Cookie: session=fixture; Path=/\r\n"; data = Data("cookie".utf8) + case "/cookie-redirect": status = "302 Found"; headers += "Location: /cookie-check\r\nSet-Cookie: session=redirect-fixture; Path=/\r\n"; data = Data() + case "/cookie-check": data = Data(head.utf8) + case "/stream": data = Data((0..<524288).map { UInt8($0 % 256) }) + default: break + } + let packet = Data("HTTP/1.1 \(status)\r\n\(headers)Content-Length: \(data.count)\r\nConnection: close\r\n\r\n".utf8) + data + let send = { connection.send(content: packet, completion: .contentProcessed { _ in connection.cancel() }) } + if path == "/slow" { queue.asyncAfter(deadline: .now() + 2, execute: send) } + else { send() } + } +} diff --git a/platforms/ios/runnerTests/HapticControlsTests.swift b/platforms/ios/runnerTests/HapticControlsTests.swift new file mode 100644 index 0000000000..14d2137a99 --- /dev/null +++ b/platforms/ios/runnerTests/HapticControlsTests.swift @@ -0,0 +1,69 @@ +import XCTest +import WebKit + +@MainActor +final class HapticControlsTests: BridgeTestCase { + func testQuickToolsSaveWithTapFeedbackEnabled() async throws { + let webView = try await editorWebView() + defer { webView.reload() } + let saved = try await webView.callAsyncJavaScript(""" + const settings = acode.require('settings'); + const original = { + vibrateOnTap: settings.value.vibrateOnTap, + quickToolsTriggerMode: settings.value.quickToolsTriggerMode + }; + const fsOperation = acode.require('fsOperation'); + const EditorFile = acode.require('EditorFile'); + const name = 'ios-haptic-save-' + Date.now() + '.txt'; + const uri = await fsOperation(Bridge.file.cacheDirectory).createFile(name, 'original'); + const fs = fsOperation(uri); + const errors = []; + const onError = event => { errors.push(event.message); event.preventDefault(); }; + let file; + addEventListener('error', onError); + try { + if(typeof navigator.vibrate !== 'undefined') throw Error('Expected native iOS vibration API to be absent'); + file = new EditorFile(name, {uri, text:'original', isUnsaved:false}); + file.makeActive(); + // Unsaved settings compare against the persisted baseline; exercise it first. + const modes = [original.quickToolsTriggerMode, + original.quickToolsTriggerMode === 'click' ? 'touch' : 'click']; + for(const mode of modes) { + await settings.update({vibrateOnTap:true, quickToolsTriggerMode:mode}, false, false); + const content = 'saved from quick tools via ' + mode; + file.session.setValue(content); + await new Promise(resolve => setTimeout(resolve, 100)); + const button = document.querySelector('footer [data-id="save"]'); + if(!button || button.disabled) throw Error('Quick-tools Save unavailable'); + button.scrollIntoView({block:'nearest', inline:'nearest'}); + await new Promise(resolve => requestAnimationFrame(()=>requestAnimationFrame(resolve))); + if(mode === 'click') button.click(); + else { + const rect = button.getBoundingClientRect(); + const hit = document.elementFromPoint(rect.x + rect.width/2, rect.y + rect.height/2); + if(hit !== button) throw Error('Save touch target obstructed: ' + hit?.outerHTML + '; ' + JSON.stringify(rect)); + const touch = new Touch({identifier:1, target:button, + clientX:rect.x + rect.width/2, clientY:rect.y + rect.height/2}); + button.dispatchEvent(new TouchEvent('touchstart', { + bubbles:true, cancelable:true, touches:[touch], changedTouches:[touch] + })); + button.dispatchEvent(new TouchEvent('touchend', { + bubbles:true, cancelable:true, touches:[], changedTouches:[touch] + })); + } + if(errors.length) throw Error(mode + ': ' + errors.join('; ')); + for(let n=0; file.isUnsaved && n<50; n++) await new Promise(resolve=>setTimeout(resolve,100)); + if(file.isUnsaved || await fs.readFile('utf-8') !== content) throw Error(mode + ' did not save'); + } + await new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'Native','haptic',[])); + return true; + } finally { + removeEventListener('error', onError); + await settings.update(original, false, false); + if(file) await file.remove(true); + await fs.delete(); + } + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(saved, true) + } +} diff --git a/platforms/ios/runnerTests/IOSBetaUITests.swift b/platforms/ios/runnerTests/IOSBetaUITests.swift new file mode 100644 index 0000000000..f46fbf9a26 --- /dev/null +++ b/platforms/ios/runnerTests/IOSBetaUITests.swift @@ -0,0 +1,88 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class IOSBetaUITests: BridgeTestCase { + func testHomeAndTerminalInfoFollowActiveTab() async throws { + let webView = try await editorWebView() + let home = try await webView.callAsyncJavaScript(""" + await acode.exec('welcome'); + editorManager.getFile('welcome-tab').makeActive(); + const badge=editorManager.getFile('welcome-tab').content.shadowRoot.querySelector('.beta-badge'); + return !badge + && !editorManager.header.querySelector('[data-action="terminal-info"]'); + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(home, true) + await capture(webView, name: "iOS home") + + defer { + webView.evaluateJavaScript("document.querySelector('.prompt.alert button')?.click();editorManager.getFile('ios-beta-terminal')?.remove(true);editorManager.getFile('ios-beta-editor')?.remove(true);editorManager.getFile('welcome-tab')?.makeActive();") + } + let terminal = try await webView.callAsyncJavaScript(""" + const EditorFile=acode.require('EditorFile'); + const terminal=new EditorFile('Terminal', {id:'ios-beta-terminal',type:'terminal',content:document.createElement('div'),render:true}); + terminal.makeActive(); + const header=editorManager.header; + const info=header.querySelector('[data-action="terminal-info"]'); + if(!info || header.querySelector('[action="toggle-edit-menu"]')) throw Error('Terminal header actions incorrect'); + if(info.tagName !== 'BUTTON' || getComputedStyle(info).pointerEvents === 'none') throw Error('Info button cannot be clicked'); + if(info.getAttribute('aria-label') !== 'About the iOS terminal') throw Error('Missing accessible label'); + info.click(); + return document.querySelector('.prompt.alert .message').textContent; + """, arguments: [:], in: nil, contentWorld: .page) as? String + XCTAssertTrue(terminal?.contains("emulation") == true) + XCTAssertTrue(terminal?.contains("take longer") == true) + XCTAssertFalse(terminal?.localizedCaseInsensitiveContains("Android") == true) + await capture(webView, name: "iOS terminal emulation info") + + let switches = try await webView.callAsyncJavaScript(""" + document.querySelector('.prompt.alert button').click(); + const EditorFile=acode.require('EditorFile'); + const file=new EditorFile('Example.txt',{id:'ios-beta-editor',text:'',isUnsaved:false,render:true}); + file.makeActive(); + const header=editorManager.header; + if(header.querySelector('[data-action="terminal-info"]') || !header.querySelector('[action="toggle-edit-menu"]')) return false; + editorManager.getFile('welcome-tab').makeActive(); + if(header.querySelector('[data-action="terminal-info"]')) return false; + editorManager.getFile('ios-beta-terminal').makeActive(); + return !!header.querySelector('[data-action="terminal-info"]') && !header.querySelector('[action="toggle-edit-menu"]'); + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(switches, true) + } + + func testTemporaryFAQReplacementPreservesBackNavigation() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(""" + await acode.exec('open','help'); + document.querySelector('[data-key="faqs"]').click(); + for(let i=0;!document.querySelector('#faqs-page')&&i<100;i++)await new Promise(r=>setTimeout(r,50)); + const page=document.querySelector('#faqs-page').closest('wc-page'); + const stack=acode.require('actionStack'); + const before=!!stack.get('faqs'); + page.handler.replaceEl(); + const detached=!page.isConnected; + page.handler.restoreEl(); + const result={before,detached,restored:page.isConnected,after:!!stack.get('faqs')}; + page.hide(); + return result; + """, arguments: [:], in: nil, contentWorld: .page) as? [String: Bool] + XCTAssertEqual(result?["before"], true) + XCTAssertEqual(result?["detached"], true) + XCTAssertEqual(result?["restored"], true) + XCTAssertEqual(result?["after"], true, "Temporary page replacement must preserve FAQ back navigation") + } + + private func capture(_ webView: WKWebView, name: String) async { + guard let window = webView.window else { return } + try? await Task.sleep(for: .milliseconds(250)) + window.layoutIfNeeded() + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + let attachment = XCTAttachment(image: image) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + } +} diff --git a/platforms/ios/runnerTests/Iap.storekit b/platforms/ios/runnerTests/Iap.storekit new file mode 100644 index 0000000000..1e52f516f9 --- /dev/null +++ b/platforms/ios/runnerTests/Iap.storekit @@ -0,0 +1,62 @@ +{ + "identifier": "DA20B521-CFA5-4B8C-8C2E-B0A036D1ABAD", + "nonRenewingSubscriptions": [], + "products": [ + { + "displayPrice": "4.99", + "familyShareable": false, + "internalID": "100", + "localizations": [ + { + "description": "Local simulator fixture only", + "displayName": "Acode Pro test", + "locale": "en_US" + } + ], + "productID": "acode_pro_new", + "referenceName": "Acode Pro test", + "type": "NonConsumable" + }, + { + "displayPrice": "2.49", + "familyShareable": false, + "internalID": "101", + "localizations": [ + { + "description": "Local simulator fixture only", + "displayName": "Plugin test", + "locale": "en_US" + } + ], + "productID": "ios_test_plugin", + "referenceName": "Plugin test", + "type": "NonConsumable" + }, + { + "displayPrice": "0.99", + "familyShareable": false, + "internalID": "102", + "localizations": [ + { + "description": "Local simulator fixture only", + "displayName": "Tip test", + "locale": "en_US" + } + ], + "productID": "ios_test_tip", + "referenceName": "Tip test", + "type": "Consumable" + } + ], + "settings": { + "_failTransactionsEnabled": false, + "_locale": "en_US", + "_storefront": "USA", + "_storeKitErrors": [] + }, + "subscriptionGroups": [], + "version": { + "major": 3, + "minor": 0 + } +} diff --git a/platforms/ios/runnerTests/IapBridgeTests.swift b/platforms/ios/runnerTests/IapBridgeTests.swift new file mode 100644 index 0000000000..8ec6798fa1 --- /dev/null +++ b/platforms/ios/runnerTests/IapBridgeTests.swift @@ -0,0 +1,177 @@ +import XCTest +import StoreKit +import StoreKitTest +import WebKit +@testable import runner + +@MainActor +final class IapBridgeTests: BridgeTestCase { + private var session: SKTestSession! + + override func setUp() async throws { + let url = try XCTUnwrap(Bundle(for: Self.self).url(forResource: "Iap", withExtension: "storekit")) + session = try SKTestSession(contentsOf: url) + session.resetToDefaultState() + session.clearTransactions() + session.disableDialogs = true + try await super.setUp() + try await reloadWebView(try await appWebView()) + _ = try await editorWebView() + } + + override func tearDownWithError() throws { + session?.clearTransactions() + session?.resetToDefaultState() + session = nil + } + + func testProductsPurchaseAcknowledgementRestoreAndRevocation() async throws { + let webView = try await prepare() + let products = try await call(webView, action: "getProducts", args: [["acode_pro_new", "ios_test_tip", "missing"]]) as? [[String: Any]] + let pro = try XCTUnwrap(products?.first { $0["productId"] as? String == "acode_pro_new" }) + XCTAssertEqual(products?.count, 2) + XCTAssertEqual(pro["title"] as? String, "Acode Pro test") + XCTAssertEqual(pro["priceAmountMicros"] as? Int, 4_990_000) + XCTAssertEqual(pro["priceCurrencyCode"] as? String, "USD") + let purchase = try await buy(webView, product: "acode_pro_new") + XCTAssertEqual(purchase["purchaseState"] as? Int, 1) + XCTAssertEqual(purchase["isAcknowledged"] as? Bool, false) + XCTAssertEqual(purchase["store"] as? String, "appstore") + let token = try XCTUnwrap(purchase["purchaseToken"] as? String) + XCTAssertEqual(token.split(separator: ".").count, 3) + XCTAssertEqual(purchase["signedTransactionInfo"] as? String, token) + _ = try await call(webView, action: "acknowledgePurchase", args: [token]) + let restored = try await call(webView, action: "restorePurchases") as? [[String: Any]] + XCTAssertEqual(restored?.count, 1) + XCTAssertEqual(restored?.first?["isAcknowledged"] as? Bool, true) + let settingsRestored = try await webView.callAsyncJavaScript(""" + await acode.exec('open','settings'); + const page=acode.require('settings').uiSettings['main-settings']; + const saved=localStorage.getItem('acode_pro'); + try { + page.getListElement().querySelector('[data-key="restorePurchases"]').click(); + for(let n=0;n<100;n++) { + const toast=document.querySelector('#toast .message'); + if(toast?.textContent===(strings['purchases restored']||'Purchases restored')) { + const removeAds=page.getListElement().querySelector('[data-key="removeads"]'); + return localStorage.getItem('acode_pro')==='true'&&(!removeAds||removeAds.hidden); + } + await new Promise(resolve=>setTimeout(resolve,50)); + } + throw Error('Restore UI did not finish: '+JSON.stringify({toast:document.querySelector('#toast .message')?.textContent,dialogs:[...document.querySelectorAll('.prompt:not(.hide)')].map(el=>el.textContent),cached:localStorage.getItem('acode_pro')})); + } finally {page.hide();if(saved===null)localStorage.removeItem('acode_pro');else localStorage.setItem('acode_pro',saved);} + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(settingsRestored, true) + let owned = try await error(webView, action: "purchase", args: ["acode_pro_new"]) + XCTAssertEqual(owned, 7) + let badToken = try await error(webView, action: "acknowledgePurchase", args: ["forged"]) + XCTAssertEqual(badToken, 8) + let notConsumable = try await error(webView, action: "consume", args: [token]) + XCTAssertEqual(notConsumable, 5) + let transaction = try XCTUnwrap(session.allTransactions().first) + try session.refundTransaction(identifier: transaction.identifier) + for _ in 0..<50 { + if (try await call(webView, action: "getPurchases") as? [Any])?.isEmpty == true { return } + try await Task.sleep(for: .milliseconds(100)) + } + XCTFail("Refunded entitlement remained owned") + } + + func testUnfinishedPurchasesSurviveReloadAndConsumablesCanBeBoughtAgain() async throws { + let webView = try await prepare() + let first = try await buy(webView, product: "ios_test_tip") + try await reloadWebView(webView) + _ = try await prepare() + let purchases = try await call(webView, action: "getPurchases") as? [[String: Any]] + XCTAssertEqual(purchases?.count, 1) + XCTAssertEqual(purchases?.first?["isAcknowledged"] as? Bool, false) + let token = try XCTUnwrap(purchases?.first?["purchaseToken"] as? String) + let consumed = try await call(webView, action: "consume", args: [token]) as? Int + XCTAssertEqual(consumed, 0) + let remaining = try await call(webView, action: "getPurchases") as? [Any] + XCTAssertEqual(remaining?.count, 0) + let repeatConsume = try await error(webView, action: "consume", args: [token]) + XCTAssertEqual(repeatConsume, 8) + let second = try await buy(webView, product: "ios_test_tip") + XCTAssertNotEqual(first["transactionId"] as? String, second["transactionId"] as? String) + _ = try await call(webView, action: "consume", args: [try XCTUnwrap(second["purchaseToken"] as? String)]) + } + + func testCancellationKeepsListenerAndPendingApprovalDeliversOnlyOnce() async throws { + let webView = try await prepare() + try await session.setSimulatedError(.generic(.userCancelled), forAPI: StoreKitPurchaseAPI()) + _ = try await call(webView, action: "purchase", args: ["ios_test_plugin"]) + let cancelled = try await wait(webView, expression: "window.iapTestErrors[0]===1") + XCTAssertTrue(cancelled) + try await session.setSimulatedError(nil, forAPI: StoreKitPurchaseAPI()) + session.askToBuyEnabled = true + _ = try await call(webView, action: "purchase", args: ["ios_test_plugin"]) + let pending = try await wait(webView, expression: "window.iapTestEvents.some(event=>event.purchaseState===2)") + XCTAssertTrue(pending) + let before = try await call(webView, action: "getPurchases") as? [Any] + XCTAssertEqual(before?.count, 0) + let transaction = try XCTUnwrap(session.allTransactions().first { $0.state == .deferred }) + try session.approveAskToBuyTransaction(identifier: transaction.identifier) + let approved = try await wait(webView, expression: "window.iapTestEvents.filter(event=>event.purchaseState===1).length===1") + XCTAssertTrue(approved) + try await Task.sleep(for: .milliseconds(300)) + let count = try await webView.evaluateJavaScript("window.iapTestEvents.filter(event=>event.purchaseState===1).length") as? Int + XCTAssertEqual(count, 1) + } + + func testVerificationFailureNeverGrantsOrFinishesPurchase() async throws { + let webView = try await prepare() + try await session.setSimulatedError(.verification(.invalidSignature), forAPI: StoreKitVerificationAPI()) + _ = try await call(webView, action: "purchase", args: ["ios_test_plugin"]) + let failed = try await wait(webView, expression: "window.iapTestErrors.includes(6)") + XCTAssertTrue(failed) + let count = try await webView.evaluateJavaScript("window.iapTestEvents.length") as? Int + XCTAssertEqual(count, 0) + let queryError = try await error(webView, action: "getPurchases") + XCTAssertEqual(queryError, 6) + var unfinished = 0 + for await result in Transaction.unfinished { + unfinished += 1 + guard case .unverified = result else { XCTFail("Expected invalid StoreKit signature"); continue } + let finishError = try await error(webView, action: "acknowledgePurchase", args: [result.jwsRepresentation]) + XCTAssertEqual(finishError, 6) + } + XCTAssertEqual(unfinished, 1) + } + + private func prepare() async throws -> WKWebView { + let webView = try await appWebView() + _ = try await webView.callAsyncJavaScript(""" + await new Promise(resolve=>document.addEventListener('deviceready',resolve)); + window.iapTestEvents=[];window.iapTestErrors=[]; + iap.setPurchaseUpdatedListener(purchases=>iapTestEvents.push(...purchases),error=>iapTestErrors.push(error)); + await new Promise((resolve,reject)=>iap.startConnection(resolve,reject)); + """, arguments: [:], in: nil, contentWorld: .page) + return webView + } + + private func buy(_ webView: WKWebView, product: String) async throws -> [String: Any] { + _ = try await webView.evaluateJavaScript("window.iapTestEvents=[];window.iapTestErrors=[]") + _ = try await call(webView, action: "purchase", args: [product]) + let received = try await wait(webView, expression: "window.iapTestEvents.some(event=>event.purchaseState===1)||window.iapTestErrors.length>0") + XCTAssertTrue(received) + let events = try await webView.evaluateJavaScript("window.iapTestEvents") as? [[String: Any]] + return try XCTUnwrap(events?.first { $0["purchaseState"] as? Int == 1 }) + } + + private func call(_ webView: WKWebView, action: String, args: [Any] = []) async throws -> Any? { + try await webView.callAsyncJavaScript("try {return await new Promise((resolve,reject)=>iap[action](...args,resolve,reject));} catch(error) {throw new Error(action+': '+JSON.stringify(error));}", arguments: ["action": action, "args": args], in: nil, contentWorld: .page) + } + + private func error(_ webView: WKWebView, action: String, args: [Any] = []) async throws -> Int? { + try await webView.callAsyncJavaScript("try {await new Promise((resolve,reject)=>iap[action](...args,resolve,reject));return null;}catch(error){return error;}", arguments: ["action": action, "args": args], in: nil, contentWorld: .page) as? Int + } + + private func wait(_ webView: WKWebView, expression: String) async throws -> Bool { + for _ in 0..<100 { + if try await webView.evaluateJavaScript(expression) as? Bool == true { return true } + try await Task.sleep(for: .milliseconds(100)) + } + return false + } +} diff --git a/platforms/ios/runnerTests/IapPurchaseUITests.swift b/platforms/ios/runnerTests/IapPurchaseUITests.swift new file mode 100644 index 0000000000..db1980f1c8 --- /dev/null +++ b/platforms/ios/runnerTests/IapPurchaseUITests.swift @@ -0,0 +1,119 @@ +import StoreKitTest +import WebKit +import XCTest + +@MainActor +final class IapPurchaseUITests: BridgeTestCase { + private var session: SKTestSession! + + override func setUp() async throws { + let url = try XCTUnwrap(Bundle(for: Self.self).url(forResource: "Iap", withExtension: "storekit")) + session = try SKTestSession(contentsOf: url) + session.resetToDefaultState() + session.clearTransactions() + session.disableDialogs = true + try await super.setUp() + try await reloadWebView(try await appWebView()) + _ = try await editorWebView() + } + + override func tearDownWithError() throws { + session?.clearTransactions() + session?.resetToDefaultState() + session = nil + } + + func testSettingsPurchaseUnlocksProAndShowsFeedbackWithoutReload() async throws { + let webView = try await editorWebView() + _ = try await webView.evaluateJavaScript("localStorage.removeItem('acode_pro')") + try await reloadWebView(webView) + _ = try await editorWebView() + let result = try await webView.callAsyncJavaScript(""" + await acode.exec('open','settings'); + const page=acode.require('settings').uiSettings['main-settings']; + const row=page.getListElement().querySelector('[data-key="removeads"]'); + if(!row||row.hidden)throw Error('Remove ads not available before purchase'); + try { + row.click(); + await Promise.resolve(); + const loading=!!document.querySelector('#__loader:not(.hide)'); + for(let n=0;n<200;n++) { + if(!row.isConnected&&!document.querySelector('#__loader:not(.hide)')) { + await new Promise(resolve=>setTimeout(resolve,4000)); + const confirmation=document.querySelector('.prompt.alert:not(#__loader):not(.hide)'); + const feedback=confirmation?.querySelector('.title')?.textContent===strings.success&& + confirmation?.querySelector('.message')?.textContent===strings['thank you :)']; + confirmation?.querySelector('button')?.click(); + return {loading,feedback,pro:acode.require('config').HAS_PRO,cached:localStorage.getItem('acode_pro')}; + } + await new Promise(resolve=>setTimeout(resolve,50)); + } + throw Error('Purchase did not update Settings: '+JSON.stringify({pro:acode.require('config').HAS_PRO,dialogs:[...document.querySelectorAll('.prompt:not(.hide)')].map(el=>el.textContent)})); + } finally {page.hide();localStorage.removeItem('acode_pro');} + """, arguments: [:], in: nil, contentWorld: .page) as? [String: Any] + XCTAssertEqual(result?["loading"] as? Bool, true) + XCTAssertEqual(result?["feedback"] as? Bool, true) + XCTAssertEqual(result?["pro"] as? Bool, true) + XCTAssertEqual(result?["cached"] as? String, "true") + try await reloadOffline(webView) + let restored = try await webView.evaluateJavaScript("acode.require('config').HAS_PRO") as? Bool + XCTAssertEqual(restored, true) + } + + func testCancelledPurchaseAfterHistoryResetCannotRestoreStaleProWhenOffline() async throws { + let webView = try await editorWebView() + _ = try await webView.evaluateJavaScript("localStorage.setItem('acode_pro','true')") + defer { webView.evaluateJavaScript("localStorage.removeItem('acode_pro')") } + try await reloadWebView(webView) + _ = try await editorWebView() + try await session.setSimulatedError(.generic(.userCancelled), forAPI: StoreKitPurchaseAPI()) + let cancelled = try await webView.callAsyncJavaScript(""" + await acode.exec('open','settings'); + const page=acode.require('settings').uiSettings['main-settings']; + const row=page.getListElement().querySelector('[data-key="removeads"]'); + if(!row||row.hidden)throw Error('Stale cache blocked purchasing after history reset'); + try { + row.click(); + await Promise.resolve(); + for(let n=0;n<200;n++) { + if(!document.querySelector('#__loader:not(.hide)')) { + return !acode.require('config').HAS_PRO&&row.isConnected&& + !document.querySelector('.prompt.alert:not(#__loader):not(.hide)'); + } + await new Promise(resolve=>setTimeout(resolve,50)); + } + return false; + } finally {page.hide();} + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(cancelled, true) + XCTAssertFalse(session.allTransactions().contains { $0.state == .purchased || $0.state == .restored }) + try await reloadOffline(webView) + let state = try await webView.evaluateJavaScript("({pro:acode.require('config').HAS_PRO,cached:localStorage.getItem('acode_pro')==='true'})") as? [String: Bool] + XCTAssertEqual(state?["pro"], false) + XCTAssertEqual(state?["cached"], false) + } + + func testVerificationFailureCannotRestoreStalePro() async throws { + let webView = try await editorWebView() + _ = try await session.buyProduct(identifier: "acode_pro_new") + try await session.setSimulatedError(.verification(.invalidSignature), forAPI: StoreKitVerificationAPI()) + _ = try await webView.evaluateJavaScript("localStorage.setItem('acode_pro','true')") + defer { webView.evaluateJavaScript("localStorage.removeItem('acode_pro')") } + try await reloadOffline(webView) + let restored = try await webView.evaluateJavaScript("acode.require('config').HAS_PRO") as? Bool + XCTAssertEqual(restored, false) + } + + private func reloadOffline(_ webView: WKWebView) async throws { + let scripts = webView.configuration.userContentController + // WebKit's bridged array changes when scripts are removed; materialize a snapshot. + let originalScripts = scripts.userScripts.map { $0 } + defer { + scripts.removeAllUserScripts() + originalScripts.forEach(scripts.addUserScript) + } + scripts.addUserScript(WKUserScript(source: "Object.defineProperty(navigator,'onLine',{get:()=>false})", injectionTime: .atDocumentStart, forMainFrameOnly: true)) + try await reloadWebView(webView) + _ = try await editorWebView() + } +} diff --git a/platforms/ios/runnerTests/InAppRunnerTests.swift b/platforms/ios/runnerTests/InAppRunnerTests.swift new file mode 100644 index 0000000000..a5a5039e50 --- /dev/null +++ b/platforms/ios/runnerTests/InAppRunnerTests.swift @@ -0,0 +1,39 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class InAppRunnerTests: BridgeTestCase { + func testExecutorAndQuickToolsRegressionsInAppRunner() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(""" + await acode.exec('run-tests'); + for (let n = 0; n < 600; n++) { + const tab = editorManager.getFile('test-runner'); + const page = tab?.content.shadowRoot?.querySelector('#test-runner-page'); + if (page && !page.querySelector('.run-btn').disabled) { + return [...page.querySelectorAll('.test-item')].map(item => ({ + name: item.querySelector('.test-name').textContent, + passed: !!item.querySelector('.check_circle'), + skipped: !!item.querySelector('.warningreport_problem'), + error: item.querySelector('.test-error-block')?.textContent || '' + })); + } + await new Promise(resolve => setTimeout(resolve, 1000)); + } + throw Error('In-app tests did not finish'); + """, arguments: [:], in: nil, contentWorld: .page) as? [[String: Any]] + let tests = try XCTUnwrap(result) + let attachment = XCTAttachment(string: String(data: try JSONSerialization.data(withJSONObject: tests, options: [.prettyPrinted]), encoding: .utf8)!) + attachment.name = "In-app test results" + attachment.lifetime = .keepAlways + add(attachment) + for name in ["Quick tools Ctrl+Right moves by word", "Quick tools Ctrl+Shift+Right selects by word", "Quick tools unsupported key falls back"] { + let test = try XCTUnwrap(tests.first { $0["name"] as? String == name }) + XCTAssertEqual(test["passed"] as? Bool, true, "\(name): \(test["error"] ?? "")") + } + let fdroid = try XCTUnwrap(tests.first { $0["name"] as? String == "FDROID env variable" }) + XCTAssertEqual(fdroid["skipped"] as? Bool, true) + XCTAssertEqual(fdroid["error"] as? String, "FDROID is only used on Android") + } +} diff --git a/platforms/ios/runnerTests/KeyboardLayoutTests.swift b/platforms/ios/runnerTests/KeyboardLayoutTests.swift new file mode 100644 index 0000000000..b45dc3e625 --- /dev/null +++ b/platforms/ios/runnerTests/KeyboardLayoutTests.swift @@ -0,0 +1,111 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class KeyboardLayoutTests: BridgeTestCase { + func testPreviewOnlyChangesBottomAnchorWhenKeyboardVisibilityChanges() throws { + let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + let window = UIWindow(windowScene: scene) + let controller = PreviewViewController(url: URL(string: "about:blank")!, theme: [:], console: false) + window.rootViewController = controller + window.isHidden = false + defer { window.isHidden = true; window.rootViewController = nil } + controller.view.layoutIfNeeded() + + func bottomConstraint() throws -> NSLayoutConstraint { + try XCTUnwrap(controller.view.constraints.first { + $0.firstItem === controller.content && $0.firstAttribute == .bottom && $0.isActive + }) + } + func notify(visible: Bool) { + let bounds = controller.view.bounds + let frame = CGRect(x: 0, y: visible ? bounds.height / 2 : bounds.height, + width: bounds.width, height: bounds.height / 2) + NotificationCenter.default.post(name: UIResponder.keyboardWillChangeFrameNotification, object: nil, + userInfo: [UIResponder.keyboardFrameEndUserInfoKey: controller.view.convert(frame, to: window.screen.coordinateSpace), + UIResponder.keyboardAnimationDurationUserInfoKey: 0]) + } + + notify(visible: false) + let hidden = try bottomConstraint() + XCTAssertTrue(hidden.secondItem === controller.view.safeAreaLayoutGuide) + notify(visible: false) + XCTAssertTrue(try bottomConstraint() === hidden) + notify(visible: true) + let shown = try bottomConstraint() + XCTAssertTrue(shown.secondItem === controller.view.keyboardLayoutGuide) + notify(visible: true) + XCTAssertTrue(try bottomConstraint() === shown) + controller.close() + notify(visible: false) + XCTAssertTrue(try bottomConstraint() === shown) + } + + func testKeyboardResizeKeepsTheEditorCaretVisible() async throws { + let webView = try await editorWebView() + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let controller = try XCTUnwrap(responder as? WebViewController) + let originalFrame = webView.frame + addTeardownBlock { @MainActor in + _ = try? await webView.callAsyncJavaScript(""" + const fixture=window.iosKeyboardFixture; + if(fixture){ + for(const [name,listener] of fixture.listeners) acode.require('keyboard').off(name,listener); + await fixture.file.remove(true); + delete window.iosKeyboardFixture; + } + """, arguments: [:], in: nil, contentWorld: .page) + controller.view.endEditing(true) + webView.frame = originalFrame + NotificationCenter.default.post(name: UIResponder.keyboardWillHideNotification, object: nil) + try await self.reloadWebView(webView) + } + _ = try await webView.callAsyncJavaScript(""" + const file = new (acode.require('EditorFile'))('ios-keyboard-layout.txt', { + text:Array.from({length:200},(_,i)=>'keyboard line '+i).join('\\n'), isUnsaved:false + }); + window.iosKeyboardFixture = {file, events:[], listeners:[]}; + file.makeActive(); + await new Promise(resolve=>setTimeout(resolve,200)); + const view = editorManager.editor; + for(const name of ['keyboardShowStart','keyboardShow','keyboardHide']) { + const listener=()=>iosKeyboardFixture.events.push(name); + iosKeyboardFixture.listeners.push([name,listener]); + acode.require('keyboard').on(name,listener); + } + view.focus(); + await new Promise(resolve=>setTimeout(resolve,500)); + view.dispatch({selection:{anchor:view.state.doc.length},scrollIntoView:true}); + for(let n=0;n<100;n++) { + await new Promise(resolve=>setTimeout(resolve,50)); + const caret=view.coordsAtPos(view.state.selection.main.head), bounds=view.scrollDOM.getBoundingClientRect(); + if(caret && caret.top>=bounds.top && caret.bottom<=bounds.bottom) { + iosKeyboardFixture.events.length=0; + return true; + } + } + throw Error('Fixture caret was not initially visible'); + """, arguments: [:], in: nil, contentWorld: .page) + + let height = min(350, controller.view.bounds.height / 2) + let frame = CGRect(x: 0, y: controller.view.bounds.height - height, + width: controller.view.bounds.width, height: height) + NotificationCenter.default.post(name: UIResponder.keyboardWillChangeFrameNotification, object: nil, + userInfo: [UIResponder.keyboardFrameEndUserInfoKey: controller.view.convert(frame, to: nil)]) + // Resize WebKit directly so free-edition banner layout cannot undo the fixture. + webView.frame.size.height -= min(200, webView.bounds.height / 3) + let result = try await webView.callAsyncJavaScript(""" + await new Promise(resolve=>setTimeout(resolve,800)); + const view=editorManager.editor, caret=view.coordsAtPos(view.state.selection.main.head); + const bounds=view.scrollDOM.getBoundingClientRect(); + const config=await new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'System','get-configuration',[])); + return {visible:!!caret && caret.top>=bounds.top && caret.bottom<=bounds.bottom, + caret,bounds:bounds.toJSON(),config,events:iosKeyboardFixture.events, + focused:view.contentDOM.contains(document.activeElement)}; + """, arguments: [:], in: nil, contentWorld: .page) as? [String: Any] + XCTAssertEqual(result?["visible"] as? Bool, true, String(describing: result)) + XCTAssertTrue((result?["events"] as? [String])?.contains("keyboardShow") == true, String(describing: result)) + } +} diff --git a/platforms/ios/runnerTests/MediaUploadTests.swift b/platforms/ios/runnerTests/MediaUploadTests.swift new file mode 100644 index 0000000000..c3ec202db0 --- /dev/null +++ b/platforms/ios/runnerTests/MediaUploadTests.swift @@ -0,0 +1,58 @@ +import XCTest +@testable import runner + +@MainActor +final class MediaUploadTests: BridgeTestCase { + func testFileInputOffersPhotoLibraryInsteadOfOpeningDocumentsDirectly() async throws { + let webView = try await appWebView() + defer { + for window in windows() { dismissMenus(window) } + webView.reload() + } + _ = try await webView.callAsyncJavaScript(""" + const input=document.createElement('input'); + input.type='file'; + input.accept='image/*'; + input.style.cssText='position:fixed;left:-10000px;width:1px;height:1px;opacity:0;pointer-events:none'; + window.mediaCancelled=false; + input.addEventListener('cancel',()=>window.mediaCancelled=true); + document.body.append(input); + input.click(); + """, arguments: [:], in: nil, contentWorld: .page) + var titles: [String] = [] + for _ in 0..<100 { + titles = windows().flatMap { labels($0) } + if titles.contains("Photo Library") { break } + try await Task.sleep(for: .milliseconds(50)) + } + XCTAssertTrue(titles.contains("Photo Library"), "Media menu missing. Visible titles: \(titles)") + XCTAssertTrue(titles.contains("Choose File"), "File access must remain available") + if UIImagePickerController.isSourceTypeAvailable(.camera) { + XCTAssertTrue(titles.contains("Take Photo or Video") || titles.contains("Take Photo"), "Camera access must remain available") + } + for window in windows() { dismissMenus(window) } + var cancelled = false + for _ in 0..<100 { + cancelled = try await webView.evaluateJavaScript("window.mediaCancelled") as? Bool == true + if cancelled { break } + try await Task.sleep(for: .milliseconds(50)) + } + XCTAssertTrue(cancelled, "Dismissing the media menu must notify the plugin") + } + + private func windows() -> [UIWindow] { + UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.flatMap(\.windows) + } + + private func labels(_ view: UIView) -> [String] { + let title = (view as? UILabel)?.text ?? (view as? UIButton)?.title(for: .normal) ?? view.accessibilityLabel + return (title.map { [$0] } ?? []) + view.subviews.flatMap { labels($0) } + } + + private func dismissMenus(_ view: UIView) { + for interaction in view.interactions { + (interaction as? UIContextMenuInteraction)?.dismissMenu() + } + for child in view.subviews { dismissMenus(child) } + } +} diff --git a/platforms/ios/runnerTests/NetworkBridgeTests.swift b/platforms/ios/runnerTests/NetworkBridgeTests.swift new file mode 100644 index 0000000000..e5feb0aa09 --- /dev/null +++ b/platforms/ios/runnerTests/NetworkBridgeTests.swift @@ -0,0 +1,72 @@ +import XCTest +import WebKit + +@MainActor +final class NetworkBridgeTests: BridgeTestCase { + func testNativeWebSocket() async throws { + let server = try HTTPFixture(websocket: true) + try await server.start() + defer { server.stop() } + let webView = try await appWebView() + let result = try await webView.callAsyncJavaScript(""" + await new Promise(resolve => document.addEventListener('deviceready', resolve)); + const socket = await Bridge.websocket.connect(origin.replace('http:','ws:'), ['acode-test'], {'X-Acode-Fixture':'test'}, 'arraybuffer'); + await new Promise((resolve,reject)=>{socket.onopen=resolve;socket.onerror=reject;}); + const echo = value=>new Promise((resolve,reject)=>{socket.onmessage=e=>resolve(e.data);socket.onerror=reject;socket.send(value);}); + if(await echo('Acode ✓') !== 'Acode ✓') throw Error('Socket text changed'); + const bytes = [0,127,128,159,255]; + if([...new Uint8Array(await echo(new Uint8Array(bytes).buffer))].join() !== bytes.join()) throw Error('Socket bytes changed'); + socket.binaryType='blob'; + if(await echo(new TextEncoder().encode('binary text').buffer) !== 'binary text') throw Error('Legacy binary text changed'); + const close = new Promise((resolve,reject)=>{socket.onclose=e=>resolve(e.code);socket.onerror=reject;}); + socket.close(1000, 'done'); + if(await close !== 1000) throw Error('Close code changed'); + if((await Bridge.websocket.listClients()).includes(socket.instanceId)) throw Error('Socket leaked'); + return true; + """, arguments: ["origin": server.origin], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + func testNativeNetworking() async throws { + let server = try HTTPFixture() + try await server.start() + defer { server.stop() } + let webView = try await appWebView() + let result = try await webView.callAsyncJavaScript(""" + await new Promise(resolve => document.addEventListener('deviceready', resolve)); + const request = (path, options = {}) => new Promise((resolve, reject) => Bridge.http.sendRequest(origin + path, options, resolve, reject)); + const bytes = [0,127,128,159,255]; + const binary = await request('/bytes', {responseType:'arraybuffer'}); + if ([...new Uint8Array(binary.data)].join() !== bytes.join()) throw Error('HTTP binary changed'); + const unicode = 'Acode ✓ 日本語'; + if ((await request('/echo', {method:'post', serializer:'utf8', data:unicode})).data !== unicode) throw Error('UTF8 body changed'); + const raw = await request('/echo', {method:'post', serializer:'raw', data:new Uint8Array(bytes).buffer, responseType:'arraybuffer'}); + if ([...new Uint8Array(raw.data)].join() !== bytes.join()) throw Error('Raw body changed'); + if ((await request('/echo', {method:'post', serializer:'urlencoded', data:{code:'a b+c'}})).data !== 'code=a%20b%2Bc') throw Error('Form body changed'); + if ((await request('/redirect', {responseType:'arraybuffer'})).status !== 200) throw Error('Redirect failed'); + try { await request('/redirect', {followRedirect:false}); throw Error('Redirect followed'); } catch(e) { if(e.status !== 302) throw e; } + try { await request('/error'); throw Error('HTTP error resolved'); } catch(e) { if(e.status !== 422 || e.error !== 'invalid request') throw e; } + await request('/cookie'); + if (!(await request('/cookie-check')).data.includes('session=fixture')) throw Error('Cookie missing'); + const destination = Bridge.file.cacheDirectory + 'network-fixture.bin'; + const entry = await request('/bytes', {method:'download', filePath:destination}); + try { if ([...new Uint8Array(await (await fetch(entry.toInternalURL())).arrayBuffer())].join() !== bytes.join()) throw Error('Download changed'); } + finally { await new Promise((resolve,reject)=>entry.remove(resolve,reject)); } + let requestId; + const aborted = new Promise((resolve,reject)=>{ requestId=Bridge.http.sendRequest(origin+'/slow',{},reject,resolve); }); + await new Promise((resolve,reject)=>Bridge.http.abort(requestId,resolve,reject)); + if((await aborted).status !== -8) throw Error('Abort status changed'); + const stream = await system.httpStream(origin+'/stream', {chunkSize:4096}); + await new Promise(resolve=>setTimeout(resolve,100)); + const streamed = new Uint8Array(await stream.arrayBuffer()); + if(streamed.length !== 524288 || streamed.some((b,i)=>b!==i%256)) throw Error('Stream truncated or corrupted'); + const controller = new AbortController(); + const cancelled = system.httpStream(origin+'/slow', {signal:controller.signal}).then(()=>false,e=>e.name==='AbortError'); + controller.abort(); + if(!await cancelled) throw Error('Stream cancellation failed'); + return true; + """, arguments: ["origin": server.origin], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + +} diff --git a/platforms/ios/runnerTests/PlatformUITests.swift b/platforms/ios/runnerTests/PlatformUITests.swift new file mode 100644 index 0000000000..11e424522a --- /dev/null +++ b/platforms/ios/runnerTests/PlatformUITests.swift @@ -0,0 +1,139 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class PlatformUITests: BridgeTestCase { + func testCoveredEditorReturnsWithItsDocumentAndScrollPosition() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(""" + const wait=async (label,check)=>{for(let n=0;n<100;n++){if(check())return;await new Promise(r=>setTimeout(r,50));}throw Error('Editor page did not settle: '+label);}; + const text=Array.from({length:300},(line,index)=>'Page navigation fixture '+index).join('\\n'); + const previous=editorManager.activeFile; + const file=new (acode.require('EditorFile'))('page-navigation-fixture.txt',{text,isUnsaved:false}); + const page=acode.require('page')('Navigation fixture'); + try { + file.makeActive(); + await new Promise(resolve=>setTimeout(resolve,1000)); + const view=editorManager.editor,dom=view.dom,scroller=view.scrollDOM; + scroller.scrollTop=300; + await wait('initial scroll',()=>scroller.scrollTop>0); + const scrollTop=scroller.scrollTop; + document.body.append(page); + await wait('cover shown',()=>page.isConnected&&getComputedStyle(page).opacity==='1'); + if(!root.isConnected||root.handler.$replacement.isConnected)throw Error('Primary editor was detached'); + page.hide(); + await wait('root restored',()=>root.isConnected&&!page.isConnected); + await wait('scroll position restored',()=>scroller.scrollTop===scrollTop); + if(editorManager.editor!==view||view.dom!==dom||!dom.isConnected)throw Error('Editor was rebuilt'); + if(view.state.doc.toString()!==text)throw Error('Editor contents changed'); + if(document.querySelectorAll('.page-replacement').length)throw Error('Page placeholder leaked'); + return true; + } finally { + page.hide(); + await file.remove(true); + previous?.makeActive(); + } + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + func testEmptyNavigationDoesNotOfferToExitButStillClosesDialogs() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(""" + const stack = acode.require('actionStack'); + const settings = acode.require('settings'); + if(stack.length) throw Error('Navigation fixture needs an empty stack'); + const original = {confirm:settings.value.confirmOnExit, close:stack.onCloseApp, exec:Bridge.exec}; + let exits = 0, callbacks = 0; + Bridge.exec = (...args) => { + if(args[2] === 'App' && args[3] === 'exitApp') exits++; + return original.exec(...args); + }; + stack.onCloseApp = () => {callbacks++;}; + try { + for(const confirmOnExit of [true, false]) { + settings.value.confirmOnExit = confirmOnExit; + const pending = stack.pop(); + await new Promise(resolve => setTimeout(resolve,50)); + const unexpected = document.querySelector('.prompt.confirm:not(.hide)'); + if(unexpected) { + unexpected.querySelector('button').click(); + await pending; + throw Error('iOS offered to exit'); + } + await pending; + } + const confirmation = acode.require('confirm')('Navigation fixture', 'Dismiss this dialog'); + if(stack.length !== 1) throw Error('Dialog was not stacked'); + await stack.pop(); + if(await confirmation !== false || stack.length) throw Error('Dialog dismissal changed'); + if(exits || callbacks) throw Error('Unsupported exit flow invoked'); + return true; + } finally { + settings.value.confirmOnExit = original.confirm; + stack.onCloseApp = original.close; + Bridge.exec = original.exec; + } + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + func testSettingsAboutAndDiagnosticsAvoidAndroidStoreActions() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(""" + const wait=async check=>{for(let n=0;n<100;n++){if(check())return;await new Promise(r=>setTimeout(r,50));}throw Error('Platform UI did not settle');}; + const openBrowser=system.openInBrowser, copy=Bridge.clipboard.copy; + const opened=[]; + let copied=''; + system.openInBrowser=(...args)=>opened.push(args); + Bridge.clipboard.copy=value=>{copied=value;}; + const stack=acode.require('actionStack'); + let settingsPage,cover; + try { + await acode.exec('open','settings'); + await wait(()=>document.querySelector('.main-settings-page [data-key="about"]')); + settingsPage=acode.require('settings').uiSettings['main-settings']; + const rating=document.querySelector('.main-settings-page [data-key="rateapp"]'); + if(rating&&!rating.hidden)throw Error('Google Play rating is visible on iOS'); + if(settingsPage.search('rate').some(item=>item.dataset.key==='rateapp'))throw Error('Search reveals unavailable rating action'); + const pro=document.querySelector('.main-settings-page [data-key="removeads"]'); + if(pro&&(pro.textContent.includes(strings['iap-pro-purchase-warning'])||!pro.textContent.includes('Apple Account')))throw Error('Pro restoration instructions target the wrong store'); + rating?.click(); + const settingsElement=document.querySelector('.main-settings-page'); + const body=settingsPage.getListElement(); + body.scrollTop=100; + await new Promise(resolve=>setTimeout(resolve,100)); + const scrollTop=body.scrollTop; + document.querySelector('.main-settings-page [data-key="about"]').click(); + await wait(()=>document.querySelector('#about-page')?.textContent.includes('com.apple.WebKit')); + if(!settingsElement.isConnected)throw Error('Previous page was detached too early'); + cover=acode.require('page')('Nested navigation fixture'); + document.body.append(cover); + await wait(()=>!settingsElement.isConnected); + if(!settingsElement.handler.$replacement.isConnected)throw Error('Deeply covered settings page lost its placeholder'); + cover.hide(); + await wait(()=>settingsElement.isConnected&&!cover.isConnected); + const info=document.querySelector('#about-page .info-item'); + if(info.hasAttribute('href')||!info.textContent.includes('WebKit'))throw Error('WebKit information offers an Android update link'); + info.click(); + if(opened.length)throw Error('About opened an external store'); + await acode.exec('copy-device-info'); + await wait(()=>copied.length>0); + if(!copied.includes('iOS Version: '+device.version)||copied.includes('Android Version:'))throw Error('Incorrect platform in device report'); + if(!copied.includes('com.apple.WebKit'))throw Error('Device report lost native WebKit information'); + await stack.pop(); + await wait(()=>!document.getElementById('about-page')&&settingsElement.isConnected); + await wait(()=>settingsElement.body.scrollTop===scrollTop); + if(settingsElement.body!==body)throw Error('Back rebuilt the settings DOM'); + return true; + } finally { + system.openInBrowser=openBrowser;Bridge.clipboard.copy=copy; + if(cover?.isConnected){cover.hide();await wait(()=>!cover.isConnected);} + if(document.getElementById('about-page'))stack.pop(); + settingsPage?.hide(); + } + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } +} diff --git a/platforms/ios/runnerTests/PluginInstallTests.swift b/platforms/ios/runnerTests/PluginInstallTests.swift new file mode 100644 index 0000000000..d9bdb1115e --- /dev/null +++ b/platforms/ios/runnerTests/PluginInstallTests.swift @@ -0,0 +1,62 @@ +import XCTest +import CryptoKit +@testable import runner + +@MainActor +final class PluginInstallTests: BridgeTestCase { + func testLocalZipInstallsLoadsLegacyAPIsAndUnmounts() async throws { + let webView = try await appWebView() + let fixture = try XCTUnwrap(Bundle(for: Self.self).url(forResource: "install-plugin", withExtension: "zip")) + let archive = AppFiles.shared.cache.appendingPathComponent("plugin install # 日本語.zip") + try Data(contentsOf: fixture).write(to: archive) + defer { try? FileManager.default.removeItem(at: archive) } + let expected = SHA256.hash(data: Data("Acode fixture".utf8)).map { String(format: "%02x", $0) }.joined() + let result = try await webView.callAsyncJavaScript(""" + const wait=async check=>{for(let n=0;n<300;n++){if(check())return;await new Promise(r=>setTimeout(r,100));}throw Error('Plugin interaction timed out');}; + await wait(()=>!app.classList.contains('loading')); + const fs=acode.require('fsOperation'); + const id='app.acode.ios-install-fixture'; + const directory=PLUGIN_DIR+'/'+id; + if(await fs(directory).exists())throw Error('Fixture plugin already exists'); + if(!(await fs(uri).exists()))throw Error('ZIP source missing'); + const errors=[]; + const log=console.error; + let unmounted=false; + console.error=(...args)=>{errors.push(args.map(e=>e?.message||JSON.stringify(e)).join(' '));log(...args);}; + try { + await acode.exec('open','plugins'); + await wait(()=>document.querySelector('[data-action="add-source"]')); + document.querySelector('[data-action="add-source"]').click(); + document.querySelector('.context-menu [data-action="remote"]').click(); + await wait(()=>document.querySelector('.prompt input[type="url"]')); + const input=document.querySelector('.prompt input[type="url"]'); + input.value=uri; + input.dispatchEvent(new Event('input',{bubbles:true})); + input.closest('form').querySelector('button[type="submit"]').click(); + await wait(()=>window.iosInstalledPlugin); + await wait(()=>!document.getElementById('__loader')); + document.getElementById('installed_plugins').click(); + await wait(()=>document.querySelector('#plugin-list [data-id="'+id+'"]')); + const loaded=window.iosInstalledPlugin; + if(JSON.stringify(loaded.bytes)!=='[0,127,128,255,10]'||loaded.checksum!==checksum||!loaded.firstInit||loaded.secret!=='default')throw Error('Plugin initialization lost data or API compatibility'); + if(!(await fs(directory+'/empty').exists()))throw Error('Empty ZIP folder missing'); + const manifest=await fs(directory+'/plugin.json').readFile('json'); + if(manifest.source!==uri)throw Error('Local installation source missing'); + acode.unmountPlugin(id); + unmounted=true; + if(window.iosInstalledPlugin)throw Error('Plugin unmount did not run'); + return true; + }catch(error){throw Error(error.message+'; '+errors.join('; '));}finally{ + console.error=log; + if(!unmounted)acode.unmountPlugin(id); + document.getElementById(id+'-mainScript')?.remove(); + if(await fs(directory).exists())await fs(directory).delete(); + const bytes=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(id)); + const state=DATA_STORAGE+'/.install-state/'+[...new Uint8Array(bytes)].map(n=>n.toString(16).padStart(2,'0')).join(''); + if(await fs(state).exists())await fs(state).delete(); + acode.require('actionStack').pop(); + } + """, arguments: ["uri": "file://" + archive.path, "checksum": expected], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } +} diff --git a/platforms/ios/runnerTests/PluginSecurityTests.swift b/platforms/ios/runnerTests/PluginSecurityTests.swift new file mode 100644 index 0000000000..86eaada1ba --- /dev/null +++ b/platforms/ios/runnerTests/PluginSecurityTests.swift @@ -0,0 +1,45 @@ +import XCTest +@testable import runner + +final class PluginSecurityTests: XCTestCase { + func testSessionTokenAndPermissionIsolation() throws { + let sessions = PluginSessions() + let session = try sessions.establish() + XCTAssertEqual(session.count, 64) + XCTAssertThrowsError(try sessions.establish()) + XCTAssertThrowsError(try sessions.issue(session: "forged", pluginID: "first", manifest: "{}")) + let first = try sessions.issue(session: session, pluginID: "first", manifest: "{\"permissions\":[\"network\"]}") + let second = try sessions.issue(session: session, pluginID: "second", manifest: "{}") + XCTAssertNotEqual(first, second) + XCTAssertEqual(try sessions.permissions(for: first), ["network"]) + XCTAssertEqual(try sessions.permissions(for: second), []) + XCTAssertEqual(try sessions.plugin(for: first), "first") + XCTAssertThrowsError(try sessions.plugin(for: session)) + XCTAssertThrowsError(try sessions.issue(session: session, pluginID: "first", manifest: "invalid")) + XCTAssertEqual(try sessions.permissions(for: first), ["network"]) + try sessions.invalidate(first) + XCTAssertThrowsError(try sessions.plugin(for: first)) + XCTAssertEqual(try sessions.plugin(for: second), "second") + sessions.reset() + XCTAssertThrowsError(try sessions.plugin(for: second)) + XCTAssertThrowsError(try sessions.issue(session: session, pluginID: "first", manifest: "{}")) + XCTAssertNotEqual(try sessions.establish(), session) + } + + func testKeychainNamespacesPersistAndClearIndependently() throws { + let namespace = "ios-test." + UUID().uuidString + let first = SecretStore(namespace: namespace + ".one") + let second = SecretStore(namespace: namespace + ".two") + defer { try? first.clear(); try? second.clear() } + try first.set("token", value: "first ✓") + try second.set("token", value: "second") + XCTAssertEqual(try SecretStore(namespace: namespace + ".one").get("token"), "first ✓") + try first.set("token", value: "updated") + XCTAssertEqual(try first.get("token"), "updated") + try first.clear() + XCTAssertEqual(try first.get("token", default: "missing"), "missing") + XCTAssertEqual(try second.get("token"), "second") + try second.remove("token") + XCTAssertEqual(try second.get("token"), "") + } +} diff --git a/platforms/ios/runnerTests/PluginWebViewTests.swift b/platforms/ios/runnerTests/PluginWebViewTests.swift new file mode 100644 index 0000000000..40567a1230 --- /dev/null +++ b/platforms/ios/runnerTests/PluginWebViewTests.swift @@ -0,0 +1,95 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class PluginWebViewTests: BridgeTestCase { + func testHiddenWebViewMessagingNavigationIsolationAndReload() async throws { + let app = try await editorWebView() + let fixture = try HTTPFixture() + try await fixture.start() + defer { fixture.stop() } + let result = try await app.callAsyncJavaScript(""" + const view=await acode.require('webview').create({mode:'hidden',allowNavigation:false}); + const loaded=()=>new Promise((resolve,reject)=>{ + const timer=setTimeout(()=>{view.off('pageFinished',listener);reject(Error('WebView load timed out'))},5000); + function listener(){clearTimeout(timer);view.off('pageFinished',listener);resolve()} + view.on('pageFinished',listener); + }); + let stage="load"; + try { + let early; + view.onMessage(message=>{early=message}); + let page=loaded(); + await view.loadHTML('Plugin view ✓'); + await page; + if(early?.early!=='ready ✓') throw Error('Document-start messaging missing'); + if(await view.evaluate('Boolean(window.Bridge || window.webkit.messageHandlers.exec)')!=='false') throw Error('Native bridge exposed'); + stage='messages'; + const echoed=new Promise(resolve=>view.onMessage(resolve)); + const payload={code:"'\\n\\u2028 ✓",values:[0,1,true]}; + await view.postMessage(payload); + if(JSON.stringify((await echoed).echo)!==JSON.stringify(payload)) throw Error('Message payload changed'); + stage='evaluate'; + if(await view.evaluate('state')!=='42') throw Error('Evaluate number changed'); + if(await view.evaluate('JSON.stringify({a:1})')!=='{"a":1}') throw Error('Evaluate string changed'); + stage='navigation'; + await view.evaluate('location.href='+JSON.stringify(origin)); + await new Promise(resolve=>setTimeout(resolve,100)); + if(await view.evaluate('document.title')!=='Plugin view ✓') throw Error('Navigation restriction ignored'); + for(const url of ['file:///etc/passwd','acode://localhost/','javascript:alert(1)']) { + let rejected=false;try{await view.loadURL(url)}catch{rejected=true} + if(!rejected) throw Error('Forbidden URL accepted'); + } + let rejected=false;try{await view.show()}catch{rejected=true} + if(!rejected) throw Error('Hidden view was shown'); + await view.hide(); + stage='reload'; + page=loaded(); await view.reload(); await page; + stage='evaluate'; + if(await view.evaluate('state')!=='42') throw Error('Reload lost content'); + stage='explicit URL'; + page=loaded(); await view.loadURL(origin+'/page'); await page; + if(!(await view.evaluate('location.href')).startsWith(origin)) throw Error('Explicit navigation blocked'); + return true; + } catch(error) { throw Error(stage+": "+(error?.message||error)); } finally { await view.destroy(); } + """, arguments: ["origin": fixture.origin], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + func testFullscreenWebViewPreservesStateOnHideAndEmitsClosed() async throws { + let app = try await editorWebView() + let prepared = try await app.callAsyncJavaScript(""" + const view=await acode.require('webview').create({mode:'fullscreen',visible:false,title:'Plugin fixture'}); + window.pluginViewFixture=view; + window.pluginViewClosed=false; + view.on('closed',()=>{window.pluginViewClosed=true}); + const loaded=new Promise((resolve,reject)=>{ + const timer=setTimeout(()=>reject(Error('Fullscreen load timed out')),5000); + view.on('pageFinished',()=>{clearTimeout(timer);resolve()}); + }); + await view.loadHTML('Fullscreen'); + let rejected=false;try{await view.evaluate('state')}catch{rejected=true} + if(!rejected) throw Error('Deferred view evaluated before showing'); + await view.show(); await loaded; + await view.evaluate('state=99'); + await view.hide(); await view.show(); + if(await view.evaluate('state')!=='99') throw Error('Hide destroyed page state'); + return true; + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(prepared, true) + var responder: UIResponder? = app + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let controller = try XCTUnwrap(responder as? WebViewController) + let browser = try XCTUnwrap(controller.presentedViewController as? PreviewViewController) + browser.close() + let closed = try await app.callAsyncJavaScript(""" + for(let n=0;!window.pluginViewClosed&&n<50;n++) await new Promise(resolve=>setTimeout(resolve,100)); + let rejected=false;try{await window.pluginViewFixture.evaluate('1')}catch{rejected=true} + delete window.pluginViewFixture; + const closed=window.pluginViewClosed;delete window.pluginViewClosed; + return closed&&rejected; + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(closed, true) + } +} diff --git a/platforms/ios/runnerTests/PreviewBrowserTests.swift b/platforms/ios/runnerTests/PreviewBrowserTests.swift new file mode 100644 index 0000000000..5c60eded92 --- /dev/null +++ b/platforms/ios/runnerTests/PreviewBrowserTests.swift @@ -0,0 +1,177 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class PreviewBrowserTests: BridgeTestCase { + func testConsoleFocusKeepsScaleAndFitsAboveKeyboard() async throws { + let app = try await editorWebView() + var responder: UIResponder? = app + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let controller = try XCTUnwrap(responder as? WebViewController) + _ = try await app.evaluateJavaScript("acode.exec('console')") + let browser = try await presentedBrowser(controller) + do { + try await waitForPage(browser.webView, expression: "Boolean(document.querySelector('#__c-input'))") + XCTAssertEqual(browser.address.text, "Console") + XCTAssertNil(browser.menuButton.superview) + assertCompactHeader(browser, screenshot: "console") + await waitForKeyboardToHide(browser) + let initialHeight = browser.content.bounds.height + let result = try await browser.webView.callAsyncJavaScript(""" + const input=document.querySelector('#__c-input'); + const initialScale=visualViewport.scale; + input.focus(); + await new Promise(resolve=>setTimeout(resolve,800)); + return {fontSize:parseFloat(getComputedStyle(input).fontSize),initialScale, + scale:visualViewport.scale,focused:document.activeElement===input}; + """, arguments: [:], in: nil, contentWorld: .page) as? [String: Any] + XCTAssertEqual(result?["focused"] as? Bool, true) + XCTAssertGreaterThanOrEqual(try XCTUnwrap(result?["fontSize"] as? Double), 16) + XCTAssertEqual(try XCTUnwrap(result?["scale"] as? Double), try XCTUnwrap(result?["initialScale"] as? Double), accuracy: 0.01) + XCTAssertLessThan(browser.content.bounds.height, initialHeight, "The software keyboard must actually appear") + attachScreenshot(browser, name: "console-keyboard") + _ = try await browser.webView.evaluateJavaScript("document.querySelector('#__c-input').blur()") + await waitForKeyboardToHide(browser) + XCTAssertEqual(browser.content.bounds.height, initialHeight, accuracy: 1) + await withCheckedContinuation { continuation in browser.dismiss(animated: false) { continuation.resume() } } + } catch { + controller.presentedViewController?.dismiss(animated: false) + throw error + } + } + + func testUnsavedEditorFileRunsInIsolatedBrowserWithConsoleAndViewportControls() async throws { + let app = try await appWebView() + let port = Int.random(in: 49152...60000) + _ = try await app.callAsyncJavaScript(""" + for(let n=0;!window.editorManager&&n<100;n++) await new Promise(resolve=>setTimeout(resolve,100)); + const settings=acode.require('settings'); + const file=new (acode.require('EditorFile'))('preview-fixture.html',{text:'Preview fixture

Unsaved ✓

',isUnsaved:true}); + window.previewTestState={file,settings,original:{serverPort:settings.value.serverPort,previewPort:settings.value.previewPort,previewMode:settings.value.previewMode,console:settings.value.console},tutorial:localStorage.__init_runPreview}; + Object.assign(settings.value,{serverPort:port,previewPort:port,previewMode:'inapp',console:settings.CONSOLE_LEGACY}); + localStorage.__init_runPreview='true'; + file.makeActive(); + file.runFile(); + """, arguments: ["port": port], in: nil, contentWorld: .page) + var responder: UIResponder? = app + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let controller = try XCTUnwrap(responder as? WebViewController) + do { + let browser = try await presentedBrowser(controller) + try await waitForPage(browser.webView, expression: "document.querySelector('h1')?.textContent === 'Unsaved ✓'") + let titleReady = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + browser.address.text == "Preview fixture" && !browser.webView.isLoading + }, object: nil) + await fulfillment(of: [titleReady], timeout: 5) + XCTAssertEqual(browser.address.text, "Preview fixture") + assertCompactHeader(browser, screenshot: "browser") + XCTAssertTrue(browser.address.becomeFirstResponder()) + XCTAssertEqual(browser.address.text, browser.webView.url?.absoluteString) + browser.address.resignFirstResponder() + XCTAssertEqual(browser.address.text, "Preview fixture") + let isolated = try await browser.webView.evaluateJavaScript("!window.Bridge && !window.webkit?.messageHandlers?.exec") as? Bool + XCTAssertEqual(isolated, true) + try await waitForPage(browser.webView, expression: "Boolean(document.querySelector('c-toggler'))") + browser.setConsoleVisible(true) + try await waitForPage(browser.webView, expression: "window.consoleShows === 1") + browser.applyViewport(CGSize(width: 768, height: 1024)) + browser.view.layoutIfNeeded() + XCTAssertEqual(browser.webView.bounds.size, CGSize(width: 768, height: 1024)) + try await waitForPage(browser.webView, expression: "window.innerWidth === 768") + XCTAssertFalse(browser.consoleVisible) + _ = try await browser.webView.evaluateJavaScript("void document.documentElement.requestFullscreen()") + for _ in 0..<100 { + if browser.webView.fullscreenState == .inFullscreen { break } + try await Task.sleep(for: .milliseconds(20)) + } + XCTAssertEqual(browser.webView.fullscreenState, .inFullscreen) + browser.view.setNeedsLayout() + browser.view.layoutIfNeeded() + let fullscreenWindow = try XCTUnwrap(browser.webView.window) + let fullscreenFrame = browser.webView.convert(browser.webView.bounds, to: fullscreenWindow) + XCTAssertEqual(fullscreenFrame.width, fullscreenWindow.bounds.width, accuracy: 1) + XCTAssertEqual(fullscreenFrame.height, fullscreenWindow.bounds.height, accuracy: 1) + _ = try await browser.webView.evaluateJavaScript("void document.exitFullscreen()") + for _ in 0..<100 { + if browser.webView.fullscreenState == .notInFullscreen { break } + try await Task.sleep(for: .milliseconds(20)) + } + XCTAssertEqual(browser.webView.fullscreenState, .notInFullscreen) + browser.view.layoutIfNeeded() + XCTAssertEqual(browser.webView.bounds.size, CGSize(width: 768, height: 1024)) + browser.applyViewport(nil) + browser.view.layoutIfNeeded() + XCTAssertEqual(browser.webView.bounds.size, browser.content.bounds.size) + let window = try XCTUnwrap(browser.view.window) + let frame = browser.webView.convert(browser.webView.bounds, to: window) + XCTAssertGreaterThanOrEqual(frame.minY, window.safeAreaInsets.top) + XCTAssertLessThanOrEqual(frame.maxY, window.bounds.height - window.safeAreaInsets.bottom) + browser.webView.stopLoading() + await withCheckedContinuation { continuation in browser.dismiss(animated: false) { continuation.resume() } } + } catch { + controller.presentedViewController?.dismiss(animated: false) + try? await cleanup(app, port: port) + throw error + } + try await cleanup(app, port: port) + } + + func presentedBrowser(_ controller: WebViewController) async throws -> PreviewViewController { + for _ in 0..<100 { + if let browser = controller.presentedViewController as? PreviewViewController, !browser.isBeingPresented { return browser } + try await Task.sleep(for: .milliseconds(100)) + } + throw NSError(domain: "AcodeTests", code: 2, userInfo: [NSLocalizedDescriptionKey: "Preview not presented"]) + } + + private func assertCompactHeader(_ browser: PreviewViewController, screenshot: String) { + browser.view.layoutIfNeeded() + XCTAssertEqual(browser.toolbar.bounds.height, 45, accuracy: 0.5) + XCTAssertEqual(browser.content.frame.minY, browser.toolbar.frame.maxY, accuracy: 0.5) + XCTAssertEqual(browser.address.convert(browser.address.bounds, to: browser.view).midY, browser.toolbar.frame.midY, accuracy: 0.5) + for button in browser.toolbar.arrangedSubviews.compactMap({ $0 as? UIButton }) { + XCTAssertNotNil(button.image(for: .normal), "Missing icon: \(button.accessibilityLabel ?? "")") + } + attachScreenshot(browser, name: screenshot) + } + + func attachScreenshot(_ browser: PreviewViewController, name: String) { + guard let window = browser.view.window else { return } + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) } + let attachment = XCTAttachment(image: image) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + } + + func waitForPage(_ webView: WKWebView, expression: String) async throws { + for _ in 0..<100 { + if !webView.isLoading, (try? await webView.evaluateJavaScript(expression)) as? Bool == true { return } + try await Task.sleep(for: .milliseconds(100)) + } + let contents = try? await webView.evaluateJavaScript("document.body.innerText") + throw NSError(domain: "AcodeTests", code: 3, userInfo: [NSLocalizedDescriptionKey: "Preview failed: \(expression); \(String(describing: contents))"]) + } + + private func waitForKeyboardToHide(_ browser: PreviewViewController) async { + let hidden = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + browser.view.layoutIfNeeded() + return browser.content.bounds.height > 0 && + abs(browser.content.frame.maxY - browser.view.safeAreaLayoutGuide.layoutFrame.maxY) < 1 + }, object: nil) + await fulfillment(of: [hidden], timeout: 5) + } + + private func cleanup(_ app: WKWebView, port: Int) async throws { + _ = try await app.callAsyncJavaScript(""" + const state=window.previewTestState; + Object.assign(state.settings.value,state.original); + if(state.tutorial===undefined) delete localStorage.__init_runPreview; + else localStorage.__init_runPreview=state.tutorial; + await state.file.remove(true); + delete window.previewTestState; + await new Promise(resolve=>Bridge.exec(resolve,resolve,'Server','stop',[port])); + """, arguments: ["port": port], in: nil, contentWorld: .page) + } +} diff --git a/platforms/ios/runnerTests/PreviewDownloadTests.swift b/platforms/ios/runnerTests/PreviewDownloadTests.swift new file mode 100644 index 0000000000..b8decd72fa --- /dev/null +++ b/platforms/ios/runnerTests/PreviewDownloadTests.swift @@ -0,0 +1,114 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class PreviewDownloadTests: BridgeTestCase { + func testAcceptedDownloadCompletesAfterClosingPreview() async throws { + try await interruptedDownload(closePreview: true) + } + + func testBrokenResponseReportsFailureAndRemovesItsPartialFile() async throws { + try await interruptedDownload(closePreview: false) + } + + private func interruptedDownload(closePreview: Bool) async throws { + let server = try HTTPFixture() + try await server.start() + defer { server.stop() } + let app = try await editorWebView() + var responder: UIResponder? = app + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let host = try XCTUnwrap(responder as? WebViewController) + var browser: PreviewViewController? = PreviewViewController(url: try XCTUnwrap(URL(string: server.origin + "/page")), theme: [:], console: false) + browser!.consoleEnabled = false + await withCheckedContinuation { continuation in host.present(browser!, animated: false) { continuation.resume() } } + addTeardownBlock { @MainActor in + if host.presentedViewController != nil { + await withCheckedContinuation { continuation in host.dismiss(animated: false) { continuation.resume() } } + } + } + let file = AppFiles.shared.cache.appendingPathComponent(server.downloadName) + defer { try? FileManager.default.removeItem(at: file) } + let destination = DownloadDestination(browser: browser!, file: file) + defer { withExtendedLifetime(destination) {} } + let request = URLRequest(url: try XCTUnwrap(URL(string: server.origin + (closePreview ? "/stalled-download" : "/broken-download")))) + let download = await withCheckedContinuation { continuation in + browser!.webView.startDownload(using: request) { download in + download.delegate = destination + continuation.resume(returning: download) + } + } + let manager = PreviewDownloadManager.shared + addTeardownBlock { @MainActor in + if manager.transfers[download] != nil { + await withCheckedContinuation { continuation in + download.cancel { _ in + manager.download(download, didFailWithError: URLError(.cancelled), resumeData: nil) + continuation.resume() + } + } + } + } + if closePreview { + for _ in 0..<100 { + if download.progress.completedUnitCount > 0, manager.transfers[download] != nil { break } + try await Task.sleep(for: .milliseconds(50)) + } + XCTAssertGreaterThan(download.progress.completedUnitCount, 0) + XCTAssertLessThan(download.progress.completedUnitCount, 16_777_216) + XCTAssertEqual(manager.transfers[download]?.file, file) + weak var closedBrowser = browser + await withCheckedContinuation { continuation in + browser!.onClose = { continuation.resume() } + browser!.close() + } + XCTAssertNil(host.presentedViewController) + browser = nil + for _ in 0..<100 where closedBrowser != nil { try await Task.sleep(for: .milliseconds(20)) } + XCTAssertNil(closedBrowser, "A download must not retain its closed preview") + XCTAssertNotNil(manager.transfers[download], "Closing the preview must preserve an accepted download") + server.completeDownloads() + for _ in 0..<200 { + if (host.presentedViewController as? UIAlertController)?.title == "Download complete" { break } + try await Task.sleep(for: .milliseconds(50)) + } + XCTAssertEqual((host.presentedViewController as? UIAlertController)?.title, "Download complete") + var expected = Data((0..<262_144).map { UInt8($0 % 256) }) + expected.append(Data(repeating: 0, count: 16_777_216 - expected.count)) + XCTAssertEqual(try Data(contentsOf: file), expected) + } else { + for _ in 0..<100 { + if browser!.activeDialog?.title == "Download failed" { break } + try await Task.sleep(for: .milliseconds(50)) + } + XCTAssertEqual(browser!.activeDialog?.title, "Download failed") + XCTAssertGreaterThan(download.progress.completedUnitCount, 0) + XCTAssertLessThan(download.progress.completedUnitCount, 16_777_216) + XCTAssertFalse(FileManager.default.fileExists(atPath: file.path)) + await withCheckedContinuation { continuation in + browser!.onClose = { continuation.resume() } + browser!.close() + } + } + XCTAssertNil(manager.transfers[download]) + } +} + +@MainActor +private final class DownloadDestination: NSObject, WKDownloadDelegate { + weak var browser: PreviewViewController? + let file: URL + init(browser: PreviewViewController, file: URL) { self.browser = browser; self.file = file } + + // Confirmation UI has separate coverage; this supplies a destination for a real WebKit transfer. + func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) { + guard let browser else { completionHandler(nil); return } + PreviewDownloadManager.shared.accept(download, destination: file, browser: browser) + completionHandler(file) + } + + func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) { + browser?.download(download, didFailWithError: error, resumeData: resumeData) + } +} diff --git a/platforms/ios/runnerTests/PreviewServerTests.swift b/platforms/ios/runnerTests/PreviewServerTests.swift new file mode 100644 index 0000000000..07889798ff --- /dev/null +++ b/platforms/ios/runnerTests/PreviewServerTests.swift @@ -0,0 +1,115 @@ +import XCTest +import WebKit +@testable import runner + +final class LocalHTTPParserTests: XCTestCase { + func testFragmentedUnicodeAndBinaryBodies() throws { + let body = Data([0, 128, 255]) + Data("✓\r\n\r\nend".utf8) + let head = "POST /a%20b%23%E2%9C%93?code=a%2Bb HTTP/1.1\r\nHost: localhost\r\nContent-Length: \(body.count)\r\n\r\n" + var parser = LocalHTTPParser() + let bytes = Data(head.utf8) + body + var request: LocalHTTPRequest? + for (index, byte) in bytes.enumerated() { + request = try parser.append(Data([byte])) + if index < bytes.count - 1 { XCTAssertNil(request) } + } + XCTAssertEqual(request?.body, body) + XCTAssertEqual(request?.payload["path"] as? String, "/a b#✓") + XCTAssertEqual(request?.payload["query"] as? String, "code=a%2Bb") + } + + func testChunkedUploadAndAmbiguousFraming() throws { + var parser = LocalHTTPParser() + let wire = "POST / HTTP/1.1\r\nHost: localhost\r\nTransfer-Encoding: chunked\r\nExpect: 100-continue\r\n\r\n3;x=1\r\nabc\r\n4\r\ndefg\r\n0\r\nX-Final: done\r\n\r\n" + var request: LocalHTTPRequest? + for byte in wire.utf8 { request = try parser.append(Data([byte])) } + XCTAssertEqual(request?.body, Data("abcdefg".utf8)) + XCTAssertTrue(parser.expectsContinue) + for headers in ["Content-Length: -1", "Content-Length: 1\r\nContent-Length: 2", "Transfer-Encoding: chunked\r\nContent-Length: 1", "Transfer-Encoding: gzip", "Content-Length: 999999999", "Host: a\r\nHost: b"] { + var invalid = LocalHTTPParser() + XCTAssertThrowsError(try invalid.append(Data("POST / HTTP/1.1\r\n\(headers)\r\n\r\n".utf8))) + } + } +} + +@MainActor +final class PreviewServerTests: BridgeTestCase { + func testImmediateRestartKeepsTheReplacementRequestHandler() async throws { + let webView = try await appWebView() + let port = Int.random(in: 49152...60000) + let result = try await webView.callAsyncJavaScript(""" + const origin='http://127.0.0.1:'+port; + let server; + try { + for(let generation=0;generation<4;generation++) { + await new Promise((resolve,reject)=>{ + server?.stop(null,reject); + const next=CreateServer(port,resolve,reject); + next.setOnRequestHandler(request=>next.send(request.requestId,{ + status:200,body:'generation-'+generation,headers:{'Content-Type':'text/plain'} + }),reject); + server=next; + }); + const response=await new Promise((resolve,reject)=>Bridge.http.sendRequest(origin,{},resolve,reject)); + if(response.data!=='generation-'+generation)throw Error('Stale preview handler: '+response.data); + } + return true; + } catch(error) {throw Error(error?.message || JSON.stringify(error));} + finally {if(server)await new Promise(resolve=>server.stop(resolve,resolve));} + """, arguments: ["port": port], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + func testServerBridgeFilesRangesAndParallelRequests() async throws { + let webView = try await appWebView() + let file = AppFiles.shared.cache.appendingPathComponent("preview # ✓.bin") + let bytes = Data((0..<524288).map { UInt8($0 % 256) }) + try bytes.write(to: file) + defer { try? FileManager.default.removeItem(at: file) } + let port = Int.random(in: 49152...60000) + let result = try await webView.callAsyncJavaScript(""" + await new Promise(resolve=>document.addEventListener('deviceready',resolve)); + const call=(action,args)=>new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'Server',action,args)); + let server; + await new Promise((resolve,reject)=>{ + server=CreateServer(port,resolve,reject); + server.setOnRequestHandler(request=>{ + if(request.path==='/file') server.send(request.requestId,{path:file}); + else if(request.path==='/missing') server.send(request.requestId,{path:file+'missing'}); + else server.send(request.requestId,{status:201,headers:{'Content-Type':'application/json'},body:JSON.stringify(request)}); + },reject); + }); + const origin='http://127.0.0.1:'+port; + const request=(path,options={})=>new Promise((resolve,reject)=>Bridge.http.sendRequest(origin+path,options,resolve,reject)); + try { + const echo=JSON.parse((await request('/a%20b%23%E2%9C%93?code=a%2Bb',{method:'post',serializer:'utf8',data:'Acode ✓',headers:{'X-Example':'value'}})).data); + if(echo.body!=='Acode ✓'||echo.path!=='/a b#✓'||echo.query!=='code=a%2Bb'||echo.headers['x-example']!=='value'||echo.method!=='POST') throw Error('Request changed'); + const responses=await Promise.all(Array.from({length:5},()=>request('/file',{responseType:'arraybuffer'}))); + for(const response of responses) { + const bytes=new Uint8Array(response.data); + if(bytes.length!==524288||bytes.some((v,i)=>v!==i%256)) throw Error('File truncated'); + } + const range=await request('/file',{headers:{Range:'bytes=127-129'},responseType:'arraybuffer'}); + if(range.status!==206||[...new Uint8Array(range.data)].join()!=='127,128,129'||range.headers['content-range']!=='bytes 127-129/524288') throw Error('Range changed'); + const suffix=await request('/file',{headers:{Range:'bytes=-2'},responseType:'arraybuffer'}); + if([...new Uint8Array(suffix.data)].join()!=='254,255') throw Error('Suffix range changed'); + const head=await request('/file',{method:'head'}); + if(head.data!==''||head.headers['content-length']!=='524288') throw Error('HEAD changed'); + const conditional=await request('/file',{headers:{'If-None-Match':responses[0].headers.etag}}).catch(error=>error); + if(conditional.status!==304) throw Error('Cache validator ignored'); + const invalid=await request('/file',{headers:{Range:'bytes=524288-'}}).catch(error=>error); + if(invalid.status!==416) throw Error('Unsatisfiable range accepted'); + const missing=await request('/missing').catch(error=>error); + if(missing.status!==404) throw Error('Missing file status changed'); + } finally { await call('stop',[port]); } + await call('start',[port]); + await call('stop',[port]); + for(const invalid of [-1,0,65536]) { + let failed=false; try { await call('start',[invalid]); } catch { failed=true; } + if(!failed) throw Error('Invalid port accepted'); + } + return true; + """, arguments: ["port": port, "file": file.absoluteString], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } +} diff --git a/platforms/ios/runnerTests/PreviewTransferTests.swift b/platforms/ios/runnerTests/PreviewTransferTests.swift new file mode 100644 index 0000000000..0838159e52 --- /dev/null +++ b/platforms/ios/runnerTests/PreviewTransferTests.swift @@ -0,0 +1,97 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class PreviewTransferTests: BridgeTestCase { + func testClosingPreviewCancelsUnconfirmedDownload() async throws { + let server = try HTTPFixture() + try await server.start() + defer { server.stop() } + let browser = try await presentBrowser(server.origin + "/preview-transfers") + _ = try await browser.webView.evaluateJavaScript("document.querySelector('a').click()") + for _ in 0..<100 { + if browser.pendingDialog != nil { break } + try await Task.sleep(for: .milliseconds(50)) + } + XCTAssertEqual(browser.activeDialog?.title, "Download file") + XCTAssertNotNil(browser.pendingDialog) + XCTAssertTrue(PreviewDownloadManager.shared.transfers.isEmpty) + await close(browser) + try await Task.sleep(for: .milliseconds(400)) + XCTAssertNil(browser.pendingDialog) + XCTAssertNil(browser.activeDialog) + XCTAssertTrue(PreviewDownloadManager.shared.transfers.isEmpty) + XCTAssertFalse(FileManager.default.fileExists(atPath: AppFiles.shared.documents.appendingPathComponent("Downloads/" + server.downloadName).path)) + } + + func testClosingPreviewCancelsQueuedCacheNavigation() async throws { + let server = try HTTPFixture() + try await server.start() + defer { server.stop() } + let browser = try await presentBrowser(server.origin + "/page") + browser.auxiliaryPresenter = browser.presentingViewController + browser.disableCache = true + var navigated = false + browser.prepareNavigation { navigated = true } + await close(browser) + try await Task.sleep(for: .milliseconds(500)) + XCTAssertFalse(navigated, "Closing a preview must cancel navigation waiting for cache removal") + browser.prepareNavigation { navigated = true } + XCTAssertFalse(navigated) + XCTAssertNil(browser.dialogPresenter) + } + + func testDisableCacheRefreshesPreviouslyCachedResource() async throws { + let server = try HTTPFixture() + try await server.start() + defer { server.stop() } + let browser = try await presentBrowser(server.origin + "/page") + let first = try await browser.webView.callAsyncJavaScript(""" + const read=()=>fetch('/cached-preview').then(response=>response.text()); + return [await read(), await read()]; + """, arguments: [:], in: nil, contentWorld: .page) as? [String] + let cached = try XCTUnwrap(first) + XCTAssertEqual(cached.count, 2) + XCTAssertEqual(cached.first, cached.last) + let refreshedPage = expectation(description: "Cache-disabled navigation finished") + browser.onPageFinished = { refreshedPage.fulfill() } + browser.disableCache = true + browser.refresh() + await fulfillment(of: [refreshedPage], timeout: 5) + browser.onPageFinished = nil + let refreshed = try await browser.webView.callAsyncJavaScript("return await fetch('/cached-preview').then(response=>response.text())", arguments: [:], in: nil, contentWorld: .page) as? String + XCTAssertNotNil(refreshed) + XCTAssertNotEqual(refreshed, cached.first) + await close(browser) + } + + private func presentBrowser(_ origin: String) async throws -> PreviewViewController { + let webView = try await editorWebView() + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let host = try XCTUnwrap(responder as? WebViewController) + XCTAssertNil(host.presentedViewController) + let browser = PreviewViewController(url: try XCTUnwrap(URL(string: origin)), theme: [:], console: false) + browser.consoleEnabled = false + let loaded = expectation(description: "Initial preview navigation finished") + browser.onPageFinished = { loaded.fulfill() } + await withCheckedContinuation { continuation in host.present(browser, animated: false) { continuation.resume() } } + addTeardownBlock { @MainActor in + if browser.presentingViewController != nil { await self.close(browser) } + } + await fulfillment(of: [loaded], timeout: 5) + browser.onPageFinished = nil + return browser + } + + private func close(_ browser: PreviewViewController) async { + let presenter = browser.presentingViewController + await withCheckedContinuation { continuation in + browser.onClose = { continuation.resume() } + browser.close() + } + XCTAssertNil(browser.presentingViewController, "Preview must leave the presentation hierarchy after closing") + XCTAssertNil(presenter?.presentedViewController, "Closing a preview must restore the editor") + } +} diff --git a/platforms/ios/runnerTests/PreviewUploadTests.swift b/platforms/ios/runnerTests/PreviewUploadTests.swift new file mode 100644 index 0000000000..d09f307bd5 --- /dev/null +++ b/platforms/ios/runnerTests/PreviewUploadTests.swift @@ -0,0 +1,89 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class PreviewUploadTests: BridgeTestCase { + func testMultipleFilesUploadThroughNativePicker() async throws { + let server = try HTTPFixture() + try await server.start() + defer { server.stop() } + let directory = AppFiles.shared.documents.appendingPathComponent("Preview upload " + UUID().uuidString.prefix(8)) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let binary = Data((0..<524293).map { UInt8($0 % 256) }) + let text = Data("café 日本語 ✓\r\nsecond line\n".utf8) + let binaryName = "binary # 50% 日本語.bin" + let textName = "café notes.txt" + try binary.write(to: directory.appendingPathComponent(binaryName)) + try text.write(to: directory.appendingPathComponent(textName)) + let sources = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) + let app = try await editorWebView() + var responder: UIResponder? = app + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let host = try XCTUnwrap(responder as? WebViewController) + let browser = PreviewViewController(url: URL(string: server.origin + "/preview-transfers")!, theme: [:], console: false) + browser.consoleEnabled = false + let loaded = expectation(description: "Upload fixture navigation finished") + browser.onPageFinished = { loaded.fulfill() } + await withCheckedContinuation { continuation in host.present(browser, animated: false) { continuation.resume() } } + addTeardownBlock { @MainActor in + await withCheckedContinuation { continuation in + browser.onClose = { continuation.resume() } + browser.close() + } + } + await fulfillment(of: [loaded], timeout: 5) + browser.onPageFinished = nil + _ = try await browser.webView.evaluateJavaScript(""" + upload.addEventListener('change',async()=>{ + try { + const data=new FormData(); + data.append('message','upload ✓'); + for(const file of upload.files)data.append('files',file,file.name); + const request=new Request('/echo',{method:'POST',body:data}); + const expected=new Uint8Array(await request.clone().arrayBuffer()); + const response=await fetch(request); + const received=new Uint8Array(await response.arrayBuffer()); + window.networkUpload={status:response.status,contentType:request.headers.get('content-type'), + count:upload.files.length,bytes:received.length, + identical:received.length===expected.length&&received.every((b,i)=>b===expected[i])}; + result.textContent=JSON.stringify(window.networkUpload); + } catch(error){window.networkUpload={error:String(error)};result.textContent=String(error);} + }); + """) + _ = try await browser.webView.evaluateJavaScript("upload.accept='.bin,.txt';upload.click()") + var picker: UIDocumentPickerViewController? + for _ in 0..<100 { + picker = browser.presentedViewController as? UIDocumentPickerViewController + if picker != nil { break } + try await Task.sleep(for: .milliseconds(50)) + } + let selection = try XCTUnwrap(picker, "Preview file input did not present a document picker") + XCTAssertTrue(selection.allowsMultipleSelection) + selection.delegate?.documentPicker?(selection, didPickDocumentsAt: sources) + if selection.presentingViewController != nil { + await withCheckedContinuation { continuation in selection.dismiss(animated: false) { continuation.resume() } } + } + var result: [String: Any]? + for _ in 0..<100 { + result = (try? await browser.webView.evaluateJavaScript("window.networkUpload || null")) as? [String: Any] + let filesReady = (try? await browser.webView.evaluateJavaScript("window.uploaded?.length===2")) as? Bool == true + if result != nil && filesReady { break } + try await Task.sleep(for: .milliseconds(100)) + } + XCTAssertNil(result?["error"]) + XCTAssertEqual(result?["count"] as? Int, 2) + XCTAssertEqual(result?["status"] as? Int, 200) + XCTAssertEqual(result?["identical"] as? Bool, true) + XCTAssertTrue((result?["contentType"] as? String ?? "").hasPrefix("multipart/form-data; boundary=")) + XCTAssertGreaterThan(result?["bytes"] as? Int ?? 0, binary.count + text.count) + let uploaded = try await browser.webView.evaluateJavaScript("window.uploaded") as? [[String: Any]] + XCTAssertEqual(uploaded?.count, 2) + for (name, bytes) in [(binaryName, binary), (textName, text)] { + let source = try XCTUnwrap(sources.first { $0.lastPathComponent == name }) + let entry = try XCTUnwrap(uploaded?.first { ($0["name"] as? String)?.utf16.elementsEqual(source.lastPathComponent.utf16) == true }, "Missing on-disk name: \(source.lastPathComponent)") + XCTAssertEqual(entry["bytes"] as? [UInt8], Array(bytes)) + } + } +} diff --git a/platforms/ios/runnerTests/RewardPassTests.swift b/platforms/ios/runnerTests/RewardPassTests.swift new file mode 100644 index 0000000000..ebaa3f0611 --- /dev/null +++ b/platforms/ios/runnerTests/RewardPassTests.swift @@ -0,0 +1,84 @@ +import XCTest +@testable import runner + +final class RewardPassTests: XCTestCase { + private let store = SecretStore(namespace: "ios-test.rewards." + UUID().uuidString) + + override func tearDownWithError() throws { try store.clear() } + + func testExistingPassPersistsAndExpiryNoticeIsConsumedOnce() throws { + var date = Date() + let expiry = Int64(date.timeIntervalSince1970 * 1000) + 3_600_000 + try store.set("reward_state", value: "{\"adFreeUntil\":\(expiry),\"redemptionsToday\":2}") + let rewards = RewardPassManager(store: store, now: { date }) + let active = try status(rewards.getRewardStatus()) + XCTAssertEqual(active["isActive"] as? Bool, true) + XCTAssertEqual(active["remainingMs"] as? Int64, 3_600_000) + XCTAssertEqual(active["canRedeem"] as? Bool, false) + XCTAssertEqual(active["hasPendingExpiryNotice"] as? Bool, false) + let reopened = RewardPassManager(store: store, now: { date }) + XCTAssertEqual(try status(reopened.getRewardStatus())["adFreeUntil"] as? Int64, expiry) + + date = date.addingTimeInterval(3600) + let expired = try status(reopened.getRewardStatus()) + XCTAssertEqual(expired["isActive"] as? Bool, false) + XCTAssertEqual(expired["adFreeUntil"] as? Int64, 0) + XCTAssertEqual(expired["remainingMs"] as? Int64, 0) + XCTAssertEqual(expired["hasPendingExpiryNotice"] as? Bool, true) + XCTAssertEqual(expired["expiryNoticePendingUntil"] as? Int64, expiry) + let consumed = try status(rewards.getRewardStatus()) + XCTAssertEqual(consumed["hasPendingExpiryNotice"] as? Bool, false) + XCTAssertEqual(consumed["lastExpiredRewardUntil"] as? Int64, expiry) + } + + func testMissingOrMalformedStateCannotGrantTime() throws { + let rewards = RewardPassManager(store: store) + for raw in ["", "malformed", "{\"redemptionsToday\":2}"] { + try store.set("reward_state", value: raw) + let empty = try status(rewards.getRewardStatus()) + XCTAssertEqual(empty["isActive"] as? Bool, false) + XCTAssertEqual(empty["canRedeem"] as? Bool, false) + XCTAssertEqual(empty["hasPendingExpiryNotice"] as? Bool, false) + } + } + + func testUnchangedStatusDoesNotRewriteStorageAndDayRolloverIsPersisted() throws { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = .current + var date = try XCTUnwrap(calendar.date(from: DateComponents(year: 2026, month: 11, day: 15, hour: 12))) + let raw = """ + { "adFreeUntil": 0, "lastExpiredRewardUntil": 0, "expiryNoticePendingUntil": 0, + "redemptionDay": "2026-11-15", "redemptionsToday": 2 } + """ + try store.set("reward_state", value: raw) + let rewards = RewardPassManager(store: store, now: { date }) + _ = try rewards.getRewardStatus() + XCTAssertEqual(try store.get("reward_state"), raw, "An unchanged read must not rewrite even the JSON formatting") + date = try XCTUnwrap(calendar.date(byAdding: .day, value: 1, to: date)) + XCTAssertEqual(try status(rewards.getRewardStatus())["redemptionsToday"] as? Int, 0) + let saved = try status(store.get("reward_state")) + XCTAssertEqual(saved["redemptionDay"] as? String, "2026-11-16") + } + + private func status(_ value: String) throws -> [String: Any] { + try XCTUnwrap(JSONSerialization.jsonObject(with: Data(value.utf8)) as? [String: Any]) + } +} + +@MainActor +final class RewardBridgeTests: BridgeTestCase { + func testStatusRemainsAvailableButRedemptionIsUnsupported() async throws { + let webView = try await appWebView() + let result = try await webView.callAsyncJavaScript(""" + const raw=await new Promise((resolve,reject)=>system.getRewardStatus(resolve,reject)); + if(typeof raw!=='string')throw Error('Changed reward response type'); + const status=JSON.parse(raw); + if(status.canRedeem!==false)throw Error('New passes must remain disabled'); + if(typeof status.hasPendingExpiryNotice!=='boolean')throw Error('Missing expiry policy'); + if(typeof system.redeemReward!=='undefined')throw Error('Retired wrapper still exposed'); + try{await new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'System','redeemReward',['quick']));return false;} + catch(error){return error?.code==='UNSUPPORTED_ACTION';} + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } +} diff --git a/platforms/ios/runnerTests/SSHBridgeSecurityTests.swift b/platforms/ios/runnerTests/SSHBridgeSecurityTests.swift new file mode 100644 index 0000000000..0536dabec0 --- /dev/null +++ b/platforms/ios/runnerTests/SSHBridgeSecurityTests.swift @@ -0,0 +1,108 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class SSHBridgeSecurityTests: BridgeTestCase { + func testQuietCommandDoesNotInheritConnectionDeadline() async throws { + let fixture = try await SSHTestFixture.configuration() + let port = fixture["port"] as! Int + let key = Data(base64Encoded: fixture["hostKey"] as! String)! + let code = try await Task.detached { + let connection = try SSHConnection(cancellation: SSHCancellation()) + let profile = SSHProfile(hostname: "127.0.0.1", port: port, username: "fixture", authType: "password", password: "fixture-password") + try connection.connect(profile, timeout: 10) { received, _ in XCTAssertEqual(received, key) } + let channel = try SSHChannel(connection: connection) + connection.begin(timeout: 1) + let result = try channel.execute("quiet") + XCTAssertEqual(result["result"] as? String, "stdout ✓\nstderr\n") + return result["code"] as? Int + }.value + XCTAssertEqual(code, 17) + } + + func testHandshakeTimeoutInvalidatesTransport() async throws { + let fixture = try await SSHTestFixture.configuration() + let port = fixture["silentPort"] as! Int + let invalidated = try await Task.detached { + let cancellation = SSHCancellation() + let connection = try SSHConnection(cancellation: cancellation) + let profile = SSHProfile(hostname: "127.0.0.1", port: port, username: "fixture", authType: "password") + do { + try connection.connect(profile, timeout: 0.2) { _, _ in XCTFail("Stalled server supplied a key") } + XCTFail("Stalled handshake succeeded") + } catch { XCTAssertEqual(error.localizedDescription, "SSH operation timed out") } + XCTAssertThrowsError(try cancellation.check()) + return !connection.isConnected + }.value + XCTAssertTrue(invalidated) + } + + func testCancellingUnknownHostDismissesPromptAndDoesNotTrustKey() async throws { + let fixture = try await SSHTestFixture.configuration() + let store = SSHProfileStore() + let (id, profile) = try store.save([NSNull(), "localhost", fixture["port"]!, "fixture", "password", "fixture-password"], legacy: false) + let hosts = SecretStore(namespace: "ssh.knownHosts") + defer { try? store.remove(id); try? hosts.remove(profile.endpoint) } + let webView = try await appWebView() + try await webView.callAsyncJavaScript(""" + window.sshPromptAttempt = new Promise(resolve=>Bridge.exec(()=>resolve({connected:true}),resolve,'Sftp','testProfile',[id,'prompt-test',30000])); + return true; + """, arguments: ["id": id], in: nil, contentWorld: .page) + var prompt: UIAlertController? + for _ in 0..<150 { + prompt = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.flatMap(\.windows).compactMap { alert($0.rootViewController) }.first + if prompt != nil { break } + try await Task.sleep(for: .milliseconds(20)) + } + XCTAssertEqual(prompt?.title, "Unknown SSH host") + XCTAssertTrue(prompt?.message?.contains("SHA256:") == true) + XCTAssertEqual(prompt?.actions.map(\.title), ["Cancel", "Trust and connect"]) + let cancelled = try await webView.callAsyncJavaScript(""" + await new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'Sftp','cancelConnection',['prompt-test'])); + const result = await window.sshPromptAttempt; + delete window.sshPromptAttempt; + return result.code === 'SFTP_CONNECT_CANCELLED'; + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(cancelled, true) + for _ in 0..<100 where prompt?.presentingViewController != nil { try await Task.sleep(for: .milliseconds(20)) } + XCTAssertNil(prompt?.presentingViewController) + XCTAssertEqual(try hosts.get(profile.endpoint), "") + } + + func testInvalidPasswordFailsWithoutCreatingConnection() async throws { + let fixture = try await SSHTestFixture.configuration() + let store = SSHProfileStore() + let (id, profile) = try store.save([NSNull(), "127.0.0.1", fixture["port"]!, "fixture", "password", "wrong-password"], legacy: false) + defer { try? store.remove(id); try? SecretStore(namespace: "ssh.knownHosts").remove(profile.endpoint) } + try store.verify(endpoint: profile.endpoint, key: Data(base64Encoded: fixture["hostKey"] as! String)!, algorithm: "ssh-rsa") { _ in true } + let webView = try await appWebView() + let result = try await webView.callAsyncJavaScript(""" + const call=(action,args=[])=>new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'Sftp',action,args)); + await call('close'); + try { await call('connectUsingProfile',[id]); throw Error('Wrong password authenticated'); } + catch(error) { if(error.message === 'Wrong password authenticated') throw error; } + return await call('isConnected') === 0; + """, arguments: ["id": id], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + private func alert(_ controller: UIViewController?) -> UIAlertController? { + guard let controller else { return nil } + if let alert = controller as? UIAlertController { return alert } + if let presented = alert(controller.presentedViewController) { return presented } + return controller.children.compactMap { alert($0) }.first + } +} + +enum SSHTestFixture { + static func configuration() async throws -> [String: Any] { + let request = URLRequest(url: URL(string: "http://127.0.0.1:22199")!, timeoutInterval: 10) + do { + let (data, _) = try await URLSession.shared.data(for: request) + return try JSONSerialization.jsonObject(with: data) as! [String: Any] + } catch let error as URLError where error.code == .cannotConnectToHost { + throw XCTSkip("Start tests/fixtures/ssh/server.py for the local SSH integration tests") + } + } +} diff --git a/platforms/ios/runnerTests/SSHBridgeTests.swift b/platforms/ios/runnerTests/SSHBridgeTests.swift new file mode 100644 index 0000000000..ca10459997 --- /dev/null +++ b/platforms/ios/runnerTests/SSHBridgeTests.swift @@ -0,0 +1,112 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class SSHBridgeTests: BridgeTestCase { + func testSFTPFilesCommandsProfilesAndCancellation() async throws { + let fixture = try await SSHTestFixture.configuration() + let port = fixture["port"] as! Int + let store = SSHProfileStore() + let (id, profile) = try store.save([NSNull(), "127.0.0.1", port, "fixture", "password", "fixture-password"], legacy: false) + let (silentID, _) = try store.save([NSNull(), "127.0.0.1", fixture["silentPort"]!, "fixture", "password", "fixture-password"], legacy: false) + defer { try? store.remove(id); try? store.remove(silentID); try? SecretStore(namespace: "ssh.knownHosts").remove(profile.endpoint) } + try store.verify(endpoint: profile.endpoint, key: Data(base64Encoded: fixture["hostKey"] as! String)!, algorithm: "ssh-rsa") { _ in true } + let webView = try await appWebView() + let result = try await webView.callAsyncJavaScript(""" + const call = (action,args=[])=>new Promise((resolve,reject)=>Bridge.exec(resolve,error=>reject(Object.assign(new Error(),error,{message:action+': '+JSON.stringify(error)})),'Sftp',action,args)); + const folder = '/acode-' + Date.now(); + const local = Bridge.file.cacheDirectory + 'ssh-fixture.bin'; + try { + const info = await call('getProfileInfo',[id]); + if(info.password || info.privateKey || info.profileId !== id) throw Error('Profile leaked or changed'); + if(await call('testProfile',[id,'test',30000]) !== '/') throw Error('Home changed'); + if(await call('isConnected') !== id) throw Error('Connection ID changed'); + await call('mkdir',[folder]); + const name = folder + '/Acode ✓ 日本語 + #% file.txt'; + await call('createFile',[name,'Acode ✓']); + try { await call('createFile',[name,'overwrite']); throw Error('Overwrote existing file'); } catch(e) { if(e.message === 'Overwrote existing file') throw e; } + const entries = await call('lsDir',[folder]); + if(entries.length !== 1 || !entries[0].isFile || entries[0].length !== 9 || entries[0].url !== name) throw Error('Directory metadata changed ' + JSON.stringify(entries)); + await call('getFile',[name,local]); + const textEntry = await new Promise((resolve,reject)=>window.resolveLocalFileSystemURL(local,resolve,reject)); + if(await (await fetch(textEntry.toInternalURL())).text() !== 'Acode ✓') throw Error('Text download changed'); + const bytes = new Uint8Array(350003).map((_,i)=>i%256); + await new Promise((resolve,reject)=>window.resolveLocalFileSystemURL(local,entry=>entry.createWriter(writer=>{writer.onwriteend=resolve;writer.onerror=reject;writer.write(new Blob([bytes]));},reject),reject)); + await call('putFile',[name,local]); + await call('rename',[name,folder+'/renamed.bin']); + await call('getFile',[folder+'/renamed.bin',local]); + const entry = await new Promise((resolve,reject)=>window.resolveLocalFileSystemURL(local,resolve,reject)); + const downloaded = new Uint8Array(await (await fetch(entry.toInternalURL())).arrayBuffer()); + if(downloaded.length !== bytes.length || downloaded.some((b,i)=>b!==i%256)) throw Error('Transfer corrupted'); + if((await call('stat',['/missing'])).exists !== false) throw Error('Missing stat changed'); + try { await call('stat',['/denied']); throw Error('Permission error hidden'); } catch(e) { if(e.message === 'Permission error hidden') throw e; } + const link = await call('stat',['/relative-link']); + if(!link.isLink || !link.isFile || link.linkTarget !== 'target.txt') throw Error('Relative link changed'); + const broken = await call('stat',['/broken-link']); + if(!broken.isLink || broken.isFile || broken.isDirectory) throw Error('Broken link changed'); + const exec = await call('exec',['large']); + if(exec.code !== 17 || !exec.result.includes('Acode ✓ 日本語') || !exec.result.includes('stderr') || exec.result.length !== ('Acode ✓ 日本語\\n'.repeat(9000)+'stderr\\n').length) throw Error('Command output truncated: '+exec.result.length+'/'+exec.code); + const request = call('testProfile',[silentID,'cancel-me',30000]).then(()=>{throw Error('Cancelled connection succeeded');},error=>error); + await new Promise(resolve=>setTimeout(resolve,100)); + await call('cancelConnection',['cancel-me']); + const cancelled = await request; + if(cancelled.code !== 'SFTP_CONNECT_CANCELLED' || !cancelled.nonRetryable) throw Error('Cancellation changed'); + await call('rm',[folder,false,true]); + if((await call('stat',[folder])).exists) throw Error('Recursive remove failed'); + await call('close'); + if(await call('isConnected') !== 0) throw Error('Connection leaked'); + return true; + } finally { + await call('close'); + try { const entry=await new Promise((resolve,reject)=>window.resolveLocalFileSystemURL(local,resolve,reject)); await new Promise((resolve,reject)=>entry.remove(resolve,reject)); } catch {} + } + """, arguments: ["id": id, "silentID": silentID], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + func testEncryptedPrivateKeyShellResizeAndExit() async throws { + try await shell(privateKey: "privateKey") + } + + func testEncryptedOpenSSHKeyShellResizeAndExit() async throws { + try await shell(privateKey: "ed25519Key") + } + + private func shell(privateKey: String) async throws { + let fixture = try await SSHTestFixture.configuration() + let keyURL = AppFiles.shared.cache.appendingPathComponent(UUID().uuidString) + try Data((fixture[privateKey] as! String).utf8).write(to: keyURL) + defer { try? FileManager.default.removeItem(at: keyURL) } + let store = SSHProfileStore() + let (id, profile) = try store.save([NSNull(), "127.0.0.1", fixture["port"]!, "fixture", "key", "", keyURL.absoluteString, "fixture-passphrase"], legacy: false) + defer { try? store.remove(id); try? SecretStore(namespace: "ssh.knownHosts").remove(profile.endpoint) } + try store.verify(endpoint: profile.endpoint, key: Data(base64Encoded: fixture["hostKey"] as! String)!, algorithm: "ssh-rsa") { _ in true } + let webView = try await appWebView() + let result = try await webView.callAsyncJavaScript(""" + const call = (action,args=[])=>new Promise((resolve,reject)=>Bridge.exec(resolve,error=>reject(Object.assign(new Error(),error,{message:action+': '+JSON.stringify(error)})),'Sftp',action,args)); + let session, output=''; + let resolveExit, rejectExit; + const exited = new Promise((resolve,reject)=>{resolveExit=resolve;rejectExit=reject;}); + try { + session = await new Promise((resolve,reject)=>Bridge.exec(event=>{ + if(event.type === 'ready') resolve(event.sessionId); + if(event.type === 'data') output += event.data; + if(event.type === 'error') rejectExit(Error(event.message)); + if(event.type === 'exit') resolveExit(event.exitCode); + },reject,'Sftp','openShellUsingProfile',[id,80,24])); + await call('resizeShell',[session,123,45]); + await call('writeShell',[session,'size\\n']); + await call('writeShell',[session,'echo ✓ 日本語\\n']); + for(let i=0;i<200 && (!output.includes('size:123x45') || !output.includes('echo ✓ 日本語'));i++) await new Promise(resolve=>setTimeout(resolve,20)); + if(!output.includes('size:123x45') || !output.includes('echo ✓ 日本語')) throw Error('Shell output changed '+output); + await call('writeShell',[session,'exit\\n']); + const code = await Promise.race([exited,new Promise((_,reject)=>setTimeout(()=>reject(Error('Shell never exited')),5000))]); + if(code !== 7) throw Error('Exit status changed '+code); + return true; + } finally { if(session) await call('closeShell',[session]); } + """, arguments: ["id": id], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + +} diff --git a/platforms/ios/runnerTests/SSHSecurityTests.swift b/platforms/ios/runnerTests/SSHSecurityTests.swift new file mode 100644 index 0000000000..7e4cad790d --- /dev/null +++ b/platforms/ios/runnerTests/SSHSecurityTests.swift @@ -0,0 +1,64 @@ +import XCTest +@testable import runner + +final class SSHSecurityTests: XCTestCase { + func testProfileEditsKeepCredentialsNativeAndPreserveBlankSecrets() throws { + let namespace = "ssh-test." + UUID().uuidString + let store = SSHProfileStore(namespace: namespace) + defer { try? SecretStore(namespace: namespace + ".profiles").clear() } + let (id, profile) = try store.save([NSNull(), " host ", 22, " user ", "password", "secret", "", ""], legacy: false) + XCTAssertTrue(id.hasPrefix("profile-")) + XCTAssertEqual(profile.hostname, "host") + XCTAssertEqual(profile.username, "user") + XCTAssertNil(profile.info(id: id)["password"]) + XCTAssertThrowsError(try store.save([id, "host", 22, "user", "password", "replacement"], legacy: true)) + let (editedID, edited) = try store.save([id, "other", 2200, "new", "password", ""], legacy: false) + XCTAssertEqual(editedID, id) + XCTAssertEqual(edited.password, "secret") + XCTAssertEqual(try SSHProfileStore(namespace: namespace).profile(id).hostname, "other") + XCTAssertThrowsError(try store.save([id, "host", 0, "user", "password", "changed"], legacy: false)) + XCTAssertEqual(try store.profile(id).password, "secret") + let key = AppFiles.shared.cache.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: key) } + try Data("private fixture key".utf8).write(to: key) + let converted = try store.save([id, "host", 22, "user", "key", "", key.absoluteString, "passphrase"], legacy: false).1 + XCTAssertEqual(converted.password, "") + XCTAssertNil(converted.info(id: id)["privateKey"]) + let preserved = try store.save([id, "host", 22, "user", "key", "", "", ""], legacy: false).1 + XCTAssertEqual(preserved.privateKey, converted.privateKey) + XCTAssertEqual(preserved.passphrase, "passphrase") + try store.remove(id) + XCTAssertThrowsError(try store.profile(id)) + } + + func testHostTrustPersistsAndChangedKeysCannotBeAccepted() throws { + let namespace = "ssh-test." + UUID().uuidString + let store = SSHProfileStore(namespace: namespace) + defer { try? SecretStore(namespace: namespace + ".knownHosts").clear() } + let key = Data("first key".utf8) + XCTAssertThrowsError(try store.verify(endpoint: "host:22", key: key, algorithm: "ssh-rsa", confirm: { _ in false })) { error in + XCTAssertEqual((error as? SSHFailure)?.payload["code"] as? String, "HOST_KEY_REJECTED") + } + try store.verify(endpoint: "host:22", key: key, algorithm: "ssh-rsa") { fingerprint in + XCTAssertTrue(fingerprint.hasPrefix("SHA256:")); return true + } + try SSHProfileStore(namespace: namespace).verify(endpoint: "host:22", key: key, algorithm: "ssh-rsa") { _ in XCTFail("Known key prompted again"); return false } + XCTAssertThrowsError(try store.verify(endpoint: "host:22", key: Data("changed".utf8), algorithm: "ssh-rsa", confirm: { _ in XCTFail("Changed key offered trust"); return true })) { error in + let failure = error as? SSHFailure + XCTAssertEqual(failure?.payload["code"] as? String, "HOST_KEY_CHANGED") + XCTAssertNotNil(failure?.payload["expectedFingerprint"]) + } + } + + func testTerminalUnicodeSurvivesEveryByteBoundary() { + let value = "Acode ✓ 日本語 🦊\r\n" + let bytes = Data(value.utf8) + for boundary in 0...bytes.count { + var decoder = SSHTextDecoder() + let text = decoder.append(Data(bytes.prefix(boundary))) + decoder.append(Data(bytes.dropFirst(boundary))) + decoder.finish() + XCTAssertEqual(text, value) + } + var decoder = SSHTextDecoder() + XCTAssertEqual(bytes.map { decoder.append(Data([$0])) }.joined() + decoder.finish(), value) + } +} diff --git a/platforms/ios/runnerTests/SSHTransferTests.swift b/platforms/ios/runnerTests/SSHTransferTests.swift new file mode 100644 index 0000000000..dd8efa2966 --- /dev/null +++ b/platforms/ios/runnerTests/SSHTransferTests.swift @@ -0,0 +1,111 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class SSHTransferTests: BridgeTestCase { + func testDroppedTransfersRejectAndAllowCleanReconnect() async throws { + let fixture = try await SSHTestFixture.configuration() + let store = SSHProfileStore() + let (id, profile) = try store.save([NSNull(), "127.0.0.1", fixture["port"]!, "fixture", "password", "fixture-password"], legacy: false) + defer { try? store.remove(id); try? SecretStore(namespace: "ssh.knownHosts").remove(profile.endpoint) } + try store.verify(endpoint: profile.endpoint, key: Data(base64Encoded: fixture["hostKey"] as! String)!, algorithm: "ssh-rsa") { _ in true } + let local = AppFiles.shared.cache.appendingPathComponent("dropped-sftp-" + UUID().uuidString) + let upload = AppFiles.shared.cache.appendingPathComponent("upload-sftp-" + UUID().uuidString) + try Data(repeating: 0xA5, count: 8_388_608).write(to: upload) + defer { + try? FileManager.default.removeItem(at: local) + try? FileManager.default.removeItem(at: upload) + } + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(""" + const call=(action,args=[])=>new Promise((resolve,reject)=>Bridge.exec(resolve,error=>reject(Error(action+' '+(args[0]||'')+': '+JSON.stringify(error))),'Sftp',action,args)); + const interrupted=async request=>{ + let timer; + try { + const outcome=await Promise.race([ + request.then(()=>({success:true}),error=>({error})), + new Promise((resolve,reject)=>{timer=setTimeout(()=>reject(Error('Dropped transfer did not settle')),5000);}) + ]); + if(outcome.success || !outcome.error) throw Error('Dropped transfer reported success'); + if(await call('isConnected')!==0) throw Error('Dropped connection still reported active'); + } finally {clearTimeout(timer);} + }; + try { + await call('close'); + await call('connectUsingProfile',[id]); + await interrupted(call('getFile',['/broken-sftp-download.bin',local])); + const fs=acode.require('fsOperation'); + const partialDownload=await fs(local).stat(); + await call('connectUsingProfile',[id]); + await call('getFile',['/target.txt',local]); + if(await fs(local).readFile('utf-8')!=='target') throw Error('Download retry retained partial data'); + await interrupted(call('putFile',['/broken-sftp-upload.bin',upload])); + await call('connectUsingProfile',[id]); + const partialUpload=await call('stat',['/broken-sftp-upload.bin']); + await call('putFile',['/broken-sftp-upload.bin',local]); + await call('getFile',['/broken-sftp-upload.bin',local]); + if(await fs(local).readFile('utf-8')!=='target') throw Error('Upload retry retained partial data'); + await call('rm',['/broken-sftp-upload.bin',false,false]); + return {download:partialDownload.length,upload:partialUpload.length}; + } catch(error) {throw Error(error?.message || JSON.stringify(error));} + finally {await call('close');} + """, arguments: ["id": id, "local": local.absoluteString, "upload": upload.absoluteString], in: nil, contentWorld: .page) as? [String: Any] + for key in ["download", "upload"] { + let size = try XCTUnwrap(result?[key] as? Int) + XCTAssertGreaterThan(size, 0) + XCTAssertLessThan(size, 8_388_608) + } + XCTAssertEqual(try String(contentsOf: local, encoding: .utf8), "target") + } + + func testClosingDuringDownloadSettlesTheTransferAndAllowsReconnect() async throws { + let fixture = try await SSHTestFixture.configuration() + let store = SSHProfileStore() + let (id, profile) = try store.save([NSNull(), "127.0.0.1", fixture["port"]!, "fixture", "password", "fixture-password"], legacy: false) + defer { try? store.remove(id); try? SecretStore(namespace: "ssh.knownHosts").remove(profile.endpoint) } + try store.verify(endpoint: profile.endpoint, key: Data(base64Encoded: fixture["hostKey"] as! String)!, algorithm: "ssh-rsa") { _ in true } + let local = AppFiles.shared.cache.appendingPathComponent("interrupted-sftp-" + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: local) } + let webView = try await appWebView() + addTeardownBlock { @MainActor in + _ = try? await webView.callAsyncJavaScript(""" + await new Promise(resolve=>Bridge.exec(resolve,resolve,'Sftp','close',[])); + delete window.interruptedTransfer; + """, arguments: [:], in: nil, contentWorld: .page) + } + _ = try await webView.callAsyncJavaScript(""" + const call=(action,args=[])=>new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'Sftp',action,args)); + await call('close'); + await call('connectUsingProfile',[id]); + window.interruptedTransfer=call('getFile',['/slow-transfer.bin',uri]).then(()=>({success:true}),error=>({error})); + return true; + """, arguments: ["id": id, "uri": local.absoluteString], in: nil, contentWorld: .page) + var length: UInt64 = 0 + for _ in 0..<100 { + length = (try? FileManager.default.attributesOfItem(atPath: local.path)[.size] as? NSNumber)?.uint64Value ?? 0 + if length > 0 { break } + try await Task.sleep(for: .milliseconds(50)) + } + XCTAssertGreaterThan(length, 0) + XCTAssertLessThan(length, 8_388_608) + let result = try await webView.callAsyncJavaScript(""" + const call=(action,args=[])=>new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'Sftp',action,args)); + let timer; + try { + const stopped=await Promise.race([ + Promise.all([call('close'),window.interruptedTransfer]), + new Promise((resolve,reject)=>{timer=setTimeout(()=>reject(Error('Transfer did not stop after close')),5000);}) + ]); + if(stopped[1].error?.code!=='SFTP_CONNECT_CANCELLED')throw Error('Interrupted transfer did not report cancellation: '+JSON.stringify(stopped[1])); + if(await call('isConnected')!==0)throw Error('Closed connection still reported active'); + await call('connectUsingProfile',[id]); + if(await call('isConnected')!==id)throw Error('Reconnect failed'); + await call('getFile',['/target.txt',uri]); + return true; + } finally {clearTimeout(timer);delete window.interruptedTransfer;} + """, arguments: ["id": id, "uri": local.absoluteString], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + XCTAssertEqual(try String(contentsOf: local, encoding: .utf8), "target") + } +} diff --git a/platforms/ios/runnerTests/SchemeRequestTests.swift b/platforms/ios/runnerTests/SchemeRequestTests.swift new file mode 100644 index 0000000000..ddae142d3f --- /dev/null +++ b/platforms/ios/runnerTests/SchemeRequestTests.swift @@ -0,0 +1,114 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class SchemeRequestTests: XCTestCase { + func testBrowserAPITransportPreservesBodiesCookiesErrorsAndCancellation() async throws { + let fixture = try HTTPFixture() + try await fixture.start() + defer { fixture.stop() } + let config = WKWebViewConfiguration() + config.setURLSchemeHandler(FixtureSchemeHandler(origin: URL(string: fixture.origin)!), forURLScheme: "acode") + let webView = WKWebView(frame: .zero, configuration: config) + webView.load(URLRequest(url: URL(string: "acode://localhost/")!)) + for _ in 0..<100 { + if !webView.isLoading, webView.url != nil { break } + try await Task.sleep(for: .milliseconds(100)) + } + let result = try await webView.callAsyncJavaScript(""" + const api = 'acode://localhost/__api__/'; + const text = 'body ✓ # %'; + const echo = await fetch(api+'echo', {method:'POST',body:text}); + if (await echo.text() !== text) throw Error('POST body changed'); + const bytes = new Uint8Array([0,128,159,255]); + const binary = await fetch(api+'echo', {method:'PATCH',body:bytes}); + if ([...new Uint8Array(await binary.arrayBuffer())].join() !== bytes.join()) throw Error('Binary body changed'); + const form = new FormData(); + form.append('name',text); form.append('file',new Blob([text]),'fixture.txt'); + const request = new Request(api+'echo', {method:'POST',body:form}); + const formBytes = await request.arrayBuffer(); + const upload = await new Promise((resolve,reject)=>{ + const xhr = new XMLHttpRequest(); + xhr.open('POST', api+'echo'); xhr.responseType='text'; + xhr.setRequestHeader('Content-Type', request.headers.get('Content-Type')); + xhr.onload=()=>resolve(xhr.response); xhr.onerror=()=>reject(Error('XHR failed')); + xhr.send(formBytes); + }); + if(!upload.includes(text) || !upload.includes('fixture.txt')) throw Error('Multipart upload changed'); + const credentials = {'X-Acode-Credentials':'include'}; + await fetch(api+'cookie', {headers:credentials}); + const withCookies = await (await fetch(api+'cookie-check', {headers:credentials})).text(); + const withoutCookies = await (await fetch(api+'cookie-check')).text(); + if(!withCookies.includes('session=fixture') || withoutCookies.includes('session=fixture')) throw Error('Cookie credentials ignored: '+JSON.stringify({withCookies,withoutCookies})); + const failure = await fetch(api+'error'); + if(failure.status !== 422 || await failure.text() !== 'invalid request') throw Error('HTTP failure lost'); + const empty = await fetch(api+'empty'); + if(empty.status !== 204 || await empty.text() !== '') throw Error('Empty response lost'); + const redirect = await fetch(api+'redirect'); + if(!redirect.headers.get('X-Acode-Response-URL').endsWith('/bytes')) throw Error('Redirect metadata lost'); + const manual = await fetch(api+'redirect', {redirect:'manual',headers:{'X-Acode-Redirect':'manual'}}); + if(manual.type !== 'opaqueredirect' || manual.status !== 0) throw Error('Manual redirect changed: '+manual.type+' '+manual.status); + let denied=false; + try { await fetch(api+'external-redirect'); } catch { denied=true; } + if(!denied) throw Error('Cross-origin redirect allowed'); + const controller = new AbortController(); + const pending = fetch(api+'slow',{signal:controller.signal}); + setTimeout(()=>controller.abort(),10); + try { await pending; throw Error('Abort ignored'); } catch(error) { if(error.name !== 'AbortError') throw error; } + return true; + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + for cookie in HTTPCookieStorage.shared.cookies ?? [] where cookie.domain == "127.0.0.1" && cookie.name == "session" { + HTTPCookieStorage.shared.deleteCookie(cookie) + } + } + + func testRedirectHookForwardsResponseCookieAndPreservesAccountToken() async throws { + let fixture = try HTTPFixture() + try await fixture.start() + defer { fixture.stop() } + var request = URLRequest(url: URL(string: fixture.origin + "/cookie-redirect")!) + request.httpShouldHandleCookies = false + request.setValue("token=account-fixture", forHTTPHeaderField: "Cookie") + let transport = HTTPTransport(request: request, followRedirects: true, connectTimeout: 5, readTimeout: 5) + defer { transport.cancel() } + let redirected = expectation(description: "Redirect cookie callback") + redirected.assertForOverFulfill = true + transport.onRedirect = { response, next in + XCTAssertEqual(response.statusCode, 302) + let header = try XCTUnwrap(response.value(forHTTPHeaderField: "Set-Cookie")) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: ["Set-Cookie": header], for: try XCTUnwrap(response.url)) + let cookie = try XCTUnwrap(HTTPCookie.requestHeaderFields(with: cookies)["Cookie"]) + let account = try XCTUnwrap(next.value(forHTTPHeaderField: "Cookie")) + next.setValue(cookie + "; " + account, forHTTPHeaderField: "Cookie") + redirected.fulfill() + } + let data: Data = try await withCheckedThrowingContinuation { continuation in + var body = Data() + transport.onData = { body.append($0) } + transport.onComplete = { error in + if let error { continuation.resume(throwing: error) } + else { continuation.resume(returning: body) } + } + transport.start() + } + await fulfillment(of: [redirected], timeout: 1) + let headers = String(decoding: data, as: UTF8.self).components(separatedBy: "\r\n") + let header = try XCTUnwrap(headers.first { $0.lowercased().hasPrefix("cookie:") }) + let cookies = Set(header.dropFirst("Cookie:".count).components(separatedBy: ";").map { $0.trimmingCharacters(in: .whitespaces) }) + XCTAssertEqual(cookies, ["session=redirect-fixture", "token=account-fixture"]) + } +} + +private final class FixtureSchemeHandler: NSObject, WKURLSchemeHandler { + private let api: AppAPIHandler + init(origin: URL) { api = AppAPIHandler(origin: origin) } + func webView(_ webView: WKWebView, start task: WKURLSchemeTask) { + if task.request.url?.path != "/" { api.start(task); return } + let data = Data("".utf8) + task.didReceive(URLResponse(url: task.request.url!, mimeType: "text/html", expectedContentLength: data.count, textEncodingName: "UTF-8")) + task.didReceive(data); task.didFinish() + } + func webView(_ webView: WKWebView, stop task: WKURLSchemeTask) { api.stop(task) } +} diff --git a/platforms/ios/runnerTests/ScrollbarLayoutTests.swift b/platforms/ios/runnerTests/ScrollbarLayoutTests.swift new file mode 100644 index 0000000000..0825418754 --- /dev/null +++ b/platforms/ios/runnerTests/ScrollbarLayoutTests.swift @@ -0,0 +1,34 @@ +import XCTest +import WebKit + +@MainActor +final class ScrollbarLayoutTests: BridgeTestCase { + func testHiddenScrollbarsKeepScrollingAndListsRetainTheirIndicators() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(""" + const fixtures=[]; + try { + const results=[]; + for(const className of ['open-file-list editor-pane-tabs','no-scroll','list']) { + const scroller=document.createElement('ul'); + scroller.className=className; + scroller.style.cssText='position:fixed;top:100px;left:0;width:160px;height:90px;overflow:auto'; + const content=document.createElement('li'); + content.style.cssText='width:800px;min-width:800px;height:400px;flex-shrink:0'; + scroller.appendChild(content);document.body.appendChild(scroller);fixtures.push(scroller); + await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))); + scroller.scrollLeft=80;scroller.scrollTop=60; + results.push({width:getComputedStyle(scroller).scrollbarWidth,horizontal:scroller.scrollLeft>0, + vertical:scroller.scrollTop>0}); + } + return results; + } finally {fixtures.forEach(element=>element.remove());} + """, arguments: [:], in: nil, contentWorld: .page) as? [[String: Any]] + XCTAssertEqual(result?.count, 3) + XCTAssertEqual(result?[0]["width"] as? String, "none") + XCTAssertEqual(result?[1]["width"] as? String, "none") + XCTAssertEqual(result?[2]["width"] as? String, "auto") + XCTAssertEqual(result?.compactMap { $0["horizontal"] as? Bool }, [true, true, true]) + XCTAssertEqual(result?[1]["vertical"] as? Bool, true) + } +} diff --git a/platforms/ios/runnerTests/ShareTests.swift b/platforms/ios/runnerTests/ShareTests.swift new file mode 100644 index 0000000000..3a0a116e2c --- /dev/null +++ b/platforms/ios/runnerTests/ShareTests.swift @@ -0,0 +1,120 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class ShareTests: BridgeTestCase { + func testFileExportsAreIsolatedAndRemovedAfterCancellationOrReload() async throws { + try await verifyFileSharing(service: "System") + } + + func testNativeFileExportsSurviveUntilDismissalAndAreRemovedOnReload() async throws { + try await verifyFileSharing(service: "Native") + } + + func testRepeatedBridgeSetupRetainsShareOwnerAndCleansPresentedExport() async throws { + try await verifyFileSharing(service: "Native", repeatSetup: true) + } + + func testNativeTextSharingPresentsAndCompletes() async throws { + let webView = try await appWebView() + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let host = try XCTUnwrap(responder as? WebViewController) + _ = try await webView.evaluateJavaScript(""" + window.shareResult={state:'pending'}; + Bridge.exec(()=>window.shareResult={state:'success'},error=>window.shareResult={state:'error',error}, + 'Native','shareText',['Share fixture']); + """) + let presented = try await sheet(host) + presented.completionWithItemsHandler?(nil, false, nil, nil) + await dismiss(presented) + let response = try await result(webView) + XCTAssertEqual(response["state"] as? String, "success") + } + + private func verifyFileSharing(service: String, repeatSetup: Bool = false) async throws { + let webView = try await appWebView() + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let host = try XCTUnwrap(responder as? WebViewController) + let files = AppFiles.shared + let source = files.documents.appendingPathComponent("share-fixture-" + UUID().uuidString + ".bin") + let bytes = Data([0, 127, 128, 255, 10]) + try bytes.write(to: source) + defer { try? files.manager.removeItem(at: source) } + let original = try exports() + try await begin(webView, service: service, path: source.absoluteString) + let first = try await sheet(host) + let exported = try XCTUnwrap(try exports().subtracting(original).first) + let copy = exported.appendingPathComponent("shared # 日本語.bin") + XCTAssertEqual(try Data(contentsOf: copy), bytes) + try Data([1, 2, 3]).write(to: source) + XCTAssertEqual(try Data(contentsOf: copy), bytes) + + try await begin(webView, service: service == "Native" ? "System" : "Native", path: source.absoluteString, key: "busyShare") + let busy = try await result(webView, key: "busyShare") + XCTAssertEqual(busy["error"] as? String, "A share sheet cannot be presented right now") + XCTAssertEqual(try exports().subtracting(original), [exported]) + first.completionWithItemsHandler?(nil, false, nil, nil) + await dismiss(first) + let cancelled = try await result(webView) + XCTAssertEqual(cancelled["state"] as? String, "success") + XCTAssertEqual(try exports(), original) + + try await begin(webView, service: service, path: source.absoluteString) + let pending = try await sheet(host) + if repeatSetup { + let owner = host.bridge.shareService + host.bridge.setup(webView: webView, viewController: host) + XCTAssertTrue(host.bridge.shareService === owner) + } + webView.reload() + for _ in 0..<100 { + if host.presentedViewController == nil { break } + try await Task.sleep(for: .milliseconds(50)) + } + XCTAssertNil(host.presentedViewController, "Reload must dismiss the old share sheet") + XCTAssertEqual(try exports(), original, "Reload must remove temporary exports") + if host.presentedViewController != nil { + pending.completionWithItemsHandler?(nil, false, nil, nil) + await dismiss(pending) + } + _ = try await editorWebView() + } + + private func begin(_ webView: WKWebView, service: String, path: String, key: String = "shareResult") async throws { + _ = try await webView.callAsyncJavaScript(""" + window[key]={state:'pending'}; + Bridge.exec(()=>window[key]={state:'success'},error=>window[key]={state:'error',error}, + service,service==='Native'?'shareFile':'file-action',[path,'shared # 日本語.bin','android.intent.action.SEND']); + """, arguments: ["service": service, "path": path, "key": key], in: nil, contentWorld: .page) + } + + private func exports() throws -> Set { + Set(try FileManager.default.contentsOfDirectory(at: AppFiles.shared.temporary, includingPropertiesForKeys: nil) + .filter { $0.lastPathComponent.hasPrefix("share-") }) + } + + private func result(_ webView: WKWebView, key: String = "shareResult") async throws -> [String: Any] { + let value = try await webView.callAsyncJavaScript(""" + for(let n=0;window[key].state==='pending'&&n<100;n++)await new Promise(r=>setTimeout(r,50)); + return window[key]; + """, arguments: ["key": key], in: nil, contentWorld: .page) + let result = try XCTUnwrap(value as? [String: Any]) + XCTAssertNotEqual(result["state"] as? String, "pending") + return result + } + + private func sheet(_ host: UIViewController) async throws -> UIActivityViewController { + for _ in 0..<100 { + if let sheet = host.presentedViewController as? UIActivityViewController, !sheet.isBeingPresented { return sheet } + try await Task.sleep(for: .milliseconds(50)) + } + throw NSError(domain: "AcodeTests", code: 1, userInfo: [NSLocalizedDescriptionKey: "Share sheet not presented"]) + } + + private func dismiss(_ controller: UIViewController) async { + await withCheckedContinuation { continuation in controller.dismiss(animated: false) { continuation.resume() } } + } +} diff --git a/platforms/ios/runnerTests/SplashTests.swift b/platforms/ios/runnerTests/SplashTests.swift new file mode 100644 index 0000000000..5a234d9d09 --- /dev/null +++ b/platforms/ios/runnerTests/SplashTests.swift @@ -0,0 +1,70 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class SplashTests: BridgeTestCase { + func testNativeBackgroundMatchesLaunchColorBeforeWebContentLoads() async throws { + let controller = WebViewController() + controller.loadViewIfNeeded() + controller.webView.stopLoading() + // Keep the fixture alive until native service initialization finishes. + try await Task.sleep(for: .milliseconds(100)) + let expected = try XCTUnwrap(UIColor(hexString: "#20202c")) + let launch = try XCTUnwrap(Bundle.main.infoDictionary?["UILaunchScreen"] as? [String: String]) + let color = try XCTUnwrap(UIColor(named: try XCTUnwrap(launch["UIColorName"]))) + XCTAssertEqual(color.cgColor.components, expected.cgColor.components) + XCTAssertEqual(controller.view.backgroundColor, color) + XCTAssertEqual(controller.webView.backgroundColor, color) + } + + func testSplashUpdatesBothSafeAreasBeforeEditorStartup() async throws { + let webView = try await editorWebView() + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let controller = try XCTUnwrap(responder as? WebViewController) + let originalColor = try await webView.evaluateJavaScript("localStorage.getItem('__primary_color')") + let storage = String(data: try JSONSerialization.data(withJSONObject: [originalColor]), encoding: .utf8)! + let scripts = webView.configuration.userContentController + // WebKit's bridged array changes when scripts are removed; materialize a snapshot. + let originalScripts = scripts.userScripts.map { $0 } + defer { + scripts.removeAllUserScripts() + originalScripts.forEach(scripts.addUserScript) + webView.evaluateJavaScript("const saved=\(storage)[0];if(saved===null)localStorage.removeItem('__primary_color');else localStorage.setItem('__primary_color',saved);") { _, _ in webView.reload() } + } + + for saved in ["", "rgb(35, 39, 42)", "#ffffff"] { + scripts.removeAllUserScripts() + originalScripts.forEach(scripts.addUserScript) + scripts.addUserScript(WKUserScript(source: """ + \(saved.isEmpty ? "localStorage.removeItem('__primary_color');" : "localStorage.setItem('__primary_color','\(saved)');") + Object.defineProperty(window,'nativeReady',{configurable:true,get:()=>new Promise(()=>{}),set:()=>{}}); + """, injectionTime: .atDocumentStart, forMainFrameOnly: true)) + webView.reload() + try await Task.sleep(for: .milliseconds(200)) + _ = try await appWebView() + let result = try await webView.evaluateJavaScript("getComputedStyle(document.documentElement).backgroundColor") + let background = try XCTUnwrap(result as? String) + let components = background.split(whereSeparator: { !$0.isNumber && $0 != "." }).compactMap { Double($0) } + let color = UIColor(red: components[0] / 255, green: components[1] / 255, blue: components[2] / 255, alpha: 1) + for _ in 0..<50 { + if controller.view.backgroundColor == color { break } + try await Task.sleep(for: .milliseconds(20)) + } + let loading = try await webView.evaluateJavaScript("document.body.classList.contains('loading')") as? Bool + XCTAssertEqual(loading, true) + XCTAssertEqual(controller.view.backgroundColor, color, saved) + XCTAssertEqual(webView.backgroundColor, color, saved) + XCTAssertEqual(webView.window?.backgroundColor, color, saved) + let window = try XCTUnwrap(webView.window) + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + let screenshot = XCTAttachment(image: image) + screenshot.name = "Splash \(saved.isEmpty ? "default" : saved)" + screenshot.lifetime = .keepAlways + add(screenshot) + } + } +} diff --git a/platforms/ios/runnerTests/SystemFileTests.swift b/platforms/ios/runnerTests/SystemFileTests.swift new file mode 100644 index 0000000000..f2b53386b1 --- /dev/null +++ b/platforms/ios/runnerTests/SystemFileTests.swift @@ -0,0 +1,113 @@ +import XCTest +@testable import runner + +final class SystemFileTests: XCTestCase { + private let files = AppFiles.shared + private var directory: URL! + + override func setUpWithError() throws { + directory = files.cache.appendingPathComponent("ios-system-files-" + UUID().uuidString) + try files.manager.createDirectory(at: directory, withIntermediateDirectories: true) + } + + override func tearDownWithError() throws { try files.manager.removeItem(at: directory) } + + func testSymlinkExistenceAndRemovalNeverDeleteTheTarget() throws { + let target = directory.appendingPathComponent("target # 日本語.txt") + let link = directory.appendingPathComponent("link") + XCTAssertEqual(try call("createSymlink", [target.lastPathComponent, link.path]) as? Int, 1) + XCTAssertEqual(try call("fileExists", [link.path, "true"]) as? Int, 1) + XCTAssertEqual(try call("fileExists", [link.path, "false"]) as? Int, 0) + try Data("retain me".utf8).write(to: target) + XCTAssertEqual(try call("fileExists", [link.path, "false"]) as? Int, 1) + XCTAssertEqual(try call("createSymlink", [target.path, link.path]) as? Int, 0) + _ = try call("deleteFile", [link.path]) + XCTAssertEqual(try String(contentsOf: target, encoding: .utf8), "retain me") + XCTAssertEqual(try call("fileExists", [link.path, "true"]) as? Int, 0) + XCTAssertEqual(try call("createSymlink", ["/etc", link.path]) as? Int, 0) + try files.manager.createSymbolicLink(at: link, withDestinationURL: URL(fileURLWithPath: "/etc")) + XCTAssertEqual(try call("fileExists", [link.path, "true"]) as? Int, 1) + XCTAssertEqual(try call("fileExists", [link.path, "false"]) as? Int, 0) + XCTAssertThrowsError(try call("writeText", [link.appendingPathComponent("escape").path, "escape"])) + _ = try call("deleteFile", [link.path]) + XCTAssertEqual(try call("fileExists", [link.path, "true"]) as? Int, 0) + XCTAssertThrowsError(try call("deleteFile", [directory.path])) + XCTAssertTrue(files.manager.fileExists(atPath: target.path)) + XCTAssertThrowsError(try call("deleteFile", [files.cache.path])) + } + + func testBinaryCopyReplacesFilesAndFailurePreservesExistingContent() throws { + let source = directory.appendingPathComponent("source.bin") + let destination = directory.appendingPathComponent("destination") + let name = "copied # 50% 日本語.bin" + let bytes = Data((0..<2_000_000).map { UInt8($0 % 256) }) + try bytes.write(to: source) + _ = try call("copyToUri", [source.absoluteString, destination.absoluteString, name]) + let copied = destination.appendingPathComponent(name) + XCTAssertEqual(try Data(contentsOf: copied), bytes) + try Data([0, 255, 128]).write(to: source) + _ = try call("copyToUri", [source.path, destination.path, name]) + XCTAssertEqual(try Data(contentsOf: copied), Data([0, 255, 128])) + XCTAssertThrowsError(try call("copyToUri", [directory.appendingPathComponent("missing").path, destination.path, name])) + XCTAssertEqual(try Data(contentsOf: copied), Data([0, 255, 128])) + XCTAssertThrowsError(try call("copyToUri", [copied.path, destination.path, name])) + XCTAssertThrowsError(try call("copyToUri", [source.path, destination.path, "../escape"])) + XCTAssertThrowsError(try call("copyToUri", [directory.path, destination.path, name])) + XCTAssertEqual(try files.manager.contentsOfDirectory(atPath: destination.path), [name]) + } + + func testPackagedAssetExtractionMatchesBundleAndRejectsTraversal() throws { + let destination = directory.appendingPathComponent("asset.html") + _ = try call("extractAsset", ["bundle/index.html", destination.path]) + XCTAssertEqual(try Data(contentsOf: destination), try Data(contentsOf: files.application.appendingPathComponent("bundle/index.html"))) + XCTAssertThrowsError(try call("extractAsset", ["../Library/test", destination.path])) + XCTAssertThrowsError(try call("extractAsset", ["bundle/index.html", "/etc/acode-test"])) + XCTAssertThrowsError(try call("extractAsset", ["not-a-bundled-asset", destination.path])) + } + + private func call(_ action: String, _ args: [Any]) throws -> Any? { try SystemFiles.perform(action, args: args) } +} + +@MainActor +final class SystemFileBridgeTests: BridgeTestCase { + func testAndroidEditAndRunIntentsRejectWithoutPresentingAShareSheet() async throws { + let webView = try await appWebView() + let result = try await webView.callAsyncJavaScript(""" + for(const action of ['EDIT','RUN']) { + const error=await new Promise(resolve=>system.fileAction('file:///missing.txt','missing.txt',action,'text/plain',resolve)); + if(error?.code!=='UNSUPPORTED_ACTION')throw Error('Unsupported intent did not reject'); + } + return true; + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + XCTAssertNil(webView.window?.rootViewController?.presentedViewController) + } + + func testPublicUtilitiesRetainAndroidResultShapesAndFileContents() async throws { + let webView = try await editorWebView() + let directory = AppFiles.shared.cache.appendingPathComponent("ios-system-bridge-" + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + let result = try await webView.callAsyncJavaScript(""" + const call=(action,...args)=>new Promise((resolve,reject)=>system[action](...args,resolve,reject)); + await call('mkdirs',root+'/nested'); + const path=root+'/nested/test # 日本語.txt'; + if(await call('writeText',path,'Acode ✓')!=='File written successfully')throw Error('Write result changed'); + if(await call('fileExists',path,false)!==1)throw Error('Existence result changed'); + if(await call('getParentPath',path)!==root+'/nested')throw Error('Incorrect parent'); + const children=await call('listChildren',root+'/nested'); + if(children.length!==1||children[0]!==path)throw Error('Incorrect children'); + if((await call('listChildren',root+'/missing')).length)throw Error('Missing directory should be empty'); + if((await call('listChildren',path)).length)throw Error('File should not list children'); + const fs=acode.require('fsOperation'); + const uri='file://'+path; + if(await fs(uri).readFile('utf-8')!=='Acode ✓\\n')throw Error('Write line terminator changed'); + try{await call('mkdirs',root+'/nested');throw Error('Existing directory accepted');} + catch(error){if(error==='Existing directory accepted'||error?.message==='Existing directory accepted')throw error;} + await call('deleteFile',path); + if(await call('fileExists',path,false)!==0)throw Error('Delete failed'); + await call('deleteFile',root+'/nested'); + return true; + """, arguments: ["root": directory.standardizedFileURL.resolvingSymlinksInPath().path], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } +} diff --git a/platforms/ios/runnerTests/SystemUITests.swift b/platforms/ios/runnerTests/SystemUITests.swift new file mode 100644 index 0000000000..616eff79e1 --- /dev/null +++ b/platforms/ios/runnerTests/SystemUITests.swift @@ -0,0 +1,174 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class SystemUITests: BridgeTestCase { + func testInputModesPreserveFieldsAndRestorePromptDefaults() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(""" + const call=(service,action,args)=>new Promise((resolve,reject)=>Bridge.exec(resolve,reject,service,action,args)); + const field=document.createElement('input');field.type='email';field.autocomplete='email';field.setAttribute('autocorrect','on'); + document.body.append(field); + try { + await call('System','set-input-type',['NO_SUGGESTIONS_AGGRESSIVE']); + if(field.getAttribute('autocorrect')!=='off'||field.getAttribute('writingsuggestions')!=='false') throw Error('Suggestions not disabled'); + if(field.type!=='email'||field.autocomplete!=='email') throw Error('Input semantics changed'); + await call('System','set-input-type',['NORMAL']); + if(field.getAttribute('autocorrect')!=='on'||field.hasAttribute('writingsuggestions')) throw Error('Prompt defaults not restored'); + await call('Native','setKeyboardSuggestionsEnabled',[false]); + if(field.getAttribute('autocorrect')!=='off') throw Error('Native compatibility API ignored'); + for(const [type,options,capitalize] of [['filename',{},'off'],['text',{},'on'],['filename',{capitalize:true},'on']]) { + const result=acode.require('prompt')('Input fixture','ios-file.txt',type,options); + const dialog=document.querySelector('.prompt:not(.hide)'), input=dialog.querySelector('input'); + try { + await call('System','set-input-type',['NORMAL']); + if(input.getAttribute('autocapitalize')!==capitalize)throw Error('Prompt capitalization changed: '+type); + if(type==='filename'&&(input.getAttribute('autocorrect')!=='off'||input.getAttribute('spellcheck')!=='false'||input.getAttribute('writingsuggestions')!=='false'))throw Error('Filename correction remained enabled'); + if(type==='text'&&(input.hasAttribute('autocorrect')||input.hasAttribute('writingsuggestions')))throw Error('Text prompt defaults changed'); + } finally {dialog.querySelector('button[type="button"]').click();await result;} + } + return true; + } finally {field.remove();await call('System','set-input-type',[acode.require('settings').value.keyboardMode]);} + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + func testNativeMenuPolicyPreservesDOMSelectionAndStatusBarCanBeHidden() async throws { + let app = try await appWebView() + let webView = try XCTUnwrap(app as? AppWebView) + let scene = try XCTUnwrap(webView.window?.windowScene) + let result = try await webView.callAsyncJavaScript(""" + const field=document.createElement('div');field.contentEditable='true';field.textContent='selected code';document.body.append(field); + const range=document.createRange();range.selectNodeContents(field); + const selection=getSelection();selection.removeAllRanges();selection.addRange(range); + await new Promise((resolve,reject)=>system.setNativeContextMenuDisabled(true,resolve,reject)); + const retained=selection.toString()==='selected code'&&field.isContentEditable; + field.remove();selection.removeAllRanges();return retained; + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + XCTAssertTrue(webView.nativeContextMenuDisabled) + defer { webView.nativeContextMenuDisabled = false } + try await call(webView, service: "SystemBarPlugin", action: "setStatusBarVisible", args: [false]) + try await Task.sleep(for: .milliseconds(300)) + let hidden = scene.statusBarManager?.isStatusBarHidden + try await call(webView, service: "SystemBarPlugin", action: "setStatusBarVisible", args: [true]) + XCTAssertEqual(hidden, true) + try await call(webView, action: "set-native-context-menu-disabled", args: ["false"]) + XCTAssertFalse(webView.nativeContextMenuDisabled) + XCTAssertTrue(webView.configuration.preferences.isTextInteractionEnabled) + } + + func testFullscreenOrientationRequiresSessionAndRestoresPolicyOnExit() async throws { + let webView = try await editorWebView() + let scene = try XCTUnwrap(webView.window?.windowScene) + XCTAssertTrue(webView.configuration.preferences.isElementFullscreenEnabled) + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let controller = try XCTUnwrap(responder as? WebViewController) + let rejected = try await webView.callAsyncJavaScript(""" + const orientation=acode.require('orientation'); + try {await orientation.lock('landscape');return false;}catch{return true;} + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(rejected, true) + do { + _ = try await webView.callAsyncJavaScript(""" + const target=document.createElement('div');target.id='ios-fullscreen-fixture';target.textContent='Fullscreen fixture';document.body.append(target); + await target.requestFullscreen();return !!document.fullscreenElement; + """, arguments: [:], in: nil, contentWorld: .page) + for _ in 0..<100 { + if controller.fullscreen.isFullscreen { break } + try await Task.sleep(for: .milliseconds(20)) + } + XCTAssertTrue(controller.fullscreen.isFullscreen) + XCTAssertEqual(webView.fullscreenState, .notInFullscreen) + XCTAssertTrue(controller.prefersStatusBarHidden) + XCTAssertTrue(controller.prefersHomeIndicatorAutoHidden) + XCTAssertEqual(webView.convert(webView.bounds, to: controller.view), controller.view.bounds) + XCTAssertGreaterThan(webView.bounds.width, 300) + XCTAssertGreaterThan(webView.bounds.height, 300) + try await checkOrientation(webView, scene: scene, controller: controller) + _ = try await webView.callAsyncJavaScript("await document.exitFullscreen()", arguments: [:], in: nil, contentWorld: .page) + for _ in 0..<100 { + if !controller.fullscreen.isFullscreen { break } + try await Task.sleep(for: .milliseconds(20)) + } + XCTAssertNil(AppDelegate.shared?.fullscreenOrientation) + XCTAssertNil(controller.fullscreen.requestedOrientation) + controller.view.layoutIfNeeded() + let frame = webView.convert(webView.bounds, to: controller.view) + XCTAssertEqual(frame.minX, controller.view.safeAreaInsets.left, accuracy: 1) + XCTAssertEqual(webView.frame.width, controller.view.safeAreaLayoutGuide.layoutFrame.width, accuracy: 1) + XCTAssertGreaterThan(webView.frame.height, 300) + } catch { + controller.fullscreen.reset() + _ = try? await webView.callAsyncJavaScript("if(document.fullscreenElement)await document.exitFullscreen();document.getElementById('ios-fullscreen-fixture')?.remove()", arguments: [:], in: nil, contentWorld: .page) + throw error + } + _ = try await webView.evaluateJavaScript("document.getElementById('ios-fullscreen-fixture')?.remove()") + let backRequiresFullscreen = try await webView.callAsyncJavaScript(""" + const call=enabled=>new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'System','set-fullscreen-back-handler',[enabled])); + await call(false);try {await call(true);return false;}catch{return true;} + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(backRequiresFullscreen, true) + } + + func testThemeAppliesSystemBarBackgroundColor() async throws { + let webView = try await editorWebView() + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let controller = try XCTUnwrap(responder as? WebViewController) + let color = controller.view.backgroundColor + let type = controller.themeType + // The startup theme timer must not overwrite direct bridge color checks. + _ = try await webView.evaluateJavaScript("window.systemThemeFixture=system.setUiTheme;system.setUiTheme=()=>{};true") + addTeardownBlock { @MainActor in + _ = try await webView.evaluateJavaScript("system.setUiTheme=window.systemThemeFixture;delete window.systemThemeFixture") + if let color { controller.setSystemBarColor(color) } + controller.setThemeType(type) + } + + let theme: [String: Any] = ["name": "Fixture", "type": "dark", "version": "free"] + try await call(webView, action: "set-ui-theme", args: ["#f8f9fa", theme]) + XCTAssertEqual(controller.view.backgroundColor, UIColor(hexString: "#f8f9fa")) + + // Dialog darkening sends the darkened color as the first argument. + try await call(webView, action: "set-ui-theme", args: ["#101010", theme]) + XCTAssertEqual(controller.view.backgroundColor, UIColor(hexString: "#101010")) + + try await call(webView, service: "SystemBarPlugin", action: "setStatusBarBackgroundColor", args: [1, 2, 3]) + XCTAssertEqual(controller.view.backgroundColor, UIColor(red: 1.0 / 255, green: 2.0 / 255, blue: 3.0 / 255, alpha: 1)) + } + + private func call(_ webView: WKWebView, service: String = "System", action: String, args: [Any]) async throws { + _ = try await webView.callAsyncJavaScript("await new Promise((resolve,reject)=>Bridge.exec(resolve,reject,service,action,args))", arguments: ["service": service, "action": action, "args": args], in: nil, contentWorld: .page) + } + + private func checkOrientation(_ webView: WKWebView, scene: UIWindowScene, controller: WebViewController) async throws { + let result = try await webView.callAsyncJavaScript(""" + try { await acode.require('orientation').lock('landscape'); return ''; } + catch(error) { return error.message; } + """, arguments: [:], in: nil, contentWorld: .page) as? String + let error = try XCTUnwrap(result) + if !error.isEmpty { + XCTAssertEqual(UIDevice.current.userInterfaceIdiom, .pad) + XCTAssertTrue(error.contains("windowing mode"), error) + XCTAssertNil(AppDelegate.shared?.fullscreenOrientation) + XCTAssertNil(controller.fullscreen.requestedOrientation) + XCTAssertTrue(controller.fullscreen.isFullscreen) + _ = try await webView.callAsyncJavaScript("await acode.require('orientation').unlock()", arguments: [:], in: nil, contentWorld: .page) + XCTAssertNil(AppDelegate.shared?.fullscreenOrientation) + return + } + XCTAssertTrue(scene.effectiveGeometry.interfaceOrientation.isLandscape) + XCTAssertEqual(AppDelegate.shared?.fullscreenOrientation, .landscape) + NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil) + XCTAssertNil(AppDelegate.shared?.fullscreenOrientation) + XCTAssertEqual(controller.fullscreen.requestedOrientation, .landscape) + NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil) + XCTAssertEqual(AppDelegate.shared?.fullscreenOrientation, .landscape) + _ = try await webView.callAsyncJavaScript("await acode.require('orientation').lock('portrait');await acode.require('orientation').unlock()", arguments: [:], in: nil, contentWorld: .page) + XCTAssertNil(AppDelegate.shared?.fullscreenOrientation) + _ = try await webView.callAsyncJavaScript("await acode.require('orientation').lock('portrait')", arguments: [:], in: nil, contentWorld: .page) + } +} diff --git a/platforms/ios/runnerTests/SystemUtilityBridgeTests.swift b/platforms/ios/runnerTests/SystemUtilityBridgeTests.swift new file mode 100644 index 0000000000..4bf3737f6e --- /dev/null +++ b/platforms/ios/runnerTests/SystemUtilityBridgeTests.swift @@ -0,0 +1,25 @@ +import XCTest + +@MainActor +final class SystemUtilityBridgeTests: BridgeTestCase { + func testLegacyChecksumAndCacheActionsPreserveTheirPublicContract() async throws { + let webView = try await appWebView() + let result = try await webView.callAsyncJavaScript(""" + const call=(action,args=[])=>new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'System',action,args)); + for(const text of ['', 'Acode ✓ 日本語']) { + const bytes=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(text)); + const expected=[...new Uint8Array(bytes)].map(n=>n.toString(16).padStart(2,'0')).join(''); + if(await call('checksumText',[text])!==expected)throw Error('Checksum mismatch'); + } + const key='ios-cache-fixture-'+crypto.randomUUID(); + try { + localStorage.setItem(key,'retain'); + if(await call('clear-cache')!=='Cache cleared')throw Error('Cache response changed'); + if(localStorage.getItem(key)!=='retain')throw Error('Cache clearing removed app data'); + await call('clearCache'); + return true; + }finally{localStorage.removeItem(key);} + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } +} diff --git a/platforms/ios/runnerTests/TerminalServerOriginTests.swift b/platforms/ios/runnerTests/TerminalServerOriginTests.swift new file mode 100644 index 0000000000..626c6423cc --- /dev/null +++ b/platforms/ios/runnerTests/TerminalServerOriginTests.swift @@ -0,0 +1,17 @@ +import XCTest +@testable import runner + +final class TerminalServerOriginTests: XCTestCase { + func testAllowsAppPagesAndCallersWithoutAnOrigin() { + XCTAssertTrue(TerminalServer.allows(origin: nil)) + XCTAssertTrue(TerminalServer.allows(origin: "acode://localhost")) + XCTAssertTrue(TerminalServer.allows(origin: "https://localhost")) + } + + func testRejectsPreviewBrowserAndOpaqueOrigins() { + XCTAssertFalse(TerminalServer.allows(origin: "http://localhost:8158")) + XCTAssertFalse(TerminalServer.allows(origin: "https://example.com")) + XCTAssertFalse(TerminalServer.allows(origin: "null")) + XCTAssertFalse(TerminalServer.allows(origin: "acode://localhost, https://example.com")) + } +} diff --git a/platforms/ios/runnerTests/TextComparisonTests.swift b/platforms/ios/runnerTests/TextComparisonTests.swift new file mode 100644 index 0000000000..0eab52f394 --- /dev/null +++ b/platforms/ios/runnerTests/TextComparisonTests.swift @@ -0,0 +1,48 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class TextComparisonTests: BridgeTestCase { + func testTextComparisonDetectsUnicodeNormalizationChanges() async throws { + let app = try await editorWebView() + let result = try await app.callAsyncJavaScript(""" + const pairs=[['é','e\\u0301'],['Å','A\\u030a'],['가','\\u1100\\u1161'],['a\\u0323\\u0301','a\\u0301\\u0323']]; + const failures=[]; + for(const [original,changed] of pairs){ + if(!await system.compareTexts(original,changed))failures.push('Missed change: '+JSON.stringify([original,changed])); + if(await system.compareTexts(original,original))failures.push('Identical text changed'); + } + if(await system.compareTexts(null,''))failures.push('Null did not default to empty text'); + if(await system.compareTexts('emoji 🧑‍💻\\r\\n','emoji 🧑‍💻\\r\\n'))failures.push('Identical emoji changed'); + if(!await system.compareTexts('line\\r\\n','line\\n'))failures.push('Missed line-ending change'); + return failures; + """, arguments: [:], in: nil, contentWorld: .page) as? [String] + XCTAssertEqual(result, []) + } + + func testFileComparisonPreservesExactDecodedTextAcrossEncodings() async throws { + let app = try await editorWebView() + let directory = AppFiles.shared.cache.appendingPathComponent("text-comparison-" + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let original = "café 🧑‍💻\r\n" + for encoding in ["UTF-8", "UTF-16LE", "UTF-16BE"] { + let file = directory.appendingPathComponent(encoding + ".txt") + let bytes = try XCTUnwrap(original.data(using: FileContents.encoding(encoding))) + try bytes.write(to: file) + let result = try await app.callAsyncJavaScript(""" + const changed=original.normalize('NFD'); + if(encoding==='UTF-8' && await system.compareFileText(uri,'',original))throw Error('Empty encoding did not use UTF-8'); + return { + equal:await system.compareFileText(uri,encoding,original), + changed:await system.compareFileText(uri,encoding,changed), + lineEnding:await system.compareFileText(uri,encoding,original.replace('\\r\\n','\\n')) + }; + """, arguments: ["uri": "file://" + file.path, "encoding": encoding, "original": original], in: nil, contentWorld: .page) as? [String: Bool] + XCTAssertEqual(result?["equal"], false, encoding) + XCTAssertEqual(result?["changed"], true, encoding) + XCTAssertEqual(result?["lineEnding"], true, encoding) + } + } +} diff --git a/platforms/ios/runnerTests/TrackingAuthorizationTests.swift b/platforms/ios/runnerTests/TrackingAuthorizationTests.swift new file mode 100644 index 0000000000..30b77978ec --- /dev/null +++ b/platforms/ios/runnerTests/TrackingAuthorizationTests.swift @@ -0,0 +1,193 @@ +import AppTrackingTransparency +import UIKit +import XCTest +@testable import runner + +@MainActor +final class TrackingAuthorizationTests: XCTestCase { + private var appActive = false + + func testTrackingWaitsForActiveAppAndCoalescesRequests() async { + appActive = false + var calls = 0 + var callback: ((ATTrackingManager.AuthorizationStatus) -> Void)? + let notifications = NotificationCenter() + let requested = expectation(description: "ATT requested in foreground") + let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { self.appActive }, + notifications: notifications, request: { calls += 1; callback = $0; requested.fulfill() }) + let finished = expectation(description: "Both callers receive the decision") + finished.expectedFulfillmentCount = 2 + for _ in 0..<2 { + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .denied) + finished.fulfill() + } + } + XCTAssertEqual(calls, 0) + appActive = true + notifications.post(name: UIApplication.didBecomeActiveNotification, object: nil) + await fulfillment(of: [requested], timeout: 2) + XCTAssertEqual(calls, 1) + callback?(.denied) + await fulfillment(of: [finished], timeout: 2) + } + + func testExistingTrackingDecisionsDoNotPromptAgain() { + for status: ATTrackingManager.AuthorizationStatus in [.denied, .restricted, .authorized] { + let tracking = AMBTrackingAuthorization(status: { status }, isActive: { false }, request: { _ in + XCTFail("A decided permission must not prompt again") + }) + var result: ATTrackingManager.AuthorizationStatus? + tracking.authorize { result = try? $0.get() } + XCTAssertEqual(result, status) + } + } + + func testUndeterminedResultCannotStartAdsAndAllowsRetry() async { + var calls = 0 + let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { true }, request: { + calls += 1 + $0(calls == 1 ? .notDetermined : .authorized) + }) + let failed = expectation(description: "No ad startup without ATT decision") + tracking.authorize { result in + if case .success = result { XCTFail("Unresolved ATT must not initialize ads") } + failed.fulfill() + } + await fulfillment(of: [failed], timeout: 2) + let retried = expectation(description: "Retry succeeds") + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .authorized) + retried.fulfill() + } + await fulfillment(of: [retried], timeout: 2) + XCTAssertEqual(calls, 2) + } + + func testResetCancelsCallerWithoutStartingAnOverlappingTrackingRequest() async { + var requests = 0 + var reply: (@Sendable (ATTrackingManager.AuthorizationStatus) -> Void)? + let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { true }, request: { + requests += 1 + reply = $0 + }) + var cancelled = false + tracking.authorize { result in + if case .failure = result { cancelled = true } + } + tracking.cancel() + XCTAssertTrue(cancelled) + let completed = expectation(description: "New caller receives the outstanding OS decision") + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .denied) + completed.fulfill() + } + XCTAssertEqual(requests, 1) + reply?(.denied) + await fulfillment(of: [completed], timeout: 2) + } + + func testDeadlineFailsWaitersWithoutOverlappingOSRequestAndLateReplyCanRecover() async { + var calls = 0 + var reply: (@Sendable (ATTrackingManager.AuthorizationStatus) -> Void)? + let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { true }, + timeout: .milliseconds(25), request: { calls += 1; reply = $0 }) + let timedOut = expectation(description: "Both callers time out without a decision") + timedOut.expectedFulfillmentCount = 2 + for _ in 0..<2 { + tracking.authorize { result in + if case .success = result { XCTFail("Timeout is not authorization") } + timedOut.fulfill() + } + } + await fulfillment(of: [timedOut], timeout: 2) + let recovered = expectation(description: "Retry uses the outstanding OS request") + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .denied) + recovered.fulfill() + } + XCTAssertEqual(calls, 1) + reply?(.denied) + await fulfillment(of: [recovered], timeout: 2) + } + + func testDeadlineReadsDeterminedOSStatusWhenReplyIsLost() async { + var current = ATTrackingManager.AuthorizationStatus.notDetermined + var calls = 0 + let tracking = AMBTrackingAuthorization(status: { current }, isActive: { true }, + timeout: .milliseconds(25), request: { _ in calls += 1 }) + let completed = expectation(description: "Deadline uses OS status, not a fabricated decision") + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .restricted) + completed.fulfill() + } + current = .restricted + await fulfillment(of: [completed], timeout: 2) + XCTAssertEqual(calls, 1) + } + + func testForegroundRechecksOSStatusEvenWithAnOutstandingRequest() async { + var current = ATTrackingManager.AuthorizationStatus.notDetermined + let notifications = NotificationCenter() + let tracking = AMBTrackingAuthorization(status: { current }, isActive: { true }, + notifications: notifications, request: { _ in }) + let completed = expectation(description: "Foreground sees the lost callback's decision") + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .denied) + completed.fulfill() + } + current = .denied + notifications.post(name: UIApplication.didBecomeActiveNotification, object: nil) + await fulfillment(of: [completed], timeout: 2) + } + + func testInactiveWaitIsBoundedAndCanRetryWhenActive() async { + appActive = false + var calls = 0 + let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { self.appActive }, + timeout: .milliseconds(25), request: { calls += 1; $0(.denied) }) + let timedOut = expectation(description: "Inactive wait times out") + tracking.authorize { result in + if case .success = result { XCTFail("Inactive timeout must not start ads") } + timedOut.fulfill() + } + await fulfillment(of: [timedOut], timeout: 2) + XCTAssertEqual(calls, 0) + appActive = true + let completed = expectation(description: "Active retry succeeds") + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .denied) + completed.fulfill() + } + await fulfillment(of: [completed], timeout: 2) + XCTAssertEqual(calls, 1) + } + + func testCancelledRequestCanRecoverFromOSStatusAndStaleReplyCannotSettleNewRequest() async { + var current = ATTrackingManager.AuthorizationStatus.notDetermined + var replies: [@Sendable (ATTrackingManager.AuthorizationStatus) -> Void] = [] + let tracking = AMBTrackingAuthorization(status: { current }, isActive: { true }, request: { replies.append($0) }) + var cancelled = false + tracking.authorize { result in + if case .failure = result { cancelled = true } + } + tracking.cancel() + XCTAssertTrue(cancelled) + current = .denied + var recovered: ATTrackingManager.AuthorizationStatus? + tracking.authorize { recovered = try? $0.get() } + XCTAssertEqual(recovered, .denied) + XCTAssertEqual(replies.count, 1) + + current = .notDetermined + let completed = expectation(description: "Only the new OS request settles the new caller") + tracking.authorize { result in + XCTAssertEqual(try? result.get(), .restricted) + completed.fulfill() + } + XCTAssertEqual(replies.count, 2) + replies[0](.authorized) + replies[1](.restricted) + await fulfillment(of: [completed], timeout: 2) + } +} diff --git a/platforms/ios/runnerTests/WebContextMenuTests.swift b/platforms/ios/runnerTests/WebContextMenuTests.swift new file mode 100644 index 0000000000..42acb1fae6 --- /dev/null +++ b/platforms/ios/runnerTests/WebContextMenuTests.swift @@ -0,0 +1,98 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class WebContextMenuTests: XCTestCase { + func testNativeConfigurationPreservesTouchDeliveryAndCoversAllFrames() { + let view = WKWebView() + let menu = WebContextMenu(webView: view) + XCTAssertTrue(view.gestureRecognizers?.contains(menu.gesture) == true) + XCTAssertEqual(menu.gesture.minimumPressDuration, 0.45) + XCTAssertEqual(menu.gesture.allowableMovement, 10) + XCTAssertFalse(menu.gesture.cancelsTouchesInView) + XCTAssertTrue(menu.gestureRecognizer(menu.gesture, shouldRecognizeSimultaneouslyWith: UIPanGestureRecognizer())) + let script = view.configuration.userContentController.userScripts.first + XCTAssertEqual(script?.injectionTime, .atDocumentStart) + XCTAssertEqual(script?.isForMainFrameOnly, false) + let preview = PreviewViewController(url: URL(string: "about:blank")!, theme: [:], console: false) + XCTAssertTrue(preview.webView.configuration.userContentController.userScripts.contains { $0.source == WebContextMenu.script }) + } + + func testNativeDispatchUsesTheDOMTargetAndKeepsProgrammaticClicksWorking() async throws { + let view = WKWebView(frame: CGRect(x: 0, y: 0, width: 400, height: 600)) + let menu = WebContextMenu(webView: view) + view.loadHTMLString(""" + + + Link + +
+ + + """, baseURL: nil) + try await waitFor(view, "typeof window.press==='function' && !!document.querySelector('iframe').contentWindow.acodeNativeContextMenu") + for name in ["button", "link", "input", "shadow-button"] { + _ = try await view.callAsyncJavaScript(""" + const target=document.getElementById(name)||document.getElementById('host').shadowRoot.getElementById(name); + await press(target); + """, arguments: ["name": name], in: nil, contentWorld: .page) + menu.send() + try await waitFor(view, "events.some(event=>event.id==='\(name)')") + if name == "link" { + let callout = try await view.evaluateJavaScript("document.getElementById('link').style.getPropertyValue('-webkit-touch-callout')") as? String + XCTAssertEqual(callout, "none") + } + } + let result = try await view.evaluateJavaScript("({events,clicks,input:document.getElementById('input').value})") as? [String: Any] + let events = try XCTUnwrap(result?["events"] as? [[String: Any]]) + XCTAssertEqual(events.compactMap { $0["id"] as? String }, ["button", "link", "input", "shadow-button"]) + XCTAssertTrue(events.allSatisfy { ($0["x"] as? Int) == 20 && ($0["y"] as? Int) == 30 && ($0["button"] as? Int) == 2 && ($0["bubbles"] as? Bool) == true }) + XCTAssertEqual(result?["clicks"] as? Int, 4) + XCTAssertEqual(result?["input"] as? String, "unchanged") + let styles = try await view.evaluateJavaScript(""" + (()=>{const link=document.getElementById('link'); + link.dispatchEvent(new PointerEvent('pointerdown',{bubbles:true,pointerType:'touch',isPrimary:true,pointerId:1})); + link.dispatchEvent(new PointerEvent('pointerup',{bubbles:true,pointerType:'touch',isPrimary:true,pointerId:1})); + return {value:link.style.getPropertyValue('-webkit-touch-callout'),priority:link.style.getPropertyPriority('-webkit-touch-callout')};})(); + """) as? [String: String] + XCTAssertEqual(styles?["value"], "default") + XCTAssertEqual(styles?["priority"], "important") + _ = try await view.callAsyncJavaScript(""" + const frame=document.querySelector('iframe').contentWindow; + frame.events=[]; + frame.document.addEventListener('contextmenu',event=>frame.events.push(event.target.id)); + frame.document.getElementById('frame-button').dispatchEvent(new frame.PointerEvent('pointerdown',{ + bubbles:true,pointerType:'touch',isPrimary:true,pointerId:1})); + await new Promise(resolve=>setTimeout(resolve,500)); + """, arguments: [:], in: nil, contentWorld: .page) + menu.send() + try await waitFor(view, "document.querySelector('iframe').contentWindow.events.length===1") + let frameEvents = try await view.evaluateJavaScript("document.querySelector('iframe').contentWindow.events") as? [String] + XCTAssertEqual(frameEvents, ["frame-button"]) + } + + private func waitFor(_ view: WKWebView, _ expression: String) async throws { + for _ in 0..<100 { + if (try? await view.evaluateJavaScript(expression)) as? Bool == true { return } + try await Task.sleep(for: .milliseconds(50)) + } + XCTFail("WebView did not settle: \(expression)") + throw NSError(domain: "WebContextMenuTests", code: 1) + } +} diff --git a/platforms/ios/runnerTests/WebFullscreenMenuTests.swift b/platforms/ios/runnerTests/WebFullscreenMenuTests.swift new file mode 100644 index 0000000000..57aa21396a --- /dev/null +++ b/platforms/ios/runnerTests/WebFullscreenMenuTests.swift @@ -0,0 +1,50 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class WebFullscreenMenuTests: BridgeTestCase { + func testRepeatedBackDismissesMenuAfterFocusMovesOutsideIt() async throws { + let webView = try await editorWebView() + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + let controller = try XCTUnwrap(responder as? WebViewController) + _ = try await webView.callAsyncJavaScript(""" + const owner=document.createElement('div');owner.id='back-menu-fixture';document.body.append(owner); + const shadow=owner.attachShadow({mode:'open'}); + shadow.innerHTML=''; + const menu=shadow.querySelector('section'); + owner.addEventListener('keydown',event=>{ + if(event.key==='Escape'&&!menu.hidden){menu.hidden=true;event.preventDefault();} + }); + await owner.requestFullscreen(); + window.fixtureBackCount=0; + await acode.require('fullscreen').setBackHandler(()=>{window.fixtureBackCount++;menu.hidden=false;menu.querySelector('button').focus();}); + """, arguments: [:], in: nil, contentWorld: .page) + do { + for _ in 0..<3 { + controller.fullscreen.back() + try await wait(webView, hidden: false) + _ = try await webView.evaluateJavaScript("document.getElementById('back-menu-fixture').shadowRoot.getElementById('game').focus()") + controller.fullscreen.back() + try await wait(webView, hidden: true) + XCTAssertTrue(controller.fullscreen.isFullscreen) + } + let count = try await webView.evaluateJavaScript("window.fixtureBackCount") as? Int + XCTAssertEqual(count, 3, "Dismissal called Pause again instead of closing the menu") + } catch { + _ = try? await webView.callAsyncJavaScript("await document.exitFullscreen();document.getElementById('back-menu-fixture')?.remove();delete window.fixtureBackCount", arguments: [:], in: nil, contentWorld: .page) + throw error + } + _ = try await webView.callAsyncJavaScript("await document.exitFullscreen();document.getElementById('back-menu-fixture').remove();delete window.fixtureBackCount", arguments: [:], in: nil, contentWorld: .page) + } + + private func wait(_ webView: WKWebView, hidden: Bool) async throws { + for _ in 0..<100 { + let actual = try await webView.evaluateJavaScript("document.getElementById('back-menu-fixture').shadowRoot.querySelector('section').hidden") as? Bool + if actual == hidden { return } + try await Task.sleep(for: .milliseconds(20)) + } + throw NSError(domain: "FullscreenMenuTests", code: 1, userInfo: [NSLocalizedDescriptionKey: "Back did not toggle menu visibility"]) + } +} diff --git a/platforms/ios/runnerTests/WebFullscreenTests.swift b/platforms/ios/runnerTests/WebFullscreenTests.swift new file mode 100644 index 0000000000..18c7597c94 --- /dev/null +++ b/platforms/ios/runnerTests/WebFullscreenTests.swift @@ -0,0 +1,203 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class WebFullscreenTests: BridgeTestCase { + func testShadowFullscreenPreservesIframeAndHitTargetsAcrossRepeatedEntryAndExit() async throws { + let webView = try await editorWebView() + let parent = webView.superview + let fixture = AppFiles.shared.cache.appendingPathComponent("fullscreen-touch.html") + try Data("".utf8).write(to: fixture) + defer { try? FileManager.default.removeItem(at: fixture) } + let result = try await webView.callAsyncJavaScript(""" + const host=document.createElement('div');host.style.cssText='transform:translate(40px,80px);width:100px;height:100px;overflow:hidden';document.body.append(host); + const shadow=host.attachShadow({mode:'open'}); + const style=document.createElement('style'); + style.textContent=':host(:fullscreen){color:rgb(0,255,0)} section:fullscreen{background:rgb(0,255,0)} section:not(:fullscreen){background:rgb(255,0,0)}'; + const target=document.createElement('section'); + target.style.cssText='position:absolute!important;left:30px!important;width:80px!important;height:70px!important;margin:12px;padding:9px;border:3px solid red;transform:translateX(5px)'; + shadow.append(style,target); + const iframe=document.createElement('iframe');iframe.allowFullscreen=true;iframe.style.cssText='width:100%;height:100%;border:0'; + const ready=new Promise(r=>iframe.onload=r); + iframe.src='acode://localhost/__cache__/fullscreen-touch.html'; + target.append(iframe);await Promise.race([ready,new Promise((resolve,reject)=>setTimeout(()=>reject(Error('Iframe fixture failed to load')),5000))]); + const original=iframe.contentWindow.document;original.body.dataset.retained='yes'; + if(!original.fullscreenEnabled||typeof original.body.requestFullscreen!=='function')throw Error('Iframe fullscreen API is unavailable'); + try { + for(let n=0;n<3;n++) { + await target.requestFullscreen(); + const rect=target.getBoundingClientRect(); + if(document.fullscreenElement!==host||shadow.fullscreenElement!==target)throw Error('Shadow owner was not retargeted'); + if(rect.x!==0||rect.y!==0||rect.width!==innerWidth||rect.height!==innerHeight)throw Error('Fullscreen viewport mismatch: '+JSON.stringify(rect)); + if(getComputedStyle(target).backgroundColor!=='rgb(0, 255, 0)'||getComputedStyle(host).color!=='rgb(0, 255, 0)')throw Error('Shadow fullscreen CSS did not apply'); + style.sheet.insertRule('section:fullscreen{background:rgb(0,0,255)}',style.sheet.cssRules.length); + if(getComputedStyle(target).backgroundColor!=='rgb(0, 0, 255)')throw Error('Dynamic fullscreen CSS did not apply'); + style.sheet.deleteRule(style.sheet.cssRules.length-1); + if(iframe.contentWindow.document!==original||original.body.dataset.retained!=='yes')throw Error('Iframe reloaded'); + const frame=iframe.getBoundingClientRect(),button=original.getElementById('touch').getBoundingClientRect(); + const x=button.x+button.width/2,y=button.y+button.height/2; + if(shadow.elementFromPoint(frame.x+x,frame.y+y)!==iframe||original.elementFromPoint(x,y).id!=='touch')throw Error('Touch target shifted'); + target.style.color='purple';target.style.setProperty('width','110px','important'); + await new Promise(r=>requestAnimationFrame(r)); + if(target.style.width!=='100%')throw Error('Plugin layout change escaped fullscreen'); + await document.exitFullscreen(); + if(target.style.width!=='110px'||target.style.height!=='70px'||target.style.left!=='30px'||target.style.marginTop!=='12px'||target.style.paddingTop!=='9px'||target.style.borderTopWidth!=='3px'||target.style.color!=='purple')throw Error('Plugin styles were lost on exit'); + if(getComputedStyle(target).backgroundColor!=='rgb(255, 0, 0)'||host.hasAttribute('data-acode-fullscreen'))throw Error('Fullscreen CSS remained active on exit'); + if(document.fullscreenElement||shadow.fullscreenElement||target.hasAttribute('popover'))throw Error('Fullscreen did not exit cleanly'); + } + await target.requestFullscreen(); + host.remove(); + for(let n=0;n<100&&target.hasAttribute('popover');n++)await new Promise(r=>setTimeout(r,20)); + if(target.hasAttribute('popover'))throw Error('Removed owner kept fullscreen'); + return true; + } finally {await document.exitFullscreen();host.remove();} + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + XCTAssertTrue(webView.superview === parent) + let controller = try controller(for: webView) + XCTAssertFalse(controller.fullscreen.isFullscreen) + XCTAssertNil(controller.fullscreen.requestedOrientation) + XCTAssertEqual(webView.fullscreenState, .notInFullscreen) + XCTAssertEqual(webView.frame.width, controller.view.safeAreaLayoutGuide.layoutFrame.width, accuracy: 1) + } + + func testNavigationRestoresNativeFullscreenAndStatusBarPreference() async throws { + let webView = try await editorWebView() + let controller = try controller(for: webView) + let hidden = controller.statusBarHidden + controller.statusBarHidden = true + defer { controller.statusBarHidden = hidden; controller.setThemeType(controller.themeType) } + _ = try await webView.callAsyncJavaScript("await document.body.requestFullscreen();await acode.require('fullscreen').setBackHandler(()=>{});", arguments: [:], in: nil, contentWorld: .page) + XCTAssertTrue(controller.fullscreen.isFullscreen) + XCTAssertTrue(controller.prefersStatusBarHidden) + webView.reload() + try await Task.sleep(for: .milliseconds(200)) + _ = try await editorWebView() + XCTAssertFalse(controller.fullscreen.isFullscreen) + XCTAssertNil(controller.fullscreen.requestedOrientation) + XCTAssertEqual(controller.statusBarHidden, true) + XCTAssertTrue(controller.prefersStatusBarHidden) + _ = try await webView.callAsyncJavaScript("await document.body.requestFullscreen()", arguments: [:], in: nil, contentWorld: .page) + controller.fullscreen.back() + try await wait(webView, until: "!document.fullscreenElement") + } + + func testBackControlsRouteToHandlerAndRestoreDefaultExitAfterRelease() async throws { + let webView = try await editorWebView() + let controller = try controller(for: webView) + let button = try XCTUnwrap(controller.view.subviews.compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "fullscreen-back" }) + let gesture = try XCTUnwrap(controller.view.gestureRecognizers?.compactMap { $0 as? UIScreenEdgePanGestureRecognizer }.first) + XCTAssertTrue(button.isHidden) + XCTAssertFalse(gesture.isEnabled) + let theme = controller.themeType + defer { controller.setThemeType(theme) } + _ = try await webView.callAsyncJavaScript(""" + window.fullscreenBackCount=0; + await document.body.requestFullscreen(); + await acode.require('fullscreen').setBackHandler(()=>window.fullscreenBackCount++); + """, arguments: [:], in: nil, contentWorld: .page) + controller.view.layoutIfNeeded() + XCTAssertTrue(button.isHidden) + XCTAssertTrue(gesture.isEnabled) + XCTAssertEqual(button.bounds.size, CGSize(width: 44, height: 44)) + XCTAssertEqual(button.frame.minX, controller.view.safeAreaInsets.left + 8, accuracy: 1) + XCTAssertEqual(button.frame.minY, controller.view.safeAreaInsets.top + 8, accuracy: 1) + XCTAssertEqual(button.accessibilityLabel, "Back") + controller.setThemeType("light") + XCTAssertEqual(button.overrideUserInterfaceStyle, .light) + controller.setThemeType("dark") + XCTAssertEqual(button.overrideUserInterfaceStyle, .dark) + button.sendActions(for: .touchUpInside) + try await wait(webView, until: "window.fullscreenBackCount===1") + _ = try await webView.callAsyncJavaScript("await acode.require('orientation').unlock()", arguments: [:], in: nil, contentWorld: .page) + controller.fullscreen.back() + try await wait(webView, until: "window.fullscreenBackCount===2") + NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil) + XCTAssertFalse(button.isEnabled) + XCTAssertFalse(gesture.isEnabled) + controller.fullscreen.back() + let pausedCount = try await webView.evaluateJavaScript("window.fullscreenBackCount") as? Int + XCTAssertEqual(pausedCount, 2) + NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil) + XCTAssertTrue(button.isEnabled) + XCTAssertTrue(gesture.isEnabled) + _ = try await webView.callAsyncJavaScript("await acode.require('fullscreen').setBackHandler(null)", arguments: [:], in: nil, contentWorld: .page) + button.sendActions(for: .touchUpInside) + try await wait(webView, until: "!document.fullscreenElement") + XCTAssertTrue(button.isHidden) + XCTAssertFalse(gesture.isEnabled) + _ = try await webView.callAsyncJavaScript("await document.body.requestFullscreen()", arguments: [:], in: nil, contentWorld: .page) + controller.fullscreen.back() + try await wait(webView, until: "!document.fullscreenElement") + } + + func testBackFailureCannotExitANewerFullscreenOwner() async throws { + let webView = try await editorWebView() + let controller = try controller(for: webView) + _ = try await webView.callAsyncJavaScript(""" + await document.body.requestFullscreen(); + await acode.require('fullscreen').setBackHandler(()=>{throw Error('fixture');}); + """, arguments: [:], in: nil, contentWorld: .page) + controller.fullscreen.back() + try await wait(webView, until: "!document.fullscreenElement") + _ = try await webView.callAsyncJavaScript(""" + await document.body.requestFullscreen(); + await acode.require('fullscreen').setBackHandler(()=>new Promise((resolve,reject)=>window.rejectFullscreenBack=reject)); + """, arguments: [:], in: nil, contentWorld: .page) + controller.fullscreen.back() + try await wait(webView, until: "!!window.rejectFullscreenBack") + let retained = try await webView.callAsyncJavaScript(""" + await document.exitFullscreen(); + const target=document.createElement('div');target.id='new-fullscreen-owner';document.body.append(target); + await target.requestFullscreen(); + window.fullscreenBackCount=0; + await acode.require('fullscreen').setBackHandler(()=>window.fullscreenBackCount++); + window.rejectFullscreenBack(Error('obsolete'));delete window.rejectFullscreenBack; + await new Promise(r=>setTimeout(r,50)); + return document.fullscreenElement===target; + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(retained, true) + controller.fullscreen.back() + try await wait(webView, until: "window.fullscreenBackCount===1") + _ = try await webView.callAsyncJavaScript("await document.exitFullscreen();document.getElementById('new-fullscreen-owner').remove()", arguments: [:], in: nil, contentWorld: .page) + } + + func testBackConsumesNativeDialogDismissalAndCancelledClose() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(""" + const owner=document.createElement('div'),dialog=document.createElement('dialog'); + owner.append(dialog);document.body.append(owner); + let calls=0,cancels=0,prevent=false; + dialog.addEventListener('cancel',event=>{cancels++;if(prevent)event.preventDefault();}); + try { + await owner.requestFullscreen(); + await acode.require('fullscreen').setBackHandler(()=>calls++); + for(const blocked of [false,true]) { + prevent=blocked;dialog.showModal(); + document.dispatchEvent(new Event('fullscreenbackbutton')); + await new Promise(r=>setTimeout(r,50)); + if(dialog.open!==blocked||calls!==0||document.fullscreenElement!==owner)throw Error('Dialog Back fell through to the game callback'); + dialog.close(); + } + if(cancels!==2)throw Error('Dialog cancel was delivered twice'); + return true; + } finally {dialog.close();await document.exitFullscreen();owner.remove();} + """, arguments: [:], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } + + private func wait(_ webView: WKWebView, until expression: String) async throws { + for _ in 0..<100 { + if (try await webView.evaluateJavaScript(expression)) as? Bool == true { return } + try await Task.sleep(for: .milliseconds(20)) + } + XCTFail("Fullscreen did not reach: " + expression) + } + + private func controller(for webView: WKWebView) throws -> WebViewController { + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + return try XCTUnwrap(responder as? WebViewController) + } +} diff --git a/platforms/ios/runnerTests/WebShadowCaretTests.swift b/platforms/ios/runnerTests/WebShadowCaretTests.swift new file mode 100644 index 0000000000..83b560a72f --- /dev/null +++ b/platforms/ios/runnerTests/WebShadowCaretTests.swift @@ -0,0 +1,90 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class WebShadowCaretTests: BridgeTestCase { + func testHostAndPluginWebViewsInstallTheFallbackAtDocumentStart() async throws { + let host = try await appWebView() + let plugin = PluginWebView(options: ["mode": "hidden"]) + defer { plugin.destroy() } + for view in [host, plugin.controller.webView] { + let scripts = view.configuration.userContentController + let installed = scripts.userScripts.filter { $0.source == WebShadowCaret.script } + XCTAssertEqual(installed.count, 1) + XCTAssertEqual(installed.first?.injectionTime, .atDocumentStart) + XCTAssertEqual(installed.first?.isForMainFrameOnly, false) + WebShadowCaret.install(on: scripts) + XCTAssertEqual(scripts.userScripts.filter { $0.source == WebShadowCaret.script }.count, 1) + } + } + + func testFinalCharacterDeletionRepeatedBackspaceAndTypingInShadowEditors() async throws { + let configuration = WKWebViewConfiguration() + configuration.websiteDataStore = .nonPersistent() + WebShadowCaret.install(on: configuration.userContentController) + let view = WKWebView(frame: CGRect(x: 0, y: 0, width: 400, height: 600), configuration: configuration) + view.loadHTMLString("", baseURL: nil) + for _ in 0..<100 { + if !view.isLoading, + (try? await view.evaluateJavaScript("document.querySelector('iframe')?.contentDocument?.readyState === 'complete'")) as? Bool == true { break } + try await Task.sleep(for: .milliseconds(50)) + } + let script = """ + (() => { + for (const doc of [document, document.querySelector('iframe').contentDocument]) { + if (doc.defaultView.Selection.prototype.addRange.name !== 'acodeShadowCaretAddRange') + throw Error('Missing document-start fallback'); + for (const mode of ['open', 'closed']) { + const host = doc.body.appendChild(doc.createElement('div')); + const shadow = host.attachShadow({mode}); + const editor = shadow.appendChild(doc.createElement('div')); + editor.contentEditable = 'true'; + editor.style.minHeight = '40px'; + // Reproduce an unmodified plugin that clears blank markup and resets its caret. + const cleanup = () => { + if (editor.textContent.trim()) return; + editor.replaceChildren(); + const range = doc.createRange(); + range.setStart(editor, 0); range.collapse(true); + const selection = doc.getSelection(); + selection.removeAllRanges(); selection.addRange(range); + }; + editor.addEventListener('input', cleanup); + editor.focus(); + doc.execCommand('insertText', false, 'x'); + if (editor.textContent !== 'x') throw Error(mode + ': initial typing failed'); + for (let n = 0; n < 3; n++) { + doc.execCommand('delete'); + if (editor.textContent || shadow.activeElement !== editor || !doc.getSelection().rangeCount) + throw Error(mode + ': caret lost after deletion ' + n); + } + doc.execCommand('insertText', false, 'again'); + if (editor.textContent !== 'again') throw Error(mode + ': typing again failed'); + const chip = doc.createElement('span'); + chip.contentEditable = 'false'; chip.dataset.chip = 'image'; chip.textContent = 'image'; + editor.prepend(chip); + const caret = doc.createRange(); + caret.setStart(editor, editor.childNodes.length); caret.collapse(true); + doc.getSelection().removeAllRanges(); doc.getSelection().addRange(caret); + doc.execCommand('insertText', false, '!'); + if (!editor.contains(chip) || !editor.textContent.includes('again!')) + throw Error(mode + ': attachment changed'); + const input = doc.body.appendChild(doc.createElement('input')); + input.value = 'other'; input.focus(); input.setSelectionRange(2, 2); + const range = doc.createRange(); range.setStart(editor, 0); range.collapse(true); + const selection = doc.getSelection(); selection.removeAllRanges(); + const before = [input.selectionStart, input.selectionEnd]; + selection.addRange(range); + if (doc.activeElement !== input || input.selectionStart !== before[0] || input.selectionEnd !== before[1]) + throw Error(mode + ': background selection stole focus'); + host.remove(); input.remove(); + } + } + return true; + })() + """ + let result = try await view.evaluateJavaScript(script) as? Bool + XCTAssertEqual(result, true) + } +} diff --git a/platforms/ios/runnerTests/WorkspaceBridgeTests.swift b/platforms/ios/runnerTests/WorkspaceBridgeTests.swift new file mode 100644 index 0000000000..a3b84c845f --- /dev/null +++ b/platforms/ios/runnerTests/WorkspaceBridgeTests.swift @@ -0,0 +1,57 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class WorkspaceBridgeTests: BridgeTestCase { + func testPublicIndexAPIStreamsUpdatesSearchDirtyAndClear() async throws { + let root = AppFiles.shared.cache.appendingPathComponent("index-bridge-" + UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: root) } + let file = root.appendingPathComponent("Acode ✓ # %.txt") + try Data("😀 needle\nsecond needle".utf8).write(to: file) + let webView = try await appWebView() + let result = try await webView.callAsyncJavaScript(""" + const index=acode.require('fileIndex'); + const events=[]; + const unsubscribe=index.subscribe(event=>events.push(event)); + const call=(action,args=[])=>new Promise((resolve,reject)=>Bridge.exec(resolve,reject,'SDcard',action,args)); + try { + if(!index.supports(root)||index.supports('content://provider/root')||index.supports('sftp://remote/root')) throw Error('Provider routing changed'); + const scan=index.scan({url:root,name:'Fixture'},{indexContent:true}); + const done=await scan; + if(done.type!=='done'||done.files!==1||done.dirs!==0||!events.some(event=>event.type==='status')) throw Error('Scan events changed'); + const entry=await index.get(file); + if(entry.name!=='Acode ✓ # %.txt'||entry.path!=='Fixture/Acode ✓ # %.txt'||entry.url!==entry.uri||entry.parent!==root) throw Error('Entry contract changed '+JSON.stringify(entry)); + const results=[]; + const search=index.search({roots:[root],search:'needle',batchResults:true,useIndex:true},event=>results.push(event)); + if((await search.result).type!=='done-searching') throw Error('Search never finished'); + const matches=results.filter(event=>event.type==='search-results').flatMap(event=>event.data).flatMap(result=>result.matches); + if(matches.length!==2||matches[0].position.start.column!==3||matches[1].position.start.row!==1) throw Error('Search positions changed'); + await call('writeText',[file,'updated', 'UTF-8']); + await index.markDirty([file]); + const fresh=[]; + await index.search({roots:[root],search:'updated',useIndex:true},event=>fresh.push(event)).result; + if(!fresh.some(event=>event.type==='search-results')) throw Error('Dirty content remained cached'); + const renamed=await call('rename',[file,'renamed.txt']); + await index.update(root,{removed:[file],added:[{url:renamed,parentUrl:root}]}); + if(await index.get(file)||!(await index.get(renamed))) throw Error('Incremental update failed'); + const replacements=[]; + await index.search({roots:[root],search:'updated',replace:'$literal',mode:'replace'},event=>replacements.push(event)).result; + if(replacements.find(event=>event.type==='replace-result')?.text!=='$literal') throw Error('Replace event changed'); + if(await call('readAsText',[renamed,'UTF-8'])!=='updated') throw Error('Native replacement unexpectedly wrote file'); + const stalled=[]; + const pending=index.search({roots:[root],search:'(a+)+$',options:{regExp:true},overlays:{[renamed]:'a'.repeat(100000)+'!'}},event=>stalled.push(event)); + const outcome=pending.result.then(()=>null,error=>error); + await new Promise(resolve=>setTimeout(resolve,100)); + await pending.cancel(); + const error=await outcome; + if(!error?.message.includes('cancelled')||!stalled.some(event=>event.type==='error')) throw Error('Search cancellation did not settle'); + await index.clear([root]); + if((await index.query({roots:[root]})).entries.length) throw Error('Clear retained workspace'); + return true; + } finally {unsubscribe();await index.clear([root]);} + """, arguments: ["root": root.absoluteString, "file": file.absoluteString], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } +} diff --git a/platforms/ios/runnerTests/WorkspaceContentTests.swift b/platforms/ios/runnerTests/WorkspaceContentTests.swift new file mode 100644 index 0000000000..a9e08126cd --- /dev/null +++ b/platforms/ios/runnerTests/WorkspaceContentTests.swift @@ -0,0 +1,24 @@ +import XCTest +@testable import runner + +final class WorkspaceContentTests: XCTestCase { + func testLargeContentIsNotTruncatedAndExplicitIncludesRaiseReadLimit() throws { + let root = AppFiles.shared.cache.appendingPathComponent("index-content-" + UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: root) } + let content = WorkspaceContent(database: try WorkspaceDatabase(url: root.appendingPathComponent("index.sqlite"))) + let file = root.appendingPathComponent("large.txt") + let text = String(repeating: "a", count: 700000) + "end-marker" + try Data(text.utf8).write(to: file) + let job = WorkspaceJob() + var entry = try WorkspaceEntry(url: file, root: root.absoluteString, parent: root.absoluteString, parentPath: "Fixture") + XCTAssertNil(try content.index(entry, encoding: "UTF-8", job: job)) + XCTAssertEqual(try content.get(entry, overlays: [:], encoding: "UTF-8", useIndex: true, large: false, job: job), text) + try Data(repeating: 97, count: 17 * 1024 * 1024).write(to: file) + entry = try WorkspaceEntry(url: file, root: root.absoluteString, parent: root.absoluteString, parentPath: "Fixture") + XCTAssertNil(try content.get(entry, overlays: [:], encoding: "UTF-8", useIndex: false, large: false, job: job)) + XCTAssertEqual(try content.get(entry, overlays: [:], encoding: "UTF-8", useIndex: false, large: true, job: job)?.utf16.count, 17 * 1024 * 1024) + let outside = WorkspaceEntry(["url": "file:///etc/passwd", "name": "passwd", "mime": "text/plain"]) + XCTAssertThrowsError(try content.get(outside, overlays: [outside.url: "overlay"], encoding: "UTF-8", useIndex: false, large: false, job: job)) + } +} diff --git a/platforms/ios/runnerTests/WorkspaceIndexTests.swift b/platforms/ios/runnerTests/WorkspaceIndexTests.swift new file mode 100644 index 0000000000..1b76ff0d9f --- /dev/null +++ b/platforms/ios/runnerTests/WorkspaceIndexTests.swift @@ -0,0 +1,128 @@ +import XCTest +@testable import runner + +final class WorkspaceIndexTests: XCTestCase { + func testScanPaginationUpdatesPersistenceAndCancelledRollback() throws { + let root = try fixture() + defer { try? FileManager.default.removeItem(at: root) } + let databaseURL = root.appendingPathComponent("index.sqlite") + let project = root.appendingPathComponent("project", isDirectory: true) + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: false) + let special = project.appendingPathComponent("100%_ '✓ #.txt") + try Data("needle".utf8).write(to: special) + let index = WorkspaceIndex(database: .success(try WorkspaceDatabase(url: databaseURL))) + let options: [String: Any] = ["rootUrl": project.absoluteString, "title": "Project", "excludeFolders": ["ignored"], "indexContent": true] + try index.scan(options, job: WorkspaceJob()) + for number in 0..<1200 { try Data("needle \(number)".utf8).write(to: project.appendingPathComponent("item-\(number).txt")) } + for name in [".hidden", "ignored", "nested"] { try FileManager.default.createDirectory(at: project.appendingPathComponent(name), withIntermediateDirectories: false) } + try Data("skip".utf8).write(to: project.appendingPathComponent("ignored/skip.txt")) + try Data("include".utf8).write(to: project.appendingPathComponent("nested/child.txt")) + try FileManager.default.createSymbolicLink(atPath: project.appendingPathComponent("nested/loop").path, withDestinationPath: project.path) + weak var cancellingJob: WorkspaceJob? + let cancelled = WorkspaceJob { type, _, _ in if type == "batch" { cancellingJob?.cancel() } } + cancellingJob = cancelled + XCTAssertThrowsError(try index.scan(options, job: cancelled)) + XCTAssertEqual(try entries(index, roots: [project.absoluteString]).count, 1) + let start = Date() + try index.scan(options, job: WorkspaceJob()) + XCTAssertLessThan(Date().timeIntervalSince(start), 15) + let all = try entries(index, roots: [project.absoluteString]) + XCTAssertEqual(all.count, 1202) + XCTAssertFalse(all.contains { ($0["path"] as? String)?.contains("ignored/") == true }) + let escaped = try index.query(["text": "%_", "roots": [project.absoluteString]])["entries"] as! [[String: Any]] + XCTAssertEqual(escaped.map { $0["name"] as! String }, [special.lastPathComponent]) + let reloaded = WorkspaceIndex(database: .success(try WorkspaceDatabase(url: databaseURL))) + XCTAssertEqual(try entries(reloaded, roots: [project.absoluteString]).count, all.count) + let old = project.appendingPathComponent("nested", isDirectory: false) + let renamed = project.appendingPathComponent("renamed", isDirectory: false) + try FileManager.default.moveItem(at: old, to: renamed) + let update = try index.update(["rootUrl": project.absoluteString, "removed": [old.absoluteString], "added": [["url": renamed.absoluteString, "parentUrl": project.absoluteString]], "excludeFolders": ["ignored"]]) + XCTAssertGreaterThan(update["removed"] as! Int, 0) + XCTAssertGreaterThan(update["added"] as! Int, 0) + XCTAssertEqual(try entries(index, roots: [project.absoluteString]).count, all.count) + XCTAssertTrue(try entries(index, roots: [project.absoluteString]).contains { $0["path"] as? String == "Project/renamed/child.txt" }) + XCTAssertThrowsError(try index.update(["rootUrl": project.absoluteString, "removed": [root.appendingPathComponent("index.sqlite").absoluteString]])) + try index.database.get().clear([project.absoluteString]) + XCTAssertTrue(try entries(index, roots: [project.absoluteString]).isEmpty) + } + + func testSearchEncodingBinaryFiltersOverlaysCacheAndLiteralReplace() throws { + let root = try fixture() + defer { try? FileManager.default.removeItem(at: root) } + let project = root.appendingPathComponent("project", isDirectory: true) + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: false) + let file = project.appendingPathComponent("unicode.txt") + try Data("😀 needle\r\nNEEDLE needleLong\n".utf8).write(to: file) + try "wide needle".data(using: .utf16LittleEndian)!.write(to: project.appendingPathComponent("wide.txt")) + try (Data([255, 254]) + "needle".data(using: .utf16LittleEndian)!).write(to: project.appendingPathComponent("bom.txt")) + try Data([0, 1, 2, 3] + Array("needle".utf8)).write(to: project.appendingPathComponent("binary.unknown")) + try Data("needle".utf8).write(to: project.appendingPathComponent("photo.png")) + try Data("readme needle".utf8).write(to: project.appendingPathComponent("README")) + let environment = project.appendingPathComponent(".env") + try Data("env needle".utf8).write(to: environment) + let index = WorkspaceIndex(database: .success(try WorkspaceDatabase(url: root.appendingPathComponent("index.sqlite")))) + try index.scan(["rootUrl": project.absoluteString, "title": "Project", "indexContent": true], job: WorkspaceJob()) + var events: [(String, [String: Any])] = [] + let job = WorkspaceJob { type, value, _ in events.append((type, value)) } + let openFile: [String: Any] = ["url": environment.absoluteString, "name": ".env", "path": "Project/.env", "mime": "application/octet-stream"] + var options: [String: Any] = ["roots": [project.absoluteString], "files": [openFile], "search": "needle", "options": ["wholeWord": true], "batchResults": true, "useIndex": true] + try index.search(options, job: job) + let results = events.filter { $0.0 == "search-results" }.flatMap { $0.1["data"] as! [[String: Any]] } + XCTAssertEqual(results.count, 5) + let bomMatch = (results.first { ($0["file"] as? [String: Any])?["name"] as? String == "bom.txt" }!["matches"] as! [[String: Any]])[0] + XCTAssertEqual((bomMatch["position"] as? [String: [String: Int]])?["start"]?["column"], 1) + let matches = results.first { ($0["file"] as? [String: Any])?["name"] as? String == "unicode.txt" }!["matches"] as! [[String: Any]] + XCTAssertEqual(matches.count, 2) + let position = matches[0]["position"] as! [String: [String: Int]] + XCTAssertEqual(position["start"], ["row": 0, "column": 3]) + XCTAssertEqual(position["end"], ["row": 0, "column": 9]) + events.removeAll() + options["overlays"] = [file.absoluteString: "unsaved NEEDLE"] + options["options"] = ["include": "**/unicode.txt", "exclude": "*.png"] + options["mode"] = "replace"; options["replace"] = "$1\\literal" + try index.search(options, job: job) + XCTAssertEqual(events.first { $0.0 == "replace-result" }?.1["text"] as? String, "unsaved $1\\literal") + XCTAssertEqual(try String(contentsOf: file, encoding: .utf8), "😀 needle\r\nNEEDLE needleLong\n") + let entry = WorkspaceEntry((try index.query(["url": file.absoluteString]))["entries"].flatMap { $0 as? [[String: Any]] }!.first!) + try Data("changed".utf8).write(to: file) + let content = WorkspaceContent(database: try index.database.get()) + XCTAssertTrue(try content.get(entry, overlays: [:], encoding: "UTF-8", useIndex: true, large: false, job: job)!.contains("needle")) + try index.database.get().execute("DELETE FROM content WHERE url = ?", [file.absoluteString]) + XCTAssertEqual(try content.get(entry, overlays: [:], encoding: "UTF-8", useIndex: true, large: false, job: job), "changed") + } + + func testSearchBatchesLimitAndRegexDeadline() throws { + let job = WorkspaceJob() + let regex = try NSRegularExpression(pattern: "x") + var sizes: [Int] = [], limited = false + try WorkspaceMatches(text: String(repeating: "x ", count: 5001), regex: regex, job: job).search { matches, limit in sizes.append(matches.count); limited = limited || limit } + XCTAssertEqual(sizes.reduce(0, +), 5000) + XCTAssertTrue(sizes.allSatisfy { $0 == 200 }) + XCTAssertTrue(limited) + let difficult = try NSRegularExpression(pattern: "(a+)+$") + let start = Date() + XCTAssertThrowsError(try WorkspaceMatches(text: String(repeating: "a", count: 100000) + "!", regex: difficult, job: job).search { _, _ in }) { error in + XCTAssertTrue(error.localizedDescription.contains("timed out")) + } + XCTAssertLessThan(Date().timeIntervalSince(start), 5) + let cancelled = WorkspaceJob(); cancelled.cancel() + XCTAssertThrowsError(try WorkspaceMatches(text: "x", regex: regex, job: cancelled).search { _, _ in }) + } + + private func fixture() throws -> URL { + let root = AppFiles.shared.cache.appendingPathComponent("workspace-tests-" + UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) + return root + } + + private func entries(_ index: WorkspaceIndex, roots: [String]) throws -> [[String: Any]] { + var result: [[String: Any]] = [], cursor = 0 + repeat { + let page = try index.query(["roots": roots, "limit": 137, "cursor": cursor]) + result += page["entries"] as! [[String: Any]] + guard page["hasMore"] as? Bool == true else { break } + cursor = page["cursor"] as! Int + } while true + return result + } +} diff --git a/platforms/ios/runnerTests/WorkspaceReplacementTests.swift b/platforms/ios/runnerTests/WorkspaceReplacementTests.swift new file mode 100644 index 0000000000..950b2c4c42 --- /dev/null +++ b/platforms/ios/runnerTests/WorkspaceReplacementTests.swift @@ -0,0 +1,43 @@ +import XCTest +@testable import runner + +final class WorkspaceReplacementTests: XCTestCase { + func testExpandsJavaScriptSubstitutions() throws { + XCTAssertEqual(try replace("foo bar", #"(\w+) (\w+)"#, "$2 $1"), "bar foo") + XCTAssertEqual(try replace("ab", "a", "[$&]"), "[a]b") + XCTAssertEqual(try replace("xay", "a", "$`|$'"), "xx|yy") + XCTAssertEqual(try replace("a", "a", "$$1"), "$1") + XCTAssertEqual(try replace("abcdefghijk", "(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)", "$11-$10-$1"), "k-j-a") + XCTAssertEqual(try replace("ab", "(a)(b)", "$3$0"), "$3$0") + } + + func testNamedGroups() throws { + XCTAssertEqual(try replace("2026-11", #"(?\d+)-(?\d+)"#, "$/$"), "11/2026") + XCTAssertEqual(try replace("a", "(?a)", "[$]"), "[]") + XCTAssertEqual(try replace("a", "(a)", "$"), "$") + XCTAssertEqual(try replace("a", "[(?)]?(a)", "$"), "$") + XCTAssertEqual(try replace("a", #"\Q(?\E|(a)"#, "$"), "$") + } + + func testLiteralModeLeavesReplacementUntouched() throws { + let regex = try NSRegularExpression(pattern: NSRegularExpression.escapedPattern(for: "a")) + let source = "a" as NSString + let match = try XCTUnwrap(regex.firstMatch(in: source as String, range: NSRange(location: 0, length: source.length))) + XCTAssertEqual(WorkspaceReplacement("$&$1", pattern: "a", regExp: false).expand(match, in: source), "$&$1") + } + + private func replace(_ text: String, _ pattern: String, _ template: String) throws -> String { + let regex = try NSRegularExpression(pattern: pattern) + let source = text as NSString + let replacement = WorkspaceReplacement(template, pattern: pattern, regExp: true) + let out = NSMutableString() + var cursor = 0 + for match in regex.matches(in: text, range: NSRange(location: 0, length: source.length)) { + out.append(source.substring(with: NSRange(location: cursor, length: match.range.location - cursor))) + out.append(replacement.expand(match, in: source)) + cursor = NSMaxRange(match.range) + } + out.append(source.substring(from: cursor)) + return out as String + } +} diff --git a/platforms/ios/runnerTests/WorkspaceSearchTests.swift b/platforms/ios/runnerTests/WorkspaceSearchTests.swift new file mode 100644 index 0000000000..3ddc406fb7 --- /dev/null +++ b/platforms/ios/runnerTests/WorkspaceSearchTests.swift @@ -0,0 +1,57 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class WorkspaceSearchTests: BridgeTestCase { + func testNativeIndexAndSearchUIReadIOSWorkspace() async throws { + let app = try await appWebView() + let directory = AppFiles.shared.cache.appendingPathComponent("search-fixture-" + UUID().uuidString, isDirectory: true) + let nested = directory.appendingPathComponent("nested", isDirectory: true) + try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + try Data("iOSWorkspaceNeedle923 first\n".utf8).write(to: directory.appendingPathComponent("match.txt")) + try Data("const text = 'iOSWorkspaceNeedle923';\n".utf8).write(to: nested.appendingPathComponent("name # ✓.js")) + let result = try await app.callAsyncJavaScript(""" + for(let n=0;!window.editorManager&&n<100;n++) await new Promise(resolve=>setTimeout(resolve,100)); + const fileList=acode.require('fileList'); + const index=acode.require('fileIndex'); + if(!index.supports(root)) throw Error('Native index unavailable'); + const apps=acode.require('sidebarApps'); + const searchApp=apps.get('searchInFiles'); + const openedSidebar=!document.querySelector('#sidebar'); + if(openedSidebar)acode.exec('toggle-sidebar'); + const oldActive=document.querySelector('[data-action="sidebar-app"].active')?.dataset.id; + acode.require('openfolder')(root,{name:'iOS search fixture',saveState:false,listFiles:true}); + const folder=acode.require('addedfolder').find(item=>item.url===root); + let input; + let originalInput; + try { + let found=[]; + for(let n=0;n<100;n++) { + found=(await index.query({roots:[root]})).entries; + if(found.length===2) break; + await new Promise(resolve=>setTimeout(resolve,100)); + } + if(found.length!==2) throw Error('File discovery incomplete: '+JSON.stringify(found)); + document.querySelector('[data-action="sidebar-app"][data-id="searchInFiles"]').click(); + input=searchApp.querySelector('[name="search"]'); + originalInput=input.value; + input.value='iOSWorkspaceNeedle923'; + input.dispatchEvent(new Event('input',{bubbles:true})); + for(let n=0;n<100;n++) { + const counts=[...searchApp.querySelectorAll('.search-result-header strong')].map(el=>Number(el.textContent)); + if(counts.length===2&&counts.every(count=>count===2)) return true; + await new Promise(resolve=>setTimeout(resolve,100)); + } + throw Error('Search did not find both files: '+searchApp.textContent); + } finally { + if(input) {input.value=originalInput;input.dispatchEvent(new Event('input',{bubbles:true}));} + folder?.remove(); + const previous=document.querySelector('[data-action="sidebar-app"][data-id="'+CSS.escape(oldActive||"files")+'"]');previous?.click(); + if(openedSidebar)acode.exec('toggle-sidebar'); + } + """, arguments: ["root": directory.absoluteString], in: nil, contentWorld: .page) as? Bool + XCTAssertEqual(result, true) + } +} diff --git a/platforms/ios/runnerUITests/AppIconUITests.swift b/platforms/ios/runnerUITests/AppIconUITests.swift new file mode 100644 index 0000000000..6cac3f1ac1 --- /dev/null +++ b/platforms/ios/runnerUITests/AppIconUITests.swift @@ -0,0 +1,89 @@ +import XCTest +import StoreKitTest + +@MainActor +final class AppIconUITests: XCTestCase { + func testChangeAndRestoreIconThroughSettings() async throws { + continueAfterFailure = false + let configuration = try XCTUnwrap(Bundle(for: Self.self).url(forResource: "Iap", withExtension: "storekit")) + let purchases = try SKTestSession(contentsOf: configuration) + purchases.resetToDefaultState() + purchases.clearTransactions() + purchases.disableDialogs = true + defer { purchases.clearTransactions(); purchases.resetToDefaultState() } + _ = try await purchases.buyProduct(identifier: "acode_pro_new") + let device = XCUIDevice.shared + let originalOrientation = device.orientation + defer { device.orientation = originalOrientation } + device.orientation = .portrait + let app = XCUIApplication() + app.launchArguments = ["-AppleLanguages", "(en)", "-AppleLocale", "en_US", "-acode-ui-testing"] + app.launch() + dismissIconNotice(app) + let entry = app.webViews.staticTexts["App icon"].firstMatch + if !entry.waitForExistence(timeout: 2) { + let settings = app.webViews.staticTexts["Settings"].firstMatch + if !settings.waitForExistence(timeout: 2) { + let header = app.webViews.otherElements["banner"].firstMatch + XCTAssertTrue(header.waitForExistence(timeout: 15), app.debugDescription) + header.coordinate(withNormalizedOffset: CGVector(dx: 0.95, dy: 0.5)).tap() + } + XCTAssertTrue(settings.waitForExistence(timeout: 15), app.debugDescription) + tapWhenReady(settings) + } + for icon in ["Default", "Pixel Party", "Default"] { + let landscape = icon == "Pixel Party" + device.orientation = landscape ? .landscapeLeft : .portrait + let rotated = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + let frame = app.windows.firstMatch.frame + return frame.width > 0 && (frame.width > frame.height) == landscape + }, object: nil) + await fulfillment(of: [rotated], timeout: 5) + XCTAssertTrue(entry.waitForExistence(timeout: 5), app.debugDescription) + scrollTo(entry, in: app) + tapWhenReady(entry) + let button = app.webViews.switches[icon].firstMatch + XCTAssertTrue(button.waitForExistence(timeout: 5), app.debugDescription) + if button.value as? String == "1" { + tapWhenReady(app.webViews.buttons.matching(NSPredicate(format: "label ==[c] %@", "close")).firstMatch) + continue + } + tapWhenReady(button) + dismissIconNotice(app) + XCTAssertTrue(app.wait(for: .runningForeground, timeout: 5)) + tapWhenReady(entry) + let selected = app.webViews.switches[icon].firstMatch + let saved = XCTNSPredicateExpectation(predicate: NSPredicate(format: "value == %@", "1"), object: selected) + await fulfillment(of: [saved], timeout: 5) + tapWhenReady(app.webViews.buttons.matching(NSPredicate(format: "label ==[c] %@", "close")).firstMatch) + } + XCTAssertTrue(app.webViews.staticTexts["App icon"].firstMatch.exists) + } + + private func tapWhenReady(_ element: XCUIElement) { + let ready = XCTNSPredicateExpectation(predicate: NSPredicate(format: "hittable == true"), object: element) + XCTAssertEqual(XCTWaiter.wait(for: [ready], timeout: 15), .completed, element.debugDescription) + element.tap() + } + + private func scrollTo(_ element: XCUIElement, in app: XCUIApplication) { + let webView = app.webViews.firstMatch + for _ in 0..<8 { + if element.isHittable { return } + let below = element.frame.midY > webView.frame.midY + let start = webView.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: below ? 0.7 : 0.4)) + let end = webView.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: below ? 0.4 : 0.7)) + start.press(forDuration: 0.05, thenDragTo: end, withVelocity: .slow, thenHoldForDuration: 0.2) + } + } + + private func dismissIconNotice(_ app: XCUIApplication) { + let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard") + let alert = app.alerts.firstMatch.waitForExistence(timeout: 2) + ? app.alerts.firstMatch : springboard.alerts.firstMatch + if alert.exists { + XCTAssertTrue(alert.staticTexts.matching(NSPredicate(format: "label CONTAINS %@", "changed the icon")).firstMatch.exists) + alert.buttons["OK"].tap() + } + } +} diff --git a/platforms/ios/runnerUITests/WebContextMenuUITests.swift b/platforms/ios/runnerUITests/WebContextMenuUITests.swift new file mode 100644 index 0000000000..61e73a630d --- /dev/null +++ b/platforms/ios/runnerUITests/WebContextMenuUITests.swift @@ -0,0 +1,36 @@ +import XCTest + +@MainActor +final class WebContextMenuUITests: XCTestCase { + func testHoldingAFileTabOpensItsExistingMenuOnRelease() async throws { + continueAfterFailure = false + let app = XCUIApplication() + app.launchArguments = ["-AppleLanguages", "(en)", "-AppleLocale", "en_US", "-acode-ui-testing"] + app.launch() + let header = app.webViews.otherElements["banner"].firstMatch + XCTAssertTrue(header.waitForExistence(timeout: 20), app.debugDescription) + header.coordinate(withNormalizedOffset: CGVector(dx: 0.95, dy: 0.5)).tap() + XCTAssertTrue(app.webViews.staticTexts["Save as"].firstMatch.waitForExistence(timeout: 5), app.debugDescription) + let newFiles = app.webViews.staticTexts.matching(identifier: "New file") + let newFile = newFiles.element(boundBy: newFiles.count - 1) + let ready = XCTNSPredicateExpectation(predicate: NSPredicate(format: "hittable == true"), object: newFile) + XCTAssertEqual(XCTWaiter.wait(for: [ready], timeout: 5), .completed, app.debugDescription) + newFile.tap() + let input = app.webViews.textFields.firstMatch + XCTAssertTrue(input.waitForExistence(timeout: 5), app.debugDescription) + let name = "context-menu-" + UUID().uuidString.prefix(8) + ".html" + input.tap() + input.typeText(name) + let confirm = app.webViews.buttons.matching(NSPredicate(format: "label ==[c] %@", "ok")).firstMatch + XCTAssertTrue(confirm.waitForExistence(timeout: 5), app.debugDescription) + confirm.tap() + let tab = app.webViews.staticTexts.matching(identifier: name).element(boundBy: 1) + XCTAssertTrue(tab.waitForExistence(timeout: 5), app.debugDescription) + tab.press(forDuration: 0.75) + let closeLeft = app.webViews.staticTexts["Close Left"].firstMatch + let close = app.webViews.staticTexts["Close file"].firstMatch + defer { if close.exists { close.tap() } } + XCTAssertTrue(closeLeft.waitForExistence(timeout: 5), app.debugDescription) + XCTAssertTrue(tab.exists, "The release click must not activate a menu item") + } +} diff --git a/proguard-rules.pro b/proguard-rules.pro deleted file mode 100644 index db72d9a955..0000000000 --- a/proguard-rules.pro +++ /dev/null @@ -1,27 +0,0 @@ -# Keep Cordova classes --keep class org.apache.cordova.** { *; } - -# Cordova discovers plugins by class name from config.xml and instantiates them -# reflectively, and plugins can dispatch actions by method name through -# reflection too (e.g. Ftp.execute() uses -# getClass().getDeclaredMethod(action, JSONArray, CallbackContext)). -# Without keeping the members, R8 strips methods such as connect()/listDirectory() -# and those plugin calls fail at runtime with NoSuchMethodException. --keep public class * extends org.apache.cordova.CordovaPlugin { *; } - -# WebView JS bridge methods are invoked by name from JavaScript. --keepclassmembers class * { - @android.webkit.JavascriptInterface ; -} - -# cordova-plugin-buildinfo resolves the app's BuildConfig reflectively: -# Class.forName(packageName + ".BuildConfig") and c.getField(fieldName). --keep class **.BuildConfig { *; } - -# maverick-synergy (SSH/SFTP) references java.lang.management from -# Utils.generateThreadDump(), which does not exist on Android. That method is -# never reached on Android, so ignore the missing Java SE classes. --dontwarn java.lang.management.** - -# Keep Javascript Interface attributes --keepattributes *Annotation*,EnclosingMethod,InnerClasses,Signature diff --git a/readme.md b/readme.md index 4ac444fff3..4a9d56deca 100644 --- a/readme.md +++ b/readme.md @@ -1,4 +1,4 @@ -# Acode - Code Editor for Android +# Acode - Code Editor for Android and iOS

@@ -8,7 +8,9 @@ ## • Overview -Welcome to Acode Editor - a powerful and versatile code editing tool designed specifically for Android devices. Whether you're working on HTML, CSS, JavaScript, or other programming languages, Acode empowers you to code on-the-go with confidence. +Welcome to Acode Editor - a powerful and versatile code editor for Android phones and tablets, iPhone and iPad. Whether you're working on HTML, CSS, JavaScript, or other programming languages, Acode empowers you to code on-the-go with confidence. + +Acode is a web app running in a native WebView shell, with its own native service bridge. Both platforms share the same editor, settings and plugin APIs: Android uses Java/Kotlin native services, and iOS uses Swift native services. ## • Features @@ -16,7 +18,7 @@ Welcome to Acode Editor - a powerful and versatile code editing tool designed sp - Seamlessly modify source files for various languages like Python, Java, JavaScript, and more. - Built-in javascript console - S/FTP and SSH terminal integration -- Built-in terminal(Alpine) +- Built-in terminal (Alpine Linux) on Android and iOS - Enjoy multi-language editing support with easy management tools. - Enjoy a large collections of community plugins to enhance your coding experience. @@ -24,36 +26,52 @@ Welcome to Acode Editor - a powerful and versatile code editing tool designed sp You can get Acode Editor from popular platforms: -[Get it on Google Play](https://play.google.com/store/apps/details?id=com.foxdebug.acodefree) [Get it on F-Droid](https://www.f-droid.org/packages/com.foxdebug.acode/) +[Get it on Google Play](https://play.google.com/store/apps/details?id=com.foxdebug.acodefree) [Get it on F-Droid](https://www.f-droid.org/packages/com.foxdebug.acode/) [Download on the App Store](https://apps.apple.com/app/id6815644799) ## • Project Structure

 Acode/
 |
-|- src/   - Core code and language files
+|- src/                   - Application source, index.html, language files, and resources
+|  |- native/             - TypeScript native APIs and shared bridge
+|  |- platforms/          - Android and iOS bridge transports
 |
-|- www/   - Public documents, compiled files, and HTML templates
+|- platforms/android/     - Native Android app, services, resources, and Gradle wrapper
+|- platforms/ios/         - iOS app, native services (runner/lib), terminal runtime, and tests
 |
-|- utils/ - CLI tools for building, string manipulation, and more
+|- tests/                 - Unit tests (Vitest)
+|- docs/                  - Platform notes (iOS port, iOS advertising)
+|- dev/                   - CLI tools for building, string manipulation, and more
 |
 |- codemirror-lsp-client/ - Git submodule providing @codemirror/lsp-client (clone with --recurse-submodules)
 
+Rspack builds `src/` into `platforms/android/app/src/main/assets/bundle/` or +`platforms/ios/runner/bundle/`. These generated directories are git-ignored and +contain the HTML, static assets, and compiled scripts. + ## • Multi-language Support -Enhance Acode's capabilities by adding new languages easily. Just create a file with the language code (e.g., en-us for English) in [`src/lang/`](https://github.com/Acode-Foundation/Acode/tree/main/src/lang) and include it in [`src/lib/lang.js`](https://github.com/Acode-Foundation/Acode/blob/main/src/lib/lang.js). Manage strings across languages effortlessly using utility commands: +Enhance Acode's capabilities by adding new languages easily. Just create a file with the language code (e.g., en-us for English) in [`src/lang/`](src/lang/) and include it in [`src/lib/lang.js`](src/lib/lang.js). Manage strings across languages effortlessly using utility commands: ```shell -pnpm run lang add -pnpm run lang remove -pnpm run lang search -pnpm run lang update +npm run lang add +npm run lang remove +npm run lang search +npm run lang update ``` ## • Contributing & Building the Application -See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed instructions. +Clone with `--recurse-submodules`, then install dependencies with `npm ci`. Build scripts live in `dev/`. + +- **Android:** set `package.json.androidPackageId` to `com.foxdebug.acode` (paid) or `com.foxdebug.acodefree` (free), then run `npm run build -- dev apk`. Paid builds exclude AdMob and its SDKs. Android builds use Java 26, the Gradle 9.8 RC3 wrapper and Android Gradle Plugin 9.4.1. +- **iOS:** copy `platforms/ios/Config.xcconfig.example` to `platforms/ios/Config.xcconfig` on a new checkout and keep only local signing settings in it. Then run `npm run build -- ios dev` for a simulator build, or `npm run dev:ios -- --target=` for live reload. iOS has one free app whose bundle ID comes from `package.json.appleAppId`, built with the `runner` scheme. Version, build number, display name and bundle ID are synced into the Xcode project from `package.json` by `dev/sync.js` on every build. + +See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed setup, build and test instructions, [docs/ios-port.md](docs/ios-port.md) for iOS platform notes, and [docs/ios-advertising.md](docs/ios-advertising.md) for the iOS advertising setup. + +The iOS terminal runs ARM64 Alpine Linux in an emulator behind the same terminal UI and AXS server as Android. See [its runtime sources, build requirements, and compatibility limits](platforms/ios/Alpine/README.md). ## • Contributors diff --git a/res/android/values/themes.xml b/res/android/values/themes.xml deleted file mode 100644 index 62745020d9..0000000000 --- a/res/android/values/themes.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - diff --git a/rspack.config.js b/rspack.config.js index f24d34bf86..b1d8102d72 100644 --- a/rspack.config.js +++ b/rspack.config.js @@ -1,40 +1,50 @@ const path = require('path'); const { rspack } = require('@rspack/core'); +const { getAppConfig, getWebBundlePath, getAdConfig } = require('./dev/config'); +const StripSourceMapCommentsPlugin = require('./dev/stripSourceMapComments'); module.exports = (env, options) => { const { mode = 'development' } = options; const prod = mode === 'production'; + const platform = process.env.ACODE_PLATFORM || 'android'; + const { variant } = getAppConfig(platform); + const ads = getAdConfig(platform, prod ? 'Release' : 'Debug'); const isDev = process.env.DEV_MODE === 'true'; const devHost = process.env.DEV_HOST || ''; const devPort = process.env.DEV_PORT || ''; const devProto = isDev ? (process.env.DEV_PROTO || '') : ''; - const devOrigin = isDev && devHost && devPort && devProto - ? ''.concat(devProto, '://', devHost, ':', devPort) - : ''; + // Match the oldest engine each platform supports (MIN_WEBVIEW_MAJOR in + // src/index.html, IPHONEOS_DEPLOYMENT_TARGET in Xcode) instead of plain + // ES2015, so native async/await, classes and spread are kept. `entry` mode + // rewrites `import "core-js/stable"` to only the polyfills that engine still + // needs, so plugins keep every global they could rely on. + const swcEnv = { + targets: platform === 'ios' ? 'ios_saf >= 18' : 'chrome >= 67', + mode: 'entry', + coreJs: require('core-js/package.json').version, + // core-js replaces the native Array.prototype.push below Chrome 122, for + // edge cases (lengths past 2^32 - 1, push() with no arguments on an array + // with a read-only length) nothing relies on. Its JS version is ~8x + // slower, and the parser, CodeMirror and the renderer push constantly. + exclude: ['es.array.push'], + }; + const typescriptLoader = { + loader: 'builtin:swc-loader', + options: { jsc: { parser: { syntax: 'typescript', tsx: false } }, env: swcEnv }, + }; const rules = [ { test: /typescript[\\/]lib[\\/]lib\..*\.d\.ts$/, type: 'asset/source', }, - // TypeScript/TSX files - Custom JSX loader + SWC + // Native APIs are plain TypeScript; only editor sources use the JSX loader. { test: /\.tsx?$/, exclude: /node_modules/, - use: [ - { - loader: 'builtin:swc-loader', - options: { - jsc: { - parser: { - syntax: 'typescript', - tsx: false, - }, - target: 'es2015', - }, - }, - }, - path.resolve(__dirname, 'utils/custom-loaders/html-tag-jsx-loader.js'), + oneOf: [ + { include: /[\\/]src[\\/](?:native|platforms)[\\/]/, use: [typescriptLoader] }, + { use: [typescriptLoader, path.resolve(__dirname, 'dev/custom-loaders/html-tag-jsx-loader.js')] }, ], }, // JavaScript files @@ -55,8 +65,8 @@ module.exports = (env, options) => { parser: { syntax: 'ecmascript', }, - target: 'es2015', }, + env: swcEnv, }, }, ], @@ -72,11 +82,11 @@ module.exports = (env, options) => { syntax: 'ecmascript', jsx: false, }, - target: 'es2015', }, + env: swcEnv, }, }, - path.resolve(__dirname, 'utils/custom-loaders/html-tag-jsx-loader.js'), + path.resolve(__dirname, 'dev/custom-loaders/html-tag-jsx-loader.js'), ], }, ], @@ -114,7 +124,7 @@ module.exports = (env, options) => { }, // Regular CSS files do not need Sass processing. Passing icon CSS through // Sass converts escaped private-use code points into literal characters in - // production, which Cordova's asset WebView renders as missing glyphs. + // production, which Android's asset WebView renders as missing glyphs. { test: /(? { }, entry: { boot: './src/boot.js', + native: './src/native/index.ts', main: './src/main.js', console: './src/lib/console.js', consoleWorker: './src/lib/consoleWorker.js', @@ -156,11 +167,11 @@ module.exports = (env, options) => { typescriptLspWorker: './src/cm/lsp/workers/typescript.worker.ts', }, output: { - path: path.resolve(__dirname, 'www/build/'), - filename: '[name].js', - chunkFilename: '[name].chunk.js', - assetModuleFilename: '[name][ext]', - publicPath: devOrigin ? ''.concat(devOrigin, '/build/') : '/build/', + path: getWebBundlePath(), + filename: 'build/[name].js', + chunkFilename: 'build/[name].chunk.js', + assetModuleFilename: 'build/[name][ext]', + publicPath: 'auto', clean: !isDev, }, // TypeScript's Node-only plugin loader uses a dynamic require. It is never @@ -191,25 +202,41 @@ module.exports = (env, options) => { roots: [], }, plugins: [ + new StripSourceMapCommentsPlugin(), + new rspack.CopyRspackPlugin({ + patterns: [ + { from: 'src/index.html', to: 'index.html' }, + { from: 'src/res/logo.svg', to: 'logo.svg' }, + { from: 'src/res/favicon.ico', to: 'favicon.ico' }, + { from: 'src/res/icons/*.svg', to: 'icons/[name][ext]' }, + ], + }), + ...(variant === 'paid' ? [new rspack.NormalModuleReplacementPlugin( + /^(?:\.\/|lib\/)(startAd|rewardedAd)(?:\.js)?$/, + (resource) => { + const name = path.basename(resource.request).replace(/\.js$/, ''); + resource.request = path.resolve(__dirname, 'src/lib/paid', `${name}.js`); + }, + )] : []), new rspack.DefinePlugin({ + __FREE__: JSON.stringify(variant === 'free'), + IS_IOS: JSON.stringify(platform === 'ios'), + IS_ANDROID: JSON.stringify(platform === 'android'), + PLATFORM: JSON.stringify(platform), + ADMOB_APP_ID: JSON.stringify(ads.appId), + ADMOB_BANNER_ID: JSON.stringify(ads.banner), + ADMOB_INTERSTITIAL_ID: JSON.stringify(ads.interstitial), + ADMOB_REWARDED_ID: JSON.stringify(ads.rewarded), + ADMOB_APP_OPEN_ID: JSON.stringify(ads.appOpen), + __FDROID__: JSON.stringify(process.env.ACODE_FDROID === 'true'), __DEV_MODE__: JSON.stringify(isDev), __DEV_HOST__: JSON.stringify(devHost), __DEV_PORT__: JSON.stringify(devPort), __DEV_PROTO__: JSON.stringify(devProto), }), new rspack.CssExtractRspackPlugin({ - filename: '[name].css', + filename: 'build/[name].css', }), - // core-js replaces the native Array.prototype.push below Chrome 122, - // for edge cases (lengths past 2^32 - 1, push() with no arguments on an - // array with a read-only length) nothing relies on. Its JS version is - // ~8x slower, and the parser and CodeMirror push constantly, so keep the - // native one. Only core-js's global polyfill is dropped: core-js-pure, - // which Babel's runtime helpers import, is untouched. - new rspack.NormalModuleReplacementPlugin( - /[\\/]node_modules[\\/]core-js[\\/]modules[\\/]es\.array\.push\.js$/, - path.resolve(__dirname, 'utils/empty-module.js'), - ), ], }; diff --git a/src/boot.js b/src/boot.js index 27af18b953..d4ee990432 100644 --- a/src/boot.js +++ b/src/boot.js @@ -1,8 +1,3 @@ -// boot.js — Entry point loaded by index.html -// Routes between development (HTTP dev server) and production (local assets). -// main.js is never imported directly; it's loaded dynamically so the dev server -// can serve a freshly compiled version on every reload. - const DEV_MODE = typeof __DEV_MODE__ !== "undefined" && __DEV_MODE__; const DEV_HOST = typeof __DEV_HOST__ !== "undefined" ? __DEV_HOST__ : ""; const DEV_PORT = typeof __DEV_PORT__ !== "undefined" ? __DEV_PORT__ : ""; @@ -12,58 +7,63 @@ const DEV_ORIGIN = ? `${DEV_PROTO}://${DEV_HOST}:${DEV_PORT}` : ""; -const loadScript = (src) => { - const el = document.createElement("script"); - el.src = src; - document.head.appendChild(el); -}; +(async () => { + let assetOrigin = "."; + if (DEV_MODE && DEV_ORIGIN) { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 3000); + try { + const response = await fetch(`${DEV_ORIGIN}/build/main.js`, { + method: "HEAD", + cache: "no-store", + signal: controller.signal, + }); + if (response.ok) assetOrigin = DEV_ORIGIN; + } catch (error) { + console.error("Error setting dev mode", error); + } finally { + clearTimeout(timeout); + } + } + await bootApp(assetOrigin); + if (assetOrigin === DEV_ORIGIN) connectWS(); +})(); + +function loadScript(src) { + return new Promise((resolve, reject) => { + const el = document.createElement("script"); + el.src = src; + el.onload = () => Promise.resolve(window.nativeReady).then(resolve, reject); + el.onerror = reject; + document.head.appendChild(el); + }); +} -const loadCSS = (href) => { +function loadCSS(href) { const el = document.createElement("link"); el.rel = "stylesheet"; el.href = href; document.head.appendChild(el); -}; - -const bootDev = () => { - loadCSS(`${DEV_ORIGIN}/build/main.css`); - loadScript(`${DEV_ORIGIN}/build/main.js`); +} +function connectWS() { const wsProto = DEV_PROTO === "https" ? "wss" : "ws"; - const connectWS = () => { - let ws; - try { - ws = new WebSocket(`${wsProto}://${DEV_HOST}:${DEV_PORT}`); - } catch { - setTimeout(connectWS, 1000); - return; - } - ws.onmessage = ({ data }) => { - if (data === "reload") location.reload(); - }; - ws.onclose = () => setTimeout(connectWS, 1000); - ws.onerror = () => {}; + let ws; + try { + ws = new WebSocket(`${wsProto}://${DEV_HOST}:${DEV_PORT}`); + } catch { + setTimeout(connectWS, 1000); + return; + } + ws.onmessage = ({ data }) => { + if (data === "reload") location.reload(); }; - connectWS(); -}; - -const bootProd = () => { - loadCSS("./build/main.css"); - loadScript("./build/main.js"); -}; + ws.onclose = () => setTimeout(connectWS, 1000); + ws.onerror = () => {}; +} -if (DEV_MODE && DEV_ORIGIN) { - fetch(`${DEV_ORIGIN}/build/main.js`, { method: "HEAD", cache: "no-store" }) - .then((res) => { - if (res.ok) { - bootDev(); - } else { - bootProd(); - } - }) - .catch(() => { - bootProd(); - }); -} else { - bootProd(); +async function bootApp(origin) { + await loadScript(`${origin}/build/native.js`); + loadCSS(`${origin}/build/main.css`); + loadScript(`${origin}/build/main.js`); } diff --git a/src/cm/colorChip.ts b/src/cm/colorChip.ts index c319709472..8b02429c4c 100644 --- a/src/cm/colorChip.ts +++ b/src/cm/colorChip.ts @@ -1,11 +1,11 @@ import type { CanvasWidgetSpec } from "@acode.app/canvas-view"; import type { LSPClient } from "@codemirror/lsp-client"; -import { LSPPlugin } from "@codemirror/lsp-client"; import type { Range } from "@codemirror/state"; import { Decoration, EditorView, WidgetType } from "@codemirror/view"; import pickColor from "dialogs/color"; import color from "utils/color"; import type { Color as LspColor } from "vscode-languageserver-types"; +import { getAllLspPlugins } from "./lsp/clientLoader"; export const COLOR_CHIP_CLASS = "cm-color-chip"; export const COLOR_CHIP_SOURCE_ATTR = "data-color-source"; @@ -116,7 +116,7 @@ export function isViewEditable(view: EditorView): boolean { } export function hasLspColorProvider(view: EditorView): boolean { - return LSPPlugin.getAll(view, "documentColor").some( + return getAllLspPlugins(view, "documentColor").some( (lsp) => lsp.client.connected && !!lsp.client.serverCapabilities?.colorProvider, ); diff --git a/src/cm/commandRegistry.js b/src/cm/commandRegistry.js index 16068769fe..3ec24baf5b 100644 --- a/src/cm/commandRegistry.js +++ b/src/cm/commandRegistry.js @@ -61,10 +61,6 @@ import { openLintPanel, previousDiagnostic, } from "@codemirror/lint"; -import { - LSPPlugin, - formatDocument as lspFormatDocument, -} from "@codemirror/lsp-client"; import { Compartment, EditorSelection } from "@codemirror/state"; import { keymap } from "@codemirror/view"; import { focusEditorIfEditable } from "cm/editorReadOnly"; @@ -81,24 +77,7 @@ import { keyBindingsConflict, toCodeMirrorKey, } from "cm/keyBindingUtils"; -import { - renameSymbol as acodeRenameSymbol, - clearDiagnosticsEffect, - clientManager, - jumpToDeclaration as lspJumpToDeclaration, - jumpToDefinition as lspJumpToDefinition, - jumpToImplementation as lspJumpToImplementation, - jumpToTypeDefinition as lspJumpToTypeDefinition, - nextSignature as lspNextSignature, - prevSignature as lspPrevSignature, - showSignatureHelp as lspShowSignatureHelp, -} from "cm/lsp"; -import { - closeReferencesPanel as acodeCloseReferencesPanel, - findAllReferences as acodeFindAllReferences, - findAllReferencesInTab as acodeFindAllReferencesInTab, -} from "cm/lsp/references"; -import { showDocumentSymbols } from "components/symbolsPanel"; +import { getLoadedLspClient, getLspPlugin } from "cm/lsp/clientLoader"; import toast from "components/toast"; import prompt from "dialogs/prompt"; import actions from "handlers/quickTools"; @@ -106,6 +85,7 @@ import keyBindings, { APP_KEY_BINDING_NAMES, CODEMIRROR_COMMAND_NAMES, } from "lib/keyBindings"; +import platform from "lib/platform"; import settings from "lib/settings"; import Url from "utils/Url"; @@ -151,6 +131,16 @@ let cachedKeymap = []; /** @type {Set} */ const commandViews = new Set(); +/** + * Commands are often registered in bursts (a plugin adding several at once), + * so the keymap is rebuilt lazily on the next read instead of per command. + */ +let keymapDirty = true; + +/** @type {Set} views waiting for the updated keymap */ +const pendingKeymapViews = new Set(); +let keymapRefreshScheduled = false; + const CODEMIRROR_COMMAND_ENTRIES = Object.entries(cmCommands).filter( ([name, value]) => typeof value === "function" && CODEMIRROR_COMMAND_NAMES.has(name), @@ -164,7 +154,6 @@ registerCoreCommands(); registerLspCommands(); registerLintCommands(); registerCommandsFromKeyBindings(); -rebuildKeymap(); function registerCoreCommands() { addCommand({ @@ -650,16 +639,17 @@ function registerCoreCommands() { return true; }, }); - addCommand({ - name: "openTerminal", - description: "Open Terminal", - readOnly: true, - requiresView: false, - run() { - acode.exec("new-terminal"); - return true; - }, - }); + if (platform.localExecution) + addCommand({ + name: "openTerminal", + description: "Open Terminal", + readOnly: true, + requiresView: false, + run() { + acode.exec("new-terminal"); + return true; + }, + }); addCommand({ name: "acode:showWelcome", description: "Show Welcome", @@ -1060,63 +1050,63 @@ function registerLspCommands() { description: "Format document (Language Server)", readOnly: false, requiresView: true, - run: runLspCommand(lspFormatDocument), + run: runLspCommand("formatDocument"), }); addCommand({ name: "renameSymbol", description: "Rename symbol (Language Server)", readOnly: false, requiresView: true, - run: runLspCommand(acodeRenameSymbol), + run: runLspCommand("renameSymbol"), }); addCommand({ name: "showSignatureHelp", description: "Show signature help", readOnly: true, requiresView: true, - run: runLspCommand(lspShowSignatureHelp), + run: runLspCommand("showSignatureHelp"), }); addCommand({ name: "nextSignature", description: "Next signature", readOnly: true, requiresView: true, - run: runLspCommand(lspNextSignature, { silentOnMissing: true }), + run: runLspCommand("nextSignature", { silentOnMissing: true }), }); addCommand({ name: "prevSignature", description: "Previous signature", readOnly: true, requiresView: true, - run: runLspCommand(lspPrevSignature, { silentOnMissing: true }), + run: runLspCommand("prevSignature", { silentOnMissing: true }), }); addCommand({ name: "jumpToDefinition", description: "Go to definition (Language Server)", readOnly: true, requiresView: true, - run: runLspCommand(lspJumpToDefinition), + run: runLspCommand("jumpToDefinition"), }); addCommand({ name: "jumpToDeclaration", description: "Go to declaration (Language Server)", readOnly: true, requiresView: true, - run: runLspCommand(lspJumpToDeclaration), + run: runLspCommand("jumpToDeclaration"), }); addCommand({ name: "jumpToTypeDefinition", description: "Go to type definition (Language Server)", readOnly: true, requiresView: true, - run: runLspCommand(lspJumpToTypeDefinition), + run: runLspCommand("jumpToTypeDefinition"), }); addCommand({ name: "jumpToImplementation", description: "Go to implementation (Language Server)", readOnly: true, requiresView: true, - run: runLspCommand(lspJumpToImplementation), + run: runLspCommand("jumpToImplementation"), }); addCommand({ name: "findReferences", @@ -1126,12 +1116,11 @@ function registerLspCommands() { async run(view) { const resolvedView = resolveView(view); if (!resolvedView) return false; - const plugin = LSPPlugin.get(resolvedView); - if (!plugin) { + if (!getLspPlugin(resolvedView)) { notifyLspUnavailable(); return false; } - return acodeFindAllReferences(resolvedView); + return getLoadedLspClient().findAllReferences(resolvedView); }, }); addCommand({ @@ -1140,7 +1129,8 @@ function registerLspCommands() { readOnly: true, requiresView: false, run() { - return acodeCloseReferencesPanel(); + // The panel can only be open once the client has loaded. + return getLoadedLspClient()?.closeReferencesPanel() ?? false; }, }); addCommand({ @@ -1151,12 +1141,11 @@ function registerLspCommands() { async run(view) { const resolvedView = resolveView(view); if (!resolvedView) return false; - const plugin = LSPPlugin.get(resolvedView); - if (!plugin) { + if (!getLspPlugin(resolvedView)) { notifyLspUnavailable(); return false; } - return acodeFindAllReferencesInTab(resolvedView); + return getLoadedLspClient().findAllReferencesInTab(resolvedView); }, }); addCommand({ @@ -1165,7 +1154,8 @@ function registerLspCommands() { readOnly: true, requiresView: false, async run() { - const activeClients = clientManager.getActiveClients(); + const clientManager = getLoadedLspClient()?.clientManager; + const activeClients = clientManager?.getActiveClients() ?? []; if (!activeClients.length) { toast("No LSP servers are currently running"); return true; @@ -1187,7 +1177,8 @@ function registerLspCommands() { readOnly: true, requiresView: false, async run() { - const activeClients = clientManager.getActiveClients(); + const clientManager = getLoadedLspClient()?.clientManager; + const activeClients = clientManager?.getActiveClients() ?? []; if (!activeClients.length) { toast("No LSP servers are currently running"); return true; @@ -1208,6 +1199,7 @@ function registerLspCommands() { async run(view) { const resolvedView = resolveView(view); if (!resolvedView) return false; + const { showDocumentSymbols } = await import("components/symbolsPanel"); return showDocumentSymbols(resolvedView); }, }); @@ -1325,18 +1317,18 @@ function notifyLspUnavailable() { toast?.("Language server not available"); } -function runLspCommand(commandFn, options = {}) { +function runLspCommand(commandName, options = {}) { return (view) => { const resolvedView = resolveView(view); if (!resolvedView) return false; - const plugin = LSPPlugin.get(resolvedView); - if (!plugin) { + // Without a loaded client no editor has a language server attached. + if (!getLspPlugin(resolvedView)) { if (!options?.silentOnMissing) { notifyLspUnavailable(); } return false; } - const result = commandFn(resolvedView); + const result = getLoadedLspClient()[commandName](resolvedView); return result !== false; }; } @@ -1360,7 +1352,7 @@ function copyCommand(view) { return state.doc.sliceString(range.from, range.to); }); const textToCopy = texts.join("\n"); - cordova.plugins.clipboard.copy(textToCopy); + Bridge.clipboard.copy(textToCopy); return true; } @@ -1381,7 +1373,7 @@ function cutCommand(view) { segments.push(state.doc.sliceString(range.from, range.to)); changes.push({ from: range.from, to: range.to, insert: "" }); }); - cordova.plugins.clipboard.copy(segments.join("\n")); + Bridge.clipboard.copy(segments.join("\n")); resolvedView.dispatch({ changes, selection: EditorSelection.single( @@ -1394,7 +1386,7 @@ function cutCommand(view) { function pasteCommand(view) { const resolvedView = resolveView(view); if (!resolvedView) return false; - cordova.plugins.clipboard.paste((text = "") => { + Bridge.clipboard.paste((text = "") => { // replaceSelection measures the inserted text after line-ending // normalization, so CRLF clipboard text can't push the cursor past // the end of the document. @@ -1513,19 +1505,34 @@ function buildResolvedKeyBindingsSnapshot() { ); } +/** + * Resolve a command's effective description and key from the bindings. + * @returns {string|null} the key source + */ +function syncCommandBinding(command, name) { + const bindingInfo = resolveBindingInfo(name); + command.description = bindingInfo?.description || command.defaultDescription; + command.key = + bindingInfo && Object.prototype.hasOwnProperty.call(bindingInfo, "key") + ? bindingInfo.key + : (command.defaultKey ?? null); + return command.key; +} + +function invalidateKeymap() { + keymapDirty = true; +} + +function ensureKeymap() { + if (keymapDirty) rebuildKeymap(); +} + function rebuildKeymap() { cachedResolvedKeyBindings = buildResolvedKeyBindingsSnapshot(); const candidates = []; let order = 0; commandMap.forEach((command, name) => { - const bindingInfo = resolveBindingInfo(name); - command.description = - bindingInfo?.description || command.defaultDescription; - const keySource = - bindingInfo && Object.prototype.hasOwnProperty.call(bindingInfo, "key") - ? bindingInfo.key - : (command.defaultKey ?? null); - command.key = keySource; + const keySource = syncCommandBinding(command, name); const combos = parseKeyString(keySource); combos.forEach((combo) => { const cmKey = toCodeMirrorKey(combo); @@ -1550,9 +1557,15 @@ function rebuildKeymap() { const conflicts = []; for (const candidate of candidates) { const canonicalKey = canonicalizeKeyBinding(candidate.key); - const claimed = Array.from(claimedKeys.entries()).find(([key]) => - keyBindingsConflict(key, canonicalKey), - ); + // First conflicting claim in insertion order, without copying the map + // for every candidate. + let claimed = null; + for (const entry of claimedKeys) { + if (keyBindingsConflict(entry[0], canonicalKey)) { + claimed = entry; + break; + } + } if (claimed) { const [claimedKey, owner] = claimed; const appCommandShadowsCodeMirrorDefault = @@ -1595,6 +1608,7 @@ function rebuildKeymap() { cachedKeyBindingConflicts = conflicts; cachedKeymap = bindings; resolvedKeyBindingsVersion += 1; + keymapDirty = false; return bindings; } @@ -1642,6 +1656,7 @@ export function executeCommand(name, view, args) { } export function getRegisteredCommands() { + ensureKeymap(); return Array.from(commandMap.values()).map((command) => ({ name: command.name, description: command.description || command.defaultDescription, @@ -1650,22 +1665,27 @@ export function getRegisteredCommands() { } export function getResolvedKeyBindings() { + ensureKeymap(); return cachedResolvedKeyBindings; } export function getEffectiveKeyBindings() { + ensureKeymap(); return cachedEffectiveKeyBindings; } export function getKeyBindingConflicts() { + ensureKeymap(); return cachedKeyBindingConflicts.map((conflict) => ({ ...conflict })); } export function getResolvedKeyBindingsVersion() { + ensureKeymap(); return resolvedKeyBindingsVersion; } export function getCommandKeymapExtension() { + ensureKeymap(); return commandKeymapCompartment.of(keymap.of(cachedKeymap)); } @@ -1753,9 +1773,11 @@ export function registerExternalCommand(descriptor = {}) { const stored = commandMap.get(name); if (stored) { stored.key = normalized.key ?? stored.key; + // The returned command reflects its final binding right away. + syncCommandBinding(stored, name); } - rebuildKeymap(); + invalidateKeymap(); return stored; } @@ -1764,13 +1786,34 @@ export function removeExternalCommand(name) { const exists = commandMap.has(name); if (!exists) return false; commandMap.delete(name); - rebuildKeymap(); + invalidateKeymap(); return true; } +/** + * Apply the current keymap to a view. Calls made in the same task are applied + * together in a microtask, which always runs before the next key event. + */ export function refreshCommandKeymap(view) { const resolvedView = resolveView(view); - applyCommandKeymap(resolvedView); + if (!resolvedView) return; + pendingKeymapViews.add(resolvedView); + if (keymapRefreshScheduled) return; + keymapRefreshScheduled = true; + Promise.resolve().then(flushKeymapRefresh); +} + +function flushKeymapRefresh() { + keymapRefreshScheduled = false; + const views = Array.from(pendingKeymapViews); + pendingKeymapViews.clear(); + for (const view of views) { + try { + applyCommandKeymap(view); + } catch (error) { + console.error("Failed to apply command keymap", error); + } + } } function normalizeExternalCommand(descriptor) { @@ -1826,8 +1869,9 @@ function normalizeExternalKey(bindKey) { return combos.length ? combos.join("|") : null; } -function applyCommandKeymap(view, bindings = cachedKeymap) { +function applyCommandKeymap(view, bindings) { if (!view) return; + ensureKeymap(); commandViews.add(view); view.dispatch({ effects: commandKeymapCompartment.reconfigure( diff --git a/src/cm/emmet/extensions.js b/src/cm/emmet/extensions.js new file mode 100644 index 0000000000..7c1cab1e17 --- /dev/null +++ b/src/cm/emmet/extensions.js @@ -0,0 +1,26 @@ +import { Prec } from "@codemirror/state"; +import { keymap } from "@codemirror/view"; +import { + abbreviationTracker, + emmetConfig, + expandAbbreviation, + wrapWithAbbreviation, +} from "@emmetio/codemirror6-plugin"; + +export { emmetCompletionSource } from "@emmetio/codemirror6-plugin"; + +/** + * Emmet's editor extensions for one syntax. + * @param {string} syntax + * @param {{tracker?: object, config?: object}} [options] + */ +export function createEmmetExtensions(syntax, { tracker = {}, config } = {}) { + const { autocompleteTab = ["markup", "stylesheet"], ...restOverrides } = + config || {}; + return [ + Prec.high(abbreviationTracker({ syntax, ...tracker })), + wrapWithAbbreviation(), + keymap.of([{ key: "Mod-e", run: expandAbbreviation }]), + emmetConfig.of({ syntax, autocompleteTab, ...restOverrides }), + ]; +} diff --git a/src/cm/emmet/index.js b/src/cm/emmet/index.js new file mode 100644 index 0000000000..73c3526c8e --- /dev/null +++ b/src/cm/emmet/index.js @@ -0,0 +1,60 @@ +import { Compartment } from "@codemirror/state"; +import whenAppVisible from "utils/whenAppVisible"; + +/** + * Emmet's syntaxes (EmmetKnownSyntax), kept here so choosing one does not load + * the Emmet package. + */ +export const EmmetSyntax = Object.freeze({ + html: "html", + xml: "xml", + xsl: "xsl", + jsx: "jsx", + tsx: "tsx", + vue: "vue", + haml: "haml", + jade: "jade", + pug: "pug", + slim: "slim", + css: "css", + scss: "scss", + less: "less", + sass: "sass", + sss: "sss", + stylus: "stylus", + postcss: "postcss", +}); + +/** Holds Emmet's extensions; empty until the Emmet chunk has loaded. */ +export const emmetCompartment = new Compartment(); + +/** @type {typeof import("./extensions") | null} */ +let emmet = null; +/** @type {Promise | null} */ +let loading = null; + +/** The loaded Emmet module, or null while it is not needed or still loading. */ +export function getLoadedEmmet() { + return emmet; +} + +/** + * Loads Emmet once the editor is visible; repeated calls share one load. + * @returns {Promise} + */ +export function loadEmmet() { + loading ??= whenAppVisible() + .then(() => import(/* webpackChunkName: "emmet" */ "./extensions")) + .then( + (module) => { + emmet = module; + return module; + }, + (error) => { + loading = null; + console.error("Failed to load Emmet", error); + throw error; + }, + ); + return loading; +} diff --git a/src/cm/keyBindingUtils.js b/src/cm/keyBindingUtils.js index 69e2a3583b..06bf26e2d2 100644 --- a/src/cm/keyBindingUtils.js +++ b/src/cm/keyBindingUtils.js @@ -45,8 +45,23 @@ export function toCodeMirrorKey(combo) { return strokes.length ? strokes.join(" ") : null; } +// Conflict checks compare every binding with every other one on each keymap +// rebuild, so cache the parsed form. The app has a few hundred binding strings; +// the cap only stops unbounded growth from repeated registrations of new keys. +const MAX_CANONICAL_KEY_CACHE_SIZE = 1000; +const canonicalKeyCache = new Map(); + export function canonicalizeKeyBinding(combo) { - return toCodeMirrorKey(combo)?.toLowerCase() || null; + if (typeof combo !== "string") { + return toCodeMirrorKey(combo)?.toLowerCase() || null; + } + if (canonicalKeyCache.has(combo)) return canonicalKeyCache.get(combo); + const canonicalKey = toCodeMirrorKey(combo)?.toLowerCase() || null; + if (canonicalKeyCache.size >= MAX_CANONICAL_KEY_CACHE_SIZE) { + canonicalKeyCache.clear(); + } + canonicalKeyCache.set(combo, canonicalKey); + return canonicalKey; } /** diff --git a/src/cm/lsp/client.ts b/src/cm/lsp/client.ts new file mode 100644 index 0000000000..755b82f20a --- /dev/null +++ b/src/cm/lsp/client.ts @@ -0,0 +1,29 @@ +/** + * The language-server client and the editor features built on it. Loaded on + * demand through clientLoader, so editors without a language server never + * parse it. + */ +export { + formatDocument, + LSPPlugin, + serverCompletionSource, +} from "@codemirror/lsp-client"; +export { + default as clientManager, + lspCompletionEnabled, +} from "./clientManager"; +export { + jumpToDeclaration, + jumpToDefinition, + jumpToImplementation, + jumpToTypeDefinition, + nextSignature, + prevSignature, + renameSymbol, + showSignatureHelp, +} from "./index"; +export { + closeReferencesPanel, + findAllReferences, + findAllReferencesInTab, +} from "./references"; diff --git a/src/cm/lsp/clientLoader.ts b/src/cm/lsp/clientLoader.ts new file mode 100644 index 0000000000..bf99f83b5a --- /dev/null +++ b/src/cm/lsp/clientLoader.ts @@ -0,0 +1,65 @@ +import type { EditorView } from "@codemirror/view"; +import whenAppVisible from "utils/whenAppVisible"; +import type * as LspClient from "./client"; +import type { ClientManagerOptions } from "./types"; + +type LspClientModule = typeof LspClient; +type LspPluginInstance = ReturnType; + +let client: LspClientModule | null = null; +let loading: Promise | null = null; +let pendingOptions: Partial = {}; + +/** + * The client module once loaded, otherwise null. While it is null no editor + * can have a language server attached. + */ +export function getLoadedLspClient(): LspClientModule | null { + return client; +} + +/** Loads the client once the editor is visible; calls share one load. */ +export function loadLspClient(): Promise { + loading ??= whenAppVisible() + .then(() => import(/* webpackChunkName: "lspClient" */ "./client")) + .then( + (module) => { + module.clientManager.setOptions(pendingOptions); + pendingOptions = {}; + client = module; + return module; + }, + (error) => { + loading = null; + throw error; + }, + ); + return loading; +} + +/** Client options, kept until the client loads. */ +export function setLspOptions(options: Partial): void { + if (client) client.clientManager.setOptions(options); + else pendingOptions = { ...pendingOptions, ...options }; +} + +export function getLspPlugin( + view: EditorView, + lspClient?: Parameters[1], +): LspPluginInstance | null { + return client?.LSPPlugin.get(view, lspClient) ?? null; +} + +export function getAllLspPlugins( + view: EditorView, + feature?: Parameters[1], +): ReturnType { + return client?.LSPPlugin.getAll(view, feature) ?? []; +} + +export function getLspPluginForFeature( + view: EditorView, + feature: Parameters[1], +): ReturnType | null { + return client?.LSPPlugin.getForFeature(view, feature) ?? null; +} diff --git a/src/cm/lsp/diagnostics.ts b/src/cm/lsp/diagnostics.ts index 6768b27b2a..b13e08f1c2 100644 --- a/src/cm/lsp/diagnostics.ts +++ b/src/cm/lsp/diagnostics.ts @@ -1,6 +1,5 @@ import { Diagnostic, linter, lintGutter } from "@codemirror/lint"; import type { LSPClient } from "@codemirror/lsp-client"; -import { LSPPlugin } from "@codemirror/lsp-client"; import type { Extension } from "@codemirror/state"; import { EditorState, @@ -9,6 +8,7 @@ import { StateField, } from "@codemirror/state"; import { type EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view"; +import { getAllLspPlugins, getLspPlugin } from "./clientLoader"; import { addLspLogFor } from "./logs"; import { safeLspPositionToOffset } from "./positionUtils"; import type { @@ -65,7 +65,7 @@ function supportsPullDiagnostics(client: LSPClient): boolean { function diagnosticsEnabledForFile(client: LSPClient, uri: string): boolean { const file = client.workspace.getFile(uri); const view = file?.getView(); - const plugin = view && LSPPlugin.get(view, client); + const plugin = view && getLspPlugin(view, client); return !!plugin?.featureEnabled("diagnostics"); } @@ -255,7 +255,7 @@ function applyDiagnostics( } const view = file.getView(); if (!view) return false; - const plugin = LSPPlugin.get(view, client); + const plugin = getLspPlugin(view, client); if (!plugin || !plugin.featureEnabled("diagnostics")) return false; const diagnostics = collectLspDiagnostics( @@ -446,7 +446,7 @@ export function lspDiagnosticsAutoSyncExtension(): Extension { flush(): void { this.pending = null; - for (const plugin of LSPPlugin.getAll(this.view, "diagnostics")) { + for (const plugin of getAllLspPlugins(this.view, "diagnostics")) { plugin.client.sync(); schedulePullDiagnostics(plugin.client, plugin.uri, 0); } @@ -488,7 +488,7 @@ function lspLinterSource(view: EditorView): Diagnostic[] { const stored = view.state.field(lspPublishedDiagnostics); const diagnostics: Diagnostic[] = []; for (const [client, items] of stored) { - const plugin = LSPPlugin.get(view, client); + const plugin = getLspPlugin(view, client); if (plugin?.featureEnabled("diagnostics")) diagnostics.push(...items); } return diagnostics; diff --git a/src/cm/lsp/documentColors.ts b/src/cm/lsp/documentColors.ts index efacbb851e..a21636c3ca 100644 --- a/src/cm/lsp/documentColors.ts +++ b/src/cm/lsp/documentColors.ts @@ -1,5 +1,4 @@ import type { LSPClient, LSPClientExtension } from "@codemirror/lsp-client"; -import { LSPPlugin } from "@codemirror/lsp-client"; import type { Extension, Range } from "@codemirror/state"; import { MapMode, StateEffect, StateField } from "@codemirror/state"; import { @@ -32,6 +31,11 @@ import { lspColorToHex, openColorPicker, } from "../colorChip"; +import { + getAllLspPlugins, + getLspPlugin, + getLspPluginForFeature, +} from "./clientLoader"; import { safeLspPositionToOffset } from "./positionUtils"; import type { LSPPluginAPI } from "./types"; @@ -292,7 +296,7 @@ function createPlugin(config: DocumentColorsConfig) { return; } - const bindings = LSPPlugin.getAll( + const bindings = getAllLspPlugins( this.view, "documentColor", ) as readonly LSPPluginAPI[]; @@ -436,8 +440,8 @@ async function handleColorPick( ): Promise { const lsp = ( payload.lspClient - ? LSPPlugin.get(view, payload.lspClient) - : LSPPlugin.getForFeature(view, "documentColor") + ? getLspPlugin(view, payload.lspClient) + : getLspPluginForFeature(view, "documentColor") ) as LSPPluginAPI | null; if (!lsp?.client.connected) return; @@ -454,8 +458,8 @@ async function handleColorPick( const lsp2 = ( payload.lspClient - ? LSPPlugin.get(view, payload.lspClient) - : LSPPlugin.getForFeature(view, "documentColor") + ? getLspPlugin(view, payload.lspClient) + : getLspPluginForFeature(view, "documentColor") ) as LSPPluginAPI | null; if (!lsp2?.client.connected) return; diff --git a/src/cm/lsp/formatter.ts b/src/cm/lsp/formatter.ts index 440f1e22c3..5ed527ce6a 100644 --- a/src/cm/lsp/formatter.ts +++ b/src/cm/lsp/formatter.ts @@ -1,7 +1,7 @@ import type { EditorView } from "@codemirror/view"; import { getModes } from "cm/modelist"; import toast from "components/toast"; -import lspClientManager from "./clientManager"; +import { loadLspClient } from "./clientLoader"; import { supportsBuiltinFormatting } from "./formattingSupport"; import serverRegistry from "./serverRegistry"; import type { AcodeApi, FileMetadata } from "./types"; @@ -69,7 +69,8 @@ export function registerLspFormatter(acode: AcodeApi): void { ...metadata, languageName: metadata.languageName || languageId, }; - const success = await lspClientManager.formatDocument(fullMetadata); + const { clientManager } = await loadLspClient(); + const success = await clientManager.formatDocument(fullMetadata); if (!success) { toast("LSP formatter failed"); } diff --git a/src/cm/lsp/runtimeProviders.ts b/src/cm/lsp/runtimeProviders.ts index 5c9ceb4314..c8c32b2d3f 100644 --- a/src/cm/lsp/runtimeProviders.ts +++ b/src/cm/lsp/runtimeProviders.ts @@ -174,6 +174,7 @@ export function inferWorkspaceKind( if (!scheme) return uri.startsWith("/") ? "app-private" : "unknown"; if (scheme === "file") return "app-private"; + if (scheme === "alpine") return "builtin-alpine"; if (scheme === "untitled") return "virtual"; if ( scheme === "ftp" || @@ -203,6 +204,7 @@ export function isBuiltinAlpineAccessible( if (!scheme) return uri.startsWith("/"); if (scheme === "file") return true; + if (scheme === "alpine") return true; if (scheme !== "content") return false; return /^content:\/\/com\.foxdebug\.acode(?:free)?\.documents\//i.test(uri); diff --git a/src/cm/lsp/runtimes/builtinAlpine.ts b/src/cm/lsp/runtimes/builtinAlpine.ts index eb0b2475ba..2f107ca138 100644 --- a/src/cm/lsp/runtimes/builtinAlpine.ts +++ b/src/cm/lsp/runtimes/builtinAlpine.ts @@ -70,16 +70,25 @@ export const builtinAlpineRuntimeProvider: LspRuntimeProvider = { server: LspServerDefinition, context: LspRuntimeUriResolutionContext, ) { + const documentUri = context.originalDocumentUri || context.uri; + if (documentUri?.startsWith("alpine://localhost/")) { + const root = context.originalRootUri || context.rootUri; + return { + documentUri: documentUri.replace("alpine://localhost/", "file:///"), + rootUri: root?.replace("alpine://localhost/", "file:///") || null, + scope: root ? "workspace" : "document", + }; + } if (canUseRealPath(context) && !isUntitled(context)) return null; - const documentUri = cacheDocumentUri(context); - if (!documentUri) { + const cachedUri = cacheDocumentUri(context); + if (!cachedUri) { throw new Error( `Built-in Alpine cannot resolve a cache URI for ${context.originalDocumentUri}`, ); } return { - documentUri, + documentUri: cachedUri, rootUri: null, scope: "document", }; diff --git a/src/cm/lsp/runtimes/registerBuiltins.ts b/src/cm/lsp/runtimes/registerBuiltins.ts index 5e49c5c9fc..bdbfab3075 100644 --- a/src/cm/lsp/runtimes/registerBuiltins.ts +++ b/src/cm/lsp/runtimes/registerBuiltins.ts @@ -3,6 +3,9 @@ import builtinAlpineRuntimeProvider from "./builtinAlpine"; import externalWebSocketRuntimeProvider from "./externalWebSocket"; import webWorkerRuntimeProvider from "./webWorker"; -registerRuntimeProvider(builtinAlpineRuntimeProvider, { replace: true }); +if (platform.localExecution) + registerRuntimeProvider(builtinAlpineRuntimeProvider, { replace: true }); registerRuntimeProvider(externalWebSocketRuntimeProvider, { replace: true }); registerRuntimeProvider(webWorkerRuntimeProvider, { replace: true }); + +import platform from "lib/platform"; diff --git a/src/cm/lsp/runtimes/webWorker.ts b/src/cm/lsp/runtimes/webWorker.ts index 2cec4c7030..7b1f3a2f57 100644 --- a/src/cm/lsp/runtimes/webWorker.ts +++ b/src/cm/lsp/runtimes/webWorker.ts @@ -18,6 +18,14 @@ const WORKER_URLS: Record = { }; const STARTUP_TIMEOUT = 10000; +interface ListedEntry { + name: string; + url: string; + isDirectory?: boolean; + isFile?: boolean; + isLink?: boolean; +} + const bundledStatus: InstallCheckResult = { status: "present", version: "bundled", @@ -26,13 +34,42 @@ const bundledStatus: InstallCheckResult = { message: "Built into Acode and runs offline in a Web Worker.", }; -async function readFileFromHost(uri: string): Promise { +async function fileSystemFor(uri: string) { const { default: fsOperation } = await import("fileSystem"); const fs = fsOperation(uri); if (!fs) throw new Error(`No filesystem provider can handle ${uri}`); + return fs; +} + +async function readFileFromHost( + uri: string, + maxBytes?: number, +): Promise { + const fs = await fileSystemFor(uri); + if (maxBytes && typeof fs.stat === "function") { + const { size } = await fs.stat(); + if (size > maxBytes) throw new Error(`${uri} exceeds ${maxBytes} bytes`); + } return (await fs.readFile("utf-8")) as string; } +async function readDirectoryFromHost(uri: string) { + const fs = await fileSystemFor(uri); + const entries: ListedEntry[] = await fs.lsDir(); + return entries.map((entry) => ({ + name: entry.name, + url: entry.url, + // Symlinked folders (e.g. pnpm's node_modules) are listed as links. + isDirectory: !!entry.isDirectory || (!!entry.isLink && !entry.isFile), + })); +} + +function requireUri(params: Record): string { + const uri = String(params.uri ?? ""); + if (!uri) throw new Error("A filesystem URI is required"); + return uri; +} + function createBuiltinWorkerTransport( server: LspServerDefinition, context: TransportContext, @@ -54,11 +91,12 @@ function createBuiltinWorkerTransport( rootUri: context.originalRootUri ?? context.rootUri, }, hostHandlers: { - readFile: async (params) => { - const uri = String(params.uri ?? ""); - if (!uri) throw new Error("A filesystem URI is required"); - return readFileFromHost(uri); - }, + readFile: (params) => + readFileFromHost( + requireUri(params), + Number(params.maxBytes) || undefined, + ), + readDirectory: (params) => readDirectoryFromHost(requireUri(params)), }, }); } diff --git a/src/cm/lsp/workerTransport.ts b/src/cm/lsp/workerTransport.ts index d5263ec0f1..9d6527b7d3 100644 --- a/src/cm/lsp/workerTransport.ts +++ b/src/cm/lsp/workerTransport.ts @@ -8,6 +8,7 @@ import { addLspLog } from "./logs"; import type { Transport, TransportHandle } from "./types"; const DEFAULT_STARTUP_TIMEOUT = 10_000; +const PROGRESS_CREATE = "window/workDoneProgress/create"; export type LspWorkerHostHandler = ( params: Record, @@ -194,6 +195,24 @@ export function createWorkerTransport( } } + // The client advertises work-done progress but answers unknown server + // requests with MethodNotFound, which would forbid using the token. + function acknowledgeProgressToken(data: string): boolean { + if (!data.includes(PROGRESS_CREATE)) return false; + try { + const message = JSON.parse(data); + if (message?.method !== PROGRESS_CREATE || message.id === undefined) { + return false; + } + worker.postMessage( + JSON.stringify({ jsonrpc: "2.0", id: message.id, result: null }), + ); + return true; + } catch { + return false; + } + } + async function handleHostRequest( message: WorkerControlMessage, ): Promise { @@ -262,7 +281,7 @@ export function createWorkerTransport( if (disposed) return; const data = event.data; if (typeof data === "string") { - dispatchToListeners(data); + if (!acknowledgeProgressToken(data)) dispatchToListeners(data); return; } if (!isControlMessage(data)) return; diff --git a/src/cm/lsp/workers/progress.ts b/src/cm/lsp/workers/progress.ts new file mode 100644 index 0000000000..ae0878a328 --- /dev/null +++ b/src/cm/lsp/workers/progress.ts @@ -0,0 +1,53 @@ +export interface WorkDoneProgress { + report(message: string, percentage?: number): void; + end(message?: string): void; +} + +export interface ProgressChannel { + /** Resolves once the client is initialized, with its progress support. */ + ready: Promise; + request(method: string, params: unknown): Promise; + notify(method: string, params: unknown): void; +} + +let nextToken = 0; + +/** + * Standard LSP work-done progress: the token is created through the client + * and every notification waits for the previous one, so begin, reports and + * end always arrive in order. + */ +export default function createProgress( + channel: ProgressChannel, + title: string, + message?: string, +): WorkDoneProgress { + const token = `acode-worker-progress-${++nextToken}`; + let created = channel.ready.then( + (supported) => + supported && + channel.request("window/workDoneProgress/create", { token }).then( + () => true, + () => false, + ), + ); + let ended = false; + const send = (value: Record) => { + created = created.then((usable) => { + if (usable) channel.notify("$/progress", { token, value }); + return usable; + }); + }; + + send({ kind: "begin", title, message, cancellable: false }); + return { + report(text, percentage) { + if (!ended) send({ kind: "report", message: text, percentage }); + }, + end(text) { + if (ended) return; + ended = true; + send({ kind: "end", message: text }); + }, + }; +} diff --git a/src/cm/lsp/workers/protocol.ts b/src/cm/lsp/workers/protocol.ts index 5daf735c5b..c49c24412d 100644 --- a/src/cm/lsp/workers/protocol.ts +++ b/src/cm/lsp/workers/protocol.ts @@ -3,6 +3,7 @@ import { type TextDocumentContentChangeEvent, } from "vscode-languageserver-textdocument"; import type { Diagnostic } from "vscode-languageserver-types"; +import createProgress, { type WorkDoneProgress } from "./progress"; export const METHOD_NOT_HANDLED = Symbol("method-not-handled"); @@ -13,6 +14,8 @@ interface JsonRpcMessage { id?: JsonRpcId; method?: string; params?: unknown; + result?: unknown; + error?: { message?: string }; } interface ConfigureMessage { @@ -32,10 +35,31 @@ interface HostResponseMessage { interface HostRequestMessage { kind: "host-request"; id: number; - method: "readFile"; + method: "readFile" | "readDirectory"; + uri: string; + maxBytes?: number; +} + +export interface DirectoryEntry { + name: string; + url: string; + isDirectory: boolean; +} + +interface WorkspaceFolder { uri: string; } +interface WorkspaceFoldersParams { + event?: { added?: WorkspaceFolder[]; removed?: WorkspaceFolder[] }; +} + +interface InitializeParams { + rootUri?: string | null; + workspaceFolders?: WorkspaceFolder[] | null; + capabilities?: { window?: { workDoneProgress?: boolean } }; +} + interface WorkerScope { onmessage: ((event: MessageEvent) => void) | null; postMessage(message: unknown): void; @@ -73,7 +97,13 @@ export interface WorkerServerContext { initializationOptions?: Record; rootUri?: string | null; getProjectVersion(): string; - requestFile(uri: string): Promise; + requestFile(uri: string, maxBytes?: number): Promise; + requestDirectory(uri: string): Promise; + /** Re-run diagnostics for every open document. */ + revalidate(): void; + log(level: "error" | "warn" | "info", message: string): void; + /** Show standard LSP work-done progress in the client. */ + progress(title: string, message?: string): WorkDoneProgress; } export interface WorkerLanguageAdapter { @@ -84,7 +114,10 @@ export interface WorkerLanguageAdapter { params: unknown, ): unknown | PromiseLike | typeof METHOD_NOT_HANDLED; configure?(settings: unknown): void; + openDocument?(uri: string): void; closeDocument?(uri: string): void; + addWorkspaceFolder?(uri: string): void; + removeWorkspaceFolder?(uri: string): void; dispose?(): void; } @@ -101,10 +134,23 @@ const hostRequests = new Map< { resolve: (value: unknown) => void; reject: (error: Error) => void } >(); +const clientRequests = new Map< + JsonRpcId, + { resolve: (value: unknown) => void; reject: (error: Error) => void } +>(); + let adapter: WorkerLanguageAdapter | null = null; let serverId = "worker"; let nextHostRequestId = 0; +let nextClientRequestId = 0; let projectVersion = 0; +let supportsProgress = false; +let markClientReady: (supportsProgress: boolean) => void = () => {}; +// Progress must wait for `initialized`: the client is not ready for +// server-initiated requests before then. +const clientReady = new Promise((resolve) => { + markClientReady = resolve; +}); function sendJson(message: unknown): void { workerScope.postMessage(JSON.stringify(message)); @@ -130,6 +176,30 @@ function sendNotification(method: string, params: unknown): void { sendJson({ jsonrpc: "2.0", method, params }); } +function requestClient(method: string, params: unknown): Promise { + const id = `worker-${++nextClientRequestId}`; + return new Promise((resolve, reject) => { + clientRequests.set(id, { resolve, reject }); + sendJson({ jsonrpc: "2.0", id, method, params }); + }); +} + +function handleClientResponse(message: JsonRpcMessage): void { + const pending = message.id != null && clientRequests.get(message.id); + if (!pending) return; + clientRequests.delete(message.id!); + if (message.error) pending.reject(new Error(message.error.message)); + else pending.resolve(message.result); +} + +function progress(title: string, message?: string): WorkDoneProgress { + return createProgress( + { ready: clientReady, request: requestClient, notify: sendNotification }, + title, + message, + ); +} + function sendLog(level: "error" | "warn" | "info", message: string): void { workerScope.postMessage({ kind: "log", level, message }); } @@ -150,13 +220,18 @@ function isHostResponse(value: unknown): value is HostResponseMessage { ); } -function requestHost(method: HostRequestMessage["method"], uri: string) { +function requestHost( + method: HostRequestMessage["method"], + uri: string, + maxBytes?: number, +) { const id = ++nextHostRequestId; const message: HostRequestMessage = { kind: "host-request", id, method, uri, + maxBytes, }; return new Promise((resolve, reject) => { hostRequests.set(id, { resolve, reject }); @@ -164,8 +239,17 @@ function requestHost(method: HostRequestMessage["method"], uri: string) { }); } -async function requestFile(uri: string): Promise { - return String(await requestHost("readFile", uri)); +async function requestFile(uri: string, maxBytes?: number): Promise { + return String(await requestHost("readFile", uri, maxBytes)); +} + +async function requestDirectory(uri: string): Promise { + const entries = await requestHost("readDirectory", uri); + return Array.isArray(entries) ? (entries as DirectoryEntry[]) : []; +} + +function revalidate(): void { + for (const uri of documents.keys()) scheduleValidation(uri); } function handleHostResponse(message: HostResponseMessage): void { @@ -227,6 +311,7 @@ function didOpen(params: DidOpenParams): void { ); documents.set(item.uri, document); projectVersion++; + adapter?.openDocument?.(item.uri); scheduleValidation(item.uri); } @@ -249,6 +334,23 @@ function didClose(params: DidCloseParams): void { publishDiagnostics(uri, 0, []); } +function initialize(params: InitializeParams | null): void { + supportsProgress = params?.capabilities?.window?.workDoneProgress === true; + for (const folder of params?.workspaceFolders ?? []) { + adapter?.addWorkspaceFolder?.(folder.uri); + } + if (params?.rootUri) adapter?.addWorkspaceFolder?.(params.rootUri); +} + +function changeWorkspaceFolders(params: WorkspaceFoldersParams | null): void { + for (const folder of params?.event?.removed ?? []) { + adapter?.removeWorkspaceFolder?.(folder.uri); + } + for (const folder of params?.event?.added ?? []) { + adapter?.addWorkspaceFolder?.(folder.uri); + } +} + function cancelRequest(params: unknown): void { const id = (params as { id?: JsonRpcId } | null)?.id; if (id !== undefined) cancelledRequests.add(id); @@ -261,6 +363,7 @@ async function handleRequest(message: JsonRpcMessage): Promise { try { switch (method) { case "initialize": + initialize(message.params as InitializeParams | null); sendResponse(id, { capabilities: { textDocumentSync: { @@ -322,10 +425,17 @@ function handleNotification(message: JsonRpcMessage): void { ); for (const uri of documents.keys()) scheduleValidation(uri); break; + case "initialized": + markClientReady(supportsProgress); + break; + case "workspace/didChangeWorkspaceFolders": + changeWorkspaceFolders(message.params as WorkspaceFoldersParams | null); + break; case "$/cancelRequest": cancelRequest(message.params); break; case "exit": + markClientReady(false); adapter?.dispose?.(); workerScope.close(); break; @@ -341,7 +451,10 @@ async function handleJsonRpc(data: string): Promise { return; } - if (!message.method) return; + if (!message.method) { + handleClientResponse(message); + return; + } if (message.id !== undefined) { await handleRequest(message); } else { @@ -366,6 +479,10 @@ export function startWorkerServer(factory: AdapterFactory): void { rootUri: data.rootUri, getProjectVersion: () => String(projectVersion), requestFile, + requestDirectory, + revalidate, + log: sendLog, + progress, }), ).then( (value) => { diff --git a/src/cm/lsp/workers/typescript.worker.ts b/src/cm/lsp/workers/typescript.worker.ts index 4a791e5746..c0038c91c0 100644 --- a/src/cm/lsp/workers/typescript.worker.ts +++ b/src/cm/lsp/workers/typescript.worker.ts @@ -1,220 +1,79 @@ -import ts from "typescript"; -import { TextDocument } from "vscode-languageserver-textdocument"; -import { - type CodeAction, - type CodeActionContext, - type CompletionItem, - CompletionItemKind, - type Diagnostic, - DiagnosticSeverity, - DiagnosticTag, - type DocumentHighlight, - DocumentHighlightKind, - type DocumentSymbol, - type FoldingRange, - FoldingRangeKind, - type FormattingOptions, - type InlayHint, - InlayHintKind, - type Location, - type LocationLink, - type SelectionRange as LspSelectionRange, - type MarkupContent, - type Position, +import type { + CodeActionContext, + CompletionItem, + FormattingOptions, + Position, Range, - SelectionRange, - type SignatureHelp, - SymbolKind, - type TextEdit, - type WorkspaceEdit, } from "vscode-languageserver-types"; import { getTextDocument, METHOD_NOT_HANDLED, startWorkerServer, } from "./protocol"; +import { + type CompletionData, + completions, + hover, + resolveCompletion, + signatureHelp, +} from "./typescript/assist"; +import type { SignatureContext } from "./typescript/convert"; +import { + diagnostics, + documentSymbols, + foldingRanges, + format, + inlayHints, + selectionRanges, +} from "./typescript/features"; +import { + codeActions, + definitions, + documentHighlights, + implementations, + prepareRename, + references, + rename, + typeDefinitions, +} from "./typescript/navigation"; +import TypeScriptWorkspace from "./typescript/workspace"; import libraries from "./typescriptLibs"; -interface CompletionData { - acodeLspProvider: "typescript"; - uri: string; - offset: number; - name: string; - source?: string; - entryData?: ts.CompletionEntryData; -} - interface RequestParams { - position: Position; - range?: Range; + position?: Position; + positions: Position[]; + range: Range; options?: FormattingOptions; newName: string; - context: CodeActionContext & { - triggerKind?: number; - triggerCharacter?: string; - isRetrigger?: boolean; - }; + context: CodeActionContext & SignatureContext; } -class TypeScriptHost implements ts.LanguageServiceHost { - constructor( - private readonly documents: Map, - private readonly options: ts.CompilerOptions, - private readonly projectVersion: () => string, - ) {} - - getCompilationSettings(): ts.CompilerOptions { - return this.options; - } - - getCurrentDirectory(): string { - return "/"; - } - - getDefaultLibFileName(options: ts.CompilerOptions): string { - return ts.getDefaultLibFileName(options); - } - - getScriptFileNames(): string[] { - return [...this.documents.keys()]; - } - - getScriptVersion(fileName: string): string { - const document = this.documents.get(fileName); - return document ? String(document.version) : "1"; - } - - getProjectVersion(): string { - return this.projectVersion(); - } - - getScriptSnapshot(fileName: string): ts.IScriptSnapshot | undefined { - const text = this.readFile(fileName); - return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text); - } - - getScriptKind(fileName: string): ts.ScriptKind { - const languageId = this.documents.get(fileName)?.languageId; - if (languageId === "typescriptreact" || languageId === "tsx") { - return ts.ScriptKind.TSX; - } - if (languageId === "javascriptreact" || languageId === "jsx") { - return ts.ScriptKind.JSX; - } - if (languageId === "typescript") return ts.ScriptKind.TS; - if (languageId === "javascript") return ts.ScriptKind.JS; - const path = uriPath(fileName).toLowerCase(); - if (path.endsWith(".tsx")) return ts.ScriptKind.TSX; - if (path.endsWith(".jsx")) return ts.ScriptKind.JSX; - if ( - path.endsWith(".ts") || - path.endsWith(".mts") || - path.endsWith(".cts") - ) { - return ts.ScriptKind.TS; - } - if ( - path.endsWith(".js") || - path.endsWith(".mjs") || - path.endsWith(".cjs") - ) { - return ts.ScriptKind.JS; - } - if (path.endsWith(".json")) return ts.ScriptKind.JSON; - return ts.ScriptKind.Unknown; - } - - fileExists(fileName: string): boolean { - return this.documents.has(fileName) || fileName in libraries; - } - - readFile(fileName: string): string | undefined { - return this.documents.get(fileName)?.getText() ?? libraries[fileName]; - } - - readDirectory(): string[] { - return [...this.documents.keys()]; - } - - directoryExists(): boolean { - return true; - } - - getDirectories(): string[] { - return []; - } - - useCaseSensitiveFileNames(): boolean { - return true; - } - - getNewLine(): string { - return "\n"; - } - - resolveModuleNames( - moduleNames: string[], - containingFile: string, - ): (ts.ResolvedModule | undefined)[] { - return moduleNames.map((moduleName) => { - const openDocument = this.resolveOpenDocument(moduleName, containingFile); - if (openDocument) return openDocument; - return ts.resolveModuleName( - moduleName, - containingFile, - this.options, - this, - ).resolvedModule; - }); - } - - private resolveOpenDocument( - moduleName: string, - containingFile: string, - ): ts.ResolvedModule | undefined { - if (!moduleName.startsWith(".") && !/^[a-z]+:/i.test(moduleName)) { - return undefined; - } - let base: string; - try { - base = new URL(moduleName, containingFile).href; - } catch { - return undefined; - } - const candidates = [ - base, - `${base}.ts`, - `${base}.tsx`, - `${base}.js`, - `${base}.jsx`, - `${base}/index.ts`, - `${base}/index.tsx`, - `${base}/index.js`, - `${base}/index.jsx`, - ]; - for (const candidate of candidates) { - if (!this.documents.has(candidate)) continue; - return { - resolvedFileName: candidate, - isExternalLibraryImport: false, - }; - } - return undefined; - } -} +const MAX_FILE_BYTES = 2 * 1024 * 1024; startWorkerServer( - async ({ documents, requestFile, rootUri, getProjectVersion }) => { - const compilerOptions = await loadCompilerOptions(rootUri, requestFile); - const host = new TypeScriptHost( + ({ + documents, + rootUri, + getProjectVersion, + requestFile, + requestDirectory, + revalidate, + log, + progress, + }) => { + const workspace = new TypeScriptWorkspace({ documents, - compilerOptions, - getProjectVersion, - ); - const service = ts.createLanguageService( - host, - ts.createDocumentRegistry(true, "/"), - ); + documentsVersion: getProjectVersion, + libraries, + host: { + readDirectory: requestDirectory, + readFile: (uri) => requestFile(uri, MAX_FILE_BYTES), + }, + onChange: revalidate, + log: (message) => log("info", message), + progress, + }); + if (rootUri) workspace.addFolder(rootUri); return { capabilities: { @@ -231,6 +90,8 @@ startWorkerServer( documentRangeFormattingProvider: true, documentSymbolProvider: true, definitionProvider: true, + typeDefinitionProvider: true, + implementationProvider: true, referencesProvider: true, renameProvider: { prepareProvider: true, @@ -242,727 +103,78 @@ startWorkerServer( inlayHintProvider: true, }, - validate(document) { - const diagnostics: ts.Diagnostic[] = [ - ...service.getSyntacticDiagnostics(document.uri), - ...service.getSuggestionDiagnostics(document.uri), - ]; - if (isTypeScriptDocument(document)) { - diagnostics.push(...service.getSemanticDiagnostics(document.uri)); - } - return diagnostics.map((diagnostic) => - toDiagnostic(document, diagnostic), - ); - }, + validate: (document) => diagnostics(workspace.target(document)), request(method, params) { if (method === "completionItem/resolve") { - return resolveCompletion( - service, - documents, - params as CompletionItem, - ); + const item = params as CompletionItem; + const data = item.data as CompletionData | undefined; + const document = data && documents.get(data.uri); + return document + ? resolveCompletion(workspace.target(document), item, data) + : item; } const document = getTextDocument(documents, params); if (!document) return null; const request = params as RequestParams; + const target = workspace.target(document); const offset = request.position ? document.offsetAt(request.position) : 0; switch (method) { - case "acode/validate": { - const diagnostics: ts.Diagnostic[] = [ - ...service.getSyntacticDiagnostics(document.uri), - ...service.getSuggestionDiagnostics(document.uri), - ]; - if (isTypeScriptDocument(document)) { - diagnostics.push(...service.getSemanticDiagnostics(document.uri)); - } - return diagnostics.map((diagnostic) => - toDiagnostic(document, diagnostic), - ); - } + case "acode/validate": + return diagnostics(target); case "textDocument/completion": - return completions(service, document, offset); + return completions(target, offset); case "textDocument/hover": - return hover(service, document, offset); + return hover(target, offset); case "textDocument/signatureHelp": - return signatureHelp(service, document, offset, request.context); + return signatureHelp(target, offset, request.context); case "textDocument/formatting": - return format(service, document, undefined, request.options); + return format(target, undefined, request.options); case "textDocument/rangeFormatting": - return format(service, document, request.range, request.options); + return format(target, request.range, request.options); case "textDocument/documentSymbol": - return documentSymbols(service, document); + return documentSymbols(target); case "textDocument/definition": - return definitions(service, documents, document, offset); + return definitions(target, offset); + case "textDocument/typeDefinition": + return typeDefinitions(target, offset); + case "textDocument/implementation": + return implementations(target, offset); case "textDocument/references": - return references(service, documents, document, offset); - case "textDocument/prepareRename": { - const info = service.getRenameInfo(document.uri, offset, { - allowRenameOfImportPath: true, - }); - return info.canRename - ? rangeFromSpan(document, info.triggerSpan) - : null; - } + return references(target, offset); + case "textDocument/prepareRename": + return prepareRename(target, offset); case "textDocument/rename": - return rename( - service, - documents, - document, - offset, - request.newName, - ); + return rename(target, offset, request.newName); case "textDocument/documentHighlight": - return documentHighlights(service, document, offset); + return documentHighlights(target, offset); case "textDocument/codeAction": return codeActions( - service, - documents, - document, - request.range!, + target, + request.range, request.context, request.options, ); case "textDocument/foldingRange": - return foldingRanges(service, document); + return foldingRanges(target); case "textDocument/selectionRange": - return selectionRanges( - service, - document, - (params as { positions: Position[] }).positions, - ); + return selectionRanges(target, request.positions); case "textDocument/inlayHint": - return inlayHints(service, document, request.range!); + return inlayHints(target, request.range); default: return METHOD_NOT_HANDLED; } }, - // Only wipe the shared semantic program when nothing is open. - // cleanupSemanticCache() releases every source file and forces a full - // re-analysis of remaining tabs — costly on multi-file mobile sessions. - closeDocument() { - if (documents.size === 0) { - service.cleanupSemanticCache(); - } - }, - - dispose() { - service.dispose(); - }, + openDocument: (uri) => workspace.documentOpened(uri), + closeDocument: (uri) => workspace.documentClosed(uri), + addWorkspaceFolder: (uri) => workspace.addFolder(uri), + removeWorkspaceFolder: (uri) => workspace.removeFolder(uri), + dispose: () => workspace.dispose(), }; }, ); - -async function loadCompilerOptions( - rootUri: string | null | undefined, - requestFile: (uri: string) => Promise, -): Promise { - const defaults: ts.CompilerOptions = { - allowJs: true, - checkJs: true, - allowImportingTsExtensions: true, - noEmit: true, - isolatedModules: true, - module: ts.ModuleKind.ESNext, - moduleResolution: ts.ModuleResolutionKind.Bundler, - moduleDetection: ts.ModuleDetectionKind.Force, - skipLibCheck: true, - target: ts.ScriptTarget.ES2022, - jsx: ts.JsxEmit.ReactJSX, - useDefineForClassFields: true, - }; - ( - defaults as ts.CompilerOptions & { - allowNonTsExtensions: boolean; - } - ).allowNonTsExtensions = true; - if (!rootUri) return defaults; - - try { - const base = rootUri.endsWith("/") ? rootUri : `${rootUri}/`; - const configUri = new URL("tsconfig.json", base).href; - const text = await requestFile(configUri); - const parsed = ts.parseConfigFileTextToJson(configUri, text); - if (parsed.error || !parsed.config?.compilerOptions) return defaults; - const converted = ts.convertCompilerOptionsFromJson( - parsed.config.compilerOptions, - base, - ); - return { ...defaults, ...converted.options, noEmit: true }; - } catch { - return defaults; - } -} - -function completions( - service: ts.LanguageService, - document: TextDocument, - offset: number, -) { - const result = service.getCompletionsAtPosition(document.uri, offset, { - allowIncompleteCompletions: true, - allowRenameOfImportPath: true, - includeCompletionsForImportStatements: true, - includeCompletionsForModuleExports: true, - includeCompletionsWithInsertText: true, - includeAutomaticOptionalChainCompletions: true, - includeCompletionsWithClassMemberSnippets: true, - includeCompletionsWithObjectLiteralMethodSnippets: true, - includeCompletionsWithSnippetText: true, - importModuleSpecifierPreference: "shortest", - }); - if (!result) return { isIncomplete: false, items: [] }; - return { - isIncomplete: !!result.isIncomplete, - items: result.entries - .filter((entry) => entry.name) - .map((entry): CompletionItem => { - const item: CompletionItem = { - label: entry.name, - kind: completionKind(entry.kind), - sortText: entry.sortText, - filterText: entry.filterText, - insertText: entry.insertText ?? entry.name, - commitCharacters: - entry.commitCharacters ?? result.defaultCommitCharacters, - data: { - acodeLspProvider: "typescript", - uri: document.uri, - offset, - name: entry.name, - source: entry.source, - entryData: entry.data, - } satisfies CompletionData, - }; - if (entry.replacementSpan) { - item.textEdit = { - range: rangeFromSpan(document, entry.replacementSpan), - newText: entry.insertText ?? entry.name, - }; - } - return item; - }), - }; -} - -function resolveCompletion( - service: ts.LanguageService, - documents: Map, - item: CompletionItem, -): CompletionItem { - const data = item.data as CompletionData | undefined; - if (!data || !documents.has(data.uri)) return item; - const details = service.getCompletionEntryDetails( - data.uri, - data.offset, - data.name, - formatSettings({ tabSize: 4, insertSpaces: true }), - data.source, - { - allowRenameOfImportPath: true, - importModuleSpecifierPreference: "shortest", - }, - data.entryData, - ); - if (!details) return item; - - item.detail = ts.displayPartsToString(details.displayParts); - const documentation = ts.displayPartsToString(details.documentation); - const tags = details.tags?.map(jsDocTag).join("\n\n") ?? ""; - item.documentation = markdownContent( - [documentation, tags].filter(Boolean).join("\n\n"), - ); - const edits: TextEdit[] = []; - for (const action of details.codeActions ?? []) { - for (const change of action.changes) { - const target = documents.get(change.fileName); - if (!target || change.fileName !== data.uri) continue; - for (const textChange of change.textChanges) { - edits.push({ - range: rangeFromSpan(target, textChange.span), - newText: textChange.newText, - }); - } - } - } - if (edits.length) item.additionalTextEdits = edits; - return item; -} - -function hover( - service: ts.LanguageService, - document: TextDocument, - offset: number, -) { - const info = service.getQuickInfoAtPosition(document.uri, offset); - if (!info) return null; - const signature = ts.displayPartsToString(info.displayParts); - const documentation = ts.displayPartsToString(info.documentation); - const tags = info.tags?.map(jsDocTag).join("\n\n") ?? ""; - return { - range: rangeFromSpan(document, info.textSpan), - contents: [ - { - language: isTypeScriptDocument(document) ? "typescript" : "javascript", - value: signature, - }, - [documentation, tags].filter(Boolean).join("\n\n"), - ], - }; -} - -function signatureHelp( - service: ts.LanguageService, - document: TextDocument, - offset: number, - context: RequestParams["context"], -): SignatureHelp | null { - const items = service.getSignatureHelpItems(document.uri, offset, { - triggerReason: signatureTrigger(context), - }); - if (!items) return null; - return { - activeSignature: items.selectedItemIndex, - activeParameter: items.argumentIndex, - signatures: items.items.map((item) => ({ - label: - ts.displayPartsToString(item.prefixDisplayParts) + - item.parameters - .map((parameter) => ts.displayPartsToString(parameter.displayParts)) - .join(ts.displayPartsToString(item.separatorDisplayParts)) + - ts.displayPartsToString(item.suffixDisplayParts), - documentation: markdownContent( - ts.displayPartsToString(item.documentation), - ), - parameters: item.parameters.map((parameter) => ({ - label: ts.displayPartsToString(parameter.displayParts), - documentation: markdownContent( - ts.displayPartsToString(parameter.documentation), - ), - })), - })), - }; -} - -function markdownContent(value: string): MarkupContent | undefined { - return value ? { kind: "markdown", value } : undefined; -} - -function format( - service: ts.LanguageService, - document: TextDocument, - range: Range | undefined, - options?: FormattingOptions, -): TextEdit[] { - const settings = formatSettings(options); - const edits = range - ? service.getFormattingEditsForRange( - document.uri, - document.offsetAt(range.start), - document.offsetAt(range.end), - settings, - ) - : service.getFormattingEditsForDocument(document.uri, settings); - return edits.map((edit) => ({ - range: rangeFromSpan(document, edit.span), - newText: edit.newText, - })); -} - -function documentSymbols( - service: ts.LanguageService, - document: TextDocument, -): DocumentSymbol[] { - const convert = (item: ts.NavigationTree): DocumentSymbol => ({ - name: item.text, - kind: symbolKind(item.kind), - range: rangeFromSpan(document, item.spans[0]), - selectionRange: rangeFromSpan(document, item.spans[0]), - children: item.childItems?.map(convert), - }); - return service.getNavigationTree(document.uri).childItems?.map(convert) ?? []; -} - -function definitions( - service: ts.LanguageService, - documents: Map, - document: TextDocument, - offset: number, -): LocationLink[] { - const result = service.getDefinitionAndBoundSpan(document.uri, offset); - if (!result?.definitions) return []; - const links: LocationLink[] = []; - for (const definition of result.definitions) { - const target = documents.get(definition.fileName); - if (!target) continue; - const selection = rangeFromSpan(target, definition.textSpan); - links.push({ - targetUri: definition.fileName, - targetRange: definition.contextSpan - ? rangeFromSpan(target, definition.contextSpan) - : selection, - targetSelectionRange: selection, - originSelectionRange: rangeFromSpan(document, result.textSpan), - }); - } - return links; -} - -function references( - service: ts.LanguageService, - documents: Map, - document: TextDocument, - offset: number, -): Location[] { - const result: Location[] = []; - for (const reference of service.getReferencesAtPosition( - document.uri, - offset, - ) ?? []) { - const target = documents.get(reference.fileName); - if (!target) continue; - result.push({ - uri: reference.fileName, - range: rangeFromSpan(target, reference.textSpan), - }); - } - return result; -} - -function rename( - service: ts.LanguageService, - documents: Map, - document: TextDocument, - offset: number, - newName: string, -): WorkspaceEdit | null { - const locations = service.findRenameLocations( - document.uri, - offset, - false, - false, - { providePrefixAndSuffixTextForRename: false }, - ); - if (!locations) return null; - const changes: Record = {}; - for (const location of locations) { - const target = documents.get(location.fileName); - if (!target) continue; - (changes[location.fileName] ??= []).push({ - range: rangeFromSpan(target, location.textSpan), - newText: newName, - }); - } - return { changes }; -} - -function documentHighlights( - service: ts.LanguageService, - document: TextDocument, - offset: number, -): DocumentHighlight[] { - const result: DocumentHighlight[] = []; - for (const item of service.getDocumentHighlights(document.uri, offset, [ - document.uri, - ]) ?? []) { - for (const highlight of item.highlightSpans) { - result.push({ - range: rangeFromSpan(document, highlight.textSpan), - kind: - highlight.kind === "writtenReference" - ? DocumentHighlightKind.Write - : DocumentHighlightKind.Text, - }); - } - } - return result; -} - -function codeActions( - service: ts.LanguageService, - documents: Map, - document: TextDocument, - range: Range, - context: CodeActionContext, - options?: FormattingOptions, -): CodeAction[] { - const fixes = service.getCodeFixesAtPosition( - document.uri, - document.offsetAt(range.start), - document.offsetAt(range.end), - context.diagnostics - .map((diagnostic) => Number(diagnostic.code)) - .filter(Number.isFinite), - formatSettings(options), - {}, - ); - return fixes.map((fix) => { - const changes: Record = {}; - for (const change of fix.changes) { - const target = documents.get(change.fileName); - if (!target) continue; - changes[change.fileName] = change.textChanges.map((textChange) => ({ - range: rangeFromSpan(target, textChange.span), - newText: textChange.newText, - })); - } - return { - title: fix.description, - kind: "quickfix", - edit: Object.keys(changes).length ? { changes } : undefined, - }; - }); -} - -function foldingRanges( - service: ts.LanguageService, - document: TextDocument, -): FoldingRange[] { - const result: FoldingRange[] = []; - for (const item of service.getOutliningSpans(document.uri)) { - const range = rangeFromSpan(document, item.textSpan); - if (range.start.line >= range.end.line) continue; - result.push({ - startLine: range.start.line, - endLine: range.end.line, - kind: - item.kind === ts.OutliningSpanKind.Comment - ? FoldingRangeKind.Comment - : item.kind === ts.OutliningSpanKind.Region - ? FoldingRangeKind.Region - : undefined, - }); - } - return result; -} - -function selectionRanges( - service: ts.LanguageService, - document: TextDocument, - positions: Position[], -): LspSelectionRange[] { - const convert = (selection: ts.SelectionRange): LspSelectionRange => - SelectionRange.create( - rangeFromSpan(document, selection.textSpan), - selection.parent ? convert(selection.parent) : undefined, - ); - return positions.map((position) => - convert( - service.getSmartSelectionRange(document.uri, document.offsetAt(position)), - ), - ); -} - -function inlayHints( - service: ts.LanguageService, - document: TextDocument, - range: Range, -): InlayHint[] { - const start = document.offsetAt(range.start); - const end = document.offsetAt(range.end); - return service - .provideInlayHints( - document.uri, - { start, length: end - start }, - { - includeInlayParameterNameHints: "all", - includeInlayParameterNameHintsWhenArgumentMatchesName: true, - includeInlayFunctionParameterTypeHints: true, - includeInlayVariableTypeHints: true, - includeInlayPropertyDeclarationTypeHints: true, - includeInlayFunctionLikeReturnTypeHints: true, - includeInlayEnumMemberValueHints: true, - }, - ) - .map((hint) => ({ - position: document.positionAt(hint.position), - label: - hint.text || hint.displayParts?.map((part) => part.text).join("") || "", - kind: - hint.kind === ts.InlayHintKind.Parameter - ? InlayHintKind.Parameter - : InlayHintKind.Type, - paddingLeft: hint.whitespaceBefore, - paddingRight: hint.whitespaceAfter, - })); -} - -function toDiagnostic( - document: TextDocument, - diagnostic: ts.Diagnostic, -): Diagnostic { - const tags: DiagnosticTag[] = []; - if (diagnostic.reportsUnnecessary) tags.push(DiagnosticTag.Unnecessary); - if (diagnostic.reportsDeprecated) tags.push(DiagnosticTag.Deprecated); - return { - range: rangeFromSpan(document, diagnostic), - code: diagnostic.code, - severity: diagnosticSeverity(diagnostic.category), - message: ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"), - source: diagnostic.source ?? "typescript", - tags, - }; -} - -function rangeFromSpan( - document: TextDocument, - span: { start?: number; length?: number }, -): Range { - const startOffset = span.start ?? 0; - return Range.create( - document.positionAt(startOffset), - document.positionAt(startOffset + (span.length ?? 0)), - ); -} - -function formatSettings( - options?: FormattingOptions | null, -): ts.FormatCodeSettings { - const tabSize = options?.tabSize ?? 4; - const insertSpaces = options?.insertSpaces ?? true; - return { - tabSize, - indentSize: tabSize, - convertTabsToSpaces: insertSpaces, - trimTrailingWhitespace: options?.trimTrailingWhitespace, - insertSpaceAfterCommaDelimiter: insertSpaces, - insertSpaceAfterSemicolonInForStatements: insertSpaces, - insertSpaceBeforeAndAfterBinaryOperators: insertSpaces, - insertSpaceAfterKeywordsInControlFlowStatements: insertSpaces, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: insertSpaces, - }; -} - -function completionKind(kind: ts.ScriptElementKind): CompletionItemKind { - switch (kind) { - case ts.ScriptElementKind.primitiveType: - case ts.ScriptElementKind.keyword: - return CompletionItemKind.Keyword; - case ts.ScriptElementKind.constElement: - case ts.ScriptElementKind.letElement: - case ts.ScriptElementKind.variableElement: - case ts.ScriptElementKind.localVariableElement: - case ts.ScriptElementKind.alias: - case ts.ScriptElementKind.parameterElement: - return CompletionItemKind.Variable; - case ts.ScriptElementKind.memberVariableElement: - case ts.ScriptElementKind.memberGetAccessorElement: - case ts.ScriptElementKind.memberSetAccessorElement: - return CompletionItemKind.Field; - case ts.ScriptElementKind.functionElement: - case ts.ScriptElementKind.localFunctionElement: - return CompletionItemKind.Function; - case ts.ScriptElementKind.memberFunctionElement: - case ts.ScriptElementKind.constructSignatureElement: - case ts.ScriptElementKind.callSignatureElement: - case ts.ScriptElementKind.indexSignatureElement: - return CompletionItemKind.Method; - case ts.ScriptElementKind.enumElement: - return CompletionItemKind.Enum; - case ts.ScriptElementKind.enumMemberElement: - return CompletionItemKind.EnumMember; - case ts.ScriptElementKind.moduleElement: - case ts.ScriptElementKind.externalModuleName: - return CompletionItemKind.Module; - case ts.ScriptElementKind.classElement: - case ts.ScriptElementKind.typeElement: - return CompletionItemKind.Class; - case ts.ScriptElementKind.interfaceElement: - return CompletionItemKind.Interface; - case ts.ScriptElementKind.scriptElement: - return CompletionItemKind.File; - case ts.ScriptElementKind.directory: - return CompletionItemKind.Folder; - default: - return CompletionItemKind.Property; - } -} - -function symbolKind(kind: ts.ScriptElementKind): SymbolKind { - switch (kind) { - case ts.ScriptElementKind.memberVariableElement: - return SymbolKind.Field; - case ts.ScriptElementKind.functionElement: - case ts.ScriptElementKind.localFunctionElement: - return SymbolKind.Function; - case ts.ScriptElementKind.memberFunctionElement: - return SymbolKind.Method; - case ts.ScriptElementKind.enumElement: - return SymbolKind.Enum; - case ts.ScriptElementKind.enumMemberElement: - return SymbolKind.EnumMember; - case ts.ScriptElementKind.moduleElement: - case ts.ScriptElementKind.externalModuleName: - return SymbolKind.Module; - case ts.ScriptElementKind.classElement: - case ts.ScriptElementKind.typeElement: - return SymbolKind.Class; - case ts.ScriptElementKind.interfaceElement: - return SymbolKind.Interface; - case ts.ScriptElementKind.scriptElement: - return SymbolKind.File; - default: - return SymbolKind.Variable; - } -} - -function diagnosticSeverity( - category: ts.DiagnosticCategory, -): DiagnosticSeverity { - switch (category) { - case ts.DiagnosticCategory.Error: - return DiagnosticSeverity.Error; - case ts.DiagnosticCategory.Warning: - return DiagnosticSeverity.Warning; - case ts.DiagnosticCategory.Suggestion: - return DiagnosticSeverity.Hint; - default: - return DiagnosticSeverity.Information; - } -} - -function signatureTrigger( - context: RequestParams["context"], -): ts.SignatureHelpTriggerReason { - if (context?.triggerKind === 2 && context.triggerCharacter) { - return context.isRetrigger - ? { - kind: "retrigger", - triggerCharacter: - context.triggerCharacter as ts.SignatureHelpTriggerCharacter, - } - : { - kind: "characterTyped", - triggerCharacter: - context.triggerCharacter as ts.SignatureHelpTriggerCharacter, - }; - } - return context?.isRetrigger ? { kind: "retrigger" } : { kind: "invoked" }; -} - -function jsDocTag(tag: ts.JSDocTagInfo): string { - const text = Array.isArray(tag.text) - ? tag.text.map((part) => part.text).join("") - : (tag.text ?? ""); - return `*@${tag.name}*${text ? ` — ${text}` : ""}`; -} - -function isTypeScriptDocument(document: TextDocument): boolean { - return ( - document.languageId.startsWith("typescript") || - document.languageId === "tsx" - ); -} - -function uriPath(uri: string): string { - try { - return new URL(uri).pathname; - } catch { - return uri; - } -} diff --git a/src/cm/lsp/workers/typescript/assist.ts b/src/cm/lsp/workers/typescript/assist.ts new file mode 100644 index 0000000000..2938ff2ebb --- /dev/null +++ b/src/cm/lsp/workers/typescript/assist.ts @@ -0,0 +1,168 @@ +import ts from "typescript"; +import type { + CompletionItem, + SignatureHelp, + TextEdit, +} from "vscode-languageserver-types"; +import { + completionKind, + formatSettings, + jsDocTag, + markdownContent, + rangeFromSpan, + type SignatureContext, + signatureTrigger, +} from "./convert"; +import { isTypeScriptLanguage } from "./scripts"; +import type { ServiceTarget } from "./workspace"; + +export interface CompletionData { + acodeLspProvider: "typescript"; + uri: string; + offset: number; + name: string; + source?: string; + entryData?: ts.CompletionEntryData; +} +export function completions(target: ServiceTarget, offset: number) { + const { service, document, fileName } = target; + const result = service.getCompletionsAtPosition(fileName, offset, { + allowIncompleteCompletions: true, + allowRenameOfImportPath: true, + includeCompletionsForImportStatements: true, + includeCompletionsForModuleExports: true, + includeCompletionsWithInsertText: true, + includeAutomaticOptionalChainCompletions: true, + includeCompletionsWithClassMemberSnippets: true, + includeCompletionsWithObjectLiteralMethodSnippets: true, + includeCompletionsWithSnippetText: true, + importModuleSpecifierPreference: "shortest", + }); + if (!result) return { isIncomplete: false, items: [] }; + return { + isIncomplete: !!result.isIncomplete, + items: result.entries + .filter((entry) => entry.name) + .map((entry): CompletionItem => { + const item: CompletionItem = { + label: entry.name, + kind: completionKind(entry.kind), + sortText: entry.sortText, + filterText: entry.filterText, + insertText: entry.insertText ?? entry.name, + commitCharacters: + entry.commitCharacters ?? result.defaultCommitCharacters, + data: { + acodeLspProvider: "typescript", + uri: document.uri, + offset, + name: entry.name, + source: entry.source, + entryData: entry.data, + } satisfies CompletionData, + }; + if (entry.replacementSpan) { + item.textEdit = { + range: rangeFromSpan(document, entry.replacementSpan), + newText: entry.insertText ?? entry.name, + }; + } + return item; + }), + }; +} + +export function resolveCompletion( + target: ServiceTarget, + item: CompletionItem, + data: CompletionData, +): CompletionItem { + const { service, document, fileName } = target; + const details = service.getCompletionEntryDetails( + fileName, + data.offset, + data.name, + formatSettings({ tabSize: 4, insertSpaces: true }), + data.source, + { + allowRenameOfImportPath: true, + importModuleSpecifierPreference: "shortest", + }, + data.entryData, + ); + if (!details) return item; + + item.detail = ts.displayPartsToString(details.displayParts); + const documentation = ts.displayPartsToString(details.documentation); + const tags = details.tags?.map(jsDocTag).join("\n\n") ?? ""; + item.documentation = markdownContent( + [documentation, tags].filter(Boolean).join("\n\n"), + ); + const edits: TextEdit[] = []; + for (const action of details.codeActions ?? []) { + for (const change of action.changes) { + if (change.fileName !== fileName) continue; + for (const textChange of change.textChanges) { + edits.push({ + range: rangeFromSpan(document, textChange.span), + newText: textChange.newText, + }); + } + } + } + if (edits.length) item.additionalTextEdits = edits; + return item; +} + +export function hover(target: ServiceTarget, offset: number) { + const { service, document, fileName } = target; + const info = service.getQuickInfoAtPosition(fileName, offset); + if (!info) return null; + const signature = ts.displayPartsToString(info.displayParts); + const documentation = ts.displayPartsToString(info.documentation); + const tags = info.tags?.map(jsDocTag).join("\n\n") ?? ""; + return { + range: rangeFromSpan(document, info.textSpan), + contents: [ + { + language: isTypeScriptLanguage(document.languageId) + ? "typescript" + : "javascript", + value: signature, + }, + [documentation, tags].filter(Boolean).join("\n\n"), + ], + }; +} + +export function signatureHelp( + target: ServiceTarget, + offset: number, + context: SignatureContext | undefined, +): SignatureHelp | null { + const items = target.service.getSignatureHelpItems(target.fileName, offset, { + triggerReason: signatureTrigger(context), + }); + if (!items) return null; + return { + activeSignature: items.selectedItemIndex, + activeParameter: items.argumentIndex, + signatures: items.items.map((item) => ({ + label: + ts.displayPartsToString(item.prefixDisplayParts) + + item.parameters + .map((parameter) => ts.displayPartsToString(parameter.displayParts)) + .join(ts.displayPartsToString(item.separatorDisplayParts)) + + ts.displayPartsToString(item.suffixDisplayParts), + documentation: markdownContent( + ts.displayPartsToString(item.documentation), + ), + parameters: item.parameters.map((parameter) => ({ + label: ts.displayPartsToString(parameter.displayParts), + documentation: markdownContent( + ts.displayPartsToString(parameter.documentation), + ), + })), + })), + }; +} diff --git a/src/cm/lsp/workers/typescript/convert.ts b/src/cm/lsp/workers/typescript/convert.ts new file mode 100644 index 0000000000..5f61412012 --- /dev/null +++ b/src/cm/lsp/workers/typescript/convert.ts @@ -0,0 +1,176 @@ +import ts from "typescript"; +import type { TextDocument } from "vscode-languageserver-textdocument"; +import { + CompletionItemKind, + type Diagnostic, + DiagnosticSeverity, + DiagnosticTag, + type FormattingOptions, + type MarkupContent, + Range, + SymbolKind, +} from "vscode-languageserver-types"; + +export interface SignatureContext { + triggerKind?: number; + triggerCharacter?: string; + isRetrigger?: boolean; +} + +export function toDiagnostic( + document: TextDocument, + diagnostic: ts.Diagnostic, +): Diagnostic { + const tags: DiagnosticTag[] = []; + if (diagnostic.reportsUnnecessary) tags.push(DiagnosticTag.Unnecessary); + if (diagnostic.reportsDeprecated) tags.push(DiagnosticTag.Deprecated); + return { + range: rangeFromSpan(document, diagnostic), + code: diagnostic.code, + severity: diagnosticSeverity(diagnostic.category), + message: ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"), + source: diagnostic.source ?? "typescript", + tags, + }; +} + +export function rangeFromSpan( + document: TextDocument, + span: { start?: number; length?: number }, +): Range { + const startOffset = span.start ?? 0; + return Range.create( + document.positionAt(startOffset), + document.positionAt(startOffset + (span.length ?? 0)), + ); +} + +export function formatSettings( + options?: FormattingOptions | null, +): ts.FormatCodeSettings { + const tabSize = options?.tabSize ?? 4; + const insertSpaces = options?.insertSpaces ?? true; + return { + tabSize, + indentSize: tabSize, + convertTabsToSpaces: insertSpaces, + trimTrailingWhitespace: options?.trimTrailingWhitespace, + insertSpaceAfterCommaDelimiter: insertSpaces, + insertSpaceAfterSemicolonInForStatements: insertSpaces, + insertSpaceBeforeAndAfterBinaryOperators: insertSpaces, + insertSpaceAfterKeywordsInControlFlowStatements: insertSpaces, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: insertSpaces, + }; +} + +export function markdownContent(value: string): MarkupContent | undefined { + return value ? { kind: "markdown", value } : undefined; +} + +export function jsDocTag(tag: ts.JSDocTagInfo): string { + const text = Array.isArray(tag.text) + ? tag.text.map((part) => part.text).join("") + : (tag.text ?? ""); + return `*@${tag.name}*${text ? ` — ${text}` : ""}`; +} + +export function signatureTrigger( + context: SignatureContext | undefined, +): ts.SignatureHelpTriggerReason { + if (context?.triggerKind === 2 && context.triggerCharacter) { + const triggerCharacter = + context.triggerCharacter as ts.SignatureHelpTriggerCharacter; + return context.isRetrigger + ? { kind: "retrigger", triggerCharacter } + : { kind: "characterTyped", triggerCharacter }; + } + return context?.isRetrigger ? { kind: "retrigger" } : { kind: "invoked" }; +} + +export function completionKind(kind: ts.ScriptElementKind): CompletionItemKind { + switch (kind) { + case ts.ScriptElementKind.primitiveType: + case ts.ScriptElementKind.keyword: + return CompletionItemKind.Keyword; + case ts.ScriptElementKind.constElement: + case ts.ScriptElementKind.letElement: + case ts.ScriptElementKind.variableElement: + case ts.ScriptElementKind.localVariableElement: + case ts.ScriptElementKind.alias: + case ts.ScriptElementKind.parameterElement: + return CompletionItemKind.Variable; + case ts.ScriptElementKind.memberVariableElement: + case ts.ScriptElementKind.memberGetAccessorElement: + case ts.ScriptElementKind.memberSetAccessorElement: + return CompletionItemKind.Field; + case ts.ScriptElementKind.functionElement: + case ts.ScriptElementKind.localFunctionElement: + return CompletionItemKind.Function; + case ts.ScriptElementKind.memberFunctionElement: + case ts.ScriptElementKind.constructSignatureElement: + case ts.ScriptElementKind.callSignatureElement: + case ts.ScriptElementKind.indexSignatureElement: + return CompletionItemKind.Method; + case ts.ScriptElementKind.enumElement: + return CompletionItemKind.Enum; + case ts.ScriptElementKind.enumMemberElement: + return CompletionItemKind.EnumMember; + case ts.ScriptElementKind.moduleElement: + case ts.ScriptElementKind.externalModuleName: + return CompletionItemKind.Module; + case ts.ScriptElementKind.classElement: + case ts.ScriptElementKind.typeElement: + return CompletionItemKind.Class; + case ts.ScriptElementKind.interfaceElement: + return CompletionItemKind.Interface; + case ts.ScriptElementKind.scriptElement: + return CompletionItemKind.File; + case ts.ScriptElementKind.directory: + return CompletionItemKind.Folder; + default: + return CompletionItemKind.Property; + } +} + +export function symbolKind(kind: ts.ScriptElementKind): SymbolKind { + switch (kind) { + case ts.ScriptElementKind.memberVariableElement: + return SymbolKind.Field; + case ts.ScriptElementKind.functionElement: + case ts.ScriptElementKind.localFunctionElement: + return SymbolKind.Function; + case ts.ScriptElementKind.memberFunctionElement: + return SymbolKind.Method; + case ts.ScriptElementKind.enumElement: + return SymbolKind.Enum; + case ts.ScriptElementKind.enumMemberElement: + return SymbolKind.EnumMember; + case ts.ScriptElementKind.moduleElement: + case ts.ScriptElementKind.externalModuleName: + return SymbolKind.Module; + case ts.ScriptElementKind.classElement: + case ts.ScriptElementKind.typeElement: + return SymbolKind.Class; + case ts.ScriptElementKind.interfaceElement: + return SymbolKind.Interface; + case ts.ScriptElementKind.scriptElement: + return SymbolKind.File; + default: + return SymbolKind.Variable; + } +} + +function diagnosticSeverity( + category: ts.DiagnosticCategory, +): DiagnosticSeverity { + switch (category) { + case ts.DiagnosticCategory.Error: + return DiagnosticSeverity.Error; + case ts.DiagnosticCategory.Warning: + return DiagnosticSeverity.Warning; + case ts.DiagnosticCategory.Suggestion: + return DiagnosticSeverity.Hint; + default: + return DiagnosticSeverity.Information; + } +} diff --git a/src/cm/lsp/workers/typescript/crawl.ts b/src/cm/lsp/workers/typescript/crawl.ts new file mode 100644 index 0000000000..4f024e73b2 --- /dev/null +++ b/src/cm/lsp/workers/typescript/crawl.ts @@ -0,0 +1,79 @@ +import type { DirectoryEntry } from "../protocol"; +import { joinPath } from "./paths"; + +export interface CrawlOptions { + skipDirectory(name: string): boolean; + includeFile(name: string): boolean; + maxDirectories: number; + maxFiles: number; + onProgress?(directories: number, files: number): void; +} + +interface Listing { + list(path: string): Promise | undefined>; +} + +interface ListedEntries { + listedEntries(path: string): { files: string[]; directories: string[] }; +} + +/** Breadth-first scan for source files, bounded by the directory budget. */ +export default async function crawl( + fs: Listing, + root: string, + options: CrawlOptions, +): Promise { + const files: string[] = []; + let level = [root]; + let visited = 0; + while (level.length && visited < options.maxDirectories) { + const batch = level.slice(0, options.maxDirectories - visited); + visited += batch.length; + const listings = await Promise.all(batch.map((dir) => fs.list(dir))); + level = []; + batch.forEach((dir, index) => { + for (const entry of listings[index]?.values() ?? []) { + const child = joinPath(dir, entry.name); + if (entry.isDirectory) { + if (!options.skipDirectory(entry.name)) level.push(child); + } else if ( + files.length < options.maxFiles && + options.includeFile(entry.name) + ) { + files.push(child); + } + } + }); + options.onProgress?.(visited, files.length); + } + return files; +} + +/** + * Source files among folders already listed, with the crawl's skip rules and + * limits. Re-run on every refresh so files found later stay in the project. + */ +export function listedSourceFiles( + fs: ListedEntries, + root: string, + options: CrawlOptions, +): string[] { + const files: string[] = []; + const pending = [root]; + for ( + let visited = 0; + pending.length && visited < options.maxDirectories; + visited++ + ) { + const directory = pending.shift()!; + const entries = fs.listedEntries(directory); + for (const name of entries.directories) { + if (!options.skipDirectory(name)) pending.push(joinPath(directory, name)); + } + for (const name of entries.files) { + if (files.length >= options.maxFiles) return files; + if (options.includeFile(name)) files.push(joinPath(directory, name)); + } + } + return files; +} diff --git a/src/cm/lsp/workers/typescript/documentHost.ts b/src/cm/lsp/workers/typescript/documentHost.ts new file mode 100644 index 0000000000..8699e98164 --- /dev/null +++ b/src/cm/lsp/workers/typescript/documentHost.ts @@ -0,0 +1,138 @@ +import ts from "typescript"; +import type { TextDocument } from "vscode-languageserver-textdocument"; +import { compilerDefaults, scriptKind } from "./scripts"; + +const RELATIVE_CANDIDATES = [ + "", + ".ts", + ".tsx", + ".js", + ".jsx", + "/index.ts", + "/index.tsx", + "/index.js", + "/index.jsx", +]; + +/** + * Single-file mode: open editor documents, keyed by URI, plus the bundled + * lib files. Serves every document that no project folder can claim. + */ +export default class DocumentHost implements ts.LanguageServiceHost { + #options = compilerDefaults(); + #documents: Map; + #libraries: Record; + #isProjectDocument: (uri: string) => boolean; + #projectVersion: () => string; + + constructor( + documents: Map, + libraries: Record, + isProjectDocument: (uri: string) => boolean, + projectVersion: () => string, + ) { + this.#documents = documents; + this.#libraries = libraries; + this.#isProjectDocument = isProjectDocument; + this.#projectVersion = projectVersion; + } + + getCompilationSettings(): ts.CompilerOptions { + return this.#options; + } + + getCurrentDirectory(): string { + return "/"; + } + + getDefaultLibFileName(options: ts.CompilerOptions): string { + return ts.getDefaultLibFileName(options); + } + + getScriptFileNames(): string[] { + return [...this.#documents.keys()].filter( + (uri) => !this.#isProjectDocument(uri), + ); + } + + getScriptVersion(fileName: string): string { + const document = this.#documents.get(fileName); + return document ? String(document.version) : "1"; + } + + getProjectVersion(): string { + return this.#projectVersion(); + } + + getScriptSnapshot(fileName: string): ts.IScriptSnapshot | undefined { + const text = this.readFile(fileName); + return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text); + } + + getScriptKind(fileName: string): ts.ScriptKind { + return scriptKind(fileName, this.#documents.get(fileName)?.languageId); + } + + fileExists(fileName: string): boolean { + return this.#documents.has(fileName) || fileName in this.#libraries; + } + + readFile(fileName: string): string | undefined { + return ( + this.#documents.get(fileName)?.getText() ?? this.#libraries[fileName] + ); + } + + readDirectory(): string[] { + return this.getScriptFileNames(); + } + + directoryExists(): boolean { + return true; + } + + getDirectories(): string[] { + return []; + } + + useCaseSensitiveFileNames(): boolean { + return true; + } + + getNewLine(): string { + return "\n"; + } + + resolveModuleNames( + moduleNames: string[], + containingFile: string, + ): (ts.ResolvedModule | undefined)[] { + return moduleNames.map( + (moduleName) => + this.#resolveOpenDocument(moduleName, containingFile) ?? + ts.resolveModuleName(moduleName, containingFile, this.#options, this) + .resolvedModule, + ); + } + + #resolveOpenDocument( + moduleName: string, + containingFile: string, + ): ts.ResolvedModule | undefined { + if (!moduleName.startsWith(".") && !/^[a-z]+:/i.test(moduleName)) { + return undefined; + } + let base: string; + try { + base = new URL(moduleName, containingFile).href; + } catch { + return undefined; + } + const resolvedFileName = RELATIVE_CANDIDATES.map( + (suffix) => `${base}${suffix}`, + ).find((candidate) => this.#documents.has(candidate)); + return resolvedFileName + ? { resolvedFileName, isExternalLibraryImport: false } + : undefined; + } +} diff --git a/src/cm/lsp/workers/typescript/features.ts b/src/cm/lsp/workers/typescript/features.ts new file mode 100644 index 0000000000..aa5515e5a5 --- /dev/null +++ b/src/cm/lsp/workers/typescript/features.ts @@ -0,0 +1,134 @@ +import ts from "typescript"; +import { + type Diagnostic, + type DocumentSymbol, + type FoldingRange, + FoldingRangeKind, + type FormattingOptions, + type InlayHint, + InlayHintKind, + type SelectionRange as LspSelectionRange, + type Position, + type Range, + SelectionRange, + type TextEdit, +} from "vscode-languageserver-types"; +import { + formatSettings, + rangeFromSpan, + symbolKind, + toDiagnostic, +} from "./convert"; +import { isTypeScriptLanguage } from "./scripts"; +import type { ServiceTarget } from "./workspace"; + +export function diagnostics(target: ServiceTarget): Diagnostic[] { + const { service, document, fileName } = target; + const found: ts.Diagnostic[] = [ + ...service.getSyntacticDiagnostics(fileName), + ...service.getSuggestionDiagnostics(fileName), + ]; + if (isTypeScriptLanguage(document.languageId) || target.checkJs) { + found.push(...service.getSemanticDiagnostics(fileName)); + } + return found.map((diagnostic) => toDiagnostic(document, diagnostic)); +} +export function format( + target: ServiceTarget, + range: Range | undefined, + options?: FormattingOptions, +): TextEdit[] { + const { service, document, fileName } = target; + const settings = formatSettings(options); + const edits = range + ? service.getFormattingEditsForRange( + fileName, + document.offsetAt(range.start), + document.offsetAt(range.end), + settings, + ) + : service.getFormattingEditsForDocument(fileName, settings); + return edits.map((edit) => ({ + range: rangeFromSpan(document, edit.span), + newText: edit.newText, + })); +} + +export function documentSymbols(target: ServiceTarget): DocumentSymbol[] { + const { service, document, fileName } = target; + const convert = (item: ts.NavigationTree): DocumentSymbol => ({ + name: item.text, + kind: symbolKind(item.kind), + range: rangeFromSpan(document, item.spans[0]), + selectionRange: rangeFromSpan(document, item.spans[0]), + children: item.childItems?.map(convert), + }); + return service.getNavigationTree(fileName).childItems?.map(convert) ?? []; +} + +export function foldingRanges(target: ServiceTarget): FoldingRange[] { + const result: FoldingRange[] = []; + for (const item of target.service.getOutliningSpans(target.fileName)) { + const range = rangeFromSpan(target.document, item.textSpan); + if (range.start.line >= range.end.line) continue; + result.push({ + startLine: range.start.line, + endLine: range.end.line, + kind: + item.kind === ts.OutliningSpanKind.Comment + ? FoldingRangeKind.Comment + : item.kind === ts.OutliningSpanKind.Region + ? FoldingRangeKind.Region + : undefined, + }); + } + return result; +} + +export function selectionRanges( + target: ServiceTarget, + positions: Position[], +): LspSelectionRange[] { + const { service, document, fileName } = target; + const convert = (selection: ts.SelectionRange): LspSelectionRange => + SelectionRange.create( + rangeFromSpan(document, selection.textSpan), + selection.parent ? convert(selection.parent) : undefined, + ); + return positions.map((position) => + convert( + service.getSmartSelectionRange(fileName, document.offsetAt(position)), + ), + ); +} + +export function inlayHints(target: ServiceTarget, range: Range): InlayHint[] { + const { service, document, fileName } = target; + const start = document.offsetAt(range.start); + const end = document.offsetAt(range.end); + return service + .provideInlayHints( + fileName, + { start, length: end - start }, + { + includeInlayParameterNameHints: "all", + includeInlayParameterNameHintsWhenArgumentMatchesName: true, + includeInlayFunctionParameterTypeHints: true, + includeInlayVariableTypeHints: true, + includeInlayPropertyDeclarationTypeHints: true, + includeInlayFunctionLikeReturnTypeHints: true, + includeInlayEnumMemberValueHints: true, + }, + ) + .map((hint) => ({ + position: document.positionAt(hint.position), + label: + hint.text || hint.displayParts?.map((part) => part.text).join("") || "", + kind: + hint.kind === ts.InlayHintKind.Parameter + ? InlayHintKind.Parameter + : InlayHintKind.Type, + paddingLeft: hint.whitespaceBefore, + paddingRight: hint.whitespaceAfter, + })); +} diff --git a/src/cm/lsp/workers/typescript/fileRoots.ts b/src/cm/lsp/workers/typescript/fileRoots.ts new file mode 100644 index 0000000000..65295cc976 --- /dev/null +++ b/src/cm/lsp/workers/typescript/fileRoots.ts @@ -0,0 +1,49 @@ +const FILE_URL = "file://"; + +/** + * Workspace roots by virtual path. `file:` roots use their real path, so the + * folders above them can be reached by URL; other providers' roots are opaque. + */ +export default class FileRoots { + #roots = new Map(); + + add(path: string, url: string): void { + this.#roots.set(path, url); + } + + delete(path: string): void { + this.#roots.delete(path); + } + + paths(): string[] { + return [...this.#roots.keys()]; + } + + /** Real path of a `file:` URL inside a file root; listings decode URLs. */ + pathOf(url: string): string | undefined { + if (!url.startsWith(`${FILE_URL}/`)) return undefined; + const path = url.slice(FILE_URL.length); + return this.contains(path) ? path : undefined; + } + + urlOf(path: string): string { + return `${FILE_URL}${path}`; + } + + contains(path: string): boolean { + return this.#fileRoots().some( + (root) => path === root || path.startsWith(`${root}/`), + ); + } + + isAbove(path: string): boolean { + const prefix = path === "/" ? "/" : `${path}/`; + return this.#fileRoots().some((root) => root.startsWith(prefix)); + } + + #fileRoots(): string[] { + return [...this.#roots] + .filter(([, url]) => url.startsWith(FILE_URL)) + .map(([path]) => path); + } +} diff --git a/src/cm/lsp/workers/typescript/fileSystem.ts b/src/cm/lsp/workers/typescript/fileSystem.ts new file mode 100644 index 0000000000..143567daf0 --- /dev/null +++ b/src/cm/lsp/workers/typescript/fileSystem.ts @@ -0,0 +1,302 @@ +import type { DirectoryEntry } from "../protocol"; +import FileRoots from "./fileRoots"; +import { baseName, joinPath, parentOf, trimSlash } from "./paths"; +import TaskQueue from "./taskQueue"; + +export interface FileSystemHost { + readDirectory(url: string): Promise; + readFile(url: string): Promise; +} + +interface DirectoryNode { + url: string; + children?: Map; + loading?: Promise | undefined>; + failed?: boolean; +} + +interface FileNode { + version: number; + text?: string; + loading?: Promise; + failed?: boolean; +} + +const CONCURRENCY = 4; +const MAX_RELOAD_DEPTH = 8; +const CHANGE_DELAY = 150; + +/** + * Synchronous view of project folders for the TypeScript compiler. Unknown + * entries read as missing and are fetched from the host in the background; + * `onChange` fires once they arrive so the program can be rebuilt. + */ +export default class ProjectFileSystem { + #host: FileSystemHost; + #onChange: () => void; + #roots = new FileRoots(); + #queue = new TaskQueue(CONCURRENCY); + #directories = new Map(); + #files = new Map(); + #paths = new Map(); + #version = 0; + #timer: ReturnType | undefined; + + constructor(host: FileSystemHost, onChange: () => void) { + this.#host = host; + this.#onChange = onChange; + } + + get version(): number { + return this.#version; + } + + get busy(): boolean { + return this.#queue.busy; + } + + addRoot(path: string, url: string): void { + this.#roots.add(path, url); + this.#directories.set(path, this.#directories.get(path) ?? { url }); + this.#paths.set(trimSlash(url), path); + } + + removeRoot(path: string): void { + this.#roots.delete(path); + const roots = this.#roots.paths(); + // Nested file roots share real paths; keep what another root still uses. + const inside = (key: string) => + (key === path || key.startsWith(`${path}/`)) && + !roots.some((root) => key === root || key.startsWith(`${root}/`)); + for (const key of this.#directories.keys()) { + if (inside(key)) this.#directories.delete(key); + } + for (const key of this.#files.keys()) { + if (inside(key)) this.#files.delete(key); + } + for (const [url, key] of this.#paths) { + if (inside(key)) this.#paths.delete(url); + } + this.#changed(); + } + + pathOf(url: string): string | undefined { + const key = trimSlash(url); + return this.#paths.get(key) ?? this.#roots.pathOf(key); + } + + urlOf(path: string): string | undefined { + const parent = this.#directories.get(parentOf(path)); + return ( + this.#directories.get(path)?.url ?? + parent?.children?.get(baseName(path))?.url ?? + (this.#roots.contains(path) ? this.#roots.urlOf(path) : undefined) + ); + } + + directoryExists(path: string): boolean { + const target = trimSlash(path); + return ( + target === "/" || + this.#directories.has(target) || + !!this.#entry(target)?.isDirectory + ); + } + + fileExists(path: string): boolean { + const entry = this.#entry(path); + return !!entry && !entry.isDirectory; + } + + readFile(path: string): string | undefined { + const node = this.#files.get(path); + if (node?.text !== undefined || node?.loading || node?.failed) { + return node.text; + } + const entry = this.#entry(path); + if (entry && !entry.isDirectory) void this.#loadFile(path, entry.url); + return undefined; + } + + fileVersion(path: string): number { + return this.#files.get(path)?.version ?? 0; + } + + getEntries(path: string): { files: string[]; directories: string[] } { + return splitEntries(this.#children(trimSlash(path))); + } + + /** Entries already listed, without fetching more; keeps scans in budget. */ + listedEntries(path: string): { files: string[]; directories: string[] } { + return splitEntries(this.#directories.get(trimSlash(path))?.children); + } + + /** + * Drop cached content so the next read comes from the host again. The + * version keeps rising so text derived from the old content is never + * mistaken for the new one. + */ + invalidate(path: string): void { + const node = this.#files.get(path); + if (!node) return; + node.text = undefined; + node.failed = undefined; + node.version++; + this.#changed(); + } + + /** + * Map a URL that listings have not reported yet, such as a newly created + * file: re-list the nearest known folder and walk down from there. Paths + * always come from provider listings, so opaque URIs map correctly. + */ + async locate(url: string, root?: string): Promise { + const key = trimSlash(url); + const known = this.pathOf(key); + if (known) { + await this.list(parentOf(known)); + if (!this.#listedEntry(known)) await this.#reload(parentOf(known)); + return known; + } + let directory = this.#ancestorOf(key) ?? root; + while (directory) { + await this.#reload(directory); + const path = this.pathOf(key); + if (path) return path; + const deeper = this.#ancestorOf(key); + if (!deeper || deeper === directory) return undefined; + directory = deeper; + } + return undefined; + } + + async list(path: string): Promise | undefined> { + const node = this.#directory(path); + if (!node || node.failed) return undefined; + return node.children ?? node.loading ?? this.#loadDirectory(path, node); + } + + async read(path: string): Promise { + const entry = (await this.list(parentOf(path)))?.get(baseName(path)); + if (!entry || entry.isDirectory) return undefined; + const node = this.#files.get(path); + if (node?.text !== undefined) return node.text; + return node?.loading ?? this.#loadFile(path, entry.url); + } + + #entry(path: string): DirectoryEntry | undefined { + return this.#children(parentOf(path))?.get(baseName(path)); + } + + #listedEntry(path: string): DirectoryEntry | undefined { + return this.#directories.get(parentOf(path))?.children?.get(baseName(path)); + } + + #children(path: string): Map | undefined { + const node = this.#directory(path); + if (!node || node.failed) return undefined; + if (!node.children && !node.loading) void this.#loadDirectory(path, node); + return node.children; + } + + #directory(path: string): DirectoryNode | undefined { + const known = this.#directories.get(path); + if (known) return known; + // Parents of a file root exist even when their own parent is unreadable, + // so shared configs and hoisted node_modules above the root resolve. + const url = this.#roots.isAbove(path) + ? this.#roots.urlOf(path) + : this.#listedDirectoryUrl(path); + if (!url) return undefined; + const node: DirectoryNode = { url }; + this.#directories.set(path, node); + return node; + } + + #listedDirectoryUrl(path: string): string | undefined { + if (path === "/") return undefined; + const entry = this.#entry(path); + return entry?.isDirectory ? entry.url : undefined; + } + + async #reload(path: string, depth = 0): Promise { + let node = this.#directory(path); + if (!node && path !== "/" && depth < MAX_RELOAD_DEPTH) { + if (!(await this.#reload(parentOf(path), depth + 1))) return false; + node = this.#directory(path); + } + if (!node) return false; + if (node.loading) await node.loading; + node.failed = undefined; + await this.#loadDirectory(path, node); + return !node.failed; + } + + #ancestorOf(url: string): string | undefined { + let current = url; + for (let index = current.lastIndexOf("/"); index > 0; ) { + current = current.slice(0, index); + const path = this.pathOf(current); + if (path) return path; + index = current.lastIndexOf("/"); + } + return undefined; + } + + #loadDirectory( + path: string, + node: DirectoryNode, + ): Promise | undefined> { + node.loading = this.#queue.run(async () => { + try { + const children = new Map(); + for (const entry of await this.#host.readDirectory(node.url)) { + children.set(entry.name, entry); + this.#paths.set(trimSlash(entry.url), joinPath(path, entry.name)); + } + node.children = children; + } catch { + node.failed = true; + } + node.loading = undefined; + this.#changed(); + return node.children; + }); + return node.loading; + } + + #loadFile(path: string, url: string): Promise { + const node: FileNode = this.#files.get(path) ?? { version: 0 }; + this.#files.set(path, node); + node.loading = this.#queue.run(async () => { + try { + node.text = await this.#host.readFile(url); + node.version++; + } catch { + node.failed = true; + } + node.loading = undefined; + this.#changed(); + return node.text; + }); + return node.loading; + } + + #changed(): void { + this.#version++; + if (this.#timer) clearTimeout(this.#timer); + this.#timer = setTimeout(() => { + this.#timer = undefined; + this.#onChange(); + }, CHANGE_DELAY); + } +} + +function splitEntries(children: Map | undefined) { + const files: string[] = []; + const directories: string[] = []; + for (const entry of children?.values() ?? []) { + (entry.isDirectory ? directories : files).push(entry.name); + } + return { files, directories }; +} diff --git a/src/cm/lsp/workers/typescript/navigation.ts b/src/cm/lsp/workers/typescript/navigation.ts new file mode 100644 index 0000000000..75db0fd5a1 --- /dev/null +++ b/src/cm/lsp/workers/typescript/navigation.ts @@ -0,0 +1,189 @@ +import type ts from "typescript"; +import { + type CodeAction, + type CodeActionContext, + type DocumentHighlight, + DocumentHighlightKind, + type FormattingOptions, + type Location, + type LocationLink, + type Range, + type TextEdit, + type WorkspaceEdit, +} from "vscode-languageserver-types"; +import { formatSettings, rangeFromSpan } from "./convert"; +import type { ServiceTarget } from "./workspace"; + +export function definitions( + target: ServiceTarget, + offset: number, +): LocationLink[] { + const { service, document, fileName } = target; + const result = service.getDefinitionAndBoundSpan(fileName, offset); + if (!result?.definitions) return []; + const links: LocationLink[] = []; + for (const definition of result.definitions) { + const location = locate(target, definition.fileName, definition.textSpan); + if (!location) continue; + links.push({ + targetUri: location.uri, + targetRange: definition.contextSpan + ? (locate(target, definition.fileName, definition.contextSpan)?.range ?? + location.range) + : location.range, + targetSelectionRange: location.range, + originSelectionRange: rangeFromSpan(document, result.textSpan), + }); + } + return links; +} + +export function references(target: ServiceTarget, offset: number): Location[] { + const { service, fileName } = target; + return locations(target, service.getReferencesAtPosition(fileName, offset)); +} + +export function implementations( + target: ServiceTarget, + offset: number, +): Location[] { + const { service, fileName } = target; + return locations( + target, + service.getImplementationAtPosition(fileName, offset), + ); +} + +export function typeDefinitions( + target: ServiceTarget, + offset: number, +): Location[] { + const { service, fileName } = target; + return locations( + target, + service.getTypeDefinitionAtPosition(fileName, offset), + ); +} + +export function prepareRename( + target: ServiceTarget, + offset: number, +): Range | null { + const info = target.service.getRenameInfo(target.fileName, offset, { + allowRenameOfImportPath: true, + }); + return info.canRename + ? rangeFromSpan(target.document, info.triggerSpan) + : null; +} + +export function rename( + target: ServiceTarget, + offset: number, + newName: string, +): WorkspaceEdit | null { + const locations = target.service.findRenameLocations( + target.fileName, + offset, + false, + false, + { providePrefixAndSuffixTextForRename: false }, + ); + if (!locations) return null; + const changes: Record = {}; + for (const location of locations) { + const found = locate(target, location.fileName, location.textSpan); + if (!found) continue; + (changes[found.uri] ??= []).push({ range: found.range, newText: newName }); + } + return { changes }; +} + +export function documentHighlights( + target: ServiceTarget, + offset: number, +): DocumentHighlight[] { + const { service, document, fileName } = target; + const result: DocumentHighlight[] = []; + for (const item of service.getDocumentHighlights(fileName, offset, [ + fileName, + ]) ?? []) { + for (const highlight of item.highlightSpans) { + result.push({ + range: rangeFromSpan(document, highlight.textSpan), + kind: + highlight.kind === "writtenReference" + ? DocumentHighlightKind.Write + : DocumentHighlightKind.Text, + }); + } + } + return result; +} + +export function codeActions( + target: ServiceTarget, + range: Range, + context: CodeActionContext, + options?: FormattingOptions, +): CodeAction[] { + const { service, document, fileName } = target; + const fixes = service.getCodeFixesAtPosition( + fileName, + document.offsetAt(range.start), + document.offsetAt(range.end), + context.diagnostics + .map((diagnostic) => Number(diagnostic.code)) + .filter(Number.isFinite), + formatSettings(options), + {}, + ); + return fixes.map((fix) => { + const changes = textChanges(target, fix.changes); + return { + title: fix.description, + kind: "quickfix", + edit: Object.keys(changes).length ? { changes } : undefined, + }; + }); +} + +export function textChanges( + target: ServiceTarget, + fileChanges: readonly ts.FileTextChanges[], +): Record { + const changes: Record = {}; + for (const change of fileChanges) { + const uri = target.uriOf(change.fileName); + const document = target.documentOf(change.fileName); + if (!uri || !document) continue; + changes[uri] = change.textChanges.map((textChange) => ({ + range: rangeFromSpan(document, textChange.span), + newText: textChange.newText, + })); + } + return changes; +} + +function locations( + target: ServiceTarget, + spans: readonly { fileName: string; textSpan: ts.TextSpan }[] | undefined, +): Location[] { + const result: Location[] = []; + for (const span of spans ?? []) { + const location = locate(target, span.fileName, span.textSpan); + if (location) result.push(location); + } + return result; +} + +function locate( + target: ServiceTarget, + fileName: string, + span: ts.TextSpan, +): Location | undefined { + const uri = target.uriOf(fileName); + const document = uri && target.documentOf(fileName); + if (!uri || !document) return undefined; + return { uri, range: rangeFromSpan(document, span) }; +} diff --git a/src/cm/lsp/workers/typescript/paths.ts b/src/cm/lsp/workers/typescript/paths.ts new file mode 100644 index 0000000000..4224e3bd22 --- /dev/null +++ b/src/cm/lsp/workers/typescript/paths.ts @@ -0,0 +1,16 @@ +export function joinPath(directory: string, name: string): string { + return directory === "/" ? `/${name}` : `${directory}/${name}`; +} + +export function parentOf(path: string): string { + const index = path.lastIndexOf("/"); + return index <= 0 ? "/" : path.slice(0, index); +} + +export function baseName(path: string): string { + return path.slice(path.lastIndexOf("/") + 1); +} + +export function trimSlash(value: string): string { + return value.length > 1 && value.endsWith("/") ? value.slice(0, -1) : value; +} diff --git a/src/cm/lsp/workers/typescript/project.ts b/src/cm/lsp/workers/typescript/project.ts new file mode 100644 index 0000000000..c6c66f5d5c --- /dev/null +++ b/src/cm/lsp/workers/typescript/project.ts @@ -0,0 +1,220 @@ +import ts from "typescript"; +import { TextDocument } from "vscode-languageserver-textdocument"; +import crawl, { type CrawlOptions, listedSourceFiles } from "./crawl"; +import type ProjectFileSystem from "./fileSystem"; +import { joinPath } from "./paths"; +import ProjectHost from "./projectHost"; +import { compilerDefaults, readDirectory, SOURCE_FILE } from "./scripts"; + +interface ProjectOptions { + fs: ProjectFileSystem; + root: string; + documents: Map; + documentsVersion(): string; + libraries: Record; + registry: ts.DocumentRegistry; + log(message: string): void; +} + +const CONFIG_FILES = ["tsconfig.json", "jsconfig.json"]; +const DEPENDENCY_DIRECTORIES = new Set([ + "node_modules", + "bower_components", + "jspm_packages", +]); +const OUTPUT_DIRECTORIES = new Set(["build", "coverage", "dist", "out"]); +const MAX_DIRECTORIES = 1500; +const MAX_FILES = 3000; +const JAVASCRIPT_FILE = /\.[cm]?jsx?$/i; +const JSCONFIG_DEFAULTS: ts.CompilerOptions = { + allowJs: true, + maxNodeModuleJsDepth: 2, + allowSyntheticDefaultImports: true, + skipLibCheck: true, +}; + +export default class Project { + readonly root: string; + readonly service: ts.LanguageService; + #options: ProjectOptions; + #host: ProjectHost; + #configPath: string | undefined; + #loaded = false; + #openDocuments = new Map(); + #openDocumentsKey = ""; + #snapshots = new Map(); + #configErrors = ""; + + constructor(options: ProjectOptions) { + this.#options = options; + this.root = options.root; + this.#host = new ProjectHost({ + fs: options.fs, + root: options.root, + libraries: options.libraries, + documentsVersion: options.documentsVersion, + openDocuments: () => this.#documentsByPath(), + }); + // Inferred defaults until the config is read, so open files work at once. + this.#host.configure(compilerDefaults(), []); + this.service = ts.createLanguageService(this.#host, options.registry); + } + + get loaded(): boolean { + return this.#loaded; + } + + /** Inferred projects keep JavaScript to syntax checks, as before. */ + get checksJavaScript(): boolean { + return ( + !!this.#configPath && this.#host.getCompilationSettings().checkJs === true + ); + } + + /** Resolves false when the root cannot be listed, e.g. a single file. */ + async load(onProgress: (message: string) => void): Promise { + const { fs } = this.#options; + const children = await fs.list(this.root); + if (!children) return false; + onProgress("Reading configuration"); + const configName = CONFIG_FILES.find( + (name) => children.has(name) && !children.get(name)!.isDirectory, + ); + if (configName) { + this.#configPath = joinPath(this.root, configName); + await fs.read(this.#configPath); + } + this.refresh(); + await crawl(fs, this.root, { + ...this.#scanOptions(), + onProgress: (directories, files) => + onProgress(`Scanned ${directories} folders, ${files} source files`), + }); + this.#loaded = true; + this.refresh(); + return true; + } + + refresh(): void { + if (!this.#configPath) { + const { fs } = this.#options; + const files = listedSourceFiles(fs, this.root, this.#scanOptions()); + this.#host.configure(compilerDefaults(), files); + return; + } + const parsed = this.#parseConfig(this.#configPath); + this.#host.configure( + { ...parsed.options, noEmit: true }, + parsed.fileNames.slice(0, MAX_FILES), + ); + if (this.#loaded) this.#reportConfigErrors(parsed.errors); + } + + pathOf(uri: string): string | undefined { + const path = this.#options.fs.pathOf(uri); + return path?.startsWith(`${this.root}/`) ? path : undefined; + } + + /** + * A program without JavaScript support cannot hold JavaScript, as in + * tsserver. `checkJs` implies `allowJs` unless that is set explicitly. + */ + accepts(fileName: string): boolean { + const { allowJs, checkJs } = this.#host.getCompilationSettings(); + return !JAVASCRIPT_FILE.test(fileName) || (allowJs ?? checkJs === true); + } + + uriOf(fileName: string): string | undefined { + for (const [uri, document] of this.#options.documents) { + if (this.pathOf(uri) === fileName) return document.uri; + } + return this.#options.fs.urlOf(fileName); + } + + /** Text of a project file, for converting offsets in results to positions. */ + documentOf(fileName: string): TextDocument | undefined { + const open = this.#documentsByPath().get(fileName); + if (open) return open; + const uri = this.uriOf(fileName); + const text = uri && this.#host.readFile(fileName); + if (!uri || text === undefined) return undefined; + const version = this.#options.fs.fileVersion(fileName); + const cached = this.#snapshots.get(fileName); + if (cached?.version === version) return cached.document; + const document = TextDocument.create(uri, "typescript", version, text); + this.#snapshots.set(fileName, { version, document }); + return document; + } + + dispose(): void { + this.service.dispose(); + } + + #parseConfig(configPath: string): ts.ParsedCommandLine { + const { fs } = this.#options; + const text = fs.readFile(configPath) ?? "{}"; + const { config } = ts.parseConfigFileTextToJson(configPath, text); + const host: ts.ParseConfigHost = { + useCaseSensitiveFileNames: true, + fileExists: (path) => fs.fileExists(path), + readFile: (path) => fs.readFile(path), + // Only what the budgeted crawl listed, so include globs cannot + // enumerate past the directory cap. + readDirectory: (path, extensions, excludes, includes, depth) => + readDirectory( + (directory) => fs.listedEntries(directory), + this.root, + path, + extensions, + excludes, + includes, + depth, + ), + }; + const defaults = configPath.endsWith("jsconfig.json") + ? JSCONFIG_DEFAULTS + : {}; + return ts.parseJsonConfigFileContent( + config ?? {}, + host, + this.root, + defaults, + configPath, + ); + } + + #scanOptions(): CrawlOptions { + const configured = !!this.#configPath; + return { + skipDirectory: (name) => + name.startsWith(".") || + DEPENDENCY_DIRECTORIES.has(name) || + (!configured && OUTPUT_DIRECTORIES.has(name)), + includeFile: (name) => + SOURCE_FILE.test(name) && !name.endsWith(".min.js"), + maxDirectories: MAX_DIRECTORIES, + maxFiles: MAX_FILES, + }; + } + + #reportConfigErrors(errors: readonly ts.Diagnostic[]): void { + const message = errors + .map((error) => ts.flattenDiagnosticMessageText(error.messageText, "\n")) + .join("\n"); + if (message === this.#configErrors) return; + this.#configErrors = message; + if (message) this.#options.log(`${this.#configPath}: ${message}`); + } + + #documentsByPath(): Map { + const key = `${this.#options.documentsVersion()}:${this.#options.fs.version}`; + if (key === this.#openDocumentsKey) return this.#openDocuments; + this.#openDocumentsKey = key; + this.#openDocuments = new Map(); + for (const [uri, document] of this.#options.documents) { + const path = this.pathOf(uri); + if (path && this.accepts(path)) this.#openDocuments.set(path, document); + } + return this.#openDocuments; + } +} diff --git a/src/cm/lsp/workers/typescript/projectHost.ts b/src/cm/lsp/workers/typescript/projectHost.ts new file mode 100644 index 0000000000..2ba8e3dc97 --- /dev/null +++ b/src/cm/lsp/workers/typescript/projectHost.ts @@ -0,0 +1,143 @@ +import ts from "typescript"; +import type { TextDocument } from "vscode-languageserver-textdocument"; +import type ProjectFileSystem from "./fileSystem"; +import { LIB_DIRECTORY, readDirectory, scriptKind } from "./scripts"; + +interface ProjectHostOptions { + fs: ProjectFileSystem; + root: string; + libraries: Record; + openDocuments(): Map; + documentsVersion(): string; +} + +export default class ProjectHost implements ts.LanguageServiceHost { + #options: ProjectHostOptions; + #compilerOptions: ts.CompilerOptions = {}; + #rootFiles: string[] = []; + #configurationKey = ""; + #configurationVersion = 0; + #seenFileSystemVersion = -1; + #resolutionsInvalidated = false; + + constructor(options: ProjectHostOptions) { + this.#options = options; + } + + configure(compilerOptions: ts.CompilerOptions, rootFiles: string[]): void { + const key = JSON.stringify([compilerOptions, rootFiles]); + if (key === this.#configurationKey) return; + this.#configurationKey = key; + this.#compilerOptions = compilerOptions; + this.#rootFiles = rootFiles; + this.#configurationVersion++; + } + + getProjectVersion(): string { + // Called once per program synchronization: newly fetched files can turn + // earlier failed module lookups into hits, so resolve everything again. + const { fs, documentsVersion } = this.#options; + this.#resolutionsInvalidated = fs.version !== this.#seenFileSystemVersion; + this.#seenFileSystemVersion = fs.version; + return `${fs.version}:${documentsVersion()}:${this.#configurationVersion}`; + } + + // TypeScript calls this detached from the host, so it must not rely on + // method binding. + hasInvalidatedResolutions = (): boolean => this.#resolutionsInvalidated; + + getCompilationSettings(): ts.CompilerOptions { + return this.#compilerOptions; + } + + getCurrentDirectory(): string { + return this.#options.root; + } + + getDefaultLibFileName(options: ts.CompilerOptions): string { + return `${LIB_DIRECTORY}/${ts.getDefaultLibFileName(options)}`; + } + + getScriptFileNames(): string[] { + const names = new Set(this.#rootFiles); + for (const path of this.#options.openDocuments().keys()) names.add(path); + return [...names]; + } + + getScriptVersion(fileName: string): string { + const document = this.#options.openDocuments().get(fileName); + if (document) return `d${document.version}`; + return `f${this.#options.fs.fileVersion(fileName)}`; + } + + getScriptSnapshot(fileName: string): ts.IScriptSnapshot | undefined { + const text = this.readFile(fileName); + return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text); + } + + getScriptKind(fileName: string): ts.ScriptKind { + const document = this.#options.openDocuments().get(fileName); + return scriptKind(fileName, document?.languageId); + } + + readFile(fileName: string): string | undefined { + const document = this.#options.openDocuments().get(fileName); + if (document) return document.getText(); + return this.#library(fileName) ?? this.#options.fs.readFile(fileName); + } + + fileExists(fileName: string): boolean { + return ( + this.#options.openDocuments().has(fileName) || + this.#library(fileName) !== undefined || + this.#options.fs.fileExists(fileName) + ); + } + + directoryExists(directoryName: string): boolean { + return ( + directoryName === LIB_DIRECTORY || + this.#options.fs.directoryExists(directoryName) + ); + } + + getDirectories(directoryName: string): string[] { + return this.#options.fs.getEntries(directoryName).directories; + } + + readDirectory( + path: string, + extensions?: readonly string[], + exclude?: readonly string[], + include?: readonly string[], + depth?: number, + ): string[] { + const { fs, root } = this.#options; + return readDirectory( + (directory) => fs.getEntries(directory), + root, + path, + extensions, + exclude, + include, + depth, + ); + } + + realpath(path: string): string { + return path; + } + + useCaseSensitiveFileNames(): boolean { + return true; + } + + getNewLine(): string { + return "\n"; + } + + #library(fileName: string): string | undefined { + if (!fileName.startsWith(`${LIB_DIRECTORY}/`)) return undefined; + return this.#options.libraries[fileName.slice(LIB_DIRECTORY.length + 1)]; + } +} diff --git a/src/cm/lsp/workers/typescript/scripts.ts b/src/cm/lsp/workers/typescript/scripts.ts new file mode 100644 index 0000000000..579c77ef2c --- /dev/null +++ b/src/cm/lsp/workers/typescript/scripts.ts @@ -0,0 +1,99 @@ +import ts from "typescript"; + +interface FileSystemEntries { + files: readonly string[]; + directories: readonly string[]; +} + +type MatchFiles = ( + path: string, + extensions: readonly string[] | undefined, + excludes: readonly string[] | undefined, + includes: readonly string[] | undefined, + useCaseSensitiveFileNames: boolean, + currentDirectory: string, + depth: number | undefined, + getFileSystemEntries: (path: string) => FileSystemEntries, + realpath: (path: string) => string, +) => string[]; + +export const LIB_DIRECTORY = "/__lib__"; +export const SOURCE_FILE = /\.[cm]?[jt]sx?$/i; + +// Internal but long-stable; it is what tsserver uses to apply tsconfig +// include/exclude globs to a file system. +const matchFiles = (ts as unknown as { matchFiles?: MatchFiles }).matchFiles; + +export function compilerDefaults(): ts.CompilerOptions { + return { + allowJs: true, + checkJs: true, + allowImportingTsExtensions: true, + noEmit: true, + isolatedModules: true, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + moduleDetection: ts.ModuleDetectionKind.Force, + skipLibCheck: true, + target: ts.ScriptTarget.ES2022, + jsx: ts.JsxEmit.ReactJSX, + useDefineForClassFields: true, + allowNonTsExtensions: true, + } as ts.CompilerOptions; +} + +export function readDirectory( + getEntries: (path: string) => FileSystemEntries, + currentDirectory: string, + path: string, + extensions?: readonly string[], + excludes?: readonly string[], + includes?: readonly string[], + depth?: number, +): string[] { + if (!matchFiles) return []; + return matchFiles( + path, + extensions, + excludes, + includes, + true, + currentDirectory, + depth, + getEntries, + (file) => file, + ); +} + +export function scriptKind( + fileName: string, + languageId?: string, +): ts.ScriptKind { + if (languageId === "typescriptreact" || languageId === "tsx") { + return ts.ScriptKind.TSX; + } + if (languageId === "javascriptreact" || languageId === "jsx") { + return ts.ScriptKind.JSX; + } + if (languageId === "typescript") return ts.ScriptKind.TS; + if (languageId === "javascript") return ts.ScriptKind.JS; + const path = uriPath(fileName).toLowerCase(); + if (path.endsWith(".tsx")) return ts.ScriptKind.TSX; + if (path.endsWith(".jsx")) return ts.ScriptKind.JSX; + if (/\.[cm]?ts$/.test(path)) return ts.ScriptKind.TS; + if (/\.[cm]?js$/.test(path)) return ts.ScriptKind.JS; + if (path.endsWith(".json")) return ts.ScriptKind.JSON; + return ts.ScriptKind.Unknown; +} + +export function isTypeScriptLanguage(languageId: string): boolean { + return languageId.startsWith("typescript") || languageId === "tsx"; +} + +function uriPath(uri: string): string { + try { + return new URL(uri).pathname; + } catch { + return uri; + } +} diff --git a/src/cm/lsp/workers/typescript/taskQueue.ts b/src/cm/lsp/workers/typescript/taskQueue.ts new file mode 100644 index 0000000000..6820814712 --- /dev/null +++ b/src/cm/lsp/workers/typescript/taskQueue.ts @@ -0,0 +1,32 @@ +/** Runs host requests with bounded concurrency so a scan cannot flood the bridge. */ +export default class TaskQueue { + #concurrency: number; + #queue: Array<() => Promise> = []; + #active = 0; + + constructor(concurrency: number) { + this.#concurrency = concurrency; + } + + get busy(): boolean { + return this.#active > 0 || this.#queue.length > 0; + } + + run(task: () => Promise): Promise { + return new Promise((resolve, reject) => { + this.#queue.push(() => task().then(resolve, reject)); + this.#drain(); + }); + } + + #drain(): void { + while (this.#active < this.#concurrency && this.#queue.length) { + const job = this.#queue.shift()!; + this.#active++; + void job().finally(() => { + this.#active--; + this.#drain(); + }); + } + } +} diff --git a/src/cm/lsp/workers/typescript/workspace.ts b/src/cm/lsp/workers/typescript/workspace.ts new file mode 100644 index 0000000000..0effbb0f59 --- /dev/null +++ b/src/cm/lsp/workers/typescript/workspace.ts @@ -0,0 +1,207 @@ +import ts from "typescript"; +import type { TextDocument } from "vscode-languageserver-textdocument"; +import type { WorkDoneProgress } from "../progress"; +import DocumentHost from "./documentHost"; +import ProjectFileSystem, { type FileSystemHost } from "./fileSystem"; +import { trimSlash } from "./paths"; +import Project from "./project"; + +/** Everything a language feature needs to query TypeScript for one document. */ +export interface ServiceTarget { + service: ts.LanguageService; + document: TextDocument; + fileName: string; + checkJs: boolean; + uriOf(fileName: string): string | undefined; + documentOf(fileName: string): TextDocument | undefined; +} + +// Crawling a remote tree would flood the connection; those files stay in +// single-file mode. +const REMOTE_FOLDER = /^s?ftps?:/i; + +interface WorkspaceOptions { + documents: Map; + documentsVersion(): string; + libraries: Record; + host: FileSystemHost; + onChange(): void; + log(message: string): void; + progress(title: string, message?: string): WorkDoneProgress; +} + +export default class TypeScriptWorkspace { + #options: WorkspaceOptions; + #fs: ProjectFileSystem; + #projects = new Map(); + #registry = ts.createDocumentRegistry(true, "/"); + #fallback: ts.LanguageService; + #nextRoot = 0; + + constructor(options: WorkspaceOptions) { + this.#options = options; + this.#fs = new ProjectFileSystem(options.host, () => this.#changed()); + const host = new DocumentHost( + options.documents, + options.libraries, + (uri) => !!this.#claim(uri), + () => `${options.documentsVersion()}:${this.#fs.version}`, + ); + this.#fallback = ts.createLanguageService(host, this.#registry); + } + + addFolder(url: string): void { + const key = trimSlash(url); + if (!key || REMOTE_FOLDER.test(key) || this.#projects.has(key)) return; + const root = filePath(key) ?? `/ws${this.#nextRoot++}`; + this.#fs.addRoot(root, key); + const project = new Project({ + fs: this.#fs, + root, + documents: this.#options.documents, + documentsVersion: this.#options.documentsVersion, + libraries: this.#options.libraries, + registry: this.#registry, + log: this.#options.log, + }); + this.#projects.set(key, project); + // Started lazily so a single file passed as the root never flashes one. + let progress: WorkDoneProgress | undefined; + const report = (message: string) => { + if (progress) progress.report(message); + else + progress = this.#options.progress( + `Loading ${folderName(key)}`, + message, + ); + }; + project.load(report).then( + (loaded) => { + progress?.end(); + if (!loaded) { + this.removeFolder(key); + return; + } + this.#options.log(`Project-wide analysis enabled for ${key}`); + this.#options.onChange(); + }, + (error) => { + progress?.end(); + this.#options.log(`Project load failed for ${key}: ${error}`); + this.removeFolder(key); + }, + ); + } + + removeFolder(url: string): void { + const key = trimSlash(url); + const project = this.#projects.get(key); + if (!project) return; + this.#projects.delete(key); + this.#fs.removeRoot(project.root); + project.dispose(); + this.#options.onChange(); + } + + target(document: TextDocument): ServiceTarget { + const claim = this.#claim(document.uri); + if (claim) { + const { project, fileName } = claim; + return { + service: project.service, + document, + fileName, + checkJs: project.checksJavaScript, + uriOf: (name) => project.uriOf(name), + documentOf: (name) => project.documentOf(name), + }; + } + const { documents } = this.#options; + return { + service: this.#fallback, + document, + fileName: document.uri, + checkJs: false, + uriOf: (name) => (documents.has(name) ? name : undefined), + documentOf: (name) => documents.get(name), + }; + } + + /** New files are absent from cached listings until their folder is re-listed. */ + documentOpened(uri: string): void { + let owner: [string, Project] | undefined; + for (const entry of this.#projects) { + if ( + uri.startsWith(entry[0]) && + entry[0].length > (owner?.[0].length ?? 0) + ) + owner = entry; + } + if (owner) void this.#fs.locate(uri, owner[1].root); + } + + /** A closed tab may hold unsaved text; reread the file from disk next time. */ + documentClosed(uri: string): void { + const path = this.#fs.pathOf(uri); + if (path) this.#fs.invalidate(path); + // Releasing the semantic cache forces open tabs to be re-analysed, so + // only do it once the single-file service has nothing left to serve. + if (this.#options.documents.size === 0) + this.#fallback.cleanupSemanticCache(); + } + + dispose(): void { + for (const project of this.#projects.values()) project.dispose(); + this.#projects.clear(); + this.#fallback.dispose(); + } + + /** The deepest owning folder wins, whatever order folders were added in. */ + #claim(uri: string): { project: Project; fileName: string } | undefined { + let owner: { project: Project; fileName: string } | undefined; + for (const project of this.#projects.values()) { + const fileName = project.pathOf(uri); + if (!fileName) continue; + if (!owner || project.root.length > owner.project.root.length) { + owner = { project, fileName }; + } + } + return owner?.project.accepts(owner.fileName) ? owner : undefined; + } + + #changed(): void { + // Keep rebuilding until fetches stop arriving; each completion + // schedules another change notification. + if (this.#fs.busy) return; + for (const project of this.#projects.values()) { + if (project.loaded) project.refresh(); + } + this.#options.onChange(); + } +} + +/** + * `file:` URLs from listings are already decoded, so their names are kept + * as-is; other providers encode theirs, e.g. a `tree/primary%3AProjects%2Fapp` + * storage URI names the folder `app`. + */ +function folderName(url: string): string { + const name = url.slice(url.lastIndexOf("/") + 1); + if (url.startsWith("file:")) return name || url; + let decoded = name; + try { + decoded = decodeURIComponent(name); + } catch { + // Not percent-encoded after all; show it as listed. + } + return decoded.split(/[/:]/).filter(Boolean).pop() || url; +} + +/** + * `file:` folders keep their real path, so references above the folder, such + * as `extends: "../tsconfig.base.json"`, resolve. Other providers' URIs are + * opaque and get an isolated root. + */ +function filePath(url: string): string | undefined { + return url.startsWith("file:///") ? url.slice("file://".length) : undefined; +} diff --git a/src/cm/mainEditorExtensions.ts b/src/cm/mainEditorExtensions.ts index f825898d4a..e2e7add31e 100644 --- a/src/cm/mainEditorExtensions.ts +++ b/src/cm/mainEditorExtensions.ts @@ -27,6 +27,7 @@ export const fixedHeightTheme = EditorView.theme({ ".cm-scroller": { height: "100%", overflow: "auto", + scrollbarWidth: "none", willChange: "transform", contentVisibility: "auto", }, diff --git a/src/cm/quickToolsNavigation.ts b/src/cm/quickToolsNavigation.ts index 85c8ff2e2c..968d2a6e52 100644 --- a/src/cm/quickToolsNavigation.ts +++ b/src/cm/quickToolsNavigation.ts @@ -123,7 +123,11 @@ export function createQuickToolKeyEvent( keyCode: number, modifiers: QuickToolKeyModifiers = {}, ): KeyboardEvent { - const key = keyNames[keyCode] || String.fromCharCode(keyCode); + const key = + keyNames[keyCode] || + (keyCode >= 112 && keyCode <= 135 + ? `F${keyCode - 111}` + : String.fromCharCode(keyCode)); return createKeyboardEvent("keydown", { type: "keydown", key, diff --git a/src/cm/themes/index.js b/src/cm/themes/index.js index 71c95dc1eb..52c055cc1f 100644 --- a/src/cm/themes/index.js +++ b/src/cm/themes/index.js @@ -141,6 +141,19 @@ function resolveThemeEntryExtensions(theme, fallbackExtensions) { } export function addTheme(id, caption, isDark, getExtension, config = null) { + return registerTheme(id, caption, isDark, getExtension, config, true); +} + +/** + * Registers a bundled theme. These are known to be valid, so the up-front + * validation (which builds every theme's extensions at startup) is skipped; + * they are still validated when applied. + */ +function addBuiltInTheme(id, caption, isDark, getExtension, config = null) { + return registerTheme(id, caption, isDark, getExtension, config, false); +} + +function registerTheme(id, caption, isDark, getExtension, config, validate) { const key = String(id || "") .trim() .toLowerCase(); @@ -154,7 +167,7 @@ export function addTheme(id, caption, isDark, getExtension, config = null) { config: config || null, }; - if (!validateThemeExtensions(key, theme.getExtension())) { + if (validate && !validateThemeExtensions(key, theme.getExtension())) { return false; } @@ -189,115 +202,133 @@ export function removeTheme(id) { themes.delete(String(id).toLowerCase()); } -addTheme("one_dark", "One Dark", true, () => oneDarkExtensions, oneDarkConfig); -addTheme(auraConfig.name, "Aura", !!auraConfig.dark, () => aura(), auraConfig); -addTheme( +addBuiltInTheme( + "one_dark", + "One Dark", + true, + () => oneDarkExtensions, + oneDarkConfig, +); +addBuiltInTheme( + auraConfig.name, + "Aura", + !!auraConfig.dark, + () => aura(), + auraConfig, +); +addBuiltInTheme( cobaltConfig.name, "Cobalt", !!cobaltConfig.dark, () => cobalt(), cobaltConfig, ); -addTheme( +addBuiltInTheme( noctisLilacConfig.name, noctisLilacConfig.caption || "Noctis Lilac", !!noctisLilacConfig.dark, () => noctisLilac(), noctisLilacConfig, ); -addTheme( +addBuiltInTheme( draculaConfig.name, "Dracula", !!draculaConfig.dark, () => dracula(), draculaConfig, ); -addTheme(nordConfig.name, "Nord", !!nordConfig.dark, () => nord(), nordConfig); -addTheme( +addBuiltInTheme( + nordConfig.name, + "Nord", + !!nordConfig.dark, + () => nord(), + nordConfig, +); +addBuiltInTheme( gruvboxDarkConfig.name, "Gruvbox Dark", !!gruvboxDarkConfig.dark, () => gruvboxDark(), gruvboxDarkConfig, ); -addTheme( +addBuiltInTheme( ayuDarkConfig.name, "Ayu Dark", !!ayuDarkConfig.dark, () => ayuDark(), ayuDarkConfig, ); -addTheme( +addBuiltInTheme( materialPalenightConfig.name, "Material Palenight", !!materialPalenightConfig.dark, () => materialPalenight(), materialPalenightConfig, ); -addTheme( +addBuiltInTheme( githubDarkConfig.name, "GitHub Dark", !!githubDarkConfig.dark, () => githubDark(), githubDarkConfig, ); -addTheme( +addBuiltInTheme( githubLightConfig.name, "GitHub Light", !!githubLightConfig.dark, () => githubLight(), githubLightConfig, ); -addTheme( +addBuiltInTheme( solarizedDarkConfig.name, "Solarized Dark", !!solarizedDarkConfig.dark, () => solarizedDark(), solarizedDarkConfig, ); -addTheme( +addBuiltInTheme( solarizedLightConfig.name, "Solarized Light", !!solarizedLightConfig.dark, () => solarizedLight(), solarizedLightConfig, ); -addTheme( +addBuiltInTheme( tokyoNightDayConfig.name, "Tokyo Night Day", !!tokyoNightDayConfig.dark, () => tokyoNightDay(), tokyoNightDayConfig, ); -addTheme( +addBuiltInTheme( tokyoNightConfig.name, "Tokyo Night", !!tokyoNightConfig.dark, () => tokyoNight(), tokyoNightConfig, ); -addTheme( +addBuiltInTheme( tomorrowNightConfig.name, "Tomorrow Night", !!tomorrowNightConfig.dark, () => tomorrowNight(), tomorrowNightConfig, ); -addTheme( +addBuiltInTheme( tomorrowNightBrightConfig.name, "Tomorrow Night Bright", !!tomorrowNightBrightConfig.dark, () => tomorrowNightBright(), tomorrowNightBrightConfig, ); -addTheme( +addBuiltInTheme( monokaiConfig.name, "Monokai", !!monokaiConfig.dark, () => monokai(), monokaiConfig, ); -addTheme( +addBuiltInTheme( vscodeDarkConfig.name, "VS Code Dark", !!vscodeDarkConfig.dark, @@ -306,7 +337,7 @@ addTheme( ); for (const config of catppuccinConfigs) { - addTheme( + addBuiltInTheme( config.name, config.caption, config.dark, diff --git a/src/cm/touchSelectionMenu.js b/src/cm/touchSelectionMenu.js index 7f45f0afa2..c31c20995f 100644 --- a/src/cm/touchSelectionMenu.js +++ b/src/cm/touchSelectionMenu.js @@ -1,4 +1,3 @@ -import { LSPPlugin } from "@codemirror/lsp-client"; import { EditorSelection } from "@codemirror/state"; import { focusEditorIfEditable, @@ -6,6 +5,7 @@ import { resolveReadOnlyContextSelection, shouldCommitReadOnlyTap, } from "cm/editorReadOnly"; +import { getAllLspPlugins } from "cm/lsp/clientLoader"; import { bindSelectionMenuButton, filterSelectionMenuItems, @@ -135,7 +135,7 @@ function clamp(value, min, max) { } function hasCodeActionProvider(view) { - return LSPPlugin.getAll(view, "codeAction").some( + return getAllLspPlugins(view, "codeAction").some( (plugin) => !!plugin.client.serverCapabilities?.codeActionProvider, ); } @@ -150,7 +150,7 @@ function hasLspActions(view) { ]; if ( capabilities.some(([feature, capability]) => - LSPPlugin.getAll(view, feature).some( + getAllLspPlugins(view, feature).some( (plugin) => !!plugin.client.serverCapabilities?.[capability], ), ) @@ -159,7 +159,7 @@ function hasLspActions(view) { } return ( !view.state.readOnly && - LSPPlugin.getAll(view, "rename").some( + getAllLspPlugins(view, "rename").some( (plugin) => !!plugin.client.serverCapabilities?.renameProvider, ) ); diff --git a/src/components/lspInfoDialog/index.js b/src/components/lspInfoDialog/index.js index c6e0afeb4f..12549a0347 100644 --- a/src/components/lspInfoDialog/index.js +++ b/src/components/lspInfoDialog/index.js @@ -1,5 +1,5 @@ import "./styles.scss"; -import lspClientManager from "cm/lsp/clientManager"; +import { getLoadedLspClient } from "cm/lsp/clientLoader"; import { getCurrentFileLanguage, getServersForCurrentFile, @@ -10,12 +10,13 @@ import { getServerStats } from "cm/lsp/serverLauncher"; import toast from "components/toast"; import actionStack from "lib/actionStack"; import restoreTheme from "lib/restoreTheme"; +import helpers from "utils/helpers"; let dialogInstance = null; function getActiveClients() { try { - return lspClientManager.getActiveClients(); + return getLoadedLspClient()?.clientManager.getActiveClients() ?? []; } catch { return []; } @@ -73,8 +74,8 @@ function copyLogsToClipboard(serverId, serverLabel) { navigator.clipboard.writeText(header + text).catch(() => { toast("Failed to copy"); }); - } else if (cordova?.plugins?.clipboard) { - cordova.plugins.clipboard.copy(header + text); + } else if (Bridge?.clipboard) { + Bridge.clipboard.copy(header + text); } else { toast("Clipboard not available"); } @@ -145,7 +146,7 @@ async function restartAllServers() { toast(`Restarting ${count} LSP server${count > 1 ? "s" : ""}...`); try { - await lspClientManager.dispose(); + await getLoadedLspClient()?.clientManager.dispose(); window.editorManager?.restartLsp?.(); toast("All servers restarted"); } catch (err) { @@ -163,7 +164,7 @@ async function stopAllServers() { const count = activeClients.length; try { - await lspClientManager.dispose(); + await getLoadedLspClient()?.clientManager.dispose(); toast(`Stopped ${count} LSP server${count > 1 ? "s" : ""}`); } catch (err) { toast("Failed to stop servers"); @@ -395,7 +396,9 @@ function showLspInfoDialog() {
Project
- {clientState?.rootUri || "(workspace folders mode)"} + {clientState?.rootUri + ? helpers.getVirtualPath(clientState.rootUri) + : "(workspace folders mode)"}
)} diff --git a/src/components/searchbar/index.js b/src/components/searchbar/index.js index 5de43125c0..aa92ae5100 100644 --- a/src/components/searchbar/index.js +++ b/src/components/searchbar/index.js @@ -20,6 +20,7 @@ function searchBar( ) { let hideOnBlur = true; let timeout = null; + let closed = false; const $searchInput = Ref(); /**@type {HTMLDivElement} */ const $container = ( @@ -30,7 +31,12 @@ function searchBar( placeholder={strings.search} enterKeyHint="go" /> - +